diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000000..788149656b8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,185 @@ + +# EditorConfig is awesome:http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Don't use tabs for indentation. +[*] +indent_style = space +# (Please don't specify an indent_size here; that has too many unintended consequences.) + +[*.yml] +indent_style = space +indent_size = 2 + +# Code files +[*.{cs,csx,vb,vbx}] +indent_size = 4 +insert_final_newline = true +charset = utf-8-bom + +# Xml project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# Xml config files +[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] +indent_size = 2 + +# JSON files +[*.json] +indent_size = 2 + +[*.{sh}] +end_of_line = lf +indent_size = 2 + +# Dotnet code style settings: +[*.{cs,vb}] +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion + +# Use language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# Suggest more modern language features when available +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion + +# Non-private static fields are PascalCase +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected internal, private protected +dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + +dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + +# Constants are PascalCase +dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants +dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + +dotnet_naming_symbols.constants.applicable_kinds = field, local +dotnet_naming_symbols.constants.required_modifiers = const + +dotnet_naming_style.constant_style.capitalization = pascal_case + +# Static fields are camelCase and start with s_ +dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static + +dotnet_naming_style.static_field_style.capitalization = camel_case +dotnet_naming_style.static_field_style.required_prefix = s_ + +# Instance fields are camelCase and start with _ +dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields +dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style + +dotnet_naming_symbols.instance_fields.applicable_kinds = field + +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Locals and parameters are camelCase +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + +dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + +dotnet_naming_style.camel_case_style.capitalization = camel_case + +# Local functions are PascalCase +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function + +dotnet_naming_style.local_function_style.capitalization = pascal_case + +# By default, name items with PascalCase +dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members +dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style + +dotnet_naming_symbols.all_members.applicable_kinds = * + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +# CSharp code style settings: +[*.cs] +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + +# Prefer method-like constructs to have a block body +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_operators = false:none + +# Prefer property-like constructs to have an expression-body +csharp_style_expression_bodied_properties = true:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_accessors = true:none + +# Suggest more modern language features when available +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion + +# Newline settings +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Spacing +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_around_binary_operators = before_and_after +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false + +# Blocks are allowed +csharp_prefer_braces = true:silent +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index 0f149df1b1f..9753d57f710 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -41,8 +41,8 @@ Provide any additional context that may be helpful in understanding and/or resol Please add X in at least one of the boxes as appropriate. In order for an issue to be accepted, a developer needs to be able to reproduce the issue on a currently supported version. If you are looking for a workaround for an issue with an older version, please visit the forums at https://dnncommunity.org/forums --> * [ ] 10.00.00 alpha build -* [ ] 09.06.01 release candidate -* [ ] 09.06.00 latest supported release +* [ ] 09.06.02 release candidate +* [ ] 09.06.01 latest supported release ## Affected browser - - - {04F77171-0634-46E0-A95E-D7477C88712E} - 2 - Debug - AnyCPU - DotNetNuke.log4net - Library - v4.7.2 - - - - bin\ - true - TRACE;DEBUG;NET;NET_2_0;NET_4_0;NET_4_5 - false - 4 - full - prompt - AnyCPU - false - 7 - bin\DotNetNuke.log4net.xml - - - bin\ - false - TRACE;STRONG;NET;NET_2_0;NET_4_0;NET_4_5 - true - 4 - pdbonly - prompt - AnyCPU - false - 7 - bin\DotNetNuke.log4net.xml - - - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - - - - $(MSBuildProjectDirectory)\..\.. - - - - - - - - +--> + + + {04F77171-0634-46E0-A95E-D7477C88712E} + 2 + Debug + AnyCPU + DotNetNuke.log4net + Library + v4.7.2 + + + + bin\ + true + TRACE;DEBUG;NET;NET_2_0;NET_4_0;NET_4_5 + false + 4 + full + prompt + AnyCPU + false + 7 + bin\DotNetNuke.log4net.xml + + + bin\ + false + TRACE;STRONG;NET;NET_2_0;NET_4_0;NET_4_5 + true + 4 + pdbonly + prompt + AnyCPU + false + 7 + bin\DotNetNuke.log4net.xml + + + + + + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + $(MSBuildProjectDirectory)\..\.. + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs index f58d11f8e25..bd710e03838 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // SSCLI 1.0 has no support for ADO.NET #if !SSCLI @@ -29,1127 +27,1072 @@ using System.Configuration; using System.Data; using System.IO; - -using log4net.Util; -using log4net.Layout; + using log4net.Core; +using log4net.Layout; +using log4net.Util; namespace log4net.Appender { - /// - /// Appender that logs to a database. - /// - /// - /// - /// appends logging events to a table within a - /// database. The appender can be configured to specify the connection - /// string by setting the property. - /// The connection type (provider) can be specified by setting the - /// property. For more information on database connection strings for - /// your specific database see http://www.connectionstrings.com/. - /// - /// - /// Records are written into the database either using a prepared - /// statement or a stored procedure. The property - /// is set to (System.Data.CommandType.Text) to specify a prepared statement - /// or to (System.Data.CommandType.StoredProcedure) to specify a stored - /// procedure. - /// - /// - /// The prepared statement text or the name of the stored procedure - /// must be set in the property. - /// - /// - /// The prepared statement or stored procedure can take a number - /// of parameters. Parameters are added using the - /// method. This adds a single to the - /// ordered list of parameters. The - /// type may be subclassed if required to provide database specific - /// functionality. The specifies - /// the parameter name, database type, size, and how the value should - /// be generated using a . - /// - /// - /// - /// An example of a SQL Server table that could be logged to: - /// - /// CREATE TABLE [dbo].[Log] ( - /// [ID] [int] IDENTITY (1, 1) NOT NULL , - /// [Date] [datetime] NOT NULL , - /// [Thread] [varchar] (255) NOT NULL , - /// [Level] [varchar] (20) NOT NULL , - /// [Logger] [varchar] (255) NOT NULL , - /// [Message] [varchar] (4000) NOT NULL - /// ) ON [PRIMARY] - /// - /// - /// - /// An example configuration to log to the above table: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Julian Biddle - /// Nicko Cadell - /// Gert Driesen - /// Lance Nehring - public class AdoNetAppender : BufferingAppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// Public default constructor to initialize a new instance of this class. - /// - public AdoNetAppender() - { - ConnectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; - UseTransactions = true; - CommandType = System.Data.CommandType.Text; - m_parameters = new ArrayList(); - ReconnectOnError = false; - } - - #endregion // Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the database connection string that is used to connect to - /// the database. - /// - /// - /// The database connection string used to connect to the database. - /// - /// - /// - /// The connections string is specific to the connection type. - /// See for more information. - /// - /// - /// Connection string for MS Access via ODBC: - /// "DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb" - /// - /// Another connection string for MS Access via ODBC: - /// "Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\log4net-1.2\access.mdb;UID=;PWD=;" - /// - /// Connection string for MS Access via OLE DB: - /// "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;" - /// - public string ConnectionString - { - get { return m_connectionString; } - set { m_connectionString = value; } - } - - /// - /// The appSettings key from App.Config that contains the connection string. - /// - public string AppSettingsKey - { - get { return m_appSettingsKey; } - set { m_appSettingsKey = value; } - } + /// + /// Appender that logs to a database. + /// + /// + /// + /// appends logging events to a table within a + /// database. The appender can be configured to specify the connection + /// string by setting the property. + /// The connection type (provider) can be specified by setting the + /// property. For more information on database connection strings for + /// your specific database see http://www.connectionstrings.com/. + /// + /// + /// Records are written into the database either using a prepared + /// statement or a stored procedure. The property + /// is set to (System.Data.CommandType.Text) to specify a prepared statement + /// or to (System.Data.CommandType.StoredProcedure) to specify a stored + /// procedure. + /// + /// + /// The prepared statement text or the name of the stored procedure + /// must be set in the property. + /// + /// + /// The prepared statement or stored procedure can take a number + /// of parameters. Parameters are added using the + /// method. This adds a single to the + /// ordered list of parameters. The + /// type may be subclassed if required to provide database specific + /// functionality. The specifies + /// the parameter name, database type, size, and how the value should + /// be generated using a . + /// + /// + /// + /// An example of a SQL Server table that could be logged to: + /// + /// CREATE TABLE [dbo].[Log] ( + /// [ID] [int] IDENTITY (1, 1) NOT NULL , + /// [Date] [datetime] NOT NULL , + /// [Thread] [varchar] (255) NOT NULL , + /// [Level] [varchar] (20) NOT NULL , + /// [Logger] [varchar] (255) NOT NULL , + /// [Message] [varchar] (4000) NOT NULL + /// ) ON [PRIMARY] + /// + /// + /// + /// An example configuration to log to the above table: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Julian Biddle. + /// Nicko Cadell. + /// Gert Driesen. + /// Lance Nehring. + public class AdoNetAppender : BufferingAppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// Public default constructor to initialize a new instance of this class. + /// + public AdoNetAppender() + { + this.ConnectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; + this.UseTransactions = true; + this.CommandType = System.Data.CommandType.Text; + this.m_parameters = new ArrayList(); + this.ReconnectOnError = false; + } + + /// + /// Gets or sets the database connection string that is used to connect to + /// the database. + /// + /// + /// The database connection string used to connect to the database. + /// + /// + /// + /// The connections string is specific to the connection type. + /// See for more information. + /// + /// + /// Connection string for MS Access via ODBC: + /// "DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb" + /// + /// Another connection string for MS Access via ODBC: + /// "Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\log4net-1.2\access.mdb;UID=;PWD=;" + /// + /// Connection string for MS Access via OLE DB: + /// "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;" + /// + public string ConnectionString + { + get { return this.m_connectionString; } + set { this.m_connectionString = value; } + } + + /// + /// Gets or sets the appSettings key from App.Config that contains the connection string. + /// + public string AppSettingsKey + { + get { return this.m_appSettingsKey; } + set { this.m_appSettingsKey = value; } + } #if NET_2_0 - /// - /// The connectionStrings key from App.Config that contains the connection string. - /// - /// - /// This property requires at least .NET 2.0. - /// - public string ConnectionStringName - { - get { return m_connectionStringName; } - set { m_connectionStringName = value; } - } + /// + /// Gets or sets the connectionStrings key from App.Config that contains the connection string. + /// + /// + /// This property requires at least .NET 2.0. + /// + public string ConnectionStringName + { + get { return this.m_connectionStringName; } + set { this.m_connectionStringName = value; } + } #endif - /// - /// Gets or sets the type name of the connection - /// that should be created. - /// - /// - /// The type name of the connection. - /// - /// - /// - /// The type name of the ADO.NET provider to use. - /// - /// - /// The default is to use the OLE DB provider. - /// - /// - /// Use the OLE DB Provider. This is the default value. - /// System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - /// - /// Use the MS SQL Server Provider. - /// System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - /// - /// Use the ODBC Provider. - /// Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral - /// This is an optional package that you can download from - /// http://msdn.microsoft.com/downloads - /// search for ODBC .NET Data Provider. - /// - /// Use the Oracle Provider. - /// System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - /// This is an optional package that you can download from - /// http://msdn.microsoft.com/downloads - /// search for .NET Managed Provider for Oracle. - /// - public string ConnectionType - { - get { return m_connectionType; } - set { m_connectionType = value; } - } - - /// - /// Gets or sets the command text that is used to insert logging events - /// into the database. - /// - /// - /// The command text used to insert logging events into the database. - /// - /// - /// - /// Either the text of the prepared statement or the - /// name of the stored procedure to execute to write into - /// the database. - /// - /// - /// The property determines if - /// this text is a prepared statement or a stored procedure. - /// - /// - /// If this property is not set, the command text is retrieved by invoking - /// . - /// - /// - public string CommandText - { - get { return m_commandText; } - set { m_commandText = value; } - } - - /// - /// Gets or sets the command type to execute. - /// - /// - /// The command type to execute. - /// - /// - /// - /// This value may be either (System.Data.CommandType.Text) to specify - /// that the is a prepared statement to execute, - /// or (System.Data.CommandType.StoredProcedure) to specify that the - /// property is the name of a stored procedure - /// to execute. - /// - /// - /// The default value is (System.Data.CommandType.Text). - /// - /// - public CommandType CommandType - { - get { return m_commandType; } - set { m_commandType = value; } - } - - /// - /// Should transactions be used to insert logging events in the database. - /// - /// - /// true if transactions should be used to insert logging events in - /// the database, otherwise false. The default value is true. - /// - /// - /// - /// Gets or sets a value that indicates whether transactions should be used - /// to insert logging events in the database. - /// - /// - /// When set a single transaction will be used to insert the buffered events - /// into the database. Otherwise each event will be inserted without using - /// an explicit transaction. - /// - /// - public bool UseTransactions - { - get { return m_useTransactions; } - set { m_useTransactions = value; } - } - - /// - /// Gets or sets the used to call the NetSend method. - /// - /// - /// The used to call the NetSend method. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return m_securityContext; } - set { m_securityContext = value; } - } - - /// - /// Should this appender try to reconnect to the database on error. - /// - /// - /// true if the appender should try to reconnect to the database after an - /// error has occurred, otherwise false. The default value is false, - /// i.e. not to try to reconnect. - /// - /// - /// - /// The default behaviour is for the appender not to try to reconnect to the - /// database if an error occurs. Subsequent logging events are discarded. - /// - /// - /// To force the appender to attempt to reconnect to the database set this - /// property to true. - /// - /// - /// When the appender attempts to connect to the database there may be a - /// delay of up to the connection timeout specified in the connection string. - /// This delay will block the calling application's thread. - /// Until the connection can be reestablished this potential delay may occur multiple times. - /// - /// - public bool ReconnectOnError - { - get { return m_reconnectOnError; } - set { m_reconnectOnError = value; } - } - - #endregion // Public Instance Properties - - #region Protected Instance Properties - - /// - /// Gets or sets the underlying . - /// - /// - /// The underlying . - /// - /// - /// creates a to insert - /// logging events into a database. Classes deriving from - /// can use this property to get or set this . Use the - /// underlying returned from if - /// you require access beyond that which provides. - /// - protected IDbConnection Connection - { - get { return m_dbConnection; } - set { m_dbConnection = value; } - } - - #endregion // Protected Instance Properties - - #region Implementation of IOptionHandler - - /// - /// Initialize the appender based on the options set - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { - base.ActivateOptions(); - - if (SecurityContext == null) - { - SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - InitializeDatabaseConnection(); - } - - #endregion - - #region Override implementation of AppenderSkeleton - - /// - /// Override the parent method to close the database - /// - /// - /// - /// Closes the database command and database connection. - /// - /// - override protected void OnClose() - { - base.OnClose(); - DiposeConnection(); - } - - #endregion - - #region Override implementation of BufferingAppenderSkeleton - - /// - /// Inserts the events into the database. - /// - /// The events to insert into the database. - /// - /// - /// Insert all the events specified in the - /// array into the database. - /// - /// - override protected void SendBuffer(LoggingEvent[] events) - { - if (ReconnectOnError && (Connection == null || Connection.State != ConnectionState.Open)) - { - LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((Connection == null) ? SystemInfo.NullText : Connection.State.ToString())); - - InitializeDatabaseConnection(); - } - - // Check that the connection exists and is open - if (Connection != null && Connection.State == ConnectionState.Open) - { - if (UseTransactions) - { - // Create transaction - // NJC - Do this on 2 lines because it can confuse the debugger - using (IDbTransaction dbTran = Connection.BeginTransaction()) - { - try - { - SendBuffer(dbTran, events); - - // commit transaction - dbTran.Commit(); - } - catch (Exception ex) - { - // rollback the transaction - try - { - dbTran.Rollback(); - } - catch (Exception) - { - // Ignore exception - } - - // Can't insert into the database. That's a bad thing - ErrorHandler.Error("Exception while writing to database", ex); - } - } - } - else - { - // Send without transaction - SendBuffer(null, events); - } - } - } - - #endregion // Override implementation of BufferingAppenderSkeleton - - #region Public Instance Methods - - /// - /// Adds a parameter to the command. - /// - /// The parameter to add to the command. - /// - /// - /// Adds a parameter to the ordered list of command parameters. - /// - /// - public void AddParameter(AdoNetAppenderParameter parameter) - { - m_parameters.Add(parameter); - } - - - #endregion // Public Instance Methods - - #region Protected Instance Methods - - /// - /// Writes the events to the database using the transaction specified. - /// - /// The transaction that the events will be executed under. - /// The array of events to insert into the database. - /// - /// - /// The transaction argument can be null if the appender has been - /// configured not to use transactions. See - /// property for more information. - /// - /// - virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events) - { - // string.IsNotNullOrWhiteSpace() does not exist in ancient .NET frameworks - if (CommandText != null && CommandText.Trim() != "") - { - using (IDbCommand dbCmd = Connection.CreateCommand()) - { - // Set the command string - dbCmd.CommandText = CommandText; - - // Set the command type - dbCmd.CommandType = CommandType; - // Send buffer using the prepared command object - if (dbTran != null) - { - dbCmd.Transaction = dbTran; - } - // prepare the command, which is significantly faster - dbCmd.Prepare(); - // run for all events - foreach (LoggingEvent e in events) - { - // clear parameters that have been set - dbCmd.Parameters.Clear(); - - // Set the parameter values - foreach (AdoNetAppenderParameter param in m_parameters) - { - param.Prepare(dbCmd); - param.FormatValue(dbCmd, e); - } - - // Execute the query - dbCmd.ExecuteNonQuery(); - } - } - } - else - { - // create a new command - using (IDbCommand dbCmd = Connection.CreateCommand()) - { - if (dbTran != null) - { - dbCmd.Transaction = dbTran; - } - // run for all events - foreach (LoggingEvent e in events) - { - // Get the command text from the Layout - string logStatement = GetLogStatement(e); - - LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]"); - - dbCmd.CommandText = logStatement; - dbCmd.ExecuteNonQuery(); - } - } - } - } - - /// - /// Formats the log message into database statement text. - /// - /// The event being logged. - /// - /// This method can be overridden by subclasses to provide - /// more control over the format of the database statement. - /// - /// - /// Text that can be passed to a . - /// - virtual protected string GetLogStatement(LoggingEvent logEvent) - { - if (Layout == null) - { - ErrorHandler.Error("AdoNetAppender: No Layout specified."); - return ""; - } - else - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - Layout.Format(writer, logEvent); - return writer.ToString(); - } - } - - /// - /// Creates an instance used to connect to the database. - /// - /// - /// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary). - /// - /// The of the object. - /// The connectionString output from the ResolveConnectionString method. - /// An instance with a valid connection string. - virtual protected IDbConnection CreateConnection(Type connectionType, string connectionString) - { - IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType); - connection.ConnectionString = connectionString; - return connection; - } - - /// - /// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey - /// property. - /// - /// - /// ConnectiongStringName is only supported on .NET 2.0 and higher. - /// - /// Additional information describing the connection string. - /// A connection string used to connect to the database. - virtual protected string ResolveConnectionString(out string connectionStringContext) - { - if (ConnectionString != null && ConnectionString.Length > 0) - { - connectionStringContext = "ConnectionString"; - return ConnectionString; - } + /// + /// Gets or sets the type name of the connection + /// that should be created. + /// + /// + /// The type name of the connection. + /// + /// + /// + /// The type name of the ADO.NET provider to use. + /// + /// + /// The default is to use the OLE DB provider. + /// + /// + /// Use the OLE DB Provider. This is the default value. + /// System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + /// + /// Use the MS SQL Server Provider. + /// System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + /// + /// Use the ODBC Provider. + /// Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral + /// This is an optional package that you can download from + /// http://msdn.microsoft.com/downloads + /// search for ODBC .NET Data Provider. + /// + /// Use the Oracle Provider. + /// System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + /// This is an optional package that you can download from + /// http://msdn.microsoft.com/downloads + /// search for .NET Managed Provider for Oracle. + /// + public string ConnectionType + { + get { return this.m_connectionType; } + set { this.m_connectionType = value; } + } + + /// + /// Gets or sets the command text that is used to insert logging events + /// into the database. + /// + /// + /// The command text used to insert logging events into the database. + /// + /// + /// + /// Either the text of the prepared statement or the + /// name of the stored procedure to execute to write into + /// the database. + /// + /// + /// The property determines if + /// this text is a prepared statement or a stored procedure. + /// + /// + /// If this property is not set, the command text is retrieved by invoking + /// . + /// + /// + public string CommandText + { + get { return this.m_commandText; } + set { this.m_commandText = value; } + } + + /// + /// Gets or sets the command type to execute. + /// + /// + /// The command type to execute. + /// + /// + /// + /// This value may be either (System.Data.CommandType.Text) to specify + /// that the is a prepared statement to execute, + /// or (System.Data.CommandType.StoredProcedure) to specify that the + /// property is the name of a stored procedure + /// to execute. + /// + /// + /// The default value is (System.Data.CommandType.Text). + /// + /// + public CommandType CommandType + { + get { return this.m_commandType; } + set { this.m_commandType = value; } + } + + /// + /// Gets or sets a value indicating whether should transactions be used to insert logging events in the database. + /// + /// + /// true if transactions should be used to insert logging events in + /// the database, otherwise false. The default value is true. + /// + /// + /// + /// Gets or sets a value that indicates whether transactions should be used + /// to insert logging events in the database. + /// + /// + /// When set a single transaction will be used to insert the buffered events + /// into the database. Otherwise each event will be inserted without using + /// an explicit transaction. + /// + /// + public bool UseTransactions + { + get { return this.m_useTransactions; } + set { this.m_useTransactions = value; } + } + + /// + /// Gets or sets the used to call the NetSend method. + /// + /// + /// The used to call the NetSend method. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } + + /// + /// Gets or sets a value indicating whether should this appender try to reconnect to the database on error. + /// + /// + /// true if the appender should try to reconnect to the database after an + /// error has occurred, otherwise false. The default value is false, + /// i.e. not to try to reconnect. + /// + /// + /// + /// The default behaviour is for the appender not to try to reconnect to the + /// database if an error occurs. Subsequent logging events are discarded. + /// + /// + /// To force the appender to attempt to reconnect to the database set this + /// property to true. + /// + /// + /// When the appender attempts to connect to the database there may be a + /// delay of up to the connection timeout specified in the connection string. + /// This delay will block the calling application's thread. + /// Until the connection can be reestablished this potential delay may occur multiple times. + /// + /// + public bool ReconnectOnError + { + get { return this.m_reconnectOnError; } + set { this.m_reconnectOnError = value; } + } + + /// + /// Gets or sets the underlying . + /// + /// + /// The underlying . + /// + /// + /// creates a to insert + /// logging events into a database. Classes deriving from + /// can use this property to get or set this . Use the + /// underlying returned from if + /// you require access beyond that which provides. + /// + protected IDbConnection Connection + { + get { return this.m_dbConnection; } + set { this.m_dbConnection = value; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.SecurityContext == null) + { + this.SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + this.InitializeDatabaseConnection(); + } + + /// + /// Override the parent method to close the database. + /// + /// + /// + /// Closes the database command and database connection. + /// + /// + protected override void OnClose() + { + base.OnClose(); + this.DiposeConnection(); + } + + /// + /// Inserts the events into the database. + /// + /// The events to insert into the database. + /// + /// + /// Insert all the events specified in the + /// array into the database. + /// + /// + protected override void SendBuffer(LoggingEvent[] events) + { + if (this.ReconnectOnError && (this.Connection == null || this.Connection.State != ConnectionState.Open)) + { + LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((this.Connection == null) ? SystemInfo.NullText : this.Connection.State.ToString())); + + this.InitializeDatabaseConnection(); + } + + // Check that the connection exists and is open + if (this.Connection != null && this.Connection.State == ConnectionState.Open) + { + if (this.UseTransactions) + { + // Create transaction + // NJC - Do this on 2 lines because it can confuse the debugger + using (IDbTransaction dbTran = this.Connection.BeginTransaction()) + { + try + { + this.SendBuffer(dbTran, events); + + // commit transaction + dbTran.Commit(); + } + catch (Exception ex) + { + // rollback the transaction + try + { + dbTran.Rollback(); + } + catch (Exception) + { + // Ignore exception + } + + // Can't insert into the database. That's a bad thing + this.ErrorHandler.Error("Exception while writing to database", ex); + } + } + } + else + { + // Send without transaction + this.SendBuffer(null, events); + } + } + } + + /// + /// Adds a parameter to the command. + /// + /// The parameter to add to the command. + /// + /// + /// Adds a parameter to the ordered list of command parameters. + /// + /// + public void AddParameter(AdoNetAppenderParameter parameter) + { + this.m_parameters.Add(parameter); + } + + /// + /// Writes the events to the database using the transaction specified. + /// + /// The transaction that the events will be executed under. + /// The array of events to insert into the database. + /// + /// + /// The transaction argument can be null if the appender has been + /// configured not to use transactions. See + /// property for more information. + /// + /// + protected virtual void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events) + { + // string.IsNotNullOrWhiteSpace() does not exist in ancient .NET frameworks + if (this.CommandText != null && this.CommandText.Trim() != string.Empty) + { + using (IDbCommand dbCmd = this.Connection.CreateCommand()) + { + // Set the command string + dbCmd.CommandText = this.CommandText; + + // Set the command type + dbCmd.CommandType = this.CommandType; + + // Send buffer using the prepared command object + if (dbTran != null) + { + dbCmd.Transaction = dbTran; + } + + // prepare the command, which is significantly faster + dbCmd.Prepare(); + + // run for all events + foreach (LoggingEvent e in events) + { + // clear parameters that have been set + dbCmd.Parameters.Clear(); + + // Set the parameter values + foreach (AdoNetAppenderParameter param in this.m_parameters) + { + param.Prepare(dbCmd); + param.FormatValue(dbCmd, e); + } + + // Execute the query + dbCmd.ExecuteNonQuery(); + } + } + } + else + { + // create a new command + using (IDbCommand dbCmd = this.Connection.CreateCommand()) + { + if (dbTran != null) + { + dbCmd.Transaction = dbTran; + } + + // run for all events + foreach (LoggingEvent e in events) + { + // Get the command text from the Layout + string logStatement = this.GetLogStatement(e); + + LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]"); + + dbCmd.CommandText = logStatement; + dbCmd.ExecuteNonQuery(); + } + } + } + } + + /// + /// Formats the log message into database statement text. + /// + /// The event being logged. + /// + /// This method can be overridden by subclasses to provide + /// more control over the format of the database statement. + /// + /// + /// Text that can be passed to a . + /// + protected virtual string GetLogStatement(LoggingEvent logEvent) + { + if (this.Layout == null) + { + this.ErrorHandler.Error("AdoNetAppender: No Layout specified."); + return string.Empty; + } + else + { + StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + this.Layout.Format(writer, logEvent); + return writer.ToString(); + } + } + + /// + /// Creates an instance used to connect to the database. + /// + /// + /// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary). + /// + /// The of the object. + /// The connectionString output from the ResolveConnectionString method. + /// An instance with a valid connection string. + protected virtual IDbConnection CreateConnection(Type connectionType, string connectionString) + { + IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType); + connection.ConnectionString = connectionString; + return connection; + } + + /// + /// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey + /// property. + /// + /// + /// ConnectiongStringName is only supported on .NET 2.0 and higher. + /// + /// Additional information describing the connection string. + /// A connection string used to connect to the database. + protected virtual string ResolveConnectionString(out string connectionStringContext) + { + if (this.ConnectionString != null && this.ConnectionString.Length > 0) + { + connectionStringContext = "ConnectionString"; + return this.ConnectionString; + } #if NET_2_0 - if (!String.IsNullOrEmpty(ConnectionStringName)) - { - ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[ConnectionStringName]; - if (settings != null) - { - connectionStringContext = "ConnectionStringName"; - return settings.ConnectionString; - } - else - { - throw new LogException("Unable to find [" + ConnectionStringName + "] ConfigurationManager.ConnectionStrings item"); - } - } + if (!string.IsNullOrEmpty(this.ConnectionStringName)) + { + ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[this.ConnectionStringName]; + if (settings != null) + { + connectionStringContext = "ConnectionStringName"; + return settings.ConnectionString; + } + else + { + throw new LogException("Unable to find [" + this.ConnectionStringName + "] ConfigurationManager.ConnectionStrings item"); + } + } #endif - if (AppSettingsKey != null && AppSettingsKey.Length > 0) - { - connectionStringContext = "AppSettingsKey"; - string appSettingsConnectionString = SystemInfo.GetAppSetting(AppSettingsKey); - if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0) - { - throw new LogException("Unable to find [" + AppSettingsKey + "] AppSettings key."); - } - return appSettingsConnectionString; - } - - connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings."; - return string.Empty; - } - - /// - /// Retrieves the class type of the ADO.NET provider. - /// - /// - /// - /// Gets the Type of the ADO.NET provider to use to connect to the - /// database. This method resolves the type specified in the - /// property. - /// - /// - /// Subclasses can override this method to return a different type - /// if necessary. - /// - /// - /// The of the ADO.NET provider - virtual protected Type ResolveConnectionType() - { - try - { - return SystemInfo.GetTypeFromString(ConnectionType, true, false); - } - catch (Exception ex) - { - ErrorHandler.Error("Failed to load connection type [" + ConnectionType + "]", ex); - throw; - } - } - - #endregion // Protected Instance Methods - - #region Private Instance Methods - - /// - /// Connects to the database. - /// - private void InitializeDatabaseConnection() - { - string connectionStringContext = "Unable to determine connection string context."; - string resolvedConnectionString = string.Empty; - - try - { - DiposeConnection(); - - // Set the connection string - resolvedConnectionString = ResolveConnectionString(out connectionStringContext); - - Connection = CreateConnection(ResolveConnectionType(), resolvedConnectionString); - - using (SecurityContext.Impersonate(this)) - { - // Open the database connection - Connection.Open(); - } - } - catch (Exception e) - { - // Sadly, your connection string is bad. - ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e); - - Connection = null; - } - } - - /// - /// Cleanup the existing connection. - /// - /// - /// Calls the IDbConnection's method. - /// - private void DiposeConnection() - { - if (Connection != null) - { - try - { - Connection.Close(); - } - catch (Exception ex) - { - LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex); - } - Connection = null; - } - } - - #endregion // Private Instance Methods - - #region Protected Instance Fields - - /// - /// The list of objects. - /// - /// - /// - /// The list of objects. - /// - /// - protected ArrayList m_parameters; - - #endregion // Protected Instance Fields - - #region Private Instance Fields - - /// - /// The security context to use for privileged calls - /// - private SecurityContext m_securityContext; - - /// - /// The that will be used - /// to insert logging events into a database. - /// - private IDbConnection m_dbConnection; - - /// - /// Database connection string. - /// - private string m_connectionString; - - /// - /// The appSettings key from App.Config that contains the connection string. - /// - private string m_appSettingsKey; + if (this.AppSettingsKey != null && this.AppSettingsKey.Length > 0) + { + connectionStringContext = "AppSettingsKey"; + string appSettingsConnectionString = SystemInfo.GetAppSetting(this.AppSettingsKey); + if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0) + { + throw new LogException("Unable to find [" + this.AppSettingsKey + "] AppSettings key."); + } + + return appSettingsConnectionString; + } + + connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings."; + return string.Empty; + } + + /// + /// Retrieves the class type of the ADO.NET provider. + /// + /// + /// + /// Gets the Type of the ADO.NET provider to use to connect to the + /// database. This method resolves the type specified in the + /// property. + /// + /// + /// Subclasses can override this method to return a different type + /// if necessary. + /// + /// + /// The of the ADO.NET provider. + protected virtual Type ResolveConnectionType() + { + try + { + return SystemInfo.GetTypeFromString(this.ConnectionType, true, false); + } + catch (Exception ex) + { + this.ErrorHandler.Error("Failed to load connection type [" + this.ConnectionType + "]", ex); + throw; + } + } + + /// + /// Connects to the database. + /// + private void InitializeDatabaseConnection() + { + string connectionStringContext = "Unable to determine connection string context."; + string resolvedConnectionString = string.Empty; + + try + { + this.DiposeConnection(); + + // Set the connection string + resolvedConnectionString = this.ResolveConnectionString(out connectionStringContext); + + this.Connection = this.CreateConnection(this.ResolveConnectionType(), resolvedConnectionString); + + using (this.SecurityContext.Impersonate(this)) + { + // Open the database connection + this.Connection.Open(); + } + } + catch (Exception e) + { + // Sadly, your connection string is bad. + this.ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e); + + this.Connection = null; + } + } + + /// + /// Cleanup the existing connection. + /// + /// + /// Calls the IDbConnection's method. + /// + private void DiposeConnection() + { + if (this.Connection != null) + { + try + { + this.Connection.Close(); + } + catch (Exception ex) + { + LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex); + } + + this.Connection = null; + } + } + + /// + /// The list of objects. + /// + /// + /// + /// The list of objects. + /// + /// + protected ArrayList m_parameters; + + /// + /// The security context to use for privileged calls. + /// + private SecurityContext m_securityContext; + + /// + /// The that will be used + /// to insert logging events into a database. + /// + private IDbConnection m_dbConnection; + + /// + /// Database connection string. + /// + private string m_connectionString; + + /// + /// The appSettings key from App.Config that contains the connection string. + /// + private string m_appSettingsKey; #if NET_2_0 - /// - /// The connectionStrings key from App.Config that contains the connection string. - /// - private string m_connectionStringName; + /// + /// The connectionStrings key from App.Config that contains the connection string. + /// + private string m_connectionStringName; #endif - /// - /// String type name of the type name. - /// - private string m_connectionType; - - /// - /// The text of the command. - /// - private string m_commandText; - - /// - /// The command type. - /// - private CommandType m_commandType; - - /// - /// Indicates whether to use transactions when writing to the database. - /// - private bool m_useTransactions; - - /// - /// Indicates whether to reconnect when a connection is lost. - /// - private bool m_reconnectOnError; - - #endregion // Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the AdoNetAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(AdoNetAppender); - - #endregion Private Static Fields - } - - /// - /// Parameter type used by the . - /// - /// - /// - /// This class provides the basic database parameter properties - /// as defined by the interface. - /// - /// This type can be subclassed to provide database specific - /// functionality. The two methods that are called externally are - /// and . - /// - /// - public class AdoNetAppenderParameter - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor for the AdoNetAppenderParameter class. - /// - public AdoNetAppenderParameter() - { - Precision = 0; - Scale = 0; - Size = 0; - } - - #endregion // Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the name of this parameter. - /// - /// - /// The name of this parameter. - /// - /// - /// - /// The name of this parameter. The parameter name - /// must match up to a named parameter to the SQL stored procedure - /// or prepared statement. - /// - /// - public string ParameterName - { - get { return m_parameterName; } - set { m_parameterName = value; } - } - - /// - /// Gets or sets the database type for this parameter. - /// - /// - /// The database type for this parameter. - /// - /// - /// - /// The database type for this parameter. This property should - /// be set to the database type from the - /// enumeration. See . - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the type from the value. - /// - /// - /// - public DbType DbType - { - get { return m_dbType; } - set - { - m_dbType = value; - m_inferType = false; - } - } - - /// - /// Gets or sets the precision for this parameter. - /// - /// - /// The precision for this parameter. - /// - /// - /// - /// The maximum number of digits used to represent the Value. - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the precision from the value. - /// - /// - /// - public byte Precision - { - get { return m_precision; } - set { m_precision = value; } - } - - /// - /// Gets or sets the scale for this parameter. - /// - /// - /// The scale for this parameter. - /// - /// - /// - /// The number of decimal places to which Value is resolved. - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the scale from the value. - /// - /// - /// - public byte Scale - { - get { return m_scale; } - set { m_scale = value; } - } - - /// - /// Gets or sets the size for this parameter. - /// - /// - /// The size for this parameter. - /// - /// - /// - /// The maximum size, in bytes, of the data within the column. - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the size from the value. - /// - /// - /// For BLOB data types like VARCHAR(max) it may be impossible to infer the value automatically, use -1 as the size in this case. - /// - /// - /// - public int Size - { - get { return m_size; } - set { m_size = value; } - } - - /// - /// Gets or sets the to use to - /// render the logging event into an object for this - /// parameter. - /// - /// - /// The used to render the - /// logging event into an object for this parameter. - /// - /// - /// - /// The that renders the value for this - /// parameter. - /// - /// - /// The can be used to adapt - /// any into a - /// for use in the property. - /// - /// - public IRawLayout Layout - { - get { return m_layout; } - set { m_layout = value; } - } - - #endregion // Public Instance Properties - - #region Public Instance Methods - - /// - /// Prepare the specified database command object. - /// - /// The command to prepare. - /// - /// - /// Prepares the database command object by adding - /// this parameter to its collection of parameters. - /// - /// - virtual public void Prepare(IDbCommand command) - { - // Create a new parameter - IDbDataParameter param = command.CreateParameter(); - - // Set the parameter properties - param.ParameterName = ParameterName; - - if (!m_inferType) - { - param.DbType = DbType; - } - if (Precision != 0) - { - param.Precision = Precision; - } - if (Scale != 0) - { - param.Scale = Scale; - } - if (Size != 0) - { - param.Size = Size; - } - - // Add the parameter to the collection of params - command.Parameters.Add(param); - } - - /// - /// Renders the logging event and set the parameter value in the command. - /// - /// The command containing the parameter. - /// The event to be rendered. - /// - /// - /// Renders the logging event using this parameters layout - /// object. Sets the value of the parameter on the command object. - /// - /// - virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent) - { - // Lookup the parameter - IDbDataParameter param = (IDbDataParameter)command.Parameters[ParameterName]; - - // Format the value - object formattedValue = Layout.Format(loggingEvent); - - // If the value is null then convert to a DBNull - if (formattedValue == null) - { - formattedValue = DBNull.Value; - } - - param.Value = formattedValue; - } - - #endregion // Public Instance Methods - - #region Private Instance Fields - - /// - /// The name of this parameter. - /// - private string m_parameterName; - - /// - /// The database type for this parameter. - /// - private DbType m_dbType; - - /// - /// Flag to infer type rather than use the DbType - /// - private bool m_inferType = true; - - /// - /// The precision for this parameter. - /// - private byte m_precision; - - /// - /// The scale for this parameter. - /// - private byte m_scale; - - /// - /// The size for this parameter. - /// - private int m_size; - - /// - /// The to use to render the - /// logging event into an object for this parameter. - /// - private IRawLayout m_layout; - - #endregion // Private Instance Fields - } + /// + /// String type name of the type name. + /// + private string m_connectionType; + + /// + /// The text of the command. + /// + private string m_commandText; + + /// + /// The command type. + /// + private CommandType m_commandType; + + /// + /// Indicates whether to use transactions when writing to the database. + /// + private bool m_useTransactions; + + /// + /// Indicates whether to reconnect when a connection is lost. + /// + private bool m_reconnectOnError; + + /// + /// The fully qualified type of the AdoNetAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(AdoNetAppender); + } + + /// + /// Parameter type used by the . + /// + /// + /// + /// This class provides the basic database parameter properties + /// as defined by the interface. + /// + /// This type can be subclassed to provide database specific + /// functionality. The two methods that are called externally are + /// and . + /// + /// + public class AdoNetAppenderParameter + { + /// + /// Initializes a new instance of the class. + /// + /// + /// Default constructor for the AdoNetAppenderParameter class. + /// + public AdoNetAppenderParameter() + { + this.Precision = 0; + this.Scale = 0; + this.Size = 0; + } + + /// + /// Gets or sets the name of this parameter. + /// + /// + /// The name of this parameter. + /// + /// + /// + /// The name of this parameter. The parameter name + /// must match up to a named parameter to the SQL stored procedure + /// or prepared statement. + /// + /// + public string ParameterName + { + get { return this.m_parameterName; } + set { this.m_parameterName = value; } + } + + /// + /// Gets or sets the database type for this parameter. + /// + /// + /// The database type for this parameter. + /// + /// + /// + /// The database type for this parameter. This property should + /// be set to the database type from the + /// enumeration. See . + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the type from the value. + /// + /// + /// + public DbType DbType + { + get { return this.m_dbType; } + + set + { + this.m_dbType = value; + this.m_inferType = false; + } + } + + /// + /// Gets or sets the precision for this parameter. + /// + /// + /// The precision for this parameter. + /// + /// + /// + /// The maximum number of digits used to represent the Value. + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the precision from the value. + /// + /// + /// + public byte Precision + { + get { return this.m_precision; } + set { this.m_precision = value; } + } + + /// + /// Gets or sets the scale for this parameter. + /// + /// + /// The scale for this parameter. + /// + /// + /// + /// The number of decimal places to which Value is resolved. + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the scale from the value. + /// + /// + /// + public byte Scale + { + get { return this.m_scale; } + set { this.m_scale = value; } + } + + /// + /// Gets or sets the size for this parameter. + /// + /// + /// The size for this parameter. + /// + /// + /// + /// The maximum size, in bytes, of the data within the column. + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the size from the value. + /// + /// + /// For BLOB data types like VARCHAR(max) it may be impossible to infer the value automatically, use -1 as the size in this case. + /// + /// + /// + public int Size + { + get { return this.m_size; } + set { this.m_size = value; } + } + + /// + /// Gets or sets the to use to + /// render the logging event into an object for this + /// parameter. + /// + /// + /// The used to render the + /// logging event into an object for this parameter. + /// + /// + /// + /// The that renders the value for this + /// parameter. + /// + /// + /// The can be used to adapt + /// any into a + /// for use in the property. + /// + /// + public IRawLayout Layout + { + get { return this.m_layout; } + set { this.m_layout = value; } + } + + /// + /// Prepare the specified database command object. + /// + /// The command to prepare. + /// + /// + /// Prepares the database command object by adding + /// this parameter to its collection of parameters. + /// + /// + public virtual void Prepare(IDbCommand command) + { + // Create a new parameter + IDbDataParameter param = command.CreateParameter(); + + // Set the parameter properties + param.ParameterName = this.ParameterName; + + if (!this.m_inferType) + { + param.DbType = this.DbType; + } + + if (this.Precision != 0) + { + param.Precision = this.Precision; + } + + if (this.Scale != 0) + { + param.Scale = this.Scale; + } + + if (this.Size != 0) + { + param.Size = this.Size; + } + + // Add the parameter to the collection of params + command.Parameters.Add(param); + } + + /// + /// Renders the logging event and set the parameter value in the command. + /// + /// The command containing the parameter. + /// The event to be rendered. + /// + /// + /// Renders the logging event using this parameters layout + /// object. Sets the value of the parameter on the command object. + /// + /// + public virtual void FormatValue(IDbCommand command, LoggingEvent loggingEvent) + { + // Lookup the parameter + IDbDataParameter param = (IDbDataParameter)command.Parameters[this.ParameterName]; + + // Format the value + object formattedValue = this.Layout.Format(loggingEvent); + + // If the value is null then convert to a DBNull + if (formattedValue == null) + { + formattedValue = DBNull.Value; + } + + param.Value = formattedValue; + } + + /// + /// The name of this parameter. + /// + private string m_parameterName; + + /// + /// The database type for this parameter. + /// + private DbType m_dbType; + + /// + /// Flag to infer type rather than use the DbType. + /// + private bool m_inferType = true; + + /// + /// The precision for this parameter. + /// + private byte m_precision; + + /// + /// The scale for this parameter. + /// + private byte m_scale; + + /// + /// The size for this parameter. + /// + private int m_size; + + /// + /// The to use to render the + /// logging event into an object for this parameter. + /// + private IRawLayout m_layout; + } } #endif // !SSCLI diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs index 73ec45543e2..f54b7c1b57a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs @@ -1,578 +1,555 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.Globalization; - -using log4net.Core; -using log4net.Layout; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Appends logging events to the terminal using ANSI color escape sequences. - /// - /// - /// - /// AnsiColorTerminalAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. It also allows the color of a specific level of message to be set. - /// - /// - /// This appender expects the terminal to understand the VT100 control set - /// in order to interpret the color codes. If the terminal or console does not - /// understand the control codes the behavior is not defined. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// NOTE: This appender writes each message to the System.Console.Out or - /// System.Console.Error that is set at the time the event is appended. - /// Therefore it is possible to programmatically redirect the output of this appender - /// (for example NUnit does this to capture program output). While this is the desired - /// behavior of this appender it may have security implications in your application. - /// - /// - /// When configuring the ANSI colored terminal appender, a mapping should be - /// specified to map a logging level to a color. For example: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The Level is the standard log4net logging level and ForeColor and BackColor can be any - /// of the following values: - /// - /// Blue - /// Green - /// Red - /// White - /// Yellow - /// Purple - /// Cyan - /// - /// These color values cannot be combined together to make new colors. - /// - /// - /// The attributes can be any combination of the following: - /// - /// Brightforeground is brighter - /// Dimforeground is dimmer - /// Underscoremessage is underlined - /// Blinkforeground is blinking (does not work on all terminals) - /// Reverseforeground and background are reversed - /// Hiddenoutput is hidden - /// Strikethroughmessage has a line through it - /// - /// While any of these attributes may be combined together not all combinations - /// work well together, for example setting both Bright and Dim attributes makes - /// no sense. - /// - /// - /// Patrick Wagstrom - /// Nicko Cadell - public class AnsiColorTerminalAppender : AppenderSkeleton - { - #region Colors Enum - - /// - /// The enum of possible display attributes - /// - /// - /// - /// The following flags can be combined together to - /// form the ANSI color attributes. - /// - /// - /// - [Flags] - public enum AnsiAttributes : int - { - /// - /// text is bright - /// - Bright = 1, - /// - /// text is dim - /// - Dim = 2, - - /// - /// text is underlined - /// - Underscore = 4, - - /// - /// text is blinking - /// - /// - /// Not all terminals support this attribute - /// - Blink = 8, - - /// - /// text and background colors are reversed - /// - Reverse = 16, - - /// - /// text is hidden - /// - Hidden = 32, - - /// - /// text is displayed with a strikethrough - /// - Strikethrough = 64, - - /// - /// text color is light - /// - Light = 128 - } - - /// - /// The enum of possible foreground or background color values for - /// use with the color mapping method - /// - /// - /// - /// The output can be in one for the following ANSI colors. - /// - /// - /// - public enum AnsiColor : int - { - /// - /// color is black - /// - Black = 0, - - /// - /// color is red - /// - Red = 1, - - /// - /// color is green - /// - Green = 2, - - /// - /// color is yellow - /// - Yellow = 3, - - /// - /// color is blue - /// - Blue = 4, - - /// - /// color is magenta - /// - Magenta = 5, - - /// - /// color is cyan - /// - Cyan = 6, - - /// - /// color is white - /// - White = 7 - } - - #endregion - - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public AnsiColorTerminalAppender() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Target is the value of the console output stream. - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - virtual public string Target - { - get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; } - set - { - string trimmedTargetName = value.Trim(); - - if (SystemInfo.EqualsIgnoringCase(ConsoleError, trimmedTargetName)) - { - m_writeToErrorStream = true; - } - else - { - m_writeToErrorStream = false; - } - } - } - - /// - /// Add a mapping of level to color - /// - /// The mapping to add - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the foreground and background colours - /// for a level. - /// - /// - public void AddMapping(LevelColors mapping) - { - m_levelMapping.Add(mapping); - } - - #endregion Public Instance Properties - - #region Override implementation of AppenderSkeleton - - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - override protected void Append(log4net.Core.LoggingEvent loggingEvent) - { - string loggingMessage = RenderLoggingEvent(loggingEvent); - - // see if there is a specified lookup. - LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; - if (levelColors != null) - { - // Prepend the Ansi Color code - loggingMessage = levelColors.CombinedColor + loggingMessage; - } - - // on most terminals there are weird effects if we don't clear the background color - // before the new line. This checks to see if it ends with a newline, and if - // so, inserts the clear codes before the newline, otherwise the clear codes - // are inserted afterwards. - if (loggingMessage.Length > 1) - { - if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r")) - { - loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes); - } - else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r")) - { - loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes); - } - else - { - loggingMessage = loggingMessage + PostEventCodes; - } - } - else - { - if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r') - { - loggingMessage = PostEventCodes + loggingMessage; - } - else - { - loggingMessage = loggingMessage + PostEventCodes; - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + using System.Text; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// Appends logging events to the terminal using ANSI color escape sequences. + /// + /// + /// + /// AnsiColorTerminalAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. It also allows the color of a specific level of message to be set. + /// + /// + /// This appender expects the terminal to understand the VT100 control set + /// in order to interpret the color codes. If the terminal or console does not + /// understand the control codes the behavior is not defined. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// NOTE: This appender writes each message to the System.Console.Out or + /// System.Console.Error that is set at the time the event is appended. + /// Therefore it is possible to programmatically redirect the output of this appender + /// (for example NUnit does this to capture program output). While this is the desired + /// behavior of this appender it may have security implications in your application. + /// + /// + /// When configuring the ANSI colored terminal appender, a mapping should be + /// specified to map a logging level to a color. For example: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// The Level is the standard log4net logging level and ForeColor and BackColor can be any + /// of the following values: + /// + /// Blue + /// Green + /// Red + /// White + /// Yellow + /// Purple + /// Cyan + /// + /// These color values cannot be combined together to make new colors. + /// + /// + /// The attributes can be any combination of the following: + /// + /// Brightforeground is brighter + /// Dimforeground is dimmer + /// Underscoremessage is underlined + /// Blinkforeground is blinking (does not work on all terminals) + /// Reverseforeground and background are reversed + /// Hiddenoutput is hidden + /// Strikethroughmessage has a line through it + /// + /// While any of these attributes may be combined together not all combinations + /// work well together, for example setting both Bright and Dim attributes makes + /// no sense. + /// + /// + /// Patrick Wagstrom. + /// Nicko Cadell. + public class AnsiColorTerminalAppender : AppenderSkeleton + { + /// + /// The enum of possible display attributes. + /// + /// + /// + /// The following flags can be combined together to + /// form the ANSI color attributes. + /// + /// + /// + [Flags] + public enum AnsiAttributes : int + { + /// + /// text is bright + /// + Bright = 1, + + /// + /// text is dim + /// + Dim = 2, + + /// + /// text is underlined + /// + Underscore = 4, + + /// + /// text is blinking + /// + /// + /// Not all terminals support this attribute + /// + Blink = 8, + + /// + /// text and background colors are reversed + /// + Reverse = 16, + + /// + /// text is hidden + /// + Hidden = 32, + + /// + /// text is displayed with a strikethrough + /// + Strikethrough = 64, + + /// + /// text color is light + /// + Light = 128, + } + + /// + /// The enum of possible foreground or background color values for + /// use with the color mapping method. + /// + /// + /// + /// The output can be in one for the following ANSI colors. + /// + /// + /// + public enum AnsiColor : int + { + /// + /// color is black + /// + Black = 0, + + /// + /// color is red + /// + Red = 1, + + /// + /// color is green + /// + Green = 2, + + /// + /// color is yellow + /// + Yellow = 3, + + /// + /// color is blue + /// + Blue = 4, + + /// + /// color is magenta + /// + Magenta = 5, + + /// + /// color is cyan + /// + Cyan = 6, + + /// + /// color is white + /// + White = 7, + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public AnsiColorTerminalAppender() + { + } + + /// + /// Gets or sets target is the value of the console output stream. + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + + set + { + string trimmedTargetName = value.Trim(); + + if (SystemInfo.EqualsIgnoringCase(ConsoleError, trimmedTargetName)) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } + } + + /// + /// Add a mapping of level to color. + /// + /// The mapping to add. + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the foreground and background colours + /// for a level. + /// + /// + public void AddMapping(LevelColors mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(log4net.Core.LoggingEvent loggingEvent) + { + string loggingMessage = this.RenderLoggingEvent(loggingEvent); + + // see if there is a specified lookup. + LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; + if (levelColors != null) + { + // Prepend the Ansi Color code + loggingMessage = levelColors.CombinedColor + loggingMessage; + } + + // on most terminals there are weird effects if we don't clear the background color + // before the new line. This checks to see if it ends with a newline, and if + // so, inserts the clear codes before the newline, otherwise the clear codes + // are inserted afterwards. + if (loggingMessage.Length > 1) + { + if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r")) + { + loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes); + } + else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r")) + { + loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes); + } + else + { + loggingMessage = loggingMessage + PostEventCodes; + } + } + else + { + if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r') + { + loggingMessage = PostEventCodes + loggingMessage; + } + else + { + loggingMessage = loggingMessage + PostEventCodes; + } + } #if NETCF_1_0 // Write to the output stream Console.Write(loggingMessage); #else - if (m_writeToErrorStream) - { - // Write to the error stream - Console.Error.Write(loggingMessage); - } - else - { - // Write to the output stream - Console.Write(loggingMessage); - } + if (this.m_writeToErrorStream) + { + // Write to the error stream + Console.Error.Write(loggingMessage); + } + else + { + // Write to the output stream + Console.Write(loggingMessage); + } #endif - - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - /// - /// Initialize the options for this appender - /// - /// - /// - /// Initialize the level to color mappings set on this appender. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - m_levelMapping.ActivateOptions(); - } - - #endregion Override implementation of AppenderSkeleton - - #region Public Static Fields - - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; - - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - public const string ConsoleError = "Console.Error"; - - #endregion Public Static Fields - - #region Private Instances Fields - - /// - /// Flag to write output to the error stream rather than the standard output stream - /// - private bool m_writeToErrorStream = false; - - /// - /// Mapping from level object to color value - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// Ansi code to reset terminal - /// - private const string PostEventCodes = "\x1b[0m"; - - #endregion Private Instances Fields - - #region LevelColors LevelMapping Entry - - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and the color it should be displayed in. - /// - /// - public class LevelColors : LevelMappingEntry - { - private AnsiColor m_foreColor; - private AnsiColor m_backColor; - private AnsiAttributes m_attributes; - private string m_combinedColor = ""; - - /// - /// The mapped foreground color for the specified level - /// - /// - /// - /// Required property. - /// The mapped foreground color for the specified level - /// - /// - public AnsiColor ForeColor - { - get { return m_foreColor; } - set { m_foreColor = value; } - } - - /// - /// The mapped background color for the specified level - /// - /// - /// - /// Required property. - /// The mapped background color for the specified level - /// - /// - public AnsiColor BackColor - { - get { return m_backColor; } - set { m_backColor = value; } - } - - /// - /// The color attributes for the specified level - /// - /// - /// - /// Required property. - /// The color attributes for the specified level - /// - /// - public AnsiAttributes Attributes - { - get { return m_attributes; } - set { m_attributes = value; } - } - - /// - /// Initialize the options for the object - /// - /// - /// - /// Combine the and together - /// and append the attributes. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - - StringBuilder buf = new StringBuilder(); - - // Reset any existing codes - buf.Append("\x1b[0;"); - - int lightAdjustment = ((m_attributes & AnsiAttributes.Light) > 0) ? 60 : 0; - - // set the foreground color - buf.Append(30 + lightAdjustment + (int)m_foreColor); - buf.Append(';'); - - // set the background color - buf.Append(40 + lightAdjustment + (int)m_backColor); - - // set the attributes - if ((m_attributes & AnsiAttributes.Bright) > 0) - { - buf.Append(";1"); - } - if ((m_attributes & AnsiAttributes.Dim) > 0) - { - buf.Append(";2"); - } - if ((m_attributes & AnsiAttributes.Underscore) > 0) - { - buf.Append(";4"); - } - if ((m_attributes & AnsiAttributes.Blink) > 0) - { - buf.Append(";5"); - } - if ((m_attributes & AnsiAttributes.Reverse) > 0) - { - buf.Append(";7"); - } - if ((m_attributes & AnsiAttributes.Hidden) > 0) - { - buf.Append(";8"); - } - if ((m_attributes & AnsiAttributes.Strikethrough) > 0) - { - buf.Append(";9"); - } - - buf.Append('m'); - - m_combinedColor = buf.ToString(); - } - - /// - /// The combined , and - /// suitable for setting the ansi terminal color. - /// - internal string CombinedColor - { - get { return m_combinedColor; } - } - } - - #endregion // LevelColors LevelMapping Entry - } + + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Initialize the options for this appender. + /// + /// + /// + /// Initialize the level to color mappings set on this appender. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); + } + + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; + + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + public const string ConsoleError = "Console.Error"; + + /// + /// Flag to write output to the error stream rather than the standard output stream. + /// + private bool m_writeToErrorStream = false; + + /// + /// Mapping from level object to color value. + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// Ansi code to reset terminal. + /// + private const string PostEventCodes = "\x1b[0m"; + + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and the color it should be displayed in. + /// + /// + public class LevelColors : LevelMappingEntry + { + private AnsiColor m_foreColor; + private AnsiColor m_backColor; + private AnsiAttributes m_attributes; + private string m_combinedColor = string.Empty; + + /// + /// Gets or sets the mapped foreground color for the specified level. + /// + /// + /// + /// Required property. + /// The mapped foreground color for the specified level. + /// + /// + public AnsiColor ForeColor + { + get { return this.m_foreColor; } + set { this.m_foreColor = value; } + } + + /// + /// Gets or sets the mapped background color for the specified level. + /// + /// + /// + /// Required property. + /// The mapped background color for the specified level. + /// + /// + public AnsiColor BackColor + { + get { return this.m_backColor; } + set { this.m_backColor = value; } + } + + /// + /// Gets or sets the color attributes for the specified level. + /// + /// + /// + /// Required property. + /// The color attributes for the specified level. + /// + /// + public AnsiAttributes Attributes + { + get { return this.m_attributes; } + set { this.m_attributes = value; } + } + + /// + /// Initialize the options for the object. + /// + /// + /// + /// Combine the and together + /// and append the attributes. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + StringBuilder buf = new StringBuilder(); + + // Reset any existing codes + buf.Append("\x1b[0;"); + + int lightAdjustment = ((this.m_attributes & AnsiAttributes.Light) > 0) ? 60 : 0; + + // set the foreground color + buf.Append(30 + lightAdjustment + (int)this.m_foreColor); + buf.Append(';'); + + // set the background color + buf.Append(40 + lightAdjustment + (int)this.m_backColor); + + // set the attributes + if ((this.m_attributes & AnsiAttributes.Bright) > 0) + { + buf.Append(";1"); + } + + if ((this.m_attributes & AnsiAttributes.Dim) > 0) + { + buf.Append(";2"); + } + + if ((this.m_attributes & AnsiAttributes.Underscore) > 0) + { + buf.Append(";4"); + } + + if ((this.m_attributes & AnsiAttributes.Blink) > 0) + { + buf.Append(";5"); + } + + if ((this.m_attributes & AnsiAttributes.Reverse) > 0) + { + buf.Append(";7"); + } + + if ((this.m_attributes & AnsiAttributes.Hidden) > 0) + { + buf.Append(";8"); + } + + if ((this.m_attributes & AnsiAttributes.Strikethrough) > 0) + { + buf.Append(";9"); + } + + buf.Append('m'); + + this.m_combinedColor = buf.ToString(); + } + + /// + /// Gets the combined , and + /// suitable for setting the ansi terminal color. + /// + internal string CombinedColor + { + get { return this.m_combinedColor; } + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs index c678ac680e6..030f4b925c3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs @@ -1,909 +1,823 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// A strongly-typed collection of objects. - /// - /// Nicko Cadell - public class AppenderCollection : ICollection, IList, IEnumerable + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// A strongly-typed collection of objects. + /// + /// Nicko Cadell. + public class AppenderCollection : ICollection, IList, IEnumerable #if !NETSTANDARD1_3 - , ICloneable + , ICloneable #endif - { - #region Interfaces - /// - /// Supports type-safe iteration over a . - /// - /// - public interface IAppenderCollectionEnumerator - { - /// - /// Gets the current element in the collection. - /// - IAppender Current { get; } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - bool MoveNext(); - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - void Reset(); - } - #endregion - - private const int DEFAULT_CAPACITY = 16; - - #region Implementation (data) - - private IAppender[] m_array; - private int m_count = 0; - private int m_version = 0; - - #endregion - - #region Static Wrappers - - /// - /// Creates a read-only wrapper for a AppenderCollection instance. - /// - /// list to create a readonly wrapper arround - /// - /// An AppenderCollection wrapper that is read-only. - /// - public static AppenderCollection ReadOnly(AppenderCollection list) - { - if(list==null) throw new ArgumentNullException("list"); - - return new ReadOnlyAppenderCollection(list); - } - - #endregion - - #region Static Fields - - /// - /// An empty readonly static AppenderCollection - /// - public static readonly AppenderCollection EmptyCollection = ReadOnly(new AppenderCollection(0)); - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the AppenderCollection class - /// that is empty and has the default initial capacity. - /// - public AppenderCollection() - { - m_array = new IAppender[DEFAULT_CAPACITY]; - } - - /// - /// Initializes a new instance of the AppenderCollection class - /// that has the specified initial capacity. - /// - /// - /// The number of elements that the new AppenderCollection is initially capable of storing. - /// - public AppenderCollection(int capacity) - { - m_array = new IAppender[capacity]; - } - - /// - /// Initializes a new instance of the AppenderCollection class - /// that contains elements copied from the specified AppenderCollection. - /// - /// The AppenderCollection whose elements are copied to the new collection. - public AppenderCollection(AppenderCollection c) - { - m_array = new IAppender[c.Count]; - AddRange(c); - } - - /// - /// Initializes a new instance of the AppenderCollection class - /// that contains elements copied from the specified array. - /// - /// The array whose elements are copied to the new list. - public AppenderCollection(IAppender[] a) - { - m_array = new IAppender[a.Length]; - AddRange(a); - } - - /// - /// Initializes a new instance of the AppenderCollection class - /// that contains elements copied from the specified collection. - /// - /// The collection whose elements are copied to the new list. - public AppenderCollection(ICollection col) - { - m_array = new IAppender[col.Count]; - AddRange(col); - } - - /// - /// Type visible only to our subclasses - /// Used to access protected constructor - /// - /// - internal protected enum Tag - { - /// - /// A value - /// - Default - } - - /// - /// Allow subclasses to avoid our default constructors - /// - /// - /// - internal protected AppenderCollection(Tag tag) - { - m_array = null; - } - - #endregion - - #region Operations (type-safe ICollection) - - /// - /// Gets the number of elements actually contained in the AppenderCollection. - /// - public virtual int Count - { - get { return m_count; } - } - - /// - /// Copies the entire AppenderCollection to a one-dimensional - /// array. - /// - /// The one-dimensional array to copy to. - public virtual void CopyTo(IAppender[] array) - { - this.CopyTo(array, 0); - } - - /// - /// Copies the entire AppenderCollection to a one-dimensional - /// array, starting at the specified index of the target array. - /// - /// The one-dimensional array to copy to. - /// The zero-based index in at which copying begins. - public virtual void CopyTo(IAppender[] array, int start) - { - if (m_count > array.GetUpperBound(0) + 1 - start) - { - throw new System.ArgumentException("Destination array was not long enough."); - } - - Array.Copy(m_array, 0, array, start, m_count); - } - - /// - /// Gets a value indicating whether access to the collection is synchronized (thread-safe). - /// - /// false, because the backing type is an array, which is never thread-safe. - public virtual bool IsSynchronized - { - get { return false; } - } - - /// - /// Gets an object that can be used to synchronize access to the collection. - /// - public virtual object SyncRoot - { - get { return m_array; } - } - - #endregion - - #region Operations (type-safe IList) - - /// - /// Gets or sets the at the specified index. - /// - /// The zero-based index of the element to get or set. - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - public virtual IAppender this[int index] - { - get - { - ValidateIndex(index); // throws - return m_array[index]; - } - set - { - ValidateIndex(index); // throws - ++m_version; - m_array[index] = value; - } - } - - /// - /// Adds a to the end of the AppenderCollection. - /// - /// The to be added to the end of the AppenderCollection. - /// The index at which the value has been added. - public virtual int Add(IAppender item) - { - if (m_count == m_array.Length) - { - EnsureCapacity(m_count + 1); - } - - m_array[m_count] = item; - m_version++; - - return m_count++; - } - - /// - /// Removes all elements from the AppenderCollection. - /// - public virtual void Clear() - { - ++m_version; - m_array = new IAppender[DEFAULT_CAPACITY]; - m_count = 0; - } - - /// - /// Creates a shallow copy of the . - /// - /// A new with a shallow copy of the collection data. - public virtual object Clone() - { - AppenderCollection newCol = new AppenderCollection(m_count); - Array.Copy(m_array, 0, newCol.m_array, 0, m_count); - newCol.m_count = m_count; - newCol.m_version = m_version; - - return newCol; - } - - /// - /// Determines whether a given is in the AppenderCollection. - /// - /// The to check for. - /// true if is found in the AppenderCollection; otherwise, false. - public virtual bool Contains(IAppender item) - { - for (int i=0; i != m_count; ++i) - { - if (m_array[i].Equals(item)) - { - return true; - } - } - return false; - } - - /// - /// Returns the zero-based index of the first occurrence of a - /// in the AppenderCollection. - /// - /// The to locate in the AppenderCollection. - /// - /// The zero-based index of the first occurrence of - /// in the entire AppenderCollection, if found; otherwise, -1. - /// - public virtual int IndexOf(IAppender item) - { - for (int i=0; i != m_count; ++i) - { - if (m_array[i].Equals(item)) - { - return i; - } - } - return -1; - } - - /// - /// Inserts an element into the AppenderCollection at the specified index. - /// - /// The zero-based index at which should be inserted. - /// The to insert. - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - public virtual void Insert(int index, IAppender item) - { - ValidateIndex(index, true); // throws - - if (m_count == m_array.Length) - { - EnsureCapacity(m_count + 1); - } - - if (index < m_count) - { - Array.Copy(m_array, index, m_array, index + 1, m_count - index); - } - - m_array[index] = item; - m_count++; - m_version++; - } - - /// - /// Removes the first occurrence of a specific from the AppenderCollection. - /// - /// The to remove from the AppenderCollection. - /// - /// The specified was not found in the AppenderCollection. - /// - public virtual void Remove(IAppender item) - { - int i = IndexOf(item); - if (i < 0) - { - throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); - } - - ++m_version; - RemoveAt(i); - } - - /// - /// Removes the element at the specified index of the AppenderCollection. - /// - /// The zero-based index of the element to remove. - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - public virtual void RemoveAt(int index) - { - ValidateIndex(index); // throws - - m_count--; - - if (index < m_count) - { - Array.Copy(m_array, index + 1, m_array, index, m_count - index); - } - - // We can't set the deleted entry equal to null, because it might be a value type. - // Instead, we'll create an empty single-element array of the right type and copy it - // over the entry we want to erase. - IAppender[] temp = new IAppender[1]; - Array.Copy(temp, 0, m_array, m_count, 1); - m_version++; - } - - /// - /// Gets a value indicating whether the collection has a fixed size. - /// - /// true if the collection has a fixed size; otherwise, false. The default is false - public virtual bool IsFixedSize - { - get { return false; } - } - - /// - /// Gets a value indicating whether the IList is read-only. - /// - /// true if the collection is read-only; otherwise, false. The default is false - public virtual bool IsReadOnly - { - get { return false; } - } - - #endregion - - #region Operations (type-safe IEnumerable) - - /// - /// Returns an enumerator that can iterate through the AppenderCollection. - /// - /// An for the entire AppenderCollection. - public virtual IAppenderCollectionEnumerator GetEnumerator() - { - return new Enumerator(this); - } - - #endregion - - #region Public helpers (just to mimic some nice features of ArrayList) - - /// - /// Gets or sets the number of elements the AppenderCollection can contain. - /// - public virtual int Capacity - { - get - { - return m_array.Length; - } - set - { - if (value < m_count) - { - value = m_count; - } - - if (value != m_array.Length) - { - if (value > 0) - { - IAppender[] temp = new IAppender[value]; - Array.Copy(m_array, 0, temp, 0, m_count); - m_array = temp; - } - else - { - m_array = new IAppender[DEFAULT_CAPACITY]; - } - } - } - } - - /// - /// Adds the elements of another AppenderCollection to the current AppenderCollection. - /// - /// The AppenderCollection whose elements should be added to the end of the current AppenderCollection. - /// The new of the AppenderCollection. - public virtual int AddRange(AppenderCollection x) - { - if (m_count + x.Count >= m_array.Length) - { - EnsureCapacity(m_count + x.Count); - } - - Array.Copy(x.m_array, 0, m_array, m_count, x.Count); - m_count += x.Count; - m_version++; - - return m_count; - } - - /// - /// Adds the elements of a array to the current AppenderCollection. - /// - /// The array whose elements should be added to the end of the AppenderCollection. - /// The new of the AppenderCollection. - public virtual int AddRange(IAppender[] x) - { - if (m_count + x.Length >= m_array.Length) - { - EnsureCapacity(m_count + x.Length); - } - - Array.Copy(x, 0, m_array, m_count, x.Length); - m_count += x.Length; - m_version++; - - return m_count; - } - - /// - /// Adds the elements of a collection to the current AppenderCollection. - /// - /// The collection whose elements should be added to the end of the AppenderCollection. - /// The new of the AppenderCollection. - public virtual int AddRange(ICollection col) - { - if (m_count + col.Count >= m_array.Length) - { - EnsureCapacity(m_count + col.Count); - } - - foreach(object item in col) - { - Add((IAppender)item); - } - - return m_count; - } - - /// - /// Sets the capacity to the actual number of elements. - /// - public virtual void TrimToSize() - { - this.Capacity = m_count; - } - - /// - /// Return the collection elements as an array - /// - /// the array - public virtual IAppender[] ToArray() - { - IAppender[] resultArray = new IAppender[m_count]; - if (m_count > 0) - { - Array.Copy(m_array, 0, resultArray, 0, m_count); - } - return resultArray; - } - - #endregion - - #region Implementation (helpers) - - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i) - { - ValidateIndex(i, false); - } - - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i, bool allowEqualEnd) - { - int max = (allowEqualEnd) ? (m_count) : (m_count-1); - if (i < 0 || i > max) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); - } - } - - private void EnsureCapacity(int min) - { - int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); - if (newCapacity < min) - { - newCapacity = min; - } - - this.Capacity = newCapacity; - } - - #endregion - - #region Implementation (ICollection) - - void ICollection.CopyTo(Array array, int start) - { - if (m_count > 0) - { - Array.Copy(m_array, 0, array, start, m_count); - } - } - - #endregion - - #region Implementation (IList) - - object IList.this[int i] - { - get { return (object)this[i]; } - set { this[i] = (IAppender)value; } - } - - int IList.Add(object x) - { - return this.Add((IAppender)x); - } - - bool IList.Contains(object x) - { - return this.Contains((IAppender)x); - } - - int IList.IndexOf(object x) - { - return this.IndexOf((IAppender)x); - } - - void IList.Insert(int pos, object x) - { - this.Insert(pos, (IAppender)x); - } - - void IList.Remove(object x) - { - this.Remove((IAppender)x); - } - - void IList.RemoveAt(int pos) - { - this.RemoveAt(pos); - } - - #endregion - - #region Implementation (IEnumerable) - - IEnumerator IEnumerable.GetEnumerator() - { - return (IEnumerator)(this.GetEnumerator()); - } - - #endregion - - #region Nested enumerator class - - /// - /// Supports simple iteration over a . - /// - /// - private sealed class Enumerator : IEnumerator, IAppenderCollectionEnumerator - { - #region Implementation (data) - - private readonly AppenderCollection m_collection; - private int m_index; - private int m_version; - - #endregion - - #region Construction - - /// - /// Initializes a new instance of the Enumerator class. - /// - /// - internal Enumerator(AppenderCollection tc) - { - m_collection = tc; - m_index = -1; - m_version = tc.m_version; - } - - #endregion - - #region Operations (type-safe IEnumerator) - - /// - /// Gets the current element in the collection. - /// - public IAppender Current - { - get { return m_collection[m_index]; } - } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - public bool MoveNext() - { - if (m_version != m_collection.m_version) - { - throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); - } - - ++m_index; - return (m_index < m_collection.Count); - } - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - public void Reset() - { - m_index = -1; - } - #endregion - - #region Implementation (IEnumerator) - - object IEnumerator.Current - { - get { return this.Current; } - } - - #endregion - } - - #endregion - - #region Nested Read Only Wrapper class - - /// - private sealed class ReadOnlyAppenderCollection : AppenderCollection, ICollection - { - #region Implementation (data) - - private readonly AppenderCollection m_collection; - - #endregion - - #region Construction - - internal ReadOnlyAppenderCollection(AppenderCollection list) : base(Tag.Default) - { - m_collection = list; - } - - #endregion - - #region Type-safe ICollection - - public override void CopyTo(IAppender[] array) - { - m_collection.CopyTo(array); - } - - public override void CopyTo(IAppender[] array, int start) - { - m_collection.CopyTo(array,start); - } - - void ICollection.CopyTo(Array array, int start) - { - ((ICollection)m_collection).CopyTo(array, start); - } - - public override int Count - { - get { return m_collection.Count; } - } - - public override bool IsSynchronized - { - get { return m_collection.IsSynchronized; } - } - - public override object SyncRoot - { - get { return this.m_collection.SyncRoot; } - } - - #endregion - - #region Type-safe IList - - public override IAppender this[int i] - { - get { return m_collection[i]; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int Add(IAppender x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Clear() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool Contains(IAppender x) - { - return m_collection.Contains(x); - } - - public override int IndexOf(IAppender x) - { - return m_collection.IndexOf(x); - } - - public override void Insert(int pos, IAppender x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Remove(IAppender x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void RemoveAt(int pos) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool IsFixedSize - { - get { return true; } - } - - public override bool IsReadOnly - { - get { return true; } - } - - #endregion - - #region Type-safe IEnumerable - - public override IAppenderCollectionEnumerator GetEnumerator() - { - return m_collection.GetEnumerator(); - } - - #endregion - - #region Public Helpers - - // (just to mimic some nice features of ArrayList) - public override int Capacity - { - get { return m_collection.Capacity; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int AddRange(AppenderCollection x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override int AddRange(IAppender[] x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override IAppender[] ToArray() - { - return m_collection.ToArray(); - } - - public override void TrimToSize() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - #endregion - } - - #endregion - } - + { + /// + /// Supports type-safe iteration over a . + /// + /// + public interface IAppenderCollectionEnumerator + { + /// + /// Gets the current element in the collection. + /// + IAppender Current { get; } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + bool MoveNext(); + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + void Reset(); + } + + private const int DEFAULT_CAPACITY = 16; + private IAppender[] m_array; + private int m_count = 0; + private int m_version = 0; + + /// + /// Creates a read-only wrapper for a AppenderCollection instance. + /// + /// list to create a readonly wrapper arround. + /// + /// An AppenderCollection wrapper that is read-only. + /// + public static AppenderCollection ReadOnly(AppenderCollection list) + { + if (list == null) + { + throw new ArgumentNullException("list"); + } + + return new ReadOnlyAppenderCollection(list); + } + + /// + /// An empty readonly static AppenderCollection. + /// + public static readonly AppenderCollection EmptyCollection = ReadOnly(new AppenderCollection(0)); + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the AppenderCollection class + /// that is empty and has the default initial capacity. + /// + public AppenderCollection() + { + this.m_array = new IAppender[DEFAULT_CAPACITY]; + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the AppenderCollection class + /// that has the specified initial capacity. + /// + /// + /// The number of elements that the new AppenderCollection is initially capable of storing. + /// + public AppenderCollection(int capacity) + { + this.m_array = new IAppender[capacity]; + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the AppenderCollection class + /// that contains elements copied from the specified AppenderCollection. + /// + /// The AppenderCollection whose elements are copied to the new collection. + public AppenderCollection(AppenderCollection c) + { + this.m_array = new IAppender[c.Count]; + this.AddRange(c); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the AppenderCollection class + /// that contains elements copied from the specified array. + /// + /// The array whose elements are copied to the new list. + public AppenderCollection(IAppender[] a) + { + this.m_array = new IAppender[a.Length]; + this.AddRange(a); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the AppenderCollection class + /// that contains elements copied from the specified collection. + /// + /// The collection whose elements are copied to the new list. + public AppenderCollection(ICollection col) + { + this.m_array = new IAppender[col.Count]; + this.AddRange(col); + } + + /// + /// Type visible only to our subclasses + /// Used to access protected constructor. + /// + /// + internal protected enum Tag + { + /// + /// A value + /// + Default, + } + + /// + /// Initializes a new instance of the class. + /// Allow subclasses to avoid our default constructors. + /// + /// + /// + internal protected AppenderCollection(Tag tag) + { + this.m_array = null; + } + + /// + /// Gets the number of elements actually contained in the AppenderCollection. + /// + public virtual int Count + { + get { return this.m_count; } + } + + /// + /// Copies the entire AppenderCollection to a one-dimensional + /// array. + /// + /// The one-dimensional array to copy to. + public virtual void CopyTo(IAppender[] array) + { + this.CopyTo(array, 0); + } + + /// + /// Copies the entire AppenderCollection to a one-dimensional + /// array, starting at the specified index of the target array. + /// + /// The one-dimensional array to copy to. + /// The zero-based index in at which copying begins. + public virtual void CopyTo(IAppender[] array, int start) + { + if (this.m_count > array.GetUpperBound(0) + 1 - start) + { + throw new System.ArgumentException("Destination array was not long enough."); + } + + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + /// + /// Gets a value indicating whether access to the collection is synchronized (thread-safe). + /// + /// false, because the backing type is an array, which is never thread-safe. + public virtual bool IsSynchronized + { + get { return false; } + } + + /// + /// Gets an object that can be used to synchronize access to the collection. + /// + public virtual object SyncRoot + { + get { return this.m_array; } + } + + /// + /// Gets or sets the at the specified index. + /// + /// The zero-based index of the element to get or set. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual IAppender this[int index] + { + get + { + this.ValidateIndex(index); // throws + return this.m_array[index]; + } + + set + { + this.ValidateIndex(index); // throws + ++this.m_version; + this.m_array[index] = value; + } + } + + /// + /// Adds a to the end of the AppenderCollection. + /// + /// The to be added to the end of the AppenderCollection. + /// The index at which the value has been added. + public virtual int Add(IAppender item) + { + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + this.m_array[this.m_count] = item; + this.m_version++; + + return this.m_count++; + } + + /// + /// Removes all elements from the AppenderCollection. + /// + public virtual void Clear() + { + ++this.m_version; + this.m_array = new IAppender[DEFAULT_CAPACITY]; + this.m_count = 0; + } + + /// + /// Creates a shallow copy of the . + /// + /// A new with a shallow copy of the collection data. + public virtual object Clone() + { + AppenderCollection newCol = new AppenderCollection(this.m_count); + Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); + newCol.m_count = this.m_count; + newCol.m_version = this.m_version; + + return newCol; + } + + /// + /// Determines whether a given is in the AppenderCollection. + /// + /// The to check for. + /// true if is found in the AppenderCollection; otherwise, false. + public virtual bool Contains(IAppender item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return true; + } + } + + return false; + } + + /// + /// Returns the zero-based index of the first occurrence of a + /// in the AppenderCollection. + /// + /// The to locate in the AppenderCollection. + /// + /// The zero-based index of the first occurrence of + /// in the entire AppenderCollection, if found; otherwise, -1. + /// + public virtual int IndexOf(IAppender item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return i; + } + } + + return -1; + } + + /// + /// Inserts an element into the AppenderCollection at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The to insert. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual void Insert(int index, IAppender item) + { + this.ValidateIndex(index, true); // throws + + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + if (index < this.m_count) + { + Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); + } + + this.m_array[index] = item; + this.m_count++; + this.m_version++; + } + + /// + /// Removes the first occurrence of a specific from the AppenderCollection. + /// + /// The to remove from the AppenderCollection. + /// + /// The specified was not found in the AppenderCollection. + /// + public virtual void Remove(IAppender item) + { + int i = this.IndexOf(item); + if (i < 0) + { + throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); + } + + ++this.m_version; + this.RemoveAt(i); + } + + /// + /// Removes the element at the specified index of the AppenderCollection. + /// + /// The zero-based index of the element to remove. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual void RemoveAt(int index) + { + this.ValidateIndex(index); // throws + + this.m_count--; + + if (index < this.m_count) + { + Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); + } + + // We can't set the deleted entry equal to null, because it might be a value type. + // Instead, we'll create an empty single-element array of the right type and copy it + // over the entry we want to erase. + IAppender[] temp = new IAppender[1]; + Array.Copy(temp, 0, this.m_array, this.m_count, 1); + this.m_version++; + } + + /// + /// Gets a value indicating whether the collection has a fixed size. + /// + /// true if the collection has a fixed size; otherwise, false. The default is false. + public virtual bool IsFixedSize + { + get { return false; } + } + + /// + /// Gets a value indicating whether the IList is read-only. + /// + /// true if the collection is read-only; otherwise, false. The default is false. + public virtual bool IsReadOnly + { + get { return false; } + } + + /// + /// Returns an enumerator that can iterate through the AppenderCollection. + /// + /// An for the entire AppenderCollection. + public virtual IAppenderCollectionEnumerator GetEnumerator() + { + return new Enumerator(this); + } + + /// + /// Gets or sets the number of elements the AppenderCollection can contain. + /// + public virtual int Capacity + { + get + { + return this.m_array.Length; + } + + set + { + if (value < this.m_count) + { + value = this.m_count; + } + + if (value != this.m_array.Length) + { + if (value > 0) + { + IAppender[] temp = new IAppender[value]; + Array.Copy(this.m_array, 0, temp, 0, this.m_count); + this.m_array = temp; + } + else + { + this.m_array = new IAppender[DEFAULT_CAPACITY]; + } + } + } + } + + /// + /// Adds the elements of another AppenderCollection to the current AppenderCollection. + /// + /// The AppenderCollection whose elements should be added to the end of the current AppenderCollection. + /// The new of the AppenderCollection. + public virtual int AddRange(AppenderCollection x) + { + if (this.m_count + x.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Count); + } + + Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); + this.m_count += x.Count; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a array to the current AppenderCollection. + /// + /// The array whose elements should be added to the end of the AppenderCollection. + /// The new of the AppenderCollection. + public virtual int AddRange(IAppender[] x) + { + if (this.m_count + x.Length >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Length); + } + + Array.Copy(x, 0, this.m_array, this.m_count, x.Length); + this.m_count += x.Length; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a collection to the current AppenderCollection. + /// + /// The collection whose elements should be added to the end of the AppenderCollection. + /// The new of the AppenderCollection. + public virtual int AddRange(ICollection col) + { + if (this.m_count + col.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + col.Count); + } + + foreach (object item in col) + { + this.Add((IAppender)item); + } + + return this.m_count; + } + + /// + /// Sets the capacity to the actual number of elements. + /// + public virtual void TrimToSize() + { + this.Capacity = this.m_count; + } + + /// + /// Return the collection elements as an array. + /// + /// the array. + public virtual IAppender[] ToArray() + { + IAppender[] resultArray = new IAppender[this.m_count]; + if (this.m_count > 0) + { + Array.Copy(this.m_array, 0, resultArray, 0, this.m_count); + } + + return resultArray; + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i) + { + this.ValidateIndex(i, false); + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i, bool allowEqualEnd) + { + int max = allowEqualEnd ? this.m_count : (this.m_count - 1); + if (i < 0 || i > max) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); + } + } + + private void EnsureCapacity(int min) + { + int newCapacity = (this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2; + if (newCapacity < min) + { + newCapacity = min; + } + + this.Capacity = newCapacity; + } + + void ICollection.CopyTo(Array array, int start) + { + if (this.m_count > 0) + { + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + } + + object IList.this[int i] + { + get { return (object)this[i]; } + set { this[i] = (IAppender)value; } + } + + int IList.Add(object x) + { + return this.Add((IAppender)x); + } + + bool IList.Contains(object x) + { + return this.Contains((IAppender)x); + } + + int IList.IndexOf(object x) + { + return this.IndexOf((IAppender)x); + } + + void IList.Insert(int pos, object x) + { + this.Insert(pos, (IAppender)x); + } + + void IList.Remove(object x) + { + this.Remove((IAppender)x); + } + + void IList.RemoveAt(int pos) + { + this.RemoveAt(pos); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (IEnumerator)this.GetEnumerator(); + } + + /// + /// Supports simple iteration over a . + /// + /// + private sealed class Enumerator : IEnumerator, IAppenderCollectionEnumerator + { + private readonly AppenderCollection m_collection; + private int m_index; + private int m_version; + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the Enumerator class. + /// + /// + internal Enumerator(AppenderCollection tc) + { + this.m_collection = tc; + this.m_index = -1; + this.m_version = tc.m_version; + } + + /// + /// Gets the current element in the collection. + /// + public IAppender Current + { + get { return this.m_collection[this.m_index]; } + } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + public bool MoveNext() + { + if (this.m_version != this.m_collection.m_version) + { + throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); + } + + ++this.m_index; + return this.m_index < this.m_collection.Count; + } + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + public void Reset() + { + this.m_index = -1; + } + + object IEnumerator.Current + { + get { return this.Current; } + } + } + + /// + private sealed class ReadOnlyAppenderCollection : AppenderCollection, ICollection + { + private readonly AppenderCollection m_collection; + + internal ReadOnlyAppenderCollection(AppenderCollection list) + : base(Tag.Default) + { + this.m_collection = list; + } + + public override void CopyTo(IAppender[] array) + { + this.m_collection.CopyTo(array); + } + + public override void CopyTo(IAppender[] array, int start) + { + this.m_collection.CopyTo(array, start); + } + + void ICollection.CopyTo(Array array, int start) + { + ((ICollection)this.m_collection).CopyTo(array, start); + } + + public override int Count + { + get { return this.m_collection.Count; } + } + + public override bool IsSynchronized + { + get { return this.m_collection.IsSynchronized; } + } + + public override object SyncRoot + { + get { return this.m_collection.SyncRoot; } + } + + public override IAppender this[int i] + { + get { return this.m_collection[i]; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int Add(IAppender x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Clear() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool Contains(IAppender x) + { + return this.m_collection.Contains(x); + } + + public override int IndexOf(IAppender x) + { + return this.m_collection.IndexOf(x); + } + + public override void Insert(int pos, IAppender x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Remove(IAppender x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void RemoveAt(int pos) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool IsFixedSize + { + get { return true; } + } + + public override bool IsReadOnly + { + get { return true; } + } + + public override IAppenderCollectionEnumerator GetEnumerator() + { + return this.m_collection.GetEnumerator(); + } + + // (just to mimic some nice features of ArrayList) + public override int Capacity + { + get { return this.m_collection.Capacity; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int AddRange(AppenderCollection x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override int AddRange(IAppender[] x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override IAppender[] ToArray() + { + return this.m_collection.ToArray(); + } + + public override void TrimToSize() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs index 91ad80d3a4f..1dde3bb4374 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs @@ -1,330 +1,311 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; -using System.Collections; - -using log4net.Filter; -using log4net.Util; -using log4net.Layout; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Abstract base class implementation of . - /// - /// - /// - /// This class provides the code for common functionality, such - /// as support for threshold filtering and support for general filters. - /// - /// - /// Appenders can also implement the interface. Therefore - /// they would require that the method - /// be called after the appenders properties have been configured. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public abstract class AppenderSkeleton : IAppender, IBulkAppender, IOptionHandler, IFlushable - { - #region Protected Instance Constructors - - /// - /// Default constructor - /// - /// - /// Empty default constructor - /// - protected AppenderSkeleton() - { - m_errorHandler = new OnlyOnceErrorHandler(this.GetType().Name); - } - - #endregion Protected Instance Constructors - - #region Finalizer - - /// - /// Finalizes this appender by calling the implementation's - /// method. - /// - /// - /// - /// If this appender has not been closed then the Finalize method - /// will call . - /// - /// - ~AppenderSkeleton() - { - // An appender might be closed then garbage collected. - // There is no point in closing twice. - if (!m_closed) - { - LogLog.Debug(declaringType, "Finalizing appender named ["+m_name+"]."); - Close(); - } - } - - #endregion Finalizer - - #region Public Instance Properties - - /// - /// Gets or sets the threshold of this appender. - /// - /// - /// The threshold of the appender. - /// - /// - /// - /// All log events with lower level than the threshold level are ignored - /// by the appender. - /// - /// - /// In configuration files this option is specified by setting the - /// value of the option to a level - /// string, such as "DEBUG", "INFO" and so on. - /// - /// - public Level Threshold - { - get { return m_threshold; } - set { m_threshold = value; } - } - - /// - /// Gets or sets the for this appender. - /// - /// The of the appender - /// - /// - /// The provides a default - /// implementation for the property. - /// - /// - virtual public IErrorHandler ErrorHandler - { - get { return this.m_errorHandler; } - set - { - lock(this) - { - if (value == null) - { - // We do not throw exception here since the cause is probably a - // bad config file. - LogLog.Warn(declaringType, "You have tried to set a null error-handler."); - } - else - { - m_errorHandler = value; - } - } - } - } - - /// - /// The filter chain. - /// - /// The head of the filter chain filter chain. - /// - /// - /// Returns the head Filter. The Filters are organized in a linked list - /// and so all Filters on this Appender are available through the result. - /// - /// - virtual public IFilter FilterHead - { - get { return m_headFilter; } - } - - /// - /// Gets or sets the for this appender. - /// - /// The layout of the appender. - /// - /// - /// See for more information. - /// - /// - /// - virtual public ILayout Layout - { - get { return m_layout; } - set { m_layout = value; } - } - - #endregion - - #region Implementation of IOptionHandler - - /// - /// Initialize the appender based on the options set - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - virtual public void ActivateOptions() - { - } - - #endregion Implementation of IOptionHandler - - #region Implementation of IAppender - - /// - /// Gets or sets the name of this appender. - /// - /// The name of the appender. - /// - /// - /// The name uniquely identifies the appender. - /// - /// - public string Name - { - get { return m_name; } - set { m_name = value; } - } - - /// - /// Closes the appender and release resources. - /// - /// - /// - /// Release any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - /// This method cannot be overridden by subclasses. This method - /// delegates the closing of the appender to the - /// method which must be overridden in the subclass. - /// - /// - public void Close() - { - // This lock prevents the appender being closed while it is still appending - lock(this) - { - if (!m_closed) - { - OnClose(); - m_closed = true; - } - } - } - - /// - /// Performs threshold checks and invokes filters before - /// delegating actual logging to the subclasses specific - /// method. - /// - /// The event to log. - /// - /// - /// This method cannot be overridden by derived classes. A - /// derived class should override the method - /// which is called by this method. - /// - /// - /// The implementation of this method is as follows: - /// - /// - /// - /// - /// - /// Checks that the severity of the - /// is greater than or equal to the of this - /// appender. - /// - /// - /// - /// Checks that the chain accepts the - /// . - /// - /// - /// - /// - /// Calls and checks that - /// it returns true. - /// - /// - /// - /// - /// If all of the above steps succeed then the - /// will be passed to the abstract method. - /// - /// - public void DoAppend(LoggingEvent loggingEvent) - { - // This lock is absolutely critical for correct formatting - // of the message in a multi-threaded environment. Without - // this, the message may be broken up into elements from - // multiple thread contexts (like get the wrong thread ID). - - lock(this) - { - if (m_closed) - { - ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"]."); - return; - } - - // prevent re-entry - if (m_recursiveGuard) - { - return; - } - - try - { - m_recursiveGuard = true; - - if (FilterEvent(loggingEvent) && PreAppendCheck()) - { - this.Append(loggingEvent); - } - } - catch(Exception ex) - { - ErrorHandler.Error("Failed in DoAppend", ex); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + + using log4net.Core; + using log4net.Filter; + using log4net.Layout; + using log4net.Util; + + /// + /// Abstract base class implementation of . + /// + /// + /// + /// This class provides the code for common functionality, such + /// as support for threshold filtering and support for general filters. + /// + /// + /// Appenders can also implement the interface. Therefore + /// they would require that the method + /// be called after the appenders properties have been configured. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class AppenderSkeleton : IAppender, IBulkAppender, IOptionHandler, IFlushable + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// Empty default constructor. + /// + protected AppenderSkeleton() + { + this.m_errorHandler = new OnlyOnceErrorHandler(this.GetType().Name); + } + + /// + /// Finalizes an instance of the class. + /// Finalizes this appender by calling the implementation's + /// method. + /// + /// + /// + /// If this appender has not been closed then the Finalize method + /// will call . + /// + /// + ~AppenderSkeleton() + { + // An appender might be closed then garbage collected. + // There is no point in closing twice. + if (!this.m_closed) + { + LogLog.Debug(declaringType, "Finalizing appender named [" + this.m_name + "]."); + this.Close(); + } + } + + /// + /// Gets or sets the threshold of this appender. + /// + /// + /// The threshold of the appender. + /// + /// + /// + /// All log events with lower level than the threshold level are ignored + /// by the appender. + /// + /// + /// In configuration files this option is specified by setting the + /// value of the option to a level + /// string, such as "DEBUG", "INFO" and so on. + /// + /// + public Level Threshold + { + get { return this.m_threshold; } + set { this.m_threshold = value; } + } + + /// + /// Gets or sets the for this appender. + /// + /// The of the appender. + /// + /// + /// The provides a default + /// implementation for the property. + /// + /// + public virtual IErrorHandler ErrorHandler + { + get { return this.m_errorHandler; } + + set + { + lock (this) + { + if (value == null) + { + // We do not throw exception here since the cause is probably a + // bad config file. + LogLog.Warn(declaringType, "You have tried to set a null error-handler."); + } + else + { + this.m_errorHandler = value; + } + } + } + } + + /// + /// Gets the filter chain. + /// + /// The head of the filter chain filter chain. + /// + /// + /// Returns the head Filter. The Filters are organized in a linked list + /// and so all Filters on this Appender are available through the result. + /// + /// + public virtual IFilter FilterHead + { + get { return this.m_headFilter; } + } + + /// + /// Gets or sets the for this appender. + /// + /// The layout of the appender. + /// + /// + /// See for more information. + /// + /// + /// + public virtual ILayout Layout + { + get { return this.m_layout; } + set { this.m_layout = value; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public virtual void ActivateOptions() + { + } + + /// + /// Gets or sets the name of this appender. + /// + /// The name of the appender. + /// + /// + /// The name uniquely identifies the appender. + /// + /// + public string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + /// + /// Closes the appender and release resources. + /// + /// + /// + /// Release any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + /// This method cannot be overridden by subclasses. This method + /// delegates the closing of the appender to the + /// method which must be overridden in the subclass. + /// + /// + public void Close() + { + // This lock prevents the appender being closed while it is still appending + lock (this) + { + if (!this.m_closed) + { + this.OnClose(); + this.m_closed = true; + } + } + } + + /// + /// Performs threshold checks and invokes filters before + /// delegating actual logging to the subclasses specific + /// method. + /// + /// The event to log. + /// + /// + /// This method cannot be overridden by derived classes. A + /// derived class should override the method + /// which is called by this method. + /// + /// + /// The implementation of this method is as follows: + /// + /// + /// + /// + /// + /// Checks that the severity of the + /// is greater than or equal to the of this + /// appender. + /// + /// + /// + /// Checks that the chain accepts the + /// . + /// + /// + /// + /// + /// Calls and checks that + /// it returns true. + /// + /// + /// + /// + /// If all of the above steps succeed then the + /// will be passed to the abstract method. + /// + /// + public void DoAppend(LoggingEvent loggingEvent) + { + // This lock is absolutely critical for correct formatting + // of the message in a multi-threaded environment. Without + // this, the message may be broken up into elements from + // multiple thread contexts (like get the wrong thread ID). + lock (this) + { + if (this.m_closed) + { + this.ErrorHandler.Error("Attempted to append to closed appender named [" + this.m_name + "]."); + return; + } + + // prevent re-entry + if (this.m_recursiveGuard) + { + return; + } + + try + { + this.m_recursiveGuard = true; + + if (this.FilterEvent(loggingEvent) && this.PreAppendCheck()) + { + this.Append(loggingEvent); + } + } + catch (Exception ex) + { + this.ErrorHandler.Error("Failed in DoAppend", ex); + } #if !MONO && !NET_2_0 && !NETSTANDARD1_3 // on .NET 2.0 (and higher) and Mono (all profiles), // exceptions that do not derive from System.Exception will be @@ -336,102 +317,97 @@ public void DoAppend(LoggingEvent loggingEvent) ErrorHandler.Error("Failed in DoAppend (unknown exception)"); } #endif - finally - { - m_recursiveGuard = false; - } - } - } - - #endregion Implementation of IAppender - - #region Implementation of IBulkAppender - - /// - /// Performs threshold checks and invokes filters before - /// delegating actual logging to the subclasses specific - /// method. - /// - /// The array of events to log. - /// - /// - /// This method cannot be overridden by derived classes. A - /// derived class should override the method - /// which is called by this method. - /// - /// - /// The implementation of this method is as follows: - /// - /// - /// - /// - /// - /// Checks that the severity of the - /// is greater than or equal to the of this - /// appender. - /// - /// - /// - /// Checks that the chain accepts the - /// . - /// - /// - /// - /// - /// Calls and checks that - /// it returns true. - /// - /// - /// - /// - /// If all of the above steps succeed then the - /// will be passed to the method. - /// - /// - public void DoAppend(LoggingEvent[] loggingEvents) - { - // This lock is absolutely critical for correct formatting - // of the message in a multi-threaded environment. Without - // this, the message may be broken up into elements from - // multiple thread contexts (like get the wrong thread ID). - - lock(this) - { - if (m_closed) - { - ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"]."); - return; - } - - // prevent re-entry - if (m_recursiveGuard) - { - return; - } - - try - { - m_recursiveGuard = true; - - ArrayList filteredEvents = new ArrayList(loggingEvents.Length); - - foreach(LoggingEvent loggingEvent in loggingEvents) - { - if (FilterEvent(loggingEvent)) - { - filteredEvents.Add(loggingEvent); - } - } - - if (filteredEvents.Count > 0 && PreAppendCheck()) - { - this.Append((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); - } - } - catch(Exception ex) - { - ErrorHandler.Error("Failed in Bulk DoAppend", ex); - } + finally + { + this.m_recursiveGuard = false; + } + } + } + + /// + /// Performs threshold checks and invokes filters before + /// delegating actual logging to the subclasses specific + /// method. + /// + /// The array of events to log. + /// + /// + /// This method cannot be overridden by derived classes. A + /// derived class should override the method + /// which is called by this method. + /// + /// + /// The implementation of this method is as follows: + /// + /// + /// + /// + /// + /// Checks that the severity of the + /// is greater than or equal to the of this + /// appender. + /// + /// + /// + /// Checks that the chain accepts the + /// . + /// + /// + /// + /// + /// Calls and checks that + /// it returns true. + /// + /// + /// + /// + /// If all of the above steps succeed then the + /// will be passed to the method. + /// + /// + public void DoAppend(LoggingEvent[] loggingEvents) + { + // This lock is absolutely critical for correct formatting + // of the message in a multi-threaded environment. Without + // this, the message may be broken up into elements from + // multiple thread contexts (like get the wrong thread ID). + lock (this) + { + if (this.m_closed) + { + this.ErrorHandler.Error("Attempted to append to closed appender named [" + this.m_name + "]."); + return; + } + + // prevent re-entry + if (this.m_recursiveGuard) + { + return; + } + + try + { + this.m_recursiveGuard = true; + + ArrayList filteredEvents = new ArrayList(loggingEvents.Length); + + foreach (LoggingEvent loggingEvent in loggingEvents) + { + if (this.FilterEvent(loggingEvent)) + { + filteredEvents.Add(loggingEvent); + } + } + + if (filteredEvents.Count > 0 && this.PreAppendCheck()) + { + this.Append((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); + } + } + catch (Exception ex) + { + this.ErrorHandler.Error("Failed in Bulk DoAppend", ex); + } #if !MONO && !NET_2_0 && !NETSTANDARD1_3 // on .NET 2.0 (and higher) and Mono (all profiles), // exceptions that do not derive from System.Exception will be @@ -443,471 +419,449 @@ public void DoAppend(LoggingEvent[] loggingEvents) ErrorHandler.Error("Failed in Bulk DoAppend (unknown exception)"); } #endif - finally - { - m_recursiveGuard = false; - } - } - } - - #endregion Implementation of IBulkAppender - - /// - /// Test if the logging event should we output by this appender - /// - /// the event to test - /// true if the event should be output, false if the event should be ignored - /// - /// - /// This method checks the logging event against the threshold level set - /// on this appender and also against the filters specified on this - /// appender. - /// - /// - /// The implementation of this method is as follows: - /// - /// - /// - /// - /// - /// Checks that the severity of the - /// is greater than or equal to the of this - /// appender. - /// - /// - /// - /// Checks that the chain accepts the - /// . - /// - /// - /// - /// - /// - virtual protected bool FilterEvent(LoggingEvent loggingEvent) - { - if (!IsAsSevereAsThreshold(loggingEvent.Level)) - { - return false; - } - - IFilter f = this.FilterHead; - - while(f != null) - { - switch(f.Decide(loggingEvent)) - { - case FilterDecision.Deny: - return false; // Return without appending + finally + { + this.m_recursiveGuard = false; + } + } + } + + /// + /// Test if the logging event should we output by this appender. + /// + /// the event to test. + /// true if the event should be output, false if the event should be ignored. + /// + /// + /// This method checks the logging event against the threshold level set + /// on this appender and also against the filters specified on this + /// appender. + /// + /// + /// The implementation of this method is as follows: + /// + /// + /// + /// + /// + /// Checks that the severity of the + /// is greater than or equal to the of this + /// appender. + /// + /// + /// + /// Checks that the chain accepts the + /// . + /// + /// + /// + /// + /// + protected virtual bool FilterEvent(LoggingEvent loggingEvent) + { + if (!this.IsAsSevereAsThreshold(loggingEvent.Level)) + { + return false; + } - case FilterDecision.Accept: - f = null; // Break out of the loop - break; + IFilter f = this.FilterHead; - case FilterDecision.Neutral: - f = f.Next; // Move to next filter - break; - } - } - - return true; - } - - #region Public Instance Methods - - /// - /// Adds a filter to the end of the filter chain. - /// - /// the filter to add to this appender - /// - /// - /// The Filters are organized in a linked list. - /// - /// - /// Setting this property causes the new filter to be pushed onto the - /// back of the filter chain. - /// - /// - virtual public void AddFilter(IFilter filter) - { - if (filter == null) - { - throw new ArgumentNullException("filter param must not be null"); - } - - if (m_headFilter == null) - { - m_headFilter = m_tailFilter = filter; - } - else - { - m_tailFilter.Next = filter; - m_tailFilter = filter; - } - } - - /// - /// Clears the filter list for this appender. - /// - /// - /// - /// Clears the filter list for this appender. - /// - /// - virtual public void ClearFilters() - { - m_headFilter = m_tailFilter = null; - } - - #endregion Public Instance Methods - - #region Protected Instance Methods - - /// - /// Checks if the message level is below this appender's threshold. - /// - /// to test against. - /// - /// - /// If there is no threshold set, then the return value is always true. - /// - /// - /// - /// true if the meets the - /// requirements of this appender. - /// - virtual protected bool IsAsSevereAsThreshold(Level level) - { - return ((m_threshold == null) || level >= m_threshold); - } - - /// - /// Is called when the appender is closed. Derived classes should override - /// this method if resources need to be released. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - virtual protected void OnClose() - { - // Do nothing by default - } - - /// - /// Subclasses of should implement this method - /// to perform actual logging. - /// - /// The event to append. - /// - /// - /// A subclass must implement this method to perform - /// logging of the . - /// - /// This method will be called by - /// if all the conditions listed for that method are met. - /// - /// - /// To restrict the logging of events in the appender - /// override the method. - /// - /// - abstract protected void Append(LoggingEvent loggingEvent); - - /// - /// Append a bulk array of logging events. - /// - /// the array of logging events - /// - /// - /// This base class implementation calls the - /// method for each element in the bulk array. - /// - /// - /// A sub class that can better process a bulk array of events should - /// override this method in addition to . - /// - /// - virtual protected void Append(LoggingEvent[] loggingEvents) - { - foreach(LoggingEvent loggingEvent in loggingEvents) - { - Append(loggingEvent); - } - } - - /// - /// Called before as a precondition. - /// - /// - /// - /// This method is called by - /// before the call to the abstract method. - /// - /// - /// This method can be overridden in a subclass to extend the checks - /// made before the event is passed to the method. - /// - /// - /// A subclass should ensure that they delegate this call to - /// this base class if it is overridden. - /// - /// - /// true if the call to should proceed. - virtual protected bool PreAppendCheck() - { - if ((m_layout == null) && RequiresLayout) - { - ErrorHandler.Error("AppenderSkeleton: No layout set for the appender named ["+m_name+"]."); - return false; - } - - return true; - } - - /// - /// Renders the to a string. - /// - /// The event to render. - /// The event rendered as a string. - /// - /// - /// Helper method to render a to - /// a string. This appender must have a - /// set to render the to - /// a string. - /// - /// If there is exception data in the logging event and - /// the layout does not process the exception, this method - /// will append the exception text to the rendered string. - /// - /// - /// Where possible use the alternative version of this method - /// . - /// That method streams the rendering onto an existing Writer - /// which can give better performance if the caller already has - /// a open and ready for writing. - /// - /// - protected string RenderLoggingEvent(LoggingEvent loggingEvent) - { - // Create the render writer on first use - if (m_renderWriter == null) - { - m_renderWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); - } - - lock (m_renderWriter) + while (f != null) + { + switch (f.Decide(loggingEvent)) + { + case FilterDecision.Deny: + return false; // Return without appending + + case FilterDecision.Accept: + f = null; // Break out of the loop + break; + + case FilterDecision.Neutral: + f = f.Next; // Move to next filter + break; + } + } + + return true; + } + + /// + /// Adds a filter to the end of the filter chain. + /// + /// the filter to add to this appender. + /// + /// + /// The Filters are organized in a linked list. + /// + /// + /// Setting this property causes the new filter to be pushed onto the + /// back of the filter chain. + /// + /// + public virtual void AddFilter(IFilter filter) + { + if (filter == null) + { + throw new ArgumentNullException("filter param must not be null"); + } + + if (this.m_headFilter == null) + { + this.m_headFilter = this.m_tailFilter = filter; + } + else + { + this.m_tailFilter.Next = filter; + this.m_tailFilter = filter; + } + } + + /// + /// Clears the filter list for this appender. + /// + /// + /// + /// Clears the filter list for this appender. + /// + /// + public virtual void ClearFilters() + { + this.m_headFilter = this.m_tailFilter = null; + } + + /// + /// Checks if the message level is below this appender's threshold. + /// + /// to test against. + /// + /// + /// If there is no threshold set, then the return value is always true. + /// + /// + /// + /// true if the meets the + /// requirements of this appender. + /// + protected virtual bool IsAsSevereAsThreshold(Level level) + { + return (this.m_threshold == null) || level >= this.m_threshold; + } + + /// + /// Is called when the appender is closed. Derived classes should override + /// this method if resources need to be released. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + protected virtual void OnClose() + { + // Do nothing by default + } + + /// + /// Subclasses of should implement this method + /// to perform actual logging. + /// + /// The event to append. + /// + /// + /// A subclass must implement this method to perform + /// logging of the . + /// + /// This method will be called by + /// if all the conditions listed for that method are met. + /// + /// + /// To restrict the logging of events in the appender + /// override the method. + /// + /// + protected abstract void Append(LoggingEvent loggingEvent); + + /// + /// Append a bulk array of logging events. + /// + /// the array of logging events. + /// + /// + /// This base class implementation calls the + /// method for each element in the bulk array. + /// + /// + /// A sub class that can better process a bulk array of events should + /// override this method in addition to . + /// + /// + protected virtual void Append(LoggingEvent[] loggingEvents) + { + foreach (LoggingEvent loggingEvent in loggingEvents) + { + this.Append(loggingEvent); + } + } + + /// + /// Called before as a precondition. + /// + /// + /// + /// This method is called by + /// before the call to the abstract method. + /// + /// + /// This method can be overridden in a subclass to extend the checks + /// made before the event is passed to the method. + /// + /// + /// A subclass should ensure that they delegate this call to + /// this base class if it is overridden. + /// + /// + /// true if the call to should proceed. + protected virtual bool PreAppendCheck() + { + if ((this.m_layout == null) && this.RequiresLayout) + { + this.ErrorHandler.Error("AppenderSkeleton: No layout set for the appender named [" + this.m_name + "]."); + return false; + } + + return true; + } + + /// + /// Renders the to a string. + /// + /// The event to render. + /// The event rendered as a string. + /// + /// + /// Helper method to render a to + /// a string. This appender must have a + /// set to render the to + /// a string. + /// + /// If there is exception data in the logging event and + /// the layout does not process the exception, this method + /// will append the exception text to the rendered string. + /// + /// + /// Where possible use the alternative version of this method + /// . + /// That method streams the rendering onto an existing Writer + /// which can give better performance if the caller already has + /// a open and ready for writing. + /// + /// + protected string RenderLoggingEvent(LoggingEvent loggingEvent) + { + // Create the render writer on first use + if (this.m_renderWriter == null) + { + this.m_renderWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); + } + + lock (this.m_renderWriter) { // Reset the writer so we can reuse it - m_renderWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); + this.m_renderWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); - RenderLoggingEvent(m_renderWriter, loggingEvent); - return m_renderWriter.ToString(); + this.RenderLoggingEvent(this.m_renderWriter, loggingEvent); + return this.m_renderWriter.ToString(); } - } - - /// - /// Renders the to a string. - /// - /// The event to render. - /// The TextWriter to write the formatted event to - /// - /// - /// Helper method to render a to - /// a string. This appender must have a - /// set to render the to - /// a string. - /// - /// If there is exception data in the logging event and - /// the layout does not process the exception, this method - /// will append the exception text to the rendered string. - /// - /// - /// Use this method in preference to - /// where possible. If, however, the caller needs to render the event - /// to a string then does - /// provide an efficient mechanism for doing so. - /// - /// - protected void RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent) - { - if (m_layout == null) - { - throw new InvalidOperationException("A layout must be set"); - } - - if (m_layout.IgnoresException) - { - string exceptionStr = loggingEvent.GetExceptionString(); - if (exceptionStr != null && exceptionStr.Length > 0) - { - // render the event and the exception - m_layout.Format(writer, loggingEvent); - writer.WriteLine(exceptionStr); - } - else - { - // there is no exception to render - m_layout.Format(writer, loggingEvent); - } - } - else - { - // The layout will render the exception - m_layout.Format(writer, loggingEvent); - } - } - - /// - /// Tests if this appender requires a to be set. - /// - /// - /// - /// In the rather exceptional case, where the appender - /// implementation admits a layout but can also work without it, - /// then the appender should return true. - /// - /// - /// This default implementation always returns false. - /// - /// - /// - /// true if the appender requires a layout object, otherwise false. - /// - virtual protected bool RequiresLayout - { - get { return false; } - } - - #endregion - - /// - /// Flushes any buffered log data. - /// - /// - /// This implementation doesn't flush anything and always returns true - /// - /// True if all logging events were flushed successfully, else false. - public virtual bool Flush(int millisecondsTimeout) - { - return true; - } - - #region Private Instance Fields - - /// - /// The layout of this appender. - /// - /// - /// See for more information. - /// - private ILayout m_layout; - - /// - /// The name of this appender. - /// - /// - /// See for more information. - /// - private string m_name; - - /// - /// The level threshold of this appender. - /// - /// - /// - /// There is no level threshold filtering by default. - /// - /// - /// See for more information. - /// - /// - private Level m_threshold; - - /// - /// It is assumed and enforced that errorHandler is never null. - /// - /// - /// - /// It is assumed and enforced that errorHandler is never null. - /// - /// - /// See for more information. - /// - /// - private IErrorHandler m_errorHandler; - - /// - /// The first filter in the filter chain. - /// - /// - /// - /// Set to null initially. - /// - /// - /// See for more information. - /// - /// - private IFilter m_headFilter; - - /// - /// The last filter in the filter chain. - /// - /// - /// See for more information. - /// - private IFilter m_tailFilter; - - /// - /// Flag indicating if this appender is closed. - /// - /// - /// See for more information. - /// - private bool m_closed = false; - - /// - /// The guard prevents an appender from repeatedly calling its own DoAppend method - /// - private bool m_recursiveGuard = false; - - /// - /// StringWriter used to render events - /// - private ReusableStringWriter m_renderWriter = null; - - #endregion Private Instance Fields - - #region Constants - - /// - /// Initial buffer size - /// - private const int c_renderBufferSize = 256; - - /// - /// Maximum buffer size before it is recycled - /// - private const int c_renderBufferMaxCapacity = 1024; - - #endregion - - #region Private Static Fields - - /// - /// The fully qualified type of the AppenderSkeleton class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(AppenderSkeleton); - - #endregion Private Static Fields - } + } + + /// + /// Renders the to a string. + /// + /// The event to render. + /// The TextWriter to write the formatted event to. + /// + /// + /// Helper method to render a to + /// a string. This appender must have a + /// set to render the to + /// a string. + /// + /// If there is exception data in the logging event and + /// the layout does not process the exception, this method + /// will append the exception text to the rendered string. + /// + /// + /// Use this method in preference to + /// where possible. If, however, the caller needs to render the event + /// to a string then does + /// provide an efficient mechanism for doing so. + /// + /// + protected void RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent) + { + if (this.m_layout == null) + { + throw new InvalidOperationException("A layout must be set"); + } + + if (this.m_layout.IgnoresException) + { + string exceptionStr = loggingEvent.GetExceptionString(); + if (exceptionStr != null && exceptionStr.Length > 0) + { + // render the event and the exception + this.m_layout.Format(writer, loggingEvent); + writer.WriteLine(exceptionStr); + } + else + { + // there is no exception to render + this.m_layout.Format(writer, loggingEvent); + } + } + else + { + // The layout will render the exception + this.m_layout.Format(writer, loggingEvent); + } + } + + /// + /// Gets a value indicating whether tests if this appender requires a to be set. + /// + /// + /// + /// In the rather exceptional case, where the appender + /// implementation admits a layout but can also work without it, + /// then the appender should return true. + /// + /// + /// This default implementation always returns false. + /// + /// + /// + /// true if the appender requires a layout object, otherwise false. + /// + protected virtual bool RequiresLayout + { + get { return false; } + } + + /// + /// Flushes any buffered log data. + /// + /// + /// This implementation doesn't flush anything and always returns true. + /// + /// True if all logging events were flushed successfully, else false. + public virtual bool Flush(int millisecondsTimeout) + { + return true; + } + + /// + /// The layout of this appender. + /// + /// + /// See for more information. + /// + private ILayout m_layout; + + /// + /// The name of this appender. + /// + /// + /// See for more information. + /// + private string m_name; + + /// + /// The level threshold of this appender. + /// + /// + /// + /// There is no level threshold filtering by default. + /// + /// + /// See for more information. + /// + /// + private Level m_threshold; + + /// + /// It is assumed and enforced that errorHandler is never null. + /// + /// + /// + /// It is assumed and enforced that errorHandler is never null. + /// + /// + /// See for more information. + /// + /// + private IErrorHandler m_errorHandler; + + /// + /// The first filter in the filter chain. + /// + /// + /// + /// Set to null initially. + /// + /// + /// See for more information. + /// + /// + private IFilter m_headFilter; + + /// + /// The last filter in the filter chain. + /// + /// + /// See for more information. + /// + private IFilter m_tailFilter; + + /// + /// Flag indicating if this appender is closed. + /// + /// + /// See for more information. + /// + private bool m_closed = false; + + /// + /// The guard prevents an appender from repeatedly calling its own DoAppend method. + /// + private bool m_recursiveGuard = false; + + /// + /// StringWriter used to render events. + /// + private ReusableStringWriter m_renderWriter = null; + + /// + /// Initial buffer size. + /// + private const int c_renderBufferSize = 256; + + /// + /// Maximum buffer size before it is recycled. + /// + private const int c_renderBufferMaxCapacity = 1024; + + /// + /// The fully qualified type of the AppenderSkeleton class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(AppenderSkeleton); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs index 51cc241ccf9..580c2aeda71 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,141 +18,124 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET #if !NETCF && !SSCLI && !CLIENT_PROFILE using System.Web; - -using log4net.Layout; + using log4net.Core; +using log4net.Layout; -namespace log4net.Appender +namespace log4net.Appender { - /// - /// - /// Appends log events to the ASP.NET system. - /// - /// - /// - /// - /// Diagnostic information and tracing messages that you specify are appended to the output - /// of the page that is sent to the requesting browser. Optionally, you can view this information - /// from a separate trace viewer (Trace.axd) that displays trace information for every page in a - /// given application. - /// - /// - /// Trace statements are processed and displayed only when tracing is enabled. You can control - /// whether tracing is displayed to a page, to the trace viewer, or both. - /// - /// - /// The logging event is passed to the or - /// method depending on the level of the logging event. - /// The event's logger name is the default value for the category parameter of the Write/Warn method. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Ron Grabowski - public class AspNetTraceAppender : AppenderSkeleton - { - #region Public Instances Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public AspNetTraceAppender() - { - } - - #endregion // Public Instances Constructors - - #region Override implementation of AppenderSkeleton - - /// - /// Write the logging event to the ASP.NET trace - /// - /// the event to log - /// - /// - /// Write the logging event to the ASP.NET trace - /// HttpContext.Current.Trace - /// (). - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - // check if log4net is running in the context of an ASP.NET application - if (HttpContext.Current != null) - { - // check if tracing is enabled for the current context - if (HttpContext.Current.Trace.IsEnabled) - { - if (loggingEvent.Level >= Level.Warn) - { - HttpContext.Current.Trace.Warn(m_category.Format(loggingEvent), RenderLoggingEvent(loggingEvent)); - } - else - { - HttpContext.Current.Trace.Write(m_category.Format(loggingEvent), RenderLoggingEvent(loggingEvent)); - } - } - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion // Override implementation of AppenderSkeleton - - #region Public Instance Properties + /// + /// + /// Appends log events to the ASP.NET system. + /// + /// + /// + /// + /// Diagnostic information and tracing messages that you specify are appended to the output + /// of the page that is sent to the requesting browser. Optionally, you can view this information + /// from a separate trace viewer (Trace.axd) that displays trace information for every page in a + /// given application. + /// + /// + /// Trace statements are processed and displayed only when tracing is enabled. You can control + /// whether tracing is displayed to a page, to the trace viewer, or both. + /// + /// + /// The logging event is passed to the or + /// method depending on the level of the logging event. + /// The event's logger name is the default value for the category parameter of the Write/Warn method. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Ron Grabowski. + public class AspNetTraceAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public AspNetTraceAppender() + { + } + + /// + /// Write the logging event to the ASP.NET trace. + /// + /// the event to log. + /// + /// + /// Write the logging event to the ASP.NET trace + /// HttpContext.Current.Trace + /// (). + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // check if log4net is running in the context of an ASP.NET application + if (HttpContext.Current != null) + { + // check if tracing is enabled for the current context + if (HttpContext.Current.Trace.IsEnabled) + { + if (loggingEvent.Level >= Level.Warn) + { + HttpContext.Current.Trace.Warn(this.m_category.Format(loggingEvent), this.RenderLoggingEvent(loggingEvent)); + } + else + { + HttpContext.Current.Trace.Write(this.m_category.Format(loggingEvent), this.RenderLoggingEvent(loggingEvent)); + } + } + } + } /// - /// The category parameter sent to the Trace method. + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Gets or sets the category parameter sent to the Trace method. /// /// /// - /// Defaults to %logger which will use the logger name of the current + /// Defaults to %logger which will use the logger name of the current /// as the category parameter. /// /// - /// + /// /// public PatternLayout Category { - get { return m_category; } - set { m_category = value; } - } - - #endregion - - #region Private Instance Fields - - /// - /// Defaults to %logger - /// - private PatternLayout m_category = new PatternLayout("%logger"); - - #endregion - } + get { return this.m_category; } + set { this.m_category = value; } + } + + /// + /// Defaults to %logger. + /// + private PatternLayout m_category = new PatternLayout("%logger"); + } } #endif // !NETCF && !SSCLI diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs index 649524af960..76afac1f929 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs @@ -1,270 +1,260 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Util; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Abstract base class implementation of that - /// buffers events in a fixed size buffer. - /// - /// - /// - /// This base class should be used by appenders that need to buffer a - /// number of events before logging them. For example the - /// buffers events and then submits the entire contents of the buffer to - /// the underlying database in one go. - /// - /// - /// Subclasses should override the - /// method to deliver the buffered events. - /// - /// The BufferingAppenderSkeleton maintains a fixed size cyclic - /// buffer of events. The size of the buffer is set using - /// the property. - /// - /// A is used to inspect - /// each event as it arrives in the appender. If the - /// triggers, then the current buffer is sent immediately - /// (see ). Otherwise the event - /// is stored in the buffer. For example, an evaluator can be used to - /// deliver the events immediately when an ERROR event arrives. - /// - /// - /// The buffering appender can be configured in a mode. - /// By default the appender is NOT lossy. When the buffer is full all - /// the buffered events are sent with . - /// If the property is set to true then the - /// buffer will not be sent when it is full, and new events arriving - /// in the appender will overwrite the oldest event in the buffer. - /// In lossy mode the buffer will only be sent when the - /// triggers. This can be useful behavior when you need to know about - /// ERROR events but not about events with a lower level, configure an - /// evaluator that will trigger when an ERROR event arrives, the whole - /// buffer will be sent which gives a history of events leading up to - /// the ERROR event. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Core; + using log4net.Util; + + /// + /// Abstract base class implementation of that + /// buffers events in a fixed size buffer. + /// + /// + /// + /// This base class should be used by appenders that need to buffer a + /// number of events before logging them. For example the + /// buffers events and then submits the entire contents of the buffer to + /// the underlying database in one go. + /// + /// + /// Subclasses should override the + /// method to deliver the buffered events. + /// + /// The BufferingAppenderSkeleton maintains a fixed size cyclic + /// buffer of events. The size of the buffer is set using + /// the property. + /// + /// A is used to inspect + /// each event as it arrives in the appender. If the + /// triggers, then the current buffer is sent immediately + /// (see ). Otherwise the event + /// is stored in the buffer. For example, an evaluator can be used to + /// deliver the events immediately when an ERROR event arrives. + /// + /// + /// The buffering appender can be configured in a mode. + /// By default the appender is NOT lossy. When the buffer is full all + /// the buffered events are sent with . + /// If the property is set to true then the + /// buffer will not be sent when it is full, and new events arriving + /// in the appender will overwrite the oldest event in the buffer. + /// In lossy mode the buffer will only be sent when the + /// triggers. This can be useful behavior when you need to know about + /// ERROR events but not about events with a lower level, configure an + /// evaluator that will trigger when an ERROR event arrives, the whole + /// buffer will be sent which gives a history of events leading up to + /// the ERROR event. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. public abstract class BufferingAppenderSkeleton : AppenderSkeleton - { - #region Protected Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Protected default constructor to allow subclassing. - /// - /// - protected BufferingAppenderSkeleton() : this(true) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// the events passed through this appender must be - /// fixed by the time that they arrive in the derived class' SendBuffer method. - /// - /// - /// Protected constructor to allow subclassing. - /// - /// - /// The should be set if the subclass - /// expects the events delivered to be fixed even if the - /// is set to zero, i.e. when no buffering occurs. - /// - /// - protected BufferingAppenderSkeleton(bool eventMustBeFixed) : base() - { - m_eventMustBeFixed = eventMustBeFixed; - } - - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets a value that indicates whether the appender is lossy. - /// - /// - /// true if the appender is lossy, otherwise false. The default is false. - /// - /// - /// - /// This appender uses a buffer to store logging events before - /// delivering them. A triggering event causes the whole buffer - /// to be send to the remote sink. If the buffer overruns before - /// a triggering event then logging events could be lost. Set - /// to false to prevent logging events - /// from being lost. - /// - /// If is set to true then an - /// must be specified. - /// - public bool Lossy - { - get { return m_lossy; } - set { m_lossy = value; } - } - - /// - /// Gets or sets the size of the cyclic buffer used to hold the - /// logging events. - /// - /// - /// The size of the cyclic buffer used to hold the logging events. - /// - /// - /// - /// The option takes a positive integer - /// representing the maximum number of logging events to collect in - /// a cyclic buffer. When the is reached, - /// oldest events are deleted as new events are added to the - /// buffer. By default the size of the cyclic buffer is 512 events. - /// - /// - /// If the is set to a value less than - /// or equal to 1 then no buffering will occur. The logging event - /// will be delivered synchronously (depending on the - /// and properties). Otherwise the event will - /// be buffered. - /// - /// - public int BufferSize - { - get { return m_bufferSize; } - set { m_bufferSize = value; } - } - - /// - /// Gets or sets the that causes the - /// buffer to be sent immediately. - /// - /// - /// The that causes the buffer to be - /// sent immediately. - /// - /// - /// - /// The evaluator will be called for each event that is appended to this - /// appender. If the evaluator triggers then the current buffer will - /// immediately be sent (see ). - /// - /// If is set to true then an - /// must be specified. - /// - public ITriggeringEventEvaluator Evaluator - { - get { return m_evaluator; } - set { m_evaluator = value; } - } + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Protected default constructor to allow subclassing. + /// + /// + protected BufferingAppenderSkeleton() + : this(true) + { + } - /// - /// Gets or sets the value of the to use. - /// - /// - /// The value of the to use. - /// - /// - /// - /// The evaluator will be called for each event that is discarded from this - /// appender. If the evaluator triggers then the current buffer will immediately - /// be sent (see ). - /// - /// - public ITriggeringEventEvaluator LossyEvaluator - { - get { return m_lossyEvaluator; } - set { m_lossyEvaluator = value; } - } + /// + /// Initializes a new instance of the class. + /// + /// the events passed through this appender must be + /// fixed by the time that they arrive in the derived class' SendBuffer method. + /// + /// + /// Protected constructor to allow subclassing. + /// + /// + /// The should be set if the subclass + /// expects the events delivered to be fixed even if the + /// is set to zero, i.e. when no buffering occurs. + /// + /// + protected BufferingAppenderSkeleton(bool eventMustBeFixed) + : base() + { + this.m_eventMustBeFixed = eventMustBeFixed; + } + + /// + /// Gets or sets a value indicating whether gets or sets a value that indicates whether the appender is lossy. + /// + /// + /// true if the appender is lossy, otherwise false. The default is false. + /// + /// + /// + /// This appender uses a buffer to store logging events before + /// delivering them. A triggering event causes the whole buffer + /// to be send to the remote sink. If the buffer overruns before + /// a triggering event then logging events could be lost. Set + /// to false to prevent logging events + /// from being lost. + /// + /// If is set to true then an + /// must be specified. + /// + public bool Lossy + { + get { return this.m_lossy; } + set { this.m_lossy = value; } + } - /// - /// Gets or sets a value indicating if only part of the logging event data - /// should be fixed. - /// - /// - /// true if the appender should only fix part of the logging event - /// data, otherwise false. The default is false. - /// - /// - /// - /// Setting this property to true will cause only part of the - /// event data to be fixed and serialized. This will improve performance. - /// - /// - /// See for more information. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - virtual public bool OnlyFixPartialEventData - { - get { return (Fix == FixFlags.Partial); } - set - { - if (value) - { - Fix = FixFlags.Partial; - } - else - { - Fix = FixFlags.All; - } - } - } + /// + /// Gets or sets the size of the cyclic buffer used to hold the + /// logging events. + /// + /// + /// The size of the cyclic buffer used to hold the logging events. + /// + /// + /// + /// The option takes a positive integer + /// representing the maximum number of logging events to collect in + /// a cyclic buffer. When the is reached, + /// oldest events are deleted as new events are added to the + /// buffer. By default the size of the cyclic buffer is 512 events. + /// + /// + /// If the is set to a value less than + /// or equal to 1 then no buffering will occur. The logging event + /// will be delivered synchronously (depending on the + /// and properties). Otherwise the event will + /// be buffered. + /// + /// + public int BufferSize + { + get { return this.m_bufferSize; } + set { this.m_bufferSize = value; } + } - /// - /// Gets or sets a the fields that will be fixed in the event - /// - /// - /// The event fields that will be fixed before the event is buffered - /// - /// - /// - /// The logging event needs to have certain thread specific values - /// captured before it can be buffered. See - /// for details. - /// - /// - /// - virtual public FixFlags Fix - { - get { return m_fixFlags; } - set { m_fixFlags = value; } - } + /// + /// Gets or sets the that causes the + /// buffer to be sent immediately. + /// + /// + /// The that causes the buffer to be + /// sent immediately. + /// + /// + /// + /// The evaluator will be called for each event that is appended to this + /// appender. If the evaluator triggers then the current buffer will + /// immediately be sent (see ). + /// + /// If is set to true then an + /// must be specified. + /// + public ITriggeringEventEvaluator Evaluator + { + get { return this.m_evaluator; } + set { this.m_evaluator = value; } + } - #endregion Public Instance Properties + /// + /// Gets or sets the value of the to use. + /// + /// + /// The value of the to use. + /// + /// + /// + /// The evaluator will be called for each event that is discarded from this + /// appender. If the evaluator triggers then the current buffer will immediately + /// be sent (see ). + /// + /// + public ITriggeringEventEvaluator LossyEvaluator + { + get { return this.m_lossyEvaluator; } + set { this.m_lossyEvaluator = value; } + } - #region Public Methods + /// + /// Gets or sets a value indicating whether gets or sets a value indicating if only part of the logging event data + /// should be fixed. + /// + /// + /// true if the appender should only fix part of the logging event + /// data, otherwise false. The default is false. + /// + /// + /// + /// Setting this property to true will cause only part of the + /// event data to be fixed and serialized. This will improve performance. + /// + /// + /// See for more information. + /// + /// + [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] + public virtual bool OnlyFixPartialEventData + { + get { return this.Fix == FixFlags.Partial; } + + set + { + if (value) + { + this.Fix = FixFlags.Partial; + } + else + { + this.Fix = FixFlags.All; + } + } + } + /// + /// Gets or sets a the fields that will be fixed in the event. + /// + /// + /// The event fields that will be fixed before the event is buffered. + /// + /// + /// + /// The logging event needs to have certain thread specific values + /// captured before it can be buffered. See + /// for details. + /// + /// + /// + public virtual FixFlags Fix + { + get { return this.m_fixFlags; } + set { this.m_fixFlags = value; } + } + /// /// Flushes any buffered log data. /// @@ -272,391 +262,369 @@ virtual public FixFlags Fix /// True if all logging events were flushed successfully, else false. public override bool Flush(int millisecondsTimeout) { - Flush(); + this.Flush(); return true; } - /// - /// Flush the currently buffered events - /// - /// - /// - /// Flushes any events that have been buffered. - /// - /// - /// If the appender is buffering in mode then the contents - /// of the buffer will NOT be flushed to the appender. - /// - /// - public virtual void Flush() - { - Flush(false); - } - - /// - /// Flush the currently buffered events - /// - /// set to true to flush the buffer of lossy events - /// - /// - /// Flushes events that have been buffered. If is - /// false then events will only be flushed if this buffer is non-lossy mode. - /// - /// - /// If the appender is buffering in mode then the contents - /// of the buffer will only be flushed if is true. - /// In this case the contents of the buffer will be tested against the - /// and if triggering will be output. All other buffered - /// events will be discarded. - /// - /// - /// If is true then the buffer will always - /// be emptied by calling this method. - /// - /// - public virtual void Flush(bool flushLossyBuffer) - { - // This method will be called outside of the AppenderSkeleton DoAppend() method - // therefore it needs to be protected by its own lock. This will block any - // Appends while the buffer is flushed. - lock(this) - { - if (m_cb != null && m_cb.Length > 0) - { - if (m_lossy) - { - // If we are allowed to eagerly flush from the lossy buffer - if (flushLossyBuffer) - { - if (m_lossyEvaluator != null) - { - // Test the contents of the buffer against the lossy evaluator - LoggingEvent[] bufferedEvents = m_cb.PopAll(); - ArrayList filteredEvents = new ArrayList(bufferedEvents.Length); - - foreach(LoggingEvent loggingEvent in bufferedEvents) - { - if (m_lossyEvaluator.IsTriggeringEvent(loggingEvent)) - { - filteredEvents.Add(loggingEvent); - } - } - - // Send the events that meet the lossy evaluator criteria - if (filteredEvents.Count > 0) - { - SendBuffer((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); - } - } - else - { - // No lossy evaluator, all buffered events are discarded - m_cb.Clear(); - } - } - } - else - { - // Not lossy, send whole buffer - SendFromBuffer(null, m_cb); - } - } - } - } - - #endregion Public Methods - - #region Implementation of IOptionHandler - - /// - /// Initialize the appender based on the options set - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { - base.ActivateOptions(); - - // If the appender is in Lossy mode then we will - // only send the buffer when the Evaluator triggers - // therefore check we have an evaluator. - if (m_lossy && m_evaluator == null) - { - ErrorHandler.Error("Appender ["+Name+"] is Lossy but has no Evaluator. The buffer will never be sent!"); - } - - if (m_bufferSize > 1) - { - m_cb = new CyclicBuffer(m_bufferSize); - } - else - { - m_cb = null; - } - } - - #endregion Implementation of IOptionHandler - - #region Override implementation of AppenderSkeleton - - /// - /// Close this appender instance. - /// - /// - /// - /// Close this appender instance. If this appender is marked - /// as not then the remaining events in - /// the buffer must be sent when the appender is closed. - /// - /// - override protected void OnClose() - { - // Flush the buffer on close - Flush(true); - } - - /// - /// This method is called by the method. - /// - /// the event to log - /// - /// - /// Stores the in the cyclic buffer. - /// - /// - /// The buffer will be sent (i.e. passed to the - /// method) if one of the following conditions is met: - /// - /// - /// - /// The cyclic buffer is full and this appender is - /// marked as not lossy (see ) - /// - /// - /// An is set and - /// it is triggered for the - /// specified. - /// - /// - /// - /// Before the event is stored in the buffer it is fixed - /// (see ) to ensure that - /// any data referenced by the event will be valid when the buffer - /// is processed. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - // If the buffer size is set to 1 or less then the buffer will be - // sent immediately because there is not enough space in the buffer - // to buffer up more than 1 event. Therefore as a special case - // we don't use the buffer at all. - if (m_cb == null || m_bufferSize <= 1) - { - // Only send the event if we are in non lossy mode or the event is a triggering event - if ((!m_lossy) || - (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) || - (m_lossyEvaluator != null && m_lossyEvaluator.IsTriggeringEvent(loggingEvent))) - { - if (m_eventMustBeFixed) - { - // Derive class expects fixed events - loggingEvent.Fix = this.Fix; - } - - // Not buffering events, send immediately - SendBuffer(new LoggingEvent[] { loggingEvent } ); - } - } - else - { - // Because we are caching the LoggingEvent beyond the - // lifetime of the Append() method we must fix any - // volatile data in the event. - loggingEvent.Fix = this.Fix; - - // Add to the buffer, returns the event discarded from the buffer if there is no space remaining after the append - LoggingEvent discardedLoggingEvent = m_cb.Append(loggingEvent); - - if (discardedLoggingEvent != null) - { - // Buffer is full and has had to discard an event - if (!m_lossy) - { - // Not lossy, must send all events - SendFromBuffer(discardedLoggingEvent, m_cb); - } - else - { - // Check if the discarded event should not be logged - if (m_lossyEvaluator == null || !m_lossyEvaluator.IsTriggeringEvent(discardedLoggingEvent)) - { - // Clear the discarded event as we should not forward it - discardedLoggingEvent = null; - } - - // Check if the event should trigger the whole buffer to be sent - if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) - { - SendFromBuffer(discardedLoggingEvent, m_cb); - } - else if (discardedLoggingEvent != null) - { - // Just send the discarded event - SendBuffer(new LoggingEvent[] { discardedLoggingEvent } ); - } - } - } - else - { - // Buffer is not yet full - - // Check if the event should trigger the whole buffer to be sent - if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) - { - SendFromBuffer(null, m_cb); - } - } - } - } - - #endregion Override implementation of AppenderSkeleton - - #region Protected Instance Methods - - /// - /// Sends the contents of the buffer. - /// - /// The first logging event. - /// The buffer containing the events that need to be send. - /// - /// - /// The subclass must override . - /// - /// - virtual protected void SendFromBuffer(LoggingEvent firstLoggingEvent, CyclicBuffer buffer) - { - LoggingEvent[] bufferEvents = buffer.PopAll(); - - if (firstLoggingEvent == null) - { - SendBuffer(bufferEvents); - } - else if (bufferEvents.Length == 0) - { - SendBuffer(new LoggingEvent[] { firstLoggingEvent } ); - } - else - { - // Create new array with the firstLoggingEvent at the head - LoggingEvent[] events = new LoggingEvent[bufferEvents.Length + 1]; - Array.Copy(bufferEvents, 0, events, 1, bufferEvents.Length); - events[0] = firstLoggingEvent; - - SendBuffer(events); - } - } - - #endregion Protected Instance Methods - - /// - /// Sends the events. - /// - /// The events that need to be send. - /// - /// - /// The subclass must override this method to process the buffered events. - /// - /// - abstract protected void SendBuffer(LoggingEvent[] events); - - #region Private Static Fields - - /// - /// The default buffer size. - /// - /// - /// The default size of the cyclic buffer used to store events. - /// This is set to 512 by default. - /// - private const int DEFAULT_BUFFER_SIZE = 512; - - #endregion Private Static Fields - - #region Private Instance Fields + /// + /// Flush the currently buffered events. + /// + /// + /// + /// Flushes any events that have been buffered. + /// + /// + /// If the appender is buffering in mode then the contents + /// of the buffer will NOT be flushed to the appender. + /// + /// + public virtual void Flush() + { + this.Flush(false); + } - /// - /// The size of the cyclic buffer used to hold the logging events. - /// - /// - /// Set to by default. - /// - private int m_bufferSize = DEFAULT_BUFFER_SIZE; + /// + /// Flush the currently buffered events. + /// + /// set to true to flush the buffer of lossy events. + /// + /// + /// Flushes events that have been buffered. If is + /// false then events will only be flushed if this buffer is non-lossy mode. + /// + /// + /// If the appender is buffering in mode then the contents + /// of the buffer will only be flushed if is true. + /// In this case the contents of the buffer will be tested against the + /// and if triggering will be output. All other buffered + /// events will be discarded. + /// + /// + /// If is true then the buffer will always + /// be emptied by calling this method. + /// + /// + public virtual void Flush(bool flushLossyBuffer) + { + // This method will be called outside of the AppenderSkeleton DoAppend() method + // therefore it needs to be protected by its own lock. This will block any + // Appends while the buffer is flushed. + lock (this) + { + if (this.m_cb != null && this.m_cb.Length > 0) + { + if (this.m_lossy) + { + // If we are allowed to eagerly flush from the lossy buffer + if (flushLossyBuffer) + { + if (this.m_lossyEvaluator != null) + { + // Test the contents of the buffer against the lossy evaluator + LoggingEvent[] bufferedEvents = this.m_cb.PopAll(); + ArrayList filteredEvents = new ArrayList(bufferedEvents.Length); + + foreach (LoggingEvent loggingEvent in bufferedEvents) + { + if (this.m_lossyEvaluator.IsTriggeringEvent(loggingEvent)) + { + filteredEvents.Add(loggingEvent); + } + } + + // Send the events that meet the lossy evaluator criteria + if (filteredEvents.Count > 0) + { + this.SendBuffer((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); + } + } + else + { + // No lossy evaluator, all buffered events are discarded + this.m_cb.Clear(); + } + } + } + else + { + // Not lossy, send whole buffer + this.SendFromBuffer(null, this.m_cb); + } + } + } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + // If the appender is in Lossy mode then we will + // only send the buffer when the Evaluator triggers + // therefore check we have an evaluator. + if (this.m_lossy && this.m_evaluator == null) + { + this.ErrorHandler.Error("Appender [" + this.Name + "] is Lossy but has no Evaluator. The buffer will never be sent!"); + } + + if (this.m_bufferSize > 1) + { + this.m_cb = new CyclicBuffer(this.m_bufferSize); + } + else + { + this.m_cb = null; + } + } + + /// + /// Close this appender instance. + /// + /// + /// + /// Close this appender instance. If this appender is marked + /// as not then the remaining events in + /// the buffer must be sent when the appender is closed. + /// + /// + protected override void OnClose() + { + // Flush the buffer on close + this.Flush(true); + } - /// - /// The cyclic buffer used to store the logging events. - /// - private CyclicBuffer m_cb; + /// + /// This method is called by the method. + /// + /// the event to log. + /// + /// + /// Stores the in the cyclic buffer. + /// + /// + /// The buffer will be sent (i.e. passed to the + /// method) if one of the following conditions is met: + /// + /// + /// + /// The cyclic buffer is full and this appender is + /// marked as not lossy (see ) + /// + /// + /// An is set and + /// it is triggered for the + /// specified. + /// + /// + /// + /// Before the event is stored in the buffer it is fixed + /// (see ) to ensure that + /// any data referenced by the event will be valid when the buffer + /// is processed. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // If the buffer size is set to 1 or less then the buffer will be + // sent immediately because there is not enough space in the buffer + // to buffer up more than 1 event. Therefore as a special case + // we don't use the buffer at all. + if (this.m_cb == null || this.m_bufferSize <= 1) + { + // Only send the event if we are in non lossy mode or the event is a triggering event + if ((!this.m_lossy) || + (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) || + (this.m_lossyEvaluator != null && this.m_lossyEvaluator.IsTriggeringEvent(loggingEvent))) + { + if (this.m_eventMustBeFixed) + { + // Derive class expects fixed events + loggingEvent.Fix = this.Fix; + } + + // Not buffering events, send immediately + this.SendBuffer(new LoggingEvent[] { loggingEvent }); + } + } + else + { + // Because we are caching the LoggingEvent beyond the + // lifetime of the Append() method we must fix any + // volatile data in the event. + loggingEvent.Fix = this.Fix; + + // Add to the buffer, returns the event discarded from the buffer if there is no space remaining after the append + LoggingEvent discardedLoggingEvent = this.m_cb.Append(loggingEvent); + + if (discardedLoggingEvent != null) + { + // Buffer is full and has had to discard an event + if (!this.m_lossy) + { + // Not lossy, must send all events + this.SendFromBuffer(discardedLoggingEvent, this.m_cb); + } + else + { + // Check if the discarded event should not be logged + if (this.m_lossyEvaluator == null || !this.m_lossyEvaluator.IsTriggeringEvent(discardedLoggingEvent)) + { + // Clear the discarded event as we should not forward it + discardedLoggingEvent = null; + } + + // Check if the event should trigger the whole buffer to be sent + if (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) + { + this.SendFromBuffer(discardedLoggingEvent, this.m_cb); + } + else if (discardedLoggingEvent != null) + { + // Just send the discarded event + this.SendBuffer(new LoggingEvent[] { discardedLoggingEvent }); + } + } + } + else + { + // Buffer is not yet full + + // Check if the event should trigger the whole buffer to be sent + if (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) + { + this.SendFromBuffer(null, this.m_cb); + } + } + } + } + + /// + /// Sends the contents of the buffer. + /// + /// The first logging event. + /// The buffer containing the events that need to be send. + /// + /// + /// The subclass must override . + /// + /// + protected virtual void SendFromBuffer(LoggingEvent firstLoggingEvent, CyclicBuffer buffer) + { + LoggingEvent[] bufferEvents = buffer.PopAll(); + + if (firstLoggingEvent == null) + { + this.SendBuffer(bufferEvents); + } + else if (bufferEvents.Length == 0) + { + this.SendBuffer(new LoggingEvent[] { firstLoggingEvent }); + } + else + { + // Create new array with the firstLoggingEvent at the head + LoggingEvent[] events = new LoggingEvent[bufferEvents.Length + 1]; + Array.Copy(bufferEvents, 0, events, 1, bufferEvents.Length); + events[0] = firstLoggingEvent; + + this.SendBuffer(events); + } + } + + /// + /// Sends the events. + /// + /// The events that need to be send. + /// + /// + /// The subclass must override this method to process the buffered events. + /// + /// + protected abstract void SendBuffer(LoggingEvent[] events); + + /// + /// The default buffer size. + /// + /// + /// The default size of the cyclic buffer used to store events. + /// This is set to 512 by default. + /// + private const int DEFAULT_BUFFER_SIZE = 512; + + /// + /// The size of the cyclic buffer used to hold the logging events. + /// + /// + /// Set to by default. + /// + private int m_bufferSize = DEFAULT_BUFFER_SIZE; - /// - /// The triggering event evaluator that causes the buffer to be sent immediately. - /// - /// - /// The object that is used to determine if an event causes the entire - /// buffer to be sent immediately. This field can be null, which - /// indicates that event triggering is not to be done. The evaluator - /// can be set using the property. If this appender - /// has the ( property) set to - /// true then an must be set. - /// - private ITriggeringEventEvaluator m_evaluator; + /// + /// The cyclic buffer used to store the logging events. + /// + private CyclicBuffer m_cb; - /// - /// Indicates if the appender should overwrite events in the cyclic buffer - /// when it becomes full, or if the buffer should be flushed when the - /// buffer is full. - /// - /// - /// If this field is set to true then an must - /// be set. - /// - private bool m_lossy = false; + /// + /// The triggering event evaluator that causes the buffer to be sent immediately. + /// + /// + /// The object that is used to determine if an event causes the entire + /// buffer to be sent immediately. This field can be null, which + /// indicates that event triggering is not to be done. The evaluator + /// can be set using the property. If this appender + /// has the ( property) set to + /// true then an must be set. + /// + private ITriggeringEventEvaluator m_evaluator; - /// - /// The triggering event evaluator filters discarded events. - /// - /// - /// The object that is used to determine if an event that is discarded should - /// really be discarded or if it should be sent to the appenders. - /// This field can be null, which indicates that all discarded events will - /// be discarded. - /// - private ITriggeringEventEvaluator m_lossyEvaluator; + /// + /// Indicates if the appender should overwrite events in the cyclic buffer + /// when it becomes full, or if the buffer should be flushed when the + /// buffer is full. + /// + /// + /// If this field is set to true then an must + /// be set. + /// + private bool m_lossy = false; - /// - /// Value indicating which fields in the event should be fixed - /// - /// - /// By default all fields are fixed - /// - private FixFlags m_fixFlags = FixFlags.All; + /// + /// The triggering event evaluator filters discarded events. + /// + /// + /// The object that is used to determine if an event that is discarded should + /// really be discarded or if it should be sent to the appenders. + /// This field can be null, which indicates that all discarded events will + /// be discarded. + /// + private ITriggeringEventEvaluator m_lossyEvaluator; - /// - /// The events delivered to the subclass must be fixed. - /// - private readonly bool m_eventMustBeFixed; + /// + /// Value indicating which fields in the event should be fixed. + /// + /// + /// By default all fields are fixed. + /// + private FixFlags m_fixFlags = FixFlags.All; - #endregion Private Instance Fields - } + /// + /// The events delivered to the subclass must be fixed. + /// + private readonly bool m_eventMustBeFixed; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs index 4d4aee6684c..bb36b55e45b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs @@ -1,278 +1,259 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Util; -using log4net.Layout; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Buffers events and then forwards them to attached appenders. - /// - /// - /// - /// The events are buffered in this appender until conditions are - /// met to allow the appender to deliver the events to the attached - /// appenders. See for the - /// conditions that cause the buffer to be sent. - /// - /// The forwarding appender can be used to specify different - /// thresholds and filters for the same appender at different locations - /// within the hierarchy. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class BufferingForwardingAppender : BufferingAppenderSkeleton, IAppenderAttachable - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public BufferingForwardingAppender() - { - } - - #endregion Public Instance Constructors - - #region Override implementation of AppenderSkeleton - - /// - /// Closes the appender and releases resources. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - override protected void OnClose() - { - // Remove all the attached appenders - lock(this) - { - // Delegate to base, which will flush buffers - base.OnClose(); - - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.RemoveAllAppenders(); - } - } - } - - #endregion Override implementation of AppenderSkeleton - - #region Override implementation of BufferingAppenderSkeleton - - /// - /// Send the events. - /// - /// The events that need to be send. - /// - /// - /// Forwards the events to the attached appenders. - /// - /// - override protected void SendBuffer(LoggingEvent[] events) - { - // Pass the logging event on to the attached appenders - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.AppendLoopOnAppenders(events); - } - } - - #endregion Override implementation of BufferingAppenderSkeleton - - #region Implementation of IAppenderAttachable - - /// - /// Adds an to the list of appenders of this - /// instance. - /// - /// The to add to this appender. - /// - /// - /// If the specified is already in the list of - /// appenders, then it won't be added again. - /// - /// - virtual public void AddAppender(IAppender newAppender) - { - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } - lock(this) - { - if (m_appenderAttachedImpl == null) - { - m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); - } - m_appenderAttachedImpl.AddAppender(newAppender); - } - } - - /// - /// Gets the appenders contained in this appender as an - /// . - /// - /// - /// If no appenders can be found, then an - /// is returned. - /// - /// - /// A collection of the appenders in this appender. - /// - virtual public AppenderCollection Appenders - { - get - { - lock(this) - { - if (m_appenderAttachedImpl == null) - { - return AppenderCollection.EmptyCollection; - } - else - { - return m_appenderAttachedImpl.Appenders; - } - } - } - } - - /// - /// Looks for the appender with the specified name. - /// - /// The name of the appender to lookup. - /// - /// The appender with the specified name, or null. - /// - /// - /// - /// Get the named appender attached to this buffering appender. - /// - /// - virtual public IAppender GetAppender(string name) - { - lock(this) - { - if (m_appenderAttachedImpl == null || name == null) - { - return null; - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// Buffers events and then forwards them to attached appenders. + /// + /// + /// + /// The events are buffered in this appender until conditions are + /// met to allow the appender to deliver the events to the attached + /// appenders. See for the + /// conditions that cause the buffer to be sent. + /// + /// The forwarding appender can be used to specify different + /// thresholds and filters for the same appender at different locations + /// within the hierarchy. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class BufferingForwardingAppender : BufferingAppenderSkeleton, IAppenderAttachable + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public BufferingForwardingAppender() + { + } + + /// + /// Closes the appender and releases resources. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + protected override void OnClose() + { + // Remove all the attached appenders + lock (this) + { + // Delegate to base, which will flush buffers + base.OnClose(); - return m_appenderAttachedImpl.GetAppender(name); - } - } + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + } + } + } + + /// + /// Send the events. + /// + /// The events that need to be send. + /// + /// + /// Forwards the events to the attached appenders. + /// + /// + protected override void SendBuffer(LoggingEvent[] events) + { + // Pass the logging event on to the attached appenders + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.AppendLoopOnAppenders(events); + } + } + + /// + /// Adds an to the list of appenders of this + /// instance. + /// + /// The to add to this appender. + /// + /// + /// If the specified is already in the list of + /// appenders, then it won't be added again. + /// + /// + public virtual void AddAppender(IAppender newAppender) + { + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } + + lock (this) + { + if (this.m_appenderAttachedImpl == null) + { + this.m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); + } + + this.m_appenderAttachedImpl.AddAppender(newAppender); + } + } - /// - /// Removes all previously added appenders from this appender. - /// - /// - /// - /// This is useful when re-reading configuration information. - /// - /// - virtual public void RemoveAllAppenders() - { - lock(this) - { - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.RemoveAllAppenders(); - m_appenderAttachedImpl = null; - } - } - } + /// + /// Gets the appenders contained in this appender as an + /// . + /// + /// + /// If no appenders can be found, then an + /// is returned. + /// + /// + /// A collection of the appenders in this appender. + /// + public virtual AppenderCollection Appenders + { + get + { + lock (this) + { + if (this.m_appenderAttachedImpl == null) + { + return AppenderCollection.EmptyCollection; + } + else + { + return this.m_appenderAttachedImpl.Appenders; + } + } + } + } - /// - /// Removes the specified appender from the list of appenders. - /// - /// The appender to remove. - /// The appender removed from the list - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - virtual public IAppender RemoveAppender(IAppender appender) - { - lock(this) - { - if (appender != null && m_appenderAttachedImpl != null) - { - return m_appenderAttachedImpl.RemoveAppender(appender); - } - } - return null; - } + /// + /// Looks for the appender with the specified name. + /// + /// The name of the appender to lookup. + /// + /// The appender with the specified name, or null. + /// + /// + /// + /// Get the named appender attached to this buffering appender. + /// + /// + public virtual IAppender GetAppender(string name) + { + lock (this) + { + if (this.m_appenderAttachedImpl == null || name == null) + { + return null; + } - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - virtual public IAppender RemoveAppender(string name) - { - lock(this) - { - if (name != null && m_appenderAttachedImpl != null) - { - return m_appenderAttachedImpl.RemoveAppender(name); - } - } - return null; - } - - #endregion Implementation of IAppenderAttachable + return this.m_appenderAttachedImpl.GetAppender(name); + } + } - #region Private Instance Fields + /// + /// Removes all previously added appenders from this appender. + /// + /// + /// + /// This is useful when re-reading configuration information. + /// + /// + public virtual void RemoveAllAppenders() + { + lock (this) + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + this.m_appenderAttachedImpl = null; + } + } + } - /// - /// Implementation of the interface - /// - private AppenderAttachedImpl m_appenderAttachedImpl; + /// + /// Removes the specified appender from the list of appenders. + /// + /// The appender to remove. + /// The appender removed from the list. + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(IAppender appender) + { + lock (this) + { + if (appender != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(appender); + } + } + + return null; + } - #endregion Private Instance Fields - } + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list. + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(string name) + { + lock (this) + { + if (name != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(name); + } + } + + return null; + } + + /// + /// Implementation of the interface. + /// + private AppenderAttachedImpl m_appenderAttachedImpl; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs index a51cdaa06d5..8718d701349 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +18,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for Win32 Console API's -#if !NETCF +#if !NETCF // .Mono 1.0 has no support for Win32 Console API's -#if !MONO +#if !MONO // SSCLI 1.0 has no support for Win32 Console API's #if !SSCLI // We don't want framework or platform specific code in the CLI version of log4net @@ -35,633 +33,601 @@ using System; using System.Globalization; using System.Runtime.InteropServices; - + using log4net.Layout; using log4net.Util; namespace log4net.Appender { - /// - /// Appends logging events to the console. - /// - /// - /// - /// ColoredConsoleAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. It also allows the color of a specific type of message to be set. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// NOTE: This appender writes directly to the application's attached console - /// not to the System.Console.Out or System.Console.Error TextWriter. - /// The System.Console.Out and System.Console.Error streams can be - /// programmatically redirected (for example NUnit does this to capture program output). - /// This appender will ignore these redirections because it needs to use Win32 - /// API calls to colorize the output. To respect these redirections the - /// must be used. - /// - /// - /// When configuring the colored console appender, mapping should be - /// specified to map a logging level to a color. For example: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The Level is the standard log4net logging level and ForeColor and BackColor can be any - /// combination of the following values: - /// - /// Blue - /// Green - /// Red - /// White - /// Yellow - /// Purple - /// Cyan - /// HighIntensity - /// - /// - /// - /// Rick Hobbs - /// Nicko Cadell - public class ColoredConsoleAppender : AppenderSkeleton - { - #region Colors Enum - - /// - /// The enum of possible color values for use with the color mapping method - /// - /// - /// - /// The following flags can be combined together to - /// form the colors. - /// - /// - /// - [Flags] - public enum Colors : int - { - /// - /// color is blue - /// - Blue = 0x0001, - - /// - /// color is green - /// - Green = 0x0002, - - /// - /// color is red - /// - Red = 0x0004, - - /// - /// color is white - /// - White = Blue | Green | Red, - - /// - /// color is yellow - /// - Yellow = Red | Green, - - /// - /// color is purple - /// - Purple = Red | Blue, - - /// - /// color is cyan - /// - Cyan = Green | Blue, - - /// - /// color is intensified - /// - HighIntensity = 0x0008, - } - - #endregion // Colors Enum - - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public ColoredConsoleAppender() - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] - public ColoredConsoleAppender(ILayout layout) : this(layout, false) - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender - /// flag set to true to write to the console error stream - /// - /// When is set to true, output is written to - /// the standard error output stream. Otherwise, output is written to the standard - /// output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout & Target properties. Scheduled removal in v10.0.0.")] - public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) - { - Layout = layout; - m_writeToErrorStream = writeToErrorStream; - } - - #endregion // Public Instance Constructors - - #region Public Instance Properties - - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - virtual public string Target - { - get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; } - set - { - string v = value.Trim(); - - if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) - { - m_writeToErrorStream = true; - } - else - { - m_writeToErrorStream = false; - } - } - } - - /// - /// Add a mapping of level to color - done by the config file - /// - /// The mapping to add - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the foreground and background colors - /// for a level. - /// - /// - public void AddMapping(LevelColors mapping) - { - m_levelMapping.Add(mapping); - } - - #endregion // Public Instance Properties - - #region Override implementation of AppenderSkeleton - - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// + /// + /// Appends logging events to the console. + /// + /// + /// + /// ColoredConsoleAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. It also allows the color of a specific type of message to be set. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// NOTE: This appender writes directly to the application's attached console + /// not to the System.Console.Out or System.Console.Error TextWriter. + /// The System.Console.Out and System.Console.Error streams can be + /// programmatically redirected (for example NUnit does this to capture program output). + /// This appender will ignore these redirections because it needs to use Win32 + /// API calls to colorize the output. To respect these redirections the + /// must be used. + /// + /// + /// When configuring the colored console appender, mapping should be + /// specified to map a logging level to a color. For example: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// The Level is the standard log4net logging level and ForeColor and BackColor can be any + /// combination of the following values: + /// + /// Blue + /// Green + /// Red + /// White + /// Yellow + /// Purple + /// Cyan + /// HighIntensity + /// + /// + /// + /// Rick Hobbs. + /// Nicko Cadell. + public class ColoredConsoleAppender : AppenderSkeleton + { + /// + /// The enum of possible color values for use with the color mapping method. + /// + /// + /// + /// The following flags can be combined together to + /// form the colors. + /// + /// + /// + [Flags] + public enum Colors : int + { + /// + /// color is blue + /// + Blue = 0x0001, + + /// + /// color is green + /// + Green = 0x0002, + + /// + /// color is red + /// + Red = 0x0004, + + /// + /// color is white + /// + White = Blue | Green | Red, + + /// + /// color is yellow + /// + Yellow = Red | Green, + + /// + /// color is purple + /// + Purple = Red | Blue, + + /// + /// color is cyan + /// + Cyan = Green | Blue, + + /// + /// color is intensified + /// + HighIntensity = 0x0008, + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public ColoredConsoleAppender() + { + } + + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender. + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] + public ColoredConsoleAppender(ILayout layout) + : this(layout, false) + { + } + + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender. + /// flag set to true to write to the console error stream. + /// + /// When is set to true, output is written to + /// the standard error output stream. Otherwise, output is written to the standard + /// output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout & Target properties. Scheduled removal in v10.0.0.")] + public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) + { + this.Layout = layout; + this.m_writeToErrorStream = writeToErrorStream; + } + + /// + /// Gets or sets target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + + set + { + string v = value.Trim(); + + if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } + } + + /// + /// Add a mapping of level to color - done by the config file. + /// + /// The mapping to add. + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the foreground and background colors + /// for a level. + /// + /// + public void AddMapping(LevelColors mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] - override protected void Append(log4net.Core.LoggingEvent loggingEvent) - { - if (m_consoleOutputWriter != null) - { - IntPtr consoleHandle = IntPtr.Zero; - if (m_writeToErrorStream) - { - // Write to the error stream - consoleHandle = GetStdHandle(STD_ERROR_HANDLE); - } - else - { - // Write to the output stream - consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); - } - - // Default to white on black - ushort colorInfo = (ushort)Colors.White; - - // see if there is a specified lookup - LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; - if (levelColors != null) - { - colorInfo = levelColors.CombinedColor; - } - - // Render the event to a string - string strLoggingMessage = RenderLoggingEvent(loggingEvent); - - // get the current console color - to restore later - CONSOLE_SCREEN_BUFFER_INFO bufferInfo; - GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo); - - // set the console colors - SetConsoleTextAttribute(consoleHandle, colorInfo); - - // Using WriteConsoleW seems to be unreliable. - // If a large buffer is written, say 15,000 chars - // Followed by a larger buffer, say 20,000 chars - // then WriteConsoleW will fail, last error 8 - // 'Not enough storage is available to process this command.' - // - // Although the documentation states that the buffer must - // be less that 64KB (i.e. 32,000 WCHARs) the longest string - // that I can write out a the first call to WriteConsoleW - // is only 30,704 chars. - // - // Unlike the WriteFile API the WriteConsoleW method does not - // seem to be able to partially write out from the input buffer. - // It does have a lpNumberOfCharsWritten parameter, but this is - // either the length of the input buffer if any output was written, - // or 0 when an error occurs. - // - // All results above were observed on Windows XP SP1 running - // .NET runtime 1.1 SP1. - // - // Old call to WriteConsoleW: - // - // WriteConsoleW( - // consoleHandle, - // strLoggingMessage, - // (UInt32)strLoggingMessage.Length, - // out (UInt32)ignoreWrittenCount, - // IntPtr.Zero); - // - // Instead of calling WriteConsoleW we use WriteFile which - // handles large buffers correctly. Because WriteFile does not - // handle the codepage conversion as WriteConsoleW does we - // need to use a System.IO.StreamWriter with the appropriate - // Encoding. The WriteFile calls are wrapped up in the - // System.IO.__ConsoleStream internal class obtained through - // the System.Console.OpenStandardOutput method. - // - // See the ActivateOptions method below for the code that - // retrieves and wraps the stream. - - - // The windows console uses ScrollConsoleScreenBuffer internally to - // scroll the console buffer when the display buffer of the console - // has been used up. ScrollConsoleScreenBuffer fills the area uncovered - // by moving the current content with the background color - // currently specified on the console. This means that it fills the - // whole line in front of the cursor position with the current - // background color. - // This causes an issue when writing out text with a non default - // background color. For example; We write a message with a Blue - // background color and the scrollable area of the console is full. - // When we write the newline at the end of the message the console - // needs to scroll the buffer to make space available for the new line. - // The ScrollConsoleScreenBuffer internals will fill the newly created - // space with the current background color: Blue. - // We then change the console color back to default (White text on a - // Black background). We write some text to the console, the text is - // written correctly in White with a Black background, however the - // remainder of the line still has a Blue background. - // - // This causes a disjointed appearance to the output where the background - // colors change. - // - // This can be remedied by restoring the console colors before causing - // the buffer to scroll, i.e. before writing the last newline. This does - // assume that the rendered message will end with a newline. - // - // Therefore we identify a trailing newline in the message and don't - // write this to the output, then we restore the console color and write - // a newline. Note that we must AutoFlush before we restore the console - // color otherwise we will have no effect. - // - // There will still be a slight artefact for the last line of the message - // will have the background extended to the end of the line, however this - // is unlikely to cause any user issues. - // - // Note that none of the above is visible while the console buffer is scrollable - // within the console window viewport, the effects only arise when the actual - // buffer is full and needs to be scrolled. - - char[] messageCharArray = strLoggingMessage.ToCharArray(); - int arrayLength = messageCharArray.Length; - bool appendNewline = false; - - // Trim off last newline, if it exists - if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n') - { - arrayLength -= 2; - appendNewline = true; - } - - // Write to the output stream - m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength); - - // Restore the console back to its previous color scheme - SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes); - - if (appendNewline) - { - // Write the newline, after changing the color scheme - m_consoleOutputWriter.Write(s_windowsNewline, 0, 2); - } - } - } - - private static readonly char[] s_windowsNewline = {'\r', '\n'}; - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - /// - /// Initialize the options for this appender - /// - /// - /// - /// Initialize the level to color mappings set on this appender. - /// - /// + protected override void Append(log4net.Core.LoggingEvent loggingEvent) + { + if (this.m_consoleOutputWriter != null) + { + IntPtr consoleHandle = IntPtr.Zero; + if (this.m_writeToErrorStream) + { + // Write to the error stream + consoleHandle = GetStdHandle(STD_ERROR_HANDLE); + } + else + { + // Write to the output stream + consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); + } + + // Default to white on black + ushort colorInfo = (ushort)Colors.White; + + // see if there is a specified lookup + LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; + if (levelColors != null) + { + colorInfo = levelColors.CombinedColor; + } + + // Render the event to a string + string strLoggingMessage = this.RenderLoggingEvent(loggingEvent); + + // get the current console color - to restore later + CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo); + + // set the console colors + SetConsoleTextAttribute(consoleHandle, colorInfo); + + // Using WriteConsoleW seems to be unreliable. + // If a large buffer is written, say 15,000 chars + // Followed by a larger buffer, say 20,000 chars + // then WriteConsoleW will fail, last error 8 + // 'Not enough storage is available to process this command.' + // + // Although the documentation states that the buffer must + // be less that 64KB (i.e. 32,000 WCHARs) the longest string + // that I can write out a the first call to WriteConsoleW + // is only 30,704 chars. + // + // Unlike the WriteFile API the WriteConsoleW method does not + // seem to be able to partially write out from the input buffer. + // It does have a lpNumberOfCharsWritten parameter, but this is + // either the length of the input buffer if any output was written, + // or 0 when an error occurs. + // + // All results above were observed on Windows XP SP1 running + // .NET runtime 1.1 SP1. + // + // Old call to WriteConsoleW: + // + // WriteConsoleW( + // consoleHandle, + // strLoggingMessage, + // (UInt32)strLoggingMessage.Length, + // out (UInt32)ignoreWrittenCount, + // IntPtr.Zero); + // + // Instead of calling WriteConsoleW we use WriteFile which + // handles large buffers correctly. Because WriteFile does not + // handle the codepage conversion as WriteConsoleW does we + // need to use a System.IO.StreamWriter with the appropriate + // Encoding. The WriteFile calls are wrapped up in the + // System.IO.__ConsoleStream internal class obtained through + // the System.Console.OpenStandardOutput method. + // + // See the ActivateOptions method below for the code that + // retrieves and wraps the stream. + + // The windows console uses ScrollConsoleScreenBuffer internally to + // scroll the console buffer when the display buffer of the console + // has been used up. ScrollConsoleScreenBuffer fills the area uncovered + // by moving the current content with the background color + // currently specified on the console. This means that it fills the + // whole line in front of the cursor position with the current + // background color. + // This causes an issue when writing out text with a non default + // background color. For example; We write a message with a Blue + // background color and the scrollable area of the console is full. + // When we write the newline at the end of the message the console + // needs to scroll the buffer to make space available for the new line. + // The ScrollConsoleScreenBuffer internals will fill the newly created + // space with the current background color: Blue. + // We then change the console color back to default (White text on a + // Black background). We write some text to the console, the text is + // written correctly in White with a Black background, however the + // remainder of the line still has a Blue background. + // + // This causes a disjointed appearance to the output where the background + // colors change. + // + // This can be remedied by restoring the console colors before causing + // the buffer to scroll, i.e. before writing the last newline. This does + // assume that the rendered message will end with a newline. + // + // Therefore we identify a trailing newline in the message and don't + // write this to the output, then we restore the console color and write + // a newline. Note that we must AutoFlush before we restore the console + // color otherwise we will have no effect. + // + // There will still be a slight artefact for the last line of the message + // will have the background extended to the end of the line, however this + // is unlikely to cause any user issues. + // + // Note that none of the above is visible while the console buffer is scrollable + // within the console window viewport, the effects only arise when the actual + // buffer is full and needs to be scrolled. + char[] messageCharArray = strLoggingMessage.ToCharArray(); + int arrayLength = messageCharArray.Length; + bool appendNewline = false; + + // Trim off last newline, if it exists + if (arrayLength > 1 && messageCharArray[arrayLength - 2] == '\r' && messageCharArray[arrayLength - 1] == '\n') + { + arrayLength -= 2; + appendNewline = true; + } + + // Write to the output stream + this.m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength); + + // Restore the console back to its previous color scheme + SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes); + + if (appendNewline) + { + // Write the newline, after changing the color scheme + this.m_consoleOutputWriter.Write(s_windowsNewline, 0, 2); + } + } + } + + private static readonly char[] s_windowsNewline = { '\r', '\n' }; + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Initialize the options for this appender. + /// + /// + /// + /// Initialize the level to color mappings set on this appender. + /// + /// #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)] + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] public override void ActivateOptions() - { - base.ActivateOptions(); - m_levelMapping.ActivateOptions(); - - System.IO.Stream consoleOutputStream = null; - - // Use the Console methods to open a Stream over the console std handle - if (m_writeToErrorStream) - { - // Write to the error stream - consoleOutputStream = Console.OpenStandardError(); - } - else - { - // Write to the output stream - consoleOutputStream = Console.OpenStandardOutput(); - } - - // Lookup the codepage encoding for the console - System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP()); - - // Create a writer around the console stream - m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100); - - m_consoleOutputWriter.AutoFlush = true; - - // SuppressFinalize on m_consoleOutputWriter because all it will do is flush - // and close the file handle. Because we have set AutoFlush the additional flush - // is not required. The console file handle should not be closed, so we don't call - // Dispose, Close or the finalizer. - GC.SuppressFinalize(m_consoleOutputWriter); - } - - #endregion // Override implementation of AppenderSkeleton - - #region Public Static Fields - - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; - - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - public const string ConsoleError = "Console.Error"; - - #endregion // Public Static Fields - - #region Private Instances Fields - - /// - /// Flag to write output to the error stream rather than the standard output stream - /// - private bool m_writeToErrorStream = false; - - /// - /// Mapping from level object to color value - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// The console output stream writer to write to - /// - /// - /// - /// This writer is not thread safe. - /// - /// - private System.IO.StreamWriter m_consoleOutputWriter = null; - - #endregion // Private Instances Fields - - #region Win32 Methods - - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] - private static extern int GetConsoleOutputCP(); - - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] - private static extern bool SetConsoleTextAttribute( - IntPtr consoleHandle, - ushort attributes); - - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] - private static extern bool GetConsoleScreenBufferInfo( - IntPtr consoleHandle, - out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); - -// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] -// private static extern bool WriteConsoleW( -// IntPtr hConsoleHandle, -// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, -// UInt32 bufferLen, -// out UInt32 written, -// IntPtr reserved); - - //private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); - private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11)); - private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12)); - - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] - private static extern IntPtr GetStdHandle( - UInt32 type); - - [StructLayout(LayoutKind.Sequential)] - private struct COORD - { - public UInt16 x; - public UInt16 y; - } - - [StructLayout(LayoutKind.Sequential)] - private struct SMALL_RECT - { - public UInt16 Left; - public UInt16 Top; - public UInt16 Right; - public UInt16 Bottom; - } - - [StructLayout(LayoutKind.Sequential)] - private struct CONSOLE_SCREEN_BUFFER_INFO - { - public COORD dwSize; - public COORD dwCursorPosition; - public ushort wAttributes; - public SMALL_RECT srWindow; - public COORD dwMaximumWindowSize; - } - - #endregion // Win32 Methods - - #region LevelColors LevelMapping Entry - - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and the color it should be displayed in. - /// - /// - public class LevelColors : LevelMappingEntry - { - private Colors m_foreColor; - private Colors m_backColor; - private ushort m_combinedColor = 0; - - /// - /// The mapped foreground color for the specified level - /// - /// - /// - /// Required property. - /// The mapped foreground color for the specified level. - /// - /// - public Colors ForeColor - { - get { return m_foreColor; } - set { m_foreColor = value; } - } - - /// - /// The mapped background color for the specified level - /// - /// - /// - /// Required property. - /// The mapped background color for the specified level. - /// - /// - public Colors BackColor - { - get { return m_backColor; } - set { m_backColor = value; } - } - - /// - /// Initialize the options for the object - /// - /// - /// - /// Combine the and together. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) ); - } - - /// - /// The combined and suitable for - /// setting the console color. - /// - internal ushort CombinedColor - { - get { return m_combinedColor; } - } - } - - #endregion // LevelColors LevelMapping Entry - } + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); + + System.IO.Stream consoleOutputStream = null; + + // Use the Console methods to open a Stream over the console std handle + if (this.m_writeToErrorStream) + { + // Write to the error stream + consoleOutputStream = Console.OpenStandardError(); + } + else + { + // Write to the output stream + consoleOutputStream = Console.OpenStandardOutput(); + } + + // Lookup the codepage encoding for the console + System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP()); + + // Create a writer around the console stream + this.m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100); + + this.m_consoleOutputWriter.AutoFlush = true; + + // SuppressFinalize on m_consoleOutputWriter because all it will do is flush + // and close the file handle. Because we have set AutoFlush the additional flush + // is not required. The console file handle should not be closed, so we don't call + // Dispose, Close or the finalizer. + GC.SuppressFinalize(this.m_consoleOutputWriter); + } + + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; + + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + public const string ConsoleError = "Console.Error"; + + /// + /// Flag to write output to the error stream rather than the standard output stream. + /// + private bool m_writeToErrorStream = false; + + /// + /// Mapping from level object to color value. + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// The console output stream writer to write to. + /// + /// + /// + /// This writer is not thread safe. + /// + /// + private System.IO.StreamWriter m_consoleOutputWriter = null; + + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern int GetConsoleOutputCP(); + + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool SetConsoleTextAttribute( + IntPtr consoleHandle, + ushort attributes); + + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool GetConsoleScreenBufferInfo( + IntPtr consoleHandle, + out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); + + // [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] + // private static extern bool WriteConsoleW( + // IntPtr hConsoleHandle, + // [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, + // UInt32 bufferLen, + // out UInt32 written, + // IntPtr reserved); + + // private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); + private const uint STD_OUTPUT_HANDLE = unchecked((uint)(-11)); + private const uint STD_ERROR_HANDLE = unchecked((uint)(-12)); + + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern IntPtr GetStdHandle( + uint type); + + [StructLayout(LayoutKind.Sequential)] + private struct COORD + { + public ushort x; + public ushort y; + } + + [StructLayout(LayoutKind.Sequential)] + private struct SMALL_RECT + { + public ushort Left; + public ushort Top; + public ushort Right; + public ushort Bottom; + } + + [StructLayout(LayoutKind.Sequential)] + private struct CONSOLE_SCREEN_BUFFER_INFO + { + public COORD dwSize; + public COORD dwCursorPosition; + public ushort wAttributes; + public SMALL_RECT srWindow; + public COORD dwMaximumWindowSize; + } + + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and the color it should be displayed in. + /// + /// + public class LevelColors : LevelMappingEntry + { + private Colors m_foreColor; + private Colors m_backColor; + private ushort m_combinedColor = 0; + + /// + /// Gets or sets the mapped foreground color for the specified level. + /// + /// + /// + /// Required property. + /// The mapped foreground color for the specified level. + /// + /// + public Colors ForeColor + { + get { return this.m_foreColor; } + set { this.m_foreColor = value; } + } + + /// + /// Gets or sets the mapped background color for the specified level. + /// + /// + /// + /// Required property. + /// The mapped background color for the specified level. + /// + /// + public Colors BackColor + { + get { return this.m_backColor; } + set { this.m_backColor = value; } + } + + /// + /// Initialize the options for the object. + /// + /// + /// + /// Combine the and together. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_combinedColor = (ushort)((int)this.m_foreColor + (((int)this.m_backColor) << 4)); + } + + /// + /// Gets the combined and suitable for + /// setting the console color. + /// + internal ushort CombinedColor + { + get { return this.m_combinedColor; } + } + } + } } #endif // !CLI_1_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs index f8ce7ff9855..413a15fd030 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs @@ -1,225 +1,203 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Globalization; - -using log4net.Layout; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Appends logging events to the console. - /// - /// - /// - /// ConsoleAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// NOTE: This appender writes each message to the System.Console.Out or - /// System.Console.Error that is set at the time the event is appended. - /// Therefore it is possible to programmatically redirect the output of this appender - /// (for example NUnit does this to capture program output). While this is the desired - /// behavior of this appender it may have security implications in your application. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class ConsoleAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public ConsoleAppender() - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] - public ConsoleAppender(ILayout layout) : this(layout, false) - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender - /// flag set to true to write to the console error stream - /// - /// When is set to true, output is written to - /// the standard error output stream. Otherwise, output is written to the standard - /// output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout & Target properties. Scheduled removal in v10.0.0.")] - public ConsoleAppender(ILayout layout, bool writeToErrorStream) - { - Layout = layout; - m_writeToErrorStream = writeToErrorStream; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - virtual public string Target - { - get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; } - set - { - string v = value.Trim(); - - if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) - { - m_writeToErrorStream = true; - } - else - { - m_writeToErrorStream = false; - } - } - } - - #endregion Public Instance Properties - - #region Override implementation of AppenderSkeleton - - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// Appends logging events to the console. + /// + /// + /// + /// ConsoleAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// NOTE: This appender writes each message to the System.Console.Out or + /// System.Console.Error that is set at the time the event is appended. + /// Therefore it is possible to programmatically redirect the output of this appender + /// (for example NUnit does this to capture program output). While this is the desired + /// behavior of this appender it may have security implications in your application. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class ConsoleAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public ConsoleAppender() + { + } + + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender. + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] + public ConsoleAppender(ILayout layout) + : this(layout, false) + { + } + + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender. + /// flag set to true to write to the console error stream. + /// + /// When is set to true, output is written to + /// the standard error output stream. Otherwise, output is written to the standard + /// output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout & Target properties. Scheduled removal in v10.0.0.")] + public ConsoleAppender(ILayout layout, bool writeToErrorStream) + { + this.Layout = layout; + this.m_writeToErrorStream = writeToErrorStream; + } + + /// + /// Gets or sets target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + + set + { + string v = value.Trim(); + + if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { #if NETCF_1_0 // Write to the output stream Console.Write(RenderLoggingEvent(loggingEvent)); #else - if (m_writeToErrorStream) - { - // Write to the error stream - Console.Error.Write(RenderLoggingEvent(loggingEvent)); - } - else - { - // Write to the output stream - Console.Write(RenderLoggingEvent(loggingEvent)); - } + if (this.m_writeToErrorStream) + { + // Write to the error stream + Console.Error.Write(this.RenderLoggingEvent(loggingEvent)); + } + else + { + // Write to the output stream + Console.Write(this.RenderLoggingEvent(loggingEvent)); + } #endif - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion Override implementation of AppenderSkeleton - - #region Public Static Fields - - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; - - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - public const string ConsoleError = "Console.Error"; - - #endregion Public Static Fields - - #region Private Instances Fields - - private bool m_writeToErrorStream = false; - - #endregion Private Instances Fields - } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; + + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + public const string ConsoleError = "Console.Error"; + private bool m_writeToErrorStream = false; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs index 290efb70ea7..6057b28034c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,176 +18,160 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - #define DEBUG - -using log4net.Layout; -using log4net.Core; - + namespace log4net.Appender { - /// - /// Appends log events to the system. - /// - /// - /// - /// The application configuration file can be used to control what listeners - /// are actually used. See the MSDN documentation for the - /// class for details on configuring the - /// debug system. - /// - /// - /// Events are written using the - /// method. The event's logger name is passed as the value for the category name to the Write method. - /// - /// - /// Nicko Cadell - public class DebugAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the . - /// - /// - /// - /// Default constructor. - /// - /// - public DebugAppender() - { - } - - /// - /// Initializes a new instance of the - /// with a specified layout. - /// - /// The layout to use with this appender. - /// - /// - /// Obsolete constructor. - /// - /// - [System.Obsolete("Instead use the default constructor and set the Layout property")] - public DebugAppender(ILayout layout) - { - Layout = layout; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets a value that indicates whether the appender will - /// flush at the end of each write. - /// - /// - /// The default behavior is to flush at the end of each - /// write. If the option is set tofalse, then the underlying - /// stream can defer writing to physical medium to a later time. - /// - /// - /// Avoiding the flush operation at the end of each append results - /// in a performance gain of 10 to 20 percent. However, there is safety - /// trade-off involved in skipping flushing. Indeed, when flushing is - /// skipped, then it is likely that the last few log events will not - /// be recorded on disk when the application exits. This is a high - /// price to pay even for a 20% performance gain. - /// - /// - public bool ImmediateFlush - { - get { return m_immediateFlush; } - set { m_immediateFlush = value; } - } - - #endregion Public Instance Properties - + using log4net.Core; + using log4net.Layout; + + /// + /// Appends log events to the system. + /// + /// + /// + /// The application configuration file can be used to control what listeners + /// are actually used. See the MSDN documentation for the + /// class for details on configuring the + /// debug system. + /// + /// + /// Events are written using the + /// method. The event's logger name is passed as the value for the category name to the Write method. + /// + /// + /// Nicko Cadell. + public class DebugAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the . + /// + /// + /// + /// Default constructor. + /// + /// + public DebugAppender() + { + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the + /// with a specified layout. + /// + /// The layout to use with this appender. + /// + /// + /// Obsolete constructor. + /// + /// + [System.Obsolete("Instead use the default constructor and set the Layout property")] + public DebugAppender(ILayout layout) + { + this.Layout = layout; + } + + /// + /// Gets or sets a value indicating whether gets or sets a value that indicates whether the appender will + /// flush at the end of each write. + /// + /// + /// The default behavior is to flush at the end of each + /// write. If the option is set tofalse, then the underlying + /// stream can defer writing to physical medium to a later time. + /// + /// + /// Avoiding the flush operation at the end of each append results + /// in a performance gain of 10 to 20 percent. However, there is safety + /// trade-off involved in skipping flushing. Indeed, when flushing is + /// skipped, then it is likely that the last few log events will not + /// be recorded on disk when the application exits. This is a high + /// price to pay even for a 20% performance gain. + /// + /// + public bool ImmediateFlush + { + get { return this.m_immediateFlush; } + set { this.m_immediateFlush = value; } + } + +#if !NETSTANDARD1_3 + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) + { + // Nothing to do if ImmediateFlush is true + if (this.m_immediateFlush) + { + return true; + } + + // System.Diagnostics.Debug is thread-safe, so no need for lock(this). + System.Diagnostics.Debug.Flush(); + + return true; + } +#endif + + /// + /// Writes the logging event to the system. + /// + /// The event to log. + /// + /// + /// Writes the logging event to the system. + /// If is true then the + /// is called. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // Write the string to the Debug system + System.Diagnostics.Debug.Write(this.RenderLoggingEvent(loggingEvent), loggingEvent.LoggerName); #if !NETSTANDARD1_3 - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) + // + // Flush the Debug system if needed + if (this.m_immediateFlush) { - // Nothing to do if ImmediateFlush is true - if (m_immediateFlush) return true; - - // System.Diagnostics.Debug is thread-safe, so no need for lock(this). System.Diagnostics.Debug.Flush(); - - return true; } #endif - - #region Override implementation of AppenderSkeleton - - /// - /// Writes the logging event to the system. - /// - /// The event to log. - /// - /// - /// Writes the logging event to the system. - /// If is true then the - /// is called. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - // - // Write the string to the Debug system - // - System.Diagnostics.Debug.Write(RenderLoggingEvent(loggingEvent), loggingEvent.LoggerName); -#if !NETSTANDARD1_3 - // - // Flush the Debug system if needed - // - if (m_immediateFlush) - { - System.Diagnostics.Debug.Flush(); - } -#endif - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion Override implementation of AppenderSkeleton - - #region Private Instance Fields - - /// - /// Immediate flush means that the underlying writer or output stream - /// will be flushed at the end of each append operation. - /// - /// - /// - /// Immediate flush is slower but ensures that each append request is - /// actually written. If is set to - /// false, then there is a good chance that the last few - /// logs events are not actually written to persistent media if and - /// when the application crashes. - /// - /// - /// The default value is true. - /// - private bool m_immediateFlush = true; - - #endregion Private Instance Fields - } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Immediate flush means that the underlying writer or output stream + /// will be flushed at the end of each append operation. + /// + /// + /// + /// Immediate flush is slower but ensures that each append request is + /// actually written. If is set to + /// false, then there is a good chance that the last few + /// logs events are not actually written to persistent media if and + /// when the application crashes. + /// + /// + /// The default value is true. + /// + private bool m_immediateFlush = true; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs index 4a2120577da..e217d769526 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,210 +18,204 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for EventLog -#if !NETCF +#if !NETCF // SSCLI 1.0 has no support for EventLog #if !SSCLI using System; using System.Diagnostics; using System.Globalization; - -using log4net.Util; -using log4net.Layout; + using log4net.Core; +using log4net.Layout; +using log4net.Util; namespace log4net.Appender { - /// - /// Writes events to the system event log. - /// - /// + /// + /// Writes events to the system event log. + /// + /// /// /// The appender will fail if you try to write using an event source that doesn't exist unless it is running with local administrator privileges. - /// See also http://logging.apache.org/log4net/release/faq.html#trouble-EventLog + /// See also http://logging.apache.org/log4net/release/faq.html#trouble-EventLog. + /// + /// + /// The EventID of the event log entry can be + /// set using the EventID property () + /// on the . /// - /// - /// The EventID of the event log entry can be - /// set using the EventID property () - /// on the . - /// /// /// The Category of the event log entry can be - /// set using the Category property () - /// on the . - /// - /// - /// There is a limit of 32K characters for an event log message - /// - /// - /// When configuring the EventLogAppender a mapping can be - /// specified to map a logging level to an event log entry type. For example: - /// - /// - /// <mapping> - /// <level value="ERROR" /> - /// <eventLogEntryType value="Error" /> - /// </mapping> - /// <mapping> - /// <level value="DEBUG" /> - /// <eventLogEntryType value="Information" /> - /// </mapping> - /// - /// - /// The Level is the standard log4net logging level and eventLogEntryType can be any value - /// from the enum, i.e.: - /// - /// Erroran error event - /// Warninga warning event - /// Informationan informational event - /// - /// - /// - /// Aspi Havewala - /// Douglas de la Torre - /// Nicko Cadell - /// Gert Driesen - /// Thomas Voss - public class EventLogAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public EventLogAppender() - { - m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; - m_logName = "Application"; // Defaults to application log - m_machineName = "."; // Only log on the local machine - } - - /// - /// Initializes a new instance of the class - /// with the specified . - /// - /// The to use with this appender. - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] - public EventLogAppender(ILayout layout) : this() - { - Layout = layout; - } - - #endregion // Public Instance Constructors - - #region Public Instance Properties - - /// - /// The name of the log where messages will be stored. - /// - /// - /// The string name of the log where messages will be stored. - /// - /// - /// This is the name of the log as it appears in the Event Viewer - /// tree. The default value is to log into the Application - /// log, this is where most applications write their events. However - /// if you need a separate log for your application (or applications) - /// then you should set the appropriately. - /// This should not be used to distinguish your event log messages - /// from those of other applications, the - /// property should be used to distinguish events. This property should be - /// used to group together events into a single log. - /// - /// - public string LogName - { - get { return m_logName; } - set { m_logName = value; } - } - - /// - /// Property used to set the Application name. This appears in the - /// event logs when logging. - /// - /// - /// The string used to distinguish events from different sources. - /// - /// - /// Sets the event log source property. - /// - public string ApplicationName - { - get { return m_applicationName; } - set { m_applicationName = value; } - } - - /// - /// This property is used to return the name of the computer to use - /// when accessing the event logs. Currently, this is the current - /// computer, denoted by a dot "." - /// - /// - /// The string name of the machine holding the event log that - /// will be logged into. - /// - /// - /// This property cannot be changed. It is currently set to '.' - /// i.e. the local machine. This may be changed in future. - /// - public string MachineName - { - get { return m_machineName; } - set { /* Currently we do not allow the machine name to be changed */; } - } - - /// - /// Add a mapping of level to - done by the config file - /// - /// The mapping to add - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the event log entry type for a level. - /// - /// - public void AddMapping(Level2EventLogEntryType mapping) - { - m_levelMapping.Add(mapping); - } - - /// - /// Gets or sets the used to write to the EventLog. - /// - /// - /// The used to write to the EventLog. - /// - /// - /// - /// The system security context used to write to the EventLog. - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return m_securityContext; } - set { m_securityContext = value; } - } + /// set using the Category property () + /// on the . + /// + /// + /// There is a limit of 32K characters for an event log message. + /// + /// + /// When configuring the EventLogAppender a mapping can be + /// specified to map a logging level to an event log entry type. For example: + /// + /// + /// <mapping> + /// <level value="ERROR" /> + /// <eventLogEntryType value="Error" /> + /// </mapping> + /// <mapping> + /// <level value="DEBUG" /> + /// <eventLogEntryType value="Information" /> + /// </mapping> + /// + /// + /// The Level is the standard log4net logging level and eventLogEntryType can be any value + /// from the enum, i.e.: + /// + /// Erroran error event + /// Warninga warning event + /// Informationan informational event + /// + /// + /// + /// Aspi Havewala. + /// Douglas de la Torre. + /// Nicko Cadell. + /// Gert Driesen. + /// Thomas Voss. + public class EventLogAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public EventLogAppender() + { + this.m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; + this.m_logName = "Application"; // Defaults to application log + this.m_machineName = "."; // Only log on the local machine + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// The to use with this appender. + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] + public EventLogAppender(ILayout layout) + : this() + { + this.Layout = layout; + } + + /// + /// Gets or sets the name of the log where messages will be stored. + /// + /// + /// The string name of the log where messages will be stored. + /// + /// + /// This is the name of the log as it appears in the Event Viewer + /// tree. The default value is to log into the Application + /// log, this is where most applications write their events. However + /// if you need a separate log for your application (or applications) + /// then you should set the appropriately. + /// This should not be used to distinguish your event log messages + /// from those of other applications, the + /// property should be used to distinguish events. This property should be + /// used to group together events into a single log. + /// + /// + public string LogName + { + get { return this.m_logName; } + set { this.m_logName = value; } + } + + /// + /// Gets or sets property used to set the Application name. This appears in the + /// event logs when logging. + /// + /// + /// The string used to distinguish events from different sources. + /// + /// + /// Sets the event log source property. + /// + public string ApplicationName + { + get { return this.m_applicationName; } + set { this.m_applicationName = value; } + } + + /// + /// Gets or sets this property is used to return the name of the computer to use + /// when accessing the event logs. Currently, this is the current + /// computer, denoted by a dot ".". + /// + /// + /// The string name of the machine holding the event log that + /// will be logged into. + /// + /// + /// This property cannot be changed. It is currently set to '.' + /// i.e. the local machine. This may be changed in future. + /// + public string MachineName + { + get { return this.m_machineName; } + set { /* Currently we do not allow the machine name to be changed */ } + } + + /// + /// Add a mapping of level to - done by the config file. + /// + /// The mapping to add. + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the event log entry type for a level. + /// + /// + public void AddMapping(Level2EventLogEntryType mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// Gets or sets the used to write to the EventLog. + /// + /// + /// The used to write to the EventLog. + /// + /// + /// + /// The system security context used to write to the EventLog. + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } /// /// Gets or sets the EventId to use unless one is explicitly specified via the LoggingEvent's properties. @@ -230,205 +223,198 @@ public SecurityContext SecurityContext /// /// /// The EventID of the event log entry will normally be - /// set using the EventID property () - /// on the . + /// set using the EventID property () + /// on the . /// This property provides the fallback value which defaults to 0. /// /// - public int EventId { - get { return m_eventId; } - set { m_eventId = value; } + public int EventId + { + get { return this.m_eventId; } + set { this.m_eventId = value; } } - - + /// /// Gets or sets the Category to use unless one is explicitly specified via the LoggingEvent's properties. /// /// /// /// The Category of the event log entry will normally be - /// set using the Category property () - /// on the . + /// set using the Category property () + /// on the . /// This property provides the fallback value which defaults to 0. /// /// public short Category { - get { return m_category; } - set { m_category = value; } - } - #endregion // Public Instance Properties - - #region Implementation of IOptionHandler - - /// - /// Initialize the appender based on the options set - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { + get { return this.m_category; } + set { this.m_category = value; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { try { base.ActivateOptions(); - if (m_securityContext == null) + if (this.m_securityContext == null) { - m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } bool sourceAlreadyExists = false; string currentLogName = null; - using (SecurityContext.Impersonate(this)) + using (this.SecurityContext.Impersonate(this)) { - sourceAlreadyExists = EventLog.SourceExists(m_applicationName); - if (sourceAlreadyExists) { - currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); + sourceAlreadyExists = EventLog.SourceExists(this.m_applicationName); + if (sourceAlreadyExists) + { + currentLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); } } - if (sourceAlreadyExists && currentLogName != m_logName) + if (sourceAlreadyExists && currentLogName != this.m_logName) { - LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]"); + LogLog.Debug(declaringType, "Changing event source [" + this.m_applicationName + "] from log [" + currentLogName + "] to log [" + this.m_logName + "]"); } else if (!sourceAlreadyExists) { - LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]"); + LogLog.Debug(declaringType, "Creating event source Source [" + this.m_applicationName + "] in log " + this.m_logName + "]"); } string registeredLogName = null; - using (SecurityContext.Impersonate(this)) + using (this.SecurityContext.Impersonate(this)) { - if (sourceAlreadyExists && currentLogName != m_logName) + if (sourceAlreadyExists && currentLogName != this.m_logName) { - // // Re-register this to the current application if the user has changed // the application / logfile association - // - EventLog.DeleteEventSource(m_applicationName, m_machineName); - CreateEventSource(m_applicationName, m_logName, m_machineName); + EventLog.DeleteEventSource(this.m_applicationName, this.m_machineName); + CreateEventSource(this.m_applicationName, this.m_logName, this.m_machineName); - registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); + registeredLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); } else if (!sourceAlreadyExists) { - CreateEventSource(m_applicationName, m_logName, m_machineName); + CreateEventSource(this.m_applicationName, this.m_logName, this.m_machineName); - registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); + registeredLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); } } - m_levelMapping.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); - LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]"); + LogLog.Debug(declaringType, "Source [" + this.m_applicationName + "] is registered to log [" + registeredLogName + "]"); } catch (System.Security.SecurityException ex) { - ErrorHandler.Error("Caught a SecurityException trying to access the EventLog. Most likely the event source " - + m_applicationName + this.ErrorHandler.Error( + "Caught a SecurityException trying to access the EventLog. Most likely the event source " + + this.m_applicationName + " doesn't exist and must be created by a local administrator. Will disable EventLogAppender." + " See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog", ex); - Threshold = Level.Off; + this.Threshold = Level.Off; } - } - - #endregion // Implementation of IOptionHandler - - /// - /// Create an event log source - /// - /// - /// Uses different API calls under NET_2_0 - /// - private static void CreateEventSource(string source, string logName, string machineName) - { + } + + /// + /// Create an event log source. + /// + /// + /// Uses different API calls under NET_2_0. + /// + private static void CreateEventSource(string source, string logName, string machineName) + { #if NET_2_0 - EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName); - eventSourceCreationData.MachineName = machineName; - EventLog.CreateEventSource(eventSourceCreationData); + EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName); + eventSourceCreationData.MachineName = machineName; + EventLog.CreateEventSource(eventSourceCreationData); #else EventLog.CreateEventSource(source, logName, machineName); #endif - } - - #region Override implementation of AppenderSkeleton - - /// - /// This method is called by the - /// method. - /// - /// the event to log - /// - /// Writes the event to the system event log using the - /// . - /// - /// If the event has an EventID property (see ) - /// set then this integer will be used as the event log event id. - /// - /// - /// There is a limit of 32K characters for an event log message - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - // - // Write the resulting string to the event log system - // - int eventID = m_eventId; - - // Look for the EventID property - object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); - if (eventIDPropertyObj != null) - { - if (eventIDPropertyObj is int) - { - eventID = (int)eventIDPropertyObj; - } - else - { - string eventIDPropertyString = eventIDPropertyObj as string; + } + + /// + /// This method is called by the + /// method. + /// + /// the event to log. + /// + /// Writes the event to the system event log using the + /// . + /// + /// If the event has an EventID property (see ) + /// set then this integer will be used as the event log event id. + /// + /// + /// There is a limit of 32K characters for an event log message. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // Write the resulting string to the event log system + int eventID = this.m_eventId; + + // Look for the EventID property + object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); + if (eventIDPropertyObj != null) + { + if (eventIDPropertyObj is int) + { + eventID = (int)eventIDPropertyObj; + } + else + { + string eventIDPropertyString = eventIDPropertyObj as string; if (eventIDPropertyString == null) { eventIDPropertyString = eventIDPropertyObj.ToString(); } - if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) - { - // Read the string property into a number - int intVal; - if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) - { - eventID = intVal; - } - else - { - ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); - } - } - } - } - - short category = m_category; + + if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) + { + // Read the string property into a number + int intVal; + if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) + { + eventID = intVal; + } + else + { + this.ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); + } + } + } + } + + short category = this.m_category; + // Look for the Category property object categoryPropertyObj = loggingEvent.LookupProperty("Category"); if (categoryPropertyObj != null) { if (categoryPropertyObj is short) { - category = (short) categoryPropertyObj; + category = (short)categoryPropertyObj; } else { @@ -437,6 +423,7 @@ override protected void Append(LoggingEvent loggingEvent) { categoryPropertyString = categoryPropertyObj.ToString(); } + if (categoryPropertyString != null && categoryPropertyString.Length > 0) { // Read the string property into a number @@ -447,120 +434,111 @@ override protected void Append(LoggingEvent loggingEvent) } else { - ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); + this.ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); } } } } - // Write to the event log - try - { - string eventTxt = RenderLoggingEvent(loggingEvent); - - // There is a limit of about 32K characters for an event log message - if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE) - { - eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE); - } - - EventLogEntryType entryType = GetEntryType(loggingEvent.Level); - - using(SecurityContext.Impersonate(this)) - { - EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category); - } - } - catch(Exception ex) - { - ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex); - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion // Override implementation of AppenderSkeleton - - #region Protected Instance Methods - - /// - /// Get the equivalent for a - /// - /// the Level to convert to an EventLogEntryType - /// The equivalent for a - /// - /// Because there are fewer applicable - /// values to use in logging levels than there are in the - /// this is a one way mapping. There is - /// a loss of information during the conversion. - /// - virtual protected EventLogEntryType GetEntryType(Level level) - { - // see if there is a specified lookup. - Level2EventLogEntryType entryType = m_levelMapping.Lookup(level) as Level2EventLogEntryType; - if (entryType != null) - { - return entryType.EventLogEntryType; - } - - // Use default behavior - - if (level >= Level.Error) - { - return EventLogEntryType.Error; - } - else if (level == Level.Warn) - { - return EventLogEntryType.Warning; - } - - // Default setting - return EventLogEntryType.Information; - } - - #endregion // Protected Instance Methods - - #region Private Instance Fields - - /// - /// The log name is the section in the event logs where the messages - /// are stored. - /// - private string m_logName; - - /// - /// Name of the application to use when logging. This appears in the - /// application column of the event log named by . - /// - private string m_applicationName; - - /// - /// The name of the machine which holds the event log. This is - /// currently only allowed to be '.' i.e. the current machine. - /// - private string m_machineName; - - /// - /// Mapping from level object to EventLogEntryType - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// The security context to use for privileged calls - /// - private SecurityContext m_securityContext; + // Write to the event log + try + { + string eventTxt = this.RenderLoggingEvent(loggingEvent); + + // There is a limit of about 32K characters for an event log message + if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE) + { + eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE); + } + + EventLogEntryType entryType = this.GetEntryType(loggingEvent.Level); + + using (this.SecurityContext.Impersonate(this)) + { + EventLog.WriteEntry(this.m_applicationName, eventTxt, entryType, eventID, category); + } + } + catch (Exception ex) + { + this.ErrorHandler.Error("Unable to write to event log [" + this.m_logName + "] using source [" + this.m_applicationName + "]", ex); + } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Get the equivalent for a . + /// + /// the Level to convert to an EventLogEntryType. + /// The equivalent for a . + /// + /// Because there are fewer applicable + /// values to use in logging levels than there are in the + /// this is a one way mapping. There is + /// a loss of information during the conversion. + /// + protected virtual EventLogEntryType GetEntryType(Level level) + { + // see if there is a specified lookup. + Level2EventLogEntryType entryType = this.m_levelMapping.Lookup(level) as Level2EventLogEntryType; + if (entryType != null) + { + return entryType.EventLogEntryType; + } + + // Use default behavior + if (level >= Level.Error) + { + return EventLogEntryType.Error; + } + else if (level == Level.Warn) + { + return EventLogEntryType.Warning; + } + + // Default setting + return EventLogEntryType.Information; + } + + /// + /// The log name is the section in the event logs where the messages + /// are stored. + /// + private string m_logName; + + /// + /// Name of the application to use when logging. This appears in the + /// application column of the event log named by . + /// + private string m_applicationName; + + /// + /// The name of the machine which holds the event log. This is + /// currently only allowed to be '.' i.e. the current machine. + /// + private string m_machineName; + + /// + /// Mapping from level object to EventLogEntryType. + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// The security context to use for privileged calls. + /// + private SecurityContext m_securityContext; /// /// The event ID to use unless one is explicitly specified via the LoggingEvent's properties. @@ -570,124 +548,117 @@ virtual protected EventLogEntryType GetEntryType(Level level) /// /// The event category to use unless one is explicitly specified via the LoggingEvent's properties. /// - private short m_category = 0; - - #endregion // Private Instance Fields - - #region Level2EventLogEntryType LevelMapping Entry - - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and its event log entry type. - /// - /// - public class Level2EventLogEntryType : LevelMappingEntry - { - private EventLogEntryType m_entryType; - - /// - /// The for this entry - /// - /// - /// - /// Required property. - /// The for this entry - /// - /// - public EventLogEntryType EventLogEntryType - { - get { return m_entryType; } - set { m_entryType = value; } - } - } - - #endregion // LevelColors LevelMapping Entry - - #region Private Static Fields - - /// - /// The fully qualified type of the EventLogAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(EventLogAppender); - - /// - /// The maximum size supported by default. - /// - /// - /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx - /// The 32766 documented max size is two bytes shy of 32K (I'm assuming 32766 - /// may leave space for a two byte null terminator of #0#0). The 32766 max - /// length is what the .NET 4.0 source code checks for, but this is WRONG! - /// Strings with a length > 31839 on Windows Vista or higher can CORRUPT - /// the event log! See: System.Diagnostics.EventLogInternal.InternalWriteEvent() - /// for the use of the 32766 max size. - /// - private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT = 32766; - - /// - /// The maximum size supported by a windows operating system that is vista - /// or newer. - /// - /// - /// See ReportEvent API: - /// http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx - /// ReportEvent's lpStrings parameter: - /// "A pointer to a buffer containing an array of - /// null-terminated strings that are merged into the message before Event Viewer - /// displays the string to the user. This parameter must be a valid pointer - /// (or NULL), even if wNumStrings is zero. Each string is limited to 31,839 characters." - /// - /// Going beyond the size of 31839 will (at some point) corrupt the event log on Windows - /// Vista or higher! It may succeed for a while...but you will eventually run into the - /// error: "System.ComponentModel.Win32Exception : A device attached to the system is - /// not functioning", and the event log will then be corrupt (I was able to corrupt - /// an event log using a length of 31877 on Windows 7). - /// - /// The max size for Windows Vista or higher is documented here: - /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx. - /// Going over this size may succeed a few times but the buffer will overrun and - /// eventually corrupt the log (based on testing). - /// - /// The maxEventMsgSize size is based on the max buffer size of the lpStrings parameter of the ReportEvent API. - /// The documented max size for EventLog.WriteEntry for Windows Vista and higher is 31839, but I'm leaving room for a - /// terminator of #0#0, as we cannot see the source of ReportEvent (though we could use an API monitor to examine the - /// buffer, given enough time). - /// - private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER = 31839 - 2; - - /// - /// The maximum size that the operating system supports for - /// a event log message. - /// - /// - /// Used to determine the maximum string length that can be written - /// to the operating system event log and eventually truncate a string - /// that exceeds the limits. - /// - private readonly static int MAX_EVENTLOG_MESSAGE_SIZE = GetMaxEventLogMessageSize(); - - /// - /// This method determines the maximum event log message size allowed for - /// the current environment. - /// - /// - private static int GetMaxEventLogMessageSize() - { - if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) - return MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER; - return MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT; - } - - #endregion Private Static Fields - } + private short m_category = 0; + + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and its event log entry type. + /// + /// + public class Level2EventLogEntryType : LevelMappingEntry + { + private EventLogEntryType m_entryType; + + /// + /// Gets or sets the for this entry. + /// + /// + /// + /// Required property. + /// The for this entry. + /// + /// + public EventLogEntryType EventLogEntryType + { + get { return this.m_entryType; } + set { this.m_entryType = value; } + } + } + + /// + /// The fully qualified type of the EventLogAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(EventLogAppender); + + /// + /// The maximum size supported by default. + /// + /// + /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx + /// The 32766 documented max size is two bytes shy of 32K (I'm assuming 32766 + /// may leave space for a two byte null terminator of #0#0). The 32766 max + /// length is what the .NET 4.0 source code checks for, but this is WRONG! + /// Strings with a length > 31839 on Windows Vista or higher can CORRUPT + /// the event log! See: System.Diagnostics.EventLogInternal.InternalWriteEvent() + /// for the use of the 32766 max size. + /// + private static readonly int MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT = 32766; + + /// + /// The maximum size supported by a windows operating system that is vista + /// or newer. + /// + /// + /// See ReportEvent API: + /// http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx + /// ReportEvent's lpStrings parameter: + /// "A pointer to a buffer containing an array of + /// null-terminated strings that are merged into the message before Event Viewer + /// displays the string to the user. This parameter must be a valid pointer + /// (or NULL), even if wNumStrings is zero. Each string is limited to 31,839 characters." + /// + /// Going beyond the size of 31839 will (at some point) corrupt the event log on Windows + /// Vista or higher! It may succeed for a while...but you will eventually run into the + /// error: "System.ComponentModel.Win32Exception : A device attached to the system is + /// not functioning", and the event log will then be corrupt (I was able to corrupt + /// an event log using a length of 31877 on Windows 7). + /// + /// The max size for Windows Vista or higher is documented here: + /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx. + /// Going over this size may succeed a few times but the buffer will overrun and + /// eventually corrupt the log (based on testing). + /// + /// The maxEventMsgSize size is based on the max buffer size of the lpStrings parameter of the ReportEvent API. + /// The documented max size for EventLog.WriteEntry for Windows Vista and higher is 31839, but I'm leaving room for a + /// terminator of #0#0, as we cannot see the source of ReportEvent (though we could use an API monitor to examine the + /// buffer, given enough time). + /// + private static readonly int MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER = 31839 - 2; + + /// + /// The maximum size that the operating system supports for + /// a event log message. + /// + /// + /// Used to determine the maximum string length that can be written + /// to the operating system event log and eventually truncate a string + /// that exceeds the limits. + /// + private static readonly int MAX_EVENTLOG_MESSAGE_SIZE = GetMaxEventLogMessageSize(); + + /// + /// This method determines the maximum event log message size allowed for + /// the current environment. + /// + /// + private static int GetMaxEventLogMessageSize() + { + if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) + { + return MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER; + } + + return MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT; + } + } } #endif // !SSCLI diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs index 5029ecf0658..373a9e4bb57 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs @@ -1,88 +1,89 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; -using System.Text; -using System.Threading; -using log4net.Util; -using log4net.Layout; -using log4net.Core; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + + #if NET_4_5 || NETSTANDARD1_3 using System.Threading.Tasks; + #endif namespace log4net.Appender { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + using System.Threading; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + #if !NETCF - /// - /// Appends logging events to a file. - /// - /// - /// - /// Logging events are sent to the file specified by - /// the property. - /// - /// - /// The file can be opened in either append or overwrite mode - /// by specifying the property. - /// If the file path is relative it is taken as relative from - /// the application base directory. The file encoding can be - /// specified by setting the property. - /// - /// - /// The layout's and - /// values will be written each time the file is opened and closed - /// respectively. If the property is - /// then the file may contain multiple copies of the header and footer. - /// - /// - /// This appender will first try to open the file for writing when - /// is called. This will typically be during configuration. - /// If the file cannot be opened for writing the appender will attempt - /// to open the file again each time a message is logged to the appender. - /// If the file cannot be opened for writing when a message is logged then - /// the message will be discarded by this appender. - /// - /// - /// The supports pluggable file locking models via - /// the property. - /// The default behavior, implemented by - /// is to obtain an exclusive write lock on the file until this appender is closed. - /// The alternative models only hold a - /// write lock while the appender is writing a logging event () - /// or synchronize by using a named system wide Mutex (). - /// - /// - /// All locking strategies have issues and you should seriously consider using a different strategy that - /// avoids having multiple processes logging to the same file. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Rodrigo B. de Oliveira - /// Douglas de la Torre - /// Niall Daley + /// + /// Appends logging events to a file. + /// + /// + /// + /// Logging events are sent to the file specified by + /// the property. + /// + /// + /// The file can be opened in either append or overwrite mode + /// by specifying the property. + /// If the file path is relative it is taken as relative from + /// the application base directory. The file encoding can be + /// specified by setting the property. + /// + /// + /// The layout's and + /// values will be written each time the file is opened and closed + /// respectively. If the property is + /// then the file may contain multiple copies of the header and footer. + /// + /// + /// This appender will first try to open the file for writing when + /// is called. This will typically be during configuration. + /// If the file cannot be opened for writing the appender will attempt + /// to open the file again each time a message is logged to the appender. + /// If the file cannot be opened for writing when a message is logged then + /// the message will be discarded by this appender. + /// + /// + /// The supports pluggable file locking models via + /// the property. + /// The default behavior, implemented by + /// is to obtain an exclusive write lock on the file until this appender is closed. + /// The alternative models only hold a + /// write lock while the appender is writing a logging event () + /// or synchronize by using a named system wide Mutex (). + /// + /// + /// All locking strategies have issues and you should seriously consider using a different strategy that + /// avoids having multiple processes logging to the same file. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Rodrigo B. de Oliveira. + /// Douglas de la Torre. + /// Niall Daley. #else /// /// Appends logging events to a file. @@ -132,40 +133,37 @@ namespace log4net.Appender /// Douglas de la Torre /// Niall Daley #endif - public class FileAppender : TextWriterAppender - { - #region LockingStream Inner Class - - /// - /// Write only that uses the - /// to manage access to an underlying resource. - /// - private sealed class LockingStream : Stream, IDisposable - { - public sealed class LockStateException : LogException - { - public LockStateException(string message) - : base(message) - { - } - } - - private Stream m_realStream = null; - private LockingModelBase m_lockingModel = null; - private int m_lockLevel = 0; - - public LockingStream(LockingModelBase locking) - : base() - { - if (locking == null) - { - throw new ArgumentException("Locking model may not be null", "locking"); - } - m_lockingModel = locking; - } - - #region Override Implementation of Stream - + public class FileAppender : TextWriterAppender + { + /// + /// Write only that uses the + /// to manage access to an underlying resource. + /// + private sealed class LockingStream : Stream, IDisposable + { + public sealed class LockStateException : LogException + { + public LockStateException(string message) + : base(message) + { + } + } + + private Stream m_realStream = null; + private LockingModelBase m_lockingModel = null; + private int m_lockLevel = 0; + + public LockingStream(LockingModelBase locking) + : base() + { + if (locking == null) + { + throw new ArgumentException("Locking model may not be null", "locking"); + } + + this.m_lockingModel = locking; + } + #if NETSTANDARD1_3 protected override void Dispose(bool disposing) { @@ -173,846 +171,848 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } #else - - private int m_readTotal = -1; - - // Methods - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - AssertLocked(); - IAsyncResult ret = m_realStream.BeginRead(buffer, offset, count, callback, state); - m_readTotal = EndRead(ret); - return ret; - } - - /// - /// True asynchronous writes are not supported, the implementation forces a synchronous write. - /// - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - AssertLocked(); - IAsyncResult ret = m_realStream.BeginWrite(buffer, offset, count, callback, state); - EndWrite(ret); - return ret; - } - - public override void Close() - { - m_lockingModel.CloseFile(); - } - - public override int EndRead(IAsyncResult asyncResult) - { - AssertLocked(); - return m_readTotal; - } - public override void EndWrite(IAsyncResult asyncResult) - { - //No-op, it has already been handled - } + + private int m_readTotal = -1; + + // Methods + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + this.AssertLocked(); + IAsyncResult ret = this.m_realStream.BeginRead(buffer, offset, count, callback, state); + this.m_readTotal = this.EndRead(ret); + return ret; + } + + /// + /// True asynchronous writes are not supported, the implementation forces a synchronous write. + /// + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + this.AssertLocked(); + IAsyncResult ret = this.m_realStream.BeginWrite(buffer, offset, count, callback, state); + this.EndWrite(ret); + return ret; + } + + public override void Close() + { + this.m_lockingModel.CloseFile(); + } + + public override int EndRead(IAsyncResult asyncResult) + { + this.AssertLocked(); + return this.m_readTotal; + } + + public override void EndWrite(IAsyncResult asyncResult) + { + // No-op, it has already been handled + } #endif #if NET_4_5 || NETSTANDARD1_3 - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - AssertLocked(); - return m_realStream.ReadAsync(buffer, offset, count, cancellationToken); - } - - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - AssertLocked(); - return base.WriteAsync(buffer, offset, count, cancellationToken); - } + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + this.AssertLocked(); + return this.m_realStream.ReadAsync(buffer, offset, count, cancellationToken); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + this.AssertLocked(); + return base.WriteAsync(buffer, offset, count, cancellationToken); + } #endif - public override void Flush() - { - AssertLocked(); - m_realStream.Flush(); - } - public override int Read(byte[] buffer, int offset, int count) - { - return m_realStream.Read(buffer, offset, count); - } - public override int ReadByte() - { - return m_realStream.ReadByte(); - } - public override long Seek(long offset, SeekOrigin origin) - { - AssertLocked(); - return m_realStream.Seek(offset, origin); - } - public override void SetLength(long value) - { - AssertLocked(); - m_realStream.SetLength(value); - } - void IDisposable.Dispose() - { + public override void Flush() + { + this.AssertLocked(); + this.m_realStream.Flush(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + return this.m_realStream.Read(buffer, offset, count); + } + + public override int ReadByte() + { + return this.m_realStream.ReadByte(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + this.AssertLocked(); + return this.m_realStream.Seek(offset, origin); + } + + public override void SetLength(long value) + { + this.AssertLocked(); + this.m_realStream.SetLength(value); + } + + void IDisposable.Dispose() + { #if NETSTANDARD1_3 Dispose(true); #else - Close(); + this.Close(); #endif - } - public override void Write(byte[] buffer, int offset, int count) - { - AssertLocked(); - m_realStream.Write(buffer, offset, count); - } - public override void WriteByte(byte value) - { - AssertLocked(); - m_realStream.WriteByte(value); - } - - // Properties - public override bool CanRead - { - get { return false; } - } - public override bool CanSeek - { - get - { - AssertLocked(); - return m_realStream.CanSeek; - } - } - public override bool CanWrite - { - get - { - AssertLocked(); - return m_realStream.CanWrite; - } - } - public override long Length - { - get - { - AssertLocked(); - return m_realStream.Length; - } - } - public override long Position - { - get - { - AssertLocked(); - return m_realStream.Position; - } - set - { - AssertLocked(); - m_realStream.Position = value; - } - } - - #endregion Override Implementation of Stream - - #region Locking Methods - - private void AssertLocked() - { - if (m_realStream == null) - { - throw new LockStateException("The file is not currently locked"); - } - } - - public bool AcquireLock() - { - bool ret = false; - lock (this) - { - if (m_lockLevel == 0) - { - // If lock is already acquired, nop - m_realStream = m_lockingModel.AcquireLock(); - } - if (m_realStream != null) - { - m_lockLevel++; - ret = true; - } - } - return ret; - } - - public void ReleaseLock() - { - lock (this) - { - m_lockLevel--; - if (m_lockLevel == 0) - { - // If already unlocked, nop - m_lockingModel.ReleaseLock(); - m_realStream = null; - } - } - } - - #endregion Locking Methods - } - - #endregion LockingStream Inner Class - - #region Locking Models - - /// - /// Locking model base class - /// - /// - /// - /// Base class for the locking models available to the derived loggers. - /// - /// - public abstract class LockingModelBase - { - private FileAppender m_appender = null; - - /// - /// Open the output file - /// - /// The filename to use - /// Whether to append to the file, or overwrite - /// The encoding to use - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// and . - /// - /// - public abstract void OpenFile(string filename, bool append, Encoding encoding); - - /// - /// Close the file - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public abstract void CloseFile(); - - /// - /// Initializes all resources used by this locking model. - /// - public abstract void ActivateOptions(); - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public abstract void OnClose(); - - /// - /// Acquire the lock on the file - /// - /// A stream that is ready to be written to. - /// - /// - /// Acquire the lock on the file in preparation for writing to it. - /// Return a stream pointing to the file. - /// must be called to release the lock on the output file. - /// - /// - public abstract Stream AcquireLock(); - - /// - /// Release the lock on the file - /// - /// - /// - /// Release the lock on the file. No further writes will be made to the - /// stream until is called again. - /// - /// - public abstract void ReleaseLock(); - - /// - /// Gets or sets the for this LockingModel - /// - /// - /// The for this LockingModel - /// - /// - /// - /// The file appender this locking model is attached to and working on - /// behalf of. - /// - /// - /// The file appender is used to locate the security context and the error handler to use. - /// - /// - /// The value of this property will be set before is - /// called. - /// - /// - public FileAppender CurrentAppender - { - get { return m_appender; } - set { m_appender = value; } - } - - /// - /// Helper method that creates a FileStream under CurrentAppender's SecurityContext. - /// - /// - /// - /// Typically called during OpenFile or AcquireLock. - /// - /// - /// If the directory portion of the does not exist, it is created - /// via Directory.CreateDirecctory. - /// - /// - /// - /// - /// - /// - protected Stream CreateStream(string filename, bool append, FileShare fileShare) - { - using (CurrentAppender.SecurityContext.Impersonate(this)) - { - // Ensure that the directory structure exists - string directoryFullName = Path.GetDirectoryName(filename); - - // Only create the directory if it does not exist - // doing this check here resolves some permissions failures - if (!Directory.Exists(directoryFullName)) - { - Directory.CreateDirectory(directoryFullName); - } - - FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create; - return new FileStream(filename, fileOpenMode, FileAccess.Write, fileShare); - } - } - - /// - /// Helper method to close under CurrentAppender's SecurityContext. - /// - /// - /// Does not set to null. - /// - /// - protected void CloseStream(Stream stream) - { - using (CurrentAppender.SecurityContext.Impersonate(this)) - { - stream.Close(); - } - } - } - - /// - /// Hold an exclusive lock on the output file - /// - /// - /// - /// Open the file once for writing and hold it open until is called. - /// Maintains an exclusive lock on the file during this time. - /// - /// - public class ExclusiveLock : LockingModelBase - { - private Stream m_stream = null; - - /// - /// Open the file specified and prepare for logging. - /// - /// The filename to use - /// Whether to append to the file, or overwrite - /// The encoding to use - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// and . - /// - /// - public override void OpenFile(string filename, bool append, Encoding encoding) - { - try - { - m_stream = CreateStream(filename, append, FileShare.Read); - } - catch (Exception e1) - { - CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); - } - } - - /// - /// Close the file - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public override void CloseFile() - { - CloseStream(m_stream); - m_stream = null; - } - - /// - /// Acquire the lock on the file - /// - /// A stream that is ready to be written to. - /// - /// - /// Does nothing. The lock is already taken - /// - /// - public override Stream AcquireLock() - { - return m_stream; - } - - /// - /// Release the lock on the file - /// - /// - /// - /// Does nothing. The lock will be released when the file is closed. - /// - /// - public override void ReleaseLock() - { - //NOP - } - - /// - /// Initializes all resources used by this locking model. - /// - public override void ActivateOptions() - { - //NOP - } - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public override void OnClose() - { - //NOP - } - } - - /// - /// Acquires the file lock for each write - /// - /// - /// - /// Opens the file once for each / cycle, - /// thus holding the lock for the minimal amount of time. This method of locking - /// is considerably slower than but allows - /// other processes to move/delete the log file whilst logging continues. - /// - /// - public class MinimalLock : LockingModelBase - { - private string m_filename; - private bool m_append; - private Stream m_stream = null; - - /// - /// Prepares to open the file when the first message is logged. - /// - /// The filename to use - /// Whether to append to the file, or overwrite - /// The encoding to use - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// and . - /// - /// - public override void OpenFile(string filename, bool append, Encoding encoding) - { - m_filename = filename; - m_append = append; - } - - /// - /// Close the file - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public override void CloseFile() - { - // NOP - } - - /// - /// Acquire the lock on the file - /// - /// A stream that is ready to be written to. - /// - /// - /// Acquire the lock on the file in preparation for writing to it. - /// Return a stream pointing to the file. - /// must be called to release the lock on the output file. - /// - /// - public override Stream AcquireLock() - { - if (m_stream == null) - { - try - { - m_stream = CreateStream(m_filename, m_append, FileShare.Read); - m_append = true; - } - catch (Exception e1) - { - CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + m_filename + ". " + e1.Message); - } - } - return m_stream; - } - - /// - /// Release the lock on the file - /// - /// - /// - /// Release the lock on the file. No further writes will be made to the - /// stream until is called again. - /// - /// - public override void ReleaseLock() - { - CloseStream(m_stream); - m_stream = null; - } - - /// - /// Initializes all resources used by this locking model. - /// - public override void ActivateOptions() - { - //NOP - } - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public override void OnClose() - { - //NOP - } - } + } + + public override void Write(byte[] buffer, int offset, int count) + { + this.AssertLocked(); + this.m_realStream.Write(buffer, offset, count); + } + + public override void WriteByte(byte value) + { + this.AssertLocked(); + this.m_realStream.WriteByte(value); + } + + // Properties + public override bool CanRead + { + get { return false; } + } + + public override bool CanSeek + { + get + { + this.AssertLocked(); + return this.m_realStream.CanSeek; + } + } + + public override bool CanWrite + { + get + { + this.AssertLocked(); + return this.m_realStream.CanWrite; + } + } + + public override long Length + { + get + { + this.AssertLocked(); + return this.m_realStream.Length; + } + } + + public override long Position + { + get + { + this.AssertLocked(); + return this.m_realStream.Position; + } + + set + { + this.AssertLocked(); + this.m_realStream.Position = value; + } + } + + private void AssertLocked() + { + if (this.m_realStream == null) + { + throw new LockStateException("The file is not currently locked"); + } + } + + public bool AcquireLock() + { + bool ret = false; + lock (this) + { + if (this.m_lockLevel == 0) + { + // If lock is already acquired, nop + this.m_realStream = this.m_lockingModel.AcquireLock(); + } + + if (this.m_realStream != null) + { + this.m_lockLevel++; + ret = true; + } + } + + return ret; + } + + public void ReleaseLock() + { + lock (this) + { + this.m_lockLevel--; + if (this.m_lockLevel == 0) + { + // If already unlocked, nop + this.m_lockingModel.ReleaseLock(); + this.m_realStream = null; + } + } + } + } + + /// + /// Locking model base class. + /// + /// + /// + /// Base class for the locking models available to the derived loggers. + /// + /// + public abstract class LockingModelBase + { + private FileAppender m_appender = null; + + /// + /// Open the output file. + /// + /// The filename to use. + /// Whether to append to the file, or overwrite. + /// The encoding to use. + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// and . + /// + /// + public abstract void OpenFile(string filename, bool append, Encoding encoding); + + /// + /// Close the file. + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public abstract void CloseFile(); + + /// + /// Initializes all resources used by this locking model. + /// + public abstract void ActivateOptions(); + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public abstract void OnClose(); + + /// + /// Acquire the lock on the file. + /// + /// A stream that is ready to be written to. + /// + /// + /// Acquire the lock on the file in preparation for writing to it. + /// Return a stream pointing to the file. + /// must be called to release the lock on the output file. + /// + /// + public abstract Stream AcquireLock(); + + /// + /// Release the lock on the file. + /// + /// + /// + /// Release the lock on the file. No further writes will be made to the + /// stream until is called again. + /// + /// + public abstract void ReleaseLock(); + + /// + /// Gets or sets the for this LockingModel. + /// + /// + /// The for this LockingModel. + /// + /// + /// + /// The file appender this locking model is attached to and working on + /// behalf of. + /// + /// + /// The file appender is used to locate the security context and the error handler to use. + /// + /// + /// The value of this property will be set before is + /// called. + /// + /// + public FileAppender CurrentAppender + { + get { return this.m_appender; } + set { this.m_appender = value; } + } + + /// + /// Helper method that creates a FileStream under CurrentAppender's SecurityContext. + /// + /// + /// + /// Typically called during OpenFile or AcquireLock. + /// + /// + /// If the directory portion of the does not exist, it is created + /// via Directory.CreateDirecctory. + /// + /// + /// + /// + /// + /// + protected Stream CreateStream(string filename, bool append, FileShare fileShare) + { + using (this.CurrentAppender.SecurityContext.Impersonate(this)) + { + // Ensure that the directory structure exists + string directoryFullName = Path.GetDirectoryName(filename); + + // Only create the directory if it does not exist + // doing this check here resolves some permissions failures + if (!Directory.Exists(directoryFullName)) + { + Directory.CreateDirectory(directoryFullName); + } + + FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create; + return new FileStream(filename, fileOpenMode, FileAccess.Write, fileShare); + } + } + + /// + /// Helper method to close under CurrentAppender's SecurityContext. + /// + /// + /// Does not set to null. + /// + /// + protected void CloseStream(Stream stream) + { + using (this.CurrentAppender.SecurityContext.Impersonate(this)) + { + stream.Close(); + } + } + } + + /// + /// Hold an exclusive lock on the output file. + /// + /// + /// + /// Open the file once for writing and hold it open until is called. + /// Maintains an exclusive lock on the file during this time. + /// + /// + public class ExclusiveLock : LockingModelBase + { + private Stream m_stream = null; + + /// + /// Open the file specified and prepare for logging. + /// + /// The filename to use. + /// Whether to append to the file, or overwrite. + /// The encoding to use. + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// and . + /// + /// + public override void OpenFile(string filename, bool append, Encoding encoding) + { + try + { + this.m_stream = this.CreateStream(filename, append, FileShare.Read); + } + catch (Exception e1) + { + this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); + } + } + + /// + /// Close the file. + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public override void CloseFile() + { + this.CloseStream(this.m_stream); + this.m_stream = null; + } + + /// + /// Acquire the lock on the file. + /// + /// A stream that is ready to be written to. + /// + /// + /// Does nothing. The lock is already taken. + /// + /// + public override Stream AcquireLock() + { + return this.m_stream; + } + + /// + /// Release the lock on the file. + /// + /// + /// + /// Does nothing. The lock will be released when the file is closed. + /// + /// + public override void ReleaseLock() + { + // NOP + } + + /// + /// Initializes all resources used by this locking model. + /// + public override void ActivateOptions() + { + // NOP + } + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public override void OnClose() + { + // NOP + } + } + + /// + /// Acquires the file lock for each write. + /// + /// + /// + /// Opens the file once for each / cycle, + /// thus holding the lock for the minimal amount of time. This method of locking + /// is considerably slower than but allows + /// other processes to move/delete the log file whilst logging continues. + /// + /// + public class MinimalLock : LockingModelBase + { + private string m_filename; + private bool m_append; + private Stream m_stream = null; + + /// + /// Prepares to open the file when the first message is logged. + /// + /// The filename to use. + /// Whether to append to the file, or overwrite. + /// The encoding to use. + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// and . + /// + /// + public override void OpenFile(string filename, bool append, Encoding encoding) + { + this.m_filename = filename; + this.m_append = append; + } + + /// + /// Close the file. + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public override void CloseFile() + { + // NOP + } + + /// + /// Acquire the lock on the file. + /// + /// A stream that is ready to be written to. + /// + /// + /// Acquire the lock on the file in preparation for writing to it. + /// Return a stream pointing to the file. + /// must be called to release the lock on the output file. + /// + /// + public override Stream AcquireLock() + { + if (this.m_stream == null) + { + try + { + this.m_stream = this.CreateStream(this.m_filename, this.m_append, FileShare.Read); + this.m_append = true; + } + catch (Exception e1) + { + this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + this.m_filename + ". " + e1.Message); + } + } + + return this.m_stream; + } + + /// + /// Release the lock on the file. + /// + /// + /// + /// Release the lock on the file. No further writes will be made to the + /// stream until is called again. + /// + /// + public override void ReleaseLock() + { + this.CloseStream(this.m_stream); + this.m_stream = null; + } + + /// + /// Initializes all resources used by this locking model. + /// + public override void ActivateOptions() + { + // NOP + } + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public override void OnClose() + { + // NOP + } + } #if !NETCF - /// - /// Provides cross-process file locking. - /// - /// Ron Grabowski - /// Steve Wranovsky - public class InterProcessLock : LockingModelBase - { - private Mutex m_mutex = null; - private Stream m_stream = null; - private int m_recursiveWatch = 0; - - /// - /// Open the file specified and prepare for logging. - /// - /// The filename to use - /// Whether to append to the file, or overwrite - /// The encoding to use - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// - and . - /// - /// + /// + /// Provides cross-process file locking. + /// + /// Ron Grabowski. + /// Steve Wranovsky. + public class InterProcessLock : LockingModelBase + { + private Mutex m_mutex = null; + private Stream m_stream = null; + private int m_recursiveWatch = 0; + + /// + /// Open the file specified and prepare for logging. + /// + /// The filename to use. + /// Whether to append to the file, or overwrite. + /// The encoding to use. + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// - and . + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] + [System.Security.SecuritySafeCritical] #endif - public override void OpenFile(string filename, bool append, Encoding encoding) - { - try - { - m_stream = CreateStream(filename, append, FileShare.ReadWrite); - } - catch (Exception e1) - { - CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); - } - } - - /// - /// Close the file - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public override void CloseFile() - { - try - { - CloseStream(m_stream); - m_stream = null; - } - finally - { - ReleaseLock(); - } - } - - /// - /// Acquire the lock on the file - /// - /// A stream that is ready to be written to. - /// - /// - /// Does nothing. The lock is already taken - /// - /// - public override Stream AcquireLock() - { - if (m_mutex != null) - { - // TODO: add timeout? - m_mutex.WaitOne(); - - // increment recursive watch - m_recursiveWatch++; - - // should always be true (and fast) for FileStream - if (m_stream != null) - { - if (m_stream.CanSeek) - { - m_stream.Seek(0, SeekOrigin.End); - } - } - else - { - // this can happen when the file appender cannot open a file for writing - } - } - else - { - CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to acquire lock! From here on things will be dangerous!"); - } - return m_stream; - } - - /// - /// Releases the lock and allows others to acquire a lock. - /// - public override void ReleaseLock() - { - if (m_mutex != null) - { - if (m_recursiveWatch > 0) - { - m_recursiveWatch--; - m_mutex.ReleaseMutex(); - } - } - else - { - CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to release the lock!"); - } - } - - /// - /// Initializes all resources used by this locking model. - /// - public override void ActivateOptions() - { - if (m_mutex == null) - { - string mutexFriendlyFilename = CurrentAppender.File - .Replace("\\", "_") - .Replace(":", "_") - .Replace("/", "_"); - - m_mutex = new Mutex(false, mutexFriendlyFilename); - } - else - { - CurrentAppender.ErrorHandler.Error("Programming error, mutex already initialized!"); - } - } - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public override void OnClose() - { - if (m_mutex != null) - { + public override void OpenFile(string filename, bool append, Encoding encoding) + { + try + { + this.m_stream = this.CreateStream(filename, append, FileShare.ReadWrite); + } + catch (Exception e1) + { + this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); + } + } + + /// + /// Close the file. + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public override void CloseFile() + { + try + { + this.CloseStream(this.m_stream); + this.m_stream = null; + } + finally + { + this.ReleaseLock(); + } + } + + /// + /// Acquire the lock on the file. + /// + /// A stream that is ready to be written to. + /// + /// + /// Does nothing. The lock is already taken. + /// + /// + public override Stream AcquireLock() + { + if (this.m_mutex != null) + { + // TODO: add timeout? + this.m_mutex.WaitOne(); + + // increment recursive watch + this.m_recursiveWatch++; + + // should always be true (and fast) for FileStream + if (this.m_stream != null) + { + if (this.m_stream.CanSeek) + { + this.m_stream.Seek(0, SeekOrigin.End); + } + } + else + { + // this can happen when the file appender cannot open a file for writing + } + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to acquire lock! From here on things will be dangerous!"); + } + + return this.m_stream; + } + + /// + /// Releases the lock and allows others to acquire a lock. + /// + public override void ReleaseLock() + { + if (this.m_mutex != null) + { + if (this.m_recursiveWatch > 0) + { + this.m_recursiveWatch--; + this.m_mutex.ReleaseMutex(); + } + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to release the lock!"); + } + } + + /// + /// Initializes all resources used by this locking model. + /// + public override void ActivateOptions() + { + if (this.m_mutex == null) + { + string mutexFriendlyFilename = this.CurrentAppender.File + .Replace("\\", "_") + .Replace(":", "_") + .Replace("/", "_"); + + this.m_mutex = new Mutex(false, mutexFriendlyFilename); + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, mutex already initialized!"); + } + } + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public override void OnClose() + { + if (this.m_mutex != null) + { #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - m_mutex.Dispose(); + this.m_mutex.Dispose(); #else m_mutex.Close(); #endif - m_mutex = null; - } - else - { - CurrentAppender.ErrorHandler.Error("Programming error, mutex not initialized!"); - } - } - } + this.m_mutex = null; + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, mutex not initialized!"); + } + } + } #endif - - #endregion Locking Models - - #region Public Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public FileAppender() - { - } - - /// - /// Construct a new appender using the layout, file and append mode. - /// - /// the layout to use with this appender - /// the full path to the file to write to - /// flag to indicate if the file should be appended to - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout, File & AppendToFile properties. Scheduled removal in v10.0.0.")] - public FileAppender(ILayout layout, string filename, bool append) - { - Layout = layout; - File = filename; - AppendToFile = append; - ActivateOptions(); - } - - /// - /// Construct a new appender using the layout and file specified. - /// The file will be appended to. - /// - /// the layout to use with this appender - /// the full path to the file to write to - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout & File properties. Scheduled removal in v10.0.0.")] - public FileAppender(ILayout layout, string filename) - : this(layout, filename, true) - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the path to the file that logging will be written to. - /// - /// - /// The path to the file that logging will be written to. - /// - /// - /// - /// If the path is relative it is taken as relative from - /// the application base directory. - /// - /// - virtual public string File - { - get { return m_fileName; } - set { m_fileName = value; } - } - - /// - /// Gets or sets a flag that indicates whether the file should be - /// appended to or overwritten. - /// - /// - /// Indicates whether the file should be appended to or overwritten. - /// - /// - /// - /// If the value is set to false then the file will be overwritten, if - /// it is set to true then the file will be appended to. - /// - /// The default value is true. - /// - public bool AppendToFile - { - get { return m_appendToFile; } - set { m_appendToFile = value; } - } - - /// - /// Gets or sets used to write to the file. - /// - /// - /// The used to write to the file. - /// - /// - /// - /// The default encoding set is - /// which is the encoding for the system's current ANSI code page. - /// - /// - public Encoding Encoding - { - get { return m_encoding; } - set { m_encoding = value; } - } - - /// - /// Gets or sets the used to write to the file. - /// - /// - /// The used to write to the file. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return m_securityContext; } - set { m_securityContext = value; } - } - + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public FileAppender() + { + } + + /// + /// Initializes a new instance of the class. + /// Construct a new appender using the layout, file and append mode. + /// + /// the layout to use with this appender. + /// the full path to the file to write to. + /// flag to indicate if the file should be appended to. + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout, File & AppendToFile properties. Scheduled removal in v10.0.0.")] + public FileAppender(ILayout layout, string filename, bool append) + { + this.Layout = layout; + this.File = filename; + this.AppendToFile = append; + this.ActivateOptions(); + } + + /// + /// Initializes a new instance of the class. + /// Construct a new appender using the layout and file specified. + /// The file will be appended to. + /// + /// the layout to use with this appender. + /// the full path to the file to write to. + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout & File properties. Scheduled removal in v10.0.0.")] + public FileAppender(ILayout layout, string filename) + : this(layout, filename, true) + { + } + + /// + /// Gets or sets the path to the file that logging will be written to. + /// + /// + /// The path to the file that logging will be written to. + /// + /// + /// + /// If the path is relative it is taken as relative from + /// the application base directory. + /// + /// + public virtual string File + { + get { return this.m_fileName; } + set { this.m_fileName = value; } + } + + /// + /// Gets or sets a value indicating whether gets or sets a flag that indicates whether the file should be + /// appended to or overwritten. + /// + /// + /// Indicates whether the file should be appended to or overwritten. + /// + /// + /// + /// If the value is set to false then the file will be overwritten, if + /// it is set to true then the file will be appended to. + /// + /// The default value is true. + /// + public bool AppendToFile + { + get { return this.m_appendToFile; } + set { this.m_appendToFile = value; } + } + + /// + /// Gets or sets used to write to the file. + /// + /// + /// The used to write to the file. + /// + /// + /// + /// The default encoding set is + /// which is the encoding for the system's current ANSI code page. + /// + /// + public Encoding Encoding + { + get { return this.m_encoding; } + set { this.m_encoding = value; } + } + + /// + /// Gets or sets the used to write to the file. + /// + /// + /// The used to write to the file. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } + #if NETCF /// /// Gets or sets the used to handle locking of the file. @@ -1035,472 +1035,444 @@ public SecurityContext SecurityContext /// /// #else - /// - /// Gets or sets the used to handle locking of the file. - /// - /// - /// The used to lock the file. - /// - /// - /// - /// Gets or sets the used to handle locking of the file. - /// - /// - /// There are three built in locking models, , and . - /// The first locks the file from the start of logging to the end, the - /// second locks only for the minimal amount of time when logging each message - /// and the last synchronizes processes using a named system wide Mutex. - /// - /// - /// The default locking model is the . - /// - /// + /// + /// Gets or sets the used to handle locking of the file. + /// + /// + /// The used to lock the file. + /// + /// + /// + /// Gets or sets the used to handle locking of the file. + /// + /// + /// There are three built in locking models, , and . + /// The first locks the file from the start of logging to the end, the + /// second locks only for the minimal amount of time when logging each message + /// and the last synchronizes processes using a named system wide Mutex. + /// + /// + /// The default locking model is the . + /// + /// #endif - public FileAppender.LockingModelBase LockingModel - { - get { return m_lockingModel; } - set { m_lockingModel = value; } - } - - #endregion Public Instance Properties - - #region Override implementation of AppenderSkeleton - - /// - /// Activate the options on the file appender. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// This will cause the file to be opened. - /// - /// - override public void ActivateOptions() - { - base.ActivateOptions(); - - if (m_securityContext == null) - { - m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - if (m_lockingModel == null) - { - m_lockingModel = new FileAppender.ExclusiveLock(); - } - - m_lockingModel.CurrentAppender = this; - m_lockingModel.ActivateOptions(); - - if (m_fileName != null) - { - using (SecurityContext.Impersonate(this)) - { - m_fileName = ConvertToFullPath(m_fileName.Trim()); - } - SafeOpenFile(m_fileName, m_appendToFile); - } - else - { - LogLog.Warn(declaringType, "FileAppender: File option not set for appender [" + Name + "]."); - LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?"); - } - } - - #endregion Override implementation of AppenderSkeleton - - #region Override implementation of TextWriterAppender - - /// - /// Closes any previously opened file and calls the parent's . - /// - /// - /// - /// Resets the filename and the file stream. - /// - /// - override protected void Reset() - { - base.Reset(); - m_fileName = null; - } - - /// - /// Close this appender instance. The underlying stream or writer is also closed. - /// - override protected void OnClose() - { - base.OnClose(); - m_lockingModel.OnClose(); - } - - /// - /// Called to initialize the file writer - /// - /// - /// - /// Will be called for each logged message until the file is - /// successfully opened. - /// - /// - override protected void PrepareWriter() - { - SafeOpenFile(m_fileName, m_appendToFile); - } - - /// - /// This method is called by the - /// method. - /// - /// The event to log. - /// - /// - /// Writes a log statement to the output stream if the output stream exists - /// and is writable. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - if (m_stream.AcquireLock()) - { - try - { - base.Append(loggingEvent); - } - finally - { - m_stream.ReleaseLock(); - } - } - } - - /// - /// This method is called by the - /// method. - /// - /// The array of events to log. - /// - /// - /// Acquires the output file locks once before writing all the events to - /// the stream. - /// - /// - override protected void Append(LoggingEvent[] loggingEvents) - { - if (m_stream.AcquireLock()) - { - try - { - base.Append(loggingEvents); - } - finally - { - m_stream.ReleaseLock(); - } - } - } - - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - protected override void WriteFooter() - { - if (m_stream != null) - { - //WriteFooter can be called even before a file is opened - m_stream.AcquireLock(); - try - { - base.WriteFooter(); - } - finally - { - m_stream.ReleaseLock(); - } - } - } - - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - protected override void WriteHeader() - { - if (m_stream != null) - { - if (m_stream.AcquireLock()) - { - try - { - base.WriteHeader(); - } - finally - { - m_stream.ReleaseLock(); - } - } - } - } - - /// - /// Closes the underlying . - /// - /// - /// - /// Closes the underlying . - /// - /// - protected override void CloseWriter() - { - if (m_stream != null) - { - m_stream.AcquireLock(); - try - { - base.CloseWriter(); - } - finally - { - m_stream.ReleaseLock(); - } - } - } - - #endregion Override implementation of TextWriterAppender - - #region Public Instance Methods - - /// - /// Closes the previously opened file. - /// - /// - /// - /// Writes the to the file and then - /// closes the file. - /// - /// - protected void CloseFile() - { - WriteFooterAndCloseWriter(); - } - - #endregion Public Instance Methods - - #region Protected Instance Methods - - /// - /// Sets and opens the file where the log output will go. The specified file must be writable. - /// - /// The path to the log file. Must be a fully qualified path. - /// If true will append to fileName. Otherwise will truncate fileName - /// - /// - /// Calls but guarantees not to throw an exception. - /// Errors are passed to the . - /// - /// - virtual protected void SafeOpenFile(string fileName, bool append) - { - try - { - OpenFile(fileName, append); - } - catch (Exception e) - { - ErrorHandler.Error("OpenFile(" + fileName + "," + append + ") call failed.", e, ErrorCode.FileOpenFailure); - } - } - - /// - /// Sets and opens the file where the log output will go. The specified file must be writable. - /// - /// The path to the log file. Must be a fully qualified path. - /// If true will append to fileName. Otherwise will truncate fileName - /// - /// - /// If there was already an opened file, then the previous file - /// is closed first. - /// - /// - /// This method will ensure that the directory structure - /// for the specified exists. - /// - /// - virtual protected void OpenFile(string fileName, bool append) - { - if (LogLog.IsErrorEnabled) - { - // Internal check that the fileName passed in is a rooted path - bool isPathRooted = false; - using (SecurityContext.Impersonate(this)) - { - isPathRooted = Path.IsPathRooted(fileName); - } - if (!isPathRooted) - { - LogLog.Error(declaringType, "INTERNAL ERROR. OpenFile(" + fileName + "): File name is not fully qualified."); - } - } - - lock (this) - { - Reset(); - - LogLog.Debug(declaringType, "Opening file for writing [" + fileName + "] append [" + append + "]"); - - // Save these for later, allowing retries if file open fails - m_fileName = fileName; - m_appendToFile = append; - - LockingModel.CurrentAppender = this; - LockingModel.OpenFile(fileName, append, m_encoding); - m_stream = new LockingStream(LockingModel); - - if (m_stream != null) - { - m_stream.AcquireLock(); - try - { - SetQWForFiles(m_stream); - } - finally - { - m_stream.ReleaseLock(); - } - } - - WriteHeader(); - } - } - - /// - /// Sets the quiet writer used for file output - /// - /// the file stream that has been opened for writing - /// - /// - /// This implementation of creates a - /// over the and passes it to the - /// method. - /// - /// - /// This method can be overridden by sub classes that want to wrap the - /// in some way, for example to encrypt the output - /// data using a System.Security.Cryptography.CryptoStream. - /// - /// - virtual protected void SetQWForFiles(Stream fileStream) - { - SetQWForFiles(new StreamWriter(fileStream, m_encoding)); - } - - /// - /// Sets the quiet writer being used. - /// - /// the writer over the file stream that has been opened for writing - /// - /// - /// This method can be overridden by sub classes that want to - /// wrap the in some way. - /// - /// - virtual protected void SetQWForFiles(TextWriter writer) - { - QuietWriter = new QuietTextWriter(writer, ErrorHandler); - } - - #endregion Protected Instance Methods - - #region Protected Static Methods - - /// - /// Convert a path into a fully qualified path. - /// - /// The path to convert. - /// The fully qualified path. - /// - /// - /// Converts the path specified to a fully - /// qualified path. If the path is relative it is - /// taken as relative from the application base - /// directory. - /// - /// - protected static string ConvertToFullPath(string path) - { - return SystemInfo.ConvertToFullPath(path); - } - - #endregion Protected Static Methods - - #region Private Instance Fields - - /// - /// Flag to indicate if we should append to the file - /// or overwrite the file. The default is to append. - /// - private bool m_appendToFile = true; - - /// - /// The name of the log file. - /// - private string m_fileName = null; - - /// - /// The encoding to use for the file stream. - /// - private Encoding m_encoding = Encoding.GetEncoding(0); - - /// - /// The security context to use for privileged calls - /// - private SecurityContext m_securityContext; - - /// - /// The stream to log to. Has added locking semantics - /// - private FileAppender.LockingStream m_stream = null; - - /// - /// The locking model to use - /// - private FileAppender.LockingModelBase m_lockingModel = new FileAppender.ExclusiveLock(); - - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the FileAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(FileAppender); - - #endregion Private Static Fields - } + public FileAppender.LockingModelBase LockingModel + { + get { return this.m_lockingModel; } + set { this.m_lockingModel = value; } + } + + /// + /// Activate the options on the file appender. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// This will cause the file to be opened. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.m_securityContext == null) + { + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + if (this.m_lockingModel == null) + { + this.m_lockingModel = new FileAppender.ExclusiveLock(); + } + + this.m_lockingModel.CurrentAppender = this; + this.m_lockingModel.ActivateOptions(); + + if (this.m_fileName != null) + { + using (this.SecurityContext.Impersonate(this)) + { + this.m_fileName = ConvertToFullPath(this.m_fileName.Trim()); + } + + this.SafeOpenFile(this.m_fileName, this.m_appendToFile); + } + else + { + LogLog.Warn(declaringType, "FileAppender: File option not set for appender [" + this.Name + "]."); + LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?"); + } + } + + /// + /// Closes any previously opened file and calls the parent's . + /// + /// + /// + /// Resets the filename and the file stream. + /// + /// + protected override void Reset() + { + base.Reset(); + this.m_fileName = null; + } + + /// + /// Close this appender instance. The underlying stream or writer is also closed. + /// + protected override void OnClose() + { + base.OnClose(); + this.m_lockingModel.OnClose(); + } + + /// + /// Called to initialize the file writer. + /// + /// + /// + /// Will be called for each logged message until the file is + /// successfully opened. + /// + /// + protected override void PrepareWriter() + { + this.SafeOpenFile(this.m_fileName, this.m_appendToFile); + } + + /// + /// This method is called by the + /// method. + /// + /// The event to log. + /// + /// + /// Writes a log statement to the output stream if the output stream exists + /// and is writable. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + if (this.m_stream.AcquireLock()) + { + try + { + base.Append(loggingEvent); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + + /// + /// This method is called by the + /// method. + /// + /// The array of events to log. + /// + /// + /// Acquires the output file locks once before writing all the events to + /// the stream. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) + { + if (this.m_stream.AcquireLock()) + { + try + { + base.Append(loggingEvents); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + protected override void WriteFooter() + { + if (this.m_stream != null) + { + // WriteFooter can be called even before a file is opened + this.m_stream.AcquireLock(); + try + { + base.WriteFooter(); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + protected override void WriteHeader() + { + if (this.m_stream != null) + { + if (this.m_stream.AcquireLock()) + { + try + { + base.WriteHeader(); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + } + + /// + /// Closes the underlying . + /// + /// + /// + /// Closes the underlying . + /// + /// + protected override void CloseWriter() + { + if (this.m_stream != null) + { + this.m_stream.AcquireLock(); + try + { + base.CloseWriter(); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + + /// + /// Closes the previously opened file. + /// + /// + /// + /// Writes the to the file and then + /// closes the file. + /// + /// + protected void CloseFile() + { + this.WriteFooterAndCloseWriter(); + } + + /// + /// Sets and opens the file where the log output will go. The specified file must be writable. + /// + /// The path to the log file. Must be a fully qualified path. + /// If true will append to fileName. Otherwise will truncate fileName. + /// + /// + /// Calls but guarantees not to throw an exception. + /// Errors are passed to the . + /// + /// + protected virtual void SafeOpenFile(string fileName, bool append) + { + try + { + this.OpenFile(fileName, append); + } + catch (Exception e) + { + this.ErrorHandler.Error("OpenFile(" + fileName + "," + append + ") call failed.", e, ErrorCode.FileOpenFailure); + } + } + + /// + /// Sets and opens the file where the log output will go. The specified file must be writable. + /// + /// The path to the log file. Must be a fully qualified path. + /// If true will append to fileName. Otherwise will truncate fileName. + /// + /// + /// If there was already an opened file, then the previous file + /// is closed first. + /// + /// + /// This method will ensure that the directory structure + /// for the specified exists. + /// + /// + protected virtual void OpenFile(string fileName, bool append) + { + if (LogLog.IsErrorEnabled) + { + // Internal check that the fileName passed in is a rooted path + bool isPathRooted = false; + using (this.SecurityContext.Impersonate(this)) + { + isPathRooted = Path.IsPathRooted(fileName); + } + + if (!isPathRooted) + { + LogLog.Error(declaringType, "INTERNAL ERROR. OpenFile(" + fileName + "): File name is not fully qualified."); + } + } + + lock (this) + { + this.Reset(); + + LogLog.Debug(declaringType, "Opening file for writing [" + fileName + "] append [" + append + "]"); + + // Save these for later, allowing retries if file open fails + this.m_fileName = fileName; + this.m_appendToFile = append; + + this.LockingModel.CurrentAppender = this; + this.LockingModel.OpenFile(fileName, append, this.m_encoding); + this.m_stream = new LockingStream(this.LockingModel); + + if (this.m_stream != null) + { + this.m_stream.AcquireLock(); + try + { + this.SetQWForFiles(this.m_stream); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + + this.WriteHeader(); + } + } + + /// + /// Sets the quiet writer used for file output. + /// + /// the file stream that has been opened for writing. + /// + /// + /// This implementation of creates a + /// over the and passes it to the + /// method. + /// + /// + /// This method can be overridden by sub classes that want to wrap the + /// in some way, for example to encrypt the output + /// data using a System.Security.Cryptography.CryptoStream. + /// + /// + protected virtual void SetQWForFiles(Stream fileStream) + { + this.SetQWForFiles(new StreamWriter(fileStream, this.m_encoding)); + } + + /// + /// Sets the quiet writer being used. + /// + /// the writer over the file stream that has been opened for writing. + /// + /// + /// This method can be overridden by sub classes that want to + /// wrap the in some way. + /// + /// + protected virtual void SetQWForFiles(TextWriter writer) + { + this.QuietWriter = new QuietTextWriter(writer, this.ErrorHandler); + } + + /// + /// Convert a path into a fully qualified path. + /// + /// The path to convert. + /// The fully qualified path. + /// + /// + /// Converts the path specified to a fully + /// qualified path. If the path is relative it is + /// taken as relative from the application base + /// directory. + /// + /// + protected static string ConvertToFullPath(string path) + { + return SystemInfo.ConvertToFullPath(path); + } + + /// + /// Flag to indicate if we should append to the file + /// or overwrite the file. The default is to append. + /// + private bool m_appendToFile = true; + + /// + /// The name of the log file. + /// + private string m_fileName = null; + + /// + /// The encoding to use for the file stream. + /// + private Encoding m_encoding = Encoding.GetEncoding(0); + + /// + /// The security context to use for privileged calls. + /// + private SecurityContext m_securityContext; + + /// + /// The stream to log to. Has added locking semantics. + /// + private FileAppender.LockingStream m_stream = null; + + /// + /// The locking model to use. + /// + private FileAppender.LockingModelBase m_lockingModel = new FileAppender.ExclusiveLock(); + + /// + /// The fully qualified type of the FileAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(FileAppender); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs index 55039e3461d..3aba0389fc1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs @@ -1,283 +1,268 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Util; -using log4net.Layout; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// This appender forwards logging events to attached appenders. - /// - /// - /// - /// The forwarding appender can be used to specify different thresholds - /// and filters for the same appender at different locations within the hierarchy. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class ForwardingAppender : AppenderSkeleton, IAppenderAttachable - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public ForwardingAppender() - { - } - - #endregion Public Instance Constructors - - #region Override implementation of AppenderSkeleton - - /// - /// Closes the appender and releases resources. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - override protected void OnClose() - { - // Remove all the attached appenders - lock(this) - { - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.RemoveAllAppenders(); - } - } - } - - /// - /// Forward the logging event to the attached appenders - /// - /// The event to log. - /// - /// - /// Delivers the logging event to all the attached appenders. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - // Pass the logging event on the the attached appenders - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); - } - } - - /// - /// Forward the logging events to the attached appenders - /// - /// The array of events to log. - /// - /// - /// Delivers the logging events to all the attached appenders. - /// - /// - override protected void Append(LoggingEvent[] loggingEvents) - { - // Pass the logging event on the the attached appenders - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvents); - } - } - - #endregion Override implementation of AppenderSkeleton - - #region Implementation of IAppenderAttachable - - /// - /// Adds an to the list of appenders of this - /// instance. - /// - /// The to add to this appender. - /// - /// - /// If the specified is already in the list of - /// appenders, then it won't be added again. - /// - /// - virtual public void AddAppender(IAppender newAppender) - { - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } - lock(this) - { - if (m_appenderAttachedImpl == null) - { - m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); - } - m_appenderAttachedImpl.AddAppender(newAppender); - } - } - - /// - /// Gets the appenders contained in this appender as an - /// . - /// - /// - /// If no appenders can be found, then an - /// is returned. - /// - /// - /// A collection of the appenders in this appender. - /// - virtual public AppenderCollection Appenders - { - get - { - lock(this) - { - if (m_appenderAttachedImpl == null) - { - return AppenderCollection.EmptyCollection; - } - else - { - return m_appenderAttachedImpl.Appenders; - } - } - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// This appender forwards logging events to attached appenders. + /// + /// + /// + /// The forwarding appender can be used to specify different thresholds + /// and filters for the same appender at different locations within the hierarchy. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class ForwardingAppender : AppenderSkeleton, IAppenderAttachable + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public ForwardingAppender() + { + } + + /// + /// Closes the appender and releases resources. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + protected override void OnClose() + { + // Remove all the attached appenders + lock (this) + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + } + } + } - /// - /// Looks for the appender with the specified name. - /// - /// The name of the appender to lookup. - /// - /// The appender with the specified name, or null. - /// - /// - /// - /// Get the named appender attached to this appender. - /// - /// - virtual public IAppender GetAppender(string name) - { - lock(this) - { - if (m_appenderAttachedImpl == null || name == null) - { - return null; - } + /// + /// Forward the logging event to the attached appenders. + /// + /// The event to log. + /// + /// + /// Delivers the logging event to all the attached appenders. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // Pass the logging event on the the attached appenders + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); + } + } - return m_appenderAttachedImpl.GetAppender(name); - } - } + /// + /// Forward the logging events to the attached appenders. + /// + /// The array of events to log. + /// + /// + /// Delivers the logging events to all the attached appenders. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) + { + // Pass the logging event on the the attached appenders + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvents); + } + } + + /// + /// Adds an to the list of appenders of this + /// instance. + /// + /// The to add to this appender. + /// + /// + /// If the specified is already in the list of + /// appenders, then it won't be added again. + /// + /// + public virtual void AddAppender(IAppender newAppender) + { + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } + + lock (this) + { + if (this.m_appenderAttachedImpl == null) + { + this.m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); + } + + this.m_appenderAttachedImpl.AddAppender(newAppender); + } + } - /// - /// Removes all previously added appenders from this appender. - /// - /// - /// - /// This is useful when re-reading configuration information. - /// - /// - virtual public void RemoveAllAppenders() - { - lock(this) - { - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.RemoveAllAppenders(); - m_appenderAttachedImpl = null; - } - } - } + /// + /// Gets the appenders contained in this appender as an + /// . + /// + /// + /// If no appenders can be found, then an + /// is returned. + /// + /// + /// A collection of the appenders in this appender. + /// + public virtual AppenderCollection Appenders + { + get + { + lock (this) + { + if (this.m_appenderAttachedImpl == null) + { + return AppenderCollection.EmptyCollection; + } + else + { + return this.m_appenderAttachedImpl.Appenders; + } + } + } + } - /// - /// Removes the specified appender from the list of appenders. - /// - /// The appender to remove. - /// The appender removed from the list - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - virtual public IAppender RemoveAppender(IAppender appender) - { - lock(this) - { - if (appender != null && m_appenderAttachedImpl != null) - { - return m_appenderAttachedImpl.RemoveAppender(appender); - } - } - return null; - } + /// + /// Looks for the appender with the specified name. + /// + /// The name of the appender to lookup. + /// + /// The appender with the specified name, or null. + /// + /// + /// + /// Get the named appender attached to this appender. + /// + /// + public virtual IAppender GetAppender(string name) + { + lock (this) + { + if (this.m_appenderAttachedImpl == null || name == null) + { + return null; + } - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - virtual public IAppender RemoveAppender(string name) - { - lock(this) - { - if (name != null && m_appenderAttachedImpl != null) - { - return m_appenderAttachedImpl.RemoveAppender(name); - } - } - return null; - } - - #endregion Implementation of IAppenderAttachable + return this.m_appenderAttachedImpl.GetAppender(name); + } + } - #region Private Instance Fields + /// + /// Removes all previously added appenders from this appender. + /// + /// + /// + /// This is useful when re-reading configuration information. + /// + /// + public virtual void RemoveAllAppenders() + { + lock (this) + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + this.m_appenderAttachedImpl = null; + } + } + } - /// - /// Implementation of the interface - /// - private AppenderAttachedImpl m_appenderAttachedImpl; + /// + /// Removes the specified appender from the list of appenders. + /// + /// The appender to remove. + /// The appender removed from the list. + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(IAppender appender) + { + lock (this) + { + if (appender != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(appender); + } + } + + return null; + } - #endregion Private Instance Fields - } + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list. + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(string name) + { + lock (this) + { + if (name != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(name); + } + } + + return null; + } + + /// + /// Implementation of the interface. + /// + private AppenderAttachedImpl m_appenderAttachedImpl; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs index 06a5da73ba4..78a5457b3b9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs @@ -1,82 +1,79 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using log4net.Filter; -using log4net.Layout; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Implement this interface for your own strategies for printing log statements. - /// - /// - /// - /// Implementors should consider extending the - /// class which provides a default implementation of this interface. - /// - /// - /// Appenders can also implement the interface. Therefore - /// they would require that the method - /// be called after the appenders properties have been configured. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IAppender - { - /// - /// Closes the appender and releases resources. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - void Close(); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using log4net.Core; + using log4net.Filter; + using log4net.Layout; + + /// + /// Implement this interface for your own strategies for printing log statements. + /// + /// + /// + /// Implementors should consider extending the + /// class which provides a default implementation of this interface. + /// + /// + /// Appenders can also implement the interface. Therefore + /// they would require that the method + /// be called after the appenders properties have been configured. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IAppender + { + /// + /// Closes the appender and releases resources. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + void Close(); - /// - /// Log the logging event in Appender specific way. - /// - /// The event to log - /// - /// - /// This method is called to log a message into this appender. - /// - /// - void DoAppend(LoggingEvent loggingEvent); + /// + /// Log the logging event in Appender specific way. + /// + /// The event to log. + /// + /// + /// This method is called to log a message into this appender. + /// + /// + void DoAppend(LoggingEvent loggingEvent); - /// - /// Gets or sets the name of this appender. - /// - /// The name of the appender. - /// - /// The name uniquely identifies the appender. - /// - string Name { get; set; } - } + /// + /// Gets or sets the name of this appender. + /// + /// The name of the appender. + /// + /// The name uniquely identifies the appender. + /// + string Name { get; set; } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs index c9e9bd3b4e0..eeba2989703 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs @@ -1,52 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Interface for appenders that support bulk logging. - /// - /// - /// - /// This interface extends the interface to - /// support bulk logging of objects. Appenders - /// should only implement this interface if they can bulk log efficiently. - /// - /// - /// Nicko Cadell - public interface IBulkAppender : IAppender - { - /// - /// Log the array of logging events in Appender specific way. - /// - /// The events to log - /// - /// - /// This method is called to log an array of events into this appender. - /// - /// - void DoAppend(LoggingEvent[] loggingEvents); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using log4net.Core; + + /// + /// Interface for appenders that support bulk logging. + /// + /// + /// + /// This interface extends the interface to + /// support bulk logging of objects. Appenders + /// should only implement this interface if they can bulk log efficiently. + /// + /// + /// Nicko Cadell. + public interface IBulkAppender : IAppender + { + /// + /// Log the array of logging events in Appender specific way. + /// + /// The events to log. + /// + /// + /// This method is called to log an array of events into this appender. + /// + /// + void DoAppend(LoggingEvent[] loggingEvents); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs index 411fbab1990..4d81ef9aaea 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs @@ -1,30 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + /// /// Interface that can be implemented by Appenders that buffer logging data and expose a method. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs index aa25f5e1688..ca2e165de88 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for Marshal.StringToHGlobalAnsi // SSCLI 1.0 has no support for Marshal.StringToHGlobalAnsi @@ -27,585 +25,543 @@ using System; using System.Runtime.InteropServices; - -using log4net.Core; + using log4net.Appender; -using log4net.Util; +using log4net.Core; using log4net.Layout; +using log4net.Util; -namespace log4net.Appender +namespace log4net.Appender { - /// - /// Logs events to a local syslog service. - /// - /// - /// - /// This appender uses the POSIX libc library functions openlog, syslog, and closelog. - /// If these functions are not available on the local system then this appender will not work! - /// - /// - /// The functions openlog, syslog, and closelog are specified in SUSv2 and - /// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service. - /// - /// - /// This appender talks to a local syslog service. If you need to log to a remote syslog - /// daemon and you cannot configure your local syslog service to do this you may be - /// able to use the to log via UDP. - /// - /// - /// Syslog messages must have a facility and and a severity. The severity - /// is derived from the Level of the logging event. - /// The facility must be chosen from the set of defined syslog - /// values. The facilities list is predefined - /// and cannot be extended. - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - /// Rob Lyon - /// Nicko Cadell - public class LocalSyslogAppender : AppenderSkeleton - { - #region Enumerations - - /// - /// syslog severities - /// - /// - /// - /// The log4net Level maps to a syslog severity using the - /// method and the - /// class. The severity is set on . - /// - /// - public enum SyslogSeverity - { - /// - /// system is unusable - /// - Emergency = 0, - - /// - /// action must be taken immediately - /// - Alert = 1, - - /// - /// critical conditions - /// - Critical = 2, - - /// - /// error conditions - /// - Error = 3, - - /// - /// warning conditions - /// - Warning = 4, - - /// - /// normal but significant condition - /// - Notice = 5, - - /// - /// informational - /// - Informational = 6, - - /// - /// debug-level messages - /// - Debug = 7 - }; - - /// - /// syslog facilities - /// - /// - /// - /// The syslog facility defines which subsystem the logging comes from. - /// This is set on the property. - /// - /// - public enum SyslogFacility - { - /// - /// kernel messages - /// - Kernel = 0, - - /// - /// random user-level messages - /// - User = 1, - - /// - /// mail system - /// - Mail = 2, - - /// - /// system daemons - /// - Daemons = 3, - - /// - /// security/authorization messages - /// - Authorization = 4, - - /// - /// messages generated internally by syslogd - /// - Syslog = 5, - - /// - /// line printer subsystem - /// - Printer = 6, - - /// - /// network news subsystem - /// - News = 7, - - /// - /// UUCP subsystem - /// - Uucp = 8, - - /// - /// clock (cron/at) daemon - /// - Clock = 9, - - /// - /// security/authorization messages (private) - /// - Authorization2 = 10, - - /// - /// ftp daemon - /// - Ftp = 11, - - /// - /// NTP subsystem - /// - Ntp = 12, - - /// - /// log audit - /// - Audit = 13, - - /// - /// log alert - /// - Alert = 14, - - /// - /// clock daemon - /// - Clock2 = 15, - - /// - /// reserved for local use - /// - Local0 = 16, - - /// - /// reserved for local use - /// - Local1 = 17, - - /// - /// reserved for local use - /// - Local2 = 18, - - /// - /// reserved for local use - /// - Local3 = 19, - - /// - /// reserved for local use - /// - Local4 = 20, - - /// - /// reserved for local use - /// - Local5 = 21, - - /// - /// reserved for local use - /// - Local6 = 22, - - /// - /// reserved for local use - /// - Local7 = 23 - } - - #endregion // Enumerations - - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// This instance of the class is set up to write - /// to a local syslog service. - /// - public LocalSyslogAppender() - { - } - - #endregion // Public Instance Constructors - - #region Public Instance Properties - - /// - /// Message identity - /// - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - public string Identity - { - get { return m_identity; } - set { m_identity = value; } - } - - /// - /// Syslog facility - /// - /// - /// Set to one of the values. The list of - /// facilities is predefined and cannot be extended. The default value - /// is . - /// - public SyslogFacility Facility - { - get { return m_facility; } - set { m_facility = value; } - } - - #endregion // Public Instance Properties - - /// - /// Add a mapping of level to severity - /// - /// The mapping to add - /// - /// - /// Adds a to this appender. - /// - /// - public void AddMapping(LevelSeverity mapping) - { - m_levelMapping.Add(mapping); - } - - #region IOptionHandler Implementation - - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// + /// + /// Logs events to a local syslog service. + /// + /// + /// + /// This appender uses the POSIX libc library functions openlog, syslog, and closelog. + /// If these functions are not available on the local system then this appender will not work!. + /// + /// + /// The functions openlog, syslog, and closelog are specified in SUSv2 and + /// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service. + /// + /// + /// This appender talks to a local syslog service. If you need to log to a remote syslog + /// daemon and you cannot configure your local syslog service to do this you may be + /// able to use the to log via UDP. + /// + /// + /// Syslog messages must have a facility and and a severity. The severity + /// is derived from the Level of the logging event. + /// The facility must be chosen from the set of defined syslog + /// values. The facilities list is predefined + /// and cannot be extended. + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + /// Rob Lyon. + /// Nicko Cadell. + public class LocalSyslogAppender : AppenderSkeleton + { + /// + /// syslog severities. + /// + /// + /// + /// The log4net Level maps to a syslog severity using the + /// method and the + /// class. The severity is set on . + /// + /// + public enum SyslogSeverity + { + /// + /// system is unusable + /// + Emergency = 0, + + /// + /// action must be taken immediately + /// + Alert = 1, + + /// + /// critical conditions + /// + Critical = 2, + + /// + /// error conditions + /// + Error = 3, + + /// + /// warning conditions + /// + Warning = 4, + + /// + /// normal but significant condition + /// + Notice = 5, + + /// + /// informational + /// + Informational = 6, + + /// + /// debug-level messages + /// + Debug = 7, + } + + /// + /// syslog facilities. + /// + /// + /// + /// The syslog facility defines which subsystem the logging comes from. + /// This is set on the property. + /// + /// + public enum SyslogFacility + { + /// + /// kernel messages + /// + Kernel = 0, + + /// + /// random user-level messages + /// + User = 1, + + /// + /// mail system + /// + Mail = 2, + + /// + /// system daemons + /// + Daemons = 3, + + /// + /// security/authorization messages + /// + Authorization = 4, + + /// + /// messages generated internally by syslogd + /// + Syslog = 5, + + /// + /// line printer subsystem + /// + Printer = 6, + + /// + /// network news subsystem + /// + News = 7, + + /// + /// UUCP subsystem + /// + Uucp = 8, + + /// + /// clock (cron/at) daemon + /// + Clock = 9, + + /// + /// security/authorization messages (private) + /// + Authorization2 = 10, + + /// + /// ftp daemon + /// + Ftp = 11, + + /// + /// NTP subsystem + /// + Ntp = 12, + + /// + /// log audit + /// + Audit = 13, + + /// + /// log alert + /// + Alert = 14, + + /// + /// clock daemon + /// + Clock2 = 15, + + /// + /// reserved for local use + /// + Local0 = 16, + + /// + /// reserved for local use + /// + Local1 = 17, + + /// + /// reserved for local use + /// + Local2 = 18, + + /// + /// reserved for local use + /// + Local3 = 19, + + /// + /// reserved for local use + /// + Local4 = 20, + + /// + /// reserved for local use + /// + Local5 = 21, + + /// + /// reserved for local use + /// + Local6 = 22, + + /// + /// reserved for local use + /// + Local7 = 23, + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// This instance of the class is set up to write + /// to a local syslog service. + /// + public LocalSyslogAppender() + { + } + + /// + /// Gets or sets message identity. + /// + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + public string Identity + { + get { return this.m_identity; } + set { this.m_identity = value; } + } + + /// + /// Gets or sets syslog facility. + /// + /// + /// Set to one of the values. The list of + /// facilities is predefined and cannot be extended. The default value + /// is . + /// + public SyslogFacility Facility + { + get { return this.m_facility; } + set { this.m_facility = value; } + } + + /// + /// Add a mapping of level to severity. + /// + /// The mapping to add. + /// + /// + /// Adds a to this appender. + /// + /// + public void AddMapping(LevelSeverity mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #endif public override void ActivateOptions() - { - base.ActivateOptions(); - - m_levelMapping.ActivateOptions(); - - string identString = m_identity; - if (identString == null) - { - // Set to app name by default - identString = SystemInfo.ApplicationFriendlyName; - } - - // create the native heap ansi string. Note this is a copy of our string - // so we do not need to hold on to the string itself, holding on to the - // handle will keep the heap ansi string alive. - m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString); - - // open syslog - openlog(m_handleToIdentity, 1, m_facility); - } - - #endregion // IOptionHandler Implementation - - #region AppenderSkeleton Implementation - - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to a remote syslog daemon. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// + { + base.ActivateOptions(); + + this.m_levelMapping.ActivateOptions(); + + string identString = this.m_identity; + if (identString == null) + { + // Set to app name by default + identString = SystemInfo.ApplicationFriendlyName; + } + + // create the native heap ansi string. Note this is a copy of our string + // so we do not need to hold on to the string itself, holding on to the + // handle will keep the heap ansi string alive. + this.m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString); + + // open syslog + openlog(this.m_handleToIdentity, 1, this.m_facility); + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to a remote syslog daemon. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #endif #if !NETSTANDARD1_3 [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] #endif - protected override void Append(LoggingEvent loggingEvent) - { - int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level)); - string message = RenderLoggingEvent(loggingEvent); - - // Call the local libc syslog method - // The second argument is a printf style format string - syslog(priority, "%s", message); - } - - /// - /// Close the syslog when the appender is closed - /// - /// - /// - /// Close the syslog when the appender is closed - /// - /// + protected override void Append(LoggingEvent loggingEvent) + { + int priority = GeneratePriority(this.m_facility, this.GetSeverity(loggingEvent.Level)); + string message = this.RenderLoggingEvent(loggingEvent); + + // Call the local libc syslog method + // The second argument is a printf style format string + syslog(priority, "%s", message); + } + + /// + /// Close the syslog when the appender is closed. + /// + /// + /// + /// Close the syslog when the appender is closed. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #endif protected override void OnClose() - { - base.OnClose(); - - try - { - // close syslog - closelog(); - } - catch(DllNotFoundException) - { - // Ignore dll not found at this point - } - - if (m_handleToIdentity != IntPtr.Zero) - { - // free global ident - Marshal.FreeHGlobal(m_handleToIdentity); - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion // AppenderSkeleton Implementation - - #region Protected Members - - /// - /// Translates a log4net level to a syslog severity. - /// - /// A log4net level. - /// A syslog severity. - /// - /// - /// Translates a log4net level to a syslog severity. - /// - /// - virtual protected SyslogSeverity GetSeverity(Level level) - { - LevelSeverity levelSeverity = m_levelMapping.Lookup(level) as LevelSeverity; - if (levelSeverity != null) - { - return levelSeverity.Severity; - } - - // - // Fallback to sensible default values - // - - if (level >= Level.Alert) - { - return SyslogSeverity.Alert; - } - else if (level >= Level.Critical) - { - return SyslogSeverity.Critical; - } - else if (level >= Level.Error) - { - return SyslogSeverity.Error; - } - else if (level >= Level.Warn) - { - return SyslogSeverity.Warning; - } - else if (level >= Level.Notice) - { - return SyslogSeverity.Notice; - } - else if (level >= Level.Info) - { - return SyslogSeverity.Informational; - } - // Default setting - return SyslogSeverity.Debug; - } - - #endregion // Protected Members - - #region Public Static Members - - /// - /// Generate a syslog priority. - /// - /// The syslog facility. - /// The syslog severity. - /// A syslog priority. - private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) - { - return ((int)facility * 8) + (int)severity; - } - - #endregion // Public Static Members - - #region Private Instances Fields - - /// - /// The facility. The default facility is . - /// - private SyslogFacility m_facility = SyslogFacility.User; - - /// - /// The message identity - /// - private string m_identity; - - /// - /// Marshaled handle to the identity string. We have to hold on to the - /// string as the openlog and syslog APIs just hold the - /// pointer to the ident and dereference it for each log message. - /// - private IntPtr m_handleToIdentity = IntPtr.Zero; - - /// - /// Mapping from level object to syslog severity - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - #endregion // Private Instances Fields - - #region External Members - - /// - /// Open connection to system logger. - /// - [DllImport("libc")] - private static extern void openlog(IntPtr ident, int option, SyslogFacility facility); - - /// - /// Generate a log message. - /// - /// - /// - /// The libc syslog method takes a format string and a variable argument list similar - /// to the classic printf function. As this type of vararg list is not supported - /// by C# we need to specify the arguments explicitly. Here we have specified the - /// format string with a single message argument. The caller must set the format - /// string to "%s". - /// - /// - [DllImport("libc", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] - private static extern void syslog(int priority, string format, string message); - - /// - /// Close descriptor used to write to system logger. - /// - [DllImport("libc")] - private static extern void closelog(); - - #endregion // External Members - - #region LevelSeverity LevelMapping Entry - - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - public class LevelSeverity : LevelMappingEntry - { - private SyslogSeverity m_severity; - - /// - /// The mapped syslog severity for the specified level - /// - /// - /// - /// Required property. - /// The mapped syslog severity for the specified level - /// - /// - public SyslogSeverity Severity - { - get { return m_severity; } - set { m_severity = value; } - } - } - - #endregion // LevelSeverity LevelMapping Entry - } + { + base.OnClose(); + + try + { + // close syslog + closelog(); + } + catch (DllNotFoundException) + { + // Ignore dll not found at this point + } + + if (this.m_handleToIdentity != IntPtr.Zero) + { + // free global ident + Marshal.FreeHGlobal(this.m_handleToIdentity); + } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Translates a log4net level to a syslog severity. + /// + /// A log4net level. + /// A syslog severity. + /// + /// + /// Translates a log4net level to a syslog severity. + /// + /// + protected virtual SyslogSeverity GetSeverity(Level level) + { + LevelSeverity levelSeverity = this.m_levelMapping.Lookup(level) as LevelSeverity; + if (levelSeverity != null) + { + return levelSeverity.Severity; + } + + // Fallback to sensible default values + if (level >= Level.Alert) + { + return SyslogSeverity.Alert; + } + else if (level >= Level.Critical) + { + return SyslogSeverity.Critical; + } + else if (level >= Level.Error) + { + return SyslogSeverity.Error; + } + else if (level >= Level.Warn) + { + return SyslogSeverity.Warning; + } + else if (level >= Level.Notice) + { + return SyslogSeverity.Notice; + } + else if (level >= Level.Info) + { + return SyslogSeverity.Informational; + } + + // Default setting + return SyslogSeverity.Debug; + } + + /// + /// Generate a syslog priority. + /// + /// The syslog facility. + /// The syslog severity. + /// A syslog priority. + private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) + { + return ((int)facility * 8) + (int)severity; + } + + /// + /// The facility. The default facility is . + /// + private SyslogFacility m_facility = SyslogFacility.User; + + /// + /// The message identity. + /// + private string m_identity; + + /// + /// Marshaled handle to the identity string. We have to hold on to the + /// string as the openlog and syslog APIs just hold the + /// pointer to the ident and dereference it for each log message. + /// + private IntPtr m_handleToIdentity = IntPtr.Zero; + + /// + /// Mapping from level object to syslog severity. + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// Open connection to system logger. + /// + [DllImport("libc")] + private static extern void openlog(IntPtr ident, int option, SyslogFacility facility); + + /// + /// Generate a log message. + /// + /// + /// + /// The libc syslog method takes a format string and a variable argument list similar + /// to the classic printf function. As this type of vararg list is not supported + /// by C# we need to specify the arguments explicitly. Here we have specified the + /// format string with a single message argument. The caller must set the format + /// string to "%s". + /// + /// + [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] + private static extern void syslog(int priority, string format, string message); + + /// + /// Close descriptor used to write to system logger. + /// + [DllImport("libc")] + private static extern void closelog(); + + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + public class LevelSeverity : LevelMappingEntry + { + private SyslogSeverity m_severity; + + /// + /// Gets or sets the mapped syslog severity for the specified level. + /// + /// + /// + /// Required property. + /// The mapped syslog severity for the specified level. + /// + /// + public SyslogSeverity Severity + { + get { return this.m_severity; } + set { this.m_severity = value; } + } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs index 55630931691..c5fb431ebcd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,12 +18,11 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // Compatibility: -// http://msdn.microsoft.com/en-us/library/system.console.foregroundcolor.aspx +// http://msdn.microsoft.com/en-us/library/system.console.foregroundcolor.aspx // Disable for unsupported targets -#if !NETCF +#if !NETCF #if !SSCLI #if !CLI_1_0 #if !MONO_1_0 @@ -46,300 +44,319 @@ // For this reason, we always reset the colors and only set those // explicitly specified in the configuration (Console.BackgroundColor // isn't set if ommited). - using System; + using log4net.Util; namespace log4net.Appender { - /// - /// Appends colorful logging events to the console, using the .NET 2 - /// built-in capabilities. - /// - /// - /// - /// ManagedColoredConsoleAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. It also allows the color of a specific type of message to be set. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// When configuring the colored console appender, mappings should be - /// specified to map logging levels to colors. For example: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The Level is the standard log4net logging level while - /// ForeColor and BackColor are the values of - /// enumeration. - /// - /// - /// Based on the ColoredConsoleAppender - /// - /// - /// Rick Hobbs - /// Nicko Cadell - /// Pavlos Touboulidis - public class ManagedColoredConsoleAppender: AppenderSkeleton - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public ManagedColoredConsoleAppender() - { - } - - #region Public Instance Properties - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - virtual public string Target - { - get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; } - set - { - string v = value.Trim(); - - if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) - { - m_writeToErrorStream = true; - } - else - { - m_writeToErrorStream = false; - } - } - } + /// + /// Appends colorful logging events to the console, using the .NET 2 + /// built-in capabilities. + /// + /// + /// + /// ManagedColoredConsoleAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. It also allows the color of a specific type of message to be set. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// When configuring the colored console appender, mappings should be + /// specified to map logging levels to colors. For example: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// The Level is the standard log4net logging level while + /// ForeColor and BackColor are the values of + /// enumeration. + /// + /// + /// Based on the ColoredConsoleAppender. + /// + /// + /// Rick Hobbs. + /// Nicko Cadell. + /// Pavlos Touboulidis. + public class ManagedColoredConsoleAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public ManagedColoredConsoleAppender() + { + } + + /// + /// Gets or sets target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + + set + { + string v = value.Trim(); - /// - /// Add a mapping of level to color - done by the config file - /// - /// The mapping to add - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the foreground and background colors - /// for a level. - /// - /// - public void AddMapping(LevelColors mapping) - { - m_levelMapping.Add(mapping); - } - #endregion // Public Instance Properties + if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } + } - #region Override implementation of AppenderSkeleton - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - override protected void Append(log4net.Core.LoggingEvent loggingEvent) - { - System.IO.TextWriter writer; - - if (m_writeToErrorStream) - writer = Console.Error; - else - writer = Console.Out; - - // Reset color - Console.ResetColor(); - - // see if there is a specified lookup - LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; - if (levelColors != null) - { - // if the backColor has been explicitly set - if (levelColors.HasBackColor) - Console.BackgroundColor = levelColors.BackColor; - // if the foreColor has been explicitly set - if (levelColors.HasForeColor) - Console.ForegroundColor = levelColors.ForeColor; - } - - // Render the event to a string - string strLoggingMessage = RenderLoggingEvent(loggingEvent); - // and write it - writer.Write(strLoggingMessage); + /// + /// Add a mapping of level to color - done by the config file. + /// + /// The mapping to add. + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the foreground and background colors + /// for a level. + /// + /// + public void AddMapping(LevelColors mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(log4net.Core.LoggingEvent loggingEvent) + { + System.IO.TextWriter writer; - // Reset color again - Console.ResetColor(); - } + if (this.m_writeToErrorStream) + { + writer = Console.Error; + } + else + { + writer = Console.Out; + } + + // Reset color + Console.ResetColor(); - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } + // see if there is a specified lookup + LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; + if (levelColors != null) + { + // if the backColor has been explicitly set + if (levelColors.HasBackColor) + { + Console.BackgroundColor = levelColors.BackColor; + } + + // if the foreColor has been explicitly set + if (levelColors.HasForeColor) + { + Console.ForegroundColor = levelColors.ForeColor; + } + } - /// - /// Initialize the options for this appender - /// - /// - /// - /// Initialize the level to color mappings set on this appender. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - m_levelMapping.ActivateOptions(); - } - #endregion // Override implementation of AppenderSkeleton + // Render the event to a string + string strLoggingMessage = this.RenderLoggingEvent(loggingEvent); + + // and write it + writer.Write(strLoggingMessage); - #region Public Static Fields - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; + // Reset color again + Console.ResetColor(); + } - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - public const string ConsoleError = "Console.Error"; - #endregion // Public Static Fields + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } - #region Private Instances Fields - /// - /// Flag to write output to the error stream rather than the standard output stream - /// - private bool m_writeToErrorStream = false; + /// + /// Initialize the options for this appender. + /// + /// + /// + /// Initialize the level to color mappings set on this appender. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); + } + + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; - /// - /// Mapping from level object to color value - /// - private LevelMapping m_levelMapping = new LevelMapping(); - #endregion // Private Instances Fields + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + public const string ConsoleError = "Console.Error"; + + /// + /// Flag to write output to the error stream rather than the standard output stream. + /// + private bool m_writeToErrorStream = false; - #region LevelColors LevelMapping Entry - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and the color it should be displayed in. - /// - /// - public class LevelColors : LevelMappingEntry - { - /// - /// The mapped foreground color for the specified level - /// - /// - /// - /// Required property. - /// The mapped foreground color for the specified level. - /// - /// - public ConsoleColor ForeColor - { - get { return (this.foreColor); } - // Keep a flag that the color has been set - // and is no longer the default. - set { this.foreColor = value; this.hasForeColor = true; } - } - private ConsoleColor foreColor; - private bool hasForeColor; - internal bool HasForeColor { - get { - return hasForeColor; + /// + /// Mapping from level object to color value. + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and the color it should be displayed in. + /// + /// + public class LevelColors : LevelMappingEntry + { + /// + /// Gets or sets the mapped foreground color for the specified level. + /// + /// + /// + /// Required property. + /// The mapped foreground color for the specified level. + /// + /// + public ConsoleColor ForeColor + { + get { return this.foreColor; } + + // Keep a flag that the color has been set + // and is no longer the default. + set + { + this.foreColor = value; + this.hasForeColor = true; + } + } + + private ConsoleColor foreColor; + private bool hasForeColor; + + internal bool HasForeColor + { + get + { + return this.hasForeColor; } } - /// - /// The mapped background color for the specified level - /// - /// - /// - /// Required property. - /// The mapped background color for the specified level. - /// - /// - public ConsoleColor BackColor - { - get { return (this.backColor); } - // Keep a flag that the color has been set - // and is no longer the default. - set { this.backColor = value; this.hasBackColor = true; } - } - private ConsoleColor backColor; + /// + /// Gets or sets the mapped background color for the specified level. + /// + /// + /// + /// Required property. + /// The mapped background color for the specified level. + /// + /// + public ConsoleColor BackColor + { + get { return this.backColor; } + + // Keep a flag that the color has been set + // and is no longer the default. + set + { + this.backColor = value; + this.hasBackColor = true; + } + } + + private ConsoleColor backColor; private bool hasBackColor; - internal bool HasBackColor { - get { - return hasBackColor; + + internal bool HasBackColor + { + get + { + return this.hasBackColor; } } - } - #endregion // LevelColors LevelMapping Entry - } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs index 60acf6c20f8..2892a581d5e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs @@ -1,229 +1,208 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Stores logging events in an array. - /// - /// - /// - /// The memory appender stores all the logging events - /// that are appended in an in-memory array. - /// - /// - /// Use the method to get - /// and clear the current list of events that have been appended. - /// - /// - /// Use the method to get the current - /// list of events that have been appended. Note there is a - /// race-condition when calling and - /// in pairs, you better use in that case. - /// - /// - /// Use the method to clear the - /// current list of events. Note there is a - /// race-condition when calling and - /// in pairs, you better use in that case. - /// - /// - /// Julian Biddle - /// Nicko Cadell - /// Gert Driesen - public class MemoryAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public MemoryAppender() : base() - { - m_eventsList = new ArrayList(); - } - - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the events that have been logged. - /// - /// The events that have been logged - /// - /// - /// Gets the events that have been logged. - /// - /// - virtual public LoggingEvent[] GetEvents() - { - lock (m_eventsList.SyncRoot) + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Core; + + /// + /// Stores logging events in an array. + /// + /// + /// + /// The memory appender stores all the logging events + /// that are appended in an in-memory array. + /// + /// + /// Use the method to get + /// and clear the current list of events that have been appended. + /// + /// + /// Use the method to get the current + /// list of events that have been appended. Note there is a + /// race-condition when calling and + /// in pairs, you better use in that case. + /// + /// + /// Use the method to clear the + /// current list of events. Note there is a + /// race-condition when calling and + /// in pairs, you better use in that case. + /// + /// + /// Julian Biddle. + /// Nicko Cadell. + /// Gert Driesen. + public class MemoryAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public MemoryAppender() + : base() + { + this.m_eventsList = new ArrayList(); + } + + /// + /// Gets the events that have been logged. + /// + /// The events that have been logged. + /// + /// + /// Gets the events that have been logged. + /// + /// + public virtual LoggingEvent[] GetEvents() + { + lock (this.m_eventsList.SyncRoot) { - return (LoggingEvent[]) m_eventsList.ToArray(typeof(LoggingEvent)); + return (LoggingEvent[])this.m_eventsList.ToArray(typeof(LoggingEvent)); } - } - - /// - /// Gets or sets a value indicating whether only part of the logging event - /// data should be fixed. - /// - /// - /// true if the appender should only fix part of the logging event - /// data, otherwise false. The default is false. - /// - /// - /// - /// Setting this property to true will cause only part of the event - /// data to be fixed and stored in the appender, hereby improving performance. - /// - /// - /// See for more information. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - virtual public bool OnlyFixPartialEventData - { - get { return (Fix == FixFlags.Partial); } - set - { - if (value) - { - Fix = FixFlags.Partial; - } - else - { - Fix = FixFlags.All; - } - } - } - - /// - /// Gets or sets the fields that will be fixed in the event - /// - /// - /// - /// The logging event needs to have certain thread specific values - /// captured before it can be buffered. See - /// for details. - /// - /// - virtual public FixFlags Fix - { - get { return m_fixFlags; } - set { m_fixFlags = value; } - } - - #endregion Public Instance Properties - - #region Override implementation of AppenderSkeleton - - /// - /// This method is called by the method. - /// - /// the event to log - /// - /// Stores the in the events list. - /// - override protected void Append(LoggingEvent loggingEvent) - { - // Because we are caching the LoggingEvent beyond the - // lifetime of the Append() method we must fix any - // volatile data in the event. - loggingEvent.Fix = this.Fix; + } - lock (m_eventsList.SyncRoot) + /// + /// Gets or sets a value indicating whether only part of the logging event + /// data should be fixed. + /// + /// + /// true if the appender should only fix part of the logging event + /// data, otherwise false. The default is false. + /// + /// + /// + /// Setting this property to true will cause only part of the event + /// data to be fixed and stored in the appender, hereby improving performance. + /// + /// + /// See for more information. + /// + /// + [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] + public virtual bool OnlyFixPartialEventData + { + get { return this.Fix == FixFlags.Partial; } + + set { - m_eventsList.Add(loggingEvent); + if (value) + { + this.Fix = FixFlags.Partial; + } + else + { + this.Fix = FixFlags.All; + } } - } - - #endregion Override implementation of AppenderSkeleton + } - #region Public Instance Methods + /// + /// Gets or sets the fields that will be fixed in the event. + /// + /// + /// + /// The logging event needs to have certain thread specific values + /// captured before it can be buffered. See + /// for details. + /// + /// + public virtual FixFlags Fix + { + get { return this.m_fixFlags; } + set { this.m_fixFlags = value; } + } + + /// + /// This method is called by the method. + /// + /// the event to log. + /// + /// Stores the in the events list. + /// + protected override void Append(LoggingEvent loggingEvent) + { + // Because we are caching the LoggingEvent beyond the + // lifetime of the Append() method we must fix any + // volatile data in the event. + loggingEvent.Fix = this.Fix; - /// - /// Clear the list of events - /// - /// - /// Clear the list of events - /// - virtual public void Clear() - { - lock (m_eventsList.SyncRoot) + lock (this.m_eventsList.SyncRoot) + { + this.m_eventsList.Add(loggingEvent); + } + } + + /// + /// Clear the list of events. + /// + /// + /// Clear the list of events. + /// + public virtual void Clear() + { + lock (this.m_eventsList.SyncRoot) { - m_eventsList.Clear(); + this.m_eventsList.Clear(); } - } + } /// /// Gets the events that have been logged and clears the list of events. /// - /// The events that have been logged + /// The events that have been logged. /// /// /// Gets the events that have been logged and clears the list of events. /// /// - virtual public LoggingEvent[] PopAllEvents() + public virtual LoggingEvent[] PopAllEvents() { - lock (m_eventsList.SyncRoot) + lock (this.m_eventsList.SyncRoot) { - LoggingEvent[] tmp = (LoggingEvent[]) m_eventsList.ToArray(typeof (LoggingEvent)); - m_eventsList.Clear(); + LoggingEvent[] tmp = (LoggingEvent[])this.m_eventsList.ToArray(typeof(LoggingEvent)); + this.m_eventsList.Clear(); return tmp; } - } - - #endregion Public Instance Methods - - #region Protected Instance Fields - - /// - /// The list of events that have been appended. - /// - protected ArrayList m_eventsList; - - /// - /// Value indicating which fields in the event should be fixed - /// - /// - /// By default all fields are fixed - /// - protected FixFlags m_fixFlags = FixFlags.All; + } + + /// + /// The list of events that have been appended. + /// + protected ArrayList m_eventsList; - #endregion Protected Instance Fields - } + /// + /// Value indicating which fields in the event should be fixed. + /// + /// + /// By default all fields are fixed. + /// + protected FixFlags m_fixFlags = FixFlags.All; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs index 531cd500f55..bcb00acef4b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +18,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API -#if !NETCF +#if !NETCF // MONO 1.0 has no support for Win32 NetMessageBufferSend API -#if !MONO +#if !MONO // SSCLI 1.0 has no support for Win32 NetMessageBufferSend API #if !SSCLI // We don't want framework or platform specific code in the CLI version of log4net @@ -35,394 +33,370 @@ using System; using System.Globalization; using System.Runtime.InteropServices; - -using log4net.Util; -using log4net.Layout; + using log4net.Core; +using log4net.Layout; +using log4net.Util; - -namespace log4net.Appender +namespace log4net.Appender { - /// - /// Logs entries by sending network messages using the - /// native function. - /// - /// - /// - /// You can send messages only to names that are active - /// on the network. If you send the message to a user name, - /// that user must be logged on and running the Messenger - /// service to receive the message. - /// - /// - /// The receiver will get a top most window displaying the - /// messages one at a time, therefore this appender should - /// not be used to deliver a high volume of messages. - /// - /// - /// The following table lists some possible uses for this appender : - /// - /// - /// - /// - /// Action - /// Property Value(s) - /// - /// - /// Send a message to a user account on the local machine - /// - /// - /// = <name of the local machine> - /// - /// - /// = <user name> - /// - /// - /// - /// - /// Send a message to a user account on a remote machine - /// - /// - /// = <name of the remote machine> - /// - /// - /// = <user name> - /// - /// - /// - /// - /// Send a message to a domain user account - /// - /// - /// = <name of a domain controller | uninitialized> - /// - /// - /// = <user name> - /// - /// - /// - /// - /// Send a message to all the names in a workgroup or domain - /// - /// - /// = <workgroup name | domain name>* - /// - /// - /// - /// - /// Send a message from the local machine to a remote machine - /// - /// - /// = <name of the local machine | uninitialized> - /// - /// - /// = <name of the remote machine> - /// - /// - /// - /// - /// - /// - /// Note : security restrictions apply for sending - /// network messages, see - /// for more information. - /// - /// - /// - /// - /// An example configuration section to log information - /// using this appender from the local machine, named - /// LOCAL_PC, to machine OPERATOR_PC : - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class NetSendAppender : AppenderSkeleton - { - #region Member Variables - - /// - /// The DNS or NetBIOS name of the server on which the function is to execute. - /// - private string m_server; - - /// - /// The sender of the network message. - /// - private string m_sender; - - /// - /// The message alias to which the message should be sent. - /// - private string m_recipient; - - /// - /// The security context to use for privileged calls - /// - private SecurityContext m_securityContext; - - #endregion - - #region Constructors - - /// - /// Initializes the appender. - /// - /// - /// The default constructor initializes all fields to their default values. - /// - public NetSendAppender() - { - } - - #endregion - - #region Properties - - /// - /// Gets or sets the sender of the message. - /// - /// - /// The sender of the message. - /// - /// - /// If this property is not specified, the message is sent from the local computer. - /// - public string Sender - { - get { return m_sender; } - set { m_sender = value; } - } - - /// - /// Gets or sets the message alias to which the message should be sent. - /// - /// - /// The recipient of the message. - /// - /// - /// This property should always be specified in order to send a message. - /// - public string Recipient - { - get { return m_recipient; } - set { m_recipient = value; } - } - - /// - /// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute. - /// - /// - /// DNS or NetBIOS name of the remote server on which the function is to execute. - /// - /// - /// - /// For Windows NT 4.0 and earlier, the string should begin with \\. - /// - /// - /// If this property is not specified, the local computer is used. - /// - /// - public string Server - { - get { return m_server; } - set { m_server = value; } - } - - /// - /// Gets or sets the used to call the NetSend method. - /// - /// - /// The used to call the NetSend method. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return m_securityContext; } - set { m_securityContext = value; } - } - - #endregion - - #region Implementation of IOptionHandler - - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// The appender will be ignored if no was specified. - /// - /// - /// The required property was not specified. - public override void ActivateOptions() - { - base.ActivateOptions(); - - if (this.Recipient == null) - { - throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified."); - } - - if (m_securityContext == null) - { - m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - } - - #endregion - - #region Override implementation of AppenderSkeleton - - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Sends the event using a network message. - /// - /// + /// + /// Logs entries by sending network messages using the + /// native function. + /// + /// + /// + /// You can send messages only to names that are active + /// on the network. If you send the message to a user name, + /// that user must be logged on and running the Messenger + /// service to receive the message. + /// + /// + /// The receiver will get a top most window displaying the + /// messages one at a time, therefore this appender should + /// not be used to deliver a high volume of messages. + /// + /// + /// The following table lists some possible uses for this appender : + /// + /// + /// + /// + /// Action + /// Property Value(s) + /// + /// + /// Send a message to a user account on the local machine + /// + /// + /// = <name of the local machine> + /// + /// + /// = <user name> + /// + /// + /// + /// + /// Send a message to a user account on a remote machine + /// + /// + /// = <name of the remote machine> + /// + /// + /// = <user name> + /// + /// + /// + /// + /// Send a message to a domain user account + /// + /// + /// = <name of a domain controller | uninitialized> + /// + /// + /// = <user name> + /// + /// + /// + /// + /// Send a message to all the names in a workgroup or domain + /// + /// + /// = <workgroup name | domain name>* + /// + /// + /// + /// + /// Send a message from the local machine to a remote machine + /// + /// + /// = <name of the local machine | uninitialized> + /// + /// + /// = <name of the remote machine> + /// + /// + /// + /// + /// + /// + /// Note : security restrictions apply for sending + /// network messages, see + /// for more information. + /// + /// + /// + /// + /// An example configuration section to log information + /// using this appender from the local machine, named + /// LOCAL_PC, to machine OPERATOR_PC : + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class NetSendAppender : AppenderSkeleton + { + /// + /// The DNS or NetBIOS name of the server on which the function is to execute. + /// + private string m_server; + + /// + /// The sender of the network message. + /// + private string m_sender; + + /// + /// The message alias to which the message should be sent. + /// + private string m_recipient; + + /// + /// The security context to use for privileged calls. + /// + private SecurityContext m_securityContext; + + /// + /// Initializes a new instance of the class. + /// Initializes the appender. + /// + /// + /// The default constructor initializes all fields to their default values. + /// + public NetSendAppender() + { + } + + /// + /// Gets or sets the sender of the message. + /// + /// + /// The sender of the message. + /// + /// + /// If this property is not specified, the message is sent from the local computer. + /// + public string Sender + { + get { return this.m_sender; } + set { this.m_sender = value; } + } + + /// + /// Gets or sets the message alias to which the message should be sent. + /// + /// + /// The recipient of the message. + /// + /// + /// This property should always be specified in order to send a message. + /// + public string Recipient + { + get { return this.m_recipient; } + set { this.m_recipient = value; } + } + + /// + /// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute. + /// + /// + /// DNS or NetBIOS name of the remote server on which the function is to execute. + /// + /// + /// + /// For Windows NT 4.0 and earlier, the string should begin with \\. + /// + /// + /// If this property is not specified, the local computer is used. + /// + /// + public string Server + { + get { return this.m_server; } + set { this.m_server = value; } + } + + /// + /// Gets or sets the used to call the NetSend method. + /// + /// + /// The used to call the NetSend method. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// The appender will be ignored if no was specified. + /// + /// + /// The required property was not specified. + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.Recipient == null) + { + throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified."); + } + + if (this.m_securityContext == null) + { + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Sends the event using a network message. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #endif #if !NETSTANDARD1_3 [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] #endif - protected override void Append(LoggingEvent loggingEvent) - { - NativeError nativeError = null; - - // Render the event in the callers security context - string renderedLoggingEvent = RenderLoggingEvent(loggingEvent); - - using(m_securityContext.Impersonate(this)) - { - // Send the message - int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize); - - // Log the error if the message could not be sent - if (returnValue != 0) - { - // Lookup the native error - nativeError = NativeError.GetError(returnValue); - } - } - - if (nativeError != null) - { - // Handle the error over to the ErrorHandler - ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")"); - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion - - #region Stubs For Native Function Calls - - /// - /// Sends a buffer of information to a registered message alias. - /// - /// The DNS or NetBIOS name of the server on which the function is to execute. - /// The message alias to which the message buffer should be sent - /// The originator of the message. - /// The message text. - /// The length, in bytes, of the message text. - /// - /// - /// The following restrictions apply for sending network messages: - /// - /// - /// - /// - /// Platform - /// Requirements - /// - /// - /// Windows NT - /// - /// - /// No special group membership is required to send a network message. - /// - /// - /// Admin, Accounts, Print, or Server Operator group membership is required to - /// successfully send a network message on a remote server. - /// - /// - /// - /// - /// Windows 2000 or later - /// - /// - /// If you send a message on a domain controller that is running Active Directory, - /// access is allowed or denied based on the access control list (ACL) for the securable - /// object. The default ACL permits only Domain Admins and Account Operators to send a network message. - /// - /// - /// On a member server or workstation, only Administrators and Server Operators can send a network message. - /// - /// - /// - /// - /// - /// - /// For more information see Security Requirements for the Network Management Functions. - /// - /// - /// - /// - /// If the function succeeds, the return value is zero. - /// - /// - [DllImport("netapi32.dll", SetLastError=true)] - protected static extern int NetMessageBufferSend( - [MarshalAs(UnmanagedType.LPWStr)] string serverName, - [MarshalAs(UnmanagedType.LPWStr)] string msgName, - [MarshalAs(UnmanagedType.LPWStr)] string fromName, - [MarshalAs(UnmanagedType.LPWStr)] string buffer, - int bufferSize); - - #endregion - } + protected override void Append(LoggingEvent loggingEvent) + { + NativeError nativeError = null; + + // Render the event in the callers security context + string renderedLoggingEvent = this.RenderLoggingEvent(loggingEvent); + + using (this.m_securityContext.Impersonate(this)) + { + // Send the message + int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize); + + // Log the error if the message could not be sent + if (returnValue != 0) + { + // Lookup the native error + nativeError = NativeError.GetError(returnValue); + } + } + + if (nativeError != null) + { + // Handle the error over to the ErrorHandler + this.ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")"); + } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Sends a buffer of information to a registered message alias. + /// + /// The DNS or NetBIOS name of the server on which the function is to execute. + /// The message alias to which the message buffer should be sent. + /// The originator of the message. + /// The message text. + /// The length, in bytes, of the message text. + /// + /// + /// The following restrictions apply for sending network messages: + /// + /// + /// + /// + /// Platform + /// Requirements + /// + /// + /// Windows NT + /// + /// + /// No special group membership is required to send a network message. + /// + /// + /// Admin, Accounts, Print, or Server Operator group membership is required to + /// successfully send a network message on a remote server. + /// + /// + /// + /// + /// Windows 2000 or later + /// + /// + /// If you send a message on a domain controller that is running Active Directory, + /// access is allowed or denied based on the access control list (ACL) for the securable + /// object. The default ACL permits only Domain Admins and Account Operators to send a network message. + /// + /// + /// On a member server or workstation, only Administrators and Server Operators can send a network message. + /// + /// + /// + /// + /// + /// + /// For more information see Security Requirements for the Network Management Functions. + /// + /// + /// + /// + /// If the function succeeds, the return value is zero. + /// + /// + [DllImport("netapi32.dll", SetLastError = true)] + protected static extern int NetMessageBufferSend( + [MarshalAs(UnmanagedType.LPWStr)] string serverName, + [MarshalAs(UnmanagedType.LPWStr)] string msgName, + [MarshalAs(UnmanagedType.LPWStr)] string fromName, + [MarshalAs(UnmanagedType.LPWStr)] string buffer, + int bufferSize); + } } #endif // !CLI_1_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs index ca6e3ceaf1c..ecbbc7b26ba 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // MONO 1.0 has no support for Win32 OutputDebugString API #if !MONO @@ -29,63 +27,57 @@ #if !CLI_1_0 using System.Runtime.InteropServices; - -using log4net.Layout; + using log4net.Core; +using log4net.Layout; namespace log4net.Appender { - /// - /// Appends log events to the OutputDebugString system. - /// - /// - /// - /// OutputDebugStringAppender appends log events to the - /// OutputDebugString system. - /// - /// - /// The string is passed to the native OutputDebugString - /// function. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class OutputDebugStringAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public OutputDebugStringAppender() - { - } - - #endregion // Public Instance Constructors - - #region Override implementation of AppenderSkeleton - - /// - /// Write the logging event to the output debug string API - /// - /// the event to log - /// - /// - /// Write the logging event to the output debug string API - /// - /// + /// + /// Appends log events to the OutputDebugString system. + /// + /// + /// + /// OutputDebugStringAppender appends log events to the + /// OutputDebugString system. + /// + /// + /// The string is passed to the native OutputDebugString + /// function. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class OutputDebugStringAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public OutputDebugStringAppender() + { + } + + /// + /// Write the logging event to the output debug string API. + /// + /// the event to log. + /// + /// + /// Write the logging event to the output debug string API. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #elif !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] #endif - override protected void Append(LoggingEvent loggingEvent) - { + protected override void Append(LoggingEvent loggingEvent) + { #if NETSTANDARD1_3 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -93,45 +85,39 @@ override protected void Append(LoggingEvent loggingEvent) } #endif - OutputDebugString(RenderLoggingEvent(loggingEvent)); - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion // Override implementation of AppenderSkeleton + OutputDebugString(this.RenderLoggingEvent(loggingEvent)); + } - #region Protected Static Methods - - /// - /// Stub for OutputDebugString native method - /// - /// the string to output - /// - /// - /// Stub for OutputDebugString native method - /// - /// + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Stub for OutputDebugString native method. + /// + /// the string to output. + /// + /// + /// Stub for OutputDebugString native method. + /// + /// #if NETCF [DllImport("CoreDll.dll")] #else - [DllImport("Kernel32.dll")] + [DllImport("Kernel32.dll")] #endif - protected static extern void OutputDebugString(string message); - - #endregion // Protected Static Methods - } + protected static extern void OutputDebugString(string message); + } } #endif // !CLI_1_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs index 3a76093af27..aca29e4a43a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs @@ -1,364 +1,347 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; -using log4net.Appender; -using log4net.Util; -using log4net.Layout; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Logs events to a remote syslog daemon. - /// - /// - /// - /// The BSD syslog protocol is used to remotely log to - /// a syslog daemon. The syslogd listens for for messages - /// on UDP port 514. - /// - /// - /// The syslog UDP protocol is not authenticated. Most syslog daemons - /// do not accept remote log messages because of the security implications. - /// You may be able to use the LocalSyslogAppender to talk to a local - /// syslog service. - /// - /// - /// There is an RFC 3164 that claims to document the BSD Syslog Protocol. - /// This RFC can be seen here: http://www.faqs.org/rfcs/rfc3164.html. - /// This appender generates what the RFC calls an "Original Device Message", - /// i.e. does not include the TIMESTAMP or HOSTNAME fields. By observation - /// this format of message will be accepted by all current syslog daemon - /// implementations. The daemon will attach the current time and the source - /// hostname or IP address to any messages received. - /// - /// - /// Syslog messages must have a facility and and a severity. The severity - /// is derived from the Level of the logging event. - /// The facility must be chosen from the set of defined syslog - /// values. The facilities list is predefined - /// and cannot be extended. - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - /// Rob Lyon - /// Nicko Cadell - public class RemoteSyslogAppender : UdpAppender - { - /// - /// Syslog port 514 - /// - private const int DefaultSyslogPort = 514; - - #region Enumerations - - /// - /// syslog severities - /// - /// - /// - /// The syslog severities. - /// - /// - public enum SyslogSeverity - { - /// - /// system is unusable - /// - Emergency = 0, - - /// - /// action must be taken immediately - /// - Alert = 1, - - /// - /// critical conditions - /// - Critical = 2, - - /// - /// error conditions - /// - Error = 3, - - /// - /// warning conditions - /// - Warning = 4, - - /// - /// normal but significant condition - /// - Notice = 5, - - /// - /// informational - /// - Informational = 6, - - /// - /// debug-level messages - /// - Debug = 7 - }; - - /// - /// syslog facilities - /// - /// - /// - /// The syslog facilities - /// - /// - public enum SyslogFacility - { - /// - /// kernel messages - /// - Kernel = 0, - - /// - /// random user-level messages - /// - User = 1, - - /// - /// mail system - /// - Mail = 2, - - /// - /// system daemons - /// - Daemons = 3, - - /// - /// security/authorization messages - /// - Authorization = 4, - - /// - /// messages generated internally by syslogd - /// - Syslog = 5, - - /// - /// line printer subsystem - /// - Printer = 6, - - /// - /// network news subsystem - /// - News = 7, - - /// - /// UUCP subsystem - /// - Uucp = 8, - - /// - /// clock (cron/at) daemon - /// - Clock = 9, - - /// - /// security/authorization messages (private) - /// - Authorization2 = 10, - - /// - /// ftp daemon - /// - Ftp = 11, - - /// - /// NTP subsystem - /// - Ntp = 12, - - /// - /// log audit - /// - Audit = 13, - - /// - /// log alert - /// - Alert = 14, - - /// - /// clock daemon - /// - Clock2 = 15, - - /// - /// reserved for local use - /// - Local0 = 16, - - /// - /// reserved for local use - /// - Local1 = 17, - - /// - /// reserved for local use - /// - Local2 = 18, - - /// - /// reserved for local use - /// - Local3 = 19, - - /// - /// reserved for local use - /// - Local4 = 20, - - /// - /// reserved for local use - /// - Local5 = 21, - - /// - /// reserved for local use - /// - Local6 = 22, - - /// - /// reserved for local use - /// - Local7 = 23 - } - - #endregion Enumerations - - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// This instance of the class is set up to write - /// to a remote syslog daemon. - /// - public RemoteSyslogAppender() - { - // syslog udp defaults - this.RemotePort = DefaultSyslogPort; - this.RemoteAddress = System.Net.IPAddress.Parse("127.0.0.1"); - this.Encoding = System.Text.Encoding.ASCII; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Message identity - /// - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - public PatternLayout Identity - { - get { return m_identity; } - set { m_identity = value; } - } - - /// - /// Syslog facility - /// - /// - /// Set to one of the values. The list of - /// facilities is predefined and cannot be extended. The default value - /// is . - /// - public SyslogFacility Facility - { - get { return m_facility; } - set { m_facility = value; } - } - - #endregion Public Instance Properties - - /// - /// Add a mapping of level to severity - /// - /// The mapping to add - /// - /// - /// Add a mapping to this appender. - /// - /// - public void AddMapping(LevelSeverity mapping) - { - m_levelMapping.Add(mapping); - } - - #region AppenderSkeleton Implementation - - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to a remote syslog daemon. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + using log4net.Appender; + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// Logs events to a remote syslog daemon. + /// + /// + /// + /// The BSD syslog protocol is used to remotely log to + /// a syslog daemon. The syslogd listens for for messages + /// on UDP port 514. + /// + /// + /// The syslog UDP protocol is not authenticated. Most syslog daemons + /// do not accept remote log messages because of the security implications. + /// You may be able to use the LocalSyslogAppender to talk to a local + /// syslog service. + /// + /// + /// There is an RFC 3164 that claims to document the BSD Syslog Protocol. + /// This RFC can be seen here: http://www.faqs.org/rfcs/rfc3164.html. + /// This appender generates what the RFC calls an "Original Device Message", + /// i.e. does not include the TIMESTAMP or HOSTNAME fields. By observation + /// this format of message will be accepted by all current syslog daemon + /// implementations. The daemon will attach the current time and the source + /// hostname or IP address to any messages received. + /// + /// + /// Syslog messages must have a facility and and a severity. The severity + /// is derived from the Level of the logging event. + /// The facility must be chosen from the set of defined syslog + /// values. The facilities list is predefined + /// and cannot be extended. + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + /// Rob Lyon. + /// Nicko Cadell. + public class RemoteSyslogAppender : UdpAppender + { + /// + /// Syslog port 514. + /// + private const int DefaultSyslogPort = 514; + + /// + /// syslog severities. + /// + /// + /// + /// The syslog severities. + /// + /// + public enum SyslogSeverity + { + /// + /// system is unusable + /// + Emergency = 0, + + /// + /// action must be taken immediately + /// + Alert = 1, + + /// + /// critical conditions + /// + Critical = 2, + + /// + /// error conditions + /// + Error = 3, + + /// + /// warning conditions + /// + Warning = 4, + + /// + /// normal but significant condition + /// + Notice = 5, + + /// + /// informational + /// + Informational = 6, + + /// + /// debug-level messages + /// + Debug = 7, + } + + /// + /// syslog facilities. + /// + /// + /// + /// The syslog facilities. + /// + /// + public enum SyslogFacility + { + /// + /// kernel messages + /// + Kernel = 0, + + /// + /// random user-level messages + /// + User = 1, + + /// + /// mail system + /// + Mail = 2, + + /// + /// system daemons + /// + Daemons = 3, + + /// + /// security/authorization messages + /// + Authorization = 4, + + /// + /// messages generated internally by syslogd + /// + Syslog = 5, + + /// + /// line printer subsystem + /// + Printer = 6, + + /// + /// network news subsystem + /// + News = 7, + + /// + /// UUCP subsystem + /// + Uucp = 8, + + /// + /// clock (cron/at) daemon + /// + Clock = 9, + + /// + /// security/authorization messages (private) + /// + Authorization2 = 10, + + /// + /// ftp daemon + /// + Ftp = 11, + + /// + /// NTP subsystem + /// + Ntp = 12, + + /// + /// log audit + /// + Audit = 13, + + /// + /// log alert + /// + Alert = 14, + + /// + /// clock daemon + /// + Clock2 = 15, + + /// + /// reserved for local use + /// + Local0 = 16, + + /// + /// reserved for local use + /// + Local1 = 17, + + /// + /// reserved for local use + /// + Local2 = 18, + + /// + /// reserved for local use + /// + Local3 = 19, + + /// + /// reserved for local use + /// + Local4 = 20, + + /// + /// reserved for local use + /// + Local5 = 21, + + /// + /// reserved for local use + /// + Local6 = 22, + + /// + /// reserved for local use + /// + Local7 = 23, + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// This instance of the class is set up to write + /// to a remote syslog daemon. + /// + public RemoteSyslogAppender() + { + // syslog udp defaults + this.RemotePort = DefaultSyslogPort; + this.RemoteAddress = System.Net.IPAddress.Parse("127.0.0.1"); + this.Encoding = System.Text.Encoding.ASCII; + } + + /// + /// Gets or sets message identity. + /// + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + public PatternLayout Identity + { + get { return this.m_identity; } + set { this.m_identity = value; } + } + + /// + /// Gets or sets syslog facility. + /// + /// + /// Set to one of the values. The list of + /// facilities is predefined and cannot be extended. The default value + /// is . + /// + public SyslogFacility Facility + { + get { return this.m_facility; } + set { this.m_facility = value; } + } + + /// + /// Add a mapping of level to severity. + /// + /// The mapping to add. + /// + /// + /// Add a mapping to this appender. + /// + /// + public void AddMapping(LevelSeverity mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to a remote syslog daemon. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { try { // Priority - int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level)); + int priority = GeneratePriority(this.m_facility, this.GetSeverity(loggingEvent.Level)); // Identity string identity; - if (m_identity != null) + if (this.m_identity != null) { - identity = m_identity.Format(loggingEvent); + identity = this.m_identity.Format(loggingEvent); } else { @@ -366,9 +349,9 @@ protected override void Append(LoggingEvent loggingEvent) } // Message. The message goes after the tag/identity - string message = RenderLoggingEvent(loggingEvent); + string message = this.RenderLoggingEvent(loggingEvent); - Byte[] buffer; + byte[] buffer; int i = 0; char c; @@ -397,6 +380,7 @@ protected override void Append(LoggingEvent loggingEvent) { builder.Append(c); } + // If character is newline, break and send the current line else if ((c == '\r') || (c == '\n')) { @@ -405,6 +389,7 @@ protected override void Append(LoggingEvent loggingEvent) { i++; } + i++; break; } @@ -422,7 +407,7 @@ protected override void Append(LoggingEvent loggingEvent) } catch (Exception e) { - ErrorHandler.Error( + this.ErrorHandler.Error( "Unable to send logging event to remote syslog " + this.RemoteAddress.ToString() + " on port " + @@ -430,171 +415,152 @@ protected override void Append(LoggingEvent loggingEvent) e, ErrorCode.WriteFailure); } - } - - /// - /// Initialize the options for this appender - /// - /// - /// - /// Initialize the level to syslog severity mappings set on this appender. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - m_levelMapping.ActivateOptions(); - } - - #endregion AppenderSkeleton Implementation - - #region Protected Members - - /// - /// Translates a log4net level to a syslog severity. - /// - /// A log4net level. - /// A syslog severity. - /// - /// - /// Translates a log4net level to a syslog severity. - /// - /// - virtual protected SyslogSeverity GetSeverity(Level level) - { - LevelSeverity levelSeverity = m_levelMapping.Lookup(level) as LevelSeverity; - if (levelSeverity != null) - { - return levelSeverity.Severity; - } - - // - // Fallback to sensible default values - // - - if (level >= Level.Alert) - { - return SyslogSeverity.Alert; - } - else if (level >= Level.Critical) - { - return SyslogSeverity.Critical; - } - else if (level >= Level.Error) - { - return SyslogSeverity.Error; - } - else if (level >= Level.Warn) - { - return SyslogSeverity.Warning; - } - else if (level >= Level.Notice) - { - return SyslogSeverity.Notice; - } - else if (level >= Level.Info) - { - return SyslogSeverity.Informational; - } - // Default setting - return SyslogSeverity.Debug; - } - - #endregion Protected Members - - #region Public Static Members - - /// - /// Generate a syslog priority. - /// - /// The syslog facility. - /// The syslog severity. - /// A syslog priority. - /// - /// - /// Generate a syslog priority. - /// - /// - public static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) - { - if (facility < SyslogFacility.Kernel || facility > SyslogFacility.Local7) - { - throw new ArgumentException("SyslogFacility out of range", "facility"); - } - - if (severity < SyslogSeverity.Emergency || severity > SyslogSeverity.Debug) - { - throw new ArgumentException("SyslogSeverity out of range", "severity"); - } - - unchecked - { - return ((int)facility * 8) + (int)severity; - } - } - - #endregion Public Static Members - - #region Private Instances Fields - - /// - /// The facility. The default facility is . - /// - private SyslogFacility m_facility = SyslogFacility.User; - - /// - /// The message identity - /// - private PatternLayout m_identity; - - /// - /// Mapping from level object to syslog severity - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// Initial buffer size - /// - private const int c_renderBufferSize = 256; - - /// - /// Maximum buffer size before it is recycled - /// - private const int c_renderBufferMaxCapacity = 1024; - - #endregion Private Instances Fields - - #region LevelSeverity LevelMapping Entry - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - public class LevelSeverity : LevelMappingEntry - { - private SyslogSeverity m_severity; - - /// - /// The mapped syslog severity for the specified level - /// - /// - /// - /// Required property. - /// The mapped syslog severity for the specified level - /// - /// - public SyslogSeverity Severity - { - get { return m_severity; } - set { m_severity = value; } - } - } - - #endregion // LevelSeverity LevelMapping Entry - } + } + + /// + /// Initialize the options for this appender. + /// + /// + /// + /// Initialize the level to syslog severity mappings set on this appender. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); + } + + /// + /// Translates a log4net level to a syslog severity. + /// + /// A log4net level. + /// A syslog severity. + /// + /// + /// Translates a log4net level to a syslog severity. + /// + /// + protected virtual SyslogSeverity GetSeverity(Level level) + { + LevelSeverity levelSeverity = this.m_levelMapping.Lookup(level) as LevelSeverity; + if (levelSeverity != null) + { + return levelSeverity.Severity; + } + + // Fallback to sensible default values + if (level >= Level.Alert) + { + return SyslogSeverity.Alert; + } + else if (level >= Level.Critical) + { + return SyslogSeverity.Critical; + } + else if (level >= Level.Error) + { + return SyslogSeverity.Error; + } + else if (level >= Level.Warn) + { + return SyslogSeverity.Warning; + } + else if (level >= Level.Notice) + { + return SyslogSeverity.Notice; + } + else if (level >= Level.Info) + { + return SyslogSeverity.Informational; + } + + // Default setting + return SyslogSeverity.Debug; + } + + /// + /// Generate a syslog priority. + /// + /// The syslog facility. + /// The syslog severity. + /// A syslog priority. + /// + /// + /// Generate a syslog priority. + /// + /// + public static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) + { + if (facility < SyslogFacility.Kernel || facility > SyslogFacility.Local7) + { + throw new ArgumentException("SyslogFacility out of range", "facility"); + } + + if (severity < SyslogSeverity.Emergency || severity > SyslogSeverity.Debug) + { + throw new ArgumentException("SyslogSeverity out of range", "severity"); + } + + unchecked + { + return ((int)facility * 8) + (int)severity; + } + } + + /// + /// The facility. The default facility is . + /// + private SyslogFacility m_facility = SyslogFacility.User; + + /// + /// The message identity. + /// + private PatternLayout m_identity; + + /// + /// Mapping from level object to syslog severity. + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// Initial buffer size. + /// + private const int c_renderBufferSize = 256; + + /// + /// Maximum buffer size before it is recycled. + /// + private const int c_renderBufferMaxCapacity = 1024; + + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + public class LevelSeverity : LevelMappingEntry + { + private SyslogSeverity m_severity; + + /// + /// Gets or sets the mapped syslog severity for the specified level. + /// + /// + /// + /// Required property. + /// The mapped syslog severity for the specified level. + /// + /// + public SyslogSeverity Severity + { + get { return this.m_severity; } + set { this.m_severity = value; } + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs index 6364f1f8a1f..579244514a6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,325 +18,303 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting #if !NETCF using System; using System.Collections; -using System.Threading; - using System.Runtime.Remoting.Messaging; - -using log4net.Layout; +using System.Threading; + using log4net.Core; +using log4net.Layout; using log4net.Util; namespace log4net.Appender { - /// - /// Delivers logging events to a remote logging sink. - /// - /// - /// - /// This Appender is designed to deliver events to a remote sink. - /// That is any object that implements the - /// interface. It delivers the events using .NET remoting. The - /// object to deliver events to is specified by setting the - /// appenders property. - /// - /// The RemotingAppender buffers events before sending them. This allows it to - /// make more efficient use of the remoting infrastructure. - /// - /// Once the buffer is full the events are still not sent immediately. - /// They are scheduled to be sent using a pool thread. The effect is that - /// the send occurs asynchronously. This is very important for a - /// number of non obvious reasons. The remoting infrastructure will - /// flow thread local variables (stored in the ), - /// if they are marked as , across the - /// remoting boundary. If the server is not contactable then - /// the remoting infrastructure will clear the - /// objects from the . To prevent a logging failure from - /// having side effects on the calling application the remoting call must be made - /// from a separate thread to the one used by the application. A - /// thread is used for this. If no thread is available then - /// the events will block in the thread pool manager until a thread is available. - /// - /// Because the events are sent asynchronously using pool threads it is possible to close - /// this appender before all the queued events have been sent. - /// When closing the appender attempts to wait until all the queued events have been sent, but - /// this will timeout after 30 seconds regardless. - /// - /// If this appender is being closed because the - /// event has fired it may not be possible to send all the queued events. During process - /// exit the runtime limits the time that a - /// event handler is allowed to run for. If the runtime terminates the threads before - /// the queued events have been sent then they will be lost. To ensure that all events - /// are sent the appender must be closed before the application exits. See - /// for details on how to shutdown - /// log4net programmatically. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Daniel Cazzulino - public class RemotingAppender : BufferingAppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public RemotingAppender() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the URL of the well-known object that will accept - /// the logging events. - /// - /// - /// The well-known URL of the remote sink. - /// - /// - /// - /// The URL of the remoting sink that will accept logging events. - /// The sink must implement the - /// interface. - /// - /// - public string Sink - { - get { return m_sinkUrl; } - set { m_sinkUrl = value; } - } - - #endregion Public Instance Properties - - #region Implementation of IOptionHandler - - /// - /// Initialize the appender based on the options set - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// + /// + /// Delivers logging events to a remote logging sink. + /// + /// + /// + /// This Appender is designed to deliver events to a remote sink. + /// That is any object that implements the + /// interface. It delivers the events using .NET remoting. The + /// object to deliver events to is specified by setting the + /// appenders property. + /// + /// The RemotingAppender buffers events before sending them. This allows it to + /// make more efficient use of the remoting infrastructure. + /// + /// Once the buffer is full the events are still not sent immediately. + /// They are scheduled to be sent using a pool thread. The effect is that + /// the send occurs asynchronously. This is very important for a + /// number of non obvious reasons. The remoting infrastructure will + /// flow thread local variables (stored in the ), + /// if they are marked as , across the + /// remoting boundary. If the server is not contactable then + /// the remoting infrastructure will clear the + /// objects from the . To prevent a logging failure from + /// having side effects on the calling application the remoting call must be made + /// from a separate thread to the one used by the application. A + /// thread is used for this. If no thread is available then + /// the events will block in the thread pool manager until a thread is available. + /// + /// Because the events are sent asynchronously using pool threads it is possible to close + /// this appender before all the queued events have been sent. + /// When closing the appender attempts to wait until all the queued events have been sent, but + /// this will timeout after 30 seconds regardless. + /// + /// If this appender is being closed because the + /// event has fired it may not be possible to send all the queued events. During process + /// exit the runtime limits the time that a + /// event handler is allowed to run for. If the runtime terminates the threads before + /// the queued events have been sent then they will be lost. To ensure that all events + /// are sent the appender must be closed before the application exits. See + /// for details on how to shutdown + /// log4net programmatically. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Daniel Cazzulino. + public class RemotingAppender : BufferingAppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public RemotingAppender() + { + } + + /// + /// Gets or sets the URL of the well-known object that will accept + /// the logging events. + /// + /// + /// The well-known URL of the remote sink. + /// + /// + /// + /// The URL of the remoting sink that will accept logging events. + /// The sink must implement the + /// interface. + /// + /// + public string Sink + { + get { return this.m_sinkUrl; } + set { this.m_sinkUrl = value; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif - override public void ActivateOptions() - { - base.ActivateOptions(); - - IDictionary channelProperties = new Hashtable(); - channelProperties["typeFilterLevel"] = "Full"; - - m_sinkObj = (IRemoteLoggingSink)Activator.GetObject(typeof(IRemoteLoggingSink), m_sinkUrl, channelProperties); - } - - #endregion - - #region Override implementation of BufferingAppenderSkeleton - - /// - /// Send the contents of the buffer to the remote sink. - /// - /// - /// The events are not sent immediately. They are scheduled to be sent - /// using a pool thread. The effect is that the send occurs asynchronously. - /// This is very important for a number of non obvious reasons. The remoting - /// infrastructure will flow thread local variables (stored in the ), - /// if they are marked as , across the - /// remoting boundary. If the server is not contactable then - /// the remoting infrastructure will clear the - /// objects from the . To prevent a logging failure from - /// having side effects on the calling application the remoting call must be made - /// from a separate thread to the one used by the application. A - /// thread is used for this. If no thread is available then - /// the events will block in the thread pool manager until a thread is available. - /// - /// The events to send. - override protected void SendBuffer(LoggingEvent[] events) - { - // Setup for an async send - BeginAsyncSend(); - - // Send the events - if (!ThreadPool.QueueUserWorkItem(new WaitCallback(SendBufferCallback), events)) - { - // Cancel the async send - EndAsyncSend(); - - ErrorHandler.Error("RemotingAppender ["+Name+"] failed to ThreadPool.QueueUserWorkItem logging events in SendBuffer."); - } - } - - /// - /// Override base class close. - /// - /// - /// - /// This method waits while there are queued work items. The events are - /// sent asynchronously using work items. These items - /// will be sent once a thread pool thread is available to send them, therefore - /// it is possible to close the appender before all the queued events have been - /// sent. - /// - /// This method attempts to wait until all the queued events have been sent, but this - /// method will timeout after 30 seconds regardless. - /// - /// If the appender is being closed because the - /// event has fired it may not be possible to send all the queued events. During process - /// exit the runtime limits the time that a - /// event handler is allowed to run for. - /// - override protected void OnClose() - { - base.OnClose(); - - // Wait for the work queue to become empty before closing, timeout 30 seconds - if (!m_workQueueEmptyEvent.WaitOne(30 * 1000, false)) - { - ErrorHandler.Error("RemotingAppender ["+Name+"] failed to send all queued events before close, in OnClose."); - } - } - - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) - { - base.Flush(); - return m_workQueueEmptyEvent.WaitOne(millisecondsTimeout, false); - } - - #endregion - - /// - /// A work item is being queued into the thread pool - /// - private void BeginAsyncSend() - { - // The work queue is not empty - m_workQueueEmptyEvent.Reset(); - - // Increment the queued count - Interlocked.Increment(ref m_queuedCallbackCount); - } - - /// - /// A work item from the thread pool has completed - /// - private void EndAsyncSend() - { - // Decrement the queued count - if (Interlocked.Decrement(ref m_queuedCallbackCount) <= 0) - { - // If the work queue is empty then set the event - m_workQueueEmptyEvent.Set(); - } - } - - /// - /// Send the contents of the buffer to the remote sink. - /// - /// - /// This method is designed to be used with the . - /// This method expects to be passed an array of - /// objects in the state param. - /// - /// the logging events to send - private void SendBufferCallback(object state) - { - try - { - LoggingEvent[] events = (LoggingEvent[])state; - - // Send the events - m_sinkObj.LogEvents(events); - } - catch(Exception ex) - { - ErrorHandler.Error("Failed in SendBufferCallback", ex); - } - finally - { - EndAsyncSend(); - } - } - - #region Private Instance Fields - - /// - /// The URL of the remote sink. - /// - private string m_sinkUrl; - - /// - /// The local proxy (.NET remoting) for the remote logging sink. - /// - private IRemoteLoggingSink m_sinkObj; - - /// - /// The number of queued callbacks currently waiting or executing - /// - private int m_queuedCallbackCount = 0; - - /// - /// Event used to signal when there are no queued work items - /// - /// - /// This event is set when there are no queued work items. In this - /// state it is safe to close the appender. - /// - private ManualResetEvent m_workQueueEmptyEvent = new ManualResetEvent(true); - - #endregion Private Instance Fields - - /// - /// Interface used to deliver objects to a remote sink. - /// - /// - /// This interface must be implemented by a remoting sink - /// if the is to be used - /// to deliver logging events to the sink. - /// - public interface IRemoteLoggingSink - { - /// - /// Delivers logging events to the remote sink - /// - /// Array of events to log. - /// - /// - /// Delivers logging events to the remote sink - /// - /// - void LogEvents(LoggingEvent[] events); - } - } + public override void ActivateOptions() + { + base.ActivateOptions(); + + IDictionary channelProperties = new Hashtable(); + channelProperties["typeFilterLevel"] = "Full"; + + this.m_sinkObj = (IRemoteLoggingSink)Activator.GetObject(typeof(IRemoteLoggingSink), this.m_sinkUrl, channelProperties); + } + + /// + /// Send the contents of the buffer to the remote sink. + /// + /// + /// The events are not sent immediately. They are scheduled to be sent + /// using a pool thread. The effect is that the send occurs asynchronously. + /// This is very important for a number of non obvious reasons. The remoting + /// infrastructure will flow thread local variables (stored in the ), + /// if they are marked as , across the + /// remoting boundary. If the server is not contactable then + /// the remoting infrastructure will clear the + /// objects from the . To prevent a logging failure from + /// having side effects on the calling application the remoting call must be made + /// from a separate thread to the one used by the application. A + /// thread is used for this. If no thread is available then + /// the events will block in the thread pool manager until a thread is available. + /// + /// The events to send. + protected override void SendBuffer(LoggingEvent[] events) + { + // Setup for an async send + this.BeginAsyncSend(); + + // Send the events + if (!ThreadPool.QueueUserWorkItem(new WaitCallback(this.SendBufferCallback), events)) + { + // Cancel the async send + this.EndAsyncSend(); + + this.ErrorHandler.Error("RemotingAppender [" + this.Name + "] failed to ThreadPool.QueueUserWorkItem logging events in SendBuffer."); + } + } + + /// + /// Override base class close. + /// + /// + /// + /// This method waits while there are queued work items. The events are + /// sent asynchronously using work items. These items + /// will be sent once a thread pool thread is available to send them, therefore + /// it is possible to close the appender before all the queued events have been + /// sent. + /// + /// This method attempts to wait until all the queued events have been sent, but this + /// method will timeout after 30 seconds regardless. + /// + /// If the appender is being closed because the + /// event has fired it may not be possible to send all the queued events. During process + /// exit the runtime limits the time that a + /// event handler is allowed to run for. + /// + protected override void OnClose() + { + base.OnClose(); + + // Wait for the work queue to become empty before closing, timeout 30 seconds + if (!this.m_workQueueEmptyEvent.WaitOne(30 * 1000, false)) + { + this.ErrorHandler.Error("RemotingAppender [" + this.Name + "] failed to send all queued events before close, in OnClose."); + } + } + + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) + { + this.Flush(); + return this.m_workQueueEmptyEvent.WaitOne(millisecondsTimeout, false); + } + + /// + /// A work item is being queued into the thread pool. + /// + private void BeginAsyncSend() + { + // The work queue is not empty + this.m_workQueueEmptyEvent.Reset(); + + // Increment the queued count + Interlocked.Increment(ref this.m_queuedCallbackCount); + } + + /// + /// A work item from the thread pool has completed. + /// + private void EndAsyncSend() + { + // Decrement the queued count + if (Interlocked.Decrement(ref this.m_queuedCallbackCount) <= 0) + { + // If the work queue is empty then set the event + this.m_workQueueEmptyEvent.Set(); + } + } + + /// + /// Send the contents of the buffer to the remote sink. + /// + /// + /// This method is designed to be used with the . + /// This method expects to be passed an array of + /// objects in the state param. + /// + /// the logging events to send. + private void SendBufferCallback(object state) + { + try + { + LoggingEvent[] events = (LoggingEvent[])state; + + // Send the events + this.m_sinkObj.LogEvents(events); + } + catch (Exception ex) + { + this.ErrorHandler.Error("Failed in SendBufferCallback", ex); + } + finally + { + this.EndAsyncSend(); + } + } + + /// + /// The URL of the remote sink. + /// + private string m_sinkUrl; + + /// + /// The local proxy (.NET remoting) for the remote logging sink. + /// + private IRemoteLoggingSink m_sinkObj; + + /// + /// The number of queued callbacks currently waiting or executing. + /// + private int m_queuedCallbackCount = 0; + + /// + /// Event used to signal when there are no queued work items. + /// + /// + /// This event is set when there are no queued work items. In this + /// state it is safe to close the appender. + /// + private ManualResetEvent m_workQueueEmptyEvent = new ManualResetEvent(true); + + /// + /// Interface used to deliver objects to a remote sink. + /// + /// + /// This interface must be implemented by a remoting sink + /// if the is to be used + /// to deliver logging events to the sink. + /// + public interface IRemoteLoggingSink + { + /// + /// Delivers logging events to the remote sink. + /// + /// Array of events to log. + /// + /// + /// Delivers logging events to the remote sink. + /// + /// + void LogEvents(LoggingEvent[] events); + } + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs index a50b2be953b..20ba3e6e683 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs @@ -1,37 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Globalization; -using System.IO; - -using log4net.Util; -using log4net.Core; -using System.Threading; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Globalization; + using System.IO; + using System.Threading; + + using log4net.Core; + using log4net.Util; + #if CONFIRM_WIN32_FILE_SHAREMODES // The following sounds good, and I though it was the case, but after // further testing on Windows I have not been able to confirm it. @@ -45,246 +42,233 @@ namespace log4net.Appender /// write access please ensure that read and delete share modes are enabled. #endif - /// - /// Appender that rolls log files based on size or date or both. - /// - /// - /// - /// RollingFileAppender can roll log files based on size or date or both - /// depending on the setting of the property. - /// When set to the log file will be rolled - /// once its size exceeds the . - /// When set to the log file will be rolled - /// once the date boundary specified in the property - /// is crossed. - /// When set to the log file will be - /// rolled once the date boundary specified in the property - /// is crossed, but within a date boundary the file will also be rolled - /// once its size exceeds the . - /// When set to the log file will be rolled when - /// the appender is configured. This effectively means that the log file can be - /// rolled once per program execution. - /// - /// - /// A of few additional optional features have been added: - /// - /// Attach date pattern for current log file - /// Backup number increments for newer files - /// Infinite number of backups by file size - /// - /// - /// - /// - /// - /// For large or infinite numbers of backup files a - /// greater than zero is highly recommended, otherwise all the backup files need - /// to be renamed each time a new backup is created. - /// - /// - /// When Date/Time based rolling is used setting - /// to will reduce the number of file renamings to few or none. - /// - /// - /// - /// - /// - /// Changing or without clearing - /// the log file directory of backup files will cause unexpected and unwanted side effects. - /// - /// - /// - /// - /// If Date/Time based rolling is enabled this appender will attempt to roll existing files - /// in the directory without a Date/Time tag based on the last write date of the base log file. - /// The appender only rolls the log file when a message is logged. If Date/Time based rolling - /// is enabled then the appender will not roll the log file at the Date/Time boundary but - /// at the point when the next message is logged after the boundary has been crossed. - /// - /// - /// - /// The extends the and - /// has the same behavior when opening the log file. - /// The appender will first try to open the file for writing when - /// is called. This will typically be during configuration. - /// If the file cannot be opened for writing the appender will attempt - /// to open the file again each time a message is logged to the appender. - /// If the file cannot be opened for writing when a message is logged then - /// the message will be discarded by this appender. - /// - /// - /// When rolling a backup file necessitates deleting an older backup file the - /// file to be deleted is moved to a temporary name before being deleted. - /// - /// - /// - /// - /// A maximum number of backup files when rolling on date/time boundaries is not supported. - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Aspi Havewala - /// Douglas de la Torre - /// Edward Smit - public class RollingFileAppender : FileAppender - { - #region Public Enums - + /// + /// Appender that rolls log files based on size or date or both. + /// + /// + /// + /// RollingFileAppender can roll log files based on size or date or both + /// depending on the setting of the property. + /// When set to the log file will be rolled + /// once its size exceeds the . + /// When set to the log file will be rolled + /// once the date boundary specified in the property + /// is crossed. + /// When set to the log file will be + /// rolled once the date boundary specified in the property + /// is crossed, but within a date boundary the file will also be rolled + /// once its size exceeds the . + /// When set to the log file will be rolled when + /// the appender is configured. This effectively means that the log file can be + /// rolled once per program execution. + /// + /// + /// A of few additional optional features have been added: + /// + /// Attach date pattern for current log file + /// Backup number increments for newer files + /// Infinite number of backups by file size + /// + /// + /// + /// + /// + /// For large or infinite numbers of backup files a + /// greater than zero is highly recommended, otherwise all the backup files need + /// to be renamed each time a new backup is created. + /// + /// + /// When Date/Time based rolling is used setting + /// to will reduce the number of file renamings to few or none. + /// + /// + /// + /// + /// + /// Changing or without clearing + /// the log file directory of backup files will cause unexpected and unwanted side effects. + /// + /// + /// + /// + /// If Date/Time based rolling is enabled this appender will attempt to roll existing files + /// in the directory without a Date/Time tag based on the last write date of the base log file. + /// The appender only rolls the log file when a message is logged. If Date/Time based rolling + /// is enabled then the appender will not roll the log file at the Date/Time boundary but + /// at the point when the next message is logged after the boundary has been crossed. + /// + /// + /// + /// The extends the and + /// has the same behavior when opening the log file. + /// The appender will first try to open the file for writing when + /// is called. This will typically be during configuration. + /// If the file cannot be opened for writing the appender will attempt + /// to open the file again each time a message is logged to the appender. + /// If the file cannot be opened for writing when a message is logged then + /// the message will be discarded by this appender. + /// + /// + /// When rolling a backup file necessitates deleting an older backup file the + /// file to be deleted is moved to a temporary name before being deleted. + /// + /// + /// + /// + /// A maximum number of backup files when rolling on date/time boundaries is not supported. + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Aspi Havewala. + /// Douglas de la Torre. + /// Edward Smit. + public class RollingFileAppender : FileAppender + { /// - /// Style of rolling to use - /// - /// - /// - /// Style of rolling to use - /// - /// - public enum RollingMode - { - /// - /// Roll files once per program execution - /// - /// - /// - /// Roll files once per program execution. - /// Well really once each time this appender is - /// configured. - /// - /// - /// Setting this option also sets AppendToFile to - /// false on the RollingFileAppender, otherwise - /// this appender would just be a normal file appender. - /// - /// - Once = 0, - - /// - /// Roll files based only on the size of the file - /// - Size = 1, - - /// - /// Roll files based only on the date - /// - Date = 2, - - /// - /// Roll files based on both the size and date of the file - /// - Composite = 3 - } - - #endregion - - #region Protected Enums - - /// - /// The code assumes that the following 'time' constants are in a increasing sequence. - /// - /// - /// - /// The code assumes that the following 'time' constants are in a increasing sequence. - /// - /// - protected enum RollPoint - { - /// - /// Roll the log not based on the date - /// - InvalidRollPoint =-1, - - /// - /// Roll the log for each minute - /// - TopOfMinute = 0, - - /// - /// Roll the log for each hour - /// - TopOfHour = 1, - - /// - /// Roll the log twice a day (midday and midnight) - /// - HalfDay = 2, - - /// - /// Roll the log each day (midnight) - /// - TopOfDay = 3, - - /// - /// Roll the log each week - /// - TopOfWeek = 4, - - /// - /// Roll the log each month - /// - TopOfMonth = 5 - } - - #endregion Protected Enums - - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public RollingFileAppender() - { - } - - /// - /// Cleans up all resources used by this appender. - /// - ~RollingFileAppender() - { + /// Style of rolling to use. + /// + /// + /// + /// Style of rolling to use. + /// + /// + public enum RollingMode + { + /// + /// Roll files once per program execution + /// + /// + /// + /// Roll files once per program execution. + /// Well really once each time this appender is + /// configured. + /// + /// + /// Setting this option also sets AppendToFile to + /// false on the RollingFileAppender, otherwise + /// this appender would just be a normal file appender. + /// + /// + Once = 0, + + /// + /// Roll files based only on the size of the file + /// + Size = 1, + + /// + /// Roll files based only on the date + /// + Date = 2, + + /// + /// Roll files based on both the size and date of the file + /// + Composite = 3, + } + + /// + /// The code assumes that the following 'time' constants are in a increasing sequence. + /// + /// + /// + /// The code assumes that the following 'time' constants are in a increasing sequence. + /// + /// + protected enum RollPoint + { + /// + /// Roll the log not based on the date + /// + InvalidRollPoint = -1, + + /// + /// Roll the log for each minute + /// + TopOfMinute = 0, + + /// + /// Roll the log for each hour + /// + TopOfHour = 1, + + /// + /// Roll the log twice a day (midday and midnight) + /// + HalfDay = 2, + + /// + /// Roll the log each day (midnight) + /// + TopOfDay = 3, + + /// + /// Roll the log each week + /// + TopOfWeek = 4, + + /// + /// Roll the log each month + /// + TopOfMonth = 5, + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public RollingFileAppender() + { + } + + /// + /// Finalizes an instance of the class. + /// Cleans up all resources used by this appender. + /// + ~RollingFileAppender() + { #if !NETCF - if (m_mutexForRolling != null) - { + if (this.m_mutexForRolling != null) + { #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - m_mutexForRolling.Dispose(); + this.m_mutexForRolling.Dispose(); #else m_mutexForRolling.Close(); #endif - m_mutexForRolling = null; - } + this.m_mutexForRolling = null; + } #endif - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - + } + #if !NET_1_0 && !CLI_1_0 && !NETCF /// - /// Gets or sets the strategy for determining the current date and time. The default - /// implementation is to use LocalDateTime which internally calls through to DateTime.Now. - /// DateTime.UtcNow may be used on frameworks newer than .NET 1.0 by specifying - /// . - /// - /// - /// An implementation of the interface which returns the current date and time. - /// - /// - /// - /// Gets or sets the used to return the current date and time. - /// + /// Gets or sets the strategy for determining the current date and time. The default + /// implementation is to use LocalDateTime which internally calls through to DateTime.Now. + /// DateTime.UtcNow may be used on frameworks newer than .NET 1.0 by specifying + /// . + /// + /// + /// An implementation of the interface which returns the current date and time. + /// + /// /// - /// There are two built strategies for determining the current date and time, - /// + /// Gets or sets the used to return the current date and time. + /// + /// + /// There are two built strategies for determining the current date and time, + /// /// and . /// /// - /// The default strategy is . - /// - /// + /// The default strategy is . + /// + /// #else /// /// Gets or sets the strategy for determining the current date and time. The default @@ -303,708 +287,702 @@ public RollingFileAppender() /// #endif public IDateTime DateTimeStrategy - { - get { return m_dateTime; } - set { m_dateTime = value; } - } - - /// - /// Gets or sets the date pattern to be used for generating file names - /// when rolling over on date. - /// - /// - /// The date pattern to be used for generating file names when rolling - /// over on date. - /// - /// - /// - /// Takes a string in the same format as expected by - /// . - /// - /// - /// This property determines the rollover schedule when rolling over - /// on date. - /// - /// - public string DatePattern - { - get { return m_datePattern; } - set { m_datePattern = value; } - } - - /// - /// Gets or sets the maximum number of backup files that are kept before - /// the oldest is erased. - /// - /// - /// The maximum number of backup files that are kept before the oldest is - /// erased. - /// - /// - /// - /// If set to zero, then there will be no backup files and the log file - /// will be truncated when it reaches . - /// - /// - /// If a negative number is supplied then no deletions will be made. Note - /// that this could result in very slow performance as a large number of - /// files are rolled over unless is used. - /// - /// - /// The maximum applies to each time based group of files and - /// not the total. - /// - /// - public int MaxSizeRollBackups - { - get { return m_maxSizeRollBackups; } - set { m_maxSizeRollBackups = value; } - } - - /// - /// Gets or sets the maximum size that the output file is allowed to reach - /// before being rolled over to backup files. - /// - /// - /// The maximum size in bytes that the output file is allowed to reach before being - /// rolled over to backup files. - /// - /// - /// - /// This property is equivalent to except - /// that it is required for differentiating the setter taking a - /// argument from the setter taking a - /// argument. - /// - /// - /// The default maximum file size is 10MB (10*1024*1024). - /// - /// - public long MaxFileSize - { - get { return m_maxFileSize; } - set { m_maxFileSize = value; } - } - - /// - /// Gets or sets the maximum size that the output file is allowed to reach - /// before being rolled over to backup files. - /// - /// - /// The maximum size that the output file is allowed to reach before being - /// rolled over to backup files. - /// - /// - /// - /// This property allows you to specify the maximum size with the - /// suffixes "KB", "MB" or "GB" so that the size is interpreted being - /// expressed respectively in kilobytes, megabytes or gigabytes. - /// - /// - /// For example, the value "10KB" will be interpreted as 10240 bytes. - /// - /// - /// The default maximum file size is 10MB. - /// - /// - /// If you have the option to set the maximum file size programmatically - /// consider using the property instead as this - /// allows you to set the size in bytes as a . - /// - /// - public string MaximumFileSize - { - get { return m_maxFileSize.ToString(NumberFormatInfo.InvariantInfo); } - set { m_maxFileSize = OptionConverter.ToFileSize(value, m_maxFileSize + 1); } - } - - /// - /// Gets or sets the rolling file count direction. - /// - /// - /// The rolling file count direction. - /// - /// - /// - /// Indicates if the current file is the lowest numbered file or the - /// highest numbered file. - /// - /// - /// By default newer files have lower numbers ( < 0), - /// i.e. log.1 is most recent, log.5 is the 5th backup, etc... - /// - /// - /// >= 0 does the opposite i.e. - /// log.1 is the first backup made, log.5 is the 5th backup made, etc. - /// For infinite backups use >= 0 to reduce - /// rollover costs. - /// - /// The default file count direction is -1. - /// - public int CountDirection - { - get { return m_countDirection; } - set { m_countDirection = value; } - } - - /// - /// Gets or sets the rolling style. - /// - /// The rolling style. - /// - /// - /// The default rolling style is . - /// - /// - /// When set to this appender's - /// property is set to false, otherwise - /// the appender would append to a single file rather than rolling - /// the file each time it is opened. - /// - /// - public RollingMode RollingStyle - { - get { return m_rollingStyle; } - set - { - m_rollingStyle = value; - switch (m_rollingStyle) - { - case RollingMode.Once: - m_rollDate = false; - m_rollSize = false; - - this.AppendToFile = false; - break; - - case RollingMode.Size: - m_rollDate = false; - m_rollSize = true; - break; - - case RollingMode.Date: - m_rollDate = true; - m_rollSize = false; - break; - - case RollingMode.Composite: - m_rollDate = true; - m_rollSize = true; - break; - } - } - } + { + get { return this.m_dateTime; } + set { this.m_dateTime = value; } + } /// - /// Gets or sets a value indicating whether to preserve the file name extension when rolling. + /// Gets or sets the date pattern to be used for generating file names + /// when rolling over on date. /// /// - /// true if the file name extension should be preserved. + /// The date pattern to be used for generating file names when rolling + /// over on date. /// /// /// - /// By default file.log is rolled to file.log.yyyy-MM-dd or file.log.curSizeRollBackup. - /// However, under Windows the new file name will loose any program associations as the - /// extension is changed. Optionally file.log can be renamed to file.yyyy-MM-dd.log or - /// file.curSizeRollBackup.log to maintain any program associations. + /// Takes a string in the same format as expected by + /// . + /// + /// + /// This property determines the rollover schedule when rolling over + /// on date. /// /// - public bool PreserveLogFileNameExtension + public string DatePattern { - get { return m_preserveLogFileNameExtension; } - set { m_preserveLogFileNameExtension = value; } + get { return this.m_datePattern; } + set { this.m_datePattern = value; } } - /// - /// Gets or sets a value indicating whether to always log to - /// the same file. - /// - /// - /// true if always should be logged to the same file, otherwise false. - /// - /// - /// - /// By default file.log is always the current file. Optionally - /// file.log.yyyy-mm-dd for current formatted datePattern can by the currently - /// logging file (or file.log.curSizeRollBackup or even - /// file.log.yyyy-mm-dd.curSizeRollBackup). - /// - /// - /// This will make time based rollovers with a large number of backups - /// much faster as the appender it won't have to rename all the backups! - /// - /// - public bool StaticLogFileName - { - get { return m_staticLogFileName; } - set { m_staticLogFileName = value; } - } - - #endregion Public Instance Properties - - #region Private Static Fields - - /// - /// The fully qualified type of the RollingFileAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(RollingFileAppender); - - #endregion Private Static Fields - - #region Override implementation of FileAppender - - /// - /// Sets the quiet writer being used. - /// - /// - /// This method can be overridden by sub classes. - /// - /// the writer to set - override protected void SetQWForFiles(TextWriter writer) - { - QuietWriter = new CountingQuietTextWriter(writer, ErrorHandler); - } - - /// - /// Write out a logging event. - /// - /// the event to write to file. - /// - /// - /// Handles append time behavior for RollingFileAppender. This checks - /// if a roll over either by date (checked first) or time (checked second) - /// is need and then appends to the file last. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - AdjustFileBeforeAppend(); - base.Append(loggingEvent); - } - - /// - /// Write out an array of logging events. - /// - /// the events to write to file. - /// - /// - /// Handles append time behavior for RollingFileAppender. This checks - /// if a roll over either by date (checked first) or time (checked second) - /// is need and then appends to the file last. - /// - /// - override protected void Append(LoggingEvent[] loggingEvents) - { - AdjustFileBeforeAppend(); - base.Append(loggingEvents); - } - - /// - /// Performs any required rolling before outputting the next event - /// - /// - /// - /// Handles append time behavior for RollingFileAppender. This checks - /// if a roll over either by date (checked first) or time (checked second) - /// is need and then appends to the file last. - /// - /// - virtual protected void AdjustFileBeforeAppend() - { - // reuse the file appenders locking model to lock the rolling -#if !NETCF - try - { - // if rolling should be locked, acquire the lock - if (m_mutexForRolling != null) - { - m_mutexForRolling.WaitOne(); - } -#endif - if (m_rollDate) - { - DateTime n = m_dateTime.Now; - if (n >= m_nextCheck) - { - m_now = n; - m_nextCheck = NextCheckDate(m_now, m_rollPoint); - - RollOverTime(true); - } - } - - if (m_rollSize) - { - if ((File != null) && ((CountingQuietTextWriter)QuietWriter).Count >= m_maxFileSize) - { - RollOverSize(); - } - } -#if !NETCF - } - finally - { - // if rolling should be locked, release the lock - if (m_mutexForRolling != null) - { - m_mutexForRolling.ReleaseMutex(); - } - } -#endif - } - - /// - /// Creates and opens the file for logging. If - /// is false then the fully qualified name is determined and used. - /// - /// the name of the file to open - /// true to append to existing file - /// - /// This method will ensure that the directory structure - /// for the specified exists. - /// - override protected void OpenFile(string fileName, bool append) - { - lock(this) - { - fileName = GetNextOutputFileName(fileName); - - // Calculate the current size of the file - long currentCount = 0; - if (append) - { - using(SecurityContext.Impersonate(this)) - { - if (System.IO.File.Exists(fileName)) - { - currentCount = (new FileInfo(fileName)).Length; - } - } - } - else - { - if (LogLog.IsErrorEnabled) - { - // Internal check that the file is not being overwritten - // If not Appending to an existing file we should have rolled the file out of the - // way. Therefore we should not be over-writing an existing file. - // The only exception is if we are not allowed to roll the existing file away. - if (m_maxSizeRollBackups != 0 && FileExists(fileName)) - { - LogLog.Error(declaringType, "RollingFileAppender: INTERNAL ERROR. Append is False but OutputFile ["+fileName+"] already exists."); - } - } - } - - if (!m_staticLogFileName) - { - m_scheduledFilename = fileName; - } - - // Open the file (call the base class to do it) - base.OpenFile(fileName, append); - - // Set the file size onto the counting writer - ((CountingQuietTextWriter)QuietWriter).Count = currentCount; - } - } - - /// - /// Get the current output file name - /// - /// the base file name - /// the output file name - /// - /// The output file name is based on the base fileName specified. - /// If is set then the output - /// file name is the same as the base file passed in. Otherwise - /// the output file depends on the date pattern, on the count - /// direction or both. - /// - protected string GetNextOutputFileName(string fileName) - { - if (!m_staticLogFileName) - { - fileName = fileName.Trim(); - - if (m_rollDate) - { - fileName = CombinePath(fileName, m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - } - - if (m_countDirection >= 0) - { - fileName = CombinePath(fileName, "." + m_curSizeRollBackups); - } - } + /// + /// Gets or sets the maximum number of backup files that are kept before + /// the oldest is erased. + /// + /// + /// The maximum number of backup files that are kept before the oldest is + /// erased. + /// + /// + /// + /// If set to zero, then there will be no backup files and the log file + /// will be truncated when it reaches . + /// + /// + /// If a negative number is supplied then no deletions will be made. Note + /// that this could result in very slow performance as a large number of + /// files are rolled over unless is used. + /// + /// + /// The maximum applies to each time based group of files and + /// not the total. + /// + /// + public int MaxSizeRollBackups + { + get { return this.m_maxSizeRollBackups; } + set { this.m_maxSizeRollBackups = value; } + } - return fileName; - } + /// + /// Gets or sets the maximum size that the output file is allowed to reach + /// before being rolled over to backup files. + /// + /// + /// The maximum size in bytes that the output file is allowed to reach before being + /// rolled over to backup files. + /// + /// + /// + /// This property is equivalent to except + /// that it is required for differentiating the setter taking a + /// argument from the setter taking a + /// argument. + /// + /// + /// The default maximum file size is 10MB (10*1024*1024). + /// + /// + public long MaxFileSize + { + get { return this.m_maxFileSize; } + set { this.m_maxFileSize = value; } + } - #endregion + /// + /// Gets or sets the maximum size that the output file is allowed to reach + /// before being rolled over to backup files. + /// + /// + /// The maximum size that the output file is allowed to reach before being + /// rolled over to backup files. + /// + /// + /// + /// This property allows you to specify the maximum size with the + /// suffixes "KB", "MB" or "GB" so that the size is interpreted being + /// expressed respectively in kilobytes, megabytes or gigabytes. + /// + /// + /// For example, the value "10KB" will be interpreted as 10240 bytes. + /// + /// + /// The default maximum file size is 10MB. + /// + /// + /// If you have the option to set the maximum file size programmatically + /// consider using the property instead as this + /// allows you to set the size in bytes as a . + /// + /// + public string MaximumFileSize + { + get { return this.m_maxFileSize.ToString(NumberFormatInfo.InvariantInfo); } + set { this.m_maxFileSize = OptionConverter.ToFileSize(value, this.m_maxFileSize + 1); } + } - #region Initialize Options + /// + /// Gets or sets the rolling file count direction. + /// + /// + /// The rolling file count direction. + /// + /// + /// + /// Indicates if the current file is the lowest numbered file or the + /// highest numbered file. + /// + /// + /// By default newer files have lower numbers ( < 0), + /// i.e. log.1 is most recent, log.5 is the 5th backup, etc... + /// + /// + /// >= 0 does the opposite i.e. + /// log.1 is the first backup made, log.5 is the 5th backup made, etc. + /// For infinite backups use >= 0 to reduce + /// rollover costs. + /// + /// The default file count direction is -1. + /// + public int CountDirection + { + get { return this.m_countDirection; } + set { this.m_countDirection = value; } + } - /// - /// Determines curSizeRollBackups (only within the current roll point) - /// - private void DetermineCurSizeRollBackups() - { - m_curSizeRollBackups = 0; - - string fullPath = null; - string fileName = null; - - using(SecurityContext.Impersonate(this)) - { - fullPath = System.IO.Path.GetFullPath(m_baseFileName); - fileName = System.IO.Path.GetFileName(fullPath); - } - - ArrayList arrayFiles = GetExistingFiles(fullPath); - InitializeRollBackups(fileName, arrayFiles); - - LogLog.Debug(declaringType, "curSizeRollBackups starts at ["+m_curSizeRollBackups+"]"); - } - - /// - /// Generates a wildcard pattern that can be used to find all files - /// that are similar to the base file name. - /// - /// - /// - private string GetWildcardPatternForFile(string baseFileName) - { - if (m_preserveLogFileNameExtension) - { - return Path.GetFileNameWithoutExtension(baseFileName) + "*" + Path.GetExtension(baseFileName); - } - else + /// + /// Gets or sets the rolling style. + /// + /// The rolling style. + /// + /// + /// The default rolling style is . + /// + /// + /// When set to this appender's + /// property is set to false, otherwise + /// the appender would append to a single file rather than rolling + /// the file each time it is opened. + /// + /// + public RollingMode RollingStyle + { + get { return this.m_rollingStyle; } + + set { - return baseFileName + '*'; + this.m_rollingStyle = value; + switch (this.m_rollingStyle) + { + case RollingMode.Once: + this.m_rollDate = false; + this.m_rollSize = false; + + this.AppendToFile = false; + break; + + case RollingMode.Size: + this.m_rollDate = false; + this.m_rollSize = true; + break; + + case RollingMode.Date: + this.m_rollDate = true; + this.m_rollSize = false; + break; + + case RollingMode.Composite: + this.m_rollDate = true; + this.m_rollSize = true; + break; + } } - } + } - /// - /// Builds a list of filenames for all files matching the base filename plus a file - /// pattern. - /// - /// - /// - private ArrayList GetExistingFiles(string baseFilePath) - { - ArrayList alFiles = new ArrayList(); - - string directory = null; - - using(SecurityContext.Impersonate(this)) - { - string fullPath = Path.GetFullPath(baseFilePath); - - directory = Path.GetDirectoryName(fullPath); - if (Directory.Exists(directory)) - { - string baseFileName = Path.GetFileName(fullPath); - - string[] files = Directory.GetFiles(directory, GetWildcardPatternForFile(baseFileName)); - - if (files != null) - { - for (int i = 0; i < files.Length; i++) - { - string curFileName = Path.GetFileName(files[i]); - if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFileName))) - { - alFiles.Add(curFileName); - } - } - } - } - } - LogLog.Debug(declaringType, "Searched for existing files in ["+directory+"]"); - return alFiles; - } - - /// - /// Initiates a roll over if needed for crossing a date boundary since the last run. - /// - private void RollOverIfDateBoundaryCrossing() - { - if (m_staticLogFileName && m_rollDate) - { - if (FileExists(m_baseFileName)) - { - DateTime last; - using(SecurityContext.Impersonate(this)) { -#if !NET_1_0 && !CLI_1_0 && !NETCF - if (DateTimeStrategy is UniversalDateTime) - { - last = System.IO.File.GetLastWriteTimeUtc(m_baseFileName); - } - else - { + /// + /// Gets or sets a value indicating whether to preserve the file name extension when rolling. + /// + /// + /// true if the file name extension should be preserved. + /// + /// + /// + /// By default file.log is rolled to file.log.yyyy-MM-dd or file.log.curSizeRollBackup. + /// However, under Windows the new file name will loose any program associations as the + /// extension is changed. Optionally file.log can be renamed to file.yyyy-MM-dd.log or + /// file.curSizeRollBackup.log to maintain any program associations. + /// + /// + public bool PreserveLogFileNameExtension + { + get { return this.m_preserveLogFileNameExtension; } + set { this.m_preserveLogFileNameExtension = value; } + } + + /// + /// Gets or sets a value indicating whether to always log to + /// the same file. + /// + /// + /// true if always should be logged to the same file, otherwise false. + /// + /// + /// + /// By default file.log is always the current file. Optionally + /// file.log.yyyy-mm-dd for current formatted datePattern can by the currently + /// logging file (or file.log.curSizeRollBackup or even + /// file.log.yyyy-mm-dd.curSizeRollBackup). + /// + /// + /// This will make time based rollovers with a large number of backups + /// much faster as the appender it won't have to rename all the backups!. + /// + /// + public bool StaticLogFileName + { + get { return this.m_staticLogFileName; } + set { this.m_staticLogFileName = value; } + } + + /// + /// The fully qualified type of the RollingFileAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(RollingFileAppender); + + /// + /// Sets the quiet writer being used. + /// + /// + /// This method can be overridden by sub classes. + /// + /// the writer to set. + protected override void SetQWForFiles(TextWriter writer) + { + this.QuietWriter = new CountingQuietTextWriter(writer, this.ErrorHandler); + } + + /// + /// Write out a logging event. + /// + /// the event to write to file. + /// + /// + /// Handles append time behavior for RollingFileAppender. This checks + /// if a roll over either by date (checked first) or time (checked second) + /// is need and then appends to the file last. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + this.AdjustFileBeforeAppend(); + base.Append(loggingEvent); + } + + /// + /// Write out an array of logging events. + /// + /// the events to write to file. + /// + /// + /// Handles append time behavior for RollingFileAppender. This checks + /// if a roll over either by date (checked first) or time (checked second) + /// is need and then appends to the file last. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) + { + this.AdjustFileBeforeAppend(); + base.Append(loggingEvents); + } + + /// + /// Performs any required rolling before outputting the next event. + /// + /// + /// + /// Handles append time behavior for RollingFileAppender. This checks + /// if a roll over either by date (checked first) or time (checked second) + /// is need and then appends to the file last. + /// + /// + protected virtual void AdjustFileBeforeAppend() + { + // reuse the file appenders locking model to lock the rolling +#if !NETCF + try + { + // if rolling should be locked, acquire the lock + if (this.m_mutexForRolling != null) + { + this.m_mutexForRolling.WaitOne(); + } +#endif + if (this.m_rollDate) + { + DateTime n = this.m_dateTime.Now; + if (n >= this.m_nextCheck) + { + this.m_now = n; + this.m_nextCheck = this.NextCheckDate(this.m_now, this.m_rollPoint); + + this.RollOverTime(true); + } + } + + if (this.m_rollSize) + { + if ((this.File != null) && ((CountingQuietTextWriter)this.QuietWriter).Count >= this.m_maxFileSize) + { + this.RollOverSize(); + } + } +#if !NETCF + } + finally + { + // if rolling should be locked, release the lock + if (this.m_mutexForRolling != null) + { + this.m_mutexForRolling.ReleaseMutex(); + } + } +#endif + } + + /// + /// Creates and opens the file for logging. If + /// is false then the fully qualified name is determined and used. + /// + /// the name of the file to open. + /// true to append to existing file. + /// + /// This method will ensure that the directory structure + /// for the specified exists. + /// + protected override void OpenFile(string fileName, bool append) + { + lock (this) + { + fileName = this.GetNextOutputFileName(fileName); + + // Calculate the current size of the file + long currentCount = 0; + if (append) + { + using (this.SecurityContext.Impersonate(this)) + { + if (System.IO.File.Exists(fileName)) + { + currentCount = new FileInfo(fileName).Length; + } + } + } + else + { + if (LogLog.IsErrorEnabled) + { + // Internal check that the file is not being overwritten + // If not Appending to an existing file we should have rolled the file out of the + // way. Therefore we should not be over-writing an existing file. + // The only exception is if we are not allowed to roll the existing file away. + if (this.m_maxSizeRollBackups != 0 && this.FileExists(fileName)) + { + LogLog.Error(declaringType, "RollingFileAppender: INTERNAL ERROR. Append is False but OutputFile [" + fileName + "] already exists."); + } + } + } + + if (!this.m_staticLogFileName) + { + this.m_scheduledFilename = fileName; + } + + // Open the file (call the base class to do it) + base.OpenFile(fileName, append); + + // Set the file size onto the counting writer + ((CountingQuietTextWriter)this.QuietWriter).Count = currentCount; + } + } + + /// + /// Get the current output file name. + /// + /// the base file name. + /// the output file name. + /// + /// The output file name is based on the base fileName specified. + /// If is set then the output + /// file name is the same as the base file passed in. Otherwise + /// the output file depends on the date pattern, on the count + /// direction or both. + /// + protected string GetNextOutputFileName(string fileName) + { + if (!this.m_staticLogFileName) + { + fileName = fileName.Trim(); + + if (this.m_rollDate) + { + fileName = this.CombinePath(fileName, this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); + } + + if (this.m_countDirection >= 0) + { + fileName = this.CombinePath(fileName, "." + this.m_curSizeRollBackups); + } + } + + return fileName; + } + + /// + /// Determines curSizeRollBackups (only within the current roll point). + /// + private void DetermineCurSizeRollBackups() + { + this.m_curSizeRollBackups = 0; + + string fullPath = null; + string fileName = null; + + using (this.SecurityContext.Impersonate(this)) + { + fullPath = System.IO.Path.GetFullPath(this.m_baseFileName); + fileName = System.IO.Path.GetFileName(fullPath); + } + + ArrayList arrayFiles = this.GetExistingFiles(fullPath); + this.InitializeRollBackups(fileName, arrayFiles); + + LogLog.Debug(declaringType, "curSizeRollBackups starts at [" + this.m_curSizeRollBackups + "]"); + } + + /// + /// Generates a wildcard pattern that can be used to find all files + /// that are similar to the base file name. + /// + /// + /// + private string GetWildcardPatternForFile(string baseFileName) + { + if (this.m_preserveLogFileNameExtension) + { + return Path.GetFileNameWithoutExtension(baseFileName) + "*" + Path.GetExtension(baseFileName); + } + else + { + return baseFileName + '*'; + } + } + + /// + /// Builds a list of filenames for all files matching the base filename plus a file + /// pattern. + /// + /// + /// + private ArrayList GetExistingFiles(string baseFilePath) + { + ArrayList alFiles = new ArrayList(); + + string directory = null; + + using (this.SecurityContext.Impersonate(this)) + { + string fullPath = Path.GetFullPath(baseFilePath); + + directory = Path.GetDirectoryName(fullPath); + if (Directory.Exists(directory)) + { + string baseFileName = Path.GetFileName(fullPath); + + string[] files = Directory.GetFiles(directory, this.GetWildcardPatternForFile(baseFileName)); + + if (files != null) + { + for (int i = 0; i < files.Length; i++) + { + string curFileName = Path.GetFileName(files[i]); + if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFileName))) + { + alFiles.Add(curFileName); + } + } + } + } + } + + LogLog.Debug(declaringType, "Searched for existing files in [" + directory + "]"); + return alFiles; + } + + /// + /// Initiates a roll over if needed for crossing a date boundary since the last run. + /// + private void RollOverIfDateBoundaryCrossing() + { + if (this.m_staticLogFileName && this.m_rollDate) + { + if (this.FileExists(this.m_baseFileName)) + { + DateTime last; + using (this.SecurityContext.Impersonate(this)) + { +#if !NET_1_0 && !CLI_1_0 && !NETCF + if (this.DateTimeStrategy is UniversalDateTime) + { + last = System.IO.File.GetLastWriteTimeUtc(this.m_baseFileName); + } + else + { #endif - last = System.IO.File.GetLastWriteTime(m_baseFileName); + last = System.IO.File.GetLastWriteTime(this.m_baseFileName); #if !NET_1_0 && !CLI_1_0 && !NETCF } #endif } - LogLog.Debug(declaringType, "["+last.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo)+"] vs. ["+m_now.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo)+"]"); - - if (!(last.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo).Equals(m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)))) - { - m_scheduledFilename = CombinePath(m_baseFileName, last.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - LogLog.Debug(declaringType, "Initial roll over to ["+m_scheduledFilename+"]"); - RollOverTime(false); - LogLog.Debug(declaringType, "curSizeRollBackups after rollOver at ["+m_curSizeRollBackups+"]"); - } - } - } - } - - /// - /// Initializes based on existing conditions at time of . - /// - /// - /// - /// Initializes based on existing conditions at time of . - /// The following is done - /// - /// determine curSizeRollBackups (only within the current roll point) - /// initiates a roll over if needed for crossing a date boundary since the last run. - /// - /// - /// - protected void ExistingInit() - { - DetermineCurSizeRollBackups(); - RollOverIfDateBoundaryCrossing(); - - // If file exists and we are not appending then roll it out of the way - if (AppendToFile == false) - { - bool fileExists = false; - string fileName = GetNextOutputFileName(m_baseFileName); - - using(SecurityContext.Impersonate(this)) - { - fileExists = System.IO.File.Exists(fileName); - } - - if (fileExists) - { - if (m_maxSizeRollBackups == 0) - { - LogLog.Debug(declaringType, "Output file ["+fileName+"] already exists. MaxSizeRollBackups is 0; cannot roll. Overwriting existing file."); - } - else - { - LogLog.Debug(declaringType, "Output file ["+fileName+"] already exists. Not appending to file. Rolling existing file out of the way."); - - RollOverRenameFiles(fileName); - } - } - } - } - - /// - /// Does the work of bumping the 'current' file counter higher - /// to the highest count when an incremental file name is seen. - /// The highest count is either the first file (when count direction - /// is greater than 0) or the last file (when count direction less than 0). - /// In either case, we want to know the highest count that is present. - /// - /// - /// - private void InitializeFromOneFile(string baseFile, string curFileName) - { + + LogLog.Debug(declaringType, "[" + last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo) + "] vs. [" + this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo) + "]"); + + if (!last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo).Equals(this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo))) + { + this.m_scheduledFilename = this.CombinePath(this.m_baseFileName, last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); + LogLog.Debug(declaringType, "Initial roll over to [" + this.m_scheduledFilename + "]"); + this.RollOverTime(false); + LogLog.Debug(declaringType, "curSizeRollBackups after rollOver at [" + this.m_curSizeRollBackups + "]"); + } + } + } + } + + /// + /// Initializes based on existing conditions at time of . + /// + /// + /// + /// Initializes based on existing conditions at time of . + /// The following is done. + /// + /// determine curSizeRollBackups (only within the current roll point) + /// initiates a roll over if needed for crossing a date boundary since the last run. + /// + /// + /// + protected void ExistingInit() + { + this.DetermineCurSizeRollBackups(); + this.RollOverIfDateBoundaryCrossing(); + + // If file exists and we are not appending then roll it out of the way + if (this.AppendToFile == false) + { + bool fileExists = false; + string fileName = this.GetNextOutputFileName(this.m_baseFileName); + + using (this.SecurityContext.Impersonate(this)) + { + fileExists = System.IO.File.Exists(fileName); + } + + if (fileExists) + { + if (this.m_maxSizeRollBackups == 0) + { + LogLog.Debug(declaringType, "Output file [" + fileName + "] already exists. MaxSizeRollBackups is 0; cannot roll. Overwriting existing file."); + } + else + { + LogLog.Debug(declaringType, "Output file [" + fileName + "] already exists. Not appending to file. Rolling existing file out of the way."); + + this.RollOverRenameFiles(fileName); + } + } + } + } + + /// + /// Does the work of bumping the 'current' file counter higher + /// to the highest count when an incremental file name is seen. + /// The highest count is either the first file (when count direction + /// is greater than 0) or the last file (when count direction less than 0). + /// In either case, we want to know the highest count that is present. + /// + /// + /// + private void InitializeFromOneFile(string baseFile, string curFileName) + { if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFile)) == false) - { - // This is not a log file, so ignore - return; - } - if (curFileName.Equals(baseFile)) - { - // Base log file is not an incremented logfile (.1 or .2, etc) - return; - } - + { + // This is not a log file, so ignore + return; + } + + if (curFileName.Equals(baseFile)) + { + // Base log file is not an incremented logfile (.1 or .2, etc) + return; + } + /* - if (m_staticLogFileName) - { - int endLength = curFileName.Length - index; - if (baseFile.Length + endLength != curFileName.Length) - { - // file is probably scheduledFilename + .x so I don't care - return; - } - } + if (m_staticLogFileName) + { + int endLength = curFileName.Length - index; + if (baseFile.Length + endLength != curFileName.Length) + { + // file is probably scheduledFilename + .x so I don't care + return; + } + } */ - - // Only look for files in the current roll point - if (m_rollDate && !m_staticLogFileName) - { - string date = m_dateTime.Now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - string prefix = m_preserveLogFileNameExtension ? Path.GetFileNameWithoutExtension(baseFile) + date : baseFile + date; - string suffix = m_preserveLogFileNameExtension ? Path.GetExtension(baseFile) : ""; - if (!curFileName.StartsWith(prefix) || !curFileName.EndsWith(suffix)) - { - LogLog.Debug(declaringType, "Ignoring file ["+curFileName+"] because it is from a different date period"); - return; - } - } - - try - { - // Bump the counter up to the highest count seen so far - int backup = GetBackUpIndex(curFileName); - + + // Only look for files in the current roll point + if (this.m_rollDate && !this.m_staticLogFileName) + { + string date = this.m_dateTime.Now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); + string prefix = this.m_preserveLogFileNameExtension ? Path.GetFileNameWithoutExtension(baseFile) + date : baseFile + date; + string suffix = this.m_preserveLogFileNameExtension ? Path.GetExtension(baseFile) : string.Empty; + if (!curFileName.StartsWith(prefix) || !curFileName.EndsWith(suffix)) + { + LogLog.Debug(declaringType, "Ignoring file [" + curFileName + "] because it is from a different date period"); + return; + } + } + + try + { + // Bump the counter up to the highest count seen so far + int backup = this.GetBackUpIndex(curFileName); + // caution: we might get a false positive when certain // date patterns such as yyyyMMdd are used...those are // valid number but aren't the kind of back up index // we're looking for - if (backup > m_curSizeRollBackups) + if (backup > this.m_curSizeRollBackups) { - if (0 == m_maxSizeRollBackups) + if (this.m_maxSizeRollBackups == 0) { // Stay at zero when zero backups are desired } - else if (-1 == m_maxSizeRollBackups) + else if (this.m_maxSizeRollBackups == -1) { // Infinite backups, so go as high as the highest value - m_curSizeRollBackups = backup; + this.m_curSizeRollBackups = backup; } else { // Backups limited to a finite number - if (m_countDirection >= 0) + if (this.m_countDirection >= 0) { // Go with the highest file when counting up - m_curSizeRollBackups = backup; + this.m_curSizeRollBackups = backup; } else { // Clip to the limit when counting down - if (backup <= m_maxSizeRollBackups) + if (backup <= this.m_maxSizeRollBackups) { - m_curSizeRollBackups = backup; + this.m_curSizeRollBackups = backup; } } } - LogLog.Debug(declaringType, "File name [" + curFileName + "] moves current count to [" + m_curSizeRollBackups + "]"); + + LogLog.Debug(declaringType, "File name [" + curFileName + "] moves current count to [" + this.m_curSizeRollBackups + "]"); } - } - catch(FormatException) - { - //this happens when file.log -> file.log.yyyy-MM-dd which is normal - //when staticLogFileName == false - LogLog.Debug(declaringType, "Encountered a backup file not ending in .x ["+curFileName+"]"); - } - } + } + catch (FormatException) + { + // this happens when file.log -> file.log.yyyy-MM-dd which is normal + // when staticLogFileName == false + LogLog.Debug(declaringType, "Encountered a backup file not ending in .x [" + curFileName + "]"); + } + } /// /// Attempts to extract a number from the end of the file name that indicates @@ -1015,16 +993,16 @@ private void InitializeFromOneFile(string baseFile, string curFileName) /// /// /// - private int GetBackUpIndex(string curFileName) - { + private int GetBackUpIndex(string curFileName) + { int backUpIndex = -1; string fileName = curFileName; - if (m_preserveLogFileNameExtension) + if (this.m_preserveLogFileNameExtension) { fileName = Path.GetFileNameWithoutExtension(fileName); } - + int index = fileName.LastIndexOf("."); if (index > 0) { @@ -1034,155 +1012,151 @@ private int GetBackUpIndex(string curFileName) } return backUpIndex; - } + } - /// - /// Takes a list of files and a base file name, and looks for - /// 'incremented' versions of the base file. Bumps the max - /// count up to the highest count seen. - /// - /// - /// - private void InitializeRollBackups(string baseFile, ArrayList arrayFiles) - { - if (null != arrayFiles) - { - string baseFileLower = baseFile.ToLower(System.Globalization.CultureInfo.InvariantCulture); - - foreach(string curFileName in arrayFiles) - { - InitializeFromOneFile(baseFileLower, curFileName.ToLower(System.Globalization.CultureInfo.InvariantCulture)); - } - } - } - - /// - /// Calculates the RollPoint for the datePattern supplied. - /// - /// the date pattern to calculate the check period for - /// The RollPoint that is most accurate for the date pattern supplied - /// - /// Essentially the date pattern is examined to determine what the - /// most suitable roll point is. The roll point chosen is the roll point - /// with the smallest period that can be detected using the date pattern - /// supplied. i.e. if the date pattern only outputs the year, month, day - /// and hour then the smallest roll point that can be detected would be - /// and hourly roll point as minutes could not be detected. - /// - private RollPoint ComputeCheckPeriod(string datePattern) - { - // s_date1970 is 1970-01-01 00:00:00 this is UniversalSortableDateTimePattern - // (based on ISO 8601) using universal time. This date is used for reference - // purposes to calculate the resolution of the date pattern. - - // Get string representation of base line date - string r0 = s_date1970.ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - - // Check each type of rolling mode starting with the smallest increment. - for(int i = (int)RollPoint.TopOfMinute; i <= (int)RollPoint.TopOfMonth; i++) - { - // Get string representation of next pattern - string r1 = NextCheckDate(s_date1970, (RollPoint)i).ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - - LogLog.Debug(declaringType, "Type = ["+i+"], r0 = ["+r0+"], r1 = ["+r1+"]"); - - // Check if the string representations are different - if (r0 != null && r1 != null && !r0.Equals(r1)) - { - // Found highest precision roll point - return (RollPoint)i; - } - } - - return RollPoint.InvalidRollPoint; // Deliberately head for trouble... - } - - /// - /// Initialize the appender based on the options set - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Sets initial conditions including date/time roll over information, first check, - /// scheduledFilename, and calls to initialize - /// the current number of backups. - /// - /// - override public void ActivateOptions() - { - if (m_dateTime == null) - { - m_dateTime = new LocalDateTime(); - } - - if (m_rollDate && m_datePattern != null) - { - m_now = m_dateTime.Now; - m_rollPoint = ComputeCheckPeriod(m_datePattern); - - if (m_rollPoint == RollPoint.InvalidRollPoint) - { - throw new ArgumentException("Invalid RollPoint, unable to parse ["+m_datePattern+"]"); - } - - // next line added as this removes the name check in rollOver - m_nextCheck = NextCheckDate(m_now, m_rollPoint); - } - else - { - if (m_rollDate) - { - ErrorHandler.Error("Either DatePattern or rollingStyle options are not set for ["+Name+"]."); - } - } - - if (SecurityContext == null) - { - SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - using(SecurityContext.Impersonate(this)) - { - // Must convert the FileAppender's m_filePath to an absolute path before we - // call ExistingInit(). This will be done by the base.ActivateOptions() but - // we need to duplicate that functionality here first. - base.File = ConvertToFullPath(base.File.Trim()); - - // Store fully qualified base file name - m_baseFileName = base.File; - } + /// + /// Takes a list of files and a base file name, and looks for + /// 'incremented' versions of the base file. Bumps the max + /// count up to the highest count seen. + /// + /// + /// + private void InitializeRollBackups(string baseFile, ArrayList arrayFiles) + { + if (arrayFiles != null) + { + string baseFileLower = baseFile.ToLower(System.Globalization.CultureInfo.InvariantCulture); + + foreach (string curFileName in arrayFiles) + { + this.InitializeFromOneFile(baseFileLower, curFileName.ToLower(System.Globalization.CultureInfo.InvariantCulture)); + } + } + } + + /// + /// Calculates the RollPoint for the datePattern supplied. + /// + /// the date pattern to calculate the check period for. + /// The RollPoint that is most accurate for the date pattern supplied. + /// + /// Essentially the date pattern is examined to determine what the + /// most suitable roll point is. The roll point chosen is the roll point + /// with the smallest period that can be detected using the date pattern + /// supplied. i.e. if the date pattern only outputs the year, month, day + /// and hour then the smallest roll point that can be detected would be + /// and hourly roll point as minutes could not be detected. + /// + private RollPoint ComputeCheckPeriod(string datePattern) + { + // s_date1970 is 1970-01-01 00:00:00 this is UniversalSortableDateTimePattern + // (based on ISO 8601) using universal time. This date is used for reference + // purposes to calculate the resolution of the date pattern. + + // Get string representation of base line date + string r0 = s_date1970.ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); + + // Check each type of rolling mode starting with the smallest increment. + for (int i = (int)RollPoint.TopOfMinute; i <= (int)RollPoint.TopOfMonth; i++) + { + // Get string representation of next pattern + string r1 = this.NextCheckDate(s_date1970, (RollPoint)i).ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); + + LogLog.Debug(declaringType, "Type = [" + i + "], r0 = [" + r0 + "], r1 = [" + r1 + "]"); + + // Check if the string representations are different + if (r0 != null && r1 != null && !r0.Equals(r1)) + { + // Found highest precision roll point + return (RollPoint)i; + } + } + + return RollPoint.InvalidRollPoint; // Deliberately head for trouble... + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Sets initial conditions including date/time roll over information, first check, + /// scheduledFilename, and calls to initialize + /// the current number of backups. + /// + /// + public override void ActivateOptions() + { + if (this.m_dateTime == null) + { + this.m_dateTime = new LocalDateTime(); + } + + if (this.m_rollDate && this.m_datePattern != null) + { + this.m_now = this.m_dateTime.Now; + this.m_rollPoint = this.ComputeCheckPeriod(this.m_datePattern); + + if (this.m_rollPoint == RollPoint.InvalidRollPoint) + { + throw new ArgumentException("Invalid RollPoint, unable to parse [" + this.m_datePattern + "]"); + } + + // next line added as this removes the name check in rollOver + this.m_nextCheck = this.NextCheckDate(this.m_now, this.m_rollPoint); + } + else + { + if (this.m_rollDate) + { + this.ErrorHandler.Error("Either DatePattern or rollingStyle options are not set for [" + this.Name + "]."); + } + } + + if (this.SecurityContext == null) + { + this.SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + using (this.SecurityContext.Impersonate(this)) + { + // Must convert the FileAppender's m_filePath to an absolute path before we + // call ExistingInit(). This will be done by the base.ActivateOptions() but + // we need to duplicate that functionality here first. + this.File = ConvertToFullPath(this.File.Trim()); + + // Store fully qualified base file name + this.m_baseFileName = this.File; + } #if !NETCF - // initialize the mutex that is used to lock rolling - m_mutexForRolling = new Mutex(false, m_baseFileName.Replace("\\", "_").Replace(":", "_").Replace("/", "_")); + // initialize the mutex that is used to lock rolling + this.m_mutexForRolling = new Mutex(false, this.m_baseFileName.Replace("\\", "_").Replace(":", "_").Replace("/", "_")); #endif - if (m_rollDate && File != null && m_scheduledFilename == null) - { - m_scheduledFilename = CombinePath(File, m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - } - - ExistingInit(); - - base.ActivateOptions(); - } + if (this.m_rollDate && this.File != null && this.m_scheduledFilename == null) + { + this.m_scheduledFilename = this.CombinePath(this.File, this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); + } - #endregion - - #region Roll File + this.ExistingInit(); + base.ActivateOptions(); + } + /// - /// + /// /// /// /// .1, .2, .3, etc. @@ -1190,7 +1164,7 @@ override public void ActivateOptions() private string CombinePath(string path1, string path2) { string extension = Path.GetExtension(path1); - if (m_preserveLogFileNameExtension && extension.Length > 0) + if (this.m_preserveLogFileNameExtension && extension.Length > 0) { return Path.Combine(Path.GetDirectoryName(path1), Path.GetFileNameWithoutExtension(path1) + path2 + extension); } @@ -1200,583 +1174,568 @@ private string CombinePath(string path1, string path2) } } - /// - /// Rollover the file(s) to date/time tagged file(s). - /// - /// set to true if the file to be rolled is currently open - /// - /// - /// Rollover the file(s) to date/time tagged file(s). - /// Resets curSizeRollBackups. - /// If fileIsOpen is set then the new file is opened (through SafeOpenFile). - /// - /// - protected void RollOverTime(bool fileIsOpen) - { - if (m_staticLogFileName) - { - // Compute filename, but only if datePattern is specified - if (m_datePattern == null) - { - ErrorHandler.Error("Missing DatePattern option in rollOver()."); - return; - } - - //is the new file name equivalent to the 'current' one - //something has gone wrong if we hit this -- we should only - //roll over if the new file will be different from the old - string dateFormat = m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - if (m_scheduledFilename.Equals(CombinePath(File, dateFormat))) - { - ErrorHandler.Error("Compare " + m_scheduledFilename + " : " + CombinePath(File, dateFormat)); - return; - } - - if (fileIsOpen) - { - // close current file, and rename it to datedFilename - this.CloseFile(); - } - - //we may have to roll over a large number of backups here - for (int i = 1; i <= m_curSizeRollBackups; i++) - { - string from = CombinePath(File, "." + i); - string to = CombinePath(m_scheduledFilename, "." + i); - RollFile(from, to); - } - - RollFile(File, m_scheduledFilename); - } - - //We've cleared out the old date and are ready for the new - m_curSizeRollBackups = 0; - - //new scheduled name - m_scheduledFilename = CombinePath(File, m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - - if (fileIsOpen) - { - // This will also close the file. This is OK since multiple close operations are safe. - SafeOpenFile(m_baseFileName, false); - } - } - - /// - /// Renames file to file . - /// - /// Name of existing file to roll. - /// New name for file. - /// - /// - /// Renames file to file . It - /// also checks for existence of target file and deletes if it does. - /// - /// - protected void RollFile(string fromFile, string toFile) - { - if (FileExists(fromFile)) - { - // Delete the toFile if it exists - DeleteFile(toFile); - - // We may not have permission to move the file, or the file may be locked - try - { - LogLog.Debug(declaringType, "Moving [" + fromFile + "] -> [" + toFile + "]"); - using(SecurityContext.Impersonate(this)) - { - System.IO.File.Move(fromFile, toFile); - } - } - catch(Exception moveEx) - { - ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", moveEx, ErrorCode.GenericFailure); - } - } - else - { - LogLog.Warn(declaringType, "Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist"); - } - } - - /// - /// Test if a file exists at a specified path - /// - /// the path to the file - /// true if the file exists - /// - /// - /// Test if a file exists at a specified path - /// - /// - protected bool FileExists(string path) - { - using(SecurityContext.Impersonate(this)) - { - return System.IO.File.Exists(path); - } - } - - /// - /// Deletes the specified file if it exists. - /// - /// The file to delete. - /// - /// - /// Delete a file if is exists. - /// The file is first moved to a new filename then deleted. - /// This allows the file to be removed even when it cannot - /// be deleted, but it still can be moved. - /// - /// - protected void DeleteFile(string fileName) - { - if (FileExists(fileName)) - { - // We may not have permission to delete the file, or the file may be locked - - string fileToDelete = fileName; - - // Try to move the file to temp name. - // If the file is locked we may still be able to move it - string tempFileName = fileName + "." + Environment.TickCount + ".DeletePending"; - try - { - using(SecurityContext.Impersonate(this)) - { - System.IO.File.Move(fileName, tempFileName); - } - fileToDelete = tempFileName; - } - catch(Exception moveEx) - { - LogLog.Debug(declaringType, "Exception while moving file to be deleted [" + fileName + "] -> [" + tempFileName + "]", moveEx); - } - - // Try to delete the file (either the original or the moved file) - try - { - using(SecurityContext.Impersonate(this)) - { - System.IO.File.Delete(fileToDelete); - } - LogLog.Debug(declaringType, "Deleted file [" + fileName + "]"); - } - catch(Exception deleteEx) - { - if (fileToDelete == fileName) - { - // Unable to move or delete the file - ErrorHandler.Error("Exception while deleting file [" + fileToDelete + "]", deleteEx, ErrorCode.GenericFailure); - } - else - { - // Moved the file, but the delete failed. File is probably locked. - // The file should automatically be deleted when the lock is released. - LogLog.Debug(declaringType, "Exception while deleting temp file [" + fileToDelete + "]", deleteEx); - } - } - } - } - - /// - /// Implements file roll base on file size. - /// - /// - /// - /// If the maximum number of size based backups is reached - /// (curSizeRollBackups == maxSizeRollBackups) then the oldest - /// file is deleted -- its index determined by the sign of countDirection. - /// If countDirection < 0, then files - /// {File.1, ..., File.curSizeRollBackups -1} - /// are renamed to {File.2, ..., - /// File.curSizeRollBackups}. Moreover, File is - /// renamed File.1 and closed. - /// - /// - /// A new file is created to receive further log output. - /// - /// - /// If maxSizeRollBackups is equal to zero, then the - /// File is truncated with no backup files created. - /// - /// - /// If maxSizeRollBackups < 0, then File is - /// renamed if needed and no files are deleted. - /// - /// - protected void RollOverSize() - { - this.CloseFile(); // keep windows happy. - - LogLog.Debug(declaringType, "rolling over count ["+((CountingQuietTextWriter)QuietWriter).Count+"]"); - LogLog.Debug(declaringType, "maxSizeRollBackups ["+m_maxSizeRollBackups+"]"); - LogLog.Debug(declaringType, "curSizeRollBackups ["+m_curSizeRollBackups+"]"); - LogLog.Debug(declaringType, "countDirection ["+m_countDirection+"]"); - - RollOverRenameFiles(File); - - if (!m_staticLogFileName && m_countDirection >= 0) - { - m_curSizeRollBackups++; - } - - // This will also close the file. This is OK since multiple close operations are safe. - SafeOpenFile(m_baseFileName, false); - } - - /// - /// Implements file roll. - /// - /// the base name to rename - /// - /// - /// If the maximum number of size based backups is reached - /// (curSizeRollBackups == maxSizeRollBackups) then the oldest - /// file is deleted -- its index determined by the sign of countDirection. - /// If countDirection < 0, then files - /// {File.1, ..., File.curSizeRollBackups -1} - /// are renamed to {File.2, ..., - /// File.curSizeRollBackups}. - /// - /// - /// If maxSizeRollBackups is equal to zero, then the - /// File is truncated with no backup files created. - /// - /// - /// If maxSizeRollBackups < 0, then File is - /// renamed if needed and no files are deleted. - /// - /// - /// This is called by to rename the files. - /// - /// - protected void RollOverRenameFiles(string baseFileName) - { - // If maxBackups <= 0, then there is no file renaming to be done. - if (m_maxSizeRollBackups != 0) - { - if (m_countDirection < 0) - { - // Delete the oldest file, to keep Windows happy. - if (m_curSizeRollBackups == m_maxSizeRollBackups) - { - DeleteFile(CombinePath(baseFileName, "." + m_maxSizeRollBackups)); - m_curSizeRollBackups--; - } - - // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} - for (int i = m_curSizeRollBackups; i >= 1; i--) - { - RollFile((CombinePath(baseFileName, "." + i)), (CombinePath(baseFileName, "." + (i + 1)))); - } - - m_curSizeRollBackups++; - - // Rename fileName to fileName.1 - RollFile(baseFileName, CombinePath(baseFileName, ".1")); - } - else - { - //countDirection >= 0 - if (m_curSizeRollBackups >= m_maxSizeRollBackups && m_maxSizeRollBackups > 0) - { - //delete the first and keep counting up. - int oldestFileIndex = m_curSizeRollBackups - m_maxSizeRollBackups; - - // If static then there is 1 file without a number, therefore 1 less archive - if (m_staticLogFileName) - { - oldestFileIndex++; - } - - // If using a static log file then the base for the numbered sequence is the baseFileName passed in - // If not using a static log file then the baseFileName will already have a numbered postfix which - // we must remove, however it may have a date postfix which we must keep! - string archiveFileBaseName = baseFileName; - if (!m_staticLogFileName) - { - int lastDotIndex = archiveFileBaseName.LastIndexOf("."); - if (lastDotIndex >= 0) - { - archiveFileBaseName = archiveFileBaseName.Substring(0, lastDotIndex); - } - } - - // Delete the archive file - DeleteFile(CombinePath(archiveFileBaseName, "." + oldestFileIndex)); - } - - if (m_staticLogFileName) - { - m_curSizeRollBackups++; - RollFile(baseFileName, CombinePath(baseFileName, "." + m_curSizeRollBackups)); - } - } - } - } - - #endregion - - #region NextCheckDate - - /// - /// Get the start time of the next window for the current rollpoint - /// - /// the current date - /// the type of roll point we are working with - /// the start time for the next roll point an interval after the currentDateTime date - /// - /// - /// Returns the date of the next roll point after the currentDateTime date passed to the method. - /// - /// - /// The basic strategy is to subtract the time parts that are less significant - /// than the rollpoint from the current time. This should roll the time back to - /// the start of the time window for the current rollpoint. Then we add 1 window - /// worth of time and get the start time of the next window for the rollpoint. - /// - /// - protected DateTime NextCheckDate(DateTime currentDateTime, RollPoint rollPoint) - { - // Local variable to work on (this does not look very efficient) - DateTime current = currentDateTime; - - // Do slightly different things depending on what the type of roll point we want. - switch(rollPoint) - { - case RollPoint.TopOfMinute: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(1); - break; - - case RollPoint.TopOfHour: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(1); - break; - - case RollPoint.HalfDay: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - - if (current.Hour < 12) - { - current = current.AddHours(12 - current.Hour); - } - else - { - current = current.AddHours(-current.Hour); - current = current.AddDays(1); - } - break; - - case RollPoint.TopOfDay: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(-current.Hour); - current = current.AddDays(1); - break; - - case RollPoint.TopOfWeek: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(-current.Hour); - current = current.AddDays(7 - (int)current.DayOfWeek); - break; - - case RollPoint.TopOfMonth: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(-current.Hour); - current = current.AddDays(1 - current.Day); /* first day of month is 1 not 0 */ - current = current.AddMonths(1); - break; - } - return current; - } - - #endregion - - #region Private Instance Fields - - /// - /// This object supplies the current date/time. Allows test code to plug in - /// a method to control this class when testing date/time based rolling. The default - /// implementation uses the underlying value of DateTime.Now. - /// - private IDateTime m_dateTime = null; + /// + /// Rollover the file(s) to date/time tagged file(s). + /// + /// set to true if the file to be rolled is currently open. + /// + /// + /// Rollover the file(s) to date/time tagged file(s). + /// Resets curSizeRollBackups. + /// If fileIsOpen is set then the new file is opened (through SafeOpenFile). + /// + /// + protected void RollOverTime(bool fileIsOpen) + { + if (this.m_staticLogFileName) + { + // Compute filename, but only if datePattern is specified + if (this.m_datePattern == null) + { + this.ErrorHandler.Error("Missing DatePattern option in rollOver()."); + return; + } - /// - /// The date pattern. By default, the pattern is set to ".yyyy-MM-dd" - /// meaning daily rollover. - /// - private string m_datePattern = ".yyyy-MM-dd"; - - /// - /// The actual formatted filename that is currently being written to - /// or will be the file transferred to on roll over - /// (based on staticLogFileName). - /// - private string m_scheduledFilename = null; - - /// - /// The timestamp when we shall next recompute the filename. - /// - private DateTime m_nextCheck = DateTime.MaxValue; - - /// - /// Holds date of last roll over - /// - private DateTime m_now; - - /// - /// The type of rolling done - /// - private RollPoint m_rollPoint; - - /// - /// The default maximum file size is 10MB - /// - private long m_maxFileSize = 10*1024*1024; - - /// - /// There is zero backup files by default - /// - private int m_maxSizeRollBackups = 0; + // is the new file name equivalent to the 'current' one + // something has gone wrong if we hit this -- we should only + // roll over if the new file will be different from the old + string dateFormat = this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); + if (this.m_scheduledFilename.Equals(this.CombinePath(this.File, dateFormat))) + { + this.ErrorHandler.Error("Compare " + this.m_scheduledFilename + " : " + this.CombinePath(this.File, dateFormat)); + return; + } - /// - /// How many sized based backups have been made so far - /// - private int m_curSizeRollBackups = 0; - - /// - /// The rolling file count direction. - /// - private int m_countDirection = -1; - - /// - /// The rolling mode used in this appender. - /// - private RollingMode m_rollingStyle = RollingMode.Composite; + if (fileIsOpen) + { + // close current file, and rename it to datedFilename + this.CloseFile(); + } - /// - /// Cache flag set if we are rolling by date. - /// - private bool m_rollDate = true; + // we may have to roll over a large number of backups here + for (int i = 1; i <= this.m_curSizeRollBackups; i++) + { + string from = this.CombinePath(this.File, "." + i); + string to = this.CombinePath(this.m_scheduledFilename, "." + i); + this.RollFile(from, to); + } - /// - /// Cache flag set if we are rolling by size. - /// - private bool m_rollSize = true; - - /// - /// Value indicating whether to always log to the same file. - /// - private bool m_staticLogFileName = true; - - /// - /// Value indicating whether to preserve the file name extension when rolling. - /// - private bool m_preserveLogFileNameExtension = false; + this.RollFile(this.File, this.m_scheduledFilename); + } + // We've cleared out the old date and are ready for the new + this.m_curSizeRollBackups = 0; - /// - /// FileName provided in configuration. Used for rolling properly - /// - private string m_baseFileName; + // new scheduled name + this.m_scheduledFilename = this.CombinePath(this.File, this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); -#if !NETCF - /// - /// A mutex that is used to lock rolling of files. - /// - private Mutex m_mutexForRolling; -#endif + if (fileIsOpen) + { + // This will also close the file. This is OK since multiple close operations are safe. + this.SafeOpenFile(this.m_baseFileName, false); + } + } - #endregion Private Instance Fields + /// + /// Renames file to file . + /// + /// Name of existing file to roll. + /// New name for file. + /// + /// + /// Renames file to file . It + /// also checks for existence of target file and deletes if it does. + /// + /// + protected void RollFile(string fromFile, string toFile) + { + if (this.FileExists(fromFile)) + { + // Delete the toFile if it exists + this.DeleteFile(toFile); - #region Static Members + // We may not have permission to move the file, or the file may be locked + try + { + LogLog.Debug(declaringType, "Moving [" + fromFile + "] -> [" + toFile + "]"); + using (this.SecurityContext.Impersonate(this)) + { + System.IO.File.Move(fromFile, toFile); + } + } + catch (Exception moveEx) + { + this.ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", moveEx, ErrorCode.GenericFailure); + } + } + else + { + LogLog.Warn(declaringType, "Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist"); + } + } - /// - /// The 1st of January 1970 in UTC - /// - private static readonly DateTime s_date1970 = new DateTime(1970, 1, 1); + /// + /// Test if a file exists at a specified path. + /// + /// the path to the file. + /// true if the file exists. + /// + /// + /// Test if a file exists at a specified path. + /// + /// + protected bool FileExists(string path) + { + using (this.SecurityContext.Impersonate(this)) + { + return System.IO.File.Exists(path); + } + } - #endregion + /// + /// Deletes the specified file if it exists. + /// + /// The file to delete. + /// + /// + /// Delete a file if is exists. + /// The file is first moved to a new filename then deleted. + /// This allows the file to be removed even when it cannot + /// be deleted, but it still can be moved. + /// + /// + protected void DeleteFile(string fileName) + { + if (this.FileExists(fileName)) + { + // We may not have permission to delete the file, or the file may be locked + string fileToDelete = fileName; - #region DateTime + // Try to move the file to temp name. + // If the file is locked we may still be able to move it + string tempFileName = fileName + "." + Environment.TickCount + ".DeletePending"; + try + { + using (this.SecurityContext.Impersonate(this)) + { + System.IO.File.Move(fileName, tempFileName); + } + + fileToDelete = tempFileName; + } + catch (Exception moveEx) + { + LogLog.Debug(declaringType, "Exception while moving file to be deleted [" + fileName + "] -> [" + tempFileName + "]", moveEx); + } - /// - /// This interface is used to supply Date/Time information to the . - /// - /// - /// This interface is used to supply Date/Time information to the . - /// Used primarily to allow test classes to plug themselves in so they can - /// supply test date/times. - /// - public interface IDateTime - { - /// - /// Gets the current time. - /// - /// The current time. - /// - /// - /// Gets the current time. - /// - /// - DateTime Now { get; } - } - - /// - /// Default implementation of that returns the current time. - /// - private class LocalDateTime : IDateTime - { - /// - /// Gets the current time. - /// - /// The current time. - /// - /// - /// Gets the current time. - /// - /// - public DateTime Now - { - get { return DateTime.Now; } - } - } + // Try to delete the file (either the original or the moved file) + try + { + using (this.SecurityContext.Impersonate(this)) + { + System.IO.File.Delete(fileToDelete); + } + + LogLog.Debug(declaringType, "Deleted file [" + fileName + "]"); + } + catch (Exception deleteEx) + { + if (fileToDelete == fileName) + { + // Unable to move or delete the file + this.ErrorHandler.Error("Exception while deleting file [" + fileToDelete + "]", deleteEx, ErrorCode.GenericFailure); + } + else + { + // Moved the file, but the delete failed. File is probably locked. + // The file should automatically be deleted when the lock is released. + LogLog.Debug(declaringType, "Exception while deleting temp file [" + fileToDelete + "]", deleteEx); + } + } + } + } -#if !NET_1_0 && !CLI_1_0 && !NETCF /// - /// Implementation of that returns the current time as the coordinated universal time (UTC). - /// - private class UniversalDateTime : IDateTime - { - /// - /// Gets the current time. - /// - /// The current time. - /// - /// - /// Gets the current time. - /// - /// - public DateTime Now - { - get { return DateTime.UtcNow; } - } - } + /// Implements file roll base on file size. + /// + /// + /// + /// If the maximum number of size based backups is reached + /// (curSizeRollBackups == maxSizeRollBackups) then the oldest + /// file is deleted -- its index determined by the sign of countDirection. + /// If countDirection < 0, then files + /// {File.1, ..., File.curSizeRollBackups -1} + /// are renamed to {File.2, ..., + /// File.curSizeRollBackups}. Moreover, File is + /// renamed File.1 and closed. + /// + /// + /// A new file is created to receive further log output. + /// + /// + /// If maxSizeRollBackups is equal to zero, then the + /// File is truncated with no backup files created. + /// + /// + /// If maxSizeRollBackups < 0, then File is + /// renamed if needed and no files are deleted. + /// + /// + protected void RollOverSize() + { + this.CloseFile(); // keep windows happy. + + LogLog.Debug(declaringType, "rolling over count [" + ((CountingQuietTextWriter)this.QuietWriter).Count + "]"); + LogLog.Debug(declaringType, "maxSizeRollBackups [" + this.m_maxSizeRollBackups + "]"); + LogLog.Debug(declaringType, "curSizeRollBackups [" + this.m_curSizeRollBackups + "]"); + LogLog.Debug(declaringType, "countDirection [" + this.m_countDirection + "]"); + + this.RollOverRenameFiles(this.File); + + if (!this.m_staticLogFileName && this.m_countDirection >= 0) + { + this.m_curSizeRollBackups++; + } + + // This will also close the file. This is OK since multiple close operations are safe. + this.SafeOpenFile(this.m_baseFileName, false); + } + + /// + /// Implements file roll. + /// + /// the base name to rename. + /// + /// + /// If the maximum number of size based backups is reached + /// (curSizeRollBackups == maxSizeRollBackups) then the oldest + /// file is deleted -- its index determined by the sign of countDirection. + /// If countDirection < 0, then files + /// {File.1, ..., File.curSizeRollBackups -1} + /// are renamed to {File.2, ..., + /// File.curSizeRollBackups}. + /// + /// + /// If maxSizeRollBackups is equal to zero, then the + /// File is truncated with no backup files created. + /// + /// + /// If maxSizeRollBackups < 0, then File is + /// renamed if needed and no files are deleted. + /// + /// + /// This is called by to rename the files. + /// + /// + protected void RollOverRenameFiles(string baseFileName) + { + // If maxBackups <= 0, then there is no file renaming to be done. + if (this.m_maxSizeRollBackups != 0) + { + if (this.m_countDirection < 0) + { + // Delete the oldest file, to keep Windows happy. + if (this.m_curSizeRollBackups == this.m_maxSizeRollBackups) + { + this.DeleteFile(this.CombinePath(baseFileName, "." + this.m_maxSizeRollBackups)); + this.m_curSizeRollBackups--; + } + + // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} + for (int i = this.m_curSizeRollBackups; i >= 1; i--) + { + this.RollFile(this.CombinePath(baseFileName, "." + i), this.CombinePath(baseFileName, "." + (i + 1))); + } + + this.m_curSizeRollBackups++; + + // Rename fileName to fileName.1 + this.RollFile(baseFileName, this.CombinePath(baseFileName, ".1")); + } + else + { + // countDirection >= 0 + if (this.m_curSizeRollBackups >= this.m_maxSizeRollBackups && this.m_maxSizeRollBackups > 0) + { + // delete the first and keep counting up. + int oldestFileIndex = this.m_curSizeRollBackups - this.m_maxSizeRollBackups; + + // If static then there is 1 file without a number, therefore 1 less archive + if (this.m_staticLogFileName) + { + oldestFileIndex++; + } + + // If using a static log file then the base for the numbered sequence is the baseFileName passed in + // If not using a static log file then the baseFileName will already have a numbered postfix which + // we must remove, however it may have a date postfix which we must keep! + string archiveFileBaseName = baseFileName; + if (!this.m_staticLogFileName) + { + int lastDotIndex = archiveFileBaseName.LastIndexOf("."); + if (lastDotIndex >= 0) + { + archiveFileBaseName = archiveFileBaseName.Substring(0, lastDotIndex); + } + } + + // Delete the archive file + this.DeleteFile(this.CombinePath(archiveFileBaseName, "." + oldestFileIndex)); + } + + if (this.m_staticLogFileName) + { + this.m_curSizeRollBackups++; + this.RollFile(baseFileName, this.CombinePath(baseFileName, "." + this.m_curSizeRollBackups)); + } + } + } + } + + /// + /// Get the start time of the next window for the current rollpoint. + /// + /// the current date. + /// the type of roll point we are working with. + /// the start time for the next roll point an interval after the currentDateTime date. + /// + /// + /// Returns the date of the next roll point after the currentDateTime date passed to the method. + /// + /// + /// The basic strategy is to subtract the time parts that are less significant + /// than the rollpoint from the current time. This should roll the time back to + /// the start of the time window for the current rollpoint. Then we add 1 window + /// worth of time and get the start time of the next window for the rollpoint. + /// + /// + protected DateTime NextCheckDate(DateTime currentDateTime, RollPoint rollPoint) + { + // Local variable to work on (this does not look very efficient) + DateTime current = currentDateTime; + + // Do slightly different things depending on what the type of roll point we want. + switch (rollPoint) + { + case RollPoint.TopOfMinute: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(1); + break; + + case RollPoint.TopOfHour: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(1); + break; + + case RollPoint.HalfDay: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + + if (current.Hour < 12) + { + current = current.AddHours(12 - current.Hour); + } + else + { + current = current.AddHours(-current.Hour); + current = current.AddDays(1); + } + + break; + + case RollPoint.TopOfDay: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(-current.Hour); + current = current.AddDays(1); + break; + + case RollPoint.TopOfWeek: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(-current.Hour); + current = current.AddDays(7 - (int)current.DayOfWeek); + break; + + case RollPoint.TopOfMonth: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(-current.Hour); + current = current.AddDays(1 - current.Day); /* first day of month is 1 not 0 */ + current = current.AddMonths(1); + break; + } + + return current; + } + + /// + /// This object supplies the current date/time. Allows test code to plug in + /// a method to control this class when testing date/time based rolling. The default + /// implementation uses the underlying value of DateTime.Now. + /// + private IDateTime m_dateTime = null; + + /// + /// The date pattern. By default, the pattern is set to ".yyyy-MM-dd" + /// meaning daily rollover. + /// + private string m_datePattern = ".yyyy-MM-dd"; + + /// + /// The actual formatted filename that is currently being written to + /// or will be the file transferred to on roll over + /// (based on staticLogFileName). + /// + private string m_scheduledFilename = null; + + /// + /// The timestamp when we shall next recompute the filename. + /// + private DateTime m_nextCheck = DateTime.MaxValue; + + /// + /// Holds date of last roll over. + /// + private DateTime m_now; + + /// + /// The type of rolling done. + /// + private RollPoint m_rollPoint; + + /// + /// The default maximum file size is 10MB. + /// + private long m_maxFileSize = 10 * 1024 * 1024; + + /// + /// There is zero backup files by default. + /// + private int m_maxSizeRollBackups = 0; + + /// + /// How many sized based backups have been made so far. + /// + private int m_curSizeRollBackups = 0; + + /// + /// The rolling file count direction. + /// + private int m_countDirection = -1; + + /// + /// The rolling mode used in this appender. + /// + private RollingMode m_rollingStyle = RollingMode.Composite; + + /// + /// Cache flag set if we are rolling by date. + /// + private bool m_rollDate = true; + + /// + /// Cache flag set if we are rolling by size. + /// + private bool m_rollSize = true; + + /// + /// Value indicating whether to always log to the same file. + /// + private bool m_staticLogFileName = true; + + /// + /// Value indicating whether to preserve the file name extension when rolling. + /// + private bool m_preserveLogFileNameExtension = false; + + /// + /// FileName provided in configuration. Used for rolling properly. + /// + private string m_baseFileName; + +#if !NETCF + /// + /// A mutex that is used to lock rolling of files. + /// + private Mutex m_mutexForRolling; #endif + + /// + /// The 1st of January 1970 in UTC. + /// + private static readonly DateTime s_date1970 = new DateTime(1970, 1, 1); + + /// + /// This interface is used to supply Date/Time information to the . + /// + /// + /// This interface is used to supply Date/Time information to the . + /// Used primarily to allow test classes to plug themselves in so they can + /// supply test date/times. + /// + public interface IDateTime + { + /// + /// Gets the current time. + /// + /// The current time. + /// + /// + /// Gets the current time. + /// + /// + DateTime Now { get; } + } + + /// + /// Default implementation of that returns the current time. + /// + private class LocalDateTime : IDateTime + { + /// + /// Gets the current time. + /// + /// The current time. + /// + /// + /// Gets the current time. + /// + /// + public DateTime Now + { + get { return DateTime.Now; } + } + } - #endregion DateTime - } +#if !NET_1_0 && !CLI_1_0 && !NETCF + /// + /// Implementation of that returns the current time as the coordinated universal time (UTC). + /// + private class UniversalDateTime : IDateTime + { + /// + /// Gets the current time. + /// + /// The current time. + /// + /// + /// Gets the current time. + /// + /// + public DateTime Now + { + get { return DateTime.UtcNow; } + } + } +#endif + + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs index d503c74f72f..724d7d4c3c5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for System.Web.Mail // SSCLI 1.0 has no support for System.Web.Mail @@ -31,95 +29,91 @@ #if NET_2_0 || MONO_2_0 using System.Net.Mail; + #else using System.Web.Mail; #endif -using log4net.Layout; using log4net.Core; +using log4net.Layout; using log4net.Util; namespace log4net.Appender { - /// - /// Send an e-mail when a specific logging event occurs, typically on errors - /// or fatal errors. - /// - /// - /// - /// The number of logging events delivered in this e-mail depend on - /// the value of option. The - /// keeps only the last - /// logging events in its - /// cyclic buffer. This keeps memory requirements at a reasonable level while - /// still delivering useful application context. - /// - /// - /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime. - /// For these features to be enabled you need to ensure that you are using a version of - /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are - /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending - /// unauthenticated messages to a server listening on port 25 (the default) is supported. - /// - /// - /// Authentication is supported by setting the property to - /// either or . - /// If using authentication then the - /// and properties must also be set. - /// - /// - /// To set the SMTP server port use the property. The default port is 25. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class SmtpAppender : BufferingAppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public SmtpAppender() - { - } - - #endregion // Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions). - /// - /// + /// + /// Send an e-mail when a specific logging event occurs, typically on errors + /// or fatal errors. + /// + /// + /// + /// The number of logging events delivered in this e-mail depend on + /// the value of option. The + /// keeps only the last + /// logging events in its + /// cyclic buffer. This keeps memory requirements at a reasonable level while + /// still delivering useful application context. + /// + /// + /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime. + /// For these features to be enabled you need to ensure that you are using a version of + /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are + /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending + /// unauthenticated messages to a server listening on port 25 (the default) is supported. + /// + /// + /// Authentication is supported by setting the property to + /// either or . + /// If using authentication then the + /// and properties must also be set. + /// + /// + /// To set the SMTP server port use the property. The default port is 25. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class SmtpAppender : BufferingAppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public SmtpAppender() + { + } + + /// + /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions). + /// + /// /// /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// /// /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// - /// - /// + /// + /// /// /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// /// /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// - /// - public string To - { - get { return m_to; } - set { m_to = MaybeTrimSeparators(value); } - } + /// + public string To + { + get { return this.m_to; } + set { this.m_to = MaybeTrimSeparators(value); } + } /// - /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses + /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses /// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions). /// /// @@ -140,8 +134,8 @@ public string To /// public string Cc { - get { return m_cc; } - set { m_cc = MaybeTrimSeparators(value); } + get { return this.m_cc; } + set { this.m_cc = MaybeTrimSeparators(value); } } /// @@ -158,349 +152,341 @@ public string Cc /// public string Bcc { - get { return m_bcc; } - set { m_bcc = MaybeTrimSeparators(value); } + get { return this.m_bcc; } + set { this.m_bcc = MaybeTrimSeparators(value); } + } + + /// + /// Gets or sets the e-mail address of the sender. + /// + /// + /// The e-mail address of the sender. + /// + /// + /// + /// The e-mail address of the sender. + /// + /// + public string From + { + get { return this.m_from; } + set { this.m_from = value; } + } + + /// + /// Gets or sets the subject line of the e-mail message. + /// + /// + /// The subject line of the e-mail message. + /// + /// + /// + /// The subject line of the e-mail message. + /// + /// + public string Subject + { + get { return this.m_subject; } + set { this.m_subject = value; } + } + + /// + /// Gets or sets the name of the SMTP relay mail server to use to send + /// the e-mail messages. + /// + /// + /// The name of the e-mail relay server. If SmtpServer is not set, the + /// name of the local SMTP server is used. + /// + /// + /// + /// The name of the e-mail relay server. If SmtpServer is not set, the + /// name of the local SMTP server is used. + /// + /// + public string SmtpHost + { + get { return this.m_smtpHost; } + set { this.m_smtpHost = value; } } - /// - /// Gets or sets the e-mail address of the sender. - /// - /// - /// The e-mail address of the sender. - /// - /// - /// - /// The e-mail address of the sender. - /// - /// - public string From - { - get { return m_from; } - set { m_from = value; } - } - - /// - /// Gets or sets the subject line of the e-mail message. - /// - /// - /// The subject line of the e-mail message. - /// - /// - /// - /// The subject line of the e-mail message. - /// - /// - public string Subject - { - get { return m_subject; } - set { m_subject = value; } - } - - /// - /// Gets or sets the name of the SMTP relay mail server to use to send - /// the e-mail messages. - /// - /// - /// The name of the e-mail relay server. If SmtpServer is not set, the - /// name of the local SMTP server is used. - /// - /// - /// - /// The name of the e-mail relay server. If SmtpServer is not set, the - /// name of the local SMTP server is used. - /// - /// - public string SmtpHost - { - get { return m_smtpHost; } - set { m_smtpHost = value; } - } - - /// - /// Obsolete - /// - /// - /// Use the BufferingAppenderSkeleton Fix methods instead - /// - /// - /// - /// Obsolete property. - /// - /// - [Obsolete("Use the BufferingAppenderSkeleton Fix methods. Scheduled removal in v10.0.0.")] - public bool LocationInfo - { - get { return false; } - set { ; } - } - - /// - /// The mode to use to authentication with the SMTP server - /// - /// - /// Authentication is only available on the MS .NET 1.1 runtime. - /// - /// Valid Authentication mode values are: , - /// , and . - /// The default value is . When using - /// you must specify the - /// and to use to authenticate. - /// When using the Windows credentials for the current - /// thread, if impersonating, or the process will be used to authenticate. - /// - /// - public SmtpAuthentication Authentication - { - get { return m_authentication; } - set { m_authentication = value; } - } - - /// - /// The username to use to authenticate with the SMTP server - /// - /// - /// Authentication is only available on the MS .NET 1.1 runtime. - /// - /// A and must be specified when - /// is set to , - /// otherwise the username will be ignored. - /// - /// - public string Username - { - get { return m_username; } - set { m_username = value; } - } - - /// - /// The password to use to authenticate with the SMTP server - /// - /// - /// Authentication is only available on the MS .NET 1.1 runtime. - /// - /// A and must be specified when - /// is set to , - /// otherwise the password will be ignored. - /// - /// - public string Password - { - get { return m_password; } - set { m_password = value; } - } - - /// - /// The port on which the SMTP server is listening - /// - /// - /// Server Port is only available on the MS .NET 1.1 runtime. - /// - /// The port on which the SMTP server is listening. The default - /// port is 25. The Port can only be changed when running on - /// the MS .NET 1.1 runtime. - /// - /// - public int Port - { - get { return m_port; } - set { m_port = value; } - } - - /// - /// Gets or sets the priority of the e-mail message - /// - /// - /// One of the values. - /// - /// - /// - /// Sets the priority of the e-mails generated by this - /// appender. The default priority is . - /// - /// - /// If you are using this appender to report errors then - /// you may want to set the priority to . - /// - /// - public MailPriority Priority - { - get { return m_mailPriority; } - set { m_mailPriority = value; } - } + /// + /// Gets or sets a value indicating whether obsolete. + /// + /// + /// Use the BufferingAppenderSkeleton Fix methods instead. + /// + /// + /// + /// Obsolete property. + /// + /// + [Obsolete("Use the BufferingAppenderSkeleton Fix methods. Scheduled removal in v10.0.0.")] + public bool LocationInfo + { + get { return false; } + set { } + } + + /// + /// Gets or sets the mode to use to authentication with the SMTP server. + /// + /// + /// Authentication is only available on the MS .NET 1.1 runtime. + /// + /// Valid Authentication mode values are: , + /// , and . + /// The default value is . When using + /// you must specify the + /// and to use to authenticate. + /// When using the Windows credentials for the current + /// thread, if impersonating, or the process will be used to authenticate. + /// + /// + public SmtpAuthentication Authentication + { + get { return this.m_authentication; } + set { this.m_authentication = value; } + } + + /// + /// Gets or sets the username to use to authenticate with the SMTP server. + /// + /// + /// Authentication is only available on the MS .NET 1.1 runtime. + /// + /// A and must be specified when + /// is set to , + /// otherwise the username will be ignored. + /// + /// + public string Username + { + get { return this.m_username; } + set { this.m_username = value; } + } + + /// + /// Gets or sets the password to use to authenticate with the SMTP server. + /// + /// + /// Authentication is only available on the MS .NET 1.1 runtime. + /// + /// A and must be specified when + /// is set to , + /// otherwise the password will be ignored. + /// + /// + public string Password + { + get { return this.m_password; } + set { this.m_password = value; } + } + + /// + /// Gets or sets the port on which the SMTP server is listening. + /// + /// + /// Server Port is only available on the MS .NET 1.1 runtime. + /// + /// The port on which the SMTP server is listening. The default + /// port is 25. The Port can only be changed when running on + /// the MS .NET 1.1 runtime. + /// + /// + public int Port + { + get { return this.m_port; } + set { this.m_port = value; } + } + + /// + /// Gets or sets the priority of the e-mail message. + /// + /// + /// One of the values. + /// + /// + /// + /// Sets the priority of the e-mails generated by this + /// appender. The default priority is . + /// + /// + /// If you are using this appender to report errors then + /// you may want to set the priority to . + /// + /// + public MailPriority Priority + { + get { return this.m_mailPriority; } + set { this.m_mailPriority = value; } + } #if NET_2_0 || MONO_2_0 /// - /// Enable or disable use of SSL when sending e-mail message + /// Gets or sets a value indicating whether enable or disable use of SSL when sending e-mail message. /// /// - /// This is available on MS .NET 2.0 runtime and higher + /// This is available on MS .NET 2.0 runtime and higher. /// public bool EnableSsl { - get { return m_enableSsl; } - set { m_enableSsl = value; } + get { return this.m_enableSsl; } + set { this.m_enableSsl = value; } } /// /// Gets or sets the reply-to e-mail address. /// /// - /// This is available on MS .NET 2.0 runtime and higher + /// This is available on MS .NET 2.0 runtime and higher. /// public string ReplyTo { - get { return m_replyTo; } - set { m_replyTo = value; } + get { return this.m_replyTo; } + set { this.m_replyTo = value; } } #endif - /// - /// Gets or sets the subject encoding to be used. - /// - /// - /// The default encoding is the operating system's current ANSI codepage. - /// - public Encoding SubjectEncoding - { - get { return m_subjectEncoding; } - set { m_subjectEncoding = value; } - } - - /// - /// Gets or sets the body encoding to be used. - /// - /// - /// The default encoding is the operating system's current ANSI codepage. - /// - public Encoding BodyEncoding - { - get { return m_bodyEncoding; } - set { m_bodyEncoding = value; } - } - - #endregion // Public Instance Properties - - #region Override implementation of BufferingAppenderSkeleton - - /// - /// Sends the contents of the cyclic buffer as an e-mail message. - /// - /// The logging events to send. - override protected void SendBuffer(LoggingEvent[] events) - { - // Note: this code already owns the monitor for this - // appender. This frees us from needing to synchronize again. - try - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - - string t = Layout.Header; - if (t != null) - { - writer.Write(t); - } + /// + /// Gets or sets the subject encoding to be used. + /// + /// + /// The default encoding is the operating system's current ANSI codepage. + /// + public Encoding SubjectEncoding + { + get { return this.m_subjectEncoding; } + set { this.m_subjectEncoding = value; } + } - for(int i = 0; i < events.Length; i++) - { - // Render the event and append the text to the buffer - RenderLoggingEvent(writer, events[i]); - } + /// + /// Gets or sets the body encoding to be used. + /// + /// + /// The default encoding is the operating system's current ANSI codepage. + /// + public Encoding BodyEncoding + { + get { return this.m_bodyEncoding; } + set { this.m_bodyEncoding = value; } + } + + /// + /// Sends the contents of the cyclic buffer as an e-mail message. + /// + /// The logging events to send. + protected override void SendBuffer(LoggingEvent[] events) + { + // Note: this code already owns the monitor for this + // appender. This frees us from needing to synchronize again. + try + { + StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - t = Layout.Footer; - if (t != null) - { - writer.Write(t); - } + string t = this.Layout.Header; + if (t != null) + { + writer.Write(t); + } - SendEmail(writer.ToString()); - } - catch(Exception e) - { - ErrorHandler.Error("Error occurred while sending e-mail notification.", e); - } - } - - #endregion // Override implementation of BufferingAppenderSkeleton - - #region Override implementation of AppenderSkeleton - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion // Override implementation of AppenderSkeleton - - #region Protected Methods - - /// - /// Send the email message - /// - /// the body text to include in the mail - virtual protected void SendEmail(string messageBody) - { + for (int i = 0; i < events.Length; i++) + { + // Render the event and append the text to the buffer + this.RenderLoggingEvent(writer, events[i]); + } + + t = this.Layout.Footer; + if (t != null) + { + writer.Write(t); + } + + this.SendEmail(writer.ToString()); + } + catch (Exception e) + { + this.ErrorHandler.Error("Error occurred while sending e-mail notification.", e); + } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Send the email message. + /// + /// the body text to include in the mail. + protected virtual void SendEmail(string messageBody) + { #if NET_2_0 || MONO_2_0 - // .NET 2.0 has a new API for SMTP email System.Net.Mail - // This API supports credentials and multiple hosts correctly. - // The old API is deprecated. - - // Create and configure the smtp client - SmtpClient smtpClient = new SmtpClient(); - if (!String.IsNullOrEmpty(m_smtpHost)) - { - smtpClient.Host = m_smtpHost; - } - smtpClient.Port = m_port; - smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; - smtpClient.EnableSsl = m_enableSsl; - - if (m_authentication == SmtpAuthentication.Basic) - { - // Perform basic authentication - smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password); - } - else if (m_authentication == SmtpAuthentication.Ntlm) - { - // Perform integrated authentication (NTLM) - smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; - } + // .NET 2.0 has a new API for SMTP email System.Net.Mail + // This API supports credentials and multiple hosts correctly. + // The old API is deprecated. + + // Create and configure the smtp client + SmtpClient smtpClient = new SmtpClient(); + if (!string.IsNullOrEmpty(this.m_smtpHost)) + { + smtpClient.Host = this.m_smtpHost; + } + + smtpClient.Port = this.m_port; + smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + smtpClient.EnableSsl = this.m_enableSsl; + + if (this.m_authentication == SmtpAuthentication.Basic) + { + // Perform basic authentication + smtpClient.Credentials = new System.Net.NetworkCredential(this.m_username, this.m_password); + } + else if (this.m_authentication == SmtpAuthentication.Ntlm) + { + // Perform integrated authentication (NTLM) + smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; + } using (MailMessage mailMessage = new MailMessage()) { mailMessage.Body = messageBody; - mailMessage.BodyEncoding = m_bodyEncoding; - mailMessage.From = new MailAddress(m_from); - mailMessage.To.Add(m_to); - if (!String.IsNullOrEmpty(m_cc)) + mailMessage.BodyEncoding = this.m_bodyEncoding; + mailMessage.From = new MailAddress(this.m_from); + mailMessage.To.Add(this.m_to); + if (!string.IsNullOrEmpty(this.m_cc)) { - mailMessage.CC.Add(m_cc); + mailMessage.CC.Add(this.m_cc); } - if (!String.IsNullOrEmpty(m_bcc)) + + if (!string.IsNullOrEmpty(this.m_bcc)) { - mailMessage.Bcc.Add(m_bcc); + mailMessage.Bcc.Add(this.m_bcc); } - if (!String.IsNullOrEmpty(m_replyTo)) + + if (!string.IsNullOrEmpty(this.m_replyTo)) { // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete: // 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202' #if !NET_4_0 && !MONO_4_0 mailMessage.ReplyTo = new MailAddress(m_replyTo); #else - mailMessage.ReplyToList.Add(new MailAddress(m_replyTo)); + mailMessage.ReplyToList.Add(new MailAddress(this.m_replyTo)); #endif } - mailMessage.Subject = m_subject; - mailMessage.SubjectEncoding = m_subjectEncoding; - mailMessage.Priority = m_mailPriority; + + mailMessage.Subject = this.m_subject; + mailMessage.SubjectEncoding = this.m_subjectEncoding; + mailMessage.Priority = this.m_mailPriority; // TODO: Consider using SendAsync to send the message without blocking. This would be a change in // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors. @@ -583,87 +569,78 @@ virtual protected void SendEmail(string messageBody) SmtpMail.Send(mailMessage); #endif // if NET_2_0 - } - - #endregion // Protected Methods - - #region Private Instance Fields - - private string m_to; + } + + private string m_to; private string m_cc; private string m_bcc; - private string m_from; - private string m_subject; - private string m_smtpHost; - private Encoding m_subjectEncoding = Encoding.UTF8; - private Encoding m_bodyEncoding = Encoding.UTF8; + private string m_from; + private string m_subject; + private string m_smtpHost; + private Encoding m_subjectEncoding = Encoding.UTF8; + private Encoding m_bodyEncoding = Encoding.UTF8; - // authentication fields - private SmtpAuthentication m_authentication = SmtpAuthentication.None; - private string m_username; - private string m_password; + // authentication fields + private SmtpAuthentication m_authentication = SmtpAuthentication.None; + private string m_username; + private string m_password; - // server port, default port 25 - private int m_port = 25; + // server port, default port 25 + private int m_port = 25; - private MailPriority m_mailPriority = MailPriority.Normal; + private MailPriority m_mailPriority = MailPriority.Normal; #if NET_2_0 || MONO_2_0 private bool m_enableSsl = false; - private string m_replyTo; + private string m_replyTo; #endif + + /// + /// Values for the property. + /// + /// + /// + /// SMTP authentication modes. + /// + /// + public enum SmtpAuthentication + { + /// + /// No authentication + /// + None, - #endregion // Private Instance Fields - - #region SmtpAuthentication Enum - - /// - /// Values for the property. - /// - /// - /// - /// SMTP authentication modes. - /// - /// - public enum SmtpAuthentication - { - /// - /// No authentication - /// - None, - - /// - /// Basic authentication. - /// - /// - /// Requires a username and password to be supplied - /// - Basic, - - /// - /// Integrated authentication - /// - /// - /// Uses the Windows credentials from the current thread or process to authenticate. - /// - Ntlm - } - - #endregion // SmtpAuthentication Enum - - private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; - /// - /// trims leading and trailing commas or semicolons + /// Basic authentication. /// - private static string MaybeTrimSeparators(string s) { + /// + /// Requires a username and password to be supplied + /// + Basic, + + /// + /// Integrated authentication + /// + /// + /// Uses the Windows credentials from the current thread or process to authenticate. + /// + Ntlm, + } + + private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; + + /// + /// trims leading and trailing commas or semicolons. + /// + private static string MaybeTrimSeparators(string s) + { #if NET_2_0 || MONO_2_0 - return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); + return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); #else return s != null && s.Length > 0 ? s : s.Trim(ADDRESS_DELIMITERS); #endif - } - } + } + } } #endif // !NETCF && !SSCLI diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs index dcd8438638c..f6e385141ac 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs @@ -1,357 +1,333 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Layout; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Send an email when a specific logging event occurs, typically on errors - /// or fatal errors. Rather than sending via smtp it writes a file into the - /// directory specified by . This allows services such - /// as the IIS SMTP agent to manage sending the messages. - /// - /// - /// - /// The configuration for this appender is identical to that of the SMTPAppender, - /// except that instead of specifying the SMTPAppender.SMTPHost you specify - /// . - /// - /// - /// The number of logging events delivered in this e-mail depend on - /// the value of option. The - /// keeps only the last - /// logging events in its - /// cyclic buffer. This keeps memory requirements at a reasonable level while - /// still delivering useful application context. - /// - /// - /// Niall Daley - /// Nicko Cadell - public class SmtpPickupDirAppender : BufferingAppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public SmtpPickupDirAppender() - { - m_fileExtension = string.Empty; // Default to empty string, not null - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets a semicolon-delimited list of recipient e-mail addresses. - /// - /// - /// A semicolon-delimited list of e-mail addresses. - /// - /// - /// - /// A semicolon-delimited list of e-mail addresses. - /// - /// - public string To - { - get { return m_to; } - set { m_to = value; } - } - - /// - /// Gets or sets the e-mail address of the sender. - /// - /// - /// The e-mail address of the sender. - /// - /// - /// - /// The e-mail address of the sender. - /// - /// - public string From - { - get { return m_from; } - set { m_from = value; } - } - - /// - /// Gets or sets the subject line of the e-mail message. - /// - /// - /// The subject line of the e-mail message. - /// - /// - /// - /// The subject line of the e-mail message. - /// - /// - public string Subject - { - get { return m_subject; } - set { m_subject = value; } - } - - /// - /// Gets or sets the path to write the messages to. - /// - /// - /// - /// Gets or sets the path to write the messages to. This should be the same - /// as that used by the agent sending the messages. - /// - /// - public string PickupDir - { - get { return m_pickupDir; } - set { m_pickupDir = value; } - } - - /// - /// Gets or sets the file extension for the generated files - /// - /// - /// The file extension for the generated files - /// - /// - /// - /// The file extension for the generated files - /// - /// - public string FileExtension - { - get { return m_fileExtension; } - set - { - m_fileExtension = value; - if (m_fileExtension == null) - { - m_fileExtension = string.Empty; - } - // Make sure any non empty extension starts with a dot + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// Send an email when a specific logging event occurs, typically on errors + /// or fatal errors. Rather than sending via smtp it writes a file into the + /// directory specified by . This allows services such + /// as the IIS SMTP agent to manage sending the messages. + /// + /// + /// + /// The configuration for this appender is identical to that of the SMTPAppender, + /// except that instead of specifying the SMTPAppender.SMTPHost you specify + /// . + /// + /// + /// The number of logging events delivered in this e-mail depend on + /// the value of option. The + /// keeps only the last + /// logging events in its + /// cyclic buffer. This keeps memory requirements at a reasonable level while + /// still delivering useful application context. + /// + /// + /// Niall Daley. + /// Nicko Cadell. + public class SmtpPickupDirAppender : BufferingAppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public SmtpPickupDirAppender() + { + this.m_fileExtension = string.Empty; // Default to empty string, not null + } + + /// + /// Gets or sets a semicolon-delimited list of recipient e-mail addresses. + /// + /// + /// A semicolon-delimited list of e-mail addresses. + /// + /// + /// + /// A semicolon-delimited list of e-mail addresses. + /// + /// + public string To + { + get { return this.m_to; } + set { this.m_to = value; } + } + + /// + /// Gets or sets the e-mail address of the sender. + /// + /// + /// The e-mail address of the sender. + /// + /// + /// + /// The e-mail address of the sender. + /// + /// + public string From + { + get { return this.m_from; } + set { this.m_from = value; } + } + + /// + /// Gets or sets the subject line of the e-mail message. + /// + /// + /// The subject line of the e-mail message. + /// + /// + /// + /// The subject line of the e-mail message. + /// + /// + public string Subject + { + get { return this.m_subject; } + set { this.m_subject = value; } + } + + /// + /// Gets or sets the path to write the messages to. + /// + /// + /// + /// Gets or sets the path to write the messages to. This should be the same + /// as that used by the agent sending the messages. + /// + /// + public string PickupDir + { + get { return this.m_pickupDir; } + set { this.m_pickupDir = value; } + } + + /// + /// Gets or sets the file extension for the generated files. + /// + /// + /// The file extension for the generated files. + /// + /// + /// + /// The file extension for the generated files. + /// + /// + public string FileExtension + { + get { return this.m_fileExtension; } + + set + { + this.m_fileExtension = value; + if (this.m_fileExtension == null) + { + this.m_fileExtension = string.Empty; + } + + // Make sure any non empty extension starts with a dot #if NET_2_0 || MONO_2_0 - if (!string.IsNullOrEmpty(m_fileExtension) && !m_fileExtension.StartsWith(".")) + if (!string.IsNullOrEmpty(this.m_fileExtension) && !this.m_fileExtension.StartsWith(".")) #else if (m_fileExtension != null && m_fileExtension.Length > 0 && !m_fileExtension.StartsWith(".")) #endif - { - m_fileExtension = "." + m_fileExtension; - } - } - } - - /// - /// Gets or sets the used to write to the pickup directory. - /// - /// - /// The used to write to the pickup directory. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return m_securityContext; } - set { m_securityContext = value; } - } - - #endregion Public Instance Properties - - #region Override implementation of BufferingAppenderSkeleton - - /// - /// Sends the contents of the cyclic buffer as an e-mail message. - /// - /// The logging events to send. - /// - /// - /// Sends the contents of the cyclic buffer as an e-mail message. - /// - /// - override protected void SendBuffer(LoggingEvent[] events) - { - // Note: this code already owns the monitor for this - // appender. This frees us from needing to synchronize again. - try - { - string filePath = null; - StreamWriter writer = null; - - // Impersonate to open the file - using(SecurityContext.Impersonate(this)) - { - filePath = Path.Combine(m_pickupDir, SystemInfo.NewGuid().ToString("N") + m_fileExtension); - writer = File.CreateText(filePath); - } - - if (writer == null) - { - ErrorHandler.Error("Failed to create output file for writing ["+filePath+"]", null, ErrorCode.FileOpenFailure); - } - else - { - using(writer) - { - writer.WriteLine("To: " + m_to); - writer.WriteLine("From: " + m_from); - writer.WriteLine("Subject: " + m_subject); - writer.WriteLine("Date: " + DateTime.UtcNow.ToString("r")); - writer.WriteLine(""); - - string t = Layout.Header; - if (t != null) - { - writer.Write(t); - } - - for(int i = 0; i < events.Length; i++) - { - // Render the event and append the text to the buffer - RenderLoggingEvent(writer, events[i]); - } - - t = Layout.Footer; - if (t != null) - { - writer.Write(t); - } - - writer.WriteLine(""); - writer.WriteLine("."); - } - } - } - catch(Exception e) - { - ErrorHandler.Error("Error occurred while sending e-mail notification.", e); - } - } - - #endregion Override implementation of BufferingAppenderSkeleton - - #region Override implementation of AppenderSkeleton - - /// - /// Activate the options on this appender. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { - base.ActivateOptions(); - - if (m_securityContext == null) - { - m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - using(SecurityContext.Impersonate(this)) - { - m_pickupDir = ConvertToFullPath(m_pickupDir.Trim()); - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion Override implementation of AppenderSkeleton - - #region Protected Static Methods - - /// - /// Convert a path into a fully qualified path. - /// - /// The path to convert. - /// The fully qualified path. - /// - /// - /// Converts the path specified to a fully - /// qualified path. If the path is relative it is - /// taken as relative from the application base - /// directory. - /// - /// - protected static string ConvertToFullPath(string path) - { - return SystemInfo.ConvertToFullPath(path); - } - - #endregion Protected Static Methods - - #region Private Instance Fields - - private string m_to; - private string m_from; - private string m_subject; - private string m_pickupDir; - private string m_fileExtension; - - /// - /// The security context to use for privileged calls - /// - private SecurityContext m_securityContext; - - #endregion Private Instance Fields - } + { + this.m_fileExtension = "." + this.m_fileExtension; + } + } + } + + /// + /// Gets or sets the used to write to the pickup directory. + /// + /// + /// The used to write to the pickup directory. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } + + /// + /// Sends the contents of the cyclic buffer as an e-mail message. + /// + /// The logging events to send. + /// + /// + /// Sends the contents of the cyclic buffer as an e-mail message. + /// + /// + protected override void SendBuffer(LoggingEvent[] events) + { + // Note: this code already owns the monitor for this + // appender. This frees us from needing to synchronize again. + try + { + string filePath = null; + StreamWriter writer = null; + + // Impersonate to open the file + using (this.SecurityContext.Impersonate(this)) + { + filePath = Path.Combine(this.m_pickupDir, SystemInfo.NewGuid().ToString("N") + this.m_fileExtension); + writer = File.CreateText(filePath); + } + + if (writer == null) + { + this.ErrorHandler.Error("Failed to create output file for writing [" + filePath + "]", null, ErrorCode.FileOpenFailure); + } + else + { + using (writer) + { + writer.WriteLine("To: " + this.m_to); + writer.WriteLine("From: " + this.m_from); + writer.WriteLine("Subject: " + this.m_subject); + writer.WriteLine("Date: " + DateTime.UtcNow.ToString("r")); + writer.WriteLine(string.Empty); + + string t = this.Layout.Header; + if (t != null) + { + writer.Write(t); + } + + for (int i = 0; i < events.Length; i++) + { + // Render the event and append the text to the buffer + this.RenderLoggingEvent(writer, events[i]); + } + + t = this.Layout.Footer; + if (t != null) + { + writer.Write(t); + } + + writer.WriteLine(string.Empty); + writer.WriteLine("."); + } + } + } + catch (Exception e) + { + this.ErrorHandler.Error("Error occurred while sending e-mail notification.", e); + } + } + + /// + /// Activate the options on this appender. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.m_securityContext == null) + { + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + using (this.SecurityContext.Impersonate(this)) + { + this.m_pickupDir = ConvertToFullPath(this.m_pickupDir.Trim()); + } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Convert a path into a fully qualified path. + /// + /// The path to convert. + /// The fully qualified path. + /// + /// + /// Converts the path specified to a fully + /// qualified path. If the path is relative it is + /// taken as relative from the application base + /// directory. + /// + /// + protected static string ConvertToFullPath(string path) + { + return SystemInfo.ConvertToFullPath(path); + } + + private string m_to; + private string m_from; + private string m_subject; + private string m_pickupDir; + private string m_fileExtension; + + /// + /// The security context to use for privileged calls. + /// + private SecurityContext m_securityContext; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs index 84c2aa27359..5a857227e88 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs @@ -1,540 +1,525 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Globalization; -using System.Net; -using System.Net.Sockets; -using System.Text; -using System.IO; -using System.Threading; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + + #if NETSTANDARD1_3 using System.Threading.Tasks; #endif -using log4net.Layout; using log4net.Core; +using log4net.Layout; using log4net.Util; -namespace log4net.Appender +namespace log4net.Appender { - /// - /// Appender that allows clients to connect via Telnet to receive log messages - /// - /// - /// - /// The TelnetAppender accepts socket connections and streams logging messages - /// back to the client. - /// The output is provided in a telnet-friendly way so that a log can be monitored - /// over a TCP/IP socket. - /// This allows simple remote monitoring of application logging. - /// - /// - /// The default is 23 (the telnet port). - /// - /// - /// Keith Long - /// Nicko Cadell - public class TelnetAppender : AppenderSkeleton - { - private SocketHandler m_handler; - private int m_listeningPort = 23; - - #region Constructor - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public TelnetAppender() - { - } - - #endregion - - #region Private Static Fields - - /// - /// The fully qualified type of the TelnetAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(TelnetAppender); - - #endregion Private Static Fields - - /// - /// Gets or sets the TCP port number on which this will listen for connections. - /// - /// - /// An integer value in the range to - /// indicating the TCP port number on which this will listen for connections. - /// - /// - /// - /// The default value is 23 (the telnet port). - /// - /// - /// The value specified is less than - /// or greater than . - public int Port - { - get - { - return m_listeningPort; - } - set - { - if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, - "The value specified for Port is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - m_listeningPort = value; - } - } - } - - #region Override implementation of AppenderSkeleton - - /// - /// Overrides the parent method to close the socket handler - /// - /// - /// - /// Closes all the outstanding connections. - /// - /// - protected override void OnClose() - { - base.OnClose(); - - if (m_handler != null) - { - m_handler.Dispose(); - m_handler = null; - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } - } - - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Create the socket handler and wait for connections - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - try - { - LogLog.Debug(declaringType, "Creating SocketHandler to listen on port ["+m_listeningPort+"]"); - m_handler = new SocketHandler(m_listeningPort); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to create SocketHandler", ex); - throw; - } - } - - /// - /// Writes the logging event to each connected client. - /// - /// The event to log. - /// - /// - /// Writes the logging event to each connected client. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - if (m_handler != null && m_handler.HasConnections) - { - m_handler.Send(RenderLoggingEvent(loggingEvent)); - } - } - - #endregion - - #region SocketHandler helper class - - /// - /// Helper class to manage connected clients - /// - /// - /// - /// The SocketHandler class is used to accept connections from - /// clients. It is threaded so that clients can connect/disconnect - /// asynchronously. - /// - /// - protected class SocketHandler : IDisposable - { - private const int MAX_CONNECTIONS = 20; - - private Socket m_serverSocket; - private ArrayList m_clients = new ArrayList(); - - /// - /// Class that represents a client connected to this handler - /// - /// - /// - /// Class that represents a client connected to this handler - /// - /// - protected class SocketClient : IDisposable - { - private Socket m_socket; - private StreamWriter m_writer; - - /// - /// Create this for the specified - /// - /// the client's socket - /// - /// - /// Opens a stream writer on the socket. - /// - /// - public SocketClient(Socket socket) - { - m_socket = socket; - - try - { - m_writer = new StreamWriter(new NetworkStream(socket)); - } - catch - { - Dispose(); - throw; - } - } - - /// - /// Write a string to the client - /// - /// string to send - /// - /// - /// Write a string to the client - /// - /// - public void Send(String message) - { - m_writer.Write(message); - m_writer.Flush(); - } - - #region IDisposable Members - - /// - /// Cleanup the clients connection - /// - /// - /// - /// Close the socket connection. - /// - /// - public void Dispose() - { - try - { - if (m_writer != null) - { - m_writer.Close(); - m_writer = null; - } - } - catch { } - - if (m_socket != null) - { - try - { - m_socket.Shutdown(SocketShutdown.Both); - } - catch { } - - try - { - m_socket.Close(); - } - catch { } - - m_socket = null; - } - } - - #endregion - } - - /// - /// Opens a new server port on - /// - /// the local port to listen on for connections - /// - /// - /// Creates a socket handler on the specified local server port. - /// - /// - public SocketHandler(int port) - { - m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - - m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, port)); - m_serverSocket.Listen(5); - AcceptConnection(); - } - - private void AcceptConnection() - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Globalization; + using System.IO; + using System.Net; + using System.Net.Sockets; + using System.Text; + using System.Threading; + + /// + /// Appender that allows clients to connect via Telnet to receive log messages. + /// + /// + /// + /// The TelnetAppender accepts socket connections and streams logging messages + /// back to the client. + /// The output is provided in a telnet-friendly way so that a log can be monitored + /// over a TCP/IP socket. + /// This allows simple remote monitoring of application logging. + /// + /// + /// The default is 23 (the telnet port). + /// + /// + /// Keith Long. + /// Nicko Cadell. + public class TelnetAppender : AppenderSkeleton + { + private SocketHandler m_handler; + private int m_listeningPort = 23; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public TelnetAppender() + { + } + + /// + /// The fully qualified type of the TelnetAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(TelnetAppender); + + /// + /// Gets or sets the TCP port number on which this will listen for connections. + /// + /// + /// An integer value in the range to + /// indicating the TCP port number on which this will listen for connections. + /// + /// + /// + /// The default value is 23 (the telnet port). + /// + /// + /// The value specified is less than + /// or greater than . + public int Port + { + get + { + return this.m_listeningPort; + } + + set + { + if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, + "The value specified for Port is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.m_listeningPort = value; + } + } + } + + /// + /// Overrides the parent method to close the socket handler. + /// + /// + /// + /// Closes all the outstanding connections. + /// + /// + protected override void OnClose() + { + base.OnClose(); + + if (this.m_handler != null) + { + this.m_handler.Dispose(); + this.m_handler = null; + } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Create the socket handler and wait for connections. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + try + { + LogLog.Debug(declaringType, "Creating SocketHandler to listen on port [" + this.m_listeningPort + "]"); + this.m_handler = new SocketHandler(this.m_listeningPort); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to create SocketHandler", ex); + throw; + } + } + + /// + /// Writes the logging event to each connected client. + /// + /// The event to log. + /// + /// + /// Writes the logging event to each connected client. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + if (this.m_handler != null && this.m_handler.HasConnections) + { + this.m_handler.Send(this.RenderLoggingEvent(loggingEvent)); + } + } + + /// + /// Helper class to manage connected clients. + /// + /// + /// + /// The SocketHandler class is used to accept connections from + /// clients. It is threaded so that clients can connect/disconnect + /// asynchronously. + /// + /// + protected class SocketHandler : IDisposable + { + private const int MAX_CONNECTIONS = 20; + + private Socket m_serverSocket; + private ArrayList m_clients = new ArrayList(); + + /// + /// Class that represents a client connected to this handler. + /// + /// + /// + /// Class that represents a client connected to this handler. + /// + /// + protected class SocketClient : IDisposable + { + private Socket m_socket; + private StreamWriter m_writer; + + /// + /// Initializes a new instance of the class. + /// Create this for the specified . + /// + /// the client's socket. + /// + /// + /// Opens a stream writer on the socket. + /// + /// + public SocketClient(Socket socket) + { + this.m_socket = socket; + + try + { + this.m_writer = new StreamWriter(new NetworkStream(socket)); + } + catch + { + this.Dispose(); + throw; + } + } + + /// + /// Write a string to the client. + /// + /// string to send. + /// + /// + /// Write a string to the client. + /// + /// + public void Send(string message) + { + this.m_writer.Write(message); + this.m_writer.Flush(); + } + + /// + /// Cleanup the clients connection. + /// + /// + /// + /// Close the socket connection. + /// + /// + public void Dispose() + { + try + { + if (this.m_writer != null) + { + this.m_writer.Close(); + this.m_writer = null; + } + } + catch + { + } + + if (this.m_socket != null) + { + try + { + this.m_socket.Shutdown(SocketShutdown.Both); + } + catch + { + } + + try + { + this.m_socket.Close(); + } + catch + { + } + + this.m_socket = null; + } + } + } + + /// + /// Initializes a new instance of the class. + /// Opens a new server port on . + /// + /// the local port to listen on for connections. + /// + /// + /// Creates a socket handler on the specified local server port. + /// + /// + public SocketHandler(int port) + { + this.m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + + this.m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, port)); + this.m_serverSocket.Listen(5); + this.AcceptConnection(); + } + + private void AcceptConnection() + { #if NETSTANDARD1_3 m_serverSocket.AcceptAsync().ContinueWith(OnConnect, TaskScheduler.Default); #else - m_serverSocket.BeginAccept(new AsyncCallback(OnConnect), null); + this.m_serverSocket.BeginAccept(new AsyncCallback(this.OnConnect), null); #endif - } - - /// - /// Sends a string message to each of the connected clients - /// - /// the text to send - /// - /// - /// Sends a string message to each of the connected clients - /// - /// - public void Send(String message) - { - ArrayList localClients = m_clients; - - foreach (SocketClient client in localClients) - { - try - { - client.Send(message); - } - catch (Exception) - { - // The client has closed the connection, remove it from our list - client.Dispose(); - RemoveClient(client); - } - } - } - - /// - /// Add a client to the internal clients list - /// - /// client to add - private void AddClient(SocketClient client) - { - lock(this) - { - ArrayList clientsCopy = (ArrayList)m_clients.Clone(); - clientsCopy.Add(client); - m_clients = clientsCopy; - } - } - - /// - /// Remove a client from the internal clients list - /// - /// client to remove - private void RemoveClient(SocketClient client) - { - lock(this) - { - ArrayList clientsCopy = (ArrayList)m_clients.Clone(); - clientsCopy.Remove(client); - m_clients = clientsCopy; - } - } - - /// - /// Test if this handler has active connections - /// - /// - /// true if this handler has active connections - /// - /// - /// - /// This property will be true while this handler has - /// active connections, that is at least one connection that - /// the handler will attempt to send a message to. - /// - /// - public bool HasConnections - { - get - { - ArrayList localClients = m_clients; - - return (localClients != null && localClients.Count > 0); - } - } - - + } + + /// + /// Sends a string message to each of the connected clients. + /// + /// the text to send. + /// + /// + /// Sends a string message to each of the connected clients. + /// + /// + public void Send(string message) + { + ArrayList localClients = this.m_clients; + + foreach (SocketClient client in localClients) + { + try + { + client.Send(message); + } + catch (Exception) + { + // The client has closed the connection, remove it from our list + client.Dispose(); + this.RemoveClient(client); + } + } + } + + /// + /// Add a client to the internal clients list. + /// + /// client to add. + private void AddClient(SocketClient client) + { + lock (this) + { + ArrayList clientsCopy = (ArrayList)this.m_clients.Clone(); + clientsCopy.Add(client); + this.m_clients = clientsCopy; + } + } + + /// + /// Remove a client from the internal clients list. + /// + /// client to remove. + private void RemoveClient(SocketClient client) + { + lock (this) + { + ArrayList clientsCopy = (ArrayList)this.m_clients.Clone(); + clientsCopy.Remove(client); + this.m_clients = clientsCopy; + } + } + + /// + /// Gets a value indicating whether test if this handler has active connections. + /// + /// + /// true if this handler has active connections. + /// + /// + /// + /// This property will be true while this handler has + /// active connections, that is at least one connection that + /// the handler will attempt to send a message to. + /// + /// + public bool HasConnections + { + get + { + ArrayList localClients = this.m_clients; + + return localClients != null && localClients.Count > 0; + } + } + #if NETSTANDARD1_3 private void OnConnect(Task acceptTask) #else - /// - /// Callback used to accept a connection on the server socket - /// - /// The result of the asynchronous operation - /// - /// - /// On connection adds to the list of connections - /// if there are two many open connections you will be disconnected - /// - /// - private void OnConnect(IAsyncResult asyncResult) + /// + /// Callback used to accept a connection on the server socket. + /// + /// The result of the asynchronous operation. + /// + /// + /// On connection adds to the list of connections + /// if there are two many open connections you will be disconnected. + /// + /// + private void OnConnect(IAsyncResult asyncResult) #endif - { - try - { + { + try + { #if NETSTANDARD1_3 Socket socket = acceptTask.GetAwaiter().GetResult(); #else - // Block until a client connects - Socket socket = m_serverSocket.EndAccept(asyncResult); + // Block until a client connects + Socket socket = this.m_serverSocket.EndAccept(asyncResult); #endif - LogLog.Debug(declaringType, "Accepting connection from ["+socket.RemoteEndPoint.ToString()+"]"); - SocketClient client = new SocketClient(socket); - - int currentActiveConnectionsCount = m_clients.Count; - if (currentActiveConnectionsCount < MAX_CONNECTIONS) - { - try - { - client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n"); - AddClient(client); - } - catch - { - client.Dispose(); - } - } - else - { - client.Send("Sorry - Too many connections.\r\n"); - client.Dispose(); - } - } - catch - { - } - finally - { - if (m_serverSocket != null) - { - AcceptConnection(); - } - } - } - - #region IDisposable Members - - /// - /// Close all network connections - /// - /// - /// - /// Make sure we close all network connections - /// - /// - public void Dispose() - { - ArrayList localClients = m_clients; - - foreach (SocketClient client in localClients) - { - client.Dispose(); - } - m_clients.Clear(); - - Socket localSocket = m_serverSocket; - m_serverSocket = null; - try - { - localSocket.Shutdown(SocketShutdown.Both); - } - catch - { - } - - try - { - localSocket.Close(); - } - catch - { - } - } - - #endregion - } - - #endregion - } + LogLog.Debug(declaringType, "Accepting connection from [" + socket.RemoteEndPoint.ToString() + "]"); + SocketClient client = new SocketClient(socket); + + int currentActiveConnectionsCount = this.m_clients.Count; + if (currentActiveConnectionsCount < MAX_CONNECTIONS) + { + try + { + client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n"); + this.AddClient(client); + } + catch + { + client.Dispose(); + } + } + else + { + client.Send("Sorry - Too many connections.\r\n"); + client.Dispose(); + } + } + catch + { + } + finally + { + if (this.m_serverSocket != null) + { + this.AcceptConnection(); + } + } + } + + /// + /// Close all network connections. + /// + /// + /// + /// Make sure we close all network connections. + /// + /// + public void Dispose() + { + ArrayList localClients = this.m_clients; + + foreach (SocketClient client in localClients) + { + client.Dispose(); + } + + this.m_clients.Clear(); + + Socket localSocket = this.m_serverSocket; + this.m_serverSocket = null; + try + { + localSocket.Shutdown(SocketShutdown.Both); + } + catch + { + } + + try + { + localSocket.Close(); + } + catch + { + } + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs index ea1f40d1fff..d3618911844 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs @@ -1,508 +1,489 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net.Util; -using log4net.Layout; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Appender { - /// - /// Sends logging events to a . - /// - /// - /// - /// An Appender that writes to a . - /// - /// - /// This appender may be used stand alone if initialized with an appropriate - /// writer, however it is typically used as a base class for an appender that - /// can open a to write to. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Douglas de la Torre + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// Sends logging events to a . + /// + /// + /// + /// An Appender that writes to a . + /// + /// + /// This appender may be used stand alone if initialized with an appropriate + /// writer, however it is typically used as a base class for an appender that + /// can open a to write to. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Douglas de la Torre. public class TextWriterAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public TextWriterAppender() - { - } - - /// - /// Initializes a new instance of the class and - /// sets the output destination to a new initialized - /// with the specified . - /// - /// The layout to use with this appender. - /// The to output to. - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout & Writer properties. Scheduled removal in v10.0.0.")] - public TextWriterAppender(ILayout layout, Stream os) : this(layout, new StreamWriter(os)) - { - } - - /// - /// Initializes a new instance of the class and sets - /// the output destination to the specified . - /// - /// The layout to use with this appender - /// The to output to - /// - /// The must have been previously opened. - /// - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout & Writer properties. Scheduled removal in v10.0.0.")] - public TextWriterAppender(ILayout layout, TextWriter writer) - { - Layout = layout; - Writer = writer; - } - - #endregion - - #region Public Instance Properties - - /// - /// Gets or set whether the appender will flush at the end - /// of each append operation. - /// - /// - /// - /// The default behavior is to flush at the end of each - /// append operation. - /// - /// - /// If this option is set to false, then the underlying - /// stream can defer persisting the logging event to a later - /// time. - /// - /// - /// - /// Avoiding the flush operation at the end of each append results in - /// a performance gain of 10 to 20 percent. However, there is safety - /// trade-off involved in skipping flushing. Indeed, when flushing is - /// skipped, then it is likely that the last few log events will not - /// be recorded on disk when the application exits. This is a high - /// price to pay even for a 20% performance gain. - /// - public bool ImmediateFlush - { - get { return m_immediateFlush; } - set { m_immediateFlush = value; } - } - - /// - /// Sets the where the log output will go. - /// - /// - /// - /// The specified must be open and writable. - /// - /// - /// The will be closed when the appender - /// instance is closed. - /// - /// - /// Note: Logging to an unopened will fail. - /// - /// - virtual public TextWriter Writer - { - get { return m_qtw; } - set - { - lock(this) - { - Reset(); - if (value != null) - { - m_qtw = new QuietTextWriter(value, ErrorHandler); - WriteHeader(); - } - } - } - } - - #endregion Public Instance Properties - - #region Override implementation of AppenderSkeleton - - /// - /// This method determines if there is a sense in attempting to append. - /// - /// - /// - /// This method checks if an output target has been set and if a - /// layout has been set. - /// - /// - /// false if any of the preconditions fail. - override protected bool PreAppendCheck() - { - if (!base.PreAppendCheck()) - { - return false; - } - - if (m_qtw == null) - { - // Allow subclass to lazily create the writer - PrepareWriter(); - - if (m_qtw == null) - { - ErrorHandler.Error("No output stream or file set for the appender named ["+ Name +"]."); - return false; - } - } - if (m_qtw.Closed) - { - ErrorHandler.Error("Output stream for appender named ["+ Name +"] has been closed."); - return false; - } - - return true; - } - - /// - /// This method is called by the - /// method. - /// - /// The event to log. - /// - /// - /// Writes a log statement to the output stream if the output stream exists - /// and is writable. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - RenderLoggingEvent(m_qtw, loggingEvent); - - if (m_immediateFlush) - { - m_qtw.Flush(); - } - } - - /// - /// This method is called by the - /// method. - /// - /// The array of events to log. - /// - /// - /// This method writes all the bulk logged events to the output writer - /// before flushing the stream. - /// - /// - override protected void Append(LoggingEvent[] loggingEvents) - { - foreach(LoggingEvent loggingEvent in loggingEvents) - { - RenderLoggingEvent(m_qtw, loggingEvent); - } - - if (m_immediateFlush) - { - m_qtw.Flush(); - } - } - - /// - /// Close this appender instance. The underlying stream or writer is also closed. - /// - /// - /// Closed appenders cannot be reused. - /// - override protected void OnClose() - { - lock(this) - { - Reset(); - } - } - - /// - /// Gets or set the and the underlying - /// , if any, for this appender. - /// - /// - /// The for this appender. - /// - override public IErrorHandler ErrorHandler - { - get { return base.ErrorHandler; } - set - { - lock(this) - { - if (value == null) - { - LogLog.Warn(declaringType, "TextWriterAppender: You have tried to set a null error-handler."); - } - else - { - base.ErrorHandler = value; - if (m_qtw != null) - { - m_qtw.ErrorHandler = value; - } - } - } - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion Override implementation of AppenderSkeleton - - #region Protected Instance Methods + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public TextWriterAppender() + { + } - /// - /// Writes the footer and closes the underlying . - /// - /// - /// - /// Writes the footer and closes the underlying . - /// - /// - virtual protected void WriteFooterAndCloseWriter() - { - WriteFooter(); - CloseWriter(); - } + /// + /// Initializes a new instance of the class and + /// sets the output destination to a new initialized + /// with the specified . + /// + /// The layout to use with this appender. + /// The to output to. + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout & Writer properties. Scheduled removal in v10.0.0.")] + public TextWriterAppender(ILayout layout, Stream os) + : this(layout, new StreamWriter(os)) + { + } - /// - /// Closes the underlying . - /// - /// - /// - /// Closes the underlying . - /// - /// - virtual protected void CloseWriter() - { - if (m_qtw != null) - { - try - { - m_qtw.Close(); - } - catch(Exception e) - { - ErrorHandler.Error("Could not close writer ["+m_qtw+"]", e); - // do need to invoke an error handler - // at this late stage - } - } - } + /// + /// Initializes a new instance of the class and sets + /// the output destination to the specified . + /// + /// The layout to use with this appender. + /// The to output to. + /// + /// The must have been previously opened. + /// + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout & Writer properties. Scheduled removal in v10.0.0.")] + public TextWriterAppender(ILayout layout, TextWriter writer) + { + this.Layout = layout; + this.Writer = writer; + } + + /// + /// Gets or sets a value indicating whether gets or set whether the appender will flush at the end + /// of each append operation. + /// + /// + /// + /// The default behavior is to flush at the end of each + /// append operation. + /// + /// + /// If this option is set to false, then the underlying + /// stream can defer persisting the logging event to a later + /// time. + /// + /// + /// + /// Avoiding the flush operation at the end of each append results in + /// a performance gain of 10 to 20 percent. However, there is safety + /// trade-off involved in skipping flushing. Indeed, when flushing is + /// skipped, then it is likely that the last few log events will not + /// be recorded on disk when the application exits. This is a high + /// price to pay even for a 20% performance gain. + /// + public bool ImmediateFlush + { + get { return this.m_immediateFlush; } + set { this.m_immediateFlush = value; } + } - /// - /// Clears internal references to the underlying - /// and other variables. - /// - /// - /// - /// Subclasses can override this method for an alternate closing behavior. - /// - /// - virtual protected void Reset() - { - WriteFooterAndCloseWriter(); - m_qtw = null; - } + /// + /// Gets or sets the where the log output will go. + /// + /// + /// + /// The specified must be open and writable. + /// + /// + /// The will be closed when the appender + /// instance is closed. + /// + /// + /// Note: Logging to an unopened will fail. + /// + /// + public virtual TextWriter Writer + { + get { return this.m_qtw; } + + set + { + lock (this) + { + this.Reset(); + if (value != null) + { + this.m_qtw = new QuietTextWriter(value, this.ErrorHandler); + this.WriteHeader(); + } + } + } + } + + /// + /// This method determines if there is a sense in attempting to append. + /// + /// + /// + /// This method checks if an output target has been set and if a + /// layout has been set. + /// + /// + /// false if any of the preconditions fail. + protected override bool PreAppendCheck() + { + if (!base.PreAppendCheck()) + { + return false; + } - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - virtual protected void WriteFooter() - { - if (Layout != null && m_qtw != null && !m_qtw.Closed) - { - string f = Layout.Footer; - if (f != null) - { - m_qtw.Write(f); - } - } - } + if (this.m_qtw == null) + { + // Allow subclass to lazily create the writer + this.PrepareWriter(); - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - virtual protected void WriteHeader() - { - if (Layout != null && m_qtw != null && !m_qtw.Closed) - { - string h = Layout.Header; - if (h != null) - { - m_qtw.Write(h); - } - } - } + if (this.m_qtw == null) + { + this.ErrorHandler.Error("No output stream or file set for the appender named [" + this.Name + "]."); + return false; + } + } + + if (this.m_qtw.Closed) + { + this.ErrorHandler.Error("Output stream for appender named [" + this.Name + "] has been closed."); + return false; + } - /// - /// Called to allow a subclass to lazily initialize the writer - /// - /// - /// - /// This method is called when an event is logged and the or - /// have not been set. This allows a subclass to - /// attempt to initialize the writer multiple times. - /// - /// - virtual protected void PrepareWriter() - { - } + return true; + } - /// - /// Gets or sets the where logging events - /// will be written to. - /// - /// - /// The where logging events are written. - /// - /// - /// - /// This is the where logging events - /// will be written to. - /// - /// - protected QuietTextWriter QuietWriter - { - get { return m_qtw; } - set { m_qtw = value; } + /// + /// This method is called by the + /// method. + /// + /// The event to log. + /// + /// + /// Writes a log statement to the output stream if the output stream exists + /// and is writable. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + this.RenderLoggingEvent(this.m_qtw, loggingEvent); + + if (this.m_immediateFlush) + { + this.m_qtw.Flush(); + } } - #endregion Protected Instance Methods + /// + /// This method is called by the + /// method. + /// + /// The array of events to log. + /// + /// + /// This method writes all the bulk logged events to the output writer + /// before flushing the stream. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) + { + foreach (LoggingEvent loggingEvent in loggingEvents) + { + this.RenderLoggingEvent(this.m_qtw, loggingEvent); + } - #region Private Instance Fields + if (this.m_immediateFlush) + { + this.m_qtw.Flush(); + } + } /// - /// This is the where logging events - /// will be written to. - /// - private QuietTextWriter m_qtw; - - /// - /// Immediate flush means that the underlying - /// or output stream will be flushed at the end of each append operation. - /// - /// - /// - /// Immediate flush is slower but ensures that each append request is - /// actually written. If is set to - /// false, then there is a good chance that the last few - /// logging events are not actually persisted if and when the application - /// crashes. - /// - /// - /// The default value is true. - /// - /// - private bool m_immediateFlush = true; + /// Close this appender instance. The underlying stream or writer is also closed. + /// + /// + /// Closed appenders cannot be reused. + /// + protected override void OnClose() + { + lock (this) + { + this.Reset(); + } + } - #endregion Private Instance Fields + /// + /// Gets or sets or set the and the underlying + /// , if any, for this appender. + /// + /// + /// The for this appender. + /// + public override IErrorHandler ErrorHandler + { + get { return base.ErrorHandler; } + + set + { + lock (this) + { + if (value == null) + { + LogLog.Warn(declaringType, "TextWriterAppender: You have tried to set a null error-handler."); + } + else + { + base.ErrorHandler = value; + if (this.m_qtw != null) + { + this.m_qtw.ErrorHandler = value; + } + } + } + } + } - #region Private Static Fields + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Writes the footer and closes the underlying . + /// + /// + /// + /// Writes the footer and closes the underlying . + /// + /// + protected virtual void WriteFooterAndCloseWriter() + { + this.WriteFooter(); + this.CloseWriter(); + } - /// - /// The fully qualified type of the TextWriterAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(TextWriterAppender); + /// + /// Closes the underlying . + /// + /// + /// + /// Closes the underlying . + /// + /// + protected virtual void CloseWriter() + { + if (this.m_qtw != null) + { + try + { + this.m_qtw.Close(); + } + catch (Exception e) + { + this.ErrorHandler.Error("Could not close writer [" + this.m_qtw + "]", e); + + // do need to invoke an error handler + // at this late stage + } + } + } - #endregion Private Static Fields + /// + /// Clears internal references to the underlying + /// and other variables. + /// + /// + /// + /// Subclasses can override this method for an alternate closing behavior. + /// + /// + protected virtual void Reset() + { + this.WriteFooterAndCloseWriter(); + this.m_qtw = null; + } - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + protected virtual void WriteFooter() + { + if (this.Layout != null && this.m_qtw != null && !this.m_qtw.Closed) { - // Nothing to do if ImmediateFlush is true - if (m_immediateFlush) return true; - - // lock(this) will block any Appends while the buffer is flushed. - lock (this) + string f = this.Layout.Footer; + if (f != null) { - m_qtw.Flush(); + this.m_qtw.Write(f); } + } + } - return true; + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + protected virtual void WriteHeader() + { + if (this.Layout != null && this.m_qtw != null && !this.m_qtw.Closed) + { + string h = this.Layout.Header; + if (h != null) + { + this.m_qtw.Write(h); + } } - } + } + + /// + /// Called to allow a subclass to lazily initialize the writer. + /// + /// + /// + /// This method is called when an event is logged and the or + /// have not been set. This allows a subclass to + /// attempt to initialize the writer multiple times. + /// + /// + protected virtual void PrepareWriter() + { + } + + /// + /// Gets or sets the where logging events + /// will be written to. + /// + /// + /// The where logging events are written. + /// + /// + /// + /// This is the where logging events + /// will be written to. + /// + /// + protected QuietTextWriter QuietWriter + { + get { return this.m_qtw; } + set { this.m_qtw = value; } + } + + /// + /// This is the where logging events + /// will be written to. + /// + private QuietTextWriter m_qtw; + + /// + /// Immediate flush means that the underlying + /// or output stream will be flushed at the end of each append operation. + /// + /// + /// + /// Immediate flush is slower but ensures that each append request is + /// actually written. If is set to + /// false, then there is a good chance that the last few + /// logging events are not actually persisted if and when the application + /// crashes. + /// + /// + /// The default value is true. + /// + /// + private bool m_immediateFlush = true; + + /// + /// The fully qualified type of the TextWriterAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(TextWriterAppender); + + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) + { + // Nothing to do if ImmediateFlush is true + if (this.m_immediateFlush) + { + return true; + } + + // lock(this) will block any Appends while the buffer is flushed. + lock (this) + { + this.m_qtw.Flush(); + } + + return true; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs index c859ca6f83b..501dd1bb088 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,198 +18,180 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - #define TRACE -using log4net.Layout; -using log4net.Core; - namespace log4net.Appender { - /// - /// Appends log events to the system. - /// - /// - /// - /// The application configuration file can be used to control what listeners - /// are actually used. See the MSDN documentation for the - /// class for details on configuring the - /// trace system. - /// - /// - /// Events are written using the System.Diagnostics.Trace.Write(string,string) - /// method. The event's logger name is the default value for the category parameter - /// of the Write method. - /// - /// - /// Compact Framework
- /// The Compact Framework does not support the - /// class for any operation except Assert. When using the Compact Framework this - /// appender will write to the system rather than - /// the Trace system. This appender will therefore behave like the . - ///
- ///
- /// Douglas de la Torre - /// Nicko Cadell - /// Gert Driesen - /// Ron Grabowski - public class TraceAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the . - /// - /// - /// - /// Default constructor. - /// - /// - public TraceAppender() - { - } - - /// - /// Initializes a new instance of the - /// with a specified layout. - /// - /// The layout to use with this appender. - /// - /// - /// Obsolete constructor. - /// - /// - [System.Obsolete("Instead use the default constructor and set the Layout property")] - public TraceAppender(ILayout layout) - { - Layout = layout; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets a value that indicates whether the appender will - /// flush at the end of each write. - /// - /// - /// The default behavior is to flush at the end of each - /// write. If the option is set tofalse, then the underlying - /// stream can defer writing to physical medium to a later time. - /// - /// - /// Avoiding the flush operation at the end of each append results - /// in a performance gain of 10 to 20 percent. However, there is safety - /// trade-off involved in skipping flushing. Indeed, when flushing is - /// skipped, then it is likely that the last few log events will not - /// be recorded on disk when the application exits. This is a high - /// price to pay even for a 20% performance gain. - /// - /// - public bool ImmediateFlush - { - get { return m_immediateFlush; } - set { m_immediateFlush = value; } - } + using log4net.Core; + using log4net.Layout; + + /// + /// Appends log events to the system. + /// + /// + /// + /// The application configuration file can be used to control what listeners + /// are actually used. See the MSDN documentation for the + /// class for details on configuring the + /// trace system. + /// + /// + /// Events are written using the System.Diagnostics.Trace.Write(string,string) + /// method. The event's logger name is the default value for the category parameter + /// of the Write method. + /// + /// + /// Compact Framework
+ /// The Compact Framework does not support the + /// class for any operation except Assert. When using the Compact Framework this + /// appender will write to the system rather than + /// the Trace system. This appender will therefore behave like the . + ///
+ ///
+ /// Douglas de la Torre. + /// Nicko Cadell. + /// Gert Driesen. + /// Ron Grabowski. + public class TraceAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the . + /// + /// + /// + /// Default constructor. + /// + /// + public TraceAppender() + { + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the + /// with a specified layout. + /// + /// The layout to use with this appender. + /// + /// + /// Obsolete constructor. + /// + /// + [System.Obsolete("Instead use the default constructor and set the Layout property")] + public TraceAppender(ILayout layout) + { + this.Layout = layout; + } + + /// + /// Gets or sets a value indicating whether gets or sets a value that indicates whether the appender will + /// flush at the end of each write. + /// + /// + /// The default behavior is to flush at the end of each + /// write. If the option is set tofalse, then the underlying + /// stream can defer writing to physical medium to a later time. + /// + /// + /// Avoiding the flush operation at the end of each append results + /// in a performance gain of 10 to 20 percent. However, there is safety + /// trade-off involved in skipping flushing. Indeed, when flushing is + /// skipped, then it is likely that the last few log events will not + /// be recorded on disk when the application exits. This is a high + /// price to pay even for a 20% performance gain. + /// + /// + public bool ImmediateFlush + { + get { return this.m_immediateFlush; } + set { this.m_immediateFlush = value; } + } /// - /// The category parameter sent to the Trace method. + /// Gets or sets the category parameter sent to the Trace method. /// /// /// - /// Defaults to %logger which will use the logger name of the current + /// Defaults to %logger which will use the logger name of the current /// as the category parameter. /// /// - /// + /// /// - public PatternLayout Category - { - get { return m_category; } - set { m_category = value; } - } - - #endregion Public Instance Properties - - #region Override implementation of AppenderSkeleton - - /// - /// Writes the logging event to the system. - /// - /// The event to log. - /// - /// - /// Writes the logging event to the system. - /// - /// - override protected void Append(LoggingEvent loggingEvent) - { - // - // Write the string to the Trace system - // + public PatternLayout Category + { + get { return this.m_category; } + set { this.m_category = value; } + } + + /// + /// Writes the logging event to the system. + /// + /// The event to log. + /// + /// + /// Writes the logging event to the system. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // Write the string to the Trace system + // #if NETCF System.Diagnostics.Debug.Write(RenderLoggingEvent(loggingEvent), m_category.Format(loggingEvent)); #else - System.Diagnostics.Trace.Write(RenderLoggingEvent(loggingEvent), m_category.Format(loggingEvent)); + System.Diagnostics.Trace.Write(this.RenderLoggingEvent(loggingEvent), this.m_category.Format(loggingEvent)); #endif - - // - // Flush the Trace system if needed - // - if (m_immediateFlush) - { + + // + // Flush the Trace system if needed + if (this.m_immediateFlush) + { #if NETCF System.Diagnostics.Debug.Flush(); #else - System.Diagnostics.Trace.Flush(); + System.Diagnostics.Trace.Flush(); #endif - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - #endregion Override implementation of AppenderSkeleton - - #region Private Instance Fields - - /// - /// Immediate flush means that the underlying writer or output stream - /// will be flushed at the end of each append operation. - /// - /// - /// - /// Immediate flush is slower but ensures that each append request is - /// actually written. If is set to - /// false, then there is a good chance that the last few - /// logs events are not actually written to persistent media if and - /// when the application crashes. - /// - /// - /// The default value is true. - /// - private bool m_immediateFlush = true; + } + } /// - /// Defaults to %logger + /// Gets a value indicating whether this appender requires a to be set. /// - private PatternLayout m_category = new PatternLayout("%logger"); - - #endregion Private Instance Fields + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Immediate flush means that the underlying writer or output stream + /// will be flushed at the end of each append operation. + /// + /// + /// + /// Immediate flush is slower but ensures that each append request is + /// actually written. If is set to + /// false, then there is a good chance that the last few + /// logs events are not actually written to persistent media if and + /// when the application crashes. + /// + /// + /// The default value is true. + /// + private bool m_immediateFlush = true; + /// + /// Defaults to %logger. + /// + private PatternLayout m_category = new PatternLayout("%logger"); + /// /// Flushes any buffered log data. /// @@ -219,9 +200,12 @@ override protected bool RequiresLayout public override bool Flush(int millisecondsTimeout) { // Nothing to do if ImmediateFlush is true - if (m_immediateFlush) return true; - - // System.Diagnostics.Trace and System.Diagnostics.Debug are thread-safe, so no need for lock(this). + if (this.m_immediateFlush) + { + return true; + } + + // System.Diagnostics.Trace and System.Diagnostics.Debug are thread-safe, so no need for lock(this). #if NETCF System.Diagnostics.Debug.Flush(); #else diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs index d493435679d..313f9a09ea8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs @@ -1,555 +1,527 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Globalization; -using System.Net; -using System.Net.Sockets; -using System.Text; - -using log4net.Layout; -using log4net.Core; -using log4net.Util; - -namespace log4net.Appender +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace log4net.Appender { - /// - /// Sends logging events as connectionless UDP datagrams to a remote host or a - /// multicast group using an . - /// - /// - /// - /// UDP guarantees neither that messages arrive, nor that they arrive in the correct order. - /// - /// - /// To view the logging results, a custom application can be developed that listens for logging - /// events. - /// - /// - /// When decoding events send via this appender remember to use the same encoding - /// to decode the events as was used to send the events. See the - /// property to specify the encoding to use. - /// - /// - /// - /// This example shows how to log receive logging events that are sent - /// on IP address 244.0.0.1 and port 8080 to the console. The event is - /// encoded in the packet as a unicode string and it is decoded as such. - /// - /// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); - /// UdpClient udpClient; - /// byte[] buffer; - /// string loggingEvent; - /// - /// try - /// { - /// udpClient = new UdpClient(8080); - /// - /// while(true) - /// { - /// buffer = udpClient.Receive(ref remoteEndPoint); - /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer); - /// Console.WriteLine(loggingEvent); - /// } - /// } - /// catch(Exception e) - /// { - /// Console.WriteLine(e.ToString()); - /// } - /// - /// - /// Dim remoteEndPoint as IPEndPoint - /// Dim udpClient as UdpClient - /// Dim buffer as Byte() - /// Dim loggingEvent as String - /// - /// Try - /// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) - /// udpClient = new UdpClient(8080) - /// - /// While True - /// buffer = udpClient.Receive(ByRef remoteEndPoint) - /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer) - /// Console.WriteLine(loggingEvent) - /// Wend - /// Catch e As Exception - /// Console.WriteLine(e.ToString()) - /// End Try - /// - /// - /// An example configuration section to log information using this appender to the - /// IP 224.0.0.1 on port 8080: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Gert Driesen - /// Nicko Cadell - public class UdpAppender : AppenderSkeleton - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// The default constructor initializes all fields to their default values. - /// - public UdpAppender() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the IP address of the remote host or multicast group to which - /// the underlying should sent the logging event. - /// - /// - /// The IP address of the remote host or multicast group to which the logging event - /// will be sent. - /// - /// - /// - /// Multicast addresses are identified by IP class D addresses (in the range 224.0.0.0 to - /// 239.255.255.255). Multicast packets can pass across different networks through routers, so - /// it is possible to use multicasts in an Internet scenario as long as your network provider - /// supports multicasting. - /// - /// - /// Hosts that want to receive particular multicast messages must register their interest by joining - /// the multicast group. Multicast messages are not sent to networks where no host has joined - /// the multicast group. Class D IP addresses are used for multicast groups, to differentiate - /// them from normal host addresses, allowing nodes to easily detect if a message is of interest. - /// - /// - /// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below: - /// - /// - /// - /// - /// IP Address - /// Description - /// - /// - /// 224.0.0.1 - /// - /// - /// Sends a message to all system on the subnet. - /// - /// - /// - /// - /// 224.0.0.2 - /// - /// - /// Sends a message to all routers on the subnet. - /// - /// - /// - /// - /// 224.0.0.12 - /// - /// - /// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet. - /// - /// - /// - /// - /// - /// - /// A complete list of actually reserved multicast addresses and their owners in the ranges - /// defined by RFC 3171 can be found at the IANA web site. - /// - /// - /// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative - /// addresses. These addresses can be reused with other local groups. Routers are typically - /// configured with filters to prevent multicast traffic in this range from flowing outside - /// of the local network. - /// - /// - public IPAddress RemoteAddress - { - get { return m_remoteAddress; } - set { m_remoteAddress = value; } - } - - /// - /// Gets or sets the TCP port number of the remote host or multicast group to which - /// the underlying should sent the logging event. - /// - /// - /// An integer value in the range to - /// indicating the TCP port number of the remote host or multicast group to which the logging event - /// will be sent. - /// - /// - /// The underlying will send messages to this TCP port number - /// on the remote host or multicast group. - /// - /// The value specified is less than or greater than . - public int RemotePort - { - get { return m_remotePort; } - set - { - if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, - "The value specified is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - m_remotePort = value; - } - } - } - - /// - /// Gets or sets the TCP port number from which the underlying will communicate. - /// - /// - /// An integer value in the range to - /// indicating the TCP port number from which the underlying will communicate. - /// - /// - /// - /// The underlying will bind to this port for sending messages. - /// - /// - /// Setting the value to 0 (the default) will cause the udp client not to bind to - /// a local port. - /// - /// - /// The value specified is less than or greater than . - public int LocalPort - { - get { return m_localPort; } - set - { - if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, - "The value specified is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - m_localPort = value; - } - } - } - - /// - /// Gets or sets used to write the packets. - /// - /// - /// The used to write the packets. - /// - /// - /// - /// The used to write the packets. - /// - /// - public Encoding Encoding - { - get { return m_encoding; } - set { m_encoding = value; } - } - - #endregion Public Instance Properties - - #region Protected Instance Properties - - /// - /// Gets or sets the underlying . - /// - /// - /// The underlying . - /// - /// - /// creates a to send logging events - /// over a network. Classes deriving from can use this - /// property to get or set this . Use the underlying - /// returned from if you require access beyond that which - /// provides. - /// - protected UdpClient Client - { - get { return this.m_client; } - set { this.m_client = value; } - } - - /// - /// Gets or sets the cached remote endpoint to which the logging events should be sent. - /// - /// - /// The cached remote endpoint to which the logging events will be sent. - /// - /// - /// The method will initialize the remote endpoint - /// with the values of the and - /// properties. - /// - protected IPEndPoint RemoteEndPoint - { - get { return this.m_remoteEndPoint; } - set { this.m_remoteEndPoint = value; } - } - - #endregion Protected Instance Properties - - #region Implementation of IOptionHandler - - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// The appender will be ignored if no was specified or - /// an invalid remote or local TCP port number was specified. - /// - /// - /// The required property was not specified. - /// The TCP port number assigned to or is less than or greater than . - public override void ActivateOptions() - { - base.ActivateOptions(); - - if (this.RemoteAddress == null) - { - throw new ArgumentNullException("The required property 'Address' was not specified."); - } - else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort, - "The RemotePort is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort)) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort, - "The LocalPort is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort); - this.InitializeClientConnection(); - } - } - - #endregion - - #region Override implementation of AppenderSkeleton - - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Sends the event using an UDP datagram. - /// - /// - /// Exceptions are passed to the . - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - try - { - Byte [] buffer = m_encoding.GetBytes(RenderLoggingEvent(loggingEvent).ToCharArray()); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + using System.Net; + using System.Net.Sockets; + using System.Text; + + using log4net.Core; + using log4net.Layout; + using log4net.Util; + + /// + /// Sends logging events as connectionless UDP datagrams to a remote host or a + /// multicast group using an . + /// + /// + /// + /// UDP guarantees neither that messages arrive, nor that they arrive in the correct order. + /// + /// + /// To view the logging results, a custom application can be developed that listens for logging + /// events. + /// + /// + /// When decoding events send via this appender remember to use the same encoding + /// to decode the events as was used to send the events. See the + /// property to specify the encoding to use. + /// + /// + /// + /// This example shows how to log receive logging events that are sent + /// on IP address 244.0.0.1 and port 8080 to the console. The event is + /// encoded in the packet as a unicode string and it is decoded as such. + /// + /// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); + /// UdpClient udpClient; + /// byte[] buffer; + /// string loggingEvent; + /// + /// try + /// { + /// udpClient = new UdpClient(8080); + /// + /// while(true) + /// { + /// buffer = udpClient.Receive(ref remoteEndPoint); + /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer); + /// Console.WriteLine(loggingEvent); + /// } + /// } + /// catch(Exception e) + /// { + /// Console.WriteLine(e.ToString()); + /// } + /// + /// + /// Dim remoteEndPoint as IPEndPoint + /// Dim udpClient as UdpClient + /// Dim buffer as Byte() + /// Dim loggingEvent as String + /// + /// Try + /// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) + /// udpClient = new UdpClient(8080) + /// + /// While True + /// buffer = udpClient.Receive(ByRef remoteEndPoint) + /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer) + /// Console.WriteLine(loggingEvent) + /// Wend + /// Catch e As Exception + /// Console.WriteLine(e.ToString()) + /// End Try + /// + /// + /// An example configuration section to log information using this appender to the + /// IP 224.0.0.1 on port 8080: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Gert Driesen. + /// Nicko Cadell. + public class UdpAppender : AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// The default constructor initializes all fields to their default values. + /// + public UdpAppender() + { + } + + /// + /// Gets or sets the IP address of the remote host or multicast group to which + /// the underlying should sent the logging event. + /// + /// + /// The IP address of the remote host or multicast group to which the logging event + /// will be sent. + /// + /// + /// + /// Multicast addresses are identified by IP class D addresses (in the range 224.0.0.0 to + /// 239.255.255.255). Multicast packets can pass across different networks through routers, so + /// it is possible to use multicasts in an Internet scenario as long as your network provider + /// supports multicasting. + /// + /// + /// Hosts that want to receive particular multicast messages must register their interest by joining + /// the multicast group. Multicast messages are not sent to networks where no host has joined + /// the multicast group. Class D IP addresses are used for multicast groups, to differentiate + /// them from normal host addresses, allowing nodes to easily detect if a message is of interest. + /// + /// + /// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below: + /// + /// + /// + /// + /// IP Address + /// Description + /// + /// + /// 224.0.0.1 + /// + /// + /// Sends a message to all system on the subnet. + /// + /// + /// + /// + /// 224.0.0.2 + /// + /// + /// Sends a message to all routers on the subnet. + /// + /// + /// + /// + /// 224.0.0.12 + /// + /// + /// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet. + /// + /// + /// + /// + /// + /// + /// A complete list of actually reserved multicast addresses and their owners in the ranges + /// defined by RFC 3171 can be found at the IANA web site. + /// + /// + /// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative + /// addresses. These addresses can be reused with other local groups. Routers are typically + /// configured with filters to prevent multicast traffic in this range from flowing outside + /// of the local network. + /// + /// + public IPAddress RemoteAddress + { + get { return this.m_remoteAddress; } + set { this.m_remoteAddress = value; } + } + + /// + /// Gets or sets the TCP port number of the remote host or multicast group to which + /// the underlying should sent the logging event. + /// + /// + /// An integer value in the range to + /// indicating the TCP port number of the remote host or multicast group to which the logging event + /// will be sent. + /// + /// + /// The underlying will send messages to this TCP port number + /// on the remote host or multicast group. + /// + /// The value specified is less than or greater than . + public int RemotePort + { + get { return this.m_remotePort; } + + set + { + if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, + "The value specified is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.m_remotePort = value; + } + } + } + + /// + /// Gets or sets the TCP port number from which the underlying will communicate. + /// + /// + /// An integer value in the range to + /// indicating the TCP port number from which the underlying will communicate. + /// + /// + /// + /// The underlying will bind to this port for sending messages. + /// + /// + /// Setting the value to 0 (the default) will cause the udp client not to bind to + /// a local port. + /// + /// + /// The value specified is less than or greater than . + public int LocalPort + { + get { return this.m_localPort; } + + set + { + if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, + "The value specified is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.m_localPort = value; + } + } + } + + /// + /// Gets or sets used to write the packets. + /// + /// + /// The used to write the packets. + /// + /// + /// + /// The used to write the packets. + /// + /// + public Encoding Encoding + { + get { return this.m_encoding; } + set { this.m_encoding = value; } + } + + /// + /// Gets or sets the underlying . + /// + /// + /// The underlying . + /// + /// + /// creates a to send logging events + /// over a network. Classes deriving from can use this + /// property to get or set this . Use the underlying + /// returned from if you require access beyond that which + /// provides. + /// + protected UdpClient Client + { + get { return this.m_client; } + set { this.m_client = value; } + } + + /// + /// Gets or sets the cached remote endpoint to which the logging events should be sent. + /// + /// + /// The cached remote endpoint to which the logging events will be sent. + /// + /// + /// The method will initialize the remote endpoint + /// with the values of the and + /// properties. + /// + protected IPEndPoint RemoteEndPoint + { + get { return this.m_remoteEndPoint; } + set { this.m_remoteEndPoint = value; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// The appender will be ignored if no was specified or + /// an invalid remote or local TCP port number was specified. + /// + /// + /// The required property was not specified. + /// The TCP port number assigned to or is less than or greater than . + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.RemoteAddress == null) + { + throw new ArgumentNullException("The required property 'Address' was not specified."); + } + else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort, + "The RemotePort is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort)) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort, + "The LocalPort is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort); + this.InitializeClientConnection(); + } + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Sends the event using an UDP datagram. + /// + /// + /// Exceptions are passed to the . + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + try + { + byte[] buffer = this.m_encoding.GetBytes(this.RenderLoggingEvent(loggingEvent).ToCharArray()); #if NETSTANDARD1_3 Client.SendAsync(buffer, buffer.Length, RemoteEndPoint).Wait(); #else - this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); + this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); #endif - } - catch (Exception ex) - { - ErrorHandler.Error( - "Unable to send logging event to remote host " + - this.RemoteAddress.ToString() + - " on port " + - this.RemotePort + ".", - ex, - ErrorCode.WriteFailure); - } - } - - /// - /// This appender requires a to be set. - /// - /// true - /// - /// - /// This appender requires a to be set. - /// - /// - override protected bool RequiresLayout - { - get { return true; } - } - - /// - /// Closes the UDP connection and releases all resources associated with - /// this instance. - /// - /// - /// - /// Disables the underlying and releases all managed - /// and unmanaged resources associated with the . - /// - /// - override protected void OnClose() - { - base.OnClose(); - - if (this.Client != null) - { - this.Client.Close(); - this.Client = null; - } - } - - #endregion Override implementation of AppenderSkeleton - - #region Protected Instance Methods - - /// - /// Initializes the underlying connection. - /// - /// - /// - /// The underlying is initialized and binds to the - /// port number from which you intend to communicate. - /// - /// - /// Exceptions are passed to the . - /// - /// - protected virtual void InitializeClientConnection() - { - try - { - if (this.LocalPort == 0) - { + } + catch (Exception ex) + { + this.ErrorHandler.Error( + "Unable to send logging event to remote host " + + this.RemoteAddress.ToString() + + " on port " + + this.RemotePort + ".", + ex, + ErrorCode.WriteFailure); + } + } + + /// + /// Gets a value indicating whether this appender requires a to be set. + /// + /// true. + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Closes the UDP connection and releases all resources associated with + /// this instance. + /// + /// + /// + /// Disables the underlying and releases all managed + /// and unmanaged resources associated with the . + /// + /// + protected override void OnClose() + { + base.OnClose(); + + if (this.Client != null) + { + this.Client.Close(); + this.Client = null; + } + } + + /// + /// Initializes the underlying connection. + /// + /// + /// + /// The underlying is initialized and binds to the + /// port number from which you intend to communicate. + /// + /// + /// Exceptions are passed to the . + /// + /// + protected virtual void InitializeClientConnection() + { + try + { + if (this.LocalPort == 0) + { #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 this.Client = new UdpClient(); #else - this.Client = new UdpClient(RemoteAddress.AddressFamily); + this.Client = new UdpClient(this.RemoteAddress.AddressFamily); #endif - } - else - { + } + else + { #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 this.Client = new UdpClient(this.LocalPort); #else - this.Client = new UdpClient(this.LocalPort, RemoteAddress.AddressFamily); + this.Client = new UdpClient(this.LocalPort, this.RemoteAddress.AddressFamily); #endif - } - } - catch (Exception ex) - { - ErrorHandler.Error( - "Could not initialize the UdpClient connection on port " + - this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".", - ex, - ErrorCode.GenericFailure); - - this.Client = null; - } - } - - #endregion Protected Instance Methods - - #region Private Instance Fields - - /// - /// The IP address of the remote host or multicast group to which - /// the logging event will be sent. - /// - private IPAddress m_remoteAddress; - - /// - /// The TCP port number of the remote host or multicast group to - /// which the logging event will be sent. - /// - private int m_remotePort; - - /// - /// The cached remote endpoint to which the logging events will be sent. - /// - private IPEndPoint m_remoteEndPoint; - - /// - /// The TCP port number from which the will communicate. - /// - private int m_localPort; - - /// - /// The instance that will be used for sending the - /// logging events. - /// - private UdpClient m_client; - - /// - /// The encoding to use for the packet. - /// + } + } + catch (Exception ex) + { + this.ErrorHandler.Error( + "Could not initialize the UdpClient connection on port " + + this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".", + ex, + ErrorCode.GenericFailure); + + this.Client = null; + } + } + + /// + /// The IP address of the remote host or multicast group to which + /// the logging event will be sent. + /// + private IPAddress m_remoteAddress; + + /// + /// The TCP port number of the remote host or multicast group to + /// which the logging event will be sent. + /// + private int m_remotePort; + + /// + /// The cached remote endpoint to which the logging events will be sent. + /// + private IPEndPoint m_remoteEndPoint; + + /// + /// The TCP port number from which the will communicate. + /// + private int m_localPort; + + /// + /// The instance that will be used for sending the + /// logging events. + /// + private UdpClient m_client; + + /// + /// The encoding to use for the packet. + /// #if NETSTANDARD1_3 private Encoding m_encoding = Encoding.Unicode; #else - private Encoding m_encoding = Encoding.Default; + private Encoding m_encoding = Encoding.Default; #endif - - #endregion Private Instance Fields - } + + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs index 0fda8ef0b28..5cd3923951b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs @@ -1,30 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// using System.Reflection; using System.Runtime.CompilerServices; -#if (!SSCLI) +#if !SSCLI // // log4net makes use of static methods which cannot be made com visible // @@ -36,14 +33,14 @@ // [assembly: System.CLSCompliant(true)] -#if (!NETCF) +#if !NETCF // // If log4net is strongly named it still allows partially trusted callers // [assembly: System.Security.AllowPartiallyTrustedCallers] #endif -#if (NET_4_0) +#if NET_4_0 // // Allows partial trust applications (e.g. ASP.NET shared hosting) on .NET 4.0 to work // given our implementation of ISerializable. @@ -52,24 +49,23 @@ #endif // -// General Information about an assembly is controlled through the following +// 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. // - -#if (CLI_1_0) +#if CLI_1_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.CLI 1.0")] [assembly: AssemblyTitle("Apache log4net for CLI 1.0 Compatible Frameworks")] -#elif (NET_1_0) +#elif NET_1_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 1.0")] [assembly: AssemblyTitle("Apache log4net for .NET Framework 1.0")] -#elif (NET_1_1) +#elif NET_1_1 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 1.1")] [assembly: AssemblyTitle("Apache log4net for .NET Framework 1.1")] -#elif (NET_4_5) +#elif NET_4_5 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 4.5")] [assembly: AssemblyTitle("Apache log4net for .NET Framework 4.5")] -#elif (NET_4_0) +#elif NET_4_0 #if CLIENT_PROFILE [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 4.0 CP")] [assembly: AssemblyTitle("Apache log4net for .NET Framework 4.0 Client Profile")] @@ -77,7 +73,7 @@ [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 4.0")] [assembly: AssemblyTitle("Apache log4net for .NET Framework 4.0")] #endif // Client Profile -#elif (NET_2_0) +#elif NET_2_0 #if CLIENT_PROFILE [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 3.5 CP")] [assembly: AssemblyTitle("Apache log4net for .NET Framework 3.5 Client Profile")] @@ -85,40 +81,40 @@ [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 2.0")] [assembly: AssemblyTitle("Apache log4net for .NET Framework 2.0")] #endif // Client Profile -#elif (NETCF_1_0) +#elif NETCF_1_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NETCF 1.0")] [assembly: AssemblyTitle("Apache log4net for .NET Compact Framework 1.0")] -#elif (NETCF_2_0) +#elif NETCF_2_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NETCF 2.0")] [assembly: AssemblyTitle("Apache log4net for .NET Compact Framework 2.0")] -#elif (MONO_1_0) +#elif MONO_1_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 1.0")] [assembly: AssemblyTitle("Apache log4net for Mono 1.0")] -#elif (MONO_2_0) +#elif MONO_2_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 2.0")] [assembly: AssemblyTitle("Apache log4net for Mono 2.0")] -#elif (MONO_3_5) +#elif MONO_3_5 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 3.5")] [assembly: AssemblyTitle("Apache log4net for Mono 3.5")] -#elif (MONO_4_0) +#elif MONO_4_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 4.0")] [assembly: AssemblyTitle("Apache log4net for Mono 4.0")] -#elif (SSCLI_1_0) +#elif SSCLI_1_0 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-SSCLI 1.0")] [assembly: AssemblyTitle("Apache log4net for Shared Source CLI 1.0")] -#elif (NET) +#elif NET [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET")] [assembly: AssemblyTitle("Apache log4net for .NET Framework")] -#elif (NETSTANDARD1_3) +#elif NETSTANDARD1_3 [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET Core 1.0")] [assembly: AssemblyTitle("DotNetNuke.log4net for .NET Core 1.0")] -#elif (NETCF) +#elif NETCF [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NETCF")] [assembly: AssemblyTitle("DotNetNuke.log4net for .NET Compact Framework")] -#elif (MONO) +#elif MONO [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono")] [assembly: AssemblyTitle("DotNetNuke.log4net for Mono")] -#elif (SSCLI) +#elif SSCLI [assembly: AssemblyInformationalVersionAttribute("2.0.6.0-SSCLI")] [assembly: AssemblyTitle("DotNetNuke.log4net for Shared Source CLI")] #else @@ -141,6 +137,6 @@ [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile(@"..\..\..\log4net.snk")] #endif + // We do not use a CSP key for strong naming // [assembly: AssemblyKeyName("")] - diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs index d8b988b1865..3fb82b90563 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs @@ -1,37 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: [assembly: System.Reflection.AssemblyVersion("3.0.1.0")] #if !NETCF @@ -42,8 +39,6 @@ // // Shared assembly settings -// - [assembly: System.Reflection.AssemblyCompany("The Apache Software Foundation")] [assembly: System.Reflection.AssemblyCopyright("Copyright 2004-2018 The Apache Software Foundation.")] [assembly: System.Reflection.AssemblyTrademark("Apache and Apache log4net are trademarks of The Apache Software Foundation")] diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs index d83f1e83578..452262e289b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF @@ -28,51 +26,48 @@ namespace log4net.Config { - /// - /// Assembly level attribute that specifies a domain to alias to this assembly's repository. - /// - /// - /// - /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. - /// - /// - /// An assembly's logger repository is defined by its , - /// however this can be overridden by an assembly loaded before the target assembly. - /// - /// - /// An assembly can alias another assembly's domain to its repository by - /// specifying this attribute with the name of the target domain. - /// - /// - /// This attribute can only be specified on the assembly and may be used - /// as many times as necessary to alias all the required domains. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly,AllowMultiple=true)] - [Serializable] - [Obsolete("Use AliasRepositoryAttribute instead of AliasDomainAttribute. Scheduled removal in v10.0.0.")] - public sealed class AliasDomainAttribute : AliasRepositoryAttribute - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class with - /// the specified domain to alias to this assembly's repository. - /// - /// The domain to alias to this assembly's repository. - /// - /// - /// Obsolete. Use instead of . - /// - /// - public AliasDomainAttribute(string name) : base(name) - { - } - - #endregion Public Instance Constructors - } + /// + /// Assembly level attribute that specifies a domain to alias to this assembly's repository. + /// + /// + /// + /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. + /// + /// + /// An assembly's logger repository is defined by its , + /// however this can be overridden by an assembly loaded before the target assembly. + /// + /// + /// An assembly can alias another assembly's domain to its repository by + /// specifying this attribute with the name of the target domain. + /// + /// + /// This attribute can only be specified on the assembly and may be used + /// as many times as necessary to alias all the required domains. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + [Serializable] + [Obsolete("Use AliasRepositoryAttribute instead of AliasDomainAttribute. Scheduled removal in v10.0.0.")] + public sealed class AliasDomainAttribute : AliasRepositoryAttribute + { + /// + /// Initializes a new instance of the class with + /// the specified domain to alias to this assembly's repository. + /// + /// The domain to alias to this assembly's repository. + /// + /// + /// Obsolete. Use instead of . + /// + /// + public AliasDomainAttribute(string name) + : base(name) + { + } + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs index 78efe186fdb..1ae747522ad 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF @@ -28,80 +26,67 @@ namespace log4net.Config { - /// - /// Assembly level attribute that specifies a repository to alias to this assembly's repository. - /// - /// - /// - /// An assembly's logger repository is defined by its , - /// however this can be overridden by an assembly loaded before the target assembly. - /// - /// - /// An assembly can alias another assembly's repository to its repository by - /// specifying this attribute with the name of the target repository. - /// - /// - /// This attribute can only be specified on the assembly and may be used - /// as many times as necessary to alias all the required repositories. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly,AllowMultiple=true)] - [Serializable] - public /*sealed*/ class AliasRepositoryAttribute : Attribute - { - // - // Class is not sealed because AliasDomainAttribute extends it while it is obsoleted - // - - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class with - /// the specified repository to alias to this assembly's repository. - /// - /// The repository to alias to this assembly's repository. - /// - /// - /// Initializes a new instance of the class with - /// the specified repository to alias to this assembly's repository. - /// - /// - public AliasRepositoryAttribute(string name) - { - Name = name; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the repository to alias to this assembly's repository. - /// - /// - /// The repository to alias to this assemby's repository. - /// - /// - /// - /// The name of the repository to alias to this assembly's repository. - /// - /// - public string Name - { - get { return m_name; } - set { m_name = value ; } - } - - #endregion Public Instance Properties - - #region Private Instance Fields - - private string m_name = null; - - #endregion Private Instance Fields - } + /// + /// Assembly level attribute that specifies a repository to alias to this assembly's repository. + /// + /// + /// + /// An assembly's logger repository is defined by its , + /// however this can be overridden by an assembly loaded before the target assembly. + /// + /// + /// An assembly can alias another assembly's repository to its repository by + /// specifying this attribute with the name of the target repository. + /// + /// + /// This attribute can only be specified on the assembly and may be used + /// as many times as necessary to alias all the required repositories. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + [Serializable] + public /*sealed*/ class AliasRepositoryAttribute : Attribute + { + // Class is not sealed because AliasDomainAttribute extends it while it is obsoleted + // + + /// + /// Initializes a new instance of the class with + /// the specified repository to alias to this assembly's repository. + /// + /// The repository to alias to this assembly's repository. + /// + /// + /// Initializes a new instance of the class with + /// the specified repository to alias to this assembly's repository. + /// + /// + public AliasRepositoryAttribute(string name) + { + this.Name = name; + } + + /// + /// Gets or sets the repository to alias to this assembly's repository. + /// + /// + /// The repository to alias to this assemby's repository. + /// + /// + /// + /// The name of the repository to alias to this assembly's repository. + /// + /// + public string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + private string m_name = null; + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs index 7688762db28..901357b21c3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs @@ -1,106 +1,94 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Reflection; - -using log4net.Appender; -using log4net.Layout; -using log4net.Util; -using log4net.Repository; -using log4net.Repository.Hierarchy; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Config { - /// - /// Use this class to quickly configure a . - /// - /// - /// - /// Allows very simple programmatic configuration of log4net. - /// - /// - /// Only one appender can be configured using this configurator. - /// The appender is set at the root of the hierarchy and all logging - /// events will be delivered to that appender. - /// - /// - /// Appenders can also implement the interface. Therefore - /// they would require that the method - /// be called after the appenders properties have been configured. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class BasicConfigurator - { - #region Private Static Fields - - /// - /// The fully qualified type of the BasicConfigurator class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(BasicConfigurator); - - #endregion Private Static Fields - - #region Private Instance Constructors - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Reflection; + + using log4net.Appender; + using log4net.Layout; + using log4net.Repository; + using log4net.Repository.Hierarchy; + using log4net.Util; + + /// + /// Use this class to quickly configure a . + /// + /// + /// + /// Allows very simple programmatic configuration of log4net. + /// + /// + /// Only one appender can be configured using this configurator. + /// The appender is set at the root of the hierarchy and all logging + /// events will be delivered to that appender. + /// + /// + /// Appenders can also implement the interface. Therefore + /// they would require that the method + /// be called after the appenders properties have been configured. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class BasicConfigurator + { /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private BasicConfigurator() - { - } - - #endregion Private Instance Constructors - - #region Public Static Methods - + /// The fully qualified type of the BasicConfigurator class. + ///
+ /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(BasicConfigurator); + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private BasicConfigurator() + { + } + #if !NETSTANDARD1_3 - /// - /// Initializes the log4net system with a default configuration. - /// - /// - /// - /// Initializes the log4net logging system using a - /// that will write to Console.Out. The log messages are - /// formatted using the layout object - /// with the - /// layout style. - /// - /// - static public ICollection Configure() - { + /// + /// Initializes the log4net system with a default configuration. + /// + /// + /// + /// Initializes the log4net logging system using a + /// that will write to Console.Out. The log messages are + /// formatted using the layout object + /// with the + /// layout style. + /// + /// + /// + public static ICollection Configure() + { return BasicConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); } @@ -112,8 +100,9 @@ static public ICollection Configure() /// /// Initializes the log4net system using the specified appenders. /// - /// - static public ICollection Configure(params IAppender[] appenders) + /// + /// + public static ICollection Configure(params IAppender[] appenders) { ArrayList configurationMessages = new ArrayList(); @@ -129,36 +118,38 @@ static public ICollection Configure(params IAppender[] appenders) return configurationMessages; } - /// - /// Initializes the log4net system using the specified appender. - /// - /// The appender to use to log all logging events. - /// - /// - /// Initializes the log4net system using the specified appender. - /// - /// - static public ICollection Configure(IAppender appender) - { + /// + /// Initializes the log4net system using the specified appender. + /// + /// The appender to use to log all logging events. + /// + /// + /// Initializes the log4net system using the specified appender. + /// + /// + /// + public static ICollection Configure(IAppender appender) + { return Configure(new IAppender[] { appender }); - } + } #endif // !NETSTANDARD1_3 - /// - /// Initializes the with a default configuration. - /// - /// The repository to configure. - /// - /// - /// Initializes the specified repository using a - /// that will write to Console.Out. The log messages are - /// formatted using the layout object - /// with the - /// layout style. - /// - /// - static public ICollection Configure(ILoggerRepository repository) - { + /// + /// Initializes the with a default configuration. + /// + /// The repository to configure. + /// + /// + /// Initializes the specified repository using a + /// that will write to Console.Out. The log messages are + /// formatted using the layout object + /// with the + /// layout style. + /// + /// + /// + public static ICollection Configure(ILoggerRepository repository) + { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) @@ -179,7 +170,7 @@ static public ICollection Configure(ILoggerRepository repository) repository.ConfigurationMessages = configurationMessages; return configurationMessages; - } + } /// /// Initializes the using the specified appender. @@ -190,8 +181,9 @@ static public ICollection Configure(ILoggerRepository repository) /// /// Initializes the using the specified appender. /// - /// - static public ICollection Configure(ILoggerRepository repository, IAppender appender) + /// + /// + public static ICollection Configure(ILoggerRepository repository, IAppender appender) { return Configure(repository, new IAppender[] { appender }); } @@ -205,8 +197,9 @@ static public ICollection Configure(ILoggerRepository repository, IAppender appe /// /// Initializes the using the specified appender. /// - /// - static public ICollection Configure(ILoggerRepository repository, params IAppender[] appenders) + /// + /// + public static ICollection Configure(ILoggerRepository repository, params IAppender[] appenders) { ArrayList configurationMessages = new ArrayList(); @@ -219,9 +212,9 @@ static public ICollection Configure(ILoggerRepository repository, params IAppend return configurationMessages; } - - static private void InternalConfigure(ILoggerRepository repository, params IAppender[] appenders) - { + + private static void InternalConfigure(ILoggerRepository repository, params IAppender[] appenders) + { IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator; if (configurableRepository != null) { @@ -231,8 +224,6 @@ static private void InternalConfigure(ILoggerRepository repository, params IAppe { LogLog.Warn(declaringType, "BasicConfigurator: Repository [" + repository + "] does not support the BasicConfigurator"); } - } - - #endregion Public Static Methods - } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs index 3290031aa86..e3753f59f2f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,99 +18,100 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF using System; using System.Reflection; - + using log4net.Repository; namespace log4net.Config { - /// - /// Base class for all log4net configuration attributes. - /// - /// - /// This is an abstract class that must be extended by - /// specific configurators. This attribute allows the - /// configurator to be parameterized by an assembly level - /// attribute. - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly)] - public abstract class ConfiguratorAttribute : Attribute, IComparable - { - private int m_priority = 0; - - /// - /// Constructor used by subclasses. - /// - /// the ordering priority for this configurator - /// - /// - /// The is used to order the configurator - /// attributes before they are invoked. Higher priority configurators are executed - /// before lower priority ones. - /// - /// - protected ConfiguratorAttribute(int priority) - { - m_priority = priority; - } + /// + /// Base class for all log4net configuration attributes. + /// + /// + /// This is an abstract class that must be extended by + /// specific configurators. This attribute allows the + /// configurator to be parameterized by an assembly level + /// attribute. + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly)] + public abstract class ConfiguratorAttribute : Attribute, IComparable + { + private int m_priority = 0; + + /// + /// Initializes a new instance of the class. + /// Constructor used by subclasses. + /// + /// the ordering priority for this configurator. + /// + /// + /// The is used to order the configurator + /// attributes before they are invoked. Higher priority configurators are executed + /// before lower priority ones. + /// + /// + protected ConfiguratorAttribute(int priority) + { + this.m_priority = priority; + } - /// - /// Configures the for the specified assembly. - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - /// - /// - /// Abstract method implemented by a subclass. When this method is called - /// the subclass should configure the . - /// - /// - public abstract void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository); + /// + /// Configures the for the specified assembly. + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + /// + /// + /// Abstract method implemented by a subclass. When this method is called + /// the subclass should configure the . + /// + /// + public abstract void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository); - /// - /// Compare this instance to another ConfiguratorAttribute - /// - /// the object to compare to - /// see - /// - /// - /// Compares the priorities of the two instances. - /// Sorts by priority in descending order. Objects with the same priority are - /// randomly ordered. - /// - /// - public int CompareTo(object obj) - { - // Reference equals - if ((object)this == obj) - { - return 0; - } + /// + /// Compare this instance to another ConfiguratorAttribute. + /// + /// the object to compare to. + /// see . + /// + /// + /// Compares the priorities of the two instances. + /// Sorts by priority in descending order. Objects with the same priority are + /// randomly ordered. + /// + /// + public int CompareTo(object obj) + { + // Reference equals + if ((object)this == obj) + { + return 0; + } - int result = -1; + int result = -1; - ConfiguratorAttribute target = obj as ConfiguratorAttribute; - if (target != null) - { - // Compare the priorities - result = target.m_priority.CompareTo(m_priority); - if (result == 0) - { - // Same priority, so have to provide some ordering - result = -1; - } - } - return result; - } - } + ConfiguratorAttribute target = obj as ConfiguratorAttribute; + if (target != null) + { + // Compare the priorities + result = target.m_priority.CompareTo(this.m_priority); + if (result == 0) + { + // Same priority, so have to provide some ordering + result = -1; + } + } + + return result; + } + } } #endif //!NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs index 99de3ed838f..3b817065f68 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs @@ -1,362 +1,347 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Xml; -using System.Collections; -using System.IO; -using System.Reflection; -using System.Threading; - -using log4net.Appender; -using log4net.Util; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Config { - /// - /// Use this class to initialize the log4net environment using an Xml tree. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// Configures a using an Xml tree. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [Obsolete("Use XmlConfigurator instead of DOMConfigurator. Scheduled removal in v10.0.0.")] - public sealed class DOMConfigurator - { - #region Private Instance Constructors - - /// - /// Private constructor - /// - private DOMConfigurator() - { - } - - #endregion Protected Instance Constructors - - #region Configure static methods - - /// - /// Automatically configures the log4net system based on the - /// application's configuration settings. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v11.0.0.")] - static public void Configure() - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); - } - - /// - /// Automatically configures the using settings - /// stored in the application's configuration file. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - /// The repository to configure. - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - static public void Configure(ILoggerRepository repository) - { - XmlConfigurator.Configure(repository); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + using System.Reflection; + using System.Threading; + using System.Xml; + + using log4net.Appender; + using log4net.Repository; + using log4net.Util; + + /// + /// Use this class to initialize the log4net environment using an Xml tree. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// Configures a using an Xml tree. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [Obsolete("Use XmlConfigurator instead of DOMConfigurator. Scheduled removal in v10.0.0.")] + public sealed class DOMConfigurator + { + /// + /// Initializes a new instance of the class. + /// Private constructor. + /// + private DOMConfigurator() + { + } + + /// + /// Automatically configures the log4net system based on the + /// application's configuration settings. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v11.0.0.")] + public static void Configure() + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); + } - /// - /// Configures log4net using a log4net element - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// The element to parse. - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - static public void Configure(XmlElement element) - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element); - } + /// + /// Automatically configures the using settings + /// stored in the application's configuration file. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + /// The repository to configure. + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] + public static void Configure(ILoggerRepository repository) + { + XmlConfigurator.Configure(repository); + } - /// - /// Configures the using the specified XML - /// element. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// The repository to configure. - /// The element to parse. - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - static public void Configure(ILoggerRepository repository, XmlElement element) - { - XmlConfigurator.Configure(repository, element); - } + /// + /// Configures log4net using a log4net element. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// The element to parse. + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] + public static void Configure(XmlElement element) + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element); + } - /// - /// Configures log4net using the specified configuration file. - /// - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// The log4net configuration file can possible be specified in the application's - /// configuration file (either MyAppName.exe.config for a - /// normal application on Web.config for an ASP.NET application). - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - static public void Configure(FileInfo configFile) - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); - } + /// + /// Configures the using the specified XML + /// element. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// The repository to configure. + /// The element to parse. + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] + public static void Configure(ILoggerRepository repository, XmlElement element) + { + XmlConfigurator.Configure(repository, element); + } - /// - /// Configures log4net using the specified configuration file. - /// - /// A stream to load the XML configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// Note that this method will NOT close the stream parameter. - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - static public void Configure(Stream configStream) - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream); - } + /// + /// Configures log4net using the specified configuration file. + /// + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// The log4net configuration file can possible be specified in the application's + /// configuration file (either MyAppName.exe.config for a + /// normal application on Web.config for an ASP.NET application). + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] + public static void Configure(FileInfo configFile) + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); + } - /// - /// Configures the using the specified configuration - /// file. - /// - /// The repository to configure. - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The log4net configuration file can possible be specified in the application's - /// configuration file (either MyAppName.exe.config for a - /// normal application on Web.config for an ASP.NET application). - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - static public void Configure(ILoggerRepository repository, FileInfo configFile) - { - XmlConfigurator.Configure(repository, configFile); - } + /// + /// Configures log4net using the specified configuration file. + /// + /// A stream to load the XML configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// Note that this method will NOT close the stream parameter. + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] + public static void Configure(Stream configStream) + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream); + } + /// + /// Configures the using the specified configuration + /// file. + /// + /// The repository to configure. + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The log4net configuration file can possible be specified in the application's + /// configuration file (either MyAppName.exe.config for a + /// normal application on Web.config for an ASP.NET application). + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] + public static void Configure(ILoggerRepository repository, FileInfo configFile) + { + XmlConfigurator.Configure(repository, configFile); + } + + /// + /// Configures the using the specified configuration + /// file. + /// + /// The repository to configure. + /// The stream to load the XML configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// Note that this method will NOT close the stream parameter. + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] + public static void Configure(ILoggerRepository repository, Stream configStream) + { + XmlConfigurator.Configure(repository, configStream); + } + +#if !NETCF && !SSCLI + + /// + /// Configures log4net using the file specified, monitors the file for changes + /// and reloads the configuration if a change is detected. + /// + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The configuration file will be monitored using a + /// and depends on the behavior of that class. + /// + /// + /// For more information on how to configure log4net using + /// a separate configuration file, see . + /// + /// + /// + [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch. Scheduled removal in v10.0.0.")] + public static void ConfigureAndWatch(FileInfo configFile) + { + XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); + } - /// - /// Configures the using the specified configuration - /// file. - /// - /// The repository to configure. - /// The stream to load the XML configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// Note that this method will NOT close the stream parameter. - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - static public void Configure(ILoggerRepository repository, Stream configStream) - { - XmlConfigurator.Configure(repository, configStream); - } - - #endregion Configure static methods - - #region ConfigureAndWatch static methods - -#if (!NETCF && !SSCLI) - - /// - /// Configures log4net using the file specified, monitors the file for changes - /// and reloads the configuration if a change is detected. - /// - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The configuration file will be monitored using a - /// and depends on the behavior of that class. - /// - /// - /// For more information on how to configure log4net using - /// a separate configuration file, see . - /// - /// - /// - [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch. Scheduled removal in v10.0.0.")] - static public void ConfigureAndWatch(FileInfo configFile) - { - XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); - } - - /// - /// Configures the using the file specified, - /// monitors the file for changes and reloads the configuration if a change - /// is detected. - /// - /// The repository to configure. - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The configuration file will be monitored using a - /// and depends on the behavior of that class. - /// - /// - /// For more information on how to configure log4net using - /// a separate configuration file, see . - /// - /// - /// - [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch. Scheduled removal in v10.0.0.")] - static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) - { - XmlConfigurator.ConfigureAndWatch(repository, configFile); - } + /// + /// Configures the using the file specified, + /// monitors the file for changes and reloads the configuration if a change + /// is detected. + /// + /// The repository to configure. + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The configuration file will be monitored using a + /// and depends on the behavior of that class. + /// + /// + /// For more information on how to configure log4net using + /// a separate configuration file, see . + /// + /// + /// + [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch. Scheduled removal in v10.0.0.")] + public static void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) + { + XmlConfigurator.ConfigureAndWatch(repository, configFile); + } #endif - - #endregion ConfigureAndWatch static methods - } -} - + + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs index 4efb23a4086..200d2d16e37 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,46 +18,45 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF using System; -using System.Reflection; using System.IO; - -using log4net.Util; +using System.Reflection; + using log4net.Repository; using log4net.Repository.Hierarchy; +using log4net.Util; namespace log4net.Config { - /// - /// Assembly level attribute to configure the . - /// - /// - /// - /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. - /// - /// - /// This attribute may only be used at the assembly scope and can only - /// be used once per assembly. - /// - /// - /// Use this attribute to configure the - /// without calling one of the - /// methods. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - [Obsolete("Use XmlConfiguratorAttribute instead of DOMConfiguratorAttribute. Scheduled removal in v10.0.0.")] - public sealed class DOMConfiguratorAttribute : XmlConfiguratorAttribute - { - } + /// + /// Assembly level attribute to configure the . + /// + /// + /// + /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. + /// + /// + /// This attribute may only be used at the assembly scope and can only + /// be used once per assembly. + /// + /// + /// Use this attribute to configure the + /// without calling one of the + /// methods. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + [Obsolete("Use XmlConfiguratorAttribute instead of DOMConfiguratorAttribute. Scheduled removal in v10.0.0.")] + public sealed class DOMConfiguratorAttribute : XmlConfiguratorAttribute + { + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs index 2109f38eeb3..72f7c5c6688 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF @@ -28,64 +26,63 @@ namespace log4net.Config { - /// - /// Assembly level attribute that specifies the logging domain for the assembly. - /// - /// - /// - /// DomainAttribute is obsolete. Use RepositoryAttribute instead of DomainAttribute. - /// - /// - /// Assemblies are mapped to logging domains. Each domain has its own - /// logging repository. This attribute specified on the assembly controls - /// the configuration of the domain. The property specifies the name - /// of the domain that this assembly is a part of. The - /// specifies the type of the repository objects to create for the domain. If - /// this attribute is not specified and a is not specified - /// then the assembly will be part of the default shared logging domain. - /// - /// - /// This attribute can only be specified on the assembly and may only be used - /// once per assembly. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - [Obsolete("Use RepositoryAttribute instead of DomainAttribute. Scheduled removal in v10.0.0.")] - public sealed class DomainAttribute : RepositoryAttribute - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. - /// - /// - public DomainAttribute() : base() - { - } - - /// - /// Initialize a new instance of the class - /// with the name of the domain. - /// - /// The name of the domain. - /// - /// - /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. - /// - /// - public DomainAttribute(string name) : base(name) - { - } - - #endregion Public Instance Constructors - } + /// + /// Assembly level attribute that specifies the logging domain for the assembly. + /// + /// + /// + /// DomainAttribute is obsolete. Use RepositoryAttribute instead of DomainAttribute. + /// + /// + /// Assemblies are mapped to logging domains. Each domain has its own + /// logging repository. This attribute specified on the assembly controls + /// the configuration of the domain. The property specifies the name + /// of the domain that this assembly is a part of. The + /// specifies the type of the repository objects to create for the domain. If + /// this attribute is not specified and a is not specified + /// then the assembly will be part of the default shared logging domain. + /// + /// + /// This attribute can only be specified on the assembly and may only be used + /// once per assembly. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + [Obsolete("Use RepositoryAttribute instead of DomainAttribute. Scheduled removal in v10.0.0.")] + public sealed class DomainAttribute : RepositoryAttribute + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. + /// + /// + public DomainAttribute() + : base() + { + } + + /// + /// Initializes a new instance of the class. + /// Initialize a new instance of the class + /// with the name of the domain. + /// + /// The name of the domain. + /// + /// + /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. + /// + /// + public DomainAttribute(string name) + : base(name) + { + } + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs index 9545495656e..af821518abb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for application .config files #if !NETCF @@ -29,68 +27,60 @@ namespace log4net.Config { - /// - /// Class to register for the log4net section of the configuration file - /// - /// - /// The log4net section of the configuration file needs to have a section - /// handler registered. This is the section handler used. It simply returns - /// the XML element that is the root of the section. - /// - /// - /// Example of registering the log4net section handler : - /// - /// - /// - ///
- /// - /// - /// log4net configuration XML goes here - /// - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class Log4NetConfigurationSectionHandler : IConfigurationSectionHandler - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public Log4NetConfigurationSectionHandler() - { - } - - #endregion Public Instance Constructors - - #region Implementation of IConfigurationSectionHandler - - /// - /// Parses the configuration section. - /// - /// The configuration settings in a corresponding parent configuration section. - /// The configuration context when called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference. - /// The for the log4net section. - /// The for the log4net section. - /// - /// - /// Returns the containing the configuration data, - /// - /// - public object Create(object parent, object configContext, XmlNode section) - { - return section; - } - - #endregion Implementation of IConfigurationSectionHandler - } + /// + /// Class to register for the log4net section of the configuration file. + /// + /// + /// The log4net section of the configuration file needs to have a section + /// handler registered. This is the section handler used. It simply returns + /// the XML element that is the root of the section. + /// + /// + /// Example of registering the log4net section handler : + /// + /// + /// + ///
+ /// + /// + /// log4net configuration XML goes here + /// + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class Log4NetConfigurationSectionHandler : IConfigurationSectionHandler + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public Log4NetConfigurationSectionHandler() + { + } + + /// + /// Parses the configuration section. + /// + /// The configuration settings in a corresponding parent configuration section. + /// The configuration context when called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference. + /// The for the log4net section. + /// The for the log4net section. + /// + /// + /// Returns the containing the configuration data. + /// + /// + public object Create(object parent, object configContext, XmlNode section) + { + return section; + } + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs index 4ac7619adfa..4619efa162d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF @@ -27,176 +25,158 @@ using System; using System.Globalization; using System.Reflection; - + using log4net.Core; -using log4net.Util; using log4net.Plugin; +using log4net.Util; namespace log4net.Config { - /// - /// Assembly level attribute that specifies a plugin to attach to - /// the repository. - /// - /// - /// - /// Specifies the type of a plugin to create and attach to the - /// assembly's repository. The plugin type must implement the - /// interface. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly,AllowMultiple=true)] - [Serializable] - public sealed class PluginAttribute : Attribute, IPluginFactory - { - #region Public Instance Constructors - + /// + /// Assembly level attribute that specifies a plugin to attach to + /// the repository. + /// + /// + /// + /// Specifies the type of a plugin to create and attach to the + /// assembly's repository. The plugin type must implement the + /// interface. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + [Serializable] + public sealed class PluginAttribute : Attribute, IPluginFactory + { #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - /// - /// Initializes a new instance of the class - /// with the specified type. - /// - /// The type name of plugin to create. - /// - /// - /// Create the attribute with the plugin type specified. - /// - /// - /// Where possible use the constructor that takes a . - /// - /// - public PluginAttribute(string typeName) - { - m_typeName = typeName; - } + /// + /// Initializes a new instance of the class + /// with the specified type. + /// + /// The type name of plugin to create. + /// + /// + /// Create the attribute with the plugin type specified. + /// + /// + /// Where possible use the constructor that takes a . + /// + /// + public PluginAttribute(string typeName) + { + this.m_typeName = typeName; + } #endif - /// - /// Initializes a new instance of the class - /// with the specified type. - /// - /// The type of plugin to create. - /// - /// - /// Create the attribute with the plugin type specified. - /// - /// - public PluginAttribute(Type type) - { - m_type = type; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the type for the plugin. - /// - /// - /// The type for the plugin. - /// - /// - /// - /// The type for the plugin. - /// - /// - public Type Type - { - get { return m_type; } - set { m_type = value ; } - } - - /// - /// Gets or sets the type name for the plugin. - /// - /// - /// The type name for the plugin. - /// - /// - /// - /// The type name for the plugin. - /// - /// - /// Where possible use the property instead. - /// - /// - public string TypeName - { - get { return m_typeName; } - set { m_typeName = value ; } - } - - #endregion Public Instance Properties - - #region Implementation of IPluginFactory - - /// - /// Creates the plugin object defined by this attribute. - /// - /// - /// - /// Creates the instance of the object as - /// specified by this attribute. - /// - /// - /// The plugin object. - public IPlugin CreatePlugin() - { - Type pluginType = m_type; + /// + /// Initializes a new instance of the class + /// with the specified type. + /// + /// The type of plugin to create. + /// + /// + /// Create the attribute with the plugin type specified. + /// + /// + public PluginAttribute(Type type) + { + this.m_type = type; + } + + /// + /// Gets or sets the type for the plugin. + /// + /// + /// The type for the plugin. + /// + /// + /// + /// The type for the plugin. + /// + /// + public Type Type + { + get { return this.m_type; } + set { this.m_type = value; } + } + + /// + /// Gets or sets the type name for the plugin. + /// + /// + /// The type name for the plugin. + /// + /// + /// + /// The type name for the plugin. + /// + /// + /// Where possible use the property instead. + /// + /// + public string TypeName + { + get { return this.m_typeName; } + set { this.m_typeName = value; } + } + + /// + /// Creates the plugin object defined by this attribute. + /// + /// + /// + /// Creates the instance of the object as + /// specified by this attribute. + /// + /// + /// The plugin object. + public IPlugin CreatePlugin() + { + Type pluginType = this.m_type; #if !NETSTANDARD1_3 - if (m_type == null) - { - // Get the plugin object type from the string type name - pluginType = SystemInfo.GetTypeFromString(m_typeName, true, true); - } + if (this.m_type == null) + { + // Get the plugin object type from the string type name + pluginType = SystemInfo.GetTypeFromString(this.m_typeName, true, true); + } #endif - // Check that the type is a plugin - if (!(typeof(IPlugin).IsAssignableFrom(pluginType))) - { - throw new LogException("Plugin type [" + pluginType.FullName + "] does not implement the log4net.IPlugin interface"); - } - - // Create an instance of the plugin using the default constructor - IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType); - - return plugin; - } - - #endregion Implementation of IPluginFactory - - #region Override implementation of Object - - /// - /// Returns a representation of the properties of this object. - /// - /// - /// - /// Overrides base class method to - /// return a representation of the properties of this object. - /// - /// - /// A representation of the properties of this object - override public string ToString() - { - if (m_type != null) - { - return "PluginAttribute[Type=" + m_type.FullName + "]"; - } - return "PluginAttribute[Type=" + m_typeName + "]"; - } - - #endregion Override implementation of Object - - #region Private Instance Fields - - private string m_typeName = null; - private Type m_type = null; - - #endregion Private Instance Fields - } + + // Check that the type is a plugin + if (!typeof(IPlugin).IsAssignableFrom(pluginType)) + { + throw new LogException("Plugin type [" + pluginType.FullName + "] does not implement the log4net.IPlugin interface"); + } + + // Create an instance of the plugin using the default constructor + IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType); + + return plugin; + } + + /// + /// Returns a representation of the properties of this object. + /// + /// + /// + /// Overrides base class method to + /// return a representation of the properties of this object. + /// + /// + /// A representation of the properties of this object. + public override string ToString() + { + if (this.m_type != null) + { + return "PluginAttribute[Type=" + this.m_type.FullName + "]"; + } + + return "PluginAttribute[Type=" + this.m_typeName + "]"; + } + + private string m_typeName = null; + private Type m_type = null; + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs index 702882b174b..e914543c1fe 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF @@ -28,121 +26,109 @@ namespace log4net.Config { - /// - /// Assembly level attribute that specifies the logging repository for the assembly. - /// - /// - /// - /// Assemblies are mapped to logging repository. This attribute specified - /// on the assembly controls - /// the configuration of the repository. The property specifies the name - /// of the repository that this assembly is a part of. The - /// specifies the type of the object - /// to create for the assembly. If this attribute is not specified or a - /// is not specified then the assembly will be part of the default shared logging repository. - /// - /// - /// This attribute can only be specified on the assembly and may only be used - /// once per assembly. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - public /*sealed*/ class RepositoryAttribute : Attribute - { - // - // Class is not sealed because DomainAttribute extends it while it is obsoleted - // + /// + /// Assembly level attribute that specifies the logging repository for the assembly. + /// + /// + /// + /// Assemblies are mapped to logging repository. This attribute specified + /// on the assembly controls + /// the configuration of the repository. The property specifies the name + /// of the repository that this assembly is a part of. The + /// specifies the type of the object + /// to create for the assembly. If this attribute is not specified or a + /// is not specified then the assembly will be part of the default shared logging repository. + /// + /// + /// This attribute can only be specified on the assembly and may only be used + /// once per assembly. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + public /*sealed*/ class RepositoryAttribute : Attribute + { + // Class is not sealed because DomainAttribute extends it while it is obsoleted + // + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public RepositoryAttribute() + { + } + + /// + /// Initializes a new instance of the class. + /// Initialize a new instance of the class + /// with the name of the repository. + /// + /// The name of the repository. + /// + /// + /// Initialize the attribute with the name for the assembly's repository. + /// + /// + public RepositoryAttribute(string name) + { + this.m_name = name; + } + + /// + /// Gets or sets the name of the logging repository. + /// + /// + /// The string name to use as the name of the repository associated with this + /// assembly. + /// + /// + /// + /// This value does not have to be unique. Several assemblies can share the + /// same repository. They will share the logging configuration of the repository. + /// + /// + public string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public RepositoryAttribute() - { - } - - /// - /// Initialize a new instance of the class - /// with the name of the repository. - /// - /// The name of the repository. - /// - /// - /// Initialize the attribute with the name for the assembly's repository. - /// - /// - public RepositoryAttribute(string name) - { - m_name = name; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the name of the logging repository. - /// - /// - /// The string name to use as the name of the repository associated with this - /// assembly. - /// - /// - /// - /// This value does not have to be unique. Several assemblies can share the - /// same repository. They will share the logging configuration of the repository. - /// - /// - public string Name - { - get { return m_name; } - set { m_name = value ; } - } - - /// - /// Gets or sets the type of repository to create for this assembly. - /// - /// - /// The type of repository to create for this assembly. - /// - /// - /// - /// The type of the repository to create for the assembly. - /// The type must implement the - /// interface. - /// - /// - /// This will be the type of repository created when - /// the repository is created. If multiple assemblies reference the - /// same repository then the repository is only created once using the - /// of the first assembly to call into the - /// repository. - /// - /// - public Type RepositoryType - { - get { return m_repositoryType; } - set { m_repositoryType = value ; } - } - - #endregion Public Instance Properties - - #region Private Instance Fields - - private string m_name = null; - private Type m_repositoryType = null; - - #endregion Private Instance Fields - } + /// + /// Gets or sets the type of repository to create for this assembly. + /// + /// + /// The type of repository to create for this assembly. + /// + /// + /// + /// The type of the repository to create for the assembly. + /// The type must implement the + /// interface. + /// + /// + /// This will be the type of repository created when + /// the repository is created. If multiple assemblies reference the + /// same repository then the repository is only created once using the + /// of the first assembly to call into the + /// repository. + /// + /// + public Type RepositoryType + { + get { return this.m_repositoryType; } + set { this.m_repositoryType = value; } + } + + private string m_name = null; + private Type m_repositoryType = null; + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs index 4c3c05446c7..33e2fb30e56 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,137 +18,118 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF using System; using System.Reflection; - -using log4net.Util; -using log4net.Repository; + using log4net.Core; +using log4net.Repository; +using log4net.Util; namespace log4net.Config { - /// - /// Assembly level attribute to configure the . - /// - /// - /// - /// This attribute may only be used at the assembly scope and can only - /// be used once per assembly. - /// - /// - /// Use this attribute to configure the - /// without calling one of the - /// methods. - /// - /// - /// Nicko Cadell - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - public sealed class SecurityContextProviderAttribute : ConfiguratorAttribute - { - #region Constructor - - /// - /// Construct provider attribute with type specified - /// - /// the type of the provider to use - /// - /// - /// The provider specified must subclass the - /// class. - /// - /// - public SecurityContextProviderAttribute(Type providerType) : base(100) /* configurator priority 100 to execute before the XmlConfigurator */ - { - m_providerType = providerType; - } - - #endregion - - #region Public Instance Properties - - /// - /// Gets or sets the type of the provider to use. - /// - /// - /// the type of the provider to use. - /// - /// - /// - /// The provider specified must subclass the - /// class. - /// - /// - public Type ProviderType - { - get { return m_providerType; } - set { m_providerType = value; } - } - - #endregion Public Instance Properties - - #region Override ConfiguratorAttribute - - /// - /// Configures the SecurityContextProvider - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - /// - /// - /// Creates a provider instance from the specified. - /// Sets this as the default security context provider . - /// - /// - override public void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) - { - if (m_providerType == null) - { - LogLog.Error(declaringType, "Attribute specified on assembly ["+sourceAssembly.FullName+"] with null ProviderType."); - } - else - { - LogLog.Debug(declaringType, "Creating provider of type ["+ m_providerType.FullName +"]"); - - SecurityContextProvider provider = Activator.CreateInstance(m_providerType) as SecurityContextProvider; - - if (provider == null) - { - LogLog.Error(declaringType, "Failed to create SecurityContextProvider instance of type ["+m_providerType.Name+"]."); - } - else - { - SecurityContextProvider.DefaultProvider = provider; - } - } - } - - #endregion - - #region Private Instance Fields - - private Type m_providerType = null; - - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the SecurityContextProviderAttribute class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(SecurityContextProviderAttribute); - - #endregion Private Static Fields - } + /// + /// Assembly level attribute to configure the . + /// + /// + /// + /// This attribute may only be used at the assembly scope and can only + /// be used once per assembly. + /// + /// + /// Use this attribute to configure the + /// without calling one of the + /// methods. + /// + /// + /// Nicko Cadell. + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + public sealed class SecurityContextProviderAttribute : ConfiguratorAttribute + { + /// + /// Initializes a new instance of the class. + /// Construct provider attribute with type specified. + /// + /// the type of the provider to use. + /// + /// + /// The provider specified must subclass the + /// class. + /// + /// + public SecurityContextProviderAttribute(Type providerType) + : base(100) /* configurator priority 100 to execute before the XmlConfigurator */ + { + this.m_providerType = providerType; + } + + /// + /// Gets or sets the type of the provider to use. + /// + /// + /// the type of the provider to use. + /// + /// + /// + /// The provider specified must subclass the + /// class. + /// + /// + public Type ProviderType + { + get { return this.m_providerType; } + set { this.m_providerType = value; } + } + + /// + /// Configures the SecurityContextProvider. + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + /// + /// + /// Creates a provider instance from the specified. + /// Sets this as the default security context provider . + /// + /// + public override void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) + { + if (this.m_providerType == null) + { + LogLog.Error(declaringType, "Attribute specified on assembly [" + sourceAssembly.FullName + "] with null ProviderType."); + } + else + { + LogLog.Debug(declaringType, "Creating provider of type [" + this.m_providerType.FullName + "]"); + + SecurityContextProvider provider = Activator.CreateInstance(this.m_providerType) as SecurityContextProvider; + + if (provider == null) + { + LogLog.Error(declaringType, "Failed to create SecurityContextProvider instance of type [" + this.m_providerType.Name + "]."); + } + else + { + SecurityContextProvider.DefaultProvider = provider; + } + } + } + + private Type m_providerType = null; + + /// + /// The fully qualified type of the SecurityContextProviderAttribute class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(SecurityContextProviderAttribute); + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs index ed6a04ee799..5c9dc3015ce 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs @@ -1,65 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Xml; -using System.Collections; -using System.IO; -using System.Reflection; -using System.Threading; -using System.Net; - -using log4net.Appender; -using log4net.Util; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Config { - /// - /// Use this class to initialize the log4net environment using an Xml tree. - /// - /// - /// - /// Configures a using an Xml tree. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class XmlConfigurator - { - #region Private Instance Constructors - - /// - /// Private constructor - /// - private XmlConfigurator() - { - } - - #endregion Protected Instance Constructors - - #region Configure static methods - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + using System.Net; + using System.Reflection; + using System.Threading; + using System.Xml; + + using log4net.Appender; + using log4net.Repository; + using log4net.Util; + + /// + /// Use this class to initialize the log4net environment using an Xml tree. + /// + /// + /// + /// Configures a using an Xml tree. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class XmlConfigurator + { + /// + /// Initializes a new instance of the class. + /// Private constructor. + /// + private XmlConfigurator() + { + } + #if !NETCF /// /// Automatically configures the using settings @@ -74,13 +66,14 @@ private XmlConfigurator() /// log4net that contains the configuration data. /// /// - /// To use this method to configure log4net you must specify + /// To use this method to configure log4net you must specify /// the section /// handler for the log4net configuration section. See the /// for an example. /// /// - /// The repository to configure. + /// The repository to configure. + /// #else /// /// Automatically configures the using settings @@ -97,7 +90,7 @@ private XmlConfigurator() /// /// The repository to configure. #endif - static public ICollection Configure(ILoggerRepository repository) + public static ICollection Configure(ILoggerRepository repository) { ArrayList configurationMessages = new ArrayList(); @@ -111,82 +104,83 @@ static public ICollection Configure(ILoggerRepository repository) return configurationMessages; } - static private void InternalConfigure(ILoggerRepository repository) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section"); + private static void InternalConfigure(ILoggerRepository repository) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section"); - try - { - LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]"); - } - catch - { - // ignore error - LogLog.Debug(declaringType, "Application config file location unknown"); - } + try + { + LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]"); + } + catch + { + // ignore error + LogLog.Debug(declaringType, "Application config file location unknown"); + } #if NETCF || NETSTANDARD1_3 // No config file reading stuff. Just go straight for the file Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation)); #else - try - { - XmlElement configElement = null; + try + { + XmlElement configElement = null; #if NET_2_0 - configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement; + configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement; #else configElement = System.Configuration.ConfigurationSettings.GetConfig("log4net") as XmlElement; #endif - if (configElement == null) - { - // Failed to load the xml config using configuration settings handler - LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the and elements. The configuration section should look like:
"); - } - else - { - // Configure using the xml loaded from the config file - InternalConfigureFromXml(repository, configElement); - } - } - catch(System.Configuration.ConfigurationException confEx) - { - if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0) - { - // Looks like the XML file is not valid - LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx); - } - else - { - // This exception is typically due to the assembly name not being correctly specified in the section type. - string configSectionStr = "
"; - LogLog.Error(declaringType, "Failed to parse config file. Is the specified as: " + configSectionStr, confEx); - } - } + if (configElement == null) + { + // Failed to load the xml config using configuration settings handler + LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the and elements. The configuration section should look like:
"); + } + else + { + // Configure using the xml loaded from the config file + InternalConfigureFromXml(repository, configElement); + } + } + catch (System.Configuration.ConfigurationException confEx) + { + if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0) + { + // Looks like the XML file is not valid + LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx); + } + else + { + // This exception is typically due to the assembly name not being correctly specified in the section type. + string configSectionStr = "
"; + LogLog.Error(declaringType, "Failed to parse config file. Is the specified as: " + configSectionStr, confEx); + } + } #endif - } - + } + #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). #if !NETCF - /// - /// Automatically configures the log4net system based on the - /// application's configuration settings. - /// - /// - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - /// - /// To use this method to configure log4net you must specify - /// the section - /// handler for the log4net configuration section. See the - /// for an example. - /// - /// - /// + /// + /// Automatically configures the log4net system based on the + /// application's configuration settings. + /// + /// + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + /// + /// To use this method to configure log4net you must specify + /// the section + /// handler for the log4net configuration section. See the + /// for an example. + /// + /// + /// + /// #else /// /// Automatically configures the log4net system based on the @@ -202,23 +196,24 @@ static private void InternalConfigure(ILoggerRepository repository) /// /// #endif - static public ICollection Configure() + public static ICollection Configure() { return Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); } - /// - /// Configures log4net using a log4net element - /// - /// - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// - /// The element to parse. - static public ICollection Configure(XmlElement element) - { + /// + /// Configures log4net using a log4net element. + /// + /// + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// + /// The element to parse. + /// + public static ICollection Configure(XmlElement element) + { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); @@ -231,59 +226,60 @@ static public ICollection Configure(XmlElement element) repository.ConfigurationMessages = configurationMessages; return configurationMessages; - } - + } + #if !NETCF - /// - /// Configures log4net using the specified configuration file. - /// - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// The log4net configuration file can possible be specified in the application's - /// configuration file (either MyAppName.exe.config for a - /// normal application on Web.config for an ASP.NET application). - /// - /// - /// The first element matching <configuration> will be read as the - /// configuration. If this file is also a .NET .config file then you must specify - /// a configuration section for the log4net element otherwise .NET will - /// complain. Set the type for the section handler to , for example: - /// - /// - ///
- /// - /// - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// + /// Configures log4net using the specified configuration file. + /// + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// The log4net configuration file can possible be specified in the application's + /// configuration file (either MyAppName.exe.config for a + /// normal application on Web.config for an ASP.NET application). + /// + /// + /// The first element matching <configuration> will be read as the + /// configuration. If this file is also a .NET .config file then you must specify + /// a configuration section for the log4net element otherwise .NET will + /// complain. Set the type for the section handler to , for example: + /// + /// + ///
+ /// + /// + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// #else /// /// Configures log4net using the specified configuration file. @@ -320,8 +316,8 @@ static public ICollection Configure(XmlElement element) /// /// #endif - static public ICollection Configure(FileInfo configFile) - { + public static ICollection Configure(FileInfo configFile) + { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) @@ -330,24 +326,25 @@ static public ICollection Configure(FileInfo configFile) } return configurationMessages; - } + } - /// - /// Configures log4net using the specified configuration URI. - /// - /// A URI to load the XML configuration from. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// The must support the URI scheme specified. - /// - /// - static public ICollection Configure(Uri configUri) - { + /// + /// Configures log4net using the specified configuration URI. + /// + /// A URI to load the XML configuration from. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// The must support the URI scheme specified. + /// + /// + /// + public static ICollection Configure(Uri configUri) + { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); @@ -359,24 +356,25 @@ static public ICollection Configure(Uri configUri) repository.ConfigurationMessages = configurationMessages; return configurationMessages; - } + } - /// - /// Configures log4net using the specified configuration data stream. - /// - /// A stream to load the XML configuration from. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// Note that this method will NOT close the stream parameter. - /// - /// - static public ICollection Configure(Stream configStream) - { + /// + /// Configures log4net using the specified configuration data stream. + /// + /// A stream to load the XML configuration from. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// Note that this method will NOT close the stream parameter. + /// + /// + /// + public static ICollection Configure(Stream configStream) + { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); @@ -388,11 +386,11 @@ static public ICollection Configure(Stream configStream) repository.ConfigurationMessages = configurationMessages; return configurationMessages; - } + } #endif // !NETSTANDARD1_3 /// - /// Configures the using the specified XML + /// Configures the using the specified XML /// element. /// /// @@ -400,8 +398,9 @@ static public ICollection Configure(Stream configStream) /// supplied as . /// /// The repository to configure. - /// The element to parse. - static public ICollection Configure(ILoggerRepository repository, XmlElement element) + /// The element to parse. + /// + public static ICollection Configure(ILoggerRepository repository, XmlElement element) { ArrayList configurationMessages = new ArrayList(); @@ -415,11 +414,11 @@ static public ICollection Configure(ILoggerRepository repository, XmlElement ele repository.ConfigurationMessages = configurationMessages; return configurationMessages; - } - + } + #if !NETCF /// - /// Configures the using the specified configuration + /// Configures the using the specified configuration /// file. /// /// The repository to configure. @@ -436,27 +435,27 @@ static public ICollection Configure(ILoggerRepository repository, XmlElement ele /// normal application on Web.config for an ASP.NET application). /// /// - /// The first element matching <configuration> will be read as the - /// configuration. If this file is also a .NET .config file then you must specify - /// a configuration section for the log4net element otherwise .NET will + /// The first element matching <configuration> will be read as the + /// configuration. If this file is also a .NET .config file then you must specify + /// a configuration section for the log4net element otherwise .NET will /// complain. Set the type for the section handler to , for example: /// /// - ///
- /// + ///
+ /// /// /// /// - /// The following example configures log4net using a configuration file, of which the + /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// /// /// using log4net.Config; /// using System.IO; /// using System.Configuration; - /// + /// /// ... - /// + /// /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// /// @@ -464,12 +463,13 @@ static public ICollection Configure(ILoggerRepository repository, XmlElement ele /// /// /// - /// - /// - /// - /// + /// + /// + /// + /// /// - /// + /// + /// #else /// /// Configures the using the specified configuration @@ -508,7 +508,7 @@ static public ICollection Configure(ILoggerRepository repository, XmlElement ele /// /// #endif - static public ICollection Configure(ILoggerRepository repository, FileInfo configFile) + public static ICollection Configure(ILoggerRepository repository, FileInfo configFile) { ArrayList configurationMessages = new ArrayList(); @@ -521,68 +521,69 @@ static public ICollection Configure(ILoggerRepository repository, FileInfo confi return configurationMessages; } - - static private void InternalConfigure(ILoggerRepository repository, FileInfo configFile) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]"); - - if (configFile == null) - { - LogLog.Error(declaringType, "Configure called with null 'configFile' parameter"); - } - else - { - // Have to use File.Exists() rather than configFile.Exists() - // because configFile.Exists() caches the value, not what we want. - if (File.Exists(configFile.FullName)) - { - // Open the file for reading - FileStream fs = null; - - // Try hard to open the file - for(int retry = 5; --retry >= 0; ) - { - try - { - fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read); - break; - } - catch(IOException ex) - { - if (retry == 0) - { - LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex); - - // The stream cannot be valid - fs = null; - } - System.Threading.Thread.Sleep(250); - } - } - - if (fs != null) - { - try - { - // Load the configuration from the stream - InternalConfigure(repository, fs); - } - finally - { - // Force the file closed whatever happens - fs.Close(); - } - } - } - else - { - LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged."); - } - } - } + + private static void InternalConfigure(ILoggerRepository repository, FileInfo configFile) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]"); + + if (configFile == null) + { + LogLog.Error(declaringType, "Configure called with null 'configFile' parameter"); + } + else + { + // Have to use File.Exists() rather than configFile.Exists() + // because configFile.Exists() caches the value, not what we want. + if (File.Exists(configFile.FullName)) + { + // Open the file for reading + FileStream fs = null; + + // Try hard to open the file + for (int retry = 5; --retry >= 0;) + { + try + { + fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read); + break; + } + catch (IOException ex) + { + if (retry == 0) + { + LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex); + + // The stream cannot be valid + fs = null; + } + + System.Threading.Thread.Sleep(250); + } + } + + if (fs != null) + { + try + { + // Load the configuration from the stream + InternalConfigure(repository, fs); + } + finally + { + // Force the file closed whatever happens + fs.Close(); + } + } + } + else + { + LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged."); + } + } + } /// - /// Configures the using the specified configuration + /// Configures the using the specified configuration /// URI. /// /// The repository to configure. @@ -596,8 +597,9 @@ static private void InternalConfigure(ILoggerRepository repository, FileInfo con /// /// The must support the URI scheme specified. /// - /// - static public ICollection Configure(ILoggerRepository repository, Uri configUri) + /// + /// + public static ICollection Configure(ILoggerRepository repository, Uri configUri) { ArrayList configurationMessages = new ArrayList(); @@ -610,83 +612,83 @@ static public ICollection Configure(ILoggerRepository repository, Uri configUri) return configurationMessages; } - - static private void InternalConfigure(ILoggerRepository repository, Uri configUri) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI ["+configUri+"]"); - - if (configUri == null) - { - LogLog.Error(declaringType, "Configure called with null 'configUri' parameter"); - } - else - { - if (configUri.IsFile) - { - // If URI is local file then call Configure with FileInfo - InternalConfigure(repository, new FileInfo(configUri.LocalPath)); - } - else - { - // NETCF dose not support WebClient - WebRequest configRequest = null; - - try - { - configRequest = WebRequest.Create(configUri); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to create WebRequest for URI ["+configUri+"]", ex); - } - - if (configRequest != null) - { + + private static void InternalConfigure(ILoggerRepository repository, Uri configUri) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI [" + configUri + "]"); + + if (configUri == null) + { + LogLog.Error(declaringType, "Configure called with null 'configUri' parameter"); + } + else + { + if (configUri.IsFile) + { + // If URI is local file then call Configure with FileInfo + InternalConfigure(repository, new FileInfo(configUri.LocalPath)); + } + else + { + // NETCF dose not support WebClient + WebRequest configRequest = null; + + try + { + configRequest = WebRequest.Create(configUri); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to create WebRequest for URI [" + configUri + "]", ex); + } + + if (configRequest != null) + { #if !NETCF_1_0 - // authentication may be required, set client to use default credentials - try - { - configRequest.Credentials = CredentialCache.DefaultCredentials; - } - catch - { - // ignore security exception - } + // authentication may be required, set client to use default credentials + try + { + configRequest.Credentials = CredentialCache.DefaultCredentials; + } + catch + { + // ignore security exception + } #endif - try - { + try + { #if NETSTANDARD1_3 WebResponse response = configRequest.GetResponseAsync().GetAwaiter().GetResult(); #else - WebResponse response = configRequest.GetResponse(); + WebResponse response = configRequest.GetResponse(); #endif - if (response != null) - { - try - { - // Open stream on config URI - using(Stream configStream = response.GetResponseStream()) - { - InternalConfigure(repository, configStream); - } - } - finally - { - response.Close(); - } - } - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to request config from URI ["+configUri+"]", ex); - } - } - } - } - } + if (response != null) + { + try + { + // Open stream on config URI + using (Stream configStream = response.GetResponseStream()) + { + InternalConfigure(repository, configStream); + } + } + finally + { + response.Close(); + } + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to request config from URI [" + configUri + "]", ex); + } + } + } + } + } /// - /// Configures the using the specified configuration + /// Configures the using the specified configuration /// file. /// /// The repository to configure. @@ -700,8 +702,9 @@ static private void InternalConfigure(ILoggerRepository repository, Uri configUr /// /// Note that this method will NOT close the stream parameter. /// - /// - static public ICollection Configure(ILoggerRepository repository, Stream configStream) + /// + /// + public static ICollection Configure(ILoggerRepository repository, Stream configStream) { ArrayList configurationMessages = new ArrayList(); @@ -714,27 +717,28 @@ static public ICollection Configure(ILoggerRepository repository, Stream configS return configurationMessages; } - - static private void InternalConfigure(ILoggerRepository repository, Stream configStream) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream"); - - if (configStream == null) - { - LogLog.Error(declaringType, "Configure called with null 'configStream' parameter"); - } - else - { - // Load the config file into a document - XmlDocument doc = new XmlDocument() { XmlResolver = null }; - try - { -#if (NETCF) + + private static void InternalConfigure(ILoggerRepository repository, Stream configStream) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream"); + + if (configStream == null) + { + LogLog.Error(declaringType, "Configure called with null 'configStream' parameter"); + } + else + { + // Load the config file into a document + XmlDocument doc = new XmlDocument() { XmlResolver = null }; + try + { +#if NETCF // Create a text reader for the file stream XmlTextReader xmlReader = new XmlTextReader(configStream); #elif NET_2_0 || NETSTANDARD1_3 - // Allow the DTD to specify entity includes - XmlReaderSettings settings = new XmlReaderSettings(); + // Allow the DTD to specify entity includes + XmlReaderSettings settings = new XmlReaderSettings(); + // .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd' // is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.' #if NETSTANDARD1_3 // TODO DtdProcessing.Parse not yet available (https://github.com/dotnet/corefx/issues/4376) @@ -743,11 +747,11 @@ static private void InternalConfigure(ILoggerRepository repository, Stream confi settings.ProhibitDtd = true; #else settings.XmlResolver = null; - settings.DtdProcessing = DtdProcessing.Prohibit; + settings.DtdProcessing = DtdProcessing.Prohibit; #endif - // Create a reader over the input stream - XmlReader xmlReader = XmlReader.Create(configStream, settings); + // Create a reader over the input stream + XmlReader xmlReader = XmlReader.Create(configStream, settings); #else // Create a validating reader around a text reader for the file stream XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream)); @@ -757,69 +761,66 @@ static private void InternalConfigure(ILoggerRepository repository, Stream confi xmlReader.ValidationType = ValidationType.None; xmlReader.EntityHandling = EntityHandling.ExpandEntities; #endif - - // load the data into the document - doc.Load(xmlReader); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Error while loading XML configuration", ex); - - // The document is invalid - doc = null; - } - - if (doc != null) - { - LogLog.Debug(declaringType, "loading XML configuration"); - - // Configure using the 'log4net' element - XmlNodeList configNodeList = doc.GetElementsByTagName("log4net"); - if (configNodeList.Count == 0) - { - LogLog.Debug(declaringType, "XML configuration does not contain a element. Configuration Aborted."); - } - else if (configNodeList.Count > 1) - { - LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] elements. Only one is allowed. Configuration Aborted."); - } - else - { - InternalConfigureFromXml(repository, configNodeList[0] as XmlElement); - } - } - } - } - - #endregion Configure static methods - - #region ConfigureAndWatch static methods - -#if (!NETCF && !SSCLI) + + // load the data into the document + doc.Load(xmlReader); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error while loading XML configuration", ex); + + // The document is invalid + doc = null; + } + + if (doc != null) + { + LogLog.Debug(declaringType, "loading XML configuration"); + + // Configure using the 'log4net' element + XmlNodeList configNodeList = doc.GetElementsByTagName("log4net"); + if (configNodeList.Count == 0) + { + LogLog.Debug(declaringType, "XML configuration does not contain a element. Configuration Aborted."); + } + else if (configNodeList.Count > 1) + { + LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] elements. Only one is allowed. Configuration Aborted."); + } + else + { + InternalConfigureFromXml(repository, configNodeList[0] as XmlElement); + } + } + } + } + +#if !NETCF && !SSCLI #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - /// - /// Configures log4net using the file specified, monitors the file for changes - /// and reloads the configuration if a change is detected. - /// - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The configuration file will be monitored using a - /// and depends on the behavior of that class. - /// - /// - /// For more information on how to configure log4net using - /// a separate configuration file, see . - /// - /// - /// - static public ICollection ConfigureAndWatch(FileInfo configFile) - { + /// + /// Configures log4net using the file specified, monitors the file for changes + /// and reloads the configuration if a change is detected. + /// + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The configuration file will be monitored using a + /// and depends on the behavior of that class. + /// + /// + /// For more information on how to configure log4net using + /// a separate configuration file, see . + /// + /// + /// + /// + public static ICollection ConfigureAndWatch(FileInfo configFile) + { ArrayList configurationMessages = new ArrayList(); ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); @@ -832,12 +833,12 @@ static public ICollection ConfigureAndWatch(FileInfo configFile) repository.ConfigurationMessages = configurationMessages; return configurationMessages; - } + } #endif // !NETSTANDARD1_3 /// - /// Configures the using the file specified, - /// monitors the file for changes and reloads the configuration if a change + /// Configures the using the file specified, + /// monitors the file for changes and reloads the configuration if a change /// is detected. /// /// The repository to configure. @@ -857,8 +858,9 @@ static public ICollection ConfigureAndWatch(FileInfo configFile) /// a separate configuration file, see . /// /// - /// - static public ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) + /// + /// + public static ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) { ArrayList configurationMessages = new ArrayList(); @@ -871,186 +873,182 @@ static public ICollection ConfigureAndWatch(ILoggerRepository repository, FileIn return configurationMessages; } - - static private void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates"); - - if (configFile == null) - { - LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter"); - } - else - { - // Configure log4net now - InternalConfigure(repository, configFile); - - try - { + + private static void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates"); + + if (configFile == null) + { + LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter"); + } + else + { + // Configure log4net now + InternalConfigure(repository, configFile); + + try + { lock (m_repositoryName2ConfigAndWatchHandler) { // support multiple repositories each having their own watcher ConfigureAndWatchHandler handler = - (ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[configFile.FullName]; + (ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[configFile.FullName]; if (handler != null) { - m_repositoryName2ConfigAndWatchHandler.Remove(configFile.FullName); + m_repositoryName2ConfigAndWatchHandler.Remove(configFile.FullName); handler.Dispose(); } // Create and start a watch handler that will reload the // configuration whenever the config file is modified. handler = new ConfigureAndWatchHandler(repository, configFile); - m_repositoryName2ConfigAndWatchHandler[configFile.FullName] = handler; + m_repositoryName2ConfigAndWatchHandler[configFile.FullName] = handler; } - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file ["+configFile.FullName+"]", ex); - } - } - } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file [" + configFile.FullName + "]", ex); + } + } + } #endif + +#if !NETCF && !SSCLI + /// + /// Class used to watch config files. + /// + /// + /// + /// Uses the to monitor + /// changes to a specified file. Because multiple change notifications + /// may be raised when the file is modified, a timer is used to + /// compress the notifications into a single event. The timer + /// waits for time before delivering + /// the event notification. If any further + /// change notifications arrive while the timer is waiting it + /// is reset and waits again for to + /// elapse. + /// + /// + private sealed class ConfigureAndWatchHandler : IDisposable + { + /// + /// Holds the FileInfo used to configure the XmlConfigurator. + /// + private FileInfo m_configFile; - #endregion ConfigureAndWatch static methods + /// + /// Holds the repository being configured. + /// + private ILoggerRepository m_repository; - #region ConfigureAndWatchHandler + /// + /// The timer used to compress the notification events. + /// + private Timer m_timer; -#if (!NETCF && !SSCLI) - /// - /// Class used to watch config files. - /// - /// - /// - /// Uses the to monitor - /// changes to a specified file. Because multiple change notifications - /// may be raised when the file is modified, a timer is used to - /// compress the notifications into a single event. The timer - /// waits for time before delivering - /// the event notification. If any further - /// change notifications arrive while the timer is waiting it - /// is reset and waits again for to - /// elapse. - /// - /// - private sealed class ConfigureAndWatchHandler : IDisposable - { - /// - /// Holds the FileInfo used to configure the XmlConfigurator - /// - private FileInfo m_configFile; - - /// - /// Holds the repository being configured. - /// - private ILoggerRepository m_repository; - - /// - /// The timer used to compress the notification events. - /// - private Timer m_timer; - - /// - /// The default amount of time to wait after receiving notification - /// before reloading the config file. - /// - private const int TimeoutMillis = 500; + /// + /// The default amount of time to wait after receiving notification + /// before reloading the config file. + /// + private const int TimeoutMillis = 500; /// /// Watches file for changes. This object should be disposed when no longer /// needed to free system handles on the watched resources. /// - private FileSystemWatcher m_watcher; - - /// - /// Initializes a new instance of the class to + private FileSystemWatcher m_watcher; + + /// + /// Initializes a new instance of the class to /// watch a specified config file used to configure a repository. - /// - /// The repository to configure. - /// The configuration file to watch. - /// - /// - /// Initializes a new instance of the class. - /// - /// + /// + /// The repository to configure. + /// The configuration file to watch. + /// + /// + /// Initializes a new instance of the class. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #endif public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile) - { - m_repository = repository; - m_configFile = configFile; - - // Create a new FileSystemWatcher and set its properties. - m_watcher = new FileSystemWatcher(); - - m_watcher.Path = m_configFile.DirectoryName; - m_watcher.Filter = m_configFile.Name; - - // Set the notification filters - m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; - - // Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs - m_watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged); - m_watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged); - m_watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged); - m_watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed); - - // Begin watching. - m_watcher.EnableRaisingEvents = true; - - // Create the timer that will be used to deliver events. Set as disabled - m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite); - } - - /// - /// Event handler used by . - /// - /// The firing the event. - /// The argument indicates the file that caused the event to be fired. - /// - /// - /// This handler reloads the configuration from the file when the event is fired. - /// - /// - private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e) - { - LogLog.Debug(declaringType, "ConfigureAndWatchHandler: "+e.ChangeType+" [" + m_configFile.FullName + "]"); - - // Deliver the event in TimeoutMillis time - // timer will fire only once - m_timer.Change(TimeoutMillis, Timeout.Infinite); - } - - /// - /// Event handler used by . - /// - /// The firing the event. - /// The argument indicates the file that caused the event to be fired. - /// - /// - /// This handler reloads the configuration from the file when the event is fired. - /// - /// - private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e) - { - LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + m_configFile.FullName + "]"); - - // Deliver the event in TimeoutMillis time - // timer will fire only once - m_timer.Change(TimeoutMillis, Timeout.Infinite); - } - - /// - /// Called by the timer when the configuration has been updated. - /// - /// null - private void OnWatchedFileChange(object state) - { - XmlConfigurator.InternalConfigure(m_repository, m_configFile); - } + { + this.m_repository = repository; + this.m_configFile = configFile; + + // Create a new FileSystemWatcher and set its properties. + this.m_watcher = new FileSystemWatcher(); + + this.m_watcher.Path = this.m_configFile.DirectoryName; + this.m_watcher.Filter = this.m_configFile.Name; + + // Set the notification filters + this.m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; + + // Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs + this.m_watcher.Changed += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); + this.m_watcher.Created += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); + this.m_watcher.Deleted += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); + this.m_watcher.Renamed += new RenamedEventHandler(this.ConfigureAndWatchHandler_OnRenamed); + + // Begin watching. + this.m_watcher.EnableRaisingEvents = true; + + // Create the timer that will be used to deliver events. Set as disabled + this.m_timer = new Timer(new TimerCallback(this.OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite); + } + + /// + /// Event handler used by . + /// + /// The firing the event. + /// The argument indicates the file that caused the event to be fired. + /// + /// + /// This handler reloads the configuration from the file when the event is fired. + /// + /// + private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e) + { + LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + this.m_configFile.FullName + "]"); + + // Deliver the event in TimeoutMillis time + // timer will fire only once + this.m_timer.Change(TimeoutMillis, Timeout.Infinite); + } + + /// + /// Event handler used by . + /// + /// The firing the event. + /// The argument indicates the file that caused the event to be fired. + /// + /// + /// This handler reloads the configuration from the file when the event is fired. + /// + /// + private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e) + { + LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + this.m_configFile.FullName + "]"); + + // Deliver the event in TimeoutMillis time + // timer will fire only once + this.m_timer.Change(TimeoutMillis, Timeout.Infinite); + } + /// + /// Called by the timer when the configuration has been updated. + /// + /// null. + private void OnWatchedFileChange(object state) + { + XmlConfigurator.InternalConfigure(this.m_repository, this.m_configFile); + } + /// /// Release the handles held by the watcher and timer. /// @@ -1059,86 +1057,75 @@ private void OnWatchedFileChange(object state) #endif public void Dispose() { - m_watcher.EnableRaisingEvents = false; - m_watcher.Dispose(); - m_timer.Dispose(); + this.m_watcher.EnableRaisingEvents = false; + this.m_watcher.Dispose(); + this.m_timer.Dispose(); } - } + } #endif - - #endregion ConfigureAndWatchHandler - - #region Private Static Methods - - /// - /// Configures the specified repository using a log4net element. - /// - /// The hierarchy to configure. - /// The element to parse. - /// - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// - /// This method is ultimately called by one of the Configure methods - /// to load the configuration from an . - /// - /// - static private void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element) - { - if (element == null) - { - LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter"); - } - else if (repository == null) - { - LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter"); - } - else - { - LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]"); - - IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator; - if (configurableRepository == null) - { - LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator"); - } - else - { - // Copy the xml data into the root of a new document - // this isolates the xml config data from the rest of - // the document - XmlDocument newDoc = new XmlDocument() { XmlResolver = null }; + + /// + /// Configures the specified repository using a log4net element. + /// + /// The hierarchy to configure. + /// The element to parse. + /// + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// + /// This method is ultimately called by one of the Configure methods + /// to load the configuration from an . + /// + /// + private static void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element) + { + if (element == null) + { + LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter"); + } + else if (repository == null) + { + LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter"); + } + else + { + LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]"); + + IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator; + if (configurableRepository == null) + { + LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator"); + } + else + { + // Copy the xml data into the root of a new document + // this isolates the xml config data from the rest of + // the document + XmlDocument newDoc = new XmlDocument() { XmlResolver = null }; XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true)); - // Pass the configurator the config element - configurableRepository.Configure(newElement); - } - } - } - - #endregion Private Static Methods - - #region Private Static Fields - + // Pass the configurator the config element + configurableRepository.Configure(newElement); + } + } + } + /// /// Maps repository names to ConfigAndWatchHandler instances to allow a particular - /// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is + /// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is /// reconfigured. /// - private readonly static Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable(); - - /// - /// The fully qualified type of the XmlConfigurator class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(XmlConfigurator); - - #endregion Private Static Fields - } -} + private static readonly Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable(); + /// + /// The fully qualified type of the XmlConfigurator class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(XmlConfigurator); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs index 43783cfc0d1..c496e853690 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,189 +18,183 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF using System; using System.Collections; -using System.Reflection; using System.IO; - -using log4net.Util; +using System.Reflection; + using log4net.Repository; using log4net.Repository.Hierarchy; +using log4net.Util; namespace log4net.Config { - /// - /// Assembly level attribute to configure the . - /// - /// - /// - /// This attribute may only be used at the assembly scope and can only - /// be used once per assembly. - /// - /// - /// Use this attribute to configure the - /// without calling one of the - /// methods. - /// - /// - /// If neither of the or - /// properties are set the configuration is loaded from the application's .config file. - /// If set the property takes priority over the - /// property. The property - /// specifies a path to a file to load the config from. The path is relative to the - /// application's base directory; . - /// The property is used as a postfix to the assembly file name. - /// The config file must be located in the application's base directory; . - /// For example in a console application setting the to - /// config has the same effect as not specifying the or - /// properties. - /// - /// - /// The property can be set to cause the - /// to watch the configuration file for changes. - /// - /// - /// - /// Log4net will only look for assembly level configuration attributes once. - /// When using the log4net assembly level attributes to control the configuration - /// of log4net you must ensure that the first call to any of the - /// methods is made from the assembly with the configuration - /// attributes. - /// - /// - /// If you cannot guarantee the order in which log4net calls will be made from - /// different assemblies you must use programmatic configuration instead, i.e. - /// call the method directly. - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - public /*sealed*/ class XmlConfiguratorAttribute : ConfiguratorAttribute - { - // - // Class is not sealed because DOMConfiguratorAttribute extends it while it is obsoleted - // - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public XmlConfiguratorAttribute() : base(0) /* configurator priority 0 */ - { - } - - #region Public Instance Properties - - /// - /// Gets or sets the filename of the configuration file. - /// - /// - /// The filename of the configuration file. - /// - /// - /// - /// If specified, this is the name of the configuration file to use with - /// the . This file path is relative to the - /// application base directory (). - /// - /// - /// The takes priority over the . - /// - /// - public string ConfigFile - { - get { return m_configFile; } - set { m_configFile = value; } - } - - /// - /// Gets or sets the extension of the configuration file. - /// - /// - /// The extension of the configuration file. - /// - /// - /// - /// If specified this is the extension for the configuration file. - /// The path to the config file is built by using the application - /// base directory (), - /// the assembly file name and the config file extension. - /// - /// - /// If the is set to MyExt then - /// possible config file names would be: MyConsoleApp.exe.MyExt or - /// MyClassLibrary.dll.MyExt. - /// - /// - /// The takes priority over the . - /// - /// - public string ConfigFileExtension - { - get { return m_configFileExtension; } - set { m_configFileExtension = value; } - } - - /// - /// Gets or sets a value indicating whether to watch the configuration file. - /// - /// - /// true if the configuration should be watched, false otherwise. - /// - /// - /// - /// If this flag is specified and set to true then the framework - /// will watch the configuration file and will reload the config each time - /// the file is modified. - /// - /// - /// The config file can only be watched if it is loaded from local disk. - /// In a No-Touch (Smart Client) deployment where the application is downloaded - /// from a web server the config file may not reside on the local disk - /// and therefore it may not be able to watch it. - /// - /// - /// Watching configuration is not supported on the SSCLI. - /// - /// - public bool Watch - { - get { return m_configureAndWatch; } - set { m_configureAndWatch = value; } - } - - #endregion Public Instance Properties - - #region Override ConfiguratorAttribute - - /// - /// Configures the for the specified assembly. - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - /// - /// - /// Configure the repository using the . - /// The specified must extend the - /// class otherwise the will not be able to - /// configure it. - /// - /// + /// + /// Assembly level attribute to configure the . + /// + /// + /// + /// This attribute may only be used at the assembly scope and can only + /// be used once per assembly. + /// + /// + /// Use this attribute to configure the + /// without calling one of the + /// methods. + /// + /// + /// If neither of the or + /// properties are set the configuration is loaded from the application's .config file. + /// If set the property takes priority over the + /// property. The property + /// specifies a path to a file to load the config from. The path is relative to the + /// application's base directory; . + /// The property is used as a postfix to the assembly file name. + /// The config file must be located in the application's base directory; . + /// For example in a console application setting the to + /// config has the same effect as not specifying the or + /// properties. + /// + /// + /// The property can be set to cause the + /// to watch the configuration file for changes. + /// + /// + /// + /// Log4net will only look for assembly level configuration attributes once. + /// When using the log4net assembly level attributes to control the configuration + /// of log4net you must ensure that the first call to any of the + /// methods is made from the assembly with the configuration + /// attributes. + /// + /// + /// If you cannot guarantee the order in which log4net calls will be made from + /// different assemblies you must use programmatic configuration instead, i.e. + /// call the method directly. + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + public /*sealed*/ class XmlConfiguratorAttribute : ConfiguratorAttribute + { + // Class is not sealed because DOMConfiguratorAttribute extends it while it is obsoleted + // + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public XmlConfiguratorAttribute() + : base(0) /* configurator priority 0 */ + { + } + + /// + /// Gets or sets the filename of the configuration file. + /// + /// + /// The filename of the configuration file. + /// + /// + /// + /// If specified, this is the name of the configuration file to use with + /// the . This file path is relative to the + /// application base directory (). + /// + /// + /// The takes priority over the . + /// + /// + public string ConfigFile + { + get { return this.m_configFile; } + set { this.m_configFile = value; } + } + + /// + /// Gets or sets the extension of the configuration file. + /// + /// + /// The extension of the configuration file. + /// + /// + /// + /// If specified this is the extension for the configuration file. + /// The path to the config file is built by using the application + /// base directory (), + /// the assembly file name and the config file extension. + /// + /// + /// If the is set to MyExt then + /// possible config file names would be: MyConsoleApp.exe.MyExt or + /// MyClassLibrary.dll.MyExt. + /// + /// + /// The takes priority over the . + /// + /// + public string ConfigFileExtension + { + get { return this.m_configFileExtension; } + set { this.m_configFileExtension = value; } + } + + /// + /// Gets or sets a value indicating whether to watch the configuration file. + /// + /// + /// true if the configuration should be watched, false otherwise. + /// + /// + /// + /// If this flag is specified and set to true then the framework + /// will watch the configuration file and will reload the config each time + /// the file is modified. + /// + /// + /// The config file can only be watched if it is loaded from local disk. + /// In a No-Touch (Smart Client) deployment where the application is downloaded + /// from a web server the config file may not reside on the local disk + /// and therefore it may not be able to watch it. + /// + /// + /// Watching configuration is not supported on the SSCLI. + /// + /// + public bool Watch + { + get { return this.m_configureAndWatch; } + set { this.m_configureAndWatch = value; } + } + + /// + /// Configures the for the specified assembly. + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + /// + /// + /// Configure the repository using the . + /// The specified must extend the + /// class otherwise the will not be able to + /// configure it. + /// + /// /// The does not extend . - override public void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) - { + public override void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) + { IList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) @@ -217,257 +210,249 @@ override public void Configure(Assembly sourceAssembly, ILoggerRepository target // and the application does not have PathDiscovery permission } - if (applicationBaseDirectory == null || (new Uri(applicationBaseDirectory)).IsFile) + if (applicationBaseDirectory == null || new Uri(applicationBaseDirectory).IsFile) { - ConfigureFromFile(sourceAssembly, targetRepository); + this.ConfigureFromFile(sourceAssembly, targetRepository); } else { - ConfigureFromUri(sourceAssembly, targetRepository); + this.ConfigureFromUri(sourceAssembly, targetRepository); } } targetRepository.ConfigurationMessages = configurationMessages; - } - - #endregion - - /// - /// Attempt to load configuration from the local file system - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository) - { - // Work out the full path to the config file - string fullPath2ConfigFile = null; - - // Select the config file - if (m_configFile == null || m_configFile.Length == 0) - { - if (m_configFileExtension == null || m_configFileExtension.Length == 0) - { - // Use the default .config file for the AppDomain - try - { - fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation; - } - catch(Exception ex) - { - LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); - } - } - else - { - // Force the extension to start with a '.' - if (m_configFileExtension[0] != '.') - { - m_configFileExtension = "." + m_configFileExtension; - } - - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex); - } - - if (applicationBaseDirectory != null) - { - fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + m_configFileExtension); - } - } - } - else - { - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch(Exception ex) - { - LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute path.", ex); - } - - if (applicationBaseDirectory != null) - { - // Just the base dir + the config file - fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, m_configFile); - } - else - { - fullPath2ConfigFile = m_configFile; - } - } + } + + /// + /// Attempt to load configuration from the local file system. + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository) + { + // Work out the full path to the config file + string fullPath2ConfigFile = null; + + // Select the config file + if (this.m_configFile == null || this.m_configFile.Length == 0) + { + if (this.m_configFileExtension == null || this.m_configFileExtension.Length == 0) + { + // Use the default .config file for the AppDomain + try + { + fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation; + } + catch (Exception ex) + { + LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); + } + } + else + { + // Force the extension to start with a '.' + if (this.m_configFileExtension[0] != '.') + { + this.m_configFileExtension = "." + this.m_configFileExtension; + } + + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex); + } + + if (applicationBaseDirectory != null) + { + fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + this.m_configFileExtension); + } + } + } + else + { + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch (Exception ex) + { + LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path [" + this.m_configFile + "] will be treated as an absolute path.", ex); + } - if (fullPath2ConfigFile != null) - { - ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile)); - } - } + if (applicationBaseDirectory != null) + { + // Just the base dir + the config file + fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, this.m_configFile); + } + else + { + fullPath2ConfigFile = this.m_configFile; + } + } - /// - /// Configure the specified repository using a - /// - /// The repository to configure. - /// the FileInfo pointing to the config file - private void ConfigureFromFile(ILoggerRepository targetRepository, FileInfo configFile) - { -#if (SSCLI) + if (fullPath2ConfigFile != null) + { + this.ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile)); + } + } + + /// + /// Configure the specified repository using a . + /// + /// The repository to configure. + /// the FileInfo pointing to the config file. + private void ConfigureFromFile(ILoggerRepository targetRepository, FileInfo configFile) + { +#if SSCLI if (m_configureAndWatch) { LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file not supported on SSCLI"); } XmlConfigurator.Configure(targetRepository, configFile); #else - // Do we configure just once or do we configure and then watch? - if (m_configureAndWatch) - { - XmlConfigurator.ConfigureAndWatch(targetRepository, configFile); - } - else - { - XmlConfigurator.Configure(targetRepository, configFile); - } + // Do we configure just once or do we configure and then watch? + if (this.m_configureAndWatch) + { + XmlConfigurator.ConfigureAndWatch(targetRepository, configFile); + } + else + { + XmlConfigurator.Configure(targetRepository, configFile); + } #endif - } - - /// - /// Attempt to load configuration from a URI - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository) - { - // Work out the full path to the config file - Uri fullPath2ConfigFile = null; - - // Select the config file - if (m_configFile == null || m_configFile.Length == 0) - { - if (m_configFileExtension == null || m_configFileExtension.Length == 0) - { - string systemConfigFilePath = null; - try - { - systemConfigFilePath = SystemInfo.ConfigurationFileLocation; - } - catch(Exception ex) - { - LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); - } - - if (systemConfigFilePath != null) - { - Uri systemConfigFileUri = new Uri(systemConfigFilePath); - - // Use the default .config file for the AppDomain - fullPath2ConfigFile = systemConfigFileUri; - } - } - else - { - // Force the extension to start with a '.' - if (m_configFileExtension[0] != '.') - { - m_configFileExtension = "." + m_configFileExtension; - } - - string systemConfigFilePath = null; - try - { - systemConfigFilePath = SystemInfo.ConfigurationFileLocation; - } - catch(Exception ex) - { - LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex); - } - - if (systemConfigFilePath != null) - { - UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath)); - - // Remove the current extension from the systemConfigFileUri path - string path = builder.Path; - int startOfExtension = path.LastIndexOf("."); - if (startOfExtension >= 0) - { - path = path.Substring(0, startOfExtension); - } - path += m_configFileExtension; - - builder.Path = path; - fullPath2ConfigFile = builder.Uri; - } - } - } - else - { - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch(Exception ex) - { - LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute URI.", ex); - } - - if (applicationBaseDirectory != null) - { - // Just the base dir + the config file - fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), m_configFile); - } - else - { - fullPath2ConfigFile = new Uri(m_configFile); - } - } - - if (fullPath2ConfigFile != null) - { - if (fullPath2ConfigFile.IsFile) - { - // The m_configFile could be an absolute local path, therefore we have to be - // prepared to switch back to using FileInfos here - ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath)); - } - else - { - if (m_configureAndWatch) - { - LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI"); - } - XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile); - } - } - } - - #region Private Instance Fields - - private string m_configFile = null; - private string m_configFileExtension = null; - private bool m_configureAndWatch = false; - - #endregion Private Instance Fields - - #region Private Static Fields + } + + /// + /// Attempt to load configuration from a URI. + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository) + { + // Work out the full path to the config file + Uri fullPath2ConfigFile = null; + + // Select the config file + if (this.m_configFile == null || this.m_configFile.Length == 0) + { + if (this.m_configFileExtension == null || this.m_configFileExtension.Length == 0) + { + string systemConfigFilePath = null; + try + { + systemConfigFilePath = SystemInfo.ConfigurationFileLocation; + } + catch (Exception ex) + { + LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); + } + + if (systemConfigFilePath != null) + { + Uri systemConfigFileUri = new Uri(systemConfigFilePath); + + // Use the default .config file for the AppDomain + fullPath2ConfigFile = systemConfigFileUri; + } + } + else + { + // Force the extension to start with a '.' + if (this.m_configFileExtension[0] != '.') + { + this.m_configFileExtension = "." + this.m_configFileExtension; + } + + string systemConfigFilePath = null; + try + { + systemConfigFilePath = SystemInfo.ConfigurationFileLocation; + } + catch (Exception ex) + { + LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex); + } + + if (systemConfigFilePath != null) + { + UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath)); + + // Remove the current extension from the systemConfigFileUri path + string path = builder.Path; + int startOfExtension = path.LastIndexOf("."); + if (startOfExtension >= 0) + { + path = path.Substring(0, startOfExtension); + } + + path += this.m_configFileExtension; + + builder.Path = path; + fullPath2ConfigFile = builder.Uri; + } + } + } + else + { + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch (Exception ex) + { + LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path [" + this.m_configFile + "] will be treated as an absolute URI.", ex); + } - /// - /// The fully qualified type of the XmlConfiguratorAttribute class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(XmlConfiguratorAttribute); + if (applicationBaseDirectory != null) + { + // Just the base dir + the config file + fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), this.m_configFile); + } + else + { + fullPath2ConfigFile = new Uri(this.m_configFile); + } + } - #endregion Private Static Fields - } + if (fullPath2ConfigFile != null) + { + if (fullPath2ConfigFile.IsFile) + { + // The m_configFile could be an absolute local path, therefore we have to be + // prepared to switch back to using FileInfos here + this.ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath)); + } + else + { + if (this.m_configureAndWatch) + { + LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI"); + } + + XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile); + } + } + } + + private string m_configFile = null; + private string m_configFileExtension = null; + private bool m_configureAndWatch = false; + + /// + /// The fully qualified type of the XmlConfiguratorAttribute class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(XmlConfiguratorAttribute); + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs index abfeccd7df6..38080144f88 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs @@ -1,361 +1,343 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Reflection; - -using log4net.Appender; -using log4net.Util; -using log4net.Repository; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// The implementation of the interface suitable - /// for use with the compact framework - /// - /// - /// - /// This implementation is a simple - /// mapping between repository name and - /// object. - /// - /// - /// The .NET Compact Framework 1.0 does not support retrieving assembly - /// level attributes therefore unlike the DefaultRepositorySelector - /// this selector does not examine the calling assembly for attributes. - /// - /// - /// Nicko Cadell - public class CompactRepositorySelector : IRepositorySelector - { - #region Member Variables - - private const string DefaultRepositoryName = "log4net-default-repository"; - - private readonly Hashtable m_name2repositoryMap = new Hashtable(); - private readonly Type m_defaultRepositoryType; - - private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; - - #endregion - - #region Constructors - - /// - /// Create a new repository selector - /// - /// the type of the repositories to create, must implement - /// - /// - /// Create an new compact repository selector. - /// The default type for repositories must be specified, - /// an appropriate value would be . - /// - /// - /// throw if is null - /// throw if does not implement - public CompactRepositorySelector(Type defaultRepositoryType) - { - if (defaultRepositoryType == null) - { - throw new ArgumentNullException("defaultRepositoryType"); - } - - // Check that the type is a repository - if (! (typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) ) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", (object)defaultRepositoryType, "Parameter: defaultRepositoryType, Value: ["+defaultRepositoryType+"] out of range. Argument must implement the ILoggerRepository interface"); - } - - m_defaultRepositoryType = defaultRepositoryType; - - LogLog.Debug(declaringType, "defaultRepositoryType ["+m_defaultRepositoryType+"]"); - } - - #endregion - - #region Implementation of IRepositorySelector - - /// - /// Get the for the specified assembly - /// - /// not used - /// The default - /// - /// - /// The argument is not used. This selector does not create a - /// separate repository for each assembly. - /// - /// - /// As a named repository is not specified the default repository is - /// returned. The default repository is named log4net-default-repository. - /// - /// - public ILoggerRepository GetRepository(Assembly assembly) - { - return CreateRepository(assembly, m_defaultRepositoryType); - } - - /// - /// Get the named - /// - /// the name of the repository to lookup - /// The named - /// - /// - /// Get the named . The default - /// repository is log4net-default-repository. Other repositories - /// must be created using the . - /// If the named repository does not exist an exception is thrown. - /// - /// - /// throw if is null - /// throw if the does not exist - public ILoggerRepository GetRepository(string repositoryName) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - lock(this) - { - // Lookup in map - ILoggerRepository rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep == null) - { - throw new LogException("Repository ["+repositoryName+"] is NOT defined."); - } - return rep; - } - } - - /// - /// Create a new repository for the assembly specified - /// - /// not used - /// the type of repository to create, must implement - /// the repository created - /// - /// - /// The argument is not used. This selector does not create a - /// separate repository for each assembly. - /// - /// - /// If the is null then the - /// default repository type specified to the constructor is used. - /// - /// - /// As a named repository is not specified the default repository is - /// returned. The default repository is named log4net-default-repository. - /// - /// - public ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType) - { - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = m_defaultRepositoryType; - } - - lock(this) - { - // This method should not throw if the default repository already exists. - - // First check that the repository does not exist - ILoggerRepository rep = m_name2repositoryMap[DefaultRepositoryName] as ILoggerRepository; - if (rep == null) - { - // Must create the repository - rep = CreateRepository(DefaultRepositoryName, repositoryType); - } - - return rep; - } - } - - /// - /// Create a new repository for the repository specified - /// - /// the repository to associate with the - /// the type of repository to create, must implement . - /// If this param is null then the default repository type is used. - /// the repository created - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same repository specified will return the same repository instance. - /// - /// - /// If the named repository already exists an exception will be thrown. - /// - /// - /// If is null then the default - /// repository type specified to the constructor is used. - /// - /// - /// throw if is null - /// throw if the already exists - public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = m_defaultRepositoryType; - } - - lock(this) - { - ILoggerRepository rep = null; - - // First check that the repository does not exist - rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep != null) - { - throw new LogException("Repository ["+repositoryName+"] is already defined. Repositories cannot be redefined."); - } - else - { - LogLog.Debug(declaringType, "Creating repository ["+repositoryName+"] using type ["+repositoryType+"]"); - - // Call the no arg constructor for the repositoryType - rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); - - // Set the name of the repository - rep.Name = repositoryName; - - // Store in map - m_name2repositoryMap[repositoryName] = rep; - - // Notify listeners that the repository has been created - OnLoggerRepositoryCreatedEvent(rep); - } - - return rep; - } - } - - /// - /// Test if a named repository exists - /// - /// the named repository to check - /// true if the repository exists - /// - /// - /// Test if a named repository exists. Use - /// to create a new repository and to retrieve - /// a repository. - /// - /// - public bool ExistsRepository(string repositoryName) - { - lock(this) - { - return m_name2repositoryMap.ContainsKey(repositoryName); - } - } - - /// - /// Gets a list of objects - /// - /// an array of all known objects - /// - /// - /// Gets an array of all of the repositories created by this selector. - /// - /// - public ILoggerRepository[] GetAllRepositories() - { - lock(this) - { - ICollection reps = m_name2repositoryMap.Values; - ILoggerRepository[] all = new ILoggerRepository[reps.Count]; - reps.CopyTo(all, 0); - return all; - } - } - - #endregion - - #region Private Static Fields - - /// - /// The fully qualified type of the CompactRepositorySelector class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(CompactRepositorySelector); - - #endregion Private Static Fields - - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// - /// Event raised when a new repository is created. - /// The event source will be this selector. The event args will - /// be a which - /// holds the newly created . - /// - /// - public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent - { - add { m_loggerRepositoryCreatedEvent += value; } - remove { m_loggerRepositoryCreatedEvent -= value; } - } - - /// - /// Notify the registered listeners that the repository has been created - /// - /// The repository that has been created - /// - /// - /// Raises the LoggerRepositoryCreatedEvent - /// event. - /// - /// - protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) - { - LoggerRepositoryCreationEventHandler handler = m_loggerRepositoryCreatedEvent; - if (handler != null) - { - handler(this, new LoggerRepositoryCreationEventArgs(repository)); - } - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Reflection; + + using log4net.Appender; + using log4net.Repository; + using log4net.Util; + + /// + /// The implementation of the interface suitable + /// for use with the compact framework. + /// + /// + /// + /// This implementation is a simple + /// mapping between repository name and + /// object. + /// + /// + /// The .NET Compact Framework 1.0 does not support retrieving assembly + /// level attributes therefore unlike the DefaultRepositorySelector + /// this selector does not examine the calling assembly for attributes. + /// + /// + /// Nicko Cadell. + public class CompactRepositorySelector : IRepositorySelector + { + private const string DefaultRepositoryName = "log4net-default-repository"; + + private readonly Hashtable m_name2repositoryMap = new Hashtable(); + private readonly Type m_defaultRepositoryType; + + private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; + + /// + /// Initializes a new instance of the class. + /// Create a new repository selector. + /// + /// the type of the repositories to create, must implement . + /// + /// + /// Create an new compact repository selector. + /// The default type for repositories must be specified, + /// an appropriate value would be . + /// + /// + /// throw if is null. + /// throw if does not implement . + public CompactRepositorySelector(Type defaultRepositoryType) + { + if (defaultRepositoryType == null) + { + throw new ArgumentNullException("defaultRepositoryType"); + } + + // Check that the type is a repository + if (!typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", (object)defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); + } + + this.m_defaultRepositoryType = defaultRepositoryType; + + LogLog.Debug(declaringType, "defaultRepositoryType [" + this.m_defaultRepositoryType + "]"); + } + + /// + /// Get the for the specified assembly. + /// + /// not used. + /// The default . + /// + /// + /// The argument is not used. This selector does not create a + /// separate repository for each assembly. + /// + /// + /// As a named repository is not specified the default repository is + /// returned. The default repository is named log4net-default-repository. + /// + /// + public ILoggerRepository GetRepository(Assembly assembly) + { + return this.CreateRepository(assembly, this.m_defaultRepositoryType); + } + + /// + /// Get the named . + /// + /// the name of the repository to lookup. + /// The named . + /// + /// + /// Get the named . The default + /// repository is log4net-default-repository. Other repositories + /// must be created using the . + /// If the named repository does not exist an exception is thrown. + /// + /// + /// throw if is null. + /// throw if the does not exist. + public ILoggerRepository GetRepository(string repositoryName) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + lock (this) + { + // Lookup in map + ILoggerRepository rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep == null) + { + throw new LogException("Repository [" + repositoryName + "] is NOT defined."); + } + + return rep; + } + } + + /// + /// Create a new repository for the assembly specified. + /// + /// not used. + /// the type of repository to create, must implement . + /// the repository created. + /// + /// + /// The argument is not used. This selector does not create a + /// separate repository for each assembly. + /// + /// + /// If the is null then the + /// default repository type specified to the constructor is used. + /// + /// + /// As a named repository is not specified the default repository is + /// returned. The default repository is named log4net-default-repository. + /// + /// + public ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType) + { + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock (this) + { + // This method should not throw if the default repository already exists. + + // First check that the repository does not exist + ILoggerRepository rep = this.m_name2repositoryMap[DefaultRepositoryName] as ILoggerRepository; + if (rep == null) + { + // Must create the repository + rep = this.CreateRepository(DefaultRepositoryName, repositoryType); + } + + return rep; + } + } + + /// + /// Create a new repository for the repository specified. + /// + /// the repository to associate with the . + /// the type of repository to create, must implement . + /// If this param is null then the default repository type is used. + /// the repository created. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same repository specified will return the same repository instance. + /// + /// + /// If the named repository already exists an exception will be thrown. + /// + /// + /// If is null then the default + /// repository type specified to the constructor is used. + /// + /// + /// throw if is null. + /// throw if the already exists. + public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock (this) + { + ILoggerRepository rep = null; + + // First check that the repository does not exist + rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep != null) + { + throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); + } + else + { + LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); + + // Call the no arg constructor for the repositoryType + rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); + + // Set the name of the repository + rep.Name = repositoryName; + + // Store in map + this.m_name2repositoryMap[repositoryName] = rep; + + // Notify listeners that the repository has been created + this.OnLoggerRepositoryCreatedEvent(rep); + } + + return rep; + } + } + + /// + /// Test if a named repository exists. + /// + /// the named repository to check. + /// true if the repository exists. + /// + /// + /// Test if a named repository exists. Use + /// to create a new repository and to retrieve + /// a repository. + /// + /// + public bool ExistsRepository(string repositoryName) + { + lock (this) + { + return this.m_name2repositoryMap.ContainsKey(repositoryName); + } + } + + /// + /// Gets a list of objects. + /// + /// an array of all known objects. + /// + /// + /// Gets an array of all of the repositories created by this selector. + /// + /// + public ILoggerRepository[] GetAllRepositories() + { + lock (this) + { + ICollection reps = this.m_name2repositoryMap.Values; + ILoggerRepository[] all = new ILoggerRepository[reps.Count]; + reps.CopyTo(all, 0); + return all; + } + } + + /// + /// The fully qualified type of the CompactRepositorySelector class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(CompactRepositorySelector); + + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// + /// Event raised when a new repository is created. + /// The event source will be this selector. The event args will + /// be a which + /// holds the newly created . + /// + /// + public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent + { + add { this.m_loggerRepositoryCreatedEvent += value; } + remove { this.m_loggerRepositoryCreatedEvent -= value; } + } + + /// + /// Notify the registered listeners that the repository has been created. + /// + /// The repository that has been created. + /// + /// + /// Raises the LoggerRepositoryCreatedEvent + /// event. + /// + /// + protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) + { + LoggerRepositoryCreationEventHandler handler = this.m_loggerRepositoryCreatedEvent; + if (handler != null) + { + handler(this, new LoggerRepositoryCreationEventArgs(repository)); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs index 91772b1a1b8..be3f8d6bcfe 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes // and uses the CompactRepositorySelector instead @@ -27,691 +25,678 @@ using System; using System.Collections; + #if !NETSTANDARD1_3 using System.Configuration; + #else using System.Linq; #endif using System.IO; using System.Reflection; - + using log4net.Config; -using log4net.Util; using log4net.Repository; +using log4net.Util; namespace log4net.Core { - /// - /// The default implementation of the interface. - /// - /// - /// - /// Uses attributes defined on the calling assembly to determine how to - /// configure the hierarchy for the repository. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class DefaultRepositorySelector : IRepositorySelector - { - #region Public Events - - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// - /// Event raised when a new repository is created. - /// The event source will be this selector. The event args will - /// be a which - /// holds the newly created . - /// - /// - public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent - { - add { m_loggerRepositoryCreatedEvent += value; } - remove { m_loggerRepositoryCreatedEvent -= value; } - } - - #endregion Public Events - - #region Public Instance Constructors - - /// - /// Creates a new repository selector. - /// - /// The type of the repositories to create, must implement - /// - /// - /// Create an new repository selector. - /// The default type for repositories must be specified, - /// an appropriate value would be . - /// - /// - /// is . - /// does not implement . - public DefaultRepositorySelector(Type defaultRepositoryType) - { - if (defaultRepositoryType == null) - { - throw new ArgumentNullException("defaultRepositoryType"); - } - - // Check that the type is a repository - if (! (typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) ) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); - } - - m_defaultRepositoryType = defaultRepositoryType; - - LogLog.Debug(declaringType, "defaultRepositoryType [" + m_defaultRepositoryType + "]"); - } - - #endregion Public Instance Constructors - - #region Implementation of IRepositorySelector - - /// - /// Gets the for the specified assembly. - /// - /// The assembly use to lookup the . - /// - /// - /// The type of the created and the repository - /// to create can be overridden by specifying the - /// attribute on the . - /// - /// - /// The default values are to use the - /// implementation of the interface and to use the - /// as the name of the repository. - /// - /// - /// The created will be automatically configured using - /// any attributes defined on - /// the . - /// - /// - /// The for the assembly - /// is . - public ILoggerRepository GetRepository(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - return CreateRepository(repositoryAssembly, m_defaultRepositoryType); - } - - /// - /// Gets the for the specified repository. - /// - /// The repository to use to lookup the . - /// The for the specified repository. - /// - /// - /// Returns the named repository. If is null - /// a is thrown. If the repository - /// does not exist a is thrown. - /// - /// - /// Use to create a repository. - /// - /// - /// is . - /// does not exist. - public ILoggerRepository GetRepository(string repositoryName) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - lock(this) - { - // Lookup in map - ILoggerRepository rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep == null) - { - throw new LogException("Repository [" + repositoryName + "] is NOT defined."); - } - return rep; - } - } - - /// - /// Create a new repository for the assembly specified - /// - /// the assembly to use to create the repository to associate with the . - /// The type of repository to create, must implement . - /// The repository created. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The type of the created and - /// the repository to create can be overridden by specifying the - /// attribute on the - /// . The default values are to use the - /// implementation of the - /// interface and to use the - /// as the name of the repository. - /// - /// - /// The created will be automatically - /// configured using any - /// attributes defined on the . - /// - /// - /// If a repository for the already exists - /// that repository will be returned. An error will not be raised and that - /// repository may be of a different type to that specified in . - /// Also the attribute on the - /// assembly may be used to override the repository type specified in - /// . - /// - /// - /// is . - public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) - { - return CreateRepository(repositoryAssembly, repositoryType, DefaultRepositoryName, true); - } - - /// - /// Creates a new repository for the assembly specified. - /// - /// the assembly to use to create the repository to associate with the . - /// The type of repository to create, must implement . - /// The name to assign to the created repository - /// Set to true to read and apply the assembly attributes - /// The repository created. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The type of the created and - /// the repository to create can be overridden by specifying the - /// attribute on the - /// . The default values are to use the - /// implementation of the - /// interface and to use the - /// as the name of the repository. - /// - /// - /// The created will be automatically - /// configured using any - /// attributes defined on the . - /// - /// - /// If a repository for the already exists - /// that repository will be returned. An error will not be raised and that - /// repository may be of a different type to that specified in . - /// Also the attribute on the - /// assembly may be used to override the repository type specified in - /// . - /// - /// - /// is . - public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = m_defaultRepositoryType; - } - - lock(this) - { - // Lookup in map - ILoggerRepository rep = m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository; - if (rep == null) - { - // Not found, therefore create - LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]"); - - // Must specify defaults - string actualRepositoryName = repositoryName; - Type actualRepositoryType = repositoryType; - - if (readAssemblyAttributes) - { - // Get the repository and type from the assembly attributes - GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType); - } - - LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]"); - - // Lookup the repository in the map (as this may already be defined) - rep = m_name2repositoryMap[actualRepositoryName] as ILoggerRepository; - if (rep == null) - { - // Create the repository - rep = CreateRepository(actualRepositoryName, actualRepositoryType); - - if (readAssemblyAttributes) - { - try - { - // Look for aliasing attributes - LoadAliases(repositoryAssembly, rep); - - // Look for plugins defined on the assembly - LoadPlugins(repositoryAssembly, rep); - - // Configure the repository using the assembly attributes - ConfigureRepository(repositoryAssembly, rep); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); - } - } - } - else - { - LogLog.Debug(declaringType, "repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]"); - - if (readAssemblyAttributes) - { - try - { - // Look for plugins defined on the assembly - LoadPlugins(repositoryAssembly, rep); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); - } - } - } - m_assembly2repositoryMap[repositoryAssembly] = rep; - } - return rep; - } - } - - /// - /// Creates a new repository for the specified repository. - /// - /// The repository to associate with the . - /// The type of repository to create, must implement . - /// If this param is then the default repository type is used. - /// The new repository. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same repository specified will return the same repository instance. - /// - /// - /// is . - /// already exists. - public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = m_defaultRepositoryType; - } - - lock(this) - { - ILoggerRepository rep = null; - - // First check that the repository does not exist - rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep != null) - { - throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); - } - else - { - // Lookup an alias before trying to create the new repository - ILoggerRepository aliasedRepository = m_alias2repositoryMap[repositoryName] as ILoggerRepository; - if (aliasedRepository != null) - { - // Found an alias - - // Check repository type - if (aliasedRepository.GetType() == repositoryType) - { - // Repository type is compatible - LogLog.Debug(declaringType, "Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]"); - rep = aliasedRepository; - - // Store in map - m_name2repositoryMap[repositoryName] = rep; - } - else - { - // Invalid repository type for alias - LogLog.Error(declaringType, "Failed to alias repository [" + repositoryName + "] to existing repository ["+aliasedRepository.Name+"]. Requested repository type ["+repositoryType.FullName+"] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]"); - - // We now drop through to create the repository without aliasing - } - } - - // If we could not find an alias - if (rep == null) - { - LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); - - // Call the no arg constructor for the repositoryType - rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); - - // Set the name of the repository - rep.Name = repositoryName; - - // Store in map - m_name2repositoryMap[repositoryName] = rep; - - // Notify listeners that the repository has been created - OnLoggerRepositoryCreatedEvent(rep); - } - } - - return rep; - } - } - - /// - /// Test if a named repository exists - /// - /// the named repository to check - /// true if the repository exists - /// - /// - /// Test if a named repository exists. Use - /// to create a new repository and to retrieve - /// a repository. - /// - /// - public bool ExistsRepository(string repositoryName) - { - lock(this) - { - return m_name2repositoryMap.ContainsKey(repositoryName); - } - } - - /// - /// Gets a list of objects - /// - /// an array of all known objects - /// - /// - /// Gets an array of all of the repositories created by this selector. - /// - /// - public ILoggerRepository[] GetAllRepositories() - { - lock(this) - { - ICollection reps = m_name2repositoryMap.Values; - ILoggerRepository[] all = new ILoggerRepository[reps.Count]; - reps.CopyTo(all, 0); - return all; - } - } - - #endregion Implementation of IRepositorySelector - - #region Public Instance Methods - - /// - /// Aliases a repository to an existing repository. - /// - /// The repository to alias. - /// The repository that the repository is aliased to. - /// - /// - /// The repository specified will be aliased to the repository when created. - /// The repository must not already exist. - /// - /// - /// When the repository is created it must utilize the same repository type as - /// the repository it is aliased to, otherwise the aliasing will fail. - /// - /// - /// - /// is . - /// -or- - /// is . - /// - public void AliasRepository(string repositoryAlias, ILoggerRepository repositoryTarget) - { - if (repositoryAlias == null) - { - throw new ArgumentNullException("repositoryAlias"); - } - if (repositoryTarget == null) - { - throw new ArgumentNullException("repositoryTarget"); - } - - lock(this) - { - // Check if the alias is already set - if (m_alias2repositoryMap.Contains(repositoryAlias)) - { - // Check if this is a duplicate of the current alias - if (repositoryTarget != ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias])) - { - // Cannot redefine existing alias - throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined."); - } - } - // Check if the alias is already mapped to a repository - else if (m_name2repositoryMap.Contains(repositoryAlias)) - { - // Check if this is a duplicate of the current mapping - if ( repositoryTarget != ((ILoggerRepository)m_name2repositoryMap[repositoryAlias]) ) - { - // Cannot define alias for already mapped repository - throw new InvalidOperationException("Repository [" + repositoryAlias + "] already exists and cannot be aliased to repository [" + repositoryTarget.Name + "]."); - } - } - else - { - // Set the alias - m_alias2repositoryMap[repositoryAlias] = repositoryTarget; - } - } - } - - #endregion Public Instance Methods - - #region Protected Instance Methods - - /// - /// Notifies the registered listeners that the repository has been created. - /// - /// The repository that has been created. - /// - /// - /// Raises the event. - /// - /// - protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) - { - LoggerRepositoryCreationEventHandler handler = m_loggerRepositoryCreatedEvent; - if (handler != null) - { - handler(this, new LoggerRepositoryCreationEventArgs(repository)); - } - } - - #endregion Protected Instance Methods - - #region Private Instance Methods - - /// - /// Gets the repository name and repository type for the specified assembly. - /// - /// The assembly that has a . - /// in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling. - /// in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling. - /// is . - private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - - try - { - LogLog.Debug(declaringType, "Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); - } - catch - { - // Ignore exception from debug call - } - - try - { - // Look for the RepositoryAttribute on the assembly + /// + /// The default implementation of the interface. + /// + /// + /// + /// Uses attributes defined on the calling assembly to determine how to + /// configure the hierarchy for the repository. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class DefaultRepositorySelector : IRepositorySelector + { + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// + /// Event raised when a new repository is created. + /// The event source will be this selector. The event args will + /// be a which + /// holds the newly created . + /// + /// + public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent + { + add { this.m_loggerRepositoryCreatedEvent += value; } + remove { this.m_loggerRepositoryCreatedEvent -= value; } + } + + /// + /// Initializes a new instance of the class. + /// Creates a new repository selector. + /// + /// The type of the repositories to create, must implement . + /// + /// + /// Create an new repository selector. + /// The default type for repositories must be specified, + /// an appropriate value would be . + /// + /// + /// is . + /// does not implement . + public DefaultRepositorySelector(Type defaultRepositoryType) + { + if (defaultRepositoryType == null) + { + throw new ArgumentNullException("defaultRepositoryType"); + } + + // Check that the type is a repository + if (!typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); + } + + this.m_defaultRepositoryType = defaultRepositoryType; + + LogLog.Debug(declaringType, "defaultRepositoryType [" + this.m_defaultRepositoryType + "]"); + } + + /// + /// Gets the for the specified assembly. + /// + /// The assembly use to lookup the . + /// + /// + /// The type of the created and the repository + /// to create can be overridden by specifying the + /// attribute on the . + /// + /// + /// The default values are to use the + /// implementation of the interface and to use the + /// as the name of the repository. + /// + /// + /// The created will be automatically configured using + /// any attributes defined on + /// the . + /// + /// + /// The for the assembly. + /// is . + public ILoggerRepository GetRepository(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + return this.CreateRepository(repositoryAssembly, this.m_defaultRepositoryType); + } + + /// + /// Gets the for the specified repository. + /// + /// The repository to use to lookup the . + /// The for the specified repository. + /// + /// + /// Returns the named repository. If is null + /// a is thrown. If the repository + /// does not exist a is thrown. + /// + /// + /// Use to create a repository. + /// + /// + /// is . + /// does not exist. + public ILoggerRepository GetRepository(string repositoryName) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + lock (this) + { + // Lookup in map + ILoggerRepository rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep == null) + { + throw new LogException("Repository [" + repositoryName + "] is NOT defined."); + } + + return rep; + } + } + + /// + /// Create a new repository for the assembly specified. + /// + /// the assembly to use to create the repository to associate with the . + /// The type of repository to create, must implement . + /// The repository created. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The type of the created and + /// the repository to create can be overridden by specifying the + /// attribute on the + /// . The default values are to use the + /// implementation of the + /// interface and to use the + /// as the name of the repository. + /// + /// + /// The created will be automatically + /// configured using any + /// attributes defined on the . + /// + /// + /// If a repository for the already exists + /// that repository will be returned. An error will not be raised and that + /// repository may be of a different type to that specified in . + /// Also the attribute on the + /// assembly may be used to override the repository type specified in + /// . + /// + /// + /// is . + public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) + { + return this.CreateRepository(repositoryAssembly, repositoryType, DefaultRepositoryName, true); + } + + /// + /// Creates a new repository for the assembly specified. + /// + /// the assembly to use to create the repository to associate with the . + /// The type of repository to create, must implement . + /// The name to assign to the created repository. + /// Set to true to read and apply the assembly attributes. + /// The repository created. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The type of the created and + /// the repository to create can be overridden by specifying the + /// attribute on the + /// . The default values are to use the + /// implementation of the + /// interface and to use the + /// as the name of the repository. + /// + /// + /// The created will be automatically + /// configured using any + /// attributes defined on the . + /// + /// + /// If a repository for the already exists + /// that repository will be returned. An error will not be raised and that + /// repository may be of a different type to that specified in . + /// Also the attribute on the + /// assembly may be used to override the repository type specified in + /// . + /// + /// + /// is . + public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock (this) + { + // Lookup in map + ILoggerRepository rep = this.m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository; + if (rep == null) + { + // Not found, therefore create + LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]"); + + // Must specify defaults + string actualRepositoryName = repositoryName; + Type actualRepositoryType = repositoryType; + + if (readAssemblyAttributes) + { + // Get the repository and type from the assembly attributes + this.GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType); + } + + LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]"); + + // Lookup the repository in the map (as this may already be defined) + rep = this.m_name2repositoryMap[actualRepositoryName] as ILoggerRepository; + if (rep == null) + { + // Create the repository + rep = this.CreateRepository(actualRepositoryName, actualRepositoryType); + + if (readAssemblyAttributes) + { + try + { + // Look for aliasing attributes + this.LoadAliases(repositoryAssembly, rep); + + // Look for plugins defined on the assembly + this.LoadPlugins(repositoryAssembly, rep); + + // Configure the repository using the assembly attributes + this.ConfigureRepository(repositoryAssembly, rep); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); + } + } + } + else + { + LogLog.Debug(declaringType, "repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]"); + + if (readAssemblyAttributes) + { + try + { + // Look for plugins defined on the assembly + this.LoadPlugins(repositoryAssembly, rep); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); + } + } + } + + this.m_assembly2repositoryMap[repositoryAssembly] = rep; + } + + return rep; + } + } + + /// + /// Creates a new repository for the specified repository. + /// + /// The repository to associate with the . + /// The type of repository to create, must implement . + /// If this param is then the default repository type is used. + /// The new repository. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same repository specified will return the same repository instance. + /// + /// + /// is . + /// already exists. + public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock (this) + { + ILoggerRepository rep = null; + + // First check that the repository does not exist + rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep != null) + { + throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); + } + else + { + // Lookup an alias before trying to create the new repository + ILoggerRepository aliasedRepository = this.m_alias2repositoryMap[repositoryName] as ILoggerRepository; + if (aliasedRepository != null) + { + // Found an alias + + // Check repository type + if (aliasedRepository.GetType() == repositoryType) + { + // Repository type is compatible + LogLog.Debug(declaringType, "Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]"); + rep = aliasedRepository; + + // Store in map + this.m_name2repositoryMap[repositoryName] = rep; + } + else + { + // Invalid repository type for alias + LogLog.Error(declaringType, "Failed to alias repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]. Requested repository type [" + repositoryType.FullName + "] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]"); + + // We now drop through to create the repository without aliasing + } + } + + // If we could not find an alias + if (rep == null) + { + LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); + + // Call the no arg constructor for the repositoryType + rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); + + // Set the name of the repository + rep.Name = repositoryName; + + // Store in map + this.m_name2repositoryMap[repositoryName] = rep; + + // Notify listeners that the repository has been created + this.OnLoggerRepositoryCreatedEvent(rep); + } + } + + return rep; + } + } + + /// + /// Test if a named repository exists. + /// + /// the named repository to check. + /// true if the repository exists. + /// + /// + /// Test if a named repository exists. Use + /// to create a new repository and to retrieve + /// a repository. + /// + /// + public bool ExistsRepository(string repositoryName) + { + lock (this) + { + return this.m_name2repositoryMap.ContainsKey(repositoryName); + } + } + + /// + /// Gets a list of objects. + /// + /// an array of all known objects. + /// + /// + /// Gets an array of all of the repositories created by this selector. + /// + /// + public ILoggerRepository[] GetAllRepositories() + { + lock (this) + { + ICollection reps = this.m_name2repositoryMap.Values; + ILoggerRepository[] all = new ILoggerRepository[reps.Count]; + reps.CopyTo(all, 0); + return all; + } + } + + /// + /// Aliases a repository to an existing repository. + /// + /// The repository to alias. + /// The repository that the repository is aliased to. + /// + /// + /// The repository specified will be aliased to the repository when created. + /// The repository must not already exist. + /// + /// + /// When the repository is created it must utilize the same repository type as + /// the repository it is aliased to, otherwise the aliasing will fail. + /// + /// + /// + /// is . + /// -or- + /// is . + /// + public void AliasRepository(string repositoryAlias, ILoggerRepository repositoryTarget) + { + if (repositoryAlias == null) + { + throw new ArgumentNullException("repositoryAlias"); + } + + if (repositoryTarget == null) + { + throw new ArgumentNullException("repositoryTarget"); + } + + lock (this) + { + // Check if the alias is already set + if (this.m_alias2repositoryMap.Contains(repositoryAlias)) + { + // Check if this is a duplicate of the current alias + if (repositoryTarget != ((ILoggerRepository)this.m_alias2repositoryMap[repositoryAlias])) + { + // Cannot redefine existing alias + throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)this.m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined."); + } + } + + // Check if the alias is already mapped to a repository + else if (this.m_name2repositoryMap.Contains(repositoryAlias)) + { + // Check if this is a duplicate of the current mapping + if (repositoryTarget != ((ILoggerRepository)this.m_name2repositoryMap[repositoryAlias])) + { + // Cannot define alias for already mapped repository + throw new InvalidOperationException("Repository [" + repositoryAlias + "] already exists and cannot be aliased to repository [" + repositoryTarget.Name + "]."); + } + } + else + { + // Set the alias + this.m_alias2repositoryMap[repositoryAlias] = repositoryTarget; + } + } + } + + /// + /// Notifies the registered listeners that the repository has been created. + /// + /// The repository that has been created. + /// + /// + /// Raises the event. + /// + /// + protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) + { + LoggerRepositoryCreationEventHandler handler = this.m_loggerRepositoryCreatedEvent; + if (handler != null) + { + handler(this, new LoggerRepositoryCreationEventArgs(repository)); + } + } + + /// + /// Gets the repository name and repository type for the specified assembly. + /// + /// The assembly that has a . + /// in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling. + /// in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling. + /// is . + private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + + try + { + LogLog.Debug(declaringType, "Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); + } + catch + { + // Ignore exception from debug call + } + + try + { + // Look for the RepositoryAttribute on the assembly #if NETSTANDARD1_3 object[] repositoryAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.RepositoryAttribute)).ToArray(); #else - object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.RepositoryAttribute), false); + object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.RepositoryAttribute), false); #endif - if (repositoryAttributes == null || repositoryAttributes.Length == 0) - { - // This is not a problem, but its nice to know what is going on. - LogLog.Debug(declaringType, "Assembly [" + assembly + "] does not have a RepositoryAttribute specified."); - } - else - { - if (repositoryAttributes.Length > 1) - { - LogLog.Error(declaringType, "Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence."); - } - - log4net.Config.RepositoryAttribute domAttr = repositoryAttributes[0] as log4net.Config.RepositoryAttribute; - - if (domAttr == null) - { - LogLog.Error(declaringType, "Assembly [" + assembly + "] has a RepositoryAttribute but it does not!."); - } - else - { - // If the Name property is set then override the default - if (domAttr.Name != null) - { - repositoryName = domAttr.Name; - } - - // If the RepositoryType property is set then override the default - if (domAttr.RepositoryType != null) - { - // Check that the type is a repository - if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) - { - repositoryType = domAttr.RepositoryType; - } - else - { - LogLog.Error(declaringType, "DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); - } - } - } - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Unhandled exception in GetInfoForAssembly", ex); - } - } - - /// - /// Configures the repository using information from the assembly. - /// - /// The assembly containing - /// attributes which define the configuration for the repository. - /// The repository to configure. - /// - /// is . - /// -or- - /// is . - /// - private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly + if (repositoryAttributes == null || repositoryAttributes.Length == 0) + { + // This is not a problem, but its nice to know what is going on. + LogLog.Debug(declaringType, "Assembly [" + assembly + "] does not have a RepositoryAttribute specified."); + } + else + { + if (repositoryAttributes.Length > 1) + { + LogLog.Error(declaringType, "Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence."); + } + + log4net.Config.RepositoryAttribute domAttr = repositoryAttributes[0] as log4net.Config.RepositoryAttribute; + + if (domAttr == null) + { + LogLog.Error(declaringType, "Assembly [" + assembly + "] has a RepositoryAttribute but it does not!."); + } + else + { + // If the Name property is set then override the default + if (domAttr.Name != null) + { + repositoryName = domAttr.Name; + } + + // If the RepositoryType property is set then override the default + if (domAttr.RepositoryType != null) + { + // Check that the type is a repository + if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) + { + repositoryType = domAttr.RepositoryType; + } + else + { + LogLog.Error(declaringType, "DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); + } + } + } + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Unhandled exception in GetInfoForAssembly", ex); + } + } + + /// + /// Configures the repository using information from the assembly. + /// + /// The assembly containing + /// attributes which define the configuration for the repository. + /// The repository to configure. + /// + /// is . + /// -or- + /// is . + /// + private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly #if NETSTANDARD1_3 object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.ConfiguratorAttribute)).ToArray(); #else - object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); + object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); #endif - if (configAttributes != null && configAttributes.Length > 0) - { - // Sort the ConfiguratorAttributes in priority order - Array.Sort(configAttributes); - - // Delegate to the attribute the job of configuring the repository - foreach(log4net.Config.ConfiguratorAttribute configAttr in configAttributes) - { - if (configAttr != null) - { - try - { - configAttr.Configure(assembly, repository); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception calling ["+configAttr.GetType().FullName+"] .Configure method.", ex); - } - } - } - } - - if (repository.Name == DefaultRepositoryName) - { - // Try to configure the default repository using an AppSettings specified config file - // Do this even if the repository has been configured (or claims to be), this allows overriding - // of the default config files etc, if that is required. - - string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); - if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) - { - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch(Exception ex) - { - LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path ["+repositoryConfigFile+"] will be treated as an absolute URI", ex); - } + if (configAttributes != null && configAttributes.Length > 0) + { + // Sort the ConfiguratorAttributes in priority order + Array.Sort(configAttributes); + + // Delegate to the attribute the job of configuring the repository + foreach (log4net.Config.ConfiguratorAttribute configAttr in configAttributes) + { + if (configAttr != null) + { + try + { + configAttr.Configure(assembly, repository); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception calling [" + configAttr.GetType().FullName + "] .Configure method.", ex); + } + } + } + } + + if (repository.Name == DefaultRepositoryName) + { + // Try to configure the default repository using an AppSettings specified config file + // Do this even if the repository has been configured (or claims to be), this allows overriding + // of the default config files etc, if that is required. + string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); + if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) + { + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch (Exception ex) + { + LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path [" + repositoryConfigFile + "] will be treated as an absolute URI", ex); + } string repositoryConfigFilePath = repositoryConfigFile; if (applicationBaseDirectory != null) @@ -720,9 +705,9 @@ private void ConfigureRepository(Assembly assembly, ILoggerRepository repository } // Determine whether to watch the file or not based on an app setting value: - bool watchRepositoryConfigFile = false; + bool watchRepositoryConfigFile = false; #if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3 - Boolean.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile); + bool.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile); #else { string watch = SystemInfo.GetAppSetting("log4net.Config.Watch"); @@ -740,154 +725,153 @@ private void ConfigureRepository(Assembly assembly, ILoggerRepository repository } #endif - if (watchRepositoryConfigFile) - { - // As we are going to watch the config file it is required to resolve it as a - // physical file system path pass that in a FileInfo object to the Configurator - FileInfo repositoryConfigFileInfo = null; - try - { - repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath); - } - catch (Exception ex) - { + if (watchRepositoryConfigFile) + { + // As we are going to watch the config file it is required to resolve it as a + // physical file system path pass that in a FileInfo object to the Configurator + FileInfo repositoryConfigFileInfo = null; + try + { + repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath); + } + catch (Exception ex) + { LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + repositoryConfigFilePath + "]", ex); - } - try - { + } + + try + { LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + repositoryConfigFilePath + "]"); XmlConfigurator.ConfigureAndWatch(repository, repositoryConfigFileInfo); - } - catch (Exception ex) - { + } + catch (Exception ex) + { LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + repositoryConfigFilePath + "]", ex); - } - } - else - { - // As we are not going to watch the config file it is easiest to just resolve it as a - // URI and pass that to the Configurator - Uri repositoryConfigUri = null; - try - { - repositoryConfigUri = new Uri(repositoryConfigFilePath); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Exception while parsing log4net.Config file path ["+repositoryConfigFile+"]", ex); - } - - if (repositoryConfigUri != null) - { - LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI ["+repositoryConfigUri.ToString()+"]"); - - try - { - // TODO: Support other types of configurator - XmlConfigurator.Configure(repository, repositoryConfigUri); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri ["+repositoryConfigUri+"]", ex); - } - } + } + } + else + { + // As we are not going to watch the config file it is easiest to just resolve it as a + // URI and pass that to the Configurator + Uri repositoryConfigUri = null; + try + { + repositoryConfigUri = new Uri(repositoryConfigFilePath); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex); + } + + if (repositoryConfigUri != null) + { + LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]"); + + try + { + // TODO: Support other types of configurator + XmlConfigurator.Configure(repository, repositoryConfigUri); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex); + } + } } - } - } - } - - /// - /// Loads the attribute defined plugins on the assembly. - /// - /// The assembly that contains the attributes. - /// The repository to add the plugins to. - /// - /// is . - /// -or- - /// is . - /// - private void LoadPlugins(Assembly assembly, ILoggerRepository repository) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - // Look for the PluginAttribute on the assembly + } + } + } + + /// + /// Loads the attribute defined plugins on the assembly. + /// + /// The assembly that contains the attributes. + /// The repository to add the plugins to. + /// + /// is . + /// -or- + /// is . + /// + private void LoadPlugins(Assembly assembly, ILoggerRepository repository) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + // Look for the PluginAttribute on the assembly #if NETSTANDARD1_3 object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.PluginAttribute)).ToArray(); #else - object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.PluginAttribute), false); + object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.PluginAttribute), false); #endif - if (configAttributes != null && configAttributes.Length > 0) - { - foreach(log4net.Plugin.IPluginFactory configAttr in configAttributes) - { - try - { - // Create the plugin and add it to the repository - repository.PluginMap.Add(configAttr.CreatePlugin()); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex); - } - } - } - } - - /// - /// Loads the attribute defined aliases on the assembly. - /// - /// The assembly that contains the attributes. - /// The repository to alias to. - /// - /// is . - /// -or- - /// is . - /// - private void LoadAliases(Assembly assembly, ILoggerRepository repository) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - // Look for the AliasRepositoryAttribute on the assembly + if (configAttributes != null && configAttributes.Length > 0) + { + foreach (log4net.Plugin.IPluginFactory configAttr in configAttributes) + { + try + { + // Create the plugin and add it to the repository + repository.PluginMap.Add(configAttr.CreatePlugin()); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex); + } + } + } + } + + /// + /// Loads the attribute defined aliases on the assembly. + /// + /// The assembly that contains the attributes. + /// The repository to alias to. + /// + /// is . + /// -or- + /// is . + /// + private void LoadAliases(Assembly assembly, ILoggerRepository repository) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + // Look for the AliasRepositoryAttribute on the assembly #if NETSTANDARD1_3 object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.AliasRepositoryAttribute)).ToArray(); #else - object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.AliasRepositoryAttribute), false); + object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.AliasRepositoryAttribute), false); #endif - if (configAttributes != null && configAttributes.Length > 0) - { - foreach(log4net.Config.AliasRepositoryAttribute configAttr in configAttributes) - { - try - { - AliasRepository(configAttr.Name, repository); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to alias repository [" + configAttr.Name + "]", ex); - } - } - } - } - - #endregion Private Instance Methods - - #region Private Static Fields - + if (configAttributes != null && configAttributes.Length > 0) + { + foreach (log4net.Config.AliasRepositoryAttribute configAttr in configAttributes) + { + try + { + this.AliasRepository(configAttr.Name, repository); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to alias repository [" + configAttr.Name + "]", ex); + } + } + } + } + /// /// The fully qualified type of the DefaultRepositorySelector class. /// @@ -895,23 +879,16 @@ private void LoadAliases(Assembly assembly, ILoggerRepository repository) /// Used by the internal logger to record the Type of the /// log message. /// - private readonly static Type declaringType = typeof(DefaultRepositorySelector); - - private const string DefaultRepositoryName = "log4net-default-repository"; - - #endregion Private Static Fields - - #region Private Instance Fields - - private readonly Hashtable m_name2repositoryMap = new Hashtable(); - private readonly Hashtable m_assembly2repositoryMap = new Hashtable(); - private readonly Hashtable m_alias2repositoryMap = new Hashtable(); - private readonly Type m_defaultRepositoryType; + private static readonly Type declaringType = typeof(DefaultRepositorySelector); - private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; + private const string DefaultRepositoryName = "log4net-default-repository"; + private readonly Hashtable m_name2repositoryMap = new Hashtable(); + private readonly Hashtable m_assembly2repositoryMap = new Hashtable(); + private readonly Hashtable m_alias2repositoryMap = new Hashtable(); + private readonly Type m_defaultRepositoryType; - #endregion Private Instance Fields - } + private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs index dfa8395044b..4a6c60333c7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs @@ -1,74 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Defined error codes that can be passed to the method. - /// - /// - /// - /// Values passed to the method. - /// - /// - /// Nicko Cadell - public enum ErrorCode : int - { - /// - /// A general error - /// - GenericFailure = 0, + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Defined error codes that can be passed to the method. + /// + /// + /// + /// Values passed to the method. + /// + /// + /// Nicko Cadell. + public enum ErrorCode : int + { + /// + /// A general error + /// + GenericFailure = 0, - /// - /// Error while writing output - /// - WriteFailure, + /// + /// Error while writing output + /// + WriteFailure, - /// - /// Failed to flush file - /// - FlushFailure, + /// + /// Failed to flush file + /// + FlushFailure, - /// - /// Failed to close file - /// - CloseFailure, + /// + /// Failed to close file + /// + CloseFailure, - /// - /// Unable to open output file - /// - FileOpenFailure, + /// + /// Unable to open output file + /// + FileOpenFailure, - /// - /// No layout specified - /// - MissingLayout, + /// + /// No layout specified + /// + MissingLayout, - /// - /// Failed to parse address - /// - AddressParseFailure - } + /// + /// Failed to parse address + /// + AddressParseFailure, + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs index 513bd89b7da..3814a974643 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs @@ -1,137 +1,133 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETSTANDARD1_3 using System.Reflection; #endif namespace log4net.Core { - /// - /// An evaluator that triggers on an Exception type - /// - /// - /// - /// This evaluator will trigger if the type of the Exception - /// passed to - /// is equal to a Type in . /// - /// - /// - /// Drew Schaeffer - public class ExceptionEvaluator : ITriggeringEventEvaluator - { - /// - /// The type that causes the trigger to fire. - /// - private Type m_type; - - /// - /// Causes subclasses of to cause the trigger to fire. - /// - private bool m_triggerOnSubclass; - - /// - /// Default ctor to allow dynamic creation through a configurator. - /// - public ExceptionEvaluator() - { - // empty - } - - /// - /// Constructs an evaluator and initializes to trigger on - /// - /// the type that triggers this evaluator. - /// If true, this evaluator will trigger on subclasses of . - public ExceptionEvaluator(Type exType, bool triggerOnSubClass) - { - if (exType == null) - { - throw new ArgumentNullException("exType"); - } - - m_type = exType; - m_triggerOnSubclass = triggerOnSubClass; - } - - /// - /// The type that triggers this evaluator. - /// - public Type ExceptionType - { - get { return m_type; } - set { m_type = value; } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// An evaluator that triggers on an Exception type. + /// + /// + /// + /// This evaluator will trigger if the type of the Exception + /// passed to + /// is equal to a Type in . ///. + /// + /// + /// Drew Schaeffer. + public class ExceptionEvaluator : ITriggeringEventEvaluator + { + /// + /// The type that causes the trigger to fire. + /// + private Type m_type; - /// - /// If true, this evaluator will trigger on subclasses of . - /// - public bool TriggerOnSubclass - { - get { return m_triggerOnSubclass; } - set { m_triggerOnSubclass = value; } - } + /// + /// Causes subclasses of to cause the trigger to fire. + /// + private bool m_triggerOnSubclass; + + /// + /// Initializes a new instance of the class. + /// Default ctor to allow dynamic creation through a configurator. + /// + public ExceptionEvaluator() + { + // empty + } + + /// + /// Initializes a new instance of the class. + /// Constructs an evaluator and initializes to trigger on . + /// + /// the type that triggers this evaluator. + /// If true, this evaluator will trigger on subclasses of . + public ExceptionEvaluator(Type exType, bool triggerOnSubClass) + { + if (exType == null) + { + throw new ArgumentNullException("exType"); + } - #region ITriggeringEventEvaluator Members + this.m_type = exType; + this.m_triggerOnSubclass = triggerOnSubClass; + } - /// - /// Is this the triggering event? - /// - /// The event to check - /// This method returns true, if the logging event Exception - /// Type is . - /// Otherwise it returns false - /// - /// - /// This evaluator will trigger if the Exception Type of the event - /// passed to - /// is . - /// - /// - public bool IsTriggeringEvent(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } + /// + /// Gets or sets the type that triggers this evaluator. + /// + public Type ExceptionType + { + get { return this.m_type; } + set { this.m_type = value; } + } - if (m_triggerOnSubclass && loggingEvent.ExceptionObject != null) - { - // check if loggingEvent.ExceptionObject is of type ExceptionType or subclass of ExceptionType - Type exceptionObjectType = loggingEvent.ExceptionObject.GetType(); - return exceptionObjectType == m_type || exceptionObjectType.IsSubclassOf(m_type); - } - else if (!m_triggerOnSubclass && loggingEvent.ExceptionObject != null) - { // check if loggingEvent.ExceptionObject is of type ExceptionType - return loggingEvent.ExceptionObject.GetType() == m_type; - } - else - { // loggingEvent.ExceptionObject is null - return false; - } - } + /// + /// Gets or sets a value indicating whether if true, this evaluator will trigger on subclasses of . + /// + public bool TriggerOnSubclass + { + get { return this.m_triggerOnSubclass; } + set { this.m_triggerOnSubclass = value; } + } + + /// + /// Is this the triggering event?. + /// + /// The event to check. + /// This method returns true, if the logging event Exception + /// Type is . + /// Otherwise it returns false. + /// + /// + /// This evaluator will trigger if the Exception Type of the event + /// passed to + /// is . + /// + /// + public bool IsTriggeringEvent(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - #endregion - } + if (this.m_triggerOnSubclass && loggingEvent.ExceptionObject != null) + { + // check if loggingEvent.ExceptionObject is of type ExceptionType or subclass of ExceptionType + Type exceptionObjectType = loggingEvent.ExceptionObject.GetType(); + return exceptionObjectType == this.m_type || exceptionObjectType.IsSubclassOf(this.m_type); + } + else if (!this.m_triggerOnSubclass && loggingEvent.ExceptionObject != null) + { // check if loggingEvent.ExceptionObject is of type ExceptionType + return loggingEvent.ExceptionObject.GetType() == this.m_type; + } + else + { // loggingEvent.ExceptionObject is null + return false; + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs index bb3af68711e..9f0017cd619 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs @@ -1,125 +1,122 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Appender; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Interface for attaching appenders to objects. - /// - /// - /// - /// Interface for attaching, removing and retrieving appenders. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IAppenderAttachable - { - /// - /// Attaches an appender. - /// - /// The appender to add. - /// - /// - /// Add the specified appender. The implementation may - /// choose to allow or deny duplicate appenders. - /// - /// - void AddAppender(IAppender appender); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Appender; + + /// + /// Interface for attaching appenders to objects. + /// + /// + /// + /// Interface for attaching, removing and retrieving appenders. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IAppenderAttachable + { + /// + /// Attaches an appender. + /// + /// The appender to add. + /// + /// + /// Add the specified appender. The implementation may + /// choose to allow or deny duplicate appenders. + /// + /// + void AddAppender(IAppender appender); - /// - /// Gets all attached appenders. - /// - /// - /// A collection of attached appenders. - /// - /// - /// - /// Gets a collection of attached appenders. - /// If there are no attached appenders the - /// implementation should return an empty - /// collection rather than null. - /// - /// - AppenderCollection Appenders {get;} + /// + /// Gets all attached appenders. + /// + /// + /// A collection of attached appenders. + /// + /// + /// + /// Gets a collection of attached appenders. + /// If there are no attached appenders the + /// implementation should return an empty + /// collection rather than null. + /// + /// + AppenderCollection Appenders { get; } - /// - /// Gets an attached appender with the specified name. - /// - /// The name of the appender to get. - /// - /// The appender with the name specified, or null if no appender with the - /// specified name is found. - /// - /// - /// - /// Returns an attached appender with the specified. - /// If no appender with the specified name is found null will be - /// returned. - /// - /// - IAppender GetAppender(string name); + /// + /// Gets an attached appender with the specified name. + /// + /// The name of the appender to get. + /// + /// The appender with the name specified, or null if no appender with the + /// specified name is found. + /// + /// + /// + /// Returns an attached appender with the specified. + /// If no appender with the specified name is found null will be + /// returned. + /// + /// + IAppender GetAppender(string name); - /// - /// Removes all attached appenders. - /// - /// - /// - /// Removes and closes all attached appenders - /// - /// - void RemoveAllAppenders(); + /// + /// Removes all attached appenders. + /// + /// + /// + /// Removes and closes all attached appenders. + /// + /// + void RemoveAllAppenders(); - /// - /// Removes the specified appender from the list of attached appenders. - /// - /// The appender to remove. - /// The appender removed from the list - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - IAppender RemoveAppender(IAppender appender); + /// + /// Removes the specified appender from the list of attached appenders. + /// + /// The appender to remove. + /// The appender removed from the list. + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + IAppender RemoveAppender(IAppender appender); - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - IAppender RemoveAppender(string name); - } + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list. + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + IAppender RemoveAppender(string name); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs index 5a5a27849ac..d6974241856 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs @@ -1,79 +1,76 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Appenders may delegate their error handling to an . - /// - /// - /// - /// Error handling is a particularly tedious to get right because by - /// definition errors are hard to predict and to reproduce. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IErrorHandler - { - /// - /// Handles the error and information about the error condition is passed as - /// a parameter. - /// - /// The message associated with the error. - /// The that was thrown when the error occurred. - /// The error code associated with the error. - /// - /// - /// Handles the error and information about the error condition is passed as - /// a parameter. - /// - /// - void Error(string message, Exception e, ErrorCode errorCode); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Appenders may delegate their error handling to an . + /// + /// + /// + /// Error handling is a particularly tedious to get right because by + /// definition errors are hard to predict and to reproduce. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IErrorHandler + { + /// + /// Handles the error and information about the error condition is passed as + /// a parameter. + /// + /// The message associated with the error. + /// The that was thrown when the error occurred. + /// The error code associated with the error. + /// + /// + /// Handles the error and information about the error condition is passed as + /// a parameter. + /// + /// + void Error(string message, Exception e, ErrorCode errorCode); - /// - /// Prints the error message passed as a parameter. - /// - /// The message associated with the error. - /// The that was thrown when the error occurred. - /// - /// - /// See . - /// - /// - void Error(string message, Exception e); + /// + /// Prints the error message passed as a parameter. + /// + /// The message associated with the error. + /// The that was thrown when the error occurred. + /// + /// + /// See . + /// + /// + void Error(string message, Exception e); - /// - /// Prints the error message passed as a parameter. - /// - /// The message associated with the error. - /// - /// - /// See . - /// - /// - void Error(string message); - } + /// + /// Prints the error message passed as a parameter. + /// + /// The message associated with the error. + /// + /// + /// See . + /// + /// + void Error(string message); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs index 89644019a9c..401115c4c53 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs @@ -1,62 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Interface for objects that require fixing. - /// - /// - /// - /// Interface that indicates that the object requires fixing before it - /// can be taken outside the context of the appender's - /// method. - /// - /// - /// When objects that implement this interface are stored - /// in the context properties maps - /// and - /// are fixed - /// (see ) the - /// method will be called. - /// - /// - /// Nicko Cadell - public interface IFixingRequired - { - /// - /// Get a portable version of this object - /// - /// the portable instance of this object - /// - /// - /// Get a portable instance object that represents the current - /// state of this object. The portable object can be stored - /// and logged from any thread with identical results. - /// - /// - object GetFixedObject(); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Interface for objects that require fixing. + /// + /// + /// + /// Interface that indicates that the object requires fixing before it + /// can be taken outside the context of the appender's + /// method. + /// + /// + /// When objects that implement this interface are stored + /// in the context properties maps + /// and + /// are fixed + /// (see ) the + /// method will be called. + /// + /// + /// Nicko Cadell. + public interface IFixingRequired + { + /// + /// Get a portable version of this object. + /// + /// the portable instance of this object. + /// + /// + /// Get a portable instance object that represents the current + /// state of this object. The portable object can be stored + /// and logged from any thread with identical results. + /// + /// + object GetFixedObject(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs index 588a8de55ac..4d0ebb0179a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs @@ -1,119 +1,116 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Interface that all loggers implement - /// - /// - /// - /// This interface supports logging events and testing if a level - /// is enabled for logging. - /// - /// - /// These methods will not throw exceptions. Note to implementor, ensure - /// that the implementation of these methods cannot allow an exception - /// to be thrown to the caller. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface ILogger - { - /// - /// Gets the name of the logger. - /// - /// - /// The name of the logger. - /// - /// - /// - /// The name of this logger - /// - /// - string Name { get; } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + using log4net.Repository; + + /// + /// Interface that all loggers implement. + /// + /// + /// + /// This interface supports logging events and testing if a level + /// is enabled for logging. + /// + /// + /// These methods will not throw exceptions. Note to implementor, ensure + /// that the implementation of these methods cannot allow an exception + /// to be thrown to the caller. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface ILogger + { + /// + /// Gets the name of the logger. + /// + /// + /// The name of the logger. + /// + /// + /// + /// The name of this logger. + /// + /// + string Name { get; } + + /// + /// This generic form is intended to be used by wrappers. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The level of the message to be logged. + /// The message object to log. + /// the exception to log, including its stack trace. Pass null to not log an exception. + /// + /// + /// Generates a logging event for the specified using + /// the and . + /// + /// + void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception); - /// - /// This generic form is intended to be used by wrappers. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The level of the message to be logged. - /// The message object to log. - /// the exception to log, including its stack trace. Pass null to not log an exception. - /// - /// - /// Generates a logging event for the specified using - /// the and . - /// - /// - void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception); - - /// - /// This is the most generic printing method that is intended to be used - /// by wrappers. - /// - /// The event being logged. - /// - /// - /// Logs the specified logging event through this logger. - /// - /// - void Log(LoggingEvent logEvent); + /// + /// This is the most generic printing method that is intended to be used + /// by wrappers. + /// + /// The event being logged. + /// + /// + /// Logs the specified logging event through this logger. + /// + /// + void Log(LoggingEvent logEvent); - /// - /// Checks if this logger is enabled for a given passed as parameter. - /// - /// The level to check. - /// - /// true if this logger is enabled for level, otherwise false. - /// - /// - /// - /// Test if this logger is going to log events of the specified . - /// - /// - bool IsEnabledFor(Level level); + /// + /// Checks if this logger is enabled for a given passed as parameter. + /// + /// The level to check. + /// + /// true if this logger is enabled for level, otherwise false. + /// + /// + /// + /// Test if this logger is going to log events of the specified . + /// + /// + bool IsEnabledFor(Level level); - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - /// The that this logger belongs to. - /// - /// - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - ILoggerRepository Repository { get; } - } + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + /// The that this logger belongs to. + /// + /// + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + ILoggerRepository Repository { get; } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs index e7ef32d8ca8..ee6e7a0ec6e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs @@ -1,63 +1,60 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net; -using log4net.Core; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Base interface for all wrappers - /// - /// - /// - /// Base interface for all wrappers. - /// - /// - /// All wrappers must implement this interface. - /// - /// - /// Nicko Cadell - public interface ILoggerWrapper - { - /// - /// Get the implementation behind this wrapper object. - /// - /// - /// The object that in implementing this object. - /// - /// - /// - /// The object that in implementing this - /// object. The Logger object may not - /// be the same object as this object because of logger decorators. - /// This gets the actual underlying objects that is used to process - /// the log events. - /// - /// - ILogger Logger { get; } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net; + using log4net.Core; + using log4net.Repository; + + /// + /// Base interface for all wrappers. + /// + /// + /// + /// Base interface for all wrappers. + /// + /// + /// All wrappers must implement this interface. + /// + /// + /// Nicko Cadell. + public interface ILoggerWrapper + { + /// + /// Gets get the implementation behind this wrapper object. + /// + /// + /// The object that in implementing this object. + /// + /// + /// + /// The object that in implementing this + /// object. The Logger object may not + /// be the same object as this object because of logger decorators. + /// This gets the actual underlying objects that is used to process + /// the log events. + /// + /// + ILogger Logger { get; } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs index e1f0272373f..2f3b7718a09 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs @@ -1,62 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Interface used to delay activate a configured object. - /// - /// - /// - /// This allows an object to defer activation of its options until all - /// options have been set. This is required for components which have - /// related options that remain ambiguous until all are set. - /// - /// - /// If a component implements this interface then the method - /// must be called by the container after its all the configured properties have been set - /// and before the component can be used. - /// - /// - /// Nicko Cadell - public interface IOptionHandler - { - /// - /// Activate the options that were previously set with calls to properties. - /// - /// - /// - /// This allows an object to defer activation of its options until all - /// options have been set. This is required for components which have - /// related options that remain ambiguous until all are set. - /// - /// - /// If a component implements this interface then this method must be called - /// after its properties have been set before the component can be used. - /// - /// - void ActivateOptions(); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Interface used to delay activate a configured object. + /// + /// + /// + /// This allows an object to defer activation of its options until all + /// options have been set. This is required for components which have + /// related options that remain ambiguous until all are set. + /// + /// + /// If a component implements this interface then the method + /// must be called by the container after its all the configured properties have been set + /// and before the component can be used. + /// + /// + /// Nicko Cadell. + public interface IOptionHandler + { + /// + /// Activate the options that were previously set with calls to properties. + /// + /// + /// + /// This allows an object to defer activation of its options until all + /// options have been set. This is required for components which have + /// related options that remain ambiguous until all are set. + /// + /// + /// If a component implements this interface then this method must be called + /// after its properties have been set before the component can be used. + /// + /// + void ActivateOptions(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs index e039d00b9e7..037583e6814 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs @@ -1,217 +1,211 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Reflection; - -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core -{ - #region LoggerRepositoryCreationEvent - - /// - /// Delegate used to handle logger repository creation event notifications - /// - /// The which created the repository. - /// The event args - /// that holds the instance that has been created. - /// - /// - /// Delegate used to handle logger repository creation event notifications. - /// - /// - public delegate void LoggerRepositoryCreationEventHandler(object sender, LoggerRepositoryCreationEventArgs e); - - /// - /// Provides data for the event. - /// - /// - /// - /// A - /// event is raised every time a is created. - /// - /// - public class LoggerRepositoryCreationEventArgs : EventArgs - { - /// - /// The created - /// - private ILoggerRepository m_repository; - - /// - /// Construct instance using specified - /// - /// the that has been created - /// - /// - /// Construct instance using specified - /// - /// - public LoggerRepositoryCreationEventArgs(ILoggerRepository repository) - { - m_repository = repository; - } - - /// - /// The that has been created - /// - /// - /// The that has been created - /// - /// - /// - /// The that has been created - /// - /// - public ILoggerRepository LoggerRepository - { - get { return m_repository; } - } - } +{ + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Reflection; + + using log4net.Repository; + + /// + /// Delegate used to handle logger repository creation event notifications. + /// + /// The which created the repository. + /// The event args + /// that holds the instance that has been created. + /// + /// + /// Delegate used to handle logger repository creation event notifications. + /// + /// + public delegate void LoggerRepositoryCreationEventHandler(object sender, LoggerRepositoryCreationEventArgs e); - #endregion + /// + /// Provides data for the event. + /// + /// + /// + /// A + /// event is raised every time a is created. + /// + /// + public class LoggerRepositoryCreationEventArgs : EventArgs + { + /// + /// The created. + /// + private ILoggerRepository m_repository; + + /// + /// Initializes a new instance of the class. + /// Construct instance using specified. + /// + /// the that has been created. + /// + /// + /// Construct instance using specified. + /// + /// + public LoggerRepositoryCreationEventArgs(ILoggerRepository repository) + { + this.m_repository = repository; + } - /// - /// Interface used by the to select the . - /// - /// - /// - /// The uses a - /// to specify the policy for selecting the correct - /// to return to the caller. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IRepositorySelector - { - /// - /// Gets the for the specified assembly. - /// - /// The assembly to use to lookup to the - /// The for the assembly. - /// - /// - /// Gets the for the specified assembly. - /// - /// - /// How the association between and - /// is made is not defined. The implementation may choose any method for - /// this association. The results of this method must be repeatable, i.e. - /// when called again with the same arguments the result must be the - /// save value. - /// - /// - ILoggerRepository GetRepository(Assembly assembly); + /// + /// Gets the that has been created. + /// + /// + /// The that has been created. + /// + /// + /// + /// The that has been created. + /// + /// + public ILoggerRepository LoggerRepository + { + get { return this.m_repository; } + } + } + + /// + /// Interface used by the to select the . + /// + /// + /// + /// The uses a + /// to specify the policy for selecting the correct + /// to return to the caller. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IRepositorySelector + { + /// + /// Gets the for the specified assembly. + /// + /// The assembly to use to lookup to the . + /// The for the assembly. + /// + /// + /// Gets the for the specified assembly. + /// + /// + /// How the association between and + /// is made is not defined. The implementation may choose any method for + /// this association. The results of this method must be repeatable, i.e. + /// when called again with the same arguments the result must be the + /// save value. + /// + /// + ILoggerRepository GetRepository(Assembly assembly); - /// - /// Gets the named . - /// - /// The name to use to lookup to the . - /// The named - /// - /// Lookup a named . This is the repository created by - /// calling . - /// - ILoggerRepository GetRepository(string repositoryName); + /// + /// Gets the named . + /// + /// The name to use to lookup to the . + /// The named . + /// + /// Lookup a named . This is the repository created by + /// calling . + /// + ILoggerRepository GetRepository(string repositoryName); - /// - /// Creates a new repository for the assembly specified. - /// - /// The assembly to use to create the domain to associate with the . - /// The type of repository to create, must implement . - /// The repository created. - /// - /// - /// The created will be associated with the domain - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// How the association between and - /// is made is not defined. The implementation may choose any method for - /// this association. - /// - /// - ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType); + /// + /// Creates a new repository for the assembly specified. + /// + /// The assembly to use to create the domain to associate with the . + /// The type of repository to create, must implement . + /// The repository created. + /// + /// + /// The created will be associated with the domain + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// How the association between and + /// is made is not defined. The implementation may choose any method for + /// this association. + /// + /// + ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType); - /// - /// Creates a new repository with the name specified. - /// - /// The name to associate with the . - /// The type of repository to create, must implement . - /// The repository created. - /// - /// - /// The created will be associated with the name - /// specified such that a call to with the - /// same name will return the same repository instance. - /// - /// - ILoggerRepository CreateRepository(string repositoryName, Type repositoryType); + /// + /// Creates a new repository with the name specified. + /// + /// The name to associate with the . + /// The type of repository to create, must implement . + /// The repository created. + /// + /// + /// The created will be associated with the name + /// specified such that a call to with the + /// same name will return the same repository instance. + /// + /// + ILoggerRepository CreateRepository(string repositoryName, Type repositoryType); - /// - /// Test if a named repository exists - /// - /// the named repository to check - /// true if the repository exists - /// - /// - /// Test if a named repository exists. Use - /// to create a new repository and to retrieve - /// a repository. - /// - /// - bool ExistsRepository(string repositoryName); + /// + /// Test if a named repository exists. + /// + /// the named repository to check. + /// true if the repository exists. + /// + /// + /// Test if a named repository exists. Use + /// to create a new repository and to retrieve + /// a repository. + /// + /// + bool ExistsRepository(string repositoryName); - /// - /// Gets an array of all currently defined repositories. - /// - /// - /// An array of the instances created by - /// this . - /// - /// - /// Gets an array of all of the repositories created by this selector. - /// - /// - ILoggerRepository[] GetAllRepositories(); + /// + /// Gets an array of all currently defined repositories. + /// + /// + /// An array of the instances created by + /// this . + /// + /// + /// Gets an array of all of the repositories created by this selector. + /// + /// + ILoggerRepository[] GetAllRepositories(); - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// - /// Event raised when a new repository is created. - /// The event source will be this selector. The event args will - /// be a which - /// holds the newly created . - /// - /// - event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent; - } + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// + /// Event raised when a new repository is created. + /// The event source will be this selector. The event args will + /// be a which + /// holds the newly created . + /// + /// + event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs index 6863ed6471a..80a1c7c9d15 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs @@ -1,55 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Test if an triggers an action - /// - /// - /// - /// Implementations of this interface allow certain appenders to decide - /// when to perform an appender specific action. - /// - /// - /// The action or behavior triggered is defined by the implementation. - /// - /// - /// Nicko Cadell - public interface ITriggeringEventEvaluator - { - /// - /// Test if this event triggers the action - /// - /// The event to check - /// true if this event triggers the action, otherwise false - /// - /// - /// Return true if this event triggers the action - /// - /// - bool IsTriggeringEvent(LoggingEvent loggingEvent); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Test if an triggers an action. + /// + /// + /// + /// Implementations of this interface allow certain appenders to decide + /// when to perform an appender specific action. + /// + /// + /// The action or behavior triggered is defined by the implementation. + /// + /// + /// Nicko Cadell. + public interface ITriggeringEventEvaluator + { + /// + /// Test if this event triggers the action. + /// + /// The event to check. + /// true if this event triggers the action, otherwise false. + /// + /// + /// Return true if this event triggers the action. + /// + /// + bool IsTriggeringEvent(LoggingEvent loggingEvent); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs index 12a5cfa300f..f9c87deb74f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs @@ -1,619 +1,590 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Defines the default set of levels recognized by the system. - /// - /// - /// - /// Each has an associated . - /// - /// - /// Levels have a numeric that defines the relative - /// ordering between levels. Two Levels with the same - /// are deemed to be equivalent. - /// - /// - /// The levels that are recognized by log4net are set for each - /// and each repository can have different levels defined. The levels are stored - /// in the on the repository. Levels are - /// looked up by name from the . - /// - /// - /// When logging at level INFO the actual level used is not but - /// the value of LoggerRepository.LevelMap["INFO"]. The default value for this is - /// , but this can be changed by reconfiguring the level map. - /// - /// - /// Each level has a in addition to its . The - /// is the string that is written into the output log. By default - /// the display name is the same as the level name, but this can be used to alias levels - /// or to localize the log output. - /// - /// - /// Some of the predefined levels recognized by the system are: - /// - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// Defines the default set of levels recognized by the system. + /// + /// + /// + /// Each has an associated . + /// + /// + /// Levels have a numeric that defines the relative + /// ordering between levels. Two Levels with the same + /// are deemed to be equivalent. + /// + /// + /// The levels that are recognized by log4net are set for each + /// and each repository can have different levels defined. The levels are stored + /// in the on the repository. Levels are + /// looked up by name from the . + /// + /// + /// When logging at level INFO the actual level used is not but + /// the value of LoggerRepository.LevelMap["INFO"]. The default value for this is + /// , but this can be changed by reconfiguring the level map. + /// + /// + /// Each level has a in addition to its . The + /// is the string that is written into the output log. By default + /// the display name is the same as the level name, but this can be used to alias levels + /// or to localize the log output. + /// + /// + /// Some of the predefined levels recognized by the system are: + /// + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if !NETCF - [Serializable] + [Serializable] #endif - sealed public class Level : IComparable - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// Integer value for this level, higher values represent more severe levels. - /// The string name of this level. - /// The display name for this level. This may be localized or otherwise different from the name - /// - /// - /// Initializes a new instance of the class with - /// the specified level name and value. - /// - /// - public Level(int level, string levelName, string displayName) - { - if (levelName == null) - { - throw new ArgumentNullException("levelName"); - } - if (displayName == null) - { - throw new ArgumentNullException("displayName"); - } - - m_levelValue = level; + public sealed class Level : IComparable + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// Integer value for this level, higher values represent more severe levels. + /// The string name of this level. + /// The display name for this level. This may be localized or otherwise different from the name. + /// + /// + /// Initializes a new instance of the class with + /// the specified level name and value. + /// + /// + public Level(int level, string levelName, string displayName) + { + if (levelName == null) + { + throw new ArgumentNullException("levelName"); + } + + if (displayName == null) + { + throw new ArgumentNullException("displayName"); + } + + this.m_levelValue = level; #if NETSTANDARD1_3 m_levelName = levelName; #else - m_levelName = string.Intern(levelName); + this.m_levelName = string.Intern(levelName); #endif - m_levelDisplayName = displayName; - } - - /// - /// Constructor - /// - /// Integer value for this level, higher values represent more severe levels. - /// The string name of this level. - /// - /// - /// Initializes a new instance of the class with - /// the specified level name and value. - /// - /// - public Level(int level, string levelName) : this(level, levelName, levelName) - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the name of this level. - /// - /// - /// The name of this level. - /// - /// - /// - /// Gets the name of this level. - /// - /// - public string Name - { - get { return m_levelName; } - } - - /// - /// Gets the value of this level. - /// - /// - /// The value of this level. - /// - /// - /// - /// Gets the value of this level. - /// - /// - public int Value - { - get { return m_levelValue; } - } - - /// - /// Gets the display name of this level. - /// - /// - /// The display name of this level. - /// - /// - /// - /// Gets the display name of this level. - /// - /// - public string DisplayName - { - get { return m_levelDisplayName; } - } - - #endregion Public Instance Properties - - #region Override implementation of Object - - /// - /// Returns the representation of the current - /// . - /// - /// - /// A representation of the current . - /// - /// - /// - /// Returns the level . - /// - /// - override public string ToString() - { - return m_levelName; - } - - /// - /// Compares levels. - /// - /// The object to compare against. - /// true if the objects are equal. - /// - /// - /// Compares the levels of instances, and - /// defers to base class if the target object is not a - /// instance. - /// - /// - override public bool Equals(object o) - { - Level otherLevel = o as Level; - if (otherLevel != null) - { - return m_levelValue == otherLevel.m_levelValue; - } - else - { - return base.Equals(o); - } - } - - /// - /// Returns a hash code - /// - /// A hash code for the current . - /// - /// - /// Returns a hash code suitable for use in hashing algorithms and data - /// structures like a hash table. - /// - /// - /// Returns the hash code of the level . - /// - /// - override public int GetHashCode() - { - return m_levelValue; - } - - #endregion Override implementation of Object - - #region Implementation of IComparable - - /// - /// Compares this instance to a specified object and returns an - /// indication of their relative values. - /// - /// A instance or to compare with this instance. - /// - /// A 32-bit signed integer that indicates the relative order of the - /// values compared. The return value has these meanings: - /// - /// - /// Value - /// Meaning - /// - /// - /// Less than zero - /// This instance is less than . - /// - /// - /// Zero - /// This instance is equal to . - /// - /// - /// Greater than zero - /// - /// This instance is greater than . - /// -or- - /// is . - /// - /// - /// - /// - /// - /// - /// must be an instance of - /// or ; otherwise, an exception is thrown. - /// - /// - /// is not a . - public int CompareTo(object r) - { - Level target = r as Level; - if (target != null) - { - return Compare(this, target); - } - throw new ArgumentException("Parameter: r, Value: [" + r + "] is not an instance of Level"); - } - - #endregion Implementation of IComparable - - #region Operators - - /// - /// Returns a value indicating whether a specified - /// is greater than another specified . - /// - /// A - /// A - /// - /// true if is greater than - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator > (Level l, Level r) - { - return l.m_levelValue > r.m_levelValue; - } - - /// - /// Returns a value indicating whether a specified - /// is less than another specified . - /// - /// A - /// A - /// - /// true if is less than - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator < (Level l, Level r) - { - return l.m_levelValue < r.m_levelValue; - } - - /// - /// Returns a value indicating whether a specified - /// is greater than or equal to another specified . - /// - /// A - /// A - /// - /// true if is greater than or equal to - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator >= (Level l, Level r) - { - return l.m_levelValue >= r.m_levelValue; - } - - /// - /// Returns a value indicating whether a specified - /// is less than or equal to another specified . - /// - /// A - /// A - /// - /// true if is less than or equal to - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator <= (Level l, Level r) - { - return l.m_levelValue <= r.m_levelValue; - } - - /// - /// Returns a value indicating whether two specified - /// objects have the same value. - /// - /// A or . - /// A or . - /// - /// true if the value of is the same as the - /// value of ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator == (Level l, Level r) - { - if (((object)l) != null && ((object)r) != null) - { - return l.m_levelValue == r.m_levelValue; - } - else - { - return ((object) l) == ((object) r); - } - } + this.m_levelDisplayName = displayName; + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// Integer value for this level, higher values represent more severe levels. + /// The string name of this level. + /// + /// + /// Initializes a new instance of the class with + /// the specified level name and value. + /// + /// + public Level(int level, string levelName) + : this(level, levelName, levelName) + { + } + + /// + /// Gets the name of this level. + /// + /// + /// The name of this level. + /// + /// + /// + /// Gets the name of this level. + /// + /// + public string Name + { + get { return this.m_levelName; } + } - /// - /// Returns a value indicating whether two specified - /// objects have different values. - /// - /// A or . - /// A or . - /// - /// true if the value of is different from - /// the value of ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator != (Level l, Level r) - { - return !(l==r); - } + /// + /// Gets the value of this level. + /// + /// + /// The value of this level. + /// + /// + /// + /// Gets the value of this level. + /// + /// + public int Value + { + get { return this.m_levelValue; } + } - #endregion Operators + /// + /// Gets the display name of this level. + /// + /// + /// The display name of this level. + /// + /// + /// + /// Gets the display name of this level. + /// + /// + public string DisplayName + { + get { return this.m_levelDisplayName; } + } + + /// + /// Returns the representation of the current + /// . + /// + /// + /// A representation of the current . + /// + /// + /// + /// Returns the level . + /// + /// + public override string ToString() + { + return this.m_levelName; + } - #region Public Static Methods + /// + /// Compares levels. + /// + /// The object to compare against. + /// true if the objects are equal. + /// + /// + /// Compares the levels of instances, and + /// defers to base class if the target object is not a + /// instance. + /// + /// + public override bool Equals(object o) + { + Level otherLevel = o as Level; + if (otherLevel != null) + { + return this.m_levelValue == otherLevel.m_levelValue; + } + else + { + return base.Equals(o); + } + } - /// - /// Compares two specified instances. - /// - /// The first to compare. - /// The second to compare. - /// - /// A 32-bit signed integer that indicates the relative order of the - /// two values compared. The return value has these meanings: - /// - /// - /// Value - /// Meaning - /// - /// - /// Less than zero - /// is less than . - /// - /// - /// Zero - /// is equal to . - /// - /// - /// Greater than zero - /// is greater than . - /// - /// - /// - /// - /// - /// Compares two levels. - /// - /// - public static int Compare(Level l, Level r) - { - // Reference equals - if ((object)l == (object)r) - { - return 0; - } + /// + /// Returns a hash code. + /// + /// A hash code for the current . + /// + /// + /// Returns a hash code suitable for use in hashing algorithms and data + /// structures like a hash table. + /// + /// + /// Returns the hash code of the level . + /// + /// + public override int GetHashCode() + { + return this.m_levelValue; + } + + /// + /// Compares this instance to a specified object and returns an + /// indication of their relative values. + /// + /// A instance or to compare with this instance. + /// + /// A 32-bit signed integer that indicates the relative order of the + /// values compared. The return value has these meanings: + /// + /// + /// Value + /// Meaning + /// + /// + /// Less than zero + /// This instance is less than . + /// + /// + /// Zero + /// This instance is equal to . + /// + /// + /// Greater than zero + /// + /// This instance is greater than . + /// -or- + /// is . + /// + /// + /// + /// + /// + /// + /// must be an instance of + /// or ; otherwise, an exception is thrown. + /// + /// + /// is not a . + public int CompareTo(object r) + { + Level target = r as Level; + if (target != null) + { + return Compare(this, target); + } + + throw new ArgumentException("Parameter: r, Value: [" + r + "] is not an instance of Level"); + } + + /// + /// Returns a value indicating whether a specified + /// is greater than another specified . + /// + /// A . + /// A . + /// + /// true if is greater than + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator >(Level l, Level r) + { + return l.m_levelValue > r.m_levelValue; + } - if (l == null && r == null) - { - return 0; - } - if (l == null) - { - return -1; - } - if (r == null) - { - return 1; - } + /// + /// Returns a value indicating whether a specified + /// is less than another specified . + /// + /// A . + /// A . + /// + /// true if is less than + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator <(Level l, Level r) + { + return l.m_levelValue < r.m_levelValue; + } - return l.m_levelValue.CompareTo(r.m_levelValue); - } + /// + /// Returns a value indicating whether a specified + /// is greater than or equal to another specified . + /// + /// A . + /// A . + /// + /// true if is greater than or equal to + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator >=(Level l, Level r) + { + return l.m_levelValue >= r.m_levelValue; + } - #endregion Public Static Methods + /// + /// Returns a value indicating whether a specified + /// is less than or equal to another specified . + /// + /// A . + /// A . + /// + /// true if is less than or equal to + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator <=(Level l, Level r) + { + return l.m_levelValue <= r.m_levelValue; + } - #region Public Static Fields + /// + /// Returns a value indicating whether two specified + /// objects have the same value. + /// + /// A or . + /// A or . + /// + /// true if the value of is the same as the + /// value of ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator ==(Level l, Level r) + { + if (((object)l) != null && ((object)r) != null) + { + return l.m_levelValue == r.m_levelValue; + } + else + { + return ((object)l) == ((object)r); + } + } - /// - /// The level designates a higher level than all the rest. - /// - public readonly static Level Off = new Level(int.MaxValue, "OFF"); + /// + /// Returns a value indicating whether two specified + /// objects have different values. + /// + /// A or . + /// A or . + /// + /// true if the value of is different from + /// the value of ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator !=(Level l, Level r) + { + return !(l == r); + } + + /// + /// Compares two specified instances. + /// + /// The first to compare. + /// The second to compare. + /// + /// A 32-bit signed integer that indicates the relative order of the + /// two values compared. The return value has these meanings: + /// + /// + /// Value + /// Meaning + /// + /// + /// Less than zero + /// is less than . + /// + /// + /// Zero + /// is equal to . + /// + /// + /// Greater than zero + /// is greater than . + /// + /// + /// + /// + /// + /// Compares two levels. + /// + /// + public static int Compare(Level l, Level r) + { + // Reference equals + if ((object)l == (object)r) + { + return 0; + } + + if (l == null && r == null) + { + return 0; + } + + if (l == null) + { + return -1; + } + + if (r == null) + { + return 1; + } + + return l.m_levelValue.CompareTo(r.m_levelValue); + } + + /// + /// The level designates a higher level than all the rest. + /// + public static readonly Level Off = new Level(int.MaxValue, "OFF"); /// - /// The level designates very severe error events. + /// The level designates very severe error events. /// System unusable, emergencies. /// - public readonly static Level Log4Net_Debug = new Level(120000, "log4net:DEBUG"); - - /// - /// The level designates very severe error events. - /// System unusable, emergencies. - /// - public readonly static Level Emergency = new Level(120000, "EMERGENCY"); - - /// - /// The level designates very severe error events - /// that will presumably lead the application to abort. - /// - public readonly static Level Fatal = new Level(110000, "FATAL"); + public static readonly Level Log4Net_Debug = new Level(120000, "log4net:DEBUG"); - /// - /// The level designates very severe error events. - /// Take immediate action, alerts. - /// - public readonly static Level Alert = new Level(100000, "ALERT"); - - /// - /// The level designates very severe error events. - /// Critical condition, critical. - /// - public readonly static Level Critical = new Level(90000, "CRITICAL"); - - /// - /// The level designates very severe error events. - /// - public readonly static Level Severe = new Level(80000, "SEVERE"); + /// + /// The level designates very severe error events. + /// System unusable, emergencies. + /// + public static readonly Level Emergency = new Level(120000, "EMERGENCY"); - /// - /// The level designates error events that might - /// still allow the application to continue running. - /// - public readonly static Level Error = new Level(70000, "ERROR"); + /// + /// The level designates very severe error events + /// that will presumably lead the application to abort. + /// + public static readonly Level Fatal = new Level(110000, "FATAL"); - /// - /// The level designates potentially harmful - /// situations. - /// - public readonly static Level Warn = new Level(60000, "WARN"); + /// + /// The level designates very severe error events. + /// Take immediate action, alerts. + /// + public static readonly Level Alert = new Level(100000, "ALERT"); - /// - /// The level designates informational messages - /// that highlight the progress of the application at the highest level. - /// - public readonly static Level Notice = new Level(50000, "NOTICE"); + /// + /// The level designates very severe error events. + /// Critical condition, critical. + /// + public static readonly Level Critical = new Level(90000, "CRITICAL"); - /// - /// The level designates informational messages that - /// highlight the progress of the application at coarse-grained level. - /// - public readonly static Level Info = new Level(40000, "INFO"); + /// + /// The level designates very severe error events. + /// + public static readonly Level Severe = new Level(80000, "SEVERE"); - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public readonly static Level Debug = new Level(30000, "DEBUG"); + /// + /// The level designates error events that might + /// still allow the application to continue running. + /// + public static readonly Level Error = new Level(70000, "ERROR"); - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public readonly static Level Fine = new Level(30000, "FINE"); + /// + /// The level designates potentially harmful + /// situations. + /// + public static readonly Level Warn = new Level(60000, "WARN"); - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public readonly static Level Trace = new Level(20000, "TRACE"); + /// + /// The level designates informational messages + /// that highlight the progress of the application at the highest level. + /// + public static readonly Level Notice = new Level(50000, "NOTICE"); - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public readonly static Level Finer = new Level(20000, "FINER"); + /// + /// The level designates informational messages that + /// highlight the progress of the application at coarse-grained level. + /// + public static readonly Level Info = new Level(40000, "INFO"); - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public readonly static Level Verbose = new Level(10000, "VERBOSE"); + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Debug = new Level(30000, "DEBUG"); - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public readonly static Level Finest = new Level(10000, "FINEST"); + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Fine = new Level(30000, "FINE"); - /// - /// The level designates the lowest level possible. - /// - public readonly static Level All = new Level(int.MinValue, "ALL"); + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Trace = new Level(20000, "TRACE"); - #endregion Public Static Fields + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Finer = new Level(20000, "FINER"); - #region Private Instance Fields + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Verbose = new Level(10000, "VERBOSE"); - private readonly int m_levelValue; - private readonly string m_levelName; - private readonly string m_levelDisplayName; + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Finest = new Level(10000, "FINEST"); - #endregion Private Instance Fields - } + /// + /// The level designates the lowest level possible. + /// + public static readonly Level All = new Level(int.MinValue, "ALL"); + private readonly int m_levelValue; + private readonly string m_levelName; + private readonly string m_levelDisplayName; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs index b0b910a751e..d60a3478db0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs @@ -1,864 +1,780 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// A strongly-typed collection of objects. - /// - /// Nicko Cadell - public class LevelCollection : ICollection, IList, IEnumerable + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// A strongly-typed collection of objects. + /// + /// Nicko Cadell. + public class LevelCollection : ICollection, IList, IEnumerable #if !NETSTANDARD1_3 - , ICloneable + , ICloneable #endif - { - #region Interfaces - - /// - /// Supports type-safe iteration over a . - /// - public interface ILevelCollectionEnumerator - { - /// - /// Gets the current element in the collection. - /// - Level Current { get; } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - bool MoveNext(); - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - void Reset(); - } - - #endregion - - private const int DEFAULT_CAPACITY = 16; - - #region Implementation (data) - - private Level[] m_array; - private int m_count = 0; - private int m_version = 0; - - #endregion - - #region Static Wrappers - - /// - /// Creates a read-only wrapper for a LevelCollection instance. - /// - /// list to create a readonly wrapper arround - /// - /// A LevelCollection wrapper that is read-only. - /// - public static LevelCollection ReadOnly(LevelCollection list) - { - if(list==null) throw new ArgumentNullException("list"); - - return new ReadOnlyLevelCollection(list); - } - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the LevelCollection class - /// that is empty and has the default initial capacity. - /// - public LevelCollection() - { - m_array = new Level[DEFAULT_CAPACITY]; - } - - /// - /// Initializes a new instance of the LevelCollection class - /// that has the specified initial capacity. - /// - /// - /// The number of elements that the new LevelCollection is initially capable of storing. - /// - public LevelCollection(int capacity) - { - m_array = new Level[capacity]; - } - - /// - /// Initializes a new instance of the LevelCollection class - /// that contains elements copied from the specified LevelCollection. - /// - /// The LevelCollection whose elements are copied to the new collection. - public LevelCollection(LevelCollection c) - { - m_array = new Level[c.Count]; - AddRange(c); - } - - /// - /// Initializes a new instance of the LevelCollection class - /// that contains elements copied from the specified array. - /// - /// The array whose elements are copied to the new list. - public LevelCollection(Level[] a) - { - m_array = new Level[a.Length]; - AddRange(a); - } - - /// - /// Initializes a new instance of the LevelCollection class - /// that contains elements copied from the specified collection. - /// - /// The collection whose elements are copied to the new list. - public LevelCollection(ICollection col) - { - m_array = new Level[col.Count]; - AddRange(col); - } - - /// - /// Type visible only to our subclasses - /// Used to access protected constructor - /// - protected internal enum Tag - { - /// - /// A value - /// - Default - } - - /// - /// Allow subclasses to avoid our default constructors - /// - /// - protected internal LevelCollection(Tag tag) - { - m_array = null; - } - #endregion - - #region Operations (type-safe ICollection) - - /// - /// Gets the number of elements actually contained in the LevelCollection. - /// - public virtual int Count - { - get { return m_count; } - } - - /// - /// Copies the entire LevelCollection to a one-dimensional - /// array. - /// - /// The one-dimensional array to copy to. - public virtual void CopyTo(Level[] array) - { - this.CopyTo(array, 0); - } - - /// - /// Copies the entire LevelCollection to a one-dimensional - /// array, starting at the specified index of the target array. - /// - /// The one-dimensional array to copy to. - /// The zero-based index in at which copying begins. - public virtual void CopyTo(Level[] array, int start) - { - if (m_count > array.GetUpperBound(0) + 1 - start) - { - throw new System.ArgumentException("Destination array was not long enough."); - } - - Array.Copy(m_array, 0, array, start, m_count); - } - - /// - /// Gets a value indicating whether access to the collection is synchronized (thread-safe). - /// - /// false, because the backing type is an array, which is never thread-safe. - public virtual bool IsSynchronized - { - get { return false; } - } - - /// - /// Gets an object that can be used to synchronize access to the collection. - /// - public virtual object SyncRoot - { - get { return m_array; } - } - - #endregion - - #region Operations (type-safe IList) - - /// - /// Gets or sets the at the specified index. - /// - /// The zero-based index of the element to get or set. - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - public virtual Level this[int index] - { - get - { - ValidateIndex(index); // throws - return m_array[index]; - } - set - { - ValidateIndex(index); // throws - ++m_version; - m_array[index] = value; - } - } - - /// - /// Adds a to the end of the LevelCollection. - /// - /// The to be added to the end of the LevelCollection. - /// The index at which the value has been added. - public virtual int Add(Level item) - { - if (m_count == m_array.Length) - { - EnsureCapacity(m_count + 1); - } - - m_array[m_count] = item; - m_version++; - - return m_count++; - } - - /// - /// Removes all elements from the LevelCollection. - /// - public virtual void Clear() - { - ++m_version; - m_array = new Level[DEFAULT_CAPACITY]; - m_count = 0; - } - - /// - /// Creates a shallow copy of the . - /// - /// A new with a shallow copy of the collection data. - public virtual object Clone() - { - LevelCollection newCol = new LevelCollection(m_count); - Array.Copy(m_array, 0, newCol.m_array, 0, m_count); - newCol.m_count = m_count; - newCol.m_version = m_version; - - return newCol; - } - - /// - /// Determines whether a given is in the LevelCollection. - /// - /// The to check for. - /// true if is found in the LevelCollection; otherwise, false. - public virtual bool Contains(Level item) - { - for (int i=0; i != m_count; ++i) - { - if (m_array[i].Equals(item)) - { - return true; - } - } - return false; - } - - /// - /// Returns the zero-based index of the first occurrence of a - /// in the LevelCollection. - /// - /// The to locate in the LevelCollection. - /// - /// The zero-based index of the first occurrence of - /// in the entire LevelCollection, if found; otherwise, -1. - /// - public virtual int IndexOf(Level item) - { - for (int i=0; i != m_count; ++i) - { - if (m_array[i].Equals(item)) - { - return i; - } - } - return -1; - } - - /// - /// Inserts an element into the LevelCollection at the specified index. - /// - /// The zero-based index at which should be inserted. - /// The to insert. - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - public virtual void Insert(int index, Level item) - { - ValidateIndex(index, true); // throws - - if (m_count == m_array.Length) - { - EnsureCapacity(m_count + 1); - } - - if (index < m_count) - { - Array.Copy(m_array, index, m_array, index + 1, m_count - index); - } - - m_array[index] = item; - m_count++; - m_version++; - } - - /// - /// Removes the first occurrence of a specific from the LevelCollection. - /// - /// The to remove from the LevelCollection. - /// - /// The specified was not found in the LevelCollection. - /// - public virtual void Remove(Level item) - { - int i = IndexOf(item); - if (i < 0) - { - throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); - } - - ++m_version; - RemoveAt(i); - } - - /// - /// Removes the element at the specified index of the LevelCollection. - /// - /// The zero-based index of the element to remove. - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - public virtual void RemoveAt(int index) - { - ValidateIndex(index); // throws - - m_count--; - - if (index < m_count) - { - Array.Copy(m_array, index + 1, m_array, index, m_count - index); - } - - // We can't set the deleted entry equal to null, because it might be a value type. - // Instead, we'll create an empty single-element array of the right type and copy it - // over the entry we want to erase. - Level[] temp = new Level[1]; - Array.Copy(temp, 0, m_array, m_count, 1); - m_version++; - } - - /// - /// Gets a value indicating whether the collection has a fixed size. - /// - /// true if the collection has a fixed size; otherwise, false. The default is false - public virtual bool IsFixedSize - { - get { return false; } - } - - /// - /// Gets a value indicating whether the IList is read-only. - /// - /// true if the collection is read-only; otherwise, false. The default is false - public virtual bool IsReadOnly - { - get { return false; } - } - - #endregion - - #region Operations (type-safe IEnumerable) - - /// - /// Returns an enumerator that can iterate through the LevelCollection. - /// - /// An for the entire LevelCollection. - public virtual ILevelCollectionEnumerator GetEnumerator() - { - return new Enumerator(this); - } - - #endregion - - #region Public helpers (just to mimic some nice features of ArrayList) - - /// - /// Gets or sets the number of elements the LevelCollection can contain. - /// - public virtual int Capacity - { - get - { - return m_array.Length; - } - set - { - if (value < m_count) - { - value = m_count; - } - - if (value != m_array.Length) - { - if (value > 0) - { - Level[] temp = new Level[value]; - Array.Copy(m_array, 0, temp, 0, m_count); - m_array = temp; - } - else - { - m_array = new Level[DEFAULT_CAPACITY]; - } - } - } - } - - /// - /// Adds the elements of another LevelCollection to the current LevelCollection. - /// - /// The LevelCollection whose elements should be added to the end of the current LevelCollection. - /// The new of the LevelCollection. - public virtual int AddRange(LevelCollection x) - { - if (m_count + x.Count >= m_array.Length) - { - EnsureCapacity(m_count + x.Count); - } - - Array.Copy(x.m_array, 0, m_array, m_count, x.Count); - m_count += x.Count; - m_version++; - - return m_count; - } - - /// - /// Adds the elements of a array to the current LevelCollection. - /// - /// The array whose elements should be added to the end of the LevelCollection. - /// The new of the LevelCollection. - public virtual int AddRange(Level[] x) - { - if (m_count + x.Length >= m_array.Length) - { - EnsureCapacity(m_count + x.Length); - } - - Array.Copy(x, 0, m_array, m_count, x.Length); - m_count += x.Length; - m_version++; - - return m_count; - } - - /// - /// Adds the elements of a collection to the current LevelCollection. - /// - /// The collection whose elements should be added to the end of the LevelCollection. - /// The new of the LevelCollection. - public virtual int AddRange(ICollection col) - { - if (m_count + col.Count >= m_array.Length) - { - EnsureCapacity(m_count + col.Count); - } - - foreach(object item in col) - { - Add((Level)item); - } - - return m_count; - } - - /// - /// Sets the capacity to the actual number of elements. - /// - public virtual void TrimToSize() - { - this.Capacity = m_count; - } - - #endregion - - #region Implementation (helpers) - - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i) - { - ValidateIndex(i, false); - } - - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i, bool allowEqualEnd) - { - int max = (allowEqualEnd) ? (m_count) : (m_count-1); - if (i < 0 || i > max) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); - } - } - - private void EnsureCapacity(int min) - { - int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); - if (newCapacity < min) - { - newCapacity = min; - } - - this.Capacity = newCapacity; - } - - #endregion - - #region Implementation (ICollection) - - void ICollection.CopyTo(Array array, int start) - { - Array.Copy(m_array, 0, array, start, m_count); - } - - #endregion - - #region Implementation (IList) - - object IList.this[int i] - { - get { return (object)this[i]; } - set { this[i] = (Level)value; } - } - - int IList.Add(object x) - { - return this.Add((Level)x); - } - - bool IList.Contains(object x) - { - return this.Contains((Level)x); - } - - int IList.IndexOf(object x) - { - return this.IndexOf((Level)x); - } - - void IList.Insert(int pos, object x) - { - this.Insert(pos, (Level)x); - } - - void IList.Remove(object x) - { - this.Remove((Level)x); - } - - void IList.RemoveAt(int pos) - { - this.RemoveAt(pos); - } - - #endregion - - #region Implementation (IEnumerable) - - IEnumerator IEnumerable.GetEnumerator() - { - return (IEnumerator)(this.GetEnumerator()); - } - - #endregion - - #region Nested enumerator class - - /// - /// Supports simple iteration over a . - /// - private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator - { - #region Implementation (data) - - private readonly LevelCollection m_collection; - private int m_index; - private int m_version; - - #endregion - - #region Construction - - /// - /// Initializes a new instance of the Enumerator class. - /// - /// - internal Enumerator(LevelCollection tc) - { - m_collection = tc; - m_index = -1; - m_version = tc.m_version; - } - - #endregion - - #region Operations (type-safe IEnumerator) - - /// - /// Gets the current element in the collection. - /// - public Level Current - { - get { return m_collection[m_index]; } - } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - public bool MoveNext() - { - if (m_version != m_collection.m_version) - { - throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); - } - - ++m_index; - return (m_index < m_collection.Count); - } - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - public void Reset() - { - m_index = -1; - } - - #endregion - - #region Implementation (IEnumerator) - - object IEnumerator.Current - { - get { return this.Current; } - } - - #endregion - } - - #endregion - - #region Nested Read Only Wrapper class - - private sealed class ReadOnlyLevelCollection : LevelCollection - { - #region Implementation (data) - - private readonly LevelCollection m_collection; - - #endregion - - #region Construction - - internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default) - { - m_collection = list; - } - - #endregion - - #region Type-safe ICollection - - public override void CopyTo(Level[] array) - { - m_collection.CopyTo(array); - } - - public override void CopyTo(Level[] array, int start) - { - m_collection.CopyTo(array,start); - } - public override int Count - { - get { return m_collection.Count; } - } - - public override bool IsSynchronized - { - get { return m_collection.IsSynchronized; } - } - - public override object SyncRoot - { - get { return this.m_collection.SyncRoot; } - } - - #endregion - - #region Type-safe IList - - public override Level this[int i] - { - get { return m_collection[i]; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int Add(Level x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Clear() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool Contains(Level x) - { - return m_collection.Contains(x); - } - - public override int IndexOf(Level x) - { - return m_collection.IndexOf(x); - } - - public override void Insert(int pos, Level x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Remove(Level x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void RemoveAt(int pos) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool IsFixedSize - { - get { return true; } - } - - public override bool IsReadOnly - { - get { return true; } - } - - #endregion - - #region Type-safe IEnumerable - - public override ILevelCollectionEnumerator GetEnumerator() - { - return m_collection.GetEnumerator(); - } - - #endregion - - #region Public Helpers - - // (just to mimic some nice features of ArrayList) - public override int Capacity - { - get { return m_collection.Capacity; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int AddRange(LevelCollection x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override int AddRange(Level[] x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - #endregion - } - - #endregion - } - + { + /// + /// Supports type-safe iteration over a . + /// + public interface ILevelCollectionEnumerator + { + /// + /// Gets the current element in the collection. + /// + Level Current { get; } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + bool MoveNext(); + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + void Reset(); + } + + private const int DEFAULT_CAPACITY = 16; + private Level[] m_array; + private int m_count = 0; + private int m_version = 0; + + /// + /// Creates a read-only wrapper for a LevelCollection instance. + /// + /// list to create a readonly wrapper arround. + /// + /// A LevelCollection wrapper that is read-only. + /// + public static LevelCollection ReadOnly(LevelCollection list) + { + if (list == null) + { + throw new ArgumentNullException("list"); + } + + return new ReadOnlyLevelCollection(list); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the LevelCollection class + /// that is empty and has the default initial capacity. + /// + public LevelCollection() + { + this.m_array = new Level[DEFAULT_CAPACITY]; + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the LevelCollection class + /// that has the specified initial capacity. + /// + /// + /// The number of elements that the new LevelCollection is initially capable of storing. + /// + public LevelCollection(int capacity) + { + this.m_array = new Level[capacity]; + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the LevelCollection class + /// that contains elements copied from the specified LevelCollection. + /// + /// The LevelCollection whose elements are copied to the new collection. + public LevelCollection(LevelCollection c) + { + this.m_array = new Level[c.Count]; + this.AddRange(c); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the LevelCollection class + /// that contains elements copied from the specified array. + /// + /// The array whose elements are copied to the new list. + public LevelCollection(Level[] a) + { + this.m_array = new Level[a.Length]; + this.AddRange(a); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the LevelCollection class + /// that contains elements copied from the specified collection. + /// + /// The collection whose elements are copied to the new list. + public LevelCollection(ICollection col) + { + this.m_array = new Level[col.Count]; + this.AddRange(col); + } + + /// + /// Type visible only to our subclasses + /// Used to access protected constructor. + /// + protected internal enum Tag + { + /// + /// A value + /// + Default, + } + + /// + /// Initializes a new instance of the class. + /// Allow subclasses to avoid our default constructors. + /// + /// + protected internal LevelCollection(Tag tag) + { + this.m_array = null; + } + + /// + /// Gets the number of elements actually contained in the LevelCollection. + /// + public virtual int Count + { + get { return this.m_count; } + } + + /// + /// Copies the entire LevelCollection to a one-dimensional + /// array. + /// + /// The one-dimensional array to copy to. + public virtual void CopyTo(Level[] array) + { + this.CopyTo(array, 0); + } + + /// + /// Copies the entire LevelCollection to a one-dimensional + /// array, starting at the specified index of the target array. + /// + /// The one-dimensional array to copy to. + /// The zero-based index in at which copying begins. + public virtual void CopyTo(Level[] array, int start) + { + if (this.m_count > array.GetUpperBound(0) + 1 - start) + { + throw new System.ArgumentException("Destination array was not long enough."); + } + + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + /// + /// Gets a value indicating whether access to the collection is synchronized (thread-safe). + /// + /// false, because the backing type is an array, which is never thread-safe. + public virtual bool IsSynchronized + { + get { return false; } + } + + /// + /// Gets an object that can be used to synchronize access to the collection. + /// + public virtual object SyncRoot + { + get { return this.m_array; } + } + + /// + /// Gets or sets the at the specified index. + /// + /// The zero-based index of the element to get or set. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual Level this[int index] + { + get + { + this.ValidateIndex(index); // throws + return this.m_array[index]; + } + + set + { + this.ValidateIndex(index); // throws + ++this.m_version; + this.m_array[index] = value; + } + } + + /// + /// Adds a to the end of the LevelCollection. + /// + /// The to be added to the end of the LevelCollection. + /// The index at which the value has been added. + public virtual int Add(Level item) + { + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + this.m_array[this.m_count] = item; + this.m_version++; + + return this.m_count++; + } + + /// + /// Removes all elements from the LevelCollection. + /// + public virtual void Clear() + { + ++this.m_version; + this.m_array = new Level[DEFAULT_CAPACITY]; + this.m_count = 0; + } + + /// + /// Creates a shallow copy of the . + /// + /// A new with a shallow copy of the collection data. + public virtual object Clone() + { + LevelCollection newCol = new LevelCollection(this.m_count); + Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); + newCol.m_count = this.m_count; + newCol.m_version = this.m_version; + + return newCol; + } + + /// + /// Determines whether a given is in the LevelCollection. + /// + /// The to check for. + /// true if is found in the LevelCollection; otherwise, false. + public virtual bool Contains(Level item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return true; + } + } + + return false; + } + + /// + /// Returns the zero-based index of the first occurrence of a + /// in the LevelCollection. + /// + /// The to locate in the LevelCollection. + /// + /// The zero-based index of the first occurrence of + /// in the entire LevelCollection, if found; otherwise, -1. + /// + public virtual int IndexOf(Level item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return i; + } + } + + return -1; + } + + /// + /// Inserts an element into the LevelCollection at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The to insert. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual void Insert(int index, Level item) + { + this.ValidateIndex(index, true); // throws + + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + if (index < this.m_count) + { + Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); + } + + this.m_array[index] = item; + this.m_count++; + this.m_version++; + } + + /// + /// Removes the first occurrence of a specific from the LevelCollection. + /// + /// The to remove from the LevelCollection. + /// + /// The specified was not found in the LevelCollection. + /// + public virtual void Remove(Level item) + { + int i = this.IndexOf(item); + if (i < 0) + { + throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); + } + + ++this.m_version; + this.RemoveAt(i); + } + + /// + /// Removes the element at the specified index of the LevelCollection. + /// + /// The zero-based index of the element to remove. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual void RemoveAt(int index) + { + this.ValidateIndex(index); // throws + + this.m_count--; + + if (index < this.m_count) + { + Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); + } + + // We can't set the deleted entry equal to null, because it might be a value type. + // Instead, we'll create an empty single-element array of the right type and copy it + // over the entry we want to erase. + Level[] temp = new Level[1]; + Array.Copy(temp, 0, this.m_array, this.m_count, 1); + this.m_version++; + } + + /// + /// Gets a value indicating whether the collection has a fixed size. + /// + /// true if the collection has a fixed size; otherwise, false. The default is false. + public virtual bool IsFixedSize + { + get { return false; } + } + + /// + /// Gets a value indicating whether the IList is read-only. + /// + /// true if the collection is read-only; otherwise, false. The default is false. + public virtual bool IsReadOnly + { + get { return false; } + } + + /// + /// Returns an enumerator that can iterate through the LevelCollection. + /// + /// An for the entire LevelCollection. + public virtual ILevelCollectionEnumerator GetEnumerator() + { + return new Enumerator(this); + } + + /// + /// Gets or sets the number of elements the LevelCollection can contain. + /// + public virtual int Capacity + { + get + { + return this.m_array.Length; + } + + set + { + if (value < this.m_count) + { + value = this.m_count; + } + + if (value != this.m_array.Length) + { + if (value > 0) + { + Level[] temp = new Level[value]; + Array.Copy(this.m_array, 0, temp, 0, this.m_count); + this.m_array = temp; + } + else + { + this.m_array = new Level[DEFAULT_CAPACITY]; + } + } + } + } + + /// + /// Adds the elements of another LevelCollection to the current LevelCollection. + /// + /// The LevelCollection whose elements should be added to the end of the current LevelCollection. + /// The new of the LevelCollection. + public virtual int AddRange(LevelCollection x) + { + if (this.m_count + x.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Count); + } + + Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); + this.m_count += x.Count; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a array to the current LevelCollection. + /// + /// The array whose elements should be added to the end of the LevelCollection. + /// The new of the LevelCollection. + public virtual int AddRange(Level[] x) + { + if (this.m_count + x.Length >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Length); + } + + Array.Copy(x, 0, this.m_array, this.m_count, x.Length); + this.m_count += x.Length; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a collection to the current LevelCollection. + /// + /// The collection whose elements should be added to the end of the LevelCollection. + /// The new of the LevelCollection. + public virtual int AddRange(ICollection col) + { + if (this.m_count + col.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + col.Count); + } + + foreach (object item in col) + { + this.Add((Level)item); + } + + return this.m_count; + } + + /// + /// Sets the capacity to the actual number of elements. + /// + public virtual void TrimToSize() + { + this.Capacity = this.m_count; + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i) + { + this.ValidateIndex(i, false); + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i, bool allowEqualEnd) + { + int max = allowEqualEnd ? this.m_count : (this.m_count - 1); + if (i < 0 || i > max) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); + } + } + + private void EnsureCapacity(int min) + { + int newCapacity = (this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2; + if (newCapacity < min) + { + newCapacity = min; + } + + this.Capacity = newCapacity; + } + + void ICollection.CopyTo(Array array, int start) + { + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + object IList.this[int i] + { + get { return (object)this[i]; } + set { this[i] = (Level)value; } + } + + int IList.Add(object x) + { + return this.Add((Level)x); + } + + bool IList.Contains(object x) + { + return this.Contains((Level)x); + } + + int IList.IndexOf(object x) + { + return this.IndexOf((Level)x); + } + + void IList.Insert(int pos, object x) + { + this.Insert(pos, (Level)x); + } + + void IList.Remove(object x) + { + this.Remove((Level)x); + } + + void IList.RemoveAt(int pos) + { + this.RemoveAt(pos); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (IEnumerator)this.GetEnumerator(); + } + + /// + /// Supports simple iteration over a . + /// + private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator + { + private readonly LevelCollection m_collection; + private int m_index; + private int m_version; + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the Enumerator class. + /// + /// + internal Enumerator(LevelCollection tc) + { + this.m_collection = tc; + this.m_index = -1; + this.m_version = tc.m_version; + } + + /// + /// Gets the current element in the collection. + /// + public Level Current + { + get { return this.m_collection[this.m_index]; } + } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + public bool MoveNext() + { + if (this.m_version != this.m_collection.m_version) + { + throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); + } + + ++this.m_index; + return this.m_index < this.m_collection.Count; + } + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + public void Reset() + { + this.m_index = -1; + } + + object IEnumerator.Current + { + get { return this.Current; } + } + } + + private sealed class ReadOnlyLevelCollection : LevelCollection + { + private readonly LevelCollection m_collection; + + internal ReadOnlyLevelCollection(LevelCollection list) + : base(Tag.Default) + { + this.m_collection = list; + } + + public override void CopyTo(Level[] array) + { + this.m_collection.CopyTo(array); + } + + public override void CopyTo(Level[] array, int start) + { + this.m_collection.CopyTo(array, start); + } + + public override int Count + { + get { return this.m_collection.Count; } + } + + public override bool IsSynchronized + { + get { return this.m_collection.IsSynchronized; } + } + + public override object SyncRoot + { + get { return this.m_collection.SyncRoot; } + } + + public override Level this[int i] + { + get { return this.m_collection[i]; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int Add(Level x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Clear() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool Contains(Level x) + { + return this.m_collection.Contains(x); + } + + public override int IndexOf(Level x) + { + return this.m_collection.IndexOf(x); + } + + public override void Insert(int pos, Level x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Remove(Level x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void RemoveAt(int pos) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool IsFixedSize + { + get { return true; } + } + + public override bool IsReadOnly + { + get { return true; } + } + + public override ILevelCollectionEnumerator GetEnumerator() + { + return this.m_collection.GetEnumerator(); + } + + // (just to mimic some nice features of ArrayList) + public override int Capacity + { + get { return this.m_collection.Capacity; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int AddRange(LevelCollection x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override int AddRange(Level[] x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs index 3f5fe85118e..f6c8f2393e0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs @@ -1,137 +1,137 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// An evaluator that triggers at a threshold level - /// - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - /// Nicko Cadell - public class LevelEvaluator : ITriggeringEventEvaluator - { - /// - /// The threshold for triggering - /// - private Level m_threshold; - - /// - /// Create a new evaluator using the threshold. - /// - /// - /// - /// Create a new evaluator using the threshold. - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public LevelEvaluator() : this(Level.Off) - { - } - - /// - /// Create a new evaluator using the specified threshold. - /// - /// the threshold to trigger at - /// - /// - /// Create a new evaluator using the specified threshold. - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public LevelEvaluator(Level threshold) - { - if (threshold == null) - { - throw new ArgumentNullException("threshold"); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net; + + /// + /// An evaluator that triggers at a threshold level. + /// + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + /// Nicko Cadell. + public class LevelEvaluator : ITriggeringEventEvaluator + { + /// + /// The threshold for triggering. + /// + private Level m_threshold; + + /// + /// Initializes a new instance of the class. + /// Create a new evaluator using the threshold. + /// + /// + /// + /// Create a new evaluator using the threshold. + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public LevelEvaluator() + : this(Level.Off) + { + } + + /// + /// Initializes a new instance of the class. + /// Create a new evaluator using the specified threshold. + /// + /// the threshold to trigger at. + /// + /// + /// Create a new evaluator using the specified threshold. + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public LevelEvaluator(Level threshold) + { + if (threshold == null) + { + throw new ArgumentNullException("threshold"); + } - m_threshold = threshold; - } + this.m_threshold = threshold; + } - /// - /// the threshold to trigger at - /// - /// - /// The that will cause this evaluator to trigger - /// - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public Level Threshold - { - get { return m_threshold; } - set { m_threshold = value; } - } + /// + /// Gets or sets the threshold to trigger at. + /// + /// + /// The that will cause this evaluator to trigger. + /// + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public Level Threshold + { + get { return this.m_threshold; } + set { this.m_threshold = value; } + } - /// - /// Is this the triggering event? - /// - /// The event to check - /// This method returns true, if the event level - /// is equal or higher than the . - /// Otherwise it returns false - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public bool IsTriggeringEvent(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } + /// + /// Is this the triggering event?. + /// + /// The event to check. + /// This method returns true, if the event level + /// is equal or higher than the . + /// Otherwise it returns false. + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public bool IsTriggeringEvent(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - return (loggingEvent.Level >= m_threshold); - } - } + return loggingEvent.Level >= this.m_threshold; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs index bcdfcca8954..ea96ab27dae 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs @@ -1,233 +1,230 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Collections.Specialized; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Mapping between string name and Level object - /// - /// - /// - /// Mapping between string name and object. - /// This mapping is held separately for each . - /// The level name is case insensitive. - /// - /// - /// Nicko Cadell - public sealed class LevelMap - { - #region Member Variables - - /// - /// Mapping from level name to Level object. The - /// level name is case insensitive - /// - private Hashtable m_mapName2Level = SystemInfo.CreateCaseInsensitiveHashtable(); - - #endregion - - /// - /// Construct the level map - /// - /// - /// - /// Construct the level map. - /// - /// - public LevelMap() - { - } - - /// - /// Clear the internal maps of all levels - /// - /// - /// - /// Clear the internal maps of all levels - /// - /// - public void Clear() - { - // Clear all current levels - m_mapName2Level.Clear(); - } - - /// - /// Lookup a by name - /// - /// The name of the Level to lookup - /// a Level from the map with the name specified - /// - /// - /// Returns the from the - /// map with the name specified. If the no level is - /// found then null is returned. - /// - /// - public Level this[string name] - { - get - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - lock(this) - { - return (Level)m_mapName2Level[name]; - } - } - } - - /// - /// Create a new Level and add it to the map - /// - /// the string to display for the Level - /// the level value to give to the Level - /// - /// - /// Create a new Level and add it to the map - /// - /// - /// - public void Add(string name, int value) - { - Add(name, value, null); - } - - /// - /// Create a new Level and add it to the map - /// - /// the string to display for the Level - /// the level value to give to the Level - /// the display name to give to the Level - /// - /// - /// Create a new Level and add it to the map - /// - /// - public void Add(string name, int value, string displayName) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - if (name.Length == 0) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("name", name, "Parameter: name, Value: ["+name+"] out of range. Level name must not be empty"); - } - - if (displayName == null || displayName.Length == 0) - { - displayName = name; - } - - Add(new Level(value, name, displayName)); - } - - /// - /// Add a Level to the map - /// - /// the Level to add - /// - /// - /// Add a Level to the map - /// - /// - public void Add(Level level) - { - if (level == null) - { - throw new ArgumentNullException("level"); - } - lock(this) - { - m_mapName2Level[level.Name] = level; - } - } - - /// - /// Return all possible levels as a list of Level objects. - /// - /// all possible levels as a list of Level objects - /// - /// - /// Return all possible levels as a list of Level objects. - /// - /// - public LevelCollection AllLevels - { - get - { - lock(this) - { - return new LevelCollection(m_mapName2Level.Values); - } - } - } - - /// - /// Lookup a named level from the map - /// - /// the name of the level to lookup is taken from this level. - /// If the level is not set on the map then this level is added - /// the level in the map with the name specified - /// - /// - /// Lookup a named level from the map. The name of the level to lookup is taken - /// from the property of the - /// argument. - /// - /// - /// If no level with the specified name is found then the - /// argument is added to the level map - /// and returned. - /// - /// - public Level LookupWithDefault(Level defaultLevel) - { - if (defaultLevel == null) - { - throw new ArgumentNullException("defaultLevel"); - } - - lock(this) - { - Level level = (Level)m_mapName2Level[defaultLevel.Name]; - if (level == null) - { - m_mapName2Level[defaultLevel.Name] = defaultLevel; - return defaultLevel; - } - return level; - } - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Collections.Specialized; + + using log4net.Util; + + /// + /// Mapping between string name and Level object. + /// + /// + /// + /// Mapping between string name and object. + /// This mapping is held separately for each . + /// The level name is case insensitive. + /// + /// + /// Nicko Cadell. + public sealed class LevelMap + { + /// + /// Mapping from level name to Level object. The + /// level name is case insensitive. + /// + private Hashtable m_mapName2Level = SystemInfo.CreateCaseInsensitiveHashtable(); + + /// + /// Initializes a new instance of the class. + /// Construct the level map. + /// + /// + /// + /// Construct the level map. + /// + /// + public LevelMap() + { + } + + /// + /// Clear the internal maps of all levels. + /// + /// + /// + /// Clear the internal maps of all levels. + /// + /// + public void Clear() + { + // Clear all current levels + this.m_mapName2Level.Clear(); + } + + /// + /// Lookup a by name. + /// + /// The name of the Level to lookup. + /// a Level from the map with the name specified. + /// + /// + /// Returns the from the + /// map with the name specified. If the no level is + /// found then null is returned. + /// + /// + public Level this[string name] + { + get + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + lock (this) + { + return (Level)this.m_mapName2Level[name]; + } + } + } + + /// + /// Create a new Level and add it to the map. + /// + /// the string to display for the Level. + /// the level value to give to the Level. + /// + /// + /// Create a new Level and add it to the map. + /// + /// + /// + public void Add(string name, int value) + { + this.Add(name, value, null); + } + + /// + /// Create a new Level and add it to the map. + /// + /// the string to display for the Level. + /// the level value to give to the Level. + /// the display name to give to the Level. + /// + /// + /// Create a new Level and add it to the map. + /// + /// + public void Add(string name, int value, string displayName) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + if (name.Length == 0) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("name", name, "Parameter: name, Value: [" + name + "] out of range. Level name must not be empty"); + } + + if (displayName == null || displayName.Length == 0) + { + displayName = name; + } + + this.Add(new Level(value, name, displayName)); + } + + /// + /// Add a Level to the map. + /// + /// the Level to add. + /// + /// + /// Add a Level to the map. + /// + /// + public void Add(Level level) + { + if (level == null) + { + throw new ArgumentNullException("level"); + } + + lock (this) + { + this.m_mapName2Level[level.Name] = level; + } + } + + /// + /// Gets return all possible levels as a list of Level objects. + /// + /// all possible levels as a list of Level objects. + /// + /// + /// Return all possible levels as a list of Level objects. + /// + /// + public LevelCollection AllLevels + { + get + { + lock (this) + { + return new LevelCollection(this.m_mapName2Level.Values); + } + } + } + + /// + /// Lookup a named level from the map. + /// + /// the name of the level to lookup is taken from this level. + /// If the level is not set on the map then this level is added. + /// the level in the map with the name specified. + /// + /// + /// Lookup a named level from the map. The name of the level to lookup is taken + /// from the property of the + /// argument. + /// + /// + /// If no level with the specified name is found then the + /// argument is added to the level map + /// and returned. + /// + /// + public Level LookupWithDefault(Level defaultLevel) + { + if (defaultLevel == null) + { + throw new ArgumentNullException("defaultLevel"); + } + + lock (this) + { + Level level = (Level)this.m_mapName2Level[defaultLevel.Name]; + if (level == null) + { + this.m_mapName2Level[defaultLevel.Name] = defaultLevel; + return defaultLevel; + } + + return level; + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs index 28c1662ac51..a8dcbd54241 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs @@ -1,323 +1,309 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Diagnostics; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// The internal representation of caller location information. - /// - /// - /// - /// This class uses the System.Diagnostics.StackTrace class to generate - /// a call stack. The caller's information is then extracted from this stack. - /// - /// - /// The System.Diagnostics.StackTrace class is not supported on the - /// .NET Compact Framework 1.0 therefore caller location information is not - /// available on that framework. - /// - /// - /// The System.Diagnostics.StackTrace class has this to say about Release builds: - /// - /// - /// "StackTrace information will be most informative with Debug build configurations. - /// By default, Debug builds include debug symbols, while Release builds do not. The - /// debug symbols contain most of the file, method name, line number, and column - /// information used in constructing StackFrame and StackTrace objects. StackTrace - /// might not report as many method calls as expected, due to code transformations - /// that occur during optimization." - /// - /// - /// This means that in a Release build the caller information may be incomplete or may - /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Diagnostics; + + using log4net.Util; + + /// + /// The internal representation of caller location information. + /// + /// + /// + /// This class uses the System.Diagnostics.StackTrace class to generate + /// a call stack. The caller's information is then extracted from this stack. + /// + /// + /// The System.Diagnostics.StackTrace class is not supported on the + /// .NET Compact Framework 1.0 therefore caller location information is not + /// available on that framework. + /// + /// + /// The System.Diagnostics.StackTrace class has this to say about Release builds: + /// + /// + /// "StackTrace information will be most informative with Debug build configurations. + /// By default, Debug builds include debug symbols, while Release builds do not. The + /// debug symbols contain most of the file, method name, line number, and column + /// information used in constructing StackFrame and StackTrace objects. StackTrace + /// might not report as many method calls as expected, due to code transformations + /// that occur during optimization.". + /// + /// + /// This means that in a Release build the caller information may be incomplete or may + /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if !NETCF - [Serializable] + [Serializable] #endif - public class LocationInfo - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// - /// - /// Initializes a new instance of the - /// class based on the current thread. - /// - /// - public LocationInfo(Type callerStackBoundaryDeclaringType) - { - // Initialize all fields - m_className = NA; - m_fileName = NA; - m_lineNumber = NA; - m_methodName = NA; - m_fullInfo = NA; + public class LocationInfo + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// + /// + /// Initializes a new instance of the + /// class based on the current thread. + /// + /// + public LocationInfo(Type callerStackBoundaryDeclaringType) + { + // Initialize all fields + this.m_className = NA; + this.m_fileName = NA; + this.m_lineNumber = NA; + this.m_methodName = NA; + this.m_fullInfo = NA; #if !(NETCF || NETSTANDARD1_3) // StackTrace isn't fully implemented for NETSTANDARD1_3 https://github.com/dotnet/corefx/issues/1797 - if (callerStackBoundaryDeclaringType != null) - { - try - { - StackTrace st = new StackTrace(true); - int frameIndex = 0; - - // skip frames not from fqnOfCallingClass - while (frameIndex < st.FrameCount) - { - StackFrame frame = st.GetFrame(frameIndex); - if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType) - { - break; - } - frameIndex++; - } + if (callerStackBoundaryDeclaringType != null) + { + try + { + StackTrace st = new StackTrace(true); + int frameIndex = 0; - // skip frames from fqnOfCallingClass - while (frameIndex < st.FrameCount) - { - StackFrame frame = st.GetFrame(frameIndex); - if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType) - { - break; - } - frameIndex++; - } + // skip frames not from fqnOfCallingClass + while (frameIndex < st.FrameCount) + { + StackFrame frame = st.GetFrame(frameIndex); + if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType) + { + break; + } + + frameIndex++; + } - if (frameIndex < st.FrameCount) - { - // take into account the frames we skip above - int adjustedFrameCount = st.FrameCount - frameIndex; - ArrayList stackFramesList = new ArrayList(adjustedFrameCount); - m_stackFrames = new StackFrameItem[adjustedFrameCount]; - for (int i=frameIndex; i < st.FrameCount; i++) - { - stackFramesList.Add(new StackFrameItem(st.GetFrame(i))); - } - - stackFramesList.CopyTo(m_stackFrames, 0); - - // now frameIndex is the first 'user' caller frame - StackFrame locationFrame = st.GetFrame(frameIndex); + // skip frames from fqnOfCallingClass + while (frameIndex < st.FrameCount) + { + StackFrame frame = st.GetFrame(frameIndex); + if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType) + { + break; + } + + frameIndex++; + } - if (locationFrame != null) - { - System.Reflection.MethodBase method = locationFrame.GetMethod(); + if (frameIndex < st.FrameCount) + { + // take into account the frames we skip above + int adjustedFrameCount = st.FrameCount - frameIndex; + ArrayList stackFramesList = new ArrayList(adjustedFrameCount); + this.m_stackFrames = new StackFrameItem[adjustedFrameCount]; + for (int i = frameIndex; i < st.FrameCount; i++) + { + stackFramesList.Add(new StackFrameItem(st.GetFrame(i))); + } - if (method != null) - { - m_methodName = method.Name; - if (method.DeclaringType != null) - { - m_className = method.DeclaringType.FullName; - } - } - m_fileName = locationFrame.GetFileName(); - m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); + stackFramesList.CopyTo(this.m_stackFrames, 0); - // Combine all location info - m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')'; - } - } - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available."); - } - } -#endif - } + // now frameIndex is the first 'user' caller frame + StackFrame locationFrame = st.GetFrame(frameIndex); - /// - /// Constructor - /// - /// The fully qualified class name. - /// The method name. - /// The file name. - /// The line number of the method within the file. - /// - /// - /// Initializes a new instance of the - /// class with the specified data. - /// - /// - public LocationInfo(string className, string methodName, string fileName, string lineNumber) - { - m_className = className; - m_fileName = fileName; - m_lineNumber = lineNumber; - m_methodName = methodName; - m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + - ':' + m_lineNumber + ')'; - } + if (locationFrame != null) + { + System.Reflection.MethodBase method = locationFrame.GetMethod(); - #endregion Public Instance Constructors + if (method != null) + { + this.m_methodName = method.Name; + if (method.DeclaringType != null) + { + this.m_className = method.DeclaringType.FullName; + } + } + + this.m_fileName = locationFrame.GetFileName(); + this.m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); - #region Public Instance Properties + // Combine all location info + this.m_fullInfo = this.m_className + '.' + this.m_methodName + '(' + this.m_fileName + ':' + this.m_lineNumber + ')'; + } + } + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available."); + } + } +#endif + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The fully qualified class name. + /// The method name. + /// The file name. + /// The line number of the method within the file. + /// + /// + /// Initializes a new instance of the + /// class with the specified data. + /// + /// + public LocationInfo(string className, string methodName, string fileName, string lineNumber) + { + this.m_className = className; + this.m_fileName = fileName; + this.m_lineNumber = lineNumber; + this.m_methodName = methodName; + this.m_fullInfo = this.m_className + '.' + this.m_methodName + '(' + this.m_fileName + + ':' + this.m_lineNumber + ')'; + } + + /// + /// Gets the fully qualified class name of the caller making the logging + /// request. + /// + /// + /// The fully qualified class name of the caller making the logging + /// request. + /// + /// + /// + /// Gets the fully qualified class name of the caller making the logging + /// request. + /// + /// + public string ClassName + { + get { return this.m_className; } + } - /// - /// Gets the fully qualified class name of the caller making the logging - /// request. - /// - /// - /// The fully qualified class name of the caller making the logging - /// request. - /// - /// - /// - /// Gets the fully qualified class name of the caller making the logging - /// request. - /// - /// - public string ClassName - { - get { return m_className; } - } + /// + /// Gets the file name of the caller. + /// + /// + /// The file name of the caller. + /// + /// + /// + /// Gets the file name of the caller. + /// + /// + public string FileName + { + get { return this.m_fileName; } + } - /// - /// Gets the file name of the caller. - /// - /// - /// The file name of the caller. - /// - /// - /// - /// Gets the file name of the caller. - /// - /// - public string FileName - { - get { return m_fileName; } - } + /// + /// Gets the line number of the caller. + /// + /// + /// The line number of the caller. + /// + /// + /// + /// Gets the line number of the caller. + /// + /// + public string LineNumber + { + get { return this.m_lineNumber; } + } - /// - /// Gets the line number of the caller. - /// - /// - /// The line number of the caller. - /// - /// - /// - /// Gets the line number of the caller. - /// - /// - public string LineNumber - { - get { return m_lineNumber; } - } + /// + /// Gets the method name of the caller. + /// + /// + /// The method name of the caller. + /// + /// + /// + /// Gets the method name of the caller. + /// + /// + public string MethodName + { + get { return this.m_methodName; } + } - /// - /// Gets the method name of the caller. - /// - /// - /// The method name of the caller. - /// - /// - /// - /// Gets the method name of the caller. - /// - /// - public string MethodName - { - get { return m_methodName; } - } + /// + /// Gets all available caller information. + /// + /// + /// All available caller information, in the format + /// fully.qualified.classname.of.caller.methodName(Filename:line). + /// + /// + /// + /// Gets all available caller information, in the format + /// fully.qualified.classname.of.caller.methodName(Filename:line). + /// + /// + public string FullInfo + { + get { return this.m_fullInfo; } + } - /// - /// Gets all available caller information - /// - /// - /// All available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line) - /// - /// - /// - /// Gets all available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line) - /// - /// - public string FullInfo - { - get { return m_fullInfo; } - } - #if !(NETCF || NETSTANDARD1_3) - /// - /// Gets the stack frames from the stack trace of the caller making the log request - /// - public StackFrameItem[] StackFrames - { - get { return m_stackFrames; } - } + /// + /// Gets the stack frames from the stack trace of the caller making the log request. + /// + public StackFrameItem[] StackFrames + { + get { return this.m_stackFrames; } + } #endif - - #endregion Public Instance Properties - - #region Private Instance Fields - - private readonly string m_className; - private readonly string m_fileName; - private readonly string m_lineNumber; - private readonly string m_methodName; - private readonly string m_fullInfo; + + private readonly string m_className; + private readonly string m_fileName; + private readonly string m_lineNumber; + private readonly string m_methodName; + private readonly string m_fullInfo; #if !(NETCF || NETSTANDARD1_3) - private readonly StackFrameItem[] m_stackFrames; + private readonly StackFrameItem[] m_stackFrames; #endif + + /// + /// The fully qualified type of the LocationInfo class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(LocationInfo); - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the LocationInfo class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(LocationInfo); - - /// - /// When location information is not available the constant - /// NA is returned. Current value of this string - /// constant is ?. - /// - private const string NA = "?"; - - #endregion Private Static Fields - } + /// + /// When location information is not available the constant + /// NA is returned. Current value of this string + /// constant is ?. + /// + private const string NA = "?"; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs index e9031bf3c24..9434a383bf1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs @@ -1,118 +1,117 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if !NETCF using System.Runtime.Serialization; + #endif namespace log4net.Core { - /// - /// Exception base type for log4net. - /// - /// - /// - /// This type extends . It - /// does not add any new functionality but does differentiate the - /// type of exception being thrown. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Exception base type for log4net. + /// + /// + /// + /// This type extends . It + /// does not add any new functionality but does differentiate the + /// type of exception being thrown. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if !NETCF - [Serializable] + [Serializable] #endif #if NETSTANDARD1_3 public class LogException : Exception #else - public class LogException : ApplicationException + public class LogException : ApplicationException #endif - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public LogException() - { - } - - /// - /// Constructor - /// - /// A message to include with the exception. - /// - /// - /// Initializes a new instance of the class with - /// the specified message. - /// - /// - public LogException(String message) : base(message) - { - } - - /// - /// Constructor - /// - /// A message to include with the exception. - /// A nested exception to include. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and inner exception. - /// - /// - public LogException(String message, Exception innerException) : base(message, innerException) - { - } - - #endregion Public Instance Constructors - - #region Protected Instance Constructors - + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public LogException() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// A message to include with the exception. + /// + /// + /// Initializes a new instance of the class with + /// the specified message. + /// + /// + public LogException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// A message to include with the exception. + /// A nested exception to include. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and inner exception. + /// + /// + public LogException(string message, Exception innerException) + : base(message, innerException) + { + } + #if !(NETCF || NETSTANDARD1_3) - /// - /// Serialization constructor - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected LogException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } + /// + /// Initializes a new instance of the class. + /// Serialization constructor. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected LogException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } #endif - - #endregion Protected Instance Constructors - } + + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs index a2382092c23..948db835892 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs @@ -1,1300 +1,1278 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Globalization; - -using log4net.Repository; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// Implementation of wrapper interface. - /// - /// - /// - /// This implementation of the interface - /// forwards to the held by the base class. - /// - /// - /// This logger has methods to allow the caller to log at the following - /// levels: - /// - /// - /// - /// DEBUG - /// - /// The and methods log messages - /// at the DEBUG level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// INFO - /// - /// The and methods log messages - /// at the INFO level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// WARN - /// - /// The and methods log messages - /// at the WARN level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// ERROR - /// - /// The and methods log messages - /// at the ERROR level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// FATAL - /// - /// The and methods log messages - /// at the FATAL level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// - /// The values for these levels and their semantic meanings can be changed by - /// configuring the for the repository. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class LogImpl : LoggerWrapperImpl, ILog - { - #region Public Instance Constructors - - /// - /// Construct a new wrapper for the specified logger. - /// - /// The logger to wrap. - /// - /// - /// Construct a new wrapper for the specified logger. - /// - /// - public LogImpl(ILogger logger) : base(logger) - { - // Listen for changes to the repository - logger.Repository.ConfigurationChanged += new LoggerRepositoryConfigurationChangedEventHandler(LoggerRepositoryConfigurationChanged); - - // load the current levels - ReloadLevels(logger.Repository); - } - - #endregion Public Instance Constructors - - /// - /// Virtual method called when the configuration of the repository changes - /// - /// the repository holding the levels - /// - /// - /// Virtual method called when the configuration of the repository changes - /// - /// - protected virtual void ReloadLevels(ILoggerRepository repository) - { - LevelMap levelMap = repository.LevelMap; - - m_levelDebug = levelMap.LookupWithDefault(Level.Debug); - m_levelInfo = levelMap.LookupWithDefault(Level.Info); - m_levelWarn = levelMap.LookupWithDefault(Level.Warn); - m_levelError = levelMap.LookupWithDefault(Level.Error); - m_levelFatal = levelMap.LookupWithDefault(Level.Fatal); - } - - #region Implementation of ILog - - /// - /// Logs a message object with the DEBUG level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is DEBUG - /// enabled by comparing the level of this logger with the - /// DEBUG level. If this logger is - /// DEBUG enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - virtual public void Debug(object message) - { - Logger.Log(ThisDeclaringType, m_levelDebug, message, null); - } - - /// - /// Logs a message object with the DEBUG level - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the DEBUG level including - /// the stack trace of the passed - /// as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - virtual public void Debug(object message, Exception exception) - { - Logger.Log(ThisDeclaringType, m_levelDebug, message, exception); - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void DebugFormat(string format, params object[] args) - { - if (IsDebugEnabled) - { - Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void DebugFormat(string format, object arg0) - { - if (IsDebugEnabled) - { - Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void DebugFormat(string format, object arg0, object arg1) - { - if (IsDebugEnabled) - { - Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + + using log4net.Repository; + using log4net.Util; + + /// + /// Implementation of wrapper interface. + /// + /// + /// + /// This implementation of the interface + /// forwards to the held by the base class. + /// + /// + /// This logger has methods to allow the caller to log at the following + /// levels: + /// + /// + /// + /// DEBUG + /// + /// The and methods log messages + /// at the DEBUG level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// INFO + /// + /// The and methods log messages + /// at the INFO level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// WARN + /// + /// The and methods log messages + /// at the WARN level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// ERROR + /// + /// The and methods log messages + /// at the ERROR level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// FATAL + /// + /// The and methods log messages + /// at the FATAL level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// + /// The values for these levels and their semantic meanings can be changed by + /// configuring the for the repository. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class LogImpl : LoggerWrapperImpl, ILog + { + /// + /// Initializes a new instance of the class. + /// Construct a new wrapper for the specified logger. + /// + /// The logger to wrap. + /// + /// + /// Construct a new wrapper for the specified logger. + /// + /// + public LogImpl(ILogger logger) + : base(logger) + { + // Listen for changes to the repository + logger.Repository.ConfigurationChanged += new LoggerRepositoryConfigurationChangedEventHandler(this.LoggerRepositoryConfigurationChanged); - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void DebugFormat(string format, object arg0, object arg1, object arg2) - { - if (IsDebugEnabled) - { - Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } + // load the current levels + this.ReloadLevels(logger.Repository); + } + + /// + /// Virtual method called when the configuration of the repository changes. + /// + /// the repository holding the levels. + /// + /// + /// Virtual method called when the configuration of the repository changes. + /// + /// + protected virtual void ReloadLevels(ILoggerRepository repository) + { + LevelMap levelMap = repository.LevelMap; - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsDebugEnabled) - { - Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(provider, format, args), null); - } - } + this.m_levelDebug = levelMap.LookupWithDefault(Level.Debug); + this.m_levelInfo = levelMap.LookupWithDefault(Level.Info); + this.m_levelWarn = levelMap.LookupWithDefault(Level.Warn); + this.m_levelError = levelMap.LookupWithDefault(Level.Error); + this.m_levelFatal = levelMap.LookupWithDefault(Level.Fatal); + } + + /// + /// Logs a message object with the DEBUG level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is DEBUG + /// enabled by comparing the level of this logger with the + /// DEBUG level. If this logger is + /// DEBUG enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Debug(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, message, null); + } - /// - /// Logs a message object with the INFO level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by comparing the level of this logger with the - /// INFO level. If this logger is - /// INFO enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - virtual public void Info(object message) - { - Logger.Log(ThisDeclaringType, m_levelInfo, message, null); - } - - /// - /// Logs a message object with the INFO level. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the INFO level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - virtual public void Info(object message, Exception exception) - { - Logger.Log(ThisDeclaringType, m_levelInfo, message, exception); - } + /// + /// Logs a message object with the DEBUG level. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the DEBUG level including + /// the stack trace of the passed + /// as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Debug(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, message, exception); + } - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void InfoFormat(string format, params object[] args) - { - if (IsInfoEnabled) - { - Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, params object[] args) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void InfoFormat(string format, object arg0) - { - if (IsInfoEnabled) - { - Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, object arg0) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void InfoFormat(string format, object arg0, object arg1) - { - if (IsInfoEnabled) - { - Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, object arg0, object arg1) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void InfoFormat(string format, object arg0, object arg1, object arg2) - { - if (IsInfoEnabled) - { - Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } - /// - /// Logs a formatted message string with the INFO level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsInfoEnabled) - { - Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(provider, format, args), null); - } - } + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(provider, format, args), null); + } + } - /// - /// Logs a message object with the WARN level. - /// - /// the message object to log - /// - /// - /// This method first checks if this logger is WARN - /// enabled by comparing the level of this logger with the - /// WARN level. If this logger is - /// WARN enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger and - /// also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an to this - /// method will print the name of the but no - /// stack trace. To print a stack trace use the - /// form instead. - /// - /// - virtual public void Warn(object message) - { - Logger.Log(ThisDeclaringType, m_levelWarn, message, null); - } - - /// - /// Logs a message object with the WARN level - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the WARN level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - virtual public void Warn(object message, Exception exception) - { - Logger.Log(ThisDeclaringType, m_levelWarn, message, exception); - } + /// + /// Logs a message object with the INFO level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by comparing the level of this logger with the + /// INFO level. If this logger is + /// INFO enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Info(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, message, null); + } - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void WarnFormat(string format, params object[] args) - { - if (IsWarnEnabled) - { - Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } + /// + /// Logs a message object with the INFO level. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the INFO level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Info(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, message, exception); + } - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void WarnFormat(string format, object arg0) - { - if (IsWarnEnabled) - { - Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, params object[] args) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void WarnFormat(string format, object arg0, object arg1) - { - if (IsWarnEnabled) - { - Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, object arg0) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void WarnFormat(string format, object arg0, object arg1, object arg2) - { - if (IsWarnEnabled) - { - Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, object arg0, object arg1) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } - /// - /// Logs a formatted message string with the WARN level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsWarnEnabled) - { - Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(provider, format, args), null); - } - } + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } - /// - /// Logs a message object with the ERROR level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by comparing the level of this logger with the - /// ERROR level. If this logger is - /// ERROR enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger and - /// also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an to this - /// method will print the name of the but no - /// stack trace. To print a stack trace use the - /// form instead. - /// - /// - virtual public void Error(object message) - { - Logger.Log(ThisDeclaringType, m_levelError, message, null); - } + /// + /// Logs a formatted message string with the INFO level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(provider, format, args), null); + } + } - /// - /// Logs a message object with the ERROR level - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the ERROR level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - virtual public void Error(object message, Exception exception) - { - Logger.Log(ThisDeclaringType, m_levelError, message, exception); - } + /// + /// Logs a message object with the WARN level. + /// + /// the message object to log. + /// + /// + /// This method first checks if this logger is WARN + /// enabled by comparing the level of this logger with the + /// WARN level. If this logger is + /// WARN enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger and + /// also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an to this + /// method will print the name of the but no + /// stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Warn(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, message, null); + } - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void ErrorFormat(string format, params object[] args) - { - if (IsErrorEnabled) - { - Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } + /// + /// Logs a message object with the WARN level. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the WARN level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Warn(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, message, exception); + } - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void ErrorFormat(string format, object arg0) - { - if (IsErrorEnabled) - { - Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, params object[] args) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void ErrorFormat(string format, object arg0, object arg1) - { - if (IsErrorEnabled) - { - Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, object arg0) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void ErrorFormat(string format, object arg0, object arg1, object arg2) - { - if (IsErrorEnabled) - { - Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, object arg0, object arg1) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } - /// - /// Logs a formatted message string with the ERROR level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsErrorEnabled) - { - Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(provider, format, args), null); - } - } + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } - /// - /// Logs a message object with the FATAL level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by comparing the level of this logger with the - /// FATAL level. If this logger is - /// FATAL enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger and - /// also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an to this - /// method will print the name of the but no - /// stack trace. To print a stack trace use the - /// form instead. - /// - /// - virtual public void Fatal(object message) - { - Logger.Log(ThisDeclaringType, m_levelFatal, message, null); - } - - /// - /// Logs a message object with the FATAL level - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the FATAL level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - virtual public void Fatal(object message, Exception exception) - { - Logger.Log(ThisDeclaringType, m_levelFatal, message, exception); - } + /// + /// Logs a formatted message string with the WARN level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(provider, format, args), null); + } + } - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void FatalFormat(string format, params object[] args) - { - if (IsFatalEnabled) - { - Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } + /// + /// Logs a message object with the ERROR level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by comparing the level of this logger with the + /// ERROR level. If this logger is + /// ERROR enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger and + /// also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an to this + /// method will print the name of the but no + /// stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Error(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, message, null); + } - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void FatalFormat(string format, object arg0) - { - if (IsFatalEnabled) - { - Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } + /// + /// Logs a message object with the ERROR level. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the ERROR level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Error(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, message, exception); + } - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void FatalFormat(string format, object arg0, object arg1) - { - if (IsFatalEnabled) - { - Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, params object[] args) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void FatalFormat(string format, object arg0, object arg1, object arg2) - { - if (IsFatalEnabled) - { - Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, object arg0) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } - /// - /// Logs a formatted message string with the FATAL level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - virtual public void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsFatalEnabled) - { - Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(provider, format, args), null); - } - } + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, object arg0, object arg1) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } - /// - /// Checks if this logger is enabled for the DEBUG - /// level. - /// - /// - /// true if this logger is enabled for DEBUG events, - /// false otherwise. - /// - /// - /// - /// This function is intended to lessen the computational cost of - /// disabled log debug statements. - /// - /// - /// For some log Logger object, when you write: - /// - /// - /// log.Debug("This is entry number: " + i ); - /// - /// - /// You incur the cost constructing the message, concatenation in - /// this case, regardless of whether the message is logged or not. - /// - /// - /// If you are worried about speed, then you should write: - /// - /// - /// if (log.IsDebugEnabled()) - /// { - /// log.Debug("This is entry number: " + i ); - /// } - /// - /// - /// This way you will not incur the cost of parameter - /// construction if debugging is disabled for log. On - /// the other hand, if the log is debug enabled, you - /// will incur the cost of evaluating whether the logger is debug - /// enabled twice. Once in IsDebugEnabled and once in - /// the Debug. This is an insignificant overhead - /// since evaluating a logger takes about 1% of the time it - /// takes to actually log. - /// - /// - virtual public bool IsDebugEnabled - { - get { return Logger.IsEnabledFor(m_levelDebug); } - } - - /// - /// Checks if this logger is enabled for the INFO level. - /// - /// - /// true if this logger is enabled for INFO events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples - /// of using this method. - /// - /// - /// - virtual public bool IsInfoEnabled - { - get { return Logger.IsEnabledFor(m_levelInfo); } - } + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } - /// - /// Checks if this logger is enabled for the WARN level. - /// - /// - /// true if this logger is enabled for WARN events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples - /// of using this method. - /// - /// - /// - virtual public bool IsWarnEnabled - { - get { return Logger.IsEnabledFor(m_levelWarn); } - } + /// + /// Logs a formatted message string with the ERROR level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(provider, format, args), null); + } + } - /// - /// Checks if this logger is enabled for the ERROR level. - /// - /// - /// true if this logger is enabled for ERROR events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples of using this method. - /// - /// - /// - virtual public bool IsErrorEnabled - { - get { return Logger.IsEnabledFor(m_levelError); } - } + /// + /// Logs a message object with the FATAL level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by comparing the level of this logger with the + /// FATAL level. If this logger is + /// FATAL enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger and + /// also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an to this + /// method will print the name of the but no + /// stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Fatal(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, message, null); + } - /// - /// Checks if this logger is enabled for the FATAL level. - /// - /// - /// true if this logger is enabled for FATAL events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples of using this method. - /// - /// - /// - virtual public bool IsFatalEnabled - { - get { return Logger.IsEnabledFor(m_levelFatal); } - } + /// + /// Logs a message object with the FATAL level. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the FATAL level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Fatal(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, message, exception); + } - #endregion Implementation of ILog + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, params object[] args) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } - #region Private Methods + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, object arg0) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } - /// - /// Event handler for the event - /// - /// the repository - /// Empty - private void LoggerRepositoryConfigurationChanged(object sender, EventArgs e) - { - ILoggerRepository repository = sender as ILoggerRepository; - if (repository != null) - { - ReloadLevels(repository); - } - } + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, object arg0, object arg1) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } - #endregion + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } - #region Private Static Instance Fields + /// + /// Logs a formatted message string with the FATAL level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(provider, format, args), null); + } + } - /// - /// The fully qualified name of this declaring type not the type of any subclass. - /// - private readonly static Type ThisDeclaringType = typeof(LogImpl); + /// + /// Gets a value indicating whether checks if this logger is enabled for the DEBUG + /// level. + /// + /// + /// true if this logger is enabled for DEBUG events, + /// false otherwise. + /// + /// + /// + /// This function is intended to lessen the computational cost of + /// disabled log debug statements. + /// + /// + /// For some log Logger object, when you write: + /// + /// + /// log.Debug("This is entry number: " + i ); + /// + /// + /// You incur the cost constructing the message, concatenation in + /// this case, regardless of whether the message is logged or not. + /// + /// + /// If you are worried about speed, then you should write: + /// + /// + /// if (log.IsDebugEnabled()) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// + /// + /// This way you will not incur the cost of parameter + /// construction if debugging is disabled for log. On + /// the other hand, if the log is debug enabled, you + /// will incur the cost of evaluating whether the logger is debug + /// enabled twice. Once in IsDebugEnabled and once in + /// the Debug. This is an insignificant overhead + /// since evaluating a logger takes about 1% of the time it + /// takes to actually log. + /// + /// + public virtual bool IsDebugEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelDebug); } + } - #endregion Private Static Instance Fields + /// + /// Gets a value indicating whether checks if this logger is enabled for the INFO level. + /// + /// + /// true if this logger is enabled for INFO events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples + /// of using this method. + /// + /// + /// + public virtual bool IsInfoEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelInfo); } + } - #region Private Fields + /// + /// Gets a value indicating whether checks if this logger is enabled for the WARN level. + /// + /// + /// true if this logger is enabled for WARN events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples + /// of using this method. + /// + /// + /// + public virtual bool IsWarnEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelWarn); } + } - private Level m_levelDebug; - private Level m_levelInfo; - private Level m_levelWarn; - private Level m_levelError; - private Level m_levelFatal; + /// + /// Gets a value indicating whether checks if this logger is enabled for the ERROR level. + /// + /// + /// true if this logger is enabled for ERROR events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples of using this method. + /// + /// + /// + public virtual bool IsErrorEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelError); } + } - #endregion - } + /// + /// Gets a value indicating whether checks if this logger is enabled for the FATAL level. + /// + /// + /// true if this logger is enabled for FATAL events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples of using this method. + /// + /// + /// + public virtual bool IsFatalEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelFatal); } + } + + /// + /// Event handler for the event. + /// + /// the repository. + /// Empty. + private void LoggerRepositoryConfigurationChanged(object sender, EventArgs e) + { + ILoggerRepository repository = sender as ILoggerRepository; + if (repository != null) + { + this.ReloadLevels(repository); + } + } + + /// + /// The fully qualified name of this declaring type not the type of any subclass. + /// + private static readonly Type ThisDeclaringType = typeof(LogImpl); + private Level m_levelDebug; + private Level m_levelInfo; + private Level m_levelWarn; + private Level m_levelError; + private Level m_levelFatal; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs index 5794b74fae7..58bdd99c1b9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs @@ -1,809 +1,823 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + + #if NETSTANDARD1_3 using System.Runtime.InteropServices; #else using System.Configuration; + #endif using System.Reflection; - -using log4net.Util; + using log4net.Repository; +using log4net.Util; namespace log4net.Core { - /// - /// Static manager that controls the creation of repositories - /// - /// - /// - /// Static manager that controls the creation of repositories - /// - /// - /// This class is used by the wrapper managers (e.g. ) - /// to provide access to the objects. - /// - /// - /// This manager also holds the that is used to - /// lookup and create repositories. The selector can be set either programmatically using - /// the property, or by setting the log4net.RepositorySelector - /// AppSetting in the applications config file to the fully qualified type name of the - /// selector to use. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class LoggerManager - { - #region Private Instance Constructors - - /// - /// Private constructor to prevent instances. Only static methods should be used. - /// - /// - /// - /// Private constructor to prevent instances. Only static methods should be used. - /// - /// - private LoggerManager() - { - } - - #endregion Private Instance Constructors - - #region Static Constructor - - /// - /// Hook the shutdown event - /// - /// - /// - /// On the full .NET runtime, the static constructor hooks up the - /// AppDomain.ProcessExit and AppDomain.DomainUnload> events. - /// These are used to shutdown the log4net system as the application exits. - /// - /// - static LoggerManager() - { - try - { - // Register the AppDomain events, note we have to do this with a - // method call rather than directly here because the AppDomain - // makes a LinkDemand which throws the exception during the JIT phase. - RegisterAppDomainEvents(); - } - catch(System.Security.SecurityException) - { - LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying "+ - "to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() "+ - "will not be called automatically when the AppDomain exits. It must be called "+ - "programmatically."); - } - - // Dump out our assembly version into the log if debug is enabled + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Static manager that controls the creation of repositories. + /// + /// + /// + /// Static manager that controls the creation of repositories. + /// + /// + /// This class is used by the wrapper managers (e.g. ) + /// to provide access to the objects. + /// + /// + /// This manager also holds the that is used to + /// lookup and create repositories. The selector can be set either programmatically using + /// the property, or by setting the log4net.RepositorySelector + /// AppSetting in the applications config file to the fully qualified type name of the + /// selector to use. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class LoggerManager + { + /// + /// Initializes a new instance of the class. + /// Private constructor to prevent instances. Only static methods should be used. + /// + /// + /// + /// Private constructor to prevent instances. Only static methods should be used. + /// + /// + private LoggerManager() + { + } + + /// + /// Initializes static members of the class. + /// Hook the shutdown event. + /// + /// + /// + /// On the full .NET runtime, the static constructor hooks up the + /// AppDomain.ProcessExit and AppDomain.DomainUnload> events. + /// These are used to shutdown the log4net system as the application exits. + /// + /// + static LoggerManager() + { + try + { + // Register the AppDomain events, note we have to do this with a + // method call rather than directly here because the AppDomain + // makes a LinkDemand which throws the exception during the JIT phase. + RegisterAppDomainEvents(); + } + catch (System.Security.SecurityException) + { + LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying " + + "to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() " + + "will not be called automatically when the AppDomain exits. It must be called " + + "programmatically."); + } + + // Dump out our assembly version into the log if debug is enabled LogLog.Debug(declaringType, GetVersionInfo()); - // Set the default repository selector + // Set the default repository selector #if NETCF s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); return; #elif !NETSTANDARD1_3 - // Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector' - string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector"); - if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0) - { - // Resolve the config string into a Type - Type appRepositorySelectorType = null; - try - { - appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type ["+appRepositorySelectorTypeName+"]", ex); - } - - if (appRepositorySelectorType != null) - { - // Create an instance of the RepositorySelectorType - object appRepositorySelectorObj = null; - try - { - appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Exception while creating RepositorySelector ["+appRepositorySelectorType.FullName+"]", ex); - } - - if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector) - { - s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj; - } - else - { - LogLog.Error(declaringType, "RepositorySelector Type ["+appRepositorySelectorType.FullName+"] is not an IRepositorySelector"); - } - } - } + // Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector' + string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector"); + if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0) + { + // Resolve the config string into a Type + Type appRepositorySelectorType = null; + try + { + appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type [" + appRepositorySelectorTypeName + "]", ex); + } + + if (appRepositorySelectorType != null) + { + // Create an instance of the RepositorySelectorType + object appRepositorySelectorObj = null; + try + { + appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while creating RepositorySelector [" + appRepositorySelectorType.FullName + "]", ex); + } + + if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector) + { + s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj; + } + else + { + LogLog.Error(declaringType, "RepositorySelector Type [" + appRepositorySelectorType.FullName + "] is not an IRepositorySelector"); + } + } + } #endif - // Create the DefaultRepositorySelector if not configured above - if (s_repositorySelector == null) - { - s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); - } - } - - /// - /// Register for ProcessExit and DomainUnload events on the AppDomain - /// - /// - /// - /// This needs to be in a separate method because the events make - /// a LinkDemand for the ControlAppDomain SecurityPermission. Because - /// this is a LinkDemand it is demanded at JIT time. Therefore we cannot - /// catch the exception in the method itself, we have to catch it in the - /// caller. - /// - /// - private static void RegisterAppDomainEvents() - { + + // Create the DefaultRepositorySelector if not configured above + if (s_repositorySelector == null) + { + s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); + } + } + + /// + /// Register for ProcessExit and DomainUnload events on the AppDomain. + /// + /// + /// + /// This needs to be in a separate method because the events make + /// a LinkDemand for the ControlAppDomain SecurityPermission. Because + /// this is a LinkDemand it is demanded at JIT time. Therefore we cannot + /// catch the exception in the method itself, we have to catch it in the + /// caller. + /// + /// + private static void RegisterAppDomainEvents() + { #if !(NETCF || NETSTANDARD1_3) - // ProcessExit seems to be fired if we are part of the default domain - AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); + // ProcessExit seems to be fired if we are part of the default domain + AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); - // Otherwise DomainUnload is fired - AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload); + // Otherwise DomainUnload is fired + AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload); #endif - } - - #endregion Static Constructor - - #region Public Static Methods - - /// - /// Return the default instance. - /// - /// the repository to lookup in - /// Return the default instance - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(string repository) - { - return GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The assembly to use to lookup the repository. - /// The default instance. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) - { - return GetRepository(repositoryAssembly); - } - - /// - /// Return the default instance. - /// - /// the repository to lookup in - /// Return the default instance - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - public static ILoggerRepository GetRepository(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - return RepositorySelector.GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The assembly to use to lookup the repository. - /// The default instance. - /// - /// - /// Returns the default instance. - /// - /// - public static ILoggerRepository GetRepository(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - return RepositorySelector.GetRepository(repositoryAssembly); - } - - /// - /// Returns the named logger if it exists. - /// - /// The repository to lookup in. - /// The fully qualified logger name to look for. - /// - /// The logger found, or null if the named logger does not exist in the - /// specified repository. - /// - /// - /// - /// If the named logger exists (in the specified repository) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// - public static ILogger Exists(string repository, string name) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - if (name == null) - { - throw new ArgumentNullException("name"); - } - return RepositorySelector.GetRepository(repository).Exists(name); - } - - /// - /// Returns the named logger if it exists. - /// - /// The assembly to use to lookup the repository. - /// The fully qualified logger name to look for. - /// - /// The logger found, or null if the named logger does not exist in the - /// specified assembly's repository. - /// - /// - /// - /// If the named logger exists (in the specified assembly's repository) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// - public static ILogger Exists(Assembly repositoryAssembly, string name) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - if (name == null) - { - throw new ArgumentNullException("name"); - } - return RepositorySelector.GetRepository(repositoryAssembly).Exists(name); - } - - /// - /// Returns all the currently defined loggers in the specified repository. - /// - /// The repository to lookup in. - /// All the defined loggers. - /// - /// - /// The root logger is not included in the returned array. - /// - /// - public static ILogger[] GetCurrentLoggers(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - return RepositorySelector.GetRepository(repository).GetCurrentLoggers(); - } - - /// - /// Returns all the currently defined loggers in the specified assembly's repository. - /// - /// The assembly to use to lookup the repository. - /// All the defined loggers. - /// - /// - /// The root logger is not included in the returned array. - /// - /// - public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers(); - } - - /// - /// Retrieves or creates a named logger. - /// - /// The repository to lookup in. - /// The name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Retrieves a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - public static ILogger GetLogger(string repository, string name) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - if (name == null) - { - throw new ArgumentNullException("name"); - } - return RepositorySelector.GetRepository(repository).GetLogger(name); - } - - /// - /// Retrieves or creates a named logger. - /// - /// The assembly to use to lookup the repository. - /// The name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Retrieves a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - public static ILogger GetLogger(Assembly repositoryAssembly, string name) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - if (name == null) - { - throw new ArgumentNullException("name"); - } - return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name); - } - - /// - /// Shorthand for . - /// - /// The repository to lookup in. - /// The of which the fullname will be used as the name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// - public static ILogger GetLogger(string repository, Type type) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - if (type == null) - { - throw new ArgumentNullException("type"); - } - return RepositorySelector.GetRepository(repository).GetLogger(type.FullName); - } - - /// - /// Shorthand for . - /// - /// the assembly to use to lookup the repository - /// The of which the fullname will be used as the name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// - public static ILogger GetLogger(Assembly repositoryAssembly, Type type) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - if (type == null) - { - throw new ArgumentNullException("type"); - } - return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName); - } - - /// - /// Shuts down the log4net system. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in all the - /// default repositories. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void Shutdown() - { - foreach(ILoggerRepository repository in GetAllRepositories()) - { - repository.Shutdown(); - } - } - - /// - /// Shuts down the repository for the repository specified. - /// - /// The repository to shutdown. - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// repository for the specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void ShutdownRepository(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - RepositorySelector.GetRepository(repository).Shutdown(); - } - - /// - /// Shuts down the repository for the repository specified. - /// - /// The assembly to use to lookup the repository. - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// repository for the repository. The repository is looked up using - /// the specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void ShutdownRepository(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - RepositorySelector.GetRepository(repositoryAssembly).Shutdown(); - } - - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// The repository to reset. - /// - /// - /// Resets all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set its default "off" value. - /// - /// - public static void ResetConfiguration(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - RepositorySelector.GetRepository(repository).ResetConfiguration(); - } - - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// The assembly to use to lookup the repository to reset. - /// - /// - /// Resets all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set its default "off" value. - /// - /// - public static void ResetConfiguration(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration(); - } - - /// - /// Creates a repository with the specified name. - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(string repository) - { - return CreateRepository(repository); - } - - /// - /// Creates a repository with the specified name. - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - return RepositorySelector.CreateRepository(repository, null); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An Exception will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(string repository, Type repositoryType) - { - return CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An Exception will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository, Type repositoryType) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - if (repositoryType == null) - { - throw new ArgumentNullException("repositoryType"); - } - return RepositorySelector.CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) - { - return CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - if (repositoryType == null) - { - throw new ArgumentNullException("repositoryType"); - } - return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Gets an array of all currently defined repositories. - /// - /// An array of all the known objects. - /// - /// - /// Gets an array of all currently defined repositories. - /// - /// - public static ILoggerRepository[] GetAllRepositories() - { - return RepositorySelector.GetAllRepositories(); - } - - /// - /// Gets or sets the repository selector used by the . - /// - /// - /// The repository selector used by the . - /// - /// - /// - /// The repository selector () is used by - /// the to create and select repositories - /// (). - /// - /// - /// The caller to supplies either a string name - /// or an assembly (if not supplied the assembly is inferred using - /// ). - /// - /// - /// This context is used by the selector to lookup a specific repository. - /// - /// - /// For the full .NET Framework, the default repository is DefaultRepositorySelector; - /// for the .NET Compact Framework CompactRepositorySelector is the default - /// repository. - /// - /// - public static IRepositorySelector RepositorySelector - { - get { return s_repositorySelector; } - set { s_repositorySelector = value; } - } - - #endregion Public Static Methods - - #region Private Static Methods - - /// - /// Internal method to get pertinent version info. - /// - /// A string of version info. - private static string GetVersionInfo() - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); + } + + /// + /// Return the default instance. + /// + /// the repository to lookup in. + /// Return the default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] + public static ILoggerRepository GetLoggerRepository(string repository) + { + return GetRepository(repository); + } + + /// + /// Returns the default instance. + /// + /// The assembly to use to lookup the repository. + /// The default instance. + [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] + public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) + { + return GetRepository(repositoryAssembly); + } + + /// + /// Return the default instance. + /// + /// the repository to lookup in. + /// Return the default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + public static ILoggerRepository GetRepository(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + return RepositorySelector.GetRepository(repository); + } + + /// + /// Returns the default instance. + /// + /// The assembly to use to lookup the repository. + /// The default instance. + /// + /// + /// Returns the default instance. + /// + /// + public static ILoggerRepository GetRepository(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + return RepositorySelector.GetRepository(repositoryAssembly); + } + + /// + /// Returns the named logger if it exists. + /// + /// The repository to lookup in. + /// The fully qualified logger name to look for. + /// + /// The logger found, or null if the named logger does not exist in the + /// specified repository. + /// + /// + /// + /// If the named logger exists (in the specified repository) then it + /// returns a reference to the logger, otherwise it returns + /// null. + /// + /// + public static ILogger Exists(string repository, string name) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + if (name == null) + { + throw new ArgumentNullException("name"); + } + + return RepositorySelector.GetRepository(repository).Exists(name); + } + + /// + /// Returns the named logger if it exists. + /// + /// The assembly to use to lookup the repository. + /// The fully qualified logger name to look for. + /// + /// The logger found, or null if the named logger does not exist in the + /// specified assembly's repository. + /// + /// + /// + /// If the named logger exists (in the specified assembly's repository) then it + /// returns a reference to the logger, otherwise it returns + /// null. + /// + /// + public static ILogger Exists(Assembly repositoryAssembly, string name) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + if (name == null) + { + throw new ArgumentNullException("name"); + } + + return RepositorySelector.GetRepository(repositoryAssembly).Exists(name); + } + + /// + /// Returns all the currently defined loggers in the specified repository. + /// + /// The repository to lookup in. + /// All the defined loggers. + /// + /// + /// The root logger is not included in the returned array. + /// + /// + public static ILogger[] GetCurrentLoggers(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + return RepositorySelector.GetRepository(repository).GetCurrentLoggers(); + } + + /// + /// Returns all the currently defined loggers in the specified assembly's repository. + /// + /// The assembly to use to lookup the repository. + /// All the defined loggers. + /// + /// + /// The root logger is not included in the returned array. + /// + /// + public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers(); + } + + /// + /// Retrieves or creates a named logger. + /// + /// The repository to lookup in. + /// The name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Retrieves a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + public static ILogger GetLogger(string repository, string name) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + if (name == null) + { + throw new ArgumentNullException("name"); + } + + return RepositorySelector.GetRepository(repository).GetLogger(name); + } + + /// + /// Retrieves or creates a named logger. + /// + /// The assembly to use to lookup the repository. + /// The name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Retrieves a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + public static ILogger GetLogger(Assembly repositoryAssembly, string name) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + if (name == null) + { + throw new ArgumentNullException("name"); + } + + return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name); + } + + /// + /// Shorthand for . + /// + /// The repository to lookup in. + /// The of which the fullname will be used as the name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// + public static ILogger GetLogger(string repository, Type type) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + return RepositorySelector.GetRepository(repository).GetLogger(type.FullName); + } + + /// + /// Shorthand for . + /// + /// the assembly to use to lookup the repository. + /// The of which the fullname will be used as the name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// + public static ILogger GetLogger(Assembly repositoryAssembly, Type type) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName); + } + + /// + /// Shuts down the log4net system. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in all the + /// default repositories. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void Shutdown() + { + foreach (ILoggerRepository repository in GetAllRepositories()) + { + repository.Shutdown(); + } + } + + /// + /// Shuts down the repository for the repository specified. + /// + /// The repository to shutdown. + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// repository for the specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void ShutdownRepository(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + RepositorySelector.GetRepository(repository).Shutdown(); + } + + /// + /// Shuts down the repository for the repository specified. + /// + /// The assembly to use to lookup the repository. + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// repository for the repository. The repository is looked up using + /// the specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void ShutdownRepository(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + RepositorySelector.GetRepository(repositoryAssembly).Shutdown(); + } + + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// The repository to reset. + /// + /// + /// Resets all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set its default "off" value. + /// + /// + public static void ResetConfiguration(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + RepositorySelector.GetRepository(repository).ResetConfiguration(); + } + + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// The assembly to use to lookup the repository to reset. + /// + /// + /// Resets all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set its default "off" value. + /// + /// + public static void ResetConfiguration(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration(); + } + + /// + /// Creates a repository with the specified name. + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] + public static ILoggerRepository CreateDomain(string repository) + { + return CreateRepository(repository); + } + + /// + /// Creates a repository with the specified name. + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + return RepositorySelector.CreateRepository(repository, null); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An Exception will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] + public static ILoggerRepository CreateDomain(string repository, Type repositoryType) + { + return CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An Exception will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository, Type repositoryType) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + if (repositoryType == null) + { + throw new ArgumentNullException("repositoryType"); + } + + return RepositorySelector.CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] + public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) + { + return CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + if (repositoryType == null) + { + throw new ArgumentNullException("repositoryType"); + } + + return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Gets an array of all currently defined repositories. + /// + /// An array of all the known objects. + /// + /// + /// Gets an array of all currently defined repositories. + /// + /// + public static ILoggerRepository[] GetAllRepositories() + { + return RepositorySelector.GetAllRepositories(); + } + + /// + /// Gets or sets the repository selector used by the . + /// + /// + /// The repository selector used by the . + /// + /// + /// + /// The repository selector () is used by + /// the to create and select repositories + /// (). + /// + /// + /// The caller to supplies either a string name + /// or an assembly (if not supplied the assembly is inferred using + /// ). + /// + /// + /// This context is used by the selector to lookup a specific repository. + /// + /// + /// For the full .NET Framework, the default repository is DefaultRepositorySelector; + /// for the .NET Compact Framework CompactRepositorySelector is the default + /// repository. + /// + /// + public static IRepositorySelector RepositorySelector + { + get { return s_repositorySelector; } + set { s_repositorySelector = value; } + } + + /// + /// Internal method to get pertinent version info. + /// + /// A string of version info. + private static string GetVersionInfo() + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); #if NETSTANDARD1_3 Assembly myAssembly = typeof(LoggerManager).GetTypeInfo().Assembly; @@ -811,74 +825,68 @@ private static string GetVersionInfo() //sb.Append($"Loaded from [{myAssembly.Location}]. "); // TODO Assembly.Location available in netstandard1.5 sb.Append($"(.NET Framework [{RuntimeInformation.FrameworkDescription}] on {RuntimeInformation.OSDescription}"); #else - Assembly myAssembly = Assembly.GetExecutingAssembly(); - sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. "); - sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. "); - sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]"); -#if (!SSCLI) + Assembly myAssembly = Assembly.GetExecutingAssembly(); + sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. "); + sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. "); + sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]"); +#if !SSCLI sb.Append(" on ").Append(Environment.OSVersion.ToString()); #endif #endif // NETSTANDARD1_3 - sb.Append(")"); - return sb.ToString(); - } - -#if (!NETCF) - /// - /// Called when the event fires - /// - /// the that is exiting - /// null - /// - /// - /// Called when the event fires. - /// - /// - /// When the event is triggered the log4net system is . - /// - /// - private static void OnDomainUnload(object sender, EventArgs e) - { - Shutdown(); - } - - /// - /// Called when the event fires - /// - /// the that is exiting - /// null - /// - /// - /// Called when the event fires. - /// - /// - /// When the event is triggered the log4net system is . - /// - /// - private static void OnProcessExit(object sender, EventArgs e) - { - Shutdown(); - } + sb.Append(")"); + return sb.ToString(); + } + +#if !NETCF + /// + /// Called when the event fires. + /// + /// the that is exiting. + /// null. + /// + /// + /// Called when the event fires. + /// + /// + /// When the event is triggered the log4net system is . + /// + /// + private static void OnDomainUnload(object sender, EventArgs e) + { + Shutdown(); + } + + /// + /// Called when the event fires. + /// + /// the that is exiting. + /// null. + /// + /// + /// Called when the event fires. + /// + /// + /// When the event is triggered the log4net system is . + /// + /// + private static void OnProcessExit(object sender, EventArgs e) + { + Shutdown(); + } #endif - - #endregion Private Static Methods - - #region Private Static Fields - - /// - /// The fully qualified type of the LoggerManager class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(LoggerManager); - - /// - /// Initialize the default repository selector - /// - private static IRepositorySelector s_repositorySelector; - - #endregion Private Static Fields - } + + /// + /// The fully qualified type of the LoggerManager class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(LoggerManager); + + /// + /// Initialize the default repository selector. + /// + private static IRepositorySelector s_repositorySelector; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs index b3bf6a750d9..7511f37ae4e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs @@ -1,90 +1,76 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// namespace log4net.Core { - /// - /// Implementation of the interface. - /// - /// - /// - /// This class should be used as the base for all wrapper implementations. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public abstract class LoggerWrapperImpl : ILoggerWrapper - { - #region Protected Instance Constructors - - /// - /// Constructs a new wrapper for the specified logger. - /// - /// The logger to wrap. - /// - /// - /// Constructs a new wrapper for the specified logger. - /// - /// - protected LoggerWrapperImpl(ILogger logger) - { - m_logger = logger; - } - - #endregion Public Instance Constructors - - #region Implementation of ILoggerWrapper - - /// - /// Gets the implementation behind this wrapper object. - /// - /// - /// The object that this object is implementing. - /// - /// - /// - /// The Logger object may not be the same object as this object - /// because of logger decorators. - /// - /// - /// This gets the actual underlying objects that is used to process - /// the log events. - /// - /// - virtual public ILogger Logger - { - get { return m_logger; } - } - - #endregion - - #region Private Instance Fields - - /// - /// The logger that this object is wrapping - /// - private readonly ILogger m_logger; - - #endregion Private Instance Fields - } + /// + /// Implementation of the interface. + /// + /// + /// + /// This class should be used as the base for all wrapper implementations. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class LoggerWrapperImpl : ILoggerWrapper + { + /// + /// Initializes a new instance of the class. + /// Constructs a new wrapper for the specified logger. + /// + /// The logger to wrap. + /// + /// + /// Constructs a new wrapper for the specified logger. + /// + /// + protected LoggerWrapperImpl(ILogger logger) + { + this.m_logger = logger; + } + + /// + /// Gets the implementation behind this wrapper object. + /// + /// + /// The object that this object is implementing. + /// + /// + /// + /// The Logger object may not be the same object as this object + /// because of logger decorators. + /// + /// + /// This gets the actual underlying objects that is used to process + /// the log events. + /// + /// + public virtual ILogger Logger + { + get { return this.m_logger; } + } + + /// + /// The logger that this object is wrapping. + /// + private readonly ILogger m_logger; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs index b4b61d610d3..aefb3364c95 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs @@ -1,109 +1,108 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.IO; -#if (!NETCF) +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + + +#if !NETCF using System.Runtime.Serialization; + #if !NETSTANDARD1_3 using System.Security.Principal; + #endif #endif -using log4net.Util; using log4net.Repository; +using log4net.Util; namespace log4net.Core { - /// - /// Portable data structure used by - /// - /// - /// - /// Portable data structure used by - /// - /// - /// Nicko Cadell - public struct LoggingEventData - { - #region Public Instance Fields - - /// - /// The logger name. - /// - /// - /// - /// The logger name. - /// - /// - public string LoggerName; - - /// - /// Level of logging event. - /// - /// - /// - /// Level of logging event. Level cannot be Serializable - /// because it is a flyweight. Due to its special serialization it - /// cannot be declared final either. - /// - /// - public Level Level; - - /// - /// The application supplied message. - /// - /// - /// - /// The application supplied message of logging event. - /// - /// - public string Message; - - /// - /// The name of thread - /// - /// - /// - /// The name of thread in which this logging event was generated - /// - /// - public string ThreadName; - - /// - /// Gets or sets the local time the event was logged - /// - /// + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + + /// + /// Portable data structure used by . + /// + /// + /// + /// Portable data structure used by . + /// + /// + /// Nicko Cadell. + public struct LoggingEventData + { + /// + /// The logger name. + /// + /// + /// + /// The logger name. + /// + /// + public string LoggerName; + + /// + /// Level of logging event. + /// + /// + /// + /// Level of logging event. Level cannot be Serializable + /// because it is a flyweight. Due to its special serialization it + /// cannot be declared final either. + /// + /// + public Level Level; + + /// + /// The application supplied message. + /// + /// + /// + /// The application supplied message of logging event. + /// + /// + public string Message; + + /// + /// The name of thread. + /// + /// + /// + /// The name of thread in which this logging event was generated. + /// + /// + public string ThreadName; + + /// + /// Gets or sets the local time the event was logged. + /// + /// /// /// Prefer using the setter, since local time can be ambiguous. - /// - /// + /// + /// [Obsolete("Prefer using TimeStampUtc, since local time can be ambiguous in time zones with daylight savings time.. Scheduled removal in v11.0.0.")] - public DateTime TimeStamp; - + public DateTime TimeStamp; + /// - /// Gets or sets the UTC time the event was logged + /// Gets or sets the UTC time the event was logged. /// /// /// @@ -115,426 +114,422 @@ public DateTime TimeStampUtc { get { - if (TimeStamp != default(DateTime) && - _timeStampUtc == default(DateTime)) + if (this.TimeStamp != default(DateTime) && + this._timeStampUtc == default(DateTime)) { // TimeStamp field has been set explicitly but TimeStampUtc hasn't // => use TimeStamp - return TimeStamp.ToUniversalTime(); + return this.TimeStamp.ToUniversalTime(); } - return _timeStampUtc; + + return this._timeStampUtc; } + set { - _timeStampUtc = value; + this._timeStampUtc = value; + // For backwards compatibility - TimeStamp = _timeStampUtc.ToLocalTime(); + this.TimeStamp = this._timeStampUtc.ToLocalTime(); } } + private DateTime _timeStampUtc; #pragma warning restore 618 /// - /// Location information for the caller. - /// - /// - /// - /// Location information for the caller. - /// - /// - public LocationInfo LocationInfo; - - /// - /// String representation of the user - /// - /// - /// - /// String representation of the user's windows name, - /// like DOMAIN\username - /// - /// - public string UserName; - - /// - /// String representation of the identity. - /// - /// - /// - /// String representation of the current thread's principal identity. - /// - /// - public string Identity; - - /// - /// The string representation of the exception - /// - /// - /// - /// The string representation of the exception - /// - /// - public string ExceptionString; - - /// - /// String representation of the AppDomain. - /// - /// - /// - /// String representation of the AppDomain. - /// - /// - public string Domain; - - /// - /// Additional event specific properties - /// - /// - /// - /// A logger or an appender may attach additional - /// properties to specific events. These properties - /// have a string key and an object value. - /// - /// - public PropertiesDictionary Properties; - - #endregion Public Instance Fields - } - - /// - /// Flags passed to the property - /// - /// - /// - /// Flags passed to the property - /// - /// - /// Nicko Cadell - [Flags] public enum FixFlags - { - /// - /// Fix the MDC - /// - [Obsolete("Replaced by composite Properties. Scheduled removal in v10.0.0.")] - Mdc = 0x01, - - /// - /// Fix the NDC - /// - Ndc = 0x02, - - /// - /// Fix the rendered message - /// - Message = 0x04, - - /// - /// Fix the thread name - /// - ThreadName = 0x08, - - /// - /// Fix the callers location information - /// - /// - /// CAUTION: Very slow to generate - /// - LocationInfo = 0x10, - - /// - /// Fix the callers windows user name - /// - /// - /// CAUTION: Slow to generate - /// - UserName = 0x20, - - /// - /// Fix the domain friendly name - /// - Domain = 0x40, - - /// - /// Fix the callers principal name - /// - /// - /// CAUTION: May be slow to generate - /// - Identity = 0x80, - - /// - /// Fix the exception text - /// - Exception = 0x100, - - /// - /// Fix the event properties. Active properties must implement in order to be eligible for fixing. - /// - Properties = 0x200, - - /// - /// No fields fixed - /// - None = 0x0, - - /// - /// All fields fixed - /// - All = 0xFFFFFFF, - - /// - /// Partial fields fixed - /// - /// - /// - /// This set of partial fields gives good performance. The following fields are fixed: - /// - /// - /// - /// - /// - /// - /// - /// - /// - Partial = Message | ThreadName | Exception | Domain | Properties, - } - - /// - /// The internal representation of logging events. - /// - /// - /// - /// When an affirmative decision is made to log then a - /// instance is created. This instance - /// is passed around to the different log4net components. - /// - /// - /// This class is of concern to those wishing to extend log4net. - /// - /// - /// Some of the values in instances of - /// are considered volatile, that is the values are correct at the - /// time the event is delivered to appenders, but will not be consistent - /// at any time afterwards. If an event is to be stored and then processed - /// at a later time these volatile values must be fixed by calling - /// . There is a performance penalty - /// for incurred by calling but it - /// is essential to maintaining data consistency. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Douglas de la Torre - /// Daniel Cazzulino + /// Location information for the caller. + /// + /// + /// + /// Location information for the caller. + /// + /// + public LocationInfo LocationInfo; + + /// + /// String representation of the user. + /// + /// + /// + /// String representation of the user's windows name, + /// like DOMAIN\username. + /// + /// + public string UserName; + + /// + /// String representation of the identity. + /// + /// + /// + /// String representation of the current thread's principal identity. + /// + /// + public string Identity; + + /// + /// The string representation of the exception. + /// + /// + /// + /// The string representation of the exception. + /// + /// + public string ExceptionString; + + /// + /// String representation of the AppDomain. + /// + /// + /// + /// String representation of the AppDomain. + /// + /// + public string Domain; + + /// + /// Additional event specific properties. + /// + /// + /// + /// A logger or an appender may attach additional + /// properties to specific events. These properties + /// have a string key and an object value. + /// + /// + public PropertiesDictionary Properties; + } + + /// + /// Flags passed to the property. + /// + /// + /// + /// Flags passed to the property. + /// + /// + /// Nicko Cadell. + [Flags] + public enum FixFlags + { + /// + /// Fix the MDC + /// + [Obsolete("Replaced by composite Properties. Scheduled removal in v10.0.0.")] + Mdc = 0x01, + + /// + /// Fix the NDC + /// + Ndc = 0x02, + + /// + /// Fix the rendered message + /// + Message = 0x04, + + /// + /// Fix the thread name + /// + ThreadName = 0x08, + + /// + /// Fix the callers location information + /// + /// + /// CAUTION: Very slow to generate + /// + LocationInfo = 0x10, + + /// + /// Fix the callers windows user name + /// + /// + /// CAUTION: Slow to generate + /// + UserName = 0x20, + + /// + /// Fix the domain friendly name + /// + Domain = 0x40, + + /// + /// Fix the callers principal name + /// + /// + /// CAUTION: May be slow to generate + /// + Identity = 0x80, + + /// + /// Fix the exception text + /// + Exception = 0x100, + + /// + /// Fix the event properties. Active properties must implement in order to be eligible for fixing. + /// + Properties = 0x200, + + /// + /// No fields fixed + /// + None = 0x0, + + /// + /// All fields fixed + /// + All = 0xFFFFFFF, + + /// + /// Partial fields fixed + /// + /// + /// + /// This set of partial fields gives good performance. The following fields are fixed: + /// + /// + /// + /// + /// + /// + /// + /// + /// + Partial = Message | ThreadName | Exception | Domain | Properties, + } + + /// + /// The internal representation of logging events. + /// + /// + /// + /// When an affirmative decision is made to log then a + /// instance is created. This instance + /// is passed around to the different log4net components. + /// + /// + /// This class is of concern to those wishing to extend log4net. + /// + /// + /// Some of the values in instances of + /// are considered volatile, that is the values are correct at the + /// time the event is delivered to appenders, but will not be consistent + /// at any time afterwards. If an event is to be stored and then processed + /// at a later time these volatile values must be fixed by calling + /// . There is a performance penalty + /// for incurred by calling but it + /// is essential to maintaining data consistency. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Douglas de la Torre. + /// Daniel Cazzulino. #if !NETCF - [Serializable] + [Serializable] #endif - public class LoggingEvent + public class LoggingEvent #if !NETCF - : ISerializable + : ISerializable #endif - { - private readonly static Type declaringType = typeof(LoggingEvent); - - #region Public Instance Constructors - - /// - /// Initializes a new instance of the class - /// from the supplied parameters. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The repository this event is logged in. - /// The name of the logger of this event. - /// The level of this event. - /// The message of this event. - /// The exception for this event. - /// - /// - /// Except , and , - /// all fields of LoggingEvent are filled when actually needed. Call - /// to cache all data locally - /// to prevent inconsistencies. - /// - /// This method is called by the log4net framework - /// to create a logging event. - /// - /// - public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, string loggerName, Level level, object message, Exception exception) - { - m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; - m_message = message; - m_repository = repository; - m_thrownException = exception; - - m_data.LoggerName = loggerName; - m_data.Level = level; - - // Store the event creation time - m_data.TimeStampUtc = DateTime.UtcNow; - } - - /// - /// Initializes a new instance of the class - /// using specific data. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The repository this event is logged in. - /// Data used to initialize the logging event. - /// The fields in the struct that have already been fixed. - /// - /// - /// This constructor is provided to allow a - /// to be created independently of the log4net framework. This can - /// be useful if you require a custom serialization scheme. - /// - /// - /// Use the method to obtain an - /// instance of the class. - /// - /// - /// The parameter should be used to specify which fields in the - /// struct have been preset. Fields not specified in the - /// will be captured from the environment if requested or fixed. - /// - /// - public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data, FixFlags fixedData) - { - m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; - m_repository = repository; - - m_data = data; - m_fixFlags = fixedData; - } - - /// - /// Initializes a new instance of the class - /// using specific data. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The repository this event is logged in. - /// Data used to initialize the logging event. - /// - /// - /// This constructor is provided to allow a - /// to be created independently of the log4net framework. This can - /// be useful if you require a custom serialization scheme. - /// - /// - /// Use the method to obtain an - /// instance of the class. - /// - /// - /// This constructor sets this objects flags to , - /// this assumes that all the data relating to this event is passed in via the - /// parameter and no other data should be captured from the environment. - /// - /// - public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data) : this(callerStackBoundaryDeclaringType, repository, data, FixFlags.All) - { - } - - /// - /// Initializes a new instance of the class - /// using specific data. - /// - /// Data used to initialize the logging event. - /// - /// - /// This constructor is provided to allow a - /// to be created independently of the log4net framework. This can - /// be useful if you require a custom serialization scheme. - /// - /// - /// Use the method to obtain an - /// instance of the class. - /// - /// - /// This constructor sets this objects flags to , - /// this assumes that all the data relating to this event is passed in via the - /// parameter and no other data should be captured from the environment. - /// - /// - public LoggingEvent(LoggingEventData data) : this(null, null, data) - { - } - - #endregion Public Instance Constructors - - #region Protected Instance Constructors + { + private static readonly Type declaringType = typeof(LoggingEvent); + + /// + /// Initializes a new instance of the class + /// from the supplied parameters. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The repository this event is logged in. + /// The name of the logger of this event. + /// The level of this event. + /// The message of this event. + /// The exception for this event. + /// + /// + /// Except , and , + /// all fields of LoggingEvent are filled when actually needed. Call + /// to cache all data locally + /// to prevent inconsistencies. + /// + /// This method is called by the log4net framework + /// to create a logging event. + /// + /// + public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, string loggerName, Level level, object message, Exception exception) + { + this.m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; + this.m_message = message; + this.m_repository = repository; + this.m_thrownException = exception; -#if !(NETCF || NETSTANDARD1_3) + this.m_data.LoggerName = loggerName; + this.m_data.Level = level; - /// - /// Serialization constructor - /// - /// The that holds the serialized object data. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected LoggingEvent(SerializationInfo info, StreamingContext context) - { - m_data.LoggerName = info.GetString("LoggerName"); - - // Note we are deserializing the whole level object. That is the - // name and the value. This value is correct for the source - // hierarchy but may not be for the target hierarchy that this - // event may be re-logged into. If it is to be re-logged it may - // be necessary to re-lookup the level based only on the name. - m_data.Level = (Level)info.GetValue("Level", typeof(Level)); - - m_data.Message = info.GetString("Message"); - m_data.ThreadName = info.GetString("ThreadName"); - m_data.TimeStampUtc = info.GetDateTime("TimeStamp").ToUniversalTime(); - m_data.LocationInfo = (LocationInfo) info.GetValue("LocationInfo", typeof(LocationInfo)); - m_data.UserName = info.GetString("UserName"); - m_data.ExceptionString = info.GetString("ExceptionString"); - m_data.Properties = (PropertiesDictionary) info.GetValue("Properties", typeof(PropertiesDictionary)); - m_data.Domain = info.GetString("Domain"); - m_data.Identity = info.GetString("Identity"); - - // We have restored all the values of this instance, i.e. all the values are fixed - // Set the fix flags otherwise the data values may be overwritten from the current environment. - m_fixFlags = FixFlags.All; - } + // Store the event creation time + this.m_data.TimeStampUtc = DateTime.UtcNow; + } -#endif + /// + /// Initializes a new instance of the class + /// using specific data. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The repository this event is logged in. + /// Data used to initialize the logging event. + /// The fields in the struct that have already been fixed. + /// + /// + /// This constructor is provided to allow a + /// to be created independently of the log4net framework. This can + /// be useful if you require a custom serialization scheme. + /// + /// + /// Use the method to obtain an + /// instance of the class. + /// + /// + /// The parameter should be used to specify which fields in the + /// struct have been preset. Fields not specified in the + /// will be captured from the environment if requested or fixed. + /// + /// + public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data, FixFlags fixedData) + { + this.m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; + this.m_repository = repository; + + this.m_data = data; + this.m_fixFlags = fixedData; + } + + /// + /// Initializes a new instance of the class + /// using specific data. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The repository this event is logged in. + /// Data used to initialize the logging event. + /// + /// + /// This constructor is provided to allow a + /// to be created independently of the log4net framework. This can + /// be useful if you require a custom serialization scheme. + /// + /// + /// Use the method to obtain an + /// instance of the class. + /// + /// + /// This constructor sets this objects flags to , + /// this assumes that all the data relating to this event is passed in via the + /// parameter and no other data should be captured from the environment. + /// + /// + public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data) + : this(callerStackBoundaryDeclaringType, repository, data, FixFlags.All) + { + } - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the time when the current process started. - /// - /// - /// This is the time when this process started. - /// - /// - /// - /// The TimeStamp is stored internally in UTC and converted to the local time zone for this computer. - /// - /// - /// Tries to get the start time for the current process. - /// Failing that it returns the time of the first call to - /// this property. - /// - /// - /// Note that AppDomains may be loaded and unloaded within the - /// same process without the process terminating and therefore - /// without the process start time being reset. - /// - /// - public static DateTime StartTime - { - get { return SystemInfo.ProcessStartTimeUtc.ToLocalTime(); } - } + /// + /// Initializes a new instance of the class + /// using specific data. + /// + /// Data used to initialize the logging event. + /// + /// + /// This constructor is provided to allow a + /// to be created independently of the log4net framework. This can + /// be useful if you require a custom serialization scheme. + /// + /// + /// Use the method to obtain an + /// instance of the class. + /// + /// + /// This constructor sets this objects flags to , + /// this assumes that all the data relating to this event is passed in via the + /// parameter and no other data should be captured from the environment. + /// + /// + public LoggingEvent(LoggingEventData data) + : this(null, null, data) + { + } + +#if !(NETCF || NETSTANDARD1_3) + + /// + /// Initializes a new instance of the class. + /// Serialization constructor. + /// + /// The that holds the serialized object data. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected LoggingEvent(SerializationInfo info, StreamingContext context) + { + this.m_data.LoggerName = info.GetString("LoggerName"); + + // Note we are deserializing the whole level object. That is the + // name and the value. This value is correct for the source + // hierarchy but may not be for the target hierarchy that this + // event may be re-logged into. If it is to be re-logged it may + // be necessary to re-lookup the level based only on the name. + this.m_data.Level = (Level)info.GetValue("Level", typeof(Level)); + + this.m_data.Message = info.GetString("Message"); + this.m_data.ThreadName = info.GetString("ThreadName"); + this.m_data.TimeStampUtc = info.GetDateTime("TimeStamp").ToUniversalTime(); + this.m_data.LocationInfo = (LocationInfo)info.GetValue("LocationInfo", typeof(LocationInfo)); + this.m_data.UserName = info.GetString("UserName"); + this.m_data.ExceptionString = info.GetString("ExceptionString"); + this.m_data.Properties = (PropertiesDictionary)info.GetValue("Properties", typeof(PropertiesDictionary)); + this.m_data.Domain = info.GetString("Domain"); + this.m_data.Identity = info.GetString("Identity"); + + // We have restored all the values of this instance, i.e. all the values are fixed + // Set the fix flags otherwise the data values may be overwritten from the current environment. + this.m_fixFlags = FixFlags.All; + } + +#endif + + /// + /// Gets the time when the current process started. + /// + /// + /// This is the time when this process started. + /// + /// + /// + /// The TimeStamp is stored internally in UTC and converted to the local time zone for this computer. + /// + /// + /// Tries to get the start time for the current process. + /// Failing that it returns the time of the first call to + /// this property. + /// + /// + /// Note that AppDomains may be loaded and unloaded within the + /// same process without the process terminating and therefore + /// without the process start time being reset. + /// + /// + public static DateTime StartTime + { + get { return SystemInfo.ProcessStartTimeUtc.ToLocalTime(); } + } /// /// Gets the UTC time when the current process started. @@ -557,39 +552,39 @@ public static DateTime StartTime public static DateTime StartTimeUtc { get { return SystemInfo.ProcessStartTimeUtc; } - } - - /// - /// Gets the of the logging event. - /// - /// - /// The of the logging event. - /// - /// - /// - /// Gets the of the logging event. - /// - /// - public Level Level - { - get { return m_data.Level; } - } - - /// - /// Gets the time of the logging event. - /// - /// - /// The time of the logging event. - /// - /// - /// - /// The TimeStamp is stored in UTC and converted to the local time zone for this computer. - /// - /// - public DateTime TimeStamp - { - get { return m_data.TimeStampUtc.ToLocalTime(); } - } + } + + /// + /// Gets the of the logging event. + /// + /// + /// The of the logging event. + /// + /// + /// + /// Gets the of the logging event. + /// + /// + public Level Level + { + get { return this.m_data.Level; } + } + + /// + /// Gets the time of the logging event. + /// + /// + /// The time of the logging event. + /// + /// + /// + /// The TimeStamp is stored in UTC and converted to the local time zone for this computer. + /// + /// + public DateTime TimeStamp + { + get { return this.m_data.TimeStampUtc.ToLocalTime(); } + } /// /// Gets UTC the time of the logging event. @@ -599,1029 +594,1023 @@ public DateTime TimeStamp /// public DateTime TimeStampUtc { - get { return m_data.TimeStampUtc; } - } - - /// - /// Gets the name of the logger that logged the event. - /// - /// - /// The name of the logger that logged the event. - /// - /// - /// - /// Gets the name of the logger that logged the event. - /// - /// - public string LoggerName - { - get { return m_data.LoggerName; } - } - - /// - /// Gets the location information for this logging event. - /// - /// - /// The location information for this logging event. - /// - /// - /// - /// The collected information is cached for future use. - /// - /// - /// See the class for more information on - /// supported frameworks and the different behavior in Debug and - /// Release builds. - /// - /// - public LocationInfo LocationInformation - { - get - { - if (m_data.LocationInfo == null && this.m_cacheUpdatable) - { - m_data.LocationInfo = new LocationInfo(m_callerStackBoundaryDeclaringType); - } - return m_data.LocationInfo; - } - } - - /// - /// Gets the message object used to initialize this event. - /// - /// - /// The message object used to initialize this event. - /// - /// - /// - /// Gets the message object used to initialize this event. - /// Note that this event may not have a valid message object. - /// If the event is serialized the message object will not - /// be transferred. To get the text of the message the - /// property must be used - /// not this property. - /// - /// - /// If there is no defined message object for this event then - /// null will be returned. - /// - /// - public object MessageObject - { - get { return m_message; } - } - - /// - /// Gets the exception object used to initialize this event. - /// - /// - /// The exception object used to initialize this event. - /// - /// - /// - /// Gets the exception object used to initialize this event. - /// Note that this event may not have a valid exception object. - /// If the event is serialized the exception object will not - /// be transferred. To get the text of the exception the - /// method must be used - /// not this property. - /// - /// - /// If there is no defined exception object for this event then - /// null will be returned. - /// - /// - public Exception ExceptionObject - { - get { return m_thrownException; } - } - - /// - /// The that this event was created in. - /// - /// - /// - /// The that this event was created in. - /// - /// - public ILoggerRepository Repository - { - get { return m_repository; } - } - - /// - /// Ensure that the repository is set. - /// - /// the value for the repository - internal void EnsureRepository(ILoggerRepository repository) - { - if (repository != null) - { - m_repository = repository; - } - } - - /// - /// Gets the message, rendered through the . - /// - /// - /// The message rendered through the . - /// - /// - /// - /// The collected information is cached for future use. - /// - /// - public string RenderedMessage - { - get - { - if (m_data.Message == null && this.m_cacheUpdatable) - { - if (m_message == null) - { - m_data.Message = ""; - } - else if (m_message is string) - { - m_data.Message = (m_message as string); - } - else if (m_repository != null) - { - m_data.Message = m_repository.RendererMap.FindAndRender(m_message); - } - else - { - // Very last resort - m_data.Message = m_message.ToString(); - } - } - return m_data.Message; - } - } - - /// - /// Write the rendered message to a TextWriter - /// - /// the writer to write the message to - /// - /// - /// Unlike the property this method - /// does store the message data in the internal cache. Therefore - /// if called only once this method should be faster than the - /// property, however if the message is - /// to be accessed multiple times then the property will be more efficient. - /// - /// - public void WriteRenderedMessage(TextWriter writer) - { - if (m_data.Message != null) - { - writer.Write(m_data.Message); - } - else - { - if (m_message != null) - { - if (m_message is string) - { - writer.Write(m_message as string); - } - else if (m_repository != null) - { - m_repository.RendererMap.FindAndRender(m_message, writer); - } - else - { - // Very last resort - writer.Write(m_message.ToString()); - } - } - } - } - - /// - /// Gets the name of the current thread. - /// - /// - /// The name of the current thread, or the thread ID when - /// the name is not available. - /// - /// - /// - /// The collected information is cached for future use. - /// - /// - public string ThreadName - { - get - { - if (m_data.ThreadName == null && this.m_cacheUpdatable) - { -#if NETCF || NETSTANDARD1_3 - // Get thread ID only - m_data.ThreadName = SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); -#else - m_data.ThreadName = System.Threading.Thread.CurrentThread.Name; - if (m_data.ThreadName == null || m_data.ThreadName.Length == 0) - { - // The thread name is not available. Therefore we - // go the the AppDomain to get the ID of the - // current thread. (Why don't Threads know their own ID?) - try - { - m_data.ThreadName = SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current thread ID. Error Ignored. Empty thread name."); - - // As a last resort use the hash code of the Thread object - m_data.ThreadName = System.Threading.Thread.CurrentThread.GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture); - } - } -#endif - } - return m_data.ThreadName; - } - } - - /// - /// Gets the name of the current user. - /// - /// - /// The name of the current user, or NOT AVAILABLE when the - /// underlying runtime has no support for retrieving the name of the - /// current user. - /// - /// - /// - /// Calls WindowsIdentity.GetCurrent().Name to get the name of - /// the current windows user. - /// - /// - /// To improve performance, we could cache the string representation of - /// the name, and reuse that as long as the identity stayed constant. - /// Once the identity changed, we would need to re-assign and re-render - /// the string. - /// - /// - /// However, the WindowsIdentity.GetCurrent() call seems to - /// return different objects every time, so the current implementation - /// doesn't do this type of caching. - /// - /// - /// Timing for these operations: - /// - /// - /// - /// Method - /// Results - /// - /// - /// WindowsIdentity.GetCurrent() - /// 10000 loops, 00:00:00.2031250 seconds - /// - /// - /// WindowsIdentity.GetCurrent().Name - /// 10000 loops, 00:00:08.0468750 seconds - /// - /// - /// - /// This means we could speed things up almost 40 times by caching the - /// value of the WindowsIdentity.GetCurrent().Name property, since - /// this takes (8.04-0.20) = 7.84375 seconds. - /// - /// - public string UserName - { - get - { - if (m_data.UserName == null && this.m_cacheUpdatable) - { -#if (NETCF || SSCLI || NETSTANDARD1_3) // NETSTANDARD1_3 TODO requires platform-specific code - // On compact framework there's no notion of current Windows user - m_data.UserName = SystemInfo.NotAvailableText; -#else - try - { - WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); - if (windowsIdentity != null && windowsIdentity.Name != null) - { - m_data.UserName = windowsIdentity.Name; - } - else - { - m_data.UserName = ""; - } - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current windows identity. Error Ignored. Empty user name."); - - m_data.UserName = ""; - } -#endif - } - return m_data.UserName; - } - } - - /// - /// Gets the identity of the current thread principal. - /// - /// - /// The string name of the identity of the current thread principal. - /// - /// - /// - /// Calls System.Threading.Thread.CurrentPrincipal.Identity.Name to get - /// the name of the current thread principal. - /// - /// - public string Identity - { - get - { - if (m_data.Identity == null && this.m_cacheUpdatable) - { -#if (NETCF || SSCLI || NETSTANDARD1_3) - // On compact framework there's no notion of current thread principals - m_data.Identity = SystemInfo.NotAvailableText; -#else - try - { - if (System.Threading.Thread.CurrentPrincipal != null && - System.Threading.Thread.CurrentPrincipal.Identity != null && - System.Threading.Thread.CurrentPrincipal.Identity.Name != null) - { - m_data.Identity = System.Threading.Thread.CurrentPrincipal.Identity.Name; - } - else - { - m_data.Identity = ""; - } - } - catch (ObjectDisposedException) - { - // This exception will occur if System.Threading.Thread.CurrentPrincipal.Identity is not null but - // the getter of the property Name tries to access disposed objects. - // Seen to happen on IIS 7 or greater with windows authentication. - LogLog.Debug(declaringType, "Object disposed exception while trying to get current thread principal. Error Ignored. Empty identity name."); - - m_data.Identity = ""; - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored. Empty identity name."); - - m_data.Identity = ""; - } -#endif - } - return m_data.Identity; - } - } - - /// - /// Gets the AppDomain friendly name. - /// - /// - /// The AppDomain friendly name. - /// - /// - /// - /// Gets the AppDomain friendly name. - /// - /// - public string Domain - { - get - { - if (m_data.Domain == null && this.m_cacheUpdatable) - { - m_data.Domain = SystemInfo.ApplicationFriendlyName; - } - return m_data.Domain; - } - } - - /// - /// Additional event specific properties. - /// - /// - /// Additional event specific properties. - /// - /// - /// - /// A logger or an appender may attach additional - /// properties to specific events. These properties - /// have a string key and an object value. - /// - /// - /// This property is for events that have been added directly to - /// this event. The aggregate properties (which include these - /// event properties) can be retrieved using - /// and . - /// - /// - /// Once the properties have been fixed this property - /// returns the combined cached properties. This ensures that updates to - /// this property are always reflected in the underlying storage. When - /// returning the combined properties there may be more keys in the - /// Dictionary than expected. - /// - /// - public PropertiesDictionary Properties - { - get - { - // If we have cached properties then return that otherwise changes will be lost - if (m_data.Properties != null) - { - return m_data.Properties; - } - - if (m_eventProperties == null) - { - m_eventProperties = new PropertiesDictionary(); - } - return m_eventProperties; - } - } - - /// - /// The fixed fields in this event - /// - /// - /// The set of fields that are fixed in this event - /// - /// - /// - /// Fields will not be fixed if they have previously been fixed. - /// It is not possible to 'unfix' a field. - /// - /// - public FixFlags Fix - { - get { return m_fixFlags; } - set { this.FixVolatileData(value); } - } - - #endregion Public Instance Properties - - #region Implementation of ISerializable + get { return this.m_data.TimeStampUtc; } + } -#if !NETCF + /// + /// Gets the name of the logger that logged the event. + /// + /// + /// The name of the logger that logged the event. + /// + /// + /// + /// Gets the name of the logger that logged the event. + /// + /// + public string LoggerName + { + get { return this.m_data.LoggerName; } + } - /// - /// Serializes this object into the provided. - /// - /// The to populate with data. - /// The destination for this serialization. - /// - /// - /// The data in this event must be fixed before it can be serialized. - /// - /// - /// The method must be called during the - /// method call if this event - /// is to be used outside that method. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecurityCritical] -#else - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] -#endif - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - // The caller must call FixVolatileData before this object - // can be serialized. - - info.AddValue("LoggerName", m_data.LoggerName); - info.AddValue("Level", m_data.Level); - info.AddValue("Message", m_data.Message); - info.AddValue("ThreadName", m_data.ThreadName); - // TODO: consider serializing UTC rather than local time. Not implemented here because it - // would give an unexpected result if client and server have different versions of this class. + /// + /// Gets the location information for this logging event. + /// + /// + /// The location information for this logging event. + /// + /// + /// + /// The collected information is cached for future use. + /// + /// + /// See the class for more information on + /// supported frameworks and the different behavior in Debug and + /// Release builds. + /// + /// + public LocationInfo LocationInformation + { + get + { + if (this.m_data.LocationInfo == null && this.m_cacheUpdatable) + { + this.m_data.LocationInfo = new LocationInfo(this.m_callerStackBoundaryDeclaringType); + } + + return this.m_data.LocationInfo; + } + } + + /// + /// Gets the message object used to initialize this event. + /// + /// + /// The message object used to initialize this event. + /// + /// + /// + /// Gets the message object used to initialize this event. + /// Note that this event may not have a valid message object. + /// If the event is serialized the message object will not + /// be transferred. To get the text of the message the + /// property must be used + /// not this property. + /// + /// + /// If there is no defined message object for this event then + /// null will be returned. + /// + /// + public object MessageObject + { + get { return this.m_message; } + } + + /// + /// Gets the exception object used to initialize this event. + /// + /// + /// The exception object used to initialize this event. + /// + /// + /// + /// Gets the exception object used to initialize this event. + /// Note that this event may not have a valid exception object. + /// If the event is serialized the exception object will not + /// be transferred. To get the text of the exception the + /// method must be used + /// not this property. + /// + /// + /// If there is no defined exception object for this event then + /// null will be returned. + /// + /// + public Exception ExceptionObject + { + get { return this.m_thrownException; } + } + + /// + /// Gets the that this event was created in. + /// + /// + /// + /// The that this event was created in. + /// + /// + public ILoggerRepository Repository + { + get { return this.m_repository; } + } + + /// + /// Ensure that the repository is set. + /// + /// the value for the repository. + internal void EnsureRepository(ILoggerRepository repository) + { + if (repository != null) + { + this.m_repository = repository; + } + } + + /// + /// Gets the message, rendered through the . + /// + /// + /// The message rendered through the . + /// + /// + /// + /// The collected information is cached for future use. + /// + /// + public string RenderedMessage + { + get + { + if (this.m_data.Message == null && this.m_cacheUpdatable) + { + if (this.m_message == null) + { + this.m_data.Message = string.Empty; + } + else if (this.m_message is string) + { + this.m_data.Message = this.m_message as string; + } + else if (this.m_repository != null) + { + this.m_data.Message = this.m_repository.RendererMap.FindAndRender(this.m_message); + } + else + { + // Very last resort + this.m_data.Message = this.m_message.ToString(); + } + } + + return this.m_data.Message; + } + } + + /// + /// Write the rendered message to a TextWriter. + /// + /// the writer to write the message to. + /// + /// + /// Unlike the property this method + /// does store the message data in the internal cache. Therefore + /// if called only once this method should be faster than the + /// property, however if the message is + /// to be accessed multiple times then the property will be more efficient. + /// + /// + public void WriteRenderedMessage(TextWriter writer) + { + if (this.m_data.Message != null) + { + writer.Write(this.m_data.Message); + } + else + { + if (this.m_message != null) + { + if (this.m_message is string) + { + writer.Write(this.m_message as string); + } + else if (this.m_repository != null) + { + this.m_repository.RendererMap.FindAndRender(this.m_message, writer); + } + else + { + // Very last resort + writer.Write(this.m_message.ToString()); + } + } + } + } + + /// + /// Gets the name of the current thread. + /// + /// + /// The name of the current thread, or the thread ID when + /// the name is not available. + /// + /// + /// + /// The collected information is cached for future use. + /// + /// + public string ThreadName + { + get + { + if (this.m_data.ThreadName == null && this.m_cacheUpdatable) + { +#if NETCF || NETSTANDARD1_3 + // Get thread ID only + m_data.ThreadName = SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); +#else + this.m_data.ThreadName = System.Threading.Thread.CurrentThread.Name; + if (this.m_data.ThreadName == null || this.m_data.ThreadName.Length == 0) + { + // The thread name is not available. Therefore we + // go the the AppDomain to get the ID of the + // current thread. (Why don't Threads know their own ID?) + try + { + this.m_data.ThreadName = SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current thread ID. Error Ignored. Empty thread name."); + + // As a last resort use the hash code of the Thread object + this.m_data.ThreadName = System.Threading.Thread.CurrentThread.GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture); + } + } +#endif + } + + return this.m_data.ThreadName; + } + } + + /// + /// Gets the name of the current user. + /// + /// + /// The name of the current user, or NOT AVAILABLE when the + /// underlying runtime has no support for retrieving the name of the + /// current user. + /// + /// + /// + /// Calls WindowsIdentity.GetCurrent().Name to get the name of + /// the current windows user. + /// + /// + /// To improve performance, we could cache the string representation of + /// the name, and reuse that as long as the identity stayed constant. + /// Once the identity changed, we would need to re-assign and re-render + /// the string. + /// + /// + /// However, the WindowsIdentity.GetCurrent() call seems to + /// return different objects every time, so the current implementation + /// doesn't do this type of caching. + /// + /// + /// Timing for these operations: + /// + /// + /// + /// Method + /// Results + /// + /// + /// WindowsIdentity.GetCurrent() + /// 10000 loops, 00:00:00.2031250 seconds + /// + /// + /// WindowsIdentity.GetCurrent().Name + /// 10000 loops, 00:00:08.0468750 seconds + /// + /// + /// + /// This means we could speed things up almost 40 times by caching the + /// value of the WindowsIdentity.GetCurrent().Name property, since + /// this takes (8.04-0.20) = 7.84375 seconds. + /// + /// + public string UserName + { + get + { + if (this.m_data.UserName == null && this.m_cacheUpdatable) + { +#if NETCF || SSCLI || NETSTANDARD1_3 // NETSTANDARD1_3 TODO requires platform-specific code + // On compact framework there's no notion of current Windows user + m_data.UserName = SystemInfo.NotAvailableText; +#else + try + { + WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); + if (windowsIdentity != null && windowsIdentity.Name != null) + { + this.m_data.UserName = windowsIdentity.Name; + } + else + { + this.m_data.UserName = string.Empty; + } + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current windows identity. Error Ignored. Empty user name."); + + this.m_data.UserName = string.Empty; + } +#endif + } + + return this.m_data.UserName; + } + } + + /// + /// Gets the identity of the current thread principal. + /// + /// + /// The string name of the identity of the current thread principal. + /// + /// + /// + /// Calls System.Threading.Thread.CurrentPrincipal.Identity.Name to get + /// the name of the current thread principal. + /// + /// + public string Identity + { + get + { + if (this.m_data.Identity == null && this.m_cacheUpdatable) + { +#if NETCF || SSCLI || NETSTANDARD1_3 + // On compact framework there's no notion of current thread principals + m_data.Identity = SystemInfo.NotAvailableText; +#else + try + { + if (System.Threading.Thread.CurrentPrincipal != null && + System.Threading.Thread.CurrentPrincipal.Identity != null && + System.Threading.Thread.CurrentPrincipal.Identity.Name != null) + { + this.m_data.Identity = System.Threading.Thread.CurrentPrincipal.Identity.Name; + } + else + { + this.m_data.Identity = string.Empty; + } + } + catch (ObjectDisposedException) + { + // This exception will occur if System.Threading.Thread.CurrentPrincipal.Identity is not null but + // the getter of the property Name tries to access disposed objects. + // Seen to happen on IIS 7 or greater with windows authentication. + LogLog.Debug(declaringType, "Object disposed exception while trying to get current thread principal. Error Ignored. Empty identity name."); + + this.m_data.Identity = string.Empty; + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored. Empty identity name."); + + this.m_data.Identity = string.Empty; + } +#endif + } + + return this.m_data.Identity; + } + } + + /// + /// Gets the AppDomain friendly name. + /// + /// + /// The AppDomain friendly name. + /// + /// + /// + /// Gets the AppDomain friendly name. + /// + /// + public string Domain + { + get + { + if (this.m_data.Domain == null && this.m_cacheUpdatable) + { + this.m_data.Domain = SystemInfo.ApplicationFriendlyName; + } + + return this.m_data.Domain; + } + } + + /// + /// Gets additional event specific properties. + /// + /// + /// Additional event specific properties. + /// + /// + /// + /// A logger or an appender may attach additional + /// properties to specific events. These properties + /// have a string key and an object value. + /// + /// + /// This property is for events that have been added directly to + /// this event. The aggregate properties (which include these + /// event properties) can be retrieved using + /// and . + /// + /// + /// Once the properties have been fixed this property + /// returns the combined cached properties. This ensures that updates to + /// this property are always reflected in the underlying storage. When + /// returning the combined properties there may be more keys in the + /// Dictionary than expected. + /// + /// + public PropertiesDictionary Properties + { + get + { + // If we have cached properties then return that otherwise changes will be lost + if (this.m_data.Properties != null) + { + return this.m_data.Properties; + } + + if (this.m_eventProperties == null) + { + this.m_eventProperties = new PropertiesDictionary(); + } + + return this.m_eventProperties; + } + } + + /// + /// Gets or sets the fixed fields in this event. + /// + /// + /// The set of fields that are fixed in this event. + /// + /// + /// + /// Fields will not be fixed if they have previously been fixed. + /// It is not possible to 'unfix' a field. + /// + /// + public FixFlags Fix + { + get { return this.m_fixFlags; } + set { this.FixVolatileData(value); } + } + +#if !NETCF + + /// + /// Serializes this object into the provided. + /// + /// The to populate with data. + /// The destination for this serialization. + /// + /// + /// The data in this event must be fixed before it can be serialized. + /// + /// + /// The method must be called during the + /// method call if this event + /// is to be used outside that method. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 + [System.Security.SecurityCritical] +#else + [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] +#endif + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + // The caller must call FixVolatileData before this object + // can be serialized. + info.AddValue("LoggerName", this.m_data.LoggerName); + info.AddValue("Level", this.m_data.Level); + info.AddValue("Message", this.m_data.Message); + info.AddValue("ThreadName", this.m_data.ThreadName); + + // TODO: consider serializing UTC rather than local time. Not implemented here because it + // would give an unexpected result if client and server have different versions of this class. // info.AddValue("TimeStamp", m_data.TimeStampUtc); #pragma warning disable 618 - info.AddValue("TimeStamp", m_data.TimeStamp); + info.AddValue("TimeStamp", this.m_data.TimeStamp); #pragma warning restore 618 - info.AddValue("LocationInfo", m_data.LocationInfo); - info.AddValue("UserName", m_data.UserName); - info.AddValue("ExceptionString", m_data.ExceptionString); - info.AddValue("Properties", m_data.Properties); - info.AddValue("Domain", m_data.Domain); - info.AddValue("Identity", m_data.Identity); - } - + info.AddValue("LocationInfo", this.m_data.LocationInfo); + info.AddValue("UserName", this.m_data.UserName); + info.AddValue("ExceptionString", this.m_data.ExceptionString); + info.AddValue("Properties", this.m_data.Properties); + info.AddValue("Domain", this.m_data.Domain); + info.AddValue("Identity", this.m_data.Identity); + } + #endif + + /// + /// Gets the portable data for this . + /// + /// The for this event. + /// + /// + /// A new can be constructed using a + /// instance. + /// + /// + /// Does a fix of the data + /// in the logging event before returning the event data. + /// + /// + public LoggingEventData GetLoggingEventData() + { + return this.GetLoggingEventData(FixFlags.Partial); + } + + /// + /// Gets the portable data for this . + /// + /// The set of data to ensure is fixed in the LoggingEventData. + /// The for this event. + /// + /// + /// A new can be constructed using a + /// instance. + /// + /// + public LoggingEventData GetLoggingEventData(FixFlags fixFlags) + { + this.Fix = fixFlags; + return this.m_data; + } + + /// + /// Returns this event's exception's rendered using the + /// . + /// + /// + /// This event's exception's rendered using the . + /// + /// + /// + /// Obsolete. Use instead. + /// + /// + [Obsolete("Use GetExceptionString instead. Scheduled removal in v10.0.0.")] + public string GetExceptionStrRep() + { + return this.GetExceptionString(); + } + + /// + /// Returns this event's exception's rendered using the + /// . + /// + /// + /// This event's exception's rendered using the . + /// + /// + /// + /// Returns this event's exception's rendered using the + /// . + /// + /// + public string GetExceptionString() + { + if (this.m_data.ExceptionString == null && this.m_cacheUpdatable) + { + if (this.m_thrownException != null) + { + if (this.m_repository != null) + { + // Render exception using the repositories renderer map + this.m_data.ExceptionString = this.m_repository.RendererMap.FindAndRender(this.m_thrownException); + } + else + { + // Very last resort + this.m_data.ExceptionString = this.m_thrownException.ToString(); + } + } + else + { + this.m_data.ExceptionString = string.Empty; + } + } + + return this.m_data.ExceptionString; + } + + /// + /// Fix instance fields that hold volatile data. + /// + /// + /// + /// Some of the values in instances of + /// are considered volatile, that is the values are correct at the + /// time the event is delivered to appenders, but will not be consistent + /// at any time afterwards. If an event is to be stored and then processed + /// at a later time these volatile values must be fixed by calling + /// . There is a performance penalty + /// incurred by calling but it + /// is essential to maintaining data consistency. + /// + /// + /// Calling is equivalent to + /// calling passing the parameter + /// false. + /// + /// + /// See for more + /// information. + /// + /// + [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] + public void FixVolatileData() + { + this.Fix = FixFlags.All; + } + + /// + /// Fixes instance fields that hold volatile data. + /// + /// Set to true to not fix data that takes a long time to fix. + /// + /// + /// Some of the values in instances of + /// are considered volatile, that is the values are correct at the + /// time the event is delivered to appenders, but will not be consistent + /// at any time afterwards. If an event is to be stored and then processed + /// at a later time these volatile values must be fixed by calling + /// . There is a performance penalty + /// for incurred by calling but it + /// is essential to maintaining data consistency. + /// + /// + /// The param controls the data that + /// is fixed. Some of the data that can be fixed takes a long time to + /// generate, therefore if you do not require those settings to be fixed + /// they can be ignored by setting the param + /// to true. This setting will ignore the + /// and settings. + /// + /// + /// Set to false to ensure that all + /// settings are fixed. + /// + /// + [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] + public void FixVolatileData(bool fastButLoose) + { + if (fastButLoose) + { + this.Fix = FixFlags.Partial; + } + else + { + this.Fix = FixFlags.All; + } + } + + /// + /// Fix the fields specified by the parameter. + /// + /// the fields to fix. + /// + /// + /// Only fields specified in the will be fixed. + /// Fields will not be fixed if they have previously been fixed. + /// It is not possible to 'unfix' a field. + /// + /// + protected void FixVolatileData(FixFlags flags) + { + object forceCreation = null; + + // Unlock the cache so that new values can be stored + // This may not be ideal if we are no longer in the correct context + // and someone calls fix. + this.m_cacheUpdatable = true; + + // determine the flags that we are actually fixing + FixFlags updateFlags = (FixFlags)((flags ^ this.m_fixFlags) & flags); + + if (updateFlags > 0) + { + if ((updateFlags & FixFlags.Message) != 0) + { + // Force the message to be rendered + forceCreation = this.RenderedMessage; + + this.m_fixFlags |= FixFlags.Message; + } + + if ((updateFlags & FixFlags.ThreadName) != 0) + { + // Grab the thread name + forceCreation = this.ThreadName; + + this.m_fixFlags |= FixFlags.ThreadName; + } + + if ((updateFlags & FixFlags.LocationInfo) != 0) + { + // Force the location information to be loaded + forceCreation = this.LocationInformation; + + this.m_fixFlags |= FixFlags.LocationInfo; + } + + if ((updateFlags & FixFlags.UserName) != 0) + { + // Grab the user name + forceCreation = this.UserName; + + this.m_fixFlags |= FixFlags.UserName; + } + + if ((updateFlags & FixFlags.Domain) != 0) + { + // Grab the domain name + forceCreation = this.Domain; + + this.m_fixFlags |= FixFlags.Domain; + } + + if ((updateFlags & FixFlags.Identity) != 0) + { + // Grab the identity + forceCreation = this.Identity; + + this.m_fixFlags |= FixFlags.Identity; + } + + if ((updateFlags & FixFlags.Exception) != 0) + { + // Force the exception text to be loaded + forceCreation = this.GetExceptionString(); + + this.m_fixFlags |= FixFlags.Exception; + } + + if ((updateFlags & FixFlags.Properties) != 0) + { + this.CacheProperties(); + + this.m_fixFlags |= FixFlags.Properties; + } + } + + // avoid warning CS0219 + if (forceCreation != null) + { + } + + // Finaly lock everything we've cached. + this.m_cacheUpdatable = false; + } + + private void CreateCompositeProperties() + { + CompositeProperties compositeProperties = new CompositeProperties(); - #endregion Implementation of ISerializable - - #region Public Instance Methods - - /// - /// Gets the portable data for this . - /// - /// The for this event. - /// - /// - /// A new can be constructed using a - /// instance. - /// - /// - /// Does a fix of the data - /// in the logging event before returning the event data. - /// - /// - public LoggingEventData GetLoggingEventData() - { - return GetLoggingEventData(FixFlags.Partial); - } - - /// - /// Gets the portable data for this . - /// - /// The set of data to ensure is fixed in the LoggingEventData - /// The for this event. - /// - /// - /// A new can be constructed using a - /// instance. - /// - /// - public LoggingEventData GetLoggingEventData(FixFlags fixFlags) - { - Fix = fixFlags; - return m_data; - } - - /// - /// Returns this event's exception's rendered using the - /// . - /// - /// - /// This event's exception's rendered using the . - /// - /// - /// - /// Obsolete. Use instead. - /// - /// - [Obsolete("Use GetExceptionString instead. Scheduled removal in v10.0.0.")] - public string GetExceptionStrRep() - { - return GetExceptionString(); - } - - /// - /// Returns this event's exception's rendered using the - /// . - /// - /// - /// This event's exception's rendered using the . - /// - /// - /// - /// Returns this event's exception's rendered using the - /// . - /// - /// - public string GetExceptionString() - { - if (m_data.ExceptionString == null && this.m_cacheUpdatable) - { - if (m_thrownException != null) - { - if (m_repository != null) - { - // Render exception using the repositories renderer map - m_data.ExceptionString = m_repository.RendererMap.FindAndRender(m_thrownException); - } - else - { - // Very last resort - m_data.ExceptionString = m_thrownException.ToString(); - } - } - else - { - m_data.ExceptionString = ""; - } - } - return m_data.ExceptionString; - } - - /// - /// Fix instance fields that hold volatile data. - /// - /// - /// - /// Some of the values in instances of - /// are considered volatile, that is the values are correct at the - /// time the event is delivered to appenders, but will not be consistent - /// at any time afterwards. If an event is to be stored and then processed - /// at a later time these volatile values must be fixed by calling - /// . There is a performance penalty - /// incurred by calling but it - /// is essential to maintaining data consistency. - /// - /// - /// Calling is equivalent to - /// calling passing the parameter - /// false. - /// - /// - /// See for more - /// information. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - public void FixVolatileData() - { - Fix = FixFlags.All; - } - - /// - /// Fixes instance fields that hold volatile data. - /// - /// Set to true to not fix data that takes a long time to fix. - /// - /// - /// Some of the values in instances of - /// are considered volatile, that is the values are correct at the - /// time the event is delivered to appenders, but will not be consistent - /// at any time afterwards. If an event is to be stored and then processed - /// at a later time these volatile values must be fixed by calling - /// . There is a performance penalty - /// for incurred by calling but it - /// is essential to maintaining data consistency. - /// - /// - /// The param controls the data that - /// is fixed. Some of the data that can be fixed takes a long time to - /// generate, therefore if you do not require those settings to be fixed - /// they can be ignored by setting the param - /// to true. This setting will ignore the - /// and settings. - /// - /// - /// Set to false to ensure that all - /// settings are fixed. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - public void FixVolatileData(bool fastButLoose) - { - if (fastButLoose) - { - Fix = FixFlags.Partial; - } - else - { - Fix = FixFlags.All; - } - } - - /// - /// Fix the fields specified by the parameter - /// - /// the fields to fix - /// - /// - /// Only fields specified in the will be fixed. - /// Fields will not be fixed if they have previously been fixed. - /// It is not possible to 'unfix' a field. - /// - /// - protected void FixVolatileData(FixFlags flags) - { - object forceCreation = null; - - //Unlock the cache so that new values can be stored - //This may not be ideal if we are no longer in the correct context - //and someone calls fix. - m_cacheUpdatable=true; - - // determine the flags that we are actually fixing - FixFlags updateFlags = (FixFlags)((flags ^ m_fixFlags) & flags); - - if (updateFlags > 0) - { - if ((updateFlags & FixFlags.Message) != 0) - { - // Force the message to be rendered - forceCreation = this.RenderedMessage; - - m_fixFlags |= FixFlags.Message; - } - if ((updateFlags & FixFlags.ThreadName) != 0) - { - // Grab the thread name - forceCreation = this.ThreadName; - - m_fixFlags |= FixFlags.ThreadName; - } - - if ((updateFlags & FixFlags.LocationInfo) != 0) - { - // Force the location information to be loaded - forceCreation = this.LocationInformation; - - m_fixFlags |= FixFlags.LocationInfo; - } - if ((updateFlags & FixFlags.UserName) != 0) - { - // Grab the user name - forceCreation = this.UserName; - - m_fixFlags |= FixFlags.UserName; - } - if ((updateFlags & FixFlags.Domain) != 0) - { - // Grab the domain name - forceCreation = this.Domain; - - m_fixFlags |= FixFlags.Domain; - } - if ((updateFlags & FixFlags.Identity) != 0) - { - // Grab the identity - forceCreation = this.Identity; - - m_fixFlags |= FixFlags.Identity; - } - - if ((updateFlags & FixFlags.Exception) != 0) - { - // Force the exception text to be loaded - forceCreation = GetExceptionString(); - - m_fixFlags |= FixFlags.Exception; - } - - if ((updateFlags & FixFlags.Properties) != 0) - { - CacheProperties(); - - m_fixFlags |= FixFlags.Properties; - } - } - - // avoid warning CS0219 - if (forceCreation != null) - { - } - - //Finaly lock everything we've cached. - m_cacheUpdatable=false; - } - - #endregion Public Instance Methods - - #region Protected Instance Methods - - private void CreateCompositeProperties() - { - CompositeProperties compositeProperties = new CompositeProperties(); - - if (m_eventProperties != null) - { - compositeProperties.Add(m_eventProperties); - } + if (this.m_eventProperties != null) + { + compositeProperties.Add(this.m_eventProperties); + } #if !(NETCF || NETSTANDARD1_3) - PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); - if (logicalThreadProperties != null) - { - compositeProperties.Add(logicalThreadProperties); - } + PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); + if (logicalThreadProperties != null) + { + compositeProperties.Add(logicalThreadProperties); + } #endif - PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); - if (threadProperties != null) - { - compositeProperties.Add(threadProperties); - } - - // TODO: Add Repository Properties - - // event properties - PropertiesDictionary eventProperties = new PropertiesDictionary(); - eventProperties[UserNameProperty] = UserName; - eventProperties[IdentityProperty] = Identity; - compositeProperties.Add(eventProperties); - - compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); - m_compositeProperties = compositeProperties; - } - - private void CacheProperties() - { - if (m_data.Properties == null && this.m_cacheUpdatable) - { - if (m_compositeProperties == null) - { - CreateCompositeProperties(); - } - - PropertiesDictionary flattenedProperties = m_compositeProperties.Flatten(); - - PropertiesDictionary fixedProperties = new PropertiesDictionary(); - - // Validate properties - foreach(DictionaryEntry entry in flattenedProperties) - { - string key = entry.Key as string; - - if (key != null) - { - object val = entry.Value; - - // Fix any IFixingRequired objects - IFixingRequired fixingRequired = val as IFixingRequired; - if (fixingRequired != null) - { - val = fixingRequired.GetFixedObject(); - } - - // Strip keys with null values - if (val != null) - { - fixedProperties[key] = val; - } - } - } - - m_data.Properties = fixedProperties; - } - } - - /// - /// Lookup a composite property in this event - /// - /// the key for the property to lookup - /// the value for the property - /// - /// - /// This event has composite properties that combine together properties from - /// several different contexts in the following order: - /// - /// - /// this events properties - /// - /// This event has that can be set. These - /// properties are specific to this event only. - /// - /// - /// - /// the thread properties - /// - /// The that are set on the current - /// thread. These properties are shared by all events logged on this thread. - /// - /// - /// - /// the global properties - /// - /// The that are set globally. These - /// properties are shared by all the threads in the AppDomain. - /// - /// - /// - /// - /// - public object LookupProperty(string key) - { - if (m_data.Properties != null) - { - return m_data.Properties[key]; - } - if (m_compositeProperties == null) - { - CreateCompositeProperties(); - } - return m_compositeProperties[key]; - } - - /// - /// Get all the composite properties in this event - /// - /// the containing all the properties - /// - /// - /// See for details of the composite properties - /// stored by the event. - /// - /// - /// This method returns a single containing all the - /// properties defined for this event. - /// - /// - public PropertiesDictionary GetProperties() - { - if (m_data.Properties != null) - { - return m_data.Properties; - } - if (m_compositeProperties == null) - { - CreateCompositeProperties(); - } - return m_compositeProperties.Flatten(); - } - - #endregion Public Instance Methods - - #region Private Instance Fields - - /// - /// The internal logging event data. - /// - private LoggingEventData m_data; - - /// - /// The internal logging event data. - /// - private CompositeProperties m_compositeProperties; - - /// - /// The internal logging event data. - /// - private PropertiesDictionary m_eventProperties; - - /// - /// The fully qualified Type of the calling - /// logger class in the stack frame (i.e. the declaring type of the method). - /// - private readonly Type m_callerStackBoundaryDeclaringType; - - /// - /// The application supplied message of logging event. - /// - private readonly object m_message; - - /// - /// The exception that was thrown. - /// - /// - /// This is not serialized. The string representation - /// is serialized instead. - /// - private readonly Exception m_thrownException; - - /// - /// The repository that generated the logging event - /// - /// - /// This is not serialized. - /// - private ILoggerRepository m_repository = null; - - /// - /// The fix state for this event - /// - /// - /// These flags indicate which fields have been fixed. - /// Not serialized. - /// - private FixFlags m_fixFlags = FixFlags.None; - - /// - /// Indicated that the internal cache is updateable (ie not fixed) - /// - /// - /// This is a seperate flag to m_fixFlags as it allows incrementel fixing and simpler - /// changes in the caching strategy. - /// - private bool m_cacheUpdatable = true; - - #endregion Private Instance Fields - - #region Constants - - /// - /// The key into the Properties map for the host name value. - /// - public const string HostNameProperty = "log4net:HostName"; - - /// - /// The key into the Properties map for the thread identity value. - /// - public const string IdentityProperty = "log4net:Identity"; - - /// - /// The key into the Properties map for the user name value. - /// - public const string UserNameProperty = "log4net:UserName"; - - #endregion - } + PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); + if (threadProperties != null) + { + compositeProperties.Add(threadProperties); + } + + // TODO: Add Repository Properties + + // event properties + PropertiesDictionary eventProperties = new PropertiesDictionary(); + eventProperties[UserNameProperty] = this.UserName; + eventProperties[IdentityProperty] = this.Identity; + compositeProperties.Add(eventProperties); + + compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); + this.m_compositeProperties = compositeProperties; + } + + private void CacheProperties() + { + if (this.m_data.Properties == null && this.m_cacheUpdatable) + { + if (this.m_compositeProperties == null) + { + this.CreateCompositeProperties(); + } + + PropertiesDictionary flattenedProperties = this.m_compositeProperties.Flatten(); + + PropertiesDictionary fixedProperties = new PropertiesDictionary(); + + // Validate properties + foreach (DictionaryEntry entry in flattenedProperties) + { + string key = entry.Key as string; + + if (key != null) + { + object val = entry.Value; + + // Fix any IFixingRequired objects + IFixingRequired fixingRequired = val as IFixingRequired; + if (fixingRequired != null) + { + val = fixingRequired.GetFixedObject(); + } + + // Strip keys with null values + if (val != null) + { + fixedProperties[key] = val; + } + } + } + + this.m_data.Properties = fixedProperties; + } + } + + /// + /// Lookup a composite property in this event. + /// + /// the key for the property to lookup. + /// the value for the property. + /// + /// + /// This event has composite properties that combine together properties from + /// several different contexts in the following order: + /// + /// + /// this events properties + /// + /// This event has that can be set. These + /// properties are specific to this event only. + /// + /// + /// + /// the thread properties + /// + /// The that are set on the current + /// thread. These properties are shared by all events logged on this thread. + /// + /// + /// + /// the global properties + /// + /// The that are set globally. These + /// properties are shared by all the threads in the AppDomain. + /// + /// + /// + /// + /// + public object LookupProperty(string key) + { + if (this.m_data.Properties != null) + { + return this.m_data.Properties[key]; + } + + if (this.m_compositeProperties == null) + { + this.CreateCompositeProperties(); + } + + return this.m_compositeProperties[key]; + } + + /// + /// Get all the composite properties in this event. + /// + /// the containing all the properties. + /// + /// + /// See for details of the composite properties + /// stored by the event. + /// + /// + /// This method returns a single containing all the + /// properties defined for this event. + /// + /// + public PropertiesDictionary GetProperties() + { + if (this.m_data.Properties != null) + { + return this.m_data.Properties; + } + + if (this.m_compositeProperties == null) + { + this.CreateCompositeProperties(); + } + + return this.m_compositeProperties.Flatten(); + } + + /// + /// The internal logging event data. + /// + private LoggingEventData m_data; + + /// + /// The internal logging event data. + /// + private CompositeProperties m_compositeProperties; + + /// + /// The internal logging event data. + /// + private PropertiesDictionary m_eventProperties; + + /// + /// The fully qualified Type of the calling + /// logger class in the stack frame (i.e. the declaring type of the method). + /// + private readonly Type m_callerStackBoundaryDeclaringType; + + /// + /// The application supplied message of logging event. + /// + private readonly object m_message; + + /// + /// The exception that was thrown. + /// + /// + /// This is not serialized. The string representation + /// is serialized instead. + /// + private readonly Exception m_thrownException; + + /// + /// The repository that generated the logging event. + /// + /// + /// This is not serialized. + /// + private ILoggerRepository m_repository = null; + + /// + /// The fix state for this event. + /// + /// + /// These flags indicate which fields have been fixed. + /// Not serialized. + /// + private FixFlags m_fixFlags = FixFlags.None; + + /// + /// Indicated that the internal cache is updateable (ie not fixed). + /// + /// + /// This is a seperate flag to m_fixFlags as it allows incrementel fixing and simpler + /// changes in the caching strategy. + /// + private bool m_cacheUpdatable = true; + + /// + /// The key into the Properties map for the host name value. + /// + public const string HostNameProperty = "log4net:HostName"; + + /// + /// The key into the Properties map for the thread identity value. + /// + public const string IdentityProperty = "log4net:Identity"; + + /// + /// The key into the Properties map for the user name value. + /// + public const string UserNameProperty = "log4net:UserName"; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs index 4beb75b0ca1..d258747cb83 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs @@ -1,175 +1,161 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion -using System; -using System.Text; -using System.Collections; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// provides method information without actually referencing a System.Reflection.MethodBase - /// as that would require that the containing assembly is loaded. - /// - /// + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Text; + + using log4net.Util; + + /// + /// provides method information without actually referencing a System.Reflection.MethodBase + /// as that would require that the containing assembly is loaded. + /// + /// #if !NETCF - [Serializable] + [Serializable] #endif - public class MethodItem - { - #region Public Instance Constructors - - /// - /// constructs a method item for an unknown method. - /// - public MethodItem() - { - m_name = NA; - m_parameters = new string[0]; - } - - /// - /// constructs a method item from the name of the method. - /// - /// - public MethodItem(string name) - : this() - { - m_name = name; - } - - /// - /// constructs a method item from the name of the method and its parameters. - /// - /// - /// - public MethodItem(string name, string[] parameters) - : this(name) - { - m_parameters = parameters; - } - - /// + public class MethodItem + { + /// + /// Initializes a new instance of the class. + /// constructs a method item for an unknown method. + /// + public MethodItem() + { + this.m_name = NA; + this.m_parameters = new string[0]; + } + + /// + /// Initializes a new instance of the class. + /// constructs a method item from the name of the method. + /// + /// + public MethodItem(string name) + : this() + { + this.m_name = name; + } + + /// + /// Initializes a new instance of the class. + /// constructs a method item from the name of the method and its parameters. + /// + /// + /// + public MethodItem(string name, string[] parameters) + : this(name) + { + this.m_parameters = parameters; + } + + /// + /// Initializes a new instance of the class. /// constructs a method item from a method base by determining the method name and its parameters. /// /// - public MethodItem(System.Reflection.MethodBase methodBase) - : this(methodBase.Name, GetMethodParameterNames(methodBase)) + public MethodItem(System.Reflection.MethodBase methodBase) + : this(methodBase.Name, GetMethodParameterNames(methodBase)) { - } - - #endregion - - private static string[] GetMethodParameterNames(System.Reflection.MethodBase methodBase) - { - ArrayList methodParameterNames = new ArrayList(); - try - { - System.Reflection.ParameterInfo[] methodBaseGetParameters = methodBase.GetParameters(); - - int methodBaseGetParametersCount = methodBaseGetParameters.GetUpperBound(0); - - for (int i = 0; i <= methodBaseGetParametersCount; i++) - { - methodParameterNames.Add(methodBaseGetParameters[i].ParameterType + " " + methodBaseGetParameters[i].Name); - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "An exception ocurred while retreiving method parameters.", ex); - } - - return (string[])methodParameterNames.ToArray(typeof(string)); - } - - #region Public Instance Properties - - /// - /// Gets the method name of the caller making the logging - /// request. - /// - /// - /// The method name of the caller making the logging - /// request. - /// - /// - /// - /// Gets the method name of the caller making the logging - /// request. - /// - /// - public string Name - { - get { return m_name; } - } - - /// - /// Gets the method parameters of the caller making - /// the logging request. - /// - /// - /// The method parameters of the caller making - /// the logging request - /// - /// - /// - /// Gets the method parameters of the caller making - /// the logging request. - /// - /// - public string[] Parameters - { - get { return m_parameters; } - } - - #endregion - - #region Private Instance Fields - - private readonly string m_name; - private readonly string[] m_parameters; - - #endregion - - #region Private Static Fields - - /// - /// The fully qualified type of the StackFrameItem class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(MethodItem); + } + + private static string[] GetMethodParameterNames(System.Reflection.MethodBase methodBase) + { + ArrayList methodParameterNames = new ArrayList(); + try + { + System.Reflection.ParameterInfo[] methodBaseGetParameters = methodBase.GetParameters(); + + int methodBaseGetParametersCount = methodBaseGetParameters.GetUpperBound(0); + + for (int i = 0; i <= methodBaseGetParametersCount; i++) + { + methodParameterNames.Add(methodBaseGetParameters[i].ParameterType + " " + methodBaseGetParameters[i].Name); + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "An exception ocurred while retreiving method parameters.", ex); + } + + return (string[])methodParameterNames.ToArray(typeof(string)); + } + + /// + /// Gets the method name of the caller making the logging + /// request. + /// + /// + /// The method name of the caller making the logging + /// request. + /// + /// + /// + /// Gets the method name of the caller making the logging + /// request. + /// + /// + public string Name + { + get { return this.m_name; } + } - /// - /// When location information is not available the constant - /// NA is returned. Current value of this string - /// constant is ?. - /// - private const string NA = "?"; + /// + /// Gets the method parameters of the caller making + /// the logging request. + /// + /// + /// The method parameters of the caller making + /// the logging request. + /// + /// + /// + /// Gets the method parameters of the caller making + /// the logging request. + /// + /// + public string[] Parameters + { + get { return this.m_parameters; } + } + + private readonly string m_name; + private readonly string[] m_parameters; + + /// + /// The fully qualified type of the StackFrameItem class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(MethodItem); - #endregion Private Static Fields - } + /// + /// When location information is not available the constant + /// NA is returned. Current value of this string + /// constant is ?. + /// + private const string NA = "?"; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs index b078fb110de..b4a42c6c818 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs @@ -1,59 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// A SecurityContext used by log4net when interacting with protected resources - /// - /// - /// - /// A SecurityContext used by log4net when interacting with protected resources - /// for example with operating system services. This can be used to impersonate - /// a principal that has been granted privileges on the system resources. - /// - /// - /// Nicko Cadell - public abstract class SecurityContext - { - /// - /// Impersonate this SecurityContext - /// - /// State supplied by the caller - /// An instance that will - /// revoke the impersonation of this SecurityContext, or null - /// - /// - /// Impersonate this security context. Further calls on the current - /// thread should now be made in the security context provided - /// by this object. When the result - /// method is called the security - /// context of the thread should be reverted to the state it was in - /// before was called. - /// - /// - public abstract IDisposable Impersonate(object state); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// A SecurityContext used by log4net when interacting with protected resources. + /// + /// + /// + /// A SecurityContext used by log4net when interacting with protected resources + /// for example with operating system services. This can be used to impersonate + /// a principal that has been granted privileges on the system resources. + /// + /// + /// Nicko Cadell. + public abstract class SecurityContext + { + /// + /// Impersonate this SecurityContext. + /// + /// State supplied by the caller. + /// An instance that will + /// revoke the impersonation of this SecurityContext, or null. + /// + /// + /// Impersonate this security context. Further calls on the current + /// thread should now be made in the security context provided + /// by this object. When the result + /// method is called the security + /// context of the thread should be reverted to the state it was in + /// before was called. + /// + /// + public abstract IDisposable Impersonate(object state); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs index 2f407f78221..5c8a082908b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs @@ -1,128 +1,126 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { - /// - /// The providers default instances. - /// - /// - /// - /// A configured component that interacts with potentially protected system - /// resources uses a to provide the elevated - /// privileges required. If the object has - /// been not been explicitly provided to the component then the component - /// will request one from this . - /// - /// - /// By default the is - /// an instance of which returns only - /// objects. This is a reasonable default - /// where the privileges required are not know by the system. - /// - /// - /// This default behavior can be overridden by subclassing the - /// and overriding the method to return - /// the desired objects. The default provider - /// can be replaced by programmatically setting the value of the - /// property. - /// - /// - /// An alternative is to use the log4net.Config.SecurityContextProviderAttribute - /// This attribute can be applied to an assembly in the same way as the - /// log4net.Config.XmlConfiguratorAttribute". The attribute takes - /// the type to use as the as an argument. - /// - /// - /// Nicko Cadell - public class SecurityContextProvider - { - /// - /// The default provider - /// - private static SecurityContextProvider s_defaultProvider = new SecurityContextProvider(); - - /// - /// Gets or sets the default SecurityContextProvider - /// - /// - /// The default SecurityContextProvider - /// - /// - /// - /// The default provider is used by configured components that - /// require a and have not had one - /// given to them. - /// - /// - /// By default this is an instance of - /// that returns objects. - /// - /// - /// The default provider can be set programmatically by setting - /// the value of this property to a sub class of - /// that has the desired behavior. - /// - /// - public static SecurityContextProvider DefaultProvider - { - get { return s_defaultProvider; } - set { s_defaultProvider = value; } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Util; + + /// + /// The providers default instances. + /// + /// + /// + /// A configured component that interacts with potentially protected system + /// resources uses a to provide the elevated + /// privileges required. If the object has + /// been not been explicitly provided to the component then the component + /// will request one from this . + /// + /// + /// By default the is + /// an instance of which returns only + /// objects. This is a reasonable default + /// where the privileges required are not know by the system. + /// + /// + /// This default behavior can be overridden by subclassing the + /// and overriding the method to return + /// the desired objects. The default provider + /// can be replaced by programmatically setting the value of the + /// property. + /// + /// + /// An alternative is to use the log4net.Config.SecurityContextProviderAttribute + /// This attribute can be applied to an assembly in the same way as the + /// log4net.Config.XmlConfiguratorAttribute". The attribute takes + /// the type to use as the as an argument. + /// + /// + /// Nicko Cadell. + public class SecurityContextProvider + { + /// + /// The default provider. + /// + private static SecurityContextProvider s_defaultProvider = new SecurityContextProvider(); - /// - /// Protected default constructor to allow subclassing - /// - /// - /// - /// Protected default constructor to allow subclassing - /// - /// - protected SecurityContextProvider() - { - } + /// + /// Gets or sets the default SecurityContextProvider. + /// + /// + /// The default SecurityContextProvider. + /// + /// + /// + /// The default provider is used by configured components that + /// require a and have not had one + /// given to them. + /// + /// + /// By default this is an instance of + /// that returns objects. + /// + /// + /// The default provider can be set programmatically by setting + /// the value of this property to a sub class of + /// that has the desired behavior. + /// + /// + public static SecurityContextProvider DefaultProvider + { + get { return s_defaultProvider; } + set { s_defaultProvider = value; } + } + + /// + /// Initializes a new instance of the class. + /// Protected default constructor to allow subclassing. + /// + /// + /// + /// Protected default constructor to allow subclassing. + /// + /// + protected SecurityContextProvider() + { + } - /// - /// Create a SecurityContext for a consumer - /// - /// The consumer requesting the SecurityContext - /// An impersonation context - /// - /// - /// The default implementation is to return a . - /// - /// - /// Subclasses should override this method to provide their own - /// behavior. - /// - /// - public virtual SecurityContext CreateSecurityContext(object consumer) - { - return NullSecurityContext.Instance; - } - } + /// + /// Create a SecurityContext for a consumer. + /// + /// The consumer requesting the SecurityContext. + /// An impersonation context. + /// + /// + /// The default implementation is to return a . + /// + /// + /// Subclasses should override this method to provide their own + /// behavior. + /// + /// + public virtual SecurityContext CreateSecurityContext(object consumer) + { + return NullSecurityContext.Instance; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs index 796607be160..92930ff63b6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs @@ -1,30 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information #if !NETCF -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// using System; -using System.Text; using System.Diagnostics; using System.Reflection; +using System.Text; + using log4net.Util; namespace log4net.Core @@ -33,69 +31,68 @@ namespace log4net.Core /// provides stack frame information without actually referencing a System.Diagnostics.StackFrame /// as that would require that the containing assembly is loaded. /// - /// + /// [Serializable] public class StackFrameItem - { - #region Public Instance Constructors - - /// - /// returns a stack frame item from a stack frame. This + { + /// + /// Initializes a new instance of the class. + /// returns a stack frame item from a stack frame. This. /// /// /// public StackFrameItem(StackFrame frame) { // set default values - m_lineNumber = NA; - m_fileName = NA; - m_method = new MethodItem(); - m_className = NA; - - try - { - // get frame values - m_lineNumber = frame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); - m_fileName = frame.GetFileName(); - // get method values - MethodBase method = frame.GetMethod(); - if (method != null) - { - if(method.DeclaringType != null) - m_className = method.DeclaringType.FullName; - m_method = new MethodItem(method); - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "An exception ocurred while retreiving stack frame information.", ex); - } + this.m_lineNumber = NA; + this.m_fileName = NA; + this.m_method = new MethodItem(); + this.m_className = NA; + + try + { + // get frame values + this.m_lineNumber = frame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); + this.m_fileName = frame.GetFileName(); + + // get method values + MethodBase method = frame.GetMethod(); + if (method != null) + { + if (method.DeclaringType != null) + { + this.m_className = method.DeclaringType.FullName; + } + + this.m_method = new MethodItem(method); + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "An exception ocurred while retreiving stack frame information.", ex); + } // set full info - m_fullInfo = m_className + '.' + m_method.Name + '(' + m_fileName + ':' + m_lineNumber + ')'; - } - - #endregion - - #region Public Instance Properties - + this.m_fullInfo = this.m_className + '.' + this.m_method.Name + '(' + this.m_fileName + ':' + this.m_lineNumber + ')'; + } + /// - /// Gets the fully qualified class name of the caller making the logging + /// Gets the fully qualified class name of the caller making the logging /// request. /// /// - /// The fully qualified class name of the caller making the logging + /// The fully qualified class name of the caller making the logging /// request. /// /// /// - /// Gets the fully qualified class name of the caller making the logging + /// Gets the fully qualified class name of the caller making the logging /// request. /// /// public string ClassName { - get { return m_className; } + get { return this.m_className; } } /// @@ -111,7 +108,7 @@ public string ClassName /// public string FileName { - get { return m_fileName; } + get { return this.m_fileName; } } /// @@ -127,7 +124,7 @@ public string FileName /// public string LineNumber { - get { return m_lineNumber; } + get { return this.m_lineNumber; } } /// @@ -143,41 +140,33 @@ public string LineNumber /// public MethodItem Method { - get { return m_method; } + get { return this.m_method; } } /// - /// Gets all available caller information + /// Gets all available caller information. /// /// /// All available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line) + /// fully.qualified.classname.of.caller.methodName(Filename:line). /// /// /// /// Gets all available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line) + /// fully.qualified.classname.of.caller.methodName(Filename:line). /// /// public string FullInfo { - get { return m_fullInfo; } - } - - #endregion Public Instance Properties - - #region Private Instance Fields - + get { return this.m_fullInfo; } + } + private readonly string m_lineNumber; private readonly string m_fileName; private readonly string m_className; private readonly string m_fullInfo; - private readonly MethodItem m_method; - - #endregion - - #region Private Static Fields - + private readonly MethodItem m_method; + /// /// The fully qualified type of the StackFrameItem class. /// @@ -185,16 +174,14 @@ public string FullInfo /// Used by the internal logger to record the Type of the /// log message. /// - private readonly static Type declaringType = typeof(StackFrameItem); + private static readonly Type declaringType = typeof(StackFrameItem); /// /// When location information is not available the constant /// NA is returned. Current value of this string /// constant is ?. /// - private const string NA = "?"; - - #endregion Private Static Fields + private const string NA = "?"; } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs index 17aff0f28f0..4718deb8092 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs @@ -1,40 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Copyright & License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + /// /// An evaluator that triggers after specified number of seconds. /// /// /// - /// This evaluator will trigger if the specified time period + /// This evaluator will trigger if the specified time period /// has passed since last check. /// /// - /// Robert Sevcik + /// Robert Sevcik. public class TimeEvaluator : ITriggeringEventEvaluator { /// @@ -50,9 +47,10 @@ public class TimeEvaluator : ITriggeringEventEvaluator /// /// The default time threshold for triggering in seconds. Zero means it won't trigger at all. /// - const int DEFAULT_INTERVAL = 0; - - /// + private const int DEFAULT_INTERVAL = 0; + + /// + /// Initializes a new instance of the class. /// Create a new evaluator using the time threshold in seconds. /// /// @@ -60,16 +58,17 @@ public class TimeEvaluator : ITriggeringEventEvaluator /// Create a new evaluator using the time threshold in seconds. /// /// - /// This evaluator will trigger if the specified time period + /// This evaluator will trigger if the specified time period /// has passed since last check. /// /// public TimeEvaluator() : this(DEFAULT_INTERVAL) { - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Create a new evaluator using the specified time threshold in seconds. /// /// @@ -81,18 +80,18 @@ public TimeEvaluator() /// Create a new evaluator using the specified time threshold in seconds. /// /// - /// This evaluator will trigger if the specified time period + /// This evaluator will trigger if the specified time period /// has passed since last check. /// /// public TimeEvaluator(int interval) { - m_interval = interval; - m_lastTimeUtc = DateTime.UtcNow; + this.m_interval = interval; + this.m_lastTimeUtc = DateTime.UtcNow; } /// - /// The time threshold in seconds to trigger after + /// Gets or sets the time threshold in seconds to trigger after. /// /// /// The time threshold in seconds to trigger after. @@ -100,26 +99,26 @@ public TimeEvaluator(int interval) /// /// /// - /// This evaluator will trigger if the specified time period + /// This evaluator will trigger if the specified time period /// has passed since last check. /// /// public int Interval { - get { return m_interval; } - set { m_interval = value; } + get { return this.m_interval; } + set { this.m_interval = value; } } /// - /// Is this the triggering event? + /// Is this the triggering event?. /// - /// The event to check - /// This method returns true, if the specified time period - /// has passed since last check.. - /// Otherwise it returns false + /// The event to check. + /// This method returns true, if the specified time period + /// has passed since last check.. + /// Otherwise it returns false. /// /// - /// This evaluator will trigger if the specified time period + /// This evaluator will trigger if the specified time period /// has passed since last check. /// /// @@ -131,15 +130,18 @@ public bool IsTriggeringEvent(LoggingEvent loggingEvent) } // disable the evaluator if threshold is zero - if (m_interval == 0) return false; - + if (this.m_interval == 0) + { + return false; + } + lock (this) // avoid triggering multiple times { - TimeSpan passed = DateTime.UtcNow.Subtract(m_lastTimeUtc); + TimeSpan passed = DateTime.UtcNow.Subtract(this.m_lastTimeUtc); - if (passed.TotalSeconds > m_interval) + if (passed.TotalSeconds > this.m_interval) { - m_lastTimeUtc = DateTime.UtcNow; + this.m_lastTimeUtc = DateTime.UtcNow; return true; } else diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs index 2525b1e0e50..96622e49df9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs @@ -1,263 +1,238 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Core -{ - #region WrapperCreationHandler - - /// - /// Delegate used to handle creation of new wrappers. - /// - /// The logger to wrap in a wrapper. - /// - /// - /// Delegate used to handle creation of new wrappers. This delegate - /// is called from the - /// method to construct the wrapper for the specified logger. - /// - /// - /// The delegate to use is supplied to the - /// constructor. - /// - /// - public delegate ILoggerWrapper WrapperCreationHandler(ILogger logger); - - #endregion WrapperCreationHandler - - /// - /// Maps between logger objects and wrapper objects. - /// - /// - /// - /// This class maintains a mapping between objects and - /// objects. Use the method to - /// lookup the for the specified . - /// - /// - /// New wrapper instances are created by the - /// method. The default behavior is for this method to delegate construction - /// of the wrapper to the delegate supplied - /// to the constructor. This allows specialization of the behavior without - /// requiring subclassing of this type. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class WrapperMap - { - #region Public Instance Constructors - - /// - /// Initializes a new instance of the - /// - /// The handler to use to create the wrapper objects. - /// - /// - /// Initializes a new instance of the class with - /// the specified handler to create the wrapper objects. - /// - /// - public WrapperMap(WrapperCreationHandler createWrapperHandler) - { - m_createWrapperHandler = createWrapperHandler; - - // Create the delegates for the event callbacks - m_shutdownHandler = new LoggerRepositoryShutdownEventHandler(ILoggerRepository_Shutdown); - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the wrapper object for the specified logger. - /// - /// The wrapper object for the specified logger - /// - /// - /// If the logger is null then the corresponding wrapper is null. - /// - /// - /// Looks up the wrapper it it has previously been requested and - /// returns it. If the wrapper has never been requested before then - /// the virtual method is - /// called. - /// - /// - virtual public ILoggerWrapper GetWrapper(ILogger logger) - { - // If the logger is null then the corresponding wrapper is null - if (logger == null) - { - return null; - } - - lock(this) - { - // Lookup hierarchy in map. - Hashtable wrappersMap = (Hashtable)m_repositories[logger.Repository]; - - if (wrappersMap == null) - { - // Hierarchy does not exist in map. - // Must register with hierarchy - - wrappersMap = new Hashtable(); - m_repositories[logger.Repository] = wrappersMap; - - // Register for config reset & shutdown on repository - logger.Repository.ShutdownEvent += m_shutdownHandler; - } - - // Look for the wrapper object in the map - ILoggerWrapper wrapperObject = wrappersMap[logger] as ILoggerWrapper; - - if (wrapperObject == null) - { - // No wrapper object exists for the specified logger - - // Create a new wrapper wrapping the logger - wrapperObject = CreateNewWrapperObject(logger); - - // Store wrapper logger in map - wrappersMap[logger] = wrapperObject; - } - - return wrapperObject; - } - } - - #endregion Public Instance Properties - - #region Protected Instance Properties - - /// - /// Gets the map of logger repositories. - /// - /// - /// Map of logger repositories. - /// - /// - /// - /// Gets the hashtable that is keyed on . The - /// values are hashtables keyed on with the - /// value being the corresponding . - /// - /// - protected Hashtable Repositories - { - get { return this.m_repositories; } - } - - #endregion Protected Instance Properties - - #region Protected Instance Methods - - /// - /// Creates the wrapper object for the specified logger. - /// - /// The logger to wrap in a wrapper. - /// The wrapper object for the logger. - /// - /// - /// This implementation uses the - /// passed to the constructor to create the wrapper. This method - /// can be overridden in a subclass. - /// - /// - virtual protected ILoggerWrapper CreateNewWrapperObject(ILogger logger) - { - if (m_createWrapperHandler != null) - { - return m_createWrapperHandler(logger); - } - return null; - } - - /// - /// Called when a monitored repository shutdown event is received. - /// - /// The that is shutting down - /// - /// - /// This method is called when a that this - /// is holding loggers for has signaled its shutdown - /// event . The default - /// behavior of this method is to release the references to the loggers - /// and their wrappers generated for this repository. - /// - /// - virtual protected void RepositoryShutdown(ILoggerRepository repository) - { - lock(this) - { - // Remove the repository from map - m_repositories.Remove(repository); - - // Unhook events from the repository - repository.ShutdownEvent -= m_shutdownHandler; - } - } - - /// - /// Event handler for repository shutdown event. - /// - /// The sender of the event. - /// The event args. - private void ILoggerRepository_Shutdown(object sender, EventArgs e) - { - ILoggerRepository repository = sender as ILoggerRepository; - if (repository != null) - { - // Remove all repository from map - RepositoryShutdown(repository); - } - } - - #endregion Protected Instance Methods - - #region Private Instance Variables - - /// - /// Map of logger repositories to hashtables of ILogger to ILoggerWrapper mappings - /// - private readonly Hashtable m_repositories = new Hashtable(); - - /// - /// The handler to use to create the extension wrapper objects. - /// - private readonly WrapperCreationHandler m_createWrapperHandler; - - /// - /// Internal reference to the delegate used to register for repository shutdown events. - /// - private readonly LoggerRepositoryShutdownEventHandler m_shutdownHandler; - - #endregion Private Instance Variables - } +{ + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Repository; + + /// + /// Delegate used to handle creation of new wrappers. + /// + /// The logger to wrap in a wrapper. + /// + /// + /// Delegate used to handle creation of new wrappers. This delegate + /// is called from the + /// method to construct the wrapper for the specified logger. + /// + /// + /// The delegate to use is supplied to the + /// constructor. + /// + /// + /// + public delegate ILoggerWrapper WrapperCreationHandler(ILogger logger); + + /// + /// Maps between logger objects and wrapper objects. + /// + /// + /// + /// This class maintains a mapping between objects and + /// objects. Use the method to + /// lookup the for the specified . + /// + /// + /// New wrapper instances are created by the + /// method. The default behavior is for this method to delegate construction + /// of the wrapper to the delegate supplied + /// to the constructor. This allows specialization of the behavior without + /// requiring subclassing of this type. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class WrapperMap + { + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the . + /// + /// The handler to use to create the wrapper objects. + /// + /// + /// Initializes a new instance of the class with + /// the specified handler to create the wrapper objects. + /// + /// + public WrapperMap(WrapperCreationHandler createWrapperHandler) + { + this.m_createWrapperHandler = createWrapperHandler; + + // Create the delegates for the event callbacks + this.m_shutdownHandler = new LoggerRepositoryShutdownEventHandler(this.ILoggerRepository_Shutdown); + } + + /// + /// Gets the wrapper object for the specified logger. + /// + /// The wrapper object for the specified logger. + /// + /// + /// If the logger is null then the corresponding wrapper is null. + /// + /// + /// Looks up the wrapper it it has previously been requested and + /// returns it. If the wrapper has never been requested before then + /// the virtual method is + /// called. + /// + /// + public virtual ILoggerWrapper GetWrapper(ILogger logger) + { + // If the logger is null then the corresponding wrapper is null + if (logger == null) + { + return null; + } + + lock (this) + { + // Lookup hierarchy in map. + Hashtable wrappersMap = (Hashtable)this.m_repositories[logger.Repository]; + + if (wrappersMap == null) + { + // Hierarchy does not exist in map. + // Must register with hierarchy + wrappersMap = new Hashtable(); + this.m_repositories[logger.Repository] = wrappersMap; + + // Register for config reset & shutdown on repository + logger.Repository.ShutdownEvent += this.m_shutdownHandler; + } + + // Look for the wrapper object in the map + ILoggerWrapper wrapperObject = wrappersMap[logger] as ILoggerWrapper; + + if (wrapperObject == null) + { + // No wrapper object exists for the specified logger + + // Create a new wrapper wrapping the logger + wrapperObject = this.CreateNewWrapperObject(logger); + + // Store wrapper logger in map + wrappersMap[logger] = wrapperObject; + } + + return wrapperObject; + } + } + + /// + /// Gets the map of logger repositories. + /// + /// + /// Map of logger repositories. + /// + /// + /// + /// Gets the hashtable that is keyed on . The + /// values are hashtables keyed on with the + /// value being the corresponding . + /// + /// + protected Hashtable Repositories + { + get { return this.m_repositories; } + } + + /// + /// Creates the wrapper object for the specified logger. + /// + /// The logger to wrap in a wrapper. + /// The wrapper object for the logger. + /// + /// + /// This implementation uses the + /// passed to the constructor to create the wrapper. This method + /// can be overridden in a subclass. + /// + /// + protected virtual ILoggerWrapper CreateNewWrapperObject(ILogger logger) + { + if (this.m_createWrapperHandler != null) + { + return this.m_createWrapperHandler(logger); + } + + return null; + } + + /// + /// Called when a monitored repository shutdown event is received. + /// + /// The that is shutting down. + /// + /// + /// This method is called when a that this + /// is holding loggers for has signaled its shutdown + /// event . The default + /// behavior of this method is to release the references to the loggers + /// and their wrappers generated for this repository. + /// + /// + protected virtual void RepositoryShutdown(ILoggerRepository repository) + { + lock (this) + { + // Remove the repository from map + this.m_repositories.Remove(repository); + + // Unhook events from the repository + repository.ShutdownEvent -= this.m_shutdownHandler; + } + } + + /// + /// Event handler for repository shutdown event. + /// + /// The sender of the event. + /// The event args. + private void ILoggerRepository_Shutdown(object sender, EventArgs e) + { + ILoggerRepository repository = sender as ILoggerRepository; + if (repository != null) + { + // Remove all repository from map + this.RepositoryShutdown(repository); + } + } + + /// + /// Map of logger repositories to hashtables of ILogger to ILoggerWrapper mappings. + /// + private readonly Hashtable m_repositories = new Hashtable(); + + /// + /// The handler to use to create the extension wrapper objects. + /// + private readonly WrapperCreationHandler m_createWrapperHandler; + + /// + /// Internal reference to the delegate used to register for repository shutdown events. + /// + private readonly LoggerRepositoryShutdownEventHandler m_shutdownHandler; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs index 0a62ce5c3d4..f65ea592b69 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs @@ -1,217 +1,206 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.IO; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.DateFormatter { - /// - /// Formats a as "HH:mm:ss,fff". - /// - /// - /// - /// Formats a in the format "HH:mm:ss,fff" for example, "15:49:37,459". - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class AbsoluteTimeDateFormatter : IDateFormatter - { - #region Protected Instance Methods - - /// - /// Renders the date into a string. Format is "HH:mm:ss". - /// - /// The date to render into a string. - /// The string builder to write to. - /// - /// - /// Subclasses should override this method to render the date - /// into a string using a precision up to the second. This method - /// will be called at most once per second and the result will be - /// reused if it is needed again during the same second. - /// - /// - virtual protected void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) - { - int hour = dateToFormat.Hour; - if (hour < 10) - { - buffer.Append('0'); - } - buffer.Append(hour); - buffer.Append(':'); - - int mins = dateToFormat.Minute; - if (mins < 10) - { - buffer.Append('0'); - } - buffer.Append(mins); - buffer.Append(':'); - - int secs = dateToFormat.Second; - if (secs < 10) - { - buffer.Append('0'); - } - buffer.Append(secs); - } - - #endregion Protected Instance Methods - - #region Implementation of IDateFormatter - - /// - /// Renders the date into a string. Format is "HH:mm:ss,fff". - /// - /// The date to render into a string. - /// The writer to write to. - /// - /// - /// Uses the method to generate the - /// time string up to the seconds and then appends the current - /// milliseconds. The results from are - /// cached and is called at most once - /// per second. - /// - /// - /// Sub classes should override - /// rather than . - /// - /// - virtual public void FormatDate(DateTime dateToFormat, TextWriter writer) - { - lock (s_lastTimeStrings) - { - // Calculate the current time precise only to the second - long currentTimeToTheSecond = (dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond)); - - string timeString = null; - // Compare this time with the stored last time - // If we are in the same second then append - // the previously calculated time string - if (s_lastTimeToTheSecond != currentTimeToTheSecond) - { - s_lastTimeStrings.Clear(); - } - else - { - timeString = (string) s_lastTimeStrings[GetType()]; - } - - if (timeString == null) - { - // lock so that only one thread can use the buffer and - // update the s_lastTimeToTheSecond and s_lastTimeStrings - - // PERF: Try removing this lock and using a new StringBuilder each time - lock(s_lastTimeBuf) - { - timeString = (string) s_lastTimeStrings[GetType()]; - - if (timeString == null) - { - // We are in a new second. - s_lastTimeBuf.Length = 0; - - // Calculate the new string for this second - FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); - - // Render the string buffer to a string - timeString = s_lastTimeBuf.ToString(); - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + using System.Text; + + /// + /// Formats a as "HH:mm:ss,fff". + /// + /// + /// + /// Formats a in the format "HH:mm:ss,fff" for example, "15:49:37,459". + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class AbsoluteTimeDateFormatter : IDateFormatter + { + /// + /// Renders the date into a string. Format is "HH:mm:ss". + /// + /// The date to render into a string. + /// The string builder to write to. + /// + /// + /// Subclasses should override this method to render the date + /// into a string using a precision up to the second. This method + /// will be called at most once per second and the result will be + /// reused if it is needed again during the same second. + /// + /// + protected virtual void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) + { + int hour = dateToFormat.Hour; + if (hour < 10) + { + buffer.Append('0'); + } + + buffer.Append(hour); + buffer.Append(':'); + + int mins = dateToFormat.Minute; + if (mins < 10) + { + buffer.Append('0'); + } + + buffer.Append(mins); + buffer.Append(':'); + + int secs = dateToFormat.Second; + if (secs < 10) + { + buffer.Append('0'); + } + + buffer.Append(secs); + } + + /// + /// Renders the date into a string. Format is "HH:mm:ss,fff". + /// + /// The date to render into a string. + /// The writer to write to. + /// + /// + /// Uses the method to generate the + /// time string up to the seconds and then appends the current + /// milliseconds. The results from are + /// cached and is called at most once + /// per second. + /// + /// + /// Sub classes should override + /// rather than . + /// + /// + public virtual void FormatDate(DateTime dateToFormat, TextWriter writer) + { + lock (s_lastTimeStrings) + { + // Calculate the current time precise only to the second + long currentTimeToTheSecond = dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond); + + string timeString = null; + + // Compare this time with the stored last time + // If we are in the same second then append + // the previously calculated time string + if (s_lastTimeToTheSecond != currentTimeToTheSecond) + { + s_lastTimeStrings.Clear(); + } + else + { + timeString = (string)s_lastTimeStrings[this.GetType()]; + } + + if (timeString == null) + { + // lock so that only one thread can use the buffer and + // update the s_lastTimeToTheSecond and s_lastTimeStrings + + // PERF: Try removing this lock and using a new StringBuilder each time + lock (s_lastTimeBuf) + { + timeString = (string)s_lastTimeStrings[this.GetType()]; + + if (timeString == null) + { + // We are in a new second. + s_lastTimeBuf.Length = 0; + + // Calculate the new string for this second + this.FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); + + // Render the string buffer to a string + timeString = s_lastTimeBuf.ToString(); + #if NET_1_1 // Ensure that the above string is written into the variable NOW on all threads. // This is only required on multiprocessor machines with weak memeory models System.Threading.Thread.MemoryBarrier(); #endif - // Store the time as a string (we only have to do this once per second) - s_lastTimeStrings[GetType()] = timeString; - s_lastTimeToTheSecond = currentTimeToTheSecond; - } - } - } - writer.Write(timeString); - - // Append the current millisecond info - writer.Write(','); - int millis = dateToFormat.Millisecond; - if (millis < 100) - { - writer.Write('0'); - } - if (millis < 10) - { - writer.Write('0'); - } - writer.Write(millis); - } - } - - #endregion Implementation of IDateFormatter - - #region Public Static Fields - - /// - /// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is ABSOLUTE. - /// - public const string AbsoluteTimeDateFormat = "ABSOLUTE"; - - /// - /// String constant used to specify DateTimeDateFormat in layouts. Current value is DATE. - /// - public const string DateAndTimeDateFormat = "DATE"; - - /// - /// String constant used to specify ISO8601DateFormat in layouts. Current value is ISO8601. - /// - public const string Iso8601TimeDateFormat = "ISO8601"; - - #endregion Public Static Fields - - #region Private Static Fields - - /// - /// Last stored time with precision up to the second. - /// - private static long s_lastTimeToTheSecond = 0; - - /// - /// Last stored time with precision up to the second, formatted - /// as a string. - /// - private static StringBuilder s_lastTimeBuf = new StringBuilder(); - - /// - /// Last stored time with precision up to the second, formatted - /// as a string. - /// - private static Hashtable s_lastTimeStrings = new Hashtable(); - - #endregion Private Static Fields - } + + // Store the time as a string (we only have to do this once per second) + s_lastTimeStrings[this.GetType()] = timeString; + s_lastTimeToTheSecond = currentTimeToTheSecond; + } + } + } + + writer.Write(timeString); + + // Append the current millisecond info + writer.Write(','); + int millis = dateToFormat.Millisecond; + if (millis < 100) + { + writer.Write('0'); + } + + if (millis < 10) + { + writer.Write('0'); + } + + writer.Write(millis); + } + } + + /// + /// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is ABSOLUTE. + /// + public const string AbsoluteTimeDateFormat = "ABSOLUTE"; + + /// + /// String constant used to specify DateTimeDateFormat in layouts. Current value is DATE. + /// + public const string DateAndTimeDateFormat = "DATE"; + + /// + /// String constant used to specify ISO8601DateFormat in layouts. Current value is ISO8601. + /// + public const string Iso8601TimeDateFormat = "ISO8601"; + + /// + /// Last stored time with precision up to the second. + /// + private static long s_lastTimeToTheSecond = 0; + + /// + /// Last stored time with precision up to the second, formatted + /// as a string. + /// + private static StringBuilder s_lastTimeBuf = new StringBuilder(); + + /// + /// Last stored time with precision up to the second, formatted + /// as a string. + /// + private static Hashtable s_lastTimeStrings = new Hashtable(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs index d6ca4d7ea94..568841722d5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs @@ -1,110 +1,97 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.Globalization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.DateFormatter { - /// - /// Formats a as "dd MMM yyyy HH:mm:ss,fff" - /// - /// - /// - /// Formats a in the format - /// "dd MMM yyyy HH:mm:ss,fff" for example, - /// "06 Nov 1994 15:49:37,459". - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Angelika Schnagl - public class DateTimeDateFormatter : AbsoluteTimeDateFormatter - { - #region Public Instance Constructors - - /// - /// Default constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public DateTimeDateFormatter() - { - m_dateTimeFormatInfo = DateTimeFormatInfo.InvariantInfo; - } - - #endregion Public Instance Constructors - - #region Override implementation of AbsoluteTimeDateFormatter - - /// - /// Formats the date without the milliseconds part - /// - /// The date to format. - /// The string builder to write to. - /// - /// - /// Formats a DateTime in the format "dd MMM yyyy HH:mm:ss" - /// for example, "06 Nov 1994 15:49:37". - /// - /// - /// The base class will append the ",fff" milliseconds section. - /// This method will only be called at most once per second. - /// - /// - override protected void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) - { - int day = dateToFormat.Day; - if (day < 10) - { - buffer.Append('0'); - } - buffer.Append(day); - buffer.Append(' '); - - buffer.Append(m_dateTimeFormatInfo.GetAbbreviatedMonthName(dateToFormat.Month)); - buffer.Append(' '); - - buffer.Append(dateToFormat.Year); - buffer.Append(' '); - - // Append the 'HH:mm:ss' - base.FormatDateWithoutMillis(dateToFormat, buffer); - } - - #endregion Override implementation of AbsoluteTimeDateFormatter + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + using System.Text; + + /// + /// Formats a as "dd MMM yyyy HH:mm:ss,fff". + /// + /// + /// + /// Formats a in the format + /// "dd MMM yyyy HH:mm:ss,fff" for example, + /// "06 Nov 1994 15:49:37,459". + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Angelika Schnagl. + public class DateTimeDateFormatter : AbsoluteTimeDateFormatter + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public DateTimeDateFormatter() + { + this.m_dateTimeFormatInfo = DateTimeFormatInfo.InvariantInfo; + } + + /// + /// Formats the date without the milliseconds part. + /// + /// The date to format. + /// The string builder to write to. + /// + /// + /// Formats a DateTime in the format "dd MMM yyyy HH:mm:ss" + /// for example, "06 Nov 1994 15:49:37". + /// + /// + /// The base class will append the ",fff" milliseconds section. + /// This method will only be called at most once per second. + /// + /// + protected override void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) + { + int day = dateToFormat.Day; + if (day < 10) + { + buffer.Append('0'); + } + + buffer.Append(day); + buffer.Append(' '); - #region Private Instance Fields + buffer.Append(this.m_dateTimeFormatInfo.GetAbbreviatedMonthName(dateToFormat.Month)); + buffer.Append(' '); - /// - /// The format info for the invariant culture. - /// - private readonly DateTimeFormatInfo m_dateTimeFormatInfo; + buffer.Append(dateToFormat.Year); + buffer.Append(' '); - #endregion Private Instance Fields - } + // Append the 'HH:mm:ss' + base.FormatDateWithoutMillis(dateToFormat, buffer); + } + + /// + /// The format info for the invariant culture. + /// + private readonly DateTimeFormatInfo m_dateTimeFormatInfo; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs index e2bea8d9954..d82e51ab753 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs @@ -1,59 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.DateFormatter { - /// - /// Render a as a string. - /// - /// - /// - /// Interface to abstract the rendering of a - /// instance into a string. - /// - /// - /// The method is used to render the - /// date to a text writer. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IDateFormatter - { - /// - /// Formats the specified date as a string. - /// - /// The date to format. - /// The writer to write to. - /// - /// - /// Format the as a string and write it - /// to the provided. - /// - /// - void FormatDate(DateTime dateToFormat, TextWriter writer); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + /// + /// Render a as a string. + /// + /// + /// + /// Interface to abstract the rendering of a + /// instance into a string. + /// + /// + /// The method is used to render the + /// date to a text writer. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IDateFormatter + { + /// + /// Formats the specified date as a string. + /// + /// The date to format. + /// The writer to write to. + /// + /// + /// Format the as a string and write it + /// to the provided. + /// + /// + void FormatDate(DateTime dateToFormat, TextWriter writer); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs index b1a560cec94..2bb6438cf5e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs @@ -1,100 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.DateFormatter { - /// - /// Formats the as "yyyy-MM-dd HH:mm:ss,fff". - /// - /// - /// - /// Formats the specified as a string: "yyyy-MM-dd HH:mm:ss,fff". - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class Iso8601DateFormatter : AbsoluteTimeDateFormatter - { - #region Public Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public Iso8601DateFormatter() - { - } - - #endregion Public Instance Constructors - - #region Override implementation of AbsoluteTimeDateFormatter - - /// - /// Formats the date without the milliseconds part - /// - /// The date to format. - /// The string builder to write to. - /// - /// - /// Formats the date specified as a string: "yyyy-MM-dd HH:mm:ss". - /// - /// - /// The base class will append the ",fff" milliseconds section. - /// This method will only be called at most once per second. - /// - /// - override protected void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) - { - buffer.Append(dateToFormat.Year); - - buffer.Append('-'); - int month = dateToFormat.Month; - if (month < 10) - { - buffer.Append('0'); - } - buffer.Append(month); - buffer.Append('-'); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + /// + /// Formats the as "yyyy-MM-dd HH:mm:ss,fff". + /// + /// + /// + /// Formats the specified as a string: "yyyy-MM-dd HH:mm:ss,fff". + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class Iso8601DateFormatter : AbsoluteTimeDateFormatter + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public Iso8601DateFormatter() + { + } + + /// + /// Formats the date without the milliseconds part. + /// + /// The date to format. + /// The string builder to write to. + /// + /// + /// Formats the date specified as a string: "yyyy-MM-dd HH:mm:ss". + /// + /// + /// The base class will append the ",fff" milliseconds section. + /// This method will only be called at most once per second. + /// + /// + protected override void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) + { + buffer.Append(dateToFormat.Year); - int day = dateToFormat.Day; - if (day < 10) - { - buffer.Append('0'); - } - buffer.Append(day); - buffer.Append(' '); + buffer.Append('-'); + int month = dateToFormat.Month; + if (month < 10) + { + buffer.Append('0'); + } + + buffer.Append(month); + buffer.Append('-'); - // Append the 'HH:mm:ss' - base.FormatDateWithoutMillis(dateToFormat, buffer); - } + int day = dateToFormat.Day; + if (day < 10) + { + buffer.Append('0'); + } + + buffer.Append(day); + buffer.Append(' '); - #endregion Override implementation of AbsoluteTimeDateFormatter - } + // Append the 'HH:mm:ss' + base.FormatDateWithoutMillis(dateToFormat, buffer); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs index 7aecb3352c7..41f1e42f092 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs @@ -1,99 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.DateFormatter { - /// - /// Formats the using the method. - /// - /// - /// - /// Formats the using the method. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class SimpleDateFormatter : IDateFormatter - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// The format string. - /// - /// - /// Initializes a new instance of the class - /// with the specified format string. - /// - /// - /// The format string must be compatible with the options - /// that can be supplied to . - /// - /// - public SimpleDateFormatter(string format) - { - m_formatString = format; - } - - #endregion Public Instance Constructors - - #region Implementation of IDateFormatter - - /// - /// Formats the date using . - /// - /// The date to convert to a string. - /// The writer to write to. - /// - /// - /// Uses the date format string supplied to the constructor to call - /// the method to format the date. - /// - /// - virtual public void FormatDate(DateTime dateToFormat, TextWriter writer) - { - writer.Write(dateToFormat.ToString(m_formatString, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - } - - #endregion - - #region Private Instance Fields - - /// - /// The format string used to format the . - /// - /// - /// - /// The format string must be compatible with the options - /// that can be supplied to . - /// - /// - private readonly string m_formatString; - - #endregion Private Instance Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + /// + /// Formats the using the method. + /// + /// + /// + /// Formats the using the method. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class SimpleDateFormatter : IDateFormatter + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The format string. + /// + /// + /// Initializes a new instance of the class + /// with the specified format string. + /// + /// + /// The format string must be compatible with the options + /// that can be supplied to . + /// + /// + public SimpleDateFormatter(string format) + { + this.m_formatString = format; + } + + /// + /// Formats the date using . + /// + /// The date to convert to a string. + /// The writer to write to. + /// + /// + /// Uses the date format string supplied to the constructor to call + /// the method to format the date. + /// + /// + public virtual void FormatDate(DateTime dateToFormat, TextWriter writer) + { + writer.Write(dateToFormat.ToString(this.m_formatString, System.Globalization.DateTimeFormatInfo.InvariantInfo)); + } + + /// + /// The format string used to format the . + /// + /// + /// + /// The format string must be compatible with the options + /// that can be supplied to . + /// + /// + private readonly string m_formatString; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs index 1d31dabbe88..74673fe255e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs @@ -1,79 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// This filter drops all . - /// - /// - /// - /// You can add this filter to the end of a filter chain to - /// switch from the default "accept all unless instructed otherwise" - /// filtering behavior to a "deny all unless instructed otherwise" - /// behavior. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class DenyAllFilter : FilterSkeleton - { - #region Constructors - - /// - /// Default constructor - /// - public DenyAllFilter() - { - } - - #endregion - - #region Override implementation of FilterSkeleton - - /// - /// Always returns the integer constant - /// - /// the LoggingEvent to filter - /// Always returns - /// - /// - /// Ignores the event being logged and just returns - /// . This can be used to change the default filter - /// chain behavior from to . This filter - /// should only be used as the last filter in the chain - /// as any further filters will be ignored! - /// - /// - override public FilterDecision Decide(LoggingEvent loggingEvent) - { - return FilterDecision.Deny; - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + + /// + /// This filter drops all . + /// + /// + /// + /// You can add this filter to the end of a filter chain to + /// switch from the default "accept all unless instructed otherwise" + /// filtering behavior to a "deny all unless instructed otherwise" + /// behavior. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class DenyAllFilter : FilterSkeleton + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public DenyAllFilter() + { + } + + /// + /// Always returns the integer constant . + /// + /// the LoggingEvent to filter. + /// Always returns . + /// + /// + /// Ignores the event being logged and just returns + /// . This can be used to change the default filter + /// chain behavior from to . This filter + /// should only be used as the last filter in the chain + /// as any further filters will be ignored!. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + return FilterDecision.Deny; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs index d5948c968d9..c80edf64b76 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs @@ -1,58 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// The return result from - /// - /// - /// - /// The return result from - /// - /// - public enum FilterDecision : int - { - /// - /// The log event must be dropped immediately without - /// consulting with the remaining filters, if any, in the chain. - /// - Deny = -1, - - /// - /// This filter is neutral with respect to the log event. - /// The remaining filters, if any, should be consulted for a final decision. - /// - Neutral = 0, + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + + /// + /// The return result from . + /// + /// + /// + /// The return result from . + /// + /// + public enum FilterDecision : int + { + /// + /// The log event must be dropped immediately without + /// consulting with the remaining filters, if any, in the chain. + /// + Deny = -1, + + /// + /// This filter is neutral with respect to the log event. + /// The remaining filters, if any, should be consulted for a final decision. + /// + Neutral = 0, - /// - /// The log event must be logged immediately without - /// consulting with the remaining filters, if any, in the chain. - /// - Accept = 1, - } + /// + /// The log event must be logged immediately without + /// consulting with the remaining filters, if any, in the chain. + /// + Accept = 1, + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs index 9ecf070e445..5328920fd8f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs @@ -1,159 +1,145 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// Subclass this type to implement customized logging event filtering - /// - /// - /// - /// Users should extend this class to implement customized logging - /// event filtering. Note that and - /// , the parent class of all standard - /// appenders, have built-in filtering rules. It is suggested that you - /// first use and understand the built-in rules before rushing to write - /// your own custom filters. - /// - /// - /// This abstract class assumes and also imposes that filters be - /// organized in a linear chain. The - /// method of each filter is called sequentially, in the order of their - /// addition to the chain. - /// - /// - /// The method must return one - /// of the integer constants , - /// or . - /// - /// - /// If the value is returned, then the log event is dropped - /// immediately without consulting with the remaining filters. - /// - /// - /// If the value is returned, then the next filter - /// in the chain is consulted. If there are no more filters in the - /// chain, then the log event is logged. Thus, in the presence of no - /// filters, the default behavior is to log all logging events. - /// - /// - /// If the value is returned, then the log - /// event is logged without consulting the remaining filters. - /// - /// - /// The philosophy of log4net filters is largely inspired from the - /// Linux ipchains. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public abstract class FilterSkeleton : IFilter - { - #region Member Variables - - /// - /// Points to the next filter in the filter chain. - /// - /// - /// - /// See for more information. - /// - /// - private IFilter m_next; - - #endregion - - #region Implementation of IOptionHandler - - /// - /// Initialize the filter with the options set - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Typically filter's options become active immediately on set, - /// however this method must still be called. - /// - /// - virtual public void ActivateOptions() - { - } - - #endregion - - #region Implementation of IFilter - - /// - /// Decide if the should be logged through an appender. - /// - /// The to decide upon - /// The decision of the filter - /// - /// - /// If the decision is , then the event will be - /// dropped. If the decision is , then the next - /// filter, if any, will be invoked. If the decision is then - /// the event will be logged without consulting with other filters in - /// the chain. - /// - /// - /// This method is marked abstract and must be implemented - /// in a subclass. - /// - /// - abstract public FilterDecision Decide(LoggingEvent loggingEvent); - - /// - /// Property to get and set the next filter - /// - /// - /// The next filter in the chain - /// - /// - /// - /// Filters are typically composed into chains. This property allows the next filter in - /// the chain to be accessed. - /// - /// - public IFilter Next - { - get { return m_next; } - set { m_next = value; } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + + /// + /// Subclass this type to implement customized logging event filtering. + /// + /// + /// + /// Users should extend this class to implement customized logging + /// event filtering. Note that and + /// , the parent class of all standard + /// appenders, have built-in filtering rules. It is suggested that you + /// first use and understand the built-in rules before rushing to write + /// your own custom filters. + /// + /// + /// This abstract class assumes and also imposes that filters be + /// organized in a linear chain. The + /// method of each filter is called sequentially, in the order of their + /// addition to the chain. + /// + /// + /// The method must return one + /// of the integer constants , + /// or . + /// + /// + /// If the value is returned, then the log event is dropped + /// immediately without consulting with the remaining filters. + /// + /// + /// If the value is returned, then the next filter + /// in the chain is consulted. If there are no more filters in the + /// chain, then the log event is logged. Thus, in the presence of no + /// filters, the default behavior is to log all logging events. + /// + /// + /// If the value is returned, then the log + /// event is logged without consulting the remaining filters. + /// + /// + /// The philosophy of log4net filters is largely inspired from the + /// Linux ipchains. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class FilterSkeleton : IFilter + { + /// + /// Points to the next filter in the filter chain. + /// + /// + /// + /// See for more information. + /// + /// + private IFilter m_next; + + /// + /// Initialize the filter with the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Typically filter's options become active immediately on set, + /// however this method must still be called. + /// + /// + public virtual void ActivateOptions() + { + } + + /// + /// Decide if the should be logged through an appender. + /// + /// The to decide upon. + /// The decision of the filter. + /// + /// + /// If the decision is , then the event will be + /// dropped. If the decision is , then the next + /// filter, if any, will be invoked. If the decision is then + /// the event will be logged without consulting with other filters in + /// the chain. + /// + /// + /// This method is marked abstract and must be implemented + /// in a subclass. + /// + /// + public abstract FilterDecision Decide(LoggingEvent loggingEvent); - #endregion - } + /// + /// Gets or sets property to get and set the next filter. + /// + /// + /// The next filter in the chain. + /// + /// + /// + /// Filters are typically composed into chains. This property allows the next filter in + /// the chain to be accessed. + /// + /// + public IFilter Next + { + get { return this.m_next; } + set { this.m_next = value; } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs index 8e4bd364127..0666a393592 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs @@ -1,106 +1,103 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// Implement this interface to provide customized logging event filtering - /// - /// - /// - /// Users should implement this interface to implement customized logging - /// event filtering. Note that and - /// , the parent class of all standard - /// appenders, have built-in filtering rules. It is suggested that you - /// first use and understand the built-in rules before rushing to write - /// your own custom filters. - /// - /// - /// This abstract class assumes and also imposes that filters be - /// organized in a linear chain. The - /// method of each filter is called sequentially, in the order of their - /// addition to the chain. - /// - /// - /// The method must return one - /// of the integer constants , - /// or . - /// - /// - /// If the value is returned, then the log event is dropped - /// immediately without consulting with the remaining filters. - /// - /// - /// If the value is returned, then the next filter - /// in the chain is consulted. If there are no more filters in the - /// chain, then the log event is logged. Thus, in the presence of no - /// filters, the default behavior is to log all logging events. - /// - /// - /// If the value is returned, then the log - /// event is logged without consulting the remaining filters. - /// - /// - /// The philosophy of log4net filters is largely inspired from the - /// Linux ipchains. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IFilter : IOptionHandler - { - /// - /// Decide if the logging event should be logged through an appender. - /// - /// The LoggingEvent to decide upon - /// The decision of the filter - /// - /// - /// If the decision is , then the event will be - /// dropped. If the decision is , then the next - /// filter, if any, will be invoked. If the decision is then - /// the event will be logged without consulting with other filters in - /// the chain. - /// - /// - FilterDecision Decide(LoggingEvent loggingEvent); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + + /// + /// Implement this interface to provide customized logging event filtering. + /// + /// + /// + /// Users should implement this interface to implement customized logging + /// event filtering. Note that and + /// , the parent class of all standard + /// appenders, have built-in filtering rules. It is suggested that you + /// first use and understand the built-in rules before rushing to write + /// your own custom filters. + /// + /// + /// This abstract class assumes and also imposes that filters be + /// organized in a linear chain. The + /// method of each filter is called sequentially, in the order of their + /// addition to the chain. + /// + /// + /// The method must return one + /// of the integer constants , + /// or . + /// + /// + /// If the value is returned, then the log event is dropped + /// immediately without consulting with the remaining filters. + /// + /// + /// If the value is returned, then the next filter + /// in the chain is consulted. If there are no more filters in the + /// chain, then the log event is logged. Thus, in the presence of no + /// filters, the default behavior is to log all logging events. + /// + /// + /// If the value is returned, then the log + /// event is logged without consulting the remaining filters. + /// + /// + /// The philosophy of log4net filters is largely inspired from the + /// Linux ipchains. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IFilter : IOptionHandler + { + /// + /// Decide if the logging event should be logged through an appender. + /// + /// The LoggingEvent to decide upon. + /// The decision of the filter. + /// + /// + /// If the decision is , then the event will be + /// dropped. If the decision is , then the next + /// filter, if any, will be invoked. If the decision is then + /// the event will be logged without consulting with other filters in + /// the chain. + /// + /// + FilterDecision Decide(LoggingEvent loggingEvent); - /// - /// Property to get and set the next filter - /// - /// - /// The next filter in the chain - /// - /// - /// - /// Filters are typically composed into chains. This property allows the next filter in - /// the chain to be accessed. - /// - /// - IFilter Next { get; set; } - } + /// + /// Gets or sets property to get and set the next filter. + /// + /// + /// The next filter in the chain. + /// + /// + /// + /// Filters are typically composed into chains. This property allows the next filter in + /// the chain to be accessed. + /// + /// + IFilter Next { get; set; } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs index 7d2c3310b34..f6b44a90018 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs @@ -1,146 +1,133 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// This is a very simple filter based on matching. - /// - /// - /// - /// The filter admits two options and - /// . If there is an exact match between the value - /// of the option and the of the - /// , then the method returns in - /// case the option value is set - /// to true, if it is false then - /// is returned. If the does not match then - /// the result will be . - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class LevelMatchFilter : FilterSkeleton - { - #region Member Variables - - /// - /// flag to indicate if the filter should on a match - /// - private bool m_acceptOnMatch = true; - - /// - /// the to match against - /// - private Level m_levelToMatch; - - #endregion - - #region Constructors - - /// - /// Default constructor - /// - public LevelMatchFilter() - { - } - - #endregion - - /// - /// when matching - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return m_acceptOnMatch; } - set { m_acceptOnMatch = value; } - } - - /// - /// The that the filter will match - /// - /// - /// - /// The level that this filter will attempt to match against the - /// level. If a match is found then - /// the result depends on the value of . - /// - /// - public Level LevelToMatch - { - get { return m_levelToMatch; } - set { m_levelToMatch = value; } - } - - #region Override implementation of FilterSkeleton + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net; + using log4net.Core; + using log4net.Util; + + /// + /// This is a very simple filter based on matching. + /// + /// + /// + /// The filter admits two options and + /// . If there is an exact match between the value + /// of the option and the of the + /// , then the method returns in + /// case the option value is set + /// to true, if it is false then + /// is returned. If the does not match then + /// the result will be . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class LevelMatchFilter : FilterSkeleton + { + /// + /// flag to indicate if the filter should on a match. + /// + private bool m_acceptOnMatch = true; - /// - /// Tests if the of the logging event matches that of the filter - /// - /// the event to filter - /// see remarks - /// - /// - /// If the of the event matches the level of the - /// filter then the result of the function depends on the - /// value of . If it is true then - /// the function will return , it it is false then it - /// will return . If the does not match then - /// the result will be . - /// - /// - override public FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } + /// + /// the to match against. + /// + private Level m_levelToMatch; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public LevelMatchFilter() + { + } + + /// + /// Gets or sets a value indicating whether when matching . + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } + } - if (m_levelToMatch != null && m_levelToMatch == loggingEvent.Level) - { - // Found match - return m_acceptOnMatch ? FilterDecision.Accept : FilterDecision.Deny; - } - return FilterDecision.Neutral; - } + /// + /// Gets or sets the that the filter will match. + /// + /// + /// + /// The level that this filter will attempt to match against the + /// level. If a match is found then + /// the result depends on the value of . + /// + /// + public Level LevelToMatch + { + get { return this.m_levelToMatch; } + set { this.m_levelToMatch = value; } + } + + /// + /// Tests if the of the logging event matches that of the filter. + /// + /// the event to filter. + /// see remarks. + /// + /// + /// If the of the event matches the level of the + /// filter then the result of the function depends on the + /// value of . If it is true then + /// the function will return , it it is false then it + /// will return . If the does not match then + /// the result will be . + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - #endregion - } + if (this.m_levelToMatch != null && this.m_levelToMatch == loggingEvent.Level) + { + // Found match + return this.m_acceptOnMatch ? FilterDecision.Accept : FilterDecision.Deny; + } + + return FilterDecision.Neutral; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs index ac0aa4e7ca2..9186c029d93 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs @@ -1,189 +1,175 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// This is a simple filter based on matching. - /// - /// - /// - /// The filter admits three options and - /// that determine the range of priorities that are matched, and - /// . If there is a match between the range - /// of priorities and the of the , then the - /// method returns in case the - /// option value is set to true, if it is false - /// then is returned. If there is no match, is returned. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class LevelRangeFilter : FilterSkeleton - { - #region Member Variables - - /// - /// Flag to indicate the behavior when matching a - /// - private bool m_acceptOnMatch = true; - - /// - /// the minimum value to match - /// - private Level m_levelMin; - - /// - /// the maximum value to match - /// - private Level m_levelMax; - - #endregion - - #region Constructors - - /// - /// Default constructor - /// - public LevelRangeFilter() - { - } - - #endregion - - /// - /// when matching and - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return m_acceptOnMatch; } - set { m_acceptOnMatch = value; } - } - - /// - /// Set the minimum matched - /// - /// - /// - /// The minimum level that this filter will attempt to match against the - /// level. If a match is found then - /// the result depends on the value of . - /// - /// - public Level LevelMin - { - get { return m_levelMin; } - set { m_levelMin = value; } - } - - /// - /// Sets the maximum matched - /// - /// - /// - /// The maximum level that this filter will attempt to match against the - /// level. If a match is found then - /// the result depends on the value of . - /// - /// - public Level LevelMax - { - get { return m_levelMax; } - set { m_levelMax = value; } - } - - #region Override implementation of FilterSkeleton - - /// - /// Check if the event should be logged. - /// - /// the logging event to check - /// see remarks - /// - /// - /// If the of the logging event is outside the range - /// matched by this filter then - /// is returned. If the is matched then the value of - /// is checked. If it is true then - /// is returned, otherwise - /// is returned. - /// - /// - override public FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - if (m_levelMin != null) - { - if (loggingEvent.Level < m_levelMin) - { - // level of event is less than minimum - return FilterDecision.Deny; - } - } - - if (m_levelMax != null) - { - if (loggingEvent.Level > m_levelMax) - { - // level of event is greater than maximum - return FilterDecision.Deny; - } - } - - if (m_acceptOnMatch) - { - // this filter set up to bypass later filters and always return - // accept if level in range - return FilterDecision.Accept; - } - else - { - // event is ok for this filter; allow later filters to have a look.. - return FilterDecision.Neutral; - } - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net; + using log4net.Core; + using log4net.Util; + + /// + /// This is a simple filter based on matching. + /// + /// + /// + /// The filter admits three options and + /// that determine the range of priorities that are matched, and + /// . If there is a match between the range + /// of priorities and the of the , then the + /// method returns in case the + /// option value is set to true, if it is false + /// then is returned. If there is no match, is returned. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class LevelRangeFilter : FilterSkeleton + { + /// + /// Flag to indicate the behavior when matching a . + /// + private bool m_acceptOnMatch = true; + + /// + /// the minimum value to match. + /// + private Level m_levelMin; + + /// + /// the maximum value to match. + /// + private Level m_levelMax; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public LevelRangeFilter() + { + } + + /// + /// Gets or sets a value indicating whether when matching and . + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } + } + + /// + /// Gets or sets set the minimum matched . + /// + /// + /// + /// The minimum level that this filter will attempt to match against the + /// level. If a match is found then + /// the result depends on the value of . + /// + /// + public Level LevelMin + { + get { return this.m_levelMin; } + set { this.m_levelMin = value; } + } + + /// + /// Gets or sets the maximum matched . + /// + /// + /// + /// The maximum level that this filter will attempt to match against the + /// level. If a match is found then + /// the result depends on the value of . + /// + /// + public Level LevelMax + { + get { return this.m_levelMax; } + set { this.m_levelMax = value; } + } + + /// + /// Check if the event should be logged. + /// + /// the logging event to check. + /// see remarks. + /// + /// + /// If the of the logging event is outside the range + /// matched by this filter then + /// is returned. If the is matched then the value of + /// is checked. If it is true then + /// is returned, otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + if (this.m_levelMin != null) + { + if (loggingEvent.Level < this.m_levelMin) + { + // level of event is less than minimum + return FilterDecision.Deny; + } + } + + if (this.m_levelMax != null) + { + if (loggingEvent.Level > this.m_levelMax) + { + // level of event is greater than maximum + return FilterDecision.Deny; + } + } + + if (this.m_acceptOnMatch) + { + // this filter set up to bypass later filters and always return + // accept if level in range + return FilterDecision.Accept; + } + else + { + // event is ok for this filter; allow later filters to have a look.. + return FilterDecision.Neutral; + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs index a949843ed5d..3d29dcb8c56 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs @@ -1,164 +1,147 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// Simple filter to match a string in the event's logger name. - /// - /// - /// - /// The works very similar to the . It admits two - /// options and . If the - /// of the starts - /// with the value of the option, then the - /// method returns in - /// case the option value is set to true, - /// if it is false then is returned. - /// - /// - /// Daniel Cazzulino - public class LoggerMatchFilter : FilterSkeleton - { - #region Member Variables - - /// - /// Flag to indicate the behavior when we have a match - /// - private bool m_acceptOnMatch = true; - - /// - /// The logger name string to substring match against the event - /// - private string m_loggerToMatch; - - #endregion - - #region Constructors - - /// - /// Default constructor - /// - public LoggerMatchFilter() - { - } - - #endregion - - #region Properties - - /// - /// when matching - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return m_acceptOnMatch; } - set { m_acceptOnMatch = value; } - } - - /// - /// The that the filter will match - /// - /// - /// - /// This filter will attempt to match this value against logger name in - /// the following way. The match will be done against the beginning of the - /// logger name (using ). The match is - /// case sensitive. If a match is found then - /// the result depends on the value of . - /// - /// - public string LoggerToMatch - { - get { return m_loggerToMatch; } - set { m_loggerToMatch = value; } - } - - #endregion - - #region Override implementation of FilterSkeleton - - /// - /// Check if this filter should allow the event to be logged - /// - /// the event being logged - /// see remarks - /// - /// - /// The rendered message is matched against the . - /// If the equals the beginning of - /// the incoming () - /// then a match will have occurred. If no match occurs - /// this function will return - /// allowing other filters to check the event. If a match occurs then - /// the value of is checked. If it is - /// true then is returned otherwise - /// is returned. - /// - /// - override public FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - // Check if we have been setup to filter - if ((m_loggerToMatch != null && m_loggerToMatch.Length != 0) && - loggingEvent.LoggerName.StartsWith(m_loggerToMatch)) - { - // we've got a match - if (m_acceptOnMatch) - { - return FilterDecision.Accept; - } - return FilterDecision.Deny; - } - else - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net; + using log4net.Core; + using log4net.Util; + + /// + /// Simple filter to match a string in the event's logger name. + /// + /// + /// + /// The works very similar to the . It admits two + /// options and . If the + /// of the starts + /// with the value of the option, then the + /// method returns in + /// case the option value is set to true, + /// if it is false then is returned. + /// + /// + /// Daniel Cazzulino. + public class LoggerMatchFilter : FilterSkeleton + { + /// + /// Flag to indicate the behavior when we have a match. + /// + private bool m_acceptOnMatch = true; + + /// + /// The logger name string to substring match against the event. + /// + private string m_loggerToMatch; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public LoggerMatchFilter() + { + } + + /// + /// Gets or sets a value indicating whether when matching . + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } + } + + /// + /// Gets or sets the that the filter will match. + /// + /// + /// + /// This filter will attempt to match this value against logger name in + /// the following way. The match will be done against the beginning of the + /// logger name (using ). The match is + /// case sensitive. If a match is found then + /// the result depends on the value of . + /// + /// + public string LoggerToMatch + { + get { return this.m_loggerToMatch; } + set { this.m_loggerToMatch = value; } + } + + /// + /// Check if this filter should allow the event to be logged. + /// + /// the event being logged. + /// see remarks. + /// + /// + /// The rendered message is matched against the . + /// If the equals the beginning of + /// the incoming () + /// then a match will have occurred. If no match occurs + /// this function will return + /// allowing other filters to check the event. If a match occurs then + /// the value of is checked. If it is + /// true then is returned otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + // Check if we have been setup to filter + if ((this.m_loggerToMatch != null && this.m_loggerToMatch.Length != 0) && + loggingEvent.LoggerName.StartsWith(this.m_loggerToMatch)) + { + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + + return FilterDecision.Deny; + } + else + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs index e8be8e9da93..87b97a263bc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs @@ -1,51 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text.RegularExpressions; - -using log4net; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// Simple filter to match a keyed string in the - /// - /// - /// - /// Simple filter to match a keyed string in the - /// - /// - /// As the MDC has been replaced with layered properties the - /// should be used instead. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [Obsolete("MdcFilter has been replaced by PropertyFilter. Scheduled removal in v10.0.0.")] - public class MdcFilter : PropertyFilter - { - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text.RegularExpressions; + + using log4net; + using log4net.Core; + using log4net.Util; + + /// + /// Simple filter to match a keyed string in the . + /// + /// + /// + /// Simple filter to match a keyed string in the . + /// + /// + /// As the MDC has been replaced with layered properties the + /// should be used instead. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [Obsolete("MdcFilter has been replaced by PropertyFilter. Scheduled removal in v10.0.0.")] + public class MdcFilter : PropertyFilter + { + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs index 9be456e350d..c29894ecb4d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs @@ -1,64 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text.RegularExpressions; - -using log4net; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// Simple filter to match a string in the - /// - /// - /// - /// Simple filter to match a string in the - /// - /// - /// As the MDC has been replaced with named stacks stored in the - /// properties collections the should - /// be used instead. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [Obsolete("NdcFilter has been replaced by PropertyFilter. Scheduled removal in v10.0.0.")] - public class NdcFilter : PropertyFilter - { - /// - /// Default constructor - /// - /// - /// - /// Sets the to "NDC". - /// - /// - public NdcFilter() - { - base.Key = "NDC"; - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text.RegularExpressions; + + using log4net; + using log4net.Core; + using log4net.Util; + + /// + /// Simple filter to match a string in the . + /// + /// + /// + /// Simple filter to match a string in the . + /// + /// + /// As the MDC has been replaced with named stacks stored in the + /// properties collections the should + /// be used instead. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [Obsolete("NdcFilter has been replaced by PropertyFilter. Scheduled removal in v10.0.0.")] + public class NdcFilter : PropertyFilter + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Sets the to "NDC". + /// + /// + public NdcFilter() + { + this.Key = "NDC"; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs index 31305ba7968..aef8997d203 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs @@ -1,169 +1,158 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text.RegularExpressions; - -using log4net; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// Simple filter to match a string an event property - /// - /// - /// - /// Simple filter to match a string in the value for a - /// specific event property - /// - /// - /// Nicko Cadell - public class PropertyFilter : StringMatchFilter - { - #region Member Variables - - /// - /// The key to use to lookup the string from the event properties - /// - private string m_key; - - #endregion - - #region Constructors - - /// - /// Default constructor - /// - public PropertyFilter() - { - } - - #endregion - - /// - /// The key to lookup in the event properties and then match against. - /// - /// - /// - /// The key name to use to lookup in the properties map of the - /// . The match will be performed against - /// the value of this property if it exists. - /// - /// - public string Key - { - get { return m_key; } - set { m_key = value; } - } - - #region Override implementation of FilterSkeleton - - /// - /// Check if this filter should allow the event to be logged - /// - /// the event being logged - /// see remarks - /// - /// - /// The event property for the is matched against - /// the . - /// If the occurs as a substring within - /// the property value then a match will have occurred. If no match occurs - /// this function will return - /// allowing other filters to check the event. If a match occurs then - /// the value of is checked. If it is - /// true then is returned otherwise - /// is returned. - /// - /// - override public FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - // Check if we have a key to lookup the event property value with - if (m_key == null) - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } - - // Lookup the string to match in from the properties using - // the key specified. - object msgObj = loggingEvent.LookupProperty(m_key); - - // Use an ObjectRenderer to convert the property value to a string - string msg = loggingEvent.Repository.RendererMap.FindAndRender(msgObj); - - // Check if we have been setup to filter - if (msg == null || (m_stringToMatch == null && m_regexToMatch == null)) - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } - - // Firstly check if we are matching using a regex - if (m_regexToMatch != null) - { - // Check the regex - if (m_regexToMatch.Match(msg).Success == false) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (m_acceptOnMatch) - { - return FilterDecision.Accept; - } - return FilterDecision.Deny; - } - else if (m_stringToMatch != null) - { - // Check substring match - if (msg.IndexOf(m_stringToMatch) == -1) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (m_acceptOnMatch) - { - return FilterDecision.Accept; - } - return FilterDecision.Deny; - } - return FilterDecision.Neutral; - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text.RegularExpressions; + + using log4net; + using log4net.Core; + using log4net.Util; + + /// + /// Simple filter to match a string an event property. + /// + /// + /// + /// Simple filter to match a string in the value for a + /// specific event property. + /// + /// + /// Nicko Cadell. + public class PropertyFilter : StringMatchFilter + { + /// + /// The key to use to lookup the string from the event properties. + /// + private string m_key; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public PropertyFilter() + { + } + + /// + /// Gets or sets the key to lookup in the event properties and then match against. + /// + /// + /// + /// The key name to use to lookup in the properties map of the + /// . The match will be performed against + /// the value of this property if it exists. + /// + /// + public string Key + { + get { return this.m_key; } + set { this.m_key = value; } + } + + /// + /// Check if this filter should allow the event to be logged. + /// + /// the event being logged. + /// see remarks. + /// + /// + /// The event property for the is matched against + /// the . + /// If the occurs as a substring within + /// the property value then a match will have occurred. If no match occurs + /// this function will return + /// allowing other filters to check the event. If a match occurs then + /// the value of is checked. If it is + /// true then is returned otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + // Check if we have a key to lookup the event property value with + if (this.m_key == null) + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } + + // Lookup the string to match in from the properties using + // the key specified. + object msgObj = loggingEvent.LookupProperty(this.m_key); + + // Use an ObjectRenderer to convert the property value to a string + string msg = loggingEvent.Repository.RendererMap.FindAndRender(msgObj); + + // Check if we have been setup to filter + if (msg == null || (this.m_stringToMatch == null && this.m_regexToMatch == null)) + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } + + // Firstly check if we are matching using a regex + if (this.m_regexToMatch != null) + { + // Check the regex + if (this.m_regexToMatch.Match(msg).Success == false) + { + // No match, continue processing + return FilterDecision.Neutral; + } + + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + + return FilterDecision.Deny; + } + else if (this.m_stringToMatch != null) + { + // Check substring match + if (msg.IndexOf(this.m_stringToMatch) == -1) + { + // No match, continue processing + return FilterDecision.Neutral; + } + + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + + return FilterDecision.Deny; + } + + return FilterDecision.Neutral; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs index f9ad32d49c8..39f1c97be5f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs @@ -1,249 +1,233 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text.RegularExpressions; - -using log4net; -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Filter { - /// - /// Simple filter to match a string in the rendered message - /// - /// - /// - /// Simple filter to match a string in the rendered message - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class StringMatchFilter : FilterSkeleton - { - #region Member Variables - - /// - /// Flag to indicate the behavior when we have a match - /// - protected bool m_acceptOnMatch = true; - - /// - /// The string to substring match against the message - /// - protected string m_stringToMatch; - - /// - /// A string regex to match - /// - protected string m_stringRegexToMatch; - - /// - /// A regex object to match (generated from m_stringRegexToMatch) - /// - protected Regex m_regexToMatch; - - #endregion - - #region Constructors - - /// - /// Default constructor - /// - public StringMatchFilter() - { - } - - #endregion - - #region Implementation of IOptionHandler - - /// - /// Initialize and precompile the Regex if required - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { - if (m_stringRegexToMatch != null) - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text.RegularExpressions; + + using log4net; + using log4net.Core; + using log4net.Util; + + /// + /// Simple filter to match a string in the rendered message. + /// + /// + /// + /// Simple filter to match a string in the rendered message. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class StringMatchFilter : FilterSkeleton + { + /// + /// Flag to indicate the behavior when we have a match. + /// + protected bool m_acceptOnMatch = true; + + /// + /// The string to substring match against the message. + /// + protected string m_stringToMatch; + + /// + /// A string regex to match. + /// + protected string m_stringRegexToMatch; + + /// + /// A regex object to match (generated from m_stringRegexToMatch). + /// + protected Regex m_regexToMatch; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public StringMatchFilter() + { + } + + /// + /// Initialize and precompile the Regex if required. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + if (this.m_stringRegexToMatch != null) + { #if NETSTANDARD1_3 m_regexToMatch = new Regex(m_stringRegexToMatch); #else - m_regexToMatch = new Regex(m_stringRegexToMatch, RegexOptions.Compiled); + this.m_regexToMatch = new Regex(this.m_stringRegexToMatch, RegexOptions.Compiled); #endif - } - } - - #endregion - - /// - /// when matching or - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return m_acceptOnMatch; } - set { m_acceptOnMatch = value; } - } - - /// - /// Sets the static string to match - /// - /// - /// - /// The string that will be substring matched against - /// the rendered message. If the message contains this - /// string then the filter will match. If a match is found then - /// the result depends on the value of . - /// - /// - /// One of or - /// must be specified. - /// - /// - public string StringToMatch - { - get { return m_stringToMatch; } - set { m_stringToMatch = value; } - } - - /// - /// Sets the regular expression to match - /// - /// - /// - /// The regular expression pattern that will be matched against - /// the rendered message. If the message matches this - /// pattern then the filter will match. If a match is found then - /// the result depends on the value of . - /// - /// - /// One of or - /// must be specified. - /// - /// - public string RegexToMatch - { - get { return m_stringRegexToMatch; } - set { m_stringRegexToMatch = value; } - } - - #region Override implementation of FilterSkeleton - - /// - /// Check if this filter should allow the event to be logged - /// - /// the event being logged - /// see remarks - /// - /// - /// The rendered message is matched against the . - /// If the occurs as a substring within - /// the message then a match will have occurred. If no match occurs - /// this function will return - /// allowing other filters to check the event. If a match occurs then - /// the value of is checked. If it is - /// true then is returned otherwise - /// is returned. - /// - /// - override public FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - string msg = loggingEvent.RenderedMessage; - - // Check if we have been setup to filter - if (msg == null || (m_stringToMatch == null && m_regexToMatch == null)) - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } - - // Firstly check if we are matching using a regex - if (m_regexToMatch != null) - { - // Check the regex - if (m_regexToMatch.Match(msg).Success == false) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (m_acceptOnMatch) - { - return FilterDecision.Accept; - } - return FilterDecision.Deny; - } - else if (m_stringToMatch != null) - { - // Check substring match - if (msg.IndexOf(m_stringToMatch) == -1) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (m_acceptOnMatch) - { - return FilterDecision.Accept; - } - return FilterDecision.Deny; - } - return FilterDecision.Neutral; - - } - - #endregion - } + } + } + + /// + /// Gets or sets a value indicating whether when matching or . + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } + } + + /// + /// Gets or sets the static string to match. + /// + /// + /// + /// The string that will be substring matched against + /// the rendered message. If the message contains this + /// string then the filter will match. If a match is found then + /// the result depends on the value of . + /// + /// + /// One of or + /// must be specified. + /// + /// + public string StringToMatch + { + get { return this.m_stringToMatch; } + set { this.m_stringToMatch = value; } + } + + /// + /// Gets or sets the regular expression to match. + /// + /// + /// + /// The regular expression pattern that will be matched against + /// the rendered message. If the message matches this + /// pattern then the filter will match. If a match is found then + /// the result depends on the value of . + /// + /// + /// One of or + /// must be specified. + /// + /// + public string RegexToMatch + { + get { return this.m_stringRegexToMatch; } + set { this.m_stringRegexToMatch = value; } + } + + /// + /// Check if this filter should allow the event to be logged. + /// + /// the event being logged. + /// see remarks. + /// + /// + /// The rendered message is matched against the . + /// If the occurs as a substring within + /// the message then a match will have occurred. If no match occurs + /// this function will return + /// allowing other filters to check the event. If a match occurs then + /// the value of is checked. If it is + /// true then is returned otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + string msg = loggingEvent.RenderedMessage; + + // Check if we have been setup to filter + if (msg == null || (this.m_stringToMatch == null && this.m_regexToMatch == null)) + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } + + // Firstly check if we are matching using a regex + if (this.m_regexToMatch != null) + { + // Check the regex + if (this.m_regexToMatch.Match(msg).Success == false) + { + // No match, continue processing + return FilterDecision.Neutral; + } + + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + + return FilterDecision.Deny; + } + else if (this.m_stringToMatch != null) + { + // Check substring match + if (msg.IndexOf(this.m_stringToMatch) == -1) + { + // No match, continue processing + return FilterDecision.Neutral; + } + + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + + return FilterDecision.Deny; + } + + return FilterDecision.Neutral; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs index f84ec1c418c..5d8326f95d0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs @@ -1,106 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net { - /// - /// The log4net Global Context. - /// - /// - /// - /// The GlobalContext provides a location for global debugging - /// information to be stored. - /// - /// - /// The global context has a properties map and these properties can - /// be included in the output of log messages. The - /// supports selecting and outputing these properties. - /// - /// - /// By default the log4net:HostName property is set to the name of - /// the current machine. - /// - /// - /// - /// - /// GlobalContext.Properties["hostname"] = Environment.MachineName; - /// - /// - /// - /// Nicko Cadell - public sealed class GlobalContext - { - #region Private Instance Constructors - - /// - /// Private Constructor. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private GlobalContext() - { - } - - #endregion Private Instance Constructors - - static GlobalContext() - { - Properties[log4net.Core.LoggingEvent.HostNameProperty] = SystemInfo.HostName; - } - - #region Public Static Properties - - /// - /// The global properties map. - /// - /// - /// The global properties map. - /// - /// - /// - /// The global properties map. - /// - /// - public static GlobalContextProperties Properties - { - get { return s_properties; } - } - - #endregion Public Static Properties - - #region Private Static Fields - - /// - /// The global context properties instance - /// - private readonly static GlobalContextProperties s_properties = new GlobalContextProperties(); - - #endregion Private Static Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Util; + + /// + /// The log4net Global Context. + /// + /// + /// + /// The GlobalContext provides a location for global debugging + /// information to be stored. + /// + /// + /// The global context has a properties map and these properties can + /// be included in the output of log messages. The + /// supports selecting and outputing these properties. + /// + /// + /// By default the log4net:HostName property is set to the name of + /// the current machine. + /// + /// + /// + /// + /// GlobalContext.Properties["hostname"] = Environment.MachineName; + /// + /// + /// + /// Nicko Cadell. + public sealed class GlobalContext + { + /// + /// Initializes a new instance of the class. + /// Private Constructor. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private GlobalContext() + { + } + + static GlobalContext() + { + Properties[log4net.Core.LoggingEvent.HostNameProperty] = SystemInfo.HostName; + } + + /// + /// Gets the global properties map. + /// + /// + /// The global properties map. + /// + /// + /// + /// The global properties map. + /// + /// + public static GlobalContextProperties Properties + { + get { return s_properties; } + } + + /// + /// The global context properties instance. + /// + private static readonly GlobalContextProperties s_properties = new GlobalContextProperties(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs index 8c936bdecc7..d882d5e9472 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs @@ -1,964 +1,961 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Reflection; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net { - /// - /// The ILog interface is use by application to log messages into - /// the log4net framework. - /// - /// - /// - /// Use the to obtain logger instances - /// that implement this interface. The - /// static method is used to get logger instances. - /// - /// - /// This class contains methods for logging at different levels and also - /// has properties for determining if those logging levels are - /// enabled in the current configuration. - /// - /// - /// This interface can be implemented in different ways. This documentation - /// specifies reasonable behavior that a caller can expect from the actual - /// implementation, however different implementations reserve the right to - /// do things differently. - /// - /// - /// Simple example of logging messages - /// - /// ILog log = LogManager.GetLogger("application-log"); - /// - /// log.Info("Application Start"); - /// log.Debug("This is a debug message"); - /// - /// if (log.IsDebugEnabled) - /// { - /// log.Debug("This is another debug message"); - /// } - /// - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface ILog : ILoggerWrapper - { - /// Log a message object with the level. - /// - /// Log a message object with the level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is DEBUG - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// DEBUG enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - void Debug(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Debug(object message, Exception exception); - - /// Log a formatted string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Logs a message object with the level. - /// - /// - /// - /// This method first checks if this logger is INFO - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// INFO enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// The message object to log. - /// - /// - void Info(object message); - - /// - /// Logs a message object with the INFO level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Info(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Log a message object with the level. - /// - /// - /// - /// This method first checks if this logger is WARN - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// WARN enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// The message object to log. - /// - /// - void Warn(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Warn(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Logs a message object with the level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// ERROR enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - void Error(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Error(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Log a message object with the level. - /// - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// FATAL enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// The message object to log. - /// - /// - void Fatal(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Fatal(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(IFormatProvider provider, string format, params object[] args); - - /// - /// Checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// - /// This function is intended to lessen the computational cost of - /// disabled log debug statements. - /// - /// For some ILog interface log, when you write: - /// - /// log.Debug("This is entry number: " + i ); - /// - /// - /// You incur the cost constructing the message, string construction and concatenation in - /// this case, regardless of whether the message is logged or not. - /// - /// - /// If you are worried about speed (who isn't), then you should write: - /// - /// - /// if (log.IsDebugEnabled) - /// { - /// log.Debug("This is entry number: " + i ); - /// } - /// - /// - /// This way you will not incur the cost of parameter - /// construction if debugging is disabled for log. On - /// the other hand, if the log is debug enabled, you - /// will incur the cost of evaluating whether the logger is debug - /// enabled twice. Once in and once in - /// the . This is an insignificant overhead - /// since evaluating a logger takes about 1% of the time it - /// takes to actually log. This is the preferred style of logging. - /// - /// Alternatively if your logger is available statically then the is debug - /// enabled state can be stored in a static variable like this: - /// - /// - /// private static readonly bool isDebugEnabled = log.IsDebugEnabled; - /// - /// - /// Then when you come to log you can write: - /// - /// - /// if (isDebugEnabled) - /// { - /// log.Debug("This is entry number: " + i ); - /// } - /// - /// - /// This way the debug enabled state is only queried once - /// when the class is loaded. Using a private static readonly - /// variable is the most efficient because it is a run time constant - /// and can be heavily optimized by the JIT compiler. - /// - /// - /// Of course if you use a static readonly variable to - /// hold the enabled state of the logger then you cannot - /// change the enabled state at runtime to vary the logging - /// that is produced. You have to decide if you need absolute - /// speed or runtime flexibility. - /// - /// - /// - /// - bool IsDebugEnabled { get; } - - /// - /// Checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsInfoEnabled { get; } - - /// - /// Checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsWarnEnabled { get; } - - /// - /// Checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsErrorEnabled { get; } - - /// - /// Checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsFatalEnabled { get; } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Reflection; + + using log4net.Core; + + /// + /// The ILog interface is use by application to log messages into + /// the log4net framework. + /// + /// + /// + /// Use the to obtain logger instances + /// that implement this interface. The + /// static method is used to get logger instances. + /// + /// + /// This class contains methods for logging at different levels and also + /// has properties for determining if those logging levels are + /// enabled in the current configuration. + /// + /// + /// This interface can be implemented in different ways. This documentation + /// specifies reasonable behavior that a caller can expect from the actual + /// implementation, however different implementations reserve the right to + /// do things differently. + /// + /// + /// Simple example of logging messages. + /// + /// ILog log = LogManager.GetLogger("application-log"); + /// + /// log.Info("Application Start"); + /// log.Debug("This is a debug message"); + /// + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is another debug message"); + /// } + /// + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface ILog : ILoggerWrapper + { + /// Log a message object with the level. + /// + /// Log a message object with the level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is DEBUG + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// DEBUG enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + void Debug(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Debug(object message, Exception exception); + + /// Log a formatted string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Logs a message object with the level. + /// + /// + /// + /// This method first checks if this logger is INFO + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// INFO enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// The message object to log. + /// + /// + void Info(object message); + + /// + /// Logs a message object with the INFO level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Info(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Log a message object with the level. + /// + /// + /// + /// This method first checks if this logger is WARN + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// WARN enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// The message object to log. + /// + /// + void Warn(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Warn(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Logs a message object with the level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// ERROR enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + void Error(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Error(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Log a message object with the level. + /// + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// FATAL enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// The message object to log. + /// + /// + void Fatal(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Fatal(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(IFormatProvider provider, string format, params object[] args); + + /// + /// Gets a value indicating whether checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// + /// This function is intended to lessen the computational cost of + /// disabled log debug statements. + /// + /// For some ILog interface log, when you write: + /// + /// log.Debug("This is entry number: " + i ); + /// + /// + /// You incur the cost constructing the message, string construction and concatenation in + /// this case, regardless of whether the message is logged or not. + /// + /// + /// If you are worried about speed (who isn't), then you should write: + /// + /// + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// + /// + /// This way you will not incur the cost of parameter + /// construction if debugging is disabled for log. On + /// the other hand, if the log is debug enabled, you + /// will incur the cost of evaluating whether the logger is debug + /// enabled twice. Once in and once in + /// the . This is an insignificant overhead + /// since evaluating a logger takes about 1% of the time it + /// takes to actually log. This is the preferred style of logging. + /// + /// Alternatively if your logger is available statically then the is debug + /// enabled state can be stored in a static variable like this: + /// + /// + /// private static readonly bool isDebugEnabled = log.IsDebugEnabled; + /// + /// + /// Then when you come to log you can write: + /// + /// + /// if (isDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// + /// + /// This way the debug enabled state is only queried once + /// when the class is loaded. Using a private static readonly + /// variable is the most efficient because it is a run time constant + /// and can be heavily optimized by the JIT compiler. + /// + /// + /// Of course if you use a static readonly variable to + /// hold the enabled state of the logger then you cannot + /// change the enabled state at runtime to vary the logging + /// that is produced. You have to decide if you need absolute + /// speed or runtime flexibility. + /// + /// + /// + /// + bool IsDebugEnabled { get; } + + /// + /// Gets a value indicating whether checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsInfoEnabled { get; } + + /// + /// Gets a value indicating whether checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsWarnEnabled { get; } + + /// + /// Gets a value indicating whether checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsErrorEnabled { get; } + + /// + /// Gets a value indicating whether checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsFatalEnabled { get; } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs index cee47a754c8..62cc3a05982 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs @@ -1,147 +1,141 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - - -using System; -using System.Collections; -using System.IO; - -using log4net.Core; -using log4net.Layout.Pattern; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// A flexible layout configurable with pattern string that re-evaluates on each call. - /// - /// - /// This class is built on and provides all the - /// features and capabilities of PatternLayout. PatternLayout is a 'static' class - /// in that its layout is done once at configuration time. This class will recreate - /// the layout on each reference. - /// One important difference between PatternLayout and DynamicPatternLayout is the - /// treatment of the Header and Footer parameters in the configuration. The Header and Footer - /// parameters for DynamicPatternLayout must be syntactically in the form of a PatternString, - /// but should not be marked as type log4net.Util.PatternString. Doing so causes the - /// pattern to be statically converted at configuration time and causes DynamicPatternLayout - /// to perform the same as PatternLayout. - /// Please see for complete documentation. - /// - /// <layout type="log4net.Layout.DynamicPatternLayout"> - /// <param name="Header" value="%newline**** Trace Opened Local: %date{yyyy-MM-dd HH:mm:ss.fff} UTC: %utcdate{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> - /// <param name="Footer" value="**** Trace Closed %date{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> - /// </layout> - /// - /// - public class DynamicPatternLayout: PatternLayout - { - #region Member Variables - /// - /// The header PatternString - /// - private PatternString m_headerPatternString = new PatternString(""); - - /// - /// The footer PatternString - /// - private PatternString m_footerPatternString = new PatternString(""); - #endregion - - #region Constructors - /// - /// Constructs a DynamicPatternLayout using the DefaultConversionPattern - /// - /// - /// - /// The default pattern just produces the application supplied message. - /// - /// - public DynamicPatternLayout() - : base() - { - } - - /// - /// Constructs a DynamicPatternLayout using the supplied conversion pattern - /// - /// the pattern to use - /// - /// - public DynamicPatternLayout (string pattern) - : base(pattern) - { - } - #endregion + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + + using log4net.Core; + using log4net.Layout.Pattern; + using log4net.Util; + + /// + /// A flexible layout configurable with pattern string that re-evaluates on each call. + /// + /// + /// This class is built on and provides all the + /// features and capabilities of PatternLayout. PatternLayout is a 'static' class + /// in that its layout is done once at configuration time. This class will recreate + /// the layout on each reference. + /// One important difference between PatternLayout and DynamicPatternLayout is the + /// treatment of the Header and Footer parameters in the configuration. The Header and Footer + /// parameters for DynamicPatternLayout must be syntactically in the form of a PatternString, + /// but should not be marked as type log4net.Util.PatternString. Doing so causes the + /// pattern to be statically converted at configuration time and causes DynamicPatternLayout + /// to perform the same as PatternLayout. + /// Please see for complete documentation. + /// + /// <layout type="log4net.Layout.DynamicPatternLayout"> + /// <param name="Header" value="%newline**** Trace Opened Local: %date{yyyy-MM-dd HH:mm:ss.fff} UTC: %utcdate{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> + /// <param name="Footer" value="**** Trace Closed %date{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> + /// </layout> + /// + /// + public class DynamicPatternLayout : PatternLayout + { + /// + /// The header PatternString. + /// + private PatternString m_headerPatternString = new PatternString(string.Empty); - #region Override implementation of LayoutSkeleton - /// - /// The header for the layout format. - /// - /// the layout header - /// - /// - /// The Header text will be appended before any logging events - /// are formatted and appended. - /// - /// The pattern will be formatted on each get operation. - /// - public override string Header - { - get - { - return m_headerPatternString.Format(); - } - set - { - base.Header = value; - m_headerPatternString = new PatternString(value); - } - } /* property DynamicPatternLayout Header */ + /// + /// The footer PatternString. + /// + private PatternString m_footerPatternString = new PatternString(string.Empty); + + /// + /// Initializes a new instance of the class. + /// Constructs a DynamicPatternLayout using the DefaultConversionPattern. + /// + /// + /// + /// The default pattern just produces the application supplied message. + /// + /// + public DynamicPatternLayout() + : base() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructs a DynamicPatternLayout using the supplied conversion pattern. + /// + /// the pattern to use. + /// + /// + public DynamicPatternLayout(string pattern) + : base(pattern) + { + } + + /// + /// Gets or sets the header for the layout format. + /// + /// the layout header. + /// + /// + /// The Header text will be appended before any logging events + /// are formatted and appended. + /// + /// The pattern will be formatted on each get operation. + /// + public override string Header + { + get + { + return this.m_headerPatternString.Format(); + } + + set + { + base.Header = value; + this.m_headerPatternString = new PatternString(value); + } + } /* property DynamicPatternLayout Header */ - /// - /// The footer for the layout format. - /// - /// the layout footer - /// - /// - /// The Footer text will be appended after all the logging events - /// have been formatted and appended. - /// - /// The pattern will be formatted on each get operation. - /// - public override string Footer - { - get - { - return m_footerPatternString.Format(); - } - set - { - base.Footer = value; - m_footerPatternString = new PatternString(value); - } - } /* property DynamicPatternLayout Footer */ - #endregion - } /* class DynamicPatternLayout */ -} /* namespace log4net.Layout */ + /// + /// Gets or sets the footer for the layout format. + /// + /// the layout footer. + /// + /// + /// The Footer text will be appended after all the logging events + /// have been formatted and appended. + /// + /// The pattern will be formatted on each get operation. + /// + public override string Footer + { + get + { + return this.m_footerPatternString.Format(); + } + + set + { + base.Footer = value; + this.m_footerPatternString = new PatternString(value); + } + } /* property DynamicPatternLayout Footer */ + } /* class DynamicPatternLayout */ +} /* namespace log4net.Layout */ diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs index 837c7d54bce..b2fcf0d61d4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs @@ -1,112 +1,98 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; -using System.Text; - -using log4net.Util; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// A Layout that renders only the Exception text from the logging event - /// - /// - /// - /// A Layout that renders only the Exception text from the logging event. - /// - /// - /// This Layout should only be used with appenders that utilize multiple - /// layouts (e.g. ). - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class ExceptionLayout : LayoutSkeleton - { - #region Constructors - - /// - /// Default constructor - /// - /// - /// - /// Constructs a ExceptionLayout - /// - /// - public ExceptionLayout() - { - this.IgnoresException = false; - } - - #endregion - - #region Implementation of IOptionHandler - - /// - /// Activate component options - /// - /// - /// - /// Part of the component activation - /// framework. - /// - /// - /// This method does nothing as options become effective immediately. - /// - /// - override public void ActivateOptions() - { - // nothing to do. - } - - #endregion - - #region Override implementation of LayoutSkeleton - - /// - /// Gets the exception text from the logging event - /// - /// The TextWriter to write the formatted event to - /// the event being logged - /// - /// - /// Write the exception string to the . - /// The exception string is retrieved from . - /// - /// - override public void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - writer.Write(loggingEvent.GetExceptionString()); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.Util; + + /// + /// A Layout that renders only the Exception text from the logging event. + /// + /// + /// + /// A Layout that renders only the Exception text from the logging event. + /// + /// + /// This Layout should only be used with appenders that utilize multiple + /// layouts (e.g. ). + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class ExceptionLayout : LayoutSkeleton + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Constructs a ExceptionLayout. + /// + /// + public ExceptionLayout() + { + this.IgnoresException = false; + } + + /// + /// Activate component options. + /// + /// + /// + /// Part of the component activation + /// framework. + /// + /// + /// This method does nothing as options become effective immediately. + /// + /// + public override void ActivateOptions() + { + // nothing to do. + } + + /// + /// Gets the exception text from the logging event. + /// + /// The TextWriter to write the formatted event to. + /// the event being logged. + /// + /// + /// Write the exception string to the . + /// The exception string is retrieved from . + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - #endregion - } + writer.Write(loggingEvent.GetExceptionString()); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs index 643040bc86c..7e0a8af4bdb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs @@ -1,125 +1,122 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Interface implemented by layout objects - /// - /// - /// - /// An object is used to format a - /// as text. The method is called by an - /// appender to transform the into a string. - /// - /// - /// The layout can also supply and - /// text that is appender before any events and after all the events respectively. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface ILayout - { - /// - /// Implement this method to create your own layout format. - /// - /// The TextWriter to write the formatted event to - /// The event to format - /// - /// - /// This method is called by an appender to format - /// the as text and output to a writer. - /// - /// - /// If the caller does not have a and prefers the - /// event to be formatted as a then the following - /// code can be used to format the event into a . - /// - /// - /// StringWriter writer = new StringWriter(); - /// Layout.Format(writer, loggingEvent); - /// string formattedEvent = writer.ToString(); - /// - /// - void Format(TextWriter writer, LoggingEvent loggingEvent); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net; + using log4net.Core; + + /// + /// Interface implemented by layout objects. + /// + /// + /// + /// An object is used to format a + /// as text. The method is called by an + /// appender to transform the into a string. + /// + /// + /// The layout can also supply and + /// text that is appender before any events and after all the events respectively. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface ILayout + { + /// + /// Implement this method to create your own layout format. + /// + /// The TextWriter to write the formatted event to. + /// The event to format. + /// + /// + /// This method is called by an appender to format + /// the as text and output to a writer. + /// + /// + /// If the caller does not have a and prefers the + /// event to be formatted as a then the following + /// code can be used to format the event into a . + /// + /// + /// StringWriter writer = new StringWriter(); + /// Layout.Format(writer, loggingEvent); + /// string formattedEvent = writer.ToString(); + /// + /// + void Format(TextWriter writer, LoggingEvent loggingEvent); - /// - /// The content type output by this layout. - /// - /// The content type - /// - /// - /// The content type output by this layout. - /// - /// - /// This is a MIME type e.g. "text/plain". - /// - /// - string ContentType { get; } + /// + /// Gets the content type output by this layout. + /// + /// The content type. + /// + /// + /// The content type output by this layout. + /// + /// + /// This is a MIME type e.g. "text/plain". + /// + /// + string ContentType { get; } - /// - /// The header for the layout format. - /// - /// the layout header - /// - /// - /// The Header text will be appended before any logging events - /// are formatted and appended. - /// - /// - string Header { get; } + /// + /// Gets the header for the layout format. + /// + /// the layout header. + /// + /// + /// The Header text will be appended before any logging events + /// are formatted and appended. + /// + /// + string Header { get; } - /// - /// The footer for the layout format. - /// - /// the layout footer - /// - /// - /// The Footer text will be appended after all the logging events - /// have been formatted and appended. - /// - /// - string Footer { get; } + /// + /// Gets the footer for the layout format. + /// + /// the layout footer. + /// + /// + /// The Footer text will be appended after all the logging events + /// have been formatted and appended. + /// + /// + string Footer { get; } - /// - /// Flag indicating if this layout handle exceptions - /// - /// false if this layout handles exceptions - /// - /// - /// If this layout handles the exception object contained within - /// , then the layout should return - /// false. Otherwise, if the layout ignores the exception - /// object, then the layout should return true. - /// - /// - bool IgnoresException { get; } - } + /// + /// Gets a value indicating whether flag indicating if this layout handle exceptions. + /// + /// false if this layout handles exceptions. + /// + /// + /// If this layout handles the exception object contained within + /// , then the layout should return + /// false. Otherwise, if the layout ignores the exception + /// object, then the layout should return true. + /// + /// + bool IgnoresException { get; } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs index 8d03fc94c49..6108b51b31f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs @@ -1,65 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net; -using log4net.Core; -using log4net.Util.TypeConverters; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Interface for raw layout objects - /// - /// - /// - /// Interface used to format a - /// to an object. - /// - /// - /// This interface should not be confused with the - /// interface. This interface is used in - /// only certain specialized situations where a raw object is - /// required rather than a formatted string. The - /// is not generally useful than this interface. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [TypeConverter(typeof(RawLayoutConverter))] - public interface IRawLayout - { - /// - /// Implement this method to create your own layout format. - /// - /// The event to format - /// returns the formatted event - /// - /// - /// Implement this method to create your own layout format. - /// - /// - object Format(LoggingEvent loggingEvent); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net; + using log4net.Core; + using log4net.Util.TypeConverters; + + /// + /// Interface for raw layout objects. + /// + /// + /// + /// Interface used to format a + /// to an object. + /// + /// + /// This interface should not be confused with the + /// interface. This interface is used in + /// only certain specialized situations where a raw object is + /// required rather than a formatted string. The + /// is not generally useful than this interface. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [TypeConverter(typeof(RawLayoutConverter))] + public interface IRawLayout + { + /// + /// Implement this method to create your own layout format. + /// + /// The event to format. + /// returns the formatted event. + /// + /// + /// Implement this method to create your own layout format. + /// + /// + object Format(LoggingEvent loggingEvent); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs index f988304058c..4cd73055f51 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs @@ -1,97 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Adapts any to a - /// - /// - /// - /// Where an is required this adapter - /// allows a to be specified. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class Layout2RawLayoutAdapter : IRawLayout - { - #region Member Variables - - /// - /// The layout to adapt - /// - private ILayout m_layout; - - #endregion - - #region Constructors - - /// - /// Construct a new adapter - /// - /// the layout to adapt - /// - /// - /// Create the adapter for the specified . - /// - /// - public Layout2RawLayoutAdapter(ILayout layout) - { - m_layout = layout; - } - - #endregion - - #region Implementation of IRawLayout - - /// - /// Format the logging event as an object. - /// - /// The event to format - /// returns the formatted event - /// - /// - /// Format the logging event as an object. - /// - /// - /// Uses the object supplied to - /// the constructor to perform the formatting. - /// - /// - virtual public object Format(LoggingEvent loggingEvent) - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - m_layout.Format(writer, loggingEvent); - return writer.ToString(); - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net; + using log4net.Core; + + /// + /// Adapts any to a . + /// + /// + /// + /// Where an is required this adapter + /// allows a to be specified. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class Layout2RawLayoutAdapter : IRawLayout + { + /// + /// The layout to adapt. + /// + private ILayout m_layout; + + /// + /// Initializes a new instance of the class. + /// Construct a new adapter. + /// + /// the layout to adapt. + /// + /// + /// Create the adapter for the specified . + /// + /// + public Layout2RawLayoutAdapter(ILayout layout) + { + this.m_layout = layout; + } + + /// + /// Format the logging event as an object. + /// + /// The event to format. + /// returns the formatted event. + /// + /// + /// Format the logging event as an object. + /// + /// + /// Uses the object supplied to + /// the constructor to perform the formatting. + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + this.m_layout.Format(writer, loggingEvent); + return writer.ToString(); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs index 7a6cf18f639..0760b6e3567 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs @@ -1,148 +1,132 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Extend this abstract class to create your own log layout format. - /// - /// - /// - /// This is the base implementation of the - /// interface. Most layout objects should extend this class. - /// - /// - /// - /// - /// - /// Subclasses must implement the - /// method. - /// - /// - /// Subclasses should set the in their default - /// constructor. - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - public abstract class LayoutSkeleton : ILayout, IOptionHandler - { - #region Member Variables - - /// - /// The header text - /// - /// - /// - /// See for more information. - /// - /// - private string m_header = null; - - /// - /// The footer text - /// - /// - /// - /// See for more information. - /// - /// - private string m_footer = null; - - /// - /// Flag indicating if this layout handles exceptions - /// - /// - /// - /// false if this layout handles exceptions - /// - /// - private bool m_ignoresException = true; - - #endregion - - #region Constructors - - /// - /// Empty default constructor - /// - /// - /// - /// Empty default constructor - /// - /// - protected LayoutSkeleton() - { - } - - #endregion - - #region Implementation of IOptionHandler - - /// - /// Activate component options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// This method must be implemented by the subclass. - /// - /// - abstract public void ActivateOptions(); - - #endregion + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net; + using log4net.Core; + + /// + /// Extend this abstract class to create your own log layout format. + /// + /// + /// + /// This is the base implementation of the + /// interface. Most layout objects should extend this class. + /// + /// + /// + /// + /// + /// Subclasses must implement the + /// method. + /// + /// + /// Subclasses should set the in their default + /// constructor. + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class LayoutSkeleton : ILayout, IOptionHandler + { + /// + /// The header text. + /// + /// + /// + /// See for more information. + /// + /// + private string m_header = null; - #region Implementation of ILayout + /// + /// The footer text. + /// + /// + /// + /// See for more information. + /// + /// + private string m_footer = null; - /// - /// Implement this method to create your own layout format. - /// - /// The TextWriter to write the formatted event to - /// The event to format - /// - /// - /// This method is called by an appender to format - /// the as text. - /// - /// - abstract public void Format(TextWriter writer, LoggingEvent loggingEvent); + /// + /// Flag indicating if this layout handles exceptions. + /// + /// + /// + /// false if this layout handles exceptions. + /// + /// + private bool m_ignoresException = true; + + /// + /// Initializes a new instance of the class. + /// Empty default constructor. + /// + /// + /// + /// Empty default constructor. + /// + /// + protected LayoutSkeleton() + { + } + + /// + /// Activate component options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// This method must be implemented by the subclass. + /// + /// + public abstract void ActivateOptions(); + + /// + /// Implement this method to create your own layout format. + /// + /// The TextWriter to write the formatted event to. + /// The event to format. + /// + /// + /// This method is called by an appender to format + /// the as text. + /// + /// + public abstract void Format(TextWriter writer, LoggingEvent loggingEvent); /// /// Convenience method for easily formatting the logging event into a string variable. @@ -150,87 +134,86 @@ protected LayoutSkeleton() /// /// /// Creates a new StringWriter instance to store the formatted logging event. - /// + /// + /// public string Format(LoggingEvent loggingEvent) { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - Format(writer, loggingEvent); + this.Format(writer, loggingEvent); return writer.ToString(); } - /// - /// The content type output by this layout. - /// - /// The content type is "text/plain" - /// - /// - /// The content type output by this layout. - /// - /// - /// This base class uses the value "text/plain". - /// To change this value a subclass must override this - /// property. - /// - /// - virtual public string ContentType - { - get { return "text/plain"; } - } - - /// - /// The header for the layout format. - /// - /// the layout header - /// - /// - /// The Header text will be appended before any logging events - /// are formatted and appended. - /// - /// - virtual public string Header - { - get { return m_header; } - set { m_header = value; } - } + /// + /// Gets the content type output by this layout. + /// + /// The content type is "text/plain". + /// + /// + /// The content type output by this layout. + /// + /// + /// This base class uses the value "text/plain". + /// To change this value a subclass must override this + /// property. + /// + /// + public virtual string ContentType + { + get { return "text/plain"; } + } - /// - /// The footer for the layout format. - /// - /// the layout footer - /// - /// - /// The Footer text will be appended after all the logging events - /// have been formatted and appended. - /// - /// - virtual public string Footer - { - get { return m_footer; } - set { m_footer = value; } - } + /// + /// Gets or sets the header for the layout format. + /// + /// the layout header. + /// + /// + /// The Header text will be appended before any logging events + /// are formatted and appended. + /// + /// + public virtual string Header + { + get { return this.m_header; } + set { this.m_header = value; } + } - /// - /// Flag indicating if this layout handles exceptions - /// - /// false if this layout handles exceptions - /// - /// - /// If this layout handles the exception object contained within - /// , then the layout should return - /// false. Otherwise, if the layout ignores the exception - /// object, then the layout should return true. - /// - /// - /// Set this value to override a this default setting. The default - /// value is true, this layout does not handle the exception. - /// - /// - virtual public bool IgnoresException - { - get { return m_ignoresException; } - set { m_ignoresException = value; } - } + /// + /// Gets or sets the footer for the layout format. + /// + /// the layout footer. + /// + /// + /// The Footer text will be appended after all the logging events + /// have been formatted and appended. + /// + /// + public virtual string Footer + { + get { return this.m_footer; } + set { this.m_footer = value; } + } - #endregion - } + /// + /// Gets or sets a value indicating whether flag indicating if this layout handles exceptions. + /// + /// false if this layout handles exceptions. + /// + /// + /// If this layout handles the exception object contained within + /// , then the layout should return + /// false. Otherwise, if the layout ignores the exception + /// object, then the layout should return true. + /// + /// + /// Set this value to override a this default setting. The default + /// value is true, this layout does not handle the exception. + /// + /// + public virtual bool IgnoresException + { + get { return this.m_ignoresException; } + set { this.m_ignoresException = value; } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs index 42fb815e9fb..409e8404b41 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs @@ -1,59 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Write the event appdomain name to the output - /// - /// - /// - /// Writes the to the output writer. - /// - /// - /// Daniel Cazzulino - /// Nicko Cadell - internal sealed class AppDomainPatternConverter : PatternLayoutConverter - { - /// - /// Write the event appdomain name to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the to the output . - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.Domain); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Write the event appdomain name to the output. + /// + /// + /// + /// Writes the to the output writer. + /// + /// + /// Daniel Cazzulino. + /// Nicko Cadell. + internal sealed class AppDomainPatternConverter : PatternLayoutConverter + { + /// + /// Write the event appdomain name to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the to the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.Domain); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs index b0fd0499ecf..9db599177e1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET @@ -27,55 +25,56 @@ using System.IO; using System.Web; + using log4net.Core; using log4net.Util; namespace log4net.Layout.Pattern { - /// - /// Converter for items in the ASP.Net Cache. - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski - internal sealed class AspNetCachePatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net Cache item to the output - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. If no property has been set, all key value pairs from the Cache will - /// be written to the output. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - if (HttpRuntime.Cache != null) - { - if (Option != null) - { - WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache[Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache.GetEnumerator()); - } - } - else - { - writer.Write(SystemInfo.NotAvailableText); - } - } - } + /// + /// Converter for items in the ASP.Net Cache. + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski. + internal sealed class AspNetCachePatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net Cache item to the output. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. If no property has been set, all key value pairs from the Cache will + /// be written to the output. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + if (HttpRuntime.Cache != null) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache.GetEnumerator()); + } + } + else + { + writer.Write(SystemInfo.NotAvailableText); + } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs index a1db90a1b68..dcfc9761bdb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET @@ -27,46 +25,47 @@ using System.IO; using System.Web; + using log4net.Core; namespace log4net.Layout.Pattern { - /// - /// Converter for items in the . - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski - internal sealed class AspNetContextPatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net HttpContext item to the output - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - if (Option != null) - { - WriteObject(writer, loggingEvent.Repository, httpContext.Items[Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, httpContext.Items); - } - } - } + /// + /// Converter for items in the . + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski. + internal sealed class AspNetContextPatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net HttpContext item to the output. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, httpContext.Items[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, httpContext.Items); + } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs index cd6dacfcae0..c25bf8a0c10 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET @@ -27,43 +25,44 @@ using System.IO; using System.Web; + using log4net.Core; using log4net.Util; namespace log4net.Layout.Pattern { - /// - /// Abstract class that provides access to the current HttpContext () that - /// derived classes need. - /// - /// - /// This class handles the case when HttpContext.Current is null by writing - /// to the writer. - /// - /// Ron Grabowski - internal abstract class AspNetPatternLayoutConverter : PatternLayoutConverter - { - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - if (HttpContext.Current == null) - { - writer.Write(SystemInfo.NotAvailableText); - } - else - { - Convert(writer, loggingEvent, HttpContext.Current); - } - } + /// + /// Abstract class that provides access to the current HttpContext () that + /// derived classes need. + /// + /// + /// This class handles the case when HttpContext.Current is null by writing + /// to the writer. + /// + /// Ron Grabowski. + internal abstract class AspNetPatternLayoutConverter : PatternLayoutConverter + { + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + if (HttpContext.Current == null) + { + writer.Write(SystemInfo.NotAvailableText); + } + else + { + this.Convert(writer, loggingEvent, HttpContext.Current); + } + } - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the correct way. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - protected abstract void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext); - } + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the correct way. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + protected abstract void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext); + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs index 966fb2ee5f3..47e9e445d1b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET @@ -27,64 +25,68 @@ using System.IO; using System.Web; + using log4net.Core; using log4net.Util; namespace log4net.Layout.Pattern { - /// - /// Converter for items in the ASP.Net Cache. - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski - internal sealed class AspNetRequestPatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net Cache item to the output - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - HttpRequest request = null; - try { - request = httpContext.Request; - } catch (HttpException) { - // likely a case of running in IIS integrated mode - // when inside an Application_Start event. - // treat it like a case of the Request - // property returning null - } + /// + /// Converter for items in the ASP.Net Cache. + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski. + internal sealed class AspNetRequestPatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net Cache item to the output. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + HttpRequest request = null; + try + { + request = httpContext.Request; + } + catch (HttpException) + { + // likely a case of running in IIS integrated mode + // when inside an Application_Start event. + // treat it like a case of the Request + // property returning null + } - if (request != null) - { - if (Option != null) - { - WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params[Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params); - } - } - else - { - writer.Write(SystemInfo.NotAvailableText); - } - } - } + if (request != null) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params); + } + } + else + { + writer.Write(SystemInfo.NotAvailableText); + } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs index 820b330d56e..fee7e38a709 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET @@ -27,55 +25,56 @@ using System.IO; using System.Web; + using log4net.Core; using log4net.Util; namespace log4net.Layout.Pattern { - /// - /// Converter for items in the ASP.Net Cache. - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski - internal sealed class AspNetSessionPatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net Cache item to the output - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. If no property has been set, all key value pairs from the Session will - /// be written to the output. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - if (httpContext.Session != null) - { - if (Option != null) - { - WriteObject(writer, loggingEvent.Repository, httpContext.Session.Contents[Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, httpContext.Session); - } - } - else - { - writer.Write(SystemInfo.NotAvailableText); - } - } - } + /// + /// Converter for items in the ASP.Net Cache. + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski. + internal sealed class AspNetSessionPatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net Cache item to the output. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. If no property has been set, all key value pairs from the Session will + /// be written to the output. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + if (httpContext.Session != null) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, httpContext.Session.Contents[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, httpContext.Session); + } + } + else + { + writer.Write(SystemInfo.NotAvailableText); + } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs index 21d58d45823..96de18914cb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs @@ -1,193 +1,182 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net.Core; -using log4net.Util; -using log4net.DateFormatter; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Date pattern converter, uses a to format - /// the date of a . - /// - /// - /// - /// Render the to the writer as a string. - /// - /// - /// The value of the determines - /// the formatting of the date. The following values are allowed: - /// - /// - /// Option value - /// Output - /// - /// - /// ISO8601 - /// - /// Uses the formatter. - /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. - /// - /// - /// - /// DATE - /// - /// Uses the formatter. - /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". - /// - /// - /// - /// ABSOLUTE - /// - /// Uses the formatter. - /// Formats using the "HH:mm:ss,yyyy" for example, "15:49:37,459". - /// - /// - /// - /// other - /// - /// Any other pattern string uses the formatter. - /// This formatter passes the pattern string to the - /// method. - /// For details on valid patterns see - /// DateTimeFormatInfo Class. - /// - /// - /// - /// - /// - /// The is in the local time zone and is rendered in that zone. - /// To output the time in Universal time see . - /// - /// - /// Nicko Cadell - internal class DatePatternConverter : PatternLayoutConverter, IOptionHandler - { - /// - /// The used to render the date to a string - /// - /// - /// - /// The used to render the date to a string - /// - /// - protected IDateFormatter m_dateFormatter; - - #region Implementation of IOptionHandler - - /// - /// Initialize the converter pattern based on the property. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - string dateFormatStr = Option; - if (dateFormatStr == null) - { - dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; - } - - if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) - { - m_dateFormatter = new Iso8601DateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) - { - m_dateFormatter = new AbsoluteTimeDateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) - { - m_dateFormatter = new DateTimeDateFormatter(); - } - else - { - try - { - m_dateFormatter = new SimpleDateFormatter(dateFormatStr); - } - catch (Exception e) - { - LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with ["+dateFormatStr+"]", e); - m_dateFormatter = new Iso8601DateFormatter(); - } - } - } - - #endregion - - /// - /// Convert the pattern into the rendered message - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Pass the to the - /// for it to render it to the writer. - /// - /// - /// The passed is in the local time zone. - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - try - { - m_dateFormatter.FormatDate(loggingEvent.TimeStamp, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } - } - - #region Private Static Fields - - /// - /// The fully qualified type of the DatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(DatePatternConverter); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net.Core; + using log4net.DateFormatter; + using log4net.Util; + + /// + /// Date pattern converter, uses a to format + /// the date of a . + /// + /// + /// + /// Render the to the writer as a string. + /// + /// + /// The value of the determines + /// the formatting of the date. The following values are allowed: + /// + /// + /// Option value + /// Output + /// + /// + /// ISO8601 + /// + /// Uses the formatter. + /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. + /// + /// + /// + /// DATE + /// + /// Uses the formatter. + /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". + /// + /// + /// + /// ABSOLUTE + /// + /// Uses the formatter. + /// Formats using the "HH:mm:ss,yyyy" for example, "15:49:37,459". + /// + /// + /// + /// other + /// + /// Any other pattern string uses the formatter. + /// This formatter passes the pattern string to the + /// method. + /// For details on valid patterns see + /// DateTimeFormatInfo Class. + /// + /// + /// + /// + /// + /// The is in the local time zone and is rendered in that zone. + /// To output the time in Universal time see . + /// + /// + /// Nicko Cadell. + internal class DatePatternConverter : PatternLayoutConverter, IOptionHandler + { + /// + /// The used to render the date to a string. + /// + /// + /// + /// The used to render the date to a string. + /// + /// + protected IDateFormatter m_dateFormatter; + + /// + /// Initialize the converter pattern based on the property. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + string dateFormatStr = this.Option; + if (dateFormatStr == null) + { + dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; + } - #endregion Private Static Fields - } + if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) + { + this.m_dateFormatter = new Iso8601DateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) + { + this.m_dateFormatter = new AbsoluteTimeDateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) + { + this.m_dateFormatter = new DateTimeDateFormatter(); + } + else + { + try + { + this.m_dateFormatter = new SimpleDateFormatter(dateFormatStr); + } + catch (Exception e) + { + LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with [" + dateFormatStr + "]", e); + this.m_dateFormatter = new Iso8601DateFormatter(); + } + } + } + + /// + /// Convert the pattern into the rendered message. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Pass the to the + /// for it to render it to the writer. + /// + /// + /// The passed is in the local time zone. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + try + { + this.m_dateFormatter.FormatDate(loggingEvent.TimeStamp, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } + } + + /// + /// The fully qualified type of the DatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(DatePatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs index 68188792b83..c8b5ea1cbaa 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs @@ -1,141 +1,140 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System.Diagnostics; -using System.IO; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Write the exception text to the output - /// - /// - /// - /// If an exception object is stored in the logging event - /// it will be rendered into the pattern output with a - /// trailing newline. - /// - /// - /// If there is no exception then nothing will be output - /// and no trailing newline will be appended. - /// It is typical to put a newline before the exception - /// and to have the exception as the last data in the pattern. - /// - /// - /// Nicko Cadell - internal sealed class ExceptionPatternConverter : PatternLayoutConverter - { - /// - /// Default constructor - /// - public ExceptionPatternConverter() - { - // This converter handles the exception - IgnoresException = false; - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System.Diagnostics; + using System.IO; + + using log4net.Core; + + /// + /// Write the exception text to the output. + /// + /// + /// + /// If an exception object is stored in the logging event + /// it will be rendered into the pattern output with a + /// trailing newline. + /// + /// + /// If there is no exception then nothing will be output + /// and no trailing newline will be appended. + /// It is typical to put a newline before the exception + /// and to have the exception as the last data in the pattern. + /// + /// + /// Nicko Cadell. + internal sealed class ExceptionPatternConverter : PatternLayoutConverter + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public ExceptionPatternConverter() + { + // This converter handles the exception + this.IgnoresException = false; + } - /// - /// Write the exception text to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// If an exception object is stored in the logging event - /// it will be rendered into the pattern output with a - /// trailing newline. - /// - /// - /// If there is no exception or the exception property specified - /// by the Option value does not exist then nothing will be output - /// and no trailing newline will be appended. - /// It is typical to put a newline before the exception - /// and to have the exception as the last data in the pattern. - /// - /// - /// Recognized values for the Option parameter are: - /// - /// - /// - /// Message - /// - /// - /// Source - /// - /// - /// StackTrace - /// - /// - /// TargetSite - /// - /// - /// HelpLink - /// - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent.ExceptionObject != null && Option != null && Option.Length > 0) - { - switch (Option.ToLower()) - { - case "message": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Message); - break; -#if !NETCF - case "source": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Source); - break; - case "stacktrace": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.StackTrace); - break; + /// + /// Write the exception text to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// If an exception object is stored in the logging event + /// it will be rendered into the pattern output with a + /// trailing newline. + /// + /// + /// If there is no exception or the exception property specified + /// by the Option value does not exist then nothing will be output + /// and no trailing newline will be appended. + /// It is typical to put a newline before the exception + /// and to have the exception as the last data in the pattern. + /// + /// + /// Recognized values for the Option parameter are: + /// + /// + /// + /// Message + /// + /// + /// Source + /// + /// + /// StackTrace + /// + /// + /// TargetSite + /// + /// + /// HelpLink + /// + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent.ExceptionObject != null && this.Option != null && this.Option.Length > 0) + { + switch (this.Option.ToLower()) + { + case "message": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Message); + break; +#if !NETCF + case "source": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Source); + break; + case "stacktrace": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.StackTrace); + break; #if !NETSTANDARD1_3 - case "targetsite": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.TargetSite); - break; + case "targetsite": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.TargetSite); + break; +#endif + case "helplink": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.HelpLink); + break; #endif - case "helplink": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.HelpLink); - break; -#endif - default: - // do not output SystemInfo.NotAvailableText - break; - } - } - else - { - string exceptionString = loggingEvent.GetExceptionString(); - if (exceptionString != null && exceptionString.Length > 0) - { - writer.WriteLine(exceptionString); - } - else - { - // do not output SystemInfo.NotAvailableText - } - } - } - } + default: + // do not output SystemInfo.NotAvailableText + break; + } + } + else + { + string exceptionString = loggingEvent.GetExceptionString(); + if (exceptionString != null && exceptionString.Length > 0) + { + writer.WriteLine(exceptionString); + } + else + { + // do not output SystemInfo.NotAvailableText + } + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs index 4a2ef1e729a..894610563d8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs @@ -1,60 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Writes the caller location file name to the output - /// - /// - /// - /// Writes the value of the for - /// the event to the output writer. - /// - /// - /// Nicko Cadell - internal sealed class FileLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the caller location file name to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the value of the for - /// the to the output . - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.LocationInformation.FileName); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Writes the caller location file name to the output. + /// + /// + /// + /// Writes the value of the for + /// the event to the output writer. + /// + /// + /// Nicko Cadell. + internal sealed class FileLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the caller location file name to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the value of the for + /// the to the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.FileName); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs index c2eba0130fb..fa487fbff1b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs @@ -1,58 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Write the caller location info to the output - /// - /// - /// - /// Writes the to the output writer. - /// - /// - /// Nicko Cadell - internal sealed class FullLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the caller location info to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the to the output writer. - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write( loggingEvent.LocationInformation.FullInfo ); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Write the caller location info to the output. + /// + /// + /// + /// Writes the to the output writer. + /// + /// + /// Nicko Cadell. + internal sealed class FullLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the caller location info to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the to the output writer. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.FullInfo); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs index a0797b1c203..9f316651005 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs @@ -1,62 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Writes the event identity to the output - /// - /// - /// - /// Writes the value of the to - /// the output writer. - /// - /// - /// Daniel Cazzulino - /// Nicko Cadell - internal sealed class IdentityPatternConverter : PatternLayoutConverter - { - /// - /// Writes the event identity to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the value of the - /// to - /// the output . - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.Identity); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Writes the event identity to the output. + /// + /// + /// + /// Writes the value of the to + /// the output writer. + /// + /// + /// Daniel Cazzulino. + /// Nicko Cadell. + internal sealed class IdentityPatternConverter : PatternLayoutConverter + { + /// + /// Writes the event identity to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the value of the + /// to + /// the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.Identity); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs index 7474a09ca98..b7b2d95654d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs @@ -1,60 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Write the event level to the output - /// - /// - /// - /// Writes the display name of the event - /// to the writer. - /// - /// - /// Nicko Cadell - internal sealed class LevelPatternConverter : PatternLayoutConverter - { - /// - /// Write the event level to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the of the - /// to the . - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write( loggingEvent.Level.DisplayName ); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Write the event level to the output. + /// + /// + /// + /// Writes the display name of the event + /// to the writer. + /// + /// + /// Nicko Cadell. + internal sealed class LevelPatternConverter : PatternLayoutConverter + { + /// + /// Write the event level to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the of the + /// to the . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.Level.DisplayName); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs index 019a62c47a5..d7d24fda223 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs @@ -1,60 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Write the caller location line number to the output - /// - /// - /// - /// Writes the value of the for - /// the event to the output writer. - /// - /// - /// Nicko Cadell - internal sealed class LineLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the caller location line number to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the value of the for - /// the to the output . - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.LocationInformation.LineNumber); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Write the caller location line number to the output. + /// + /// + /// + /// Writes the value of the for + /// the event to the output writer. + /// + /// + /// Nicko Cadell. + internal sealed class LineLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the caller location line number to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the value of the for + /// the to the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.LineNumber); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs index e54e527f168..311b5150c26 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs @@ -1,58 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Converter for logger name - /// - /// - /// - /// Outputs the of the event. - /// - /// - /// Nicko Cadell - internal sealed class LoggerPatternConverter : NamedPatternConverter - { - /// - /// Gets the fully qualified name of the logger - /// - /// the event being logged - /// The fully qualified logger name - /// - /// - /// Returns the of the . - /// - /// - override protected string GetFullyQualifiedName(LoggingEvent loggingEvent) - { - return loggingEvent.LoggerName; - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Converter for logger name. + /// + /// + /// + /// Outputs the of the event. + /// + /// + /// Nicko Cadell. + internal sealed class LoggerPatternConverter : NamedPatternConverter + { + /// + /// Gets the fully qualified name of the logger. + /// + /// the event being logged. + /// The fully qualified logger name. + /// + /// + /// Returns the of the . + /// + /// + protected override string GetFullyQualifiedName(LoggingEvent loggingEvent) + { + return loggingEvent.LoggerName; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs index a13bdcf9e13..79e70453b33 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs @@ -1,60 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Writes the event message to the output - /// - /// - /// - /// Uses the method - /// to write out the event message. - /// - /// - /// Nicko Cadell - internal sealed class MessagePatternConverter : PatternLayoutConverter - { - /// - /// Writes the event message to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Uses the method - /// to write out the event message. - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - loggingEvent.WriteRenderedMessage(writer); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Writes the event message to the output. + /// + /// + /// + /// Uses the method + /// to write out the event message. + /// + /// + /// Nicko Cadell. + internal sealed class MessagePatternConverter : PatternLayoutConverter + { + /// + /// Writes the event message to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Uses the method + /// to write out the event message. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + loggingEvent.WriteRenderedMessage(writer); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs index e3116248f8a..8e3ffa64e3f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs @@ -1,60 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Write the method name to the output - /// - /// - /// - /// Writes the caller location to - /// the output. - /// - /// - /// Nicko Cadell - internal sealed class MethodLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the method name to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the caller location to - /// the output. - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.LocationInformation.MethodName); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Write the method name to the output. + /// + /// + /// + /// Writes the caller location to + /// the output. + /// + /// + /// Nicko Cadell. + internal sealed class MethodLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the method name to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the caller location to + /// the output. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.MethodName); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs index 322f3694588..c3119090971 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs @@ -1,139 +1,132 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Globalization; -using System.Text; -using System.IO; - -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Converter to output and truncate '.' separated strings - /// - /// - /// - /// This abstract class supports truncating a '.' separated string - /// to show a specified number of elements from the right hand side. - /// This is used to truncate class names that are fully qualified. - /// - /// - /// Subclasses should override the method to - /// return the fully qualified string. - /// - /// - /// Nicko Cadell - public abstract class NamedPatternConverter : PatternLayoutConverter, IOptionHandler - { - private int m_precision = 0; - - #region Implementation of IOptionHandler - - /// - /// Initialize the converter - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - m_precision = 0; - - if (Option != null) - { - string optStr = Option.Trim(); - if (optStr.Length > 0) - { - int precisionVal; - if (SystemInfo.TryParse(optStr, out precisionVal)) - { - if (precisionVal <= 0) - { - LogLog.Error(declaringType, "NamedPatternConverter: Precision option (" + optStr + ") isn't a positive integer."); - } - else - { - m_precision = precisionVal; - } - } - else - { - LogLog.Error(declaringType, "NamedPatternConverter: Precision option \"" + optStr + "\" not a decimal integer."); - } - } - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.Util; + + /// + /// Converter to output and truncate '.' separated strings. + /// + /// + /// + /// This abstract class supports truncating a '.' separated string + /// to show a specified number of elements from the right hand side. + /// This is used to truncate class names that are fully qualified. + /// + /// + /// Subclasses should override the method to + /// return the fully qualified string. + /// + /// + /// Nicko Cadell. + public abstract class NamedPatternConverter : PatternLayoutConverter, IOptionHandler + { + private int m_precision = 0; + + /// + /// Initialize the converter. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + this.m_precision = 0; - #endregion + if (this.Option != null) + { + string optStr = this.Option.Trim(); + if (optStr.Length > 0) + { + int precisionVal; + if (SystemInfo.TryParse(optStr, out precisionVal)) + { + if (precisionVal <= 0) + { + LogLog.Error(declaringType, "NamedPatternConverter: Precision option (" + optStr + ") isn't a positive integer."); + } + else + { + this.m_precision = precisionVal; + } + } + else + { + LogLog.Error(declaringType, "NamedPatternConverter: Precision option \"" + optStr + "\" not a decimal integer."); + } + } + } + } + + /// + /// Get the fully qualified string data. + /// + /// the event being logged. + /// the fully qualified name. + /// + /// + /// Overridden by subclasses to get the fully qualified name before the + /// precision is applied to it. + /// + /// + /// Return the fully qualified '.' (dot/period) separated string. + /// + /// + protected abstract string GetFullyQualifiedName(LoggingEvent loggingEvent); - /// - /// Get the fully qualified string data - /// - /// the event being logged - /// the fully qualified name - /// - /// - /// Overridden by subclasses to get the fully qualified name before the - /// precision is applied to it. - /// - /// - /// Return the fully qualified '.' (dot/period) separated string. - /// - /// - abstract protected string GetFullyQualifiedName(LoggingEvent loggingEvent); - - /// - /// Convert the pattern to the rendered message - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// Render the to the precision - /// specified by the property. - /// - sealed override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - string name = GetFullyQualifiedName(loggingEvent); - if (m_precision <= 0 || name == null || name.Length < 2) - { - writer.Write(name); - } - else - { - int len = name.Length; + /// + /// Convert the pattern to the rendered message. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// Render the to the precision + /// specified by the property. + /// + protected sealed override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + string name = this.GetFullyQualifiedName(loggingEvent); + if (this.m_precision <= 0 || name == null || name.Length < 2) + { + writer.Write(name); + } + else + { + int len = name.Length; string trailingDot = string.Empty; if (name.EndsWith(DOT)) { @@ -143,10 +136,11 @@ sealed override protected void Convert(TextWriter writer, LoggingEvent loggingEv } int end = name.LastIndexOf(DOT); - for(int i = 1; end > 0 && i < m_precision; i++) - { + for (int i = 1; end > 0 && i < this.m_precision; i++) + { end = name.LastIndexOf('.', end - 1); } + if (end == -1) { writer.Write(name + trailingDot); @@ -155,21 +149,18 @@ sealed override protected void Convert(TextWriter writer, LoggingEvent loggingEv { writer.Write(name.Substring(end + 1, len - end - 1) + trailingDot); } - } - } - - #region Private Static Fields - - /// - /// The fully qualified type of the NamedPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(NamedPatternConverter); + } + } + + /// + /// The fully qualified type of the NamedPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(NamedPatternConverter); - private const string DOT = "."; - #endregion Private Static Fields - } + private const string DOT = "."; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs index 5e46c4b6c0d..ca7dbb01461 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs @@ -1,66 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Converter to include event NDC - /// - /// - /// - /// Outputs the value of the event property named NDC. - /// - /// - /// The should be used instead. - /// - /// - /// Nicko Cadell - internal sealed class NdcPatternConverter : PatternLayoutConverter - { - /// - /// Write the event NDC to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// As the thread context stacks are now stored in named event properties - /// this converter simply looks up the value of the NDC property. - /// - /// - /// The should be used instead. - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - // Write the value for the specified key - WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty("NDC")); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Converter to include event NDC. + /// + /// + /// + /// Outputs the value of the event property named NDC. + /// + /// + /// The should be used instead. + /// + /// + /// Nicko Cadell. + internal sealed class NdcPatternConverter : PatternLayoutConverter + { + /// + /// Write the event NDC to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// As the thread context stacks are now stored in named event properties + /// this converter simply looks up the value of the NDC property. + /// + /// + /// The should be used instead. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + // Write the value for the specified key + WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty("NDC")); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs index a4cdbe1e455..71abd6f5f37 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs @@ -1,127 +1,108 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; -using System.Collections; - -using log4net.Core; -using log4net.Util; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Abstract class that provides the formatting functionality that - /// derived classes need. - /// - /// - /// Conversion specifiers in a conversion patterns are parsed to - /// individual PatternConverters. Each of which is responsible for - /// converting a logging event in a converter specific manner. - /// - /// Nicko Cadell - public abstract class PatternLayoutConverter : PatternConverter - { - #region Protected Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - protected PatternLayoutConverter() - { - } - - #endregion Protected Instance Constructors - - #region Public Properties - - /// - /// Flag indicating if this converter handles the logging event exception - /// - /// false if this converter handles the logging event exception - /// - /// - /// If this converter handles the exception object contained within - /// , then this property should be set to - /// false. Otherwise, if the layout ignores the exception - /// object, then the property should be set to true. - /// - /// - /// Set this value to override a this default setting. The default - /// value is true, this converter does not handle the exception. - /// - /// - virtual public bool IgnoresException - { - get { return m_ignoresException; } - set { m_ignoresException = value; } - } - - #endregion Public Properties - - #region Protected Abstract Methods - - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the correct way. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - abstract protected void Convert(TextWriter writer, LoggingEvent loggingEvent); - - #endregion Protected Abstract Methods - - #region Protected Methods - - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the correct way. - /// - /// that will receive the formatted result. - /// The state object on which the pattern converter should be executed. - override protected void Convert(TextWriter writer, object state) - { - LoggingEvent loggingEvent = state as LoggingEvent; - if (loggingEvent != null) - { - Convert(writer, loggingEvent); - } - else - { - throw new ArgumentException("state must be of type ["+typeof(LoggingEvent).FullName+"]", "state"); - } - } - - #endregion Protected Methods - - /// - /// Flag indicating if this converter handles exceptions - /// - /// - /// false if this converter handles exceptions - /// - private bool m_ignoresException = true; - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.Repository; + using log4net.Util; + + /// + /// Abstract class that provides the formatting functionality that + /// derived classes need. + /// + /// + /// Conversion specifiers in a conversion patterns are parsed to + /// individual PatternConverters. Each of which is responsible for + /// converting a logging event in a converter specific manner. + /// + /// Nicko Cadell. + public abstract class PatternLayoutConverter : PatternConverter + { + /// + /// Initializes a new instance of the class. + /// + protected PatternLayoutConverter() + { + } + + /// + /// Gets or sets a value indicating whether flag indicating if this converter handles the logging event exception. + /// + /// false if this converter handles the logging event exception. + /// + /// + /// If this converter handles the exception object contained within + /// , then this property should be set to + /// false. Otherwise, if the layout ignores the exception + /// object, then the property should be set to true. + /// + /// + /// Set this value to override a this default setting. The default + /// value is true, this converter does not handle the exception. + /// + /// + public virtual bool IgnoresException + { + get { return this.m_ignoresException; } + set { this.m_ignoresException = value; } + } + + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the correct way. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + protected abstract void Convert(TextWriter writer, LoggingEvent loggingEvent); + + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the correct way. + /// + /// that will receive the formatted result. + /// The state object on which the pattern converter should be executed. + protected override void Convert(TextWriter writer, object state) + { + LoggingEvent loggingEvent = state as LoggingEvent; + if (loggingEvent != null) + { + this.Convert(writer, loggingEvent); + } + else + { + throw new ArgumentException("state must be of type [" + typeof(LoggingEvent).FullName + "]", "state"); + } + } + + /// + /// Flag indicating if this converter handles exceptions. + /// + /// + /// false if this converter handles exceptions. + /// + private bool m_ignoresException = true; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs index c21b4555d61..8959edac5b9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs @@ -1,81 +1,78 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; -using System.Collections; - -using log4net.Core; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Property pattern converter - /// - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - /// If the is set to null - /// then all the properties are written as key value pairs. - /// - /// - /// Nicko Cadell - internal sealed class PropertyPatternConverter : PatternLayoutConverter - { - /// - /// Write the property value to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - /// If the is set to null - /// then all the properties are written as key value pairs. - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - if (Option != null) - { - // Write the value for the specified key - WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(Option)); - } - else - { - // Write all the key value pairs - WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); - } - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.Repository; + + /// + /// Property pattern converter. + /// + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + /// If the is set to null + /// then all the properties are written as key value pairs. + /// + /// + /// Nicko Cadell. + internal sealed class PropertyPatternConverter : PatternLayoutConverter + { + /// + /// Write the property value to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + /// If the is set to null + /// then all the properties are written as key value pairs. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + if (this.Option != null) + { + // Write the value for the specified key + WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(this.Option)); + } + else + { + // Write all the key value pairs + WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs index 18756d1353d..413610007ba 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs @@ -1,74 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Converter to output the relative time of the event - /// - /// - /// - /// Converter to output the time of the event relative to the start of the program. - /// - /// - /// Nicko Cadell - internal sealed class RelativeTimePatternConverter : PatternLayoutConverter - { - /// - /// Write the relative time to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes out the relative time of the event in milliseconds. - /// That is the number of milliseconds between the event - /// and the . - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write( TimeDifferenceInMillis(LoggingEvent.StartTimeUtc, loggingEvent.TimeStampUtc).ToString(System.Globalization.NumberFormatInfo.InvariantInfo) ); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Converter to output the relative time of the event. + /// + /// + /// + /// Converter to output the time of the event relative to the start of the program. + /// + /// + /// Nicko Cadell. + internal sealed class RelativeTimePatternConverter : PatternLayoutConverter + { + /// + /// Write the relative time to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes out the relative time of the event in milliseconds. + /// That is the number of milliseconds between the event + /// and the . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(TimeDifferenceInMillis(LoggingEvent.StartTimeUtc, loggingEvent.TimeStampUtc).ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); + } - /// - /// Helper method to get the time difference between two DateTime objects - /// - /// start time (in the current local time zone) - /// end time (in the current local time zone) - /// the time difference in milliseconds - private static long TimeDifferenceInMillis(DateTime start, DateTime end) - { - // We must convert all times to UTC before performing any mathematical - // operations on them. This allows use to take into account discontinuities - // caused by daylight savings time transitions. - return (long)(end.ToUniversalTime() - start.ToUniversalTime()).TotalMilliseconds; - } - } + /// + /// Helper method to get the time difference between two DateTime objects. + /// + /// start time (in the current local time zone). + /// end time (in the current local time zone). + /// the time difference in milliseconds. + private static long TimeDifferenceInMillis(DateTime start, DateTime end) + { + // We must convert all times to UTC before performing any mathematical + // operations on them. This allows use to take into account discontinuities + // caused by daylight savings time transitions. + return (long)(end.ToUniversalTime() - start.ToUniversalTime()).TotalMilliseconds; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs index c66fecd9717..857dc95c99a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -27,14 +27,14 @@ using System; using System.Collections; using System.Text; - -using log4net.Util; + using log4net.Core; +using log4net.Util; namespace log4net.Layout.Pattern { /// - /// Write the caller stack frames to the output + /// Write the caller stack frames to the output. /// /// /// @@ -42,16 +42,16 @@ namespace log4net.Layout.Pattern /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) /// /// - /// Adam Davies + /// Adam Davies. internal class StackTraceDetailPatternConverter : StackTracePatternConverter { internal override string GetMethodInformation(MethodItem method) { - string returnValue=""; + string returnValue = string.Empty; try { - string param = ""; + string param = string.Empty; string[] names = method.Parameters; StringBuilder sb = new StringBuilder(); if (names != null && names.GetUpperBound(0) > 0) @@ -68,7 +68,7 @@ internal override string GetMethodInformation(MethodItem method) param = sb.ToString(); } - returnValue=base.GetMethodInformation(method) + "(" + param + ")"; + returnValue = base.GetMethodInformation(method) + "(" + param + ")"; } catch (Exception ex) { @@ -76,10 +76,8 @@ internal override string GetMethodInformation(MethodItem method) } return returnValue; - } - - #region Private Static Fields - + } + /// /// The fully qualified type of the StackTraceDetailPatternConverter class. /// @@ -87,9 +85,7 @@ internal override string GetMethodInformation(MethodItem method) /// Used by the internal logger to record the Type of the /// log message. /// - private readonly static Type declaringType = typeof(StackTracePatternConverter); - - #endregion Private Static Fields + private static readonly Type declaringType = typeof(StackTracePatternConverter); } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs index 5824c62ef8d..cbf7a1339dd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,136 +18,134 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion #if !NETCF using System; -using System.IO; using System.Diagnostics; - -using log4net.Util; +using System.IO; + using log4net.Core; +using log4net.Util; namespace log4net.Layout.Pattern { - /// - /// Write the caller stack frames to the output - /// - /// - /// - /// Writes the to the output writer, using format: - /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 - /// - /// - /// Michael Cromwell - internal class StackTracePatternConverter : PatternLayoutConverter, IOptionHandler - { - private int m_stackFrameLevel = 1; - - /// - /// Initialize the converter - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - if (Option == null) - return; - - string optStr = Option.Trim(); - if (optStr.Length != 0) - { - int stackLevelVal; - if (SystemInfo.TryParse(optStr, out stackLevelVal)) - { - if (stackLevelVal <= 0) - { - LogLog.Error(declaringType, "StackTracePatternConverter: StackeFrameLevel option (" + optStr + ") isn't a positive integer."); - } - else - { - m_stackFrameLevel = stackLevelVal; - } - } - else - { - LogLog.Error(declaringType, "StackTracePatternConverter: StackFrameLevel option \"" + optStr + "\" not a decimal integer."); - } - } - } - - /// - /// Write the strack frames to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the to the output writer. - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - StackFrameItem[] stackframes = loggingEvent.LocationInformation.StackFrames; - if ((stackframes == null) || (stackframes.Length <= 0)) - { - LogLog.Error(declaringType, "loggingEvent.LocationInformation.StackFrames was null or empty."); - return; - } - - int stackFrameIndex = m_stackFrameLevel - 1; - while (stackFrameIndex >= 0) - { - if (stackFrameIndex >= stackframes.Length) - { - stackFrameIndex--; - continue; - } - - StackFrameItem stackFrame = stackframes[stackFrameIndex]; - writer.Write("{0}.{1}", stackFrame.ClassName, GetMethodInformation(stackFrame.Method)); - if (stackFrameIndex > 0) - { - // TODO: make this user settable? - writer.Write(" > "); - } - stackFrameIndex--; - } - } + /// + /// Write the caller stack frames to the output. + /// + /// + /// + /// Writes the to the output writer, using format: + /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1. + /// + /// + /// Michael Cromwell. + internal class StackTracePatternConverter : PatternLayoutConverter, IOptionHandler + { + private int m_stackFrameLevel = 1; - /// - /// Returns the Name of the method + /// + /// Initialize the converter. /// - /// - /// This method was created, so this class could be used as a base class for StackTraceDetailPatternConverter - /// string - internal virtual string GetMethodInformation(MethodItem method) + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() { - return method.Name; + if (this.Option == null) + { + return; + } + + string optStr = this.Option.Trim(); + if (optStr.Length != 0) + { + int stackLevelVal; + if (SystemInfo.TryParse(optStr, out stackLevelVal)) + { + if (stackLevelVal <= 0) + { + LogLog.Error(declaringType, "StackTracePatternConverter: StackeFrameLevel option (" + optStr + ") isn't a positive integer."); + } + else + { + this.m_stackFrameLevel = stackLevelVal; + } + } + else + { + LogLog.Error(declaringType, "StackTracePatternConverter: StackFrameLevel option \"" + optStr + "\" not a decimal integer."); + } + } } - - #region Private Static Fields - /// - /// The fully qualified type of the StackTracePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(StackTracePatternConverter); + /// + /// Write the strack frames to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the to the output writer. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + StackFrameItem[] stackframes = loggingEvent.LocationInformation.StackFrames; + if ((stackframes == null) || (stackframes.Length <= 0)) + { + LogLog.Error(declaringType, "loggingEvent.LocationInformation.StackFrames was null or empty."); + return; + } + + int stackFrameIndex = this.m_stackFrameLevel - 1; + while (stackFrameIndex >= 0) + { + if (stackFrameIndex >= stackframes.Length) + { + stackFrameIndex--; + continue; + } - #endregion Private Static Fields - } + StackFrameItem stackFrame = stackframes[stackFrameIndex]; + writer.Write("{0}.{1}", stackFrame.ClassName, this.GetMethodInformation(stackFrame.Method)); + if (stackFrameIndex > 0) + { + // TODO: make this user settable? + writer.Write(" > "); + } + + stackFrameIndex--; + } + } + + /// + /// Returns the Name of the method. + /// + /// + /// This method was created, so this class could be used as a base class for StackTraceDetailPatternConverter. + /// string. + internal virtual string GetMethodInformation(MethodItem method) + { + return method.Name; + } + + /// + /// The fully qualified type of the StackTracePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(StackTracePatternConverter); + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs index 9326d078c28..5134f6439dc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs @@ -1,58 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Converter to include event thread name - /// - /// - /// - /// Writes the to the output. - /// - /// - /// Nicko Cadell - internal sealed class ThreadPatternConverter : PatternLayoutConverter - { - /// - /// Write the ThreadName to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Writes the to the . - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.ThreadName); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Converter to include event thread name. + /// + /// + /// + /// Writes the to the output. + /// + /// + /// Nicko Cadell. + internal sealed class ThreadPatternConverter : PatternLayoutConverter + { + /// + /// Write the ThreadName to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Writes the to the . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.ThreadName); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs index ee4eb539ebe..90cee1df9a0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs @@ -1,58 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Pattern converter for the class name - /// - /// - /// - /// Outputs the of the event. - /// - /// - /// Nicko Cadell - internal sealed class TypeNamePatternConverter : NamedPatternConverter - { - /// - /// Gets the fully qualified name of the class - /// - /// the event being logged - /// The fully qualified type name for the caller location - /// - /// - /// Returns the of the . - /// - /// - override protected string GetFullyQualifiedName(LoggingEvent loggingEvent) - { - return loggingEvent.LocationInformation.ClassName; - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Pattern converter for the class name. + /// + /// + /// + /// Outputs the of the event. + /// + /// + /// Nicko Cadell. + internal sealed class TypeNamePatternConverter : NamedPatternConverter + { + /// + /// Gets the fully qualified name of the class. + /// + /// the event being logged. + /// The fully qualified type name for the caller location. + /// + /// + /// Returns the of the . + /// + /// + protected override string GetFullyQualifiedName(LoggingEvent loggingEvent) + { + return loggingEvent.LocationInformation.ClassName; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs index a069bd9354e..71b4079887a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs @@ -1,49 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Converter to include event user name - /// - /// Douglas de la Torre - /// Nicko Cadell - internal sealed class UserNamePatternConverter : PatternLayoutConverter - { - /// - /// Convert the pattern to the rendered message - /// - /// that will receive the formatted result. - /// the event being logged - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write( loggingEvent.UserName ); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// Converter to include event user name. + /// + /// Douglas de la Torre. + /// Nicko Cadell. + internal sealed class UserNamePatternConverter : PatternLayoutConverter + { + /// + /// Convert the pattern to the rendered message. + /// + /// that will receive the formatted result. + /// the event being logged. + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.UserName); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs index dcece2f802a..b40f978b4ae 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs @@ -1,95 +1,88 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; -using log4net.Util; -using log4net.DateFormatter; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout.Pattern { - /// - /// Write the TimeStamp to the output - /// - /// - /// - /// Date pattern converter, uses a to format - /// the date of a . - /// - /// - /// Uses a to format the - /// in Universal time. - /// - /// - /// See the for details on the date pattern syntax. - /// - /// - /// - /// Nicko Cadell - internal class UtcDatePatternConverter : DatePatternConverter - { - /// - /// Write the TimeStamp to the output - /// - /// that will receive the formatted result. - /// the event being logged - /// - /// - /// Pass the to the - /// for it to render it to the writer. - /// - /// - /// The passed is in the local time zone, this is converted - /// to Universal time before it is rendered. - /// - /// - /// - override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - try - { - m_dateFormatter.FormatDate(loggingEvent.TimeStampUtc, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } - } - - #region Private Static Fields - - /// - /// The fully qualified type of the UtcDatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(UtcDatePatternConverter); - - #endregion Private Static Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.DateFormatter; + using log4net.Util; + + /// + /// Write the TimeStamp to the output. + /// + /// + /// + /// Date pattern converter, uses a to format + /// the date of a . + /// + /// + /// Uses a to format the + /// in Universal time. + /// + /// + /// See the for details on the date pattern syntax. + /// + /// + /// + /// Nicko Cadell. + internal class UtcDatePatternConverter : DatePatternConverter + { + /// + /// Write the TimeStamp to the output. + /// + /// that will receive the formatted result. + /// the event being logged. + /// + /// + /// Pass the to the + /// for it to render it to the writer. + /// + /// + /// The passed is in the local time zone, this is converted + /// to Universal time before it is rendered. + /// + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + try + { + this.m_dateFormatter.FormatDate(loggingEvent.TimeStampUtc, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } + } + + /// + /// The fully qualified type of the UtcDatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(UtcDatePatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs index 81ed7c7c7d3..cec1ccf6230 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs @@ -1,29 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.IO; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETSTANDARD1_3 using System.Reflection; #endif @@ -32,98 +10,119 @@ using log4net.Layout.Pattern; using log4net.Util; using log4net.Util.PatternStringConverters; -using AppDomainPatternConverter=log4net.Layout.Pattern.AppDomainPatternConverter; -using DatePatternConverter=log4net.Layout.Pattern.DatePatternConverter; -using IdentityPatternConverter=log4net.Layout.Pattern.IdentityPatternConverter; -using PropertyPatternConverter=log4net.Layout.Pattern.PropertyPatternConverter; -using UserNamePatternConverter=log4net.Layout.Pattern.UserNamePatternConverter; -using UtcDatePatternConverter=log4net.Layout.Pattern.UtcDatePatternConverter; + +using AppDomainPatternConverter = log4net.Layout.Pattern.AppDomainPatternConverter; +using DatePatternConverter = log4net.Layout.Pattern.DatePatternConverter; +using IdentityPatternConverter = log4net.Layout.Pattern.IdentityPatternConverter; +using PropertyPatternConverter = log4net.Layout.Pattern.PropertyPatternConverter; +using UserNamePatternConverter = log4net.Layout.Pattern.UserNamePatternConverter; +using UtcDatePatternConverter = log4net.Layout.Pattern.UtcDatePatternConverter; namespace log4net.Layout { - /// - /// A flexible layout configurable with pattern string. - /// - /// - /// - /// The goal of this class is to a - /// as a string. The results - /// depend on the conversion pattern. - /// - /// - /// The conversion pattern is closely related to the conversion - /// pattern of the printf function in C. A conversion pattern is - /// composed of literal text and format control expressions called - /// conversion specifiers. - /// - /// - /// You are free to insert any literal text within the conversion - /// pattern. - /// - /// - /// Each conversion specifier starts with a percent sign (%) and is - /// followed by optional format modifiers and a conversion - /// pattern name. The conversion pattern name specifies the type of - /// data, e.g. logger, level, date, thread name. The format - /// modifiers control such things as field width, padding, left and - /// right justification. The following is a simple example. - /// - /// - /// Let the conversion pattern be "%-5level [%thread]: %message%newline" and assume - /// that the log4net environment was set to use a PatternLayout. Then the - /// statements - /// - /// - /// ILog log = LogManager.GetLogger(typeof(TestApp)); - /// log.Debug("Message 1"); - /// log.Warn("Message 2"); - /// - /// would yield the output - /// - /// DEBUG [main]: Message 1 - /// WARN [main]: Message 2 - /// - /// - /// Note that there is no explicit separator between text and - /// conversion specifiers. The pattern parser knows when it has reached - /// the end of a conversion specifier when it reads a conversion - /// character. In the example above the conversion specifier - /// %-5level means the level of the logging event should be left - /// justified to a width of five characters. - /// - /// - /// The recognized conversion pattern names are: - /// - /// - /// - /// Conversion Pattern Name - /// Effect - /// - /// - /// a - /// Equivalent to appdomain - /// - /// - /// appdomain - /// - /// Used to output the friendly name of the AppDomain where the - /// logging event was generated. - /// - /// - /// - /// aspnet-cache - /// + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + + /// + /// A flexible layout configurable with pattern string. + /// + /// + /// + /// The goal of this class is to a + /// as a string. The results + /// depend on the conversion pattern. + /// + /// + /// The conversion pattern is closely related to the conversion + /// pattern of the printf function in C. A conversion pattern is + /// composed of literal text and format control expressions called + /// conversion specifiers. + /// + /// + /// You are free to insert any literal text within the conversion + /// pattern. + /// + /// + /// Each conversion specifier starts with a percent sign (%) and is + /// followed by optional format modifiers and a conversion + /// pattern name. The conversion pattern name specifies the type of + /// data, e.g. logger, level, date, thread name. The format + /// modifiers control such things as field width, padding, left and + /// right justification. The following is a simple example. + /// + /// + /// Let the conversion pattern be "%-5level [%thread]: %message%newline" and assume + /// that the log4net environment was set to use a PatternLayout. Then the + /// statements. + /// + /// + /// ILog log = LogManager.GetLogger(typeof(TestApp)); + /// log.Debug("Message 1"); + /// log.Warn("Message 2"); + /// + /// would yield the output. + /// + /// DEBUG [main]: Message 1 + /// WARN [main]: Message 2 + /// + /// + /// Note that there is no explicit separator between text and + /// conversion specifiers. The pattern parser knows when it has reached + /// the end of a conversion specifier when it reads a conversion + /// character. In the example above the conversion specifier + /// %-5level means the level of the logging event should be left + /// justified to a width of five characters. + /// + /// + /// The recognized conversion pattern names are: + /// + /// + /// + /// Conversion Pattern Name + /// Effect + /// + /// + /// a + /// Equivalent to appdomain + /// + /// + /// appdomain + /// + /// Used to output the friendly name of the AppDomain where the + /// logging event was generated. + /// + /// + /// + /// aspnet-cache + /// /// /// Used to output all cache items in the case of %aspnet-cache or just one named item if used as %aspnet-cache{key} /// /// /// This pattern is not available for Compact Framework or Client Profile assemblies. /// - /// - /// - /// - /// aspnet-context - /// + /// + /// + /// + /// aspnet-context + /// /// /// Used to output all context items in the case of %aspnet-context or just one named item if used as %aspnet-context{key} /// @@ -131,10 +130,10 @@ namespace log4net.Layout /// This pattern is not available for Compact Framework or Client Profile assemblies. /// /// - /// - /// - /// aspnet-request - /// + /// + /// + /// aspnet-request + /// /// /// Used to output all request parameters in the case of %aspnet-request or just one named param if used as %aspnet-request{key} /// @@ -142,10 +141,10 @@ namespace log4net.Layout /// This pattern is not available for Compact Framework or Client Profile assemblies. /// /// - /// - /// - /// aspnet-session - /// + /// + /// + /// aspnet-session + /// /// /// Used to output all session items in the case of %aspnet-session or just one named item if used as %aspnet-session{key} /// @@ -153,1025 +152,1015 @@ namespace log4net.Layout /// This pattern is not available for Compact Framework or Client Profile assemblies. /// /// - /// - /// - /// c - /// Equivalent to logger - /// - /// - /// C - /// Equivalent to type - /// - /// - /// class - /// Equivalent to type - /// - /// - /// d - /// Equivalent to date - /// - /// - /// date - /// - /// - /// Used to output the date of the logging event in the local time zone. - /// To output the date in universal time use the %utcdate pattern. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %date{HH:mm:ss,fff} or - /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %date{ISO8601} or %date{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// exception - /// - /// - /// Used to output the exception passed in with the log message. - /// - /// - /// If an exception object is stored in the logging event - /// it will be rendered into the pattern output with a - /// trailing newline. - /// If there is no exception then nothing will be output - /// and no trailing newline will be appended. - /// It is typical to put a newline before the exception - /// and to have the exception as the last data in the pattern. - /// - /// - /// - /// - /// F - /// Equivalent to file - /// - /// - /// file - /// - /// - /// Used to output the file name where the logging request was - /// issued. - /// - /// - /// WARNING Generating caller location information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// identity - /// - /// - /// Used to output the user name for the currently active user - /// (Principal.Identity.Name). - /// - /// - /// WARNING Generating caller information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// - /// - /// l - /// Equivalent to location - /// - /// - /// L - /// Equivalent to line - /// - /// - /// location - /// - /// - /// Used to output location information of the caller which generated - /// the logging event. - /// - /// - /// The location information depends on the CLI implementation but - /// usually consists of the fully qualified name of the calling - /// method followed by the callers source the file name and line - /// number between parentheses. - /// - /// - /// The location information can be very useful. However, its - /// generation is extremely slow. Its use should be avoided - /// unless execution speed is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// level - /// - /// - /// Used to output the level of the logging event. - /// - /// - /// - /// - /// line - /// - /// - /// Used to output the line number from where the logging request - /// was issued. - /// - /// - /// WARNING Generating caller location information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// logger - /// - /// - /// Used to output the logger of the logging event. The - /// logger conversion specifier can be optionally followed by - /// precision specifier, that is a decimal constant in - /// brackets. - /// - /// - /// If a precision specifier is given, then only the corresponding - /// number of right most components of the logger name will be - /// printed. By default the logger name is printed in full. - /// - /// - /// For example, for the logger name "a.b.c" the pattern - /// %logger{2} will output "b.c". - /// - /// - /// - /// - /// m - /// Equivalent to message - /// - /// - /// M - /// Equivalent to method - /// - /// - /// message - /// - /// - /// Used to output the application supplied message associated with - /// the logging event. - /// - /// - /// - /// - /// mdc - /// - /// - /// The MDC (old name for the ThreadContext.Properties) is now part of the - /// combined event properties. This pattern is supported for compatibility - /// but is equivalent to property. - /// - /// - /// - /// - /// method - /// - /// - /// Used to output the method name where the logging request was - /// issued. - /// - /// - /// WARNING Generating caller location information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// n - /// Equivalent to newline - /// - /// - /// newline - /// - /// - /// Outputs the platform dependent line separator character or - /// characters. - /// - /// - /// This conversion pattern offers the same performance as using - /// non-portable line separator strings such as "\n", or "\r\n". - /// Thus, it is the preferred way of specifying a line separator. - /// - /// - /// - /// - /// ndc - /// - /// - /// Used to output the NDC (nested diagnostic context) associated - /// with the thread that generated the logging event. - /// - /// - /// - /// - /// p - /// Equivalent to level - /// - /// - /// P - /// Equivalent to property - /// - /// - /// properties - /// Equivalent to property - /// - /// - /// property - /// - /// - /// Used to output the an event specific property. The key to - /// lookup must be specified within braces and directly following the - /// pattern specifier, e.g. %property{user} would include the value - /// from the property that is keyed by the string 'user'. Each property value - /// that is to be included in the log must be specified separately. - /// Properties are added to events by loggers or appenders. By default - /// the log4net:HostName property is set to the name of machine on - /// which the event was originally logged. - /// - /// - /// If no key is specified, e.g. %property then all the keys and their - /// values are printed in a comma separated list. - /// - /// - /// The properties of an event are combined from a number of different - /// contexts. These are listed below in the order in which they are searched. - /// - /// - /// - /// the event properties - /// - /// The event has that can be set. These - /// properties are specific to this event only. - /// - /// - /// - /// the thread properties - /// - /// The that are set on the current - /// thread. These properties are shared by all events logged on this thread. - /// - /// - /// - /// the global properties - /// - /// The that are set globally. These - /// properties are shared by all the threads in the AppDomain. - /// - /// - /// - /// - /// - /// - /// - /// r - /// Equivalent to timestamp - /// - /// - /// stacktrace - /// - /// - /// Used to output the stack trace of the logging event - /// The stack trace level specifier may be enclosed - /// between braces. For example, %stacktrace{level}. - /// If no stack trace level specifier is given then 1 is assumed - /// - /// - /// Output uses the format: - /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 - /// + /// + /// + /// c + /// Equivalent to logger + /// + /// + /// C + /// Equivalent to type + /// + /// + /// class + /// Equivalent to type + /// + /// + /// d + /// Equivalent to date + /// + /// + /// date + /// + /// + /// Used to output the date of the logging event in the local time zone. + /// To output the date in universal time use the %utcdate pattern. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %date{HH:mm:ss,fff} or + /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %date{ISO8601} or %date{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// exception + /// + /// + /// Used to output the exception passed in with the log message. + /// + /// + /// If an exception object is stored in the logging event + /// it will be rendered into the pattern output with a + /// trailing newline. + /// If there is no exception then nothing will be output + /// and no trailing newline will be appended. + /// It is typical to put a newline before the exception + /// and to have the exception as the last data in the pattern. + /// + /// + /// + /// + /// F + /// Equivalent to file + /// + /// + /// file + /// + /// + /// Used to output the file name where the logging request was + /// issued. + /// + /// + /// WARNING Generating caller location information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// identity + /// + /// + /// Used to output the user name for the currently active user + /// (Principal.Identity.Name). + /// + /// + /// WARNING Generating caller information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// + /// + /// l + /// Equivalent to location + /// + /// + /// L + /// Equivalent to line + /// + /// + /// location + /// + /// + /// Used to output location information of the caller which generated + /// the logging event. + /// + /// + /// The location information depends on the CLI implementation but + /// usually consists of the fully qualified name of the calling + /// method followed by the callers source the file name and line + /// number between parentheses. + /// + /// + /// The location information can be very useful. However, its + /// generation is extremely slow. Its use should be avoided + /// unless execution speed is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// level + /// + /// + /// Used to output the level of the logging event. + /// + /// + /// + /// + /// line + /// + /// + /// Used to output the line number from where the logging request + /// was issued. + /// + /// + /// WARNING Generating caller location information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// logger + /// + /// + /// Used to output the logger of the logging event. The + /// logger conversion specifier can be optionally followed by + /// precision specifier, that is a decimal constant in + /// brackets. + /// + /// + /// If a precision specifier is given, then only the corresponding + /// number of right most components of the logger name will be + /// printed. By default the logger name is printed in full. + /// + /// + /// For example, for the logger name "a.b.c" the pattern + /// %logger{2} will output "b.c". + /// + /// + /// + /// + /// m + /// Equivalent to message + /// + /// + /// M + /// Equivalent to method + /// + /// + /// message + /// + /// + /// Used to output the application supplied message associated with + /// the logging event. + /// + /// + /// + /// + /// mdc + /// + /// + /// The MDC (old name for the ThreadContext.Properties) is now part of the + /// combined event properties. This pattern is supported for compatibility + /// but is equivalent to property. + /// + /// + /// + /// + /// method + /// + /// + /// Used to output the method name where the logging request was + /// issued. + /// + /// + /// WARNING Generating caller location information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// n + /// Equivalent to newline + /// + /// + /// newline + /// + /// + /// Outputs the platform dependent line separator character or + /// characters. + /// + /// + /// This conversion pattern offers the same performance as using + /// non-portable line separator strings such as "\n", or "\r\n". + /// Thus, it is the preferred way of specifying a line separator. + /// + /// + /// + /// + /// ndc + /// + /// + /// Used to output the NDC (nested diagnostic context) associated + /// with the thread that generated the logging event. + /// + /// + /// + /// + /// p + /// Equivalent to level + /// + /// + /// P + /// Equivalent to property + /// + /// + /// properties + /// Equivalent to property + /// + /// + /// property + /// + /// + /// Used to output the an event specific property. The key to + /// lookup must be specified within braces and directly following the + /// pattern specifier, e.g. %property{user} would include the value + /// from the property that is keyed by the string 'user'. Each property value + /// that is to be included in the log must be specified separately. + /// Properties are added to events by loggers or appenders. By default + /// the log4net:HostName property is set to the name of machine on + /// which the event was originally logged. + /// + /// + /// If no key is specified, e.g. %property then all the keys and their + /// values are printed in a comma separated list. + /// + /// + /// The properties of an event are combined from a number of different + /// contexts. These are listed below in the order in which they are searched. + /// + /// + /// + /// the event properties + /// + /// The event has that can be set. These + /// properties are specific to this event only. + /// + /// + /// + /// the thread properties + /// + /// The that are set on the current + /// thread. These properties are shared by all events logged on this thread. + /// + /// + /// + /// the global properties + /// + /// The that are set globally. These + /// properties are shared by all the threads in the AppDomain. + /// + /// + /// + /// + /// + /// + /// + /// r + /// Equivalent to timestamp + /// + /// + /// stacktrace + /// + /// + /// Used to output the stack trace of the logging event + /// The stack trace level specifier may be enclosed + /// between braces. For example, %stacktrace{level}. + /// If no stack trace level specifier is given then 1 is assumed + /// + /// + /// Output uses the format: + /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 + /// /// /// This pattern is not available for Compact Framework assemblies. /// - /// - /// - /// - /// stacktracedetail - /// - /// - /// Used to output the stack trace of the logging event - /// The stack trace level specifier may be enclosed - /// between braces. For example, %stacktracedetail{level}. - /// If no stack trace level specifier is given then 1 is assumed - /// - /// - /// Output uses the format: + /// + /// + /// + /// stacktracedetail + /// + /// + /// Used to output the stack trace of the logging event + /// The stack trace level specifier may be enclosed + /// between braces. For example, %stacktracedetail{level}. + /// If no stack trace level specifier is given then 1 is assumed + /// + /// + /// Output uses the format: /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) - /// + /// /// /// This pattern is not available for Compact Framework assemblies. /// - /// - /// + /// + /// /// - /// t - /// Equivalent to thread - /// - /// - /// timestamp - /// - /// - /// Used to output the number of milliseconds elapsed since the start - /// of the application until the creation of the logging event. - /// - /// - /// - /// - /// thread - /// - /// - /// Used to output the name of the thread that generated the - /// logging event. Uses the thread number if no name is available. - /// - /// - /// - /// - /// type - /// - /// - /// Used to output the fully qualified type name of the caller - /// issuing the logging request. This conversion specifier - /// can be optionally followed by precision specifier, that - /// is a decimal constant in brackets. - /// - /// - /// If a precision specifier is given, then only the corresponding - /// number of right most components of the class name will be - /// printed. By default the class name is output in fully qualified form. - /// - /// - /// For example, for the class name "log4net.Layout.PatternLayout", the - /// pattern %type{1} will output "PatternLayout". - /// - /// - /// WARNING Generating the caller class information is - /// slow. Thus, its use should be avoided unless execution speed is - /// not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// u - /// Equivalent to identity - /// - /// - /// username - /// - /// - /// Used to output the WindowsIdentity for the currently - /// active user. - /// - /// - /// WARNING Generating caller WindowsIdentity information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// - /// - /// utcdate - /// - /// - /// Used to output the date of the logging event in universal time. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %utcdate{HH:mm:ss,fff} or - /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// w - /// Equivalent to username - /// - /// - /// x - /// Equivalent to ndc - /// - /// - /// X - /// Equivalent to mdc - /// - /// - /// % - /// - /// - /// The sequence %% outputs a single percent sign. - /// - /// - /// - /// - /// - /// The single letter patterns are deprecated in favor of the - /// longer more descriptive pattern names. - /// - /// - /// By default the relevant information is output as is. However, - /// with the aid of format modifiers it is possible to change the - /// minimum field width, the maximum field width and justification. - /// - /// - /// The optional format modifier is placed between the percent sign - /// and the conversion pattern name. - /// - /// - /// The first optional format modifier is the left justification - /// flag which is just the minus (-) character. Then comes the - /// optional minimum field width modifier. This is a decimal - /// constant that represents the minimum number of characters to - /// output. If the data item requires fewer characters, it is padded on - /// either the left or the right until the minimum width is - /// reached. The default is to pad on the left (right justify) but you - /// can specify right padding with the left justification flag. The - /// padding character is space. If the data item is larger than the - /// minimum field width, the field is expanded to accommodate the - /// data. The value is never truncated. - /// - /// - /// This behavior can be changed using the maximum field - /// width modifier which is designated by a period followed by a - /// decimal constant. If the data item is longer than the maximum - /// field, then the extra characters are removed from the - /// beginning of the data item and not from the end. For - /// example, it the maximum field width is eight and the data item is - /// ten characters long, then the first two characters of the data item - /// are dropped. This behavior deviates from the printf function in C - /// where truncation is done from the end. - /// - /// - /// Below are various format modifier examples for the logger - /// conversion specifier. - /// - ///
- /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ///
Format modifierleft justifyminimum widthmaximum widthcomment
%20loggerfalse20none - /// - /// Left pad with spaces if the logger name is less than 20 - /// characters long. - /// - ///
%-20loggertrue20none - /// - /// Right pad with spaces if the logger - /// name is less than 20 characters long. - /// - ///
%.30loggerNAnone30 - /// - /// Truncate from the beginning if the logger - /// name is longer than 30 characters. - /// - ///
%20.30loggerfalse2030 - /// - /// Left pad with spaces if the logger name is shorter than 20 - /// characters. However, if logger name is longer than 30 characters, - /// then truncate from the beginning. - /// - ///
%-20.30loggertrue2030 - /// - /// Right pad with spaces if the logger name is shorter than 20 - /// characters. However, if logger name is longer than 30 characters, - /// then truncate from the beginning. - /// - ///
- ///
- /// - /// Note about caller location information.
- /// The following patterns %type %file %line %method %location %class %C %F %L %l %M - /// all generate caller location information. - /// Location information uses the System.Diagnostics.StackTrace class to generate - /// a call stack. The caller's information is then extracted from this stack. - ///
- /// - /// - /// The System.Diagnostics.StackTrace class is not supported on the - /// .NET Compact Framework 1.0 therefore caller location information is not - /// available on that framework. - /// - /// - /// - /// - /// The System.Diagnostics.StackTrace class has this to say about Release builds: - /// - /// - /// "StackTrace information will be most informative with Debug build configurations. - /// By default, Debug builds include debug symbols, while Release builds do not. The - /// debug symbols contain most of the file, method name, line number, and column - /// information used in constructing StackFrame and StackTrace objects. StackTrace - /// might not report as many method calls as expected, due to code transformations - /// that occur during optimization." - /// - /// - /// This means that in a Release build the caller information may be incomplete or may - /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. - /// - /// - /// - /// Additional pattern converters may be registered with a specific - /// instance using the method. - /// - ///
- /// - /// This is a more detailed pattern. - /// %timestamp [%thread] %level %logger %ndc - %message%newline - /// - /// - /// A similar pattern except that the relative time is - /// right padded if less than 6 digits, thread name is right padded if - /// less than 15 characters and truncated if longer and the logger - /// name is left padded if shorter than 30 characters and truncated if - /// longer. - /// %-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline - /// - /// Nicko Cadell - /// Gert Driesen - /// Douglas de la Torre - /// Daniel Cazzulino - public class PatternLayout : LayoutSkeleton - { - #region Constants - - /// - /// Default pattern string for log output. - /// - /// - /// - /// Default pattern string for log output. - /// Currently set to the string "%message%newline" - /// which just prints the application supplied message. - /// - /// - public const string DefaultConversionPattern ="%message%newline"; - - /// - /// A detailed conversion pattern - /// - /// - /// - /// A conversion pattern which includes Time, Thread, Logger, and Nested Context. - /// Current value is %timestamp [%thread] %level %logger %ndc - %message%newline. - /// - /// - public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline"; - - #endregion - - #region Static Fields - - /// - /// Internal map of converter identifiers to converter types. - /// - /// - /// - /// This static map is overridden by the m_converterRegistry instance map - /// - /// - private static Hashtable s_globalRulesRegistry; - - #endregion Static Fields - - #region Member Variables - - /// - /// the pattern - /// - private string m_pattern; - - /// - /// the head of the pattern converter chain - /// - private PatternConverter m_head; - - /// - /// patterns defined on this PatternLayout only - /// - private Hashtable m_instanceRulesRegistry = new Hashtable(); - - #endregion + /// t + /// Equivalent to thread + /// + /// + /// timestamp + /// + /// + /// Used to output the number of milliseconds elapsed since the start + /// of the application until the creation of the logging event. + /// + /// + /// + /// + /// thread + /// + /// + /// Used to output the name of the thread that generated the + /// logging event. Uses the thread number if no name is available. + /// + /// + /// + /// + /// type + /// + /// + /// Used to output the fully qualified type name of the caller + /// issuing the logging request. This conversion specifier + /// can be optionally followed by precision specifier, that + /// is a decimal constant in brackets. + /// + /// + /// If a precision specifier is given, then only the corresponding + /// number of right most components of the class name will be + /// printed. By default the class name is output in fully qualified form. + /// + /// + /// For example, for the class name "log4net.Layout.PatternLayout", the + /// pattern %type{1} will output "PatternLayout". + /// + /// + /// WARNING Generating the caller class information is + /// slow. Thus, its use should be avoided unless execution speed is + /// not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// u + /// Equivalent to identity + /// + /// + /// username + /// + /// + /// Used to output the WindowsIdentity for the currently + /// active user. + /// + /// + /// WARNING Generating caller WindowsIdentity information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// + /// + /// utcdate + /// + /// + /// Used to output the date of the logging event in universal time. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %utcdate{HH:mm:ss,fff} or + /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// w + /// Equivalent to username + /// + /// + /// x + /// Equivalent to ndc + /// + /// + /// X + /// Equivalent to mdc + /// + /// + /// % + /// + /// + /// The sequence %% outputs a single percent sign. + /// + /// + /// + /// + /// + /// The single letter patterns are deprecated in favor of the + /// longer more descriptive pattern names. + /// + /// + /// By default the relevant information is output as is. However, + /// with the aid of format modifiers it is possible to change the + /// minimum field width, the maximum field width and justification. + /// + /// + /// The optional format modifier is placed between the percent sign + /// and the conversion pattern name. + /// + /// + /// The first optional format modifier is the left justification + /// flag which is just the minus (-) character. Then comes the + /// optional minimum field width modifier. This is a decimal + /// constant that represents the minimum number of characters to + /// output. If the data item requires fewer characters, it is padded on + /// either the left or the right until the minimum width is + /// reached. The default is to pad on the left (right justify) but you + /// can specify right padding with the left justification flag. The + /// padding character is space. If the data item is larger than the + /// minimum field width, the field is expanded to accommodate the + /// data. The value is never truncated. + /// + /// + /// This behavior can be changed using the maximum field + /// width modifier which is designated by a period followed by a + /// decimal constant. If the data item is longer than the maximum + /// field, then the extra characters are removed from the + /// beginning of the data item and not from the end. For + /// example, it the maximum field width is eight and the data item is + /// ten characters long, then the first two characters of the data item + /// are dropped. This behavior deviates from the printf function in C + /// where truncation is done from the end. + /// + /// + /// Below are various format modifier examples for the logger + /// conversion specifier. + /// + ///
+ /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + ///
Format modifierleft justifyminimum widthmaximum widthcomment
%20loggerfalse20none + /// + /// Left pad with spaces if the logger name is less than 20 + /// characters long. + /// + ///
%-20loggertrue20none + /// + /// Right pad with spaces if the logger + /// name is less than 20 characters long. + /// + ///
%.30loggerNAnone30 + /// + /// Truncate from the beginning if the logger + /// name is longer than 30 characters. + /// + ///
%20.30loggerfalse2030 + /// + /// Left pad with spaces if the logger name is shorter than 20 + /// characters. However, if logger name is longer than 30 characters, + /// then truncate from the beginning. + /// + ///
%-20.30loggertrue2030 + /// + /// Right pad with spaces if the logger name is shorter than 20 + /// characters. However, if logger name is longer than 30 characters, + /// then truncate from the beginning. + /// + ///
+ ///
+ /// + /// Note about caller location information.
+ /// The following patterns %type %file %line %method %location %class %C %F %L %l %M + /// all generate caller location information. + /// Location information uses the System.Diagnostics.StackTrace class to generate + /// a call stack. The caller's information is then extracted from this stack. + ///
+ /// + /// + /// The System.Diagnostics.StackTrace class is not supported on the + /// .NET Compact Framework 1.0 therefore caller location information is not + /// available on that framework. + /// + /// + /// + /// + /// The System.Diagnostics.StackTrace class has this to say about Release builds: + /// + /// + /// "StackTrace information will be most informative with Debug build configurations. + /// By default, Debug builds include debug symbols, while Release builds do not. The + /// debug symbols contain most of the file, method name, line number, and column + /// information used in constructing StackFrame and StackTrace objects. StackTrace + /// might not report as many method calls as expected, due to code transformations + /// that occur during optimization.". + /// + /// + /// This means that in a Release build the caller information may be incomplete or may + /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. + /// + /// + /// + /// Additional pattern converters may be registered with a specific + /// instance using the method. + /// + /// + /// + /// This is a more detailed pattern. + /// %timestamp [%thread] %level %logger %ndc - %message%newline + /// + /// + /// A similar pattern except that the relative time is + /// right padded if less than 6 digits, thread name is right padded if + /// less than 15 characters and truncated if longer and the logger + /// name is left padded if shorter than 30 characters and truncated if + /// longer. + /// %-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Douglas de la Torre. + /// Daniel Cazzulino. + public class PatternLayout : LayoutSkeleton + { + /// + /// Default pattern string for log output. + /// + /// + /// + /// Default pattern string for log output. + /// Currently set to the string "%message%newline" + /// which just prints the application supplied message. + /// + /// + public const string DefaultConversionPattern = "%message%newline"; - #region Static Constructor + /// + /// A detailed conversion pattern. + /// + /// + /// + /// A conversion pattern which includes Time, Thread, Logger, and Nested Context. + /// Current value is %timestamp [%thread] %level %logger %ndc - %message%newline. + /// + /// + public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline"; + + /// + /// Internal map of converter identifiers to converter types. + /// + /// + /// + /// This static map is overridden by the m_converterRegistry instance map. + /// + /// + private static Hashtable s_globalRulesRegistry; + + /// + /// the pattern. + /// + private string m_pattern; - /// - /// Initialize the global registry - /// - /// - /// - /// Defines the builtin global rules. - /// - /// - static PatternLayout() - { - s_globalRulesRegistry = new Hashtable(45); + /// + /// the head of the pattern converter chain. + /// + private PatternConverter m_head; - s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); - s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); - s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter)); + /// + /// patterns defined on this PatternLayout only. + /// + private Hashtable m_instanceRulesRegistry = new Hashtable(); + + /// + /// Initializes static members of the class. + /// Initialize the global registry. + /// + /// + /// + /// Defines the builtin global rules. + /// + /// + static PatternLayout() + { + s_globalRulesRegistry = new Hashtable(45); -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET + s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); + s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); + s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter)); + + // .NET Compact Framework 1.0 has no support for ASP.NET + // SSCLI 1.0 has no support for ASP.NET #if !NETCF && !SSCLI && !CLIENT_PROFILE && !NETSTANDARD1_3 - s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter)); - s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter)); - s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter)); - s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter)); + s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter)); + s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter)); + s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter)); + s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter)); #endif - s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter)); - s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter)); + s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter)); + s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter)); + + s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter)); + s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter)); + s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter)); - s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter)); - s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter)); - s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter)); + s_globalRulesRegistry.Add("d", typeof(DatePatternConverter)); + s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); - s_globalRulesRegistry.Add("d", typeof(DatePatternConverter)); - s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); + s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter)); - s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter)); + s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter)); + s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter)); - s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter)); - s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter)); + s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter)); + s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter)); - s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter)); - s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter)); + s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter)); + s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter)); - s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter)); - s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter)); + s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter)); + s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter)); - s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter)); - s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter)); + s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter)); + s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter)); - s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter)); - s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter)); + s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter)); + s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter)); - s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter)); - s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter)); + s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter)); + s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter)); - s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter)); - s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter)); - #if !(NETCF || NETSTANDARD1_3) - s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter)); + s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter)); s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter)); #endif - s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter)); - s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter)); + s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter)); + s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter)); - // For backwards compatibility the NDC patterns - s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter)); - s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter)); + // For backwards compatibility the NDC patterns + s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter)); + s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter)); - // For backwards compatibility the MDC patterns just do a property lookup - s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter)); + // For backwards compatibility the MDC patterns just do a property lookup + s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter)); - s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); + s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter)); + s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); - s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter)); - s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); + s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter)); + s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); - s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter)); - s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); - } + s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter)); + s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); + } + + /// + /// Initializes a new instance of the class. + /// Constructs a PatternLayout using the DefaultConversionPattern. + /// + /// + /// + /// The default pattern just produces the application supplied message. + /// + /// + /// Note to Inheritors: This constructor calls the virtual method + /// . If you override this method be + /// aware that it will be called before your is called constructor. + /// + /// + /// As per the contract the + /// method must be called after the properties on this object have been + /// configured. + /// + /// + public PatternLayout() + : this(DefaultConversionPattern) + { + } + + /// + /// Initializes a new instance of the class. + /// Constructs a PatternLayout using the supplied conversion pattern. + /// + /// the pattern to use. + /// + /// + /// Note to Inheritors: This constructor calls the virtual method + /// . If you override this method be + /// aware that it will be called before your is called constructor. + /// + /// + /// When using this constructor the method + /// need not be called. This may not be the case when using a subclass. + /// + /// + public PatternLayout(string pattern) + { + // By default we do not process the exception + this.IgnoresException = true; - #endregion Static Constructor - - #region Constructors - - /// - /// Constructs a PatternLayout using the DefaultConversionPattern - /// - /// - /// - /// The default pattern just produces the application supplied message. - /// - /// - /// Note to Inheritors: This constructor calls the virtual method - /// . If you override this method be - /// aware that it will be called before your is called constructor. - /// - /// - /// As per the contract the - /// method must be called after the properties on this object have been - /// configured. - /// - /// - public PatternLayout() : this(DefaultConversionPattern) - { - } - - /// - /// Constructs a PatternLayout using the supplied conversion pattern - /// - /// the pattern to use - /// - /// - /// Note to Inheritors: This constructor calls the virtual method - /// . If you override this method be - /// aware that it will be called before your is called constructor. - /// - /// - /// When using this constructor the method - /// need not be called. This may not be the case when using a subclass. - /// - /// - public PatternLayout(string pattern) - { - // By default we do not process the exception - IgnoresException = true; - - m_pattern = pattern; - if (m_pattern == null) - { - m_pattern = DefaultConversionPattern; - } - - ActivateOptions(); - } + this.m_pattern = pattern; + if (this.m_pattern == null) + { + this.m_pattern = DefaultConversionPattern; + } - #endregion - - /// - /// The pattern formatting string - /// - /// - /// - /// The ConversionPattern option. This is the string which - /// controls formatting and consists of a mix of literal content and - /// conversion specifiers. - /// - /// - public string ConversionPattern - { - get { return m_pattern; } - set { m_pattern = value; } - } + this.ActivateOptions(); + } + + /// + /// Gets or sets the pattern formatting string. + /// + /// + /// + /// The ConversionPattern option. This is the string which + /// controls formatting and consists of a mix of literal content and + /// conversion specifiers. + /// + /// + public string ConversionPattern + { + get { return this.m_pattern; } + set { this.m_pattern = value; } + } - /// - /// Create the pattern parser instance - /// - /// the pattern to parse - /// The that will format the event - /// - /// - /// Creates the used to parse the conversion string. Sets the - /// global and instance rules on the . - /// - /// - virtual protected PatternParser CreatePatternParser(string pattern) - { - PatternParser patternParser = new PatternParser(pattern); + /// + /// Create the pattern parser instance. + /// + /// the pattern to parse. + /// The that will format the event. + /// + /// + /// Creates the used to parse the conversion string. Sets the + /// global and instance rules on the . + /// + /// + protected virtual PatternParser CreatePatternParser(string pattern) + { + PatternParser patternParser = new PatternParser(pattern); - // Add all the builtin patterns - foreach(DictionaryEntry entry in s_globalRulesRegistry) - { + // Add all the builtin patterns + foreach (DictionaryEntry entry in s_globalRulesRegistry) + { ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = (string)entry.Key; converterInfo.Type = (Type)entry.Value; patternParser.PatternConverters[entry.Key] = converterInfo; - } - // Add the instance patterns - foreach(DictionaryEntry entry in m_instanceRulesRegistry) - { - patternParser.PatternConverters[entry.Key] = entry.Value; - } - - return patternParser; - } - - #region Implementation of IOptionHandler - - /// - /// Initialize layout options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { - m_head = CreatePatternParser(m_pattern).Parse(); - - PatternConverter curConverter = m_head; - while(curConverter != null) - { - PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter; - if (layoutConverter != null) - { - if (!layoutConverter.IgnoresException) - { - // Found converter that handles the exception - this.IgnoresException = false; - - break; - } - } - curConverter = curConverter.Next; - } - } - - #endregion - - #region Override implementation of LayoutSkeleton - - /// - /// Produces a formatted string as specified by the conversion pattern. - /// - /// the event being logged - /// The TextWriter to write the formatted event to - /// - /// - /// Parse the using the patter format - /// specified in the property. - /// - /// - override public void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (writer == null) - { - throw new ArgumentNullException("writer"); - } - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } + } + + // Add the instance patterns + foreach (DictionaryEntry entry in this.m_instanceRulesRegistry) + { + patternParser.PatternConverters[entry.Key] = entry.Value; + } - PatternConverter c = m_head; + return patternParser; + } + + /// + /// Initialize layout options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + this.m_head = this.CreatePatternParser(this.m_pattern).Parse(); - // loop through the chain of pattern converters - while(c != null) - { - c.Format(writer, loggingEvent); - c = c.Next; - } - } + PatternConverter curConverter = this.m_head; + while (curConverter != null) + { + PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter; + if (layoutConverter != null) + { + if (!layoutConverter.IgnoresException) + { + // Found converter that handles the exception + this.IgnoresException = false; - #endregion + break; + } + } + + curConverter = curConverter.Next; + } + } + + /// + /// Produces a formatted string as specified by the conversion pattern. + /// + /// the event being logged. + /// The TextWriter to write the formatted event to. + /// + /// + /// Parse the using the patter format + /// specified in the property. + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - /// - /// Add a converter to this PatternLayout - /// - /// the converter info - /// - /// - /// This version of the method is used by the configurator. - /// Programmatic users should use the alternative method. - /// - /// - public void AddConverter(ConverterInfo converterInfo) - { - if (converterInfo == null) throw new ArgumentNullException("converterInfo"); + PatternConverter c = this.m_head; + // loop through the chain of pattern converters + while (c != null) + { + c.Format(writer, loggingEvent); + c = c.Next; + } + } + + /// + /// Add a converter to this PatternLayout. + /// + /// the converter info. + /// + /// + /// This version of the method is used by the configurator. + /// Programmatic users should use the alternative method. + /// + /// + public void AddConverter(ConverterInfo converterInfo) + { + if (converterInfo == null) + { + throw new ArgumentNullException("converterInfo"); + } + if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) { throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); } - m_instanceRulesRegistry[converterInfo.Name] = converterInfo; - } - - /// - /// Add a converter to this PatternLayout - /// - /// the name of the conversion pattern for this converter - /// the type of the converter - /// - /// - /// Add a named pattern converter to this instance. This - /// converter will be used in the formatting of the event. - /// This method must be called before . - /// - /// - /// The specified must extend the - /// type. - /// - /// - public void AddConverter(string name, Type type) - { - if (name == null) throw new ArgumentNullException("name"); - if (type == null) throw new ArgumentNullException("type"); + + this.m_instanceRulesRegistry[converterInfo.Name] = converterInfo; + } + /// + /// Add a converter to this PatternLayout. + /// + /// the name of the conversion pattern for this converter. + /// the type of the converter. + /// + /// + /// Add a named pattern converter to this instance. This + /// converter will be used in the formatting of the event. + /// This method must be called before . + /// + /// + /// The specified must extend the + /// type. + /// + /// + public void AddConverter(string name, Type type) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = name; converterInfo.Type = type; - AddConverter(converterInfo); - } - } + this.AddConverter(converterInfo); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs index 1b5a4beac11..afb348103e7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs @@ -1,27 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETSTANDARD1_3 using System.Reflection; #endif @@ -32,64 +12,79 @@ namespace log4net.Layout { - /// - /// Type converter for the interface - /// - /// - /// - /// Used to convert objects to the interface. - /// Supports converting from the interface to - /// the interface using the . - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class RawLayoutConverter : IConvertFrom - { - #region Override Implementation of IRawLayout - - /// - /// Can the sourceType be converted to an - /// - /// the source to be to be converted - /// true if the source type can be converted to - /// - /// - /// Test if the can be converted to a - /// . Only is supported - /// as the . - /// - /// - public bool CanConvertFrom(Type sourceType) - { - // Accept an ILayout object - return (typeof(ILayout).IsAssignableFrom(sourceType)); - } - - /// - /// Convert the value to a object - /// - /// the value to convert - /// the object - /// - /// - /// Convert the object to a - /// object. If the object - /// is a then the - /// is used to adapt between the two interfaces, otherwise an - /// exception is thrown. - /// - /// - public object ConvertFrom(object source) - { - ILayout layout = source as ILayout; - if (layout != null) - { - return new Layout2RawLayoutAdapter(layout); - } - throw ConversionNotSupportedException.Create(typeof(IRawLayout), source); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Type converter for the interface. + /// + /// + /// + /// Used to convert objects to the interface. + /// Supports converting from the interface to + /// the interface using the . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class RawLayoutConverter : IConvertFrom + { + /// + /// Can the sourceType be converted to an . + /// + /// the source to be to be converted. + /// true if the source type can be converted to . + /// + /// + /// Test if the can be converted to a + /// . Only is supported + /// as the . + /// + /// + public bool CanConvertFrom(Type sourceType) + { + // Accept an ILayout object + return typeof(ILayout).IsAssignableFrom(sourceType); + } - #endregion - } + /// + /// Convert the value to a object. + /// + /// the value to convert. + /// the object. + /// + /// + /// Convert the object to a + /// object. If the object + /// is a then the + /// is used to adapt between the two interfaces, otherwise an + /// exception is thrown. + /// + /// + public object ConvertFrom(object source) + { + ILayout layout = source as ILayout; + if (layout != null) + { + return new Layout2RawLayoutAdapter(layout); + } + + throw ConversionNotSupportedException.Create(typeof(IRawLayout), source); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs index 5f5f1f03090..fef198bc147 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs @@ -1,94 +1,84 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; - -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Extract the value of a property from the - /// - /// - /// - /// Extract the value of a property from the - /// - /// - /// Nicko Cadell - public class RawPropertyLayout : IRawLayout - { - #region Constructors - - /// - /// Constructs a RawPropertyLayout - /// - public RawPropertyLayout() - { - } - - #endregion - - private string m_key; - - /// - /// The name of the value to lookup in the LoggingEvent Properties collection. - /// - /// - /// Value to lookup in the LoggingEvent Properties collection - /// - /// - /// - /// String name of the property to lookup in the . - /// - /// - public string Key - { - get { return m_key; } - set { m_key = value; } - } - - #region Implementation of IRawLayout - - /// - /// Lookup the property for - /// - /// The event to format - /// returns property value - /// - /// - /// Looks up and returns the object value of the property - /// named . If there is no property defined - /// with than name then null will be returned. - /// - /// - public virtual object Format(LoggingEvent loggingEvent) - { - return loggingEvent.LookupProperty(m_key); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + using log4net.Core; + using log4net.Util; + + /// + /// Extract the value of a property from the . + /// + /// + /// + /// Extract the value of a property from the . + /// + /// + /// Nicko Cadell. + public class RawPropertyLayout : IRawLayout + { + /// + /// Initializes a new instance of the class. + /// Constructs a RawPropertyLayout. + /// + public RawPropertyLayout() + { + } + + private string m_key; - #endregion - } + /// + /// Gets or sets the name of the value to lookup in the LoggingEvent Properties collection. + /// + /// + /// Value to lookup in the LoggingEvent Properties collection. + /// + /// + /// + /// String name of the property to lookup in the . + /// + /// + public string Key + { + get { return this.m_key; } + set { this.m_key = value; } + } + + /// + /// Lookup the property for . + /// + /// The event to format. + /// returns property value. + /// + /// + /// Looks up and returns the object value of the property + /// named . If there is no property defined + /// with than name then null will be returned. + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + return loggingEvent.LookupProperty(this.m_key); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs index a9bcfcf1945..d922cf357a7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs @@ -1,78 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; - -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Extract the date from the - /// - /// - /// - /// Extract the date from the - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class RawTimeStampLayout : IRawLayout - { - #region Constructors - - /// - /// Constructs a RawTimeStampLayout - /// - public RawTimeStampLayout() - { - } - - #endregion - - #region Implementation of IRawLayout - - /// - /// Gets the as a . - /// - /// The event to format - /// returns the time stamp - /// - /// - /// Gets the as a . - /// - /// - /// The time stamp is in local time. To format the time stamp - /// in universal time use . - /// - /// - public virtual object Format(LoggingEvent loggingEvent) - { - return loggingEvent.TimeStamp; - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + using log4net.Core; + using log4net.Util; + + /// + /// Extract the date from the . + /// + /// + /// + /// Extract the date from the . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class RawTimeStampLayout : IRawLayout + { + /// + /// Initializes a new instance of the class. + /// Constructs a RawTimeStampLayout. + /// + public RawTimeStampLayout() + { + } + + /// + /// Gets the as a . + /// + /// The event to format. + /// returns the time stamp. + /// + /// + /// Gets the as a . + /// + /// + /// The time stamp is in local time. To format the time stamp + /// in universal time use . + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + return loggingEvent.TimeStamp; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs index d7a3d081f72..3691a5a3259 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs @@ -1,78 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; - -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Extract the date from the - /// - /// - /// - /// Extract the date from the - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class RawUtcTimeStampLayout : IRawLayout - { - #region Constructors - - /// - /// Constructs a RawUtcTimeStampLayout - /// - public RawUtcTimeStampLayout() - { - } - - #endregion - - #region Implementation of IRawLayout - - /// - /// Gets the as a . - /// - /// The event to format - /// returns the time stamp - /// - /// - /// Gets the as a . - /// - /// - /// The time stamp is in universal time. To format the time stamp - /// in local time use . - /// - /// - public virtual object Format(LoggingEvent loggingEvent) - { - return loggingEvent.TimeStampUtc; - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + using log4net.Core; + using log4net.Util; + + /// + /// Extract the date from the . + /// + /// + /// + /// Extract the date from the . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class RawUtcTimeStampLayout : IRawLayout + { + /// + /// Initializes a new instance of the class. + /// Constructs a RawUtcTimeStampLayout. + /// + public RawUtcTimeStampLayout() + { + } + + /// + /// Gets the as a . + /// + /// The event to format. + /// returns the time stamp. + /// + /// + /// Gets the as a . + /// + /// + /// The time stamp is in universal time. To format the time stamp + /// in local time use . + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + return loggingEvent.TimeStampUtc; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs index 6489512537f..c877deac11e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs @@ -1,115 +1,101 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; -using System.Text; - -using log4net.Util; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// A very simple layout - /// - /// - /// - /// SimpleLayout consists of the level of the log statement, - /// followed by " - " and then the log message itself. For example, - /// - /// DEBUG - Hello world - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class SimpleLayout : LayoutSkeleton - { - #region Constructors - - /// - /// Constructs a SimpleLayout - /// - public SimpleLayout() - { - IgnoresException = true; - } - - #endregion - - #region Implementation of IOptionHandler - - /// - /// Initialize layout options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { - // nothing to do. - } - - #endregion - - #region Override implementation of LayoutSkeleton - - /// - /// Produces a simple formatted output. - /// - /// the event being logged - /// The TextWriter to write the formatted event to - /// - /// - /// Formats the event as the level of the even, - /// followed by " - " and then the log message itself. The - /// output is terminated by a newline. - /// - /// - override public void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - writer.Write(loggingEvent.Level.DisplayName); - writer.Write(" - "); - loggingEvent.WriteRenderedMessage(writer); - writer.WriteLine(); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.Util; + + /// + /// A very simple layout. + /// + /// + /// + /// SimpleLayout consists of the level of the log statement, + /// followed by " - " and then the log message itself. For example. + /// + /// DEBUG - Hello world + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class SimpleLayout : LayoutSkeleton + { + /// + /// Initializes a new instance of the class. + /// Constructs a SimpleLayout. + /// + public SimpleLayout() + { + this.IgnoresException = true; + } + + /// + /// Initialize layout options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + // nothing to do. + } + + /// + /// Produces a simple formatted output. + /// + /// the event being logged. + /// The TextWriter to write the formatted event to. + /// + /// + /// Formats the event as the level of the even, + /// followed by " - " and then the log message itself. The + /// output is terminated by a newline. + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - #endregion - } + writer.Write(loggingEvent.Level.DisplayName); + writer.Write(" - "); + loggingEvent.WriteRenderedMessage(writer); + writer.WriteLine(); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs index 85963ce6a9f..ea43f0c3ed9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs @@ -1,367 +1,344 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.Xml; - -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Layout that formats the log events as XML elements. - /// - /// - /// - /// The output of the consists of a series of - /// log4net:event elements. It does not output a complete well-formed XML - /// file. The output is designed to be included as an external entity - /// in a separate file to form a correct XML file. - /// - /// - /// For example, if abc is the name of the file where - /// the output goes, then a well-formed XML file would - /// be: - /// - /// - /// <?xml version="1.0" ?> - /// - /// <!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [<!ENTITY data SYSTEM "abc">]> - /// - /// <log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2> - /// &data; - /// </log4net:events> - /// - /// - /// This approach enforces the independence of the - /// and the appender where it is embedded. - /// - /// - /// The version attribute helps components to correctly - /// interpret output generated by . The value of - /// this attribute should be "1.2" for release 1.2 and later. - /// - /// - /// Alternatively the Header and Footer properties can be - /// configured to output the correct XML header, open tag and close tag. - /// When setting the Header and Footer properties it is essential - /// that the underlying data store not be appendable otherwise the data - /// will become invalid XML. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class XmlLayout : XmlLayoutBase - { - #region Public Instance Constructors - - /// - /// Constructs an XmlLayout - /// - public XmlLayout() : base() - { - } - - /// - /// Constructs an XmlLayout. - /// - /// - /// - /// The LocationInfo option takes a boolean value. By - /// default, it is set to false which means there will be no location - /// information output by this layout. If the the option is set to - /// true, then the file name and line number of the statement - /// at the origin of the log statement will be output. - /// - /// - /// If you are embedding this layout within an SmtpAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - public XmlLayout(bool locationInfo) : base(locationInfo) - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// The prefix to use for all element names - /// - /// - /// - /// The default prefix is log4net. Set this property - /// to change the prefix. If the prefix is set to an empty string - /// then no prefix will be written. - /// - /// - public string Prefix - { - get { return m_prefix; } - set { m_prefix = value; } - } - - - /// - /// Set whether or not to base64 encode the message. - /// - /// - /// - /// By default the log message will be written as text to the xml - /// output. This can cause problems when the message contains binary - /// data. By setting this to true the contents of the message will be - /// base64 encoded. If this is set then invalid character replacement - /// (see ) will not be performed - /// on the log message. - /// - /// - public bool Base64EncodeMessage - { - get {return m_base64Message;} - set {m_base64Message=value;} - } - - /// - /// Set whether or not to base64 encode the property values. - /// - /// - /// - /// By default the properties will be written as text to the xml - /// output. This can cause problems when one or more properties contain - /// binary data. By setting this to true the values of the properties - /// will be base64 encoded. If this is set then invalid character replacement - /// (see ) will not be performed - /// on the property values. - /// - /// - public bool Base64EncodeProperties - { - get {return m_base64Properties;} - set {m_base64Properties=value;} - } - - - #endregion Public Instance Properties - - #region Implementation of IOptionHandler - - /// - /// Initialize layout options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Builds a cache of the element names - /// - /// - override public void ActivateOptions() - { - base.ActivateOptions(); - - // Cache the full element names including the prefix - if (m_prefix != null && m_prefix.Length > 0) - { - m_elmEvent = m_prefix + ":" + ELM_EVENT; - m_elmMessage = m_prefix + ":" + ELM_MESSAGE; - m_elmProperties = m_prefix + ":" + ELM_PROPERTIES; - m_elmData = m_prefix + ":" + ELM_DATA; - m_elmException = m_prefix + ":" + ELM_EXCEPTION; - m_elmLocation = m_prefix + ":" + ELM_LOCATION; - } - } - - #endregion Implementation of IOptionHandler - - #region Override implementation of XMLLayoutBase - - /// - /// Does the actual writing of the XML. - /// - /// The writer to use to output the event to. - /// The event to write. - /// - /// - /// Override the base class method - /// to write the to the . - /// - /// - override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) - { - writer.WriteStartElement(m_elmEvent); - writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + using System.Xml; + + using log4net.Core; + using log4net.Util; + + /// + /// Layout that formats the log events as XML elements. + /// + /// + /// + /// The output of the consists of a series of + /// log4net:event elements. It does not output a complete well-formed XML + /// file. The output is designed to be included as an external entity + /// in a separate file to form a correct XML file. + /// + /// + /// For example, if abc is the name of the file where + /// the output goes, then a well-formed XML file would + /// be: + /// + /// + /// <?xml version="1.0" ?> + /// + /// <!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [<!ENTITY data SYSTEM "abc">]> + /// + /// <log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2> + /// &data; + /// </log4net:events> + /// + /// + /// This approach enforces the independence of the + /// and the appender where it is embedded. + /// + /// + /// The version attribute helps components to correctly + /// interpret output generated by . The value of + /// this attribute should be "1.2" for release 1.2 and later. + /// + /// + /// Alternatively the Header and Footer properties can be + /// configured to output the correct XML header, open tag and close tag. + /// When setting the Header and Footer properties it is essential + /// that the underlying data store not be appendable otherwise the data + /// will become invalid XML. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class XmlLayout : XmlLayoutBase + { + /// + /// Initializes a new instance of the class. + /// Constructs an XmlLayout. + /// + public XmlLayout() + : base() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructs an XmlLayout. + /// + /// + /// + /// The LocationInfo option takes a boolean value. By + /// default, it is set to false which means there will be no location + /// information output by this layout. If the the option is set to + /// true, then the file name and line number of the statement + /// at the origin of the log statement will be output. + /// + /// + /// If you are embedding this layout within an SmtpAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + public XmlLayout(bool locationInfo) + : base(locationInfo) + { + } + + /// + /// Gets or sets the prefix to use for all element names. + /// + /// + /// + /// The default prefix is log4net. Set this property + /// to change the prefix. If the prefix is set to an empty string + /// then no prefix will be written. + /// + /// + public string Prefix + { + get { return this.m_prefix; } + set { this.m_prefix = value; } + } + + /// + /// Gets or sets a value indicating whether set whether or not to base64 encode the message. + /// + /// + /// + /// By default the log message will be written as text to the xml + /// output. This can cause problems when the message contains binary + /// data. By setting this to true the contents of the message will be + /// base64 encoded. If this is set then invalid character replacement + /// (see ) will not be performed + /// on the log message. + /// + /// + public bool Base64EncodeMessage + { + get { return this.m_base64Message; } + set { this.m_base64Message = value; } + } + + /// + /// Gets or sets a value indicating whether set whether or not to base64 encode the property values. + /// + /// + /// + /// By default the properties will be written as text to the xml + /// output. This can cause problems when one or more properties contain + /// binary data. By setting this to true the values of the properties + /// will be base64 encoded. If this is set then invalid character replacement + /// (see ) will not be performed + /// on the property values. + /// + /// + public bool Base64EncodeProperties + { + get { return this.m_base64Properties; } + set { this.m_base64Properties = value; } + } + + /// + /// Initialize layout options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Builds a cache of the element names. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + // Cache the full element names including the prefix + if (this.m_prefix != null && this.m_prefix.Length > 0) + { + this.m_elmEvent = this.m_prefix + ":" + ELM_EVENT; + this.m_elmMessage = this.m_prefix + ":" + ELM_MESSAGE; + this.m_elmProperties = this.m_prefix + ":" + ELM_PROPERTIES; + this.m_elmData = this.m_prefix + ":" + ELM_DATA; + this.m_elmException = this.m_prefix + ":" + ELM_EXCEPTION; + this.m_elmLocation = this.m_prefix + ":" + ELM_LOCATION; + } + } + + /// + /// Does the actual writing of the XML. + /// + /// The writer to use to output the event to. + /// The event to write. + /// + /// + /// Override the base class method + /// to write the to the . + /// + /// + protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) + { + writer.WriteStartElement(this.m_elmEvent); + writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); #if NET_2_0 || NETCF_2_0 || MONO_2_0 || NETSTANDARD1_3 - writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); + writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); #else writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp)); #endif - writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); - writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); - - if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) - { - writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); - } - if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) - { - writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); - } - if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) - { - writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); - } - - // Append the message text - writer.WriteStartElement(m_elmMessage); - if (!this.Base64EncodeMessage) - { - Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); - } - else - { - byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); - string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); - Transform.WriteEscapedXmlString(writer, base64Message,this.InvalidCharReplacement); - } - writer.WriteEndElement(); - - PropertiesDictionary properties = loggingEvent.GetProperties(); - - // Append the properties text - if (properties.Count > 0) - { - writer.WriteStartElement(m_elmProperties); - foreach(System.Collections.DictionaryEntry entry in properties) - { - writer.WriteStartElement(m_elmData); - writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key,this.InvalidCharReplacement)); - - // Use an ObjectRenderer to convert the object to a string - string valueStr =null; - if (!this.Base64EncodeProperties) - { - valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value),this.InvalidCharReplacement); - } - else - { - byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); - valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); - } - writer.WriteAttributeString(ATTR_VALUE, valueStr); - - writer.WriteEndElement(); - } - writer.WriteEndElement(); - } - - string exceptionStr = loggingEvent.GetExceptionString(); - if (exceptionStr != null && exceptionStr.Length > 0) - { - // Append the stack trace line - writer.WriteStartElement(m_elmException); - Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); - writer.WriteEndElement(); - } - - if (LocationInfo) - { - LocationInfo locationInfo = loggingEvent.LocationInformation; - - writer.WriteStartElement(m_elmLocation); - writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); - writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); - writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); - writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); - writer.WriteEndElement(); - } - - writer.WriteEndElement(); - } - - #endregion Override implementation of XMLLayoutBase - - #region Private Instance Fields - - /// - /// The prefix to use for all generated element names - /// - private string m_prefix = PREFIX; - - private string m_elmEvent = ELM_EVENT; - private string m_elmMessage = ELM_MESSAGE; - private string m_elmData = ELM_DATA; - private string m_elmProperties = ELM_PROPERTIES; - private string m_elmException = ELM_EXCEPTION; - private string m_elmLocation = ELM_LOCATION; - - private bool m_base64Message=false; - private bool m_base64Properties=false; - - #endregion Private Instance Fields - - #region Private Static Fields - - private const string PREFIX = "log4net"; - - private const string ELM_EVENT = "event"; - private const string ELM_MESSAGE = "message"; - private const string ELM_PROPERTIES = "properties"; - private const string ELM_GLOBAL_PROPERTIES = "global-properties"; - private const string ELM_DATA = "data"; - private const string ELM_EXCEPTION = "exception"; - private const string ELM_LOCATION = "locationInfo"; - - private const string ATTR_LOGGER = "logger"; - private const string ATTR_TIMESTAMP = "timestamp"; - private const string ATTR_LEVEL = "level"; - private const string ATTR_THREAD = "thread"; - private const string ATTR_DOMAIN = "domain"; - private const string ATTR_IDENTITY = "identity"; - private const string ATTR_USERNAME = "username"; - private const string ATTR_CLASS = "class"; - private const string ATTR_METHOD = "method"; - private const string ATTR_FILE = "file"; - private const string ATTR_LINE = "line"; - private const string ATTR_NAME = "name"; - private const string ATTR_VALUE = "value"; - - - #endregion Private Static Fields - } -} - + writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); + writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); + + if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) + { + writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); + } + + if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) + { + writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); + } + + if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) + { + writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); + } + + // Append the message text + writer.WriteStartElement(this.m_elmMessage); + if (!this.Base64EncodeMessage) + { + Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); + } + else + { + byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); + string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); + Transform.WriteEscapedXmlString(writer, base64Message, this.InvalidCharReplacement); + } + + writer.WriteEndElement(); + + PropertiesDictionary properties = loggingEvent.GetProperties(); + + // Append the properties text + if (properties.Count > 0) + { + writer.WriteStartElement(this.m_elmProperties); + foreach (System.Collections.DictionaryEntry entry in properties) + { + writer.WriteStartElement(this.m_elmData); + writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key, this.InvalidCharReplacement)); + + // Use an ObjectRenderer to convert the object to a string + string valueStr = null; + if (!this.Base64EncodeProperties) + { + valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value), this.InvalidCharReplacement); + } + else + { + byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); + valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); + } + + writer.WriteAttributeString(ATTR_VALUE, valueStr); + + writer.WriteEndElement(); + } + + writer.WriteEndElement(); + } + + string exceptionStr = loggingEvent.GetExceptionString(); + if (exceptionStr != null && exceptionStr.Length > 0) + { + // Append the stack trace line + writer.WriteStartElement(this.m_elmException); + Transform.WriteEscapedXmlString(writer, exceptionStr, this.InvalidCharReplacement); + writer.WriteEndElement(); + } + + if (this.LocationInfo) + { + LocationInfo locationInfo = loggingEvent.LocationInformation; + + writer.WriteStartElement(this.m_elmLocation); + writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); + writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); + writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); + writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); + } + + /// + /// The prefix to use for all generated element names. + /// + private string m_prefix = PREFIX; + + private string m_elmEvent = ELM_EVENT; + private string m_elmMessage = ELM_MESSAGE; + private string m_elmData = ELM_DATA; + private string m_elmProperties = ELM_PROPERTIES; + private string m_elmException = ELM_EXCEPTION; + private string m_elmLocation = ELM_LOCATION; + + private bool m_base64Message = false; + private bool m_base64Properties = false; + private const string PREFIX = "log4net"; + + private const string ELM_EVENT = "event"; + private const string ELM_MESSAGE = "message"; + private const string ELM_PROPERTIES = "properties"; + private const string ELM_GLOBAL_PROPERTIES = "global-properties"; + private const string ELM_DATA = "data"; + private const string ELM_EXCEPTION = "exception"; + private const string ELM_LOCATION = "locationInfo"; + + private const string ATTR_LOGGER = "logger"; + private const string ATTR_TIMESTAMP = "timestamp"; + private const string ATTR_LEVEL = "level"; + private const string ATTR_THREAD = "thread"; + private const string ATTR_DOMAIN = "domain"; + private const string ATTR_IDENTITY = "identity"; + private const string ATTR_USERNAME = "username"; + private const string ATTR_CLASS = "class"; + private const string ATTR_METHOD = "method"; + private const string ATTR_FILE = "file"; + private const string ATTR_LINE = "line"; + private const string ATTR_NAME = "name"; + private const string ATTR_VALUE = "value"; + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs index bb26711dd10..f6a750a263c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs @@ -1,205 +1,193 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; -using System.Text; -using System.Xml; - -using log4net.Util; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Layout that formats the log events as XML elements. - /// - /// - /// - /// This is an abstract class that must be subclassed by an implementation - /// to conform to a specific schema. - /// - /// - /// Deriving classes must implement the method. - /// - /// - /// Nicko Cadell - /// Gert Driesen - abstract public class XmlLayoutBase : LayoutSkeleton - { - #region Protected Instance Constructors - - /// - /// Protected constructor to support subclasses - /// - /// - /// - /// Initializes a new instance of the class - /// with no location info. - /// - /// - protected XmlLayoutBase() : this(false) - { - IgnoresException = false; - } - - /// - /// Protected constructor to support subclasses - /// - /// - /// - /// The parameter determines whether - /// location information will be output by the layout. If - /// is set to true, then the - /// file name and line number of the statement at the origin of the log - /// statement will be output. - /// - /// - /// If you are embedding this layout within an SMTPAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - protected XmlLayoutBase(bool locationInfo) - { - IgnoresException = false; - m_locationInfo = locationInfo; - } - - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets a value indicating whether to include location information in - /// the XML events. - /// - /// - /// true if location information should be included in the XML - /// events; otherwise, false. - /// - /// - /// - /// If is set to true, then the file - /// name and line number of the statement at the origin of the log - /// statement will be output. - /// - /// - /// If you are embedding this layout within an SMTPAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - public bool LocationInfo - { - get { return m_locationInfo; } - set { m_locationInfo = value; } - } - /// - /// The string to replace characters that can not be expressed in XML with. - /// - /// - /// Not all characters may be expressed in XML. This property contains the - /// string to replace those that can not with. This defaults to a ?. Set it - /// to the empty string to simply remove offending characters. For more - /// details on the allowed character ranges see http://www.w3.org/TR/REC-xml/#charsets - /// Character replacement will occur in the log message, the property names - /// and the property values. - /// - /// - /// - public string InvalidCharReplacement - { - get {return m_invalidCharReplacement;} - set {m_invalidCharReplacement=value;} - } - #endregion - - #region Implementation of IOptionHandler - - /// - /// Initialize layout options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - override public void ActivateOptions() - { - // nothing to do - } - - #endregion Implementation of IOptionHandler - - #region Override implementation of LayoutSkeleton - - /// - /// Gets the content type output by this layout. - /// - /// - /// As this is the XML layout, the value is always "text/xml". - /// - /// - /// - /// As this is the XML layout, the value is always "text/xml". - /// - /// - override public string ContentType - { - get { return "text/xml"; } - } - - /// - /// Produces a formatted string. - /// - /// The event being logged. - /// The TextWriter to write the formatted event to - /// - /// - /// Format the and write it to the . - /// - /// - /// This method creates an that writes to the - /// . The is passed - /// to the method. Subclasses should override the - /// method rather than this method. - /// - /// - override public void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + using System.Xml; + + using log4net.Core; + using log4net.Util; + + /// + /// Layout that formats the log events as XML elements. + /// + /// + /// + /// This is an abstract class that must be subclassed by an implementation + /// to conform to a specific schema. + /// + /// + /// Deriving classes must implement the method. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class XmlLayoutBase : LayoutSkeleton + { + /// + /// Initializes a new instance of the class. + /// Protected constructor to support subclasses. + /// + /// + /// + /// Initializes a new instance of the class + /// with no location info. + /// + /// + protected XmlLayoutBase() + : this(false) + { + this.IgnoresException = false; + } + + /// + /// Initializes a new instance of the class. + /// Protected constructor to support subclasses. + /// + /// + /// + /// The parameter determines whether + /// location information will be output by the layout. If + /// is set to true, then the + /// file name and line number of the statement at the origin of the log + /// statement will be output. + /// + /// + /// If you are embedding this layout within an SMTPAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + protected XmlLayoutBase(bool locationInfo) + { + this.IgnoresException = false; + this.m_locationInfo = locationInfo; + } + + /// + /// Gets or sets a value indicating whether to include location information in + /// the XML events. + /// + /// + /// true if location information should be included in the XML + /// events; otherwise, false. + /// + /// + /// + /// If is set to true, then the file + /// name and line number of the statement at the origin of the log + /// statement will be output. + /// + /// + /// If you are embedding this layout within an SMTPAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + public bool LocationInfo + { + get { return this.m_locationInfo; } + set { this.m_locationInfo = value; } + } + + /// + /// Gets or sets the string to replace characters that can not be expressed in XML with. + /// + /// + /// Not all characters may be expressed in XML. This property contains the + /// string to replace those that can not with. This defaults to a ?. Set it + /// to the empty string to simply remove offending characters. For more + /// details on the allowed character ranges see http://www.w3.org/TR/REC-xml/#charsets + /// Character replacement will occur in the log message, the property names + /// and the property values. + /// + /// + /// + public string InvalidCharReplacement + { + get { return this.m_invalidCharReplacement; } + set { this.m_invalidCharReplacement = value; } + } + + /// + /// Initialize layout options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + // nothing to do + } + + /// + /// Gets the content type output by this layout. + /// + /// + /// As this is the XML layout, the value is always "text/xml". + /// + /// + /// + /// As this is the XML layout, the value is always "text/xml". + /// + /// + public override string ContentType + { + get { return "text/xml"; } + } + + /// + /// Produces a formatted string. + /// + /// The event being logged. + /// The TextWriter to write the formatted event to. + /// + /// + /// Format the and write it to the . + /// + /// + /// This method creates an that writes to the + /// . The is passed + /// to the method. Subclasses should override the + /// method rather than this method. + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } #if NETSTANDARD1_3 var settings = new XmlWriterSettings { @@ -208,52 +196,43 @@ override public void Format(TextWriter writer, LoggingEvent loggingEvent) }; var xmlWriter = XmlWriter.Create(new ProtectCloseTextWriter(writer), settings); #else - XmlTextWriter xmlWriter = new XmlTextWriter(new ProtectCloseTextWriter(writer)); - xmlWriter.Formatting = Formatting.None; - xmlWriter.Namespaces = false; + XmlTextWriter xmlWriter = new XmlTextWriter(new ProtectCloseTextWriter(writer)); + xmlWriter.Formatting = Formatting.None; + xmlWriter.Namespaces = false; #endif - // Write the event to the writer - FormatXml(xmlWriter, loggingEvent); - - xmlWriter.WriteWhitespace(SystemInfo.NewLine); - - // Close on xmlWriter will ensure xml is flushed - // the protected writer will ignore the actual close - xmlWriter.Close(); - } - - #endregion Override implementation of LayoutSkeleton - - #region Protected Instance Methods - - /// - /// Does the actual writing of the XML. - /// - /// The writer to use to output the event to. - /// The event to write. - /// - /// - /// Subclasses should override this method to format - /// the as XML. - /// - /// - abstract protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent); - - #endregion Protected Instance Methods - - #region Private Instance Fields - - /// - /// Flag to indicate if location information should be included in - /// the XML events. - /// - private bool m_locationInfo = false; - - /// - /// The string to replace invalid chars with - /// - private string m_invalidCharReplacement="?"; - - #endregion Private Instance Fields - } + + // Write the event to the writer + this.FormatXml(xmlWriter, loggingEvent); + + xmlWriter.WriteWhitespace(SystemInfo.NewLine); + + // Close on xmlWriter will ensure xml is flushed + // the protected writer will ignore the actual close + xmlWriter.Close(); + } + + /// + /// Does the actual writing of the XML. + /// + /// The writer to use to output the event to. + /// The event to write. + /// + /// + /// Subclasses should override this method to format + /// the as XML. + /// + /// + protected abstract void FormatXml(XmlWriter writer, LoggingEvent loggingEvent); + + /// + /// Flag to indicate if location information should be included in + /// the XML events. + /// + private bool m_locationInfo = false; + + /// + /// The string to replace invalid chars with. + /// + private string m_invalidCharReplacement = "?"; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs index 5f48c58aa58..0914d4a7fe4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs @@ -1,113 +1,103 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.Xml; -using System.IO; - -using log4net.Core; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Layout { - /// - /// Layout that formats the log events as XML elements compatible with the log4j schema - /// - /// - /// - /// Formats the log events according to the http://logging.apache.org/log4j schema. - /// - /// - /// Nicko Cadell - public class XmlLayoutSchemaLog4j : XmlLayoutBase - { - #region Static Members - - /// - /// The 1st of January 1970 in UTC - /// - private static readonly DateTime s_date1970 = new DateTime(1970, 1, 1); - - #endregion - - #region Constructors - - /// - /// Constructs an XMLLayoutSchemaLog4j - /// - public XmlLayoutSchemaLog4j() : base() - { - } - - /// - /// Constructs an XMLLayoutSchemaLog4j. - /// - /// - /// - /// The LocationInfo option takes a boolean value. By - /// default, it is set to false which means there will be no location - /// information output by this layout. If the the option is set to - /// true, then the file name and line number of the statement - /// at the origin of the log statement will be output. - /// - /// - /// If you are embedding this layout within an SMTPAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - public XmlLayoutSchemaLog4j(bool locationInfo) : base(locationInfo) - { - } - - #endregion - - #region Public Properties - - /// - /// The version of the log4j schema to use. - /// - /// - /// - /// Only version 1.2 of the log4j schema is supported. - /// - /// - public string Version - { - get { return "1.2"; } - set - { - if (value != "1.2") - { - throw new ArgumentException("Only version 1.2 of the log4j schema is currently supported"); - } - } - } - - #endregion - - /* Example log4j schema event + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + using System.Xml; + + using log4net.Core; + using log4net.Util; + + /// + /// Layout that formats the log events as XML elements compatible with the log4j schema. + /// + /// + /// + /// Formats the log events according to the http://logging.apache.org/log4j schema. + /// + /// + /// Nicko Cadell. + public class XmlLayoutSchemaLog4j : XmlLayoutBase + { + /// + /// The 1st of January 1970 in UTC. + /// + private static readonly DateTime s_date1970 = new DateTime(1970, 1, 1); + + /// + /// Initializes a new instance of the class. + /// Constructs an XMLLayoutSchemaLog4j. + /// + public XmlLayoutSchemaLog4j() + : base() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructs an XMLLayoutSchemaLog4j. + /// + /// + /// + /// The LocationInfo option takes a boolean value. By + /// default, it is set to false which means there will be no location + /// information output by this layout. If the the option is set to + /// true, then the file name and line number of the statement + /// at the origin of the log statement will be output. + /// + /// + /// If you are embedding this layout within an SMTPAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + public XmlLayoutSchemaLog4j(bool locationInfo) + : base(locationInfo) + { + } + + /// + /// Gets or sets the version of the log4j schema to use. + /// + /// + /// + /// Only version 1.2 of the log4j schema is supported. + /// + /// + public string Version + { + get { return "1.2"; } + + set + { + if (value != "1.2") + { + throw new ArgumentException("Only version 1.2 of the log4j schema is currently supported"); + } + } + } + + /* Example log4j schema event @@ -116,7 +106,7 @@ public string Version @@ -126,131 +116,131 @@ at org.apache.log4j.chainsaw.Generator.run(Generator.java:94) - */ - - /* Since log4j 1.3 the log4j:MDC has been combined into the log4j:properties element */ - - /// - /// Actually do the writing of the xml - /// - /// the writer to use - /// the event to write - /// - /// - /// Generate XML that is compatible with the log4j schema. - /// - /// - override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) - { - // Translate logging events for log4j - - // Translate hostname property - if (loggingEvent.LookupProperty(LoggingEvent.HostNameProperty) != null && - loggingEvent.LookupProperty("log4jmachinename") == null) - { - loggingEvent.GetProperties()["log4jmachinename"] = loggingEvent.LookupProperty(LoggingEvent.HostNameProperty); - } - - // translate appdomain name - if (loggingEvent.LookupProperty("log4japp") == null && - loggingEvent.Domain != null && - loggingEvent.Domain.Length > 0) - { - loggingEvent.GetProperties()["log4japp"] = loggingEvent.Domain; - } - - // translate identity name - if (loggingEvent.Identity != null && - loggingEvent.Identity.Length > 0 && - loggingEvent.LookupProperty(LoggingEvent.IdentityProperty) == null) - { - loggingEvent.GetProperties()[LoggingEvent.IdentityProperty] = loggingEvent.Identity; - } - - // translate user name - if (loggingEvent.UserName != null && - loggingEvent.UserName.Length > 0 && - loggingEvent.LookupProperty(LoggingEvent.UserNameProperty) == null) - { - loggingEvent.GetProperties()[LoggingEvent.UserNameProperty] = loggingEvent.UserName; - } - - // Write the start element - writer.WriteStartElement("log4j:event"); - writer.WriteAttributeString("logger", loggingEvent.LoggerName); - - // Calculate the timestamp as the number of milliseconds since january 1970 - // - // We must convert the TimeStamp to UTC before performing any mathematical - // operations. This allows use to take into account discontinuities - // caused by daylight savings time transitions. - TimeSpan timeSince1970 = loggingEvent.TimeStampUtc - s_date1970; - - writer.WriteAttributeString("timestamp", XmlConvert.ToString((long)timeSince1970.TotalMilliseconds)); - writer.WriteAttributeString("level", loggingEvent.Level.DisplayName); - writer.WriteAttributeString("thread", loggingEvent.ThreadName); - - // Append the message text - writer.WriteStartElement("log4j:message"); - Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage,this.InvalidCharReplacement); - writer.WriteEndElement(); - - object ndcObj = loggingEvent.LookupProperty("NDC"); - if (ndcObj != null) - { - string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(ndcObj); - - if (valueStr != null && valueStr.Length > 0) - { - // Append the NDC text - writer.WriteStartElement("log4j:NDC"); - Transform.WriteEscapedXmlString(writer, valueStr,this.InvalidCharReplacement); - writer.WriteEndElement(); - } - } - - // Append the properties text - PropertiesDictionary properties = loggingEvent.GetProperties(); - if (properties.Count > 0) - { - writer.WriteStartElement("log4j:properties"); - foreach(System.Collections.DictionaryEntry entry in properties) - { - writer.WriteStartElement("log4j:data"); - writer.WriteAttributeString("name", (string)entry.Key); - - // Use an ObjectRenderer to convert the object to a string - string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(entry.Value); - writer.WriteAttributeString("value", valueStr); - - writer.WriteEndElement(); - } - writer.WriteEndElement(); - } - - string exceptionStr = loggingEvent.GetExceptionString(); - if (exceptionStr != null && exceptionStr.Length > 0) - { - // Append the stack trace line - writer.WriteStartElement("log4j:throwable"); - Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); - writer.WriteEndElement(); - } - - if (LocationInfo) - { - LocationInfo locationInfo = loggingEvent.LocationInformation; - - writer.WriteStartElement("log4j:locationInfo"); - writer.WriteAttributeString("class", locationInfo.ClassName); - writer.WriteAttributeString("method", locationInfo.MethodName); - writer.WriteAttributeString("file", locationInfo.FileName); - writer.WriteAttributeString("line", locationInfo.LineNumber); - writer.WriteEndElement(); - } - - writer.WriteEndElement(); - } - } -} - + */ + + /* Since log4j 1.3 the log4j:MDC has been combined into the log4j:properties element */ + + /// + /// Actually do the writing of the xml. + /// + /// the writer to use. + /// the event to write. + /// + /// + /// Generate XML that is compatible with the log4j schema. + /// + /// + protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) + { + // Translate logging events for log4j + + // Translate hostname property + if (loggingEvent.LookupProperty(LoggingEvent.HostNameProperty) != null && + loggingEvent.LookupProperty("log4jmachinename") == null) + { + loggingEvent.GetProperties()["log4jmachinename"] = loggingEvent.LookupProperty(LoggingEvent.HostNameProperty); + } + + // translate appdomain name + if (loggingEvent.LookupProperty("log4japp") == null && + loggingEvent.Domain != null && + loggingEvent.Domain.Length > 0) + { + loggingEvent.GetProperties()["log4japp"] = loggingEvent.Domain; + } + + // translate identity name + if (loggingEvent.Identity != null && + loggingEvent.Identity.Length > 0 && + loggingEvent.LookupProperty(LoggingEvent.IdentityProperty) == null) + { + loggingEvent.GetProperties()[LoggingEvent.IdentityProperty] = loggingEvent.Identity; + } + + // translate user name + if (loggingEvent.UserName != null && + loggingEvent.UserName.Length > 0 && + loggingEvent.LookupProperty(LoggingEvent.UserNameProperty) == null) + { + loggingEvent.GetProperties()[LoggingEvent.UserNameProperty] = loggingEvent.UserName; + } + + // Write the start element + writer.WriteStartElement("log4j:event"); + writer.WriteAttributeString("logger", loggingEvent.LoggerName); + + // Calculate the timestamp as the number of milliseconds since january 1970 + // + // We must convert the TimeStamp to UTC before performing any mathematical + // operations. This allows use to take into account discontinuities + // caused by daylight savings time transitions. + TimeSpan timeSince1970 = loggingEvent.TimeStampUtc - s_date1970; + + writer.WriteAttributeString("timestamp", XmlConvert.ToString((long)timeSince1970.TotalMilliseconds)); + writer.WriteAttributeString("level", loggingEvent.Level.DisplayName); + writer.WriteAttributeString("thread", loggingEvent.ThreadName); + + // Append the message text + writer.WriteStartElement("log4j:message"); + Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); + writer.WriteEndElement(); + + object ndcObj = loggingEvent.LookupProperty("NDC"); + if (ndcObj != null) + { + string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(ndcObj); + + if (valueStr != null && valueStr.Length > 0) + { + // Append the NDC text + writer.WriteStartElement("log4j:NDC"); + Transform.WriteEscapedXmlString(writer, valueStr, this.InvalidCharReplacement); + writer.WriteEndElement(); + } + } + + // Append the properties text + PropertiesDictionary properties = loggingEvent.GetProperties(); + if (properties.Count > 0) + { + writer.WriteStartElement("log4j:properties"); + foreach (System.Collections.DictionaryEntry entry in properties) + { + writer.WriteStartElement("log4j:data"); + writer.WriteAttributeString("name", (string)entry.Key); + + // Use an ObjectRenderer to convert the object to a string + string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(entry.Value); + writer.WriteAttributeString("value", valueStr); + + writer.WriteEndElement(); + } + + writer.WriteEndElement(); + } + + string exceptionStr = loggingEvent.GetExceptionString(); + if (exceptionStr != null && exceptionStr.Length > 0) + { + // Append the stack trace line + writer.WriteStartElement("log4j:throwable"); + Transform.WriteEscapedXmlString(writer, exceptionStr, this.InvalidCharReplacement); + writer.WriteEndElement(); + } + + if (this.LocationInfo) + { + LocationInfo locationInfo = loggingEvent.LocationInformation; + + writer.WriteStartElement("log4j:locationInfo"); + writer.WriteAttributeString("class", locationInfo.ClassName); + writer.WriteAttributeString("method", locationInfo.MethodName); + writer.WriteAttributeString("file", locationInfo.FileName); + writer.WriteAttributeString("line", locationInfo.LineNumber); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs b/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs index 46987f9500e..24e04f7697f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs @@ -1,135 +1,126 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Reflection; - -using log4net.Core; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net { - /// - /// This class is used by client applications to request logger instances. - /// - /// - /// - /// This class has static methods that are used by a client to request - /// a logger instance. The method is - /// used to retrieve a logger. - /// - /// - /// See the interface for more details. - /// - /// - /// Simple example of logging messages - /// - /// ILog log = LogManager.GetLogger("application-log"); - /// - /// log.Info("Application Start"); - /// log.Debug("This is a debug message"); - /// - /// if (log.IsDebugEnabled) - /// { - /// log.Debug("This is another debug message"); - /// } - /// - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class LogManager - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private LogManager() - { - } - - #endregion Private Instance Constructors - - #region Type Specific Manager Methods - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Reflection; + + using log4net.Core; + using log4net.Repository; + + /// + /// This class is used by client applications to request logger instances. + /// + /// + /// + /// This class has static methods that are used by a client to request + /// a logger instance. The method is + /// used to retrieve a logger. + /// + /// + /// See the interface for more details. + /// + /// + /// Simple example of logging messages. + /// + /// ILog log = LogManager.GetLogger("application-log"); + /// + /// log.Info("Application Start"); + /// log.Debug("This is a debug message"); + /// + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is another debug message"); + /// } + /// + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class LogManager + { + /// + /// Initializes a new instance of the class. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private LogManager() + { + } + #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - /// Returns the named logger if it exists. - /// - /// Returns the named logger if it exists. - /// - /// - /// - /// If the named logger exists (in the default repository) then it - /// returns a reference to the logger, otherwise it returns null. - /// - /// - /// The fully qualified logger name to look for. - /// The logger found, or null if no logger could be found. - public static ILog Exists(string name) - { - return Exists(Assembly.GetCallingAssembly(), name); - } - - /// Get the currently defined loggers. - /// - /// Returns all the currently defined loggers in the default repository. - /// - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers. - public static ILog[] GetCurrentLoggers() - { - return GetCurrentLoggers(Assembly.GetCallingAssembly()); - } - - /// Get or create a logger. - /// - /// Retrieves or creates a named logger. - /// - /// - /// - /// Retrieves a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - /// The name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(string name) - { - return GetLogger(Assembly.GetCallingAssembly(), name); - } + /// Returns the named logger if it exists. + /// + /// Returns the named logger if it exists. + /// + /// + /// + /// If the named logger exists (in the default repository) then it + /// returns a reference to the logger, otherwise it returns null. + /// + /// + /// The fully qualified logger name to look for. + /// The logger found, or null if no logger could be found. + public static ILog Exists(string name) + { + return Exists(Assembly.GetCallingAssembly(), name); + } + + /// Get the currently defined loggers. + /// + /// Returns all the currently defined loggers in the default repository. + /// + /// + /// The root logger is not included in the returned array. + /// + /// All the defined loggers. + public static ILog[] GetCurrentLoggers() + { + return GetCurrentLoggers(Assembly.GetCallingAssembly()); + } + + /// Get or create a logger. + /// + /// Retrieves or creates a named logger. + /// + /// + /// + /// Retrieves a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + /// The name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(string name) + { + return GetLogger(Assembly.GetCallingAssembly(), name); + } #endif // !NETSTANDARD1_3 /// @@ -145,687 +136,675 @@ public static ILog GetLogger(string name) /// The repository to lookup in. /// The fully qualified logger name to look for. /// - /// The logger found, or null if the logger doesn't exist in the specified + /// The logger found, or null if the logger doesn't exist in the specified /// repository. /// - public static ILog Exists(string repository, string name) - { - return WrapLogger(LoggerManager.Exists(repository, name)); - } - - /// - /// Returns the named logger if it exists. - /// - /// - /// - /// If the named logger exists (in the repository for the specified assembly) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// - /// The assembly to use to lookup the repository. - /// The fully qualified logger name to look for. - /// - /// The logger, or null if the logger doesn't exist in the specified - /// assembly's repository. - /// - public static ILog Exists(Assembly repositoryAssembly, string name) - { - return WrapLogger(LoggerManager.Exists(repositoryAssembly, name)); - } - - /// - /// Returns all the currently defined loggers in the specified repository. - /// - /// The repository to lookup in. - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers. - public static ILog[] GetCurrentLoggers(string repository) - { - return WrapLoggers(LoggerManager.GetCurrentLoggers(repository)); - } - - /// - /// Returns all the currently defined loggers in the specified assembly's repository. - /// - /// The assembly to use to lookup the repository. - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers. - public static ILog[] GetCurrentLoggers(Assembly repositoryAssembly) - { - return WrapLoggers(LoggerManager.GetCurrentLoggers(repositoryAssembly)); - } - - /// - /// Retrieves or creates a named logger. - /// - /// - /// - /// Retrieve a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - /// The repository to lookup in. - /// The name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(string repository, string name) - { - return WrapLogger(LoggerManager.GetLogger(repository, name)); - } - - /// - /// Retrieves or creates a named logger. - /// - /// - /// - /// Retrieve a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - /// The assembly to use to lookup the repository. - /// The name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(Assembly repositoryAssembly, string name) - { - return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, name)); - } - - /// - /// Shorthand for . - /// - /// - /// Get the logger for the fully qualified name of the type specified. - /// - /// The full name of will be used as the name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(Type type) - { + public static ILog Exists(string repository, string name) + { + return WrapLogger(LoggerManager.Exists(repository, name)); + } + + /// + /// Returns the named logger if it exists. + /// + /// + /// + /// If the named logger exists (in the repository for the specified assembly) then it + /// returns a reference to the logger, otherwise it returns + /// null. + /// + /// + /// The assembly to use to lookup the repository. + /// The fully qualified logger name to look for. + /// + /// The logger, or null if the logger doesn't exist in the specified + /// assembly's repository. + /// + public static ILog Exists(Assembly repositoryAssembly, string name) + { + return WrapLogger(LoggerManager.Exists(repositoryAssembly, name)); + } + + /// + /// Returns all the currently defined loggers in the specified repository. + /// + /// The repository to lookup in. + /// + /// The root logger is not included in the returned array. + /// + /// All the defined loggers. + public static ILog[] GetCurrentLoggers(string repository) + { + return WrapLoggers(LoggerManager.GetCurrentLoggers(repository)); + } + + /// + /// Returns all the currently defined loggers in the specified assembly's repository. + /// + /// The assembly to use to lookup the repository. + /// + /// The root logger is not included in the returned array. + /// + /// All the defined loggers. + public static ILog[] GetCurrentLoggers(Assembly repositoryAssembly) + { + return WrapLoggers(LoggerManager.GetCurrentLoggers(repositoryAssembly)); + } + + /// + /// Retrieves or creates a named logger. + /// + /// + /// + /// Retrieve a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + /// The repository to lookup in. + /// The name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(string repository, string name) + { + return WrapLogger(LoggerManager.GetLogger(repository, name)); + } + + /// + /// Retrieves or creates a named logger. + /// + /// + /// + /// Retrieve a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + /// The assembly to use to lookup the repository. + /// The name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(Assembly repositoryAssembly, string name) + { + return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, name)); + } + + /// + /// Shorthand for . + /// + /// + /// Get the logger for the fully qualified name of the type specified. + /// + /// The full name of will be used as the name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(Type type) + { #if NETSTANDARD1_3 return GetLogger(type.GetTypeInfo().Assembly, type.FullName); #else - return GetLogger(Assembly.GetCallingAssembly(), type.FullName); + return GetLogger(Assembly.GetCallingAssembly(), type.FullName); #endif - } - - /// - /// Shorthand for . - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// The repository to lookup in. - /// The full name of will be used as the name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(string repository, Type type) - { - return WrapLogger(LoggerManager.GetLogger(repository, type)); - } - - /// - /// Shorthand for . - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// The assembly to use to lookup the repository. - /// The full name of will be used as the name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(Assembly repositoryAssembly, Type type) - { - return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, type)); - } - - #endregion Type Specific Manager Methods - - #region Domain & Repository Manager Methods - - /// - /// Shuts down the log4net system. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in all the - /// default repositories. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void Shutdown() - { - LoggerManager.Shutdown(); - } + } + + /// + /// Shorthand for . + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// The repository to lookup in. + /// The full name of will be used as the name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(string repository, Type type) + { + return WrapLogger(LoggerManager.GetLogger(repository, type)); + } + + /// + /// Shorthand for . + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// The assembly to use to lookup the repository. + /// The full name of will be used as the name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(Assembly repositoryAssembly, Type type) + { + return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, type)); + } + + /// + /// Shuts down the log4net system. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in all the + /// default repositories. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void Shutdown() + { + LoggerManager.Shutdown(); + } #if !NETSTANDARD1_3 - /// Shutdown a logger repository. - /// - /// Shuts down the default repository. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// default repository. - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void ShutdownRepository() - { - ShutdownRepository(Assembly.GetCallingAssembly()); - } + /// Shutdown a logger repository. + /// + /// Shuts down the default repository. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// default repository. + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void ShutdownRepository() + { + ShutdownRepository(Assembly.GetCallingAssembly()); + } #endif - /// - /// Shuts down the repository for the repository specified. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - /// The repository to shutdown. - public static void ShutdownRepository(string repository) - { - LoggerManager.ShutdownRepository(repository); - } - - /// - /// Shuts down the repository specified. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// repository. The repository is looked up using - /// the specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - /// The assembly to use to lookup the repository. - public static void ShutdownRepository(Assembly repositoryAssembly) - { - LoggerManager.ShutdownRepository(repositoryAssembly); - } + + /// + /// Shuts down the repository for the repository specified. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + /// The repository to shutdown. + public static void ShutdownRepository(string repository) + { + LoggerManager.ShutdownRepository(repository); + } + + /// + /// Shuts down the repository specified. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// repository. The repository is looked up using + /// the specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + /// The assembly to use to lookup the repository. + public static void ShutdownRepository(Assembly repositoryAssembly) + { + LoggerManager.ShutdownRepository(repositoryAssembly); + } #if !NETSTANDARD1_3 - /// Reset the configuration of a repository - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// - /// - /// Resets all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set to its default "off" value. - /// - /// - public static void ResetConfiguration() - { - ResetConfiguration(Assembly.GetCallingAssembly()); - } + /// Reset the configuration of a repository. + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// + /// + /// Resets all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set to its default "off" value. + /// + /// + public static void ResetConfiguration() + { + ResetConfiguration(Assembly.GetCallingAssembly()); + } #endif - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// - /// - /// Reset all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set to its default "off" value. - /// - /// - /// The repository to reset. - public static void ResetConfiguration(string repository) - { - LoggerManager.ResetConfiguration(repository); - } - - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// - /// - /// Reset all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set to its default "off" value. - /// - /// - /// The assembly to use to lookup the repository to reset. - public static void ResetConfiguration(Assembly repositoryAssembly) - { - LoggerManager.ResetConfiguration(repositoryAssembly); - } + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// + /// + /// Reset all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set to its default "off" value. + /// + /// + /// The repository to reset. + public static void ResetConfiguration(string repository) + { + LoggerManager.ResetConfiguration(repository); + } + + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// + /// + /// Reset all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set to its default "off" value. + /// + /// + /// The assembly to use to lookup the repository to reset. + public static void ResetConfiguration(Assembly repositoryAssembly) + { + LoggerManager.ResetConfiguration(repositoryAssembly); + } #if !NETSTANDARD1_3 - /// Get the logger repository. - /// - /// Returns the default instance. - /// - /// - /// - /// Gets the for the repository specified - /// by the callers assembly (). - /// - /// - /// The instance for the default repository. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository() - { - return GetRepository(Assembly.GetCallingAssembly()); - } + /// Get the logger repository. + /// + /// Returns the default instance. + /// + /// + /// + /// Gets the for the repository specified + /// by the callers assembly (). + /// + /// + /// The instance for the default repository. + [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] + public static ILoggerRepository GetLoggerRepository() + { + return GetRepository(Assembly.GetCallingAssembly()); + } #endif - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The repository to lookup in. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(string repository) - { - return GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The assembly to use to lookup the repository. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) - { - return GetRepository(repositoryAssembly); - } + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The repository to lookup in. + [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] + public static ILoggerRepository GetLoggerRepository(string repository) + { + return GetRepository(repository); + } + + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The assembly to use to lookup the repository. + [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] + public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) + { + return GetRepository(repositoryAssembly); + } #if !NETSTANDARD1_3 - /// Get a logger repository. - /// - /// Returns the default instance. - /// - /// - /// - /// Gets the for the repository specified - /// by the callers assembly (). - /// - /// - /// The instance for the default repository. - public static ILoggerRepository GetRepository() - { - return GetRepository(Assembly.GetCallingAssembly()); - } + /// Get a logger repository. + /// + /// Returns the default instance. + /// + /// + /// + /// Gets the for the repository specified + /// by the callers assembly (). + /// + /// + /// The instance for the default repository. + public static ILoggerRepository GetRepository() + { + return GetRepository(Assembly.GetCallingAssembly()); + } #endif - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The repository to lookup in. - public static ILoggerRepository GetRepository(string repository) - { - return LoggerManager.GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The assembly to use to lookup the repository. - public static ILoggerRepository GetRepository(Assembly repositoryAssembly) - { - return LoggerManager.GetRepository(repositoryAssembly); - } + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The repository to lookup in. + public static ILoggerRepository GetRepository(string repository) + { + return LoggerManager.GetRepository(repository); + } + + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The assembly to use to lookup the repository. + public static ILoggerRepository GetRepository(Assembly repositoryAssembly) + { + return LoggerManager.GetRepository(repositoryAssembly); + } #if !NETSTANDARD1_3 - /// Create a domain - /// - /// Creates a repository with the specified repository type. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to will return - /// the same repository instance. - /// - /// - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(Type repositoryType) - { - return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); - } - - /// Create a logger repository. - /// - /// Creates a repository with the specified repository type. - /// - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to will return - /// the same repository instance. - /// - /// - public static ILoggerRepository CreateRepository(Type repositoryType) - { - return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); - } + /// Create a domain. + /// + /// Creates a repository with the specified repository type. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to will return + /// the same repository instance. + /// + /// + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] + public static ILoggerRepository CreateDomain(Type repositoryType) + { + return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); + } + + /// Create a logger repository. + /// + /// Creates a repository with the specified repository type. + /// + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to will return + /// the same repository instance. + /// + /// + public static ILoggerRepository CreateRepository(Type repositoryType) + { + return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); + } #endif - /// - /// Creates a repository with the specified name. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v11.0.0.")] - public static ILoggerRepository CreateDomain(string repository) - { - return LoggerManager.CreateRepository(repository); - } - - /// - /// Creates a repository with the specified name. - /// - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository) - { - return LoggerManager.CreateRepository(repository); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(string repository, Type repositoryType) - { - return LoggerManager.CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository, Type repositoryType) - { - return LoggerManager.CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) - { - return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) - { - return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Gets the list of currently defined repositories. - /// - /// - /// - /// Get an array of all the objects that have been created. - /// - /// - /// An array of all the known objects. - public static ILoggerRepository[] GetAllRepositories() - { - return LoggerManager.GetAllRepositories(); - } - - /// - /// Flushes logging events buffered in all configured appenders in the default repository. - /// - /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed. - /// True if all logging events were flushed successfully, else false. - public static bool Flush(int millisecondsTimeout) - { + /// + /// Creates a repository with the specified name. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v11.0.0.")] + public static ILoggerRepository CreateDomain(string repository) + { + return LoggerManager.CreateRepository(repository); + } + + /// + /// Creates a repository with the specified name. + /// + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository) + { + return LoggerManager.CreateRepository(repository); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] + public static ILoggerRepository CreateDomain(string repository, Type repositoryType) + { + return LoggerManager.CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository, Type repositoryType) + { + return LoggerManager.CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] + public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) + { + return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) + { + return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Gets the list of currently defined repositories. + /// + /// + /// + /// Get an array of all the objects that have been created. + /// + /// + /// An array of all the known objects. + public static ILoggerRepository[] GetAllRepositories() + { + return LoggerManager.GetAllRepositories(); + } + + /// + /// Flushes logging events buffered in all configured appenders in the default repository. + /// + /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed. + /// True if all logging events were flushed successfully, else false. + public static bool Flush(int millisecondsTimeout) + { #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; - if (flushableRepository == null) - { - return false; - } - else - { - return flushableRepository.Flush(millisecondsTimeout); - } + Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; + if (flushableRepository == null) + { + return false; + } + else + { + return flushableRepository.Flush(millisecondsTimeout); + } #else return false; #endif + } + + /// + /// Looks up the wrapper object for the logger specified. + /// + /// The logger to get the wrapper for. + /// The wrapper for the logger specified. + private static ILog WrapLogger(ILogger logger) + { + return (ILog)s_wrapperMap.GetWrapper(logger); + } + + /// + /// Looks up the wrapper objects for the loggers specified. + /// + /// The loggers to get the wrappers for. + /// The wrapper objects for the loggers specified. + private static ILog[] WrapLoggers(ILogger[] loggers) + { + ILog[] results = new ILog[loggers.Length]; + for (int i = 0; i < loggers.Length; i++) + { + results[i] = WrapLogger(loggers[i]); } + + return results; + } - #endregion Domain & Repository Manager Methods - - #region Extension Handlers - - /// - /// Looks up the wrapper object for the logger specified. - /// - /// The logger to get the wrapper for. - /// The wrapper for the logger specified. - private static ILog WrapLogger(ILogger logger) - { - return (ILog)s_wrapperMap.GetWrapper(logger); - } - - /// - /// Looks up the wrapper objects for the loggers specified. - /// - /// The loggers to get the wrappers for. - /// The wrapper objects for the loggers specified. - private static ILog[] WrapLoggers(ILogger[] loggers) - { - ILog[] results = new ILog[loggers.Length]; - for(int i=0; i - /// Create the objects used by - /// this manager. - /// - /// The logger to wrap. - /// The wrapper for the logger specified. - private static ILoggerWrapper WrapperCreationHandler(ILogger logger) - { - return new LogImpl(logger); - } - - #endregion - - #region Private Static Fields - - /// - /// The wrapper map to use to hold the objects. - /// - private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler)); - - #endregion Private Static Fields - } + /// + /// Create the objects used by + /// this manager. + /// + /// The logger to wrap. + /// The wrapper for the logger specified. + private static ILoggerWrapper WrapperCreationHandler(ILogger logger) + { + return new LogImpl(logger); + } + + /// + /// The wrapper map to use to hold the objects. + /// + private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler)); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs index 555fbbc674d..8754e81bcde 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,137 +18,125 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext #if !NETCF using System; using System.Collections; - + using log4net.Util; namespace log4net { - /// - /// The log4net Logical Thread Context. - /// - /// - /// - /// The LogicalThreadContext provides a location for specific debugging - /// information to be stored. - /// The LogicalThreadContext properties override any or - /// properties with the same name. - /// - /// - /// The Logical Thread Context has a properties map and a stack. - /// The properties and stack can - /// be included in the output of log messages. The - /// supports selecting and outputting these properties. - /// - /// - /// The Logical Thread Context provides a diagnostic context for the current call context. - /// This is an instrument for distinguishing interleaved log - /// output from different sources. Log output is typically interleaved - /// when a server handles multiple clients near-simultaneously. - /// - /// - /// The Logical Thread Context is managed on a per basis. - /// - /// - /// The requires a link time - /// for the - /// . - /// If the calling code does not have this permission then this context will be disabled. - /// It will not store any property values set on it. - /// - /// - /// Example of using the thread context properties to store a username. - /// - /// LogicalThreadContext.Properties["user"] = userName; - /// log.Info("This log message has a LogicalThreadContext Property called 'user'"); - /// - /// - /// Example of how to push a message into the context stack - /// - /// using(LogicalThreadContext.Stacks["LDC"].Push("my context message")) - /// { - /// log.Info("This log message has a LogicalThreadContext Stack message that includes 'my context message'"); - /// - /// } // at the end of the using block the message is automatically popped - /// - /// - /// - /// Nicko Cadell - public sealed class LogicalThreadContext - { - #region Private Instance Constructors - - /// - /// Private Constructor. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private LogicalThreadContext() - { - } - - #endregion Private Instance Constructors - - #region Public Static Properties - - /// - /// The thread properties map - /// - /// - /// The thread properties map - /// - /// - /// - /// The LogicalThreadContext properties override any - /// or properties with the same name. - /// - /// - public static LogicalThreadContextProperties Properties - { - get { return s_properties; } - } - - /// - /// The thread stacks - /// - /// - /// stack map - /// - /// - /// - /// The logical thread stacks. - /// - /// - public static LogicalThreadContextStacks Stacks - { - get { return s_stacks; } - } - - #endregion Public Static Properties - - #region Private Static Fields - - /// - /// The thread context properties instance - /// - private readonly static LogicalThreadContextProperties s_properties = new LogicalThreadContextProperties(); + /// + /// The log4net Logical Thread Context. + /// + /// + /// + /// The LogicalThreadContext provides a location for specific debugging + /// information to be stored. + /// The LogicalThreadContext properties override any or + /// properties with the same name. + /// + /// + /// The Logical Thread Context has a properties map and a stack. + /// The properties and stack can + /// be included in the output of log messages. The + /// supports selecting and outputting these properties. + /// + /// + /// The Logical Thread Context provides a diagnostic context for the current call context. + /// This is an instrument for distinguishing interleaved log + /// output from different sources. Log output is typically interleaved + /// when a server handles multiple clients near-simultaneously. + /// + /// + /// The Logical Thread Context is managed on a per basis. + /// + /// + /// The requires a link time + /// for the + /// . + /// If the calling code does not have this permission then this context will be disabled. + /// It will not store any property values set on it. + /// + /// + /// Example of using the thread context properties to store a username. + /// + /// LogicalThreadContext.Properties["user"] = userName; + /// log.Info("This log message has a LogicalThreadContext Property called 'user'"); + /// + /// + /// Example of how to push a message into the context stack. + /// + /// using(LogicalThreadContext.Stacks["LDC"].Push("my context message")) + /// { + /// log.Info("This log message has a LogicalThreadContext Stack message that includes 'my context message'"); + /// + /// } // at the end of the using block the message is automatically popped + /// + /// + /// + /// Nicko Cadell. + public sealed class LogicalThreadContext + { + /// + /// Initializes a new instance of the class. + /// Private Constructor. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private LogicalThreadContext() + { + } + + /// + /// Gets the thread properties map. + /// + /// + /// The thread properties map. + /// + /// + /// + /// The LogicalThreadContext properties override any + /// or properties with the same name. + /// + /// + public static LogicalThreadContextProperties Properties + { + get { return s_properties; } + } - /// - /// The thread context stacks instance - /// - private readonly static LogicalThreadContextStacks s_stacks = new LogicalThreadContextStacks(s_properties); + /// + /// Gets the thread stacks. + /// + /// + /// stack map. + /// + /// + /// + /// The logical thread stacks. + /// + /// + public static LogicalThreadContextStacks Stacks + { + get { return s_stacks; } + } + + /// + /// The thread context properties instance. + /// + private static readonly LogicalThreadContextProperties s_properties = new LogicalThreadContextProperties(); - #endregion Private Static Fields - } + /// + /// The thread context stacks instance. + /// + private static readonly LogicalThreadContextStacks s_stacks = new LogicalThreadContextStacks(s_properties); + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs b/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs index f328dc84cf6..b3ba989e716 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs @@ -1,173 +1,163 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net { - /// - /// Implementation of Mapped Diagnostic Contexts. - /// - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// The MDC class is similar to the class except that it is - /// based on a map instead of a stack. It provides mapped - /// diagnostic contexts. A Mapped Diagnostic Context, or - /// MDC in short, is an instrument for distinguishing interleaved log - /// output from different sources. Log output is typically interleaved - /// when a server handles multiple clients near-simultaneously. - /// - /// - /// The MDC is managed on a per thread basis. - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public sealed class MDC - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private MDC() - { - } - - #endregion Private Instance Constructors - - #region Public Static Methods - - /// - /// Gets the context value identified by the parameter. - /// - /// The key to lookup in the MDC. - /// The string value held for the key, or a null reference if no corresponding value is found. - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// If the parameter does not look up to a - /// previously defined context then null will be returned. - /// - /// - /*[Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v11.0.0.")]*/ - public static string Get(string key) - { - object obj = ThreadContext.Properties[key]; - if (obj == null) - { - return null; - } - return obj.ToString(); - } - - /// - /// Add an entry to the MDC - /// - /// The key to store the value under. - /// The value to store. - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// Puts a context value (the parameter) as identified - /// with the parameter into the current thread's - /// context map. - /// - /// - /// If a value is already defined for the - /// specified then the value will be replaced. If the - /// is specified as null then the key value mapping will be removed. - /// - /// - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public static void Set(string key, string value) - { - ThreadContext.Properties[key] = value; - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// Implementation of Mapped Diagnostic Contexts. + /// + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// The MDC class is similar to the class except that it is + /// based on a map instead of a stack. It provides mapped + /// diagnostic contexts. A Mapped Diagnostic Context, or + /// MDC in short, is an instrument for distinguishing interleaved log + /// output from different sources. Log output is typically interleaved + /// when a server handles multiple clients near-simultaneously. + /// + /// + /// The MDC is managed on a per thread basis. + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] + public sealed class MDC + { + /// + /// Initializes a new instance of the class. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private MDC() + { + } + + /// + /// Gets the context value identified by the parameter. + /// + /// The key to lookup in the MDC. + /// The string value held for the key, or a null reference if no corresponding value is found. + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// If the parameter does not look up to a + /// previously defined context then null will be returned. + /// + /// + /*[Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v11.0.0.")]*/ + public static string Get(string key) + { + object obj = ThreadContext.Properties[key]; + if (obj == null) + { + return null; + } + + return obj.ToString(); + } - /// - /// Removes the key value mapping for the key specified. - /// - /// The key to remove. - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// Remove the specified entry from this thread's MDC - /// - /// - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public static void Remove(string key) - { - ThreadContext.Properties.Remove(key); - } + /// + /// Add an entry to the MDC. + /// + /// The key to store the value under. + /// The value to store. + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// Puts a context value (the parameter) as identified + /// with the parameter into the current thread's + /// context map. + /// + /// + /// If a value is already defined for the + /// specified then the value will be replaced. If the + /// is specified as null then the key value mapping will be removed. + /// + /// + [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] + public static void Set(string key, string value) + { + ThreadContext.Properties[key] = value; + } - /// - /// Clear all entries in the MDC - /// - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// Remove all the entries from this thread's MDC - /// - /// - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public static void Clear() - { - ThreadContext.Properties.Clear(); - } + /// + /// Removes the key value mapping for the key specified. + /// + /// The key to remove. + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// Remove the specified entry from this thread's MDC. + /// + /// + [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] + public static void Remove(string key) + { + ThreadContext.Properties.Remove(key); + } - #endregion Public Static Methods - } + /// + /// Clear all entries in the MDC. + /// + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// Remove all the entries from this thread's MDC. + /// + /// + [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] + public static void Clear() + { + ThreadContext.Properties.Clear(); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs b/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs index fa286b573a2..5165d70013e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs @@ -1,353 +1,338 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETCF_1_0 using Stack = log4net.Util.ThreadContextStack.Stack; #endif namespace log4net { - /// - /// Implementation of Nested Diagnostic Contexts. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// A Nested Diagnostic Context, or NDC in short, is an instrument - /// to distinguish interleaved log output from different sources. Log - /// output is typically interleaved when a server handles multiple - /// clients near-simultaneously. - /// - /// - /// Interleaved log output can still be meaningful if each log entry - /// from different contexts had a distinctive stamp. This is where NDCs - /// come into play. - /// - /// - /// Note that NDCs are managed on a per thread basis. The NDC class - /// is made up of static methods that operate on the context of the - /// calling thread. - /// - /// - /// How to push a message into the context - /// - /// using(NDC.Push("my context message")) - /// { - /// ... all log calls will have 'my context message' included ... - /// - /// } // at the end of the using block the message is automatically removed - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public sealed class NDC - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private NDC() - { - } - - #endregion Private Instance Constructors - - #region Public Static Properties - - /// - /// Gets the current context depth. - /// - /// The current context depth. - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// The number of context values pushed onto the context stack. - /// - /// - /// Used to record the current depth of the context. This can then - /// be restored using the method. - /// - /// - /// - /*[Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v11.0.0.")]*/ - public static int Depth - { - get { return ThreadContext.Stacks["NDC"].Count; } - } - - #endregion Public Static Properties - - #region Public Static Methods - - /// - /// Clears all the contextual information held on the current thread. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Clears the stack of NDC data held on the current thread. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static void Clear() - { - ThreadContext.Stacks["NDC"].Clear(); - } - - /// - /// Creates a clone of the stack of context information. - /// - /// A clone of the context info for this thread. - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// The results of this method can be passed to the - /// method to allow child threads to inherit the context of their - /// parent thread. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static Stack CloneStack() - { - return ThreadContext.Stacks["NDC"].InternalStack; - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// Implementation of Nested Diagnostic Contexts. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// A Nested Diagnostic Context, or NDC in short, is an instrument + /// to distinguish interleaved log output from different sources. Log + /// output is typically interleaved when a server handles multiple + /// clients near-simultaneously. + /// + /// + /// Interleaved log output can still be meaningful if each log entry + /// from different contexts had a distinctive stamp. This is where NDCs + /// come into play. + /// + /// + /// Note that NDCs are managed on a per thread basis. The NDC class + /// is made up of static methods that operate on the context of the + /// calling thread. + /// + /// + /// How to push a message into the context. + /// + /// using(NDC.Push("my context message")) + /// { + /// ... all log calls will have 'my context message' included ... + /// + /// } // at the end of the using block the message is automatically removed + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] + public sealed class NDC + { + /// + /// Initializes a new instance of the class. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private NDC() + { + } + + /// + /// Gets the current context depth. + /// + /// The current context depth. + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// The number of context values pushed onto the context stack. + /// + /// + /// Used to record the current depth of the context. This can then + /// be restored using the method. + /// + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v11.0.0.")]*/ + public static int Depth + { + get { return ThreadContext.Stacks["NDC"].Count; } + } + + /// + /// Clears all the contextual information held on the current thread. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Clears the stack of NDC data held on the current thread. + /// + /// + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] + public static void Clear() + { + ThreadContext.Stacks["NDC"].Clear(); + } - /// - /// Inherits the contextual information from another thread. - /// - /// The context stack to inherit. - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// This thread will use the context information from the stack - /// supplied. This can be used to initialize child threads with - /// the same contextual information as their parent threads. These - /// contexts will NOT be shared. Any further contexts that - /// are pushed onto the stack will not be visible to the other. - /// Call to obtain a stack to pass to - /// this method. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.", true)] - public static void Inherit(Stack stack) - { - ThreadContext.Stacks["NDC"].InternalStack = stack; - } + /// + /// Creates a clone of the stack of context information. + /// + /// A clone of the context info for this thread. + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// The results of this method can be passed to the + /// method to allow child threads to inherit the context of their + /// parent thread. + /// + /// + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] + public static Stack CloneStack() + { + return ThreadContext.Stacks["NDC"].InternalStack; + } - /// - /// Removes the top context from the stack. - /// - /// - /// The message in the context that was removed from the top - /// of the stack. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Remove the top context from the stack, and return - /// it to the caller. If the stack is empty then an - /// empty string (not null) is returned. - /// - /// - /*[Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v11.0.0.")]*/ - public static string Pop() - { - return ThreadContext.Stacks["NDC"].Pop(); - } + /// + /// Inherits the contextual information from another thread. + /// + /// The context stack to inherit. + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// This thread will use the context information from the stack + /// supplied. This can be used to initialize child threads with + /// the same contextual information as their parent threads. These + /// contexts will NOT be shared. Any further contexts that + /// are pushed onto the stack will not be visible to the other. + /// Call to obtain a stack to pass to + /// this method. + /// + /// + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.", true)] + public static void Inherit(Stack stack) + { + ThreadContext.Stacks["NDC"].InternalStack = stack; + } - /// - /// Pushes a new context message. - /// - /// The new context message. - /// - /// An that can be used to clean up - /// the context stack. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Pushes a new context onto the context stack. An - /// is returned that can be used to clean up the context stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// using(log4net.NDC.Push("NDC_Message")) - /// { - /// log.Warn("This should have an NDC message"); - /// } - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static IDisposable Push(string message) - { - return ThreadContext.Stacks["NDC"].Push(message); - } + /// + /// Removes the top context from the stack. + /// + /// + /// The message in the context that was removed from the top + /// of the stack. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Remove the top context from the stack, and return + /// it to the caller. If the stack is empty then an + /// empty string (not null) is returned. + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v11.0.0.")]*/ + public static string Pop() + { + return ThreadContext.Stacks["NDC"].Pop(); + } - /// - /// Pushes a new context message. - /// - /// The new context message string format. - /// Arguments to be passed into messageFormat. - /// - /// An that can be used to clean up - /// the context stack. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Pushes a new context onto the context stack. An - /// is returned that can be used to clean up the context stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// var someValue = "ExampleContext" - /// using(log4net.NDC.PushFormat("NDC_Message {0}", someValue)) - /// { - /// log.Warn("This should have an NDC message"); - /// } - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static IDisposable PushFormat(string messageFormat, params object[] args) - { - return Push(string.Format(messageFormat, args)); - } + /// + /// Pushes a new context message. + /// + /// The new context message. + /// + /// An that can be used to clean up + /// the context stack. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Pushes a new context onto the context stack. An + /// is returned that can be used to clean up the context stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// using(log4net.NDC.Push("NDC_Message")) + /// { + /// log.Warn("This should have an NDC message"); + /// } + /// + /// + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] + public static IDisposable Push(string message) + { + return ThreadContext.Stacks["NDC"].Push(message); + } - /// - /// Removes the context information for this thread. It is - /// not required to call this method. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// This method is not implemented. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static void Remove() - { - } + /// + /// Pushes a new context message. + /// + /// The new context message string format. + /// Arguments to be passed into messageFormat. + /// + /// An that can be used to clean up + /// the context stack. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Pushes a new context onto the context stack. An + /// is returned that can be used to clean up the context stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// var someValue = "ExampleContext" + /// using(log4net.NDC.PushFormat("NDC_Message {0}", someValue)) + /// { + /// log.Warn("This should have an NDC message"); + /// } + /// + /// + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] + public static IDisposable PushFormat(string messageFormat, params object[] args) + { + return Push(string.Format(messageFormat, args)); + } - /// - /// Forces the stack depth to be at most . - /// - /// The maximum depth of the stack - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Forces the stack depth to be at most . - /// This may truncate the head of the stack. This only affects the - /// stack in the current thread. Also it does not prevent it from - /// growing, it only sets the maximum depth at the time of the - /// call. This can be used to return to a known context depth. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static void SetMaxDepth(int maxDepth) - { - if (maxDepth >= 0) - { - log4net.Util.ThreadContextStack stack = ThreadContext.Stacks["NDC"]; + /// + /// Removes the context information for this thread. It is + /// not required to call this method. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// This method is not implemented. + /// + /// + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] + public static void Remove() + { + } - if (maxDepth == 0) - { - stack.Clear(); - } - else - { - while(stack.Count > maxDepth) - { - stack.Pop(); - } - } - } - } + /// + /// Forces the stack depth to be at most . + /// + /// The maximum depth of the stack. + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Forces the stack depth to be at most . + /// This may truncate the head of the stack. This only affects the + /// stack in the current thread. Also it does not prevent it from + /// growing, it only sets the maximum depth at the time of the + /// call. This can be used to return to a known context depth. + /// + /// + [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] + public static void SetMaxDepth(int maxDepth) + { + if (maxDepth >= 0) + { + log4net.Util.ThreadContextStack stack = ThreadContext.Stacks["NDC"]; - #endregion Public Static Methods - } + if (maxDepth == 0) + { + stack.Clear(); + } + else + { + while (stack.Count > maxDepth) + { + stack.Pop(); + } + } + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs index 256d5261fbd..300f4ede916 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs @@ -1,314 +1,305 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; -using System.Collections; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.ObjectRenderer { - /// - /// The default object Renderer. - /// - /// - /// - /// The default renderer supports rendering objects and collections to strings. - /// - /// - /// See the method for details of the output. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class DefaultRenderer : IObjectRenderer - { - #region Constructors - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public DefaultRenderer() - { - } - - #endregion - - #region Implementation of IObjectRenderer + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + using System.Text; + + using log4net.Util; + + /// + /// The default object Renderer. + /// + /// + /// + /// The default renderer supports rendering objects and collections to strings. + /// + /// + /// See the method for details of the output. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class DefaultRenderer : IObjectRenderer + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public DefaultRenderer() + { + } + + /// + /// Render the object to a string. + /// + /// The map used to lookup renderers. + /// The object to render. + /// The writer to render to. + /// + /// + /// Render the object to a string. + /// + /// + /// The parameter is + /// provided to lookup and render other objects. This is + /// very useful where contains + /// nested objects of unknown type. The + /// method can be used to render these objects. + /// + /// + /// The default renderer supports rendering objects to strings as follows: + /// + /// + /// + /// Value + /// Rendered String + /// + /// + /// null + /// + /// "(null)" + /// + /// + /// + /// + /// + /// + /// For a one dimensional array this is the + /// array type name, an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. + /// + /// + /// For example: int[] {1, 2, 3}. + /// + /// + /// If the array is not one dimensional the + /// Array.ToString() is returned. + /// + /// + /// + /// + /// , & + /// + /// + /// Rendered as an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. + /// + /// + /// For example: {a, b, c}. + /// + /// + /// All collection classes that implement its subclasses, + /// or generic equivalents all implement the interface. + /// + /// + /// + /// + /// + /// + /// + /// Rendered as the key, an equals sign ('='), and the value (using the appropriate + /// renderer). + /// + /// + /// For example: key=value. + /// + /// + /// + /// + /// other + /// + /// Object.ToString() + /// + /// + /// + /// + public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) + { + if (rendererMap == null) + { + throw new ArgumentNullException("rendererMap"); + } - /// - /// Render the object to a string - /// - /// The map used to lookup renderers - /// The object to render - /// The writer to render to - /// - /// - /// Render the object to a string. - /// - /// - /// The parameter is - /// provided to lookup and render other objects. This is - /// very useful where contains - /// nested objects of unknown type. The - /// method can be used to render these objects. - /// - /// - /// The default renderer supports rendering objects to strings as follows: - /// - /// - /// - /// Value - /// Rendered String - /// - /// - /// null - /// - /// "(null)" - /// - /// - /// - /// - /// - /// - /// For a one dimensional array this is the - /// array type name, an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. - /// - /// - /// For example: int[] {1, 2, 3}. - /// - /// - /// If the array is not one dimensional the - /// Array.ToString() is returned. - /// - /// - /// - /// - /// , & - /// - /// - /// Rendered as an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. - /// - /// - /// For example: {a, b, c}. - /// - /// - /// All collection classes that implement its subclasses, - /// or generic equivalents all implement the interface. - /// - /// - /// - /// - /// - /// - /// - /// Rendered as the key, an equals sign ('='), and the value (using the appropriate - /// renderer). - /// - /// - /// For example: key=value. - /// - /// - /// - /// - /// other - /// - /// Object.ToString() - /// - /// - /// - /// - public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) - { - if (rendererMap == null) - { - throw new ArgumentNullException("rendererMap"); - } + if (obj == null) + { + writer.Write(SystemInfo.NullText); + return; + } - if (obj == null) - { - writer.Write(SystemInfo.NullText); - return; - } - - Array objArray = obj as Array; - if (objArray != null) - { - RenderArray(rendererMap, objArray, writer); - return; - } + Array objArray = obj as Array; + if (objArray != null) + { + this.RenderArray(rendererMap, objArray, writer); + return; + } - // Test if we are dealing with some form of collection object - IEnumerable objEnumerable = obj as IEnumerable; - if (objEnumerable != null) - { - // Get a collection interface if we can as its .Count property may be more - // performant than getting the IEnumerator object and trying to advance it. - ICollection objCollection = obj as ICollection; - if (objCollection != null && objCollection.Count == 0) - { - writer.Write("{}"); - return; - } - - // This is a special check to allow us to get the enumerator from the IDictionary - // interface as this guarantees us DictionaryEntry objects. Note that in .NET 2.0 - // the generic IDictionary<> interface enumerates KeyValuePair objects rather than - // DictionaryEntry ones. However the implementation of the plain IDictionary - // interface on the generic Dictionary<> still returns DictionaryEntry objects. - IDictionary objDictionary = obj as IDictionary; - if (objDictionary != null) - { - RenderEnumerator(rendererMap, objDictionary.GetEnumerator(), writer); - return; - } + // Test if we are dealing with some form of collection object + IEnumerable objEnumerable = obj as IEnumerable; + if (objEnumerable != null) + { + // Get a collection interface if we can as its .Count property may be more + // performant than getting the IEnumerator object and trying to advance it. + ICollection objCollection = obj as ICollection; + if (objCollection != null && objCollection.Count == 0) + { + writer.Write("{}"); + return; + } - RenderEnumerator(rendererMap, objEnumerable.GetEnumerator(), writer); - return; - } + // This is a special check to allow us to get the enumerator from the IDictionary + // interface as this guarantees us DictionaryEntry objects. Note that in .NET 2.0 + // the generic IDictionary<> interface enumerates KeyValuePair objects rather than + // DictionaryEntry ones. However the implementation of the plain IDictionary + // interface on the generic Dictionary<> still returns DictionaryEntry objects. + IDictionary objDictionary = obj as IDictionary; + if (objDictionary != null) + { + this.RenderEnumerator(rendererMap, objDictionary.GetEnumerator(), writer); + return; + } - IEnumerator objEnumerator = obj as IEnumerator; - if (objEnumerator != null) - { - RenderEnumerator(rendererMap, objEnumerator, writer); - return; - } - - if (obj is DictionaryEntry) - { - RenderDictionaryEntry(rendererMap, (DictionaryEntry)obj, writer); - return; - } + this.RenderEnumerator(rendererMap, objEnumerable.GetEnumerator(), writer); + return; + } - string str = obj.ToString(); - writer.Write( (str==null) ? SystemInfo.NullText : str ); - } + IEnumerator objEnumerator = obj as IEnumerator; + if (objEnumerator != null) + { + this.RenderEnumerator(rendererMap, objEnumerator, writer); + return; + } - #endregion + if (obj is DictionaryEntry) + { + this.RenderDictionaryEntry(rendererMap, (DictionaryEntry)obj, writer); + return; + } - /// - /// Render the array argument into a string - /// - /// The map used to lookup renderers - /// the array to render - /// The writer to render to - /// - /// - /// For a one dimensional array this is the - /// array type name, an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. For example: - /// int[] {1, 2, 3}. - /// - /// - /// If the array is not one dimensional the - /// Array.ToString() is returned. - /// - /// - private void RenderArray(RendererMap rendererMap, Array array, TextWriter writer) - { - if (array.Rank != 1) - { - writer.Write(array.ToString()); - } - else - { - writer.Write(array.GetType().Name + " {"); - int len = array.Length; + string str = obj.ToString(); + writer.Write((str == null) ? SystemInfo.NullText : str); + } + + /// + /// Render the array argument into a string. + /// + /// The map used to lookup renderers. + /// the array to render. + /// The writer to render to. + /// + /// + /// For a one dimensional array this is the + /// array type name, an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. For example: + /// int[] {1, 2, 3}. + /// + /// + /// If the array is not one dimensional the + /// Array.ToString() is returned. + /// + /// + private void RenderArray(RendererMap rendererMap, Array array, TextWriter writer) + { + if (array.Rank != 1) + { + writer.Write(array.ToString()); + } + else + { + writer.Write(array.GetType().Name + " {"); + int len = array.Length; - if (len > 0) - { - rendererMap.FindAndRender(array.GetValue(0), writer); - for(int i=1; i 0) + { + rendererMap.FindAndRender(array.GetValue(0), writer); + for (int i = 1; i < len; i++) + { + writer.Write(", "); + rendererMap.FindAndRender(array.GetValue(i), writer); + } + } + + writer.Write("}"); + } + } - /// - /// Render the enumerator argument into a string - /// - /// The map used to lookup renderers - /// the enumerator to render - /// The writer to render to - /// - /// - /// Rendered as an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. For example: - /// {a, b, c}. - /// - /// - private void RenderEnumerator(RendererMap rendererMap, IEnumerator enumerator, TextWriter writer) - { - writer.Write("{"); + /// + /// Render the enumerator argument into a string. + /// + /// The map used to lookup renderers. + /// the enumerator to render. + /// The writer to render to. + /// + /// + /// Rendered as an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. For example: + /// {a, b, c}. + /// + /// + private void RenderEnumerator(RendererMap rendererMap, IEnumerator enumerator, TextWriter writer) + { + writer.Write("{"); - if (enumerator != null && enumerator.MoveNext()) - { - rendererMap.FindAndRender(enumerator.Current, writer); + if (enumerator != null && enumerator.MoveNext()) + { + rendererMap.FindAndRender(enumerator.Current, writer); - while (enumerator.MoveNext()) - { - writer.Write(", "); - rendererMap.FindAndRender(enumerator.Current, writer); - } - } + while (enumerator.MoveNext()) + { + writer.Write(", "); + rendererMap.FindAndRender(enumerator.Current, writer); + } + } - writer.Write("}"); - } + writer.Write("}"); + } - /// - /// Render the DictionaryEntry argument into a string - /// - /// The map used to lookup renderers - /// the DictionaryEntry to render - /// The writer to render to - /// - /// - /// Render the key, an equals sign ('='), and the value (using the appropriate - /// renderer). For example: key=value. - /// - /// - private void RenderDictionaryEntry(RendererMap rendererMap, DictionaryEntry entry, TextWriter writer) - { - rendererMap.FindAndRender(entry.Key, writer); - writer.Write("="); - rendererMap.FindAndRender(entry.Value, writer); - } - } + /// + /// Render the DictionaryEntry argument into a string. + /// + /// The map used to lookup renderers. + /// the DictionaryEntry to render. + /// The writer to render to. + /// + /// + /// Render the key, an equals sign ('='), and the value (using the appropriate + /// renderer). For example: key=value. + /// + /// + private void RenderDictionaryEntry(RendererMap rendererMap, DictionaryEntry entry, TextWriter writer) + { + rendererMap.FindAndRender(entry.Key, writer); + writer.Write("="); + rendererMap.FindAndRender(entry.Value, writer); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs index 3940c4c8df2..9efb078790b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs @@ -1,65 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.ObjectRenderer { - /// - /// Implement this interface in order to render objects as strings - /// - /// - /// - /// Certain types require special case conversion to - /// string form. This conversion is done by an object renderer. - /// Object renderers implement the - /// interface. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IObjectRenderer - { - /// - /// Render the object to a string - /// - /// The map used to lookup renderers - /// The object to render - /// The writer to render to - /// - /// - /// Render the object to a - /// string. - /// - /// - /// The parameter is - /// provided to lookup and render other objects. This is - /// very useful where contains - /// nested objects of unknown type. The - /// method can be used to render these objects. - /// - /// - void RenderObject(RendererMap rendererMap, object obj, TextWriter writer); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + /// + /// Implement this interface in order to render objects as strings. + /// + /// + /// + /// Certain types require special case conversion to + /// string form. This conversion is done by an object renderer. + /// Object renderers implement the + /// interface. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IObjectRenderer + { + /// + /// Render the object to a string. + /// + /// The map used to lookup renderers. + /// The object to render. + /// The writer to render to. + /// + /// + /// Render the object to a + /// string. + /// + /// + /// The parameter is + /// provided to lookup and render other objects. This is + /// very useful where contains + /// nested objects of unknown type. The + /// method can be used to render these objects. + /// + /// + void RenderObject(RendererMap rendererMap, object obj, TextWriter writer); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs index 4494b9bd77f..a7c8f95dcc9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs @@ -1,28 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETSTANDARD1_3 using System.Reflection; #endif @@ -31,308 +10,322 @@ namespace log4net.ObjectRenderer { - /// - /// Map class objects to an . - /// - /// - /// - /// Maintains a mapping between types that require special - /// rendering and the that - /// is used to render them. - /// - /// - /// The method is used to render an - /// object using the appropriate renderers defined in this map. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class RendererMap - { - private readonly static Type declaringType = typeof(RendererMap); - - #region Member Variables - - private System.Collections.Hashtable m_map; - private System.Collections.Hashtable m_cache = new System.Collections.Hashtable(); - - private static IObjectRenderer s_defaultRenderer = new DefaultRenderer(); - - #endregion - - #region Constructors - - /// - /// Default Constructor - /// - /// - /// - /// Default constructor. - /// - /// - public RendererMap() - { - m_map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + /// + /// Map class objects to an . + /// + /// + /// + /// Maintains a mapping between types that require special + /// rendering and the that + /// is used to render them. + /// + /// + /// The method is used to render an + /// object using the appropriate renderers defined in this map. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class RendererMap + { + private static readonly Type declaringType = typeof(RendererMap); + private System.Collections.Hashtable m_map; + private System.Collections.Hashtable m_cache = new System.Collections.Hashtable(); - #endregion + private static IObjectRenderer s_defaultRenderer = new DefaultRenderer(); + + /// + /// Initializes a new instance of the class. + /// Default Constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public RendererMap() + { + this.m_map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); + } + + /// + /// Render using the appropriate renderer. + /// + /// the object to render to a string. + /// the object rendered as a string. + /// + /// + /// This is a convenience method used to render an object to a string. + /// The alternative method + /// should be used when streaming output to a . + /// + /// + public string FindAndRender(object obj) + { + // Optimisation for strings + string strData = obj as string; + if (strData != null) + { + return strData; + } - /// - /// Render using the appropriate renderer. - /// - /// the object to render to a string - /// the object rendered as a string - /// - /// - /// This is a convenience method used to render an object to a string. - /// The alternative method - /// should be used when streaming output to a . - /// - /// - public string FindAndRender(object obj) - { - // Optimisation for strings - string strData = obj as String; - if (strData != null) - { - return strData; - } + StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + this.FindAndRender(obj, stringWriter); + return stringWriter.ToString(); + } - StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - FindAndRender(obj, stringWriter); - return stringWriter.ToString(); - } + /// + /// Render using the appropriate renderer. + /// + /// the object to render to a string. + /// The writer to render to. + /// + /// + /// Find the appropriate renderer for the type of the + /// parameter. This is accomplished by calling the + /// method. Once a renderer is found, it is + /// applied on the object and the result is returned + /// as a . + /// + /// + public void FindAndRender(object obj, TextWriter writer) + { + if (obj == null) + { + writer.Write(SystemInfo.NullText); + } + else + { + // Optimisation for strings + string str = obj as string; + if (str != null) + { + writer.Write(str); + } + else + { + // Lookup the renderer for the specific type + try + { + this.Get(obj.GetType()).RenderObject(this, obj, writer); + } + catch (Exception ex) + { + // Exception rendering the object + log4net.Util.LogLog.Error(declaringType, "Exception while rendering object of type [" + obj.GetType().FullName + "]", ex); - /// - /// Render using the appropriate renderer. - /// - /// the object to render to a string - /// The writer to render to - /// - /// - /// Find the appropriate renderer for the type of the - /// parameter. This is accomplished by calling the - /// method. Once a renderer is found, it is - /// applied on the object and the result is returned - /// as a . - /// - /// - public void FindAndRender(object obj, TextWriter writer) - { - if (obj == null) - { - writer.Write(SystemInfo.NullText); - } - else - { - // Optimisation for strings - string str = obj as string; - if (str != null) - { - writer.Write(str); - } - else - { - // Lookup the renderer for the specific type - try - { - Get(obj.GetType()).RenderObject(this, obj, writer); - } - catch(Exception ex) - { - // Exception rendering the object - log4net.Util.LogLog.Error(declaringType, "Exception while rendering object of type ["+obj.GetType().FullName+"]", ex); + // return default message + string objectTypeName = string.Empty; + if (obj != null && obj.GetType() != null) + { + objectTypeName = obj.GetType().FullName; + } - // return default message - string objectTypeName = ""; - if (obj != null && obj.GetType() != null) - { - objectTypeName = obj.GetType().FullName; - } + writer.Write("Exception rendering object type [" + objectTypeName + "]"); + if (ex != null) + { + string exceptionText = null; - writer.Write("Exception rendering object type ["+objectTypeName+"]"); - if (ex != null) - { - string exceptionText = null; + try + { + exceptionText = ex.ToString(); + } + catch + { + // Ignore exception + } - try - { - exceptionText = ex.ToString(); - } - catch - { - // Ignore exception - } + writer.Write("" + exceptionText + ""); + } + + writer.Write(""); + } + } + } + } - writer.Write("" + exceptionText + ""); - } - writer.Write(""); - } - } - } - } + /// + /// Gets the renderer for the specified object type. + /// + /// the object to lookup the renderer for. + /// the renderer for . + /// + /// + /// Gets the renderer for the specified object type. + /// + /// + /// Syntactic sugar method that calls + /// with the type of the object parameter. + /// + /// + public IObjectRenderer Get(object obj) + { + if (obj == null) + { + return null; + } + else + { + return this.Get(obj.GetType()); + } + } - /// - /// Gets the renderer for the specified object type - /// - /// the object to lookup the renderer for - /// the renderer for - /// - /// - /// Gets the renderer for the specified object type. - /// - /// - /// Syntactic sugar method that calls - /// with the type of the object parameter. - /// - /// - public IObjectRenderer Get(Object obj) - { - if (obj == null) - { - return null; - } - else - { - return Get(obj.GetType()); - } - } - - /// - /// Gets the renderer for the specified type - /// - /// the type to lookup the renderer for - /// the renderer for the specified type - /// - /// - /// Returns the renderer for the specified type. - /// If no specific renderer has been defined the - /// will be returned. - /// - /// - public IObjectRenderer Get(Type type) - { - if (type == null) - { - throw new ArgumentNullException("type"); - } + /// + /// Gets the renderer for the specified type. + /// + /// the type to lookup the renderer for. + /// the renderer for the specified type. + /// + /// + /// Returns the renderer for the specified type. + /// If no specific renderer has been defined the + /// will be returned. + /// + /// + public IObjectRenderer Get(Type type) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } - IObjectRenderer result = null; + IObjectRenderer result = null; - // Check cache - result = (IObjectRenderer)m_cache[type]; + // Check cache + result = (IObjectRenderer)this.m_cache[type]; - if (result == null) - { + if (result == null) + { #if NETSTANDARD1_3 for (Type cur = type; cur != null; cur = cur.GetTypeInfo().BaseType) #else - for(Type cur = type; cur != null; cur = cur.BaseType) + for (Type cur = type; cur != null; cur = cur.BaseType) #endif - { - // Search the type's interfaces - result = SearchTypeAndInterfaces(cur); - if (result != null) - { - break; - } - } + { + // Search the type's interfaces + result = this.SearchTypeAndInterfaces(cur); + if (result != null) + { + break; + } + } - // if not set then use the default renderer - if (result == null) - { - result = s_defaultRenderer; - } + // if not set then use the default renderer + if (result == null) + { + result = s_defaultRenderer; + } - // Add to cache - m_cache[type] = result; - } + // Add to cache + this.m_cache[type] = result; + } - return result; - } + return result; + } - /// - /// Internal function to recursively search interfaces - /// - /// the type to lookup the renderer for - /// the renderer for the specified type - private IObjectRenderer SearchTypeAndInterfaces(Type type) - { - IObjectRenderer r = (IObjectRenderer)m_map[type]; - if (r != null) - { - return r; - } - else - { - foreach(Type t in type.GetInterfaces()) - { - r = SearchTypeAndInterfaces(t); - if (r != null) - { - return r; - } - } - } - return null; - } + /// + /// Internal function to recursively search interfaces. + /// + /// the type to lookup the renderer for. + /// the renderer for the specified type. + private IObjectRenderer SearchTypeAndInterfaces(Type type) + { + IObjectRenderer r = (IObjectRenderer)this.m_map[type]; + if (r != null) + { + return r; + } + else + { + foreach (Type t in type.GetInterfaces()) + { + r = this.SearchTypeAndInterfaces(t); + if (r != null) + { + return r; + } + } + } + + return null; + } - /// - /// Get the default renderer instance - /// - /// the default renderer - /// - /// - /// Get the default renderer - /// - /// - public IObjectRenderer DefaultRenderer - { - get { return s_defaultRenderer; } - } + /// + /// Gets get the default renderer instance. + /// + /// the default renderer. + /// + /// + /// Get the default renderer. + /// + /// + public IObjectRenderer DefaultRenderer + { + get { return s_defaultRenderer; } + } - /// - /// Clear the map of renderers - /// - /// - /// - /// Clear the custom renderers defined by using - /// . The - /// cannot be removed. - /// - /// - public void Clear() - { - m_map.Clear(); - m_cache.Clear(); - } + /// + /// Clear the map of renderers. + /// + /// + /// + /// Clear the custom renderers defined by using + /// . The + /// cannot be removed. + /// + /// + public void Clear() + { + this.m_map.Clear(); + this.m_cache.Clear(); + } - /// - /// Register an for . - /// - /// the type that will be rendered by - /// the renderer for - /// - /// - /// Register an object renderer for a specific source type. - /// This renderer will be returned from a call to - /// specifying the same as an argument. - /// - /// - public void Put(Type typeToRender, IObjectRenderer renderer) - { - m_cache.Clear(); + /// + /// Register an for . + /// + /// the type that will be rendered by . + /// the renderer for . + /// + /// + /// Register an object renderer for a specific source type. + /// This renderer will be returned from a call to + /// specifying the same as an argument. + /// + /// + public void Put(Type typeToRender, IObjectRenderer renderer) + { + this.m_cache.Clear(); - if (typeToRender == null) - { - throw new ArgumentNullException("typeToRender"); - } - if (renderer == null) - { - throw new ArgumentNullException("renderer"); - } + if (typeToRender == null) + { + throw new ArgumentNullException("typeToRender"); + } + + if (renderer == null) + { + throw new ArgumentNullException("renderer"); + } - m_map[typeToRender] = renderer; - } - } + this.m_map[typeToRender] = renderer; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs index f3b6274d4cb..7e96570b39a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs @@ -1,89 +1,86 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Plugin { - /// - /// Interface implemented by logger repository plugins. - /// - /// - /// - /// Plugins define additional behavior that can be associated - /// with a . - /// The held by the - /// property is used to store the plugins for a repository. - /// - /// - /// The log4net.Config.PluginAttribute can be used to - /// attach plugins to repositories created using configuration - /// attributes. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IPlugin - { - /// - /// Gets the name of the plugin. - /// - /// - /// The name of the plugin. - /// - /// - /// - /// Plugins are stored in the - /// keyed by name. Each plugin instance attached to a - /// repository must be a unique name. - /// - /// - string Name { get; } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using log4net.Repository; + + /// + /// Interface implemented by logger repository plugins. + /// + /// + /// + /// Plugins define additional behavior that can be associated + /// with a . + /// The held by the + /// property is used to store the plugins for a repository. + /// + /// + /// The log4net.Config.PluginAttribute can be used to + /// attach plugins to repositories created using configuration + /// attributes. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IPlugin + { + /// + /// Gets the name of the plugin. + /// + /// + /// The name of the plugin. + /// + /// + /// + /// Plugins are stored in the + /// keyed by name. Each plugin instance attached to a + /// repository must be a unique name. + /// + /// + string Name { get; } - /// - /// Attaches the plugin to the specified . - /// - /// The that this plugin should be attached to. - /// - /// - /// A plugin may only be attached to a single repository. - /// - /// - /// This method is called when the plugin is attached to the repository. - /// - /// - void Attach(ILoggerRepository repository); + /// + /// Attaches the plugin to the specified . + /// + /// The that this plugin should be attached to. + /// + /// + /// A plugin may only be attached to a single repository. + /// + /// + /// This method is called when the plugin is attached to the repository. + /// + /// + void Attach(ILoggerRepository repository); - /// - /// Is called when the plugin is to shutdown. - /// - /// - /// - /// This method is called to notify the plugin that - /// it should stop operating and should detach from - /// the repository. - /// - /// - void Shutdown(); - } + /// + /// Is called when the plugin is to shutdown. + /// + /// + /// + /// This method is called to notify the plugin that + /// it should stop operating and should detach from + /// the repository. + /// + /// + void Shutdown(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs index 51ba399f0fd..153a60523bb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs @@ -1,49 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// namespace log4net.Plugin { - /// - /// Interface used to create plugins. - /// - /// - /// - /// Interface used to create a plugin. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IPluginFactory - { - /// - /// Creates the plugin object. - /// - /// the new plugin instance - /// - /// - /// Create and return a new plugin instance. - /// - /// - IPlugin CreatePlugin(); - } + /// + /// Interface used to create plugins. + /// + /// + /// + /// Interface used to create a plugin. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IPluginFactory + { + /// + /// Creates the plugin object. + /// + /// the new plugin instance. + /// + /// + /// Create and return a new plugin instance. + /// + /// + IPlugin CreatePlugin(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs index aa34c9a96a2..2b55fd75742 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs @@ -1,880 +1,797 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Plugin { - /// - /// A strongly-typed collection of objects. - /// - /// Nicko Cadell - public class PluginCollection : ICollection, IList, IEnumerable + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// A strongly-typed collection of objects. + /// + /// Nicko Cadell. + public class PluginCollection : ICollection, IList, IEnumerable #if !NETSTANDARD1_3 - , ICloneable + , ICloneable #endif - { - #region Interfaces - - /// - /// Supports type-safe iteration over a . - /// - /// - public interface IPluginCollectionEnumerator - { - /// - /// Gets the current element in the collection. - /// - IPlugin Current { get; } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - bool MoveNext(); - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - void Reset(); - } - - #endregion Interfaces - - private const int DEFAULT_CAPACITY = 16; - - #region Implementation (data) - - private IPlugin[] m_array; - private int m_count = 0; - private int m_version = 0; - - #endregion Implementation (data) - - #region Static Wrappers - - /// - /// Creates a read-only wrapper for a PluginCollection instance. - /// - /// list to create a readonly wrapper arround - /// - /// A PluginCollection wrapper that is read-only. - /// - public static PluginCollection ReadOnly(PluginCollection list) - { - if(list == null) throw new ArgumentNullException("list"); - - return new ReadOnlyPluginCollection(list); - } - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the PluginCollection class - /// that is empty and has the default initial capacity. - /// - public PluginCollection() - { - m_array = new IPlugin[DEFAULT_CAPACITY]; - } - - /// - /// Initializes a new instance of the PluginCollection class - /// that has the specified initial capacity. - /// - /// - /// The number of elements that the new PluginCollection is initially capable of storing. - /// - public PluginCollection(int capacity) - { - m_array = new IPlugin[capacity]; - } - - /// - /// Initializes a new instance of the PluginCollection class - /// that contains elements copied from the specified PluginCollection. - /// - /// The PluginCollection whose elements are copied to the new collection. - public PluginCollection(PluginCollection c) - { - m_array = new IPlugin[c.Count]; - AddRange(c); - } - - /// - /// Initializes a new instance of the PluginCollection class - /// that contains elements copied from the specified array. - /// - /// The array whose elements are copied to the new list. - public PluginCollection(IPlugin[] a) - { - m_array = new IPlugin[a.Length]; - AddRange(a); - } - - /// - /// Initializes a new instance of the PluginCollection class - /// that contains elements copied from the specified collection. - /// - /// The collection whose elements are copied to the new list. - public PluginCollection(ICollection col) - { - m_array = new IPlugin[col.Count]; - AddRange(col); - } - - /// - /// Type visible only to our subclasses - /// Used to access protected constructor - /// - /// - protected internal enum Tag - { - /// - /// A value - /// - Default - } - - /// - /// Allow subclasses to avoid our default constructors - /// - /// - /// - protected internal PluginCollection(Tag tag) - { - m_array = null; - } - - #endregion - - #region Operations (type-safe ICollection) - - /// - /// Gets the number of elements actually contained in the PluginCollection. - /// - public virtual int Count - { - get { return m_count; } - } - - /// - /// Copies the entire PluginCollection to a one-dimensional - /// array. - /// - /// The one-dimensional array to copy to. - public virtual void CopyTo(IPlugin[] array) - { - this.CopyTo(array, 0); - } - - /// - /// Copies the entire PluginCollection to a one-dimensional - /// array, starting at the specified index of the target array. - /// - /// The one-dimensional array to copy to. - /// The zero-based index in at which copying begins. - public virtual void CopyTo(IPlugin[] array, int start) - { - if (m_count > array.GetUpperBound(0) + 1 - start) - { - throw new System.ArgumentException("Destination array was not long enough."); - } - - Array.Copy(m_array, 0, array, start, m_count); - } - - /// - /// Gets a value indicating whether access to the collection is synchronized (thread-safe). - /// - /// false, because the backing type is an array, which is never thread-safe. - public virtual bool IsSynchronized - { - get { return false; } - } - - /// - /// Gets an object that can be used to synchronize access to the collection. - /// - /// - /// An object that can be used to synchronize access to the collection. - /// - public virtual object SyncRoot - { - get { return m_array; } - } - - #endregion - - #region Operations (type-safe IList) - - /// - /// Gets or sets the at the specified index. - /// - /// - /// The at the specified index. - /// - /// The zero-based index of the element to get or set. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual IPlugin this[int index] - { - get - { - ValidateIndex(index); // throws - return m_array[index]; - } - set - { - ValidateIndex(index); // throws - ++m_version; - m_array[index] = value; - } - } - - /// - /// Adds a to the end of the PluginCollection. - /// - /// The to be added to the end of the PluginCollection. - /// The index at which the value has been added. - public virtual int Add(IPlugin item) - { - if (m_count == m_array.Length) - { - EnsureCapacity(m_count + 1); - } - - m_array[m_count] = item; - m_version++; - - return m_count++; - } - - /// - /// Removes all elements from the PluginCollection. - /// - public virtual void Clear() - { - ++m_version; - m_array = new IPlugin[DEFAULT_CAPACITY]; - m_count = 0; - } - - /// - /// Creates a shallow copy of the . - /// - /// A new with a shallow copy of the collection data. - public virtual object Clone() - { - PluginCollection newCol = new PluginCollection(m_count); - Array.Copy(m_array, 0, newCol.m_array, 0, m_count); - newCol.m_count = m_count; - newCol.m_version = m_version; - - return newCol; - } - - /// - /// Determines whether a given is in the PluginCollection. - /// - /// The to check for. - /// true if is found in the PluginCollection; otherwise, false. - public virtual bool Contains(IPlugin item) - { - for (int i=0; i != m_count; ++i) - { - if (m_array[i].Equals(item)) - { - return true; - } - } - return false; - } - - /// - /// Returns the zero-based index of the first occurrence of a - /// in the PluginCollection. - /// - /// The to locate in the PluginCollection. - /// - /// The zero-based index of the first occurrence of - /// in the entire PluginCollection, if found; otherwise, -1. - /// - public virtual int IndexOf(IPlugin item) - { - for (int i=0; i != m_count; ++i) - { - if (m_array[i].Equals(item)) - { - return i; - } - } - return -1; - } - - /// - /// Inserts an element into the PluginCollection at the specified index. - /// - /// The zero-based index at which should be inserted. - /// The to insert. - /// - /// is less than zero - /// -or- - /// is equal to or greater than . - /// - public virtual void Insert(int index, IPlugin item) - { - ValidateIndex(index, true); // throws - - if (m_count == m_array.Length) - { - EnsureCapacity(m_count + 1); - } - - if (index < m_count) - { - Array.Copy(m_array, index, m_array, index + 1, m_count - index); - } - - m_array[index] = item; - m_count++; - m_version++; - } - - /// - /// Removes the first occurrence of a specific from the PluginCollection. - /// - /// The to remove from the PluginCollection. - /// - /// The specified was not found in the PluginCollection. - /// - public virtual void Remove(IPlugin item) - { - int i = IndexOf(item); - if (i < 0) - { - throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); - } - ++m_version; - RemoveAt(i); - } - - /// - /// Removes the element at the specified index of the PluginCollection. - /// - /// The zero-based index of the element to remove. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual void RemoveAt(int index) - { - ValidateIndex(index); // throws - - m_count--; - - if (index < m_count) - { - Array.Copy(m_array, index + 1, m_array, index, m_count - index); - } - - // We can't set the deleted entry equal to null, because it might be a value type. - // Instead, we'll create an empty single-element array of the right type and copy it - // over the entry we want to erase. - IPlugin[] temp = new IPlugin[1]; - Array.Copy(temp, 0, m_array, m_count, 1); - m_version++; - } - - /// - /// Gets a value indicating whether the collection has a fixed size. - /// - /// true if the collection has a fixed size; otherwise, false. The default is false. - public virtual bool IsFixedSize - { - get { return false; } - } - - /// - /// Gets a value indicating whether the IList is read-only. - /// - /// true if the collection is read-only; otherwise, false. The default is false. - public virtual bool IsReadOnly - { - get { return false; } - } - - #endregion - - #region Operations (type-safe IEnumerable) - - /// - /// Returns an enumerator that can iterate through the PluginCollection. - /// - /// An for the entire PluginCollection. - public virtual IPluginCollectionEnumerator GetEnumerator() - { - return new Enumerator(this); - } - - #endregion - - #region Public helpers (just to mimic some nice features of ArrayList) - - /// - /// Gets or sets the number of elements the PluginCollection can contain. - /// - /// - /// The number of elements the PluginCollection can contain. - /// - public virtual int Capacity - { - get - { - return m_array.Length; - } - set - { - if (value < m_count) - { - value = m_count; - } - - if (value != m_array.Length) - { - if (value > 0) - { - IPlugin[] temp = new IPlugin[value]; - Array.Copy(m_array, 0, temp, 0, m_count); - m_array = temp; - } - else - { - m_array = new IPlugin[DEFAULT_CAPACITY]; - } - } - } - } - - /// - /// Adds the elements of another PluginCollection to the current PluginCollection. - /// - /// The PluginCollection whose elements should be added to the end of the current PluginCollection. - /// The new of the PluginCollection. - public virtual int AddRange(PluginCollection x) - { - if (m_count + x.Count >= m_array.Length) - { - EnsureCapacity(m_count + x.Count); - } - - Array.Copy(x.m_array, 0, m_array, m_count, x.Count); - m_count += x.Count; - m_version++; - - return m_count; - } - - /// - /// Adds the elements of a array to the current PluginCollection. - /// - /// The array whose elements should be added to the end of the PluginCollection. - /// The new of the PluginCollection. - public virtual int AddRange(IPlugin[] x) - { - if (m_count + x.Length >= m_array.Length) - { - EnsureCapacity(m_count + x.Length); - } - - Array.Copy(x, 0, m_array, m_count, x.Length); - m_count += x.Length; - m_version++; - - return m_count; - } - - /// - /// Adds the elements of a collection to the current PluginCollection. - /// - /// The collection whose elements should be added to the end of the PluginCollection. - /// The new of the PluginCollection. - public virtual int AddRange(ICollection col) - { - if (m_count + col.Count >= m_array.Length) - { - EnsureCapacity(m_count + col.Count); - } - - foreach(object item in col) - { - Add((IPlugin)item); - } - - return m_count; - } - - /// - /// Sets the capacity to the actual number of elements. - /// - public virtual void TrimToSize() - { - this.Capacity = m_count; - } - - #endregion - - #region Implementation (helpers) - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i) - { - ValidateIndex(i, false); - } - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i, bool allowEqualEnd) - { - int max = (allowEqualEnd) ? (m_count) : (m_count-1); - if (i < 0 || i > max) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); - } - } - - private void EnsureCapacity(int min) - { - int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); - if (newCapacity < min) - { - newCapacity = min; - } - - this.Capacity = newCapacity; - } - - #endregion - - #region Implementation (ICollection) - - void ICollection.CopyTo(Array array, int start) - { - Array.Copy(m_array, 0, array, start, m_count); - } - - #endregion - - #region Implementation (IList) - - object IList.this[int i] - { - get { return (object)this[i]; } - set { this[i] = (IPlugin)value; } - } - - int IList.Add(object x) - { - return this.Add((IPlugin)x); - } - - bool IList.Contains(object x) - { - return this.Contains((IPlugin)x); - } - - int IList.IndexOf(object x) - { - return this.IndexOf((IPlugin)x); - } - - void IList.Insert(int pos, object x) - { - this.Insert(pos, (IPlugin)x); - } - - void IList.Remove(object x) - { - this.Remove((IPlugin)x); - } - - void IList.RemoveAt(int pos) - { - this.RemoveAt(pos); - } - - #endregion - - #region Implementation (IEnumerable) - - IEnumerator IEnumerable.GetEnumerator() - { - return (IEnumerator)(this.GetEnumerator()); - } - - #endregion Implementation (IEnumerable) - - #region Nested enumerator class - - /// - /// Supports simple iteration over a . - /// - /// - private sealed class Enumerator : IEnumerator, IPluginCollectionEnumerator - { - #region Implementation (data) - - private readonly PluginCollection m_collection; - private int m_index; - private int m_version; - - #endregion Implementation (data) - - #region Construction - - /// - /// Initializes a new instance of the Enumerator class. - /// - /// - internal Enumerator(PluginCollection tc) - { - m_collection = tc; - m_index = -1; - m_version = tc.m_version; - } - - #endregion - - #region Operations (type-safe IEnumerator) - - /// - /// Gets the current element in the collection. - /// - /// - /// The current element in the collection. - /// - public IPlugin Current - { - get { return m_collection[m_index]; } - } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - public bool MoveNext() - { - if (m_version != m_collection.m_version) - { - throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); - } - - ++m_index; - return (m_index < m_collection.Count); - } - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - public void Reset() - { - m_index = -1; - } - - #endregion - - #region Implementation (IEnumerator) - - object IEnumerator.Current - { - get { return this.Current; } - } - - #endregion - } - - #endregion - - #region Nested Read Only Wrapper class - - /// - private sealed class ReadOnlyPluginCollection : PluginCollection - { - #region Implementation (data) - - private readonly PluginCollection m_collection; - - #endregion - - #region Construction - - internal ReadOnlyPluginCollection(PluginCollection list) : base(Tag.Default) - { - m_collection = list; - } - - #endregion - - #region Type-safe ICollection - - public override void CopyTo(IPlugin[] array) - { - m_collection.CopyTo(array); - } - - public override void CopyTo(IPlugin[] array, int start) - { - m_collection.CopyTo(array,start); - } - public override int Count - { - get { return m_collection.Count; } - } - - public override bool IsSynchronized - { - get { return m_collection.IsSynchronized; } - } - - public override object SyncRoot - { - get { return this.m_collection.SyncRoot; } - } - - #endregion - - #region Type-safe IList - - public override IPlugin this[int i] - { - get { return m_collection[i]; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int Add(IPlugin x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Clear() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool Contains(IPlugin x) - { - return m_collection.Contains(x); - } - - public override int IndexOf(IPlugin x) - { - return m_collection.IndexOf(x); - } - - public override void Insert(int pos, IPlugin x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Remove(IPlugin x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void RemoveAt(int pos) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool IsFixedSize - { - get { return true; } - } - - public override bool IsReadOnly - { - get { return true; } - } - - #endregion - - #region Type-safe IEnumerable - - public override IPluginCollectionEnumerator GetEnumerator() - { - return m_collection.GetEnumerator(); - } - - #endregion - - #region Public Helpers - - // (just to mimic some nice features of ArrayList) - public override int Capacity - { - get { return m_collection.Capacity; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int AddRange(PluginCollection x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override int AddRange(IPlugin[] x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - #endregion - } - - #endregion - } + { + /// + /// Supports type-safe iteration over a . + /// + /// + public interface IPluginCollectionEnumerator + { + /// + /// Gets the current element in the collection. + /// + IPlugin Current { get; } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + bool MoveNext(); + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + void Reset(); + } + + private const int DEFAULT_CAPACITY = 16; + private IPlugin[] m_array; + private int m_count = 0; + private int m_version = 0; + + /// + /// Creates a read-only wrapper for a PluginCollection instance. + /// + /// list to create a readonly wrapper arround. + /// + /// A PluginCollection wrapper that is read-only. + /// + public static PluginCollection ReadOnly(PluginCollection list) + { + if (list == null) + { + throw new ArgumentNullException("list"); + } + + return new ReadOnlyPluginCollection(list); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the PluginCollection class + /// that is empty and has the default initial capacity. + /// + public PluginCollection() + { + this.m_array = new IPlugin[DEFAULT_CAPACITY]; + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the PluginCollection class + /// that has the specified initial capacity. + /// + /// + /// The number of elements that the new PluginCollection is initially capable of storing. + /// + public PluginCollection(int capacity) + { + this.m_array = new IPlugin[capacity]; + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the PluginCollection class + /// that contains elements copied from the specified PluginCollection. + /// + /// The PluginCollection whose elements are copied to the new collection. + public PluginCollection(PluginCollection c) + { + this.m_array = new IPlugin[c.Count]; + this.AddRange(c); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the PluginCollection class + /// that contains elements copied from the specified array. + /// + /// The array whose elements are copied to the new list. + public PluginCollection(IPlugin[] a) + { + this.m_array = new IPlugin[a.Length]; + this.AddRange(a); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the PluginCollection class + /// that contains elements copied from the specified collection. + /// + /// The collection whose elements are copied to the new list. + public PluginCollection(ICollection col) + { + this.m_array = new IPlugin[col.Count]; + this.AddRange(col); + } + + /// + /// Type visible only to our subclasses + /// Used to access protected constructor. + /// + /// + protected internal enum Tag + { + /// + /// A value + /// + Default, + } + + /// + /// Initializes a new instance of the class. + /// Allow subclasses to avoid our default constructors. + /// + /// + /// + protected internal PluginCollection(Tag tag) + { + this.m_array = null; + } + + /// + /// Gets the number of elements actually contained in the PluginCollection. + /// + public virtual int Count + { + get { return this.m_count; } + } + + /// + /// Copies the entire PluginCollection to a one-dimensional + /// array. + /// + /// The one-dimensional array to copy to. + public virtual void CopyTo(IPlugin[] array) + { + this.CopyTo(array, 0); + } + + /// + /// Copies the entire PluginCollection to a one-dimensional + /// array, starting at the specified index of the target array. + /// + /// The one-dimensional array to copy to. + /// The zero-based index in at which copying begins. + public virtual void CopyTo(IPlugin[] array, int start) + { + if (this.m_count > array.GetUpperBound(0) + 1 - start) + { + throw new System.ArgumentException("Destination array was not long enough."); + } + + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + /// + /// Gets a value indicating whether access to the collection is synchronized (thread-safe). + /// + /// false, because the backing type is an array, which is never thread-safe. + public virtual bool IsSynchronized + { + get { return false; } + } + + /// + /// Gets an object that can be used to synchronize access to the collection. + /// + /// + /// An object that can be used to synchronize access to the collection. + /// + public virtual object SyncRoot + { + get { return this.m_array; } + } + + /// + /// Gets or sets the at the specified index. + /// + /// + /// The at the specified index. + /// + /// The zero-based index of the element to get or set. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual IPlugin this[int index] + { + get + { + this.ValidateIndex(index); // throws + return this.m_array[index]; + } + + set + { + this.ValidateIndex(index); // throws + ++this.m_version; + this.m_array[index] = value; + } + } + + /// + /// Adds a to the end of the PluginCollection. + /// + /// The to be added to the end of the PluginCollection. + /// The index at which the value has been added. + public virtual int Add(IPlugin item) + { + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + this.m_array[this.m_count] = item; + this.m_version++; + + return this.m_count++; + } + + /// + /// Removes all elements from the PluginCollection. + /// + public virtual void Clear() + { + ++this.m_version; + this.m_array = new IPlugin[DEFAULT_CAPACITY]; + this.m_count = 0; + } + + /// + /// Creates a shallow copy of the . + /// + /// A new with a shallow copy of the collection data. + public virtual object Clone() + { + PluginCollection newCol = new PluginCollection(this.m_count); + Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); + newCol.m_count = this.m_count; + newCol.m_version = this.m_version; + + return newCol; + } + + /// + /// Determines whether a given is in the PluginCollection. + /// + /// The to check for. + /// true if is found in the PluginCollection; otherwise, false. + public virtual bool Contains(IPlugin item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return true; + } + } + + return false; + } + + /// + /// Returns the zero-based index of the first occurrence of a + /// in the PluginCollection. + /// + /// The to locate in the PluginCollection. + /// + /// The zero-based index of the first occurrence of + /// in the entire PluginCollection, if found; otherwise, -1. + /// + public virtual int IndexOf(IPlugin item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return i; + } + } + + return -1; + } + + /// + /// Inserts an element into the PluginCollection at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The to insert. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual void Insert(int index, IPlugin item) + { + this.ValidateIndex(index, true); // throws + + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + if (index < this.m_count) + { + Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); + } + + this.m_array[index] = item; + this.m_count++; + this.m_version++; + } + + /// + /// Removes the first occurrence of a specific from the PluginCollection. + /// + /// The to remove from the PluginCollection. + /// + /// The specified was not found in the PluginCollection. + /// + public virtual void Remove(IPlugin item) + { + int i = this.IndexOf(item); + if (i < 0) + { + throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); + } + + ++this.m_version; + this.RemoveAt(i); + } + + /// + /// Removes the element at the specified index of the PluginCollection. + /// + /// The zero-based index of the element to remove. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual void RemoveAt(int index) + { + this.ValidateIndex(index); // throws + + this.m_count--; + + if (index < this.m_count) + { + Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); + } + + // We can't set the deleted entry equal to null, because it might be a value type. + // Instead, we'll create an empty single-element array of the right type and copy it + // over the entry we want to erase. + IPlugin[] temp = new IPlugin[1]; + Array.Copy(temp, 0, this.m_array, this.m_count, 1); + this.m_version++; + } + + /// + /// Gets a value indicating whether the collection has a fixed size. + /// + /// true if the collection has a fixed size; otherwise, false. The default is false. + public virtual bool IsFixedSize + { + get { return false; } + } + + /// + /// Gets a value indicating whether the IList is read-only. + /// + /// true if the collection is read-only; otherwise, false. The default is false. + public virtual bool IsReadOnly + { + get { return false; } + } + + /// + /// Returns an enumerator that can iterate through the PluginCollection. + /// + /// An for the entire PluginCollection. + public virtual IPluginCollectionEnumerator GetEnumerator() + { + return new Enumerator(this); + } + + /// + /// Gets or sets the number of elements the PluginCollection can contain. + /// + /// + /// The number of elements the PluginCollection can contain. + /// + public virtual int Capacity + { + get + { + return this.m_array.Length; + } + + set + { + if (value < this.m_count) + { + value = this.m_count; + } + + if (value != this.m_array.Length) + { + if (value > 0) + { + IPlugin[] temp = new IPlugin[value]; + Array.Copy(this.m_array, 0, temp, 0, this.m_count); + this.m_array = temp; + } + else + { + this.m_array = new IPlugin[DEFAULT_CAPACITY]; + } + } + } + } + + /// + /// Adds the elements of another PluginCollection to the current PluginCollection. + /// + /// The PluginCollection whose elements should be added to the end of the current PluginCollection. + /// The new of the PluginCollection. + public virtual int AddRange(PluginCollection x) + { + if (this.m_count + x.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Count); + } + + Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); + this.m_count += x.Count; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a array to the current PluginCollection. + /// + /// The array whose elements should be added to the end of the PluginCollection. + /// The new of the PluginCollection. + public virtual int AddRange(IPlugin[] x) + { + if (this.m_count + x.Length >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Length); + } + + Array.Copy(x, 0, this.m_array, this.m_count, x.Length); + this.m_count += x.Length; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a collection to the current PluginCollection. + /// + /// The collection whose elements should be added to the end of the PluginCollection. + /// The new of the PluginCollection. + public virtual int AddRange(ICollection col) + { + if (this.m_count + col.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + col.Count); + } + + foreach (object item in col) + { + this.Add((IPlugin)item); + } + + return this.m_count; + } + + /// + /// Sets the capacity to the actual number of elements. + /// + public virtual void TrimToSize() + { + this.Capacity = this.m_count; + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i) + { + this.ValidateIndex(i, false); + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i, bool allowEqualEnd) + { + int max = allowEqualEnd ? this.m_count : (this.m_count - 1); + if (i < 0 || i > max) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); + } + } + + private void EnsureCapacity(int min) + { + int newCapacity = (this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2; + if (newCapacity < min) + { + newCapacity = min; + } + + this.Capacity = newCapacity; + } + + void ICollection.CopyTo(Array array, int start) + { + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + object IList.this[int i] + { + get { return (object)this[i]; } + set { this[i] = (IPlugin)value; } + } + + int IList.Add(object x) + { + return this.Add((IPlugin)x); + } + + bool IList.Contains(object x) + { + return this.Contains((IPlugin)x); + } + + int IList.IndexOf(object x) + { + return this.IndexOf((IPlugin)x); + } + + void IList.Insert(int pos, object x) + { + this.Insert(pos, (IPlugin)x); + } + + void IList.Remove(object x) + { + this.Remove((IPlugin)x); + } + + void IList.RemoveAt(int pos) + { + this.RemoveAt(pos); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (IEnumerator)this.GetEnumerator(); + } + + /// + /// Supports simple iteration over a . + /// + /// + private sealed class Enumerator : IEnumerator, IPluginCollectionEnumerator + { + private readonly PluginCollection m_collection; + private int m_index; + private int m_version; + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the Enumerator class. + /// + /// + internal Enumerator(PluginCollection tc) + { + this.m_collection = tc; + this.m_index = -1; + this.m_version = tc.m_version; + } + + /// + /// Gets the current element in the collection. + /// + /// + /// The current element in the collection. + /// + public IPlugin Current + { + get { return this.m_collection[this.m_index]; } + } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + public bool MoveNext() + { + if (this.m_version != this.m_collection.m_version) + { + throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); + } + + ++this.m_index; + return this.m_index < this.m_collection.Count; + } + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + public void Reset() + { + this.m_index = -1; + } + + object IEnumerator.Current + { + get { return this.Current; } + } + } + + /// + private sealed class ReadOnlyPluginCollection : PluginCollection + { + private readonly PluginCollection m_collection; + + internal ReadOnlyPluginCollection(PluginCollection list) + : base(Tag.Default) + { + this.m_collection = list; + } + + public override void CopyTo(IPlugin[] array) + { + this.m_collection.CopyTo(array); + } + + public override void CopyTo(IPlugin[] array, int start) + { + this.m_collection.CopyTo(array, start); + } + + public override int Count + { + get { return this.m_collection.Count; } + } + + public override bool IsSynchronized + { + get { return this.m_collection.IsSynchronized; } + } + + public override object SyncRoot + { + get { return this.m_collection.SyncRoot; } + } + + public override IPlugin this[int i] + { + get { return this.m_collection[i]; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int Add(IPlugin x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Clear() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool Contains(IPlugin x) + { + return this.m_collection.Contains(x); + } + + public override int IndexOf(IPlugin x) + { + return this.m_collection.IndexOf(x); + } + + public override void Insert(int pos, IPlugin x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Remove(IPlugin x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void RemoveAt(int pos) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool IsFixedSize + { + get { return true; } + } + + public override bool IsReadOnly + { + get { return true; } + } + + public override IPluginCollectionEnumerator GetEnumerator() + { + return this.m_collection.GetEnumerator(); + } + + // (just to mimic some nice features of ArrayList) + public override int Capacity + { + get { return this.m_collection.Capacity; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int AddRange(PluginCollection x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override int AddRange(IPlugin[] x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs index 396cf05016b..888ad8b1916 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs @@ -1,193 +1,176 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Util; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Plugin { - /// - /// Map of repository plugins. - /// - /// - /// - /// This class is a name keyed map of the plugins that are - /// attached to a repository. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class PluginMap - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// The repository that the plugins should be attached to. - /// - /// - /// Initialize a new instance of the class with a - /// repository that the plugins should be attached to. - /// - /// - public PluginMap(ILoggerRepository repository) - { - m_repository = repository; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets a by name. - /// - /// The name of the to lookup. - /// - /// The from the map with the name specified, or - /// null if no plugin is found. - /// - /// - /// - /// Lookup a plugin by name. If the plugin is not found null - /// will be returned. - /// - /// - public IPlugin this[string name] - { - get - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - lock(this) - { - return (IPlugin)m_mapName2Plugin[name]; - } - } - } - - /// - /// Gets all possible plugins as a list of objects. - /// - /// All possible plugins as a list of objects. - /// - /// - /// Get a collection of all the plugins defined in this map. - /// - /// - public PluginCollection AllPlugins - { - get - { - lock(this) - { - return new PluginCollection(m_mapName2Plugin.Values); - } - } - } - - #endregion Public Instance Properties - - #region Public Instance Methods - - /// - /// Adds a to the map. - /// - /// The to add to the map. - /// - /// - /// The will be attached to the repository when added. - /// - /// - /// If there already exists a plugin with the same name - /// attached to the repository then the old plugin will - /// be and replaced with - /// the new plugin. - /// - /// - public void Add(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException("plugin"); - } - - IPlugin curPlugin = null; - - lock(this) - { - // Get the current plugin if it exists - curPlugin = m_mapName2Plugin[plugin.Name] as IPlugin; - - // Store new plugin - m_mapName2Plugin[plugin.Name] = plugin; - } - - // Shutdown existing plugin with same name - if (curPlugin != null) - { - curPlugin.Shutdown(); - } - - // Attach new plugin to repository - plugin.Attach(m_repository); - } - - /// - /// Removes a from the map. - /// - /// The to remove from the map. - /// - /// - /// Remove a specific plugin from this map. - /// - /// - public void Remove(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException("plugin"); - } - lock(this) - { - m_mapName2Plugin.Remove(plugin.Name); - } - } - - #endregion Public Instance Methods - - #region Private Instance Fields - - private readonly Hashtable m_mapName2Plugin = new Hashtable(); - private readonly ILoggerRepository m_repository; - - #endregion Private Instance Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Repository; + using log4net.Util; + + /// + /// Map of repository plugins. + /// + /// + /// + /// This class is a name keyed map of the plugins that are + /// attached to a repository. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class PluginMap + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The repository that the plugins should be attached to. + /// + /// + /// Initialize a new instance of the class with a + /// repository that the plugins should be attached to. + /// + /// + public PluginMap(ILoggerRepository repository) + { + this.m_repository = repository; + } + + /// + /// Gets a by name. + /// + /// The name of the to lookup. + /// + /// The from the map with the name specified, or + /// null if no plugin is found. + /// + /// + /// + /// Lookup a plugin by name. If the plugin is not found null + /// will be returned. + /// + /// + public IPlugin this[string name] + { + get + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + lock (this) + { + return (IPlugin)this.m_mapName2Plugin[name]; + } + } + } + + /// + /// Gets all possible plugins as a list of objects. + /// + /// All possible plugins as a list of objects. + /// + /// + /// Get a collection of all the plugins defined in this map. + /// + /// + public PluginCollection AllPlugins + { + get + { + lock (this) + { + return new PluginCollection(this.m_mapName2Plugin.Values); + } + } + } + + /// + /// Adds a to the map. + /// + /// The to add to the map. + /// + /// + /// The will be attached to the repository when added. + /// + /// + /// If there already exists a plugin with the same name + /// attached to the repository then the old plugin will + /// be and replaced with + /// the new plugin. + /// + /// + public void Add(IPlugin plugin) + { + if (plugin == null) + { + throw new ArgumentNullException("plugin"); + } + + IPlugin curPlugin = null; + + lock (this) + { + // Get the current plugin if it exists + curPlugin = this.m_mapName2Plugin[plugin.Name] as IPlugin; + + // Store new plugin + this.m_mapName2Plugin[plugin.Name] = plugin; + } + + // Shutdown existing plugin with same name + if (curPlugin != null) + { + curPlugin.Shutdown(); + } + + // Attach new plugin to repository + plugin.Attach(this.m_repository); + } + + /// + /// Removes a from the map. + /// + /// The to remove from the map. + /// + /// + /// Remove a specific plugin from this map. + /// + /// + public void Remove(IPlugin plugin) + { + if (plugin == null) + { + throw new ArgumentNullException("plugin"); + } + + lock (this) + { + this.m_mapName2Plugin.Remove(plugin.Name); + } + } + + private readonly Hashtable m_mapName2Plugin = new Hashtable(); + private readonly ILoggerRepository m_repository; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs index 67e4ccf8571..3496caa4211 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs @@ -1,152 +1,134 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Plugin { - /// - /// Base implementation of - /// - /// - /// - /// Default abstract implementation of the - /// interface. This base class can be used by implementors - /// of the interface. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public abstract class PluginSkeleton : IPlugin - { - #region Protected Instance Constructors - - /// - /// Constructor - /// - /// the name of the plugin - /// - /// Initializes a new Plugin with the specified name. - /// - protected PluginSkeleton(string name) - { - m_name = name; - } - - #endregion Protected Instance Constructors - - #region Implementation of IPlugin - - /// - /// Gets or sets the name of the plugin. - /// - /// - /// The name of the plugin. - /// - /// - /// - /// Plugins are stored in the - /// keyed by name. Each plugin instance attached to a - /// repository must be a unique name. - /// - /// - /// The name of the plugin must not change one the - /// plugin has been attached to a repository. - /// - /// - public virtual string Name - { - get { return m_name; } - set { m_name = value; } - } - - /// - /// Attaches this plugin to a . - /// - /// The that this plugin should be attached to. - /// - /// - /// A plugin may only be attached to a single repository. - /// - /// - /// This method is called when the plugin is attached to the repository. - /// - /// - public virtual void Attach(ILoggerRepository repository) - { - m_repository = repository; - } - - /// - /// Is called when the plugin is to shutdown. - /// - /// - /// - /// This method is called to notify the plugin that - /// it should stop operating and should detach from - /// the repository. - /// - /// - public virtual void Shutdown() - { - } - - #endregion Implementation of IPlugin - - #region Protected Instance Properties - - /// - /// The repository for this plugin - /// - /// - /// The that this plugin is attached to. - /// - /// - /// - /// Gets or sets the that this plugin is - /// attached to. - /// - /// - protected virtual ILoggerRepository LoggerRepository - { - get { return this.m_repository; } - set { this.m_repository = value; } - } - - #endregion Protected Instance Properties - - #region Private Instance Fields - - /// - /// The name of this plugin. - /// - private string m_name; - - /// - /// The repository this plugin is attached to. - /// - private ILoggerRepository m_repository; - - #endregion Private Instance Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using log4net.Repository; + + /// + /// Base implementation of . + /// + /// + /// + /// Default abstract implementation of the + /// interface. This base class can be used by implementors + /// of the interface. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class PluginSkeleton : IPlugin + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// the name of the plugin. + /// + /// Initializes a new Plugin with the specified name. + /// + protected PluginSkeleton(string name) + { + this.m_name = name; + } + + /// + /// Gets or sets the name of the plugin. + /// + /// + /// The name of the plugin. + /// + /// + /// + /// Plugins are stored in the + /// keyed by name. Each plugin instance attached to a + /// repository must be a unique name. + /// + /// + /// The name of the plugin must not change one the + /// plugin has been attached to a repository. + /// + /// + public virtual string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + /// + /// Attaches this plugin to a . + /// + /// The that this plugin should be attached to. + /// + /// + /// A plugin may only be attached to a single repository. + /// + /// + /// This method is called when the plugin is attached to the repository. + /// + /// + public virtual void Attach(ILoggerRepository repository) + { + this.m_repository = repository; + } + + /// + /// Is called when the plugin is to shutdown. + /// + /// + /// + /// This method is called to notify the plugin that + /// it should stop operating and should detach from + /// the repository. + /// + /// + public virtual void Shutdown() + { + } + + /// + /// Gets or sets the repository for this plugin. + /// + /// + /// The that this plugin is attached to. + /// + /// + /// + /// Gets or sets the that this plugin is + /// attached to. + /// + /// + protected virtual ILoggerRepository LoggerRepository + { + get { return this.m_repository; } + set { this.m_repository = value; } + } + + /// + /// The name of this plugin. + /// + private string m_name; + + /// + /// The repository this plugin is attached to. + /// + private ILoggerRepository m_repository; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs index d4d83715386..ce75e250439 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,265 +18,234 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting #if !NETCF using System; using System.Runtime.Remoting; - -using log4net.Util; -using log4net.Repository; + using log4net.Core; +using log4net.Repository; +using log4net.Util; + using IRemoteLoggingSink = log4net.Appender.RemotingAppender.IRemoteLoggingSink; namespace log4net.Plugin { - /// - /// Plugin that listens for events from the - /// - /// - /// - /// This plugin publishes an instance of - /// on a specified . This listens for logging events delivered from - /// a remote . - /// - /// - /// When an event is received it is relogged within the attached repository - /// as if it had been raised locally. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class RemoteLoggingServerPlugin : PluginSkeleton - { - #region Public Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - /// The property must be set. - /// - /// - public RemoteLoggingServerPlugin() : base("RemoteLoggingServerPlugin:Unset URI") - { - } - - /// - /// Construct with sink Uri. - /// - /// The name to publish the sink under in the remoting infrastructure. - /// See for more details. - /// - /// - /// Initializes a new instance of the class - /// with specified name. - /// - /// - public RemoteLoggingServerPlugin(string sinkUri) : base("RemoteLoggingServerPlugin:"+sinkUri) - { - m_sinkUri = sinkUri; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the URI of this sink. - /// - /// - /// The URI of this sink. - /// - /// - /// - /// This is the name under which the object is marshaled. - /// - /// - /// - public virtual string SinkUri - { - get { return m_sinkUri; } - set { m_sinkUri = value; } - } - - #endregion Public Instance Properties - - #region Override implementation of PluginSkeleton - - /// - /// Attaches this plugin to a . - /// - /// The that this plugin should be attached to. - /// - /// - /// A plugin may only be attached to a single repository. - /// - /// - /// This method is called when the plugin is attached to the repository. - /// - /// + /// + /// Plugin that listens for events from the . + /// + /// + /// + /// This plugin publishes an instance of + /// on a specified . This listens for logging events delivered from + /// a remote . + /// + /// + /// When an event is received it is relogged within the attached repository + /// as if it had been raised locally. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class RemoteLoggingServerPlugin : PluginSkeleton + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + /// The property must be set. + /// + /// + public RemoteLoggingServerPlugin() + : base("RemoteLoggingServerPlugin:Unset URI") + { + } + + /// + /// Initializes a new instance of the class. + /// Construct with sink Uri. + /// + /// The name to publish the sink under in the remoting infrastructure. + /// See for more details. + /// + /// + /// Initializes a new instance of the class + /// with specified name. + /// + /// + public RemoteLoggingServerPlugin(string sinkUri) + : base("RemoteLoggingServerPlugin:" + sinkUri) + { + this.m_sinkUri = sinkUri; + } + + /// + /// Gets or sets the URI of this sink. + /// + /// + /// The URI of this sink. + /// + /// + /// + /// This is the name under which the object is marshaled. + /// . + /// + /// + public virtual string SinkUri + { + get { return this.m_sinkUri; } + set { this.m_sinkUri = value; } + } + + /// + /// Attaches this plugin to a . + /// + /// The that this plugin should be attached to. + /// + /// + /// A plugin may only be attached to a single repository. + /// + /// + /// This method is called when the plugin is attached to the repository. + /// + /// #if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] + [System.Security.SecuritySafeCritical] #endif - override public void Attach(ILoggerRepository repository) - { - base.Attach(repository); - - // Create the sink and marshal it - m_sink = new RemoteLoggingSinkImpl(repository); - - try - { - RemotingServices.Marshal(m_sink, m_sinkUri, typeof(IRemoteLoggingSink)); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to Marshal remoting sink", ex); - } - } - - /// - /// Is called when the plugin is to shutdown. - /// - /// - /// - /// When the plugin is shutdown the remote logging - /// sink is disconnected. - /// - /// + public override void Attach(ILoggerRepository repository) + { + base.Attach(repository); + + // Create the sink and marshal it + this.m_sink = new RemoteLoggingSinkImpl(repository); + + try + { + RemotingServices.Marshal(this.m_sink, this.m_sinkUri, typeof(IRemoteLoggingSink)); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to Marshal remoting sink", ex); + } + } + + /// + /// Is called when the plugin is to shutdown. + /// + /// + /// + /// When the plugin is shutdown the remote logging + /// sink is disconnected. + /// + /// #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif - override public void Shutdown() - { - // Stops the sink from receiving messages - RemotingServices.Disconnect(m_sink); - m_sink = null; - - base.Shutdown(); - } - - #endregion Override implementation of PluginSkeleton - - #region Private Instance Fields - - private RemoteLoggingSinkImpl m_sink; - private string m_sinkUri; - - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the RemoteLoggingServerPlugin class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(RemoteLoggingServerPlugin); - - #endregion Private Static Fields - - /// - /// Delivers objects to a remote sink. - /// - /// - /// - /// Internal class used to listen for logging events - /// and deliver them to the local repository. - /// - /// - private class RemoteLoggingSinkImpl : MarshalByRefObject, IRemoteLoggingSink - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// The repository to log to. - /// - /// - /// Initializes a new instance of the for the - /// specified . - /// - /// - public RemoteLoggingSinkImpl(ILoggerRepository repository) - { - m_repository = repository; - } - - #endregion Public Instance Constructors - - #region Implementation of IRemoteLoggingSink - - /// - /// Logs the events to the repository. - /// - /// The events to log. - /// - /// - /// The events passed are logged to the - /// - /// - public void LogEvents(LoggingEvent[] events) - { - if (events != null) - { - foreach(LoggingEvent logEvent in events) - { - if (logEvent != null) - { - m_repository.Log(logEvent); - } - } - } - } - - #endregion Implementation of IRemoteLoggingSink - - #region Override implementation of MarshalByRefObject - - /// - /// Obtains a lifetime service object to control the lifetime - /// policy for this instance. - /// - /// null to indicate that this instance should live forever. - /// - /// - /// Obtains a lifetime service object to control the lifetime - /// policy for this instance. This object should live forever - /// therefore this implementation returns null. - /// - /// + public override void Shutdown() + { + // Stops the sink from receiving messages + RemotingServices.Disconnect(this.m_sink); + this.m_sink = null; + + base.Shutdown(); + } + + private RemoteLoggingSinkImpl m_sink; + private string m_sinkUri; + + /// + /// The fully qualified type of the RemoteLoggingServerPlugin class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(RemoteLoggingServerPlugin); + + /// + /// Delivers objects to a remote sink. + /// + /// + /// + /// Internal class used to listen for logging events + /// and deliver them to the local repository. + /// + /// + private class RemoteLoggingSinkImpl : MarshalByRefObject, IRemoteLoggingSink + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The repository to log to. + /// + /// + /// Initializes a new instance of the for the + /// specified . + /// + /// + public RemoteLoggingSinkImpl(ILoggerRepository repository) + { + this.m_repository = repository; + } + + /// + /// Logs the events to the repository. + /// + /// The events to log. + /// + /// + /// The events passed are logged to the . + /// + /// + public void LogEvents(LoggingEvent[] events) + { + if (events != null) + { + foreach (LoggingEvent logEvent in events) + { + if (logEvent != null) + { + this.m_repository.Log(logEvent); + } + } + } + } + + /// + /// Obtains a lifetime service object to control the lifetime + /// policy for this instance. + /// + /// null to indicate that this instance should live forever. + /// + /// + /// Obtains a lifetime service object to control the lifetime + /// policy for this instance. This object should live forever + /// therefore this implementation returns null. + /// + /// #if NET_4_0 || MONO_4_0 [System.Security.SecurityCritical] #endif public override object InitializeLifetimeService() - { - return null; - } - - #endregion Override implementation of MarshalByRefObject - - #region Private Instance Fields - - /// - /// The underlying that events should - /// be logged to. - /// - private readonly ILoggerRepository m_repository; - - #endregion Private Instance Fields - } - } + { + return null; + } + + /// + /// The underlying that events should + /// be logged to. + /// + private readonly ILoggerRepository m_repository; + } + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs index a9d6f0894a1..06874302c6d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs @@ -1,8 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace log4net.Repository +{ + /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -23,20 +25,18 @@ * */ -using System; -using System.Collections; - -namespace log4net.Repository -{ + using System; + using System.Collections; + /// - /// + /// /// public class ConfigurationChangedEventArgs : EventArgs { - private readonly ICollection configurationMessages; - - /// - /// + private readonly ICollection configurationMessages; + + /// + /// Initializes a new instance of the class. /// /// public ConfigurationChangedEventArgs(ICollection configurationMessages) @@ -45,11 +45,11 @@ public ConfigurationChangedEventArgs(ICollection configurationMessages) } /// - /// + /// /// public ICollection ConfigurationMessages { - get { return configurationMessages; } + get { return this.configurationMessages; } } } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs index d06e30589a1..6ad84edb010 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs @@ -1,118 +1,111 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository.Hierarchy { - /// - /// Default implementation of - /// - /// - /// - /// This default implementation of the - /// interface is used to create the default subclass - /// of the object. - /// - /// - /// Nicko Cadell - /// Gert Driesen - internal class DefaultLoggerFactory : ILoggerFactory - { - #region Internal Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal DefaultLoggerFactory() - { - } - - #endregion Internal Instance Constructors - - #region Implementation of ILoggerFactory - - /// - /// Create a new instance - /// - /// The that will own the . - /// The name of the . - /// The instance for the specified name. - /// - /// - /// Create a new instance with the - /// specified name. - /// - /// - /// Called by the to create - /// new named instances. - /// - /// - /// If the is null then the root logger - /// must be returned. - /// - /// - public Logger CreateLogger(ILoggerRepository repository, string name) - { - if (name == null) - { - return new RootLogger(repository.LevelMap.LookupWithDefault(Level.Debug)); - } - return new LoggerImpl(name); - } - - #endregion - - /// - /// Default internal subclass of - /// - /// - /// - /// This subclass has no additional behavior over the - /// class but does allow instances - /// to be created. - /// - /// - internal sealed class LoggerImpl : Logger - { - /// - /// Construct a new Logger - /// - /// the name of the logger - /// - /// - /// Initializes a new instance of the class - /// with the specified name. - /// - /// - internal LoggerImpl(string name) : base(name) - { - } - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using log4net.Core; + + /// + /// Default implementation of . + /// + /// + /// + /// This default implementation of the + /// interface is used to create the default subclass + /// of the object. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + internal class DefaultLoggerFactory : ILoggerFactory + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal DefaultLoggerFactory() + { + } + + /// + /// Create a new instance. + /// + /// The that will own the . + /// The name of the . + /// The instance for the specified name. + /// + /// + /// Create a new instance with the + /// specified name. + /// + /// + /// Called by the to create + /// new named instances. + /// + /// + /// If the is null then the root logger + /// must be returned. + /// + /// + public Logger CreateLogger(ILoggerRepository repository, string name) + { + if (name == null) + { + return new RootLogger(repository.LevelMap.LookupWithDefault(Level.Debug)); + } + + return new LoggerImpl(name); + } + + /// + /// Default internal subclass of . + /// + /// + /// + /// This subclass has no additional behavior over the + /// class but does allow instances + /// to be created. + /// + /// + internal sealed class LoggerImpl : Logger + { + /// + /// Initializes a new instance of the class. + /// Construct a new Logger. + /// + /// the name of the logger. + /// + /// + /// Initializes a new instance of the class + /// with the specified name. + /// + /// + internal LoggerImpl(string name) + : base(name) + { + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs index 22967210abc..017a81d7d9a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs @@ -1,1090 +1,1066 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using log4net.Appender; -using log4net.Core; -using log4net.Repository; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository.Hierarchy -{ - #region LoggerCreationEvent - - /// - /// Delegate used to handle logger creation event notifications. - /// - /// The in which the has been created. - /// The event args that hold the instance that has been created. - /// - /// - /// Delegate used to handle logger creation event notifications. - /// - /// - public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e); - - /// - /// Provides data for the event. - /// - /// - /// - /// A event is raised every time a - /// is created. - /// - /// - public class LoggerCreationEventArgs : EventArgs - { - /// - /// The created - /// - private Logger m_log; - - /// - /// Constructor - /// - /// The that has been created. - /// - /// - /// Initializes a new instance of the event argument - /// class,with the specified . - /// - /// - public LoggerCreationEventArgs(Logger log) - { - m_log = log; - } - - /// - /// Gets the that has been created. - /// - /// - /// The that has been created. - /// - /// - /// - /// The that has been created. - /// - /// - public Logger Logger - { - get { return m_log; } - } - } - - #endregion LoggerCreationEvent - - /// - /// Hierarchical organization of loggers - /// - /// - /// - /// The casual user should not have to deal with this class - /// directly. - /// - /// - /// This class is specialized in retrieving loggers by name and - /// also maintaining the logger hierarchy. Implements the - /// interface. - /// - /// - /// The structure of the logger hierarchy is maintained by the - /// method. The hierarchy is such that children - /// link to their parent but parents do not have any references to their - /// children. Moreover, loggers can be instantiated in any order, in - /// particular descendant before ancestor. - /// - /// - /// In case a descendant is created before a particular ancestor, - /// then it creates a provision node for the ancestor and adds itself - /// to the provision node. Other descendants of the same ancestor add - /// themselves to the previously created provision node. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IXmlRepositoryConfigurator - { - #region Public Events - - /// - /// Event used to notify that a logger has been created. - /// - /// - /// - /// Event raised when a logger is created. - /// - /// - public event LoggerCreationEventHandler LoggerCreatedEvent - { - add { m_loggerCreatedEvent += value; } - remove { m_loggerCreatedEvent -= value; } - } - - #endregion Public Events - - #region Public Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public Hierarchy() : this(new DefaultLoggerFactory()) - { - } - - /// - /// Construct with properties - /// - /// The properties to pass to this repository. - /// - /// - /// Initializes a new instance of the class. - /// - /// - public Hierarchy(PropertiesDictionary properties) : this(properties, new DefaultLoggerFactory()) - { - } - - /// - /// Construct with a logger factory - /// - /// The factory to use to create new logger instances. - /// - /// - /// Initializes a new instance of the class with - /// the specified . - /// - /// - public Hierarchy(ILoggerFactory loggerFactory) : this(new PropertiesDictionary(), loggerFactory) - { - } - - /// - /// Construct with properties and a logger factory - /// - /// The properties to pass to this repository. - /// The factory to use to create new logger instances. - /// - /// - /// Initializes a new instance of the class with - /// the specified . - /// - /// - public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) : base(properties) - { - if (loggerFactory == null) - { - throw new ArgumentNullException("loggerFactory"); - } - - m_defaultFactory = loggerFactory; - - m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Has no appender warning been emitted - /// - /// - /// - /// Flag to indicate if we have already issued a warning - /// about not having an appender warning. - /// - /// - public bool EmittedNoAppenderWarning - { - get { return m_emittedNoAppenderWarning; } - set { m_emittedNoAppenderWarning = value; } - } - - /// - /// Get the root of this hierarchy - /// - /// - /// - /// Get the root of this hierarchy. - /// - /// - public Logger Root - { - get - { - if (m_root == null) - { - lock(this) - { - if (m_root == null) - { - // Create the root logger - Logger root = m_defaultFactory.CreateLogger(this, null); - root.Hierarchy = this; - - // Store root - m_root = root; - } - } - } - return m_root; - } - } - - /// - /// Gets or sets the default instance. - /// - /// The default - /// - /// - /// The logger factory is used to create logger instances. - /// - /// - public ILoggerFactory LoggerFactory - { - get { return m_defaultFactory; } - set - { - if (value == null) - { - throw new ArgumentNullException("value"); - } - m_defaultFactory = value; - } - } - - #endregion Public Instance Properties - - #region Override Implementation of LoggerRepositorySkeleton - - /// - /// Test if a logger exists - /// - /// The name of the logger to lookup - /// The Logger object with the name specified - /// - /// - /// Check if the named logger exists in the hierarchy. If so return - /// its reference, otherwise returns null. - /// - /// - override public ILogger Exists(string name) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - lock(m_ht) - { - return m_ht[new LoggerKey(name)] as Logger; - } - } - - /// - /// Returns all the currently defined loggers in the hierarchy as an Array - /// - /// All the defined loggers - /// - /// - /// Returns all the currently defined loggers in the hierarchy as an Array. - /// The root logger is not included in the returned - /// enumeration. - /// - /// - override public ILogger[] GetCurrentLoggers() - { - // The accumulation in loggers is necessary because not all elements in - // ht are Logger objects as there might be some ProvisionNodes - // as well. - lock(m_ht) - { - System.Collections.ArrayList loggers = new System.Collections.ArrayList(m_ht.Count); - - // Iterate through m_ht values - foreach(object node in m_ht.Values) - { - if (node is Logger) - { - loggers.Add(node); - } - } - return (Logger[])loggers.ToArray(typeof(Logger)); - } - } - - /// - /// Return a new logger instance named as the first parameter using - /// the default factory. - /// - /// - /// - /// Return a new logger instance named as the first parameter using - /// the default factory. - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated and - /// then linked with its existing ancestors as well as children. - /// - /// - /// The name of the logger to retrieve - /// The logger object with the name specified - override public ILogger GetLogger(string name) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - return GetLogger(name, m_defaultFactory); - } - - /// - /// Shutting down a hierarchy will safely close and remove - /// all appenders in all loggers including the root logger. - /// - /// - /// - /// Shutting down a hierarchy will safely close and remove - /// all appenders in all loggers including the root logger. - /// - /// - /// Some appenders need to be closed before the - /// application exists. Otherwise, pending logging events might be - /// lost. - /// - /// - /// The Shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - override public void Shutdown() - { - LogLog.Debug(declaringType, "Shutdown called on Hierarchy ["+this.Name+"]"); - - // begin by closing nested appenders - Root.CloseNestedAppenders(); - - lock(m_ht) - { - ILogger[] currentLoggers = this.GetCurrentLoggers(); - - foreach(Logger logger in currentLoggers) - { - logger.CloseNestedAppenders(); - } - - // then, remove all appenders - Root.RemoveAllAppenders(); - - foreach(Logger logger in currentLoggers) - { - logger.RemoveAllAppenders(); - } - } - - base.Shutdown(); - } - - /// - /// Reset all values contained in this hierarchy instance to their default. - /// - /// - /// - /// Reset all values contained in this hierarchy instance to their - /// default. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set its default "off" value. - /// - /// - /// Existing loggers are not removed. They are just reset. - /// - /// - /// This method should be used sparingly and with care as it will - /// block all logging until it is completed. - /// - /// - override public void ResetConfiguration() - { - Root.Level = LevelMap.LookupWithDefault(Level.Debug); - Threshold = LevelMap.LookupWithDefault(Level.All); - - // the synchronization is needed to prevent hashtable surprises - lock(m_ht) - { - Shutdown(); // nested locks are OK - - foreach(Logger l in this.GetCurrentLoggers()) - { - l.Level = null; - l.Additivity = true; - } - } - - base.ResetConfiguration(); - - // Notify listeners - OnConfigurationChanged(null); - } - - /// - /// Log the logEvent through this hierarchy. - /// - /// the event to log - /// - /// - /// This method should not normally be used to log. - /// The interface should be used - /// for routine logging. This interface can be obtained - /// using the method. - /// - /// - /// The logEvent is delivered to the appropriate logger and - /// that logger is then responsible for logging the event. - /// - /// - override public void Log(LoggingEvent logEvent) - { - if (logEvent == null) - { - throw new ArgumentNullException("logEvent"); - } - - this.GetLogger(logEvent.LoggerName, m_defaultFactory).Log(logEvent); - } - - /// - /// Returns all the Appenders that are currently configured - /// - /// An array containing all the currently configured appenders - /// - /// - /// Returns all the instances that are currently configured. - /// All the loggers are searched for appenders. The appenders may also be containers - /// for appenders and these are also searched for additional loggers. - /// - /// - /// The list returned is unordered but does not contain duplicates. - /// - /// - override public Appender.IAppender[] GetAppenders() - { - System.Collections.ArrayList appenderList = new System.Collections.ArrayList(); - - CollectAppenders(appenderList, Root); - - foreach(Logger logger in GetCurrentLoggers()) - { - CollectAppenders(appenderList, logger); - } - - return (Appender.IAppender[])appenderList.ToArray(typeof(Appender.IAppender)); - } - - #endregion Override Implementation of LoggerRepositorySkeleton - - #region Private Static Methods +{ + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Appender; + using log4net.Core; + using log4net.Repository; + using log4net.Util; + + /// + /// Delegate used to handle logger creation event notifications. + /// + /// The in which the has been created. + /// The event args that hold the instance that has been created. + /// + /// + /// Delegate used to handle logger creation event notifications. + /// + /// + public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e); + + /// + /// Provides data for the event. + /// + /// + /// + /// A event is raised every time a + /// is created. + /// + /// + public class LoggerCreationEventArgs : EventArgs + { + /// + /// The created. + /// + private Logger m_log; + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The that has been created. + /// + /// + /// Initializes a new instance of the event argument + /// class,with the specified . + /// + /// + public LoggerCreationEventArgs(Logger log) + { + this.m_log = log; + } + + /// + /// Gets the that has been created. + /// + /// + /// The that has been created. + /// + /// + /// + /// The that has been created. + /// + /// + public Logger Logger + { + get { return this.m_log; } + } + } + + /// + /// Hierarchical organization of loggers. + /// + /// + /// + /// The casual user should not have to deal with this class + /// directly. + /// + /// + /// This class is specialized in retrieving loggers by name and + /// also maintaining the logger hierarchy. Implements the + /// interface. + /// + /// + /// The structure of the logger hierarchy is maintained by the + /// method. The hierarchy is such that children + /// link to their parent but parents do not have any references to their + /// children. Moreover, loggers can be instantiated in any order, in + /// particular descendant before ancestor. + /// + /// + /// In case a descendant is created before a particular ancestor, + /// then it creates a provision node for the ancestor and adds itself + /// to the provision node. Other descendants of the same ancestor add + /// themselves to the previously created provision node. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IXmlRepositoryConfigurator + { + /// + /// Event used to notify that a logger has been created. + /// + /// + /// + /// Event raised when a logger is created. + /// + /// + public event LoggerCreationEventHandler LoggerCreatedEvent + { + add { this.m_loggerCreatedEvent += value; } + remove { this.m_loggerCreatedEvent -= value; } + } + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public Hierarchy() + : this(new DefaultLoggerFactory()) + { + } + + /// + /// Initializes a new instance of the class. + /// Construct with properties. + /// + /// The properties to pass to this repository. + /// + /// + /// Initializes a new instance of the class. + /// + /// + public Hierarchy(PropertiesDictionary properties) + : this(properties, new DefaultLoggerFactory()) + { + } + + /// + /// Initializes a new instance of the class. + /// Construct with a logger factory. + /// + /// The factory to use to create new logger instances. + /// + /// + /// Initializes a new instance of the class with + /// the specified . + /// + /// + public Hierarchy(ILoggerFactory loggerFactory) + : this(new PropertiesDictionary(), loggerFactory) + { + } + + /// + /// Initializes a new instance of the class. + /// Construct with properties and a logger factory. + /// + /// The properties to pass to this repository. + /// The factory to use to create new logger instances. + /// + /// + /// Initializes a new instance of the class with + /// the specified . + /// + /// + public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) + : base(properties) + { + if (loggerFactory == null) + { + throw new ArgumentNullException("loggerFactory"); + } + + this.m_defaultFactory = loggerFactory; + + this.m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); + } + + /// + /// Gets or sets a value indicating whether has no appender warning been emitted. + /// + /// + /// + /// Flag to indicate if we have already issued a warning + /// about not having an appender warning. + /// + /// + public bool EmittedNoAppenderWarning + { + get { return this.m_emittedNoAppenderWarning; } + set { this.m_emittedNoAppenderWarning = value; } + } + + /// + /// Gets get the root of this hierarchy. + /// + /// + /// + /// Get the root of this hierarchy. + /// + /// + public Logger Root + { + get + { + if (this.m_root == null) + { + lock (this) + { + if (this.m_root == null) + { + // Create the root logger + Logger root = this.m_defaultFactory.CreateLogger(this, null); + root.Hierarchy = this; + + // Store root + this.m_root = root; + } + } + } + + return this.m_root; + } + } + + /// + /// Gets or sets the default instance. + /// + /// The default . + /// + /// + /// The logger factory is used to create logger instances. + /// + /// + public ILoggerFactory LoggerFactory + { + get { return this.m_defaultFactory; } + + set + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + + this.m_defaultFactory = value; + } + } + + /// + /// Test if a logger exists. + /// + /// The name of the logger to lookup. + /// The Logger object with the name specified. + /// + /// + /// Check if the named logger exists in the hierarchy. If so return + /// its reference, otherwise returns null. + /// + /// + public override ILogger Exists(string name) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + lock (this.m_ht) + { + return this.m_ht[new LoggerKey(name)] as Logger; + } + } + + /// + /// Returns all the currently defined loggers in the hierarchy as an Array. + /// + /// All the defined loggers. + /// + /// + /// Returns all the currently defined loggers in the hierarchy as an Array. + /// The root logger is not included in the returned + /// enumeration. + /// + /// + public override ILogger[] GetCurrentLoggers() + { + // The accumulation in loggers is necessary because not all elements in + // ht are Logger objects as there might be some ProvisionNodes + // as well. + lock (this.m_ht) + { + System.Collections.ArrayList loggers = new System.Collections.ArrayList(this.m_ht.Count); + + // Iterate through m_ht values + foreach (object node in this.m_ht.Values) + { + if (node is Logger) + { + loggers.Add(node); + } + } + + return (Logger[])loggers.ToArray(typeof(Logger)); + } + } + + /// + /// Return a new logger instance named as the first parameter using + /// the default factory. + /// + /// + /// + /// Return a new logger instance named as the first parameter using + /// the default factory. + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated and + /// then linked with its existing ancestors as well as children. + /// + /// + /// The name of the logger to retrieve. + /// The logger object with the name specified. + public override ILogger GetLogger(string name) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + return this.GetLogger(name, this.m_defaultFactory); + } + + /// + /// Shutting down a hierarchy will safely close and remove + /// all appenders in all loggers including the root logger. + /// + /// + /// + /// Shutting down a hierarchy will safely close and remove + /// all appenders in all loggers including the root logger. + /// + /// + /// Some appenders need to be closed before the + /// application exists. Otherwise, pending logging events might be + /// lost. + /// + /// + /// The Shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public override void Shutdown() + { + LogLog.Debug(declaringType, "Shutdown called on Hierarchy [" + this.Name + "]"); + + // begin by closing nested appenders + this.Root.CloseNestedAppenders(); + + lock (this.m_ht) + { + ILogger[] currentLoggers = this.GetCurrentLoggers(); + + foreach (Logger logger in currentLoggers) + { + logger.CloseNestedAppenders(); + } + + // then, remove all appenders + this.Root.RemoveAllAppenders(); + + foreach (Logger logger in currentLoggers) + { + logger.RemoveAllAppenders(); + } + } + + base.Shutdown(); + } + + /// + /// Reset all values contained in this hierarchy instance to their default. + /// + /// + /// + /// Reset all values contained in this hierarchy instance to their + /// default. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set its default "off" value. + /// + /// + /// Existing loggers are not removed. They are just reset. + /// + /// + /// This method should be used sparingly and with care as it will + /// block all logging until it is completed. + /// + /// + public override void ResetConfiguration() + { + this.Root.Level = this.LevelMap.LookupWithDefault(Level.Debug); + this.Threshold = this.LevelMap.LookupWithDefault(Level.All); + + // the synchronization is needed to prevent hashtable surprises + lock (this.m_ht) + { + this.Shutdown(); // nested locks are OK + + foreach (Logger l in this.GetCurrentLoggers()) + { + l.Level = null; + l.Additivity = true; + } + } + + base.ResetConfiguration(); + + // Notify listeners + this.OnConfigurationChanged(null); + } /// - /// Collect the appenders from an . - /// The appender may also be a container. - /// - /// - /// - private static void CollectAppender(System.Collections.ArrayList appenderList, Appender.IAppender appender) - { - if (!appenderList.Contains(appender)) - { - appenderList.Add(appender); - - IAppenderAttachable container = appender as IAppenderAttachable; - if (container != null) - { - CollectAppenders(appenderList, container); - } - } - } - - /// - /// Collect the appenders from an container - /// - /// - /// - private static void CollectAppenders(System.Collections.ArrayList appenderList, IAppenderAttachable container) - { - foreach(Appender.IAppender appender in container.Appenders) - { - CollectAppender(appenderList, appender); - } + /// Log the logEvent through this hierarchy. + /// + /// the event to log. + /// + /// + /// This method should not normally be used to log. + /// The interface should be used + /// for routine logging. This interface can be obtained + /// using the method. + /// + /// + /// The logEvent is delivered to the appropriate logger and + /// that logger is then responsible for logging the event. + /// + /// + public override void Log(LoggingEvent logEvent) + { + if (logEvent == null) + { + throw new ArgumentNullException("logEvent"); + } + + this.GetLogger(logEvent.LoggerName, this.m_defaultFactory).Log(logEvent); } - #endregion + /// + /// Returns all the Appenders that are currently configured. + /// + /// An array containing all the currently configured appenders. + /// + /// + /// Returns all the instances that are currently configured. + /// All the loggers are searched for appenders. The appenders may also be containers + /// for appenders and these are also searched for additional loggers. + /// + /// + /// The list returned is unordered but does not contain duplicates. + /// + /// + public override Appender.IAppender[] GetAppenders() + { + System.Collections.ArrayList appenderList = new System.Collections.ArrayList(); + + CollectAppenders(appenderList, this.Root); + + foreach (Logger logger in this.GetCurrentLoggers()) + { + CollectAppenders(appenderList, logger); + } + + return (Appender.IAppender[])appenderList.ToArray(typeof(Appender.IAppender)); + } + + /// + /// Collect the appenders from an . + /// The appender may also be a container. + /// + /// + /// + private static void CollectAppender(System.Collections.ArrayList appenderList, Appender.IAppender appender) + { + if (!appenderList.Contains(appender)) + { + appenderList.Add(appender); - #region Implementation of IBasicRepositoryConfigurator + IAppenderAttachable container = appender as IAppenderAttachable; + if (container != null) + { + CollectAppenders(appenderList, container); + } + } + } /// - /// Initialize the log4net system using the specified appender - /// - /// the appender to use to log all logging events - void IBasicRepositoryConfigurator.Configure(IAppender appender) - { - BasicRepositoryConfigure(appender); - } + /// Collect the appenders from an container. + ///
+ /// + /// + private static void CollectAppenders(System.Collections.ArrayList appenderList, IAppenderAttachable container) + { + foreach (Appender.IAppender appender in container.Appenders) + { + CollectAppender(appenderList, appender); + } + } + + /// + /// Initialize the log4net system using the specified appender. + /// + /// the appender to use to log all logging events. + void IBasicRepositoryConfigurator.Configure(IAppender appender) + { + this.BasicRepositoryConfigure(appender); + } /// - /// Initialize the log4net system using the specified appenders + /// Initialize the log4net system using the specified appenders. /// - /// the appenders to use to log all logging events + /// the appenders to use to log all logging events. void IBasicRepositoryConfigurator.Configure(params IAppender[] appenders) { - BasicRepositoryConfigure(appenders); + this.BasicRepositoryConfigure(appenders); } - /// - /// Initialize the log4net system using the specified appenders - /// - /// the appenders to use to log all logging events - /// - /// - /// This method provides the same functionality as the - /// method implemented - /// on this object, but it is protected and therefore can be called by subclasses. - /// - /// - protected void BasicRepositoryConfigure(params IAppender[] appenders) - { + /// + /// Initialize the log4net system using the specified appenders. + /// + /// the appenders to use to log all logging events. + /// + /// + /// This method provides the same functionality as the + /// method implemented + /// on this object, but it is protected and therefore can be called by subclasses. + /// + /// + protected void BasicRepositoryConfigure(params IAppender[] appenders) + { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { foreach (IAppender appender in appenders) { - Root.AddAppender(appender); + this.Root.AddAppender(appender); } } - Configured = true; - - ConfigurationMessages = configurationMessages; - - // Notify listeners - OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); - } - - #endregion Implementation of IBasicRepositoryConfigurator - - #region Implementation of IXmlRepositoryConfigurator - - /// - /// Initialize the log4net system using the specified config - /// - /// the element containing the root of the config - void IXmlRepositoryConfigurator.Configure(System.Xml.XmlElement element) - { - XmlRepositoryConfigure(element); - } - - /// - /// Initialize the log4net system using the specified config - /// - /// the element containing the root of the config - /// - /// - /// This method provides the same functionality as the - /// method implemented - /// on this object, but it is protected and therefore can be called by subclasses. - /// - /// - protected void XmlRepositoryConfigure(System.Xml.XmlElement element) - { + this.Configured = true; + + this.ConfigurationMessages = configurationMessages; + + // Notify listeners + this.OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); + } + + /// + /// Initialize the log4net system using the specified config. + /// + /// the element containing the root of the config. + void IXmlRepositoryConfigurator.Configure(System.Xml.XmlElement element) + { + this.XmlRepositoryConfigure(element); + } + + /// + /// Initialize the log4net system using the specified config. + /// + /// the element containing the root of the config. + /// + /// + /// This method provides the same functionality as the + /// method implemented + /// on this object, but it is protected and therefore can be called by subclasses. + /// + /// + protected void XmlRepositoryConfigure(System.Xml.XmlElement element) + { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - XmlHierarchyConfigurator config = new XmlHierarchyConfigurator(this); + { + XmlHierarchyConfigurator config = new XmlHierarchyConfigurator(this); config.Configure(element); - } - - Configured = true; - - ConfigurationMessages = configurationMessages; - - // Notify listeners - OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); - } - - #endregion Implementation of IXmlRepositoryConfigurator - - #region Public Instance Methods - - /// - /// Test if this hierarchy is disabled for the specified . - /// - /// The level to check against. - /// - /// true if the repository is disabled for the level argument, false otherwise. - /// - /// - /// - /// If this hierarchy has not been configured then this method will - /// always return true. - /// - /// - /// This method will return true if this repository is - /// disabled for level object passed as parameter and - /// false otherwise. - /// - /// - /// See also the property. - /// - /// - public bool IsDisabled(Level level) - { - // Cast level to object for performance - if ((object)level == null) - { - throw new ArgumentNullException("level"); - } - - if (Configured) - { - return Threshold > level; - } - else - { - // If not configured the hierarchy is effectively disabled - return true; - } - } - - /// - /// Clear all logger definitions from the internal hashtable - /// - /// - /// - /// This call will clear all logger definitions from the internal - /// hashtable. Invoking this method will irrevocably mess up the - /// logger hierarchy. - /// - /// - /// You should really know what you are doing before - /// invoking this method. - /// - /// - public void Clear() - { - lock(m_ht) - { - m_ht.Clear(); - } - } - - /// - /// Return a new logger instance named as the first parameter using - /// . - /// - /// The name of the logger to retrieve - /// The factory that will make the new logger instance - /// The logger object with the name specified - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated by the - /// parameter and linked with its existing - /// ancestors as well as children. - /// - /// - public Logger GetLogger(string name, ILoggerFactory factory) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - if (factory == null) - { - throw new ArgumentNullException("factory"); - } - - LoggerKey key = new LoggerKey(name); - - // Synchronize to prevent write conflicts. Read conflicts (in - // GetEffectiveLevel() method) are possible only if variable - // assignments are non-atomic. - - lock(m_ht) - { - Logger logger = null; - - Object node = m_ht[key]; - if (node == null) - { - logger = factory.CreateLogger(this, name); - logger.Hierarchy = this; - m_ht[key] = logger; - UpdateParents(logger); - OnLoggerCreationEvent(logger); - return logger; - } - - Logger nodeLogger = node as Logger; - if (nodeLogger != null) - { - return nodeLogger; - } - - ProvisionNode nodeProvisionNode = node as ProvisionNode; - if (nodeProvisionNode != null) - { - logger = factory.CreateLogger(this, name); - logger.Hierarchy = this; - m_ht[key] = logger; - UpdateChildren(nodeProvisionNode, logger); - UpdateParents(logger); - OnLoggerCreationEvent(logger); - return logger; - } - - // It should be impossible to arrive here but let's keep the compiler happy. - return null; - } - } - - #endregion Public Instance Methods - - #region Protected Instance Methods - - /// - /// Sends a logger creation event to all registered listeners - /// - /// The newly created logger - /// - /// Raises the logger creation event. - /// - protected virtual void OnLoggerCreationEvent(Logger logger) - { - LoggerCreationEventHandler handler = m_loggerCreatedEvent; - if (handler != null) - { - handler(this, new LoggerCreationEventArgs(logger)); - } - } - - #endregion Protected Instance Methods - - #region Private Instance Methods - - /// - /// Updates all the parents of the specified logger - /// - /// The logger to update the parents for - /// - /// - /// This method loops through all the potential parents of - /// . There 3 possible cases: - /// - /// - /// - /// No entry for the potential parent of exists - /// - /// We create a ProvisionNode for this potential - /// parent and insert in that provision node. - /// - /// - /// - /// The entry is of type Logger for the potential parent. - /// - /// The entry is 's nearest existing parent. We - /// update 's parent field with this entry. We also break from - /// he loop because updating our parent's parent is our parent's - /// responsibility. - /// - /// - /// - /// The entry is of type ProvisionNode for this potential parent. - /// - /// We add to the list of children for this - /// potential parent. - /// - /// - /// - /// - private void UpdateParents(Logger log) - { - string name = log.Name; - int length = name.Length; - bool parentFound = false; - - // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" - for(int i = name.LastIndexOf('.', length-1); i >= 0; i = name.LastIndexOf('.', i-1)) - { - string substr = name.Substring(0, i); - - LoggerKey key = new LoggerKey(substr); // simple constructor - Object node = m_ht[key]; - // Create a provision node for a future parent. - if (node == null) - { - ProvisionNode pn = new ProvisionNode(log); - m_ht[key] = pn; - } - else - { - Logger nodeLogger = node as Logger; - if (nodeLogger != null) - { - parentFound = true; - log.Parent = nodeLogger; - break; // no need to update the ancestors of the closest ancestor - } - else - { - ProvisionNode nodeProvisionNode = node as ProvisionNode; - if (nodeProvisionNode != null) - { - nodeProvisionNode.Add(log); - } - else - { - LogLog.Error(declaringType, "Unexpected object type ["+node.GetType()+"] in ht.", new LogException()); - } - } - } - if (i == 0) { - // logger name starts with a dot - // and we've hit the start - break; - } - } - - // If we could not find any existing parents, then link with root. - if (!parentFound) - { - log.Parent = this.Root; - } - } - - /// - /// Replace a with a in the hierarchy. - /// - /// - /// - /// - /// - /// We update the links for all the children that placed themselves - /// in the provision node 'pn'. The second argument 'log' is a - /// reference for the newly created Logger, parent of all the - /// children in 'pn'. - /// - /// - /// We loop on all the children 'c' in 'pn'. - /// - /// - /// If the child 'c' has been already linked to a child of - /// 'log' then there is no need to update 'c'. - /// - /// - /// Otherwise, we set log's parent field to c's parent and set - /// c's parent field to log. - /// - /// - private static void UpdateChildren(ProvisionNode pn, Logger log) - { - for(int i = 0; i < pn.Count; i++) - { - Logger childLogger = (Logger)pn[i]; - - // Unless this child already points to a correct (lower) parent, - // make log.Parent point to childLogger.Parent and childLogger.Parent to log. - if (!childLogger.Parent.Name.StartsWith(log.Name)) - { - log.Parent = childLogger.Parent; - childLogger.Parent = log; - } - } - } - - /// - /// Define or redefine a Level using the values in the argument - /// - /// the level values - /// - /// - /// Define or redefine a Level using the values in the argument - /// - /// - /// Supports setting levels via the configuration file. - /// - /// - internal void AddLevel(LevelEntry levelEntry) - { - if (levelEntry == null) throw new ArgumentNullException("levelEntry"); - if (levelEntry.Name == null) throw new ArgumentNullException("levelEntry.Name"); - - // Lookup replacement value - if (levelEntry.Value == -1) - { - Level previousLevel = LevelMap[levelEntry.Name]; - if (previousLevel == null) - { - throw new InvalidOperationException("Cannot redefine level ["+levelEntry.Name+"] because it is not defined in the LevelMap. To define the level supply the level value."); - } - - levelEntry.Value = previousLevel.Value; - } - - LevelMap.Add(levelEntry.Name, levelEntry.Value, levelEntry.DisplayName); - } - - /// - /// A class to hold the value, name and display name for a level - /// - /// - /// - /// A class to hold the value, name and display name for a level - /// - /// - internal class LevelEntry - { - private int m_levelValue = -1; - private string m_levelName = null; - private string m_levelDisplayName = null; - - /// - /// Value of the level - /// - /// - /// - /// If the value is not set (defaults to -1) the value will be looked - /// up for the current level with the same name. - /// - /// - public int Value - { - get { return m_levelValue; } - set { m_levelValue = value; } - } - - /// - /// Name of the level - /// - /// - /// The name of the level - /// - /// - /// - /// The name of the level. - /// - /// - public string Name - { - get { return m_levelName; } - set { m_levelName = value; } - } - - /// - /// Display name for the level - /// - /// - /// The display name of the level - /// - /// - /// - /// The display name of the level. - /// - /// - public string DisplayName - { - get { return m_levelDisplayName; } - set { m_levelDisplayName = value; } - } - - /// - /// Override Object.ToString to return sensible debug info - /// - /// string info about this object - public override string ToString() - { - return "LevelEntry(Value="+m_levelValue+", Name="+m_levelName+", DisplayName="+m_levelDisplayName+")"; - } - } - - /// - /// Set a Property using the values in the argument - /// - /// the property value - /// - /// - /// Set a Property using the values in the argument. - /// - /// - /// Supports setting property values via the configuration file. - /// - /// - internal void AddProperty(PropertyEntry propertyEntry) - { - if (propertyEntry == null) throw new ArgumentNullException("propertyEntry"); - if (propertyEntry.Key == null) throw new ArgumentNullException("propertyEntry.Key"); - - Properties[propertyEntry.Key] = propertyEntry.Value; - } - - #endregion Private Instance Methods - - #region Private Instance Fields - - private ILoggerFactory m_defaultFactory; - - private System.Collections.Hashtable m_ht; - private Logger m_root; - - private bool m_emittedNoAppenderWarning = false; - - private event LoggerCreationEventHandler m_loggerCreatedEvent; - - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the Hierarchy class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(Hierarchy); - - #endregion Private Static Fields - } + } + + this.Configured = true; + + this.ConfigurationMessages = configurationMessages; + + // Notify listeners + this.OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); + } + + /// + /// Test if this hierarchy is disabled for the specified . + /// + /// The level to check against. + /// + /// true if the repository is disabled for the level argument, false otherwise. + /// + /// + /// + /// If this hierarchy has not been configured then this method will + /// always return true. + /// + /// + /// This method will return true if this repository is + /// disabled for level object passed as parameter and + /// false otherwise. + /// + /// + /// See also the property. + /// + /// + public bool IsDisabled(Level level) + { + // Cast level to object for performance + if ((object)level == null) + { + throw new ArgumentNullException("level"); + } + + if (this.Configured) + { + return this.Threshold > level; + } + else + { + // If not configured the hierarchy is effectively disabled + return true; + } + } + + /// + /// Clear all logger definitions from the internal hashtable. + /// + /// + /// + /// This call will clear all logger definitions from the internal + /// hashtable. Invoking this method will irrevocably mess up the + /// logger hierarchy. + /// + /// + /// You should really know what you are doing before + /// invoking this method. + /// + /// + public void Clear() + { + lock (this.m_ht) + { + this.m_ht.Clear(); + } + } + + /// + /// Return a new logger instance named as the first parameter using + /// . + /// + /// The name of the logger to retrieve. + /// The factory that will make the new logger instance. + /// The logger object with the name specified. + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated by the + /// parameter and linked with its existing + /// ancestors as well as children. + /// + /// + public Logger GetLogger(string name, ILoggerFactory factory) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + if (factory == null) + { + throw new ArgumentNullException("factory"); + } + + LoggerKey key = new LoggerKey(name); + + // Synchronize to prevent write conflicts. Read conflicts (in + // GetEffectiveLevel() method) are possible only if variable + // assignments are non-atomic. + lock (this.m_ht) + { + Logger logger = null; + + object node = this.m_ht[key]; + if (node == null) + { + logger = factory.CreateLogger(this, name); + logger.Hierarchy = this; + this.m_ht[key] = logger; + this.UpdateParents(logger); + this.OnLoggerCreationEvent(logger); + return logger; + } + + Logger nodeLogger = node as Logger; + if (nodeLogger != null) + { + return nodeLogger; + } + + ProvisionNode nodeProvisionNode = node as ProvisionNode; + if (nodeProvisionNode != null) + { + logger = factory.CreateLogger(this, name); + logger.Hierarchy = this; + this.m_ht[key] = logger; + UpdateChildren(nodeProvisionNode, logger); + this.UpdateParents(logger); + this.OnLoggerCreationEvent(logger); + return logger; + } + + // It should be impossible to arrive here but let's keep the compiler happy. + return null; + } + } + + /// + /// Sends a logger creation event to all registered listeners. + /// + /// The newly created logger. + /// + /// Raises the logger creation event. + /// + protected virtual void OnLoggerCreationEvent(Logger logger) + { + LoggerCreationEventHandler handler = this.m_loggerCreatedEvent; + if (handler != null) + { + handler(this, new LoggerCreationEventArgs(logger)); + } + } + + /// + /// Updates all the parents of the specified logger. + /// + /// The logger to update the parents for. + /// + /// + /// This method loops through all the potential parents of + /// . There 3 possible cases: + /// + /// + /// + /// No entry for the potential parent of exists + /// + /// We create a ProvisionNode for this potential + /// parent and insert in that provision node. + /// + /// + /// + /// The entry is of type Logger for the potential parent. + /// + /// The entry is 's nearest existing parent. We + /// update 's parent field with this entry. We also break from + /// he loop because updating our parent's parent is our parent's + /// responsibility. + /// + /// + /// + /// The entry is of type ProvisionNode for this potential parent. + /// + /// We add to the list of children for this + /// potential parent. + /// + /// + /// + /// + private void UpdateParents(Logger log) + { + string name = log.Name; + int length = name.Length; + bool parentFound = false; + + // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" + for (int i = name.LastIndexOf('.', length - 1); i >= 0; i = name.LastIndexOf('.', i - 1)) + { + string substr = name.Substring(0, i); + + LoggerKey key = new LoggerKey(substr); // simple constructor + object node = this.m_ht[key]; + + // Create a provision node for a future parent. + if (node == null) + { + ProvisionNode pn = new ProvisionNode(log); + this.m_ht[key] = pn; + } + else + { + Logger nodeLogger = node as Logger; + if (nodeLogger != null) + { + parentFound = true; + log.Parent = nodeLogger; + break; // no need to update the ancestors of the closest ancestor + } + else + { + ProvisionNode nodeProvisionNode = node as ProvisionNode; + if (nodeProvisionNode != null) + { + nodeProvisionNode.Add(log); + } + else + { + LogLog.Error(declaringType, "Unexpected object type [" + node.GetType() + "] in ht.", new LogException()); + } + } + } + + if (i == 0) + { + // logger name starts with a dot + // and we've hit the start + break; + } + } + + // If we could not find any existing parents, then link with root. + if (!parentFound) + { + log.Parent = this.Root; + } + } + + /// + /// Replace a with a in the hierarchy. + /// + /// + /// + /// + /// + /// We update the links for all the children that placed themselves + /// in the provision node 'pn'. The second argument 'log' is a + /// reference for the newly created Logger, parent of all the + /// children in 'pn'. + /// + /// + /// We loop on all the children 'c' in 'pn'. + /// + /// + /// If the child 'c' has been already linked to a child of + /// 'log' then there is no need to update 'c'. + /// + /// + /// Otherwise, we set log's parent field to c's parent and set + /// c's parent field to log. + /// + /// + private static void UpdateChildren(ProvisionNode pn, Logger log) + { + for (int i = 0; i < pn.Count; i++) + { + Logger childLogger = (Logger)pn[i]; + + // Unless this child already points to a correct (lower) parent, + // make log.Parent point to childLogger.Parent and childLogger.Parent to log. + if (!childLogger.Parent.Name.StartsWith(log.Name)) + { + log.Parent = childLogger.Parent; + childLogger.Parent = log; + } + } + } + + /// + /// Define or redefine a Level using the values in the argument. + /// + /// the level values. + /// + /// + /// Define or redefine a Level using the values in the argument. + /// + /// + /// Supports setting levels via the configuration file. + /// + /// + internal void AddLevel(LevelEntry levelEntry) + { + if (levelEntry == null) + { + throw new ArgumentNullException("levelEntry"); + } + + if (levelEntry.Name == null) + { + throw new ArgumentNullException("levelEntry.Name"); + } + + // Lookup replacement value + if (levelEntry.Value == -1) + { + Level previousLevel = this.LevelMap[levelEntry.Name]; + if (previousLevel == null) + { + throw new InvalidOperationException("Cannot redefine level [" + levelEntry.Name + "] because it is not defined in the LevelMap. To define the level supply the level value."); + } + + levelEntry.Value = previousLevel.Value; + } + + this.LevelMap.Add(levelEntry.Name, levelEntry.Value, levelEntry.DisplayName); + } + + /// + /// A class to hold the value, name and display name for a level. + /// + /// + /// + /// A class to hold the value, name and display name for a level. + /// + /// + internal class LevelEntry + { + private int m_levelValue = -1; + private string m_levelName = null; + private string m_levelDisplayName = null; + + /// + /// Gets or sets value of the level. + /// + /// + /// + /// If the value is not set (defaults to -1) the value will be looked + /// up for the current level with the same name. + /// + /// + public int Value + { + get { return this.m_levelValue; } + set { this.m_levelValue = value; } + } + + /// + /// Gets or sets name of the level. + /// + /// + /// The name of the level. + /// + /// + /// + /// The name of the level. + /// + /// + public string Name + { + get { return this.m_levelName; } + set { this.m_levelName = value; } + } + + /// + /// Gets or sets display name for the level. + /// + /// + /// The display name of the level. + /// + /// + /// + /// The display name of the level. + /// + /// + public string DisplayName + { + get { return this.m_levelDisplayName; } + set { this.m_levelDisplayName = value; } + } + + /// + /// Override Object.ToString to return sensible debug info. + /// + /// string info about this object. + public override string ToString() + { + return "LevelEntry(Value=" + this.m_levelValue + ", Name=" + this.m_levelName + ", DisplayName=" + this.m_levelDisplayName + ")"; + } + } + + /// + /// Set a Property using the values in the argument. + /// + /// the property value. + /// + /// + /// Set a Property using the values in the argument. + /// + /// + /// Supports setting property values via the configuration file. + /// + /// + internal void AddProperty(PropertyEntry propertyEntry) + { + if (propertyEntry == null) + { + throw new ArgumentNullException("propertyEntry"); + } + + if (propertyEntry.Key == null) + { + throw new ArgumentNullException("propertyEntry.Key"); + } + + this.Properties[propertyEntry.Key] = propertyEntry.Value; + } + + private ILoggerFactory m_defaultFactory; + + private System.Collections.Hashtable m_ht; + private Logger m_root; + + private bool m_emittedNoAppenderWarning = false; + + private event LoggerCreationEventHandler m_loggerCreatedEvent; + + /// + /// The fully qualified type of the Hierarchy class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(Hierarchy); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs index 1ea4e03313d..d23d2238d68 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs @@ -1,68 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// namespace log4net.Repository.Hierarchy { - /// - /// Interface abstracts creation of instances - /// - /// - /// - /// This interface is used by the to - /// create new objects. - /// - /// - /// The method is called - /// to create a named . - /// - /// - /// Implement this interface to create new subclasses of . - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface ILoggerFactory - { - /// - /// Create a new instance - /// - /// The that will own the . - /// The name of the . - /// The instance for the specified name. - /// - /// - /// Create a new instance with the - /// specified name. - /// - /// - /// Called by the to create - /// new named instances. - /// - /// - /// If the is null then the root logger - /// must be returned. - /// - /// - Logger CreateLogger(ILoggerRepository repository, string name); - } + /// + /// Interface abstracts creation of instances. + /// + /// + /// + /// This interface is used by the to + /// create new objects. + /// + /// + /// The method is called + /// to create a named . + /// + /// + /// Implement this interface to create new subclasses of . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface ILoggerFactory + { + /// + /// Create a new instance. + /// + /// The that will own the . + /// The name of the . + /// The instance for the specified name. + /// + /// + /// Create a new instance with the + /// specified name. + /// + /// + /// Called by the to create + /// new named instances. + /// + /// + /// If the is null then the root logger + /// must be returned. + /// + /// + Logger CreateLogger(ILoggerRepository repository, string name); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs index 1708a17fd7e..38975447611 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs @@ -1,793 +1,771 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Appender; -using log4net.Util; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository.Hierarchy { - /// - /// Implementation of used by - /// - /// - /// - /// Internal class used to provide implementation of - /// interface. Applications should use to get - /// logger instances. - /// - /// - /// This is one of the central classes in the log4net implementation. One of the - /// distinctive features of log4net are hierarchical loggers and their - /// evaluation. The organizes the - /// instances into a rooted tree hierarchy. - /// - /// - /// The class is abstract. Only concrete subclasses of - /// can be created. The - /// is used to create instances of this type for the . - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Aspi Havewala - /// Douglas de la Torre - public abstract class Logger : IAppenderAttachable, ILogger - { - #region Protected Instance Constructors - - /// - /// This constructor created a new instance and - /// sets its name. - /// - /// The name of the . - /// - /// - /// This constructor is protected and designed to be used by - /// a subclass that is not abstract. - /// - /// - /// Loggers are constructed by - /// objects. See for the default - /// logger creator. - /// - /// - protected Logger(string name) - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Appender; + using log4net.Core; + using log4net.Util; + + /// + /// Implementation of used by . + /// + /// + /// + /// Internal class used to provide implementation of + /// interface. Applications should use to get + /// logger instances. + /// + /// + /// This is one of the central classes in the log4net implementation. One of the + /// distinctive features of log4net are hierarchical loggers and their + /// evaluation. The organizes the + /// instances into a rooted tree hierarchy. + /// + /// + /// The class is abstract. Only concrete subclasses of + /// can be created. The + /// is used to create instances of this type for the . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Aspi Havewala. + /// Douglas de la Torre. + public abstract class Logger : IAppenderAttachable, ILogger + { + /// + /// Initializes a new instance of the class. + /// This constructor created a new instance and + /// sets its name. + /// + /// The name of the . + /// + /// + /// This constructor is protected and designed to be used by + /// a subclass that is not abstract. + /// + /// + /// Loggers are constructed by + /// objects. See for the default + /// logger creator. + /// + /// + protected Logger(string name) + { #if NETCF || NETSTANDARD1_3 // NETCF: String.Intern causes Native Exception m_name = name; #else - m_name = string.Intern(name); + this.m_name = string.Intern(name); #endif - } - - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the parent logger in the hierarchy. - /// - /// - /// The parent logger in the hierarchy. - /// - /// - /// - /// Part of the Composite pattern that makes the hierarchy. - /// The hierarchy is parent linked rather than child linked. - /// - /// - virtual public Logger Parent - { - get { return m_parent; } - set { m_parent = value; } - } - - /// - /// Gets or sets a value indicating if child loggers inherit their parent's appenders. - /// - /// - /// true if child loggers inherit their parent's appenders. - /// - /// - /// - /// Additivity is set to true by default, that is children inherit - /// the appenders of their ancestors by default. If this variable is - /// set to false then the appenders found in the - /// ancestors of this logger are not used. However, the children - /// of this logger will inherit its appenders, unless the children - /// have their additivity flag set to false too. See - /// the user manual for more details. - /// - /// - virtual public bool Additivity - { - get { return m_additive; } - set { m_additive = value; } - } - - /// - /// Gets the effective level for this logger. - /// - /// The nearest level in the logger hierarchy. - /// - /// - /// Starting from this logger, searches the logger hierarchy for a - /// non-null level and returns it. Otherwise, returns the level of the - /// root logger. - /// - /// The Logger class is designed so that this method executes as - /// quickly as possible. - /// - virtual public Level EffectiveLevel - { - get - { - for(Logger c = this; c != null; c = c.m_parent) - { - Level level = c.m_level; - - // Casting level to Object for performance, otherwise the overloaded operator is called - if ((object)level != null) - { - return level; - } - } - return null; // If reached will cause an NullPointerException. - } - } - - /// - /// Gets or sets the where this - /// Logger instance is attached to. - /// - /// The hierarchy that this logger belongs to. - /// - /// - /// This logger must be attached to a single . - /// - /// - virtual public Hierarchy Hierarchy - { - get { return m_hierarchy; } - set { m_hierarchy = value; } - } - - /// - /// Gets or sets the assigned , if any, for this Logger. - /// - /// - /// The of this logger. - /// - /// - /// - /// The assigned can be null. - /// - /// - virtual public Level Level - { - get { return m_level; } - set { m_level = value; } - } - - #endregion Public Instance Properties - - #region Implementation of IAppenderAttachable - - /// - /// Add to the list of appenders of this - /// Logger instance. - /// - /// An appender to add to this logger - /// - /// - /// Add to the list of appenders of this - /// Logger instance. - /// - /// - /// If is already in the list of - /// appenders, then it won't be added again. - /// - /// - virtual public void AddAppender(IAppender newAppender) - { - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } + } + + /// + /// Gets or sets the parent logger in the hierarchy. + /// + /// + /// The parent logger in the hierarchy. + /// + /// + /// + /// Part of the Composite pattern that makes the hierarchy. + /// The hierarchy is parent linked rather than child linked. + /// + /// + public virtual Logger Parent + { + get { return this.m_parent; } + set { this.m_parent = value; } + } - m_appenderLock.AcquireWriterLock(); - try - { - if (m_appenderAttachedImpl == null) - { - m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); - } - m_appenderAttachedImpl.AddAppender(newAppender); - } - finally - { - m_appenderLock.ReleaseWriterLock(); - } - } + /// + /// Gets or sets a value indicating whether gets or sets a value indicating if child loggers inherit their parent's appenders. + /// + /// + /// true if child loggers inherit their parent's appenders. + /// + /// + /// + /// Additivity is set to true by default, that is children inherit + /// the appenders of their ancestors by default. If this variable is + /// set to false then the appenders found in the + /// ancestors of this logger are not used. However, the children + /// of this logger will inherit its appenders, unless the children + /// have their additivity flag set to false too. See + /// the user manual for more details. + /// + /// + public virtual bool Additivity + { + get { return this.m_additive; } + set { this.m_additive = value; } + } - /// - /// Get the appenders contained in this logger as an - /// . - /// - /// A collection of the appenders in this logger - /// - /// - /// Get the appenders contained in this logger as an - /// . If no appenders - /// can be found, then a is returned. - /// - /// - virtual public AppenderCollection Appenders - { - get - { - m_appenderLock.AcquireReaderLock(); - try - { - if (m_appenderAttachedImpl == null) - { - return AppenderCollection.EmptyCollection; - } - else - { - return m_appenderAttachedImpl.Appenders; - } - } - finally - { - m_appenderLock.ReleaseReaderLock(); - } - } - } + /// + /// Gets the effective level for this logger. + /// + /// The nearest level in the logger hierarchy. + /// + /// + /// Starting from this logger, searches the logger hierarchy for a + /// non-null level and returns it. Otherwise, returns the level of the + /// root logger. + /// + /// The Logger class is designed so that this method executes as + /// quickly as possible. + /// + public virtual Level EffectiveLevel + { + get + { + for (Logger c = this; c != null; c = c.m_parent) + { + Level level = c.m_level; + + // Casting level to Object for performance, otherwise the overloaded operator is called + if ((object)level != null) + { + return level; + } + } + + return null; // If reached will cause an NullPointerException. + } + } - /// - /// Look for the appender named as name - /// - /// The name of the appender to lookup - /// The appender with the name specified, or null. - /// - /// - /// Returns the named appender, or null if the appender is not found. - /// - /// - virtual public IAppender GetAppender(string name) - { - m_appenderLock.AcquireReaderLock(); - try - { - if (m_appenderAttachedImpl == null || name == null) - { - return null; - } + /// + /// Gets or sets the where this + /// Logger instance is attached to. + /// + /// The hierarchy that this logger belongs to. + /// + /// + /// This logger must be attached to a single . + /// + /// + public virtual Hierarchy Hierarchy + { + get { return this.m_hierarchy; } + set { this.m_hierarchy = value; } + } - return m_appenderAttachedImpl.GetAppender(name); - } - finally - { - m_appenderLock.ReleaseReaderLock(); - } - } + /// + /// Gets or sets the assigned , if any, for this Logger. + /// + /// + /// The of this logger. + /// + /// + /// + /// The assigned can be null. + /// + /// + public virtual Level Level + { + get { return this.m_level; } + set { this.m_level = value; } + } + + /// + /// Add to the list of appenders of this + /// Logger instance. + /// + /// An appender to add to this logger. + /// + /// + /// Add to the list of appenders of this + /// Logger instance. + /// + /// + /// If is already in the list of + /// appenders, then it won't be added again. + /// + /// + public virtual void AddAppender(IAppender newAppender) + { + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } + + this.m_appenderLock.AcquireWriterLock(); + try + { + if (this.m_appenderAttachedImpl == null) + { + this.m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); + } + + this.m_appenderAttachedImpl.AddAppender(newAppender); + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + } - /// - /// Remove all previously added appenders from this Logger instance. - /// - /// - /// - /// Remove all previously added appenders from this Logger instance. - /// - /// - /// This is useful when re-reading configuration information. - /// - /// - virtual public void RemoveAllAppenders() - { - m_appenderLock.AcquireWriterLock(); - try - { - if (m_appenderAttachedImpl != null) - { - m_appenderAttachedImpl.RemoveAllAppenders(); - m_appenderAttachedImpl = null; - } - } - finally - { - m_appenderLock.ReleaseWriterLock(); - } - } + /// + /// Gets get the appenders contained in this logger as an + /// . + /// + /// A collection of the appenders in this logger. + /// + /// + /// Get the appenders contained in this logger as an + /// . If no appenders + /// can be found, then a is returned. + /// + /// + public virtual AppenderCollection Appenders + { + get + { + this.m_appenderLock.AcquireReaderLock(); + try + { + if (this.m_appenderAttachedImpl == null) + { + return AppenderCollection.EmptyCollection; + } + else + { + return this.m_appenderAttachedImpl.Appenders; + } + } + finally + { + this.m_appenderLock.ReleaseReaderLock(); + } + } + } - /// - /// Remove the appender passed as parameter form the list of appenders. - /// - /// The appender to remove - /// The appender removed from the list - /// - /// - /// Remove the appender passed as parameter form the list of appenders. - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - virtual public IAppender RemoveAppender(IAppender appender) - { - m_appenderLock.AcquireWriterLock(); - try - { - if (appender != null && m_appenderAttachedImpl != null) - { - return m_appenderAttachedImpl.RemoveAppender(appender); - } - } - finally - { - m_appenderLock.ReleaseWriterLock(); - } - return null; - } + /// + /// Look for the appender named as name. + /// + /// The name of the appender to lookup. + /// The appender with the name specified, or null. + /// + /// + /// Returns the named appender, or null if the appender is not found. + /// + /// + public virtual IAppender GetAppender(string name) + { + this.m_appenderLock.AcquireReaderLock(); + try + { + if (this.m_appenderAttachedImpl == null || name == null) + { + return null; + } + + return this.m_appenderAttachedImpl.GetAppender(name); + } + finally + { + this.m_appenderLock.ReleaseReaderLock(); + } + } - /// - /// Remove the appender passed as parameter form the list of appenders. - /// - /// The name of the appender to remove - /// The appender removed from the list - /// - /// - /// Remove the named appender passed as parameter form the list of appenders. - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - virtual public IAppender RemoveAppender(string name) - { - m_appenderLock.AcquireWriterLock(); - try - { - if (name != null && m_appenderAttachedImpl != null) - { - return m_appenderAttachedImpl.RemoveAppender(name); - } - } - finally - { - m_appenderLock.ReleaseWriterLock(); - } - return null; - } - - #endregion + /// + /// Remove all previously added appenders from this Logger instance. + /// + /// + /// + /// Remove all previously added appenders from this Logger instance. + /// + /// + /// This is useful when re-reading configuration information. + /// + /// + public virtual void RemoveAllAppenders() + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + this.m_appenderAttachedImpl = null; + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + } - #region Implementation of ILogger + /// + /// Remove the appender passed as parameter form the list of appenders. + /// + /// The appender to remove. + /// The appender removed from the list. + /// + /// + /// Remove the appender passed as parameter form the list of appenders. + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public virtual IAppender RemoveAppender(IAppender appender) + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (appender != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(appender); + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + + return null; + } - /// - /// Gets the logger name. - /// - /// - /// The name of the logger. - /// - /// - /// - /// The name of this logger - /// - /// - virtual public string Name - { - get { return m_name; } - } + /// + /// Remove the appender passed as parameter form the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list. + /// + /// + /// Remove the named appender passed as parameter form the list of appenders. + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public virtual IAppender RemoveAppender(string name) + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (name != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(name); + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + + return null; + } + + /// + /// Gets the logger name. + /// + /// + /// The name of the logger. + /// + /// + /// + /// The name of this logger. + /// + /// + public virtual string Name + { + get { return this.m_name; } + } - /// - /// This generic form is intended to be used by wrappers. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The level of the message to be logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Generate a logging event for the specified using - /// the and . - /// - /// - /// This method must not throw any exception to the caller. - /// - /// - virtual public void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) - { - try - { - if (IsEnabledFor(level)) - { - ForcedLog((callerStackBoundaryDeclaringType != null) ? callerStackBoundaryDeclaringType : declaringType, level, message, exception); - } - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + /// + /// This generic form is intended to be used by wrappers. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The level of the message to be logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Generate a logging event for the specified using + /// the and . + /// + /// + /// This method must not throw any exception to the caller. + /// + /// + public virtual void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) + { + try + { + if (this.IsEnabledFor(level)) + { + this.ForcedLog((callerStackBoundaryDeclaringType != null) ? callerStackBoundaryDeclaringType : declaringType, level, message, exception); + } + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { log4net.Util.LogLog.Error(declaringType, "Exception while logging"); } #endif - } + } - /// - /// This is the most generic printing method that is intended to be used - /// by wrappers. - /// - /// The event being logged. - /// - /// - /// Logs the specified logging event through this logger. - /// - /// - /// This method must not throw any exception to the caller. - /// - /// - virtual public void Log(LoggingEvent logEvent) - { - try - { - if (logEvent != null) - { - if (IsEnabledFor(logEvent.Level)) - { - ForcedLog(logEvent); - } - } - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + /// + /// This is the most generic printing method that is intended to be used + /// by wrappers. + /// + /// The event being logged. + /// + /// + /// Logs the specified logging event through this logger. + /// + /// + /// This method must not throw any exception to the caller. + /// + /// + public virtual void Log(LoggingEvent logEvent) + { + try + { + if (logEvent != null) + { + if (this.IsEnabledFor(logEvent.Level)) + { + this.ForcedLog(logEvent); + } + } + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { log4net.Util.LogLog.Error(declaringType, "Exception while logging"); } #endif - } + } - /// - /// Checks if this logger is enabled for a given passed as parameter. - /// - /// The level to check. - /// - /// true if this logger is enabled for level, otherwise false. - /// - /// - /// - /// Test if this logger is going to log events of the specified . - /// - /// - /// This method must not throw any exception to the caller. - /// - /// - virtual public bool IsEnabledFor(Level level) - { - try - { - if (level != null) - { - if (m_hierarchy.IsDisabled(level)) - { - return false; - } - return level >= this.EffectiveLevel; - } - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + /// + /// Checks if this logger is enabled for a given passed as parameter. + /// + /// The level to check. + /// + /// true if this logger is enabled for level, otherwise false. + /// + /// + /// + /// Test if this logger is going to log events of the specified . + /// + /// + /// This method must not throw any exception to the caller. + /// + /// + public virtual bool IsEnabledFor(Level level) + { + try + { + if (level != null) + { + if (this.m_hierarchy.IsDisabled(level)) + { + return false; + } + + return level >= this.EffectiveLevel; + } + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { log4net.Util.LogLog.Error(declaringType, "Exception while logging"); } #endif - return false; - } + return false; + } - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - /// The that this logger belongs to. - /// - /// - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - public ILoggerRepository Repository - { - get { return m_hierarchy; } - } - - #endregion Implementation of ILogger - - /// - /// Deliver the to the attached appenders. - /// - /// The event to log. - /// - /// - /// Call the appenders in the hierarchy starting at - /// this. If no appenders could be found, emit a - /// warning. - /// - /// - /// This method calls all the appenders inherited from the - /// hierarchy circumventing any evaluation of whether to log or not - /// to log the particular log request. - /// - /// - virtual protected void CallAppenders(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - int writes = 0; - - for(Logger c=this; c != null; c=c.m_parent) - { - if (c.m_appenderAttachedImpl != null) - { - // Protected against simultaneous call to addAppender, removeAppender,... - c.m_appenderLock.AcquireReaderLock(); - try - { - if (c.m_appenderAttachedImpl != null) - { - writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); - } - } - finally - { - c.m_appenderLock.ReleaseReaderLock(); - } - } - - if (!c.m_additive) - { - break; - } - } - - // No appenders in hierarchy, warn user only once. - // - // Note that by including the AppDomain values for the currently running - // thread, it becomes much easier to see which application the warning - // is from, which is especially helpful in a multi-AppDomain environment - // (like IIS with multiple VDIRS). Without this, it can be difficult - // or impossible to determine which .config file is missing appender - // definitions. - // - if (!m_hierarchy.EmittedNoAppenderWarning && writes == 0) - { - m_hierarchy.EmittedNoAppenderWarning = true; - LogLog.Debug(declaringType, "No appenders could be found for logger [" + Name + "] repository [" + Repository.Name + "]"); - LogLog.Debug(declaringType, "Please initialize the log4net system properly."); - try - { - LogLog.Debug(declaringType, " Current AppDomain context information: "); - LogLog.Debug(declaringType, " BaseDirectory : " + SystemInfo.ApplicationBaseDirectory); + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + /// The that this logger belongs to. + /// + /// + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + public ILoggerRepository Repository + { + get { return this.m_hierarchy; } + } + + /// + /// Deliver the to the attached appenders. + /// + /// The event to log. + /// + /// + /// Call the appenders in the hierarchy starting at + /// this. If no appenders could be found, emit a + /// warning. + /// + /// + /// This method calls all the appenders inherited from the + /// hierarchy circumventing any evaluation of whether to log or not + /// to log the particular log request. + /// + /// + protected virtual void CallAppenders(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + int writes = 0; + + for (Logger c = this; c != null; c = c.m_parent) + { + if (c.m_appenderAttachedImpl != null) + { + // Protected against simultaneous call to addAppender, removeAppender,... + c.m_appenderLock.AcquireReaderLock(); + try + { + if (c.m_appenderAttachedImpl != null) + { + writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); + } + } + finally + { + c.m_appenderLock.ReleaseReaderLock(); + } + } + + if (!c.m_additive) + { + break; + } + } + + // No appenders in hierarchy, warn user only once. + // + // Note that by including the AppDomain values for the currently running + // thread, it becomes much easier to see which application the warning + // is from, which is especially helpful in a multi-AppDomain environment + // (like IIS with multiple VDIRS). Without this, it can be difficult + // or impossible to determine which .config file is missing appender + // definitions. + if (!this.m_hierarchy.EmittedNoAppenderWarning && writes == 0) + { + this.m_hierarchy.EmittedNoAppenderWarning = true; + LogLog.Debug(declaringType, "No appenders could be found for logger [" + this.Name + "] repository [" + this.Repository.Name + "]"); + LogLog.Debug(declaringType, "Please initialize the log4net system properly."); + try + { + LogLog.Debug(declaringType, " Current AppDomain context information: "); + LogLog.Debug(declaringType, " BaseDirectory : " + SystemInfo.ApplicationBaseDirectory); #if !(NETCF || NETSTANDARD1_3) - LogLog.Debug(declaringType, " FriendlyName : " + AppDomain.CurrentDomain.FriendlyName); - LogLog.Debug(declaringType, " DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory); + LogLog.Debug(declaringType, " FriendlyName : " + AppDomain.CurrentDomain.FriendlyName); + LogLog.Debug(declaringType, " DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory); #endif - } - catch(System.Security.SecurityException) - { - // Insufficient permissions to display info from the AppDomain - } - } - } - - /// - /// Closes all attached appenders implementing the interface. - /// - /// - /// - /// Used to ensure that the appenders are correctly shutdown. - /// - /// - virtual public void CloseNestedAppenders() - { - m_appenderLock.AcquireWriterLock(); - try - { - if (m_appenderAttachedImpl != null) - { - AppenderCollection appenders = m_appenderAttachedImpl.Appenders; - foreach(IAppender appender in appenders) - { - if (appender is IAppenderAttachable) - { - appender.Close(); - } - } - } - } - finally - { - m_appenderLock.ReleaseWriterLock(); - } - } + } + catch (System.Security.SecurityException) + { + // Insufficient permissions to display info from the AppDomain + } + } + } - /// - /// This is the most generic printing method. This generic form is intended to be used by wrappers - /// - /// The level of the message to be logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Generate a logging event for the specified using - /// the . - /// - /// - virtual public void Log(Level level, object message, Exception exception) - { - if (IsEnabledFor(level)) - { - ForcedLog(declaringType, level, message, exception); - } - } - - /// - /// Creates a new logging event and logs the event without further checks. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The level of the message to be logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Generates a logging event and delivers it to the attached - /// appenders. - /// - /// - virtual protected void ForcedLog(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) - { - CallAppenders(new LoggingEvent(callerStackBoundaryDeclaringType, this.Hierarchy, this.Name, level, message, exception)); - } - - /// - /// Creates a new logging event and logs the event without further checks. - /// - /// The event being logged. - /// - /// - /// Delivers the logging event to the attached appenders. - /// - /// - virtual protected void ForcedLog(LoggingEvent logEvent) - { - // The logging event may not have been created by this logger - // the Repository may not be correctly set on the event. This - // is required for the appenders to correctly lookup renderers etc... - logEvent.EnsureRepository(this.Hierarchy); + /// + /// Closes all attached appenders implementing the interface. + /// + /// + /// + /// Used to ensure that the appenders are correctly shutdown. + /// + /// + public virtual void CloseNestedAppenders() + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (this.m_appenderAttachedImpl != null) + { + AppenderCollection appenders = this.m_appenderAttachedImpl.Appenders; + foreach (IAppender appender in appenders) + { + if (appender is IAppenderAttachable) + { + appender.Close(); + } + } + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + } - CallAppenders(logEvent); - } + /// + /// This is the most generic printing method. This generic form is intended to be used by wrappers. + /// + /// The level of the message to be logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Generate a logging event for the specified using + /// the . + /// + /// + public virtual void Log(Level level, object message, Exception exception) + { + if (this.IsEnabledFor(level)) + { + this.ForcedLog(declaringType, level, message, exception); + } + } - #region Private Static Fields + /// + /// Creates a new logging event and logs the event without further checks. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The level of the message to be logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Generates a logging event and delivers it to the attached + /// appenders. + /// + /// + protected virtual void ForcedLog(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) + { + this.CallAppenders(new LoggingEvent(callerStackBoundaryDeclaringType, this.Hierarchy, this.Name, level, message, exception)); + } + /// + /// Creates a new logging event and logs the event without further checks. + /// + /// The event being logged. + /// + /// + /// Delivers the logging event to the attached appenders. + /// + /// + protected virtual void ForcedLog(LoggingEvent logEvent) + { + // The logging event may not have been created by this logger + // the Repository may not be correctly set on the event. This + // is required for the appenders to correctly lookup renderers etc... + logEvent.EnsureRepository(this.Hierarchy); + + this.CallAppenders(logEvent); + } + /// /// The fully qualified type of the Logger class. /// - private readonly static Type declaringType = typeof(Logger); - - #endregion Private Static Fields - - #region Private Instance Fields - - /// - /// The name of this logger. - /// - private readonly string m_name; + private static readonly Type declaringType = typeof(Logger); + + /// + /// The name of this logger. + /// + private readonly string m_name; - /// - /// The assigned level of this logger. - /// - /// - /// - /// The level variable need not be - /// assigned a value in which case it is inherited - /// form the hierarchy. - /// - /// - private Level m_level; + /// + /// The assigned level of this logger. + /// + /// + /// + /// The level variable need not be + /// assigned a value in which case it is inherited + /// form the hierarchy. + /// + /// + private Level m_level; - /// - /// The parent of this logger. - /// - /// - /// - /// The parent of this logger. - /// All loggers have at least one ancestor which is the root logger. - /// - /// - private Logger m_parent; + /// + /// The parent of this logger. + /// + /// + /// + /// The parent of this logger. + /// All loggers have at least one ancestor which is the root logger. + /// + /// + private Logger m_parent; - /// - /// Loggers need to know what Hierarchy they are in. - /// - /// - /// - /// Loggers need to know what Hierarchy they are in. - /// The hierarchy that this logger is a member of is stored - /// here. - /// - /// - private Hierarchy m_hierarchy; + /// + /// Loggers need to know what Hierarchy they are in. + /// + /// + /// + /// Loggers need to know what Hierarchy they are in. + /// The hierarchy that this logger is a member of is stored + /// here. + /// + /// + private Hierarchy m_hierarchy; - /// - /// Helper implementation of the interface - /// - private log4net.Util.AppenderAttachedImpl m_appenderAttachedImpl; + /// + /// Helper implementation of the interface. + /// + private log4net.Util.AppenderAttachedImpl m_appenderAttachedImpl; - /// - /// Flag indicating if child loggers inherit their parents appenders - /// - /// - /// - /// Additivity is set to true by default, that is children inherit - /// the appenders of their ancestors by default. If this variable is - /// set to false then the appenders found in the - /// ancestors of this logger are not used. However, the children - /// of this logger will inherit its appenders, unless the children - /// have their additivity flag set to false too. See - /// the user manual for more details. - /// - /// - private bool m_additive = true; + /// + /// Flag indicating if child loggers inherit their parents appenders. + /// + /// + /// + /// Additivity is set to true by default, that is children inherit + /// the appenders of their ancestors by default. If this variable is + /// set to false then the appenders found in the + /// ancestors of this logger are not used. However, the children + /// of this logger will inherit its appenders, unless the children + /// have their additivity flag set to false too. See + /// the user manual for more details. + /// + /// + private bool m_additive = true; - /// - /// Lock to protect AppenderAttachedImpl variable m_appenderAttachedImpl - /// - private readonly ReaderWriterLock m_appenderLock = new ReaderWriterLock(); - - #endregion - } + /// + /// Lock to protect AppenderAttachedImpl variable m_appenderAttachedImpl. + /// + private readonly ReaderWriterLock m_appenderLock = new ReaderWriterLock(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs index 07a3024bf37..61362c47c7f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs @@ -1,142 +1,128 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository.Hierarchy { - /// - /// Used internally to accelerate hash table searches. - /// - /// - /// - /// Internal class used to improve performance of - /// string keyed hashtables. - /// - /// - /// The hashcode of the string is cached for reuse. - /// The string is stored as an interned value. - /// When comparing two objects for equality - /// the reference equality of the interned strings is compared. - /// - /// - /// Nicko Cadell - /// Gert Driesen - internal sealed class LoggerKey - { - #region Internal Instance Constructors - - /// - /// Construct key with string name - /// - /// - /// - /// Initializes a new instance of the class - /// with the specified name. - /// - /// - /// Stores the hashcode of the string and interns - /// the string key to optimize comparisons. - /// - /// - /// The Compact Framework 1.0 the - /// method does not work. On the Compact Framework - /// the string keys are not interned nor are they - /// compared by reference. - /// - /// - /// The name of the logger. - internal LoggerKey(string name) - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Used internally to accelerate hash table searches. + /// + /// + /// + /// Internal class used to improve performance of + /// string keyed hashtables. + /// + /// + /// The hashcode of the string is cached for reuse. + /// The string is stored as an interned value. + /// When comparing two objects for equality + /// the reference equality of the interned strings is compared. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + internal sealed class LoggerKey + { + /// + /// Initializes a new instance of the class. + /// Construct key with string name. + /// + /// + /// + /// Initializes a new instance of the class + /// with the specified name. + /// + /// + /// Stores the hashcode of the string and interns + /// the string key to optimize comparisons. + /// + /// + /// The Compact Framework 1.0 the + /// method does not work. On the Compact Framework + /// the string keys are not interned nor are they + /// compared by reference. + /// + /// + /// The name of the logger. + internal LoggerKey(string name) + { #if NETCF || NETSTANDARD1_3 // NETCF: String.Intern causes Native Exception m_name = name; #else - m_name = string.Intern(name); + this.m_name = string.Intern(name); #endif - m_hashCache = name.GetHashCode(); - } - - #endregion Internal Instance Constructors - - #region Override implementation of Object + this.m_hashCache = name.GetHashCode(); + } + + /// + /// Returns a hash code for the current instance. + /// + /// A hash code for the current instance. + /// + /// + /// Returns the cached hashcode. + /// + /// + public override int GetHashCode() + { + return this.m_hashCache; + } - /// - /// Returns a hash code for the current instance. - /// - /// A hash code for the current instance. - /// - /// - /// Returns the cached hashcode. - /// - /// - override public int GetHashCode() - { - return m_hashCache; - } + /// + /// Determines whether two instances + /// are equal. + /// + /// The to compare with the current . + /// + /// true if the specified is equal to the current ; otherwise, false. + /// + /// + /// + /// Compares the references of the interned strings. + /// + /// + public override bool Equals(object obj) + { + // Compare reference type of this against argument + if (((object)this) == obj) + { + return true; + } - /// - /// Determines whether two instances - /// are equal. - /// - /// The to compare with the current . - /// - /// true if the specified is equal to the current ; otherwise, false. - /// - /// - /// - /// Compares the references of the interned strings. - /// - /// - override public bool Equals(object obj) - { - // Compare reference type of this against argument - if (((object)this) == obj) - { - return true; - } - - LoggerKey objKey = obj as LoggerKey; - if (objKey != null) - { + LoggerKey objKey = obj as LoggerKey; + if (objKey != null) + { #if NETCF || NETSTANDARD1_3 return ( m_name == objKey.m_name ); #else - // Compare reference types rather than string's overloaded == - return ( ((object)m_name) == ((object)objKey.m_name) ); + // Compare reference types rather than string's overloaded == + return ((object)this.m_name) == ((object)objKey.m_name); #endif - } - return false; - } - - #endregion - - #region Private Instance Fields - - private readonly string m_name; - private readonly int m_hashCache; - - #endregion Private Instance Fields - } -} - + } + + return false; + } + + private readonly string m_name; + private readonly int m_hashCache; + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs index 035daa99638..a10e91afef3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs @@ -1,62 +1,61 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository.Hierarchy { - /// - /// Provision nodes are used where no logger instance has been specified - /// - /// - /// - /// instances are used in the - /// when there is no specified - /// for that node. - /// - /// - /// A provision node holds a list of child loggers on behalf of - /// a logger that does not exist. - /// - /// - /// Nicko Cadell - /// Gert Driesen - internal sealed class ProvisionNode : ArrayList - { - /// - /// Create a new provision node with child node - /// - /// A child logger to add to this node. - /// - /// - /// Initializes a new instance of the class - /// with the specified child logger. - /// - /// - internal ProvisionNode(Logger log) : base() - { - this.Add(log); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// Provision nodes are used where no logger instance has been specified. + /// + /// + /// + /// instances are used in the + /// when there is no specified + /// for that node. + /// + /// + /// A provision node holds a list of child loggers on behalf of + /// a logger that does not exist. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + internal sealed class ProvisionNode : ArrayList + { + /// + /// Initializes a new instance of the class. + /// Create a new provision node with child node. + /// + /// A child logger to add to this node. + /// + /// + /// Initializes a new instance of the class + /// with the specified child logger. + /// + /// + internal ProvisionNode(Logger log) + : base() + { + this.Add(log); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs index 6c147fd02ad..7d22ba3ba8f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs @@ -1,137 +1,125 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Util; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository.Hierarchy { - /// - /// The sits at the root of the logger hierarchy tree. - /// - /// - /// - /// The is a regular except - /// that it provides several guarantees. - /// - /// - /// First, it cannot be assigned a null - /// level. Second, since the root logger cannot have a parent, the - /// property always returns the value of the - /// level field without walking the hierarchy. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class RootLogger : Logger - { - #region Public Instance Constructors - - /// - /// Construct a - /// - /// The level to assign to the root logger. - /// - /// - /// Initializes a new instance of the class with - /// the specified logging level. - /// - /// - /// The root logger names itself as "root". However, the root - /// logger cannot be retrieved by name. - /// - /// - public RootLogger(Level level) : base("root") - { - this.Level = level; - } - - #endregion Public Instance Constructors - - #region Override implementation of Logger - - /// - /// Gets the assigned level value without walking the logger hierarchy. - /// - /// The assigned level value without walking the logger hierarchy. - /// - /// - /// Because the root logger cannot have a parent and its level - /// must not be null this property just returns the - /// value of . - /// - /// - override public Level EffectiveLevel - { - get - { - return base.Level; - } - } - - /// - /// Gets or sets the assigned for the root logger. - /// - /// - /// The of the root logger. - /// - /// - /// - /// Setting the level of the root logger to a null reference - /// may have catastrophic results. We prevent this here. - /// - /// - override public Level Level - { - get { return base.Level; } - set - { - if (value == null) - { - LogLog.Error(declaringType, "You have tried to set a null level to root.", new LogException()); - } - else - { - base.Level = value; - } - } - } - - #endregion Override implementation of Logger - - #region Private Static Fields - - /// - /// The fully qualified type of the RootLogger class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(RootLogger); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + using log4net.Util; + + /// + /// The sits at the root of the logger hierarchy tree. + /// + /// + /// + /// The is a regular except + /// that it provides several guarantees. + /// + /// + /// First, it cannot be assigned a null + /// level. Second, since the root logger cannot have a parent, the + /// property always returns the value of the + /// level field without walking the hierarchy. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class RootLogger : Logger + { + /// + /// Initializes a new instance of the class. + /// Construct a . + /// + /// The level to assign to the root logger. + /// + /// + /// Initializes a new instance of the class with + /// the specified logging level. + /// + /// + /// The root logger names itself as "root". However, the root + /// logger cannot be retrieved by name. + /// + /// + public RootLogger(Level level) + : base("root") + { + this.Level = level; + } + + /// + /// Gets the assigned level value without walking the logger hierarchy. + /// + /// The assigned level value without walking the logger hierarchy. + /// + /// + /// Because the root logger cannot have a parent and its level + /// must not be null this property just returns the + /// value of . + /// + /// + public override Level EffectiveLevel + { + get + { + return base.Level; + } + } - #endregion Private Static Fields - } + /// + /// Gets or sets the assigned for the root logger. + /// + /// + /// The of the root logger. + /// + /// + /// + /// Setting the level of the root logger to a null reference + /// may have catastrophic results. We prevent this here. + /// + /// + public override Level Level + { + get { return base.Level; } + + set + { + if (value == null) + { + LogLog.Error(declaringType, "You have tried to set a null level to root.", new LogException()); + } + else + { + base.Level = value; + } + } + } + + /// + /// The fully qualified type of the RootLogger class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(RootLogger); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs index b7932bff2a5..45456f8f4de 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs @@ -1,102 +1,94 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Globalization; -using System.Reflection; -using System.Xml; - -using log4net.Appender; -using log4net.Util; -using log4net.Core; -using log4net.ObjectRenderer; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository.Hierarchy { - /// - /// Initializes the log4net environment using an XML DOM. - /// - /// - /// - /// Configures a using an XML DOM. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class XmlHierarchyConfigurator - { - private enum ConfigUpdateMode - { - Merge, - Overwrite - } - - #region Public Instance Constructors - - /// - /// Construct the configurator for a hierarchy - /// - /// The hierarchy to build. - /// - /// - /// Initializes a new instance of the class - /// with the specified . - /// - /// - public XmlHierarchyConfigurator(Hierarchy hierarchy) - { - m_hierarchy = hierarchy; - m_appenderBag = new Hashtable(); - } - - #endregion Public Instance Constructors - - #region Public Instance Methods - - /// - /// Configure the hierarchy by parsing a DOM tree of XML elements. - /// - /// The root element to parse. - /// - /// - /// Configure the hierarchy by parsing a DOM tree of XML elements. - /// - /// - public void Configure(XmlElement element) - { - if (element == null || m_hierarchy == null) - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Globalization; + using System.Reflection; + using System.Xml; + + using log4net.Appender; + using log4net.Core; + using log4net.ObjectRenderer; + using log4net.Util; + + /// + /// Initializes the log4net environment using an XML DOM. + /// + /// + /// + /// Configures a using an XML DOM. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class XmlHierarchyConfigurator + { + private enum ConfigUpdateMode + { + Merge, + Overwrite, + } + + /// + /// Initializes a new instance of the class. + /// Construct the configurator for a hierarchy. + /// + /// The hierarchy to build. + /// + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + public XmlHierarchyConfigurator(Hierarchy hierarchy) + { + this.m_hierarchy = hierarchy; + this.m_appenderBag = new Hashtable(); + } + + /// + /// Configure the hierarchy by parsing a DOM tree of XML elements. + /// + /// The root element to parse. + /// + /// + /// Configure the hierarchy by parsing a DOM tree of XML elements. + /// + /// + public void Configure(XmlElement element) + { + if (element == null || this.m_hierarchy == null) + { return; - } + } - string rootElementName = element.LocalName; + string rootElementName = element.LocalName; - if (rootElementName != CONFIGURATION_TAG) - { - LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element."); + if (rootElementName != CONFIGURATION_TAG) + { + LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element."); return; - } + } if (!LogLog.EmitInternalMessages) { @@ -114,967 +106,966 @@ public void Configure(XmlElement element) } } - if (!LogLog.InternalDebugging) - { - // Look for a debug attribute to enable internal debug - string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR); - LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR+" attribute [" + debugAttribute + "]."); - - if (debugAttribute.Length>0 && debugAttribute != "null") - { - LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true); - } - else - { - LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); - } - - string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR); - if (confDebug.Length>0 && confDebug != "null") - { - LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated."); - LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead."); - LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true); - } - } - - // Default mode is merge - ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge; - - // Look for the config update attribute - string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR); - if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0) - { - // Parse the attribute - try - { - configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute); - } - catch - { - LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]"); - } - } - - // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0 - LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "]."); - - // Only reset configuration if overwrite flag specified - if (configUpdateMode == ConfigUpdateMode.Overwrite) - { - // Reset to original unset configuration - m_hierarchy.ResetConfiguration(); - LogLog.Debug(declaringType, "Configuration reset before reading config."); - } - - /* Building Appender objects, placing them in a local namespace - for future reference */ - - /* Process all the top level elements */ - - foreach (XmlNode currentNode in element.ChildNodes) - { - if (currentNode.NodeType == XmlNodeType.Element) - { - XmlElement currentElement = (XmlElement)currentNode; - - if (currentElement.LocalName == LOGGER_TAG) - { - ParseLogger(currentElement); - } - else if (currentElement.LocalName == CATEGORY_TAG) - { - // TODO: deprecated use of category - ParseLogger(currentElement); - } - else if (currentElement.LocalName == ROOT_TAG) - { - ParseRoot(currentElement); - } - else if (currentElement.LocalName == RENDERER_TAG) - { - ParseRenderer(currentElement); - } - else if (currentElement.LocalName == APPENDER_TAG) - { - // We ignore appenders in this pass. They will - // be found and loaded if they are referenced. - } - else - { - // Read the param tags and set properties on the hierarchy - SetParameter(currentElement, m_hierarchy); - } - } - } - - // Lastly set the hierarchy threshold - string thresholdStr = element.GetAttribute(THRESHOLD_ATTR); - LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]"); - if (thresholdStr.Length > 0 && thresholdStr != "null") - { - Level thresholdLevel = (Level) ConvertStringTo(typeof(Level), thresholdStr); - if (thresholdLevel != null) - { - m_hierarchy.Threshold = thresholdLevel; - } - else - { - LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)"); - } - } - - // Done reading config - } - - #endregion Public Instance Methods - - #region Protected Instance Methods - - /// - /// Parse appenders by IDREF. - /// - /// The appender ref element. - /// The instance of the appender that the ref refers to. - /// - /// - /// Parse an XML element that represents an appender and return - /// the appender. - /// - /// - protected IAppender FindAppenderByReference(XmlElement appenderRef) - { - string appenderName = appenderRef.GetAttribute(REF_ATTR); - - IAppender appender = (IAppender)m_appenderBag[appenderName]; - if (appender != null) - { - return appender; - } - else - { - // Find the element with that id - XmlElement element = null; - - if (appenderName != null && appenderName.Length > 0) - { - foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG)) - { - if (curAppenderElement.GetAttribute("name") == appenderName) - { - element = curAppenderElement; - break; - } - } - } - - if (element == null) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found."); - return null; - } - else - { - appender = ParseAppender(element); - if (appender != null) - { - m_appenderBag[appenderName] = appender; - } - return appender; - } - } - } - - /// - /// Parses an appender element. - /// - /// The appender element. - /// The appender instance or null when parsing failed. - /// - /// - /// Parse an XML element that represents an appender and return - /// the appender instance. - /// - /// - protected IAppender ParseAppender(XmlElement appenderElement) - { - string appenderName = appenderElement.GetAttribute(NAME_ATTR); - string typeName = appenderElement.GetAttribute(TYPE_ATTR); - - LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]"); - try - { + if (!LogLog.InternalDebugging) + { + // Look for a debug attribute to enable internal debug + string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR); + LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR + " attribute [" + debugAttribute + "]."); + + if (debugAttribute.Length > 0 && debugAttribute != "null") + { + LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true); + } + else + { + LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); + } + + string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR); + if (confDebug.Length > 0 && confDebug != "null") + { + LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated."); + LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead."); + LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true); + } + } + + // Default mode is merge + ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge; + + // Look for the config update attribute + string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR); + if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0) + { + // Parse the attribute + try + { + configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute); + } + catch + { + LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]"); + } + } + + // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0 + LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "]."); + + // Only reset configuration if overwrite flag specified + if (configUpdateMode == ConfigUpdateMode.Overwrite) + { + // Reset to original unset configuration + this.m_hierarchy.ResetConfiguration(); + LogLog.Debug(declaringType, "Configuration reset before reading config."); + } + + /* Building Appender objects, placing them in a local namespace + for future reference */ + + /* Process all the top level elements */ + + foreach (XmlNode currentNode in element.ChildNodes) + { + if (currentNode.NodeType == XmlNodeType.Element) + { + XmlElement currentElement = (XmlElement)currentNode; + + if (currentElement.LocalName == LOGGER_TAG) + { + this.ParseLogger(currentElement); + } + else if (currentElement.LocalName == CATEGORY_TAG) + { + // TODO: deprecated use of category + this.ParseLogger(currentElement); + } + else if (currentElement.LocalName == ROOT_TAG) + { + this.ParseRoot(currentElement); + } + else if (currentElement.LocalName == RENDERER_TAG) + { + this.ParseRenderer(currentElement); + } + else if (currentElement.LocalName == APPENDER_TAG) + { + // We ignore appenders in this pass. They will + // be found and loaded if they are referenced. + } + else + { + // Read the param tags and set properties on the hierarchy + this.SetParameter(currentElement, this.m_hierarchy); + } + } + } + + // Lastly set the hierarchy threshold + string thresholdStr = element.GetAttribute(THRESHOLD_ATTR); + LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]"); + if (thresholdStr.Length > 0 && thresholdStr != "null") + { + Level thresholdLevel = (Level)this.ConvertStringTo(typeof(Level), thresholdStr); + if (thresholdLevel != null) + { + this.m_hierarchy.Threshold = thresholdLevel; + } + else + { + LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)"); + } + } + + // Done reading config + } + + /// + /// Parse appenders by IDREF. + /// + /// The appender ref element. + /// The instance of the appender that the ref refers to. + /// + /// + /// Parse an XML element that represents an appender and return + /// the appender. + /// + /// + protected IAppender FindAppenderByReference(XmlElement appenderRef) + { + string appenderName = appenderRef.GetAttribute(REF_ATTR); + + IAppender appender = (IAppender)this.m_appenderBag[appenderName]; + if (appender != null) + { + return appender; + } + else + { + // Find the element with that id + XmlElement element = null; + + if (appenderName != null && appenderName.Length > 0) + { + foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG)) + { + if (curAppenderElement.GetAttribute("name") == appenderName) + { + element = curAppenderElement; + break; + } + } + } + + if (element == null) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found."); + return null; + } + else + { + appender = this.ParseAppender(element); + if (appender != null) + { + this.m_appenderBag[appenderName] = appender; + } + + return appender; + } + } + } + + /// + /// Parses an appender element. + /// + /// The appender element. + /// The appender instance or null when parsing failed. + /// + /// + /// Parse an XML element that represents an appender and return + /// the appender instance. + /// + /// + protected IAppender ParseAppender(XmlElement appenderElement) + { + string appenderName = appenderElement.GetAttribute(NAME_ATTR); + string typeName = appenderElement.GetAttribute(TYPE_ATTR); + + LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]"); + try + { #if NETSTANDARD1_3 IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, typeName, true, true)); #else - IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true)); + IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true)); #endif - appender.Name = appenderName; - - foreach (XmlNode currentNode in appenderElement.ChildNodes) - { - /* We're only interested in Elements */ - if (currentNode.NodeType == XmlNodeType.Element) - { - XmlElement currentElement = (XmlElement)currentNode; - - // Look for the appender ref tag - if (currentElement.LocalName == APPENDER_REF_TAG) - { - string refName = currentElement.GetAttribute(REF_ATTR); - - IAppenderAttachable appenderContainer = appender as IAppenderAttachable; - if (appenderContainer != null) - { - LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "]."); - - IAppender referencedAppender = FindAppenderByReference(currentElement); - if (referencedAppender != null) - { - appenderContainer.AddAppender(referencedAppender); - } - } - else - { - LogLog.Error(declaringType, "Requesting attachment of appender named ["+refName+ "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable."); - } - } - else - { - // For all other tags we use standard set param method - SetParameter(currentElement, appender); - } - } - } - - IOptionHandler optionHandler = appender as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - - LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]"); - return appender; - } - catch (Exception ex) - { - // Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender - - LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex); - return null; - } - } - - /// - /// Parses a logger element. - /// - /// The logger element. - /// - /// - /// Parse an XML element that represents a logger. - /// - /// - protected void ParseLogger(XmlElement loggerElement) - { - // Create a new log4net.Logger object from the element. - string loggerName = loggerElement.GetAttribute(NAME_ATTR); - - LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + loggerName + "]."); - Logger log = m_hierarchy.GetLogger(loggerName) as Logger; - - // Setting up a logger needs to be an atomic operation, in order - // to protect potential log operations while logger - // configuration is in progress. - lock(log) - { - bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true); - - LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "]."); - log.Additivity = additivity; - ParseChildrenOfLoggerElement(loggerElement, log, false); - } - } - - /// - /// Parses the root logger element. - /// - /// The root element. - /// - /// - /// Parse an XML element that represents the root logger. - /// - /// - protected void ParseRoot(XmlElement rootElement) - { - Logger root = m_hierarchy.Root; - // logger configuration needs to be atomic - lock(root) - { - ParseChildrenOfLoggerElement(rootElement, root, true); - } - } - - /// - /// Parses the children of a logger element. - /// - /// The category element. - /// The logger instance. - /// Flag to indicate if the logger is the root logger. - /// - /// - /// Parse the child elements of a <logger> element. - /// - /// - protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot) - { - // Remove all existing appenders from log. They will be - // reconstructed if need be. - log.RemoveAllAppenders(); - - foreach (XmlNode currentNode in catElement.ChildNodes) - { - if (currentNode.NodeType == XmlNodeType.Element) - { - XmlElement currentElement = (XmlElement) currentNode; - - if (currentElement.LocalName == APPENDER_REF_TAG) - { - IAppender appender = FindAppenderByReference(currentElement); - string refName = currentElement.GetAttribute(REF_ATTR); - if (appender != null) - { - LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "]."); - log.AddAppender(appender); - } - else - { - LogLog.Error(declaringType, "Appender named [" + refName + "] not found."); - } - } - else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG) - { - ParseLevel(currentElement, log, isRoot); - } - else - { - SetParameter(currentElement, log); - } - } - } - - IOptionHandler optionHandler = log as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - } - - /// - /// Parses an object renderer. - /// - /// The renderer element. - /// - /// - /// Parse an XML element that represents a renderer. - /// - /// - protected void ParseRenderer(XmlElement element) - { - string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR); - string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR); - - LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "]."); - IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null); - if (renderer == null) - { - LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "]."); - return; - } - else - { - try - { + appender.Name = appenderName; + + foreach (XmlNode currentNode in appenderElement.ChildNodes) + { + /* We're only interested in Elements */ + if (currentNode.NodeType == XmlNodeType.Element) + { + XmlElement currentElement = (XmlElement)currentNode; + + // Look for the appender ref tag + if (currentElement.LocalName == APPENDER_REF_TAG) + { + string refName = currentElement.GetAttribute(REF_ATTR); + + IAppenderAttachable appenderContainer = appender as IAppenderAttachable; + if (appenderContainer != null) + { + LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "]."); + + IAppender referencedAppender = this.FindAppenderByReference(currentElement); + if (referencedAppender != null) + { + appenderContainer.AddAppender(referencedAppender); + } + } + else + { + LogLog.Error(declaringType, "Requesting attachment of appender named [" + refName + "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable."); + } + } + else + { + // For all other tags we use standard set param method + this.SetParameter(currentElement, appender); + } + } + } + + IOptionHandler optionHandler = appender as IOptionHandler; + if (optionHandler != null) + { + optionHandler.ActivateOptions(); + } + + LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]"); + return appender; + } + catch (Exception ex) + { + // Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender + LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex); + return null; + } + } + + /// + /// Parses a logger element. + /// + /// The logger element. + /// + /// + /// Parse an XML element that represents a logger. + /// + /// + protected void ParseLogger(XmlElement loggerElement) + { + // Create a new log4net.Logger object from the element. + string loggerName = loggerElement.GetAttribute(NAME_ATTR); + + LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + loggerName + "]."); + Logger log = this.m_hierarchy.GetLogger(loggerName) as Logger; + + // Setting up a logger needs to be an atomic operation, in order + // to protect potential log operations while logger + // configuration is in progress. + lock (log) + { + bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true); + + LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "]."); + log.Additivity = additivity; + this.ParseChildrenOfLoggerElement(loggerElement, log, false); + } + } + + /// + /// Parses the root logger element. + /// + /// The root element. + /// + /// + /// Parse an XML element that represents the root logger. + /// + /// + protected void ParseRoot(XmlElement rootElement) + { + Logger root = this.m_hierarchy.Root; + + // logger configuration needs to be atomic + lock (root) + { + this.ParseChildrenOfLoggerElement(rootElement, root, true); + } + } + + /// + /// Parses the children of a logger element. + /// + /// The category element. + /// The logger instance. + /// Flag to indicate if the logger is the root logger. + /// + /// + /// Parse the child elements of a <logger> element. + /// + /// + protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot) + { + // Remove all existing appenders from log. They will be + // reconstructed if need be. + log.RemoveAllAppenders(); + + foreach (XmlNode currentNode in catElement.ChildNodes) + { + if (currentNode.NodeType == XmlNodeType.Element) + { + XmlElement currentElement = (XmlElement)currentNode; + + if (currentElement.LocalName == APPENDER_REF_TAG) + { + IAppender appender = this.FindAppenderByReference(currentElement); + string refName = currentElement.GetAttribute(REF_ATTR); + if (appender != null) + { + LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "]."); + log.AddAppender(appender); + } + else + { + LogLog.Error(declaringType, "Appender named [" + refName + "] not found."); + } + } + else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG) + { + this.ParseLevel(currentElement, log, isRoot); + } + else + { + this.SetParameter(currentElement, log); + } + } + } + + IOptionHandler optionHandler = log as IOptionHandler; + if (optionHandler != null) + { + optionHandler.ActivateOptions(); + } + } + + /// + /// Parses an object renderer. + /// + /// The renderer element. + /// + /// + /// Parse an XML element that represents a renderer. + /// + /// + protected void ParseRenderer(XmlElement element) + { + string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR); + string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR); + + LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "]."); + IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null); + if (renderer == null) + { + LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "]."); + return; + } + else + { + try + { #if NETSTANDARD1_3 m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, renderedClassName, true, true), renderer); #else - m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer); + this.m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer); #endif - } - catch(Exception e) - { - LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e); - } - } - } - - /// - /// Parses a level element. - /// - /// The level element. - /// The logger object to set the level on. - /// Flag to indicate if the logger is the root logger. - /// - /// - /// Parse an XML element that represents a level. - /// - /// - protected void ParseLevel(XmlElement element, Logger log, bool isRoot) - { - string loggerName = log.Name; - if (isRoot) - { - loggerName = "root"; - } - - string levelStr = element.GetAttribute(VALUE_ATTR); - LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "]."); - - if (INHERITED == levelStr) - { - if (isRoot) - { - LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive."); - } - else - { - LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent."); - log.Level = null; - } - } - else - { - log.Level = log.Hierarchy.LevelMap[levelStr]; - if (log.Level == null) - { - LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "]."); - } - else - { - LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "]."); - } - } - } - - /// - /// Sets a parameter on an object. - /// - /// The parameter element. - /// The object to set the parameter on. - /// - /// The parameter name must correspond to a writable property - /// on the object. The value of the parameter is a string, - /// therefore this function will attempt to set a string - /// property first. If unable to set a string property it - /// will inspect the property and its argument type. It will - /// attempt to call a static method called Parse on the - /// type of the property. This method will take a single - /// string argument and return a value that can be used to - /// set the property. - /// - protected void SetParameter(XmlElement element, object target) - { - // Get the property name - string name = element.GetAttribute(NAME_ATTR); - - // If the name attribute does not exist then use the name of the element - if (element.LocalName != PARAM_TAG || name == null || name.Length == 0) - { - name = element.LocalName; - } - - // Look for the property on the target object - Type targetType = target.GetType(); - Type propertyType = null; - - PropertyInfo propInfo = null; - MethodInfo methInfo = null; - - // Try to find a writable property - propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); - if (propInfo != null && propInfo.CanWrite) - { - // found a property - propertyType = propInfo.PropertyType; - } - else - { - propInfo = null; - - // look for a method with the signature Add(type) - methInfo = FindMethodInfo(targetType, name); - - if (methInfo != null) - { - propertyType = methInfo.GetParameters()[0].ParameterType; - } - } - - if (propertyType == null) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]"); - } - else - { - string propertyValue = null; - - if (element.GetAttributeNode(VALUE_ATTR) != null) - { - propertyValue = element.GetAttribute(VALUE_ATTR); - } - else if (element.HasChildNodes) - { - // Concatenate the CDATA and Text nodes together - foreach(XmlNode childNode in element.ChildNodes) - { - if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text) - { - if (propertyValue == null) - { - propertyValue = childNode.InnerText; - } - else - { - propertyValue += childNode.InnerText; - } - } - } - } - - if(propertyValue != null) - { + } + catch (Exception e) + { + LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e); + } + } + } + + /// + /// Parses a level element. + /// + /// The level element. + /// The logger object to set the level on. + /// Flag to indicate if the logger is the root logger. + /// + /// + /// Parse an XML element that represents a level. + /// + /// + protected void ParseLevel(XmlElement element, Logger log, bool isRoot) + { + string loggerName = log.Name; + if (isRoot) + { + loggerName = "root"; + } + + string levelStr = element.GetAttribute(VALUE_ATTR); + LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "]."); + + if (levelStr == INHERITED) + { + if (isRoot) + { + LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive."); + } + else + { + LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent."); + log.Level = null; + } + } + else + { + log.Level = log.Hierarchy.LevelMap[levelStr]; + if (log.Level == null) + { + LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "]."); + } + else + { + LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "]."); + } + } + } + + /// + /// Sets a parameter on an object. + /// + /// The parameter element. + /// The object to set the parameter on. + /// + /// The parameter name must correspond to a writable property + /// on the object. The value of the parameter is a string, + /// therefore this function will attempt to set a string + /// property first. If unable to set a string property it + /// will inspect the property and its argument type. It will + /// attempt to call a static method called Parse on the + /// type of the property. This method will take a single + /// string argument and return a value that can be used to + /// set the property. + /// + protected void SetParameter(XmlElement element, object target) + { + // Get the property name + string name = element.GetAttribute(NAME_ATTR); + + // If the name attribute does not exist then use the name of the element + if (element.LocalName != PARAM_TAG || name == null || name.Length == 0) + { + name = element.LocalName; + } + + // Look for the property on the target object + Type targetType = target.GetType(); + Type propertyType = null; + + PropertyInfo propInfo = null; + MethodInfo methInfo = null; + + // Try to find a writable property + propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); + if (propInfo != null && propInfo.CanWrite) + { + // found a property + propertyType = propInfo.PropertyType; + } + else + { + propInfo = null; + + // look for a method with the signature Add(type) + methInfo = this.FindMethodInfo(targetType, name); + + if (methInfo != null) + { + propertyType = methInfo.GetParameters()[0].ParameterType; + } + } + + if (propertyType == null) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]"); + } + else + { + string propertyValue = null; + + if (element.GetAttributeNode(VALUE_ATTR) != null) + { + propertyValue = element.GetAttribute(VALUE_ATTR); + } + else if (element.HasChildNodes) + { + // Concatenate the CDATA and Text nodes together + foreach (XmlNode childNode in element.ChildNodes) + { + if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text) + { + if (propertyValue == null) + { + propertyValue = childNode.InnerText; + } + else + { + propertyValue += childNode.InnerText; + } + } + } + } + + if (propertyValue != null) + { #if !(NETCF || NETSTANDARD1_3) // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 - try - { - // Expand environment variables in the string. - IDictionary environmentVariables = Environment.GetEnvironmentVariables(); - if (HasCaseInsensitiveEnvironment) { - environmentVariables = CreateCaseInsensitiveWrapper(environmentVariables); - } - propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables); - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // unrestricted environment permission. If this occurs the expansion - // will be skipped with the following warning message. - LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion."); - } + try + { + // Expand environment variables in the string. + IDictionary environmentVariables = Environment.GetEnvironmentVariables(); + if (this.HasCaseInsensitiveEnvironment) + { + environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables); + } + + propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables); + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // unrestricted environment permission. If this occurs the expansion + // will be skipped with the following warning message. + LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion."); + } #endif - Type parsedObjectConversionTargetType = null; + Type parsedObjectConversionTargetType = null; - // Check if a specific subtype is specified on the element using the 'type' attribute - string subTypeString = element.GetAttribute(TYPE_ATTR); - if (subTypeString != null && subTypeString.Length > 0) - { - // Read the explicit subtype - try - { + // Check if a specific subtype is specified on the element using the 'type' attribute + string subTypeString = element.GetAttribute(TYPE_ATTR); + if (subTypeString != null && subTypeString.Length > 0) + { + // Read the explicit subtype + try + { #if NETSTANDARD1_3 Type subType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, subTypeString, true, true); #else - Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true); + Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true); #endif - LogLog.Debug(declaringType, "Parameter ["+name+"] specified subtype ["+subType.FullName+"]"); - - if (!propertyType.IsAssignableFrom(subType)) - { - // Check if there is an appropriate type converter - if (OptionConverter.CanConvertTypeTo(subType, propertyType)) - { - // Must re-convert to the real property type - parsedObjectConversionTargetType = propertyType; - - // Use sub type as intermediary type - propertyType = subType; - } - else - { - LogLog.Error(declaringType, "subtype ["+subType.FullName+"] set on ["+name+"] is not a subclass of property type ["+propertyType.FullName+"] and there are no acceptable type conversions."); - } - } - else - { - // The subtype specified is found and is actually a subtype of the property - // type, therefore we can switch to using this type. - propertyType = subType; - } - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to find type ["+subTypeString+"] set on ["+name+"]", ex); - } - } - - // Now try to convert the string value to an acceptable type - // to pass to this property. - - object convertedValue = ConvertStringTo(propertyType, propertyValue); - - // Check if we need to do an additional conversion - if (convertedValue != null && parsedObjectConversionTargetType != null) - { - LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]"); - convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType); - } - - if (convertedValue != null) - { - if (propInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); - - try - { - // Pass to the property + LogLog.Debug(declaringType, "Parameter [" + name + "] specified subtype [" + subType.FullName + "]"); + + if (!propertyType.IsAssignableFrom(subType)) + { + // Check if there is an appropriate type converter + if (OptionConverter.CanConvertTypeTo(subType, propertyType)) + { + // Must re-convert to the real property type + parsedObjectConversionTargetType = propertyType; + + // Use sub type as intermediary type + propertyType = subType; + } + else + { + LogLog.Error(declaringType, "subtype [" + subType.FullName + "] set on [" + name + "] is not a subclass of property type [" + propertyType.FullName + "] and there are no acceptable type conversions."); + } + } + else + { + // The subtype specified is found and is actually a subtype of the property + // type, therefore we can switch to using this type. + propertyType = subType; + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to find type [" + subTypeString + "] set on [" + name + "]", ex); + } + } + + // Now try to convert the string value to an acceptable type + // to pass to this property. + object convertedValue = this.ConvertStringTo(propertyType, propertyValue); + + // Check if we need to do an additional conversion + if (convertedValue != null && parsedObjectConversionTargetType != null) + { + LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]"); + convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType); + } + + if (convertedValue != null) + { + if (propInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); + + try + { + // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 propInfo.SetValue(target, convertedValue, null); #else - propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); + propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); #endif - } - catch(TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); - } - } - else if (methInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); - - try - { - // Pass to the property + } + catch (TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); + } + } + else if (methInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); + + try + { + // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 methInfo.Invoke(target, new[] { convertedValue }); #else - methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {convertedValue}, CultureInfo.InvariantCulture); + methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture); #endif - } - catch(TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); - } - } - } - else - { - LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)"); - } - } - else - { - object createdObject = null; - - if (propertyType == typeof(string) && !HasAttributesOrElements(element)) - { - // If the property is a string and the element is empty (no attributes - // or child elements) then we special case the object value to an empty string. - // This is necessary because while the String is a class it does not have - // a default constructor that creates an empty string, which is the behavior - // we are trying to simulate and would be expected from CreateObjectFromXml - createdObject = ""; - } - else - { - // No value specified - Type defaultObjectType = null; - if (IsTypeConstructible(propertyType)) - { - defaultObjectType = propertyType; - } - - createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType); - } - - if (createdObject == null) - { - LogLog.Error(declaringType, "Failed to create object to set param: "+name); - } - else - { - if (propInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Property ["+ propInfo.Name +"] to object ["+ createdObject +"]"); - - try - { - // Pass to the property + } + catch (TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); + } + } + } + else + { + LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)"); + } + } + else + { + object createdObject = null; + + if (propertyType == typeof(string) && !this.HasAttributesOrElements(element)) + { + // If the property is a string and the element is empty (no attributes + // or child elements) then we special case the object value to an empty string. + // This is necessary because while the String is a class it does not have + // a default constructor that creates an empty string, which is the behavior + // we are trying to simulate and would be expected from CreateObjectFromXml + createdObject = string.Empty; + } + else + { + // No value specified + Type defaultObjectType = null; + if (IsTypeConstructible(propertyType)) + { + defaultObjectType = propertyType; + } + + createdObject = this.CreateObjectFromXml(element, defaultObjectType, propertyType); + } + + if (createdObject == null) + { + LogLog.Error(declaringType, "Failed to create object to set param: " + name); + } + else + { + if (propInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]"); + + try + { + // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 propInfo.SetValue(target, createdObject, null); #else - propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); + propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); #endif - } - catch(TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); - } - } - else if (methInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Collection Property ["+ methInfo.Name +"] to object ["+ createdObject +"]"); - - try - { - // Pass to the property + } + catch (TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); + } + } + else if (methInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to object [" + createdObject + "]"); + + try + { + // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 methInfo.Invoke(target, new[] { createdObject }); #else - methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {createdObject}, CultureInfo.InvariantCulture); + methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture); #endif - } - catch(TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); - } - } - } - } - } - } - - /// - /// Test if an element has no attributes or child elements - /// - /// the element to inspect - /// true if the element has any attributes or child elements, false otherwise - private bool HasAttributesOrElements(XmlElement element) - { - foreach(XmlNode node in element.ChildNodes) - { - if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element) - { - return true; - } - } - return false; - } - - /// - /// Test if a is constructible with Activator.CreateInstance. - /// - /// the type to inspect - /// true if the type is creatable using a default constructor, false otherwise - private static bool IsTypeConstructible(Type type) - { + } + catch (TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); + } + } + } + } + } + } + + /// + /// Test if an element has no attributes or child elements. + /// + /// the element to inspect. + /// true if the element has any attributes or child elements, false otherwise. + private bool HasAttributesOrElements(XmlElement element) + { + foreach (XmlNode node in element.ChildNodes) + { + if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element) + { + return true; + } + } + + return false; + } + + /// + /// Test if a is constructible with Activator.CreateInstance. + /// + /// the type to inspect. + /// true if the type is creatable using a default constructor, false otherwise. + private static bool IsTypeConstructible(Type type) + { #if NETSTANDARD1_3 TypeInfo typeInfo = type.GetTypeInfo(); if (typeInfo.IsClass && !typeInfo.IsAbstract) #else - if (type.IsClass && !type.IsAbstract) + if (type.IsClass && !type.IsAbstract) #endif - { - ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]); - if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate) - { - return true; - } - } - return false; - } - - /// - /// Look for a method on the that matches the supplied - /// - /// the type that has the method - /// the name of the method - /// the method info found - /// - /// - /// The method must be a public instance method on the . - /// The method must be named or "Add" followed by . - /// The method must take a single parameter. - /// - /// - private MethodInfo FindMethodInfo(Type targetType, string name) - { - string requiredMethodNameA = name; - string requiredMethodNameB = "Add" + name; - - MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - - foreach(MethodInfo methInfo in methods) - { - if (!methInfo.IsStatic) - { - string methodInfoName = methInfo.Name; - - if (SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameA) || - SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameB)) - { - // Found matching method name - - // Look for version with one arg only - System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters(); - if (methParams.Length == 1) - { - return methInfo; - } - } - } - } - return null; - } - - /// - /// Converts a string value to a target type. - /// - /// The type of object to convert the string to. - /// The string value to use as the value of the object. - /// - /// - /// An object of type with value or - /// null when the conversion could not be performed. - /// - /// - protected object ConvertStringTo(Type type, string value) - { - // Hack to allow use of Level in property - if (typeof(Level) == type) - { - // Property wants a level - Level levelValue = m_hierarchy.LevelMap[value]; - - if (levelValue == null) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified ["+ value +"]"); - } - - return levelValue; - } - return OptionConverter.ConvertStringTo(type, value); - } - - /// - /// Creates an object as specified in XML. - /// - /// The XML element that contains the definition of the object. - /// The object type to use if not explicitly specified. - /// The type that the returned object must be or must inherit from. - /// The object or null - /// - /// - /// Parse an XML element and create an object instance based on the configuration - /// data. - /// - /// - /// The type of the instance may be specified in the XML. If not - /// specified then the is used - /// as the type. However the type is specified it must support the - /// type. - /// - /// - protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint) - { - Type objectType = null; - - // Get the object type - string objectTypeString = element.GetAttribute(TYPE_ATTR); - if (objectTypeString == null || objectTypeString.Length == 0) - { - if (defaultTargetType == null) - { - LogLog.Error(declaringType, "Object type not specified. Cannot create object of type ["+typeConstraint.FullName+"]. Missing Value or Type."); - return null; - } - else - { - // Use the default object type - objectType = defaultTargetType; - } - } - else - { - // Read the explicit object type - try - { + { + ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]); + if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate) + { + return true; + } + } + + return false; + } + + /// + /// Look for a method on the that matches the supplied. + /// + /// the type that has the method. + /// the name of the method. + /// the method info found. + /// + /// + /// The method must be a public instance method on the . + /// The method must be named or "Add" followed by . + /// The method must take a single parameter. + /// + /// + private MethodInfo FindMethodInfo(Type targetType, string name) + { + string requiredMethodNameA = name; + string requiredMethodNameB = "Add" + name; + + MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + foreach (MethodInfo methInfo in methods) + { + if (!methInfo.IsStatic) + { + string methodInfoName = methInfo.Name; + + if (SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameA) || + SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameB)) + { + // Found matching method name + + // Look for version with one arg only + System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters(); + if (methParams.Length == 1) + { + return methInfo; + } + } + } + } + + return null; + } + + /// + /// Converts a string value to a target type. + /// + /// The type of object to convert the string to. + /// The string value to use as the value of the object. + /// + /// + /// An object of type with value or + /// null when the conversion could not be performed. + /// + /// + protected object ConvertStringTo(Type type, string value) + { + // Hack to allow use of Level in property + if (typeof(Level) == type) + { + // Property wants a level + Level levelValue = this.m_hierarchy.LevelMap[value]; + + if (levelValue == null) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified [" + value + "]"); + } + + return levelValue; + } + + return OptionConverter.ConvertStringTo(type, value); + } + + /// + /// Creates an object as specified in XML. + /// + /// The XML element that contains the definition of the object. + /// The object type to use if not explicitly specified. + /// The type that the returned object must be or must inherit from. + /// The object or null. + /// + /// + /// Parse an XML element and create an object instance based on the configuration + /// data. + /// + /// + /// The type of the instance may be specified in the XML. If not + /// specified then the is used + /// as the type. However the type is specified it must support the + /// type. + /// + /// + protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint) + { + Type objectType = null; + + // Get the object type + string objectTypeString = element.GetAttribute(TYPE_ATTR); + if (objectTypeString == null || objectTypeString.Length == 0) + { + if (defaultTargetType == null) + { + LogLog.Error(declaringType, "Object type not specified. Cannot create object of type [" + typeConstraint.FullName + "]. Missing Value or Type."); + return null; + } + else + { + // Use the default object type + objectType = defaultTargetType; + } + } + else + { + // Read the explicit object type + try + { #if NETSTANDARD1_3 objectType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, objectTypeString, true, true); #else - objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true); + objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true); #endif - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to find type ["+objectTypeString+"]", ex); - return null; - } - } - - bool requiresConversion = false; - - // Got the object type. Check that it meets the typeConstraint - if (typeConstraint != null) - { - if (!typeConstraint.IsAssignableFrom(objectType)) - { - // Check if there is an appropriate type converter - if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint)) - { - requiresConversion = true; - } - else - { - LogLog.Error(declaringType, "Object type ["+objectType.FullName+"] is not assignable to type ["+typeConstraint.FullName+"]. There are no acceptable type conversions."); - return null; - } - } - } - - // Create using the default constructor - object createdObject = null; - try - { - createdObject = Activator.CreateInstance(objectType); - } - catch(Exception createInstanceEx) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: "+createInstanceEx.ToString()); - } - - // Set any params on object - foreach (XmlNode currentNode in element.ChildNodes) - { - if (currentNode.NodeType == XmlNodeType.Element) - { - SetParameter((XmlElement)currentNode, createdObject); - } - } - - // Check if we need to call ActivateOptions - IOptionHandler optionHandler = createdObject as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - - // Ok object should be initialized - - if (requiresConversion) - { - // Convert the object type - return OptionConverter.ConvertTypeTo(createdObject, typeConstraint); - } - else - { - // The object is of the correct type - return createdObject; - } - } - - #endregion Protected Instance Methods + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to find type [" + objectTypeString + "]", ex); + return null; + } + } + + bool requiresConversion = false; + // Got the object type. Check that it meets the typeConstraint + if (typeConstraint != null) + { + if (!typeConstraint.IsAssignableFrom(objectType)) + { + // Check if there is an appropriate type converter + if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint)) + { + requiresConversion = true; + } + else + { + LogLog.Error(declaringType, "Object type [" + objectType.FullName + "] is not assignable to type [" + typeConstraint.FullName + "]. There are no acceptable type conversions."); + return null; + } + } + } + + // Create using the default constructor + object createdObject = null; + try + { + createdObject = Activator.CreateInstance(objectType); + } + catch (Exception createInstanceEx) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: " + createInstanceEx.ToString()); + } + + // Set any params on object + foreach (XmlNode currentNode in element.ChildNodes) + { + if (currentNode.NodeType == XmlNodeType.Element) + { + this.SetParameter((XmlElement)currentNode, createdObject); + } + } + + // Check if we need to call ActivateOptions + IOptionHandler optionHandler = createdObject as IOptionHandler; + if (optionHandler != null) + { + optionHandler.ActivateOptions(); + } + + // Ok object should be initialized + if (requiresConversion) + { + // Convert the object type + return OptionConverter.ConvertTypeTo(createdObject, typeConstraint); + } + else + { + // The object is of the correct type + return createdObject; + } + } + #if !(NETCF || NETSTANDARD1_3) // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 - private bool HasCaseInsensitiveEnvironment - { - get - { + private bool HasCaseInsensitiveEnvironment + { + get + { #if NET_1_0 || NET_1_1 || CLI_1_0 // actually there is no guarantee, but we don't know better return true; @@ -1082,86 +1073,78 @@ private bool HasCaseInsensitiveEnvironment // see above return false; #else - PlatformID platform = Environment.OSVersion.Platform; - return platform != PlatformID.Unix && platform != PlatformID.MacOSX; -#endif - } - } - - private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict) - { - if (dict == null) - { - return dict; - } - Hashtable hash = SystemInfo.CreateCaseInsensitiveHashtable(); - foreach (DictionaryEntry entry in dict) { - hash[entry.Key] = entry.Value; - } - return hash; - } + PlatformID platform = Environment.OSVersion.Platform; + return platform != PlatformID.Unix && platform != PlatformID.MacOSX; #endif + } + } - #region Private Constants - - // String constants used while parsing the XML data - private const string CONFIGURATION_TAG = "log4net"; - private const string RENDERER_TAG = "renderer"; - private const string APPENDER_TAG = "appender"; - private const string APPENDER_REF_TAG = "appender-ref"; - private const string PARAM_TAG = "param"; - - // TODO: Deprecate use of category tags - private const string CATEGORY_TAG = "category"; - // TODO: Deprecate use of priority tag - private const string PRIORITY_TAG = "priority"; - - private const string LOGGER_TAG = "logger"; - private const string NAME_ATTR = "name"; - private const string TYPE_ATTR = "type"; - private const string VALUE_ATTR = "value"; - private const string ROOT_TAG = "root"; - private const string LEVEL_TAG = "level"; - private const string REF_ATTR = "ref"; - private const string ADDITIVITY_ATTR = "additivity"; - private const string THRESHOLD_ATTR = "threshold"; - private const string CONFIG_DEBUG_ATTR = "configDebug"; - private const string INTERNAL_DEBUG_ATTR = "debug"; - private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug"; - private const string CONFIG_UPDATE_MODE_ATTR = "update"; - private const string RENDERING_TYPE_ATTR = "renderingClass"; - private const string RENDERED_TYPE_ATTR = "renderedClass"; - - // flag used on the level element - private const string INHERITED = "inherited"; - - #endregion Private Constants - - #region Private Instance Fields - - /// - /// key: appenderName, value: appender. - /// - private Hashtable m_appenderBag; - - /// - /// The Hierarchy being configured. - /// - private readonly Hierarchy m_hierarchy; - - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the XmlHierarchyConfigurator class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(XmlHierarchyConfigurator); - - #endregion Private Static Fields - } + private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict) + { + if (dict == null) + { + return dict; + } + + Hashtable hash = SystemInfo.CreateCaseInsensitiveHashtable(); + foreach (DictionaryEntry entry in dict) + { + hash[entry.Key] = entry.Value; + } + + return hash; + } +#endif + + // String constants used while parsing the XML data + private const string CONFIGURATION_TAG = "log4net"; + private const string RENDERER_TAG = "renderer"; + private const string APPENDER_TAG = "appender"; + private const string APPENDER_REF_TAG = "appender-ref"; + private const string PARAM_TAG = "param"; + + // TODO: Deprecate use of category tags + private const string CATEGORY_TAG = "category"; + + // TODO: Deprecate use of priority tag + private const string PRIORITY_TAG = "priority"; + + private const string LOGGER_TAG = "logger"; + private const string NAME_ATTR = "name"; + private const string TYPE_ATTR = "type"; + private const string VALUE_ATTR = "value"; + private const string ROOT_TAG = "root"; + private const string LEVEL_TAG = "level"; + private const string REF_ATTR = "ref"; + private const string ADDITIVITY_ATTR = "additivity"; + private const string THRESHOLD_ATTR = "threshold"; + private const string CONFIG_DEBUG_ATTR = "configDebug"; + private const string INTERNAL_DEBUG_ATTR = "debug"; + private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug"; + private const string CONFIG_UPDATE_MODE_ATTR = "update"; + private const string RENDERING_TYPE_ATTR = "renderingClass"; + private const string RENDERED_TYPE_ATTR = "renderedClass"; + + // flag used on the level element + private const string INHERITED = "inherited"; + + /// + /// key: appenderName, value: appender. + /// + private Hashtable m_appenderBag; + + /// + /// The Hierarchy being configured. + /// + private readonly Hierarchy m_hierarchy; + + /// + /// The fully qualified type of the XmlHierarchyConfigurator class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(XmlHierarchyConfigurator); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs index 4798fa204e8..8561a51c911 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs @@ -1,61 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// namespace log4net.Repository { - /// - /// Basic Configurator interface for repositories - /// - /// - /// - /// Interface used by basic configurator to configure a - /// with a default . - /// - /// - /// A should implement this interface to support - /// configuration by the . - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IBasicRepositoryConfigurator - { - /// - /// Initialize the repository using the specified appender - /// - /// the appender to use to log all logging events - /// - /// - /// Configure the repository to route all logging events to the - /// specified appender. - /// - /// + /// + /// Basic Configurator interface for repositories. + /// + /// + /// + /// Interface used by basic configurator to configure a + /// with a default . + /// + /// + /// A should implement this interface to support + /// configuration by the . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IBasicRepositoryConfigurator + { + /// + /// Initialize the repository using the specified appender. + /// + /// the appender to use to log all logging events. + /// + /// + /// Configure the repository to route all logging events to the + /// specified appender. + /// + /// void Configure(Appender.IAppender appender); /// - /// Initialize the repository using the specified appenders + /// Initialize the repository using the specified appenders. /// - /// the appenders to use to log all logging events + /// the appenders to use to log all logging events. /// /// /// Configure the repository to route all logging events to the @@ -63,5 +60,5 @@ public interface IBasicRepositoryConfigurator /// /// void Configure(params Appender.IAppender[] appenders); - } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs index f8c55578e27..ddf598730a9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs @@ -1,353 +1,339 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using log4net; -using log4net.ObjectRenderer; -using log4net.Core; -using log4net.Plugin; -using log4net.Repository.Hierarchy; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository -{ - #region LoggerRepositoryShutdownEvent - - /// - /// Delegate used to handle logger repository shutdown event notifications - /// - /// The that is shutting down. - /// Empty event args - /// - /// - /// Delegate used to handle logger repository shutdown event notifications. - /// - /// - public delegate void LoggerRepositoryShutdownEventHandler(object sender, EventArgs e); - - #endregion - - #region LoggerRepositoryConfigurationResetEventHandler - - /// - /// Delegate used to handle logger repository configuration reset event notifications - /// - /// The that has had its configuration reset. - /// Empty event args - /// - /// - /// Delegate used to handle logger repository configuration reset event notifications. - /// - /// - public delegate void LoggerRepositoryConfigurationResetEventHandler(object sender, EventArgs e); - - #endregion - - #region LoggerRepositoryConfigurationChangedEventHandler - - /// - /// Delegate used to handle event notifications for logger repository configuration changes. - /// - /// The that has had its configuration changed. - /// Empty event arguments. - /// - /// - /// Delegate used to handle event notifications for logger repository configuration changes. - /// - /// - public delegate void LoggerRepositoryConfigurationChangedEventHandler(object sender, EventArgs e); - - #endregion - - /// - /// Interface implemented by logger repositories. - /// - /// - /// - /// This interface is implemented by logger repositories. e.g. - /// . - /// - /// - /// This interface is used by the - /// to obtain interfaces. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface ILoggerRepository - { - /// - /// The name of the repository - /// - /// - /// The name of the repository - /// - /// - /// - /// The name of the repository. - /// - /// - string Name { get; set; } +{ + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net; + using log4net.Core; + using log4net.ObjectRenderer; + using log4net.Plugin; + using log4net.Repository.Hierarchy; + using log4net.Util; + + /// + /// Delegate used to handle logger repository shutdown event notifications. + /// + /// The that is shutting down. + /// Empty event args. + /// + /// + /// Delegate used to handle logger repository shutdown event notifications. + /// + /// + public delegate void LoggerRepositoryShutdownEventHandler(object sender, EventArgs e); + + /// + /// Delegate used to handle logger repository configuration reset event notifications. + /// + /// The that has had its configuration reset. + /// Empty event args. + /// + /// + /// Delegate used to handle logger repository configuration reset event notifications. + /// + /// + public delegate void LoggerRepositoryConfigurationResetEventHandler(object sender, EventArgs e); + + /// + /// Delegate used to handle event notifications for logger repository configuration changes. + /// + /// The that has had its configuration changed. + /// Empty event arguments. + /// + /// + /// Delegate used to handle event notifications for logger repository configuration changes. + /// + /// + public delegate void LoggerRepositoryConfigurationChangedEventHandler(object sender, EventArgs e); + + /// + /// Interface implemented by logger repositories. + /// + /// + /// + /// This interface is implemented by logger repositories. e.g. + /// . + /// + /// + /// This interface is used by the + /// to obtain interfaces. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface ILoggerRepository + { + /// + /// Gets or sets the name of the repository. + /// + /// + /// The name of the repository. + /// + /// + /// + /// The name of the repository. + /// + /// + string Name { get; set; } - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// The RendererMap holds a mapping between types and - /// objects. - /// - /// - RendererMap RendererMap { get; } + /// + /// Gets rendererMap accesses the object renderer map for this repository. + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// The RendererMap holds a mapping between types and + /// objects. + /// + /// + RendererMap RendererMap { get; } - /// - /// The plugin map for this repository. - /// - /// - /// The plugin map for this repository. - /// - /// - /// - /// The plugin map holds the instances - /// that have been attached to this repository. - /// - /// - PluginMap PluginMap { get; } + /// + /// Gets the plugin map for this repository. + /// + /// + /// The plugin map for this repository. + /// + /// + /// + /// The plugin map holds the instances + /// that have been attached to this repository. + /// + /// + PluginMap PluginMap { get; } - /// - /// Get the level map for the Repository. - /// - /// - /// - /// Get the level map for the Repository. - /// - /// - /// The level map defines the mappings between - /// level names and objects in - /// this repository. - /// - /// - LevelMap LevelMap { get; } + /// + /// Gets get the level map for the Repository. + /// + /// + /// + /// Get the level map for the Repository. + /// + /// + /// The level map defines the mappings between + /// level names and objects in + /// this repository. + /// + /// + LevelMap LevelMap { get; } - /// - /// The threshold for all events in this repository - /// - /// - /// The threshold for all events in this repository - /// - /// - /// - /// The threshold for all events in this repository. - /// - /// - Level Threshold { get; set; } + /// + /// Gets or sets the threshold for all events in this repository. + /// + /// + /// The threshold for all events in this repository. + /// + /// + /// + /// The threshold for all events in this repository. + /// + /// + Level Threshold { get; set; } - /// - /// Check if the named logger exists in the repository. If so return - /// its reference, otherwise returns null. - /// - /// The name of the logger to lookup - /// The Logger object with the name specified - /// - /// - /// If the names logger exists it is returned, otherwise - /// null is returned. - /// - /// - ILogger Exists(string name); + /// + /// Check if the named logger exists in the repository. If so return + /// its reference, otherwise returns null. + /// + /// The name of the logger to lookup. + /// The Logger object with the name specified. + /// + /// + /// If the names logger exists it is returned, otherwise + /// null is returned. + /// + /// + ILogger Exists(string name); - /// - /// Returns all the currently defined loggers as an Array. - /// - /// All the defined loggers - /// - /// - /// Returns all the currently defined loggers as an Array. - /// - /// - ILogger[] GetCurrentLoggers(); + /// + /// Returns all the currently defined loggers as an Array. + /// + /// All the defined loggers. + /// + /// + /// Returns all the currently defined loggers as an Array. + /// + /// + ILogger[] GetCurrentLoggers(); - /// - /// Returns a named logger instance - /// - /// The name of the logger to retrieve - /// The logger object with the name specified - /// - /// - /// Returns a named logger instance. - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated and - /// then linked with its existing ancestors as well as children. - /// - /// - ILogger GetLogger(string name); + /// + /// Returns a named logger instance. + /// + /// The name of the logger to retrieve. + /// The logger object with the name specified. + /// + /// + /// Returns a named logger instance. + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated and + /// then linked with its existing ancestors as well as children. + /// + /// + ILogger GetLogger(string name); - /// Shutdown the repository - /// - /// - /// Shutting down a repository will safely close and remove - /// all appenders in all loggers including the root logger. - /// - /// - /// Some appenders need to be closed before the - /// application exists. Otherwise, pending logging events might be - /// lost. - /// - /// - /// The method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - void Shutdown(); + /// Shutdown the repository. + /// + /// + /// Shutting down a repository will safely close and remove + /// all appenders in all loggers including the root logger. + /// + /// + /// Some appenders need to be closed before the + /// application exists. Otherwise, pending logging events might be + /// lost. + /// + /// + /// The method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + void Shutdown(); - /// - /// Reset the repositories configuration to a default state - /// - /// - /// - /// Reset all values contained in this instance to their - /// default state. - /// - /// - /// Existing loggers are not removed. They are just reset. - /// - /// - /// This method should be used sparingly and with care as it will - /// block all logging until it is completed. - /// - /// - void ResetConfiguration(); + /// + /// Reset the repositories configuration to a default state. + /// + /// + /// + /// Reset all values contained in this instance to their + /// default state. + /// + /// + /// Existing loggers are not removed. They are just reset. + /// + /// + /// This method should be used sparingly and with care as it will + /// block all logging until it is completed. + /// + /// + void ResetConfiguration(); - /// - /// Log the through this repository. - /// - /// the event to log - /// - /// - /// This method should not normally be used to log. - /// The interface should be used - /// for routine logging. This interface can be obtained - /// using the method. - /// - /// - /// The logEvent is delivered to the appropriate logger and - /// that logger is then responsible for logging the event. - /// - /// - void Log(LoggingEvent logEvent); + /// + /// Log the through this repository. + /// + /// the event to log. + /// + /// + /// This method should not normally be used to log. + /// The interface should be used + /// for routine logging. This interface can be obtained + /// using the method. + /// + /// + /// The logEvent is delivered to the appropriate logger and + /// that logger is then responsible for logging the event. + /// + /// + void Log(LoggingEvent logEvent); - /// - /// Flag indicates if this repository has been configured. - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - bool Configured { get; set; } + /// + /// Gets or sets a value indicating whether flag indicates if this repository has been configured. + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + bool Configured { get; set; } /// - /// Collection of internal messages captured during the most + /// Gets or sets collection of internal messages captured during the most /// recent configuration process. /// ICollection ConfigurationMessages { get; set; } - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// - /// Event raised when the repository has been shutdown. - /// - /// - event LoggerRepositoryShutdownEventHandler ShutdownEvent; + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// + /// Event raised when the repository has been shutdown. + /// + /// + event LoggerRepositoryShutdownEventHandler ShutdownEvent; - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// - /// Event raised when the repository's configuration has been - /// reset to default. - /// - /// - event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset; + /// + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// + /// Event raised when the repository's configuration has been + /// reset to default. + /// + /// + event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset; - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// - /// Event raised when the repository's configuration has been changed. - /// - /// - event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged; + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// + /// Event raised when the repository's configuration has been changed. + /// + /// + event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged; - /// - /// Repository specific properties - /// - /// - /// Repository specific properties - /// - /// - /// - /// These properties can be specified on a repository specific basis. - /// - /// - PropertiesDictionary Properties { get; } + /// + /// Gets repository specific properties. + /// + /// + /// Repository specific properties. + /// + /// + /// + /// These properties can be specified on a repository specific basis. + /// + /// + PropertiesDictionary Properties { get; } - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// All the Appenders - /// - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// - log4net.Appender.IAppender[] GetAppenders(); - } + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// All the Appenders. + /// + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// + log4net.Appender.IAppender[] GetAppenders(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs index dfe1564285a..a1786a3a931 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs @@ -1,58 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository { - /// - /// Configure repository using XML - /// - /// - /// - /// Interface used by Xml configurator to configure a . - /// - /// - /// A should implement this interface to support - /// configuration by the . - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IXmlRepositoryConfigurator - { - /// - /// Initialize the repository using the specified config - /// - /// the element containing the root of the config - /// - /// - /// The schema for the XML configuration data is defined by - /// the implementation. - /// - /// - void Configure(System.Xml.XmlElement element); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Util; + + /// + /// Configure repository using XML. + /// + /// + /// + /// Interface used by Xml configurator to configure a . + /// + /// + /// A should implement this interface to support + /// configuration by the . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IXmlRepositoryConfigurator + { + /// + /// Initialize the repository using the specified config. + /// + /// the element containing the root of the config. + /// + /// + /// The schema for the XML configuration data is defined by + /// the implementation. + /// + /// + void Configure(System.Xml.XmlElement element); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs index 4357ccbc210..9d7f7365df7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs @@ -1,592 +1,594 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using log4net.ObjectRenderer; -using log4net.Core; -using log4net.Util; -using log4net.Plugin; -using System.Threading; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Repository { - /// - /// Base implementation of - /// - /// - /// - /// Default abstract implementation of the interface. - /// - /// - /// Skeleton implementation of the interface. - /// All types can extend this type. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public abstract class LoggerRepositorySkeleton : ILoggerRepository, Appender.IFlushable - { - #region Member Variables - - private string m_name; - private RendererMap m_rendererMap; - private PluginMap m_pluginMap; - private LevelMap m_levelMap; - private Level m_threshold; - private bool m_configured; + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Threading; + + using log4net.Core; + using log4net.ObjectRenderer; + using log4net.Plugin; + using log4net.Util; + + /// + /// Base implementation of . + /// + /// + /// + /// Default abstract implementation of the interface. + /// + /// + /// Skeleton implementation of the interface. + /// All types can extend this type. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class LoggerRepositorySkeleton : ILoggerRepository, Appender.IFlushable + { + private string m_name; + private RendererMap m_rendererMap; + private PluginMap m_pluginMap; + private LevelMap m_levelMap; + private Level m_threshold; + private bool m_configured; private ICollection m_configurationMessages; - private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; - private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; - private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; - private PropertiesDictionary m_properties; - - #endregion - - #region Constructors - - /// - /// Default Constructor - /// - /// - /// - /// Initializes the repository with default (empty) properties. - /// - /// - protected LoggerRepositorySkeleton() : this(new PropertiesDictionary()) - { - } - - /// - /// Construct the repository using specific properties - /// - /// the properties to set for this repository - /// - /// - /// Initializes the repository with specified properties. - /// - /// - protected LoggerRepositorySkeleton(PropertiesDictionary properties) - { - m_properties = properties; - m_rendererMap = new RendererMap(); - m_pluginMap = new PluginMap(this); - m_levelMap = new LevelMap(); - m_configurationMessages = EmptyCollection.Instance; - m_configured = false; - - AddBuiltinLevels(); - - // Don't disable any levels by default. - m_threshold = Level.All; - } - - #endregion - - #region Implementation of ILoggerRepository - - /// - /// The name of the repository - /// - /// - /// The string name of the repository - /// - /// - /// - /// The name of this repository. The name is - /// used to store and lookup the repositories - /// stored by the . - /// - /// - virtual public string Name - { - get { return m_name; } - set { m_name = value; } - } - - /// - /// The threshold for all events in this repository - /// - /// - /// The threshold for all events in this repository - /// - /// - /// - /// The threshold for all events in this repository - /// - /// - virtual public Level Threshold - { - get { return m_threshold; } - set - { - if (value != null) - { - m_threshold = value; - } - else - { - // Must not set threshold to null - LogLog.Warn(declaringType, "LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); - m_threshold = Level.All; - } - } - } - - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// The RendererMap holds a mapping between types and - /// objects. - /// - /// - virtual public RendererMap RendererMap - { - get { return m_rendererMap; } - } - - /// - /// The plugin map for this repository. - /// - /// - /// The plugin map for this repository. - /// - /// - /// - /// The plugin map holds the instances - /// that have been attached to this repository. - /// - /// - virtual public PluginMap PluginMap - { - get { return m_pluginMap; } - } - - /// - /// Get the level map for the Repository. - /// - /// - /// - /// Get the level map for the Repository. - /// - /// - /// The level map defines the mappings between - /// level names and objects in - /// this repository. - /// - /// - virtual public LevelMap LevelMap - { - get { return m_levelMap; } - } - - /// - /// Test if logger exists - /// - /// The name of the logger to lookup - /// The Logger object with the name specified - /// - /// - /// Check if the named logger exists in the repository. If so return - /// its reference, otherwise returns null. - /// - /// - abstract public ILogger Exists(string name); - - /// - /// Returns all the currently defined loggers in the repository - /// - /// All the defined loggers - /// - /// - /// Returns all the currently defined loggers in the repository as an Array. - /// - /// - abstract public ILogger[] GetCurrentLoggers(); - - /// - /// Return a new logger instance - /// - /// The name of the logger to retrieve - /// The logger object with the name specified - /// - /// - /// Return a new logger instance. - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated and - /// then linked with its existing ancestors as well as children. - /// - /// - abstract public ILogger GetLogger(string name); - - /// - /// Shutdown the repository - /// - /// - /// - /// Shutdown the repository. Can be overridden in a subclass. - /// This base class implementation notifies the - /// listeners and all attached plugins of the shutdown event. - /// - /// - virtual public void Shutdown() - { - // Shutdown attached plugins - foreach(IPlugin plugin in PluginMap.AllPlugins) - { - plugin.Shutdown(); - } - - // Notify listeners - OnShutdown(null); - } - - /// - /// Reset the repositories configuration to a default state - /// - /// - /// - /// Reset all values contained in this instance to their - /// default state. - /// - /// - /// Existing loggers are not removed. They are just reset. - /// - /// - /// This method should be used sparingly and with care as it will - /// block all logging until it is completed. - /// - /// - virtual public void ResetConfiguration() - { - // Clear internal data structures - m_rendererMap.Clear(); - m_levelMap.Clear(); - m_configurationMessages = EmptyCollection.Instance; - - // Add the predefined levels to the map - AddBuiltinLevels(); - - Configured = false; - - // Notify listeners - OnConfigurationReset(null); - } - - /// - /// Log the logEvent through this repository. - /// - /// the event to log - /// - /// - /// This method should not normally be used to log. - /// The interface should be used - /// for routine logging. This interface can be obtained - /// using the method. - /// - /// - /// The logEvent is delivered to the appropriate logger and - /// that logger is then responsible for logging the event. - /// - /// - abstract public void Log(LoggingEvent logEvent); - - /// - /// Flag indicates if this repository has been configured. - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - virtual public bool Configured - { - get { return m_configured; } - set { m_configured = value; } - } + + private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; + + private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; + + private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; + + private PropertiesDictionary m_properties; + + /// + /// Initializes a new instance of the class. + /// Default Constructor. + /// + /// + /// + /// Initializes the repository with default (empty) properties. + /// + /// + protected LoggerRepositorySkeleton() + : this(new PropertiesDictionary()) + { + } + + /// + /// Initializes a new instance of the class. + /// Construct the repository using specific properties. + /// + /// the properties to set for this repository. + /// + /// + /// Initializes the repository with specified properties. + /// + /// + protected LoggerRepositorySkeleton(PropertiesDictionary properties) + { + this.m_properties = properties; + this.m_rendererMap = new RendererMap(); + this.m_pluginMap = new PluginMap(this); + this.m_levelMap = new LevelMap(); + this.m_configurationMessages = EmptyCollection.Instance; + this.m_configured = false; + + this.AddBuiltinLevels(); + + // Don't disable any levels by default. + this.m_threshold = Level.All; + } + + /// + /// Gets or sets the name of the repository. + /// + /// + /// The string name of the repository. + /// + /// + /// + /// The name of this repository. The name is + /// used to store and lookup the repositories + /// stored by the . + /// + /// + public virtual string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + /// + /// Gets or sets the threshold for all events in this repository. + /// + /// + /// The threshold for all events in this repository. + /// + /// + /// + /// The threshold for all events in this repository. + /// + /// + public virtual Level Threshold + { + get { return this.m_threshold; } + + set + { + if (value != null) + { + this.m_threshold = value; + } + else + { + // Must not set threshold to null + LogLog.Warn(declaringType, "LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); + this.m_threshold = Level.All; + } + } + } + + /// + /// Gets rendererMap accesses the object renderer map for this repository. + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// The RendererMap holds a mapping between types and + /// objects. + /// + /// + public virtual RendererMap RendererMap + { + get { return this.m_rendererMap; } + } + + /// + /// Gets the plugin map for this repository. + /// + /// + /// The plugin map for this repository. + /// + /// + /// + /// The plugin map holds the instances + /// that have been attached to this repository. + /// + /// + public virtual PluginMap PluginMap + { + get { return this.m_pluginMap; } + } + + /// + /// Gets get the level map for the Repository. + /// + /// + /// + /// Get the level map for the Repository. + /// + /// + /// The level map defines the mappings between + /// level names and objects in + /// this repository. + /// + /// + public virtual LevelMap LevelMap + { + get { return this.m_levelMap; } + } + + /// + /// Test if logger exists. + /// + /// The name of the logger to lookup. + /// The Logger object with the name specified. + /// + /// + /// Check if the named logger exists in the repository. If so return + /// its reference, otherwise returns null. + /// + /// + public abstract ILogger Exists(string name); + + /// + /// Returns all the currently defined loggers in the repository. + /// + /// All the defined loggers. + /// + /// + /// Returns all the currently defined loggers in the repository as an Array. + /// + /// + public abstract ILogger[] GetCurrentLoggers(); + + /// + /// Return a new logger instance. + /// + /// The name of the logger to retrieve. + /// The logger object with the name specified. + /// + /// + /// Return a new logger instance. + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated and + /// then linked with its existing ancestors as well as children. + /// + /// + public abstract ILogger GetLogger(string name); + + /// + /// Shutdown the repository. + /// + /// + /// + /// Shutdown the repository. Can be overridden in a subclass. + /// This base class implementation notifies the + /// listeners and all attached plugins of the shutdown event. + /// + /// + public virtual void Shutdown() + { + // Shutdown attached plugins + foreach (IPlugin plugin in this.PluginMap.AllPlugins) + { + plugin.Shutdown(); + } + + // Notify listeners + this.OnShutdown(null); + } + + /// + /// Reset the repositories configuration to a default state. + /// + /// + /// + /// Reset all values contained in this instance to their + /// default state. + /// + /// + /// Existing loggers are not removed. They are just reset. + /// + /// + /// This method should be used sparingly and with care as it will + /// block all logging until it is completed. + /// + /// + public virtual void ResetConfiguration() + { + // Clear internal data structures + this.m_rendererMap.Clear(); + this.m_levelMap.Clear(); + this.m_configurationMessages = EmptyCollection.Instance; + + // Add the predefined levels to the map + this.AddBuiltinLevels(); + + this.Configured = false; + + // Notify listeners + this.OnConfigurationReset(null); + } + + /// + /// Log the logEvent through this repository. + /// + /// the event to log. + /// + /// + /// This method should not normally be used to log. + /// The interface should be used + /// for routine logging. This interface can be obtained + /// using the method. + /// + /// + /// The logEvent is delivered to the appropriate logger and + /// that logger is then responsible for logging the event. + /// + /// + public abstract void Log(LoggingEvent logEvent); /// - /// Contains a list of internal messages captures during the + /// Gets or sets a value indicating whether flag indicates if this repository has been configured. + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + public virtual bool Configured + { + get { return this.m_configured; } + set { this.m_configured = value; } + } + + /// + /// Gets or sets contains a list of internal messages captures during the /// last configuration. /// - virtual public ICollection ConfigurationMessages - { - get { return m_configurationMessages; } - set { m_configurationMessages = value; } - } - - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// - /// Event raised when the repository has been shutdown. - /// - /// - public event LoggerRepositoryShutdownEventHandler ShutdownEvent - { - add { m_shutdownEvent += value; } - remove { m_shutdownEvent -= value; } - } - - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// - /// Event raised when the repository's configuration has been - /// reset to default. - /// - /// - public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset - { - add { m_configurationResetEvent += value; } - remove { m_configurationResetEvent -= value; } - } - - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// - /// Event raised when the repository's configuration has been changed. - /// - /// - public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged - { - add { m_configurationChangedEvent += value; } - remove { m_configurationChangedEvent -= value; } - } - - /// - /// Repository specific properties - /// - /// - /// Repository specific properties - /// - /// - /// These properties can be specified on a repository specific basis - /// - public PropertiesDictionary Properties - { - get { return m_properties; } - } - - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// All the Appenders - /// - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// - abstract public log4net.Appender.IAppender[] GetAppenders(); - - #endregion - - #region Private Static Fields - - /// - /// The fully qualified type of the LoggerRepositorySkeleton class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(LoggerRepositorySkeleton); - - #endregion Private Static Fields - - private void AddBuiltinLevels() - { - // Add the predefined levels to the map - m_levelMap.Add(Level.Off); - - // Unrecoverable errors - m_levelMap.Add(Level.Emergency); - m_levelMap.Add(Level.Fatal); - m_levelMap.Add(Level.Alert); - - // Recoverable errors - m_levelMap.Add(Level.Critical); - m_levelMap.Add(Level.Severe); - m_levelMap.Add(Level.Error); - m_levelMap.Add(Level.Warn); - - // Information - m_levelMap.Add(Level.Notice); - m_levelMap.Add(Level.Info); - - // Debug - m_levelMap.Add(Level.Debug); - m_levelMap.Add(Level.Fine); - m_levelMap.Add(Level.Trace); - m_levelMap.Add(Level.Finer); - m_levelMap.Add(Level.Verbose); - m_levelMap.Add(Level.Finest); - - m_levelMap.Add(Level.All); - } - - /// - /// Adds an object renderer for a specific class. - /// - /// The type that will be rendered by the renderer supplied. - /// The object renderer used to render the object. - /// - /// - /// Adds an object renderer for a specific class. - /// - /// - virtual public void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) - { - if (typeToRender == null) - { - throw new ArgumentNullException("typeToRender"); - } - if (rendererInstance == null) - { - throw new ArgumentNullException("rendererInstance"); - } - - m_rendererMap.Put(typeToRender, rendererInstance); - } - - /// - /// Notify the registered listeners that the repository is shutting down - /// - /// Empty EventArgs - /// - /// - /// Notify any listeners that this repository is shutting down. - /// - /// - protected virtual void OnShutdown(EventArgs e) - { - if (e == null) - { - e = EventArgs.Empty; - } - - LoggerRepositoryShutdownEventHandler handler = m_shutdownEvent; - if (handler != null) - { - handler(this, e); - } - } - - /// - /// Notify the registered listeners that the repository has had its configuration reset - /// - /// Empty EventArgs - /// - /// - /// Notify any listeners that this repository's configuration has been reset. - /// - /// - protected virtual void OnConfigurationReset(EventArgs e) - { - if (e == null) - { - e = EventArgs.Empty; - } - - LoggerRepositoryConfigurationResetEventHandler handler = m_configurationResetEvent; - if (handler != null) - { - handler(this, e); - } - } - - /// - /// Notify the registered listeners that the repository has had its configuration changed - /// - /// Empty EventArgs - /// - /// - /// Notify any listeners that this repository's configuration has changed. - /// - /// - protected virtual void OnConfigurationChanged(EventArgs e) - { - if (e == null) - { - e = EventArgs.Empty; - } - - LoggerRepositoryConfigurationChangedEventHandler handler = m_configurationChangedEvent; - if (handler != null) - { - handler(this, e); - } - } - - /// - /// Raise a configuration changed event on this repository - /// - /// EventArgs.Empty - /// - /// - /// Applications that programmatically change the configuration of the repository should - /// raise this event notification to notify listeners. - /// - /// - public void RaiseConfigurationChanged(EventArgs e) - { - OnConfigurationChanged(e); - } + public virtual ICollection ConfigurationMessages + { + get { return this.m_configurationMessages; } + set { this.m_configurationMessages = value; } + } - private static int GetWaitTime(DateTime startTimeUtc, int millisecondsTimeout) + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// + /// Event raised when the repository has been shutdown. + /// + /// + public event LoggerRepositoryShutdownEventHandler ShutdownEvent + { + add { this.m_shutdownEvent += value; } + remove { this.m_shutdownEvent -= value; } + } + + /// + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// + /// Event raised when the repository's configuration has been + /// reset to default. + /// + /// + public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset + { + add { this.m_configurationResetEvent += value; } + remove { this.m_configurationResetEvent -= value; } + } + + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// + /// Event raised when the repository's configuration has been changed. + /// + /// + public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged + { + add { this.m_configurationChangedEvent += value; } + remove { this.m_configurationChangedEvent -= value; } + } + + /// + /// Gets repository specific properties. + /// + /// + /// Repository specific properties. + /// + /// + /// These properties can be specified on a repository specific basis. + /// + public PropertiesDictionary Properties + { + get { return this.m_properties; } + } + + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// All the Appenders. + /// + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// + public abstract log4net.Appender.IAppender[] GetAppenders(); + + /// + /// The fully qualified type of the LoggerRepositorySkeleton class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(LoggerRepositorySkeleton); + + private void AddBuiltinLevels() + { + // Add the predefined levels to the map + this.m_levelMap.Add(Level.Off); + + // Unrecoverable errors + this.m_levelMap.Add(Level.Emergency); + this.m_levelMap.Add(Level.Fatal); + this.m_levelMap.Add(Level.Alert); + + // Recoverable errors + this.m_levelMap.Add(Level.Critical); + this.m_levelMap.Add(Level.Severe); + this.m_levelMap.Add(Level.Error); + this.m_levelMap.Add(Level.Warn); + + // Information + this.m_levelMap.Add(Level.Notice); + this.m_levelMap.Add(Level.Info); + + // Debug + this.m_levelMap.Add(Level.Debug); + this.m_levelMap.Add(Level.Fine); + this.m_levelMap.Add(Level.Trace); + this.m_levelMap.Add(Level.Finer); + this.m_levelMap.Add(Level.Verbose); + this.m_levelMap.Add(Level.Finest); + + this.m_levelMap.Add(Level.All); + } + + /// + /// Adds an object renderer for a specific class. + /// + /// The type that will be rendered by the renderer supplied. + /// The object renderer used to render the object. + /// + /// + /// Adds an object renderer for a specific class. + /// + /// + public virtual void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) + { + if (typeToRender == null) + { + throw new ArgumentNullException("typeToRender"); + } + + if (rendererInstance == null) + { + throw new ArgumentNullException("rendererInstance"); + } + + this.m_rendererMap.Put(typeToRender, rendererInstance); + } + + /// + /// Notify the registered listeners that the repository is shutting down. + /// + /// Empty EventArgs. + /// + /// + /// Notify any listeners that this repository is shutting down. + /// + /// + protected virtual void OnShutdown(EventArgs e) + { + if (e == null) + { + e = EventArgs.Empty; + } + + LoggerRepositoryShutdownEventHandler handler = this.m_shutdownEvent; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Notify the registered listeners that the repository has had its configuration reset. + /// + /// Empty EventArgs. + /// + /// + /// Notify any listeners that this repository's configuration has been reset. + /// + /// + protected virtual void OnConfigurationReset(EventArgs e) + { + if (e == null) + { + e = EventArgs.Empty; + } + + LoggerRepositoryConfigurationResetEventHandler handler = this.m_configurationResetEvent; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Notify the registered listeners that the repository has had its configuration changed. + /// + /// Empty EventArgs. + /// + /// + /// Notify any listeners that this repository's configuration has changed. + /// + /// + protected virtual void OnConfigurationChanged(EventArgs e) + { + if (e == null) + { + e = EventArgs.Empty; + } + + LoggerRepositoryConfigurationChangedEventHandler handler = this.m_configurationChangedEvent; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Raise a configuration changed event on this repository. + /// + /// EventArgs.Empty. + /// + /// + /// Applications that programmatically change the configuration of the repository should + /// raise this event notification to notify listeners. + /// + /// + public void RaiseConfigurationChanged(EventArgs e) { - if (millisecondsTimeout == Timeout.Infinite) return Timeout.Infinite; - if (millisecondsTimeout == 0) return 0; + this.OnConfigurationChanged(e); + } + private static int GetWaitTime(DateTime startTimeUtc, int millisecondsTimeout) + { + if (millisecondsTimeout == Timeout.Infinite) + { + return Timeout.Infinite; + } + + if (millisecondsTimeout == 0) + { + return 0; + } + int elapsedMilliseconds = (int)(DateTime.UtcNow - startTimeUtc).TotalMilliseconds; int timeout = millisecondsTimeout - elapsedMilliseconds; - if (timeout < 0) timeout = 0; + if (timeout < 0) + { + timeout = 0; + } + return timeout; } @@ -598,39 +600,56 @@ private static int GetWaitTime(DateTime startTimeUtc, int millisecondsTimeout) /// True if all logging events were flushed successfully, else false. public bool Flush(int millisecondsTimeout) { - if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException("millisecondsTimeout", "Timeout must be -1 (Timeout.Infinite) or non-negative"); - - // Assume success until one of the appenders fails + if (millisecondsTimeout < -1) + { + throw new ArgumentOutOfRangeException("millisecondsTimeout", "Timeout must be -1 (Timeout.Infinite) or non-negative"); + } + + // Assume success until one of the appenders fails bool result = true; // Use DateTime.UtcNow rather than a System.Diagnostics.Stopwatch for compatibility with .NET 1.x DateTime startTimeUtc = DateTime.UtcNow; // Do buffering appenders first. These may be forwarding to other appenders - foreach(log4net.Appender.IAppender appender in GetAppenders()) + foreach (log4net.Appender.IAppender appender in this.GetAppenders()) { log4net.Appender.IFlushable flushable = appender as log4net.Appender.IFlushable; - if (flushable == null) continue; + if (flushable == null) + { + continue; + } + if (appender is Appender.BufferingAppenderSkeleton) { int timeout = GetWaitTime(startTimeUtc, millisecondsTimeout); - if (!flushable.Flush(timeout)) result = false; + if (!flushable.Flush(timeout)) + { + result = false; + } } } // Do non-buffering appenders. - foreach (log4net.Appender.IAppender appender in GetAppenders()) + foreach (log4net.Appender.IAppender appender in this.GetAppenders()) { log4net.Appender.IFlushable flushable = appender as log4net.Appender.IFlushable; - if (flushable == null) continue; + if (flushable == null) + { + continue; + } + if (!(appender is Appender.BufferingAppenderSkeleton)) { int timeout = GetWaitTime(startTimeUtc, millisecondsTimeout); - if (!flushable.Flush(timeout)) result = false; + if (!flushable.Flush(timeout)) + { + result = false; + } } } return result; } - } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs index 38c05997e28..1a034245725 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs @@ -1,143 +1,129 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net { - /// - /// The log4net Thread Context. - /// - /// - /// - /// The ThreadContext provides a location for thread specific debugging - /// information to be stored. - /// The ThreadContext properties override any - /// properties with the same name. - /// - /// - /// The thread context has a properties map and a stack. - /// The properties and stack can - /// be included in the output of log messages. The - /// supports selecting and outputting these properties. - /// - /// - /// The Thread Context provides a diagnostic context for the current thread. - /// This is an instrument for distinguishing interleaved log - /// output from different sources. Log output is typically interleaved - /// when a server handles multiple clients near-simultaneously. - /// - /// - /// The Thread Context is managed on a per thread basis. - /// - /// - /// Example of using the thread context properties to store a username. - /// - /// ThreadContext.Properties["user"] = userName; - /// log.Info("This log message has a ThreadContext Property called 'user'"); - /// - /// - /// Example of how to push a message into the context stack - /// - /// using(ThreadContext.Stacks["NDC"].Push("my context message")) - /// { - /// log.Info("This log message has a ThreadContext Stack message that includes 'my context message'"); - /// - /// } // at the end of the using block the message is automatically popped - /// - /// - /// - /// Nicko Cadell - public sealed class ThreadContext - { - #region Private Instance Constructors - - /// - /// Private Constructor. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private ThreadContext() - { - } - - #endregion Private Instance Constructors - - #region Public Static Properties - - /// - /// The thread properties map - /// - /// - /// The thread properties map - /// - /// - /// - /// The ThreadContext properties override any - /// properties with the same name. - /// - /// - public static ThreadContextProperties Properties - { - get { return s_properties; } - } - - /// - /// The thread stacks - /// - /// - /// stack map - /// - /// - /// - /// The thread local stacks. - /// - /// - public static ThreadContextStacks Stacks - { - get { return s_stacks; } - } - - #endregion Public Static Properties - - #region Private Static Fields - - /// - /// The thread context properties instance - /// - private readonly static ThreadContextProperties s_properties = new ThreadContextProperties(); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Util; + + /// + /// The log4net Thread Context. + /// + /// + /// + /// The ThreadContext provides a location for thread specific debugging + /// information to be stored. + /// The ThreadContext properties override any + /// properties with the same name. + /// + /// + /// The thread context has a properties map and a stack. + /// The properties and stack can + /// be included in the output of log messages. The + /// supports selecting and outputting these properties. + /// + /// + /// The Thread Context provides a diagnostic context for the current thread. + /// This is an instrument for distinguishing interleaved log + /// output from different sources. Log output is typically interleaved + /// when a server handles multiple clients near-simultaneously. + /// + /// + /// The Thread Context is managed on a per thread basis. + /// + /// + /// Example of using the thread context properties to store a username. + /// + /// ThreadContext.Properties["user"] = userName; + /// log.Info("This log message has a ThreadContext Property called 'user'"); + /// + /// + /// Example of how to push a message into the context stack. + /// + /// using(ThreadContext.Stacks["NDC"].Push("my context message")) + /// { + /// log.Info("This log message has a ThreadContext Stack message that includes 'my context message'"); + /// + /// } // at the end of the using block the message is automatically popped + /// + /// + /// + /// Nicko Cadell. + public sealed class ThreadContext + { + /// + /// Initializes a new instance of the class. + /// Private Constructor. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private ThreadContext() + { + } + + /// + /// Gets the thread properties map. + /// + /// + /// The thread properties map. + /// + /// + /// + /// The ThreadContext properties override any + /// properties with the same name. + /// + /// + public static ThreadContextProperties Properties + { + get { return s_properties; } + } - /// - /// The thread context stacks instance - /// - private readonly static ThreadContextStacks s_stacks = new ThreadContextStacks(s_properties); + /// + /// Gets the thread stacks. + /// + /// + /// stack map. + /// + /// + /// + /// The thread local stacks. + /// + /// + public static ThreadContextStacks Stacks + { + get { return s_stacks; } + } + + /// + /// The thread context properties instance. + /// + private static readonly ThreadContextProperties s_properties = new ThreadContextProperties(); - #endregion Private Static Fields - } + /// + /// The thread context stacks instance. + /// + private static readonly ThreadContextStacks s_stacks = new ThreadContextStacks(s_properties); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs index 026c777f401..895706c770c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs @@ -1,380 +1,363 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; -using log4net.Appender; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// A straightforward implementation of the interface. - /// - /// - /// - /// This is the default implementation of the - /// interface. Implementors of the interface - /// should aggregate an instance of this type. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class AppenderAttachedImpl : IAppenderAttachable - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public AppenderAttachedImpl() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Methods - - /// - /// Append on on all attached appenders. - /// - /// The event being logged. - /// The number of appenders called. - /// - /// - /// Calls the method on all - /// attached appenders. - /// - /// - public int AppendLoopOnAppenders(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - // m_appenderList is null when empty - if (m_appenderList == null) - { - return 0; - } - - if (m_appenderArray == null) - { - m_appenderArray = m_appenderList.ToArray(); - } - - foreach(IAppender appender in m_appenderArray) - { - try - { - appender.DoAppend(loggingEvent); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); - } - } - return m_appenderList.Count; - } - - /// - /// Append on on all attached appenders. - /// - /// The array of events being logged. - /// The number of appenders called. - /// - /// - /// Calls the method on all - /// attached appenders. - /// - /// - public int AppendLoopOnAppenders(LoggingEvent[] loggingEvents) - { - if (loggingEvents == null) - { - throw new ArgumentNullException("loggingEvents"); - } - if (loggingEvents.Length == 0) - { - throw new ArgumentException("loggingEvents array must not be empty", "loggingEvents"); - } - if (loggingEvents.Length == 1) - { - // Fall back to single event path - return AppendLoopOnAppenders(loggingEvents[0]); - } - - // m_appenderList is null when empty - if (m_appenderList == null) - { - return 0; - } - - if (m_appenderArray == null) - { - m_appenderArray = m_appenderList.ToArray(); - } - - foreach(IAppender appender in m_appenderArray) - { - try - { - CallAppend(appender, loggingEvents); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); - } - } - return m_appenderList.Count; - } - - #endregion Public Instance Methods - - #region Private Static Methods - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Appender; + using log4net.Core; + + /// + /// A straightforward implementation of the interface. + /// + /// + /// + /// This is the default implementation of the + /// interface. Implementors of the interface + /// should aggregate an instance of this type. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class AppenderAttachedImpl : IAppenderAttachable + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public AppenderAttachedImpl() + { + } + /// - /// Calls the DoAppende method on the with - /// the objects supplied. - /// - /// The appender - /// The events - /// - /// - /// If the supports the - /// interface then the will be passed - /// through using that interface. Otherwise the - /// objects in the array will be passed one at a time. - /// - /// - private static void CallAppend(IAppender appender, LoggingEvent[] loggingEvents) - { - IBulkAppender bulkAppender = appender as IBulkAppender; - if (bulkAppender != null) - { - bulkAppender.DoAppend(loggingEvents); - } - else - { - foreach(LoggingEvent loggingEvent in loggingEvents) - { - appender.DoAppend(loggingEvent); - } - } + /// Append on on all attached appenders. + ///
+ /// The event being logged. + /// The number of appenders called. + /// + /// + /// Calls the method on all + /// attached appenders. + /// + /// + public int AppendLoopOnAppenders(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + // m_appenderList is null when empty + if (this.m_appenderList == null) + { + return 0; + } + + if (this.m_appenderArray == null) + { + this.m_appenderArray = this.m_appenderList.ToArray(); + } + + foreach (IAppender appender in this.m_appenderArray) + { + try + { + appender.DoAppend(loggingEvent); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); + } + } + + return this.m_appenderList.Count; } - #endregion - - #region Implementation of IAppenderAttachable - /// - /// Attaches an appender. - /// - /// The appender to add. - /// - /// - /// If the appender is already in the list it won't be added again. - /// - /// - public void AddAppender(IAppender newAppender) - { - // Null values for newAppender parameter are strictly forbidden. - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } - - m_appenderArray = null; - if (m_appenderList == null) - { - m_appenderList = new AppenderCollection(1); - } - if (!m_appenderList.Contains(newAppender)) - { - m_appenderList.Add(newAppender); - } - } - - /// - /// Gets all attached appenders. - /// - /// - /// A collection of attached appenders, or null if there - /// are no attached appenders. - /// - /// - /// - /// The read only collection of all currently attached appenders. - /// - /// - public AppenderCollection Appenders - { - get - { - if (m_appenderList == null) - { - // We must always return a valid collection - return AppenderCollection.EmptyCollection; - } - else - { - return AppenderCollection.ReadOnly(m_appenderList); - } - } - } - - /// - /// Gets an attached appender with the specified name. - /// - /// The name of the appender to get. - /// - /// The appender with the name specified, or null if no appender with the - /// specified name is found. - /// - /// - /// - /// Lookup an attached appender by name. - /// - /// - public IAppender GetAppender(string name) - { - if (m_appenderList != null && name != null) - { - foreach(IAppender appender in m_appenderList) - { - if (name == appender.Name) - { - return appender; - } - } - } - return null; - } - - /// - /// Removes all attached appenders. - /// - /// - /// - /// Removes and closes all attached appenders - /// - /// - public void RemoveAllAppenders() - { - if (m_appenderList != null) - { - foreach(IAppender appender in m_appenderList) - { - try - { - appender.Close(); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Failed to Close appender ["+appender.Name+"]", ex); - } - } - m_appenderList = null; - m_appenderArray = null; - } - } - - /// - /// Removes the specified appender from the list of attached appenders. - /// - /// The appender to remove. - /// The appender removed from the list - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - public IAppender RemoveAppender(IAppender appender) - { - if (appender != null && m_appenderList != null) - { - m_appenderList.Remove(appender); - if (m_appenderList.Count == 0) - { - m_appenderList = null; - } - m_appenderArray = null; - } - return appender; - } - - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - public IAppender RemoveAppender(string name) - { - return RemoveAppender(GetAppender(name)); - } - - #endregion - - #region Private Instance Fields + /// Append on on all attached appenders. + ///
+ /// The array of events being logged. + /// The number of appenders called. + /// + /// + /// Calls the method on all + /// attached appenders. + /// + /// + public int AppendLoopOnAppenders(LoggingEvent[] loggingEvents) + { + if (loggingEvents == null) + { + throw new ArgumentNullException("loggingEvents"); + } + + if (loggingEvents.Length == 0) + { + throw new ArgumentException("loggingEvents array must not be empty", "loggingEvents"); + } + + if (loggingEvents.Length == 1) + { + // Fall back to single event path + return this.AppendLoopOnAppenders(loggingEvents[0]); + } + + // m_appenderList is null when empty + if (this.m_appenderList == null) + { + return 0; + } + + if (this.m_appenderArray == null) + { + this.m_appenderArray = this.m_appenderList.ToArray(); + } + + foreach (IAppender appender in this.m_appenderArray) + { + try + { + CallAppend(appender, loggingEvents); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); + } + } + + return this.m_appenderList.Count; + } + + /// + /// Calls the DoAppende method on the with + /// the objects supplied. + /// + /// The appender. + /// The events. + /// + /// + /// If the supports the + /// interface then the will be passed + /// through using that interface. Otherwise the + /// objects in the array will be passed one at a time. + /// + /// + private static void CallAppend(IAppender appender, LoggingEvent[] loggingEvents) + { + IBulkAppender bulkAppender = appender as IBulkAppender; + if (bulkAppender != null) + { + bulkAppender.DoAppend(loggingEvents); + } + else + { + foreach (LoggingEvent loggingEvent in loggingEvents) + { + appender.DoAppend(loggingEvent); + } + } + } + + /// + /// Attaches an appender. + /// + /// The appender to add. + /// + /// + /// If the appender is already in the list it won't be added again. + /// + /// + public void AddAppender(IAppender newAppender) + { + // Null values for newAppender parameter are strictly forbidden. + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } + + this.m_appenderArray = null; + if (this.m_appenderList == null) + { + this.m_appenderList = new AppenderCollection(1); + } + + if (!this.m_appenderList.Contains(newAppender)) + { + this.m_appenderList.Add(newAppender); + } + } - /// - /// List of appenders - /// - private AppenderCollection m_appenderList; + /// + /// Gets all attached appenders. + /// + /// + /// A collection of attached appenders, or null if there + /// are no attached appenders. + /// + /// + /// + /// The read only collection of all currently attached appenders. + /// + /// + public AppenderCollection Appenders + { + get + { + if (this.m_appenderList == null) + { + // We must always return a valid collection + return AppenderCollection.EmptyCollection; + } + else + { + return AppenderCollection.ReadOnly(this.m_appenderList); + } + } + } - /// - /// Array of appenders, used to cache the m_appenderList - /// - private IAppender[] m_appenderArray; + /// + /// Gets an attached appender with the specified name. + /// + /// The name of the appender to get. + /// + /// The appender with the name specified, or null if no appender with the + /// specified name is found. + /// + /// + /// + /// Lookup an attached appender by name. + /// + /// + public IAppender GetAppender(string name) + { + if (this.m_appenderList != null && name != null) + { + foreach (IAppender appender in this.m_appenderList) + { + if (name == appender.Name) + { + return appender; + } + } + } + + return null; + } - #endregion Private Instance Fields + /// + /// Removes all attached appenders. + /// + /// + /// + /// Removes and closes all attached appenders. + /// + /// + public void RemoveAllAppenders() + { + if (this.m_appenderList != null) + { + foreach (IAppender appender in this.m_appenderList) + { + try + { + appender.Close(); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to Close appender [" + appender.Name + "]", ex); + } + } + + this.m_appenderList = null; + this.m_appenderArray = null; + } + } - #region Private Static Fields + /// + /// Removes the specified appender from the list of attached appenders. + /// + /// The appender to remove. + /// The appender removed from the list. + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public IAppender RemoveAppender(IAppender appender) + { + if (appender != null && this.m_appenderList != null) + { + this.m_appenderList.Remove(appender); + if (this.m_appenderList.Count == 0) + { + this.m_appenderList = null; + } + + this.m_appenderArray = null; + } + + return appender; + } - /// - /// The fully qualified type of the AppenderAttachedImpl class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(AppenderAttachedImpl); + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list. + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public IAppender RemoveAppender(string name) + { + return this.RemoveAppender(this.GetAppender(name)); + } + + /// + /// List of appenders. + /// + private AppenderCollection m_appenderList; - #endregion Private Static Fields - } + /// + /// Array of appenders, used to cache the m_appenderList. + /// + private IAppender[] m_appenderArray; + + /// + /// The fully qualified type of the AppenderAttachedImpl class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(AppenderAttachedImpl); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs index 466a642ba5a..dd58e8970b2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs @@ -1,159 +1,142 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// This class aggregates several PropertiesDictionary collections together. - /// - /// - /// - /// Provides a dictionary style lookup over an ordered list of - /// collections. - /// - /// - /// Nicko Cadell - public sealed class CompositeProperties - { - #region Private Instance Fields - - private PropertiesDictionary m_flattened = null; - private ArrayList m_nestedProperties = new ArrayList(); - - #endregion Private Instance Fields - - #region Public Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal CompositeProperties() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the value of a property - /// - /// - /// The value for the property with the specified key - /// - /// - /// - /// Looks up the value for the specified. - /// The collections are searched - /// in the order in which they were added to this collection. The value - /// returned is the value held by the first collection that contains - /// the specified key. - /// - /// - /// If none of the collections contain the specified key then - /// null is returned. - /// - /// - public object this[string key] - { - get - { - // Look in the flattened properties first - if (m_flattened != null) - { - return m_flattened[key]; - } - - // Look for the key in all the nested properties - foreach(ReadOnlyPropertiesDictionary cur in m_nestedProperties) - { - if (cur.Contains(key)) - { - return cur[key]; - } - } - return null; - } - } - - #endregion Public Instance Properties - - #region Public Instance Methods - - /// - /// Add a Properties Dictionary to this composite collection - /// - /// the properties to add - /// - /// - /// Properties dictionaries added first take precedence over dictionaries added - /// later. - /// - /// - public void Add(ReadOnlyPropertiesDictionary properties) - { - m_flattened = null; - m_nestedProperties.Add(properties); - } - - /// - /// Flatten this composite collection into a single properties dictionary - /// - /// the flattened dictionary - /// - /// - /// Reduces the collection of ordered dictionaries to a single dictionary - /// containing the resultant values for the keys. - /// - /// - public PropertiesDictionary Flatten() - { - if (m_flattened == null) - { - m_flattened = new PropertiesDictionary(); - - for(int i=m_nestedProperties.Count; --i>=0; ) - { - ReadOnlyPropertiesDictionary cur = (ReadOnlyPropertiesDictionary)m_nestedProperties[i]; - - foreach(DictionaryEntry entry in cur) - { - m_flattened[(string)entry.Key] = entry.Value; - } - } - } - return m_flattened; - } - - #endregion Public Instance Methods - } -} - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// This class aggregates several PropertiesDictionary collections together. + /// + /// + /// + /// Provides a dictionary style lookup over an ordered list of + /// collections. + /// + /// + /// Nicko Cadell. + public sealed class CompositeProperties + { + private PropertiesDictionary m_flattened = null; + private ArrayList m_nestedProperties = new ArrayList(); + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal CompositeProperties() + { + } + + /// + /// Gets the value of a property. + /// + /// + /// The value for the property with the specified key. + /// + /// + /// + /// Looks up the value for the specified. + /// The collections are searched + /// in the order in which they were added to this collection. The value + /// returned is the value held by the first collection that contains + /// the specified key. + /// + /// + /// If none of the collections contain the specified key then + /// null is returned. + /// + /// + public object this[string key] + { + get + { + // Look in the flattened properties first + if (this.m_flattened != null) + { + return this.m_flattened[key]; + } + + // Look for the key in all the nested properties + foreach (ReadOnlyPropertiesDictionary cur in this.m_nestedProperties) + { + if (cur.Contains(key)) + { + return cur[key]; + } + } + + return null; + } + } + + /// + /// Add a Properties Dictionary to this composite collection. + /// + /// the properties to add. + /// + /// + /// Properties dictionaries added first take precedence over dictionaries added + /// later. + /// + /// + public void Add(ReadOnlyPropertiesDictionary properties) + { + this.m_flattened = null; + this.m_nestedProperties.Add(properties); + } + + /// + /// Flatten this composite collection into a single properties dictionary. + /// + /// the flattened dictionary. + /// + /// + /// Reduces the collection of ordered dictionaries to a single dictionary + /// containing the resultant values for the keys. + /// + /// + public PropertiesDictionary Flatten() + { + if (this.m_flattened == null) + { + this.m_flattened = new PropertiesDictionary(); + + for (int i = this.m_nestedProperties.Count; --i >= 0;) + { + ReadOnlyPropertiesDictionary cur = (ReadOnlyPropertiesDictionary)this.m_nestedProperties[i]; + + foreach (DictionaryEntry entry in cur) + { + this.m_flattened[(string)entry.Key] = entry.Value; + } + } + } + + return this.m_flattened; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs index 8e10ffe0946..30773457f72 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs @@ -1,54 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Base class for Context Properties implementations - /// - /// - /// - /// This class defines a basic property get set accessor - /// - /// - /// Nicko Cadell - public abstract class ContextPropertiesBase - { - /// - /// Gets or sets the value of a property - /// - /// - /// The value for the property with the specified key - /// - /// - /// - /// Gets or sets the value of a property - /// - /// - public abstract object this[string key] { get; set; } - } -} - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// Base class for Context Properties implementations. + /// + /// + /// + /// This class defines a basic property get set accessor. + /// + /// + /// Nicko Cadell. + public abstract class ContextPropertiesBase + { + /// + /// Gets or sets the value of a property. + /// + /// + /// The value for the property with the specified key. + /// + /// + /// + /// Gets or sets the value of a property. + /// + /// + public abstract object this[string key] { get; set; } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs index 323437d7a6b..f89b61397db 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs @@ -1,8 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace log4net.Util +{ + /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -23,12 +25,10 @@ * */ -using System; - -namespace log4net.Util -{ + using System; + /// - /// Wrapper class used to map converter names to converter types + /// Wrapper class used to map converter names to converter types. /// /// /// @@ -40,59 +40,60 @@ public sealed class ConverterInfo { private string m_name; private Type m_type; - private readonly PropertiesDictionary properties = new PropertiesDictionary(); - - /// - /// default constructor + private readonly PropertiesDictionary properties = new PropertiesDictionary(); + + /// + /// Initializes a new instance of the class. + /// default constructor. /// public ConverterInfo() { } /// - /// Gets or sets the name of the conversion pattern + /// Gets or sets the name of the conversion pattern. /// /// /// - /// The name of the pattern in the format string + /// The name of the pattern in the format string. /// /// public string Name { - get { return m_name; } - set { m_name = value; } + get { return this.m_name; } + set { this.m_name = value; } } /// - /// Gets or sets the type of the converter + /// Gets or sets the type of the converter. /// /// /// - /// The value specified must extend the + /// The value specified must extend the /// type. /// /// public Type Type { - get { return m_type; } - set { m_type = value; } + get { return this.m_type; } + set { this.m_type = value; } } /// - /// + /// /// /// public void AddProperty(PropertyEntry entry) { - properties[entry.Key] = entry.Value; + this.properties[entry.Key] = entry.Value; } /// - /// + /// /// public PropertiesDictionary Properties { - get { return properties; } + get { return this.properties; } } } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs index 8e17490a600..661bb2615cd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs @@ -1,184 +1,167 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Subclass of that maintains a count of - /// the number of bytes written. - /// - /// - /// - /// This writer counts the number of bytes written. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class CountingQuietTextWriter : QuietTextWriter - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// The to actually write to. - /// The to report errors to. - /// - /// - /// Creates a new instance of the class - /// with the specified and . - /// - /// - public CountingQuietTextWriter(TextWriter writer, IErrorHandler errorHandler) : base(writer, errorHandler) - { - m_countBytes = 0; - } - - #endregion Public Instance Constructors - - #region Override implementation of QuietTextWriter - - /// - /// Writes a character to the underlying writer and counts the number of bytes written. - /// - /// the char to write - /// - /// - /// Overrides implementation of . Counts - /// the number of bytes written. - /// - /// - public override void Write(char value) - { - try - { - base.Write(value); - - // get the number of bytes needed to represent the - // char using the supplied encoding. - m_countBytes += this.Encoding.GetByteCount(new char[] { value }); - } - catch(Exception e) - { - this.ErrorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); - } - } - - /// - /// Writes a buffer to the underlying writer and counts the number of bytes written. - /// - /// the buffer to write - /// the start index to write from - /// the number of characters to write - /// - /// - /// Overrides implementation of . Counts - /// the number of bytes written. - /// - /// - public override void Write(char[] buffer, int index, int count) - { - if (count > 0) - { - try - { - base.Write(buffer, index, count); - - // get the number of bytes needed to represent the - // char array using the supplied encoding. - m_countBytes += this.Encoding.GetByteCount(buffer, index, count); - } - catch(Exception e) - { - this.ErrorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); - } - } - } - - /// - /// Writes a string to the output and counts the number of bytes written. - /// - /// The string data to write to the output. - /// - /// - /// Overrides implementation of . Counts - /// the number of bytes written. - /// - /// - override public void Write(string str) - { - if (str != null && str.Length > 0) - { - try - { - base.Write(str); - - // get the number of bytes needed to represent the - // string using the supplied encoding. - m_countBytes += this.Encoding.GetByteCount(str); - } - catch(Exception e) - { - this.ErrorHandler.Error("Failed to write [" + str + "].", e, ErrorCode.WriteFailure); - } - } - } - - #endregion Override implementation of QuietTextWriter + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net.Core; + + /// + /// Subclass of that maintains a count of + /// the number of bytes written. + /// + /// + /// + /// This writer counts the number of bytes written. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class CountingQuietTextWriter : QuietTextWriter + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The to actually write to. + /// The to report errors to. + /// + /// + /// Creates a new instance of the class + /// with the specified and . + /// + /// + public CountingQuietTextWriter(TextWriter writer, IErrorHandler errorHandler) + : base(writer, errorHandler) + { + this.m_countBytes = 0; + } + + /// + /// Writes a character to the underlying writer and counts the number of bytes written. + /// + /// the char to write. + /// + /// + /// Overrides implementation of . Counts + /// the number of bytes written. + /// + /// + public override void Write(char value) + { + try + { + base.Write(value); - #region Public Instance Properties + // get the number of bytes needed to represent the + // char using the supplied encoding. + this.m_countBytes += this.Encoding.GetByteCount(new char[] { value }); + } + catch (Exception e) + { + this.ErrorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); + } + } - /// - /// Gets or sets the total number of bytes written. - /// - /// - /// The total number of bytes written. - /// - /// - /// - /// Gets or sets the total number of bytes written. - /// - /// - public long Count - { - get { return m_countBytes; } - set { m_countBytes = value; } - } + /// + /// Writes a buffer to the underlying writer and counts the number of bytes written. + /// + /// the buffer to write. + /// the start index to write from. + /// the number of characters to write. + /// + /// + /// Overrides implementation of . Counts + /// the number of bytes written. + /// + /// + public override void Write(char[] buffer, int index, int count) + { + if (count > 0) + { + try + { + base.Write(buffer, index, count); - #endregion Public Instance Properties - - #region Private Instance Fields + // get the number of bytes needed to represent the + // char array using the supplied encoding. + this.m_countBytes += this.Encoding.GetByteCount(buffer, index, count); + } + catch (Exception e) + { + this.ErrorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); + } + } + } - /// - /// Total number of bytes written. - /// - private long m_countBytes; + /// + /// Writes a string to the output and counts the number of bytes written. + /// + /// The string data to write to the output. + /// + /// + /// Overrides implementation of . Counts + /// the number of bytes written. + /// + /// + public override void Write(string str) + { + if (str != null && str.Length > 0) + { + try + { + base.Write(str); - #endregion Private Instance Fields - } + // get the number of bytes needed to represent the + // string using the supplied encoding. + this.m_countBytes += this.Encoding.GetByteCount(str); + } + catch (Exception e) + { + this.ErrorHandler.Error("Failed to write [" + str + "].", e, ErrorCode.WriteFailure); + } + } + } + + /// + /// Gets or sets the total number of bytes written. + /// + /// + /// The total number of bytes written. + /// + /// + /// + /// Gets or sets the total number of bytes written. + /// + /// + public long Count + { + get { return this.m_countBytes; } + set { this.m_countBytes = value; } + } + + /// + /// Total number of bytes written. + /// + private long m_countBytes; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs index 5920265e77a..7d523893cff 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs @@ -1,212 +1,205 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// A fixed size rolling buffer of logging events. - /// - /// - /// - /// An array backed fixed size leaky bucket. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class CyclicBuffer - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// The maximum number of logging events in the buffer. - /// - /// - /// Initializes a new instance of the class with - /// the specified maximum number of buffered logging events. - /// - /// - /// The argument is not a positive integer. - public CyclicBuffer(int maxSize) - { - if (maxSize < 1) - { - throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required"); - } - - m_maxSize = maxSize; - m_events = new LoggingEvent[maxSize]; - m_first = 0; - m_last = 0; - m_numElems = 0; - } - - #endregion Public Instance Constructors - - #region Public Instance Methods - - /// - /// Appends a to the buffer. - /// - /// The event to append to the buffer. - /// The event discarded from the buffer, if the buffer is full, otherwise null. - /// - /// - /// Append an event to the buffer. If the buffer still contains free space then - /// null is returned. If the buffer is full then an event will be dropped - /// to make space for the new event, the event dropped is returned. - /// - /// - public LoggingEvent Append(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - lock(this) - { - // save the discarded event - LoggingEvent discardedLoggingEvent = m_events[m_last]; - - // overwrite the last event position - m_events[m_last] = loggingEvent; - if (++m_last == m_maxSize) - { - m_last = 0; - } - - if (m_numElems < m_maxSize) - { - m_numElems++; - } - else if (++m_first == m_maxSize) - { - m_first = 0; - } - - if (m_numElems < m_maxSize) - { - // Space remaining - return null; - } - else - { - // Buffer is full and discarding an event - return discardedLoggingEvent; - } - } - } - - /// - /// Get and remove the oldest event in the buffer. - /// - /// The oldest logging event in the buffer - /// - /// - /// Gets the oldest (first) logging event in the buffer and removes it - /// from the buffer. - /// - /// - public LoggingEvent PopOldest() - { - lock(this) - { - LoggingEvent ret = null; - if (m_numElems > 0) - { - m_numElems--; - ret = m_events[m_first]; - m_events[m_first] = null; - if (++m_first == m_maxSize) - { - m_first = 0; - } - } - return ret; - } - } - - /// - /// Pops all the logging events from the buffer into an array. - /// - /// An array of all the logging events in the buffer. - /// - /// - /// Get all the events in the buffer and clear the buffer. - /// - /// - public LoggingEvent[] PopAll() - { - lock(this) - { - LoggingEvent[] ret = new LoggingEvent[m_numElems]; - - if (m_numElems > 0) - { - if (m_first < m_last) - { - Array.Copy(m_events, m_first, ret, 0, m_numElems); - } - else - { - Array.Copy(m_events, m_first, ret, 0, m_maxSize - m_first); - Array.Copy(m_events, 0, ret, m_maxSize - m_first, m_last); - } - } - - Clear(); - - return ret; - } - } - - /// - /// Clear the buffer - /// - /// - /// - /// Clear the buffer of all events. The events in the buffer are lost. - /// - /// - public void Clear() - { - lock(this) - { - // Set all the elements to null - Array.Clear(m_events, 0, m_events.Length); - - m_first = 0; - m_last = 0; - m_numElems = 0; - } - } - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + + /// + /// A fixed size rolling buffer of logging events. + /// + /// + /// + /// An array backed fixed size leaky bucket. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class CyclicBuffer + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The maximum number of logging events in the buffer. + /// + /// + /// Initializes a new instance of the class with + /// the specified maximum number of buffered logging events. + /// + /// + /// The argument is not a positive integer. + public CyclicBuffer(int maxSize) + { + if (maxSize < 1) + { + throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required"); + } + + this.m_maxSize = maxSize; + this.m_events = new LoggingEvent[maxSize]; + this.m_first = 0; + this.m_last = 0; + this.m_numElems = 0; + } + + /// + /// Appends a to the buffer. + /// + /// The event to append to the buffer. + /// The event discarded from the buffer, if the buffer is full, otherwise null. + /// + /// + /// Append an event to the buffer. If the buffer still contains free space then + /// null is returned. If the buffer is full then an event will be dropped + /// to make space for the new event, the event dropped is returned. + /// + /// + public LoggingEvent Append(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + lock (this) + { + // save the discarded event + LoggingEvent discardedLoggingEvent = this.m_events[this.m_last]; + + // overwrite the last event position + this.m_events[this.m_last] = loggingEvent; + if (++this.m_last == this.m_maxSize) + { + this.m_last = 0; + } + + if (this.m_numElems < this.m_maxSize) + { + this.m_numElems++; + } + else if (++this.m_first == this.m_maxSize) + { + this.m_first = 0; + } + + if (this.m_numElems < this.m_maxSize) + { + // Space remaining + return null; + } + else + { + // Buffer is full and discarding an event + return discardedLoggingEvent; + } + } + } + + /// + /// Get and remove the oldest event in the buffer. + /// + /// The oldest logging event in the buffer. + /// + /// + /// Gets the oldest (first) logging event in the buffer and removes it + /// from the buffer. + /// + /// + public LoggingEvent PopOldest() + { + lock (this) + { + LoggingEvent ret = null; + if (this.m_numElems > 0) + { + this.m_numElems--; + ret = this.m_events[this.m_first]; + this.m_events[this.m_first] = null; + if (++this.m_first == this.m_maxSize) + { + this.m_first = 0; + } + } + + return ret; + } + } + + /// + /// Pops all the logging events from the buffer into an array. + /// + /// An array of all the logging events in the buffer. + /// + /// + /// Get all the events in the buffer and clear the buffer. + /// + /// + public LoggingEvent[] PopAll() + { + lock (this) + { + LoggingEvent[] ret = new LoggingEvent[this.m_numElems]; + + if (this.m_numElems > 0) + { + if (this.m_first < this.m_last) + { + Array.Copy(this.m_events, this.m_first, ret, 0, this.m_numElems); + } + else + { + Array.Copy(this.m_events, this.m_first, ret, 0, this.m_maxSize - this.m_first); + Array.Copy(this.m_events, 0, ret, this.m_maxSize - this.m_first, this.m_last); + } + } + + this.Clear(); + + return ret; + } + } + + /// + /// Clear the buffer. + /// + /// + /// + /// Clear the buffer of all events. The events in the buffer are lost. + /// + /// + public void Clear() + { + lock (this) + { + // Set all the elements to null + Array.Clear(this.m_events, 0, this.m_events.Length); + + this.m_first = 0; + this.m_last = 0; + this.m_numElems = 0; + } + } + #if RESIZABLE_CYCLIC_BUFFER /// /// Resizes the cyclic buffer to . @@ -265,55 +258,51 @@ public void Resize(int newSize) } } #endif - - #endregion Public Instance Methods - - #region Public Instance Properties - - /// - /// Gets the th oldest event currently in the buffer. - /// - /// The th oldest event currently in the buffer. - /// - /// - /// If is outside the range 0 to the number of events - /// currently in the buffer, then null is returned. - /// - /// - public LoggingEvent this[int i] - { - get - { - lock(this) - { - if (i < 0 || i >= m_numElems) - { - return null; - } - - return m_events[(m_first + i) % m_maxSize]; - } - } - } - - /// - /// Gets the maximum size of the buffer. - /// - /// The maximum size of the buffer. - /// - /// - /// Gets the maximum size of the buffer - /// - /// - public int MaxSize - { - get - { - lock(this) - { - return m_maxSize; - } - } + + /// + /// Gets the th oldest event currently in the buffer. + /// + /// The th oldest event currently in the buffer. + /// + /// + /// If is outside the range 0 to the number of events + /// currently in the buffer, then null is returned. + /// + /// + public LoggingEvent this[int i] + { + get + { + lock (this) + { + if (i < 0 || i >= this.m_numElems) + { + return null; + } + + return this.m_events[(this.m_first + i) % this.m_maxSize]; + } + } + } + + /// + /// Gets the maximum size of the buffer. + /// + /// The maximum size of the buffer. + /// + /// + /// Gets the maximum size of the buffer. + /// + /// + public int MaxSize + { + get + { + lock (this) + { + return this.m_maxSize; + } + } #if RESIZABLE_CYCLIC_BUFFER set { @@ -321,39 +310,33 @@ public int MaxSize Resize(value); } #endif - } - - /// - /// Gets the number of logging events in the buffer. - /// - /// The number of logging events in the buffer. - /// - /// - /// This number is guaranteed to be in the range 0 to - /// (inclusive). - /// - /// - public int Length - { - get - { - lock(this) - { - return m_numElems; - } - } - } - - #endregion Public Instance Properties - - #region Private Instance Fields - - private LoggingEvent[] m_events; - private int m_first; - private int m_last; - private int m_numElems; - private int m_maxSize; - - #endregion Private Instance Fields - } + } + + /// + /// Gets the number of logging events in the buffer. + /// + /// The number of logging events in the buffer. + /// + /// + /// This number is guaranteed to be in the range 0 to + /// (inclusive). + /// + /// + public int Length + { + get + { + lock (this) + { + return this.m_numElems; + } + } + } + + private LoggingEvent[] m_events; + private int m_first; + private int m_last; + private int m_numElems; + private int m_maxSize; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs index a5642dab750..46ce13f4fe9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs @@ -1,182 +1,159 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the - /// interface that always represents an empty collection. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the + /// interface that always represents an empty collection. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if !NETCF - [Serializable] + [Serializable] #endif - public sealed class EmptyCollection : ICollection - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private EmptyCollection() - { - } - - #endregion Private Instance Constructors - - #region Public Static Properties - - /// - /// Gets the singleton instance of the empty collection. - /// - /// The singleton instance of the empty collection. - /// - /// - /// Gets the singleton instance of the empty collection. - /// - /// - public static EmptyCollection Instance - { - get { return s_instance; } - } - - #endregion Public Static Properties - - #region Implementation of ICollection - - /// - /// Copies the elements of the to an - /// , starting at a particular Array index. - /// - /// The one-dimensional - /// that is the destination of the elements copied from - /// . The Array must have zero-based - /// indexing. - /// The zero-based index in array at which - /// copying begins. - /// - /// - /// As the collection is empty no values are copied into the array. - /// - /// - public void CopyTo(System.Array array, int index) - { - // copy nothing - } - - /// - /// Gets a value indicating if access to the is synchronized (thread-safe). - /// - /// - /// true if access to the is synchronized (thread-safe); otherwise, false. - /// - /// - /// - /// For the this property is always true. - /// - /// - public bool IsSynchronized - { - get { return true; } - } - - /// - /// Gets the number of elements contained in the . - /// - /// - /// The number of elements contained in the . - /// - /// - /// - /// As the collection is empty the is always 0. - /// - /// - public int Count - { - get { return 0; } - } - - /// - /// Gets an object that can be used to synchronize access to the . - /// - /// - /// An object that can be used to synchronize access to the . - /// - /// - /// - /// As the collection is empty and thread safe and synchronized this instance is also - /// the object. - /// - /// - public object SyncRoot - { - get { return this; } - } - - #endregion Implementation of ICollection - - #region Implementation of IEnumerable - - /// - /// Returns an enumerator that can iterate through a collection. - /// - /// - /// An that can be used to - /// iterate through the collection. - /// - /// - /// - /// As the collection is empty a is returned. - /// - /// - public IEnumerator GetEnumerator() - { - return NullEnumerator.Instance; - } - - #endregion Implementation of IEnumerable - - #region Private Static Fields - - /// - /// The singleton instance of the empty collection. - /// - private readonly static EmptyCollection s_instance = new EmptyCollection(); - - #endregion Private Static Fields - } + public sealed class EmptyCollection : ICollection + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private EmptyCollection() + { + } + + /// + /// Gets the singleton instance of the empty collection. + /// + /// The singleton instance of the empty collection. + /// + /// + /// Gets the singleton instance of the empty collection. + /// + /// + public static EmptyCollection Instance + { + get { return s_instance; } + } + + /// + /// Copies the elements of the to an + /// , starting at a particular Array index. + /// + /// The one-dimensional + /// that is the destination of the elements copied from + /// . The Array must have zero-based + /// indexing. + /// The zero-based index in array at which + /// copying begins. + /// + /// + /// As the collection is empty no values are copied into the array. + /// + /// + public void CopyTo(System.Array array, int index) + { + // copy nothing + } + + /// + /// Gets a value indicating whether gets a value indicating if access to the is synchronized (thread-safe). + /// + /// + /// true if access to the is synchronized (thread-safe); otherwise, false. + /// + /// + /// + /// For the this property is always true. + /// + /// + public bool IsSynchronized + { + get { return true; } + } + + /// + /// Gets the number of elements contained in the . + /// + /// + /// The number of elements contained in the . + /// + /// + /// + /// As the collection is empty the is always 0. + /// + /// + public int Count + { + get { return 0; } + } + + /// + /// Gets an object that can be used to synchronize access to the . + /// + /// + /// An object that can be used to synchronize access to the . + /// + /// + /// + /// As the collection is empty and thread safe and synchronized this instance is also + /// the object. + /// + /// + public object SyncRoot + { + get { return this; } + } + + /// + /// Returns an enumerator that can iterate through a collection. + /// + /// + /// An that can be used to + /// iterate through the collection. + /// + /// + /// + /// As the collection is empty a is returned. + /// + /// + public IEnumerator GetEnumerator() + { + return NullEnumerator.Instance; + } + + /// + /// The singleton instance of the empty collection. + /// + private static readonly EmptyCollection s_instance = new EmptyCollection(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs index 3148e663628..50b34bf626d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs @@ -1,343 +1,316 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the - /// interface that always represents an empty collection. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the + /// interface that always represents an empty collection. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if !NETCF - [Serializable] + [Serializable] #endif - public sealed class EmptyDictionary : IDictionary - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private EmptyDictionary() - { - } - - #endregion Private Instance Constructors - - #region Public Static Properties - - /// - /// Gets the singleton instance of the . - /// - /// The singleton instance of the . - /// - /// - /// Gets the singleton instance of the . - /// - /// - public static EmptyDictionary Instance - { - get { return s_instance; } - } - - #endregion Public Static Properties - - #region Implementation of ICollection - - /// - /// Copies the elements of the to an - /// , starting at a particular Array index. - /// - /// The one-dimensional - /// that is the destination of the elements copied from - /// . The Array must have zero-based - /// indexing. - /// The zero-based index in array at which - /// copying begins. - /// - /// - /// As the collection is empty no values are copied into the array. - /// - /// - public void CopyTo(System.Array array, int index) - { - // copy nothing - } - - /// - /// Gets a value indicating if access to the is synchronized (thread-safe). - /// - /// - /// true if access to the is synchronized (thread-safe); otherwise, false. - /// - /// - /// - /// For the this property is always true. - /// - /// - public bool IsSynchronized - { - get { return true; } - } - - /// - /// Gets the number of elements contained in the - /// - /// - /// The number of elements contained in the . - /// - /// - /// - /// As the collection is empty the is always 0. - /// - /// - public int Count - { - get { return 0; } - } - - /// - /// Gets an object that can be used to synchronize access to the . - /// - /// - /// An object that can be used to synchronize access to the . - /// - /// - /// - /// As the collection is empty and thread safe and synchronized this instance is also - /// the object. - /// - /// - public object SyncRoot - { - get { return this; } - } - - #endregion Implementation of ICollection - - #region Implementation of IEnumerable - - /// - /// Returns an enumerator that can iterate through a collection. - /// - /// - /// An that can be used to - /// iterate through the collection. - /// - /// - /// - /// As the collection is empty a is returned. - /// - /// - IEnumerator IEnumerable.GetEnumerator() - { - return NullEnumerator.Instance; - } - - #endregion Implementation of IEnumerable - - #region Implementation of IDictionary - - /// - /// Adds an element with the provided key and value to the - /// . - /// - /// The to use as the key of the element to add. - /// The to use as the value of the element to add. - /// - /// - /// As the collection is empty no new values can be added. A - /// is thrown if this method is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public void Add(object key, object value) - { - throw new InvalidOperationException(); - } + public sealed class EmptyDictionary : IDictionary + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private EmptyDictionary() + { + } + + /// + /// Gets the singleton instance of the . + /// + /// The singleton instance of the . + /// + /// + /// Gets the singleton instance of the . + /// + /// + public static EmptyDictionary Instance + { + get { return s_instance; } + } + + /// + /// Copies the elements of the to an + /// , starting at a particular Array index. + /// + /// The one-dimensional + /// that is the destination of the elements copied from + /// . The Array must have zero-based + /// indexing. + /// The zero-based index in array at which + /// copying begins. + /// + /// + /// As the collection is empty no values are copied into the array. + /// + /// + public void CopyTo(System.Array array, int index) + { + // copy nothing + } - /// - /// Removes all elements from the . - /// - /// - /// - /// As the collection is empty no values can be removed. A - /// is thrown if this method is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public void Clear() - { - throw new InvalidOperationException(); - } + /// + /// Gets a value indicating whether gets a value indicating if access to the is synchronized (thread-safe). + /// + /// + /// true if access to the is synchronized (thread-safe); otherwise, false. + /// + /// + /// + /// For the this property is always true. + /// + /// + public bool IsSynchronized + { + get { return true; } + } - /// - /// Determines whether the contains an element - /// with the specified key. - /// - /// The key to locate in the . - /// false - /// - /// - /// As the collection is empty the method always returns false. - /// - /// - public bool Contains(object key) - { - return false; - } + /// + /// Gets the number of elements contained in the . + /// + /// + /// The number of elements contained in the . + /// + /// + /// + /// As the collection is empty the is always 0. + /// + /// + public int Count + { + get { return 0; } + } - /// - /// Returns an enumerator that can iterate through a collection. - /// - /// - /// An that can be used to - /// iterate through the collection. - /// - /// - /// - /// As the collection is empty a is returned. - /// - /// - public IDictionaryEnumerator GetEnumerator() - { - return NullDictionaryEnumerator.Instance; - } + /// + /// Gets an object that can be used to synchronize access to the . + /// + /// + /// An object that can be used to synchronize access to the . + /// + /// + /// + /// As the collection is empty and thread safe and synchronized this instance is also + /// the object. + /// + /// + public object SyncRoot + { + get { return this; } + } + + /// + /// Returns an enumerator that can iterate through a collection. + /// + /// + /// An that can be used to + /// iterate through the collection. + /// + /// + /// + /// As the collection is empty a is returned. + /// + /// + IEnumerator IEnumerable.GetEnumerator() + { + return NullEnumerator.Instance; + } + + /// + /// Adds an element with the provided key and value to the + /// . + /// + /// The to use as the key of the element to add. + /// The to use as the value of the element to add. + /// + /// + /// As the collection is empty no new values can be added. A + /// is thrown if this method is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public void Add(object key, object value) + { + throw new InvalidOperationException(); + } - /// - /// Removes the element with the specified key from the . - /// - /// The key of the element to remove. - /// - /// - /// As the collection is empty no values can be removed. A - /// is thrown if this method is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public void Remove(object key) - { - throw new InvalidOperationException(); - } + /// + /// Removes all elements from the . + /// + /// + /// + /// As the collection is empty no values can be removed. A + /// is thrown if this method is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public void Clear() + { + throw new InvalidOperationException(); + } - /// - /// Gets a value indicating whether the has a fixed size. - /// - /// true - /// - /// - /// As the collection is empty always returns true. - /// - /// - public bool IsFixedSize - { - get { return true; } - } + /// + /// Determines whether the contains an element + /// with the specified key. + /// + /// The key to locate in the . + /// false. + /// + /// + /// As the collection is empty the method always returns false. + /// + /// + public bool Contains(object key) + { + return false; + } - /// - /// Gets a value indicating whether the is read-only. - /// - /// true - /// - /// - /// As the collection is empty always returns true. - /// - /// - public bool IsReadOnly - { - get { return true; } - } + /// + /// Returns an enumerator that can iterate through a collection. + /// + /// + /// An that can be used to + /// iterate through the collection. + /// + /// + /// + /// As the collection is empty a is returned. + /// + /// + public IDictionaryEnumerator GetEnumerator() + { + return NullDictionaryEnumerator.Instance; + } - /// - /// Gets an containing the keys of the . - /// - /// An containing the keys of the . - /// - /// - /// As the collection is empty a is returned. - /// - /// - public System.Collections.ICollection Keys - { - get { return EmptyCollection.Instance; } - } + /// + /// Removes the element with the specified key from the . + /// + /// The key of the element to remove. + /// + /// + /// As the collection is empty no values can be removed. A + /// is thrown if this method is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public void Remove(object key) + { + throw new InvalidOperationException(); + } - /// - /// Gets an containing the values of the . - /// - /// An containing the values of the . - /// - /// - /// As the collection is empty a is returned. - /// - /// - public System.Collections.ICollection Values - { - get { return EmptyCollection.Instance; } - } + /// + /// Gets a value indicating whether the has a fixed size. + /// + /// true. + /// + /// + /// As the collection is empty always returns true. + /// + /// + public bool IsFixedSize + { + get { return true; } + } - /// - /// Gets or sets the element with the specified key. - /// - /// The key of the element to get or set. - /// null - /// - /// - /// As the collection is empty no values can be looked up or stored. - /// If the index getter is called then null is returned. - /// A is thrown if the setter is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public object this[object key] - { - get { return null; } - set { throw new InvalidOperationException(); } - } + /// + /// Gets a value indicating whether the is read-only. + /// + /// true. + /// + /// + /// As the collection is empty always returns true. + /// + /// + public bool IsReadOnly + { + get { return true; } + } - #endregion Implementation of IDictionary + /// + /// Gets an containing the keys of the . + /// + /// An containing the keys of the . + /// + /// + /// As the collection is empty a is returned. + /// + /// + public System.Collections.ICollection Keys + { + get { return EmptyCollection.Instance; } + } - #region Private Static Fields + /// + /// Gets an containing the values of the . + /// + /// An containing the values of the . + /// + /// + /// As the collection is empty a is returned. + /// + /// + public System.Collections.ICollection Values + { + get { return EmptyCollection.Instance; } + } - /// - /// The singleton instance of the empty dictionary. - /// - private readonly static EmptyDictionary s_instance = new EmptyDictionary(); - - #endregion Private Static Fields - } + /// + /// Gets or sets the element with the specified key. + /// + /// The key of the element to get or set. + /// null. + /// + /// + /// As the collection is empty no values can be looked up or stored. + /// If the index getter is called then null is returned. + /// A is thrown if the setter is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public object this[object key] + { + get { return null; } + set { throw new InvalidOperationException(); } + } + + /// + /// The singleton instance of the empty dictionary. + /// + private static readonly EmptyDictionary s_instance = new EmptyDictionary(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs index fb6edd8d060..3eb6aa38a86 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs @@ -1,140 +1,128 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Contain the information obtained when parsing formatting modifiers - /// in conversion modifiers. - /// - /// - /// - /// Holds the formatting information extracted from the format string by - /// the . This is used by the - /// objects when rendering the output. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class FormattingInfo - { - #region Public Instance Constructors - - /// - /// Defaut Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public FormattingInfo() - { - } - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class - /// with the specified parameters. - /// - /// - public FormattingInfo(int min, int max, bool leftAlign) - { - m_min = min; - m_max = max; - m_leftAlign = leftAlign; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the minimum value. - /// - /// - /// The minimum value. - /// - /// - /// - /// Gets or sets the minimum value. - /// - /// - public int Min - { - get { return m_min; } - set { m_min = value; } - } - - /// - /// Gets or sets the maximum value. - /// - /// - /// The maximum value. - /// - /// - /// - /// Gets or sets the maximum value. - /// - /// - public int Max - { - get { return m_max; } - set { m_max = value; } - } - - /// - /// Gets or sets a flag indicating whether left align is enabled - /// or not. - /// - /// - /// A flag indicating whether left align is enabled or not. - /// - /// - /// - /// Gets or sets a flag indicating whether left align is enabled or not. - /// - /// - public bool LeftAlign - { - get { return m_leftAlign; } - set { m_leftAlign = value; } - } - - #endregion Public Instance Properties - - #region Private Instance Fields + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Util; + + /// + /// Contain the information obtained when parsing formatting modifiers + /// in conversion modifiers. + /// + /// + /// + /// Holds the formatting information extracted from the format string by + /// the . This is used by the + /// objects when rendering the output. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class FormattingInfo + { + /// + /// Initializes a new instance of the class. + /// Defaut Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public FormattingInfo() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class + /// with the specified parameters. + /// + /// + public FormattingInfo(int min, int max, bool leftAlign) + { + this.m_min = min; + this.m_max = max; + this.m_leftAlign = leftAlign; + } + + /// + /// Gets or sets the minimum value. + /// + /// + /// The minimum value. + /// + /// + /// + /// Gets or sets the minimum value. + /// + /// + public int Min + { + get { return this.m_min; } + set { this.m_min = value; } + } - private int m_min = -1; - private int m_max = int.MaxValue; - private bool m_leftAlign = false; + /// + /// Gets or sets the maximum value. + /// + /// + /// The maximum value. + /// + /// + /// + /// Gets or sets the maximum value. + /// + /// + public int Max + { + get { return this.m_max; } + set { this.m_max = value; } + } - #endregion Private Instance Fields - } + /// + /// Gets or sets a value indicating whether gets or sets a flag indicating whether left align is enabled + /// or not. + /// + /// + /// A flag indicating whether left align is enabled or not. + /// + /// + /// + /// Gets or sets a flag indicating whether left align is enabled or not. + /// + /// + public bool LeftAlign + { + get { return this.m_leftAlign; } + set { this.m_leftAlign = value; } + } + + private int m_min = -1; + private int m_max = int.MaxValue; + private bool m_leftAlign = false; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs index 3ef03af9b93..7da9da0dd3a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs @@ -1,181 +1,159 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Implementation of Properties collection for the - /// - /// - /// - /// This class implements a properties collection that is thread safe and supports both - /// storing properties and capturing a read only copy of the current propertied. - /// - /// - /// This class is optimized to the scenario where the properties are read frequently - /// and are modified infrequently. - /// - /// - /// Nicko Cadell - public sealed class GlobalContextProperties : ContextPropertiesBase - { - #region Private Instance Fields - - /// - /// The read only copy of the properties. - /// - /// - /// - /// This variable is declared volatile to prevent the compiler and JIT from - /// reordering reads and writes of this thread performed on different threads. - /// - /// + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// Implementation of Properties collection for the . + /// + /// + /// + /// This class implements a properties collection that is thread safe and supports both + /// storing properties and capturing a read only copy of the current propertied. + /// + /// + /// This class is optimized to the scenario where the properties are read frequently + /// and are modified infrequently. + /// + /// + /// Nicko Cadell. + public sealed class GlobalContextProperties : ContextPropertiesBase + { + /// + /// The read only copy of the properties. + /// + /// + /// + /// This variable is declared volatile to prevent the compiler and JIT from + /// reordering reads and writes of this thread performed on different threads. + /// + /// #if NETCF private ReadOnlyPropertiesDictionary m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); #else - private volatile ReadOnlyPropertiesDictionary m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); + private volatile ReadOnlyPropertiesDictionary m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); #endif - /// - /// Lock object used to synchronize updates within this instance - /// - private readonly object m_syncRoot = new object(); - - #endregion Private Instance Fields - - #region Public Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal GlobalContextProperties() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the value of a property - /// - /// - /// The value for the property with the specified key - /// - /// - /// - /// Reading the value for a key is faster than setting the value. - /// When the value is written a new read only copy of - /// the properties is created. - /// - /// - override public object this[string key] - { - get - { - return m_readOnlyProperties[key]; - } - set - { - lock(m_syncRoot) - { - PropertiesDictionary mutableProps = new PropertiesDictionary(m_readOnlyProperties); - - mutableProps[key] = value; - - m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); - } - } - } - - #endregion Public Instance Properties - - #region Public Instance Methods - - /// - /// Remove a property from the global context - /// - /// the key for the entry to remove - /// - /// - /// Removing an entry from the global context properties is relatively expensive compared - /// with reading a value. - /// - /// - public void Remove(string key) - { - lock(m_syncRoot) - { - if (m_readOnlyProperties.Contains(key)) - { - PropertiesDictionary mutableProps = new PropertiesDictionary(m_readOnlyProperties); - - mutableProps.Remove(key); - - m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); - } - } - } - - /// - /// Clear the global context properties - /// - public void Clear() - { - lock(m_syncRoot) - { - m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); - } - } - - #endregion Public Instance Methods - - #region Internal Instance Methods - - /// - /// Get a readonly immutable copy of the properties - /// - /// the current global context properties - /// - /// - /// This implementation is fast because the GlobalContextProperties class - /// stores a readonly copy of the properties. - /// - /// - internal ReadOnlyPropertiesDictionary GetReadOnlyProperties() - { - return m_readOnlyProperties; - } - - #endregion Internal Instance Methods - } -} - + /// + /// Lock object used to synchronize updates within this instance. + /// + private readonly object m_syncRoot = new object(); + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal GlobalContextProperties() + { + } + + /// + /// Gets or sets the value of a property. + /// + /// + /// The value for the property with the specified key. + /// + /// + /// + /// Reading the value for a key is faster than setting the value. + /// When the value is written a new read only copy of + /// the properties is created. + /// + /// + public override object this[string key] + { + get + { + return this.m_readOnlyProperties[key]; + } + + set + { + lock (this.m_syncRoot) + { + PropertiesDictionary mutableProps = new PropertiesDictionary(this.m_readOnlyProperties); + + mutableProps[key] = value; + + this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); + } + } + } + + /// + /// Remove a property from the global context. + /// + /// the key for the entry to remove. + /// + /// + /// Removing an entry from the global context properties is relatively expensive compared + /// with reading a value. + /// + /// + public void Remove(string key) + { + lock (this.m_syncRoot) + { + if (this.m_readOnlyProperties.Contains(key)) + { + PropertiesDictionary mutableProps = new PropertiesDictionary(this.m_readOnlyProperties); + + mutableProps.Remove(key); + + this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); + } + } + } + + /// + /// Clear the global context properties. + /// + public void Clear() + { + lock (this.m_syncRoot) + { + this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); + } + } + + /// + /// Get a readonly immutable copy of the properties. + /// + /// the current global context properties. + /// + /// + /// This implementation is fast because the GlobalContextProperties class + /// stores a readonly copy of the properties. + /// + /// + internal ReadOnlyPropertiesDictionary GetReadOnlyProperties() + { + return this.m_readOnlyProperties; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs index 4c8220bcbbf..b748a823931 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,1727 +18,1731 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - #if NET_3_5 || NET_4_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3 using System; - + using log4net.Core; namespace log4net.Util { - /// - /// The static class ILogExtensions contains a set of widely used - /// methods that ease the interaction with the ILog interface implementations. - /// - /// - /// - /// This class contains methods for logging at different levels and checks the - /// properties for determining if those logging levels are enabled in the current - /// configuration. - /// - /// - /// Simple example of logging messages - /// - /// using log4net.Util; - /// - /// ILog log = LogManager.GetLogger("application-log"); - /// - /// log.InfoExt("Application Start"); - /// log.DebugExt("This is a debug message"); - /// - /// - public static class ILogExtensions - { - #region Private Static Fields - - /// - /// The fully qualified type of the Logger class. - /// - private readonly static Type declaringType = typeof(ILogExtensions); - - #endregion //Private Static Fields - - #region debug extensions - - #region debug extensions that uses log message lambda expression - - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, Func callback) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.Debug(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, Func callback, Exception exception) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.Debug(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region debug extension that use the formatter - - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, object message) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.Debug(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, object message, Exception exception) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.Debug(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region debug extension that use string format - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, object arg0) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.DebugFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, params object[] args) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.DebugFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.DebugFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.DebugFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { - if (!logger.IsDebugEnabled) - return; - - logger.DebugFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #endregion - - #region info extensions - - #region info extensions that uses log message lambda expression - - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, Func callback) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.Info(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, Func callback, Exception exception) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.Info(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region info extension that use the formatter - - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, object message) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.Info(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, object message, Exception exception) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.Info(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region info extension that use string format - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, object arg0) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.InfoFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, params object[] args) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.InfoFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.InfoFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.InfoFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { - if (!logger.IsInfoEnabled) - return; - - logger.InfoFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #endregion - - #region warn extensions - - #region warn extensions that uses log message lambda expression - - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is WARN - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is WARN enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, Func callback) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.Warn(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, Func callback, Exception exception) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.Warn(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region warn extension that use the formatter - - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is WARN - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is WARN enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, object message) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.Warn(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, object message, Exception exception) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.Warn(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region warn extension that use string format - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, object arg0) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.WarnFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, params object[] args) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.WarnFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.WarnFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.WarnFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { - if (!logger.IsWarnEnabled) - return; - - logger.WarnFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #endregion - - #region error extensions - - #region error extensions that uses log message lambda expression - - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is ERROR enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, Func callback) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.Error(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, Func callback, Exception exception) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.Error(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region error extension that use the formatter - - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is ERROR enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, object message) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.Error(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, object message, Exception exception) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.Error(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region error extension that use string format - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, object arg0) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.ErrorFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, params object[] args) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.ErrorFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.ErrorFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.ErrorFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { - if (!logger.IsErrorEnabled) - return; - - logger.ErrorFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #endregion - - #region fatal extensions - - #region fatal extensions that uses log message lambda expression - - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is FATAL enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, Func callback) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.Fatal(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, Func callback, Exception exception) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.Fatal(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region fatal extension that use the formatter - - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is FATAL enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, object message) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.Fatal(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, object message, Exception exception) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.Fatal(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #region fatal extension that use string format - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, object arg0) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.FatalFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, params object[] args) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.FatalFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object array containing zero or more objects to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.FatalFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.FatalFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items - /// An Object to format - /// An Object to format - /// An Object to format - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { - if (!logger.IsFatalEnabled) - return; - - logger.FatalFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - #endregion - - #endregion - } + /// + /// The static class ILogExtensions contains a set of widely used + /// methods that ease the interaction with the ILog interface implementations. + /// + /// + /// + /// This class contains methods for logging at different levels and checks the + /// properties for determining if those logging levels are enabled in the current + /// configuration. + /// + /// + /// Simple example of logging messages. + /// + /// using log4net.Util; + /// + /// ILog log = LogManager.GetLogger("application-log"); + /// + /// log.InfoExt("Application Start"); + /// log.DebugExt("This is a debug message"); + /// + /// + public static class ILogExtensions + { + /// + /// The fully qualified type of the Logger class. + /// + private static readonly Type declaringType = typeof(ILogExtensions); + + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, Func callback) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.Debug(callback()); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, Func callback, Exception exception) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.Debug(callback(), exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, object message) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.Debug(message); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, object message, Exception exception) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.Debug(message, exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, object arg0) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.DebugFormat(format, arg0); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, params object[] args) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.DebugFormat(format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.DebugFormat(provider, format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.DebugFormat(format, arg0, arg1); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { + if (!logger.IsDebugEnabled) + { + return; + } + + logger.DebugFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, Func callback) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.Info(callback()); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, Func callback, Exception exception) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.Info(callback(), exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, object message) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.Info(message); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, object message, Exception exception) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.Info(message, exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, object arg0) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.InfoFormat(format, arg0); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, params object[] args) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.InfoFormat(format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.InfoFormat(provider, format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.InfoFormat(format, arg0, arg1); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { + if (!logger.IsInfoEnabled) + { + return; + } + + logger.InfoFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is WARN + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is WARN enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, Func callback) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.Warn(callback()); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, Func callback, Exception exception) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.Warn(callback(), exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is WARN + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is WARN enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, object message) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.Warn(message); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, object message, Exception exception) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.Warn(message, exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, object arg0) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.WarnFormat(format, arg0); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, params object[] args) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.WarnFormat(format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.WarnFormat(provider, format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.WarnFormat(format, arg0, arg1); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { + if (!logger.IsWarnEnabled) + { + return; + } + + logger.WarnFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is ERROR enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, Func callback) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.Error(callback()); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, Func callback, Exception exception) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.Error(callback(), exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is ERROR enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, object message) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.Error(message); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, object message, Exception exception) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.Error(message, exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, object arg0) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.ErrorFormat(format, arg0); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, params object[] args) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.ErrorFormat(format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.ErrorFormat(provider, format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.ErrorFormat(format, arg0, arg1); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { + if (!logger.IsErrorEnabled) + { + return; + } + + logger.ErrorFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is FATAL enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, Func callback) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.Fatal(callback()); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, Func callback, Exception exception) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.Fatal(callback(), exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is FATAL enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, object message) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.Fatal(message); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, object message, Exception exception) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.Fatal(message, exception); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, object arg0) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.FatalFormat(format, arg0); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, params object[] args) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.FatalFormat(format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information. + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object array containing zero or more objects to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.FatalFormat(provider, format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.FatalFormat(format, arg0, arg1); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items. + /// An Object to format. + /// An Object to format. + /// An Object to format. + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { + if (!logger.IsFatalEnabled) + { + return; + } + + logger.FatalFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); + } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs index 06ccba1ee9f..fafd53c36f4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs @@ -1,154 +1,138 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Manages a mapping from levels to - /// - /// - /// - /// Manages an ordered mapping from instances - /// to subclasses. - /// - /// - /// Nicko Cadell - public sealed class LevelMapping : IOptionHandler - { - #region Public Instance Constructors - - /// - /// Default constructor - /// - /// - /// - /// Initialise a new instance of . - /// - /// - public LevelMapping() - { - } - - #endregion // Public Instance Constructors - - #region Public Instance Methods - - /// - /// Add a to this mapping - /// - /// the entry to add - /// - /// - /// If a has previously been added - /// for the same then that entry will be - /// overwritten. - /// - /// - public void Add(LevelMappingEntry entry) - { - if (m_entriesMap.ContainsKey(entry.Level)) - { - m_entriesMap.Remove(entry.Level); - } - m_entriesMap.Add(entry.Level, entry); - } - - /// - /// Lookup the mapping for the specified level - /// - /// the level to lookup - /// the for the level or null if no mapping found - /// - /// - /// Lookup the value for the specified level. Finds the nearest - /// mapping value for the level that is equal to or less than the - /// specified. - /// - /// - /// If no mapping could be found then null is returned. - /// - /// - public LevelMappingEntry Lookup(Level level) - { - if (m_entries != null) - { - foreach(LevelMappingEntry entry in m_entries) - { - if (level >= entry.Level) - { - return entry; - } - } - } - return null; - } - - #endregion // Public Instance Methods - - #region IOptionHandler Members - - /// - /// Initialize options - /// - /// - /// - /// Caches the sorted list of in an array - /// - /// - public void ActivateOptions() - { - Level[] sortKeys = new Level[m_entriesMap.Count]; - LevelMappingEntry[] sortValues = new LevelMappingEntry[m_entriesMap.Count]; - - m_entriesMap.Keys.CopyTo(sortKeys, 0); - m_entriesMap.Values.CopyTo(sortValues, 0); - - // Sort in level order - Array.Sort(sortKeys, sortValues, 0, sortKeys.Length, null); - - // Reverse list so that highest level is first - Array.Reverse(sortValues, 0, sortValues.Length); - - foreach(LevelMappingEntry entry in sortValues) - { - entry.ActivateOptions(); - } - - m_entries = sortValues; - } - - #endregion // IOptionHandler Members - - #region Private Instance Fields - - private Hashtable m_entriesMap = new Hashtable(); - private LevelMappingEntry[] m_entries = null; - - #endregion // Private Instance Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Core; + + /// + /// Manages a mapping from levels to . + /// + /// + /// + /// Manages an ordered mapping from instances + /// to subclasses. + /// + /// + /// Nicko Cadell. + public sealed class LevelMapping : IOptionHandler + { + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Initialise a new instance of . + /// + /// + public LevelMapping() + { + } + + /// + /// Add a to this mapping. + /// + /// the entry to add. + /// + /// + /// If a has previously been added + /// for the same then that entry will be + /// overwritten. + /// + /// + public void Add(LevelMappingEntry entry) + { + if (this.m_entriesMap.ContainsKey(entry.Level)) + { + this.m_entriesMap.Remove(entry.Level); + } + + this.m_entriesMap.Add(entry.Level, entry); + } + + /// + /// Lookup the mapping for the specified level. + /// + /// the level to lookup. + /// the for the level or null if no mapping found. + /// + /// + /// Lookup the value for the specified level. Finds the nearest + /// mapping value for the level that is equal to or less than the + /// specified. + /// + /// + /// If no mapping could be found then null is returned. + /// + /// + public LevelMappingEntry Lookup(Level level) + { + if (this.m_entries != null) + { + foreach (LevelMappingEntry entry in this.m_entries) + { + if (level >= entry.Level) + { + return entry; + } + } + } + + return null; + } + + /// + /// Initialize options. + /// + /// + /// + /// Caches the sorted list of in an array. + /// + /// + public void ActivateOptions() + { + Level[] sortKeys = new Level[this.m_entriesMap.Count]; + LevelMappingEntry[] sortValues = new LevelMappingEntry[this.m_entriesMap.Count]; + + this.m_entriesMap.Keys.CopyTo(sortKeys, 0); + this.m_entriesMap.Values.CopyTo(sortValues, 0); + + // Sort in level order + Array.Sort(sortKeys, sortValues, 0, sortKeys.Length, null); + + // Reverse list so that highest level is first + Array.Reverse(sortValues, 0, sortValues.Length); + + foreach (LevelMappingEntry entry in sortValues) + { + entry.ActivateOptions(); + } + + this.m_entries = sortValues; + } + + private Hashtable m_entriesMap = new Hashtable(); + private LevelMappingEntry[] m_entries = null; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs index 35dc43709c5..2e08dec9d00 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs @@ -1,104 +1,86 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// An entry in the - /// - /// - /// - /// This is an abstract base class for types that are stored in the - /// object. - /// - /// - /// Nicko Cadell - public abstract class LevelMappingEntry : IOptionHandler - { - #region Public Instance Constructors - - /// - /// Default protected constructor - /// - /// - /// - /// Default protected constructor - /// - /// - protected LevelMappingEntry() - { - } - - #endregion // Public Instance Constructors - - #region Public Instance Properties - - /// - /// The level that is the key for this mapping - /// - /// - /// The that is the key for this mapping - /// - /// - /// - /// Get or set the that is the key for this - /// mapping subclass. - /// - /// - public Level Level - { - get { return m_level; } - set { m_level = value; } - } - - #endregion // Public Instance Properties - - #region IOptionHandler Members - - /// - /// Initialize any options defined on this entry - /// - /// - /// - /// Should be overridden by any classes that need to initialise based on their options - /// - /// - virtual public void ActivateOptions() - { - // default implementation is to do nothing - } - - #endregion // IOptionHandler Members - - #region Private Instance Fields - - private Level m_level; - - #endregion // Private Instance Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + using log4net.Core; + + /// + /// An entry in the . + /// + /// + /// + /// This is an abstract base class for types that are stored in the + /// object. + /// + /// + /// Nicko Cadell. + public abstract class LevelMappingEntry : IOptionHandler + { + /// + /// Initializes a new instance of the class. + /// Default protected constructor. + /// + /// + /// + /// Default protected constructor. + /// + /// + protected LevelMappingEntry() + { + } + + /// + /// Gets or sets the level that is the key for this mapping. + /// + /// + /// The that is the key for this mapping. + /// + /// + /// + /// Get or set the that is the key for this + /// mapping subclass. + /// + /// + public Level Level + { + get { return this.m_level; } + set { this.m_level = value; } + } + + /// + /// Initialize any options defined on this entry. + /// + /// + /// + /// Should be overridden by any classes that need to initialise based on their options. + /// + /// + public virtual void ActivateOptions() + { + // default implementation is to do nothing + } + + private Level m_level; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs index d6bb3f1a380..934659e380a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs @@ -1,61 +1,60 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if !NETSTANDARD1_3 using System.Configuration; + #endif using System.Diagnostics; namespace log4net.Util { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + /// - /// + /// /// /// /// public delegate void LogReceivedEventHandler(object source, LogReceivedEventArgs e); - /// - /// Outputs log statements from within the log4net assembly. - /// - /// - /// - /// Log4net components cannot make log4net logging calls. However, it is - /// sometimes useful for the user to learn about what log4net is - /// doing. - /// - /// - /// All log4net internal debug calls go to the standard output stream - /// whereas internal error messages are sent to the standard error output - /// stream. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class LogLog - { + /// + /// Outputs log statements from within the log4net assembly. + /// + /// + /// + /// Log4net components cannot make log4net logging calls. However, it is + /// sometimes useful for the user to learn about what log4net is + /// doing. + /// + /// + /// All log4net internal debug calls go to the standard output stream + /// whereas internal error messages are sent to the standard error output + /// stream. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class LogLog + { /// /// The event raised when an internal message has been received. /// @@ -68,230 +67,217 @@ public sealed class LogLog private readonly Exception exception; /// - /// The Type that generated the internal message. + /// Gets the Type that generated the internal message. /// - public Type Source - { - get { return source; } - } + public Type Source + { + get { return this.source; } + } /// - /// The DateTime stamp of when the internal message was received. + /// Gets the DateTime stamp of when the internal message was received. /// - public DateTime TimeStamp - { - get { return timeStampUtc.ToLocalTime(); } - } + public DateTime TimeStamp + { + get { return this.timeStampUtc.ToLocalTime(); } + } /// - /// The UTC DateTime stamp of when the internal message was received. + /// Gets the UTC DateTime stamp of when the internal message was received. /// public DateTime TimeStampUtc { - get { return timeStampUtc; } - } + get { return this.timeStampUtc; } + } /// - /// A string indicating the severity of the internal message. + /// Gets a string indicating the severity of the internal message. /// /// - /// "log4net: ", - /// "log4net:ERROR ", - /// "log4net:WARN " + /// "log4net: ", + /// "log4net:ERROR ", + /// "log4net:WARN ". /// - public string Prefix - { - get { return prefix; } - } + public string Prefix + { + get { return this.prefix; } + } /// - /// The internal log message. + /// Gets the internal log message. /// - public string Message - { - get { return message; } - } + public string Message + { + get { return this.message; } + } /// - /// The Exception related to the message. + /// Gets the Exception related to the message. /// /// /// Optional. Will be null if no Exception was passed. /// - public Exception Exception - { - get { return exception; } - } + public Exception Exception + { + get { return this.exception; } + } /// /// Formats Prefix, Source, and Message in the same format as the value /// sent to Console.Out and Trace.Write. /// /// - public override string ToString() - { - return Prefix + Source.Name + ": " + Message; - } - - #region Private Instance Constructors - + public override string ToString() + { + return this.Prefix + this.Source.Name + ": " + this.Message; + } + /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// /// /// /// - public LogLog(Type source, string prefix, string message, Exception exception) - { - timeStampUtc = DateTime.UtcNow; - + public LogLog(Type source, string prefix, string message, Exception exception) + { + this.timeStampUtc = DateTime.UtcNow; + this.source = source; - this.prefix = prefix; - this.message = message; - this.exception = exception; - } - - #endregion Private Instance Constructors - - #region Static Constructor - - /// - /// Static constructor that initializes logging by reading - /// settings from the application configuration file. - /// - /// - /// - /// The log4net.Internal.Debug application setting - /// controls internal debugging. This setting should be set - /// to true to enable debugging. - /// - /// - /// The log4net.Internal.Quiet application setting - /// suppresses all internal logging including error messages. - /// This setting should be set to true to enable message - /// suppression. - /// - /// - static LogLog() - { + this.prefix = prefix; + this.message = message; + this.exception = exception; + } + + /// + /// Initializes static members of the class. + /// Static constructor that initializes logging by reading + /// settings from the application configuration file. + /// + /// + /// + /// The log4net.Internal.Debug application setting + /// controls internal debugging. This setting should be set + /// to true to enable debugging. + /// + /// + /// The log4net.Internal.Quiet application setting + /// suppresses all internal logging including error messages. + /// This setting should be set to true to enable message + /// suppression. + /// + /// + static LogLog() + { #if !NETCF - try - { - InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false); - QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false); - EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Emit"), true); - } - catch(Exception ex) - { - // If an exception is thrown here then it looks like the config file does not - // parse correctly. - // - // We will leave debug OFF and print an Error message - Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); - } + try + { + InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false); + QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false); + EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Emit"), true); + } + catch (Exception ex) + { + // If an exception is thrown here then it looks like the config file does not + // parse correctly. + // + // We will leave debug OFF and print an Error message + Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); + } #endif - } - - #endregion Static Constructor - - #region Public Static Properties - - /// - /// Gets or sets a value indicating whether log4net internal logging - /// is enabled or disabled. - /// - /// - /// true if log4net internal logging is enabled, otherwise - /// false. - /// - /// - /// - /// When set to true, internal debug level logging will be - /// displayed. - /// - /// - /// This value can be set by setting the application setting - /// log4net.Internal.Debug in the application configuration - /// file. - /// - /// - /// The default value is false, i.e. debugging is - /// disabled. - /// - /// - /// - /// - /// The following example enables internal debugging using the - /// application configuration file : - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static bool InternalDebugging - { - get { return s_debugEnabled; } - set { s_debugEnabled = value; } - } - - /// - /// Gets or sets a value indicating whether log4net should generate no output - /// from internal logging, not even for errors. - /// - /// - /// true if log4net should generate no output at all from internal - /// logging, otherwise false. - /// - /// - /// - /// When set to true will cause internal logging at all levels to be - /// suppressed. This means that no warning or error reports will be logged. - /// This option overrides the setting and - /// disables all debug also. - /// - /// This value can be set by setting the application setting - /// log4net.Internal.Quiet in the application configuration file. - /// - /// - /// The default value is false, i.e. internal logging is not - /// disabled. - /// - /// - /// - /// The following example disables internal logging using the - /// application configuration file : - /// - /// - /// - /// - /// - /// - /// - /// - public static bool QuietMode - { - get { return s_quietMode; } - set { s_quietMode = value; } - } + } + + /// + /// Gets or sets a value indicating whether log4net internal logging + /// is enabled or disabled. + /// + /// + /// true if log4net internal logging is enabled, otherwise + /// false. + /// + /// + /// + /// When set to true, internal debug level logging will be + /// displayed. + /// + /// + /// This value can be set by setting the application setting + /// log4net.Internal.Debug in the application configuration + /// file. + /// + /// + /// The default value is false, i.e. debugging is + /// disabled. + /// + /// + /// + /// + /// The following example enables internal debugging using the + /// application configuration file : + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool InternalDebugging + { + get { return s_debugEnabled; } + set { s_debugEnabled = value; } + } + + /// + /// Gets or sets a value indicating whether log4net should generate no output + /// from internal logging, not even for errors. + /// + /// + /// true if log4net should generate no output at all from internal + /// logging, otherwise false. + /// + /// + /// + /// When set to true will cause internal logging at all levels to be + /// suppressed. This means that no warning or error reports will be logged. + /// This option overrides the setting and + /// disables all debug also. + /// + /// This value can be set by setting the application setting + /// log4net.Internal.Quiet in the application configuration file. + /// + /// + /// The default value is false, i.e. internal logging is not + /// disabled. + /// + /// + /// + /// The following example disables internal logging using the + /// application configuration file : + /// + /// + /// + /// + /// + /// + /// + /// + public static bool QuietMode + { + get { return s_quietMode; } + set { s_quietMode = value; } + } /// - /// + /// /// public static bool EmitInternalMessages { get { return s_emitInternalMessages; } set { s_emitInternalMessages = value; } - } - - #endregion Public Static Properties - - #region Public Static Methods - + } + /// /// Raises the LogReceived event when an internal messages is received. /// @@ -307,64 +293,64 @@ public static void OnLogReceived(Type source, string prefix, string message, Exc } } - /// - /// Test if LogLog.Debug is enabled for output. - /// - /// - /// true if Debug is enabled - /// - /// - /// - /// Test if LogLog.Debug is enabled for output. - /// - /// - public static bool IsDebugEnabled - { - get { return s_debugEnabled && !s_quietMode; } - } - - /// - /// Writes log4net internal debug messages to the - /// standard output stream. - /// + /// + /// Gets a value indicating whether test if LogLog.Debug is enabled for output. + /// + /// + /// true if Debug is enabled. + /// + /// + /// + /// Test if LogLog.Debug is enabled for output. + /// + /// + public static bool IsDebugEnabled + { + get { return s_debugEnabled && !s_quietMode; } + } + + /// + /// Writes log4net internal debug messages to the + /// standard output stream. + /// /// - /// The message to log. - /// - /// - /// All internal debug messages are prepended with - /// the string "log4net: ". - /// - /// - public static void Debug(Type source, string message) - { - if (IsDebugEnabled) - { + /// The message to log. + /// + /// + /// All internal debug messages are prepended with + /// the string "log4net: ". + /// + /// + public static void Debug(Type source, string message) + { + if (IsDebugEnabled) + { if (EmitInternalMessages) { EmitOutLine(PREFIX + message); } OnLogReceived(source, PREFIX, message, null); - } - } + } + } - /// - /// Writes log4net internal debug messages to the - /// standard output stream. - /// + /// + /// Writes log4net internal debug messages to the + /// standard output stream. + /// /// The Type that generated this message. - /// The message to log. - /// An exception to log. - /// - /// - /// All internal debug messages are prepended with - /// the string "log4net: ". - /// - /// - public static void Debug(Type source, string message, Exception exception) - { - if (IsDebugEnabled) - { + /// The message to log. + /// An exception to log. + /// + /// + /// All internal debug messages are prepended with + /// the string "log4net: ". + /// + /// + public static void Debug(Type source, string message, Exception exception) + { + if (IsDebugEnabled) + { if (EmitInternalMessages) { EmitOutLine(PREFIX + message); @@ -375,67 +361,67 @@ public static void Debug(Type source, string message, Exception exception) } OnLogReceived(source, PREFIX, message, exception); - } - } - - /// - /// Test if LogLog.Warn is enabled for output. - /// - /// - /// true if Warn is enabled - /// - /// - /// - /// Test if LogLog.Warn is enabled for output. - /// - /// - public static bool IsWarnEnabled - { - get { return !s_quietMode; } - } - - /// - /// Writes log4net internal warning messages to the - /// standard error stream. - /// + } + } + + /// + /// Gets a value indicating whether test if LogLog.Warn is enabled for output. + /// + /// + /// true if Warn is enabled. + /// + /// + /// + /// Test if LogLog.Warn is enabled for output. + /// + /// + public static bool IsWarnEnabled + { + get { return !s_quietMode; } + } + + /// + /// Writes log4net internal warning messages to the + /// standard error stream. + /// /// The Type that generated this message. - /// The message to log. - /// - /// - /// All internal warning messages are prepended with - /// the string "log4net:WARN ". - /// - /// - public static void Warn(Type source, string message) - { - if (IsWarnEnabled) - { + /// The message to log. + /// + /// + /// All internal warning messages are prepended with + /// the string "log4net:WARN ". + /// + /// + public static void Warn(Type source, string message) + { + if (IsWarnEnabled) + { if (EmitInternalMessages) { EmitErrorLine(WARN_PREFIX + message); } OnLogReceived(source, WARN_PREFIX, message, null); - } - } + } + } - /// - /// Writes log4net internal warning messages to the - /// standard error stream. - /// + /// + /// Writes log4net internal warning messages to the + /// standard error stream. + /// /// The Type that generated this message. - /// The message to log. - /// An exception to log. - /// - /// - /// All internal warning messages are prepended with - /// the string "log4net:WARN ". - /// - /// - public static void Warn(Type source, string message, Exception exception) - { - if (IsWarnEnabled) - { + /// The message to log. + /// An exception to log. + /// + /// + /// All internal warning messages are prepended with + /// the string "log4net:WARN ". + /// + /// + public static void Warn(Type source, string message, Exception exception) + { + if (IsWarnEnabled) + { if (EmitInternalMessages) { EmitErrorLine(WARN_PREFIX + message); @@ -446,67 +432,67 @@ public static void Warn(Type source, string message, Exception exception) } OnLogReceived(source, WARN_PREFIX, message, exception); - } - } - - /// - /// Test if LogLog.Error is enabled for output. - /// - /// - /// true if Error is enabled - /// - /// - /// - /// Test if LogLog.Error is enabled for output. - /// - /// - public static bool IsErrorEnabled - { - get { return !s_quietMode; } - } - - /// - /// Writes log4net internal error messages to the - /// standard error stream. - /// + } + } + + /// + /// Gets a value indicating whether test if LogLog.Error is enabled for output. + /// + /// + /// true if Error is enabled. + /// + /// + /// + /// Test if LogLog.Error is enabled for output. + /// + /// + public static bool IsErrorEnabled + { + get { return !s_quietMode; } + } + + /// + /// Writes log4net internal error messages to the + /// standard error stream. + /// /// The Type that generated this message. - /// The message to log. - /// - /// - /// All internal error messages are prepended with - /// the string "log4net:ERROR ". - /// - /// - public static void Error(Type source, string message) - { - if (IsErrorEnabled) - { + /// The message to log. + /// + /// + /// All internal error messages are prepended with + /// the string "log4net:ERROR ". + /// + /// + public static void Error(Type source, string message) + { + if (IsErrorEnabled) + { if (EmitInternalMessages) { EmitErrorLine(ERR_PREFIX + message); } OnLogReceived(source, ERR_PREFIX, message, null); - } - } + } + } - /// - /// Writes log4net internal error messages to the - /// standard error stream. - /// + /// + /// Writes log4net internal error messages to the + /// standard error stream. + /// /// The Type that generated this message. - /// The message to log. - /// An exception to log. - /// - /// - /// All internal debug messages are prepended with - /// the string "log4net:ERROR ". - /// - /// - public static void Error(Type source, string message, Exception exception) - { - if (IsErrorEnabled) - { + /// The message to log. + /// An exception to log. + /// + /// + /// All internal debug messages are prepended with + /// the string "log4net:ERROR ". + /// + /// + public static void Error(Type source, string message, Exception exception) + { + if (IsErrorEnabled) + { if (EmitInternalMessages) { EmitErrorLine(ERR_PREFIX + message); @@ -517,99 +503,93 @@ public static void Error(Type source, string message, Exception exception) } OnLogReceived(source, ERR_PREFIX, message, exception); - } - } - - #endregion Public Static Methods - - /// - /// Writes output to the standard output stream. - /// - /// The message to log. - /// - /// - /// Writes to both Console.Out and System.Diagnostics.Trace. - /// Note that the System.Diagnostics.Trace is not supported - /// on the Compact Framework. - /// - /// - /// If the AppDomain is not configured with a config file then - /// the call to System.Diagnostics.Trace may fail. This is only - /// an issue if you are programmatically creating your own AppDomains. - /// - /// - private static void EmitOutLine(string message) - { - try - { + } + } + + /// + /// Writes output to the standard output stream. + /// + /// The message to log. + /// + /// + /// Writes to both Console.Out and System.Diagnostics.Trace. + /// Note that the System.Diagnostics.Trace is not supported + /// on the Compact Framework. + /// + /// + /// If the AppDomain is not configured with a config file then + /// the call to System.Diagnostics.Trace may fail. This is only + /// an issue if you are programmatically creating your own AppDomains. + /// + /// + private static void EmitOutLine(string message) + { + try + { #if NETCF Console.WriteLine(message); //System.Diagnostics.Debug.WriteLine(message); #else - Console.Out.WriteLine(message); - Trace.WriteLine(message); + Console.Out.WriteLine(message); + Trace.WriteLine(message); #endif - } - catch - { - // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller - } - } - - /// - /// Writes output to the standard error stream. - /// - /// The message to log. - /// - /// - /// Writes to both Console.Error and System.Diagnostics.Trace. - /// Note that the System.Diagnostics.Trace is not supported - /// on the Compact Framework. - /// - /// - /// If the AppDomain is not configured with a config file then - /// the call to System.Diagnostics.Trace may fail. This is only - /// an issue if you are programmatically creating your own AppDomains. - /// - /// - private static void EmitErrorLine(string message) - { - try - { + } + catch + { + // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller + } + } + + /// + /// Writes output to the standard error stream. + /// + /// The message to log. + /// + /// + /// Writes to both Console.Error and System.Diagnostics.Trace. + /// Note that the System.Diagnostics.Trace is not supported + /// on the Compact Framework. + /// + /// + /// If the AppDomain is not configured with a config file then + /// the call to System.Diagnostics.Trace may fail. This is only + /// an issue if you are programmatically creating your own AppDomains. + /// + /// + private static void EmitErrorLine(string message) + { + try + { #if NETCF Console.WriteLine(message); //System.Diagnostics.Debug.WriteLine(message); #else - Console.Error.WriteLine(message); - Trace.WriteLine(message); + Console.Error.WriteLine(message); + Trace.WriteLine(message); #endif - } - catch - { - // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller - } - } - - #region Private Static Fields - - /// - /// Default debug level - /// - private static bool s_debugEnabled = false; + } + catch + { + // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller + } + } + + /// + /// Default debug level. + /// + private static bool s_debugEnabled = false; - /// - /// In quietMode not even errors generate any output. - /// - private static bool s_quietMode = false; + /// + /// In quietMode not even errors generate any output. + /// + private static bool s_quietMode = false; private static bool s_emitInternalMessages = true; - private const string PREFIX = "log4net: "; - private const string ERR_PREFIX = "log4net:ERROR "; - private const string WARN_PREFIX = "log4net:WARN "; - - #endregion Private Static Fields - + private const string PREFIX = "log4net: "; + private const string ERR_PREFIX = "log4net:ERROR "; + private const string WARN_PREFIX = "log4net:WARN "; + /// /// Subscribes to the LogLog.LogReceived event and stores messages /// to the supplied IList instance. @@ -617,53 +597,53 @@ private static void EmitErrorLine(string message) public class LogReceivedAdapter : IDisposable { private readonly IList items; - private readonly LogReceivedEventHandler handler; - - /// - /// + private readonly LogReceivedEventHandler handler; + + /// + /// Initializes a new instance of the class. /// /// public LogReceivedAdapter(IList items) { this.items = items; - handler = new LogReceivedEventHandler(LogLog_LogReceived); + this.handler = new LogReceivedEventHandler(this.LogLog_LogReceived); - LogReceived += handler; + LogReceived += this.handler; } - void LogLog_LogReceived(object source, LogReceivedEventArgs e) + private void LogLog_LogReceived(object source, LogReceivedEventArgs e) { - items.Add(e.LogLog); + this.items.Add(e.LogLog); } /// - /// + /// /// public IList Items { - get { return items; } + get { return this.items; } } /// - /// + /// /// public void Dispose() { - LogReceived -= handler; + LogReceived -= this.handler; } } - } + } /// - /// + /// /// public class LogReceivedEventArgs : EventArgs { - private readonly LogLog loglog; - - /// - /// + private readonly LogLog loglog; + + /// + /// Initializes a new instance of the class. /// /// public LogReceivedEventArgs(LogLog loglog) @@ -672,11 +652,11 @@ public LogReceivedEventArgs(LogLog loglog) } /// - /// + /// /// public LogLog LogLog { - get { return loglog; } + get { return this.loglog; } } } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs index 3442e2a7c38..6d873d142a2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext #if !NETCF @@ -30,238 +28,220 @@ namespace log4net.Util { - /// - /// Implementation of Properties collection for the - /// - /// - /// - /// Class implements a collection of properties that is specific to each thread. - /// The class is not synchronized as each thread has its own . - /// - /// - /// This class stores its properties in a slot on the named - /// log4net.Util.LogicalThreadContextProperties. - /// - /// - /// The requires a link time - /// for the - /// . - /// If the calling code does not have this permission then this context will be disabled. - /// It will not store any property values set on it. - /// - /// - /// Nicko Cadell - public sealed class LogicalThreadContextProperties : ContextPropertiesBase - { - private const string c_SlotName = "log4net.Util.LogicalThreadContextProperties"; - - /// - /// Flag used to disable this context if we don't have permission to access the CallContext. - /// - private bool m_disabled = false; - - #region Public Instance Constructors + /// + /// Implementation of Properties collection for the . + /// + /// + /// + /// Class implements a collection of properties that is specific to each thread. + /// The class is not synchronized as each thread has its own . + /// + /// + /// This class stores its properties in a slot on the named + /// log4net.Util.LogicalThreadContextProperties. + /// + /// + /// The requires a link time + /// for the + /// . + /// If the calling code does not have this permission then this context will be disabled. + /// It will not store any property values set on it. + /// + /// + /// Nicko Cadell. + public sealed class LogicalThreadContextProperties : ContextPropertiesBase + { + private const string c_SlotName = "log4net.Util.LogicalThreadContextProperties"; - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal LogicalThreadContextProperties() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the value of a property - /// - /// - /// The value for the property with the specified key - /// - /// - /// - /// Get or set the property value for the specified. - /// - /// - override public object this[string key] - { - get - { - // Don't create the dictionary if it does not already exist - PropertiesDictionary dictionary = GetProperties(false); - if (dictionary != null) - { - return dictionary[key]; - } - return null; - } - set - { - // Force the dictionary to be created - PropertiesDictionary props = GetProperties(true); - // Reason for cloning the dictionary below: object instances set on the CallContext - // need to be immutable to correctly flow through async/await - PropertiesDictionary immutableProps = new PropertiesDictionary(props); - immutableProps[key] = value; - SetCallContextData(immutableProps); - } - } - - #endregion Public Instance Properties - - #region Public Instance Methods - - /// - /// Remove a property - /// - /// the key for the entry to remove - /// - /// - /// Remove the value for the specified from the context. - /// - /// - public void Remove(string key) - { - PropertiesDictionary dictionary = GetProperties(false); - if (dictionary != null) - { - PropertiesDictionary immutableProps = new PropertiesDictionary(dictionary); - immutableProps.Remove(key); - SetCallContextData(immutableProps); - } - } - - /// - /// Clear all the context properties - /// - /// - /// - /// Clear all the context properties - /// - /// - public void Clear() - { - PropertiesDictionary dictionary = GetProperties(false); - if (dictionary != null) - { - PropertiesDictionary immutableProps = new PropertiesDictionary(); - SetCallContextData(immutableProps); - } - } - - #endregion Public Instance Methods - - #region Internal Instance Methods - - /// - /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. - /// - /// create the dictionary if it does not exist, otherwise return null if is does not exist - /// the properties for this thread - /// - /// - /// The collection returned is only to be used on the calling thread. If the - /// caller needs to share the collection between different threads then the - /// caller must clone the collection before doings so. - /// - /// - internal PropertiesDictionary GetProperties(bool create) - { - if (!m_disabled) - { - try - { - PropertiesDictionary properties = GetCallContextData(); - if (properties == null && create) - { - properties = new PropertiesDictionary(); - SetCallContextData(properties); - } - return properties; - } - catch (SecurityException secEx) - { - m_disabled = true; - - // Thrown if we don't have permission to read or write the CallContext - LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx); - } - } - - // Only get here is we are disabled because of a security exception - if (create) - { - return new PropertiesDictionary(); - } - return null; - } - - #endregion Internal Instance Methods - - #region Private Static Methods + /// + /// Flag used to disable this context if we don't have permission to access the CallContext. + /// + private bool m_disabled = false; + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal LogicalThreadContextProperties() + { + } + + /// + /// Gets or sets the value of a property. + /// + /// + /// The value for the property with the specified key. + /// + /// + /// + /// Get or set the property value for the specified. + /// + /// + public override object this[string key] + { + get + { + // Don't create the dictionary if it does not already exist + PropertiesDictionary dictionary = this.GetProperties(false); + if (dictionary != null) + { + return dictionary[key]; + } + + return null; + } + + set + { + // Force the dictionary to be created + PropertiesDictionary props = this.GetProperties(true); + + // Reason for cloning the dictionary below: object instances set on the CallContext + // need to be immutable to correctly flow through async/await + PropertiesDictionary immutableProps = new PropertiesDictionary(props); + immutableProps[key] = value; + SetCallContextData(immutableProps); + } + } + + /// + /// Remove a property. + /// + /// the key for the entry to remove. + /// + /// + /// Remove the value for the specified from the context. + /// + /// + public void Remove(string key) + { + PropertiesDictionary dictionary = this.GetProperties(false); + if (dictionary != null) + { + PropertiesDictionary immutableProps = new PropertiesDictionary(dictionary); + immutableProps.Remove(key); + SetCallContextData(immutableProps); + } + } /// - /// Gets the call context get data. - /// - /// The peroperties dictionary stored in the call context - /// - /// The method has a - /// security link demand, therfore we must put the method call in a seperate method - /// that we can wrap in an exception handler. - /// + /// Clear all the context properties. + /// + /// + /// + /// Clear all the context properties. + /// + /// + public void Clear() + { + PropertiesDictionary dictionary = this.GetProperties(false); + if (dictionary != null) + { + PropertiesDictionary immutableProps = new PropertiesDictionary(); + SetCallContextData(immutableProps); + } + } + + /// + /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. + /// + /// create the dictionary if it does not exist, otherwise return null if is does not exist. + /// the properties for this thread. + /// + /// + /// The collection returned is only to be used on the calling thread. If the + /// caller needs to share the collection between different threads then the + /// caller must clone the collection before doings so. + /// + /// + internal PropertiesDictionary GetProperties(bool create) + { + if (!this.m_disabled) + { + try + { + PropertiesDictionary properties = GetCallContextData(); + if (properties == null && create) + { + properties = new PropertiesDictionary(); + SetCallContextData(properties); + } + + return properties; + } + catch (SecurityException secEx) + { + this.m_disabled = true; + + // Thrown if we don't have permission to read or write the CallContext + LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx); + } + } + + // Only get here is we are disabled because of a security exception + if (create) + { + return new PropertiesDictionary(); + } + + return null; + } + + /// + /// Gets the call context get data. + /// + /// The peroperties dictionary stored in the call context. + /// + /// The method has a + /// security link demand, therfore we must put the method call in a seperate method + /// that we can wrap in an exception handler. + /// #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif private static PropertiesDictionary GetCallContextData() - { + { #if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 return CallContext.LogicalGetData(c_SlotName) as PropertiesDictionary; #else return CallContext.GetData(c_SlotName) as PropertiesDictionary; #endif - } - - /// - /// Sets the call context data. - /// - /// The properties. - /// - /// The method has a - /// security link demand, therfore we must put the method call in a seperate method - /// that we can wrap in an exception handler. - /// + } + + /// + /// Sets the call context data. + /// + /// The properties. + /// + /// The method has a + /// security link demand, therfore we must put the method call in a seperate method + /// that we can wrap in an exception handler. + /// #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif private static void SetCallContextData(PropertiesDictionary properties) - { + { #if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 - CallContext.LogicalSetData(c_SlotName, properties); + CallContext.LogicalSetData(c_SlotName, properties); #else CallContext.SetData(c_SlotName, properties); #endif - } - - #endregion - - #region Private Static Fields - - /// - /// The fully qualified type of the LogicalThreadContextProperties class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(LogicalThreadContextProperties); - - #endregion Private Static Fields + } + + /// + /// The fully qualified type of the LogicalThreadContextProperties class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(LogicalThreadContextProperties); } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs index f00f777b4a0..2c9870c8388 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,415 +18,375 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - #if !NETCF using System; using System.Collections; - + using log4net.Core; namespace log4net.Util -{ - - /// - /// Delegate type used for LogicalThreadContextStack's callbacks. - /// - #if NET_2_0 || MONO_2_0 - public delegate void TwoArgAction(T1 t1, T2 t2); - #else +{ + /// + /// Delegate type used for LogicalThreadContextStack's callbacks. + /// +#if NET_2_0 || MONO_2_0 + public delegate void TwoArgAction(T1 t1, T2 t2); +#else public delegate void TwoArgAction(string t1, LogicalThreadContextStack t2); - #endif - +#endif + + /// + /// Implementation of Stack for the . + /// + /// + /// + /// Implementation of Stack for the . + /// + /// + /// Nicko Cadell. + public sealed class LogicalThreadContextStack : IFixingRequired + { /// - /// Implementation of Stack for the - /// - /// - /// - /// Implementation of Stack for the - /// - /// - /// Nicko Cadell - public sealed class LogicalThreadContextStack : IFixingRequired - { - #region Private Instance Fields - - /// - /// The stack store. - /// - private Stack m_stack = new Stack(); - - /// - /// The name of this within the - /// . - /// - private string m_propertyKey; + /// The stack store. + /// + private Stack m_stack = new Stack(); - /// - /// The callback used to let the register a - /// new instance of a . - /// - #if NET_2_0 || MONO_2_0 - private TwoArgAction m_registerNew; - #else + /// + /// The name of this within the + /// . + /// + private string m_propertyKey; + + /// + /// The callback used to let the register a + /// new instance of a . + /// +#if NET_2_0 || MONO_2_0 + private TwoArgAction m_registerNew; +#else private TwoArgAction m_registerNew; - #endif - - #endregion Private Instance Fields - - #region Public Instance Constructors - - /// - /// Internal constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - #if NET_2_0 || MONO_2_0 - internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) - #else +#endif + + /// + /// Initializes a new instance of the class. + /// Internal constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// +#if NET_2_0 || MONO_2_0 + internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) +#else internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) - #endif - { - m_propertyKey = propertyKey; - m_registerNew = registerNew; - } - - #endregion Public Instance Constructors - - #region Public Properties - - /// - /// The number of messages in the stack - /// - /// - /// The current number of messages in the stack - /// - /// - /// - /// The current number of messages in the stack. That is - /// the number of times has been called - /// minus the number of times has been called. - /// - /// - public int Count - { - get { return m_stack.Count; } - } - - #endregion // Public Properties - - #region Public Methods - - /// - /// Clears all the contextual information held in this stack. - /// - /// - /// - /// Clears all the contextual information held in this stack. - /// Only call this if you think that this thread is being reused after - /// a previous call execution which may not have completed correctly. - /// You do not need to use this method if you always guarantee to call - /// the method of the - /// returned from even in exceptional circumstances, - /// for example by using the using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// syntax. - /// - /// - public void Clear() - { - m_registerNew(m_propertyKey, new LogicalThreadContextStack(m_propertyKey, m_registerNew)); - } - - /// - /// Removes the top context from this stack. - /// - /// The message in the context that was removed from the top of this stack. - /// - /// - /// Remove the top context from this stack, and return - /// it to the caller. If this stack is empty then an - /// empty string (not ) is returned. - /// - /// - public string Pop() - { - // copy current stack - Stack stack = new Stack(new Stack(m_stack)); - string result = ""; - if (stack.Count > 0) - { - result = ((StackFrame)(stack.Pop())).Message; - } - LogicalThreadContextStack ltcs = new LogicalThreadContextStack(m_propertyKey, m_registerNew); - ltcs.m_stack = stack; - m_registerNew(m_propertyKey, ltcs); - return result; - } - - /// - /// Pushes a new context message into this stack. - /// - /// The new context message. - /// - /// An that can be used to clean up the context stack. - /// - /// - /// - /// Pushes a new context onto this stack. An - /// is returned that can be used to clean up this stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// { - /// log.Warn("This should have an ThreadContext Stack message"); - /// } - /// - /// - public IDisposable Push(string message) - { - // do modifications on a copy - Stack stack = new Stack(new Stack(m_stack)); - stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); - - LogicalThreadContextStack contextStack = new LogicalThreadContextStack(m_propertyKey, m_registerNew); - contextStack.m_stack = stack; - m_registerNew(m_propertyKey, contextStack); - return new AutoPopStackFrame(contextStack, stack.Count - 1); - } - - #endregion Public Methods - - #region Internal Methods - - /// - /// Gets the current context information for this stack. - /// - /// The current context information. - internal string GetFullMessage() - { - Stack stack = m_stack; - if (stack.Count > 0) - { - return ((StackFrame)(stack.Peek())).FullMessage; - } - return null; - } - - /// - /// Gets and sets the internal stack used by this - /// - /// The internal storage stack - /// - /// - /// This property is provided only to support backward compatability - /// of the . Tytpically the internal stack should not - /// be modified. - /// - /// - internal Stack InternalStack - { - get { return m_stack; } - set { m_stack = value; } - } - - #endregion Internal Methods - - /// - /// Gets the current context information for this stack. - /// - /// Gets the current context information - /// - /// - /// Gets the current context information for this stack. - /// - /// - public override string ToString() - { - return GetFullMessage(); - } - - /// - /// Get a portable version of this object - /// - /// the portable instance of this object - /// - /// - /// Get a cross thread portable version of this object - /// - /// - object IFixingRequired.GetFixedObject() - { - return GetFullMessage(); - } - - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - private sealed class StackFrame - { - #region Private Instance Fields - - private readonly string m_message; - private readonly StackFrame m_parent; - private string m_fullMessage = null; - - #endregion - - #region Internal Instance Constructors - - /// - /// Constructor - /// - /// The message for this context. - /// The parent context in the chain. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and parent context. - /// - /// - internal StackFrame(string message, StackFrame parent) - { - m_message = message; - m_parent = parent; - - if (parent == null) - { - m_fullMessage = message; - } - } - - #endregion Internal Instance Constructors - - #region Internal Instance Properties - - /// - /// Get the message. - /// - /// The message. - /// - /// - /// Get the message. - /// - /// - internal string Message - { - get { return m_message; } - } - - /// - /// Gets the full text of the context down to the root level. - /// - /// - /// The full text of the context down to the root level. - /// - /// - /// - /// Gets the full text of the context down to the root level. - /// - /// - internal string FullMessage - { - get - { - if (m_fullMessage == null && m_parent != null) - { - m_fullMessage = string.Concat(m_parent.FullMessage, " ", m_message); - } - return m_fullMessage; - } - } - - #endregion Internal Instance Properties - } - - /// - /// Struct returned from the method. - /// - /// - /// - /// This struct implements the and is designed to be used - /// with the pattern to remove the stack frame at the end of the scope. - /// - /// - private struct AutoPopStackFrame : IDisposable - { - #region Private Instance Fields - - /// - /// The depth to trim the stack to when this instance is disposed - /// - private int m_frameDepth; - - /// - /// The outer LogicalThreadContextStack. - /// - private LogicalThreadContextStack m_logicalThreadContextStack; - - #endregion Private Instance Fields - - #region Internal Instance Constructors +#endif + { + this.m_propertyKey = propertyKey; + this.m_registerNew = registerNew; + } + + /// + /// Gets the number of messages in the stack. + /// + /// + /// The current number of messages in the stack. + /// + /// + /// + /// The current number of messages in the stack. That is + /// the number of times has been called + /// minus the number of times has been called. + /// + /// + public int Count + { + get { return this.m_stack.Count; } + } + + /// + /// Clears all the contextual information held in this stack. + /// + /// + /// + /// Clears all the contextual information held in this stack. + /// Only call this if you think that this thread is being reused after + /// a previous call execution which may not have completed correctly. + /// You do not need to use this method if you always guarantee to call + /// the method of the + /// returned from even in exceptional circumstances, + /// for example by using the using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// syntax. + /// + /// + public void Clear() + { + this.m_registerNew(this.m_propertyKey, new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew)); + } - /// - /// Constructor - /// - /// The internal stack used by the ThreadContextStack. - /// The depth to return the stack to when this object is disposed. - /// - /// - /// Initializes a new instance of the class with - /// the specified stack and return depth. - /// - /// - internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack, int frameDepth) - { - m_frameDepth = frameDepth; - m_logicalThreadContextStack = logicalThreadContextStack; - } + /// + /// Removes the top context from this stack. + /// + /// The message in the context that was removed from the top of this stack. + /// + /// + /// Remove the top context from this stack, and return + /// it to the caller. If this stack is empty then an + /// empty string (not ) is returned. + /// + /// + public string Pop() + { + // copy current stack + Stack stack = new Stack(new Stack(this.m_stack)); + string result = string.Empty; + if (stack.Count > 0) + { + result = ((StackFrame)stack.Pop()).Message; + } + + LogicalThreadContextStack ltcs = new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew); + ltcs.m_stack = stack; + this.m_registerNew(this.m_propertyKey, ltcs); + return result; + } - #endregion Internal Instance Constructors + /// + /// Pushes a new context message into this stack. + /// + /// The new context message. + /// + /// An that can be used to clean up the context stack. + /// + /// + /// + /// Pushes a new context onto this stack. An + /// is returned that can be used to clean up this stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// { + /// log.Warn("This should have an ThreadContext Stack message"); + /// } + /// + /// + public IDisposable Push(string message) + { + // do modifications on a copy + Stack stack = new Stack(new Stack(this.m_stack)); + stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); + + LogicalThreadContextStack contextStack = new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew); + contextStack.m_stack = stack; + this.m_registerNew(this.m_propertyKey, contextStack); + return new AutoPopStackFrame(contextStack, stack.Count - 1); + } + + /// + /// Gets the current context information for this stack. + /// + /// The current context information. + internal string GetFullMessage() + { + Stack stack = this.m_stack; + if (stack.Count > 0) + { + return ((StackFrame)stack.Peek()).FullMessage; + } + + return null; + } - #region Implementation of IDisposable + /// + /// Gets or sets and sets the internal stack used by this . + /// + /// The internal storage stack. + /// + /// + /// This property is provided only to support backward compatability + /// of the . Tytpically the internal stack should not + /// be modified. + /// + /// + internal Stack InternalStack + { + get { return this.m_stack; } + set { this.m_stack = value; } + } + + /// + /// Gets the current context information for this stack. + /// + /// Gets the current context information. + /// + /// + /// Gets the current context information for this stack. + /// + /// + public override string ToString() + { + return this.GetFullMessage(); + } - /// - /// Returns the stack to the correct depth. - /// - /// - /// - /// Returns the stack to the correct depth. - /// - /// - public void Dispose() - { - if (m_frameDepth >= 0 && m_logicalThreadContextStack.m_stack != null) - { - Stack stack = new Stack(new Stack(m_logicalThreadContextStack.m_stack)); - while (stack.Count > m_frameDepth) - { - stack.Pop(); - } - LogicalThreadContextStack ltcs = new LogicalThreadContextStack(m_logicalThreadContextStack.m_propertyKey, m_logicalThreadContextStack.m_registerNew); - ltcs.m_stack = stack; - m_logicalThreadContextStack.m_registerNew(m_logicalThreadContextStack.m_propertyKey, - ltcs); - } - } + /// + /// Get a portable version of this object. + /// + /// the portable instance of this object. + /// + /// + /// Get a cross thread portable version of this object. + /// + /// + object IFixingRequired.GetFixedObject() + { + return this.GetFullMessage(); + } - #endregion Implementation of IDisposable - } + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + private sealed class StackFrame + { + private readonly string m_message; + private readonly StackFrame m_parent; + private string m_fullMessage = null; + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The message for this context. + /// The parent context in the chain. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and parent context. + /// + /// + internal StackFrame(string message, StackFrame parent) + { + this.m_message = message; + this.m_parent = parent; + + if (parent == null) + { + this.m_fullMessage = message; + } + } + + /// + /// Gets get the message. + /// + /// The message. + /// + /// + /// Get the message. + /// + /// + internal string Message + { + get { return this.m_message; } + } + + /// + /// Gets the full text of the context down to the root level. + /// + /// + /// The full text of the context down to the root level. + /// + /// + /// + /// Gets the full text of the context down to the root level. + /// + /// + internal string FullMessage + { + get + { + if (this.m_fullMessage == null && this.m_parent != null) + { + this.m_fullMessage = string.Concat(this.m_parent.FullMessage, " ", this.m_message); + } + + return this.m_fullMessage; + } + } + } - } + /// + /// Struct returned from the method. + /// + /// + /// + /// This struct implements the and is designed to be used + /// with the pattern to remove the stack frame at the end of the scope. + /// + /// + private struct AutoPopStackFrame : IDisposable + { + /// + /// The depth to trim the stack to when this instance is disposed. + /// + private int m_frameDepth; + + /// + /// The outer LogicalThreadContextStack. + /// + private LogicalThreadContextStack m_logicalThreadContextStack; + + /// + /// Initializes a new instance of the struct. + /// Constructor. + /// + /// The internal stack used by the ThreadContextStack. + /// The depth to return the stack to when this object is disposed. + /// + /// + /// Initializes a new instance of the class with + /// the specified stack and return depth. + /// + /// + internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack, int frameDepth) + { + this.m_frameDepth = frameDepth; + this.m_logicalThreadContextStack = logicalThreadContextStack; + } + + /// + /// Returns the stack to the correct depth. + /// + /// + /// + /// Returns the stack to the correct depth. + /// + /// + public void Dispose() + { + if (this.m_frameDepth >= 0 && this.m_logicalThreadContextStack.m_stack != null) + { + Stack stack = new Stack(new Stack(this.m_logicalThreadContextStack.m_stack)); + while (stack.Count > this.m_frameDepth) + { + stack.Pop(); + } + + LogicalThreadContextStack ltcs = new LogicalThreadContextStack(this.m_logicalThreadContextStack.m_propertyKey, this.m_logicalThreadContextStack.m_registerNew); + ltcs.m_stack = stack; + this.m_logicalThreadContextStack.m_registerNew( + this.m_logicalThreadContextStack.m_propertyKey, + ltcs); + } + } + } + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs index 98d30c6a279..b0083a05eb2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,129 +18,112 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - #if !NETCF using System; using System.Collections; namespace log4net.Util { - /// - /// Implementation of Stacks collection for the - /// - /// - /// - /// Implementation of Stacks collection for the - /// - /// - /// Nicko Cadell - public sealed class LogicalThreadContextStacks - { - private readonly LogicalThreadContextProperties m_properties; - - #region Public Instance Constructors - - /// - /// Internal constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal LogicalThreadContextStacks(LogicalThreadContextProperties properties) - { - m_properties = properties; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the named thread context stack - /// - /// - /// The named stack - /// - /// - /// - /// Gets the named thread context stack - /// - /// - public LogicalThreadContextStack this[string key] - { - get - { - LogicalThreadContextStack stack = null; - - object propertyValue = m_properties[key]; - if (propertyValue == null) - { - // Stack does not exist, create + /// + /// Implementation of Stacks collection for the . + /// + /// + /// + /// Implementation of Stacks collection for the . + /// + /// + /// Nicko Cadell. + public sealed class LogicalThreadContextStacks + { + private readonly LogicalThreadContextProperties m_properties; + + /// + /// Initializes a new instance of the class. + /// Internal constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal LogicalThreadContextStacks(LogicalThreadContextProperties properties) + { + this.m_properties = properties; + } + + /// + /// Gets the named thread context stack. + /// + /// + /// The named stack. + /// + /// + /// + /// Gets the named thread context stack. + /// + /// + public LogicalThreadContextStack this[string key] + { + get + { + LogicalThreadContextStack stack = null; + + object propertyValue = this.m_properties[key]; + if (propertyValue == null) + { + // Stack does not exist, create #if NET_2_0 || MONO_2_0 - stack = new LogicalThreadContextStack(key, registerNew); + stack = new LogicalThreadContextStack(key, this.registerNew); #else stack = new LogicalThreadContextStack(key, new TwoArgAction(registerNew)); #endif - m_properties[key] = stack; - } - else - { - // Look for existing stack - stack = propertyValue as LogicalThreadContextStack; - if (stack == null) - { - // Property is not set to a stack! - string propertyValueString = SystemInfo.NullText; - - try - { - propertyValueString = propertyValue.ToString(); - } - catch - { - } - - LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named [" + key + "] failed because a property with the same name exists which is a [" + propertyValue.GetType().Name + "] with value [" + propertyValueString + "]"); + this.m_properties[key] = stack; + } + else + { + // Look for existing stack + stack = propertyValue as LogicalThreadContextStack; + if (stack == null) + { + // Property is not set to a stack! + string propertyValueString = SystemInfo.NullText; + + try + { + propertyValueString = propertyValue.ToString(); + } + catch + { + } + + LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named [" + key + "] failed because a property with the same name exists which is a [" + propertyValue.GetType().Name + "] with value [" + propertyValueString + "]"); #if NET_2_0 || MONO_2_0 - stack = new LogicalThreadContextStack(key, registerNew); + stack = new LogicalThreadContextStack(key, this.registerNew); #else stack = new LogicalThreadContextStack(key, new TwoArgAction(registerNew)); #endif - } - } - - return stack; - } - } - - #endregion Public Instance Properties - - #region Private Instance Fields - - private void registerNew(string stackName, LogicalThreadContextStack stack) - { - m_properties[stackName] = stack; - } - - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the ThreadContextStacks class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(LogicalThreadContextStacks); - - #endregion Private Static Fields - } + } + } + + return stack; + } + } + + private void registerNew(string stackName, LogicalThreadContextStack stack) + { + this.m_properties[stackName] = stack; + } + + /// + /// The fully qualified type of the ThreadContextStacks class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(LogicalThreadContextStacks); + } } #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs index 2b04178da30..2e4c6e1ae57 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // MONO 1.0 has no support for Win32 Error APIs #if !MONO @@ -32,261 +30,238 @@ using System.Globalization; using System.Runtime.InteropServices; -namespace log4net.Util +namespace log4net.Util { - /// - /// Represents a native error code and message. - /// - /// - /// - /// Represents a Win32 platform native error. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class NativeError - { - #region Protected Instance Constructors + /// + /// Represents a native error code and message. + /// + /// + /// + /// Represents a Win32 platform native error. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class NativeError + { + /// + /// Initializes a new instance of the class. + /// Create an instance of the class with the specified + /// error number and message. + /// + /// The number of the native error. + /// The message of the native error. + /// + /// + /// Create an instance of the class with the specified + /// error number and message. + /// + /// + private NativeError(int number, string message) + { + this.m_number = number; + this.m_message = message; + } + + /// + /// Gets the number of the native error. + /// + /// + /// The number of the native error. + /// + /// + /// + /// Gets the number of the native error. + /// + /// + public int Number + { + get { return this.m_number; } + } - /// - /// Create an instance of the class with the specified - /// error number and message. - /// - /// The number of the native error. - /// The message of the native error. - /// - /// - /// Create an instance of the class with the specified - /// error number and message. - /// - /// - private NativeError(int number, string message) - { - m_number = number; - m_message = message; - } - - #endregion // Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the number of the native error. - /// - /// - /// The number of the native error. - /// - /// - /// - /// Gets the number of the native error. - /// - /// - public int Number - { - get { return m_number; } - } - - /// - /// Gets the message of the native error. - /// - /// - /// The message of the native error. - /// - /// - /// - /// - /// Gets the message of the native error. - /// - public string Message - { - get { return m_message; } - } - - #endregion // Public Instance Properties - - #region Public Static Methods - - /// - /// Create a new instance of the class for the last Windows error. - /// - /// - /// An instance of the class for the last windows error. - /// - /// - /// - /// The message for the error number is lookup up using the - /// native Win32 FormatMessage function. - /// - /// + /// + /// Gets the message of the native error. + /// + /// + /// The message of the native error. + /// + /// + /// + /// + /// Gets the message of the native error. + /// + public string Message + { + get { return this.m_message; } + } + + /// + /// Create a new instance of the class for the last Windows error. + /// + /// + /// An instance of the class for the last windows error. + /// + /// + /// + /// The message for the error number is lookup up using the + /// native Win32 FormatMessage function. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #elif !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)] #endif - public static NativeError GetLastError() - { - int number = Marshal.GetLastWin32Error(); - return new NativeError(number, NativeError.GetErrorMessage(number)); - } + public static NativeError GetLastError() + { + int number = Marshal.GetLastWin32Error(); + return new NativeError(number, NativeError.GetErrorMessage(number)); + } - /// - /// Create a new instance of the class. - /// - /// the error number for the native error - /// - /// An instance of the class for the specified - /// error number. - /// - /// - /// - /// The message for the specified error number is lookup up using the - /// native Win32 FormatMessage function. - /// - /// - public static NativeError GetError(int number) - { - return new NativeError(number, NativeError.GetErrorMessage(number)); - } - - /// - /// Retrieves the message corresponding with a Win32 message identifier. - /// - /// Message identifier for the requested message. - /// - /// The message corresponding with the specified message identifier. - /// - /// - /// - /// The message will be searched for in system message-table resource(s) - /// using the native FormatMessage function. - /// - /// + /// + /// Create a new instance of the class. + /// + /// the error number for the native error. + /// + /// An instance of the class for the specified + /// error number. + /// + /// + /// + /// The message for the specified error number is lookup up using the + /// native Win32 FormatMessage function. + /// + /// + public static NativeError GetError(int number) + { + return new NativeError(number, NativeError.GetErrorMessage(number)); + } + + /// + /// Retrieves the message corresponding with a Win32 message identifier. + /// + /// Message identifier for the requested message. + /// + /// The message corresponding with the specified message identifier. + /// + /// + /// + /// The message will be searched for in system message-table resource(s) + /// using the native FormatMessage function. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #elif !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] #endif - public static string GetErrorMessage(int messageId) - { - // Win32 constants - int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; // The function should allocates a buffer large enough to hold the formatted message - int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; // Insert sequences in the message definition are to be ignored - int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; // The function should search the system message-table resource(s) for the requested message - - string msgBuf = ""; // buffer that will receive the message - IntPtr sourcePtr = new IntPtr(); // Location of the message definition, will be ignored - IntPtr argumentsPtr = new IntPtr(); // Pointer to array of values to insert, not supported as it requires unsafe code + public static string GetErrorMessage(int messageId) + { + // Win32 constants + int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; // The function should allocates a buffer large enough to hold the formatted message + int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; // Insert sequences in the message definition are to be ignored + int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; // The function should search the system message-table resource(s) for the requested message - if (messageId != 0) - { - // If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character - int messageSize = FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - ref sourcePtr, - messageId, - 0, - ref msgBuf, - 255, - argumentsPtr); + string msgBuf = string.Empty; // buffer that will receive the message + IntPtr sourcePtr = IntPtr.Zero; // Location of the message definition, will be ignored + IntPtr argumentsPtr = IntPtr.Zero; // Pointer to array of values to insert, not supported as it requires unsafe code - if (messageSize > 0) - { - // Remove trailing null-terminating characters (\r\n) from the message - msgBuf = msgBuf.TrimEnd(new char[] {'\r', '\n'}); - } - else - { - // A message could not be located. - msgBuf = null; - } - } - else - { - msgBuf = null; - } + if (messageId != 0) + { + // If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character + int messageSize = FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + ref sourcePtr, + messageId, + 0, + ref msgBuf, + 255, + argumentsPtr); - return msgBuf; - } + if (messageSize > 0) + { + // Remove trailing null-terminating characters (\r\n) from the message + msgBuf = msgBuf.TrimEnd(new char[] { '\r', '\n' }); + } + else + { + // A message could not be located. + msgBuf = null; + } + } + else + { + msgBuf = null; + } - #endregion // Public Static Methods - - #region Override Object Implementation - - /// - /// Return error information string - /// - /// error information string - /// - /// - /// Return error information string - /// - /// - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", this.Number) + (this.Message != null ? ": " + this.Message : ""); - } - - #endregion // Override Object Implementation - - #region Stubs For Native Function Calls - - /// - /// Formats a message string. - /// - /// Formatting options, and how to interpret the parameter. - /// Location of the message definition. - /// Message identifier for the requested message. - /// Language identifier for the requested message. - /// If includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in . - /// If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer. - /// Pointer to an array of values that are used as insert values in the formatted message. - /// - /// - /// The function requires a message definition as input. The message definition can come from a - /// buffer passed into the function. It can come from a message table resource in an - /// already-loaded module. Or the caller can ask the function to search the system's message - /// table resource(s) for the message definition. The function finds the message definition - /// in a message table resource based on a message identifier and a language identifier. - /// The function copies the formatted message text to an output buffer, processing any embedded - /// insert sequences if requested. - /// - /// - /// To prevent the usage of unsafe code, this stub does not support inserting values in the formatted message. - /// - /// - /// - /// - /// If the function succeeds, the return value is the number of TCHARs stored in the output - /// buffer, excluding the terminating null character. - /// - /// - /// If the function fails, the return value is zero. To get extended error information, - /// call . - /// - /// + return msgBuf; + } + + /// + /// Return error information string. + /// + /// error information string. + /// + /// + /// Return error information string. + /// + /// + public override string ToString() + { + return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", this.Number) + (this.Message != null ? ": " + this.Message : string.Empty); + } + + /// + /// Formats a message string. + /// + /// Formatting options, and how to interpret the parameter. + /// Location of the message definition. + /// Message identifier for the requested message. + /// Language identifier for the requested message. + /// If includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in . + /// If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// Pointer to an array of values that are used as insert values in the formatted message. + /// + /// + /// The function requires a message definition as input. The message definition can come from a + /// buffer passed into the function. It can come from a message table resource in an + /// already-loaded module. Or the caller can ask the function to search the system's message + /// table resource(s) for the message definition. The function finds the message definition + /// in a message table resource based on a message identifier and a language identifier. + /// The function copies the formatted message text to an output buffer, processing any embedded + /// insert sequences if requested. + /// + /// + /// To prevent the usage of unsafe code, this stub does not support inserting values in the formatted message. + /// + /// + /// + /// + /// If the function succeeds, the return value is the number of TCHARs stored in the output + /// buffer, excluding the terminating null character. + /// + /// + /// If the function fails, the return value is zero. To get extended error information, + /// call . + /// + /// #if NETCF [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] #else - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] #endif - private static extern int FormatMessage( - int dwFlags, - ref IntPtr lpSource, - int dwMessageId, - int dwLanguageId, - ref String lpBuffer, - int nSize, - IntPtr Arguments); - - #endregion // Stubs For Native Function Calls - - #region Private Instance Fields - - private int m_number; - private string m_message; - - #endregion - } + private static extern int FormatMessage( + int dwFlags, + ref IntPtr lpSource, + int dwMessageId, + int dwLanguageId, + ref string lpBuffer, + int nSize, + IntPtr Arguments); + + private int m_number; + private string m_message; + } } #endif // !CLI_1_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs index e4a129d2fa1..3ba57dc03fe 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs @@ -1,206 +1,183 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the over a collection - /// that is empty and not modifiable. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class NullDictionaryEnumerator : IDictionaryEnumerator - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private NullDictionaryEnumerator() - { - } - - #endregion Private Instance Constructors - - #region Public Static Properties - - /// - /// Gets the singleton instance of the . - /// - /// The singleton instance of the . - /// - /// - /// Gets the singleton instance of the . - /// - /// - public static NullDictionaryEnumerator Instance - { - get { return s_instance; } - } - - #endregion Public Static Properties - - #region Implementation of IEnumerator - - /// - /// Gets the current object from the enumerator. - /// - /// - /// Throws an because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Current - { - get { throw new InvalidOperationException(); } - } - - /// - /// Test if the enumerator can advance, if so advance. - /// - /// false as the cannot advance. - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will always return false. - /// - /// - public bool MoveNext() - { - return false; - } - - /// - /// Resets the enumerator back to the start. - /// - /// - /// - /// As the enumerator is over an empty collection does nothing. - /// - /// - public void Reset() - { - } - - #endregion Implementation of IEnumerator - - #region Implementation of IDictionaryEnumerator - - /// - /// Gets the current key from the enumerator. - /// - /// - /// Throws an exception because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Key - { - get { throw new InvalidOperationException(); } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the over a collection + /// that is empty and not modifiable. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class NullDictionaryEnumerator : IDictionaryEnumerator + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private NullDictionaryEnumerator() + { + } + + /// + /// Gets the singleton instance of the . + /// + /// The singleton instance of the . + /// + /// + /// Gets the singleton instance of the . + /// + /// + public static NullDictionaryEnumerator Instance + { + get { return s_instance; } + } + + /// + /// Gets the current object from the enumerator. + /// + /// + /// Throws an because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Current + { + get { throw new InvalidOperationException(); } + } - /// - /// Gets the current value from the enumerator. - /// - /// The current value from the enumerator. - /// - /// Throws an because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Value - { - get { throw new InvalidOperationException(); } - } + /// + /// Test if the enumerator can advance, if so advance. + /// + /// false as the cannot advance. + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will always return false. + /// + /// + public bool MoveNext() + { + return false; + } - /// - /// Gets the current entry from the enumerator. - /// - /// - /// Throws an because the - /// never has a current entry. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public DictionaryEntry Entry - { - get { throw new InvalidOperationException(); } - } - - #endregion Implementation of IDictionaryEnumerator + /// + /// Resets the enumerator back to the start. + /// + /// + /// + /// As the enumerator is over an empty collection does nothing. + /// + /// + public void Reset() + { + } + + /// + /// Gets the current key from the enumerator. + /// + /// + /// Throws an exception because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Key + { + get { throw new InvalidOperationException(); } + } - #region Private Static Fields + /// + /// Gets the current value from the enumerator. + /// + /// The current value from the enumerator. + /// + /// Throws an because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Value + { + get { throw new InvalidOperationException(); } + } - /// - /// The singleton instance of the . - /// - private readonly static NullDictionaryEnumerator s_instance = new NullDictionaryEnumerator(); - - #endregion Private Static Fields - } + /// + /// Gets the current entry from the enumerator. + /// + /// + /// Throws an because the + /// never has a current entry. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public DictionaryEntry Entry + { + get { throw new InvalidOperationException(); } + } + + /// + /// The singleton instance of the . + /// + private static readonly NullDictionaryEnumerator s_instance = new NullDictionaryEnumerator(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs index 3353941f2d0..8689e7edaf6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs @@ -1,138 +1,119 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the over a collection - /// that is empty and not modifiable. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class NullEnumerator : IEnumerator - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private NullEnumerator() - { - } - - #endregion Private Instance Constructors - - #region Public Static Properties - - /// - /// Get the singleton instance of the . - /// - /// The singleton instance of the . - /// - /// - /// Gets the singleton instance of the . - /// - /// - public static NullEnumerator Instance - { - get { return s_instance; } - } - - #endregion Public Static Properties - - #region Implementation of IEnumerator - - /// - /// Gets the current object from the enumerator. - /// - /// - /// Throws an because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Current - { - get { throw new InvalidOperationException(); } - } - - /// - /// Test if the enumerator can advance, if so advance - /// - /// false as the cannot advance. - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will always return false. - /// - /// - public bool MoveNext() - { - return false; - } - - /// - /// Resets the enumerator back to the start. - /// - /// - /// - /// As the enumerator is over an empty collection does nothing. - /// - /// - public void Reset() - { - } - - #endregion Implementation of IEnumerator + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the over a collection + /// that is empty and not modifiable. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class NullEnumerator : IEnumerator + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private NullEnumerator() + { + } + + /// + /// Gets get the singleton instance of the . + /// + /// The singleton instance of the . + /// + /// + /// Gets the singleton instance of the . + /// + /// + public static NullEnumerator Instance + { + get { return s_instance; } + } + + /// + /// Gets the current object from the enumerator. + /// + /// + /// Throws an because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Current + { + get { throw new InvalidOperationException(); } + } - #region Private Static Fields + /// + /// Test if the enumerator can advance, if so advance. + /// + /// false as the cannot advance. + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will always return false. + /// + /// + public bool MoveNext() + { + return false; + } - /// - /// The singleton instance of the . - /// - private readonly static NullEnumerator s_instance = new NullEnumerator(); - - #endregion Private Static Fields - } + /// + /// Resets the enumerator back to the start. + /// + /// + /// + /// As the enumerator is over an empty collection does nothing. + /// + /// + public void Reset() + { + } + + /// + /// The singleton instance of the . + /// + private static readonly NullEnumerator s_instance = new NullEnumerator(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs index 5738c2e69f9..847df1c0b57 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs @@ -1,80 +1,78 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// A SecurityContext used when a SecurityContext is not required - /// - /// - /// - /// The is a no-op implementation of the - /// base class. It is used where a - /// is required but one has not been provided. - /// - /// - /// Nicko Cadell - public sealed class NullSecurityContext : SecurityContext - { - /// - /// Singleton instance of - /// - /// - /// - /// Singleton instance of - /// - /// - public static readonly NullSecurityContext Instance = new NullSecurityContext(); - - /// - /// Private constructor - /// - /// - /// - /// Private constructor for singleton pattern. - /// - /// - private NullSecurityContext() - { - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + + /// + /// A SecurityContext used when a SecurityContext is not required. + /// + /// + /// + /// The is a no-op implementation of the + /// base class. It is used where a + /// is required but one has not been provided. + /// + /// + /// Nicko Cadell. + public sealed class NullSecurityContext : SecurityContext + { + /// + /// Singleton instance of . + /// + /// + /// + /// Singleton instance of . + /// + /// + public static readonly NullSecurityContext Instance = new NullSecurityContext(); + + /// + /// Initializes a new instance of the class. + /// Private constructor. + /// + /// + /// + /// Private constructor for singleton pattern. + /// + /// + private NullSecurityContext() + { + } - /// - /// Impersonate this SecurityContext - /// - /// State supplied by the caller - /// null - /// - /// - /// No impersonation is done and null is always returned. - /// - /// - public override IDisposable Impersonate(object state) - { - return null; - } - } + /// + /// Impersonate this SecurityContext. + /// + /// State supplied by the caller. + /// null. + /// + /// + /// No impersonation is done and null is always returned. + /// + /// + public override IDisposable Impersonate(object state) + { + return null; + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs index a6f5b47f775..440f3dad646 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs @@ -1,120 +1,111 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Implements log4net's default error handling policy which consists - /// of emitting a message for the first error in an appender and - /// ignoring all subsequent errors. - /// - /// - /// - /// The error message is processed using the LogLog sub-system by default. - /// - /// - /// This policy aims at protecting an otherwise working application - /// from being flooded with error messages when logging fails. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Ron Grabowski - public class OnlyOnceErrorHandler : IErrorHandler - { - #region Public Instance Constructors - - /// - /// Default Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public OnlyOnceErrorHandler() - { - m_prefix = ""; - } - - /// - /// Constructor - /// - /// The prefix to use for each message. - /// - /// - /// Initializes a new instance of the class - /// with the specified prefix. - /// - /// - public OnlyOnceErrorHandler(string prefix) - { - m_prefix = prefix; - } - - #endregion Public Instance Constructors - - #region Public Instance Methods - - /// - /// Reset the error handler back to its initial disabled state. - /// - public void Reset() - { - m_enabledDateUtc = DateTime.MinValue; - m_errorCode = ErrorCode.GenericFailure; - m_exception = null; - m_message = null; - m_firstTime = true; - } - - #region Implementation of IErrorHandler - - /// - /// Log an Error - /// - /// The error message. - /// The exception. - /// The internal error code. - /// - /// - /// Invokes if and only if this is the first error or the first error after has been called. - /// - /// - public void Error(string message, Exception e, ErrorCode errorCode) - { - if (m_firstTime) - { - FirstError(message, e, errorCode); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + using log4net.Core; + + /// + /// Implements log4net's default error handling policy which consists + /// of emitting a message for the first error in an appender and + /// ignoring all subsequent errors. + /// + /// + /// + /// The error message is processed using the LogLog sub-system by default. + /// + /// + /// This policy aims at protecting an otherwise working application + /// from being flooded with error messages when logging fails. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Ron Grabowski. + public class OnlyOnceErrorHandler : IErrorHandler + { + /// + /// Initializes a new instance of the class. + /// Default Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public OnlyOnceErrorHandler() + { + this.m_prefix = string.Empty; + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The prefix to use for each message. + /// + /// + /// Initializes a new instance of the class + /// with the specified prefix. + /// + /// + public OnlyOnceErrorHandler(string prefix) + { + this.m_prefix = prefix; + } + + /// + /// Reset the error handler back to its initial disabled state. + /// + public void Reset() + { + this.m_enabledDateUtc = DateTime.MinValue; + this.m_errorCode = ErrorCode.GenericFailure; + this.m_exception = null; + this.m_message = null; + this.m_firstTime = true; + } + + /// + /// Log an Error. + /// + /// The error message. + /// The exception. + /// The internal error code. + /// + /// + /// Invokes if and only if this is the first error or the first error after has been called. + /// + /// + public void Error(string message, Exception e, ErrorCode errorCode) + { + if (this.m_firstTime) + { + this.FirstError(message, e, errorCode); + } + } /// - /// Log the very first error + /// Log the very first error. /// /// The error message. /// The exception. @@ -124,164 +115,154 @@ public void Error(string message, Exception e, ErrorCode errorCode) /// Sends the error information to 's Error method. /// /// - public virtual void FirstError(string message, Exception e, ErrorCode errorCode) { - m_enabledDateUtc = DateTime.UtcNow; - m_errorCode = errorCode; - m_exception = e; - m_message = message; - m_firstTime = false; + public virtual void FirstError(string message, Exception e, ErrorCode errorCode) + { + this.m_enabledDateUtc = DateTime.UtcNow; + this.m_errorCode = errorCode; + this.m_exception = e; + this.m_message = message; + this.m_firstTime = false; - if (LogLog.InternalDebugging && !LogLog.QuietMode) { - LogLog.Error(declaringType, "[" + m_prefix + "] ErrorCode: " + errorCode.ToString() + ". " + message, e); + if (LogLog.InternalDebugging && !LogLog.QuietMode) + { + LogLog.Error(declaringType, "[" + this.m_prefix + "] ErrorCode: " + errorCode.ToString() + ". " + message, e); } } /// - /// Log an Error - /// - /// The error message. - /// The exception. - /// + /// Log an Error. + /// + /// The error message. + /// The exception. + /// /// /// Invokes if and only if this is the first error or the first error after has been called. /// /// - public void Error(string message, Exception e) - { - Error(message, e, ErrorCode.GenericFailure); - } + public void Error(string message, Exception e) + { + this.Error(message, e, ErrorCode.GenericFailure); + } - /// - /// Log an error - /// - /// The error message. - /// + /// + /// Log an error. + /// + /// The error message. + /// /// /// Invokes if and only if this is the first error or the first error after has been called. /// /// - public void Error(string message) - { - Error(message, null, ErrorCode.GenericFailure); - } - - #endregion Implementation of IErrorHandler - - #endregion - - #region Public Instance Properties - - /// - /// Is error logging enabled - /// - /// - /// - /// Is error logging enabled. Logging is only enabled for the - /// first error delivered to the . - /// - /// - public bool IsEnabled - { - get { return m_firstTime; } - } + public void Error(string message) + { + this.Error(message, null, ErrorCode.GenericFailure); + } + + /// + /// Gets a value indicating whether is error logging enabled. + /// + /// + /// + /// Is error logging enabled. Logging is only enabled for the + /// first error delivered to the . + /// + /// + public bool IsEnabled + { + get { return this.m_firstTime; } + } - /// - /// The date the first error that trigged this error handler occurred, or if it has not been triggered. - /// - public DateTime EnabledDate - { - get + /// + /// Gets the date the first error that trigged this error handler occurred, or if it has not been triggered. + /// + public DateTime EnabledDate + { + get { - if (m_enabledDateUtc == DateTime.MinValue) return DateTime.MinValue; - return m_enabledDateUtc.ToLocalTime(); + if (this.m_enabledDateUtc == DateTime.MinValue) + { + return DateTime.MinValue; + } + + return this.m_enabledDateUtc.ToLocalTime(); } - } + } /// - /// The UTC date the first error that trigged this error handler occured, or if it has not been triggered. + /// Gets the UTC date the first error that trigged this error handler occured, or if it has not been triggered. /// public DateTime EnabledDateUtc { - get { return m_enabledDateUtc; } + get { return this.m_enabledDateUtc; } } - /// - /// The message from the first error that trigged this error handler. - /// - public string ErrorMessage - { - get { return m_message; } - } - - /// - /// The exception from the first error that trigged this error handler. - /// - /// - /// May be . - /// - public Exception Exception - { - get { return m_exception; } - } - - /// - /// The error code from the first error that trigged this error handler. - /// - /// - /// Defaults to - /// - public ErrorCode ErrorCode - { - get { return m_errorCode; } - } - - #endregion - - #region Private Instance Fields - - /// - /// The UTC date the error was recorded. - /// - private DateTime m_enabledDateUtc; - - /// - /// Flag to indicate if it is the first error - /// - private bool m_firstTime = true; - - /// - /// The message recorded during the first error. - /// - private string m_message = null; + /// + /// Gets the message from the first error that trigged this error handler. + /// + public string ErrorMessage + { + get { return this.m_message; } + } - /// - /// The exception recorded during the first error. - /// - private Exception m_exception = null; + /// + /// Gets the exception from the first error that trigged this error handler. + /// + /// + /// May be . + /// + public Exception Exception + { + get { return this.m_exception; } + } - /// - /// The error code recorded during the first error. - /// - private ErrorCode m_errorCode = ErrorCode.GenericFailure; + /// + /// Gets the error code from the first error that trigged this error handler. + /// + /// + /// Defaults to . + /// + public ErrorCode ErrorCode + { + get { return this.m_errorCode; } + } + + /// + /// The UTC date the error was recorded. + /// + private DateTime m_enabledDateUtc; - /// - /// String to prefix each message with - /// - private readonly string m_prefix; + /// + /// Flag to indicate if it is the first error. + /// + private bool m_firstTime = true; - #endregion Private Instance Fields + /// + /// The message recorded during the first error. + /// + private string m_message = null; - #region Private Static Fields + /// + /// The exception recorded during the first error. + /// + private Exception m_exception = null; - /// - /// The fully qualified type of the OnlyOnceErrorHandler class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(OnlyOnceErrorHandler); + /// + /// The error code recorded during the first error. + /// + private ErrorCode m_errorCode = ErrorCode.GenericFailure; - #endregion - } + /// + /// String to prefix each message with. + /// + private readonly string m_prefix; + + /// + /// The fully qualified type of the OnlyOnceErrorHandler class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(OnlyOnceErrorHandler); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs index baa0814087b..f3af76ea8d2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs @@ -1,618 +1,612 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Globalization; -using System.Reflection; -using System.Text; - -using log4net.Core; -using log4net.Util.TypeConverters; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// A convenience class to convert property values to specific types. - /// - /// - /// - /// Utility functions for converting types and parsing values. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class OptionConverter - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private OptionConverter() - { - } - - #endregion Private Instance Constructors - - #region Public Static Methods - -// /// -// /// Concatenates two string arrays. -// /// -// /// Left array. -// /// Right array. -// /// Array containing both left and right arrays. -// public static string[] ConcatenateArrays(string[] l, string[] r) -// { -// return (string[])ConcatenateArrays(l, r); -// } - -// /// -// /// Concatenates two arrays. -// /// -// /// Left array -// /// Right array -// /// Array containing both left and right arrays. -// public static Array ConcatenateArrays(Array l, Array r) -// { -// if (l == null) -// { -// throw new ArgumentNullException("l"); -// } -// if (r == null) -// { -// throw new ArgumentNullException("r"); -// } -// -// int len = l.Length + r.Length; -// Array a = Array.CreateInstance(l.GetType(), len); -// -// Array.Copy(l, 0, a, 0, l.Length); -// Array.Copy(r, 0, a, l.Length, r.Length); -// -// return a; -// } - -// /// -// /// Converts string escape characters back to their correct values. -// /// -// /// String to convert. -// /// Converted result. -// public static string ConvertSpecialChars(string s) -// { -// if (s == null) -// { -// throw new ArgumentNullException("s"); -// } -// char c; -// int len = s.Length; -// StringBuilder buf = new StringBuilder(len); -// -// int i = 0; -// while(i < len) -// { -// c = s[i++]; -// if (c == '\\') -// { -// c = s[i++]; -// if (c == 'n') c = '\n'; -// else if (c == 'r') c = '\r'; -// else if (c == 't') c = '\t'; -// else if (c == 'f') c = '\f'; -// else if (c == '\b') c = '\b'; -// else if (c == '\"') c = '\"'; -// else if (c == '\'') c = '\''; -// else if (c == '\\') c = '\\'; -// } -// buf.Append(c); -// } -// return buf.ToString(); -// } - - /// - /// Converts a string to a value. - /// - /// String to convert. - /// The default value. - /// The value of . - /// - /// - /// If is "true", then true is returned. - /// If is "false", then false is returned. - /// Otherwise, is returned. - /// - /// - public static bool ToBoolean(string argValue, bool defaultValue) - { - if (argValue != null && argValue.Length > 0) - { - try - { - return bool.Parse(argValue); - } - catch(Exception e) - { - LogLog.Error(declaringType, "[" + argValue + "] is not in proper bool form.", e); - } - } - return defaultValue; - } - -// /// -// /// Converts a string to an integer. -// /// -// /// String to convert. -// /// The default value. -// /// The value of . -// /// -// /// -// /// is returned when -// /// cannot be converted to a value. -// /// -// /// -// public static int ToInt(string argValue, int defaultValue) -// { -// if (argValue != null) -// { -// string s = argValue.Trim(); -// try -// { -// return int.Parse(s, NumberFormatInfo.InvariantInfo); -// } -// catch (Exception e) -// { -// LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e); -// } -// } -// return defaultValue; -// } - - /// - /// Parses a file size into a number. - /// - /// String to parse. - /// The default value. - /// The value of . - /// - /// - /// Parses a file size of the form: number[KB|MB|GB] into a - /// long value. It is scaled with the appropriate multiplier. - /// - /// - /// is returned when - /// cannot be converted to a value. - /// - /// - public static long ToFileSize(string argValue, long defaultValue) - { - if (argValue == null) - { - return defaultValue; - } - - string s = argValue.Trim().ToUpper(CultureInfo.InvariantCulture); - long multiplier = 1; - int index; - - if ((index = s.IndexOf("KB")) != -1) - { - multiplier = 1024; - s = s.Substring(0, index); - } - else if ((index = s.IndexOf("MB")) != -1) - { - multiplier = 1024 * 1024; - s = s.Substring(0, index); - } - else if ((index = s.IndexOf("GB")) != -1) - { - multiplier = 1024 * 1024 * 1024; - s = s.Substring(0, index); - } - if (s != null) - { - // Try again to remove whitespace between the number and the size specifier - s = s.Trim(); - - long longVal; - if (SystemInfo.TryParse(s, out longVal)) - { - return longVal * multiplier; - } - else - { - LogLog.Error(declaringType, "OptionConverter: ["+ s +"] is not in the correct file size syntax."); - } - } - return defaultValue; - } - - /// - /// Converts a string to an object. - /// - /// The target type to convert to. - /// The string to convert to an object. - /// - /// The object converted from a string or null when the - /// conversion failed. - /// - /// - /// - /// Converts a string to an object. Uses the converter registry to try - /// to convert the string value into the specified target type. - /// - /// - public static object ConvertStringTo(Type target, string txt) - { - if (target == null) - { - throw new ArgumentNullException("target"); - } - - // If we want a string we already have the correct type - if (typeof(string) == target || typeof(object) == target) - { - return txt; - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Globalization; + using System.Reflection; + using System.Text; + + using log4net.Core; + using log4net.Util.TypeConverters; + + /// + /// A convenience class to convert property values to specific types. + /// + /// + /// + /// Utility functions for converting types and parsing values. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class OptionConverter + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private OptionConverter() + { + } + + // /// + // /// Concatenates two string arrays. + // /// + // /// Left array. + // /// Right array. + // /// Array containing both left and right arrays. + // public static string[] ConcatenateArrays(string[] l, string[] r) + // { + // return (string[])ConcatenateArrays(l, r); + // } + + // /// + // /// Concatenates two arrays. + // /// + // /// Left array + // /// Right array + // /// Array containing both left and right arrays. + // public static Array ConcatenateArrays(Array l, Array r) + // { + // if (l == null) + // { + // throw new ArgumentNullException("l"); + // } + // if (r == null) + // { + // throw new ArgumentNullException("r"); + // } + // + // int len = l.Length + r.Length; + // Array a = Array.CreateInstance(l.GetType(), len); + // + // Array.Copy(l, 0, a, 0, l.Length); + // Array.Copy(r, 0, a, l.Length, r.Length); + // + // return a; + // } + + // /// + // /// Converts string escape characters back to their correct values. + // /// + // /// String to convert. + // /// Converted result. + // public static string ConvertSpecialChars(string s) + // { + // if (s == null) + // { + // throw new ArgumentNullException("s"); + // } + // char c; + // int len = s.Length; + // StringBuilder buf = new StringBuilder(len); + // + // int i = 0; + // while(i < len) + // { + // c = s[i++]; + // if (c == '\\') + // { + // c = s[i++]; + // if (c == 'n') c = '\n'; + // else if (c == 'r') c = '\r'; + // else if (c == 't') c = '\t'; + // else if (c == 'f') c = '\f'; + // else if (c == '\b') c = '\b'; + // else if (c == '\"') c = '\"'; + // else if (c == '\'') c = '\''; + // else if (c == '\\') c = '\\'; + // } + // buf.Append(c); + // } + // return buf.ToString(); + // } + + /// + /// Converts a string to a value. + /// + /// String to convert. + /// The default value. + /// The value of . + /// + /// + /// If is "true", then true is returned. + /// If is "false", then false is returned. + /// Otherwise, is returned. + /// + /// + public static bool ToBoolean(string argValue, bool defaultValue) + { + if (argValue != null && argValue.Length > 0) + { + try + { + return bool.Parse(argValue); + } + catch (Exception e) + { + LogLog.Error(declaringType, "[" + argValue + "] is not in proper bool form.", e); + } + } + + return defaultValue; + } + + // /// + // /// Converts a string to an integer. + // /// + // /// String to convert. + // /// The default value. + // /// The value of . + // /// + // /// + // /// is returned when + // /// cannot be converted to a value. + // /// + // /// + // public static int ToInt(string argValue, int defaultValue) + // { + // if (argValue != null) + // { + // string s = argValue.Trim(); + // try + // { + // return int.Parse(s, NumberFormatInfo.InvariantInfo); + // } + // catch (Exception e) + // { + // LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e); + // } + // } + // return defaultValue; + // } + + /// + /// Parses a file size into a number. + /// + /// String to parse. + /// The default value. + /// The value of . + /// + /// + /// Parses a file size of the form: number[KB|MB|GB] into a + /// long value. It is scaled with the appropriate multiplier. + /// + /// + /// is returned when + /// cannot be converted to a value. + /// + /// + public static long ToFileSize(string argValue, long defaultValue) + { + if (argValue == null) + { + return defaultValue; + } + + string s = argValue.Trim().ToUpper(CultureInfo.InvariantCulture); + long multiplier = 1; + int index; + + if ((index = s.IndexOf("KB")) != -1) + { + multiplier = 1024; + s = s.Substring(0, index); + } + else if ((index = s.IndexOf("MB")) != -1) + { + multiplier = 1024 * 1024; + s = s.Substring(0, index); + } + else if ((index = s.IndexOf("GB")) != -1) + { + multiplier = 1024 * 1024 * 1024; + s = s.Substring(0, index); + } + + if (s != null) + { + // Try again to remove whitespace between the number and the size specifier + s = s.Trim(); + + long longVal; + if (SystemInfo.TryParse(s, out longVal)) + { + return longVal * multiplier; + } + else + { + LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in the correct file size syntax."); + } + } + + return defaultValue; + } - // First lets try to find a type converter - IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target); - if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) - { - // Found appropriate converter - return typeConverter.ConvertFrom(txt); - } - else - { + /// + /// Converts a string to an object. + /// + /// The target type to convert to. + /// The string to convert to an object. + /// + /// The object converted from a string or null when the + /// conversion failed. + /// + /// + /// + /// Converts a string to an object. Uses the converter registry to try + /// to convert the string value into the specified target type. + /// + /// + public static object ConvertStringTo(Type target, string txt) + { + if (target == null) + { + throw new ArgumentNullException("target"); + } + + // If we want a string we already have the correct type + if (typeof(string) == target || typeof(object) == target) + { + return txt; + } + + // First lets try to find a type converter + IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target); + if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) + { + // Found appropriate converter + return typeConverter.ConvertFrom(txt); + } + else + { #if NETSTANDARD1_3 if (target.GetTypeInfo().IsEnum) #else - if (target.IsEnum) + if (target.IsEnum) #endif - { - // Target type is an enum. - - // Use the Enum.Parse(EnumType, string) method to get the enum value - return ParseEnum(target, txt, true); - } - else - { - // We essentially make a guess that to convert from a string - // to an arbitrary type T there will be a static method defined on type T called Parse - // that will take an argument of type string. i.e. T.Parse(string)->T we call this - // method to convert the string to the type required by the property. - System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] {typeof(string)}); - if (meth != null) - { - // Call the Parse method + { + // Target type is an enum. + + // Use the Enum.Parse(EnumType, string) method to get the enum value + return ParseEnum(target, txt, true); + } + else + { + // We essentially make a guess that to convert from a string + // to an arbitrary type T there will be a static method defined on type T called Parse + // that will take an argument of type string. i.e. T.Parse(string)->T we call this + // method to convert the string to the type required by the property. + System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] { typeof(string) }); + if (meth != null) + { + // Call the Parse method #if NETSTANDARD1_3 return meth.Invoke(target, new[] { txt }); #else - return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] {txt}, CultureInfo.InvariantCulture); + return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] { txt }, CultureInfo.InvariantCulture); #endif - } - else - { - // No Parse() method found. - } - } - } - return null; - } - -// /// -// /// Looks up the for the target type. -// /// -// /// The type to lookup the converter for. -// /// The converter for the specified type. -// public static IConvertFrom GetTypeConverter(Type target) -// { -// IConvertFrom converter = ConverterRegistry.GetConverter(target); -// if (converter == null) -// { -// throw new InvalidOperationException("No type converter defined for [" + target + "]"); -// } -// return converter; -// } - - /// - /// Checks if there is an appropriate type conversion from the source type to the target type. - /// - /// The type to convert from. - /// The type to convert to. - /// true if there is a conversion from the source type to the target type. - /// - /// Checks if there is an appropriate type conversion from the source type to the target type. - /// - /// - /// - public static bool CanConvertTypeTo(Type sourceType, Type targetType) - { - if (sourceType == null || targetType == null) - { - return false; - } - - // Check if we can assign directly from the source type to the target type - if (targetType.IsAssignableFrom(sourceType)) - { - return true; - } - - // Look for a To converter - IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); - if (tcSource != null) - { - if (tcSource.CanConvertTo(targetType)) - { - return true; - } - } - - // Look for a From converter - IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); - if (tcTarget != null) - { - if (tcTarget.CanConvertFrom(sourceType)) - { - return true; - } - } - - return false; - } - - /// - /// Converts an object to the target type. - /// - /// The object to convert to the target type. - /// The type to convert to. - /// The converted object. - /// - /// - /// Converts an object to the target type. - /// - /// - public static object ConvertTypeTo(object sourceInstance, Type targetType) - { - Type sourceType = sourceInstance.GetType(); - - // Check if we can assign directly from the source type to the target type - if (targetType.IsAssignableFrom(sourceType)) - { - return sourceInstance; - } - - // Look for a TO converter - IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); - if (tcSource != null) - { - if (tcSource.CanConvertTo(targetType)) - { - return tcSource.ConvertTo(sourceInstance, targetType); - } - } - - // Look for a FROM converter - IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); - if (tcTarget != null) - { - if (tcTarget.CanConvertFrom(sourceType)) - { - return tcTarget.ConvertFrom(sourceInstance); - } - } - - throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance"); - } - -// /// -// /// Finds the value corresponding to in -// /// and then perform variable substitution -// /// on the found value. -// /// -// /// The key to lookup. -// /// The association to use for lookups. -// /// The substituted result. -// public static string FindAndSubst(string key, System.Collections.IDictionary props) -// { -// if (props == null) -// { -// throw new ArgumentNullException("props"); -// } -// -// string v = props[key] as string; -// if (v == null) -// { -// return null; -// } -// -// try -// { -// return SubstituteVariables(v, props); -// } -// catch(Exception e) -// { -// LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e); -// return v; -// } -// } + } + else + { + // No Parse() method found. + } + } + } + + return null; + } + + // /// + // /// Looks up the for the target type. + // /// + // /// The type to lookup the converter for. + // /// The converter for the specified type. + // public static IConvertFrom GetTypeConverter(Type target) + // { + // IConvertFrom converter = ConverterRegistry.GetConverter(target); + // if (converter == null) + // { + // throw new InvalidOperationException("No type converter defined for [" + target + "]"); + // } + // return converter; + // } + + /// + /// Checks if there is an appropriate type conversion from the source type to the target type. + /// + /// The type to convert from. + /// The type to convert to. + /// true if there is a conversion from the source type to the target type. + /// + /// Checks if there is an appropriate type conversion from the source type to the target type. + /// + /// + /// + public static bool CanConvertTypeTo(Type sourceType, Type targetType) + { + if (sourceType == null || targetType == null) + { + return false; + } + + // Check if we can assign directly from the source type to the target type + if (targetType.IsAssignableFrom(sourceType)) + { + return true; + } + + // Look for a To converter + IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); + if (tcSource != null) + { + if (tcSource.CanConvertTo(targetType)) + { + return true; + } + } + + // Look for a From converter + IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); + if (tcTarget != null) + { + if (tcTarget.CanConvertFrom(sourceType)) + { + return true; + } + } + + return false; + } - /// - /// Instantiates an object given a class name. - /// - /// The fully qualified class name of the object to instantiate. - /// The class to which the new object should belong. - /// The object to return in case of non-fulfillment. - /// - /// An instance of the or - /// if the object could not be instantiated. - /// - /// - /// - /// Checks that the is a subclass of - /// . If that test fails or the object could - /// not be instantiated, then is returned. - /// - /// - public static object InstantiateByClassName(string className, Type superClass, object defaultValue) - { - if (className != null) - { - try - { + /// + /// Converts an object to the target type. + /// + /// The object to convert to the target type. + /// The type to convert to. + /// The converted object. + /// + /// + /// Converts an object to the target type. + /// + /// + public static object ConvertTypeTo(object sourceInstance, Type targetType) + { + Type sourceType = sourceInstance.GetType(); + + // Check if we can assign directly from the source type to the target type + if (targetType.IsAssignableFrom(sourceType)) + { + return sourceInstance; + } + + // Look for a TO converter + IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); + if (tcSource != null) + { + if (tcSource.CanConvertTo(targetType)) + { + return tcSource.ConvertTo(sourceInstance, targetType); + } + } + + // Look for a FROM converter + IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); + if (tcTarget != null) + { + if (tcTarget.CanConvertFrom(sourceType)) + { + return tcTarget.ConvertFrom(sourceInstance); + } + } + + throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance"); + } + + // /// + // /// Finds the value corresponding to in + // /// and then perform variable substitution + // /// on the found value. + // /// + // /// The key to lookup. + // /// The association to use for lookups. + // /// The substituted result. + // public static string FindAndSubst(string key, System.Collections.IDictionary props) + // { + // if (props == null) + // { + // throw new ArgumentNullException("props"); + // } + // + // string v = props[key] as string; + // if (v == null) + // { + // return null; + // } + // + // try + // { + // return SubstituteVariables(v, props); + // } + // catch(Exception e) + // { + // LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e); + // return v; + // } + // } + + /// + /// Instantiates an object given a class name. + /// + /// The fully qualified class name of the object to instantiate. + /// The class to which the new object should belong. + /// The object to return in case of non-fulfillment. + /// + /// An instance of the or + /// if the object could not be instantiated. + /// + /// + /// + /// Checks that the is a subclass of + /// . If that test fails or the object could + /// not be instantiated, then is returned. + /// + /// + public static object InstantiateByClassName(string className, Type superClass, object defaultValue) + { + if (className != null) + { + try + { #if NETSTANDARD1_3 Type classObj = SystemInfo.GetTypeFromString(superClass.GetTypeInfo().Assembly, className, true, true); #else - Type classObj = SystemInfo.GetTypeFromString(className, true, true); + Type classObj = SystemInfo.GetTypeFromString(className, true, true); #endif - if (!superClass.IsAssignableFrom(classObj)) - { - LogLog.Error(declaringType, "OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable."); - return defaultValue; - } - return Activator.CreateInstance(classObj); - } - catch (Exception e) - { - LogLog.Error(declaringType, "Could not instantiate class [" + className + "].", e); - } - } - return defaultValue; - } - - /// - /// Performs variable substitution in string from the - /// values of keys found in . - /// - /// The string on which variable substitution is performed. - /// The dictionary to use to lookup variables. - /// The result of the substitutions. - /// - /// - /// The variable substitution delimiters are ${ and }. - /// - /// - /// For example, if props contains key=value, then the call - /// - /// - /// - /// string s = OptionConverter.SubstituteVariables("Value of key is ${key}."); - /// - /// - /// - /// will set the variable s to "Value of key is value.". - /// - /// - /// If no value could be found for the specified key, then substitution - /// defaults to an empty string. - /// - /// - /// For example, if system properties contains no value for the key - /// "nonExistentKey", then the call - /// - /// - /// - /// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]"); - /// - /// - /// - /// will set s to "Value of nonExistentKey is []". - /// - /// - /// An Exception is thrown if contains a start - /// delimiter "${" which is not balanced by a stop delimiter "}". - /// - /// - public static string SubstituteVariables(string value, System.Collections.IDictionary props) - { - StringBuilder buf = new StringBuilder(); + if (!superClass.IsAssignableFrom(classObj)) + { + LogLog.Error(declaringType, "OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable."); + return defaultValue; + } + + return Activator.CreateInstance(classObj); + } + catch (Exception e) + { + LogLog.Error(declaringType, "Could not instantiate class [" + className + "].", e); + } + } + + return defaultValue; + } - int i = 0; - int j, k; - - while(true) - { - j = value.IndexOf(DELIM_START, i); - if (j == -1) - { - if (i == 0) - { - return value; - } - else - { - buf.Append(value.Substring(i, value.Length - i)); - return buf.ToString(); - } - } - else - { - buf.Append(value.Substring(i, j - i)); - k = value.IndexOf(DELIM_STOP, j); - if (k == -1) - { - throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]"); - } - else - { - j += DELIM_START_LEN; - string key = value.Substring(j, k - j); - - string replacement = props[key] as string; - - if (replacement != null) - { - buf.Append(replacement); - } - i = k + DELIM_STOP_LEN; - } - } - } - } - - #endregion Public Static Methods - - #region Private Static Methods - - /// - /// Converts the string representation of the name or numeric value of one or - /// more enumerated constants to an equivalent enumerated object. - /// - /// The type to convert to. - /// The enum string value. - /// If true, ignore case; otherwise, regard case. - /// An object of type whose value is represented by . - private static object ParseEnum(System.Type enumType, string value, bool ignoreCase) - { + /// + /// Performs variable substitution in string from the + /// values of keys found in . + /// + /// The string on which variable substitution is performed. + /// The dictionary to use to lookup variables. + /// The result of the substitutions. + /// + /// + /// The variable substitution delimiters are ${ and }. + /// + /// + /// For example, if props contains key=value, then the call. + /// + /// + /// + /// string s = OptionConverter.SubstituteVariables("Value of key is ${key}."); + /// + /// + /// + /// will set the variable s to "Value of key is value.". + /// + /// + /// If no value could be found for the specified key, then substitution + /// defaults to an empty string. + /// + /// + /// For example, if system properties contains no value for the key + /// "nonExistentKey", then the call. + /// + /// + /// + /// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]"); + /// + /// + /// + /// will set s to "Value of nonExistentKey is []". + /// + /// + /// An Exception is thrown if contains a start + /// delimiter "${" which is not balanced by a stop delimiter "}". + /// + /// + public static string SubstituteVariables(string value, System.Collections.IDictionary props) + { + StringBuilder buf = new StringBuilder(); + + int i = 0; + int j, k; + + while (true) + { + j = value.IndexOf(DELIM_START, i); + if (j == -1) + { + if (i == 0) + { + return value; + } + else + { + buf.Append(value.Substring(i, value.Length - i)); + return buf.ToString(); + } + } + else + { + buf.Append(value.Substring(i, j - i)); + k = value.IndexOf(DELIM_STOP, j); + if (k == -1) + { + throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]"); + } + else + { + j += DELIM_START_LEN; + string key = value.Substring(j, k - j); + + string replacement = props[key] as string; + + if (replacement != null) + { + buf.Append(replacement); + } + + i = k + DELIM_STOP_LEN; + } + } + } + } + + /// + /// Converts the string representation of the name or numeric value of one or + /// more enumerated constants to an equivalent enumerated object. + /// + /// The type to convert to. + /// The enum string value. + /// If true, ignore case; otherwise, regard case. + /// An object of type whose value is represented by . + private static object ParseEnum(System.Type enumType, string value, bool ignoreCase) + { #if !NETCF - return Enum.Parse(enumType, value, ignoreCase); + return Enum.Parse(enumType, value, ignoreCase); #else FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); @@ -650,12 +644,8 @@ private static object ParseEnum(System.Type enumType, string value, bool ignoreC } return Enum.ToObject(enumType, retVal); #endif - } - - #endregion Private Static Methods - - #region Private Static Fields - + } + /// /// The fully qualified type of the OptionConverter class. /// @@ -663,13 +653,11 @@ private static object ParseEnum(System.Type enumType, string value, bool ignoreC /// Used by the internal logger to record the Type of the /// log message. /// - private readonly static Type declaringType = typeof(OptionConverter); - - private const string DELIM_START = "${"; - private const char DELIM_STOP = '}'; - private const int DELIM_START_LEN = 2; - private const int DELIM_STOP_LEN = 1; + private static readonly Type declaringType = typeof(OptionConverter); - #endregion Private Static Fields - } + private const string DELIM_START = "${"; + private const char DELIM_STOP = '}'; + private const int DELIM_START_LEN = 2; + private const int DELIM_STOP_LEN = 1; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs index 0580738a888..34c2d338556 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs @@ -1,197 +1,182 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System.Text; -using System.IO; -using System.Collections; - -using log4net.Util; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Abstract class that provides the formatting functionality that - /// derived classes need. - /// - /// - /// - /// Conversion specifiers in a conversion patterns are parsed to - /// individual PatternConverters. Each of which is responsible for - /// converting a logging event in a converter specific manner. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public abstract class PatternConverter - { - #region Protected Instance Constructors - - /// - /// Protected constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - protected PatternConverter() - { - } - - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Get the next pattern converter in the chain - /// - /// - /// the next pattern converter in the chain - /// - /// - /// - /// Get the next pattern converter in the chain - /// - /// - public virtual PatternConverter Next - { - get { return m_next; } - } - - /// - /// Gets or sets the formatting info for this converter - /// - /// - /// The formatting info for this converter - /// - /// - /// - /// Gets or sets the formatting info for this converter - /// - /// - public virtual FormattingInfo FormattingInfo - { - get { return new FormattingInfo(m_min, m_max, m_leftAlign); } - set - { - m_min = value.Min; - m_max = value.Max; - m_leftAlign = value.LeftAlign; - } - } - - /// - /// Gets or sets the option value for this converter - /// - /// - /// The option for this converter - /// - /// - /// - /// Gets or sets the option value for this converter - /// - /// - public virtual string Option - { - get { return m_option; } - set { m_option = value; } - } - - #endregion Public Instance Properties - - #region Protected Abstract Methods - - /// - /// Evaluate this pattern converter and write the output to a writer. - /// - /// that will receive the formatted result. - /// The state object on which the pattern converter should be executed. - /// - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the appropriate way. - /// - /// - abstract protected void Convert(TextWriter writer, object state); - - #endregion Protected Abstract Methods + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System.Collections; + using System.IO; + using System.Text; + + using log4net.Repository; + using log4net.Util; + + /// + /// Abstract class that provides the formatting functionality that + /// derived classes need. + /// + /// + /// + /// Conversion specifiers in a conversion patterns are parsed to + /// individual PatternConverters. Each of which is responsible for + /// converting a logging event in a converter specific manner. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public abstract class PatternConverter + { + /// + /// Initializes a new instance of the class. + /// Protected constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + protected PatternConverter() + { + } + + /// + /// Gets get the next pattern converter in the chain. + /// + /// + /// the next pattern converter in the chain. + /// + /// + /// + /// Get the next pattern converter in the chain. + /// + /// + public virtual PatternConverter Next + { + get { return this.m_next; } + } - #region Public Instance Methods + /// + /// Gets or sets the formatting info for this converter. + /// + /// + /// The formatting info for this converter. + /// + /// + /// + /// Gets or sets the formatting info for this converter. + /// + /// + public virtual FormattingInfo FormattingInfo + { + get { return new FormattingInfo(this.m_min, this.m_max, this.m_leftAlign); } + + set + { + this.m_min = value.Min; + this.m_max = value.Max; + this.m_leftAlign = value.LeftAlign; + } + } - /// - /// Set the next pattern converter in the chains - /// - /// the pattern converter that should follow this converter in the chain - /// the next converter - /// - /// - /// The PatternConverter can merge with its neighbor during this method (or a sub class). - /// Therefore the return value may or may not be the value of the argument passed in. - /// - /// - public virtual PatternConverter SetNext(PatternConverter patternConverter) - { - m_next = patternConverter; - return m_next; - } + /// + /// Gets or sets the option value for this converter. + /// + /// + /// The option for this converter. + /// + /// + /// + /// Gets or sets the option value for this converter. + /// + /// + public virtual string Option + { + get { return this.m_option; } + set { this.m_option = value; } + } + + /// + /// Evaluate this pattern converter and write the output to a writer. + /// + /// that will receive the formatted result. + /// The state object on which the pattern converter should be executed. + /// + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the appropriate way. + /// + /// + protected abstract void Convert(TextWriter writer, object state); + + /// + /// Set the next pattern converter in the chains. + /// + /// the pattern converter that should follow this converter in the chain. + /// the next converter. + /// + /// + /// The PatternConverter can merge with its neighbor during this method (or a sub class). + /// Therefore the return value may or may not be the value of the argument passed in. + /// + /// + public virtual PatternConverter SetNext(PatternConverter patternConverter) + { + this.m_next = patternConverter; + return this.m_next; + } - /// - /// Write the pattern converter to the writer with appropriate formatting - /// - /// that will receive the formatted result. - /// The state object on which the pattern converter should be executed. - /// - /// - /// This method calls to allow the subclass to perform - /// appropriate conversion of the pattern converter. If formatting options have - /// been specified via the then this method will - /// apply those formattings before writing the output. - /// - /// - virtual public void Format(TextWriter writer, object state) - { - if (m_min < 0 && m_max == int.MaxValue) - { - // Formatting options are not in use - Convert(writer, state); - } - else - { + /// + /// Write the pattern converter to the writer with appropriate formatting. + /// + /// that will receive the formatted result. + /// The state object on which the pattern converter should be executed. + /// + /// + /// This method calls to allow the subclass to perform + /// appropriate conversion of the pattern converter. If formatting options have + /// been specified via the then this method will + /// apply those formattings before writing the output. + /// + /// + public virtual void Format(TextWriter writer, object state) + { + if (this.m_min < 0 && this.m_max == int.MaxValue) + { + // Formatting options are not in use + this.Convert(writer, state); + } + else + { string msg = null; int len; - lock (m_formatWriter) + lock (this.m_formatWriter) { - m_formatWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); + this.m_formatWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); - Convert(m_formatWriter, state); + this.Convert(this.m_formatWriter, state); - StringBuilder buf = m_formatWriter.GetStringBuilder(); + StringBuilder buf = this.m_formatWriter.GetStringBuilder(); len = buf.Length; - if (len > m_max) + if (len > this.m_max) { - msg = buf.ToString(len - m_max, m_max); - len = m_max; + msg = buf.ToString(len - this.m_max, this.m_max); + len = this.m_max; } else { @@ -199,203 +184,193 @@ virtual public void Format(TextWriter writer, object state) } } - if (len < m_min) - { - if (m_leftAlign) - { - writer.Write(msg); - SpacePad(writer, m_min - len); - } - else - { - SpacePad(writer, m_min - len); - writer.Write(msg); - } - } - else - { - writer.Write(msg); - } - } - } - - private static readonly string[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 spaces - " ", // 16 spaces - " " }; // 32 spaces - - /// - /// Fast space padding method. - /// - /// to which the spaces will be appended. - /// The number of spaces to be padded. - /// - /// - /// Fast space padding method. - /// - /// - protected static void SpacePad(TextWriter writer, int length) - { - while(length >= 32) - { - writer.Write(SPACES[5]); - length -= 32; - } - - for(int i = 4; i >= 0; i--) - { - if ((length & (1< - /// The option string to the converter - /// - private string m_option = null; - - private ReusableStringWriter m_formatWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); - - #endregion Private Instance Fields - - #region Constants - - /// - /// Initial buffer size - /// - private const int c_renderBufferSize = 256; - - /// - /// Maximum buffer size before it is recycled - /// - private const int c_renderBufferMaxCapacity = 1024; - - #endregion - - #region Static Methods + if (len < this.m_min) + { + if (this.m_leftAlign) + { + writer.Write(msg); + SpacePad(writer, this.m_min - len); + } + else + { + SpacePad(writer, this.m_min - len); + writer.Write(msg); + } + } + else + { + writer.Write(msg); + } + } + } - /// - /// Write an dictionary to a - /// - /// the writer to write to - /// a to use for object conversion - /// the value to write to the writer - /// - /// - /// Writes the to a writer in the form: - /// - /// - /// {key1=value1, key2=value2, key3=value3} - /// - /// - /// If the specified - /// is not null then it is used to render the key and value to text, otherwise - /// the object's ToString method is called. - /// - /// - protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value) - { - WriteDictionary(writer, repository, value.GetEnumerator()); - } + private static readonly string[] SPACES = + { + " ", " ", " ", " ", // 1,2,4,8 spaces + " ", // 16 spaces + " ", + }; // 32 spaces - /// - /// Write an dictionary to a - /// - /// the writer to write to - /// a to use for object conversion - /// the value to write to the writer - /// - /// - /// Writes the to a writer in the form: - /// - /// - /// {key1=value1, key2=value2, key3=value3} - /// - /// - /// If the specified - /// is not null then it is used to render the key and value to text, otherwise - /// the object's ToString method is called. - /// - /// - protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value) - { - writer.Write("{"); + /// + /// Fast space padding method. + /// + /// to which the spaces will be appended. + /// The number of spaces to be padded. + /// + /// + /// Fast space padding method. + /// + /// + protected static void SpacePad(TextWriter writer, int length) + { + while (length >= 32) + { + writer.Write(SPACES[5]); + length -= 32; + } + + for (int i = 4; i >= 0; i--) + { + if ((length & (1 << i)) != 0) + { + writer.Write(SPACES[i]); + } + } + } + + private PatternConverter m_next; + private int m_min = -1; + private int m_max = int.MaxValue; + private bool m_leftAlign = false; - bool first = true; + /// + /// The option string to the converter. + /// + private string m_option = null; - // Write out all the dictionary key value pairs - while (value.MoveNext()) - { - if (first) - { - first = false; - } - else - { - writer.Write(", "); - } - WriteObject(writer, repository, value.Key); - writer.Write("="); - WriteObject(writer, repository, value.Value); - } + private ReusableStringWriter m_formatWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); + + /// + /// Initial buffer size. + /// + private const int c_renderBufferSize = 256; - writer.Write("}"); - } + /// + /// Maximum buffer size before it is recycled. + /// + private const int c_renderBufferMaxCapacity = 1024; + + /// + /// Write an dictionary to a . + /// + /// the writer to write to. + /// a to use for object conversion. + /// the value to write to the writer. + /// + /// + /// Writes the to a writer in the form: + /// + /// + /// {key1=value1, key2=value2, key3=value3} + /// + /// + /// If the specified + /// is not null then it is used to render the key and value to text, otherwise + /// the object's ToString method is called. + /// + /// + protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value) + { + WriteDictionary(writer, repository, value.GetEnumerator()); + } - /// - /// Write an object to a - /// - /// the writer to write to - /// a to use for object conversion - /// the value to write to the writer - /// - /// - /// Writes the Object to a writer. If the specified - /// is not null then it is used to render the object to text, otherwise - /// the object's ToString method is called. - /// - /// - protected static void WriteObject(TextWriter writer, ILoggerRepository repository, object value) - { - if (repository != null) - { - repository.RendererMap.FindAndRender(value, writer); - } - else - { - // Don't have a repository to render with so just have to rely on ToString - if (value == null) - { - writer.Write( SystemInfo.NullText ); - } - else - { - writer.Write( value.ToString() ); - } - } - } + /// + /// Write an dictionary to a . + /// + /// the writer to write to. + /// a to use for object conversion. + /// the value to write to the writer. + /// + /// + /// Writes the to a writer in the form: + /// + /// + /// {key1=value1, key2=value2, key3=value3} + /// + /// + /// If the specified + /// is not null then it is used to render the key and value to text, otherwise + /// the object's ToString method is called. + /// + /// + protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value) + { + writer.Write("{"); + + bool first = true; + + // Write out all the dictionary key value pairs + while (value.MoveNext()) + { + if (first) + { + first = false; + } + else + { + writer.Write(", "); + } + + WriteObject(writer, repository, value.Key); + writer.Write("="); + WriteObject(writer, repository, value.Value); + } - #endregion + writer.Write("}"); + } + /// + /// Write an object to a . + /// + /// the writer to write to. + /// a to use for object conversion. + /// the value to write to the writer. + /// + /// + /// Writes the Object to a writer. If the specified + /// is not null then it is used to render the object to text, otherwise + /// the object's ToString method is called. + /// + /// + protected static void WriteObject(TextWriter writer, ILoggerRepository repository, object value) + { + if (repository != null) + { + repository.RendererMap.FindAndRender(value, writer); + } + else + { + // Don't have a repository to render with so just have to rely on ToString + if (value == null) + { + writer.Write(SystemInfo.NullText); + } + else + { + writer.Write(value.ToString()); + } + } + } + private PropertiesDictionary properties; /// - /// + /// /// public PropertiesDictionary Properties - { - get { return properties; } - set { properties = value; } - } - } + { + get { return this.properties; } + set { this.properties = value; } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs index d2b40bc8d5d..cc6b5cbf447 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs @@ -1,439 +1,405 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Globalization; - -using log4net.Core; -using log4net.Layout; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Most of the work of the class - /// is delegated to the PatternParser class. - /// - /// - /// - /// The PatternParser processes a pattern string and - /// returns a chain of objects. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class PatternParser - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// The pattern to parse. - /// - /// - /// Initializes a new instance of the class - /// with the specified pattern string. - /// - /// - public PatternParser(string pattern) - { - m_pattern = pattern; - } - - #endregion Public Instance Constructors - - #region Public Instance Methods - - /// - /// Parses the pattern into a chain of pattern converters. - /// - /// The head of a chain of pattern converters. - /// - /// - /// Parses the pattern into a chain of pattern converters. - /// - /// - public PatternConverter Parse() - { - string[] converterNamesCache = BuildCache(); - - ParseInternal(m_pattern, converterNamesCache); - - return m_head; - } - - #endregion Public Instance Methods - - #region Public Instance Properties - - /// - /// Get the converter registry used by this parser - /// - /// - /// The converter registry used by this parser - /// - /// - /// - /// Get the converter registry used by this parser - /// - /// - public Hashtable PatternConverters - { - get { return m_patternConverters; } - } - - #endregion Public Instance Properties - - #region Private Instance Methods - - /// - /// Build the unified cache of converters from the static and instance maps - /// - /// the list of all the converter names - /// - /// - /// Build the unified cache of converters from the static and instance maps - /// - /// - private string[] BuildCache() - { - string[] converterNamesCache = new string[m_patternConverters.Keys.Count]; - m_patternConverters.Keys.CopyTo(converterNamesCache, 0); - - // sort array so that longer strings come first - Array.Sort(converterNamesCache, 0, converterNamesCache.Length, StringLengthComparer.Instance); - - return converterNamesCache; - } - - #region StringLengthComparer - - /// - /// Sort strings by length - /// - /// - /// - /// that orders strings by string length. - /// The longest strings are placed first - /// - /// - private sealed class StringLengthComparer : IComparer - { - public static readonly StringLengthComparer Instance = new StringLengthComparer(); - - private StringLengthComparer() - { - } - - #region Implementation of IComparer - - public int Compare(object x, object y) - { - string s1 = x as string; - string s2 = y as string; - - if (s1 == null && s2 == null) - { - return 0; - } - if (s1 == null) - { - return 1; - } - if (s2 == null) - { - return -1; - } - - return s2.Length.CompareTo(s1.Length); - } - - #endregion - } - - #endregion // StringLengthComparer - - /// - /// Internal method to parse the specified pattern to find specified matches - /// - /// the pattern to parse - /// the converter names to match in the pattern - /// - /// - /// The matches param must be sorted such that longer strings come before shorter ones. - /// - /// - private void ParseInternal(string pattern, string[] matches) - { - int offset = 0; - while(offset < pattern.Length) - { - int i = pattern.IndexOf('%', offset); - if (i < 0 || i == pattern.Length - 1) - { - ProcessLiteral(pattern.Substring(offset)); - offset = pattern.Length; - } - else - { - if (pattern[i+1] == '%') - { - // Escaped - ProcessLiteral(pattern.Substring(offset, i - offset + 1)); - offset = i + 2; - } - else - { - ProcessLiteral(pattern.Substring(offset, i - offset)); - offset = i + 1; - - FormattingInfo formattingInfo = new FormattingInfo(); - - // Process formatting options - - // Look for the align flag - if (offset < pattern.Length) - { - if (pattern[offset] == '-') - { - // Seen align flag - formattingInfo.LeftAlign = true; - offset++; - } - } - // Look for the minimum length - while (offset < pattern.Length && char.IsDigit(pattern[offset])) - { - // Seen digit - if (formattingInfo.Min < 0) - { - formattingInfo.Min = 0; - } - - formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); - - offset++; - } - // Look for the separator between min and max - if (offset < pattern.Length) - { - if (pattern[offset] == '.') - { - // Seen separator - offset++; - } - } - // Look for the maximum length - while (offset < pattern.Length && char.IsDigit(pattern[offset])) - { - // Seen digit - if (formattingInfo.Max == int.MaxValue) - { - formattingInfo.Max = 0; - } - - formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); - - offset++; - } - - int remainingStringLength = pattern.Length - offset; - - // Look for pattern - for(int m=0; m - /// Process a parsed literal - /// - /// the literal text - private void ProcessLiteral(string text) - { - if (text.Length > 0) - { - // Convert into a pattern - ProcessConverter("literal", text, new FormattingInfo()); - } - } - - /// - /// Process a parsed converter pattern - /// - /// the name of the converter - /// the optional option for the converter - /// the formatting info for the converter - private void ProcessConverter(string converterName, string option, FormattingInfo formattingInfo) - { - LogLog.Debug(declaringType, "Converter ["+converterName+"] Option ["+option+"] Format [min="+formattingInfo.Min+",max="+formattingInfo.Max+",leftAlign="+formattingInfo.LeftAlign+"]"); - - // Lookup the converter type - ConverterInfo converterInfo = (ConverterInfo)m_patternConverters[converterName]; - if (converterInfo == null) - { - LogLog.Error(declaringType, "Unknown converter name ["+converterName+"] in conversion pattern."); - } - else - { - // Create the pattern converter - PatternConverter pc = null; - try - { + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Globalization; + + using log4net.Core; + using log4net.Layout; + + /// + /// Most of the work of the class + /// is delegated to the PatternParser class. + /// + /// + /// + /// The PatternParser processes a pattern string and + /// returns a chain of objects. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class PatternParser + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The pattern to parse. + /// + /// + /// Initializes a new instance of the class + /// with the specified pattern string. + /// + /// + public PatternParser(string pattern) + { + this.m_pattern = pattern; + } + + /// + /// Parses the pattern into a chain of pattern converters. + /// + /// The head of a chain of pattern converters. + /// + /// + /// Parses the pattern into a chain of pattern converters. + /// + /// + public PatternConverter Parse() + { + string[] converterNamesCache = this.BuildCache(); + + this.ParseInternal(this.m_pattern, converterNamesCache); + + return this.m_head; + } + + /// + /// Gets get the converter registry used by this parser. + /// + /// + /// The converter registry used by this parser. + /// + /// + /// + /// Get the converter registry used by this parser. + /// + /// + public Hashtable PatternConverters + { + get { return this.m_patternConverters; } + } + + /// + /// Build the unified cache of converters from the static and instance maps. + /// + /// the list of all the converter names. + /// + /// + /// Build the unified cache of converters from the static and instance maps. + /// + /// + private string[] BuildCache() + { + string[] converterNamesCache = new string[this.m_patternConverters.Keys.Count]; + this.m_patternConverters.Keys.CopyTo(converterNamesCache, 0); + + // sort array so that longer strings come first + Array.Sort(converterNamesCache, 0, converterNamesCache.Length, StringLengthComparer.Instance); + + return converterNamesCache; + } + + /// + /// Sort strings by length. + /// + /// + /// + /// that orders strings by string length. + /// The longest strings are placed first. + /// + /// + private sealed class StringLengthComparer : IComparer + { + public static readonly StringLengthComparer Instance = new StringLengthComparer(); + + private StringLengthComparer() + { + } + + public int Compare(object x, object y) + { + string s1 = x as string; + string s2 = y as string; + + if (s1 == null && s2 == null) + { + return 0; + } + + if (s1 == null) + { + return 1; + } + + if (s2 == null) + { + return -1; + } + + return s2.Length.CompareTo(s1.Length); + } + } + + /// + /// Internal method to parse the specified pattern to find specified matches. + /// + /// the pattern to parse. + /// the converter names to match in the pattern. + /// + /// + /// The matches param must be sorted such that longer strings come before shorter ones. + /// + /// + private void ParseInternal(string pattern, string[] matches) + { + int offset = 0; + while (offset < pattern.Length) + { + int i = pattern.IndexOf('%', offset); + if (i < 0 || i == pattern.Length - 1) + { + this.ProcessLiteral(pattern.Substring(offset)); + offset = pattern.Length; + } + else + { + if (pattern[i + 1] == '%') + { + // Escaped + this.ProcessLiteral(pattern.Substring(offset, i - offset + 1)); + offset = i + 2; + } + else + { + this.ProcessLiteral(pattern.Substring(offset, i - offset)); + offset = i + 1; + + FormattingInfo formattingInfo = new FormattingInfo(); + + // Process formatting options + + // Look for the align flag + if (offset < pattern.Length) + { + if (pattern[offset] == '-') + { + // Seen align flag + formattingInfo.LeftAlign = true; + offset++; + } + } + + // Look for the minimum length + while (offset < pattern.Length && char.IsDigit(pattern[offset])) + { + // Seen digit + if (formattingInfo.Min < 0) + { + formattingInfo.Min = 0; + } + + formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); + + offset++; + } + + // Look for the separator between min and max + if (offset < pattern.Length) + { + if (pattern[offset] == '.') + { + // Seen separator + offset++; + } + } + + // Look for the maximum length + while (offset < pattern.Length && char.IsDigit(pattern[offset])) + { + // Seen digit + if (formattingInfo.Max == int.MaxValue) + { + formattingInfo.Max = 0; + } + + formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); + + offset++; + } + + int remainingStringLength = pattern.Length - offset; + + // Look for pattern + for (int m = 0; m < matches.Length; m++) + { + string key = matches[m]; + + if (key.Length <= remainingStringLength) + { + if (string.Compare(pattern, offset, key, 0, key.Length) == 0) + { + // Found match + offset = offset + matches[m].Length; + + string option = null; + + // Look for option + if (offset < pattern.Length) + { + if (pattern[offset] == '{') + { + // Seen option start + offset++; + + int optEnd = pattern.IndexOf('}', offset); + if (optEnd < 0) + { + // error + } + else + { + option = pattern.Substring(offset, optEnd - offset); + offset = optEnd + 1; + } + } + } + + this.ProcessConverter(matches[m], option, formattingInfo); + break; + } + } + } + } + } + } + } + + /// + /// Process a parsed literal. + /// + /// the literal text. + private void ProcessLiteral(string text) + { + if (text.Length > 0) + { + // Convert into a pattern + this.ProcessConverter("literal", text, new FormattingInfo()); + } + } + + /// + /// Process a parsed converter pattern. + /// + /// the name of the converter. + /// the optional option for the converter. + /// the formatting info for the converter. + private void ProcessConverter(string converterName, string option, FormattingInfo formattingInfo) + { + LogLog.Debug(declaringType, "Converter [" + converterName + "] Option [" + option + "] Format [min=" + formattingInfo.Min + ",max=" + formattingInfo.Max + ",leftAlign=" + formattingInfo.LeftAlign + "]"); + + // Lookup the converter type + ConverterInfo converterInfo = (ConverterInfo)this.m_patternConverters[converterName]; + if (converterInfo == null) + { + LogLog.Error(declaringType, "Unknown converter name [" + converterName + "] in conversion pattern."); + } + else + { + // Create the pattern converter + PatternConverter pc = null; + try + { pc = (PatternConverter)Activator.CreateInstance(converterInfo.Type); - } - catch(Exception createInstanceEx) - { + } + catch (Exception createInstanceEx) + { LogLog.Error(declaringType, "Failed to create instance of Type [" + converterInfo.Type.FullName + "] using default constructor. Exception: " + createInstanceEx.ToString()); - } + } - // formattingInfo variable is an instance variable, occasionally reset - // and used over and over again - pc.FormattingInfo = formattingInfo; - pc.Option = option; + // formattingInfo variable is an instance variable, occasionally reset + // and used over and over again + pc.FormattingInfo = formattingInfo; + pc.Option = option; pc.Properties = converterInfo.Properties; - IOptionHandler optionHandler = pc as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - - AddConverter(pc); - } - } - - /// - /// Resets the internal state of the parser and adds the specified pattern converter - /// to the chain. - /// - /// The pattern converter to add. - private void AddConverter(PatternConverter pc) - { - // Add the pattern converter to the list. - - if (m_head == null) - { - m_head = m_tail = pc; - } - else - { - // Set the next converter on the tail - // Update the tail reference - // note that a converter may combine the 'next' into itself - // and therefore the tail would not change! - m_tail = m_tail.SetNext(pc); - } - } - - #endregion Protected Instance Methods - - #region Private Constants - - private const char ESCAPE_CHAR = '%'; - - #endregion Private Constants - - #region Private Instance Fields - - /// - /// The first pattern converter in the chain - /// - private PatternConverter m_head; - - /// - /// the last pattern converter in the chain - /// - private PatternConverter m_tail; - - /// - /// The pattern - /// - private string m_pattern; - - /// - /// Internal map of converter identifiers to converter types - /// - /// - /// - /// This map overrides the static s_globalRulesRegistry map. - /// - /// - private Hashtable m_patternConverters = new Hashtable(); - - #endregion Private Instance Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the PatternParser class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(PatternParser); - - #endregion Private Static Fields - } + IOptionHandler optionHandler = pc as IOptionHandler; + if (optionHandler != null) + { + optionHandler.ActivateOptions(); + } + + this.AddConverter(pc); + } + } + + /// + /// Resets the internal state of the parser and adds the specified pattern converter + /// to the chain. + /// + /// The pattern converter to add. + private void AddConverter(PatternConverter pc) + { + // Add the pattern converter to the list. + if (this.m_head == null) + { + this.m_head = this.m_tail = pc; + } + else + { + // Set the next converter on the tail + // Update the tail reference + // note that a converter may combine the 'next' into itself + // and therefore the tail would not change! + this.m_tail = this.m_tail.SetNext(pc); + } + } + + private const char ESCAPE_CHAR = '%'; + + /// + /// The first pattern converter in the chain. + /// + private PatternConverter m_head; + + /// + /// the last pattern converter in the chain. + /// + private PatternConverter m_tail; + + /// + /// The pattern. + /// + private string m_pattern; + + /// + /// Internal map of converter identifiers to converter types. + /// + /// + /// + /// This map overrides the static s_globalRulesRegistry map. + /// + /// + private Hashtable m_patternConverters = new Hashtable(); + + /// + /// The fully qualified type of the PatternParser class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(PatternParser); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs index ef07c003ae6..42cba7675f9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs @@ -1,526 +1,520 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.IO; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + + #if NETSTANDARD1_3 using System.Reflection; #endif +using log4net.Core; using log4net.Util; using log4net.Util.PatternStringConverters; -using log4net.Core; namespace log4net.Util { - /// - /// This class implements a patterned string. - /// - /// - /// - /// This string has embedded patterns that are resolved and expanded - /// when the string is formatted. - /// - /// - /// This class functions similarly to the - /// in that it accepts a pattern and renders it to a string. Unlike the - /// however the PatternString - /// does not render the properties of a specific but - /// of the process in general. - /// - /// - /// The recognized conversion pattern names are: - /// - /// - /// - /// Conversion Pattern Name - /// Effect - /// - /// - /// appdomain - /// - /// - /// Used to output the friendly name of the current AppDomain. - /// - /// - /// - /// - /// appsetting - /// - /// - /// Used to output the value of a specific appSetting key in the application - /// configuration file. - /// - /// - /// - /// - /// date - /// - /// - /// Used to output the current date and time in the local time zone. - /// To output the date in universal time use the %utcdate pattern. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %date{HH:mm:ss,fff} or - /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %date{ISO8601} or %date{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// env - /// - /// - /// Used to output the a specific environment variable. The key to - /// lookup must be specified within braces and directly following the - /// pattern specifier, e.g. %env{COMPUTERNAME} would include the value - /// of the COMPUTERNAME environment variable. - /// - /// - /// The env pattern is not supported on the .NET Compact Framework. - /// - /// - /// - /// - /// identity - /// - /// - /// Used to output the user name for the currently active user - /// (Principal.Identity.Name). - /// - /// - /// - /// - /// newline - /// - /// - /// Outputs the platform dependent line separator character or - /// characters. - /// - /// - /// This conversion pattern name offers the same performance as using - /// non-portable line separator strings such as "\n", or "\r\n". - /// Thus, it is the preferred way of specifying a line separator. - /// - /// - /// - /// - /// processid - /// - /// - /// Used to output the system process ID for the current process. - /// - /// - /// - /// - /// property - /// - /// - /// Used to output a specific context property. The key to - /// lookup must be specified within braces and directly following the - /// pattern specifier, e.g. %property{user} would include the value - /// from the property that is keyed by the string 'user'. Each property value - /// that is to be included in the log must be specified separately. - /// Properties are stored in logging contexts. By default - /// the log4net:HostName property is set to the name of machine on - /// which the event was originally logged. - /// - /// - /// If no key is specified, e.g. %property then all the keys and their - /// values are printed in a comma separated list. - /// - /// - /// The properties of an event are combined from a number of different - /// contexts. These are listed below in the order in which they are searched. - /// - /// - /// - /// the thread properties - /// - /// The that are set on the current - /// thread. These properties are shared by all events logged on this thread. - /// - /// - /// - /// the global properties - /// - /// The that are set globally. These - /// properties are shared by all the threads in the AppDomain. - /// - /// - /// - /// - /// - /// - /// random - /// - /// - /// Used to output a random string of characters. The string is made up of - /// uppercase letters and numbers. By default the string is 4 characters long. - /// The length of the string can be specified within braces directly following the - /// pattern specifier, e.g. %random{8} would output an 8 character string. - /// - /// - /// - /// - /// username - /// - /// - /// Used to output the WindowsIdentity for the currently - /// active user. - /// - /// - /// - /// - /// utcdate - /// - /// - /// Used to output the date of the logging event in universal time. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %utcdate{HH:mm:ss,fff} or - /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// % - /// - /// - /// The sequence %% outputs a single percent sign. - /// - /// - /// - /// - /// - /// Additional pattern converters may be registered with a specific - /// instance using or - /// . - /// - /// - /// See the for details on the - /// format modifiers supported by the patterns. - /// - /// - /// Nicko Cadell - public class PatternString : IOptionHandler - { - #region Static Fields - - /// - /// Internal map of converter identifiers to converter types. - /// - private static Hashtable s_globalRulesRegistry; - - #endregion Static Fields - - #region Member Variables - - /// - /// the pattern - /// - private string m_pattern; - - /// - /// the head of the pattern converter chain - /// - private PatternConverter m_head; - - /// - /// patterns defined on this PatternString only - /// - private Hashtable m_instanceRulesRegistry = new Hashtable(); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + + /// + /// This class implements a patterned string. + /// + /// + /// + /// This string has embedded patterns that are resolved and expanded + /// when the string is formatted. + /// + /// + /// This class functions similarly to the + /// in that it accepts a pattern and renders it to a string. Unlike the + /// however the PatternString + /// does not render the properties of a specific but + /// of the process in general. + /// + /// + /// The recognized conversion pattern names are: + /// + /// + /// + /// Conversion Pattern Name + /// Effect + /// + /// + /// appdomain + /// + /// + /// Used to output the friendly name of the current AppDomain. + /// + /// + /// + /// + /// appsetting + /// + /// + /// Used to output the value of a specific appSetting key in the application + /// configuration file. + /// + /// + /// + /// + /// date + /// + /// + /// Used to output the current date and time in the local time zone. + /// To output the date in universal time use the %utcdate pattern. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %date{HH:mm:ss,fff} or + /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %date{ISO8601} or %date{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// env + /// + /// + /// Used to output the a specific environment variable. The key to + /// lookup must be specified within braces and directly following the + /// pattern specifier, e.g. %env{COMPUTERNAME} would include the value + /// of the COMPUTERNAME environment variable. + /// + /// + /// The env pattern is not supported on the .NET Compact Framework. + /// + /// + /// + /// + /// identity + /// + /// + /// Used to output the user name for the currently active user + /// (Principal.Identity.Name). + /// + /// + /// + /// + /// newline + /// + /// + /// Outputs the platform dependent line separator character or + /// characters. + /// + /// + /// This conversion pattern name offers the same performance as using + /// non-portable line separator strings such as "\n", or "\r\n". + /// Thus, it is the preferred way of specifying a line separator. + /// + /// + /// + /// + /// processid + /// + /// + /// Used to output the system process ID for the current process. + /// + /// + /// + /// + /// property + /// + /// + /// Used to output a specific context property. The key to + /// lookup must be specified within braces and directly following the + /// pattern specifier, e.g. %property{user} would include the value + /// from the property that is keyed by the string 'user'. Each property value + /// that is to be included in the log must be specified separately. + /// Properties are stored in logging contexts. By default + /// the log4net:HostName property is set to the name of machine on + /// which the event was originally logged. + /// + /// + /// If no key is specified, e.g. %property then all the keys and their + /// values are printed in a comma separated list. + /// + /// + /// The properties of an event are combined from a number of different + /// contexts. These are listed below in the order in which they are searched. + /// + /// + /// + /// the thread properties + /// + /// The that are set on the current + /// thread. These properties are shared by all events logged on this thread. + /// + /// + /// + /// the global properties + /// + /// The that are set globally. These + /// properties are shared by all the threads in the AppDomain. + /// + /// + /// + /// + /// + /// + /// random + /// + /// + /// Used to output a random string of characters. The string is made up of + /// uppercase letters and numbers. By default the string is 4 characters long. + /// The length of the string can be specified within braces directly following the + /// pattern specifier, e.g. %random{8} would output an 8 character string. + /// + /// + /// + /// + /// username + /// + /// + /// Used to output the WindowsIdentity for the currently + /// active user. + /// + /// + /// + /// + /// utcdate + /// + /// + /// Used to output the date of the logging event in universal time. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %utcdate{HH:mm:ss,fff} or + /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// % + /// + /// + /// The sequence %% outputs a single percent sign. + /// + /// + /// + /// + /// + /// Additional pattern converters may be registered with a specific + /// instance using or + /// . + /// + /// + /// See the for details on the + /// format modifiers supported by the patterns. + /// + /// + /// Nicko Cadell. + public class PatternString : IOptionHandler + { + /// + /// Internal map of converter identifiers to converter types. + /// + private static Hashtable s_globalRulesRegistry; + + /// + /// the pattern. + /// + private string m_pattern; - #endregion + /// + /// the head of the pattern converter chain. + /// + private PatternConverter m_head; - #region Static Constructor + /// + /// patterns defined on this PatternString only. + /// + private Hashtable m_instanceRulesRegistry = new Hashtable(); + + /// + /// Initializes static members of the class. + /// Initialize the global registry. + /// + static PatternString() + { + s_globalRulesRegistry = new Hashtable(18); - /// - /// Initialize the global registry - /// - static PatternString() - { - s_globalRulesRegistry = new Hashtable(18); - - s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); - s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); + s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); + s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); #if !NETCF - s_globalRulesRegistry.Add("env", typeof(EnvironmentPatternConverter)); + s_globalRulesRegistry.Add("env", typeof(EnvironmentPatternConverter)); #if !NETSTANDARD1_3 // EnvironmentFolderPathPatternConverter not yet supported - s_globalRulesRegistry.Add("envFolderPath", typeof(EnvironmentFolderPathPatternConverter)); + s_globalRulesRegistry.Add("envFolderPath", typeof(EnvironmentFolderPathPatternConverter)); #endif #endif - s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); - s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); - s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); - s_globalRulesRegistry.Add("processid", typeof(ProcessIdPatternConverter)); - s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("random", typeof(RandomStringPatternConverter)); - s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); + s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); + s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); + s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); + s_globalRulesRegistry.Add("processid", typeof(ProcessIdPatternConverter)); + s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("random", typeof(RandomStringPatternConverter)); + s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); - s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); #if !NETCF && !NETSTANDARD1_3 - // TODO - have added common variants of casing like utcdate above. - // Wouldn't it be better to use a case-insensitive Hashtable? - s_globalRulesRegistry.Add("appsetting", typeof(AppSettingPatternConverter)); - s_globalRulesRegistry.Add("appSetting", typeof(AppSettingPatternConverter)); - s_globalRulesRegistry.Add("AppSetting", typeof(AppSettingPatternConverter)); + // TODO - have added common variants of casing like utcdate above. + // Wouldn't it be better to use a case-insensitive Hashtable? + s_globalRulesRegistry.Add("appsetting", typeof(AppSettingPatternConverter)); + s_globalRulesRegistry.Add("appSetting", typeof(AppSettingPatternConverter)); + s_globalRulesRegistry.Add("AppSetting", typeof(AppSettingPatternConverter)); #endif - } - - #endregion Static Constructor - - #region Constructors - - /// - /// Default constructor - /// - /// - /// - /// Initialize a new instance of - /// - /// - public PatternString() - { - } - - /// - /// Constructs a PatternString - /// - /// The pattern to use with this PatternString - /// - /// - /// Initialize a new instance of with the pattern specified. - /// - /// - public PatternString(string pattern) - { - m_pattern = pattern; - ActivateOptions(); - } - - #endregion - - /// - /// Gets or sets the pattern formatting string - /// - /// - /// The pattern formatting string - /// - /// - /// - /// The ConversionPattern option. This is the string which - /// controls formatting and consists of a mix of literal content and - /// conversion specifiers. - /// - /// - public string ConversionPattern - { - get { return m_pattern; } - set { m_pattern = value; } - } + } + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Initialize a new instance of . + /// + /// + public PatternString() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructs a PatternString. + /// + /// The pattern to use with this PatternString. + /// + /// + /// Initialize a new instance of with the pattern specified. + /// + /// + public PatternString(string pattern) + { + this.m_pattern = pattern; + this.ActivateOptions(); + } + + /// + /// Gets or sets the pattern formatting string. + /// + /// + /// The pattern formatting string. + /// + /// + /// + /// The ConversionPattern option. This is the string which + /// controls formatting and consists of a mix of literal content and + /// conversion specifiers. + /// + /// + public string ConversionPattern + { + get { return this.m_pattern; } + set { this.m_pattern = value; } + } + + /// + /// Initialize object options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public virtual void ActivateOptions() + { + this.m_head = this.CreatePatternParser(this.m_pattern).Parse(); + } + + /// + /// Create the used to parse the pattern. + /// + /// the pattern to parse. + /// The . + /// + /// + /// Returns PatternParser used to parse the conversion string. Subclasses + /// may override this to return a subclass of PatternParser which recognize + /// custom conversion pattern name. + /// + /// + private PatternParser CreatePatternParser(string pattern) + { + PatternParser patternParser = new PatternParser(pattern); - #region Implementation of IOptionHandler - - /// - /// Initialize object options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - virtual public void ActivateOptions() - { - m_head = CreatePatternParser(m_pattern).Parse(); - } - - #endregion - - /// - /// Create the used to parse the pattern - /// - /// the pattern to parse - /// The - /// - /// - /// Returns PatternParser used to parse the conversion string. Subclasses - /// may override this to return a subclass of PatternParser which recognize - /// custom conversion pattern name. - /// - /// - private PatternParser CreatePatternParser(string pattern) - { - PatternParser patternParser = new PatternParser(pattern); - - // Add all the builtin patterns - foreach(DictionaryEntry entry in s_globalRulesRegistry) - { + // Add all the builtin patterns + foreach (DictionaryEntry entry in s_globalRulesRegistry) + { ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = (string)entry.Key; converterInfo.Type = (Type)entry.Value; patternParser.PatternConverters.Add(entry.Key, converterInfo); - } - // Add the instance patterns - foreach(DictionaryEntry entry in m_instanceRulesRegistry) - { - patternParser.PatternConverters[entry.Key] = entry.Value; - } + } + + // Add the instance patterns + foreach (DictionaryEntry entry in this.m_instanceRulesRegistry) + { + patternParser.PatternConverters[entry.Key] = entry.Value; + } - return patternParser; - } - - /// - /// Produces a formatted string as specified by the conversion pattern. - /// - /// The TextWriter to write the formatted event to - /// - /// - /// Format the pattern to the . - /// - /// - public void Format(TextWriter writer) - { - if (writer == null) - { - throw new ArgumentNullException("writer"); - } + return patternParser; + } - PatternConverter c = m_head; + /// + /// Produces a formatted string as specified by the conversion pattern. + /// + /// The TextWriter to write the formatted event to. + /// + /// + /// Format the pattern to the . + /// + /// + public void Format(TextWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } - // loop through the chain of pattern converters - while(c != null) - { - c.Format(writer, null); - c = c.Next; - } - } + PatternConverter c = this.m_head; - /// - /// Format the pattern as a string - /// - /// the pattern formatted as a string - /// - /// - /// Format the pattern to a string. - /// - /// - public string Format() - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - Format(writer); - return writer.ToString(); - } + // loop through the chain of pattern converters + while (c != null) + { + c.Format(writer, null); + c = c.Next; + } + } - /// - /// Add a converter to this PatternString - /// - /// the converter info - /// - /// - /// This version of the method is used by the configurator. - /// Programmatic users should use the alternative method. - /// - /// - public void AddConverter(ConverterInfo converterInfo) - { - if (converterInfo == null) throw new ArgumentNullException("converterInfo"); + /// + /// Format the pattern as a string. + /// + /// the pattern formatted as a string. + /// + /// + /// Format the pattern to a string. + /// + /// + public string Format() + { + StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + this.Format(writer); + return writer.ToString(); + } + /// + /// Add a converter to this PatternString. + /// + /// the converter info. + /// + /// + /// This version of the method is used by the configurator. + /// Programmatic users should use the alternative method. + /// + /// + public void AddConverter(ConverterInfo converterInfo) + { + if (converterInfo == null) + { + throw new ArgumentNullException("converterInfo"); + } + if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) { throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); } - m_instanceRulesRegistry[converterInfo.Name] = converterInfo; - } - - /// - /// Add a converter to this PatternString - /// - /// the name of the conversion pattern for this converter - /// the type of the converter - /// - /// - /// Add a converter to this PatternString - /// - /// - public void AddConverter(string name, Type type) - { - if (name == null) throw new ArgumentNullException("name"); - if (type == null) throw new ArgumentNullException("type"); + + this.m_instanceRulesRegistry[converterInfo.Name] = converterInfo; + } + /// + /// Add a converter to this PatternString. + /// + /// the name of the conversion pattern for this converter. + /// the type of the converter. + /// + /// + /// Add a converter to this PatternString. + /// + /// + public void AddConverter(string name, Type type) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = name; converterInfo.Type = type; - AddConverter(converterInfo); - } - } + this.AddConverter(converterInfo); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs index 3e85fc590fe..62174263be0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs @@ -1,58 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Write the name of the current AppDomain to the output - /// - /// - /// - /// Write the name of the current AppDomain to the output writer - /// - /// - /// Nicko Cadell - internal sealed class AppDomainPatternConverter : PatternConverter - { - /// - /// Write the name of the current AppDomain to the output - /// - /// the writer to write to - /// null, state is not set - /// - /// - /// Writes name of the current AppDomain to the output . - /// - /// - override protected void Convert(TextWriter writer, object state) - { - writer.Write( SystemInfo.ApplicationFriendlyName ); - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Util; + + /// + /// Write the name of the current AppDomain to the output. + /// + /// + /// + /// Write the name of the current AppDomain to the output writer. + /// + /// + /// Nicko Cadell. + internal sealed class AppDomainPatternConverter : PatternConverter + { + /// + /// Write the name of the current AppDomain to the output. + /// + /// the writer to write to. + /// null, state is not set. + /// + /// + /// Writes name of the current AppDomain to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { + writer.Write(SystemInfo.ApplicationFriendlyName); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs index 4405d20c245..cd5fc21370c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,24 +18,23 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for application .config files #if !NETCF using System; -using System.Text; -using System.IO; using System.Collections; - +using System.IO; +using System.Text; + using log4net.Core; -using log4net.Util; using log4net.Repository; +using log4net.Util; namespace log4net.Util.PatternStringConverters { /// - /// AppSetting pattern converter + /// AppSetting pattern converter. /// /// /// @@ -70,23 +68,25 @@ private static IDictionary AppSettingsDictionary if (_appSettingsHashTable == null) { Hashtable h = new Hashtable(); - foreach(string key in System.Configuration.ConfigurationManager.AppSettings) + foreach (string key in System.Configuration.ConfigurationManager.AppSettings) { h.Add(key, System.Configuration.ConfigurationManager.AppSettings[key]); } + _appSettingsHashTable = h; } + return _appSettingsHashTable; } - } + private static Hashtable _appSettingsHashTable; /// - /// Write the property value to the output + /// Write the property value to the output. /// /// that will receive the formatted result. - /// null, state is not set + /// null, state is not set. /// /// /// Writes out the value of a named property. The property name @@ -98,13 +98,12 @@ private static IDictionary AppSettingsDictionary /// then all the properties are written as key value pairs. /// /// - override protected void Convert(TextWriter writer, object state) + protected override void Convert(TextWriter writer, object state) { - - if (Option != null) + if (this.Option != null) { // Write the value for the specified key - WriteObject(writer, null, System.Configuration.ConfigurationManager.AppSettings[Option]); + WriteObject(writer, null, System.Configuration.ConfigurationManager.AppSettings[this.Option]); } else { diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs index 978bb63dc31..d19fe902409 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs @@ -1,193 +1,182 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net.DateFormatter; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Write the current date to the output - /// - /// - /// - /// Date pattern converter, uses a to format - /// the current date and time to the writer as a string. - /// - /// - /// The value of the determines - /// the formatting of the date. The following values are allowed: - /// - /// - /// Option value - /// Output - /// - /// - /// ISO8601 - /// - /// Uses the formatter. - /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. - /// - /// - /// - /// DATE - /// - /// Uses the formatter. - /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". - /// - /// - /// - /// ABSOLUTE - /// - /// Uses the formatter. - /// Formats using the "HH:mm:ss,fff" for example, "15:49:37,459". - /// - /// - /// - /// other - /// - /// Any other pattern string uses the formatter. - /// This formatter passes the pattern string to the - /// method. - /// For details on valid patterns see - /// DateTimeFormatInfo Class. - /// - /// - /// - /// - /// - /// The date and time is in the local time zone and is rendered in that zone. - /// To output the time in Universal time see . - /// - /// - /// Nicko Cadell - internal class DatePatternConverter : PatternConverter, IOptionHandler - { - /// - /// The used to render the date to a string - /// - /// - /// - /// The used to render the date to a string - /// - /// - protected IDateFormatter m_dateFormatter; - - #region Implementation of IOptionHandler - - /// - /// Initialize the converter options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - string dateFormatStr = Option; - - if (dateFormatStr == null) - { - dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; - } - - if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) - { - m_dateFormatter = new Iso8601DateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) - { - m_dateFormatter = new AbsoluteTimeDateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) - { - m_dateFormatter = new DateTimeDateFormatter(); - } - else - { - try - { - m_dateFormatter = new SimpleDateFormatter(dateFormatStr); - } - catch (Exception e) - { - LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with ["+dateFormatStr+"]", e); - m_dateFormatter = new Iso8601DateFormatter(); - } - } - } - - #endregion - - /// - /// Write the current date to the output - /// - /// that will receive the formatted result. - /// null, state is not set - /// - /// - /// Pass the current date and time to the - /// for it to render it to the writer. - /// - /// - /// The date and time passed is in the local time zone. - /// - /// - override protected void Convert(TextWriter writer, object state) - { - try - { - m_dateFormatter.FormatDate(DateTime.Now, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } - } - - #region Private Static Fields + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net.Core; + using log4net.DateFormatter; + + /// + /// Write the current date to the output. + /// + /// + /// + /// Date pattern converter, uses a to format + /// the current date and time to the writer as a string. + /// + /// + /// The value of the determines + /// the formatting of the date. The following values are allowed: + /// + /// + /// Option value + /// Output + /// + /// + /// ISO8601 + /// + /// Uses the formatter. + /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. + /// + /// + /// + /// DATE + /// + /// Uses the formatter. + /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". + /// + /// + /// + /// ABSOLUTE + /// + /// Uses the formatter. + /// Formats using the "HH:mm:ss,fff" for example, "15:49:37,459". + /// + /// + /// + /// other + /// + /// Any other pattern string uses the formatter. + /// This formatter passes the pattern string to the + /// method. + /// For details on valid patterns see + /// DateTimeFormatInfo Class. + /// + /// + /// + /// + /// + /// The date and time is in the local time zone and is rendered in that zone. + /// To output the time in Universal time see . + /// + /// + /// Nicko Cadell. + internal class DatePatternConverter : PatternConverter, IOptionHandler + { + /// + /// The used to render the date to a string. + /// + /// + /// + /// The used to render the date to a string. + /// + /// + protected IDateFormatter m_dateFormatter; + + /// + /// Initialize the converter options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + string dateFormatStr = this.Option; - /// - /// The fully qualified type of the DatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(DatePatternConverter); + if (dateFormatStr == null) + { + dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; + } - #endregion Private Static Fields - } + if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) + { + this.m_dateFormatter = new Iso8601DateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) + { + this.m_dateFormatter = new AbsoluteTimeDateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) + { + this.m_dateFormatter = new DateTimeDateFormatter(); + } + else + { + try + { + this.m_dateFormatter = new SimpleDateFormatter(dateFormatStr); + } + catch (Exception e) + { + LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with [" + dateFormatStr + "]", e); + this.m_dateFormatter = new Iso8601DateFormatter(); + } + } + } + + /// + /// Write the current date to the output. + /// + /// that will receive the formatted result. + /// null, state is not set. + /// + /// + /// Pass the current date and time to the + /// for it to render it to the writer. + /// + /// + /// The date and time passed is in the local time zone. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + this.m_dateFormatter.FormatDate(DateTime.Now, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } + } + + /// + /// The fully qualified type of the DatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(DatePatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs index 12837ef505f..9c503909149 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,8 +18,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - #if !NETCF using System; @@ -29,24 +26,24 @@ namespace log4net.Util.PatternStringConverters { /// - /// Write an folder path to the output + /// Write an folder path to the output. /// /// /// /// Write an special path environment folder path to the output writer. - /// The value of the determines + /// The value of the determines /// the name of the variable to output. /// should be a value in the enumeration. /// /// - /// Ron Grabowski + /// Ron Grabowski. internal sealed class EnvironmentFolderPathPatternConverter : PatternConverter { /// - /// Write an special path environment folder path to the output + /// Write an special path environment folder path to the output. /// - /// the writer to write to - /// null, state is not set + /// the writer to write to. + /// null, state is not set. /// /// /// Writes the special path environment folder path to the output . @@ -55,14 +52,14 @@ internal sealed class EnvironmentFolderPathPatternConverter : PatternConverter /// property. /// /// - override protected void Convert(TextWriter writer, object state) + protected override void Convert(TextWriter writer, object state) { try { - if (Option != null && Option.Length > 0) + if (this.Option != null && this.Option.Length > 0) { Environment.SpecialFolder specialFolder = - (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), Option, true); + (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), this.Option, true); string envFolderPathValue = Environment.GetFolderPath(specialFolder); if (envFolderPathValue != null && envFolderPathValue.Length > 0) @@ -73,8 +70,8 @@ override protected void Convert(TextWriter writer, object state) } catch (System.Security.SecurityException secEx) { - // This security exception will occur if the caller does not have - // unrestricted environment permission. If this occurs the expansion + // This security exception will occur if the caller does not have + // unrestricted environment permission. If this occurs the expansion // will be skipped with the following warning message. LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.", secEx); } @@ -82,10 +79,8 @@ override protected void Convert(TextWriter writer, object state) { LogLog.Error(declaringType, "Error occurred while converting environment variable.", ex); } - } - - #region Private Static Fields - + } + /// /// The fully qualified type of the EnvironmentFolderPathPatternConverter class. /// @@ -93,9 +88,7 @@ override protected void Convert(TextWriter writer, object state) /// Used by the internal logger to record the Type of the /// log message. /// - private readonly static Type declaringType = typeof(EnvironmentFolderPathPatternConverter); - - #endregion Private Static Fields + private static readonly Type declaringType = typeof(EnvironmentFolderPathPatternConverter); } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs index e32eb8c66a6..9e9304cd4bc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,102 +18,97 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for Environment.GetEnvironmentVariable() #if !NETCF using System; -using System.Text; using System.IO; - -using log4net.Util; -using log4net.DateFormatter; +using System.Text; + using log4net.Core; +using log4net.DateFormatter; +using log4net.Util; namespace log4net.Util.PatternStringConverters { - /// - /// Write an environment variable to the output - /// - /// - /// - /// Write an environment variable to the output writer. - /// The value of the determines - /// the name of the variable to output. - /// - /// - /// Nicko Cadell - internal sealed class EnvironmentPatternConverter : PatternConverter - { - /// - /// Write an environment variable to the output - /// - /// the writer to write to - /// null, state is not set - /// - /// - /// Writes the environment variable to the output . - /// The name of the environment variable to output must be set - /// using the - /// property. - /// - /// - override protected void Convert(TextWriter writer, object state) - { - try - { - if (this.Option != null && this.Option.Length > 0) - { - // Lookup the environment variable - string envValue = Environment.GetEnvironmentVariable(this.Option); + /// + /// Write an environment variable to the output. + /// + /// + /// + /// Write an environment variable to the output writer. + /// The value of the determines + /// the name of the variable to output. + /// + /// + /// Nicko Cadell. + internal sealed class EnvironmentPatternConverter : PatternConverter + { + /// + /// Write an environment variable to the output. + /// + /// the writer to write to. + /// null, state is not set. + /// + /// + /// Writes the environment variable to the output . + /// The name of the environment variable to output must be set + /// using the + /// property. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + if (this.Option != null && this.Option.Length > 0) + { + // Lookup the environment variable + string envValue = Environment.GetEnvironmentVariable(this.Option); -#if NET_2_0 +#if NET_2_0 // If we didn't see it for the process, try a user level variable. - if (envValue == null) - { - envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.User); - } + if (envValue == null) + { + envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.User); + } // If we still didn't find it, try a system level one. - if (envValue == null) - { - envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.Machine); - } -#endif - - if (envValue != null && envValue.Length > 0) - { - writer.Write(envValue); - } - } - } - catch(System.Security.SecurityException secEx) - { - // This security exception will occur if the caller does not have - // unrestricted environment permission. If this occurs the expansion - // will be skipped with the following warning message. - LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.", secEx); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting environment variable.", ex); - } - } - - #region Private Static Fields - - /// - /// The fully qualified type of the EnvironmentPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(EnvironmentPatternConverter); + if (envValue == null) + { + envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.Machine); + } +#endif - #endregion Private Static Fields - } + if (envValue != null && envValue.Length > 0) + { + writer.Write(envValue); + } + } + } + catch (System.Security.SecurityException secEx) + { + // This security exception will occur if the caller does not have + // unrestricted environment permission. If this occurs the expansion + // will be skipped with the following warning message. + LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.", secEx); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting environment variable.", ex); + } + } + + /// + /// The fully qualified type of the EnvironmentPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(EnvironmentPatternConverter); + } } #endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs index 1b8cd1829c6..5ca00f216de 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs @@ -1,92 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Write the current thread identity to the output - /// - /// - /// - /// Write the current thread identity to the output writer - /// - /// - /// Nicko Cadell - internal sealed class IdentityPatternConverter : PatternConverter - { - /// - /// Write the current thread identity to the output - /// - /// the writer to write to - /// null, state is not set - /// - /// - /// Writes the current thread identity to the output . - /// - /// - override protected void Convert(TextWriter writer, object state) - { -#if (NETCF || SSCLI || NETSTANDARD1_3) + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Util; + + /// + /// Write the current thread identity to the output. + /// + /// + /// + /// Write the current thread identity to the output writer. + /// + /// + /// Nicko Cadell. + internal sealed class IdentityPatternConverter : PatternConverter + { + /// + /// Write the current thread identity to the output. + /// + /// the writer to write to. + /// null, state is not set. + /// + /// + /// Writes the current thread identity to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { +#if NETCF || SSCLI || NETSTANDARD1_3 // On compact framework there's no notion of current thread principals writer.Write( SystemInfo.NotAvailableText ); #else - try - { - if (System.Threading.Thread.CurrentPrincipal != null && - System.Threading.Thread.CurrentPrincipal.Identity != null && - System.Threading.Thread.CurrentPrincipal.Identity.Name != null) - { - writer.Write( System.Threading.Thread.CurrentPrincipal.Identity.Name ); - } - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored."); + try + { + if (System.Threading.Thread.CurrentPrincipal != null && + System.Threading.Thread.CurrentPrincipal.Identity != null && + System.Threading.Thread.CurrentPrincipal.Identity.Name != null) + { + writer.Write(System.Threading.Thread.CurrentPrincipal.Identity.Name); + } + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored."); - writer.Write( SystemInfo.NotAvailableText ); - } + writer.Write(SystemInfo.NotAvailableText); + } #endif - } - - #region Private Static Fields - - /// - /// The fully qualified type of the IdentityPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(IdentityPatternConverter); - - #endregion Private Static Fields - } + } + + /// + /// The fully qualified type of the IdentityPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(IdentityPatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs index 345dfa7883e..de417e99b5c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs @@ -1,111 +1,108 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Pattern converter for literal string instances in the pattern - /// - /// - /// - /// Writes the literal string value specified in the - /// property to - /// the output. - /// - /// - /// Nicko Cadell - internal class LiteralPatternConverter : PatternConverter - { - /// - /// Set the next converter in the chain - /// - /// The next pattern converter in the chain - /// The next pattern converter - /// - /// - /// Special case the building of the pattern converter chain - /// for instances. Two adjacent - /// literals in the pattern can be represented by a single combined - /// pattern converter. This implementation detects when a - /// is added to the chain - /// after this converter and combines its value with this converter's - /// literal value. - /// - /// - public override PatternConverter SetNext(PatternConverter pc) - { - LiteralPatternConverter literalPc = pc as LiteralPatternConverter; - if (literalPc != null) - { - // Combine the two adjacent literals together - Option = Option + literalPc.Option; + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Util; + + /// + /// Pattern converter for literal string instances in the pattern. + /// + /// + /// + /// Writes the literal string value specified in the + /// property to + /// the output. + /// + /// + /// Nicko Cadell. + internal class LiteralPatternConverter : PatternConverter + { + /// + /// Set the next converter in the chain. + /// + /// The next pattern converter in the chain. + /// The next pattern converter. + /// + /// + /// Special case the building of the pattern converter chain + /// for instances. Two adjacent + /// literals in the pattern can be represented by a single combined + /// pattern converter. This implementation detects when a + /// is added to the chain + /// after this converter and combines its value with this converter's + /// literal value. + /// + /// + public override PatternConverter SetNext(PatternConverter pc) + { + LiteralPatternConverter literalPc = pc as LiteralPatternConverter; + if (literalPc != null) + { + // Combine the two adjacent literals together + this.Option = this.Option + literalPc.Option; - // We are the next converter now - return this; - } + // We are the next converter now + return this; + } - return base.SetNext(pc); - } + return base.SetNext(pc); + } - /// - /// Write the literal to the output - /// - /// the writer to write to - /// null, not set - /// - /// - /// Override the formatting behavior to ignore the FormattingInfo - /// because we have a literal instead. - /// - /// - /// Writes the value of - /// to the output . - /// - /// - override public void Format(TextWriter writer, object state) - { - writer.Write(Option); - } + /// + /// Write the literal to the output. + /// + /// the writer to write to. + /// null, not set. + /// + /// + /// Override the formatting behavior to ignore the FormattingInfo + /// because we have a literal instead. + /// + /// + /// Writes the value of + /// to the output . + /// + /// + public override void Format(TextWriter writer, object state) + { + writer.Write(this.Option); + } - /// - /// Convert this pattern into the rendered message - /// - /// that will receive the formatted result. - /// null, not set - /// - /// - /// This method is not used. - /// - /// - override protected void Convert(TextWriter writer, object state) - { - throw new InvalidOperationException("Should never get here because of the overridden Format method"); - } - } + /// + /// Convert this pattern into the rendered message. + /// + /// that will receive the formatted result. + /// null, not set. + /// + /// + /// This method is not used. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + throw new InvalidOperationException("Should never get here because of the overridden Format method"); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs index 1d7489bb05f..e5754fed1ce 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs @@ -1,90 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Writes a newline to the output - /// - /// - /// - /// Writes the system dependent line terminator to the output. - /// This behavior can be overridden by setting the : - /// - /// - /// - /// Option Value - /// Output - /// - /// - /// DOS - /// DOS or Windows line terminator "\r\n" - /// - /// - /// UNIX - /// UNIX line terminator "\n" - /// - /// - /// - /// Nicko Cadell - internal sealed class NewLinePatternConverter : LiteralPatternConverter, IOptionHandler - { - #region Implementation of IOptionHandler - - /// - /// Initialize the converter - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - if (SystemInfo.EqualsIgnoringCase(Option, "DOS")) - { - Option = "\r\n"; - } - else if (SystemInfo.EqualsIgnoringCase(Option, "UNIX")) - { - Option = "\n"; - } - else - { - Option = SystemInfo.NewLine; - } - } - - #endregion - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using log4net.Core; + + /// + /// Writes a newline to the output. + /// + /// + /// + /// Writes the system dependent line terminator to the output. + /// This behavior can be overridden by setting the : + /// + /// + /// + /// Option Value + /// Output + /// + /// + /// DOS + /// DOS or Windows line terminator "\r\n" + /// + /// + /// UNIX + /// UNIX line terminator "\n" + /// + /// + /// + /// Nicko Cadell. + internal sealed class NewLinePatternConverter : LiteralPatternConverter, IOptionHandler + { + /// + /// Initialize the converter. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + if (SystemInfo.EqualsIgnoringCase(this.Option, "DOS")) + { + this.Option = "\r\n"; + } + else if (SystemInfo.EqualsIgnoringCase(this.Option, "UNIX")) + { + this.Option = "\n"; + } + else + { + this.Option = SystemInfo.NewLine; + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs index 5e8963e2d96..ff48fbb6cf2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs @@ -1,90 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Write the current process ID to the output - /// - /// - /// - /// Write the current process ID to the output writer - /// - /// - /// Nicko Cadell - internal sealed class ProcessIdPatternConverter : PatternConverter - { - /// - /// Write the current process ID to the output - /// - /// the writer to write to - /// null, state is not set - /// - /// - /// Write the current process ID to the output . - /// - /// + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Util; + + /// + /// Write the current process ID to the output. + /// + /// + /// + /// Write the current process ID to the output writer. + /// + /// + /// Nicko Cadell. + internal sealed class ProcessIdPatternConverter : PatternConverter + { + /// + /// Write the current process ID to the output. + /// + /// the writer to write to. + /// null, state is not set. + /// + /// + /// Write the current process ID to the output . + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecuritySafeCritical] #endif - override protected void Convert(TextWriter writer, object state) - { -#if (NETCF || SSCLI) + protected override void Convert(TextWriter writer, object state) + { +#if NETCF || SSCLI // On compact framework there is no System.Diagnostics.Process class writer.Write( SystemInfo.NotAvailableText ); #else - try - { - writer.Write( System.Diagnostics.Process.GetCurrentProcess().Id ); - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current process id. Error Ignored."); + try + { + writer.Write(System.Diagnostics.Process.GetCurrentProcess().Id); + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current process id. Error Ignored."); - writer.Write( SystemInfo.NotAvailableText ); - } + writer.Write(SystemInfo.NotAvailableText); + } #endif - } - - #region Private Static Fields - - /// - /// The fully qualified type of the ProcessIdPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(ProcessIdPatternConverter); - - #endregion Private Static Fields - } + } + + /// + /// The fully qualified type of the ProcessIdPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(ProcessIdPatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs index 1bd29f1c127..2e11e983a2d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs @@ -1,103 +1,100 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; -using System.Collections; - -using log4net.Core; -using log4net.Util; -using log4net.Repository; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Property pattern converter - /// - /// - /// - /// This pattern converter reads the thread and global properties. - /// The thread properties take priority over global properties. - /// See for details of the - /// thread properties. See for - /// details of the global properties. - /// - /// - /// If the is specified then that will be used to - /// lookup a single property. If no is specified - /// then all properties will be dumped as a list of key value pairs. - /// - /// - /// Nicko Cadell - internal sealed class PropertyPatternConverter : PatternConverter - { - /// - /// Write the property value to the output - /// - /// that will receive the formatted result. - /// null, state is not set - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - /// If the is set to null - /// then all the properties are written as key value pairs. - /// - /// - override protected void Convert(TextWriter writer, object state) - { - CompositeProperties compositeProperties = new CompositeProperties(); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.Repository; + using log4net.Util; + + /// + /// Property pattern converter. + /// + /// + /// + /// This pattern converter reads the thread and global properties. + /// The thread properties take priority over global properties. + /// See for details of the + /// thread properties. See for + /// details of the global properties. + /// + /// + /// If the is specified then that will be used to + /// lookup a single property. If no is specified + /// then all properties will be dumped as a list of key value pairs. + /// + /// + /// Nicko Cadell. + internal sealed class PropertyPatternConverter : PatternConverter + { + /// + /// Write the property value to the output. + /// + /// that will receive the formatted result. + /// null, state is not set. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + /// If the is set to null + /// then all the properties are written as key value pairs. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + CompositeProperties compositeProperties = new CompositeProperties(); #if !(NETCF || NETSTANDARD1_3) - PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); - if (logicalThreadProperties != null) - { - compositeProperties.Add(logicalThreadProperties); - } + PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); + if (logicalThreadProperties != null) + { + compositeProperties.Add(logicalThreadProperties); + } #endif - PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); - if (threadProperties != null) - { - compositeProperties.Add(threadProperties); - } + PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); + if (threadProperties != null) + { + compositeProperties.Add(threadProperties); + } - // TODO: Add Repository Properties - compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); + // TODO: Add Repository Properties + compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); - if (Option != null) - { - // Write the value for the specified key - WriteObject(writer, null, compositeProperties[Option]); - } - else - { - // Write all the key value pairs - WriteDictionary(writer, null, compositeProperties.Flatten()); - } - } - } + if (this.Option != null) + { + // Write the value for the specified key + WriteObject(writer, null, compositeProperties[this.Option]); + } + else + { + // Write all the key value pairs + WriteDictionary(writer, null, compositeProperties.Flatten()); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs index be16891bab8..1cc9cbe5081 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs @@ -1,160 +1,149 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Util; -using log4net.DateFormatter; -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// A Pattern converter that generates a string of random characters - /// - /// - /// - /// The converter generates a string of random characters. By default - /// the string is length 4. This can be changed by setting the - /// to the string value of the length required. - /// - /// - /// The random characters in the string are limited to uppercase letters - /// and numbers only. - /// - /// - /// The random number generator used by this class is not cryptographically secure. - /// - /// - /// Nicko Cadell - internal sealed class RandomStringPatternConverter : PatternConverter, IOptionHandler - { - /// - /// Shared random number generator - /// - private static readonly Random s_random = new Random(); - - /// - /// Length of random string to generate. Default length 4. - /// - private int m_length = 4; - - #region Implementation of IOptionHandler - - /// - /// Initialize the converter options - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - string optionStr = Option; - if (optionStr != null && optionStr.Length > 0) - { - int lengthVal; - if (SystemInfo.TryParse(optionStr, out lengthVal)) - { - m_length = lengthVal; - } - else - { - LogLog.Error(declaringType, "RandomStringPatternConverter: Could not convert Option ["+optionStr+"] to Length Int32"); - } - } - } - - #endregion - - /// - /// Write a randoim string to the output - /// - /// the writer to write to - /// null, state is not set - /// - /// - /// Write a randoim string to the output . - /// - /// - override protected void Convert(TextWriter writer, object state) - { - try - { - lock(s_random) - { - for(int i=0; i + /// A Pattern converter that generates a string of random characters. + /// + /// + /// + /// The converter generates a string of random characters. By default + /// the string is length 4. This can be changed by setting the + /// to the string value of the length required. + /// + /// + /// The random characters in the string are limited to uppercase letters + /// and numbers only. + /// + /// + /// The random number generator used by this class is not cryptographically secure. + /// + /// + /// Nicko Cadell. + internal sealed class RandomStringPatternConverter : PatternConverter, IOptionHandler + { + /// + /// Shared random number generator. + /// + private static readonly Random s_random = new Random(); - /// - /// The fully qualified type of the RandomStringPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(RandomStringPatternConverter); + /// + /// Length of random string to generate. Default length 4. + /// + private int m_length = 4; + + /// + /// Initialize the converter options. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + string optionStr = this.Option; + if (optionStr != null && optionStr.Length > 0) + { + int lengthVal; + if (SystemInfo.TryParse(optionStr, out lengthVal)) + { + this.m_length = lengthVal; + } + else + { + LogLog.Error(declaringType, "RandomStringPatternConverter: Could not convert Option [" + optionStr + "] to Length Int32"); + } + } + } + + /// + /// Write a randoim string to the output. + /// + /// the writer to write to. + /// null, state is not set. + /// + /// + /// Write a randoim string to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + lock (s_random) + { + for (int i = 0; i < this.m_length; i++) + { + int randValue = s_random.Next(36); - #endregion Private Static Fields - } + if (randValue < 26) + { + // Letter + char ch = (char)('A' + randValue); + writer.Write(ch); + } + else if (randValue < 36) + { + // Number + char ch = (char)('0' + (randValue - 26)); + writer.Write(ch); + } + else + { + // Should not get here + writer.Write('X'); + } + } + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting.", ex); + } + } + + /// + /// The fully qualified type of the RandomStringPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(RandomStringPatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs index 5bb64e9e0bd..ddcbd449467 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs @@ -1,92 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Write the current threads username to the output - /// - /// - /// - /// Write the current threads username to the output writer - /// - /// - /// Nicko Cadell - internal sealed class UserNamePatternConverter : PatternConverter - { - /// - /// Write the current threads username to the output - /// - /// the writer to write to - /// null, state is not set - /// - /// - /// Write the current threads username to the output . - /// - /// - override protected void Convert(TextWriter writer, object state) - { -#if (NETCF || SSCLI || NETSTANDARD1_3) + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Util; + + /// + /// Write the current threads username to the output. + /// + /// + /// + /// Write the current threads username to the output writer. + /// + /// + /// Nicko Cadell. + internal sealed class UserNamePatternConverter : PatternConverter + { + /// + /// Write the current threads username to the output. + /// + /// the writer to write to. + /// null, state is not set. + /// + /// + /// Write the current threads username to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { +#if NETCF || SSCLI || NETSTANDARD1_3 // On compact framework there's no notion of current Windows user writer.Write( SystemInfo.NotAvailableText ); #else - try - { - System.Security.Principal.WindowsIdentity windowsIdentity = null; - windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); - if (windowsIdentity != null && windowsIdentity.Name != null) - { - writer.Write( windowsIdentity.Name ); - } - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current windows identity. Error Ignored."); + try + { + System.Security.Principal.WindowsIdentity windowsIdentity = null; + windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); + if (windowsIdentity != null && windowsIdentity.Name != null) + { + writer.Write(windowsIdentity.Name); + } + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current windows identity. Error Ignored."); - writer.Write( SystemInfo.NotAvailableText ); - } + writer.Write(SystemInfo.NotAvailableText); + } #endif - } - - #region Private Static Fields - - /// - /// The fully qualified type of the UserNamePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(UserNamePatternConverter); - - #endregion Private Static Fields - } + } + + /// + /// The fully qualified type of the UserNamePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(UserNamePatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs index 4add260037f..35c72776f5c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs @@ -1,90 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - -using log4net.Core; -using log4net.Util; -using log4net.DateFormatter; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.PatternStringConverters { - /// - /// Write the UTC date time to the output - /// - /// - /// - /// Date pattern converter, uses a to format - /// the current date and time in Universal time. - /// - /// - /// See the for details on the date pattern syntax. - /// - /// - /// - /// Nicko Cadell - internal class UtcDatePatternConverter : DatePatternConverter - { - /// - /// Write the current date and time to the output - /// - /// that will receive the formatted result. - /// null, state is not set - /// - /// - /// Pass the current date and time to the - /// for it to render it to the writer. - /// - /// - /// The date is in Universal time when it is rendered. - /// - /// - /// - override protected void Convert(TextWriter writer, object state) - { - try - { - m_dateFormatter.FormatDate(DateTime.UtcNow, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } - } - - #region Private Static Fields - - /// - /// The fully qualified type of the UtcDatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(UtcDatePatternConverter); - - #endregion Private Static Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + using log4net.DateFormatter; + using log4net.Util; + + /// + /// Write the UTC date time to the output. + /// + /// + /// + /// Date pattern converter, uses a to format + /// the current date and time in Universal time. + /// + /// + /// See the for details on the date pattern syntax. + /// + /// + /// + /// Nicko Cadell. + internal class UtcDatePatternConverter : DatePatternConverter + { + /// + /// Write the current date and time to the output. + /// + /// that will receive the formatted result. + /// null, state is not set. + /// + /// + /// Pass the current date and time to the + /// for it to render it to the writer. + /// + /// + /// The date is in Universal time when it is rendered. + /// + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + this.m_dateFormatter.FormatDate(DateTime.UtcNow, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } + } + + /// + /// The fully qualified type of the UtcDatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(UtcDatePatternConverter); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs index 5e72b46ff67..6d30e123196 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs @@ -1,339 +1,319 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if !NETCF using System.Runtime.Serialization; using System.Xml; + #endif namespace log4net.Util { - /// - /// String keyed object map. - /// - /// - /// - /// While this collection is serializable only member - /// objects that are serializable will - /// be serialized along with this collection. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// String keyed object map. + /// + /// + /// + /// While this collection is serializable only member + /// objects that are serializable will + /// be serialized along with this collection. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if NETCF public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, IDictionary #else - [Serializable] public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, ISerializable, IDictionary + [Serializable] + public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, ISerializable, IDictionary #endif - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public PropertiesDictionary() - { - } - - /// - /// Constructor - /// - /// properties to copy - /// - /// - /// Initializes a new instance of the class. - /// - /// - public PropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) : base(propertiesDictionary) - { - } - - #endregion Public Instance Constructors - - #region Private Instance Constructors - + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public PropertiesDictionary() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// properties to copy. + /// + /// + /// Initializes a new instance of the class. + /// + /// + public PropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) + : base(propertiesDictionary) + { + } + #if !(NETCF || NETSTANDARD1_3) - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// The that holds the serialized object data. - /// The that contains contextual information about the source or destination. - /// - /// - /// Because this class is sealed the serialization constructor is private. - /// - /// - private PropertiesDictionary(SerializationInfo info, StreamingContext context) : base(info, context) - { - } + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// The that holds the serialized object data. + /// The that contains contextual information about the source or destination. + /// + /// + /// Because this class is sealed the serialization constructor is private. + /// + /// + private PropertiesDictionary(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } #endif - - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the value of the property with the specified key. - /// - /// - /// The value of the property with the specified key. - /// - /// The key of the property to get or set. - /// - /// - /// The property value will only be serialized if it is serializable. - /// If it cannot be serialized it will be silently ignored if - /// a serialization operation is performed. - /// - /// - override public object this[string key] - { - get { return InnerHashtable[key]; } - set { InnerHashtable[key] = value; } - } - - #endregion Public Instance Properties - - #region Public Instance Methods - - /// - /// Remove the entry with the specified key from this dictionary - /// - /// the key for the entry to remove - /// - /// - /// Remove the entry with the specified key from this dictionary - /// - /// - public void Remove(string key) - { - InnerHashtable.Remove(key); - } - - #endregion Public Instance Methods - - #region Implementation of IDictionary - - /// - /// See - /// - /// an enumerator - /// - /// - /// Returns a over the contest of this collection. - /// - /// - IDictionaryEnumerator IDictionary.GetEnumerator() - { - return InnerHashtable.GetEnumerator(); - } - - /// - /// See - /// - /// the key to remove - /// - /// - /// Remove the entry with the specified key from this dictionary - /// - /// - void IDictionary.Remove(object key) - { - InnerHashtable.Remove(key); - } - - /// - /// See - /// - /// the key to lookup in the collection - /// true if the collection contains the specified key - /// - /// - /// Test if this collection contains a specified key. - /// - /// - bool IDictionary.Contains(object key) - { - return InnerHashtable.Contains(key); - } - - /// - /// Remove all properties from the properties collection - /// - /// - /// - /// Remove all properties from the properties collection - /// - /// - public override void Clear() - { - InnerHashtable.Clear(); - } - - /// - /// See - /// - /// the key - /// the value to store for the key - /// - /// - /// Store a value for the specified . - /// - /// - /// Thrown if the is not a string - void IDictionary.Add(object key, object value) - { - if (!(key is string)) - { - throw new ArgumentException("key must be a string", "key"); - } - InnerHashtable.Add(key, value); - } - - /// - /// See - /// - /// - /// false - /// - /// - /// - /// This collection is modifiable. This property always - /// returns false. - /// - /// - bool IDictionary.IsReadOnly - { - get { return false; } - } - - /// - /// See - /// - /// - /// The value for the key specified. - /// - /// - /// - /// Get or set a value for the specified . - /// - /// - /// Thrown if the is not a string - object IDictionary.this[object key] - { - get - { - if (!(key is string)) - { - throw new ArgumentException("key must be a string", "key"); - } - return InnerHashtable[key]; - } - set - { - if (!(key is string)) - { - throw new ArgumentException("key must be a string", "key"); - } - InnerHashtable[key] = value; - } - } - - /// - /// See - /// - ICollection IDictionary.Values - { - get { return InnerHashtable.Values; } - } - - /// - /// See - /// - ICollection IDictionary.Keys - { - get { return InnerHashtable.Keys; } - } - - /// - /// See - /// - bool IDictionary.IsFixedSize - { - get { return false; } - } - - #endregion - - #region Implementation of ICollection - - /// - /// See - /// - /// - /// - void ICollection.CopyTo(Array array, int index) - { - InnerHashtable.CopyTo(array, index); - } - - /// - /// See - /// - bool ICollection.IsSynchronized - { - get { return InnerHashtable.IsSynchronized; } - } - - /// - /// See - /// - object ICollection.SyncRoot - { - get { return InnerHashtable.SyncRoot; } - } - - #endregion - - #region Implementation of IEnumerable - - /// - /// See - /// - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)InnerHashtable).GetEnumerator(); - } - - #endregion - } -} - + + /// + /// Gets or sets the value of the property with the specified key. + /// + /// + /// The value of the property with the specified key. + /// + /// The key of the property to get or set. + /// + /// + /// The property value will only be serialized if it is serializable. + /// If it cannot be serialized it will be silently ignored if + /// a serialization operation is performed. + /// + /// + public override object this[string key] + { + get { return this.InnerHashtable[key]; } + set { this.InnerHashtable[key] = value; } + } + + /// + /// Remove the entry with the specified key from this dictionary. + /// + /// the key for the entry to remove. + /// + /// + /// Remove the entry with the specified key from this dictionary. + /// + /// + public void Remove(string key) + { + this.InnerHashtable.Remove(key); + } + + /// + /// See . + /// + /// an enumerator. + /// + /// + /// Returns a over the contest of this collection. + /// + /// + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return this.InnerHashtable.GetEnumerator(); + } + + /// + /// See . + /// + /// the key to remove. + /// + /// + /// Remove the entry with the specified key from this dictionary. + /// + /// + void IDictionary.Remove(object key) + { + this.InnerHashtable.Remove(key); + } + + /// + /// See . + /// + /// the key to lookup in the collection. + /// true if the collection contains the specified key. + /// + /// + /// Test if this collection contains a specified key. + /// + /// + bool IDictionary.Contains(object key) + { + return this.InnerHashtable.Contains(key); + } + + /// + /// Remove all properties from the properties collection. + /// + /// + /// + /// Remove all properties from the properties collection. + /// + /// + public override void Clear() + { + this.InnerHashtable.Clear(); + } + + /// + /// See . + /// + /// the key. + /// the value to store for the key. + /// + /// + /// Store a value for the specified . + /// + /// + /// Thrown if the is not a string. + void IDictionary.Add(object key, object value) + { + if (!(key is string)) + { + throw new ArgumentException("key must be a string", "key"); + } + + this.InnerHashtable.Add(key, value); + } + + /// + /// Gets a value indicating whether see . + /// + /// + /// false. + /// + /// + /// + /// This collection is modifiable. This property always + /// returns false. + /// + /// + bool IDictionary.IsReadOnly + { + get { return false; } + } + + /// + /// See . + /// + /// + /// The value for the key specified. + /// + /// + /// + /// Get or set a value for the specified . + /// + /// + /// Thrown if the is not a string. + object IDictionary.this[object key] + { + get + { + if (!(key is string)) + { + throw new ArgumentException("key must be a string", "key"); + } + + return this.InnerHashtable[key]; + } + + set + { + if (!(key is string)) + { + throw new ArgumentException("key must be a string", "key"); + } + + this.InnerHashtable[key] = value; + } + } + + /// + /// Gets see . + /// + ICollection IDictionary.Values + { + get { return this.InnerHashtable.Values; } + } + + /// + /// Gets see . + /// + ICollection IDictionary.Keys + { + get { return this.InnerHashtable.Keys; } + } + + /// + /// Gets a value indicating whether see . + /// + bool IDictionary.IsFixedSize + { + get { return false; } + } + + /// + /// See . + /// + /// + /// + void ICollection.CopyTo(Array array, int index) + { + this.InnerHashtable.CopyTo(array, index); + } + + /// + /// Gets a value indicating whether see . + /// + bool ICollection.IsSynchronized + { + get { return this.InnerHashtable.IsSynchronized; } + } + + /// + /// Gets see . + /// + object ICollection.SyncRoot + { + get { return this.InnerHashtable.SyncRoot; } + } + + /// + /// See . + /// + /// + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this.InnerHashtable).GetEnumerator(); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs index aeba757a7dc..3d4dce2d9f8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -26,11 +26,11 @@ namespace log4net.Util { /// - /// A class to hold the key and data for a property set in the config file + /// A class to hold the key and data for a property set in the config file. /// /// /// - /// A class to hold the key and data for a property set in the config file + /// A class to hold the key and data for a property set in the config file. /// /// public class PropertyEntry @@ -39,10 +39,10 @@ public class PropertyEntry private object m_value = null; /// - /// Property Key + /// Gets or sets property Key. /// /// - /// Property Key + /// Property Key. /// /// /// @@ -51,15 +51,15 @@ public class PropertyEntry /// public string Key { - get { return m_key; } - set { m_key = value; } + get { return this.m_key; } + set { this.m_key = value; } } /// - /// Property Value + /// Gets or sets property Value. /// /// - /// Property Value + /// Property Value. /// /// /// @@ -68,17 +68,17 @@ public string Key /// public object Value { - get { return m_value; } - set { m_value = value; } + get { return this.m_value; } + set { this.m_value = value; } } /// - /// Override Object.ToString to return sensible debug info + /// Override Object.ToString to return sensible debug info. /// - /// string info about this object + /// string info about this object. public override string ToString() { - return "PropertyEntry(Key=" + m_key + ", Value=" + m_value + ")"; + return "PropertyEntry(Key=" + this.m_key + ", Value=" + this.m_value + ")"; } } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs index 16c567252f3..b82e1569c5d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs @@ -1,97 +1,84 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; -using System.Text; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// A that ignores the message - /// - /// - /// - /// This writer is used in special cases where it is necessary - /// to protect a writer from being closed by a client. - /// - /// - /// Nicko Cadell - public class ProtectCloseTextWriter : TextWriterAdapter - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// the writer to actually write to - /// - /// - /// Create a new ProtectCloseTextWriter using a writer - /// - /// - public ProtectCloseTextWriter(TextWriter writer) : base(writer) - { - } - - #endregion Public Instance Constructors - - #region Public Properties - - /// - /// Attach this instance to a different underlying - /// - /// the writer to attach to - /// - /// - /// Attach this instance to a different underlying - /// - /// - public void Attach(TextWriter writer) - { - this.Writer = writer; - } - - #endregion - - #region Override Implementation of TextWriter - - /// - /// Does not close the underlying output writer. - /// - /// - /// - /// Does not close the underlying output writer. - /// This method does nothing. - /// - /// - override public void Close() - { - // do nothing - } - - #endregion Public Instance Methods - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + using log4net.Core; + + /// + /// A that ignores the message. + /// + /// + /// + /// This writer is used in special cases where it is necessary + /// to protect a writer from being closed by a client. + /// + /// + /// Nicko Cadell. + public class ProtectCloseTextWriter : TextWriterAdapter + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// the writer to actually write to. + /// + /// + /// Create a new ProtectCloseTextWriter using a writer. + /// + /// + public ProtectCloseTextWriter(TextWriter writer) + : base(writer) + { + } + + /// + /// Attach this instance to a different underlying . + /// + /// the writer to attach to. + /// + /// + /// Attach this instance to a different underlying . + /// + /// + public void Attach(TextWriter writer) + { + this.Writer = writer; + } + + /// + /// Does not close the underlying output writer. + /// + /// + /// + /// Does not close the underlying output writer. + /// This method does nothing. + /// + /// + public override void Close() + { + // do nothing + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs index 98f91b3f8ca..07299581e24 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs @@ -1,209 +1,195 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.IO; - -using log4net.Core; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// that does not leak exceptions - /// - /// - /// - /// does not throw exceptions when things go wrong. - /// Instead, it delegates error handling to its . - /// - /// - /// Nicko Cadell - /// Gert Driesen - public class QuietTextWriter : TextWriterAdapter - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// the writer to actually write to - /// the error handler to report error to - /// - /// - /// Create a new QuietTextWriter using a writer and error handler - /// - /// - public QuietTextWriter(TextWriter writer, IErrorHandler errorHandler) : base(writer) - { - if (errorHandler == null) - { - throw new ArgumentNullException("errorHandler"); - } - ErrorHandler = errorHandler; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the error handler that all errors are passed to. - /// - /// - /// The error handler that all errors are passed to. - /// - /// - /// - /// Gets or sets the error handler that all errors are passed to. - /// - /// - public IErrorHandler ErrorHandler - { - get { return m_errorHandler; } - set - { - if (value == null) - { - // This is a programming error on the part of the enclosing appender. - throw new ArgumentNullException("value"); - } - m_errorHandler = value; - } - } - - /// - /// Gets a value indicating whether this writer is closed. - /// - /// - /// true if this writer is closed, otherwise false. - /// - /// - /// - /// Gets a value indicating whether this writer is closed. - /// - /// - public bool Closed - { - get { return m_closed; } - } - - #endregion Public Instance Properties - - #region Override Implementation of TextWriter - - /// - /// Writes a character to the underlying writer - /// - /// the char to write - /// - /// - /// Writes a character to the underlying writer - /// - /// - public override void Write(char value) - { - try - { - base.Write(value); - } - catch(Exception e) - { - m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); - } - } - - /// - /// Writes a buffer to the underlying writer - /// - /// the buffer to write - /// the start index to write from - /// the number of characters to write - /// - /// - /// Writes a buffer to the underlying writer - /// - /// - public override void Write(char[] buffer, int index, int count) - { - try - { - base.Write(buffer, index, count); - } - catch(Exception e) - { - m_errorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); - } - } - - /// - /// Writes a string to the output. - /// - /// The string data to write to the output. - /// - /// - /// Writes a string to the output. - /// - /// - override public void Write(string value) - { - try - { - base.Write(value); - } - catch(Exception e) - { - m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); - } - } - - /// - /// Closes the underlying output writer. - /// - /// - /// - /// Closes the underlying output writer. - /// - /// - override public void Close() - { - m_closed = true; - base.Close(); - } - - #endregion Public Instance Methods - - #region Private Instance Fields - - /// - /// The error handler instance to pass all errors to - /// - private IErrorHandler m_errorHandler; - - /// - /// Flag to indicate if this writer is closed - /// - private bool m_closed = false; - - #endregion Private Instance Fields - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + + using log4net.Core; + + /// + /// that does not leak exceptions. + /// + /// + /// + /// does not throw exceptions when things go wrong. + /// Instead, it delegates error handling to its . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public class QuietTextWriter : TextWriterAdapter + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// the writer to actually write to. + /// the error handler to report error to. + /// + /// + /// Create a new QuietTextWriter using a writer and error handler. + /// + /// + public QuietTextWriter(TextWriter writer, IErrorHandler errorHandler) + : base(writer) + { + if (errorHandler == null) + { + throw new ArgumentNullException("errorHandler"); + } + + this.ErrorHandler = errorHandler; + } + + /// + /// Gets or sets the error handler that all errors are passed to. + /// + /// + /// The error handler that all errors are passed to. + /// + /// + /// + /// Gets or sets the error handler that all errors are passed to. + /// + /// + public IErrorHandler ErrorHandler + { + get { return this.m_errorHandler; } + + set + { + if (value == null) + { + // This is a programming error on the part of the enclosing appender. + throw new ArgumentNullException("value"); + } + + this.m_errorHandler = value; + } + } + + /// + /// Gets a value indicating whether this writer is closed. + /// + /// + /// true if this writer is closed, otherwise false. + /// + /// + /// + /// Gets a value indicating whether this writer is closed. + /// + /// + public bool Closed + { + get { return this.m_closed; } + } + + /// + /// Writes a character to the underlying writer. + /// + /// the char to write. + /// + /// + /// Writes a character to the underlying writer. + /// + /// + public override void Write(char value) + { + try + { + base.Write(value); + } + catch (Exception e) + { + this.m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); + } + } + + /// + /// Writes a buffer to the underlying writer. + /// + /// the buffer to write. + /// the start index to write from. + /// the number of characters to write. + /// + /// + /// Writes a buffer to the underlying writer. + /// + /// + public override void Write(char[] buffer, int index, int count) + { + try + { + base.Write(buffer, index, count); + } + catch (Exception e) + { + this.m_errorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); + } + } + + /// + /// Writes a string to the output. + /// + /// The string data to write to the output. + /// + /// + /// Writes a string to the output. + /// + /// + public override void Write(string value) + { + try + { + base.Write(value); + } + catch (Exception e) + { + this.m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); + } + } + + /// + /// Closes the underlying output writer. + /// + /// + /// + /// Closes the underlying output writer. + /// + /// + public override void Close() + { + this.m_closed = true; + base.Close(); + } + + /// + /// The error handler instance to pass all errors to. + /// + private IErrorHandler m_errorHandler; + + /// + /// Flag to indicate if this writer is closed. + /// + private bool m_closed = false; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs index 39bbb99e9c9..c09d93af17c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs @@ -1,224 +1,205 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; -using System.Reflection; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if !NETCF using System.Runtime.Serialization; using System.Xml; + #endif namespace log4net.Util { - /// - /// String keyed object map that is read only. - /// - /// - /// - /// This collection is readonly and cannot be modified. - /// - /// - /// While this collection is serializable only member - /// objects that are serializable will - /// be serialized along with this collection. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + using System.Reflection; + + /// + /// String keyed object map that is read only. + /// + /// + /// + /// This collection is readonly and cannot be modified. + /// + /// + /// While this collection is serializable only member + /// objects that are serializable will + /// be serialized along with this collection. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if NETCF public class ReadOnlyPropertiesDictionary : IDictionary #else - [Serializable] public class ReadOnlyPropertiesDictionary : ISerializable, IDictionary + [Serializable] + public class ReadOnlyPropertiesDictionary : ISerializable, IDictionary #endif - { - #region Private Instance Fields - - /// - /// The Hashtable used to store the properties data - /// - private readonly Hashtable m_hashtable = new Hashtable(); - - #endregion Private Instance Fields - - #region Public Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ReadOnlyPropertiesDictionary() - { - } - - /// - /// Copy Constructor - /// - /// properties to copy - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ReadOnlyPropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) - { - foreach(DictionaryEntry entry in propertiesDictionary) - { - InnerHashtable.Add(entry.Key, entry.Value); - } - } - - #endregion Public Instance Constructors - - #region Private Instance Constructors - + { + /// + /// The Hashtable used to store the properties data. + /// + private readonly Hashtable m_hashtable = new Hashtable(); + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ReadOnlyPropertiesDictionary() + { + } + + /// + /// Initializes a new instance of the class. + /// Copy Constructor. + /// + /// properties to copy. + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ReadOnlyPropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) + { + foreach (DictionaryEntry entry in propertiesDictionary) + { + this.InnerHashtable.Add(entry.Key, entry.Value); + } + } + #if !(NETCF || NETSTANDARD1_3) - /// - /// Deserialization constructor - /// - /// The that holds the serialized object data. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected ReadOnlyPropertiesDictionary(SerializationInfo info, StreamingContext context) - { - foreach(SerializationEntry entry in info) - { - // The keys are stored as Xml encoded names - InnerHashtable[XmlConvert.DecodeName(entry.Name)] = entry.Value; - } - } + /// + /// Initializes a new instance of the class. + /// Deserialization constructor. + /// + /// The that holds the serialized object data. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected ReadOnlyPropertiesDictionary(SerializationInfo info, StreamingContext context) + { + foreach (SerializationEntry entry in info) + { + // The keys are stored as Xml encoded names + this.InnerHashtable[XmlConvert.DecodeName(entry.Name)] = entry.Value; + } + } #endif - - #endregion Protected Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the key names. - /// - /// An array of all the keys. - /// - /// - /// Gets the key names. - /// - /// - public string[] GetKeys() - { - string[] keys = new String[InnerHashtable.Count]; - InnerHashtable.Keys.CopyTo(keys, 0); - return keys; - } - - /// - /// Gets or sets the value of the property with the specified key. - /// - /// - /// The value of the property with the specified key. - /// - /// The key of the property to get or set. - /// - /// - /// The property value will only be serialized if it is serializable. - /// If it cannot be serialized it will be silently ignored if - /// a serialization operation is performed. - /// - /// - public virtual object this[string key] - { - get { return InnerHashtable[key]; } - set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } - } - - #endregion Public Instance Properties - - #region Public Instance Methods - - /// - /// Test if the dictionary contains a specified key - /// - /// the key to look for - /// true if the dictionary contains the specified key - /// - /// - /// Test if the dictionary contains a specified key - /// - /// - public bool Contains(string key) - { - return InnerHashtable.Contains(key); - } - - #endregion - - /// - /// The hashtable used to store the properties - /// - /// - /// The internal collection used to store the properties - /// - /// - /// - /// The hashtable used to store the properties - /// - /// - protected Hashtable InnerHashtable - { - get { return m_hashtable; } - } - - #region Implementation of ISerializable - + + /// + /// Gets the key names. + /// + /// An array of all the keys. + /// + /// + /// Gets the key names. + /// + /// + public string[] GetKeys() + { + string[] keys = new string[this.InnerHashtable.Count]; + this.InnerHashtable.Keys.CopyTo(keys, 0); + return keys; + } + + /// + /// Gets or sets the value of the property with the specified key. + /// + /// + /// The value of the property with the specified key. + /// + /// The key of the property to get or set. + /// + /// + /// The property value will only be serialized if it is serializable. + /// If it cannot be serialized it will be silently ignored if + /// a serialization operation is performed. + /// + /// + public virtual object this[string key] + { + get { return this.InnerHashtable[key]; } + set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } + } + + /// + /// Test if the dictionary contains a specified key. + /// + /// the key to look for. + /// true if the dictionary contains the specified key. + /// + /// + /// Test if the dictionary contains a specified key. + /// + /// + public bool Contains(string key) + { + return this.InnerHashtable.Contains(key); + } + + /// + /// Gets the hashtable used to store the properties. + /// + /// + /// The internal collection used to store the properties. + /// + /// + /// + /// The hashtable used to store the properties. + /// + /// + protected Hashtable InnerHashtable + { + get { return this.m_hashtable; } + } + #if !NETCF - /// - /// Serializes this object into the provided. - /// - /// The to populate with data. - /// The destination for this serialization. - /// - /// - /// Serializes this object into the provided. - /// - /// + /// + /// Serializes this object into the provided. + /// + /// The to populate with data. + /// The destination for this serialization. + /// + /// + /// Serializes this object into the provided. + /// + /// #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecurityCritical] #else [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] #endif public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - foreach(DictionaryEntry entry in InnerHashtable.Clone() as IDictionary) - { - string entryKey = entry.Key as string; - object entryValue = entry.Value; + { + foreach (DictionaryEntry entry in this.InnerHashtable.Clone() as IDictionary) + { + string entryKey = entry.Key as string; + object entryValue = entry.Value; // If value is serializable then we add it to the list #if NETSTANDARD1_3 @@ -226,166 +207,158 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte #else bool isSerializable = entryValue.GetType().IsSerializable; #endif - if (entryKey != null && entryValue != null && isSerializable) - { - // Store the keys as an Xml encoded local name as it may contain colons (':') - // which are NOT escaped by the Xml Serialization framework. - // This must be a bug in the serialization framework as we cannot be expected - // to know the implementation details of all the possible transport layers. - info.AddValue(XmlConvert.EncodeLocalName(entryKey), entryValue); - } - } - } + if (entryKey != null && entryValue != null && isSerializable) + { + // Store the keys as an Xml encoded local name as it may contain colons (':') + // which are NOT escaped by the Xml Serialization framework. + // This must be a bug in the serialization framework as we cannot be expected + // to know the implementation details of all the possible transport layers. + info.AddValue(XmlConvert.EncodeLocalName(entryKey), entryValue); + } + } + } #endif - - #endregion Implementation of ISerializable - - #region Implementation of IDictionary - - /// - /// See - /// - IDictionaryEnumerator IDictionary.GetEnumerator() - { - return InnerHashtable.GetEnumerator(); - } - - /// - /// See - /// - /// - void IDictionary.Remove(object key) - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - - /// - /// See - /// - /// - /// - bool IDictionary.Contains(object key) - { - return InnerHashtable.Contains(key); - } - - /// - /// Remove all properties from the properties collection - /// - public virtual void Clear() - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - - /// - /// See - /// - /// - /// - void IDictionary.Add(object key, object value) - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - - /// - /// See - /// - bool IDictionary.IsReadOnly - { - get { return true; } - } - - /// - /// See - /// - object IDictionary.this[object key] - { - get - { - if (!(key is string)) throw new ArgumentException("key must be a string"); - return InnerHashtable[key]; - } - set - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - } - - /// - /// See - /// - ICollection IDictionary.Values - { - get { return InnerHashtable.Values; } - } - - /// - /// See - /// - ICollection IDictionary.Keys - { - get { return InnerHashtable.Keys; } - } - - /// - /// See - /// - bool IDictionary.IsFixedSize - { - get { return InnerHashtable.IsFixedSize; } - } - - #endregion - - #region Implementation of ICollection - - /// - /// See - /// - /// - /// - void ICollection.CopyTo(Array array, int index) - { - InnerHashtable.CopyTo(array, index); - } - - /// - /// See - /// - bool ICollection.IsSynchronized - { - get { return InnerHashtable.IsSynchronized; } - } - - /// - /// The number of properties in this collection - /// - public int Count - { - get { return InnerHashtable.Count; } - } - - /// - /// See - /// - object ICollection.SyncRoot - { - get { return InnerHashtable.SyncRoot; } - } - - #endregion - - #region Implementation of IEnumerable - - /// - /// See - /// - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)InnerHashtable).GetEnumerator(); - } - - #endregion - } -} - + + /// + /// See . + /// + /// + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return this.InnerHashtable.GetEnumerator(); + } + + /// + /// See . + /// + /// + void IDictionary.Remove(object key) + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); + } + + /// + /// See . + /// + /// + /// + bool IDictionary.Contains(object key) + { + return this.InnerHashtable.Contains(key); + } + + /// + /// Remove all properties from the properties collection. + /// + public virtual void Clear() + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); + } + + /// + /// See . + /// + /// + /// + void IDictionary.Add(object key, object value) + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); + } + + /// + /// Gets a value indicating whether see . + /// + bool IDictionary.IsReadOnly + { + get { return true; } + } + + /// + /// See . + /// + object IDictionary.this[object key] + { + get + { + if (!(key is string)) + { + throw new ArgumentException("key must be a string"); + } + + return this.InnerHashtable[key]; + } + + set + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); + } + } + + /// + /// Gets see . + /// + ICollection IDictionary.Values + { + get { return this.InnerHashtable.Values; } + } + + /// + /// Gets see . + /// + ICollection IDictionary.Keys + { + get { return this.InnerHashtable.Keys; } + } + + /// + /// Gets a value indicating whether see . + /// + bool IDictionary.IsFixedSize + { + get { return this.InnerHashtable.IsFixedSize; } + } + + /// + /// See . + /// + /// + /// + void ICollection.CopyTo(Array array, int index) + { + this.InnerHashtable.CopyTo(array, index); + } + + /// + /// Gets a value indicating whether see . + /// + bool ICollection.IsSynchronized + { + get { return this.InnerHashtable.IsSynchronized; } + } + + /// + /// Gets the number of properties in this collection. + /// + public int Count + { + get { return this.InnerHashtable.Count; } + } + + /// + /// Gets see . + /// + object ICollection.SyncRoot + { + get { return this.InnerHashtable.SyncRoot; } + } + + /// + /// See . + /// + /// + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this.InnerHashtable).GetEnumerator(); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs index 52e5cca8397..510550a3028 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,9 +18,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - -#if (!NETCF) +#if !NETCF #define HAS_READERWRITERLOCK #endif #if NET_4_0 || MONO_4_0 @@ -32,94 +29,90 @@ namespace log4net.Util { - /// - /// Defines a lock that supports single writers and multiple readers - /// - /// - /// - /// ReaderWriterLock is used to synchronize access to a resource. - /// At any given time, it allows either concurrent read access for - /// multiple threads, or write access for a single thread. In a - /// situation where a resource is changed infrequently, a - /// ReaderWriterLock provides better throughput than a simple - /// one-at-a-time lock, such as . - /// - /// - /// If a platform does not support a System.Threading.ReaderWriterLock - /// implementation then all readers and writers are serialized. Therefore - /// the caller must not rely on multiple simultaneous readers. - /// - /// - /// Nicko Cadell - public sealed class ReaderWriterLock - { - #region Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ReaderWriterLock() - { - + /// + /// Defines a lock that supports single writers and multiple readers. + /// + /// + /// + /// ReaderWriterLock is used to synchronize access to a resource. + /// At any given time, it allows either concurrent read access for + /// multiple threads, or write access for a single thread. In a + /// situation where a resource is changed infrequently, a + /// ReaderWriterLock provides better throughput than a simple + /// one-at-a-time lock, such as . + /// + /// + /// If a platform does not support a System.Threading.ReaderWriterLock + /// implementation then all readers and writers are serialized. Therefore + /// the caller must not rely on multiple simultaneous readers. + /// + /// + /// Nicko Cadell. + public sealed class ReaderWriterLock + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ReaderWriterLock() + { #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - m_lock = new System.Threading.ReaderWriterLockSlim(System.Threading.LockRecursionPolicy.SupportsRecursion); + this.m_lock = new System.Threading.ReaderWriterLockSlim(System.Threading.LockRecursionPolicy.SupportsRecursion); #else m_lock = new System.Threading.ReaderWriterLock(); #endif #endif - } - - #endregion Private Instance Constructors - - #region Public Methods - - /// - /// Acquires a reader lock - /// - /// - /// - /// blocks if a different thread has the writer - /// lock, or if at least one thread is waiting for the writer lock. - /// - /// - public void AcquireReaderLock() - { + } + + /// + /// Acquires a reader lock. + /// + /// + /// + /// blocks if a different thread has the writer + /// lock, or if at least one thread is waiting for the writer lock. + /// + /// + public void AcquireReaderLock() + { #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 - try { } - finally - { - m_lock.EnterReadLock(); - } + // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 + try + { + } + finally + { + this.m_lock.EnterReadLock(); + } #else m_lock.AcquireReaderLock(-1); #endif #else System.Threading.Monitor.Enter(this); #endif - } - - /// - /// Decrements the lock count - /// - /// - /// - /// decrements the lock count. When the count - /// reaches zero, the lock is released. - /// - /// - public void ReleaseReaderLock() - { + } + + /// + /// Decrements the lock count. + /// + /// + /// + /// decrements the lock count. When the count + /// reaches zero, the lock is released. + /// + /// + public void ReleaseReaderLock() + { #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - m_lock.ExitReadLock(); + this.m_lock.ExitReadLock(); #else m_lock.ReleaseReaderLock(); @@ -127,69 +120,66 @@ public void ReleaseReaderLock() #else System.Threading.Monitor.Exit(this); #endif - } - - /// - /// Acquires the writer lock - /// - /// - /// - /// This method blocks if another thread has a reader lock or writer lock. - /// - /// - public void AcquireWriterLock() - { + } + + /// + /// Acquires the writer lock. + /// + /// + /// + /// This method blocks if another thread has a reader lock or writer lock. + /// + /// + public void AcquireWriterLock() + { #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 - try { } - finally - { - m_lock.EnterWriteLock(); - } + // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 + try + { + } + finally + { + this.m_lock.EnterWriteLock(); + } #else m_lock.AcquireWriterLock(-1); #endif #else System.Threading.Monitor.Enter(this); #endif - } - - /// - /// Decrements the lock count on the writer lock - /// - /// - /// - /// ReleaseWriterLock decrements the writer lock count. - /// When the count reaches zero, the writer lock is released. - /// - /// - public void ReleaseWriterLock() - { + } + + /// + /// Decrements the lock count on the writer lock. + /// + /// + /// + /// ReleaseWriterLock decrements the writer lock count. + /// When the count reaches zero, the writer lock is released. + /// + /// + public void ReleaseWriterLock() + { #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - m_lock.ExitWriteLock(); + this.m_lock.ExitWriteLock(); #else m_lock.ReleaseWriterLock(); #endif #else System.Threading.Monitor.Exit(this); #endif - } - - #endregion Public Methods - - #region Private Members - + } + #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - private System.Threading.ReaderWriterLockSlim m_lock; + private System.Threading.ReaderWriterLockSlim m_lock; #else private System.Threading.ReaderWriterLock m_lock; #endif - + #endif - - #endregion - } + + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs index 8f1da56c186..ad6fabf7c1e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs @@ -1,98 +1,93 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// A that can be and reused - /// - /// - /// - /// A that can be and reused. - /// This uses a single buffer for string operations. - /// - /// - /// Nicko Cadell - public class ReusableStringWriter : StringWriter - { - #region Constructor - - /// - /// Create an instance of - /// - /// the format provider to use - /// - /// - /// Create an instance of - /// - /// - public ReusableStringWriter(IFormatProvider formatProvider) : base(formatProvider) - { - } - - #endregion + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.IO; + using System.Text; + + /// + /// A that can be and reused. + /// + /// + /// + /// A that can be and reused. + /// This uses a single buffer for string operations. + /// + /// + /// Nicko Cadell. + public class ReusableStringWriter : StringWriter + { + /// + /// Initializes a new instance of the class. + /// Create an instance of . + /// + /// the format provider to use. + /// + /// + /// Create an instance of . + /// + /// + public ReusableStringWriter(IFormatProvider formatProvider) + : base(formatProvider) + { + } + + /// + /// Override Dispose to prevent closing of writer. + /// + /// flag. + /// + /// + /// Override Dispose to prevent closing of writer. + /// + /// + protected override void Dispose(bool disposing) + { + // Do not close the writer + } - /// - /// Override Dispose to prevent closing of writer - /// - /// flag - /// - /// - /// Override Dispose to prevent closing of writer - /// - /// - protected override void Dispose(bool disposing) - { - // Do not close the writer - } + /// + /// Reset this string writer so that it can be reused. + /// + /// the maximum buffer capacity before it is trimmed. + /// the default size to make the buffer. + /// + /// + /// Reset this string writer so that it can be reused. + /// The internal buffers are cleared and reset. + /// + /// + public void Reset(int maxCapacity, int defaultSize) + { + // Reset working string buffer + StringBuilder sb = this.GetStringBuilder(); - /// - /// Reset this string writer so that it can be reused. - /// - /// the maximum buffer capacity before it is trimmed - /// the default size to make the buffer - /// - /// - /// Reset this string writer so that it can be reused. - /// The internal buffers are cleared and reset. - /// - /// - public void Reset(int maxCapacity, int defaultSize) - { - // Reset working string buffer - StringBuilder sb = this.GetStringBuilder(); + sb.Length = 0; - sb.Length = 0; - - // Check if over max size - if (sb.Capacity > maxCapacity) - { - sb.Capacity = defaultSize; - } - } - } + // Check if over max size + if (sb.Capacity > maxCapacity) + { + sb.Capacity = defaultSize; + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs index 8bbbf76b486..1bd60bcb5e3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs @@ -1,411 +1,400 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + + #if NETSTANDARD1_3 using System.Globalization; #else using System.Configuration; + #endif -using System.Reflection; -using System.Text; +using System.Collections; using System.IO; +using System.Reflection; using System.Runtime.InteropServices; -using System.Collections; +using System.Text; namespace log4net.Util { - /// - /// Utility class for system specific information. - /// - /// - /// - /// Utility class of static methods for system specific information. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Alexey Solofnenko - public sealed class SystemInfo - { - #region Private Constants - - private const string DEFAULT_NULL_TEXT = "(null)"; - private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE"; - - #endregion - - #region Private Instance Constructors - - /// - /// Private constructor to prevent instances. - /// - /// - /// - /// Only static methods are exposed from this type. - /// - /// - private SystemInfo() - { - } - - #endregion Private Instance Constructors - - #region Public Static Constructor - - /// - /// Initialize default values for private static fields. - /// - /// - /// - /// Only static methods are exposed from this type. - /// - /// - static SystemInfo() - { - string nullText = DEFAULT_NULL_TEXT; - string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT; + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Utility class for system specific information. + /// + /// + /// + /// Utility class of static methods for system specific information. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + /// Alexey Solofnenko. + public sealed class SystemInfo + { + private const string DEFAULT_NULL_TEXT = "(null)"; + private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE"; + + /// + /// Initializes a new instance of the class. + /// Private constructor to prevent instances. + /// + /// + /// + /// Only static methods are exposed from this type. + /// + /// + private SystemInfo() + { + } + + /// + /// Initializes static members of the class. + /// Initialize default values for private static fields. + /// + /// + /// + /// Only static methods are exposed from this type. + /// + /// + static SystemInfo() + { + string nullText = DEFAULT_NULL_TEXT; + string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT; #if !NETCF - // Look for log4net.NullText in AppSettings - string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText"); - if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0) - { - LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "]."); - nullText = nullTextAppSettingsKey; - } + // Look for log4net.NullText in AppSettings + string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText"); + if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0) + { + LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "]."); + nullText = nullTextAppSettingsKey; + } - // Look for log4net.NotAvailableText in AppSettings - string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText"); - if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0) - { - LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "]."); - notAvailableText = notAvailableTextAppSettingsKey; - } + // Look for log4net.NotAvailableText in AppSettings + string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText"); + if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0) + { + LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "]."); + notAvailableText = notAvailableTextAppSettingsKey; + } #endif - s_notAvailableText = notAvailableText; - s_nullText = nullText; - } - - #endregion - - #region Public Static Properties - - /// - /// Gets the system dependent line terminator. - /// - /// - /// The system dependent line terminator. - /// - /// - /// - /// Gets the system dependent line terminator. - /// - /// - public static string NewLine - { - get - { + s_notAvailableText = notAvailableText; + s_nullText = nullText; + } + + /// + /// Gets the system dependent line terminator. + /// + /// + /// The system dependent line terminator. + /// + /// + /// + /// Gets the system dependent line terminator. + /// + /// + public static string NewLine + { + get + { #if NETCF return "\r\n"; #else - return System.Environment.NewLine; + return System.Environment.NewLine; #endif - } - } + } + } - /// - /// Gets the base directory for this . - /// - /// The base directory path for the current . - /// - /// - /// Gets the base directory for this . - /// - /// - /// The value returned may be either a local file path or a URI. - /// - /// - public static string ApplicationBaseDirectory - { - get - { + /// + /// Gets the base directory for this . + /// + /// The base directory path for the current . + /// + /// + /// Gets the base directory for this . + /// + /// + /// The value returned may be either a local file path or a URI. + /// + /// + public static string ApplicationBaseDirectory + { + get + { #if NETCF - return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar; #elif NETSTANDARD1_3 return Directory.GetCurrentDirectory(); #else - return AppDomain.CurrentDomain.BaseDirectory; + return AppDomain.CurrentDomain.BaseDirectory; #endif - } - } + } + } - /// - /// Gets the path to the configuration file for the current . - /// - /// The path to the configuration file for the current . - /// - /// - /// The .NET Compact Framework 1.0 does not have a concept of a configuration - /// file. For this runtime, we use the entry assembly location as the root for - /// the configuration file name. - /// - /// - /// The value returned may be either a local file path or a URI. - /// - /// - public static string ConfigurationFileLocation - { - get - { + /// + /// Gets the path to the configuration file for the current . + /// + /// The path to the configuration file for the current . + /// + /// + /// The .NET Compact Framework 1.0 does not have a concept of a configuration + /// file. For this runtime, we use the entry assembly location as the root for + /// the configuration file name. + /// + /// + /// The value returned may be either a local file path or a URI. + /// + /// + public static string ConfigurationFileLocation + { + get + { #if NETCF || NETSTANDARD1_3 return SystemInfo.EntryAssemblyLocation+".config"; #else - return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; + return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; #endif - } - } + } + } - /// - /// Gets the path to the file that first executed in the current . - /// - /// The path to the entry assembly. - /// - /// - /// Gets the path to the file that first executed in the current . - /// - /// - public static string EntryAssemblyLocation - { - get - { + /// + /// Gets the path to the file that first executed in the current . + /// + /// The path to the entry assembly. + /// + /// + /// Gets the path to the file that first executed in the current . + /// + /// + public static string EntryAssemblyLocation + { + get + { #if NETCF return SystemInfo.NativeEntryAssemblyLocation; #elif NETSTANDARD1_3 // TODO GetEntryAssembly is available for netstandard1.5 return AppContext.BaseDirectory; #else - return System.Reflection.Assembly.GetEntryAssembly().Location; + return System.Reflection.Assembly.GetEntryAssembly().Location; #endif - } - } + } + } - /// - /// Gets the ID of the current thread. - /// - /// The ID of the current thread. - /// - /// - /// On the .NET framework, the AppDomain.GetCurrentThreadId method - /// is used to obtain the thread ID for the current thread. This is the - /// operating system ID for the thread. - /// - /// - /// On the .NET Compact Framework 1.0 it is not possible to get the - /// operating system thread ID for the current thread. The native method - /// GetCurrentThreadId is implemented inline in a header file - /// and cannot be called. - /// - /// - /// On the .NET Framework 2.0 the Thread.ManagedThreadId is used as this - /// gives a stable id unrelated to the operating system thread ID which may - /// change if the runtime is using fibers. - /// - /// - public static int CurrentThreadId - { - get - { + /// + /// Gets the ID of the current thread. + /// + /// The ID of the current thread. + /// + /// + /// On the .NET framework, the AppDomain.GetCurrentThreadId method + /// is used to obtain the thread ID for the current thread. This is the + /// operating system ID for the thread. + /// + /// + /// On the .NET Compact Framework 1.0 it is not possible to get the + /// operating system thread ID for the current thread. The native method + /// GetCurrentThreadId is implemented inline in a header file + /// and cannot be called. + /// + /// + /// On the .NET Framework 2.0 the Thread.ManagedThreadId is used as this + /// gives a stable id unrelated to the operating system thread ID which may + /// change if the runtime is using fibers. + /// + /// + public static int CurrentThreadId + { + get + { #if NETCF_1_0 return System.Threading.Thread.CurrentThread.GetHashCode(); #elif NET_2_0 || NETCF_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3 - return System.Threading.Thread.CurrentThread.ManagedThreadId; + return System.Threading.Thread.CurrentThread.ManagedThreadId; #else return AppDomain.GetCurrentThreadId(); #endif - } - } - - /// - /// Get the host name or machine name for the current machine - /// - /// - /// The hostname or machine name - /// - /// - /// - /// Get the host name or machine name for the current machine - /// - /// - /// The host name () or - /// the machine name (Environment.MachineName) for - /// the current machine, or if neither of these are available - /// then NOT AVAILABLE is returned. - /// - /// - public static string HostName - { - get - { - if (s_hostName == null) - { - - // Get the DNS host name of the current machine - try - { - // Lookup the host name - s_hostName = System.Net.Dns.GetHostName(); - } - catch (System.Net.Sockets.SocketException) - { - LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored."); - } - catch (System.Security.SecurityException) - { - // We may get a security exception looking up the hostname - // You must have Unrestricted DnsPermission to access resource - LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored."); - } - catch (Exception ex) - { - LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex); - } + } + } - // Get the NETBIOS machine name of the current machine - if (s_hostName == null || s_hostName.Length == 0) - { - try - { + /// + /// Gets get the host name or machine name for the current machine. + /// + /// + /// The hostname or machine name. + /// + /// + /// + /// Get the host name or machine name for the current machine. + /// + /// + /// The host name () or + /// the machine name (Environment.MachineName) for + /// the current machine, or if neither of these are available + /// then NOT AVAILABLE is returned. + /// + /// + public static string HostName + { + get + { + if (s_hostName == null) + { + // Get the DNS host name of the current machine + try + { + // Lookup the host name + s_hostName = System.Net.Dns.GetHostName(); + } + catch (System.Net.Sockets.SocketException) + { + LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored."); + } + catch (System.Security.SecurityException) + { + // We may get a security exception looking up the hostname + // You must have Unrestricted DnsPermission to access resource + LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored."); + } + catch (Exception ex) + { + LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex); + } + + // Get the NETBIOS machine name of the current machine + if (s_hostName == null || s_hostName.Length == 0) + { + try + { #if NETSTANDARD1_3 s_hostName = Environment.GetEnvironmentVariable("COMPUTERNAME"); -#elif (!SSCLI && !NETCF) - s_hostName = Environment.MachineName; +#elif !SSCLI && !NETCF + s_hostName = Environment.MachineName; #endif - } - catch(InvalidOperationException) - { - } - catch(System.Security.SecurityException) - { - // We may get a security exception looking up the machine name - // You must have Unrestricted EnvironmentPermission to access resource - } - } - - // Couldn't find a value - if (s_hostName == null || s_hostName.Length == 0) - { - s_hostName = s_notAvailableText; - LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used"); - } - } - return s_hostName; - } - } + } + catch (InvalidOperationException) + { + } + catch (System.Security.SecurityException) + { + // We may get a security exception looking up the machine name + // You must have Unrestricted EnvironmentPermission to access resource + } + } + + // Couldn't find a value + if (s_hostName == null || s_hostName.Length == 0) + { + s_hostName = s_notAvailableText; + LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used"); + } + } + + return s_hostName; + } + } - /// - /// Get this application's friendly name - /// - /// - /// The friendly name of this application as a string - /// - /// - /// - /// If available the name of the application is retrieved from - /// the AppDomain using AppDomain.CurrentDomain.FriendlyName. - /// - /// - /// Otherwise the file name of the entry assembly is used. - /// - /// - public static string ApplicationFriendlyName - { - get - { - if (s_appFriendlyName == null) - { - try - { + /// + /// Gets get this application's friendly name. + /// + /// + /// The friendly name of this application as a string. + /// + /// + /// + /// If available the name of the application is retrieved from + /// the AppDomain using AppDomain.CurrentDomain.FriendlyName. + /// + /// + /// Otherwise the file name of the entry assembly is used. + /// + /// + public static string ApplicationFriendlyName + { + get + { + if (s_appFriendlyName == null) + { + try + { #if !(NETCF || NETSTANDARD1_3) - s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName; + s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName; #endif - } - catch(System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored."); - } - - if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) - { - try - { - string assemblyLocation = SystemInfo.EntryAssemblyLocation; - s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation); - } - catch(System.Security.SecurityException) - { - // Caller needs path discovery permission - } - } - - if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) - { - s_appFriendlyName = s_notAvailableText; - } - } - return s_appFriendlyName; - } - } + } + catch (System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored."); + } + + if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) + { + try + { + string assemblyLocation = SystemInfo.EntryAssemblyLocation; + s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation); + } + catch (System.Security.SecurityException) + { + // Caller needs path discovery permission + } + } + + if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) + { + s_appFriendlyName = s_notAvailableText; + } + } + + return s_appFriendlyName; + } + } - /// - /// Get the start time for the current process. - /// - /// - /// - /// This is the time at which the log4net library was loaded into the - /// AppDomain. Due to reports of a hang in the call to System.Diagnostics.Process.StartTime - /// this is not the start time for the current process. - /// - /// - /// The log4net library should be loaded by an application early during its - /// startup, therefore this start time should be a good approximation for - /// the actual start time. - /// - /// - /// Note that AppDomains may be loaded and unloaded within the - /// same process without the process terminating, however this start time - /// will be set per AppDomain. - /// - /// + /// + /// Gets get the start time for the current process. + /// + /// + /// + /// This is the time at which the log4net library was loaded into the + /// AppDomain. Due to reports of a hang in the call to System.Diagnostics.Process.StartTime + /// this is not the start time for the current process. + /// + /// + /// The log4net library should be loaded by an application early during its + /// startup, therefore this start time should be a good approximation for + /// the actual start time. + /// + /// + /// Note that AppDomains may be loaded and unloaded within the + /// same process without the process terminating, however this start time + /// will be set per AppDomain. + /// + /// [Obsolete("Use ProcessStartTimeUtc and convert to local time if needed.. Scheduled removal in v10.0.0.")] - public static DateTime ProcessStartTime - { - get { return s_processStartTimeUtc.ToLocalTime(); } - } + public static DateTime ProcessStartTime + { + get { return s_processStartTimeUtc.ToLocalTime(); } + } /// - /// Get the UTC start time for the current process. + /// Gets get the UTC start time for the current process. /// /// /// @@ -427,83 +416,79 @@ public static DateTime ProcessStartTime public static DateTime ProcessStartTimeUtc { get { return s_processStartTimeUtc; } - } - - /// - /// Text to output when a null is encountered. - /// - /// - /// - /// Use this value to indicate a null has been encountered while - /// outputting a string representation of an item. - /// - /// - /// The default value is (null). This value can be overridden by specifying - /// a value for the log4net.NullText appSetting in the application's - /// .config file. - /// - /// - public static string NullText - { - get { return s_nullText; } - set { s_nullText = value; } - } - - /// - /// Text to output when an unsupported feature is requested. - /// - /// - /// - /// Use this value when an unsupported feature is requested. - /// - /// - /// The default value is NOT AVAILABLE. This value can be overridden by specifying - /// a value for the log4net.NotAvailableText appSetting in the application's - /// .config file. - /// - /// - public static string NotAvailableText - { - get { return s_notAvailableText; } - set { s_notAvailableText = value; } - } - - #endregion Public Static Properties + } - #region Public Static Methods + /// + /// Gets or sets text to output when a null is encountered. + /// + /// + /// + /// Use this value to indicate a null has been encountered while + /// outputting a string representation of an item. + /// + /// + /// The default value is (null). This value can be overridden by specifying + /// a value for the log4net.NullText appSetting in the application's + /// .config file. + /// + /// + public static string NullText + { + get { return s_nullText; } + set { s_nullText = value; } + } - /// - /// Gets the assembly location path for the specified assembly. - /// - /// The assembly to get the location for. - /// The location of the assembly. - /// - /// - /// This method does not guarantee to return the correct path - /// to the assembly. If only tries to give an indication as to - /// where the assembly was loaded from. - /// - /// - public static string AssemblyLocationInfo(Assembly myAssembly) - { + /// + /// Gets or sets text to output when an unsupported feature is requested. + /// + /// + /// + /// Use this value when an unsupported feature is requested. + /// + /// + /// The default value is NOT AVAILABLE. This value can be overridden by specifying + /// a value for the log4net.NotAvailableText appSetting in the application's + /// .config file. + /// + /// + public static string NotAvailableText + { + get { return s_notAvailableText; } + set { s_notAvailableText = value; } + } + + /// + /// Gets the assembly location path for the specified assembly. + /// + /// The assembly to get the location for. + /// The location of the assembly. + /// + /// + /// This method does not guarantee to return the correct path + /// to the assembly. If only tries to give an indication as to + /// where the assembly was loaded from. + /// + /// + public static string AssemblyLocationInfo(Assembly myAssembly) + { #if NETCF return "Not supported on Microsoft .NET Compact Framework"; #elif NETSTANDARD1_3 // TODO Assembly.Location available in netstandard1.5 return "Not supported on .NET Core"; #else - if (myAssembly.GlobalAssemblyCache) - { - return "Global Assembly Cache"; - } - else - { - try - { + if (myAssembly.GlobalAssemblyCache) + { + return "Global Assembly Cache"; + } + else + { + try + { #if NET_4_0 || MONO_4_0 - if (myAssembly.IsDynamic) - { - return "Dynamic Assembly"; - } + if (myAssembly.IsDynamic) + { + return "Dynamic Assembly"; + } #else if (myAssembly is System.Reflection.Emit.AssemblyBuilder) { @@ -514,109 +499,110 @@ public static string AssemblyLocationInfo(Assembly myAssembly) return "Dynamic Assembly"; } #endif - else - { - // This call requires FileIOPermission for access to the path - // if we don't have permission then we just ignore it and - // carry on. - return myAssembly.Location; - } - } - catch (NotSupportedException) - { - // The location information may be unavailable for dynamic assemblies and a NotSupportedException - // is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx - return "Dynamic Assembly"; - } - catch (TargetInvocationException ex) - { - return "Location Detect Failed (" + ex.Message + ")"; - } - catch (ArgumentException ex) - { - return "Location Detect Failed (" + ex.Message + ")"; - } - catch (System.Security.SecurityException) - { - return "Location Permission Denied"; - } - } + else + { + // This call requires FileIOPermission for access to the path + // if we don't have permission then we just ignore it and + // carry on. + return myAssembly.Location; + } + } + catch (NotSupportedException) + { + // The location information may be unavailable for dynamic assemblies and a NotSupportedException + // is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx + return "Dynamic Assembly"; + } + catch (TargetInvocationException ex) + { + return "Location Detect Failed (" + ex.Message + ")"; + } + catch (ArgumentException ex) + { + return "Location Detect Failed (" + ex.Message + ")"; + } + catch (System.Security.SecurityException) + { + return "Location Permission Denied"; + } + } #endif - } + } - /// - /// Gets the fully qualified name of the , including - /// the name of the assembly from which the was - /// loaded. - /// - /// The to get the fully qualified name for. - /// The fully qualified name for the . - /// - /// - /// This is equivalent to the Type.AssemblyQualifiedName property, - /// but this method works on the .NET Compact Framework 1.0 as well as - /// the full .NET runtime. - /// - /// - public static string AssemblyQualifiedName(Type type) - { - return type.FullName + ", " + /// + /// Gets the fully qualified name of the , including + /// the name of the assembly from which the was + /// loaded. + /// + /// The to get the fully qualified name for. + /// The fully qualified name for the . + /// + /// + /// This is equivalent to the Type.AssemblyQualifiedName property, + /// but this method works on the .NET Compact Framework 1.0 as well as + /// the full .NET runtime. + /// + /// + public static string AssemblyQualifiedName(Type type) + { + return type.FullName + ", " #if NETSTANDARD1_3 + type.GetTypeInfo().Assembly.FullName; #else - + type.Assembly.FullName; + + type.Assembly.FullName; #endif - } + } - /// - /// Gets the short name of the . - /// - /// The to get the name for. - /// The short name of the . - /// - /// - /// The short name of the assembly is the - /// without the version, culture, or public key. i.e. it is just the - /// assembly's file name without the extension. - /// - /// - /// Use this rather than Assembly.GetName().Name because that - /// is not available on the Compact Framework. - /// - /// - /// Because of a FileIOPermission security demand we cannot do - /// the obvious Assembly.GetName().Name. We are allowed to get - /// the of the assembly so we - /// start from there and strip out just the assembly name. - /// - /// - public static string AssemblyShortName(Assembly myAssembly) - { - string name = myAssembly.FullName; - int offset = name.IndexOf(','); - if (offset > 0) - { - name = name.Substring(0, offset); - } - return name.Trim(); + /// + /// Gets the short name of the . + /// + /// The to get the name for. + /// The short name of the . + /// + /// + /// The short name of the assembly is the + /// without the version, culture, or public key. i.e. it is just the + /// assembly's file name without the extension. + /// + /// + /// Use this rather than Assembly.GetName().Name because that + /// is not available on the Compact Framework. + /// + /// + /// Because of a FileIOPermission security demand we cannot do + /// the obvious Assembly.GetName().Name. We are allowed to get + /// the of the assembly so we + /// start from there and strip out just the assembly name. + /// + /// + public static string AssemblyShortName(Assembly myAssembly) + { + string name = myAssembly.FullName; + int offset = name.IndexOf(','); + if (offset > 0) + { + name = name.Substring(0, offset); + } + + return name.Trim(); - // TODO: Do we need to unescape the assembly name string? - // Doc says '\' is an escape char but has this already been - // done by the string loader? - } + // TODO: Do we need to unescape the assembly name string? + // Doc says '\' is an escape char but has this already been + // done by the string loader? + } - /// - /// Gets the file name portion of the , including the extension. - /// - /// The to get the file name for. - /// The file name of the assembly. - /// - /// - /// Gets the file name portion of the , including the extension. - /// - /// - public static string AssemblyFileName(Assembly myAssembly) - { + /// + /// Gets the file name portion of the , including the extension. + /// + /// The to get the file name for. + /// The file name of the assembly. + /// + /// + /// Gets the file name portion of the , including the extension. + /// + /// + public static string AssemblyFileName(Assembly myAssembly) + { #if NETCF || NETSTANDARD1_3 // TODO Assembly.Location is in netstandard1.5 System.Reflection // This is not very good because it assumes that only // the entry assembly can be an EXE. In fact multiple @@ -636,229 +622,229 @@ public static string AssemblyFileName(Assembly myAssembly) return assemblyShortName + ".dll"; } #else - return System.IO.Path.GetFileName(myAssembly.Location); + return System.IO.Path.GetFileName(myAssembly.Location); #endif - } + } - /// - /// Loads the type specified in the type string. - /// - /// A sibling type to use to load the type. - /// The name of the type to load. - /// Flag set to true to throw an exception if the type cannot be loaded. - /// true to ignore the case of the type name; otherwise, false - /// The type loaded or null if it could not be loaded. - /// - /// - /// If the type name is fully qualified, i.e. if contains an assembly name in - /// the type name, the type will be loaded from the system using - /// . - /// - /// - /// If the type name is not fully qualified, it will be loaded from the assembly - /// containing the specified relative type. If the type is not found in the assembly - /// then all the loaded assemblies will be searched for the type. - /// - /// - public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase) - { + /// + /// Loads the type specified in the type string. + /// + /// A sibling type to use to load the type. + /// The name of the type to load. + /// Flag set to true to throw an exception if the type cannot be loaded. + /// true to ignore the case of the type name; otherwise, false. + /// The type loaded or null if it could not be loaded. + /// + /// + /// If the type name is fully qualified, i.e. if contains an assembly name in + /// the type name, the type will be loaded from the system using + /// . + /// + /// + /// If the type name is not fully qualified, it will be loaded from the assembly + /// containing the specified relative type. If the type is not found in the assembly + /// then all the loaded assemblies will be searched for the type. + /// + /// + public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase) + { #if NETSTANDARD1_3 return GetTypeFromString(relativeType.GetTypeInfo().Assembly, typeName, throwOnError, ignoreCase); #else - return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase); + return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase); #endif - } + } #if !NETSTANDARD1_3 - /// - /// Loads the type specified in the type string. - /// - /// The name of the type to load. - /// Flag set to true to throw an exception if the type cannot be loaded. - /// true to ignore the case of the type name; otherwise, false - /// The type loaded or null if it could not be loaded. - /// - /// - /// If the type name is fully qualified, i.e. if contains an assembly name in - /// the type name, the type will be loaded from the system using - /// . - /// - /// - /// If the type name is not fully qualified it will be loaded from the - /// assembly that is directly calling this method. If the type is not found - /// in the assembly then all the loaded assemblies will be searched for the type. - /// - /// - public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase) - { - return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase); - } + /// + /// Loads the type specified in the type string. + /// + /// The name of the type to load. + /// Flag set to true to throw an exception if the type cannot be loaded. + /// true to ignore the case of the type name; otherwise, false. + /// The type loaded or null if it could not be loaded. + /// + /// + /// If the type name is fully qualified, i.e. if contains an assembly name in + /// the type name, the type will be loaded from the system using + /// . + /// + /// + /// If the type name is not fully qualified it will be loaded from the + /// assembly that is directly calling this method. If the type is not found + /// in the assembly then all the loaded assemblies will be searched for the type. + /// + /// + public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase) + { + return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase); + } #endif - /// - /// Loads the type specified in the type string. - /// - /// An assembly to load the type from. - /// The name of the type to load. - /// Flag set to true to throw an exception if the type cannot be loaded. - /// true to ignore the case of the type name; otherwise, false - /// The type loaded or null if it could not be loaded. - /// - /// - /// If the type name is fully qualified, i.e. if contains an assembly name in - /// the type name, the type will be loaded from the system using - /// . - /// - /// - /// If the type name is not fully qualified it will be loaded from the specified - /// assembly. If the type is not found in the assembly then all the loaded assemblies - /// will be searched for the type. - /// - /// - public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase) - { - // Check if the type name specifies the assembly name - if(typeName.IndexOf(',') == -1) - { - //LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); + /// + /// Loads the type specified in the type string. + /// + /// An assembly to load the type from. + /// The name of the type to load. + /// Flag set to true to throw an exception if the type cannot be loaded. + /// true to ignore the case of the type name; otherwise, false. + /// The type loaded or null if it could not be loaded. + /// + /// + /// If the type name is fully qualified, i.e. if contains an assembly name in + /// the type name, the type will be loaded from the system using + /// . + /// + /// + /// If the type name is not fully qualified it will be loaded from the specified + /// assembly. If the type is not found in the assembly then all the loaded assemblies + /// will be searched for the type. + /// + /// + public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase) + { + // Check if the type name specifies the assembly name + if (typeName.IndexOf(',') == -1) + { + // LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); #if NETSTANDARD1_3 return relativeAssembly.GetType(typeName, throwOnError, ignoreCase); #elif NETCF return relativeAssembly.GetType(typeName, throwOnError); #else - // Attempt to lookup the type from the relativeAssembly - Type type = relativeAssembly.GetType(typeName, false, ignoreCase); - if (type != null) - { - // Found type in relative assembly - //LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); - return type; - } + // Attempt to lookup the type from the relativeAssembly + Type type = relativeAssembly.GetType(typeName, false, ignoreCase); + if (type != null) + { + // Found type in relative assembly + // LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); + return type; + } - Assembly[] loadedAssemblies = null; - try - { - loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); - } - catch(System.Security.SecurityException) - { - // Insufficient permissions to get the list of loaded assemblies - } + Assembly[] loadedAssemblies = null; + try + { + loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); + } + catch (System.Security.SecurityException) + { + // Insufficient permissions to get the list of loaded assemblies + } - if (loadedAssemblies != null) - { - Type fallback = null; - // Search the loaded assemblies for the type - foreach (Assembly assembly in loadedAssemblies) - { - Type t = assembly.GetType(typeName, false, ignoreCase); - if (t != null) - { - // Found type in loaded assembly - LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies."); - if (assembly.GlobalAssemblyCache) - { - fallback = t; - } - else - { - return t; - } - } - } - if (fallback != null) - { - return fallback; - } - } + if (loadedAssemblies != null) + { + Type fallback = null; + + // Search the loaded assemblies for the type + foreach (Assembly assembly in loadedAssemblies) + { + Type t = assembly.GetType(typeName, false, ignoreCase); + if (t != null) + { + // Found type in loaded assembly + LogLog.Debug(declaringType, "Loaded type [" + typeName + "] from assembly [" + assembly.FullName + "] by searching loaded assemblies."); + if (assembly.GlobalAssemblyCache) + { + fallback = t; + } + else + { + return t; + } + } + } + + if (fallback != null) + { + return fallback; + } + } - // Didn't find the type - if (throwOnError) - { - throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies"); - } - return null; + // Didn't find the type + if (throwOnError) + { + throw new TypeLoadException("Could not load type [" + typeName + "]. Tried assembly [" + relativeAssembly.FullName + "] and all loaded assemblies"); + } + + return null; #endif - } - else - { - // Includes explicit assembly name - //LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type"); - + } + else + { + // Includes explicit assembly name + // LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type"); #if NETCF // In NETCF 2 and 3 arg versions seem to behave differently // https://issues.apache.org/jira/browse/LOG4NET-113 return Type.GetType(typeName, throwOnError); #else - return Type.GetType(typeName, throwOnError, ignoreCase); + return Type.GetType(typeName, throwOnError, ignoreCase); #endif - } - } - - - /// - /// Generate a new guid - /// - /// A new Guid - /// - /// - /// Generate a new guid - /// - /// - public static Guid NewGuid() - { + } + } + + /// + /// Generate a new guid. + /// + /// A new Guid. + /// + /// + /// Generate a new guid. + /// + /// + public static Guid NewGuid() + { #if NETCF_1_0 return PocketGuid.NewGuid(); #else - return Guid.NewGuid(); + return Guid.NewGuid(); #endif - } + } - /// - /// Create an - /// - /// The name of the parameter that caused the exception - /// The value of the argument that causes this exception - /// The message that describes the error - /// the ArgumentOutOfRangeException object - /// - /// - /// Create a new instance of the class - /// with a specified error message, the parameter name, and the value - /// of the argument. - /// - /// - /// The Compact Framework does not support the 3 parameter constructor for the - /// type. This method provides an - /// implementation that works for all platforms. - /// - /// - public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message) - { + /// + /// Create an . + /// + /// The name of the parameter that caused the exception. + /// The value of the argument that causes this exception. + /// The message that describes the error. + /// the ArgumentOutOfRangeException object. + /// + /// + /// Create a new instance of the class + /// with a specified error message, the parameter name, and the value + /// of the argument. + /// + /// + /// The Compact Framework does not support the 3 parameter constructor for the + /// type. This method provides an + /// implementation that works for all platforms. + /// + /// + public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message) + { #if NETCF_1_0 return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]"); #elif NETCF_2_0 return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]"); #else - return new ArgumentOutOfRangeException(parameterName, actualValue, message); + return new ArgumentOutOfRangeException(parameterName, actualValue, message); #endif - } - - - /// - /// Parse a string into an value - /// - /// the string to parse - /// out param where the parsed value is placed - /// true if the string was able to be parsed into an integer - /// - /// - /// Attempts to parse the string into an integer. If the string cannot - /// be parsed then this method returns false. The method does not throw an exception. - /// - /// - public static bool TryParse(string s, out int val) - { + } + + /// + /// Parse a string into an value. + /// + /// the string to parse. + /// out param where the parsed value is placed. + /// true if the string was able to be parsed into an integer. + /// + /// + /// Attempts to parse the string into an integer. If the string cannot + /// be parsed then this method returns false. The method does not throw an exception. + /// + /// + public static bool TryParse(string s, out int val) + { #if NETCF val = 0; try @@ -872,41 +858,41 @@ public static bool TryParse(string s, out int val) return false; #else - // Initialise out param - val = 0; + // Initialise out param + val = 0; - try - { - double doubleVal; - if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) - { - val = Convert.ToInt32(doubleVal); - return true; - } - } - catch - { - // Ignore exception, just return false - } + try + { + double doubleVal; + if (double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) + { + val = Convert.ToInt32(doubleVal); + return true; + } + } + catch + { + // Ignore exception, just return false + } - return false; + return false; #endif - } + } - /// - /// Parse a string into an value - /// - /// the string to parse - /// out param where the parsed value is placed - /// true if the string was able to be parsed into an integer - /// - /// - /// Attempts to parse the string into an integer. If the string cannot - /// be parsed then this method returns false. The method does not throw an exception. - /// - /// - public static bool TryParse(string s, out long val) - { + /// + /// Parse a string into an value. + /// + /// the string to parse. + /// out param where the parsed value is placed. + /// true if the string was able to be parsed into an integer. + /// + /// + /// Attempts to parse the string into an integer. If the string cannot + /// be parsed then this method returns false. The method does not throw an exception. + /// + /// + public static bool TryParse(string s, out long val) + { #if NETCF val = 0; try @@ -920,33 +906,33 @@ public static bool TryParse(string s, out long val) return false; #else - // Initialise out param - val = 0; + // Initialise out param + val = 0; - try - { - double doubleVal; - if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) - { - val = Convert.ToInt64(doubleVal); - return true; - } - } - catch - { - // Ignore exception, just return false - } + try + { + double doubleVal; + if (double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) + { + val = Convert.ToInt64(doubleVal); + return true; + } + } + catch + { + // Ignore exception, just return false + } - return false; + return false; #endif - } + } /// - /// Parse a string into an value + /// Parse a string into an value. /// - /// the string to parse - /// out param where the parsed value is placed - /// true if the string was able to be parsed into an integer + /// the string to parse. + /// out param where the parsed value is placed. + /// true if the string was able to be parsed into an integer. /// /// /// Attempts to parse the string into an integer. If the string cannot @@ -971,10 +957,10 @@ public static bool TryParse(string s, out short val) // Initialise out param val = 0; - try + try { double doubleVal; - if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) + if (double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) { val = Convert.ToInt16(doubleVal); return true; @@ -990,104 +976,106 @@ public static bool TryParse(string s, out short val) } /// - /// Lookup an application setting - /// - /// the application settings key to lookup - /// the value for the key, or null - /// - /// - /// Configuration APIs are not supported under the Compact Framework - /// - /// - public static string GetAppSetting(string key) - { - try - { + /// Lookup an application setting. + /// + /// the application settings key to lookup. + /// the value for the key, or null. + /// + /// + /// Configuration APIs are not supported under the Compact Framework. + /// + /// + public static string GetAppSetting(string key) + { + try + { #if NETCF || NETSTANDARD1_3 // Configuration APIs are not suported under the Compact Framework #elif NET_2_0 - return ConfigurationManager.AppSettings[key]; + return ConfigurationManager.AppSettings[key]; #else return ConfigurationSettings.AppSettings[key]; #endif - } - catch(Exception ex) - { - // If an exception is thrown here then it looks like the config file does not parse correctly. - LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); - } - return null; - } + } + catch (Exception ex) + { + // If an exception is thrown here then it looks like the config file does not parse correctly. + LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); + } + + return null; + } - /// - /// Convert a path into a fully qualified local file path. - /// - /// The path to convert. - /// The fully qualified path. - /// - /// - /// Converts the path specified to a fully - /// qualified path. If the path is relative it is - /// taken as relative from the application base - /// directory. - /// - /// - /// The path specified must be a local file path, a URI is not supported. - /// - /// - public static string ConvertToFullPath(string path) - { - if (path == null) - { - throw new ArgumentNullException("path"); - } + /// + /// Convert a path into a fully qualified local file path. + /// + /// The path to convert. + /// The fully qualified path. + /// + /// + /// Converts the path specified to a fully + /// qualified path. If the path is relative it is + /// taken as relative from the application base + /// directory. + /// + /// + /// The path specified must be a local file path, a URI is not supported. + /// + /// + public static string ConvertToFullPath(string path) + { + if (path == null) + { + throw new ArgumentNullException("path"); + } - string baseDirectory = ""; - try - { - string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - if (applicationBaseDirectory != null) - { - // applicationBaseDirectory may be a URI not a local file path - Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory); - if (applicationBaseDirectoryUri.IsFile) - { - baseDirectory = applicationBaseDirectoryUri.LocalPath; - } - } - } - catch - { - // Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory - } + string baseDirectory = string.Empty; + try + { + string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + if (applicationBaseDirectory != null) + { + // applicationBaseDirectory may be a URI not a local file path + Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory); + if (applicationBaseDirectoryUri.IsFile) + { + baseDirectory = applicationBaseDirectoryUri.LocalPath; + } + } + } + catch + { + // Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory + } - if (baseDirectory != null && baseDirectory.Length > 0) - { - // Note that Path.Combine will return the second path if it is rooted - return Path.GetFullPath(Path.Combine(baseDirectory, path)); - } - return Path.GetFullPath(path); - } + if (baseDirectory != null && baseDirectory.Length > 0) + { + // Note that Path.Combine will return the second path if it is rooted + return Path.GetFullPath(Path.Combine(baseDirectory, path)); + } + + return Path.GetFullPath(path); + } - /// - /// Creates a new case-insensitive instance of the class with the default initial capacity. - /// - /// A new case-insensitive instance of the class with the default initial capacity - /// - /// - /// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer. - /// - /// - public static Hashtable CreateCaseInsensitiveHashtable() - { + /// + /// Creates a new case-insensitive instance of the class with the default initial capacity. + /// + /// A new case-insensitive instance of the class with the default initial capacity. + /// + /// + /// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer. + /// + /// + public static Hashtable CreateCaseInsensitiveHashtable() + { #if NETCF_1_0 return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); #elif NETCF_2_0 || NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 - return new Hashtable(StringComparer.OrdinalIgnoreCase); + return new Hashtable(StringComparer.OrdinalIgnoreCase); #else return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable(); #endif - } + } /// /// Tests two strings for equality, the ignoring case. @@ -1101,21 +1089,17 @@ public static Hashtable CreateCaseInsensitiveHashtable() /// The one string. /// The other string. /// true if the strings are equal, false otherwise. - public static Boolean EqualsIgnoringCase(String a, String b) + public static bool EqualsIgnoringCase(string a, string b) { #if NET_1_0 || NET_1_1 || NETCF_1_0 return string.Compare(a, b, true, System.Globalization.CultureInfo.InvariantCulture) == 0 #elif NETSTANDARD1_3 return CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0; #else // >= .NET-2.0 - return String.Equals(a, b, StringComparison.OrdinalIgnoreCase); + return string.Equals(a, b, StringComparison.OrdinalIgnoreCase); #endif - } - - #endregion Public Static Methods - - #region Private Static Methods - + } + #if NETCF private static string NativeEntryAssemblyLocation { @@ -1152,63 +1136,52 @@ private static extern Int32 GetModuleFileName( Int32 cch); #endif + + /// + /// Gets an empty array of types. + /// + /// + /// + /// The Type.EmptyTypes field is not available on + /// the .NET Compact Framework 1.0. + /// + /// + public static readonly Type[] EmptyTypes = new Type[0]; + + /// + /// The fully qualified type of the SystemInfo class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(SystemInfo); - #endregion Private Static Methods - - #region Public Static Fields - - /// - /// Gets an empty array of types. - /// - /// - /// - /// The Type.EmptyTypes field is not available on - /// the .NET Compact Framework 1.0. - /// - /// - public static readonly Type[] EmptyTypes = new Type[0]; - - #endregion Public Static Fields - - #region Private Static Fields - - /// - /// The fully qualified type of the SystemInfo class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(SystemInfo); - - /// - /// Cache the host name for the current machine - /// - private static string s_hostName; - - /// - /// Cache the application friendly name - /// - private static string s_appFriendlyName; - - /// - /// Text to output when a null is encountered. - /// - private static string s_nullText; + /// + /// Cache the host name for the current machine. + /// + private static string s_hostName; - /// - /// Text to output when an unsupported feature is requested. - /// - private static string s_notAvailableText; + /// + /// Cache the application friendly name. + /// + private static string s_appFriendlyName; - /// - /// Start time for the current process. - /// - private static DateTime s_processStartTimeUtc = DateTime.UtcNow; + /// + /// Text to output when a null is encountered. + /// + private static string s_nullText; - #endregion + /// + /// Text to output when an unsupported feature is requested. + /// + private static string s_notAvailableText; - #region Compact Framework Helper Classes + /// + /// Start time for the current process. + /// + private static DateTime s_processStartTimeUtc = DateTime.UtcNow; + #if NETCF_1_0 /// /// Generate GUIDs on the .NET Compact Framework. @@ -1327,6 +1300,5 @@ public static Guid NewGuid() } } #endif - #endregion Compact Framework Helper Classes - } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs index 535616bdca6..a4d90bc8170 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs @@ -1,118 +1,110 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.Xml; -using System.Text.RegularExpressions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Utility class that represents a format string. - /// - /// - /// - /// Utility class that represents a format string. - /// - /// - /// Nicko Cadell - public sealed class SystemStringFormat - { - private readonly IFormatProvider m_provider; - private readonly string m_format; - private readonly object[] m_args; - - #region Constructor - - /// - /// Initialise the - /// - /// An that supplies culture-specific formatting information. - /// A containing zero or more format items. - /// An array containing zero or more objects to format. - public SystemStringFormat(IFormatProvider provider, string format, params object[] args) - { - m_provider = provider; - m_format = format; - m_args = args; - } - - #endregion Constructor - - /// - /// Format the string and arguments - /// - /// the formatted string - public override string ToString() - { - return StringFormat(m_provider, m_format, m_args); - } - - #region StringFormat - - /// - /// Replaces the format item in a specified with the text equivalent - /// of the value of a corresponding instance in a specified array. - /// A specified parameter supplies culture-specific formatting information. - /// - /// An that supplies culture-specific formatting information. - /// A containing zero or more format items. - /// An array containing zero or more objects to format. - /// - /// A copy of format in which the format items have been replaced by the - /// equivalent of the corresponding instances of in args. - /// - /// - /// - /// This method does not throw exceptions. If an exception thrown while formatting the result the - /// exception and arguments are returned in the result string. - /// - /// - private static string StringFormat(IFormatProvider provider, string format, params object[] args) - { - try - { - // The format is missing, log null value - if (format == null) - { - return null; - } - - // The args are missing - should not happen unless we are called explicitly with a null array - if (args == null) - { - return format; - } - - // Try to format the string - return String.Format(provider, format, args); - } - catch(Exception ex) - { - log4net.Util.LogLog.Warn(declaringType, "Exception while rendering format ["+format+"]", ex); - return StringFormatError(ex, format, args); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + using System.Text.RegularExpressions; + using System.Xml; + + /// + /// Utility class that represents a format string. + /// + /// + /// + /// Utility class that represents a format string. + /// + /// + /// Nicko Cadell. + public sealed class SystemStringFormat + { + private readonly IFormatProvider m_provider; + private readonly string m_format; + private readonly object[] m_args; + + /// + /// Initializes a new instance of the class. + /// Initialise the . + /// + /// An that supplies culture-specific formatting information. + /// A containing zero or more format items. + /// An array containing zero or more objects to format. + public SystemStringFormat(IFormatProvider provider, string format, params object[] args) + { + this.m_provider = provider; + this.m_format = format; + this.m_args = args; + } + + /// + /// Format the string and arguments. + /// + /// the formatted string. + public override string ToString() + { + return StringFormat(this.m_provider, this.m_format, this.m_args); + } + + /// + /// Replaces the format item in a specified with the text equivalent + /// of the value of a corresponding instance in a specified array. + /// A specified parameter supplies culture-specific formatting information. + /// + /// An that supplies culture-specific formatting information. + /// A containing zero or more format items. + /// An array containing zero or more objects to format. + /// + /// A copy of format in which the format items have been replaced by the + /// equivalent of the corresponding instances of in args. + /// + /// + /// + /// This method does not throw exceptions. If an exception thrown while formatting the result the + /// exception and arguments are returned in the result string. + /// + /// + private static string StringFormat(IFormatProvider provider, string format, params object[] args) + { + try + { + // The format is missing, log null value + if (format == null) + { + return null; + } + + // The args are missing - should not happen unless we are called explicitly with a null array + if (args == null) + { + return format; + } + + // Try to format the string + return string.Format(provider, format, args); + } + catch (Exception ex) + { + log4net.Util.LogLog.Warn(declaringType, "Exception while rendering format [" + format + "]", ex); + return StringFormatError(ex, format, args); + } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { @@ -120,38 +112,39 @@ private static string StringFormat(IFormatProvider provider, string format, para return StringFormatError(null, format, args); } #endif - } - - /// - /// Process an error during StringFormat - /// - private static string StringFormatError(Exception formatException, string format, object[] args) - { - try - { - StringBuilder buf = new StringBuilder(""); - - if (formatException != null) - { - buf.Append("Exception during StringFormat: ").Append(formatException.Message); - } - else - { - buf.Append("Exception during StringFormat"); - } - buf.Append(" ").Append(format).Append(""); - buf.Append(""); - RenderArray(args, buf); - buf.Append(""); - buf.Append(""); - - return buf.ToString(); - } - catch(Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling", ex); - return "Exception during StringFormat. See Internal Log."; - } + } + + /// + /// Process an error during StringFormat. + /// + private static string StringFormatError(Exception formatException, string format, object[] args) + { + try + { + StringBuilder buf = new StringBuilder(""); + + if (formatException != null) + { + buf.Append("Exception during StringFormat: ").Append(formatException.Message); + } + else + { + buf.Append("Exception during StringFormat"); + } + + buf.Append(" ").Append(format).Append(""); + buf.Append(""); + RenderArray(args, buf); + buf.Append(""); + buf.Append(""); + + return buf.ToString(); + } + catch (Exception ex) + { + log4net.Util.LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling", ex); + return "Exception during StringFormat. See Internal Log."; + } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { @@ -159,83 +152,78 @@ private static string StringFormatError(Exception formatException, string format return "Exception during StringFormat. See Internal Log."; } #endif - } - - /// - /// Dump the contents of an array into a string builder - /// - private static void RenderArray(Array array, StringBuilder buffer) - { - if (array == null) - { - buffer.Append(SystemInfo.NullText); - } - else - { - if (array.Rank != 1) - { - buffer.Append(array.ToString()); - } - else - { - buffer.Append("{"); - int len = array.Length; - - if (len > 0) - { - RenderObject(array.GetValue(0), buffer); - for (int i = 1; i < len; i++) - { - buffer.Append(", "); - RenderObject(array.GetValue(i), buffer); - } - } - buffer.Append("}"); - } - } - } - - /// - /// Dump an object to a string - /// - private static void RenderObject(Object obj, StringBuilder buffer) - { - if (obj == null) - { - buffer.Append(SystemInfo.NullText); - } - else - { - try - { - buffer.Append(obj); - } - catch(Exception ex) - { - buffer.Append(""); - } + } + + /// + /// Dump the contents of an array into a string builder. + /// + private static void RenderArray(Array array, StringBuilder buffer) + { + if (array == null) + { + buffer.Append(SystemInfo.NullText); + } + else + { + if (array.Rank != 1) + { + buffer.Append(array.ToString()); + } + else + { + buffer.Append("{"); + int len = array.Length; + + if (len > 0) + { + RenderObject(array.GetValue(0), buffer); + for (int i = 1; i < len; i++) + { + buffer.Append(", "); + RenderObject(array.GetValue(i), buffer); + } + } + + buffer.Append("}"); + } + } + } + + /// + /// Dump an object to a string. + /// + private static void RenderObject(object obj, StringBuilder buffer) + { + if (obj == null) + { + buffer.Append(SystemInfo.NullText); + } + else + { + try + { + buffer.Append(obj); + } + catch (Exception ex) + { + buffer.Append(""); + } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { buffer.Append(""); } #endif - } - } - - #endregion StringFormat - - #region Private Static Fields - - /// - /// The fully qualified type of the SystemStringFormat class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(SystemStringFormat); - - #endregion Private Static Fields - } + } + } + + /// + /// The fully qualified type of the SystemStringFormat class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(SystemStringFormat); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs index 19401790ca5..3d04e273abe 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs @@ -1,245 +1,224 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.IO; -using System.Globalization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Adapter that extends and forwards all - /// messages to an instance of . - /// - /// - /// - /// Adapter that extends and forwards all - /// messages to an instance of . - /// - /// - /// Nicko Cadell - public abstract class TextWriterAdapter : TextWriter - { - #region Private Member Variables - - /// - /// The writer to forward messages to - /// - private TextWriter m_writer; - - #endregion - - #region Constructors - - /// - /// Create an instance of that forwards all - /// messages to a . - /// - /// The to forward to - /// - /// - /// Create an instance of that forwards all - /// messages to a . - /// - /// - protected TextWriterAdapter(TextWriter writer) : base(CultureInfo.InvariantCulture) - { - m_writer = writer; - } - - #endregion - - #region Protected Instance Properties - - /// - /// Gets or sets the underlying . - /// - /// - /// The underlying . - /// - /// - /// - /// Gets or sets the underlying . - /// - /// - protected TextWriter Writer - { - get { return m_writer; } - set { m_writer = value; } - } - - #endregion Protected Instance Properties - - #region Public Properties - - /// - /// The Encoding in which the output is written - /// - /// - /// The - /// - /// - /// - /// The Encoding in which the output is written - /// - /// - override public Encoding Encoding - { - get { return m_writer.Encoding; } - } - - /// - /// Gets an object that controls formatting - /// - /// - /// The format provider - /// - /// - /// - /// Gets an object that controls formatting - /// - /// - override public IFormatProvider FormatProvider - { - get { return m_writer.FormatProvider; } - } - - /// - /// Gets or sets the line terminator string used by the TextWriter - /// - /// - /// The line terminator to use - /// - /// - /// - /// Gets or sets the line terminator string used by the TextWriter - /// - /// - override public String NewLine - { - get { return m_writer.NewLine; } - set { m_writer.NewLine = value; } - } - - #endregion - - #region Public Methods - - /// - /// Closes the writer and releases any system resources associated with the writer - /// - /// - /// - /// - /// + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + using System.IO; + using System.Text; + + /// + /// Adapter that extends and forwards all + /// messages to an instance of . + /// + /// + /// + /// Adapter that extends and forwards all + /// messages to an instance of . + /// + /// + /// Nicko Cadell. + public abstract class TextWriterAdapter : TextWriter + { + /// + /// The writer to forward messages to. + /// + private TextWriter m_writer; + + /// + /// Initializes a new instance of the class. + /// Create an instance of that forwards all + /// messages to a . + /// + /// The to forward to. + /// + /// + /// Create an instance of that forwards all + /// messages to a . + /// + /// + protected TextWriterAdapter(TextWriter writer) + : base(CultureInfo.InvariantCulture) + { + this.m_writer = writer; + } + + /// + /// Gets or sets the underlying . + /// + /// + /// The underlying . + /// + /// + /// + /// Gets or sets the underlying . + /// + /// + protected TextWriter Writer + { + get { return this.m_writer; } + set { this.m_writer = value; } + } + + /// + /// Gets the Encoding in which the output is written. + /// + /// + /// The . + /// + /// + /// + /// The Encoding in which the output is written. + /// + /// + public override Encoding Encoding + { + get { return this.m_writer.Encoding; } + } + + /// + /// Gets an object that controls formatting. + /// + /// + /// The format provider. + /// + /// + /// + /// Gets an object that controls formatting. + /// + /// + public override IFormatProvider FormatProvider + { + get { return this.m_writer.FormatProvider; } + } + + /// + /// Gets or sets the line terminator string used by the TextWriter. + /// + /// + /// The line terminator to use. + /// + /// + /// + /// Gets or sets the line terminator string used by the TextWriter. + /// + /// + public override string NewLine + { + get { return this.m_writer.NewLine; } + set { this.m_writer.NewLine = value; } + } + + /// + /// Closes the writer and releases any system resources associated with the writer. + /// + /// + /// + /// + /// #if NETSTANDARD1_3 virtual public void Close() { m_writer.Dispose(); } #else - override public void Close() - { - m_writer.Close(); - } + public override void Close() + { + this.m_writer.Close(); + } #endif - /// - /// Dispose this writer - /// - /// flag indicating if we are being disposed - /// - /// - /// Dispose this writer - /// - /// - override protected void Dispose(bool disposing) - { - if (disposing) - { - ((IDisposable)m_writer).Dispose(); - } - } - - /// - /// Flushes any buffered output - /// - /// - /// - /// Clears all buffers for the writer and causes any buffered data to be written - /// to the underlying device - /// - /// - override public void Flush() - { - m_writer.Flush(); - } - - /// - /// Writes a character to the wrapped TextWriter - /// - /// the value to write to the TextWriter - /// - /// - /// Writes a character to the wrapped TextWriter - /// - /// - override public void Write(char value) - { - m_writer.Write(value); - } - - /// - /// Writes a character buffer to the wrapped TextWriter - /// - /// the data buffer - /// the start index - /// the number of characters to write - /// - /// - /// Writes a character buffer to the wrapped TextWriter - /// - /// - override public void Write(char[] buffer, int index, int count) - { - m_writer.Write(buffer, index, count); - } - - /// - /// Writes a string to the wrapped TextWriter - /// - /// the value to write to the TextWriter - /// - /// - /// Writes a string to the wrapped TextWriter - /// - /// - override public void Write(String value) - { - m_writer.Write(value); - } - - #endregion - } + /// + /// Dispose this writer. + /// + /// flag indicating if we are being disposed. + /// + /// + /// Dispose this writer. + /// + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + ((IDisposable)this.m_writer).Dispose(); + } + } + + /// + /// Flushes any buffered output. + /// + /// + /// + /// Clears all buffers for the writer and causes any buffered data to be written + /// to the underlying device. + /// + /// + public override void Flush() + { + this.m_writer.Flush(); + } + + /// + /// Writes a character to the wrapped TextWriter. + /// + /// the value to write to the TextWriter. + /// + /// + /// Writes a character to the wrapped TextWriter. + /// + /// + public override void Write(char value) + { + this.m_writer.Write(value); + } + + /// + /// Writes a character buffer to the wrapped TextWriter. + /// + /// the data buffer. + /// the start index. + /// the number of characters to write. + /// + /// + /// Writes a character buffer to the wrapped TextWriter. + /// + /// + public override void Write(char[] buffer, int index, int count) + { + this.m_writer.Write(buffer, index, count); + } + + /// + /// Writes a string to the wrapped TextWriter. + /// + /// the value to write to the TextWriter. + /// + /// + /// Writes a string to the wrapped TextWriter. + /// + /// + public override void Write(string value) + { + this.m_writer.Write(value); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs index e5681898619..ebd18d32f84 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs @@ -1,204 +1,186 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETCF using System.Collections; #endif namespace log4net.Util { - /// - /// Implementation of Properties collection for the - /// - /// - /// - /// Class implements a collection of properties that is specific to each thread. - /// The class is not synchronized as each thread has its own . - /// - /// - /// Nicko Cadell - public sealed class ThreadContextProperties : ContextPropertiesBase - { - #region Private Instance Fields - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Implementation of Properties collection for the . + /// + /// + /// + /// Class implements a collection of properties that is specific to each thread. + /// The class is not synchronized as each thread has its own . + /// + /// + /// Nicko Cadell. + public sealed class ThreadContextProperties : ContextPropertiesBase + { #if NETCF /// /// The thread local data slot to use to store a PropertiesDictionary. /// private readonly static LocalDataStoreSlot s_threadLocalSlot = System.Threading.Thread.AllocateDataSlot(); #else - /// - /// Each thread will automatically have its instance. - /// - [ThreadStatic] - private static PropertiesDictionary _dictionary; + /// + /// Each thread will automatically have its instance. + /// + [ThreadStatic] + private static PropertiesDictionary _dictionary; #endif - - #endregion Private Instance Fields - - #region Public Instance Constructors - - /// - /// Internal constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal ThreadContextProperties() - { - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets or sets the value of a property - /// - /// - /// The value for the property with the specified key - /// - /// - /// - /// Gets or sets the value of a property - /// - /// - override public object this[string key] - { - get - { + + /// + /// Initializes a new instance of the class. + /// Internal constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal ThreadContextProperties() + { + } + + /// + /// Gets or sets the value of a property. + /// + /// + /// The value for the property with the specified key. + /// + /// + /// + /// Gets or sets the value of a property. + /// + /// + public override object this[string key] + { + get + { #if NETCF PropertiesDictionary _dictionary = GetProperties(false); #endif - if (_dictionary != null) - { - return _dictionary[key]; - } - return null; - } - set - { - GetProperties(true)[key] = value; - } - } - - #endregion Public Instance Properties - - #region Public Instance Methods - - /// - /// Remove a property - /// - /// the key for the entry to remove - /// - /// - /// Remove a property - /// - /// - public void Remove(string key) - { + if (_dictionary != null) + { + return _dictionary[key]; + } + + return null; + } + + set + { + this.GetProperties(true)[key] = value; + } + } + + /// + /// Remove a property. + /// + /// the key for the entry to remove. + /// + /// + /// Remove a property. + /// + /// + public void Remove(string key) + { #if NETCF PropertiesDictionary _dictionary = GetProperties(false); #endif - if (_dictionary != null) - { - _dictionary.Remove(key); - } - } - - /// - /// Get the keys stored in the properties. - /// - /// - /// Gets the keys stored in the properties. - /// - /// a set of the defined keys - public string[] GetKeys() - { + if (_dictionary != null) + { + _dictionary.Remove(key); + } + } + + /// + /// Get the keys stored in the properties. + /// + /// + /// Gets the keys stored in the properties. + /// + /// a set of the defined keys. + public string[] GetKeys() + { #if NETCF PropertiesDictionary _dictionary = GetProperties(false); #endif - if (_dictionary != null) - { - return _dictionary.GetKeys(); - } - return null; - } - - /// - /// Clear all properties - /// - /// - /// - /// Clear all properties - /// - /// - public void Clear() - { + if (_dictionary != null) + { + return _dictionary.GetKeys(); + } + + return null; + } + + /// + /// Clear all properties. + /// + /// + /// + /// Clear all properties. + /// + /// + public void Clear() + { #if NETCF PropertiesDictionary _dictionary = GetProperties(false); #endif - if (_dictionary != null) - { - _dictionary.Clear(); - } - } - - #endregion Public Instance Methods - - #region Internal Instance Methods - - /// - /// Get the PropertiesDictionary for this thread. - /// - /// create the dictionary if it does not exist, otherwise return null if does not exist - /// the properties for this thread - /// - /// - /// The collection returned is only to be used on the calling thread. If the - /// caller needs to share the collection between different threads then the - /// caller must clone the collection before doing so. - /// - /// - internal PropertiesDictionary GetProperties(bool create) - { + if (_dictionary != null) + { + _dictionary.Clear(); + } + } + + /// + /// Get the PropertiesDictionary for this thread. + /// + /// create the dictionary if it does not exist, otherwise return null if does not exist. + /// the properties for this thread. + /// + /// + /// The collection returned is only to be used on the calling thread. If the + /// caller needs to share the collection between different threads then the + /// caller must clone the collection before doing so. + /// + /// + internal PropertiesDictionary GetProperties(bool create) + { #if NETCF PropertiesDictionary _dictionary = (PropertiesDictionary)System.Threading.Thread.GetData(s_threadLocalSlot); #endif - if (_dictionary == null && create) - { - _dictionary = new PropertiesDictionary(); + if (_dictionary == null && create) + { + _dictionary = new PropertiesDictionary(); #if NETCF System.Threading.Thread.SetData(s_threadLocalSlot, _dictionary); #endif - } - return _dictionary; - } - - #endregion Internal Instance Methods - } -} - + } + + return _dictionary; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs index 3105f0c1c96..1909a792872 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs @@ -1,388 +1,349 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if !NETCF_1_0 using System.Collections; + #endif using log4net.Core; namespace log4net.Util { - /// - /// Implementation of Stack for the - /// - /// - /// - /// Implementation of Stack for the - /// - /// - /// Nicko Cadell - public sealed class ThreadContextStack : IFixingRequired - { - #region Private Static Fields - - /// - /// The stack store. - /// - private Stack m_stack = new Stack(); - - #endregion Private Static Fields - - #region Public Instance Constructors - - /// - /// Internal constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal ThreadContextStack() - { - } - - #endregion Public Instance Constructors - - #region Public Properties - - /// - /// The number of messages in the stack - /// - /// - /// The current number of messages in the stack - /// - /// - /// - /// The current number of messages in the stack. That is - /// the number of times has been called - /// minus the number of times has been called. - /// - /// - public int Count - { - get { return m_stack.Count; } - } - - #endregion // Public Properties - - #region Public Methods - - /// - /// Clears all the contextual information held in this stack. - /// - /// - /// - /// Clears all the contextual information held in this stack. - /// Only call this if you think that this tread is being reused after - /// a previous call execution which may not have completed correctly. - /// You do not need to use this method if you always guarantee to call - /// the method of the - /// returned from even in exceptional circumstances, - /// for example by using the using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// syntax. - /// - /// - public void Clear() - { - m_stack.Clear(); - } - - /// - /// Removes the top context from this stack. - /// - /// The message in the context that was removed from the top of this stack. - /// - /// - /// Remove the top context from this stack, and return - /// it to the caller. If this stack is empty then an - /// empty string (not ) is returned. - /// - /// - public string Pop() - { - Stack stack = m_stack; - if (stack.Count > 0) - { - return ((StackFrame)(stack.Pop())).Message; - } - return ""; - } - - /// - /// Pushes a new context message into this stack. - /// - /// The new context message. - /// - /// An that can be used to clean up the context stack. - /// - /// - /// - /// Pushes a new context onto this stack. An - /// is returned that can be used to clean up this stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// { - /// log.Warn("This should have an ThreadContext Stack message"); - /// } - /// - /// - public IDisposable Push(string message) - { - Stack stack = m_stack; - stack.Push(new StackFrame(message, (stack.Count>0) ? (StackFrame)stack.Peek() : null)); - - return new AutoPopStackFrame(stack, stack.Count - 1); - } - - #endregion Public Methods - - #region Internal Methods - - /// - /// Gets the current context information for this stack. - /// - /// The current context information. - internal string GetFullMessage() - { - Stack stack = m_stack; - if (stack.Count > 0) - { - return ((StackFrame)(stack.Peek())).FullMessage; - } - return null; - } - - /// - /// Gets and sets the internal stack used by this - /// - /// The internal storage stack - /// - /// - /// This property is provided only to support backward compatability - /// of the . Tytpically the internal stack should not - /// be modified. - /// - /// - internal Stack InternalStack - { - get { return m_stack; } - set { m_stack = value; } - } - - #endregion Internal Methods - - /// - /// Gets the current context information for this stack. - /// - /// Gets the current context information - /// - /// - /// Gets the current context information for this stack. - /// - /// - public override string ToString() - { - return GetFullMessage(); - } - - /// - /// Get a portable version of this object - /// - /// the portable instance of this object - /// - /// - /// Get a cross thread portable version of this object - /// - /// - object IFixingRequired.GetFixedObject() - { - return GetFullMessage(); - } - - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - private sealed class StackFrame - { - #region Private Instance Fields - - private readonly string m_message; - private readonly StackFrame m_parent; - private string m_fullMessage = null; - - #endregion - - #region Internal Instance Constructors - - /// - /// Constructor - /// - /// The message for this context. - /// The parent context in the chain. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and parent context. - /// - /// - internal StackFrame(string message, StackFrame parent) - { - m_message = message; - m_parent = parent; - - if (parent == null) - { - m_fullMessage = message; - } - } - - #endregion Internal Instance Constructors - - #region Internal Instance Properties - - /// - /// Get the message. - /// - /// The message. - /// - /// - /// Get the message. - /// - /// - internal string Message - { - get { return m_message; } - } - - /// - /// Gets the full text of the context down to the root level. - /// - /// - /// The full text of the context down to the root level. - /// - /// - /// - /// Gets the full text of the context down to the root level. - /// - /// - internal string FullMessage - { - get - { - if (m_fullMessage == null && m_parent != null) - { - m_fullMessage = string.Concat(m_parent.FullMessage, " ", m_message); - } - return m_fullMessage; - } - } - - #endregion Internal Instance Properties - } - - /// - /// Struct returned from the method. - /// - /// - /// - /// This struct implements the and is designed to be used - /// with the pattern to remove the stack frame at the end of the scope. - /// - /// - private struct AutoPopStackFrame : IDisposable - { - #region Private Instance Fields - - /// - /// The ThreadContextStack internal stack - /// - private Stack m_frameStack; - - /// - /// The depth to trim the stack to when this instance is disposed - /// - private int m_frameDepth; - - #endregion Private Instance Fields - - #region Internal Instance Constructors - - /// - /// Constructor - /// - /// The internal stack used by the ThreadContextStack. - /// The depth to return the stack to when this object is disposed. - /// - /// - /// Initializes a new instance of the class with - /// the specified stack and return depth. - /// - /// - internal AutoPopStackFrame(Stack frameStack, int frameDepth) - { - m_frameStack = frameStack; - m_frameDepth = frameDepth; - } - - #endregion Internal Instance Constructors - - #region Implementation of IDisposable - - /// - /// Returns the stack to the correct depth. - /// - /// - /// - /// Returns the stack to the correct depth. - /// - /// - public void Dispose() - { - if (m_frameDepth >= 0 && m_frameStack != null) - { - while(m_frameStack.Count > m_frameDepth) - { - m_frameStack.Pop(); - } - } - } - - #endregion Implementation of IDisposable - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Implementation of Stack for the . + /// + /// + /// + /// Implementation of Stack for the . + /// + /// + /// Nicko Cadell. + public sealed class ThreadContextStack : IFixingRequired + { + /// + /// The stack store. + /// + private Stack m_stack = new Stack(); + + /// + /// Initializes a new instance of the class. + /// Internal constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal ThreadContextStack() + { + } + + /// + /// Gets the number of messages in the stack. + /// + /// + /// The current number of messages in the stack. + /// + /// + /// + /// The current number of messages in the stack. That is + /// the number of times has been called + /// minus the number of times has been called. + /// + /// + public int Count + { + get { return this.m_stack.Count; } + } + + /// + /// Clears all the contextual information held in this stack. + /// + /// + /// + /// Clears all the contextual information held in this stack. + /// Only call this if you think that this tread is being reused after + /// a previous call execution which may not have completed correctly. + /// You do not need to use this method if you always guarantee to call + /// the method of the + /// returned from even in exceptional circumstances, + /// for example by using the using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// syntax. + /// + /// + public void Clear() + { + this.m_stack.Clear(); + } + + /// + /// Removes the top context from this stack. + /// + /// The message in the context that was removed from the top of this stack. + /// + /// + /// Remove the top context from this stack, and return + /// it to the caller. If this stack is empty then an + /// empty string (not ) is returned. + /// + /// + public string Pop() + { + Stack stack = this.m_stack; + if (stack.Count > 0) + { + return ((StackFrame)stack.Pop()).Message; + } + + return string.Empty; + } + + /// + /// Pushes a new context message into this stack. + /// + /// The new context message. + /// + /// An that can be used to clean up the context stack. + /// + /// + /// + /// Pushes a new context onto this stack. An + /// is returned that can be used to clean up this stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// { + /// log.Warn("This should have an ThreadContext Stack message"); + /// } + /// + /// + public IDisposable Push(string message) + { + Stack stack = this.m_stack; + stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); + + return new AutoPopStackFrame(stack, stack.Count - 1); + } + + /// + /// Gets the current context information for this stack. + /// + /// The current context information. + internal string GetFullMessage() + { + Stack stack = this.m_stack; + if (stack.Count > 0) + { + return ((StackFrame)stack.Peek()).FullMessage; + } + + return null; + } + + /// + /// Gets or sets and sets the internal stack used by this . + /// + /// The internal storage stack. + /// + /// + /// This property is provided only to support backward compatability + /// of the . Tytpically the internal stack should not + /// be modified. + /// + /// + internal Stack InternalStack + { + get { return this.m_stack; } + set { this.m_stack = value; } + } + + /// + /// Gets the current context information for this stack. + /// + /// Gets the current context information. + /// + /// + /// Gets the current context information for this stack. + /// + /// + public override string ToString() + { + return this.GetFullMessage(); + } + + /// + /// Get a portable version of this object. + /// + /// the portable instance of this object. + /// + /// + /// Get a cross thread portable version of this object. + /// + /// + object IFixingRequired.GetFixedObject() + { + return this.GetFullMessage(); + } + + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + private sealed class StackFrame + { + private readonly string m_message; + private readonly StackFrame m_parent; + private string m_fullMessage = null; + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// The message for this context. + /// The parent context in the chain. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and parent context. + /// + /// + internal StackFrame(string message, StackFrame parent) + { + this.m_message = message; + this.m_parent = parent; + + if (parent == null) + { + this.m_fullMessage = message; + } + } + + /// + /// Gets get the message. + /// + /// The message. + /// + /// + /// Get the message. + /// + /// + internal string Message + { + get { return this.m_message; } + } + + /// + /// Gets the full text of the context down to the root level. + /// + /// + /// The full text of the context down to the root level. + /// + /// + /// + /// Gets the full text of the context down to the root level. + /// + /// + internal string FullMessage + { + get + { + if (this.m_fullMessage == null && this.m_parent != null) + { + this.m_fullMessage = string.Concat(this.m_parent.FullMessage, " ", this.m_message); + } + + return this.m_fullMessage; + } + } + } + + /// + /// Struct returned from the method. + /// + /// + /// + /// This struct implements the and is designed to be used + /// with the pattern to remove the stack frame at the end of the scope. + /// + /// + private struct AutoPopStackFrame : IDisposable + { + /// + /// The ThreadContextStack internal stack. + /// + private Stack m_frameStack; + + /// + /// The depth to trim the stack to when this instance is disposed. + /// + private int m_frameDepth; + + /// + /// Initializes a new instance of the struct. + /// Constructor. + /// + /// The internal stack used by the ThreadContextStack. + /// The depth to return the stack to when this object is disposed. + /// + /// + /// Initializes a new instance of the class with + /// the specified stack and return depth. + /// + /// + internal AutoPopStackFrame(Stack frameStack, int frameDepth) + { + this.m_frameStack = frameStack; + this.m_frameDepth = frameDepth; + } + + /// + /// Returns the stack to the correct depth. + /// + /// + /// + /// Returns the stack to the correct depth. + /// + /// + public void Dispose() + { + if (this.m_frameDepth >= 0 && this.m_frameStack != null) + { + while (this.m_frameStack.Count > this.m_frameDepth) + { + this.m_frameStack.Pop(); + } + } + } + } #if NETCF_1_0 /// @@ -435,5 +396,5 @@ public Stack Clone() } } #endif - } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs index a947d90f3f3..6c6c445c8b7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs @@ -1,128 +1,113 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Implementation of Stacks collection for the - /// - /// - /// - /// Implementation of Stacks collection for the - /// - /// - /// Nicko Cadell - public sealed class ThreadContextStacks - { - private readonly ContextPropertiesBase m_properties; - - #region Public Instance Constructors - - /// - /// Internal constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal ThreadContextStacks(ContextPropertiesBase properties) - { - m_properties = properties; - } - - #endregion Public Instance Constructors - - #region Public Instance Properties - - /// - /// Gets the named thread context stack - /// - /// - /// The named stack - /// - /// - /// - /// Gets the named thread context stack - /// - /// - public ThreadContextStack this[string key] - { - get - { - ThreadContextStack stack = null; - - object propertyValue = m_properties[key]; - if (propertyValue == null) - { - // Stack does not exist, create - stack = new ThreadContextStack(); - m_properties[key] = stack; - } - else - { - // Look for existing stack - stack = propertyValue as ThreadContextStack; - if (stack == null) - { - // Property is not set to a stack! - string propertyValueString = SystemInfo.NullText; - - try - { - propertyValueString = propertyValue.ToString(); - } - catch - { - } - - LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named ["+key+"] failed because a property with the same name exists which is a ["+propertyValue.GetType().Name+"] with value ["+propertyValueString+"]"); - - stack = new ThreadContextStack(); - } - } - - return stack; - } - } - - #endregion Public Instance Properties - - #region Private Static Fields - - /// - /// The fully qualified type of the ThreadContextStacks class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(ThreadContextStacks); - - #endregion Private Static Fields - } -} - + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Collections; + + /// + /// Implementation of Stacks collection for the . + /// + /// + /// + /// Implementation of Stacks collection for the . + /// + /// + /// Nicko Cadell. + public sealed class ThreadContextStacks + { + private readonly ContextPropertiesBase m_properties; + + /// + /// Initializes a new instance of the class. + /// Internal constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal ThreadContextStacks(ContextPropertiesBase properties) + { + this.m_properties = properties; + } + + /// + /// Gets the named thread context stack. + /// + /// + /// The named stack. + /// + /// + /// + /// Gets the named thread context stack. + /// + /// + public ThreadContextStack this[string key] + { + get + { + ThreadContextStack stack = null; + + object propertyValue = this.m_properties[key]; + if (propertyValue == null) + { + // Stack does not exist, create + stack = new ThreadContextStack(); + this.m_properties[key] = stack; + } + else + { + // Look for existing stack + stack = propertyValue as ThreadContextStack; + if (stack == null) + { + // Property is not set to a stack! + string propertyValueString = SystemInfo.NullText; + + try + { + propertyValueString = propertyValue.ToString(); + } + catch + { + } + + LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named [" + key + "] failed because a property with the same name exists which is a [" + propertyValue.GetType().Name + "] with value [" + propertyValueString + "]"); + + stack = new ThreadContextStack(); + } + } + + return stack; + } + } + + /// + /// The fully qualified type of the ThreadContextStacks class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(ThreadContextStacks); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs index 1f28113abbc..acd93e41879 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs @@ -1,204 +1,187 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; -using System.Xml; -using System.Text.RegularExpressions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util { - /// - /// Utility class for transforming strings. - /// - /// - /// - /// Utility class for transforming strings. - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class Transform - { - #region Private Instance Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private Transform() - { - } - - #endregion Private Instance Constructors - - #region XML String Methods - - /// - /// Write a string to an - /// - /// the writer to write to - /// the string to write - /// The string to replace non XML compliant chars with - /// - /// - /// The test is escaped either using XML escape entities - /// or using CDATA sections. - /// - /// - public static void WriteEscapedXmlString(XmlWriter writer, string textData, string invalidCharReplacement) - { - string stringData = MaskXmlInvalidCharacters(textData, invalidCharReplacement); - // Write either escaped text or CDATA sections - - int weightCData = 12 * (1 + CountSubstrings(stringData, CDATA_END)); - int weightStringEscapes = 3*(CountSubstrings(stringData, "<") + CountSubstrings(stringData, ">")) + 4*CountSubstrings(stringData, "&"); - - if (weightStringEscapes <= weightCData) - { - // Write string using string escapes - writer.WriteString(stringData); - } - else - { - // Write string using CDATA section - - int end = stringData.IndexOf(CDATA_END); - - if (end < 0) - { - writer.WriteCData(stringData); - } - else - { - int start = 0; - while (end > -1) - { - writer.WriteCData(stringData.Substring(start, end - start)); - if (end == stringData.Length - 3) - { - start = stringData.Length; - writer.WriteString(CDATA_END); - break; - } - else - { - writer.WriteString(CDATA_UNESCAPABLE_TOKEN); - start = end + 2; - end = stringData.IndexOf(CDATA_END, start); - } - } - - if (start < stringData.Length) - { - writer.WriteCData(stringData.Substring(start)); - } - } - } - } - - /// - /// Replace invalid XML characters in text string - /// - /// the XML text input string - /// the string to use in place of invalid characters - /// A string that does not contain invalid XML characters. - /// - /// - /// Certain Unicode code points are not allowed in the XML InfoSet, for - /// details see: http://www.w3.org/TR/REC-xml/#charsets. - /// - /// - /// This method replaces any illegal characters in the input string - /// with the mask string specified. - /// - /// - public static string MaskXmlInvalidCharacters(string textData, string mask) - { - return INVALIDCHARS.Replace(textData, mask); - } - - #endregion XML String Methods - - #region Private Helper Methods - - /// - /// Count the number of times that the substring occurs in the text - /// - /// the text to search - /// the substring to find - /// the number of times the substring occurs in the text - /// - /// - /// The substring is assumed to be non repeating within itself. - /// - /// - private static int CountSubstrings(string text, string substring) - { - int count = 0; - int offset = 0; - int length = text.Length; - int substringLength = substring.Length; - - if (length == 0) - { - return 0; - } - if (substringLength == 0) - { - return 0; - } - - while(offset < length) - { - int index = text.IndexOf(substring, offset); - - if (index == -1) - { - break; - } - - count++; - offset = index + substringLength; - } - return count; - } - - #endregion - - #region Private Static Fields + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + using System.Text.RegularExpressions; + using System.Xml; + + /// + /// Utility class for transforming strings. + /// + /// + /// + /// Utility class for transforming strings. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class Transform + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private Transform() + { + } + + /// + /// Write a string to an . + /// + /// the writer to write to. + /// the string to write. + /// The string to replace non XML compliant chars with. + /// + /// + /// The test is escaped either using XML escape entities + /// or using CDATA sections. + /// + /// + public static void WriteEscapedXmlString(XmlWriter writer, string textData, string invalidCharReplacement) + { + string stringData = MaskXmlInvalidCharacters(textData, invalidCharReplacement); + + // Write either escaped text or CDATA sections + int weightCData = 12 * (1 + CountSubstrings(stringData, CDATA_END)); + int weightStringEscapes = (3 * (CountSubstrings(stringData, "<") + CountSubstrings(stringData, ">"))) + (4 * CountSubstrings(stringData, "&")); + + if (weightStringEscapes <= weightCData) + { + // Write string using string escapes + writer.WriteString(stringData); + } + else + { + // Write string using CDATA section + int end = stringData.IndexOf(CDATA_END); + + if (end < 0) + { + writer.WriteCData(stringData); + } + else + { + int start = 0; + while (end > -1) + { + writer.WriteCData(stringData.Substring(start, end - start)); + if (end == stringData.Length - 3) + { + start = stringData.Length; + writer.WriteString(CDATA_END); + break; + } + else + { + writer.WriteString(CDATA_UNESCAPABLE_TOKEN); + start = end + 2; + end = stringData.IndexOf(CDATA_END, start); + } + } + + if (start < stringData.Length) + { + writer.WriteCData(stringData.Substring(start)); + } + } + } + } - private const string CDATA_END = "]]>"; - private const string CDATA_UNESCAPABLE_TOKEN = "]]"; + /// + /// Replace invalid XML characters in text string. + /// + /// the XML text input string. + /// the string to use in place of invalid characters. + /// A string that does not contain invalid XML characters. + /// + /// + /// Certain Unicode code points are not allowed in the XML InfoSet, for + /// details see: http://www.w3.org/TR/REC-xml/#charsets. + /// + /// + /// This method replaces any illegal characters in the input string + /// with the mask string specified. + /// + /// + public static string MaskXmlInvalidCharacters(string textData, string mask) + { + return INVALIDCHARS.Replace(textData, mask); + } + + /// + /// Count the number of times that the substring occurs in the text. + /// + /// the text to search. + /// the substring to find. + /// the number of times the substring occurs in the text. + /// + /// + /// The substring is assumed to be non repeating within itself. + /// + /// + private static int CountSubstrings(string text, string substring) + { + int count = 0; + int offset = 0; + int length = text.Length; + int substringLength = substring.Length; + + if (length == 0) + { + return 0; + } + + if (substringLength == 0) + { + return 0; + } + + while (offset < length) + { + int index = text.IndexOf(substring, offset); + + if (index == -1) + { + break; + } + + count++; + offset = index + substringLength; + } + + return count; + } + + private const string CDATA_END = "]]>"; + private const string CDATA_UNESCAPABLE_TOKEN = "]]"; /// - /// Characters illegal in XML 1.0 + /// Characters illegal in XML 1.0. /// - private static Regex INVALIDCHARS=new Regex(@"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD]",RegexOptions.Compiled); - #endregion Private Static Fields - } + private static Regex INVALIDCHARS = new Regex(@"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD]", RegexOptions.Compiled); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs index e7e7e139923..6d5bb99ee07 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs @@ -1,89 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.TypeConverters { - /// - /// Type converter for Boolean. - /// - /// - /// - /// Supports conversion from string to bool type. - /// - /// - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - internal class BooleanConverter : IConvertFrom - { - #region Implementation of IConvertFrom - - /// - /// Can the source type be converted to the type supported by this object - /// - /// the type to convert - /// true if the conversion is possible - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return (sourceType == typeof(string)); - } - - /// - /// Convert the source object to the type supported by this object - /// - /// the object to convert - /// the converted object - /// - /// - /// Uses the method to convert the - /// argument to a . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return bool.Parse(str); - } - throw ConversionNotSupportedException.Create(typeof(bool), source); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Type converter for Boolean. + /// + /// + /// + /// Supports conversion from string to bool type. + /// + /// + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + internal class BooleanConverter : IConvertFrom + { + /// + /// Can the source type be converted to the type supported by this object. + /// + /// the type to convert. + /// true if the conversion is possible. + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return sourceType == typeof(string); + } - #endregion - } + /// + /// Convert the source object to the type supported by this object. + /// + /// the object to convert. + /// the converted object. + /// + /// + /// Uses the method to convert the + /// argument to a . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return bool.Parse(str); + } + + throw ConversionNotSupportedException.Create(typeof(bool), source); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs index 0764cc3c767..3e3ac3ba5bb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs @@ -1,162 +1,156 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if !(NETCF || NETSTANDARD1_3) using System.Runtime.Serialization; + #endif namespace log4net.Util.TypeConverters { - /// - /// Exception base type for conversion errors. - /// - /// - /// - /// This type extends . It - /// does not add any new functionality but does differentiate the - /// type of exception being thrown. - /// - /// - /// Nicko Cadell - /// Gert Driesen + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Exception base type for conversion errors. + /// + /// + /// + /// This type extends . It + /// does not add any new functionality but does differentiate the + /// type of exception being thrown. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. #if !NETCF - [Serializable] + [Serializable] #endif #if NETSTANDARD1_3 public class ConversionNotSupportedException : Exception #else - public class ConversionNotSupportedException : ApplicationException + public class ConversionNotSupportedException : ApplicationException #endif - { - #region Public Instance Constructors - - /// - /// Constructor - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ConversionNotSupportedException() - { - } - - /// - /// Constructor - /// - /// A message to include with the exception. - /// - /// - /// Initializes a new instance of the class - /// with the specified message. - /// - /// - public ConversionNotSupportedException(String message) : base(message) - { - } - - /// - /// Constructor - /// - /// A message to include with the exception. - /// A nested exception to include. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and inner exception. - /// - /// - public ConversionNotSupportedException(String message, Exception innerException) : base(message, innerException) - { - } - - #endregion Public Instance Constructors - - #region Protected Instance Constructors - + { + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ConversionNotSupportedException() + { + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// A message to include with the exception. + /// + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + public ConversionNotSupportedException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// A message to include with the exception. + /// A nested exception to include. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and inner exception. + /// + /// + public ConversionNotSupportedException(string message, Exception innerException) + : base(message, innerException) + { + } + #if !(NETCF || NETSTANDARD1_3) - /// - /// Serialization constructor - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected ConversionNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } + /// + /// Initializes a new instance of the class. + /// Serialization constructor. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected ConversionNotSupportedException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } #endif + + /// + /// Creates a new instance of the class. + /// + /// The conversion destination type. + /// The value to convert. + /// An instance of the . + /// + /// + /// Creates a new instance of the class. + /// + /// + public static ConversionNotSupportedException Create(Type destinationType, object sourceValue) + { + return Create(destinationType, sourceValue, null); + } - #endregion Protected Instance Constructors - - #region Public Static Methods - - /// - /// Creates a new instance of the class. - /// - /// The conversion destination type. - /// The value to convert. - /// An instance of the . - /// - /// - /// Creates a new instance of the class. - /// - /// - public static ConversionNotSupportedException Create(Type destinationType, object sourceValue) - { - return Create(destinationType, sourceValue, null); - } - - /// - /// Creates a new instance of the class. - /// - /// The conversion destination type. - /// The value to convert. - /// A nested exception to include. - /// An instance of the . - /// - /// - /// Creates a new instance of the class. - /// - /// - public static ConversionNotSupportedException Create(Type destinationType, object sourceValue, Exception innerException) - { - if (sourceValue == null) - { - return new ConversionNotSupportedException("Cannot convert value [null] to type ["+destinationType+"]", innerException); - } - else - { - return new ConversionNotSupportedException("Cannot convert from type ["+sourceValue.GetType()+"] value ["+sourceValue+"] to type ["+destinationType+"]", innerException); - } - } - - #endregion Public Static Methods - } + /// + /// Creates a new instance of the class. + /// + /// The conversion destination type. + /// The value to convert. + /// A nested exception to include. + /// An instance of the . + /// + /// + /// Creates a new instance of the class. + /// + /// + public static ConversionNotSupportedException Create(Type destinationType, object sourceValue, Exception innerException) + { + if (sourceValue == null) + { + return new ConversionNotSupportedException("Cannot convert value [null] to type [" + destinationType + "]", innerException); + } + else + { + return new ConversionNotSupportedException("Cannot convert from type [" + sourceValue.GetType() + "] value [" + sourceValue + "] to type [" + destinationType + "]", innerException); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs index b9b47acf1cc..d87772b18f1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs @@ -1,300 +1,284 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Globalization; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + + #if NETSTANDARD1_3 using System.Linq; #endif -using System.Reflection; using System.Collections; +using System.Reflection; namespace log4net.Util.TypeConverters { - /// - /// Register of type converters for specific types. - /// - /// - /// - /// Maintains a registry of type converters used to convert between - /// types. - /// - /// - /// Use the and - /// methods to register new converters. - /// The and methods - /// lookup appropriate converters to use. - /// - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - public sealed class ConverterRegistry - { - #region Private Constructors - - /// - /// Private constructor - /// - /// - /// Initializes a new instance of the class. - /// - private ConverterRegistry() - { - } - - #endregion Private Constructors - - #region Static Constructor - - /// - /// Static constructor. - /// - /// - /// - /// This constructor defines the intrinsic type converters. - /// - /// - static ConverterRegistry() - { - // Add predefined converters here - AddConverter(typeof(bool), typeof(BooleanConverter)); - AddConverter(typeof(System.Text.Encoding), typeof(EncodingConverter)); - AddConverter(typeof(System.Type), typeof(TypeConverter)); - AddConverter(typeof(log4net.Layout.PatternLayout), typeof(PatternLayoutConverter)); - AddConverter(typeof(log4net.Util.PatternString), typeof(PatternStringConverter)); - AddConverter(typeof(System.Net.IPAddress), typeof(IPAddressConverter)); - } - - #endregion Static Constructor - - #region Public Static Methods - - /// - /// Adds a converter for a specific type. - /// - /// The type being converted to. - /// The type converter to use to convert to the destination type. - /// - /// - /// Adds a converter instance for a specific type. - /// - /// - public static void AddConverter(Type destinationType, object converter) - { - if (destinationType != null && converter != null) - { - lock(s_type2converter) - { - s_type2converter[destinationType] = converter; - } - } - } - - /// - /// Adds a converter for a specific type. - /// - /// The type being converted to. - /// The type of the type converter to use to convert to the destination type. - /// - /// - /// Adds a converter for a specific type. - /// - /// - public static void AddConverter(Type destinationType, Type converterType) - { - AddConverter(destinationType, CreateConverterInstance(converterType)); - } - - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// The type being converted from. - /// The type being converted to. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - /// - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// - public static IConvertTo GetConvertTo(Type sourceType, Type destinationType) - { - // TODO: Support inheriting type converters. - // i.e. getting a type converter for a base of sourceType - - // TODO: Is destinationType required? We don't use it for anything. - - lock(s_type2converter) - { - // Lookup in the static registry - IConvertTo converter = s_type2converter[sourceType] as IConvertTo; - - if (converter == null) - { - // Lookup using attributes - converter = GetConverterFromAttribute(sourceType) as IConvertTo; + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Globalization; + + /// + /// Register of type converters for specific types. + /// + /// + /// + /// Maintains a registry of type converters used to convert between + /// types. + /// + /// + /// Use the and + /// methods to register new converters. + /// The and methods + /// lookup appropriate converters to use. + /// + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public sealed class ConverterRegistry + { + /// + /// Initializes a new instance of the class. + /// Private constructor. + /// + /// + /// Initializes a new instance of the class. + /// + private ConverterRegistry() + { + } + + /// + /// Initializes static members of the class. + /// Static constructor. + /// + /// + /// + /// This constructor defines the intrinsic type converters. + /// + /// + static ConverterRegistry() + { + // Add predefined converters here + AddConverter(typeof(bool), typeof(BooleanConverter)); + AddConverter(typeof(System.Text.Encoding), typeof(EncodingConverter)); + AddConverter(typeof(System.Type), typeof(TypeConverter)); + AddConverter(typeof(log4net.Layout.PatternLayout), typeof(PatternLayoutConverter)); + AddConverter(typeof(log4net.Util.PatternString), typeof(PatternStringConverter)); + AddConverter(typeof(System.Net.IPAddress), typeof(IPAddressConverter)); + } + + /// + /// Adds a converter for a specific type. + /// + /// The type being converted to. + /// The type converter to use to convert to the destination type. + /// + /// + /// Adds a converter instance for a specific type. + /// + /// + public static void AddConverter(Type destinationType, object converter) + { + if (destinationType != null && converter != null) + { + lock (s_type2converter) + { + s_type2converter[destinationType] = converter; + } + } + } - if (converter != null) - { - // Store in registry - s_type2converter[sourceType] = converter; - } - } + /// + /// Adds a converter for a specific type. + /// + /// The type being converted to. + /// The type of the type converter to use to convert to the destination type. + /// + /// + /// Adds a converter for a specific type. + /// + /// + public static void AddConverter(Type destinationType, Type converterType) + { + AddConverter(destinationType, CreateConverterInstance(converterType)); + } - return converter; - } - } + /// + /// Gets the type converter to use to convert values to the destination type. + /// + /// The type being converted from. + /// The type being converted to. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + /// + /// + /// Gets the type converter to use to convert values to the destination type. + /// + /// + public static IConvertTo GetConvertTo(Type sourceType, Type destinationType) + { + // TODO: Support inheriting type converters. + // i.e. getting a type converter for a base of sourceType - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// The type being converted to. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - /// - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// - public static IConvertFrom GetConvertFrom(Type destinationType) - { - // TODO: Support inheriting type converters. - // i.e. getting a type converter for a base of destinationType + // TODO: Is destinationType required? We don't use it for anything. + lock (s_type2converter) + { + // Lookup in the static registry + IConvertTo converter = s_type2converter[sourceType] as IConvertTo; - lock(s_type2converter) - { - // Lookup in the static registry - IConvertFrom converter = s_type2converter[destinationType] as IConvertFrom; + if (converter == null) + { + // Lookup using attributes + converter = GetConverterFromAttribute(sourceType) as IConvertTo; - if (converter == null) - { - // Lookup using attributes - converter = GetConverterFromAttribute(destinationType) as IConvertFrom; + if (converter != null) + { + // Store in registry + s_type2converter[sourceType] = converter; + } + } - if (converter != null) - { - // Store in registry - s_type2converter[destinationType] = converter; - } - } + return converter; + } + } - return converter; - } - } - - /// - /// Lookups the type converter to use as specified by the attributes on the - /// destination type. - /// - /// The type being converted to. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - private static object GetConverterFromAttribute(Type destinationType) - { - // Look for an attribute on the destination type - object[] attributes = destinationType.GetCustomAttributes(typeof(TypeConverterAttribute), true); - if (attributes != null && attributes.Length > 0) - { - TypeConverterAttribute tcAttr = attributes[0] as TypeConverterAttribute; - if (tcAttr != null) - { - Type converterType = SystemInfo.GetTypeFromString(destinationType, tcAttr.ConverterTypeName, false, true); - return CreateConverterInstance(converterType); - } - } + /// + /// Gets the type converter to use to convert values to the destination type. + /// + /// The type being converted to. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + /// + /// + /// Gets the type converter to use to convert values to the destination type. + /// + /// + public static IConvertFrom GetConvertFrom(Type destinationType) + { + // TODO: Support inheriting type converters. + // i.e. getting a type converter for a base of destinationType + lock (s_type2converter) + { + // Lookup in the static registry + IConvertFrom converter = s_type2converter[destinationType] as IConvertFrom; - // Not found converter using attributes - return null; - } + if (converter == null) + { + // Lookup using attributes + converter = GetConverterFromAttribute(destinationType) as IConvertFrom; - /// - /// Creates the instance of the type converter. - /// - /// The type of the type converter. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - /// - /// - /// The type specified for the type converter must implement - /// the or interfaces - /// and must have a public default (no argument) constructor. - /// - /// - private static object CreateConverterInstance(Type converterType) - { - if (converterType == null) - { - throw new ArgumentNullException("converterType", "CreateConverterInstance cannot create instance, converterType is null"); - } + if (converter != null) + { + // Store in registry + s_type2converter[destinationType] = converter; + } + } - // Check type is a converter - if (typeof(IConvertFrom).IsAssignableFrom(converterType) || typeof(IConvertTo).IsAssignableFrom(converterType)) - { - try - { - // Create the type converter - return Activator.CreateInstance(converterType); - } - catch(Exception ex) - { - LogLog.Error(declaringType, "Cannot CreateConverterInstance of type ["+converterType.FullName+"], Exception in call to Activator.CreateInstance", ex); - } - } - else - { - LogLog.Error(declaringType, "Cannot CreateConverterInstance of type ["+converterType.FullName+"], type does not implement IConvertFrom or IConvertTo"); - } - return null; - } + return converter; + } + } - #endregion Public Static Methods + /// + /// Lookups the type converter to use as specified by the attributes on the + /// destination type. + /// + /// The type being converted to. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + private static object GetConverterFromAttribute(Type destinationType) + { + // Look for an attribute on the destination type + object[] attributes = destinationType.GetCustomAttributes(typeof(TypeConverterAttribute), true); + if (attributes != null && attributes.Length > 0) + { + TypeConverterAttribute tcAttr = attributes[0] as TypeConverterAttribute; + if (tcAttr != null) + { + Type converterType = SystemInfo.GetTypeFromString(destinationType, tcAttr.ConverterTypeName, false, true); + return CreateConverterInstance(converterType); + } + } - #region Private Static Fields + // Not found converter using attributes + return null; + } - /// - /// The fully qualified type of the ConverterRegistry class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private readonly static Type declaringType = typeof(ConverterRegistry); + /// + /// Creates the instance of the type converter. + /// + /// The type of the type converter. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + /// + /// + /// The type specified for the type converter must implement + /// the or interfaces + /// and must have a public default (no argument) constructor. + /// + /// + private static object CreateConverterInstance(Type converterType) + { + if (converterType == null) + { + throw new ArgumentNullException("converterType", "CreateConverterInstance cannot create instance, converterType is null"); + } - /// - /// Mapping from to type converter. - /// - private static Hashtable s_type2converter = new Hashtable(); + // Check type is a converter + if (typeof(IConvertFrom).IsAssignableFrom(converterType) || typeof(IConvertTo).IsAssignableFrom(converterType)) + { + try + { + // Create the type converter + return Activator.CreateInstance(converterType); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Cannot CreateConverterInstance of type [" + converterType.FullName + "], Exception in call to Activator.CreateInstance", ex); + } + } + else + { + LogLog.Error(declaringType, "Cannot CreateConverterInstance of type [" + converterType.FullName + "], type does not implement IConvertFrom or IConvertTo"); + } + + return null; + } + + /// + /// The fully qualified type of the ConverterRegistry class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(ConverterRegistry); - #endregion - } + /// + /// Mapping from to type converter. + /// + private static Hashtable s_type2converter = new Hashtable(); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs index ee1ee9dafc5..c1767ce8be9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs @@ -1,90 +1,84 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.TypeConverters { - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// - /// - /// - /// Nicko Cadell - /// Gert Driesen - internal class EncodingConverter : IConvertFrom - { - #region Implementation of IConvertFrom - - /// - /// Can the source type be converted to the type supported by this object - /// - /// the type to convert - /// true if the conversion is possible - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return (sourceType == typeof(string)); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to an encoding - /// the encoding - /// - /// - /// Uses the method to - /// convert the argument to an . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return Encoding.GetEncoding(str); - } - throw ConversionNotSupportedException.Create(typeof(Encoding), source); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + internal class EncodingConverter : IConvertFrom + { + /// + /// Can the source type be converted to the type supported by this object. + /// + /// the type to convert. + /// true if the conversion is possible. + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return sourceType == typeof(string); + } - #endregion - } + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to an encoding. + /// the encoding. + /// + /// + /// Uses the method to + /// convert the argument to an . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return Encoding.GetEncoding(str); + } + + throw ConversionNotSupportedException.Create(typeof(Encoding), source); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs index ba540f97486..b1d01f89c44 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs @@ -1,67 +1,64 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.TypeConverters { - /// - /// Interface supported by type converters - /// - /// - /// - /// This interface supports conversion from arbitrary types - /// to a single target type. See . - /// - /// - /// Nicko Cadell - /// Gert Driesen - public interface IConvertFrom - { - /// - /// Can the source type be converted to the type supported by this object - /// - /// the type to convert - /// true if the conversion is possible - /// - /// - /// Test if the can be converted to the - /// type supported by this converter. - /// - /// - bool CanConvertFrom(Type sourceType); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Interface supported by type converters. + /// + /// + /// + /// This interface supports conversion from arbitrary types + /// to a single target type. See . + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + public interface IConvertFrom + { + /// + /// Can the source type be converted to the type supported by this object. + /// + /// the type to convert. + /// true if the conversion is possible. + /// + /// + /// Test if the can be converted to the + /// type supported by this converter. + /// + /// + bool CanConvertFrom(Type sourceType); - /// - /// Convert the source object to the type supported by this object - /// - /// the object to convert - /// the converted object - /// - /// - /// Converts the to the type supported - /// by this converter. - /// - /// - object ConvertFrom(object source); - } + /// + /// Convert the source object to the type supported by this object. + /// + /// the object to convert. + /// the converted object. + /// + /// + /// Converts the to the type supported + /// by this converter. + /// + /// + object ConvertFrom(object source); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs index 1f552a045e1..1c3f8d453f6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs @@ -1,67 +1,64 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.TypeConverters { - /// - /// Interface supported by type converters - /// - /// - /// - /// This interface supports conversion from a single type to arbitrary types. - /// See . - /// - /// - /// Nicko Cadell - public interface IConvertTo - { - /// - /// Returns whether this converter can convert the object to the specified type - /// - /// A Type that represents the type you want to convert to - /// true if the conversion is possible - /// - /// - /// Test if the type supported by this converter can be converted to the - /// . - /// - /// - bool CanConvertTo(Type targetType); + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Interface supported by type converters. + /// + /// + /// + /// This interface supports conversion from a single type to arbitrary types. + /// See . + /// + /// + /// Nicko Cadell. + public interface IConvertTo + { + /// + /// Returns whether this converter can convert the object to the specified type. + /// + /// A Type that represents the type you want to convert to. + /// true if the conversion is possible. + /// + /// + /// Test if the type supported by this converter can be converted to the + /// . + /// + /// + bool CanConvertTo(Type targetType); - /// - /// Converts the given value object to the specified type, using the arguments - /// - /// the object to convert - /// The Type to convert the value parameter to - /// the converted object - /// - /// - /// Converts the (which must be of the type supported - /// by this converter) to the specified.. - /// - /// - object ConvertTo(object source, Type targetType); - } + /// + /// Converts the given value object to the specified type, using the arguments. + /// + /// the object to convert. + /// The Type to convert the value parameter to. + /// the converted object. + /// + /// + /// Converts the (which must be of the type supported + /// by this converter) to the specified.. + /// + /// + object ConvertTo(object source, Type targetType); + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs index b2b2d2347e0..8817ada0b03 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs @@ -1,107 +1,102 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Net; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.TypeConverters { - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// - /// - /// Nicko Cadell - internal class IPAddressConverter : IConvertFrom - { - #region Implementation of IConvertFrom + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Net; + + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// + /// + /// Nicko Cadell. + internal class IPAddressConverter : IConvertFrom + { + /// + /// Can the source type be converted to the type supported by this object. + /// + /// the type to convert. + /// true if the conversion is possible. + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return sourceType == typeof(string); + } - /// - /// Can the source type be converted to the type supported by this object - /// - /// the type to convert - /// true if the conversion is possible - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return (sourceType == typeof(string)); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to an IPAddress - /// the IPAddress - /// - /// - /// Uses the method to convert the - /// argument to an . - /// If that fails then the string is resolved as a DNS hostname. - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null && str.Length > 0) - { - try - { + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to an IPAddress. + /// the IPAddress. + /// + /// + /// Uses the method to convert the + /// argument to an . + /// If that fails then the string is resolved as a DNS hostname. + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null && str.Length > 0) + { + try + { #if NET_2_0 || NETCF_2_0 #if !NETCF_2_0 - // Try an explicit parse of string representation of an IPAddress (v4 or v6) - IPAddress result; - if (IPAddress.TryParse(str, out result)) - { - return result; - } + // Try an explicit parse of string representation of an IPAddress (v4 or v6) + IPAddress result; + if (IPAddress.TryParse(str, out result)) + { + return result; + } #endif - // Try to resolve via DNS. This is a blocking call. - // GetHostEntry works with either an IPAddress string or a host name - IPHostEntry host = Dns.GetHostEntry(str); - if (host != null && - host.AddressList != null && - host.AddressList.Length > 0 && - host.AddressList[0] != null) - { - return host.AddressList[0]; - } + // Try to resolve via DNS. This is a blocking call. + // GetHostEntry works with either an IPAddress string or a host name + IPHostEntry host = Dns.GetHostEntry(str); + if (host != null && + host.AddressList != null && + host.AddressList.Length > 0 && + host.AddressList[0] != null) + { + return host.AddressList[0]; + } #else // Before .NET 2 we need to try to parse the IPAddress from the string first @@ -133,20 +128,19 @@ public object ConvertFrom(object source) return host.AddressList[0]; } #endif - } - catch(Exception ex) - { - throw ConversionNotSupportedException.Create(typeof(IPAddress), source, ex); - } - } - throw ConversionNotSupportedException.Create(typeof(IPAddress), source); - } - - #endregion - - /// - /// Valid characters in an IPv4 or IPv6 address string. (Does not support subnets) - /// - private static readonly char[] validIpAddressChars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','A','B','C','D','E','F','x','X','.',':','%'}; - } + } + catch (Exception ex) + { + throw ConversionNotSupportedException.Create(typeof(IPAddress), source, ex); + } + } + + throw ConversionNotSupportedException.Create(typeof(IPAddress), source); + } + + /// + /// Valid characters in an IPv4 or IPv6 address string. (Does not support subnets). + /// + private static readonly char[] validIpAddressChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', 'x', 'X', '.', ':', '%' }; + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs index 89a8aef657c..d5fb5cb593c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs @@ -1,96 +1,90 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; - -using log4net.Layout; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.TypeConverters { - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// The string is used as the - /// of the . - /// - /// - /// - /// - /// - /// Nicko Cadell - internal class PatternLayoutConverter : IConvertFrom - { - #region Implementation of IConvertFrom - - /// - /// Can the source type be converted to the type supported by this object - /// - /// the type to convert - /// true if the conversion is possible - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(System.Type sourceType) - { - return (sourceType == typeof(string)); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to a PatternLayout - /// the PatternLayout - /// - /// - /// Creates and returns a new using - /// the as the - /// . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return new PatternLayout(str); - } - throw ConversionNotSupportedException.Create(typeof(PatternLayout), source); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + using log4net.Layout; + + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// The string is used as the + /// of the . + /// + /// + /// + /// + /// + /// Nicko Cadell. + internal class PatternLayoutConverter : IConvertFrom + { + /// + /// Can the source type be converted to the type supported by this object. + /// + /// the type to convert. + /// true if the conversion is possible. + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(System.Type sourceType) + { + return sourceType == typeof(string); + } - #endregion - } + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to a PatternLayout. + /// the PatternLayout. + /// + /// + /// Creates and returns a new using + /// the as the + /// . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return new PatternLayout(str); + } + + throw ConversionNotSupportedException.Create(typeof(PatternLayout), source); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs index 800eba08c05..79f59b45014 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs @@ -1,147 +1,139 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETSTANDARD1_3 using System.Reflection; #endif using System.Text; - + using log4net.Util; namespace log4net.Util.TypeConverters { - /// - /// Convert between string and - /// - /// - /// - /// Supports conversion from string to type, - /// and from a type to a string. - /// - /// - /// The string is used as the - /// of the . - /// - /// - /// - /// - /// - /// Nicko Cadell - internal class PatternStringConverter : IConvertTo, IConvertFrom - { - #region Implementation of IConvertTo - - /// - /// Can the target type be converted to the type supported by this object - /// - /// A that represents the type you want to convert to - /// true if the conversion is possible - /// - /// - /// Returns true if the is - /// assignable from a type. - /// - /// - public bool CanConvertTo(Type targetType) - { - return (typeof(string).IsAssignableFrom(targetType)); - } - - /// - /// Converts the given value object to the specified type, using the arguments - /// - /// the object to convert - /// The Type to convert the value parameter to - /// the converted object - /// - /// - /// Uses the method to convert the - /// argument to a . - /// - /// - /// - /// The object cannot be converted to the - /// . To check for this condition use the - /// method. - /// - public object ConvertTo(object source, Type targetType) - { - PatternString patternString = source as PatternString; - if (patternString != null && CanConvertTo(targetType)) - { - return patternString.Format(); - } - throw ConversionNotSupportedException.Create(targetType, source); - } - - #endregion - - #region Implementation of IConvertFrom - - /// - /// Can the source type be converted to the type supported by this object - /// - /// the type to convert - /// true if the conversion is possible - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(System.Type sourceType) - { - return (sourceType == typeof(string)); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Convert between string and . + /// + /// + /// + /// Supports conversion from string to type, + /// and from a type to a string. + /// + /// + /// The string is used as the + /// of the . + /// + /// + /// + /// + /// + /// Nicko Cadell. + internal class PatternStringConverter : IConvertTo, IConvertFrom + { + /// + /// Can the target type be converted to the type supported by this object. + /// + /// A that represents the type you want to convert to. + /// true if the conversion is possible. + /// + /// + /// Returns true if the is + /// assignable from a type. + /// + /// + public bool CanConvertTo(Type targetType) + { + return typeof(string).IsAssignableFrom(targetType); + } - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to a PatternString - /// the PatternString - /// - /// - /// Creates and returns a new using - /// the as the - /// . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return new PatternString(str); - } - throw ConversionNotSupportedException.Create(typeof(PatternString), source); - } + /// + /// Converts the given value object to the specified type, using the arguments. + /// + /// the object to convert. + /// The Type to convert the value parameter to. + /// the converted object. + /// + /// + /// Uses the method to convert the + /// argument to a . + /// + /// + /// + /// The object cannot be converted to the + /// . To check for this condition use the + /// method. + /// + public object ConvertTo(object source, Type targetType) + { + PatternString patternString = source as PatternString; + if (patternString != null && this.CanConvertTo(targetType)) + { + return patternString.Format(); + } + + throw ConversionNotSupportedException.Create(targetType, source); + } + + /// + /// Can the source type be converted to the type supported by this object. + /// + /// the type to convert. + /// true if the conversion is possible. + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(System.Type sourceType) + { + return sourceType == typeof(string); + } - #endregion - } + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to a PatternString. + /// the PatternString. + /// + /// + /// Creates and returns a new using + /// the as the + /// . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return new PatternString(str); + } + + throw ConversionNotSupportedException.Create(typeof(PatternString), source); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs index 675d9970cf2..c889203809a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs @@ -1,98 +1,93 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; -using System.Text; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if NETSTANDARD1_3 using System.Reflection; #endif namespace log4net.Util.TypeConverters { - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// - /// - /// - /// Nicko Cadell - internal class TypeConverter : IConvertFrom - { - #region Implementation of IConvertFrom - - /// - /// Can the source type be converted to the type supported by this object - /// - /// the type to convert - /// true if the conversion is possible - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return (sourceType == typeof(string)); - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + using System.Text; + + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// + /// + /// + /// Nicko Cadell. + internal class TypeConverter : IConvertFrom + { + /// + /// Can the source type be converted to the type supported by this object. + /// + /// the type to convert. + /// true if the conversion is possible. + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return sourceType == typeof(string); + } - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to a Type - /// the Type - /// - /// - /// Uses the method to convert the - /// argument to a . - /// Additional effort is made to locate partially specified types - /// by searching the loaded assemblies. - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to a Type. + /// the Type. + /// + /// + /// Uses the method to convert the + /// argument to a . + /// Additional effort is made to locate partially specified types + /// by searching the loaded assemblies. + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { #if NETSTANDARD1_3 // TODO can we use ComponentModel here? return SystemInfo.GetTypeFromString(GetType().GetTypeInfo().Assembly, str, true, true); #else - return SystemInfo.GetTypeFromString(str, true, true); + return SystemInfo.GetTypeFromString(str, true, true); #endif - } - throw ConversionNotSupportedException.Create(typeof(Type), source); - } - - #endregion - } + } + + throw ConversionNotSupportedException.Create(typeof(Type), source); + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs index c913b1085ab..2682acb88c3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs @@ -1,120 +1,112 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#endregion - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace log4net.Util.TypeConverters { - /// - /// Attribute used to associate a type converter - /// - /// - /// - /// Class and Interface level attribute that specifies a type converter - /// to use with the associated type. - /// - /// - /// To associate a type converter with a target type apply a - /// TypeConverterAttribute to the target type. Specify the - /// type of the type converter on the attribute. - /// - /// - /// Nicko Cadell - /// Gert Driesen - [AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface|AttributeTargets.Enum)] - public sealed class TypeConverterAttribute : Attribute - { - #region Member Variables - - /// - /// The string type name of the type converter - /// - private string m_typeName = null; - - #endregion - - #region Constructors - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public TypeConverterAttribute() - { - } - - /// - /// Create a new type converter attribute for the specified type name - /// - /// The string type name of the type converter - /// - /// - /// The type specified must implement the - /// or the interfaces. - /// - /// - public TypeConverterAttribute(string typeName) - { - m_typeName = typeName; - } - - /// - /// Create a new type converter attribute for the specified type - /// - /// The type of the type converter - /// - /// - /// The type specified must implement the - /// or the interfaces. - /// - /// - public TypeConverterAttribute(Type converterType) - { - m_typeName = log4net.Util.SystemInfo.AssemblyQualifiedName(converterType); - } - - #endregion - - /// - /// The string type name of the type converter - /// - /// - /// The string type name of the type converter - /// - /// - /// - /// The type specified must implement the - /// or the interfaces. - /// - /// - public string ConverterTypeName - { - get { return m_typeName; } - set { m_typeName = value ; } - } - } + // + // Licensed to the Apache Software Foundation (ASF) under one or more + // contributor license agreements. See the NOTICE file distributed with + // this work for additional information regarding copyright ownership. + // The ASF licenses this file to you under the Apache License, Version 2.0 + // (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + using System; + + /// + /// Attribute used to associate a type converter. + /// + /// + /// + /// Class and Interface level attribute that specifies a type converter + /// to use with the associated type. + /// + /// + /// To associate a type converter with a target type apply a + /// TypeConverterAttribute to the target type. Specify the + /// type of the type converter on the attribute. + /// + /// + /// Nicko Cadell. + /// Gert Driesen. + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum)] + public sealed class TypeConverterAttribute : Attribute + { + /// + /// The string type name of the type converter. + /// + private string m_typeName = null; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public TypeConverterAttribute() + { + } + + /// + /// Initializes a new instance of the class. + /// Create a new type converter attribute for the specified type name. + /// + /// The string type name of the type converter. + /// + /// + /// The type specified must implement the + /// or the interfaces. + /// + /// + public TypeConverterAttribute(string typeName) + { + this.m_typeName = typeName; + } + + /// + /// Initializes a new instance of the class. + /// Create a new type converter attribute for the specified type. + /// + /// The type of the type converter. + /// + /// + /// The type specified must implement the + /// or the interfaces. + /// + /// + public TypeConverterAttribute(Type converterType) + { + this.m_typeName = log4net.Util.SystemInfo.AssemblyQualifiedName(converterType); + } + + /// + /// Gets or sets the string type name of the type converter. + /// + /// + /// The string type name of the type converter. + /// + /// + /// + /// The type specified must implement the + /// or the interfaces. + /// + /// + public string ConverterTypeName + { + get { return this.m_typeName; } + set { this.m_typeName = value; } + } + } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs index 597e4ee6960..7d9a6a341d8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Apache License +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // -// Licensed to the Apache Software Foundation (ASF) under one or more +// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. +// this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with +// (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,10 +18,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion // .NET Compact Framework 1.0 has no support for WindowsIdentity -#if !NETCF +#if !NETCF // MONO 1.0 has no support for Win32 Logon APIs #if !MONO // SSCLI 1.0 has no support for Win32 Logon APIs @@ -32,356 +30,349 @@ using System; using System.Runtime.InteropServices; -using System.Security.Principal; using System.Security.Permissions; - +using System.Security.Principal; + using log4net.Core; namespace log4net.Util { - /// - /// Impersonate a Windows Account - /// - /// - /// - /// This impersonates a Windows account. - /// - /// - /// How the impersonation is done depends on the value of . - /// This allows the context to either impersonate a set of user credentials specified - /// using username, domain name and password or to revert to the process credentials. - /// - /// - public class WindowsSecurityContext : SecurityContext, IOptionHandler - { - /// - /// The impersonation modes for the - /// - /// - /// - /// See the property for - /// details. - /// - /// - public enum ImpersonationMode - { - /// - /// Impersonate a user using the credentials supplied - /// - User, - - /// - /// Revert this the thread to the credentials of the process - /// - Process - } - - #region Member Variables - - private ImpersonationMode m_impersonationMode = ImpersonationMode.User; - private string m_userName; - private string m_domainName = Environment.MachineName; - private string m_password; - private WindowsIdentity m_identity; - - #endregion - - #region Constructor - - /// - /// Default constructor - /// - /// - /// - /// Default constructor - /// - /// - public WindowsSecurityContext() - { - } - - #endregion - - #region Public Properties - - /// - /// Gets or sets the impersonation mode for this security context - /// - /// - /// The impersonation mode for this security context - /// - /// - /// - /// Impersonate either a user with user credentials or - /// revert this thread to the credentials of the process. - /// The value is one of the - /// enum. - /// - /// - /// The default value is - /// - /// - /// When the mode is set to - /// the user's credentials are established using the - /// , and - /// values. - /// - /// - /// When the mode is set to - /// no other properties need to be set. If the calling thread is - /// impersonating then it will be reverted back to the process credentials. - /// - /// - public ImpersonationMode Credentials - { - get { return m_impersonationMode; } - set { m_impersonationMode = value; } - } - - /// - /// Gets or sets the Windows username for this security context - /// - /// - /// The Windows username for this security context - /// - /// - /// - /// This property must be set if - /// is set to (the default setting). - /// - /// - public string UserName - { - get { return m_userName; } - set { m_userName = value; } - } - - /// - /// Gets or sets the Windows domain name for this security context - /// - /// - /// The Windows domain name for this security context - /// - /// - /// - /// The default value for is the local machine name - /// taken from the property. - /// - /// - /// This property must be set if - /// is set to (the default setting). - /// - /// - public string DomainName - { - get { return m_domainName; } - set { m_domainName = value; } - } - - /// - /// Sets the password for the Windows account specified by the and properties. - /// - /// - /// The password for the Windows account specified by the and properties. - /// - /// - /// - /// This property must be set if - /// is set to (the default setting). - /// - /// - public string Password - { - set { m_password = value; } - } - - #endregion - - #region IOptionHandler Members - - /// - /// Initialize the SecurityContext based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// The security context will try to Logon the specified user account and - /// capture a primary token for impersonation. - /// - /// - /// The required , - /// or properties were not specified. - public void ActivateOptions() - { - if (m_impersonationMode == ImpersonationMode.User) - { - if (m_userName == null) throw new ArgumentNullException("m_userName"); - if (m_domainName == null) throw new ArgumentNullException("m_domainName"); - if (m_password == null) throw new ArgumentNullException("m_password"); - - m_identity = LogonUser(m_userName, m_domainName, m_password); - } - } - - #endregion - - /// - /// Impersonate the Windows account specified by the and properties. - /// - /// caller provided state - /// - /// An instance that will revoke the impersonation of this SecurityContext - /// - /// - /// - /// Depending on the property either - /// impersonate a user using credentials supplied or revert - /// to the process credentials. - /// - /// - public override IDisposable Impersonate(object state) - { - if (m_impersonationMode == ImpersonationMode.User) - { - if (m_identity != null) - { - return new DisposableImpersonationContext(m_identity.Impersonate()); - } - } - else if (m_impersonationMode == ImpersonationMode.Process) - { - // Impersonate(0) will revert to the process credentials - return new DisposableImpersonationContext(WindowsIdentity.Impersonate(IntPtr.Zero)); - } - return null; - } - - /// - /// Create a given the userName, domainName and password. - /// - /// the user name - /// the domain name - /// the password - /// the for the account specified - /// - /// - /// Uses the Windows API call LogonUser to get a principal token for the account. This - /// token is used to initialize the WindowsIdentity. - /// - /// + /// + /// Impersonate a Windows Account. + /// + /// + /// + /// This impersonates a Windows account. + /// + /// + /// How the impersonation is done depends on the value of . + /// This allows the context to either impersonate a set of user credentials specified + /// using username, domain name and password or to revert to the process credentials. + /// + /// + public class WindowsSecurityContext : SecurityContext, IOptionHandler + { + /// + /// The impersonation modes for the . + /// + /// + /// + /// See the property for + /// details. + /// + /// + public enum ImpersonationMode + { + /// + /// Impersonate a user using the credentials supplied + /// + User, + + /// + /// Revert this the thread to the credentials of the process + /// + Process, + } + + private ImpersonationMode m_impersonationMode = ImpersonationMode.User; + private string m_userName; + private string m_domainName = Environment.MachineName; + private string m_password; + private WindowsIdentity m_identity; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + /// + /// + /// Default constructor. + /// + /// + public WindowsSecurityContext() + { + } + + /// + /// Gets or sets the impersonation mode for this security context. + /// + /// + /// The impersonation mode for this security context. + /// + /// + /// + /// Impersonate either a user with user credentials or + /// revert this thread to the credentials of the process. + /// The value is one of the + /// enum. + /// + /// + /// The default value is . + /// + /// + /// When the mode is set to + /// the user's credentials are established using the + /// , and + /// values. + /// + /// + /// When the mode is set to + /// no other properties need to be set. If the calling thread is + /// impersonating then it will be reverted back to the process credentials. + /// + /// + public ImpersonationMode Credentials + { + get { return this.m_impersonationMode; } + set { this.m_impersonationMode = value; } + } + + /// + /// Gets or sets the Windows username for this security context. + /// + /// + /// The Windows username for this security context. + /// + /// + /// + /// This property must be set if + /// is set to (the default setting). + /// + /// + public string UserName + { + get { return this.m_userName; } + set { this.m_userName = value; } + } + + /// + /// Gets or sets the Windows domain name for this security context. + /// + /// + /// The Windows domain name for this security context. + /// + /// + /// + /// The default value for is the local machine name + /// taken from the property. + /// + /// + /// This property must be set if + /// is set to (the default setting). + /// + /// + public string DomainName + { + get { return this.m_domainName; } + set { this.m_domainName = value; } + } + + /// + /// Sets the password for the Windows account specified by the and properties. + /// + /// + /// The password for the Windows account specified by the and properties. + /// + /// + /// + /// This property must be set if + /// is set to (the default setting). + /// + /// + public string Password + { + set { this.m_password = value; } + } + + /// + /// Initialize the SecurityContext based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// The security context will try to Logon the specified user account and + /// capture a primary token for impersonation. + /// + /// + /// The required , + /// or properties were not specified. + public void ActivateOptions() + { + if (this.m_impersonationMode == ImpersonationMode.User) + { + if (this.m_userName == null) + { + throw new ArgumentNullException("m_userName"); + } + + if (this.m_domainName == null) + { + throw new ArgumentNullException("m_domainName"); + } + + if (this.m_password == null) + { + throw new ArgumentNullException("m_password"); + } + + this.m_identity = LogonUser(this.m_userName, this.m_domainName, this.m_password); + } + } + + /// + /// Impersonate the Windows account specified by the and properties. + /// + /// caller provided state. + /// + /// An instance that will revoke the impersonation of this SecurityContext. + /// + /// + /// + /// Depending on the property either + /// impersonate a user using credentials supplied or revert + /// to the process credentials. + /// + /// + public override IDisposable Impersonate(object state) + { + if (this.m_impersonationMode == ImpersonationMode.User) + { + if (this.m_identity != null) + { + return new DisposableImpersonationContext(this.m_identity.Impersonate()); + } + } + else if (this.m_impersonationMode == ImpersonationMode.Process) + { + // Impersonate(0) will revert to the process credentials + return new DisposableImpersonationContext(WindowsIdentity.Impersonate(IntPtr.Zero)); + } + + return null; + } + + /// + /// Create a given the userName, domainName and password. + /// + /// the user name. + /// the domain name. + /// the password. + /// the for the account specified. + /// + /// + /// Uses the Windows API call LogonUser to get a principal token for the account. This + /// token is used to initialize the WindowsIdentity. + /// + /// #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] private static WindowsIdentity LogonUser(string userName, string domainName, string password) - { - const int LOGON32_PROVIDER_DEFAULT = 0; - //This parameter causes LogonUser to create a primary token. - const int LOGON32_LOGON_INTERACTIVE = 2; - - // Call LogonUser to obtain a handle to an access token. - IntPtr tokenHandle = IntPtr.Zero; - if(!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle)) - { - NativeError error = NativeError.GetLastError(); - throw new Exception("Failed to LogonUser ["+userName+"] in Domain ["+domainName+"]. Error: "+ error.ToString()); - } - - const int SecurityImpersonation = 2; - IntPtr dupeTokenHandle = IntPtr.Zero; - if(!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle)) - { - NativeError error = NativeError.GetLastError(); - if (tokenHandle != IntPtr.Zero) - { - CloseHandle(tokenHandle); - } - throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString()); - } - - WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle); - - // Free the tokens. - if (dupeTokenHandle != IntPtr.Zero) - { - CloseHandle(dupeTokenHandle); - } - if (tokenHandle != IntPtr.Zero) - { - CloseHandle(tokenHandle); - } - - return identity; - } - - #region Native Method Stubs - - [DllImport("advapi32.dll", SetLastError=true)] - private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); - - [DllImport("kernel32.dll", CharSet=CharSet.Auto)] - private extern static bool CloseHandle(IntPtr handle); - - [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] - private extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); - - #endregion - - #region DisposableImpersonationContext class - - /// - /// Adds to - /// - /// - /// - /// Helper class to expose the - /// through the interface. - /// - /// - private sealed class DisposableImpersonationContext : IDisposable - { - private readonly WindowsImpersonationContext m_impersonationContext; - - /// - /// Constructor - /// - /// the impersonation context being wrapped - /// - /// - /// Constructor - /// - /// - public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext) - { - m_impersonationContext = impersonationContext; - } - - /// - /// Revert the impersonation - /// - /// - /// - /// Revert the impersonation - /// - /// - public void Dispose() - { - m_impersonationContext.Undo(); - } - } - - #endregion - } + { + const int LOGON32_PROVIDER_DEFAULT = 0; + + // This parameter causes LogonUser to create a primary token. + const int LOGON32_LOGON_INTERACTIVE = 2; + + // Call LogonUser to obtain a handle to an access token. + IntPtr tokenHandle = IntPtr.Zero; + if (!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle)) + { + NativeError error = NativeError.GetLastError(); + throw new Exception("Failed to LogonUser [" + userName + "] in Domain [" + domainName + "]. Error: " + error.ToString()); + } + + const int SecurityImpersonation = 2; + IntPtr dupeTokenHandle = IntPtr.Zero; + if (!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle)) + { + NativeError error = NativeError.GetLastError(); + if (tokenHandle != IntPtr.Zero) + { + CloseHandle(tokenHandle); + } + + throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString()); + } + + WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle); + + // Free the tokens. + if (dupeTokenHandle != IntPtr.Zero) + { + CloseHandle(dupeTokenHandle); + } + + if (tokenHandle != IntPtr.Zero) + { + CloseHandle(tokenHandle); + } + + return identity; + } + + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); + + [DllImport("kernel32.dll", CharSet = CharSet.Auto)] + private static extern bool CloseHandle(IntPtr handle); + + [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] + private static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); + + /// + /// Adds to . + /// + /// + /// + /// Helper class to expose the + /// through the interface. + /// + /// + private sealed class DisposableImpersonationContext : IDisposable + { + private readonly WindowsImpersonationContext m_impersonationContext; + + /// + /// Initializes a new instance of the class. + /// Constructor. + /// + /// the impersonation context being wrapped. + /// + /// + /// Constructor. + /// + /// + public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext) + { + this.m_impersonationContext = impersonationContext; + } + + /// + /// Revert the impersonation. + /// + /// + /// + /// Revert the impersonation. + /// + /// + public void Dispose() + { + this.m_impersonationContext.Undo(); + } + } + } } #endif // !CLI_1_0 diff --git a/DNN Platform/DotNetNuke.ModulePipeline/DotNetNuke.ModulePipeline.csproj b/DNN Platform/DotNetNuke.ModulePipeline/DotNetNuke.ModulePipeline.csproj index a66b285d4e9..9f6ad4eb9ce 100644 --- a/DNN Platform/DotNetNuke.ModulePipeline/DotNetNuke.ModulePipeline.csproj +++ b/DNN Platform/DotNetNuke.ModulePipeline/DotNetNuke.ModulePipeline.csproj @@ -14,8 +14,16 @@ + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs b/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs index ba1cc1d62b5..47091f0cda1 100644 --- a/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs +++ b/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs @@ -1,42 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules.Html5; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Razor; -using System.Collections.Generic; -using DotNetNuke.Web.Mvc; - -#if NET472 -using System.Web.UI; -#endif - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ModulePipeline { + using System; + using System.Collections.Generic; + using System.IO; +#if NET472 + using System.Web.UI; +#endif + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Instrumentation; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Modules.Html5; + using DotNetNuke.Web.Mvc; + using DotNetNuke.Web.Razor; + /// /// The Module Pipeline that determines which Module pattern /// to invoke based on the input module type. /// - public class ModuleControlPipeline - // MULTI-TARGETTING PIPELINE - // ------------------------- - // This file multi-targets .NET Framework and .NET Standard, - // which is needed as DNN migrates to .NET Core. The 'NET472' - // pre-processor directives are to fully support Legacy DNN. - // As the Pipeline is upgraded to be more complaint with - // .NET Standard 2.0 use the apprioprate pre-processor directives. + public class ModuleControlPipeline + + // MULTI-TARGETTING PIPELINE + // ------------------------- + // This file multi-targets .NET Framework and .NET Standard, + // which is needed as DNN migrates to .NET Core. The 'NET472' + // pre-processor directives are to fully support Legacy DNN. + // As the Pipeline is upgraded to be more complaint with + // .NET Standard 2.0 use the appropriate pre-processor directives. #if NET472 : IModuleControlPipeline #endif { private static readonly ILog TraceLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); private Dictionary _controlFactories; + public ModuleControlPipeline( WebFormsModuleControlFactory webforms, Html5ModuleControlFactory html5, @@ -44,32 +44,27 @@ public ModuleControlPipeline( MvcModuleControlFactory mvc, ReflectedModuleControlFactory fallthrough) { - _controlFactories = new Dictionary(StringComparer.OrdinalIgnoreCase); - _controlFactories.Add(".ascx", webforms); - _controlFactories.Add(".htm", html5); - _controlFactories.Add(".html", html5); - _controlFactories.Add(".cshtml", razor3); - _controlFactories.Add(".vbhtml", razor3); - _controlFactories.Add(".mvc", mvc); - _controlFactories.Add("default", fallthrough); + this._controlFactories = new Dictionary(StringComparer.OrdinalIgnoreCase); + this._controlFactories.Add(".ascx", webforms); + this._controlFactories.Add(".htm", html5); + this._controlFactories.Add(".html", html5); + this._controlFactories.Add(".cshtml", razor3); + this._controlFactories.Add(".vbhtml", razor3); + this._controlFactories.Add(".mvc", mvc); + this._controlFactories.Add("default", fallthrough); } #if NET472 - private IModuleControlFactory GetModuleControlFactory(string controlSrc) - { - string extension = Path.GetExtension(controlSrc); - _controlFactories.TryGetValue(extension, out IModuleControlFactory factory); - - return factory ?? _controlFactories["default"]; - } - + /// public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc) { - if (TraceLogger.IsDebugEnabled) - TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - + if (TraceLogger.IsDebugEnabled) + { + TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; - IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); + IModuleControlFactory controlFactory = this.GetModuleControlFactory(controlSrc); if (controlFactory != null) { @@ -90,17 +85,24 @@ public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo mo } } - if (TraceLogger.IsDebugEnabled) - TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + if (TraceLogger.IsDebugEnabled) + { + TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } + /// public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { if (TraceLogger.IsDebugEnabled) + { TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; - IModuleControlFactory controlFactory = GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); + IModuleControlFactory controlFactory = this.GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); if (controlFactory != null) { @@ -122,17 +124,23 @@ public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo mo } if (TraceLogger.IsDebugEnabled) + { TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } + /// public Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) { - if (TraceLogger.IsDebugEnabled) - TraceLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - + if (TraceLogger.IsDebugEnabled) + { + TraceLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; - IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); + IModuleControlFactory controlFactory = this.GetModuleControlFactory(controlSrc); if (controlFactory != null) { @@ -157,11 +165,15 @@ public Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo } } - if (TraceLogger.IsDebugEnabled) - TraceLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + if (TraceLogger.IsDebugEnabled) + { + TraceLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } + /// public Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfiguration) { var moduleControl = new CachedModuleControl(cachedContent); @@ -169,11 +181,20 @@ public Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfig return moduleControl; } + /// public Control CreateModuleControl(ModuleInfo moduleConfiguration) { - IModuleControlFactory factory = GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); + IModuleControlFactory factory = this.GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); return factory.CreateModuleControl(moduleConfiguration); } + + private IModuleControlFactory GetModuleControlFactory(string controlSrc) + { + string extension = Path.GetExtension(controlSrc); + this._controlFactories.TryGetValue(extension, out IModuleControlFactory factory); + + return factory ?? this._controlFactories["default"]; + } #endif } } diff --git a/DNN Platform/DotNetNuke.ModulePipeline/Startup.cs b/DNN Platform/DotNetNuke.ModulePipeline/Startup.cs index 22325d0ca9b..5186bc6d14b 100644 --- a/DNN Platform/DotNetNuke.ModulePipeline/Startup.cs +++ b/DNN Platform/DotNetNuke.ModulePipeline/Startup.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.DependencyInjection; -using DotNetNuke.UI.Modules; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ModulePipeline { + using DotNetNuke.DependencyInjection; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + public class Startup : IDnnStartup { public void ConfigureServices(IServiceCollection services) @@ -17,7 +17,7 @@ public void ConfigureServices(IServiceCollection services) // This file multi-targets .NET Framework and .NET Standard, // which is needed as DNN migrates to .NET Core. The 'NET472' // pre-processor directives are to fully support Legacy DNN. - // As the Pipeline is upgraded to be more complaint with + // As the Pipeline is upgraded to be more complaint with // .NET Standard 2.0 use the apprioprate pre-processor directives. #if NET472 services.AddSingleton(); diff --git a/DNN Platform/DotNetNuke.Web.Client/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Web.Client/AssemblyInfo.cs index 4c4e62d4221..6b7149551a9 100644 --- a/DNN Platform/DotNetNuke.Web.Client/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Web.Client/AssemblyInfo.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Web.Client")] diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs index daa02586cad..5e320bec516 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs @@ -1,101 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Configuration; -using System.Web; -using System.Web.Configuration; -using System.Web.Hosting; -using System.Xml; -using System.Xml.XPath; - -using ClientDependency.Core.CompositeFiles.Providers; - -using DotNetNuke; - -using ClientDependency.Core.Config; - -using DotNetNuke.Instrumentation; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { + using System; + using System.Collections.Generic; + using System.Configuration; using System.IO; + using System.Threading; + using System.Web; + using System.Web.Configuration; + using System.Web.Hosting; using System.Web.UI; + using System.Xml; + using System.Xml.XPath; + using ClientDependency.Core; - using System.Collections.Generic; - using System.Threading; - + using ClientDependency.Core.CompositeFiles.Providers; + using ClientDependency.Core.Config; + using DotNetNuke; + using DotNetNuke.Instrumentation; + /// /// Provides the ability to request that client resources (JavaScript and CSS) be loaded on the client browser. /// public class ClientResourceManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ClientResourceManager)); internal const string DefaultCssProvider = "DnnPageHeaderProvider"; internal const string DefaultJsProvider = "DnnBodyProvider"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ClientResourceManager)); - static Dictionary _fileExistsCache = new Dictionary(); - static ReaderWriterLockSlim _lockFileExistsCache = new ReaderWriterLockSlim(); - - #region Private Methods - - private static bool FileExists(Page page, string filePath) - { - // remove query string for the file exists check, won't impact the absoluteness, so just do it either way. - filePath = RemoveQueryString(filePath); - var cacheKey = filePath.ToLowerInvariant(); - // cache css file paths - if (!_fileExistsCache.ContainsKey(cacheKey)) - { - // appply lock after IF, locking is more expensive than worst case scenario (check disk twice) - _lockFileExistsCache.EnterWriteLock(); - try - { - _fileExistsCache[cacheKey] = IsAbsoluteUrl(filePath) || File.Exists(page.Server.MapPath(filePath)); - } - finally - { - _lockFileExistsCache.ExitWriteLock(); - } - } - - // return if file exists from cache - _lockFileExistsCache.EnterReadLock(); - try - { - return _fileExistsCache[cacheKey]; - } - finally - { - _lockFileExistsCache.ExitReadLock(); - } - } - - private static bool IsAbsoluteUrl(string url) - { - Uri result; - return Uri.TryCreate(url, UriKind.Absolute, out result); - } - - private static string RemoveQueryString(string filePath) - { - var queryStringPosition = filePath.IndexOf("?", StringComparison.Ordinal); - return queryStringPosition != -1 ? filePath.Substring(0, queryStringPosition) : filePath; - } - - #endregion - - #region Public Methods - + private static Dictionary _fileExistsCache = new Dictionary(); + private static ReaderWriterLockSlim _lockFileExistsCache = new ReaderWriterLockSlim(); + /// /// Adds the neccessary configuration to website root web.config to use the Client Depenedecny componenet. /// public static void AddConfiguration() { var configPath = HostingEnvironment.MapPath("~/web.config"); - if (!String.IsNullOrEmpty(configPath)) + if (!string.IsNullOrEmpty(configPath)) { var xmlDoc = new XmlDocument { XmlResolver = null }; xmlDoc.Load(configPath); @@ -126,6 +71,7 @@ public static void AddConfiguration() xmlDoc.DocumentElement.SelectSingleNode("system.webServer/modules").AppendChild(xmlFrag); } } + // Handler Config var systemWebServerHandlersConfig = xmlDoc.DocumentElement.SelectSingleNode("system.webServer/handlers"); if (systemWebServerHandlersConfig != null) @@ -151,6 +97,7 @@ public static void AddConfiguration() xmlDoc.DocumentElement.SelectSingleNode("system.web/httpModules").AppendChild(xmlFrag); } } + // HttpHandler Config var systemWebServerHttpHandlersConfig = xmlDoc.DocumentElement.SelectSingleNode("system.web/httpHandlers"); if (systemWebServerHttpHandlersConfig != null) @@ -201,7 +148,7 @@ public static bool IsInstalled() var configPath = HostingEnvironment.MapPath("~/web.config"); var installed = false; - if (!String.IsNullOrEmpty(configPath)) + if (!string.IsNullOrEmpty(configPath)) { var xmlDoc = new XmlDocument { XmlResolver = null }; xmlDoc.Load(configPath); @@ -217,6 +164,51 @@ public static bool IsInstalled() return installed; } + + private static bool FileExists(Page page, string filePath) + { + // remove query string for the file exists check, won't impact the absoluteness, so just do it either way. + filePath = RemoveQueryString(filePath); + var cacheKey = filePath.ToLowerInvariant(); + + // cache css file paths + if (!_fileExistsCache.ContainsKey(cacheKey)) + { + // appply lock after IF, locking is more expensive than worst case scenario (check disk twice) + _lockFileExistsCache.EnterWriteLock(); + try + { + _fileExistsCache[cacheKey] = IsAbsoluteUrl(filePath) || File.Exists(page.Server.MapPath(filePath)); + } + finally + { + _lockFileExistsCache.ExitWriteLock(); + } + } + + // return if file exists from cache + _lockFileExistsCache.EnterReadLock(); + try + { + return _fileExistsCache[cacheKey]; + } + finally + { + _lockFileExistsCache.ExitReadLock(); + } + } + + private static bool IsAbsoluteUrl(string url) + { + Uri result; + return Uri.TryCreate(url, UriKind.Absolute, out result); + } + + private static string RemoveQueryString(string filePath) + { + var queryStringPosition = filePath.IndexOf("?", StringComparison.Ordinal); + return queryStringPosition != -1 ? filePath.Substring(0, queryStringPosition) : filePath; + } public static void RegisterAdminStylesheet(Page page, string filePath) { @@ -243,7 +235,7 @@ public static void RegisterIEStylesheet(Page page, string filePath) } /// - /// Requests that a JavaScript file be registered on the client browser + /// Requests that a JavaScript file be registered on the client browser. /// /// The current page. Used to get a reference to the client resource loader. /// The relative file path to the JavaScript resource. @@ -253,7 +245,7 @@ public static void RegisterScript(Page page, string filePath) } /// - /// Requests that a JavaScript file be registered on the client browser + /// Requests that a JavaScript file be registered on the client browser. /// /// The current page. Used to get a reference to the client resource loader. /// The relative file path to the JavaScript resource. @@ -264,7 +256,7 @@ public static void RegisterScript(Page page, string filePath, int priority) } /// - /// Requests that a JavaScript file be registered on the client browser + /// Requests that a JavaScript file be registered on the client browser. /// /// The current page. Used to get a reference to the client resource loader. /// The relative file path to the JavaScript resource. @@ -275,7 +267,7 @@ public static void RegisterScript(Page page, string filePath, FileOrder.Js prior } /// - /// Requests that a JavaScript file be registered on the client browser + /// Requests that a JavaScript file be registered on the client browser. /// /// The current page. Used to get a reference to the client resource loader. /// The relative file path to the JavaScript resource. @@ -287,7 +279,7 @@ public static void RegisterScript(Page page, string filePath, FileOrder.Js prior } /// - /// Requests that a JavaScript file be registered on the client browser + /// Requests that a JavaScript file be registered on the client browser. /// /// The current page. Used to get a reference to the client resource loader. /// The relative file path to the JavaScript resource. @@ -295,18 +287,18 @@ public static void RegisterScript(Page page, string filePath, FileOrder.Js prior /// The name of the provider responsible for rendering the script output. public static void RegisterScript(Page page, string filePath, int priority, string provider) { - RegisterScript(page, filePath, priority, provider, "", ""); + RegisterScript(page, filePath, priority, provider, string.Empty, string.Empty); } /// - /// Requests that a JavaScript file be registered on the client browser + /// Requests that a JavaScript file be registered on the client browser. /// /// The current page. Used to get a reference to the client resource loader. /// The relative file path to the JavaScript resource. /// The relative priority in which the file should be loaded. /// The name of the provider responsible for rendering the script output. - /// Name of framework like Bootstrap, Angular, etc - /// Version nr of framework + /// Name of framework like Bootstrap, Angular, etc. + /// Version nr of framework. public static void RegisterScript(Page page, string filePath, int priority, string provider, string name, string version) { var include = new DnnJsInclude { ForceProvider = provider, Priority = priority, FilePath = filePath, Name = name, Version = version }; @@ -318,7 +310,7 @@ public static void RegisterScript(Page page, string filePath, int priority, stri } /// - /// Requests that a CSS file be registered on the client browser + /// Requests that a CSS file be registered on the client browser. /// /// The current page. Used to get a reference to the client resource loader. /// The relative file path to the CSS resource. @@ -358,7 +350,7 @@ public static void RegisterStyleSheet(Page page, string filePath, FileOrder.Css /// The provider name to be used to render the css file on the page. public static void RegisterStyleSheet(Page page, string filePath, int priority, string provider) { - RegisterStyleSheet(page, filePath, priority, provider, "", ""); + RegisterStyleSheet(page, filePath, priority, provider, string.Empty, string.Empty); } /// @@ -368,8 +360,8 @@ public static void RegisterStyleSheet(Page page, string filePath, int priority, /// The relative file path to the CSS resource. /// The relative priority in which the file should be loaded. /// The provider name to be used to render the css file on the page. - /// Name of framework like Bootstrap, Angular, etc - /// Version nr of framework + /// Name of framework like Bootstrap, Angular, etc. + /// Version nr of framework. public static void RegisterStyleSheet(Page page, string filePath, int priority, string provider, string name, string version) { var fileExists = false; @@ -408,7 +400,6 @@ public static void RegisterStyleSheet(Page page, string filePath, int priority, [Obsolete("This method is not required anymore. The CRM vesion is now managed in host settings and site settings.. Scheduled removal in v11.0.0.")] public static void UpdateVersion() { - } /// @@ -435,7 +426,6 @@ public static void ClearCache() { Logger.Error(ex); } - } } @@ -465,9 +455,6 @@ public static void EnableAsyncPostBackHandler() { HttpContext.Current.Items.Add("AsyncPostBackHandlerEnabled", true); } - } - - #endregion - + } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs index 83910f0eba4..23a4d344f1d 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client { using System; @@ -28,6 +28,9 @@ public class ClientResourceSettings private static readonly Type _hostControllerType; private static readonly Type _commonGlobalsType; + private bool _statusChecked; + private UpgradeStatus _status; + static ClientResourceSettings() { try @@ -40,15 +43,44 @@ static ClientResourceSettings() } catch (Exception) { - //ignore + // ignore } } + private enum UpgradeStatus + { + /// + /// The application need update to a higher version. + /// + Upgrade, + + /// + /// The application need to install itself. + /// + Install, + + /// + /// The application is normal running. + /// + None, + + /// + /// The application occur error when running. + /// + Error, + + /// + /// The application status is unknown, + /// + /// This status should never be returned. its is only used as a flag that Status hasn't been determined. + Unknown, + } + /// - /// + /// /// /// - public Boolean IsOverridingDefaultSettingsEnabled() + public bool IsOverridingDefaultSettingsEnabled() { var portalVersion = GetIntegerSetting(PortalSettingsDictionaryKey, VersionKey); var overrideDefaultSettings = GetBooleanSetting(PortalSettingsDictionaryKey, OverrideDefaultSettingsKey); @@ -66,12 +98,16 @@ public Boolean IsOverridingDefaultSettingsEnabled() // if portal version is set // and the portal "override default settings" flag is set and set to true if (portalVersion.HasValue && overrideDefaultSettings.HasValue && overrideDefaultSettings.Value) + { return portalVersion.Value; + } // otherwise return the host setting var hostVersion = GetIntegerSetting(HostSettingsDictionaryKey, VersionKey); if (hostVersion.HasValue) + { return hostVersion.Value; + } // otherwise tell the calling method that nothing is set return null; @@ -79,41 +115,17 @@ public Boolean IsOverridingDefaultSettingsEnabled() public bool? AreCompositeFilesEnabled() { - return IsBooleanSettingEnabled(EnableCompositeFilesKey); + return this.IsBooleanSettingEnabled(EnableCompositeFilesKey); } public bool? EnableCssMinification() { - return IsBooleanSettingEnabled(MinifyCssKey); + return this.IsBooleanSettingEnabled(MinifyCssKey); } public bool? EnableJsMinification() { - return IsBooleanSettingEnabled(MinifyJsKey); - } - - private bool? IsBooleanSettingEnabled(string settingKey) - { - if (Status != UpgradeStatus.None) - { - return false; - } - - var portalEnabled = GetBooleanSetting(PortalSettingsDictionaryKey, settingKey); - var overrideDefaultSettings = GetBooleanSetting(PortalSettingsDictionaryKey, OverrideDefaultSettingsKey); - - // if portal version is set - // and the portal "override default settings" flag is set and set to true - if (portalEnabled.HasValue && overrideDefaultSettings.HasValue && overrideDefaultSettings.Value) - return portalEnabled.Value; - - // otherwise return the host setting - var hostEnabled = GetBooleanSetting(HostSettingsDictionaryKey, settingKey); - if (hostEnabled.HasValue) - return hostEnabled.Value; - - // otherwise tell the calling method that nothing is set - return null; + return this.IsBooleanSettingEnabled(MinifyJsKey); } private static bool? GetBooleanSetting(string dictionaryKey, string settingKey) @@ -124,6 +136,7 @@ public Boolean IsOverridingDefaultSettingsEnabled() { return result; } + return null; } @@ -138,6 +151,35 @@ public Boolean IsOverridingDefaultSettingsEnabled() return version; } } + + return null; + } + + private bool? IsBooleanSettingEnabled(string settingKey) + { + if (this.Status != UpgradeStatus.None) + { + return false; + } + + var portalEnabled = GetBooleanSetting(PortalSettingsDictionaryKey, settingKey); + var overrideDefaultSettings = GetBooleanSetting(PortalSettingsDictionaryKey, OverrideDefaultSettingsKey); + + // if portal version is set + // and the portal "override default settings" flag is set and set to true + if (portalEnabled.HasValue && overrideDefaultSettings.HasValue && overrideDefaultSettings.Value) + { + return portalEnabled.Value; + } + + // otherwise return the host setting + var hostEnabled = GetBooleanSetting(HostSettingsDictionaryKey, settingKey); + if (hostEnabled.HasValue) + { + return hostEnabled.Value; + } + + // otherwise tell the calling method that nothing is set return null; } @@ -148,7 +190,9 @@ private static string GetSetting(string dictionaryKey, string settingKey) if (settings == null) { if (dictionaryKey == HostSettingsDictionaryKey) + { return GetHostSettingThroughReflection(settingKey); + } return GetPortalSettingThroughReflection(settingKey); } @@ -182,8 +226,9 @@ private static string GetPortalSettingThroughReflection(string settingKey) } catch (Exception) { - //ignore + // ignore } + return null; } @@ -201,8 +246,9 @@ private static string GetPortalSettingThroughReflection(string settingKey) } catch (Exception) { - //ignore + // ignore } + return null; } @@ -222,25 +268,23 @@ private static string GetHostSettingThroughReflection(string settingKey) } catch (Exception) { - //ignore + // ignore } + return null; } - private bool _statusChecked; - private UpgradeStatus _status; - private UpgradeStatus Status { get { - if (!_statusChecked) + if (!this._statusChecked) { - _status = GetStatusByReflection(); - _statusChecked = true; + this._status = this.GetStatusByReflection(); + this._statusChecked = true; } - return _status; + return this._status; } } @@ -257,30 +301,5 @@ private UpgradeStatus GetStatusByReflection() return UpgradeStatus.Unknown; } } - - private enum UpgradeStatus - { - /// - /// The application need update to a higher version. - /// - Upgrade, - /// - /// The application need to install itself. - /// - Install, - /// - /// The application is normal running. - /// - None, - /// - /// The application occur error when running. - /// - Error, - /// - /// The application status is unknown, - /// - /// This status should never be returned. its is only used as a flag that Status hasn't been determined. - Unknown - } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs index a5669a39aee..8747a833d4e 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using ClientDependency.Core; -using ClientDependency.Core.Controls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.Controls { + using System; + using System.Web.UI; + + using ClientDependency.Core; + using ClientDependency.Core.Controls; + public abstract class ClientResourceExclude : Control { - public string Name { get; set; } public ClientDependencyType DependencyType { get; internal set; } @@ -19,23 +19,24 @@ public abstract class ClientResourceExclude : Control protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - var loader = Page.FindControl("ClientResourceIncludes"); - Name = Name.ToLowerInvariant(); + var loader = this.Page.FindControl("ClientResourceIncludes"); + this.Name = this.Name.ToLowerInvariant(); if (loader != null) { ClientDependencyInclude ctlToRemove = null; - if (!String.IsNullOrEmpty(Name)) + if (!string.IsNullOrEmpty(this.Name)) { foreach (ClientDependencyInclude ctl in loader.Controls) { - if (ctl.Name.ToLowerInvariant() == Name && ctl.DependencyType == DependencyType) + if (ctl.Name.ToLowerInvariant() == this.Name && ctl.DependencyType == this.DependencyType) { ctlToRemove = ctl; break; } } } + if (ctlToRemove != null) { loader.Controls.Remove(ctlToRemove); diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs index 83bf6958f28..d2036591ead 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { using ClientDependency.Core.Controls; /// - /// Represents an included client resource + /// Represents an included client resource. /// public class ClientResourceInclude : ClientDependencyInclude { diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceLoader.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceLoader.cs index f870e7ce2db..6e992c35509 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceLoader.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceLoader.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { + using System; + using System.Web; + using System.Web.UI; + using ClientDependency.Core.Controls; - + /// /// The central control with which all client resources are registered. /// public class ClientResourceLoader : ClientDependencyLoader { - private bool AsyncPostBackHandlerEnabled + private bool AsyncPostBackHandlerEnabled { get { @@ -26,12 +26,12 @@ private bool AsyncPostBackHandlerEnabled protected override void OnPreRender(System.EventArgs e) { - foreach (var path in Paths) + foreach (var path in this.Paths) { path.Name = path.Name.ToLowerInvariant(); } - if (AsyncPostBackHandlerEnabled) + if (this.AsyncPostBackHandlerEnabled) { const string handlerScript = @" var loadScriptInSingleMode = function(){ @@ -131,7 +131,7 @@ protected override void OnPreRender(System.EventArgs e) }; }(jQuery)); "; - Page.ClientScript.RegisterStartupScript(this.GetType(), "CRMHandler", handlerScript, true); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "CRMHandler", handlerScript, true); } base.OnPreRender(e); diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs index 12a1d358c4f..93686ebd08a 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { using ClientDependency.Core.Controls; /// - /// Defines the path to a client resource + /// Defines the path to a client resource. /// public class ClientResourcePath : ClientDependencyPath { diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs index 0311c4cfa30..73ac80e7d1d 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { using ClientDependency.Core.Controls; diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssExclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssExclude.cs index c043c60f2b1..87338376f0f 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssExclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssExclude.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Client.Controls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { + using DotNetNuke.Web.Client.Controls; + public class DnnCssExclude : ClientResourceExclude { public DnnCssExclude() { - DependencyType = ClientDependency.Core.ClientDependencyType.Css; + this.DependencyType = ClientDependency.Core.ClientDependencyType.Css; } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssInclude.cs index f8b0735690f..c92223f1afa 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnCssInclude.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { + using System.Web.UI; + using ClientDependency.Core.Controls; - + /// - /// Registers a CSS resource + /// Registers a CSS resource. /// public class DnnCssInclude : CssInclude { public DnnCssInclude() { - ForceProvider = ClientResourceManager.DefaultCssProvider; + this.ForceProvider = ClientResourceManager.DefaultCssProvider; } protected override void OnLoad(System.EventArgs e) @@ -27,9 +27,9 @@ protected override void OnLoad(System.EventArgs e) protected override void Render(HtmlTextWriter writer) { - if (AddTag || Context.IsDebuggingEnabled) + if (this.AddTag || this.Context.IsDebuggingEnabled) { - writer.Write("", DependencyType, FilePath, ForceProvider, Priority); + writer.Write("", this.DependencyType, this.FilePath, this.ForceProvider, this.Priority); } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs index 16a0a5e80a4..78aecdeb8ec 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { using ClientDependency.Core.Controls; /// - /// Allows for registration of CSS and JavaScript resources + /// Allows for registration of CSS and JavaScript resources. /// public class DnnHtmlInclude : HtmlInclude { diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsExclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsExclude.cs index 9967468fd22..3140b7c4a1e 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsExclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsExclude.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Client.Controls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { + using DotNetNuke.Web.Client.Controls; + public class DnnJsExclude : ClientResourceExclude { public DnnJsExclude() { - DependencyType = ClientDependency.Core.ClientDependencyType.Javascript; + this.DependencyType = ClientDependency.Core.ClientDependencyType.Javascript; } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs index 60ff5fa6f9c..a83223b20a6 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { + using System.Web.UI; + using ClientDependency.Core.Controls; - + /// - /// Registers a JavaScript resource + /// Registers a JavaScript resource. /// public class DnnJsInclude : JsInclude - { - /// - /// Sets up default settings for the control + { + /// + /// Initializes a new instance of the class. + /// Sets up default settings for the control. /// public DnnJsInclude() { - ForceProvider = ClientResourceManager.DefaultJsProvider; + this.ForceProvider = ClientResourceManager.DefaultJsProvider; } protected override void OnLoad(System.EventArgs e) @@ -30,9 +31,9 @@ protected override void OnLoad(System.EventArgs e) protected override void Render(HtmlTextWriter writer) { - if (AddTag || Context.IsDebuggingEnabled) + if (this.AddTag || this.Context.IsDebuggingEnabled) { - writer.Write("", DependencyType, FilePath, ForceProvider, Priority); + writer.Write("", this.DependencyType, this.FilePath, this.ForceProvider, this.Priority); } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs index 7e4c12ce90f..94866edcad3 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs @@ -1,46 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; -using System.Web.UI.WebControls; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Client.ClientResourceManagement { + using System.Web.UI; + using System.Web.UI.WebControls; + /// - /// Emit a fallback block for a script in the same part of the page + /// Emit a fallback block for a script in the same part of the page. /// public class DnnJsIncludeFallback : WebControl { - public DnnJsIncludeFallback(string objectName, string fileName) { - ObjectName = objectName; - FileName = fileName; + this.ObjectName = objectName; + this.FileName = fileName; } public string ObjectName { get; set; } + public string FileName { get; set; } - - + public override void RenderControl(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); writer.RenderBeginTag(HtmlTextWriterTag.Script); - if (ObjectName.Contains(".")) + if (this.ObjectName.Contains(".")) { - //generate function check - writer.Write("if (typeof " + ObjectName + " != 'function') {"); + // generate function check + writer.Write("if (typeof " + this.ObjectName + " != 'function') {"); } else { - //generate object check - writer.Write("if (typeof " + ObjectName + " == 'undefined') {"); + // generate object check + writer.Write("if (typeof " + this.ObjectName + " == 'undefined') {"); } - writer.Write("document.write('"; - Page.ClientScript.RegisterClientScriptBlock(GetType(), "DnnFormNumericTextBoxItem", initalizeScript); + var initalizeScript = ""; + this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DnnFormNumericTextBoxItem", initalizeScript); - return _textBox; + return this._textBox; } protected override void OnInit(EventArgs e) { base.OnInit(e); - FormMode = DnnFormMode.Short; + this.FormMode = DnnFormMode.Short; + } + + private void TextChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this._textBox.Text, this.DataField); } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormPagesItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormPagesItem.cs index 67677e7001d..7f48243edff 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormPagesItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormPagesItem.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + public class DnnFormPagesItem : DnnFormComboBoxItem { public DnnFormPagesItem() { - ListSource = TabController.GetPortalTabs(PortalSettings.PortalId, Null.NullInteger, true, "<" + Localization.GetString("None_Specified") + ">", true, false, true, true, false); - ListTextField = "TabName"; - ListValueField = "TabID"; + this.ListSource = TabController.GetPortalTabs(this.PortalSettings.PortalId, Null.NullInteger, true, "<" + Localization.GetString("None_Specified") + ">", true, false, true, true, false); + this.ListTextField = "TabName"; + this.ListValueField = "TabID"; } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs index 1bab38590ec..74b67e78fe3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs @@ -1,28 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.UI.Skins; + public class DnnFormSkinsItem : DnnFormItemBase { - //private DropDownList _containerCombo; + // private DropDownList _containerCombo; private DnnComboBox _containerCombo; private object _containerValue; - //private DropDownList _skinCombo; + + // private DropDownList _skinCombo; private DnnComboBox _skinCombo; private object _skinValue; @@ -34,84 +30,85 @@ public class DnnFormSkinsItem : DnnFormItemBase public string SkinDataField { get; set; } - private void ContainerIndexChanged(object sender, EventArgs e) - { - UpdateDataSource(_containerValue, _containerCombo.SelectedValue, ContainerDataField); - } - - private void SkinIndexChanged(object sender, EventArgs e) - { - UpdateDataSource(_skinValue, _skinCombo.SelectedValue, SkinDataField); - } - - private Dictionary GetSkins(string skinRoot) - { - // load host skins - var skins = SkinController.GetSkins(null, skinRoot, SkinScope.Host).ToDictionary(skin => skin.Key, skin => skin.Value); - - if (IncludePortalSkins) - { - // load portal skins - var portal = PortalController.Instance.GetPortal(PortalId); - - foreach (var skin in SkinController.GetSkins(portal, skinRoot, SkinScope.Site)) - { - skins.Add(skin.Key, skin.Value); - } - } - return skins; - } - protected override WebControl CreateControlInternal(Control container) { var panel = new Panel(); container.Controls.Add(panel); - var skinLabel = new Label { Text = LocalizeString("Skin") }; + var skinLabel = new Label { Text = this.LocalizeString("Skin") }; skinLabel.CssClass += "dnnFormSkinLabel"; panel.Controls.Add(skinLabel); - //_skinCombo = new DropDownList { ID = ID + "_SkinComboBox" }; - _skinCombo = new DnnComboBox { ID = ID + "_SkinComboBox" }; - _skinCombo.CssClass += "dnnFormSkinInput"; - _skinCombo.SelectedIndexChanged += SkinIndexChanged; - panel.Controls.Add(_skinCombo); + // _skinCombo = new DropDownList { ID = ID + "_SkinComboBox" }; + this._skinCombo = new DnnComboBox { ID = this.ID + "_SkinComboBox" }; + this._skinCombo.CssClass += "dnnFormSkinInput"; + this._skinCombo.SelectedIndexChanged += this.SkinIndexChanged; + panel.Controls.Add(this._skinCombo); - DnnFormComboBoxItem.BindListInternal(_skinCombo, _skinValue, GetSkins(SkinController.RootSkin), "Key", "Value"); + DnnFormComboBoxItem.BindListInternal(this._skinCombo, this._skinValue, this.GetSkins(SkinController.RootSkin), "Key", "Value"); - var containerLabel = new Label { Text = LocalizeString("Container") }; + var containerLabel = new Label { Text = this.LocalizeString("Container") }; containerLabel.CssClass += "dnnFormSkinLabel"; panel.Controls.Add(containerLabel); - //_containerCombo = new DropDownList { ID = ID + "_ContainerComboBox" }; - _containerCombo = new DnnComboBox { ID = ID + "_ContainerComboBox" }; - _containerCombo.CssClass += "dnnFormSkinInput"; - _containerCombo.SelectedIndexChanged += ContainerIndexChanged; - panel.Controls.Add(_containerCombo); + // _containerCombo = new DropDownList { ID = ID + "_ContainerComboBox" }; + this._containerCombo = new DnnComboBox { ID = this.ID + "_ContainerComboBox" }; + this._containerCombo.CssClass += "dnnFormSkinInput"; + this._containerCombo.SelectedIndexChanged += this.ContainerIndexChanged; + panel.Controls.Add(this._containerCombo); - DnnFormComboBoxItem.BindListInternal(_containerCombo, _containerValue, GetSkins(SkinController.RootContainer), "Key", "Value"); + DnnFormComboBoxItem.BindListInternal(this._containerCombo, this._containerValue, this.GetSkins(SkinController.RootContainer), "Key", "Value"); return panel; } protected override void DataBindInternal() { - DataBindInternal(SkinDataField, ref _skinValue); + this.DataBindInternal(this.SkinDataField, ref this._skinValue); + + this.DataBindInternal(this.ContainerDataField, ref this._containerValue); + + this.Value = new Pair { First = this._skinValue, Second = this._containerValue }; + } + + private void ContainerIndexChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this._containerValue, this._containerCombo.SelectedValue, this.ContainerDataField); + } + + private void SkinIndexChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this._skinValue, this._skinCombo.SelectedValue, this.SkinDataField); + } + + private Dictionary GetSkins(string skinRoot) + { + // load host skins + var skins = SkinController.GetSkins(null, skinRoot, SkinScope.Host).ToDictionary(skin => skin.Key, skin => skin.Value); - DataBindInternal(ContainerDataField, ref _containerValue); + if (this.IncludePortalSkins) + { + // load portal skins + var portal = PortalController.Instance.GetPortal(this.PortalId); - Value = new Pair {First = _skinValue, Second = _containerValue}; + foreach (var skin in SkinController.GetSkins(portal, skinRoot, SkinScope.Site)) + { + skins.Add(skin.Key, skin.Value); + } + } + + return skins; } protected override void LoadControlState(object state) { base.LoadControlState(state); - var pair = Value as Pair; + var pair = this.Value as Pair; if (pair != null) { - _skinValue = pair.First; - _containerValue = pair.Second; + this._skinValue = pair.First; + this._containerValue = pair.Second; } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs index 66a178aa111..5411f9222b5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs @@ -1,95 +1,89 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using Telerik.Web.UI; + public class DnnFormToggleButtonItem : DnnFormItemBase - { - #region CheckBoxMode enum - - public enum CheckBoxMode - { - TrueFalse = 0, - YN = 1, - YesNo = 2 - } - - #endregion - - //private DnnRadButton _checkBox; + { + // private DnnRadButton _checkBox; private CheckBox _checkBox; public DnnFormToggleButtonItem() { - Mode = CheckBoxMode.TrueFalse; + this.Mode = CheckBoxMode.TrueFalse; } + + public enum CheckBoxMode + { + TrueFalse = 0, + YN = 1, + YesNo = 2, + } public CheckBoxMode Mode { get; set; } - private void CheckedChanged(object sender, EventArgs e) - { - string newValue; - switch (Mode) - { - case CheckBoxMode.YN: - newValue = (_checkBox.Checked) ? "Y" : "N"; - break; - case CheckBoxMode.YesNo: - newValue = (_checkBox.Checked) ? "Yes" : "No"; - break; - default: - newValue = (_checkBox.Checked) ? "true" : "false"; - break; - } - UpdateDataSource(Value, newValue, DataField); - } - protected override WebControl CreateControlInternal(Control container) { - //_checkBox = new DnnRadButton {ID = ID + "_CheckBox", ButtonType = RadButtonType.ToggleButton, ToggleType = ButtonToggleType.CheckBox, AutoPostBack = false}; - _checkBox = new CheckBox{ ID = ID + "_CheckBox", AutoPostBack = false }; + // _checkBox = new DnnRadButton {ID = ID + "_CheckBox", ButtonType = RadButtonType.ToggleButton, ToggleType = ButtonToggleType.CheckBox, AutoPostBack = false}; + this._checkBox = new CheckBox { ID = this.ID + "_CheckBox", AutoPostBack = false }; - _checkBox.CheckedChanged += CheckedChanged; - container.Controls.Add(_checkBox); + this._checkBox.CheckedChanged += this.CheckedChanged; + container.Controls.Add(this._checkBox); - //Load from ControlState - if (!_checkBox.Page.IsPostBack) + // Load from ControlState + if (!this._checkBox.Page.IsPostBack) { } - switch (Mode) + + switch (this.Mode) { case CheckBoxMode.YN: case CheckBoxMode.YesNo: - var stringValue = Value as string; + var stringValue = this.Value as string; if (stringValue != null) { - _checkBox.Checked = stringValue.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase); + this._checkBox.Checked = stringValue.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase); } + break; default: - _checkBox.Checked = Convert.ToBoolean(Value); + this._checkBox.Checked = Convert.ToBoolean(this.Value); break; } - return _checkBox; + return this._checkBox; } protected override void OnInit(EventArgs e) { base.OnInit(e); - FormMode = DnnFormMode.Short; + this.FormMode = DnnFormMode.Short; + } + + private void CheckedChanged(object sender, EventArgs e) + { + string newValue; + switch (this.Mode) + { + case CheckBoxMode.YN: + newValue = this._checkBox.Checked ? "Y" : "N"; + break; + case CheckBoxMode.YesNo: + newValue = this._checkBox.Checked ? "Yes" : "No"; + break; + default: + newValue = this._checkBox.Checked ? "true" : "false"; + break; + } + + this.UpdateDataSource(this.Value, newValue, this.DataField); } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs index 25cc1fd6371..5f10635351a 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs @@ -1,70 +1,61 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.Framework; - -#endregion - -#region Usings - -using DotNetNuke.Framework.JavaScriptLibraries; -using Telerik.Web.UI; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGrid : RadGrid - { - - #region public properties - + { public int ScreenRowNumber { get; set; } - public int RowHeight { get; set; } - - #endregion + public int RowHeight { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); - base.EnableEmbeddedBaseStylesheet = false; + this.EnableEmbeddedBaseStylesheet = false; Utilities.ApplySkin(this); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - if (string.IsNullOrEmpty(ClientSettings.ClientEvents.OnGridCreated)) + if (string.IsNullOrEmpty(this.ClientSettings.ClientEvents.OnGridCreated)) { - ClientSettings.ClientEvents.OnGridCreated = "$.dnnGridCreated"; + this.ClientSettings.ClientEvents.OnGridCreated = "$.dnnGridCreated"; } - this.PreRender += new EventHandler(DnnGrid_PreRender); + this.PreRender += new EventHandler(this.DnnGrid_PreRender); this.MasterTableView.NoMasterRecordsText = Localization.GetString("NoRecords", Localization.SharedResourceFile); } - void DnnGrid_PreRender(object sender, EventArgs e) + private void DnnGrid_PreRender(object sender, EventArgs e) { var items = this.MasterTableView.Items; - if (ScreenRowNumber == 0) - ScreenRowNumber = 15; - - if (items.Count > ScreenRowNumber) + if (this.ScreenRowNumber == 0) + { + this.ScreenRowNumber = 15; + } + + if (items.Count > this.ScreenRowNumber) { // need scroll this.ClientSettings.Scrolling.AllowScroll = true; this.ClientSettings.Scrolling.UseStaticHeaders = true; - if(RowHeight == 0) - RowHeight = 25; - - this.ClientSettings.Scrolling.ScrollHeight = RowHeight * ScreenRowNumber; + if (this.RowHeight == 0) + { + this.RowHeight = 25; + } + + this.ClientSettings.Scrolling.ScrollHeight = this.RowHeight * this.ScreenRowNumber; } else { - this.ClientSettings.Scrolling.AllowScroll = false; + this.ClientSettings.Scrolling.AllowScroll = false; } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs index 29491fa8ad6..057142e930a 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridGroupSplitterColumn : GridGroupSplitterColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridGroupSplitterColumn dnnGridColumn = new DnnGridGroupSplitterColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs index d72b551b099..bc630b2c86e 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridBinaryImageColumn : GridBinaryImageColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridBinaryImageColumn dnnGridColumn = new DnnGridBinaryImageColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs index be074daf2cb..b4c608a18a3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridBoundColumn : GridBoundColumn - { - #region "Public Properties" - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region "Public Methods" - + } + public override GridColumn Clone() { DnnGridBoundColumn dnnGridColumn = new DnnGridBoundColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,22 +32,20 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { GridHeaderItem headerItem = inItem as GridHeaderItem; - string columnName = DataField; - if (!Owner.AllowSorting) + string columnName = this.DataField; + if (!this.Owner.AllowSorting) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } else { - LinkButton button = (LinkButton) headerItem[columnName].Controls[0]; - button.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + LinkButton button = (LinkButton)headerItem[columnName].Controls[0]; + button.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs index 0c385e1d4dc..6afbcd27d7f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs @@ -1,94 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridButtonColumn : GridButtonColumn - { - #region "Public Properties" - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region "Public Methods" - - public override GridColumn Clone() - { - DnnGridButtonColumn dnnGridColumn = new DnnGridButtonColumn(); - - //you should override CopyBaseProperties if you have some column specific properties - dnnGridColumn.CopyBaseProperties(this); - - return dnnGridColumn; - } - - public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) - { - base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) - { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); - } - } + } /// ----------------------------------------------------------------------------- /// - /// The Icon Key to obtain ImageURL + /// Gets or sets the Icon Key to obtain ImageURL. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconKey { get; set; } /// ----------------------------------------------------------------------------- /// - /// The Icon Siz to obtain ImageURL + /// Gets or sets the Icon Siz to obtain ImageURL. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconSize { get; set; } /// ----------------------------------------------------------------------------- /// - /// The Icon Style to obtain ImageURL + /// Gets or sets the Icon Style to obtain ImageURL. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconStyle { get; set; } + + public override GridColumn Clone() + { + DnnGridButtonColumn dnnGridColumn = new DnnGridButtonColumn(); + + // you should override CopyBaseProperties if you have some column specific properties + dnnGridColumn.CopyBaseProperties(this); + + return dnnGridColumn; + } + + public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) + { + base.InitializeCell(cell, columnIndex, inItem); + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) + { + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); + } + } public override string ImageUrl { get { - if (string.IsNullOrEmpty(base.ImageUrl)) - base.ImageUrl = Entities.Icons.IconController.IconURL(IconKey, IconSize, IconStyle); - + if (string.IsNullOrEmpty(base.ImageUrl)) + { + base.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); + } + return base.ImageUrl; } + set { base.ImageUrl = value; } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs index 0b6b08d1204..9d39b4ca502 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridCalculatedColumn : GridCalculatedColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridCalculatedColumn dnnGridColumn = new DnnGridCalculatedColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs index d5d720e53f7..f125bdf09b2 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridCheckBoxColumn : GridCheckBoxColumn - { - #region "Public Properties" - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region "Public Methods" - + } + public override GridColumn Clone() { DnnGridCheckBoxColumn dnnGridColumn = new DnnGridCheckBoxColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs index 2ceb3c99fea..69b4bcedaf4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridClientSelectColumn : GridClientSelectColumn - { - #region "Public Properties" - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region "Public Methods" - + } + public override GridColumn Clone() { var dnnGridColumn = new DnnGridClientSelectColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,15 +32,13 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - if (! inItem.OwnerTableView.OwnerGrid.AllowMultiRowSelection) + if (!inItem.OwnerTableView.OwnerGrid.AllowMultiRowSelection) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs index e7399827e1d..c6ab0371be5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs @@ -1,70 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridColumn : GridColumn - { - #region Public Properties - + { + private string _HeaderText; + public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - - public override GridColumn Clone() - { - var dnnGridColumn = new DnnGridColumn(); - dnnGridColumn.CopyBaseProperties(this); - dnnGridColumn.setHeaderText = HeaderText; - return dnnGridColumn; - } - - private String _HeaderText; + } public override string HeaderText { get { - if (String.IsNullOrEmpty(base.HeaderText)) - base.HeaderText = Localization.GetString(string.Format("{0}.Header", _HeaderText), DotNetNuke.Web.UI.Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent)); + if (string.IsNullOrEmpty(base.HeaderText)) + { + base.HeaderText = Localization.GetString(string.Format("{0}.Header", this._HeaderText), DotNetNuke.Web.UI.Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent)); + } + return base.HeaderText; } + set { - _HeaderText = value; - base.HeaderText = ""; + this._HeaderText = value; + base.HeaderText = string.Empty; } } - public String setHeaderText + public string setHeaderText { set { base.HeaderText = value; } + } + + public override GridColumn Clone() + { + var dnnGridColumn = new DnnGridColumn(); + dnnGridColumn.CopyBaseProperties(this); + dnnGridColumn.setHeaderText = this.HeaderText; + return dnnGridColumn; } - - - #endregion } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs index b76339f4396..2a5856e4c8f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs @@ -1,22 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnGridDataItem : GridDataItem { - public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) : base(ownerTableView, itemIndex, dataSetIndex) + public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) + : base(ownerTableView, itemIndex, dataSetIndex) { } - public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) : base(ownerTableView, itemIndex, dataSetIndex, itemType) + public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) + : base(ownerTableView, itemIndex, dataSetIndex, itemType) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs index 7edfd6b57a9..d3edd19bad2 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridDateTimeColumn : GridDateTimeColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridDateTimeColumn dnnGridColumn = new DnnGridDateTimeColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs index 028e0f4fae5..73fd7c2d0cd 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridDropDownColumn : GridDropDownColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridDropDownColumn dnnGridColumn = new DnnGridDropDownColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs index 9d797e20601..3e43c9ad122 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs @@ -1,41 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnGridEditColumn : GridEditCommandColumn - { - #region "Public Properties" - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region "Public Methods" - + } + public override GridColumn Clone() { DnnGridEditColumn dnnGridColumn = new DnnGridEditColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs index 63a5913b977..c26e1128369 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnGridEditFormSettings : GridEditFormSettings { - public DnnGridEditFormSettings(DnnGridTableView owner) : base(owner) + public DnnGridEditFormSettings(DnnGridTableView owner) + : base(owner) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs index 0b54c460cdc..75833d51aa4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridExpandColumn : GridColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridExpandColumn dnnGridColumn = new DnnGridExpandColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs index d2a95b1a11d..e3247ddbb13 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnGridFooterItem : GridFooterItem { - public DnnGridFooterItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) : base(ownerTableView, itemIndex, dataSetIndex) + public DnnGridFooterItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) + : base(ownerTableView, itemIndex, dataSetIndex) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs index 1fdce3e7f10..6571c9477ed 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridAttachmentColumn : GridAttachmentColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridAttachmentColumn dnnGridColumn = new DnnGridAttachmentColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs index 3882079a743..3db65db9141 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridHTMLEditorColumn : GridHTMLEditorColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridHTMLEditorColumn dnnGridColumn = new DnnGridHTMLEditorColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs index 4abaca83895..45d8781c885 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnGridHeaderItem : GridHeaderItem { - public DnnGridHeaderItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) : base(ownerTableView, itemIndex, dataSetIndex) + public DnnGridHeaderItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) + : base(ownerTableView, itemIndex, dataSetIndex) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs index 5a3c4caa6fb..0706ce503d0 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridHyperLinkColumn : GridHyperLinkColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridHyperLinkColumn dnnGridColumn = new DnnGridHyperLinkColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs index 2f55d0305ea..be88c628b12 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridImageColumn : GridImageColumn - { - #region "Public Properties" - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region "Public Methods" - + } + public override GridColumn Clone() { DnnGridImageColumn dnnGridColumn = new DnnGridImageColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs index 4b64b565849..be0027ae8cf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using System.Web.UI.WebControls; -using DotNetNuke.Entities.Icons; -using DotNetNuke.UI.WebControls; -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.UI.WebControls; + using Telerik.Web.UI; + public class DnnGridImageCommandColumn : DnnGridTemplateColumn { private ImageCommandColumnEditMode _editMode = ImageCommandColumnEditMode.Command; @@ -18,167 +19,157 @@ public class DnnGridImageCommandColumn : DnnGridTemplateColumn private string _imageURL = string.Empty; /// - /// Gets or sets the CommandName for the Column + /// Gets or sets the CommandName for the Column. /// - /// A String + /// A String. public string CommandName { get; set; } - - + /// - /// EditMode for the Column + /// Gets or sets editMode for the Column. /// - /// A String + /// A String. public ImageCommandColumnEditMode EditMode { - get { return _editMode; } - set { _editMode = value; } + get { return this._editMode; } + set { this._editMode = value; } } - - + /// - /// Gets or sets the URL of the Image + /// Gets or sets the URL of the Image. /// - /// A String + /// A String. public string ImageURL { get { - if (!string.IsNullOrEmpty(_imageURL)) + if (!string.IsNullOrEmpty(this._imageURL)) { - return _imageURL; + return this._imageURL; } - return IconController.IconURL(IconKey, IconSize, IconStyle); + return IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); } - set { _imageURL = value; } + + set { this._imageURL = value; } } - - + /// - /// The Icon Key to obtain ImageURL + /// Gets or sets the Icon Key to obtain ImageURL. /// - /// A String + /// A String. public string IconKey { get; set; } - - + /// - /// The Icon Siz to obtain ImageURL + /// Gets or sets the Icon Siz to obtain ImageURL. /// - /// A String + /// A String. public string IconSize { get; set; } - - + /// - /// The Icon Style to obtain ImageURL + /// Gets or sets the Icon Style to obtain ImageURL. /// - /// A String + /// A String. public string IconStyle { get; set; } - - + /// - /// The Key Field that provides a Unique key to the data Item + /// Gets or sets the Key Field that provides a Unique key to the data Item. /// - /// A String + /// A String. public string KeyField { get; set; } - - + /// - /// Gets or sets the URL of the Link (unless DataBinding through KeyField) + /// Gets or sets the URL of the Link (unless DataBinding through KeyField). /// - /// A String + /// A String. public string NavigateURL { get; set; } - - + /// - /// Gets or sets the URL Formatting string + /// Gets or sets the URL Formatting string. /// - /// A String + /// A String. public string NavigateURLFormatString { get; set; } - - + /// - /// Javascript text to attach to the OnClick Event + /// Gets or sets javascript text to attach to the OnClick Event. /// - /// A String + /// A String. public string OnClickJs { get; set; } - - + /// - /// Gets or sets whether an Image is displayed + /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. public bool ShowImage { - get { return _showImage; } - set { _showImage = value; } + get { return this._showImage; } + set { this._showImage = value; } } - - + /// - /// Gets or sets the Text (for Header/Footer Templates) + /// Gets or sets the Text (for Header/Footer Templates). /// - /// A String + /// A String. public string Text { get; set; } - - + /// - /// An flag that indicates whether the buttons are visible. + /// Gets or sets an flag that indicates whether the buttons are visible. /// - /// A Boolean + /// A Boolean. public string VisibleField { get; set; } + /// + /// Initialises the Column. + /// + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(GridItemType.Item); + this.EditItemTemplate = this.CreateTemplate(GridItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(GridItemType.Header); + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } + /// - /// Creates a ImageCommandColumnTemplate + /// Creates a ImageCommandColumnTemplate. /// - /// A ImageCommandColumnTemplate + /// A ImageCommandColumnTemplate. private DnnGridImageCommandColumnTemplate CreateTemplate(GridItemType type) { bool isDesignMode = HttpContext.Current == null; var template = new DnnGridImageCommandColumnTemplate(type); if (type != GridItemType.Header) { - template.ImageURL = ImageURL; + template.ImageURL = this.ImageURL; if (!isDesignMode) { - template.CommandName = CommandName; - template.VisibleField = VisibleField; - template.KeyField = KeyField; + template.CommandName = this.CommandName; + template.VisibleField = this.VisibleField; + template.KeyField = this.KeyField; } } - template.EditMode = EditMode; - template.NavigateURL = NavigateURL; - template.NavigateURLFormatString = NavigateURLFormatString; - template.OnClickJs = OnClickJs; - template.ShowImage = ShowImage; - template.Visible = Visible; + + template.EditMode = this.EditMode; + template.NavigateURL = this.NavigateURL; + template.NavigateURLFormatString = this.NavigateURLFormatString; + template.OnClickJs = this.OnClickJs; + template.ShowImage = this.ShowImage; + template.Visible = this.Visible; - template.Text = type == GridItemType.Header ? HeaderText : Text; + template.Text = type == GridItemType.Header ? this.HeaderText : this.Text; - //Set Design Mode to True + // Set Design Mode to True template.DesignMode = isDesignMode; return template; } - - /// - /// Initialises the Column - /// - public override void Initialize() - { - ItemTemplate = CreateTemplate(GridItemType.Item); - EditItemTemplate = CreateTemplate(GridItemType.EditItem); - HeaderTemplate = CreateTemplate(GridItemType.Header); - - if (HttpContext.Current == null) - { - HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; - HeaderStyle.Font.Size = new FontUnit("10pt"); - HeaderStyle.Font.Bold = true; - } - ItemStyle.HorizontalAlign = HorizontalAlign.Center; - HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs index 7c06ea55b5f..4a86cc60f9f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.UI.Utilities; -using DotNetNuke.UI.WebControls; -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.UI.Utilities; + using DotNetNuke.UI.WebControls; + using Telerik.Web.UI; + public class DnnGridImageCommandColumnTemplate : IBindableTemplate { private ImageCommandColumnEditMode _editMode = ImageCommandColumnEditMode.Command; @@ -28,244 +29,231 @@ public DnnGridImageCommandColumnTemplate() public DnnGridImageCommandColumnTemplate(GridItemType itemType) { - ItemType = itemType; + this.ItemType = itemType; } - - + /// - /// Gets or sets the CommandName for the Column + /// Gets or sets the CommandName for the Column. /// - /// A String + /// A String. public string CommandName { get; set; } - - + /// - /// Gets or sets the Design Mode of the Column + /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. /// - /// A Boolean + /// A Boolean. public bool DesignMode { get; set; } - - + /// - /// Gets or sets the CommandName for the Column + /// Gets or sets the CommandName for the Column. /// - /// A String + /// A String. public ImageCommandColumnEditMode EditMode { - get { return _editMode; } - set { _editMode = value; } + get { return this._editMode; } + set { this._editMode = value; } } - - + /// - /// Gets or sets the URL of the Image + /// Gets or sets the URL of the Image. /// - /// A String + /// A String. public string ImageURL { get; set; } - - + /// - /// The type of Template to Create + /// Gets or sets the type of Template to Create. /// - /// A String + /// A String. public GridItemType ItemType { - get { return _itemType; } - set { _itemType = value; } + get { return this._itemType; } + set { this._itemType = value; } } - - + /// - /// The Key Field that provides a Unique key to the data Item + /// Gets or sets the Key Field that provides a Unique key to the data Item. /// - /// A String + /// A String. public string KeyField { get; set; } - - + /// - /// Gets or sets the URL of the Link (unless DataBinding through KeyField) + /// Gets or sets the URL of the Link (unless DataBinding through KeyField). /// - /// A String + /// A String. public string NavigateURL { get; set; } - - + /// - /// Gets or sets the URL Formatting string + /// Gets or sets the URL Formatting string. /// - /// A String + /// A String. public string NavigateURLFormatString { get; set; } - - + /// - /// Javascript text to attach to the OnClick Event + /// Gets or sets javascript text to attach to the OnClick Event. /// - /// A String + /// A String. public string OnClickJs { get; set; } - - + /// - /// Gets or sets whether an Image is displayed + /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. public bool ShowImage { - get { return _showImage; } - set { _showImage = value; } + get { return this._showImage; } + set { this._showImage = value; } } - - + /// - /// Gets or sets the Text (for Header/Footer Templates) + /// Gets or sets the Text (for Header/Footer Templates). /// - /// A String + /// A String. public string Text { get; set; } - - + /// - /// An flag that indicates whether the buttons are visible (this is overridden if + /// Gets or sets a value indicating whether an flag that indicates whether the buttons are visible (this is overridden if /// the VisibleField is set) - /// changed + /// changed. /// - /// A Boolean + /// A Boolean. public bool Visible { - get { return _visible; } - set { _visible = value; } + get { return this._visible; } + set { this._visible = value; } } - - + /// - /// An flag that indicates whether the buttons are visible. + /// Gets or sets an flag that indicates whether the buttons are visible. /// - /// A Boolean - public string VisibleField { get; set; } - - #region ITemplate Members - + /// A Boolean. + public string VisibleField { get; set; } + /// - /// InstantiateIn instantiates the template (implementation of ITemplate) + /// InstantiateIn instantiates the template (implementation of ITemplate). /// /// /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). public void InstantiateIn(Control container) { - switch (ItemType) + switch (this.ItemType) { case GridItemType.Item: case GridItemType.AlternatingItem: case GridItemType.SelectedItem: case GridItemType.EditItem: - if (EditMode == ImageCommandColumnEditMode.URL) + if (this.EditMode == ImageCommandColumnEditMode.URL) { - var hypLink = new HyperLink {ToolTip = Text}; - if (!String.IsNullOrEmpty(ImageURL) && ShowImage) + var hypLink = new HyperLink { ToolTip = this.Text }; + if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { - var img = new Image {ImageUrl = DesignMode ? ImageURL.Replace("~/", "../../") : ImageURL}; + var img = new Image { ImageUrl = this.DesignMode ? this.ImageURL.Replace("~/", "../../") : this.ImageURL }; hypLink.Controls.Add(img); - img.ToolTip = Text; + img.ToolTip = this.Text; } else { - hypLink.Text = Text; + hypLink.Text = this.Text; } - hypLink.DataBinding += ItemDataBinding; + + hypLink.DataBinding += this.ItemDataBinding; container.Controls.Add(hypLink); } else { - if (!String.IsNullOrEmpty(ImageURL) && ShowImage) + if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { - var colIcon = new ImageButton - {ImageUrl = DesignMode ? ImageURL.Replace("~/", "../../") : ImageURL, ToolTip = Text}; - if (!String.IsNullOrEmpty(OnClickJs)) + var colIcon = new ImageButton + { ImageUrl = this.DesignMode ? this.ImageURL.Replace("~/", "../../") : this.ImageURL, ToolTip = this.Text }; + if (!string.IsNullOrEmpty(this.OnClickJs)) { - ClientAPI.AddButtonConfirm(colIcon, OnClickJs); + ClientAPI.AddButtonConfirm(colIcon, this.OnClickJs); } - colIcon.CommandName = CommandName; - colIcon.DataBinding += ItemDataBinding; + + colIcon.CommandName = this.CommandName; + colIcon.DataBinding += this.ItemDataBinding; container.Controls.Add(colIcon); } - if (!String.IsNullOrEmpty(Text) && !ShowImage) + + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { - var colLink = new LinkButton {ToolTip = Text}; - if (!String.IsNullOrEmpty(OnClickJs)) + var colLink = new LinkButton { ToolTip = this.Text }; + if (!string.IsNullOrEmpty(this.OnClickJs)) { - ClientAPI.AddButtonConfirm(colLink, OnClickJs); + ClientAPI.AddButtonConfirm(colLink, this.OnClickJs); } - colLink.CommandName = CommandName; - colLink.Text = Text; - colLink.DataBinding += ItemDataBinding; + + colLink.CommandName = this.CommandName; + colLink.Text = this.Text; + colLink.DataBinding += this.ItemDataBinding; container.Controls.Add(colLink); } } + break; case GridItemType.Footer: case GridItemType.Header: - container.Controls.Add(new LiteralControl(Text)); + container.Controls.Add(new LiteralControl(this.Text)); break; } } - + public IOrderedDictionary ExtractValues(Control container) { - //do nothing we don't really support databinding - //but the telerik grid trys to databind to all template columns regardless + // do nothing we don't really support databinding + // but the telerik grid trys to databind to all template columns regardless return new OrderedDictionary(); - } - - #endregion - + } + /// - /// Gets whether theButton is visible + /// Gets whether theButton is visible. /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). private bool GetIsVisible(GridItem container) { - if (!String.IsNullOrEmpty(VisibleField)) + if (!string.IsNullOrEmpty(this.VisibleField)) { - return Convert.ToBoolean(DataBinder.Eval(container.DataItem, VisibleField)); + return Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.VisibleField)); } - return Visible; + return this.Visible; } - - + /// - /// Gets the value of the key + /// Gets the value of the key. /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). private int GetValue(GridItem container) { int keyValue = Null.NullInteger; - if (!String.IsNullOrEmpty(KeyField)) + if (!string.IsNullOrEmpty(this.KeyField)) { - keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, KeyField)); + keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, this.KeyField)); } + return keyValue; } - - + /// - /// Item_DataBinding runs when an Item of type GridItemType.Item is being data-bound + /// Item_DataBinding runs when an Item of type GridItemType.Item is being data-bound. /// /// /// - /// The object that triggers the event - /// An EventArgs object + /// The object that triggers the event. + /// An EventArgs object. private void ItemDataBinding(object sender, EventArgs e) { GridItem container; int keyValue; - if (EditMode == ImageCommandColumnEditMode.URL) + if (this.EditMode == ImageCommandColumnEditMode.URL) { - var hypLink = (HyperLink) sender; - container = (GridItem) hypLink.NamingContainer; - keyValue = GetValue(container); - if (!String.IsNullOrEmpty(NavigateURLFormatString)) + var hypLink = (HyperLink)sender; + container = (GridItem)hypLink.NamingContainer; + keyValue = this.GetValue(container); + if (!string.IsNullOrEmpty(this.NavigateURLFormatString)) { - hypLink.NavigateUrl = string.Format(NavigateURLFormatString, keyValue); + hypLink.NavigateUrl = string.Format(this.NavigateURLFormatString, keyValue); } else { @@ -274,23 +262,24 @@ private void ItemDataBinding(object sender, EventArgs e) } else { - //Bind Image Button - if (!String.IsNullOrEmpty(ImageURL) && ShowImage) + // Bind Image Button + if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { - var colIcon = (ImageButton) sender; - container = (GridItem) colIcon.NamingContainer; - keyValue = GetValue(container); + var colIcon = (ImageButton)sender; + container = (GridItem)colIcon.NamingContainer; + keyValue = this.GetValue(container); colIcon.CommandArgument = keyValue.ToString(CultureInfo.InvariantCulture); - colIcon.Visible = GetIsVisible(container); + colIcon.Visible = this.GetIsVisible(container); } - if (!String.IsNullOrEmpty(Text) && !ShowImage) + + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { - //Bind Link Button - var colLink = (LinkButton) sender; - container = (GridItem) colLink.NamingContainer; - keyValue = GetValue(container); + // Bind Link Button + var colLink = (LinkButton)sender; + container = (GridItem)colLink.NamingContainer; + keyValue = this.GetValue(container); colLink.CommandArgument = keyValue.ToString(CultureInfo.InvariantCulture); - colLink.Visible = GetIsVisible(container); + colLink.Visible = this.GetIsVisible(container); } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs index 1d836e9f092..11eabf7f8e6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnGridItem : GridItem { - public DnnGridItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) : base(ownerTableView, itemIndex, dataSetIndex, itemType) + public DnnGridItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) + : base(ownerTableView, itemIndex, dataSetIndex, itemType) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs index 415ea79e6cc..89a70db3ebc 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs @@ -1,40 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnGridItemSelectedEventArgs : EventArgs { - private readonly GridItemCollection _SelectedItems; - - #region "Constructors" - + private readonly GridItemCollection _SelectedItems; + public DnnGridItemSelectedEventArgs(GridItemCollection selectedItems) { - _SelectedItems = selectedItems; - } - - #endregion - - #region "Public Properties" - + this._SelectedItems = selectedItems; + } + public GridItemCollection SelectedItems { get { - return _SelectedItems; + return this._SelectedItems; } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventHandler.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventHandler.cs index 56b58018132..bbe84fb9859 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventHandler.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { public delegate void DnnGridItemSelectedEventHandler(object sender, DnnGridItemSelectedEventArgs e); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs index 1b3104b248b..3c03130f814 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridMaskedColumn : GridMaskedColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridMaskedColumn dnnGridColumn = new DnnGridMaskedColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs index 87963b84850..96df3eab746 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridNumericColumn : GridNumericColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridNumericColumn dnnGridColumn = new DnnGridNumericColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs index ac6fc3d4445..18b6833b411 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridRatingColumn : GridRatingColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridRatingColumn dnnGridColumn = new DnnGridRatingColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs index 54b01b9c01e..bd868cfe396 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridRowIndicatorColumn : GridRowIndicatorColumn - { - #region Public Properties - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region Public Methods - + } + public override GridColumn Clone() { DnnGridRowIndicatorColumn dnnGridColumn = new DnnGridRowIndicatorColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs index d4a087154e5..df8dc141566 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnGridTableView : GridTableView { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs index 7beb4a7503e..131be71ded8 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs @@ -1,41 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnGridTemplateColumn : GridTemplateColumn - { - #region "Public Properties" - + { public string LocalResourceFile { get { - return Utilities.GetLocalResourceFile(Owner.OwnerGrid.Parent); + return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - - #endregion - - #region "Public Methods" - + } + public override GridColumn Clone() { DnnGridTemplateColumn dnnGridColumn = new DnnGridTemplateColumn(); - //you should override CopyBaseProperties if you have some column specific properties + // you should override CopyBaseProperties if you have some column specific properties dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; @@ -44,12 +32,10 @@ public override GridColumn Clone() public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) { base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && HeaderTemplate == null && !String.IsNullOrEmpty(HeaderText)) + if (inItem is GridHeaderItem && this.HeaderTemplate == null && !string.IsNullOrEmpty(this.HeaderText)) { - cell.Text = Localization.GetString(string.Format("{0}.Header", HeaderText), LocalResourceFile); + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs index c58944bf1b3..6ae8d035317 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnInputManager : RadInputManager { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs index a3aed536531..a8581217a7f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs @@ -1,27 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; - -using Telerik.Web.UI; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + using Telerik.Web.UI; + public class DnnLanguageComboBox : WebControl { private readonly string _viewTypePersonalizationKey; @@ -31,6 +24,25 @@ public class DnnLanguageComboBox : WebControl private DnnComboBox _nativeCombo; private string _originalValue; + + public DnnLanguageComboBox() + { + this.AutoPostBack = Null.NullBoolean; + this.CausesValidation = Null.NullBoolean; + this.ShowFlag = true; + this.ShowModeButtons = true; + this.HideLanguagesList = new Dictionary(); + this.FlagImageUrlFormatString = "~/images/Flags/{0}.gif"; + this._viewTypePersonalizationKey = "ViewType" + this.PortalId; + } + + public event EventHandler ItemChanged; + + public event EventHandler ModeChanged; + + public string FlagImageUrlFormatString { get; set; } + + public Dictionary HideLanguagesList { get; set; } protected override HtmlTextWriterTag TagKey { @@ -38,60 +50,34 @@ protected override HtmlTextWriterTag TagKey { return HtmlTextWriterTag.Div; } - } - - #region "Public Events" - - public event EventHandler ItemChanged; - public event EventHandler ModeChanged; - - #endregion - - #region "Constructor" - - public DnnLanguageComboBox() - { - AutoPostBack = Null.NullBoolean; - CausesValidation = Null.NullBoolean; - ShowFlag = true; - ShowModeButtons = true; - HideLanguagesList = new Dictionary(); - FlagImageUrlFormatString = "~/images/Flags/{0}.gif"; - _viewTypePersonalizationKey = "ViewType" + PortalId; - } - - #endregion - - #region "Public Properties" - + } + private string DisplayMode { get { - string displayMode = Convert.ToString(Personalization.GetProfile("LanguageDisplayMode", _viewTypePersonalizationKey)); + string displayMode = Convert.ToString(Personalization.GetProfile("LanguageDisplayMode", this._viewTypePersonalizationKey)); if (string.IsNullOrEmpty(displayMode)) { displayMode = "NATIVE"; } + return displayMode; } } - public string FlagImageUrlFormatString { get; set; } - - public Dictionary HideLanguagesList { get; set; } - public bool IncludeNoneSpecified { get; set; } public LanguagesListType LanguagesListType { get { - return _languagesListType; + return this._languagesListType; } + set { - _languagesListType = value; + this._languagesListType = value; } } @@ -101,11 +87,12 @@ public string SelectedValue { get { - string selectedValue = DisplayMode.Equals("NATIVE", StringComparison.InvariantCultureIgnoreCase) ? _nativeCombo.SelectedValue : _englishCombo.SelectedValue; + string selectedValue = this.DisplayMode.Equals("NATIVE", StringComparison.InvariantCultureIgnoreCase) ? this._nativeCombo.SelectedValue : this._englishCombo.SelectedValue; if (selectedValue == "None") { selectedValue = Null.NullString; } + return selectedValue; } } @@ -116,36 +103,32 @@ public string SelectedValue /// ----------------------------------------------------------------------------- /// - /// Determines whether the List Auto Posts Back + /// Gets or sets a value indicating whether determines whether the List Auto Posts Back. /// /// ----------------------------------------------------------------------------- public bool AutoPostBack { get; set; } - public bool CausesValidation { get; set; } - - #endregion - - #region "Private Methods" - + public bool CausesValidation { get; set; } + public void BindData(bool refresh) { if (refresh) { List cultures; - switch (LanguagesListType) + switch (this.LanguagesListType) { case LanguagesListType.Supported: cultures = LocaleController.Instance.GetCultures(LocaleController.Instance.GetLocales(Null.NullInteger)); break; case LanguagesListType.Enabled: - cultures = LocaleController.Instance.GetCultures(LocaleController.Instance.GetLocales(PortalId)); + cultures = LocaleController.Instance.GetCultures(LocaleController.Instance.GetLocales(this.PortalId)); break; default: cultures = new List(CultureInfo.GetCultures(CultureTypes.SpecificCultures)); break; } - foreach (KeyValuePair lang in HideLanguagesList) + foreach (KeyValuePair lang in this.HideLanguagesList) { string cultureCode = lang.Value.Code; CultureInfo culture = cultures.Where(c => c.Name == cultureCode).SingleOrDefault(); @@ -155,159 +138,144 @@ public void BindData(bool refresh) } } - _nativeCombo.DataSource = cultures.OrderBy(c => c.NativeName); - _englishCombo.DataSource = cultures.OrderBy(c => c.EnglishName); + this._nativeCombo.DataSource = cultures.OrderBy(c => c.NativeName); + this._englishCombo.DataSource = cultures.OrderBy(c => c.EnglishName); } + + this._nativeCombo.DataBind(); + this._englishCombo.DataBind(); - - _nativeCombo.DataBind(); - _englishCombo.DataBind(); - - if (IncludeNoneSpecified && refresh) + if (this.IncludeNoneSpecified && refresh) { - _englishCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None")); - _nativeCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None")); + this._englishCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None")); + this._nativeCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None")); + } + } + + public void SetLanguage(string code) + { + if (string.IsNullOrEmpty(code)) + { + this._nativeCombo.SelectedIndex = this._nativeCombo.FindItemIndexByValue("None"); + this._englishCombo.SelectedIndex = this._englishCombo.FindItemIndexByValue("None"); + } + else + { + this._nativeCombo.SelectedIndex = this._nativeCombo.FindItemIndexByValue(code); + this._englishCombo.SelectedIndex = this._englishCombo.FindItemIndexByValue(code); } } - #endregion - - #region "Protected Methods" - + public override void DataBind() + { + this.BindData(!this.Page.IsPostBack); + } + protected override void OnInit(EventArgs e) { base.OnInit(e); - _nativeCombo = new DnnComboBox(); - _nativeCombo.DataValueField = "Name"; - _nativeCombo.DataTextField = "NativeName"; - _nativeCombo.SelectedIndexChanged += ItemChangedInternal; - Controls.Add(_nativeCombo); - - _englishCombo = new DnnComboBox(); - _englishCombo.DataValueField = "Name"; - _englishCombo.DataTextField = "EnglishName"; - _englishCombo.SelectedIndexChanged += ItemChangedInternal; - Controls.Add(_englishCombo); - - _modeRadioButtonList = new RadioButtonList(); - _modeRadioButtonList.AutoPostBack = true; - _modeRadioButtonList.RepeatDirection = RepeatDirection.Horizontal; - _modeRadioButtonList.Items.Add(new ListItem(Localization.GetString("NativeName", Localization.GlobalResourceFile), "NATIVE")); - _modeRadioButtonList.Items.Add(new ListItem(Localization.GetString("EnglishName", Localization.GlobalResourceFile), "ENGLISH")); - _modeRadioButtonList.SelectedIndexChanged += ModeChangedInternal; - Controls.Add(_modeRadioButtonList); + this._nativeCombo = new DnnComboBox(); + this._nativeCombo.DataValueField = "Name"; + this._nativeCombo.DataTextField = "NativeName"; + this._nativeCombo.SelectedIndexChanged += this.ItemChangedInternal; + this.Controls.Add(this._nativeCombo); + + this._englishCombo = new DnnComboBox(); + this._englishCombo.DataValueField = "Name"; + this._englishCombo.DataTextField = "EnglishName"; + this._englishCombo.SelectedIndexChanged += this.ItemChangedInternal; + this.Controls.Add(this._englishCombo); + + this._modeRadioButtonList = new RadioButtonList(); + this._modeRadioButtonList.AutoPostBack = true; + this._modeRadioButtonList.RepeatDirection = RepeatDirection.Horizontal; + this._modeRadioButtonList.Items.Add(new ListItem(Localization.GetString("NativeName", Localization.GlobalResourceFile), "NATIVE")); + this._modeRadioButtonList.Items.Add(new ListItem(Localization.GetString("EnglishName", Localization.GlobalResourceFile), "ENGLISH")); + this._modeRadioButtonList.SelectedIndexChanged += this.ModeChangedInternal; + this.Controls.Add(this._modeRadioButtonList); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - _originalValue = SelectedValue; + this._originalValue = this.SelectedValue; } protected virtual void OnItemChanged() { - if (ItemChanged != null) + if (this.ItemChanged != null) { - ItemChanged(this, new EventArgs()); + this.ItemChanged(this, new EventArgs()); } } protected void OnModeChanged(EventArgs e) { - if (ModeChanged != null) + if (this.ModeChanged != null) { - ModeChanged(this, e); + this.ModeChanged(this, e); } } - - + protected override void OnPreRender(EventArgs e) { - if (DisplayMode.Equals("ENGLISH", StringComparison.InvariantCultureIgnoreCase)) + if (this.DisplayMode.Equals("ENGLISH", StringComparison.InvariantCultureIgnoreCase)) { - if (_englishCombo.Items.FindItemByValue(_originalValue) != null) + if (this._englishCombo.Items.FindItemByValue(this._originalValue) != null) { - _englishCombo.Items.FindItemByValue(_originalValue).Selected = true; + this._englishCombo.Items.FindItemByValue(this._originalValue).Selected = true; } } else { - if (_nativeCombo.Items.FindItemByValue(_originalValue) != null) + if (this._nativeCombo.Items.FindItemByValue(this._originalValue) != null) { - _nativeCombo.Items.FindItemByValue(_originalValue).Selected = true; + this._nativeCombo.Items.FindItemByValue(this._originalValue).Selected = true; } } - _modeRadioButtonList.Items.FindByValue(DisplayMode).Selected = true; + this._modeRadioButtonList.Items.FindByValue(this.DisplayMode).Selected = true; - foreach (RadComboBoxItem item in _englishCombo.Items) + foreach (RadComboBoxItem item in this._englishCombo.Items) { - item.ImageUrl = string.Format(FlagImageUrlFormatString, item.Value); + item.ImageUrl = string.Format(this.FlagImageUrlFormatString, item.Value); } - foreach (RadComboBoxItem item in _nativeCombo.Items) + + foreach (RadComboBoxItem item in this._nativeCombo.Items) { - item.ImageUrl = string.Format(FlagImageUrlFormatString, item.Value); + item.ImageUrl = string.Format(this.FlagImageUrlFormatString, item.Value); } - _englishCombo.AutoPostBack = AutoPostBack; - _englishCombo.CausesValidation = CausesValidation; - _englishCombo.Visible = (DisplayMode.Equals("ENGLISH", StringComparison.InvariantCultureIgnoreCase)); + this._englishCombo.AutoPostBack = this.AutoPostBack; + this._englishCombo.CausesValidation = this.CausesValidation; + this._englishCombo.Visible = this.DisplayMode.Equals("ENGLISH", StringComparison.InvariantCultureIgnoreCase); - _nativeCombo.AutoPostBack = AutoPostBack; - _nativeCombo.CausesValidation = CausesValidation; - _nativeCombo.Visible = (DisplayMode.Equals("NATIVE", StringComparison.InvariantCultureIgnoreCase)); + this._nativeCombo.AutoPostBack = this.AutoPostBack; + this._nativeCombo.CausesValidation = this.CausesValidation; + this._nativeCombo.Visible = this.DisplayMode.Equals("NATIVE", StringComparison.InvariantCultureIgnoreCase); - _modeRadioButtonList.Visible = ShowModeButtons; + this._modeRadioButtonList.Visible = this.ShowModeButtons; - _englishCombo.Width = Width; - _nativeCombo.Width = Width; + this._englishCombo.Width = this.Width; + this._nativeCombo.Width = this.Width; base.OnPreRender(e); - } - - #endregion - - #region "Public Methods" - - public void SetLanguage(string code) - { - if (string.IsNullOrEmpty(code)) - { - _nativeCombo.SelectedIndex = _nativeCombo.FindItemIndexByValue("None"); - _englishCombo.SelectedIndex = _englishCombo.FindItemIndexByValue("None"); - } - else - { - _nativeCombo.SelectedIndex = _nativeCombo.FindItemIndexByValue(code); - _englishCombo.SelectedIndex = _englishCombo.FindItemIndexByValue(code); - } - } - - public override void DataBind() - { - BindData(!Page.IsPostBack); - } - - #endregion - - #region "Event Handlers" - + } + private void ModeChangedInternal(object sender, EventArgs e) { - Personalization.SetProfile("LanguageDisplayMode", _viewTypePersonalizationKey, _modeRadioButtonList.SelectedValue); + Personalization.SetProfile("LanguageDisplayMode", this._viewTypePersonalizationKey, this._modeRadioButtonList.SelectedValue); - //Resort - BindData(true); + // Resort + this.BindData(true); - OnModeChanged(EventArgs.Empty); + this.OnModeChanged(EventArgs.Empty); } private void ItemChangedInternal(object sender, EventArgs e) { - OnItemChanged(); - } - - #endregion + this.OnItemChanged(); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBox.cs index 1560297e317..eedbcb289ba 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBox.cs @@ -1,24 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnListBox : RadListBox { - - //public DnnListBox() - //{ + // public DnnListBox() + // { // Utilities.ApplySkin(this); - //} - + // } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs index af4b8a24bc9..d0776e7427f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnListBoxItem : RadListBoxItem { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs index e17c9de1131..8f50da1baf7 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnListView : RadListView { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs index 9b037699228..f32b7134299 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnListViewItem : RadListViewItem { - public DnnListViewItem(RadListViewItemType itemType, RadListView ownerView) : base(itemType, ownerView) + public DnnListViewItem(RadListViewItemType itemType, RadListView ownerView) + : base(itemType, ownerView) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs index ce9045652b4..be1514a4a9e 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnListViewItemDragHandle : RadListViewItemDragHandle { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs index 05fed7f15e1..89b68b29fc2 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnMaskedTextBox : RadMaskedTextBox { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs index a4d9836b8d6..b8ae7ec29b5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnMenu : RadMenu { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs index feca58197f1..dfce694f15b 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnMenuItem : RadMenuItem { public DnnMenuItem() { } - public DnnMenuItem(string text) : base(text) + public DnnMenuItem(string text) + : base(text) { } - public DnnMenuItem(string text, string navigateUrl) : base(text, navigateUrl) + public DnnMenuItem(string text, string navigateUrl) + : base(text, navigateUrl) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs index b9f778b1263..0dce6d38afd 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnMenuItemBinding : RadMenuItemBinding { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs index 074d3967241..fc92438e2ae 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs @@ -1,49 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Installer.Packages; - -using Telerik.Web.UI; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Installer.Packages; + using Telerik.Web.UI; + public class DnnModuleComboBox : WebControl { - private const string DefaultExtensionImage = "icon_extensions_32px.png"; - - #region Public Events - - public event EventHandler ItemChanged; - - #endregion - - #region Public Properties - + private const string DefaultExtensionImage = "icon_extensions_32px.png"; + + private DnnComboBox _moduleCombo; + private string _originalValue; + + public event EventHandler ItemChanged; + public Func, bool> Filter { get; set; } public int ItemCount { get { - return _moduleCombo.Items.Count; + return this._moduleCombo.Items.Count; } } @@ -51,7 +41,7 @@ public string SelectedValue { get { - return _moduleCombo.SelectedValue; + return this._moduleCombo.SelectedValue; } } @@ -59,43 +49,52 @@ public string RadComboBoxClientId { get { - return _moduleCombo.ClientID; + return this._moduleCombo.ClientID; } } - public override bool Enabled { + public override bool Enabled + { get { - return _moduleCombo.Enabled; + return this._moduleCombo.Enabled; } + set { - _moduleCombo.Enabled = value; + this._moduleCombo.Enabled = value; } + } + + public void BindAllPortalDesktopModules() + { + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = this.GetPortalDesktopModules(); + this._moduleCombo.DataBind(); + this.BindPortalDesktopModuleImages(); } - #endregion - - #region Private Methods - - private Dictionary GetPortalDesktopModules() + public void BindTabModulesByTabID(int tabID) { - IOrderedEnumerable> portalModulesList; - if (Filter == null) - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || String.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) - .OrderBy(c => c.Key); - } - else - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where(Filter) - .OrderBy(c => c.Key); - } + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = GetTabModules(tabID); + this._moduleCombo.DataBind(); + this.BindTabModuleImages(tabID); + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this._moduleCombo = new DnnComboBox(); + this._moduleCombo.DataValueField = "key"; + this._moduleCombo.DataTextField = "value"; + this.Controls.Add(this._moduleCombo); + } - return portalModulesList.ToDictionary(portalModule => portalModule.Value.DesktopModuleID, - portalModule => portalModule.Key); + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this._originalValue = this.SelectedValue; } private static Dictionary GetTabModules(int tabID) @@ -121,13 +120,34 @@ private static bool ModuleSuportsSharing(ModuleInfo moduleInfo) return false; } } + + private Dictionary GetPortalDesktopModules() + { + IOrderedEnumerable> portalModulesList; + if (this.Filter == null) + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || string.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) + .OrderBy(c => c.Key); + } + else + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where(this.Filter) + .OrderBy(c => c.Key); + } + + return portalModulesList.ToDictionary( + portalModule => portalModule.Value.DesktopModuleID, + portalModule => portalModule.Key); + } private void BindPortalDesktopModuleImages() { var portalDesktopModules = DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId); var packages = PackageController.Instance.GetExtensionPackages(PortalSettings.Current.PortalId); - foreach (RadComboBoxItem item in _moduleCombo.Items) + foreach (RadComboBoxItem item in this._moduleCombo.Items) { string imageUrl = (from pkgs in packages @@ -135,7 +155,7 @@ join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.Pa where portMods.Value.DesktopModuleID.ToString() == item.Value select pkgs.IconFile).FirstOrDefault(); - item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; + item.ImageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; } } @@ -146,7 +166,7 @@ private void BindTabModuleImages(int tabID) var moduleDefnitions = ModuleDefinitionController.GetModuleDefinitions(); var packages = PackageController.Instance.GetExtensionPackages(PortalSettings.Current.PortalId); - foreach (RadComboBoxItem item in _moduleCombo.Items) + foreach (RadComboBoxItem item in this._moduleCombo.Items) { string imageUrl = (from pkgs in packages join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.PackageID @@ -155,76 +175,32 @@ join tabMods in tabModules on modDefs.Value.DesktopModuleID equals tabMods.Value where tabMods.Value.ModuleID.ToString() == item.Value select pkgs.IconFile).FirstOrDefault(); - item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; + item.ImageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; } - } - - #endregion - - #region Protected Methods - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - _moduleCombo = new DnnComboBox(); - _moduleCombo.DataValueField = "key"; - _moduleCombo.DataTextField = "value"; - Controls.Add(_moduleCombo); - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - _originalValue = SelectedValue; - } + } protected virtual void OnItemChanged() { - if (ItemChanged != null) + if (this.ItemChanged != null) { - ItemChanged(this, new EventArgs()); + this.ItemChanged(this, new EventArgs()); } } protected override void OnPreRender(EventArgs e) { - if (_moduleCombo.Items.FindItemByValue(_originalValue) != null) + if (this._moduleCombo.Items.FindItemByValue(this._originalValue) != null) { - _moduleCombo.Items.FindItemByValue(_originalValue).Selected = true; + this._moduleCombo.Items.FindItemByValue(this._originalValue).Selected = true; } - _moduleCombo.Width = Width; + this._moduleCombo.Width = this.Width; base.OnPreRender(e); - } - - #endregion - - #region Public Methods - - public void BindAllPortalDesktopModules() - { - _moduleCombo.SelectedValue = null; - _moduleCombo.DataSource = GetPortalDesktopModules(); - _moduleCombo.DataBind(); - BindPortalDesktopModuleImages(); - } - - public void BindTabModulesByTabID(int tabID) - { - _moduleCombo.SelectedValue = null; - _moduleCombo.DataSource = GetTabModules(tabID); - _moduleCombo.DataBind(); - BindTabModuleImages(tabID); - } + } public void SetModule(string code) { - _moduleCombo.SelectedIndex = _moduleCombo.FindItemIndexByValue(code); - } - - #endregion - - private DnnComboBox _moduleCombo; - private string _originalValue; + this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs index 69edaccc3be..a17ab66532d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - class DnnMonthYearPicker : RadMonthYearPicker + using System; + + using Telerik.Web.UI; + + internal class DnnMonthYearPicker : RadMonthYearPicker { - } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMultiPage.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMultiPage.cs index de7475df9e0..79045731ef1 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMultiPage.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMultiPage.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnMultiPage : RadMultiPage { - //TODO: Hide properties that we don't want to expose + // TODO: Hide properties that we don't want to expose } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs index 8b2a4bbc8d3..3ed5b6e1184 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnNumericTextBox : RadNumericTextBox { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs index 7bf34dbf8c3..7fa1f76fdf1 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnPageView : RadPageView { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelBar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelBar.cs index 3ddd40f7f06..f4d29186ab6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelBar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelBar.cs @@ -1,25 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnPanelBar : RadPanelBar { - protected override void OnInit(EventArgs e) { base.OnInit(e); Utilities.ApplySkin(this); } - } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs index c422c0324bf..6ee036da2b4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnPanelItem : RadPanelItem { public DnnPanelItem() { } - public DnnPanelItem(string text) : base(text) + public DnnPanelItem(string text) + : base(text) { } - public DnnPanelItem(string text, string navigateUrl) : base(text, navigateUrl) + public DnnPanelItem(string text, string navigateUrl) + : base(text, navigateUrl) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs index cf76da2fc91..f2127fd2506 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnPanelItemBinding : RadPanelItemBinding { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressArea.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressArea.cs index 011ed403e26..bde0f6e5c6e 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressArea.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressArea.cs @@ -1,24 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnProgressArea : RadProgressArea { - - //public DnnProgressArea() - //{ + // public DnnProgressArea() + // { // Utilities.ApplySkin(this); - //} - + // } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs index 8aa5eb1d87b..7c63de1d40c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnProgressManager : RadProgressManager { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs index dba840a14a6..8f57e43f1dc 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs @@ -1,81 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -using DotNetNuke.Services.Localization; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + + using DotNetNuke.Services.Localization; + using Telerik.Web.UI; + public class DnnRadButton : RadButton - { - private bool _Localize = true; - - #region Protected Methods - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - base.Render(writer); - } - - #endregion - - #region ILocalizable Implementation - + { + private bool _Localize = true; + public bool Localize { get { - if (DesignMode) + if (this.DesignMode) { return false; } - return _Localize; + + return this._Localize; } + set { - _Localize = value; + this._Localize = value; } - } - - public string LocalResourceFile { get; set; } - + } + + public string LocalResourceFile { get; set; } + public virtual void LocalizeStrings() { - if ((Localize)) + if (this.Localize) { - if ((!string.IsNullOrEmpty(ToolTip))) + if (!string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(ToolTip, LocalResourceFile); + this.ToolTip = Localization.GetString(this.ToolTip, this.LocalResourceFile); } - if ((!string.IsNullOrEmpty(Text))) + if (!string.IsNullOrEmpty(this.Text)) { - Text = Localization.GetString(Text, LocalResourceFile); + this.Text = Localization.GetString(this.Text, this.LocalResourceFile); - if ((string.IsNullOrEmpty(ToolTip))) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(string.Format("{0}.ToolTip", Text), LocalResourceFile); + this.ToolTip = Localization.GetString(string.Format("{0}.ToolTip", this.Text), this.LocalResourceFile); } } } - } - - #endregion + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadRibbonBar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadRibbonBar.cs index e44ac1db070..f9e9cc78423 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadRibbonBar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadRibbonBar.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnRadRibbonBar : RadRibbonBar { - } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs index 223b3ab9d45..97e1d407265 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnRating : RadRating { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs index f3a64c021d5..c245473e668 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs @@ -1,30 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnRatingItem : RadRatingItem { public DnnRatingItem() { } - public DnnRatingItem(string imageUrl) : base(imageUrl) + public DnnRatingItem(string imageUrl) + : base(imageUrl) { } - public DnnRatingItem(string imageUrl, string selectedImageUrl) : base(imageUrl, selectedImageUrl) + public DnnRatingItem(string imageUrl, string selectedImageUrl) + : base(imageUrl, selectedImageUrl) { } - public DnnRatingItem(string imageUrl, string selectedImageUrl, string hoveredImageUrl) : base(imageUrl, selectedImageUrl, hoveredImageUrl) + public DnnRatingItem(string imageUrl, string selectedImageUrl, string hoveredImageUrl) + : base(imageUrl, selectedImageUrl, hoveredImageUrl) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs index f2206884917..d686ae6f368 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnRotator : RadRotator { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs index 5b413c4f564..f18a9c0bda1 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnRotatorItem : RadRotatorItem { public DnnRotatorItem() { } - public DnnRotatorItem(object dataItem) : base(dataItem) + public DnnRotatorItem(object dataItem) + : base(dataItem) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs index bcf8e24ed70..dae995b8316 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnScheduler : RadScheduler { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs index ae31cc2411e..779d53674e4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSchedulerContextMenu : RadSchedulerContextMenu { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs index e8ad1351719..437585a56a3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSchedulerResourceStyleMapping : ResourceStyleMapping { public DnnSchedulerResourceStyleMapping() { } - public DnnSchedulerResourceStyleMapping(string type, string key, string applyCssClass) : base(type, key, applyCssClass) + public DnnSchedulerResourceStyleMapping(string type, string key, string applyCssClass) + : base(type, key, applyCssClass) { } - public DnnSchedulerResourceStyleMapping(string type, string key, string text, string applyCssClass) : base(type, key, text, applyCssClass) + public DnnSchedulerResourceStyleMapping(string type, string key, string text, string applyCssClass) + : base(type, key, text, applyCssClass) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs index e51325d1f7c..882a59c9458 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSchedulerResourceType : ResourceType { public DnnSchedulerResourceType() { } - public DnnSchedulerResourceType(string resourceTypeName) : base(resourceTypeName) + public DnnSchedulerResourceType(string resourceTypeName) + : base(resourceTypeName) { } - public DnnSchedulerResourceType(string resourceTypeName, bool allowMultipleResourceValues) : base(resourceTypeName, allowMultipleResourceValues) + public DnnSchedulerResourceType(string resourceTypeName, bool allowMultipleResourceValues) + : base(resourceTypeName, allowMultipleResourceValues) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs index 5f916c1f95b..bc4a9bf0535 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnScriptBlock : RadScriptBlock { - } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs index 99dbf5bfa4e..301eadaa7fc 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - class DnnScriptManager : RadScriptManager + using System; + + using Telerik.Web.UI; + + internal class DnnScriptManager : RadScriptManager { - } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs index 5cab697950d..44250b68d62 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSiteMap : RadSiteMap { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs index 2afabdc214a..7259057a2f0 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs @@ -1,30 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSiteMapLevelSetting : SiteMapLevelSetting { public DnnSiteMapLevelSetting() { } - public DnnSiteMapLevelSetting(int level) : base(level) + public DnnSiteMapLevelSetting(int level) + : base(level) { } - public DnnSiteMapLevelSetting(int level, SiteMapLayout layout) : base(level, layout) + public DnnSiteMapLevelSetting(int level, SiteMapLayout layout) + : base(level, layout) { } - public DnnSiteMapLevelSetting(SiteMapLayout layout) : base(layout) + public DnnSiteMapLevelSetting(SiteMapLayout layout) + : base(layout) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs index 46facbdaa9b..e61bcf2157d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSiteMapNode : RadSiteMapNode { public DnnSiteMapNode() { } - public DnnSiteMapNode(string text, string navigateUrl) : base(text, navigateUrl) + public DnnSiteMapNode(string text, string navigateUrl) + : base(text, navigateUrl) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs index f4ec6eb8432..b7d07479108 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSiteMapNodeBinding : RadSiteMapNodeBinding { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs index 75d789f2004..8233bb6851f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs @@ -1,28 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Web.UI; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.UI.Skins; -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Text; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.UI.Skins; + using Telerik.Web.UI; + [ToolboxData("<{0}:DnnSkinComboBox runat='server'>")] public class DnnSkinComboBox : DnnComboBox - { - #region Public Properties - + { + public DnnSkinComboBox() + { + this.PortalId = Null.NullInteger; + } + public int PortalId { get; set; } public string RootPath { get; set; } @@ -31,67 +35,46 @@ public class DnnSkinComboBox : DnnComboBox public bool IncludeNoneSpecificItem { get; set; } - public string NoneSpecificText { get; set; } - - #endregion - - #region Private Properties - + public string NoneSpecificText { get; set; } + private PortalInfo Portal { - get { return PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(PortalId); } - } - - #endregion - - #region Constructors - - public DnnSkinComboBox() - { - PortalId = Null.NullInteger; - } - - #endregion - - #region Event Handlers - + get { return this.PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(this.PortalId); } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - DataTextField = "Key"; - DataValueField = "Value"; + this.DataTextField = "Key"; + this.DataValueField = "Value"; - if (!Page.IsPostBack && !string.IsNullOrEmpty(RootPath)) + if (!this.Page.IsPostBack && !string.IsNullOrEmpty(this.RootPath)) { - DataSource = SkinController.GetSkins(Portal, RootPath, Scope) + this.DataSource = SkinController.GetSkins(this.Portal, this.RootPath, this.Scope) .ToDictionary(skin => skin.Key, skin => skin.Value); - DataBind(SelectedValue); + this.DataBind(this.SelectedValue); - if (IncludeNoneSpecificItem) + if (this.IncludeNoneSpecificItem) { - InsertItem(0, NoneSpecificText, string.Empty); + this.InsertItem(0, this.NoneSpecificText, string.Empty); } } - AttachEvents(); + this.AttachEvents(); } protected override void PerformDataBinding(IEnumerable dataSource) { - //do not select item during data binding, item will select later - var selectedValue = SelectedValue; - SelectedValue = string.Empty; + // do not select item during data binding, item will select later + var selectedValue = this.SelectedValue; + this.SelectedValue = string.Empty; base.PerformDataBinding(dataSource); - SelectedValue = selectedValue; - } - - #endregion - - #region Private Methods - + this.SelectedValue = selectedValue; + } + private void AttachEvents() { if (!UserController.Instance.GetCurrentUserInfo().IsSuperUser) @@ -99,19 +82,19 @@ private void AttachEvents() return; } - Attributes.Add("PortalPath", Portal != null ? Portal.HomeDirectory : string.Empty); - Attributes.Add("HostPath", Globals.HostPath); + this.Attributes.Add("PortalPath", this.Portal != null ? this.Portal.HomeDirectory : string.Empty); + this.Attributes.Add("HostPath", Globals.HostPath); - OnClientSelectedIndexChanged = "selectedIndexChangedMethod"; + this.OnClientSelectedIndexChanged = "selectedIndexChangedMethod"; var indexChangedMethod = @"function selectedIndexChangedMethod(sender, eventArgs){ var value = eventArgs.get_item().get_value(); value = value.replace('[L]', sender.get_attributes().getAttribute('PortalPath')); value = value.replace('[G]', sender.get_attributes().getAttribute('HostPath')); sender.get_inputDomElement().title = value; }"; - Page.ClientScript.RegisterClientScriptBlock(GetType(), "OnClientSelectedIndexChanged", indexChangedMethod, true); + this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnClientSelectedIndexChanged", indexChangedMethod, true); - foreach (RadComboBoxItem item in Items) + foreach (RadComboBoxItem item in this.Items) { if (string.IsNullOrEmpty(item.Value)) { @@ -119,19 +102,17 @@ private void AttachEvents() } var tooltip = item.Value.Replace("[G]", Globals.HostPath); - if (Portal != null) + if (this.Portal != null) { - tooltip = tooltip.Replace("[L]", Portal.HomeDirectory); + tooltip = tooltip.Replace("[L]", this.Portal.HomeDirectory); } item.ToolTip = tooltip; - if (item.Value.Equals(SelectedValue)) + if (item.Value.Equals(this.SelectedValue)) { - ToolTip = tooltip; + this.ToolTip = tooltip; } } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSlider.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSlider.cs index bf21f08eb29..b6f6e8b50a5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSlider.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSlider.cs @@ -1,25 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnSlider : RadSlider { - - //public DnnSlider() - //{ + // public DnnSlider() + // { // Utilities.ApplySkin(this); - //} - + // } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs index 2e0defc0f38..6be6ff2eaaf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSliderItem : RadSliderItem { public DnnSliderItem() { } - public DnnSliderItem(string text) : base(text) + public DnnSliderItem(string text) + : base(text) { } - public DnnSliderItem(string text, string value) : base(text, value) + public DnnSliderItem(string text, string value) + : base(text, value) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs index 14c05b9708d..3297e3ac946 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSpell : RadSpell { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs index 78012e3db93..1e5475a448a 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSplitBar : RadSplitBar { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs index e717ce3c125..6e13996e756 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSplitPane : RadPane { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs index 483937a2300..62dd9a09144 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSplitSlidingPane : RadSlidingPane { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs index cc94981f7df..51cef78adf6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSplitSlidingZone : RadSlidingZone { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs index 6d8ab10855d..f38478fc828 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnSplitter : RadSplitter { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs index cab40657b6c..047fd8f225d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs @@ -1,20 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using Telerik.Web.UI; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using Telerik.Web.UI; + [ParseChildrenAttribute(true)] public class DnnTabPanel : WebControl { @@ -22,76 +16,76 @@ public class DnnTabPanel : WebControl private RadMultiPage _TelerikPages; private RadTabStrip _TelerikTabs; - private RadTabStrip TelerikTabs + public DnnTabCollection Tabs { get { - if (_TelerikTabs == null) + if (this._Tabs == null) { - _TelerikTabs = new RadTabStrip(); + this._Tabs = new DnnTabCollection(this); } - return _TelerikTabs; + return this._Tabs; } } - private RadMultiPage TelerikPages + private RadTabStrip TelerikTabs { get { - if (_TelerikPages == null) + if (this._TelerikTabs == null) { - _TelerikPages = new RadMultiPage(); + this._TelerikTabs = new RadTabStrip(); } - return _TelerikPages; + return this._TelerikTabs; } } - public DnnTabCollection Tabs + private RadMultiPage TelerikPages { get { - if (_Tabs == null) + if (this._TelerikPages == null) { - _Tabs = new DnnTabCollection(this); + this._TelerikPages = new RadMultiPage(); } - return _Tabs; + return this._TelerikPages; } } protected override void OnLoad(EventArgs e) { - base.EnsureChildControls(); + this.EnsureChildControls(); } protected override void CreateChildControls() { - Controls.Clear(); + this.Controls.Clear(); - TelerikTabs.ID = ID + "_Tabs"; - TelerikTabs.Skin = "Office2007"; - TelerikTabs.EnableEmbeddedSkins = true; + this.TelerikTabs.ID = this.ID + "_Tabs"; + this.TelerikTabs.Skin = "Office2007"; + this.TelerikTabs.EnableEmbeddedSkins = true; - TelerikPages.ID = ID + "_Pages"; + this.TelerikPages.ID = this.ID + "_Pages"; - TelerikTabs.MultiPageID = TelerikPages.ID; + this.TelerikTabs.MultiPageID = this.TelerikPages.ID; - Controls.Add(TelerikTabs); - Controls.Add(TelerikPages); + this.Controls.Add(this.TelerikTabs); + this.Controls.Add(this.TelerikPages); } protected override void OnPreRender(EventArgs e) { - if ((!Page.IsPostBack)) + if (!this.Page.IsPostBack) { - TelerikTabs.SelectedIndex = 0; - TelerikPages.SelectedIndex = 0; + this.TelerikTabs.SelectedIndex = 0; + this.TelerikPages.SelectedIndex = 0; int idIndex = 0; - foreach (DnnTab t in Tabs) + foreach (DnnTab t in this.Tabs) { RadTab tab = new RadTab(); tab.TabTemplate = t.Header; @@ -101,8 +95,8 @@ protected override void OnPreRender(EventArgs e) tab.PageViewID = "PV_" + idIndex; pageView.ID = "PV_" + idIndex; - TelerikTabs.Tabs.Add(tab); - TelerikPages.PageViews.Add(pageView); + this.TelerikTabs.Tabs.Add(tab); + this.TelerikPages.PageViews.Add(pageView); idIndex = idIndex + 1; } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabStrip.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabStrip.cs index 23523aeee81..26929df2991 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabStrip.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabStrip.cs @@ -1,25 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnTabStrip : RadTabStrip { - protected override void OnInit(EventArgs e) { base.OnInit(e); Utilities.ApplySkin(this); } - } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloud.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloud.cs index 53d53c2f04e..a82b812bbdf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloud.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloud.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnTagCloud : RadTagCloud { protected void OnItemDataBound(DnnTagCloudItem item) diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs index ad05da6ea83..ac091065266 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnTagCloudItem : RadTagCloudItem { public DnnTagCloudItem() { } - public DnnTagCloudItem(string text) : base(text) + public DnnTagCloudItem(string text) + : base(text) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTextBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTextBox.cs index 15ffd21de96..8dcb73c8dd3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTextBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTextBox.cs @@ -1,24 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnTextBox : RadTextBox { - - //public DnnTextBox() - //{ + // public DnnTextBox() + // { // Utilities.ApplySkin(this); - //} - + // } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs index cddb60d2088..b7c23c310ee 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnTicker : RadTicker { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs index f8f4a1fb85b..8b5c238ba09 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnTickerItem : RadTickerItem { public DnnTickerItem() { } - public DnnTickerItem(string text) : base(text) + public DnnTickerItem(string text) + : base(text) { } - public DnnTickerItem(string text, string navigateUrl) : base(text, navigateUrl) + public DnnTickerItem(string text, string navigateUrl) + : base(text, navigateUrl) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimePicker.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimePicker.cs index 691a7d128e9..dc45cc088b0 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimePicker.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimePicker.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnTimePicker : RadTimePicker { - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - base.EnableEmbeddedBaseStylesheet = true; - Utilities.ApplySkin(this, string.Empty, "DatePicker"); - } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this.EnableEmbeddedBaseStylesheet = true; + Utilities.ApplySkin(this, string.Empty, "DatePicker"); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs index 5804c89cfb4..98c2e56f1e3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnTimeView : RadTimeView { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs index d759788b15b..8900449e819 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnToolBar : RadToolBar { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs index d46dbcd3fc0..e556e4ad57c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnToolBarButton : RadToolBarButton { public DnnToolBarButton() { } - public DnnToolBarButton(string text) : base(text) + public DnnToolBarButton(string text) + : base(text) { } - public DnnToolBarButton(string text, bool isChecked, string @group) : base(text, isChecked, @group) + public DnnToolBarButton(string text, bool isChecked, string @group) + : base(text, isChecked, @group) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs index 35f214cbd69..839add20ff6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnToolBarDropDown : RadToolBarDropDown { public DnnToolBarDropDown() { } - public DnnToolBarDropDown(string text) : base(text) + public DnnToolBarDropDown(string text) + : base(text) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs index d71ae0bc71c..c7075754a01 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnToolBarSplitButton : RadToolBarSplitButton { public DnnToolBarSplitButton() { } - public DnnToolBarSplitButton(string text) : base(text) + public DnnToolBarSplitButton(string text) + : base(text) { } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs index e213f6f228e..e46bf6afea8 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs @@ -1,69 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using DotNetNuke.Web.UI; -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - public class DnnToolTip : RadToolTip, ILocalizable - { - private bool _localize = true; - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - base.Render(writer); - } - - public string ResourceKey { get; set; } - -#region ILocalizable Implementation - public bool Localize - { - get - { - if (base.DesignMode) - { - return false; - } - return _localize; - } - set - { - _localize = value; - } - } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() - { - if ((this.Localize) && (!(String.IsNullOrEmpty(this.ResourceKey)))) - { - if (!(String.IsNullOrEmpty(base.ManualCloseButtonText))) - { - base.ManualCloseButtonText = Utilities.GetLocalizedStringFromParent(String.Format("{0}.ManualCloseButtonText", this.ResourceKey), this); - } - - if (!(String.IsNullOrEmpty(base.Text))) - { - base.Text = Utilities.GetLocalizedStringFromParent(String.Format("{0}.Text", this.ResourceKey), this); - } - - if (!(String.IsNullOrEmpty(base.ToolTip))) - { - base.ToolTip = Utilities.GetLocalizedStringFromParent(String.Format("{0}.ToolTip", this.ResourceKey), this); - } - } - } -#endregion - } + using System; + using System.Web.UI; + + using DotNetNuke.Web.UI; + using Telerik.Web.UI; + + public class DnnToolTip : RadToolTip, ILocalizable + { + private bool _localize = true; + + public string ResourceKey { get; set; } + + public bool Localize + { + get + { + if (this.DesignMode) + { + return false; + } + + return this._localize; + } + + set + { + this._localize = value; + } + } + + public string LocalResourceFile { get; set; } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } + + public virtual void LocalizeStrings() + { + if (this.Localize && (!string.IsNullOrEmpty(this.ResourceKey))) + { + if (!string.IsNullOrEmpty(this.ManualCloseButtonText)) + { + this.ManualCloseButtonText = Utilities.GetLocalizedStringFromParent(string.Format("{0}.ManualCloseButtonText", this.ResourceKey), this); + } + + if (!string.IsNullOrEmpty(this.Text)) + { + this.Text = Utilities.GetLocalizedStringFromParent(string.Format("{0}.Text", this.ResourceKey), this); + } + + if (!string.IsNullOrEmpty(this.ToolTip)) + { + this.ToolTip = Utilities.GetLocalizedStringFromParent(string.Format("{0}.ToolTip", this.ResourceKey), this); + } + } + } + } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs index 46a0ddebf66..46a2ed49d42 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnToolTipManager : RadToolTipManager { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs index b04a7330d25..ccfc3193831 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnTreeList : RadTreeList { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs index 591e1d17f2d..1accdd411b0 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs @@ -1,19 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - + using Telerik.Web.UI; + public class DnnTreeNode : RadTreeNode { - - } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeView.cs index eb2b0c13487..676d0ec4e4f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeView.cs @@ -1,24 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using Telerik.Web.UI; + public class DnnTreeView : RadTreeView { - - //public DnnTreeView() - //{ + // public DnnTreeView() + // { // Utilities.ApplySkin(this); - //} - + // } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeViewContextMenu.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeViewContextMenu.cs index 531aa10ec88..c06604cdb90 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeViewContextMenu.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeViewContextMenu.cs @@ -1,25 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - + using System; + + using Telerik.Web.UI; + public class DnnTreeViewContextMenu : RadTreeViewContextMenu { - - //public DnnTreeViewContextMenu() - //{ + // public DnnTreeViewContextMenu() + // { // Utilities.ApplySkin(this); - //} - + // } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs index 21d60ff972a..90e0ab756d6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnUpload : RadUpload { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs index 2cc919d8f61..99464ea293e 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnWindow : RadWindow { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs index bdec3b465e6..197a32f54a2 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using Telerik.Web.UI; + public class DnnWindowManager : RadWindowManager { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs index 8b917b032ed..c9d135df542 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs @@ -1,30 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Data.SqlTypes; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.WebControls; - -using Telerik.Web.UI; - -using Calendar = DotNetNuke.Common.Utilities.Calendar; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.PropertyEditorControls { + using System; + using System.Collections.Specialized; + using System.Data.SqlTypes; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.WebControls; + using Telerik.Web.UI; + + using Calendar = DotNetNuke.Common.Utilities.Calendar; + /// ----------------------------------------------------------------------------- /// /// The DateEditControl control provides a standard UI component for editing @@ -36,16 +30,36 @@ namespace DotNetNuke.Web.UI.WebControls.PropertyEditorControls [ToolboxData("<{0}:DateEditControl runat=server>")] public class DateEditControl : EditControl { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DateEditControl)); - private DnnDatePicker _dateControl; - - #region Protected Properties + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); + private DnnDatePicker _dateControl; + + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + public override string EditControlClientId + { + get + { + this.EnsureChildControls(); + return this.DateControl.DateInput.ClientID; + } + } + /// ----------------------------------------------------------------------------- /// - /// DateValue returns the Date representation of the Value + /// Gets dateValue returns the Date representation of the Value. /// - /// A Date representing the Value + /// A Date representing the Value. /// ----------------------------------------------------------------------------- protected DateTime DateValue { @@ -54,25 +68,25 @@ protected DateTime DateValue DateTime dteValue = Null.NullDate; try { - var dteString = Convert.ToString(Value); + var dteString = Convert.ToString(this.Value); DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); } catch (Exception exc) { Logger.Error(exc); - } + return dteValue; } } /// ----------------------------------------------------------------------------- /// - /// DefaultDateFormat is a string that will be used to format the date in the absence of a - /// FormatAttribute + /// Gets defaultDateFormat is a string that will be used to format the date in the absence of a + /// FormatAttribute. /// - /// A String representing the default format to use to render the date - /// A Format String + /// A String representing the default format to use to render the date. + /// A Format String. /// ----------------------------------------------------------------------------- protected virtual string DefaultFormat { @@ -84,37 +98,38 @@ protected virtual string DefaultFormat /// ----------------------------------------------------------------------------- /// - /// Format is a string that will be used to format the date in View mode + /// Gets format is a string that will be used to format the date in View mode. /// - /// A String representing the format to use to render the date - /// A Format String + /// A String representing the format to use to render the date. + /// A Format String. /// ----------------------------------------------------------------------------- protected virtual string Format { get { - string _Format = DefaultFormat; - if (CustomAttributes != null) + string _Format = this.DefaultFormat; + if (this.CustomAttributes != null) { - foreach (Attribute attribute in CustomAttributes) + foreach (Attribute attribute in this.CustomAttributes) { if (attribute is FormatAttribute) { - var formatAtt = (FormatAttribute) attribute; + var formatAtt = (FormatAttribute)attribute; _Format = formatAtt.Format; break; } } } + return _Format; } } /// ----------------------------------------------------------------------------- /// - /// OldDateValue returns the Date representation of the OldValue + /// Gets oldDateValue returns the Date representation of the OldValue. /// - /// A Date representing the OldValue + /// A Date representing the OldValue. /// ----------------------------------------------------------------------------- protected DateTime OldDateValue { @@ -123,8 +138,8 @@ protected DateTime OldDateValue DateTime dteValue = Null.NullDate; try { - //Try and cast the value to an DateTime - var dteString = OldValue as string; + // Try and cast the value to an DateTime + var dteString = this.OldValue as string; if (!string.IsNullOrEmpty(dteString)) { dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture); @@ -133,164 +148,134 @@ protected DateTime OldDateValue catch (Exception exc) { Logger.Error(exc); - } + return dteValue; } } /// - /// The Value expressed as a String + /// Gets or sets the Value expressed as a String. /// protected override string StringValue { get { string _StringValue = Null.NullString; - if ((DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && DateValue != Null.NullDate)) + if (this.DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && this.DateValue != Null.NullDate) { - _StringValue = DateValue.ToString(Format); + _StringValue = this.DateValue.ToString(this.Format); } + return _StringValue; } + set { - Value = DateTime.Parse(value); + this.Value = DateTime.Parse(value); } - } - - #endregion - - #region Override Properties - - public override string ID - { - get - { - return base.ID + "_control"; - } - set - { - base.ID = value; - } - } - - public override string EditControlClientId + } + + private DnnDatePicker DateControl { get { - EnsureChildControls(); - return DateControl.DateInput.ClientID; - - } - } - - #endregion - - #region Private Properties - - private DnnDatePicker DateControl - { - get - { - if (_dateControl == null) - { - _dateControl = new DnnDatePicker(); - } - - return _dateControl; - } - } - - #endregion - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - - DateControl.ControlStyle.CopyFrom(ControlStyle); - DateControl.ID = base.ID + "_control"; - - Controls.Add(DateControl); - } + if (this._dateControl == null) + { + this._dateControl = new DnnDatePicker(); + } - protected virtual void LoadDateControls() - { - if (DateValue != Null.NullDate) - { - DateControl.SelectedDate = DateValue.Date; + return this._dateControl; } - } + } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { - EnsureChildControls(); + this.EnsureChildControls(); bool dataChanged = false; - string presentValue = StringValue; - string postedValue = postCollection[postDataKey + "_control"]; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_control"]; if (!presentValue.Equals(postedValue)) { if (string.IsNullOrEmpty(postedValue)) { - Value = Null.NullDate; + this.Value = Null.NullDate; dataChanged = true; } else { - Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); + this.Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); dataChanged = true; } } - LoadDateControls(); + + this.LoadDateControls(); return dataChanged; } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; + + this.Controls.Add(this.DateControl); + } + + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue.Date; + } + } /// - /// OnDataChanged is called by the PostBack Handler when the Data has changed + /// OnDataChanged is called by the PostBack Handler when the Data has changed. /// - /// An EventArgs object + /// An EventArgs object. protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = DateValue; - args.OldValue = OldDateValue; - args.StringValue = DateValue.ToString(CultureInfo.InvariantCulture); - base.OnValueChanged(args); + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.DateValue; + args.OldValue = this.OldDateValue; + args.StringValue = this.DateValue.ToString(CultureInfo.InvariantCulture); + this.OnValueChanged(args); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - LoadDateControls(); + this.LoadDateControls(); - if (Page != null && EditMode == PropertyEditorMode.Edit) + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } /// - /// RenderEditMode is called by the base control to render the control in Edit Mode + /// RenderEditMode is called by the base control to render the control in Edit Mode. /// /// protected override void RenderEditMode(HtmlTextWriter writer) { - RenderChildren(writer); + this.RenderChildren(writer); } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderViewMode(HtmlTextWriter writer) { - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(StringValue); + writer.Write(this.StringValue); writer.RenderEndTag(); } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs index 200b07699d8..e2664d9d320 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs @@ -1,295 +1,282 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Data.SqlTypes; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.WebControls; - -using Telerik.Web.UI; - -using Calendar = DotNetNuke.Common.Utilities.Calendar; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.PropertyEditorControls { - /// ----------------------------------------------------------------------------- - /// Project: DotNetNuke - /// Namespace: DotNetNuke.UI.WebControls - /// Class: DateEditControl - /// ----------------------------------------------------------------------------- - /// - /// The DateEditControl control provides a standard UI component for editing - /// date properties. - /// - /// - /// - /// ----------------------------------------------------------------------------- - [ToolboxData("<{0}:DateTimeEditControl runat=server>")] - public class DateTimeEditControl : EditControl - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); - private DnnDateTimePicker _dateControl; - - #region "Protected Properties" - - /// ----------------------------------------------------------------------------- - /// - /// DateValue returns the Date representation of the Value - /// - /// A Date representing the Value - /// ----------------------------------------------------------------------------- - protected DateTime DateValue - { - get - { - DateTime dteValue = Null.NullDate; - try - { - var dteString = Convert.ToString(Value); - DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); - } - catch (Exception exc) - { - Logger.Error(exc); - - } - return dteValue; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// DefaultDateFormat is a string that will be used to format the date in the absence of a - /// FormatAttribute - /// - /// A String representing the default format to use to render the date - /// A Format String - /// ----------------------------------------------------------------------------- - protected virtual string DefaultFormat - { - get - { - return "g"; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Format is a string that will be used to format the date in View mode - /// - /// A String representing the format to use to render the date - /// A Format String - /// ----------------------------------------------------------------------------- - protected virtual string Format - { - get - { - string _Format = DefaultFormat; - if (CustomAttributes != null) - { - foreach (Attribute attribute in CustomAttributes) - { - if (attribute is FormatAttribute) - { - var formatAtt = (FormatAttribute)attribute; - _Format = formatAtt.Format; - break; - } - } - } - return _Format; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// OldDateValue returns the Date representation of the OldValue - /// - /// A Date representing the OldValue - /// ----------------------------------------------------------------------------- - protected DateTime OldDateValue - { - get - { - DateTime dteValue = Null.NullDate; - try - { - //Try and cast the value to an DateTime - var dteString = OldValue as string; - if (!string.IsNullOrEmpty(dteString)) - { - dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture); - } - } - catch (Exception exc) - { - Logger.Error(exc); - - } - return dteValue; - } - } - - /// - /// The Value expressed as a String - /// - protected override string StringValue - { - get - { - string _StringValue = Null.NullString; - if ((DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && DateValue != Null.NullDate)) - { - _StringValue = DateValue.ToString(Format); - } - return _StringValue; - } - set - { - Value = DateTime.Parse(value); - } - } - - #endregion - - #region Override Properties - - public override string ID - { - get - { - return base.ID + "_control"; - } - set - { - base.ID = value; - } - } - - #endregion - - #region Private Properties - - private DnnDateTimePicker DateControl - { - get - { - if (_dateControl == null) - { - _dateControl = new DnnDateTimePicker(); - } - - return _dateControl; - } - } - - #endregion - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - DateControl.ControlStyle.CopyFrom(ControlStyle); - DateControl.ID = base.ID + "_control"; - - Controls.Add(DateControl); - } - - protected virtual void LoadDateControls() - { - if (DateValue != Null.NullDate) - { - DateControl.SelectedDate = DateValue; - } - } - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - EnsureChildControls(); - bool dataChanged = false; - string presentValue = StringValue; - string postedValue = postCollection[postDataKey + "_control"]; - if (!presentValue.Equals(postedValue)) - { - if (string.IsNullOrEmpty(postedValue)) - { - Value = Null.NullDate; - dataChanged = true; - } - else - { - DateTime value; - if (DateTime.TryParseExact(postedValue, "yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture, - DateTimeStyles.None, out value)) - { - Value = value; - dataChanged = true; - } - } - } - LoadDateControls(); - return dataChanged; - } - - /// - /// OnDataChanged is called by the PostBack Handler when the Data has changed - /// - /// An EventArgs object - protected override void OnDataChanged(EventArgs e) - { - var args = new PropertyEditorEventArgs(Name); - args.Value = DateValue; - args.OldValue = OldDateValue; - args.StringValue = DateValue.ToString(CultureInfo.InvariantCulture); - base.OnValueChanged(args); - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - LoadDateControls(); - - if (Page != null && EditMode == PropertyEditorMode.Edit) - { - Page.RegisterRequiresPostBack(this); - } - } - - /// - /// RenderEditMode is called by the base control to render the control in Edit Mode - /// - /// - protected override void RenderEditMode(HtmlTextWriter writer) - { - RenderChildren(writer); - } - - /// ----------------------------------------------------------------------------- - /// - /// RenderViewMode renders the View (readonly) mode of the control - /// - /// A HtmlTextWriter. - /// ----------------------------------------------------------------------------- - protected override void RenderViewMode(HtmlTextWriter writer) - { - ControlStyle.AddAttributesToRender(writer); - writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(StringValue); - writer.RenderEndTag(); - } - } + using System; + using System.Collections.Specialized; + using System.Data.SqlTypes; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.WebControls; + using Telerik.Web.UI; + + using Calendar = DotNetNuke.Common.Utilities.Calendar; + + /// ----------------------------------------------------------------------------- + /// Project: DotNetNuke + /// Namespace: DotNetNuke.UI.WebControls + /// Class: DateEditControl + /// ----------------------------------------------------------------------------- + /// + /// The DateEditControl control provides a standard UI component for editing + /// date properties. + /// + /// + /// + /// ----------------------------------------------------------------------------- + [ToolboxData("<{0}:DateTimeEditControl runat=server>")] + public class DateTimeEditControl : EditControl + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); + private DnnDateTimePicker _dateControl; + + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets dateValue returns the Date representation of the Value. + /// + /// A Date representing the Value. + /// ----------------------------------------------------------------------------- + protected DateTime DateValue + { + get + { + DateTime dteValue = Null.NullDate; + try + { + var dteString = Convert.ToString(this.Value); + DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); + } + catch (Exception exc) + { + Logger.Error(exc); + } + + return dteValue; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets defaultDateFormat is a string that will be used to format the date in the absence of a + /// FormatAttribute. + /// + /// A String representing the default format to use to render the date. + /// A Format String. + /// ----------------------------------------------------------------------------- + protected virtual string DefaultFormat + { + get + { + return "g"; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets format is a string that will be used to format the date in View mode. + /// + /// A String representing the format to use to render the date. + /// A Format String. + /// ----------------------------------------------------------------------------- + protected virtual string Format + { + get + { + string _Format = this.DefaultFormat; + if (this.CustomAttributes != null) + { + foreach (Attribute attribute in this.CustomAttributes) + { + if (attribute is FormatAttribute) + { + var formatAtt = (FormatAttribute)attribute; + _Format = formatAtt.Format; + break; + } + } + } + + return _Format; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets oldDateValue returns the Date representation of the OldValue. + /// + /// A Date representing the OldValue. + /// ----------------------------------------------------------------------------- + protected DateTime OldDateValue + { + get + { + DateTime dteValue = Null.NullDate; + try + { + // Try and cast the value to an DateTime + var dteString = this.OldValue as string; + if (!string.IsNullOrEmpty(dteString)) + { + dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture); + } + } + catch (Exception exc) + { + Logger.Error(exc); + } + + return dteValue; + } + } + + /// + /// Gets or sets the Value expressed as a String. + /// + protected override string StringValue + { + get + { + string _StringValue = Null.NullString; + if (this.DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && this.DateValue != Null.NullDate) + { + _StringValue = this.DateValue.ToString(this.Format); + } + + return _StringValue; + } + + set + { + this.Value = DateTime.Parse(value); + } + } + + private DnnDateTimePicker DateControl + { + get + { + if (this._dateControl == null) + { + this._dateControl = new DnnDateTimePicker(); + } + + return this._dateControl; + } + } + + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + this.EnsureChildControls(); + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_control"]; + if (!presentValue.Equals(postedValue)) + { + if (string.IsNullOrEmpty(postedValue)) + { + this.Value = Null.NullDate; + dataChanged = true; + } + else + { + DateTime value; + if (DateTime.TryParseExact(postedValue, "yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture, + DateTimeStyles.None, out value)) + { + this.Value = value; + dataChanged = true; + } + } + } + + this.LoadDateControls(); + return dataChanged; + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; + + this.Controls.Add(this.DateControl); + } + + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue; + } + } + + /// + /// OnDataChanged is called by the PostBack Handler when the Data has changed. + /// + /// An EventArgs object. + protected override void OnDataChanged(EventArgs e) + { + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.DateValue; + args.OldValue = this.OldDateValue; + args.StringValue = this.DateValue.ToString(CultureInfo.InvariantCulture); + this.OnValueChanged(args); + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + this.LoadDateControls(); + + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) + { + this.Page.RegisterRequiresPostBack(this); + } + } + + /// + /// RenderEditMode is called by the base control to render the control in Edit Mode. + /// + /// + protected override void RenderEditMode(HtmlTextWriter writer) + { + this.RenderChildren(writer); + } + + /// ----------------------------------------------------------------------------- + /// + /// RenderViewMode renders the View (readonly) mode of the control. + /// + /// A HtmlTextWriter. + /// ----------------------------------------------------------------------------- + protected override void RenderViewMode(HtmlTextWriter writer) + { + this.ControlStyle.AddAttributesToRender(writer); + writer.RenderBeginTag(HtmlTextWriterTag.Span); + writer.Write(this.StringValue); + writer.RenderEndTag(); + } + } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs index dd7e6861d16..fb5b16143a5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs @@ -1,43 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Taxonomy; - -using Telerik.Web.UI; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Taxonomy; + using Telerik.Web.UI; + public class TermsList : WebControl { private bool _IsHeirarchical; private DnnListBox _ListBox; - private DnnTreeView _TreeView; - - #region "Events" - - public event EventHandler SelectedTermChanged; - - #endregion - - #region "Public Properties" - + private DnnTreeView _TreeView; + + public event EventHandler SelectedTermChanged; + public bool IsHeirarchical { get { - return _IsHeirarchical; + return this._IsHeirarchical; } } @@ -46,10 +33,10 @@ public Term SelectedTerm get { Term _SelectedTerm = null; - if (!string.IsNullOrEmpty(SelectedValue)) + if (!string.IsNullOrEmpty(this.SelectedValue)) { - int _TermId = int.Parse(SelectedValue); - foreach (Term term in Terms) + int _TermId = int.Parse(this.SelectedValue); + foreach (Term term in this.Terms) { if (term.TermId == _TermId) { @@ -58,6 +45,7 @@ public Term SelectedTerm } } } + return _SelectedTerm; } } @@ -67,14 +55,15 @@ public string SelectedValue get { string _SelectedValue = Null.NullString; - if (IsHeirarchical) + if (this.IsHeirarchical) { - _SelectedValue = _TreeView.SelectedValue; + _SelectedValue = this._TreeView.SelectedValue; } else { - _SelectedValue = _ListBox.SelectedValue; + _SelectedValue = this._ListBox.SelectedValue; } + return _SelectedValue; } } @@ -84,114 +73,101 @@ public List Terms get { object _DataSource = null; - if (IsHeirarchical) + if (this.IsHeirarchical) { - _DataSource = _TreeView.DataSource; + _DataSource = this._TreeView.DataSource; } else { - _DataSource = _ListBox.DataSource; + _DataSource = this._ListBox.DataSource; } + return _DataSource as List; } - } + } + + public void BindTerms(List terms, bool isHeirarchical, bool dataBind) + { + this._IsHeirarchical = isHeirarchical; - #endregion + this._ListBox.DataSource = terms; + this._TreeView.DataSource = terms; - #region "Protected Methods" + if (dataBind) + { + this._ListBox.DataBind(); + this._TreeView.DataBind(); + } + } + public void ClearSelectedTerm() + { + this._ListBox.SelectedIndex = Null.NullInteger; + this._TreeView.UnselectAllNodes(); + } + protected override void CreateChildControls() { - Controls.Clear(); - - _ListBox = new DnnListBox(); - _ListBox.ID = string.Concat(ID, "_List"); - _ListBox.DataTextField = "Name"; - _ListBox.DataValueField = "TermId"; - _ListBox.AutoPostBack = true; - _ListBox.SelectedIndexChanged += ListBoxSelectedIndexChanged; - - _TreeView = new DnnTreeView(); - _TreeView.ID = string.Concat(ID, "_Tree"); - _TreeView.DataTextField = "Name"; - _TreeView.DataValueField = "TermId"; - _TreeView.DataFieldID = "TermId"; - _TreeView.DataFieldParentID = "ParentTermId"; - _TreeView.NodeClick += TreeViewNodeClick; - - Controls.Add(_ListBox); - Controls.Add(_TreeView); + this.Controls.Clear(); + + this._ListBox = new DnnListBox(); + this._ListBox.ID = string.Concat(this.ID, "_List"); + this._ListBox.DataTextField = "Name"; + this._ListBox.DataValueField = "TermId"; + this._ListBox.AutoPostBack = true; + this._ListBox.SelectedIndexChanged += this.ListBoxSelectedIndexChanged; + + this._TreeView = new DnnTreeView(); + this._TreeView.ID = string.Concat(this.ID, "_Tree"); + this._TreeView.DataTextField = "Name"; + this._TreeView.DataValueField = "TermId"; + this._TreeView.DataFieldID = "TermId"; + this._TreeView.DataFieldParentID = "ParentTermId"; + this._TreeView.NodeClick += this.TreeViewNodeClick; + + this.Controls.Add(this._ListBox); + this.Controls.Add(this._TreeView); } protected override void OnInit(EventArgs e) { - EnsureChildControls(); + this.EnsureChildControls(); } protected override void OnPreRender(EventArgs e) { - _ListBox.Visible = !IsHeirarchical; - _TreeView.Visible = IsHeirarchical; + this._ListBox.Visible = !this.IsHeirarchical; + this._TreeView.Visible = this.IsHeirarchical; - _ListBox.Height = Height; - _ListBox.Width = Width; - _TreeView.Height = Height; - _TreeView.Width = Width; + this._ListBox.Height = this.Height; + this._ListBox.Width = this.Width; + this._TreeView.Height = this.Height; + this._TreeView.Width = this.Width; - _TreeView.ExpandAllNodes(); + this._TreeView.ExpandAllNodes(); base.OnPreRender(e); } protected virtual void OnSelectedTermChanged(TermsEventArgs e) { - //Raise the SelectedTermChanged Event - if (SelectedTermChanged != null) + // Raise the SelectedTermChanged Event + if (this.SelectedTermChanged != null) { - SelectedTermChanged(this, e); + this.SelectedTermChanged(this, e); } - } - - #endregion - - #region "Event Handlers" - + } + private void ListBoxSelectedIndexChanged(object sender, EventArgs e) { - //Raise the SelectedTermChanged Event - OnSelectedTermChanged(new TermsEventArgs(SelectedTerm)); + // Raise the SelectedTermChanged Event + this.OnSelectedTermChanged(new TermsEventArgs(this.SelectedTerm)); } private void TreeViewNodeClick(object sender, RadTreeNodeEventArgs e) { - //Raise the SelectedTermChanged Event - OnSelectedTermChanged(new TermsEventArgs(SelectedTerm)); - } - - #endregion - - #region "Public Methods" - - public void BindTerms(List terms, bool isHeirarchical, bool dataBind) - { - _IsHeirarchical = isHeirarchical; - - _ListBox.DataSource = terms; - _TreeView.DataSource = terms; - - if (dataBind) - { - _ListBox.DataBind(); - _TreeView.DataBind(); - } - } - - public void ClearSelectedTerm() - { - _ListBox.SelectedIndex = Null.NullInteger; - _TreeView.UnselectAllNodes(); - } - - #endregion + // Raise the SelectedTermChanged Event + this.OnSelectedTermChanged(new TermsEventArgs(this.SelectedTerm)); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs index e24ce337eae..9b1e7dd7921 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs @@ -1,68 +1,70 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Web.Script.Serialization; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Telerik.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Web.Script.Serialization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Telerik.Web.UI; + public class TermsSelector : DnnComboBox, IClientAPICallbackEventHandler { public TermsSelector() { - IncludeSystemVocabularies = false; - IncludeTags = true; - EnableViewState = false; - } - - #region Public Properties - + this.IncludeSystemVocabularies = false; + this.IncludeTags = true; + this.EnableViewState = false; + } + public int PortalId { get; set; } public bool IncludeSystemVocabularies { get; set; } public bool IncludeTags { get; set; } - public List Terms { get; set; } - - #endregion - - #region Protected Methods - + public List Terms { get; set; } + + public string RaiseClientAPICallbackEvent(string eventArgument) + { + var parameters = eventArgument.Split('-'); + this.PortalId = Convert.ToInt32(parameters[1]); + this.IncludeTags = Convert.ToBoolean(parameters[2]); + this.IncludeSystemVocabularies = Convert.ToBoolean(parameters[3]); + var terms = this.GetTerms(); + terms.Insert(0, new { clientId = parameters[0] }); + var serializer = new JavaScriptSerializer(); + return serializer.Serialize(terms); + } + protected override void OnInit(EventArgs e) { - ItemTemplate = new TreeViewTemplate(); - Items.Add(new RadComboBoxItem()); + this.ItemTemplate = new TreeViewTemplate(); + this.Items.Add(new RadComboBoxItem()); base.OnInit(e); JavaScript.RequestRegistration(CommonJs.jQueryMigrate); - OnClientDropDownOpened = "webcontrols.termsSelector.OnClientDropDownOpened"; - if (!string.IsNullOrEmpty(CssClass)) + this.OnClientDropDownOpened = "webcontrols.termsSelector.OnClientDropDownOpened"; + if (!string.IsNullOrEmpty(this.CssClass)) { - CssClass = string.Format("{0} TermsSelector", CssClass); + this.CssClass = string.Format("{0} TermsSelector", this.CssClass); } else { - CssClass = "TermsSelector"; + this.CssClass = "TermsSelector"; } } @@ -70,46 +72,46 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (Page.IsPostBack) + if (this.Page.IsPostBack) { - if (Terms == null) + if (this.Terms == null) { - Terms = new List(); + this.Terms = new List(); } else { - Terms.Clear(); + this.Terms.Clear(); } - if (!string.IsNullOrEmpty(SelectedValue)) + if (!string.IsNullOrEmpty(this.SelectedValue)) { - foreach (var id in SelectedValue.Split(',')) + foreach (var id in this.SelectedValue.Split(',')) { var termId = Convert.ToInt32(id.Trim()); var term = Util.GetTermController().GetTerm(termId); if (term != null) { - Terms.Add(term); + this.Terms.Add(term); } } - //clear the append item by client side - if (Items.Count > 1) + // clear the append item by client side + if (this.Items.Count > 1) { - Items.Remove(1); + this.Items.Remove(1); } } } - - - if (!Page.IsPostBack) + + if (!this.Page.IsPostBack) { - Page.ClientScript.RegisterClientScriptResource(GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.js"); + this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.js"); - ClientResourceManager.RegisterStyleSheet(Page, - Page.ClientScript.GetWebResourceUrl(GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.css")); + ClientResourceManager.RegisterStyleSheet( + this.Page, + this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.css")); - ClientAPI.RegisterClientVariable(Page, "TermsSelectorCallback", + ClientAPI.RegisterClientVariable(this.Page, "TermsSelectorCallback", ClientAPI.GetCallbackEventReference(this, "'[PARAMS]'", "webcontrols.termsSelector.itemDataLoaded", "this", "webcontrols.termsSelector.itemDataLoadError"), true); } @@ -118,90 +120,34 @@ protected override void OnLoad(EventArgs e) protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (Terms != null) - { - Attributes.Add("SelectedTerms", String.Join(",", Terms.Select(t => t.TermId.ToString()).ToArray())); - } - Attributes.Add("IncludeSystemVocabularies", IncludeSystemVocabularies.ToString().ToLowerInvariant()); - Attributes.Add("IncludeTags", IncludeTags.ToString().ToLowerInvariant()); - Attributes.Add("PortalId", PortalId.ToString()); - } - - #endregion - - #region Private Template Class - - public class TreeViewTemplate : ITemplate - { - #region Private Fields - - private RadComboBoxItem _container; - private TermsSelector _termsSelector; - - private DnnTreeView _tree; - - #endregion - - #region ITemplate Members - - public void InstantiateIn(Control container) + if (this.Terms != null) { - _container = (RadComboBoxItem)container; - _termsSelector = (TermsSelector)container.Parent; - - _tree = new DnnTreeView(); - _tree.ID = string.Format("{0}_TreeView", _termsSelector.ID); - _tree.CheckBoxes = true; - _tree.EnableViewState = false; - - //bind client-side events - _tree.OnClientNodeChecked = "webcontrols.termsSelector.OnClientNodeChecked"; - - _container.Controls.Add(_tree); + this.Attributes.Add("SelectedTerms", string.Join(",", this.Terms.Select(t => t.TermId.ToString()).ToArray())); } - - - #endregion - } - - #endregion - - #region IClientAPICallbackEventHandler Implementation - - public string RaiseClientAPICallbackEvent(string eventArgument) - { - var parameters = eventArgument.Split('-'); - PortalId = Convert.ToInt32(parameters[1]); - IncludeTags = Convert.ToBoolean(parameters[2]); - IncludeSystemVocabularies = Convert.ToBoolean(parameters[3]); - var terms = GetTerms(); - terms.Insert(0, new { clientId = parameters[0] }); - var serializer = new JavaScriptSerializer(); - return serializer.Serialize(terms); - } - - #endregion - - #region Private Methods - + + this.Attributes.Add("IncludeSystemVocabularies", this.IncludeSystemVocabularies.ToString().ToLowerInvariant()); + this.Attributes.Add("IncludeTags", this.IncludeTags.ToString().ToLowerInvariant()); + this.Attributes.Add("PortalId", this.PortalId.ToString()); + } + private ArrayList GetTerms() { var vocabRep = Util.GetVocabularyController(); var terms = new ArrayList(); - var vocabularies = from v in vocabRep.GetVocabularies() where v.ScopeType.ScopeType == "Application" || (v.ScopeType.ScopeType == "Portal" && v.ScopeId == PortalId) select v; + var vocabularies = from v in vocabRep.GetVocabularies() where v.ScopeType.ScopeType == "Application" || (v.ScopeType.ScopeType == "Portal" && v.ScopeId == this.PortalId) select v; foreach (Vocabulary v in vocabularies) { if (v.IsSystem) { - if (IncludeSystemVocabularies || (IncludeTags && v.Name == "Tags")) + if (this.IncludeSystemVocabularies || (this.IncludeTags && v.Name == "Tags")) { - AddTerms(v, terms); + this.AddTerms(v, terms); } } else { - AddTerms(v, terms); + this.AddTerms(v, terms); } } @@ -212,22 +158,45 @@ private void AddTerms(Vocabulary v, ArrayList terms) { ITermController termRep = Util.GetTermController(); - //Add a dummy parent term if simple vocabulary + // Add a dummy parent term if simple vocabulary if (v.Type == VocabularyType.Simple) { terms.Add(new { termId = -v.VocabularyId, name = v.Name, parentTermId = Null.NullInteger }); } + foreach (Term t in termRep.GetTermsByVocabulary(v.VocabularyId)) { if (v.Type == VocabularyType.Simple) { t.ParentTermId = -v.VocabularyId; } + terms.Add(new { termId = t.TermId, name = t.Name, parentTermId = t.ParentTermId }); } + } + + public class TreeViewTemplate : ITemplate + { + private RadComboBoxItem _container; + private TermsSelector _termsSelector; - } + private DnnTreeView _tree; + + public void InstantiateIn(Control container) + { + this._container = (RadComboBoxItem)container; + this._termsSelector = (TermsSelector)container.Parent; + + this._tree = new DnnTreeView(); + this._tree.ID = string.Format("{0}_TreeView", this._termsSelector.ID); + this._tree.CheckBoxes = true; + this._tree.EnableViewState = false; + + // bind client-side events + this._tree.OnClientNodeChecked = "webcontrols.termsSelector.OnClientNodeChecked"; - #endregion + this._container.Controls.Add(this._tree); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/dnn_Web_Deprecated.dnn b/DNN Platform/DotNetNuke.Web.Deprecated/dnn_Web_Deprecated.dnn index 852b7fe1ce3..67afb171489 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/dnn_Web_Deprecated.dnn +++ b/DNN Platform/DotNetNuke.Web.Deprecated/dnn_Web_Deprecated.dnn @@ -1,6 +1,6 @@  - + DNN Deprecated Web Controls Library DNN Deprecated Web Controls library for legacy Telerik depepndency diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/packages.config b/DNN Platform/DotNetNuke.Web.Deprecated/packages.config index f60bd73968b..56ff2303e0d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/packages.config +++ b/DNN Platform/DotNetNuke.Web.Deprecated/packages.config @@ -3,4 +3,5 @@ + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgery.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgery.cs index f887794fc45..460dd3f8039 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgery.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgery.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { + using System; + + using DotNetNuke.Framework; + public class AntiForgery : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs index 4f05642729b..8c47fc161fd 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs @@ -1,12 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { internal class AntiForgeryImpl : IAntiForgery { - public string CookieName { get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } } + public string CookieName + { + get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } + } + public void Validate(string cookieToken, string headerToken) { System.Web.Helpers.AntiForgery.Validate(cookieToken, headerToken); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs index 30cf51bf13c..041b6e714aa 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { + using System; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + public class DesktopModuleControllerAdapter : ServiceLocator, IDesktopModuleController { - protected override Func GetFactory() - { - return () => new DesktopModuleControllerAdapter(); - } - public DesktopModuleInfo GetDesktopModule(int desktopModuleId, int portalId) { return Entities.Modules.DesktopModuleController.GetDesktopModule(desktopModuleId, portalId); } + + protected override Func GetFactory() + { + return () => new DesktopModuleControllerAdapter(); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/DictionaryExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/DictionaryExtensions.cs index 1502d0050f8..2054890fb52 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/DictionaryExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/DictionaryExtensions.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + internal static class DictionaryExtensions { /// @@ -19,7 +19,8 @@ internal static class DictionaryExtensions public static void RemoveFromDictionary(this IDictionary dictionary, Func, bool> removeCondition) { // Pass the delegate as the state to avoid a delegate and closure - dictionary.RemoveFromDictionary((entry, innerCondition) => + dictionary.RemoveFromDictionary( + (entry, innerCondition) => { return innerCondition(entry); }, @@ -46,6 +47,7 @@ public static void RemoveFromDictionary(this IDictionary(this IDictionary /// Gets the value of associated with the specified key or default value if - /// either the key is not present or the value is not of type . + /// either the key is not present or the value is not of type . /// /// The type of the value associated with the specified key. /// The instance where TValue is object. diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/IAntiForgery.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/IAntiForgery.cs index ed0e56bb6a5..f49fb2a89d3 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/IAntiForgery.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/IAntiForgery.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { public interface IAntiForgery { string CookieName { get; } + void Validate(string cookieToken, string headerToken); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/IDesktopModuleController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/IDesktopModuleController.cs index 2cbda68442b..675dfff2beb 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/IDesktopModuleController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/IDesktopModuleController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { + using DotNetNuke.Entities.Modules; + public interface IDesktopModuleController { DesktopModuleInfo GetDesktopModule(int desktopModuleId, int portalId); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/IModuleControlController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/IModuleControlController.cs index c676915f736..9546e09f8ae 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/IModuleControlController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/IModuleControlController.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + public interface IModuleControlController { ModuleControlInfo GetModuleControlByControlKey(string controlKey, int moduleDefID); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs index 7592071c3ca..af6ec17d7d3 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs @@ -1,27 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { - public class ModuleControlControllerAdapter: ServiceLocator, IModuleControlController + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + + public class ModuleControlControllerAdapter : ServiceLocator, IModuleControlController { - protected override Func GetFactory() - { - return () => new ModuleControlControllerAdapter(); - } - public ModuleControlInfo GetModuleControlByControlKey(string controlKey, int moduleDefID) { return ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefID); } + + protected override Func GetFactory() + { + return () => new ModuleControlControllerAdapter(); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs index a47a16096ac..d7c633fb398 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using DotNetNuke.Common; + internal class PropertyHelper { private static readonly MethodInfo CallPropertyGetterByReferenceOpenGenericMethod = typeof(PropertyHelper).GetMethod("CallPropertyGetterByReference", BindingFlags.NonPublic | BindingFlags.Static); @@ -22,8 +23,8 @@ public PropertyHelper(PropertyInfo property) { Requires.NotNull("property", property); - Name = property.Name; - _valueGetter = MakeFastPropertyGetter(property); + this.Name = property.Name; + this._valueGetter = MakeFastPropertyGetter(property); } // Implementation of the fast getter. @@ -31,22 +32,6 @@ public PropertyHelper(PropertyInfo property) public virtual string Name { get; protected set; } - private static object CallPropertyGetter(Func getter, object @this) - { - return getter((TDeclaringType)@this); - } - - private static object CallPropertyGetterByReference(ByRefFunc getter, object @this) - { - TDeclaringType unboxed = (TDeclaringType)@this; - return getter(ref unboxed); - } - - private static PropertyHelper CreateInstance(PropertyInfo property) - { - return new PropertyHelper(property); - } - /// /// Creates and caches fast property helpers that expose getters for every public get property on the underlying type. /// @@ -57,46 +42,6 @@ public static PropertyHelper[] GetProperties(object instance) return GetProperties(instance, CreateInstance, ReflectionCache); } - protected static PropertyHelper[] GetProperties(object instance, - Func createPropertyHelper, - ConcurrentDictionary cache) - { - // Using an array rather than IEnumerable, as this will be called on the hot path numerous times. - PropertyHelper[] helpers; - - Type type = instance.GetType(); - - if (!cache.TryGetValue(type, out helpers)) - { - // We avoid loading indexed properties using the where statement. - // Indexed properties are not useful (or valid) for grabbing properties off an anonymous object. - IEnumerable properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(prop => prop.GetIndexParameters().Length == 0 && - prop.GetMethod != null); - - var newHelpers = new List(); - - foreach (PropertyInfo property in properties) - { - PropertyHelper propertyHelper = createPropertyHelper(property); - - newHelpers.Add(propertyHelper); - } - - helpers = newHelpers.ToArray(); - cache.TryAdd(type, helpers); - } - - return helpers; - } - - public object GetValue(object instance) - { - //Contract.Assert(_valueGetter != null, "Must call Initialize before using this object"); - - return _valueGetter(instance); - } - /// /// Creates a single fast property getter. The result is not cached. /// @@ -136,5 +81,61 @@ public static Func MakeFastPropertyGetter(PropertyInfo propertyI return (Func)callPropertyGetterDelegate; } + + public object GetValue(object instance) + { + // Contract.Assert(_valueGetter != null, "Must call Initialize before using this object"); + return this._valueGetter(instance); + } + + protected static PropertyHelper[] GetProperties( + object instance, + Func createPropertyHelper, + ConcurrentDictionary cache) + { + // Using an array rather than IEnumerable, as this will be called on the hot path numerous times. + PropertyHelper[] helpers; + + Type type = instance.GetType(); + + if (!cache.TryGetValue(type, out helpers)) + { + // We avoid loading indexed properties using the where statement. + // Indexed properties are not useful (or valid) for grabbing properties off an anonymous object. + IEnumerable properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(prop => prop.GetIndexParameters().Length == 0 && + prop.GetMethod != null); + + var newHelpers = new List(); + + foreach (PropertyInfo property in properties) + { + PropertyHelper propertyHelper = createPropertyHelper(property); + + newHelpers.Add(propertyHelper); + } + + helpers = newHelpers.ToArray(); + cache.TryAdd(type, helpers); + } + + return helpers; + } + + private static object CallPropertyGetter(Func getter, object @this) + { + return getter((TDeclaringType)@this); + } + + private static object CallPropertyGetterByReference(ByRefFunc getter, object @this) + { + TDeclaringType unboxed = (TDeclaringType)@this; + return getter(ref unboxed); + } + + private static PropertyHelper CreateInstance(PropertyInfo property) + { + return new PropertyHelper(property); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs index b5b1b65918d..161f0befea8 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Common { + using System.Web.Routing; + public static class TypeHelper { /// @@ -13,7 +13,8 @@ public static class TypeHelper /// /// This helper will cache accessors and types, and is intended when the anonymous object is accessed multiple /// times throughout the lifetime of the web application. - /// + /// + /// public static RouteValueDictionary ObjectToDictionary(object value) { RouteValueDictionary dictionary = new RouteValueDictionary(); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs index d94b09cbf8e..570ebf4f341 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Web.Mvc; -using DotNetNuke.Services.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System; + using System.Collections.Generic; + using System.Web.Mvc; + + using DotNetNuke.Services.DependencyInjection; + using Microsoft.Extensions.DependencyInjection; + /// /// The implementation used in the /// MVC Modules of DNN. @@ -20,44 +21,48 @@ internal class DnnMvcDependencyResolver : IDependencyResolver public DnnMvcDependencyResolver(IServiceProvider serviceProvider) { - _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); + this._serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); } /// - /// Returns the specified service from the scope + /// Returns the specified service from the scope. /// /// - /// The service to be retrieved + /// The service to be retrieved. /// /// - /// The retrieved service + /// The retrieved service. /// public object GetService(Type serviceType) { - var accessor = _serviceProvider.GetRequiredService(); + var accessor = this._serviceProvider.GetRequiredService(); var scope = accessor.GetScope(); - if (scope != null) - return scope.ServiceProvider.GetService(serviceType); - + if (scope != null) + { + return scope.ServiceProvider.GetService(serviceType); + } + throw new InvalidOperationException("IServiceScope not provided"); } /// - /// Returns the specified services from the scope + /// Returns the specified services from the scope. /// /// - /// The service to be retrieved + /// The service to be retrieved. /// /// - /// The retrieved service + /// The retrieved service. /// public IEnumerable GetServices(Type serviceType) { - var accessor = _serviceProvider.GetRequiredService(); + var accessor = this._serviceProvider.GetRequiredService(); var scope = accessor.GetScope(); - if (scope != null) - return scope.ServiceProvider.GetServices(serviceType); - + if (scope != null) + { + return scope.ServiceProvider.GetServices(serviceType); + } + throw new InvalidOperationException("IServiceScope not provided"); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs index fa886e7892d..f0d547beb0e 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs @@ -1,25 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using System.Web.SessionState; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Modules; -using DotNetNuke.HttpModules.Membership; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Common; -using DotNetNuke.Web.Mvc.Framework.ActionFilters; -using DotNetNuke.Web.Mvc.Framework.Modules; -using DotNetNuke.Web.Mvc.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + using System.Web.SessionState; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Modules; + using DotNetNuke.HttpModules.Membership; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Common; + using DotNetNuke.Web.Mvc.Framework.ActionFilters; + using DotNetNuke.Web.Mvc.Framework.Modules; + using DotNetNuke.Web.Mvc.Routing; + public class DnnMvcHandler : IHttpHandler, IRequiresSessionState { + public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version"; + + private ControllerBuilder _controllerBuilder; + public DnnMvcHandler(RequestContext requestContext) { if (requestContext == null) @@ -27,24 +32,29 @@ public DnnMvcHandler(RequestContext requestContext) throw new ArgumentNullException("requestContext"); } - RequestContext = requestContext; + this.RequestContext = requestContext; } - public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version"; + public static bool DisableMvcResponseHeader { get; set; } - private ControllerBuilder _controllerBuilder; + bool IHttpHandler.IsReusable + { + get { return this.IsReusable; } + } internal ControllerBuilder ControllerBuilder { get { - if (_controllerBuilder == null) + if (this._controllerBuilder == null) { - _controllerBuilder = ControllerBuilder.Current; + this._controllerBuilder = ControllerBuilder.Current; } - return _controllerBuilder; + + return this._controllerBuilder; } - set { _controllerBuilder = value; } + + set { this._controllerBuilder = value; } } protected virtual bool IsReusable @@ -52,45 +62,37 @@ protected virtual bool IsReusable get { return false; } } - public static bool DisableMvcResponseHeader { get; set; } - - bool IHttpHandler.IsReusable - { - get { return IsReusable; } - } - - void IHttpHandler.ProcessRequest(HttpContext httpContext) - { - MembershipModule.AuthenticateRequest(RequestContext.HttpContext, allowUnknownExtensions: true); - ProcessRequest(httpContext); - } - public RequestContext RequestContext { get; private set; } - protected virtual void ProcessRequest(HttpContext httpContext) + void IHttpHandler.ProcessRequest(HttpContext httpContext) { - HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); - ProcessRequest(httpContextBase); + MembershipModule.AuthenticateRequest(this.RequestContext.HttpContext, allowUnknownExtensions: true); + this.ProcessRequest(httpContext); } protected internal virtual void ProcessRequest(HttpContextBase httpContext) { try { - var moduleExecutionEngine = GetModuleExecutionEngine(); + var moduleExecutionEngine = this.GetModuleExecutionEngine(); + // Check if the controller supports IDnnController var moduleResult = - moduleExecutionEngine.ExecuteModule(GetModuleRequestContext(httpContext)); + moduleExecutionEngine.ExecuteModule(this.GetModuleRequestContext(httpContext)); httpContext.SetModuleRequestResult(moduleResult); - RenderModule(moduleResult); + this.RenderModule(moduleResult); } finally { } - } - - #region DNN Mvc Methods + } + protected virtual void ProcessRequest(HttpContext httpContext) + { + HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); + this.ProcessRequest(httpContextBase); + } + private IModuleExecutionEngine GetModuleExecutionEngine() { var moduleExecutionEngine = ComponentFactory.GetComponent(); @@ -100,19 +102,20 @@ private IModuleExecutionEngine GetModuleExecutionEngine() moduleExecutionEngine = new ModuleExecutionEngine(); ComponentFactory.RegisterComponentInstance(moduleExecutionEngine); } + return moduleExecutionEngine; } private ModuleRequestContext GetModuleRequestContext(HttpContextBase httpContext) { var moduleInfo = httpContext.Request.FindModuleInfo(); - var moduleContext = new ModuleInstanceContext() {Configuration = moduleInfo }; + var moduleContext = new ModuleInstanceContext() { Configuration = moduleInfo }; var desktopModule = DesktopModuleControllerAdapter.Instance.GetDesktopModule(moduleInfo.DesktopModuleID, moduleInfo.PortalID); var moduleRequestContext = new ModuleRequestContext { HttpContext = httpContext, ModuleContext = moduleContext, - ModuleApplication = new ModuleApplication(RequestContext, DisableMvcResponseHeader) + ModuleApplication = new ModuleApplication(this.RequestContext, DisableMvcResponseHeader) { ModuleName = desktopModule.ModuleName, FolderPath = desktopModule.FolderName, @@ -124,13 +127,11 @@ private ModuleRequestContext GetModuleRequestContext(HttpContextBase httpContext private void RenderModule(ModuleRequestResult moduleResult) { - var writer = RequestContext.HttpContext.Response.Output; + var writer = this.RequestContext.HttpContext.Response.Output; var moduleExecutionEngine = ComponentFactory.GetComponent(); moduleExecutionEngine.ExecuteModuleResult(moduleResult, writer); - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs index e68113055da..cc70bc66ce1 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs @@ -1,31 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using System.Web.SessionState; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + using System.Web.SessionState; + public class DnnMvcRouteHandler : IRouteHandler { private readonly IControllerFactory _controllerFactory; - + public DnnMvcRouteHandler() { } public DnnMvcRouteHandler(IControllerFactory controllerFactory) { - _controllerFactory = controllerFactory; + this._controllerFactory = controllerFactory; } + + IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) + { + return this.GetHttpHandler(requestContext); + } protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext) { - requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext)); + requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext)); return new DnnMvcHandler(requestContext); } @@ -37,17 +42,8 @@ protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext re throw new InvalidOperationException("No Controller"); } - IControllerFactory controllerFactory = _controllerFactory ?? ControllerBuilder.Current.GetControllerFactory(); + IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory(); return controllerFactory.GetControllerSessionBehavior(requestContext, controllerName); - } - - #region IRouteHandler Members - - IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) - { - return GetHttpHandler(requestContext); - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj b/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj index 7960f3f49ef..490cc3c2c7a 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj +++ b/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj @@ -1,227 +1,233 @@ - - - - - Debug - AnyCPU - {64DC5798-9D37-4F8D-97DD-8403E6E70DD3} - Library - Properties - DotNetNuke.Web.Mvc - DotNetNuke.Web.Mvc - v4.7.2 - 512 - ..\..\ - true - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - 7 - - - - False - ..\Library\bin\DotNetNuke.dll - - - - ..\..\packages\Microsoft.AspNet.WebHelpers.3.1.1\lib\net45\Microsoft.Web.Helpers.dll - True - - - ..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - True - - - - - - - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.Helpers.dll - True - - - False - ..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - - - False - ..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll - - - False - ..\..\Packages\Microsoft.AspNet.Mvc.5.1.3\lib\net45\System.Web.Mvc.dll - True - - - ..\..\packages\Microsoft.AspNet.Razor.3.1.1\lib\net45\System.Web.Razor.dll - True - - - False - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.dll - True - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Deployment.dll - True - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Razor.dll - True - - - - - - - - ..\..\packages\Microsoft.AspNet.WebPages.Data.3.1.1\lib\net45\WebMatrix.Data.dll - True - - - ..\..\packages\Microsoft.AspNet.WebPages.WebData.3.1.1\lib\net45\WebMatrix.WebData.dll - True - - - - - SolutionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - Designer - - - - - {6928a9b1-f88a-4581-a132-d3eb38669bb0} - DotNetNuke.Abstractions - - - {0fca217a-5f9a-4f5b-a31b-86d64ae65198} - DotNetNuke.DependencyInjection - - - {3cd5f6b8-8360-4862-80b6-f402892db7dd} - DotNetNuke.Instrumentation - - - {3D9C3F5F-1D2D-4D89-995B-438055A5E3A6} - DotNetNuke.HttpModules - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - + + + + + Debug + AnyCPU + {64DC5798-9D37-4F8D-97DD-8403E6E70DD3} + Library + Properties + DotNetNuke.Web.Mvc + DotNetNuke.Web.Mvc + v4.7.2 + 512 + ..\..\ + true + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + 7 + + + + False + ..\Library\bin\DotNetNuke.dll + + + + ..\..\packages\Microsoft.AspNet.WebHelpers.3.1.1\lib\net45\Microsoft.Web.Helpers.dll + True + + + ..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll + True + + + + + + + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.Helpers.dll + True + + + False + ..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + + + False + ..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll + + + False + ..\..\Packages\Microsoft.AspNet.Mvc.5.1.3\lib\net45\System.Web.Mvc.dll + True + + + ..\..\packages\Microsoft.AspNet.Razor.3.1.1\lib\net45\System.Web.Razor.dll + True + + + False + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.dll + True + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Deployment.dll + True + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Razor.dll + True + + + + + + + + ..\..\packages\Microsoft.AspNet.WebPages.Data.3.1.1\lib\net45\WebMatrix.Data.dll + True + + + ..\..\packages\Microsoft.AspNet.WebPages.WebData.3.1.1\lib\net45\WebMatrix.WebData.dll + True + + + + + SolutionInfo.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + stylecop.json + + + + Designer + + + Designer + + + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + + + {0fca217a-5f9a-4f5b-a31b-86d64ae65198} + DotNetNuke.DependencyInjection + + + {3cd5f6b8-8360-4862-80b6-f402892db7dd} + DotNetNuke.Instrumentation + + + {3D9C3F5F-1D2D-4D89-995B-438055A5E3A6} + DotNetNuke.HttpModules + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs index e61440b9f78..05ba2c91327 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs @@ -1,15 +1,20 @@ -using DotNetNuke.DependencyInjection.Extensions; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Extensions { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + using DotNetNuke.DependencyInjection.Extensions; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; + public static class StartupExtensions { public static void AddMvcControllers(this IServiceCollection services) @@ -18,8 +23,7 @@ public static void AddMvcControllers(this IServiceCollection services) .SelectMany(TypeExtensions.SafeGetTypes) .Where(x => typeof(IDnnController).IsAssignableFrom(x) && x.IsClass - && !x.IsAbstract - ); + && !x.IsAbstract); foreach (var controller in controllerTypes) { services.TryAddTransient(controller); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs index 8d72958e659..a11e2e53138 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs @@ -1,27 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// - -using System; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Web.Mvc; -using DotNetNuke.Entities.Host; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Web.Mvc; + + using DotNetNuke.Entities.Host; + public class AuthFilterContext { public AuthFilterContext(AuthorizationContext filterContext, string authFailureMessage) { - ActionContext = filterContext; - AuthFailureMessage = authFailureMessage; + this.ActionContext = filterContext; + this.AuthFailureMessage = authFailureMessage; } public AuthorizationContext ActionContext { get; private set; } + public string AuthFailureMessage { get; set; } /// @@ -30,10 +31,10 @@ public AuthFilterContext(AuthorizationContext filterContext, string authFailureM /// public virtual void HandleUnauthorizedRequest() { - ActionContext.Result = new HttpUnauthorizedResult(AuthFailureMessage); + this.ActionContext.Result = new HttpUnauthorizedResult(this.AuthFailureMessage); if (!Host.DebugMode) { - ActionContext.RequestContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; + this.ActionContext.RequestContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs index b61ecd04836..5ea5e45c7a3 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs @@ -1,50 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Mvc; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Web; + using System.Web.Mvc; + + using DotNetNuke.Common; + public abstract class AuthorizeAttributeBase : FilterAttribute, IAuthorizationFilter { - protected virtual bool AuthorizeCore(HttpContextBase httpContext) - { - return true; - } - - private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) + public static bool IsAnonymousAttributePresent(AuthorizationContext filterContext) { - validationStatus = OnCacheAuthorization(new HttpContextWrapper(context)); + return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) + || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); } - + public virtual void OnAuthorization(AuthorizationContext filterContext) { Requires.NotNull("filterContext", filterContext); - if (SkipAuthorization(filterContext)) + if (this.SkipAuthorization(filterContext)) { return; } - if (AuthorizeCore(filterContext.HttpContext)) + if (this.AuthorizeCore(filterContext.HttpContext)) { - HandleAuthorizedRequest(filterContext); + this.HandleAuthorizedRequest(filterContext); } else { - HandleUnauthorizedRequest(filterContext); + this.HandleUnauthorizedRequest(filterContext); } } + + protected virtual bool AuthorizeCore(HttpContextBase httpContext) + { + return true; + } protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContext) { HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge(new TimeSpan(0)); - cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */); + cachePolicy.AddValidationCallback(this.CacheValidateHandler, null /* data */); + } + + private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) + { + validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); } protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) @@ -52,19 +59,20 @@ protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterCont const string failureMessage = "Authorization has been denied for this request."; var authFilterContext = new AuthFilterContext(filterContext, failureMessage); authFilterContext.HandleUnauthorizedRequest(); - //filterContext.HttpContext.Response.Redirect(Globals.AccessDeniedURL()); + + // filterContext.HttpContext.Response.Redirect(Globals.AccessDeniedURL()); } protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) { Requires.NotNull("httpContext", httpContext); - bool isAuthorized = AuthorizeCore(httpContext); - return (isAuthorized) ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest; + bool isAuthorized = this.AuthorizeCore(httpContext); + return isAuthorized ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest; } /// - /// Skips this authorization step if anonymous attribute is applied, override if auth should never be skipped, or other conditions are required + /// Skips this authorization step if anonymous attribute is applied, override if auth should never be skipped, or other conditions are required. /// /// /// @@ -72,11 +80,5 @@ protected virtual bool SkipAuthorization(AuthorizationContext filterContext) { return IsAnonymousAttributePresent(filterContext); } - - public static bool IsAnonymousAttributePresent(AuthorizationContext filterContext) - { - return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) - || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs index 5df0d974c62..5422140e7cf 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Web; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Web; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + public class DnnAuthorizeAttribute : AuthorizeAttributeBase { private string _staticRoles; @@ -21,28 +22,30 @@ public class DnnAuthorizeAttribute : AuthorizeAttributeBase private string[] _denyRolesSplit = new string[0]; /// - /// Gets or sets the authorized roles (separated by comma) + /// Gets or sets the authorized roles (separated by comma). /// public string StaticRoles { - get { return _staticRoles; } + get { return this._staticRoles; } + set { - _staticRoles = value; - _staticRolesSplit = SplitString(_staticRoles); + this._staticRoles = value; + this._staticRolesSplit = this.SplitString(this._staticRoles); } } /// - /// Gets or sets the denied roles (separated by comma) + /// Gets or sets the denied roles (separated by comma). /// public string DenyRoles { - get { return _denyRoles; } + get { return this._denyRoles; } + set { - _denyRoles = value; - _denyRolesSplit = SplitString(_denyRoles); + this._denyRoles = value; + this._denyRolesSplit = this.SplitString(this._denyRoles); } } @@ -53,29 +56,29 @@ protected virtual bool IsAuthenticated() protected virtual UserInfo GetCurrentUser() { - return PortalController.Instance.GetCurrentPortalSettings().UserInfo; + return PortalController.Instance.GetCurrentPortalSettings().UserInfo; } protected override bool AuthorizeCore(HttpContextBase httpContext) { - if (!IsAuthenticated()) + if (!this.IsAuthenticated()) { return false; } - if (_denyRolesSplit.Any()) + if (this._denyRolesSplit.Any()) { - var currentUser = GetCurrentUser(); - if (!currentUser.IsSuperUser && _denyRolesSplit.Any(currentUser.IsInRole)) + var currentUser = this.GetCurrentUser(); + if (!currentUser.IsSuperUser && this._denyRolesSplit.Any(currentUser.IsInRole)) { return false; } } - if (_staticRolesSplit.Any()) + if (this._staticRolesSplit.Any()) { - var currentUser = GetCurrentUser(); - if (!_staticRolesSplit.Any(currentUser.IsInRole)) + var currentUser = this.GetCurrentUser(); + if (!this._staticRolesSplit.Any(currentUser.IsInRole)) { return false; } @@ -86,17 +89,16 @@ protected override bool AuthorizeCore(HttpContextBase httpContext) private string[] SplitString(string original) { - if (String.IsNullOrEmpty(original)) + if (string.IsNullOrEmpty(original)) { return new string[0]; } IEnumerable split = from piece in original.Split(',') let trimmed = piece.Trim() - where !String.IsNullOrEmpty(trimmed) + where !string.IsNullOrEmpty(trimmed) select trimmed; return split.ToArray(); } - } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnHandleErrorAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnHandleErrorAttribute.cs index ad17b2ccac3..46468523572 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnHandleErrorAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnHandleErrorAttribute.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Mvc; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Web.Mvc; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public class DnnHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) @@ -19,8 +20,8 @@ public override void OnException(ExceptionContext filterContext) { throw new InvalidOperationException("This attribute can only be applied to Controllers that implement IDnnController"); } - - LogException(filterContext.Exception); + + this.LogException(filterContext.Exception); } protected virtual void LogException(Exception exception) diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs index d45b7fdf19b..70870d9e308 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs @@ -1,40 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Mvc; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Web; + using System.Web.Mvc; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public class DnnModuleAuthorizeAttribute : AuthorizeAttributeBase { private ModuleInfo _module; public DnnModuleAuthorizeAttribute() { - AccessLevel = SecurityAccessLevel.Host; + this.AccessLevel = SecurityAccessLevel.Host; } public SecurityAccessLevel AccessLevel { get; set; } public string PermissionKey { get; set; } - protected override bool AuthorizeCore(HttpContextBase httpContext) - { - if (_module != null) - { - return HasModuleAccess(); - } - - return false; - } - public override void OnAuthorization(AuthorizationContext filterContext) { var controller = filterContext.Controller as IDnnController; @@ -44,14 +35,24 @@ public override void OnAuthorization(AuthorizationContext filterContext) throw new InvalidOperationException("This attribute can only be applied to Controllers that implement IDnnController"); } - _module = controller.ModuleContext.Configuration; + this._module = controller.ModuleContext.Configuration; base.OnAuthorization(filterContext); } + protected override bool AuthorizeCore(HttpContextBase httpContext) + { + if (this._module != null) + { + return this.HasModuleAccess(); + } + + return false; + } + protected virtual bool HasModuleAccess() { - return ModulePermissionController.HasModuleAccess(AccessLevel, PermissionKey, _module); + return ModulePermissionController.HasModuleAccess(this.AccessLevel, this.PermissionKey, this._module); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs index 00f1f5eaed3..c2ff7467c55 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs @@ -1,48 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Mvc; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Security; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Web.Mvc; + + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Security; + using DotNetNuke.Web.Mvc.Framework.Controllers; + /// - /// The ModuleActionAttribute is used to define a single ModuleAction. It can be applied at the Controller level if all + /// The ModuleActionAttribute is used to define a single ModuleAction. It can be applied at the Controller level if all /// Action methods should have the same ModuleAction, but it is more likely to be used at the Action method level. /// - public class ModuleActionAttribute : ActionFilterAttribute + public class ModuleActionAttribute : ActionFilterAttribute { public ModuleActionAttribute() { - SecurityAccessLevel = SecurityAccessLevel.Edit; + this.SecurityAccessLevel = SecurityAccessLevel.Edit; } /// - /// The ControlKey property is the key for the module control + /// Gets or sets the ControlKey property is the key for the module control. /// public string ControlKey { get; set; } /// - /// The Icon property is the url for the Icon to be used in the Module Actions menu. An empty string will mean that the Edit "pencil" icon is used. + /// Gets or sets the Icon property is the url for the Icon to be used in the Module Actions menu. An empty string will mean that the Edit "pencil" icon is used. /// public string Icon { get; set; } /// - /// The SecurityAccessLevel is an enum property that sets the security level for the module action. + /// Gets or sets the SecurityAccessLevel is an enum property that sets the security level for the module action. /// public SecurityAccessLevel SecurityAccessLevel { get; set; } /// - /// The Title property is the title for the Module Action. This property is only used if the TitleKey is left blank. + /// Gets or sets the Title property is the title for the Module Action. This property is only used if the TitleKey is left blank. /// public string Title { get; set; } /// - /// The TitleKey property is the localization key for the title for the Module Action. + /// Gets or sets the TitleKey property is the localization key for the title for the Module Action. /// public string TitleKey { get; set; } @@ -60,16 +61,17 @@ public override void OnActionExecuting(ActionExecutingContext filterContext) controller.ModuleActions = new ModuleActionCollection(); } - controller.ModuleActions.Add(-1, - (!String.IsNullOrEmpty(TitleKey)) ? controller.LocalizeString(TitleKey) : Title, - ModuleActionType.AddContent, - "", - Icon, - controller.ModuleContext.EditUrl(ControlKey), - false, - SecurityAccessLevel, - true, - false); + controller.ModuleActions.Add( + -1, + (!string.IsNullOrEmpty(this.TitleKey)) ? controller.LocalizeString(this.TitleKey) : this.Title, + ModuleActionType.AddContent, + string.Empty, + this.Icon, + controller.ModuleContext.EditUrl(this.ControlKey), + false, + this.SecurityAccessLevel, + true, + false); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionItemsAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionItemsAttribute.cs index f62638d0e26..ff1f763c8ae 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionItemsAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionItemsAttribute.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Reflection; -using System.Web.Mvc; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Framework; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Reflection; + using System.Web.Mvc; + + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Framework; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public class ModuleActionItemsAttribute : ActionFilterAttribute { private const string MethodNameTemplate = "Get{0}Actions"; @@ -25,34 +26,34 @@ public override void OnActionExecuting(ActionExecutingContext filterContext) Type type; string methodName; - if(controller == null) + if (controller == null) { throw new InvalidOperationException("This attribute can only be applied to Controllers that implement IDnnController"); } object instance; - if (Type == null) + if (this.Type == null) { type = filterContext.Controller.GetType(); instance = controller; } else { - type = Type; + type = this.Type; instance = Reflection.CreateInstance(type); } - if (String.IsNullOrEmpty(MethodName)) + if (string.IsNullOrEmpty(this.MethodName)) { - methodName = String.Format(MethodNameTemplate, filterContext.ActionDescriptor.ActionName); + methodName = string.Format(MethodNameTemplate, filterContext.ActionDescriptor.ActionName); } else { - methodName = MethodName; + methodName = this.MethodName; } - var method = GetMethod(type, methodName); + var method = this.GetMethod(type, methodName); controller.ModuleActions = method.Invoke(instance, null) as ModuleActionCollection; } @@ -63,7 +64,7 @@ private MethodInfo GetMethod(Type type, string methodName) if (method == null) { - throw new NotImplementedException(String.Format("The expected method to get the module actions cannot be found. Type: {0}, Method: {1}", type.FullName, methodName)); + throw new NotImplementedException(string.Format("The expected method to get the module actions cannot be found. Type: {0}, Method: {1}", type.FullName, methodName)); } var returnType = method.ReturnType.FullName; diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs index b1f1702a8cd..1578f8fc094 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs @@ -1,36 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Threading; -using System.Web; -using System.Web.Mvc; -using DotNetNuke.Entities.Users; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { + using System; + using System.Threading; + using System.Web; + using System.Web.Mvc; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public class RequireHostAttribute : AuthorizeAttributeBase { private UserInfo _user; - protected override bool AuthorizeCore(HttpContextBase httpContext) - { - var principal = Thread.CurrentPrincipal; - if (!principal.Identity.IsAuthenticated) - { - return false; - } - - if (_user != null) - { - return _user.IsSuperUser; - } - - return false; - } - public override void OnAuthorization(AuthorizationContext filterContext) { var controller = filterContext.Controller as IDnnController; @@ -40,9 +25,25 @@ public override void OnAuthorization(AuthorizationContext filterContext) throw new InvalidOperationException("This attribute can only be applied to Controllers that implement IDnnController"); } - _user = controller.ModuleContext.PortalSettings.UserInfo; + this._user = controller.ModuleContext.PortalSettings.UserInfo; base.OnAuthorization(filterContext); } + + protected override bool AuthorizeCore(HttpContextBase httpContext) + { + var principal = Thread.CurrentPrincipal; + if (!principal.Identity.IsAuthenticated) + { + return false; + } + + if (this._user != null) + { + return this._user.IsSuperUser; + } + + return false; + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs index f8781033fb0..df015229dda 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Web; -using System.Web.Mvc; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Web.Mvc.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionFilters { - public class ValidateAntiForgeryTokenAttribute : AuthorizeAttributeBase + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Web; + using System.Web.Mvc; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Web.Mvc.Common; + + public class ValidateAntiForgeryTokenAttribute : AuthorizeAttributeBase { public virtual bool IsAuthenticated(HttpContextBase httpContext) { @@ -24,14 +25,14 @@ public virtual bool IsAuthenticated(HttpContextBase httpContext) { var headers = httpContext.Request.Headers; var form = httpContext.Request.Form; - //Try to fetch the token from Headers. (Used with Dnn service framework.). - //If not found then fetch it from form fields. (Would be used with standard MVC call). + + // Try to fetch the token from Headers. (Used with Dnn service framework.). + // If not found then fetch it from form fields. (Would be used with standard MVC call). var token = headers.AllKeys.Contains("RequestVerificationToken") ? headers.GetValues("RequestVerificationToken").FirstOrDefault() : ( - form.AllKeys.Contains("__RequestVerificationToken") ? form.GetValues("__RequestVerificationToken").FirstOrDefault(): null - ); + form.AllKeys.Contains("__RequestVerificationToken") ? form.GetValues("__RequestVerificationToken").FirstOrDefault() : null); - var cookieValue = GetAntiForgeryCookieValue(httpContext); + var cookieValue = this.GetAntiForgeryCookieValue(httpContext); if (token != null) { AntiForgery.Instance.Validate(cookieValue, token); @@ -68,15 +69,16 @@ protected string GetAntiForgeryCookieValue(HttpContextBase context) } } - return ""; + return string.Empty; } protected override bool AuthorizeCore(HttpContextBase httpContext) { - if (!IsAuthenticated(httpContext)) + if (!this.IsAuthenticated(httpContext)) { return false; } + return true; } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnPartialViewResult.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnPartialViewResult.cs index 446f7e380f8..789586640eb 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnPartialViewResult.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnPartialViewResult.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Mvc; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionResults { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Web.Mvc; + + using DotNetNuke.Common; + public class DnnPartialViewResult : PartialViewResult, IDnnViewResult { public void ExecuteResult(ControllerContext context, TextWriter writer) @@ -21,25 +22,25 @@ public void ExecuteResult(ControllerContext context, TextWriter writer) Requires.NotNull("context", context); Requires.NotNull("writer", writer); - if (String.IsNullOrEmpty(ViewName)) + if (string.IsNullOrEmpty(this.ViewName)) { - ViewName = context.RouteData.GetRequiredString("action"); + this.ViewName = context.RouteData.GetRequiredString("action"); } ViewEngineResult result = null; - if (View == null) + if (this.View == null) { - result = ViewEngineCollection.FindPartialView(context, ViewName); - View = result.View; + result = this.ViewEngineCollection.FindPartialView(context, this.ViewName); + this.View = result.View; } - var viewContext = new ViewContext(context, View, ViewData, TempData, writer); - View.Render(viewContext, writer); + var viewContext = new ViewContext(context, this.View, this.ViewData, this.TempData, writer); + this.View.Render(viewContext, writer); if (result != null) { - result.ViewEngine.ReleaseView(context, View); + result.ViewEngine.ReleaseView(context, this.View); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs index 15607242a49..6d79d51ed49 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs @@ -1,35 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using System.Web.Routing; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionResults { + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Helpers; + using Microsoft.Extensions.DependencyInjection; + internal class DnnRedirecttoRouteResult : RedirectToRouteResult { - protected INavigationManager NavigationManager { get; } public DnnRedirecttoRouteResult(string actionName, string controllerName, string routeName, RouteValueDictionary routeValues, bool permanent) : base(routeName, routeValues, permanent) { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - ActionName = actionName; - ControllerName = controllerName; + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.ActionName = actionName; + this.ControllerName = controllerName; } public DnnRedirecttoRouteResult(string actionName, string controllerName, string routeName, RouteValueDictionary routeValues, bool permanent, DnnUrlHelper url) : this(actionName, controllerName, routeName, routeValues, permanent) { - Url = url; + this.Url = url; } public DnnUrlHelper Url { get; private set; } + + protected INavigationManager NavigationManager { get; } public string ActionName { get; private set; } @@ -42,17 +44,17 @@ public override void ExecuteResult(ControllerContext context) Guard.Against(context.IsChildAction, "Cannot Redirect In Child Action"); string url; - if (Url != null && context.Controller is IDnnController) + if (this.Url != null && context.Controller is IDnnController) { - url = Url.Action(ActionName, ControllerName); + url = this.Url.Action(this.ActionName, this.ControllerName); } else { - //TODO - match other actions - url = NavigationManager.NavigateURL(); + // TODO - match other actions + url = this.NavigationManager.NavigateURL(); } - if (Permanent) + if (this.Permanent) { context.HttpContext.Response.RedirectPermanent(url, true); } @@ -60,8 +62,6 @@ public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.Redirect(url, true); } - - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnViewResult.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnViewResult.cs index 3ed1df34bb7..bb5b652ad12 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnViewResult.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnViewResult.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web.Mvc; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionResults { + using System; + using System.IO; + using System.Web.Mvc; + + using DotNetNuke.Common; + public class DnnViewResult : ViewResult, IDnnViewResult { public void ExecuteResult(ControllerContext context, TextWriter writer) @@ -16,25 +17,25 @@ public void ExecuteResult(ControllerContext context, TextWriter writer) Requires.NotNull("context", context); Requires.NotNull("writer", writer); - if (String.IsNullOrEmpty(ViewName)) + if (string.IsNullOrEmpty(this.ViewName)) { - ViewName = context.RouteData.GetRequiredString("action"); + this.ViewName = context.RouteData.GetRequiredString("action"); } ViewEngineResult result = null; - if (View == null) + if (this.View == null) { - result = ViewEngineCollection.FindView(context, ViewName, MasterName); - View = result.View; + result = this.ViewEngineCollection.FindView(context, this.ViewName, this.MasterName); + this.View = result.View; } - var viewContext = new ViewContext(context, View, ViewData, TempData, writer); - View.Render(viewContext, writer); + var viewContext = new ViewContext(context, this.View, this.ViewData, this.TempData, writer); + this.View.Render(viewContext, writer); if (result != null) { - result.ViewEngine.ReleaseView(context, View); + result.ViewEngine.ReleaseView(context, this.View); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/IDnnViewResult.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/IDnnViewResult.cs index 35dc8b6ae68..bafad84d7f9 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/IDnnViewResult.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/IDnnViewResult.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.ActionResults { + using System.IO; + using System.Web.Mvc; + public interface IDnnViewResult { void ExecuteResult(ControllerContext context, TextWriter writer); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs index 4dbc8a3bdb4..d2c29dbc52e 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs @@ -1,40 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text; -using System.Web.Mvc; -using System.Web.Routing; -using System.Web.UI; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework.ActionResults; -using DotNetNuke.Web.Mvc.Framework.Modules; -using DotNetNuke.Web.Mvc.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Controllers { + using System; + using System.Text; + using System.Web.Mvc; + using System.Web.Routing; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework.ActionResults; + using DotNetNuke.Web.Mvc.Framework.Modules; + using DotNetNuke.Web.Mvc.Helpers; + public abstract class DnnController : Controller, IDnnController { protected DnnController() { - ActionInvoker = new ResultCapturingActionInvoker(); + this.ActionInvoker = new ResultCapturingActionInvoker(); } public ModuleInfo ActiveModule { - get { return (ModuleContext == null) ? null : ModuleContext.Configuration; } + get { return (this.ModuleContext == null) ? null : this.ModuleContext.Configuration; } } public TabInfo ActivePage { - get { return (PortalSettings == null) ? null : PortalSettings.ActiveTab; } + get { return (this.PortalSettings == null) ? null : this.PortalSettings.ActiveTab; } } public Page DnnPage { get; set; } @@ -43,56 +44,58 @@ public TabInfo ActivePage public string LocalResourceFile { get; set; } - public string LocalizeString(string key) - { - return Localization.GetString(key, LocalResourceFile); - } - public ModuleActionCollection ModuleActions { get; set; } public ModuleInstanceContext ModuleContext { get; set; } public PortalSettings PortalSettings { - get { return (ModuleContext == null) ? null : ModuleContext.PortalSettings; } - } - - protected override RedirectToRouteResult RedirectToAction(string actionName, string controllerName, RouteValueDictionary routeValues) - { - return new DnnRedirecttoRouteResult(actionName, controllerName, string.Empty, routeValues, false, Url); + get { return (this.ModuleContext == null) ? null : this.ModuleContext.PortalSettings; } } - protected internal RedirectToRouteResult RedirectToDefaultRoute() + public string LocalizeString(string key) { - return new DnnRedirecttoRouteResult(String.Empty, String.Empty, String.Empty, null, false); + return Localization.GetString(key, this.LocalResourceFile); } public ActionResult ResultOfLastExecute { get { - var actionInvoker = ActionInvoker as ResultCapturingActionInvoker; - return (actionInvoker != null) ? actionInvoker.ResultOfLastInvoke : null; + var actionInvoker = this.ActionInvoker as ResultCapturingActionInvoker; + return (actionInvoker != null) ? actionInvoker.ResultOfLastInvoke : null; } } public new UserInfo User { - get { return (PortalSettings == null) ? null : PortalSettings.UserInfo; } + get { return (this.PortalSettings == null) ? null : this.PortalSettings.UserInfo; } + } + + public ViewEngineCollection ViewEngineCollectionEx { get; set; } + + protected internal RedirectToRouteResult RedirectToDefaultRoute() + { + return new DnnRedirecttoRouteResult(string.Empty, string.Empty, string.Empty, null, false); + } + + protected override RedirectToRouteResult RedirectToAction(string actionName, string controllerName, RouteValueDictionary routeValues) + { + return new DnnRedirecttoRouteResult(actionName, controllerName, string.Empty, routeValues, false, this.Url); } protected override ViewResult View(IView view, object model) { if (model != null) { - ViewData.Model = model; + this.ViewData.Model = model; } return new DnnViewResult { View = view, - ViewData = ViewData, - TempData = TempData + ViewData = this.ViewData, + TempData = this.TempData, }; } @@ -100,16 +103,16 @@ protected override ViewResult View(string viewName, string masterName, object mo { if (model != null) { - ViewData.Model = model; + this.ViewData.Model = model; } return new DnnViewResult { ViewName = viewName, MasterName = masterName, - ViewData = ViewData, - TempData = TempData, - ViewEngineCollection = ViewEngineCollection + ViewData = this.ViewData, + TempData = this.TempData, + ViewEngineCollection = this.ViewEngineCollection, }; } @@ -117,24 +120,22 @@ protected override PartialViewResult PartialView(string viewName, object model) { if (model != null) { - ViewData.Model = model; + this.ViewData.Model = model; } return new DnnPartialViewResult { ViewName = viewName, - ViewData = ViewData, - TempData = TempData, - ViewEngineCollection = ViewEngineCollection + ViewData = this.ViewData, + TempData = this.TempData, + ViewEngineCollection = this.ViewEngineCollection, }; } protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); - Url = new DnnUrlHelper(requestContext, this); + this.Url = new DnnUrlHelper(requestContext, this); } - - public ViewEngineCollection ViewEngineCollectionEx { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs index f77a5e286d9..3c2f1ba3b45 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using System.Web.UI; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Controllers { + using System.Web.Mvc; + using System.Web.UI; + + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Helpers; + public interface IDnnController : IController { ControllerContext ControllerContext { get; } @@ -18,19 +19,18 @@ public interface IDnnController : IController string LocalResourceFile { get; set; } - string LocalizeString(string key); - ModuleActionCollection ModuleActions { get; set; } ModuleInstanceContext ModuleContext { get; set; } ActionResult ResultOfLastExecute { get; } + string LocalizeString(string key); + bool ValidateRequest { get; set; } ViewEngineCollection ViewEngineCollectionEx { get; set; } DnnUrlHelper Url { get; set; } - } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPage.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPage.cs index 5908ec9deb2..30a100f239f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPage.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPage.cs @@ -1,26 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using DotNetNuke.Web.Mvc.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework { + using System.Web.Mvc; + + using DotNetNuke.Web.Mvc.Helpers; + public abstract class DnnWebViewPage : WebViewPage { public DnnHelper Dnn { get; set; } public new DnnHtmlHelper Html { get; set; } - public new DnnUrlHelper Url { get; set; } + public new DnnUrlHelper Url { get; set; } public override void InitHelpers() { - Ajax = new AjaxHelper(ViewContext, this); - Html = new DnnHtmlHelper(ViewContext, this); - Url = new DnnUrlHelper(ViewContext); - Dnn = new DnnHelper(ViewContext, this); + this.Ajax = new AjaxHelper(this.ViewContext, this); + this.Html = new DnnHtmlHelper(this.ViewContext, this); + this.Url = new DnnUrlHelper(this.ViewContext); + this.Dnn = new DnnHelper(this.ViewContext, this); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPageOfT.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPageOfT.cs index 32dd4a5bc47..159111c844c 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPageOfT.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/DnnWebViewPageOfT.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using DotNetNuke.Web.Mvc.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework { + using System.Web.Mvc; + + using DotNetNuke.Web.Mvc.Helpers; + public abstract class DnnWebViewPage : WebViewPage { public DnnHelper Dnn { get; set; } @@ -15,12 +16,12 @@ public abstract class DnnWebViewPage : WebViewPage public new DnnUrlHelper Url { get; set; } - public override void InitHelpers() + public override void InitHelpers() { - Ajax = new AjaxHelper(ViewContext, this); - Html = new DnnHtmlHelper(ViewContext, this); - Url = new DnnUrlHelper(ViewContext); - Dnn = new DnnHelper(ViewContext, this); + this.Ajax = new AjaxHelper(this.ViewContext, this); + this.Html = new DnnHtmlHelper(this.ViewContext, this); + this.Url = new DnnUrlHelper(this.ViewContext); + this.Dnn = new DnnHelper(this.ViewContext, this); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs index 2f348a39dae..fadc409b3a8 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Mvc; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Framework.Modules; -using DotNetNuke.Web.Mvc.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework { + using System; + using System.Collections.Generic; + using System.Web.Mvc; + + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Framework.Modules; + using DotNetNuke.Web.Mvc.Routing; + /// /// A View Engine that will delegate to whatever ViewEngine(s) the module application defines. /// @@ -27,7 +28,7 @@ public class ModuleDelegatingViewEngine : IViewEngine /// The controller context.The name of the partial view.true to specify that the view engine returns the cached view, if a cached view exists; otherwise, false. public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache) { - return RunAgainstModuleViewEngines(controllerContext, e => e.FindPartialView(controllerContext, partialViewName, useCache)); + return this.RunAgainstModuleViewEngines(controllerContext, e => e.FindPartialView(controllerContext, partialViewName, useCache)); } /// @@ -39,7 +40,7 @@ public ViewEngineResult FindPartialView(ControllerContext controllerContext, str /// The controller context.The name of the view.The name of the master.true to specify that the view engine returns the cached view, if a cached view exists; otherwise, false. public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { - return RunAgainstModuleViewEngines(controllerContext, e => e.FindView(controllerContext, viewName, masterName, useCache)); + return this.RunAgainstModuleViewEngines(controllerContext, e => e.FindView(controllerContext, viewName, masterName, useCache)); } /// @@ -48,36 +49,39 @@ public ViewEngineResult FindView(ControllerContext controllerContext, string vie /// The controller context.The view. public void ReleaseView(ControllerContext controllerContext, IView view) { - if (_viewEngineMappings.ContainsKey(view)) + if (this._viewEngineMappings.ContainsKey(view)) + { + this._viewEngineMappings[view].ReleaseView(controllerContext, view); + } + } + + private static ModuleRequestResult GetCurrentModuleRequestResult(ControllerContext controllerContext) + { + if (controllerContext.HttpContext.HasModuleRequestResult()) { - _viewEngineMappings[view].ReleaseView(controllerContext, view); + return controllerContext.HttpContext.GetModuleRequestResult(); } + + return null; } private ViewEngineResult RunAgainstModuleViewEngines(ControllerContext controllerContext, Func engineRequest) { var controller = controllerContext.Controller as IDnnController; - if (controller == null || controller.ViewEngineCollectionEx == null) - return new ViewEngineResult(new string[0]); - + if (controller == null || controller.ViewEngineCollectionEx == null) + { + return new ViewEngineResult(new string[0]); + } + var result = engineRequest(controller.ViewEngineCollectionEx); // If there is a view, store the view<->viewengine mapping so release works correctly if (result.View != null) { - _viewEngineMappings[result.View] = result.ViewEngine; + this._viewEngineMappings[result.View] = result.ViewEngine; } return result; } - - private static ModuleRequestResult GetCurrentModuleRequestResult(ControllerContext controllerContext) - { - if (controllerContext.HttpContext.HasModuleRequestResult()) - { - return controllerContext.HttpContext.GetModuleRequestResult(); - } - return null; - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/IModuleExecutionEngine.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/IModuleExecutionEngine.cs index a14c758fefc..3f406231407 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/IModuleExecutionEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/IModuleExecutionEngine.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Modules { + using System.IO; + public interface IModuleExecutionEngine { ModuleRequestResult ExecuteModule(ModuleRequestContext moduleRequestContext); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs index c80b57de99c..488367a5958 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs @@ -1,53 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using System.Web; -using System.Reflection; -using DotNetNuke.Web.Mvc.Common; -using Microsoft.Web.Infrastructure.DynamicValidationHelper; -using DotNetNuke.Common; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Modules { + using System; + using System.Globalization; + using System.Reflection; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Mvc.Common; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Web.Infrastructure.DynamicValidationHelper; + public class ModuleApplication { + internal static readonly string MvcVersion = GetMvcVersionString(); + protected const string ControllerMasterFormat = "~/DesktopModules/MVC/{0}/Views/{{1}}/{{0}}.cshtml"; protected const string SharedMasterFormat = "~/DesktopModules/MVC/{0}/Views/Shared/{{0}}.cshtml"; protected const string ControllerViewFormat = "~/DesktopModules/MVC/{0}/Views/{{1}}/{{0}}.cshtml"; protected const string SharedViewFormat = "~/DesktopModules/MVC/{0}/Views/Shared/{{0}}.cshtml"; protected const string ControllerPartialFormat = "~/DesktopModules/MVC/{0}/Views/{{1}}/{{0}}.cshtml"; protected const string SharedPartialFormat = "~/DesktopModules/MVC/{0}/Views/Shared/{{0}}.cshtml"; - - public RequestContext RequestContext { get; private set; } - internal static readonly string MvcVersion = GetMvcVersionString(); private const string MvcVersionHeaderName = "X-AspNetMvc-Version"; - private static bool DisableMvcResponseHeader { get; set; } + private readonly object _lock = new object(); private bool _initialized; - private readonly object _lock = new object(); - public ModuleApplication():this(null, false) + public ModuleApplication() + : this(null, false) { } - public ModuleApplication(bool disableMvcResponseHeader) : this(null, disableMvcResponseHeader) + + public RequestContext RequestContext { get; private set; } + + private static bool DisableMvcResponseHeader { get; set; } + + public ModuleApplication(bool disableMvcResponseHeader) + : this(null, disableMvcResponseHeader) { } + public ModuleApplication(RequestContext requestContext, bool disableMvcResponseHeader) { - RequestContext = requestContext; + this.RequestContext = requestContext; + // ReSharper disable once DoNotCallOverridableMethodsInConstructor DisableMvcResponseHeader = disableMvcResponseHeader; - ControllerFactory = Globals.DependencyProvider.GetRequiredService(); - ViewEngines = new ViewEngineCollection(); - //ViewEngines.Add(new ModuleDelegatingViewEngine()); + this.ControllerFactory = Globals.DependencyProvider.GetRequiredService(); + this.ViewEngines = new ViewEngineCollection(); + + // ViewEngines.Add(new ModuleDelegatingViewEngine()); } public virtual IControllerFactory ControllerFactory { get; set; } @@ -64,23 +73,10 @@ public ModuleApplication(RequestContext requestContext, bool disableMvcResponseH public ViewEngineCollection ViewEngines { get; set; } - protected void EnsureInitialized() - { - // Double-check lock to wait for initialization - // TODO: Is there a better (preferably using events and waits) way to do this? - if (_initialized) return; - lock (_lock) - { - if (_initialized) return; - Init(); - _initialized = true; - } - } - public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) { - EnsureInitialized(); - RequestContext = RequestContext ?? new RequestContext(context.HttpContext, context.RouteData); + this.EnsureInitialized(); + this.RequestContext = this.RequestContext ?? new RequestContext(context.HttpContext, context.RouteData); var currentContext = HttpContext.Current; if (currentContext != null) { @@ -90,13 +86,14 @@ public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) ValidationUtility.EnableDynamicValidation(currentContext); } } - AddVersionHeader(RequestContext.HttpContext); - RemoveOptionalRoutingParameters(); + + this.AddVersionHeader(this.RequestContext.HttpContext); + this.RemoveOptionalRoutingParameters(); - var controllerName = RequestContext.RouteData.GetRequiredString("controller"); + var controllerName = this.RequestContext.RouteData.GetRequiredString("controller"); - //Construct the controller using the ControllerFactory - var controller = ControllerFactory.CreateController(RequestContext, controllerName); + // Construct the controller using the ControllerFactory + var controller = this.ControllerFactory.CreateController(this.RequestContext, controllerName); try { // Check if the controller supports IDnnController @@ -115,62 +112,79 @@ public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) moduleController.ModuleContext = context.ModuleContext; - moduleController.LocalResourceFile = String.Format("~/DesktopModules/MVC/{0}/{1}/{2}.resx", - context.ModuleContext.Configuration.DesktopModule.FolderName, - Localization.LocalResourceDirectory, - controllerName); + moduleController.LocalResourceFile = string.Format( + "~/DesktopModules/MVC/{0}/{1}/{2}.resx", + context.ModuleContext.Configuration.DesktopModule.FolderName, + Localization.LocalResourceDirectory, + controllerName); - moduleController.ViewEngineCollectionEx = ViewEngines; + moduleController.ViewEngineCollectionEx = this.ViewEngines; + // Execute the controller and capture the result // if our ActionFilter is executed after the ActionResult has triggered an Exception the filter // MUST explicitly flip the ExceptionHandled bit otherwise the view will not render - moduleController.Execute(RequestContext); + moduleController.Execute(this.RequestContext); var result = moduleController.ResultOfLastExecute; // Return the final result - return new ModuleRequestResult - { - ActionResult = result, - ControllerContext = moduleController.ControllerContext, - ModuleActions = moduleController.ModuleActions, - ModuleContext = context.ModuleContext, - ModuleApplication = this - }; + return new ModuleRequestResult + { + ActionResult = result, + ControllerContext = moduleController.ControllerContext, + ModuleActions = moduleController.ModuleActions, + ModuleContext = context.ModuleContext, + ModuleApplication = this, + }; } finally { - ControllerFactory.ReleaseController(controller); + this.ControllerFactory.ReleaseController(controller); } } protected internal virtual void Init() { - var prefix = NormalizeFolderPath(FolderPath); + var prefix = NormalizeFolderPath(this.FolderPath); string[] masterFormats = - { + { string.Format(CultureInfo.InvariantCulture, ControllerMasterFormat, prefix), - string.Format(CultureInfo.InvariantCulture, SharedMasterFormat, prefix) + string.Format(CultureInfo.InvariantCulture, SharedMasterFormat, prefix), }; string[] viewFormats = - { + { string.Format(CultureInfo.InvariantCulture, ControllerViewFormat, prefix), string.Format(CultureInfo.InvariantCulture, SharedViewFormat, prefix), string.Format(CultureInfo.InvariantCulture, ControllerPartialFormat, prefix), - string.Format(CultureInfo.InvariantCulture, SharedPartialFormat, prefix) + string.Format(CultureInfo.InvariantCulture, SharedPartialFormat, prefix), }; - ViewEngines.Add(new RazorViewEngine - { - MasterLocationFormats = masterFormats, - ViewLocationFormats = viewFormats, - PartialViewLocationFormats = viewFormats - }); + this.ViewEngines.Add(new RazorViewEngine + { + MasterLocationFormats = masterFormats, + ViewLocationFormats = viewFormats, + PartialViewLocationFormats = viewFormats, + }); } - protected static string NormalizeFolderPath(string path) + protected void EnsureInitialized() { - // Remove leading and trailing slashes - return !string.IsNullOrEmpty(path) ? path.Trim('/') : path; + // Double-check lock to wait for initialization + // TODO: Is there a better (preferably using events and waits) way to do this? + if (this._initialized) + { + return; + } + + lock (this._lock) + { + if (this._initialized) + { + return; + } + + this.Init(); + this._initialized = true; + } } protected internal virtual void AddVersionHeader(HttpContextBase httpContext) @@ -181,12 +195,10 @@ protected internal virtual void AddVersionHeader(HttpContextBase httpContext) } } - private void RemoveOptionalRoutingParameters() + protected static string NormalizeFolderPath(string path) { - var rvd = RequestContext.RouteData.Values; - - // Ensure delegate is stateless - rvd.RemoveFromDictionary((entry) => entry.Value == UrlParameter.Optional); + // Remove leading and trailing slashes + return !string.IsNullOrEmpty(path) ? path.Trim('/') : path; } private static string GetMvcVersionString() @@ -196,5 +208,13 @@ private static string GetMvcVersionString() // medium trust. However, Assembly.FullName *is* accessible in medium trust. return new AssemblyName(typeof(MvcHandler).Assembly.FullName).Version.ToString(2); } + + private void RemoveOptionalRoutingParameters() + { + var rvd = this.RequestContext.RouteData.Values; + + // Ensure delegate is stateless + rvd.RemoveFromDictionary((entry) => entry.Value == UrlParameter.Optional); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs index 6bc67bcbb4c..faaa5696a76 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Web.Mvc.Framework.ActionResults; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Modules { + using System; + using System.IO; + + using DotNetNuke.Common; + using DotNetNuke.Web.Mvc.Framework.ActionResults; + public class ModuleExecutionEngine : IModuleExecutionEngine { public ModuleRequestResult ExecuteModule(ModuleRequestContext moduleRequestContext) @@ -17,9 +18,10 @@ public ModuleRequestResult ExecuteModule(ModuleRequestContext moduleRequestConte if (moduleRequestContext.ModuleApplication != null) { - //Run the module + // Run the module return moduleRequestContext.ModuleApplication.ExecuteRequest(moduleRequestContext); } + return null; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestContext.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestContext.cs index 16e23c8357f..18e41593e05 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestContext.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestContext.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using System.Web.Routing; -using System.Web.UI; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Modules { + using System.Web; + using System.Web.Routing; + using System.Web.UI; + + using DotNetNuke.UI.Modules; + public class ModuleRequestContext { public Page DnnPage { get; set; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestResult.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestResult.cs index 53365fa114e..1bdde925ce0 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestResult.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleRequestResult.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Modules { + using System.Web.Mvc; + + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.UI.Modules; + public class ModuleRequestResult { public ActionResult ActionResult { get; set; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs index d354c8c55ef..0f29b1be48f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs @@ -1,34 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework.Modules { + using System; + using System.Collections.Generic; + using System.Web.Mvc; + public class ResultCapturingActionInvoker : ControllerActionInvoker { public ActionResult ResultOfLastInvoke { get; set; } + protected override ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList filters, ActionDescriptor actionDescriptor, IDictionary parameters) { var context = base.InvokeActionMethodWithFilters(controllerContext, filters, actionDescriptor, parameters); - ResultOfLastInvoke = context.Result; + this.ResultOfLastInvoke = context.Result; return context; } protected override ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList filters, Exception exception) - { + { var context = base.InvokeExceptionFilters(controllerContext, filters, exception); - ResultOfLastInvoke = context.Result; + this.ResultOfLastInvoke = context.Result; return context; } - + protected override void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) { - //Do not invoke the action. Instead, store it for later retrieval - if(ResultOfLastInvoke == null) ResultOfLastInvoke = actionResult; + // Do not invoke the action. Instead, store it for later retrieval + if (this.ResultOfLastInvoke == null) + { + this.ResultOfLastInvoke = actionResult; + } } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs index 9ba1bc31fa8..5f012848855 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs @@ -1,27 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.Linq; -using System.Reflection; -using DotNetNuke.Framework; -using System.Text; -using System.Threading.Tasks; -using System.Web.Caching; -using System.Web.Mvc; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Framework { + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Globalization; + using System.Linq; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + using System.Web.Caching; + using System.Web.Mvc; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public static class ViewEngineCollectionExt { - //Enable the call to ViewEngineCollection FindView method with useCache=false - public static ViewEngineResult FindView(this ViewEngineCollection viewEngineCollection, + // Enable the call to ViewEngineCollection FindView method with useCache=false + public static ViewEngineResult FindView( + this ViewEngineCollection viewEngineCollection, ControllerContext controllerContext, string viewName, string masterName, bool useCache) { @@ -34,7 +36,7 @@ public static ViewEngineResult FindView(this ViewEngineCollection viewEngineColl { new Func( e => e.FindView(controllerContext, viewName, masterName, false)), - false + false, }); return useCache ? CBO.GetCachedObject(cachArg, CallFind) : CallFind(cachArg); @@ -45,8 +47,9 @@ public static ViewEngineResult FindView(this ViewEngineCollection viewEngineColl } } - //Enable the call to ViewEngineCollection FindPartialView method with useCache=false - public static ViewEngineResult FindPartialView(this ViewEngineCollection viewEngineCollection, + // Enable the call to ViewEngineCollection FindPartialView method with useCache=false + public static ViewEngineResult FindPartialView( + this ViewEngineCollection viewEngineCollection, ControllerContext controllerContext, string partialViewName, bool useCache) { try @@ -58,7 +61,7 @@ public static ViewEngineResult FindPartialView(this ViewEngineCollection viewEng { new Func( e => e.FindPartialView(controllerContext, partialViewName, false)), - false + false, }); return useCache ? CBO.GetCachedObject(cachArg, CallFind) : CallFind(cachArg); @@ -76,7 +79,8 @@ private static ViewEngineResult CallFind(CacheItemArgs cacheItem) var target = cacheItem.Params[1]; var parameters = cacheItem.Params[2] as object[]; return - factoryType.InvokeMember(name, + factoryType.InvokeMember( + name, BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, target, parameters) as ViewEngineResult; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs index a51d8627042..dfe25e6642f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Mvc; -using System.Web.Routing; -using System.Web.UI; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ConvertPropertyToExpressionBody - namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Web.Mvc; + using System.Web.Routing; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public class DnnHelper { - public DnnHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) + public DnnHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) : this(viewContext, viewDataContainer, RouteTable.Routes) { } @@ -32,7 +32,7 @@ public DnnHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, protected DnnHelper(HtmlHelper htmlHelper) { - HtmlHelper = htmlHelper; + this.HtmlHelper = htmlHelper; var controller = htmlHelper.ViewContext.Controller as IDnnController; @@ -41,53 +41,68 @@ protected DnnHelper(HtmlHelper htmlHelper) throw new InvalidOperationException("The DnnHelper class can only be used in Views that inherit from DnnWebViewPage"); } - DnnPage = controller.DnnPage; + this.DnnPage = controller.DnnPage; - ModuleContext = controller.ModuleContext; - LocalResourceFile = controller.LocalResourceFile; + this.ModuleContext = controller.ModuleContext; + this.LocalResourceFile = controller.LocalResourceFile; } public ModuleInfo ActiveModule { - get { return (ModuleContext == null) ? null : ModuleContext.Configuration; } + get { return (this.ModuleContext == null) ? null : this.ModuleContext.Configuration; } } public TabInfo ActivePage { - get { return (PortalSettings == null) ? null : PortalSettings.ActiveTab; } + get { return (this.PortalSettings == null) ? null : this.PortalSettings.ActiveTab; } } public Page DnnPage { get; set; } - internal HtmlHelper HtmlHelper { get; set; } - public string LocalResourceFile { get; set; } - public string LocalizeString(string key) - { - return Localization.GetString(key, LocalResourceFile); - } - public ModuleInstanceContext ModuleContext { get; set; } + internal HtmlHelper HtmlHelper { get; set; } + public PortalSettings PortalSettings { - get { return (ModuleContext == null) ? null : ModuleContext.PortalSettings; } + get { return (this.ModuleContext == null) ? null : this.ModuleContext.PortalSettings; } } - public RouteCollection RouteCollection { get { return HtmlHelper.RouteCollection; } } + public RouteCollection RouteCollection + { + get { return this.HtmlHelper.RouteCollection; } + } - public UserInfo User + public string LocalizeString(string key) { - get { return (PortalSettings == null) ? null : PortalSettings.UserInfo; } + return Localization.GetString(key, this.LocalResourceFile); } - public dynamic ViewBag { get { return HtmlHelper.ViewBag; } } - - public ViewContext ViewContext { get { return HtmlHelper.ViewContext; } } - - public ViewDataDictionary ViewData { get { return HtmlHelper.ViewData; } } + public UserInfo User + { + get { return (this.PortalSettings == null) ? null : this.PortalSettings.UserInfo; } + } - public IViewDataContainer ViewDataContainer { get { return HtmlHelper.ViewDataContainer; } } + public dynamic ViewBag + { + get { return this.HtmlHelper.ViewBag; } + } + + public ViewContext ViewContext + { + get { return this.HtmlHelper.ViewContext; } + } + + public ViewDataDictionary ViewData + { + get { return this.HtmlHelper.ViewData; } + } + + public IViewDataContainer ViewDataContainer + { + get { return this.HtmlHelper.ViewDataContainer; } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelperOfT.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelperOfT.cs index 036d1669bf1..1580e253c20 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelperOfT.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelperOfT.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using System.Web.Routing; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ConvertPropertyToExpressionBody - namespace DotNetNuke.Web.Mvc.Helpers { + using System.Web.Mvc; + using System.Web.Routing; + public class DnnHelper : DnnHelper { - public DnnHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) + public DnnHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) : this(viewContext, viewDataContainer, RouteTable.Routes) { } @@ -22,7 +22,7 @@ public DnnHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, public new ViewDataDictionary ViewData { - get { return ((HtmlHelper)HtmlHelper).ViewData; } + get { return ((HtmlHelper)this.HtmlHelper).ViewData; } } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs index 82a2ec6fbe4..ef5d1819820 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Framework; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Framework; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public class DnnHtmlHelper { - public DnnHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) + public DnnHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) : this(viewContext, viewDataContainer, RouteTable.Routes) { } @@ -27,7 +28,7 @@ public DnnHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContain protected DnnHtmlHelper(HtmlHelper htmlHelper) { - HtmlHelper = htmlHelper; + this.HtmlHelper = htmlHelper; var controller = htmlHelper.ViewContext.Controller as IDnnController; @@ -36,58 +37,57 @@ protected DnnHtmlHelper(HtmlHelper htmlHelper) throw new InvalidOperationException("The DnnHtmlHelper class can only be used in Views that inherit from DnnWebViewPage"); } - ModuleContext = controller.ModuleContext; + this.ModuleContext = controller.ModuleContext; } + public ModuleInstanceContext ModuleContext { get; set; } + + public RouteCollection RouteCollection => this.HtmlHelper.RouteCollection; + + internal HtmlHelper HtmlHelper { get; set; } + public MvcHtmlString AntiForgeryToken() { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - return new MvcHtmlString(String.Empty); + return new MvcHtmlString(string.Empty); } - internal HtmlHelper HtmlHelper { get; set; } - - public ModuleInstanceContext ModuleContext { get; set; } - - public RouteCollection RouteCollection => HtmlHelper.RouteCollection; - - public dynamic ViewBag => HtmlHelper.ViewBag; - - public ViewContext ViewContext => HtmlHelper.ViewContext; + public dynamic ViewBag => this.HtmlHelper.ViewBag; - public ViewDataDictionary ViewData => HtmlHelper.ViewData; + public ViewContext ViewContext => this.HtmlHelper.ViewContext; - public IViewDataContainer ViewDataContainer => HtmlHelper.ViewDataContainer; + public ViewDataDictionary ViewData => this.HtmlHelper.ViewData; - public string AttributeEncode(string value) => HtmlHelper.AttributeEncode(value); + public IViewDataContainer ViewDataContainer => this.HtmlHelper.ViewDataContainer; - public string AttributeEncode(object value) => HtmlHelper.AttributeEncode(value); + public string AttributeEncode(string value) => this.HtmlHelper.AttributeEncode(value); - public string Encode(string value) => HtmlHelper.Encode(value); + public string AttributeEncode(object value) => this.HtmlHelper.AttributeEncode(value); - public string Encode(object value) => HtmlHelper.Encode(value); + public string Encode(string value) => this.HtmlHelper.Encode(value); - public string FormatValue(object value, string format) => HtmlHelper.FormatValue(value, format); + public string Encode(object value) => this.HtmlHelper.Encode(value); - public MvcHtmlString HttpMethodOverride(HttpVerbs httpVerb) => HtmlHelper.HttpMethodOverride(httpVerb); + public string FormatValue(object value, string format) => this.HtmlHelper.FormatValue(value, format); - public MvcHtmlString HttpMethodOverride(string httpVerb) => HtmlHelper.HttpMethodOverride(httpVerb); + public MvcHtmlString HttpMethodOverride(HttpVerbs httpVerb) => this.HtmlHelper.HttpMethodOverride(httpVerb); - public IHtmlString Raw(string value) => HtmlHelper.Raw(value); + public MvcHtmlString HttpMethodOverride(string httpVerb) => this.HtmlHelper.HttpMethodOverride(httpVerb); - public IHtmlString Raw(object value) => HtmlHelper.Raw(value); + public IHtmlString Raw(string value) => this.HtmlHelper.Raw(value); - public IDictionary GetUnobtrusiveValidationAttributes(string name) => HtmlHelper.GetUnobtrusiveValidationAttributes(name); + public IHtmlString Raw(object value) => this.HtmlHelper.Raw(value); - public IDictionary GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata) => HtmlHelper.GetUnobtrusiveValidationAttributes(name, metadata); + public IDictionary GetUnobtrusiveValidationAttributes(string name) => this.HtmlHelper.GetUnobtrusiveValidationAttributes(name); - public void EnableClientValidation() => HtmlHelper.EnableClientValidation(); + public IDictionary GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata) => this.HtmlHelper.GetUnobtrusiveValidationAttributes(name, metadata); - public void EnableClientValidation(bool enabled) => HtmlHelper.EnableClientValidation(enabled); + public void EnableClientValidation() => this.HtmlHelper.EnableClientValidation(); - public void EnableUnobtrusiveJavaScript() => HtmlHelper.EnableUnobtrusiveJavaScript(); + public void EnableClientValidation(bool enabled) => this.HtmlHelper.EnableClientValidation(enabled); - public void EnableUnobtrusiveJavaScript(bool enabled) => HtmlHelper.EnableUnobtrusiveJavaScript(enabled); + public void EnableUnobtrusiveJavaScript() => this.HtmlHelper.EnableUnobtrusiveJavaScript(); + public void EnableUnobtrusiveJavaScript(bool enabled) => this.HtmlHelper.EnableUnobtrusiveJavaScript(enabled); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs index 188d382ef99..9858e7b094e 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs @@ -1,29 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using System.Web.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System.Web.Mvc; + using System.Web.Routing; + public class DnnHtmlHelper : DnnHtmlHelper { - public DnnHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) + public DnnHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) : this(viewContext, viewDataContainer, RouteTable.Routes) { } public DnnHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection) : base(new HtmlHelper(viewContext, viewDataContainer, routeCollection)) - { } - internal new HtmlHelper HtmlHelper => (HtmlHelper)base.HtmlHelper; + public new object ViewBag => this.HtmlHelper.ViewBag; - public new object ViewBag => HtmlHelper.ViewBag; + public new ViewDataDictionary ViewData => this.HtmlHelper.ViewData; - public new ViewDataDictionary ViewData => HtmlHelper.ViewData; + internal new HtmlHelper HtmlHelper => (HtmlHelper)base.HtmlHelper; } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs index fbfd1b6ae2b..74e7c975a90 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Web.Mvc; + public static class DnnLabelExtensions { public static MvcHtmlString Label(this DnnHelper dnnHelper, string expression, string labelText, string helpText) @@ -26,12 +26,13 @@ public static MvcHtmlString Label(this DnnHelper dnnHelper, stri { var htmlHelper = dnnHelper.HtmlHelper as HtmlHelper; - return LabelHelper(htmlHelper, - ModelMetadata.FromStringExpression(expression, htmlHelper.ViewData), - expression, - labelText, - helpText, - htmlAttributes); + return LabelHelper( + htmlHelper, + ModelMetadata.FromStringExpression(expression, htmlHelper.ViewData), + expression, + labelText, + helpText, + htmlAttributes); } public static MvcHtmlString LabelFor(this DnnHelper dnnHelper, Expression> expression) @@ -78,26 +79,18 @@ public static MvcHtmlString LabelFor(this DnnHelper dnnH { var htmlHelper = dnnHelper.HtmlHelper as HtmlHelper; - return LabelHelper(htmlHelper, - ModelMetadata.FromLambdaExpression(expression, dnnHelper.ViewData), - ExpressionHelper.GetExpressionText(expression), - labelText, - helpText, - htmlAttributes); - } - - internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, string helpText = null, IDictionary htmlAttributes = null) - { - string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); - string resolvedHelpText = helpText ?? metadata.Description ?? metadata.Description ?? null; - string resolvedId = TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)); - - return LabelHelper(html, resolvedId, resolvedLabelText, resolvedHelpText, htmlAttributes); + return LabelHelper( + htmlHelper, + ModelMetadata.FromLambdaExpression(expression, dnnHelper.ViewData), + ExpressionHelper.GetExpressionText(expression), + labelText, + helpText, + htmlAttributes); } public static MvcHtmlString LabelHelper(HtmlHelper html, string htmlFieldName, string labelText, string helpText = null, IDictionary htmlAttributes = null) { - if (String.IsNullOrEmpty(labelText)) + if (string.IsNullOrEmpty(labelText)) { return MvcHtmlString.Empty; } @@ -145,9 +138,17 @@ public static MvcHtmlString LabelHelper(HtmlHelper html, string htmlFieldName, s toolTipTag.InnerHtml = toolTipContentTag.ToString(); divTag.InnerHtml += toolTipTag.ToString(); + + return new MvcHtmlString(divTag.ToString(TagRenderMode.Normal)); + } + internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, string helpText = null, IDictionary htmlAttributes = null) + { + string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); + string resolvedHelpText = helpText ?? metadata.Description ?? metadata.Description ?? null; + string resolvedId = TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)); - return new MvcHtmlString(divTag.ToString(TagRenderMode.Normal)); + return LabelHelper(html, resolvedId, resolvedLabelText, resolvedHelpText, htmlAttributes); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs index 18774e144a1..6b3e9acdaef 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs @@ -1,26 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Common; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Common; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Common; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Common; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Routing; + public class DnnUrlHelper { private readonly ViewContext _viewContext; private readonly IDnnController _controller; - public DnnUrlHelper(ViewContext viewContext) - : this(viewContext , RouteTable.Routes) + + public DnnUrlHelper(ViewContext viewContext) + : this(viewContext, RouteTable.Routes) { } @@ -29,33 +31,33 @@ public DnnUrlHelper(RequestContext requestContext, IDnnController controller) Requires.NotNull("requestContext", requestContext); Requires.NotNull("controller", controller); - UrlHelper = new UrlHelper(requestContext); - _controller = controller; - ModuleContext = _controller.ModuleContext; + this.UrlHelper = new UrlHelper(requestContext); + this._controller = controller; + this.ModuleContext = this._controller.ModuleContext; } public DnnUrlHelper(ViewContext viewContext, RouteCollection routeCollection) { Requires.NotNull("viewContext", viewContext); - UrlHelper = new UrlHelper(viewContext.RequestContext, routeCollection); - - _viewContext = viewContext; + this.UrlHelper = new UrlHelper(viewContext.RequestContext, routeCollection); + + this._viewContext = viewContext; - _controller = viewContext.Controller as IDnnController; + this._controller = viewContext.Controller as IDnnController; - if (_controller == null) + if (this._controller == null) { throw new InvalidOperationException("The DnnUrlHelper class can only be used in Views that inherit from DnnWebViewPage"); } - ModuleContext = _controller.ModuleContext; + this.ModuleContext = this._controller.ModuleContext; } - internal UrlHelper UrlHelper { get; set; } - public ModuleInstanceContext ModuleContext { get; set; } + internal UrlHelper UrlHelper { get; set; } + public virtual string Encode(string url) { return HttpUtility.UrlEncode(url); @@ -64,69 +66,69 @@ public virtual string Encode(string url) /// /// Converts a virtual (relative) path to an application absolute path. /// - /// + /// /// /// The application absolute path. /// /// The virtual path of the content. public virtual string Content(string contentPath) { - return UrlHelper.Content(contentPath); + return this.UrlHelper.Content(contentPath); } /// /// Returns a value that indicates whether the URL is local. /// - /// + /// /// /// true if the URL is local; otherwise, false. /// /// The URL. public virtual bool IsLocalUrl(string url) { - return UrlHelper.IsLocalUrl(url); + return this.UrlHelper.IsLocalUrl(url); } public virtual string Action() { - return UrlHelper.RequestContext.HttpContext.Request.RawUrl; + return this.UrlHelper.RequestContext.HttpContext.Request.RawUrl; } public virtual string Action(string actionName) { - return GenerateUrl(actionName, null, new RouteValueDictionary()); + return this.GenerateUrl(actionName, null, new RouteValueDictionary()); } public virtual string Action(string actionName, RouteValueDictionary routeValues) { - return GenerateUrl(actionName, null, routeValues); + return this.GenerateUrl(actionName, null, routeValues); } public virtual string Action(string actionName, object routeValues) { - return GenerateUrl(actionName, null, TypeHelper.ObjectToDictionary(routeValues)); + return this.GenerateUrl(actionName, null, TypeHelper.ObjectToDictionary(routeValues)); } public virtual string Action(string actionName, string controllerName) { - return GenerateUrl(actionName, controllerName, new RouteValueDictionary()); + return this.GenerateUrl(actionName, controllerName, new RouteValueDictionary()); } public virtual string Action(string actionName, string controllerName, RouteValueDictionary routeValues) { - return GenerateUrl(actionName, controllerName, routeValues); + return this.GenerateUrl(actionName, controllerName, routeValues); } public virtual string Action(string actionName, string controllerName, object routeValues) { - return GenerateUrl(actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues)); + return this.GenerateUrl(actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues)); } private string GenerateUrl(string actionName, string controllerName, RouteValueDictionary routeValues) { - routeValues["controller"] = controllerName ?? _controller.ControllerContext?.RouteData.Values["controller"]; + routeValues["controller"] = controllerName ?? this._controller.ControllerContext?.RouteData.Values["controller"]; routeValues["action"] = actionName; - return ModuleRoutingProvider.Instance().GenerateUrl(routeValues, ModuleContext); + return ModuleRoutingProvider.Instance().GenerateUrl(routeValues, this.ModuleContext); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayExtensions.cs index 1ffe50c22f1..dcfad7f22d9 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayExtensions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Represents support for rendering object values as HTML. /// @@ -18,7 +18,7 @@ public static class HtmlDisplayExtensions /// /// Returns HTML markup for each property in the object that is represented by a string expression. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -31,7 +31,7 @@ public static MvcHtmlString Display(this DnnHtmlHelper html, string expression) /// /// Returns HTML markup for each property in the object that is represented by a string expression, using additional view data. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -44,7 +44,7 @@ public static MvcHtmlString Display(this DnnHtmlHelper html, string expression, /// /// Returns HTML markup for each property in the object that is represented by the expression, using the specified template. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -57,7 +57,7 @@ public static MvcHtmlString Display(this DnnHtmlHelper html, string expression, /// /// Returns HTML markup for each property in the object that is represented by the expression, using the specified template and additional view data. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -70,7 +70,7 @@ public static MvcHtmlString Display(this DnnHtmlHelper html, string expression, /// /// Returns HTML markup for each property in the object that is represented by the expression, using the specified template and an HTML field ID. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -83,7 +83,7 @@ public static MvcHtmlString Display(this DnnHtmlHelper html, string expression, /// /// Returns HTML markup for each property in the object that is represented by the expression, using the specified template, HTML field ID, and additional view data. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -96,7 +96,7 @@ public static MvcHtmlString Display(this DnnHtmlHelper html, string expression, /// /// Returns HTML markup for each property in the object that is represented by the expression. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -109,7 +109,7 @@ public static MvcHtmlString DisplayFor(this DnnHtmlHelper /// Returns a string that contains each property value in the object that is represented by the specified expression, using additional view data. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -122,7 +122,7 @@ public static MvcHtmlString DisplayFor(this DnnHtmlHelper /// Returns a string that contains each property value in the object that is represented by the , using the specified template. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -135,7 +135,7 @@ public static MvcHtmlString DisplayFor(this DnnHtmlHelper /// Returns a string that contains each property value in the object that is represented by the specified expression, using the specified template and additional view data. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -148,7 +148,7 @@ public static MvcHtmlString DisplayFor(this DnnHtmlHelper /// Returns HTML markup for each property in the object that is represented by the , using the specified template and an HTML field ID. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -161,7 +161,7 @@ public static MvcHtmlString DisplayFor(this DnnHtmlHelper /// Returns HTML markup for each property in the object that is represented by the specified expression, using the template, an HTML field ID, and additional view data. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -174,20 +174,20 @@ public static MvcHtmlString DisplayFor(this DnnHtmlHelper /// Returns HTML markup for each property in the model. /// - /// + /// /// /// The HTML markup for each property in the model. /// /// The HTML helper instance that this method extends. public static MvcHtmlString DisplayForModel(this DnnHtmlHelper html) { - return html.HtmlHelper.DisplayForModel( html.ViewData.ModelMetadata); + return html.HtmlHelper.DisplayForModel(html.ViewData.ModelMetadata); } /// /// Returns HTML markup for each property in the model, using additional view data. /// - /// + /// /// /// The HTML markup for each property in the model. /// @@ -200,7 +200,7 @@ public static MvcHtmlString DisplayForModel(this DnnHtmlHelper html, object addi /// /// Returns HTML markup for each property in the model using the specified template. /// - /// + /// /// /// The HTML markup for each property in the model. /// @@ -213,7 +213,7 @@ public static MvcHtmlString DisplayForModel(this DnnHtmlHelper html, string temp /// /// Returns HTML markup for each property in the model, using the specified template and additional view data. /// - /// + /// /// /// The HTML markup for each property in the model. /// @@ -226,7 +226,7 @@ public static MvcHtmlString DisplayForModel(this DnnHtmlHelper html, string temp /// /// Returns HTML markup for each property in the model using the specified template and HTML field ID. /// - /// + /// /// /// The HTML markup for each property in the model. /// @@ -239,7 +239,7 @@ public static MvcHtmlString DisplayForModel(this DnnHtmlHelper html, string temp /// /// Returns HTML markup for each property in the model, using the specified template, an HTML field ID, and additional view data. /// - /// + /// /// /// The HTML markup for each property in the model. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayNameExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayNameExtensions.cs index d10387f4e9c..24ab99da67b 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayNameExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayNameExtensions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Provides a mechanism to get display names. /// @@ -18,7 +18,7 @@ public static class HtmlDisplayNameExtensions /// /// Gets the display name. /// - /// + /// /// /// The display name. /// @@ -31,7 +31,7 @@ public static MvcHtmlString DisplayName(this DnnHtmlHelper html, string expressi /// /// Gets the display name for the model. /// - /// + /// /// /// The display name for the model. /// @@ -44,7 +44,7 @@ public static MvcHtmlString DisplayNameFor(this DnnHtmlHelper /// Gets the display name for the model. /// - /// + /// /// /// The display name for the model. /// @@ -57,7 +57,7 @@ public static MvcHtmlString DisplayNameFor(this DnnHtmlHelper /// Gets the display name for the model. /// - /// + /// /// /// The display name for the model. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayTextExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayTextExtensions.cs index 07de19f797a..881e2912cc3 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayTextExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlDisplayTextExtensions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Provides a way to render object values as HTML. /// @@ -18,7 +18,7 @@ public static class HtmlDisplayTextExtensions /// /// Returns HTML markup for each property in the object that is represented by the specified expression. /// - /// + /// /// /// The HTML markup for each property in the object that is represented by the expression. /// @@ -31,7 +31,7 @@ public static MvcHtmlString DisplayText(this DnnHtmlHelper html, string name) /// /// Returns HTML markup for each property in the object that is represented by the specified expression. /// - /// + /// /// /// The HTML markup for each property. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs index 259f44a6411..f0a13707144 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Represents support for the HTML input element in an application. /// @@ -17,7 +17,7 @@ public static class HtmlEditorExtensions /// /// Returns an HTML input element for each property in the object that is represented by the expression. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -30,20 +30,20 @@ public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression) /// /// Returns an HTML input element for each property in the object that is represented by the expression, using additional view data. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// /// The HTML helper instance that this method extends.An expression that identifies the object that contains the properties to display.An anonymous object that can contain additional view data that will be merged into the instance that is created for the template. public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression, object additionalViewData) { - return html.HtmlHelper.Editor(expression, additionalViewData); + return html.HtmlHelper.Editor(expression, additionalViewData); } /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -56,7 +56,7 @@ public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression, s /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and additional view data. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -69,7 +69,7 @@ public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression, s /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and HTML field name. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -82,7 +82,7 @@ public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression, s /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -95,7 +95,7 @@ public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression, s /// /// Returns an HTML input element for each property in the object that is represented by the expression. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -108,7 +108,7 @@ public static MvcHtmlString EditorFor(this DnnHtmlHelper /// /// Returns an HTML input element for each property in the object that is represented by the expression, using additional view data. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -121,7 +121,7 @@ public static MvcHtmlString EditorFor(this DnnHtmlHelper /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -134,7 +134,7 @@ public static MvcHtmlString EditorFor(this DnnHtmlHelper /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and additional view data. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -147,7 +147,7 @@ public static MvcHtmlString EditorFor(this DnnHtmlHelper /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template and HTML field name. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -160,7 +160,7 @@ public static MvcHtmlString EditorFor(this DnnHtmlHelper /// /// Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data. /// - /// + /// /// /// An HTML input element for each property in the object that is represented by the expression. /// @@ -173,7 +173,7 @@ public static MvcHtmlString EditorFor(this DnnHtmlHelper /// /// Returns an HTML input element for each property in the model. /// - /// + /// /// /// An HTML input element for each property in the model. /// @@ -186,7 +186,7 @@ public static MvcHtmlString EditorForModel(this DnnHtmlHelper html) /// /// Returns an HTML input element for each property in the model, using additional view data. /// - /// + /// /// /// An HTML input element for each property in the model. /// @@ -199,7 +199,7 @@ public static MvcHtmlString EditorForModel(this DnnHtmlHelper html, object addit /// /// Returns an HTML input element for each property in the model, using the specified template. /// - /// + /// /// /// An HTML input element for each property in the model and in the specified template. /// @@ -212,7 +212,7 @@ public static MvcHtmlString EditorForModel(this DnnHtmlHelper html, string templ /// /// Returns an HTML input element for each property in the model, using the specified template and additional view data. /// - /// + /// /// /// An HTML input element for each property in the model. /// @@ -225,7 +225,7 @@ public static MvcHtmlString EditorForModel(this DnnHtmlHelper html, string templ /// /// Returns an HTML input element for each property in the model, using the specified template name and HTML field name. /// - /// + /// /// /// An HTML input element for each property in the model and in the named template. /// @@ -238,7 +238,7 @@ public static MvcHtmlString EditorForModel(this DnnHtmlHelper html, string templ /// /// Returns an HTML input element for each property in the model, using the template name, HTML field name, and additional view data. /// - /// + /// /// /// An HTML input element for each property in the model. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlInputExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlInputExtensions.cs index 444f12db005..5f7408fbb9c 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlInputExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlInputExtensions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Represents support for HTML input controls in an application. /// @@ -20,7 +20,7 @@ public static class HtmlInputExtensions /// /// Returns a check box input element by using the specified HTML helper and the name of the form field. /// - /// + /// /// /// An input element whose type attribute is set to "checkbox". /// @@ -33,7 +33,7 @@ public static MvcHtmlString CheckBox(this DnnHtmlHelper html, string name) /// /// Returns a check box input element by using the specified HTML helper, the name of the form field, and a value to indicate whether the check box is selected. /// - /// + /// /// /// An input element whose type attribute is set to "checkbox". /// @@ -46,7 +46,7 @@ public static MvcHtmlString CheckBox(this DnnHtmlHelper html, string name, bool /// /// Returns a check box input element by using the specified HTML helper, the name of the form field, a value that indicates whether the check box is selected, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "checkbox". /// @@ -59,7 +59,7 @@ public static MvcHtmlString CheckBox(this DnnHtmlHelper html, string name, bool /// /// Returns a check box input element by using the specified HTML helper, the name of the form field, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "checkbox". /// @@ -72,7 +72,7 @@ public static MvcHtmlString CheckBox(this DnnHtmlHelper html, string name, objec /// /// Returns a check box input element by using the specified HTML helper, the name of the form field, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "checkbox". /// @@ -85,7 +85,7 @@ public static MvcHtmlString CheckBox(this DnnHtmlHelper html, string name, IDict /// /// Returns a check box input element by using the specified HTML helper, the name of the form field, a value to indicate whether the check box is selected, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "checkbox". /// @@ -98,7 +98,7 @@ public static MvcHtmlString CheckBox(this DnnHtmlHelper html, string name, bool /// /// Returns a check box input element for each property in the object that is represented by the specified expression. /// - /// + /// /// /// An HTML input element whose type attribute is set to "checkbox" for each property in the object that is represented by the specified expression. /// @@ -111,7 +111,7 @@ public static MvcHtmlString CheckBoxFor(this DnnHtmlHelper html, /// /// Returns a check box input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element whose type attribute is set to "checkbox" for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// @@ -124,7 +124,7 @@ public static MvcHtmlString CheckBoxFor(this DnnHtmlHelper html, /// /// Returns a check box input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element whose type attribute is set to "checkbox" for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// @@ -139,7 +139,7 @@ public static MvcHtmlString CheckBoxFor(this DnnHtmlHelper html, /// /// Returns a hidden input element by using the specified HTML helper and the name of the form field. /// - /// + /// /// /// An input element whose type attribute is set to "hidden". /// @@ -152,7 +152,7 @@ public static MvcHtmlString Hidden(this DnnHtmlHelper html, string name) /// /// Returns a hidden input element by using the specified HTML helper, the name of the form field, and the value. /// - /// + /// /// /// An input element whose type attribute is set to "hidden". /// @@ -165,7 +165,7 @@ public static MvcHtmlString Hidden(this DnnHtmlHelper html, string name, object /// /// Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "hidden". /// @@ -178,7 +178,7 @@ public static MvcHtmlString Hidden(this DnnHtmlHelper html, string name, object /// /// Returns a hidden input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "hidden". /// @@ -191,7 +191,7 @@ public static MvcHtmlString Hidden(this DnnHtmlHelper html, string name, object /// /// Returns an HTML hidden input element for each property in the object that is represented by the specified expression. /// - /// + /// /// /// An input element whose type attribute is set to "hidden" for each property in the object that is represented by the expression. /// @@ -204,7 +204,7 @@ public static MvcHtmlString HiddenFor(this DnnHtmlHelper /// Returns an HTML hidden input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "hidden" for each property in the object that is represented by the expression. /// @@ -217,7 +217,7 @@ public static MvcHtmlString HiddenFor(this DnnHtmlHelper /// Returns an HTML hidden input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "hidden" for each property in the object that is represented by the expression. /// @@ -232,7 +232,7 @@ public static MvcHtmlString HiddenFor(this DnnHtmlHelper /// Returns a password input element by using the specified HTML helper and the name of the form field. /// - /// + /// /// /// An input element whose type attribute is set to "password". /// @@ -245,7 +245,7 @@ public static MvcHtmlString Password(this DnnHtmlHelper html, string name) /// /// Returns a password input element by using the specified HTML helper, the name of the form field, and the value. /// - /// + /// /// /// An input element whose type attribute is set to "password". /// @@ -258,7 +258,7 @@ public static MvcHtmlString Password(this DnnHtmlHelper html, string name, objec /// /// Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "password". /// @@ -271,7 +271,7 @@ public static MvcHtmlString Password(this DnnHtmlHelper html, string name, objec /// /// Returns a password input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "password". /// @@ -284,7 +284,7 @@ public static MvcHtmlString Password(this DnnHtmlHelper html, string name, objec /// /// Returns a password input element for each property in the object that is represented by the specified expression. /// - /// + /// /// /// An HTML input element whose type attribute is set to "password" for each property in the object that is represented by the specified expression. /// @@ -297,7 +297,7 @@ public static MvcHtmlString PasswordFor(this DnnHtmlHelper /// Returns a password input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element whose type attribute is set to "password" for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// @@ -310,7 +310,7 @@ public static MvcHtmlString PasswordFor(this DnnHtmlHelper /// Returns a password input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element whose type attribute is set to "password" for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// @@ -325,7 +325,7 @@ public static MvcHtmlString PasswordFor(this DnnHtmlHelper /// Returns a radio button input element that is used to present mutually exclusive options. /// - /// + /// /// /// An input element whose type attribute is set to "radio". /// @@ -338,7 +338,7 @@ public static MvcHtmlString RadioButton(this DnnHtmlHelper html, string name, ob /// /// Returns a radio button input element that is used to present mutually exclusive options. /// - /// + /// /// /// An input element whose type attribute is set to "radio". /// @@ -351,7 +351,7 @@ public static MvcHtmlString RadioButton(this DnnHtmlHelper html, string name, ob /// /// Returns a radio button input element that is used to present mutually exclusive options. /// - /// + /// /// /// An input element whose type attribute is set to "radio". /// @@ -364,7 +364,7 @@ public static MvcHtmlString RadioButton(this DnnHtmlHelper html, string name, ob /// /// Returns a radio button input element that is used to present mutually exclusive options. /// - /// + /// /// /// An input element whose type attribute is set to "radio". /// @@ -377,7 +377,7 @@ public static MvcHtmlString RadioButton(this DnnHtmlHelper html, string name, ob /// /// Returns a radio button input element that is used to present mutually exclusive options. /// - /// + /// /// /// An input element whose type attribute is set to "radio". /// @@ -390,7 +390,7 @@ public static MvcHtmlString RadioButton(this DnnHtmlHelper html, string name, ob /// /// Returns a radio button input element that is used to present mutually exclusive options. /// - /// + /// /// /// An input element whose type attribute is set to "radio". /// @@ -403,7 +403,7 @@ public static MvcHtmlString RadioButton(this DnnHtmlHelper html, string name, ob /// /// Returns a radio button input element for each property in the object that is represented by the specified expression. /// - /// + /// /// /// An HTML input element whose type attribute is set to "radio" for each property in the object that is represented by the specified expression. /// @@ -416,7 +416,7 @@ public static MvcHtmlString RadioButtonFor(this DnnHtmlHelper /// /// Returns a radio button input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element whose type attribute is set to "radio" for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// @@ -429,7 +429,7 @@ public static MvcHtmlString RadioButtonFor(this DnnHtmlHelper /// /// Returns a radio button input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element whose type attribute is set to "radio" for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// @@ -444,7 +444,7 @@ public static MvcHtmlString RadioButtonFor(this DnnHtmlHelper /// /// Returns a text input element by using the specified HTML helper and the name of the form field. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -457,7 +457,7 @@ public static MvcHtmlString TextBox(this DnnHtmlHelper html, string name) /// /// Returns a text input element by using the specified HTML helper, the name of the form field, and the value. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -470,7 +470,7 @@ public static MvcHtmlString TextBox(this DnnHtmlHelper html, string name, object /// /// Returns a text input element. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -483,7 +483,7 @@ public static MvcHtmlString TextBox(this DnnHtmlHelper html, string name, object /// /// Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -496,7 +496,7 @@ public static MvcHtmlString TextBox(this DnnHtmlHelper html, string name, object /// /// Returns a text input element. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -509,7 +509,7 @@ public static MvcHtmlString TextBox(this DnnHtmlHelper html, string name, object /// /// Returns a text input element by using the specified HTML helper, the name of the form field, the value, and the HTML attributes. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -522,7 +522,7 @@ public static MvcHtmlString TextBox(this DnnHtmlHelper html, string name, object /// /// Returns a text input element. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -535,7 +535,7 @@ public static MvcHtmlString TextBox(this DnnHtmlHelper html, string name, object /// /// Returns a text input element for each property in the object that is represented by the specified expression. /// - /// + /// /// /// An HTML input element whose type attribute is set to "text" for each property in the object that is represented by the expression. /// @@ -548,7 +548,7 @@ public static MvcHtmlString TextBoxFor(this DnnHtmlHelper /// Returns a text input element. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -561,7 +561,7 @@ public static MvcHtmlString TextBoxFor(this DnnHtmlHelper /// Returns a text input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element whose type attribute is set to "text" for each property in the object that is represented by the expression. /// @@ -574,7 +574,7 @@ public static MvcHtmlString TextBoxFor(this DnnHtmlHelper /// Returns a text input element. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// @@ -587,7 +587,7 @@ public static MvcHtmlString TextBoxFor(this DnnHtmlHelper /// Returns a text input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. /// - /// + /// /// /// An HTML input element type attribute is set to "text" for each property in the object that is represented by the expression. /// @@ -600,7 +600,7 @@ public static MvcHtmlString TextBoxFor(this DnnHtmlHelper /// Returns a text input element. /// - /// + /// /// /// An input element whose type attribute is set to "text". /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs index 52ed5f84ee7..a0cfddb4005 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Represents support for the HTML label element in an ASP.NET MVC view. /// @@ -18,12 +18,12 @@ public static class HtmlLabelExtensions /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// /// The HTML helper instance that this method extends.An expression that identifies the property to display. - public static MvcHtmlString Label(this DnnHtmlHelper html,string expression) + public static MvcHtmlString Label(this DnnHtmlHelper html, string expression) { return html.HtmlHelper.Label(expression); } @@ -31,12 +31,12 @@ public static MvcHtmlString Label(this DnnHtmlHelper html,string expression) /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// /// The HTML helper instance that this method extends.An expression that identifies the property to display.The label text to display. - public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, string labelText) + public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, string labelText) { return html.HtmlHelper.Label(expression, labelText); } @@ -44,38 +44,38 @@ public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, str /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// /// The HTML helper instance that this method extends.An expression that identifies the property to display.An object that contains the HTML attributes to set for the element. - public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, object htmlAttributes) + public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, object htmlAttributes) { - return html.HtmlHelper.Label(expression, htmlAttributes); + return html.HtmlHelper.Label(expression, htmlAttributes); } /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// /// The HTML helper instance that this method extends.An expression that identifies the property to display.An object that contains the HTML attributes to set for the element. - public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, IDictionary htmlAttributes) + public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, IDictionary htmlAttributes) { - return html.HtmlHelper.Label(expression, htmlAttributes); + return html.HtmlHelper.Label(expression, htmlAttributes); } /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// /// The HTML helper instance that this method extends.An expression that identifies the property to display.The label text.An object that contains the HTML attributes to set for the element. - public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, string labelText, object htmlAttributes) + public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, string labelText, object htmlAttributes) { return html.HtmlHelper.Label(expression, labelText, htmlAttributes); } @@ -83,12 +83,12 @@ public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, str /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// /// The HTML helper instance that this method extends.An expression that identifies the property to display.The label text.An object that contains the HTML attributes to set for the element. - public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, string labelText, IDictionary htmlAttributes) + public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, string labelText, IDictionary htmlAttributes) { return html.HtmlHelper.Label(expression, labelText, htmlAttributes); } @@ -96,7 +96,7 @@ public static MvcHtmlString Label(this DnnHtmlHelper html,string expression, str /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -110,7 +110,7 @@ public static MvcHtmlString LabelFor(this DnnHtmlHelper /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -123,7 +123,7 @@ public static MvcHtmlString LabelFor(this DnnHtmlHelper /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -136,7 +136,7 @@ public static MvcHtmlString LabelFor(this DnnHtmlHelper /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -149,7 +149,7 @@ public static MvcHtmlString LabelFor(this DnnHtmlHelper /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -162,7 +162,7 @@ public static MvcHtmlString LabelFor(this DnnHtmlHelper /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -175,7 +175,7 @@ public static MvcHtmlString LabelFor(this DnnHtmlHelper /// /// Returns an HTML label element and the property name of the property that is represented by the model. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the model. /// @@ -188,7 +188,7 @@ public static MvcHtmlString LabelForModel(this DnnHtmlHelper html) /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -201,7 +201,7 @@ public static MvcHtmlString LabelForModel(this DnnHtmlHelper html, string labelT /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -214,7 +214,7 @@ public static MvcHtmlString LabelForModel(this DnnHtmlHelper html, object htmlAt /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -227,7 +227,7 @@ public static MvcHtmlString LabelForModel(this DnnHtmlHelper html, IDictionary /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// @@ -240,7 +240,7 @@ public static MvcHtmlString LabelForModel(this DnnHtmlHelper html, string labelT /// /// Returns an HTML label element and the property name of the property that is represented by the specified expression. /// - /// + /// /// /// An HTML label element and the property name of the property that is represented by the expression. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLinkExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLinkExtensions.cs index 6602985dfa5..fc1b43d8ede 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLinkExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLinkExtensions.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common; -using DotNetNuke.Web.Mvc.Common; -using System; -using System.Collections.Generic; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Common; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Common; + using DotNetNuke.Web.Mvc.Routing; + public static class HtmlLinkExtensions { public static MvcHtmlString ActionLink(this DnnHtmlHelper htmlHelper, string linkText, string actionName) @@ -78,7 +79,7 @@ private static string GenerateLink(string linkText, string actionName, string co TagBuilder tagBuilder = new TagBuilder("a") { - InnerHtml = (!String.IsNullOrEmpty(linkText)) ? HttpUtility.HtmlEncode(linkText) : String.Empty + InnerHtml = (!string.IsNullOrEmpty(linkText)) ? HttpUtility.HtmlEncode(linkText) : string.Empty, }; tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("href", url); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlNameExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlNameExtensions.cs index 71044b242af..192042cad76 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlNameExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlNameExtensions.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Gets the HTML ID and name attributes of the string. /// @@ -17,7 +17,7 @@ public static class HtmlNameExtensions /// /// Gets the ID of the string. /// - /// + /// /// /// The HTML ID attribute value for the object that is represented by the expression. /// @@ -28,9 +28,9 @@ public static MvcHtmlString Id(this DnnHtmlHelper html, string name) } /// - /// Gets the ID of the string + /// Gets the ID of the string. /// - /// + /// /// /// The HTML ID attribute value for the object that is represented by the expression. /// @@ -43,7 +43,7 @@ public static MvcHtmlString IdFor(this DnnHtmlHelper /// /// Gets the ID of the string. /// - /// + /// /// /// The HTML ID attribute value for the object that is represented by the expression. /// @@ -56,7 +56,7 @@ public static MvcHtmlString IdForModel(this DnnHtmlHelper html) /// /// Gets the full HTML field name for the object that is represented by the expression. /// - /// + /// /// /// The full HTML field name for the object that is represented by the expression. /// @@ -69,7 +69,7 @@ public static MvcHtmlString Name(this DnnHtmlHelper html, string name) /// /// Gets the full HTML field name for the object that is represented by the expression. /// - /// + /// /// /// The full HTML field name for the object that is represented by the expression. /// @@ -82,7 +82,7 @@ public static MvcHtmlString NameFor(this DnnHtmlHelper /// Gets the full HTML field name for the object that is represented by the expression. /// - /// + /// /// /// The full HTML field name for the object that is represented by the expression. /// @@ -91,6 +91,5 @@ public static MvcHtmlString NameForModel(this DnnHtmlHelper html) { return html.HtmlHelper.NameForModel(); } - } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlPartialExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlPartialExtensions.cs index a0fe4a8b9fe..b7c1b91e2d1 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlPartialExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlPartialExtensions.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Represents the functionality to render a partial view as an HTML-encoded string. /// @@ -15,7 +15,7 @@ public static class HtmlPartialExtensions /// /// Renders the specified partial view as an HTML-encoded string. /// - /// + /// /// /// The partial view that is rendered as an HTML-encoded string. /// @@ -28,20 +28,20 @@ public static MvcHtmlString Partial(this DnnHtmlHelper html, string partialViewN /// /// Renders the specified partial view as an HTML-encoded string. /// - /// + /// /// /// The partial view that is rendered as an HTML-encoded string. /// /// The HTML helper instance that this method extends.The name of the partial view to render.The view data dictionary for the partial view. public static MvcHtmlString Partial(this DnnHtmlHelper html, string partialViewName, ViewDataDictionary viewData) { - return html.HtmlHelper.Partial(partialViewName, (object) null, viewData); + return html.HtmlHelper.Partial(partialViewName, (object)null, viewData); } /// /// Renders the specified partial view as an HTML-encoded string. /// - /// + /// /// /// The partial view that is rendered as an HTML-encoded string. /// @@ -54,7 +54,7 @@ public static MvcHtmlString Partial(this DnnHtmlHelper html, string partialViewN /// /// Renders the specified partial view as an HTML-encoded string. /// - /// + /// /// /// The partial view that is rendered as an HTML-encoded string. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlRenderPartialExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlRenderPartialExtensions.cs index 07c4bba7177..cfd2771080c 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlRenderPartialExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlRenderPartialExtensions.cs @@ -1,23 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Web.Mvc; + using System.Web.Mvc.Html; + public static class HtmlRenderPartialExtensions { /// /// Renders the specified partial view by using the specified HTML helper. /// - /// The HTML helper.The name of the partial view + /// The HTML helper.The name of the partial view. public static void RenderPartial(this DnnHtmlHelper html, string partialViewName) { html.HtmlHelper.RenderPartial(partialViewName, html.HtmlHelper.ViewData); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlSelectExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlSelectExtensions.cs index 479ff4791b5..479d7543aa0 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlSelectExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlSelectExtensions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Represents support for making selections in a list. /// @@ -20,7 +20,7 @@ public static class HtmlSelectExtensions /// /// Returns a single-selection select element using the specified HTML helper and the name of the form field. /// - /// + /// /// /// An HTML select element. /// @@ -33,7 +33,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name) /// /// Returns a single-selection select element using the specified HTML helper, the name of the form field, and an option label. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -46,7 +46,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name, s /// /// Returns a single-selection select element using the specified HTML helper, the name of the form field, and the specified list items. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -59,7 +59,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name, I /// /// Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -72,7 +72,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name, I /// /// Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HTML attributes. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -85,7 +85,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name, I /// /// Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, and an option label. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -98,7 +98,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name, I /// /// Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -111,7 +111,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name, I /// /// Returns a single-selection select element using the specified HTML helper, the name of the form field, the specified list items, an option label, and the specified HTML attributes. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -124,7 +124,7 @@ public static MvcHtmlString DropDownList(this DnnHtmlHelper html, string name, I /// /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -137,7 +137,7 @@ public static MvcHtmlString DropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -150,7 +150,7 @@ public static MvcHtmlString DropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -163,7 +163,7 @@ public static MvcHtmlString DropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items and option label. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -176,7 +176,7 @@ public static MvcHtmlString DropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items, option label, and HTML attributes. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -189,7 +189,7 @@ public static MvcHtmlString DropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items, option label, and HTML attributes. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -202,7 +202,7 @@ public static MvcHtmlString DropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each value in the enumeration that is represented by the specified expression. /// - /// + /// /// /// An HTML select element for each value in the enumeration that is represented by the expression. /// @@ -215,7 +215,7 @@ public static MvcHtmlString EnumDropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each value in the enumeration that is represented by the specified expression. /// - /// + /// /// /// An HTML select element for each value in the enumeration that is represented by the expression. /// @@ -228,7 +228,7 @@ public static MvcHtmlString EnumDropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each value in the enumeration that is represented by the specified expression. /// - /// + /// /// /// An HTML select element for each value in the enumeration that is represented by the expression. /// @@ -241,7 +241,7 @@ public static MvcHtmlString EnumDropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each value in the enumeration that is represented by the specified expression. /// - /// + /// /// /// An HTML select element for each value in the enumeration that is represented by the expression. /// @@ -254,7 +254,7 @@ public static MvcHtmlString EnumDropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each value in the enumeration that is represented by the specified expression. /// - /// + /// /// /// An HTML select element for each value in the enumeration that is represented by the expression. /// @@ -267,7 +267,7 @@ public static MvcHtmlString EnumDropDownListFor(this DnnHtmlHelpe /// /// Returns an HTML select element for each value in the enumeration that is represented by the specified expression. /// - /// + /// /// /// An HTML select element for each value in the enumeration that is represented by the expression. /// @@ -282,7 +282,7 @@ public static MvcHtmlString EnumDropDownListFor(this DnnHtmlHelpe /// /// Returns a multi-select select element using the specified HTML helper and the name of the form field. /// - /// + /// /// /// An HTML select element. /// @@ -295,7 +295,7 @@ public static MvcHtmlString ListBox(this DnnHtmlHelper html, string name) /// /// Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list. /// @@ -308,7 +308,7 @@ public static MvcHtmlString ListBox(this DnnHtmlHelper html, string name, IEnume /// /// Returns a multi-select select element using the specified HTML helper, the name of the form field, and the specified list items. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list.. /// @@ -321,7 +321,7 @@ public static MvcHtmlString ListBox(this DnnHtmlHelper html, string name, IEnume /// /// Returns a multi-select select element using the specified HTML helper, the name of the form field, the specified list items, and the specified HMTL attributes. /// - /// + /// /// /// An HTML select element with an option subelement for each item in the list.. /// @@ -334,7 +334,7 @@ public static MvcHtmlString ListBox(this DnnHtmlHelper html, string name, IEnume /// /// Returns an HTML select element for each property in the object that is represented by the specified expression and using the specified list items. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -347,7 +347,7 @@ public static MvcHtmlString ListBoxFor(this DnnHtmlHelper /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -360,7 +360,7 @@ public static MvcHtmlString ListBoxFor(this DnnHtmlHelper /// Returns an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes. /// - /// + /// /// /// An HTML select element for each property in the object that is represented by the expression. /// @@ -369,6 +369,5 @@ public static MvcHtmlString ListBoxFor(this DnnHtmlHelper /// Provides support for validating the input from an HTML form. /// @@ -41,7 +41,7 @@ public static void ValidateFor(this DnnHtmlHelper htm /// /// Displays a validation message if an error exists for the specified field in the object. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -54,7 +54,7 @@ public static MvcHtmlString ValidationMessage(this DnnHtmlHelper html, string mo /// /// Displays a validation message if an error exists for the specified field in the object. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -67,7 +67,7 @@ public static MvcHtmlString ValidationMessage(this DnnHtmlHelper html, string mo /// /// Displays a validation message if an error exists for the specified field in the object. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -80,7 +80,7 @@ public static MvcHtmlString ValidationMessage(this DnnHtmlHelper html, string mo /// /// Displays a validation message if an error exists for the specified field in the object. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -93,7 +93,7 @@ public static MvcHtmlString ValidationMessage(this DnnHtmlHelper html, string mo /// /// Displays a validation message if an error exists for the specified field in the object. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -106,7 +106,7 @@ public static MvcHtmlString ValidationMessage(this DnnHtmlHelper html, string mo /// /// Displays a validation message if an error exists for the specified field in the object. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -119,7 +119,7 @@ public static MvcHtmlString ValidationMessage(this DnnHtmlHelper html, string mo /// /// Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -133,7 +133,7 @@ public static MvcHtmlString ValidationMessageFor(this DnnHtml /// /// Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -147,7 +147,7 @@ public static MvcHtmlString ValidationMessageFor(this DnnHtml /// /// Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message and HTML attributes. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -161,7 +161,7 @@ public static MvcHtmlString ValidationMessageFor(this DnnHtml /// /// Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message and HTML attributes. /// - /// + /// /// /// If the property or object is valid, an empty string; otherwise, a span element that contains an error message. /// @@ -177,7 +177,7 @@ public static MvcHtmlString ValidationMessageFor(this DnnHtml /// /// Returns an unordered list (ul element) of validation messages that are in the object. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// @@ -190,7 +190,7 @@ public static MvcHtmlString ValidationSummary(this DnnHtmlHelper html) /// /// Returns an unordered list (ul element) of validation messages that are in the object and optionally displays only model-level errors. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// @@ -203,7 +203,7 @@ public static MvcHtmlString ValidationSummary(this DnnHtmlHelper html, bool excl /// /// Returns an unordered list (ul element) of validation messages that are in the object. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// @@ -216,7 +216,7 @@ public static MvcHtmlString ValidationSummary(this DnnHtmlHelper html, string me /// /// Returns an unordered list (ul element) of validation messages that are in the object and optionally displays only model-level errors. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// @@ -229,7 +229,7 @@ public static MvcHtmlString ValidationSummary(this DnnHtmlHelper html, bool excl /// /// Returns an unordered list (ul element) of validation messages in the object. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// @@ -242,7 +242,7 @@ public static MvcHtmlString ValidationSummary(this DnnHtmlHelper html, string me /// /// Returns an unordered list (ul element) of validation messages that are in the object and optionally displays only model-level errors. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// @@ -255,7 +255,7 @@ public static MvcHtmlString ValidationSummary(this DnnHtmlHelper html, bool excl /// /// Returns an unordered list (ul element) of validation messages that are in the object. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// @@ -268,7 +268,7 @@ public static MvcHtmlString ValidationSummary(this DnnHtmlHelper html, string me /// /// Returns an unordered list (ul element) of validation messages that are in the object and optionally displays only model-level errors. /// - /// + /// /// /// A string that contains an unordered list (ul element) of validation messages. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlValueExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlValueExtensions.cs index d2f6e0f7133..b7f81f81a07 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlValueExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlValueExtensions.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq.Expressions; -using System.Web.Mvc; -using System.Web.Mvc.Html; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Helpers { + using System; + using System.Linq.Expressions; + using System.Web.Mvc; + using System.Web.Mvc.Html; + /// /// Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. /// @@ -17,7 +17,7 @@ public static class HtmlValueExtensions /// /// Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. /// - /// + /// /// /// The HTML markup for the value. /// @@ -30,7 +30,7 @@ public static MvcHtmlString Value(this DnnHtmlHelper html, string name) /// /// Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. /// - /// + /// /// /// The HTML markup for the value. /// @@ -43,7 +43,7 @@ public static MvcHtmlString Value(this DnnHtmlHelper html, string name, string f /// /// Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. /// - /// + /// /// /// The HTML markup for the value. /// @@ -56,7 +56,7 @@ public static MvcHtmlString ValueFor(this DnnHtmlHelper /// Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. /// - /// + /// /// /// The HTML markup for the value. /// @@ -69,7 +69,7 @@ public static MvcHtmlString ValueFor(this DnnHtmlHelper /// Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. /// - /// + /// /// /// The HTML markup for the value. /// @@ -82,7 +82,7 @@ public static MvcHtmlString ValueForModel(this DnnHtmlHelper html) /// /// Provides a mechanism to create custom HTML markup compatible with the ASP.NET MVC model binders and templates. /// - /// + /// /// /// The HTML markup for the value. /// @@ -91,6 +91,5 @@ public static MvcHtmlString ValueForModel(this DnnHtmlHelper html, string format { return html.HtmlHelper.Value(format); } - } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs index 78d6cdb20a4..c019e97257c 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Web.Http; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Web.Http; + + using DotNetNuke.Common; + public static class HttpConfigurationExtensions { private const string Key = "MvcTabAndModuleInfoProvider"; @@ -29,11 +30,6 @@ public static void AddTabAndModuleInfoProvider(this HttpConfiguration configurat providers.Enqueue(tabAndModuleInfoProvider); } - private static object InitValue(object o) - { - return new ConcurrentQueue(); - } - public static IEnumerable GetTabAndModuleInfoProviders(this HttpConfiguration configuration) { Requires.NotNull("configuration", configuration); @@ -42,11 +38,16 @@ public static IEnumerable GetTabAndModuleInfoProvider if (providers == null) { - //shouldn't ever happen outside of unit tests + // shouldn't ever happen outside of unit tests return new ITabAndModuleInfoProvider[] { }; } return providers.ToArray(); } + + private static object InitValue(object o) + { + return new ConcurrentQueue(); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/HttpContextExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/HttpContextExtensions.cs index 5f1b65aff47..d10882784bf 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/HttpContextExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/HttpContextExtensions.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using DotNetNuke.Web.Mvc.Framework.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System.Web; + + using DotNetNuke.Web.Mvc.Framework.Modules; + public static class HttpContextExtensions { public const string ModuleRequestResultKey = "Dnn_ModuleRequestResult"; diff --git a/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs index 76486311ac9..65f13d08e11 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs @@ -1,16 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System.Web; + + using DotNetNuke.Entities.Modules; + public interface ITabAndModuleInfoProvider { bool TryFindTabId(HttpRequestBase request, out int tabId); + bool TryFindModuleId(HttpRequestBase request, out int moduleId); + bool TryFindModuleInfo(HttpRequestBase request, out ModuleInfo moduleInfo); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs index 3967f5d2893..407d8448d4c 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs @@ -1,61 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.IO; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using System.Web.UI; -using DotNetNuke.Collections; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Common; -using DotNetNuke.Web.Mvc.Framework.Modules; -using DotNetNuke.Web.Mvc.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System; + using System.Globalization; + using System.IO; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + using System.Web.UI; + + using DotNetNuke.Collections; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Framework; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Common; + using DotNetNuke.Web.Mvc.Framework.Modules; + using DotNetNuke.Web.Mvc.Routing; + public class MvcHostControl : ModuleControlBase, IActionable - { - #region Fields - + { private ModuleRequestResult _result; - private string _controlKey; - - #endregion - - #region Constructors - + private string _controlKey; + public MvcHostControl() { - _controlKey = String.Empty; + this._controlKey = string.Empty; } public MvcHostControl(string controlKey) { - _controlKey = controlKey; - } + this._controlKey = controlKey; + } + + public ModuleActionCollection ModuleActions { get; private set; } + + protected bool ExecuteModuleImmediately { get; set; } = true; - #endregion + protected void ExecuteModule() + { + try + { + HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current); - #region Private Methods + var moduleExecutionEngine = this.GetModuleExecutionEngine(); - private ModuleApplication GetModuleApplication(DesktopModuleInfo desktopModule, RouteData defaultRouteData) + this._result = moduleExecutionEngine.ExecuteModule(this.GetModuleRequestContext(httpContext)); + + this.ModuleActions = this.LoadActions(this._result); + + httpContext.SetModuleRequestResult(this._result); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected override void OnInit(EventArgs e) { + base.OnInit(e); + if (this.ExecuteModuleImmediately) + { + this.ExecuteModule(); + } + } + + private ModuleApplication GetModuleApplication(DesktopModuleInfo desktopModule, RouteData defaultRouteData) + { ModuleApplication moduleApplication = null; - //Check if the MVC Module overrides the base ModuleApplication class. + // Check if the MVC Module overrides the base ModuleApplication class. var businessControllerClass = desktopModule.BusinessControllerClass; - if (!String.IsNullOrEmpty(businessControllerClass)) + if (!string.IsNullOrEmpty(businessControllerClass)) { var moduleApplicationType = Reflection.CreateType(businessControllerClass); if (moduleApplicationType != null) @@ -76,14 +100,14 @@ private ModuleApplication GetModuleApplication(DesktopModuleInfo desktopModule, var defaultActionName = (string)defaultRouteData.Values["action"]; var defaultNamespaces = (string[])defaultRouteData.DataTokens["namespaces"]; - moduleApplication = new ModuleApplication - { - DefaultActionName = defaultControllerName, - DefaultControllerName = defaultActionName, - DefaultNamespaces = defaultNamespaces, - ModuleName = desktopModule.ModuleName, - FolderPath = desktopModule.FolderName - }; + moduleApplication = new ModuleApplication + { + DefaultActionName = defaultControllerName, + DefaultControllerName = defaultActionName, + DefaultNamespaces = defaultNamespaces, + ModuleName = desktopModule.ModuleName, + FolderPath = desktopModule.FolderName, + }; } return moduleApplication; @@ -104,23 +128,23 @@ private IModuleExecutionEngine GetModuleExecutionEngine() private ModuleRequestContext GetModuleRequestContext(HttpContextBase httpContext) { - var module = ModuleContext.Configuration; + var module = this.ModuleContext.Configuration; - //TODO DesktopModuleControllerAdapter usage is temporary in order to make method testable + // TODO DesktopModuleControllerAdapter usage is temporary in order to make method testable var desktopModule = DesktopModuleControllerAdapter.Instance.GetDesktopModule(module.DesktopModuleID, module.PortalID); - var defaultControl = ModuleControlControllerAdapter.Instance.GetModuleControlByControlKey("", module.ModuleDefID); + var defaultControl = ModuleControlControllerAdapter.Instance.GetModuleControlByControlKey(string.Empty, module.ModuleDefID); var defaultRouteData = ModuleRoutingProvider.Instance().GetRouteData(null, defaultControl); - var moduleApplication = GetModuleApplication(desktopModule, defaultRouteData); + var moduleApplication = this.GetModuleApplication(desktopModule, defaultRouteData); RouteData routeData; var queryString = httpContext.Request.QueryString; - if (String.IsNullOrEmpty(_controlKey)) + if (string.IsNullOrEmpty(this._controlKey)) { - _controlKey = queryString.GetValueOrDefault("ctl", String.Empty); + this._controlKey = queryString.GetValueOrDefault("ctl", string.Empty); } var moduleId = Null.NullInteger; @@ -129,25 +153,25 @@ private ModuleRequestContext GetModuleRequestContext(HttpContextBase httpContext int.TryParse(queryString["moduleid"], out moduleId); } - if (moduleId != ModuleContext.ModuleId && String.IsNullOrEmpty(_controlKey)) + if (moduleId != this.ModuleContext.ModuleId && string.IsNullOrEmpty(this._controlKey)) { - //Set default routeData for module that is not the "selected" module + // Set default routeData for module that is not the "selected" module routeData = defaultRouteData; } else { - var control = ModuleControlControllerAdapter.Instance.GetModuleControlByControlKey(_controlKey, module.ModuleDefID); + var control = ModuleControlControllerAdapter.Instance.GetModuleControlByControlKey(this._controlKey, module.ModuleDefID); routeData = ModuleRoutingProvider.Instance().GetRouteData(httpContext, control); } - var moduleRequestContext = new ModuleRequestContext - { - DnnPage = Page, - HttpContext = httpContext, - ModuleContext = ModuleContext, - ModuleApplication = moduleApplication, - RouteData = routeData - }; + var moduleRequestContext = new ModuleRequestContext + { + DnnPage = this.Page, + HttpContext = httpContext, + ModuleContext = this.ModuleContext, + ModuleApplication = moduleApplication, + RouteData = routeData, + }; return moduleRequestContext; } @@ -160,7 +184,7 @@ private ModuleActionCollection LoadActions(ModuleRequestResult result) { foreach (ModuleAction action in result.ModuleActions) { - action.ID = ModuleContext.GetNextActionID(); + action.ID = this.ModuleContext.GetNextActionID(); actions.Add(action); } } @@ -183,66 +207,26 @@ private MvcHtmlString RenderModule(ModuleRequestResult moduleResult) return moduleOutput; } - protected void ExecuteModule() - { - try - { - HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current); - - var moduleExecutionEngine = GetModuleExecutionEngine(); - - _result = moduleExecutionEngine.ExecuteModule(GetModuleRequestContext(httpContext)); - - ModuleActions = LoadActions(_result); - - httpContext.SetModuleRequestResult(_result); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - #endregion - - #region Properties - - public ModuleActionCollection ModuleActions { get; private set; } - - protected bool ExecuteModuleImmediately { get; set; } = true; - - #endregion - - #region Event Handlers - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (ExecuteModuleImmediately) - { - ExecuteModule(); - } - } - protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); try { - if (_result == null) return; - var mvcString = RenderModule(_result); + if (this._result == null) + { + return; + } + + var mvcString = this.RenderModule(this._result); if (!string.IsNullOrEmpty(Convert.ToString(mvcString))) { - Controls.Add(new LiteralControl(Convert.ToString(mvcString))); + this.Controls.Add(new LiteralControl(Convert.ToString(mvcString))); } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs index caaef88a66e..423c8154e8a 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Helpers; -using System.Web.Mvc; -using System.Web.Routing; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Framework.Reflections; -using DotNetNuke.Web.Mvc.Framework; -using DotNetNuke.Web.Mvc.Framework.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Helpers; + using System.Web.Mvc; + using System.Web.Routing; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Framework.Reflections; + using DotNetNuke.Web.Mvc.Framework; + using DotNetNuke.Web.Mvc.Framework.Modules; + public class MvcHttpModule : IHttpModule { public static readonly Regex MvcServicePath = new Regex(@"DesktopModules/MVC/", RegexOptions.Compiled); @@ -38,6 +39,10 @@ public void Init(HttpApplication context) ComponentFactory.RegisterComponentInstance(new ModuleExecutionEngine()); context.BeginRequest += InitDnn; } + + public void Dispose() + { + } private static void InitDnn(object sender, EventArgs e) { @@ -47,9 +52,6 @@ private static void InitDnn(object sender, EventArgs e) Initialize.Init(app); } } - public void Dispose() - { - } /// /// Suppress X-Frame-Options Header if there is configuration specified in web.config for it. diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs index 575ed282621..3dc28447d8d 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + public class MvcModuleControlFactory : BaseModuleControlFactory { public override Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc) @@ -25,15 +26,15 @@ public override ModuleControlBase CreateModuleControl(ModuleInfo moduleConfigura { ModuleControlBase moduleControl = base.CreateModuleControl(moduleConfiguration); - var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", "").Split('/'); + var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); - moduleControl.LocalResourceFile = string.Format("~/DesktopModules/MVC/{0}/{1}/{2}.resx", - moduleConfiguration.DesktopModule.FolderName, - Localization.LocalResourceDirectory, - segments[0]); + moduleControl.LocalResourceFile = string.Format( + "~/DesktopModules/MVC/{0}/{1}/{2}.resx", + moduleConfiguration.DesktopModule.FolderName, + Localization.LocalResourceDirectory, + segments[0]); return moduleControl; - } public override Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs index d05a56aa896..628ce56419e 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs @@ -1,29 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using DotNetNuke.Entities.Modules; + using DotNetNuke.UI.Modules; + public class MvcSettingsControl : MvcHostControl, ISettingsControl { - public MvcSettingsControl() : base("Settings") + public MvcSettingsControl() + : base("Settings") { - ExecuteModuleImmediately = false; + this.ExecuteModuleImmediately = false; } public void LoadSettings() { - ExecuteModule(); + this.ExecuteModule(); } public void UpdateSettings() { - ExecuteModule(); + this.ExecuteModule(); - ModuleController.Instance.UpdateModule(ModuleContext.Configuration); + ModuleController.Instance.UpdateModule(this.ModuleContext.Configuration); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Properties/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Web.Mvc/Properties/AssemblyInfo.cs index 9c67836b82b..ff2540d8206 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Properties/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Properties/AssemblyInfo.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Web.Mvc")] @@ -14,8 +14,8 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] -// 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 +// 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)] diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/ConstraintValidation.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/ConstraintValidation.cs index 7140cc1358b..629682d86c7 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/ConstraintValidation.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/ConstraintValidation.cs @@ -1,25 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Web.Routing; + /// /// Validates that the constraints on a Route are of a type that can be processed by . /// /// /// This validation is only applicable when the is one that we created. A user-defined /// type that is derived from may have different semantics. - /// - /// The logic here is duplicated from System.Web, but we need it to validate correctness of routes on startup. Since we can't + /// + /// The logic here is duplicated from System.Web, but we need it to validate correctness of routes on startup. Since we can't /// change System.Web, this just lives in a static class for MVC. /// internal static class ConstraintValidation diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs index ab2bf935306..f6a4a16feeb 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs @@ -1,45 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Text; -using System.Web; -using System.Web.Http; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.UserRequest; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Linq; + using System.Net; + using System.Net.NetworkInformation; + using System.Net.Sockets; + using System.Text; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.UserRequest; + internal static class HttpRequestExtensions { + private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestBase request, out T output); + public static int FindTabId(this HttpRequestBase request) { return IterateTabAndModuleInfoProviders(request, TryFindTabId, -1); } - private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestBase request, out int output) + public static ModuleInfo FindModuleInfo(this HttpRequestBase request) { - return provider.TryFindTabId(request, out output); + return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); } - public static ModuleInfo FindModuleInfo(this HttpRequestBase request) + public static int FindModuleId(this HttpRequestBase request) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); + return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); } - private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestBase request, out ModuleInfo output) + public static string GetIPAddress(HttpRequestBase request) { - return provider.TryFindModuleInfo(request, out output); + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(request); } - public static int FindModuleId(this HttpRequestBase request) + private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestBase request, out int output) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); + return provider.TryFindTabId(request, out output); + } + + private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestBase request, out ModuleInfo output) + { + return provider.TryFindModuleInfo(request, out output); } private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequestBase request, out int output) @@ -47,12 +55,10 @@ private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequ return provider.TryFindModuleId(request, out output); } - private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestBase request, out T output); - private static T IterateTabAndModuleInfoProviders(HttpRequestBase request, TryMethod func, T fallback) { var providers = GlobalConfiguration.Configuration.GetTabAndModuleInfoProviders(); - + foreach (var provider in providers) { T output; @@ -64,10 +70,5 @@ private static T IterateTabAndModuleInfoProviders(HttpRequestBase request, Tr return fallback; } - - public static string GetIPAddress(HttpRequestBase request) - { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(request); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMapRoute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMapRoute.cs index ac3df3bfef8..0d30a34f3d8 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMapRoute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMapRoute.cs @@ -1,49 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Collections.Generic; + using System.Web.Routing; + public interface IMapRoute { /// - /// Sets up the route(s) for DotNetNuke MVC Controls + /// Sets up the route(s) for DotNetNuke MVC Controls. /// - /// The name of the folder under DesktopModules in which your module resides - /// A unique name for the route - /// The parameterized portion of the route - /// The namespace(s) in which to search for the controllers for this route + /// The name of the folder under DesktopModules in which your module resides. + /// A unique name for the route. + /// The parameterized portion of the route. + /// The namespace(s) in which to search for the controllers for this route. /// A list of all routes that were registered. - /// The combination of moduleFolderName and routeName must be unique for each route + /// The combination of moduleFolderName and routeName must be unique for each route. Route MapRoute(string moduleFolderName, string routeName, string url, string[] namespaces); /// - /// Sets up the route(s) for DotNetNuke MVC Controls + /// Sets up the route(s) for DotNetNuke MVC Controls. /// - /// The name of the folder under DesktopModules in which your module resides - /// A unique name for the route - /// The parameterized portion of the route - /// Default values for the route parameters - /// The namespace(s) in which to search for the controllers for this route + /// The name of the folder under DesktopModules in which your module resides. + /// A unique name for the route. + /// The parameterized portion of the route. + /// Default values for the route parameters. + /// The namespace(s) in which to search for the controllers for this route. /// A list of all routes that were registered. - /// The combination of moduleFolderName and routeName must be unique for each route + /// The combination of moduleFolderName and routeName must be unique for each route. Route MapRoute(string moduleFolderName, string routeName, string url, object defaults, string[] namespaces); /// - /// Sets up the route(s) for DotNetNuke MVC Controls + /// Sets up the route(s) for DotNetNuke MVC Controls. /// - /// The name of the folder under DesktopModules in which your module resides - /// A unique name for the route - /// The parameterized portion of the route - /// Default values for the route parameters - /// The constraints - /// The namespace(s) in which to search for the controllers for this route + /// The name of the folder under DesktopModules in which your module resides. + /// A unique name for the route. + /// The parameterized portion of the route. + /// Default values for the route parameters. + /// The constraints. + /// The namespace(s) in which to search for the controllers for this route. /// A list of all routes that were registered. - /// The combination of moduleFolderName and routeName must be unique for each route + /// The combination of moduleFolderName and routeName must be unique for each route. Route MapRoute(string moduleFolderName, string routeName, string url, object defaults, object constraints, string[] namespaces); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMvcRouteMapper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMvcRouteMapper.cs index 187ab8f27a3..035131f4bdc 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMvcRouteMapper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IMvcRouteMapper.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { public interface IMvcRouteMapper diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs index 7ffb49bc67a..a7b5c913f6b 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs @@ -1,24 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Routing; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Web.Routing; + + using DotNetNuke.Entities.Portals; + internal interface IPortalAliasMvcRouteManager { IEnumerable GetRoutePrefixCounts(); + string GetRouteName(string moduleFolderName, string routeName, int count); + string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias); + RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues); + string GetRouteUrl(string moduleFolderName, string url, int count); + void ClearCachedData(); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/ModuleRoutingProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/ModuleRoutingProvider.cs index f7ad042beb8..a99990d52de 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/ModuleRoutingProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/ModuleRoutingProvider.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using System.Web.Routing; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System.Web; + using System.Web.Routing; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Modules; + using DotNetNuke.UI.Modules; + public abstract class ModuleRoutingProvider { public static ModuleRoutingProvider Instance() diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs index 5ce38353996..24678e46e6f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs @@ -1,20 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Web.Routing; + public static class MvcRouteExtensions { private const string NamespaceKey = "namespaces"; private const string NameKey = "name"; + + /// + /// Get the name of the route. + /// + /// Route name. + public static string GetName(this Route route) + { + return (string)route.DataTokens[NameKey]; + } internal static void SetNameSpaces(this Route route, string[] namespaces) { @@ -22,27 +31,17 @@ internal static void SetNameSpaces(this Route route, string[] namespaces) } /// - /// Get Namespaces that are searched for controllers for this route + /// Get Namespaces that are searched for controllers for this route. /// - /// Namespaces + /// Namespaces. internal static string[] GetNameSpaces(this Route route) { - return (string[]) route.DataTokens[NamespaceKey]; + return (string[])route.DataTokens[NamespaceKey]; } internal static void SetName(this Route route, string name) { route.DataTokens[NameKey] = name; } - - - /// - /// Get the name of the route - /// - /// Route name - public static string GetName(this Route route) - { - return (string) route.DataTokens[NameKey]; - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs index b7e09a6d5f7..e7cda2d1251 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs @@ -1,95 +1,102 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Routing; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework.Reflections; -using DotNetNuke.Services.Localization; -using DotNetNuke.Instrumentation; -using DotNetNuke.Web.Mvc.Common; -using System.Web.Http; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Collections.Generic; + using System.Web.Http; + using System.Web.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.Reflections; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Mvc.Common; + public sealed class MvcRoutingManager : IMapRoute { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (MvcRoutingManager)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MvcRoutingManager)); private readonly Dictionary _moduleUsage = new Dictionary(); private readonly RouteCollection _routes; private readonly PortalAliasMvcRouteManager _portalAliasMvcRouteManager; - public MvcRoutingManager() : this(RouteTable.Routes) + public MvcRoutingManager() + : this(RouteTable.Routes) { } internal MvcRoutingManager(RouteCollection routes) { - _routes = routes; - _portalAliasMvcRouteManager = new PortalAliasMvcRouteManager(); - TypeLocator = new TypeLocator(); + this._routes = routes; + this._portalAliasMvcRouteManager = new PortalAliasMvcRouteManager(); + this.TypeLocator = new TypeLocator(); } - internal ITypeLocator TypeLocator { get; set; } - - #region IMapRoute Members - + internal ITypeLocator TypeLocator { get; set; } + public Route MapRoute(string moduleFolderName, string routeName, string url, string[] namespaces) { - return MapRoute(moduleFolderName, routeName, url, null /* defaults */, null /* constraints */, namespaces); + return this.MapRoute(moduleFolderName, routeName, url, null /* defaults */, null /* constraints */, namespaces); } public Route MapRoute(string moduleFolderName, string routeName, string url, object defaults, string[] namespaces) { - return MapRoute(moduleFolderName, routeName, url, defaults, null /* constraints */, namespaces); + return this.MapRoute(moduleFolderName, routeName, url, defaults, null /* constraints */, namespaces); } public Route MapRoute(string moduleFolderName, string routeName, string url, object defaults, object constraints, string[] namespaces) { - if (namespaces == null || namespaces.Length == 0 || String.IsNullOrEmpty(namespaces[0])) + if (namespaces == null || namespaces.Length == 0 || string.IsNullOrEmpty(namespaces[0])) { - throw new ArgumentException(Localization.GetExceptionMessage("ArgumentCannotBeNullOrEmpty", - "The argument '{0}' cannot be null or empty.", - "namespaces")); + throw new ArgumentException(Localization.GetExceptionMessage( + "ArgumentCannotBeNullOrEmpty", + "The argument '{0}' cannot be null or empty.", + "namespaces")); } Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); url = url.Trim('/', '\\'); - var prefixCounts = _portalAliasMvcRouteManager.GetRoutePrefixCounts(); + var prefixCounts = this._portalAliasMvcRouteManager.GetRoutePrefixCounts(); Route route = null; - if (url == null) - throw new ArgumentNullException(nameof(url)); - + if (url == null) + { + throw new ArgumentNullException(nameof(url)); + } + foreach (var count in prefixCounts) { - var fullRouteName = _portalAliasMvcRouteManager.GetRouteName(moduleFolderName, routeName, count); - var routeUrl = _portalAliasMvcRouteManager.GetRouteUrl(moduleFolderName, url, count); + var fullRouteName = this._portalAliasMvcRouteManager.GetRouteName(moduleFolderName, routeName, count); + var routeUrl = this._portalAliasMvcRouteManager.GetRouteUrl(moduleFolderName, url, count); route = MapRouteWithNamespace(fullRouteName, routeUrl, defaults, constraints, namespaces); - _routes.Add(route); + this._routes.Add(route); Logger.Trace("Mapping route: " + fullRouteName + " @ " + routeUrl); } return route; - } - - #endregion - + } + public void RegisterRoutes() { - //add standard tab and module id provider + // add standard tab and module id provider GlobalConfiguration.Configuration.AddTabAndModuleInfoProvider(new StandardTabAndModuleInfoProvider()); - using (_routes.GetWriteLock()) + using (this._routes.GetWriteLock()) { - //_routes.Clear(); -- don't use; it will remove original WEP API maps - LocateServicesAndMapRoutes(); + // _routes.Clear(); -- don't use; it will remove original WEP API maps + this.LocateServicesAndMapRoutes(); } - Logger.TraceFormat("Registered a total of {0} routes", _routes.Count); + + Logger.TraceFormat("Registered a total of {0} routes", this._routes.Count); + } + + internal static bool IsValidServiceRouteMapper(Type t) + { + return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IMvcRouteMapper).IsAssignableFrom(t); } private static bool IsTracingEnabled() @@ -99,13 +106,40 @@ private static bool IsTracingEnabled() return !string.IsNullOrEmpty(configValue) && Convert.ToBoolean(configValue); } + private static void RegisterSystemRoutes() + { + // _routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + } + + private static Route MapRouteWithNamespace(string name, string url, object defaults, object constraints, string[] namespaces) + { + var route = new Route(url, new DnnMvcRouteHandler()) + { + Defaults = CreateRouteValueDictionaryUncached(defaults), + Constraints = CreateRouteValueDictionaryUncached(constraints), + }; + if (route.DataTokens == null) + { + route.DataTokens = new RouteValueDictionary(); + } + + ConstraintValidation.Validate(route); + if ((namespaces != null) && (namespaces.Length > 0)) + { + route.SetNameSpaces(namespaces); + } + + route.SetName(name); + return route; + } + private void LocateServicesAndMapRoutes() { RegisterSystemRoutes(); - ClearCachedRouteData(); + this.ClearCachedRouteData(); - _moduleUsage.Clear(); - foreach (var routeMapper in GetServiceRouteMappers()) + this._moduleUsage.Clear(); + foreach (var routeMapper in this.GetServiceRouteMappers()) { try { @@ -121,17 +155,12 @@ private void LocateServicesAndMapRoutes() private void ClearCachedRouteData() { - _portalAliasMvcRouteManager.ClearCachedData(); - } - - private static void RegisterSystemRoutes() - { - //_routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + this._portalAliasMvcRouteManager.ClearCachedData(); } private IEnumerable GetServiceRouteMappers() { - IEnumerable types = GetAllServiceRouteMapperTypes(); + IEnumerable types = this.GetAllServiceRouteMapperTypes(); foreach (var routeMapperType in types) { @@ -156,32 +185,7 @@ private IEnumerable GetServiceRouteMappers() private IEnumerable GetAllServiceRouteMapperTypes() { - return TypeLocator.GetAllMatchingTypes(IsValidServiceRouteMapper); - } - - internal static bool IsValidServiceRouteMapper(Type t) - { - return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IMvcRouteMapper).IsAssignableFrom(t); - } - - private static Route MapRouteWithNamespace(string name, string url, object defaults, object constraints, string[] namespaces) - { - var route = new Route(url, new DnnMvcRouteHandler()) - { - Defaults = CreateRouteValueDictionaryUncached(defaults), - Constraints = CreateRouteValueDictionaryUncached(constraints) - }; - if (route.DataTokens == null) - { - route.DataTokens = new RouteValueDictionary(); - } - ConstraintValidation.Validate(route); - if ((namespaces != null) && (namespaces.Length > 0)) - { - route.SetNameSpaces(namespaces); - } - route.SetName(name); - return route; + return this.TypeLocator.GetAllMatchingTypes(IsValidServiceRouteMapper); } private static RouteValueDictionary CreateRouteValueDictionaryUncached(object values) diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs index fe1aa740cc8..9212f6bb1cf 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Web.Routing; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Web.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Portals; + internal class PortalAliasMvcRouteManager : IPortalAliasMvcRouteManager { private List _prefixCounts; @@ -39,24 +40,8 @@ public string GetRouteName(string moduleFolderName, string routeName, PortalAlia alias = alias.Remove(i, appPath.Length); } } - return GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); - } - - private static string GeneratePrefixString(int count) - { - if (count == 0) - { - return ""; - } - - var prefix = ""; - - for (var i = count - 1; i >= 0; i--) - { - prefix = "{prefix" + i + "}/" + prefix; - } - - return prefix; + + return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); } public RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) @@ -65,7 +50,11 @@ public RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, o var segments = portalAliasInfo.HTTPAlias.Split('/'); - if (segments.Length <= 1) return allRouteValues; + if (segments.Length <= 1) + { + return allRouteValues; + } + for (var i = 1; i < segments.Length; i++) { var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); @@ -84,16 +73,37 @@ public string GetRouteUrl(string moduleFolderName, string url, int count) return $"{GeneratePrefixString(count)}DesktopModules/MVC/{moduleFolderName}/{url}"; } + private static string GeneratePrefixString(int count) + { + if (count == 0) + { + return string.Empty; + } + + var prefix = string.Empty; + + for (var i = count - 1; i >= 0; i--) + { + prefix = "{prefix" + i + "}/" + prefix; + } + + return prefix; + } + public void ClearCachedData() { - _prefixCounts = null; + this._prefixCounts = null; } public IEnumerable GetRoutePrefixCounts() { - if (_prefixCounts != null) return _prefixCounts; - //prefixCounts are required for each route that is mapped but they only change - //when a new portal is added so cache them until that time + if (this._prefixCounts != null) + { + return this._prefixCounts; + } + + // prefixCounts are required for each route that is mapped but they only change + // when a new portal is added so cache them until that time var portals = PortalController.Instance.GetPortals(); var segmentCounts1 = new List(); @@ -104,17 +114,18 @@ var count in portal => PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID) .Select(x => x.HTTPAlias)) - .Select(StripApplicationPath) + .Select(this.StripApplicationPath) .SelectMany( aliases => aliases.Select(CalcAliasPrefixCount).Where(count => !segmentCounts1.Contains(count)))) { segmentCounts1.Add(count); } + IEnumerable segmentCounts = segmentCounts1; - _prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); + this._prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); - return _prefixCounts; + return this._prefixCounts; } private static int CalcAliasPrefixCount(string alias) @@ -122,13 +133,6 @@ private static int CalcAliasPrefixCount(string alias) return alias.Count(c => c == '/'); } - private IEnumerable StripApplicationPath(IEnumerable aliases) - { - var appPath = TestableGlobals.Instance.ApplicationPath; - - return string.IsNullOrEmpty(appPath) ? aliases : StripApplicationPathIterable(aliases, appPath); - } - private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) { foreach (var alias in aliases) @@ -145,5 +149,12 @@ private static IEnumerable StripApplicationPathIterable(IEnumerable StripApplicationPath(IEnumerable aliases) + { + var appPath = TestableGlobals.Instance.ApplicationPath; + + return string.IsNullOrEmpty(appPath) ? aliases : StripApplicationPathIterable(aliases, appPath); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs index 5301b5911f4..d814f713543 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs @@ -1,36 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Routing; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Collections; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc.Routing { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.Routing; + + using DotNetNuke.Abstractions; + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + public class StandardModuleRoutingProvider : ModuleRoutingProvider { - protected INavigationManager NavigationManager { get; } private const string ExcludedQueryStringParams = "tabid,mid,ctl,language,popup,action,controller"; private const string ExcludedRouteValues = "mid,ctl,popup"; + public StandardModuleRoutingProvider() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } - - + + protected INavigationManager NavigationManager { get; } + public override string GenerateUrl(RouteValueDictionary routeValues, ModuleInstanceContext moduleContext) { - //Look for a module control - string controlKey = (routeValues.ContainsKey("ctl")) ? (string)routeValues["ctl"] : String.Empty; + // Look for a module control + string controlKey = routeValues.ContainsKey("ctl") ? (string)routeValues["ctl"] : string.Empty; List additionalParams = (from routeValue in routeValues where !ExcludedRouteValues.Split(',').ToList().Contains(routeValue.Key.ToLowerInvariant()) @@ -38,14 +40,14 @@ public override string GenerateUrl(RouteValueDictionary routeValues, ModuleInsta .ToList(); string url; - if (String.IsNullOrEmpty(controlKey)) + if (string.IsNullOrEmpty(controlKey)) { additionalParams.Insert(0, "moduleId=" + moduleContext.Configuration.ModuleID); - url = NavigationManager.NavigateURL("", additionalParams.ToArray()); + url = this.NavigationManager.NavigateURL(string.Empty, additionalParams.ToArray()); } else { - url = moduleContext.EditUrl(String.Empty, String.Empty, controlKey, additionalParams.ToArray()); + url = moduleContext.EditUrl(string.Empty, string.Empty, controlKey, additionalParams.ToArray()); } return url; @@ -53,8 +55,8 @@ public override string GenerateUrl(RouteValueDictionary routeValues, ModuleInsta public override RouteData GetRouteData(HttpContextBase httpContext, ModuleControlInfo moduleControl) { - var segments = moduleControl.ControlSrc.Replace(".mvc", "").Split('/'); - string routeNamespace = String.Empty; + var segments = moduleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); + string routeNamespace = string.Empty; string routeControllerName; string routeActionName; if (segments.Length == 3) @@ -86,7 +88,8 @@ public override RouteData GetRouteData(HttpContextBase httpContext, ModuleContro } } } - if (!String.IsNullOrEmpty(routeNamespace)) + + if (!string.IsNullOrEmpty(routeNamespace)) { routeData.DataTokens.Add("namespaces", new string[] { routeNamespace }); } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs index fcd2076025e..92940fb6b28 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + public sealed class StandardTabAndModuleInfoProvider : ITabAndModuleInfoProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); - private const string ModuleIdKey = "ModuleId"; private const string TabIdKey = "TabId"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); private const string MonikerQueryKey = "Moniker"; private const string MonikerHeaderKey = "X-DNN-MONIKER"; private const string MonikerSettingsKey = "Moniker"; @@ -28,6 +29,23 @@ public bool TryFindTabId(HttpRequestBase request, out int tabId) return TryFindTabId(request, out tabId, true); } + public bool TryFindModuleId(HttpRequestBase request, out int moduleId) + { + return TryFindModuleId(request, out moduleId, true); + } + + public bool TryFindModuleInfo(HttpRequestBase request, out ModuleInfo moduleInfo) + { + int tabId, moduleId; + if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) + { + moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); + return moduleInfo != null; + } + + return TryFindByMoniker(request, out moduleInfo); + } + private static bool TryFindTabId(HttpRequestBase request, out int tabId, bool tryMoniker) { tabId = FindInt(request, TabIdKey); @@ -49,11 +67,6 @@ private static bool TryFindTabId(HttpRequestBase request, out int tabId, bool tr return false; } - public bool TryFindModuleId(HttpRequestBase request, out int moduleId) - { - return TryFindModuleId(request, out moduleId, true); - } - private static bool TryFindModuleId(HttpRequestBase request, out int moduleId, bool tryMoniker) { moduleId = FindInt(request, ModuleIdKey); @@ -75,22 +88,10 @@ private static bool TryFindModuleId(HttpRequestBase request, out int moduleId, b return false; } - public bool TryFindModuleInfo(HttpRequestBase request, out ModuleInfo moduleInfo) - { - int tabId, moduleId; - if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) - { - moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); - return moduleInfo != null; - } - - return TryFindByMoniker(request, out moduleInfo); - } - private static int FindInt(HttpRequestBase requestBase, string key) { string value = null; - if (requestBase.Headers[key]!=null) + if (requestBase.Headers[key] != null) { value = requestBase.Headers[key]; } @@ -120,7 +121,7 @@ private static bool TryFindByMoniker(HttpRequestBase requestBase, out ModuleInfo private static int FindIntInHeader(HttpRequestBase requestBase, string key) { string value = null; - if (requestBase.Headers[key]!=null) + if (requestBase.Headers[key] != null) { value = requestBase.Headers[key]; } @@ -142,7 +143,7 @@ private static int FindIntInQueryString(HttpRequestBase requestBase, string key) private static int GetTabModuleInfoFromMoniker(string monikerValue) { - monikerValue = (monikerValue ?? "").Trim(); + monikerValue = (monikerValue ?? string.Empty).Trim(); if (monikerValue.Length > 0) { var ids = TabModulesController.Instance.GetTabModuleIdsBySetting(MonikerSettingsKey, monikerValue); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Startup.cs b/DNN Platform/DotNetNuke.Web.Mvc/Startup.cs index 973ebaa6048..846185d6cc5 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Startup.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Startup.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.DependencyInjection; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Web.Mvc.Extensions; -using System.Web.Mvc; -using DotNetNuke.Common; -using Microsoft.Extensions.DependencyInjection.Extensions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvc { + using System.Web.Mvc; + + using DotNetNuke.Common; + using DotNetNuke.DependencyInjection; + using DotNetNuke.Web.Mvc.Extensions; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; + public class Startup : IDnnStartup { public void ConfigureServices(IServiceCollection services) diff --git a/DNN Platform/DotNetNuke.Web.Mvc/packages.config b/DNN Platform/DotNetNuke.Web.Mvc/packages.config index 66010687c57..1a237298448 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/packages.config +++ b/DNN Platform/DotNetNuke.Web.Mvc/packages.config @@ -7,4 +7,5 @@ + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Web.Razor/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Web.Razor/AssemblyInfo.cs index 85495d54965..0ea40cdc74b 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/AssemblyInfo.cs @@ -1,27 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System.Reflection; -using System.Runtime.InteropServices; - -#endregion - -// 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. - -// Review the values of the assembly attributes - +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. + +// Review the values of the assembly attributes [assembly: AssemblyTitle("DotNetNuke.Web.Razor")] [assembly: AssemblyDescription("Open Source Web Application Framework")] [assembly: ComVisible(false)] -//The following GUID is for the ID of the typelib if this project is exposed to COM - +// The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d396c63f-4cb7-4258-9ec6-7052f7d756cb")] -[assembly: AssemblyDelaySign(false)] - +[assembly: AssemblyDelaySign(false)] diff --git a/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj b/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj index 04694be556c..85352046976 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj +++ b/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj @@ -1,149 +1,156 @@ - - - - Debug - AnyCPU - - - - - {9806C125-8CA9-48CC-940A-CCD0442C5993} - Library - Properties - DotNetNuke.Web.Razor - DotNetNuke.Web.Razor - 512 - Windows - v4.7.2 - - ..\..\ - true - - - true - full - DEBUG;TRACE - bin\ - bin\DotNetNuke.Web.Razor.XML - 4 - 1591 - 7 - - - pdbonly - TRACE - true - bin\ - bin\DotNetNuke.Web.Razor.XML - 1591 - 7 - - - On - - - - False - ..\Library\bin\DotNetNuke.dll - - - ..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll - - - ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - - - ..\..\packages\Microsoft.AspNet.WebHelpers.3.1.1\lib\net45\Microsoft.Web.Helpers.dll - True - - - True - ..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - - - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.Helpers.dll - True - - - ..\..\packages\Microsoft.AspNet.Razor.3.1.1\lib\net45\System.Web.Razor.dll - True - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.dll - True - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Deployment.dll - True - - - ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Razor.dll - True - - - - - ..\..\packages\Microsoft.AspNet.WebPages.Data.3.1.1\lib\net45\WebMatrix.Data.dll - True - - - ..\..\packages\Microsoft.AspNet.WebPages.WebData.3.1.1\lib\net45\WebMatrix.WebData.dll - True - - - - - - - - - - - - - - - SolutionInfo.cs - - - - - - - - - - ASPXCodeBehind - - - - - - - - - - - - - - {6928a9b1-f88a-4581-a132-d3eb38669bb0} - DotNetNuke.Abstractions - - - {0fca217a-5f9a-4f5b-a31b-86d64ae65198} - DotNetNuke.DependencyInjection - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + + + + + {9806C125-8CA9-48CC-940A-CCD0442C5993} + Library + Properties + DotNetNuke.Web.Razor + DotNetNuke.Web.Razor + 512 + Windows + v4.7.2 + + ..\..\ + true + + + true + full + DEBUG;TRACE + bin\ + bin\DotNetNuke.Web.Razor.XML + 4 + 1591 + 7 + + + pdbonly + TRACE + true + bin\ + bin\DotNetNuke.Web.Razor.XML + 1591 + 7 + + + On + + + + False + ..\Library\bin\DotNetNuke.dll + + + ..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll + + + ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + ..\..\packages\Microsoft.AspNet.WebHelpers.3.1.1\lib\net45\Microsoft.Web.Helpers.dll + True + + + True + ..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll + + + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.Helpers.dll + True + + + ..\..\packages\Microsoft.AspNet.Razor.3.1.1\lib\net45\System.Web.Razor.dll + True + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.dll + True + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Deployment.dll + True + + + ..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Razor.dll + True + + + + + ..\..\packages\Microsoft.AspNet.WebPages.Data.3.1.1\lib\net45\WebMatrix.Data.dll + True + + + ..\..\packages\Microsoft.AspNet.WebPages.WebData.3.1.1\lib\net45\WebMatrix.WebData.dll + True + + + + + + + + + + + + + + + SolutionInfo.cs + + + + + + + + + + ASPXCodeBehind + + + + + + + + + + stylecop.json + + + + + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + + + {0fca217a-5f9a-4f5b-a31b-86d64ae65198} + DotNetNuke.DependencyInjection + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs index 658dc692d73..434444bdbf5 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs @@ -1,20 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.WebPages; -using DotNetNuke.Common; -using DotNetNuke.Web.Razor.Helpers; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Razor { + using System; + using System.Web.WebPages; + + using DotNetNuke.Common; + using DotNetNuke.Web.Razor.Helpers; + using Microsoft.Extensions.DependencyInjection; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public abstract class DotNetNukeWebPage : WebPageBase { private dynamic _model; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + public dynamic Model + { + get { return this._model ?? (this._model = this.PageContext.Model); } + set { this._model = value; } + } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected internal DnnHelper Dnn { get; internal set; } @@ -29,34 +37,28 @@ protected override void ConfigurePage(WebPageBase parentPage) { base.ConfigurePage(parentPage); - //Child pages need to get their context from the Parent - Context = parentPage.Context; - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public dynamic Model - { - get { return _model ?? (_model = PageContext.Model); } - set { _model = value; } + // Child pages need to get their context from the Parent + this.Context = parentPage.Context; } } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public abstract class DotNetNukeWebPage :DotNetNukeWebPage where TModel : class + public abstract class DotNetNukeWebPage : DotNetNukeWebPage + where TModel : class { private TModel _model; public DotNetNukeWebPage() { var model = Globals.DependencyProvider.GetService(); - Model = model ?? Activator.CreateInstance(); + this.Model = model ?? Activator.CreateInstance(); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public new TModel Model { - get { return PageContext?.Model as TModel ?? _model; } - set { _model = value; } + get { return this.PageContext?.Model as TModel ?? this._model; } + set { this._model = value; } } } } diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs index 75fcdd01db0..6c0935b797f 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs @@ -1,20 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.UI.Modules; -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Razor.Helpers { + using System; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.UI.Modules; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class DnnHelper { @@ -23,7 +19,7 @@ public class DnnHelper [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public DnnHelper(ModuleInstanceContext context) { - _context = context; + this._context = context; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] @@ -31,7 +27,7 @@ public ModuleInfo Module { get { - return _context.Configuration; + return this._context.Configuration; } } @@ -40,7 +36,7 @@ public TabInfo Tab { get { - return _context.PortalSettings.ActiveTab; + return this._context.PortalSettings.ActiveTab; } } @@ -49,7 +45,7 @@ public PortalSettings Portal { get { - return _context.PortalSettings; + return this._context.PortalSettings; } } @@ -58,7 +54,7 @@ public UserInfo User { get { - return _context.PortalSettings.UserInfo; + return this._context.PortalSettings.UserInfo; } } } diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs index 4a94903dbce..57802a2ac80 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using System; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Razor.Helpers { + using System; + using System.Web; + + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class HtmlHelper { @@ -22,20 +18,20 @@ public class HtmlHelper [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public HtmlHelper(ModuleInstanceContext context, string resourcefile) { - _context = context; - _resourceFile = resourcefile; + this._context = context; + this._resourceFile = resourcefile; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public object GetLocalizedString(string key) { - return Localization.GetString(key, _resourceFile); + return Localization.GetString(key, this._resourceFile); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public object GetLocalizedString(string key, string culture) { - return Localization.GetString(key, _resourceFile, culture); + return Localization.GetString(key, this._resourceFile, culture); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs index c4e69a5e6b6..2904da99fde 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs @@ -1,42 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.UI.Modules; -using System; -using Microsoft.Extensions.DependencyInjection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Razor.Helpers { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class UrlHelper { private readonly ModuleInstanceContext _context; - protected INavigationManager NavigationManager { get; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public UrlHelper(ModuleInstanceContext context) { - _context = context; - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this._context = context; + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + + protected INavigationManager NavigationManager { get; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public string NavigateToControl() { - return NavigationManager.NavigateURL(_context.TabId); + return this.NavigationManager.NavigateURL(this._context.TabId); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public string NavigateToControl(string controlKey) { - return NavigationManager.NavigateURL(_context.TabId, controlKey, "mid=" + _context.ModuleId); + return this.NavigationManager.NavigateURL(this._context.TabId, controlKey, "mid=" + this._context.ModuleId); } } } diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs index 49eb908f6e6..cca41cad8d8 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs @@ -1,38 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Using - -using System; -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; -using System.Web; -using System.Web.Compilation; -using System.Web.WebPages; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Razor.Helpers; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Razor { + using System; + using System.Globalization; + using System.IO; + using System.Runtime.CompilerServices; + using System.Web; + using System.Web.Compilation; + using System.Web.WebPages; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Razor.Helpers; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class RazorEngine { [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, string localResourceFile) { - RazorScriptFile = razorScriptFile; - ModuleContext = moduleContext; - LocalResourceFile = localResourceFile ?? Path.Combine(Path.GetDirectoryName(razorScriptFile), Localization.LocalResourceDirectory, Path.GetFileName(razorScriptFile) + ".resx"); + this.RazorScriptFile = razorScriptFile; + this.ModuleContext = moduleContext; + this.LocalResourceFile = localResourceFile ?? Path.Combine(Path.GetDirectoryName(razorScriptFile), Localization.LocalResourceDirectory, Path.GetFileName(razorScriptFile) + ".resx"); try { - InitWebpage(); + this.InitWebpage(); } catch (HttpParseException) { @@ -48,6 +44,9 @@ public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, } } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + public DotNetNukeWebPage Webpage { get; set; } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string RazorScriptFile { get; set; } @@ -57,9 +56,6 @@ public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string LocalResourceFile { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public DotNetNukeWebPage Webpage { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected HttpContextBase HttpContext { @@ -69,14 +65,15 @@ protected HttpContextBase HttpContext [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public Type RequestedModelType() { - if (Webpage != null) + if (this.Webpage != null) { - var webpageType = Webpage.GetType(); + var webpageType = this.Webpage.GetType(); if (webpageType.BaseType.IsGenericType) { return webpageType.BaseType.GetGenericArguments()[0]; } } + return null; } @@ -85,7 +82,7 @@ public void Render(TextWriter writer, T model) { try { - Webpage.ExecutePageHierarchy(new WebPageContext(HttpContext, Webpage, model), writer, Webpage); + this.Webpage.ExecutePageHierarchy(new WebPageContext(this.HttpContext, this.Webpage, model), writer, this.Webpage); } catch (Exception exc) { @@ -98,7 +95,7 @@ public void Render(TextWriter writer) { try { - Webpage.ExecutePageHierarchy(new WebPageContext(HttpContext, Webpage, null), writer, Webpage); + this.Webpage.ExecutePageHierarchy(new WebPageContext(this.HttpContext, this.Webpage, null), writer, this.Webpage); } catch (Exception exc) { @@ -111,7 +108,7 @@ public void Render(TextWriter writer, WebPageContext context) { try { - Webpage.ExecutePageHierarchy(context, writer, Webpage); + this.Webpage.ExecutePageHierarchy(context, writer, this.Webpage); } catch (Exception exc) { @@ -121,39 +118,42 @@ public void Render(TextWriter writer, WebPageContext context) private object CreateWebPageInstance() { - var compiledType = BuildManager.GetCompiledType(RazorScriptFile); + var compiledType = BuildManager.GetCompiledType(this.RazorScriptFile); object objectValue = null; - if (((compiledType != null))) + if (compiledType != null) { objectValue = RuntimeHelpers.GetObjectValue(Activator.CreateInstance(compiledType)); } + return objectValue; } private void InitHelpers(DotNetNukeWebPage webPage) { - webPage.Dnn = new DnnHelper(ModuleContext); - webPage.Html = new HtmlHelper(ModuleContext, LocalResourceFile); - webPage.Url = new UrlHelper(ModuleContext); + webPage.Dnn = new DnnHelper(this.ModuleContext); + webPage.Html = new HtmlHelper(this.ModuleContext, this.LocalResourceFile); + webPage.Url = new UrlHelper(this.ModuleContext); } private void InitWebpage() { - if (!string.IsNullOrEmpty(RazorScriptFile)) + if (!string.IsNullOrEmpty(this.RazorScriptFile)) { - var objectValue = RuntimeHelpers.GetObjectValue(CreateWebPageInstance()); - if ((objectValue == null)) + var objectValue = RuntimeHelpers.GetObjectValue(this.CreateWebPageInstance()); + if (objectValue == null) { - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The webpage found at '{0}' was not created.", new object[] {RazorScriptFile})); + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The webpage found at '{0}' was not created.", new object[] { this.RazorScriptFile })); } - Webpage = objectValue as DotNetNukeWebPage; - if ((Webpage == null)) + + this.Webpage = objectValue as DotNetNukeWebPage; + if (this.Webpage == null) { - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The webpage at '{0}' must derive from DotNetNukeWebPage.", new object[] {RazorScriptFile})); + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The webpage at '{0}' must derive from DotNetNukeWebPage.", new object[] { this.RazorScriptFile })); } - Webpage.Context = HttpContext; - Webpage.VirtualPath = VirtualPathUtility.GetDirectory(RazorScriptFile); - InitHelpers(Webpage); + + this.Webpage.Context = this.HttpContext; + this.Webpage.VirtualPath = VirtualPathUtility.GetDirectory(this.RazorScriptFile); + this.InitHelpers(this.Webpage); } } } diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs index 2b2d35327a8..22effdb2320 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs @@ -1,78 +1,74 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web; -using System.Web.UI; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Razor { + using System; + using System.IO; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.UI.Modules; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class RazorHostControl : ModuleControlBase, IActionable { private readonly string _razorScriptFile; + private RazorEngine _engine; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public RazorHostControl(string scriptFile) { - _razorScriptFile = scriptFile; + this._razorScriptFile = scriptFile; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected virtual string RazorScriptFile + public ModuleActionCollection ModuleActions { - get { return _razorScriptFile; } + get + { + if (this.Engine.Webpage is IActionable) + { + return (this.Engine.Webpage as IActionable).ModuleActions; + } + + return new ModuleActionCollection(); + } } - private RazorEngine _engine; - private RazorEngine Engine - { - get - { - if (_engine == null) - { - _engine = new RazorEngine(RazorScriptFile, ModuleContext, LocalResourceFile); - } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected virtual string RazorScriptFile + { + get { return this._razorScriptFile; } + } + + private RazorEngine Engine + { + get + { + if (this._engine == null) + { + this._engine = new RazorEngine(this.RazorScriptFile, this.ModuleContext, this.LocalResourceFile); + } - return _engine; - } - } + return this._engine; + } + } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (!(string.IsNullOrEmpty(RazorScriptFile))) + if (!string.IsNullOrEmpty(this.RazorScriptFile)) { var writer = new StringWriter(); - Engine.Render(writer); - Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(writer.ToString()))); + this.Engine.Render(writer); + this.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(writer.ToString()))); } } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public ModuleActionCollection ModuleActions - { - get - { - if (Engine.Webpage is IActionable) - { - return (Engine.Webpage as IActionable).ModuleActions; - } - - return new ModuleActionCollection(); - } - } - } + } } diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs index 26b3042398b..2d6ca46ba70 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs @@ -1,19 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web.UI; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Razor { + using System; + using System.IO; + using System.Web.UI; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.Modules; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class RazorModuleBase : ModuleUserControlBase { @@ -22,19 +18,19 @@ protected virtual string RazorScriptFile { get { - var scriptFolder = AppRelativeTemplateSourceDirectory; - var fileRoot = Path.GetFileNameWithoutExtension(AppRelativeVirtualPath); + var scriptFolder = this.AppRelativeTemplateSourceDirectory; + var fileRoot = Path.GetFileNameWithoutExtension(this.AppRelativeVirtualPath); var scriptFile = scriptFolder + "_" + fileRoot + ".cshtml"; - if (! (File.Exists(Server.MapPath(scriptFile)))) + if (!File.Exists(this.Server.MapPath(scriptFile))) { - //Try VB (vbhtml) + // Try VB (vbhtml) scriptFile = scriptFolder + "_" + fileRoot + ".vbhtml"; - if (!(File.Exists(Server.MapPath(scriptFile)))) + if (!File.Exists(this.Server.MapPath(scriptFile))) { - //Return "" - scriptFile = ""; + // Return "" + scriptFile = string.Empty; } } @@ -48,13 +44,13 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); try { - if (! (string.IsNullOrEmpty(RazorScriptFile))) + if (!string.IsNullOrEmpty(this.RazorScriptFile)) { - var razorEngine = new RazorEngine(RazorScriptFile, ModuleContext, LocalResourceFile); + var razorEngine = new RazorEngine(this.RazorScriptFile, this.ModuleContext, this.LocalResourceFile); var writer = new StringWriter(); razorEngine.Render(writer); - Controls.Add(new LiteralControl(writer.ToString())); + this.Controls.Add(new LiteralControl(writer.ToString())); } } catch (Exception ex) diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs index ce483966f63..25a3d14f00b 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Razor { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.UI.Modules; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class RazorModuleControlFactory : BaseModuleControlFactory { @@ -21,13 +22,13 @@ public override Control CreateControl(TemplateControl containerControl, string c [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public override Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { - return CreateControl(containerControl, String.Empty, moduleConfiguration.ModuleControl.ControlSrc); + return this.CreateControl(containerControl, string.Empty, moduleConfiguration.ModuleControl.ControlSrc); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public override Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) { - return CreateControl(containerControl, String.Empty, controlSrc); + return this.CreateControl(containerControl, string.Empty, controlSrc); } } } diff --git a/DNN Platform/DotNetNuke.Web.Razor/Startup.cs b/DNN Platform/DotNetNuke.Web.Razor/Startup.cs index 53696454189..e7f080d6f00 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Startup.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Startup.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.DependencyInjection; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Razor { + using DotNetNuke.DependencyInjection; + using Microsoft.Extensions.DependencyInjection; + public class Startup : IDnnStartup { public void ConfigureServices(IServiceCollection services) diff --git a/DNN Platform/DotNetNuke.Web.Razor/packages.config b/DNN Platform/DotNetNuke.Web.Razor/packages.config index 319b210263a..3284de701ab 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/packages.config +++ b/DNN Platform/DotNetNuke.Web.Razor/packages.config @@ -8,4 +8,5 @@ + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs index dc00990661e..09048d61bd5 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs @@ -1,81 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Security.Principal; -using System.Threading; -using System.Threading.Tasks; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Auth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Security.Principal; + using System.Threading; + using System.Threading.Tasks; + + using DotNetNuke.Instrumentation; + public abstract class AuthMessageHandlerBase : DelegatingHandler { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthMessageHandlerBase)); - public abstract string AuthScheme { get; } - public virtual bool BypassAntiForgeryToken => false; - public bool DefaultInclude { get; } - public bool ForceSsl { get; } - protected AuthMessageHandlerBase(bool includeByDefault, bool forceSsl) { - DefaultInclude = includeByDefault; - ForceSsl = forceSsl; + this.DefaultInclude = includeByDefault; + this.ForceSsl = forceSsl; } - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - var response = OnInboundRequest(request, cancellationToken); - if(response != null) - { - response.RequestMessage = response.RequestMessage ?? request; //if someone returns new HttpResponseMessage(), fill in the requestMessage for other handlers in the chain - return Task.Factory.StartNew(() => response, cancellationToken); - } - - return base.SendAsync(request, cancellationToken).ContinueWith(x => OnOutboundResponse(x.Result, cancellationToken), cancellationToken); - } + public abstract string AuthScheme { get; } + + public virtual bool BypassAntiForgeryToken => false; + + public bool DefaultInclude { get; } + + public bool ForceSsl { get; } /// - /// A chance to process inbound requests + /// A chance to process inbound requests. /// - /// the request message - /// a cancellationtoken - /// null normally, if a response is returned all inbound processing is terminated and the resposne is returned + /// the request message. + /// a cancellationtoken. + /// null normally, if a response is returned all inbound processing is terminated and the resposne is returned. public virtual HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) { return null; } /// - /// A change to process outbound responses + /// A change to process outbound responses. /// - /// The response message - /// a cancellationtoken - /// the responsemessage + /// The response message. + /// a cancellationtoken. + /// the responsemessage. public virtual HttpResponseMessage OnOutboundResponse(HttpResponseMessage response, CancellationToken cancellationToken) { return response; } - protected bool NeedsAuthentication(HttpRequestMessage request) + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - if (MustEnforceSslInRequest(request)) + var response = this.OnInboundRequest(request, cancellationToken); + if (response != null) { - return !Thread.CurrentPrincipal.Identity.IsAuthenticated; - } - - if (Logger.IsTraceEnabled) - { - Logger.Trace($"{AuthScheme}: Validating request vs. SSL mode ({ForceSsl}) failed. "); + response.RequestMessage = response.RequestMessage ?? request; // if someone returns new HttpResponseMessage(), fill in the requestMessage for other handlers in the chain + return Task.Factory.StartNew(() => response, cancellationToken); } - // will let callers to return without authenticating the user - return false; + return base.SendAsync(request, cancellationToken).ContinueWith(x => this.OnOutboundResponse(x.Result, cancellationToken), cancellationToken); } protected static bool IsXmlHttpRequest(HttpRequestMessage request) @@ -86,23 +74,40 @@ protected static bool IsXmlHttpRequest(HttpRequestMessage request) { value = values.FirstOrDefault(); } + return !string.IsNullOrEmpty(value) && value.Equals("XmlHttpRequest", StringComparison.InvariantCultureIgnoreCase); } + protected static void SetCurrentPrincipal(IPrincipal principal, HttpRequestMessage request) + { + Thread.CurrentPrincipal = principal; + request.GetHttpContext().User = principal; + } + + protected bool NeedsAuthentication(HttpRequestMessage request) + { + if (this.MustEnforceSslInRequest(request)) + { + return !Thread.CurrentPrincipal.Identity.IsAuthenticated; + } + + if (Logger.IsTraceEnabled) + { + Logger.Trace($"{this.AuthScheme}: Validating request vs. SSL mode ({this.ForceSsl}) failed. "); + } + + // will let callers to return without authenticating the user + return false; + } + /// /// Validated the setting of the instane against the HTTP(S) request. /// /// True if matcher the request scheme; false otherwise. private bool MustEnforceSslInRequest(HttpRequestMessage request) { - return !ForceSsl || request.RequestUri.Scheme.Equals("HTTPS", StringComparison.InvariantCultureIgnoreCase); - } - - protected static void SetCurrentPrincipal(IPrincipal principal, HttpRequestMessage request) - { - Thread.CurrentPrincipal = principal; - request.GetHttpContext().User = principal; + return !this.ForceSsl || request.RequestUri.Scheme.Equals("HTTPS", StringComparison.InvariantCultureIgnoreCase); } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs index 189b19b26a9..21b9b462621 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs @@ -1,40 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Security.Principal; -using System.Text; -using System.Threading; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Membership; -using DotNetNuke.Web.ConfigSection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Auth { + using System; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Security.Principal; + using System.Text; + using System.Threading; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + using DotNetNuke.Web.ConfigSection; + public class BasicAuthMessageHandler : AuthMessageHandlerBase { - public override string AuthScheme => "Basic"; - private readonly Encoding _encoding = Encoding.GetEncoding("iso-8859-1"); public BasicAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { } + + public override string AuthScheme => "Basic"; public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) { - if(NeedsAuthentication(request)) + if (this.NeedsAuthentication(request)) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (portalSettings != null) { - TryToAuthenticate(request, portalSettings.PortalId); + this.TryToAuthenticate(request, portalSettings.PortalId); } } @@ -43,9 +44,9 @@ public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, public override HttpResponseMessage OnOutboundResponse(HttpResponseMessage response, CancellationToken cancellationToken) { - if (response.StatusCode == HttpStatusCode.Unauthorized && SupportsBasicAuth(response.RequestMessage)) + if (response.StatusCode == HttpStatusCode.Unauthorized && this.SupportsBasicAuth(response.RequestMessage)) { - response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(AuthScheme, "realm=\"DNNAPI\"")); + response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(this.AuthScheme, "realm=\"DNNAPI\"")); } return base.OnOutboundResponse(response, cancellationToken); @@ -58,7 +59,7 @@ private bool SupportsBasicAuth(HttpRequestMessage request) private void TryToAuthenticate(HttpRequestMessage request, int portalId) { - UserCredentials credentials = GetCredentials(request); + UserCredentials credentials = this.GetCredentials(request); if (credentials == null) { @@ -68,12 +69,12 @@ private void TryToAuthenticate(HttpRequestMessage request, int portalId) var status = UserLoginStatus.LOGIN_FAILURE; string ipAddress = request.GetIPAddress(); - UserInfo user = UserController.ValidateUser(portalId, credentials.UserName, credentials.Password, "DNN", "", - "a portal", ipAddress ?? "", ref status); + UserInfo user = UserController.ValidateUser(portalId, credentials.UserName, credentials.Password, "DNN", string.Empty, + "a portal", ipAddress ?? string.Empty, ref status); if (user != null) { - SetCurrentPrincipal(new GenericPrincipal(new GenericIdentity(credentials.UserName, AuthScheme), null), request); + SetCurrentPrincipal(new GenericPrincipal(new GenericIdentity(credentials.UserName, this.AuthScheme), null), request); } } @@ -84,42 +85,39 @@ private UserCredentials GetCredentials(HttpRequestMessage request) return null; } - if (request?.Headers.Authorization.Scheme.ToLower() != AuthScheme.ToLower()) + if (request?.Headers.Authorization.Scheme.ToLower() != this.AuthScheme.ToLower()) { return null; } string authorization = request?.Headers.Authorization.Parameter; - if (String.IsNullOrEmpty(authorization)) + if (string.IsNullOrEmpty(authorization)) { return null; } - string decoded = _encoding.GetString(Convert.FromBase64String(authorization)); + string decoded = this._encoding.GetString(Convert.FromBase64String(authorization)); - string[] parts = decoded.Split(new[] {':'}, 2); + string[] parts = decoded.Split(new[] { ':' }, 2); if (parts.Length < 2) { return null; } return new UserCredentials(parts[0], parts[1]); - } - - #region Nested type: UserCredentials - + } + internal class UserCredentials { public UserCredentials(string userName, string password) { - UserName = userName; - Password = password; + this.UserName = userName; + this.Password = password; } public string Password { get; set; } + public string UserName { get; set; } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs index b6fad0fc945..d903da4cb50 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs @@ -1,32 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Membership; -using DotNetNuke.Web.Api.Internal.Auth; -using DotNetNuke.Web.ConfigSection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Auth { + using System; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Threading; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Membership; + using DotNetNuke.Web.Api.Internal.Auth; + using DotNetNuke.Web.ConfigSection; + public class DigestAuthMessageHandler : AuthMessageHandlerBase { - public override string AuthScheme => DigestAuthentication.AuthenticationScheme; - public DigestAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { } + + public override string AuthScheme => DigestAuthentication.AuthenticationScheme; public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) { - if (NeedsAuthentication(request)) + if (this.NeedsAuthentication(request)) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (portalSettings != null) @@ -36,7 +37,7 @@ public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, if (isStale) { var staleResponse = request.CreateResponse(HttpStatusCode.Unauthorized); - AddStaleWwwAuthenticateHeader(staleResponse); + this.AddStaleWwwAuthenticateHeader(staleResponse); return staleResponse; } @@ -48,25 +49,14 @@ public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, public override HttpResponseMessage OnOutboundResponse(HttpResponseMessage response, CancellationToken cancellationToken) { - if (response.StatusCode == HttpStatusCode.Unauthorized && SupportsDigestAuth(response.RequestMessage)) + if (response.StatusCode == HttpStatusCode.Unauthorized && this.SupportsDigestAuth(response.RequestMessage)) { - AddWwwAuthenticateHeader(response); + this.AddWwwAuthenticateHeader(response); } return base.OnOutboundResponse(response, cancellationToken); } - private void AddStaleWwwAuthenticateHeader(HttpResponseMessage response) - { - AddWwwAuthenticateHeader(response, true); - } - - private void AddWwwAuthenticateHeader(HttpResponseMessage response, bool isStale = false) - { - var value = string.Format("realm=\"DNNAPI\", nonce=\"{0}\", opaque=\"0000000000000000\", stale={1}, algorithm=MD5, qop=\"auth\"", CreateNewNonce(), isStale); - response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(AuthScheme, value)); - } - private static string CreateNewNonce() { DateTime nonceTime = DateTime.Now + TimeSpan.FromMinutes(1); @@ -94,7 +84,7 @@ private static bool TryToAuthenticate(HttpRequestMessage request, int portalId) { SetCurrentPrincipal(digestAuthentication.User, request); } - else if(digestAuthentication.IsNonceStale) + else if (digestAuthentication.IsNonceStale) { return true; } @@ -102,6 +92,17 @@ private static bool TryToAuthenticate(HttpRequestMessage request, int portalId) return false; } + private void AddStaleWwwAuthenticateHeader(HttpResponseMessage response) + { + this.AddWwwAuthenticateHeader(response, true); + } + + private void AddWwwAuthenticateHeader(HttpResponseMessage response, bool isStale = false) + { + var value = string.Format("realm=\"DNNAPI\", nonce=\"{0}\", opaque=\"0000000000000000\", stale={1}, algorithm=MD5, qop=\"auth\"", CreateNewNonce(), isStale); + response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(this.AuthScheme, value)); + } + private bool SupportsDigestAuth(HttpRequestMessage request) { return !IsXmlHttpRequest(request) && MembershipProviderConfig.PasswordRetrievalEnabled; diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs b/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs index 63b3ad82ef6..e98ec9a7d49 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs @@ -1,46 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using System.Web.Http.Controllers; -using System.Web.Http.Filters; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using System.Web.Http.Controllers; + using System.Web.Http.Filters; + + using DotNetNuke.Common; + public abstract class AuthFilterBase : IAuthorizationFilter { /// - /// Tests if the request passes the authorization requirements - /// - /// The auth filter context - /// True when authorization is succesful - public abstract bool IsAuthorized(AuthFilterContext context); - - /// - /// Co-ordinates check of authorization and handles Auth failure. Should rarely be overridden. + /// Gets a value indicating whether more than one instance of the indicated attribute can be specified for a single program element. /// - /// - protected virtual void OnAuthorization(HttpActionContext actionContext) - { - Requires.NotNull("actionContext", actionContext); - - const string failureMessage = "Authorization has been denied for this request."; - var authFilterContext = new AuthFilterContext(actionContext, failureMessage); - if (!IsAuthorized(authFilterContext)) - { - authFilterContext.HandleUnauthorizedRequest(); - } - } - + public abstract bool AllowMultiple { get; } + /// - /// Gets or sets a value indicating whether more than one instance of the indicated attribute can be specified for a single program element. + /// Tests if the request passes the authorization requirements. /// - public abstract bool AllowMultiple { get; } + /// The auth filter context. + /// True when authorization is succesful. + public abstract bool IsAuthorized(AuthFilterContext context); Task IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func> continuation) { @@ -49,7 +34,7 @@ Task IAuthorizationFilter.ExecuteAuthorizationFilterAsync(H try { - OnAuthorization(actionContext); + this.OnAuthorization(actionContext); } catch (Exception e) { @@ -64,8 +49,24 @@ Task IAuthorizationFilter.ExecuteAuthorizationFilterAsync(H tcs.SetResult(actionContext.Response); return tcs.Task; } - + return continuation(); } + + /// + /// Co-ordinates check of authorization and handles Auth failure. Should rarely be overridden. + /// + /// + protected virtual void OnAuthorization(HttpActionContext actionContext) + { + Requires.NotNull("actionContext", actionContext); + + const string failureMessage = "Authorization has been denied for this request."; + var authFilterContext = new AuthFilterContext(actionContext, failureMessage); + if (!this.IsAuthorized(authFilterContext)) + { + authFilterContext.HandleUnauthorizedRequest(); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs b/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs index c225f6129a8..a983167df84 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using System.Web.Http.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Net; + using System.Net.Http; + using System.Web.Http.Controllers; + public class AuthFilterContext { public AuthFilterContext(HttpActionContext actionContext, string authFailureMessage) { - ActionContext = actionContext; - AuthFailureMessage = authFailureMessage; + this.ActionContext = actionContext; + this.AuthFailureMessage = authFailureMessage; } public HttpActionContext ActionContext { get; private set; } + public string AuthFailureMessage { get; set; } /// @@ -26,7 +27,7 @@ public AuthFilterContext(HttpActionContext actionContext, string authFailureMess /// public virtual void HandleUnauthorizedRequest() { - ActionContext.Response = ActionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, AuthFailureMessage); + this.ActionContext.Response = this.ActionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, this.AuthFailureMessage); } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs b/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs index 2dd614a3bf8..117d098c114 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs @@ -1,23 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Filters; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Linq; + using System.Web.Http; + using System.Web.Http.Controllers; + using System.Web.Http.Filters; + + using DotNetNuke.Common; + public abstract class AuthorizeAttributeBase : AuthorizationFilterAttribute { + public static bool IsAnonymousAttributePresent(HttpActionContext actionContext) + { + return actionContext.ActionDescriptor.GetCustomAttributes().Any() + || (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any() + && actionContext.ActionDescriptor.GetCustomAttributes().All(t => t is SupportedModulesAttribute)); + } + /// - /// Tests if the request passes the authorization requirements + /// Tests if the request passes the authorization requirements. /// - /// The auth filter context - /// True when authorization is succesful + /// The auth filter context. + /// True when authorization is succesful. public abstract bool IsAuthorized(AuthFilterContext context); /// @@ -28,21 +36,21 @@ public override void OnAuthorization(HttpActionContext actionContext) { Requires.NotNull("actionContext", actionContext); - if (SkipAuthorization(actionContext)) + if (this.SkipAuthorization(actionContext)) { return; } const string failureMessage = "Authorization has been denied for this request."; var authFilterContext = new AuthFilterContext(actionContext, failureMessage); - if (!IsAuthorized(authFilterContext)) + if (!this.IsAuthorized(authFilterContext)) { authFilterContext.HandleUnauthorizedRequest(); } } /// - /// Skips this authorization step if anonymous attribute is applied, override if auth should never be skipped, or other conditions are required + /// Skips this authorization step if anonymous attribute is applied, override if auth should never be skipped, or other conditions are required. /// /// /// @@ -50,12 +58,5 @@ protected virtual bool SkipAuthorization(HttpActionContext actionContext) { return IsAnonymousAttributePresent(actionContext); } - - public static bool IsAnonymousAttributePresent(HttpActionContext actionContext) - { - return actionContext.ActionDescriptor.GetCustomAttributes().Any() - || (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any() - && actionContext.ActionDescriptor.GetCustomAttributes().All(t => t is SupportedModulesAttribute)); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs b/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs index f850b9ae6a5..f574289fb31 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Http; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Web.Http; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + [DnnExceptionFilter] public abstract class DnnApiController : ApiController { @@ -17,16 +18,11 @@ public abstract class DnnApiController : ApiController protected DnnApiController() { - _activeModule = new Lazy(InitModuleInfo); - } - - private ModuleInfo InitModuleInfo() - { - return Request.FindModuleInfo(); + this._activeModule = new Lazy(this.InitModuleInfo); } /// - /// PortalSettings for the current portal + /// Gets portalSettings for the current portal. /// public PortalSettings PortalSettings { @@ -37,16 +33,25 @@ public PortalSettings PortalSettings } /// - /// UserInfo for the current user + /// Gets userInfo for the current user. /// - public UserInfo UserInfo { get { return PortalSettings.UserInfo; } } + public UserInfo UserInfo + { + get { return this.PortalSettings.UserInfo; } + } /// - /// ModuleInfo for the current module + /// Gets moduleInfo for the current module. /// Will be null unless a valid pair of module and tab ids were provided in the request /// - public ModuleInfo ActiveModule { - get { return _activeModule.Value; } + public ModuleInfo ActiveModule + { + get { return this._activeModule.Value; } + } + + private ModuleInfo InitModuleInfo() + { + return this.Request.FindModuleInfo(); } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs index a7e90bbefe5..81674351f8d 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs @@ -1,18 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + public sealed class DnnAuthorizeAttribute : AuthorizeAttributeBase, IOverrideDefaultAuthLevel { + private static readonly List DefaultAuthTypes = new List(); + + private static readonly string[] EmptyArray = new string[0]; + private string _staticRoles; private string[] _staticRolesSplit = new string[0]; @@ -22,52 +27,53 @@ public sealed class DnnAuthorizeAttribute : AuthorizeAttributeBase, IOverrideDef private string _authTypes; private string[] _authTypesSplit = new string[0]; - private static readonly List DefaultAuthTypes = new List(); - - internal static void AppendToDefaultAuthTypes(string authType) - { - if (!string.IsNullOrEmpty(authType)) - { - DefaultAuthTypes.Add(authType.Trim()); - } - } - /// - /// Gets or sets the authorized roles (separated by comma) + /// Gets or sets the authorized roles (separated by comma). /// public string StaticRoles { - get { return _staticRoles; } + get { return this._staticRoles; } + set { - _staticRoles = value; - _staticRolesSplit = SplitString(_staticRoles); + this._staticRoles = value; + this._staticRolesSplit = SplitString(this._staticRoles); } } /// - /// Gets or sets the denied roles (separated by comma) + /// Gets or sets the denied roles (separated by comma). /// public string DenyRoles { - get { return _denyRoles; } - set - { - _denyRoles = value; - _denyRolesSplit = SplitString(_denyRoles); + get { return this._denyRoles; } + + set + { + this._denyRoles = value; + this._denyRolesSplit = SplitString(this._denyRoles); } } /// - /// Gets or sets the allowed authentication types (separated by comma) + /// Gets or sets the allowed authentication types (separated by comma). /// public string AuthTypes { - get { return _authTypes; } - set + get { return this._authTypes; } + + set { - _authTypes = value; - _authTypesSplit = SplitString(_authTypes); + this._authTypes = value; + this._authTypesSplit = SplitString(this._authTypes); + } + } + + internal static void AppendToDefaultAuthTypes(string authType) + { + if (!string.IsNullOrEmpty(authType)) + { + DefaultAuthTypes.Add(authType.Trim()); } } @@ -76,37 +82,37 @@ public override bool IsAuthorized(AuthFilterContext context) Requires.NotNull("context", context); var identity = Thread.CurrentPrincipal.Identity; - if(!identity.IsAuthenticated) + if (!identity.IsAuthenticated) { return false; } - if(_denyRolesSplit.Any()) + if (this._denyRolesSplit.Any()) { var currentUser = PortalController.Instance.GetCurrentPortalSettings().UserInfo; - if (!currentUser.IsSuperUser && _denyRolesSplit.Any(currentUser.IsInRole)) + if (!currentUser.IsSuperUser && this._denyRolesSplit.Any(currentUser.IsInRole)) { return false; } } - if (_staticRolesSplit.Any()) + if (this._staticRolesSplit.Any()) { var currentUser = PortalController.Instance.GetCurrentPortalSettings().UserInfo; - if (!_staticRolesSplit.Any(currentUser.IsInRole)) + if (!this._staticRolesSplit.Any(currentUser.IsInRole)) { return false; } } - // if the attribute opted in explicitly for specific authentication types, then + // if the attribute opted in explicitly for specific authentication types, then // use it; otherwise use the defaults according to settings in the web.config. - var currentAuthType = (identity.AuthenticationType ?? "").Trim(); + var currentAuthType = (identity.AuthenticationType ?? string.Empty).Trim(); if (currentAuthType.Length > 0) { - if (_authTypesSplit.Any()) + if (this._authTypesSplit.Any()) { - return _authTypesSplit.Contains(currentAuthType); + return this._authTypesSplit.Contains(currentAuthType); } return DefaultAuthTypes.Contains(currentAuthType); @@ -114,8 +120,7 @@ public override bool IsAuthorized(AuthFilterContext context) return true; } - - private static readonly string[] EmptyArray = new string[0]; + private static string[] SplitString(string original) { if (string.IsNullOrEmpty(original)) @@ -123,7 +128,7 @@ private static string[] SplitString(string original) return EmptyArray; } - var split = original.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries) + var split = original.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s)); return split.ToArray(); } diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnExceptionAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/DnnExceptionAttribute.cs index e5ba8393161..ddba32096a9 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnExceptionAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnExceptionAttribute.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using System.Web.Http.Filters; - -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Net; + using System.Net.Http; + using System.Web.Http.Filters; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + public class DnnExceptionFilterAttribute : ExceptionFilterAttribute { public string MessageKey { get; set; } @@ -26,11 +26,11 @@ public override void OnException(HttpActionExecutedContext actionExecutedContext var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; var controllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName; - var resourceFile = string.IsNullOrEmpty(LocalResourceFile) + var resourceFile = string.IsNullOrEmpty(this.LocalResourceFile) ? Localization.ExceptionsResourceFile - : LocalResourceFile; + : this.LocalResourceFile; - var key = string.IsNullOrEmpty(MessageKey) ? controllerName + "_" + actionName + ".Error" : MessageKey; + var key = string.IsNullOrEmpty(this.MessageKey) ? controllerName + "_" + actionName + ".Error" : this.MessageKey; HttpStatusCode statusCode; if (exception is NotImplementedException) @@ -57,7 +57,7 @@ public override void OnException(HttpActionExecutedContext actionExecutedContext var response = new HttpResponseMessage { StatusCode = statusCode, - ReasonPhrase = Localization.GetString(key, resourceFile) + ReasonPhrase = Localization.GetString(key, resourceFile), }; actionExecutedContext.Response = response; diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs b/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs index d7b538c6300..849eef08d7a 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Dispatcher; -using System.Web.Http.Routing; -using DotNetNuke.Common; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + using System.Web.Http.Controllers; + using System.Web.Http.Dispatcher; + using System.Web.Http.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Services.Localization; + internal class DnnHttpControllerSelector : IHttpControllerSelector { private const string ControllerSuffix = "Controller"; @@ -29,47 +30,49 @@ public DnnHttpControllerSelector(HttpConfiguration configuration) { Requires.NotNull("configuration", configuration); - _configuration = configuration; - _descriptorCache = new Lazy>(InitTypeCache, - isThreadSafe: true); + this._configuration = configuration; + this._descriptorCache = new Lazy>( + this.InitTypeCache, + isThreadSafe: true); } private ConcurrentDictionary DescriptorCache { - get { return _descriptorCache.Value; } + get { return this._descriptorCache.Value; } } public HttpControllerDescriptor SelectController(HttpRequestMessage request) { Requires.NotNull("request", request); - string controllerName = GetControllerName(request); - IEnumerable namespaces = GetNameSpaces(request); - if (namespaces == null || !namespaces.Any() || String.IsNullOrEmpty(controllerName)) + string controllerName = this.GetControllerName(request); + IEnumerable namespaces = this.GetNameSpaces(request); + if (namespaces == null || !namespaces.Any() || string.IsNullOrEmpty(controllerName)) { - throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, - "Unable to locate a controller for " + + throw new HttpResponseException(request.CreateErrorResponse( + HttpStatusCode.NotFound, + "Unable to locate a controller for " + request.RequestUri)); } var matches = new List(); foreach (string ns in namespaces) { - string fullName = GetFullName(controllerName, ns); + string fullName = this.GetFullName(controllerName, ns); HttpControllerDescriptor descriptor; - if (DescriptorCache.TryGetValue(fullName, out descriptor)) + if (this.DescriptorCache.TryGetValue(fullName, out descriptor)) { matches.Add(descriptor); } } - if(matches.Count == 1) + if (matches.Count == 1) { return matches.First(); } - //only errors thrown beyond this point + // only errors thrown beyond this point if (matches.Count == 0) { throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format(Localization.GetString("ControllerNotFound", Localization.ExceptionsResourceFile), request.RequestUri, string.Join(", ", namespaces)))); @@ -80,7 +83,7 @@ public HttpControllerDescriptor SelectController(HttpRequestMessage request) public IDictionary GetControllerMapping() { - return DescriptorCache; + return this.DescriptorCache; } private string GetFullName(string controllerName, string ns) @@ -115,8 +118,8 @@ private string GetControllerName(HttpRequestMessage request) private ConcurrentDictionary InitTypeCache() { - IAssembliesResolver assembliesResolver = _configuration.Services.GetAssembliesResolver(); - IHttpControllerTypeResolver controllersResolver = _configuration.Services.GetHttpControllerTypeResolver(); + IAssembliesResolver assembliesResolver = this._configuration.Services.GetAssembliesResolver(); + IHttpControllerTypeResolver controllersResolver = this._configuration.Services.GetHttpControllerTypeResolver(); ICollection controllerTypes = controllersResolver.GetControllerTypes(assembliesResolver); @@ -127,7 +130,7 @@ private ConcurrentDictionary InitTypeCache() if (type.FullName != null) { string controllerName = type.Name.Substring(0, type.Name.Length - ControllerSuffix.Length); - dict.TryAdd(type.FullName.ToLowerInvariant(), new HttpControllerDescriptor(_configuration, controllerName, type)); + dict.TryAdd(type.FullName.ToLowerInvariant(), new HttpControllerDescriptor(this._configuration, controllerName, type)); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs index e3c306df20f..4d89fb32c5f 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs @@ -1,32 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Net.Http; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + public class DnnModuleAuthorizeAttribute : AuthorizeAttributeBase, IOverrideDefaultAuthLevel { public DnnModuleAuthorizeAttribute() { - AccessLevel = SecurityAccessLevel.Host; + this.AccessLevel = SecurityAccessLevel.Host; } public string PermissionKey { get; set; } + public SecurityAccessLevel AccessLevel { get; set; } public override bool IsAuthorized(AuthFilterContext context) { - var activeModule = FindModuleInfo(context.ActionContext.Request); + var activeModule = this.FindModuleInfo(context.ActionContext.Request); if (activeModule != null) { - return ModulePermissionController.HasModuleAccess(AccessLevel, PermissionKey, activeModule); + return ModulePermissionController.HasModuleAccess(this.AccessLevel, this.PermissionKey, activeModule); } return false; diff --git a/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs index a4894ed04d7..d4d65dc29b7 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.DependencyInjection.Extensions; -using DotNetNuke.Web.Api; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Extensions { + using System; + using System.Linq; + + using DotNetNuke.DependencyInjection.Extensions; + using DotNetNuke.Web.Api; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; + /// /// Adds DNN Web API Specific startup extensions to simplify the /// Class. diff --git a/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs index bc88f7a6922..b9b92643563 100644 --- a/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Web.Http; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Web.Http; + + using DotNetNuke.Common; + public static class HttpConfigurationExtensions { private const string Key = "TabAndModuleInfoProvider"; @@ -21,7 +22,7 @@ public static void AddTabAndModuleInfoProvider(this HttpConfiguration configurat var providers = configuration.Properties.GetOrAdd(Key, InitValue) as ConcurrentQueue; - if(providers == null) + if (providers == null) { providers = new ConcurrentQueue(); configuration.Properties[Key] = providers; @@ -30,11 +31,6 @@ public static void AddTabAndModuleInfoProvider(this HttpConfiguration configurat providers.Enqueue(tabAndModuleInfoProvider); } - private static object InitValue(object o) - { - return new ConcurrentQueue(); - } - public static IEnumerable GetTabAndModuleInfoProviders(this HttpConfiguration configuration) { Requires.NotNull("configuration", configuration); @@ -43,11 +39,16 @@ public static IEnumerable GetTabAndModuleInfoProvider if (providers == null) { - //shouldn't ever happen outside of unit tests - return new ITabAndModuleInfoProvider[]{}; + // shouldn't ever happen outside of unit tests + return new ITabAndModuleInfoProvider[] { }; } return providers.ToArray(); } + + private static object InitValue(object o) + { + return new ConcurrentQueue(); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs index 45c08254396..c6e558b6c2c 100644 --- a/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs @@ -1,39 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Net.Http; -using System.Web; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.UserRequest; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System.Net.Http; + using System.Web; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.UserRequest; + public static class HttpRequestMessageExtensions { + private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out T output); + public static int FindTabId(this HttpRequestMessage request) { return IterateTabAndModuleInfoProviders(request, TryFindTabId, -1); } - private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out int output) + public static ModuleInfo FindModuleInfo(this HttpRequestMessage request) { - return provider.TryFindTabId(request, out output); + return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); } - public static ModuleInfo FindModuleInfo(this HttpRequestMessage request) + public static int FindModuleId(this HttpRequestMessage request) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); + return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); } - private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out ModuleInfo output) + public static HttpContextBase GetHttpContext(this HttpRequestMessage request) { - return provider.TryFindModuleInfo(request, out output); + object context; + request.Properties.TryGetValue("MS_HttpContext", out context); + + return context as HttpContextBase; } - public static int FindModuleId(this HttpRequestMessage request) + public static string GetIPAddress(this HttpRequestMessage request) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(GetHttpContext(request).Request); + } + + private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out int output) + { + return provider.TryFindTabId(request, out output); + } + + private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out ModuleInfo output) + { + return provider.TryFindModuleInfo(request, out output); } private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out int output) @@ -41,8 +57,6 @@ private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequ return provider.TryFindModuleId(request, out output); } - private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out T output); - private static T IterateTabAndModuleInfoProviders(HttpRequestMessage request, TryMethod func, T fallback) { var providers = request.GetConfiguration().GetTabAndModuleInfoProviders(); @@ -58,18 +72,5 @@ private static T IterateTabAndModuleInfoProviders(HttpRequestMessage request, return fallback; } - - public static HttpContextBase GetHttpContext(this HttpRequestMessage request) - { - object context; - request.Properties.TryGetValue("MS_HttpContext", out context); - - return context as HttpContextBase; - } - - public static string GetIPAddress(this HttpRequestMessage request) - { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(GetHttpContext(request).Request); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/HttpStatusCodeAdditions.cs b/DNN Platform/DotNetNuke.Web/Api/HttpStatusCodeAdditions.cs index d5c2e2df1cc..782803afb6f 100644 --- a/DNN Platform/DotNetNuke.Web/Api/HttpStatusCodeAdditions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/HttpStatusCodeAdditions.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { /// - /// Enumeration that contains HTTP Status Codes that are not included in the HttpStatusCode enumeration provided by the .NET framework + /// Enumeration that contains HTTP Status Codes that are not included in the HttpStatusCode enumeration provided by the .NET framework. /// public enum HttpStatusCodeAdditions { @@ -17,6 +17,6 @@ public enum HttpStatusCodeAdditions /// http://tools.ietf.org/html/rfc4918 /// /// - UnprocessableEntity = 422 + UnprocessableEntity = 422, } } diff --git a/DNN Platform/DotNetNuke.Web/Api/IMapRoute.cs b/DNN Platform/DotNetNuke.Web/Api/IMapRoute.cs index 28c18621a71..24afba4be6f 100644 --- a/DNN Platform/DotNetNuke.Web/Api/IMapRoute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/IMapRoute.cs @@ -1,49 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections.Generic; + using System.Web.Routing; + public interface IMapRoute { /// - /// Sets up the route(s) for DotNetNuke services + /// Sets up the route(s) for DotNetNuke services. /// - /// The name of the folder under DesktopModules in which your module resides - /// A unique name for the route - /// The parameterized portion of the route - /// Default values for the route parameters - /// The constraints - /// The namespace(s) in which to search for the controllers for this route + /// The name of the folder under DesktopModules in which your module resides. + /// A unique name for the route. + /// The parameterized portion of the route. + /// Default values for the route parameters. + /// The constraints. + /// The namespace(s) in which to search for the controllers for this route. /// A list of all routes that were registered. - /// The combination of moduleFolderName and routeName must be unique for each route + /// The combination of moduleFolderName and routeName must be unique for each route. IList MapHttpRoute(string moduleFolderName, string routeName, string url, object defaults, object constraints, string[] namespaces); /// - /// Sets up the route(s) for DotNetNuke services + /// Sets up the route(s) for DotNetNuke services. /// - /// The name of the folder under DesktopModules in which your module resides - /// A unique name for the route - /// The parameterized portion of the route - /// Default values for the route parameters - /// The namespace(s) in which to search for the controllers for this route + /// The name of the folder under DesktopModules in which your module resides. + /// A unique name for the route. + /// The parameterized portion of the route. + /// Default values for the route parameters. + /// The namespace(s) in which to search for the controllers for this route. /// A list of all routes that were registered. - /// The combination of moduleFolderName and routeName must be unique for each route + /// The combination of moduleFolderName and routeName must be unique for each route. IList MapHttpRoute(string moduleFolderName, string routeName, string url, object defaults, string[] namespaces); /// - /// Sets up the route(s) for DotNetNuke services + /// Sets up the route(s) for DotNetNuke services. /// - /// The name of the folder under DesktopModules in which your module resides - /// A unique name for the route - /// The parameterized portion of the route - /// The namespace(s) in which to search for the controllers for this route + /// The name of the folder under DesktopModules in which your module resides. + /// A unique name for the route. + /// The parameterized portion of the route. + /// The namespace(s) in which to search for the controllers for this route. /// A list of all routes that were registered. - /// The combination of moduleFolderName and routeName must be unique for each route + /// The combination of moduleFolderName and routeName must be unique for each route. IList MapHttpRoute(string moduleFolderName, string routeName, string url, string[] namespaces); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/IOverrideDefaultAuthLevel.cs b/DNN Platform/DotNetNuke.Web/Api/IOverrideDefaultAuthLevel.cs index d00f992b679..1e0e9c68d6b 100644 --- a/DNN Platform/DotNetNuke.Web/Api/IOverrideDefaultAuthLevel.cs +++ b/DNN Platform/DotNetNuke.Web/Api/IOverrideDefaultAuthLevel.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + /// /// Implementing this interface on an Auth filter will allow the filter to override the default - /// Host level auth provided by DnnController + /// Host level auth provided by DnnController. /// public interface IOverrideDefaultAuthLevel { - //no need for methods the mere presence of this interface acts as a flag to OverridableHostAuthFilter + // no need for methods the mere presence of this interface acts as a flag to OverridableHostAuthFilter } } diff --git a/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs b/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs index b7ae77702b4..5e901ab8c67 100644 --- a/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs @@ -1,21 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Http.Routing; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections.Generic; + using System.Web.Http.Routing; + + using DotNetNuke.Entities.Portals; + internal interface IPortalAliasRouteManager { IEnumerable GetRoutePrefixCounts(); + string GetRouteName(string moduleFolderName, string routeName, int count); + string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias); + HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues); + string GetRouteUrl(string moduleFolderName, string url, int count); + void ClearCachedData(); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/IServiceRouteMapper.cs b/DNN Platform/DotNetNuke.Web/Api/IServiceRouteMapper.cs index 3eea8f9e2b9..374056ef459 100644 --- a/DNN Platform/DotNetNuke.Web/Api/IServiceRouteMapper.cs +++ b/DNN Platform/DotNetNuke.Web/Api/IServiceRouteMapper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + public interface IServiceRouteMapper { void RegisterRoutes(IMapRoute mapRouteManager); diff --git a/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs index 6622a4a88c6..6d1cbf993e7 100644 --- a/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs @@ -1,16 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Net.Http; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System.Net.Http; + + using DotNetNuke.Entities.Modules; + public interface ITabAndModuleInfoProvider { bool TryFindTabId(HttpRequestMessage request, out int tabId); + bool TryFindModuleId(HttpRequestMessage request, out int moduleId); + bool TryFindModuleInfo(HttpRequestMessage request, out ModuleInfo moduleInfo); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgery.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgery.cs index 3e483c59a30..1c87d13cb04 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgery.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgery.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using System; + + using DotNetNuke.Framework; + public class AntiForgery : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs index 920500af574..e63b954e8c6 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs @@ -1,12 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { internal class AntiForgeryImpl : IAntiForgery { - public string CookieName { get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } } + public string CookieName + { + get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } + } + public void Validate(string cookieToken, string headerToken) { System.Web.Helpers.AntiForgery.Validate(cookieToken, headerToken); diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs index d66f46a5af0..38e05f87b8b 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Security.Cryptography; -using System.Security.Principal; -using System.Text; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Membership; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal.Auth { + using System; + using System.Security.Cryptography; + using System.Security.Principal; + using System.Text; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + internal class DigestAuthentication { internal const string AuthenticationScheme = "Digest"; @@ -20,125 +21,131 @@ internal class DigestAuthentication private readonly int _portalId; private readonly string _ipAddress; + public DigestAuthentication(DigestAuthenticationRequest request, int portalId, string ipAddress) + { + this._request = request; + this._portalId = portalId; + this._ipAddress = ipAddress ?? string.Empty; + this.AuthenticateRequest(); + } + public DigestAuthenticationRequest Request { - get { return _request; } - set { _request = value; } + get { return this._request; } + set { this._request = value; } } public bool IsValid { get; private set; } public bool IsNonceStale { get; private set; } + public IPrincipal User { get; private set; } + public string CalculateHashedDigest() { - return CreateMd5HashBinHex(GenerateUnhashedDigest()); + return CreateMd5HashBinHex(this.GenerateUnhashedDigest()); } - public IPrincipal User { get; private set; } + private static string CreateMd5HashBinHex(string val) + { + // Services.Logging.LoggingController.SimpleLog(String.Format("Creating Hash for {0}", val)) + // Services.Logging.LoggingController.SimpleLog(String.Format("Back and forth: {0}", Encoding.Default.GetString(Encoding.Default.GetBytes(val)))) + byte[] bha1 = Md5.ComputeHash(Encoding.Default.GetBytes(val)); + string ha1 = string.Empty; + for (int i = 0; i <= 15; i++) + { + ha1 += string.Format("{0:x02}", bha1[i]); + } + + return ha1; + } - public DigestAuthentication(DigestAuthenticationRequest request, int portalId, string ipAddress) + // the nonce is created in DotNetNuke.Web.Api.DigestAuthMessageHandler + private static bool IsNonceValid(string nonce) { - _request = request; - _portalId = portalId; - _ipAddress = ipAddress ?? ""; - AuthenticateRequest(); + DateTime expireTime; + + int numPadChars = nonce.Length % 4; + if (numPadChars > 0) + { + numPadChars = 4 - numPadChars; + } + + string newNonce = nonce.PadRight(nonce.Length + numPadChars, '='); + + try + { + byte[] decodedBytes = Convert.FromBase64String(newNonce); + string expireStr = Encoding.Default.GetString(decodedBytes); + expireTime = DateTime.Parse(expireStr); + } + catch (FormatException) + { + return false; + } + + return DateTime.Now <= expireTime; } private void AuthenticateRequest() { - _password = GetPassword(Request); - if(_password != null) + this._password = this.GetPassword(this.Request); + if (this._password != null) { - IsNonceStale = ! (IsNonceValid(_request.RequestParams["nonce"])); - //Services.Logging.LoggingController.SimpleLog(String.Format("Request hash: {0} - Response Hash: {1}", _request.RequestParams("response"), HashedDigest)) - if ((! IsNonceStale) && _request.RequestParams["response"] == CalculateHashedDigest()) + this.IsNonceStale = !IsNonceValid(this._request.RequestParams["nonce"]); + + // Services.Logging.LoggingController.SimpleLog(String.Format("Request hash: {0} - Response Hash: {1}", _request.RequestParams("response"), HashedDigest)) + if ((!this.IsNonceStale) && this._request.RequestParams["response"] == this.CalculateHashedDigest()) { - IsValid = true; - User = new GenericPrincipal(new GenericIdentity(_request.RawUsername, AuthenticationScheme), null); + this.IsValid = true; + this.User = new GenericPrincipal(new GenericIdentity(this._request.RawUsername, AuthenticationScheme), null); } } } private string GetPassword(DigestAuthenticationRequest request) { - UserInfo user = UserController.GetUserByName(_portalId, request.CleanUsername); + UserInfo user = UserController.GetUserByName(this._portalId, request.CleanUsername); if (user == null) { - user = UserController.GetUserByName(_portalId, request.RawUsername); + user = UserController.GetUserByName(this._portalId, request.RawUsername); } + if (user == null) { return null; } - var password = UserController.GetPassword(ref user, ""); - - //Try to validate user + + var password = UserController.GetPassword(ref user, string.Empty); + + // Try to validate user var loginStatus = UserLoginStatus.LOGIN_FAILURE; - user = UserController.ValidateUser(_portalId, user.Username, password, "DNN", "", _ipAddress, ref loginStatus); + user = UserController.ValidateUser(this._portalId, user.Username, password, "DNN", string.Empty, this._ipAddress, ref loginStatus); return user != null ? password : null; } private string GenerateUnhashedDigest() { - string a1 = String.Format("{0}:{1}:{2}", _request.RequestParams["username"].Replace("\\\\", "\\"), - _request.RequestParams["realm"], _password); + string a1 = string.Format("{0}:{1}:{2}", this._request.RequestParams["username"].Replace("\\\\", "\\"), + this._request.RequestParams["realm"], this._password); string ha1 = CreateMd5HashBinHex(a1); - string a2 = String.Format("{0}:{1}", _request.HttpMethod, _request.RequestParams["uri"]); + string a2 = string.Format("{0}:{1}", this._request.HttpMethod, this._request.RequestParams["uri"]); string ha2 = CreateMd5HashBinHex(a2); string unhashedDigest; - if (_request.RequestParams["qop"] != null) + if (this._request.RequestParams["qop"] != null) { - unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", ha1, _request.RequestParams["nonce"], - _request.RequestParams["nc"], _request.RequestParams["cnonce"], - _request.RequestParams["qop"], ha2); + unhashedDigest = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", ha1, this._request.RequestParams["nonce"], + this._request.RequestParams["nc"], this._request.RequestParams["cnonce"], + this._request.RequestParams["qop"], ha2); } else { - unhashedDigest = String.Format("{0}:{1}:{2}", ha1, _request.RequestParams["nonce"], ha2); + unhashedDigest = string.Format("{0}:{1}:{2}", ha1, this._request.RequestParams["nonce"], ha2); } - //Services.Logging.LoggingController.SimpleLog(A1, HA1, A2, HA2, unhashedDigest) + + // Services.Logging.LoggingController.SimpleLog(A1, HA1, A2, HA2, unhashedDigest) return unhashedDigest; } - - private static string CreateMd5HashBinHex(string val) - { - //Services.Logging.LoggingController.SimpleLog(String.Format("Creating Hash for {0}", val)) - //Services.Logging.LoggingController.SimpleLog(String.Format("Back and forth: {0}", Encoding.Default.GetString(Encoding.Default.GetBytes(val)))) - byte[] bha1 = Md5.ComputeHash(Encoding.Default.GetBytes(val)); - string ha1 = ""; - for (int i = 0; i <= 15; i++) - { - ha1 += String.Format("{0:x02}", bha1[i]); - } - return ha1; - } - - //the nonce is created in DotNetNuke.Web.Api.DigestAuthMessageHandler - private static bool IsNonceValid(string nonce) - { - DateTime expireTime; - - int numPadChars = nonce.Length%4; - if (numPadChars > 0) - { - numPadChars = 4 - numPadChars; - } - string newNonce = nonce.PadRight(nonce.Length + numPadChars, '='); - - try - { - byte[] decodedBytes = Convert.FromBase64String(newNonce); - string expireStr = Encoding.Default.GetString(decodedBytes); - expireTime = DateTime.Parse(expireStr); - } - catch (FormatException) - { - return false; - } - - return (DateTime.Now <= expireTime); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs index 8a5dd1689ff..cd85037e860 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs @@ -1,50 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using System.Text.RegularExpressions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal.Auth { + using System; + using System.Collections.Specialized; + using System.Text.RegularExpressions; + internal class DigestAuthenticationRequest { private static readonly Regex AuthHeaderRegex = new Regex("\\s?(?'name'\\w+)=(\"(?'value'[^\"]+)\"|(?'value'[^,]+))", RegexOptions.Compiled); public DigestAuthenticationRequest(string authorizationHeader, string httpMethod) { - //Authorization: Digest - //username="Mufasa", - //realm="testrealm@host.com", - //nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", - //uri="/dir/index.html", - //qop=auth, - //nc=00000001, - //cnonce="0a4f113b", - //response="6629fae49393a05397450978507c4ef1", - //opaque="5ccc069c403ebaf9f0171e9517f40e41" + // Authorization: Digest + // username="Mufasa", + // realm="testrealm@host.com", + // nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", + // uri="/dir/index.html", + // qop=auth, + // nc=00000001, + // cnonce="0a4f113b", + // response="6629fae49393a05397450978507c4ef1", + // opaque="5ccc069c403ebaf9f0171e9517f40e41" try { - RequestParams = new NameValueCollection(); + this.RequestParams = new NameValueCollection(); foreach (Match m in AuthHeaderRegex.Matches(authorizationHeader)) { - RequestParams.Add(m.Groups["name"].Value, m.Groups["value"].Value); + this.RequestParams.Add(m.Groups["name"].Value, m.Groups["value"].Value); } - HttpMethod = httpMethod; - RawUsername = RequestParams["username"].Replace("\\\\", "\\"); - CleanUsername = RawUsername; - if (CleanUsername.LastIndexOf("\\", System.StringComparison.Ordinal) > 0) + + this.HttpMethod = httpMethod; + this.RawUsername = this.RequestParams["username"].Replace("\\\\", "\\"); + this.CleanUsername = this.RawUsername; + if (this.CleanUsername.LastIndexOf("\\", System.StringComparison.Ordinal) > 0) { - CleanUsername = CleanUsername.Substring(CleanUsername.LastIndexOf("\\", System.StringComparison.Ordinal) + 2 - 1); + this.CleanUsername = this.CleanUsername.Substring(this.CleanUsername.LastIndexOf("\\", System.StringComparison.Ordinal) + 2 - 1); } } catch (Exception) { - - //suppress any issue e.g. another 401 from a different auth method + // suppress any issue e.g. another 401 from a different auth method } - } public NameValueCollection RequestParams { get; set; } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/WebFormsAuthMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/WebFormsAuthMessageHandler.cs index 4a9e14eb1f3..107265a95e1 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/WebFormsAuthMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/WebFormsAuthMessageHandler.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Net.Http; -using System.Threading; -using DotNetNuke.HttpModules.Membership; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal.Auth { + using System.Net.Http; + using System.Threading; + + using DotNetNuke.HttpModules.Membership; + public class WebFormsAuthMessageHandler : MessageProcessingHandler { public string AuthScheme => "Forms"; diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnActionFilterProvider.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnActionFilterProvider.cs index ff07d8640f6..d63d1595f8a 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnActionFilterProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnActionFilterProvider.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Filters; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using System.Collections.Generic; + using System.Linq; + using System.Web.Http; + using System.Web.Http.Controllers; + using System.Web.Http.Filters; + + using DotNetNuke.Common; + internal class DnnActionFilterProvider : IFilterProvider { public IEnumerable GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor) { - //Requires.NotNull("configuration", configuration); + // Requires.NotNull("configuration", configuration); Requires.NotNull("actionDescriptor", actionDescriptor); var controllerFilters = actionDescriptor.ControllerDescriptor.GetFilters().Select(instance => new FilterInfo(instance, FilterScope.Controller)); @@ -25,7 +26,7 @@ public IEnumerable GetFilters(HttpConfiguration configuration, HttpA var overrideFilterPresent = allFilters.Any(x => x.Instance is IOverrideDefaultAuthLevel); - if(!overrideFilterPresent) + if (!overrideFilterPresent) { allFilters.Add(new FilterInfo(new RequireHostAttribute(), FilterScope.Action)); } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs index 2a4b51afafc..db0844c7c22 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Globalization; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Web.Http; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Localization.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using System.Globalization; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Web.Http; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Localization.Internal; + public class DnnContextMessageHandler : MessageProcessingHandler { protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken) @@ -27,6 +28,11 @@ protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, return request; } + protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) + { + return response; + } + private static void SetThreadCulture(PortalSettings portalSettings) { CultureInfo pageLocale = TestableLocalization.Instance.GetPageLocale(portalSettings); @@ -49,7 +55,7 @@ private static PortalSettings SetupPortalSettings(HttpRequestMessage request) request.GetHttpContext().Items["PortalSettings"] = portalSettings; return portalSettings; } - + private static bool TabIsInPortalOrHost(int tabId, int portalId) { var tab = TabController.Instance.GetTab(tabId, portalId); @@ -97,10 +103,5 @@ private static void ValidateTabAndModuleContext(HttpRequestMessage request, int } } } - - protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) - { - return response; - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs index 84da1e85b6d..836bfb04daf 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs @@ -1,87 +1,89 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Web.Http.Dependencies; -using DotNetNuke.Common.Extensions; -using DotNetNuke.Services.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using System; + using System.Collections.Generic; + using System.Web.Http.Dependencies; + + using DotNetNuke.Common.Extensions; + using DotNetNuke.Services.DependencyInjection; + using Microsoft.Extensions.DependencyInjection; + /// /// The implementation used in the /// Web API Modules of DNN. /// internal class DnnDependencyResolver : IDependencyResolver { - private readonly IServiceProvider _serviceProvider; - - /// + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. /// Instantiate a new instance of the . /// /// - /// The to be used in the + /// The to be used in the . /// public DnnDependencyResolver(IServiceProvider serviceProvider) { - _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); + this._serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); } /// - /// Starts a new resolution scope + /// Starts a new resolution scope. /// /// - /// The dependency scope + /// The dependency scope. /// public IDependencyScope BeginScope() { - var accessor = _serviceProvider.GetRequiredService(); + var accessor = this._serviceProvider.GetRequiredService(); var scope = accessor.GetScope(); return new DnnDependencyResolver(scope.ServiceProvider); } /// - /// Returns the specified service from the scope + /// Returns the specified service from the scope. /// /// - /// The service to be retrieved + /// The service to be retrieved. /// /// - /// The retrieved service + /// The retrieved service. /// public object GetService(Type serviceType) { - return _serviceProvider.GetService(serviceType); + return this._serviceProvider.GetService(serviceType); } /// - /// Returns the specified services from the scope + /// Returns the specified services from the scope. /// /// - /// The service to be retrieved + /// The service to be retrieved. /// /// - /// The retrieved service + /// The retrieved service. /// public IEnumerable GetServices(Type serviceType) { - return _serviceProvider.GetServices(serviceType); + return this._serviceProvider.GetServices(serviceType); } /// - /// Performs application-defined tasks associated with freeing, + /// Performs application-defined tasks associated with freeing, /// releasing, or resetting unmanaged resources. /// public void Dispose() { - Dispose(true); + this.Dispose(true); } /// - /// Performs application-defined tasks associated with freeing, + /// Performs application-defined tasks associated with freeing, /// releasing, or resetting unmanaged resources. /// /// diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs index 3035f931c51..a1a7b2cf4fc 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + public sealed class DnnPageEditorAttribute : AuthorizeAttributeBase, IOverrideDefaultAuthLevel { public override bool IsAuthorized(AuthFilterContext context) { Requires.NotNull("context", context); - return PagePermissionsAttributesHelper.HasTabPermission("EDIT,CONTENT,MANAGE") || IsModuleAdmin(((DnnApiController)context.ActionContext.ControllerContext.Controller).PortalSettings); - + return PagePermissionsAttributesHelper.HasTabPermission("EDIT,CONTENT,MANAGE") || this.IsModuleAdmin(((DnnApiController)context.ActionContext.ControllerContext.Controller).PortalSettings); } private bool IsModuleAdmin(PortalSettings portalSettings) @@ -37,6 +36,7 @@ private bool IsModuleAdmin(PortalSettings portalSettings) } } } + return portalSettings.ControlPanelSecurity == PortalSettings.ControlPanelPermission.ModuleEditor && isModuleAdmin; } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs index 7e39f6c6e9e..209f1860604 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using DotNetNuke.Common; + public sealed class DnnPagePermissionAttribute : AuthorizeAttributeBase, IOverrideDefaultAuthLevel { private string permissionKey = "EDIT"; @@ -14,18 +14,20 @@ public string PermissionKey { get { - return permissionKey; + return this.permissionKey; } + set { - permissionKey = value; + this.permissionKey = value; } } + public override bool IsAuthorized(AuthFilterContext context) { Requires.NotNull("context", context); - return PagePermissionsAttributesHelper.HasTabPermission(PermissionKey); + return PagePermissionsAttributesHelper.HasTabPermission(this.PermissionKey); } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs index b7025e6847c..b1ff41c55fc 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { public interface IAntiForgery { string CookieName { get; } + void Validate(string cookieToken, string headerToken); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs index f47b175cab4..ca1401c9b54 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs @@ -1,20 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using System.Web.Http.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using System; + using System.Net.Http; + using System.Web.Http.Controllers; + public class IFrameSupportedValidateAntiForgeryTokenAttribute : ValidateAntiForgeryTokenAttribute { protected override Tuple IsAuthorized(HttpActionContext actionContext) { var result = base.IsAuthorized(actionContext); - if (result.Item1) return SuccessResult; - + if (result.Item1) + { + return SuccessResult; + } + try { var queryString = actionContext.Request.GetQueryNameValuePairs(); @@ -27,6 +30,7 @@ protected override Tuple IsAuthorized(HttpActionContext actionCont break; } } + var cookieValue = GetAntiForgeryCookieValue(actionContext); AntiForgery.Instance.Validate(cookieValue, token); diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs index 56dbead498b..7ec1cc9a4bb 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Threading; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using System.Threading; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + public class PagePermissionsAttributesHelper { public static bool HasTabPermission(string permissionKey) { var principal = Thread.CurrentPrincipal; - if(!principal.Identity.IsAuthenticated) + if (!principal.Identity.IsAuthenticated) { return false; } @@ -22,8 +23,11 @@ public static bool HasTabPermission(string permissionKey) var currentPortal = PortalController.Instance.GetCurrentPortalSettings(); bool isAdminUser = currentPortal.UserInfo.IsSuperUser || PortalSecurity.IsInRole(currentPortal.AdministratorRoleName); - if (isAdminUser) return true; - + if (isAdminUser) + { + return true; + } + return TabPermissionController.HasTabPermission(permissionKey); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs index ecb99a8ae75..a9b9ec69f9e 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs @@ -1,81 +1,86 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Http; -using System.Web.Http.Dispatcher; -using System.Web.Http.Filters; -using System.Web.Http.Tracing; -using System.Web.Routing; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Framework.Reflections; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Api.Auth; -using DotNetNuke.Web.Api.Internal.Auth; -using DotNetNuke.Web.ConfigSection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api.Internal { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.Http; + using System.Web.Http.Dispatcher; + using System.Web.Http.Filters; + using System.Web.Http.Tracing; + using System.Web.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Framework.Reflections; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Api.Auth; + using DotNetNuke.Web.Api.Internal.Auth; + using DotNetNuke.Web.ConfigSection; + public sealed class ServicesRoutingManager : IMapRoute { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ServicesRoutingManager)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServicesRoutingManager)); private readonly Dictionary _moduleUsage = new Dictionary(); private readonly RouteCollection _routes; private readonly PortalAliasRouteManager _portalAliasRouteManager; - public ServicesRoutingManager() : this(RouteTable.Routes) + public ServicesRoutingManager() + : this(RouteTable.Routes) { } internal ServicesRoutingManager(RouteCollection routes) { - _routes = routes; - _portalAliasRouteManager = new PortalAliasRouteManager(); - TypeLocator = new TypeLocator(); + this._routes = routes; + this._portalAliasRouteManager = new PortalAliasRouteManager(); + this.TypeLocator = new TypeLocator(); } - internal ITypeLocator TypeLocator { get; set; } - - #region IMapRoute Members - + internal ITypeLocator TypeLocator { get; set; } + public IList MapHttpRoute(string moduleFolderName, string routeName, string url, object defaults, object constraints, string[] namespaces) { - if (namespaces == null || namespaces.Length == 0 || String.IsNullOrEmpty(namespaces[0])) + if (namespaces == null || namespaces.Length == 0 || string.IsNullOrEmpty(namespaces[0])) { - throw new ArgumentException(Localization.GetExceptionMessage("ArgumentCannotBeNullOrEmpty", - "The argument '{0}' cannot be null or empty.", - "namespaces")); + throw new ArgumentException(Localization.GetExceptionMessage( + "ArgumentCannotBeNullOrEmpty", + "The argument '{0}' cannot be null or empty.", + "namespaces")); } Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); url = url.Trim('/', '\\'); - IEnumerable prefixCounts = _portalAliasRouteManager.GetRoutePrefixCounts(); + IEnumerable prefixCounts = this._portalAliasRouteManager.GetRoutePrefixCounts(); var routes = new List(); foreach (int count in prefixCounts) { - string fullRouteName = _portalAliasRouteManager.GetRouteName(moduleFolderName, routeName, count); - string routeUrl = _portalAliasRouteManager.GetRouteUrl(moduleFolderName, url, count); - Route route = MapHttpRouteWithNamespace(fullRouteName, routeUrl, defaults, constraints, namespaces); + string fullRouteName = this._portalAliasRouteManager.GetRouteName(moduleFolderName, routeName, count); + string routeUrl = this._portalAliasRouteManager.GetRouteUrl(moduleFolderName, url, count); + Route route = this.MapHttpRouteWithNamespace(fullRouteName, routeUrl, defaults, constraints, namespaces); routes.Add(route); - if (Logger.IsTraceEnabled) - Logger.Trace("Mapping route: " + fullRouteName + " @ " + routeUrl); - - //compatible with old service path: DesktopModules/{namespace}/API/{controller}/{action}. + if (Logger.IsTraceEnabled) + { + Logger.Trace("Mapping route: " + fullRouteName + " @ " + routeUrl); + } + + // compatible with old service path: DesktopModules/{namespace}/API/{controller}/{action}. var oldRouteName = $"{fullRouteName}-old"; var oldRouteUrl = PortalAliasRouteManager.GetOldRouteUrl(moduleFolderName, url, count); - var oldRoute = MapHttpRouteWithNamespace(oldRouteName, oldRouteUrl, defaults, constraints, namespaces); + var oldRoute = this.MapHttpRouteWithNamespace(oldRouteName, oldRouteUrl, defaults, constraints, namespaces); routes.Add(oldRoute); - if (Logger.IsTraceEnabled) - Logger.Trace("Mapping route: " + oldRouteName + " @ " + oldRouteUrl); + if (Logger.IsTraceEnabled) + { + Logger.Trace("Mapping route: " + oldRouteName + " @ " + oldRouteUrl); + } } return routes; @@ -83,71 +88,79 @@ public IList MapHttpRoute(string moduleFolderName, string routeName, stri public IList MapHttpRoute(string moduleFolderName, string routeName, string url, object defaults, string[] namespaces) { - return MapHttpRoute(moduleFolderName, routeName, url, defaults, null, namespaces); + return this.MapHttpRoute(moduleFolderName, routeName, url, defaults, null, namespaces); } public IList MapHttpRoute(string moduleFolderName, string routeName, string url, string[] namespaces) { - return MapHttpRoute(moduleFolderName, routeName, url, null, null, namespaces); - } - - #endregion - + return this.MapHttpRoute(moduleFolderName, routeName, url, null, null, namespaces); + } + public void RegisterRoutes() { - //register routes is ONLY called from within DNN application initialization - //which is well protected from races - //allowing us to not worry about multi-threading threats here + // register routes is ONLY called from within DNN application initialization + // which is well protected from races + // allowing us to not worry about multi-threading threats here if (!GlobalConfiguration.Configuration.MessageHandlers.Any(x => x is BasicAuthMessageHandler)) { - //Everything in this block is run one time at startup + // Everything in this block is run one time at startup - //dnnContext message handler - //this must run before any auth message handlers + // dnnContext message handler + // this must run before any auth message handlers GlobalConfiguration.Configuration.MessageHandlers.Add(new DnnContextMessageHandler()); RegisterAuthenticationHandlers(); - //this must run after all other auth message handlers + + // this must run after all other auth message handlers var handler = new WebFormsAuthMessageHandler(); GlobalConfiguration.Configuration.MessageHandlers.Add(handler); DnnAuthorizeAttribute.AppendToDefaultAuthTypes(handler.AuthScheme); - //Add Windows Authentication type to make API request works when windows authentication enabled. + + // Add Windows Authentication type to make API request works when windows authentication enabled. DnnAuthorizeAttribute.AppendToDefaultAuthTypes("Negotiate"); - //media type formatter for text/html, text/plain + // media type formatter for text/html, text/plain GlobalConfiguration.Configuration.Formatters.Add(new StringPassThroughMediaTypeFormatter()); - //controller selector that respects namespaces + // controller selector that respects namespaces GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new DnnHttpControllerSelector(GlobalConfiguration.Configuration)); GlobalConfiguration.Configuration.DependencyResolver = new DnnDependencyResolver(Globals.DependencyProvider); - //tracwriter for dotnetnuke.instrumentation + // tracwriter for dotnetnuke.instrumentation GlobalConfiguration.Configuration.Services.Replace(typeof(ITraceWriter), new TraceWriter(IsTracingEnabled())); - //replace the default action filter provider with our own + // replace the default action filter provider with our own GlobalConfiguration.Configuration.Services.Add(typeof(IFilterProvider), new DnnActionFilterProvider()); var defaultprovider = GlobalConfiguration.Configuration.Services.GetFilterProviders().Where(x => x is ActionDescriptorFilterProvider); GlobalConfiguration.Configuration.Services.Remove(typeof(IFilterProvider), defaultprovider); - //add standard tab and module id provider + // add standard tab and module id provider GlobalConfiguration.Configuration.AddTabAndModuleInfoProvider(new StandardTabAndModuleInfoProvider()); } - using (_routes.GetWriteLock()) + using (this._routes.GetWriteLock()) { - _routes.Clear(); - LocateServicesAndMapRoutes(); + this._routes.Clear(); + this.LocateServicesAndMapRoutes(); } - Logger.TraceFormat("Registered a total of {0} routes", _routes.Count); + + Logger.TraceFormat("Registered a total of {0} routes", this._routes.Count); + } + + internal static bool IsValidServiceRouteMapper(Type t) + { + return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IServiceRouteMapper).IsAssignableFrom(t); } private static void RegisterAuthenticationHandlers() { - //authentication message handlers from web.config file + // authentication message handlers from web.config file var authSvcCfg = AuthServicesConfiguration.GetConfig(); - if (authSvcCfg?.MessageHandlers == null || authSvcCfg.MessageHandlers.Count <= 0) - return; - + if (authSvcCfg?.MessageHandlers == null || authSvcCfg.MessageHandlers.Count <= 0) + { + return; + } + var registeredSchemes = new List(); foreach (var handlerEntry in authSvcCfg.MessageHandlers.Cast()) { @@ -181,6 +194,7 @@ private static void RegisterAuthenticationHandlers() { DnnAuthorizeAttribute.AppendToDefaultAuthTypes(handler.AuthScheme); } + if (handler.BypassAntiForgeryToken) { ValidateAntiForgeryTokenAttribute.AppendToBypassAuthTypes(handler.AuthScheme); @@ -197,7 +211,7 @@ private static bool IsTracingEnabled() { var configValue = Config.GetSetting("EnableServicesFrameworkTracing"); - if(!string.IsNullOrEmpty(configValue)) + if (!string.IsNullOrEmpty(configValue)) { return Convert.ToBoolean(configValue); } @@ -207,11 +221,11 @@ private static bool IsTracingEnabled() private void LocateServicesAndMapRoutes() { - RegisterSystemRoutes(); - ClearCachedRouteData(); + this.RegisterSystemRoutes(); + this.ClearCachedRouteData(); - _moduleUsage.Clear(); - foreach (IServiceRouteMapper routeMapper in GetServiceRouteMappers()) + this._moduleUsage.Clear(); + foreach (IServiceRouteMapper routeMapper in this.GetServiceRouteMappers()) { try { @@ -227,17 +241,17 @@ private void LocateServicesAndMapRoutes() private void ClearCachedRouteData() { - _portalAliasRouteManager.ClearCachedData(); + this._portalAliasRouteManager.ClearCachedData(); } private void RegisterSystemRoutes() { - //_routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + // _routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); } private IEnumerable GetServiceRouteMappers() { - IEnumerable types = GetAllServiceRouteMapperTypes(); + IEnumerable types = this.GetAllServiceRouteMapperTypes(); foreach (Type routeMapperType in types) { @@ -262,19 +276,14 @@ private IEnumerable GetServiceRouteMappers() private IEnumerable GetAllServiceRouteMapperTypes() { - return TypeLocator.GetAllMatchingTypes(IsValidServiceRouteMapper); - } - - internal static bool IsValidServiceRouteMapper(Type t) - { - return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof (IServiceRouteMapper).IsAssignableFrom(t); + return this.TypeLocator.GetAllMatchingTypes(IsValidServiceRouteMapper); } private Route MapHttpRouteWithNamespace(string name, string url, object defaults, object constraints, string[] namespaces) { - Route route = _routes.MapHttpRoute(name, url, defaults, constraints); - - if(route.DataTokens == null) + Route route = this._routes.MapHttpRoute(name, url, defaults, constraints); + + if (route.DataTokens == null) { route.DataTokens = new RouteValueDictionary(); } diff --git a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs index f6dadf0dfa3..85135b250c2 100644 --- a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs @@ -1,28 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web.Http.Routing; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.Http.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Portals; + internal class PortalAliasRouteManager : IPortalAliasRouteManager { private List _prefixCounts; + // TODO: this method need remove after drop use old api format. + [Obsolete("Replaced with GetRouteUrl. Scheduled for removal in v11.0.0")] + public static string GetOldRouteUrl(string moduleFolderName, string url, int count) + { + Requires.NotNegative("count", count); + Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + + return string.Format("{0}DesktopModules/{1}/API/{2}", new PortalAliasRouteManager().GeneratePrefixString(count), moduleFolderName, url); + } + public string GetRouteName(string moduleFolderName, string routeName, int count) { Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); Requires.NotNegative("count", count); - + return moduleFolderName + "-" + routeName + "-" + count.ToString(CultureInfo.InvariantCulture); } @@ -38,24 +49,8 @@ public string GetRouteName(string moduleFolderName, string routeName, PortalAlia alias = alias.Remove(i, appPath.Length); } } - return GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); - } - - private string GeneratePrefixString(int count) - { - if (count == 0) - { - return ""; - } - - string prefix = ""; - - for (int i = count - 1; i >= 0; i--) - { - prefix = "{prefix" + i + "}/" + prefix; - } - - return prefix; + + return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); } public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) @@ -63,15 +58,15 @@ public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInf var allRouteValues = new HttpRouteValueDictionary(routeValues); var segments = portalAliasInfo.HTTPAlias.Split('/'); - - if(segments.Length > 1) - { - for(int i = 1; i < segments.Length; i++) - { - var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); - var value = segments[i]; - allRouteValues.Add(key, value); - } + + if (segments.Length > 1) + { + for (int i = 1; i < segments.Length; i++) + { + var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); + var value = segments[i]; + allRouteValues.Add(key, value); + } } return allRouteValues; @@ -82,42 +77,46 @@ public string GetRouteUrl(string moduleFolderName, string url, int count) Requires.NotNegative("count", count); Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); - return string.Format("{0}API/{1}/{2}", GeneratePrefixString(count), moduleFolderName, url); + return string.Format("{0}API/{1}/{2}", this.GeneratePrefixString(count), moduleFolderName, url); } - //TODO: this method need remove after drop use old api format. - [Obsolete("Replaced with GetRouteUrl. Scheduled for removal in v11.0.0")] - public static string GetOldRouteUrl(string moduleFolderName, string url, int count) + private string GeneratePrefixString(int count) { - Requires.NotNegative("count", count); - Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + if (count == 0) + { + return string.Empty; + } - return string.Format("{0}DesktopModules/{1}/API/{2}", new PortalAliasRouteManager().GeneratePrefixString(count), moduleFolderName, url); + string prefix = string.Empty; + + for (int i = count - 1; i >= 0; i--) + { + prefix = "{prefix" + i + "}/" + prefix; + } + + return prefix; } public void ClearCachedData() { - _prefixCounts = null; + this._prefixCounts = null; } public IEnumerable GetRoutePrefixCounts() { - if (_prefixCounts == null) + if (this._prefixCounts == null) { - //prefixCounts are required for each route that is mapped but they only change - //when a new portal is added so cache them until that time - - + // prefixCounts are required for each route that is mapped but they only change + // when a new portal is added so cache them until that time var portals = PortalController.Instance.GetPortals(); - - + var segmentCounts1 = new List(); foreach (PortalInfo portal in portals) { IEnumerable aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).Select(x => x.HTTPAlias); - aliases = StripApplicationPath(aliases); + aliases = this.StripApplicationPath(aliases); foreach (string alias in aliases) { @@ -129,11 +128,12 @@ public IEnumerable GetRoutePrefixCounts() } } } + IEnumerable segmentCounts = segmentCounts1; - _prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); + this._prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); } - return _prefixCounts; + return this._prefixCounts; } private static int CalcAliasPrefixCount(string alias) @@ -141,18 +141,6 @@ private static int CalcAliasPrefixCount(string alias) return alias.Count(c => c == '/'); } - private IEnumerable StripApplicationPath(IEnumerable aliases) - { - string appPath = TestableGlobals.Instance.ApplicationPath; - - if (String.IsNullOrEmpty(appPath)) - { - return aliases; - } - - return StripApplicationPathIterable(aliases, appPath); - } - private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) { foreach (string alias in aliases) @@ -169,5 +157,17 @@ private static IEnumerable StripApplicationPathIterable(IEnumerable StripApplicationPath(IEnumerable aliases) + { + string appPath = TestableGlobals.Instance.ApplicationPath; + + if (string.IsNullOrEmpty(appPath)) + { + return aliases; + } + + return StripApplicationPathIterable(aliases, appPath); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/RequireHostAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/RequireHostAttribute.cs index 95e4fec495f..052265dbbf5 100644 --- a/DNN Platform/DotNetNuke.Web/Api/RequireHostAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/RequireHostAttribute.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Threading; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System.Threading; + + using DotNetNuke.Entities.Portals; + public class RequireHostAttribute : AuthorizeAttributeBase { /// - /// Tests if the request passes the authorization requirements + /// Tests if the request passes the authorization requirements. /// - /// The auth filter context - /// True when authorization is succesful + /// The auth filter context. + /// True when authorization is succesful. public override bool IsAuthorized(AuthFilterContext context) { var principal = Thread.CurrentPrincipal; diff --git a/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs index 2386a7e66fc..f51f9ee82f3 100644 --- a/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs @@ -1,18 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Http.Routing; -using System.Web.Routing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Web.Http.Routing; + using System.Web.Routing; + public static class RouteExtensions { private const string NamespaceKey = "namespaces"; private const string NameKey = "name"; + /// + /// Get the name of the route. + /// + /// Route name. + public static string GetName(this Route route) + { + return (string)route.DataTokens[NameKey]; + } + + /// + /// Get the name of the route. + /// + /// Route name. + public static string GetName(this IHttpRoute route) + { + return (string)route.DataTokens[NameKey]; + } + internal static void SetNameSpaces(this Route route, string[] namespaces) { route.DataTokens[NamespaceKey] = namespaces; @@ -24,18 +42,18 @@ internal static void SetNameSpaces(this IHttpRoute route, string[] namespaces) } /// - /// Get Namespaces that are searched for controllers for this route + /// Get Namespaces that are searched for controllers for this route. /// - /// Namespaces + /// Namespaces. internal static string[] GetNameSpaces(this Route route) { - return (string[]) route.DataTokens[NamespaceKey]; + return (string[])route.DataTokens[NamespaceKey]; } /// - /// Get Namespaces that are searched for controllers for this route + /// Get Namespaces that are searched for controllers for this route. /// - /// Namespaces + /// Namespaces. internal static string[] GetNameSpaces(this IHttpRoute route) { return (string[])route.DataTokens[NamespaceKey]; @@ -50,23 +68,5 @@ internal static void SetName(this IHttpRoute route, string name) { route.DataTokens[NameKey] = name; } - - /// - /// Get the name of the route - /// - /// Route name - public static string GetName(this Route route) - { - return (string) route.DataTokens[NameKey]; - } - - /// - /// Get the name of the route - /// - /// Route name - public static string GetName(this IHttpRoute route) - { - return (string)route.DataTokens[NameKey]; - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs index 80f0f6ed6a7..8425baf70a0 100644 --- a/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + public sealed class StandardTabAndModuleInfoProvider : ITabAndModuleInfoProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); - private const string ModuleIdKey = "ModuleId"; private const string TabIdKey = "TabId"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); private const string MonikerQueryKey = "Moniker"; private const string MonikerHeaderKey = "X-DNN-MONIKER"; private const string MonikerSettingsKey = "Moniker"; @@ -28,6 +29,28 @@ public bool TryFindTabId(HttpRequestMessage request, out int tabId) return TryFindTabId(request, out tabId, true); } + public bool TryFindModuleId(HttpRequestMessage request, out int moduleId) + { + return TryFindModuleId(request, out moduleId, true); + } + + public bool TryFindModuleInfo(HttpRequestMessage request, out ModuleInfo moduleInfo) + { + int tabId, moduleId; + if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) + { + moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); + if (moduleInfo != null && moduleInfo.IsDeleted) + { + moduleInfo = null; + } + + return moduleInfo != null; + } + + return TryFindByMoniker(request, out moduleInfo); + } + private static bool TryFindTabId(HttpRequestMessage request, out int tabId, bool tryMoniker) { tabId = FindInt(request, TabIdKey); @@ -49,11 +72,6 @@ private static bool TryFindTabId(HttpRequestMessage request, out int tabId, bool return false; } - public bool TryFindModuleId(HttpRequestMessage request, out int moduleId) - { - return TryFindModuleId(request, out moduleId, true); - } - private static bool TryFindModuleId(HttpRequestMessage request, out int moduleId, bool tryMoniker) { moduleId = FindInt(request, ModuleIdKey); @@ -75,19 +93,6 @@ private static bool TryFindModuleId(HttpRequestMessage request, out int moduleId return false; } - public bool TryFindModuleInfo(HttpRequestMessage request, out ModuleInfo moduleInfo) - { - int tabId, moduleId; - if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) - { - moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); - if (moduleInfo != null && moduleInfo.IsDeleted) moduleInfo = null; - return moduleInfo != null; - } - - return TryFindByMoniker(request, out moduleInfo); - } - private static int FindInt(HttpRequestMessage requestMessage, string key) { string value = null; @@ -116,7 +121,11 @@ private static bool TryFindByMoniker(HttpRequestMessage requestMessage, out Modu } moduleInfo = id > Null.NullInteger ? ModuleController.Instance.GetTabModule(id) : null; - if (moduleInfo != null && moduleInfo.IsDeleted) moduleInfo = null; + if (moduleInfo != null && moduleInfo.IsDeleted) + { + moduleInfo = null; + } + return moduleInfo != null; } @@ -146,7 +155,7 @@ private static int FindIntInQueryString(HttpRequestMessage requestMessage, strin private static int GetTabModuleInfoFromMoniker(string monikerValue) { - monikerValue = (monikerValue ?? "").Trim(); + monikerValue = (monikerValue ?? string.Empty).Trim(); if (monikerValue.Length > 0) { var ids = TabModulesController.Instance.GetTabModuleIdsBySetting(MonikerSettingsKey, monikerValue); diff --git a/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs b/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs index 4d68b99d185..bcba5c5e20f 100644 --- a/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs +++ b/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs @@ -1,44 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http.Formatting; -using System.Net.Http.Headers; -using System.Threading.Tasks; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Net.Http.Formatting; + using System.Net.Http.Headers; + using System.Threading.Tasks; + /// - /// A MediaTypeFormatter that simply allows strings to pass through WebAPI and be associated with the specified MIME type + /// A MediaTypeFormatter that simply allows strings to pass through WebAPI and be associated with the specified MIME type. /// public class StringPassThroughMediaTypeFormatter : MediaTypeFormatter - { - /// - /// Initialize a formatter that can handle text/plain and text/html + { + /// + /// Initializes a new instance of the class. + /// Initialize a formatter that can handle text/plain and text/html. /// - public StringPassThroughMediaTypeFormatter() : this(new [] {"text/plain", "text/html"}) {} - - /// - /// Initialize a formatter that can handle the specified media types + public StringPassThroughMediaTypeFormatter() + : this(new[] { "text/plain", "text/html" }) + { + } + + /// + /// Initializes a new instance of the class. + /// Initialize a formatter that can handle the specified media types. /// public StringPassThroughMediaTypeFormatter(IEnumerable mediaTypes) { foreach (var type in mediaTypes) { - SupportedMediaTypes.Add(new MediaTypeHeaderValue(type)); + this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(type)); } } - public override bool CanReadType(Type type) + public override bool CanReadType(Type type) { return type == typeof(string); } - public override bool CanWriteType(Type type) + public override bool CanWriteType(Type type) { return type == typeof(string); } diff --git a/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs index 6b4a9df5059..954881f476f 100644 --- a/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs @@ -1,42 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Net.Http; -using System.Web.Http.Controllers; - -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Linq; + using System.Net.Http; + using System.Web.Http.Controllers; + + using DotNetNuke.Entities.Modules; + public class SupportedModulesAttribute : AuthorizeAttributeBase { private readonly string[] _supportedModules; public SupportedModulesAttribute(string supportedModules) { - _supportedModules = supportedModules.Split(new[] { ',' }); + this._supportedModules = supportedModules.Split(new[] { ',' }); } public override bool IsAuthorized(AuthFilterContext context) { - var module = FindModuleInfo(context.ActionContext.Request); + var module = this.FindModuleInfo(context.ActionContext.Request); if (module != null) { - return ModuleIsSupported(module); + return this.ModuleIsSupported(module); } return false; } - private bool ModuleIsSupported(ModuleInfo module) - { - return _supportedModules.Contains(module.DesktopModule.ModuleName); - } - protected virtual ModuleInfo FindModuleInfo(HttpRequestMessage request) { return request.FindModuleInfo(); @@ -46,5 +41,10 @@ protected override bool SkipAuthorization(HttpActionContext actionContext) { return false; } + + private bool ModuleIsSupported(ModuleInfo module) + { + return this._supportedModules.Contains(module.DesktopModule.ModuleName); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/TraceWriter.cs b/DNN Platform/DotNetNuke.Web/Api/TraceWriter.cs index 42df173507d..19884970fc9 100644 --- a/DNN Platform/DotNetNuke.Web/Api/TraceWriter.cs +++ b/DNN Platform/DotNetNuke.Web/Api/TraceWriter.cs @@ -1,35 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using System.Text; -using System.Web.Http.Tracing; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Net.Http; + using System.Text; + using System.Web.Http.Tracing; + + using DotNetNuke.Instrumentation; + internal sealed class TraceWriter : ITraceWriter { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (TraceWriter)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TraceWriter)); private readonly bool _enabled; public TraceWriter(bool isTracingEnabled) { - _enabled = isTracingEnabled; + this._enabled = isTracingEnabled; } public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action traceAction) { - if(!_enabled || level == TraceLevel.Off) + if (!this._enabled || level == TraceLevel.Off) { return; } var rec = new TraceRecord(request, category, level); traceAction(rec); - Log(rec); + this.Log(rec); } private void Log(TraceRecord rec) @@ -61,7 +62,7 @@ private void Log(TraceRecord rec) string output = message.ToString(); - if (!String.IsNullOrEmpty(output)) + if (!string.IsNullOrEmpty(output)) { switch (rec.Level) { diff --git a/DNN Platform/DotNetNuke.Web/Api/UrlHelperExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/UrlHelperExtensions.cs index 9f82221d657..0bc76f3fccf 100644 --- a/DNN Platform/DotNetNuke.Web/Api/UrlHelperExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/UrlHelperExtensions.cs @@ -1,36 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Http.Routing; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System.Web.Http.Routing; + + using DotNetNuke.Entities.Portals; + public static class UrlHelperExtensions { /// - /// Generate WebAPI Links compatible with DNN Services Framework + /// Generate WebAPI Links compatible with DNN Services Framework. /// - /// The UrlHelper - /// ModuleFolderName for the route - /// RouteName for the route - /// Values to be passed to the route - /// a url + /// The UrlHelper. + /// ModuleFolderName for the route. + /// RouteName for the route. + /// Values to be passed to the route. + /// a url. public static string DnnLink(this UrlHelper urlHelper, string moduleFolderName, string routeName, object routeValues) { return DnnLink(urlHelper, moduleFolderName, routeName, routeValues, PortalController.Instance.GetCurrentPortalSettings().PortalAlias); } /// - /// Generate WebAPI Links compatible with DNN Services Framework + /// Generate WebAPI Links compatible with DNN Services Framework. /// - /// The UrlHelper - /// ModuleFolderName for the route - /// RouteName for the route - /// Values to be passed to the route - /// The PortalAlias to use in the Url - /// a url + /// The UrlHelper. + /// ModuleFolderName for the route. + /// RouteName for the route. + /// Values to be passed to the route. + /// The PortalAlias to use in the Url. + /// a url. public static string DnnLink(this UrlHelper urlHelper, string moduleFolderName, string routeName, object routeValues, PortalAliasInfo portalAliasInfo) { var parm = new PortalAliasRouteManager(); diff --git a/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs index 15f4647944d..2888c0df2eb 100644 --- a/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs @@ -1,49 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Web.Api.Internal; -using System.Threading; -using System.Web.Http.Controllers; -using System.Web.Http.Filters; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Web.Http.Controllers; + using System.Web.Http.Filters; + + using DotNetNuke.Web.Api.Internal; + public class ValidateAntiForgeryTokenAttribute : ActionFilterAttribute { + protected static Tuple SuccessResult = new Tuple(true, null); + private static readonly List BypassedAuthTypes = new List(); - protected static Tuple SuccessResult = new Tuple(true, null); + public override bool AllowMultiple => false; - internal static void AppendToBypassAuthTypes(string authType) + public override void OnActionExecuting(HttpActionContext actionContext) { - var text = (authType ?? "").Trim(); - if (text.Length > 0) + if (!BypassTokenCheck()) { - BypassedAuthTypes.Add(text); + var result = this.IsAuthorized(actionContext); + if (!result.Item1) + { + throw new UnauthorizedAccessException(result.Item2); + } } } - private static bool BypassTokenCheck() + internal static void AppendToBypassAuthTypes(string authType) { - // bypass anti-forgery for those handllers that request so. - var authType = Thread.CurrentPrincipal?.Identity?.AuthenticationType; - return !string.IsNullOrEmpty(authType) && BypassedAuthTypes.Contains(authType); + var text = (authType ?? string.Empty).Trim(); + if (text.Length > 0) + { + BypassedAuthTypes.Add(text); + } } - public override void OnActionExecuting(HttpActionContext actionContext) + protected static string GetAntiForgeryCookieValue(HttpActionContext actionContext) { - if (!BypassTokenCheck()) + IEnumerable cookies; + if (actionContext?.Request != null && actionContext.Request.Headers.TryGetValues("Cookie", out cookies)) { - var result = IsAuthorized(actionContext); - if (!result.Item1) + foreach (var cookieValue in cookies) { - throw new UnauthorizedAccessException(result.Item2); + var nameIndex = cookieValue.IndexOf(AntiForgery.Instance.CookieName, StringComparison.InvariantCultureIgnoreCase); + if (nameIndex > -1) + { + var valueIndex = nameIndex + AntiForgery.Instance.CookieName.Length + 1; + var valueEndIndex = cookieValue.Substring(valueIndex).IndexOf(';'); + return valueEndIndex > -1 ? cookieValue.Substring(valueIndex, valueEndIndex) : cookieValue.Substring(valueIndex); + } } } + + return string.Empty; } protected virtual Tuple IsAuthorized(HttpActionContext actionContext) @@ -60,9 +76,11 @@ protected virtual Tuple IsAuthorized(HttpActionContext actionConte token = values.FirstOrDefault(); } - if (string.IsNullOrEmpty(token)) - return new Tuple(false, "RequestVerificationToken not present"); - + if (string.IsNullOrEmpty(token)) + { + return new Tuple(false, "RequestVerificationToken not present"); + } + var cookieValue = GetAntiForgeryCookieValue(actionContext); AntiForgery.Instance.Validate(cookieValue, token); } @@ -75,26 +93,11 @@ protected virtual Tuple IsAuthorized(HttpActionContext actionConte return SuccessResult; } - protected static string GetAntiForgeryCookieValue(HttpActionContext actionContext) + private static bool BypassTokenCheck() { - IEnumerable cookies; - if (actionContext?.Request != null && actionContext.Request.Headers.TryGetValues("Cookie", out cookies)) - { - foreach (var cookieValue in cookies) - { - var nameIndex = cookieValue.IndexOf(AntiForgery.Instance.CookieName, StringComparison.InvariantCultureIgnoreCase); - if (nameIndex > -1) - { - var valueIndex = nameIndex + AntiForgery.Instance.CookieName.Length + 1; - var valueEndIndex = cookieValue.Substring(valueIndex).IndexOf(';'); - return valueEndIndex > -1 ? cookieValue.Substring(valueIndex, valueEndIndex) : cookieValue.Substring(valueIndex); - } - } - } - - return ""; + // bypass anti-forgery for those handllers that request so. + var authType = Thread.CurrentPrincipal?.Identity?.AuthenticationType; + return !string.IsNullOrEmpty(authType) && BypassedAuthTypes.Contains(authType); } - - public override bool AllowMultiple => false; } } diff --git a/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs b/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs index f382144d2fb..9a9d559ccce 100644 --- a/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs +++ b/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs @@ -1,50 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Api { + using System; + using System.Net.Http; + + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + /// /// Represents a non successful response while executing a WebApi call. /// public class WebApiException : Exception - { - /// - /// Initializes a new instance of the WebApiException class, with the specified inner exception and response - /// message that caused the exception + { + /// + /// Initializes a new instance of the class, with the specified inner exception and response. + /// message that caused the exception. /// - /// The original exception - /// The result of the request + /// The original exception. + /// The result of the request. public WebApiException(Exception innerException, HttpResponseMessage result) : base(innerException.Message, innerException) { - Result = result; + this.Result = result; } public WebApiException(Exception innerException, HttpResponseMessage result, string body) : this(innerException, result) { - Body = body; + this.Body = body; } /// - /// The result of the request. Can be used to retrieve additional info like HTTP status code + /// Gets the result of the request. Can be used to retrieve additional info like HTTP status code. /// public HttpResponseMessage Result { get; private set; } /// - /// Body from the Get Response. Available when exception is thrown as well. + /// Gets body from the Get Response. Available when exception is thrown as well. /// public string Body { get; } public dynamic BodyAsJson() { - return JsonConvert.DeserializeObject(Body); + return JsonConvert.DeserializeObject(this.Body); } } } diff --git a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs index e301715dedb..54c2525279c 100644 --- a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs +++ b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs @@ -1,52 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Net; -using System.Web; -using System.Web.Security; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Framework; -using DotNetNuke.Modules.HTMLEditorProvider; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Profile; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.ClientCapability; -using DotNetNuke.Services.Cryptography; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.ModuleCache; -using DotNetNuke.Services.OutputCache; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Services.Sitemap; -using DotNetNuke.Services.Url.FriendlyUrl; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Cookies; -using DotNetNuke.Services.Installer.Blocker; -using DotNetNuke.HttpModules.DependencyInjection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Common.Internal { + using System; + using System.Linq; + using System.Net; + using System.Web; + using System.Web.Security; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Framework; + using DotNetNuke.HttpModules.DependencyInjection; + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.HTMLEditorProvider; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.Security.Cookies; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Profile; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.ClientCapability; + using DotNetNuke.Services.Cryptography; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Installer.Blocker; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.ModuleCache; + using DotNetNuke.Services.OutputCache; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Services.Sitemap; + using DotNetNuke.Services.Url.FriendlyUrl; + /// /// DotNetNuke Http Application. It will handle Start, End, BeginRequest, Error event for whole application. /// public class DotNetNukeHttpApplication : HttpApplication { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DotNetNukeHttpApplication)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DotNetNukeHttpApplication)); + + private static readonly string[] Endings = + { + ".css", ".gif", ".jpeg", ".jpg", ".js", ".png", "scriptresource.axd", "webresource.axd", + }; + + private static void RegisterIfNotAlreadyRegistered() + where TConcrete : class, new() + { + RegisterIfNotAlreadyRegistered(string.Empty); + } + + private static void RegisterIfNotAlreadyRegistered(string name) + where TAbstract : class + where TConcrete : class, new() + { + var provider = ComponentFactory.GetComponent(); + if (provider == null) + { + if (string.IsNullOrEmpty(name)) + { + ComponentFactory.RegisterComponentInstance(new TConcrete()); + } + else + { + ComponentFactory.RegisterComponentInstance(name, new TConcrete()); + } + } + } private void Application_Error(object sender, EventArgs eventArgs) { @@ -55,7 +80,11 @@ private void Application_Error(object sender, EventArgs eventArgs) { // Get the exception object. Logger.Trace("Dumping all Application Errors"); - foreach (Exception exc in HttpContext.Current.AllErrors) Logger.Fatal(exc); + foreach (Exception exc in HttpContext.Current.AllErrors) + { + Logger.Fatal(exc); + } + Logger.Trace("End Dumping all Application Errors"); } } @@ -65,7 +94,7 @@ private void Application_Start(object sender, EventArgs eventArgs) Logger.InfoFormat("Application Starting ({0})", Globals.ElapsedSinceAppStart); // just to start the timer var name = Config.GetSetting("ServerName"); - Globals.ServerName = String.IsNullOrEmpty(name) ? Dns.GetHostName() : name; + Globals.ServerName = string.IsNullOrEmpty(name) ? Dns.GetHostName() : name; Globals.DependencyProvider = new LazyServiceProvider(); var startup = new Startup(); @@ -79,10 +108,10 @@ private void Application_Start(object sender, EventArgs eventArgs) ComponentFactory.InstallComponents(new ProviderInstaller("caching", typeof(CachingProvider), typeof(FBCachingProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("logging", typeof(LoggingProvider), typeof(DBLoggingProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("scheduling", typeof(SchedulingProvider), typeof(DNNScheduler))); - ComponentFactory.InstallComponents(new ProviderInstaller("searchIndex", typeof(IndexingProvider), typeof(ModuleIndexer))); - #pragma warning disable 0618 - ComponentFactory.InstallComponents(new ProviderInstaller("searchDataStore", typeof(SearchDataStoreProvider), typeof(SearchDataStore))); - #pragma warning restore 0618 + ComponentFactory.InstallComponents(new ProviderInstaller("searchIndex", typeof(IndexingProvider), typeof(ModuleIndexer))); +#pragma warning disable 0618 + ComponentFactory.InstallComponents(new ProviderInstaller("searchDataStore", typeof(SearchDataStoreProvider), typeof(SearchDataStore))); +#pragma warning restore 0618 ComponentFactory.InstallComponents(new ProviderInstaller("members", typeof(MembershipProvider), typeof(AspNetMembershipProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("roles", typeof(RoleProvider), typeof(DNNRoleProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("profiles", typeof(ProfileProvider), typeof(DNNProfileProvider))); @@ -100,37 +129,27 @@ private void Application_Start(object sender, EventArgs eventArgs) ComponentFactory.InstallComponents(new ProviderInstaller("htmlEditor", typeof(HtmlEditorProvider), ComponentLifeStyleType.Transient)); ComponentFactory.InstallComponents(new ProviderInstaller("navigationControl", typeof(NavigationProvider), ComponentLifeStyleType.Transient)); ComponentFactory.InstallComponents(new ProviderInstaller("clientcapability", typeof(ClientCapabilityProvider))); - ComponentFactory.InstallComponents(new ProviderInstaller("cryptography", typeof(CryptographyProvider),typeof(FipsCompilanceCryptographyProvider))); + ComponentFactory.InstallComponents(new ProviderInstaller("cryptography", typeof(CryptographyProvider), typeof(FipsCompilanceCryptographyProvider))); Logger.InfoFormat("Application Started ({0})", Globals.ElapsedSinceAppStart); // just to start the timer DotNetNukeShutdownOverload.InitializeFcnSettings(); // register the assembly-lookup to correct the breaking rename in DNN 9.2 DotNetNuke.Services.Zip.SharpZipLibRedirect.RegisterSharpZipLibRedirect(); - //DotNetNukeSecurity.Initialize(); - } - - private static void RegisterIfNotAlreadyRegistered() where TConcrete : class, new() - { - RegisterIfNotAlreadyRegistered(""); + + // DotNetNukeSecurity.Initialize(); } - private static void RegisterIfNotAlreadyRegistered(string name) - where TAbstract : class - where TConcrete : class, new() + private static bool IsInstallOrUpgradeRequest(HttpRequest request) { - var provider = ComponentFactory.GetComponent(); - if (provider == null) - { - if (String.IsNullOrEmpty(name)) - { - ComponentFactory.RegisterComponentInstance(new TConcrete()); - } - else - { - ComponentFactory.RegisterComponentInstance(name, new TConcrete()); - } - } + var url = request.Url.LocalPath.ToLowerInvariant(); + + return url.EndsWith("webresource.axd") + || url.EndsWith("scriptresource.axd") + || url.EndsWith("captcha.aspx") + || url.Contains("upgradewizard.aspx") + || url.Contains("installwizard.aspx") + || url.EndsWith("install.aspx"); } private void Application_End(object sender, EventArgs eventArgs) @@ -155,30 +174,33 @@ private void Application_End(object sender, EventArgs eventArgs) Logger.Error(e); } - //Shutdown Lucene, but not when we are installing + // Shutdown Lucene, but not when we are installing if (Globals.Status != Globals.UpgradeStatus.Install) { Logger.Trace("Disposing Lucene"); var lucene = LuceneController.Instance as IDisposable; - if (lucene != null) lucene.Dispose(); + if (lucene != null) + { + lucene.Dispose(); + } } + Logger.Trace("Dumping all Application Errors"); if (HttpContext.Current != null) { if (HttpContext.Current.AllErrors != null) { - foreach (Exception exc in HttpContext.Current.AllErrors) Logger.Fatal(exc); + foreach (Exception exc in HttpContext.Current.AllErrors) + { + Logger.Fatal(exc); + } } } + Logger.Trace("End Dumping all Application Errors"); Logger.Info("Application Ended"); } - private static readonly string[] Endings = - { - ".css", ".gif", ".jpeg", ".jpg", ".js", ".png", "scriptresource.axd", "webresource.axd" - }; - private void Application_BeginRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; @@ -194,12 +216,12 @@ private void Application_BeginRequest(object sender, EventArgs e) } var requestUrl = app.Request.Url.LocalPath.ToLowerInvariant(); - if (!requestUrl.EndsWith(".aspx") && !requestUrl.EndsWith("/") && Endings.Any(requestUrl.EndsWith)) + if (!requestUrl.EndsWith(".aspx") && !requestUrl.EndsWith("/") && Endings.Any(requestUrl.EndsWith)) { return; } - if (IsInstallInProgress(app)) + if (this.IsInstallInProgress(app)) { return; } @@ -208,30 +230,18 @@ private void Application_BeginRequest(object sender, EventArgs e) Initialize.RunSchedule(app.Request); } - private void Application_PreSendRequestHeaders(object sender, EventArgs e) - { - if (HttpContext.Current != null && HttpContext.Current.Handler is PageBase) - { - var page = HttpContext.Current.Handler as PageBase; - page.HeaderIsWritten = true; - } - } - - private bool IsInstallInProgress(HttpApplication app) + private void Application_PreSendRequestHeaders(object sender, EventArgs e) { - return InstallBlocker.Instance.IsInstallInProgress(); + if (HttpContext.Current != null && HttpContext.Current.Handler is PageBase) + { + var page = HttpContext.Current.Handler as PageBase; + page.HeaderIsWritten = true; + } } - private static bool IsInstallOrUpgradeRequest(HttpRequest request) + private bool IsInstallInProgress(HttpApplication app) { - var url = request.Url.LocalPath.ToLowerInvariant(); - - return url.EndsWith("webresource.axd") - || url.EndsWith("scriptresource.axd") - || url.EndsWith("captcha.aspx") - || url.Contains("upgradewizard.aspx") - || url.Contains("installwizard.aspx") - || url.EndsWith("install.aspx"); + return InstallBlocker.Instance.IsInstallInProgress(); } } } diff --git a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeSecurity.cs b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeSecurity.cs index 0d92371433c..20696a0ab3b 100644 --- a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeSecurity.cs +++ b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeSecurity.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if false using System; using System.Collections.Generic; @@ -71,7 +71,6 @@ internal static void Initialize() } } -#region File Watcher Functions private static void InitializeFileWatcher() { @@ -257,7 +256,6 @@ private static void NotifyManager(string[] paths) } } -#endregion } } #endif diff --git a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs index 392c9f04f66..2b40ce524c1 100644 --- a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs +++ b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Reflection; -using System.Threading; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Common.Internal { + using System; + using System.IO; + using System.Reflection; + using System.Threading; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + internal static class DotNetNukeShutdownOverload { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DotNetNukeShutdownOverload)); @@ -20,7 +21,7 @@ internal static class DotNetNukeShutdownOverload private static bool _handleShutdowns; private static bool _shutdownInprogress; private static FileSystemWatcher _binOrRootWatcher; - private static string _binFolder = ""; + private static string _binFolder = string.Empty; internal static void InitializeFcnSettings() { @@ -35,7 +36,8 @@ internal static void InitializeFcnSettings() if (fileChangesMonitor == null) { Logger.Info("fileChangesMonitor is null"); - //AddSiteFilesMonitoring(true); + + // AddSiteFilesMonitoring(true); } else { @@ -47,12 +49,14 @@ internal static void InitializeFcnSettings() Logger.Info("FCNMode = " + fcnVal + " (Modes: NotSet/Default=0, Disabled=1, Single=2)"); var dirMonCompletion = typeof(HttpRuntime).Assembly.GetType("System.Web.DirMonCompletion"); - var dirMonCount = (int)dirMonCompletion.InvokeMember("_activeDirMonCompletions", + var dirMonCount = (int)dirMonCompletion.InvokeMember( + "_activeDirMonCompletions", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null); Logger.Trace("DirMonCompletion count: " + dirMonCount); + // enable our monitor only when fcnMode="Disabled" - //AddSiteFilesMonitoring(fcnVal.ToString() == "1"); + // AddSiteFilesMonitoring(fcnVal.ToString() == "1"); } // just monitor the root folder but don't interfere @@ -75,9 +79,11 @@ private static void AddSiteFilesMonitoring(bool handleShutdowns) try { _handleShutdowns = handleShutdowns; - if (_handleShutdowns) - _shutDownDelayTimer = new Timer(InitiateShutdown); - + if (_handleShutdowns) + { + _shutDownDelayTimer = new Timer(InitiateShutdown); + } + _binFolder = Path.Combine(Globals.ApplicationMapPath, "bin").ToLowerInvariant(); _binOrRootWatcher = new FileSystemWatcher { @@ -108,7 +114,11 @@ private static void AddSiteFilesMonitoring(bool handleShutdowns) private static void InitiateShutdown(object state) { - if (!_handleShutdowns) return; + if (!_handleShutdowns) + { + return; + } + try { HttpRuntime.UnloadAppDomain(); @@ -126,6 +136,7 @@ private static void ShceduleShutdown() if (_handleShutdowns && !_shutdownInprogress) { _shutdownInprogress = true; + // delay for a very short period _shutDownDelayTimer.Change(1500, Timeout.Infinite); } @@ -133,10 +144,12 @@ private static void ShceduleShutdown() private static void WatcherOnChanged(object sender, FileSystemEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); - - if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? "").StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); + } + + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) { ShceduleShutdown(); } @@ -144,35 +157,49 @@ private static void WatcherOnChanged(object sender, FileSystemEventArgs e) private static void WatcherOnCreated(object sender, FileSystemEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); - - if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? "").StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) - ShceduleShutdown(); + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); + } + + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) + { + ShceduleShutdown(); + } } private static void WatcherOnRenamed(object sender, RenamedEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - Logger.Info($"Watcher Activity: {e.ChangeType}. New Path: {e.FullPath}. Old Path: {e.OldFullPath}"); - - if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? "").StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) - ShceduleShutdown(); + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. New Path: {e.FullPath}. Old Path: {e.OldFullPath}"); + } + + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) + { + ShceduleShutdown(); + } } private static void WatcherOnDeleted(object sender, FileSystemEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); - - if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? "").StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) - ShceduleShutdown(); + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); + } + + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) + { + ShceduleShutdown(); + } } private static void WatcherOnError(object sender, ErrorEventArgs e) { - if (Logger.IsInfoEnabled) - Logger.Info("Watcher Activity: N/A. Error: " + e.GetException()); + if (Logger.IsInfoEnabled) + { + Logger.Info("Watcher Activity: N/A. Error: " + e.GetException()); + } } } } diff --git a/DNN Platform/DotNetNuke.Web/Common/DynamicSharedConstants.cs b/DNN Platform/DotNetNuke.Web/Common/DynamicSharedConstants.cs index 917da1d80de..9c842c83bdf 100644 --- a/DNN Platform/DotNetNuke.Web/Common/DynamicSharedConstants.cs +++ b/DNN Platform/DotNetNuke.Web/Common/DynamicSharedConstants.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Common { + using DotNetNuke.Services.Localization; + public class DynamicSharedConstants { public static string RootFolder diff --git a/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs b/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs index 3b2c47ca81e..32182b59d0c 100644 --- a/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs @@ -1,26 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Common { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + public class LazyServiceProvider : IServiceProvider { private IServiceProvider _serviceProvider; public object GetService(Type serviceType) { - if (_serviceProvider is null) - throw new Exception("Cannot resolve services until the service provider is built."); - - return _serviceProvider.GetService(serviceType); + if (this._serviceProvider is null) + { + throw new Exception("Cannot resolve services until the service provider is built."); + } + + return this._serviceProvider.GetService(serviceType); } internal void SetProvider(IServiceProvider serviceProvider) { - _serviceProvider = serviceProvider; + this._serviceProvider = serviceProvider; } } } diff --git a/DNN Platform/DotNetNuke.Web/Common/SharedConstants.cs b/DNN Platform/DotNetNuke.Web/Common/SharedConstants.cs index 1b2ecbdfe60..b1f16d9336a 100644 --- a/DNN Platform/DotNetNuke.Web/Common/SharedConstants.cs +++ b/DNN Platform/DotNetNuke.Web/Common/SharedConstants.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Common { + using DotNetNuke.Services.Localization; + public static class SharedConstants { public static readonly string RootFolder = null; diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs index d43086581d7..68954da3bb1 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.Framework; -using DotNetNuke.Services.Upgrade; -using DotNetNuke.Web.Components.Controllers.Models; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Components.Controllers { - public class ControlBarController: ServiceLocator, IControlBarController + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.Framework; + using DotNetNuke.Services.Upgrade; + using DotNetNuke.Web.Components.Controllers.Models; + + public class ControlBarController : ServiceLocator, IControlBarController { private const string BookmarkModulesTitle = "module"; private const string BookmarkCategoryProperty = "ControlBar_BookmarkCategory"; @@ -25,11 +26,12 @@ public class ControlBarController: ServiceLocator> GetCategoryDesktopModules(int portalId, string category, string searchTerm = "") { - var formattedSearchTerm = String.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.ToLower(CultureInfo.InvariantCulture); + var formattedSearchTerm = string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.ToLower(CultureInfo.InvariantCulture); Func, bool> Filter = category == "All" ? (kvp => kvp.Key.ToLower(CultureInfo.InvariantCulture).Contains(formattedSearchTerm)) @@ -41,9 +43,9 @@ public IEnumerable> GetCategoryDes public IEnumerable> GetBookmarkedDesktopModules(int portalId, int userId, string searchTerm = "") { - var formattedSearchTerm = String.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.ToLower(CultureInfo.InvariantCulture); - - IEnumerable> bookmarkedModules = GetBookmarkedModules(PortalSettings.Current.PortalId, userId) + var formattedSearchTerm = string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.ToLower(CultureInfo.InvariantCulture); + + IEnumerable> bookmarkedModules = this.GetBookmarkedModules(PortalSettings.Current.PortalId, userId) .Where(kvp => kvp.Key.ToLower(CultureInfo.InvariantCulture).Contains(formattedSearchTerm)); return bookmarkedModules; @@ -54,9 +56,9 @@ public void SaveBookMark(int portalId, int userId, string bookmarkTitle, string var ensuredBookmarkValue = bookmarkValue; if (bookmarkTitle == BookmarkModulesTitle) { - ensuredBookmarkValue = EnsureBookmarkValue(portalId, ensuredBookmarkValue); + ensuredBookmarkValue = this.EnsureBookmarkValue(portalId, ensuredBookmarkValue); } - + var personalizationController = new DotNetNuke.Services.Personalization.PersonalizationController(); var personalization = personalizationController.LoadProfile(userId, portalId); personalization.Profile["ControlBar:" + bookmarkTitle + portalId] = ensuredBookmarkValue; @@ -66,19 +68,20 @@ public void SaveBookMark(int portalId, int userId, string bookmarkTitle, string public string GetBookmarkCategory(int portalId) { - var bookmarkCategory = PortalController.GetPortalSetting(BookmarkCategoryProperty, portalId, ""); - if (String.IsNullOrEmpty(bookmarkCategory)) + var bookmarkCategory = PortalController.GetPortalSetting(BookmarkCategoryProperty, portalId, string.Empty); + if (string.IsNullOrEmpty(bookmarkCategory)) { PortalController.UpdatePortalSetting(portalId, BookmarkCategoryProperty, "Common"); return "Common"; } + return bookmarkCategory; } public UpgradeIndicatorViewModel GetUpgradeIndicator(Version version, bool isLocal, bool isSecureConnection) { var imageUrl = Upgrade.UpgradeIndicator(version, isLocal, isSecureConnection); - return !String.IsNullOrEmpty(imageUrl) ? GetDefaultUpgradeIndicator(imageUrl) : null; + return !string.IsNullOrEmpty(imageUrl) ? this.GetDefaultUpgradeIndicator(imageUrl) : null; } public string GetControlBarLogoURL() @@ -88,8 +91,13 @@ public string GetControlBarLogoURL() public IEnumerable GetCustomMenuItems() { - var menuItemsExtensionPoints = _mef.GetUserControlExtensionPoints("ControlBar", "CustomMenuItems"); - return menuItemsExtensionPoints.Select(GetMenuItemFromExtensionPoint); + var menuItemsExtensionPoints = this._mef.GetUserControlExtensionPoints("ControlBar", "CustomMenuItems"); + return menuItemsExtensionPoints.Select(this.GetMenuItemFromExtensionPoint); + } + + protected override Func GetFactory() + { + return () => new ControlBarController(); } private UpgradeIndicatorViewModel GetDefaultUpgradeIndicator(string imageUrl) @@ -105,8 +113,8 @@ private UpgradeIndicatorViewModel GetDefaultUpgradeIndicator(string imageUrl) WebAction = "location.href='" + navigateUrl + "'; return false;", AltText = alt, ToolTip = toolTip, - CssClass = "" - }; + CssClass = string.Empty, + }; } private MenuItemViewModel GetMenuItemFromExtensionPoint(IUserControlExtensionPoint userControlExtensionPoint) @@ -116,36 +124,32 @@ private MenuItemViewModel GetMenuItemFromExtensionPoint(IUserControlExtensionPoi ID = Path.GetFileNameWithoutExtension(userControlExtensionPoint.UserControlSrc), Text = userControlExtensionPoint.Text, Source = userControlExtensionPoint.UserControlSrc, - Order = userControlExtensionPoint.Order + Order = userControlExtensionPoint.Order, }; } private string EnsureBookmarkValue(int portalId, string bookmarkValue) { - var bookmarkCategoryModules = GetCategoryDesktopModules(portalId, GetBookmarkCategory(portalId)); + var bookmarkCategoryModules = this.GetCategoryDesktopModules(portalId, this.GetBookmarkCategory(portalId)); var ensuredModules = bookmarkValue.Split(',').Where(desktopModuleId => bookmarkCategoryModules.All(m => m.Value.DesktopModuleID.ToString(CultureInfo.InvariantCulture) != desktopModuleId)).ToList(); - return String.Join(",", ensuredModules.Distinct()); + return string.Join(",", ensuredModules.Distinct()); } private IEnumerable> GetBookmarkedModules(int portalId, int userId) { var personalizationController = new DotNetNuke.Services.Personalization.PersonalizationController(); var personalization = personalizationController.LoadProfile(userId, portalId); - var bookmarkItems = personalization.Profile["ControlBar:"+ BookmarkModulesTitle + portalId]; + var bookmarkItems = personalization.Profile["ControlBar:" + BookmarkModulesTitle + portalId]; if (bookmarkItems == null) { return new List>(); } + var bookmarkItemsKeys = bookmarkItems.ToString().Split(',').ToList(); var bookmarkedModules = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) .Where(dm => bookmarkItemsKeys.Contains(dm.Value.DesktopModuleID.ToString(CultureInfo.InvariantCulture))); return bookmarkedModules; } - - protected override Func GetFactory() - { - return () => new ControlBarController(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs index 4f918834d25..02bb3d69ac3 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs @@ -1,71 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Web.Components.Controllers.Models; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Components.Controllers { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Web.Components.Controllers.Models; + public interface IControlBarController { /// - /// Get all desktop modules that belong to a category + /// Get all desktop modules that belong to a category. /// - /// Portal Id where modules are installed - /// Catenory name - /// Search term to filter modules - /// A list with all matched desktop modules - IEnumerable> GetCategoryDesktopModules(int portalId, + /// Portal Id where modules are installed. + /// Catenory name. + /// Search term to filter modules. + /// A list with all matched desktop modules. + IEnumerable> GetCategoryDesktopModules( + int portalId, string category, string searchTerm = ""); /// - /// Get all desktop modules bookmark by user in Control Bar + /// Get all desktop modules bookmark by user in Control Bar. /// - /// Portal Id where modules are installed - /// User Id who has bookmarked the modules - /// Search term to filter modules - /// A list with all matched modules + /// Portal Id where modules are installed. + /// User Id who has bookmarked the modules. + /// Search term to filter modules. + /// A list with all matched modules. IEnumerable> GetBookmarkedDesktopModules(int portalId, int userId, string searchTerm = ""); /// - /// Save a user bookmark + /// Save a user bookmark. /// - /// Portal Id where save the bookmark - /// User Id who is going to create the bookmark - /// Title for the personalization setting - /// Value for the personalization setting + /// Portal Id where save the bookmark. + /// User Id who is going to create the bookmark. + /// Title for the personalization setting. + /// Value for the personalization setting. void SaveBookMark(int portalId, int userId, string bookarkTitle, string bookmarkValue); /// - /// Get the category name where the bookmarked modules are shown + /// Get the category name where the bookmarked modules are shown. /// - /// Portal Id where modules are installed - /// The name of the bookmark category + /// Portal Id where modules are installed. + /// The name of the bookmark category. string GetBookmarkCategory(int portalId); /// - /// Returns the upgrade indicator model + /// Returns the upgrade indicator model. /// /// /// /// - /// An instance of the view model UpgradeIndicator + /// An instance of the view model UpgradeIndicator. UpgradeIndicatorViewModel GetUpgradeIndicator(Version version, bool isLocal, bool isSecureConnection); /// - /// Get the current Logo URL shown in Control Bar + /// Get the current Logo URL shown in Control Bar. /// - /// The URL of the Control Bar Logo + /// The URL of the Control Bar Logo. string GetControlBarLogoURL(); /// - /// Gets all custom Menu item available in the system + /// Gets all custom Menu item available in the system. /// - /// All custom Menu Items + /// All custom Menu Items. IEnumerable GetCustomMenuItems(); } } diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs index b439ca6e971..9078a4b5665 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs @@ -1,19 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Components.Controllers.Models { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + public class MenuItemViewModel { public string ID { get; set; } + public string Text { get; set; } + public string Source { get; set; } + public int Order { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs index e1bc24e3178..18f9ec94d55 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs @@ -1,16 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Components.Controllers.Models { public class UpgradeIndicatorViewModel { public string ID { get; set; } + public string ImageUrl { get; set; } + public string WebAction { get; set; } + public string AltText { get; set; } + public string ToolTip { get; set; } + public string CssClass { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/Components/LocalizationHelper.cs b/DNN Platform/DotNetNuke.Web/Components/LocalizationHelper.cs index 16a85f81c08..ddc366ec092 100644 --- a/DNN Platform/DotNetNuke.Web/Components/LocalizationHelper.cs +++ b/DNN Platform/DotNetNuke.Web/Components/LocalizationHelper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Components { + using DotNetNuke.Services.Localization; + public class LocalizationHelper { private const string ResourceFile = "admin/ControlPanel/App_LocalResources/ControlBar"; diff --git a/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs b/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs index 95fd9e1f0a3..7b91872deb4 100644 --- a/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs +++ b/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Configuration; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.ConfigSection { + using System.Configuration; + public class AuthServicesConfiguration : ConfigurationSection { + [ConfigurationProperty("messageHandlers", IsRequired = true)] + public MessageHandlersCollection MessageHandlers => this["messageHandlers"] as MessageHandlersCollection; + public static AuthServicesConfiguration GetConfig() { return ConfigurationManager.GetSection("dotnetnuke/authServices") as AuthServicesConfiguration; } - - [ConfigurationProperty("messageHandlers", IsRequired = true)] - public MessageHandlersCollection MessageHandlers => this["messageHandlers"] as MessageHandlersCollection; } } diff --git a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs index d9325c08384..5d51590ac9a 100644 --- a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs +++ b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Configuration; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.ConfigSection { + using System.Configuration; + + using DotNetNuke.Web.Api; + public class MessageHandlerEntry : ConfigurationElement { private const string NameTag = "name"; @@ -16,13 +17,15 @@ public class MessageHandlerEntry : ConfigurationElement private const string ForceSslTag = "forceSSL"; [ConfigurationProperty(NameTag, DefaultValue = "", IsRequired = true)] - //[StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] + + // [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public string Name { get { return (string)this[NameTag]; } + set { this[NameTag] = value; @@ -30,13 +33,15 @@ public string Name } [ConfigurationProperty(ClassNameTag, DefaultValue = "", IsRequired = true)] - //[StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 300)] + + // [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 300)] public string ClassName { get { return (string)this[ClassNameTag]; } + set { this[ClassNameTag] = value; @@ -51,6 +56,7 @@ public bool Enabled var b = (bool?)this[EnabledNameTag]; return b.Value; } + set { this[EnabledNameTag] = value; @@ -58,7 +64,7 @@ public bool Enabled } /// - /// This property specifies whether this is automatically included when the + /// Gets or sets a value indicating whether this property specifies whether this is automatically included when the . /// [ConfigurationProperty(DefaultIncludeTag, DefaultValue = false, IsRequired = true)] public bool DefaultInclude @@ -68,6 +74,7 @@ public bool DefaultInclude var b = (bool?)this[DefaultIncludeTag]; return b.Value; } + set { this[DefaultIncludeTag] = value; @@ -82,6 +89,7 @@ public bool ForceSsl var b = (bool?)this[ForceSslTag]; return b.Value; } + set { this[ForceSslTag] = value; diff --git a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs index bf8e30b5b59..11b22ed02b7 100644 --- a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs +++ b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs @@ -1,26 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Configuration; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.ConfigSection { + using System.Configuration; + public class MessageHandlersCollection : ConfigurationElementCollection { public MessageHandlerEntry this[int index] { get { - return BaseGet(index) as MessageHandlerEntry; + return this.BaseGet(index) as MessageHandlerEntry; } + set { - if (BaseGet(index) != null) + if (this.BaseGet(index) != null) { - BaseRemoveAt(index); + this.BaseRemoveAt(index); } - BaseAdd(index, value); + + this.BaseAdd(index, value); } } diff --git a/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj b/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj index 04a05b4dad4..71b441306e6 100644 --- a/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj +++ b/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj @@ -412,6 +412,9 @@ + + stylecop.json + Designer @@ -433,6 +436,10 @@ DotNetNuke.ModulePipeline + + + + diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs index ee5c701e792..683e1283cb7 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs @@ -1,36 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Content.Workflow.Dto; -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Dto; + using DotNetNuke.Framework; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class ContentWorkflowServiceController : DnnApiController - { - #region Members - private readonly IWorkflowEngine _workflowEngine; - #endregion - - #region Constructor + { + private readonly IWorkflowEngine _workflowEngine; + public ContentWorkflowServiceController() { - _workflowEngine = WorkflowEngine.Instance; - } - #endregion - - #region Web Methods + this._workflowEngine = WorkflowEngine.Instance; + } + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage Reject(NotificationDTO postData) @@ -42,21 +38,21 @@ public HttpResponseMessage Reject(NotificationDTO postData) { if (string.IsNullOrEmpty(notification.Context)) { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } string[] parameters = notification.Context.Split(':'); - var stateTransiction = new StateTransaction - { - ContentItemId = int.Parse(parameters[0]), - CurrentStateId = int.Parse(parameters[2]), - Message = new StateTransactionMessage (), - UserId = UserInfo.UserID - }; - _workflowEngine.DiscardState(stateTransiction); + var stateTransiction = new StateTransaction + { + ContentItemId = int.Parse(parameters[0]), + CurrentStateId = int.Parse(parameters[2]), + Message = new StateTransactionMessage(), + UserId = this.UserInfo.UserID, + }; + this._workflowEngine.DiscardState(stateTransiction); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } } catch (Exception exc) @@ -64,7 +60,7 @@ public HttpResponseMessage Reject(NotificationDTO postData) Exceptions.LogException(exc); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } [HttpPost] @@ -78,21 +74,21 @@ public HttpResponseMessage Approve(NotificationDTO postData) { if (string.IsNullOrEmpty(notification.Context)) { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } string[] parameters = notification.Context.Split(':'); - var stateTransiction = new StateTransaction - { - ContentItemId = int.Parse(parameters[0]), - CurrentStateId = int.Parse(parameters[2]), - Message = new StateTransactionMessage(), - UserId = UserInfo.UserID - }; - _workflowEngine.CompleteState(stateTransiction); + var stateTransiction = new StateTransaction + { + ContentItemId = int.Parse(parameters[0]), + CurrentStateId = int.Parse(parameters[2]), + Message = new StateTransactionMessage(), + UserId = this.UserInfo.UserID, + }; + this._workflowEngine.CompleteState(stateTransiction); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } } catch (Exception exc) @@ -100,8 +96,7 @@ public HttpResponseMessage Approve(NotificationDTO postData) Exceptions.LogException(exc); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); - + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } [Obsolete("Obsolted in Platform 7.4.0. Scheduled removal in v10.0.0.")] @@ -117,7 +112,7 @@ public HttpResponseMessage Review(NotificationDTO postData) { if (string.IsNullOrEmpty(notification.Context)) { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } var source = notification.Context; @@ -129,20 +124,20 @@ public HttpResponseMessage Review(NotificationDTO postData) parameters = parameters.ToList().Skip(1).ToArray(); } - var workflow = ContentWorkflowController.Instance.GetDefaultWorkflow(PortalSettings.PortalId); + var workflow = ContentWorkflowController.Instance.GetDefaultWorkflow(this.PortalSettings.PortalId); var workflowSource = ContentWorkflowController.Instance.GetWorkflowSource(workflow.WorkflowID, source); if (workflowSource == null) { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } var sourceAction = Reflection.CreateInstance(Reflection.CreateType(workflowSource.SourceType)) as IContentWorkflowAction; if (sourceAction == null) { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = sourceAction.GetAction(parameters) }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = sourceAction.GetAction(parameters) }); } } catch (Exception exc) @@ -150,9 +145,7 @@ public HttpResponseMessage Review(NotificationDTO postData) Exceptions.LogException(exc); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); - - } - #endregion + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs index 669f02d6fcb..507a242c161 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs @@ -1,95 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading; -using System.Web.Http; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + using DotNetNuke.Web.Client.ClientResourceManagement; + [DnnAuthorize] public class ControlBarController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ControlBarController)); private const string DefaultExtensionImage = "icon_extensions_32px.png"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ControlBarController)); private readonly Components.Controllers.IControlBarController Controller; private IDictionary _nameDics; public ControlBarController() { - Controller = Components.Controllers.ControlBarController.Instance; - } - - public class ModuleDefDTO - { - public int ModuleID { get; set; } - public string ModuleName { get; set; } - public string ModuleImage { get; set; } - public bool Bookmarked { get; set; } - public bool ExistsInBookmarkCategory { get; set; } - } - - public class PageDefDTO - { - public int TabID { get; set; } - public string IndentedTabName { get; set; } - } - - public class AddModuleDTO - { - public string Visibility { get; set; } - public string Position { get; set; } - public string Module { get; set; } - public string Page { get; set; } - public string Pane { get; set; } - public string AddExistingModule { get; set; } - public string CopyModule { get; set; } - public string Sort { get; set; } - } - - public class UserModeDTO - { - public string UserMode { get; set; } - } - - public class SwitchSiteDTO - { - public string Site { get; set; } - } - - public class SwitchLanguageDTO - { - public string Language { get; set; } + this.Controller = Components.Controllers.ControlBarController.Instance; } - - - + [HttpGet] [DnnPageEditor] public HttpResponseMessage GetPortalDesktopModules(string category, int loadingStartIndex, int loadingPageSize, string searchTerm, string excludeCategories = "", bool sortBookmarks = false, string topModule = "") @@ -98,12 +55,13 @@ public HttpResponseMessage GetPortalDesktopModules(string category, int loadingS { category = "All"; } - var bookmarCategory = Controller.GetBookmarkCategory(PortalSettings.Current.PortalId); - var bookmarkedModules = Controller.GetBookmarkedDesktopModules(PortalSettings.Current.PortalId, UserController.Instance.GetCurrentUserInfo().UserID, searchTerm); - var bookmarkCategoryModules = Controller.GetCategoryDesktopModules(PortalSettings.PortalId, bookmarCategory, searchTerm); + + var bookmarCategory = this.Controller.GetBookmarkCategory(PortalSettings.Current.PortalId); + var bookmarkedModules = this.Controller.GetBookmarkedDesktopModules(PortalSettings.Current.PortalId, UserController.Instance.GetCurrentUserInfo().UserID, searchTerm); + var bookmarkCategoryModules = this.Controller.GetCategoryDesktopModules(this.PortalSettings.PortalId, bookmarCategory, searchTerm); var filteredList = bookmarCategory == category ? bookmarkCategoryModules.OrderBy(m => m.Key).Union(bookmarkedModules.OrderBy(m => m.Key)).Distinct() - : Controller.GetCategoryDesktopModules(PortalSettings.PortalId, category, searchTerm).OrderBy(m => m.Key); + : this.Controller.GetCategoryDesktopModules(this.PortalSettings.PortalId, category, searchTerm).OrderBy(m => m.Key); if (!string.IsNullOrEmpty(excludeCategories)) { @@ -112,13 +70,15 @@ public HttpResponseMessage GetPortalDesktopModules(string category, int loadingS filteredList.Where(kvp => !excludeList.Contains(kvp.Value.DesktopModule.Category.ToLowerInvariant())); } + if (sortBookmarks) { - //sort bookmarked modules + // sort bookmarked modules filteredList = bookmarkedModules.OrderBy(m => m.Key).Concat(filteredList.Except(bookmarkedModules)); - //move Html on top - filteredList = (filteredList.Where(m => m.Key.ToLowerInvariant() == topModule.ToLowerInvariant())). - Concat(filteredList.Except((filteredList.Where(m => m.Key.ToLowerInvariant() == topModule.ToLowerInvariant())))); + + // move Html on top + filteredList = filteredList.Where(m => m.Key.ToLowerInvariant() == topModule.ToLowerInvariant()). + Concat(filteredList.Except(filteredList.Where(m => m.Key.ToLowerInvariant() == topModule.ToLowerInvariant()))); } filteredList = filteredList @@ -129,23 +89,23 @@ public HttpResponseMessage GetPortalDesktopModules(string category, int loadingS { ModuleID = kvp.Value.DesktopModuleID, ModuleName = kvp.Key, - ModuleImage = GetDeskTopModuleImage(kvp.Value.DesktopModuleID), + ModuleImage = this.GetDeskTopModuleImage(kvp.Value.DesktopModuleID), Bookmarked = bookmarkedModules.Any(m => m.Key == kvp.Key), - ExistsInBookmarkCategory = bookmarkCategoryModules.Any(m => m.Key == kvp.Key) + ExistsInBookmarkCategory = bookmarkCategoryModules.Any(m => m.Key == kvp.Key), }).ToList(); - return Request.CreateResponse(HttpStatusCode.OK, result); + return this.Request.CreateResponse(HttpStatusCode.OK, result); } [HttpGet] [DnnPageEditor] public HttpResponseMessage GetPageList(string portal) { - var portalSettings = GetPortalSettings(portal); + var portalSettings = this.GetPortalSettings(portal); List tabList = null; - if (PortalSettings.PortalId == portalSettings.PortalId) + if (this.PortalSettings.PortalId == portalSettings.PortalId) { - tabList = TabController.GetPortalTabs(portalSettings.PortalId, PortalSettings.ActiveTab.TabID, false, string.Empty, true, false, false, false, true); + tabList = TabController.GetPortalTabs(portalSettings.PortalId, this.PortalSettings.ActiveTab.TabID, false, string.Empty, true, false, false, false, true); } else { @@ -164,20 +124,20 @@ where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) else { // try to get pages not allowed - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } } List result = new List(); foreach (var tab in tabList) { - if (tab.PortalID == PortalSettings.PortalId || (GetModules(tab.TabID).Count > 0 && tab.TabID != portalSettings.AdminTabId && tab.ParentId != portalSettings.AdminTabId)) + if (tab.PortalID == this.PortalSettings.PortalId || (this.GetModules(tab.TabID).Count > 0 && tab.TabID != portalSettings.AdminTabId && tab.ParentId != portalSettings.AdminTabId)) { result.Add(new PageDefDTO { TabID = tab.TabID, IndentedTabName = tab.IndentedTabName }); } } - return Request.CreateResponse(HttpStatusCode.OK, result); + return this.Request.CreateResponse(HttpStatusCode.OK, result); } [HttpGet] @@ -186,36 +146,77 @@ public HttpResponseMessage GetTabModules(string tab) { int tabID; - if (Int32.TryParse(tab, out tabID)) + if (int.TryParse(tab, out tabID)) { var result = new List(); if (tabID > 0) { - var pageModules = GetModules(tabID); + var pageModules = this.GetModules(tabID); Dictionary resultDict = pageModules.ToDictionary(module => module.ModuleID, module => module.ModuleTitle); result.AddRange(from kvp in resultDict - let imageUrl = GetTabModuleImage(tabID, kvp.Key) - select new ModuleDefDTO { ModuleID = kvp.Key, ModuleName = kvp.Value, ModuleImage = imageUrl } - ); + let imageUrl = this.GetTabModuleImage(tabID, kvp.Key) + select new ModuleDefDTO { ModuleID = kvp.Key, ModuleName = kvp.Value, ModuleImage = imageUrl }); } - return Request.CreateResponse(HttpStatusCode.OK, result); + + return this.Request.CreateResponse(HttpStatusCode.OK, result); } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } - private IList GetModules(int tabID) + public class ModuleDefDTO { - var isRemote = TabController.Instance.GetTab(tabID, Null.NullInteger, false).PortalID != PortalSettings.Current.PortalId; - var tabModules = ModuleController.Instance.GetTabModules(tabID); + public int ModuleID { get; set; } + + public string ModuleName { get; set; } + + public string ModuleImage { get; set; } + + public bool Bookmarked { get; set; } + + public bool ExistsInBookmarkCategory { get; set; } + } - var pageModules = isRemote - ? tabModules.Values.Where(m => ModuleSupportsSharing(m) && !m.IsDeleted).ToList() - : tabModules.Values.Where(m => ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", m) && !m.IsDeleted).ToList(); + public class PageDefDTO + { + public int TabID { get; set; } + + public string IndentedTabName { get; set; } + } - return pageModules; + public class AddModuleDTO + { + public string Visibility { get; set; } + + public string Position { get; set; } + + public string Module { get; set; } + + public string Page { get; set; } + + public string Pane { get; set; } + + public string AddExistingModule { get; set; } + + public string CopyModule { get; set; } + + public string Sort { get; set; } + } + + public class UserModeDTO + { + public string UserMode { get; set; } + } + public class SwitchSiteDTO + { + public string Site { get; set; } + } + + public class SwitchLanguageDTO + { + public string Language { get; set; } } [HttpPost] @@ -224,13 +225,13 @@ private IList GetModules(int tabID) public HttpResponseMessage CopyPermissionsToChildren() { if (TabPermissionController.CanManagePage() && UserController.Instance.GetCurrentUserInfo().IsInRole("Administrators") - && ActiveTabHasChildren() && !PortalSettings.ActiveTab.IsSuperTab) + && this.ActiveTabHasChildren() && !this.PortalSettings.ActiveTab.IsSuperTab) { - TabController.CopyPermissionsToChildren(PortalSettings.ActiveTab, PortalSettings.ActiveTab.TabPermissions); - return Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); + TabController.CopyPermissionsToChildren(this.PortalSettings.ActiveTab, this.PortalSettings.ActiveTab.TabPermissions); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } [HttpPost] @@ -238,7 +239,7 @@ public HttpResponseMessage CopyPermissionsToChildren() [DnnPageEditor] public HttpResponseMessage AddModule(AddModuleDTO dto) { - if (TabPermissionController.CanAddContentToPage() && CanAddModuleToPage()) + if (TabPermissionController.CanAddContentToPage() && this.CanAddModuleToPage()) { int permissionType; try @@ -258,8 +259,10 @@ public HttpResponseMessage AddModule(AddModuleDTO dto) try { sortID = int.Parse(dto.Sort); - if (sortID >= 0) - positionID = GetPaneModuleOrder(dto.Pane, sortID); + if (sortID >= 0) + { + positionID = this.GetPaneModuleOrder(dto.Pane, sortID); + } } catch (Exception exc) { @@ -296,10 +299,9 @@ public HttpResponseMessage AddModule(AddModuleDTO dto) try { int tabModuleId = -1; - if ((moduleLstID > -1)) + if (moduleLstID > -1) { - - if ((dto.AddExistingModule == "true")) + if (dto.AddExistingModule == "true") { int pageID; try @@ -312,18 +314,18 @@ public HttpResponseMessage AddModule(AddModuleDTO dto) pageID = -1; } - if ((pageID > -1)) + if (pageID > -1) { - tabModuleId = DoAddExistingModule(moduleLstID, pageID, dto.Pane, positionID, "", dto.CopyModule == "true"); + tabModuleId = this.DoAddExistingModule(moduleLstID, pageID, dto.Pane, positionID, string.Empty, dto.CopyModule == "true"); } } else { - tabModuleId = DoAddNewModule("", moduleLstID, dto.Pane, positionID, permissionType, ""); + tabModuleId = this.DoAddNewModule(string.Empty, moduleLstID, dto.Pane, positionID, permissionType, string.Empty); } } - return Request.CreateResponse(HttpStatusCode.OK, new { TabModuleID = tabModuleId }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { TabModuleID = tabModuleId }); } catch (Exception ex) { @@ -331,7 +333,19 @@ public HttpResponseMessage AddModule(AddModuleDTO dto) } } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); + } + + private IList GetModules(int tabID) + { + var isRemote = TabController.Instance.GetTab(tabID, Null.NullInteger, false).PortalID != PortalSettings.Current.PortalId; + var tabModules = ModuleController.Instance.GetTabModules(tabID); + + var pageModules = isRemote + ? tabModules.Values.Where(m => this.ModuleSupportsSharing(m) && !m.IsDeleted).ToList() + : tabModules.Values.Where(m => ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", m) && !m.IsDeleted).ToList(); + + return pageModules; } [HttpPost] @@ -343,10 +357,10 @@ public HttpResponseMessage ClearHostCache() { DataCache.ClearCache(); ClientResourceManager.ClearCache(); - return Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } [HttpPost] @@ -360,10 +374,10 @@ public HttpResponseMessage RecycleApplicationPool() log.AddProperty("Message", "UserRestart"); LogController.Instance.AddLog(log); Config.Touch(); - return Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } [HttpPost] @@ -375,20 +389,20 @@ public HttpResponseMessage SwitchSite(SwitchSiteDTO dto) { try { - if ((!string.IsNullOrEmpty(dto.Site))) + if (!string.IsNullOrEmpty(dto.Site)) { int selectedPortalID = int.Parse(dto.Site); var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(selectedPortalID).ToList(); - if ((portalAliases.Count > 0 && (portalAliases[0] != null))) + if (portalAliases.Count > 0 && (portalAliases[0] != null)) { - return Request.CreateResponse(HttpStatusCode.OK, new { RedirectURL = Globals.AddHTTP(((PortalAliasInfo)portalAliases[0]).HTTPAlias) }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { RedirectURL = Globals.AddHTTP(((PortalAliasInfo)portalAliases[0]).HTTPAlias) }); } } } catch (System.Threading.ThreadAbortException) { - //Do nothing we are not logging ThreadAbortxceptions caused by redirects + // Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception ex) { @@ -396,7 +410,7 @@ public HttpResponseMessage SwitchSite(SwitchSiteDTO dto) } } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } [HttpPost] @@ -405,30 +419,29 @@ public HttpResponseMessage SwitchLanguage(SwitchLanguageDTO dto) { try { - if (PortalSettings.AllowUserUICulture && PortalSettings.ContentLocalizationEnabled) + if (this.PortalSettings.AllowUserUICulture && this.PortalSettings.ContentLocalizationEnabled) { - if ((!string.IsNullOrEmpty(dto.Language))) + if (!string.IsNullOrEmpty(dto.Language)) { var personalizationController = new DotNetNuke.Services.Personalization.PersonalizationController(); - var personalization = personalizationController.LoadProfile(UserInfo.UserID, PortalSettings.PortalId); + var personalization = personalizationController.LoadProfile(this.UserInfo.UserID, this.PortalSettings.PortalId); personalization.Profile["Usability:UICulture"] = dto.Language; personalization.IsModified = true; personalizationController.SaveProfile(personalization); - return Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); } } - } catch (System.Threading.ThreadAbortException) { - //Do nothing we are not logging ThreadAbortxceptions caused by redirects + // Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception ex) { Exceptions.LogException(ex); } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } [HttpPost] @@ -436,18 +449,20 @@ public HttpResponseMessage SwitchLanguage(SwitchLanguageDTO dto) [DnnPageEditor] public HttpResponseMessage ToggleUserMode(UserModeDTO userMode) { - if (userMode == null) - userMode = new UserModeDTO { UserMode = "VIEW" }; - - ToggleUserMode(userMode.UserMode); - var response = Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); + if (userMode == null) + { + userMode = new UserModeDTO { UserMode = "VIEW" }; + } + + this.ToggleUserMode(userMode.UserMode); + var response = this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); if (userMode.UserMode.Equals("VIEW", StringComparison.InvariantCultureIgnoreCase)) { - var cookie = Request.Headers.GetCookies("StayInEditMode").FirstOrDefault(); + var cookie = this.Request.Headers.GetCookies("StayInEditMode").FirstOrDefault(); if (cookie != null && !string.IsNullOrEmpty(cookie["StayInEditMode"].Value)) { - var expireCookie = new CookieHeaderValue("StayInEditMode", ""); + var expireCookie = new CookieHeaderValue("StayInEditMode", string.Empty); expireCookie.Expires = DateTimeOffset.Now.AddDays(-1); expireCookie.Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/"; response.Headers.AddCookies(new List { expireCookie }); @@ -457,27 +472,19 @@ public HttpResponseMessage ToggleUserMode(UserModeDTO userMode) return response; } - public class BookmarkDTO - { - public string Title { get; set; } - public string Bookmark { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] [DnnPageEditor] public HttpResponseMessage SaveBookmark(BookmarkDTO bookmark) { - if (string.IsNullOrEmpty(bookmark.Bookmark)) bookmark.Bookmark = string.Empty; - - Controller.SaveBookMark(PortalSettings.PortalId, UserInfo.UserID, bookmark.Title, bookmark.Bookmark); + if (string.IsNullOrEmpty(bookmark.Bookmark)) + { + bookmark.Bookmark = string.Empty; + } + + this.Controller.SaveBookMark(this.PortalSettings.PortalId, this.UserInfo.UserID, bookmark.Title, bookmark.Bookmark); - return Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); - } - - public class LockingDTO - { - public bool Lock { get; set; } + return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); } [HttpPost] @@ -486,7 +493,7 @@ public class LockingDTO public HttpResponseMessage LockInstance(LockingDTO lockingRequest) { HostController.Instance.Update("IsLocked", lockingRequest.Lock.ToString(), true); - return Request.CreateResponse(HttpStatusCode.OK); + return this.Request.CreateResponse(HttpStatusCode.OK); } [HttpPost] @@ -494,35 +501,60 @@ public HttpResponseMessage LockInstance(LockingDTO lockingRequest) [RequireHost] public HttpResponseMessage LockSite(LockingDTO lockingRequest) { - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "IsLocked", lockingRequest.Lock.ToString(), true); - return Request.CreateResponse(HttpStatusCode.OK); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "IsLocked", lockingRequest.Lock.ToString(), true); + return this.Request.CreateResponse(HttpStatusCode.OK); + } + + public bool CanAddModuleToPage() + { + return true; + + // If we are not in an edit page + // return (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) && (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); + } + + private static void SetCloneModuleContext(bool cloneModuleContext) + { + Thread.SetData( + Thread.GetNamedDataSlot("CloneModuleContext"), + cloneModuleContext ? bool.TrueString : bool.FalseString); } private void ToggleUserMode(string mode) { var personalizationController = new DotNetNuke.Services.Personalization.PersonalizationController(); - var personalization = personalizationController.LoadProfile(UserInfo.UserID, PortalSettings.PortalId); - personalization.Profile["Usability:UserMode" + PortalSettings.PortalId] = mode.ToUpper(); + var personalization = personalizationController.LoadProfile(this.UserInfo.UserID, this.PortalSettings.PortalId); + personalization.Profile["Usability:UserMode" + this.PortalSettings.PortalId] = mode.ToUpper(); personalization.IsModified = true; personalizationController.SaveProfile(personalization); } + public class BookmarkDTO + { + public string Title { get; set; } + + public string Bookmark { get; set; } + } + + public class LockingDTO + { + public bool Lock { get; set; } + } + private PortalSettings GetPortalSettings(string portal) { var portalSettings = PortalSettings.Current; try { - if (!string.IsNullOrEmpty(portal)) { var selectedPortalId = int.Parse(portal); - if (PortalSettings.PortalId != selectedPortalId) + if (this.PortalSettings.PortalId != selectedPortalId) { portalSettings = new PortalSettings(selectedPortalId); } } - } catch (Exception) { @@ -555,7 +587,7 @@ join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.Pa where portMods.Value.DesktopModuleID == moduleId select pkgs.IconFile).FirstOrDefault(); - imageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; + imageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; return System.Web.VirtualPathUtility.ToAbsolute(imageUrl); } @@ -573,22 +605,15 @@ join tabMods in tabModules on modDefs.Value.DesktopModuleID equals tabMods.Value where tabMods.Value.ModuleID == moduleId select pkgs.IconFile).FirstOrDefault(); - imageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; + imageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; return System.Web.VirtualPathUtility.ToAbsolute(imageUrl); } - public bool CanAddModuleToPage() - { - return true; - //If we are not in an edit page - //return (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) && (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); - } - private bool ActiveTabHasChildren() { - var children = TabController.GetTabsByParent(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID); + var children = TabController.GetTabsByParent(this.PortalSettings.ActiveTab.TabID, this.PortalSettings.ActiveTab.PortalID); - if (((children == null) || children.Count < 1)) + if ((children == null) || children.Count < 1) { return false; } @@ -607,9 +632,8 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po { userID = user.UserID; } - - - if ((moduleInfo != null)) + + if (moduleInfo != null) { // Is this from a site other than our own? (i.e., is the user requesting "module sharing"?) var remote = moduleInfo.PortalID != PortalSettings.Current.PortalId; @@ -619,8 +643,9 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po { case ModuleSharing.Unsupported: // Should never happen since the module should not be listed in the first place. - throw new ApplicationException(string.Format("Module '{0}' does not support Shareable and should not be listed in Add Existing Module from a different source site", - moduleInfo.DesktopModule.FriendlyName)); + throw new ApplicationException(string.Format( + "Module '{0}' does not support Shareable and should not be listed in Add Existing Module from a different source site", + moduleInfo.DesktopModule.FriendlyName)); case ModuleSharing.Supported: break; case ModuleSharing.Unknown: @@ -639,11 +664,11 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po newModule.PaneName = paneName; newModule.Alignment = align; - if ((cloneModule)) + if (cloneModule) { newModule.ModuleID = Null.NullInteger; - //copy module settings and tab module settings + // copy module settings and tab module settings newModule.ModuleSettings.Clear(); foreach (var key in moduleInfo.ModuleSettings.Keys) { @@ -656,7 +681,7 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po newModule.TabModuleSettings.Add(key, moduleInfo.TabModuleSettings[key]); } - //reset the module id + // reset the module id newModule.ModuleID = ModuleController.Instance.AddModule(newModule); if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass)) @@ -682,7 +707,7 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po } else { - //copy tab module settings + // copy tab module settings newModule.TabModuleSettings.Clear(); foreach (var key in moduleInfo.TabModuleSettings.Keys) { @@ -692,8 +717,8 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po ModuleController.Instance.AddModule(newModule); } - //if the tab of original module has custom stylesheet defined, then also copy the stylesheet - //to the destination tab if its custom stylesheet is empty. + // if the tab of original module has custom stylesheet defined, then also copy the stylesheet + // to the destination tab if its custom stylesheet is empty. var originalTab = TabController.Instance.GetTab(moduleInfo.TabID, moduleInfo.PortalID); var targetTab = PortalSettings.Current.ActiveTab; if (originalTab != null @@ -707,23 +732,24 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po if (remote) { - //Ensure the Portal Admin has View rights + // Ensure the Portal Admin has View rights var permissionController = new PermissionController(); ArrayList arrSystemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); - AddModulePermission(newModule, - (PermissionInfo)arrSystemModuleViewPermissions[0], - PortalSettings.Current.AdministratorRoleId, - Null.NullInteger, - true); - - //Set PortalID correctly + this.AddModulePermission( + newModule, + (PermissionInfo)arrSystemModuleViewPermissions[0], + PortalSettings.Current.AdministratorRoleId, + Null.NullInteger, + true); + + // Set PortalID correctly newModule.OwnerPortalID = newModule.PortalID; newModule.PortalID = PortalSettings.Current.PortalId; ModulePermissionController.SaveModulePermissions(newModule); } - //Add Event Log - EventLogController.Instance.AddLog(newModule, PortalSettings.Current, userID, "", EventLogController.EventLogType.MODULE_CREATED); + // Add Event Log + EventLogController.Instance.AddLog(newModule, PortalSettings.Current, userID, string.Empty, EventLogController.EventLogType.MODULE_CREATED); return newModule.ModuleID; } @@ -731,12 +757,6 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po return -1; } - private static void SetCloneModuleContext(bool cloneModuleContext) - { - Thread.SetData(Thread.GetNamedDataSlot("CloneModuleContext"), - cloneModuleContext ? bool.TrueString : bool.FalseString); - } - private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) { var objModulePermission = new ModulePermissionInfo @@ -746,7 +766,7 @@ private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, Permissio RoleID = roleId, UserID = userId, PermissionKey = permission.PermissionKey, - AllowAccess = allowAccess + AllowAccess = allowAccess, }; // add the permission to the collection @@ -764,10 +784,10 @@ private int GetPaneModuleOrder(string pane, int sort) foreach (ModuleInfo m in PortalSettings.Current.ActiveTab.Modules) { - //if user is allowed to view module and module is not deleted + // if user is allowed to view module and module is not deleted if (ModulePermissionController.CanViewModule(m) && !m.IsDeleted) { - //modules which are displayed on all tabs should not be displayed on the Admin or Super tabs + // modules which are displayed on all tabs should not be displayed on the Admin or Super tabs if (!m.AllTabs || !PortalSettings.Current.ActiveTab.IsSuperTab) { if (string.Equals(m.PaneName, pane, StringComparison.OrdinalIgnoreCase)) @@ -834,7 +854,7 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger) { ModuleInfo defaultModule = ModuleController.Instance.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true); - if ((defaultModule != null)) + if (defaultModule != null) { objModule.CacheTime = defaultModule.CacheTime; } @@ -846,7 +866,8 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i if (PortalSettings.Current.ContentLocalizationEnabled) { Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId); - //set the culture of the module to that of the tab + + // set the culture of the module to that of the tab var tabInfo = TabController.Instance.GetTab(objModule.TabID, PortalSettings.Current.PortalId, false); objModule.CultureCode = tabInfo != null ? tabInfo.CultureCode : defaultLocale.Code; } @@ -854,6 +875,7 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i { objModule.CultureCode = Null.NullString; } + objModule.AllTabs = false; objModule.Alignment = align; @@ -863,7 +885,8 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i { tabModuleId = objModule.ModuleID; } - //update the position to let later modules with add after previous one. + + // update the position to let later modules with add after previous one. position = ModuleController.Instance.GetTabModule(objModule.TabModuleID).ModuleOrder + 1; } @@ -872,14 +895,17 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i private string GetModuleName(string moduleName) { - if (_nameDics == null) + if (this._nameDics == null) { - _nameDics = new Dictionary {{"SearchCrawlerAdmin", "SearchCrawler Admin"}, - {"SearchCrawlerInput", "SearchCrawler Input"}, - {"SearchCrawlerResults", "SearchCrawler Results"}}; + this._nameDics = new Dictionary + { + { "SearchCrawlerAdmin", "SearchCrawler Admin" }, + { "SearchCrawlerInput", "SearchCrawler Input" }, + { "SearchCrawlerResults", "SearchCrawler Results" }, + }; } - return _nameDics.ContainsKey(moduleName) ? _nameDics[moduleName] : moduleName; + return this._nameDics.ContainsKey(moduleName) ? this._nameDics[moduleName] : moduleName; } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs index fc12f1e44bc..6ef33ae2874 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs @@ -1,54 +1,54 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Web; -using System.Web.Http; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { - [AllowAnonymous] - public class CountryRegionController : DnnApiController - { - - [HttpGet()] - public HttpResponseMessage Countries() - { - var searchString = (HttpContext.Current.Request.Params["SearchString"] ?? "").NormalizeString(); + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Web.Api; + + [AllowAnonymous] + public class CountryRegionController : DnnApiController + { + [HttpGet] + public HttpResponseMessage Countries() + { + var searchString = (HttpContext.Current.Request.Params["SearchString"] ?? string.Empty).NormalizeString(); var countries = CachedCountryList.GetCountryList(Thread.CurrentThread.CurrentCulture.Name); - return Request.CreateResponse(HttpStatusCode.OK, countries.Values.Where( + return this.Request.CreateResponse(HttpStatusCode.OK, countries.Values.Where( x => x.NormalizedFullName.IndexOf(searchString, StringComparison.CurrentCulture) > -1).OrderBy(x => x.NormalizedFullName)); - } - - public struct Region - { - public string Text; - public string Value; - } + } - [HttpGet()] - public HttpResponseMessage Regions(int country) - { - List res = new List(); - foreach (ListEntryInfo r in (new ListController()).GetListEntryInfoItems("Region").Where(l => l.ParentID == country)) - { - res.Add(new Region - { - Text = r.Text, - Value = r.EntryID.ToString() - }); - } - return Request.CreateResponse(HttpStatusCode.OK, res.OrderBy(r => r.Text)); - } + [HttpGet] + public HttpResponseMessage Regions(int country) + { + List res = new List(); + foreach (ListEntryInfo r in new ListController().GetListEntryInfoItems("Region").Where(l => l.ParentID == country)) + { + res.Add(new Region + { + Text = r.Text, + Value = r.EntryID.ToString(), + }); + } + + return this.Request.CreateResponse(HttpStatusCode.OK, res.OrderBy(r => r.Text)); + } - } + public struct Region + { + public string Text; + public string Value; + } + } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs index 0823b6f03d1..26a28743727 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs @@ -1,22 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Web; -using System.Web.Http; - - -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Net; + using System.Net.Http; + using System.Text; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class EventLogServiceController : DnnApiController { @@ -29,28 +28,28 @@ public HttpResponseMessage GetLogDetails(string guid) Guid logId; if (string.IsNullOrEmpty(guid) || !Guid.TryParse(guid, out logId)) { - return Request.CreateResponse(HttpStatusCode.BadRequest); + return this.Request.CreateResponse(HttpStatusCode.BadRequest); } try { - var logInfo = new LogInfo {LogGUID = guid}; + var logInfo = new LogInfo { LogGUID = guid }; logInfo = EventLogController.Instance.GetSingleLog(logInfo, LoggingProvider.ReturnType.LogInfoObjects) as LogInfo; if (logInfo == null) { - return Request.CreateResponse(HttpStatusCode.BadRequest); + return this.Request.CreateResponse(HttpStatusCode.BadRequest); } - return Request.CreateResponse(HttpStatusCode.OK, new - { - Title = Localization.GetSafeJSString("CriticalError.Error", Localization.SharedResourceFile), - Content = GetPropertiesText(logInfo) - }); + return this.Request.CreateResponse(HttpStatusCode.OK, new + { + Title = Localization.GetSafeJSString("CriticalError.Error", Localization.SharedResourceFile), + Content = this.GetPropertiesText(logInfo), + }); } catch (Exception ex) { Logger.Error(ex); - return Request.CreateResponse(HttpStatusCode.BadRequest); + return this.Request.CreateResponse(HttpStatusCode.BadRequest); } } @@ -61,7 +60,7 @@ private string GetPropertiesText(LogInfo logInfo) int i; for (i = 0; i <= objLogProperties.Count - 1; i++) { - //display the values in the Panel child controls. + // display the values in the Panel child controls. var ldi = (LogDetailInfo)objLogProperties[i]; if (ldi.PropertyName == "Message") { @@ -72,6 +71,7 @@ private string GetPropertiesText(LogInfo logInfo) str.Append("

" + ldi.PropertyName + ":" + HttpUtility.HtmlEncode(ldi.PropertyValue) + "

"); } } + str.Append("

Server Name: " + HttpUtility.HtmlEncode(logInfo.LogServerName) + "

"); return str.ToString(); } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs index 69dead5c0fd..061ab8632dd 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs @@ -1,77 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Formatting; -using System.Net.Http.Headers; -using System.Runtime.Serialization; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using System.Web.Http; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Common.Utils; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; -using ContentDisposition = System.Net.Mime.ContentDisposition; -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; -using System.Web; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections.Generic; + using System.Drawing; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Net.Http.Formatting; + using System.Net.Http.Headers; + using System.Runtime.Serialization; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using System.Web; + using System.Web.Http; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Common.Utils; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + + using ContentDisposition = System.Net.Mime.ContentDisposition; + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + [DnnAuthorize] public class FileUploadController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileUploadController)); private static readonly Regex UserFolderEx = new Regex(@"users/\d+/\d+/(\d+)/", RegexOptions.Compiled | RegexOptions.IgnoreCase); - public class FolderItemDTO - { - public int FolderId { get; set; } - public string FileFilter { get; set; } - public bool Required { get; set; } - } + private static readonly List ImageExtensions = Globals.glbImageFileTypes.Split(',').ToList(); - public class SavedFileDTO + public static string GetUrl(int fileId) { - public string FileId { get; set; } - public string FilePath { get; set; } + var file = FileManager.Instance.GetFile(fileId, true); + return FileManager.Instance.GetUrl(file); } [HttpPost] public HttpResponseMessage LoadFiles(FolderItemDTO folderItem) { - int effectivePortalId = PortalSettings.PortalId; - + int effectivePortalId = this.PortalSettings.PortalId; if (folderItem.FolderId <= 0) { - return Request.CreateResponse(HttpStatusCode.BadRequest); + return this.Request.CreateResponse(HttpStatusCode.BadRequest); } var folder = FolderManager.Instance.GetFolder(folderItem.FolderId); if (folder == null) { - return Request.CreateResponse(HttpStatusCode.BadRequest); + return this.Request.CreateResponse(HttpStatusCode.BadRequest); } int userId; @@ -91,7 +87,7 @@ public HttpResponseMessage LoadFiles(FolderItemDTO folderItem) var list = Globals.GetFileList(effectivePortalId, folderItem.FileFilter, !folderItem.Required, folder.FolderPath); var fileItems = list.OfType().ToList(); - return Request.CreateResponse(HttpStatusCode.OK, fileItems); + return this.Request.CreateResponse(HttpStatusCode.OK, fileItems); } [HttpGet] @@ -103,18 +99,18 @@ public HttpResponseMessage LoadImage(string fileId) if (int.TryParse(fileId, out file)) { var imageUrl = ShowImage(file); - return Request.CreateResponse(HttpStatusCode.OK, imageUrl); + return this.Request.CreateResponse(HttpStatusCode.OK, imageUrl); } } - return Request.CreateResponse(HttpStatusCode.InternalServerError); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } [HttpPost] [IFrameSupportedValidateAntiForgeryToken] public Task PostFile() { - HttpRequestMessage request = Request; + HttpRequestMessage request = this.Request; if (!request.Content.IsMimeMultipartContent()) { @@ -124,9 +120,9 @@ public Task PostFile() var provider = new MultipartMemoryStreamProvider(); // local references for use in closure - var portalSettings = PortalSettings; + var portalSettings = this.PortalSettings; var currentSynchronizationContext = SynchronizationContext.Current; - var userInfo = UserInfo; + var userInfo = this.UserInfo; var task = request.Content.ReadAsMultipartAsync(provider) .ContinueWith(o => { @@ -145,11 +141,11 @@ public Task PostFile() switch (name.ToUpper()) { case "\"FOLDER\"": - folder = item.ReadAsStringAsync().Result ?? ""; + folder = item.ReadAsStringAsync().Result ?? string.Empty; break; case "\"FILTER\"": - filter = item.ReadAsStringAsync().Result ?? ""; + filter = item.ReadAsStringAsync().Result ?? string.Empty; break; case "\"OVERWRITE\"": @@ -165,17 +161,18 @@ public Task PostFile() break; case "\"POSTFILE\"": - fileName = item.Headers.ContentDisposition.FileName.Replace("\"", ""); + fileName = item.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); if (fileName.IndexOf("\\", StringComparison.Ordinal) != -1) { fileName = Path.GetFileName(fileName); } + stream = item.ReadAsStreamAsync().Result; break; } } - var errorMessage = ""; + var errorMessage = string.Empty; var alreadyExists = false; if (!string.IsNullOrEmpty(fileName) && stream != null) { @@ -183,38 +180,180 @@ public Task PostFile() // The SynchronizationContext keeps the main thread context. Send method is synchronous currentSynchronizationContext.Send( - delegate + state => { returnFileDto = SaveFile(stream, portalSettings, userInfo, folder, filter, fileName, overwrite, isHostMenu, extract, out alreadyExists, out errorMessage); - }, null - ); - + }, null); } - /* Response Content Type cannot be application/json - * because IE9 with iframe-transport manages the response - * as a file download + /* Response Content Type cannot be application/json + * because IE9 with iframe-transport manages the response + * as a file download */ var mediaTypeFormatter = new JsonMediaTypeFormatter(); mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); if (!string.IsNullOrEmpty(errorMessage)) { - return Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.BadRequest, new { AlreadyExists = alreadyExists, - Message = string.Format(GetLocalizedString("ErrorMessage"), fileName, errorMessage) + Message = string.Format(GetLocalizedString("ErrorMessage"), fileName, errorMessage), }, mediaTypeFormatter, "text/plain"); } - return Request.CreateResponse(HttpStatusCode.OK, returnFileDto, mediaTypeFormatter, "text/plain"); + return this.Request.CreateResponse(HttpStatusCode.OK, returnFileDto, mediaTypeFormatter, "text/plain"); }); return task; } + public class FolderItemDTO + { + public int FolderId { get; set; } + + public string FileFilter { get; set; } + + public bool Required { get; set; } + } + + public class SavedFileDTO + { + public string FileId { get; set; } + + public string FilePath { get; set; } + } + + [HttpPost] + [IFrameSupportedValidateAntiForgeryToken] + [AllowAnonymous] + public Task UploadFromLocal() + { + return this.UploadFromLocal(this.PortalSettings.PortalId); + } + + [HttpPost] + [IFrameSupportedValidateAntiForgeryToken] + [AllowAnonymous] + public Task UploadFromLocal(int portalId) + { + var request = this.Request; + FileUploadDto result = null; + if (!request.Content.IsMimeMultipartContent()) + { + throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); + } + + if (portalId > -1) + { + if (!this.IsPortalIdValid(portalId)) + { + throw new HttpResponseException(HttpStatusCode.Unauthorized); + } + } + else + { + portalId = this.PortalSettings.PortalId; + } + + var provider = new MultipartMemoryStreamProvider(); + + // local references for use in closure + var currentSynchronizationContext = SynchronizationContext.Current; + var userInfo = this.UserInfo; + var task = request.Content.ReadAsMultipartAsync(provider) + .ContinueWith(o => + { + var folder = string.Empty; + var filter = string.Empty; + var fileName = string.Empty; + var validationCode = string.Empty; + var overwrite = false; + var isHostPortal = false; + var extract = false; + Stream stream = null; + + foreach (var item in provider.Contents) + { + var name = item.Headers.ContentDisposition.Name; + switch (name.ToUpper()) + { + case "\"FOLDER\"": + folder = item.ReadAsStringAsync().Result ?? string.Empty; + break; + + case "\"FILTER\"": + filter = item.ReadAsStringAsync().Result ?? string.Empty; + break; + + case "\"OVERWRITE\"": + bool.TryParse(item.ReadAsStringAsync().Result, out overwrite); + break; + + case "\"ISHOSTPORTAL\"": + bool.TryParse(item.ReadAsStringAsync().Result, out isHostPortal); + break; + + case "\"EXTRACT\"": + bool.TryParse(item.ReadAsStringAsync().Result, out extract); + break; + + case "\"PORTALID\"": + if (userInfo.IsSuperUser) + { + int.TryParse(item.ReadAsStringAsync().Result, out portalId); + } + + break; + case "\"VALIDATIONCODE\"": + validationCode = item.ReadAsStringAsync().Result ?? string.Empty; + break; + case "\"POSTFILE\"": + fileName = item.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); + if (fileName.IndexOf("\\", StringComparison.Ordinal) != -1) + { + fileName = Path.GetFileName(fileName); + } + + if (Globals.FileEscapingRegex.Match(fileName).Success == false) + { + stream = item.ReadAsStreamAsync().Result; + } + + break; + } + } + + if (!string.IsNullOrEmpty(fileName) && stream != null) + { + // The SynchronizationContext keeps the main thread context. Send method is synchronous + currentSynchronizationContext.Send( + state => + { + result = UploadFile(stream, portalId, userInfo, folder, filter, fileName, overwrite, isHostPortal, extract, validationCode); + }, + null); + } + + var mediaTypeFormatter = new JsonMediaTypeFormatter(); + mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); + + /* Response Content Type cannot be application/json + * because IE9 with iframe-transport manages the response + * as a file download + */ + return this.Request.CreateResponse( + HttpStatusCode.OK, + result, + mediaTypeFormatter, + "text/plain"); + }); + + return task; + } + private static SavedFileDTO SaveFile( Stream stream, PortalSettings portalSettings, @@ -232,7 +371,7 @@ private static SavedFileDTO SaveFile( var savedFileDto = new SavedFileDTO(); try { - var extension = Path.GetExtension(fileName).ValueOrEmpty().Replace(".", ""); + var extension = Path.GetExtension(fileName).ValueOrEmpty().Replace(".", string.Empty); if (!string.IsNullOrEmpty(filter) && !filter.ToLowerInvariant().Contains(extension.ToLowerInvariant())) { errorMessage = GetLocalizedString("ExtensionNotAllowed"); @@ -278,7 +417,7 @@ private static SavedFileDTO SaveFile( FileManager.Instance.DeleteFile(file); } - errorMessage = ""; + errorMessage = string.Empty; savedFileDto.FileId = file.FileId.ToString(CultureInfo.InvariantCulture); savedFileDto.FilePath = FileManager.Instance.GetUrl(file); return savedFileDto; @@ -323,8 +462,6 @@ private static string ShowImage(int fileId) return null; } - private static readonly List ImageExtensions = Globals.glbImageFileTypes.Split(',').ToList(); - private static bool IsImageExtension(string extension) { return ImageExtensions.Any(e => e.Equals(extension, StringComparison.OrdinalIgnoreCase)); @@ -335,52 +472,6 @@ private static bool IsImage(string fileName) return ImageExtensions.Any(extension => fileName.EndsWith("." + extension, StringComparison.OrdinalIgnoreCase)); } - public class UploadByUrlDto - { - public string Url { get; set; } - public string Folder { get; set; } - public bool Overwrite { get; set; } - public bool Unzip { get; set; } - public string Filter { get; set; } - public bool IsHostMenu { get; set; } - public int PortalId { get; set; } = -1; - public string ValidationCode { get; set; } - } - - [DataContract] - public class FileUploadDto - { - [DataMember(Name = "path")] - public string Path { get; set; } - - [DataMember(Name = "orientation")] - public Orientation Orientation { get; set; } - - [DataMember(Name = "alreadyExists")] - public bool AlreadyExists { get; set; } - - [DataMember(Name = "message")] - public string Message { get; set; } - - [DataMember(Name = "fileIconUrl")] - public string FileIconUrl { get; set; } - - [DataMember(Name = "fileId")] - public int FileId { get; set; } - - [DataMember(Name = "fileName")] - public string FileName { get; set; } - - [DataMember(Name = "prompt")] - public string Prompt { get; set; } - } - - public static string GetUrl(int fileId) - { - var file = FileManager.Instance.GetFile(fileId, true); - return FileManager.Instance.GetUrl(file); - } - private static FileUploadDto UploadFile( Stream stream, int portalId, @@ -404,13 +495,18 @@ private static FileUploadDto UploadFile( extensionList = filter.Split(',').Select(i => i.Trim()).ToList(); } - var validateParams = new List{ extensionList, portalId, userInfo.UserID}; + var validateParams = new List { extensionList, userInfo.UserID }; + if (!userInfo.IsSuperUser) + { + validateParams.Add(portalId); + } + if (!ValidationUtils.ValidationCodeMatched(validateParams, validationCode)) { throw new InvalidOperationException("Bad Request"); } - var extension = Path.GetExtension(fileName).ValueOrEmpty().Replace(".", ""); + var extension = Path.GetExtension(fileName).ValueOrEmpty().Replace(".", string.Empty); result.FileIconUrl = IconController.GetFileIconUrl(extension); if (!string.IsNullOrEmpty(filter) && !filter.ToLowerInvariant().Contains(extension.ToLowerInvariant())) @@ -466,6 +562,7 @@ private static FileUploadDto UploadFile( : string.Empty; result.Prompt = string.Format("{{\"invalidFiles\":[{0}], \"totalCount\": {1}}}", invalidFilesJson, filesCount); } + result.FileId = file.FileId; } @@ -523,6 +620,7 @@ private static FileUploadDto UploadFile( reader.Close(); reader.Dispose(); } + if (fileContent != null) { fileContent.Close(); @@ -531,126 +629,51 @@ private static FileUploadDto UploadFile( } } - [HttpPost] - [IFrameSupportedValidateAntiForgeryToken] - [AllowAnonymous] - public Task UploadFromLocal() + public class UploadByUrlDto { - return UploadFromLocal(PortalSettings.PortalId); - } + public string Url { get; set; } - [HttpPost] - [IFrameSupportedValidateAntiForgeryToken] - [AllowAnonymous] - public Task UploadFromLocal(int portalId) - { - var request = Request; - FileUploadDto result = null; - if (!request.Content.IsMimeMultipartContent()) - { - throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); - } - if (portalId > -1) - { - if (!IsPortalIdValid(portalId)) throw new HttpResponseException(HttpStatusCode.Unauthorized); - } - else - { - portalId = PortalSettings.PortalId; - } + public string Folder { get; set; } - var provider = new MultipartMemoryStreamProvider(); + public bool Overwrite { get; set; } - // local references for use in closure - var currentSynchronizationContext = SynchronizationContext.Current; - var userInfo = UserInfo; - var task = request.Content.ReadAsMultipartAsync(provider) - .ContinueWith(o => - { - var folder = string.Empty; - var filter = string.Empty; - var fileName = string.Empty; - var validationCode = string.Empty; - var overwrite = false; - var isHostPortal = false; - var extract = false; - Stream stream = null; + public bool Unzip { get; set; } - foreach (var item in provider.Contents) - { - var name = item.Headers.ContentDisposition.Name; - switch (name.ToUpper()) - { - case "\"FOLDER\"": - folder = item.ReadAsStringAsync().Result ?? ""; - break; + public string Filter { get; set; } - case "\"FILTER\"": - filter = item.ReadAsStringAsync().Result ?? ""; - break; + public bool IsHostMenu { get; set; } - case "\"OVERWRITE\"": - bool.TryParse(item.ReadAsStringAsync().Result, out overwrite); - break; + public int PortalId { get; set; } = -1; - case "\"ISHOSTPORTAL\"": - bool.TryParse(item.ReadAsStringAsync().Result, out isHostPortal); - break; + public string ValidationCode { get; set; } + } - case "\"EXTRACT\"": - bool.TryParse(item.ReadAsStringAsync().Result, out extract); - break; + [DataContract] + public class FileUploadDto + { + [DataMember(Name = "path")] + public string Path { get; set; } - case "\"PORTALID\"": - if (userInfo.IsSuperUser) - { - int.TryParse(item.ReadAsStringAsync().Result, out portalId); - } - break; - case "\"VALIDATIONCODE\"": - validationCode = item.ReadAsStringAsync().Result ?? ""; - break; - case "\"POSTFILE\"": - fileName = item.Headers.ContentDisposition.FileName.Replace("\"", ""); - if (fileName.IndexOf("\\", StringComparison.Ordinal) != -1) - { - fileName = Path.GetFileName(fileName); - } - if (Globals.FileEscapingRegex.Match(fileName).Success == false) - { - stream = item.ReadAsStreamAsync().Result; - } - break; - } - } + [DataMember(Name = "orientation")] + public Orientation Orientation { get; set; } - if (!string.IsNullOrEmpty(fileName) && stream != null) - { - // The SynchronizationContext keeps the main thread context. Send method is synchronous - currentSynchronizationContext.Send( - delegate - { - result = UploadFile(stream, portalId, userInfo, folder, filter, fileName, overwrite, isHostPortal, extract, validationCode); - }, - null - ); - } + [DataMember(Name = "alreadyExists")] + public bool AlreadyExists { get; set; } - var mediaTypeFormatter = new JsonMediaTypeFormatter(); - mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); + [DataMember(Name = "message")] + public string Message { get; set; } - /* Response Content Type cannot be application/json - * because IE9 with iframe-transport manages the response - * as a file download - */ - return Request.CreateResponse( - HttpStatusCode.OK, - result, - mediaTypeFormatter, - "text/plain"); - }); + [DataMember(Name = "fileIconUrl")] + public string FileIconUrl { get; set; } - return task; + [DataMember(Name = "fileId")] + public int FileId { get; set; } + + [DataMember(Name = "fileName")] + public string FileName { get; set; } + + [DataMember(Name = "prompt")] + public string Prompt { get; set; } } [HttpPost] @@ -664,9 +687,9 @@ public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) var mediaTypeFormatter = new JsonMediaTypeFormatter(); mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); - if (VerifySafeUrl(dto.Url) == false) + if (this.VerifySafeUrl(dto.Url) == false) { - return Request.CreateResponse(HttpStatusCode.BadRequest); + return this.Request.CreateResponse(HttpStatusCode.BadRequest); } try @@ -680,7 +703,7 @@ public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) throw new Exception("No server response"); } - var fileName = GetFileName(response); + var fileName = this.GetFileName(response); if (string.IsNullOrEmpty(fileName)) { fileName = HttpUtility.UrlDecode(new Uri(dto.Url).Segments.Last()); @@ -689,21 +712,24 @@ public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) var portalId = dto.PortalId; if (portalId > -1) { - if (!IsPortalIdValid(portalId)) throw new HttpResponseException(HttpStatusCode.Unauthorized); + if (!this.IsPortalIdValid(portalId)) + { + throw new HttpResponseException(HttpStatusCode.Unauthorized); + } } else { - portalId = PortalSettings.PortalId; + portalId = this.PortalSettings.PortalId; } - result = UploadFile(responseStream, portalId, UserInfo, dto.Folder.ValueOrEmpty(), dto.Filter.ValueOrEmpty(), + result = UploadFile(responseStream, portalId, this.UserInfo, dto.Folder.ValueOrEmpty(), dto.Filter.ValueOrEmpty(), fileName, dto.Overwrite, dto.IsHostMenu, dto.Unzip, dto.ValidationCode); - /* Response Content Type cannot be application/json - * because IE9 with iframe-transport manages the response - * as a file download + /* Response Content Type cannot be application/json + * because IE9 with iframe-transport manages the response + * as a file download */ - return Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.OK, result, mediaTypeFormatter, @@ -713,9 +739,9 @@ public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) { result = new FileUploadDto { - Message = ex.Message + Message = ex.Message, }; - return Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.OK, result, mediaTypeFormatter, @@ -727,6 +753,7 @@ public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) { response.Close(); } + if (responseStream != null) { responseStream.Close(); @@ -734,6 +761,17 @@ public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) } } + private static IEnumerable GetMyPortalGroup() + { + var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); + var mygroup = (from @group in groups + select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); + return mygroup; + } + private string GetFileName(WebResponse response) { if (!response.Headers.AllKeys.Contains("Content-Disposition")) @@ -750,15 +788,16 @@ private bool VerifySafeUrl(string url) Uri uri = new Uri(url); if (uri.Scheme == "http" || uri.Scheme == "https") { - if (!uri.Host.Contains(".")) { return false; } + if (uri.IsLoopback) { return false; } + if (uri.PathAndQuery.Contains("#") || uri.PathAndQuery.Contains(":")) { return false; @@ -766,7 +805,7 @@ private bool VerifySafeUrl(string url) if (uri.Host.StartsWith("10") || uri.Host.StartsWith("172") || uri.Host.StartsWith("192")) { - //check nonroutable IP addresses + // check nonroutable IP addresses if (NetworkUtils.IsIPInRange(uri.Host, "10.0.0.0", "8") || NetworkUtils.IsIPInRange(uri.Host, "172.16.0.0", "12") || NetworkUtils.IsIPInRange(uri.Host, "192.168.0.0", "16")) @@ -777,31 +816,30 @@ private bool VerifySafeUrl(string url) return true; } - return false; - } - private static IEnumerable GetMyPortalGroup() - { - var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); - var mygroup = (from @group in groups - select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); - return mygroup; + return false; } private bool IsPortalIdValid(int portalId) { - if (UserInfo.IsSuperUser) return true; - if (PortalSettings.PortalId == portalId) return true; + if (this.UserInfo.IsSuperUser) + { + return true; + } - var isAdminUser = PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); - if (!isAdminUser) return false; + if (this.PortalSettings.PortalId == portalId) + { + return true; + } + + var isAdminUser = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); + if (!isAdminUser) + { + return false; + } var mygroup = GetMyPortalGroup(); - return (mygroup != null && mygroup.Any(p => p.PortalID == portalId)); + return mygroup != null && mygroup.Any(p => p.PortalID == portalId); } } - } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs index 41c8ca3c81d..ebcaafc66bc 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs @@ -1,183 +1,190 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { - /// - /// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349 - /// Minor improvements including supporting unsigned 16-bit integers when decoding Jfif and added logic - /// to load the image using new Bitmap if reading the headers fails - /// - public static class ImageHeader - { - private const string ErrorMessage = "Could not recognize image format."; - - private static readonly Dictionary> ImageFormatDecoders = new Dictionary - > - { - {new byte[] {0x42, 0x4D}, DecodeBitmap}, - {new byte[] {0x47, 0x49, 0x46, 0x38, 0x37, 0x61}, DecodeGif}, - {new byte[] {0x47, 0x49, 0x46, 0x38, 0x39, 0x61}, DecodeGif}, - {new byte[] {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, DecodePng}, - {new byte[] {0xff, 0xd8}, DecodeJfif}, - }; - + using System; + using System.Collections.Generic; + using System.Drawing; + using System.IO; + using System.Linq; + + /// + /// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349 + /// Minor improvements including supporting unsigned 16-bit integers when decoding Jfif and added logic + /// to load the image using new Bitmap if reading the headers fails. + /// + public static class ImageHeader + { + private const string ErrorMessage = "Could not recognize image format."; - /// - /// Gets the dimensions of an image. - /// - /// The path of the image to get the dimensions of. - /// The dimensions of the specified image. - /// The image was of an unrecognised format. - public static Size GetDimensions(string path) - { - Size size; - try - { - using (var binaryReader = new BinaryReader(File.OpenRead(path))) - { - try - { - size = GetDimensions(binaryReader); - } - catch (ArgumentException e) - { - var newMessage = string.Format("{0} file: '{1}' ", ErrorMessage, path); - throw new ArgumentException(newMessage, "path", e); - } - } - } - catch (ArgumentException) - { - //do it the old fashioned way - using (var b = new Bitmap(path)) - { - size = b.Size; - } - } - return size; - } + private static readonly Dictionary> ImageFormatDecoders = new Dictionary + > + { + { new byte[] { 0x42, 0x4D }, DecodeBitmap }, + { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif }, + { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif }, + { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng }, + { new byte[] { 0xff, 0xd8 }, DecodeJfif }, + }; + + /// + /// Gets the dimensions of an image. + /// + /// The path of the image to get the dimensions of. + /// The dimensions of the specified image. + /// The image was of an unrecognised format. + public static Size GetDimensions(string path) + { + Size size; + try + { + using (var binaryReader = new BinaryReader(File.OpenRead(path))) + { + try + { + size = GetDimensions(binaryReader); + } + catch (ArgumentException e) + { + var newMessage = string.Format("{0} file: '{1}' ", ErrorMessage, path); + throw new ArgumentException(newMessage, "path", e); + } + } + } + catch (ArgumentException) + { + // do it the old fashioned way + using (var b = new Bitmap(path)) + { + size = b.Size; + } + } + + return size; + } - /// - /// Gets the dimensions of an image. - /// - /// The path of the image to get the dimensions of. - /// The dimensions of the specified image. - /// The image was of an unrecognised format. - public static Size GetDimensions(BinaryReader binaryReader) - { - int maxMagicBytesLength = ImageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length; - var magicBytes = new byte[maxMagicBytesLength]; - for (var i = 0; i < maxMagicBytesLength; i += 1) - { - magicBytes[i] = binaryReader.ReadByte(); - foreach (var pair in ImageFormatDecoders) - { - if (StartsWith(magicBytes, pair.Key)) - { - return pair.Value(binaryReader); - } - } - } - throw new ArgumentException(ErrorMessage, "binaryReader"); - } + /// + /// Gets the dimensions of an image. + /// + /// The path of the image to get the dimensions of. + /// The dimensions of the specified image. + /// The image was of an unrecognised format. + public static Size GetDimensions(BinaryReader binaryReader) + { + int maxMagicBytesLength = ImageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length; + var magicBytes = new byte[maxMagicBytesLength]; + for (var i = 0; i < maxMagicBytesLength; i += 1) + { + magicBytes[i] = binaryReader.ReadByte(); + foreach (var pair in ImageFormatDecoders) + { + if (StartsWith(magicBytes, pair.Key)) + { + return pair.Value(binaryReader); + } + } + } + + throw new ArgumentException(ErrorMessage, "binaryReader"); + } - private static bool StartsWith(IList thisBytes, IList thatBytes) - { - for (var i = 0; i < thatBytes.Count; i += 1) - { - if (thisBytes[i] != thatBytes[i]) - { - return false; - } - } - return true; - } + private static bool StartsWith(IList thisBytes, IList thatBytes) + { + for (var i = 0; i < thatBytes.Count; i += 1) + { + if (thisBytes[i] != thatBytes[i]) + { + return false; + } + } + + return true; + } - private static short ReadLittleEndianInt16(BinaryReader binaryReader) - { - var bytes = new byte[sizeof (short)]; - for (var i = 0; i < sizeof (short); i += 1) - { - bytes[sizeof (short) - 1 - i] = binaryReader.ReadByte(); - } - return BitConverter.ToInt16(bytes, 0); - } + private static short ReadLittleEndianInt16(BinaryReader binaryReader) + { + var bytes = new byte[sizeof(short)]; + for (var i = 0; i < sizeof(short); i += 1) + { + bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte(); + } + + return BitConverter.ToInt16(bytes, 0); + } - private static ushort ReadLittleEndianUInt16(BinaryReader binaryReader) - { - var bytes = new byte[sizeof (ushort)]; - for (var i = 0; i < sizeof (ushort); i += 1) - { - bytes[sizeof (ushort) - 1 - i] = binaryReader.ReadByte(); - } - return BitConverter.ToUInt16(bytes, 0); - } + private static ushort ReadLittleEndianUInt16(BinaryReader binaryReader) + { + var bytes = new byte[sizeof(ushort)]; + for (var i = 0; i < sizeof(ushort); i += 1) + { + bytes[sizeof(ushort) - 1 - i] = binaryReader.ReadByte(); + } + + return BitConverter.ToUInt16(bytes, 0); + } - private static int ReadLittleEndianInt32(BinaryReader binaryReader) - { - var bytes = new byte[sizeof(int)]; - for (var i = 0; i < sizeof (int); i += 1) - { - bytes[sizeof (int) - 1 - i] = binaryReader.ReadByte(); - } - return BitConverter.ToInt32(bytes, 0); - } + private static int ReadLittleEndianInt32(BinaryReader binaryReader) + { + var bytes = new byte[sizeof(int)]; + for (var i = 0; i < sizeof(int); i += 1) + { + bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte(); + } + + return BitConverter.ToInt32(bytes, 0); + } - private static Size DecodeBitmap(BinaryReader binaryReader) - { - binaryReader.ReadBytes(16); - var width = binaryReader.ReadInt32(); - var height = binaryReader.ReadInt32(); - return new Size(width, height); - } + private static Size DecodeBitmap(BinaryReader binaryReader) + { + binaryReader.ReadBytes(16); + var width = binaryReader.ReadInt32(); + var height = binaryReader.ReadInt32(); + return new Size(width, height); + } - private static Size DecodeGif(BinaryReader binaryReader) - { - int width = binaryReader.ReadInt16(); - int height = binaryReader.ReadInt16(); - return new Size(width, height); - } + private static Size DecodeGif(BinaryReader binaryReader) + { + int width = binaryReader.ReadInt16(); + int height = binaryReader.ReadInt16(); + return new Size(width, height); + } - private static Size DecodePng(BinaryReader binaryReader) - { - binaryReader.ReadBytes(8); - var width = ReadLittleEndianInt32(binaryReader); - var height = ReadLittleEndianInt32(binaryReader); - return new Size(width, height); - } + private static Size DecodePng(BinaryReader binaryReader) + { + binaryReader.ReadBytes(8); + var width = ReadLittleEndianInt32(binaryReader); + var height = ReadLittleEndianInt32(binaryReader); + return new Size(width, height); + } - private static Size DecodeJfif(BinaryReader binaryReader) - { - while (binaryReader.ReadByte() == 0xff) - { - byte marker = binaryReader.ReadByte(); - short chunkLength = ReadLittleEndianInt16(binaryReader); + private static Size DecodeJfif(BinaryReader binaryReader) + { + while (binaryReader.ReadByte() == 0xff) + { + byte marker = binaryReader.ReadByte(); + short chunkLength = ReadLittleEndianInt16(binaryReader); if (marker == 0xc0 || marker == 0xc2) - { - binaryReader.ReadByte(); - int height = ReadLittleEndianInt16(binaryReader); - int width = ReadLittleEndianInt16(binaryReader); - return new Size(width, height); - } - if (chunkLength < 0) - { - var uchunkLength = (ushort) chunkLength; - binaryReader.ReadBytes(uchunkLength - 2); - } - else - { - binaryReader.ReadBytes(chunkLength - 2); - } - } - throw new ArgumentException(ErrorMessage); - } - } + { + binaryReader.ReadByte(); + int height = ReadLittleEndianInt16(binaryReader); + int width = ReadLittleEndianInt16(binaryReader); + return new Size(width, height); + } + + if (chunkLength < 0) + { + var uchunkLength = (ushort)chunkLength; + binaryReader.ReadBytes(uchunkLength - 2); + } + else + { + binaryReader.ReadBytes(chunkLength - 2); + } + } + + throw new ArgumentException(ErrorMessage); + } + } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs index 6f7750aaa32..4a64f05bb8e 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs @@ -1,200 +1,194 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.Serialization; -using System.Web.Http; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.DataStructures; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Common; -using DotNetNuke.Common; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Runtime.Serialization; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.DataStructures; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Common; + [DnnAuthorize] public class ItemListServiceController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ItemListServiceController)); - private const string PortalPrefix = "P-"; - private const string RootKey = "Root"; - - #region Dtos - - [DataContract] - public class ItemDto - { - [DataMember(Name = "key")] - public string Key { get; set; } - - [DataMember(Name = "value")] - public string Value { get; set; } - - [DataMember(Name = "hasChildren")] - public bool HasChildren { get; set; } - - [DataMember(Name = "selectable")] - public bool Selectable { get; set; } - } - - [DataContract] - public class ItemIdDto - { - [DataMember(Name = "id")] - public string Id { get; set; } - } - - #endregion - - #region Web Methods - - #region Page Methods + private const string RootKey = "Root"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ItemListServiceController)); + [HttpGet] - public HttpResponseMessage GetPageDescendants(string parentId = null, int sortOrder = 0, - string searchText = "", int portalId = -1, bool includeDisabled = false, + public HttpResponseMessage GetPageDescendants(string parentId = null, int sortOrder = 0, + string searchText = "", int portalId = -1, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) { var response = new { Success = true, - Items = GetPageDescendantsInternal(portalId, parentId, sortOrder, searchText, - includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, disabledNotSelectable) + Items = this.GetPageDescendantsInternal(portalId, parentId, sortOrder, searchText, + includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, disabledNotSelectable), }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] public HttpResponseMessage GetTreePathForPage(string itemId, int sortOrder = 0, int portalId = -1, - bool includeDisabled = false, bool includeAllTypes = false, + bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { var response = new { Success = true, - Tree = GetTreePathForPageInternal(portalId, itemId, sortOrder, false, + Tree = this.GetTreePathForPageInternal(portalId, itemId, sortOrder, false, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), - IgnoreRoot = true + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] - public HttpResponseMessage SortPages(string treeAsJson, int sortOrder = 0, string searchText = "", + public HttpResponseMessage SortPages(string treeAsJson, int sortOrder = 0, string searchText = "", int portalId = -1, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { var response = new { Success = true, - Tree = string.IsNullOrEmpty(searchText) ? SortPagesInternal(portalId, treeAsJson, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles) - : SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), - IgnoreRoot = true + Tree = string.IsNullOrEmpty(searchText) ? this.SortPagesInternal(portalId, treeAsJson, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles) + : this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); + } + + [DataContract] + public class ItemDto + { + [DataMember(Name = "key")] + public string Key { get; set; } + + [DataMember(Name = "value")] + public string Value { get; set; } + + [DataMember(Name = "hasChildren")] + public bool HasChildren { get; set; } + + [DataMember(Name = "selectable")] + public bool Selectable { get; set; } } + [DataContract] + public class ItemIdDto + { + [DataMember(Name = "id")] + public string Id { get; set; } + } + [HttpGet] - public HttpResponseMessage SortPagesInPortalGroup(string treeAsJson, int sortOrder = 0, + public HttpResponseMessage SortPagesInPortalGroup(string treeAsJson, int sortOrder = 0, string searchText = "", bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { var response = new { Success = true, - Tree = string.IsNullOrEmpty(searchText) ? SortPagesInPortalGroupInternal(treeAsJson, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles) - : SearchPagesInPortalGroupInternal(treeAsJson, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), - IgnoreRoot = true + Tree = string.IsNullOrEmpty(searchText) ? this.SortPagesInPortalGroupInternal(treeAsJson, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles) + : this.SearchPagesInPortalGroupInternal(treeAsJson, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] - public HttpResponseMessage GetPages(int sortOrder = 0, int portalId = -1, - bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, + public HttpResponseMessage GetPages(int sortOrder = 0, int portalId = -1, + bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) { var response = new { Success = true, - Tree = GetPagesInternal(portalId, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, disabledNotSelectable), - IgnoreRoot = true + Tree = this.GetPagesInternal(portalId, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, disabledNotSelectable), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] - public HttpResponseMessage GetPagesInPortalGroup(int sortOrder = 0) + public HttpResponseMessage GetPagesInPortalGroup(int sortOrder = 0) { var response = new { Success = true, Tree = GetPagesInPortalGroupInternal(sortOrder), - IgnoreRoot = true + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] - public HttpResponseMessage SearchPages(string searchText, int sortOrder = 0, int portalId = -1, + public HttpResponseMessage SearchPages(string searchText, int sortOrder = 0, int portalId = -1, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { var response = new { Success = true, - Tree = string.IsNullOrEmpty(searchText) ? GetPagesInternal(portalId, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, false) - : SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), - IgnoreRoot = true + Tree = string.IsNullOrEmpty(searchText) ? this.GetPagesInternal(portalId, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, false) + : this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] - public HttpResponseMessage GetPageDescendantsInPortalGroup(string parentId = null, int sortOrder = 0, + public HttpResponseMessage GetPageDescendantsInPortalGroup(string parentId = null, int sortOrder = 0, string searchText = "", bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { var response = new { Success = true, - Items = GetPageDescendantsInPortalGroupInternal(parentId, sortOrder, searchText, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles) + Items = this.GetPageDescendantsInPortalGroupInternal(parentId, sortOrder, searchText, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] - public HttpResponseMessage GetTreePathForPageInPortalGroup(string itemId, int sortOrder = 0, + public HttpResponseMessage GetTreePathForPageInPortalGroup(string itemId, int sortOrder = 0, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { var response = new { Success = true, - Tree = GetTreePathForPageInternal(itemId, sortOrder, true, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), - IgnoreRoot = true + Tree = this.GetTreePathForPageInternal(itemId, sortOrder, true, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] - public HttpResponseMessage SearchPagesInPortalGroup(string searchText, int sortOrder = 0, + public HttpResponseMessage SearchPagesInPortalGroup(string searchText, int sortOrder = 0, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { @@ -202,25 +196,21 @@ public HttpResponseMessage SearchPagesInPortalGroup(string searchText, int sortO { Success = true, Tree = string.IsNullOrEmpty(searchText) ? GetPagesInPortalGroupInternal(sortOrder) - : SearchPagesInPortalGroupInternal(searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), - IgnoreRoot = true + : this.SearchPagesInPortalGroupInternal(searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); - } - - #endregion - - #region Folder Methods - + return this.Request.CreateResponse(HttpStatusCode.OK, response); + } + [HttpGet] public HttpResponseMessage GetFolderDescendants(string parentId = null, int sortOrder = 0, string searchText = "", string permission = null, int portalId = -1) { var response = new { Success = true, - Items = GetFolderDescendantsInternal(portalId, parentId, sortOrder, searchText, permission) + Items = this.GetFolderDescendantsInternal(portalId, parentId, sortOrder, searchText, permission), }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] @@ -229,10 +219,10 @@ public HttpResponseMessage GetFolders(int sortOrder = 0, string permission = nul var response = new { Success = true, - Tree = GetFoldersInternal(portalId, sortOrder, permission), - IgnoreRoot = true + Tree = this.GetFoldersInternal(portalId, sortOrder, permission), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] @@ -241,10 +231,10 @@ public HttpResponseMessage SortFolders(string treeAsJson, int sortOrder = 0, str var response = new { Success = true, - Tree = string.IsNullOrEmpty(searchText) ? SortFoldersInternal(portalId, treeAsJson, sortOrder, permission) : SearchFoldersInternal(portalId, searchText, sortOrder, permission), - IgnoreRoot = true + Tree = string.IsNullOrEmpty(searchText) ? this.SortFoldersInternal(portalId, treeAsJson, sortOrder, permission) : this.SearchFoldersInternal(portalId, searchText, sortOrder, permission), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] @@ -253,10 +243,10 @@ public HttpResponseMessage GetTreePathForFolder(string itemId, int sortOrder = 0 var response = new { Success = true, - Tree = GetTreePathForFolderInternal(itemId, sortOrder, permission), - IgnoreRoot = true + Tree = this.GetTreePathForFolderInternal(itemId, sortOrder, permission), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] @@ -265,26 +255,22 @@ public HttpResponseMessage SearchFolders(string searchText, int sortOrder = 0, s var response = new { Success = true, - Tree = string.IsNullOrEmpty(searchText) ? GetFoldersInternal(portalId, sortOrder, permission) : SearchFoldersInternal(portalId, searchText, sortOrder, permission), - IgnoreRoot = true + Tree = string.IsNullOrEmpty(searchText) ? this.GetFoldersInternal(portalId, sortOrder, permission) : this.SearchFoldersInternal(portalId, searchText, sortOrder, permission), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); - } - - #endregion - - #region File Methods - + return this.Request.CreateResponse(HttpStatusCode.OK, response); + } + [HttpGet] public HttpResponseMessage GetFiles(int parentId, string filter, int sortOrder = 0, string permission = null, int portalId = -1) { var response = new { Success = true, - Tree = GetFilesInternal(portalId, parentId, filter, string.Empty, sortOrder, permission), - IgnoreRoot = true + Tree = this.GetFilesInternal(portalId, parentId, filter, string.Empty, sortOrder, permission), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] @@ -293,10 +279,10 @@ public HttpResponseMessage SortFiles(int parentId, string filter, int sortOrder var response = new { Success = true, - Tree = string.IsNullOrEmpty(searchText) ? SortFilesInternal(portalId, parentId, filter, sortOrder, permission) : GetFilesInternal(portalId, parentId, filter, searchText, sortOrder, permission), - IgnoreRoot = true + Tree = string.IsNullOrEmpty(searchText) ? this.SortFilesInternal(portalId, parentId, filter, sortOrder, permission) : this.GetFilesInternal(portalId, parentId, filter, searchText, sortOrder, permission), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } [HttpGet] @@ -305,48 +291,122 @@ public HttpResponseMessage SearchFiles(int parentId, string filter, string searc var response = new { Success = true, - Tree = GetFilesInternal(portalId, parentId, filter, searchText, sortOrder, permission), - IgnoreRoot = true + Tree = this.GetFilesInternal(portalId, parentId, filter, searchText, sortOrder, permission), + IgnoreRoot = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); - } + return this.Request.CreateResponse(HttpStatusCode.OK, response); + } - #endregion + [HttpGet] + public HttpResponseMessage SearchUser(string q) + { + try + { + var portalId = PortalController.GetEffectivePortalId(this.PortalSettings.PortalId); + const int numResults = 5; - #endregion + // GetUsersAdvancedSearch doesn't accept a comma or a single quote in the query so we have to remove them for now. See issue 20224. + q = q.Replace(",", string.Empty).Replace("'", string.Empty); + if (q.Length == 0) + { + return this.Request.CreateResponse(HttpStatusCode.OK, null); + } + + var results = UserController.Instance.GetUsersBasicSearch(portalId, 0, numResults, "DisplayName", true, "DisplayName", q) + .Select(user => new SearchResult + { + id = user.UserID, + name = user.DisplayName, + iconfile = UserController.Instance.GetUserProfilePictureUrl(user.UserID, 32, 32), + }).ToList(); - #region Pages List + return this.Request.CreateResponse(HttpStatusCode.OK, results.OrderBy(sr => sr.name)); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpGet] + public HttpResponseMessage GetTerms(string q, bool includeSystem, bool includeTags) + { + var portalId = PortalSettings.Current.PortalId; + + var vocabRep = Util.GetVocabularyController(); + var termRep = Util.GetTermController(); - private NTree GetPagesInternal(int portalId, int sortOrder, bool includeDisabled = false, + var terms = new ArrayList(); + var vocabularies = from v in vocabRep.GetVocabularies() + where (v.ScopeType.ScopeType == "Application" + || (v.ScopeType.ScopeType == "Portal" && v.ScopeId == portalId)) + && (!v.IsSystem || includeSystem) + && (v.Name != "Tags" || includeTags) + select v; + + foreach (var v in vocabularies) + { + terms.AddRange(new[] + { + from t in termRep.GetTermsByVocabulary(v.VocabularyId) + where string.IsNullOrEmpty(q) || t.Name.IndexOf(q, StringComparison.InvariantCultureIgnoreCase) > -1 + select new { text = t.Name, value = t.TermId }, + }); + } + + return this.Request.CreateResponse(HttpStatusCode.OK, terms); + } + + private static NTree GetPagesInPortalGroupInternal(int sortOrder) + { + var treeNode = new NTree { Data = new ItemDto { Key = RootKey } }; + var portals = GetPortalGroup(sortOrder); + treeNode.Children = portals.Select(dto => new NTree { Data = dto }).ToList(); + return treeNode; + } + + private static IEnumerable GetChildrenOf(IEnumerable tabs, int parentId, IList filterTabs = null) + { + return tabs.Where(tab => tab.ParentId == parentId).Select(tab => new ItemDto + { + Key = tab.TabID.ToString(CultureInfo.InvariantCulture), + Value = tab.LocalizedTabName, + HasChildren = tab.HasChildren, + Selectable = filterTabs == null || filterTabs.Contains(tab.TabID), + }).ToList(); + } + + private static IEnumerable GetChildrenOf(IEnumerable tabs, string parentId) + { + int id; + id = int.TryParse(parentId, out id) ? id : Null.NullInteger; + return GetChildrenOf(tabs, id); + } + + private NTree GetPagesInternal(int portalId, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) { if (portalId == -1) { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } - var tabs = GetPortalPages(portalId, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + + var tabs = this.GetPortalPages(portalId, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); var sortedTree = new NTree { Data = new ItemDto { Key = RootKey } }; if (tabs == null) { return sortedTree; } - var filterTabs = FilterTabsByRole(tabs, roles, disabledNotSelectable); + var filterTabs = this.FilterTabsByRole(tabs, roles, disabledNotSelectable); var children = ApplySort(GetChildrenOf(tabs, Null.NullInteger, filterTabs), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); sortedTree.Children = children; return sortedTree; } - private static NTree GetPagesInPortalGroupInternal(int sortOrder) - { - var treeNode = new NTree { Data = new ItemDto { Key = RootKey } }; - var portals = GetPortalGroup(sortOrder); - treeNode.Children = portals.Select(dto => new NTree { Data = dto }).ToList(); - return treeNode; - } - - private IEnumerable GetPageDescendantsInPortalGroupInternal(string parentId, int sortOrder, + private IEnumerable GetPageDescendantsInPortalGroupInternal(string parentId, int sortOrder, string searchText, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") { @@ -354,6 +414,7 @@ private IEnumerable GetPageDescendantsInPortalGroupInternal(string pare { return null; } + int portalId; int parentIdAsInt; if (parentId.StartsWith(PortalPrefix)) @@ -363,9 +424,10 @@ private IEnumerable GetPageDescendantsInPortalGroupInternal(string pare { portalId = -1; } - if (!String.IsNullOrEmpty(searchText)) + + if (!string.IsNullOrEmpty(searchText)) { - return SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles).Children.Select(node => node.Data); + return this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles).Children.Select(node => node.Data); } } else @@ -376,19 +438,20 @@ private IEnumerable GetPageDescendantsInPortalGroupInternal(string pare parentIdAsInt = -1; } } - return GetPageDescendantsInternal(portalId, parentIdAsInt, sortOrder, searchText, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + + return this.GetPageDescendantsInternal(portalId, parentIdAsInt, sortOrder, searchText, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } - private IEnumerable GetPageDescendantsInternal(int portalId, string parentId, int sortOrder, + private IEnumerable GetPageDescendantsInternal(int portalId, string parentId, int sortOrder, string searchText, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) { int id; id = int.TryParse(parentId, out id) ? id : Null.NullInteger; - return GetPageDescendantsInternal(portalId, id, sortOrder, searchText, includeDisabled , includeAllTypes, includeActive, includeHostPages, roles, disabledNotSelectable); + return this.GetPageDescendantsInternal(portalId, id, sortOrder, searchText, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, disabledNotSelectable); } - private IEnumerable GetPageDescendantsInternal(int portalId, int parentId, int sortOrder, + private IEnumerable GetPageDescendantsInternal(int portalId, int parentId, int sortOrder, string searchText, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) { @@ -396,15 +459,18 @@ private IEnumerable GetPageDescendantsInternal(int portalId, int parent if (portalId == -1) { - portalId = GetActivePortalId(parentId); + portalId = this.GetActivePortalId(parentId); } else { - if (!IsPortalIdValid(portalId)) return new List(); + if (!this.IsPortalIdValid(portalId)) + { + return new List(); + } } Func searchFunc; - if (String.IsNullOrEmpty(searchText)) + if (string.IsNullOrEmpty(searchText)) { searchFunc = page => true; } @@ -415,17 +481,16 @@ private IEnumerable GetPageDescendantsInternal(int portalId, int parent if (portalId > -1) { - tabs = TabController.GetPortalTabs(portalId, (includeActive) ? Null.NullInteger : PortalSettings.ActiveTab.TabID, false, null, true, false, includeAllTypes, true, false) - .Where(tab => searchFunc(tab) - && tab.ParentId == parentId - && (includeDisabled || !tab.DisableLink) + tabs = TabController.GetPortalTabs(portalId, includeActive ? Null.NullInteger : this.PortalSettings.ActiveTab.TabID, false, null, true, false, includeAllTypes, true, false) + .Where(tab => searchFunc(tab) + && tab.ParentId == parentId + && (includeDisabled || !tab.DisableLink) && (includeAllTypes || tab.TabType == TabType.Normal) - && !tab.IsSystem - ) + && !tab.IsSystem) .OrderBy(tab => tab.TabOrder) .ToList(); - if (PortalSettings.UserInfo.IsSuperUser && includeHostPages) + if (this.PortalSettings.UserInfo.IsSuperUser && includeHostPages) { tabs.AddRange(TabController.Instance.GetTabsByPortal(-1).AsList() .Where(tab => searchFunc(tab) && tab.ParentId == parentId && !tab.IsDeleted && !tab.DisableLink && !tab.IsSystem) @@ -435,9 +500,8 @@ private IEnumerable GetPageDescendantsInternal(int portalId, int parent } else { - if (PortalSettings.UserInfo.IsSuperUser) + if (this.PortalSettings.UserInfo.IsSuperUser) { - tabs = TabController.Instance.GetTabsByPortal(-1).AsList() .Where(tab => searchFunc(tab) && tab.ParentId == parentId && !tab.IsDeleted && !tab.DisableLink && !tab.IsSystem) .OrderBy(tab => tab.TabOrder) @@ -449,20 +513,20 @@ private IEnumerable GetPageDescendantsInternal(int portalId, int parent } } - var filterTabs = FilterTabsByRole(tabs, roles, disabledNotSelectable); + var filterTabs = this.FilterTabsByRole(tabs, roles, disabledNotSelectable); var pages = tabs.Select(tab => new ItemDto { Key = tab.TabID.ToString(CultureInfo.InvariantCulture), Value = tab.LocalizedTabName, HasChildren = tab.HasChildren, - Selectable = filterTabs.Contains(tab.TabID) + Selectable = filterTabs.Contains(tab.TabID), }); return ApplySort(pages, sortOrder); } - private NTree SearchPagesInternal(int portalId, string searchText, int sortOrder, + private NTree SearchPagesInternal(int portalId, string searchText, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) { @@ -471,18 +535,18 @@ private NTree SearchPagesInternal(int portalId, string searchText, int List tabs; if (portalId == -1) { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } else { - if (!IsPortalIdValid(portalId)) + if (!this.IsPortalIdValid(portalId)) { return tree; } } Func searchFunc; - if (String.IsNullOrEmpty(searchText)) + if (string.IsNullOrEmpty(searchText)) { searchFunc = page => true; } @@ -493,18 +557,17 @@ private NTree SearchPagesInternal(int portalId, string searchText, int if (portalId > -1) { - tabs = TabController.Instance.GetTabsByPortal(portalId).Where(tab => - (includeActive || tab.Value.TabID != PortalSettings.ActiveTab.TabID) - && (includeDisabled || !tab.Value.DisableLink) - && (includeAllTypes || tab.Value.TabType == TabType.Normal) + (includeActive || tab.Value.TabID != this.PortalSettings.ActiveTab.TabID) + && (includeDisabled || !tab.Value.DisableLink) + && (includeAllTypes || tab.Value.TabType == TabType.Normal) && searchFunc(tab.Value) && !tab.Value.IsSystem) .OrderBy(tab => tab.Value.TabOrder) .Select(tab => tab.Value) .ToList(); - if (PortalSettings.UserInfo.IsSuperUser && includeHostPages) + if (this.PortalSettings.UserInfo.IsSuperUser && includeHostPages) { tabs.AddRange(TabController.Instance.GetTabsByPortal(-1).Where(tab => !tab.Value.DisableLink && searchFunc(tab.Value) && !tab.Value.IsSystem) .OrderBy(tab => tab.Value.TabOrder) @@ -514,7 +577,7 @@ private NTree SearchPagesInternal(int portalId, string searchText, int } else { - if (PortalSettings.UserInfo.IsSuperUser) + if (this.PortalSettings.UserInfo.IsSuperUser) { tabs = TabController.Instance.GetTabsByPortal(-1).Where(tab => !tab.Value.DisableLink && searchFunc(tab.Value) && !tab.Value.IsSystem) .OrderBy(tab => tab.Value.TabOrder) @@ -527,51 +590,51 @@ private NTree SearchPagesInternal(int portalId, string searchText, int } } - var filterTabs = FilterTabsByRole(tabs, roles, disabledNotSelectable); + var filterTabs = this.FilterTabsByRole(tabs, roles, disabledNotSelectable); var pages = tabs.Select(tab => new ItemDto { Key = tab.TabID.ToString(CultureInfo.InvariantCulture), Value = tab.LocalizedTabName, HasChildren = false, - Selectable = filterTabs.Contains(tab.TabID) + Selectable = filterTabs.Contains(tab.TabID), }); tree.Children = ApplySort(pages, sortOrder).Select(dto => new NTree { Data = dto }).ToList(); return tree; } - private List GetPortalPages(int portalId, bool includeDisabled = false, + private List GetPortalPages(int portalId, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { List tabs = null; if (portalId == -1) { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } else { - if (!IsPortalIdValid(portalId)) + if (!this.IsPortalIdValid(portalId)) { return null; } } if (portalId > -1) - { - tabs = TabController.GetPortalTabs(portalId, (includeActive) ? Null.NullInteger : PortalSettings.ActiveTab.TabID, false, null, true, false, includeAllTypes, true, false) - .Where(t => (!t.DisableLink || includeDisabled) && !t.IsSystem) - .ToList(); - - if (PortalSettings.UserInfo.IsSuperUser && includeHostPages) + { + tabs = TabController.GetPortalTabs(portalId, includeActive ? Null.NullInteger : this.PortalSettings.ActiveTab.TabID, false, null, true, false, includeAllTypes, true, false) + .Where(t => (!t.DisableLink || includeDisabled) && !t.IsSystem) + .ToList(); + + if (this.PortalSettings.UserInfo.IsSuperUser && includeHostPages) { tabs.AddRange(TabController.Instance.GetTabsByPortal(-1).AsList().Where(t => !t.IsDeleted && !t.DisableLink && !t.IsSystem).ToList()); } } else { - if (PortalSettings.UserInfo.IsSuperUser) + if (this.PortalSettings.UserInfo.IsSuperUser) { tabs = TabController.Instance.GetTabsByPortal(-1).AsList().Where(t => !t.IsDeleted && !t.DisableLink && !t.IsSystem).ToList(); } @@ -580,47 +643,80 @@ private List GetPortalPages(int portalId, bool includeDisabled = false, return tabs; } - private static IEnumerable GetChildrenOf(IEnumerable tabs, int parentId, IList filterTabs = null) + private static void SortPagesRecursevely(IEnumerable tabs, NTree treeNode, NTree openedNode, int sortOrder) { - return tabs.Where(tab => tab.ParentId == parentId).Select(tab => new ItemDto + if (openedNode == null) { - Key = tab.TabID.ToString(CultureInfo.InvariantCulture), - Value = tab.LocalizedTabName, - HasChildren = tab.HasChildren, - Selectable = filterTabs == null || filterTabs.Contains(tab.TabID) - }).ToList(); + return; + } + + var children = ApplySort(GetChildrenOf(tabs, openedNode.Data.Id), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); + treeNode.Children = children; + if (openedNode.HasChildren()) + { + foreach (var openedNodeChild in openedNode.Children) + { + var treeNodeChild = treeNode.Children.Find(child => string.Equals(child.Data.Key, openedNodeChild.Data.Id, StringComparison.InvariantCultureIgnoreCase)); + if (treeNodeChild == null) + { + continue; + } + + SortPagesRecursevely(tabs, treeNodeChild, openedNodeChild, sortOrder); + } + } } - private static IEnumerable GetChildrenOf(IEnumerable tabs, string parentId) + private static IEnumerable GetPortalGroup(int sortOrder) { - int id; - id = int.TryParse(parentId, out id) ? id : Null.NullInteger; - return GetChildrenOf(tabs, id); + var mygroup = GetMyPortalGroup(); + var portals = mygroup.Select(p => new ItemDto + { + Key = PortalPrefix + p.PortalID.ToString(CultureInfo.InvariantCulture), + Value = p.PortalName, + HasChildren = true, + Selectable = false, + }).ToList(); + return ApplySort(portals, sortOrder); } + + private static IEnumerable ApplySort(IEnumerable items, int sortOrder) + { + switch (sortOrder) + { + case 1: // sort by a-z + return items.OrderBy(item => item.Value).ToList(); + case 2: // sort by z-a + return items.OrderByDescending(item => item.Value).ToList(); + default: // no sort + return items; + } + } - private NTree SortPagesInternal(int portalId, string treeAsJson, int sortOrder, + private NTree SortPagesInternal(int portalId, string treeAsJson, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { var tree = DotNetNuke.Common.Utilities.Json.Deserialize>(treeAsJson); - return SortPagesInternal(portalId, tree, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + return this.SortPagesInternal(portalId, tree, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } - private NTree SortPagesInternal(int portalId, NTree openedNodesTree, int sortOrder, + private NTree SortPagesInternal(int portalId, NTree openedNodesTree, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { - var pages = GetPortalPages(portalId, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + var pages = this.GetPortalPages(portalId, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); var sortedTree = new NTree { Data = new ItemDto { Key = RootKey } }; if (pages == null) { return sortedTree; } + SortPagesRecursevely(pages, sortedTree, openedNodesTree, sortOrder); return sortedTree; } - private NTree SearchPagesInPortalGroupInternal(string searchText, int sortOrder, + private NTree SearchPagesInPortalGroupInternal(string searchText, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { @@ -632,14 +728,15 @@ private NTree SearchPagesInPortalGroupInternal(string searchText, int s int portalId; if (int.TryParse(child.Data.Key.Replace(PortalPrefix, string.Empty), out portalId)) { - var pageTree = SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + var pageTree = this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); child.Children = pageTree.Children; } } + return treeNode; } - private NTree SearchPagesInPortalGroupInternal(string treeAsJson, string searchText, + private NTree SearchPagesInPortalGroupInternal(string treeAsJson, string searchText, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { @@ -657,33 +754,36 @@ private NTree SearchPagesInPortalGroupInternal(string treeAsJson, strin { return treeNode; } + foreach (var openedNodeChild in openedNode.Children) { var portalIdString = openedNodeChild.Data.Id; - var treeNodeChild = treeNode.Children.Find(child => String.Equals(child.Data.Key, portalIdString, StringComparison.InvariantCultureIgnoreCase)); + var treeNodeChild = treeNode.Children.Find(child => string.Equals(child.Data.Key, portalIdString, StringComparison.InvariantCultureIgnoreCase)); if (treeNodeChild == null) { continue; } + int portalId; if (int.TryParse(treeNodeChild.Data.Key.Replace(PortalPrefix, string.Empty), out portalId)) { - var pageTree = SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + var pageTree = this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); treeNodeChild.Children = pageTree.Children; } } + return treeNode; } - private NTree SortPagesInPortalGroupInternal(string treeAsJson, int sortOrder, + private NTree SortPagesInPortalGroupInternal(string treeAsJson, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { var tree = DotNetNuke.Common.Utilities.Json.Deserialize>(treeAsJson); - return SortPagesInPortalGroupInternal(tree, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + return this.SortPagesInPortalGroupInternal(tree, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } - private NTree SortPagesInPortalGroupInternal(NTree openedNode, int sortOrder, + private NTree SortPagesInPortalGroupInternal(NTree openedNode, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { @@ -692,6 +792,7 @@ private NTree SortPagesInPortalGroupInternal(NTree openedNod { return treeNode; } + var portals = GetPortalGroup(sortOrder); treeNode.Children = portals.Select(dto => new NTree { Data = dto }).ToList(); if (openedNode.HasChildren()) @@ -699,46 +800,27 @@ private NTree SortPagesInPortalGroupInternal(NTree openedNod foreach (var openedNodeChild in openedNode.Children) { var portalIdString = openedNodeChild.Data.Id; - var treeNodeChild = treeNode.Children.Find(child => String.Equals(child.Data.Key, portalIdString, StringComparison.InvariantCultureIgnoreCase)); + var treeNodeChild = treeNode.Children.Find(child => string.Equals(child.Data.Key, portalIdString, StringComparison.InvariantCultureIgnoreCase)); if (treeNodeChild == null) { continue; } + int portalId; if (!int.TryParse(portalIdString.Replace(PortalPrefix, string.Empty), out portalId)) { portalId = -1; } - var treeOfPages = SortPagesInternal(portalId, openedNodeChild, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + + var treeOfPages = this.SortPagesInternal(portalId, openedNodeChild, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); treeNodeChild.Children = treeOfPages.Children; } } + return treeNode; } - private static void SortPagesRecursevely(IEnumerable tabs, NTree treeNode, NTree openedNode, int sortOrder) - { - if (openedNode == null) - { - return; - } - var children = ApplySort(GetChildrenOf(tabs, openedNode.Data.Id), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); - treeNode.Children = children; - if (openedNode.HasChildren()) - { - foreach (var openedNodeChild in openedNode.Children) - { - var treeNodeChild = treeNode.Children.Find(child => String.Equals(child.Data.Key, openedNodeChild.Data.Id, StringComparison.InvariantCultureIgnoreCase)); - if (treeNodeChild == null) - { - continue; - } - SortPagesRecursevely(tabs, treeNodeChild, openedNodeChild, sortOrder); - } - } - } - - private NTree GetTreePathForPageInternal(int portalId, string itemId, int sortOrder, + private NTree GetTreePathForPageInternal(int portalId, string itemId, int sortOrder, bool includePortalTree = false, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { @@ -747,10 +829,11 @@ private NTree GetTreePathForPageInternal(int portalId, string itemId, i { itemIdAsInt = Null.NullInteger; } - return GetTreePathForPageInternal(portalId, itemIdAsInt, sortOrder, includePortalTree, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + + return this.GetTreePathForPageInternal(portalId, itemIdAsInt, sortOrder, includePortalTree, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } - private NTree GetTreePathForPageInternal(string itemId, int sortOrder, + private NTree GetTreePathForPageInternal(string itemId, int sortOrder, bool includePortalTree = false, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") { @@ -760,6 +843,7 @@ private NTree GetTreePathForPageInternal(string itemId, int sortOrder, { return tree; } + var portals = PortalController.GetPortalDictionary(); int portalId; if (portals.ContainsKey(itemIdAsInt)) @@ -770,11 +854,12 @@ private NTree GetTreePathForPageInternal(string itemId, int sortOrder, { return tree; } - return GetTreePathForPageInternal(portalId, itemIdAsInt, sortOrder, includePortalTree, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + + return this.GetTreePathForPageInternal(portalId, itemIdAsInt, sortOrder, includePortalTree, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } - private NTree GetTreePathForPageInternal(int portalId, int selectedItemId, - int sortOrder, bool includePortalTree = false, bool includeDisabled = false, + private NTree GetTreePathForPageInternal(int portalId, int selectedItemId, + int sortOrder, bool includePortalTree = false, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) { @@ -785,7 +870,7 @@ private NTree GetTreePathForPageInternal(int portalId, int selectedItem return tree; } - var pages = GetPortalPages(portalId, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); + var pages = this.GetPortalPages(portalId, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); if (pages == null) { @@ -807,12 +892,12 @@ private NTree GetTreePathForPageInternal(int portalId, int selectedItem Value = page.LocalizedTabName, HasChildren = page.HasChildren, Selectable = true - } + }, }; var parentId = page.ParentId; var parentTab = parentId > 0 ? pages.SingleOrDefault(t => t.TabID == parentId) : null; - var filterTabs = FilterTabsByRole(pages, roles, disabledNotSelectable); + var filterTabs = this.FilterTabsByRole(pages, roles, disabledNotSelectable); while (parentTab != null) { // load all sibiling @@ -840,9 +925,9 @@ private NTree GetTreePathForPageInternal(int portalId, int selectedItem Key = parentId.ToString(CultureInfo.InvariantCulture), Value = parentTab.LocalizedTabName, HasChildren = true, - Selectable = true + Selectable = true, }, - Children = siblingTabsTree + Children = siblingTabsTree, }; parentId = parentTab.ParentId; @@ -875,7 +960,7 @@ private NTree GetTreePathForPageInternal(int portalId, int selectedItem Value = portal.PortalName, HasChildren = true, Selectable = false - } + }, }).ToList(); foreach (var node in portalTree) @@ -886,26 +971,15 @@ private NTree GetTreePathForPageInternal(int portalId, int selectedItem break; } } + rootTree = portalTree; } + tree.Children = rootTree; return tree; } - private static IEnumerable GetPortalGroup(int sortOrder) - { - var mygroup = GetMyPortalGroup(); - var portals = mygroup.Select(p => new ItemDto - { - Key = PortalPrefix + p.PortalID.ToString(CultureInfo.InvariantCulture), - Value = p.PortalName, - HasChildren = true, - Selectable = false - }).ToList(); - return ApplySort(portals, sortOrder); - } - private List FilterTabsByRole(IList tabs, string roles, bool disabledNotSelectable) { var filterTabs = new List(); @@ -919,8 +993,7 @@ private List FilterTabsByRole(IList tabs, string roles, bool disab t.TabPermissions.Cast() .Any(p => roleList.Contains(p.RoleID) && p.UserID == Null.NullInteger && p.PermissionKey == "VIEW" && p.AllowAccess)).ToList() .Where(t => !disabledNotSelectable || !t.DisableLink) - .Select(t => t.TabID) - ); + .Select(t => t.TabID)); } else { @@ -928,35 +1001,32 @@ private List FilterTabsByRole(IList tabs, string roles, bool disab } return filterTabs; - } - - #endregion - - #region Folders List - + } + private NTree GetFoldersInternal(int portalId, int sortOrder, string permissions) { var tree = new NTree { Data = new ItemDto { Key = RootKey } }; - var children = ApplySort(GetFolderDescendantsInternal(portalId, -1, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); + var children = ApplySort(this.GetFolderDescendantsInternal(portalId, -1, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); tree.Children = children; foreach (var child in tree.Children) { - children = ApplySort(GetFolderDescendantsInternal(portalId, child.Data.Key, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); + children = ApplySort(this.GetFolderDescendantsInternal(portalId, child.Data.Key, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); child.Children = children; } + return tree; } private NTree SortFoldersInternal(int portalId, string treeAsJson, int sortOrder, string permissions) { var tree = DotNetNuke.Common.Utilities.Json.Deserialize>(treeAsJson); - return SortFoldersInternal(portalId, tree, sortOrder, permissions); + return this.SortFoldersInternal(portalId, tree, sortOrder, permissions); } private NTree SortFoldersInternal(int portalId, NTree openedNodesTree, int sortOrder, string permissions) { var sortedTree = new NTree { Data = new ItemDto { Key = RootKey } }; - SortFoldersRecursevely(portalId, sortedTree, openedNodesTree, sortOrder, permissions); + this.SortFoldersRecursevely(portalId, sortedTree, openedNodesTree, sortOrder, permissions); return sortedTree; } @@ -966,18 +1036,20 @@ private void SortFoldersRecursevely(int portalId, NTree treeNode, NTree { return; } - var children = ApplySort(GetFolderDescendantsInternal(portalId, openedNode.Data.Id, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); + + var children = ApplySort(this.GetFolderDescendantsInternal(portalId, openedNode.Data.Id, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); treeNode.Children = children; if (openedNode.HasChildren()) { foreach (var openedNodeChild in openedNode.Children) { - var treeNodeChild = treeNode.Children.Find(child => String.Equals(child.Data.Key, openedNodeChild.Data.Id, StringComparison.InvariantCultureIgnoreCase)); + var treeNodeChild = treeNode.Children.Find(child => string.Equals(child.Data.Key, openedNodeChild.Data.Id, StringComparison.InvariantCultureIgnoreCase)); if (treeNodeChild == null) { continue; } - SortFoldersRecursevely(portalId, treeNodeChild, openedNodeChild, sortOrder, permissions); + + this.SortFoldersRecursevely(portalId, treeNodeChild, openedNodeChild, sortOrder, permissions); } } } @@ -986,20 +1058,24 @@ private IEnumerable GetFolderDescendantsInternal(int portalId, string p { int id; id = int.TryParse(parentId, out id) ? id : Null.NullInteger; - return GetFolderDescendantsInternal(portalId, id, sortOrder, searchText, permission); + return this.GetFolderDescendantsInternal(portalId, id, sortOrder, searchText, permission); } private IEnumerable GetFolderDescendantsInternal(int portalId, int parentId, int sortOrder, string searchText, string permission) { if (portalId > -1) { - if (!IsPortalIdValid(portalId)) return new List(); + if (!this.IsPortalIdValid(portalId)) + { + return new List(); + } } else { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } - var parentFolder = parentId > -1 ? FolderManager.Instance.GetFolder(parentId) : FolderManager.Instance.GetFolder(portalId, ""); + + var parentFolder = parentId > -1 ? FolderManager.Instance.GetFolder(parentId) : FolderManager.Instance.GetFolder(portalId, string.Empty); if (parentFolder == null) { @@ -1007,26 +1083,35 @@ private IEnumerable GetFolderDescendantsInternal(int portalId, int pare } var hasPermission = string.IsNullOrEmpty(permission) ? - (HasPermission(parentFolder, "BROWSE") || HasPermission(parentFolder, "READ")) : - HasPermission(parentFolder, permission.ToUpper()); - if (!hasPermission) return new List(); - - if (parentId < 1) return new List { new ItemDto + (this.HasPermission(parentFolder, "BROWSE") || this.HasPermission(parentFolder, "READ")) : + this.HasPermission(parentFolder, permission.ToUpper()); + if (!hasPermission) + { + return new List(); + } + + if (parentId < 1) + { + return new List + { + new ItemDto { - Key = parentFolder.FolderID.ToString(CultureInfo.InvariantCulture), + Key = parentFolder.FolderID.ToString(CultureInfo.InvariantCulture), Value = portalId == -1 ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder, - HasChildren = HasChildren(parentFolder, permission), + HasChildren = this.HasChildren(parentFolder, permission), Selectable = true - } }; - - var childrenFolders = GetFolderDescendants(parentFolder, searchText, permission); + }, + }; + } + + var childrenFolders = this.GetFolderDescendants(parentFolder, searchText, permission); var folders = childrenFolders.Select(folder => new ItemDto { Key = folder.FolderID.ToString(CultureInfo.InvariantCulture), Value = folder.FolderName, - HasChildren = HasChildren(folder, permission), - Selectable = true + HasChildren = this.HasChildren(folder, permission), + Selectable = true, }); return ApplySort(folders, sortOrder); @@ -1038,23 +1123,23 @@ private NTree SearchFoldersInternal(int portalId, string searchText, in if (portalId > -1) { - if (!IsPortalIdValid(portalId)) + if (!this.IsPortalIdValid(portalId)) { return tree; } } else { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } - var allFolders = GetPortalFolders(portalId, searchText, permission); + var allFolders = this.GetPortalFolders(portalId, searchText, permission); var folders = allFolders.Select(f => new ItemDto { Key = f.FolderID.ToString(CultureInfo.InvariantCulture), Value = f.FolderName, HasChildren = false, - Selectable = true + Selectable = true, }); tree.Children = ApplySort(folders, sortOrder).Select(dto => new NTree { Data = dto }).ToList(); return tree; @@ -1082,19 +1167,22 @@ private NTree GetTreePathForFolderInternal(string selectedItemId, int s } var hasPermission = string.IsNullOrEmpty(permission) ? - (HasPermission(folder, "BROWSE") || HasPermission(folder, "READ")) : - HasPermission(folder, permission.ToUpper()); - if (!hasPermission) return new NTree(); - + (this.HasPermission(folder, "BROWSE") || this.HasPermission(folder, "READ")) : + this.HasPermission(folder, permission.ToUpper()); + if (!hasPermission) + { + return new NTree(); + } + var selfTree = new NTree { Data = new ItemDto { Key = folder.FolderID.ToString(CultureInfo.InvariantCulture), Value = folder.FolderName, - HasChildren = HasChildren(folder, permission), + HasChildren = this.HasChildren(folder, permission), Selectable = true - } + }, }; var parentId = folder.ParentID; var parentFolder = parentId > 0 ? FolderManager.Instance.GetFolder(parentId) : null; @@ -1102,13 +1190,13 @@ private NTree GetTreePathForFolderInternal(string selectedItemId, int s while (parentFolder != null) { // load all sibling - var siblingFolders = GetFolderDescendants(parentFolder, string.Empty, permission) + var siblingFolders = this.GetFolderDescendants(parentFolder, string.Empty, permission) .Select(folderInfo => new ItemDto { Key = folderInfo.FolderID.ToString(CultureInfo.InvariantCulture), Value = folderInfo.FolderName, - HasChildren = HasChildren(folderInfo, permission), - Selectable = true + HasChildren = this.HasChildren(folderInfo, permission), + Selectable = true, }).ToList(); siblingFolders = ApplySort(siblingFolders, sortOrder).ToList(); @@ -1134,14 +1222,15 @@ private NTree GetTreePathForFolderInternal(string selectedItemId, int s Key = parentId.ToString(CultureInfo.InvariantCulture), Value = parentFolder.FolderName, HasChildren = true, - Selectable = true + Selectable = true, }, - Children = siblingFoldersTree + Children = siblingFoldersTree, }; parentId = parentFolder.ParentID; parentFolder = parentId > 0 ? FolderManager.Instance.GetFolder(parentId) : null; } + selfTree.Data.Value = DynamicSharedConstants.RootFolder; tree.Children.Add(selfTree); @@ -1150,7 +1239,7 @@ private NTree GetTreePathForFolderInternal(string selectedItemId, int s private bool HasPermission(IFolderInfo folder, string permissionKey) { - var hasPermision = PortalSettings.UserInfo.IsSuperUser; + var hasPermision = this.PortalSettings.UserInfo.IsSuperUser; if (!hasPermision && folder != null) { @@ -1163,7 +1252,7 @@ private bool HasPermission(IFolderInfo folder, string permissionKey) private IEnumerable GetFolderDescendants(IFolderInfo parentFolder, string searchText, string permission) { Func searchFunc; - if (String.IsNullOrEmpty(searchText)) + if (string.IsNullOrEmpty(searchText)) { searchFunc = folder => true; } @@ -1171,22 +1260,23 @@ private IEnumerable GetFolderDescendants(IFolderInfo parentFolder, { searchFunc = folder => folder.FolderName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1; } + permission = string.IsNullOrEmpty(permission) ? null : permission.ToUpper(); return FolderManager.Instance.GetFolders(parentFolder).Where(folder => (string.IsNullOrEmpty(permission) ? - (HasPermission(folder, "BROWSE") || HasPermission(folder, "READ")) : - (HasPermission(folder, permission)) - ) && searchFunc(folder)); + (this.HasPermission(folder, "BROWSE") || this.HasPermission(folder, "READ")) : + this.HasPermission(folder, permission)) && searchFunc(folder)); } private IEnumerable GetPortalFolders(int portalId, string searchText, string permission) { if (portalId == -1) { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } + Func searchFunc; - if (String.IsNullOrEmpty(searchText)) + if (string.IsNullOrEmpty(searchText)) { searchFunc = folder => true; } @@ -1194,12 +1284,12 @@ private IEnumerable GetPortalFolders(int portalId, string searchTex { searchFunc = folder => folder.FolderName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1; } + permission = string.IsNullOrEmpty(permission) ? null : permission.ToUpper(); return FolderManager.Instance.GetFolders(portalId).Where(folder => (string.IsNullOrEmpty(permission) ? - (HasPermission(folder, "BROWSE") || HasPermission(folder, "READ")) : - (HasPermission(folder, permission)) - ) && searchFunc(folder)); + (this.HasPermission(folder, "BROWSE") || this.HasPermission(folder, "READ")) : + this.HasPermission(folder, permission)) && searchFunc(folder)); } private bool HasChildren(IFolderInfo parentFolder, string permission) @@ -1207,20 +1297,14 @@ private bool HasChildren(IFolderInfo parentFolder, string permission) permission = string.IsNullOrEmpty(permission) ? null : permission.ToUpper(); return FolderManager.Instance.GetFolders(parentFolder).Any(folder => (string.IsNullOrEmpty(permission) ? - (HasPermission(folder, "BROWSE") || HasPermission(folder, "READ")) : - (HasPermission(folder, permission)) - ) - ); - } - - #endregion - - #region Files List - + (this.HasPermission(folder, "BROWSE") || this.HasPermission(folder, "READ")) : + this.HasPermission(folder, permission))); + } + private NTree GetFilesInternal(int portalId, int parentId, string filter, string searchText, int sortOrder, string permissions) { var tree = new NTree { Data = new ItemDto { Key = RootKey } }; - var children = GetFileItemsDto(portalId, parentId, filter, searchText, permissions, sortOrder).Select(dto => new NTree { Data = dto }).ToList(); + var children = this.GetFileItemsDto(portalId, parentId, filter, searchText, permissions, sortOrder).Select(dto => new NTree { Data = dto }).ToList(); tree.Children = children; return tree; } @@ -1228,7 +1312,7 @@ private NTree GetFilesInternal(int portalId, int parentId, string filte private NTree SortFilesInternal(int portalId, int parentId, string filter, int sortOrder, string permissions) { var sortedTree = new NTree { Data = new ItemDto { Key = RootKey } }; - var children = GetFileItemsDto(portalId, parentId, filter, string.Empty, permissions, sortOrder).Select(dto => new NTree { Data = dto }).ToList(); + var children = this.GetFileItemsDto(portalId, parentId, filter, string.Empty, permissions, sortOrder).Select(dto => new NTree { Data = dto }).ToList(); sortedTree.Children = children; return sortedTree; } @@ -1237,13 +1321,17 @@ private IEnumerable GetFileItemsDto(int portalId, int parentId, string { if (portalId > -1) { - if (!IsPortalIdValid(portalId)) return new List(); + if (!this.IsPortalIdValid(portalId)) + { + return new List(); + } } else { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } - var parentFolder = parentId > -1 ? FolderManager.Instance.GetFolder(parentId) : FolderManager.Instance.GetFolder(portalId, ""); + + var parentFolder = parentId > -1 ? FolderManager.Instance.GetFolder(parentId) : FolderManager.Instance.GetFolder(portalId, string.Empty); if (parentFolder == null) { @@ -1251,23 +1339,26 @@ private IEnumerable GetFileItemsDto(int portalId, int parentId, string } var hasPermission = string.IsNullOrEmpty(permission) ? - (HasPermission(parentFolder, "BROWSE") || HasPermission(parentFolder, "READ")) : - HasPermission(parentFolder, permission.ToUpper()); - if (!hasPermission) return new List(); - + (this.HasPermission(parentFolder, "BROWSE") || this.HasPermission(parentFolder, "READ")) : + this.HasPermission(parentFolder, permission.ToUpper()); + if (!hasPermission) + { + return new List(); + } + if (parentId < 1) { return new List(); } - var files = GetFiles(parentFolder, filter, searchText); + var files = this.GetFiles(parentFolder, filter, searchText); var filesDto = files.Select(f => new ItemDto { Key = f.FileId.ToString(CultureInfo.InvariantCulture), Value = f.FileName, HasChildren = false, - Selectable = true + Selectable = true, }).ToList(); var sortedList = ApplySort(filesDto, sortOrder); @@ -1279,7 +1370,7 @@ private IEnumerable GetFiles(IFolderInfo parentFolder, string filter, { Func searchFunc; var filterList = string.IsNullOrEmpty(filter) ? null : filter.ToLowerInvariant().Split(',').ToList(); - if (String.IsNullOrEmpty(searchText)) + if (string.IsNullOrEmpty(searchText)) { searchFunc = f => filterList == null || filterList.Contains(f.Extension.ToLowerInvariant()); } @@ -1290,14 +1381,10 @@ private IEnumerable GetFiles(IFolderInfo parentFolder, string filter, } return FolderManager.Instance.GetFiles(parentFolder).Where(f => searchFunc(f)); - } - - #endregion - - #region Users List - + } + /// - /// This class stores a single search result needed by jQuery Tokeninput + /// This class stores a single search result needed by jQuery Tokeninput. /// private class SearchResult { @@ -1306,111 +1393,42 @@ private class SearchResult public int id; public string name; public string iconfile; + // ReSharper restore NotAccessedField.Local // ReSharper restore InconsistentNaming } - - [HttpGet] - public HttpResponseMessage SearchUser(string q) - { - try - { - var portalId = PortalController.GetEffectivePortalId(PortalSettings.PortalId); - const int numResults = 5; - - // GetUsersAdvancedSearch doesn't accept a comma or a single quote in the query so we have to remove them for now. See issue 20224. - q = q.Replace(",", "").Replace("'", ""); - if (q.Length == 0) return Request.CreateResponse(HttpStatusCode.OK, null); - - var results = UserController.Instance.GetUsersBasicSearch(portalId, 0, numResults, "DisplayName", true, "DisplayName", q) - .Select(user => new SearchResult - { - id = user.UserID, - name = user.DisplayName, - iconfile = UserController.Instance.GetUserProfilePictureUrl(user.UserID, 32, 32), - }).ToList(); - - return Request.CreateResponse(HttpStatusCode.OK, results.OrderBy(sr => sr.name)); - } - catch (Exception exc) - { - Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - #endregion - - #region Terms List - - [HttpGet] - public HttpResponseMessage GetTerms(string q, bool includeSystem, bool includeTags) - { - var portalId = PortalSettings.Current.PortalId; - - var vocabRep = Util.GetVocabularyController(); - var termRep = Util.GetTermController(); - - var terms = new ArrayList(); - var vocabularies = from v in vocabRep.GetVocabularies() - where (v.ScopeType.ScopeType == "Application" - || (v.ScopeType.ScopeType == "Portal" && v.ScopeId == portalId)) - && (!v.IsSystem || includeSystem) - && (v.Name != "Tags" || includeTags) - select v; - - foreach (var v in vocabularies) - { - terms.AddRange(new[] {from t in termRep.GetTermsByVocabulary(v.VocabularyId) - where string.IsNullOrEmpty(q) || t.Name.IndexOf(q, StringComparison.InvariantCultureIgnoreCase) > -1 - select new {text = t.Name, value = t.TermId}}); - } - - return Request.CreateResponse(HttpStatusCode.OK, terms); - } - - #endregion - - #region Sort - - private static IEnumerable ApplySort(IEnumerable items, int sortOrder) - { - switch (sortOrder) - { - case 1: // sort by a-z - return items.OrderBy(item => item.Value).ToList(); - case 2: // sort by z-a - return items.OrderByDescending(item => item.Value).ToList(); - default: // no sort - return items; - } - } - - #endregion - - #region check portal permission - + private static IEnumerable GetMyPortalGroup() { var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); var mygroup = (from @group in groups select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); return mygroup; } private bool IsPortalIdValid(int portalId) { - if (UserInfo.IsSuperUser) return true; - if (PortalSettings.PortalId == portalId) return true; - - var isAdminUser = PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); - if (!isAdminUser) return false; - + if (this.UserInfo.IsSuperUser) + { + return true; + } + + if (this.PortalSettings.PortalId == portalId) + { + return true; + } + + var isAdminUser = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); + if (!isAdminUser) + { + return false; + } + var mygroup = GetMyPortalGroup(); - return (mygroup != null && mygroup.Any(p => p.PortalID == portalId)); + return mygroup != null && mygroup.Any(p => p.PortalID == portalId); } private int GetActivePortalId(int pageId) @@ -1420,21 +1438,21 @@ private int GetActivePortalId(int pageId) if (portalId == Null.NullInteger) { - portalId = GetActivePortalId(); + portalId = this.GetActivePortalId(); } + return portalId; } private int GetActivePortalId() { var portalId = -1; - if (!TabController.CurrentPage.IsSuperTab) - portalId = PortalSettings.PortalId; - + if (!TabController.CurrentPage.IsSuperTab) + { + portalId = this.PortalSettings.PortalId; + } + return portalId; - } - - #endregion - + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs index bdca517aae9..c23114caca7 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs @@ -1,65 +1,70 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web; -using System.Web.Http; -using System.Collections.Generic; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Api; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Abstractions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Abstractions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class LanguageServiceController : DnnApiController { - protected INavigationManager NavigationManager { get; } public LanguageServiceController(INavigationManager navigationManager) { - NavigationManager = navigationManager; - } - - public class PageDto - { - public string Name { get; set; } - public string ViewUrl { get; set; } - public string EditUrl { get; set; } - } - private bool IsDefaultLanguage(string code) - { - return code == PortalSettings.DefaultLanguage; + this.NavigationManager = navigationManager; } + + protected INavigationManager NavigationManager { get; } [HttpGet] public HttpResponseMessage GetNonTranslatedPages(string languageCode) { var request = HttpContext.Current.Request; - var locale = new LocaleController().GetLocale(languageCode); + var locale = new LocaleController().GetLocale(languageCode); List pages = new List(); - if (!IsDefaultLanguage(locale.Code)) + if (!this.IsDefaultLanguage(locale.Code)) { TabController ctl = new TabController(); - var nonTranslated = (from t in ctl.GetTabsByPortal(PortalSettings.PortalId).WithCulture(locale.Code, false).Values where !t.IsTranslated && !t.IsDeleted select t); + var nonTranslated = from t in ctl.GetTabsByPortal(this.PortalSettings.PortalId).WithCulture(locale.Code, false).Values where !t.IsTranslated && !t.IsDeleted select t; foreach (TabInfo page in nonTranslated) { pages.Add(new PageDto() { Name = page.TabName, - ViewUrl = NavigationManager.NavigateURL(page.TabID), - EditUrl = NavigationManager.NavigateURL(page.TabID, "Tab", "action=edit", "returntabid=" + PortalSettings.ActiveTab.TabID) + ViewUrl = this.NavigationManager.NavigateURL(page.TabID), + EditUrl = this.NavigationManager.NavigateURL(page.TabID, "Tab", "action=edit", "returntabid=" + this.PortalSettings.ActiveTab.TabID), }); } } - return Request.CreateResponse(HttpStatusCode.OK, pages); + + return this.Request.CreateResponse(HttpStatusCode.OK, pages); + } + + private bool IsDefaultLanguage(string code) + { + return code == this.PortalSettings.DefaultLanguage; + } + + public class PageDto + { + public string Name { get; set; } + + public string ViewUrl { get; set; } + + public string EditUrl { get; set; } } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs index 630ce36977e..97fd3384e13 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs @@ -1,63 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Dynamic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web; -using System.Web.Http; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections.Generic; + using System.Dynamic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class MessagingServiceController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (MessagingServiceController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MessagingServiceController)); + [HttpGet] public HttpResponseMessage WaitTimeForNextMessage() { try { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Value = InternalMessagingController.Instance.WaitTimeForNextMessage(UserInfo) }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Value = InternalMessagingController.Instance.WaitTimeForNextMessage(this.UserInfo) }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } - public class CreateDTO - { - public string Subject; - public string Body; - public string RoleIds; - public string UserIds; - public string FileIds; - } - [ValidateAntiForgeryToken] [HttpPost] public HttpResponseMessage Create(CreateDTO postData) { try { - var portalId = PortalController.GetEffectivePortalId(PortalSettings.PortalId); + var portalId = PortalController.GetEffectivePortalId(this.PortalSettings.PortalId); var roleIdsList = string.IsNullOrEmpty(postData.RoleIds) ? null : postData.RoleIds.FromJson>(); var userIdsList = string.IsNullOrEmpty(postData.UserIds) ? null : postData.UserIds.FromJson>(); var fileIdsList = string.IsNullOrEmpty(postData.FileIds) ? null : postData.FileIds.FromJson>(); @@ -74,12 +66,12 @@ public HttpResponseMessage Create(CreateDTO postData) var message = new Message { Subject = HttpUtility.UrlDecode(postData.Subject), Body = HttpUtility.UrlDecode(postData.Body) }; MessagingController.Instance.SendMessage(message, roles, users, fileIdsList); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Value = message.MessageID }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Value = message.MessageID }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -88,48 +80,60 @@ public HttpResponseMessage Search(string q) { try { - var portalId = PortalController.GetEffectivePortalId(PortalSettings.PortalId); - var isAdmin = UserInfo.IsSuperUser || UserInfo.IsInRole("Administrators"); + var portalId = PortalController.GetEffectivePortalId(this.PortalSettings.PortalId); + var isAdmin = this.UserInfo.IsSuperUser || this.UserInfo.IsInRole("Administrators"); const int numResults = 10; // GetUsersAdvancedSearch doesn't accept a comma or a single quote in the query so we have to remove them for now. See issue 20224. - q = q.Replace(",", "").Replace("'", ""); - if (q.Length == 0) return Request.CreateResponse(HttpStatusCode.OK, null); - + q = q.Replace(",", string.Empty).Replace("'", string.Empty); + if (q.Length == 0) + { + return this.Request.CreateResponse(HttpStatusCode.OK, null); + } + var results = UserController.Instance.GetUsersBasicSearch(portalId, 0, numResults, "DisplayName", true, "DisplayName", q) .Select(user => new SearchResult { id = "user-" + user.UserID, name = user.DisplayName, - iconfile = UserController.Instance.GetUserProfilePictureUrl(user.UserID, 32, 32) + iconfile = UserController.Instance.GetUserProfilePictureUrl(user.UserID, 32, 32), }).ToList(); - //Roles should be visible to Administrators or User in the Role. + // Roles should be visible to Administrators or User in the Role. var roles = RoleController.Instance.GetRolesBasicSearch(portalId, numResults, q); - results.AddRange(from roleInfo in roles - where - isAdmin || - UserInfo.Social.Roles.SingleOrDefault(ur => ur.RoleID == roleInfo.RoleID && ur.IsOwner) != null - select new SearchResult - { - id = "role-" + roleInfo.RoleID, - name = roleInfo.RoleName, - iconfile = TestableGlobals.Instance.ResolveUrl(string.IsNullOrEmpty(roleInfo.IconFile) - ? "~/images/no_avatar.gif" - : PortalSettings.HomeDirectory.TrimEnd('/') + "/" + roleInfo.IconFile) - }); + results.AddRange(from roleInfo in roles + where + isAdmin || + this.UserInfo.Social.Roles.SingleOrDefault(ur => ur.RoleID == roleInfo.RoleID && ur.IsOwner) != null + select new SearchResult + { + id = "role-" + roleInfo.RoleID, + name = roleInfo.RoleName, + iconfile = TestableGlobals.Instance.ResolveUrl(string.IsNullOrEmpty(roleInfo.IconFile) + ? "~/images/no_avatar.gif" + : this.PortalSettings.HomeDirectory.TrimEnd('/') + "/" + roleInfo.IconFile), + }); - return Request.CreateResponse(HttpStatusCode.OK, results.OrderBy(sr => sr.name)); + return this.Request.CreateResponse(HttpStatusCode.OK, results.OrderBy(sr => sr.name)); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } + public class CreateDTO + { + public string Subject; + public string Body; + public string RoleIds; + public string UserIds; + public string FileIds; + } + /// - /// This class stores a single search result needed by jQuery Tokeninput + /// This class stores a single search result needed by jQuery Tokeninput. /// private class SearchResult { @@ -138,6 +142,7 @@ private class SearchResult public string id; public string name; public string iconfile; + // ReSharper restore NotAccessedField.Local // ReSharper restore InconsistentNaming } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs index b75c1fbd468..c94be293c03 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs @@ -1,40 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + [DnnAuthorize] public class ModuleServiceController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleServiceController)); - public class MoveModuleDTO - { - public int ModuleId { get; set; } - public int ModuleOrder { get; set; } - public string Pane { get; set; } - public int TabId { get; set; } - } - - public class DeleteModuleDto - { - public int ModuleId { get; set; } - public int TabId { get; set; } - public bool SoftDelete { get; set; } - } [HttpGet] [DnnAuthorize(StaticRoles = "Registered Users")] @@ -48,7 +35,7 @@ public HttpResponseMessage GetModuleShareable(int moduleId, int tabId, int porta } else { - portalId = FixPortalId(portalId); + portalId = this.FixPortalId(portalId); } DesktopModuleInfo desktopModule; @@ -62,17 +49,17 @@ public HttpResponseMessage GetModuleShareable(int moduleId, int tabId, int porta desktopModule = moduleInfo.DesktopModule; - requiresWarning = moduleInfo.PortalID != PortalSettings.PortalId && desktopModule.Shareable == ModuleSharing.Unknown; + requiresWarning = moduleInfo.PortalID != this.PortalSettings.PortalId && desktopModule.Shareable == ModuleSharing.Unknown; } if (desktopModule == null) { var message = string.Format("Cannot find module ID {0} (tab ID {1}, portal ID {2})", moduleId, tabId, portalId); Logger.Error(message); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message); } - return Request.CreateResponse(HttpStatusCode.OK, new { Shareable = desktopModule.Shareable.ToString(), RequiresWarning = requiresWarning }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Shareable = desktopModule.Shareable.ToString(), RequiresWarning = requiresWarning }); } [HttpPost] @@ -83,8 +70,8 @@ public HttpResponseMessage MoveModule(MoveModuleDTO postData) var moduleOrder = postData.ModuleOrder; if (moduleOrder > 0) { - //DNN-7099: the deleted modules won't show in page, so when the module index calculated from client, it will lost the - //index count of deleted modules and will cause order issue. + // DNN-7099: the deleted modules won't show in page, so when the module index calculated from client, it will lost the + // index count of deleted modules and will cause order issue. var deletedModules = ModuleController.Instance.GetTabModules(postData.TabId).Values.Where(m => m.IsDeleted); foreach (var module in deletedModules) { @@ -94,18 +81,19 @@ public HttpResponseMessage MoveModule(MoveModuleDTO postData) } } } + ModuleController.Instance.UpdateModuleOrder(postData.TabId, postData.ModuleId, moduleOrder, postData.Pane); ModuleController.Instance.UpdateTabModuleOrder(postData.TabId); - return Request.CreateResponse(HttpStatusCode.OK); + return this.Request.CreateResponse(HttpStatusCode.OK); } /// /// Web method that deletes a tab module. /// /// This has been introduced for integration testing purpuses. - /// delete module dto - /// Http response message + /// delete module dto. + /// Http response message. [HttpPost] [ValidateAntiForgeryToken] [DnnAuthorize(StaticRoles = "Administrators")] @@ -113,15 +101,35 @@ public HttpResponseMessage DeleteModule(DeleteModuleDto deleteModuleDto) { ModuleController.Instance.DeleteTabModule(deleteModuleDto.TabId, deleteModuleDto.ModuleId, deleteModuleDto.SoftDelete); - return Request.CreateResponse(HttpStatusCode.OK); + return this.Request.CreateResponse(HttpStatusCode.OK); + } + + public class MoveModuleDTO + { + public int ModuleId { get; set; } + + public int ModuleOrder { get; set; } + + public string Pane { get; set; } + + public int TabId { get; set; } + } + + public class DeleteModuleDto + { + public int ModuleId { get; set; } + + public int TabId { get; set; } + + public bool SoftDelete { get; set; } } private int FixPortalId(int portalId) { - return UserInfo.IsSuperUser && PortalSettings.PortalId != portalId && PortalController.Instance.GetPortals() + return this.UserInfo.IsSuperUser && this.PortalSettings.PortalId != portalId && PortalController.Instance.GetPortals() .OfType().Any(x => x.PortalID == portalId) ? portalId - : PortalSettings.PortalId; + : this.PortalSettings.PortalId; } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/NewUserNotificationServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/NewUserNotificationServiceController.cs index 6bf41f40aa1..b2d12d04fdb 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/NewUserNotificationServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/NewUserNotificationServiceController.cs @@ -1,61 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Common; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; -using DotNetNuke.Services.Mail; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class NewUserNotificationServiceController : DnnApiController - { + { [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage Authorize(NotificationDTO postData) { - var user = GetUser(postData); + var user = this.GetUser(postData); if (user == null) { NotificationsController.Instance.DeleteNotification(postData.NotificationId); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "User not found"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "User not found"); } user.Membership.Approved = true; - UserController.UpdateUser(PortalSettings.PortalId, user); + UserController.UpdateUser(this.PortalSettings.PortalId, user); - //Update User Roles if needed - if (!user.IsSuperUser && user.IsInRole("Unverified Users") && PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) + // Update User Roles if needed + if (!user.IsSuperUser && user.IsInRole("Unverified Users") && this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) { UserController.ApproveUser(user); } - Mail.SendMail(user, MessageType.UserAuthorized, PortalSettings); + Mail.SendMail(user, MessageType.UserAuthorized, this.PortalSettings); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage Reject(NotificationDTO postData) { - var user = GetUser(postData); + var user = this.GetUser(postData); if (user == null) { NotificationsController.Instance.DeleteNotification(postData.NotificationId); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "User not found"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "User not found"); } UserController.RemoveUser(user); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } [HttpPost] @@ -63,24 +64,24 @@ public HttpResponseMessage Reject(NotificationDTO postData) [ValidateAntiForgeryToken] public HttpResponseMessage SendVerificationMail(NotificationDTO postData) { - if (UserInfo.Membership.Approved) + if (this.UserInfo.Membership.Approved) { throw new UserAlreadyVerifiedException(); } - if (!UserInfo.IsInRole("Unverified Users")) + if (!this.UserInfo.IsInRole("Unverified Users")) { throw new InvalidVerificationCodeException(); } - var message = Mail.SendMail(UserInfo, MessageType.UserRegistrationVerified, PortalSettings); + var message = Mail.SendMail(this.UserInfo, MessageType.UserRegistrationVerified, this.PortalSettings); if (string.IsNullOrEmpty(message)) { - return Request.CreateResponse(HttpStatusCode.OK, new {Result = Localization.GetSafeJSString("VerificationMailSendSuccessful", Localization.SharedResourceFile) }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = Localization.GetSafeJSString("VerificationMailSendSuccessful", Localization.SharedResourceFile) }); } else { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message); } } @@ -94,7 +95,7 @@ private UserInfo GetUser(NotificationDTO notificationDto) return null; } - return UserController.GetUserById(PortalSettings.PortalId, userId); + return UserController.GetUserById(this.PortalSettings.PortalId, userId); } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/NotificationDto.cs b/DNN Platform/DotNetNuke.Web/InternalServices/NotificationDto.cs index 980ade62373..2be4d4214ea 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/NotificationDto.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/NotificationDto.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { public class NotificationDTO diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs index 0d632c1c2dc..f73640c61be 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs @@ -1,60 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class NotificationsServiceController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (NotificationsServiceController)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(NotificationsServiceController)); + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage Dismiss(NotificationDTO postData) { try { - var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID); + var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); if (recipient != null) { - NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, UserInfo.UserID); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, this.UserInfo.UserID); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unable to dismiss notification"); + return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unable to dismiss notification"); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } + + [HttpGet] + public HttpResponseMessage GetToasts() + { + var toasts = NotificationsController.Instance.GetToasts(this.UserInfo); + IList convertedObjects = toasts.Select(this.ToExpandoObject).ToList(); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true, Toasts = convertedObjects.Take(3) }); + } - - [HttpGet] - public HttpResponseMessage GetToasts() - { - var toasts = NotificationsController.Instance.GetToasts(this.UserInfo); - IList convertedObjects = toasts.Select(ToExpandoObject).ToList(); - return Request.CreateResponse(HttpStatusCode.OK, new { Success = true, Toasts = convertedObjects.Take(3) }); - } - - private object ToExpandoObject(Notification notification) - { - return new {Subject = notification.Subject, Body = notification.Body}; - } - + private object ToExpandoObject(Notification notification) + { + return new { Subject = notification.Subject, Body = notification.Body }; + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs index 11f1a0e8ce7..a827d8c7582 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs @@ -1,153 +1,157 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Globalization; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System.Globalization; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + [DnnAuthorize] [DnnPageEditor] public class PageServiceController : DnnApiController { private int? _portalId; + protected int PortalId { get { - if (!_portalId.HasValue) + if (!this._portalId.HasValue) { - _portalId = PortalSettings.ActiveTab.IsSuperTab ? -1 : PortalSettings.PortalId; + this._portalId = this.PortalSettings.ActiveTab.IsSuperTab ? -1 : this.PortalSettings.PortalId; } - return _portalId.Value; + + return this._portalId.Value; } } - - + [HttpPost] [ValidateAntiForgeryToken] [DnnPagePermission] public HttpResponseMessage PublishPage(PublishPageDto dto) { - var tabId = Request.FindTabId(); - - TabPublishingController.Instance.SetTabPublishing(tabId, PortalId, dto.Publish); - - return Request.CreateResponse(HttpStatusCode.OK); + var tabId = this.Request.FindTabId(); + + TabPublishingController.Instance.SetTabPublishing(tabId, this.PortalId, dto.Publish); + + return this.Request.CreateResponse(HttpStatusCode.OK); } - + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage UpdateCustomUrl(SaveUrlDto dto) { var urlPath = dto.Path.ValueOrEmpty().TrimStart('/'); bool modified; - //Clean Url - var options = UrlRewriterUtils.ExtendOptionsForCustomURLs( UrlRewriterUtils.GetOptionsFromSettings(new FriendlyUrlSettings(PortalSettings.PortalId)) ); - - //now clean the path + + // Clean Url + var options = UrlRewriterUtils.ExtendOptionsForCustomURLs(UrlRewriterUtils.GetOptionsFromSettings(new FriendlyUrlSettings(this.PortalSettings.PortalId))); + + // now clean the path urlPath = FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); if (modified) { - return Request.CreateResponse(HttpStatusCode.OK, + return this.Request.CreateResponse( + HttpStatusCode.OK, new { Success = false, ErrorMessage = Localization.GetString("CustomUrlPathCleaned.Error", Localization.GlobalResourceFile), - SuggestedUrlPath = "/" + urlPath + SuggestedUrlPath = "/" + urlPath, }); } - //Validate for uniqueness - urlPath = FriendlyUrlController.ValidateUrl(urlPath, -1, PortalSettings, out modified); + // Validate for uniqueness + urlPath = FriendlyUrlController.ValidateUrl(urlPath, -1, this.PortalSettings, out modified); if (modified) { - return Request.CreateResponse(HttpStatusCode.OK, + return this.Request.CreateResponse( + HttpStatusCode.OK, new { Success = false, ErrorMessage = Localization.GetString("UrlPathNotUnique.Error", Localization.GlobalResourceFile), - SuggestedUrlPath = "/" + urlPath + SuggestedUrlPath = "/" + urlPath, }); } - var tab = PortalSettings.ActiveTab; - var cultureCode = LocaleController.Instance.GetLocales(PortalId) + var tab = this.PortalSettings.ActiveTab; + var cultureCode = LocaleController.Instance.GetLocales(this.PortalId) .Where(l => l.Value.KeyID == dto.LocaleKey) .Select(l => l.Value.Code) .SingleOrDefault(); if (dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture) == "200") { - //We need to check if we are updating a current url or creating a new 200 + // We need to check if we are updating a current url or creating a new 200 var tabUrl = tab.TabUrls.SingleOrDefault(t => t.SeqNum == dto.Id && t.HttpStatus == "200"); if (tabUrl == null) { - //Just create Url - tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = dto.Id, - PortalAliasId = dto.SiteAliasKey, - PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, - QueryString = dto.QueryString.ValueOrEmpty(), - Url = dto.Path.ValueOrEmpty(), - CultureCode = cultureCode, - HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), - IsSystem = dto.IsSystem // false - }; - TabController.Instance.SaveTabUrl(tabUrl, PortalId, true); + // Just create Url + tabUrl = new TabUrlInfo + { + TabId = tab.TabID, + SeqNum = dto.Id, + PortalAliasId = dto.SiteAliasKey, + PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, + QueryString = dto.QueryString.ValueOrEmpty(), + Url = dto.Path.ValueOrEmpty(), + CultureCode = cultureCode, + HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), + IsSystem = dto.IsSystem, // false + }; + TabController.Instance.SaveTabUrl(tabUrl, this.PortalId, true); } else { - //Change the original 200 url to a redirect + // Change the original 200 url to a redirect tabUrl.HttpStatus = "301"; tabUrl.SeqNum = dto.Id; - TabController.Instance.SaveTabUrl(tabUrl, PortalId, true); + TabController.Instance.SaveTabUrl(tabUrl, this.PortalId, true); - //Add new custom url + // Add new custom url tabUrl.Url = dto.Path.ValueOrEmpty(); tabUrl.HttpStatus = "200"; tabUrl.SeqNum = tab.TabUrls.Max(t => t.SeqNum) + 1; - TabController.Instance.SaveTabUrl(tabUrl, PortalId, true); + TabController.Instance.SaveTabUrl(tabUrl, this.PortalId, true); } } else { - //Just update the url - var tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = dto.Id, - PortalAliasId = dto.SiteAliasKey, - PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, - QueryString = dto.QueryString.ValueOrEmpty(), - Url = dto.Path.ValueOrEmpty(), - CultureCode = cultureCode, - HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), - IsSystem = dto.IsSystem // false - }; - TabController.Instance.SaveTabUrl(tabUrl, PortalId, true); + // Just update the url + var tabUrl = new TabUrlInfo + { + TabId = tab.TabID, + SeqNum = dto.Id, + PortalAliasId = dto.SiteAliasKey, + PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, + QueryString = dto.QueryString.ValueOrEmpty(), + Url = dto.Path.ValueOrEmpty(), + CultureCode = cultureCode, + HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), + IsSystem = dto.IsSystem, // false + }; + TabController.Instance.SaveTabUrl(tabUrl, this.PortalId, true); } - - + var response = new { Success = true, }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs index d1231111934..18a6b9463eb 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs @@ -1,40 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web; -using System.Web.Http; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Api; -using DotNetNuke.Services.Registration; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.InternalServices { + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Registration; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class ProfileServiceController : DnnApiController { [HttpGet] public HttpResponseMessage Search(string q) { - var results = RegistrationProfileController.Instance.Search(PortalController.GetEffectivePortalId(PortalSettings.PortalId), q); - return Request.CreateResponse(HttpStatusCode.OK, - results.OrderBy(sr => sr) - .Select(field => new { id = field, name = field }) - ); + var results = RegistrationProfileController.Instance.Search(PortalController.GetEffectivePortalId(this.PortalSettings.PortalId), q); + return this.Request.CreateResponse( + HttpStatusCode.OK, + results.OrderBy(sr => sr) + .Select(field => new { id = field, name = field })); } [HttpPost] @@ -43,51 +39,47 @@ public HttpResponseMessage UpdateVanityUrl(VanityUrlDTO vanityUrl) { bool modified; - //Clean Url - var options = UrlRewriterUtils.GetOptionsFromSettings(new FriendlyUrlSettings(PortalSettings.PortalId)); + // Clean Url + var options = UrlRewriterUtils.GetOptionsFromSettings(new FriendlyUrlSettings(this.PortalSettings.PortalId)); var cleanUrl = FriendlyUrlController.CleanNameForUrl(vanityUrl.Url, options, out modified); - - + if (modified) { - return Request.CreateResponse(HttpStatusCode.OK, - new { - Result = "warning", - Title = Localization.GetString("CleanWarningTitle", Localization.SharedResourceFile), - Message = Localization.GetString("ProfileUrlCleaned", Localization.SharedResourceFile), - SuggestedUrl = cleanUrl - }); + return this.Request.CreateResponse( + HttpStatusCode.OK, + new + { + Result = "warning", + Title = Localization.GetString("CleanWarningTitle", Localization.SharedResourceFile), + Message = Localization.GetString("ProfileUrlCleaned", Localization.SharedResourceFile), + SuggestedUrl = cleanUrl, + }); } - //Validate for uniqueness - var uniqueUrl = FriendlyUrlController.ValidateUrl(cleanUrl, -1, PortalSettings, out modified); - - + // Validate for uniqueness + var uniqueUrl = FriendlyUrlController.ValidateUrl(cleanUrl, -1, this.PortalSettings, out modified); + if (modified) { - return Request.CreateResponse(HttpStatusCode.OK, - new - { - Result = "warning", - Title = Localization.GetString("DuplicateUrlWarningTitle", Localization.SharedResourceFile), - Message = Localization.GetString("ProfileUrlNotUnique", Localization.SharedResourceFile), - SuggestedUrl = uniqueUrl - }); + return this.Request.CreateResponse( + HttpStatusCode.OK, + new + { + Result = "warning", + Title = Localization.GetString("DuplicateUrlWarningTitle", Localization.SharedResourceFile), + Message = Localization.GetString("ProfileUrlNotUnique", Localization.SharedResourceFile), + SuggestedUrl = uniqueUrl, + }); } - var user = PortalSettings.UserInfo; + var user = this.PortalSettings.UserInfo; user.VanityUrl = uniqueUrl; - UserController.UpdateUser(PortalSettings.PortalId, user); + UserController.UpdateUser(this.PortalSettings.PortalId, user); - DataCache.RemoveCache(string.Format(CacheController.VanityUrlLookupKey, PortalSettings.PortalId)); + DataCache.RemoveCache(string.Format(CacheController.VanityUrlLookupKey, this.PortalSettings.PortalId)); - //Url is clean and validated so we can update the User - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - public class VanityUrlDTO - { - public string Url { get; set; } + // Url is clean and validated so we can update the User + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } [DnnAuthorize] @@ -97,8 +89,12 @@ public HttpResponseMessage ProfilePropertyValues() string searchString = HttpContext.Current.Request.Params["SearchString"].NormalizeString(); string propertyName = HttpContext.Current.Request.Params["PropName"].NormalizeString(); int portalId = int.Parse(HttpContext.Current.Request.Params["PortalId"]); - return Request.CreateResponse(HttpStatusCode.OK, Entities.Profile.ProfileController.SearchProfilePropertyValues(portalId, propertyName, searchString)); + return this.Request.CreateResponse(HttpStatusCode.OK, Entities.Profile.ProfileController.SearchProfilePropertyValues(portalId, propertyName, searchString)); } + public class VanityUrlDTO + { + public string Url { get; set; } + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs index 22cae824ba7..b7b779ae4f4 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class RelationshipServiceController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (RelationshipServiceController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RelationshipServiceController)); [HttpPost] [ValidateAntiForgeryToken] @@ -29,7 +30,7 @@ public HttpResponseMessage AcceptFriend(NotificationDTO postData) try { - var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID); + var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); if (recipient != null) { var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); @@ -39,7 +40,7 @@ public HttpResponseMessage AcceptFriend(NotificationDTO postData) var userRelationship = RelationshipController.Instance.GetUserRelationship(userRelationshipId); if (userRelationship != null) { - var friend = UserController.GetUserById(PortalSettings.PortalId, userRelationship.UserId); + var friend = UserController.GetUserById(this.PortalSettings.PortalId, userRelationship.UserId); FriendsController.Instance.AcceptFriend(friend); success = true; } @@ -50,16 +51,15 @@ public HttpResponseMessage AcceptFriend(NotificationDTO postData) { Logger.Error(exc); } - - if(success) + + if (success) { - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } - - + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage FollowBack(NotificationDTO postData) @@ -68,27 +68,28 @@ public HttpResponseMessage FollowBack(NotificationDTO postData) try { - var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID); + var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); if (recipient != null) { var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); int targetUserId; if (int.TryParse(notification.Context, out targetUserId)) { - var targetUser = UserController.GetUserById(PortalSettings.PortalId, targetUserId); + var targetUser = UserController.GetUserById(this.PortalSettings.PortalId, targetUserId); if (targetUser == null) { var response = new { - Message = Localization.GetExceptionMessage("UserDoesNotExist", - "The user you are trying to follow no longer exists.") + Message = Localization.GetExceptionMessage( + "UserDoesNotExist", + "The user you are trying to follow no longer exists."), }; - return Request.CreateResponse(HttpStatusCode.InternalServerError, response); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError, response); } FollowersController.Instance.FollowUser(targetUser); - NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, UserInfo.UserID); + NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, this.UserInfo.UserID); success = true; } @@ -99,23 +100,24 @@ public HttpResponseMessage FollowBack(NotificationDTO postData) Logger.Error(exc); var response = new { - Message = Localization.GetExceptionMessage("AlreadyFollowingUser", - "You are already following this user.") + Message = Localization.GetExceptionMessage( + "AlreadyFollowingUser", + "You are already following this user."), }; - return Request.CreateResponse(HttpStatusCode.InternalServerError, response); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError, response); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc.Message); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc.Message); } if (success) { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs index 35fa23dff01..0cd24fb0512 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs @@ -1,75 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Caching; -using System.Web.Http; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Search.Controllers; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.InternalServices.Views.Search; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Caching; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.InternalServices.Views.Search; + [DnnAuthorize(StaticRoles = "Administrators")] public class SearchServiceController : DnnApiController { + private const string ModuleInfosCacheKey = "ModuleInfos{0}"; + private const CacheItemPriority ModuleInfosCachePriority = CacheItemPriority.AboveNormal; + private const int ModuleInfosCacheTimeOut = 20; + private static readonly Regex GroupedBasicViewRegex = new Regex("userid(/|\\|=)(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - public class SynonymsGroupDto - { - public int Id { get; set; } - public string Tags { get; set; } - public int PortalId { get; set; } - public string Culture { get; set; } - } - - public class StopWordsDto - { - public int Id { get; set; } - public string Words { get; set; } - public int PortalId { get; set; } - public string Culture { get; set; } - } + + private int HtmlModuleDefitionId; public SearchServiceController() { var modDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Text/HTML"); - HtmlModuleDefitionId = modDef != null ? modDef.ModuleDefID : -1; + this.HtmlModuleDefitionId = modDef != null ? modDef.ModuleDefID : -1; } - //this constructor is for unit tests - internal SearchServiceController(int htmlModuleDefitionId)//, TabController newtabController, ModuleController newmoduleController) + // this constructor is for unit tests + internal SearchServiceController(int htmlModuleDefitionId) // , TabController newtabController, ModuleController newmoduleController) { - HtmlModuleDefitionId = htmlModuleDefitionId; - //_tabController = newtabController; - //_moduleController = newmoduleController; - } - - #region private methods - - private int HtmlModuleDefitionId; + this.HtmlModuleDefitionId = htmlModuleDefitionId; + + // _tabController = newtabController; + // _moduleController = newmoduleController; + } private bool IsWildCardEnabledForModule() { - var searchModuleSettings = GetSearchModuleSettings(); + var searchModuleSettings = this.GetSearchModuleSettings(); var enableWildSearch = true; if (!string.IsNullOrEmpty(Convert.ToString(searchModuleSettings["EnableWildSearch"]))) { @@ -77,182 +64,35 @@ private bool IsWildCardEnabledForModule() } return enableWildSearch; - } - - #region Loads Search portal ids, crawler ids and module def ids - - private const string ModuleInfosCacheKey = "ModuleInfos{0}"; - private const CacheItemPriority ModuleInfosCachePriority = CacheItemPriority.AboveNormal; - private const int ModuleInfosCacheTimeOut = 20; + } - private static ArrayList GetModulesByDefinition(int portalID, string friendlyName) - { - var cacheKey = string.Format(ModuleInfosCacheKey, portalID); - return CBO.GetCachedObject( - new CacheItemArgs(cacheKey, ModuleInfosCacheTimeOut, ModuleInfosCachePriority), - args => CBO.FillCollection(DataProvider.Instance().GetModuleByDefinition(portalID, friendlyName), typeof(ModuleInfo))); - } - - private ModuleInfo GetSearchModule() - { - var arrModules = GetModulesByDefinition(PortalSettings.PortalId, "Search Results"); - ModuleInfo findModule = null; - if (arrModules.Count > 1) - { - findModule = arrModules.Cast().FirstOrDefault(searchModule => searchModule.CultureCode == PortalSettings.CultureCode); - } - - return findModule ?? (arrModules.Count > 0 ? (ModuleInfo)arrModules[0] : null); - } - - private Hashtable GetSearchModuleSettings() - { - if (ActiveModule != null && ActiveModule.ModuleDefinition.FriendlyName == "Search Results") - { - return ActiveModule.ModuleSettings; - } - - var searchModule = GetSearchModule(); - return searchModule != null ? searchModule.ModuleSettings : null; - } - - private bool GetBooleanSetting(string settingName, bool defaultValue) - { - if (PortalSettings == null) - { - return defaultValue; - } - - var settings = GetSearchModuleSettings(); - if (settings == null || !settings.ContainsKey(settingName)) - { - return defaultValue; - } - - return Convert.ToBoolean(settings[settingName]); - } - - private int GetIntegerSetting(string settingName, int defaultValue) - { - if (PortalSettings == null) - { - return defaultValue; - } - - var settings = GetSearchModuleSettings(); - if (settings == null || !settings.ContainsKey(settingName)) - { - return defaultValue; - } - - var settingValue = Convert.ToString(settings[settingName]); - if (!string.IsNullOrEmpty(settingValue) && Regex.IsMatch(settingValue, "^\\d+$")) - { - return Convert.ToInt32(settingValue); - } - - return defaultValue; - } - - private List GetSearchPortalIds(IDictionary settings, int portalId) - { - var list = new List(); - if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForPortals"]))) - { - list = Convert.ToString(settings["ScopeForPortals"]).Split('|').Select(s => Convert.ToInt32(s)).ToList(); - } - - if (portalId == -1) portalId = PortalSettings.ActiveTab.PortalID; - if (portalId > -1 && !list.Contains(portalId)) list.Add(portalId); - - //Add Host - var userInfo = UserInfo; - if (userInfo.IsSuperUser) - list.Add(-1); - - return list; - } - - private static List GetSearchTypeIds(IDictionary settings, IEnumerable searchContentSources) - { - var list = new List(); - var configuredList = new List(); - if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) - { - configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); - } - - // check content source in configured list or not - foreach (var contentSource in searchContentSources) - { - if (contentSource.IsPrivate) continue; - if (configuredList.Count > 0) - { - if (configuredList.Any(l => l.Contains(contentSource.LocalizedName))) // in configured list - list.Add(contentSource.SearchTypeId); - } - else - { - list.Add(contentSource.SearchTypeId); - } - } - - return list.Distinct().ToList(); - } - - private static IEnumerable GetSearchModuleDefIds(IDictionary settings, IEnumerable searchContentSources) + public class SynonymsGroupDto { - var list = new List(); - var configuredList = new List(); - if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) - { - configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); - } - - // check content source in configured list or not - foreach (var contentSource in searchContentSources) - { - if (contentSource.IsPrivate) continue; ; - if (configuredList.Count > 0) - { - if (configuredList.Any(l => l.Contains(contentSource.LocalizedName)) && contentSource.ModuleDefinitionId > 0) // in configured list - list.Add(contentSource.ModuleDefinitionId); - } - else - { - if (contentSource.ModuleDefinitionId > 0) - list.Add(contentSource.ModuleDefinitionId); - } - } - - return list; + public int Id { get; set; } + + public string Tags { get; set; } + + public int PortalId { get; set; } + + public string Culture { get; set; } } - private IList GetSearchContentSources(IList typesList) + public class StopWordsDto { - var sources = new List(); - var list = InternalSearchController.Instance.GetSearchContentSourceList(PortalSettings.PortalId); - - if (typesList.Any()) - { - foreach (var contentSources in typesList.Select(t1 => list.Where(src => string.Equals(src.LocalizedName, t1, StringComparison.OrdinalIgnoreCase)))) - { - sources.AddRange(contentSources); - } - } - else - { - // no types fitler specified, add all available content sources - sources.AddRange(list); - } - - return sources; + public int Id { get; set; } + + public string Words { get; set; } + + public int PortalId { get; set; } + + public string Culture { get; set; } } - #endregion - - #region view models for search results - internal IEnumerable GetGroupedDetailViews(SearchQuery searchQuery, int userSearchTypeId, out int totalHits, out bool more) + private const string ModuleTitleCacheKey = "SearchModuleTabTitle_{0}"; + private const CacheItemPriority ModuleTitleCachePriority = CacheItemPriority.Normal; + private const int ModuleTitleCacheTimeOut = 20; + + internal IEnumerable GetGroupedDetailViews(SearchQuery searchQuery, int userSearchTypeId, out int totalHits, out bool more) { var searchResults = SearchController.Instance.SiteSearch(searchQuery); totalHits = searchResults.TotalHits; @@ -260,10 +100,10 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search var groups = new List(); var tabGroups = new Dictionary>(); - + foreach (var result in searchResults.Results) { - //var key = result.TabId + result.Url; + // var key = result.TabId + result.Url; var key = result.Url; if (!tabGroups.ContainsKey(key)) { @@ -271,7 +111,7 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search } else { - //when the result is a user search type, we should only show one result + // when the result is a user search type, we should only show one result // and if duplicate, we should also reduce the totalHit number. if (result.SearchTypeId != userSearchTypeId || tabGroups[key].All(r => r.Url != result.Url)) @@ -285,51 +125,56 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search } } - var showFriendlyTitle = ActiveModule == null - || !ActiveModule.ModuleSettings.ContainsKey("ShowFriendlyTitle") - || Convert.ToBoolean(ActiveModule.ModuleSettings["ShowFriendlyTitle"]); + var showFriendlyTitle = this.ActiveModule == null + || !this.ActiveModule.ModuleSettings.ContainsKey("ShowFriendlyTitle") + || Convert.ToBoolean(this.ActiveModule.ModuleSettings["ShowFriendlyTitle"]); foreach (var results in tabGroups.Values) { var group = new GroupedDetailView(); - //first entry + // first entry var first = results[0]; - group.Title = showFriendlyTitle ? GetFriendlyTitle(first) : first.Title; + group.Title = showFriendlyTitle ? this.GetFriendlyTitle(first) : first.Title; group.DocumentUrl = first.Url; - //Find a different title for multiple entries with same url + // Find a different title for multiple entries with same url if (results.Count > 1) { if (first.TabId > 0) { var tab = TabController.Instance.GetTab(first.TabId, first.PortalId, false); - if (tab != null) - group.Title = showFriendlyTitle && !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; + if (tab != null) + { + group.Title = showFriendlyTitle && !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; + } } else if (first.ModuleId > 0) { - var tabTitle = GetTabTitleFromModuleId(first.ModuleId); + var tabTitle = this.GetTabTitleFromModuleId(first.ModuleId); if (!string.IsNullOrEmpty(tabTitle)) { group.Title = tabTitle; } } } - else if (first.ModuleDefId > 0 && first.ModuleDefId == HtmlModuleDefitionId) //special handling for Html module + else if (first.ModuleDefId > 0 && first.ModuleDefId == this.HtmlModuleDefitionId) // special handling for Html module { - var tabTitle = GetTabTitleFromModuleId(first.ModuleId); + var tabTitle = this.GetTabTitleFromModuleId(first.ModuleId); if (!string.IsNullOrEmpty(tabTitle)) { group.Title = tabTitle; - if (first.Title != "Enter Title" && first.Title != "Text/HTML") - group.Title += " > " + first.Title; + if (first.Title != "Enter Title" && first.Title != "Text/HTML") + { + group.Title += " > " + first.Title; + } + first.Title = group.Title; } } foreach (var result in results) { - var title = showFriendlyTitle ? GetFriendlyTitle(result) : result.Title; + var title = showFriendlyTitle ? this.GetFriendlyTitle(result) : result.Title; var detail = new DetailedView { Title = title != null && title.Contains("<") ? HttpUtility.HtmlEncode(title) : title, @@ -340,7 +185,7 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search DisplayModifiedTime = result.DisplayModifiedTime, Tags = result.Tags.ToList(), AuthorProfileUrl = result.AuthorUserId > 0 ? Globals.UserProfileURL(result.AuthorUserId) : string.Empty, - AuthorName = result.AuthorName + AuthorName = result.AuthorName, }; group.Results.Add(detail); } @@ -351,32 +196,22 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search return groups; } - private string GetFriendlyTitle(SearchResult result) - { - if (result.Keywords.ContainsKey("title") && !string.IsNullOrEmpty(result.Keywords["title"])) - { - return result.Keywords["title"]; - } - - return result.Title; - } - internal List GetGroupedBasicViews(SearchQuery query, SearchContentSource userSearchSource, int portalId) { int totalHists; var results = new List(); - var previews = GetBasicViews(query, out totalHists); + var previews = this.GetBasicViews(query, out totalHists); foreach (var preview in previews) { - //if the document type is user, then try to add user pic into preview's custom attributes. + // if the document type is user, then try to add user pic into preview's custom attributes. if (userSearchSource != null && preview.DocumentTypeName == userSearchSource.LocalizedName) { var match = GroupedBasicViewRegex.Match(preview.DocumentUrl); if (match.Success) { var userid = Convert.ToInt32(match.Groups[2].Value); - var user = UserController.Instance.GetUserById(portalId, userid); + var user = UserController.Instance.GetUserById(portalId, userid); if (user != null) { preview.Attributes.Add("Avatar", user.Profile.PhotoURL); @@ -387,15 +222,17 @@ internal List GetGroupedBasicViews(SearchQuery query, SearchCo var groupedResult = results.SingleOrDefault(g => g.DocumentTypeName == preview.DocumentTypeName); if (groupedResult != null) { - if (!groupedResult.Results.Any(r => string.Equals(r.DocumentUrl, preview.DocumentUrl))) + if (!groupedResult.Results.Any(r => string.Equals(r.DocumentUrl, preview.DocumentUrl))) + { groupedResult.Results.Add(new BasicView { Title = preview.Title.Contains("<") ? HttpUtility.HtmlEncode(preview.Title) : preview.Title, Snippet = preview.Snippet, Description = preview.Description, DocumentUrl = preview.DocumentUrl, - Attributes = preview.Attributes - }); + Attributes = preview.Attributes, + }); + } } else { @@ -410,10 +247,10 @@ internal IEnumerable GetBasicViews(SearchQuery searchQuery, out int t { var sResult = SearchController.Instance.SiteSearch(searchQuery); totalHits = sResult.TotalHits; - var showFriendlyTitle = GetBooleanSetting("ShowFriendlyTitle", true); - var showDescription = GetBooleanSetting("ShowDescription", true); - var showSnippet = GetBooleanSetting("ShowSnippet", true); - var maxDescriptionLength = GetIntegerSetting("MaxDescriptionLength", 100); + var showFriendlyTitle = this.GetBooleanSetting("ShowFriendlyTitle", true); + var showDescription = this.GetBooleanSetting("ShowDescription", true); + var showSnippet = this.GetBooleanSetting("ShowSnippet", true); + var maxDescriptionLength = this.GetIntegerSetting("MaxDescriptionLength", 100); return sResult.Results.Select(result => { @@ -425,61 +262,231 @@ internal IEnumerable GetBasicViews(SearchQuery searchQuery, out int t return new BasicView { - Title = GetTitle(result, showFriendlyTitle), + Title = this.GetTitle(result, showFriendlyTitle), DocumentTypeName = InternalSearchController.Instance.GetSearchDocumentTypeDisplayName(result), DocumentUrl = result.Url, Snippet = showSnippet ? result.Snippet : string.Empty, - Description = showDescription ? description : string.Empty + Description = showDescription ? description : string.Empty, }; }); } - private string GetTitle(SearchResult result, bool showFriendlyTitle = false) + private static ArrayList GetModulesByDefinition(int portalID, string friendlyName) { - if (result.ModuleDefId > 0 && result.ModuleDefId == HtmlModuleDefitionId) //special handling for Html module + var cacheKey = string.Format(ModuleInfosCacheKey, portalID); + return CBO.GetCachedObject( + new CacheItemArgs(cacheKey, ModuleInfosCacheTimeOut, ModuleInfosCachePriority), + args => CBO.FillCollection(DataProvider.Instance().GetModuleByDefinition(portalID, friendlyName), typeof(ModuleInfo))); + } + + private static List GetSearchTypeIds(IDictionary settings, IEnumerable searchContentSources) + { + var list = new List(); + var configuredList = new List(); + if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) { - var tabTitle = GetTabTitleFromModuleId(result.ModuleId); - if (!string.IsNullOrEmpty(tabTitle)) + configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); + } + + // check content source in configured list or not + foreach (var contentSource in searchContentSources) + { + if (contentSource.IsPrivate) + { + continue; + } + + if (configuredList.Count > 0) { - if (result.Title != "Enter Title" && result.Title != "Text/HTML") - return tabTitle + " > " + result.Title; - return tabTitle; + if (configuredList.Any(l => l.Contains(contentSource.LocalizedName))) // in configured list + { + list.Add(contentSource.SearchTypeId); + } + } + else + { + list.Add(contentSource.SearchTypeId); } } - return showFriendlyTitle ? GetFriendlyTitle(result) : result.Title; + return list.Distinct().ToList(); } - private const string ModuleTitleCacheKey = "SearchModuleTabTitle_{0}"; - private const CacheItemPriority ModuleTitleCachePriority = CacheItemPriority.Normal; - private const int ModuleTitleCacheTimeOut = 20; + private static IEnumerable GetSearchModuleDefIds(IDictionary settings, IEnumerable searchContentSources) + { + var list = new List(); + var configuredList = new List(); + if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) + { + configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); + } - private string GetTabTitleFromModuleId(int moduleId) + // check content source in configured list or not + foreach (var contentSource in searchContentSources) + { + if (contentSource.IsPrivate) + { + continue; + } + + if (configuredList.Count > 0) + { + if (configuredList.Any(l => l.Contains(contentSource.LocalizedName)) && contentSource.ModuleDefinitionId > 0) // in configured list + { + list.Add(contentSource.ModuleDefinitionId); + } + } + else + { + if (contentSource.ModuleDefinitionId > 0) + { + list.Add(contentSource.ModuleDefinitionId); + } + } + } + + return list; + } + + private ModuleInfo GetSearchModule() { - // no manual clearing of the cache exists; let is just expire - var cacheKey = string.Format(ModuleTitleCacheKey, moduleId); + var arrModules = GetModulesByDefinition(this.PortalSettings.PortalId, "Search Results"); + ModuleInfo findModule = null; + if (arrModules.Count > 1) + { + findModule = arrModules.Cast().FirstOrDefault(searchModule => searchModule.CultureCode == this.PortalSettings.CultureCode); + } - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, ModuleTitleCacheTimeOut, ModuleTitleCachePriority, moduleId), GetTabTitleCallBack); + return findModule ?? (arrModules.Count > 0 ? (ModuleInfo)arrModules[0] : null); } - private object GetTabTitleCallBack(CacheItemArgs cacheItemArgs) + private Hashtable GetSearchModuleSettings() { - var moduleId = (int)cacheItemArgs.ParamList[0]; - var moduleInfo = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - if (moduleInfo != null) + if (this.ActiveModule != null && this.ActiveModule.ModuleDefinition.FriendlyName == "Search Results") { - var tab = moduleInfo.ParentTab; + return this.ActiveModule.ModuleSettings; + } - return !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; + var searchModule = this.GetSearchModule(); + return searchModule != null ? searchModule.ModuleSettings : null; + } + + private bool GetBooleanSetting(string settingName, bool defaultValue) + { + if (this.PortalSettings == null) + { + return defaultValue; } - return string.Empty; + var settings = this.GetSearchModuleSettings(); + if (settings == null || !settings.ContainsKey(settingName)) + { + return defaultValue; + } + + return Convert.ToBoolean(settings[settingName]); + } + + private int GetIntegerSetting(string settingName, int defaultValue) + { + if (this.PortalSettings == null) + { + return defaultValue; + } + + var settings = this.GetSearchModuleSettings(); + if (settings == null || !settings.ContainsKey(settingName)) + { + return defaultValue; + } + + var settingValue = Convert.ToString(settings[settingName]); + if (!string.IsNullOrEmpty(settingValue) && Regex.IsMatch(settingValue, "^\\d+$")) + { + return Convert.ToInt32(settingValue); + } + + return defaultValue; + } + + private List GetSearchPortalIds(IDictionary settings, int portalId) + { + var list = new List(); + if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForPortals"]))) + { + list = Convert.ToString(settings["ScopeForPortals"]).Split('|').Select(s => Convert.ToInt32(s)).ToList(); + } + + if (portalId == -1) + { + portalId = this.PortalSettings.ActiveTab.PortalID; + } + + if (portalId > -1 && !list.Contains(portalId)) + { + list.Add(portalId); + } + + // Add Host + var userInfo = this.UserInfo; + if (userInfo.IsSuperUser) + { + list.Add(-1); + } + + return list; } - #endregion + private IList GetSearchContentSources(IList typesList) + { + var sources = new List(); + var list = InternalSearchController.Instance.GetSearchContentSourceList(this.PortalSettings.PortalId); + + if (typesList.Any()) + { + foreach (var contentSources in typesList.Select(t1 => list.Where(src => string.Equals(src.LocalizedName, t1, StringComparison.OrdinalIgnoreCase)))) + { + sources.AddRange(contentSources); + } + } + else + { + // no types fitler specified, add all available content sources + sources.AddRange(list); + } + + return sources; + } + + private string GetFriendlyTitle(SearchResult result) + { + if (result.Keywords.ContainsKey("title") && !string.IsNullOrEmpty(result.Keywords["title"])) + { + return result.Keywords["title"]; + } + + return result.Title; + } - #endregion + private string GetTitle(SearchResult result, bool showFriendlyTitle = false) + { + if (result.ModuleDefId > 0 && result.ModuleDefId == this.HtmlModuleDefitionId) // special handling for Html module + { + var tabTitle = this.GetTabTitleFromModuleId(result.ModuleId); + if (!string.IsNullOrEmpty(tabTitle)) + { + if (result.Title != "Enter Title" && result.Title != "Text/HTML") + { + return tabTitle + " > " + result.Title; + } + + return tabTitle; + } + } + return showFriendlyTitle ? this.GetFriendlyTitle(result) : result.Title; + } + [HttpGet] [AllowAnonymous] public HttpResponseMessage Preview(string keywords, string culture, int forceWild = 1, int portal = -1) @@ -489,12 +496,12 @@ public HttpResponseMessage Preview(string keywords, string culture, int forceWil var tags = SearchQueryStringParser.Instance.GetTags(keywords, out cleanedKeywords); var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords); var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out cleanedKeywords); - - var contentSources = GetSearchContentSources(searchTypes); - var settings = GetSearchModuleSettings(); + + var contentSources = this.GetSearchContentSources(searchTypes); + var settings = this.GetSearchModuleSettings(); var searchTypeIds = GetSearchTypeIds(settings, contentSources); var moduleDefids = GetSearchModuleDefIds(settings, contentSources); - var portalIds = GetSearchPortalIds(settings, portal); + var portalIds = this.GetSearchPortalIds(settings, portal); var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; var userSearchSource = contentSources.FirstOrDefault(s => s.SearchTypeId == userSearchTypeId); @@ -516,12 +523,12 @@ public HttpResponseMessage Preview(string keywords, string culture, int forceWil TitleSnippetLength = 40, BodySnippetLength = 100, CultureCode = culture, - WildCardSearch = forceWild > 0 + WildCardSearch = forceWild > 0, }; try { - results = GetGroupedBasicViews(query, userSearchSource, PortalSettings.PortalId); + results = this.GetGroupedBasicViews(query, userSearchSource, this.PortalSettings.PortalId); } catch (Exception ex) { @@ -529,7 +536,7 @@ public HttpResponseMessage Preview(string keywords, string culture, int forceWil } } - return Request.CreateResponse(HttpStatusCode.OK, results); + return this.Request.CreateResponse(HttpStatusCode.OK, results); } [HttpGet] @@ -542,40 +549,40 @@ public HttpResponseMessage Search(string search, string culture, int pageIndex, var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords); var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(cleanedKeywords, out cleanedKeywords); - var contentSources = GetSearchContentSources(searchTypes); - var settings = GetSearchModuleSettings(); + var contentSources = this.GetSearchContentSources(searchTypes); + var settings = this.GetSearchModuleSettings(); var searchTypeIds = GetSearchTypeIds(settings, contentSources); var moduleDefids = GetSearchModuleDefIds(settings, contentSources); - var portalIds = GetSearchPortalIds(settings, -1); + var portalIds = this.GetSearchPortalIds(settings, -1); var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; var more = false; var totalHits = 0; var results = new List(); - if (portalIds.Any() && searchTypeIds.Any() && + if (portalIds.Any() && searchTypeIds.Any() && (!string.IsNullOrEmpty(cleanedKeywords) || tags.Any())) { - var query = new SearchQuery - { - KeyWords = cleanedKeywords, - Tags = tags, - PortalIds = portalIds, - SearchTypeIds = searchTypeIds, - ModuleDefIds = moduleDefids, - BeginModifiedTimeUtc = beginModifiedTimeUtc, - EndModifiedTimeUtc = beginModifiedTimeUtc > DateTime.MinValue ? DateTime.MaxValue : DateTime.MinValue, - PageIndex = pageIndex, - PageSize = pageSize, - SortField = (SortFields) sortOption, - TitleSnippetLength = 120, - BodySnippetLength = 300, - CultureCode = culture, - WildCardSearch = IsWildCardEnabledForModule() - }; + var query = new SearchQuery + { + KeyWords = cleanedKeywords, + Tags = tags, + PortalIds = portalIds, + SearchTypeIds = searchTypeIds, + ModuleDefIds = moduleDefids, + BeginModifiedTimeUtc = beginModifiedTimeUtc, + EndModifiedTimeUtc = beginModifiedTimeUtc > DateTime.MinValue ? DateTime.MaxValue : DateTime.MinValue, + PageIndex = pageIndex, + PageSize = pageSize, + SortField = (SortFields)sortOption, + TitleSnippetLength = 120, + BodySnippetLength = 300, + CultureCode = culture, + WildCardSearch = this.IsWildCardEnabledForModule(), + }; try { - results = GetGroupedDetailViews(query, userSearchTypeId, out totalHits, out more).ToList(); + results = this.GetGroupedDetailViews(query, userSearchTypeId, out totalHits, out more).ToList(); } catch (Exception ex) { @@ -583,9 +590,31 @@ public HttpResponseMessage Search(string search, string culture, int pageIndex, } } - return Request.CreateResponse(HttpStatusCode.OK, new { results, totalHits, more }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { results, totalHits, more }); + } + + private string GetTabTitleFromModuleId(int moduleId) + { + // no manual clearing of the cache exists; let is just expire + var cacheKey = string.Format(ModuleTitleCacheKey, moduleId); + + return CBO.GetCachedObject(new CacheItemArgs(cacheKey, ModuleTitleCacheTimeOut, ModuleTitleCachePriority, moduleId), this.GetTabTitleCallBack); } - + + private object GetTabTitleCallBack(CacheItemArgs cacheItemArgs) + { + var moduleId = (int)cacheItemArgs.ParamList[0]; + var moduleInfo = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); + if (moduleInfo != null) + { + var tab = moduleInfo.ParentTab; + + return !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; + } + + return string.Empty; + } + [HttpPost] [ValidateAntiForgeryToken] [SupportedModules("SearchAdmin")] @@ -593,7 +622,7 @@ public HttpResponseMessage AddSynonymsGroup(SynonymsGroupDto synonymsGroup) { string duplicateWord; var synonymsGroupId = SearchHelper.Instance.AddSynonymsGroup(synonymsGroup.Tags, synonymsGroup.PortalId, synonymsGroup.Culture, out duplicateWord); - return Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); } [HttpPost] @@ -603,7 +632,7 @@ public HttpResponseMessage UpdateSynonymsGroup(SynonymsGroupDto synonymsGroup) { string duplicateWord; var synonymsGroupId = SearchHelper.Instance.UpdateSynonymsGroup(synonymsGroup.Id, synonymsGroup.Tags, synonymsGroup.PortalId, synonymsGroup.Culture, out duplicateWord); - return Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); } [HttpPost] @@ -612,17 +641,16 @@ public HttpResponseMessage UpdateSynonymsGroup(SynonymsGroupDto synonymsGroup) public HttpResponseMessage DeleteSynonymsGroup(SynonymsGroupDto synonymsGroup) { SearchHelper.Instance.DeleteSynonymsGroup(synonymsGroup.Id, synonymsGroup.PortalId, synonymsGroup.Culture); - return Request.CreateResponse(HttpStatusCode.OK); + return this.Request.CreateResponse(HttpStatusCode.OK); } - - + [HttpPost] [ValidateAntiForgeryToken] [SupportedModules("SearchAdmin")] public HttpResponseMessage AddStopWords(StopWordsDto stopWords) { var stopWordsId = SearchHelper.Instance.AddSearchStopWords(stopWords.Words, stopWords.PortalId, stopWords.Culture); - return Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); } [HttpPost] @@ -631,7 +659,7 @@ public HttpResponseMessage AddStopWords(StopWordsDto stopWords) public HttpResponseMessage UpdateStopWords(StopWordsDto stopWords) { var stopWordsId = SearchHelper.Instance.UpdateSearchStopWords(stopWords.Id, stopWords.Words, stopWords.PortalId, stopWords.Culture); - return Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); } [HttpPost] @@ -640,8 +668,7 @@ public HttpResponseMessage UpdateStopWords(StopWordsDto stopWords) public HttpResponseMessage DeleteStopWords(StopWordsDto stopWords) { SearchHelper.Instance.DeleteSearchStopWords(stopWords.Id, stopWords.PortalId, stopWords.Culture); - return Request.CreateResponse(HttpStatusCode.OK); + return this.Request.CreateResponse(HttpStatusCode.OK); } - } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs index 86c4230335d..f1817aca1a3 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using DotNetNuke.Web.Api; + public class ServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) { - mapRouteManager.MapHttpRoute("InternalServices", - "default", - "{controller}/{action}", - new[] { "DotNetNuke.Web.InternalServices" }); + mapRouteManager.MapHttpRoute( + "InternalServices", + "default", + "{controller}/{action}", + new[] { "DotNetNuke.Web.InternalServices" }); } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs index 6c81cb076e5..845eba8919a 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs @@ -1,41 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Net; -using System.Web.Http; -using System.Net.Http; -using DotNetNuke.Common; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.InternalServices { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Api; + public class UserFileController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (UserFileController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserFileController)); private readonly IFolderManager _folderManager = FolderManager.Instance; [DnnAuthorize] [HttpGet] public HttpResponseMessage GetItems() { - return GetItems(null); + return this.GetItems(null); } - + [DnnAuthorize] [HttpGet] public HttpResponseMessage GetItems(string fileExtensions) { try { - var userFolder = _folderManager.GetUserFolder(UserInfo); + var userFolder = this._folderManager.GetUserFolder(this.UserInfo); var extensions = new List(); if (!string.IsNullOrEmpty(fileExtensions)) @@ -46,27 +47,48 @@ public HttpResponseMessage GetItems(string fileExtensions) var folderStructure = new Item { - children = GetChildren(userFolder, extensions), + children = this.GetChildren(userFolder, extensions), folder = true, id = userFolder.FolderID, - name = Localization.GetString("UserFolderTitle.Text", Localization.SharedResourceFile) + name = Localization.GetString("UserFolderTitle.Text", Localization.SharedResourceFile), }; - return Request.CreateResponse(HttpStatusCode.OK, new List { folderStructure }); + return this.Request.CreateResponse(HttpStatusCode.OK, new List { folderStructure }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } + private static string GetModifiedTime(DateTime dateTime) + { + return string.Format("{0:MMM} {0:dd}, {0:yyyy} at {0:t}", dateTime); + } + + private static string GetTypeName(IFileInfo file) + { + return file.ContentType == null + ? string.Empty + : (file.ContentType.StartsWith("image/") + ? file.ContentType.Replace("image/", string.Empty) + : (file.Extension != null ? file.Extension.ToLowerInvariant() : string.Empty)); + } + + private static bool IsImageFile(string relativePath) + { + var acceptedExtensions = new List { "jpg", "png", "gif", "jpe", "jpeg", "tiff" }; + var extension = relativePath.Substring(relativePath.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLowerInvariant(); + return acceptedExtensions.Contains(extension); + } + // ReSharper disable LoopCanBeConvertedToQuery private List GetChildren(IFolderInfo folder, ICollection extensions) { var everything = new List(); - var folders = _folderManager.GetFolders(folder); + var folders = this._folderManager.GetFolders(folder); foreach (var currentFolder in folders) { @@ -76,11 +98,11 @@ private List GetChildren(IFolderInfo folder, ICollection extension name = currentFolder.DisplayName ?? currentFolder.FolderName, folder = true, parentId = folder.FolderID, - children = GetChildren(currentFolder, extensions) + children = this.GetChildren(currentFolder, extensions), }); } - var files = _folderManager.GetFiles(folder); + var files = this._folderManager.GetFiles(folder); foreach (var file in files) { @@ -93,10 +115,10 @@ private List GetChildren(IFolderInfo folder, ICollection extension name = file.FileName, folder = false, parentId = file.FolderId, - thumb_url = GetThumbUrl(file), + thumb_url = this.GetThumbUrl(file), type = GetTypeName(file), size = GetFileSize(file.Size), - modified = GetModifiedTime(file.LastModificationTime) + modified = GetModifiedTime(file.LastModificationTime), }); } } @@ -104,13 +126,7 @@ private List GetChildren(IFolderInfo folder, ICollection extension return everything; } - private static string GetModifiedTime(DateTime dateTime) - { - return string.Format("{0:MMM} {0:dd}, {0:yyyy} at {0:t}", dateTime); - } - // ReSharper restore LoopCanBeConvertedToQuery - private string GetThumbUrl(IFileInfo file) { if (IsImageFile(file.RelativePath)) @@ -119,53 +135,48 @@ private string GetThumbUrl(IFileInfo file) } var fileIcon = IconController.IconURL("Ext" + file.Extension, "32x32"); - if (!System.IO.File.Exists(Request.GetHttpContext().Server.MapPath(fileIcon))) + if (!System.IO.File.Exists(this.Request.GetHttpContext().Server.MapPath(fileIcon))) { fileIcon = IconController.IconURL("File", "32x32"); } + return fileIcon; } - private static string GetTypeName(IFileInfo file) - { - return file.ContentType == null - ? string.Empty - : (file.ContentType.StartsWith("image/") - ? file.ContentType.Replace("image/", string.Empty) - : (file.Extension != null ? file.Extension.ToLowerInvariant() : string.Empty)); - } - - private static bool IsImageFile(string relativePath) - { - var acceptedExtensions = new List { "jpg", "png", "gif", "jpe", "jpeg", "tiff" }; - var extension = relativePath.Substring(relativePath.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLowerInvariant(); - return acceptedExtensions.Contains(extension); - } - private static string GetFileSize(int sizeInBytes) { var size = sizeInBytes / 1024; var biggerThanAMegabyte = size > 1024; if (biggerThanAMegabyte) { - size = (size / 1024); + size = size / 1024; } + return size.ToString(CultureInfo.InvariantCulture) + (biggerThanAMegabyte ? "Mb" : "k"); } - class Item + private class Item { // ReSharper disable InconsistentNaming // ReSharper disable UnusedAutoPropertyAccessor.Local public int id { get; set; } + public string name { get; set; } + public bool folder { get; set; } + public int parentId { get; set; } + public string thumb_url { get; set; } + public string type { get; set; } + public string size { get; set; } + public string modified { get; set; } + public List children { get; set; } + // ReSharper restore UnusedAutoPropertyAccessor.Local // ReSharper restore InconsistentNaming } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs index 1ad6b5f3a90..1be0a054e43 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs @@ -1,56 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.InternalServices.Views.Search { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Internals; + /// - /// Detailed Search Result View + /// Detailed Search Result View. /// public class BasicView { + public BasicView() + { + this.Attributes = new Dictionary(); + } + /// - /// Document's Title + /// Gets or sets document's Title. /// public string Title { get; set; } /// - /// Highlighted snippet from document + /// Gets or sets highlighted snippet from document. /// public string Snippet { get; set; } /// - /// Description from document + /// Gets or sets description from document. /// public string Description { get; set; } /// - /// Link to the Document + /// Gets or sets link to the Document. /// public string DocumentUrl { get; set; } /// - /// Display Name of the Document Type + /// Gets or sets display Name of the Document Type. /// public string DocumentTypeName { get; set; } /// - /// Custom Attributes of the document. + /// Gets or sets custom Attributes of the document. /// public IDictionary Attributes { get; set; } - - public BasicView() - { - Attributes = new Dictionary(); - } - } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/DetailedView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/DetailedView.cs index 5c461345c26..809db919555 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/DetailedView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/DetailedView.cs @@ -1,59 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.InternalServices.Views.Search { + using System; + using System.Collections.Generic; + /// - /// Detailed Search Result View + /// Detailed Search Result View. /// public class DetailedView : BasicView { /// - /// Tags associated with Document + /// Gets or sets tags associated with Document. /// public IEnumerable Tags { get; set; } - + /// - /// Time when Content was last modified (in Utc) + /// Gets or sets time when Content was last modified (in Utc). /// - public String DisplayModifiedTime { get; set; } + public string DisplayModifiedTime { get; set; } /// - /// Author profile URL + /// Gets or sets author profile URL. /// public string AuthorProfileUrl { get; set; } /// - /// Optional: Display Name of the Author + /// Gets or sets optional: Display Name of the Author. /// /// This may be different form current Display Name when Index was run prior to change in Display Name. public string AuthorName { get; set; } /// - /// Number of Likes associated with Content. + /// Gets or sets number of Likes associated with Content. /// /// Content with more Likes is ranked higher. public int Likes { get; set; } /// - /// Number of Comments associated with Content. + /// Gets or sets number of Comments associated with Content. /// /// Content with more Comments is ranked higher. public int Comments { get; set; } /// - /// Number of Views associated with Content. + /// Gets or sets number of Views associated with Content. /// /// Content with more Views is ranked higher. public int Views { get; set; } - } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs index bb17c5f2836..05090e315ca 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs @@ -1,40 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.InternalServices.Views.Search { + using System; + using System.Collections.Generic; + /// - /// BasicView grouped by DocumentTypeName + /// BasicView grouped by DocumentTypeName. /// public class GroupedBasicView { - /// - /// Type of Search Document - /// - public string DocumentTypeName { get; set; } - - /// - /// Results of the Search - /// - public List Results { get; set; } - - #region constructor - public GroupedBasicView() - {} + { + } public GroupedBasicView(BasicView basic) { - DocumentTypeName = basic.DocumentTypeName; - Results = new List + this.DocumentTypeName = basic.DocumentTypeName; + this.Results = new List { new BasicView { @@ -43,10 +27,18 @@ public GroupedBasicView(BasicView basic) Description = basic.Description, DocumentUrl = basic.DocumentUrl, Attributes = basic.Attributes - } + }, }; - } + } + + /// + /// Gets or sets type of Search Document. + /// + public string DocumentTypeName { get; set; } - #endregion + /// + /// Gets or sets results of the Search. + /// + public List Results { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs index 293637cb9fd..9c9fda33ab4 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs @@ -1,43 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.InternalServices.Views.Search { + using System; + using System.Collections.Generic; + /// - /// DetailedView grouped by Url (TabId) + /// DetailedView grouped by Url (TabId). /// public class GroupedDetailView { + public GroupedDetailView() + { + this.Results = new List(); + } + /// - /// Document's Url + /// Gets or sets document's Url. /// public string DocumentUrl { get; set; } /// - /// Document's Title + /// Gets or sets document's Title. /// public string Title { get; set; } /// - /// Results of the Search - /// - public List Results { get; set; } - - #region constructor - - public GroupedDetailView() - { - Results = new List(); - } - - #endregion + /// Gets or sets results of the Search. + /// + public List Results { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs b/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs index 36a64ea6169..4b859cdaafe 100644 --- a/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs +++ b/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs @@ -1,15 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Models { + using System.Collections.Generic; + using System.Runtime.Serialization; + [DataContract] public class ModuleDetail { + public ModuleDetail() + { + this.ModuleInstances = new List(); + } + [DataMember] public string ModuleVersion { get; set; } @@ -18,10 +23,5 @@ public class ModuleDetail [DataMember] public IList ModuleInstances { get; set; } - - public ModuleDetail() - { - ModuleInstances = new List(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Models/ModuleInstance.cs b/DNN Platform/DotNetNuke.Web/Models/ModuleInstance.cs index c46e23e878e..0be147f74d1 100644 --- a/DNN Platform/DotNetNuke.Web/Models/ModuleInstance.cs +++ b/DNN Platform/DotNetNuke.Web/Models/ModuleInstance.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Models { + using System.Runtime.Serialization; + [DataContract] public class ModuleInstance { diff --git a/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs b/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs index 5f77a7f5aa3..60d7a671f40 100644 --- a/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs +++ b/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs @@ -1,15 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Models { + using System.Collections.Generic; + using System.Runtime.Serialization; + [DataContract] public class SiteDetail { + public SiteDetail() + { + this.Modules = new List(); + } + [DataMember] public string DnnVersion { get; set; } @@ -24,10 +29,5 @@ public class SiteDetail [DataMember] public IList Modules { get; set; } - - public SiteDetail() - { - Modules = new List(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Models/TabModule.cs b/DNN Platform/DotNetNuke.Web/Models/TabModule.cs index d04f70cfa54..6ae3fad5f8f 100644 --- a/DNN Platform/DotNetNuke.Web/Models/TabModule.cs +++ b/DNN Platform/DotNetNuke.Web/Models/TabModule.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Models { + using System; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + [Serializable] public class TabModule { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs b/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs index ab47fb62d17..5ac739ce367 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Reflection; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + using System.Linq; + using System.Reflection; + using System.Web.UI; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public class AttributeBasedViewStateSerializer { @@ -22,18 +17,18 @@ public static void DeSerialize(object value, StateBag state) { Type typ = value.GetType(); - //Parse all the Public instance properties + // Parse all the Public instance properties foreach (PropertyInfo member in typ.GetProperties(MemberBindingFlags)) { - //Determine if they are attributed with a ViewState Attribute - ViewStateAttribute attr = member.GetCustomAttributes(typeof (ViewStateAttribute), true).OfType().FirstOrDefault(); - if ((attr != null)) + // Determine if they are attributed with a ViewState Attribute + ViewStateAttribute attr = member.GetCustomAttributes(typeof(ViewStateAttribute), true).OfType().FirstOrDefault(); + if (attr != null) { - //Get object from ViewState bag + // Get object from ViewState bag string viewStateKey = attr.ViewStateKey; if (string.IsNullOrEmpty(viewStateKey)) { - //Use class member's name for Key + // Use class member's name for Key viewStateKey = member.Name; } @@ -46,18 +41,18 @@ public static void Serialize(object value, StateBag state) { Type typ = value.GetType(); - //Parse all the Public instance properties + // Parse all the Public instance properties foreach (PropertyInfo member in typ.GetProperties(MemberBindingFlags)) { - //Determine if they are attributed with a ViewState Attribute - ViewStateAttribute attr = member.GetCustomAttributes(typeof (ViewStateAttribute), true).OfType().FirstOrDefault(); - if ((attr != null)) + // Determine if they are attributed with a ViewState Attribute + ViewStateAttribute attr = member.GetCustomAttributes(typeof(ViewStateAttribute), true).OfType().FirstOrDefault(); + if (attr != null) { - //Add property to ViewState bag + // Add property to ViewState bag string viewStateKey = attr.ViewStateKey; if (string.IsNullOrEmpty(viewStateKey)) { - //Use class member's name for Key + // Use class member's name for Key viewStateKey = member.Name; } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs index 5b14b506cef..8dfd3d2ff1c 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs @@ -1,17 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using WebFormsMvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class HttpHandlerPresenter : Presenter where TView : class, IHttpHandlerView + public abstract class HttpHandlerPresenter : Presenter + where TView : class, IHttpHandlerView { - protected HttpHandlerPresenter(TView view) : base(view) + protected HttpHandlerPresenter(TView view) + : base(view) { } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs index eb7e2c74c92..0caf7546cc4 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp.Web; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public abstract class HttpHandlerView : MvpHttpHandler, IHttpHandlerView { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs index 9cef0018daa..5e217c94314 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface IHttpHandlerView : IView { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs index 0b074a070fb..cd3c22032b5 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface IModuleView : IModuleViewBase { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs index 98e28814a3b..5e9dd07be43 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs @@ -1,25 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.UI.Skins.Controls; - -using WebFormsMvp; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + + using DotNetNuke.UI.Skins.Controls; + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface IModuleViewBase : IView { - bool AutoDataBind { get; set; } - event EventHandler Initialize; + + bool AutoDataBind { get; set; } void ProcessModuleLoadException(Exception ex); diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs index 14c63c102b2..02cfced008f 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs @@ -1,18 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using WebFormsMvp; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IModuleView : IModuleViewBase, IView where TModel : class, new() + public interface IModuleView : IModuleViewBase, IView + where TModel : class, new() { } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs index 53e9e3a7eab..9f4ca89c5b6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface ISettingsView : IModuleViewBase { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsViewOfT.cs index 0bc9244b6dc..76a884fad41 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsViewOfT.cs @@ -1,14 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface ISettingsView : IModuleViewBase, IView where TModel : class, new() + public interface ISettingsView : IModuleViewBase, IView + where TModel : class, new() { event EventHandler OnLoadSettings; diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs index a6e000bfd6e..c943d579308 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface IWebServiceView : IWebServiceViewBase { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs index 5fe782cfb64..f3d971261e8 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface IWebServiceViewBase : IView { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs index 319aae51adf..40398dec299 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs @@ -1,14 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IWebServiceView : IWebServiceViewBase, IView where TModel : class, new() + public interface IWebServiceView : IWebServiceViewBase, IView + where TModel : class, new() { } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs index a1e5062028c..548a4d7fbf7 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs @@ -1,20 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModulePresenter : ModulePresenterBase where TView : class, IModuleView - { - #region Constructors - - protected ModulePresenter(TView view) : base(view) + public abstract class ModulePresenter : ModulePresenterBase + where TView : class, IModuleView + { + protected ModulePresenter(TView view) + : base(view) { - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs index bf9470128ac..4a06e9105b4 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs @@ -1,58 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web.UI; - -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Web.Validators; - -using WebFormsMvp; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + using System.Collections.Generic; + using System.Web.UI; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.Validators; + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModulePresenterBase : Presenter where TView : class, IModuleViewBase - { - #region Constructors - - protected ModulePresenterBase(TView view) : base(view) + public abstract class ModulePresenterBase : Presenter + where TView : class, IModuleViewBase + { + protected ModulePresenterBase(TView view) + : base(view) { - //Try and cast view to Control to get common control properties + // Try and cast view to Control to get common control properties var control = view as Control; if (control != null && control.Page != null) { - IsPostBack = control.Page.IsPostBack; + this.IsPostBack = control.Page.IsPostBack; } - //Try and cast view to IModuleControl to get the Context + // Try and cast view to IModuleControl to get the Context var moduleControl = view as IModuleControl; if (moduleControl != null) { - LocalResourceFile = moduleControl.LocalResourceFile; - ModuleContext = moduleControl.ModuleContext; + this.LocalResourceFile = moduleControl.LocalResourceFile; + this.ModuleContext = moduleControl.ModuleContext; } - Validator = new Validator(new DataAnnotationsObjectValidator()); - - view.Initialize += InitializeInternal; - view.Load += LoadInternal; - } - - #endregion + + this.Validator = new Validator(new DataAnnotationsObjectValidator()); - #region Protected Properties + view.Initialize += this.InitializeInternal; + view.Load += this.LoadInternal; + } + + public bool AutoDataBind { get; set; } + public ModuleInfo ModuleInfo { get; set; } + protected internal virtual bool AllowAnonymousAccess { get @@ -67,15 +62,7 @@ protected internal virtual bool IsUserAuthorized { return true; } - } - - #endregion - - #region Public Properties - - public bool AutoDataBind { get; set; } - - public ModuleInfo ModuleInfo { get; set; } + } public bool IsEditable { get; set; } @@ -97,41 +84,29 @@ protected internal virtual bool IsUserAuthorized public Dictionary Settings { get; set; } - public Validator Validator { get; set; } - - #endregion - - #region Event Handlers - - private void InitializeInternal(object sender, EventArgs e) + public Validator Validator { get; set; } + + public virtual void RestoreState(StateBag stateBag) { - LoadFromContext(); - OnInit(); + AttributeBasedViewStateSerializer.DeSerialize(this, stateBag); } - private void LoadInternal(object sender, EventArgs e) + public virtual void SaveState(StateBag stateBag) { - if (CheckAuthPolicy()) - { - OnLoad(); - } - } - - #endregion - - #region Protected Methods - + AttributeBasedViewStateSerializer.Serialize(this, stateBag); + } + protected internal virtual bool CheckAuthPolicy() { - if ((UserId == Null.NullInteger && !AllowAnonymousAccess)) + if (this.UserId == Null.NullInteger && !this.AllowAnonymousAccess) { - OnNoCurrentUser(); + this.OnNoCurrentUser(); return false; } - if ((!IsUserAuthorized)) + if (!this.IsUserAuthorized) { - OnUnauthorizedUser(); + this.OnUnauthorizedUser(); return false; } @@ -140,34 +115,50 @@ protected internal virtual bool CheckAuthPolicy() protected virtual void LoadFromContext() { - if (ModuleContext != null) + if (this.ModuleContext != null) { - ModuleInfo = ModuleContext.Configuration; - IsEditable = ModuleContext.IsEditable; - IsSuperUser = ModuleContext.PortalSettings.UserInfo.IsSuperUser; - ModuleId = ModuleContext.ModuleId; - PortalId = ModuleContext.PortalId; - Settings = new Dictionary(); - foreach (object key in ModuleContext.Settings.Keys) + this.ModuleInfo = this.ModuleContext.Configuration; + this.IsEditable = this.ModuleContext.IsEditable; + this.IsSuperUser = this.ModuleContext.PortalSettings.UserInfo.IsSuperUser; + this.ModuleId = this.ModuleContext.ModuleId; + this.PortalId = this.ModuleContext.PortalId; + this.Settings = new Dictionary(); + foreach (object key in this.ModuleContext.Settings.Keys) { - Settings[key.ToString()] = (string) ModuleContext.Settings[key]; + this.Settings[key.ToString()] = (string)this.ModuleContext.Settings[key]; } - TabId = ModuleContext.TabId; - UserId = ModuleContext.PortalSettings.UserInfo.UserID; + + this.TabId = this.ModuleContext.TabId; + this.UserId = this.ModuleContext.PortalSettings.UserInfo.UserID; } } + + private void InitializeInternal(object sender, EventArgs e) + { + this.LoadFromContext(); + this.OnInit(); + } + + private void LoadInternal(object sender, EventArgs e) + { + if (this.CheckAuthPolicy()) + { + this.OnLoad(); + } + } protected virtual string LocalizeString(string key) { string localizedString; - if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(LocalResourceFile)) + if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(this.LocalResourceFile)) { - localizedString = Localization.GetString(key, LocalResourceFile); + localizedString = Localization.GetString(key, this.LocalResourceFile); } else { localizedString = Null.NullString; } + return localizedString; } @@ -181,47 +172,47 @@ protected virtual void OnLoad() protected virtual void OnNoCurrentUser() { - RedirectToLogin(); + this.RedirectToLogin(); } protected virtual void OnUnauthorizedUser() { - RedirectToAccessDenied(); + this.RedirectToAccessDenied(); } protected void RedirectToAccessDenied() { - Response.Redirect(TestableGlobals.Instance.AccessDeniedURL(), true); + this.Response.Redirect(TestableGlobals.Instance.AccessDeniedURL(), true); } protected void RedirectToCurrentPage() { - Response.Redirect(TestableGlobals.Instance.NavigateURL(), true); + this.Response.Redirect(TestableGlobals.Instance.NavigateURL(), true); } protected void RedirectToLogin() { - Response.Redirect(TestableGlobals.Instance.LoginURL(Request.RawUrl, false), true); + this.Response.Redirect(TestableGlobals.Instance.LoginURL(this.Request.RawUrl, false), true); } protected void ProcessModuleLoadException(Exception ex) { - View.ProcessModuleLoadException(ex); + this.View.ProcessModuleLoadException(ex); } protected void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) { - ShowMessage(messageHeader, message, messageType, true); + this.ShowMessage(messageHeader, message, messageType, true); } protected void ShowMessage(string message, ModuleMessage.ModuleMessageType messageType) { - ShowMessage(message, messageType, true); + this.ShowMessage(message, messageType, true); } protected void ShowMessage(string message, ModuleMessage.ModuleMessageType messageType, bool localize) { - ShowMessage(string.Empty, message, messageType, localize); + this.ShowMessage(string.Empty, message, messageType, localize); } protected void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType, bool localize) @@ -230,27 +221,12 @@ protected void ShowMessage(string messageHeader, string message, ModuleMessage.M { if (localize) { - messageHeader = LocalizeString(messageHeader); - message = LocalizeString(message); + messageHeader = this.LocalizeString(messageHeader); + message = this.LocalizeString(message); } - View.ShowMessage(messageHeader, message, messageType); + + this.View.ShowMessage(messageHeader, message, messageType); } - } - - #endregion - - #region Public Methods - - public virtual void RestoreState(StateBag stateBag) - { - AttributeBasedViewStateSerializer.DeSerialize(this, stateBag); - } - - public virtual void SaveState(StateBag stateBag) - { - AttributeBasedViewStateSerializer.Serialize(this, stateBag); - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs index 0397a2788f3..2d81cd64e0c 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs @@ -1,15 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModulePresenter : ModulePresenterBase where TView : class, IModuleView where TModel : class, new() + public abstract class ModulePresenter : ModulePresenterBase + where TView : class, IModuleView + where TModel : class, new() { - protected ModulePresenter(TView view) : base(view) + protected ModulePresenter(TView view) + : base(view) { } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs index 08ee80d3efb..3ef2ae0a213 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs @@ -1,72 +1,61 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + using System.Collections.Generic; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class ModuleSettingsPresenterBase : ModulePresenterBase where TView : class, ISettingsView - { - #region Constructors - - public ModuleSettingsPresenterBase(TView view) : base(view) + public class ModuleSettingsPresenterBase : ModulePresenterBase + where TView : class, ISettingsView + { + public ModuleSettingsPresenterBase(TView view) + : base(view) { - view.OnLoadSettings += OnLoadSettingsInternal; - view.OnSaveSettings += OnSaveSettingsInternal; - - ModuleSettings = new Dictionary(); - TabModuleSettings = new Dictionary(); - } - - #endregion + view.OnLoadSettings += this.OnLoadSettingsInternal; + view.OnSaveSettings += this.OnSaveSettingsInternal; + this.ModuleSettings = new Dictionary(); + this.TabModuleSettings = new Dictionary(); + } + public Dictionary ModuleSettings { get; set; } - public Dictionary TabModuleSettings { get; set; } - - #region Event Handlers - - private void OnLoadSettingsInternal(object sender, EventArgs e) - { - LoadSettings(); - } - - private void OnSaveSettingsInternal(object sender, EventArgs e) - { - SaveSettings(); - } - - #endregion - - #region Protected Methods - + public Dictionary TabModuleSettings { get; set; } + protected override void LoadFromContext() { base.LoadFromContext(); - foreach (var key in ModuleContext.Configuration.ModuleSettings.Keys) + foreach (var key in this.ModuleContext.Configuration.ModuleSettings.Keys) { - ModuleSettings.Add(Convert.ToString(key), Convert.ToString(ModuleContext.Configuration.ModuleSettings[key])); + this.ModuleSettings.Add(Convert.ToString(key), Convert.ToString(this.ModuleContext.Configuration.ModuleSettings[key])); } - foreach (var key in ModuleContext.Configuration.TabModuleSettings.Keys) + foreach (var key in this.ModuleContext.Configuration.TabModuleSettings.Keys) { - TabModuleSettings.Add(Convert.ToString(key), Convert.ToString(ModuleContext.Configuration.TabModuleSettings[key])); + this.TabModuleSettings.Add(Convert.ToString(key), Convert.ToString(this.ModuleContext.Configuration.TabModuleSettings[key])); } } protected virtual void LoadSettings() { } - - protected virtual void SaveSettings() + + private void OnLoadSettingsInternal(object sender, EventArgs e) { + this.LoadSettings(); } - #endregion + private void OnSaveSettingsInternal(object sender, EventArgs e) + { + this.SaveSettings(); + } + protected virtual void SaveSettings() + { + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs index 68e68a73cfd..2e268351498 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs @@ -1,84 +1,76 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Linq; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Entities.Modules; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public abstract class ModuleSettingsPresenter : ModulePresenterBase where TView : class, ISettingsView where TModel : SettingsModel, new() { - protected ModuleSettingsPresenter(TView view) : base(view) - { - view.OnLoadSettings += OnLoadSettingsInternal; - view.OnSaveSettings += OnSaveSettingsInternal; - } - - #region Event Handlers - - private void OnLoadSettingsInternal(object sender, EventArgs e) + protected ModuleSettingsPresenter(TView view) + : base(view) { - LoadSettings(); - } - - private void OnSaveSettingsInternal(object sender, EventArgs e) - { - SaveSettings(); - } - - #endregion - - #region Protected Methods - + view.OnLoadSettings += this.OnLoadSettingsInternal; + view.OnSaveSettings += this.OnSaveSettingsInternal; + } + protected override void OnLoad() { base.OnLoad(); - if (IsPostBack) + if (this.IsPostBack) { - //Initialize dictionaries as LoadSettings is not called on Postback - View.Model.ModuleSettings = new Dictionary(); - View.Model.TabModuleSettings = new Dictionary(); + // Initialize dictionaries as LoadSettings is not called on Postback + this.View.Model.ModuleSettings = new Dictionary(); + this.View.Model.TabModuleSettings = new Dictionary(); } } protected virtual void LoadSettings() { - View.Model.ModuleSettings = new Dictionary( - ModuleContext.Configuration.ModuleSettings + this.View.Model.ModuleSettings = new Dictionary( + this.ModuleContext.Configuration.ModuleSettings .Cast() - .ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value) - ); + .ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value)); - View.Model.TabModuleSettings = new Dictionary( - ModuleContext.Configuration.TabModuleSettings + this.View.Model.TabModuleSettings = new Dictionary( + this.ModuleContext.Configuration.TabModuleSettings .Cast() - .ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value) - ); + .ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value)); + } + + private void OnLoadSettingsInternal(object sender, EventArgs e) + { + this.LoadSettings(); } + private void OnSaveSettingsInternal(object sender, EventArgs e) + { + this.SaveSettings(); + } + protected virtual void SaveSettings() { var controller = ModuleController.Instance; - foreach (var setting in View.Model.ModuleSettings) + foreach (var setting in this.View.Model.ModuleSettings) { - ModuleController.Instance.UpdateModuleSetting(ModuleId, setting.Key, setting.Value); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, setting.Key, setting.Value); } - foreach (var setting in View.Model.TabModuleSettings) + foreach (var setting in this.View.Model.TabModuleSettings) { - ModuleController.Instance.UpdateTabModuleSetting(ModuleContext.TabModuleId, setting.Key, setting.Value); + ModuleController.Instance.UpdateTabModuleSetting(this.ModuleContext.TabModuleId, setting.Key, setting.Value); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs index 6e305c5c00d..43b8f8809c1 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public abstract class ModuleView : ModuleViewBase { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs index 6566db43c43..07a903f7962 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs @@ -1,71 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins.Controls; - -using WebFormsMvp.Web; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + using System.Globalization; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; + using WebFormsMvp.Web; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public abstract class ModuleViewBase : ModuleUserControlBase, IModuleViewBase - { - #region Constructors - + { protected ModuleViewBase() { - AutoDataBind = true; - } - - #endregion - - #region Protected Methods - - protected T DataItem() where T : class, new() - { - var _T = Page.GetDataItem() as T ?? new T(); - return _T; - } - - protected T DataValue() - { - return (T) Page.GetDataItem(); - } - - protected string DataValue(string format) - { - return string.Format(CultureInfo.CurrentCulture, format, DataValue()); - } - - protected override void OnInit(EventArgs e) - { - PageViewHost.Register(this, Context, false); - - base.OnInit(e); - - Page.InitComplete += PageInitComplete; - Page.PreRenderComplete += PagePreRenderComplete; - Page.Load += PageLoad; - } - - #endregion - - #region IModuleView(Of TModel) Implementation + this.AutoDataBind = true; + } + public event EventHandler Initialize; + + public new event EventHandler Load; + public bool AutoDataBind { get; set; } - public event EventHandler Initialize; + public bool ThrowExceptionIfNoPresenterBound + { + get { return true; } + } public void ProcessModuleLoadException(Exception ex) { @@ -75,49 +38,60 @@ public void ProcessModuleLoadException(Exception ex) public void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) { DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, messageHeader, message, messageType); + } + + protected T DataItem() + where T : class, new() + { + var _T = this.Page.GetDataItem() as T ?? new T(); + return _T; } - #endregion - - #region IView(Of TModel) Implementation - - public new event EventHandler Load; + protected T DataValue() + { + return (T)this.Page.GetDataItem(); + } - public bool ThrowExceptionIfNoPresenterBound + protected string DataValue(string format) { - get { return true; } + return string.Format(CultureInfo.CurrentCulture, format, this.DataValue()); } - #endregion + protected override void OnInit(EventArgs e) + { + PageViewHost.Register(this, this.Context, false); - #region Event Handlers + base.OnInit(e); + this.Page.InitComplete += this.PageInitComplete; + this.Page.PreRenderComplete += this.PagePreRenderComplete; + this.Page.Load += this.PageLoad; + } + private void PageInitComplete(object sender, EventArgs e) { - if (Initialize != null) + if (this.Initialize != null) { - Initialize(this, EventArgs.Empty); + this.Initialize(this, EventArgs.Empty); } } private void PageLoad(object sender, EventArgs e) { - if (Load != null) + if (this.Load != null) { - Load(this, e); + this.Load(this, e); } } private void PagePreRenderComplete(object sender, EventArgs e) { - //This event is raised after any async page tasks have completed, so it - //is safe to data-bind - if ((AutoDataBind)) + // This event is raised after any async page tasks have completed, so it + // is safe to data-bind + if (this.AutoDataBind) { - DataBind(); + this.DataBind(); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs index 0f918adc5a9..be44cad0b92 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs @@ -1,52 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using WebFormsMvp; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModuleView : ModuleViewBase, IView where TModel : class, new() + public abstract class ModuleView : ModuleViewBase, IView + where TModel : class, new() { - private TModel _model; - - #region IView Members - + private TModel _model; + public TModel Model { get { - if ((_model == null)) + if (this._model == null) { throw new InvalidOperationException( "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } - return _model; + + return this._model; } - set { _model = value; } - } - - #endregion - + + set { this._model = value; } + } + protected override void LoadViewState(object savedState) { - //Call the base class to load any View State + // Call the base class to load any View State base.LoadViewState(savedState); - AttributeBasedViewStateSerializer.DeSerialize(Model, ViewState); + AttributeBasedViewStateSerializer.DeSerialize(this.Model, this.ViewState); } protected override object SaveViewState() { - AttributeBasedViewStateSerializer.Serialize(Model, ViewState); - //Call the base class to save the View State + AttributeBasedViewStateSerializer.Serialize(this.Model, this.ViewState); + + // Call the base class to save the View State return base.SaveViewState(); } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs index 0a6db341dc6..b7436d124d6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs @@ -1,32 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + using System.Globalization; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ProfileModuleViewBase : ModuleView, IProfileModule where TModel : class, new() + public abstract class ProfileModuleViewBase : ModuleView, IProfileModule + where TModel : class, new() { - protected INavigationManager NavigationManager { get; } public ProfileModuleViewBase() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - #region IProfileModule Members - + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + } + public abstract bool DisplayModule { get; } public int ProfileUserId @@ -34,39 +32,50 @@ public int ProfileUserId get { int UserId = Null.NullInteger; - if (!string.IsNullOrEmpty(Request.Params["UserId"])) + if (!string.IsNullOrEmpty(this.Request.Params["UserId"])) { - UserId = Int32.Parse(Request.Params["UserId"]); + UserId = int.Parse(this.Request.Params["UserId"]); } + return UserId; } - } - - #endregion - - #region Protected Properties - + } + + protected INavigationManager NavigationManager { get; } + protected bool IsUser { get { - return ProfileUserId == ModuleContext.PortalSettings.UserId; + return this.ProfileUserId == this.ModuleContext.PortalSettings.UserId; } } protected UserInfo ProfileUser { - get { return UserController.GetUserById(ModuleContext.PortalId, ProfileUserId); } - } - - #endregion - - #region Private Methods + get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } + } + + protected override void OnInit(EventArgs e) + { + if (this.ProfileUserId == Null.NullInteger && + (this.ModuleContext.PortalSettings.ActiveTab.TabID == this.ModuleContext.PortalSettings.UserTabId + || this.ModuleContext.PortalSettings.ActiveTab.ParentId == this.ModuleContext.PortalSettings.UserTabId)) + { + // Clicked on breadcrumb - don't know which user + this.Response.Redirect( + this.Request.IsAuthenticated + ? this.NavigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, string.Empty, "UserId=" + this.ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) + : this.GetRedirectUrl(), true); + } + base.OnInit(e); + } + private string GetRedirectUrl() { - //redirect user to default page if not specific the home tab, do this action to prevent loop redirect. - var homeTabId = ModuleContext.PortalSettings.HomeTabId; + // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. + var homeTabId = this.ModuleContext.PortalSettings.HomeTabId; string redirectUrl; if (homeTabId > Null.NullInteger) @@ -75,31 +84,10 @@ private string GetRedirectUrl() } else { - redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, Request, true) + "/" + Globals.glbDefaultPage; + redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, this.Request, true) + "/" + Globals.glbDefaultPage; } return redirectUrl; - } - - #endregion - - #region Protected Methods - - protected override void OnInit(EventArgs e) - { - if (ProfileUserId == Null.NullInteger && - (ModuleContext.PortalSettings.ActiveTab.TabID == ModuleContext.PortalSettings.UserTabId - || ModuleContext.PortalSettings.ActiveTab.ParentId == ModuleContext.PortalSettings.UserTabId)) - { - //Clicked on breadcrumb - don't know which user - Response.Redirect(Request.IsAuthenticated - ? NavigationManager.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "", "UserId=" + ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) - : GetRedirectUrl(), true); - } - - base.OnInit(e); - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs index 99b1671dc38..8ff9f5344c2 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + using System.Collections.Generic; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public class SettingsModel { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs index ffd0b39e2f7..86585f36cb7 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs @@ -1,41 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class SettingsView : SettingsViewBase, ISettingsView where TModel : SettingsModel, new() + public abstract class SettingsView : SettingsViewBase, ISettingsView + where TModel : SettingsModel, new() { - private TModel _model; - - #region IView Members - + private TModel _model; + public TModel Model { get { - if ((_model == null)) + if (this._model == null) { throw new InvalidOperationException( "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } - return _model; + + return this._model; } - set { _model = value; } - } - - #endregion - + + set { this._model = value; } + } + protected string GetModuleSetting(string key, string defaultValue) { var value = defaultValue; - if(Model.ModuleSettings.ContainsKey(key)) + if (this.Model.ModuleSettings.ContainsKey(key)) { - value = Model.ModuleSettings[key]; + value = this.Model.ModuleSettings[key]; } return value; @@ -45,13 +44,12 @@ protected string GetTabModuleSetting(string key, string defaultValue) { var value = defaultValue; - if (Model.TabModuleSettings.ContainsKey(key)) + if (this.Model.TabModuleSettings.ContainsKey(key)) { - value = Model.TabModuleSettings[key]; + value = this.Model.TabModuleSettings[key]; } return value; } - } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs index 5b4c7aa42be..183effd02a6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs @@ -1,61 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + + using DotNetNuke.UI.Modules; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public class SettingsViewBase : ModuleViewBase, ISettingsView, ISettingsControl - { - #region ISettingsControl Members - + { + public event EventHandler OnLoadSettings; + + public event EventHandler OnSaveSettings; + public void LoadSettings() { - if (OnLoadSettings != null) + if (this.OnLoadSettings != null) { - OnLoadSettings(this, EventArgs.Empty); + this.OnLoadSettings(this, EventArgs.Empty); } - OnSettingsLoaded(); - + this.OnSettingsLoaded(); } public void UpdateSettings() { - OnSavingSettings(); + this.OnSavingSettings(); - if (OnSaveSettings != null) + if (this.OnSaveSettings != null) { - OnSaveSettings(this, EventArgs.Empty); + this.OnSaveSettings(this, EventArgs.Empty); } - } - - #endregion - - #region ISettingsView Members - - public event EventHandler OnLoadSettings; - public event EventHandler OnSaveSettings; - - #endregion - + } + /// - /// The OnSettingsLoaded method is called when the Settings have been Loaded + /// The OnSettingsLoaded method is called when the Settings have been Loaded. /// protected virtual void OnSettingsLoaded() { } /// - /// OnSavingSettings method is called just before the Settings are saved + /// OnSavingSettings method is called just before the Settings are saved. /// protected virtual void OnSavingSettings() { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs b/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs index ab350cbfd22..4143e17c668 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public class ViewStateAttribute : Attribute diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs index 4dcb9dd7808..7783a06be77 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs @@ -1,16 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class WebServicePresenter : Presenter where TView : class, IWebServiceView + public abstract class WebServicePresenter : Presenter + where TView : class, IWebServiceView { - protected WebServicePresenter(TView view) : base(view) + protected WebServicePresenter(TView view) + : base(view) { } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs index aeca5531c26..0b71438e459 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public abstract class WebServiceView : WebServiceViewBase { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs index 567a1d546b6..59c4ab18c13 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp.Web; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public abstract class WebServiceViewBase : MvpWebService, IWebServiceViewBase { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs index 2470e72391a..8d40d8f92b6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs @@ -1,33 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using WebFormsMvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Mvp { + using System; + + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class WebServiceViewOfT : ModuleViewBase, IView where TModel : class, new() + public abstract class WebServiceViewOfT : ModuleViewBase, IView + where TModel : class, new() { - private TModel _model; - - #region IView Members - + private TModel _model; + public TModel Model { get { - if ((_model == null)) + if (this._model == null) { throw new InvalidOperationException( "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } - return _model; + + return this._model; } - set { _model = value; } - } - - #endregion + + set { this._model = value; } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Properties/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Web/Properties/AssemblyInfo.cs index 886f961f3b4..82fcde51023 100644 --- a/DNN Platform/DotNetNuke.Web/Properties/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Web/Properties/AssemblyInfo.cs @@ -1,28 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -#endregion - -// 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. - -// Review the values of the assembly attributes - +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. + +// Review the values of the assembly attributes [assembly: AssemblyTitle("DotNetNuke.Web")] [assembly: AssemblyDescription("Open Source Web Application Framework")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] -//The following GUID is for the ID of the typelib if this project is exposed to COM - + +// The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("99d0e26d-a924-41d2-a195-33496a3f48ad")] [assembly: InternalsVisibleTo("DotNetNuke.Tests.Content")] diff --git a/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs b/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs index c1147a758ac..fc9d449eb3e 100644 --- a/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs +++ b/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs @@ -1,49 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Models; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Services { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Models; + [AllowAnonymous] public class MobileHelperController : DnnApiController { private readonly string _dnnVersion = Globals.FormatVersion(DotNetNukeContext.Current.Application.Version, false); /// - /// Gets the various defined monikers for the various tab modules in the system - /// + /// Gets the various defined monikers for the various tab modules in the system. + /// + /// [HttpGet] public IHttpActionResult Monikers(string moduleList) { var monikers = GetMonikersForList(moduleList); - return Ok(monikers.Select(kpv => new { tabModuleId = kpv.Key, moniker = kpv.Value })); + return this.Ok(monikers.Select(kpv => new { tabModuleId = kpv.Key, moniker = kpv.Value })); } [HttpGet] public HttpResponseMessage ModuleDetails(string moduleList) { - var siteDetails = GetSiteDetails(moduleList); - return Request.CreateResponse(HttpStatusCode.OK, siteDetails); - } - - #region private methods - + var siteDetails = this.GetSiteDetails(moduleList); + return this.Request.CreateResponse(HttpStatusCode.OK, siteDetails); + } + private static IEnumerable> GetMonikersForList(string moduleList) { var portalId = PortalSettings.Current.PortalId; @@ -57,7 +57,7 @@ private static IEnumerable> GetMonikersForList(string if (modules.Any()) { - foreach (var moduleName in (moduleList ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var moduleName in (moduleList ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var dtmRecord = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, portalId); if (dtmRecord != null) @@ -77,50 +77,12 @@ private static IEnumerable> GetMonikersForList(string return monikers.Where(kpv => resultIds.Contains(kpv.Key)); } - private SiteDetail GetSiteDetails(string moduleList) - { - var siteDetails = new SiteDetail - { - SiteName = PortalSettings.PortalName, - DnnVersion = _dnnVersion, - IsHost = UserInfo.IsSuperUser, - IsAdmin = UserInfo.IsInRole("Administrators") - }; - - foreach (var moduleName in (moduleList ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) - { - var modulesCollection = GetTabModules((moduleName ?? "").Trim()) - .Where(tabmodule => TabPermissionController.CanViewPage(tabmodule.TabInfo) && - ModulePermissionController.CanViewModule(tabmodule.ModuleInfo)); - foreach (var tabmodule in modulesCollection) - { - var moduleDetail = new ModuleDetail - { - ModuleName = moduleName, - ModuleVersion = tabmodule.ModuleVersion - }; - - moduleDetail.ModuleInstances.Add(new ModuleInstance - { - TabId = tabmodule.TabInfo.TabID, - ModuleId = tabmodule.ModuleInfo.ModuleID, - PageName = tabmodule.TabInfo.TabName, - PagePath = tabmodule.TabInfo.TabPath - }); - siteDetails.Modules.Add(moduleDetail); - } - } - - return siteDetails; - } - private static IEnumerable GetTabModules(string moduleName) { var portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId; var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, portalId); if (desktopModule != null) { - var cacheKey = string.Format(DataCache.DesktopModuleCacheKey, portalId) + "_" + desktopModule.DesktopModuleID; var args = new CacheItemArgs(cacheKey, DataCache.DesktopModuleCacheTimeOut, @@ -144,7 +106,7 @@ private static object GetTabModulesCallback(CacheItemArgs cacheItemArgs) var allPortalTabs = tabController.GetTabsByPortal(portalId); IDictionary tabsInOrder = new Dictionary(); - //must get each tab, they parent may not exist + // must get each tab, they parent may not exist foreach (var tab in allPortalTabs.Values) { AddChildTabsToList(tab, allPortalTabs, tabsWithModule, tabsInOrder); @@ -159,28 +121,64 @@ private static object GetTabModulesCallback(CacheItemArgs cacheItemArgs) { TabInfo = tab, ModuleInfo = childModule, - ModuleVersion = desktopModule.Version + ModuleVersion = desktopModule.Version, })); } return tabModules; } + private SiteDetail GetSiteDetails(string moduleList) + { + var siteDetails = new SiteDetail + { + SiteName = this.PortalSettings.PortalName, + DnnVersion = this._dnnVersion, + IsHost = this.UserInfo.IsSuperUser, + IsAdmin = this.UserInfo.IsInRole("Administrators"), + }; + + foreach (var moduleName in (moduleList ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + { + var modulesCollection = GetTabModules((moduleName ?? string.Empty).Trim()) + .Where(tabmodule => TabPermissionController.CanViewPage(tabmodule.TabInfo) && + ModulePermissionController.CanViewModule(tabmodule.ModuleInfo)); + foreach (var tabmodule in modulesCollection) + { + var moduleDetail = new ModuleDetail + { + ModuleName = moduleName, + ModuleVersion = tabmodule.ModuleVersion, + }; + + moduleDetail.ModuleInstances.Add(new ModuleInstance + { + TabId = tabmodule.TabInfo.TabID, + ModuleId = tabmodule.ModuleInfo.ModuleID, + PageName = tabmodule.TabInfo.TabName, + PagePath = tabmodule.TabInfo.TabPath, + }); + siteDetails.Modules.Add(moduleDetail); + } + } + + return siteDetails; + } + private static void AddChildTabsToList(TabInfo currentTab, TabCollection allPortalTabs, IDictionary tabsWithModule, IDictionary tabsInOrder) { if (tabsWithModule.ContainsKey(currentTab.TabID) && !tabsInOrder.ContainsKey(currentTab.TabID)) { - //add current tab + // add current tab tabsInOrder.Add(currentTab.TabID, currentTab); - //add children of current tab + + // add children of current tab foreach (var tab in allPortalTabs.WithParentId(currentTab.TabID)) { AddChildTabsToList(tab, allPortalTabs, tabsWithModule, tabsInOrder); } } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/Services/ServiceRouteMapper.cs b/DNN Platform/DotNetNuke.Web/Services/ServiceRouteMapper.cs index 46da6569430..a17491bf964 100644 --- a/DNN Platform/DotNetNuke.Web/Services/ServiceRouteMapper.cs +++ b/DNN Platform/DotNetNuke.Web/Services/ServiceRouteMapper.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Services { + using DotNetNuke.Web.Api; + public class ServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) { mapRouteManager.MapHttpRoute( - "web", "default", "{controller}/{action}", new[] { GetType().Namespace }); + "web", "default", "{controller}/{action}", new[] { this.GetType().Namespace }); } } } diff --git a/DNN Platform/DotNetNuke.Web/Startup.cs b/DNN Platform/DotNetNuke.Web/Startup.cs index ce0c37fc09c..c05fd6887f1 100644 --- a/DNN Platform/DotNetNuke.Web/Startup.cs +++ b/DNN Platform/DotNetNuke.Web/Startup.cs @@ -1,34 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.DependencyInjection; -using DotNetNuke.DependencyInjection.Extensions; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.DependencyInjection; -using DotNetNuke.Web.Extensions; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using DotNetNuke.DependencyInjection; + using DotNetNuke.DependencyInjection.Extensions; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.DependencyInjection; + using DotNetNuke.Web.Extensions; + using Microsoft.Extensions.DependencyInjection; + public class Startup : IDnnStartup { private static readonly ILog _logger = LoggerSource.Instance.GetLogger(typeof(Startup)); + public Startup() { - Configure(); - } - - private void Configure() - { - var services = new ServiceCollection(); - services.AddSingleton(); - ConfigureServices(services); - DependencyProvider = services.BuildServiceProvider(); + this.Configure(); } public IServiceProvider DependencyProvider { get; private set; } @@ -43,7 +37,7 @@ public void ConfigureServices(IServiceCollection services) !x.IsAbstract); var startupInstances = startupTypes - .Select(x => CreateInstance(x)) + .Select(x => this.CreateInstance(x)) .Where(x => x != null); foreach (IDnnStartup startup in startupInstances) @@ -61,6 +55,14 @@ public void ConfigureServices(IServiceCollection services) services.AddWebApi(); } + private void Configure() + { + var services = new ServiceCollection(); + services.AddSingleton(); + this.ConfigureServices(services); + this.DependencyProvider = services.BuildServiceProvider(); + } + private object CreateInstance(Type startupType) { IDnnStartup startup = null; diff --git a/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs b/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs index 2a675cc128f..7a1428a505b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs +++ b/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI { public interface ILocalizable { string LocalResourceFile { get; set; } + bool Localize { get; set; } void LocalizeStrings(); diff --git a/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs b/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs index 6668d849aea..5695703ae90 100644 --- a/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs +++ b/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs @@ -1,53 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI { + using System.Web.UI.WebControls; + public class MessageWindowParameters { - private string _Message = ""; - private string _Title = ""; + private string _Message = string.Empty; + private string _Title = string.Empty; private Unit _WindowHeight = Unit.Pixel(175); private Unit _WindowWidth = Unit.Pixel(350); public MessageWindowParameters(string message) { - _Message = message; + this._Message = message; } public MessageWindowParameters(string message, string title) { - _Message = message; - _Title = title; + this._Message = message; + this._Title = title; } public MessageWindowParameters(string message, string title, string windowWidth, string windowHeight) { - _Message = message; - _Title = title; - _WindowWidth = Unit.Parse(windowWidth); - _WindowHeight = Unit.Parse(windowHeight); + this._Message = message; + this._Title = title; + this._WindowWidth = Unit.Parse(windowWidth); + this._WindowHeight = Unit.Parse(windowHeight); } public string Message { get { - return _Message; + return this._Message; } + set { - //todo: javascript encode for onclick events - _Message = value; - _Message = _Message.Replace("'", "\\'"); - _Message = _Message.Replace("\"", "\\\""); + // todo: javascript encode for onclick events + this._Message = value; + this._Message = this._Message.Replace("'", "\\'"); + this._Message = this._Message.Replace("\"", "\\\""); } } @@ -55,14 +51,15 @@ public string Title { get { - return _Title; + return this._Title; } + set { - //todo: javascript encode for onclick events - _Title = value; - _Title = _Title.Replace("'", "\\'"); - _Title = _Title.Replace("\"", "\\\""); + // todo: javascript encode for onclick events + this._Title = value; + this._Title = this._Title.Replace("'", "\\'"); + this._Title = this._Title.Replace("\"", "\\\""); } } @@ -70,11 +67,12 @@ public Unit WindowWidth { get { - return _WindowWidth; + return this._WindowWidth; } + set { - _WindowWidth = value; + this._WindowWidth = value; } } @@ -82,11 +80,12 @@ public Unit WindowHeight { get { - return _WindowHeight; + return this._WindowHeight; } + set { - _WindowHeight = value; + this._WindowHeight = value; } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs index c039e5333fe..242e52b752d 100644 --- a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs +++ b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs @@ -1,39 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Text.RegularExpressions; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.Serialization; + using System.Text.RegularExpressions; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + + public enum DotNetNukeErrorCode + { + NotSet, + PageExists, + PageNameRequired, + PageNameInvalid, + DeserializePanesFailed, + PageCircularReference, + ParentTabInvalid, + PageEditorPermissionError, + HostBeforeAfterError, + DuplicateWithAlias, + } + + public enum TabRelativeLocation + { + NOTSET, + BEFORE, + AFTER, + CHILD, + } + public class RibbonBarManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (RibbonBarManager)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RibbonBarManager)); + public static TabInfo InitTabInfoObject() { return InitTabInfoObject(null, TabRelativeLocation.AFTER); @@ -46,9 +63,9 @@ public static TabInfo InitTabInfoObject(TabInfo relativeToTab) public static TabInfo InitTabInfoObject(TabInfo relativeToTab, TabRelativeLocation location) { - if (((relativeToTab == null))) + if (relativeToTab == null) { - if (((PortalSettings.Current != null) && (PortalSettings.Current.ActiveTab != null))) + if ((PortalSettings.Current != null) && (PortalSettings.Current.ActiveTab != null)) { relativeToTab = PortalSettings.Current.ActiveTab; } @@ -57,26 +74,27 @@ public static TabInfo InitTabInfoObject(TabInfo relativeToTab, TabRelativeLocati var newTab = new TabInfo { TabID = Null.NullInteger, - TabName = "", - Title = "", + TabName = string.Empty, + Title = string.Empty, IsVisible = false, DisableLink = false, IsDeleted = false, IsSecure = false, - PermanentRedirect = false + PermanentRedirect = false, }; TabInfo parentTab = GetParentTab(relativeToTab, location); - if (((parentTab != null))) + if (parentTab != null) { newTab.PortalID = parentTab.PortalID; newTab.ParentId = parentTab.TabID; newTab.Level = parentTab.Level + 1; - if ((PortalSettings.Current.SSLEnabled)) + if (PortalSettings.Current.SSLEnabled) { newTab.IsSecure = parentTab.IsSecure; - //Inherit from parent + + // Inherit from parent } } else @@ -86,15 +104,15 @@ public static TabInfo InitTabInfoObject(TabInfo relativeToTab, TabRelativeLocati newTab.Level = 0; } - //Inherit permissions from parent + // Inherit permissions from parent newTab.TabPermissions.Clear(); - if ((newTab.PortalID != Null.NullInteger && (parentTab != null))) + if (newTab.PortalID != Null.NullInteger && (parentTab != null)) { newTab.TabPermissions.AddRange(parentTab.TabPermissions); } - else if ((newTab.PortalID != Null.NullInteger)) + else if (newTab.PortalID != Null.NullInteger) { - //Give admin full permission + // Give admin full permission ArrayList permissions = PermissionController.GetPermissionsByTab(); foreach (PermissionInfo permission in permissions) @@ -114,17 +132,17 @@ public static TabInfo InitTabInfoObject(TabInfo relativeToTab, TabRelativeLocati public static TabInfo GetParentTab(TabInfo relativeToTab, TabRelativeLocation location) { - if (((relativeToTab == null))) + if (relativeToTab == null) { return null; } TabInfo parentTab = null; - if ((location == TabRelativeLocation.CHILD)) + if (location == TabRelativeLocation.CHILD) { parentTab = relativeToTab; } - else if (((relativeToTab != null) && relativeToTab.ParentId != Null.NullInteger)) + else if ((relativeToTab != null) && relativeToTab.ParentId != Null.NullInteger) { parentTab = TabController.Instance.GetTab(relativeToTab.ParentId, relativeToTab.PortalID, false); } @@ -136,9 +154,9 @@ public static IList GetPagesList() { IList portalTabs = null; UserInfo userInfo = UserController.Instance.GetCurrentUserInfo(); - if (((userInfo != null) && userInfo.UserID != Null.NullInteger)) + if ((userInfo != null) && userInfo.UserID != Null.NullInteger) { - if ((userInfo.IsSuperUser && PortalSettings.Current.ActiveTab.IsSuperTab)) + if (userInfo.IsSuperUser && PortalSettings.Current.ActiveTab.IsSuperTab) { portalTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger).AsList(); } @@ -148,7 +166,7 @@ public static IList GetPagesList() } } - if (((portalTabs == null))) + if (portalTabs == null) { portalTabs = new List(); } @@ -158,34 +176,34 @@ public static IList GetPagesList() public static bool IsHostConsolePage() { - return (PortalSettings.Current.ActiveTab.IsSuperTab && PortalSettings.Current.ActiveTab.TabPath == "//Host"); + return PortalSettings.Current.ActiveTab.IsSuperTab && PortalSettings.Current.ActiveTab.TabPath == "//Host"; } public static bool IsHostConsolePage(TabInfo tab) { - return (tab.IsSuperTab && tab.TabPath == "//Host"); + return tab.IsSuperTab && tab.TabPath == "//Host"; } public static bool CanMovePage() { - //Cannot move the host console page - if ((IsHostConsolePage())) + // Cannot move the host console page + if (IsHostConsolePage()) { return false; } - //Page Editors - Can only move children they have 'Manage' permission to, they cannot move the top level page - if ((!PortalSecurity.IsInRole("Administrators"))) + // Page Editors - Can only move children they have 'Manage' permission to, they cannot move the top level page + if (!PortalSecurity.IsInRole("Administrators")) { int parentTabID = PortalSettings.Current.ActiveTab.ParentId; - if ((parentTabID == Null.NullInteger)) + if (parentTabID == Null.NullInteger) { return false; } TabInfo parentTab = TabController.Instance.GetTab(parentTabID, PortalSettings.Current.ActiveTab.PortalID, false); string permissionList = "MANAGE"; - if ((!TabPermissionController.HasTabPermission(parentTab.TabPermissions, permissionList))) + if (!TabPermissionController.HasTabPermission(parentTab.TabPermissions, permissionList)) { return false; } @@ -196,21 +214,21 @@ public static bool CanMovePage() public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelativeLocation location, string templateFileId) { - //Validation: - //Tab name is required - //Tab name is invalid - string invalidType; - if (!TabController.IsValidTabName(tab.TabName, out invalidType)) - { - switch (invalidType) - { - case "EmptyTabName": - throw new DotNetNukeException("Page name is required.", DotNetNukeErrorCode.PageNameRequired); - case "InvalidTabName": - throw new DotNetNukeException("Page name is invalid.", DotNetNukeErrorCode.PageNameInvalid); - } - } - else if ((Validate_IsCircularReference(tab.PortalID, tab.TabID))) + // Validation: + // Tab name is required + // Tab name is invalid + string invalidType; + if (!TabController.IsValidTabName(tab.TabName, out invalidType)) + { + switch (invalidType) + { + case "EmptyTabName": + throw new DotNetNukeException("Page name is required.", DotNetNukeErrorCode.PageNameRequired); + case "InvalidTabName": + throw new DotNetNukeException("Page name is invalid.", DotNetNukeErrorCode.PageNameInvalid); + } + } + else if (Validate_IsCircularReference(tab.PortalID, tab.TabID)) { throw new DotNetNukeException("Cannot move page to that location.", DotNetNukeErrorCode.PageCircularReference); } @@ -219,60 +237,62 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat if (PortalSettings.Current.ContentLocalizationEnabled) { - if ((!usingDefaultLanguage)) + if (!usingDefaultLanguage) { TabInfo defaultLanguageSelectedTab = tab.DefaultLanguageTab; - if ((defaultLanguageSelectedTab == null)) + if (defaultLanguageSelectedTab == null) { - //get the siblings from the selectedtab and iterate through until you find a sibbling with a corresponding defaultlanguagetab - //if none are found get a list of all the tabs from the default language and then select the last one + // get the siblings from the selectedtab and iterate through until you find a sibbling with a corresponding defaultlanguagetab + // if none are found get a list of all the tabs from the default language and then select the last one var selectedTabSibblings = TabController.Instance.GetTabsByPortal(tab.PortalID).WithCulture(tab.CultureCode, true).AsList(); foreach (TabInfo sibling in selectedTabSibblings) { TabInfo siblingDefaultTab = sibling.DefaultLanguageTab; - if (((siblingDefaultTab != null))) + if (siblingDefaultTab != null) { defaultLanguageSelectedTab = siblingDefaultTab; break; } } - //still haven't found it - if ((defaultLanguageSelectedTab == null)) + // still haven't found it + if (defaultLanguageSelectedTab == null) { var defaultLanguageTabs = TabController.Instance.GetTabsByPortal(tab.PortalID).WithCulture(PortalSettings.Current.DefaultLanguage, true).AsList(); defaultLanguageSelectedTab = defaultLanguageTabs[defaultLanguageTabs.Count]; - //get the last tab + + // get the last tab } } relativeToTab = defaultLanguageSelectedTab; } } - - - if ((location != TabRelativeLocation.NOTSET)) + + if (location != TabRelativeLocation.NOTSET) { - //Check Host tab - don't allow adding before or after - if ((IsHostConsolePage(relativeToTab) && (location == TabRelativeLocation.AFTER || location == TabRelativeLocation.BEFORE))) + // Check Host tab - don't allow adding before or after + if (IsHostConsolePage(relativeToTab) && (location == TabRelativeLocation.AFTER || location == TabRelativeLocation.BEFORE)) { throw new DotNetNukeException("You cannot add or move pages before or after the Host tab.", DotNetNukeErrorCode.HostBeforeAfterError); } TabInfo parentTab = GetParentTab(relativeToTab, location); string permissionList = "ADD,COPY,EDIT,MANAGE"; - //Check permissions for Page Editors when moving or inserting - if ((!PortalSecurity.IsInRole("Administrators"))) + + // Check permissions for Page Editors when moving or inserting + if (!PortalSecurity.IsInRole("Administrators")) { - if (((parentTab == null) || !TabPermissionController.HasTabPermission(parentTab.TabPermissions, permissionList))) + if ((parentTab == null) || !TabPermissionController.HasTabPermission(parentTab.TabPermissions, permissionList)) { - throw new DotNetNukeException("You do not have permissions to add or move pages to this location. You can only add or move pages as children of pages you can edit.", - DotNetNukeErrorCode.PageEditorPermissionError); + throw new DotNetNukeException( + "You do not have permissions to add or move pages to this location. You can only add or move pages as children of pages you can edit.", + DotNetNukeErrorCode.PageEditorPermissionError); } } - if (((parentTab != null))) + if (parentTab != null) { tab.ParentId = parentTab.TabID; tab.Level = parentTab.Level + 1; @@ -284,25 +304,26 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat } } - if ((tab.TabID > Null.NullInteger && tab.TabID == tab.ParentId)) + if (tab.TabID > Null.NullInteger && tab.TabID == tab.ParentId) { throw new DotNetNukeException("Parent page is invalid.", DotNetNukeErrorCode.ParentTabInvalid); } tab.TabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); - //check whether have conflict between tab path and portal alias. - if(TabController.IsDuplicateWithPortalAlias(PortalSettings.Current.PortalId, tab.TabPath)) + + // check whether have conflict between tab path and portal alias. + if (TabController.IsDuplicateWithPortalAlias(PortalSettings.Current.PortalId, tab.TabPath)) { throw new DotNetNukeException("The page path is duplicate with a site alias", DotNetNukeErrorCode.DuplicateWithAlias); } try { - if ((tab.TabID < 0)) + if (tab.TabID < 0) { - if ((tab.TabPermissions.Count == 0 && tab.PortalID != Null.NullInteger)) + if (tab.TabPermissions.Count == 0 && tab.PortalID != Null.NullInteger) { - //Give admin full permission + // Give admin full permission ArrayList permissions = PermissionController.GetPermissionsByTab(); foreach (PermissionInfo permission in permissions) @@ -329,11 +350,11 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat tab.CultureCode = Null.NullString; } - if ((location == TabRelativeLocation.AFTER && (relativeToTab != null))) + if (location == TabRelativeLocation.AFTER && (relativeToTab != null)) { tab.TabID = TabController.Instance.AddTabAfter(tab, relativeToTab.TabID); } - else if ((location == TabRelativeLocation.BEFORE && (relativeToTab != null))) + else if (location == TabRelativeLocation.BEFORE && (relativeToTab != null)) { tab.TabID = TabController.Instance.AddTabBefore(tab, relativeToTab.TabID); } @@ -347,22 +368,22 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat TabController.Instance.CreateLocalizedCopies(tab); } - TabController.Instance.UpdateTabSetting(tab.TabID, "CacheProvider", ""); - TabController.Instance.UpdateTabSetting(tab.TabID, "CacheDuration", ""); + TabController.Instance.UpdateTabSetting(tab.TabID, "CacheProvider", string.Empty); + TabController.Instance.UpdateTabSetting(tab.TabID, "CacheDuration", string.Empty); TabController.Instance.UpdateTabSetting(tab.TabID, "CacheIncludeExclude", "0"); - TabController.Instance.UpdateTabSetting(tab.TabID, "IncludeVaryBy", ""); - TabController.Instance.UpdateTabSetting(tab.TabID, "ExcludeVaryBy", ""); - TabController.Instance.UpdateTabSetting(tab.TabID, "MaxVaryByCount", ""); + TabController.Instance.UpdateTabSetting(tab.TabID, "IncludeVaryBy", string.Empty); + TabController.Instance.UpdateTabSetting(tab.TabID, "ExcludeVaryBy", string.Empty); + TabController.Instance.UpdateTabSetting(tab.TabID, "MaxVaryByCount", string.Empty); } else { TabController.Instance.UpdateTab(tab); - if ((location == TabRelativeLocation.AFTER && (relativeToTab != null))) + if (location == TabRelativeLocation.AFTER && (relativeToTab != null)) { TabController.Instance.MoveTabAfter(tab, relativeToTab.TabID); } - else if ((location == TabRelativeLocation.BEFORE && (relativeToTab != null))) + else if (location == TabRelativeLocation.BEFORE && (relativeToTab != null)) { TabController.Instance.MoveTabBefore(tab, relativeToTab.TabID); } @@ -384,11 +405,11 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; try { - var templateFile = FileManager.Instance.GetFile(Convert.ToInt32(templateFileId)); - xmlDoc.Load(FileManager.Instance.GetFileContent(templateFile)); + var templateFile = FileManager.Instance.GetFile(Convert.ToInt32(templateFileId)); + xmlDoc.Load(FileManager.Instance.GetFileContent(templateFile)); TabController.DeserializePanes(xmlDoc.SelectSingleNode("//portal/tabs/tab/panes"), tab.PortalID, tab.TabID, PortalTemplateModuleAction.Ignore, new Hashtable()); - - //save tab permissions + + // save tab permissions DeserializeTabPermissions(xmlDoc.SelectNodes("//portal/tabs/tab/tabpermissions/permission"), tab); } catch (Exception ex) @@ -397,7 +418,7 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat throw new DotNetNukeException("Unable to process page template.", ex, DotNetNukeErrorCode.DeserializePanesFailed); } } - + return tab.TabID; } @@ -407,20 +428,24 @@ public static bool Validate_IsCircularReference(int portalID, int tabID) { TabInfo objtab = TabController.Instance.GetTab(tabID, portalID, false); - if (((objtab == null))) + if (objtab == null) { return false; } + if (objtab.Level == 0) { return false; } + if (tabID == objtab.ParentId) { return true; } + return Validate_IsCircularReference(portalID, objtab.ParentId); } + return false; } @@ -452,8 +477,10 @@ public static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, Tab { roleId = role.RoleID; } + break; } + if (roleId != int.MinValue && !tab.TabPermissions.Cast().Any(p => p.RoleID == roleId @@ -464,7 +491,7 @@ public static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, Tab TabID = tab.TabID, PermissionID = permissionId, RoleID = roleId, - AllowAccess = allowAccess + AllowAccess = allowAccess, }; tab.TabPermissions.Add(tabPermission); @@ -483,25 +510,30 @@ public DotNetNukeException() { } - public DotNetNukeException(string message) : base(message) + public DotNetNukeException(string message) + : base(message) { } - public DotNetNukeException(string message, Exception innerException) : base(message, innerException) + public DotNetNukeException(string message, Exception innerException) + : base(message, innerException) { } - public DotNetNukeException(string message, DotNetNukeErrorCode errorCode) : base(message) + public DotNetNukeException(string message, DotNetNukeErrorCode errorCode) + : base(message) { - _ErrorCode = errorCode; + this._ErrorCode = errorCode; } - public DotNetNukeException(string message, Exception innerException, DotNetNukeErrorCode errorCode) : base(message, innerException) + public DotNetNukeException(string message, Exception innerException, DotNetNukeErrorCode errorCode) + : base(message, innerException) { - _ErrorCode = errorCode; + this._ErrorCode = errorCode; } - public DotNetNukeException(SerializationInfo info, StreamingContext context) : base(info, context) + public DotNetNukeException(SerializationInfo info, StreamingContext context) + : base(info, context) { } @@ -509,30 +541,8 @@ public DotNetNukeErrorCode ErrorCode { get { - return _ErrorCode; + return this._ErrorCode; } } } - - public enum DotNetNukeErrorCode - { - NotSet, - PageExists, - PageNameRequired, - PageNameInvalid, - DeserializePanesFailed, - PageCircularReference, - ParentTabInvalid, - PageEditorPermissionError, - HostBeforeAfterError, - DuplicateWithAlias - } - - public enum TabRelativeLocation - { - NOTSET, - BEFORE, - AFTER, - CHILD - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs index 2318a44128e..42de159479a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs +++ b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs @@ -1,64 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Reflection; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI; -using DotNetNuke.UI.ControlPanels; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI { + using System; + using System.IO; + using System.Reflection; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI; + using DotNetNuke.UI.ControlPanels; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + public class Utilities - { - #region Private Methods - - private static void AddMessageWindow(Control ctrl) - { - ClientResourceManager.RegisterScript(ctrl.Page, ctrl.ResolveUrl("~/js/dnn.postbackconfirm.js")); - } - - #endregion - - #region Public Methods - + { public static void ApplySkin(Control telerikControl) { - ApplySkin(telerikControl, "", "", ""); + ApplySkin(telerikControl, string.Empty, string.Empty, string.Empty); } public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkinName) { - ApplySkin(telerikControl, "", "", fallBackEmbeddedSkinName); + ApplySkin(telerikControl, string.Empty, string.Empty, fallBackEmbeddedSkinName); } + + private static void AddMessageWindow(Control ctrl) + { + ClientResourceManager.RegisterScript(ctrl.Page, ctrl.ResolveUrl("~/js/dnn.postbackconfirm.js")); + } public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkinName, string controlName) { - ApplySkin(telerikControl, "", controlName, fallBackEmbeddedSkinName); + ApplySkin(telerikControl, string.Empty, controlName, fallBackEmbeddedSkinName); } - //Use selected skin's webcontrol skin if one exists - //or use _default skin's webcontrol skin if one exists - //or use embedded skin + // Use selected skin's webcontrol skin if one exists + // or use _default skin's webcontrol skin if one exists + // or use embedded skin public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkinName, string controlName, string webControlSkinSubFolderName) { PropertyInfo skinProperty = null; @@ -70,70 +58,79 @@ public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkin skinProperty = telerikControl.GetType().GetProperty("Skin"); enableEmbeddedSkinsProperty = telerikControl.GetType().GetProperty("EnableEmbeddedSkins"); - if ((string.IsNullOrEmpty(controlName))) + if (string.IsNullOrEmpty(controlName)) { controlName = telerikControl.GetType().BaseType.Name; - if ((controlName.StartsWith("Rad") || controlName.StartsWith("Dnn"))) + if (controlName.StartsWith("Rad") || controlName.StartsWith("Dnn")) { controlName = controlName.Substring(3); } } - - - string skinVirtualFolder = ""; - if (PortalSettings.Current != null) - skinVirtualFolder = PortalSettings.Current.ActiveTab.SkinPath.Replace('\\', '/').Replace("//", "/"); - else - skinVirtualFolder = telerikControl.ResolveUrl("~/Portals/_default/skins/_default/Aphelia"); // developer skin Aphelia - - string skinName = ""; - string webControlSkinName = ""; + + string skinVirtualFolder = string.Empty; + if (PortalSettings.Current != null) + { + skinVirtualFolder = PortalSettings.Current.ActiveTab.SkinPath.Replace('\\', '/').Replace("//", "/"); + } + else + { + skinVirtualFolder = telerikControl.ResolveUrl("~/Portals/_default/skins/_default/Aphelia"); // developer skin Aphelia + } + + string skinName = string.Empty; + string webControlSkinName = string.Empty; if (skinProperty != null) { var v = skinProperty.GetValue(telerikControl, null); - if (v != null) - webControlSkinName = v.ToString(); - + if (v != null) + { + webControlSkinName = v.ToString(); + } } - if (string.IsNullOrEmpty(webControlSkinName)) webControlSkinName = "default"; - - if ((skinVirtualFolder.EndsWith("/"))) + + if (string.IsNullOrEmpty(webControlSkinName)) + { + webControlSkinName = "default"; + } + + if (skinVirtualFolder.EndsWith("/")) { skinVirtualFolder = skinVirtualFolder.Substring(0, skinVirtualFolder.Length - 1); } + int lastIndex = skinVirtualFolder.LastIndexOf("/"); - if ((lastIndex > -1 && skinVirtualFolder.Length > lastIndex)) + if (lastIndex > -1 && skinVirtualFolder.Length > lastIndex) { skinName = skinVirtualFolder.Substring(skinVirtualFolder.LastIndexOf("/") + 1); } string systemWebControlSkin = string.Empty; - if ((!string.IsNullOrEmpty(skinName) && !string.IsNullOrEmpty(skinVirtualFolder))) + if (!string.IsNullOrEmpty(skinName) && !string.IsNullOrEmpty(skinVirtualFolder)) { - systemWebControlSkin = HttpContext.Current.Server.MapPath(skinVirtualFolder); + systemWebControlSkin = HttpContext.Current.Server.MapPath(skinVirtualFolder); systemWebControlSkin = Path.Combine(systemWebControlSkin, "WebControlSkin"); systemWebControlSkin = Path.Combine(systemWebControlSkin, skinName); systemWebControlSkin = Path.Combine(systemWebControlSkin, webControlSkinSubFolderName); systemWebControlSkin = Path.Combine(systemWebControlSkin, string.Format("{0}.{1}.css", controlName, webControlSkinName)); - //Check if the selected skin has the webcontrol skin - if ((!File.Exists(systemWebControlSkin))) + // Check if the selected skin has the webcontrol skin + if (!File.Exists(systemWebControlSkin)) { - systemWebControlSkin = ""; + systemWebControlSkin = string.Empty; } - //No skin, try default folder - if ((string.IsNullOrEmpty(systemWebControlSkin))) + // No skin, try default folder + if (string.IsNullOrEmpty(systemWebControlSkin)) { skinVirtualFolder = telerikControl.ResolveUrl("~/Portals/_default/Skins/_default"); skinName = "Default"; - if ((skinVirtualFolder.EndsWith("/"))) + if (skinVirtualFolder.EndsWith("/")) { skinVirtualFolder = skinVirtualFolder.Substring(0, skinVirtualFolder.Length - 1); } - if ((!string.IsNullOrEmpty(skinName) && !string.IsNullOrEmpty(skinVirtualFolder))) + if (!string.IsNullOrEmpty(skinName) && !string.IsNullOrEmpty(skinVirtualFolder)) { systemWebControlSkin = HttpContext.Current.Server.MapPath(skinVirtualFolder); systemWebControlSkin = Path.Combine(systemWebControlSkin, "WebControlSkin"); @@ -141,28 +138,28 @@ public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkin systemWebControlSkin = Path.Combine(systemWebControlSkin, webControlSkinSubFolderName); systemWebControlSkin = Path.Combine(systemWebControlSkin, string.Format("{0}.{1}.css", controlName, webControlSkinName)); - if ((!File.Exists(systemWebControlSkin))) + if (!File.Exists(systemWebControlSkin)) { - systemWebControlSkin = ""; + systemWebControlSkin = string.Empty; } } } } - if ((!string.IsNullOrEmpty(systemWebControlSkin))) + if (!string.IsNullOrEmpty(systemWebControlSkin)) { string filePath = Path.Combine(skinVirtualFolder, "WebControlSkin"); filePath = Path.Combine(filePath, skinName); filePath = Path.Combine(filePath, webControlSkinSubFolderName); filePath = Path.Combine(filePath, string.Format("{0}.{1}.css", controlName, webControlSkinName)); filePath = filePath.Replace('\\', '/').Replace("//", "/").TrimEnd('/'); - + if (HttpContext.Current != null && HttpContext.Current.Handler is Page) { ClientResourceManager.RegisterStyleSheet(HttpContext.Current.Handler as Page, filePath, FileOrder.Css.ResourceCss); } - if (((skinProperty != null) && (enableEmbeddedSkinsProperty != null))) + if ((skinProperty != null) && (enableEmbeddedSkinsProperty != null)) { skinApplied = true; skinProperty.SetValue(telerikControl, webControlSkinName, null); @@ -177,12 +174,12 @@ public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkin if (skinProperty != null && enableEmbeddedSkinsProperty != null && !skinApplied) { - if ((string.IsNullOrEmpty(fallBackEmbeddedSkinName))) + if (string.IsNullOrEmpty(fallBackEmbeddedSkinName)) { fallBackEmbeddedSkinName = "Simple"; } - //Set fall back skin Embedded Skin + // Set fall back skin Embedded Skin skinProperty.SetValue(telerikControl, fallBackEmbeddedSkinName, null); enableEmbeddedSkinsProperty.SetValue(telerikControl, true, null); } @@ -196,7 +193,7 @@ public static void CreateThumbnail(FileInfo image, Image img, int maxWidth, int if (image.Width > maxWidth) { img.Width = maxWidth; - img.Height = Convert.ToInt32((image.Height*maxWidth)/(float) image.Width); + img.Height = Convert.ToInt32((image.Height * maxWidth) / (float)image.Width); } else { @@ -209,7 +206,7 @@ public static void CreateThumbnail(FileInfo image, Image img, int maxWidth, int // Portrait if (image.Height > maxHeight) { - img.Width = Convert.ToInt32((image.Width*maxHeight)/(float) image.Height); + img.Width = Convert.ToInt32((image.Width * maxHeight) / (float)image.Height); img.Height = maxHeight; } else @@ -262,7 +259,8 @@ public static string GetOnClientClickConfirm(Control ctrl, string message) public static string GetOnClientClickConfirm(Control ctrl, MessageWindowParameters message) { AddMessageWindow(ctrl); - //function(text, mozEvent, oWidth, oHeight, callerObj, oTitle) + + // function(text, mozEvent, oWidth, oHeight, callerObj, oTitle) return string.Format("return postBackConfirm('{0}', event, '{1}', '{2}', '', '{3}');", message.Message, message.WindowWidth, message.WindowHeight, message.Title); } @@ -273,6 +271,7 @@ public static string GetViewStateAsString(object value, string defaultValue) { _Value = Convert.ToString(value); } + return _Value; } @@ -284,8 +283,6 @@ public static void RegisterAlertOnPageLoad(Control ctrl, string message) public static void RegisterAlertOnPageLoad(Control ctrl, MessageWindowParameters message) { ctrl.Page.ClientScript.RegisterClientScriptBlock(ctrl.GetType(), ctrl.ID + "_AlertOnPageLoad", GetClientAlert(ctrl, message), true); - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs index d4b4737a48a..dd5da6e7575 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs @@ -1,34 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + public class DnnButton : Button, ILocalizable { - private bool _Localize = true; - - #region "Constructors" - + private bool _Localize = true; + public DnnButton() { - CssClass = "CommandButton"; - DisabledCssClass = "CommandButtonDisabled"; - } - - #endregion - - #region "Public Properties" - + this.CssClass = "CommandButton"; + this.DisabledCssClass = "CommandButtonDisabled"; + } + [Bindable(true)] [Category("Appearance")] [DefaultValue("")] @@ -37,11 +26,12 @@ public string ConfirmMessage { get { - return ViewState["ConfirmMessage"] == null ? string.Empty : ViewState["ConfirmMessage"].ToString(); + return this.ViewState["ConfirmMessage"] == null ? string.Empty : this.ViewState["ConfirmMessage"].ToString(); } + set { - ViewState["ConfirmMessage"] = value; + this.ViewState["ConfirmMessage"] = value; } } @@ -53,62 +43,30 @@ public string ConfirmMessage { get { - return ViewState["DisabledCssClass"] == null ? string.Empty : ViewState["DisabledCssClass"].ToString(); + return this.ViewState["DisabledCssClass"] == null ? string.Empty : this.ViewState["DisabledCssClass"].ToString(); } + set { - ViewState["DisabledCssClass"] = value; - } - } - - #endregion - - #region "Protected Methods" - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if ((!Enabled)) - { - CssClass = DisabledCssClass; - } - - if ((!string.IsNullOrEmpty(ConfirmMessage))) - { - string msg = ConfirmMessage; - if ((Localize)) - { - msg = Utilities.GetLocalizedStringFromParent(ConfirmMessage, this); - } - //must be done before render - OnClientClick = Utilities.GetOnClientClickConfirm(this, msg); + this.ViewState["DisabledCssClass"] = value; } - } - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - base.Render(writer); - } - - #endregion - - #region "ILocalizable Implementation" - + } + public bool Localize { get { - if (DesignMode) + if (this.DesignMode) { return false; } - return _Localize; + + return this._Localize; } + set { - _Localize = value; + this._Localize = value; } } @@ -116,34 +74,60 @@ public bool Localize public virtual void LocalizeStrings() { - if ((Localize)) + if (this.Localize) { - if ((!string.IsNullOrEmpty(ToolTip))) + if (!string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Utilities.GetLocalizedStringFromParent(ToolTip, this); + this.ToolTip = Utilities.GetLocalizedStringFromParent(this.ToolTip, this); } - if ((!string.IsNullOrEmpty(Text))) + if (!string.IsNullOrEmpty(this.Text)) { - string unlocalizedText = Text; - Text = Utilities.GetLocalizedStringFromParent(unlocalizedText, this); - if (String.IsNullOrEmpty(Text)) + string unlocalizedText = this.Text; + this.Text = Utilities.GetLocalizedStringFromParent(unlocalizedText, this); + if (string.IsNullOrEmpty(this.Text)) { - Text = unlocalizedText; + this.Text = unlocalizedText; } - if ((string.IsNullOrEmpty(ToolTip))) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Utilities.GetLocalizedStringFromParent(unlocalizedText + ".ToolTip", this); - if (String.IsNullOrEmpty(ToolTip)) + this.ToolTip = Utilities.GetLocalizedStringFromParent(unlocalizedText + ".ToolTip", this); + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = unlocalizedText; + this.ToolTip = unlocalizedText; } } } } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (!this.Enabled) + { + this.CssClass = this.DisabledCssClass; + } + + if (!string.IsNullOrEmpty(this.ConfirmMessage)) + { + string msg = this.ConfirmMessage; + if (this.Localize) + { + msg = Utilities.GetLocalizedStringFromParent(this.ConfirmMessage, this); + } + + // must be done before render + this.OnClientClick = Utilities.GetOnClientClickConfirm(this, msg); + } } - #endregion + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs index 47494449483..468f45e39f4 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs @@ -1,27 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI.WebControls; + public class DnnCheckBox : CheckBox { public string CommandArgument { get { - return Convert.ToString(ViewState["CommandArgument"]); + return Convert.ToString(this.ViewState["CommandArgument"]); } + set { - ViewState["CommandArgument"] = value; + this.ViewState["CommandArgument"] = value; } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnConfirmPasswordOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnConfirmPasswordOptions.cs index bfeeaa94923..59effe1d644 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnConfirmPasswordOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnConfirmPasswordOptions.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Runtime.Serialization; + [DataContract] public class DnnConfirmPasswordOptions { @@ -34,9 +34,8 @@ public class DnnConfirmPasswordOptions public DnnConfirmPasswordOptions() { // all the Confirm Password related resources are located under the Website\App_GlobalResources\WebControls.resx - ConfirmPasswordUnmatchedText = Utilities.GetLocalizedString("ConfirmPasswordUnmatched"); - ConfirmPasswordMatchedText = Utilities.GetLocalizedString("ConfirmPasswordMatched"); + this.ConfirmPasswordUnmatchedText = Utilities.GetLocalizedString("ConfirmPasswordUnmatched"); + this.ConfirmPasswordMatchedText = Utilities.GetLocalizedString("ConfirmPasswordMatched"); } - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs index e2ea595e264..42f5e46ae27 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs @@ -1,27 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.Serialization; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls.Extensions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Runtime.Serialization; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls.Extensions; + [DataContract] public class DnnDropDownListState { @@ -31,159 +30,153 @@ public class DnnDropDownListState [ToolboxData("<{0}:DnnDropDownList runat='server'>")] public class DnnDropDownList : Panel, INamingContainer - { - #region Private Fields - + { private static readonly object EventSelectionChanged = new object(); private readonly Lazy _options = new Lazy(() => new DnnDropDownListOptions()); private DnnGenericHiddenField _stateControl; - private HtmlAnchor _selectedValue; - - #endregion - - #region Protected Properties - - internal DnnDropDownListOptions Options + private HtmlAnchor _selectedValue; + + /// + /// Occurs when the selection from the list control changes between posts to the server. + /// + public event EventHandler SelectionChanged { - get + add { - return _options.Value; + this.Events.AddHandler(EventSelectionChanged, value); } - } - - protected DnnGenericHiddenField StateControl - { - get + + remove { - EnsureChildControls(); - return _stateControl; + this.Events.RemoveHandler(EventSelectionChanged, value); } - } - - private HtmlAnchor SelectedValue + } + + public override ControlCollection Controls { get { - EnsureChildControls(); - return _selectedValue; + this.EnsureChildControls(); + return base.Controls; } } - private bool UseUndefinedItem + /// + /// Gets or sets the selected item in the control, or selects the item in the control. + /// + public ListItem SelectedItem { get { - return ViewState.GetValue("UseUndefinedItem", false); + if (this.StateControl.TypedValue != null && this.StateControl.TypedValue.SelectedItem != null) + { + return new ListItem { Text = this.StateControl.TypedValue.SelectedItem.Value, Value = this.StateControl.TypedValue.SelectedItem.Key }; + } + + return null; } + set { - ViewState.SetValue("UseUndefinedItem", value, false); + this.StateControl.TypedValueOrDefault.SelectedItem = (value == null) ? null : new SerializableKeyValuePair(value.Value, value.Text); } } - - #endregion - - #region Events - - /// - /// Occurs when the selection from the list control changes between posts to the server. - /// - public event EventHandler SelectionChanged + + internal DnnDropDownListOptions Options { - add + get { - Events.AddHandler(EventSelectionChanged, value); + return this._options.Value; } - remove + } + + protected DnnGenericHiddenField StateControl + { + get { - Events.RemoveHandler(EventSelectionChanged, value); + this.EnsureChildControls(); + return this._stateControl; } } - #endregion - - #region Public Properties - - public override ControlCollection Controls + private HtmlAnchor SelectedValue { get { - EnsureChildControls(); - return base.Controls; + this.EnsureChildControls(); + return this._selectedValue; } } - /// - /// Gets the selected item in the control, or selects the item in the control. - /// - public ListItem SelectedItem + private bool UseUndefinedItem { get { - if (StateControl.TypedValue != null && StateControl.TypedValue.SelectedItem != null) - { - return new ListItem { Text = StateControl.TypedValue.SelectedItem.Value, Value = StateControl.TypedValue.SelectedItem.Key }; - } - return null; + return this.ViewState.GetValue("UseUndefinedItem", false); } + set { - StateControl.TypedValueOrDefault.SelectedItem = (value == null) ? null : new SerializableKeyValuePair(value.Value, value.Text); + this.ViewState.SetValue("UseUndefinedItem", value, false); } - } + } /// - /// When this method returns, contains the 32-bit signed integer value equivalent to the number contained in + /// Gets when this method returns, contains the 32-bit signed integer value equivalent to the number contained in /// SelectedItem.Value, if the conversion succeeded, or Null.NullInteger if the conversion failed. /// - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int SelectedItemValueAsInt { get { - if (SelectedItem != null && !string.IsNullOrEmpty(SelectedItem.Value)) + if (this.SelectedItem != null && !string.IsNullOrEmpty(this.SelectedItem.Value)) { int valueAsInt; - var parsed = Int32.TryParse(SelectedItem.Value, out valueAsInt); + var parsed = int.TryParse(this.SelectedItem.Value, out valueAsInt); return parsed ? valueAsInt : Null.NullInteger; } + return Null.NullInteger; } } /// - /// SelectedItem's value when SelectedItem is not explicitly specified (i.e. equals null); - /// Always displayed as first option in the list + /// Gets or sets selectedItem's value when SelectedItem is not explicitly specified (i.e. equals null); + /// Always displayed as first option in the list. /// public ListItem UndefinedItem { get { - return FirstItem; + return this.FirstItem; } + set { - FirstItem = value; - UseUndefinedItem = true; + this.FirstItem = value; + this.UseUndefinedItem = true; } } /// - /// Item to be displayed as first item + /// Gets or sets item to be displayed as first item. /// public ListItem FirstItem { get { - return (Options.ItemList.FirstItem == null) ? null : new ListItem(Options.ItemList.FirstItem.Value, Options.ItemList.FirstItem.Key); + return (this.Options.ItemList.FirstItem == null) ? null : new ListItem(this.Options.ItemList.FirstItem.Value, this.Options.ItemList.FirstItem.Key); } + set { - Options.ItemList.FirstItem = (value == null) ? null : new SerializableKeyValuePair(value.Value, value.Text); - UseUndefinedItem = false; + this.Options.ItemList.FirstItem = (value == null) ? null : new SerializableKeyValuePair(value.Value, value.Text); + this.UseUndefinedItem = false; } } @@ -191,18 +184,18 @@ public ItemListServicesOptions Services { get { - return Options.Services; + return this.Options.Services; } } /// - /// DropDownList Caption when no Item is selected. + /// Sets dropDownList Caption when no Item is selected. /// public string SelectItemDefaultText { set { - Options.SelectItemDefaultText = value; + this.Options.SelectItemDefaultText = value; } } @@ -222,11 +215,12 @@ public bool AutoPostBack { get { - return ViewState.GetValue("AutoPostBack", false); + return this.ViewState.GetValue("AutoPostBack", false); } + set { - ViewState.SetValue("AutoPostBack", value, false); + this.ViewState.SetValue("AutoPostBack", value, false); } } @@ -237,11 +231,12 @@ public virtual bool CausesValidation { get { - return ViewState.GetValue("CausesValidation", false); + return this.ViewState.GetValue("CausesValidation", false); } + set { - ViewState.SetValue("CausesValidation", value, false); + this.ViewState.SetValue("CausesValidation", value, false); } } @@ -252,187 +247,181 @@ public virtual string ValidationGroup { get { - return ViewState.GetValue("ValidationGroup", string.Empty); + return this.ViewState.GetValue("ValidationGroup", string.Empty); } + set { - ViewState.SetValue("ValidationGroup", value, string.Empty); + this.ViewState.SetValue("ValidationGroup", value, string.Empty); } } /// - /// Register a list of JavaScript methods that are executed when the selection from the list control changes on the client. + /// Gets register a list of JavaScript methods that are executed when the selection from the list control changes on the client. /// public List OnClientSelectionChanged { get { - return Options.OnClientSelectionChanged; + return this.Options.OnClientSelectionChanged; } } /// - /// When the tree view in drop down has multiple level nodes, and the initial selected item is a child node. + /// Gets or sets when the tree view in drop down has multiple level nodes, and the initial selected item is a child node. /// we need expand its parent nodes to make it selected. /// public string ExpandPath { get { - return ClientAPI.GetClientVariable(Page, ClientID + "_expandPath"); + return ClientAPI.GetClientVariable(this.Page, this.ClientID + "_expandPath"); } + set { - ClientAPI.RegisterClientVariable(Page, ClientID + "_expandPath", value, true); + ClientAPI.RegisterClientVariable(this.Page, this.ClientID + "_expandPath", value, true); } - } - - #endregion + } - #region Event Handlers + internal static void RegisterClientScript(Page page, string skin) + { + ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList.css", FileOrder.Css.ResourceCss); + if (!string.IsNullOrEmpty(skin)) + { + ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList." + skin + ".css", FileOrder.Css.ResourceCss); + } + + ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.extensions.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.DataStructures.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/jquery.mousewheel.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.TreeView.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.DynamicTreeView.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/Components/DropDownList/dnn.DropDownList.js"); + } + protected override void CreateChildControls() { - Controls.Clear(); + this.Controls.Clear(); var selectedItemPanel = new Panel { CssClass = "selected-item" }; - _selectedValue = new HtmlAnchor { HRef = "javascript:void(0);", Title = LocalizeString("DropDownList.SelectedItemExpandTooltip") }; - _selectedValue.Attributes.Add(HtmlTextWriterAttribute.Class.ToString(), "selected-value"); - _selectedValue.ViewStateMode = ViewStateMode.Disabled; - selectedItemPanel.Controls.Add(_selectedValue); - Controls.Add(selectedItemPanel); - - _stateControl = new DnnGenericHiddenField { ID = "state" }; - _stateControl.ValueChanged += (sender, args) => OnSelectionChanged(EventArgs.Empty); - Controls.Add(_stateControl); + this._selectedValue = new HtmlAnchor { HRef = "javascript:void(0);", Title = LocalizeString("DropDownList.SelectedItemExpandTooltip") }; + this._selectedValue.Attributes.Add(HtmlTextWriterAttribute.Class.ToString(), "selected-value"); + this._selectedValue.ViewStateMode = ViewStateMode.Disabled; + selectedItemPanel.Controls.Add(this._selectedValue); + this.Controls.Add(selectedItemPanel); + this._stateControl = new DnnGenericHiddenField { ID = "state" }; + this._stateControl.ValueChanged += (sender, args) => this.OnSelectionChanged(EventArgs.Empty); + this.Controls.Add(this._stateControl); } protected override void OnInit(EventArgs e) { base.OnInit(e); - StateControl.Value = ""; // for state persistence (stateControl) + this.StateControl.Value = string.Empty; // for state persistence (stateControl) ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); } protected override void OnPreRender(EventArgs e) { - RegisterClientScript(Page, Skin); + RegisterClientScript(this.Page, this.Skin); this.AddCssClass("dnnDropDownList"); base.OnPreRender(e); - RegisterStartupScript(); + this.RegisterStartupScript(); } protected virtual void OnSelectionChanged(EventArgs e) { - var eventHandler = (EventHandler)Events[EventSelectionChanged]; + var eventHandler = (EventHandler)this.Events[EventSelectionChanged]; if (eventHandler == null) { return; } + eventHandler(this, e); - } - - #endregion - - #region Private Methods - + } + private static string LocalizeString(string key) { return Localization.GetString(key, Localization.SharedResourceFile); } - internal static void RegisterClientScript(Page page, string skin) - { - ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList.css", FileOrder.Css.ResourceCss); - if (!string.IsNullOrEmpty(skin)) - { - ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList." + skin + ".css", FileOrder.Css.ResourceCss); - } - ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.css", FileOrder.Css.ResourceCss); - - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.extensions.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.DataStructures.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/jquery.mousewheel.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.TreeView.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.DynamicTreeView.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/Components/DropDownList/dnn.DropDownList.js"); - } - private string GetPostBackScript() { var script = string.Empty; - if (HasAttributes) + if (this.HasAttributes) { - script = Attributes["onchange"]; + script = this.Attributes["onchange"]; if (script != null) { - Attributes.Remove("onchange"); + this.Attributes.Remove("onchange"); } } + var options = new PostBackOptions(this, string.Empty); - if (CausesValidation) + if (this.CausesValidation) { options.PerformValidation = true; - options.ValidationGroup = ValidationGroup; + options.ValidationGroup = this.ValidationGroup; } - if (Page.Form != null) + + if (this.Page.Form != null) { options.AutoPostBack = true; options.TrackFocus = true; } - return script.Append(Page.ClientScript.GetPostBackEventReference(options), "; "); + + return script.Append(this.Page.ClientScript.GetPostBackEventReference(options), "; "); } private void RegisterStartupScript() { - Options.InternalStateFieldId = StateControl.ClientID; + this.Options.InternalStateFieldId = this.StateControl.ClientID; - if (SelectedItem == null && UseUndefinedItem) + if (this.SelectedItem == null && this.UseUndefinedItem) { - SelectedItem = UndefinedItem; + this.SelectedItem = this.UndefinedItem; } - Options.InitialState = new DnnDropDownListState + this.Options.InitialState = new DnnDropDownListState { - SelectedItem = StateControl.TypedValue != null ? StateControl.TypedValue.SelectedItem : null + SelectedItem = this.StateControl.TypedValue != null ? this.StateControl.TypedValue.SelectedItem : null, }; - SelectedValue.InnerText = (SelectedItem != null) ? SelectedItem.Text : Options.SelectItemDefaultText; + this.SelectedValue.InnerText = (this.SelectedItem != null) ? this.SelectedItem.Text : this.Options.SelectItemDefaultText; - Options.Disabled = !Enabled; + this.Options.Disabled = !this.Enabled; - var optionsAsJsonString = Json.Serialize(Options); + var optionsAsJsonString = Json.Serialize(this.Options); var methods = new JavaScriptObjectDictionary(); - if (AutoPostBack) + if (this.AutoPostBack) { - methods.AddMethodBody("onSelectionChangedBackScript", GetPostBackScript()); + methods.AddMethodBody("onSelectionChangedBackScript", this.GetPostBackScript()); } var methodsAsJsonString = methods.ToJsonString(); - var script = string.Format("dnn.createDropDownList('#{0}', {1}, {2});{3}", ClientID, optionsAsJsonString, methodsAsJsonString, Environment.NewLine); + var script = string.Format("dnn.createDropDownList('#{0}', {1}, {2});{3}", this.ClientID, optionsAsJsonString, methodsAsJsonString, Environment.NewLine); - if (ScriptManager.GetCurrent(Page) != null) + if (ScriptManager.GetCurrent(this.Page) != null) { // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), ClientID + "DnnDropDownList", script, true); + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID + "DnnDropDownList", script, true); } else { - Page.ClientScript.RegisterStartupScript(GetType(), ClientID + "DnnDropDownList", script, true); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "DnnDropDownList", script, true); } - } - - #endregion - + } } - } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs index d47fbfdf0ea..a88083da748 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs @@ -1,16 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System.Collections.Generic; + using System.Runtime.Serialization; + [DataContract] public class DnnDropDownListOptions { - [DataMember(Name = "selectedItemCss")] public string SelectedItemCss; @@ -26,30 +25,29 @@ public class DnnDropDownListOptions [DataMember(Name = "initialState")] public DnnDropDownListState InitialState; - private List _onClientSelectionChanged; - - [DataMember(Name = "onSelectionChanged")] - public List OnClientSelectionChanged - { - get - { - return _onClientSelectionChanged ?? (_onClientSelectionChanged = new List()); - } - } - [DataMember(Name = "services")] public ItemListServicesOptions Services; [DataMember(Name = "itemList")] public ItemListOptions ItemList; + private List _onClientSelectionChanged; + public DnnDropDownListOptions() { - SelectedItemCss = "selected-item"; - SelectItemDefaultText = ""; - Services = new ItemListServicesOptions(); - ItemList = new ItemListOptions(); + this.SelectedItemCss = "selected-item"; + this.SelectItemDefaultText = string.Empty; + this.Services = new ItemListServicesOptions(); + this.ItemList = new ItemListOptions(); } + [DataMember(Name = "onSelectionChanged")] + public List OnClientSelectionChanged + { + get + { + return this._onClientSelectionChanged ?? (this._onClientSelectionChanged = new List()); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLabel.cs index 38396570453..92f2e2dd6c7 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLabel.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { public class DnnFieldLabel : DnnLabel @@ -9,7 +9,7 @@ public class DnnFieldLabel : DnnLabel public override void LocalizeStrings() { base.LocalizeStrings(); - Text = Text + Utilities.GetLocalizedString("FieldSuffix.Text"); + this.Text = this.Text + Utilities.GetLocalizedString("FieldSuffix.Text"); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLiteral.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLiteral.cs index d02ecae7350..a202a9a469f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLiteral.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFieldLiteral.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { public class DnnFieldLiteral : DnnLiteral @@ -9,7 +9,7 @@ public class DnnFieldLiteral : DnnLiteral public override void LocalizeStrings() { base.LocalizeStrings(); - Text = Text + Utilities.GetLocalizedString("FieldSuffix.Text"); + this.Text = this.Text + Utilities.GetLocalizedString("FieldSuffix.Text"); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs index 9931437d344..03742168353 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs @@ -1,65 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Common; -using DotNetNuke.Web.UI.WebControls.Extensions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Common; + using DotNetNuke.Web.UI.WebControls.Extensions; + [ToolboxData("<{0}:DnnFileDropDownList runat='server'>")] public class DnnFileDropDownList : DnnDropDownList { - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - SelectItemDefaultText = Localization.GetString("DropDownList.SelectFileDefaultText", Localization.SharedResourceFile); - Services.GetTreeMethod = "ItemListService/GetFiles"; - Services.SearchTreeMethod = "ItemListService/SearchFiles"; - Services.SortTreeMethod = "ItemListService/SortFiles"; - Services.ServiceRoot = "InternalServices"; - Options.ItemList.DisableUnspecifiedOrder = true; - - FolderId = Null.NullInteger; - } - - protected override void OnPreRender(EventArgs e) - { - this.AddCssClass("file"); - - if (IncludeNoneSpecificItem) - { - UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, Null.NullInteger.ToString(CultureInfo.InvariantCulture)); - } - - base.OnPreRender(e); - } - /// - /// Gets the selected Folder in the control, or selects the Folder in the control. + /// Gets or sets the selected Folder in the control, or selects the Folder in the control. /// - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IFileInfo SelectedFile { get { - var fileId = SelectedItemValueAsInt; + var fileId = this.SelectedItemValueAsInt; return (fileId == Null.NullInteger) ? null : FileManager.Instance.GetFile(fileId); } + set { - SelectedItem = (value != null) ? new ListItem() { Text = value.FileName, Value = value.FileId.ToString(CultureInfo.InvariantCulture) } : null; + this.SelectedItem = (value != null) ? new ListItem() { Text = value.FileName, Value = value.FileId.ToString(CultureInfo.InvariantCulture) } : null; } } @@ -67,18 +43,45 @@ public int FolderId { get { - return Services.Parameters.ContainsKey("parentId") ? Convert.ToInt32(Services.Parameters["parentId"]) : Null.NullInteger; + return this.Services.Parameters.ContainsKey("parentId") ? Convert.ToInt32(this.Services.Parameters["parentId"]) : Null.NullInteger; } + set { - Services.Parameters["parentId"] = value.ToString(); + this.Services.Parameters["parentId"] = value.ToString(); } } public string Filter { - get { return Services.Parameters.ContainsKey("filter") ? Services.Parameters["filter"] : string.Empty; } - set { Services.Parameters["filter"] = value; } + get { return this.Services.Parameters.ContainsKey("filter") ? this.Services.Parameters["filter"] : string.Empty; } + set { this.Services.Parameters["filter"] = value; } + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectFileDefaultText", Localization.SharedResourceFile); + this.Services.GetTreeMethod = "ItemListService/GetFiles"; + this.Services.SearchTreeMethod = "ItemListService/SearchFiles"; + this.Services.SortTreeMethod = "ItemListService/SortFiles"; + this.Services.ServiceRoot = "InternalServices"; + this.Options.ItemList.DisableUnspecifiedOrder = true; + + this.FolderId = Null.NullInteger; + } + + protected override void OnPreRender(EventArgs e) + { + this.AddCssClass("file"); + + if (this.IncludeNoneSpecificItem) + { + this.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, Null.NullInteger.ToString(CultureInfo.InvariantCulture)); + } + + base.OnPreRender(e); } public bool IncludeNoneSpecificItem { get; set; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs index 7c8212a6be3..30c525347e9 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs @@ -1,31 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Web.UI; - -using DotNetNuke.UI.WebControls; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Web.UI; + + using DotNetNuke.UI.WebControls; + public class DnnFileEditControl : IntegerEditControl - { - #region Private Fields - - private DnnFilePickerUploader _fileControl; - //private DnnFilePicker _fileControl; - - #endregion - - #region Public Properties - + { + private DnnFilePickerUploader _fileControl; + + // private DnnFilePicker _fileControl; + /// ----------------------------------------------------------------------------- /// /// Gets or sets the current file extension filter. @@ -38,37 +27,62 @@ public class DnnFileEditControl : IntegerEditControl /// Gets or sets the current file path. /// /// ----------------------------------------------------------------------------- - public string FilePath { get; set; } - - #endregion - - #region Protected Methods - + public string FilePath { get; set; } + /// ----------------------------------------------------------------------------- /// - /// Creates the control contained within this control + /// Loads the Post Back Data and determines whether the value has change. + /// + /// + /// In this case because the is a contained control, we do not need + /// to process the PostBackData (it has been handled by the File Control). We just use + /// this method as the Framework calls it for us. + /// + /// A key to the PostBack Data to load. + /// A name value collection of postback data. + /// + /// ----------------------------------------------------------------------------- + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + bool dataChanged = false; + string presentValue = this.StringValue; + + // string postedValue = postCollection[string.Format("{0}FileControl$dnnFileUploadFileId", postDataKey)]; + string postedValue = this._fileControl.FileID.ToString(); + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } + + /// ----------------------------------------------------------------------------- + /// + /// Creates the control contained within this control. /// /// ----------------------------------------------------------------------------- protected override void CreateChildControls() { - //First clear the controls collection - Controls.Clear(); + // First clear the controls collection + this.Controls.Clear(); - var userControl = Page.LoadControl("~/controls/filepickeruploader.ascx"); - _fileControl = userControl as DnnFilePickerUploader; + var userControl = this.Page.LoadControl("~/controls/filepickeruploader.ascx"); + this._fileControl = userControl as DnnFilePickerUploader; - if (_fileControl != null) + if (this._fileControl != null) { - _fileControl.ID = string.Format("{0}FileControl", ID); - _fileControl.FileFilter = FileFilter; - _fileControl.FilePath = FilePath; - _fileControl.FileID = IntegerValue; - _fileControl.UsePersonalFolder = true; - _fileControl.User = User; - _fileControl.Required = true; - - //Add table to Control - Controls.Add(_fileControl); + this._fileControl.ID = string.Format("{0}FileControl", this.ID); + this._fileControl.FileFilter = this.FileFilter; + this._fileControl.FilePath = this.FilePath; + this._fileControl.FileID = this.IntegerValue; + this._fileControl.UsePersonalFolder = true; + this._fileControl.User = this.User; + this._fileControl.Required = true; + + // Add table to Control + this.Controls.Add(this._fileControl); } base.CreateChildControls(); @@ -76,7 +90,7 @@ protected override void CreateChildControls() protected override void OnInit(EventArgs e) { - EnsureChildControls(); + this.EnsureChildControls(); base.OnInit(e); } @@ -89,55 +103,23 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - _fileControl.FileID = IntegerValue; + this._fileControl.FileID = this.IntegerValue; - if (Page != null) + if (this.Page != null) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } /// ----------------------------------------------------------------------------- /// - /// Renders the control in edit mode + /// Renders the control in edit mode. /// - /// An HtmlTextWriter to render the control to + /// An HtmlTextWriter to render the control to. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { - RenderChildren(writer); - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// Loads the Post Back Data and determines whether the value has change - /// - /// - /// In this case because the is a contained control, we do not need - /// to process the PostBackData (it has been handled by the File Control). We just use - /// this method as the Framework calls it for us. - /// - /// A key to the PostBack Data to load - /// A name value collection of postback data - /// ----------------------------------------------------------------------------- - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - bool dataChanged = false; - string presentValue = StringValue; - //string postedValue = postCollection[string.Format("{0}FileControl$dnnFileUploadFileId", postDataKey)]; - string postedValue = _fileControl.FileID.ToString(); - if (!presentValue.Equals(postedValue)) - { - Value = postedValue; - dataChanged = true; - } - return dataChanged; - } - - #endregion + this.RenderChildren(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs index 2ff762bf2db..1a5be592cb7 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs @@ -1,909 +1,890 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; -using DotNetNuke.Entities.Host; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.IO; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + + /// + /// The FilePicker Class provides a File Picker Control for DotNetNuke. + /// + public class DnnFilePicker : CompositeControl, ILocalizable + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DnnFilePicker)); + + private Panel _pnlContainer; + private Panel _pnlLeftDiv; + private Panel _pnlFolder; + + /// + /// Represents a possible mode for the File Control. + /// + protected enum FileControlMode + { + /// + /// The File Control is in its Normal mode + /// + Normal, + + /// + /// The File Control is in the Upload File mode + /// + UpLoadFile, + + /// + /// The File Control is in the Preview mode + /// + Preview, + } + private Label _lblFolder; + private DropDownList _cboFolders; + private Panel _pnlFile; + private Label _lblFile; + private DropDownList _cboFiles; + private Panel _pnlUpload; + private HtmlInputFile _txtFile; + private Panel _pnlButtons; + private LinkButton _cmdCancel; + private LinkButton _cmdSave; + private LinkButton _cmdUpload; + private Panel _pnlMessage; + private Label _lblMessage; + private Panel _pnlRightDiv; + private Image _imgPreview; + private bool _localize = true; + private int _maxHeight = 100; + private int _maxWidth = 135; + + public int MaxHeight + { + get + { + return this._maxHeight; + } + + set + { + this._maxHeight = value; + } + } - /// - /// The FilePicker Class provides a File Picker Control for DotNetNuke - /// - public class DnnFilePicker : CompositeControl, ILocalizable - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DnnFilePicker)); - - #region Public Enums - - /// - /// Represents a possible mode for the File Control - /// - protected enum FileControlMode - { - /// - /// The File Control is in its Normal mode - /// - Normal, - - /// - /// The File Control is in the Upload File mode - /// - UpLoadFile, - - /// - /// The File Control is in the Preview mode - /// - Preview - } - - #endregion - - #region Private Members - - #region Controls - - private Panel _pnlContainer; - private Panel _pnlLeftDiv; - private Panel _pnlFolder; - private Label _lblFolder; - private DropDownList _cboFolders; - private Panel _pnlFile; - private Label _lblFile; - private DropDownList _cboFiles; - private Panel _pnlUpload; - private HtmlInputFile _txtFile; - private Panel _pnlButtons; - private LinkButton _cmdCancel; - private LinkButton _cmdSave; - private LinkButton _cmdUpload; - private Panel _pnlMessage; - private Label _lblMessage; - private Panel _pnlRightDiv; - private Image _imgPreview; - - #endregion - - private bool _localize = true; - private int _maxHeight = 100; - private int _maxWidth = 135; - - #endregion - - #region Protected Properties - - /// - /// Gets whether the control is on a Host or Portal Tab - /// - /// A Boolean - protected bool IsHost - { - get - { - var isHost = Globals.IsHostTab(PortalSettings.ActiveTab.TabID); - //if not host tab but current edit user is a host user, then return true - if(!isHost && User != null && User.IsSuperUser) + public int MaxWidth + { + get + { + return this._maxWidth; + } + + set + { + this._maxWidth = value; + } + } + + /// + /// Gets a value indicating whether gets whether the control is on a Host or Portal Tab. + /// + /// A Boolean. + protected bool IsHost + { + get + { + var isHost = Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); + + // if not host tab but current edit user is a host user, then return true + if (!isHost && this.User != null && this.User.IsSuperUser) { isHost = true; } - return isHost; - } - } - - public int MaxHeight - { - get - { - return _maxHeight; - } - set - { - _maxHeight = value; - } - } - - public int MaxWidth - { - get - { - return _maxWidth; - } - set - { - _maxWidth = value; - } - } - - /// - /// Gets or sets the current mode of the control - /// - /// - /// Defaults to FileControlMode.Normal - /// - /// A FileControlMode enum - protected FileControlMode Mode - { - get - { - return ViewState["Mode"] == null ? FileControlMode.Normal : (FileControlMode) ViewState["Mode"]; - } - set - { - ViewState["Mode"] = value; - } - } - - /// - /// Gets the root folder for the control - /// - /// A String - protected string ParentFolder - { - get - { - return IsHost ? Globals.HostMapPath : PortalSettings.HomeDirectoryMapPath; - } - } - - /// - /// Gets or sets the file PortalId to use - /// - /// - /// Defaults to PortalSettings.PortalId - /// - /// An Integer + return isHost; + } + } + + /// + /// Gets or sets the class to be used for the Labels. + /// + /// + /// Defaults to 'CommandButton'. + /// + /// A String. + public string CommandCssClass + { + get + { + var cssClass = Convert.ToString(this.ViewState["CommandCssClass"]); + return string.IsNullOrEmpty(cssClass) ? "dnnSecondaryAction" : cssClass; + } + + set + { + this.ViewState["CommandCssClass"] = value; + } + } + + /// + /// Gets or sets the file Filter to use. + /// + /// + /// Defaults to ''. + /// + /// a comma seperated list of file extenstions no wildcards or periods e.g. "jpg,png,gif". + public string FileFilter + { + get + { + return this.ViewState["FileFilter"] != null ? (string)this.ViewState["FileFilter"] : string.Empty; + } + + set + { + this.ViewState["FileFilter"] = value; + } + } + + /// + /// Gets or sets the current mode of the control. + /// + /// + /// Defaults to FileControlMode.Normal. + /// + /// A FileControlMode enum. + protected FileControlMode Mode + { + get + { + return this.ViewState["Mode"] == null ? FileControlMode.Normal : (FileControlMode)this.ViewState["Mode"]; + } + + set + { + this.ViewState["Mode"] = value; + } + } + + /// + /// Gets the root folder for the control. + /// + /// A String. + protected string ParentFolder + { + get + { + return this.IsHost ? Globals.HostMapPath : this.PortalSettings.HomeDirectoryMapPath; + } + } + + /// + /// Gets the file PortalId to use. + /// + /// + /// Defaults to PortalSettings.PortalId. + /// + /// An Integer. protected int PortalId - { - get - { - if ((Page.Request.QueryString["pid"] != null) && (Globals.IsHostTab(PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + { + get + { + if ((this.Page.Request.QueryString["pid"] != null) && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + { + return int.Parse(this.Page.Request.QueryString["pid"]); + } + + if (!this.IsHost) + { + return this.PortalSettings.PortalId; + } + + return Null.NullInteger; + } + } + + /// + /// Gets the current Portal Settings. + /// + protected PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } + + /// + /// Gets or sets the FileID for the control. + /// + /// An Integer. + public int FileID + { + get + { + this.EnsureChildControls(); + if (this.ViewState["FileID"] == null) + { + // Get FileId from the file combo + var fileId = Null.NullInteger; + if (this._cboFiles.SelectedItem != null) + { + fileId = int.Parse(this._cboFiles.SelectedItem.Value); + } + + this.ViewState["FileID"] = fileId; + } + + return Convert.ToInt32(this.ViewState["FileID"]); + } + + set + { + this.EnsureChildControls(); + this.ViewState["FileID"] = value; + if (string.IsNullOrEmpty(this.FilePath)) + { + var fileInfo = FileManager.Instance.GetFile(value); + if (fileInfo != null) + { + this.SetFilePath(fileInfo.Folder + fileInfo.FileName); + } + } + } + } + + /// + /// Gets or sets the FilePath for the control. + /// + /// A String. + public string FilePath + { + get + { + return Convert.ToString(this.ViewState["FilePath"]); + } + + set + { + this.ViewState["FilePath"] = value; + } + } + + /// + /// Gets or sets a value indicating whether gets or sets whether to Include Personal Folder. + /// + /// + /// Defaults to false. + /// + /// A Boolean. + public bool UsePersonalFolder + { + get + { + return this.ViewState["UsePersonalFolder"] != null && Convert.ToBoolean(this.ViewState["UsePersonalFolder"]); + } + + set + { + this.ViewState["UsePersonalFolder"] = value; + } + } + + /// + /// Gets or sets the class to be used for the Labels. + /// + /// A String. + public string LabelCssClass + { + get + { + var cssClass = Convert.ToString(this.ViewState["LabelCssClass"]); + return string.IsNullOrEmpty(cssClass) ? string.Empty : cssClass; + } + + set + { + this.ViewState["LabelCssClass"] = value; + } + } + + public string Permissions + { + get + { + var permissions = Convert.ToString(this.ViewState["Permissions"]); + return string.IsNullOrEmpty(permissions) ? "BROWSE,ADD" : permissions; + } + + set + { + this.ViewState["Permissions"] = value; + } + } + + /// + /// Gets or sets a value indicating whether gets or sets whether the combos have a "Not Specified" option. + /// + /// + /// Defaults to True (ie no "Not Specified"). + /// + /// A Boolean. + public bool Required + { + get + { + return this.ViewState["Required"] != null && Convert.ToBoolean(this.ViewState["Required"]); + } + + set + { + this.ViewState["Required"] = value; + } + } + + public bool ShowFolders + { + get + { + return this.ViewState["ShowFolders"] == null || Convert.ToBoolean(this.ViewState["ShowFolders"]); + } + + set + { + this.ViewState["ShowFolders"] = value; + } + } + + /// + /// Gets or sets a value indicating whether gets or sets whether to Show the Upload Button. + /// + /// + /// Defaults to True. + /// + /// A Boolean. + public bool ShowUpLoad + { + get + { + return this.ViewState["ShowUpLoad"] == null || Convert.ToBoolean(this.ViewState["ShowUpLoad"]); + } + + set + { + this.ViewState["ShowUpLoad"] = value; + } + } + + public UserInfo User { get; set; } + + public bool Localize + { + get + { + return this._localize; + } + + set + { + this._localize = value; + } + } + + public string LocalResourceFile { get; set; } + + public virtual void LocalizeStrings() + { + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + this.EnsureChildControls(); + } + + /// + /// CreateChildControls overrides the Base class's method to correctly build the + /// control based on the configuration. + /// + protected override void CreateChildControls() + { + // First clear the controls collection + this.Controls.Clear(); + + this._pnlContainer = new Panel { CssClass = "dnnFilePicker" }; + + this._pnlLeftDiv = new Panel { CssClass = "dnnLeft" }; + + this.AddFolderArea(); + this.AddFileAndUploadArea(); + this.AddButtonArea(); + this.AddMessageRow(); + + this._pnlContainer.Controls.Add(this._pnlLeftDiv); + + this._pnlRightDiv = new Panel { CssClass = "dnnLeft" }; + + this.GeneratePreviewImage(); + + this._pnlContainer.Controls.Add(this._pnlRightDiv); + + this.Controls.Add(this._pnlContainer); + + base.CreateChildControls(); + } + + /// + /// AddButton adds a button to the Command Row. + /// + /// The button to add to the Row. + private void AddButton(ref LinkButton button) + { + button = new LinkButton { EnableViewState = false, CausesValidation = false }; + button.ControlStyle.CssClass = this.CommandCssClass; + button.Visible = false; + + this._pnlButtons.Controls.Add(button); + } + + /// + /// AddCommandRow adds the Command Row. + /// + private void AddButtonArea() + { + this._pnlButtons = new Panel { Visible = false }; + + this.AddButton(ref this._cmdUpload); + this._cmdUpload.Click += this.UploadFile; + + this.AddButton(ref this._cmdSave); + this._cmdSave.Click += this.SaveFile; + + this.AddButton(ref this._cmdCancel); + this._cmdCancel.Click += this.CancelUpload; + + this._pnlLeftDiv.Controls.Add(this._pnlButtons); + } + + /// + /// AddFileRow adds the Files Row. + /// + private void AddFileAndUploadArea() + { + // Create Url Div + this._pnlFile = new Panel { CssClass = "dnnFormItem" }; + + // Create File Label + this._lblFile = new Label { EnableViewState = false }; + this._pnlFile.Controls.Add(this._lblFile); + + // Create Files Combo + this._cboFiles = new DropDownList { ID = "File", DataTextField = "Text", DataValueField = "Value", AutoPostBack = true }; + this._cboFiles.SelectedIndexChanged += this.FileChanged; + this._pnlFile.Controls.Add(this._cboFiles); + + this._pnlLeftDiv.Controls.Add(this._pnlFile); + + // Create Upload Div + this._pnlUpload = new Panel { CssClass = "dnnFormItem" }; + + // Create Upload Box + this._txtFile = new HtmlInputFile(); + this._txtFile.Attributes.Add("size", "13"); + this._pnlUpload.Controls.Add(this._txtFile); + + this._pnlLeftDiv.Controls.Add(this._pnlUpload); + } + + /// + /// AddFolderRow adds the Folders Row. + /// + private void AddFolderArea() + { + // Create Url Div + this._pnlFolder = new Panel { CssClass = "dnnFormItem" }; + + // Create Folder Label + this._lblFolder = new Label { EnableViewState = false }; + this._pnlFolder.Controls.Add(this._lblFolder); + + // Create Folders Combo + this._cboFolders = new DropDownList { ID = "Folder", AutoPostBack = true }; + this._cboFolders.SelectedIndexChanged += this.FolderChanged; + this._pnlFolder.Controls.Add(this._cboFolders); + + // add to left div + this._pnlLeftDiv.Controls.Add(this._pnlFolder); + + // Load Folders + this.LoadFolders(); + } + + /// + /// + /// + private void GeneratePreviewImage() + { + this._imgPreview = new Image(); + this._pnlRightDiv.Controls.Add(this._imgPreview); + } + + /// + /// AddMessageRow adds the Message Row. + /// + private void AddMessageRow() + { + this._pnlMessage = new Panel { CssClass = "dnnFormMessage dnnFormWarning" }; + + // Create Label + this._lblMessage = new Label { EnableViewState = false, Text = string.Empty }; + this._pnlMessage.Controls.Add(this._lblMessage); + + this._pnlLeftDiv.Controls.Add(this._pnlMessage); + } + + private bool IsUserFolder(string folderPath) + { + UserInfo user = this.User ?? UserController.Instance.GetCurrentUserInfo(); + return folderPath.StartsWith("users/", StringComparison.InvariantCultureIgnoreCase) && folderPath.EndsWith(string.Format("/{0}/", user.UserID)); + } + + private void LoadFiles() + { + int effectivePortalId = this.PortalId; + if (this.IsUserFolder(this._cboFolders.SelectedItem.Value)) + { + effectivePortalId = PortalController.GetEffectivePortalId(this.PortalId); + } + + this._cboFiles.DataSource = Globals.GetFileList(effectivePortalId, this.FileFilter, !this.Required, this._cboFolders.SelectedItem.Value); + this._cboFiles.DataBind(); + } + + /// + /// LoadFolders fetches the list of folders from the Database. + /// + private void LoadFolders() + { + UserInfo user = this.User ?? UserController.Instance.GetCurrentUserInfo(); + this._cboFolders.Items.Clear(); + + // Add Personal Folder + if (this.UsePersonalFolder) + { + var userFolder = FolderManager.Instance.GetUserFolder(user).FolderPath; + var userFolderItem = this._cboFolders.Items.FindByValue(userFolder); + if (userFolderItem != null) + { + userFolderItem.Text = Utilities.GetLocalizedString("MyFolder"); + } + else { - return Int32.Parse(Page.Request.QueryString["pid"]); + // Add DummyFolder + this._cboFolders.Items.Add(new ListItem(Utilities.GetLocalizedString("MyFolder"), userFolder)); } - if (!IsHost) - { - return PortalSettings.PortalId; - } - - return Null.NullInteger; - } - } - - /// - /// Gets the current Portal Settings - /// - protected PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - - #endregion - - #region Public Properties - - /// - /// Gets or sets the class to be used for the Labels - /// - /// - /// Defaults to 'CommandButton' - /// - /// A String - public string CommandCssClass - { - get - { - var cssClass = Convert.ToString(ViewState["CommandCssClass"]); - return string.IsNullOrEmpty(cssClass) ? "dnnSecondaryAction" : cssClass; - } - set - { - ViewState["CommandCssClass"] = value; - } - } - - /// - /// Gets or sets the file Filter to use - /// - /// - /// Defaults to '' - /// - /// a comma seperated list of file extenstions no wildcards or periods e.g. "jpg,png,gif" - public string FileFilter - { - get - { - return ViewState["FileFilter"] != null ? (string) ViewState["FileFilter"] : ""; - } - set - { - ViewState["FileFilter"] = value; - } - } - - /// - /// Gets or sets the FileID for the control - /// - /// An Integer - public int FileID - { - get - { - EnsureChildControls(); - if (ViewState["FileID"] == null) - { - //Get FileId from the file combo - var fileId = Null.NullInteger; - if (_cboFiles.SelectedItem != null) - { - fileId = Int32.Parse(_cboFiles.SelectedItem.Value); - } - ViewState["FileID"] = fileId; - } - return Convert.ToInt32(ViewState["FileID"]); - } - set - { - EnsureChildControls(); - ViewState["FileID"] = value; - if (string.IsNullOrEmpty(FilePath)) - { - var fileInfo = FileManager.Instance.GetFile(value); - if (fileInfo != null) - { - SetFilePath(fileInfo.Folder + fileInfo.FileName); - } - } - } - } - - /// - /// Gets or sets the FilePath for the control - /// - /// A String - public string FilePath - { - get - { - return Convert.ToString(ViewState["FilePath"]); - } - set - { - ViewState["FilePath"] = value; - } - } - - /// - /// Gets or sets whether to Include Personal Folder - /// - /// - /// Defaults to false - /// - /// A Boolean - public bool UsePersonalFolder - { - get - { - return ViewState["UsePersonalFolder"] != null && Convert.ToBoolean(ViewState["UsePersonalFolder"]); - } - set - { - ViewState["UsePersonalFolder"] = value; - } - } - - /// - /// Gets or sets the class to be used for the Labels - /// - /// A String - public string LabelCssClass - { - get - { - var cssClass = Convert.ToString(ViewState["LabelCssClass"]); - return string.IsNullOrEmpty(cssClass) ? "" : cssClass; - } - set - { - ViewState["LabelCssClass"] = value; - } - } - - public string Permissions - { - get - { - var permissions = Convert.ToString(ViewState["Permissions"]); - return string.IsNullOrEmpty(permissions) ? "BROWSE,ADD" : permissions; - } - set - { - ViewState["Permissions"] = value; - } - } - - /// - /// Gets or sets whether the combos have a "Not Specified" option - /// - /// - /// Defaults to True (ie no "Not Specified") - /// - /// A Boolean - public bool Required - { - get - { - return ViewState["Required"] != null && Convert.ToBoolean(ViewState["Required"]); - } - set - { - ViewState["Required"] = value; - } - } - - public bool ShowFolders - { - get - { - return ViewState["ShowFolders"] == null || Convert.ToBoolean(ViewState["ShowFolders"]); - } - set - { - ViewState["ShowFolders"] = value; - } - } - - /// - /// Gets or sets whether to Show the Upload Button - /// - /// - /// Defaults to True - /// - /// A Boolean - public bool ShowUpLoad - { - get - { - return ViewState["ShowUpLoad"] == null || Convert.ToBoolean(ViewState["ShowUpLoad"]); - } - set - { - ViewState["ShowUpLoad"] = value; - } - } - - public UserInfo User { get; set; } - - #endregion - - #region Private Methods - - /// - /// AddButton adds a button to the Command Row - /// - /// The button to add to the Row - private void AddButton(ref LinkButton button) - { - button = new LinkButton {EnableViewState = false, CausesValidation = false}; - button.ControlStyle.CssClass = CommandCssClass; - button.Visible = false; - - _pnlButtons.Controls.Add(button); - } - - /// - /// AddCommandRow adds the Command Row - /// - private void AddButtonArea() - { - _pnlButtons = new Panel {Visible = false}; - - AddButton(ref _cmdUpload); - _cmdUpload.Click += UploadFile; - - AddButton(ref _cmdSave); - _cmdSave.Click += SaveFile; - - AddButton(ref _cmdCancel); - _cmdCancel.Click += CancelUpload; - - _pnlLeftDiv.Controls.Add(_pnlButtons); - } - - /// - /// AddFileRow adds the Files Row - /// - private void AddFileAndUploadArea() - { - //Create Url Div - _pnlFile = new Panel {CssClass = "dnnFormItem"}; - - //Create File Label - _lblFile = new Label {EnableViewState = false}; - _pnlFile.Controls.Add(_lblFile); - - //Create Files Combo - _cboFiles = new DropDownList {ID = "File", DataTextField = "Text", DataValueField = "Value", AutoPostBack = true}; - _cboFiles.SelectedIndexChanged += FileChanged; - _pnlFile.Controls.Add(_cboFiles); - - _pnlLeftDiv.Controls.Add(_pnlFile); - - //Create Upload Div - _pnlUpload = new Panel {CssClass = "dnnFormItem"}; - - //Create Upload Box - _txtFile = new HtmlInputFile(); - _txtFile.Attributes.Add("size", "13"); - _pnlUpload.Controls.Add(_txtFile); - - _pnlLeftDiv.Controls.Add(_pnlUpload); - } - - /// - /// AddFolderRow adds the Folders Row - /// - private void AddFolderArea() - { - //Create Url Div - _pnlFolder = new Panel {CssClass = "dnnFormItem"}; - - //Create Folder Label - _lblFolder = new Label {EnableViewState = false}; - _pnlFolder.Controls.Add(_lblFolder); - - //Create Folders Combo - _cboFolders = new DropDownList {ID = "Folder", AutoPostBack = true}; - _cboFolders.SelectedIndexChanged += FolderChanged; - _pnlFolder.Controls.Add(_cboFolders); - - // add to left div - _pnlLeftDiv.Controls.Add(_pnlFolder); - - //Load Folders - LoadFolders(); - } - - /// - /// - /// - private void GeneratePreviewImage() - { - _imgPreview = new Image(); - _pnlRightDiv.Controls.Add(_imgPreview); - } - - /// - /// AddMessageRow adds the Message Row - /// - private void AddMessageRow() - { - _pnlMessage = new Panel {CssClass = "dnnFormMessage dnnFormWarning"}; - - //Create Label - _lblMessage = new Label {EnableViewState = false, Text = ""}; - _pnlMessage.Controls.Add(_lblMessage); - - _pnlLeftDiv.Controls.Add(_pnlMessage); - } - - private bool IsUserFolder(string folderPath) - { - UserInfo user = User ?? UserController.Instance.GetCurrentUserInfo(); - return (folderPath.StartsWith("users/", StringComparison.InvariantCultureIgnoreCase) && folderPath.EndsWith(string.Format("/{0}/", user.UserID))); - } - - private void LoadFiles() - { - int effectivePortalId = PortalId; - if (IsUserFolder(_cboFolders.SelectedItem.Value)) - { - effectivePortalId = PortalController.GetEffectivePortalId(PortalId); - } - _cboFiles.DataSource = Globals.GetFileList(effectivePortalId, FileFilter, !Required, _cboFolders.SelectedItem.Value); - _cboFiles.DataBind(); - } - - /// - /// LoadFolders fetches the list of folders from the Database - /// - private void LoadFolders() - { - UserInfo user = User ?? UserController.Instance.GetCurrentUserInfo(); - _cboFolders.Items.Clear(); - - //Add Personal Folder - if (UsePersonalFolder) - { - var userFolder = FolderManager.Instance.GetUserFolder(user).FolderPath; - var userFolderItem = _cboFolders.Items.FindByValue(userFolder); - if (userFolderItem != null) - { - userFolderItem.Text = Utilities.GetLocalizedString("MyFolder"); - } - else - { - //Add DummyFolder - _cboFolders.Items.Add(new ListItem(Utilities.GetLocalizedString("MyFolder"), userFolder)); - } - } - else - { - var folders = FolderManager.Instance.GetFolders(PortalId, "READ,ADD", user.UserID); - foreach (FolderInfo folder in folders) - { - var folderItem = new ListItem - { - Text = - folder.FolderPath == Null.NullString - ? Utilities.GetLocalizedString("PortalRoot") - : folder.DisplayPath, - Value = folder.FolderPath - }; - _cboFolders.Items.Add(folderItem); - } - } - } - - /// - /// SetFilePath sets the FilePath property - /// - /// - /// This overload uses the selected item in the Folder combo - /// - private void SetFilePath() - { - SetFilePath(_cboFiles.SelectedItem.Text); - } - - /// - /// SetFilePath sets the FilePath property - /// - /// - /// This overload allows the caller to specify a file - /// - /// The filename to use in setting the property - private void SetFilePath(string fileName) - { - if (string.IsNullOrEmpty(_cboFolders.SelectedItem.Value)) - { - FilePath = fileName; - } - else - { - FilePath = (_cboFolders.SelectedItem.Value + "/") + fileName; - } - } - - /// - /// ShowButton configures and displays a button - /// - /// The button to configure - /// The command name (amd key) of the button - private void ShowButton(LinkButton button, string command) - { - button.Visible = true; - if (!string.IsNullOrEmpty(command)) - { - button.Text = Utilities.GetLocalizedString(command); - } - AJAX.RegisterPostBackControl(button); - _pnlButtons.Visible = true; - } - - /// - /// ShowImage displays the Preview Image - /// - private void ShowImage() - { - var image = (FileInfo)FileManager.Instance.GetFile(FileID); + } + else + { + var folders = FolderManager.Instance.GetFolders(this.PortalId, "READ,ADD", user.UserID); + foreach (FolderInfo folder in folders) + { + var folderItem = new ListItem + { + Text = + folder.FolderPath == Null.NullString + ? Utilities.GetLocalizedString("PortalRoot") + : folder.DisplayPath, + Value = folder.FolderPath, + }; + this._cboFolders.Items.Add(folderItem); + } + } + } + + /// + /// SetFilePath sets the FilePath property. + /// + /// + /// This overload uses the selected item in the Folder combo. + /// + private void SetFilePath() + { + this.SetFilePath(this._cboFiles.SelectedItem.Text); + } + + /// + /// SetFilePath sets the FilePath property. + /// + /// + /// This overload allows the caller to specify a file. + /// + /// The filename to use in setting the property. + private void SetFilePath(string fileName) + { + if (string.IsNullOrEmpty(this._cboFolders.SelectedItem.Value)) + { + this.FilePath = fileName; + } + else + { + this.FilePath = (this._cboFolders.SelectedItem.Value + "/") + fileName; + } + } + + /// + /// ShowButton configures and displays a button. + /// + /// The button to configure. + /// The command name (amd key) of the button. + private void ShowButton(LinkButton button, string command) + { + button.Visible = true; + if (!string.IsNullOrEmpty(command)) + { + button.Text = Utilities.GetLocalizedString(command); + } + + AJAX.RegisterPostBackControl(button); + this._pnlButtons.Visible = true; + } + + /// + /// ShowImage displays the Preview Image. + /// + private void ShowImage() + { + var image = (FileInfo)FileManager.Instance.GetFile(this.FileID); if (image != null) { - _imgPreview.ImageUrl = FileManager.Instance.GetUrl(image); + this._imgPreview.ImageUrl = FileManager.Instance.GetUrl(image); try { - Utilities.CreateThumbnail(image, _imgPreview, MaxWidth, MaxHeight); + Utilities.CreateThumbnail(image, this._imgPreview, this.MaxWidth, this.MaxHeight); } catch (Exception) { Logger.WarnFormat("Unable to create thumbnail for {0}", image.PhysicalPath); - _pnlRightDiv.Visible = false; + this._pnlRightDiv.Visible = false; } - } else { - _imgPreview.Visible = false; + this._imgPreview.Visible = false; Panel imageHolderPanel = new Panel { CssClass = "dnnFilePickerImageHolder" }; - _pnlRightDiv.Controls.Add(imageHolderPanel); - _pnlRightDiv.Visible = true; - } - } - - #endregion - - #region Protected Methods - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - LocalResourceFile = Utilities.GetLocalResourceFile(this); - EnsureChildControls(); - } - - /// - /// CreateChildControls overrides the Base class's method to correctly build the - /// control based on the configuration - /// - protected override void CreateChildControls() - { - //First clear the controls collection - Controls.Clear(); - - _pnlContainer = new Panel {CssClass = "dnnFilePicker"}; - - _pnlLeftDiv = new Panel {CssClass = "dnnLeft"}; - - AddFolderArea(); - AddFileAndUploadArea(); - AddButtonArea(); - AddMessageRow(); - - _pnlContainer.Controls.Add(_pnlLeftDiv); - - _pnlRightDiv = new Panel {CssClass = "dnnLeft"}; - - GeneratePreviewImage(); - - _pnlContainer.Controls.Add(_pnlRightDiv); - - Controls.Add(_pnlContainer); - - base.CreateChildControls(); - } - - /// - /// OnPreRender runs just before the control is rendered - /// - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (_cboFolders.Items.Count > 0) - { - //Configure Labels - _lblFolder.Text = Utilities.GetLocalizedString("Folder"); - _lblFolder.CssClass = LabelCssClass; - _lblFile.Text = Utilities.GetLocalizedString("File"); - _lblFile.CssClass = LabelCssClass; - - //select folder - string fileName; - string folderPath; - if (!string.IsNullOrEmpty(FilePath)) - { - fileName = FilePath.Substring(FilePath.LastIndexOf("/") + 1); - folderPath = string.IsNullOrEmpty(fileName) ? FilePath : FilePath.Replace(fileName, ""); - } - else - { - fileName = FilePath; - folderPath = string.Empty; - } - - if (_cboFolders.Items.FindByValue(folderPath) != null) - { - _cboFolders.SelectedIndex = -1; - _cboFolders.Items.FindByValue(folderPath).Selected = true; - } - - //Get Files - LoadFiles(); - if (_cboFiles.Items.FindByText(fileName) != null) - { - _cboFiles.Items.FindByText(fileName).Selected = true; - } - if (_cboFiles.SelectedItem == null || string.IsNullOrEmpty(_cboFiles.SelectedItem.Value)) - { - FileID = -1; - } - else - { - FileID = Int32.Parse(_cboFiles.SelectedItem.Value); - } - - if (_cboFolders.Items.Count > 1 && ShowFolders) - { - _pnlFolder.Visible = true; - } - else - { - _pnlFolder.Visible = false; - } - //Configure Mode - switch (Mode) - { - case FileControlMode.Normal: - _pnlFile.Visible = true; - _pnlUpload.Visible = false; - _pnlRightDiv.Visible = true; - ShowImage(); - - if ((FolderPermissionController.HasFolderPermission(PortalId, _cboFolders.SelectedItem.Value, "ADD") || IsUserFolder(_cboFolders.SelectedItem.Value)) && ShowUpLoad) - { - ShowButton(_cmdUpload, "Upload"); - } - break; - - case FileControlMode.UpLoadFile: - _pnlFile.Visible = false; - _pnlUpload.Visible = true; - _pnlRightDiv.Visible = false; - ShowButton(_cmdSave, "Save"); - ShowButton(_cmdCancel, "Cancel"); - break; - } - } - else - { - _lblMessage.Text = Utilities.GetLocalizedString("NoPermission"); - } - - //Show message Row - _pnlMessage.Visible = (!string.IsNullOrEmpty(_lblMessage.Text)); - } - - #endregion - - #region Event Handlers - - private void CancelUpload(object sender, EventArgs e) - { - Mode = FileControlMode.Normal; - } - - private void FileChanged(object sender, EventArgs e) - { - SetFilePath(); - } - - private void FolderChanged(object sender, EventArgs e) - { - LoadFiles(); - SetFilePath(); - } - - private void SaveFile(object sender, EventArgs e) - { - //if file is selected exit - if (!string.IsNullOrEmpty(_txtFile.PostedFile.FileName)) - { - var extension = Path.GetExtension(_txtFile.PostedFile.FileName).Replace(".", ""); - - if (!string.IsNullOrEmpty(FileFilter) && !FileFilter.ToLowerInvariant().Contains(extension.ToLowerInvariant())) - { - // trying to upload a file not allowed for current filter - var localizedString = Localization.GetString("UploadError", LocalResourceFile); - if(String.IsNullOrEmpty(localizedString)) - { - localizedString = Utilities.GetLocalizedString("UploadError"); - } - - _lblMessage.Text = string.Format(localizedString, FileFilter, extension); - } - else - { - var folderManager = FolderManager.Instance; - - var folderPath = PathUtils.Instance.GetRelativePath(PortalId, ParentFolder) + _cboFolders.SelectedItem.Value; - - //Check if this is a User Folder - IFolderInfo folder; - if (IsUserFolder(_cboFolders.SelectedItem.Value)) - { - //Make sure the user folder exists - folder = folderManager.GetFolder(PortalController.GetEffectivePortalId(PortalId), folderPath); - if (folder == null) - { - //Add User folder - var user = User ?? UserController.Instance.GetCurrentUserInfo(); - //fix user's portal id - user.PortalID = PortalId; + this._pnlRightDiv.Controls.Add(imageHolderPanel); + this._pnlRightDiv.Visible = true; + } + } + + /// + /// OnPreRender runs just before the control is rendered. + /// + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (this._cboFolders.Items.Count > 0) + { + // Configure Labels + this._lblFolder.Text = Utilities.GetLocalizedString("Folder"); + this._lblFolder.CssClass = this.LabelCssClass; + this._lblFile.Text = Utilities.GetLocalizedString("File"); + this._lblFile.CssClass = this.LabelCssClass; + + // select folder + string fileName; + string folderPath; + if (!string.IsNullOrEmpty(this.FilePath)) + { + fileName = this.FilePath.Substring(this.FilePath.LastIndexOf("/") + 1); + folderPath = string.IsNullOrEmpty(fileName) ? this.FilePath : this.FilePath.Replace(fileName, string.Empty); + } + else + { + fileName = this.FilePath; + folderPath = string.Empty; + } + + if (this._cboFolders.Items.FindByValue(folderPath) != null) + { + this._cboFolders.SelectedIndex = -1; + this._cboFolders.Items.FindByValue(folderPath).Selected = true; + } + + // Get Files + this.LoadFiles(); + if (this._cboFiles.Items.FindByText(fileName) != null) + { + this._cboFiles.Items.FindByText(fileName).Selected = true; + } + + if (this._cboFiles.SelectedItem == null || string.IsNullOrEmpty(this._cboFiles.SelectedItem.Value)) + { + this.FileID = -1; + } + else + { + this.FileID = int.Parse(this._cboFiles.SelectedItem.Value); + } + + if (this._cboFolders.Items.Count > 1 && this.ShowFolders) + { + this._pnlFolder.Visible = true; + } + else + { + this._pnlFolder.Visible = false; + } + + // Configure Mode + switch (this.Mode) + { + case FileControlMode.Normal: + this._pnlFile.Visible = true; + this._pnlUpload.Visible = false; + this._pnlRightDiv.Visible = true; + this.ShowImage(); + + if ((FolderPermissionController.HasFolderPermission(this.PortalId, this._cboFolders.SelectedItem.Value, "ADD") || this.IsUserFolder(this._cboFolders.SelectedItem.Value)) && this.ShowUpLoad) + { + this.ShowButton(this._cmdUpload, "Upload"); + } + + break; + + case FileControlMode.UpLoadFile: + this._pnlFile.Visible = false; + this._pnlUpload.Visible = true; + this._pnlRightDiv.Visible = false; + this.ShowButton(this._cmdSave, "Save"); + this.ShowButton(this._cmdCancel, "Cancel"); + break; + } + } + else + { + this._lblMessage.Text = Utilities.GetLocalizedString("NoPermission"); + } + + // Show message Row + this._pnlMessage.Visible = !string.IsNullOrEmpty(this._lblMessage.Text); + } + + private void CancelUpload(object sender, EventArgs e) + { + this.Mode = FileControlMode.Normal; + } + + private void FileChanged(object sender, EventArgs e) + { + this.SetFilePath(); + } + + private void FolderChanged(object sender, EventArgs e) + { + this.LoadFiles(); + this.SetFilePath(); + } + + private void SaveFile(object sender, EventArgs e) + { + // if file is selected exit + if (!string.IsNullOrEmpty(this._txtFile.PostedFile.FileName)) + { + var extension = Path.GetExtension(this._txtFile.PostedFile.FileName).Replace(".", string.Empty); + + if (!string.IsNullOrEmpty(this.FileFilter) && !this.FileFilter.ToLowerInvariant().Contains(extension.ToLowerInvariant())) + { + // trying to upload a file not allowed for current filter + var localizedString = Localization.GetString("UploadError", this.LocalResourceFile); + if (string.IsNullOrEmpty(localizedString)) + { + localizedString = Utilities.GetLocalizedString("UploadError"); + } + + this._lblMessage.Text = string.Format(localizedString, this.FileFilter, extension); + } + else + { + var folderManager = FolderManager.Instance; + + var folderPath = PathUtils.Instance.GetRelativePath(this.PortalId, this.ParentFolder) + this._cboFolders.SelectedItem.Value; + + // Check if this is a User Folder + IFolderInfo folder; + if (this.IsUserFolder(this._cboFolders.SelectedItem.Value)) + { + // Make sure the user folder exists + folder = folderManager.GetFolder(PortalController.GetEffectivePortalId(this.PortalId), folderPath); + if (folder == null) + { + // Add User folder + var user = this.User ?? UserController.Instance.GetCurrentUserInfo(); + + // fix user's portal id + user.PortalID = this.PortalId; folder = ((FolderManager)folderManager).AddUserFolder(user); - } - } - else - { - folder = folderManager.GetFolder(PortalId, folderPath); + } + } + else + { + folder = folderManager.GetFolder(this.PortalId, folderPath); + } + + var fileName = Path.GetFileName(this._txtFile.PostedFile.FileName); + + try + { + FileManager.Instance.AddFile(folder, fileName, this._txtFile.PostedFile.InputStream, true); } + catch (PermissionsNotMetException) + { + this._lblMessage.Text += "
" + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); + } + catch (NoSpaceAvailableException) + { + this._lblMessage.Text += "
" + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); + } + catch (InvalidFileExtensionException) + { + this._lblMessage.Text += "
" + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); + } + catch (Exception ex) + { + Logger.Error(ex); - var fileName = Path.GetFileName(_txtFile.PostedFile.FileName); - - try - { - FileManager.Instance.AddFile(folder, fileName, _txtFile.PostedFile.InputStream, true); - } - catch (PermissionsNotMetException) - { - _lblMessage.Text += "
" + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); - } - catch (NoSpaceAvailableException) - { - _lblMessage.Text += "
" + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); - } - catch (InvalidFileExtensionException) - { - _lblMessage.Text += "
" + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); - } - catch (Exception ex) - { - Logger.Error(ex); - - _lblMessage.Text += "
" + string.Format(Localization.GetString("SaveFileError"), fileName); - } - } - - if (string.IsNullOrEmpty(_lblMessage.Text)) - { - var fileName = _txtFile.PostedFile.FileName.Substring(_txtFile.PostedFile.FileName.LastIndexOf("\\") + 1); - SetFilePath(fileName); - } - } - Mode = FileControlMode.Normal; - } - - private void UploadFile(object sender, EventArgs e) - { - Mode = FileControlMode.UpLoadFile; - } - - #endregion - - #region ILocalizable Implementation - - public bool Localize - { - get - { - return _localize; - } - set - { - _localize = value; - } - } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() - { - } - - #endregion - - } + this._lblMessage.Text += "
" + string.Format(Localization.GetString("SaveFileError"), fileName); + } + } + + if (string.IsNullOrEmpty(this._lblMessage.Text)) + { + var fileName = this._txtFile.PostedFile.FileName.Substring(this._txtFile.PostedFile.FileName.LastIndexOf("\\") + 1); + this.SetFilePath(fileName); + } + } + + this.Mode = FileControlMode.Normal; + } + + private void UploadFile(object sender, EventArgs e) + { + this.Mode = FileControlMode.UpLoadFile; + } + } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs index e34d14e49cd..b3d12e336df 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs @@ -1,47 +1,80 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Localization; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.UI.UserControls; -using DotNetNuke.Web.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.UserControls; + using DotNetNuke.Web.Common; + public class DnnFilePickerUploader : UserControl, IFilePickerUploader - { - #region Private Fields - + { + protected DnnFileDropDownList FilesComboBox; + protected DnnFolderDropDownList FoldersComboBox; private const string MyFileName = "filepickeruploader.ascx"; - private int? _portalId = null; + private int? _portalId = null; private string _fileFilter; - private string _folderPath = String.Empty; - private bool _folderPathSet = false; + private string _folderPath = string.Empty; + private bool _folderPathSet = false; + protected Label FoldersLabel; + protected DnnFileUpload FileUploadControl; + + public bool UsePersonalFolder { get; set; } - #endregion + public string FilePath + { + get + { + this.EnsureChildControls(); - #region Protected Properties + var path = string.Empty; + if (this.FoldersComboBox.SelectedFolder != null && this.FilesComboBox.SelectedFile != null) + { + path = this.FilesComboBox.SelectedFile.RelativePath; + } - protected DnnFileDropDownList FilesComboBox; - protected DnnFolderDropDownList FoldersComboBox; - protected Label FoldersLabel; - protected DnnFileUpload FileUploadControl; + return path; + } + + set + { + this.EnsureChildControls(); + if (!string.IsNullOrEmpty(value)) + { + var file = FileManager.Instance.GetFile(this.PortalId, value); + if (file != null) + { + this.FoldersComboBox.SelectedFolder = FolderManager.Instance.GetFolder(file.FolderId); + this.FilesComboBox.SelectedFile = file; + } + } + else + { + this.FoldersComboBox.SelectedFolder = null; + this.FilesComboBox.SelectedFile = null; + + this.LoadFolders(); + } + } + } protected string FolderLabel { @@ -73,86 +106,44 @@ protected string DropFileLabel { return Localization.GetString("DropFile", Localization.GetResourceFile(this, MyFileName)); } - } - - #endregion - - #region Public Properties - - public bool UsePersonalFolder { get; set; } - - public string FilePath - { - get - { - EnsureChildControls(); - - var path = string.Empty; - if (FoldersComboBox.SelectedFolder != null && FilesComboBox.SelectedFile != null) - { - path = FilesComboBox.SelectedFile.RelativePath; - } + } - return path; - } - - set - { - EnsureChildControls(); - if (!string.IsNullOrEmpty(value)) - { - var file = FileManager.Instance.GetFile(PortalId, value); - if (file != null) - { - FoldersComboBox.SelectedFolder = FolderManager.Instance.GetFolder(file.FolderId); - FilesComboBox.SelectedFile = file; - } - } - else - { - FoldersComboBox.SelectedFolder = null; - FilesComboBox.SelectedFile = null; - - LoadFolders(); - } - } - } - public int FileID { get { - EnsureChildControls(); - - return FilesComboBox.SelectedFile != null ? FilesComboBox.SelectedFile.FileId : Null.NullInteger; + this.EnsureChildControls(); + + return this.FilesComboBox.SelectedFile != null ? this.FilesComboBox.SelectedFile.FileId : Null.NullInteger; } set { - EnsureChildControls(); + this.EnsureChildControls(); var file = FileManager.Instance.GetFile(value); if (file != null) { - FoldersComboBox.SelectedFolder = FolderManager.Instance.GetFolder(file.FolderId); - FilesComboBox.SelectedFile = file; + this.FoldersComboBox.SelectedFolder = FolderManager.Instance.GetFolder(file.FolderId); + this.FilesComboBox.SelectedFile = file; } } } - public string FolderPath - { - get + public string FolderPath + { + get { - return _folderPathSet - ? _folderPath - : FoldersComboBox.SelectedFolder != null - ? FoldersComboBox.SelectedFolder.FolderPath - : string.Empty; + return this._folderPathSet + ? this._folderPath + : this.FoldersComboBox.SelectedFolder != null + ? this.FoldersComboBox.SelectedFolder.FolderPath + : string.Empty; } - set + + set { - _folderPath = value; - _folderPathSet = true; + this._folderPath = value; + this._folderPathSet = true; } } @@ -160,157 +151,148 @@ public string FileFilter { get { - return _fileFilter; + return this._fileFilter; } + set { - _fileFilter = value; + this._fileFilter = value; if (!string.IsNullOrEmpty(value)) { - FileUploadControl.Options.Extensions = value.Split(',').ToList(); + this.FileUploadControl.Options.Extensions = value.Split(',').ToList(); } else { - FileUploadControl.Options.Extensions.RemoveAll(t => true); + this.FileUploadControl.Options.Extensions.RemoveAll(t => true); } } } - + public bool Required { get; set; } - - public UserInfo User { get; set; } - public int PortalId - { - get - { - return !_portalId.HasValue ? PortalSettings.Current.PortalId : _portalId.Value; - } - set - { - _portalId = value; - } - } + public UserInfo User { get; set; } - public bool SupportHost + public int PortalId { - get { return FileUploadControl.SupportHost; } - set { FileUploadControl.SupportHost = value; } + get + { + return !this._portalId.HasValue ? PortalSettings.Current.PortalId : this._portalId.Value; + } + + set + { + this._portalId = value; + } } - #endregion - - #region Event Handlers - + public bool SupportHost + { + get { return this.FileUploadControl.SupportHost; } + set { this.FileUploadControl.SupportHost = value; } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - FoldersComboBox.SelectItemDefaultText = (SupportHost && PortalSettings.Current.ActiveTab.IsSuperTab) ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; - FoldersComboBox.OnClientSelectionChanged.Add("dnn.dnnFileUpload.Folders_Changed"); - FoldersComboBox.Options.Services.Parameters.Add("permission", "READ,ADD"); + this.FoldersComboBox.SelectItemDefaultText = (this.SupportHost && PortalSettings.Current.ActiveTab.IsSuperTab) ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; + this.FoldersComboBox.OnClientSelectionChanged.Add("dnn.dnnFileUpload.Folders_Changed"); + this.FoldersComboBox.Options.Services.Parameters.Add("permission", "READ,ADD"); - FilesComboBox.OnClientSelectionChanged.Add("dnn.dnnFileUpload.Files_Changed"); - FilesComboBox.SelectItemDefaultText = DynamicSharedConstants.Unspecified; - FilesComboBox.IncludeNoneSpecificItem = true; - FilesComboBox.Filter = FileFilter; + this.FilesComboBox.OnClientSelectionChanged.Add("dnn.dnnFileUpload.Files_Changed"); + this.FilesComboBox.SelectItemDefaultText = DynamicSharedConstants.Unspecified; + this.FilesComboBox.IncludeNoneSpecificItem = true; + this.FilesComboBox.Filter = this.FileFilter; if (UrlUtils.InPopUp()) { - FileUploadControl.Width = 630; - FileUploadControl.Height = 400; + this.FileUploadControl.Width = 630; + this.FileUploadControl.Height = 400; } - LoadFolders(); - jQuery.RegisterFileUpload(Page); + this.LoadFolders(); + jQuery.RegisterFileUpload(this.Page); JavaScript.RequestRegistration(CommonJs.DnnPlugins); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); } protected override void OnPreRender(EventArgs e) { - if (FoldersComboBox.SelectedFolder != null && FoldersComboBox.SelectedFolder.FolderPath.StartsWith("Users/", StringComparison.InvariantCultureIgnoreCase)) + if (this.FoldersComboBox.SelectedFolder != null && this.FoldersComboBox.SelectedFolder.FolderPath.StartsWith("Users/", StringComparison.InvariantCultureIgnoreCase)) { - var userFolder = FolderManager.Instance.GetUserFolder(User ?? UserController.Instance.GetCurrentUserInfo()); - if (FoldersComboBox.SelectedFolder.FolderID == userFolder.FolderID) + var userFolder = FolderManager.Instance.GetUserFolder(this.User ?? UserController.Instance.GetCurrentUserInfo()); + if (this.FoldersComboBox.SelectedFolder.FolderID == userFolder.FolderID) { - FoldersComboBox.SelectedItem = new ListItem - { - Text = FolderManager.Instance.MyFolderName, - Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture) - }; + this.FoldersComboBox.SelectedItem = new ListItem + { + Text = FolderManager.Instance.MyFolderName, + Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture), + }; } - else if (UsePersonalFolder) //if UserPersonalFolder is true, make sure the file is under the user folder. + else if (this.UsePersonalFolder) // if UserPersonalFolder is true, make sure the file is under the user folder. { - FoldersComboBox.SelectedItem = new ListItem - { - Text = FolderManager.Instance.MyFolderName, - Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture) - }; + this.FoldersComboBox.SelectedItem = new ListItem + { + Text = FolderManager.Instance.MyFolderName, + Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture), + }; - FilesComboBox.SelectedFile = null; + this.FilesComboBox.SelectedFile = null; } } - FoldersLabel.Text = FolderManager.Instance.MyFolderName; + this.FoldersLabel.Text = FolderManager.Instance.MyFolderName; - FileUploadControl.Options.FolderPicker.Disabled = UsePersonalFolder; - if (FileUploadControl.Options.FolderPicker.Disabled && FoldersComboBox.SelectedFolder != null) + this.FileUploadControl.Options.FolderPicker.Disabled = this.UsePersonalFolder; + if (this.FileUploadControl.Options.FolderPicker.Disabled && this.FoldersComboBox.SelectedFolder != null) { var selectedItem = new SerializableKeyValuePair( - FoldersComboBox.SelectedItem.Value, FoldersComboBox.SelectedItem.Text); - - FileUploadControl.Options.FolderPicker.InitialState = new DnnDropDownListState - { - SelectedItem = selectedItem - - }; - FileUploadControl.Options.FolderPath = FoldersComboBox.SelectedFolder.FolderPath; + this.FoldersComboBox.SelectedItem.Value, this.FoldersComboBox.SelectedItem.Text); + + this.FileUploadControl.Options.FolderPicker.InitialState = new DnnDropDownListState + { + SelectedItem = selectedItem, + }; + this.FileUploadControl.Options.FolderPath = this.FoldersComboBox.SelectedFolder.FolderPath; } base.OnPreRender(e); - } - - #endregion - - #region Private Methods - + } + private void LoadFolders() { - if (UsePersonalFolder) + if (this.UsePersonalFolder) { - var user = User ?? UserController.Instance.GetCurrentUserInfo(); + var user = this.User ?? UserController.Instance.GetCurrentUserInfo(); var userFolder = FolderManager.Instance.GetUserFolder(user); - FoldersComboBox.SelectedFolder = userFolder; + this.FoldersComboBox.SelectedFolder = userFolder; } else { - //select folder + // select folder string fileName; string folderPath; - if (!string.IsNullOrEmpty(FilePath)) + if (!string.IsNullOrEmpty(this.FilePath)) { - fileName = FilePath.Substring(FilePath.LastIndexOf("/") + 1); - folderPath = string.IsNullOrEmpty(fileName) ? FilePath : FilePath.Replace(fileName, ""); + fileName = this.FilePath.Substring(this.FilePath.LastIndexOf("/") + 1); + folderPath = string.IsNullOrEmpty(fileName) ? this.FilePath : this.FilePath.Replace(fileName, string.Empty); } else { - fileName = FilePath; - folderPath = FolderPath; + fileName = this.FilePath; + folderPath = this.FolderPath; } - FoldersComboBox.SelectedFolder = FolderManager.Instance.GetFolder(PortalId, folderPath); + this.FoldersComboBox.SelectedFolder = FolderManager.Instance.GetFolder(this.PortalId, folderPath); if (!string.IsNullOrEmpty(fileName)) { - FilesComboBox.SelectedFile = FileManager.Instance.GetFile(FoldersComboBox.SelectedFolder, fileName); + this.FilesComboBox.SelectedFile = FileManager.Instance.GetFile(this.FoldersComboBox.SelectedFolder, fileName); } } - FoldersComboBox.Enabled = !UsePersonalFolder; - FoldersLabel.Visible = UsePersonalFolder; - } - - #endregion + this.FoldersComboBox.Enabled = !this.UsePersonalFolder; + this.FoldersLabel.Visible = this.UsePersonalFolder; + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs index 2bf044796cd..8c5fe687494 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs @@ -1,36 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Linq; -using System.Web.Services.Description; -using System.Web.UI; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - + using System; + using System.Globalization; + using System.Linq; + using System.Web.Services.Description; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.Common; + [ToolboxData("<{0}:DnnFileUpload runat='server'>")] public class DnnFileUpload : Control, INamingContainer { - private readonly Lazy _options = new Lazy(() => new DnnFileUploadOptions()); public DnnFileUploadOptions Options { get { - return _options.Value; + return this._options.Value; } } @@ -39,19 +38,19 @@ public int ModuleId set { var moduleIdString = value.ToString(CultureInfo.InvariantCulture); - Options.ModuleId = moduleIdString; - Options.FolderPicker.Services.ModuleId = moduleIdString; + this.Options.ModuleId = moduleIdString; + this.Options.FolderPicker.Services.ModuleId = moduleIdString; } } public string ParentClientId { - set { Options.ParentClientId = value; } + set { this.Options.ParentClientId = value; } } public bool ShowOnStartup { - set { Options.ShowOnStartup = value; } + set { this.Options.ShowOnStartup = value; } } public string Skin { get; set; } @@ -60,14 +59,14 @@ public bool ShowOnStartup public int Width { - get { return Options.Width; } - set { Options.Width = value; } + get { return this.Options.Width; } + set { this.Options.Width = value; } } public int Height { - get { return Options.Height; } - set { Options.Height = value; } + get { return this.Options.Height; } + set { this.Options.Height = value; } } public static DnnFileUpload GetCurrent(Page page) @@ -80,15 +79,15 @@ protected override void OnInit(EventArgs e) base.OnInit(e); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - jQuery.RegisterFileUpload(Page); + jQuery.RegisterFileUpload(this.Page); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - RegisterClientScript(Page, Skin); - RegisterStartupScript(); + RegisterClientScript(this.Page, this.Skin); + this.RegisterStartupScript(); } private static void RegisterClientScript(Page page, string skin) @@ -110,58 +109,57 @@ private static void RegisterClientScript(Page page, string skin) private void RegisterStartupScript() { - Options.ClientId = ClientID; + this.Options.ClientId = this.ClientID; var portalSettings = PortalSettings.Current; - if (Options.FolderPicker.InitialState == null) + if (this.Options.FolderPicker.InitialState == null) { var folder = FolderManager.Instance.GetFolder(portalSettings.PortalId, string.Empty); - var rootFolder = (SupportHost && portalSettings.ActiveTab.IsSuperTab) ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; + var rootFolder = (this.SupportHost && portalSettings.ActiveTab.IsSuperTab) ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; - Options.FolderPicker.InitialState = new DnnDropDownListState + this.Options.FolderPicker.InitialState = new DnnDropDownListState { - SelectedItem = (folder != null) ? new SerializableKeyValuePair(folder.FolderID.ToString(CultureInfo.InvariantCulture), rootFolder) : null + SelectedItem = (folder != null) ? new SerializableKeyValuePair(folder.FolderID.ToString(CultureInfo.InvariantCulture), rootFolder) : null, }; } - if (Options.Extensions.Count > 0) + if (this.Options.Extensions.Count > 0) { - var extensionsText = Options.Extensions.Aggregate(string.Empty, (current, extension) => current.Append(extension, ", ")); - Options.Resources.InvalidFileExtensions = string.Format(Options.Resources.InvalidFileExtensions, extensionsText); + var extensionsText = this.Options.Extensions.Aggregate(string.Empty, (current, extension) => current.Append(extension, ", ")); + this.Options.Resources.InvalidFileExtensions = string.Format(this.Options.Resources.InvalidFileExtensions, extensionsText); } - if (Options.MaxFiles > 0) + if (this.Options.MaxFiles > 0) { - Options.Resources.TooManyFiles = string.Format(Options.Resources.TooManyFiles, Options.MaxFiles.ToString(CultureInfo.InvariantCulture)); + this.Options.Resources.TooManyFiles = string.Format(this.Options.Resources.TooManyFiles, this.Options.MaxFiles.ToString(CultureInfo.InvariantCulture)); } - if (!SupportHost) + if (!this.SupportHost) { - Options.FolderPicker.Services.Parameters["portalId"] = portalSettings.PortalId.ToString(); + this.Options.FolderPicker.Services.Parameters["portalId"] = portalSettings.PortalId.ToString(); } - Options.FolderPicker.Services.GetTreeMethod = "ItemListService/GetFolders"; - Options.FolderPicker.Services.GetNodeDescendantsMethod = "ItemListService/GetFolderDescendants"; - Options.FolderPicker.Services.SearchTreeMethod = "ItemListService/SearchFolders"; - Options.FolderPicker.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForFolder"; - Options.FolderPicker.Services.SortTreeMethod = "ItemListService/SortFolders"; - Options.FolderPicker.Services.ServiceRoot = "InternalServices"; + + this.Options.FolderPicker.Services.GetTreeMethod = "ItemListService/GetFolders"; + this.Options.FolderPicker.Services.GetNodeDescendantsMethod = "ItemListService/GetFolderDescendants"; + this.Options.FolderPicker.Services.SearchTreeMethod = "ItemListService/SearchFolders"; + this.Options.FolderPicker.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForFolder"; + this.Options.FolderPicker.Services.SortTreeMethod = "ItemListService/SortFolders"; + this.Options.FolderPicker.Services.ServiceRoot = "InternalServices"; - var optionsAsJsonString = Json.Serialize(Options); + var optionsAsJsonString = Json.Serialize(this.Options); var script = string.Format("dnn.createFileUpload({0});{1}", optionsAsJsonString, Environment.NewLine); - if (ScriptManager.GetCurrent(Page) != null) + if (ScriptManager.GetCurrent(this.Page) != null) { // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), ClientID + "DnnFileUpload", script, true); + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID + "DnnFileUpload", script, true); } else { - Page.ClientScript.RegisterStartupScript(GetType(), ClientID + "DnnFileUpload", script, true); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "DnnFileUpload", script, true); } - } - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs index 5abfa6d56a7..bbb92fb3fc8 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Globalization; -using System.Runtime.Serialization; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - + using System.Collections.Generic; + using System.Globalization; + using System.Runtime.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + [DataContract] public class DnnFileUploadResources { @@ -93,13 +93,13 @@ public class DnnFileUploadResources [DataContract] public class DnnFileUploadOptions { - private const int DefaultWidth = 780; - private const int DefaultHeight = 630; [DataMember(Name = "clientId")] public string ClientId; - [DataMember(Name = "moduleId")] public string ModuleId = string.Empty; + + private const int DefaultWidth = 780; + private const int DefaultHeight = 630; [DataMember(Name = "parentClientId")] public string ParentClientId; @@ -128,45 +128,19 @@ public class DnnFileUploadOptions [DataMember(Name = "height")] public int Height; - private Dictionary _parameters; - - [DataMember(Name = "parameters")] - public Dictionary Parameters - { - get - { - return _parameters ?? (_parameters = new Dictionary()); - } - } - [DataMember(Name = "folderPath")] public string FolderPath; - [DataMember(Name = "validationCode")] - public string ValidationCode - { - get - { - var portalSettings = PortalSettings.Current; - var parameters = new List(){Extensions}; - if (portalSettings != null) - { - parameters.Add(portalSettings.PortalId); - parameters.Add(portalSettings.UserInfo.UserID); - } - - return ValidationUtils.ComputeValidationCode(parameters); - } - } + private Dictionary _parameters; public DnnFileUploadOptions() { - FolderPicker = new DnnDropDownListOptions(); - MaxFileSize = (int)Config.GetMaxUploadSize(); - Extensions = new List(); - Width = DefaultWidth; - Height = DefaultHeight; - Resources = new DnnFileUploadResources + this.FolderPicker = new DnnDropDownListOptions(); + this.MaxFileSize = (int)Config.GetMaxUploadSize(); + this.Extensions = new List(); + this.Width = DefaultWidth; + this.Height = DefaultHeight; + this.Resources = new DnnFileUploadResources { Title = Utilities.GetLocalizedString("FileUpload.Title.Text"), DecompressLabel = Utilities.GetLocalizedString("FileUpload.DecompressLabel.Text"), @@ -177,7 +151,7 @@ public DnnFileUploadOptions() CloseButtonText = Utilities.GetLocalizedString("FileUpload.CloseButton.Text"), UploadFromWebButtonText = Utilities.GetLocalizedString("FileUpload.UploadFromWebButton.Text"), DecompressingFile = Utilities.GetLocalizedString("FileUpload.DecompressingFile.Text"), - FileIsTooLarge = string.Format(Utilities.GetLocalizedString("FileUpload.FileIsTooLarge.Error") + " Mb", (MaxFileSize / (1024 * 1024)).ToString(CultureInfo.InvariantCulture)), + FileIsTooLarge = string.Format(Utilities.GetLocalizedString("FileUpload.FileIsTooLarge.Error") + " Mb", (this.MaxFileSize / (1024 * 1024)).ToString(CultureInfo.InvariantCulture)), FileUploadCancelled = Utilities.GetLocalizedString("FileUpload.FileUploadCancelled.Error"), FileUploadFailed = Utilities.GetLocalizedString("FileUpload.FileUploadFailed.Error"), TooManyFiles = Utilities.GetLocalizedString("FileUpload.TooManyFiles.Error"), @@ -192,8 +166,37 @@ public DnnFileUploadOptions() ReplaceButtonText = Utilities.GetLocalizedString("FileUpload.ReplaceButton.Text"), UnzipFilePromptTitle = Utilities.GetLocalizedString("FileUpload.UnzipFilePromptTitle.Text"), UnzipFileFailedPromptBody = Utilities.GetLocalizedString("FileUpload.UnzipFileFailedPromptBody.Text"), - UnzipFileSuccessPromptBody = Utilities.GetLocalizedString("FileUpload.UnzipFileSuccessPromptBody.Text") + UnzipFileSuccessPromptBody = Utilities.GetLocalizedString("FileUpload.UnzipFileSuccessPromptBody.Text"), }; } + + [DataMember(Name = "parameters")] + public Dictionary Parameters + { + get + { + return this._parameters ?? (this._parameters = new Dictionary()); + } + } + + [DataMember(Name = "validationCode")] + public string ValidationCode + { + get + { + var portalSettings = PortalSettings.Current; + var parameters = new List() { this.Extensions }; + if (portalSettings != null) + { + parameters.Add(portalSettings.UserInfo.UserID); + if (!portalSettings.UserInfo.IsSuperUser) + { + parameters.Add(portalSettings.PortalId); + } + } + + return ValidationUtils.ComputeValidationCode(parameters); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs index 4dcdb4576f6..6754d299db8 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs @@ -1,40 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Common; -using DotNetNuke.Web.UI.WebControls.Extensions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Common; + using DotNetNuke.Web.UI.WebControls.Extensions; + [ToolboxData("<{0}:DnnFolderDropDownList runat='server'>")] public class DnnFolderDropDownList : DnnDropDownList { + /// + /// Gets or sets the selected Folder in the control, or selects the Folder in the control. + /// + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IFolderInfo SelectedFolder + { + get + { + var folderId = this.SelectedItemValueAsInt; + return (folderId == Null.NullInteger) ? null : FolderManager.Instance.GetFolder(folderId); + } + + set + { + var folderName = value != null ? value.FolderName : null; + if (folderName == string.Empty) + { + folderName = PortalSettings.Current.ActiveTab.IsSuperTab ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; + } + + this.SelectedItem = (value != null) ? new ListItem() { Text = folderName, Value = value.FolderID.ToString(CultureInfo.InvariantCulture) } : null; + } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); - SelectItemDefaultText = Localization.GetString("DropDownList.SelectFolderDefaultText", Localization.SharedResourceFile); - Services.GetTreeMethod = "ItemListService/GetFolders"; - Services.GetNodeDescendantsMethod = "ItemListService/GetFolderDescendants"; - Services.SearchTreeMethod = "ItemListService/SearchFolders"; - Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForFolder"; - Services.SortTreeMethod = "ItemListService/SortFolders"; - Services.ServiceRoot = "InternalServices"; + this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectFolderDefaultText", Localization.SharedResourceFile); + this.Services.GetTreeMethod = "ItemListService/GetFolders"; + this.Services.GetNodeDescendantsMethod = "ItemListService/GetFolderDescendants"; + this.Services.SearchTreeMethod = "ItemListService/SearchFolders"; + this.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForFolder"; + this.Services.SortTreeMethod = "ItemListService/SortFolders"; + this.Services.ServiceRoot = "InternalServices"; - Options.ItemList.DisableUnspecifiedOrder = true; + this.Options.ItemList.DisableUnspecifiedOrder = true; } protected override void OnPreRender(EventArgs e) @@ -42,8 +67,8 @@ protected override void OnPreRender(EventArgs e) this.AddCssClass("folder"); base.OnPreRender(e); - //add the selected folder's level path so that it can expand to the selected node in client side. - var selectedFolder = SelectedFolder; + // add the selected folder's level path so that it can expand to the selected node in client side. + var selectedFolder = this.SelectedFolder; if (selectedFolder != null && selectedFolder.ParentID > Null.NullInteger) { var folderLevel = string.Empty; @@ -54,33 +79,8 @@ protected override void OnPreRender(EventArgs e) parentFolder = (parentFolder.ParentID < 0) ? null : FolderManager.Instance.GetFolder(parentFolder.ParentID); } - ExpandPath = folderLevel.TrimEnd(','); + this.ExpandPath = folderLevel.TrimEnd(','); } - } - - /// - /// Gets the selected Folder in the control, or selects the Folder in the control. - /// - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public IFolderInfo SelectedFolder - { - get - { - var folderId = SelectedItemValueAsInt; - return (folderId == Null.NullInteger) ? null : FolderManager.Instance.GetFolder(folderId); - } - set - { - var folderName = value != null ? value.FolderName : null; - if (folderName == string.Empty) - { - folderName = PortalSettings.Current.ActiveTab.IsSuperTab ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; - } - - SelectedItem = (value != null) ? new ListItem() { Text = folderName, Value = value.FolderID.ToString(CultureInfo.InvariantCulture) } : null; - } - } - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditControlItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditControlItem.cs index 2e907e99a0b..b8ad3530873 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditControlItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditControlItem.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Framework; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.UI.WebControls; + public class DnnFormEditControlItem : DnnFormItemBase { private EditControl control; @@ -23,30 +18,30 @@ public class DnnFormEditControlItem : DnnFormItemBase protected override WebControl CreateControlInternal(Control container) { - control = Reflection.CreateObject(ControlType, ControlType) as EditControl; + this.control = Reflection.CreateObject(this.ControlType, this.ControlType) as EditControl; - if (control != null) + if (this.control != null) { - control.ID = ID + "_Control"; - control.Name = ID; - control.EditMode = PropertyEditorMode.Edit; - control.Required = false; - control.Value = Value; - control.OldValue = Value; - control.ValueChanged += ValueChanged; - control.DataField = DataField; - - control.CssClass = "dnnFormInput"; - - container.Controls.Add(control); + this.control.ID = this.ID + "_Control"; + this.control.Name = this.ID; + this.control.EditMode = PropertyEditorMode.Edit; + this.control.Required = false; + this.control.Value = this.Value; + this.control.OldValue = this.Value; + this.control.ValueChanged += this.ValueChanged; + this.control.DataField = this.DataField; + + this.control.CssClass = "dnnFormInput"; + + container.Controls.Add(this.control); } - return control; + return this.control; } - void ValueChanged(object sender, PropertyEditorEventArgs e) + private void ValueChanged(object sender, PropertyEditorEventArgs e) { - UpdateDataSource(Value, e.Value, DataField); + this.UpdateDataSource(this.Value, e.Value, this.DataField); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs index 71be8423079..750ccf2ae3b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs @@ -1,26 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; -using ClientDependency.Core; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using ClientDependency.Core; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + [ParseChildren(true)] public class DnnFormEditor : WebControl, INamingContainer { @@ -29,51 +25,52 @@ public class DnnFormEditor : WebControl, INamingContainer public DnnFormEditor() { - Items = new List(); - Sections = new List(); - Tabs = new List(); + this.Items = new List(); + this.Sections = new List(); + this.Tabs = new List(); - FormMode = DnnFormMode.Long; - ViewStateMode = ViewStateMode.Disabled; + this.FormMode = DnnFormMode.Long; + this.ViewStateMode = ViewStateMode.Disabled; } - protected string LocalResourceFile + public object DataSource { get { - return Utilities.GetLocalResourceFile(this); + return this._dataSource; + } + + set + { + if (this._dataSource != value) + { + this._dataSource = value; + if (this.Page.IsPostBack) + { + this.DataBindItems(false); + } + } } } - protected override HtmlTextWriterTag TagKey + public DnnFormMode FormMode { get; set; } + + protected string LocalResourceFile { get { - return HtmlTextWriterTag.Div; + return Utilities.GetLocalResourceFile(this); } } - public object DataSource + protected override HtmlTextWriterTag TagKey { get { - return _dataSource; - } - set - { - if (_dataSource != value) - { - _dataSource = value; - if (Page.IsPostBack) - { - DataBindItems(false); - } - } + return HtmlTextWriterTag.Div; } } - public DnnFormMode FormMode { get; set; } - public bool EncryptIds { get; set; } public bool IsValid @@ -81,72 +78,124 @@ public bool IsValid get { bool isValid = true; - foreach (var item in GetAllItems()) + foreach (var item in this.GetAllItems()) { item.CheckIsValid(); - if(!item.IsValid) + if (!item.IsValid) { isValid = false; break; } } + return isValid; } } - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Items { get; private set; } - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Sections { get; private set; } - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Tabs { get; private set; } + public override void DataBind() + { + this.OnDataBinding(EventArgs.Empty); + this.Controls.Clear(); + this.ClearChildViewState(); + this.TrackViewState(); + this.CreateControlHierarchy(true); + this.ChildControlsCreated = true; + } + + [Obsolete("Obsoleted in Platform 7.4.1, please add encryptIds. Scheduled removal in v10.0.0.")] + internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile) + { + SetUpItems(items, parentControl, localResourceFile, false); + } + + internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile, bool encryptIds) + { + foreach (DnnFormItemBase item in items) + { + if (encryptIds) + { + item.ID = (Host.GUID.Substring(0, 7) + item.ID + DateTime.Now.Day).GenerateHash(); + } + + parentControl.Controls.Add(item); + } + } + private List GetAllItems() { var items = new List(); - //iterate over pages - foreach (DnnFormTab page in Tabs) + // iterate over pages + foreach (DnnFormTab page in this.Tabs) { foreach (DnnFormSection section in page.Sections) { items.AddRange(section.Items); } + items.AddRange(page.Items); } - //iterate over section - foreach (DnnFormSection section in Sections) + // iterate over section + foreach (DnnFormSection section in this.Sections) { items.AddRange(section.Items); } - //Add base items - items.AddRange(Items); + // Add base items + items.AddRange(this.Items); return items; - } + } + + protected override void CreateChildControls() + { + // CreateChildControls re-creates the children (the items) + // using the saved view state. + // First clear any existing child controls. + this.Controls.Clear(); - #region Private Methods + // Create the items only if there is view state + // corresponding to the children. + if (this._itemCount > 0) + { + this.CreateControlHierarchy(false); + } + } - [Obsolete("Obsoleted in Platform 7.4.1, please add encryptIds. Scheduled removal in v10.0.0.")] - internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile) + protected virtual void CreateControlHierarchy(bool useDataSource) { - SetUpItems(items, parentControl, localResourceFile, false); - } + this.CssClass = string.IsNullOrEmpty(this.CssClass) ? "dnnForm" : this.CssClass.Contains("dnnForm") ? this.CssClass : string.Format("dnnForm {0}", this.CssClass); - internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile, bool encryptIds) + this.SetUpTabs(); + + this.SetUpSections(this.Sections, this); + + SetUpItems(this.Items, this, this.LocalResourceFile, this.EncryptIds); + + this.DataBindItems(useDataSource); + } + + protected override void LoadControlState(object state) { - foreach (DnnFormItemBase item in items) + if (state != null) { - if (encryptIds) - { - item.ID = (Host.GUID.Substring(0, 7) + item.ID + DateTime.Now.Day).GenerateHash(); - } - - parentControl.Controls.Add(item); + this._itemCount = (int)state; } } @@ -156,44 +205,45 @@ private void SetUpSections(List sections, WebControl parentContr { foreach (DnnFormSection section in sections) { - var panel = new DnnFormPanel {CssClass = "dnnFormSectionHead"}; + var panel = new DnnFormPanel { CssClass = "dnnFormSectionHead" }; parentControl.Controls.Add(panel); var resourceKey = section.ResourceKey; - if (String.IsNullOrEmpty(resourceKey)) + if (string.IsNullOrEmpty(resourceKey)) { resourceKey = section.ID; } - panel.Text = Localization.GetString(resourceKey, LocalResourceFile); + + panel.Text = Localization.GetString(resourceKey, this.LocalResourceFile); panel.Expanded = section.Expanded; - SetUpItems(section.Items, panel, LocalResourceFile, EncryptIds); + SetUpItems(section.Items, panel, this.LocalResourceFile, this.EncryptIds); } } } private void SetUpTabs() { - if (Tabs.Count > 0) + if (this.Tabs.Count > 0) { - var tabStrip = new DnnFormTabStrip {CssClass = "dnnAdminTabNav dnnClear"}; - Controls.Add(tabStrip); + var tabStrip = new DnnFormTabStrip { CssClass = "dnnAdminTabNav dnnClear" }; + this.Controls.Add(tabStrip); tabStrip.Items.Clear(); - foreach (DnnFormTab formTab in Tabs) + foreach (DnnFormTab formTab in this.Tabs) { var resourceKey = formTab.ResourceKey; - if (String.IsNullOrEmpty(resourceKey)) + if (string.IsNullOrEmpty(resourceKey)) { resourceKey = formTab.ID; } - var tab = new Panel {CssClass = formTab.ID + " dnnClear", ID = "tab_" + formTab.ID}; - Controls.Add(tab); + var tab = new Panel { CssClass = formTab.ID + " dnnClear", ID = "tab_" + formTab.ID }; + this.Controls.Add(tab); if (formTab.IncludeExpandAll) { - var expandAll = new Panel {CssClass = "dnnFormExpandContent"}; + var expandAll = new Panel { CssClass = "dnnFormExpandContent" }; string expandAllText = Localization.GetString("ExpandAll", Localization.SharedResourceFile); expandAll.Controls.Add(new LiteralControl("" + expandAllText + "")); tab.Controls.Add(expandAll); @@ -204,103 +254,51 @@ private void SetUpTabs() formTab.ExpandAllScript += "\t\t\t\ttargetArea: '#" + tab.ClientID + "' });\r\n"; } - tabStrip.Items.Add(new ListItem(Localization.GetString(resourceKey, LocalResourceFile), "#" + tab.ClientID)); + tabStrip.Items.Add(new ListItem(Localization.GetString(resourceKey, this.LocalResourceFile), "#" + tab.ClientID)); if (formTab.Sections.Count > 0) { - SetUpSections(formTab.Sections, tab); + this.SetUpSections(formTab.Sections, tab); } else { tab.CssClass += " dnnFormNoSections"; } - SetUpItems(formTab.Items, tab, LocalResourceFile, EncryptIds); + SetUpItems(formTab.Items, tab, this.LocalResourceFile, this.EncryptIds); } } - } - - #endregion - - #region Control Hierarchy and Data Binding - - protected override void CreateChildControls() - { - // CreateChildControls re-creates the children (the items) - // using the saved view state. - // First clear any existing child controls. - Controls.Clear(); - - // Create the items only if there is view state - // corresponding to the children. - if (_itemCount > 0) - { - CreateControlHierarchy(false); - } - } + } private void DataBindItems(bool useDataSource) { - var items = GetAllItems(); + var items = this.GetAllItems(); foreach (DnnFormItemBase item in items) { - if (String.IsNullOrEmpty(item.LocalResourceFile)) + if (string.IsNullOrEmpty(item.LocalResourceFile)) { - item.LocalResourceFile = LocalResourceFile; + item.LocalResourceFile = this.LocalResourceFile; } + if (item.FormMode == DnnFormMode.Inherit) { - item.FormMode = FormMode; + item.FormMode = this.FormMode; } - if (DataSource != null) + if (this.DataSource != null) { - item.DataSource = DataSource; + item.DataSource = this.DataSource; item.DataBindItem(useDataSource); } } - _itemCount = GetAllItems().Count; - } - - protected virtual void CreateControlHierarchy(bool useDataSource) - { - CssClass = string.IsNullOrEmpty(CssClass) ? "dnnForm" : CssClass.Contains("dnnForm") ? CssClass : string.Format("dnnForm {0}", CssClass); - - SetUpTabs(); - - SetUpSections(Sections, this); - - SetUpItems(Items, this, LocalResourceFile, EncryptIds); - - DataBindItems(useDataSource); - } - - public override void DataBind() - { - base.OnDataBinding(EventArgs.Empty); - Controls.Clear(); - ClearChildViewState(); - TrackViewState(); - CreateControlHierarchy(true); - ChildControlsCreated = true; - } - - #endregion - - #region Protected Methods - - protected override void LoadControlState(object state) - { - if (state != null) - { - _itemCount = (int) state; - } + + this._itemCount = this.GetAllItems().Count; } protected override void OnInit(EventArgs e) { - Page.RegisterRequiresControlState(this); + this.Page.RegisterRequiresControlState(this); JavaScript.RequestRegistration(CommonJs.DnnPlugins); base.OnInit(e); } @@ -309,27 +307,27 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if(Tabs.Count > 0) + if (this.Tabs.Count > 0) { const string scriptName = "FormEditorjQuery"; - ClientScriptManager cs = Page.ClientScript; - - - if (!cs.IsClientScriptBlockRegistered(GetType(), scriptName)) + ClientScriptManager cs = this.Page.ClientScript; + + if (!cs.IsClientScriptBlockRegistered(this.GetType(), scriptName)) { - //Render Script + // Render Script var scriptBuilder = new StringBuilder(); scriptBuilder.Append("\r\n"); - cs.RegisterClientScriptBlock(GetType(), scriptName, scriptBuilder.ToString()); + cs.RegisterClientScriptBlock(this.GetType(), scriptName, scriptBuilder.ToString()); } } } protected override object SaveControlState() { - return _itemCount > 0 ? (object) _itemCount : null; - } - - #endregion + return this._itemCount > 0 ? (object)this._itemCount : null; + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEmptyTemplate.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEmptyTemplate.cs index 1cc3230fe4e..2aa8d4a5b21 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEmptyTemplate.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEmptyTemplate.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.Web.UI; + using System.Web.UI.WebControls; + [ParseChildren(true)] public class DnnFormEmptyTemplate : WebControl, INamingContainer { diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs index 69e520ebd24..57e0dc06552 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs @@ -1,50 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Collections; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Reflection; + using System.Text.RegularExpressions; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Collections; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + public abstract class DnnFormItemBase : WebControl, INamingContainer { private object _value; private string _requiredMessageSuffix = ".Required"; private string _validationMessageSuffix = ".RegExError"; - + protected DnnFormItemBase() { - FormMode = DnnFormMode.Inherit; - IsValid = true; - - Validators = new List(); - } + this.FormMode = DnnFormMode.Inherit; + this.IsValid = true; - #region Protected Properties + this.Validators = new List(); + } + public object Value + { + get { return this._value; } + set { this._value = value; } + } + + public string DataField { get; set; } + protected PropertyInfo ChildProperty { get { - Type type = Property.PropertyType; + Type type = this.Property.PropertyType; IList props = new List(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)); - return props.SingleOrDefault(p => p.Name == DataField); + return props.SingleOrDefault(p => p.Name == this.DataField); } } @@ -57,11 +58,11 @@ protected PropertyInfo Property { get { - Type type = DataSource.GetType(); + Type type = this.DataSource.GetType(); IList props = new List(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)); - return !String.IsNullOrEmpty(DataMember) - ? props.SingleOrDefault(p => p.Name == DataMember) - : props.SingleOrDefault(p => p.Name == DataField); + return !string.IsNullOrEmpty(this.DataMember) + ? props.SingleOrDefault(p => p.Name == this.DataMember) + : props.SingleOrDefault(p => p.Name == this.DataField); } } @@ -73,26 +74,14 @@ protected override HtmlTextWriterTag TagKey } } - public object Value - { - get { return _value; } - set { _value = value; } - } - - #endregion - - #region Public Properties - - public string DataField { get; set; } - public string DataMember { get; set; } - internal object DataSource { get; set; } - public DnnFormMode FormMode { get; set; } public bool IsValid { get; private set; } + internal object DataSource { get; set; } + public string OnClientClicked { get; set; } public string LocalResourceFile { get; set; } @@ -105,11 +94,12 @@ public string RequiredMessageSuffix { get { - return _requiredMessageSuffix; + return this._requiredMessageSuffix; } + set { - _requiredMessageSuffix = value; + this._requiredMessageSuffix = value; } } @@ -117,119 +107,142 @@ public string ValidationMessageSuffix { get { - return _validationMessageSuffix; + return this._validationMessageSuffix; } + set { - _validationMessageSuffix = value; + this._validationMessageSuffix = value; } } - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Validators { get; private set; } - public string ValidationExpression { get; set; } + public string ValidationExpression { get; set; } - #endregion - - #region Control Hierarchy and Data Binding - - private void AddValidators(string controlId) + public void CheckIsValid() { - var value = Value as String; - Validators.Clear(); - - //Add Validators - if (Required) + this.IsValid = true; + foreach (BaseValidator validator in this.Validators) { - var requiredValidator = new RequiredFieldValidator - { - ID = ID + "_Required", - ErrorMessage = ResourceKey + RequiredMessageSuffix - }; - Validators.Add(requiredValidator); - } - - if (!String.IsNullOrEmpty(ValidationExpression)) - { - var regexValidator = new RegularExpressionValidator - { - ID = ID + "_RegEx", - ErrorMessage = ResourceKey + ValidationMessageSuffix, - ValidationExpression = ValidationExpression - }; - if (!String.IsNullOrEmpty(value)) - { - regexValidator.IsValid = Regex.IsMatch(value, ValidationExpression); - IsValid = regexValidator.IsValid; - } - Validators.Add(regexValidator); - } - - if (Validators.Count > 0) - { - foreach (BaseValidator validator in Validators) + validator.Validate(); + if (!validator.IsValid) { - validator.ControlToValidate = controlId; - validator.Display = ValidatorDisplay.Dynamic; - validator.ErrorMessage = LocalizeString(validator.ErrorMessage); - validator.CssClass = "dnnFormMessage dnnFormError"; - Controls.Add(validator); + this.IsValid = false; + break; } } } - public void CheckIsValid() + public void DataBindItem(bool useDataSource) { - IsValid = true; - foreach (BaseValidator validator in Validators) + if (useDataSource) { - validator.Validate(); - if (!validator.IsValid) + this.OnDataBinding(EventArgs.Empty); + this.Controls.Clear(); + this.ClearChildViewState(); + this.TrackViewState(); + + this.DataBindInternal(); + + this.CreateControlHierarchy(); + this.ChildControlsCreated = true; + } + else + { + if (!string.IsNullOrEmpty(this.DataField)) { - IsValid = false; - break; + this.UpdateDataSourceInternal(null, this._value, this.DataField); } } } protected virtual void CreateControlHierarchy() { - //Load Item Style - CssClass = "dnnFormItem"; - CssClass += (FormMode == DnnFormMode.Long) ? "" : " dnnFormShort"; + // Load Item Style + this.CssClass = "dnnFormItem"; + this.CssClass += (this.FormMode == DnnFormMode.Long) ? string.Empty : " dnnFormShort"; - if (String.IsNullOrEmpty(ResourceKey)) + if (string.IsNullOrEmpty(this.ResourceKey)) { - ResourceKey = DataField; + this.ResourceKey = this.DataField; } - //Add Label - var label = new DnnFormLabel - { - LocalResourceFile = LocalResourceFile, - ResourceKey = ResourceKey + ".Text", - ToolTipKey = ResourceKey + ".Help", - ViewStateMode = ViewStateMode.Disabled - }; - - if (Required) { + // Add Label + var label = new DnnFormLabel + { + LocalResourceFile = this.LocalResourceFile, + ResourceKey = this.ResourceKey + ".Text", + ToolTipKey = this.ResourceKey + ".Help", + ViewStateMode = ViewStateMode.Disabled, + }; + if (this.Required) + { label.RequiredField = true; } - Controls.Add(label); + this.Controls.Add(label); - WebControl inputControl = CreateControlInternal(this); + WebControl inputControl = this.CreateControlInternal(this); label.AssociatedControlID = inputControl.ID; - AddValidators(inputControl.ID); + this.AddValidators(inputControl.ID); + } + + private void AddValidators(string controlId) + { + var value = this.Value as string; + this.Validators.Clear(); + + // Add Validators + if (this.Required) + { + var requiredValidator = new RequiredFieldValidator + { + ID = this.ID + "_Required", + ErrorMessage = this.ResourceKey + this.RequiredMessageSuffix, + }; + this.Validators.Add(requiredValidator); + } + + if (!string.IsNullOrEmpty(this.ValidationExpression)) + { + var regexValidator = new RegularExpressionValidator + { + ID = this.ID + "_RegEx", + ErrorMessage = this.ResourceKey + this.ValidationMessageSuffix, + ValidationExpression = this.ValidationExpression, + }; + if (!string.IsNullOrEmpty(value)) + { + regexValidator.IsValid = Regex.IsMatch(value, this.ValidationExpression); + this.IsValid = regexValidator.IsValid; + } + + this.Validators.Add(regexValidator); + } + + if (this.Validators.Count > 0) + { + foreach (BaseValidator validator in this.Validators) + { + validator.ControlToValidate = controlId; + validator.Display = ValidatorDisplay.Dynamic; + validator.ErrorMessage = this.LocalizeString(validator.ErrorMessage); + validator.CssClass = "dnnFormMessage dnnFormError"; + this.Controls.Add(validator); + } + } } /// - /// Use container to add custom control hierarchy to + /// Use container to add custom control hierarchy to. /// /// - /// An "input" control that can be used for attaching validators + /// An "input" control that can be used for attaching validators. protected virtual WebControl CreateControlInternal(Control container) { return null; @@ -240,44 +253,46 @@ protected override void CreateChildControls() // CreateChildControls re-creates the children (the items) // using the saved view state. // First clear any existing child controls. - Controls.Clear(); + this.Controls.Clear(); - CreateControlHierarchy(); + this.CreateControlHierarchy(); } protected void DataBindInternal(string dataField, ref object value) { - var dictionary = DataSource as IDictionary; + var dictionary = this.DataSource as IDictionary; if (dictionary != null) { - if (!String.IsNullOrEmpty(dataField) && dictionary.Contains(dataField)) + if (!string.IsNullOrEmpty(dataField) && dictionary.Contains(dataField)) { value = dictionary[dataField]; } } else { - if (!String.IsNullOrEmpty(dataField)) + if (!string.IsNullOrEmpty(dataField)) { - if (String.IsNullOrEmpty(DataMember)) + if (string.IsNullOrEmpty(this.DataMember)) { - if (Property != null && Property.GetValue(DataSource, null) != null) + if (this.Property != null && this.Property.GetValue(this.DataSource, null) != null) { // ReSharper disable PossibleNullReferenceException - value = Property.GetValue(DataSource, null); + value = this.Property.GetValue(this.DataSource, null); + // ReSharper restore PossibleNullReferenceException - } + } } else { - if (Property != null && Property.GetValue(DataSource, null) != null) + if (this.Property != null && this.Property.GetValue(this.DataSource, null) != null) { // ReSharper disable PossibleNullReferenceException - object parentValue = Property.GetValue(DataSource, null); - if (ChildProperty != null && ChildProperty.GetValue(parentValue, null) != null) + object parentValue = this.Property.GetValue(this.DataSource, null); + if (this.ChildProperty != null && this.ChildProperty.GetValue(parentValue, null) != null) { - value = ChildProperty.GetValue(parentValue, null); + value = this.ChildProperty.GetValue(parentValue, null); } + // ReSharper restore PossibleNullReferenceException } } @@ -287,73 +302,64 @@ protected void DataBindInternal(string dataField, ref object value) protected virtual void DataBindInternal() { - DataBindInternal(DataField, ref _value); + this.DataBindInternal(this.DataField, ref this._value); } - public void DataBindItem(bool useDataSource) + protected void UpdateDataSource(object oldValue, object newValue, string dataField) { - if (useDataSource) - { - base.OnDataBinding(EventArgs.Empty); - Controls.Clear(); - ClearChildViewState(); - TrackViewState(); + this.CheckIsValid(); - DataBindInternal(); + this._value = newValue; - CreateControlHierarchy(); - ChildControlsCreated = true; - } - else - { - if (!String.IsNullOrEmpty(DataField)) - { - UpdateDataSourceInternal(null, _value, DataField); - } - } + this.UpdateDataSourceInternal(oldValue, newValue, dataField); + } + + protected override void LoadControlState(object state) + { + this._value = state; } private void UpdateDataSourceInternal(object oldValue, object newValue, string dataField) { - if (DataSource != null) + if (this.DataSource != null) { - if (DataSource is IDictionary) + if (this.DataSource is IDictionary) { - var dictionary = DataSource as IDictionary; + var dictionary = this.DataSource as IDictionary; if (dictionary.ContainsKey(dataField) && !ReferenceEquals(newValue, oldValue)) { dictionary[dataField] = newValue as string; } } - else if(DataSource is IIndexable) + else if (this.DataSource is IIndexable) { - var indexer = DataSource as IIndexable; + var indexer = this.DataSource as IIndexable; indexer[dataField] = newValue; } else { - if (String.IsNullOrEmpty(DataMember)) + if (string.IsNullOrEmpty(this.DataMember)) { - if (Property != null) + if (this.Property != null) { if (!ReferenceEquals(newValue, oldValue)) { - if (Property.PropertyType.IsEnum) + if (this.Property.PropertyType.IsEnum) { - Property.SetValue(DataSource, Enum.Parse(Property.PropertyType, newValue.ToString()), null); + this.Property.SetValue(this.DataSource, Enum.Parse(this.Property.PropertyType, newValue.ToString()), null); } else { - Property.SetValue(DataSource, Convert.ChangeType(newValue, Property.PropertyType), null); + this.Property.SetValue(this.DataSource, Convert.ChangeType(newValue, this.Property.PropertyType), null); } } } } else { - if (Property != null) + if (this.Property != null) { - object parentValue = Property.GetValue(DataSource, null); + object parentValue = this.Property.GetValue(this.DataSource, null); if (parentValue != null) { if (parentValue is IDictionary) @@ -369,58 +375,38 @@ private void UpdateDataSourceInternal(object oldValue, object newValue, string d var indexer = parentValue as IIndexable; indexer[dataField] = newValue; } - else if (ChildProperty != null) + else if (this.ChildProperty != null) { - if (Property.PropertyType.IsEnum) + if (this.Property.PropertyType.IsEnum) { - ChildProperty.SetValue(parentValue, Enum.Parse(ChildProperty.PropertyType, newValue.ToString()), null); + this.ChildProperty.SetValue(parentValue, Enum.Parse(this.ChildProperty.PropertyType, newValue.ToString()), null); } else { - ChildProperty.SetValue(parentValue, Convert.ChangeType(newValue, ChildProperty.PropertyType), null); + this.ChildProperty.SetValue(parentValue, Convert.ChangeType(newValue, this.ChildProperty.PropertyType), null); } } } } } } - } - } - - protected void UpdateDataSource(object oldValue, object newValue, string dataField) - { - CheckIsValid(); - - _value = newValue; - - UpdateDataSourceInternal(oldValue, newValue, dataField); - } - - #endregion - - #region Protected Methods - - protected override void LoadControlState(object state) - { - _value = state; + } } protected string LocalizeString(string key) { - return Localization.GetString(key, LocalResourceFile); + return Localization.GetString(key, this.LocalResourceFile); } protected override void OnInit(EventArgs e) { - Page.RegisterRequiresControlState(this); + this.Page.RegisterRequiresControlState(this); base.OnInit(e); } protected override object SaveControlState() { - return _value; - } - - #endregion + return this._value; + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs index 370bee10803..c40c0339298 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs @@ -1,90 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.UserControls; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - public class DnnFormLabel : Panel - { - public string AssociatedControlID { get; set; } - - public string LocalResourceFile { get; set; } - - public string ResourceKey { get; set; } - - public string ToolTipKey { get; set; } + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.UserControls; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client.ClientResourceManagement; + + public class DnnFormLabel : Panel + { + public string AssociatedControlID { get; set; } + + public string LocalResourceFile { get; set; } + + public string ResourceKey { get; set; } + + public string ToolTipKey { get; set; } public bool RequiredField { get; set; } - protected override void CreateChildControls() - { - string toolTipText = LocalizeString(ToolTipKey); - if (string.IsNullOrEmpty(CssClass)) - CssClass = "dnnLabel"; - - else if (!CssClass.Contains("dnnLabel")) - CssClass += " dnnLabel"; - - - //var outerPanel = new Panel(); - //outerPanel.CssClass = "dnnLabel"; - //Controls.Add(outerPanel); - + protected override void CreateChildControls() + { + string toolTipText = this.LocalizeString(this.ToolTipKey); + if (string.IsNullOrEmpty(this.CssClass)) + { + this.CssClass = "dnnLabel"; + } + else if (!this.CssClass.Contains("dnnLabel")) + { + this.CssClass += " dnnLabel"; + } + + // var outerPanel = new Panel(); + // outerPanel.CssClass = "dnnLabel"; + // Controls.Add(outerPanel); var outerLabel = new System.Web.UI.HtmlControls.HtmlGenericControl { TagName = "label" }; - Controls.Add(outerLabel); - - var label = new Label { ID = "Label", Text = LocalizeString(ResourceKey) }; - if (RequiredField) + this.Controls.Add(outerLabel); + + var label = new Label { ID = "Label", Text = this.LocalizeString(this.ResourceKey) }; + if (this.RequiredField) { label.CssClass += " dnnFormRequired"; } - outerLabel.Controls.Add(label); + + outerLabel.Controls.Add(label); var link = new LinkButton { ID = "Link", CssClass = "dnnFormHelp", TabIndex = -1 }; link.Attributes.Add("aria-label", "Help"); - Controls.Add(link); - - if (!String.IsNullOrEmpty(toolTipText)) - { - //CssClass += "dnnLabel"; + this.Controls.Add(link); - var tooltipPanel = new Panel() { CssClass = "dnnTooltip"}; - Controls.Add(tooltipPanel); + if (!string.IsNullOrEmpty(toolTipText)) + { + // CssClass += "dnnLabel"; + var tooltipPanel = new Panel() { CssClass = "dnnTooltip" }; + this.Controls.Add(tooltipPanel); - var panel = new Panel { ID = "Help", CssClass = "dnnFormHelpContent dnnClear" }; + var panel = new Panel { ID = "Help", CssClass = "dnnFormHelpContent dnnClear" }; tooltipPanel.Controls.Add(panel); - - var helpLabel = new Label { ID = "Text", CssClass="dnnHelpText", Text = LocalizeString(ToolTipKey) }; - panel.Controls.Add(helpLabel); - var pinLink = new HyperLink { CssClass = "pinHelp"}; + var helpLabel = new Label { ID = "Text", CssClass = "dnnHelpText", Text = this.LocalizeString(this.ToolTipKey) }; + panel.Controls.Add(helpLabel); + + var pinLink = new HyperLink { CssClass = "pinHelp" }; pinLink.Attributes.Add("href", "#"); pinLink.Attributes.Add("aria-label", "Pin"); panel.Controls.Add(pinLink); - JavaScript.RegisterClientReference(Page, ClientAPI.ClientNamespaceReferences.dnn); + JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - //ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); - } - } + + // ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); + } + } - protected string LocalizeString(string key) - { - return Localization.GetString(key, LocalResourceFile); - } - } + protected string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs index 4ebe95c8841..f9c96b27775 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.Collections; + public abstract class DnnFormListItemBase : DnnFormItemBase { private IEnumerable _listSource; @@ -20,15 +15,16 @@ public IEnumerable ListSource { get { - return _listSource; + return this._listSource; } + set { - var changed = !Equals(_listSource, value); + var changed = !Equals(this._listSource, value); if (changed) { - _listSource = value; - BindList(); + this._listSource = value; + this.BindList(); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs index e1c189018d5..a14fdd979ac 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs @@ -1,27 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + public class DnnFormLiteralItem : DnnFormItemBase { - public DnnFormLiteralItem() : base() + public DnnFormLiteralItem() + : base() { - ViewStateMode = ViewStateMode.Disabled; + this.ViewStateMode = ViewStateMode.Disabled; } protected override WebControl CreateControlInternal(Control container) { - var literal = new Label {ID = ID + "_Label", Text = Convert.ToString(Value)}; + var literal = new Label { ID = this.ID + "_Label", Text = Convert.ToString(this.Value) }; container.Controls.Add(literal); return literal; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormMode.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormMode.cs index f8f7e6aae70..25df527a879 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormMode.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormMode.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { public enum DnnFormMode { Inherit = 0, Short = 1, - Long = 2 + Long = 2, } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs index 859f5b68f42..09194c202ec 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs @@ -1,38 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - public class DnnFormPanel : WebControl + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + public class DnnFormPanel : WebControl { - public bool Expanded { get; set; } public string Text { get; set; } protected override void Render(HtmlTextWriter writer) { - writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass); + writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); writer.RenderBeginTag(HtmlTextWriterTag.H2); - if (Expanded) + if (this.Expanded) { writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnSectionExpanded"); } + writer.RenderBeginTag(HtmlTextWriterTag.A); - writer.Write(Text); + writer.Write(this.Text); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Fieldset); - RenderChildren(writer); + this.RenderChildren(writer); writer.RenderEndTag(); } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs index f295fdeb8f2..41eb322dd2b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + public class DnnFormPasswordItem : DnnFormItemBase { private TextBox _password; @@ -25,11 +21,12 @@ public string TextBoxCssClass { get { - return ViewState.GetValue("TextBoxCssClass", string.Empty); + return this.ViewState.GetValue("TextBoxCssClass", string.Empty); } + set { - ViewState.SetValue("TextBoxCssClass", value, string.Empty); + this.ViewState.SetValue("TextBoxCssClass", value, string.Empty); } } @@ -37,82 +34,81 @@ public string ContainerCssClass { get { - return ViewState.GetValue("ContainerCssClass", string.Empty); + return this.ViewState.GetValue("ContainerCssClass", string.Empty); } + set { - ViewState.SetValue("ContainerCssClass", value, string.Empty); + this.ViewState.SetValue("ContainerCssClass", value, string.Empty); } } - private void TextChanged(object sender, EventArgs e) - { - UpdateDataSource(Value, _password.Text, DataField); - } - /// - /// Use container to add custom control hierarchy to + /// Use container to add custom control hierarchy to. /// /// - /// An "input" control that can be used for attaching validators + /// An "input" control that can be used for attaching validators. protected override WebControl CreateControlInternal(Control container) { - _password = new TextBox() + this._password = new TextBox() { - ID = ID + "_TextBox", + ID = this.ID + "_TextBox", TextMode = TextBoxMode.Password, - CssClass = TextBoxCssClass, - MaxLength = 39, //ensure password cannot be cut if too long - Text = Convert.ToString(Value) // Load from ControlState + CssClass = this.TextBoxCssClass, + MaxLength = 39, // ensure password cannot be cut if too long + Text = Convert.ToString(this.Value), // Load from ControlState }; - _password.Attributes.Add("autocomplete", "off"); - _password.Attributes.Add("aria-label", DataField); - _password.TextChanged += TextChanged; + this._password.Attributes.Add("autocomplete", "off"); + this._password.Attributes.Add("aria-label", this.DataField); + this._password.TextChanged += this.TextChanged; - var passwordContainer = new Panel() { ID = "passwordContainer", CssClass = ContainerCssClass }; + var passwordContainer = new Panel() { ID = "passwordContainer", CssClass = this.ContainerCssClass }; // add control hierarchy to the container container.Controls.Add(passwordContainer); - passwordContainer.Controls.Add(_password); + passwordContainer.Controls.Add(this._password); // return input control that can be used for validation - return _password; + return this._password; } protected override void OnInit(EventArgs e) { base.OnInit(e); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); JavaScript.RequestRegistration(CommonJs.DnnPlugins); } + private void TextChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this._password.Text, this.DataField); + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); var options = new DnnPaswordStrengthOptions(); var optionsAsJsonString = Json.Serialize(options); - var script = string.Format("dnn.initializePasswordStrength('.{0}', {1});{2}", - TextBoxCssClass, optionsAsJsonString, Environment.NewLine); + var script = string.Format( + "dnn.initializePasswordStrength('.{0}', {1});{2}", + this.TextBoxCssClass, optionsAsJsonString, Environment.NewLine); - if (ScriptManager.GetCurrent(Page) != null) + if (ScriptManager.GetCurrent(this.Page) != null) { // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "PasswordStrength", script, true); + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "PasswordStrength", script, true); } else { - Page.ClientScript.RegisterStartupScript(GetType(), "PasswordStrength", script, true); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PasswordStrength", script, true); } - } - } - } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs index ff45ec5acfb..7a9e42ac362 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs @@ -1,77 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Web.UI; + using System.Web.UI.WebControls; + public class DnnFormRadioButtonListItem : DnnFormListItemBase { private RadioButtonList _radioButtonList; protected override void BindList() { - if (_radioButtonList != null) + if (this._radioButtonList != null) { - string selectedValue = !_radioButtonList.Page.IsPostBack ? Convert.ToString(Value) : _radioButtonList.Page.Request.Form[_radioButtonList.UniqueID]; + string selectedValue = !this._radioButtonList.Page.IsPostBack ? Convert.ToString(this.Value) : this._radioButtonList.Page.Request.Form[this._radioButtonList.UniqueID]; - if (ListSource is Dictionary) + if (this.ListSource is Dictionary) { - var items = ListSource as Dictionary; + var items = this.ListSource as Dictionary; foreach (var item in items) { var listItem = new ListItem(item.Key, item.Value); - listItem.Attributes.Add("onClick", OnClientClicked); + listItem.Attributes.Add("onClick", this.OnClientClicked); - _radioButtonList.Items.Add(listItem); + this._radioButtonList.Items.Add(listItem); } } else { - _radioButtonList.DataTextField = ListTextField; - _radioButtonList.DataValueField = ListValueField; - _radioButtonList.DataSource = ListSource; + this._radioButtonList.DataTextField = this.ListTextField; + this._radioButtonList.DataValueField = this.ListValueField; + this._radioButtonList.DataSource = this.ListSource; - _radioButtonList.DataBind(); + this._radioButtonList.DataBind(); } - if (String.IsNullOrEmpty(selectedValue)) + + if (string.IsNullOrEmpty(selectedValue)) { - selectedValue = DefaultValue; + selectedValue = this.DefaultValue; } - //Reset SelectedValue - if (_radioButtonList.Items.FindByValue(selectedValue) != null) + // Reset SelectedValue + if (this._radioButtonList.Items.FindByValue(selectedValue) != null) { - _radioButtonList.Items.FindByValue(selectedValue).Selected = true; + this._radioButtonList.Items.FindByValue(selectedValue).Selected = true; } - if (selectedValue != Convert.ToString(Value)) + if (selectedValue != Convert.ToString(this.Value)) { - UpdateDataSource(Value, selectedValue, DataField); + this.UpdateDataSource(this.Value, selectedValue, this.DataField); } } } protected override WebControl CreateControlInternal(Control container) { - _radioButtonList = new RadioButtonList { ID = ID + "_RadioButtonList", RepeatColumns = 1, RepeatDirection = RepeatDirection.Vertical, RepeatLayout = RepeatLayout.Flow}; + this._radioButtonList = new RadioButtonList { ID = this.ID + "_RadioButtonList", RepeatColumns = 1, RepeatDirection = RepeatDirection.Vertical, RepeatLayout = RepeatLayout.Flow }; - container.Controls.Add(_radioButtonList); + container.Controls.Add(this._radioButtonList); - if (ListSource != null) + if (this.ListSource != null) { - BindList(); + this.BindList(); } - return _radioButtonList; + return this._radioButtonList; } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs index 633f3ddc27d..a6b14c6ed00 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs @@ -1,29 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.Collections.Generic; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + [ParseChildren(true)] public class DnnFormSection : WebControl, INamingContainer { public DnnFormSection() { - Items = new List(); + this.Items = new List(); } public bool Expanded { get; set; } - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Items { get; private set; } public string ResourceKey { get; set; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs index 27151776946..9eabf61e67a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs @@ -1,39 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.Collections.Generic; + using System.Web.UI; + using System.Web.UI.WebControls; + internal class DnnFormSectionTemplate : ITemplate { public DnnFormSectionTemplate() { - Items = new List(); + this.Items = new List(); } public List Items { get; private set; } - public string LocalResourceFile { get; set; } - - #region ITemplate Members - + public string LocalResourceFile { get; set; } + public void InstantiateIn(Control container) { var webControl = container as WebControl; if (webControl != null) { - DnnFormEditor.SetUpItems(Items, webControl, LocalResourceFile, false); + DnnFormEditor.SetUpItems(this.Items, webControl, this.LocalResourceFile, false); } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs index aff8cf0e3cf..058e269249c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs @@ -1,37 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.Collections.Generic; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + [ParseChildren(true)] public class DnnFormTab : WebControl, INamingContainer { public DnnFormTab() { - Sections = new List(); - Items = new List(); + this.Sections = new List(); + this.Items = new List(); } public bool IncludeExpandAll { get; set; } - internal string ExpandAllScript { get; set; } - - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Items { get; private set; } - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Sections { get; private set; } + internal string ExpandAllScript { get; set; } + public string ResourceKey { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTabStrip.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTabStrip.cs index b73deac6f7f..c02bfe40f35 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTabStrip.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTabStrip.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - public class DnnFormTabStrip : ListControl + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + public class DnnFormTabStrip : ListControl { - protected override void Render(HtmlTextWriter writer) { - writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass); + writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); writer.RenderBeginTag(HtmlTextWriterTag.Ul); - foreach (ListItem item in Items) + foreach (ListItem item in this.Items) { writer.RenderBeginTag(HtmlTextWriterTag.Li); - + writer.AddAttribute(HtmlTextWriterAttribute.Href, item.Value); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(item.Text); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs index afdc82ec6e1..62ac54dbc29 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs @@ -1,31 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.ComponentModel; + using System.Web.UI; + [ParseChildren(true)] public class DnnFormTemplateItem : DnnFormItemBase { - [Browsable(false), DefaultValue(null), Description("The Item Template."), TemplateInstance(TemplateInstance.Single), PersistenceMode(PersistenceMode.InnerProperty), - TemplateContainer(typeof (DnnFormEmptyTemplate))] + [Browsable(false)] + [DefaultValue(null)] + [Description("The Item Template.")] + [TemplateInstance(TemplateInstance.Single)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TemplateContainer(typeof(DnnFormEmptyTemplate))] public ITemplate ItemTemplate { get; set; } protected override void CreateControlHierarchy() { - CssClass += " dnnFormItem"; - CssClass += (FormMode == DnnFormMode.Long) ? " dnnFormLong" : " dnnFormShort"; + this.CssClass += " dnnFormItem"; + this.CssClass += (this.FormMode == DnnFormMode.Long) ? " dnnFormLong" : " dnnFormShort"; var template = new DnnFormEmptyTemplate(); - ItemTemplate.InstantiateIn(template); - Controls.Add(template); + this.ItemTemplate.InstantiateIn(template); + this.Controls.Add(template); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs index 0f06a0e4140..a66604450be 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + public class DnnFormTextBoxItem : DnnFormItemBase { private TextBox _textBox; @@ -30,66 +25,64 @@ public string TextBoxCssClass { get { - return ViewState.GetValue("TextBoxCssClass", string.Empty); + return this.ViewState.GetValue("TextBoxCssClass", string.Empty); } + set { - ViewState.SetValue("TextBoxCssClass", value, string.Empty); + this.ViewState.SetValue("TextBoxCssClass", value, string.Empty); } } public TextBoxMode TextMode { get; set; } - /// - /// do not output field's value after post back when text mode set to password mode. - /// - public bool ClearContentInPasswordMode { get; set; } - - private void TextChanged(object sender, EventArgs e) - { - UpdateDataSource(Value, _textBox.Text, DataField); - } + /// + /// Gets or sets a value indicating whether do not output field's value after post back when text mode set to password mode. + /// + public bool ClearContentInPasswordMode { get; set; } protected override WebControl CreateControlInternal(Control container) { - - _textBox = new TextBox { ID = ID + "_TextBox" }; - - _textBox.Rows = Rows; - _textBox.Columns = Columns; - _textBox.TextMode = TextMode; - _textBox.CssClass = TextBoxCssClass; - _textBox.AutoCompleteType = AutoCompleteType; - _textBox.TextChanged += TextChanged; - _textBox.Attributes.Add("aria-label", DataField); - - //Load from ControlState - _textBox.Text = Convert.ToString(Value); - if (TextMode == TextBoxMode.Password) + this._textBox = new TextBox { ID = this.ID + "_TextBox" }; + + this._textBox.Rows = this.Rows; + this._textBox.Columns = this.Columns; + this._textBox.TextMode = this.TextMode; + this._textBox.CssClass = this.TextBoxCssClass; + this._textBox.AutoCompleteType = this.AutoCompleteType; + this._textBox.TextChanged += this.TextChanged; + this._textBox.Attributes.Add("aria-label", this.DataField); + + // Load from ControlState + this._textBox.Text = Convert.ToString(this.Value); + if (this.TextMode == TextBoxMode.Password) { - _textBox.Attributes.Add("autocomplete", "off"); + this._textBox.Attributes.Add("autocomplete", "off"); } - if (MaxLength > 0) + + if (this.MaxLength > 0) { - _textBox.MaxLength = MaxLength; + this._textBox.MaxLength = this.MaxLength; } - container.Controls.Add(_textBox); + container.Controls.Add(this._textBox); - return _textBox; + return this._textBox; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (TextMode == TextBoxMode.Password && !ClearContentInPasswordMode) + if (this.TextMode == TextBoxMode.Password && !this.ClearContentInPasswordMode) { - _textBox.Attributes.Add("value", Convert.ToString(Value)); + this._textBox.Attributes.Add("value", Convert.ToString(this.Value)); } } + private void TextChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this._textBox.Text, this.DataField); + } } - -} - +} diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs index 449fa6f1bf2..091df32a75b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs @@ -1,32 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Specialized; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - public class DnnGenericHiddenField : HiddenField where T : class, new() + using System.Collections.Specialized; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + + public class DnnGenericHiddenField : HiddenField + where T : class, new() { - private T _typedValue = null; private bool _isValueSerialized = false; + public T TypedValue { get { - return _typedValue; + return this._typedValue; } + set { - _typedValue = value; - _isValueSerialized = false; + this._typedValue = value; + this._isValueSerialized = false; } } @@ -34,25 +35,31 @@ public T TypedValueOrDefault { get { - return TypedValue ?? (TypedValue = new T()); + return this.TypedValue ?? (this.TypedValue = new T()); } } public bool HasValue { - get { return _typedValue != null; } + get { return this._typedValue != null; } + } + + public override void RenderControl(HtmlTextWriter writer) + { + this.EnsureValue(); + base.RenderControl(writer); } protected override object SaveViewState() { - EnsureValue(); + this.EnsureValue(); return base.SaveViewState(); } protected override void LoadViewState(object savedState) { base.LoadViewState(savedState); - SetTypedValue(); + this.SetTypedValue(); } protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection) @@ -60,41 +67,35 @@ protected override bool LoadPostData(string postDataKey, NameValueCollection pos var controlsStateChanged = base.LoadPostData(postDataKey, postCollection); if (controlsStateChanged) { - SetTypedValue(); + this.SetTypedValue(); } + return controlsStateChanged; } + protected override void TrackViewState() + { + this.EnsureValue(); + base.TrackViewState(); + } + private void SetTypedValue() { - _typedValue = string.IsNullOrEmpty(Value) ? null : Json.Deserialize(Value); + this._typedValue = string.IsNullOrEmpty(this.Value) ? null : Json.Deserialize(this.Value); } private void EnsureValue() { - if (!_isValueSerialized) + if (!this._isValueSerialized) { - SerializeValue(); + this.SerializeValue(); } } private void SerializeValue() { - Value = _typedValue == null ? string.Empty : Json.Serialize(_typedValue); - _isValueSerialized = true; - } - - protected override void TrackViewState() - { - EnsureValue(); - base.TrackViewState(); - } - - public override void RenderControl(HtmlTextWriter writer) - { - EnsureValue(); - base.RenderControl(writer); + this.Value = this._typedValue == null ? string.Empty : Json.Serialize(this._typedValue); + this._isValueSerialized = true; } - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs index 8d4ed0f6768..fc7ef1a6a0f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs @@ -1,39 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + public class DnnImage : Image - { - - #region Public Properties - + { public string IconKey { get; set; } + public string IconSize { get; set; } - public string IconStyle { get; set; } - - #endregion - - #region "Protected Methods" - + + public string IconStyle { get; set; } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (string.IsNullOrEmpty(ImageUrl)) - ImageUrl = Entities.Icons.IconController.IconURL(IconKey, IconSize, IconStyle); - } - - #endregion - + if (string.IsNullOrEmpty(this.ImageUrl)) + { + this.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs index 13fd973df34..93f55b42adf 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs @@ -1,39 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + public class DnnImageButton : ImageButton - { - - #region Public Properties - + { public string IconKey { get; set; } + public string IconSize { get; set; } - public string IconStyle { get; set; } - - #endregion - - #region "Protected Methods" - + + public string IconStyle { get; set; } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (string.IsNullOrEmpty(ImageUrl)) - ImageUrl = Entities.Icons.IconController.IconURL(IconKey, IconSize, IconStyle); - } - - #endregion - + if (string.IsNullOrEmpty(this.ImageUrl)) + { + this.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageEditControl.cs index 7d0e4569921..8b9cd0488e0 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageEditControl.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using DotNetNuke.Common; + public class DnnImageEditControl : DnnFileEditControl { public DnnImageEditControl() { - FileFilter = Globals.glbImageFileTypes; + this.FileFilter = Globals.glbImageFileTypes; } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs index 6c92ff76010..793ebc8723c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs @@ -1,60 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + public class DnnLabel : Label, ILocalizable { - - private bool _localize = true; - - #region Constructors - + private bool _localize = true; + public DnnLabel() { - CssClass = "dnnFormLabel"; - } - - #endregion - - #region "Protected Methods" - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - base.Render(writer); - } - - #endregion - - #region ILocalizable Implementation - + this.CssClass = "dnnFormLabel"; + } + public bool Localize { get { - return !DesignMode && _localize; + return !this.DesignMode && this._localize; } + set { - _localize = value; + this._localize = value; } } @@ -62,28 +35,37 @@ public bool Localize public virtual void LocalizeStrings() { - if (Localize) + if (this.Localize) { - if (!string.IsNullOrEmpty(ToolTip)) + if (!string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(ToolTip, LocalResourceFile); + this.ToolTip = Localization.GetString(this.ToolTip, this.LocalResourceFile); } - if (!string.IsNullOrEmpty(Text)) + if (!string.IsNullOrEmpty(this.Text)) { - var unLocalized = Text; + var unLocalized = this.Text; - Text = Localization.GetString(unLocalized, LocalResourceFile); + this.Text = Localization.GetString(unLocalized, this.LocalResourceFile); - if (string.IsNullOrEmpty(ToolTip)) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(unLocalized + ".ToolTip", LocalResourceFile); + this.ToolTip = Localization.GetString(unLocalized + ".ToolTip", this.LocalResourceFile); } } } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); } - #endregion - + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs index fa28e281017..71d8bdc1b15 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs @@ -1,107 +1,99 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + public class DnnLanguageLabel : CompositeControl, ILocalizable - { - #region Controls - + { private Image _Flag; - private Label _Label; - - #endregion - + private Label _Label; + public DnnLanguageLabel() { - Localize = true; - } - - #region Public Properties - + this.Localize = true; + } + public CultureDropDownTypes DisplayType { get; set; } public string Language { get { - return (string) ViewState["Language"]; + return (string)this.ViewState["Language"]; } + set { - ViewState["Language"] = value; + this.ViewState["Language"] = value; } - } - - #endregion + } + + public bool Localize { get; set; } - #region Protected Methods + public string LocalResourceFile { get; set; } + public virtual void LocalizeStrings() + { + } + protected override void OnInit(EventArgs e) { base.OnInit(e); - LocalResourceFile = Utilities.GetLocalResourceFile(this); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); } /// ----------------------------------------------------------------------------- /// /// CreateChildControls overrides the Base class's method to correctly build the - /// control based on the configuration + /// control based on the configuration. /// /// ----------------------------------------------------------------------------- protected override void CreateChildControls() { - //First clear the controls collection - Controls.Clear(); + // First clear the controls collection + this.Controls.Clear(); - _Flag = new Image {ViewStateMode = ViewStateMode.Disabled}; - Controls.Add(_Flag); + this._Flag = new Image { ViewStateMode = ViewStateMode.Disabled }; + this.Controls.Add(this._Flag); - Controls.Add(new LiteralControl(" ")); + this.Controls.Add(new LiteralControl(" ")); - _Label = new Label(); - _Label.ViewStateMode = ViewStateMode.Disabled; - Controls.Add(_Label); - - //Call base class's method + this._Label = new Label(); + this._Label.ViewStateMode = ViewStateMode.Disabled; + this.Controls.Add(this._Label); + // Call base class's method base.CreateChildControls(); } /// ----------------------------------------------------------------------------- /// - /// OnPreRender runs just before the control is rendered + /// OnPreRender runs just before the control is rendered. /// /// ----------------------------------------------------------------------------- protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (string.IsNullOrEmpty(Language)) + if (string.IsNullOrEmpty(this.Language)) { - _Flag.ImageUrl = "~/images/Flags/none.gif"; + this._Flag.ImageUrl = "~/images/Flags/none.gif"; } else { - _Flag.ImageUrl = string.Format("~/images/Flags/{0}.gif", Language); + this._Flag.ImageUrl = string.Format("~/images/Flags/{0}.gif", this.Language); } - if (DisplayType == 0) + if (this.DisplayType == 0) { PortalSettings _PortalSettings = PortalController.Instance.GetCurrentPortalSettings(); string _ViewTypePersonalizationKey = "ViewType" + _PortalSettings.PortalId; @@ -109,42 +101,29 @@ protected override void OnPreRender(EventArgs e) switch (_ViewType) { case "NATIVE": - DisplayType = CultureDropDownTypes.NativeName; + this.DisplayType = CultureDropDownTypes.NativeName; break; case "ENGLISH": - DisplayType = CultureDropDownTypes.EnglishName; + this.DisplayType = CultureDropDownTypes.EnglishName; break; default: - DisplayType = CultureDropDownTypes.DisplayName; + this.DisplayType = CultureDropDownTypes.DisplayName; break; } } string localeName = null; - if (string.IsNullOrEmpty(Language)) + if (string.IsNullOrEmpty(this.Language)) { localeName = Localization.GetString("NeutralCulture", Localization.GlobalResourceFile); } else { - localeName = Localization.GetLocaleName(Language, DisplayType); + localeName = Localization.GetLocaleName(this.Language, this.DisplayType); } - _Label.Text = localeName; - _Flag.AlternateText = localeName; - } - - #endregion - - #region ILocalizable Implementation - - public bool Localize { get; set; } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() - { - } - - #endregion + + this._Label.Text = localeName; + this._Flag.AlternateText = localeName; + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs index 8d5cb846f11..3728f5e58e8 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs @@ -1,50 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + public class DnnLiteral : Literal, ILocalizable { - private bool _Localize = true; - - #region "Protected Methods" - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - base.Render(writer); - } - - #endregion - - #region "ILocalizable Implementation" - + private bool _Localize = true; + public bool Localize { get { - return _Localize; + return this._Localize; } + set { - _Localize = value; + this._Localize = value; } } @@ -52,15 +30,25 @@ public bool Localize public virtual void LocalizeStrings() { - if ((Localize)) + if (this.Localize) { - if ((!string.IsNullOrEmpty(Text))) + if (!string.IsNullOrEmpty(this.Text)) { - Text = Localization.GetString(Text, LocalResourceFile); + this.Text = Localization.GetString(this.Text, this.LocalResourceFile); } } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); } - #endregion + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs index 8c299967268..e96c68909ef 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs @@ -1,94 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Linq; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Linq; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Services.Tokens; + /// /// This control is used for displaying a template based list of users based upon various filter and sorting capabilities. /// [ToolboxData("<{0}:DnnMemberListControl runat=\"server\">")] public class DnnMemberListControl : WebControl - { - #region Private Variables - + { private UserInfo _currentUser; - private RelationshipController _relationshipController; - - #endregion - - #region Properties - - #region Layout Properties - + private RelationshipController _relationshipController; + /// /// Gets or sets the template for displaying the header section of a DnnMemberListControl object. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] public string HeaderTemplate { get; set; } - + /// /// Gets or sets the template for the row header. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] public string RowHeaderTemplate { get; set; } /// /// Gets or sets the template for displaying an item in a DnnMemberListControl object. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] public string ItemTemplate { get; set; } /// /// Gets or sets the template for the row footer. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] public string RowFooterTemplate { get; set; } /// /// Gets or sets the template for displaying the alternating row headers in a DnnMemberListControl object. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] public string AlternatingRowHeaderTemplate { get; set; } /// /// Gets or sets the template for displaying the alternating items in a DnnMemberListControl object. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] public string AlternatingItemTemplate { get; set; } /// /// Gets or sets the template for displaying the alternating row footers in a DnnMemberListControl object. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] public string AlternatingRowFooterTemplate { get; set; } /// /// Gets or sets the template for displaying the footer section of a DnnMemberListControl object. /// - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] - public string FooterTemplate { get; set; } - - #endregion - - #region Filter Properties - + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] + public string FooterTemplate { get; set; } + /// /// Gets or sets the index of the currently displayed page. /// @@ -100,21 +91,21 @@ public class DnnMemberListControl : WebControl /// [DefaultValue(10)] public int PageSize { get; set; } - + /// /// Gets or sets the number of items displayed on each row. /// [DefaultValue(1)] public int RowSize { get; set; } - + /// - /// Sets the property value to sort by. + /// Gets or sets the property value to sort by. /// [DefaultValue("UserId")] public string SortBy { get; set; } /// - /// Gets or sets the sort direction + /// Gets or sets a value indicating whether gets or sets the sort direction. /// [DefaultValue(true)] public bool SortAscending { get; set; } @@ -125,43 +116,44 @@ public class DnnMemberListControl : WebControl /// /// Posible keys are: RoleId, RelationshipTypeId, UserId, Profile:PropertyName, FirstName, LastName, DisplayName, Username, Email. /// - public IDictionary Filters { get; set; } - - #endregion - - #endregion - - #region Event Handlers - + public IDictionary Filters { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); - - _currentUser = UserController.Instance.GetCurrentUserInfo(); - _relationshipController = new RelationshipController(); + + this._currentUser = UserController.Instance.GetCurrentUserInfo(); + this._relationshipController = new RelationshipController(); } protected override void Render(HtmlTextWriter writer) { - if (ItemTemplate == "") return; - - writer.Write(HeaderTemplate); + if (this.ItemTemplate == string.Empty) + { + return; + } + + writer.Write(this.HeaderTemplate); // Filters - if (Filters == null) Filters = new Dictionary(); + if (this.Filters == null) + { + this.Filters = new Dictionary(); + } + var additionalFilters = new Dictionary(); - additionalFilters.Add("Records", PageSize.ToString()); - additionalFilters.Add("PageIndex", PageIndex.ToString()); - additionalFilters.Add("Rowsize", RowSize.ToString()); - additionalFilters.Add("SortBy", SortBy); - additionalFilters.Add("SortAscending", SortAscending.ToString()); + additionalFilters.Add("Records", this.PageSize.ToString()); + additionalFilters.Add("PageIndex", this.PageIndex.ToString()); + additionalFilters.Add("Rowsize", this.RowSize.ToString()); + additionalFilters.Add("SortBy", this.SortBy); + additionalFilters.Add("SortAscending", this.SortAscending.ToString()); // Currently Not Used by the SPROC - var filterUser = Filters.ContainsKey("UserId") && Filters["UserId"] != null ? new UserInfo() { UserID = int.Parse(Filters["UserId"]) } : new UserInfo() { PortalID = _currentUser.PortalID }; - var role = Filters.ContainsKey("RoleId") && Filters["RoleId"] != null ? new UserRoleInfo() { RoleID = int.Parse(Filters["RoleId"]) } : null; - var relationship = Filters.ContainsKey("RelationshipTypeId") && Filters["RelationshipTypeId"] != null ? new RelationshipType() { RelationshipTypeId = int.Parse(Filters["RelationshipTypeId"]) } : null; - - foreach (var filter in Filters.Where(filter => !additionalFilters.ContainsKey(filter.Key))) + var filterUser = this.Filters.ContainsKey("UserId") && this.Filters["UserId"] != null ? new UserInfo() { UserID = int.Parse(this.Filters["UserId"]) } : new UserInfo() { PortalID = this._currentUser.PortalID }; + var role = this.Filters.ContainsKey("RoleId") && this.Filters["RoleId"] != null ? new UserRoleInfo() { RoleID = int.Parse(this.Filters["RoleId"]) } : null; + var relationship = this.Filters.ContainsKey("RelationshipTypeId") && this.Filters["RelationshipTypeId"] != null ? new RelationshipType() { RelationshipTypeId = int.Parse(this.Filters["RelationshipTypeId"]) } : null; + + foreach (var filter in this.Filters.Where(filter => !additionalFilters.ContainsKey(filter.Key))) { additionalFilters.Add(filter.Key, filter.Value); } @@ -169,14 +161,13 @@ protected override void Render(HtmlTextWriter writer) var row = 0; var users = new DataTable(); - //users.Load(_relationshipController.GetUsersAdvancedSearch(_currentUser, filterUser, role, relationship, Filters, additionalFilters)); - + // users.Load(_relationshipController.GetUsersAdvancedSearch(_currentUser, filterUser, role, relationship, Filters, additionalFilters)); if (users.Rows.Count > 0) { foreach (DataRow user in users.Rows) { - //Row Header - writer.Write(string.IsNullOrEmpty(AlternatingRowHeaderTemplate) || row%2 == 0 ? RowHeaderTemplate : AlternatingRowHeaderTemplate); + // Row Header + writer.Write(string.IsNullOrEmpty(this.AlternatingRowHeaderTemplate) || row % 2 == 0 ? this.RowHeaderTemplate : this.AlternatingRowHeaderTemplate); var tokenReplace = new TokenReplace(); var tokenKeyValues = new Dictionary(); @@ -186,20 +177,18 @@ protected override void Render(HtmlTextWriter writer) tokenKeyValues.Add(col.ColumnName, user[col.ColumnName].ToString()); } - var listItem = string.IsNullOrEmpty(AlternatingItemTemplate) || row%2 == 0 ? ItemTemplate : AlternatingItemTemplate; + var listItem = string.IsNullOrEmpty(this.AlternatingItemTemplate) || row % 2 == 0 ? this.ItemTemplate : this.AlternatingItemTemplate; listItem = tokenReplace.ReplaceEnvironmentTokens(listItem, tokenKeyValues, "Member"); writer.Write(listItem); - //Row Footer - writer.Write(string.IsNullOrEmpty(AlternatingRowFooterTemplate) || row%2 == 0 ? RowFooterTemplate : AlternatingRowFooterTemplate); + // Row Footer + writer.Write(string.IsNullOrEmpty(this.AlternatingRowFooterTemplate) || row % 2 == 0 ? this.RowFooterTemplate : this.AlternatingRowFooterTemplate); row++; } } - writer.Write(FooterTemplate); - } - - #endregion + writer.Write(this.FooterTemplate); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs index 30f89a2fb68..e103b5a029b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs @@ -1,99 +1,98 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Globalization; -using System.Linq; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.UI.WebControls.Extensions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Globalization; + using System.Linq; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.UI.WebControls.Extensions; + [ToolboxData("<{0}:DnnPageDropDownList runat='server'>")] public class DnnPageDropDownList : DnnDropDownList { + /// + /// Gets or sets a value indicating whether whether disabled pages are not selectable + /// Please note: IncludeDisabledTabs needs also be set to true to include disabled pages. + /// + public bool DisabledNotSelectable { get; set; } + /// + /// Gets or sets a value indicating whether whether include active page. + /// + public bool IncludeActiveTab { get; set; } + + /// + /// Gets or sets a value indicating whether whether include pages which are disabled. + /// + public bool IncludeDisabledTabs { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); - Roles = new List(); + this.Roles = new List(); - SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); - Services.GetTreeMethod = "ItemListService/GetPages"; - Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendants"; - Services.SearchTreeMethod = "ItemListService/SearchPages"; - Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPage"; - Services.ServiceRoot = "InternalServices"; - Services.SortTreeMethod = "ItemListService/SortPages"; + this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); + this.Services.GetTreeMethod = "ItemListService/GetPages"; + this.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendants"; + this.Services.SearchTreeMethod = "ItemListService/SearchPages"; + this.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPage"; + this.Services.ServiceRoot = "InternalServices"; + this.Services.SortTreeMethod = "ItemListService/SortPages"; } protected override void OnPreRender(EventArgs e) { this.AddCssClass("page"); - if (InternalPortalId.HasValue) + if (this.InternalPortalId.HasValue) { - Services.Parameters.Add("PortalId", InternalPortalId.Value.ToString(CultureInfo.InvariantCulture)); - } + this.Services.Parameters.Add("PortalId", this.InternalPortalId.Value.ToString(CultureInfo.InvariantCulture)); + } - Services.Parameters.Add("includeDisabled", IncludeDisabledTabs.ToString().ToLowerInvariant()); - Services.Parameters.Add("includeAllTypes", IncludeAllTabTypes.ToString().ToLowerInvariant()); - Services.Parameters.Add("includeActive", IncludeActiveTab.ToString().ToLowerInvariant()); - Services.Parameters.Add("disabledNotSelectable", DisabledNotSelectable.ToString().ToLowerInvariant()); - Services.Parameters.Add("includeHostPages", (IncludeHostPages && UserController.Instance.GetCurrentUserInfo().IsSuperUser).ToString().ToLowerInvariant()); - Services.Parameters.Add("roles", string.Join(";", Roles.ToArray())); + this.Services.Parameters.Add("includeDisabled", this.IncludeDisabledTabs.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("includeAllTypes", this.IncludeAllTabTypes.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("includeActive", this.IncludeActiveTab.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("disabledNotSelectable", this.DisabledNotSelectable.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("includeHostPages", (this.IncludeHostPages && UserController.Instance.GetCurrentUserInfo().IsSuperUser).ToString().ToLowerInvariant()); + this.Services.Parameters.Add("roles", string.Join(";", this.Roles.ToArray())); base.OnPreRender(e); - //add the selected folder's level path so that it can expand to the selected node in client side. - var selectedPage = SelectedPage; + // add the selected folder's level path so that it can expand to the selected node in client side. + var selectedPage = this.SelectedPage; if (selectedPage != null && selectedPage.ParentId > Null.NullInteger) { var tabLevel = string.Empty; - var parentTab = TabController.Instance.GetTab(selectedPage.ParentId, PortalId, false); + var parentTab = TabController.Instance.GetTab(selectedPage.ParentId, this.PortalId, false); while (parentTab != null) { tabLevel = string.Format("{0},{1}", parentTab.TabID, tabLevel); - parentTab = TabController.Instance.GetTab(parentTab.ParentId, PortalId, false); + parentTab = TabController.Instance.GetTab(parentTab.ParentId, this.PortalId, false); } - ExpandPath = tabLevel.TrimEnd(','); + this.ExpandPath = tabLevel.TrimEnd(','); } } /// - /// Whether disabled pages are not selectable - /// Please note: IncludeDisabledTabs needs also be set to true to include disabled pages - /// - public bool DisabledNotSelectable { get; set; } - - /// - /// Whether include active page. + /// Gets or sets a value indicating whether whether include pages which tab type is not normal. /// - public bool IncludeActiveTab { get; set; } - - /// - /// Whether include pages which are disabled. - /// - public bool IncludeDisabledTabs { get; set; } - - /// - /// Whether include pages which tab type is not normal. - /// - public bool IncludeAllTabTypes { get; set; } + public bool IncludeAllTabTypes { get; set; } /// - /// Whether include Host Pages + /// Gets or sets a value indicating whether whether include Host Pages. /// public bool IncludeHostPages { get; set; } @@ -101,51 +100,55 @@ public int PortalId { get { - if (InternalPortalId.HasValue) + if (this.InternalPortalId.HasValue) { - return InternalPortalId.Value; + return this.InternalPortalId.Value; } + return PortalSettings.Current.ActiveTab.IsSuperTab ? -1 : PortalSettings.Current.PortalId; } + set { - InternalPortalId = value; + this.InternalPortalId = value; } } - private int? InternalPortalId + /// + /// Gets or sets the selected Page in the control, or selects the Page in the control. + /// + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public TabInfo SelectedPage { get { - return ViewState.GetValue("PortalId", null); + var pageId = this.SelectedItemValueAsInt; + return (pageId == Null.NullInteger) ? null : TabController.Instance.GetTab(pageId, this.PortalId, false); } + set { - ViewState.SetValue("PortalId", value, null); + this.SelectedItem = (value != null) ? new ListItem() { Text = value.IndentedTabName, Value = value.TabID.ToString(CultureInfo.InvariantCulture) } : null; } } /// - /// Gets the selected Page in the control, or selects the Page in the control. + /// Gets or sets specific to only show tabs which have view permission on these roles. /// - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public TabInfo SelectedPage + public IList Roles { get; set; } + + private int? InternalPortalId { get { - var pageId = SelectedItemValueAsInt; - return (pageId == Null.NullInteger) ? null : TabController.Instance.GetTab(pageId, PortalId, false); + return this.ViewState.GetValue("PortalId", null); } + set { - SelectedItem = (value != null) ? new ListItem() { Text = value.IndentedTabName, Value = value.TabID.ToString(CultureInfo.InvariantCulture) } : null; + this.ViewState.SetValue("PortalId", value, null); } } - - /// - /// Specific to only show tabs which have view permission on these roles. - /// - public IList Roles { get; set; } - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPaswordStrengthOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPaswordStrengthOptions.cs index 45a87087cb7..42079909c8a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPaswordStrengthOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPaswordStrengthOptions.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users.Membership; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users.Membership; + [DataContract] public class DnnPaswordStrengthOptions { @@ -58,49 +58,49 @@ public class DnnPaswordStrengthOptions [DataMember(Name = "criteriaValidationExpression")] public string CriteriaValidationExpressionText; - [DataMember(Name = "passwordRulesHeadText")] - public string PasswordRulesHeadText; + [DataMember(Name = "passwordRulesHeadText")] + public string PasswordRulesHeadText; public DnnPaswordStrengthOptions() { // all the PasswordStrength related resources are located under the Website\App_GlobalResources\WebControls.resx - MinLengthText = Utilities.GetLocalizedString("PasswordStrengthMinLength"); - WeakText = Utilities.GetLocalizedString("PasswordStrengthWeak"); - FairText = Utilities.GetLocalizedString("PasswordStrengthFair"); ; - StrongText = Utilities.GetLocalizedString("PasswordStrengthStrong"); ; - - CriteriaAtLeastNCharsText = Utilities.GetLocalizedString("CriteriaAtLeastNChars"); - CriteriaAtLeastNSpecialCharsText = Utilities.GetLocalizedString("CriteriaAtLeastNSpecialChars"); - CriteriaValidationExpressionText = Utilities.GetLocalizedString("CriteriaValidationExpression"); - - PasswordRulesHeadText = Utilities.GetLocalizedString("PasswordRulesHeadText"); - - WeakColor = "#ed1e24"; - FairColor = "#f6d50a"; - StrongColor = "#69bd44"; - - LabelCss = "min-length-text"; - MeterCss = "meter"; + this.MinLengthText = Utilities.GetLocalizedString("PasswordStrengthMinLength"); + this.WeakText = Utilities.GetLocalizedString("PasswordStrengthWeak"); + this.FairText = Utilities.GetLocalizedString("PasswordStrengthFair"); + this.StrongText = Utilities.GetLocalizedString("PasswordStrengthStrong"); + + this.CriteriaAtLeastNCharsText = Utilities.GetLocalizedString("CriteriaAtLeastNChars"); + this.CriteriaAtLeastNSpecialCharsText = Utilities.GetLocalizedString("CriteriaAtLeastNSpecialChars"); + this.CriteriaValidationExpressionText = Utilities.GetLocalizedString("CriteriaValidationExpression"); + + this.PasswordRulesHeadText = Utilities.GetLocalizedString("PasswordRulesHeadText"); + + this.WeakColor = "#ed1e24"; + this.FairColor = "#f6d50a"; + this.StrongColor = "#69bd44"; + + this.LabelCss = "min-length-text"; + this.MeterCss = "meter"; } /// - /// To avoid fetching data from the database in constructor, the OnSerializing method is consumed + /// To avoid fetching data from the database in constructor, the OnSerializing method is consumed. /// /// [OnSerializing] public void OnSerializing(StreamingContext context) { - int portalId = (PortalController.Instance.GetCurrentPortalSettings()) != null ? (PortalController.Instance.GetCurrentPortalSettings().PortalId) : -1; + int portalId = PortalController.Instance.GetCurrentPortalSettings() != null ? PortalController.Instance.GetCurrentPortalSettings().PortalId : -1; var settings = new MembershipPasswordSettings(portalId); - MinLength = settings.MinPasswordLength; - CriteriaAtLeastNCharsText = string.Format(CriteriaAtLeastNCharsText, MinLength); + this.MinLength = settings.MinPasswordLength; + this.CriteriaAtLeastNCharsText = string.Format(this.CriteriaAtLeastNCharsText, this.MinLength); - MinNumberOfSpecialChars = settings.MinNonAlphanumericCharacters; - CriteriaAtLeastNSpecialCharsText = string.Format(CriteriaAtLeastNSpecialCharsText, MinNumberOfSpecialChars); + this.MinNumberOfSpecialChars = settings.MinNonAlphanumericCharacters; + this.CriteriaAtLeastNSpecialCharsText = string.Format(this.CriteriaAtLeastNSpecialCharsText, this.MinNumberOfSpecialChars); - ValidationExpression = settings.ValidationExpression; - CriteriaValidationExpressionText = string.Format(CriteriaValidationExpressionText, ValidationExpression); + this.ValidationExpression = settings.ValidationExpression; + this.CriteriaValidationExpressionText = string.Format(this.CriteriaValidationExpressionText, this.ValidationExpression); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs index 966780efb16..24cfbac9bf3 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs @@ -1,61 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.UI.WebControls.Extensions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.UI.WebControls.Extensions; + [ToolboxData("<{0}:DnnPortalPageDropDownList runat='server'>")] public class DnnPortalPageDropDownList : DnnDropDownList { private readonly Lazy _portalId = new Lazy(() => PortalSettings.Current.ActiveTab.IsSuperTab ? -1 : PortalSettings.Current.PortalId); - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); - Services.GetTreeMethod = "ItemListService/GetPagesInPortalGroup"; - Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendantsInPortalGroup"; - Services.SearchTreeMethod = "ItemListService/SearchPagesInPortalGroup"; - Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPageInPortalGroup"; - Services.SortTreeMethod = "ItemListService/SortPagesInPortalGroup"; - Services.ServiceRoot = "InternalServices"; - } - - protected override void OnPreRender(EventArgs e) - { - this.AddCssClass("page"); - base.OnPreRender(e); - } - /// - /// Gets the selected Page in the control, or selects the Page in the control. + /// Gets or sets the selected Page in the control, or selects the Page in the control. /// - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TabInfo SelectedPage { get { - var pageId = SelectedItemValueAsInt; - return (pageId == Null.NullInteger) ? null : TabController.Instance.GetTab(pageId, _portalId.Value, false); + var pageId = this.SelectedItemValueAsInt; + return (pageId == Null.NullInteger) ? null : TabController.Instance.GetTab(pageId, this._portalId.Value, false); } + set { - SelectedItem = (value != null) ? new ListItem() { Text = value.IndentedTabName, Value = value.TabID.ToString(CultureInfo.InvariantCulture) } : null; + this.SelectedItem = (value != null) ? new ListItem() { Text = value.IndentedTabName, Value = value.TabID.ToString(CultureInfo.InvariantCulture) } : null; } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); + this.Services.GetTreeMethod = "ItemListService/GetPagesInPortalGroup"; + this.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendantsInPortalGroup"; + this.Services.SearchTreeMethod = "ItemListService/SearchPagesInPortalGroup"; + this.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPageInPortalGroup"; + this.Services.SortTreeMethod = "ItemListService/SortPagesInPortalGroup"; + this.Services.ServiceRoot = "InternalServices"; + } + + protected override void OnPreRender(EventArgs e) + { + this.AddCssClass("page"); + base.OnPreRender(e); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs index c502b19655e..de0b5ab76de 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs @@ -1,59 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + public class DnnRadioButton : RadioButton, ILocalizable { - private bool _Localize = true; - - #region "Constructors" - + private bool _Localize = true; + public DnnRadioButton() { - CssClass = "SubHead dnnLabel"; - } - - #endregion - - #region "Protected Methods" - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - base.Render(writer); - } - - #endregion - - #region "ILocalizable Implementation" - + this.CssClass = "SubHead dnnLabel"; + } + public bool Localize { get { - return _Localize; + return this._Localize; } + set { - _Localize = value; + this._Localize = value; } } @@ -61,25 +35,35 @@ public bool Localize public virtual void LocalizeStrings() { - if ((Localize)) + if (this.Localize) { - if ((!string.IsNullOrEmpty(ToolTip))) + if (!string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(ToolTip, LocalResourceFile); + this.ToolTip = Localization.GetString(this.ToolTip, this.LocalResourceFile); } - if ((!string.IsNullOrEmpty(Text))) + if (!string.IsNullOrEmpty(this.Text)) { - Text = Localization.GetString(Text, LocalResourceFile); + this.Text = Localization.GetString(this.Text, this.LocalResourceFile); - if ((string.IsNullOrEmpty(ToolTip))) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(Text + ".ToolTip", LocalResourceFile); + this.ToolTip = Localization.GetString(this.Text + ".ToolTip", this.LocalResourceFile); } } } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); } - #endregion + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs index efc8c9ec782..d7971f2cfea 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs @@ -1,35 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + [ParseChildren(true)] public class DnnRibbonBar : WebControl { - public DnnRibbonBar() : base("div") + public DnnRibbonBar() + : base("div") { - CssClass = "dnnRibbon"; + this.CssClass = "dnnRibbon"; Control control = this; - Utilities.ApplySkin(control, "", "RibbonBar", "RibbonBar"); + Utilities.ApplySkin(control, string.Empty, "RibbonBar", "RibbonBar"); } - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DnnRibbonBarGroupCollection Groups { get { - return (DnnRibbonBarGroupCollection) Controls; + return (DnnRibbonBarGroupCollection)this.Controls; } } @@ -53,21 +50,21 @@ protected override ControlCollection CreateControlCollection() protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (Visible) + if (this.Visible) { - Utilities.ApplySkin(this, "", "RibbonBar", "RibbonBar"); + Utilities.ApplySkin(this, string.Empty, "RibbonBar", "RibbonBar"); } } protected override void Render(HtmlTextWriter writer) { - if ((Groups.Count > 0)) + if (this.Groups.Count > 0) { - Groups[0].CssClass = Groups[0].CssClass + " " + Groups[0].CssClass.Trim() + "First"; - Groups[Groups.Count - 1].CssClass = Groups[Groups.Count - 1].CssClass + " " + Groups[Groups.Count - 1].CssClass.Trim() + "Last"; + this.Groups[0].CssClass = this.Groups[0].CssClass + " " + this.Groups[0].CssClass.Trim() + "First"; + this.Groups[this.Groups.Count - 1].CssClass = this.Groups[this.Groups.Count - 1].CssClass + " " + this.Groups[this.Groups.Count - 1].CssClass.Trim() + "Last"; } - base.RenderBeginTag(writer); + this.RenderBeginTag(writer); writer.AddAttribute("class", "barContent"); writer.RenderBeginTag("div"); @@ -78,24 +75,26 @@ protected override void Render(HtmlTextWriter writer) writer.RenderBeginTag("table"); writer.RenderBeginTag("tr"); - foreach (DnnRibbonBarGroup grp in Groups) + foreach (DnnRibbonBarGroup grp in this.Groups) { - if ((grp.Visible)) + if (grp.Visible) { writer.RenderBeginTag("td"); grp.RenderControl(writer); writer.RenderEndTag(); } } - //MyBase.RenderChildren(writer) - + + // MyBase.RenderChildren(writer) writer.RenderEndTag(); - //tr + + // tr writer.RenderEndTag(); - //table + + // table writer.RenderEndTag(); - //div - + + // div writer.AddAttribute("class", "barBottomLeft"); writer.RenderBeginTag("div"); writer.RenderEndTag(); @@ -104,7 +103,7 @@ protected override void Render(HtmlTextWriter writer) writer.RenderBeginTag("div"); writer.RenderEndTag(); - base.RenderEndTag(writer); + this.RenderEndTag(writer); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs index 81e22b80e97..b86f37fc4bd 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs @@ -1,33 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + [ParseChildren(true)] public class DnnRibbonBarGroup : WebControl { private bool _CheckToolVisibility = true; private HtmlGenericControl _contentContainer; - public DnnRibbonBarGroup() : base("div") + public DnnRibbonBarGroup() + : base("div") { - CssClass = "dnnRibbonGroup"; + this.CssClass = "dnnRibbonGroup"; } public override ControlCollection Controls { get { - EnsureChildControls(); + this.EnsureChildControls(); return base.Controls; } } @@ -42,17 +38,34 @@ public virtual bool CheckToolVisibility { get { - return _CheckToolVisibility; + return this._CheckToolVisibility; } + set { - _CheckToolVisibility = value; + this._CheckToolVisibility = value; + } + } + + public override Control FindControl(string id) + { + this.EnsureChildControls(); + return base.FindControl(id); + } + + public override void RenderControl(HtmlTextWriter writer) + { + if (this.CheckVisibility()) + { + this.RenderBeginTag(writer); + this.RenderChildren(writer); + this.RenderEndTag(writer); } } protected override void CreateChildControls() { - Controls.Clear(); + this.Controls.Clear(); HtmlGenericControl topLeft = new HtmlGenericControl("div"); topLeft.Attributes.Add("class", "topLeft"); @@ -64,40 +77,41 @@ protected override void CreateChildControls() HtmlGenericControl bottomRight = new HtmlGenericControl("div"); bottomRight.Attributes.Add("class", "bottomRight"); - _contentContainer = new HtmlGenericControl("div"); - _contentContainer.Attributes.Add("class", "content"); + this._contentContainer = new HtmlGenericControl("div"); + this._contentContainer.Attributes.Add("class", "content"); HtmlGenericControl footerContainer = new HtmlGenericControl("div"); footerContainer.Attributes.Add("class", "footer"); - Controls.Add(topLeft); - Controls.Add(topRight); - Controls.Add(_contentContainer); - Controls.Add(footerContainer); - Controls.Add(bottomLeft); - Controls.Add(bottomRight); + this.Controls.Add(topLeft); + this.Controls.Add(topRight); + this.Controls.Add(this._contentContainer); + this.Controls.Add(footerContainer); + this.Controls.Add(bottomLeft); + this.Controls.Add(bottomRight); - if (Content != null) + if (this.Content != null) { - Content.InstantiateIn(_contentContainer); + this.Content.InstantiateIn(this._contentContainer); } - if (Footer != null) + if (this.Footer != null) { - Footer.InstantiateIn(footerContainer); + this.Footer.InstantiateIn(footerContainer); } } private bool CheckVisibility() { bool returnValue = true; - if ((Visible && CheckToolVisibility)) + if (this.Visible && this.CheckToolVisibility) { - //Hide group if all tools are invisible + // Hide group if all tools are invisible bool foundTool = false; - ControlCollection controls = _contentContainer.Controls; - returnValue = AreChildToolsVisible(ref controls, ref foundTool); + ControlCollection controls = this._contentContainer.Controls; + returnValue = this.AreChildToolsVisible(ref controls, ref foundTool); } + return returnValue; } @@ -107,10 +121,10 @@ private bool AreChildToolsVisible(ref ControlCollection children, ref bool found foreach (Control ctrl in children) { - if ((ctrl is IDnnRibbonBarTool)) + if (ctrl is IDnnRibbonBarTool) { foundTool = true; - if ((ctrl.Visible)) + if (ctrl.Visible) { returnValue = true; break; @@ -119,9 +133,9 @@ private bool AreChildToolsVisible(ref ControlCollection children, ref bool found else { ControlCollection controls = ctrl.Controls; - if ((AreChildToolsVisible(ref controls, ref foundTool))) + if (this.AreChildToolsVisible(ref controls, ref foundTool)) { - if ((foundTool)) + if (foundTool) { returnValue = true; break; @@ -130,28 +144,12 @@ private bool AreChildToolsVisible(ref ControlCollection children, ref bool found } } - if ((!foundTool)) + if (!foundTool) { return true; } return returnValue; } - - public override Control FindControl(string id) - { - EnsureChildControls(); - return base.FindControl(id); - } - - public override void RenderControl(HtmlTextWriter writer) - { - if ((CheckVisibility())) - { - base.RenderBeginTag(writer); - base.RenderChildren(writer); - base.RenderEndTag(writer); - } - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs index c4922dbab86..706cbc96427 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + public class DnnRibbonBarGroupCollection : ControlCollection { - public DnnRibbonBarGroupCollection(Control owner) : base(owner) + public DnnRibbonBarGroupCollection(Control owner) + : base(owner) { } @@ -22,7 +17,7 @@ public DnnRibbonBarGroupCollection(Control owner) : base(owner) { get { - return (DnnRibbonBarGroup) base[index]; + return (DnnRibbonBarGroup)base[index]; } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs index b228c38d3ea..6cdee9ac980 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs @@ -1,62 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Threading; + using System.Web.UI; + + using DotNetNuke.Abstractions; + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Microsoft.Extensions.DependencyInjection; + [ParseChildren(true)] public class DnnRibbonBarTool : Control, IDnnRibbonBarTool { - protected INavigationManager NavigationManager { get; } + private IDictionary _allTools; + private DnnTextLink _dnnLink; + private DnnTextButton _dnnLinkButton; + public DnnRibbonBarTool() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } - #region Properties - - private IDictionary _allTools; - private DnnTextLink _dnnLink; - private DnnTextButton _dnnLinkButton; + protected INavigationManager NavigationManager { get; } public virtual RibbonBarToolInfo ToolInfo { get { - if ((ViewState["ToolInfo"] == null)) + if (this.ViewState["ToolInfo"] == null) { - ViewState.Add("ToolInfo", new RibbonBarToolInfo()); + this.ViewState.Add("ToolInfo", new RibbonBarToolInfo()); } - return (RibbonBarToolInfo) ViewState["ToolInfo"]; + + return (RibbonBarToolInfo)this.ViewState["ToolInfo"]; } + set { - ViewState["ToolInfo"] = value; + this.ViewState["ToolInfo"] = value; } } @@ -64,11 +60,12 @@ public virtual string NavigateUrl { get { - return Utilities.GetViewStateAsString(ViewState["NavigateUrl"], Null.NullString); + return Utilities.GetViewStateAsString(this.ViewState["NavigateUrl"], Null.NullString); } + set { - ViewState["NavigateUrl"] = value; + this.ViewState["NavigateUrl"] = value; } } @@ -76,11 +73,12 @@ public virtual string ToolCssClass { get { - return Utilities.GetViewStateAsString(ViewState["ToolCssClass"], Null.NullString); + return Utilities.GetViewStateAsString(this.ViewState["ToolCssClass"], Null.NullString); } + set { - ViewState["ToolCssClass"] = value; + this.ViewState["ToolCssClass"] = value; } } @@ -88,11 +86,12 @@ public virtual string Text { get { - return Utilities.GetViewStateAsString(ViewState["Text"], Null.NullString); + return Utilities.GetViewStateAsString(this.ViewState["Text"], Null.NullString); } + set { - ViewState["Text"] = value; + this.ViewState["Text"] = value; } } @@ -100,11 +99,32 @@ public virtual string ToolTip { get { - return Utilities.GetViewStateAsString(ViewState["ToolTip"], Null.NullString); + return Utilities.GetViewStateAsString(this.ViewState["ToolTip"], Null.NullString); } + set { - ViewState["ToolTip"] = value; + this.ViewState["ToolTip"] = value; + } + } + + public virtual string ToolName + { + get + { + return this.ToolInfo.ToolName; + } + + set + { + if (this.AllTools.ContainsKey(value)) + { + this.ToolInfo = this.AllTools[value]; + } + else + { + throw new NotSupportedException("Tool not found [" + value + "]"); + } } } @@ -112,12 +132,13 @@ protected virtual DnnTextButton DnnLinkButton { get { - if ((_dnnLinkButton == null)) + if (this._dnnLinkButton == null) { // Appending _CPCommandBtn is also assumed in the RibbonBar.ascx. If changed, one would need to change in both places. - _dnnLinkButton = new DnnTextButton {ID = ID + "_CPCommandBtn"}; + this._dnnLinkButton = new DnnTextButton { ID = this.ID + "_CPCommandBtn" }; } - return _dnnLinkButton; + + return this._dnnLinkButton; } } @@ -125,11 +146,12 @@ protected virtual DnnTextLink DnnLink { get { - if ((_dnnLink == null)) + if (this._dnnLink == null) { - _dnnLink = new DnnTextLink(); + this._dnnLink = new DnnTextLink(); } - return _dnnLink; + + return this._dnnLink; } } @@ -137,32 +159,33 @@ protected virtual IDictionary AllTools { get { - if (_allTools == null) + if (this._allTools == null) { - _allTools = new Dictionary + this._allTools = new Dictionary { - //Framework - {"PageSettings", new RibbonBarToolInfo("PageSettings", false, false, "", "", "", true)}, - {"CopyPage", new RibbonBarToolInfo("CopyPage", false, false, "", "", "", true)}, - {"DeletePage", new RibbonBarToolInfo("DeletePage", false, true, "", "", "", true)}, - {"ImportPage", new RibbonBarToolInfo("ImportPage", false, false, "", "", "", true)}, - {"ExportPage", new RibbonBarToolInfo("ExportPage", false, false, "", "", "", true)}, - {"NewPage", new RibbonBarToolInfo("NewPage", false, false, "", "", "", true)}, - {"CopyPermissionsToChildren", new RibbonBarToolInfo("CopyPermissionsToChildren", false, true, "", "", "", false)}, - {"CopyDesignToChildren", new RibbonBarToolInfo("CopyDesignToChildren", false, true, "", "", "", false)}, - {"Help", new RibbonBarToolInfo("Help", false, false, "_Blank", "", "", false)}, - //Modules On Tabs - {"Console", new RibbonBarToolInfo("Console", false, false, "", "Console", "", false)}, - {"HostConsole", new RibbonBarToolInfo("HostConsole", true, false, "", "Console", "", false)}, - {"UploadFile", new RibbonBarToolInfo("UploadFile", false, false, "", "", "WebUpload", true)}, - {"NewRole", new RibbonBarToolInfo("NewRole", false, false, "", "Security Roles", "Edit", true)}, - {"NewUser", new RibbonBarToolInfo("NewUser", false, false, "", "User Accounts", "Edit", true)}, - {"ClearCache", new RibbonBarToolInfo("ClearCache", true, true, "", "", "", false)}, - {"RecycleApp", new RibbonBarToolInfo("RecycleApp", true, true, "", "", "", false)} + // Framework + { "PageSettings", new RibbonBarToolInfo("PageSettings", false, false, string.Empty, string.Empty, string.Empty, true) }, + { "CopyPage", new RibbonBarToolInfo("CopyPage", false, false, string.Empty, string.Empty, string.Empty, true) }, + { "DeletePage", new RibbonBarToolInfo("DeletePage", false, true, string.Empty, string.Empty, string.Empty, true) }, + { "ImportPage", new RibbonBarToolInfo("ImportPage", false, false, string.Empty, string.Empty, string.Empty, true) }, + { "ExportPage", new RibbonBarToolInfo("ExportPage", false, false, string.Empty, string.Empty, string.Empty, true) }, + { "NewPage", new RibbonBarToolInfo("NewPage", false, false, string.Empty, string.Empty, string.Empty, true) }, + { "CopyPermissionsToChildren", new RibbonBarToolInfo("CopyPermissionsToChildren", false, true, string.Empty, string.Empty, string.Empty, false) }, + { "CopyDesignToChildren", new RibbonBarToolInfo("CopyDesignToChildren", false, true, string.Empty, string.Empty, string.Empty, false) }, + { "Help", new RibbonBarToolInfo("Help", false, false, "_Blank", string.Empty, string.Empty, false) }, + + // Modules On Tabs + { "Console", new RibbonBarToolInfo("Console", false, false, string.Empty, "Console", string.Empty, false) }, + { "HostConsole", new RibbonBarToolInfo("HostConsole", true, false, string.Empty, "Console", string.Empty, false) }, + { "UploadFile", new RibbonBarToolInfo("UploadFile", false, false, string.Empty, string.Empty, "WebUpload", true) }, + { "NewRole", new RibbonBarToolInfo("NewRole", false, false, string.Empty, "Security Roles", "Edit", true) }, + { "NewUser", new RibbonBarToolInfo("NewUser", false, false, string.Empty, "User Accounts", "Edit", true) }, + { "ClearCache", new RibbonBarToolInfo("ClearCache", true, true, string.Empty, string.Empty, string.Empty, false) }, + { "RecycleApp", new RibbonBarToolInfo("RecycleApp", true, true, string.Empty, string.Empty, string.Empty, false) }, }; } - return _allTools; + return this._allTools; } } @@ -174,154 +197,133 @@ private static PortalSettings PortalSettings } } - public virtual string ToolName - { - get - { - return ToolInfo.ToolName; - } - set - { - if ((AllTools.ContainsKey(value))) - { - ToolInfo = AllTools[value]; - } - else - { - throw new NotSupportedException("Tool not found [" + value + "]"); - } - } - } - - #endregion - - #region Events - - protected override void CreateChildControls() - { - Controls.Clear(); - Controls.Add(DnnLinkButton); - Controls.Add(DnnLink); - } - - protected override void OnInit(EventArgs e) - { - EnsureChildControls(); - DnnLinkButton.Click += ControlPanelTool_OnClick; - } - - protected override void OnPreRender(EventArgs e) - { - ProcessTool(); - Visible = (DnnLink.Visible || DnnLinkButton.Visible); - base.OnPreRender(e); - } - public virtual void ControlPanelTool_OnClick(object sender, EventArgs e) { - switch (ToolInfo.ToolName) + switch (this.ToolInfo.ToolName) { case "DeletePage": - if ((HasToolPermissions("DeletePage"))) + if (this.HasToolPermissions("DeletePage")) { string url = TestableGlobals.Instance.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=delete"); - Page.Response.Redirect(url, true); + this.Page.Response.Redirect(url, true); } + break; case "CopyPermissionsToChildren": - if ((HasToolPermissions("CopyPermissionsToChildren"))) + if (this.HasToolPermissions("CopyPermissionsToChildren")) { TabController.CopyPermissionsToChildren(PortalSettings.ActiveTab, PortalSettings.ActiveTab.TabPermissions); - Page.Response.Redirect(Page.Request.RawUrl); + this.Page.Response.Redirect(this.Page.Request.RawUrl); } + break; case "CopyDesignToChildren": - if ((HasToolPermissions("CopyDesignToChildren"))) + if (this.HasToolPermissions("CopyDesignToChildren")) { TabController.CopyDesignToChildren(PortalSettings.ActiveTab, PortalSettings.ActiveTab.SkinSrc, PortalSettings.ActiveTab.ContainerSrc); - Page.Response.Redirect(Page.Request.RawUrl); + this.Page.Response.Redirect(this.Page.Request.RawUrl); } + break; case "ClearCache": - if ((HasToolPermissions("ClearCache"))) + if (this.HasToolPermissions("ClearCache")) { - ClearCache(); - ClientResourceManager.ClearCache(); - Page.Response.Redirect(Page.Request.RawUrl); + this.ClearCache(); + ClientResourceManager.ClearCache(); + this.Page.Response.Redirect(this.Page.Request.RawUrl); } + break; case "RecycleApp": - if ((HasToolPermissions("RecycleApp"))) + if (this.HasToolPermissions("RecycleApp")) { - RestartApplication(); - Page.Response.Redirect(Page.Request.RawUrl); + this.RestartApplication(); + this.Page.Response.Redirect(this.Page.Request.RawUrl); } + break; } } - #endregion + protected override void CreateChildControls() + { + this.Controls.Clear(); + this.Controls.Add(this.DnnLinkButton); + this.Controls.Add(this.DnnLink); + } - #region Methods + protected override void OnInit(EventArgs e) + { + this.EnsureChildControls(); + this.DnnLinkButton.Click += this.ControlPanelTool_OnClick; + } + + protected override void OnPreRender(EventArgs e) + { + this.ProcessTool(); + this.Visible = this.DnnLink.Visible || this.DnnLinkButton.Visible; + base.OnPreRender(e); + } protected virtual void ProcessTool() { - DnnLink.Visible = false; - DnnLinkButton.Visible = false; + this.DnnLink.Visible = false; + this.DnnLinkButton.Visible = false; - if ((!string.IsNullOrEmpty(ToolInfo.ToolName))) + if (!string.IsNullOrEmpty(this.ToolInfo.ToolName)) { - if ((ToolInfo.UseButton)) + if (this.ToolInfo.UseButton) { - DnnLinkButton.Visible = HasToolPermissions(ToolInfo.ToolName); - DnnLinkButton.Enabled = EnableTool(); - DnnLinkButton.Localize = false; + this.DnnLinkButton.Visible = this.HasToolPermissions(this.ToolInfo.ToolName); + this.DnnLinkButton.Enabled = this.EnableTool(); + this.DnnLinkButton.Localize = false; - DnnLinkButton.CssClass = ToolCssClass; - DnnLinkButton.DisabledCssClass = ToolCssClass + " dnnDisabled"; + this.DnnLinkButton.CssClass = this.ToolCssClass; + this.DnnLinkButton.DisabledCssClass = this.ToolCssClass + " dnnDisabled"; - DnnLinkButton.Text = GetText(); - DnnLinkButton.ToolTip = GetToolTip(); + this.DnnLinkButton.Text = this.GetText(); + this.DnnLinkButton.ToolTip = this.GetToolTip(); } else { - DnnLink.Visible = HasToolPermissions(ToolInfo.ToolName); - DnnLink.Enabled = EnableTool(); - DnnLink.Localize = false; + this.DnnLink.Visible = this.HasToolPermissions(this.ToolInfo.ToolName); + this.DnnLink.Enabled = this.EnableTool(); + this.DnnLink.Localize = false; - if ((DnnLink.Enabled)) + if (this.DnnLink.Enabled) { - DnnLink.NavigateUrl = BuildToolUrl(); + this.DnnLink.NavigateUrl = this.BuildToolUrl(); - //can't find the page, disable it? - if ((string.IsNullOrEmpty(DnnLink.NavigateUrl))) + // can't find the page, disable it? + if (string.IsNullOrEmpty(this.DnnLink.NavigateUrl)) { - DnnLink.Enabled = false; + this.DnnLink.Enabled = false; } - //create popup event - else if (ToolInfo.ShowAsPopUp && PortalSettings.EnablePopUps) + + // create popup event + else if (this.ToolInfo.ShowAsPopUp && PortalSettings.EnablePopUps) { // Prevent PageSettings in a popup if SSL is enabled and enforced, which causes redirection/javascript broswer security issues. - if (ToolInfo.ToolName == "PageSettings" || ToolInfo.ToolName == "CopyPage" || ToolInfo.ToolName == "NewPage") + if (this.ToolInfo.ToolName == "PageSettings" || this.ToolInfo.ToolName == "CopyPage" || this.ToolInfo.ToolName == "NewPage") { if (!(PortalSettings.SSLEnabled && PortalSettings.SSLEnforced)) { - DnnLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(DnnLink.NavigateUrl, this, PortalSettings, true, false)); + this.DnnLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(this.DnnLink.NavigateUrl, this, PortalSettings, true, false)); } } else { - DnnLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(DnnLink.NavigateUrl, this, PortalSettings, true, false)); + this.DnnLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(this.DnnLink.NavigateUrl, this, PortalSettings, true, false)); } } } - DnnLink.CssClass = ToolCssClass; - DnnLink.DisabledCssClass = ToolCssClass + " dnnDisabled"; + this.DnnLink.CssClass = this.ToolCssClass; + this.DnnLink.DisabledCssClass = this.ToolCssClass + " dnnDisabled"; - DnnLink.Text = GetText(); - DnnLink.ToolTip = GetToolTip(); - DnnLink.Target = ToolInfo.LinkWindowTarget; + this.DnnLink.Text = this.GetText(); + this.DnnLink.ToolTip = this.GetToolTip(); + this.DnnLink.Target = this.ToolInfo.LinkWindowTarget; } } } @@ -330,24 +332,26 @@ protected virtual bool EnableTool() { bool returnValue = true; - switch (ToolInfo.ToolName) + switch (this.ToolInfo.ToolName) { case "DeletePage": - if ((TabController.IsSpecialTab(TabController.CurrentPage.TabID, PortalSettings.PortalId))) + if (TabController.IsSpecialTab(TabController.CurrentPage.TabID, PortalSettings.PortalId)) { returnValue = false; } + break; case "CopyDesignToChildren": case "CopyPermissionsToChildren": - returnValue = ActiveTabHasChildren(); - if ((returnValue && ToolInfo.ToolName == "CopyPermissionsToChildren")) + returnValue = this.ActiveTabHasChildren(); + if (returnValue && this.ToolInfo.ToolName == "CopyPermissionsToChildren") { - if ((PortalSettings.ActiveTab.IsSuperTab)) + if (PortalSettings.ActiveTab.IsSuperTab) { returnValue = false; } } + break; } @@ -357,16 +361,16 @@ protected virtual bool EnableTool() protected virtual bool HasToolPermissions(string toolName) { bool isHostTool = false; - if ((ToolInfo.ToolName == toolName)) + if (this.ToolInfo.ToolName == toolName) { - isHostTool = ToolInfo.IsHostTool; + isHostTool = this.ToolInfo.IsHostTool; } - else if ((AllTools.ContainsKey(toolName))) + else if (this.AllTools.ContainsKey(toolName)) { - isHostTool = AllTools[toolName].IsHostTool; + isHostTool = this.AllTools[toolName].IsHostTool; } - if ((isHostTool && !UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + if (isHostTool && !UserController.Instance.GetCurrentUserInfo().IsSuperUser) { return false; } @@ -379,19 +383,20 @@ protected virtual bool HasToolPermissions(string toolName) case "CopyPermissionsToChildren": returnValue = TabPermissionController.CanManagePage(); - if ((returnValue && toolName == "CopyPermissionsToChildren")) + if (returnValue && toolName == "CopyPermissionsToChildren") { - if ((!PortalSecurity.IsInRole("Administrators"))) + if (!PortalSecurity.IsInRole("Administrators")) { returnValue = false; } } + break; case "CopyPage": returnValue = TabPermissionController.CanCopyPage(); break; case "DeletePage": - returnValue = (TabPermissionController.CanDeletePage()); + returnValue = TabPermissionController.CanDeletePage(); break; case "ImportPage": returnValue = TabPermissionController.CanImportPage(); @@ -406,24 +411,24 @@ protected virtual bool HasToolPermissions(string toolName) returnValue = !string.IsNullOrEmpty(Host.HelpURL); break; default: - //if it has a module definition, look it up and check permissions - //if it doesn't exist, assume no permission - string friendlyName = ""; - if ((ToolInfo.ToolName == toolName)) + // if it has a module definition, look it up and check permissions + // if it doesn't exist, assume no permission + string friendlyName = string.Empty; + if (this.ToolInfo.ToolName == toolName) { - friendlyName = ToolInfo.ModuleFriendlyName; + friendlyName = this.ToolInfo.ModuleFriendlyName; } - else if ((AllTools.ContainsKey(toolName))) + else if (this.AllTools.ContainsKey(toolName)) { - friendlyName = AllTools[toolName].ModuleFriendlyName; + friendlyName = this.AllTools[toolName].ModuleFriendlyName; } - if ((!string.IsNullOrEmpty(friendlyName))) + if (!string.IsNullOrEmpty(friendlyName)) { returnValue = false; ModuleInfo moduleInfo; - if ((isHostTool)) + if (isHostTool) { moduleInfo = GetInstalledModule(Null.NullInteger, friendlyName); } @@ -432,11 +437,12 @@ protected virtual bool HasToolPermissions(string toolName) moduleInfo = GetInstalledModule(PortalSettings.PortalId, friendlyName); } - if ((moduleInfo != null)) + if (moduleInfo != null) { returnValue = ModulePermissionController.CanViewModule(moduleInfo); } } + break; } @@ -445,18 +451,18 @@ protected virtual bool HasToolPermissions(string toolName) protected virtual string BuildToolUrl() { - if ((ToolInfo.IsHostTool && !UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + if (this.ToolInfo.IsHostTool && !UserController.Instance.GetCurrentUserInfo().IsSuperUser) { return "javascript:void(0);"; } - if ((!string.IsNullOrEmpty(NavigateUrl))) + if (!string.IsNullOrEmpty(this.NavigateUrl)) { - return NavigateUrl; + return this.NavigateUrl; } string returnValue = "javascript:void(0);"; - switch (ToolInfo.ToolName) + switch (this.ToolInfo.ToolName) { case "PageSettings": returnValue = TestableGlobals.Instance.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=edit"); @@ -475,7 +481,7 @@ protected virtual string BuildToolUrl() break; case "ExportPage": - returnValue = NavigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "ExportTab"); + returnValue = this.NavigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "ExportTab"); break; case "NewPage": @@ -487,82 +493,86 @@ protected virtual string BuildToolUrl() var version = Globals.FormatVersion(DotNetNukeContext.Current.Application.Version, false); returnValue = TestableGlobals.Instance.FormatHelpUrl(Host.HelpURL, PortalSettings, "Home", version); } + break; - case "UploadFile": - case "HostUploadFile": + case "UploadFile": + case "HostUploadFile": returnValue = TestableGlobals.Instance.NavigateURL(PortalSettings.ActiveTab.TabID, "WebUpload"); break; default: - if ((!string.IsNullOrEmpty(ToolInfo.ModuleFriendlyName))) + if (!string.IsNullOrEmpty(this.ToolInfo.ModuleFriendlyName)) { var additionalParams = new List(); - returnValue = GetTabURL(additionalParams); + returnValue = this.GetTabURL(additionalParams); } + break; } + return returnValue; } protected virtual string GetText() { - if ((string.IsNullOrEmpty(Text))) + if (string.IsNullOrEmpty(this.Text)) { - return GetString(string.Format("Tool.{0}.Text", ToolInfo.ToolName)); + return this.GetString(string.Format("Tool.{0}.Text", this.ToolInfo.ToolName)); } - return Text; + return this.Text; } protected virtual string GetToolTip() { - if ((ToolInfo.ToolName == "DeletePage")) + if (this.ToolInfo.ToolName == "DeletePage") { - if ((TabController.IsSpecialTab(TabController.CurrentPage.TabID, PortalSettings.PortalId))) + if (TabController.IsSpecialTab(TabController.CurrentPage.TabID, PortalSettings.PortalId)) { - return GetString("Tool.DeletePage.Special.ToolTip"); + return this.GetString("Tool.DeletePage.Special.ToolTip"); } } - if ((string.IsNullOrEmpty(Text))) + if (string.IsNullOrEmpty(this.Text)) { - string tip = GetString(string.Format("Tool.{0}.ToolTip", ToolInfo.ToolName)); - if ((string.IsNullOrEmpty(tip))) + string tip = this.GetString(string.Format("Tool.{0}.ToolTip", this.ToolInfo.ToolName)); + if (string.IsNullOrEmpty(tip)) { - tip = GetString(string.Format("Tool.{0}.Text", ToolInfo.ToolName)); + tip = this.GetString(string.Format("Tool.{0}.Text", this.ToolInfo.ToolName)); } + return tip; } - return ToolTip; + return this.ToolTip; } protected virtual string GetTabURL(List additionalParams) { - int portalId = (ToolInfo.IsHostTool) ? Null.NullInteger : PortalSettings.PortalId; + int portalId = this.ToolInfo.IsHostTool ? Null.NullInteger : PortalSettings.PortalId; string strURL = string.Empty; - if (((additionalParams == null))) + if (additionalParams == null) { additionalParams = new List(); } - var moduleInfo = ModuleController.Instance.GetModuleByDefinition(portalId, ToolInfo.ModuleFriendlyName); + var moduleInfo = ModuleController.Instance.GetModuleByDefinition(portalId, this.ToolInfo.ModuleFriendlyName); - if (((moduleInfo != null))) + if (moduleInfo != null) { - bool isHostPage = (portalId == Null.NullInteger); - if ((!string.IsNullOrEmpty(ToolInfo.ControlKey))) + bool isHostPage = portalId == Null.NullInteger; + if (!string.IsNullOrEmpty(this.ToolInfo.ControlKey)) { additionalParams.Insert(0, "mid=" + moduleInfo.ModuleID); - if (ToolInfo.ShowAsPopUp && PortalSettings.EnablePopUps) + if (this.ToolInfo.ShowAsPopUp && PortalSettings.EnablePopUps) { additionalParams.Add("popUp=true"); } } string currentCulture = Thread.CurrentThread.CurrentCulture.Name; - strURL = NavigationManager.NavigateURL(moduleInfo.TabID, isHostPage, PortalSettings, ToolInfo.ControlKey, currentCulture, additionalParams.ToArray()); + strURL = this.NavigationManager.NavigateURL(moduleInfo.TabID, isHostPage, PortalSettings, this.ToolInfo.ControlKey, currentCulture, additionalParams.ToArray()); } return strURL; @@ -572,7 +582,7 @@ protected virtual bool ActiveTabHasChildren() { var children = TabController.GetTabsByParent(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID); - if (((children == null) || children.Count < 1)) + if ((children == null) || children.Count < 1) { return false; } @@ -585,11 +595,6 @@ protected virtual string GetString(string key) return Utilities.GetLocalizedStringFromParent(key, this); } - private static ModuleInfo GetInstalledModule(int portalID, string friendlyName) - { - return ModuleController.Instance.GetModuleByDefinition(portalID, friendlyName); - } - protected virtual void ClearCache() { DataCache.ClearCache(); @@ -598,11 +603,14 @@ protected virtual void ClearCache() protected virtual void RestartApplication() { var log = new LogInfo { BypassBuffering = true, LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; - log.AddProperty("Message", GetString("UserRestart")); + log.AddProperty("Message", this.GetString("UserRestart")); LogController.Instance.AddLog(log); Config.Touch(); } - #endregion + private static ModuleInfo GetInstalledModule(int portalID, string friendlyName) + { + return ModuleController.Instance.GetModuleByDefinition(portalID, friendlyName); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs index 8a56d88f82a..7d17418df2a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs @@ -1,20 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System.Web.UI; + using System.Web.UI.WebControls; + [ParseChildren(true)] public class DnnTab : WebControl { - public DnnTab() : base("div") + public DnnTab() + : base("div") { } @@ -22,7 +18,7 @@ public override ControlCollection Controls { get { - EnsureChildControls(); + this.EnsureChildControls(); return base.Controls; } } @@ -33,27 +29,27 @@ public override ControlCollection Controls [TemplateInstance(TemplateInstance.Single)] public virtual ITemplate Content { get; set; } + public override Control FindControl(string id) + { + this.EnsureChildControls(); + return base.FindControl(id); + } + protected override void CreateChildControls() { - Controls.Clear(); + this.Controls.Clear(); - if (Content != null) + if (this.Content != null) { - Content.InstantiateIn(this); + this.Content.InstantiateIn(this); } } - public override Control FindControl(string id) - { - EnsureChildControls(); - return base.FindControl(id); - } - protected override void Render(HtmlTextWriter writer) { - base.RenderBeginTag(writer); - base.RenderChildren(writer); - base.RenderEndTag(writer); + this.RenderBeginTag(writer); + this.RenderChildren(writer); + this.RenderEndTag(writer); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs index 594033718d5..1f8aefc1313 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + public class DnnTabCollection : ControlCollection { - public DnnTabCollection(Control owner) : base(owner) + public DnnTabCollection(Control owner) + : base(owner) { } @@ -22,7 +17,7 @@ public DnnTabCollection(Control owner) : base(owner) { get { - return (DnnTab) base[index]; + return (DnnTab)base[index]; } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs index 8f1173a77d6..ee218de93b7 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs @@ -1,25 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + public class DnnTextButton : LinkButton, ILocalizable { - private bool _localize = true; - - #region "Public Properties" - + private bool _localize = true; + [Bindable(true)] [Category("Appearance")] [DefaultValue("")] @@ -28,11 +22,12 @@ public string ConfirmMessage { get { - return ViewState["ConfirmMessage"] == null ? string.Empty : (string) ViewState["ConfirmMessage"]; + return this.ViewState["ConfirmMessage"] == null ? string.Empty : (string)this.ViewState["ConfirmMessage"]; } + set { - ViewState["ConfirmMessage"] = value; + this.ViewState["ConfirmMessage"] = value; } } @@ -44,11 +39,12 @@ public override string CssClass { get { - return ViewState["CssClass"] == null ? string.Empty : (string) ViewState["CssClass"]; + return this.ViewState["CssClass"] == null ? string.Empty : (string)this.ViewState["CssClass"]; } + set { - ViewState["CssClass"] = value; + this.ViewState["CssClass"] = value; } } @@ -60,11 +56,12 @@ public override string CssClass { get { - return ViewState["DisabledCssClass"] == null ? string.Empty : (string) ViewState["DisabledCssClass"]; + return this.ViewState["DisabledCssClass"] == null ? string.Empty : (string)this.ViewState["DisabledCssClass"]; } + set { - ViewState["DisabledCssClass"] = value; + this.ViewState["DisabledCssClass"] = value; } } @@ -76,45 +73,25 @@ public override string CssClass { get { - return ViewState["Text"] == null ? string.Empty : (string) ViewState["Text"]; + return this.ViewState["Text"] == null ? string.Empty : (string)this.ViewState["Text"]; } + set { - ViewState["Text"] = value; + this.ViewState["Text"] = value; } - } - - #endregion - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - if (!Enabled && !string.IsNullOrEmpty(DisabledCssClass)) - { - CssClass = DisabledCssClass; - } - writer.AddAttribute("class", CssClass.Trim()); - base.Render(writer); - } - - #region "ILocalizable Implementation" - + } + public bool Localize { get { - return _localize; + return this._localize; } + set { - _localize = value; + this._localize = value; } } @@ -122,30 +99,47 @@ public bool Localize public virtual void LocalizeStrings() { - if ((Localize)) + if (this.Localize) { - if ((!string.IsNullOrEmpty(ToolTip))) + if (!string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(ToolTip, LocalResourceFile); + this.ToolTip = Localization.GetString(this.ToolTip, this.LocalResourceFile); } - if ((!string.IsNullOrEmpty(Text))) + if (!string.IsNullOrEmpty(this.Text)) { - Text = Localization.GetString(Text, LocalResourceFile); + this.Text = Localization.GetString(this.Text, this.LocalResourceFile); - if ((string.IsNullOrEmpty(ToolTip))) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(string.Format("{0}.ToolTip", Text), LocalResourceFile); + this.ToolTip = Localization.GetString(string.Format("{0}.ToolTip", this.Text), this.LocalResourceFile); } - if ((string.IsNullOrEmpty(ToolTip))) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Text; + this.ToolTip = this.Text; } } } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); } - #endregion + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + if (!this.Enabled && !string.IsNullOrEmpty(this.DisabledCssClass)) + { + this.CssClass = this.DisabledCssClass; + } + + writer.AddAttribute("class", this.CssClass.Trim()); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs index c987a9fde1c..6c7732be3e0 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs @@ -1,28 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + public class DnnTextLink : WebControl, ILocalizable { private bool _localize = true; private HyperLink _textHyperlinkControl; - public DnnTextLink() : base("span") + public DnnTextLink() + : base("span") { - CssClass = "dnnTextLink"; - DisabledCssClass = "dnnTextLink disabled"; + this.CssClass = "dnnTextLink"; + this.DisabledCssClass = "dnnTextLink disabled"; } [Bindable(true)] @@ -33,11 +30,12 @@ public string Text { get { - return TextHyperlinkControl.Text; + return this.TextHyperlinkControl.Text; } + set { - TextHyperlinkControl.Text = value; + this.TextHyperlinkControl.Text = value; } } @@ -49,11 +47,12 @@ public override string ToolTip { get { - return TextHyperlinkControl.ToolTip; + return this.TextHyperlinkControl.ToolTip; } + set { - TextHyperlinkControl.ToolTip = value; + this.TextHyperlinkControl.ToolTip = value; } } @@ -65,11 +64,12 @@ public string NavigateUrl { get { - return TextHyperlinkControl.NavigateUrl; + return this.TextHyperlinkControl.NavigateUrl; } + set { - TextHyperlinkControl.NavigateUrl = value; + this.TextHyperlinkControl.NavigateUrl = value; } } @@ -81,11 +81,12 @@ public string Target { get { - return TextHyperlinkControl.Target; + return this.TextHyperlinkControl.Target; } + set { - TextHyperlinkControl.Target = value; + this.TextHyperlinkControl.Target = value; } } @@ -97,102 +98,98 @@ public string Target { get { - return ViewState["DisabledCssClass"] == null ? string.Empty : (string) ViewState["DisabledCssClass"]; + return this.ViewState["DisabledCssClass"] == null ? string.Empty : (string)this.ViewState["DisabledCssClass"]; } + set { - ViewState["DisabledCssClass"] = value; + this.ViewState["DisabledCssClass"] = value; } } - - private HyperLink TextHyperlinkControl + + public bool Localize { get { - if (_textHyperlinkControl == null) - { - _textHyperlinkControl = new HyperLink(); - } - return _textHyperlinkControl; + return this._localize; } - } - - protected override void CreateChildControls() - { - Controls.Clear(); - Controls.Add(TextHyperlinkControl); - } - - #region "Protected Methods" - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - LocalizeStrings(); - - if ((!Enabled)) + + set { - if ((!string.IsNullOrEmpty(DisabledCssClass))) - { - CssClass = DisabledCssClass; - } - NavigateUrl = "javascript:void(0);"; + this._localize = value; } - - base.RenderBeginTag(writer); - base.RenderChildren(writer); - base.RenderEndTag(writer); } - #endregion - - #region "ILocalizable Implementation" + public string LocalResourceFile { get; set; } - public bool Localize + private HyperLink TextHyperlinkControl { get { - return _localize; - } - set - { - _localize = value; + if (this._textHyperlinkControl == null) + { + this._textHyperlinkControl = new HyperLink(); + } + + return this._textHyperlinkControl; } } - public string LocalResourceFile { get; set; } - public virtual void LocalizeStrings() { - if ((Localize)) + if (this.Localize) { - if ((!string.IsNullOrEmpty(ToolTip))) + if (!string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(ToolTip, LocalResourceFile); + this.ToolTip = Localization.GetString(this.ToolTip, this.LocalResourceFile); } - if ((!string.IsNullOrEmpty(Text))) + if (!string.IsNullOrEmpty(this.Text)) { - Text = Localization.GetString(Text, LocalResourceFile); + this.Text = Localization.GetString(this.Text, this.LocalResourceFile); - if ((string.IsNullOrEmpty(ToolTip))) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Localization.GetString(string.Format("{0}.ToolTip", Text), LocalResourceFile); + this.ToolTip = Localization.GetString(string.Format("{0}.ToolTip", this.Text), this.LocalResourceFile); } - if ((string.IsNullOrEmpty(ToolTip))) + if (string.IsNullOrEmpty(this.ToolTip)) { - ToolTip = Text; + this.ToolTip = this.Text; } } } + } + + protected override void CreateChildControls() + { + this.Controls.Clear(); + this.Controls.Add(this.TextHyperlinkControl); + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); } - #endregion + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + + if (!this.Enabled) + { + if (!string.IsNullOrEmpty(this.DisabledCssClass)) + { + this.CssClass = this.DisabledCssClass; + } + + this.NavigateUrl = "javascript:void(0);"; + } + + this.RenderBeginTag(writer); + this.RenderChildren(writer); + this.RenderEndTag(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneComboBox.cs index 0a9942e87bf..53a6222a2e9 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneComboBox.cs @@ -1,31 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - + using System; + using System.Web.UI.WebControls; + public class DnnTimeZoneComboBox : DropDownList { - protected override void OnInit(System.EventArgs e) { - //Utilities.ApplySkin(this); + // Utilities.ApplySkin(this); base.OnInit(e); this.DataTextField = "DisplayName"; this.DataValueField = "Id"; this.DataSource = TimeZoneInfo.GetSystemTimeZones(); - this.DataBind(); + this.DataBind(); } } -} - +} diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs index 679c5fdcccb..85608ee10eb 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs @@ -1,73 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.UI.WebControls; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Web.UI.WebControls.Extensions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { - + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.UI.WebControls.Extensions; + public class DnnTimeZoneEditControl : TextEditControl { - - - private DnnTimeZoneComboBox TimeZones; - #region "Constructors" - + private DnnTimeZoneComboBox TimeZones; + public DnnTimeZoneEditControl() { } - public override string EditControlClientId - { - get - { - EnsureChildControls(); - return TimeZones.ClientID; - } - } - - #endregion - - protected override void CreateChildControls() + public override string EditControlClientId { - TimeZones = new DnnTimeZoneComboBox(); - TimeZones.ViewStateMode = ViewStateMode.Disabled; - - Controls.Clear(); - Controls.Add(TimeZones); - - base.CreateChildControls(); - } + get + { + this.EnsureChildControls(); + return this.TimeZones.ClientID; + } + } public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { bool dataChanged = false; - string presentValue = StringValue; - string postedValue = TimeZones.SelectedValue; + string presentValue = this.StringValue; + string postedValue = this.TimeZones.SelectedValue; if (!presentValue.Equals(postedValue)) { - Value = postedValue; + this.Value = postedValue; dataChanged = true; } return dataChanged; } + + protected override void CreateChildControls() + { + this.TimeZones = new DnnTimeZoneComboBox(); + this.TimeZones.ViewStateMode = ViewStateMode.Disabled; + + this.Controls.Clear(); + this.Controls.Add(this.TimeZones); + + base.CreateChildControls(); + } protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = TimeZoneInfo.FindSystemTimeZoneById(StringValue); - args.OldValue = OldStringValue; - args.StringValue = StringValue; + var args = new PropertyEditorEventArgs(this.Name); + args.Value = TimeZoneInfo.FindSystemTimeZoneById(this.StringValue); + args.OldValue = this.OldStringValue; + args.StringValue = this.StringValue; base.OnValueChanged(args); } @@ -81,9 +71,9 @@ protected override void OnPreRender(System.EventArgs e) { base.OnPreRender(e); - TimeZones.DataBind(StringValue); + this.TimeZones.DataBind(this.StringValue); - if ((Page != null) && this.EditMode == PropertyEditorMode.Edit) + if ((this.Page != null) && this.EditMode == PropertyEditorMode.Edit) { this.Page.RegisterRequiresPostBack(this); } @@ -97,12 +87,10 @@ protected override void RenderEditMode(System.Web.UI.HtmlTextWriter writer) protected override void RenderViewMode(System.Web.UI.HtmlTextWriter writer) { string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(propValue); writer.RenderEndTag(); } - } - } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs index c9cf3f4773e..8ec9bbd1360 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs @@ -1,56 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using System.ComponentModel; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + /// /// Creates a control that renders its childs as a bulleted list. /// /// - /// Control renders an unordered list HTML contol. + /// Control renders an unordered list HTML contol. /// Each child control in is rendered as a separate list item. - /// To obtain a control over list item style, add a to a controls list, + /// To obtain a control over list item style, add a to a controls list, /// and tune this object appropriately. /// public class DnnUnsortedList : WebControl, INamingContainer { private UniformControlCollection _listItems = null; - public DnnUnsortedList() : base(HtmlTextWriterTag.Ul) - { - } - - protected override sealed ControlCollection CreateControlCollection() + public DnnUnsortedList() + : base(HtmlTextWriterTag.Ul) { - return new TypedControlCollection(this); } - [PersistenceMode(PersistenceMode.InnerDefaultProperty), MergableProperty(false)] + [PersistenceMode(PersistenceMode.InnerDefaultProperty)] + [MergableProperty(false)] public virtual UniformControlCollection ListItems { get { - return _listItems ?? (_listItems = new UniformControlCollection(this)); - } - } - - protected override void AddAttributesToRender(HtmlTextWriter writer) - { - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); - if (!string.IsNullOrEmpty(CssClass)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass); + return this._listItems ?? (this._listItems = new UniformControlCollection(this)); } } /// - /// A "macro" that adds a set of controls or control as a single list item (li). Use ListItems.Add(UnsortedListItem) method + /// A "macro" that adds a set of controls or control as a single list item (li). Use ListItems.Add(UnsortedListItem) method. /// /// /// All controls from the list will be rendered as a childs of a single list item. @@ -59,9 +47,21 @@ public void AddListItem(params Control[] listItemControls) { var listItem = new DnnUnsortedListItem(); listItem.AddControls(listItemControls); - ListItems.Add(listItem); + this.ListItems.Add(listItem); } - } + protected override sealed ControlCollection CreateControlCollection() + { + return new TypedControlCollection(this); + } + protected override void AddAttributesToRender(HtmlTextWriter writer) + { + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + if (!string.IsNullOrEmpty(this.CssClass)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); + } + } + } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs index dd165b3b67b..c9829570bed 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs @@ -1,22 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + /// /// Creates a control that render one item in a list ($lt;li> control). /// /// public class DnnUnsortedListItem : WebControl { - - public DnnUnsortedListItem() : base(HtmlTextWriterTag.Li) + public DnnUnsortedListItem() + : base(HtmlTextWriterTag.Li) { } @@ -26,24 +25,23 @@ public void AddControls(params Control[] childControls) { if (childControl != null) { - Controls.Add(childControl); + this.Controls.Add(childControl); } } } protected override void AddAttributesToRender(HtmlTextWriter writer) { - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); - if (!string.IsNullOrEmpty(CssClass)) + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + if (!string.IsNullOrEmpty(this.CssClass)) { - writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass); + writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); } - if (!string.IsNullOrEmpty(ToolTip)) + + if (!string.IsNullOrEmpty(this.ToolTip)) { - writer.AddAttribute(HtmlTextWriterAttribute.Title, ToolTip); + writer.AddAttribute(HtmlTextWriterAttribute.Title, this.ToolTip); } } - } - } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs index 68de5af89bb..a9f3f42e691 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs @@ -1,37 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text.RegularExpressions; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.Common; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.IO; + using System.Text.RegularExpressions; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.Common; + + using Globals = DotNetNuke.Common.Globals; + public abstract class DnnUrlControl : UserControlBase - { - #region Private Members - + { protected Panel ErrorRow; protected Panel FileRow; protected Panel ImagesRow; @@ -39,13 +33,13 @@ public abstract class DnnUrlControl : UserControlBase protected Panel TypeRow; protected Panel URLRow; protected Panel UserRow; + protected DropDownList cboImages; + protected DnnPageDropDownList cboTabs; private bool _doChangeURL; private bool _doRenderTypeControls; private bool _doRenderTypes; private string _localResourceFile; private PortalInfo _objPortal; - protected DropDownList cboImages; - protected DnnPageDropDownList cboTabs; protected DropDownList cboUrls; protected CheckBox chkLog; protected CheckBox chkNewWindow; @@ -62,26 +56,23 @@ public abstract class DnnUrlControl : UserControlBase protected RadioButtonList optType; protected TextBox txtUrl; protected TextBox txtUser; - protected DnnFilePickerUploader ctlFile; - - #endregion - - #region Public Properties - + protected DnnFilePickerUploader ctlFile; + public string FileFilter { get { - if (ViewState["FileFilter"] != null) + if (this.ViewState["FileFilter"] != null) { - return ViewState["FileFilter"].ToString(); + return this.ViewState["FileFilter"].ToString(); } return string.Empty; } + set { - ViewState["FileFilter"] = value; + this.ViewState["FileFilter"] = value; } } @@ -89,21 +80,22 @@ public bool IncludeActiveTab { get { - if (ViewState["IncludeActiveTab"] != null) + if (this.ViewState["IncludeActiveTab"] != null) { - return Convert.ToBoolean(ViewState["IncludeActiveTab"]); + return Convert.ToBoolean(this.ViewState["IncludeActiveTab"]); } else { - return false; //Set as default + return false; // Set as default } } + set { - ViewState["IncludeActiveTab"] = value; - if (IsTrackingViewState) + this.ViewState["IncludeActiveTab"] = value; + if (this.IsTrackingViewState) { - _doRenderTypeControls = true; + this._doRenderTypeControls = true; } } } @@ -113,19 +105,21 @@ public string LocalResourceFile get { string fileRoot; - if (String.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/URLControl.ascx"; + fileRoot = this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/URLControl.ascx"; } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } } @@ -133,9 +127,9 @@ public bool Log { get { - if (chkLog.Visible) + if (this.chkLog.Visible) { - return chkLog.Checked; + return this.chkLog.Checked; } else { @@ -149,31 +143,34 @@ public int ModuleID get { int myMid = -2; - if (ViewState["ModuleId"] != null) + if (this.ViewState["ModuleId"] != null) { - myMid = Convert.ToInt32(ViewState["ModuleId"]); + myMid = Convert.ToInt32(this.ViewState["ModuleId"]); } - else if (Request.QueryString["mid"] != null) + else if (this.Request.QueryString["mid"] != null) { - Int32.TryParse(Request.QueryString["mid"], out myMid); + int.TryParse(this.Request.QueryString["mid"], out myMid); } + return myMid; } + set { - ViewState["ModuleId"] = value; + this.ViewState["ModuleId"] = value; } } public bool NewWindow { - get + get { - return chkNewWindow.Visible && chkNewWindow.Checked; + return this.chkNewWindow.Visible && this.chkNewWindow.Checked; } - set + + set { - chkNewWindow.Checked = chkNewWindow.Visible && value; + this.chkNewWindow.Checked = this.chkNewWindow.Visible && value; } } @@ -181,21 +178,22 @@ public bool Required { get { - if (ViewState["Required"] != null) + if (this.ViewState["Required"] != null) { - return Convert.ToBoolean(ViewState["Required"]); + return Convert.ToBoolean(this.ViewState["Required"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["Required"] = value; - if (IsTrackingViewState) + this.ViewState["Required"] = value; + if (this.IsTrackingViewState) { - _doRenderTypeControls = true; + this._doRenderTypeControls = true; } } } @@ -204,21 +202,22 @@ public bool ShowFiles { get { - if (ViewState["ShowFiles"] != null) + if (this.ViewState["ShowFiles"] != null) { - return Convert.ToBoolean(ViewState["ShowFiles"]); + return Convert.ToBoolean(this.ViewState["ShowFiles"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowFiles"] = value; - if (IsTrackingViewState) + this.ViewState["ShowFiles"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -227,21 +226,22 @@ public bool ShowImages { get { - if (ViewState["ShowImages"] != null) + if (this.ViewState["ShowImages"] != null) { - return Convert.ToBoolean(ViewState["ShowImages"]); + return Convert.ToBoolean(this.ViewState["ShowImages"]); } else { return false; } } + set { - ViewState["ShowImages"] = value; - if (IsTrackingViewState) + this.ViewState["ShowImages"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -250,11 +250,12 @@ public bool ShowLog { get { - return chkLog.Visible; + return this.chkLog.Visible; } + set { - chkLog.Visible = value; + this.chkLog.Visible = value; } } @@ -262,11 +263,12 @@ public bool ShowNewWindow { get { - return chkNewWindow.Visible; + return this.chkNewWindow.Visible; } + set { - chkNewWindow.Visible = value; + this.chkNewWindow.Visible = value; } } @@ -274,21 +276,22 @@ public bool ShowNone { get { - if (ViewState["ShowNone"] != null) + if (this.ViewState["ShowNone"] != null) { - return Convert.ToBoolean(ViewState["ShowNone"]); + return Convert.ToBoolean(this.ViewState["ShowNone"]); } else { - return false; //Set as default in the old variable + return false; // Set as default in the old variable } } + set { - ViewState["ShowNone"] = value; - if (IsTrackingViewState) + this.ViewState["ShowNone"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -297,21 +300,22 @@ public bool ShowTabs { get { - if (ViewState["ShowTabs"] != null) + if (this.ViewState["ShowTabs"] != null) { - return Convert.ToBoolean(ViewState["ShowTabs"]); + return Convert.ToBoolean(this.ViewState["ShowTabs"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowTabs"] = value; - if (IsTrackingViewState) + this.ViewState["ShowTabs"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -320,11 +324,12 @@ public bool ShowTrack { get { - return chkTrack.Visible; + return this.chkTrack.Visible; } + set { - chkTrack.Visible = value; + this.chkTrack.Visible = value; } } @@ -332,21 +337,22 @@ public bool ShowUpLoad { get { - if (ViewState["ShowUpLoad"] != null) + if (this.ViewState["ShowUpLoad"] != null) { - return Convert.ToBoolean(ViewState["ShowUpLoad"]); + return Convert.ToBoolean(this.ViewState["ShowUpLoad"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowUpLoad"] = value; - if (IsTrackingViewState) + this.ViewState["ShowUpLoad"] = value; + if (this.IsTrackingViewState) { - _doRenderTypeControls = true; + this._doRenderTypeControls = true; } } } @@ -355,21 +361,22 @@ public bool ShowUrls { get { - if (ViewState["ShowUrls"] != null) + if (this.ViewState["ShowUrls"] != null) { - return Convert.ToBoolean(ViewState["ShowUrls"]); + return Convert.ToBoolean(this.ViewState["ShowUrls"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowUrls"] = value; - if (IsTrackingViewState) + this.ViewState["ShowUrls"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -378,21 +385,22 @@ public bool ShowUsers { get { - if (ViewState["ShowUsers"] != null) + if (this.ViewState["ShowUsers"] != null) { - return Convert.ToBoolean(ViewState["ShowUsers"]); + return Convert.ToBoolean(this.ViewState["ShowUsers"]); } else { - return false; //Set as default in the old variable + return false; // Set as default in the old variable } } + set { - ViewState["ShowUsers"] = value; - if (IsTrackingViewState) + this.ViewState["ShowUsers"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -401,9 +409,9 @@ public bool Track { get { - if (chkTrack.Visible) + if (this.chkTrack.Visible) { - return chkTrack.Checked; + return this.chkTrack.Checked; } else { @@ -416,91 +424,99 @@ public string Url { get { - string r = ""; - string strCurrentType = ""; - if (optType.Items.Count > 0 && optType.SelectedIndex >= 0) + string r = string.Empty; + string strCurrentType = string.Empty; + if (this.optType.Items.Count > 0 && this.optType.SelectedIndex >= 0) { - strCurrentType = optType.SelectedItem.Value; + strCurrentType = this.optType.SelectedItem.Value; } + switch (strCurrentType) { case "I": - if (cboImages.SelectedItem != null) + if (this.cboImages.SelectedItem != null) { - r = cboImages.SelectedItem.Value; + r = this.cboImages.SelectedItem.Value; } + break; case "U": - if (cboUrls.Visible) + if (this.cboUrls.Visible) { - if (cboUrls.SelectedItem != null) + if (this.cboUrls.SelectedItem != null) { - r = cboUrls.SelectedItem.Value; - txtUrl.Text = r; + r = this.cboUrls.SelectedItem.Value; + this.txtUrl.Text = r; } } else { - string mCustomUrl = txtUrl.Text; + string mCustomUrl = this.txtUrl.Text; if (mCustomUrl.Equals("http://", StringComparison.InvariantCultureIgnoreCase)) { - r = ""; + r = string.Empty; } else { r = Globals.AddHTTP(mCustomUrl); } } + break; case "T": - string strTab = ""; - if (cboTabs.SelectedItem != null) + string strTab = string.Empty; + if (this.cboTabs.SelectedItem != null) { - strTab = cboTabs.SelectedItem.Value; + strTab = this.cboTabs.SelectedItem.Value; int id; - if (int.TryParse(strTab,out id) && id >= 0) + if (int.TryParse(strTab, out id) && id >= 0) { r = strTab; } } + break; case "F": - if (ctlFile.FileID > Null.NullInteger) + if (this.ctlFile.FileID > Null.NullInteger) { - r = "FileID=" + ctlFile.FileID; + r = "FileID=" + this.ctlFile.FileID; } else { - r = ""; + r = string.Empty; } + break; case "M": - if (!String.IsNullOrEmpty(txtUser.Text)) + if (!string.IsNullOrEmpty(this.txtUser.Text)) { - UserInfo objUser = UserController.GetCachedUser(_objPortal.PortalID, txtUser.Text); + UserInfo objUser = UserController.GetCachedUser(this._objPortal.PortalID, this.txtUser.Text); if (objUser != null) { r = "UserID=" + objUser.UserID; } else { - lblMessage.Text = Localization.GetString("NoUser", LocalResourceFile); - ErrorRow.Visible = true; - txtUser.Text = ""; + this.lblMessage.Text = Localization.GetString("NoUser", this.LocalResourceFile); + this.ErrorRow.Visible = true; + this.txtUser.Text = string.Empty; } } + break; } + return r; } + set { - ViewState["Url"] = value; - txtUrl.Text = string.Empty; + this.ViewState["Url"] = value; + this.txtUrl.Text = string.Empty; - if (IsTrackingViewState) + if (this.IsTrackingViewState) { - _doChangeURL = true; + this._doChangeURL = true; } } } @@ -509,16 +525,17 @@ public string UrlType { get { - return Convert.ToString(ViewState["UrlType"]); + return Convert.ToString(this.ViewState["UrlType"]); } + set { - if (value != null && !String.IsNullOrEmpty(value.Trim())) + if (value != null && !string.IsNullOrEmpty(value.Trim())) { - ViewState["UrlType"] = value; - if (IsTrackingViewState) + this.ViewState["UrlType"] = value; + if (this.IsTrackingViewState) { - _doChangeURL = true; + this._doChangeURL = true; } } } @@ -528,49 +545,102 @@ public string Width { get { - return Convert.ToString(ViewState["SkinControlWidth"]); + return Convert.ToString(this.ViewState["SkinControlWidth"]); } + set { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { - cboUrls.Width = Unit.Parse(value); - txtUrl.Width = Unit.Parse(value); - cboImages.Width = Unit.Parse(value); - cboTabs.Width = Unit.Parse(value); - txtUser.Width = Unit.Parse(value); - ViewState["SkinControlWidth"] = value; + this.cboUrls.Width = Unit.Parse(value); + this.txtUrl.Width = Unit.Parse(value); + this.cboImages.Width = Unit.Parse(value); + this.cboTabs.Width = Unit.Parse(value); + this.txtUser.Width = Unit.Parse(value); + this.ViewState["SkinControlWidth"] = value; } } + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + // prevent unauthorized access + if (this.Request.IsAuthenticated == false) + { + this.Visible = false; + } + + ClientResourceManager.EnableAsyncPostBackHandler(); } - #endregion + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.optType.SelectedIndexChanged += this.optType_SelectedIndexChanged; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdSelect.Click += this.cmdSelect_Click; - #region Private Methods + this.ErrorRow.Visible = false; + try + { + if ((this.Request.QueryString["pid"] != null) && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + { + this._objPortal = PortalController.Instance.GetPortal(int.Parse(this.Request.QueryString["pid"])); + } + else + { + this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); + } + + if (this.ViewState["IsUrlControlLoaded"] == null) + { + // If Not Page.IsPostBack Then + // let's make at least an initialization + // The type radio button must be initialized + // The url must be initialized no matter its value + this._doRenderTypes = true; + this._doChangeURL = true; + ClientAPI.AddButtonConfirm(this.cmdDelete, Localization.GetString("DeleteItem")); + + // The following line was mover to the pre-render event to ensure render for the first time + // ViewState("IsUrlControlLoaded") = "Loaded" + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private void LoadUrls() { var objUrls = new UrlController(); - cboUrls.Items.Clear(); - cboUrls.DataSource = objUrls.GetUrls(_objPortal.PortalID); - cboUrls.DataBind(); + this.cboUrls.Items.Clear(); + this.cboUrls.DataSource = objUrls.GetUrls(this._objPortal.PortalID); + this.cboUrls.DataBind(); } private void DoChangeURL() { - string _Url = Convert.ToString(ViewState["Url"]); - string _Urltype = Convert.ToString(ViewState["UrlType"]); - if (!String.IsNullOrEmpty(_Url)) + string _Url = Convert.ToString(this.ViewState["Url"]); + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); + if (!string.IsNullOrEmpty(_Url)) { var objUrls = new UrlController(); string TrackingUrl = _Url; _Urltype = Globals.GetURLType(_Url).ToString("g").Substring(0, 1); - if (_Urltype == "U" && (_Url.StartsWith("~/" + PortalSettings.DefaultIconLocation, StringComparison.InvariantCultureIgnoreCase))) + if (_Urltype == "U" && _Url.StartsWith("~/" + this.PortalSettings.DefaultIconLocation, StringComparison.InvariantCultureIgnoreCase)) { _Urltype = "I"; } - ViewState["UrlType"] = _Urltype; + + this.ViewState["UrlType"] = _Urltype; if (_Urltype == "F") { if (_Url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) @@ -584,10 +654,10 @@ private void DoChangeURL() } else { - //to handle legacy scenarios before the introduction of the FileServerHandler + // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(_Url); var folderPath = _Url.Substring(0, _Url.LastIndexOf(fileName)); - var folder = FolderManager.Instance.GetFolder(_objPortal.PortalID, folderPath); + var folder = FolderManager.Instance.GetFolder(this._objPortal.PortalID, folderPath); var fileId = -1; if (folder != null) { @@ -597,415 +667,379 @@ private void DoChangeURL() fileId = file.FileId; } } + TrackingUrl = "FileID=" + fileId.ToString(); } } + if (_Urltype == "M") { if (_Url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) { - UserInfo objUser = UserController.GetUserById(_objPortal.PortalID, int.Parse(_Url.Substring(7))); + UserInfo objUser = UserController.GetUserById(this._objPortal.PortalID, int.Parse(_Url.Substring(7))); if (objUser != null) { _Url = objUser.Username; } } } - UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(_objPortal.PortalID, TrackingUrl, ModuleID); + + UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this._objPortal.PortalID, TrackingUrl, this.ModuleID); if (objUrlTracking != null) { - chkNewWindow.Checked = objUrlTracking.NewWindow; - chkTrack.Checked = objUrlTracking.TrackClicks; - chkLog.Checked = objUrlTracking.LogActivity; + this.chkNewWindow.Checked = objUrlTracking.NewWindow; + this.chkTrack.Checked = objUrlTracking.TrackClicks; + this.chkLog.Checked = objUrlTracking.LogActivity; } - else //the url does not exist in the tracking table + else // the url does not exist in the tracking table { - chkTrack.Checked = false; - chkLog.Checked = false; + this.chkTrack.Checked = false; + this.chkLog.Checked = false; } - ViewState["Url"] = _Url; + + this.ViewState["Url"] = _Url; } else { - if (!String.IsNullOrEmpty(_Urltype)) + if (!string.IsNullOrEmpty(_Urltype)) { - optType.ClearSelection(); - if (optType.Items.FindByValue(_Urltype) != null) + this.optType.ClearSelection(); + if (this.optType.Items.FindByValue(_Urltype) != null) { - optType.Items.FindByValue(_Urltype).Selected = true; + this.optType.Items.FindByValue(_Urltype).Selected = true; } else { - optType.Items[0].Selected = true; + this.optType.Items[0].Selected = true; } } else { - if (optType.Items.Count > 0) + if (this.optType.Items.Count > 0) { - optType.ClearSelection(); - optType.Items[0].Selected = true; + this.optType.ClearSelection(); + this.optType.Items[0].Selected = true; } } - chkNewWindow.Checked = false; //Need check - chkTrack.Checked = false; //Need check - chkLog.Checked = false; //Need check + + this.chkNewWindow.Checked = false; // Need check + this.chkTrack.Checked = false; // Need check + this.chkLog.Checked = false; // Need check } - //Url type changed, then we must draw the controlos for that type - _doRenderTypeControls = true; + // Url type changed, then we must draw the controlos for that type + this._doRenderTypeControls = true; } private void DoRenderTypes() { - //We must clear the list to keep the same item order - string strCurrent = ""; - if (optType.SelectedIndex >= 0) + // We must clear the list to keep the same item order + string strCurrent = string.Empty; + if (this.optType.SelectedIndex >= 0) { - strCurrent = optType.SelectedItem.Value; //Save current selected value + strCurrent = this.optType.SelectedItem.Value; // Save current selected value } - optType.Items.Clear(); - if (ShowNone) + + this.optType.Items.Clear(); + if (this.ShowNone) { - if (optType.Items.FindByValue("N") == null) + if (this.optType.Items.FindByValue("N") == null) { - optType.Items.Add(new ListItem(Localization.GetString("NoneType", LocalResourceFile), "N")); + this.optType.Items.Add(new ListItem(Localization.GetString("NoneType", this.LocalResourceFile), "N")); } } else { - if (optType.Items.FindByValue("N") != null) + if (this.optType.Items.FindByValue("N") != null) { - optType.Items.Remove(optType.Items.FindByValue("N")); + this.optType.Items.Remove(this.optType.Items.FindByValue("N")); } } - if (ShowUrls) + + if (this.ShowUrls) { - if (optType.Items.FindByValue("U") == null) + if (this.optType.Items.FindByValue("U") == null) { - optType.Items.Add(new ListItem(Localization.GetString("URLType", LocalResourceFile), "U")); + this.optType.Items.Add(new ListItem(Localization.GetString("URLType", this.LocalResourceFile), "U")); } } else { - if (optType.Items.FindByValue("U") != null) + if (this.optType.Items.FindByValue("U") != null) { - optType.Items.Remove(optType.Items.FindByValue("U")); + this.optType.Items.Remove(this.optType.Items.FindByValue("U")); } } - if (ShowTabs) + + if (this.ShowTabs) { - if (optType.Items.FindByValue("T") == null) + if (this.optType.Items.FindByValue("T") == null) { - optType.Items.Add(new ListItem(Localization.GetString("TabType", LocalResourceFile), "T")); + this.optType.Items.Add(new ListItem(Localization.GetString("TabType", this.LocalResourceFile), "T")); } } else { - if (optType.Items.FindByValue("T") != null) + if (this.optType.Items.FindByValue("T") != null) { - optType.Items.Remove(optType.Items.FindByValue("T")); + this.optType.Items.Remove(this.optType.Items.FindByValue("T")); } } - if (ShowFiles) + + if (this.ShowFiles) { - if (optType.Items.FindByValue("F") == null) + if (this.optType.Items.FindByValue("F") == null) { - optType.Items.Add(new ListItem(Localization.GetString("FileType", LocalResourceFile), "F")); + this.optType.Items.Add(new ListItem(Localization.GetString("FileType", this.LocalResourceFile), "F")); } } else { - if (optType.Items.FindByValue("F") != null) + if (this.optType.Items.FindByValue("F") != null) { - optType.Items.Remove(optType.Items.FindByValue("F")); + this.optType.Items.Remove(this.optType.Items.FindByValue("F")); } } - if (ShowImages) + + if (this.ShowImages) { - if (optType.Items.FindByValue("I") == null) + if (this.optType.Items.FindByValue("I") == null) { - optType.Items.Add(new ListItem(Localization.GetString("ImageType", LocalResourceFile), "I")); + this.optType.Items.Add(new ListItem(Localization.GetString("ImageType", this.LocalResourceFile), "I")); } } else { - if (optType.Items.FindByValue("I") != null) + if (this.optType.Items.FindByValue("I") != null) { - optType.Items.Remove(optType.Items.FindByValue("I")); + this.optType.Items.Remove(this.optType.Items.FindByValue("I")); } } - if (ShowUsers) + + if (this.ShowUsers) { - if (optType.Items.FindByValue("M") == null) + if (this.optType.Items.FindByValue("M") == null) { - optType.Items.Add(new ListItem(Localization.GetString("UserType", LocalResourceFile), "M")); + this.optType.Items.Add(new ListItem(Localization.GetString("UserType", this.LocalResourceFile), "M")); } } else { - if (optType.Items.FindByValue("M") != null) + if (this.optType.Items.FindByValue("M") != null) { - optType.Items.Remove(optType.Items.FindByValue("M")); + this.optType.Items.Remove(this.optType.Items.FindByValue("M")); } } - if (optType.Items.Count > 0) + + if (this.optType.Items.Count > 0) { - if (!String.IsNullOrEmpty(strCurrent)) + if (!string.IsNullOrEmpty(strCurrent)) { - if (optType.Items.FindByValue(strCurrent) != null) + if (this.optType.Items.FindByValue(strCurrent) != null) { - optType.Items.FindByValue(strCurrent).Selected = true; + this.optType.Items.FindByValue(strCurrent).Selected = true; } else { - optType.Items[0].Selected = true; - _doRenderTypeControls = true; //Type changed, re-draw + this.optType.Items[0].Selected = true; + this._doRenderTypeControls = true; // Type changed, re-draw } } else { - optType.Items[0].Selected = true; - _doRenderTypeControls = true; //Type changed, re-draw + this.optType.Items[0].Selected = true; + this._doRenderTypeControls = true; // Type changed, re-draw } - TypeRow.Visible = optType.Items.Count > 1; + + this.TypeRow.Visible = this.optType.Items.Count > 1; } else { - TypeRow.Visible = false; + this.TypeRow.Visible = false; } } private void DoCorrectRadioButtonList() { - string _Urltype = Convert.ToString(ViewState["UrlType"]); + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); - if (optType.Items.Count > 0) + if (this.optType.Items.Count > 0) { - optType.ClearSelection(); - if (!String.IsNullOrEmpty(_Urltype)) + this.optType.ClearSelection(); + if (!string.IsNullOrEmpty(_Urltype)) { - if (optType.Items.FindByValue(_Urltype) != null) + if (this.optType.Items.FindByValue(_Urltype) != null) { - optType.Items.FindByValue(_Urltype).Selected = true; + this.optType.Items.FindByValue(_Urltype).Selected = true; } else { - optType.Items[0].Selected = true; - _Urltype = optType.Items[0].Value; - ViewState["UrlType"] = _Urltype; + this.optType.Items[0].Selected = true; + _Urltype = this.optType.Items[0].Value; + this.ViewState["UrlType"] = _Urltype; } } else { - optType.Items[0].Selected = true; - _Urltype = optType.Items[0].Value; - ViewState["UrlType"] = _Urltype; + this.optType.Items[0].Selected = true; + _Urltype = this.optType.Items[0].Value; + this.ViewState["UrlType"] = _Urltype; } } } private void DoRenderTypeControls() { - string _Url = Convert.ToString(ViewState["Url"]); - string _Urltype = Convert.ToString(ViewState["UrlType"]); + string _Url = Convert.ToString(this.ViewState["Url"]); + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); var objUrls = new UrlController(); - if (!String.IsNullOrEmpty(_Urltype)) + if (!string.IsNullOrEmpty(_Urltype)) { - //load listitems - switch (optType.SelectedItem.Value) + // load listitems + switch (this.optType.SelectedItem.Value) { - case "N": //None - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = false; + case "N": // None + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; break; - case "I": //System Image - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = true; + case "I": // System Image + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = true; - cboImages.Items.Clear(); + this.cboImages.Items.Clear(); - string strImagesFolder = Path.Combine(Globals.ApplicationMapPath, PortalSettings.DefaultIconLocation.Replace('/', '\\')); + string strImagesFolder = Path.Combine(Globals.ApplicationMapPath, this.PortalSettings.DefaultIconLocation.Replace('/', '\\')); foreach (string strImage in Directory.GetFiles(strImagesFolder)) { - string img = strImage.Replace(strImagesFolder, "").Trim('/').Trim('\\'); - cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", PortalSettings.DefaultIconLocation, img).ToLowerInvariant())); + string img = strImage.Replace(strImagesFolder, string.Empty).Trim('/').Trim('\\'); + this.cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", this.PortalSettings.DefaultIconLocation, img).ToLowerInvariant())); } - ListItem selecteItem = cboImages.Items.FindByValue(_Url.ToLowerInvariant()); + ListItem selecteItem = this.cboImages.Items.FindByValue(_Url.ToLowerInvariant()); if (selecteItem != null) { selecteItem.Selected = true; } + break; - case "U": //Url - URLRow.Visible = true; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = false; - if (String.IsNullOrEmpty(txtUrl.Text)) + case "U": // Url + this.URLRow.Visible = true; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + if (string.IsNullOrEmpty(this.txtUrl.Text)) { - txtUrl.Text = _Url; + this.txtUrl.Text = _Url; } - if (String.IsNullOrEmpty(txtUrl.Text)) + + if (string.IsNullOrEmpty(this.txtUrl.Text)) { - txtUrl.Text = "http://"; + this.txtUrl.Text = "http://"; } - txtUrl.Visible = true; + + this.txtUrl.Visible = true; - cmdSelect.Visible = true; + this.cmdSelect.Visible = true; - cboUrls.Visible = false; - cmdAdd.Visible = false; - cmdDelete.Visible = false; + this.cboUrls.Visible = false; + this.cmdAdd.Visible = false; + this.cmdDelete.Visible = false; break; - case "T": //tab - URLRow.Visible = false; - TabRow.Visible = true; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = false; - - cboTabs.IncludeAllTabTypes = false; - cboTabs.IncludeActiveTab = IncludeActiveTab; - cboTabs.IncludeDisabledTabs = true; - cboTabs.DisabledNotSelectable = true; - cboTabs.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, string.Empty); + case "T": // tab + this.URLRow.Visible = false; + this.TabRow.Visible = true; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + + this.cboTabs.IncludeAllTabTypes = false; + this.cboTabs.IncludeActiveTab = this.IncludeActiveTab; + this.cboTabs.IncludeDisabledTabs = true; + this.cboTabs.DisabledNotSelectable = true; + this.cboTabs.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, string.Empty); if (!string.IsNullOrEmpty(_Url)) { PortalSettings _settings = PortalController.Instance.GetCurrentPortalSettings(); - var tabId = Int32.Parse(_Url); + var tabId = int.Parse(_Url); var page = TabController.Instance.GetTab(tabId, _settings.PortalId); - cboTabs.SelectedPage = page; + this.cboTabs.SelectedPage = page; } + break; - case "F": //file - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = true; - UserRow.Visible = false; - ImagesRow.Visible = false; - - //select folder - //We Must check if selected folder has changed because of a property change (Secure, Database) + case "F": // file + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = true; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + + // select folder + // We Must check if selected folder has changed because of a property change (Secure, Database) string FileName = string.Empty; string FolderPath = string.Empty; string LastFileName = string.Empty; string LastFolderPath = string.Empty; - //Let's try to remember last selection - if (ViewState["LastFolderPath"] != null) + + // Let's try to remember last selection + if (this.ViewState["LastFolderPath"] != null) { - LastFolderPath = Convert.ToString(ViewState["LastFolderPath"]); + LastFolderPath = Convert.ToString(this.ViewState["LastFolderPath"]); } - if (ViewState["LastFileName"] != null) + + if (this.ViewState["LastFileName"] != null) { - LastFileName = Convert.ToString(ViewState["LastFileName"]); + LastFileName = Convert.ToString(this.ViewState["LastFileName"]); } + if (_Url != string.Empty) { - //Let's use the new URL + // Let's use the new URL FileName = _Url.Substring(_Url.LastIndexOf("/") + 1); - FolderPath = _Url.Replace(FileName, ""); + FolderPath = _Url.Replace(FileName, string.Empty); } else { - //Use last settings + // Use last settings FileName = LastFileName; FolderPath = LastFolderPath; } - ctlFile.FilePath = FolderPath + FileName; + this.ctlFile.FilePath = FolderPath + FileName; - txtUrl.Visible = false; + this.txtUrl.Visible = false; break; - case "M": //membership users - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = true; - ImagesRow.Visible = false; - if (String.IsNullOrEmpty(txtUser.Text)) + case "M": // membership users + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = true; + this.ImagesRow.Visible = false; + if (string.IsNullOrEmpty(this.txtUser.Text)) { - txtUser.Text = _Url; + this.txtUser.Text = _Url; } + break; } } else { - URLRow.Visible = false; - ImagesRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - } - } - - #endregion - - #region Event Handlers - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - //prevent unauthorized access - if (Request.IsAuthenticated == false) - { - Visible = false; + this.URLRow.Visible = false; + this.ImagesRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; } - - ClientResourceManager.EnableAsyncPostBackHandler(); - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - optType.SelectedIndexChanged += optType_SelectedIndexChanged; - cmdAdd.Click += cmdAdd_Click; - cmdDelete.Click += cmdDelete_Click; - cmdSelect.Click += cmdSelect_Click; - - ErrorRow.Visible = false; - - try - { - if ((Request.QueryString["pid"] != null) && (Globals.IsHostTab(PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) - { - _objPortal = PortalController.Instance.GetPortal(Int32.Parse(Request.QueryString["pid"])); - } - else - { - _objPortal = PortalController.Instance.GetPortal(PortalSettings.PortalId); - } - if (ViewState["IsUrlControlLoaded"] == null) - { - //If Not Page.IsPostBack Then - //let's make at least an initialization - //The type radio button must be initialized - //The url must be initialized no matter its value - _doRenderTypes = true; - _doChangeURL = true; - ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem")); - //The following line was mover to the pre-render event to ensure render for the first time - //ViewState("IsUrlControlLoaded") = "Loaded" - } - } - catch (Exception exc) //Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } + } protected override void OnPreRender(EventArgs e) { @@ -1013,82 +1047,85 @@ protected override void OnPreRender(EventArgs e) try { - if (_doRenderTypes) + if (this._doRenderTypes) { - DoRenderTypes(); + this.DoRenderTypes(); } - if (_doChangeURL) + + if (this._doChangeURL) { - DoChangeURL(); + this.DoChangeURL(); } - DoCorrectRadioButtonList(); + + this.DoCorrectRadioButtonList(); - if (_doRenderTypeControls) + if (this._doRenderTypeControls) { - DoRenderTypeControls(); + this.DoRenderTypeControls(); } - ViewState["Url"] = null; - ViewState["IsUrlControlLoaded"] = "Loaded"; + + this.ViewState["Url"] = null; + this.ViewState["IsUrlControlLoaded"] = "Loaded"; - ctlFile.FileFilter = FileFilter; + this.ctlFile.FileFilter = this.FileFilter; } catch (Exception exc) { - //Let's detect possible problems + // Let's detect possible problems Exceptions.LogException(new Exception("Error rendering URLControl subcontrols.", exc)); } } protected void cmdAdd_Click(object sender, EventArgs e) { - cboUrls.Visible = false; - cmdSelect.Visible = true; - txtUrl.Visible = true; - cmdAdd.Visible = false; - cmdDelete.Visible = false; - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; + this.cboUrls.Visible = false; + this.cmdSelect.Visible = true; + this.txtUrl.Visible = true; + this.cmdAdd.Visible = false; + this.cmdDelete.Visible = false; + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; } protected void cmdDelete_Click(object sender, EventArgs e) { - if (cboUrls.SelectedItem != null) + if (this.cboUrls.SelectedItem != null) { var objUrls = new UrlController(); - objUrls.DeleteUrl(_objPortal.PortalID, cboUrls.SelectedItem.Value); - LoadUrls(); //we must reload the url list + objUrls.DeleteUrl(this._objPortal.PortalID, this.cboUrls.SelectedItem.Value); + this.LoadUrls(); // we must reload the url list } - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; } protected void cmdSelect_Click(object sender, EventArgs e) { - cboUrls.Visible = true; - cmdSelect.Visible = false; - txtUrl.Visible = false; - cmdAdd.Visible = true; - cmdDelete.Visible = PortalSecurity.IsInRole(_objPortal.AdministratorRoleName); - LoadUrls(); - if (cboUrls.Items.FindByValue(txtUrl.Text) != null) - { - cboUrls.ClearSelection(); - cboUrls.Items.FindByValue(txtUrl.Text).Selected = true; - } - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; + this.cboUrls.Visible = true; + this.cmdSelect.Visible = false; + this.txtUrl.Visible = false; + this.cmdAdd.Visible = true; + this.cmdDelete.Visible = PortalSecurity.IsInRole(this._objPortal.AdministratorRoleName); + this.LoadUrls(); + if (this.cboUrls.Items.FindByValue(this.txtUrl.Text) != null) + { + this.cboUrls.ClearSelection(); + this.cboUrls.Items.FindByValue(this.txtUrl.Text).Selected = true; + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; } - protected void optType_SelectedIndexChanged(Object sender, EventArgs e) + protected void optType_SelectedIndexChanged(object sender, EventArgs e) { - //Type changed, render the correct control set - ViewState["UrlType"] = optType.SelectedItem.Value; - _doRenderTypeControls = true; - } - - #endregion + // Type changed, render the correct control set + this.ViewState["UrlType"] = this.optType.SelectedItem.Value; + this._doRenderTypeControls = true; + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs index a95e2653375..6538ac1a9a1 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls.Extensions { + using System; + using System.Linq; + using System.Web.UI.WebControls; + public static class ListControlExtensions { public static void AddItem(this ListControl control, string text, string value) @@ -44,12 +44,12 @@ public static void Select(this ListControl control, string initial, bool findByT public static void Select(this ListControl control, string initial, bool findByText, int fallbackIndex) { - control.ClearSelection(); + control.ClearSelection(); if (findByText) { - if (control.Items.FindByTextWithIgnoreCase(initial) != null) + if (control.Items.FindByTextWithIgnoreCase(initial) != null) { - control.Items.FindByTextWithIgnoreCase(initial).Selected = true; + control.Items.FindByTextWithIgnoreCase(initial).Selected = true; } else if (fallbackIndex > -1) { @@ -58,9 +58,9 @@ public static void Select(this ListControl control, string initial, bool findByT } else { - if (control.Items.FindByValueWithIgnoreCase(initial) != null) + if (control.Items.FindByValueWithIgnoreCase(initial) != null) { - control.Items.FindByValueWithIgnoreCase(initial).Selected = true; + control.Items.FindByValueWithIgnoreCase(initial).Selected = true; } else if (fallbackIndex > -1) { @@ -68,26 +68,27 @@ public static void Select(this ListControl control, string initial, bool findByT } } } - /// - /// Use this method instead of ListItemCollection.FindByText to find the specific item with case-insensitive. - /// - /// the items. - /// the item with this text want to find. - /// the specific item or null if didn't match the text with any item. - public static ListItem FindByTextWithIgnoreCase(this ListItemCollection listItems, string text) - { - return listItems.Cast().FirstOrDefault(item => item.Text.Equals(text, StringComparison.InvariantCultureIgnoreCase)); - } + + /// + /// Use this method instead of ListItemCollection.FindByText to find the specific item with case-insensitive. + /// + /// the items. + /// the item with this text want to find. + /// the specific item or null if didn't match the text with any item. + public static ListItem FindByTextWithIgnoreCase(this ListItemCollection listItems, string text) + { + return listItems.Cast().FirstOrDefault(item => item.Text.Equals(text, StringComparison.InvariantCultureIgnoreCase)); + } - /// - /// Use this method instead of ListItemCollection.FindBValue to find the specific item with case-insensitive. - /// - /// the items. - /// the item with this value want to find. - /// the specific item or null if didn't match the value with any item. - public static ListItem FindByValueWithIgnoreCase(this ListItemCollection listItems, string value) - { - return listItems.Cast().FirstOrDefault(item => item.Value.Equals(value, StringComparison.InvariantCultureIgnoreCase)); - } + /// + /// Use this method instead of ListItemCollection.FindBValue to find the specific item with case-insensitive. + /// + /// the items. + /// the item with this value want to find. + /// the specific item or null if didn't match the value with any item. + public static ListItem FindByValueWithIgnoreCase(this ListItemCollection listItems, string value) + { + return listItems.Cast().FirstOrDefault(item => item.Value.Equals(value, StringComparison.InvariantCultureIgnoreCase)); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/WebControlExtensions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/WebControlExtensions.cs index d16098ea641..479a332ee0d 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/WebControlExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/WebControlExtensions.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Drawing; -using System.Linq; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls.Extensions { + using System; + using System.Drawing; + using System.Linq; + using System.Web.UI.WebControls; + public static class WebControlExtensions { public static void AddCssClass(this WebControl control, string cssClass) @@ -43,7 +43,5 @@ public static Orientation Orientation(this Size size) return size.Width > size.Height ? System.Web.UI.WebControls.Orientation.Horizontal : System.Web.UI.WebControls.Orientation.Vertical; } - } - } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/IDnnRibbonBarTool.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/IDnnRibbonBarTool.cs index 46e5b2fbc8a..c85ebc9fe4d 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/IDnnRibbonBarTool.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/IDnnRibbonBarTool.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { public interface IDnnRibbonBarTool diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs index f643eb8d91b..df929f7ffe0 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs @@ -1,46 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls.Extensions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls.Extensions; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnCheckBoxList : CheckBoxList { - protected override void OnInit(EventArgs e) - { - RepeatColumns = 1; - base.OnInit(e); - } - private string _initValue; + public override string SelectedValue { get { return base.SelectedValue; - } + set { if (this.RequiresDataBinding) { - _initValue = value; + this._initValue = value; } else { @@ -49,19 +40,11 @@ public override string SelectedValue } } - protected override void OnPreRender(EventArgs e) - { - Utilities.ApplySkin(this); - RegisterRequestResources(); - - base.OnPreRender(e); - } - public override void DataBind() { - if (!string.IsNullOrEmpty(_initValue)) + if (!string.IsNullOrEmpty(this._initValue)) { - DataBind(_initValue); + this.DataBind(this._initValue); } else { @@ -71,57 +54,71 @@ public override void DataBind() public void AddItem(string text, string value) { - Items.Add(new ListItem(text, value)); + this.Items.Add(new ListItem(text, value)); + } + + protected override void OnInit(EventArgs e) + { + this.RepeatColumns = 1; + base.OnInit(e); + } + + protected override void OnPreRender(EventArgs e) + { + Utilities.ApplySkin(this); + this.RegisterRequestResources(); + + base.OnPreRender(e); } public void InsertItem(int index, string text, string value) { - Items.Insert(index, new ListItem(text, value)); + this.Items.Insert(index, new ListItem(text, value)); } public void DataBind(string initialValue) { - DataBind(initialValue, false); + this.DataBind(initialValue, false); } public void DataBind(string initial, bool findByText) { base.DataBind(); - Select(initial, findByText); + this.Select(initial, findByText); } public void Select(string initial, bool findByText) { if (findByText) { - if (FindItemByText(initial, true) != null) + if (this.FindItemByText(initial, true) != null) { - FindItemByText(initial, true).Selected = true; + this.FindItemByText(initial, true).Selected = true; } } else { - if (FindItemByValue(initial, true) != null) + if (this.FindItemByValue(initial, true) != null) { - FindItemByValue(initial, true).Selected = true; + this.FindItemByValue(initial, true).Selected = true; } } } public ListItem FindItemByText(string text, bool ignoreCase = false) { - return ignoreCase ? Items.FindByText(text) : Items.FindByTextWithIgnoreCase(text); + return ignoreCase ? this.Items.FindByText(text) : this.Items.FindByTextWithIgnoreCase(text); } public ListItem FindItemByValue(string value, bool ignoreCase = false) { - return ignoreCase ? Items.FindByValue(value) : Items.FindByValueWithIgnoreCase(value); + return ignoreCase ? this.Items.FindByValue(value) : this.Items.FindByValueWithIgnoreCase(value); } public int FindItemIndexByValue(string value) { - return Items.IndexOf(FindItemByValue(value)); + return this.Items.IndexOf(this.FindItemByValue(value)); } private void RegisterRequestResources() @@ -137,12 +134,12 @@ private void RegisterRequestResources() var libraryPath = $"~/Resources/Libraries/{package.LibraryName}/{Globals.FormatVersion(package.Version, "00", 3, "_")}/"; - ClientResourceManager.RegisterStyleSheet(Page, $"{libraryPath}selectize.css"); - ClientResourceManager.RegisterStyleSheet(Page, $"{libraryPath}selectize.default.css"); + ClientResourceManager.RegisterStyleSheet(this.Page, $"{libraryPath}selectize.css"); + ClientResourceManager.RegisterStyleSheet(this.Page, $"{libraryPath}selectize.default.css"); - var initScripts = $"$('#{ClientID}').selectize({{}});"; + var initScripts = $"$('#{this.ClientID}').selectize({{}});"; - Page.ClientScript.RegisterStartupScript(Page.GetType(), $"{ClientID}Sctipts", initScripts, true); + this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), $"{this.ClientID}Sctipts", initScripts, true); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs index 932c7e53091..717218b8def 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs @@ -1,54 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Linq; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls.Extensions; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Collections.Specialized; + using System.Linq; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls.Extensions; + using Newtonsoft.Json; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnComboBox : DropDownList - { - #region Fields - + { private string _initValue; - private string _multipleValue; - - #endregion - - #region Properties - + private string _multipleValue; + public override string SelectedValue { get { return base.SelectedValue; - } + set { if (this.RequiresDataBinding) { - _initValue = value; + this._initValue = value; } - if (Items.Cast().Any(i => i.Value == value)) + if (this.Items.Cast().Any(i => i.Value == value)) { base.SelectedValue = value; } @@ -65,45 +55,59 @@ public string Value { get { - if (TagKey == HtmlTextWriterTag.Input) + if (this.TagKey == HtmlTextWriterTag.Input) { - return _multipleValue ?? string.Empty; + return this._multipleValue ?? string.Empty; } - return SelectedValue ?? string.Empty; + return this.SelectedValue ?? string.Empty; } + set { - if (TagKey == HtmlTextWriterTag.Input) + if (this.TagKey == HtmlTextWriterTag.Input) { - Attributes.Remove("value"); - Attributes.Add("value", value); + this.Attributes.Remove("value"); + this.Attributes.Add("value", value); } - SelectedValue = value; + this.SelectedValue = value; } } + public DnnComboBoxOption Options { get; set; } = new DnnComboBoxOption(); + protected override HtmlTextWriterTag TagKey { get { - return MultipleSelect || CheckBoxes ? HtmlTextWriterTag.Input : HtmlTextWriterTag.Select; + return this.MultipleSelect || this.CheckBoxes ? HtmlTextWriterTag.Input : HtmlTextWriterTag.Select; } } - public DnnComboBoxOption Options { get; set; } = new DnnComboBoxOption(); - - #endregion - - #region Override Methods - + public override void DataBind() + { + if (!string.IsNullOrEmpty(this._initValue)) + { + this.DataBind(this._initValue); + } + else + { + base.DataBind(); + } + } + + public void AddItem(string text, string value) + { + this.Items.Add(new ListItem(text, value)); + } + protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { var postData = postCollection[postDataKey]; if (!string.IsNullOrEmpty(postData)) { - _multipleValue = postData; + this._multipleValue = postData; } return base.LoadPostData(postDataKey, postCollection); @@ -111,7 +115,7 @@ protected override bool LoadPostData(string postDataKey, NameValueCollection pos protected override void RenderContents(HtmlTextWriter writer) { - if (TagKey == HtmlTextWriterTag.Select) + if (this.TagKey == HtmlTextWriterTag.Select) { base.RenderContents(writer); } @@ -121,111 +125,87 @@ protected override void OnPreRender(EventArgs e) { Utilities.ApplySkin(this); - if (TagKey == HtmlTextWriterTag.Input) + if (this.TagKey == HtmlTextWriterTag.Input) { - Options.Items = Items.Cast(); - Value = string.Join(",", Options.Items.Where(i => i.Selected).Select(i => i.Value)); + this.Options.Items = this.Items.Cast(); + this.Value = string.Join(",", this.Options.Items.Where(i => i.Selected).Select(i => i.Value)); } else { - if (Items.Cast().Any(i => string.IsNullOrEmpty(i.Value))) + if (this.Items.Cast().Any(i => string.IsNullOrEmpty(i.Value))) { - Options.AllowEmptyOption = true; + this.Options.AllowEmptyOption = true; } } - if (!Options.Localization.ContainsKey("ItemsChecked")) + if (!this.Options.Localization.ContainsKey("ItemsChecked")) { - Options.Localization.Add("ItemsChecked", Utilities.GetLocalizedString("ItemsCheckedString")); + this.Options.Localization.Add("ItemsChecked", Utilities.GetLocalizedString("ItemsCheckedString")); } - if (!Options.Localization.ContainsKey("AllItemsChecked")) + + if (!this.Options.Localization.ContainsKey("AllItemsChecked")) { - Options.Localization.Add("AllItemsChecked", Utilities.GetLocalizedString("AllItemsCheckedString")); + this.Options.Localization.Add("AllItemsChecked", Utilities.GetLocalizedString("AllItemsCheckedString")); } - Options.Checkbox = CheckBoxes; - Options.OnChangeEvent = OnClientSelectedIndexChanged; + this.Options.Checkbox = this.CheckBoxes; + this.Options.OnChangeEvent = this.OnClientSelectedIndexChanged; - RegisterRequestResources(); + this.RegisterRequestResources(); base.OnPreRender(e); } - public override void DataBind() - { - if (!string.IsNullOrEmpty(_initValue)) - { - DataBind(_initValue); - } - else - { - base.DataBind(); - } - } - - #endregion - - #region Public Methods - - public void AddItem(string text, string value) - { - Items.Add(new ListItem(text, value)); - } - public void InsertItem(int index, string text, string value) { - Items.Insert(index, new ListItem(text, value)); + this.Items.Insert(index, new ListItem(text, value)); } public void DataBind(string initialValue) { - DataBind(initialValue, false); + this.DataBind(initialValue, false); } public void DataBind(string initial, bool findByText) { base.DataBind(); - Select(initial, findByText); + this.Select(initial, findByText); } public void Select(string initial, bool findByText) { if (findByText) { - if (FindItemByText(initial, true) != null) + if (this.FindItemByText(initial, true) != null) { - FindItemByText(initial, true).Selected = true; + this.FindItemByText(initial, true).Selected = true; } } else { - if (FindItemByValue(initial, true) != null) + if (this.FindItemByValue(initial, true) != null) { - FindItemByValue(initial, true).Selected = true; + this.FindItemByValue(initial, true).Selected = true; } - } + } } public ListItem FindItemByText(string text, bool ignoreCase = false) { - return ignoreCase ? Items.FindByText(text) : Items.FindByTextWithIgnoreCase(text); + return ignoreCase ? this.Items.FindByText(text) : this.Items.FindByTextWithIgnoreCase(text); } public ListItem FindItemByValue(string value, bool ignoreCase = false) { - return ignoreCase ? Items.FindByValue(value) : Items.FindByValueWithIgnoreCase(value); + return ignoreCase ? this.Items.FindByValue(value) : this.Items.FindByValueWithIgnoreCase(value); } public int FindItemIndexByValue(string value) { - return Items.IndexOf(FindItemByValue(value)); - } - - #endregion - - #region Private Methods - + return this.Items.IndexOf(this.FindItemByValue(value)); + } + private void RegisterRequestResources() { JavaScript.RequestRegistration(CommonJs.DnnPlugins); @@ -240,23 +220,21 @@ private void RegisterRequestResources() var libraryPath = $"~/Resources/Libraries/{package.LibraryName}/{Globals.FormatVersion(package.Version, "00", 3, "_")}/"; - ClientResourceManager.RegisterScript(Page, $"{libraryPath}dnn.combobox.js"); - ClientResourceManager.RegisterStyleSheet(Page, $"{libraryPath}selectize.css"); - ClientResourceManager.RegisterStyleSheet(Page, $"{libraryPath}selectize.default.css"); + ClientResourceManager.RegisterScript(this.Page, $"{libraryPath}dnn.combobox.js"); + ClientResourceManager.RegisterStyleSheet(this.Page, $"{libraryPath}selectize.css"); + ClientResourceManager.RegisterStyleSheet(this.Page, $"{libraryPath}selectize.default.css"); - var options = JsonConvert.SerializeObject(Options, Formatting.None, + var options = JsonConvert.SerializeObject(this.Options, Formatting.None, new JsonSerializerSettings { - NullValueHandling = NullValueHandling.Ignore + NullValueHandling = NullValueHandling.Ignore, }); - var initScripts = $"$('#{ClientID}').dnnComboBox({options});"; + var initScripts = $"$('#{this.ClientID}').dnnComboBox({options});"; - ScriptManager.RegisterStartupScript(Page, Page.GetType(), $"{ClientID}Sctipts", initScripts, true); + ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), $"{this.ClientID}Sctipts", initScripts, true); } } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs index 637fc40e42a..5f1f1b64495 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs @@ -1,25 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls.Extensions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.Serialization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls.Extensions; + + /// /// This class is added only for internal use, please don't reference it in any other places as it may removed in future. /// [DataContract] @@ -64,14 +60,12 @@ public class DnnComboBoxOption [DataMember(Name = "options")] public IEnumerable Options { - get { return Items?.Select(i => new OptionItem {Text = i.Text, Value = i.Value, Selected = i.Selected}); } + get { return this.Items?.Select(i => new OptionItem { Text = i.Text, Value = i.Value, Selected = i.Selected }); } } [DataMember(Name = "localization")] - public IDictionary Localization { get; set; } = new Dictionary(); - - #region Events - + public IDictionary Localization { get; set; } = new Dictionary(); + [DataMember(Name = "render")] public RenderOption Render { get; set; } @@ -79,9 +73,7 @@ public IEnumerable Options public string Load { get; set; } [DataMember(Name = "onChange")] - public string OnChangeEvent { get; set; } - - #endregion + public string OnChangeEvent { get; set; } } [DataContract] @@ -96,7 +88,6 @@ public class OptionItem { public OptionItem() { - } [DataMember(Name = "text")] diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs index af39a98fe33..cc3cca1c93e 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs @@ -1,83 +1,81 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client.ClientResourceManagement; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnDatePicker : TextBox { - protected virtual string Format => "yyyy-MM-dd"; - protected virtual string ClientFormat => "YYYY-MM-DD"; - - public DateTime? SelectedDate { + public DateTime? SelectedDate + { get { DateTime value; - if (!string.IsNullOrEmpty(Text) && DateTime.TryParse(Text, out value)) + if (!string.IsNullOrEmpty(this.Text) && DateTime.TryParse(this.Text, out value)) { return value; } return null; } + set { - Text = value?.ToString(Format) ?? string.Empty; + this.Text = value?.ToString(this.Format) ?? string.Empty; } } public DateTime MinDate { get; set; } = new DateTime(1900, 1, 1); + + protected virtual string Format => "yyyy-MM-dd"; + + protected virtual string ClientFormat => "YYYY-MM-DD"; public DateTime MaxDate { get; set; } = DateTime.MaxValue; - - + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); JavaScript.RequestRegistration(CommonJs.jQuery); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/components/DatePicker/moment.min.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/components/DatePicker/pikaday.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/components/DatePicker/pikaday.jquery.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/DatePicker/moment.min.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/DatePicker/pikaday.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/DatePicker/pikaday.jquery.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/components/DatePicker/pikaday.css"); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/components/DatePicker/pikaday.css"); - RegisterClientResources(); + this.RegisterClientResources(); } protected virtual IDictionary GetSettings() { return new Dictionary { - {"minDate", MinDate > DateTime.MinValue ? $"$new Date('{MinDate.ToString(Format, CultureInfo.InvariantCulture)}')$" : ""}, - {"maxDate", MaxDate > DateTime.MinValue ? $"$new Date('{MaxDate.ToString(Format, CultureInfo.InvariantCulture)}')$" : ""}, - {"format", ClientFormat } + { "minDate", this.MinDate > DateTime.MinValue ? $"$new Date('{this.MinDate.ToString(this.Format, CultureInfo.InvariantCulture)}')$" : string.Empty }, + { "maxDate", this.MaxDate > DateTime.MinValue ? $"$new Date('{this.MaxDate.ToString(this.Format, CultureInfo.InvariantCulture)}')$" : string.Empty }, + { "format", this.ClientFormat }, }; - } + } private void RegisterClientResources() { - var settings = Json.Serialize(GetSettings()).Replace("\"$", "").Replace("$\"", ""); - var script = $"$('#{ClientID}').pikaday({settings});"; + var settings = Json.Serialize(this.GetSettings()).Replace("\"$", string.Empty).Replace("$\"", string.Empty); + var script = $"$('#{this.ClientID}').pikaday({settings});"; - ScriptManager.RegisterStartupScript(Page, Page.GetType(), "DnnDatePicker" + ClientID, script, true); + ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "DnnDatePicker" + this.ClientID, script, true); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs index 6fffc6e7bca..f6b7e13ef08 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs @@ -1,21 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System.Collections.Generic; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnDateTimePicker : DnnDatePicker { protected override string Format => "yyyy-MM-dd HH:mm:ss"; + protected override string ClientFormat => "YYYY-MM-DD HH:mm:ss"; protected override IDictionary GetSettings() diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs index c40851dcefa..84feff33b24 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs @@ -1,39 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Collections; + using System.Collections.Generic; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Web.UI.WebControls; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnFormComboBoxItem : DnnFormListItemBase { - //public DropDownList ComboBox { get; set; } + // public DropDownList ComboBox { get; set; } public DnnComboBox ComboBox { get; set; } - private void IndexChanged(object sender, EventArgs e) - { - UpdateDataSource(Value, ComboBox.SelectedValue, DataField); - } - - protected override void BindList() - { - BindListInternal(ComboBox, Value, ListSource, ListTextField, ListValueField); - } - - //internal static void BindListInternal(DropDownList comboBox, object value, IEnumerable listSource, string textField, string valueField) + // internal static void BindListInternal(DropDownList comboBox, object value, IEnumerable listSource, string textField, string valueField) internal static void BindListInternal(DnnComboBox comboBox, object value, IEnumerable listSource, string textField, string valueField) { if (comboBox != null) @@ -45,7 +31,7 @@ internal static void BindListInternal(DnnComboBox comboBox, object value, IEnume var items = listSource as Dictionary; foreach (var item in items) { - //comboBox.Items.Add(new ListItem(item.Key, item.Value)); + // comboBox.Items.Add(new ListItem(item.Key, item.Value)); comboBox.AddItem(item.Key, item.Value); } } @@ -58,27 +44,39 @@ internal static void BindListInternal(DnnComboBox comboBox, object value, IEnume comboBox.DataBind(); } - //Reset SelectedValue - //comboBox.Select(selectedValue); + // Reset SelectedValue + // comboBox.Select(selectedValue); var selectedItem = comboBox.FindItemByValue(selectedValue); - if (selectedItem != null) - selectedItem.Selected = true; + if (selectedItem != null) + { + selectedItem.Selected = true; + } } } + protected override void BindList() + { + BindListInternal(this.ComboBox, this.Value, this.ListSource, this.ListTextField, this.ListValueField); + } + protected override WebControl CreateControlInternal(Control container) { - //ComboBox = new DropDownList { ID = ID + "_ComboBox" }; - ComboBox = new DnnComboBox { ID = ID + "_ComboBox" }; - ComboBox.SelectedIndexChanged += IndexChanged; - container.Controls.Add(ComboBox); + // ComboBox = new DropDownList { ID = ID + "_ComboBox" }; + this.ComboBox = new DnnComboBox { ID = this.ID + "_ComboBox" }; + this.ComboBox.SelectedIndexChanged += this.IndexChanged; + container.Controls.Add(this.ComboBox); - if (ListSource != null) + if (this.ListSource != null) { - BindList(); + this.BindList(); } - return ComboBox; + return this.ComboBox; + } + + private void IndexChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this.ComboBox.SelectedValue, this.DataField); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs index 307debb1fd0..f9b507716d4 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs @@ -1,97 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Web.UI.WebControls; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnFormToggleButtonItem : DnnFormItemBase - { - #region CheckBoxMode enum - - public enum CheckBoxMode - { - TrueFalse = 0, - YN = 1, - YesNo = 2 - } - - #endregion - - //private DnnRadButton _checkBox; + { + // private DnnRadButton _checkBox; private CheckBox _checkBox; public DnnFormToggleButtonItem() { - Mode = CheckBoxMode.TrueFalse; + this.Mode = CheckBoxMode.TrueFalse; } + + public enum CheckBoxMode + { + TrueFalse = 0, + YN = 1, + YesNo = 2, + } public CheckBoxMode Mode { get; set; } - private void CheckedChanged(object sender, EventArgs e) - { - string newValue; - switch (Mode) - { - case CheckBoxMode.YN: - newValue = (_checkBox.Checked) ? "Y" : "N"; - break; - case CheckBoxMode.YesNo: - newValue = (_checkBox.Checked) ? "Yes" : "No"; - break; - default: - newValue = (_checkBox.Checked) ? "true" : "false"; - break; - } - UpdateDataSource(Value, newValue, DataField); - } - protected override WebControl CreateControlInternal(Control container) { - //_checkBox = new DnnRadButton {ID = ID + "_CheckBox", ButtonType = RadButtonType.ToggleButton, ToggleType = ButtonToggleType.CheckBox, AutoPostBack = false}; - _checkBox = new CheckBox{ ID = ID + "_CheckBox", AutoPostBack = false }; + // _checkBox = new DnnRadButton {ID = ID + "_CheckBox", ButtonType = RadButtonType.ToggleButton, ToggleType = ButtonToggleType.CheckBox, AutoPostBack = false}; + this._checkBox = new CheckBox { ID = this.ID + "_CheckBox", AutoPostBack = false }; - _checkBox.CheckedChanged += CheckedChanged; - container.Controls.Add(_checkBox); + this._checkBox.CheckedChanged += this.CheckedChanged; + container.Controls.Add(this._checkBox); - //Load from ControlState - if (!_checkBox.Page.IsPostBack) + // Load from ControlState + if (!this._checkBox.Page.IsPostBack) { } - switch (Mode) + + switch (this.Mode) { case CheckBoxMode.YN: case CheckBoxMode.YesNo: - var stringValue = Value as string; + var stringValue = this.Value as string; if (stringValue != null) { - _checkBox.Checked = stringValue.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase); + this._checkBox.Checked = stringValue.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase); } + break; default: - _checkBox.Checked = Convert.ToBoolean(Value); + this._checkBox.Checked = Convert.ToBoolean(this.Value); break; } - return _checkBox; + return this._checkBox; } protected override void OnInit(EventArgs e) { base.OnInit(e); - FormMode = DnnFormMode.Short; + this.FormMode = DnnFormMode.Short; + } + + private void CheckedChanged(object sender, EventArgs e) + { + string newValue; + switch (this.Mode) + { + case CheckBoxMode.YN: + newValue = this._checkBox.Checked ? "Y" : "N"; + break; + case CheckBoxMode.YesNo: + newValue = this._checkBox.Checked ? "Yes" : "No"; + break; + default: + newValue = this._checkBox.Checked ? "true" : "false"; + break; + } + + this.UpdateDataSource(this.Value, newValue, this.DataField); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs index e9d1966c051..b8e43387f48 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs @@ -1,24 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; -using DotNetNuke.Framework.JavaScriptLibraries; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework.JavaScriptLibraries; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnGrid : GridView - { - #region public properties - + { public int ScreenRowNumber { get; set; } public int RowHeight { get; set; } @@ -27,19 +21,20 @@ public int CurrentPageIndex { get { - return PageIndex; - + return this.PageIndex; } - set { PageIndex = value; } + + set { this.PageIndex = value; } } - public TableItemStyle ItemStyle => RowStyle; - public TableItemStyle AlternatingItemStyle => AlternatingRowStyle; - public TableItemStyle EditItemStyle => EditRowStyle; - public TableItemStyle SelectedItemStyle => SelectedRowStyle; - - - #endregion + public TableItemStyle ItemStyle => this.RowStyle; + + public TableItemStyle AlternatingItemStyle => this.AlternatingRowStyle; + + public TableItemStyle EditItemStyle => this.EditRowStyle; + + public TableItemStyle SelectedItemStyle => this.SelectedRowStyle; + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -53,8 +48,8 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - AlternatingRowStyle.CssClass = "alter-row"; - Style.Remove("border-collapse"); + this.AlternatingRowStyle.CssClass = "alter-row"; + this.Style.Remove("border-collapse"); } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs index ae99be6da06..8f20367a1df 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs @@ -1,20 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System.Web.UI.WebControls; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnGridBoundColumn : BoundField { - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs index c616cd7c222..8fde5a21b93 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs @@ -1,20 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System.Web.UI.WebControls; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnGridTemplateColumn : TemplateField { - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs index ea21f7f6d79..cb15f0e3056 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs @@ -1,46 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Installer.Packages; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnModuleComboBox : DnnComboBox { - private const string DefaultExtensionImage = "icon_extensions_32px.png"; - - #region Public Events - - public event EventHandler ItemChanged; - - #endregion - - #region Public Properties - + private const string DefaultExtensionImage = "icon_extensions_32px.png"; + + private DnnComboBox _moduleCombo; + private string _originalValue; + + public event EventHandler ItemChanged; + public Func, bool> Filter { get; set; } public int ItemCount { get { - return _moduleCombo.Items.Count; + return this._moduleCombo.Items.Count; } } @@ -48,7 +41,7 @@ public override string SelectedValue { get { - return _moduleCombo.SelectedValue; + return this._moduleCombo.SelectedValue; } } @@ -56,43 +49,52 @@ public string RadComboBoxClientId { get { - return _moduleCombo.ClientID; + return this._moduleCombo.ClientID; } } - public override bool Enabled { + public override bool Enabled + { get { - return _moduleCombo.Enabled; + return this._moduleCombo.Enabled; } + set { - _moduleCombo.Enabled = value; + this._moduleCombo.Enabled = value; } + } + + public void BindAllPortalDesktopModules() + { + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = this.GetPortalDesktopModules(); + this._moduleCombo.DataBind(); + this.BindPortalDesktopModuleImages(); } - #endregion - - #region Private Methods - - private Dictionary GetPortalDesktopModules() + public void BindTabModulesByTabID(int tabID) { - IOrderedEnumerable> portalModulesList; - if (Filter == null) - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || String.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) - .OrderBy(c => c.Key); - } - else - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where(Filter) - .OrderBy(c => c.Key); - } + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = GetTabModules(tabID); + this._moduleCombo.DataBind(); + this.BindTabModuleImages(tabID); + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this._moduleCombo = new DnnComboBox(); + this._moduleCombo.DataValueField = "key"; + this._moduleCombo.DataTextField = "value"; + this.Controls.Add(this._moduleCombo); + } - return portalModulesList.ToDictionary(portalModule => portalModule.Value.DesktopModuleID, - portalModule => portalModule.Key); + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this._originalValue = this.SelectedValue; } private static Dictionary GetTabModules(int tabID) @@ -118,22 +120,43 @@ private static bool ModuleSuportsSharing(ModuleInfo moduleInfo) return false; } } + + private Dictionary GetPortalDesktopModules() + { + IOrderedEnumerable> portalModulesList; + if (this.Filter == null) + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || string.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) + .OrderBy(c => c.Key); + } + else + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where(this.Filter) + .OrderBy(c => c.Key); + } + + return portalModulesList.ToDictionary( + portalModule => portalModule.Value.DesktopModuleID, + portalModule => portalModule.Key); + } private void BindPortalDesktopModuleImages() { var portalDesktopModules = DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId); var packages = PackageController.Instance.GetExtensionPackages(PortalSettings.Current.PortalId); - //foreach (var item in _moduleCombo.Items) - //{ + // foreach (var item in _moduleCombo.Items) + // { // string imageUrl = // (from pkgs in packages // join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.PackageID // where portMods.Value.DesktopModuleID.ToString() == item.Value // select pkgs.IconFile).FirstOrDefault(); - // item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; - //} + // item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; + // } } private void BindTabModuleImages(int tabID) @@ -143,8 +166,8 @@ private void BindTabModuleImages(int tabID) var moduleDefnitions = ModuleDefinitionController.GetModuleDefinitions(); var packages = PackageController.Instance.GetExtensionPackages(PortalSettings.Current.PortalId); - //foreach (RadComboBoxItem item in _moduleCombo.Items) - //{ + // foreach (RadComboBoxItem item in _moduleCombo.Items) + // { // string imageUrl = (from pkgs in packages // join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.PackageID // join modDefs in moduleDefnitions on portMods.Value.DesktopModuleID equals modDefs.Value.DesktopModuleID @@ -152,76 +175,32 @@ private void BindTabModuleImages(int tabID) // where tabMods.Value.ModuleID.ToString() == item.Value // select pkgs.IconFile).FirstOrDefault(); - // item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; - //} - } - - #endregion - - #region Protected Methods - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - _moduleCombo = new DnnComboBox(); - _moduleCombo.DataValueField = "key"; - _moduleCombo.DataTextField = "value"; - Controls.Add(_moduleCombo); - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - _originalValue = SelectedValue; - } + // item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; + // } + } protected virtual void OnItemChanged() { - if (ItemChanged != null) + if (this.ItemChanged != null) { - ItemChanged(this, new EventArgs()); + this.ItemChanged(this, new EventArgs()); } } protected override void OnPreRender(EventArgs e) { - if (_moduleCombo.FindItemByValue(_originalValue) != null) + if (this._moduleCombo.FindItemByValue(this._originalValue) != null) { - _moduleCombo.FindItemByValue(_originalValue).Selected = true; + this._moduleCombo.FindItemByValue(this._originalValue).Selected = true; } - _moduleCombo.Width = Width; + this._moduleCombo.Width = this.Width; base.OnPreRender(e); - } - - #endregion - - #region Public Methods - - public void BindAllPortalDesktopModules() - { - _moduleCombo.SelectedValue = null; - _moduleCombo.DataSource = GetPortalDesktopModules(); - _moduleCombo.DataBind(); - BindPortalDesktopModuleImages(); - } - - public void BindTabModulesByTabID(int tabID) - { - _moduleCombo.SelectedValue = null; - _moduleCombo.DataSource = GetTabModules(tabID); - _moduleCombo.DataBind(); - BindTabModuleImages(tabID); - } + } public void SetModule(string code) { - _moduleCombo.SelectedIndex = _moduleCombo.FindItemIndexByValue(code); - } - - #endregion - - private DnnComboBox _moduleCombo; - private string _originalValue; + this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnScriptBlock.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnScriptBlock.cs index 51d9de69a02..57f7472bb12 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnScriptBlock.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnScriptBlock.cs @@ -1,30 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System.IO; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnScriptBlock : Control { protected override void Render(HtmlTextWriter writer) { - if (!DesignMode) + if (!this.DesignMode) { - ScriptManager scriptManager = AJAX.GetScriptManager(Page); + ScriptManager scriptManager = AJAX.GetScriptManager(this.Page); if (scriptManager.IsInAsyncPostBack) { StringBuilder scriBuilder = new StringBuilder(); base.Render(new HtmlTextWriter(new StringWriter(scriBuilder))); - ScriptManager.RegisterClientScriptBlock(Page, typeof (Page), this.UniqueID, scriBuilder.ToString(), + ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), this.UniqueID, scriBuilder.ToString(), false); } else diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs index c60c53301f5..85703c9435c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs @@ -1,27 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Linq; -using System.Web.UI; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.UI.Skins; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Collections; + using System.Linq; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.UI.Skins; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// [ToolboxData("<{0}:DnnSkinComboBox runat='server'>")] public class DnnSkinComboBox : DnnComboBox - { - #region Public Properties - + { + public DnnSkinComboBox() + { + this.PortalId = Null.NullInteger; + } + public int PortalId { get; set; } public string RootPath { get; set; } @@ -30,75 +34,54 @@ public class DnnSkinComboBox : DnnComboBox public bool IncludeNoneSpecificItem { get; set; } - public string NoneSpecificText { get; set; } - - #endregion - - #region Private Properties - + public string NoneSpecificText { get; set; } + private PortalInfo Portal { - get { return PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(PortalId); } - } - - #endregion - - #region Constructors - - public DnnSkinComboBox() - { - PortalId = Null.NullInteger; - } - - #endregion - - #region Event Handlers - + get { return this.PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(this.PortalId); } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - DataTextField = "Key"; - DataValueField = "Value"; + this.DataTextField = "Key"; + this.DataValueField = "Value"; - if (!Page.IsPostBack && !string.IsNullOrEmpty(RootPath)) + if (!this.Page.IsPostBack && !string.IsNullOrEmpty(this.RootPath)) { - DataSource = SkinController.GetSkins(Portal, RootPath, Scope) + this.DataSource = SkinController.GetSkins(this.Portal, this.RootPath, this.Scope) .ToDictionary(skin => skin.Key, skin => skin.Value); - if (string.IsNullOrEmpty(SelectedValue)) + if (string.IsNullOrEmpty(this.SelectedValue)) { - DataBind(); + this.DataBind(); } else { - DataBind(SelectedValue); + this.DataBind(this.SelectedValue); } - if (IncludeNoneSpecificItem) + if (this.IncludeNoneSpecificItem) { - InsertItem(0, NoneSpecificText, string.Empty); + this.InsertItem(0, this.NoneSpecificText, string.Empty); } } - AttachEvents(); + this.AttachEvents(); } protected override void PerformDataBinding(IEnumerable dataSource) { - //do not select item during data binding, item will select later - var selectedValue = SelectedValue; - SelectedValue = null; + // do not select item during data binding, item will select later + var selectedValue = this.SelectedValue; + this.SelectedValue = null; base.PerformDataBinding(dataSource); - SelectedValue = selectedValue; - } - - #endregion - - #region Private Methods - + this.SelectedValue = selectedValue; + } + private void AttachEvents() { if (!UserController.Instance.GetCurrentUserInfo().IsSuperUser) @@ -106,39 +89,37 @@ private void AttachEvents() return; } - Attributes.Add("PortalPath", Portal != null ? Portal.HomeDirectory : string.Empty); - Attributes.Add("HostPath", Globals.HostPath); + this.Attributes.Add("PortalPath", this.Portal != null ? this.Portal.HomeDirectory : string.Empty); + this.Attributes.Add("HostPath", Globals.HostPath); - //OnClientSelectedIndexChanged = "selectedIndexChangedMethod"; + // OnClientSelectedIndexChanged = "selectedIndexChangedMethod"; var indexChangedMethod = @"function selectedIndexChangedMethod(sender, eventArgs){ var value = eventArgs.get_item().get_value(); value = value.replace('[L]', sender.get_attributes().getAttribute('PortalPath')); value = value.replace('[G]', sender.get_attributes().getAttribute('HostPath')); sender.get_inputDomElement().title = value; }"; - Page.ClientScript.RegisterClientScriptBlock(GetType(), "OnClientSelectedIndexChanged", indexChangedMethod, true); + this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnClientSelectedIndexChanged", indexChangedMethod, true); - //foreach (var item in Items) - //{ + // foreach (var item in Items) + // { // if (string.IsNullOrEmpty(item.Value)) // { // continue; // } - // var tooltip = item.Value.Replace("[G]", Globals.HostPath); + // var tooltip = item.Value.Replace("[G]", Globals.HostPath); // if (Portal != null) // { // tooltip = tooltip.Replace("[L]", Portal.HomeDirectory); // } - // item.ToolTip = tooltip; + // item.ToolTip = tooltip; // if (item.Value.Equals(SelectedValue)) // { // ToolTip = tooltip; // } - //} - } - - #endregion + // } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs index 918540108aa..46b0549d2b1 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Data.SqlTypes; -using System.Globalization; -using System.Web.UI; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls { + using System; + using System.Collections.Specialized; + using System.Data.SqlTypes; + using System.Globalization; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- /// /// The DateEditControl control provides a standard UI component for editing @@ -29,16 +25,36 @@ namespace DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls [ToolboxData("<{0}:DateEditControl runat=server>")] public class DateEditControl : EditControl { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DateEditControl)); - private DnnDatePicker _dateControl; - - #region Protected Properties + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); + private DnnDatePicker _dateControl; + + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + public override string EditControlClientId + { + get + { + this.EnsureChildControls(); + return this.DateControl.ClientID; + } + } + /// ----------------------------------------------------------------------------- /// - /// DateValue returns the Date representation of the Value + /// Gets dateValue returns the Date representation of the Value. /// - /// A Date representing the Value + /// A Date representing the Value. /// ----------------------------------------------------------------------------- protected DateTime DateValue { @@ -47,25 +63,25 @@ protected DateTime DateValue DateTime dteValue = Null.NullDate; try { - var dteString = Convert.ToString(Value); + var dteString = Convert.ToString(this.Value); DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); } catch (Exception exc) { Logger.Error(exc); - } + return dteValue; } } /// ----------------------------------------------------------------------------- /// - /// DefaultDateFormat is a string that will be used to format the date in the absence of a - /// FormatAttribute + /// Gets defaultDateFormat is a string that will be used to format the date in the absence of a + /// FormatAttribute. /// - /// A String representing the default format to use to render the date - /// A Format String + /// A String representing the default format to use to render the date. + /// A Format String. /// ----------------------------------------------------------------------------- protected virtual string DefaultFormat { @@ -77,37 +93,38 @@ protected virtual string DefaultFormat /// ----------------------------------------------------------------------------- /// - /// Format is a string that will be used to format the date in View mode + /// Gets format is a string that will be used to format the date in View mode. /// - /// A String representing the format to use to render the date - /// A Format String + /// A String representing the format to use to render the date. + /// A Format String. /// ----------------------------------------------------------------------------- protected virtual string Format { get { - string _Format = DefaultFormat; - if (CustomAttributes != null) + string _Format = this.DefaultFormat; + if (this.CustomAttributes != null) { - foreach (Attribute attribute in CustomAttributes) + foreach (Attribute attribute in this.CustomAttributes) { if (attribute is FormatAttribute) { - var formatAtt = (FormatAttribute) attribute; + var formatAtt = (FormatAttribute)attribute; _Format = formatAtt.Format; break; } } } + return _Format; } } /// ----------------------------------------------------------------------------- /// - /// OldDateValue returns the Date representation of the OldValue + /// Gets oldDateValue returns the Date representation of the OldValue. /// - /// A Date representing the OldValue + /// A Date representing the OldValue. /// ----------------------------------------------------------------------------- protected DateTime OldDateValue { @@ -116,8 +133,8 @@ protected DateTime OldDateValue DateTime dteValue = Null.NullDate; try { - //Try and cast the value to an DateTime - var dteString = OldValue as string; + // Try and cast the value to an DateTime + var dteString = this.OldValue as string; if (!string.IsNullOrEmpty(dteString)) { dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture); @@ -126,129 +143,99 @@ protected DateTime OldDateValue catch (Exception exc) { Logger.Error(exc); - } + return dteValue; } } /// - /// The Value expressed as a String + /// Gets or sets the Value expressed as a String. /// protected override string StringValue { get { string _StringValue = Null.NullString; - if ((DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && DateValue != Null.NullDate)) + if (this.DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && this.DateValue != Null.NullDate) { - _StringValue = DateValue.ToString(Format); + _StringValue = this.DateValue.ToString(this.Format); } + return _StringValue; } + set { - Value = DateTime.Parse(value); + this.Value = DateTime.Parse(value); } - } - - #endregion - - #region Override Properties - - public override string ID - { - get - { - return base.ID + "_control"; - } - set - { - base.ID = value; - } - } - - public override string EditControlClientId + } + + private DnnDatePicker DateControl { get { - EnsureChildControls(); - return DateControl.ClientID; - - } - } - - #endregion - - #region Private Properties - - private DnnDatePicker DateControl - { - get - { - if (_dateControl == null) - { - _dateControl = new DnnDatePicker(); - } - - return _dateControl; - } - } - - #endregion - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - - DateControl.ControlStyle.CopyFrom(ControlStyle); - DateControl.ID = base.ID + "_control"; - - Controls.Add(DateControl); - } + if (this._dateControl == null) + { + this._dateControl = new DnnDatePicker(); + } - protected virtual void LoadDateControls() - { - if (DateValue != Null.NullDate) - { - DateControl.SelectedDate = DateValue.Date; + return this._dateControl; } - } + } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { - EnsureChildControls(); + this.EnsureChildControls(); bool dataChanged = false; - string presentValue = StringValue; - string postedValue = postCollection[postDataKey + "_control"]; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_control"]; if (!presentValue.Equals(postedValue)) { if (string.IsNullOrEmpty(postedValue)) { - Value = Null.NullDate; + this.Value = Null.NullDate; dataChanged = true; } else { - Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); + this.Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); dataChanged = true; } } - LoadDateControls(); + + this.LoadDateControls(); return dataChanged; } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; + + this.Controls.Add(this.DateControl); + } + + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue.Date; + } + } /// - /// OnDataChanged is called by the PostBack Handler when the Data has changed + /// OnDataChanged is called by the PostBack Handler when the Data has changed. /// - /// An EventArgs object + /// An EventArgs object. protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = DateValue; - args.OldValue = OldDateValue; - args.StringValue = DateValue.ToString(CultureInfo.InvariantCulture); + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.DateValue; + args.OldValue = this.OldDateValue; + args.StringValue = this.DateValue.ToString(CultureInfo.InvariantCulture); base.OnValueChanged(args); } @@ -256,34 +243,34 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - LoadDateControls(); + this.LoadDateControls(); - if (Page != null && EditMode == PropertyEditorMode.Edit) + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } /// - /// RenderEditMode is called by the base control to render the control in Edit Mode + /// RenderEditMode is called by the base control to render the control in Edit Mode. /// /// protected override void RenderEditMode(HtmlTextWriter writer) { - RenderChildren(writer); + this.RenderChildren(writer); } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderViewMode(HtmlTextWriter writer) { - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(StringValue); + writer.Write(this.StringValue); writer.RenderEndTag(); } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs index 0bc4b3f0804..a3d7debca7f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Data.SqlTypes; -using System.Globalization; -using System.Web.UI; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls { + using System; + using System.Collections.Specialized; + using System.Data.SqlTypes; + using System.Globalization; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -31,258 +27,251 @@ namespace DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls /// /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:DateTimeEditControl runat=server>")] - public class DateTimeEditControl : EditControl - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); - private DnnDateTimePicker _dateControl; - - #region "Protected Properties" - - /// ----------------------------------------------------------------------------- - /// - /// DateValue returns the Date representation of the Value - /// - /// A Date representing the Value - /// ----------------------------------------------------------------------------- - protected DateTime DateValue - { - get - { - DateTime dteValue = Null.NullDate; - try - { - var dteString = Convert.ToString(Value); - DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); - } - catch (Exception exc) - { - Logger.Error(exc); - - } - return dteValue; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// DefaultDateFormat is a string that will be used to format the date in the absence of a - /// FormatAttribute - /// - /// A String representing the default format to use to render the date - /// A Format String - /// ----------------------------------------------------------------------------- - protected virtual string DefaultFormat - { - get - { - return "g"; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Format is a string that will be used to format the date in View mode - /// - /// A String representing the format to use to render the date - /// A Format String - /// ----------------------------------------------------------------------------- - protected virtual string Format - { - get - { - string _Format = DefaultFormat; - if (CustomAttributes != null) - { - foreach (Attribute attribute in CustomAttributes) - { - if (attribute is FormatAttribute) - { - var formatAtt = (FormatAttribute)attribute; - _Format = formatAtt.Format; - break; - } - } - } - return _Format; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// OldDateValue returns the Date representation of the OldValue - /// - /// A Date representing the OldValue - /// ----------------------------------------------------------------------------- - protected DateTime OldDateValue - { - get - { - DateTime dteValue = Null.NullDate; - try - { - //Try and cast the value to an DateTime - var dteString = OldValue as string; - if (!string.IsNullOrEmpty(dteString)) - { - dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture); - } - } - catch (Exception exc) - { - Logger.Error(exc); - - } - return dteValue; - } - } - - /// - /// The Value expressed as a String - /// - protected override string StringValue - { - get - { - string _StringValue = Null.NullString; - if ((DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && DateValue != Null.NullDate)) - { - _StringValue = DateValue.ToString(Format); - } - return _StringValue; - } - set - { - Value = DateTime.Parse(value); - } - } - - #endregion - - #region Override Properties - - public override string ID - { - get - { - return base.ID + "_control"; - } - set - { - base.ID = value; - } - } - - #endregion + public class DateTimeEditControl : EditControl + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); + private DnnDateTimePicker _dateControl; + + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets dateValue returns the Date representation of the Value. + /// + /// A Date representing the Value. + /// ----------------------------------------------------------------------------- + protected DateTime DateValue + { + get + { + DateTime dteValue = Null.NullDate; + try + { + var dteString = Convert.ToString(this.Value); + DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); + } + catch (Exception exc) + { + Logger.Error(exc); + } + + return dteValue; + } + } - #region Private Properties + /// ----------------------------------------------------------------------------- + /// + /// Gets defaultDateFormat is a string that will be used to format the date in the absence of a + /// FormatAttribute. + /// + /// A String representing the default format to use to render the date. + /// A Format String. + /// ----------------------------------------------------------------------------- + protected virtual string DefaultFormat + { + get + { + return "g"; + } + } - private DnnDateTimePicker DateControl - { - get - { - if (_dateControl == null) - { - _dateControl = new DnnDateTimePicker(); - } + /// ----------------------------------------------------------------------------- + /// + /// Gets format is a string that will be used to format the date in View mode. + /// + /// A String representing the format to use to render the date. + /// A Format String. + /// ----------------------------------------------------------------------------- + protected virtual string Format + { + get + { + string _Format = this.DefaultFormat; + if (this.CustomAttributes != null) + { + foreach (Attribute attribute in this.CustomAttributes) + { + if (attribute is FormatAttribute) + { + var formatAtt = (FormatAttribute)attribute; + _Format = formatAtt.Format; + break; + } + } + } + + return _Format; + } + } - return _dateControl; - } - } + /// ----------------------------------------------------------------------------- + /// + /// Gets oldDateValue returns the Date representation of the OldValue. + /// + /// A Date representing the OldValue. + /// ----------------------------------------------------------------------------- + protected DateTime OldDateValue + { + get + { + DateTime dteValue = Null.NullDate; + try + { + // Try and cast the value to an DateTime + var dteString = this.OldValue as string; + if (!string.IsNullOrEmpty(dteString)) + { + dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture); + } + } + catch (Exception exc) + { + Logger.Error(exc); + } + + return dteValue; + } + } - #endregion + /// + /// Gets or sets the Value expressed as a String. + /// + protected override string StringValue + { + get + { + string _StringValue = Null.NullString; + if (this.DateValue.ToUniversalTime().Date != (DateTime)SqlDateTime.MinValue && this.DateValue != Null.NullDate) + { + _StringValue = this.DateValue.ToString(this.Format); + } + + return _StringValue; + } + + set + { + this.Value = DateTime.Parse(value); + } + } + + private DnnDateTimePicker DateControl + { + get + { + if (this._dateControl == null) + { + this._dateControl = new DnnDateTimePicker(); + } - protected override void CreateChildControls() - { - base.CreateChildControls(); + return this._dateControl; + } + } - DateControl.ControlStyle.CopyFrom(ControlStyle); - DateControl.ID = base.ID + "_control"; + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + this.EnsureChildControls(); + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_control"]; + if (!presentValue.Equals(postedValue)) + { + if (string.IsNullOrEmpty(postedValue)) + { + this.Value = Null.NullDate; + dataChanged = true; + } + else + { + DateTime value; + if (DateTime.TryParseExact(postedValue, "yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture, + DateTimeStyles.None, out value)) + { + this.Value = value; + dataChanged = true; + } + } + } + + this.LoadDateControls(); + return dataChanged; + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); - Controls.Add(DateControl); - } + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; - protected virtual void LoadDateControls() - { - if (DateValue != Null.NullDate) - { - DateControl.SelectedDate = DateValue; - } - } + this.Controls.Add(this.DateControl); + } - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - EnsureChildControls(); - bool dataChanged = false; - string presentValue = StringValue; - string postedValue = postCollection[postDataKey + "_control"]; - if (!presentValue.Equals(postedValue)) - { - if (string.IsNullOrEmpty(postedValue)) - { - Value = Null.NullDate; - dataChanged = true; - } - else - { - DateTime value; - if (DateTime.TryParseExact(postedValue, "yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture, - DateTimeStyles.None, out value)) - { - Value = value; - dataChanged = true; - } - } - } - LoadDateControls(); - return dataChanged; - } + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue; + } + } - /// - /// OnDataChanged is called by the PostBack Handler when the Data has changed - /// - /// An EventArgs object - protected override void OnDataChanged(EventArgs e) - { - var args = new PropertyEditorEventArgs(Name); - args.Value = DateValue; - args.OldValue = OldDateValue; - args.StringValue = DateValue.ToString(CultureInfo.InvariantCulture); - base.OnValueChanged(args); - } + /// + /// OnDataChanged is called by the PostBack Handler when the Data has changed. + /// + /// An EventArgs object. + protected override void OnDataChanged(EventArgs e) + { + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.DateValue; + args.OldValue = this.OldDateValue; + args.StringValue = this.DateValue.ToString(CultureInfo.InvariantCulture); + base.OnValueChanged(args); + } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); - LoadDateControls(); + this.LoadDateControls(); - if (Page != null && EditMode == PropertyEditorMode.Edit) - { - Page.RegisterRequiresPostBack(this); - } - } + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) + { + this.Page.RegisterRequiresPostBack(this); + } + } - /// - /// RenderEditMode is called by the base control to render the control in Edit Mode - /// - /// - protected override void RenderEditMode(HtmlTextWriter writer) - { - RenderChildren(writer); - } + /// + /// RenderEditMode is called by the base control to render the control in Edit Mode. + /// + /// + protected override void RenderEditMode(HtmlTextWriter writer) + { + this.RenderChildren(writer); + } - /// ----------------------------------------------------------------------------- - /// - /// RenderViewMode renders the View (readonly) mode of the control - /// - /// A HtmlTextWriter. - /// ----------------------------------------------------------------------------- - protected override void RenderViewMode(HtmlTextWriter writer) - { - ControlStyle.AddAttributesToRender(writer); - writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(StringValue); - writer.RenderEndTag(); - } - } + /// ----------------------------------------------------------------------------- + /// + /// RenderViewMode renders the View (readonly) mode of the control. + /// + /// A HtmlTextWriter. + /// ----------------------------------------------------------------------------- + protected override void RenderViewMode(HtmlTextWriter writer) + { + this.ControlStyle.AddAttributesToRender(writer); + writer.RenderBeginTag(HtmlTextWriterTag.Span); + writer.Write(this.StringValue); + writer.RenderEndTag(); + } + } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs index 5f443cccefd..2379701fcd5 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.UI.WebControls; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls.Internal { - /// + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client.ClientResourceManagement; + + using Globals = DotNetNuke.Common.Globals; + + /// /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class TermsSelector : DnnComboBox - { - #region Public Properties - + { public int PortalId { get; set; } public bool IncludeSystemVocabularies { get; set; } = false; @@ -36,11 +31,11 @@ public List Terms get { var terms = new List(); - if (!string.IsNullOrEmpty(Value)) + if (!string.IsNullOrEmpty(this.Value)) { var termRep = Util.GetTermController(); - var termIds = Value.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries); + var termIds = this.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var i in termIds) { if (!string.IsNullOrEmpty(i.Trim())) @@ -57,46 +52,43 @@ public List Terms return terms; } + set { - Value = string.Join(",", value.Select(t => t.TermId.ToString())); + this.Value = string.Join(",", value.Select(t => t.TermId.ToString())); - Items.Clear(); - value.Select(t => new ListItem(t.Name, t.TermId.ToString()) {Selected = true}).ToList().ForEach(Items.Add); + this.Items.Clear(); + value.Select(t => new ListItem(t.Name, t.TermId.ToString()) { Selected = true }).ToList().ForEach(this.Items.Add); } } - public override bool MultipleSelect { get; set; } = true; - - #endregion - - #region Protected Methods - + public override bool MultipleSelect { get; set; } = true; + protected override void OnInit(EventArgs e) { base.OnInit(e); - if (!string.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - CssClass = string.Format("{0} TermsSelector", CssClass); + this.CssClass = string.Format("{0} TermsSelector", this.CssClass); } else { - CssClass = "TermsSelector"; + this.CssClass = "TermsSelector"; } - var includeSystem = IncludeSystemVocabularies.ToString().ToLowerInvariant(); - var includeTags = IncludeTags.ToString().ToLowerInvariant(); + var includeSystem = this.IncludeSystemVocabularies.ToString().ToLowerInvariant(); + var includeTags = this.IncludeTags.ToString().ToLowerInvariant(); var apiPath = Globals.ResolveUrl($"~/API/InternalServices/ItemListService/GetTerms?includeSystem={includeSystem}&includeTags={includeTags}&q="); - Options.Preload = "focus"; - Options.Plugins.Add("remove_button"); - Options.Render = new RenderOption - { - Option = "function(item, escape) {return '
' + item.text + '
';}" - }; + this.Options.Preload = "focus"; + this.Options.Plugins.Add("remove_button"); + this.Options.Render = new RenderOption + { + Option = "function(item, escape) {return '
' + item.text + '
';}", + }; - Options.Load = $@"function(query, callback) {{ + this.Options.Load = $@"function(query, callback) {{ $.ajax({{ url: '{apiPath}' + encodeURIComponent(query), type: 'GET', @@ -109,13 +101,6 @@ protected override void OnInit(EventArgs e) }}); }} "; - } - - #endregion - - #region Private Methods - - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListOptions.cs index 0580fe11156..4325196ff77 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListOptions.cs @@ -1,19 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Services.Localization; + [DataContract] public class ItemListOptions { - [DataMember(Name = "sortAscendingButtonTitle")] public string SortAscendingButtonTitle; @@ -56,18 +55,17 @@ public class ItemListOptions public ItemListOptions() { // all the resources are located under the Website\App_GlobalResources\SharedResources.resx - SortAscendingButtonTitle = Localization.GetString("DropDownList.SortAscendingButtonTitle", Localization.SharedResourceFile); - UnsortedOrderButtonTooltip = Localization.GetString("DropDownList.UnsortedOrderButtonTooltip", Localization.SharedResourceFile); - SortAscendingButtonTooltip = Localization.GetString("DropDownList.SortAscendingButtonTooltip", Localization.SharedResourceFile); - SortDescendingButtonTooltip = Localization.GetString("DropDownList.SortDescendingButtonTooltip", Localization.SharedResourceFile); - SelectedItemExpandTooltip = Localization.GetString("DropDownList.SelectedItemExpandTooltip", Localization.SharedResourceFile); - SelectedItemCollapseTooltip = Localization.GetString("DropDownList.SelectedItemCollapseTooltip", Localization.SharedResourceFile); - SearchInputPlaceHolder = Localization.GetString("DropDownList.SearchInputPlaceHolder", Localization.SharedResourceFile); - ClearButtonTooltip = Localization.GetString("DropDownList.ClearButtonTooltip", Localization.SharedResourceFile); - SearchButtonTooltip = Localization.GetString("DropDownList.SearchButtonTooltip", Localization.SharedResourceFile); - LoadingResultText = Localization.GetString("DropDownList.LoadingResultText", Localization.SharedResourceFile); - ResultsText = Localization.GetString("DropDownList.Results", Localization.SharedResourceFile); + this.SortAscendingButtonTitle = Localization.GetString("DropDownList.SortAscendingButtonTitle", Localization.SharedResourceFile); + this.UnsortedOrderButtonTooltip = Localization.GetString("DropDownList.UnsortedOrderButtonTooltip", Localization.SharedResourceFile); + this.SortAscendingButtonTooltip = Localization.GetString("DropDownList.SortAscendingButtonTooltip", Localization.SharedResourceFile); + this.SortDescendingButtonTooltip = Localization.GetString("DropDownList.SortDescendingButtonTooltip", Localization.SharedResourceFile); + this.SelectedItemExpandTooltip = Localization.GetString("DropDownList.SelectedItemExpandTooltip", Localization.SharedResourceFile); + this.SelectedItemCollapseTooltip = Localization.GetString("DropDownList.SelectedItemCollapseTooltip", Localization.SharedResourceFile); + this.SearchInputPlaceHolder = Localization.GetString("DropDownList.SearchInputPlaceHolder", Localization.SharedResourceFile); + this.ClearButtonTooltip = Localization.GetString("DropDownList.ClearButtonTooltip", Localization.SharedResourceFile); + this.SearchButtonTooltip = Localization.GetString("DropDownList.SearchButtonTooltip", Localization.SharedResourceFile); + this.LoadingResultText = Localization.GetString("DropDownList.LoadingResultText", Localization.SharedResourceFile); + this.ResultsText = Localization.GetString("DropDownList.Results", Localization.SharedResourceFile); } - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs index b4cb5f90ba6..24c428d5839 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs @@ -1,16 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System.Collections.Generic; + using System.Runtime.Serialization; + [DataContract] public class ItemListServicesOptions { - [DataMember(Name = "moduleId")] public string ModuleId = string.Empty; @@ -32,6 +31,9 @@ public class ItemListServicesOptions [DataMember(Name = "getTreeWithNodeMethod")] public string GetTreeWithNodeMethod; + [DataMember(Name = "rootId")] + public string RootId = "Root"; // should not be (-1), as (-1) can be treated as Null.Integer + private Dictionary _parameters; [DataMember(Name = "parameters")] @@ -39,12 +41,8 @@ public Dictionary Parameters { get { - return _parameters ?? (_parameters = new Dictionary()); + return this._parameters ?? (this._parameters = new Dictionary()); } } - - [DataMember(Name = "rootId")] - public string RootId = "Root"; // should not be (-1), as (-1) can be treated as Null.Integer - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/RibbonBarToolInfo.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/RibbonBarToolInfo.cs index 9c1ed8318fd..d24d37eb6d0 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/RibbonBarToolInfo.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/RibbonBarToolInfo.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + [Serializable] public class RibbonBarToolInfo { public RibbonBarToolInfo() { - ControlKey = ""; - ModuleFriendlyName = ""; - LinkWindowTarget = ""; - ToolName = ""; + this.ControlKey = string.Empty; + this.ModuleFriendlyName = string.Empty; + this.LinkWindowTarget = string.Empty; + this.ToolName = string.Empty; } public RibbonBarToolInfo(string toolName, bool isHostTool, bool useButton, string linkWindowTarget, string moduleFriendlyName, string controlKey, bool showAsPopUp) { - ToolName = toolName; - IsHostTool = isHostTool; - UseButton = useButton; - LinkWindowTarget = linkWindowTarget; - ModuleFriendlyName = moduleFriendlyName; - ControlKey = controlKey; - ShowAsPopUp = showAsPopUp; + this.ToolName = toolName; + this.IsHostTool = isHostTool; + this.UseButton = useButton; + this.LinkWindowTarget = linkWindowTarget; + this.ModuleFriendlyName = moduleFriendlyName; + this.ControlKey = controlKey; + this.ShowAsPopUp = showAsPopUp; } public string ControlKey { get; set; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs index fcd66c2553d..36cc677edc4 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs @@ -1,34 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Linq; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Security; -using DotNetNuke.Services.Localization; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Security; + using DotNetNuke.Services.Localization; + public class Tags : WebControl, IPostBackEventHandler, IPostBackDataHandler { private string _RepeatDirection = "Horizontal"; private string _Separator = ", "; private string _Tags; + + public event EventHandler TagsUpdated; + + public string AddImageUrl { get; set; } + + public bool AllowTagging { get; set; } private Vocabulary TagVocabulary { @@ -37,13 +37,7 @@ private Vocabulary TagVocabulary VocabularyController vocabularyController = new VocabularyController(); return (from v in vocabularyController.GetVocabularies() where v.IsSystem && v.Name == "Tags" select v).SingleOrDefault(); } - } - - #region "Public Properties" - - public string AddImageUrl { get; set; } - - public bool AllowTagging { get; set; } + } public string CancelImageUrl { get; set; } @@ -54,15 +48,17 @@ public bool IsEditMode get { bool _IsEditMode = false; - if (ViewState["IsEditMode"] != null) + if (this.ViewState["IsEditMode"] != null) { - _IsEditMode = Convert.ToBoolean(ViewState["IsEditMode"]); + _IsEditMode = Convert.ToBoolean(this.ViewState["IsEditMode"]); } + return _IsEditMode; } + set { - ViewState["IsEditMode"] = value; + this.ViewState["IsEditMode"] = value; } } @@ -72,11 +68,12 @@ public string RepeatDirection { get { - return _RepeatDirection; + return this._RepeatDirection; } + set { - _RepeatDirection = value; + this._RepeatDirection = value; } } @@ -86,184 +83,52 @@ public string Separator { get { - return _Separator; + return this._Separator; } + set { - _Separator = value; + this._Separator = value; } } public bool ShowCategories { get; set; } - public bool ShowTags { get; set; } - - #endregion - - #region "Private Methods" - - private string LocalizeString(string key) - { - string LocalResourceFile = Utilities.GetLocalResourceFile(this); - string localizedString = null; - if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(LocalResourceFile)) - { - localizedString = Localization.GetString(key, LocalResourceFile); - } - else - { - localizedString = Null.NullString; - } - return localizedString; - } - - private void RenderButton(HtmlTextWriter writer, string buttonType, string imageUrl) - { - writer.AddAttribute(HtmlTextWriterAttribute.Title, LocalizeString(string.Format("{0}.ToolTip", buttonType))); - writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, buttonType)); - writer.RenderBeginTag(HtmlTextWriterTag.A); - - //Image - if (!string.IsNullOrEmpty(imageUrl)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveUrl(imageUrl)); - writer.RenderBeginTag(HtmlTextWriterTag.Img); - writer.RenderEndTag(); - } - - writer.Write(LocalizeString(buttonType)); - writer.RenderEndTag(); - } - - private void RenderTerm(HtmlTextWriter writer, Term term, bool renderSeparator) - { - writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format(NavigateUrlFormatString, term.Name)); - writer.AddAttribute(HtmlTextWriterAttribute.Title, term.Name); - writer.AddAttribute(HtmlTextWriterAttribute.Rel, "tag"); - writer.RenderBeginTag(HtmlTextWriterTag.A); - writer.Write(term.Name); - writer.RenderEndTag(); - - if (renderSeparator) - { - writer.Write(Separator); - } - } - - private void SaveTags() - { - string tags = _Tags; - - if (!string.IsNullOrEmpty(tags)) - { - foreach (string t in tags.Split(',')) - { - if (!string.IsNullOrEmpty(t)) - { - string tagName = t.Trim(' '); - Term existingTerm = (from term in ContentItem.Terms.AsQueryable() where term.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select term).SingleOrDefault(); - - if (existingTerm == null) - { - //Not tagged - TermController termController = new TermController(); - Term term = - (from te in termController.GetTermsByVocabulary(TagVocabulary.VocabularyId) where te.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select te). - SingleOrDefault(); - if (term == null) - { - //Add term - term = new Term(TagVocabulary.VocabularyId); - term.Name = tagName; - termController.AddTerm(term); - } - - //Add term to content - ContentItem.Terms.Add(term); - termController.AddTermToContent(term, ContentItem); - } - } - } - } - - IsEditMode = false; - - //Raise the Tags Updated Event - OnTagsUpdate(EventArgs.Empty); - } - - #endregion - - public event EventHandler TagsUpdated; - - protected void OnTagsUpdate(EventArgs e) - { - if (TagsUpdated != null) - { - TagsUpdated(this, e); - } - } - - #region "Public Methods" - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if ((!Page.ClientScript.IsClientScriptBlockRegistered(UniqueID))) - { - StringBuilder sb = new StringBuilder(); - - sb.Append(""); - - Page.ClientScript.RegisterClientScriptBlock(GetType(), UniqueID, sb.ToString()); - } - } - - + public bool ShowTags { get; set; } + public override void RenderControl(HtmlTextWriter writer) { - //Render Outer Div - writer.AddAttribute(HtmlTextWriterAttribute.Class, RepeatDirection.ToLowerInvariant()); + // Render Outer Div + writer.AddAttribute(HtmlTextWriterAttribute.Class, this.RepeatDirection.ToLowerInvariant()); writer.RenderBeginTag(HtmlTextWriterTag.Div); - //Render Categories - if (ShowCategories) + // Render Categories + if (this.ShowCategories) { - //Render UL + // Render UL writer.AddAttribute(HtmlTextWriterAttribute.Class, "categories"); - writer.AddAttribute(HtmlTextWriterAttribute.Title, LocalizeString("Category.ToolTip")); + writer.AddAttribute(HtmlTextWriterAttribute.Title, this.LocalizeString("Category.ToolTip")); writer.RenderBeginTag(HtmlTextWriterTag.Ul); - //Render Category Links - var categories = (from cat in ContentItem.Terms where cat.VocabularyId != TagVocabulary.VocabularyId select cat); + // Render Category Links + var categories = from cat in this.ContentItem.Terms where cat.VocabularyId != this.TagVocabulary.VocabularyId select cat; for (int i = 0; i <= categories.Count() - 1; i++) { if (i == 0) { - //First Category + // First Category writer.AddAttribute(HtmlTextWriterAttribute.Class, "first_tag"); } else if (i == categories.Count() - 1) { - //Last Category + // Last Category writer.AddAttribute(HtmlTextWriterAttribute.Class, "last_tag"); } + writer.RenderBeginTag(HtmlTextWriterTag.Li); - RenderTerm(writer, categories.ToList()[i], i < categories.Count() - 1 && RepeatDirection.ToLowerInvariant() == "horizontal"); + this.RenderTerm(writer, categories.ToList()[i], i < categories.Count() - 1 && this.RepeatDirection.ToLowerInvariant() == "horizontal"); writer.RenderEndTag(); } @@ -271,64 +136,65 @@ public override void RenderControl(HtmlTextWriter writer) writer.RenderEndTag(); } - if (ShowTags) + if (this.ShowTags) { - //Render UL + // Render UL writer.AddAttribute(HtmlTextWriterAttribute.Class, "tags"); - writer.AddAttribute(HtmlTextWriterAttribute.Title, LocalizeString("Tag.ToolTip")); + writer.AddAttribute(HtmlTextWriterAttribute.Title, this.LocalizeString("Tag.ToolTip")); writer.RenderBeginTag(HtmlTextWriterTag.Ul); - //Render Tag Links - var tags = (from cat in ContentItem.Terms where cat.VocabularyId == TagVocabulary.VocabularyId select cat); + // Render Tag Links + var tags = from cat in this.ContentItem.Terms where cat.VocabularyId == this.TagVocabulary.VocabularyId select cat; for (int i = 0; i <= tags.Count() - 1; i++) { if (i == 0) { - //First Tag + // First Tag writer.AddAttribute(HtmlTextWriterAttribute.Class, "first_tag"); } else if (i == tags.Count() - 1) { - //Last Tag + // Last Tag writer.AddAttribute(HtmlTextWriterAttribute.Class, "last_tag"); } + writer.RenderBeginTag(HtmlTextWriterTag.Li); - RenderTerm(writer, tags.ToList()[i], i < tags.Count() - 1 && RepeatDirection.ToLowerInvariant() == "horizontal"); + this.RenderTerm(writer, tags.ToList()[i], i < tags.Count() - 1 && this.RepeatDirection.ToLowerInvariant() == "horizontal"); writer.RenderEndTag(); } - if (AllowTagging) + if (this.AllowTagging) { writer.RenderBeginTag(HtmlTextWriterTag.Li); - if (IsEditMode) + if (this.IsEditMode) { writer.Write("  "); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.AddAttribute("OnKeyPress", "return disableEnterKey(event)"); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); writer.Write("  "); - //Render Save Button - RenderButton(writer, "Save", SaveImageUrl); + // Render Save Button + this.RenderButton(writer, "Save", this.SaveImageUrl); writer.Write("  "); - //Render Add Button - RenderButton(writer, "Cancel", CancelImageUrl); + // Render Add Button + this.RenderButton(writer, "Cancel", this.CancelImageUrl); } else { writer.Write("  "); - //Render Add Button - RenderButton(writer, "Add", AddImageUrl); + // Render Add Button + this.RenderButton(writer, "Add", this.AddImageUrl); } writer.RenderEndTag(); @@ -338,47 +204,160 @@ public override void RenderControl(HtmlTextWriter writer) } writer.RenderEndTag(); + } + + public bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + this._Tags = postCollection[postDataKey]; + + return true; } - #endregion + protected void OnTagsUpdate(EventArgs e) + { + if (this.TagsUpdated != null) + { + this.TagsUpdated(this, e); + } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); - #region "IPostBackDataHandler Implementation" + if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.UniqueID)) + { + StringBuilder sb = new StringBuilder(); - public bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - _Tags = postCollection[postDataKey]; + sb.Append(""); - return true; + this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.UniqueID, sb.ToString()); + } + } + + private string LocalizeString(string key) + { + string LocalResourceFile = Utilities.GetLocalResourceFile(this); + string localizedString = null; + if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(LocalResourceFile)) + { + localizedString = Localization.GetString(key, LocalResourceFile); + } + else + { + localizedString = Null.NullString; + } + + return localizedString; } + private void RenderButton(HtmlTextWriter writer, string buttonType, string imageUrl) + { + writer.AddAttribute(HtmlTextWriterAttribute.Title, this.LocalizeString(string.Format("{0}.ToolTip", buttonType))); + writer.AddAttribute(HtmlTextWriterAttribute.Href, this.Page.ClientScript.GetPostBackClientHyperlink(this, buttonType)); + writer.RenderBeginTag(HtmlTextWriterTag.A); - public void RaisePostDataChangedEvent() + // Image + if (!string.IsNullOrEmpty(imageUrl)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Src, this.ResolveUrl(imageUrl)); + writer.RenderBeginTag(HtmlTextWriterTag.Img); + writer.RenderEndTag(); + } + + writer.Write(this.LocalizeString(buttonType)); + writer.RenderEndTag(); + } + + private void RenderTerm(HtmlTextWriter writer, Term term, bool renderSeparator) { + writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format(this.NavigateUrlFormatString, term.Name)); + writer.AddAttribute(HtmlTextWriterAttribute.Title, term.Name); + writer.AddAttribute(HtmlTextWriterAttribute.Rel, "tag"); + writer.RenderBeginTag(HtmlTextWriterTag.A); + writer.Write(term.Name); + writer.RenderEndTag(); + + if (renderSeparator) + { + writer.Write(this.Separator); + } } - #endregion + private void SaveTags() + { + string tags = this._Tags; + + if (!string.IsNullOrEmpty(tags)) + { + foreach (string t in tags.Split(',')) + { + if (!string.IsNullOrEmpty(t)) + { + string tagName = t.Trim(' '); + Term existingTerm = (from term in this.ContentItem.Terms.AsQueryable() where term.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select term).SingleOrDefault(); - #region "IPostBackEventHandler Implementation" + if (existingTerm == null) + { + // Not tagged + TermController termController = new TermController(); + Term term = + (from te in termController.GetTermsByVocabulary(this.TagVocabulary.VocabularyId) where te.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select te). + SingleOrDefault(); + if (term == null) + { + // Add term + term = new Term(this.TagVocabulary.VocabularyId); + term.Name = tagName; + termController.AddTerm(term); + } + // Add term to content + this.ContentItem.Terms.Add(term); + termController.AddTermToContent(term, this.ContentItem); + } + } + } + } + + this.IsEditMode = false; + + // Raise the Tags Updated Event + this.OnTagsUpdate(EventArgs.Empty); + } + + public void RaisePostDataChangedEvent() + { + } + public void RaisePostBackEvent(string eventArgument) { switch (eventArgument) { case "Add": - IsEditMode = true; + this.IsEditMode = true; break; case "Cancel": - IsEditMode = false; + this.IsEditMode = false; break; case "Save": - SaveTags(); + this.SaveTags(); break; default: - IsEditMode = false; + this.IsEditMode = false; break; } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs index cec736d034f..45f8201e17c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs @@ -1,40 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Content.Taxonomy; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { + using System; + + using DotNetNuke.Entities.Content.Taxonomy; + public class TermsEventArgs : EventArgs { - private readonly Term _SelectedTerm; - - #region "Constructors" - + private readonly Term _SelectedTerm; + public TermsEventArgs(Term selectedTerm) { - _SelectedTerm = selectedTerm; - } - - #endregion - - #region "Public Properties" - + this._SelectedTerm = selectedTerm; + } + public Term SelectedTerm { get { - return _SelectedTerm; + return this._SelectedTerm; } - } - - #endregion + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs index b7e70ab9e81..4a37e94e691 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { + using System; + using System.Web.UI; + /// - /// Restricts the client to add only controls of specific type into the control collection + /// Restricts the client to add only controls of specific type into the control collection. /// /// - public sealed class TypedControlCollection : ControlCollection where T : Control + public sealed class TypedControlCollection : ControlCollection + where T : Control { - - public TypedControlCollection(Control owner) : base(owner) + public TypedControlCollection(Control owner) + : base(owner) { } @@ -24,6 +25,7 @@ public override void Add(Control child) { throw new InvalidOperationException("Not supported"); } + base.Add(child); } @@ -33,9 +35,8 @@ public override void AddAt(int index, Control child) { throw new InvalidOperationException("Not supported"); } + base.AddAt(index, child); } - } - } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs index b203e0f840c..81d63e8ca20 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs @@ -1,257 +1,257 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Web.UI; -using System.Threading; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.UI.WebControls { - - public sealed class UniformControlCollection : IList where TOwner : Control where TChildren : Control + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Web.UI; + + public sealed class UniformControlCollection : IList + where TOwner : Control + where TChildren : Control { - private readonly TOwner _owner; internal UniformControlCollection(TOwner owner) { - _owner = owner; - } - - public void AddAt(int index, TChildren childControl) - { - _owner.Controls.AddAt(index, childControl); + this._owner = owner; } - /// - ///Determines the index of a specific item in the . - /// - /// - ///The index of if found in the list; otherwise, -1. - /// - /// - ///The object to locate in the . - /// - public int IndexOf(TChildren item) - { - return _owner.Controls.IndexOf(item); - } - - /// - /// Inserts an item to the at the specified index. - /// - /// - /// The zero-based index at which should be inserted. - /// - /// - /// The object to insert into the . - /// - /// is not a valid index in the . - /// - /// - ///The is read-only. - /// - public void Insert(int index, TChildren item) + /// + /// Gets the number of elements contained in the . + /// + /// + /// The number of elements contained in the . + /// + public int Count { - _owner.Controls.AddAt(index, item); + get + { + return this._owner.HasControls() ? this._owner.Controls.Count : 0; + } } - /// - ///Removes the item at the specified index. - /// - /// - ///The zero-based index of the item to remove. - /// - /// is not a valid index in the . - /// - /// - ///The is read-only. - /// - public void RemoveAt(int index) + /// + /// Gets a value indicating whether the is read-only. + /// + /// + /// true if the is read-only; otherwise, false. + /// + public bool IsReadOnly { - _owner.Controls.RemoveAt(index); + get + { + return false; + } } - /// - ///Gets or sets the element at the specified index. - /// - /// - ///The element at the specified index. - /// - /// - ///The zero-based index of the element to get or set. - /// - /// is not a valid index in the . - /// - /// - ///The property is set and the is read-only. - /// + /// + /// Gets or sets the element at the specified index. + /// + /// + /// The element at the specified index. + /// + /// + /// The zero-based index of the element to get or set. + /// + /// is not a valid index in the . + /// + /// + /// The property is set and the is read-only. + /// public TChildren this[int index] { get { - return _owner.Controls[index] as TChildren; + return this._owner.Controls[index] as TChildren; } + set { - RemoveAt(index); - AddAt(index, value); + this.RemoveAt(index); + this.AddAt(index, value); } } - /// - ///Gets the number of elements contained in the . - /// - /// - ///The number of elements contained in the . - /// - public int Count + public void AddAt(int index, TChildren childControl) { - get - { - return _owner.HasControls() ? _owner.Controls.Count : 0; - } + this._owner.Controls.AddAt(index, childControl); } - /// - ///Removes the first occurrence of a specific object from the . - /// - /// - ///true if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . - /// - /// - ///The object to remove from the . - /// - /// - ///The is read-only. - /// - public bool Remove(TChildren item) + /// + /// Determines the index of a specific item in the . + /// + /// + /// The index of if found in the list; otherwise, -1. + /// + /// + /// The object to locate in the . + /// + public int IndexOf(TChildren item) { - _owner.Controls.Remove(item); - return true; + return this._owner.Controls.IndexOf(item); } - /// - ///Gets a value indicating whether the is read-only. - /// - /// - ///true if the is read-only; otherwise, false. - /// - public bool IsReadOnly + /// + /// Inserts an item to the at the specified index. + /// + /// + /// The zero-based index at which should be inserted. + /// + /// + /// The object to insert into the . + /// + /// is not a valid index in the . + /// + /// + /// The is read-only. + /// + public void Insert(int index, TChildren item) { - get - { - return false; - } + this._owner.Controls.AddAt(index, item); } - /// - ///Returns an enumerator that iterates through the collection. - /// - /// - ///A that can be used to iterate through the collection. - /// - ///1 + /// + /// Removes the item at the specified index. + /// + /// + /// The zero-based index of the item to remove. + /// + /// is not a valid index in the . + /// + /// + /// The is read-only. + /// + public void RemoveAt(int index) + { + this._owner.Controls.RemoveAt(index); + } + + /// + /// Removes the first occurrence of a specific object from the . + /// + /// + /// true if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . + /// + /// + /// The object to remove from the . + /// + /// + /// The is read-only. + /// + public bool Remove(TChildren item) + { + this._owner.Controls.Remove(item); + return true; + } + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + /// 1. public IEnumerator GetEnumerator() { - var enumerator = _owner.Controls.GetEnumerator(); + var enumerator = this._owner.Controls.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current as TChildren; } } - /// - ///Removes all items from the . - /// - /// - ///The is read-only. - /// + /// + /// Removes all items from the . + /// + /// + /// The is read-only. + /// public void Clear() { - if (_owner.HasControls()) + if (this._owner.HasControls()) { - _owner.Controls.Clear(); + this._owner.Controls.Clear(); } } - /// - ///Adds an item to the . - /// - /// - ///The object to add to the . - /// - /// - ///The is read-only. - /// + /// + /// Adds an item to the . + /// + /// + /// The object to add to the . + /// + /// + /// The is read-only. + /// public void Add(TChildren item) { - _owner.Controls.Add(item); + this._owner.Controls.Add(item); } - /// - ///Copies the elements of the to an , starting at a particular index. - /// - /// - ///The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing. - /// - /// - ///The zero-based index in at which copying begins. - /// - /// is null. - /// - /// is less than 0. - /// - /// is multidimensional. - ///-or- - /// is equal to or greater than the length of . - ///-or- - ///The number of elements in the source is greater than the available space from to the end of the destination . - ///-or- - ///Type paramref name="T" cannot be cast automatically to the type of the destination . - /// + /// + /// Copies the elements of the to an , starting at a particular index. + /// + /// + /// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing. + /// + /// + /// The zero-based index in at which copying begins. + /// + /// is null. + /// + /// is less than 0. + /// + /// is multidimensional. + /// -or- + /// is equal to or greater than the length of . + /// -or- + /// The number of elements in the source is greater than the available space from to the end of the destination . + /// -or- + /// Type paramref name="T" cannot be cast automatically to the type of the destination . + /// public void CopyTo(TChildren[] array, int arrayIndex) { - var enumerator = GetEnumerator(); + var enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { array.SetValue(enumerator.Current, Math.Max(Interlocked.Increment(ref arrayIndex), arrayIndex - 1)); } } - /// - ///Determines whether the contains a specific value. - /// - /// - ///true if is found in the ; otherwise, false. - /// - /// - ///The object to locate in the . - /// + /// + /// Determines whether the contains a specific value. + /// + /// + /// true if is found in the ; otherwise, false. + /// + /// + /// The object to locate in the . + /// public bool Contains(TChildren item) { - return _owner.Controls.Contains(item); + return this._owner.Controls.Contains(item); } - /// - ///Returns an enumerator that iterates through a collection. - /// - /// - ///An object that can be used to iterate through the collection. - /// - ///2 - private IEnumerator EnumerableGetEnumerator() + IEnumerator IEnumerable.GetEnumerator() { - return _owner.Controls.GetEnumerator(); + return this.EnumerableGetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() + /// + /// Returns an enumerator that iterates through a collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + /// 2. + private IEnumerator EnumerableGetEnumerator() { - return EnumerableGetEnumerator(); + return this._owner.Controls.GetEnumerator(); } - } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs b/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs index 0d6144dcee1..0c396f8b963 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs @@ -1,27 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Validators { - public abstract class AttributeBasedObjectValidator : PropertyBasedObjectValidator where TAttribute : Attribute + using System; + using System.Linq; + using System.Reflection; + + public abstract class AttributeBasedObjectValidator : PropertyBasedObjectValidator + where TAttribute : Attribute { protected override ValidationResult ValidateProperty(object target, PropertyInfo targetProperty) { - return targetProperty.GetCustomAttributes(true).OfType().Aggregate(ValidationResult.Successful, - (result, attribute) => - result.CombineWith(ValidateAttribute(target, targetProperty, attribute) ?? ValidationResult.Successful)); + return targetProperty.GetCustomAttributes(true).OfType().Aggregate( + ValidationResult.Successful, + (result, attribute) => + result.CombineWith(this.ValidateAttribute(target, targetProperty, attribute) ?? ValidationResult.Successful)); } - - + protected abstract ValidationResult ValidateAttribute(object target, PropertyInfo targetProperty, TAttribute attribute); } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs b/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs index 1393c0d26b5..530b10972e0 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs @@ -1,27 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel.DataAnnotations; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Validators { + using System.ComponentModel.DataAnnotations; + using System.Reflection; + public class DataAnnotationsObjectValidator : AttributeBasedObjectValidator { protected override ValidationResult ValidateAttribute(object target, PropertyInfo targetProperty, ValidationAttribute attribute) { - return !attribute.IsValid(targetProperty.GetValue(target, new object[] {})) ? new ValidationResult(new[] {CreateError(targetProperty.Name, attribute)}) : ValidationResult.Successful; + return !attribute.IsValid(targetProperty.GetValue(target, new object[] { })) ? new ValidationResult(new[] { this.CreateError(targetProperty.Name, attribute) }) : ValidationResult.Successful; } - - + protected virtual ValidationError CreateError(string propertyName, ValidationAttribute attribute) { - return new ValidationError {ErrorMessage = attribute.FormatErrorMessage(propertyName), PropertyName = propertyName, Validator = attribute}; + return new ValidationError { ErrorMessage = attribute.FormatErrorMessage(propertyName), PropertyName = propertyName, Validator = attribute }; } } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/ObjectValidator.cs b/DNN Platform/DotNetNuke.Web/Validators/ObjectValidator.cs index 29d3f4917e6..25b3e1b98cd 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/ObjectValidator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/ObjectValidator.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Validators { public abstract class ObjectValidator diff --git a/DNN Platform/DotNetNuke.Web/Validators/PropertyBasedObjectValidator.cs b/DNN Platform/DotNetNuke.Web/Validators/PropertyBasedObjectValidator.cs index 2cd84b5c988..0ec59952402 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/PropertyBasedObjectValidator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/PropertyBasedObjectValidator.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Linq; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Validators { + using System.Linq; + using System.Reflection; + public abstract class PropertyBasedObjectValidator : ObjectValidator { public override ValidationResult ValidateObject(object target) { - return target.GetType().GetProperties().Aggregate(ValidationResult.Successful, (result, member) => result.CombineWith(ValidateProperty(target, member) ?? ValidationResult.Successful)); + return target.GetType().GetProperties().Aggregate(ValidationResult.Successful, (result, member) => result.CombineWith(this.ValidateProperty(target, member) ?? ValidationResult.Successful)); } protected abstract ValidationResult ValidateProperty(object target, PropertyInfo targetProperty); diff --git a/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs b/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs index 10e213fe6aa..a6322356b05 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs @@ -1,19 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.Validators { public class ValidationError - { - #region "Public Properties" - + { public string ErrorMessage { get; set; } public string PropertyName { get; set; } - public object Validator { get; set; } - - #endregion + public object Validator { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs b/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs index 838ebc4d7ba..a5c51dacd25 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs @@ -1,76 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Validators { + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + public class ValidationResult { - private readonly IEnumerable _Errors; - - #region "Constructors" - + private readonly IEnumerable _Errors; + public ValidationResult() { - _Errors = Enumerable.Empty(); + this._Errors = Enumerable.Empty(); } public ValidationResult(IEnumerable errors) { Requires.NotNull("errors", errors); - _Errors = errors; - } - - #endregion - - #region "Public Properties" + this._Errors = errors; + } - public IEnumerable Errors + public static ValidationResult Successful { get { - return _Errors; + return new ValidationResult(); } - } - - public bool IsValid + } + + public IEnumerable Errors { get { - return (_Errors.Count() == 0); + return this._Errors; } } - public static ValidationResult Successful + public bool IsValid { get { - return new ValidationResult(); + return this._Errors.Count() == 0; } } - - #endregion - - #region "Public Methods" - + public ValidationResult CombineWith(ValidationResult other) { Requires.NotNull("other", other); - //Just concatenate the errors collection - return new ValidationResult(_Errors.Concat(other.Errors)); - } - - #endregion + // Just concatenate the errors collection + return new ValidationResult(this._Errors.Concat(other.Errors)); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/Validator.cs b/DNN Platform/DotNetNuke.Web/Validators/Validator.cs index 9ed2ed6da3d..1680d8dece3 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/Validator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/Validator.cs @@ -1,41 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Validators { + using System.Collections.Generic; + using System.Linq; + public class Validator { private readonly IList _Validators; public Validator() { - _Validators = new List(); + this._Validators = new List(); } - public Validator(ObjectValidator validator) : this() + public Validator(ObjectValidator validator) + : this() { - _Validators.Add(validator); + this._Validators.Add(validator); } public IList Validators { get { - return _Validators; + return this._Validators; } } public ValidationResult ValidateObject(object target) { - return _Validators.Aggregate(ValidationResult.Successful, (result, validator) => result.CombineWith(validator.ValidateObject(target) ?? ValidationResult.Successful)); + return this._Validators.Aggregate(ValidationResult.Successful, (result, validator) => result.CombineWith(validator.ValidateObject(target) ?? ValidationResult.Successful)); } } } diff --git a/DNN Platform/DotNetNuke.Web/packages.config b/DNN Platform/DotNetNuke.Web/packages.config index 4a7bf694062..211aecc063e 100644 --- a/DNN Platform/DotNetNuke.Web/packages.config +++ b/DNN Platform/DotNetNuke.Web/packages.config @@ -11,5 +11,6 @@ + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.ClientAPI.dnn b/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.ClientAPI.dnn index 09bd5d0f3ce..c470f5a7a5a 100644 --- a/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.ClientAPI.dnn +++ b/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.ClientAPI.dnn @@ -1,6 +1,6 @@  - + DotNetNuke ClientAPI The DotNetNuke Client API is composed of both server-side and client-side code that works together to enable a simple and reliable interface for the developer to provide a rich client-side experience. diff --git a/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj b/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj index 8571765076b..bfb46c577e7 100644 --- a/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj +++ b/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj @@ -170,7 +170,11 @@ + + stylecop.json + + diff --git a/DNN Platform/DotNetNuke.WebUtility/packages.config b/DNN Platform/DotNetNuke.WebUtility/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/DotNetNuke.WebUtility/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/DotNetNuke.Website.Deprecated.csproj b/DNN Platform/DotNetNuke.Website.Deprecated/DotNetNuke.Website.Deprecated.csproj index b5b35e0cb6e..9f01bc47c74 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/DotNetNuke.Website.Deprecated.csproj +++ b/DNN Platform/DotNetNuke.Website.Deprecated/DotNetNuke.Website.Deprecated.csproj @@ -1,214 +1,221 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {19EAE090-9D06-43BE-A62E-D6217E813AD1} - Library - DotNetNuke.Website - DotNetNuke.Website.Deprecated - 512 - WebControl - v4.7.2 - true - On - Binary - Off - On - - - 4.0 - - false - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - - ..\..\ - true - - - true - full - true - true - bin\ - bin\DotNetNuke.Website.Deprecated.xml - 1591 - AllRules.ruleset - 7 - false - - - pdbonly - false - true - true - bin\ - bin\DotNetNuke.Website.Deprecated.xml - 1591 - AllRules.ruleset - false - 7 - - - 1591 - AllRules.ruleset - false - - - AllRules.ruleset - false - - - - - ..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll - - - ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - - - - - - - - - - - - - - ..\Components\Telerik\bin\Telerik.Web.UI.dll - True - - - ..\Components\Telerik\bin\Telerik.Web.UI.Skins.dll - - - - - SolutionInfo.cs - - - ASPXCodeBehind - - - AddModule.ascx.cs - - - ASPXCodeBehind - - - AddPage.ascx.cs - - - ASPXCodeBehind - - - ControlBar.ascx.cs - - - ASPXCodeBehind - - - RibbonBar.ascx.cs - - - ASPXCodeBehind - - - SwitchSite.ascx.cs - - - ASPXCodeBehind - - - UpdatePage.ascx.cs - - - ASPXCodeBehind - - - WebUpload.ascx.cs - - - - - - - - - - - - - - {6928A9B1-F88A-4581-A132-D3EB38669BB0} - DotNetNuke.Abstractions - - - {ddf18e36-41a0-4ca7-a098-78ca6e6f41c1} - DotNetNuke.Instrumentation - - - {537b45eb-2ec3-4849-bc6b-d761f43674a5} - DotNetNuke.Web.Client - - - {9ba59b3d-9ffb-4a9e-bd7d-8b58d08b3a33} - DotNetNuke.Web.Deprecated - - - {4912f062-f8a8-4f9d-8f8e-244ebee1acbd} - DotNetNuke.WebUtility - - - {ee1329fe-fd88-4e1a-968c-345e394ef080} - DotNetNuke.Web - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {a86ebc44-2bc8-4c4a-997b-2708e4aac345} - DotNetNuke.Modules.DDRMenu - - - - - Designer - - - Designer - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {19EAE090-9D06-43BE-A62E-D6217E813AD1} + Library + DotNetNuke.Website + DotNetNuke.Website.Deprecated + 512 + WebControl + v4.7.2 + true + On + Binary + Off + On + + + 4.0 + + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + ..\..\ + true + + + true + full + true + true + bin\ + bin\DotNetNuke.Website.Deprecated.xml + 1591 + AllRules.ruleset + 7 + false + + + pdbonly + false + true + true + bin\ + bin\DotNetNuke.Website.Deprecated.xml + 1591 + AllRules.ruleset + false + 7 + + + 1591 + AllRules.ruleset + false + + + AllRules.ruleset + false + + + + + ..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll + + + ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + + + + + + + + + + + + ..\Components\Telerik\bin\Telerik.Web.UI.dll + True + + + ..\Components\Telerik\bin\Telerik.Web.UI.Skins.dll + + + + + SolutionInfo.cs + + + ASPXCodeBehind + + + AddModule.ascx.cs + + + ASPXCodeBehind + + + AddPage.ascx.cs + + + ASPXCodeBehind + + + ControlBar.ascx.cs + + + ASPXCodeBehind + + + RibbonBar.ascx.cs + + + ASPXCodeBehind + + + SwitchSite.ascx.cs + + + ASPXCodeBehind + + + UpdatePage.ascx.cs + + + ASPXCodeBehind + + + WebUpload.ascx.cs + + + + + + + + + + + + + + {6928A9B1-F88A-4581-A132-D3EB38669BB0} + DotNetNuke.Abstractions + + + {ddf18e36-41a0-4ca7-a098-78ca6e6f41c1} + DotNetNuke.Instrumentation + + + {537b45eb-2ec3-4849-bc6b-d761f43674a5} + DotNetNuke.Web.Client + + + {9ba59b3d-9ffb-4a9e-bd7d-8b58d08b3a33} + DotNetNuke.Web.Deprecated + + + {4912f062-f8a8-4f9d-8f8e-244ebee1acbd} + DotNetNuke.WebUtility + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {a86ebc44-2bc8-4c4a-997b-2708e4aac345} + DotNetNuke.Modules.DDRMenu + + + + + stylecop.json + + + Designer + + + Designer + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/Properties/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Website.Deprecated/Properties/AssemblyInfo.cs index a7bb750276b..d2b25837307 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/Properties/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/Properties/AssemblyInfo.cs @@ -1,27 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Web.UI; - -#endregion - -// 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. - -// Review the values of the assembly attributes - +using System.Web.UI; + +// 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. + +// Review the values of the assembly attributes [assembly: AssemblyTitle("DotNetNuke.Website.Deprecated")] [assembly: AssemblyDescription("Open Source Web Application Framework")] [assembly: CLSCompliant(false)] [assembly: ComVisible(false)] -//The following GUID is for the ID of the typelib if this project is exposed to COM - + +// The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4B693EF0-E5D9-4647-B9F1-CD057D8DC011")] diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs index 95b2b6cee8e..b13c073fdc3 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs @@ -1,60 +1,94 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Web; -using System.Web.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Personalization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.UI; -using DotNetNuke.Web.UI.WebControls; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Web.UI.WebControls.Extensions; - -using Globals = DotNetNuke.Common.Globals; -using PortalInfo = DotNetNuke.Entities.Portals.PortalInfo; -using Reflection = DotNetNuke.Framework.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.ControlPanel { - public partial class AddModule : UserControlBase, IDnnRibbonBarTool - { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Personalization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.UI; + using DotNetNuke.Web.UI.WebControls; + using DotNetNuke.Web.UI.WebControls.Extensions; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; + using PortalInfo = DotNetNuke.Entities.Portals.PortalInfo; + using Reflection = DotNetNuke.Framework.Reflection; + + public partial class AddModule : UserControlBase, IDnnRibbonBarTool + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AddModule)); private readonly INavigationManager _navigationManager; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (AddModule)); private bool _enabled = true; public AddModule() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } + + public override bool Visible + { + get + { + return base.Visible && TabPermissionController.CanAddContentToPage(); + } + + set + { + base.Visible = value; + } + } + + public bool Enabled + { + get + { + return this._enabled && this.CanAddModuleToPage(); + } + + set + { + this._enabled = value; + } + } + + public string ToolName + { + get + { + return "QuickAddModule"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } } /// - /// Return the for the selected portal (from the Site list), unless + /// Gets return the for the selected portal (from the Site list), unless /// the site list is not visible or there are no other sites in our site group, in which case /// it returns the PortalSettings for the current portal. /// @@ -66,14 +100,14 @@ private PortalSettings SelectedPortalSettings try { - if (SiteListPanel.Visible && SiteList.SelectedItem != null) + if (this.SiteListPanel.Visible && this.SiteList.SelectedItem != null) { - if (!string.IsNullOrEmpty(SiteList.SelectedItem.Value)) + if (!string.IsNullOrEmpty(this.SiteList.SelectedItem.Value)) { - var selectedPortalId = int.Parse(SiteList.SelectedItem.Value); - if (PortalSettings.PortalId != selectedPortalId) + var selectedPortalId = int.Parse(this.SiteList.SelectedItem.Value); + if (this.PortalSettings.PortalId != selectedPortalId) { - portalSettings = new PortalSettings(int.Parse(SiteList.SelectedItem.Value)); + portalSettings = new PortalSettings(int.Parse(this.SiteList.SelectedItem.Value)); } } } @@ -85,285 +119,250 @@ private PortalSettings SelectedPortalSettings return portalSettings; } + } + + protected void AddNewOrExisting_OnClick(object sender, EventArgs e) + { + this.LoadAllLists(); } + protected void PaneLstSelectedIndexChanged(object sender, EventArgs e) + { + this.LoadPositionList(); + this.LoadPaneModulesList(); + } - #region Event Handlers - - protected void AddNewOrExisting_OnClick(Object sender, EventArgs e) - { - LoadAllLists(); - } - - protected void PaneLstSelectedIndexChanged(Object sender, EventArgs e) - { - LoadPositionList(); - LoadPaneModulesList(); - } - - protected void PageLstSelectedIndexChanged(Object sender, EventArgs e) - { - LoadModuleList(); - } + protected void PageLstSelectedIndexChanged(object sender, EventArgs e) + { + this.LoadModuleList(); + } - protected void PositionLstSelectedIndexChanged(Object sender, EventArgs e) - { - PaneModulesLst.Enabled = PositionLst.SelectedValue == "ABOVE" || PositionLst.SelectedValue == "BELOW"; - } + protected void PositionLstSelectedIndexChanged(object sender, EventArgs e) + { + this.PaneModulesLst.Enabled = this.PositionLst.SelectedValue == "ABOVE" || this.PositionLst.SelectedValue == "BELOW"; + } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); // Is there more than one site in this group? - var multipleSites = GetCurrentPortalsGroup().Count() > 1; - ClientAPI.RegisterClientVariable(Page, "moduleSharing", multipleSites.ToString().ToLowerInvariant(), true); + var multipleSites = this.GetCurrentPortalsGroup().Count() > 1; + ClientAPI.RegisterClientVariable(this.Page, "moduleSharing", multipleSites.ToString().ToLowerInvariant(), true); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - cmdAddModule.Click += CmdAddModuleClick; - AddNewModule.CheckedChanged += AddNewOrExisting_OnClick; - AddExistingModule.CheckedChanged += AddNewOrExisting_OnClick; - SiteList.SelectedIndexChanged += SiteList_SelectedIndexChanged; - CategoryList.SelectedIndexChanged += CategoryListSelectedIndexChanged; - PageLst.SelectedIndexChanged += PageLstSelectedIndexChanged; - PaneLst.SelectedIndexChanged += PaneLstSelectedIndexChanged; - PositionLst.SelectedIndexChanged += PositionLstSelectedIndexChanged; + this.cmdAddModule.Click += this.CmdAddModuleClick; + this.AddNewModule.CheckedChanged += this.AddNewOrExisting_OnClick; + this.AddExistingModule.CheckedChanged += this.AddNewOrExisting_OnClick; + this.SiteList.SelectedIndexChanged += this.SiteList_SelectedIndexChanged; + this.CategoryList.SelectedIndexChanged += this.CategoryListSelectedIndexChanged; + this.PageLst.SelectedIndexChanged += this.PageLstSelectedIndexChanged; + this.PaneLst.SelectedIndexChanged += this.PaneLstSelectedIndexChanged; + this.PositionLst.SelectedIndexChanged += this.PositionLstSelectedIndexChanged; try - { - if ((Visible)) - { - cmdAddModule.Enabled = Enabled; - AddExistingModule.Enabled = Enabled; - AddNewModule.Enabled = Enabled; - Title.Enabled = Enabled; - PageLst.Enabled = Enabled; - ModuleLst.Enabled = Enabled; - VisibilityLst.Enabled = Enabled; - PaneLst.Enabled = Enabled; - PositionLst.Enabled = Enabled; - PaneModulesLst.Enabled = Enabled; - - UserInfo objUser = UserController.Instance.GetCurrentUserInfo(); - if ((objUser != null)) - { - if (objUser.IsSuperUser) - { + { + if (this.Visible) + { + this.cmdAddModule.Enabled = this.Enabled; + this.AddExistingModule.Enabled = this.Enabled; + this.AddNewModule.Enabled = this.Enabled; + this.Title.Enabled = this.Enabled; + this.PageLst.Enabled = this.Enabled; + this.ModuleLst.Enabled = this.Enabled; + this.VisibilityLst.Enabled = this.Enabled; + this.PaneLst.Enabled = this.Enabled; + this.PositionLst.Enabled = this.Enabled; + this.PaneModulesLst.Enabled = this.Enabled; + + UserInfo objUser = UserController.Instance.GetCurrentUserInfo(); + if (objUser != null) + { + if (objUser.IsSuperUser) + { var objModule = ModuleController.Instance.GetModuleByDefinition(-1, "Extensions"); - if (objModule != null) - { - var strURL = _navigationManager.NavigateURL(objModule.TabID, true); - hlMoreExtensions.NavigateUrl = strURL + "#moreExtensions"; - } - else - { - hlMoreExtensions.Enabled = false; - } - hlMoreExtensions.Text = GetString("hlMoreExtensions"); - hlMoreExtensions.Visible = true; - } - } - } - - if ((!IsPostBack && Visible && Enabled)) - { - AddNewModule.Checked = true; - LoadAllLists(); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - private void CmdConfirmAddModuleClick(object sender, EventArgs e) - { - CmdAddModuleClick(sender, e); + if (objModule != null) + { + var strURL = this._navigationManager.NavigateURL(objModule.TabID, true); + this.hlMoreExtensions.NavigateUrl = strURL + "#moreExtensions"; + } + else + { + this.hlMoreExtensions.Enabled = false; + } + + this.hlMoreExtensions.Text = this.GetString("hlMoreExtensions"); + this.hlMoreExtensions.Visible = true; + } + } + } + + if (!this.IsPostBack && this.Visible && this.Enabled) + { + this.AddNewModule.Checked = true; + this.LoadAllLists(); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } } - void SiteList_SelectedIndexChanged(object sender, EventArgs e) + protected void CmdAddModuleClick(object sender, EventArgs e) { - LoadModuleList(); - LoadPageList(); - } + if (TabPermissionController.CanAddContentToPage() && this.CanAddModuleToPage()) + { + int permissionType; + try + { + permissionType = int.Parse(this.VisibilityLst.SelectedValue); + } + catch (Exception exc) + { + Logger.Error(exc); + + permissionType = 0; + } - private void CategoryListSelectedIndexChanged(object sender, EventArgs e) - { - LoadModuleList(); - } - - protected void CmdAddModuleClick(object sender, EventArgs e) - { - if (TabPermissionController.CanAddContentToPage() && CanAddModuleToPage()) - { - int permissionType; - try - { - permissionType = int.Parse(VisibilityLst.SelectedValue); - } - catch (Exception exc) - { - Logger.Error(exc); - - permissionType = 0; - } - - int position = -1; - switch (PositionLst.SelectedValue) - { - case "TOP": - position = 0; - break; - case "ABOVE": - if (!string.IsNullOrEmpty(PaneModulesLst.SelectedValue)) - { - try - { - position = int.Parse(PaneModulesLst.SelectedValue) - 1; - } - catch (Exception exc) - { - Logger.Error(exc); - - position = -1; - } - } - else - { - position = 0; - } - break; - case "BELOW": - if (!string.IsNullOrEmpty(PaneModulesLst.SelectedValue)) - { - try - { - position = int.Parse(PaneModulesLst.SelectedValue) + 1; - } - catch (Exception exc) - { - Logger.Error(exc); - - position = -1; - } - } - else - { - position = -1; - } - break; - case "BOTTOM": - position = -1; - break; - } - - int moduleLstID; - try - { - moduleLstID = int.Parse(ModuleLst.SelectedValue); - } - catch (Exception exc) - { - Logger.Error(exc); - - moduleLstID = -1; - } - - if ((moduleLstID > -1)) - { - if ((AddExistingModule.Checked)) - { - int pageID; - try - { - pageID = int.Parse(PageLst.SelectedValue); - } - catch (Exception exc) - { - Logger.Error(exc); - - pageID = -1; - } - - if ((pageID > -1)) - { - DoAddExistingModule(moduleLstID, pageID, PaneLst.SelectedValue, position, "", chkCopyModule.Checked); - } - } - else - { - DoAddNewModule(Title.Text, moduleLstID, PaneLst.SelectedValue, position, permissionType, ""); - } - } - - //set view mode to edit after add module. - if (PortalSettings.UserMode != PortalSettings.Mode.Edit) - { - Personalization.SetProfile("Usability", "UserMode" + PortalSettings.PortalId, "EDIT"); - } - Response.Redirect(Request.RawUrl, true); - } - } - - #endregion - - #region Properties - - public override bool Visible - { - get - { - return base.Visible && TabPermissionController.CanAddContentToPage(); - } - set - { - base.Visible = value; - } - } - - public bool Enabled - { - get - { - return _enabled && CanAddModuleToPage(); - } - set - { - _enabled = value; - } - } - - public string ToolName - { - get - { - return "QuickAddModule"; - } - set - { - throw new NotSupportedException("Set ToolName not supported"); - } - } - - /// The currently-selected module. - protected DesktopModuleInfo SelectedModule - { - get - { - if (AddExistingModule.Checked) + int position = -1; + switch (this.PositionLst.SelectedValue) { - var tabId = -1; - if (!string.IsNullOrEmpty(PageLst.SelectedValue)) - tabId = int.Parse(PageLst.SelectedValue); + case "TOP": + position = 0; + break; + case "ABOVE": + if (!string.IsNullOrEmpty(this.PaneModulesLst.SelectedValue)) + { + try + { + position = int.Parse(this.PaneModulesLst.SelectedValue) - 1; + } + catch (Exception exc) + { + Logger.Error(exc); + + position = -1; + } + } + else + { + position = 0; + } + + break; + case "BELOW": + if (!string.IsNullOrEmpty(this.PaneModulesLst.SelectedValue)) + { + try + { + position = int.Parse(this.PaneModulesLst.SelectedValue) + 1; + } + catch (Exception exc) + { + Logger.Error(exc); - if (tabId < 0) - tabId = PortalSettings.Current.ActiveTab.TabID; + position = -1; + } + } + else + { + position = -1; + } + + break; + case "BOTTOM": + position = -1; + break; + } - if (!string.IsNullOrEmpty(ModuleLst.SelectedValue)) + int moduleLstID; + try + { + moduleLstID = int.Parse(this.ModuleLst.SelectedValue); + } + catch (Exception exc) + { + Logger.Error(exc); + + moduleLstID = -1; + } + + if (moduleLstID > -1) + { + if (this.AddExistingModule.Checked) { - var moduleId = int.Parse(ModuleLst.SelectedValue); + int pageID; + try + { + pageID = int.Parse(this.PageLst.SelectedValue); + } + catch (Exception exc) + { + Logger.Error(exc); + + pageID = -1; + } + + if (pageID > -1) + { + this.DoAddExistingModule(moduleLstID, pageID, this.PaneLst.SelectedValue, position, string.Empty, this.chkCopyModule.Checked); + } + } + else + { + DoAddNewModule(this.Title.Text, moduleLstID, this.PaneLst.SelectedValue, position, permissionType, string.Empty); + } + } + + // set view mode to edit after add module. + if (this.PortalSettings.UserMode != PortalSettings.Mode.Edit) + { + Personalization.SetProfile("Usability", "UserMode" + this.PortalSettings.PortalId, "EDIT"); + } + + this.Response.Redirect(this.Request.RawUrl, true); + } + } + + private void CmdConfirmAddModuleClick(object sender, EventArgs e) + { + this.CmdAddModuleClick(sender, e); + } + + private void SiteList_SelectedIndexChanged(object sender, EventArgs e) + { + this.LoadModuleList(); + this.LoadPageList(); + } + + private void CategoryListSelectedIndexChanged(object sender, EventArgs e) + { + this.LoadModuleList(); + } + + /// Gets the currently-selected module. + protected DesktopModuleInfo SelectedModule + { + get + { + if (this.AddExistingModule.Checked) + { + var tabId = -1; + if (!string.IsNullOrEmpty(this.PageLst.SelectedValue)) + { + tabId = int.Parse(this.PageLst.SelectedValue); + } + + if (tabId < 0) + { + tabId = PortalSettings.Current.ActiveTab.TabID; + } + + if (!string.IsNullOrEmpty(this.ModuleLst.SelectedValue)) + { + var moduleId = int.Parse(this.ModuleLst.SelectedValue); if (moduleId >= 0) { return ModuleController.Instance.GetModule(moduleId, tabId, false).DesktopModule; @@ -374,13 +373,19 @@ protected DesktopModuleInfo SelectedModule { var portalId = -1; - if (SiteListPanel.Visible) portalId = int.Parse(SiteList.SelectedValue); - - if (portalId < 0) portalId = PortalSettings.Current.PortalId; - - if (!string.IsNullOrEmpty(ModuleLst.SelectedValue)) + if (this.SiteListPanel.Visible) + { + portalId = int.Parse(this.SiteList.SelectedValue); + } + + if (portalId < 0) + { + portalId = PortalSettings.Current.PortalId; + } + + if (!string.IsNullOrEmpty(this.ModuleLst.SelectedValue)) { - var moduleId = int.Parse(ModuleLst.SelectedValue); + var moduleId = int.Parse(this.ModuleLst.SelectedValue); if (moduleId >= 0) { return DesktopModuleController.GetDesktopModule(moduleId, portalId); @@ -389,13 +394,33 @@ protected DesktopModuleInfo SelectedModule } return null; - } - } - - #endregion + } + } - #region Methods + private string LocalResourceFile + { + get + { + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); + } + } + + public bool CanAddModuleToPage() + { + if (HttpContext.Current == null) + { + return false; + } + + // If we are not in an edit page + return string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"]) && string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"]); + } + protected string GetString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + private static ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) { var objModulePermission = new ModulePermissionInfo @@ -405,7 +430,7 @@ private static ModulePermissionInfo AddModulePermission(ModuleInfo objModule, Pe RoleID = roleId, UserID = userId, PermissionKey = permission.PermissionKey, - AllowAccess = allowAccess + AllowAccess = allowAccess, }; // add the permission to the collection @@ -417,21 +442,97 @@ private static ModulePermissionInfo AddModulePermission(ModuleInfo objModule, Pe return objModulePermission; } + private static void SetCloneModuleContext(bool cloneModuleContext) + { + Thread.SetData( + Thread.GetNamedDataSlot("CloneModuleContext"), + cloneModuleContext ? bool.TrueString : bool.FalseString); + } + + private static void DoAddNewModule(string title, int desktopModuleId, string paneName, int position, int permissionType, string align) + { + try + { + DesktopModuleInfo desktopModule; + if (!DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId).TryGetValue(desktopModuleId, out desktopModule)) + { + throw new ArgumentException("desktopModuleId"); + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + foreach (ModuleDefinitionInfo objModuleDefinition in + ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values) + { + var objModule = new ModuleInfo(); + objModule.Initialize(PortalSettings.Current.ActiveTab.PortalID); + + objModule.PortalID = PortalSettings.Current.ActiveTab.PortalID; + objModule.TabID = PortalSettings.Current.ActiveTab.TabID; + objModule.ModuleOrder = position; + objModule.ModuleTitle = string.IsNullOrEmpty(title) ? objModuleDefinition.FriendlyName : title; + objModule.PaneName = paneName; + objModule.ModuleDefID = objModuleDefinition.ModuleDefID; + if (objModuleDefinition.DefaultCacheTime > 0) + { + objModule.CacheTime = objModuleDefinition.DefaultCacheTime; + if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger) + { + ModuleInfo defaultModule = ModuleController.Instance.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true); + if (defaultModule != null) + { + objModule.CacheTime = defaultModule.CacheTime; + } + } + } + + ModuleController.Instance.InitialModulePermission(objModule, objModule.TabID, permissionType); + + if (PortalSettings.Current.ContentLocalizationEnabled) + { + Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId); + + // check whether original tab is exists, if true then set culture code to default language, + // otherwise set culture code to current. + if (TabController.Instance.GetTabByCulture(objModule.TabID, PortalSettings.Current.PortalId, defaultLocale) != null) + { + objModule.CultureCode = defaultLocale.Code; + } + else + { + objModule.CultureCode = PortalSettings.Current.CultureCode; + } + } + else + { + objModule.CultureCode = Null.NullString; + } + + objModule.AllTabs = false; + objModule.Alignment = align; + + ModuleController.Instance.AddModule(objModule); + } + } + private void DoAddExistingModule(int moduleId, int tabId, string paneName, int position, string align, bool cloneModule) { ModuleInfo moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); int userID = -1; - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { UserInfo user = UserController.Instance.GetCurrentUserInfo(); - if (((user != null))) + if (user != null) { userID = user.UserID; } } - if ((moduleInfo != null)) + if (moduleInfo != null) { // Is this from a site other than our own? (i.e., is the user requesting "module sharing"?) var remote = moduleInfo.PortalID != PortalSettings.Current.PortalId; @@ -441,8 +542,9 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p { case ModuleSharing.Unsupported: // Should never happen since the module should not be listed in the first place. - throw new ApplicationException(string.Format("Module '{0}' does not support Shareable and should not be listed in Add Existing Module from a different source site", - moduleInfo.DesktopModule.FriendlyName)); + throw new ApplicationException(string.Format( + "Module '{0}' does not support Shareable and should not be listed in Add Existing Module from a different source site", + moduleInfo.DesktopModule.FriendlyName)); case ModuleSharing.Supported: break; default: @@ -461,11 +563,11 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p newModule.PaneName = paneName; newModule.Alignment = align; - if ((cloneModule)) + if (cloneModule) { newModule.ModuleID = Null.NullInteger; - //copy module settings and tab module settings + // copy module settings and tab module settings newModule.ModuleSettings.Clear(); foreach (var key in moduleInfo.ModuleSettings.Keys) { @@ -478,7 +580,7 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p newModule.TabModuleSettings.Add(key, moduleInfo.TabModuleSettings[key]); } - //reset the module id + // reset the module id newModule.ModuleID = ModuleController.Instance.AddModule(newModule); if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass)) @@ -504,7 +606,7 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p } else { - //copy tab module settings + // copy tab module settings newModule.TabModuleSettings.Clear(); foreach (var key in moduleInfo.TabModuleSettings.Keys) { @@ -516,97 +618,50 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p if (remote) { - //Ensure the Portal Admin has View rights + // Ensure the Portal Admin has View rights var permissionController = new PermissionController(); ArrayList arrSystemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); - AddModulePermission(newModule, - (PermissionInfo)arrSystemModuleViewPermissions[0], - PortalSettings.Current.AdministratorRoleId, - Null.NullInteger, - true); - - //Set PortalID correctly + AddModulePermission( + newModule, + (PermissionInfo)arrSystemModuleViewPermissions[0], + PortalSettings.Current.AdministratorRoleId, + Null.NullInteger, + true); + + // Set PortalID correctly newModule.OwnerPortalID = newModule.PortalID; newModule.PortalID = PortalSettings.Current.PortalId; ModulePermissionController.SaveModulePermissions(newModule); } - //Add Event Log - EventLogController.Instance.AddLog(newModule, PortalSettings.Current, userID, "", EventLogController.EventLogType.MODULE_CREATED); + // Add Event Log + EventLogController.Instance.AddLog(newModule, PortalSettings.Current, userID, string.Empty, EventLogController.EventLogType.MODULE_CREATED); } } - private static void SetCloneModuleContext(bool cloneModuleContext) - { - Thread.SetData(Thread.GetNamedDataSlot("CloneModuleContext"), - cloneModuleContext ? bool.TrueString : bool.FalseString); - } - - private static void DoAddNewModule(string title, int desktopModuleId, string paneName, int position, int permissionType, string align) + private static bool GetIsPortable(string moduleID, string tabID) { - try - { - DesktopModuleInfo desktopModule; - if (!DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId).TryGetValue(desktopModuleId, out desktopModule)) - { - throw new ArgumentException("desktopModuleId"); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - foreach (ModuleDefinitionInfo objModuleDefinition in - ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values) - { - var objModule = new ModuleInfo(); - objModule.Initialize(PortalSettings.Current.ActiveTab.PortalID); - - objModule.PortalID = PortalSettings.Current.ActiveTab.PortalID; - objModule.TabID = PortalSettings.Current.ActiveTab.TabID; - objModule.ModuleOrder = position; - objModule.ModuleTitle = string.IsNullOrEmpty(title) ? objModuleDefinition.FriendlyName : title; - objModule.PaneName = paneName; - objModule.ModuleDefID = objModuleDefinition.ModuleDefID; - if (objModuleDefinition.DefaultCacheTime > 0) - { - objModule.CacheTime = objModuleDefinition.DefaultCacheTime; - if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger) - { - ModuleInfo defaultModule = ModuleController.Instance.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true); - if ((defaultModule != null)) - { - objModule.CacheTime = defaultModule.CacheTime; - } - } - } + bool isPortable = false; + int parsedModuleID; + int parsedTabID; - ModuleController.Instance.InitialModulePermission(objModule, objModule.TabID, permissionType); + bool validModuleID = int.TryParse(moduleID, out parsedModuleID); + bool validTabID = int.TryParse(tabID, out parsedTabID); - if (PortalSettings.Current.ContentLocalizationEnabled) + if (validModuleID && validTabID) + { + ModuleInfo moduleInfo = ModuleController.Instance.GetModule(parsedModuleID, parsedTabID, false); + if (moduleInfo != null) { - Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId); - //check whether original tab is exists, if true then set culture code to default language, - //otherwise set culture code to current. - if (TabController.Instance.GetTabByCulture(objModule.TabID, PortalSettings.Current.PortalId, defaultLocale) != null) - { - objModule.CultureCode = defaultLocale.Code; - } - else + DesktopModuleInfo moduleDesktopInfo = moduleInfo.DesktopModule; + if (moduleDesktopInfo != null) { - objModule.CultureCode = PortalSettings.Current.CultureCode; + isPortable = moduleDesktopInfo.IsPortable; } } - else - { - objModule.CultureCode = Null.NullString; - } - objModule.AllTabs = false; - objModule.Alignment = align; - - ModuleController.Instance.AddModule(objModule); } + + return isPortable; } private IEnumerable GetCurrentPortalsGroup() @@ -615,9 +670,9 @@ private IEnumerable GetCurrentPortalsGroup() var result = (from @group in groups select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); // Are we in a group of one? if (result == null || result.Length == 0) @@ -628,132 +683,105 @@ where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) return result; } - private static bool GetIsPortable(string moduleID, string tabID) - { - bool isPortable = false; - int parsedModuleID; - int parsedTabID; - - bool validModuleID = int.TryParse(moduleID, out parsedModuleID); - bool validTabID = int.TryParse(tabID, out parsedTabID); - - if ((validModuleID && validTabID)) - { - ModuleInfo moduleInfo = ModuleController.Instance.GetModule(parsedModuleID, parsedTabID, false); - if (((moduleInfo != null))) - { - DesktopModuleInfo moduleDesktopInfo = moduleInfo.DesktopModule; - if (((moduleDesktopInfo != null))) - { - isPortable = moduleDesktopInfo.IsPortable; - } - } - } - - return isPortable; - } - - protected string GetString(string key) + private void LoadAllLists() { - return Localization.GetString(key, LocalResourceFile); + this.LoadSiteList(); + this.LoadCategoryList(); + this.LoadPageList(); + this.LoadModuleList(); + this.LoadVisibilityList(); + this.LoadPaneList(); + this.LoadPositionList(); + this.LoadPaneModulesList(); } - private void LoadAllLists() - { - LoadSiteList(); - LoadCategoryList(); - LoadPageList(); - LoadModuleList(); - LoadVisibilityList(); - LoadPaneList(); - LoadPositionList(); - LoadPaneModulesList(); - } - private void LoadCategoryList() { - CategoryListPanel.Visible = !AddExistingModule.Checked; + this.CategoryListPanel.Visible = !this.AddExistingModule.Checked; ITermController termController = Util.GetTermController(); - CategoryList.DataSource = termController.GetTermsByVocabulary("Module_Categories").OrderBy(t => t.Weight).Where(t => t.Name != "< None >").ToList(); - CategoryList.DataBind(); - //CategoryList.Items.Add(new ListItem(Localization.GetString("AllCategories", LocalResourceFile), "All")); - CategoryList.AddItem(Localization.GetString("AllCategories", LocalResourceFile), "All"); - if (!IsPostBack) + this.CategoryList.DataSource = termController.GetTermsByVocabulary("Module_Categories").OrderBy(t => t.Weight).Where(t => t.Name != "< None >").ToList(); + this.CategoryList.DataBind(); + + // CategoryList.Items.Add(new ListItem(Localization.GetString("AllCategories", LocalResourceFile), "All")); + this.CategoryList.AddItem(Localization.GetString("AllCategories", this.LocalResourceFile), "All"); + if (!this.IsPostBack) { - CategoryList.Select("Common", false); + this.CategoryList.Select("Common", false); } } private void LoadModuleList() { - if (AddExistingModule.Checked) + if (this.AddExistingModule.Checked) { - //Get list of modules for the selected tab - if (!string.IsNullOrEmpty(PageLst.SelectedValue)) + // Get list of modules for the selected tab + if (!string.IsNullOrEmpty(this.PageLst.SelectedValue)) { - var tabId = int.Parse(PageLst.SelectedValue); + var tabId = int.Parse(this.PageLst.SelectedValue); if (tabId >= 0) { - ModuleLst.BindTabModulesByTabID(tabId); + this.ModuleLst.BindTabModulesByTabID(tabId); } - if ((ModuleLst.ItemCount > 0)) + + if (this.ModuleLst.ItemCount > 0) { - chkCopyModule.Visible = true; - SetCopyModuleMessage(GetIsPortable(ModuleLst.SelectedValue, PageLst.SelectedValue)); + this.chkCopyModule.Visible = true; + this.SetCopyModuleMessage(GetIsPortable(this.ModuleLst.SelectedValue, this.PageLst.SelectedValue)); } } } else { - ModuleLst.Filter = CategoryList.SelectedValue == "All" + this.ModuleLst.Filter = this.CategoryList.SelectedValue == "All" ? (kvp => true) - : (Func, bool>)(kvp => kvp.Value.DesktopModule.Category == CategoryList.SelectedValue); - ModuleLst.BindAllPortalDesktopModules(); + : (Func, bool>)(kvp => kvp.Value.DesktopModule.Category == this.CategoryList.SelectedValue); + this.ModuleLst.BindAllPortalDesktopModules(); } - ModuleLst.Enabled = ModuleLst.ItemCount > 0; + this.ModuleLst.Enabled = this.ModuleLst.ItemCount > 0; } private void LoadPageList() - { - PageListPanel.Visible = AddExistingModule.Checked; - TitlePanel.Enabled = !AddExistingModule.Checked; - chkCopyModule.Visible = AddExistingModule.Checked; + { + this.PageListPanel.Visible = this.AddExistingModule.Checked; + this.TitlePanel.Enabled = !this.AddExistingModule.Checked; + this.chkCopyModule.Visible = this.AddExistingModule.Checked; - if ((AddExistingModule.Checked)) - { - chkCopyModule.Text = Localization.GetString("CopyModuleDefault.Text", LocalResourceFile); - } + if (this.AddExistingModule.Checked) + { + this.chkCopyModule.Text = Localization.GetString("CopyModuleDefault.Text", this.LocalResourceFile); + } - var portalSettings = SelectedPortalSettings; + var portalSettings = this.SelectedPortalSettings; - PageLst.Items.Clear(); + this.PageLst.Items.Clear(); - if (PageListPanel.Visible) + if (this.PageListPanel.Visible) { - PageLst.DataValueField = "TabID"; - PageLst.DataTextField = "IndentedTabName"; - if(PortalSettings.PortalId == SelectedPortalSettings.PortalId) + this.PageLst.DataValueField = "TabID"; + this.PageLst.DataTextField = "IndentedTabName"; + if (this.PortalSettings.PortalId == this.SelectedPortalSettings.PortalId) { - PageLst.DataSource = TabController.GetPortalTabs(portalSettings.PortalId, portalSettings.ActiveTab.TabID, true, string.Empty, true, false, false, false, true); + this.PageLst.DataSource = TabController.GetPortalTabs(portalSettings.PortalId, portalSettings.ActiveTab.TabID, true, string.Empty, true, false, false, false, true); } else { - PageLst.DataSource = TabController.GetPortalTabs(portalSettings.PortalId, Null.NullInteger, true, string.Empty, true, false, false, false, true); + this.PageLst.DataSource = TabController.GetPortalTabs(portalSettings.PortalId, Null.NullInteger, true, string.Empty, true, false, false, false, true); } - PageLst.DataBind(); - } - } + + this.PageLst.DataBind(); + } + } private void LoadPaneList() { - PaneLst.Items.Clear(); - PaneLst.DataSource = PortalSettings.Current.ActiveTab.Panes; - PaneLst.DataBind(); - if ((PortalSettings.Current.ActiveTab.Panes.Contains(Globals.glbDefaultPane))) + this.PaneLst.Items.Clear(); + this.PaneLst.DataSource = PortalSettings.Current.ActiveTab.Panes; + this.PaneLst.DataBind(); + if (PortalSettings.Current.ActiveTab.Panes.Contains(Globals.glbDefaultPane)) { - PaneLst.SelectedValue = Globals.glbDefaultPane; + this.PaneLst.SelectedValue = Globals.glbDefaultPane; } } @@ -763,13 +791,13 @@ private void LoadPaneModulesList() foreach (ModuleInfo m in PortalSettings.Current.ActiveTab.Modules) { - //if user is allowed to view module and module is not deleted + // if user is allowed to view module and module is not deleted if (ModulePermissionController.CanViewModule(m) && !m.IsDeleted) { - //modules which are displayed on all tabs should not be displayed on the Admin or Super tabs + // modules which are displayed on all tabs should not be displayed on the Admin or Super tabs if (!m.AllTabs || !PortalSettings.Current.ActiveTab.IsSuperTab) { - if (m.PaneName == PaneLst.SelectedValue) + if (m.PaneName == this.PaneLst.SelectedValue) { int moduleOrder = m.ModuleOrder; @@ -777,127 +805,108 @@ private void LoadPaneModulesList() { moduleOrder++; } + items.Add(moduleOrder.ToString(), m.ModuleTitle); } } } } - PaneModulesLst.Enabled = true; - PaneModulesLst.Items.Clear(); - PaneModulesLst.DataValueField = "key"; - PaneModulesLst.DataTextField = "value"; - PaneModulesLst.DataSource = items; - PaneModulesLst.DataBind(); + this.PaneModulesLst.Enabled = true; + this.PaneModulesLst.Items.Clear(); + this.PaneModulesLst.DataValueField = "key"; + this.PaneModulesLst.DataTextField = "value"; + this.PaneModulesLst.DataSource = items; + this.PaneModulesLst.DataBind(); - if ((PaneModulesLst.Items.Count <= 1)) + if (this.PaneModulesLst.Items.Count <= 1) { - var listItem = PositionLst.FindItemByValue("ABOVE"); - if (((listItem != null))) + var listItem = this.PositionLst.FindItemByValue("ABOVE"); + if (listItem != null) { - PositionLst.Items.Remove(listItem); + this.PositionLst.Items.Remove(listItem); } - listItem = PositionLst.FindItemByValue("BELOW"); - if (((listItem != null))) + + listItem = this.PositionLst.FindItemByValue("BELOW"); + if (listItem != null) { - PositionLst.Items.Remove(listItem); + this.PositionLst.Items.Remove(listItem); } - PaneModulesLst.Enabled = false; + + this.PaneModulesLst.Enabled = false; } - if ((PositionLst.SelectedValue == "TOP" || PositionLst.SelectedValue == "BOTTOM")) + if (this.PositionLst.SelectedValue == "TOP" || this.PositionLst.SelectedValue == "BOTTOM") { - PaneModulesLst.Enabled = false; + this.PaneModulesLst.Enabled = false; } } private void LoadPositionList() { var items = new Dictionary - { - {"TOP", GetString("Top")}, - {"ABOVE", GetString("Above")}, - {"BELOW", GetString("Below")}, - {"BOTTOM", GetString("Bottom")} - }; - - PositionLst.Items.Clear(); - PositionLst.DataValueField = "key"; - PositionLst.DataTextField = "value"; - PositionLst.DataSource = items; - PositionLst.DataBind(); - PositionLst.SelectedValue = "BOTTOM"; + { + { "TOP", this.GetString("Top") }, + { "ABOVE", this.GetString("Above") }, + { "BELOW", this.GetString("Below") }, + { "BOTTOM", this.GetString("Bottom") }, + }; + + this.PositionLst.Items.Clear(); + this.PositionLst.DataValueField = "key"; + this.PositionLst.DataTextField = "value"; + this.PositionLst.DataSource = items; + this.PositionLst.DataBind(); + this.PositionLst.SelectedValue = "BOTTOM"; } private void LoadSiteList() { // Is there more than one site in this group? - var multipleSites = GetCurrentPortalsGroup().Count() > 1; + var multipleSites = this.GetCurrentPortalsGroup().Count() > 1; - SiteListPanel.Visible = multipleSites && AddExistingModule.Checked; + this.SiteListPanel.Visible = multipleSites && this.AddExistingModule.Checked; - if (SiteListPanel.Visible) + if (this.SiteListPanel.Visible) { // Get a list of portals in this SiteGroup. var portals = PortalController.Instance.GetPortals().Cast().ToArray(); - SiteList.DataSource = portals.Select( - x => new {Value = x.PortalID, Name = x.PortalName, GroupID = x.PortalGroupID}).ToList(); - SiteList.DataTextField = "Name"; - SiteList.DataValueField = "Value"; - SiteList.DataBind(); + this.SiteList.DataSource = portals.Select( + x => new { Value = x.PortalID, Name = x.PortalName, GroupID = x.PortalGroupID }).ToList(); + this.SiteList.DataTextField = "Name"; + this.SiteList.DataValueField = "Value"; + this.SiteList.DataBind(); } } - private void LoadVisibilityList() - { - VisibilityLst.Enabled = !AddExistingModule.Checked; - if ((VisibilityLst.Enabled)) - { - var items = new Dictionary {{"0", GetString("PermissionView")}, {"1", GetString("PermissionEdit")}}; - - VisibilityLst.Items.Clear(); - VisibilityLst.DataValueField = "key"; - VisibilityLst.DataTextField = "value"; - VisibilityLst.DataSource = items; - VisibilityLst.DataBind(); - } - } - - private string LocalResourceFile + private void LoadVisibilityList() { - get + this.VisibilityLst.Enabled = !this.AddExistingModule.Checked; + if (this.VisibilityLst.Enabled) { - return string.Format("{0}/{1}/{2}.ascx.resx", TemplateSourceDirectory, Localization.LocalResourceDirectory, GetType().BaseType.Name); + var items = new Dictionary { { "0", this.GetString("PermissionView") }, { "1", this.GetString("PermissionEdit") } }; + + this.VisibilityLst.Items.Clear(); + this.VisibilityLst.DataValueField = "key"; + this.VisibilityLst.DataTextField = "value"; + this.VisibilityLst.DataSource = items; + this.VisibilityLst.DataBind(); } } private void SetCopyModuleMessage(bool isPortable) { - if ((isPortable)) + if (isPortable) { - chkCopyModule.Text = Localization.GetString("CopyModuleWcontent", LocalResourceFile); - chkCopyModule.ToolTip = Localization.GetString("CopyModuleWcontent.ToolTip", LocalResourceFile); + this.chkCopyModule.Text = Localization.GetString("CopyModuleWcontent", this.LocalResourceFile); + this.chkCopyModule.ToolTip = Localization.GetString("CopyModuleWcontent.ToolTip", this.LocalResourceFile); } else { - chkCopyModule.Text = Localization.GetString("CopyModuleWOcontent", LocalResourceFile); - chkCopyModule.ToolTip = Localization.GetString("CopyModuleWOcontent.ToolTip", LocalResourceFile); - } - } - - #endregion - - - public bool CanAddModuleToPage() - { - if (HttpContext.Current == null) - { - return false; + this.chkCopyModule.Text = Localization.GetString("CopyModuleWOcontent", this.LocalResourceFile); + this.chkCopyModule.ToolTip = Localization.GetString("CopyModuleWOcontent.ToolTip", this.LocalResourceFile); } - //If we are not in an edit page - return (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) && (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); - } - + } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs index b385d6097b3..86d913c6d7b 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs @@ -1,66 +1,101 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.UI; -using DotNetNuke.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.ControlPanel { - using DotNetNuke.Abstractions; + using System; + using System.Collections; + using System.IO; + using System.Web.UI; using System.Web.UI.WebControls; - + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.UI; + using DotNetNuke.Web.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + public partial class AddPage : UserControl, IDnnRibbonBarTool { private readonly INavigationManager _navigationManager; + + private TabInfo _newTabObject; + public AddPage() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } + + public override bool Visible + { + get + { + return base.Visible && TabPermissionController.CanAddPage(); + } + + set + { + base.Visible = value; + } } - #region "Event Handlers" + public string ToolName + { + get + { + return "QuickAddPage"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } + } + protected TabInfo NewTabObject + { + get + { + if (this._newTabObject == null) + { + this._newTabObject = RibbonBarManager.InitTabInfoObject(PortalSettings.ActiveTab); + } + + return this._newTabObject; + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdAddPage.Click += CmdAddPageClick; + this.cmdAddPage.Click += this.CmdAddPageClick; try { if (PortalSettings.Pages < PortalSettings.PageQuota || UserController.Instance.GetCurrentUserInfo().IsSuperUser || PortalSettings.PageQuota == 0) { - cmdAddPage.Enabled = true; + this.cmdAddPage.Enabled = true; } else { - cmdAddPage.Enabled = false; - cmdAddPage.ToolTip = Localization.GetString("ExceededQuota", LocalResourceFile); + this.cmdAddPage.Enabled = false; + this.cmdAddPage.ToolTip = Localization.GetString("ExceededQuota", this.LocalResourceFile); } - if (!IsPostBack) + + if (!this.IsPostBack) { - if ((Visible)) + if (this.Visible) { - LoadAllLists(); + this.LoadAllLists(); } } } @@ -72,23 +107,23 @@ protected override void OnLoad(EventArgs e) protected void CmdAddPageClick(object sender, EventArgs e) { - int selectedTabID = Int32.Parse(PageLst.SelectedValue); + int selectedTabID = int.Parse(this.PageLst.SelectedValue); TabInfo selectedTab = TabController.Instance.GetTab(selectedTabID, PortalSettings.ActiveTab.PortalID, false); - var tabLocation = (TabRelativeLocation) Enum.Parse(typeof (TabRelativeLocation), LocationLst.SelectedValue); + var tabLocation = (TabRelativeLocation)Enum.Parse(typeof(TabRelativeLocation), this.LocationLst.SelectedValue); TabInfo newTab = RibbonBarManager.InitTabInfoObject(selectedTab, tabLocation); - newTab.TabName = Name.Text; - newTab.IsVisible = IncludeInMenu.Checked; + newTab.TabName = this.Name.Text; + newTab.IsVisible = this.IncludeInMenu.Checked; string errMsg = string.Empty; try { - RibbonBarManager.SaveTabInfoObject(newTab, selectedTab, tabLocation, TemplateLst.SelectedValue); + RibbonBarManager.SaveTabInfoObject(newTab, selectedTab, tabLocation, this.TemplateLst.SelectedValue); } catch (DotNetNukeException ex) { Exceptions.LogException(ex); - errMsg = (ex.ErrorCode != DotNetNukeErrorCode.NotSet) ? GetString("Err." + ex.ErrorCode) : ex.Message; + errMsg = (ex.ErrorCode != DotNetNukeErrorCode.NotSet) ? this.GetString("Err." + ex.ErrorCode) : ex.Message; } catch (Exception ex) { @@ -96,70 +131,32 @@ protected void CmdAddPageClick(object sender, EventArgs e) errMsg = ex.Message; } - //Clear the Tab's Cached modules + // Clear the Tab's Cached modules DataCache.ClearModuleCache(PortalSettings.ActiveTab.TabID); - //Update Cached Tabs as TabPath may be needed before cache is cleared + // Update Cached Tabs as TabPath may be needed before cache is cleared TabInfo tempTab; if (TabController.Instance.GetTabsByPortal(PortalSettings.ActiveTab.PortalID).TryGetValue(newTab.TabID, out tempTab)) { tempTab.TabPath = newTab.TabPath; } - if ((string.IsNullOrEmpty(errMsg))) + if (string.IsNullOrEmpty(errMsg)) { - Response.Redirect(_navigationManager.NavigateURL(newTab.TabID)); + this.Response.Redirect(this._navigationManager.NavigateURL(newTab.TabID)); } else { - errMsg = string.Format("

{0}

{1}

", GetString("Err.Header"), errMsg); - Web.UI.Utilities.RegisterAlertOnPageLoad(this, new MessageWindowParameters(errMsg) { Title = GetString("Err.Title")}); - } - } - - #endregion - - #region "Properties" - - public override bool Visible - { - get - { - return base.Visible && TabPermissionController.CanAddPage(); - } - set - { - base.Visible = value; - } - } - - public string ToolName - { - get - { - return "QuickAddPage"; - } - set - { - throw new NotSupportedException("Set ToolName not supported"); + errMsg = string.Format("

{0}

{1}

", this.GetString("Err.Header"), errMsg); + Web.UI.Utilities.RegisterAlertOnPageLoad(this, new MessageWindowParameters(errMsg) { Title = this.GetString("Err.Title") }); } - } + } - #endregion - - #region "Methods" - - private TabInfo _newTabObject; - - protected TabInfo NewTabObject + private static PortalSettings PortalSettings { get { - if (((_newTabObject == null))) - { - _newTabObject = RibbonBarManager.InitTabInfoObject(PortalSettings.ActiveTab); - } - return _newTabObject; + return PortalSettings.Current; } } @@ -167,73 +164,64 @@ private string LocalResourceFile { get { - return string.Format("{0}/{1}/{2}.ascx.resx", TemplateSourceDirectory, Localization.LocalResourceDirectory, GetType().BaseType.Name); - } - } - - private static PortalSettings PortalSettings - { - get - { - return PortalSettings.Current; + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); } } private void LoadAllLists() { - LoadLocationList(); - LoadTemplateList(); - LoadPageList(); + this.LoadLocationList(); + this.LoadTemplateList(); + this.LoadPageList(); } private void LoadTemplateList() { - TemplateLst.ClearSelection(); - TemplateLst.Items.Clear(); + this.TemplateLst.ClearSelection(); + this.TemplateLst.Items.Clear(); - //Get Templates Folder + // Get Templates Folder ArrayList templateFiles = Globals.GetFileList(PortalSettings.PortalId, "page.template", false, "Templates/"); foreach (FileItem dnnFile in templateFiles) { - var item = new DnnComboBoxItem(dnnFile.Text.Replace(".page.template", ""), dnnFile.Value); - TemplateLst.Items.Add(item); + var item = new DnnComboBoxItem(dnnFile.Text.Replace(".page.template", string.Empty), dnnFile.Value); + this.TemplateLst.Items.Add(item); if (item.Text == "Default") { item.Selected = true; } } - TemplateLst.InsertItem(0, GetString("NoTemplate"), ""); + this.TemplateLst.InsertItem(0, this.GetString("NoTemplate"), string.Empty); } private void LoadLocationList() { - LocationLst.ClearSelection(); - LocationLst.Items.Clear(); - - //LocationLst.Items.Add(new ListItem(GetString("Before"), "BEFORE")); - //LocationLst.Items.Add(new ListItem(GetString("After"), "AFTER")); - //LocationLst.Items.Add(new ListItem(GetString("Child"), "CHILD")); + this.LocationLst.ClearSelection(); + this.LocationLst.Items.Clear(); - LocationLst.AddItem(GetString("Before"), "BEFORE"); - LocationLst.AddItem(GetString("After"), "AFTER"); - LocationLst.AddItem(GetString("Child"), "CHILD"); + // LocationLst.Items.Add(new ListItem(GetString("Before"), "BEFORE")); + // LocationLst.Items.Add(new ListItem(GetString("After"), "AFTER")); + // LocationLst.Items.Add(new ListItem(GetString("Child"), "CHILD")); + this.LocationLst.AddItem(this.GetString("Before"), "BEFORE"); + this.LocationLst.AddItem(this.GetString("After"), "AFTER"); + this.LocationLst.AddItem(this.GetString("Child"), "CHILD"); - LocationLst.SelectedIndex = (!PortalSecurity.IsInRole("Administrators")) ? 2 : 1; + this.LocationLst.SelectedIndex = (!PortalSecurity.IsInRole("Administrators")) ? 2 : 1; } private void LoadPageList() { - PageLst.ClearSelection(); - PageLst.Items.Clear(); + this.PageLst.ClearSelection(); + this.PageLst.Items.Clear(); - PageLst.DataTextField = "IndentedTabName"; - PageLst.DataValueField = "TabID"; - PageLst.DataSource = RibbonBarManager.GetPagesList(); - PageLst.DataBind(); + this.PageLst.DataTextField = "IndentedTabName"; + this.PageLst.DataValueField = "TabID"; + this.PageLst.DataSource = RibbonBarManager.GetPagesList(); + this.PageLst.DataBind(); - var item = PageLst.FindItemByValue(PortalSettings.ActiveTab.TabID.ToString()); - if (((item != null))) + var item = this.PageLst.FindItemByValue(PortalSettings.ActiveTab.TabID.ToString()); + if (item != null) { item.Selected = true; } @@ -241,9 +229,7 @@ private void LoadPageList() private string GetString(string key) { - return Localization.GetString(key, LocalResourceFile); - } - - #endregion + return Localization.GetString(key, this.LocalResourceFile); + } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs index 465d8362368..53983b3dcc1 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs @@ -1,63 +1,64 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web; -using Microsoft.Extensions.DependencyInjection; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Application; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.ImprovementsProgram; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.Common; -using DotNetNuke.Web.UI.WebControls; -using DotNetNuke.Services.Personalization; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Components.Controllers; -using DotNetNuke.Web.Components.Controllers.Models; -using Globals = DotNetNuke.Common.Globals; -using DotNetNuke.Abstractions; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.UI.ControlPanels + // ReSharper restore CheckNamespace { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Application; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.ImprovementsProgram; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.Common; + using DotNetNuke.Web.Components.Controllers; + using DotNetNuke.Web.Components.Controllers.Models; + using DotNetNuke.Web.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; + public partial class ControlBar : ControlPanelBase { + protected DnnFileUpload FileUploader; + private readonly INavigationManager _navigationManager; - public ControlBar() - { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); - } - private readonly IList _adminCommonTabs = new List { "Site Settings", + private readonly IList _adminCommonTabs = new List + { + "Site Settings", "Security Roles", "User Accounts", - "File Management" }; + "File Management", + }; - private readonly IList _hostCommonTabs = new List { "Host Settings", + private readonly IList _hostCommonTabs = new List + { + "Host Settings", "Site Management", "File Management", "Extensions", @@ -65,9 +66,31 @@ public ControlBar() "Health Monitoring", "Technical Support", "Knowledge Base", - "Software and Documentation" }; + "Software and Documentation", + }; + + private List _adminBookmarkItems; + + public ControlBar() + { + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } - protected DnnFileUpload FileUploader; + private List _hostBookmarkItems; + + private List _adminTabs; + private List _adminBaseTabs; + private List _adminAdvancedTabs; + + public override bool IsDockable { get; set; } + + public override bool IncludeInControlHierarchy + { + get + { + return base.IncludeInControlHierarchy && (this.IsPageAdmin() || this.IsModuleAdmin()); + } + } protected string CurrentUICulture { get; set; } @@ -79,7 +102,7 @@ protected string BookmarkModuleCategory { get { - return ControlBarController.Instance.GetBookmarkCategory(PortalSettings.PortalId); + return ControlBarController.Instance.GetBookmarkCategory(this.PortalSettings.PortalId); } } @@ -87,40 +110,71 @@ protected string BookmarkedModuleKeys { get { - var bookmarkModules = Personalization.GetProfile("ControlBar", "module" + PortalSettings.PortalId); + var bookmarkModules = Personalization.GetProfile("ControlBar", "module" + this.PortalSettings.PortalId); if (bookmarkModules == null) { return string.Empty; } + return bookmarkModules.ToString(); } } - - public override bool IsDockable { get; set; } - - public override bool IncludeInControlHierarchy + + protected List AdminBookmarkItems { get { - return base.IncludeInControlHierarchy && (IsPageAdmin() || IsModuleAdmin()); + if (this._adminBookmarkItems == null) + { + var bookmarkItems = Personalization.GetProfile("ControlBar", "admin" + this.PortalSettings.PortalId); + + this._adminBookmarkItems = bookmarkItems != null + ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() + : new List(); + } + + return this._adminBookmarkItems; } } + + protected List HostBookmarkItems + { + get + { + if (this._hostBookmarkItems == null) + { + var bookmarkItems = Personalization.GetProfile("ControlBar", "host" + this.PortalSettings.PortalId); - #region Event Handlers + this._hostBookmarkItems = bookmarkItems != null + ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() + : new List(); + } + return this._hostBookmarkItems; + } + } + + private new string LocalResourceFile + { + get + { + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType?.Name); + } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); - //page will be null if the control panel initial twice, it will be removed in the second time. - if (Page != null) + // page will be null if the control panel initial twice, it will be removed in the second time. + if (this.Page != null) { - ID = "ControlBar"; + this.ID = "ControlBar"; - FileUploader = new DnnFileUpload {ID = "fileUploader", SupportHost = false}; - Page.Form.Controls.Add(FileUploader); + this.FileUploader = new DnnFileUpload { ID = "fileUploader", SupportHost = false }; + this.Page.Form.Controls.Add(this.FileUploader); - LoadCustomMenuItems(); + this.LoadCustomMenuItems(); } } @@ -128,53 +182,49 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (PortalSettings.EnablePopUps && Host.EnableModuleOnLineHelp) + if (this.PortalSettings.EnablePopUps && Host.EnableModuleOnLineHelp) { - helpLink.Text = string.Format(@"
  • {1}
  • ", UrlUtils.PopUpUrl(Host.HelpURL, this, PortalSettings, false, false), GetString("Tool.Help.ToolTip")); + this.helpLink.Text = string.Format(@"
  • {1}
  • ", UrlUtils.PopUpUrl(Host.HelpURL, this, this.PortalSettings, false, false), this.GetString("Tool.Help.ToolTip")); } else if (Host.EnableModuleOnLineHelp) { - helpLink.Text = string.Format(@"
  • {1}
  • ", Host.HelpURL, GetString("Tool.Help.ToolTip")); + this.helpLink.Text = string.Format(@"
  • {1}
  • ", Host.HelpURL, this.GetString("Tool.Help.ToolTip")); } - LoginUrl = ResolveClientUrl(@"~/Login.aspx"); + this.LoginUrl = this.ResolveClientUrl(@"~/Login.aspx"); - if (ControlPanel.Visible && IncludeInControlHierarchy) + if (this.ControlPanel.Visible && this.IncludeInControlHierarchy) { - ClientResourceManager.RegisterStyleSheet(Page, "~/admin/ControlPanel/ControlBar.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/admin/ControlPanel/ControlBar.css", FileOrder.Css.ResourceCss); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ClientResourceManager.RegisterScript(Page, "~/resources/shared/scripts/dnn.controlBar.js"); + ClientResourceManager.RegisterScript(this.Page, "~/resources/shared/scripts/dnn.controlBar.js"); // Is there more than one site in this group? var multipleSites = GetCurrentPortalsGroup().Count() > 1; - ClientAPI.RegisterClientVariable(Page, "moduleSharing", multipleSites.ToString().ToLowerInvariant(), true); + ClientAPI.RegisterClientVariable(this.Page, "moduleSharing", multipleSites.ToString().ToLowerInvariant(), true); } ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); var multipleSite = false; - conrolbar_logo.ImageUrl = ControlBarController.Instance.GetControlBarLogoURL(); - if (!IsPostBack) + this.conrolbar_logo.ImageUrl = ControlBarController.Instance.GetControlBarLogoURL(); + if (!this.IsPostBack) { - LoadCategoryList(); - multipleSite = LoadSiteList(); - LoadVisibilityList(); - AutoSetUserMode(); - BindPortalsList(); - BindLanguagesList(); + this.LoadCategoryList(); + multipleSite = this.LoadSiteList(); + this.LoadVisibilityList(); + this.AutoSetUserMode(); + this.BindPortalsList(); + this.BindLanguagesList(); } - LoadTabModuleMessage = multipleSite ? GetString("LoadingTabModuleCE.Text") : GetString("LoadingTabModule.Text"); - } - - #endregion - - #region Protected Methods - + this.LoadTabModuleMessage = multipleSite ? this.GetString("LoadingTabModuleCE.Text") : this.GetString("LoadingTabModule.Text"); + } + protected bool CheckPageQuota() { UserInfo objUser = UserController.Instance.GetCurrentUserInfo(); - return (objUser != null && objUser.IsSuperUser) || PortalSettings.PageQuota == 0 || PortalSettings.Pages < PortalSettings.PageQuota; + return (objUser != null && objUser.IsSuperUser) || this.PortalSettings.PageQuota == 0 || this.PortalSettings.Pages < this.PortalSettings.PageQuota; } protected string GetUpgradeIndicator() @@ -183,74 +233,57 @@ protected string GetUpgradeIndicator() if (objUser != null && objUser.IsSuperUser) { - var upgradeIndicator = ControlBarController.Instance.GetUpgradeIndicator(DotNetNukeContext.Current.Application.Version, - Request.IsLocal, Request.IsSecureConnection); + var upgradeIndicator = ControlBarController.Instance.GetUpgradeIndicator( + DotNetNukeContext.Current.Application.Version, + this.Request.IsLocal, this.Request.IsSecureConnection); if (upgradeIndicator == null) { - return String.Empty; + return string.Empty; } - return GetUpgradeIndicatorButton(upgradeIndicator); + + return this.GetUpgradeIndicatorButton(upgradeIndicator); } return string.Empty; } - private void LoadCustomMenuItems() + protected string PreviewPopup() { - foreach (var menuItem in ControlBarController.Instance.GetCustomMenuItems()) - { - var liElement = new HtmlGenericControl("li"); - liElement.Attributes.Add("id", menuItem.ID + "_tab"); - - var control = Page.LoadControl(menuItem.Source); - control.ID = menuItem.ID; - - liElement.Controls.Add(control); + var previewUrl = string.Format( + "{0}/Default.aspx?ctl={1}&previewTab={2}&TabID={2}", + Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias), + "MobilePreview", + this.PortalSettings.ActiveTab.TabID); - CustomMenuItems.Controls.Add(liElement); + if (this.PortalSettings.EnablePopUps) + { + return UrlUtils.PopUpUrl(previewUrl, this, this.PortalSettings, true, false, 660, 800); } - } - - private string GetUpgradeIndicatorButton(UpgradeIndicatorViewModel upgradeIndicator) - { - return string.Format("\"{4}\"", - upgradeIndicator.ID, upgradeIndicator.WebAction, upgradeIndicator.CssClass, ResolveClientUrl(upgradeIndicator.ImageUrl), upgradeIndicator.AltText, upgradeIndicator.ToolTip); - } - - protected string PreviewPopup() - { - var previewUrl = string.Format("{0}/Default.aspx?ctl={1}&previewTab={2}&TabID={2}", - Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias), - "MobilePreview", - PortalSettings.ActiveTab.TabID); - - if(PortalSettings.EnablePopUps) - { - return UrlUtils.PopUpUrl(previewUrl, this, PortalSettings, true, false, 660, 800); - } return string.Format("location.href = \"{0}\"", previewUrl); - } + } protected IEnumerable LoadPaneList() { ArrayList panes = PortalSettings.Current.ActiveTab.Panes; var resultPanes = new List(); - if(panes.Count < 4 ) + if (panes.Count < 4) { foreach (var p in panes) { - var topPane = new[]{ - string.Format(GetString("Pane.AddTop.Text"), p), + var topPane = new[] + { + string.Format(this.GetString("Pane.AddTop.Text"), p), p.ToString(), - "TOP" + "TOP", }; - var botPane = new[]{ - string.Format(GetString("Pane.AddBottom.Text"), p), + var botPane = new[] + { + string.Format(this.GetString("Pane.AddBottom.Text"), p), p.ToString(), - "BOTTOM" + "BOTTOM", }; resultPanes.Add(topPane); @@ -261,11 +294,11 @@ protected IEnumerable LoadPaneList() { foreach (var p in panes) { - - var botPane = new[]{ - string.Format(GetString("Pane.Add.Text"), p), + var botPane = new[] + { + string.Format(this.GetString("Pane.Add.Text"), p), p.ToString(), - "BOTTOM" + "BOTTOM", }; resultPanes.Add(botPane); @@ -275,10 +308,32 @@ protected IEnumerable LoadPaneList() return resultPanes; } + private void LoadCustomMenuItems() + { + foreach (var menuItem in ControlBarController.Instance.GetCustomMenuItems()) + { + var liElement = new HtmlGenericControl("li"); + liElement.Attributes.Add("id", menuItem.ID + "_tab"); + + var control = this.Page.LoadControl(menuItem.Source); + control.ID = menuItem.ID; + + liElement.Controls.Add(control); + this.CustomMenuItems.Controls.Add(liElement); + } + } + + private string GetUpgradeIndicatorButton(UpgradeIndicatorViewModel upgradeIndicator) + { + return string.Format( + "\"{4}\"", + upgradeIndicator.ID, upgradeIndicator.WebAction, upgradeIndicator.CssClass, this.ResolveClientUrl(upgradeIndicator.ImageUrl), upgradeIndicator.AltText, upgradeIndicator.ToolTip); + } + protected string GetString(string key) { - return Localization.GetString(key, LocalResourceFile); + return Localization.GetString(key, this.LocalResourceFile); } protected string BuildToolUrl(string toolName, bool isHostTool, string moduleFriendlyName, @@ -300,79 +355,91 @@ protected string BuildToolUrl(string toolName, bool isHostTool, string moduleFri case "PageSettings": if (TabPermissionController.CanManagePage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=settingTab"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=settingTab"); } + break; case "CopyPage": if (TabPermissionController.CanCopyPage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=copy&activeTab=copyTab"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=copy&activeTab=copyTab"); } + break; case "DeletePage": if (TabPermissionController.CanDeletePage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=delete"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=delete"); } + break; case "PageTemplate": if (TabPermissionController.CanManagePage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=advancedTab"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=advancedTab"); } + break; case "PageLocalization": if (TabPermissionController.CanManagePage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=localizationTab"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=localizationTab"); } + break; case "PagePermission": if (TabPermissionController.CanAdminPage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=permissionsTab"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=permissionsTab"); } + break; case "ImportPage": if (TabPermissionController.CanImportPage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "ImportTab"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "ImportTab"); } + break; case "ExportPage": if (TabPermissionController.CanExportPage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "ExportTab"); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "ExportTab"); } + break; case "NewPage": if (TabPermissionController.CanAddPage()) { - returnValue = _navigationManager.NavigateURL("Tab", "activeTab=settingTab"); + returnValue = this._navigationManager.NavigateURL("Tab", "activeTab=settingTab"); } + break; case "PublishPage": if (TabPermissionController.CanAdminPage()) { - returnValue = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID); + returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID); } + break; default: if (!string.IsNullOrEmpty(moduleFriendlyName)) { var additionalParams = new List(); - returnValue = GetTabURL(additionalParams, toolName, isHostTool, + returnValue = this.GetTabURL(additionalParams, toolName, isHostTool, moduleFriendlyName, controlKey, showAsPopUp); } + break; } + return returnValue; } protected string GetTabURL(List additionalParams, string toolName, bool isHostTool, string moduleFriendlyName, string controlKey, bool showAsPopUp) { - int portalId = isHostTool ? Null.NullInteger : PortalSettings.PortalId; + int portalId = isHostTool ? Null.NullInteger : this.PortalSettings.PortalId; string strURL = string.Empty; @@ -389,23 +456,23 @@ protected string GetTabURL(List additionalParams, string toolName, bool if (!string.IsNullOrEmpty(controlKey)) { additionalParams.Insert(0, "mid=" + moduleInfo.ModuleID); - if (showAsPopUp && PortalSettings.EnablePopUps) + if (showAsPopUp && this.PortalSettings.EnablePopUps) { additionalParams.Add("popUp=true"); } } string currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture.Name; - strURL = _navigationManager.NavigateURL(moduleInfo.TabID, isHostPage, PortalSettings, controlKey, currentCulture, additionalParams.ToArray()); + strURL = this._navigationManager.NavigateURL(moduleInfo.TabID, isHostPage, this.PortalSettings, controlKey, currentCulture, additionalParams.ToArray()); } return strURL; } - protected string GetTabURL(string tabName, bool isHostTool) - { - return GetTabURL(tabName, isHostTool, null); - } + protected string GetTabURL(string tabName, bool isHostTool) + { + return this.GetTabURL(tabName, isHostTool, null); + } protected string GetTabURL(string tabName, bool isHostTool, int? parentId) { @@ -414,8 +481,8 @@ protected string GetTabURL(string tabName, bool isHostTool, int? parentId) return "javascript:void(0);"; } - int portalId = isHostTool ? Null.NullInteger : PortalSettings.PortalId; - return GetTabURL(tabName, portalId, parentId); + int portalId = isHostTool ? Null.NullInteger : this.PortalSettings.PortalId; + return this.GetTabURL(tabName, portalId, parentId); } protected string GetTabURL(string tabName, int portalId, int? parentId) @@ -432,29 +499,30 @@ protected string GetTabURL(string tabName, int portalId, int? parentId) protected string GetTabPublishing() { - return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, PortalSettings.PortalId) ? "true" : "false"; + return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, this.PortalSettings.PortalId) ? "true" : "false"; } protected string GetPublishActionText() { - return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, PortalSettings.PortalId) - ? ClientAPI.GetSafeJSString(GetString("Tool.UnpublishPage.Text")) - : ClientAPI.GetSafeJSString(GetString("Tool.PublishPage.Text")); + return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, this.PortalSettings.PortalId) + ? ClientAPI.GetSafeJSString(this.GetString("Tool.UnpublishPage.Text")) + : ClientAPI.GetSafeJSString(this.GetString("Tool.PublishPage.Text")); } protected string GetPublishConfirmText() { - return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, PortalSettings.PortalId) - ? GetButtonConfirmMessage("UnpublishPage") - : GetButtonConfirmMessage("PublishPage"); + return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, this.PortalSettings.PortalId) + ? this.GetButtonConfirmMessage("UnpublishPage") + : this.GetButtonConfirmMessage("PublishPage"); } protected string GetPublishConfirmHeader() { - return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, PortalSettings.PortalId) - ? GetButtonConfirmHeader("UnpublishPage") - : GetButtonConfirmHeader("PublishPage"); + return TabPublishingController.Instance.IsTabPublished(TabController.CurrentPage.TabID, this.PortalSettings.PortalId) + ? this.GetButtonConfirmHeader("UnpublishPage") + : this.GetButtonConfirmHeader("PublishPage"); } + protected string GetMenuItem(string tabName, bool isHostTool) { if (isHostTool && !UserController.Instance.GetCurrentUserInfo().IsSuperUser) @@ -463,19 +531,27 @@ protected string GetMenuItem(string tabName, bool isHostTool) } List tabList; - if(isHostTool) + if (isHostTool) { - if(_hostTabs == null) GetHostTabs(); - tabList = _hostTabs; + if (this._hostTabs == null) + { + this.GetHostTabs(); + } + + tabList = this._hostTabs; } else { - if(_adminTabs == null) GetAdminTabs(); - tabList = _adminTabs; + if (this._adminTabs == null) + { + this.GetAdminTabs(); + } + + tabList = this._adminTabs; } var tab = tabList?.SingleOrDefault(t => t.TabName == tabName); - return GetMenuItem(tab); + return this.GetMenuItem(tab); } protected string GetMenuItem(string tabName, bool isHostTool, bool isRemoveBookmark, bool isHideBookmark = false) @@ -488,63 +564,82 @@ protected string GetMenuItem(string tabName, bool isHostTool, bool isRemoveBookm List tabList; if (isHostTool) { - if (_hostTabs == null) GetHostTabs(); - tabList = _hostTabs; + if (this._hostTabs == null) + { + this.GetHostTabs(); + } + + tabList = this._hostTabs; } else { - if (_adminTabs == null) GetAdminTabs(); - tabList = _adminTabs; + if (this._adminTabs == null) + { + this.GetAdminTabs(); + } + + tabList = this._adminTabs; } var tab = tabList?.SingleOrDefault(t => t.TabName == tabName); - return GetMenuItem(tab, isRemoveBookmark, isHideBookmark); + return this.GetMenuItem(tab, isRemoveBookmark, isHideBookmark); } protected string GetMenuItem(TabInfo tab, bool isRemoveBookmark = false, bool isHideBookmark = false) { - if (tab == null) return string.Empty; + if (tab == null) + { + return string.Empty; + } + if (tab.IsVisible && !tab.IsDeleted && !tab.DisableLink) { string name = !string.IsNullOrEmpty(tab.LocalizedTabName) ? tab.LocalizedTabName : tab.Title; - var linkClass = DotNetNukeContext.Current.Application.Name == "DNNCORP.CE" && tab.FullUrl.Contains("ProfessionalFeatures") ? "class=\"PE\"" : string.Empty; + var linkClass = DotNetNukeContext.Current.Application.Name == "DNNCORP.CE" && tab.FullUrl.Contains("ProfessionalFeatures") ? "class=\"PE\"" : string.Empty; if (!isRemoveBookmark) { - if(!isHideBookmark) - return string.Format("
  • {1}
  • ", - tab.FullUrl, - name, - ClientAPI.GetSafeJSString(GetString("Tool.AddToBookmarks.ToolTip")), - ClientAPI.GetSafeJSString(tab.TabName), - linkClass); - else - return string.Format("
  • {1}
  • ", - tab.FullUrl, - name, - ClientAPI.GetSafeJSString(GetString("Tool.AddToBookmarks.ToolTip")), - ClientAPI.GetSafeJSString(tab.TabName), - linkClass); + if (!isHideBookmark) + { + return string.Format( + "
  • {1}
  • ", + tab.FullUrl, + name, + ClientAPI.GetSafeJSString(this.GetString("Tool.AddToBookmarks.ToolTip")), + ClientAPI.GetSafeJSString(tab.TabName), + linkClass); + } + else + { + return string.Format( + "
  • {1}
  • ", + tab.FullUrl, + name, + ClientAPI.GetSafeJSString(this.GetString("Tool.AddToBookmarks.ToolTip")), + ClientAPI.GetSafeJSString(tab.TabName), + linkClass); + } } - return string.Format("
  • {1}
  • ", - tab.FullUrl, - name, - ClientAPI.GetSafeJSString(GetString("Tool.RemoveFromBookmarks.ToolTip")), - ClientAPI.GetSafeJSString(tab.TabName), - linkClass); + return string.Format( + "
  • {1}
  • ", + tab.FullUrl, + name, + ClientAPI.GetSafeJSString(this.GetString("Tool.RemoveFromBookmarks.ToolTip")), + ClientAPI.GetSafeJSString(tab.TabName), + linkClass); } + return string.Empty; } - - + protected string GetAdminBaseMenu() { - var tabs = AdminBaseTabs; + var tabs = this.AdminBaseTabs; var sb = new StringBuilder(); - foreach(var tab in tabs) + foreach (var tab in tabs) { - var hideBookmark = AdminBookmarkItems.Contains(tab.TabName); - sb.Append(GetMenuItem(tab, false, hideBookmark)); + var hideBookmark = this.AdminBookmarkItems.Contains(tab.TabName); + sb.Append(this.GetMenuItem(tab, false, hideBookmark)); } return sb.ToString(); @@ -552,12 +647,12 @@ protected string GetAdminBaseMenu() protected string GetAdminAdvancedMenu() { - var tabs = AdminAdvancedTabs; + var tabs = this.AdminAdvancedTabs; var sb = new StringBuilder(); foreach (var tab in tabs) { - var hideBookmark = AdminBookmarkItems.Contains(tab.TabName); - sb.Append(GetMenuItem(tab, false, hideBookmark)); + var hideBookmark = this.AdminBookmarkItems.Contains(tab.TabName); + sb.Append(this.GetMenuItem(tab, false, hideBookmark)); } return sb.ToString(); @@ -565,13 +660,13 @@ protected string GetAdminAdvancedMenu() protected string GetHostBaseMenu() { - var tabs = HostBaseTabs; + var tabs = this.HostBaseTabs; var sb = new StringBuilder(); foreach (var tab in tabs) { - var hideBookmark = HostBookmarkItems.Contains(tab.TabName); - sb.Append(GetMenuItem(tab, false, hideBookmark)); + var hideBookmark = this.HostBookmarkItems.Contains(tab.TabName); + sb.Append(this.GetMenuItem(tab, false, hideBookmark)); } return sb.ToString(); @@ -579,12 +674,12 @@ protected string GetHostBaseMenu() protected string GetHostAdvancedMenu() { - var tabs = HostAdvancedTabs; + var tabs = this.HostAdvancedTabs; var sb = new StringBuilder(); foreach (var tab in tabs) { - var hideBookmark = HostBookmarkItems.Contains(tab.TabName); - sb.Append(GetMenuItem(tab, false, hideBookmark)); + var hideBookmark = this.HostBookmarkItems.Contains(tab.TabName); + sb.Append(this.GetMenuItem(tab, false, hideBookmark)); } return sb.ToString(); @@ -593,15 +688,16 @@ protected string GetHostAdvancedMenu() protected string GetBookmarkItems(string title) { var isHostTool = title == "host"; - var bookmarkItems = isHostTool ? HostBookmarkItems : AdminBookmarkItems; + var bookmarkItems = isHostTool ? this.HostBookmarkItems : this.AdminBookmarkItems; - if(bookmarkItems != null && bookmarkItems.Any()) + if (bookmarkItems != null && bookmarkItems.Any()) { var sb = new StringBuilder(); - foreach(var itemKey in bookmarkItems) + foreach (var itemKey in bookmarkItems) { - sb.Append(GetMenuItem(itemKey, isHostTool, true)); + sb.Append(this.GetMenuItem(itemKey, isHostTool, true)); } + return sb.ToString(); } @@ -610,12 +706,12 @@ protected string GetBookmarkItems(string title) protected string GetButtonConfirmMessage(string toolName) { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool."+toolName+".ConfirmText", LocalResourceFile)); + return ClientAPI.GetSafeJSString(Localization.GetString("Tool." + toolName + ".ConfirmText", this.LocalResourceFile)); } protected string GetButtonConfirmHeader(string toolName) { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool." + toolName + ".ConfirmHeader", LocalResourceFile)); + return ClientAPI.GetSafeJSString(Localization.GetString("Tool." + toolName + ".ConfirmHeader", this.LocalResourceFile)); } protected IEnumerable LoadPortalsList() @@ -632,7 +728,7 @@ protected IEnumerable LoadPortalsList() string[] p = { pi.PortalName, - pi.PortalID.ToString("D") + pi.PortalID.ToString("D"), }; result.Add(p); @@ -646,34 +742,33 @@ protected IEnumerable LoadLanguagesList() { var result = new List(); - if (PortalSettings.AllowUserUICulture) + if (this.PortalSettings.AllowUserUICulture) { - if(CurrentUICulture == null) + if (this.CurrentUICulture == null) { object oCulture = Personalization.GetProfile("Usability", "UICulture"); if (oCulture != null) { - CurrentUICulture = oCulture.ToString(); + this.CurrentUICulture = oCulture.ToString(); } else { var l = new Localization(); - CurrentUICulture = l.CurrentUICulture; - SetLanguage(true, CurrentUICulture); + this.CurrentUICulture = l.CurrentUICulture; + this.SetLanguage(true, this.CurrentUICulture); } } - - - IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, CurrentUICulture, "", false); + + IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, this.CurrentUICulture, string.Empty, false); foreach (var cultureItem in cultureListItems) { - var selected = cultureItem.Value == CurrentUICulture ? "true" : "false"; + var selected = cultureItem.Value == this.CurrentUICulture ? "true" : "false"; string[] p = new string[] { cultureItem.Text, cultureItem.Value, - selected + selected, }; result.Add(p); } @@ -683,47 +778,46 @@ protected IEnumerable LoadLanguagesList() } protected bool ShowSwitchLanguagesPanel() - { - if (PortalSettings.AllowUserUICulture && PortalSettings.ContentLocalizationEnabled) - { - if (CurrentUICulture == null) - { - object oCulture = Personalization.GetProfile("Usability", "UICulture"); - - if (oCulture != null) - { - CurrentUICulture = oCulture.ToString(); - } - else - { - var l = new Localization(); - CurrentUICulture = l.CurrentUICulture; - } - } - - IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, CurrentUICulture, "", false); - return cultureListItems.Count() > 1; - } - + { + if (this.PortalSettings.AllowUserUICulture && this.PortalSettings.ContentLocalizationEnabled) + { + if (this.CurrentUICulture == null) + { + object oCulture = Personalization.GetProfile("Usability", "UICulture"); + + if (oCulture != null) + { + this.CurrentUICulture = oCulture.ToString(); + } + else + { + var l = new Localization(); + this.CurrentUICulture = l.CurrentUICulture; + } + } + + IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, this.CurrentUICulture, string.Empty, false); + return cultureListItems.Count() > 1; + } + return false; - } protected string CheckedWhenInLayoutMode() { - return UserMode == PortalSettings.Mode.Layout ? "checked='checked'" : string.Empty; + return this.UserMode == PortalSettings.Mode.Layout ? "checked='checked'" : string.Empty; } protected string CheckedWhenStayInEditMode() { string checkboxState = string.Empty; - var cookie = Request.Cookies["StayInEditMode"]; - if(cookie != null && cookie.Value == "YES") + var cookie = this.Request.Cookies["StayInEditMode"]; + if (cookie != null && cookie.Value == "YES") { checkboxState = "checked='checked'"; } - if(UserMode == PortalSettings.Mode.Layout) + if (this.UserMode == PortalSettings.Mode.Layout) { checkboxState += " disabled='disabled'"; } @@ -733,22 +827,22 @@ protected string CheckedWhenStayInEditMode() protected string SpecialClassWhenNotInViewMode() { - return UserMode == PortalSettings.Mode.View ? string.Empty : "controlBar_editPageInEditMode"; + return this.UserMode == PortalSettings.Mode.View ? string.Empty : "controlBar_editPageInEditMode"; } protected string GetModeForAttribute() { - return UserMode.ToString().ToUpperInvariant(); + return this.UserMode.ToString().ToUpperInvariant(); } protected string GetEditButtonLabel() { - return UserMode == PortalSettings.Mode.Edit ? GetString("Tool.CloseEditMode.Text") : GetString("Tool.EditThisPage.Text"); + return this.UserMode == PortalSettings.Mode.Edit ? this.GetString("Tool.CloseEditMode.Text") : this.GetString("Tool.EditThisPage.Text"); } protected virtual bool ActiveTabHasChildren() { - var children = TabController.GetTabsByParent(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID); + var children = TabController.GetTabsByParent(this.PortalSettings.ActiveTab.TabID, this.PortalSettings.ActiveTab.PortalID); if ((children == null) || children.Count < 1) { @@ -761,31 +855,38 @@ protected virtual bool ActiveTabHasChildren() protected bool IsLanguageModuleInstalled() { return DesktopModuleController.GetDesktopModuleByFriendlyName("Languages") != null; - } + } - #endregion + private static IEnumerable GetCurrentPortalsGroup() + { + var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); - #region Private Methods + var result = (from @group in groups + select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); - private new string LocalResourceFile - { - get + // Are we in a group of one? + if (result == null || result.Length == 0) { - return string.Format("{0}/{1}/{2}.ascx.resx", TemplateSourceDirectory, Localization.LocalResourceDirectory, GetType().BaseType?.Name); + result = new[] { PortalController.Instance.GetPortal(PortalSettings.Current.PortalId) }; } + + return result; } private void LoadCategoryList() { ITermController termController = Util.GetTermController(); var terms = termController.GetTermsByVocabulary("Module_Categories").OrderBy(t => t.Weight).Where(t => t.Name != "< None >").ToList(); - var allTerm = new Term("All", Localization.GetString("AllCategories", LocalResourceFile)); + var allTerm = new Term("All", Localization.GetString("AllCategories", this.LocalResourceFile)); terms.Add(allTerm); - CategoryList.DataSource = terms; - CategoryList.DataBind(); - if (!IsPostBack) + this.CategoryList.DataSource = terms; + this.CategoryList.DataBind(); + if (!this.IsPostBack) { - CategoryList.Select(!String.IsNullOrEmpty(BookmarkedModuleKeys) ? BookmarkModuleCategory : "All", false); + this.CategoryList.Select(!string.IsNullOrEmpty(this.BookmarkedModuleKeys) ? this.BookmarkModuleCategory : "All", false); } } @@ -795,99 +896,81 @@ private bool LoadSiteList() var multipleSites = GetCurrentPortalsGroup().Count() > 1; if (multipleSites) { - PageList.Services.GetTreeMethod = "ItemListService/GetPagesInPortalGroup"; - PageList.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendantsInPortalGroup"; - PageList.Services.SearchTreeMethod = "ItemListService/SearchPagesInPortalGroup"; - PageList.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPageInPortalGroup"; - PageList.Services.SortTreeMethod = "ItemListService/SortPagesInPortalGroup"; + this.PageList.Services.GetTreeMethod = "ItemListService/GetPagesInPortalGroup"; + this.PageList.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendantsInPortalGroup"; + this.PageList.Services.SearchTreeMethod = "ItemListService/SearchPagesInPortalGroup"; + this.PageList.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPageInPortalGroup"; + this.PageList.Services.SortTreeMethod = "ItemListService/SortPagesInPortalGroup"; } - PageList.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, string.Empty); - PageList.OnClientSelectionChanged.Add("dnn.controlBar.ControlBar_Module_PageList_Changed"); + this.PageList.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, string.Empty); + this.PageList.OnClientSelectionChanged.Add("dnn.controlBar.ControlBar_Module_PageList_Changed"); return multipleSites; } private void LoadVisibilityList() { - var items = new Dictionary { { "0", GetString("PermissionView") }, { "1", GetString("PermissionEdit") } }; + var items = new Dictionary { { "0", this.GetString("PermissionView") }, { "1", this.GetString("PermissionEdit") } }; - VisibilityLst.Items.Clear(); - VisibilityLst.DataValueField = "key"; - VisibilityLst.DataTextField = "value"; - VisibilityLst.DataSource = items; - VisibilityLst.DataBind(); - } - - private static IEnumerable GetCurrentPortalsGroup() - { - var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); - - var result = (from @group in groups - select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); - - // Are we in a group of one? - if (result == null || result.Length == 0) - { - result = new[] { PortalController.Instance.GetPortal(PortalSettings.Current.PortalId) }; - } - - return result; + this.VisibilityLst.Items.Clear(); + this.VisibilityLst.DataValueField = "key"; + this.VisibilityLst.DataTextField = "value"; + this.VisibilityLst.DataSource = items; + this.VisibilityLst.DataBind(); } private void AutoSetUserMode() { - int tabId = PortalSettings.ActiveTab.TabID; + int tabId = this.PortalSettings.ActiveTab.TabID; int portalId = PortalSettings.Current.PortalId; string pageId = string.Format("{0}:{1}", portalId, tabId); - HttpCookie cookie = Request.Cookies["StayInEditMode"]; + HttpCookie cookie = this.Request.Cookies["StayInEditMode"]; if (cookie != null && cookie.Value == "YES") { if (PortalSettings.Current.UserMode != PortalSettings.Mode.Edit) { - SetUserMode("EDIT"); - SetLastPageHistory(pageId); - Response.Redirect(Request.RawUrl, true); - + this.SetUserMode("EDIT"); + this.SetLastPageHistory(pageId); + this.Response.Redirect(this.Request.RawUrl, true); } return; } - string lastPageId = GetLastPageHistory(); - var isShowAsCustomError = Request.QueryString.AllKeys.Contains("aspxerrorpath"); + string lastPageId = this.GetLastPageHistory(); + var isShowAsCustomError = this.Request.QueryString.AllKeys.Contains("aspxerrorpath"); - if (lastPageId != pageId && !isShowAsCustomError) + if (lastPageId != pageId && !isShowAsCustomError) { // navigate between pages if (PortalSettings.Current.UserMode != PortalSettings.Mode.View) { - SetUserMode("VIEW"); - SetLastPageHistory(pageId); - Response.Redirect(Request.RawUrl, true); + this.SetUserMode("VIEW"); + this.SetLastPageHistory(pageId); + this.Response.Redirect(this.Request.RawUrl, true); } } - if (!isShowAsCustomError) - { - SetLastPageHistory(pageId); - } + if (!isShowAsCustomError) + { + this.SetLastPageHistory(pageId); + } } private void SetLastPageHistory(string pageId) { - Response.Cookies.Add(new HttpCookie("LastPageId", pageId) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); + this.Response.Cookies.Add(new HttpCookie("LastPageId", pageId) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); } private string GetLastPageHistory() { - var cookie = Request.Cookies["LastPageId"]; - if (cookie != null) - return cookie.Value; - + var cookie = this.Request.Cookies["LastPageId"]; + if (cookie != null) + { + return cookie.Value; + } + return "NEW"; } @@ -899,20 +982,20 @@ private void SetLanguage(bool update, string currentCulture) } } - private void BindPortalsList() - { - foreach (var portal in LoadPortalsList()) - { - controlBar_SwitchSite.Items.Add(new DnnComboBoxItem(portal[0], portal[1])); - } - } - - private void BindLanguagesList() - { - if (ShowSwitchLanguagesPanel()) + private void BindPortalsList() + { + foreach (var portal in this.LoadPortalsList()) + { + this.controlBar_SwitchSite.Items.Add(new DnnComboBoxItem(portal[0], portal[1])); + } + } + + private void BindLanguagesList() + { + if (this.ShowSwitchLanguagesPanel()) { const string FlagImageUrlFormatString = "~/images/Flags/{0}.gif"; - foreach (var lang in LoadLanguagesList()) + foreach (var lang in this.LoadLanguagesList()) { var item = new DnnComboBoxItem(lang[0], lang[1]); item.ImageUrl = string.Format(FlagImageUrlFormatString, item.Value); @@ -921,55 +1004,10 @@ private void BindLanguagesList() item.Selected = true; } - controlBar_SwitchLanguage.Items.Add(item); - } - - } - } - - #endregion - - #region Menu Items Properties - - private List _adminBookmarkItems; - protected List AdminBookmarkItems - { - get - { - if (_adminBookmarkItems == null) - { - var bookmarkItems = Personalization.GetProfile("ControlBar", "admin" + PortalSettings.PortalId); - - _adminBookmarkItems = bookmarkItems != null - ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() - : new List(); - } - - return _adminBookmarkItems; - } - } - - private List _hostBookmarkItems; - protected List HostBookmarkItems - { - get - { - if(_hostBookmarkItems == null) - { - var bookmarkItems = Personalization.GetProfile("ControlBar", "host" + PortalSettings.PortalId); - - _hostBookmarkItems = bookmarkItems != null - ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() - : new List(); + this.controlBar_SwitchLanguage.Items.Add(item); } - - return _hostBookmarkItems; } - } - - private List _adminTabs; - private List _adminBaseTabs; - private List _adminAdvancedTabs; + } private List _hostTabs; private List _hostBaseTabs; private List _hostAdvancedTabs; @@ -978,11 +1016,12 @@ protected List AdminBaseTabs { get { - if (_adminBaseTabs == null) + if (this._adminBaseTabs == null) { - GetAdminTabs(); + this.GetAdminTabs(); } - return _adminBaseTabs; + + return this._adminBaseTabs; } } @@ -990,11 +1029,12 @@ protected List AdminAdvancedTabs { get { - if (_adminAdvancedTabs == null) + if (this._adminAdvancedTabs == null) { - GetAdminTabs(); + this.GetAdminTabs(); } - return _adminAdvancedTabs; + + return this._adminAdvancedTabs; } } @@ -1002,11 +1042,12 @@ protected List HostBaseTabs { get { - if (_hostBaseTabs == null) + if (this._hostBaseTabs == null) { - GetHostTabs(); + this.GetHostTabs(); } - return _hostBaseTabs; + + return this._hostBaseTabs; } } @@ -1014,14 +1055,32 @@ protected List HostAdvancedTabs { get { - if (_hostAdvancedTabs == null) + if (this._hostAdvancedTabs == null) { - GetHostTabs(); + this.GetHostTabs(); } - return _hostAdvancedTabs; + + return this._hostAdvancedTabs; } } + protected bool IsBeaconEnabled + { + get + { + var user = UserController.Instance.GetCurrentUserInfo(); + return BeaconService.Instance.IsBeaconEnabledForControlBar(user); + } + } + + protected string GetBeaconUrl() + { + var beaconService = BeaconService.Instance; + var user = UserController.Instance.GetCurrentUserInfo(); + var path = this.PortalSettings.ActiveTab.TabPath; + return beaconService.GetBeaconUrl(user, path); + } + private void GetHostTabs() { var hostTab = TabController.GetTabByTabPath(Null.NullInteger, "//Host", string.Empty); @@ -1032,47 +1091,46 @@ private void GetHostTabs() ? TabController.GetTabsByParent(professionalTab.TabID, -1) : new List(); - _hostTabs = new List(); - _hostTabs.AddRange(hosts); - _hostTabs.AddRange(professionalTabs); - _hostTabs = _hostTabs.OrderBy(t => t.LocalizedTabName).ToList(); + this._hostTabs = new List(); + this._hostTabs.AddRange(hosts); + this._hostTabs.AddRange(professionalTabs); + this._hostTabs = this._hostTabs.OrderBy(t => t.LocalizedTabName).ToList(); - _hostBaseTabs = new List(); - _hostAdvancedTabs = new List(); + this._hostBaseTabs = new List(); + this._hostAdvancedTabs = new List(); - foreach (var tabInfo in _hostTabs) + foreach (var tabInfo in this._hostTabs) { - if (IsCommonTab(tabInfo, true)) + if (this.IsCommonTab(tabInfo, true)) { - _hostBaseTabs.Add(tabInfo); + this._hostBaseTabs.Add(tabInfo); } else { - _hostAdvancedTabs.Add(tabInfo); + this._hostAdvancedTabs.Add(tabInfo); } } } private void GetAdminTabs() { - var adminTab = TabController.GetTabByTabPath(PortalSettings.PortalId, "//Admin", string.Empty); - _adminTabs = TabController.GetTabsByParent(adminTab, PortalSettings.PortalId).OrderBy(t => t.LocalizedTabName).ToList(); + var adminTab = TabController.GetTabByTabPath(this.PortalSettings.PortalId, "//Admin", string.Empty); + this._adminTabs = TabController.GetTabsByParent(adminTab, this.PortalSettings.PortalId).OrderBy(t => t.LocalizedTabName).ToList(); - _adminBaseTabs = new List(); - _adminAdvancedTabs = new List(); + this._adminBaseTabs = new List(); + this._adminAdvancedTabs = new List(); - foreach (var tabInfo in _adminTabs) + foreach (var tabInfo in this._adminTabs) { - if (IsCommonTab(tabInfo)) + if (this.IsCommonTab(tabInfo)) { - _adminBaseTabs.Add(tabInfo); + this._adminBaseTabs.Add(tabInfo); } else { - _adminAdvancedTabs.Add(tabInfo); + this._adminAdvancedTabs.Add(tabInfo); } } - } private bool IsCommonTab(TabInfo tab, bool isHost = false) @@ -1082,33 +1140,8 @@ private bool IsCommonTab(TabInfo tab, bool isHost = false) { return true; } - - - return isHost ? _hostCommonTabs.Contains(tab.TabName) : _adminCommonTabs.Contains(tab.TabName); - } - - #endregion - - #region Beacon code - - protected string GetBeaconUrl() - { - var beaconService = BeaconService.Instance; - var user = UserController.Instance.GetCurrentUserInfo(); - var path = PortalSettings.ActiveTab.TabPath; - return beaconService.GetBeaconUrl(user, path); - } - - protected bool IsBeaconEnabled - { - get - { - var user = UserController.Instance.GetCurrentUserInfo(); - return BeaconService.Instance.IsBeaconEnabledForControlBar(user); - } - } - - #endregion + + return isHost ? this._hostCommonTabs.Contains(tab.TabName) : this._adminCommonTabs.Contains(tab.TabName); + } } - } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs index 235126e8b45..3e40b27b082 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs @@ -1,38 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Application; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mobile; -using DotNetNuke.Services.Upgrade; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.ControlPanels { + using System; + using System.Collections.Generic; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Application; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mobile; + using DotNetNuke.Services.Upgrade; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls; + + using Globals = DotNetNuke.Common.Globals; + public partial class RibbonBar : ControlPanelBase { public override bool IsDockable { get; set; } @@ -41,328 +36,317 @@ public override bool IncludeInControlHierarchy { get { - return base.IncludeInControlHierarchy && (IsPageAdmin() || IsModuleAdmin()); + return base.IncludeInControlHierarchy && (this.IsPageAdmin() || this.IsModuleAdmin()); } - } + } + protected string GetButtonConfirmMessage(string toolName) + { + if (toolName == "DeletePage") + { + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.DeletePage.Confirm", this.LocalResourceFile)); + } - #region "Private Methods" + if (toolName == "CopyPermissionsToChildren") + { + if (PortalSecurity.IsInRole("Administrators")) + { + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildren.Confirm", this.LocalResourceFile)); + } - private void Localize() + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildrenPageEditor.Confirm", this.LocalResourceFile)); + } + + if (toolName == "CopyDesignToChildren") + { + if (PortalSecurity.IsInRole("Administrators")) + { + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildren.Confirm", this.LocalResourceFile)); + } + + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildrenPageEditor.Confirm", this.LocalResourceFile)); + } + + return string.Empty; + } + + protected void DetermineNodesToInclude(object sender, EventArgs e) { + var skinObject = (Web.DDRMenu.SkinObject)sender; + string admin = this.StripLocalizationPrefix(Localization.GetString("//Admin.String", Localization.GlobalResourceFile)).Trim(); + string host = this.StripLocalizationPrefix(Localization.GetString("//Host.String", Localization.GlobalResourceFile)).Trim(); - Control ctrl = AdminPanel.FindControl("SiteNewPage"); - if (((ctrl != null) && ctrl is DnnRibbonBarTool)) + skinObject.IncludeNodes = admin + ", " + host; + } + + private void Localize() + { + Control ctrl = this.AdminPanel.FindControl("SiteNewPage"); + if ((ctrl != null) && ctrl is DnnRibbonBarTool) { var toolCtrl = (DnnRibbonBarTool)ctrl; - toolCtrl.Text = Localization.GetString("SiteNewPage", LocalResourceFile); - toolCtrl.ToolTip = Localization.GetString("SiteNewPage.ToolTip", LocalResourceFile); + toolCtrl.Text = Localization.GetString("SiteNewPage", this.LocalResourceFile); + toolCtrl.ToolTip = Localization.GetString("SiteNewPage.ToolTip", this.LocalResourceFile); } - } private void SetMode(bool update) { if (update) { - SetUserMode(ddlMode.SelectedValue); + this.SetUserMode(this.ddlMode.SelectedValue); } if (!TabPermissionController.CanAddContentToPage()) { - RemoveModeDropDownItem("LAYOUT"); + this.RemoveModeDropDownItem("LAYOUT"); } if (!(new PreviewProfileController().GetProfilesByPortal(this.PortalSettings.PortalId).Count > 0)) { - RemoveModeDropDownItem("PREVIEW"); + this.RemoveModeDropDownItem("PREVIEW"); } - switch (UserMode) + switch (this.UserMode) { case PortalSettings.Mode.View: - ddlMode.FindItemByValue("VIEW").Selected = true; + this.ddlMode.FindItemByValue("VIEW").Selected = true; break; case PortalSettings.Mode.Edit: - ddlMode.FindItemByValue("EDIT").Selected = true; + this.ddlMode.FindItemByValue("EDIT").Selected = true; break; case PortalSettings.Mode.Layout: - ddlMode.FindItemByValue("LAYOUT").Selected = true; + this.ddlMode.FindItemByValue("LAYOUT").Selected = true; break; } } private void RemoveModeDropDownItem(string value) { - var item = ddlMode.FindItemByValue(value); + var item = this.ddlMode.FindItemByValue(value); if (item != null) { - ddlMode.Items.Remove(item); + this.ddlMode.Items.Remove(item); } } private void SetLanguage(bool update) - { - if (update) - { - DotNetNuke.Services.Personalization.Personalization.SetProfile("Usability", "UICulture", ddlUICulture.SelectedValue); - } - } - - protected string GetButtonConfirmMessage(string toolName) - { - if (toolName == "DeletePage") - { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.DeletePage.Confirm", LocalResourceFile)); - } - - if (toolName == "CopyPermissionsToChildren") - { - if (PortalSecurity.IsInRole("Administrators")) - { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildren.Confirm", LocalResourceFile)); - } - - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildrenPageEditor.Confirm", LocalResourceFile)); - } - - if (toolName == "CopyDesignToChildren") - { - if (PortalSecurity.IsInRole("Administrators")) - { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildren.Confirm", LocalResourceFile)); - } - - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildrenPageEditor.Confirm", LocalResourceFile)); - } - - return string.Empty; - } - - protected void DetermineNodesToInclude(object sender, EventArgs e) - { - var skinObject = (Web.DDRMenu.SkinObject)sender; - string admin = StripLocalizationPrefix(Localization.GetString("//Admin.String", Localization.GlobalResourceFile)).Trim(); - string host = StripLocalizationPrefix(Localization.GetString("//Host.String", Localization.GlobalResourceFile)).Trim(); - - skinObject.IncludeNodes = admin + ", " + host; - - } - - private string StripLocalizationPrefix(string s) { - const string prefix = "[L]"; - - if (s.StartsWith(prefix)) + if (update) { - return s.Substring(prefix.Length); + DotNetNuke.Services.Personalization.Personalization.SetProfile("Usability", "UICulture", this.ddlUICulture.SelectedValue); } - - return s; } - - #endregion - - #region "Event Handlers" - + protected override void OnInit(EventArgs e) { base.OnInit(e); - ID = "RibbonBar"; + this.ID = "RibbonBar"; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - ddlMode.SelectedIndexChanged += ddlMode_SelectedIndexChanged; - ddlUICulture.SelectedIndexChanged += ddlUICulture_SelectedIndexChanged; + this.ddlMode.SelectedIndexChanged += this.ddlMode_SelectedIndexChanged; + this.ddlUICulture.SelectedIndexChanged += this.ddlUICulture_SelectedIndexChanged; try { - AdminPanel.Visible = false; - AdvancedToolsPanel.Visible = false; + this.AdminPanel.Visible = false; + this.AdvancedToolsPanel.Visible = false; - if (ControlPanel.Visible && IncludeInControlHierarchy) + if (this.ControlPanel.Visible && this.IncludeInControlHierarchy) { ClientResourceManager.RegisterStyleSheet(this.Page, "~/admin/ControlPanel/module.css"); ClientResourceManager.RegisterScript(this.Page, "~/Resources/ControlPanel/ControlPanel.debug.js"); } - JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); - Control copyPageButton = CurrentPagePanel.FindControl("CopyPage"); - if ((copyPageButton != null)) + Control copyPageButton = this.CurrentPagePanel.FindControl("CopyPage"); + if (copyPageButton != null) { - copyPageButton.Visible = LocaleController.Instance.IsDefaultLanguage(LocaleController.Instance.GetCurrentLocale(PortalSettings.PortalId).Code); + copyPageButton.Visible = LocaleController.Instance.IsDefaultLanguage(LocaleController.Instance.GetCurrentLocale(this.PortalSettings.PortalId).Code); } - - - if ((Request.IsAuthenticated)) + + if (this.Request.IsAuthenticated) { UserInfo user = UserController.Instance.GetCurrentUserInfo(); - if (((user != null))) + if (user != null) { bool isAdmin = user.IsInRole(PortalSettings.Current.AdministratorRoleName); - AdminPanel.Visible = isAdmin; + this.AdminPanel.Visible = isAdmin; } } - if (IsPageAdmin()) - { - ControlPanel.Visible = true; - BodyPanel.Visible = true; + if (this.IsPageAdmin()) + { + this.ControlPanel.Visible = true; + this.BodyPanel.Visible = true; - if ((DotNetNukeContext.Current.Application.Name == "DNNCORP.CE")) + if (DotNetNukeContext.Current.Application.Name == "DNNCORP.CE") { - //Hide Support icon in CE - AdminPanel.FindControl("SupportTickets").Visible = false; + // Hide Support icon in CE + this.AdminPanel.FindControl("SupportTickets").Visible = false; } else { - //Show PE/XE tools - AdvancedToolsPanel.Visible = true; + // Show PE/XE tools + this.AdvancedToolsPanel.Visible = true; } - Localize(); - - if (!Page.IsPostBack) - { - UserInfo objUser = UserController.Instance.GetCurrentUserInfo(); - if ((objUser != null)) - { - if (objUser.IsSuperUser) - { - hypMessage.ImageUrl = Upgrade.UpgradeIndicator(DotNetNukeContext.Current.Application.Version, Request.IsLocal, Request.IsSecureConnection); - if (!string.IsNullOrEmpty(hypMessage.ImageUrl)) - { - hypMessage.ToolTip = Localization.GetString("hypUpgrade.Text", LocalResourceFile); - hypMessage.NavigateUrl = Upgrade.UpgradeRedirect(); - } - } - else - { - if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) && Host.DisplayCopyright) - { - hypMessage.ImageUrl = "~/images/branding/iconbar_logo.png"; - hypMessage.ToolTip = DotNetNukeContext.Current.Application.Description; - hypMessage.NavigateUrl = Localization.GetString("hypMessageUrl.Text", LocalResourceFile); - } - else - { - hypMessage.Visible = false; - } + this.Localize(); + + if (!this.Page.IsPostBack) + { + UserInfo objUser = UserController.Instance.GetCurrentUserInfo(); + if (objUser != null) + { + if (objUser.IsSuperUser) + { + this.hypMessage.ImageUrl = Upgrade.UpgradeIndicator(DotNetNukeContext.Current.Application.Version, this.Request.IsLocal, this.Request.IsSecureConnection); + if (!string.IsNullOrEmpty(this.hypMessage.ImageUrl)) + { + this.hypMessage.ToolTip = Localization.GetString("hypUpgrade.Text", this.LocalResourceFile); + this.hypMessage.NavigateUrl = Upgrade.UpgradeRedirect(); + } + } + else + { + if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) && Host.DisplayCopyright) + { + this.hypMessage.ImageUrl = "~/images/branding/iconbar_logo.png"; + this.hypMessage.ToolTip = DotNetNukeContext.Current.Application.Description; + this.hypMessage.NavigateUrl = Localization.GetString("hypMessageUrl.Text", this.LocalResourceFile); + } + else + { + this.hypMessage.Visible = false; + } if (!TabPermissionController.CanAddContentToPage()) { - CommonTasksPanel.Visible = false; + this.CommonTasksPanel.Visible = false; + } + } + + if (this.PortalSettings.AllowUserUICulture) + { + object oCulture = DotNetNuke.Services.Personalization.Personalization.GetProfile("Usability", "UICulture"); + string currentCulture; + if (oCulture != null) + { + currentCulture = oCulture.ToString(); + } + else + { + Localization l = new Localization(); + currentCulture = l.CurrentUICulture; } - } - if (PortalSettings.AllowUserUICulture) - { - object oCulture = DotNetNuke.Services.Personalization.Personalization.GetProfile("Usability", "UICulture"); - string currentCulture; - if (oCulture != null) - { - currentCulture = oCulture.ToString(); - } - else - { - Localization l = new Localization(); - currentCulture = l.CurrentUICulture; - } - //Localization.LoadCultureDropDownList(ddlUICulture, CultureDropDownTypes.NativeName, currentCulture); - IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, currentCulture, "", false); + + // Localization.LoadCultureDropDownList(ddlUICulture, CultureDropDownTypes.NativeName, currentCulture); + IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, currentCulture, string.Empty, false); foreach (var cultureItem in cultureListItems) { - ddlUICulture.AddItem(cultureItem.Text, cultureItem.Value); + this.ddlUICulture.AddItem(cultureItem.Text, cultureItem.Value); } - var selectedCultureItem = ddlUICulture.FindItemByValue(currentCulture); + var selectedCultureItem = this.ddlUICulture.FindItemByValue(currentCulture); if (selectedCultureItem != null) { selectedCultureItem.Selected = true; } - //only show language selector if more than one language - if (ddlUICulture.Items.Count > 1) - { - lblUILanguage.Visible = true; - ddlUICulture.Visible = true; - - if (oCulture == null) - { - SetLanguage(true); - } - } - } - } - SetMode(false); - } - } - else if (IsModuleAdmin()) - { - ControlPanel.Visible = true; - BodyPanel.Visible = false; - adminMenus.Visible = false; - if (!Page.IsPostBack) - { - SetMode(false); - } - } - else - { - ControlPanel.Visible = false; - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void ddlMode_SelectedIndexChanged(object sender, EventArgs e) - { - if (Page.IsCallback) - { - return; - } - SetMode(true); - Response.Redirect(Request.RawUrl, true); - } - - private void ddlUICulture_SelectedIndexChanged(object sender, EventArgs e) - { - if (Page.IsCallback) - { - return; - } - SetLanguage(true); - Response.Redirect(Request.RawUrl, true); - } - - #endregion - - #region "Protected Methods" - - protected string PreviewPopup() - { - var previewUrl = string.Format("{0}/Default.aspx?ctl={1}&previewTab={2}&TabID={2}", - Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias), - "MobilePreview", - PortalSettings.ActiveTab.TabID); - - if(PortalSettings.EnablePopUps) - { - return UrlUtils.PopUpUrl(previewUrl, this, PortalSettings, true, false, 660, 800); - } - else - { - return string.Format("location.href = \"{0}\"", previewUrl); - } - } - - #endregion - } + // only show language selector if more than one language + if (this.ddlUICulture.Items.Count > 1) + { + this.lblUILanguage.Visible = true; + this.ddlUICulture.Visible = true; + + if (oCulture == null) + { + this.SetLanguage(true); + } + } + } + } + + this.SetMode(false); + } + } + else if (this.IsModuleAdmin()) + { + this.ControlPanel.Visible = true; + this.BodyPanel.Visible = false; + this.adminMenus.Visible = false; + if (!this.Page.IsPostBack) + { + this.SetMode(false); + } + } + else + { + this.ControlPanel.Visible = false; + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + private string StripLocalizationPrefix(string s) + { + const string prefix = "[L]"; + + if (s.StartsWith(prefix)) + { + return s.Substring(prefix.Length); + } + + return s; + } + + protected void ddlMode_SelectedIndexChanged(object sender, EventArgs e) + { + if (this.Page.IsCallback) + { + return; + } + + this.SetMode(true); + this.Response.Redirect(this.Request.RawUrl, true); + } + + protected string PreviewPopup() + { + var previewUrl = string.Format( + "{0}/Default.aspx?ctl={1}&previewTab={2}&TabID={2}", + Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias), + "MobilePreview", + this.PortalSettings.ActiveTab.TabID); + + if (this.PortalSettings.EnablePopUps) + { + return UrlUtils.PopUpUrl(previewUrl, this, this.PortalSettings, true, false, 660, 800); + } + else + { + return string.Format("location.href = \"{0}\"", previewUrl); + } + } + + private void ddlUICulture_SelectedIndexChanged(object sender, EventArgs e) + { + if (this.Page.IsCallback) + { + return; + } + + this.SetLanguage(true); + this.Response.Redirect(this.Request.RawUrl, true); + } + } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs index 6c15ab0248c..e25d0474f03 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs @@ -1,42 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Linq; -using System.Threading; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.ControlPanel { + using System; + using System.Collections; + using System.Linq; + using System.Threading; + using System.Web.UI; using System.Web.UI.WebControls; - + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Web.UI.WebControls; + public partial class SwitchSite : UserControl, IDnnRibbonBarTool - { - #region Event Handlers + { + public override bool Visible + { + get + { + if (PortalSettings.Current.UserId == Null.NullInteger) + { + return false; + } + + return PortalSettings.Current.UserInfo.IsSuperUser && base.Visible; + } + + set + { + base.Visible = value; + } + } + public string ToolName + { + get + { + return "QuickSwitchSite"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdSwitch.Click += CmdSwitchClick; + this.cmdSwitch.Click += this.CmdSwitchClick; try { - if (Visible && !IsPostBack) + if (this.Visible && !this.IsPostBack) { - LoadPortalsList(); + this.LoadPortalsList(); } } catch (Exception exc) @@ -49,79 +72,41 @@ protected void CmdSwitchClick(object sender, EventArgs e) { try { - if ((!string.IsNullOrEmpty(SitesLst.SelectedValue))) + if (!string.IsNullOrEmpty(this.SitesLst.SelectedValue)) { - int selectedPortalID = int.Parse(SitesLst.SelectedValue); + int selectedPortalID = int.Parse(this.SitesLst.SelectedValue); var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(selectedPortalID).ToList(); - if ((portalAliases.Count > 0 && (portalAliases[0] != null))) + if (portalAliases.Count > 0 && (portalAliases[0] != null)) { - Response.Redirect(Globals.AddHTTP(((PortalAliasInfo) portalAliases[0]).HTTPAlias)); + this.Response.Redirect(Globals.AddHTTP(((PortalAliasInfo)portalAliases[0]).HTTPAlias)); } } } - catch(ThreadAbortException) - { - //Do nothing we are not logging ThreadAbortxceptions caused by redirects + catch (ThreadAbortException) + { + // Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception ex) { Exceptions.LogException(ex); } - } - - #endregion - - #region Properties - - public override bool Visible - { - get - { - if ((PortalSettings.Current.UserId == Null.NullInteger)) - { - return false; - } - return PortalSettings.Current.UserInfo.IsSuperUser && base.Visible; - } - set - { - base.Visible = value; - } - } - - public string ToolName - { - get - { - return "QuickSwitchSite"; - } - set - { - throw new NotSupportedException("Set ToolName not supported"); - } - } - - #endregion - - #region Methods - + } + private void LoadPortalsList() { var portals = PortalController.Instance.GetPortals(); - SitesLst.ClearSelection(); - SitesLst.Items.Clear(); + this.SitesLst.ClearSelection(); + this.SitesLst.Items.Clear(); - SitesLst.DataSource = portals; - SitesLst.DataTextField = "PortalName"; - SitesLst.DataValueField = "PortalID"; - SitesLst.DataBind(); - - //SitesLst.Items.Insert(0, new ListItem(string.Empty)); - SitesLst.InsertItem(0, string.Empty, string.Empty); - } + this.SitesLst.DataSource = portals; + this.SitesLst.DataTextField = "PortalName"; + this.SitesLst.DataValueField = "PortalID"; + this.SitesLst.DataBind(); - #endregion + // SitesLst.Items.Insert(0, new ListItem(string.Empty)); + this.SitesLst.InsertItem(0, string.Empty, string.Empty); + } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs index 113d10d8a07..567e46e6c0e 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs @@ -1,63 +1,104 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Linq; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins; -using DotNetNuke.Web.UI; -using DotNetNuke.Web.UI.WebControls; - -using Telerik.Web.UI; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.ControlPanel { - using DotNetNuke.Abstractions; + using System; + using System.IO; + using System.Linq; + using System.Web.UI; using System.Web.UI.WebControls; - + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins; + using DotNetNuke.Web.UI; + using DotNetNuke.Web.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + using Telerik.Web.UI; + public partial class UpdatePage : UserControl, IDnnRibbonBarTool { private readonly INavigationManager _navigationManager; + + private TabInfo _currentTab; + public UpdatePage() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } + + public override bool Visible + { + get + { + return base.Visible && TabPermissionController.CanManagePage(); + } + + set + { + base.Visible = value; + } } - #region "Event Handlers" + public string ToolName + { + get + { + return "QuickUpdatePage"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } + } + + private static PortalSettings PortalSettings + { + get + { + return PortalSettings.Current; + } + } + private TabInfo CurrentTab + { + get + { + // Weird - but the activetab has different skin src value than getting from the db + if (this._currentTab == null) + { + this._currentTab = TabController.Instance.GetTab(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID, false); + } + + return this._currentTab; + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdUpdate.Click += CmdUpdateClick; + this.cmdUpdate.Click += this.CmdUpdateClick; try { - if (Visible && !IsPostBack) + if (this.Visible && !this.IsPostBack) { - Name.Text = CurrentTab.TabName; - IncludeInMenu.Checked = CurrentTab.IsVisible; - IsDisabled.Checked = CurrentTab.DisableLink; - IsSecurePanel.Visible = PortalSettings.SSLEnabled; - IsSecure.Enabled = PortalSettings.SSLEnabled; - IsSecure.Checked = CurrentTab.IsSecure; - LoadAllLists(); + this.Name.Text = this.CurrentTab.TabName; + this.IncludeInMenu.Checked = this.CurrentTab.IsVisible; + this.IsDisabled.Checked = this.CurrentTab.DisableLink; + this.IsSecurePanel.Visible = PortalSettings.SSLEnabled; + this.IsSecure.Enabled = PortalSettings.SSLEnabled; + this.IsSecure.Checked = this.CurrentTab.IsSecure; + this.LoadAllLists(); } } catch (Exception exc) @@ -68,30 +109,30 @@ protected override void OnLoad(EventArgs e) protected void CmdUpdateClick(object sender, EventArgs e) { - if ((TabPermissionController.CanManagePage())) + if (TabPermissionController.CanManagePage()) { TabInfo selectedTab = null; - if ((!string.IsNullOrEmpty(PageLst.SelectedValue))) + if (!string.IsNullOrEmpty(this.PageLst.SelectedValue)) { - int selectedTabID = Int32.Parse(PageLst.SelectedValue); + int selectedTabID = int.Parse(this.PageLst.SelectedValue); selectedTab = TabController.Instance.GetTab(selectedTabID, PortalSettings.ActiveTab.PortalID, false); } TabRelativeLocation tabLocation = TabRelativeLocation.NOTSET; - if ((!string.IsNullOrEmpty(LocationLst.SelectedValue))) + if (!string.IsNullOrEmpty(this.LocationLst.SelectedValue)) { - tabLocation = (TabRelativeLocation) Enum.Parse(typeof (TabRelativeLocation), LocationLst.SelectedValue); + tabLocation = (TabRelativeLocation)Enum.Parse(typeof(TabRelativeLocation), this.LocationLst.SelectedValue); } - TabInfo tab = CurrentTab; + TabInfo tab = this.CurrentTab; - tab.TabName = Name.Text; - tab.IsVisible = IncludeInMenu.Checked; - tab.DisableLink = IsDisabled.Checked; - tab.IsSecure = IsSecure.Checked; - tab.SkinSrc = SkinLst.SelectedValue; + tab.TabName = this.Name.Text; + tab.IsVisible = this.IncludeInMenu.Checked; + tab.DisableLink = this.IsDisabled.Checked; + tab.IsSecure = this.IsSecure.Checked; + tab.SkinSrc = this.SkinLst.SelectedValue; - string errMsg = ""; + string errMsg = string.Empty; try { RibbonBarManager.SaveTabInfoObject(tab, selectedTab, tabLocation, null); @@ -99,7 +140,7 @@ protected void CmdUpdateClick(object sender, EventArgs e) catch (DotNetNukeException ex) { Exceptions.LogException(ex); - errMsg = (ex.ErrorCode != DotNetNukeErrorCode.NotSet) ? GetString("Err." + ex.ErrorCode) : ex.Message; + errMsg = (ex.ErrorCode != DotNetNukeErrorCode.NotSet) ? this.GetString("Err." + ex.ErrorCode) : ex.Message; } catch (Exception ex) { @@ -107,117 +148,80 @@ protected void CmdUpdateClick(object sender, EventArgs e) errMsg = ex.Message; } - //Clear the Tab's Cached modules + // Clear the Tab's Cached modules DataCache.ClearModuleCache(PortalSettings.ActiveTab.TabID); - //Update Cached Tabs as TabPath may be needed before cache is cleared + // Update Cached Tabs as TabPath may be needed before cache is cleared TabInfo tempTab; if (TabController.Instance.GetTabsByPortal(PortalSettings.ActiveTab.PortalID).TryGetValue(tab.TabID, out tempTab)) { tempTab.TabPath = tab.TabPath; } - if ((string.IsNullOrEmpty(errMsg))) + if (string.IsNullOrEmpty(errMsg)) { - Response.Redirect(_navigationManager.NavigateURL(tab.TabID)); + this.Response.Redirect(this._navigationManager.NavigateURL(tab.TabID)); } else { - errMsg = string.Format("

    {0}

    {1}

    ", GetString("Err.Header"), errMsg); - Web.UI.Utilities.RegisterAlertOnPageLoad(this, new MessageWindowParameters(errMsg) { Title = GetString("Err.Title") }); + errMsg = string.Format("

    {0}

    {1}

    ", this.GetString("Err.Header"), errMsg); + Web.UI.Utilities.RegisterAlertOnPageLoad(this, new MessageWindowParameters(errMsg) { Title = this.GetString("Err.Title") }); } } - } - - #endregion - - #region "Properties" - - public override bool Visible - { - get - { - return base.Visible && TabPermissionController.CanManagePage(); - } - set - { - base.Visible = value; - } - } - - public string ToolName - { - get - { - return "QuickUpdatePage"; - } - set - { - throw new NotSupportedException("Set ToolName not supported"); - } - } + } - #endregion - - #region "Methods" - - private TabInfo _currentTab; - - private TabInfo CurrentTab + private string LocalResourceFile { get { - //Weird - but the activetab has different skin src value than getting from the db - if (((_currentTab == null))) - { - _currentTab = TabController.Instance.GetTab(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID, false); - } - return _currentTab; + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); } } - private string LocalResourceFile + private static string FormatSkinName(string strSkinFolder, string strSkinFile) { - get + if (strSkinFolder.ToLowerInvariant() == "_default") { - return string.Format("{0}/{1}/{2}.ascx.resx", TemplateSourceDirectory, Localization.LocalResourceDirectory, GetType().BaseType.Name); + return strSkinFile; } - } - - private static PortalSettings PortalSettings - { - get + + switch (strSkinFile.ToLowerInvariant()) { - return PortalSettings.Current; + case "skin": + case "container": + case "default": + return strSkinFolder; + default: + return strSkinFolder + " - " + strSkinFile; } } private void LoadAllLists() { - LocationLst.Enabled = RibbonBarManager.CanMovePage(); - PageLst.Enabled = RibbonBarManager.CanMovePage(); - if ((LocationLst.Enabled)) + this.LocationLst.Enabled = RibbonBarManager.CanMovePage(); + this.PageLst.Enabled = RibbonBarManager.CanMovePage(); + if (this.LocationLst.Enabled) { - LoadLocationList(); - LoadPageList(); + this.LoadLocationList(); + this.LoadPageList(); } - LoadSkinList(); + this.LoadSkinList(); } private void LoadSkinList() { - SkinLst.ClearSelection(); - SkinLst.Items.Clear(); - SkinLst.Items.Add(new RadComboBoxItem(GetString("DefaultSkin"), string.Empty)); + this.SkinLst.ClearSelection(); + this.SkinLst.Items.Clear(); + this.SkinLst.Items.Add(new RadComboBoxItem(this.GetString("DefaultSkin"), string.Empty)); // load portal skins - var portalSkinsHeader = new RadComboBoxItem(GetString("PortalSkins"), string.Empty) {Enabled = false, CssClass = "SkinListHeader"}; - SkinLst.Items.Add(portalSkinsHeader); + var portalSkinsHeader = new RadComboBoxItem(this.GetString("PortalSkins"), string.Empty) { Enabled = false, CssClass = "SkinListHeader" }; + this.SkinLst.Items.Add(portalSkinsHeader); string[] arrFolders; string[] arrFiles; - string strLastFolder = ""; + string strLastFolder = string.Empty; string strRoot = PortalSettings.HomeDirectoryMapPath + SkinController.RootSkin; if (Directory.Exists(strRoot)) { @@ -232,25 +236,28 @@ private void LoadSkinList() { if (!string.IsNullOrEmpty(strLastFolder)) { - SkinLst.Items.Add(GetSeparatorItem()); + this.SkinLst.Items.Add(this.GetSeparatorItem()); } + strLastFolder = folder; } - SkinLst.Items.Add(new RadComboBoxItem(FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), - "[L]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile))); + + this.SkinLst.Items.Add(new RadComboBoxItem( + FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), + "[L]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile))); } } } - //No portal skins added, remove the header - if ((SkinLst.Items.Count == 2)) + // No portal skins added, remove the header + if (this.SkinLst.Items.Count == 2) { - SkinLst.Items.Remove(1); + this.SkinLst.Items.Remove(1); } - //load host skins - var hostSkinsHeader = new RadComboBoxItem(GetString("HostSkins"), string.Empty) {Enabled = false, CssClass = "SkinListHeader"}; - SkinLst.Items.Add(hostSkinsHeader); + // load host skins + var hostSkinsHeader = new RadComboBoxItem(this.GetString("HostSkins"), string.Empty) { Enabled = false, CssClass = "SkinListHeader" }; + this.SkinLst.Items.Add(hostSkinsHeader); strRoot = Globals.HostMapPath + SkinController.RootSkin; if (Directory.Exists(strRoot)) @@ -268,23 +275,26 @@ private void LoadSkinList() { if (!string.IsNullOrEmpty(strLastFolder)) { - SkinLst.Items.Add(GetSeparatorItem()); + this.SkinLst.Items.Add(this.GetSeparatorItem()); } + strLastFolder = folder; } - SkinLst.Items.Add(new RadComboBoxItem(FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), - "[G]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile))); + + this.SkinLst.Items.Add(new RadComboBoxItem( + FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), + "[G]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile))); } } } } - //Set the selected item - SkinLst.SelectedIndex = 0; - if ((!string.IsNullOrEmpty(CurrentTab.SkinSrc))) + // Set the selected item + this.SkinLst.SelectedIndex = 0; + if (!string.IsNullOrEmpty(this.CurrentTab.SkinSrc)) { - RadComboBoxItem selectItem = SkinLst.FindItemByValue(CurrentTab.SkinSrc); - if (((selectItem != null))) + RadComboBoxItem selectItem = this.SkinLst.FindItemByValue(this.CurrentTab.SkinSrc); + if (selectItem != null) { selectItem.Selected = true; } @@ -293,78 +303,59 @@ private void LoadSkinList() private RadComboBoxItem GetSeparatorItem() { - return new RadComboBoxItem(GetString("SkinLstSeparator"), string.Empty) {CssClass = "SkinLstSeparator", Enabled = false}; - } - - private static string FormatSkinName(string strSkinFolder, string strSkinFile) - { - if (strSkinFolder.ToLowerInvariant() == "_default") - { - return strSkinFile; - } - switch (strSkinFile.ToLowerInvariant()) - { - case "skin": - case "container": - case "default": - return strSkinFolder; - default: - return strSkinFolder + " - " + strSkinFile; - } + return new RadComboBoxItem(this.GetString("SkinLstSeparator"), string.Empty) { CssClass = "SkinLstSeparator", Enabled = false }; } private void LoadLocationList() { - LocationLst.ClearSelection(); - LocationLst.Items.Clear(); - - //LocationLst.Items.Add(new ListItem(GetString("NoLocationSelection"), "")); - //LocationLst.Items.Add(new ListItem(GetString("Before"), "BEFORE")); - //LocationLst.Items.Add(new ListItem(GetString("After"), "AFTER")); - //LocationLst.Items.Add(new ListItem(GetString("Child"), "CHILD")); - - LocationLst.AddItem(GetString("NoLocationSelection"), ""); - LocationLst.AddItem(GetString("Before"), "BEFORE"); - LocationLst.AddItem(GetString("After"), "AFTER"); - LocationLst.AddItem(GetString("Child"), "CHILD"); - - LocationLst.SelectedIndex = 0; + this.LocationLst.ClearSelection(); + this.LocationLst.Items.Clear(); + + // LocationLst.Items.Add(new ListItem(GetString("NoLocationSelection"), "")); + // LocationLst.Items.Add(new ListItem(GetString("Before"), "BEFORE")); + // LocationLst.Items.Add(new ListItem(GetString("After"), "AFTER")); + // LocationLst.Items.Add(new ListItem(GetString("Child"), "CHILD")); + this.LocationLst.AddItem(this.GetString("NoLocationSelection"), string.Empty); + this.LocationLst.AddItem(this.GetString("Before"), "BEFORE"); + this.LocationLst.AddItem(this.GetString("After"), "AFTER"); + this.LocationLst.AddItem(this.GetString("Child"), "CHILD"); + + this.LocationLst.SelectedIndex = 0; } private void LoadPageList() { - PageLst.ClearSelection(); - PageLst.Items.Clear(); + this.PageLst.ClearSelection(); + this.PageLst.Items.Clear(); - PageLst.DataTextField = "IndentedTabName"; - PageLst.DataValueField = "TabID"; - PageLst.DataSource = RibbonBarManager.GetPagesList().Where(t => !IsParentTab(t, CurrentTab.TabID)); - PageLst.DataBind(); + this.PageLst.DataTextField = "IndentedTabName"; + this.PageLst.DataValueField = "TabID"; + this.PageLst.DataSource = RibbonBarManager.GetPagesList().Where(t => !this.IsParentTab(t, this.CurrentTab.TabID)); + this.PageLst.DataBind(); - //PageLst.Items.Insert(0, new ListItem(GetString("NoPageSelection"), string.Empty)); - PageLst.InsertItem(0, GetString("NoPageSelection"), string.Empty); - PageLst.SelectedIndex = 0; + // PageLst.Items.Insert(0, new ListItem(GetString("NoPageSelection"), string.Empty)); + this.PageLst.InsertItem(0, this.GetString("NoPageSelection"), string.Empty); + this.PageLst.SelectedIndex = 0; } private string GetString(string key) { - return Localization.GetString(key, LocalResourceFile); + return Localization.GetString(key, this.LocalResourceFile); } - private bool IsParentTab(TabInfo tab, int parentTabId) - { - while (tab != null) - { - if (tab.TabID == parentTabId) - { - return true; - } + private bool IsParentTab(TabInfo tab, int parentTabId) + { + while (tab != null) + { + if (tab.TabID == parentTabId) + { + return true; + } + tab = tab.ParentId != Null.NullInteger ? TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false) : null; - } - - return false; - } + } - #endregion + return false; + } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs index b0e01271f49..8f4f0a38340 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs @@ -1,81 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Linq; -using System.Web; -using System.Web.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Web.Common; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.FileManager { + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.Common; + using Microsoft.Extensions.DependencyInjection; + using Host = DotNetNuke.Entities.Host.Host; - + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : WebUpload + /// Project : DotNetNuke + /// Class : WebUpload /// ----------------------------------------------------------------------------- /// - /// Supplies the functionality for uploading files to the Portal + /// Supplies the functionality for uploading files to the Portal. /// /// /// /// ----------------------------------------------------------------------------- public partial class WebUpload : PortalModuleBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (WebUpload)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(WebUpload)); private readonly INavigationManager _navigationManager; - public WebUpload() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - #region "Members" - + private string _DestinationFolder; private UploadType _FileType; private string _FileTypeName; + + public WebUpload() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } private string _RootFolder; - private string _UploadRoles; - - #endregion - - #region "Public Properties" - + private string _UploadRoles; + public string DestinationFolder { get { - if (_DestinationFolder == null) + if (this._DestinationFolder == null) { - _DestinationFolder = string.Empty; - if ((Request.QueryString["dest"] != null)) + this._DestinationFolder = string.Empty; + if (this.Request.QueryString["dest"] != null) { - _DestinationFolder = Globals.QueryStringDecode(Request.QueryString["dest"]); + this._DestinationFolder = Globals.QueryStringDecode(this.Request.QueryString["dest"]); } } - return PathUtils.Instance.RemoveTrailingSlash(_DestinationFolder.Replace("\\", "/")); + + return PathUtils.Instance.RemoveTrailingSlash(this._DestinationFolder.Replace("\\", "/")); } } @@ -83,18 +75,19 @@ public UploadType FileType { get { - _FileType = UploadType.File; - if ((Request.QueryString["ftype"] != null)) + this._FileType = UploadType.File; + if (this.Request.QueryString["ftype"] != null) { - //The select statement ensures that the parameter can be converted to UploadType - switch (Request.QueryString["ftype"].ToLowerInvariant()) + // The select statement ensures that the parameter can be converted to UploadType + switch (this.Request.QueryString["ftype"].ToLowerInvariant()) { case "file": - _FileType = (UploadType) Enum.Parse(typeof (UploadType), Request.QueryString["ftype"]); + this._FileType = (UploadType)Enum.Parse(typeof(UploadType), this.Request.QueryString["ftype"]); break; } } - return _FileType; + + return this._FileType; } } @@ -102,11 +95,12 @@ public string FileTypeName { get { - if (_FileTypeName == null) + if (this._FileTypeName == null) { - _FileTypeName = Localization.GetString(FileType.ToString(), LocalResourceFile); + this._FileTypeName = Localization.GetString(this.FileType.ToString(), this.LocalResourceFile); } - return _FileTypeName; + + return this._FileTypeName; } } @@ -114,13 +108,13 @@ public int FolderPortalID { get { - if (IsHostMenu) + if (this.IsHostMenu) { return Null.NullInteger; } else { - return PortalId; + return this.PortalId; } } } @@ -129,18 +123,19 @@ public string RootFolder { get { - if (_RootFolder == null) + if (this._RootFolder == null) { - if (IsHostMenu) + if (this.IsHostMenu) { - _RootFolder = Globals.HostMapPath; + this._RootFolder = Globals.HostMapPath; } else { - _RootFolder = PortalSettings.HomeDirectoryMapPath; + this._RootFolder = this.PortalSettings.HomeDirectoryMapPath; } } - return _RootFolder; + + return this._RootFolder; } } @@ -148,35 +143,60 @@ public string UploadRoles { get { - if (_UploadRoles == null) + if (this._UploadRoles == null) { - _UploadRoles = string.Empty; + this._UploadRoles = string.Empty; - if (Convert.ToString(Settings["uploadroles"]) != null) + if (Convert.ToString(this.Settings["uploadroles"]) != null) { - _UploadRoles = Convert.ToString(Settings["uploadroles"]); + this._UploadRoles = Convert.ToString(this.Settings["uploadroles"]); } } - return _UploadRoles; + + return this._UploadRoles; } - } + } + + /// ----------------------------------------------------------------------------- + /// + /// This routine determines the Return Url. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- + public string ReturnURL() + { + int TabID = this.PortalSettings.HomeTabId; - #endregion + if (this.Request.Params["rtab"] != null) + { + TabID = int.Parse(this.Request.Params["rtab"]); + } + + return this._navigationManager.NavigateURL(TabID); + } - #region "Private Methods" + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + // Customise the Control Title + this.ModuleConfiguration.ModuleTitle = Localization.GetString("UploadType" + this.FileType, this.LocalResourceFile); + } + /// ----------------------------------------------------------------------------- /// - /// This routine checks the Access Security + /// This routine checks the Access Security. /// /// /// /// ----------------------------------------------------------------------------- private void CheckSecurity() { - if (!ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, "CONTENT,EDIT") && !UserController.Instance.GetCurrentUserInfo().IsInRole("Administrators")) + if (!ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, "CONTENT,EDIT") && !UserController.Instance.GetCurrentUserInfo().IsInRole("Administrators")) { - Response.Redirect(_navigationManager.NavigateURL("Access Denied"), true); + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); } } @@ -192,55 +212,25 @@ private void LoadFolders() { var user = UserController.Instance.GetCurrentUserInfo(); - var folders = FolderManager.Instance.GetFolders(FolderPortalID, "ADD", user.UserID); - ddlFolders.Services.Parameters.Add("permission", "ADD"); - if (!String.IsNullOrEmpty(DestinationFolder)) + var folders = FolderManager.Instance.GetFolders(this.FolderPortalID, "ADD", user.UserID); + this.ddlFolders.Services.Parameters.Add("permission", "ADD"); + if (!string.IsNullOrEmpty(this.DestinationFolder)) { - ddlFolders.SelectedFolder = folders.SingleOrDefault(f => f.FolderPath == DestinationFolder); + this.ddlFolders.SelectedFolder = folders.SingleOrDefault(f => f.FolderPath == this.DestinationFolder); } else { - var rootFolder = folders.SingleOrDefault(f => f.FolderPath == ""); + var rootFolder = folders.SingleOrDefault(f => f.FolderPath == string.Empty); if (rootFolder != null) { - ddlFolders.SelectedItem = new ListItem() { Text = DynamicSharedConstants.RootFolder, Value = rootFolder.FolderID.ToString() }; + this.ddlFolders.SelectedItem = new ListItem() { Text = DynamicSharedConstants.RootFolder, Value = rootFolder.FolderID.ToString() }; } } - } - - #endregion - - #region "Public Methods" - - /// ----------------------------------------------------------------------------- - /// - /// This routine determines the Return Url - /// - /// - /// - /// ----------------------------------------------------------------------------- - public string ReturnURL() - { - int TabID = PortalSettings.HomeTabId; - - if (Request.Params["rtab"] != null) - { - TabID = int.Parse(Request.Params["rtab"]); - } - return _navigationManager.NavigateURL(TabID); - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - //Customise the Control Title - ModuleConfiguration.ModuleTitle = Localization.GetString("UploadType" + FileType, LocalResourceFile); - } + } /// ----------------------------------------------------------------------------- /// - /// The Page_Load runs when the page loads + /// The Page_Load runs when the page loads. /// /// /// @@ -250,45 +240,47 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdAdd.Click += cmdAdd_Click; - cmdReturn1.Click += cmdReturn_Click; - cmdReturn2.Click += cmdReturn_Click; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdReturn1.Click += this.cmdReturn_Click; + this.cmdReturn2.Click += this.cmdReturn_Click; try { - CheckSecurity(); + this.CheckSecurity(); - //Get localized Strings - string strHost = Localization.GetString("HostRoot", LocalResourceFile); - string strPortal = Localization.GetString("PortalRoot", LocalResourceFile); + // Get localized Strings + string strHost = Localization.GetString("HostRoot", this.LocalResourceFile); + string strPortal = Localization.GetString("PortalRoot", this.LocalResourceFile); - maxSizeWarningLabel.Text = String.Format(Localization.GetString("FileSizeRestriction", LocalResourceFile), (Config.GetMaxUploadSize()/(1024 *1024))); + this.maxSizeWarningLabel.Text = string.Format(Localization.GetString("FileSizeRestriction", this.LocalResourceFile), Config.GetMaxUploadSize() / (1024 * 1024)); - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - cmdAdd.Text = Localization.GetString("UploadType" + FileType, LocalResourceFile); - if (FileType == UploadType.File) + this.cmdAdd.Text = Localization.GetString("UploadType" + this.FileType, this.LocalResourceFile); + if (this.FileType == UploadType.File) { - foldersRow.Visible = true; - rootRow.Visible = true; - unzipRow.Visible = true; + this.foldersRow.Visible = true; + this.rootRow.Visible = true; + this.unzipRow.Visible = true; - if (IsHostMenu) + if (this.IsHostMenu) { - lblRootType.Text = strHost + ":"; - lblRootFolder.Text = RootFolder; + this.lblRootType.Text = strHost + ":"; + this.lblRootFolder.Text = this.RootFolder; } else { - lblRootType.Text = strPortal + ":"; - lblRootFolder.Text = RootFolder; + this.lblRootType.Text = strPortal + ":"; + this.lblRootFolder.Text = this.RootFolder; } - LoadFolders(); + + this.LoadFolders(); } - chkUnzip.Checked = false; + + this.chkUnzip.Checked = false; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -296,7 +288,7 @@ protected override void OnLoad(EventArgs e) /// ----------------------------------------------------------------------------- /// - /// The cmdAdd_Click runs when the Add Button is clicked + /// The cmdAdd_Click runs when the Add Button is clicked. /// /// /// @@ -307,25 +299,25 @@ private void cmdAdd_Click(object sender, EventArgs e) { try { - CheckSecurity(); - var strMessage = ""; + this.CheckSecurity(); + var strMessage = string.Empty; - var postedFile = cmdBrowse.PostedFile; + var postedFile = this.cmdBrowse.PostedFile; - //Get localized Strings - Localization.GetString("InvalidExt", LocalResourceFile); + // Get localized Strings + Localization.GetString("InvalidExt", this.LocalResourceFile); var strFileName = Path.GetFileName(postedFile.FileName); - if (!String.IsNullOrEmpty(postedFile.FileName)) + if (!string.IsNullOrEmpty(postedFile.FileName)) { - switch (FileType) + switch (this.FileType) { - case UploadType.File: //content files + case UploadType.File: // content files try { - var folder = FolderManager.Instance.GetFolder(ddlFolders.SelectedItemValueAsInt); + var folder = FolderManager.Instance.GetFolder(this.ddlFolders.SelectedItemValueAsInt); var fileManager = Services.FileSystem.FileManager.Instance; var file = fileManager.AddFile(folder, strFileName, postedFile.InputStream, true, true, postedFile.ContentType); - if (chkUnzip.Checked && file.Extension == "zip") + if (this.chkUnzip.Checked && file.Extension == "zip") { fileManager.UnzipFile(file, folder); } @@ -333,7 +325,7 @@ private void cmdAdd_Click(object sender, EventArgs e) catch (PermissionsNotMetException exc) { Logger.Warn(exc); - strMessage += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), ddlFolders.SelectedItemValueAsInt); + strMessage += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), this.ddlFolders.SelectedItemValueAsInt); } catch (NoSpaceAvailableException exc) { @@ -350,27 +342,29 @@ private void cmdAdd_Click(object sender, EventArgs e) Logger.Error(exc); strMessage += "
    " + string.Format(Localization.GetString("SaveFileError"), strFileName); } + break; } } else { - strMessage = Localization.GetString("NoFile", LocalResourceFile); + strMessage = Localization.GetString("NoFile", this.LocalResourceFile); } - if (phPaLogs.Controls.Count > 0) + + if (this.phPaLogs.Controls.Count > 0) { - tblLogs.Visible = true; + this.tblLogs.Visible = true; } - else if (String.IsNullOrEmpty(strMessage)) + else if (string.IsNullOrEmpty(strMessage)) { - Skin.AddModuleMessage(this, String.Format(Localization.GetString("FileUploadSuccess", LocalResourceFile), strFileName), ModuleMessage.ModuleMessageType.GreenSuccess); + Skin.AddModuleMessage(this, string.Format(Localization.GetString("FileUploadSuccess", this.LocalResourceFile), strFileName), ModuleMessage.ModuleMessageType.GreenSuccess); } else { - lblMessage.Text = strMessage; + this.lblMessage.Text = strMessage; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -378,18 +372,16 @@ private void cmdAdd_Click(object sender, EventArgs e) /// ----------------------------------------------------------------------------- /// - /// The cmdReturn_Click runs when the Return Button is clicked + /// The cmdReturn_Click runs when the Return Button is clicked. /// /// /// /// /// /// ----------------------------------------------------------------------------- - private void cmdReturn_Click(Object sender, EventArgs e) + private void cmdReturn_Click(object sender, EventArgs e) { - Response.Redirect(ReturnURL(), true); - } - - #endregion + this.Response.Redirect(this.ReturnURL(), true); + } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/dnn_Website_Deprecated.dnn b/DNN Platform/DotNetNuke.Website.Deprecated/dnn_Website_Deprecated.dnn index c63a8634220..51c59d6aacb 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/dnn_Website_Deprecated.dnn +++ b/DNN Platform/DotNetNuke.Website.Deprecated/dnn_Website_Deprecated.dnn @@ -1,6 +1,6 @@  - + DNN Deprecated Website Codebehind files DNN Deprecated Website Codebehind files for backward compability. diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/packages.config b/DNN Platform/DotNetNuke.Website.Deprecated/packages.config index 015e7e36813..4fca05e5f8c 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/packages.config +++ b/DNN Platform/DotNetNuke.Website.Deprecated/packages.config @@ -1,5 +1,6 @@ - - - - + + + + + \ No newline at end of file diff --git a/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs b/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs index 0570746802a..1a8326373e6 100644 --- a/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs +++ b/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs @@ -1,32 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using DotNetNuke.Common; -using DotNetNuke.Framework; -using DotNetNuke.HttpModules.Config; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Analytics; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Analytics { + using System; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + + using DotNetNuke.Common; + using DotNetNuke.Framework; + using DotNetNuke.HttpModules.Config; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Analytics; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- /// - /// This module contains functionality for injecting web analytics scripts into the page + /// This module contains functionality for injecting web analytics scripts into the page. /// /// ----------------------------------------------------------------------------- public class AnalyticsModule : IHttpModule { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (AnalyticsModule)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AnalyticsModule)); public string ModuleName { @@ -34,10 +30,8 @@ public string ModuleName { return "AnalyticsModule"; } - } - - #region IHttpModule Members - + } + public void Init(HttpApplication application) { application.PreRequestHandlerExecute += OnPreRequestHandlerExecute; @@ -45,39 +39,49 @@ public void Init(HttpApplication application) public void Dispose() { - } - - #endregion - + } + private static void OnPreRequestHandlerExecute(object sender, EventArgs e) { try { - //First check if we are upgrading/installing or if it is a non-page request - var app = (HttpApplication) sender; + // First check if we are upgrading/installing or if it is a non-page request + var app = (HttpApplication)sender; var request = app.Request; - if (!Initialize.ProcessHttpModule(request, false, false)) return; - - if (HttpContext.Current == null) return; + if (!Initialize.ProcessHttpModule(request, false, false)) + { + return; + } + + if (HttpContext.Current == null) + { + return; + } + var context = HttpContext.Current; - - if (context == null) return; - - var page = context.Handler as CDefault; - if (page == null) return; + if (context == null) + { + return; + } + + var page = context.Handler as CDefault; + if (page == null) + { + return; + } + page.InitComplete += OnPageInitComplete; - page.PreRender += OnPagePreRender; + page.PreRender += OnPagePreRender; } catch (Exception ex) { - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("Analytics.AnalyticsModule", "OnPreRequestHandlerExecute"); log.AddProperty("ExceptionMessage", ex.Message); LogController.Instance.AddLog(log); Logger.Error(log); - } } @@ -85,8 +89,7 @@ private static void OnPageInitComplete(object sender, EventArgs e) { InitializeAnalyticsControls(sender as Page, true); } - - + private static void OnPagePreRender(object sender, EventArgs e) { InitializeAnalyticsControls(sender as Page, false); @@ -96,11 +99,17 @@ private static void InitializeAnalyticsControls(Page page, bool injectTop) { try { - var analyticsEngines = AnalyticsEngineConfiguration.GetConfig().AnalyticsEngines; - if (analyticsEngines == null || analyticsEngines.Count == 0) return; - - if (page == null) return; - + var analyticsEngines = AnalyticsEngineConfiguration.GetConfig().AnalyticsEngines; + if (analyticsEngines == null || analyticsEngines.Count == 0) + { + return; + } + + if (page == null) + { + return; + } + foreach (AnalyticsEngine engine in analyticsEngines) { if (string.IsNullOrEmpty(engine.ElementId) || engine.InjectTop != injectTop) @@ -109,30 +118,47 @@ private static void InitializeAnalyticsControls(Page page, bool injectTop) } AnalyticsEngineBase objEngine; - if ((!string.IsNullOrEmpty(engine.EngineType))) + if (!string.IsNullOrEmpty(engine.EngineType)) { var engineType = Type.GetType(engine.EngineType); - if (engineType == null) - objEngine = new GenericAnalyticsEngine(); - else - objEngine = (AnalyticsEngineBase) Activator.CreateInstance(engineType); + if (engineType == null) + { + objEngine = new GenericAnalyticsEngine(); + } + else + { + objEngine = (AnalyticsEngineBase)Activator.CreateInstance(engineType); + } } else { objEngine = new GenericAnalyticsEngine(); } - if (objEngine == null) continue; - + + if (objEngine == null) + { + continue; + } + var script = engine.ScriptTemplate; - if ((string.IsNullOrEmpty(script))) continue; - + if (string.IsNullOrEmpty(script)) + { + continue; + } + script = objEngine.RenderScript(script); - if ((string.IsNullOrEmpty(script))) continue; - - var element = (HtmlContainerControl) page.FindControl(engine.ElementId); - if (element == null) continue; - - var scriptControl = new LiteralControl {Text = script}; + if (string.IsNullOrEmpty(script)) + { + continue; + } + + var element = (HtmlContainerControl)page.FindControl(engine.ElementId); + if (element == null) + { + continue; + } + + var scriptControl = new LiteralControl { Text = script }; if (engine.InjectTop) { element.Controls.AddAt(0, scriptControl); @@ -145,12 +171,11 @@ private static void InitializeAnalyticsControls(Page page, bool injectTop) } catch (Exception ex) { - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("Analytics.AnalyticsModule", "OnPagePreRender"); log.AddProperty("ExceptionMessage", ex.Message); LogController.Instance.AddLog(log); Logger.Error(ex); - } } } diff --git a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs index b18be530a37..69d1bcf3e14 100644 --- a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs +++ b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Config { + using System; + [Serializable] public class AnalyticsEngine { @@ -22,11 +17,12 @@ public string EngineType { get { - return _engineType; + return this._engineType; } + set { - _engineType = value; + this._engineType = value; } } @@ -34,11 +30,12 @@ public string ScriptTemplate { get { - return _scriptTemplate; + return this._scriptTemplate; } + set { - _scriptTemplate = value; + this._scriptTemplate = value; } } @@ -46,11 +43,12 @@ public string ElementId { get { - return _elementId; + return this._elementId; } + set { - _elementId = value; + this._elementId = value; } } @@ -58,11 +56,12 @@ public bool InjectTop { get { - return _injectTop; + return this._injectTop; } + set { - _injectTop = value; + this._injectTop = value; } } } diff --git a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs index 4626ff6ef3b..4ce0e757107 100644 --- a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs +++ b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Config { + using System; + using System.Collections; + [Serializable] public class AnalyticsEngineCollection : CollectionBase { @@ -18,17 +13,18 @@ public virtual AnalyticsEngine this[int index] { get { - return (AnalyticsEngine) base.List[index]; + return (AnalyticsEngine)this.List[index]; } + set { - base.List[index] = value; + this.List[index] = value; } } public void Add(AnalyticsEngine a) { - InnerList.Add(a); + this.InnerList.Add(a); } } } diff --git a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs index 7c894e46b5e..dca96466c54 100644 --- a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs +++ b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml.Serialization; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Config { + using System; + using System.IO; + using System.Xml.Serialization; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.HttpModules.Analytics /// Project: HttpModules @@ -25,84 +20,90 @@ namespace DotNetNuke.HttpModules.Config /// ----------------------------------------------------------------------------- /// /// Class definition for AnalyticsEngineConfiguration which is used to create - /// an AnalyticsEngineCollection + /// an AnalyticsEngineCollection. /// /// /// /// ----------------------------------------------------------------------------- - [Serializable, XmlRoot("AnalyticsEngineConfig")] + [Serializable] + [XmlRoot("AnalyticsEngineConfig")] public class AnalyticsEngineConfiguration { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (AnalyticsEngineConfiguration)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AnalyticsEngineConfiguration)); private AnalyticsEngineCollection _analyticsEngines; public AnalyticsEngineCollection AnalyticsEngines { get { - return _analyticsEngines; + return this._analyticsEngines; } + set { - _analyticsEngines = value; + this._analyticsEngines = value; } } public static AnalyticsEngineConfiguration GetConfig() { - var config = new AnalyticsEngineConfiguration {AnalyticsEngines = new AnalyticsEngineCollection()}; + var config = new AnalyticsEngineConfiguration { AnalyticsEngines = new AnalyticsEngineCollection() }; FileStream fileReader = null; string filePath = null; try { - config = (AnalyticsEngineConfiguration) DataCache.GetCache("AnalyticsEngineConfig"); - if ((config == null)) + config = (AnalyticsEngineConfiguration)DataCache.GetCache("AnalyticsEngineConfig"); + if (config == null) { filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.SiteAnalytics); - //Create a FileStream for the Config file + // Create a FileStream for the Config file fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); var doc = new XPathDocument(fileReader); - config = new AnalyticsEngineConfiguration {AnalyticsEngines = new AnalyticsEngineCollection()}; + config = new AnalyticsEngineConfiguration { AnalyticsEngines = new AnalyticsEngineCollection() }; foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsEngineConfig/Engines/AnalyticsEngine")) { - var analyticsEngine = new AnalyticsEngine - { - EngineType = nav.SelectSingleNode("EngineType").Value, - ElementId = nav.SelectSingleNode("ElementId").Value, - InjectTop = Convert.ToBoolean(nav.SelectSingleNode("InjectTop").Value), - ScriptTemplate = nav.SelectSingleNode("ScriptTemplate").Value - }; + var analyticsEngine = new AnalyticsEngine + { + EngineType = nav.SelectSingleNode("EngineType").Value, + ElementId = nav.SelectSingleNode("ElementId").Value, + InjectTop = Convert.ToBoolean(nav.SelectSingleNode("InjectTop").Value), + ScriptTemplate = nav.SelectSingleNode("ScriptTemplate").Value, + }; config.AnalyticsEngines.Add(analyticsEngine); } + if (File.Exists(filePath)) { - //Set back into Cache + // Set back into Cache DataCache.SetCache("AnalyticsEngineConfig", config, new DNNCacheDependency(filePath)); } } } catch (Exception ex) { - //log it - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + // log it + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("Analytics.AnalyticsEngineConfiguration", "GetConfig Failed"); - if (!string.IsNullOrEmpty(filePath)) - log.AddProperty("FilePath", filePath); + if (!string.IsNullOrEmpty(filePath)) + { + log.AddProperty("FilePath", filePath); + } + log.AddProperty("ExceptionMessage", ex.Message); LogController.Instance.AddLog(log); Logger.Error(log); - } finally { if (fileReader != null) { - //Close the Reader + // Close the Reader fileReader.Close(); } } + return config; } } diff --git a/DNN Platform/HttpModules/Compression/CompressionModule.cs b/DNN Platform/HttpModules/Compression/CompressionModule.cs index 14dd9ad6c75..62b43cd30da 100644 --- a/DNN Platform/HttpModules/Compression/CompressionModule.cs +++ b/DNN Platform/HttpModules/Compression/CompressionModule.cs @@ -1,29 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Compression { - + using System; + using System.IO; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + [Obsolete("The http modules in web.config removed in 9.2.0, this class need to be removed in future release for upgrade compactible.. Scheduled removal in v11.0.0.")] public class CompressionModule : IHttpModule - { - #region IHttpModule Members - + { /// - /// Init the handler and fulfill + /// Init the handler and fulfill . /// /// /// This implementation hooks the ReleaseRequestState and PreSendRequestHeaders events to @@ -36,15 +28,13 @@ public void Init(HttpApplication context) } /// - /// Implementation of + /// Implementation of . /// /// /// Currently empty. Nothing to really do, as I have no member variables. /// public void Dispose() { - } - - #endregion + } } } diff --git a/DNN Platform/HttpModules/Compression/Config/Enums.cs b/DNN Platform/HttpModules/Compression/Config/Enums.cs index 419eaa4ac01..49cc6ac746b 100644 --- a/DNN Platform/HttpModules/Compression/Config/Enums.cs +++ b/DNN Platform/HttpModules/Compression/Config/Enums.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.HttpModules.Compression { /// - /// The available compression algorithms to use with the HttpCompressionModule + /// The available compression algorithms to use with the HttpCompressionModule. /// public enum Algorithms { Deflate = 2, GZip = 1, None = 0, - Default = -1 + Default = -1, } } diff --git a/DNN Platform/HttpModules/Compression/Config/Settings.cs b/DNN Platform/HttpModules/Compression/Config/Settings.cs index 223cb0e5192..f369c1c5d69 100644 --- a/DNN Platform/HttpModules/Compression/Config/Settings.cs +++ b/DNN Platform/HttpModules/Compression/Config/Settings.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.IO; -using System.Text.RegularExpressions; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Services.Cache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Compression { + using System; + using System.Collections.Specialized; + using System.IO; + using System.Text.RegularExpressions; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Services.Cache; + /// - /// This class encapsulates the settings for an HttpCompressionModule + /// This class encapsulates the settings for an HttpCompressionModule. /// [Serializable] public class Settings @@ -29,12 +24,12 @@ public class Settings private Settings() { - _preferredAlgorithm = Algorithms.None; - _excludedPaths = new StringCollection(); + this._preferredAlgorithm = Algorithms.None; + this._excludedPaths = new StringCollection(); } /// - /// The default settings. Deflate + normal. + /// Gets the default settings. Deflate + normal. /// public static Settings Default { @@ -45,29 +40,31 @@ public static Settings Default } /// - /// The preferred algorithm to use for compression + /// Gets the preferred algorithm to use for compression. /// public Algorithms PreferredAlgorithm { get { - return _preferredAlgorithm; + return this._preferredAlgorithm; } } /// - /// Get the current settings from the xml config file - /// + /// Get the current settings from the xml config file. + ///
    + /// public static Settings GetSettings() { - var settings = (Settings) DataCache.GetCache("CompressionConfig"); + var settings = (Settings)DataCache.GetCache("CompressionConfig"); if (settings == null) { settings = Default; - //Place this in a try/catch as during install the host settings will not exist + + // Place this in a try/catch as during install the host settings will not exist try { - settings._preferredAlgorithm = (Algorithms) Host.HttpCompressionAlgorithm; + settings._preferredAlgorithm = (Algorithms)Host.HttpCompressionAlgorithm; } catch (Exception e) { @@ -76,7 +73,7 @@ public static Settings GetSettings() string filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.Compression); - //Create a FileStream for the Config file + // Create a FileStream for the Config file using (var fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var doc = new XPathDocument(fileReader); @@ -85,24 +82,26 @@ public static Settings GetSettings() settings._excludedPaths.Add(nav.Value.ToLowerInvariant()); } } - if ((File.Exists(filePath))) + + if (File.Exists(filePath)) { - //Set back into Cache + // Set back into Cache DataCache.SetCache("CompressionConfig", settings, new DNNCacheDependency(filePath)); } } + return settings; } /// - /// Looks for a given path in the list of paths excluded from compression + /// Looks for a given path in the list of paths excluded from compression. /// - /// the relative url to check - /// true if excluded, false if not + /// the relative url to check. + /// true if excluded, false if not. public bool IsExcludedPath(string relUrl) { bool match = false; - foreach (string path in _excludedPaths) + foreach (string path in this._excludedPaths) { if (relUrl.ToLowerInvariant().Contains(path)) { @@ -110,6 +109,7 @@ public bool IsExcludedPath(string relUrl) break; } } + return match; } } diff --git a/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs b/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs index 8bc3e4ae381..070291ae25d 100644 --- a/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs @@ -1,39 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Compression { + using System.IO; + using System.Web; + /// - /// Base for any HttpFilter that performing compression + /// Base for any HttpFilter that performing compression. /// /// /// When implementing this class, you need to implement a - /// along with a . The latter corresponds to a + /// along with a . The latter corresponds to a /// content coding (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5) /// that your implementation will support. /// public abstract class CompressingFilter : HttpOutputFilter { - private bool _HasWrittenHeaders; - - /// - /// Protected constructor that sets up the underlying stream we're compressing into + private bool _HasWrittenHeaders; + + /// + /// Initializes a new instance of the class. + /// Protected constructor that sets up the underlying stream we're compressing into. /// - /// The stream we're wrapping up - protected CompressingFilter(Stream baseStream) : base(baseStream) + /// The stream we're wrapping up. + protected CompressingFilter(Stream baseStream) + : base(baseStream) { } /// - /// The name of the content-encoding that's being implemented + /// Gets the name of the content-encoding that's being implemented. /// /// /// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5 for more @@ -42,13 +39,13 @@ protected CompressingFilter(Stream baseStream) : base(baseStream) public abstract string ContentEncoding { get; } /// - /// Keeps track of whether or not we're written the compression headers + /// Gets a value indicating whether keeps track of whether or not we're written the compression headers. /// protected bool HasWrittenHeaders { get { - return _HasWrittenHeaders; + return this._HasWrittenHeaders; } } @@ -57,12 +54,12 @@ protected bool HasWrittenHeaders /// internal void WriteHeaders() { - //this is dangerous. if Response.End is called before the filter is used, directly or indirectly, - //the content will not pass through the filter. However, this header will still be appended. - //Look for handling cases in PreRequestSendHeaders and Pre - HttpContext.Current.Response.AppendHeader("Content-Encoding", ContentEncoding); + // this is dangerous. if Response.End is called before the filter is used, directly or indirectly, + // the content will not pass through the filter. However, this header will still be appended. + // Look for handling cases in PreRequestSendHeaders and Pre + HttpContext.Current.Response.AppendHeader("Content-Encoding", this.ContentEncoding); HttpContext.Current.Response.AppendHeader("X-Compressed-By", "DotNetNuke-Compression"); - _HasWrittenHeaders = true; + this._HasWrittenHeaders = true; } } } diff --git a/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs b/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs index 8000694d4a1..25229305e32 100644 --- a/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.IO.Compression; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Compression { + using System.IO; + using System.IO.Compression; + /// /// Summary description for DeflateFilter. /// @@ -18,9 +13,10 @@ public class DeflateFilter : CompressingFilter { private readonly DeflateStream m_stream; - public DeflateFilter(Stream baseStream) : base(baseStream) + public DeflateFilter(Stream baseStream) + : base(baseStream) { - m_stream = new DeflateStream(baseStream, CompressionMode.Compress); + this.m_stream = new DeflateStream(baseStream, CompressionMode.Compress); } public override string ContentEncoding @@ -33,21 +29,22 @@ public override string ContentEncoding public override void Write(byte[] buffer, int offset, int count) { - if (!HasWrittenHeaders) + if (!this.HasWrittenHeaders) { - WriteHeaders(); + this.WriteHeaders(); } - m_stream.Write(buffer, offset, count); + + this.m_stream.Write(buffer, offset, count); } public override void Close() { - m_stream.Close(); + this.m_stream.Close(); } public override void Flush() { - m_stream.Flush(); + this.m_stream.Flush(); } } } diff --git a/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs b/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs index 27504d32df1..79b993b87cc 100644 --- a/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs @@ -1,26 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.IO.Compression; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Compression { + using System.IO; + using System.IO.Compression; + /// - /// This is a little filter to support HTTP compression using GZip + /// This is a little filter to support HTTP compression using GZip. /// public class GZipFilter : CompressingFilter { private readonly GZipStream m_stream; - public GZipFilter(Stream baseStream) : base(baseStream) + public GZipFilter(Stream baseStream) + : base(baseStream) { - m_stream = new GZipStream(baseStream, CompressionMode.Compress); + this.m_stream = new GZipStream(baseStream, CompressionMode.Compress); } public override string ContentEncoding @@ -33,21 +29,22 @@ public override string ContentEncoding public override void Write(byte[] buffer, int offset, int count) { - if (!HasWrittenHeaders) + if (!this.HasWrittenHeaders) { - WriteHeaders(); + this.WriteHeaders(); } - m_stream.Write(buffer, offset, count); + + this.m_stream.Write(buffer, offset, count); } public override void Close() { - m_stream.Close(); + this.m_stream.Close(); } public override void Flush() { - m_stream.Flush(); + this.m_stream.Flush(); } } } diff --git a/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs b/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs index 45326fc5e8d..c73dc96310c 100644 --- a/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Compression { + using System; + using System.IO; + public abstract class HttpOutputFilter : Stream { private readonly Stream _sink; protected HttpOutputFilter(Stream baseStream) { - _sink = baseStream; + this._sink = baseStream; } - protected Stream BaseStream + public override bool CanRead { get { - return _sink; + return false; } } - public override bool CanRead + public override bool CanSeek { get { @@ -36,11 +31,11 @@ public override bool CanRead } } - public override bool CanSeek + protected Stream BaseStream { get { - return false; + return this._sink; } } @@ -48,7 +43,7 @@ public override bool CanWrite { get { - return _sink.CanWrite; + return this._sink.CanWrite; } } @@ -66,6 +61,7 @@ public override long Position { throw new NotSupportedException(); } + set { throw new NotSupportedException(); @@ -84,12 +80,12 @@ public override void SetLength(long length) public override void Close() { - _sink.Close(); + this._sink.Close(); } public override void Flush() { - _sink.Flush(); + this._sink.Flush(); } public override int Read(byte[] buffer, int offset, int count) diff --git a/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs b/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs index f7b151cd4db..e9eadf74035 100644 --- a/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs +++ b/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs @@ -1,5 +1,10 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +using System; using System.Web; + using DotNetNuke.Common.Extensions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Web.Infrastructure.DynamicModuleHelper; @@ -10,48 +15,35 @@ namespace DotNetNuke.HttpModules.DependencyInjection { public class ServiceRequestScopeModule : IHttpModule { + private static IServiceProvider _serviceProvider; + public static void InitModule() { DynamicModuleUtility.RegisterModule(typeof(ServiceRequestScopeModule)); } - private static IServiceProvider _serviceProvider; - - public void Init(HttpApplication context) - { - context.BeginRequest += Context_BeginRequest; - context.EndRequest += Context_EndRequest; - } - public static void SetServiceProvider(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } - private void Context_BeginRequest(object sender, EventArgs e) + public void Init(HttpApplication context) { - var context = ((HttpApplication)sender).Context; - context.SetScope(_serviceProvider.CreateScope()); - } - - private void Context_EndRequest(object sender, EventArgs e) - { - var context = ((HttpApplication)sender).Context; - context.GetScope()?.Dispose(); - context.ClearScope(); + context.BeginRequest += this.Context_BeginRequest; + context.EndRequest += this.Context_EndRequest; } /// - /// Performs application-defined tasks associated with freeing, + /// Performs application-defined tasks associated with freeing, /// releasing, or resetting unmanaged resources. /// public void Dispose() { - Dispose(true); + this.Dispose(true); } /// - /// Performs application-defined tasks associated with freeing, + /// Performs application-defined tasks associated with freeing, /// releasing, or resetting unmanaged resources. /// /// @@ -61,5 +53,18 @@ protected virtual void Dispose(bool disposing) { // left empty by design } + + private void Context_BeginRequest(object sender, EventArgs e) + { + var context = ((HttpApplication)sender).Context; + context.SetScope(_serviceProvider.CreateScope()); + } + + private void Context_EndRequest(object sender, EventArgs e) + { + var context = ((HttpApplication)sender).Context; + context.GetScope()?.Dispose(); + context.ClearScope(); + } } } diff --git a/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj b/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj index 617a0078af6..c9b9ec652a3 100644 --- a/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj +++ b/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj @@ -1,143 +1,150 @@ - - - - 9.0.30729 - 2.0 - {3D9C3F5F-1D2D-4D89-995B-438055A5E3A6} - Debug - AnyCPU - DotNetNuke.HttpModules - Library - v4.7.2 - DotNetNuke.HttpModules - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - bin\ - bin\DotNetNuke.HttpModules.XML - true - true - 4 - full - AllRules.ruleset - 1591 - 7 - DEBUG - - - bin\ - bin\DotNetNuke.HttpModules.XML - true - true - 4 - pdbonly - AllRules.ruleset - 1591 - true - 7 - - - - False - ..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll - - - - ..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - - - - - - - - - - - SolutionInfo.cs - - - - - - Code - - - - - - - - - - - {6928A9B1-F88A-4581-A132-D3EB38669BB0} - DotNetNuke.Abstractions - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(MSBuildProjectDirectory)\..\.. - - - - - - - - - + + + + 9.0.30729 + 2.0 + {3D9C3F5F-1D2D-4D89-995B-438055A5E3A6} + Debug + AnyCPU + DotNetNuke.HttpModules + Library + v4.7.2 + DotNetNuke.HttpModules + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + bin\ + bin\DotNetNuke.HttpModules.XML + true + true + 4 + full + AllRules.ruleset + 1591 + 7 + DEBUG + + + bin\ + bin\DotNetNuke.HttpModules.XML + true + true + 4 + pdbonly + AllRules.ruleset + 1591 + true + 7 + + + + False + ..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll + + + + ..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll + + + + + + + + + + + SolutionInfo.cs + + + + + + Code + + + + + + + + + + + {6928A9B1-F88A-4581-A132-D3EB38669BB0} + DotNetNuke.Abstractions + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + stylecop.json + + + + + + + + + + + + + + + + $(MSBuildProjectDirectory)\..\.. + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/HttpModules/Exception/ExceptionModule.cs b/DNN Platform/HttpModules/Exception/ExceptionModule.cs index 689ed3c3167..99a505b3672 100644 --- a/DNN Platform/HttpModules/Exception/ExceptionModule.cs +++ b/DNN Platform/HttpModules/Exception/ExceptionModule.cs @@ -1,30 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Exceptions { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Log.EventLog; + /// - /// Handles the exception that occur with http modules + /// Handles the exception that occur with http modules. /// public class ExceptionModule : IHttpModule { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ExceptionModule)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExceptionModule)); + /// /// Gets the name of the module. /// /// - /// The name of the module: "ExceptionModule" + /// The name of the module: "ExceptionModule". /// public string ModuleName { @@ -32,38 +29,34 @@ public string ModuleName { return "ExceptionModule"; } - } - - #region IHttpModule Members - + } + /// /// Initializes the error handling for the specified application. /// /// The application. public void Init(HttpApplication application) { - application.Error += OnErrorRequest; + application.Error += this.OnErrorRequest; } public void Dispose() { - } - - #endregion - + } + /// /// Called when error handling is requested. /// - /// The object with the error + /// The object with the error. /// The instance containing the event data. public void OnErrorRequest(object s, EventArgs e) { try { - if(HttpContext.Current == null) - { - return; - } + if (HttpContext.Current == null) + { + return; + } HttpContext contxt = HttpContext.Current; HttpServerUtility srver = contxt.Server; @@ -76,7 +69,7 @@ public void OnErrorRequest(object s, EventArgs e) Exception lastException = srver.GetLastError(); - //HttpExceptions are logged elsewhere + // HttpExceptions are logged elsewhere if (!(lastException is HttpException)) { var lex = new Exception("Unhandled Error: ", srver.GetLastError()); @@ -85,17 +78,17 @@ public void OnErrorRequest(object s, EventArgs e) { objExceptionLog.AddLog(lex); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } } } catch (Exception exc) { - //it is possible when terminating the request for the context not to exist - //in this case we just want to exit since there is nothing else we can do - Logger.Error(exc); + // it is possible when terminating the request for the context not to exist + // in this case we just want to exit since there is nothing else we can do + Logger.Error(exc); } } } diff --git a/DNN Platform/HttpModules/Membership/MembershipModule.cs b/DNN Platform/HttpModules/Membership/MembershipModule.cs index 3d70e30368a..59faa367362 100644 --- a/DNN Platform/HttpModules/Membership/MembershipModule.cs +++ b/DNN Platform/HttpModules/Membership/MembershipModule.cs @@ -1,40 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; -using System.Linq; -using System.Security.Principal; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Security; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.HttpModules.Services; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.Skins.EventListeners; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.UserRequest; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Membership { + using System; + using System.Globalization; + using System.Linq; + using System.Security.Principal; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Security; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.HttpModules.Services; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + using DotNetNuke.Services.UserRequest; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.Skins.EventListeners; + /// - /// Information about membership + /// Information about membership. /// public class MembershipModule : IHttpModule { @@ -43,11 +39,12 @@ public class MembershipModule : IHttpModule private static readonly Regex NameRegex = new Regex(@"\w+[\\]+(?=)", RegexOptions.Compiled); private static string _cultureCode; + /// /// Gets the name of the module. /// /// - /// The name of the module: "DNNMembershipModule" + /// The name of the module: "DNNMembershipModule". /// public string ModuleName { @@ -63,65 +60,13 @@ private static string CurrentCulture { if (string.IsNullOrEmpty(_cultureCode)) { - _cultureCode = Localization.GetPageLocale(PortalSettings.Current).Name; + _cultureCode = Localization.GetPageLocale(PortalSettings.Current).Name; } return _cultureCode; } - } - - #region IHttpModule Members - - /// - /// Initializes the specified application. - /// - /// The application. - public void Init(HttpApplication application) - { - application.AuthenticateRequest += OnAuthenticateRequest; - application.PreSendRequestHeaders += OnPreSendRequestHeaders; - } - - /// - /// Disposes of the resources (other than memory) used by the module that implements . - /// - public void Dispose() - { - } - - #endregion - - private void OnAuthenticateRequest(object sender, EventArgs e) - { - var application = (HttpApplication) sender; - AuthenticateRequest(new HttpContextWrapper(application.Context), false); - } - - //DNN-6973: if the authentication cookie set by cookie slide in membership, - //then use SignIn method instead if current portal is in portal group. - private void OnPreSendRequestHeaders(object sender, EventArgs e) - { - var application = (HttpApplication)sender; - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var hasAuthCookie = application.Response.Headers["Set-Cookie"] != null - && application.Response.Headers["Set-Cookie"].Contains(FormsAuthentication.FormsCookieName); - if (portalSettings != null && hasAuthCookie && !application.Context.Items.Contains("DNN_UserSignIn")) - { - var isInPortalGroup = PortalController.IsMemberOfPortalGroup(portalSettings.PortalId); - if (isInPortalGroup) - { - var authCookie = application.Response.Cookies[FormsAuthentication.FormsCookieName]; - if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value) && string.IsNullOrEmpty(authCookie.Domain)) - { - application.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); - PortalSecurity.Instance.SignIn(UserController.Instance.GetCurrentUserInfo(), false); - } - } - } - } - - + } + /// /// Called when unverified user skin initialize. /// @@ -130,7 +75,7 @@ private void OnPreSendRequestHeaders(object sender, EventArgs e) public static void OnUnverifiedUserSkinInit(object sender, SkinEventArgs e) { var strMessage = Localization.GetString("UnverifiedUser", Localization.SharedResourceFile, CurrentCulture); - UI.Skins.Skin.AddPageMessage(e.Skin, "", strMessage, ModuleMessage.ModuleMessageType.YellowWarning); + UI.Skins.Skin.AddPageMessage(e.Skin, string.Empty, strMessage, ModuleMessage.ModuleMessageType.YellowWarning); } /// @@ -143,13 +88,13 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow HttpRequestBase request = context.Request; HttpResponseBase response = context.Response; - //First check if we are upgrading/installing + // First check if we are upgrading/installing if (!Initialize.ProcessHttpModule(context.ApplicationInstance.Request, allowUnknownExtensions, false)) { return; } - //Obtain PortalSettings from Current Context + // Obtain PortalSettings from Current Context PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); bool isActiveDirectoryAuthHeaderPresent = false; @@ -162,28 +107,29 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow } } - if (request.IsAuthenticated && !isActiveDirectoryAuthHeaderPresent && portalSettings != null) + if (request.IsAuthenticated && !isActiveDirectoryAuthHeaderPresent && portalSettings != null) { var user = UserController.GetCachedUser(portalSettings.PortalId, context.User.Identity.Name); - //if current login is from windows authentication, the ignore the process + + // if current login is from windows authentication, the ignore the process if (user == null && context.User is WindowsPrincipal) { return; } - //authenticate user and set last login ( this is necessary for users who have a permanent Auth cookie set ) + // authenticate user and set last login ( this is necessary for users who have a permanent Auth cookie set ) if (RequireLogout(context, user)) { var portalSecurity = PortalSecurity.Instance; portalSecurity.SignOut(); - //Remove user from cache + // Remove user from cache if (user != null) { DataCache.ClearUserCache(portalSettings.PortalId, context.User.Identity.Name); } - //Redirect browser back to home page + // Redirect browser back to home page response.Redirect(request.RawUrl, true); return; } @@ -199,16 +145,16 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessageType, ModuleMessage.ModuleMessageType.GreenSuccess); } - //if users LastActivityDate is outside of the UsersOnlineTimeWindow then record user activity + // if users LastActivityDate is outside of the UsersOnlineTimeWindow then record user activity if (DateTime.Compare(user.Membership.LastActivityDate.AddMinutes(Host.UsersOnlineTimeWindow), DateTime.Now) < 0) { - //update LastActivityDate and IP Address for user + // update LastActivityDate and IP Address for user user.Membership.LastActivityDate = DateTime.Now; user.LastIPAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(request); UserController.UpdateUser(portalSettings.PortalId, user, false, false); } - //check for RSVP code + // check for RSVP code if (request.QueryString["rsvp"] != null && !string.IsNullOrEmpty(request.QueryString["rsvp"])) { foreach (var role in RoleController.Instance.GetRoles(portalSettings.PortalId, r => (r.SecurityMode != SecurityMode.SocialGroup || r.IsPublic) && r.Status == RoleStatus.Approved)) @@ -220,7 +166,7 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow } } - //save userinfo object in context + // save userinfo object in context if (context.Items["UserInfo"] != null) { context.Items["UserInfo"] = user; @@ -230,7 +176,7 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow context.Items.Add("UserInfo", user); } - //Localization.SetLanguage also updates the user profile, so this needs to go after the profile is loaded + // Localization.SetLanguage also updates the user profile, so this needs to go after the profile is loaded if (request.RawUrl != null && !ServicesModule.ServiceApi.IsMatch(request.RawUrl)) { Localization.SetLanguage(user.Profile.PreferredLocale); @@ -242,13 +188,60 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow context.Items.Add("UserInfo", new UserInfo()); } } + + /// + /// Initializes the specified application. + /// + /// The application. + public void Init(HttpApplication application) + { + application.AuthenticateRequest += this.OnAuthenticateRequest; + application.PreSendRequestHeaders += this.OnPreSendRequestHeaders; + } + + /// + /// Disposes of the resources (other than memory) used by the module that implements . + /// + public void Dispose() + { + } + + private void OnAuthenticateRequest(object sender, EventArgs e) + { + var application = (HttpApplication)sender; + AuthenticateRequest(new HttpContextWrapper(application.Context), false); + } + + // DNN-6973: if the authentication cookie set by cookie slide in membership, + // then use SignIn method instead if current portal is in portal group. + private void OnPreSendRequestHeaders(object sender, EventArgs e) + { + var application = (HttpApplication)sender; + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var hasAuthCookie = application.Response.Headers["Set-Cookie"] != null + && application.Response.Headers["Set-Cookie"].Contains(FormsAuthentication.FormsCookieName); + if (portalSettings != null && hasAuthCookie && !application.Context.Items.Contains("DNN_UserSignIn")) + { + var isInPortalGroup = PortalController.IsMemberOfPortalGroup(portalSettings.PortalId); + if (isInPortalGroup) + { + var authCookie = application.Response.Cookies[FormsAuthentication.FormsCookieName]; + if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value) && string.IsNullOrEmpty(authCookie.Domain)) + { + application.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); + PortalSecurity.Instance.SignIn(UserController.Instance.GetCurrentUserInfo(), false); + } + } + } + } private static bool RequireLogout(HttpContextBase context, UserInfo user) { try { if (user == null || user.IsDeleted || user.Membership.LockedOut - || !user.Membership.Approved && !user.IsInRole("Unverified Users") + || (!user.Membership.Approved && !user.IsInRole("Unverified Users")) || !user.Username.Equals(context.User.Identity.Name, StringComparison.InvariantCultureIgnoreCase)) { return true; @@ -261,7 +254,12 @@ private static bool RequireLogout(HttpContextBase context, UserInfo user) } // if user's password changed after the user cookie created, then force user to login again. - var issueDate = ((FormsIdentity)context.User.Identity)?.Ticket.IssueDate; + DateTime? issueDate = null; + if (context.User.Identity is FormsIdentity formsIdentity) + { + issueDate = formsIdentity.Ticket.IssueDate; + } + return !Null.IsNull(issueDate) && issueDate < user.Membership.LastPasswordChangeDate; } catch (Exception ex) diff --git a/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs b/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs index 2bd861693ed..b5ba2015973 100644 --- a/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs +++ b/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs @@ -1,79 +1,72 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Urls; -using DotNetNuke.HttpModules.Services; -using DotNetNuke.Services.Mobile; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules { + using System; + using System.Collections.Generic; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Urls; + using DotNetNuke.HttpModules.Services; + using DotNetNuke.Services.Mobile; + public class MobileRedirectModule : IHttpModule { private IRedirectionController _redirectionController; private readonly IList _specialPages = new List { "/login.aspx", "/register.aspx", "/terms.aspx", "/privacy.aspx", "/login", "/register", "/terms", "/privacy" }; private readonly Regex MvcServicePath = new Regex(@"DesktopModules/MVC/", RegexOptions.Compiled); - public string ModuleName => "MobileRedirectModule"; - - #region IHttpModule Members - + + public string ModuleName => "MobileRedirectModule"; + public void Init(HttpApplication application) { - _redirectionController = new RedirectionController(); - application.BeginRequest += OnBeginRequest; + this._redirectionController = new RedirectionController(); + application.BeginRequest += this.OnBeginRequest; } public void Dispose() { - } - - #endregion - + } + public void OnBeginRequest(object s, EventArgs e) { var app = (HttpApplication)s; var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - - //First check if we are upgrading/installing + + // First check if we are upgrading/installing var rawUrl = app.Request.RawUrl; if (!Initialize.ProcessHttpModule(app.Request, false, false) || app.Request.HttpMethod == "POST" - || ServicesModule.ServiceApi.IsMatch(rawUrl) - || MvcServicePath.IsMatch(rawUrl) - || IsSpecialPage(rawUrl) + || ServicesModule.ServiceApi.IsMatch(rawUrl) + || this.MvcServicePath.IsMatch(rawUrl) + || this.IsSpecialPage(rawUrl) || (portalSettings != null && !IsRedirectAllowed(rawUrl, app, portalSettings))) { return; } - //Check if redirection has been disabled for the session - //This method inspects cookie and query string. It can also setup / clear cookies. - if (_redirectionController != null && + // Check if redirection has been disabled for the session + // This method inspects cookie and query string. It can also setup / clear cookies. + if (this._redirectionController != null && portalSettings?.ActiveTab != null && !string.IsNullOrEmpty(app.Request.UserAgent) && - _redirectionController.IsRedirectAllowedForTheSession(app)) + this._redirectionController.IsRedirectAllowedForTheSession(app)) { - var redirectUrl = _redirectionController.GetRedirectUrl(app.Request.UserAgent); + var redirectUrl = this._redirectionController.GetRedirectUrl(app.Request.UserAgent); if (!string.IsNullOrEmpty(redirectUrl)) { - //append the query string from original url + // append the query string from original url var idx = rawUrl.IndexOf("?", StringComparison.Ordinal); var queryString = idx >= 0 ? rawUrl.Substring(idx + 1) : string.Empty; if (!string.IsNullOrEmpty(queryString)) { redirectUrl = string.Concat(redirectUrl, redirectUrl.Contains("?") ? "&" : "?", queryString); } + app.Response.Redirect(redirectUrl); } } @@ -107,7 +100,8 @@ private bool IsSpecialPage(string url) { tabPath = tabPath.Replace(alias.Substring(idx), string.Empty); } - return _specialPages.Contains(tabPath); + + return this._specialPages.Contains(tabPath); } } } diff --git a/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs b/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs index 2678f7de2ba..a86efdde995 100644 --- a/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs +++ b/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs @@ -1,72 +1,74 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Installer.Blocker; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.OutputCache; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.HttpModules.OutputCaching { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Installer.Blocker; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.OutputCache; + /// - /// Manages the output cache for a request + /// Manages the output cache for a request. /// public class OutputCacheModule : IHttpModule { private const string ContextKeyResponseFilter = "OutputCache:ResponseFilter"; private const string ContextKeyTabId = "OutputCache:TabId"; private const string ContextKeyTabOutputCacheProvider = "OutputCache:TabOutputCacheProvider"; - private HttpApplication _app; - - #region IHttpModule Members - + private HttpApplication _app; + + private enum IncludeExcludeType + { + IncludeByDefault, + ExcludeByDefault, + } + public void Init(HttpApplication httpApp) { - _app = httpApp; + this._app = httpApp; - httpApp.ResolveRequestCache += OnResolveRequestCache; - httpApp.UpdateRequestCache += OnUpdateRequestCache; + httpApp.ResolveRequestCache += this.OnResolveRequestCache; + httpApp.UpdateRequestCache += this.OnUpdateRequestCache; } - - + public void Dispose() { - } - - #endregion - - + } + private bool IsInstallInProgress(HttpApplication app) { - return InstallBlocker.Instance.IsInstallInProgress(); + return InstallBlocker.Instance.IsInstallInProgress(); } private void OnResolveRequestCache(object sender, EventArgs e) { bool cached = false; - if (_app == null || _app.Context == null || !_app.Response.ContentType.Equals("text/html", StringComparison.InvariantCultureIgnoreCase) || _app.Context.Request.IsAuthenticated || _app.Context.Request.Browser.Crawler) + if (this._app == null || this._app.Context == null || !this._app.Response.ContentType.Equals("text/html", StringComparison.InvariantCultureIgnoreCase) || this._app.Context.Request.IsAuthenticated || this._app.Context.Request.Browser.Crawler) { return; } - - if (IsInstallInProgress(_app)) + + if (this.IsInstallInProgress(this._app)) { return; } - if (_app.Context.Request.RequestType == "POST" || ! (_app.Context.Request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase))) + if (this._app.Context.Request.RequestType == "POST" || !this._app.Context.Request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { return; } - var portalSettings = (PortalSettings) (HttpContext.Current.Items["PortalSettings"]); + + var portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; int tabId = portalSettings.ActiveTab.TabID; Hashtable tabSettings = TabController.Instance.GetTabSettings(tabId); @@ -80,7 +82,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) string locale = Localization.GetPageLocale(portalSettings).Name; IncludeExcludeType includeExclude = IncludeExcludeType.ExcludeByDefault; - if (tabSettings["CacheIncludeExclude"] != null && ! string.IsNullOrEmpty(tabSettings["CacheIncludeExclude"].ToString())) + if (tabSettings["CacheIncludeExclude"] != null && !string.IsNullOrEmpty(tabSettings["CacheIncludeExclude"].ToString())) { if (tabSettings["CacheIncludeExclude"].ToString() == "0") { @@ -91,12 +93,11 @@ private void OnResolveRequestCache(object sender, EventArgs e) includeExclude = IncludeExcludeType.IncludeByDefault; } } - - + string tabOutputCacheProvider = tabSettings["CacheProvider"].ToString(); - _app.Context.Items[ContextKeyTabOutputCacheProvider] = tabOutputCacheProvider; - int maxCachedVariationsForTab = 250; //by default, prevent DOS attacks - if (tabSettings["MaxVaryByCount"] != null && ! string.IsNullOrEmpty(tabSettings["MaxVaryByCount"].ToString())) + this._app.Context.Items[ContextKeyTabOutputCacheProvider] = tabOutputCacheProvider; + int maxCachedVariationsForTab = 250; // by default, prevent DOS attacks + if (tabSettings["MaxVaryByCount"] != null && !string.IsNullOrEmpty(tabSettings["MaxVaryByCount"].ToString())) { maxCachedVariationsForTab = Convert.ToInt32(tabSettings["MaxVaryByCount"].ToString()); } @@ -107,9 +108,9 @@ private void OnResolveRequestCache(object sender, EventArgs e) includeVaryByKeys.Add("tabid"); includeVaryByKeys.Add("portalid"); includeVaryByKeys.Add("locale"); - includeVaryByKeys.Add("alias"); - //make sure to always add keys in lowercase only - + includeVaryByKeys.Add("alias"); + + // make sure to always add keys in lowercase only if (includeExclude == IncludeExcludeType.ExcludeByDefault) { string includeVaryByKeysSettings = string.Empty; @@ -118,7 +119,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) includeVaryByKeysSettings = tabSettings["IncludeVaryBy"].ToString(); } - if (! string.IsNullOrEmpty(includeVaryByKeysSettings)) + if (!string.IsNullOrEmpty(includeVaryByKeysSettings)) { if (includeVaryByKeysSettings.Contains(",")) { @@ -134,6 +135,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) } } } + var excludeVaryByKeys = new StringCollection(); if (includeExclude == IncludeExcludeType.IncludeByDefault) { @@ -143,7 +145,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) excludeVaryByKeysSettings = tabSettings["ExcludeVaryBy"].ToString(); } - if (! string.IsNullOrEmpty(excludeVaryByKeysSettings)) + if (!string.IsNullOrEmpty(excludeVaryByKeysSettings)) { if (excludeVaryByKeysSettings.Contains(",")) { @@ -162,100 +164,94 @@ private void OnResolveRequestCache(object sender, EventArgs e) var varyBy = new SortedDictionary(); - foreach (string key in _app.Context.Request.QueryString) + foreach (string key in this._app.Context.Request.QueryString) { - if (key != null && _app.Context.Request.QueryString[key] != null) + if (key != null && this._app.Context.Request.QueryString[key] != null) { var varyKey = key.ToLowerInvariant(); - varyBy.Add(varyKey, _app.Context.Request.QueryString[key]); + varyBy.Add(varyKey, this._app.Context.Request.QueryString[key]); if (includeExclude == IncludeExcludeType.IncludeByDefault && !includeVaryByKeys.Contains(varyKey)) { includeVaryByKeys.Add(varyKey); } } - } - if (! (varyBy.ContainsKey("portalid"))) + + if (!varyBy.ContainsKey("portalid")) { varyBy.Add("portalid", portalId.ToString()); } - if (! (varyBy.ContainsKey("tabid"))) + + if (!varyBy.ContainsKey("tabid")) { varyBy.Add("tabid", tabId.ToString()); } - if (! (varyBy.ContainsKey("locale"))) + + if (!varyBy.ContainsKey("locale")) { varyBy.Add("locale", locale); } - if (!(varyBy.ContainsKey("alias"))) - { - varyBy.Add("alias", portalSettings.PortalAlias.HTTPAlias); - } - - + + if (!varyBy.ContainsKey("alias")) + { + varyBy.Add("alias", portalSettings.PortalAlias.HTTPAlias); + } + string cacheKey = OutputCachingProvider.Instance(tabOutputCacheProvider).GenerateCacheKey(tabId, includeVaryByKeys, excludeVaryByKeys, varyBy); - bool returnedFromCache = OutputCachingProvider.Instance(tabOutputCacheProvider).StreamOutput(tabId, cacheKey, _app.Context); + bool returnedFromCache = OutputCachingProvider.Instance(tabOutputCacheProvider).StreamOutput(tabId, cacheKey, this._app.Context); if (returnedFromCache) { - //output the content type heade when read content from cache. - _app.Context.Response.AddHeader("Content-Type", string.Format("{0}; charset={1}", _app.Response.ContentType, _app.Response.Charset)); - //This is to give a site owner the ability - //to visually verify that a page was rendered via - //the output cache. Use FireFox FireBug or another - //tool to view the response headers easily. - _app.Context.Response.AddHeader("DNNOutputCache", "true"); - - //Also add it ti the Context - the Headers are readonly unless using IIS in Integrated Pipleine mode - //and we need to know if OutPut Caching is active in the compression module - _app.Context.Items.Add("DNNOutputCache", "true"); - - _app.Context.Response.End(); + // output the content type heade when read content from cache. + this._app.Context.Response.AddHeader("Content-Type", string.Format("{0}; charset={1}", this._app.Response.ContentType, this._app.Response.Charset)); + + // This is to give a site owner the ability + // to visually verify that a page was rendered via + // the output cache. Use FireFox FireBug or another + // tool to view the response headers easily. + this._app.Context.Response.AddHeader("DNNOutputCache", "true"); + + // Also add it ti the Context - the Headers are readonly unless using IIS in Integrated Pipleine mode + // and we need to know if OutPut Caching is active in the compression module + this._app.Context.Items.Add("DNNOutputCache", "true"); + + this._app.Context.Response.End(); cached = true; } - _app.Context.Items[ContextKeyTabId] = tabId; + this._app.Context.Items[ContextKeyTabId] = tabId; if (cached != true) { - if (tabSettings["CacheDuration"] != null && ! string.IsNullOrEmpty(tabSettings["CacheDuration"].ToString()) && Convert.ToInt32(tabSettings["CacheDuration"].ToString()) > 0) + if (tabSettings["CacheDuration"] != null && !string.IsNullOrEmpty(tabSettings["CacheDuration"].ToString()) && Convert.ToInt32(tabSettings["CacheDuration"].ToString()) > 0) { int seconds = Convert.ToInt32(tabSettings["CacheDuration"].ToString()); var duration = new TimeSpan(0, 0, seconds); - OutputCacheResponseFilter responseFilter = OutputCachingProvider.Instance(_app.Context.Items[ContextKeyTabOutputCacheProvider].ToString()).GetResponseFilter(Convert.ToInt32(_app.Context.Items[ContextKeyTabId]), - maxCachedVariationsForTab, - _app.Response.Filter, - cacheKey, - duration); - _app.Context.Items[ContextKeyResponseFilter] = responseFilter; - _app.Context.Response.Filter = responseFilter; + OutputCacheResponseFilter responseFilter = OutputCachingProvider.Instance(this._app.Context.Items[ContextKeyTabOutputCacheProvider].ToString()).GetResponseFilter( + Convert.ToInt32(this._app.Context.Items[ContextKeyTabId]), + maxCachedVariationsForTab, + this._app.Response.Filter, + cacheKey, + duration); + this._app.Context.Items[ContextKeyResponseFilter] = responseFilter; + this._app.Context.Response.Filter = responseFilter; } } } private void OnUpdateRequestCache(object sender, EventArgs e) { - if (! HttpContext.Current.Request.Browser.Crawler) + if (!HttpContext.Current.Request.Browser.Crawler) { - var responseFilter = _app.Context.Items[ContextKeyResponseFilter] as OutputCacheResponseFilter; + var responseFilter = this._app.Context.Items[ContextKeyResponseFilter] as OutputCacheResponseFilter; if (responseFilter != null) { - responseFilter.StopFiltering(Convert.ToInt32(_app.Context.Items[ContextKeyTabId]), false); + responseFilter.StopFiltering(Convert.ToInt32(this._app.Context.Items[ContextKeyTabId]), false); } } - } - - #region Nested type: IncludeExcludeType - - private enum IncludeExcludeType - { - IncludeByDefault, - ExcludeByDefault - } - - #endregion + } } } diff --git a/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs b/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs index 94a419e63c8..23f91c38843 100644 --- a/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs +++ b/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs @@ -1,20 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Personalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.Personalization { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Personalization; + public class PersonalizationModule : IHttpModule { public string ModuleName @@ -23,36 +19,32 @@ public string ModuleName { return "PersonalizationModule"; } - } - - #region IHttpModule Members - + } + public void Init(HttpApplication application) { - application.EndRequest += OnEndRequest; + application.EndRequest += this.OnEndRequest; } public void Dispose() { - } - - #endregion - + } + public void OnEndRequest(object s, EventArgs e) { - HttpContext context = ((HttpApplication) s).Context; + HttpContext context = ((HttpApplication)s).Context; HttpRequest request = context.Request; if (!Initialize.ProcessHttpModule(request, false, false)) { return; } - - //Obtain PortalSettings from Current Context + + // Obtain PortalSettings from Current Context var _portalSettings = (PortalSettings)context.Items["PortalSettings"]; if (_portalSettings != null) { - //load the user info object + // load the user info object UserInfo UserInfo = UserController.Instance.GetCurrentUserInfo(); var personalization = new PersonalizationController(); personalization.SaveProfile(context, UserInfo.UserID, _portalSettings.PortalId); diff --git a/DNN Platform/HttpModules/Properties/AssemblyInfo.cs b/DNN Platform/HttpModules/Properties/AssemblyInfo.cs index 3dc32e887e4..013e218f79d 100644 --- a/DNN Platform/HttpModules/Properties/AssemblyInfo.cs +++ b/DNN Platform/HttpModules/Properties/AssemblyInfo.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -#endregion - +using System.Runtime.InteropServices; + [assembly: AssemblyTitle("DotNetNuke.HttpModules")] [assembly: AssemblyDescription("Open Source Web Application Framework")] diff --git a/DNN Platform/HttpModules/RequestFilter/Config/Enums.cs b/DNN Platform/HttpModules/RequestFilter/Config/Enums.cs index f0480b28efc..d2042417503 100644 --- a/DNN Platform/HttpModules/RequestFilter/Config/Enums.cs +++ b/DNN Platform/HttpModules/RequestFilter/Config/Enums.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.HttpModules.RequestFilter { public enum RequestFilterRuleType { Redirect, PermanentRedirect, - NotFound + NotFound, } public enum RequestFilterOperatorType { Equal, NotEqual, - Regex + Regex, } } diff --git a/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs b/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs index 06e2ad5f3c6..2aa24cccdac 100644 --- a/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs +++ b/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs @@ -1,26 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; -using System.Xml.Serialization; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Services.Cache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.RequestFilter { - [Serializable, XmlRoot("RewriterConfig")] + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + using System.Xml.Serialization; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Services.Cache; + + [Serializable] + [XmlRoot("RewriterConfig")] public class RequestFilterSettings { private const string RequestFilterConfig = "RequestFilter.Config"; @@ -39,26 +35,28 @@ public List Rules { get { - return _rules; + return this._rules; } + set { - _rules = value; + this._rules = value; } } /// - /// Get the current settings from the xml config file - /// + /// Get the current settings from the xml config file. + /// + /// public static RequestFilterSettings GetSettings() { - var settings = (RequestFilterSettings) DataCache.GetCache(RequestFilterConfig); + var settings = (RequestFilterSettings)DataCache.GetCache(RequestFilterConfig); if (settings == null) { settings = new RequestFilterSettings(); string filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.DotNetNuke); - //Create a FileStream for the Config file + // Create a FileStream for the Config file using (var fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var doc = new XPathDocument(fileReader); @@ -81,12 +79,14 @@ public static RequestFilterSettings GetSettings() } } } - if ((File.Exists(filePath))) + + if (File.Exists(filePath)) { - //Set back into Cache + // Set back into Cache DataCache.SetCache(RequestFilterConfig, settings, new DNNCacheDependency(filePath)); } } + return settings; } @@ -96,11 +96,12 @@ public static void Save(List rules) if (!File.Exists(filePath)) { string defaultConfigFile = Globals.ApplicationMapPath + Globals.glbConfigFolder + Globals.glbDotNetNukeConfig; - if ((File.Exists(defaultConfigFile))) + if (File.Exists(defaultConfigFile)) { File.Copy(defaultConfigFile, filePath, true); } } + var doc = new XmlDocument { XmlResolver = null }; doc.Load(filePath); XmlNode ruleRoot = doc.SelectSingleNode("/configuration/blockrequests"); @@ -125,6 +126,7 @@ public static void Save(List rules) xmlRule.Attributes.Append(location); ruleRoot.AppendChild(xmlRule); } + var settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(filePath, settings)) diff --git a/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs b/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs index 5e1c523cb49..3aa9742af8f 100644 --- a/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs +++ b/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs @@ -1,29 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utils; -using DotNetNuke.Entities.Urls; -using DotNetNuke.HttpModules.UrlRewrite; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.RequestFilter { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utils; + using DotNetNuke.Entities.Urls; + using DotNetNuke.HttpModules.UrlRewrite; + public class RequestFilterModule : IHttpModule { - private const string InstalledKey = "httprequestfilter.attemptedinstall"; - - #region IHttpModule Members - + private const string InstalledKey = "httprequestfilter.attemptedinstall"; + /// - /// Implementation of + /// Implementation of . /// /// /// Currently empty. Nothing to really do, as I have no member variables. @@ -35,17 +28,16 @@ public void Dispose() public void Init(HttpApplication context) { context.BeginRequest += FilterRequest; - } - - #endregion - + } + private static void FilterRequest(object sender, EventArgs e) { - var app = (HttpApplication) sender; + var app = (HttpApplication)sender; if ((app == null) || (app.Context == null) || (app.Context.Items == null)) { return; } + var request = app.Context.Request; if (!Initialize.ProcessHttpModule(request, true, true)) @@ -53,30 +45,31 @@ private static void FilterRequest(object sender, EventArgs e) return; } - //Carry out first time initialization tasks + // Carry out first time initialization tasks Initialize.Init(app); - - //only do this if we havn't already attempted an install. This prevents PreSendRequestHeaders from - //trying to add this item way to late. We only want the first run through to do anything. - //also, we use the context to store whether or not we've attempted an add, as it's thread-safe and - //scoped to the request. An instance of this module can service multiple requests at the same time, - //so we cannot use a member variable. + + // only do this if we havn't already attempted an install. This prevents PreSendRequestHeaders from + // trying to add this item way to late. We only want the first run through to do anything. + // also, we use the context to store whether or not we've attempted an add, as it's thread-safe and + // scoped to the request. An instance of this module can service multiple requests at the same time, + // so we cannot use a member variable. if (!app.Context.Items.Contains(InstalledKey)) { - //log the install attempt in the HttpContext - //must do this first as several IF statements - //below skip full processing of this method + // log the install attempt in the HttpContext + // must do this first as several IF statements + // below skip full processing of this method app.Context.Items.Add(InstalledKey, true); var settings = RequestFilterSettings.GetSettings(); - if ((settings == null || settings.Rules.Count == 0 || !settings.Enabled)) + if (settings == null || settings.Rules.Count == 0 || !settings.Enabled) { return; } + foreach (var rule in settings.Rules) { - //Added ability to determine the specific value types for addresses - //this check was necessary so that your rule could deal with IPv4 or IPv6 - //To use this mode, add ":IPv4" or ":IPv6" to your servervariable name. + // Added ability to determine the specific value types for addresses + // this check was necessary so that your rule could deal with IPv4 or IPv6 + // To use this mode, add ":IPv4" or ":IPv6" to your servervariable name. var varArray = rule.ServerVariable.Split(':'); var varVal = request.ServerVariables[varArray[0]]; if (varArray[0].EndsWith("_ADDR", StringComparison.InvariantCultureIgnoreCase) && varArray.Length > 1) @@ -91,9 +84,10 @@ private static void FilterRequest(object sender, EventArgs e) break; } } - if ((!string.IsNullOrEmpty(varVal))) + + if (!string.IsNullOrEmpty(varVal)) { - if ((rule.Matches(varVal))) + if (rule.Matches(varVal)) { rule.Execute(); } diff --git a/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs b/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs index 27da5029487..a0d996fe934 100644 --- a/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs +++ b/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.RequestFilter { + using System; + using System.Collections.Generic; + using System.Text.RegularExpressions; + using System.Web; + [Serializable] public class RequestFilterRule { @@ -20,10 +15,10 @@ public class RequestFilterRule private string _Location; private RequestFilterOperatorType _Operator; private string _ServerVariable; - private List _Values = new List(); - - /// - /// Initializes a new instance of the RequestFilterRule class. + private List _Values = new List(); + + /// + /// Initializes a new instance of the class. /// /// /// @@ -32,15 +27,15 @@ public class RequestFilterRule /// public RequestFilterRule(string serverVariable, string values, RequestFilterOperatorType op, RequestFilterRuleType action, string location) { - _ServerVariable = serverVariable; - SetValues(values, op); - _Operator = op; - _Action = action; - _Location = location; - } - - /// - /// Initializes a new instance of the RequestFilterRule class. + this._ServerVariable = serverVariable; + this.SetValues(values, op); + this._Operator = op; + this._Action = action; + this._Location = location; + } + + /// + /// Initializes a new instance of the class. /// public RequestFilterRule() { @@ -50,11 +45,12 @@ public string ServerVariable { get { - return _ServerVariable; + return this._ServerVariable; } + set { - _ServerVariable = value; + this._ServerVariable = value; } } @@ -62,11 +58,12 @@ public List Values { get { - return _Values; + return this._Values; } + set { - _Values = value; + this._Values = value; } } @@ -74,7 +71,7 @@ public string RawValue { get { - return string.Join(" ", _Values.ToArray()); + return string.Join(" ", this._Values.ToArray()); } } @@ -82,11 +79,12 @@ public RequestFilterRuleType Action { get { - return _Action; + return this._Action; } + set { - _Action = value; + this._Action = value; } } @@ -94,11 +92,12 @@ public RequestFilterOperatorType Operator { get { - return _Operator; + return this._Operator; } + set { - _Operator = value; + this._Operator = value; } } @@ -106,57 +105,59 @@ public string Location { get { - return _Location; + return this._Location; } + set { - _Location = value; + this._Location = value; } } public void SetValues(string values, RequestFilterOperatorType op) { - _Values.Clear(); - if ((op != RequestFilterOperatorType.Regex)) + this._Values.Clear(); + if (op != RequestFilterOperatorType.Regex) { - string[] vals = values.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); + string[] vals = values.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string value in vals) { - _Values.Add(value.ToUpperInvariant()); + this._Values.Add(value.ToUpperInvariant()); } } else { - _Values.Add(values); + this._Values.Add(values); } } public bool Matches(string ServerVariableValue) { - switch (Operator) + switch (this.Operator) { case RequestFilterOperatorType.Equal: - return Values.Contains(ServerVariableValue.ToUpperInvariant()); + return this.Values.Contains(ServerVariableValue.ToUpperInvariant()); case RequestFilterOperatorType.NotEqual: - return !Values.Contains(ServerVariableValue.ToUpperInvariant()); + return !this.Values.Contains(ServerVariableValue.ToUpperInvariant()); case RequestFilterOperatorType.Regex: - return Regex.IsMatch(ServerVariableValue, Values[0], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + return Regex.IsMatch(ServerVariableValue, this.Values[0], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } + return false; } public void Execute() { HttpResponse response = HttpContext.Current.Response; - switch (Action) + switch (this.Action) { case RequestFilterRuleType.Redirect: - response.Redirect(Location, true); + response.Redirect(this.Location, true); break; case RequestFilterRuleType.PermanentRedirect: response.StatusCode = 301; response.Status = "301 Moved Permanently"; - response.RedirectLocation = Location; + response.RedirectLocation = this.Location; response.End(); break; case RequestFilterRuleType.NotFound: diff --git a/DNN Platform/HttpModules/Services/ServicesModule.cs b/DNN Platform/HttpModules/Services/ServicesModule.cs index 9094cd32e9b..dd281283f41 100644 --- a/DNN Platform/HttpModules/Services/ServicesModule.cs +++ b/DNN Platform/HttpModules/Services/ServicesModule.cs @@ -1,40 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text.RegularExpressions; -using System.Web; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.HttpModules.Services { + using System; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common; + public class ServicesModule : IHttpModule { public static readonly Regex ServiceApi = Globals.ServicesFrameworkRegex; public void Init(HttpApplication context) { - context.BeginRequest += InitDnn; + context.BeginRequest += InitDnn; - context.PreSendRequestHeaders += OnPreSendRequestHeaders; + context.PreSendRequestHeaders += this.OnPreSendRequestHeaders; } - private void OnPreSendRequestHeaders(object sender, EventArgs e) + public void Dispose() { - var app = sender as HttpApplication; - if (app != null) - { - // WEB API should not send cookies and other specific headers in repsone; - // they reveal too much info and are security risk - var headers = app.Response.Headers; - headers.Remove("Server"); - //DNN-8325 - //if (ServiceApi.IsMatch(app.Context.Request.RawUrl.ToLowerInvariant())) - //{ - // headers.Remove("Set-Cookie"); - //} - } } private static void InitDnn(object sender, EventArgs e) @@ -46,8 +34,22 @@ private static void InitDnn(object sender, EventArgs e) } } - public void Dispose() + private void OnPreSendRequestHeaders(object sender, EventArgs e) { + var app = sender as HttpApplication; + if (app != null) + { + // WEB API should not send cookies and other specific headers in repsone; + // they reveal too much info and are security risk + var headers = app.Response.Headers; + headers.Remove("Server"); + + // DNN-8325 + // if (ServiceApi.IsMatch(app.Context.Request.RawUrl.ToLowerInvariant())) + // { + // headers.Remove("Set-Cookie"); + // } + } } } } diff --git a/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs b/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs index 92ce362ed9d..11aa4c84148 100644 --- a/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs +++ b/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs @@ -1,44 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Urls.Config; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.EventQueue; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.UrlRewrite { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Urls.Config; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.EventQueue; + using DotNetNuke.Services.Localization; + internal class BasicUrlRewriter : UrlRewriterBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BasicUrlRewriter)); - public static readonly Regex TabIdRegex = new Regex("&?tabid=\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); - public static readonly Regex PortalIdRegex = new Regex("&?portalid=\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - #region overridden methods - + public static readonly Regex PortalIdRegex = new Regex("&?portalid=\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BasicUrlRewriter)); + internal override void RewriteUrl(object sender, EventArgs e) { - var app = (HttpApplication) sender; + var app = (HttpApplication)sender; HttpServerUtility server = app.Server; HttpRequest request = app.Request; HttpResponse response = app.Response; @@ -50,52 +43,51 @@ internal override void RewriteUrl(object sender, EventArgs e) return; } - //'Carry out first time initialization tasks + // 'Carry out first time initialization tasks Initialize.Init(app); if (!Initialize.ProcessHttpModule(request, false, false)) { return; } - //URL validation - //check for ".." escape characters commonly used by hackers to traverse the folder tree on the server - //the application should always use the exact relative location of the resource it is requesting + // URL validation + // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server + // the application should always use the exact relative location of the resource it is requesting var strURL = request.Url.AbsolutePath; - var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.RawUrl)) ?? ""; + var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.RawUrl)) ?? string.Empty; if (Globals.FileEscapingRegex.Match(strURL).Success || Globals.FileEscapingRegex.Match(strDoubleDecodeURL).Success) { DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } + try { - //fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459 - if ((request.Path.IndexOf("\\", StringComparison.Ordinal) >= 0 || Path.GetFullPath(request.PhysicalPath) != request.PhysicalPath)) + // fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459 + if (request.Path.IndexOf("\\", StringComparison.Ordinal) >= 0 || Path.GetFullPath(request.PhysicalPath) != request.PhysicalPath) { DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } } catch (Exception exc) { - //DNN 5479 - //request.physicalPath throws an exception when the path of the request exceeds 248 chars. - //example to test: http://localhost/dotnetnuke_2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/default.aspx + // DNN 5479 + // request.physicalPath throws an exception when the path of the request exceeds 248 chars. + // example to test: http://localhost/dotnetnuke_2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/default.aspx Logger.Error(exc); } + + string domainName; + this.RewriteUrl(app, out domainName); - - String domainName; - RewriteUrl(app, out domainName); - - //blank DomainName indicates RewriteUrl couldn't locate a current portal - //reprocess url for portal alias if auto add is an option - if (domainName == "" && CanAutoAddPortalAlias()) + // blank DomainName indicates RewriteUrl couldn't locate a current portal + // reprocess url for portal alias if auto add is an option + if (domainName == string.Empty && CanAutoAddPortalAlias()) { domainName = Globals.GetDomainName(app.Request, true); } - //from this point on we are dealing with a "standard" querystring ( ie. http://www.domain.com/default.aspx?tabid=## ) - //if the portal/url was succesfully identified - + // from this point on we are dealing with a "standard" querystring ( ie. http://www.domain.com/default.aspx?tabid=## ) + // if the portal/url was succesfully identified int tabId = Null.NullInteger; int portalId = Null.NullInteger; string portalAlias = null; @@ -105,7 +97,7 @@ internal override void RewriteUrl(object sender, EventArgs e) // get TabId from querystring ( this is mandatory for maintaining portal context for child portals ) if (!string.IsNullOrEmpty(request.QueryString["tabid"])) { - if (!Int32.TryParse(request.QueryString["tabid"], out tabId)) + if (!int.TryParse(request.QueryString["tabid"], out tabId)) { tabId = Null.NullInteger; parsingError = true; @@ -115,7 +107,7 @@ internal override void RewriteUrl(object sender, EventArgs e) // get PortalId from querystring ( this is used for host menu options as well as child portal navigation ) if (!string.IsNullOrEmpty(request.QueryString["portalid"])) { - if (!Int32.TryParse(request.QueryString["portalid"], out portalId)) + if (!int.TryParse(request.QueryString["portalid"], out portalId)) { portalId = Null.NullInteger; parsingError = true; @@ -124,39 +116,38 @@ internal override void RewriteUrl(object sender, EventArgs e) if (parsingError) { - //The tabId or PortalId are incorrectly formatted (potential DOS) + // The tabId or PortalId are incorrectly formatted (potential DOS) DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } - - + try { - //alias parameter can be used to switch portals + // alias parameter can be used to switch portals if (request.QueryString["alias"] != null) { // check if the alias is valid string childAlias = request.QueryString["alias"]; if (!Globals.UsePortNumber()) { - childAlias = childAlias.Replace(":" + request.Url.Port, ""); + childAlias = childAlias.Replace(":" + request.Url.Port, string.Empty); } if (PortalAliasController.Instance.GetPortalAlias(childAlias) != null) { - //check if the domain name contains the alias + // check if the domain name contains the alias if (childAlias.IndexOf(domainName, StringComparison.OrdinalIgnoreCase) == -1) { - //redirect to the url defined in the alias + // redirect to the url defined in the alias response.Redirect(Globals.GetPortalDomainName(childAlias, request, true), true); } - else //the alias is the same as the current domain + else // the alias is the same as the current domain { portalAlias = childAlias; } } } - //PortalId identifies a portal when set + // PortalId identifies a portal when set if (portalAlias == null) { if (portalId != Null.NullInteger) @@ -165,52 +156,55 @@ internal override void RewriteUrl(object sender, EventArgs e) } } - //TabId uniquely identifies a Portal + // TabId uniquely identifies a Portal if (portalAlias == null) { if (tabId != Null.NullInteger) { - //get the alias from the tabid, but only if it is for a tab in that domain + // get the alias from the tabid, but only if it is for a tab in that domain portalAlias = PortalAliasController.GetPortalAliasByTab(tabId, domainName); - if (String.IsNullOrEmpty(portalAlias)) + if (string.IsNullOrEmpty(portalAlias)) { - //if the TabId is not for the correct domain - //see if the correct domain can be found and redirect it + // if the TabId is not for the correct domain + // see if the correct domain can be found and redirect it portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(domainName); if (portalAliasInfo != null && !request.Url.LocalPath.ToLowerInvariant().EndsWith("/linkclick.aspx")) { if (app.Request.Url.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { - strURL = "https://" + portalAliasInfo.HTTPAlias.Replace("*.", ""); + strURL = "https://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty); } else { - strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", ""); + strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty); } + if (strURL.IndexOf(domainName, StringComparison.InvariantCultureIgnoreCase) == -1) { strURL += app.Request.Url.PathAndQuery; } + response.Redirect(strURL, true); } } } } - //else use the domain name - if (String.IsNullOrEmpty(portalAlias)) + // else use the domain name + if (string.IsNullOrEmpty(portalAlias)) { portalAlias = domainName; } - //using the DomainName above will find that alias that is the domainname portion of the Url - //ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url + + // using the DomainName above will find that alias that is the domainname portion of the Url + // ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias); if (portalAliasInfo != null) { portalId = portalAliasInfo.PortalID; } - //if the portalid is not known + // if the portalid is not known if (portalId == Null.NullInteger) { bool autoAddPortalAlias = CanAutoAddPortalAlias(); @@ -229,21 +223,22 @@ internal override void RewriteUrl(object sender, EventArgs e) } catch (ThreadAbortException exc) { - //Do nothing if Thread is being aborted - there are two response.redirect calls in the Try block + // Do nothing if Thread is being aborted - there are two response.redirect calls in the Try block Logger.Debug(exc); } catch (Exception ex) { - //500 Error - Redirect to ErrorPage + // 500 Error - Redirect to ErrorPage Logger.Error(ex); strURL = "~/ErrorPage.aspx?status=500&error=" + server.UrlEncode(ex.Message); HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer(strURL); } + if (portalId != -1) { - //load the PortalSettings into current context + // load the PortalSettings into current context var portalSettings = new PortalSettings(tabId, portalAliasInfo); app.Context.Items.Add("PortalSettings", portalSettings); @@ -251,14 +246,12 @@ internal override void RewriteUrl(object sender, EventArgs e) // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way app.Context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalId)); app.Context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary()); - - - if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect + + if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect && portalAliasInfo != null && !portalAliasInfo.IsPrimary - && !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias) // don't redirect if no primary alias is defined - ) + && !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias)) // don't redirect if no primary alias is defined { - //Permanently Redirect + // Permanently Redirect response.StatusCode = 301; var redirectAlias = Globals.AddHTTP(portalSettings.DefaultPortalAlias); @@ -272,78 +265,84 @@ internal override void RewriteUrl(object sender, EventArgs e) response.AppendHeader("Location", redirectUrl); } - //manage page URL redirects - that reach here because they bypass the built-in navigation - //ie Spiders, saved favorites, hand-crafted urls etc - if (!String.IsNullOrEmpty(portalSettings.ActiveTab.Url) && request.QueryString["ctl"] == null && + // manage page URL redirects - that reach here because they bypass the built-in navigation + // ie Spiders, saved favorites, hand-crafted urls etc + if (!string.IsNullOrEmpty(portalSettings.ActiveTab.Url) && request.QueryString["ctl"] == null && request.QueryString["fileticket"] == null) { - //Target Url + // Target Url string redirectUrl = portalSettings.ActiveTab.FullUrl; if (portalSettings.ActiveTab.PermanentRedirect) { - //Permanently Redirect + // Permanently Redirect response.StatusCode = 301; response.AppendHeader("Location", redirectUrl); } else { - //Normal Redirect + // Normal Redirect response.Redirect(redirectUrl, true); } } - //manage secure connections + // manage secure connections if (request.Url.AbsolutePath.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase)) { - //request is for a standard page - strURL = ""; - //if SSL is enabled + // request is for a standard page + strURL = string.Empty; + + // if SSL is enabled if (portalSettings.SSLEnabled) { - //if page is secure and connection is not secure orelse ssloffload is enabled and server value exists + // if page is secure and connection is not secure orelse ssloffload is enabled and server value exists if ((portalSettings.ActiveTab.IsSecure && !request.IsSecureConnection) && (UrlUtils.IsSslOffloadEnabled(request) == false)) { - //switch to secure connection + // switch to secure connection strURL = requestedPath.Replace("http://", "https://"); - strURL = FormatDomain(strURL, portalSettings.STDURL, portalSettings.SSLURL); + strURL = this.FormatDomain(strURL, portalSettings.STDURL, portalSettings.SSLURL); } } - //if SSL is enforced + + // if SSL is enforced if (portalSettings.SSLEnforced) { - //if page is not secure and connection is secure - if ((!portalSettings.ActiveTab.IsSecure && request.IsSecureConnection)) + // if page is not secure and connection is secure + if (!portalSettings.ActiveTab.IsSecure && request.IsSecureConnection) { - //check if connection has already been forced to secure orelse ssloffload is disabled + // check if connection has already been forced to secure orelse ssloffload is disabled if (request.QueryString["ssl"] == null) { strURL = requestedPath.Replace("https://", "http://"); - strURL = FormatDomain(strURL, portalSettings.SSLURL, portalSettings.STDURL); + strURL = this.FormatDomain(strURL, portalSettings.SSLURL, portalSettings.STDURL); } } } - //if a protocol switch is necessary - if (!String.IsNullOrEmpty(strURL)) + // if a protocol switch is necessary + if (!string.IsNullOrEmpty(strURL)) { if (strURL.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { - //redirect to secure connection + // redirect to secure connection response.RedirectPermanent(strURL); } - else - //when switching to an unsecure page, use a clientside redirector to avoid the browser security warning + else + + // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning { response.Clear(); - //add a refresh header to the response + + // add a refresh header to the response response.AddHeader("Refresh", "0;URL=" + strURL); - //add the clientside javascript redirection script + + // add the clientside javascript redirection script response.Write(""); response.Write(""); response.Write(""); - //send the response + + // send the response response.End(); } } @@ -351,10 +350,10 @@ internal override void RewriteUrl(object sender, EventArgs e) } else { - //alias does not exist in database - //and all attempts to find another have failed - //this should only happen if the HostPortal does not have any aliases - //404 Error - Redirect to ErrorPage + // alias does not exist in database + // and all attempts to find another have failed + // this should only happen if the HostPortal does not have any aliases + // 404 Error - Redirect to ErrorPage strURL = "~/ErrorPage.aspx?status=404&error=" + domainName; HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer(strURL); @@ -364,25 +363,22 @@ internal override void RewriteUrl(object sender, EventArgs e) { app.Context.Items.Remove("FirstRequest"); - //Process any messages in the EventQueue for the Application_Start_FirstRequest event + // Process any messages in the EventQueue for the Application_Start_FirstRequest event EventQueueController.ProcessMessages("Application_Start_FirstRequest"); } - } - - #endregion - - #region rewriting methods - - //Note these formerly lived in the 'UrlRewriteModule.cs' class + } + + // Note these formerly lived in the 'UrlRewriteModule.cs' class private string FormatDomain(string url, string replaceDomain, string withDomain) { - if (!String.IsNullOrEmpty(replaceDomain) && !String.IsNullOrEmpty(withDomain)) + if (!string.IsNullOrEmpty(replaceDomain) && !string.IsNullOrEmpty(withDomain)) { if (url.IndexOf(replaceDomain, StringComparison.Ordinal) != -1) { url = url.Replace(replaceDomain, withDomain); } } + return url; } @@ -391,12 +387,11 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) HttpRequest request = app.Request; HttpResponse response = app.Response; string requestedPath = app.Request.Url.AbsoluteUri; + + portalAlias = string.Empty; - - portalAlias = ""; - - //determine portal alias looking for longest possible match - String myAlias = Globals.GetDomainName(app.Request, true); + // determine portal alias looking for longest possible match + string myAlias = Globals.GetDomainName(app.Request, true); PortalAliasInfo objPortalAlias; do { @@ -409,90 +404,98 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } int slashIndex = myAlias.LastIndexOf('/'); - myAlias = slashIndex > 1 ? myAlias.Substring(0, slashIndex) : ""; - } while (myAlias.Length > 0); - - + myAlias = slashIndex > 1 ? myAlias.Substring(0, slashIndex) : string.Empty; + } + while (myAlias.Length > 0); + app.Context.Items.Add("UrlRewrite:OriginalUrl", app.Request.Url.AbsoluteUri); - //Friendly URLs are exposed externally using the following format - //http://www.domain.com/tabid/###/mid/###/ctl/xxx/default.aspx - //and processed internally using the following format - //http://www.domain.com/default.aspx?tabid=###&mid=###&ctl=xxx - //The system for accomplishing this is based on an extensible Regex rules definition stored in /SiteUrls.config - string sendTo = ""; - - //save and remove the querystring as it gets added back on later - //path parameter specifications will take precedence over querystring parameters - string strQueryString = ""; - if ((!String.IsNullOrEmpty(app.Request.Url.Query))) + // Friendly URLs are exposed externally using the following format + // http://www.domain.com/tabid/###/mid/###/ctl/xxx/default.aspx + // and processed internally using the following format + // http://www.domain.com/default.aspx?tabid=###&mid=###&ctl=xxx + // The system for accomplishing this is based on an extensible Regex rules definition stored in /SiteUrls.config + string sendTo = string.Empty; + + // save and remove the querystring as it gets added back on later + // path parameter specifications will take precedence over querystring parameters + string strQueryString = string.Empty; + if (!string.IsNullOrEmpty(app.Request.Url.Query)) { strQueryString = request.QueryString.ToString(); - requestedPath = requestedPath.Replace(app.Request.Url.Query, ""); + requestedPath = requestedPath.Replace(app.Request.Url.Query, string.Empty); } - //get url rewriting rules + // get url rewriting rules RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules; - //iterate through list of rules + // iterate through list of rules int matchIndex = -1; for (int ruleIndex = 0; ruleIndex <= rules.Count - 1; ruleIndex++) { - //check for the existence of the LookFor value + // check for the existence of the LookFor value string pattern = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[ruleIndex].LookFor) + "$"; Match objMatch = Regex.Match(requestedPath, pattern, RegexOptions.IgnoreCase); - //if there is a match - if ((objMatch.Success)) + // if there is a match + if (objMatch.Success) { - //create a new URL using the SendTo regex value - sendTo = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, - Regex.Replace(requestedPath, pattern, rules[ruleIndex].SendTo, + // create a new URL using the SendTo regex value + sendTo = RewriterUtils.ResolveUrl( + app.Context.Request.ApplicationPath, + Regex.Replace(requestedPath, pattern, rules[ruleIndex].SendTo, RegexOptions.IgnoreCase)); string parameters = objMatch.Groups[2].Value; - //process the parameters - if ((parameters.Trim().Length > 0)) + + // process the parameters + if (parameters.Trim().Length > 0) { - //split the value into an array based on "/" ( ie. /tabid/##/ ) + // split the value into an array based on "/" ( ie. /tabid/##/ ) parameters = parameters.Replace("\\", "/"); string[] splitParameters = parameters.Split('/'); - //icreate a well formed querystring based on the array of parameters + + // icreate a well formed querystring based on the array of parameters for (int parameterIndex = 0; parameterIndex < splitParameters.Length; parameterIndex++) { - //ignore the page name + // ignore the page name if ( - splitParameters[parameterIndex].IndexOf(".aspx", - StringComparison.InvariantCultureIgnoreCase) == + splitParameters[parameterIndex].IndexOf( + ".aspx", + StringComparison.InvariantCultureIgnoreCase) == -1) { - //get parameter name + // get parameter name string parameterName = splitParameters[parameterIndex].Trim(); if (parameterName.Length > 0) { - //add parameter to SendTo if it does not exist already + // add parameter to SendTo if it does not exist already if ( - sendTo.IndexOf("?" + parameterName + "=", - StringComparison.InvariantCultureIgnoreCase) == -1 && - sendTo.IndexOf("&" + parameterName + "=", - StringComparison.InvariantCultureIgnoreCase) == -1) + sendTo.IndexOf( + "?" + parameterName + "=", + StringComparison.InvariantCultureIgnoreCase) == -1 && + sendTo.IndexOf( + "&" + parameterName + "=", + StringComparison.InvariantCultureIgnoreCase) == -1) { - //get parameter delimiter + // get parameter delimiter string parameterDelimiter = sendTo.IndexOf("?", StringComparison.Ordinal) != -1 ? "&" : "?"; sendTo = sendTo + parameterDelimiter + parameterName; - //get parameter value - string parameterValue = ""; + + // get parameter value + string parameterValue = string.Empty; if (parameterIndex < splitParameters.Length - 1) { parameterIndex += 1; - if (!String.IsNullOrEmpty(splitParameters[parameterIndex].Trim())) + if (!string.IsNullOrEmpty(splitParameters[parameterIndex].Trim())) { parameterValue = splitParameters[parameterIndex].Trim(); } } - //add the parameter value + + // add the parameter value if (parameterValue.Length > 0) { sendTo = sendTo + "=" + parameterValue; @@ -502,28 +505,32 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } } } + matchIndex = ruleIndex; - break; //exit as soon as it processes the first match + break; // exit as soon as it processes the first match } } - if (!String.IsNullOrEmpty(strQueryString)) + + if (!string.IsNullOrEmpty(strQueryString)) { - //add querystring parameters back to SendTo + // add querystring parameters back to SendTo string[] parameters = strQueryString.Split('&'); - //iterate through the array of parameters + + // iterate through the array of parameters for (int parameterIndex = 0; parameterIndex <= parameters.Length - 1; parameterIndex++) { - //get parameter name + // get parameter name string parameterName = parameters[parameterIndex]; if (parameterName.IndexOf("=", StringComparison.Ordinal) != -1) { parameterName = parameterName.Substring(0, parameterName.IndexOf("=", StringComparison.Ordinal)); } - //check if parameter already exists + + // check if parameter already exists if (sendTo.IndexOf("?" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1 && sendTo.IndexOf("&" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1) { - //add parameter to SendTo value + // add parameter to SendTo value sendTo = sendTo.IndexOf("?", StringComparison.Ordinal) != -1 ? sendTo + "&" + parameters[parameterIndex] : sendTo + "?" + parameters[parameterIndex]; @@ -531,23 +538,23 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } } - //if a match was found to the urlrewrite rules + // if a match was found to the urlrewrite rules if (matchIndex != -1) { if (rules[matchIndex].SendTo.StartsWith("~")) { - //rewrite the URL for internal processing + // rewrite the URL for internal processing RewriterUtils.RewriteUrl(app.Context, sendTo); } else { - //it is not possible to rewrite the domain portion of the URL so redirect to the new URL + // it is not possible to rewrite the domain portion of the URL so redirect to the new URL response.Redirect(sendTo, true); } } else { - //Try to rewrite by TabPath + // Try to rewrite by TabPath string url; if (Globals.UsePortNumber() && ((app.Request.Url.Port != 80 && !app.Request.IsSecureConnection) || @@ -560,30 +567,32 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) url = app.Request.Url.Host + app.Request.Url.LocalPath; } - if (!String.IsNullOrEmpty(myAlias)) + if (!string.IsNullOrEmpty(myAlias)) { if (objPortalAlias != null) { int portalID = objPortalAlias.PortalID; - //Identify Tab Name + + // Identify Tab Name string tabPath = url; if (tabPath.StartsWith(myAlias)) { tabPath = url.Remove(0, myAlias.Length); } - //Default Page has been Requested - if ((tabPath == "/" + Globals.glbDefaultPage.ToLowerInvariant())) + + // Default Page has been Requested + if (tabPath == "/" + Globals.glbDefaultPage.ToLowerInvariant()) { return; } - //Start of patch + // Start of patch string cultureCode = string.Empty; Dictionary dicLocales = LocaleController.Instance.GetLocales(portalID); if (dicLocales.Count > 1) { - String[] splitUrl = app.Request.Url.ToString().Split('/'); + string[] splitUrl = app.Request.Url.ToString().Split('/'); foreach (string culturePart in splitUrl) { @@ -594,7 +603,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) if (key.Key.ToLower().Equals(culturePart.ToLower())) { cultureCode = key.Value.Code; - tabPath = tabPath.Replace("/" + culturePart, ""); + tabPath = tabPath.Replace("/" + culturePart, string.Empty); break; } } @@ -603,39 +612,44 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } // Check to see if the tab exists (if localization is enable, check for the specified culture) - int tabID = TabController.GetTabByTabPath(portalID, - tabPath.Replace("/", "//").Replace(".aspx", ""), - cultureCode); + int tabID = TabController.GetTabByTabPath( + portalID, + tabPath.Replace("/", "//").Replace(".aspx", string.Empty), + cultureCode); // Check to see if neutral culture tab exists - if ((tabID == Null.NullInteger && cultureCode.Length > 0)) + if (tabID == Null.NullInteger && cultureCode.Length > 0) { - tabID = TabController.GetTabByTabPath(portalID, - tabPath.Replace("/", "//").Replace(".aspx", ""), ""); + tabID = TabController.GetTabByTabPath( + portalID, + tabPath.Replace("/", "//").Replace(".aspx", string.Empty), string.Empty); } - //End of patch - - if ((tabID != Null.NullInteger)) + + // End of patch + if (tabID != Null.NullInteger) { string sendToUrl = "~/" + Globals.glbDefaultPage + "?TabID=" + tabID; if (!cultureCode.Equals(string.Empty)) { sendToUrl = sendToUrl + "&language=" + cultureCode; } - if ((!String.IsNullOrEmpty(app.Request.Url.Query))) + + if (!string.IsNullOrEmpty(app.Request.Url.Query)) { sendToUrl = sendToUrl + "&" + app.Request.Url.Query.TrimStart('?'); } + RewriterUtils.RewriteUrl(app.Context, sendToUrl); return; } + tabPath = tabPath.ToLowerInvariant(); - if ((tabPath.IndexOf('?') != -1)) + if (tabPath.IndexOf('?') != -1) { tabPath = tabPath.Substring(0, tabPath.IndexOf('?')); } - //Get the Portal + // Get the Portal PortalInfo portal = PortalController.Instance.GetPortal(portalID); string requestQuery = app.Request.Url.Query; if (!string.IsNullOrEmpty(requestQuery)) @@ -644,20 +658,23 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) requestQuery = PortalIdRegex.Replace(requestQuery, string.Empty); requestQuery = requestQuery.TrimStart('?', '&'); } + if (tabPath == "/login.aspx") { if (portal.LoginTabId > Null.NullInteger && Globals.ValidateLoginTabID(portal.LoginTabId)) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.LoginTabId + "&" + requestQuery); } else { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.LoginTabId); } } @@ -665,35 +682,41 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=login&" + requestQuery); } else { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=login"); } } + return; } + if (tabPath == "/register.aspx") { if (portal.RegisterTabId > Null.NullInteger) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.RegisterTabId + "&portalid=" + portalID + "&" + requestQuery); } else { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.RegisterTabId + "&portalid=" + portalID); } } @@ -701,79 +724,92 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Register&" + requestQuery); } else { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Register"); } } + return; } + if (tabPath == "/terms.aspx") { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Terms&" + requestQuery); } else { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Terms"); } + return; } + if (tabPath == "/privacy.aspx") { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Privacy&" + requestQuery); } else { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Privacy"); } + return; } + tabPath = tabPath.Replace("/", "//"); - tabPath = tabPath.Replace(".aspx", ""); + tabPath = tabPath.Replace(".aspx", string.Empty); TabCollection objTabs = TabController.Instance.GetTabsByPortal(tabPath.StartsWith("//host") ? Null.NullInteger : portalID); foreach (KeyValuePair kvp in objTabs) { - if ((kvp.Value.IsDeleted == false && kvp.Value.TabPath.ToLowerInvariant() == tabPath)) + if (kvp.Value.IsDeleted == false && kvp.Value.TabPath.ToLowerInvariant() == tabPath) { - if ((!String.IsNullOrEmpty(app.Request.Url.Query))) + if (!string.IsNullOrEmpty(app.Request.Url.Query)) { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID + + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID + "&" + app.Request.Url.Query.TrimStart('?')); } else { - RewriterUtils.RewriteUrl(app.Context, - "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID); + RewriterUtils.RewriteUrl( + app.Context, + "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID); } + return; } } } } } - } - - #endregion + } } } diff --git a/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs b/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs index 055bc925de4..884d5d5edf3 100644 --- a/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs +++ b/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs @@ -1,23 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Framework.Providers; -using DotNetNuke.HttpModules.UrlRewrite; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.Services.Url.FriendlyUrl + // ReSharper restore CheckNamespace { + using System; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Framework.Providers; + using DotNetNuke.HttpModules.UrlRewrite; + public class DNNFriendlyUrlProvider : FriendlyUrlProvider { internal const string ProviderName = "DNNFriendlyUrl"; @@ -31,72 +28,73 @@ public class DNNFriendlyUrlProvider : FriendlyUrlProvider public DNNFriendlyUrlProvider() { - //Read the configuration specific information for this provider - var objProvider = (Provider)_providerConfiguration.Providers[ProviderName]; + // Read the configuration specific information for this provider + var objProvider = (Provider)this._providerConfiguration.Providers[ProviderName]; - if (!String.IsNullOrEmpty(objProvider.Attributes["urlFormat"])) + if (!string.IsNullOrEmpty(objProvider.Attributes["urlFormat"])) { switch (objProvider.Attributes["urlFormat"].ToLowerInvariant()) { case "searchfriendly": - _urlFormat = UrlFormatType.SearchFriendly; + this._urlFormat = UrlFormatType.SearchFriendly; break; case "humanfriendly": - _urlFormat = UrlFormatType.HumanFriendly; + this._urlFormat = UrlFormatType.HumanFriendly; break; case "advanced": case "customonly": - _urlFormat = UrlFormatType.Advanced; + this._urlFormat = UrlFormatType.Advanced; break; default: - _urlFormat = UrlFormatType.SearchFriendly; + this._urlFormat = UrlFormatType.SearchFriendly; break; } } - //instance the correct provider implementation - switch (_urlFormat) + + // instance the correct provider implementation + switch (this._urlFormat) { case UrlFormatType.Advanced: - _providerInstance = new AdvancedFriendlyUrlProvider(objProvider.Attributes); + this._providerInstance = new AdvancedFriendlyUrlProvider(objProvider.Attributes); break; case UrlFormatType.HumanFriendly: case UrlFormatType.SearchFriendly: - _providerInstance = new BasicFriendlyUrlProvider(objProvider.Attributes); + this._providerInstance = new BasicFriendlyUrlProvider(objProvider.Attributes); break; } - string extensions = !String.IsNullOrEmpty(objProvider.Attributes["validExtensions"]) ? objProvider.Attributes["validExtensions"] : ".aspx"; - _validExtensions = extensions.Split(','); + string extensions = !string.IsNullOrEmpty(objProvider.Attributes["validExtensions"]) ? objProvider.Attributes["validExtensions"] : ".aspx"; + this._validExtensions = extensions.Split(','); } public string[] ValidExtensions { - get { return _validExtensions; } + get { return this._validExtensions; } } public UrlFormatType UrlFormat { - get { return _urlFormat; } + get { return this._urlFormat; } } public override string FriendlyUrl(TabInfo tab, string path) { - return _providerInstance.FriendlyUrl(tab, path); + return this._providerInstance.FriendlyUrl(tab, path); } public override string FriendlyUrl(TabInfo tab, string path, string pageName) { - return _providerInstance.FriendlyUrl(tab, path, pageName); + return this._providerInstance.FriendlyUrl(tab, path, pageName); } public override string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings) { - return _providerInstance.FriendlyUrl(tab, path, pageName, settings); + return this._providerInstance.FriendlyUrl(tab, path, pageName, settings); } public override string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) { - return _providerInstance.FriendlyUrl(tab, path, pageName, portalAlias); + return this._providerInstance.FriendlyUrl(tab, path, pageName, portalAlias); } } } diff --git a/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs b/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs index c00d95e51eb..c5e52088b6c 100644 --- a/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs +++ b/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web; - -using DotNetNuke.Entities.Urls; -using DotNetNuke.Framework.Providers; -using DotNetNuke.HttpModules.UrlRewrite; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules { + using System.Web; + + using DotNetNuke.Entities.Urls; + using DotNetNuke.Framework.Providers; + using DotNetNuke.HttpModules.UrlRewrite; + public class UrlRewriteModule : IHttpModule { private string _providerToUse; @@ -22,38 +17,34 @@ public class UrlRewriteModule : IHttpModule public string ModuleName { get { return "UrlRewriteModule"; } - } - - #region IHttpModule Members - + } + public void Init(HttpApplication application) { - _providerToUse = DotNetNuke.Common.Utilities.Config.GetFriendlyUrlProvider(); - - //bind events depending on currently configured friendly url provider - //note that the current configured friendly url provider determines what type - //of url rewriting is required. + this._providerToUse = DotNetNuke.Common.Utilities.Config.GetFriendlyUrlProvider(); - switch (_providerToUse) + // bind events depending on currently configured friendly url provider + // note that the current configured friendly url provider determines what type + // of url rewriting is required. + switch (this._providerToUse) { case "advanced": var advancedRewriter = new AdvancedUrlRewriter(); - _urlRewriter = advancedRewriter; - //bind the rewrite event to the begin request event - application.BeginRequest += _urlRewriter.RewriteUrl; + this._urlRewriter = advancedRewriter; + + // bind the rewrite event to the begin request event + application.BeginRequest += this._urlRewriter.RewriteUrl; break; default: var basicRewriter = new BasicUrlRewriter(); - _urlRewriter = basicRewriter; - application.BeginRequest += _urlRewriter.RewriteUrl; + this._urlRewriter = basicRewriter; + application.BeginRequest += this._urlRewriter.RewriteUrl; break; } } public void Dispose() { - } - - #endregion + } } } diff --git a/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs b/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs index bbc9e69b57a..6ee0d7d1024 100644 --- a/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs +++ b/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.HttpModules.UsersOnline { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Users; + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public class UsersOnlineModule : IHttpModule { @@ -23,39 +19,35 @@ public string ModuleName { return "UsersOnlineModule"; } - } - - #region IHttpModule Members - + } + public void Init(HttpApplication application) { - application.AuthorizeRequest += OnAuthorizeRequest; + application.AuthorizeRequest += this.OnAuthorizeRequest; } public void Dispose() { - } - - #endregion - + } + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public void OnAuthorizeRequest(object s, EventArgs e) { - //First check if we are upgrading/installing - var app = (HttpApplication) s; + // First check if we are upgrading/installing + var app = (HttpApplication)s; HttpRequest request = app.Request; - //check if we are upgrading/installing or if this is a captcha request + // check if we are upgrading/installing or if this is a captcha request if (!Initialize.ProcessHttpModule(request, false, false)) { return; } - //Create a Users Online Controller + // Create a Users Online Controller var objUserOnlineController = new UserOnlineController(); - //Is Users Online Enabled? - if ((objUserOnlineController.IsEnabled())) + // Is Users Online Enabled? + if (objUserOnlineController.IsEnabled()) { objUserOnlineController.TrackUsers(); } diff --git a/DNN Platform/HttpModules/packages.config b/DNN Platform/HttpModules/packages.config index 50cd50d0ad8..93fa98c3e44 100644 --- a/DNN Platform/HttpModules/packages.config +++ b/DNN Platform/HttpModules/packages.config @@ -1,4 +1,5 @@ - - - + + + + \ No newline at end of file diff --git a/DNN Platform/Library/Application/Application.cs b/DNN Platform/Library/Application/Application.cs index 3f152cdd751..3db14dbd800 100644 --- a/DNN Platform/Library/Application/Application.cs +++ b/DNN Platform/Library/Application/Application.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Diagnostics; -using System.Reflection; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Application { + using System; + using System.Diagnostics; + using System.Reflection; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + /// /// The Application class contains properties that describe the DotNetNuke Application. /// @@ -31,7 +26,7 @@ protected internal Application() /// /// Gets the company to which the DotNetNuke application is related. /// - /// Fixed result: DotNetNuke Corporation + /// Fixed result: DotNetNuke Corporation. public string Company { get @@ -54,9 +49,9 @@ public virtual Version CurrentVersion } /// - /// Gets the description of the application + /// Gets the description of the application. /// - /// Fixed result: DNN Platform + /// Fixed result: DNN Platform. public virtual string Description { get @@ -66,9 +61,9 @@ public virtual string Description } /// - /// Gets the help URL related to the DotNetNuke application + /// Gets the help URL related to the DotNetNuke application. /// - /// Fixed result: https://dnndocs.com/ + /// Fixed result: https://dnndocs.com/. public string HelpUrl { get @@ -80,19 +75,19 @@ public string HelpUrl /// /// Gets the legal copyright. /// - /// Dynamic: DNN Platform is copyright 2002-todays year by .NET Foundation" + /// Dynamic: DNN Platform is copyright 2002-todays year by .NET Foundation". public string LegalCopyright { get { - return string.Concat("DNN Platform is copyright 2002-", DateTime.Today.ToString("yyyy")," by .NET Foundation"); + return string.Concat("DNN Platform is copyright 2002-", DateTime.Today.ToString("yyyy"), " by .NET Foundation"); } } /// - /// Gets the name of the application + /// Gets the name of the application. /// - /// Fixed result: DNNCORP.CE + /// Fixed result: DNNCORP.CE. public virtual string Name { get @@ -102,9 +97,9 @@ public virtual string Name } /// - /// Gets the SKU (Stock Keeping Unit) + /// Gets the SKU (Stock Keeping Unit). /// - /// Fixed result: DNN + /// Fixed result: DNN. public virtual string SKU { get @@ -114,13 +109,13 @@ public virtual string SKU } /// - /// Gets the status of the DotnetNuke application + /// Gets the status of the DotnetNuke application. /// /// - /// If the value is not be Stable, you will see the exactly status and version in page's title if allow display beta message in host setting. + /// If the value is not be Stable, you will see the exactly status and version in page's title if allow display beta message in host setting. /// /// - /// The value can be: None, Alpha, Beta, RC, Stable + /// The value can be: None, Alpha, Beta, RC, Stable. /// public ReleaseMode Status { @@ -129,21 +124,22 @@ public ReleaseMode Status if (_status == ReleaseMode.None) { Assembly assy = Assembly.GetExecutingAssembly(); - if (Attribute.IsDefined(assy, typeof (AssemblyStatusAttribute))) + if (Attribute.IsDefined(assy, typeof(AssemblyStatusAttribute))) { - Attribute attr = Attribute.GetCustomAttribute(assy, typeof (AssemblyStatusAttribute)); + Attribute attr = Attribute.GetCustomAttribute(assy, typeof(AssemblyStatusAttribute)); if (attr != null) { - _status = ((AssemblyStatusAttribute) attr).Status; + _status = ((AssemblyStatusAttribute)attr).Status; } } } + return _status; } } /// - /// Gets the title of the application + /// Gets the title of the application. /// /// Fixed value: DotNetNuke. public string Title @@ -157,7 +153,7 @@ public string Title /// /// Gets the trademark. /// - /// Fixed value: DotNetNuke,DNN + /// Fixed value: DotNetNuke,DNN. public string Trademark { get @@ -167,9 +163,9 @@ public string Trademark } /// - /// Gets the type of the application + /// Gets the type of the application. /// - /// Fixed value: Framework + /// Fixed value: Framework. public string Type { get @@ -181,24 +177,25 @@ public string Type /// /// Gets the upgrade URL. /// - /// Fixed value: https://dnnplatform.io + /// Fixed value: https://dnnplatform.io. public string UpgradeUrl { get { - var url = Config.GetSetting("UpdateServiceUrl"); - if (string.IsNullOrEmpty(url)) - { - return "https://dnnplatform.io"; - } - return url; + var url = Config.GetSetting("UpdateServiceUrl"); + if (string.IsNullOrEmpty(url)) + { + return "https://dnnplatform.io"; + } + + return url; } } /// - /// Gets the URL of the application + /// Gets the URL of the application. /// - /// Fixed value: https://dnncommunity.org + /// Fixed value: https://dnncommunity.org. public string Url { get @@ -208,7 +205,7 @@ public string Url } /// - /// Gets the version of the DotNetNuke framework/application + /// Gets the version of the DotNetNuke framework/application. /// /// The version as retreieved from the Executing assembly. public virtual Version Version @@ -219,22 +216,18 @@ public virtual Version Version var fileVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).FileVersion; return new Version(fileVersion); } - } - - #region "Public Functions" - + } + /// - /// Determine whether a product specific change is to be applied + /// Determine whether a product specific change is to be applied. /// - /// list of product names - /// true if product is within list of names + /// list of product names. + /// true if product is within list of names. /// /// public virtual bool ApplyToProduct(string productNames) { - return productNames.Contains(Name); - } - - #endregion + return productNames.Contains(this.Name); + } } } diff --git a/DNN Platform/Library/Application/AssemblyStatusAttribute.cs b/DNN Platform/Library/Application/AssemblyStatusAttribute.cs index ea427d7826a..324e8c1f3b4 100644 --- a/DNN Platform/Library/Application/AssemblyStatusAttribute.cs +++ b/DNN Platform/Library/Application/AssemblyStatusAttribute.cs @@ -1,61 +1,60 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Application { - /// - /// The enumeration of release mode. - /// - /// - /// - /// None: Not specified for the current release. - /// Alpha:Alpha release is an opportunity for customers to get an early look at a particular software feature. - /// Beta: Beta release is a mostly completed release, - /// At this point we will have implemented most of the major features planned for a specific release. - /// RC: RC release will be the Stable release if there is no major show-stopping bugs, - /// We have gone through all the major test scenarios and are just running through a final set of regression - /// tests and verifying the packaging. - /// Stable: Stable release is believed to be ready for use, - /// remember that only stable release can be used in production environment. - /// - /// + using System; + + /// + /// The enumeration of release mode. + /// + /// + /// + /// None: Not specified for the current release. + /// Alpha:Alpha release is an opportunity for customers to get an early look at a particular software feature. + /// Beta: Beta release is a mostly completed release, + /// At this point we will have implemented most of the major features planned for a specific release. + /// RC: RC release will be the Stable release if there is no major show-stopping bugs, + /// We have gone through all the major test scenarios and are just running through a final set of regression + /// tests and verifying the packaging. + /// Stable: Stable release is believed to be ready for use, + /// remember that only stable release can be used in production environment. + /// + /// public enum ReleaseMode { /// /// Not asssigned /// None, + /// /// Alpha release /// Alpha, + /// /// Beta release /// Beta, + /// /// Release candidate /// RC, + /// /// Stable release version /// - Stable + Stable, } - /// - /// The status of current assembly. - /// - /// - /// [assembly: AssemblyStatus(ReleaseMode.Stable)] - /// + /// + /// The status of current assembly. + /// + /// + /// [assembly: AssemblyStatus(ReleaseMode.Stable)]. + /// [AttributeUsage(AttributeTargets.Assembly)] public class AssemblyStatusAttribute : Attribute { @@ -67,18 +66,17 @@ public class AssemblyStatusAttribute : Attribute /// The release mode. public AssemblyStatusAttribute(ReleaseMode releaseMode) { - _releaseMode = releaseMode; + this._releaseMode = releaseMode; } - - - /// - /// Status of current assembly. - /// + + /// + /// Gets status of current assembly. + /// public ReleaseMode Status { get { - return _releaseMode; + return this._releaseMode; } } } diff --git a/DNN Platform/Library/Application/DotNetNukeContext.cs b/DNN Platform/Library/Application/DotNetNukeContext.cs index 7a4f69d70a7..558ad76b508 100644 --- a/DNN Platform/Library/Application/DotNetNukeContext.cs +++ b/DNN Platform/Library/Application/DotNetNukeContext.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.UI.Containers.EventListeners; -using DotNetNuke.UI.Skins.EventListeners; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Application { + using System.Collections.Generic; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.UI.Containers.EventListeners; + using DotNetNuke.UI.Skins.EventListeners; + /// - /// Defines the context for the environment of the DotNetNuke application + /// Defines the context for the environment of the DotNetNuke application. /// public class DotNetNukeContext { @@ -27,7 +22,8 @@ public class DotNetNukeContext /// /// Initializes a new instance of the class. /// - protected DotNetNukeContext() : this(new Application()) + protected DotNetNukeContext() + : this(new Application()) { } @@ -37,70 +33,72 @@ protected DotNetNukeContext() : this(new Application()) /// The application. protected DotNetNukeContext(Application application) { - _application = application; - _containerEventListeners = new NaiveLockingList(); - _skinEventListeners = new NaiveLockingList(); + this._application = application; + this._containerEventListeners = new NaiveLockingList(); + this._skinEventListeners = new NaiveLockingList(); } - /// - /// Get the application. - /// - public Application Application + /// + /// Gets or sets the current app context. + /// + public static DotNetNukeContext Current { get { - return _application; + if (_current == null) + { + _current = new DotNetNukeContext(); + } + + return _current; + } + + set + { + _current = value; } } - /// - /// Gets the container event listeners. The listeners will be called in each life cycle of load container. - /// - /// - /// - /// - /// - /// - public IList ContainerEventListeners + /// + /// Gets get the application. + /// + public Application Application { get { - return _containerEventListeners; + return this._application; } } - /// - /// Gets the skin event listeners. The listeners will be called in each life cycle of load skin. - /// - /// - /// - /// - /// - /// - public IList SkinEventListeners + /// + /// Gets the container event listeners. The listeners will be called in each life cycle of load container. + /// + /// + /// + /// + /// + /// + public IList ContainerEventListeners { get { - return _skinEventListeners; + return this._containerEventListeners; } } - /// - /// Gets or sets the current app context. - /// - public static DotNetNukeContext Current + /// + /// Gets the skin event listeners. The listeners will be called in each life cycle of load skin. + /// + /// + /// + /// + /// + /// + public IList SkinEventListeners { get { - if (_current == null) - { - _current = new DotNetNukeContext(); - } - return _current; - } - set - { - _current = value; + return this._skinEventListeners; } } } diff --git a/DNN Platform/Library/Collections/CollectionExtensions.cs b/DNN Platform/Library/Collections/CollectionExtensions.cs index fec3f196f6c..fa8051c7818 100644 --- a/DNN Platform/Library/Collections/CollectionExtensions.cs +++ b/DNN Platform/Library/Collections/CollectionExtensions.cs @@ -1,40 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.Linq; -using System.Xml.Linq; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Collections { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.Linq; + using System.Xml.Linq; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Instrumentation; + /// - /// Provides a collection of useful extensions to collections + /// Provides a collection of useful extensions to collections. /// public static class CollectionExtensions { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CollectionExtensions)); /// - /// Converts a string with multiple key-value pairs into a Dictionary, if there are duplicated keys in your string - /// only the first found key is kept since keys must be unique in a Dictionary + /// Converts a string with multiple key-value pairs into a Dictionary, if there are duplicated keys in your string + /// only the first found key is kept since keys must be unique in a Dictionary. /// - /// The string containing the key-value pairs - /// The separator used to separate each key-value pair - /// The separator used between the each key and value - /// Dictionary with a string key and a string value - public static Dictionary CreateDictionaryFromString(string stringOfPairs, char pairsSeparator, char pairSeparator) + /// The string containing the key-value pairs. + /// The separator used to separate each key-value pair. + /// The separator used between the each key and value. + /// Dictionary with a string key and a string value. + public static Dictionary CreateDictionaryFromString(string stringOfPairs, char pairsSeparator, char pairSeparator) { - var dictionary = new Dictionary(); + var dictionary = new Dictionary(); if (!string.IsNullOrEmpty(stringOfPairs)) { var pairs = stringOfPairs.Split(pairsSeparator); @@ -47,29 +47,32 @@ public static Dictionary CreateDictionaryFromString(string strin { key = keyValues[0]; } + if (keyValues.GetUpperBound(0) >= 1) { value = keyValues[1]; } + if (!string.IsNullOrEmpty(key) && value != null && !dictionary.ContainsKey(key)) { dictionary.Add(key, value); } } } + return dictionary; } /// - /// Converts a Dictionary with a string key and a string value into a plain string separated by your choice of separators + /// Converts a Dictionary with a string key and a string value into a plain string separated by your choice of separators. /// - /// The Dictionary to convert - /// The separator to use between key-value pairs - /// The separator to use between each key and value - /// The dictionary's contents as a - public static string DictionaryToString(this Dictionary dictionary, string pairsSeparator, string pairSeparator) + /// The Dictionary to convert. + /// The separator to use between key-value pairs. + /// The separator to use between each key and value. + /// The dictionary's contents as a . + public static string DictionaryToString(this Dictionary dictionary, string pairsSeparator, string pairSeparator) { - return String.Join(pairsSeparator, dictionary.Select(pair => pair.Key + pairSeparator + pair.Value)); + return string.Join(pairsSeparator, dictionary.Select(pair => pair.Key + pairSeparator + pair.Value)); } /// @@ -94,105 +97,103 @@ public static Func GetFlexibleBooleanParsingFunction() public static Func GetFlexibleBooleanParsingFunction(params string[] trueValues) { return value => trueValues.Contains(value, StringComparer.OrdinalIgnoreCase); - } - - #region GetValue Extension Methods - + } + /// Gets the value from the dictionary. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this IDictionary dictionary, string key) { return dictionary.GetValue(key, ConvertValue); } /// Gets the value from the lookup. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// has multiple values for the given - /// does not contain a value for + /// is null. + /// has multiple values for the given . + /// does not contain a value for . public static T GetValue(this ILookup lookup, string key) { return lookup.ToDictionary(key).GetValue(key); } /// Gets the value from the XML node's child elements, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this IXPathNavigable node, string key) { return node.ToDictionary().GetValue(key); } /// Gets the value from the collection. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// has multiple values for the given - /// does not contain a value for + /// is null. + /// has multiple values for the given . + /// does not contain a value for . public static T GetValue(this NameValueCollection collection, string key) { return collection.ToLookup(false).GetValue(key); } /// Gets the value from the XML node's child elements. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this XContainer node, string key) { return node.ToDictionary().GetValue(key); } /// Gets the value from the dictionary. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// or is null - /// does not contain a value for + /// or is null. + /// does not contain a value for . public static T GetValue(this IDictionary dictionary, string key, Func converter) { Requires.NotNull("dictionary", dictionary); @@ -207,214 +208,210 @@ public static T GetValue(this IDictionary dictionary, string key, FuncGets the value from the lookup. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given - /// does not contain a value for + /// is null. + /// has multiple values for the given . + /// does not contain a value for . public static T GetValue(this ILookup lookup, string key, Func converter) { return lookup.ToDictionary(key).GetValue(key, converter); } /// Gets the value from the XML node's child elements. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this IXPathNavigable node, string key, Func converter) { return node.ToDictionary().GetValue(key, converter); } /// Gets the value from the collection. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given - /// does not contain a value for + /// is null. + /// has multiple values for the given . + /// does not contain a value for . public static T GetValue(this NameValueCollection collection, string key, Func converter) { return collection.ToLookup(false).GetValue(key, converter); } /// Gets the value from the XML node's child elements. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this XContainer node, string key, Func converter) { return node.ToDictionary().GetValue(key, converter); } /// Gets the value from the dictionary. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this IDictionary dictionary, string key, Func converter) { return dictionary.GetValue(key, (object value) => ConvertValue(value, converter)); } /// Gets the value from the lookup. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given - /// does not contain a value for + /// is null. + /// has multiple values for the given . + /// does not contain a value for . public static T GetValue(this ILookup lookup, string key, Func converter) { return lookup.ToDictionary(key).GetValue(key, converter); } /// Gets the value from the XML node's child elements. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this IXPathNavigable node, string key, Func converter) { return node.ToDictionary().GetValue(key, converter); } /// Gets the value from the collection. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given - /// does not contain a value for + /// is null. + /// has multiple values for the given . + /// does not contain a value for . public static T GetValue(this NameValueCollection collection, string key, Func converter) { return collection.ToLookup(false).GetValue(key, converter); } /// Gets the value from the XML node's child elements. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// does not contain a value for + /// is null. + /// does not contain a value for . public static T GetValue(this XContainer node, string key, Func converter) { return node.ToDictionary().GetValue(key, converter); - } - - #endregion - - #region GetValueOrDefault Extension Methods - + } + /// Gets the value from the dictionary, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null + /// is null. public static T GetValueOrDefault(this IDictionary dictionary, string key) { return dictionary.GetValueOrDefault(key, default(T)); } /// Gets the value from the lookup, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this ILookup lookup, string key) { return lookup.ToDictionary(key).GetValueOrDefault(key); } /// Gets the value from the XML node's child elements, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null + /// is null. public static T GetValueOrDefault(this IXPathNavigable node, string key) { return node.ToDictionary().GetValueOrDefault(key); } /// Gets the value from the collection, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this NameValueCollection collection, string key) { return collection.ToLookup(false).GetValueOrDefault(key); } /// Gets the value from the XML node's child elements, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null + /// is null. public static T GetValueOrDefault(this XContainer node, string key) { return node.ToDictionary().GetValueOrDefault(key); } /// Gets the value from the dictionary, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// The default value to return if the dictionary doesn't have a value for the given . @@ -422,16 +419,16 @@ public static T GetValueOrDefault(this XContainer node, string key) /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null + /// is null. public static T GetValueOrDefault(this IDictionary dictionary, string key, T defaultValue) { return dictionary.GetValueOrDefault(key, defaultValue, ConvertValue); } /// Gets the value from the lookup, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// The default value to return if the lookup doesn't have a value for the given . @@ -439,17 +436,17 @@ public static T GetValueOrDefault(this IDictionary dictionary, string key, T /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this ILookup lookup, string key, T defaultValue) { return lookup.ToDictionary(key).GetValueOrDefault(key, defaultValue); } /// Gets the value from the XML node's child elements, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// The default value to return if the node doesn't have a value for the given . @@ -457,16 +454,16 @@ public static T GetValueOrDefault(this ILookup lookup, string /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null + /// is null. public static T GetValueOrDefault(this IXPathNavigable node, string key, T defaultValue) { return node.ToDictionary().GetValueOrDefault(key, defaultValue); } /// Gets the value from the collection, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// The default value to return if the collection doesn't have a value for the given . @@ -474,17 +471,17 @@ public static T GetValueOrDefault(this IXPathNavigable node, string key, T de /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this NameValueCollection collection, string key, T defaultValue) { return collection.ToLookup(false).GetValueOrDefault(key, defaultValue); } /// Gets the value from the XML node's child elements, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// The default value to return if the node doesn't have a value for the given . @@ -492,267 +489,267 @@ public static T GetValueOrDefault(this NameValueCollection collection, string /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// - /// is null + /// is null. public static T GetValueOrDefault(this XContainer node, string key, T defaultValue) { return node.ToDictionary().GetValueOrDefault(key, defaultValue); } /// Gets the value from the dictionary, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this IDictionary dictionary, string key, Func converter) { return dictionary.GetValueOrDefault(key, default(T), converter); } /// Gets the value from the lookup, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this ILookup lookup, string key, Func converter) { return lookup.ToDictionary(key).GetValueOrDefault(key, converter); } /// Gets the value from the XML node's child elements, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this IXPathNavigable node, string key, Func converter) { return node.ToDictionary().GetValueOrDefault(key, converter); } /// Gets the value from the collection, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this NameValueCollection collection, string key, Func converter) { return collection.ToLookup(false).GetValueOrDefault(key, converter); } /// Gets the value from the XML node's child elements, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this XContainer node, string key, Func converter) { return node.ToDictionary().GetValueOrDefault(key, converter); } /// Gets the value from the dictionary, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this IDictionary dictionary, string key, Func converter) { return dictionary.GetValueOrDefault(key, default(T), (object value) => ConvertValue(value, converter)); } /// Gets the value from the lookup, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this ILookup lookup, string key, Func converter) { return lookup.ToDictionary(key).GetValueOrDefault(key, converter); } /// Gets the value from the XML node's child elements, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this IXPathNavigable node, string key, Func converter) { return node.ToDictionary().GetValueOrDefault(key, converter); } /// Gets the value from the collection, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this NameValueCollection collection, string key, Func converter) { return collection.ToLookup(false).GetValueOrDefault(key, converter); } /// Gets the value from the XML node's child elements, returning the default value of if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this XContainer node, string key, Func converter) { return node.ToDictionary().GetValueOrDefault(key, converter); } /// Gets the value from the dictionary, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// The default value to return if the dictionary doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this IDictionary dictionary, string key, T defaultValue, Func converter) { return dictionary.GetValueOrDefault(key, defaultValue, (object value) => ConvertValue(value, converter)); } /// Gets the value from the lookup, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// The default value to return if the lookup doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this ILookup lookup, string key, T defaultValue, Func converter) { return lookup.ToDictionary(key).GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the XML node's child elements, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// The default value to return if the node doesn't have a value for the given . /// A function to convert the value as a to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this IXPathNavigable node, string key, T defaultValue, Func converter) { return node.ToDictionary().GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the collection, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// The default value to return if the collection doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this NameValueCollection collection, string key, T defaultValue, Func converter) { return collection.ToLookup(false).GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the XML node's child elements, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// The default value to return if the node doesn't have a value for the given . /// A function to convert the value as a to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this XContainer node, string key, T defaultValue, Func converter) { return node.ToDictionary().GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the lookup, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The lookup. /// The key by which to get the value. /// The default value to return if the lookup doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this ILookup lookup, string key, T defaultValue, Func converter) { return lookup.ToDictionary(key).GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the XML node's child elements, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// The default value to return if the node doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this IXPathNavigable node, string key, T defaultValue, Func converter) { return node.ToDictionary().GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the collection, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The collection. /// The key by which to get the value. /// The default value to return if the collection doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// is null - /// has multiple values for the given + /// is null. + /// has multiple values for the given . public static T GetValueOrDefault(this NameValueCollection collection, string key, T defaultValue, Func converter) { return collection.ToLookup(false).GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the XML node's child elements, returning if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// An XML node which containers other elements. /// The name of the element from which to get the value. /// The default value to return if the node doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// is null + /// is null. public static T GetValueOrDefault(this XContainer node, string key, T defaultValue, Func converter) { return node.ToDictionary().GetValueOrDefault(key, defaultValue, converter); } /// Gets the value from the dictionary, returning the if the value doesn't exist. - /// The type of the value to retrieve + /// The type of the value to retrieve. /// The dictionary. /// The key by which to get the value. /// The default value to return if the dictionary doesn't have a value for the given . /// A function to convert the value as an to a instance. /// A instance. - /// or is null + /// or is null. public static T GetValueOrDefault(this IDictionary dictionary, string key, T defaultValue, Func converter) { Requires.NotNull("dictionary", dictionary); @@ -766,42 +763,39 @@ public static T GetValueOrDefault(this IDictionary dictionary, string key, T { Logger.ErrorFormat("Error loading portal setting: {0} Default value {1} was used instead", key + ":" + dictionary[key], defaultValue.ToString()); } + return value; - } - - #endregion - - #region GetValues Extension Methods - + } + /// Gets the values from the lookup. - /// The type of the values to retrieve + /// The type of the values to retrieve. /// The lookup. /// The key by which to get the values. /// A sequence of instances. - /// is null + /// is null. public static IEnumerable GetValues(this ILookup lookup, string key) { return lookup.GetValues(key, ConvertValue); } /// Gets the values from the collection. - /// The type of the values to retrieve + /// The type of the values to retrieve. /// The collection. /// The key by which to get the values. /// A sequence of instances. - /// is null + /// is null. public static IEnumerable GetValues(this NameValueCollection collection, string key) { return collection.ToLookup().GetValues(key); } /// Gets the values from the lookup. - /// The type of the values to retrieve + /// The type of the values to retrieve. /// The lookup. /// The key by which to get the values. /// A function to convert a value as an to a instance. /// A sequence of instances. - /// or is null + /// or is null. public static IEnumerable GetValues(this ILookup lookup, string key, Func converter) { Requires.NotNull("lookup", lookup); @@ -811,23 +805,21 @@ public static IEnumerable GetValues(this ILookup lookup, s } /// Gets the values from the collection. - /// The type of the values to retrieve + /// The type of the values to retrieve. /// The collection. /// The key by which to get the values. /// A function to convert a value as an to a instance. /// A sequence of instances. - /// or is null + /// or is null. public static IEnumerable GetValues(this NameValueCollection collection, string key, Func converter) { return collection.ToLookup().GetValues(key, converter); - } - - #endregion - + } + /// Converts the to an . /// The collection. /// An instance. - /// is null + /// is null. public static ILookup ToLookup(this NameValueCollection collection) { return collection.ToLookup(true); @@ -835,9 +827,9 @@ public static ILookup ToLookup(this NameValueCollection collecti /// Converts the to an . /// The collection. - /// If true, treats values in the as comma-delimited lists of items (e.g. from a ) + /// If true, treats values in the as comma-delimited lists of items (e.g. from a ). /// An instance. - /// is null + /// is null. public static ILookup ToLookup(this NameValueCollection collection, bool splitValues) { Requires.NotNull("collection", collection); @@ -861,18 +853,16 @@ public static IEnumerable ForEach(this IEnumerable source, } return source; - } - - #region Private Methods - + } + /// Converts the into a instance. - /// The type of the value to return + /// The type of the value to return. /// The value to convert. /// A instance. /// /// the value is null and is a value type, or /// the value does not implement the interface and - /// no cast is defined from the value to + /// no cast is defined from the value to . /// private static T ConvertValue(object value) { @@ -911,7 +901,7 @@ private static T ConvertValue(object value) } /// Converts the into a instance. - /// The type of the value to return + /// The type of the value to return. /// The value to convert. /// A function to convert a to a instance. /// A instance. @@ -933,7 +923,7 @@ private static IEnumerable> ParseValues(string key, /// Wraps the into instances. /// The key. /// The values. - /// If true, treats a single item in as a comma-delimited list of items (e.g. from a ) + /// If true, treats a single item in as a comma-delimited list of items (e.g. from a ). /// A sequence of instances. private static IEnumerable> ParseValues(string key, string[] values, bool splitSingleValue) { @@ -945,7 +935,7 @@ private static IEnumerable> ParseValues(string key, /// Converts the to a . /// The node. /// A instance. - /// is null + /// is null. private static Dictionary ToDictionary(this XContainer node) { Requires.NotNull("node", node); @@ -955,7 +945,7 @@ private static Dictionary ToDictionary(this XContainer node) /// Converts the to a . /// The node. /// A instance. - /// is null + /// is null. private static Dictionary ToDictionary(this IXPathNavigable node) { Requires.NotNull("node", node); @@ -966,8 +956,8 @@ private static Dictionary ToDictionary(this IXPathNavigable node /// The lookup. /// The key. /// A instance with zero or one key/value. - /// is null - /// There were multiple values for the given key + /// is null. + /// There were multiple values for the given key. private static Dictionary ToDictionary(this ILookup lookup, string key) { Requires.NotNull("lookup", lookup); @@ -980,9 +970,6 @@ private static Dictionary ToDictionary(this ILookup - /// Provides extensions to IEnumerable + /// Provides extensions to IEnumerable. /// public static class EnumerableExtensions { /// /// Converts dynamic data to a DataTable. Useful for databinding. /// - /// The items in the IEnumerable + /// The items in the IEnumerable. /// A DataTable with the copied dynamic data. public static DataTable ToDataTable(this IEnumerable items) { var data = items.ToArray(); - if (!data.Any()) - return null; - + if (!data.Any()) + { + return null; + } + var dt = new DataTable(); - + // Create the columns foreach (var key in ((IDictionary)data[0]).Keys) { @@ -38,6 +40,7 @@ public static DataTable ToDataTable(this IEnumerable items) { dt.Rows.Add(((IDictionary)d).Values.ToArray()); } + return dt; } } diff --git a/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs b/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs index 17da9d77c25..d72c81f00b2 100644 --- a/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs +++ b/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs @@ -1,51 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Threading; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + using System.Threading; + public class ExclusiveLockStrategy : ILockStrategy { private readonly object _lock = new object(); private bool _isDisposed; - private Thread _lockedThread; - - #region ILockStrategy Members - - public ISharedCollectionLock GetReadLock() - { - return GetLock(TimeSpan.FromMilliseconds(-1)); - } - - public ISharedCollectionLock GetReadLock(TimeSpan timeout) - { - return GetLock(timeout); - } - - public ISharedCollectionLock GetWriteLock() - { - return GetLock(TimeSpan.FromMilliseconds(-1)); - } - - public ISharedCollectionLock GetWriteLock(TimeSpan timeout) - { - return GetLock(timeout); - } + private Thread _lockedThread; public bool ThreadCanRead { get { - EnsureNotDisposed(); - return IsThreadLocked(); + this.EnsureNotDisposed(); + return this.IsThreadLocked(); } } @@ -53,8 +26,8 @@ public bool ThreadCanWrite { get { - EnsureNotDisposed(); - return IsThreadLocked(); + this.EnsureNotDisposed(); + return this.IsThreadLocked(); } } @@ -65,26 +38,52 @@ public bool SupportsConcurrentReads return false; } } + + public ISharedCollectionLock GetReadLock() + { + return this.GetLock(TimeSpan.FromMilliseconds(-1)); + } - public void Dispose() + public ISharedCollectionLock GetReadLock(TimeSpan timeout) { - _isDisposed = true; - //todo remove disposable from interface? + return this.GetLock(timeout); } - #endregion + public ISharedCollectionLock GetWriteLock() + { + return this.GetLock(TimeSpan.FromMilliseconds(-1)); + } + + public ISharedCollectionLock GetWriteLock(TimeSpan timeout) + { + return this.GetLock(timeout); + } + public void Dispose() + { + this._isDisposed = true; + + // todo remove disposable from interface? + } + + public void Exit() + { + this.EnsureNotDisposed(); + Monitor.Exit(this._lock); + this._lockedThread = null; + } + private ISharedCollectionLock GetLock(TimeSpan timeout) { - EnsureNotDisposed(); - if (IsThreadLocked()) + this.EnsureNotDisposed(); + if (this.IsThreadLocked()) { throw new LockRecursionException(); } - if (Monitor.TryEnter(_lock, timeout)) + if (Monitor.TryEnter(this._lock, timeout)) { - _lockedThread = Thread.CurrentThread; + this._lockedThread = Thread.CurrentThread; return new MonitorLock(this); } else @@ -95,32 +94,25 @@ private ISharedCollectionLock GetLock(TimeSpan timeout) private ISharedCollectionLock GetLock() { - EnsureNotDisposed(); - if (IsThreadLocked()) + this.EnsureNotDisposed(); + if (this.IsThreadLocked()) { throw new LockRecursionException(); } - Monitor.Enter(_lock); - _lockedThread = Thread.CurrentThread; + Monitor.Enter(this._lock); + this._lockedThread = Thread.CurrentThread; return new MonitorLock(this); } private bool IsThreadLocked() { - return Thread.CurrentThread.Equals(_lockedThread); - } - - public void Exit() - { - EnsureNotDisposed(); - Monitor.Exit(_lock); - _lockedThread = null; + return Thread.CurrentThread.Equals(this._lockedThread); } private void EnsureNotDisposed() { - if (_isDisposed) + if (this._isDisposed) { throw new ObjectDisposedException("ExclusiveLockStrategy"); } diff --git a/DNN Platform/Library/Collections/IIndexable.cs b/DNN Platform/Library/Collections/IIndexable.cs index 64c99afd5fb..3124dbe62da 100644 --- a/DNN Platform/Library/Collections/IIndexable.cs +++ b/DNN Platform/Library/Collections/IIndexable.cs @@ -1,10 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Collections { + using System; + /// /// This interface used to make a class can have index declaration. /// diff --git a/DNN Platform/Library/Collections/ILockStrategy.cs b/DNN Platform/Library/Collections/ILockStrategy.cs index 8f1fd5ae2b3..67956cdaa80 100644 --- a/DNN Platform/Library/Collections/ILockStrategy.cs +++ b/DNN Platform/Library/Collections/ILockStrategy.cs @@ -1,19 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + public interface ILockStrategy : IDisposable { bool ThreadCanRead { get; } + bool ThreadCanWrite { get; } + bool SupportsConcurrentReads { get; } ISharedCollectionLock GetReadLock(); diff --git a/DNN Platform/Library/Collections/IPagedList.cs b/DNN Platform/Library/Collections/IPagedList.cs index ad1b8578394..3e88de80ddd 100644 --- a/DNN Platform/Library/Collections/IPagedList.cs +++ b/DNN Platform/Library/Collections/IPagedList.cs @@ -1,62 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections { + using System.Collections.Generic; + // Taken from Rob Conery's Blog post on the ASP.Net MVC PagedList Helper // http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/ /// /// Provides an interface to a paged list, which contains a snapshot - /// of a single page of data from the data store + /// of a single page of data from the data store. /// - /// The type of objects stored in the list + /// The type of objects stored in the list. public interface IPagedList : IList { /// - /// Gets a boolean indicating if there is a next page available + /// Gets a value indicating whether gets a boolean indicating if there is a next page available. /// bool HasNextPage { get; } /// - /// Gets a boolean indicating if there is a previous page available + /// Gets a value indicating whether gets a boolean indicating if there is a previous page available. /// bool HasPreviousPage { get; } /// - /// Gets a boolean indicating if this is the first page + /// Gets a value indicating whether gets a boolean indicating if this is the first page. /// bool IsFirstPage { get; } /// - /// Gets a boolean indicating if this is the last page + /// Gets a value indicating whether gets a boolean indicating if this is the last page. /// bool IsLastPage { get; } /// - /// The no of pages in this list + /// Gets or sets the no of pages in this list. /// int PageCount { get; set; } /// - /// The index of the page contained in this list + /// Gets or sets the index of the page contained in this list. /// int PageIndex { get; set; } /// - /// The size of the page in this list + /// Gets or sets the size of the page in this list. /// int PageSize { get; set; } /// - /// The total number of objects in the data store + /// Gets or sets the total number of objects in the data store. /// int TotalCount { get; set; } } diff --git a/DNN Platform/Library/Collections/ISharedCollectionLock.cs b/DNN Platform/Library/Collections/ISharedCollectionLock.cs index febd8fd9bf7..e8c77527704 100644 --- a/DNN Platform/Library/Collections/ISharedCollectionLock.cs +++ b/DNN Platform/Library/Collections/ISharedCollectionLock.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + public interface ISharedCollectionLock : IDisposable { } diff --git a/DNN Platform/Library/Collections/LockingStrategy.cs b/DNN Platform/Library/Collections/LockingStrategy.cs index a8880b926b0..b1e836d0a3c 100644 --- a/DNN Platform/Library/Collections/LockingStrategy.cs +++ b/DNN Platform/Library/Collections/LockingStrategy.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Collections.Internal { public enum LockingStrategy { ReaderWriter = 0, - Exclusive + Exclusive, } } diff --git a/DNN Platform/Library/Collections/LockingStrategyFactory.cs b/DNN Platform/Library/Collections/LockingStrategyFactory.cs index 81b9c854029..134418e0ce8 100644 --- a/DNN Platform/Library/Collections/LockingStrategyFactory.cs +++ b/DNN Platform/Library/Collections/LockingStrategyFactory.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + internal class LockingStrategyFactory { public static ILockStrategy Create(LockingStrategy strategy) diff --git a/DNN Platform/Library/Collections/MonitorLock.cs b/DNN Platform/Library/Collections/MonitorLock.cs index f1b1453c575..3ad20df1ddc 100644 --- a/DNN Platform/Library/Collections/MonitorLock.cs +++ b/DNN Platform/Library/Collections/MonitorLock.cs @@ -1,50 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + internal class MonitorLock : IDisposable, ISharedCollectionLock { private ExclusiveLockStrategy _lockStrategy; + + // To detect redundant calls + private bool _isDisposed; public MonitorLock(ExclusiveLockStrategy lockStrategy) { - _lockStrategy = lockStrategy; - } - - #region "IDisposable Support" - - // To detect redundant calls - private bool _isDisposed; - - + this._lockStrategy = lockStrategy; + } + public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { - if (!_isDisposed) + if (!this._isDisposed) { if (disposing) { - _lockStrategy.Exit(); - _lockStrategy = null; + this._lockStrategy.Exit(); + this._lockStrategy = null; } } - _isDisposed = true; - } - - #endregion + + this._isDisposed = true; + } } } diff --git a/DNN Platform/Library/Collections/NaiveLockingList.cs b/DNN Platform/Library/Collections/NaiveLockingList.cs index c380bf8f20f..c869481f8bb 100644 --- a/DNN Platform/Library/Collections/NaiveLockingList.cs +++ b/DNN Platform/Library/Collections/NaiveLockingList.cs @@ -1,138 +1,147 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Collections.Internal { + using System; + using System.Collections; + using System.Collections.Generic; + public class NaiveLockingList : IList { private readonly SharedList _list = new SharedList(); - //TODO is no recursion the correct policy - - void DoInReadLock(Action action) - { - DoInReadLock(() =>{ action.Invoke(); return true; }); - } - TRet DoInReadLock(Func func) + /// + /// Gets access to the underlying SharedList. + /// + /// Allows locking to be explicitly managed for the sake of effeciency + /// + /// + public SharedList SharedList { - using (_list.GetReadLock()) + get { - return func.Invoke(); + return this._list; } } - void DoInWriteLock(Action action) + public int Count { - DoInWriteLock(() => { action.Invoke(); return true; }); + get + { + return this.DoInReadLock(() => this._list.Count); + } } - private TRet DoInWriteLock(Func func) + public bool IsReadOnly { - using (_list.GetWriteLock()) + get { - return func.Invoke(); + return false; } } - /// - /// Access to the underlying SharedList - /// - /// Allows locking to be explicitly managed for the sake of effeciency - /// - /// - public SharedList SharedList + public T this[int index] { get { - return _list; + return this.DoInReadLock(() => this._list[index]); + } + + set + { + this.DoInWriteLock(() => this._list[index] = value); } } public IEnumerator GetEnumerator() { - //disposal of enumerator will release read lock - //TODO is there a need for some sort of timed release? the timmer must release from the correct thread - //if using RWLS - var readLock = _list.GetReadLock(); - return new NaiveLockingEnumerator(_list.GetEnumerator(), readLock); + // disposal of enumerator will release read lock + // TODO is there a need for some sort of timed release? the timmer must release from the correct thread + // if using RWLS + var readLock = this._list.GetReadLock(); + return new NaiveLockingEnumerator(this._list.GetEnumerator(), readLock); } IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); + } + + // TODO is no recursion the correct policy + private void DoInReadLock(Action action) + { + this.DoInReadLock(() => + { + action.Invoke(); + return true; + }); } - public void Add(T item) + private TRet DoInReadLock(Func func) { - DoInWriteLock(() => _list.Add(item)); + using (this._list.GetReadLock()) + { + return func.Invoke(); + } } - public void Clear() + private void DoInWriteLock(Action action) { - DoInWriteLock(() => _list.Clear()); + this.DoInWriteLock(() => + { + action.Invoke(); + return true; + }); } - public bool Contains(T item) + private TRet DoInWriteLock(Func func) { - return DoInReadLock(() => _list.Contains(item)); + using (this._list.GetWriteLock()) + { + return func.Invoke(); + } } - public void CopyTo(T[] array, int arrayIndex) + public void Add(T item) { - DoInReadLock(() => _list.CopyTo(array, arrayIndex)); + this.DoInWriteLock(() => this._list.Add(item)); } - public bool Remove(T item) + public void Clear() { - return DoInWriteLock(() => _list.Remove(item)); + this.DoInWriteLock(() => this._list.Clear()); } - public int Count + public bool Contains(T item) { - get - { - return DoInReadLock(() => _list.Count); - } + return this.DoInReadLock(() => this._list.Contains(item)); } - public bool IsReadOnly + public void CopyTo(T[] array, int arrayIndex) { - get - { - return false; - } + this.DoInReadLock(() => this._list.CopyTo(array, arrayIndex)); } - public int IndexOf(T item) + public bool Remove(T item) { - return DoInReadLock(() => _list.IndexOf(item)); + return this.DoInWriteLock(() => this._list.Remove(item)); } - public void Insert(int index, T item) + public int IndexOf(T item) { - DoInWriteLock(() => _list.Insert(index, item)); + return this.DoInReadLock(() => this._list.IndexOf(item)); } - public void RemoveAt(int index) + public void Insert(int index, T item) { - DoInWriteLock(() => _list.RemoveAt(index)); + this.DoInWriteLock(() => this._list.Insert(index, item)); } - public T this[int index] + public void RemoveAt(int index) { - get - { - return DoInReadLock(() => _list[index]); - } - set - { - DoInWriteLock(() => _list[index] = value); - } + this.DoInWriteLock(() => this._list.RemoveAt(index)); } public class NaiveLockingEnumerator : IEnumerator @@ -143,25 +152,20 @@ public class NaiveLockingEnumerator : IEnumerator public NaiveLockingEnumerator(IEnumerator enumerator, ISharedCollectionLock readLock) { - _enumerator = enumerator; - _readLock = readLock; + this._enumerator = enumerator; + this._readLock = readLock; } - public bool MoveNext() - { - return _enumerator.MoveNext(); - } - - public void Reset() + ~NaiveLockingEnumerator() { - _enumerator.Reset(); + this.Dispose(false); } public T Current { get { - return _enumerator.Current; + return this._enumerator.Current; } } @@ -169,37 +173,42 @@ object IEnumerator.Current { get { - return Current; + return this.Current; } } + public bool MoveNext() + { + return this._enumerator.MoveNext(); + } + + public void Reset() + { + this._enumerator.Reset(); + } + public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { - if (!_isDisposed) + if (!this._isDisposed) { if (disposing) { - //dispose managed resrources here - _enumerator.Dispose(); - _readLock.Dispose(); + // dispose managed resrources here + this._enumerator.Dispose(); + this._readLock.Dispose(); } - //dispose unmanaged resrources here - _isDisposed = true; + // dispose unmanaged resrources here + this._isDisposed = true; } } - - ~NaiveLockingEnumerator() - { - Dispose(false); - } } } } diff --git a/DNN Platform/Library/Collections/PagedList.cs b/DNN Platform/Library/Collections/PagedList.cs index 46be0513d6f..b02c345eee0 100644 --- a/DNN Platform/Library/Collections/PagedList.cs +++ b/DNN Platform/Library/Collections/PagedList.cs @@ -1,61 +1,67 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections { + using System; + using System.Collections.Generic; + using System.Linq; + // Taken from Rob Conery's Blog post on the ASP.Net MVC PagedList Helper // http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/ /// - /// Represents a snapshot of a single page of objects from a data store + /// Represents a snapshot of a single page of objects from a data store. /// - /// The type of objects contained in this list + /// The type of objects contained in this list. public class PagedList : List, IPagedList - { - #region Constructors - - /// - /// Initializes a new instance of the a paged list containing objects from the selected enumerable source + { + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the a paged list containing objects from the selected enumerable source. /// - /// The data store containing objects to be retrieved - /// The index of the page to retrieve - /// The size of the page to retrieve + /// The data store containing objects to be retrieved. + /// The index of the page to retrieve. + /// The size of the page to retrieve. public PagedList(IEnumerable source, int pageIndex, int pageSize) { var enumerable = source as T[] ?? source.ToArray(); - CommonConstruct(enumerable.Skip(pageIndex * pageSize).Take(pageSize).ToList(), enumerable.Count(), pageIndex, pageSize); - } - - /// - /// Initializes a new instance of the a paged list containing objects from the selected enumerable source + this.CommonConstruct(enumerable.Skip(pageIndex * pageSize).Take(pageSize).ToList(), enumerable.Count(), pageIndex, pageSize); + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the a paged list containing objects from the selected enumerable source. /// - /// The items that constitute the page - /// The total number of items in the original source - /// The index of the page to retrieve - /// The size of the page to retrieve + /// The items that constitute the page. + /// The total number of items in the original source. + /// The index of the page to retrieve. + /// The size of the page to retrieve. public PagedList(IEnumerable items, int totalCount, int pageIndex, int pageSize) { - CommonConstruct(items, totalCount, pageIndex, pageSize); - } - - #endregion + this.CommonConstruct(items, totalCount, pageIndex, pageSize); + } + + /// + /// Gets a value indicating whether gets a boolean indicating if there is a next page available. + /// + public bool HasNextPage { get; private set; } - #region Private Methods + /// + /// Gets a value indicating whether gets a boolean indicating if there is a previous page available. + /// + public bool HasPreviousPage { get; private set; } + /// + /// Gets a value indicating whether gets a boolean indicating if this is the first page. + /// + public bool IsFirstPage { get; private set; } + private void CommonConstruct(IEnumerable items, int totalCount, int pageIndex, int pageSize) { - PageCount = (int)Math.Ceiling(totalCount / (double)pageSize); + this.PageCount = (int)Math.Ceiling(totalCount / (double)pageSize); - if (PageCount == 0) + if (this.PageCount == 0) { if (pageIndex > 0) { @@ -68,66 +74,47 @@ private void CommonConstruct(IEnumerable items, int totalCount, int pageIndex { throw new IndexOutOfRangeException("Index cannot be negative"); } - if (pageIndex >= PageCount) + + if (pageIndex >= this.PageCount) { throw new IndexOutOfRangeException("Invalid Page Index"); } } - TotalCount = totalCount; - PageSize = pageSize; - PageIndex = pageIndex; - AddRange(items); - - HasNextPage = (PageIndex < (PageCount - 1)); - HasPreviousPage = (PageIndex > 0); - IsFirstPage = (PageIndex <= 0); - IsLastPage = (PageIndex >= (PageCount - 1)); - } - - #endregion - - #region IPagedList Members - - /// - /// Gets a boolean indicating if there is a next page available - /// - public bool HasNextPage { get; private set; } - - /// - /// Gets a boolean indicating if there is a previous page available - /// - public bool HasPreviousPage { get; private set; } - - /// - /// Gets a boolean indicating if this is the first page - /// - public bool IsFirstPage { get; private set; } + + this.TotalCount = totalCount; + this.PageSize = pageSize; + this.PageIndex = pageIndex; + this.AddRange(items); + + this.HasNextPage = this.PageIndex < (this.PageCount - 1); + this.HasPreviousPage = this.PageIndex > 0; + this.IsFirstPage = this.PageIndex <= 0; + this.IsLastPage = this.PageIndex >= (this.PageCount - 1); + } /// - /// Gets a boolean indicating if this is the last page + /// Gets a value indicating whether gets a boolean indicating if this is the last page. /// public bool IsLastPage { get; private set; } /// - /// Gets or sets the number of pages in this list + /// Gets or sets the number of pages in this list. /// public int PageCount { get; set; } /// - /// Gets or sets the index of the page contained in this list + /// Gets or sets the index of the page contained in this list. /// public int PageIndex { get; set; } /// - /// Gets or sets the size of the page in this list + /// Gets or sets the size of the page in this list. /// public int PageSize { get; set; } /// - /// Gets or ses the total number of objects in the data store + /// Gets or sets or ses the total number of objects in the data store. /// - public int TotalCount { get; set; } - - #endregion + public int TotalCount { get; set; } } } diff --git a/DNN Platform/Library/Collections/PagedSelector.cs b/DNN Platform/Library/Collections/PagedSelector.cs index 92b1c756ff7..ec69fab021d 100644 --- a/DNN Platform/Library/Collections/PagedSelector.cs +++ b/DNN Platform/Library/Collections/PagedSelector.cs @@ -1,53 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Collections { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + /// - /// Provides options to allow the consumer to select a page of data from a paged data store + /// Provides options to allow the consumer to select a page of data from a paged data store. /// - /// The type of object in the data store + /// The type of object in the data store. public class PageSelector { private readonly int _pageSize; - private readonly IEnumerable _source; - - #region Constructors - - /// - /// Initializes a new instance of the for use on the specified data store + private readonly IEnumerable _source; + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the for use on the specified data store. /// - /// The data store to page - /// The size of each page + /// The data store to page. + /// The size of each page. public PageSelector(IEnumerable source, int pageSize) { - _source = source; - _pageSize = pageSize; - } - - #endregion - - #region Public Methods - + this._source = source; + this._pageSize = pageSize; + } + /// - /// Retrieves the specified page as a + /// Retrieves the specified page as a . /// - /// The index (zero-based) of the page to retrieve + /// The index (zero-based) of the page to retrieve. /// - /// An containing the page of data, or an - /// empty list if the page does not exist + /// An containing the page of data, or an + /// empty list if the page does not exist. /// public IPagedList GetPage(int pageIndex) { - return new PagedList(_source, pageIndex, _pageSize); - } - - #endregion + return new PagedList(this._source, pageIndex, this._pageSize); + } } } diff --git a/DNN Platform/Library/Collections/PagingExtensions.cs b/DNN Platform/Library/Collections/PagingExtensions.cs index 1be85b40c4a..20ee86d2e39 100644 --- a/DNN Platform/Library/Collections/PagingExtensions.cs +++ b/DNN Platform/Library/Collections/PagingExtensions.cs @@ -1,28 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections { + using System.Collections.Generic; + /// - /// Contains filters that can be applied to stores + /// Contains filters that can be applied to stores. /// public static class PagingExtensions - { - #region Public Extension Methods - + { /// /// Filters the incoming store to retrieve pages of a specified size. /// - /// The type of the object being filtered - /// The source object being filtered - /// The page size to use + /// The type of the object being filtered. + /// The source object being filtered. + /// The page size to use. /// /// A object that is used to select a single /// page of data from the data source. @@ -33,19 +26,17 @@ public static PageSelector InPagesOf(this IEnumerable source, int pageS } /// - /// Converts an into an + /// Converts an into an . /// - /// The type of the items in the - /// The source to convert - /// The page index requested - /// The page size requested - /// A object that is used to select a single - /// page of data from the data source + /// The type of the items in the . + /// The source to convert. + /// The page index requested. + /// The page size requested. + /// A object that is used to select a single + /// page of data from the data source. public static IPagedList ToPagedList(this IEnumerable source, int pageIndex, int pageSize) { return new PagedList(source, pageIndex, pageSize); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Collections/ReadLockRequiredException.cs b/DNN Platform/Library/Collections/ReadLockRequiredException.cs index d49b26f6826..2bed480d2a6 100644 --- a/DNN Platform/Library/Collections/ReadLockRequiredException.cs +++ b/DNN Platform/Library/Collections/ReadLockRequiredException.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + public class ReadLockRequiredException : Exception { } diff --git a/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs b/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs index 5a8e2d699c1..fb70a956453 100644 --- a/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs +++ b/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; -using System.Threading; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Collections.Internal { + using System; + using System.Runtime.Serialization; + using System.Threading; + [Serializable] public class ReaderWriterLockStrategy : IDisposable, ILockStrategy { @@ -15,55 +15,87 @@ public class ReaderWriterLockStrategy : IDisposable, ILockStrategy private ReaderWriterLockSlim _lock; private LockRecursionPolicy _lockRecursionPolicy; + + private bool _isDisposed; + + public ReaderWriterLockStrategy() + : this(LockRecursionPolicy.NoRecursion) + { + } + + public ReaderWriterLockStrategy(LockRecursionPolicy recursionPolicy) + { + this._lockRecursionPolicy = recursionPolicy; + this._lock = new ReaderWriterLockSlim(recursionPolicy); + } + + // The special constructor is used to deserialize values. + public ReaderWriterLockStrategy(SerializationInfo info, StreamingContext context) + { + this._lockRecursionPolicy = (LockRecursionPolicy)info.GetValue("_lockRecursionPolicy", typeof(LockRecursionPolicy)); + this._lock = new ReaderWriterLockSlim(this._lockRecursionPolicy); + } private ReaderWriterLockSlim Lock { get { - return _lock ?? (_lock = new ReaderWriterLockSlim(_lockRecursionPolicy)); + return this._lock ?? (this._lock = new ReaderWriterLockSlim(this._lockRecursionPolicy)); } } - // Implement this method to serialize data. The method is called + // Implement this method to serialize data. The method is called // on serialization. public void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. - info.AddValue("_lockRecursionPolicy", _lockRecursionPolicy, typeof(LockRecursionPolicy)); + info.AddValue("_lockRecursionPolicy", this._lockRecursionPolicy, typeof(LockRecursionPolicy)); } - public ReaderWriterLockStrategy() - : this(LockRecursionPolicy.NoRecursion) + ~ReaderWriterLockStrategy() { - } + // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. + this.Dispose(false); + } - public ReaderWriterLockStrategy(LockRecursionPolicy recursionPolicy) + public bool ThreadCanRead { - _lockRecursionPolicy = recursionPolicy; - _lock = new ReaderWriterLockSlim(recursionPolicy); + get + { + this.EnsureNotDisposed(); + return this.Lock.IsReadLockHeld || this.Lock.IsWriteLockHeld; + } } - // The special constructor is used to deserialize values. - public ReaderWriterLockStrategy(SerializationInfo info, StreamingContext context) + public bool ThreadCanWrite { - _lockRecursionPolicy = (LockRecursionPolicy)info.GetValue("_lockRecursionPolicy", typeof(LockRecursionPolicy)); - _lock = new ReaderWriterLockSlim(_lockRecursionPolicy); + get + { + this.EnsureNotDisposed(); + return this.Lock.IsWriteLockHeld; + } } - #region ILockStrategy Members - + public bool SupportsConcurrentReads + { + get + { + return true; + } + } + public ISharedCollectionLock GetReadLock() { - return GetReadLock(TimeSpan.FromMilliseconds(-1)); + return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); } public ISharedCollectionLock GetReadLock(TimeSpan timeout) { - EnsureNotDisposed(); - if (Lock.RecursionPolicy == LockRecursionPolicy.NoRecursion && Lock.IsReadLockHeld || - Lock.TryEnterReadLock(timeout)) + this.EnsureNotDisposed(); + if ((this.Lock.RecursionPolicy == LockRecursionPolicy.NoRecursion && this.Lock.IsReadLockHeld) || + this.Lock.TryEnterReadLock(timeout)) { - return new ReaderWriterSlimLock(Lock); + return new ReaderWriterSlimLock(this.Lock); } else { @@ -73,16 +105,16 @@ public ISharedCollectionLock GetReadLock(TimeSpan timeout) public ISharedCollectionLock GetWriteLock() { - return GetWriteLock(TimeSpan.FromMilliseconds(-1)); + return this.GetWriteLock(TimeSpan.FromMilliseconds(-1)); } public ISharedCollectionLock GetWriteLock(TimeSpan timeout) { - EnsureNotDisposed(); - if (Lock.RecursionPolicy == LockRecursionPolicy.NoRecursion && Lock.IsWriteLockHeld || - Lock.TryEnterWriteLock(timeout)) + this.EnsureNotDisposed(); + if ((this.Lock.RecursionPolicy == LockRecursionPolicy.NoRecursion && this.Lock.IsWriteLockHeld) || + this.Lock.TryEnterWriteLock(timeout)) { - return new ReaderWriterSlimLock(Lock); + return new ReaderWriterSlimLock(this.Lock); } else { @@ -90,82 +122,43 @@ public ISharedCollectionLock GetWriteLock(TimeSpan timeout) } } - public bool ThreadCanRead - { - get - { - EnsureNotDisposed(); - return Lock.IsReadLockHeld || Lock.IsWriteLockHeld; - } - } - - public bool ThreadCanWrite - { - get - { - EnsureNotDisposed(); - return Lock.IsWriteLockHeld; - } - } - - public bool SupportsConcurrentReads - { - get - { - return true; - } - } - - #endregion - - #region "IDisposable Support" - - private bool _isDisposed; - public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } - private void EnsureNotDisposed() - { - if (_isDisposed) - { - throw new ObjectDisposedException("ReaderWriterLockStrategy"); - } - } - // To detect redundant calls // IDisposable protected virtual void Dispose(bool disposing) { - if (!_isDisposed) + if (!this._isDisposed) { if (disposing) { - //dispose managed state (managed objects). + // dispose managed state (managed objects). } - if (_lock != null) + if (this._lock != null) { - _lock.Dispose(); - _lock = null; + this._lock.Dispose(); + this._lock = null; } } - _isDisposed = true; + + this._isDisposed = true; } - ~ReaderWriterLockStrategy() + private void EnsureNotDisposed() { - // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. - Dispose(false); + if (this._isDisposed) + { + throw new ObjectDisposedException("ReaderWriterLockStrategy"); + } } - - // This code added by Visual Basic to correctly implement the disposable pattern. - - #endregion + + // This code added by Visual Basic to correctly implement the disposable pattern. } } diff --git a/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs b/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs index 3a5e57976bc..a1c9d1fbcb9 100644 --- a/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs +++ b/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Threading; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + using System.Threading; + internal class ReaderWriterSlimLock : ISharedCollectionLock { private bool _disposed; @@ -18,59 +13,55 @@ internal class ReaderWriterSlimLock : ISharedCollectionLock public ReaderWriterSlimLock(ReaderWriterLockSlim @lock) { - _lock = @lock; - } - - #region ISharedCollectionLock Members + this._lock = @lock; + } + ~ReaderWriterSlimLock() + { + this.Dispose(false); + } + public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); - } - - #endregion - - private void EnsureNotDisposed() - { - if (_disposed) - { - throw new ObjectDisposedException("ReaderWriterSlimLock"); - } - } + } protected virtual void Dispose(bool disposing) { - if (!_disposed) + if (!this._disposed) { if (disposing) { - //free managed resources here + // free managed resources here } - //free unmanaged resrources here - if (_lock.IsReadLockHeld) + // free unmanaged resrources here + if (this._lock.IsReadLockHeld) { - _lock.ExitReadLock(); + this._lock.ExitReadLock(); } - else if (_lock.IsWriteLockHeld) + else if (this._lock.IsWriteLockHeld) { - _lock.ExitWriteLock(); + this._lock.ExitWriteLock(); } - else if (_lock.IsUpgradeableReadLockHeld) + else if (this._lock.IsUpgradeableReadLockHeld) { - _lock.ExitUpgradeableReadLock(); + this._lock.ExitUpgradeableReadLock(); } - _lock = null; - _disposed = true; + this._lock = null; + this._disposed = true; } } - - ~ReaderWriterSlimLock() + + private void EnsureNotDisposed() { - Dispose(false); + if (this._disposed) + { + throw new ObjectDisposedException("ReaderWriterSlimLock"); + } } } } diff --git a/DNN Platform/Library/Collections/SharedDictionary.cs b/DNN Platform/Library/Collections/SharedDictionary.cs index ecde97521ee..8981a89431e 100644 --- a/DNN Platform/Library/Collections/SharedDictionary.cs +++ b/DNN Platform/Library/Collections/SharedDictionary.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + using System.Collections; + using System.Collections.Generic; + [Serializable] public class SharedDictionary : IDictionary, IDisposable { @@ -20,208 +15,233 @@ public class SharedDictionary : IDictionary, IDispos private bool _isDisposed; private ILockStrategy _lockController; - public SharedDictionary() : this(LockingStrategy.ReaderWriter) + public SharedDictionary() + : this(LockingStrategy.ReaderWriter) { } public SharedDictionary(ILockStrategy lockStrategy) { - _dict = new Dictionary(); - _lockController = lockStrategy; + this._dict = new Dictionary(); + this._lockController = lockStrategy; } - public SharedDictionary(LockingStrategy strategy) : this(LockingStrategyFactory.Create(strategy)) + public SharedDictionary(LockingStrategy strategy) + : this(LockingStrategyFactory.Create(strategy)) { } - internal IDictionary BackingDictionary + ~SharedDictionary() + { + this.Dispose(false); + } + + public int Count { get { - return _dict; + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.Count; } } - #region IDictionary Members + public bool IsReadOnly + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.IsReadOnly; + } + } + + public ICollection Keys + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.Keys; + } + } + internal IDictionary BackingDictionary + { + get + { + return this._dict; + } + } + IEnumerator> IEnumerable>.GetEnumerator() { - return IEnumerable_GetEnumerator(); + return this.IEnumerable_GetEnumerator(); } public IEnumerator GetEnumerator() { - return IEnumerable_GetEnumerator(); + return this.IEnumerable_GetEnumerator(); } public void Add(KeyValuePair item) { - EnsureNotDisposed(); - EnsureWriteAccess(); - _dict.Add(item); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._dict.Add(item); } public void Clear() { - EnsureNotDisposed(); - EnsureWriteAccess(); - _dict.Clear(); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._dict.Clear(); } public bool Contains(KeyValuePair item) { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict.Contains(item); + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.Contains(item); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { - EnsureNotDisposed(); - EnsureReadAccess(); - _dict.CopyTo(array, arrayIndex); + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + this._dict.CopyTo(array, arrayIndex); } public bool Remove(KeyValuePair item) { - EnsureNotDisposed(); - EnsureWriteAccess(); - return _dict.Remove(item); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + return this._dict.Remove(item); } - public int Count + public ICollection Values { get { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict.Count; + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.Values; } - } + } - public bool IsReadOnly + public TValue this[TKey key] { get { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict.IsReadOnly; + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict[key]; + } + + set + { + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._dict[key] = value; } } public bool ContainsKey(TKey key) { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict.ContainsKey(key); + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.ContainsKey(key); } public void Add(TKey key, TValue value) { - EnsureNotDisposed(); - EnsureWriteAccess(); - _dict.Add(key, value); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._dict.Add(key, value); } public bool Remove(TKey key) { - EnsureNotDisposed(); - EnsureWriteAccess(); - return _dict.Remove(key); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + return this._dict.Remove(key); } public bool TryGetValue(TKey key, out TValue value) { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict.TryGetValue(key, out value); - } - - public TValue this[TKey key] - { - get - { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict[key]; - } - set - { - EnsureNotDisposed(); - EnsureWriteAccess(); - _dict[key] = value; - } + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.TryGetValue(key, out value); } - - public ICollection Keys - { - get - { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict.Keys; - } - } - - public ICollection Values - { - get - { - EnsureNotDisposed(); - EnsureReadAccess(); - return _dict.Values; - } - } - - #endregion - - #region IDisposable Members - + public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); - } - - #endregion - + } + public ISharedCollectionLock GetReadLock() { - return GetReadLock(TimeSpan.FromMilliseconds(-1)); + return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); } public ISharedCollectionLock GetReadLock(TimeSpan timeOut) { - EnsureNotDisposed(); - return _lockController.GetReadLock(timeOut); + this.EnsureNotDisposed(); + return this._lockController.GetReadLock(timeOut); } public ISharedCollectionLock GetReadLock(int millisecondTimeout) { - return GetReadLock(TimeSpan.FromMilliseconds(millisecondTimeout)); + return this.GetReadLock(TimeSpan.FromMilliseconds(millisecondTimeout)); } public ISharedCollectionLock GetWriteLock() { - return GetWriteLock(TimeSpan.FromMilliseconds(-1)); + return this.GetWriteLock(TimeSpan.FromMilliseconds(-1)); } public ISharedCollectionLock GetWriteLock(TimeSpan timeOut) { - EnsureNotDisposed(); - return _lockController.GetWriteLock(timeOut); + this.EnsureNotDisposed(); + return this._lockController.GetWriteLock(timeOut); } public ISharedCollectionLock GetWriteLock(int millisecondTimeout) { - return GetWriteLock(TimeSpan.FromMilliseconds(millisecondTimeout)); + return this.GetWriteLock(TimeSpan.FromMilliseconds(millisecondTimeout)); + } + + public IEnumerator> IEnumerable_GetEnumerator() + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + + // todo nothing ensures read lock is held for life of enumerator + return this._dict.GetEnumerator(); } + protected virtual void Dispose(bool disposing) + { + if (!this._isDisposed) + { + if (disposing) + { + // dispose managed resrources here + this._dict = null; + } + // dispose unmanaged resrources here + this._lockController.Dispose(); + this._lockController = null; + this._isDisposed = true; + } + } + private void EnsureReadAccess() { - if (!(_lockController.ThreadCanRead)) + if (!this._lockController.ThreadCanRead) { throw new ReadLockRequiredException(); } @@ -229,49 +249,18 @@ private void EnsureReadAccess() private void EnsureWriteAccess() { - if (!_lockController.ThreadCanWrite) + if (!this._lockController.ThreadCanWrite) { throw new WriteLockRequiredException(); } } - public IEnumerator> IEnumerable_GetEnumerator() - { - EnsureNotDisposed(); - EnsureReadAccess(); - - //todo nothing ensures read lock is held for life of enumerator - return _dict.GetEnumerator(); - } - private void EnsureNotDisposed() { - if (_isDisposed) + if (this._isDisposed) { throw new ObjectDisposedException("SharedDictionary"); } } - - protected virtual void Dispose(bool disposing) - { - if (!_isDisposed) - { - if (disposing) - { - //dispose managed resrources here - _dict = null; - } - - //dispose unmanaged resrources here - _lockController.Dispose(); - _lockController = null; - _isDisposed = true; - } - } - - ~SharedDictionary() - { - Dispose(false); - } } } diff --git a/DNN Platform/Library/Collections/SharedList.cs b/DNN Platform/Library/Collections/SharedList.cs index 5c4871e155f..9bed4fa0cfd 100644 --- a/DNN Platform/Library/Collections/SharedList.cs +++ b/DNN Platform/Library/Collections/SharedList.cs @@ -1,229 +1,224 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + using System.Collections; + using System.Collections.Generic; + public class SharedList : IList, IDisposable { private readonly List _list = new List(); private ILockStrategy _lockStrategy; + + private bool _isDisposed; - public SharedList() : this(LockingStrategy.ReaderWriter) + public SharedList() + : this(LockingStrategy.ReaderWriter) { } public SharedList(ILockStrategy lockStrategy) { - _lockStrategy = lockStrategy; + this._lockStrategy = lockStrategy; } - public SharedList(LockingStrategy strategy) : this(LockingStrategyFactory.Create(strategy)) + public SharedList(LockingStrategy strategy) + : this(LockingStrategyFactory.Create(strategy)) { } - internal IList BackingList + ~SharedList() + { + this.Dispose(false); + } + + public int Count { get { - return _list; + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._list.Count; } } - #region IList Members - - public void Add(T item) + public bool IsReadOnly { - EnsureNotDisposed(); - EnsureWriteAccess(); - _list.Add(item); + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return ((ICollection)this._list).IsReadOnly; + } } - public void Clear() + internal IList BackingList { - EnsureNotDisposed(); - EnsureWriteAccess(); - _list.Clear(); - } + get + { + return this._list; + } + } - public bool Contains(T item) + public T this[int index] { - EnsureNotDisposed(); - EnsureReadAccess(); - return _list.Contains(item); + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._list[index]; + } + + set + { + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._list[index] = value; + } + } + + public void Add(T item) + { + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._list.Add(item); } - public void CopyTo(T[] array, int arrayIndex) + public void Clear() { - EnsureNotDisposed(); - EnsureReadAccess(); - _list.CopyTo(array, arrayIndex); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._list.Clear(); } - public int Count + public bool Contains(T item) { - get - { - EnsureNotDisposed(); - EnsureReadAccess(); - return _list.Count; - } + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._list.Contains(item); } - public bool IsReadOnly + public void CopyTo(T[] array, int arrayIndex) { - get - { - EnsureNotDisposed(); - EnsureReadAccess(); - return ((ICollection) _list).IsReadOnly; - } + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + this._list.CopyTo(array, arrayIndex); } public bool Remove(T item) { - EnsureNotDisposed(); - EnsureWriteAccess(); - return _list.Remove(item); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + return this._list.Remove(item); } public IEnumerator GetEnumerator() { - EnsureNotDisposed(); - EnsureReadAccess(); - return _list.GetEnumerator(); + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._list.GetEnumerator(); } public int IndexOf(T item) { - EnsureNotDisposed(); - EnsureReadAccess(); - return _list.IndexOf(item); + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._list.IndexOf(item); } public void Insert(int index, T item) { - EnsureNotDisposed(); - EnsureWriteAccess(); - _list.Insert(index, item); - } - - public T this[int index] - { - get - { - EnsureNotDisposed(); - EnsureReadAccess(); - return _list[index]; - } - set - { - EnsureNotDisposed(); - EnsureWriteAccess(); - _list[index] = value; - } + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._list.Insert(index, item); } public void RemoveAt(int index) { - EnsureNotDisposed(); - EnsureWriteAccess(); - _list.RemoveAt(index); + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._list.RemoveAt(index); } IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator1(); - } - - #endregion - - #region "IDisposable Support" - - private bool _isDisposed; + return this.GetEnumerator1(); + } public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } // To detect redundant calls - public void EnsureNotDisposed() { - if (_isDisposed) + if (this._isDisposed) { throw new ObjectDisposedException("SharedList"); } } + + public ISharedCollectionLock GetReadLock() + { + return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); + } + + public ISharedCollectionLock GetReadLock(TimeSpan timeOut) + { + this.EnsureNotDisposed(); + return this._lockStrategy.GetReadLock(timeOut); + } // IDisposable protected virtual void Dispose(bool disposing) { - if (!_isDisposed) + if (!this._isDisposed) { if (disposing) { // dispose managed state (managed objects). } - _lockStrategy.Dispose(); - _lockStrategy = null; + this._lockStrategy.Dispose(); + this._lockStrategy = null; } - _isDisposed = true; - } - - ~SharedList() - { - Dispose(false); - } - - #endregion - - public ISharedCollectionLock GetReadLock() - { - return GetReadLock(TimeSpan.FromMilliseconds(-1)); - } - - public ISharedCollectionLock GetReadLock(TimeSpan timeOut) - { - EnsureNotDisposed(); - return _lockStrategy.GetReadLock(timeOut); + + this._isDisposed = true; } public ISharedCollectionLock GetReadLock(int millisecondTimeout) { - return GetReadLock(TimeSpan.FromMilliseconds(millisecondTimeout)); + return this.GetReadLock(TimeSpan.FromMilliseconds(millisecondTimeout)); } public ISharedCollectionLock GetWriteLock() { - return GetWriteLock(TimeSpan.FromMilliseconds(-1)); + return this.GetWriteLock(TimeSpan.FromMilliseconds(-1)); } public ISharedCollectionLock GetWriteLock(TimeSpan timeOut) { - EnsureNotDisposed(); - return _lockStrategy.GetWriteLock(timeOut); + this.EnsureNotDisposed(); + return this._lockStrategy.GetWriteLock(timeOut); } public ISharedCollectionLock GetWriteLock(int millisecondTimeout) { - return GetWriteLock(TimeSpan.FromMilliseconds(millisecondTimeout)); + return this.GetWriteLock(TimeSpan.FromMilliseconds(millisecondTimeout)); + } + + public IEnumerator GetEnumerator1() + { + return this.GetEnumerator(); } private void EnsureReadAccess() { - if (!(_lockStrategy.ThreadCanRead)) + if (!this._lockStrategy.ThreadCanRead) { throw new ReadLockRequiredException(); } @@ -231,15 +226,10 @@ private void EnsureReadAccess() private void EnsureWriteAccess() { - if (!_lockStrategy.ThreadCanWrite) + if (!this._lockStrategy.ThreadCanWrite) { throw new WriteLockRequiredException(); } } - - public IEnumerator GetEnumerator1() - { - return GetEnumerator(); - } } } diff --git a/DNN Platform/Library/Collections/WriteLockRequiredException.cs b/DNN Platform/Library/Collections/WriteLockRequiredException.cs index ef9e817ef94..a5cd2de5a95 100644 --- a/DNN Platform/Library/Collections/WriteLockRequiredException.cs +++ b/DNN Platform/Library/Collections/WriteLockRequiredException.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Collections.Internal { + using System; + public class WriteLockRequiredException : Exception { } diff --git a/DNN Platform/Library/Common/Controls/ActionLessForm.cs b/DNN Platform/Library/Common/Controls/ActionLessForm.cs index 1af2f9f1b9e..cd54401c381 100644 --- a/DNN Platform/Library/Common/Controls/ActionLessForm.cs +++ b/DNN Platform/Library/Common/Controls/ActionLessForm.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Controls { - /// - /// The Form will reset action to raw url instead of rewrite url. - /// + using System.IO; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + + /// + /// The Form will reset action to raw url instead of rewrite url. + /// public class Form : HtmlForm { protected override void RenderAttributes(HtmlTextWriter writer) @@ -24,6 +19,7 @@ protected override void RenderAttributes(HtmlTextWriter writer) var htmlWriter = new HtmlTextWriter(stringWriter); base.RenderAttributes(htmlWriter); string html = stringWriter.ToString(); + // Locate and replace action attribute int StartPoint = html.IndexOf("action=\""); if (StartPoint >= 0) @@ -32,17 +28,19 @@ protected override void RenderAttributes(HtmlTextWriter writer) html = html.Remove(StartPoint, EndPoint - StartPoint); html = html.Insert(StartPoint, "action=\"" + HttpUtility.HtmlEncode(HttpContext.Current.Request.RawUrl) + "\""); } - if (base.ID != null) - { - // Locate and replace id attribute + + if (this.ID != null) + { + // Locate and replace id attribute StartPoint = html.IndexOf("id=\""); if (StartPoint >= 0) { int EndPoint = html.IndexOf("\"", StartPoint + 4) + 1; html = html.Remove(StartPoint, EndPoint - StartPoint); - html = html.Insert(StartPoint, "id=\"" + base.ClientID + "\""); + html = html.Insert(StartPoint, "id=\"" + this.ClientID + "\""); } } + writer.Write(html); } } diff --git a/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs b/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs index 58cd7973c28..546d084f0d6 100644 --- a/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs +++ b/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs @@ -1,8 +1,13 @@ -using System.Web; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Extensions { + using System.Web; + + using Microsoft.Extensions.DependencyInjection; + public static class HttpContextDependencyInjectionExtensions { public static void SetScope(this HttpContextBase httpContext, IServiceScope scope) @@ -32,9 +37,11 @@ public static IServiceScope GetScope(this HttpContext httpContext) internal static IServiceScope GetScope(System.Collections.IDictionary contextItems) { - if (!contextItems.Contains(typeof(IServiceScope))) - return null; - + if (!contextItems.Contains(typeof(IServiceScope))) + { + return null; + } + return contextItems[typeof(IServiceScope)] is IServiceScope scope ? scope : null; } } diff --git a/DNN Platform/Library/Common/FileItem.cs b/DNN Platform/Library/Common/FileItem.cs index 7da1000c98a..42675c32429 100644 --- a/DNN Platform/Library/Common/FileItem.cs +++ b/DNN Platform/Library/Common/FileItem.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common { /// - /// This class handles basic elements about File Items. Is is a basic Get/Set for Value and Text + /// This class handles basic elements about File Items. Is is a basic Get/Set for Value and Text. /// public class FileItem { @@ -16,8 +16,8 @@ public class FileItem /// The text. public FileItem(string value, string text) { - Value = value; - Text = text; + this.Value = value; + this.Text = text; } /// diff --git a/DNN Platform/Library/Common/Globals.cs b/DNN Platform/Library/Common/Globals.cs index f2f6358a697..fb1f495d536 100644 --- a/DNN Platform/Library/Common/Globals.cs +++ b/DNN Platform/Library/Common/Globals.cs @@ -1,79 +1,93 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Runtime.InteropServices; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using System.Web.Caching; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Xml; -using DotNetNuke.Abstractions; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Application; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Upgrade; -using DotNetNuke.Services.Url.FriendlyUrl; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.Utilities; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.VisualBasic.CompilerServices; - -using DataCache = DotNetNuke.UI.Utilities.DataCache; -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net; + using System.Runtime.InteropServices; + using System.Runtime.Serialization.Formatters.Binary; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Web.Caching; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Application; + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Upgrade; + using DotNetNuke.Services.Url.FriendlyUrl; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.Utilities; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.VisualBasic.CompilerServices; + + using DataCache = DotNetNuke.UI.Utilities.DataCache; + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + /// /// The global instance of DotNetNuke. all basic functions and properties are defined in this instance. /// [StandardModule] public sealed class Globals { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Globals)); + /// + /// Global role id for all users. + /// + /// -1. + public const string glbRoleAllUsers = "-1"; + + /// + /// Global role id for super user. + /// + /// -2. + public const string glbRoleSuperUser = "-2"; + + /// + /// Global role id for unauthenticated users. + /// + /// -3. + public const string glbRoleUnauthUser = "-3"; public static readonly Regex EmailValidatorRegex = new Regex(glbEmailRegEx, RegexOptions.Compiled); public static readonly Regex NonAlphanumericCharacters = new Regex("[^A-Za-z0-9]", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Globals)); public static readonly Regex InvalidCharacters = new Regex("[^A-Za-z0-9_-]", RegexOptions.Compiled | RegexOptions.CultureInvariant); public static readonly Regex InvalidInitialCharacters = new Regex("^[^A-Za-z]", RegexOptions.Compiled | RegexOptions.CultureInvariant); public static readonly Regex NumberMatchRegex = new Regex(@"^\d+$", RegexOptions.Compiled); @@ -84,8 +98,6 @@ public sealed class Globals public static readonly Regex ServicesFrameworkRegex = new Regex("/API/|DESKTOPMODULES/.+/API/", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); public static readonly string USERNAME_UNALLOWED_ASCII = "!\"#$%&'()*+,/:;<=>?[\\]^`{|}"; - #region PerformanceSettings enum - /// /// Enumeration of site performance setting, say by another way that means how to set the cache. /// @@ -97,7 +109,7 @@ public sealed class Globals /// update cache immediately after the data changed. /// default cache policy in core api will use cache timeout muitple Host Performance setting's value as cache time(unit: minutes): /// - /// HostSettingsCacheTimeOut: 20 + /// HostSettingsCacheTimeOut: 20 /// PortalAliasCacheTimeOut: 200 /// PortalSettingsCacheTimeOut: 20 /// More cache timeout definitions see @@ -109,24 +121,23 @@ public enum PerformanceSettings /// No Caching /// NoCaching = 0, + /// /// Caching for a short time /// LightCaching = 1, + /// /// Caching for moderate /// ModerateCaching = 3, + /// /// Caching for a long time /// - HeavyCaching = 6 + HeavyCaching = 6, } - #endregion - - #region PortalRegistrationType enum - /// /// Enumeration Of Registration Type for portal. /// @@ -147,24 +158,23 @@ public enum PortalRegistrationType /// Disabled Registration /// NoRegistration = 0, + /// /// Account need be approved by portal's administrator. /// PrivateRegistration = 1, + /// /// Account will be available after post registration data successful. /// PublicRegistration = 2, + /// /// Account will be available by verify code. /// - VerifiedRegistration = 3 + VerifiedRegistration = 3, } - #endregion - - #region UpgradeStatus enum - /// /// Enumeration Of Application upgrade status. /// @@ -174,159 +184,144 @@ public enum UpgradeStatus /// The application need update to a higher version. /// Upgrade, + /// /// The application need to install itself. /// Install, + /// /// The application is normal running. /// None, + /// /// The application occur error when running. /// Error, + /// /// The application status is unknown, /// /// This status should never be returned. its is only used as a flag that Status hasn't been determined. - Unknown + Unknown, } - #endregion - /// - /// Global role id for all users + /// Global role id by default. /// - /// -1 - public const string glbRoleAllUsers = "-1"; - - /// - /// Global role id for super user - /// - /// -2 - public const string glbRoleSuperUser = "-2"; - - /// - /// Global role id for unauthenticated users - /// - /// -3 - public const string glbRoleUnauthUser = "-3"; - - /// - /// Global role id by default - /// - /// -4 + /// -4. public const string glbRoleNothing = "-4"; /// - /// Global role name for all users + /// Global role name for all users. /// - /// All Users + /// All Users. public const string glbRoleAllUsersName = "All Users"; /// - /// Global ro name for super user + /// Global ro name for super user. /// - /// Superuser + /// Superuser. public const string glbRoleSuperUserName = "Superuser"; /// - /// Global role name for unauthenticated users + /// Global role name for unauthenticated users. /// - /// Unauthenticated Users + /// Unauthenticated Users. public const string glbRoleUnauthUserName = "Unauthenticated Users"; /// - /// Default page name + /// Default page name. /// - /// Default.aspx + /// Default.aspx. public const string glbDefaultPage = "Default.aspx"; /// - /// Default host skin folder + /// Default host skin folder. /// - /// _default + /// _default. public const string glbHostSkinFolder = "_default"; /// - /// Default control panel + /// Default control panel. /// - /// Admin/ControlPanel/IconBar.ascx + /// Admin/ControlPanel/IconBar.ascx. public const string glbDefaultControlPanel = "Admin/ControlPanel/IconBar.ascx"; /// - /// Default setting to determine if selected control panel is loaded to evaluate visibility + /// Default setting to determine if selected control panel is loaded to evaluate visibility. /// - /// false + /// false. public const bool glbAllowControlPanelToDetermineVisibility = false; /// - /// Default pane name + /// Default pane name. /// - /// ContentPane + /// ContentPane. public const string glbDefaultPane = "ContentPane"; /// - /// Config files folder + /// Config files folder. /// - /// \Config\ + /// \Config\. public const string glbConfigFolder = "\\Config\\"; /// - /// About page name + /// About page name. /// - /// about.htm + /// about.htm. public const string glbAboutPage = "about.htm"; /// - /// DotNetNuke config file + /// DotNetNuke config file. /// - /// DotNetNuke.config + /// DotNetNuke.config. public const string glbDotNetNukeConfig = "DotNetNuke.config"; /// - /// Default portal id for super user + /// Default portal id for super user. /// - /// -1 + /// -1. public const int glbSuperUserAppName = -1; /// - /// extension of protected files + /// extension of protected files. /// - /// .resources + /// .resources. public const string glbProtectedExtension = ".resources"; /// - /// Default container folder + /// Default container folder. /// - /// Portals/_default/Containers/ + /// Portals/_default/Containers/. public const string glbContainersPath = "Portals/_default/Containers/"; /// - /// Default skin folder + /// Default skin folder. /// - /// Portals/_default/Skins/ + /// Portals/_default/Skins/. public const string glbSkinsPath = "Portals/_default/Skins/"; /// - /// Email address regex pattern + /// Email address regex pattern. /// /// public const string glbEmailRegEx = @"^\s*[a-zA-Z0-9_%+#&'*/=^`{|}~-](?:\.?[a-zA-Z0-9_%+#&'*/=^`{|}~-])*@(?:[a-zA-Z0-9_](?:(?:\.?|-*)[a-zA-Z0-9_])*\.[a-zA-Z]{2,9}|\[(?:2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?:2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?:2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?:2[0-4]\d|25[0-5]|[01]?\d\d?)])\s*$"; /// - /// User Name regex pattern + /// User Name regex pattern. /// /// public const string glbUserNameRegEx = @""; /// - /// format of a script tag + /// format of a script tag. /// /// ]]> public const string glbScriptFormat = ""; + private const string _tabPathInvalidCharsEx = "[&\\? \\./'#:\\*]"; // this value should keep same with the value used in sp BuildTabLevelAndPath to remove invalid chars. // global constants for the life of the application ( set in Application_Start ) private static string _applicationPath; @@ -339,9 +334,10 @@ public enum UpgradeStatus private static string _installPath; private static Version _dataBaseVersion; private static UpgradeStatus _status = UpgradeStatus.Unknown; - private const string _tabPathInvalidCharsEx = "[&\\? \\./'#:\\*]"; //this value should keep same with the value used in sp BuildTabLevelAndPath to remove invalid chars. private static readonly Regex TabPathInvalidCharsRx = new Regex(_tabPathInvalidCharsEx, RegexOptions.Compiled); + private static readonly Stopwatch AppStopwatch = Stopwatch.StartNew(); + /// /// Gets the application path. /// @@ -353,7 +349,7 @@ public static string ApplicationPath { if (HttpContext.Current.Request.ApplicationPath == "/") { - _applicationPath = string.IsNullOrEmpty(Config.GetSetting("InstallationSubfolder")) ? "" : (Config.GetSetting("InstallationSubfolder") + "/").ToLowerInvariant(); + _applicationPath = string.IsNullOrEmpty(Config.GetSetting("InstallationSubfolder")) ? string.Empty : (Config.GetSetting("InstallationSubfolder") + "/").ToLowerInvariant(); } else { @@ -366,7 +362,7 @@ public static string ApplicationPath } /// - /// Gets or sets the application map path. + /// Gets the application map path. /// /// /// The application map path. @@ -379,20 +375,10 @@ public static string ApplicationMapPath } } - private static string GetCurrentDomainDirectory() - { - var dir = AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\"); - if (dir.Length > 3 && dir.EndsWith("\\")) - { - dir = dir.Substring(0, dir.Length - 1); - } - return dir; - } - /// /// Gets the desktop module path. /// - /// ApplicationPath + "/DesktopModules/" + /// ApplicationPath + "/DesktopModules/". public static string DesktopModulePath { get @@ -401,6 +387,7 @@ public static string DesktopModulePath { _desktopModulePath = ApplicationPath + "/DesktopModules/"; } + return _desktopModulePath; } } @@ -408,7 +395,7 @@ public static string DesktopModulePath /// /// Gets the image path. /// - /// ApplicationPath + "/Images/" + /// ApplicationPath + "/Images/". public static string ImagePath { get @@ -417,6 +404,7 @@ public static string ImagePath { _imagePath = ApplicationPath + "/Images/"; } + return _imagePath; } } @@ -432,10 +420,21 @@ public static Version DataBaseVersion } } + private static string GetCurrentDomainDirectory() + { + var dir = AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\"); + if (dir.Length > 3 && dir.EndsWith("\\")) + { + dir = dir.Substring(0, dir.Length - 1); + } + + return dir; + } + /// - /// Gets or sets the host map path. + /// Gets the host map path. /// - /// ApplicationMapPath + "Portals\_default\" + /// ApplicationMapPath + "Portals\_default\". public static string HostMapPath { get @@ -444,14 +443,15 @@ public static string HostMapPath { _hostMapPath = Path.Combine(ApplicationMapPath, @"Portals\_default\"); } + return _hostMapPath; } } /// - /// Gets or sets the host path. + /// Gets the host path. /// - /// ApplicationPath + "/Portals/_default/" + /// ApplicationPath + "/Portals/_default/". public static string HostPath { get @@ -460,12 +460,13 @@ public static string HostPath { _hostPath = ApplicationPath + "/Portals/_default/"; } + return _hostPath; } } /// - /// Gets or sets the install map path. + /// Gets the install map path. /// /// server map path of InstallPath. public static string InstallMapPath @@ -476,14 +477,15 @@ public static string InstallMapPath { _installMapPath = ApplicationMapPath + "\\Install\\"; } + return _installMapPath; } } /// - /// Gets or sets the install path. + /// Gets the install path. /// - /// ApplicationPath + "/Install/" + /// ApplicationPath + "/Install/". public static string InstallPath { get @@ -492,6 +494,7 @@ public static string InstallPath { _installPath = ApplicationPath + "/Install/"; } + return _installPath; } } @@ -500,7 +503,7 @@ public static string InstallPath /// Gets or sets the name of the IIS app. /// /// - /// request.ServerVariables["APPL_MD_PATH"] + /// request.ServerVariables["APPL_MD_PATH"]. /// public static string IISAppName { get; set; } @@ -536,36 +539,6 @@ public static string InstallPath /// public static Version DatabaseEngineVersion { get; set; } - /// - /// Gets or sets the Dependency Service. - /// - /// - /// The Dependency Service. - /// - internal static IServiceProvider DependencyProvider { get; set; } - - /// - /// Redirects the specified URL. - /// - /// The URL. - /// if set to true [end response]. - public static void Redirect(string url, bool endResponse) - { - try - { - HttpContext.Current.Response.Redirect(url, endResponse); - } - catch (ThreadAbortException) - { - //we are ignoreing this error simply because there is no graceful way to redirect the user, wihtout the threadabort exception. - //RobC - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - /// /// Gets the status of application. /// @@ -580,10 +553,12 @@ public static UpgradeStatus Status Logger.Trace("Getting application status"); tempStatus = UpgradeStatus.None; - //first call GetProviderPath - this insures that the Database is Initialised correctly - //and also generates the appropriate error message if it cannot be initialised correctly + + // first call GetProviderPath - this insures that the Database is Initialised correctly + // and also generates the appropriate error message if it cannot be initialised correctly string strMessage = DataProvider.Instance().GetProviderPath(); - //get current database version from DB + + // get current database version from DB if (!strMessage.StartsWith("ERROR:")) { try @@ -596,22 +571,23 @@ public static UpgradeStatus Status strMessage = "ERROR:" + ex.Message; } } + if (strMessage.StartsWith("ERROR")) { if (IsInstalled()) { - //Errors connecting to the database after an initial installation should be treated as errors. + // Errors connecting to the database after an initial installation should be treated as errors. tempStatus = UpgradeStatus.Error; } else { - //An error that occurs before the database has been installed should be treated as a new install - tempStatus = UpgradeStatus.Install; + // An error that occurs before the database has been installed should be treated as a new install + tempStatus = UpgradeStatus.Install; } } else if (DataBaseVersion == null) { - //No Db Version so Install + // No Db Version so Install tempStatus = UpgradeStatus.Install; } else @@ -619,218 +595,117 @@ public static UpgradeStatus Status var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (version.Major > DataBaseVersion.Major) { - //Upgrade Required (Major Version Upgrade) + // Upgrade Required (Major Version Upgrade) tempStatus = UpgradeStatus.Upgrade; } else if (version.Major == DataBaseVersion.Major && version.Minor > DataBaseVersion.Minor) { - //Upgrade Required (Minor Version Upgrade) + // Upgrade Required (Minor Version Upgrade) tempStatus = UpgradeStatus.Upgrade; } else if (version.Major == DataBaseVersion.Major && version.Minor == DataBaseVersion.Minor && version.Build > DataBaseVersion.Build) { - //Upgrade Required (Build Version Upgrade) + // Upgrade Required (Build Version Upgrade) tempStatus = UpgradeStatus.Upgrade; } else if (version.Major == DataBaseVersion.Major && version.Minor == DataBaseVersion.Minor && version.Build == DataBaseVersion.Build && IncrementalVersionExists(version)) { - //Upgrade Required (Build Version Upgrade) + // Upgrade Required (Build Version Upgrade) tempStatus = UpgradeStatus.Upgrade; } } _status = tempStatus; - Logger.Trace(string.Format("result of getting providerpath: {0}",strMessage)); + Logger.Trace(string.Format("result of getting providerpath: {0}", strMessage)); Logger.Trace("Application status is " + _status); } - return _status; - } - } - - public static bool IncrementalVersionExists(Version version) - { - Provider currentdataprovider = Config.GetDefaultProvider("data"); - string providerpath = currentdataprovider.Attributes["providerPath"]; - //If the provider path does not exist, then there can't be any log files - if (!string.IsNullOrEmpty(providerpath)) - { - providerpath = HttpRuntime.AppDomainAppPath + providerpath.Replace("~",""); - if (Directory.Exists(providerpath)) - { - var incrementalcount = Directory.GetFiles(providerpath, Upgrade.GetStringVersion(version) + ".*." + Upgrade.DefaultProvider).Length; - - if (incrementalcount > Globals.GetLastAppliedIteration(version)) - { - return true; - } - } + return _status; } - return false; - } - - - /// - /// IsInstalled looks at various file artifacts to determine if DotNetNuke has already been installed. - /// - /// - /// - /// If DotNetNuke has been installed, then we should treat database connection errors as real errors. - /// If DotNetNuke has not been installed, then we should expect to have database connection problems - /// since the connection string may not have been configured yet, which can occur during the installation - /// wizard. - /// - internal static bool IsInstalled() - { - const int c_PassingScore = 4; - int installationdatefactor = Convert.ToInt32(HasInstallationDate() ? 1 : 0); - int dataproviderfactor = Convert.ToInt32(HasDataProviderLogFiles() ? 3 : 0); - int htmlmodulefactor = Convert.ToInt32(ModuleDirectoryExists("html") ? 2 : 0); - int portaldirectoryfactor = Convert.ToInt32(HasNonDefaultPortalDirectory() ? 2 : 0); - int localexecutionfactor = Convert.ToInt32(HttpContext.Current.Request.IsLocal ? c_PassingScore - 1 : 0); - //This calculation ensures that you have a more than one item that indicates you have already installed DNN. - //While it is possible that you might not have an installation date or that you have deleted log files - //it is unlikely that you have removed every trace of an installation and yet still have a working install - - bool isInstalled = (!IsInstallationURL()) && ((installationdatefactor + dataproviderfactor + htmlmodulefactor + portaldirectoryfactor + localexecutionfactor) >= c_PassingScore); - - // we need to tighten this check. We now are enforcing the existence of the InstallVersion value in web.config. If - // this value exists, then DNN was previously installed, and we should never try to re-install it - return isInstalled || HasInstallVersion(); } /// - /// Determines whether has data provider log files. + /// Gets image file types. /// - /// - /// true if has data provider log files; otherwise, false. - /// - private static bool HasDataProviderLogFiles() + /// Values read from ImageTypes List. If there is not List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. + public static string glbImageFileTypes { - Provider currentdataprovider = Config.GetDefaultProvider("data"); - string providerpath = currentdataprovider.Attributes["providerPath"]; - //If the provider path does not exist, then there can't be any log files - if (!string.IsNullOrEmpty(providerpath)) + get { - providerpath = HttpContext.Current.Server.MapPath(providerpath); - if (Directory.Exists(providerpath)) + var listController = new ListController(); + var listEntries = listController.GetListEntryInfoItems("ImageTypes"); + if (listEntries == null || listEntries.Count() == 0) { - return Directory.GetFiles(providerpath, "*.log.resources").Length > 0; + return "jpg,jpeg,jpe,gif,bmp,png,svg,ico"; } - } - return false; - } - /// - /// Determines whether has installation date. - /// - /// - /// true if has installation date; otherwise, false. - /// - private static bool HasInstallationDate() - { - return Config.GetSetting("InstallationDate") != null; - } - - /// - /// Determines whether has InstallVersion set. - /// - /// - /// true if has installation date; otherwise, false. - /// - private static bool HasInstallVersion() - { - return Config.GetSetting("InstallVersion") != null; - } - - /// - /// Check whether the modules directory is exists. - /// - /// Name of the module. - /// - /// true if the module directory exist, otherwise, false. - /// - private static bool ModuleDirectoryExists(string moduleName) - { - string dir = ApplicationMapPath + "\\desktopmodules\\" + moduleName; - return Directory.Exists(dir); + return string.Join(",", listEntries.Select(l => l.Value)); + } } - /// - /// Determines whether has portal directory except default portal directory in portal path. - /// - /// - /// true if has portal directory except default portal directory in portal path; otherwise, false. - /// - private static bool HasNonDefaultPortalDirectory() + public static TimeSpan ElapsedSinceAppStart { - string dir = ApplicationMapPath + "\\portals"; - if (Directory.Exists(dir)) + get { - return Directory.GetDirectories(dir).Length > 1; + return AppStopwatch.Elapsed; } - return false; } /// - /// Determines whether current request is for install. + /// Gets or sets the Dependency Service. /// - /// - /// true if current request is for install; otherwise, false. - /// - private static bool IsInstallationURL() - { - string requestURL = HttpContext.Current.Request.RawUrl.ToLowerInvariant().Replace("\\", "/"); - return requestURL.Contains("/install.aspx") || requestURL.Contains("/installwizard.aspx"); - } + /// + /// The Dependency Service. + /// + internal static IServiceProvider DependencyProvider { get; set; } /// - /// Gets the culture code of the tab. + /// Redirects the specified URL. /// - /// The tab ID. - /// if set to true [is super tab]. - /// The settings. - /// return the tab's culture code, if ths tab doesn't exist, it will return current culture name. - internal static string GetCultureCode(int TabID, bool IsSuperTab, IPortalSettings settings) + /// The URL. + /// if set to true [end response]. + public static void Redirect(string url, bool endResponse) { - string cultureCode = Null.NullString; - if (settings != null) + try { - TabInfo linkTab = TabController.Instance.GetTab(TabID, IsSuperTab ? Null.NullInteger : settings.PortalId, false); - if (linkTab != null) - { - cultureCode = linkTab.CultureCode; - } - if (string.IsNullOrEmpty(cultureCode)) - { - cultureCode = Thread.CurrentThread.CurrentCulture.Name; - } + HttpContext.Current.Response.Redirect(url, endResponse); + } + catch (ThreadAbortException) + { + // we are ignoreing this error simply because there is no graceful way to redirect the user, wihtout the threadabort exception. + // RobC + } + catch (Exception ex) + { + Logger.Error(ex); } - - return cultureCode; } - /// - /// Image file types - /// - /// Values read from ImageTypes List. If there is not List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico - public static string glbImageFileTypes + public static bool IncrementalVersionExists(Version version) { - get + Provider currentdataprovider = Config.GetDefaultProvider("data"); + string providerpath = currentdataprovider.Attributes["providerPath"]; + + // If the provider path does not exist, then there can't be any log files + if (!string.IsNullOrEmpty(providerpath)) { - var listController = new ListController(); - var listEntries = listController.GetListEntryInfoItems("ImageTypes"); - if (listEntries == null || listEntries.Count() == 0) + providerpath = HttpRuntime.AppDomainAppPath + providerpath.Replace("~", string.Empty); + if (Directory.Exists(providerpath)) { - return "jpg,jpeg,jpe,gif,bmp,png,svg,ico"; + var incrementalcount = Directory.GetFiles(providerpath, Upgrade.GetStringVersion(version) + ".*." + Upgrade.DefaultProvider).Length; + + if (incrementalcount > Globals.GetLastAppliedIteration(version)) + { + return true; + } } - return String.Join(",", listEntries.Select(l => l.Value)); } - } + return false; + } /// /// Builds the cross tab dataset. @@ -844,7 +719,7 @@ public static string glbImageFileTypes /// The field type column. /// The string value column. /// The numeric value column. - /// the dataset instance + /// the dataset instance. public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader result, string FixedColumns, string VariableColumns, string KeyColumn, string FieldColumn, string FieldTypeColumn, string StringValueColumn, string NumericValueColumn) { @@ -853,19 +728,19 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul /// ----------------------------------------------------------------------------- /// - /// converts a data reader with serialized fields into a typed data set - /// - /// Name of the dataset to be created - /// Data reader that contains all field values serialized - /// List of fixed columns, delimited by commas. Columns must be contained in DataReader - /// List of variable columns, delimited by commas. Columns must be contained in DataReader - /// Name of the column, that contains the row ID. Column must be contained in DataReader - /// Name of the column, that contains the field name. Column must be contained in DataReader - /// Name of the column, that contains the field type name. Column must be contained in DataReader - /// Name of the column, that contains the field value, if stored as string. Column must be contained in DataReader - /// Name of the column, that contains the field value, if stored as number. Column must be contained in DataReader - /// culture of the field values in data reader's string value column - /// The generated DataSet + /// converts a data reader with serialized fields into a typed data set. + /// + /// Name of the dataset to be created. + /// Data reader that contains all field values serialized. + /// List of fixed columns, delimited by commas. Columns must be contained in DataReader. + /// List of variable columns, delimited by commas. Columns must be contained in DataReader. + /// Name of the column, that contains the row ID. Column must be contained in DataReader. + /// Name of the column, that contains the field name. Column must be contained in DataReader. + /// Name of the column, that contains the field type name. Column must be contained in DataReader. + /// Name of the column, that contains the field value, if stored as string. Column must be contained in DataReader. + /// Name of the column, that contains the field value, if stored as number. Column must be contained in DataReader. + /// culture of the field values in data reader's string value column. + /// The generated DataSet. /// ----------------------------------------------------------------------------- public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader result, string FixedColumns, string VariableColumns, string KeyColumn, string FieldColumn, string FieldTypeColumn, string StringValueColumn, string NumericValueColumn, CultureInfo Culture) @@ -876,13 +751,17 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul string FieldType; int intColumn; int intKeyColumn; + // create dataset var crosstab = new DataSet(DataSetName); crosstab.Namespace = "NetFrameWork"; + // create table var tab = new DataTable(DataSetName); + // split fixed columns arrFixedColumns = FixedColumns.Split(','); + // add fixed columns to table for (intColumn = 0; intColumn < arrFixedColumns.Length; intColumn++) { @@ -892,10 +771,11 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul } // split variable columns - if (!String.IsNullOrEmpty(VariableColumns)) + if (!string.IsNullOrEmpty(VariableColumns)) { arrVariableColumns = VariableColumns.Split(','); - //add varible columns to table + + // add varible columns to table for (intColumn = 0; intColumn < arrVariableColumns.Length; intColumn++) { arrField = arrVariableColumns[intColumn].Split('|'); @@ -904,31 +784,36 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul tab.Columns.Add(col); } } + // add table to dataset crosstab.Tables.Add(tab); + // add rows to table intKeyColumn = -1; DataRow row = null; while (result.Read()) { - //loop using KeyColumn as control break + // loop using KeyColumn as control break if (Convert.ToInt32(result[KeyColumn]) != intKeyColumn) { - //add row + // add row if (intKeyColumn != -1) { tab.Rows.Add(row); } + // create new row row = tab.NewRow(); + // assign fixed column values for (intColumn = 0; intColumn < arrFixedColumns.Length; intColumn++) { arrField = arrFixedColumns[intColumn].Split('|'); row[arrField[0]] = result[arrField[0]]; } - //initialize variable column values - if (!String.IsNullOrEmpty(VariableColumns)) + + // initialize variable column values + if (!string.IsNullOrEmpty(VariableColumns)) { for (intColumn = 0; intColumn < arrVariableColumns.Length; intColumn++) { @@ -939,15 +824,17 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul row[arrField[0]] = 0; break; case "String": - row[arrField[0]] = ""; + row[arrField[0]] = string.Empty; break; } } } + intKeyColumn = Convert.ToInt32(result[KeyColumn]); } - //assign pivot column value - if (!String.IsNullOrEmpty(FieldTypeColumn)) + + // assign pivot column value + if (!string.IsNullOrEmpty(FieldTypeColumn)) { FieldType = result[FieldTypeColumn].ToString(); } @@ -955,6 +842,7 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul { FieldType = "String"; } + switch (FieldType) { case "Decimal": @@ -974,33 +862,182 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul row[result[FieldColumn].ToString()] = decimal.Parse(result[StringValueColumn].ToString(), Culture); break; case "System.Int32": - row[result[FieldColumn].ToString()] = Int32.Parse(result[StringValueColumn].ToString(), Culture); + row[result[FieldColumn].ToString()] = int.Parse(result[StringValueColumn].ToString(), Culture); break; default: row[result[FieldColumn].ToString()] = result[StringValueColumn]; break; } } + break; } } + result.Close(); + // add row if (intKeyColumn != -1) { tab.Rows.Add(row); } + // finalize dataset crosstab.AcceptChanges(); + // return the dataset return crosstab; } + /// + /// IsInstalled looks at various file artifacts to determine if DotNetNuke has already been installed. + /// + /// + /// + /// If DotNetNuke has been installed, then we should treat database connection errors as real errors. + /// If DotNetNuke has not been installed, then we should expect to have database connection problems + /// since the connection string may not have been configured yet, which can occur during the installation + /// wizard. + /// + internal static bool IsInstalled() + { + const int c_PassingScore = 4; + int installationdatefactor = Convert.ToInt32(HasInstallationDate() ? 1 : 0); + int dataproviderfactor = Convert.ToInt32(HasDataProviderLogFiles() ? 3 : 0); + int htmlmodulefactor = Convert.ToInt32(ModuleDirectoryExists("html") ? 2 : 0); + int portaldirectoryfactor = Convert.ToInt32(HasNonDefaultPortalDirectory() ? 2 : 0); + int localexecutionfactor = Convert.ToInt32(HttpContext.Current.Request.IsLocal ? c_PassingScore - 1 : 0); + + // This calculation ensures that you have a more than one item that indicates you have already installed DNN. + // While it is possible that you might not have an installation date or that you have deleted log files + // it is unlikely that you have removed every trace of an installation and yet still have a working install + bool isInstalled = (!IsInstallationURL()) && ((installationdatefactor + dataproviderfactor + htmlmodulefactor + portaldirectoryfactor + localexecutionfactor) >= c_PassingScore); + + // we need to tighten this check. We now are enforcing the existence of the InstallVersion value in web.config. If + // this value exists, then DNN was previously installed, and we should never try to re-install it + return isInstalled || HasInstallVersion(); + } + + /// + /// Gets the culture code of the tab. + /// + /// The tab ID. + /// if set to true [is super tab]. + /// The settings. + /// return the tab's culture code, if ths tab doesn't exist, it will return current culture name. + internal static string GetCultureCode(int TabID, bool IsSuperTab, IPortalSettings settings) + { + string cultureCode = Null.NullString; + if (settings != null) + { + TabInfo linkTab = TabController.Instance.GetTab(TabID, IsSuperTab ? Null.NullInteger : settings.PortalId, false); + if (linkTab != null) + { + cultureCode = linkTab.CultureCode; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + cultureCode = Thread.CurrentThread.CurrentCulture.Name; + } + } + + return cultureCode; + } + + /// + /// Determines whether has data provider log files. + /// + /// + /// true if has data provider log files; otherwise, false. + /// + private static bool HasDataProviderLogFiles() + { + Provider currentdataprovider = Config.GetDefaultProvider("data"); + string providerpath = currentdataprovider.Attributes["providerPath"]; + + // If the provider path does not exist, then there can't be any log files + if (!string.IsNullOrEmpty(providerpath)) + { + providerpath = HttpContext.Current.Server.MapPath(providerpath); + if (Directory.Exists(providerpath)) + { + return Directory.GetFiles(providerpath, "*.log.resources").Length > 0; + } + } + + return false; + } + + /// + /// Determines whether has installation date. + /// + /// + /// true if has installation date; otherwise, false. + /// + private static bool HasInstallationDate() + { + return Config.GetSetting("InstallationDate") != null; + } + + /// + /// Determines whether has InstallVersion set. + /// + /// + /// true if has installation date; otherwise, false. + /// + private static bool HasInstallVersion() + { + return Config.GetSetting("InstallVersion") != null; + } + + /// + /// Check whether the modules directory is exists. + /// + /// Name of the module. + /// + /// true if the module directory exist, otherwise, false. + /// + private static bool ModuleDirectoryExists(string moduleName) + { + string dir = ApplicationMapPath + "\\desktopmodules\\" + moduleName; + return Directory.Exists(dir); + } + + /// + /// Determines whether has portal directory except default portal directory in portal path. + /// + /// + /// true if has portal directory except default portal directory in portal path; otherwise, false. + /// + private static bool HasNonDefaultPortalDirectory() + { + string dir = ApplicationMapPath + "\\portals"; + if (Directory.Exists(dir)) + { + return Directory.GetDirectories(dir).Length > 1; + } + + return false; + } + + /// + /// Determines whether current request is for install. + /// + /// + /// true if current request is for install; otherwise, false. + /// + private static bool IsInstallationURL() + { + string requestURL = HttpContext.Current.Request.RawUrl.ToLowerInvariant().Replace("\\", "/"); + return requestURL.Contains("/install.aspx") || requestURL.Contains("/installwizard.aspx"); + } + /// /// Converts the datareader to dataset. /// /// The reader. - /// the dataset instance + /// the dataset instance. public static DataSet ConvertDataReaderToDataSet(IDataReader reader) { // add datatable to dataset @@ -1011,11 +1048,12 @@ public static DataSet ConvertDataReaderToDataSet(IDataReader reader) do { objDataSet.Tables.Add(ConvertDataReaderToDataTable(reader, false)); - } while (reader.NextResult()); + } + while (reader.NextResult()); } finally { - reader.Close(); + reader.Close(); } return objDataSet; @@ -1025,43 +1063,45 @@ public static DataSet ConvertDataReaderToDataSet(IDataReader reader) /// Converts the datareader to datatable. /// /// The reader. - /// the datatable instance - public static DataTable ConvertDataReaderToDataTable(IDataReader reader) + /// the datatable instance. + public static DataTable ConvertDataReaderToDataTable(IDataReader reader) { - return ConvertDataReaderToDataTable(reader, true); + return ConvertDataReaderToDataTable(reader, true); } - /// - /// Converts the datareader to datatable. - /// - /// The reader. - /// Whether close reader. - /// the datatable instance + /// + /// Converts the datareader to datatable. + /// + /// The reader. + /// Whether close reader. + /// the datatable instance. public static DataTable ConvertDataReaderToDataTable(IDataReader reader, bool closeReader) { - try - { + try + { // create datatable from datareader var objDataTable = new DataTable(); - int intFieldCount = reader.FieldCount; - int intCounter; - for (intCounter = 0; intCounter <= intFieldCount - 1; intCounter++) - { - objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter)); - } - // populate datatable - objDataTable.BeginLoadData(); - var objValues = new object[intFieldCount]; - while (reader.Read()) - { - reader.GetValues(objValues); - objDataTable.LoadDataRow(objValues, true); - } - objDataTable.EndLoadData(); - return objDataTable; - } - finally - { + int intFieldCount = reader.FieldCount; + int intCounter; + for (intCounter = 0; intCounter <= intFieldCount - 1; intCounter++) + { + objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter)); + } + + // populate datatable + objDataTable.BeginLoadData(); + var objValues = new object[intFieldCount]; + while (reader.Read()) + { + reader.GetValues(objValues); + objDataTable.LoadDataRow(objValues, true); + } + + objDataTable.EndLoadData(); + return objDataTable; + } + finally + { if (closeReader) { reader.Close(); @@ -1073,7 +1113,7 @@ public static DataTable ConvertDataReaderToDataTable(IDataReader reader, bool cl /// Gets the absolute server path. /// /// The request. - /// absolute server path + /// absolute server path. public static string GetAbsoluteServerPath(HttpRequest Request) { string strServerPath; @@ -1082,6 +1122,7 @@ public static string GetAbsoluteServerPath(HttpRequest Request) { strServerPath += "\\"; } + return strServerPath; } @@ -1095,11 +1136,12 @@ public static string GetAbsoluteServerPath(HttpRequest Request) /// for this instance of DotNetNuke, and Id is the current PortalId for normal /// users or glbSuperUserAppName for SuperUsers. /// + /// /// ----------------------------------------------------------------------------- public static string GetApplicationName() { string appName; - if (HttpContext.Current.Items["ApplicationName"] == null || String.IsNullOrEmpty(HttpContext.Current.Items["ApplicationName"].ToString())) + if (HttpContext.Current.Items["ApplicationName"] == null || string.IsNullOrEmpty(HttpContext.Current.Items["ApplicationName"].ToString())) { PortalSettings _PortalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (_PortalSettings == null) @@ -1115,6 +1157,7 @@ public static string GetApplicationName() { appName = Convert.ToString(HttpContext.Current.Items["ApplicationName"]); } + return appName; } @@ -1123,22 +1166,27 @@ public static string GetApplicationName() /// Gets the ApplicationName for the MemberRole API. /// /// - /// This overload is used to build the Application Name from the Portal Id + /// This overload is used to build the Application Name from the Portal Id. /// + /// /// ----------------------------------------------------------------------------- public static string GetApplicationName(int PortalID) { string appName; - //Get the Data Provider Configuration + + // Get the Data Provider Configuration ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration("data"); - //Read the configuration specific information for the current Provider + + // Read the configuration specific information for the current Provider var objProvider = (Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider]; - //Get the Object Qualifier frm the Provider Configuration + + // Get the Object Qualifier frm the Provider Configuration string _objectQualifier = objProvider.Attributes["objectQualifier"]; - if (!String.IsNullOrEmpty(_objectQualifier) && _objectQualifier.EndsWith("_") == false) + if (!string.IsNullOrEmpty(_objectQualifier) && _objectQualifier.EndsWith("_") == false) { _objectQualifier += "_"; } + appName = _objectQualifier + Convert.ToString(PortalID); return appName; } @@ -1170,6 +1218,7 @@ public static bool FindDatabaseVersion(int Major, int Minor, int Build) { CBO.CloseDataReader(dr, true); } + return version; } @@ -1179,7 +1228,7 @@ public static bool FindDatabaseVersion(int Major, int Minor, int Build) /// The version. public static void UpdateDataBaseVersion(Version version) { - //update the version + // update the version DataProvider.Instance().UpdateDatabaseVersion(version.Major, version.Minor, version.Build, DotNetNukeContext.Current.Application.Name); _dataBaseVersion = version; } @@ -1189,33 +1238,31 @@ public static void UpdateDataBaseVersion(Version version) /// /// The version. /// The increment. - public static void UpdateDataBaseVersionIncrement(Version version,int increment) + public static void UpdateDataBaseVersionIncrement(Version version, int increment) { - //update the version and increment - DataProvider.Instance().UpdateDatabaseVersionIncrement(version.Major, version.Minor, version.Build, increment, DotNetNukeContext.Current.Application.Name); + // update the version and increment + DataProvider.Instance().UpdateDatabaseVersionIncrement(version.Major, version.Minor, version.Build, increment, DotNetNukeContext.Current.Application.Name); _dataBaseVersion = version; } - public static int GetLastAppliedIteration(Version version) - { - try - { - return DataProvider.Instance().GetLastAppliedIteration(version.Major, version.Minor, version.Build); - } - catch (Exception) - { - - return 0; - } - - } + public static int GetLastAppliedIteration(Version version) + { + try + { + return DataProvider.Instance().GetLastAppliedIteration(version.Major, version.Minor, version.Build); + } + catch (Exception) + { + return 0; + } + } /// /// Adds the port. /// /// The HTTP alias. /// The original URL. - /// url with port if the post number is not 80 + /// url with port if the post number is not 80. public static string AddPort(string httpAlias, string originalUrl) { var uri = new Uri(originalUrl); @@ -1233,7 +1280,7 @@ public static string AddPort(string httpAlias, string originalUrl) /// Gets the name of the domain. /// /// The request. - /// domain name + /// domain name. public static string GetDomainName(HttpRequest request) { return GetDomainName(new HttpRequestWrapper(request), false); @@ -1243,29 +1290,29 @@ public static string GetDomainName(HttpRequest request) /// Gets the name of the domain. /// /// The request. - /// domain name + /// domain name. public static string GetDomainName(HttpRequestBase request) { return GetDomainName(request, false); } /// - /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ) + /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ). /// /// The request. /// if set to true [parse port number]. - /// domain name + /// domain name. public static string GetDomainName(HttpRequest request, bool parsePortNumber) { return GetDomainName(new HttpRequestWrapper(request), parsePortNumber); } /// - /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ) + /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ). /// /// The request. /// if set to true [parse port number]. - /// domain name + /// domain name. public static string GetDomainName(HttpRequestBase request, bool parsePortNumber) { return TestableGlobals.Instance.GetDomainName(request.Url, parsePortNumber); @@ -1280,10 +1327,11 @@ public static string GetDomainName(HttpRequestBase request, bool parsePortNumber public static bool UsePortNumber() { bool usePort = true; - if ((Config.GetSetting("UsePortNumber") != null)) + if (Config.GetSetting("UsePortNumber") != null) { usePort = bool.Parse(Config.GetSetting("UsePortNumber")); } + return usePort; } @@ -1293,17 +1341,17 @@ public static bool UsePortNumber() /// file list. public static ArrayList GetFileList() { - return GetFileList(-1, "", true, "", false); + return GetFileList(-1, string.Empty, true, string.Empty, false); } /// /// Gets the file list. /// /// The portal id. - /// file list + /// file list. public static ArrayList GetFileList(int portalId) { - return GetFileList(portalId, "", true, "", false); + return GetFileList(portalId, string.Empty, true, string.Empty, false); } /// @@ -1311,10 +1359,10 @@ public static ArrayList GetFileList(int portalId) /// /// The portal id. /// The STR extensions. - /// file list + /// file list. public static ArrayList GetFileList(int portalId, string strExtensions) { - return GetFileList(portalId, strExtensions, true, "", false); + return GetFileList(portalId, strExtensions, true, string.Empty, false); } /// @@ -1323,10 +1371,10 @@ public static ArrayList GetFileList(int portalId, string strExtensions) /// The portal id. /// The STR extensions. /// if set to true [none specified]. - /// file list + /// file list. public static ArrayList GetFileList(int portalId, string strExtensions, bool noneSpecified) { - return GetFileList(portalId, strExtensions, noneSpecified, "", false); + return GetFileList(portalId, strExtensions, noneSpecified, string.Empty, false); } /// @@ -1336,7 +1384,7 @@ public static ArrayList GetFileList(int portalId, string strExtensions, bool non /// The STR extensions. /// if set to true [none specified]. /// The folder. - /// file list + /// file list. public static ArrayList GetFileList(int PortalId, string strExtensions, bool NoneSpecified, string Folder) { return GetFileList(PortalId, strExtensions, NoneSpecified, Folder, false); @@ -1350,13 +1398,13 @@ public static ArrayList GetFileList(int PortalId, string strExtensions, bool Non /// if set to true [none specified]. /// The folder. /// if set to true [include hidden]. - /// file list + /// file list. public static ArrayList GetFileList(int PortalId, string strExtensions, bool NoneSpecified, string Folder, bool includeHidden) { var arrFileList = new ArrayList(); if (NoneSpecified) { - arrFileList.Add(new FileItem("", "<" + Localization.GetString("None_Specified") + ">")); + arrFileList.Add(new FileItem(string.Empty, "<" + Localization.GetString("None_Specified") + ">")); } var objFolder = FolderManager.Instance.GetFolder(PortalId, Folder); @@ -1393,7 +1441,7 @@ public static ArrayList GetFileList(int PortalId, string strExtensions, bool Non } else { - //File is stored in DB - Just add to arraylist + // File is stored in DB - Just add to arraylist arrFileList.Add(new FileItem(file.FileId.ToString(), file.FileName)); } } @@ -1404,26 +1452,30 @@ public static ArrayList GetFileList(int PortalId, string strExtensions, bool Non Exceptions.LogException(ex); } } + return arrFileList; } /// /// Gets the host portal settings. /// - /// Host portal settings + /// Host portal settings. public static PortalSettings GetHostPortalSettings() { int TabId = -1; int PortalId = -1; PortalAliasInfo objPortalAliasInfo = null; - //if the portal alias exists + + // if the portal alias exists if (Host.HostPortalID > Null.NullInteger) { PortalId = Host.HostPortalID; + // use the host portal objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalID = PortalId; } + // load the PortalSettings into current context return new PortalSettings(TabId, objPortalAliasInfo); } @@ -1434,16 +1486,17 @@ public static PortalSettings GetHostPortalSettings() /// The portal alias. /// The request or null. /// if set to true calls on the result. - /// domain name + /// domain name. public static string GetPortalDomainName(string strPortalAlias, HttpRequest Request, bool blnAddHTTP) { - string strDomainName = ""; - string strURL = ""; + string strDomainName = string.Empty; + string strURL = string.Empty; int intAlias; if (Request != null) { strURL = GetDomainName(Request); } + string[] arrPortalAlias = strPortalAlias.Split(','); for (intAlias = 0; intAlias <= arrPortalAlias.Length - 1; intAlias++) { @@ -1452,45 +1505,52 @@ public static string GetPortalDomainName(string strPortalAlias, HttpRequest Requ strDomainName = arrPortalAlias[intAlias]; } } - if (String.IsNullOrEmpty(strDomainName)) + + if (string.IsNullOrEmpty(strDomainName)) { strDomainName = arrPortalAlias[0]; } + if (blnAddHTTP) { strDomainName = AddHTTP(strDomainName); } + return strDomainName; } /// /// Gets the portal settings. /// - /// Portal settings + /// Portal settings. public static PortalSettings GetPortalSettings() { PortalSettings portalSettings = null; - //Try getting the settings from the Context + + // Try getting the settings from the Context if (HttpContext.Current != null) { portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; } - //If nothing then try getting the Host Settings + + // If nothing then try getting the Host Settings if (portalSettings == null) { portalSettings = GetHostPortalSettings(); } + return portalSettings; } /// ----------------------------------------------------------------------------- /// - /// Returns the folder path under the root for the portal + /// Returns the folder path under the root for the portal. /// - /// The folder the absolute path + /// The folder the absolute path. /// Portal Id. /// /// + /// /// ----------------------------------------------------------------------------- public static string GetSubFolderPath(string strFileNamePath, int portalId) { @@ -1504,6 +1564,7 @@ public static string GetSubFolderPath(string strFileNamePath, int portalId) PortalInfo objPortal = PortalController.Instance.GetPortal(portalId); ParentFolderName = objPortal.HomeDirectoryMapPath.Replace("/", "\\"); } + string strFolderpath = strFileNamePath.Substring(0, strFileNamePath.LastIndexOf("\\") + 1); return strFolderpath.Substring(ParentFolderName.Length).Replace("\\", "/"); } @@ -1512,8 +1573,8 @@ public static string GetSubFolderPath(string strFileNamePath, int portalId) /// /// The GetTotalRecords method gets the number of Records returned. /// - /// An containing the Total no of records - /// An Integer + /// An containing the Total no of records. + /// An Integer. /// ----------------------------------------------------------------------------- public static int GetTotalRecords(ref IDataReader dr) { @@ -1530,6 +1591,7 @@ public static int GetTotalRecords(ref IDataReader dr) total = -1; } } + return total; } @@ -1545,11 +1607,11 @@ public static void SetStatus(UpgradeStatus status) /// ----------------------------------------------------------------------------- /// /// ImportFile - converts a file url (/Portals/0/somefile.gif) to the appropriate - /// FileID=xx identification for use in importing portals, tabs and modules + /// FileID=xx identification for use in importing portals, tabs and modules. /// /// /// - /// An UpgradeStatus enum Upgrade/Install/None + /// An UpgradeStatus enum Upgrade/Install/None. /// ----------------------------------------------------------------------------- public static string ImportFile(int PortalId, string url) { @@ -1575,13 +1637,13 @@ public static string ImportFile(int PortalId, string url) } /// - /// Encode the post url + /// Encode the post url. /// /// The post url. - /// encoded value + /// encoded value. public static string HTTPPOSTEncode(string strPost) { - strPost = strPost.Replace("\\", ""); + strPost = strPost.Replace("\\", string.Empty); strPost = HttpUtility.UrlEncode(strPost); strPost = strPost.Replace("%2f", "/"); return strPost; @@ -1589,12 +1651,12 @@ public static string HTTPPOSTEncode(string strPost) /// ----------------------------------------------------------------------------- /// - /// Sets the ApplicationName for the MemberRole API + /// Sets the ApplicationName for the MemberRole API. /// /// - /// This overload takes a the PortalId + /// This overload takes a the PortalId. /// - /// The Portal Id + /// The Portal Id. /// ----------------------------------------------------------------------------- public static void SetApplicationName(int PortalID) { @@ -1603,12 +1665,12 @@ public static void SetApplicationName(int PortalID) /// ----------------------------------------------------------------------------- /// - /// Sets the ApplicationName for the MemberRole API + /// Sets the ApplicationName for the MemberRole API. /// /// - /// This overload takes a the PortalId + /// This overload takes a the PortalId. /// - /// The Application Name to set + /// The Application Name to set. /// ----------------------------------------------------------------------------- public static void SetApplicationName(string ApplicationName) { @@ -1616,7 +1678,7 @@ public static void SetApplicationName(string ApplicationName) } /// - /// Formats the address on a single line ( ie. Unit, Street, City, Region, Country, PostalCode ) + /// Formats the address on a single line ( ie. Unit, Street, City, Region, Country, PostalCode ). /// /// The unit. /// The street. @@ -1627,61 +1689,68 @@ public static void SetApplicationName(string ApplicationName) /// public static string FormatAddress(object Unit, object Street, object City, object Region, object Country, object PostalCode) { - string strAddress = ""; + string strAddress = string.Empty; if (Unit != null) { - if (!String.IsNullOrEmpty(Unit.ToString().Trim())) + if (!string.IsNullOrEmpty(Unit.ToString().Trim())) { strAddress += ", " + Unit; } } + if (Street != null) { - if (!String.IsNullOrEmpty(Street.ToString().Trim())) + if (!string.IsNullOrEmpty(Street.ToString().Trim())) { strAddress += ", " + Street; } } + if (City != null) { - if (!String.IsNullOrEmpty(City.ToString().Trim())) + if (!string.IsNullOrEmpty(City.ToString().Trim())) { strAddress += ", " + City; } } + if (Region != null) { - if (!String.IsNullOrEmpty(Region.ToString().Trim())) + if (!string.IsNullOrEmpty(Region.ToString().Trim())) { strAddress += ", " + Region; } } + if (Country != null) { - if (!String.IsNullOrEmpty(Country.ToString().Trim())) + if (!string.IsNullOrEmpty(Country.ToString().Trim())) { strAddress += ", " + Country; } } + if (PostalCode != null) { - if (!String.IsNullOrEmpty(PostalCode.ToString().Trim())) + if (!string.IsNullOrEmpty(PostalCode.ToString().Trim())) { strAddress += ", " + PostalCode; } } - if (!String.IsNullOrEmpty(strAddress.Trim())) + + if (!string.IsNullOrEmpty(strAddress.Trim())) { strAddress = strAddress.Substring(2); } + return strAddress; } /// - /// Formats the system.version into the standard format nn.nn.nn + /// Formats the system.version into the standard format nn.nn.nn. /// /// The version. - /// Formatted version as string + /// Formatted version as string. public static string FormatVersion(Version version) { return FormatVersion(version, false); @@ -1692,7 +1761,7 @@ public static string FormatVersion(Version version) /// /// The version. /// if set to true [include build]. - /// Formatted version as string + /// Formatted version as string. /// /// /// var version = new Version(6, 0, 0, 147); @@ -1706,20 +1775,21 @@ public static string FormatVersion(Version version, bool includeBuild) { strVersion += " (" + version.Revision + ")"; } + return strVersion; } /// - /// Formats a version into the standard format nn.nn.nn + /// Formats a version into the standard format nn.nn.nn. /// /// The version to be formatted. /// The field format. /// The field count. /// The delimiter character. - /// Formatted version as a string + /// Formatted version as a string. public static string FormatVersion(Version version, string fieldFormat, int fieldCount, string delimiterCharacter) { - string strVersion = ""; + string strVersion = string.Empty; int intZero = 0; if (version != null) { @@ -1734,6 +1804,7 @@ public static string FormatVersion(Version version, string fieldFormat, int fiel strVersion += intZero.ToString(fieldFormat); } } + if (fieldCount > 1) { strVersion += delimiterCharacter; @@ -1746,6 +1817,7 @@ public static string FormatVersion(Version version, string fieldFormat, int fiel strVersion += intZero.ToString(fieldFormat); } } + if (fieldCount > 2) { strVersion += delimiterCharacter; @@ -1758,6 +1830,7 @@ public static string FormatVersion(Version version, string fieldFormat, int fiel strVersion += intZero.ToString(fieldFormat); } } + if (fieldCount > 3) { strVersion += delimiterCharacter; @@ -1771,14 +1844,15 @@ public static string FormatVersion(Version version, string fieldFormat, int fiel } } } + return strVersion; } /// - /// Cloaks the text, obfuscate sensitive data to prevent collection by robots and spiders and crawlers + /// Cloaks the text, obfuscate sensitive data to prevent collection by robots and spiders and crawlers. /// /// The personal info. - /// obfuscated sensitive data by hustling ASCII characters + /// obfuscated sensitive data by hustling ASCII characters. public static string CloakText(string PersonalInfo) { if (PersonalInfo == null) @@ -1810,7 +1884,7 @@ public static string CloakText(string PersonalInfo) /// public static string GetMediumDate(string strDate) { - if (!String.IsNullOrEmpty(strDate)) + if (!string.IsNullOrEmpty(strDate)) { DateTime datDate = Convert.ToDateTime(strDate); string strYear = datDate.Year.ToString(); @@ -1818,6 +1892,7 @@ public static string GetMediumDate(string strDate) string strDay = datDate.Day.ToString(); strDate = strDay + "-" + strMonth + "-" + strYear; } + return strDate; } @@ -1828,7 +1903,7 @@ public static string GetMediumDate(string strDate) /// short date content of the input. public static string GetShortDate(string strDate) { - if (!String.IsNullOrEmpty(strDate)) + if (!string.IsNullOrEmpty(strDate)) { DateTime datDate = Convert.ToDateTime(strDate); string strYear = datDate.Year.ToString(); @@ -1836,6 +1911,7 @@ public static string GetShortDate(string strDate) string strDay = datDate.Day.ToString(); strDate = strMonth + "/" + strDay + "/" + strYear; } + return strDate; } @@ -1852,6 +1928,7 @@ public static bool IsAdminControl() { return false; } + return (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) || (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); } @@ -1867,27 +1944,30 @@ public static bool IsAdminSkin() if (HttpContext.Current != null) { string AdminKeys = "tab,module,importmodule,exportmodule,help"; - string ControlKey = ""; + string ControlKey = string.Empty; if (HttpContext.Current.Request.QueryString["ctl"] != null) { ControlKey = HttpContext.Current.Request.QueryString["ctl"].ToLowerInvariant(); } + int ModuleID = -1; if (HttpContext.Current.Request.QueryString["mid"] != null) { - Int32.TryParse(HttpContext.Current.Request.QueryString["mid"], out ModuleID); + int.TryParse(HttpContext.Current.Request.QueryString["mid"], out ModuleID); } - _IsAdminSkin = (!String.IsNullOrEmpty(ControlKey) && ControlKey != "view" && ModuleID != -1) || - (!String.IsNullOrEmpty(ControlKey) && AdminKeys.IndexOf(ControlKey) != -1 && ModuleID == -1); + + _IsAdminSkin = (!string.IsNullOrEmpty(ControlKey) && ControlKey != "view" && ModuleID != -1) || + (!string.IsNullOrEmpty(ControlKey) && AdminKeys.IndexOf(ControlKey) != -1 && ModuleID == -1); } + return _IsAdminSkin; } /// ----------------------------------------------------------------------------- /// - /// Returns whether the current tab is in EditMode + /// Returns whether the current tab is in EditMode. /// - /// true if the tab is in Edit mode; otherwise false + /// true if the tab is in Edit mode; otherwise false. /// /// /// ----------------------------------------------------------------------------- @@ -1904,15 +1984,15 @@ public static bool IsEditMode() /// ----------------------------------------------------------------------------- /// - /// Returns whether the current tab is in LayoutMode + /// Returns whether the current tab is in LayoutMode. /// - /// true if the current tab is in layout mode; otherwise false + /// true if the current tab is in layout mode; otherwise false. /// /// /// ----------------------------------------------------------------------------- public static bool IsLayoutMode() { - return (TabPermissionController.CanAddContentToPage() && PortalController.Instance.GetCurrentPortalSettings().UserMode == PortalSettings.Mode.Layout); + return TabPermissionController.CanAddContentToPage() && PortalController.Instance.GetCurrentPortalSettings().UserMode == PortalSettings.Mode.Layout; } /// @@ -1937,12 +2017,12 @@ public static void CreateRSS(IDataReader dr, string TitleField, string URLField, while (dr.Read()) { int field; - int.TryParse((dr[SyndicateField] ?? "").ToString(), out field); + int.TryParse((dr[SyndicateField] ?? string.Empty).ToString(), out field); if (field > 0) { strRSS.AppendLine(" "); strRSS.AppendLine(" " + dr[TitleField] + ""); - var drUrl = (dr["URL"] ?? "").ToString(); + var drUrl = (dr["URL"] ?? string.Empty).ToString(); if (drUrl.IndexOf("://", StringComparison.InvariantCulture) == -1) { strRSS.Append(" "); @@ -1954,12 +2034,14 @@ public static void CreateRSS(IDataReader dr, string TitleField, string URLField, { strRSS.Append(strRelativePath + dr[URLField]); } + strRSS.AppendLine(""); } else { strRSS.AppendLine(" " + dr[URLField] + ""); } + strRSS.AppendLine(" " + _portalSettings.PortalName + " " + GetMediumDate(dr[CreatedDateField].ToString()) + ""); strRSS.AppendLine(" "); } @@ -1995,11 +2077,11 @@ public static void CreateRSS(IDataReader dr, string TitleField, string URLField, /// ----------------------------------------------------------------------------- /// - /// injects the upload directory into raw HTML for src and background tags + /// injects the upload directory into raw HTML for src and background tags. /// - /// raw HTML text - /// path of portal image directory - /// HTML with paths for images and background corrected + /// raw HTML text. + /// path of portal image directory. + /// HTML with paths for images and background corrected. /// /// /// ----------------------------------------------------------------------------- @@ -2011,12 +2093,12 @@ public static string ManageUploadDirectory(string strHTML, string strUploadDirec /// ----------------------------------------------------------------------------- /// - /// injects the upload directory into raw HTML for a single token + /// injects the upload directory into raw HTML for a single token. /// - /// raw HTML text - /// path of portal image directory - /// token to be replaced - /// HTML with paths for images and background corrected + /// raw HTML text. + /// path of portal image directory. + /// token to be replaced. + /// HTML with paths for images and background corrected. /// /// called by ManageUploadDirectory for each token. /// @@ -2028,18 +2110,19 @@ public static string ManageTokenUploadDirectory(string strHTML, string strUpload int S = 0; int tLen; string strURL; - var sbBuff = new StringBuilder(""); - if (!String.IsNullOrEmpty(strHTML)) + var sbBuff = new StringBuilder(string.Empty); + if (!string.IsNullOrEmpty(strHTML)) { tLen = strToken.Length + 2; string _UploadDirectory = strUploadDirectory.ToLowerInvariant(); - //find position of first occurrance: + + // find position of first occurrance: P = strHTML.IndexOf(strToken + "=\"", StringComparison.InvariantCultureIgnoreCase); while (P != -1) { - sbBuff.Append(strHTML.Substring(S, P - S + tLen)); //keep charactes left of URL - S = P + tLen; //save startpos of URL - R = strHTML.IndexOf("\"", S); //end of URL + sbBuff.Append(strHTML.Substring(S, P - S + tLen)); // keep charactes left of URL + S = P + tLen; // save startpos of URL + R = strHTML.IndexOf("\"", S); // end of URL if (R >= 0) { strURL = strHTML.Substring(S, R - S).ToLowerInvariant(); @@ -2048,19 +2131,23 @@ public static string ManageTokenUploadDirectory(string strHTML, string strUpload { strURL = strHTML.Substring(S).ToLowerInvariant(); } + // add uploaddirectory if we are linking internally and the uploaddirectory is not already included if (!strURL.Contains("://") && !strURL.StartsWith("/") && !strURL.StartsWith(_UploadDirectory)) { sbBuff.Append(strUploadDirectory); } - //find position of next occurrance: + + // find position of next occurrance: P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); } + if (S > -1) { sbBuff.Append(strHTML.Substring(S)); } } + return sbBuff.ToString(); } @@ -2091,10 +2178,10 @@ public static Control FindControlRecursive(Control objControl, string strControl /// ----------------------------------------------------------------------------- /// - /// Searches control hierarchy from top down to find a control matching the passed in name + /// Searches control hierarchy from top down to find a control matching the passed in name. /// - /// Root control to begin searching - /// Name of control to look for + /// Root control to begin searching. + /// Name of control to look for. /// /// /// This differs from FindControlRecursive in that it looks down the control hierarchy, whereas, the @@ -2117,6 +2204,7 @@ public static Control FindControlRecursiveDown(Control objParent, string strCont } } } + return objCtl; } @@ -2130,7 +2218,7 @@ public static void SetFormFocus(Control control) { if (control.Page.Request.Browser.EcmaScriptVersion.Major >= 1) { - //JH dnn.js mod + // JH dnn.js mod if (ClientAPI.ClientAPIDisabled() == false) { JavaScript.RegisterClientReference(control.Page, ClientAPI.ClientNamespaceReferences.dnn); @@ -2138,7 +2226,7 @@ public static void SetFormFocus(Control control) } else { - //Create JavaScript + // Create JavaScript var sb = new StringBuilder(); sb.Append(""); + // Register Client Script ClientAPI.RegisterClientScriptBlock(control.Page, "InitialFocus", sb.ToString()); } @@ -2172,36 +2263,45 @@ public static void SetFormFocus(Control control) /// Gets the external request. /// /// The address. - /// Web request + /// Web request. public static HttpWebRequest GetExternalRequest(string Address) { - //Obtain PortalSettings from Current Context + // Obtain PortalSettings from Current Context PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - //Create the request object + + // Create the request object var objRequest = (HttpWebRequest)WebRequest.Create(Address); - //Set a time out to the request ... 10 seconds + + // Set a time out to the request ... 10 seconds objRequest.Timeout = Host.WebRequestTimeout; - //Attach a User Agent to the request + + // Attach a User Agent to the request objRequest.UserAgent = "DotNetNuke"; - //If there is Proxy info, apply it to the request + + // If there is Proxy info, apply it to the request if (!string.IsNullOrEmpty(Host.ProxyServer)) { - //Create a new Proxy + // Create a new Proxy WebProxy Proxy; - //Create a new Network Credentials item + + // Create a new Network Credentials item NetworkCredential ProxyCredentials; - //Fill Proxy info from host settings + + // Fill Proxy info from host settings Proxy = new WebProxy(Host.ProxyServer, Host.ProxyPort); if (!string.IsNullOrEmpty(Host.ProxyUsername)) { - //Fill the credential info from host settings + // Fill the credential info from host settings ProxyCredentials = new NetworkCredential(Host.ProxyUsername, Host.ProxyPassword); - //Apply credentials to proxy + + // Apply credentials to proxy Proxy.Credentials = ProxyCredentials; } - //Apply Proxy to request + + // Apply Proxy to request objRequest.Proxy = Proxy; } + return objRequest; } @@ -2210,38 +2310,47 @@ public static HttpWebRequest GetExternalRequest(string Address) /// /// The address. /// The credentials. - /// Web request + /// Web request. public static HttpWebRequest GetExternalRequest(string Address, NetworkCredential Credentials) { - //Create the request object + // Create the request object var objRequest = (HttpWebRequest)WebRequest.Create(Address); + // Set a time out to the request ... 10 seconds objRequest.Timeout = Host.WebRequestTimeout; + // Attach a User Agent to the request objRequest.UserAgent = "DotNetNuke"; + // Attach supplied credentials if (Credentials.UserName != null) { objRequest.Credentials = Credentials; } + // If there is Proxy info, apply it to the request if (!string.IsNullOrEmpty(Host.ProxyServer)) { // Create a new Proxy WebProxy Proxy; + // Create a new Network Credentials item NetworkCredential ProxyCredentials; + // Fill Proxy info from host settings Proxy = new WebProxy(Host.ProxyServer, Host.ProxyPort); if (!string.IsNullOrEmpty(Host.ProxyUsername)) { // Fill the credential info from host settings ProxyCredentials = new NetworkCredential(Host.ProxyUsername, Host.ProxyPassword); - //Apply credentials to proxy + + // Apply credentials to proxy Proxy.Credentials = ProxyCredentials; } + objRequest.Proxy = Proxy; } + return objRequest; } @@ -2253,6 +2362,7 @@ public static void DeleteFolderRecursive(string strRoot) { FileSystemUtils.DeleteFolderRecursive(strRoot); } + /// /// Deletes the files recursive which match the filter, will not delete folders and will ignore folder which is hidden or system. /// @@ -2263,6 +2373,27 @@ public static void DeleteFilesRecursive(string strRoot, string filter) FileSystemUtils.DeleteFilesRecursive(strRoot, filter); } + /// + /// Cleans the name of the file. + /// + /// Name of the file. + /// clean name. + public static string CleanFileName(string FileName) + { + return CleanFileName(FileName, string.Empty, string.Empty); + } + + /// + /// Cleans the name of the file. + /// + /// Name of the file. + /// The bad chars. + /// clean name. + public static string CleanFileName(string FileName, string BadChars) + { + return CleanFileName(FileName, BadChars, string.Empty); + } + private static void DeleteFile(string filePath) { try @@ -2283,7 +2414,7 @@ private static void DeleteFolder(string strRoot) } catch (IOException) { - //Force Deletion. Directory should be empty + // Force Deletion. Directory should be empty try { Thread.Sleep(50); @@ -2300,50 +2431,32 @@ private static void DeleteFolder(string strRoot) } } - /// - /// Cleans the name of the file. - /// - /// Name of the file. - /// clean name - public static string CleanFileName(string FileName) - { - return CleanFileName(FileName, "", ""); - } - - /// - /// Cleans the name of the file. - /// - /// Name of the file. - /// The bad chars. - /// clean name - public static string CleanFileName(string FileName, string BadChars) - { - return CleanFileName(FileName, BadChars, ""); - } - /// /// Cleans the name of the file. /// /// Name of the file. /// The bad chars. /// The replace char. - /// clean name + /// clean name. public static string CleanFileName(string FileName, string BadChars, string ReplaceChar) { string strFileName = FileName; - if (String.IsNullOrEmpty(BadChars)) + if (string.IsNullOrEmpty(BadChars)) { BadChars = ":/\\?*|" + ((char)34) + ((char)39) + ((char)9); } - if (String.IsNullOrEmpty(ReplaceChar)) + + if (string.IsNullOrEmpty(ReplaceChar)) { ReplaceChar = "_"; } + int intCounter; for (intCounter = 0; intCounter <= BadChars.Length - 1; intCounter++) { strFileName = strFileName.Replace(BadChars.Substring(intCounter, 1), ReplaceChar); } + return strFileName; } @@ -2354,7 +2467,7 @@ public static string CleanFileName(string FileName, string BadChars, string Repl /// /// /// - /// A cleaned string + /// A cleaned string. /// ----------------------------------------------------------------------------- public static string CleanName(string Name) { @@ -2363,8 +2476,9 @@ public static string CleanName(string Name) int intCounter; for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++) { - strName = strName.Replace(strBadChars.Substring(intCounter, 1), ""); + strName = strName.Replace(strBadChars.Substring(intCounter, 1), string.Empty); } + return strName; } @@ -2374,29 +2488,30 @@ public static string CleanName(string Name) /// for use as an XHTML class attribute / CSS class selector value and optionally /// prepends the letter 'A' if the first character is not alphabetic. This differs /// from CreateValidID which replaces invalid characters with an underscore - /// and replaces the first letter with an 'A' if it is not alphabetic + /// and replaces the first letter with an 'A' if it is not alphabetic. /// - /// String to use to create the class value + /// String to use to create the class value. /// If set true, validate whether the first character - /// is alphabetic and, if not, prepend the letter 'A' to the returned value + /// is alphabetic and, if not, prepend the letter 'A' to the returned value. /// /// - /// A string suitable for use as a class value + /// A string suitable for use as a class value. /// ----------------------------------------------------------------------------- public static string CreateValidClass(string inputValue, bool validateFirstChar) { string returnValue = Null.NullString; - //Regex is expensive so we will cache the results in a lookup table - var validClassLookupDictionary = CBO.GetCachedObject>(new CacheItemArgs("ValidClassLookup", 200, CacheItemPriority.NotRemovable), - (CacheItemArgs cacheItemArgs) => new SharedDictionary()); + // Regex is expensive so we will cache the results in a lookup table + var validClassLookupDictionary = CBO.GetCachedObject>( + new CacheItemArgs("ValidClassLookup", 200, CacheItemPriority.NotRemovable), + (CacheItemArgs cacheItemArgs) => new SharedDictionary()); bool idFound = Null.NullBoolean; using (ISharedCollectionLock readLock = validClassLookupDictionary.GetReadLock()) { if (validClassLookupDictionary.ContainsKey(inputValue)) { - //Return value + // Return value returnValue = validClassLookupDictionary[inputValue]; idFound = true; } @@ -2408,29 +2523,29 @@ public static string CreateValidClass(string inputValue, bool validateFirstChar) { if (!validClassLookupDictionary.ContainsKey(inputValue)) { - //Create Valid Class + // Create Valid Class // letters ([a-zA-Z]), digits ([0-9]), hyphens ("-") and underscores ("_") are valid in class values // Remove all characters that aren't in the list returnValue = InvalidCharacters.Replace(inputValue, string.Empty); // If we're asked to validate the first character... - if ((validateFirstChar)) + if (validateFirstChar) { // classes should begin with a letter ([A-Za-z])' // prepend a starting non-letter character with an A - if ((InvalidCharacters.IsMatch(returnValue))) + if (InvalidCharacters.IsMatch(returnValue)) { returnValue = "A" + returnValue; } } - //put in Dictionary + // put in Dictionary validClassLookupDictionary[inputValue] = returnValue; } } } - //Return Value + // Return Value return returnValue; } @@ -2438,21 +2553,22 @@ public static string CreateValidClass(string inputValue, bool validateFirstChar) /// Creates the valid ID. /// /// The input value. - /// String with a valid ID + /// String with a valid ID. public static string CreateValidID(string inputValue) { string returnValue = Null.NullString; - //Regex is expensive so we will cache the results in a lookup table - var validIDLookupDictionary = CBO.GetCachedObject>(new CacheItemArgs("ValidIDLookup", 200, CacheItemPriority.NotRemovable), - (CacheItemArgs cacheItemArgs) => new SharedDictionary()); + // Regex is expensive so we will cache the results in a lookup table + var validIDLookupDictionary = CBO.GetCachedObject>( + new CacheItemArgs("ValidIDLookup", 200, CacheItemPriority.NotRemovable), + (CacheItemArgs cacheItemArgs) => new SharedDictionary()); bool idFound = Null.NullBoolean; using (ISharedCollectionLock readLock = validIDLookupDictionary.GetReadLock()) { if (validIDLookupDictionary.ContainsKey(inputValue)) { - //Return value + // Return value returnValue = validIDLookupDictionary[inputValue]; idFound = true; } @@ -2464,7 +2580,7 @@ public static string CreateValidID(string inputValue) { if (!validIDLookupDictionary.ContainsKey(inputValue)) { - //Create Valid ID + // Create Valid ID // '... letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")' are valid identifiers // We aren't allowing hyphens or periods, even though they're valid, since the previous version of this function didn't // Replace all characters that aren't in the list with an underscore @@ -2474,44 +2590,44 @@ public static string CreateValidID(string inputValue) // replace a starting non-letter character with an A returnValue = InvalidInitialCharacters.Replace(returnValue, "A"); - //put in Dictionary + // put in Dictionary validIDLookupDictionary[inputValue] = returnValue; } } } + return returnValue; } - /// /// Get the URL to show the "access denied" message. /// - /// URL to access denied view + /// URL to access denied view. public static string AccessDeniedURL() { - return AccessDeniedURL(""); + return AccessDeniedURL(string.Empty); } /// /// Get the URL to show the "access denied" message. /// /// The message to display. - /// URL to access denied view + /// URL to access denied view. public static string AccessDeniedURL(string Message) { var navigationManager = DependencyProvider.GetRequiredService(); - string strURL = ""; + string strURL = string.Empty; PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (HttpContext.Current.Request.IsAuthenticated) { - if (String.IsNullOrEmpty(Message)) + if (string.IsNullOrEmpty(Message)) { - //redirect to access denied page + // redirect to access denied page strURL = navigationManager.NavigateURL(_portalSettings.ActiveTab.TabID, "Access Denied"); } else { - //redirect to access denied page with custom message + // redirect to access denied page with custom message var messageGuid = DataProvider.Instance().AddRedirectMessage( _portalSettings.UserId, _portalSettings.ActiveTab.TabID, Message).ToString("N"); strURL = navigationManager.NavigateURL(_portalSettings.ActiveTab.TabID, "Access Denied", "message=" + messageGuid); @@ -2521,54 +2637,57 @@ public static string AccessDeniedURL(string Message) { strURL = LoginURL(HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl), false); } + return strURL; } /// - /// Adds the current request's protocol ("http://" or "https://") to the given URL, if it does not already have a protocol specified + /// Adds the current request's protocol ("http://" or "https://") to the given URL, if it does not already have a protocol specified. /// - /// The URL - /// The formatted URL + /// The URL. + /// The formatted URL. public static string AddHTTP(string strURL) { - if (!String.IsNullOrEmpty(strURL)) + if (!string.IsNullOrEmpty(strURL)) { if (strURL.IndexOf("mailto:") == -1 && strURL.IndexOf("://") == -1 && strURL.IndexOf("~") == -1 && strURL.IndexOf("\\\\") == -1) { strURL = ((HttpContext.Current != null && UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request)) ? "https://" : "http://") + strURL; } } + return strURL; } /// ----------------------------------------------------------------------------- /// - /// Generates the Application root url (including the tab/page) + /// Generates the Application root url (including the tab/page). /// /// - /// This overload assumes the current page + /// This overload assumes the current page. /// - /// The formatted root url + /// The formatted root url. /// ----------------------------------------------------------------------------- public static string ApplicationURL() { PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (_portalSettings != null && _portalSettings.ActiveTab.HasAVisibleVersion) { - return (ApplicationURL(_portalSettings.ActiveTab.TabID)); + return ApplicationURL(_portalSettings.ActiveTab.TabID); } - return (ApplicationURL(-1)); + + return ApplicationURL(-1); } /// ----------------------------------------------------------------------------- /// - /// Generates the Application root url (including the tab/page) + /// Generates the Application root url (including the tab/page). /// /// - /// This overload takes the tabid (page id) as a parameter + /// This overload takes the tabid (page id) as a parameter. /// - /// The id of the tab/page - /// The formatted root url + /// The id of the tab/page. + /// The formatted root url. /// ----------------------------------------------------------------------------- public static string ApplicationURL(int TabID) { @@ -2577,6 +2696,7 @@ public static string ApplicationURL(int TabID) { strURL += "?tabid=" + TabID; } + return strURL; } @@ -2589,7 +2709,7 @@ public static string ApplicationURL(int TabID) /// Formatted URL. public static string FormatHelpUrl(string HelpUrl, PortalSettings objPortalSettings, string Name) { - return FormatHelpUrl(HelpUrl, objPortalSettings, Name, ""); + return FormatHelpUrl(HelpUrl, objPortalSettings, Name, string.Empty); } /// @@ -2611,7 +2731,8 @@ public static string FormatHelpUrl(string HelpUrl, PortalSettings objPortalSetti { strURL += "?helpculture="; } - if (!String.IsNullOrEmpty(Thread.CurrentThread.CurrentUICulture.ToString().ToLowerInvariant())) + + if (!string.IsNullOrEmpty(Thread.CurrentThread.CurrentUICulture.ToString().ToLowerInvariant())) { strURL += Thread.CurrentThread.CurrentUICulture.ToString().ToLowerInvariant(); } @@ -2619,14 +2740,17 @@ public static string FormatHelpUrl(string HelpUrl, PortalSettings objPortalSetti { strURL += objPortalSettings.DefaultLanguage.ToLowerInvariant(); } - if (!String.IsNullOrEmpty(Name)) + + if (!string.IsNullOrEmpty(Name)) { strURL += "&helpmodule=" + HttpUtility.UrlEncode(Name); } - if (!String.IsNullOrEmpty(Version)) + + if (!string.IsNullOrEmpty(Version)) { strURL += "&helpversion=" + HttpUtility.UrlEncode(Version); } + return AddHTTP(strURL); } @@ -2634,26 +2758,26 @@ public static string FormatHelpUrl(string HelpUrl, PortalSettings objPortalSetti /// Generates the correctly formatted friendly URL. /// /// - /// Assumes Default.aspx, and that portalsettings are saved to Context + /// Assumes Default.aspx, and that portalsettings are saved to Context. /// - /// The current tab + /// The current tab. /// The path to format. - /// The formatted (friendly) URL + /// The formatted (friendly) URL. public static string FriendlyUrl(TabInfo tab, string path) { return FriendlyUrl(tab, path, glbDefaultPage); } /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// /// This overload includes an optional page to include in the url. /// - /// The current tab + /// The current tab. /// The path to format. /// The page to include in the url. - /// The formatted (friendly) URL + /// The formatted (friendly) URL. public static string FriendlyUrl(TabInfo tab, string path, string pageName) { PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -2661,15 +2785,15 @@ public static string FriendlyUrl(TabInfo tab, string path, string pageName) } /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// - /// This overload includes the portal settings for the site + /// This overload includes the portal settings for the site. /// - /// The current tab + /// The current tab. /// The path to format. - /// The portal settings - /// The formatted (friendly) URL + /// The portal settings. + /// The formatted (friendly) URL. [Obsolete("Deprecated in Platform 9.4.3. Scheduled for removal in v11.0.0. Use the IPortalSettings overload")] public static string FriendlyUrl(TabInfo tab, string path, PortalSettings settings) { @@ -2677,32 +2801,32 @@ public static string FriendlyUrl(TabInfo tab, string path, PortalSettings settin } /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// - /// This overload includes the portal settings for the site + /// This overload includes the portal settings for the site. /// - /// The current tab + /// The current tab. /// The path to format. - /// The portal settings - /// The formatted (friendly) URL + /// The portal settings. + /// The formatted (friendly) URL. public static string FriendlyUrl(TabInfo tab, string path, IPortalSettings settings) { return FriendlyUrl(tab, path, glbDefaultPage, settings); } /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// /// This overload includes an optional page to include in the URL, and the portal - /// settings for the site + /// settings for the site. /// - /// The current tab + /// The current tab. /// The path to format. /// The page to include in the URL. - /// The portal settings - /// The formatted (friendly) url + /// The portal settings. + /// The formatted (friendly) url. [Obsolete("Deprecated in Platform 9.4.3. Scheduled for removal in v11.0.0. Use the IPortalSettings overload")] public static string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings) { @@ -2710,34 +2834,34 @@ public static string FriendlyUrl(TabInfo tab, string path, string pageName, Port } /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// /// This overload includes an optional page to include in the URL, and the portal - /// settings for the site + /// settings for the site. /// - /// The current tab + /// The current tab. /// The path to format. /// The page to include in the URL. - /// The portal settings - /// The formatted (friendly) url + /// The portal settings. + /// The formatted (friendly) url. public static string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings) { return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, settings); } /// - /// Generates the correctly formatted friendly url + /// Generates the correctly formatted friendly url. /// /// /// This overload includes an optional page to include in the url, and the portal - /// alias for the site + /// alias for the site. /// - /// The current tab + /// The current tab. /// The path to format. /// The page to include in the URL. - /// The portal alias for the site - /// The formatted (friendly) URL + /// The portal alias for the site. + /// The formatted (friendly) URL. public static string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) { return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, portalAlias); @@ -2745,31 +2869,35 @@ public static string FriendlyUrl(TabInfo tab, string path, string pageName, stri /// ----------------------------------------------------------------------------- /// - /// Returns the type of URl (T=other tab, F=file, U=URL, N=normal) + /// Returns the type of URl (T=other tab, F=file, U=URL, N=normal). /// /// /// - /// The url - /// The url type + /// The url. + /// The url type. /// ----------------------------------------------------------------------------- public static TabType GetURLType(string URL) { - if (String.IsNullOrEmpty(URL)) + if (string.IsNullOrEmpty(URL)) { return TabType.Normal; } + if (URL.ToLowerInvariant().StartsWith("mailto:") == false && URL.IndexOf("://") == -1 && URL.StartsWith("~") == false && URL.StartsWith("\\\\") == false && URL.StartsWith("/") == false) { if (NumberMatchRegex.IsMatch(URL)) { return TabType.Tab; } + if (URL.ToLowerInvariant().StartsWith("userid=")) { return TabType.Member; } + return TabType.File; } + return TabType.Url; } @@ -2777,11 +2905,11 @@ public static TabType GetURLType(string URL) /// Url's as internal links to Files, Tabs and Users should only be imported if /// those files, tabs and users exist. This function parses the url, and checks /// whether the internal links exist. - /// If the link does not exist, the function will return an empty string + /// If the link does not exist, the function will return an empty string. /// - /// Integer - /// String - /// If an internal link does not exist, an empty string is returned, otherwise the passed in url is returned as is + /// Integer. + /// String. + /// If an internal link does not exist, an empty string is returned, otherwise the passed in url is returned as is. public static string ImportUrl(int ModuleId, string url) { string strUrl = url; @@ -2791,52 +2919,56 @@ public static string ImportUrl(int ModuleId, string url) switch (urlType) { case TabType.File: - if (Int32.TryParse(url.Replace("FileID=", ""), out intId)) + if (int.TryParse(url.Replace("FileID=", string.Empty), out intId)) { var objFile = FileManager.Instance.GetFile(intId); if (objFile == null) { - //fileId does not exist in the portal - strUrl = ""; + // fileId does not exist in the portal + strUrl = string.Empty; } } else { - //failed to get fileId - strUrl = ""; + // failed to get fileId + strUrl = string.Empty; } + break; case TabType.Member: - if (Int32.TryParse(url.Replace("UserID=", ""), out intId)) + if (int.TryParse(url.Replace("UserID=", string.Empty), out intId)) { if (UserController.GetUserById(portalSettings.PortalId, intId) == null) { - //UserId does not exist for this portal - strUrl = ""; + // UserId does not exist for this portal + strUrl = string.Empty; } } else { - //failed to get UserId - strUrl = ""; + // failed to get UserId + strUrl = string.Empty; } + break; case TabType.Tab: - if (Int32.TryParse(url, out intId)) + if (int.TryParse(url, out intId)) { if (TabController.Instance.GetTab(intId, portalSettings.PortalId, false) == null) { - //the tab does not exist - strUrl = ""; + // the tab does not exist + strUrl = string.Empty; } } else { - //failed to get TabId - strUrl = ""; + // failed to get TabId + strUrl = string.Empty; } + break; } + return strUrl; } @@ -2866,7 +2998,8 @@ public static string LoginURL(string returnUrl, bool overrideSetting, PortalSett { returnUrl = string.Format("returnurl={0}", returnUrl); } - var popUpParameter = ""; + + var popUpParameter = string.Empty; if (HttpUtility.UrlDecode(returnUrl).IndexOf("popUp=true", StringComparison.OrdinalIgnoreCase) >= 0) { popUpParameter = "popUp=true"; @@ -2877,13 +3010,14 @@ public static string LoginURL(string returnUrl, bool overrideSetting, PortalSett if (ValidateLoginTabID(portalSettings.LoginTabId)) { loginUrl = string.IsNullOrEmpty(returnUrl) - ? navigationManager.NavigateURL(portalSettings.LoginTabId, "", popUpParameter) - : navigationManager.NavigateURL(portalSettings.LoginTabId, "", returnUrl, popUpParameter); + ? navigationManager.NavigateURL(portalSettings.LoginTabId, string.Empty, popUpParameter) + : navigationManager.NavigateURL(portalSettings.LoginTabId, string.Empty, returnUrl, popUpParameter); } else { string strMessage = string.Format("error={0}", Localization.GetString("NoLoginControl", Localization.GlobalResourceFile)); - //No account module so use portal tab + + // No account module so use portal tab loginUrl = string.IsNullOrEmpty(returnUrl) ? navigationManager.NavigateURL(portalSettings.ActiveTab.TabID, "Login", strMessage, popUpParameter) : navigationManager.NavigateURL(portalSettings.ActiveTab.TabID, "Login", returnUrl, strMessage, popUpParameter); @@ -2891,11 +3025,12 @@ public static string LoginURL(string returnUrl, bool overrideSetting, PortalSett } else { - //portal tab + // portal tab loginUrl = string.IsNullOrEmpty(returnUrl) ? navigationManager.NavigateURL(portalSettings.ActiveTab.TabID, "Login", popUpParameter) : navigationManager.NavigateURL(portalSettings.ActiveTab.TabID, "Login", returnUrl, popUpParameter); } + return loginUrl; } @@ -2906,10 +3041,10 @@ public static string LoginURL(string returnUrl, bool overrideSetting, PortalSett /// Formatted url. public static string UserProfileURL(int userId) { - string strURL = ""; + string strURL = string.Empty; PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - strURL = DependencyProvider.GetRequiredService().NavigateURL(portalSettings.UserTabId, "", string.Format("userId={0}", userId)); + strURL = DependencyProvider.GetRequiredService().NavigateURL(portalSettings.UserTabId, string.Empty, string.Format("userId={0}", userId)); return strURL; } @@ -2918,7 +3053,8 @@ public static string UserProfileURL(int userId) /// Gets the URL to the current page. /// /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL() { @@ -2930,7 +3066,8 @@ public static string NavigateURL() /// /// The tab ID. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(int tabID) { @@ -2943,7 +3080,8 @@ public static string NavigateURL(int tabID) /// The tab ID. /// if set to true the page is a "super-tab," i.e. a host-level page. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(int tabID, bool isSuperTab) { @@ -2955,7 +3093,8 @@ public static string NavigateURL(int tabID, bool isSuperTab) /// /// The control key, or or null. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(string controlKey) { @@ -2968,7 +3107,8 @@ public static string NavigateURL(string controlKey) /// The control key, or or null. /// Any additional parameters, in "key=value" format. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(string controlKey, params string[] additionalParameters) { @@ -2981,7 +3121,8 @@ public static string NavigateURL(string controlKey, params string[] additionalPa /// The tab ID. /// The control key, or or null. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(int tabID, string controlKey) { @@ -2995,7 +3136,8 @@ public static string NavigateURL(int tabID, string controlKey) /// The control key, or or null. /// Any additional parameters. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(int tabID, string controlKey, params string[] additionalParameters) { @@ -3010,7 +3152,8 @@ public static string NavigateURL(int tabID, string controlKey, params string[] a /// The control key, or or null. /// Any additional parameters. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(int tabID, PortalSettings settings, string controlKey, params string[] additionalParameters) { @@ -3026,7 +3169,8 @@ public static string NavigateURL(int tabID, PortalSettings settings, string cont /// The control key, or or null. /// Any additional parameters. /// Formatted URL. - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] public static string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, params string[] additionalParameters) { @@ -3067,10 +3211,10 @@ public static string NavigateURL(int tabID, bool isSuperTab, PortalSettings sett } /// - /// UrlEncode query string + /// UrlEncode query string. /// /// The query string. - /// Encoded content + /// Encoded content. public static string QueryStringEncode(string QueryString) { QueryString = HttpUtility.UrlEncode(QueryString); @@ -3078,10 +3222,10 @@ public static string QueryStringEncode(string QueryString) } /// - /// UrlDecode query string + /// UrlDecode query string. /// /// The query string. - /// Decoded content + /// Decoded content. public static string QueryStringDecode(string QueryString) { QueryString = HttpUtility.UrlDecode(QueryString); @@ -3094,11 +3238,13 @@ public static string QueryStringDecode(string QueryString) { Exceptions.ProcessHttpException(exc); } + string strDoubleDecodeURL = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Server.UrlDecode(QueryString)); if (QueryString.IndexOf("..") != -1 || strDoubleDecodeURL.IndexOf("..") != -1) { Exceptions.ProcessHttpException(); } + return QueryString; } @@ -3113,54 +3259,60 @@ public static string RegisterURL(string returnURL, string originalURL) var navigationManager = DependencyProvider.GetRequiredService(); string strURL; PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - string extraParams = String.Empty; + string extraParams = string.Empty; if (!string.IsNullOrEmpty(returnURL)) { extraParams = string.Concat("returnurl=", returnURL); } + if (!string.IsNullOrEmpty(originalURL)) { extraParams += string.Concat("&orignalurl=", originalURL); } + if (_portalSettings.RegisterTabId != -1) { - //user defined tab - strURL = navigationManager.NavigateURL(_portalSettings.RegisterTabId, "", extraParams); + // user defined tab + strURL = navigationManager.NavigateURL(_portalSettings.RegisterTabId, string.Empty, extraParams); } else { strURL = navigationManager.NavigateURL(_portalSettings.ActiveTab.TabID, "Register", extraParams); } + return strURL; } /// ----------------------------------------------------------------------------- /// - /// Generates the correctly formatted url + /// Generates the correctly formatted url. /// /// /// /// The url to format. - /// The formatted (resolved) url + /// The formatted (resolved) url. /// ----------------------------------------------------------------------------- public static string ResolveUrl(string url) { // String is Empty, just return Url - if (String.IsNullOrEmpty(url)) + if (string.IsNullOrEmpty(url)) { return url; } + // String does not contain a ~, so just return Url - if ((url.StartsWith("~") == false)) + if (url.StartsWith("~") == false) { return url; } + // There is just the ~ in the Url, return the appPath - if ((url.Length == 1)) + if (url.Length == 1) { return ApplicationPath; } - if ((url.ToCharArray()[1] == '/' || url.ToCharArray()[1] == '\\')) + + if (url.ToCharArray()[1] == '/' || url.ToCharArray()[1] == '\\') { // Url looks like ~/ or ~\ if (!string.IsNullOrEmpty(ApplicationPath) && ApplicationPath.Length > 1) @@ -3190,7 +3342,7 @@ public static string ResolveUrl(string url) /// Encodes the reserved characters. /// /// The query string. - /// Encoded content + /// Encoded content. public static string EncodeReservedCharacters(string QueryString) { QueryString = QueryString.Replace("$", "%24"); @@ -3242,7 +3394,7 @@ public static string GetHashValue(object HashObject, string DefaultValue) { if (HashObject != null) { - if (!String.IsNullOrEmpty(HashObject.ToString())) + if (!string.IsNullOrEmpty(HashObject.ToString())) { return Convert.ToString(HashObject); } @@ -3266,7 +3418,7 @@ public static string GetHashValue(object HashObject, string DefaultValue) /// Formatted url. public static string LinkClick(string Link, int TabID, int ModuleID) { - return LinkClick(Link, TabID, ModuleID, true, ""); + return LinkClick(Link, TabID, ModuleID, true, string.Empty); } /// @@ -3279,7 +3431,7 @@ public static string LinkClick(string Link, int TabID, int ModuleID) /// Formatted url. public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks) { - return LinkClick(Link, TabID, ModuleID, TrackClicks, ""); + return LinkClick(Link, TabID, ModuleID, TrackClicks, string.Empty); } /// @@ -3293,7 +3445,7 @@ public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackC /// Formatted url. public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks, string ContentType) { - return LinkClick(Link, TabID, ModuleID, TrackClicks, !String.IsNullOrEmpty(ContentType)); + return LinkClick(Link, TabID, ModuleID, TrackClicks, !string.IsNullOrEmpty(ContentType)); } /// @@ -3325,7 +3477,7 @@ public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackC /// Formatted url. public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks, bool ForceDownload, int PortalId, bool EnableUrlLanguage, string portalGuid) { - string strLink = ""; + string strLink = string.Empty; TabType UrlType = GetURLType(Link); if (UrlType == TabType.Member) { @@ -3333,40 +3485,46 @@ public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackC } else if (TrackClicks || ForceDownload || UrlType == TabType.File) { - //format LinkClick wrapper + // format LinkClick wrapper if (Link.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) { strLink = ApplicationPath + "/LinkClick.aspx?fileticket=" + UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(Link), portalGuid); - if (PortalId == Null.NullInteger) //To track Host files + if (PortalId == Null.NullInteger) // To track Host files { strLink += "&hf=1"; } } - if (String.IsNullOrEmpty(strLink)) + + if (string.IsNullOrEmpty(strLink)) { strLink = ApplicationPath + "/LinkClick.aspx?link=" + HttpUtility.UrlEncode(Link); } + // tabid is required to identify the portal where the click originated if (TabID != Null.NullInteger) { strLink += "&tabid=" + TabID; } - //append portal id to query string to identity portal the click originated. - if(PortalId != Null.NullInteger) + + // append portal id to query string to identity portal the click originated. + if (PortalId != Null.NullInteger) { strLink += "&portalid=" + PortalId; } + // moduleid is used to identify the module where the url is stored if (ModuleID != -1) { strLink += "&mid=" + ModuleID; } - //only add language to url if more than one locale is enabled, and if admin did not turn it off + + // only add language to url if more than one locale is enabled, and if admin did not turn it off if (LocaleController.Instance.GetLocales(PortalId).Count > 1 && EnableUrlLanguage) { strLink += "&language=" + Thread.CurrentThread.CurrentCulture.Name; } - //force a download dialog + + // force a download dialog if (ForceDownload) { strLink += "&forcedownload=true"; @@ -3384,6 +3542,7 @@ public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackC break; } } + return strLink; } @@ -3391,7 +3550,7 @@ public static string LinkClick(string Link, int TabID, int ModuleID, bool TrackC /// Gets the name of the role. /// /// The role ID. - /// Role Name + /// Role Name. public static string GetRoleName(int RoleID) { switch (Convert.ToString(RoleID)) @@ -3401,11 +3560,13 @@ public static string GetRoleName(int RoleID) case glbRoleUnauthUser: return glbRoleUnauthUserName; } + Hashtable htRoles = null; if (Host.PerformanceSetting != PerformanceSettings.NoCaching) { htRoles = (Hashtable)DataCache.GetCache("GetRoles"); } + if (htRoles == null) { var roles = RoleController.Instance.GetRoles(Null.NullInteger, r => r.SecurityMode != SecurityMode.SocialGroup); @@ -3416,11 +3577,13 @@ public static string GetRoleName(int RoleID) RoleInfo role = roles[i]; htRoles.Add(role.RoleID, role.RoleName); } + if (Host.PerformanceSetting != PerformanceSettings.NoCaching) { DataCache.SetCache("GetRoles", htRoles); } } + return Convert.ToString(htRoles[RoleID]); } @@ -3434,7 +3597,7 @@ public static XmlNode GetContent(string Content, string ContentType) { var xmlDoc = new XmlDocument { XmlResolver = null }; xmlDoc.LoadXml(Content); - if (String.IsNullOrEmpty(ContentType)) + if (string.IsNullOrEmpty(ContentType)) { return xmlDoc.DocumentElement; } @@ -3446,13 +3609,13 @@ public static XmlNode GetContent(string Content, string ContentType) /// ----------------------------------------------------------------------------- /// - /// GenerateTabPath generates the TabPath used in Friendly URLS + /// GenerateTabPath generates the TabPath used in Friendly URLS. /// /// /// - /// The Id of the Parent Tab - /// The Name of the current Tab - /// The TabPath + /// The Id of the Parent Tab. + /// The Name of the current Tab. + /// The TabPath. /// ----------------------------------------------------------------------------- public static string GenerateTabPath(int parentId, string tabName) { @@ -3488,11 +3651,12 @@ public static string GetHelpText(int moduleControlId) { string FileName = Path.GetFileName(objModuleControl.ControlSrc); string LocalResourceFile = objModuleControl.ControlSrc.Replace(FileName, Localization.LocalResourceDirectory + "/" + FileName); - if (!String.IsNullOrEmpty(Localization.GetString(ModuleActionType.HelpText, LocalResourceFile))) + if (!string.IsNullOrEmpty(Localization.GetString(ModuleActionType.HelpText, LocalResourceFile))) { helpText = Localization.GetString(ModuleActionType.HelpText, LocalResourceFile); } } + return helpText; } @@ -3506,20 +3670,22 @@ public static string GetOnLineHelp(string HelpUrl, ModuleInfo moduleConfig) { if (string.IsNullOrEmpty(HelpUrl)) { - //bool isAdminModule = moduleConfig.DesktopModule.IsAdmin; - //string ctlString = Convert.ToString(HttpContext.Current.Request.QueryString["ctl"]); - //if (((Host.EnableModuleOnLineHelp && !isAdminModule) || (isAdminModule))) - //{ + // bool isAdminModule = moduleConfig.DesktopModule.IsAdmin; + // string ctlString = Convert.ToString(HttpContext.Current.Request.QueryString["ctl"]); + // if (((Host.EnableModuleOnLineHelp && !isAdminModule) || (isAdminModule))) + // { // if ((isAdminModule) || (IsAdminControl() && ctlString == "Module") || (IsAdminControl() && ctlString == "Tab")) // { // HelpUrl = Host.HelpURL; // } - //} - //else - //{ + // } + // else + // { HelpUrl = Host.HelpURL; - //} + + // } } + return HelpUrl; } @@ -3530,79 +3696,50 @@ public static string GetOnLineHelp(string HelpUrl, ModuleInfo moduleConfig) /// true if the tab contains "Account Login" module, otherwise, false. public static bool ValidateLoginTabID(int tabId) { - return ValidateModuleInTab(tabId, "Account Login"); + return ValidateModuleInTab(tabId, "Account Login"); } - /// - /// Check whether the tab contains specific module. - /// - /// The tab id. - /// The module need to check. - /// true if the tab contains the module, otherwise, false. - public static bool ValidateModuleInTab(int tabId, string moduleName) - { - bool hasModule = Null.NullBoolean; + /// + /// Check whether the tab contains specific module. + /// + /// The tab id. + /// The module need to check. + /// true if the tab contains the module, otherwise, false. + public static bool ValidateModuleInTab(int tabId, string moduleName) + { + bool hasModule = Null.NullBoolean; foreach (ModuleInfo objModule in ModuleController.Instance.GetTabModules(tabId).Values) { - if (objModule.ModuleDefinition.FriendlyName == moduleName) + if (objModule.ModuleDefinition.FriendlyName == moduleName) { - //We need to ensure that Anonymous Users or All Users have View permissions to the login page + // We need to ensure that Anonymous Users or All Users have View permissions to the login page TabInfo tab = TabController.Instance.GetTab(tabId, objModule.PortalID, false); if (TabPermissionController.CanViewPage(tab)) { - hasModule = true; + hasModule = true; break; } } } - return hasModule; - } - /// - /// Check whether the Filename matches extensions. - /// - /// The filename. - /// The valid extensions. - /// true if the Filename matches extensions, otherwise, false. - private static bool FilenameMatchesExtensions(string filename, string strExtensions) - { - bool result = string.IsNullOrEmpty(strExtensions); - if (!result) - { - filename = filename.ToUpper(); - strExtensions = strExtensions.ToUpper(); - foreach (string extension in strExtensions.Split(',')) - { - string ext = extension.Trim(); - if (!ext.StartsWith(".")) - { - ext = "." + extension; - } - result = filename.EndsWith(extension); - if (result) - { - break; - } - } - } - return result; + return hasModule; } /// ----------------------------------------------------------------------------- /// - /// DeserializeHashTableBase64 deserializes a Hashtable using Binary Formatting + /// DeserializeHashTableBase64 deserializes a Hashtable using Binary Formatting. /// /// /// While this method of serializing is no longer supported (due to Medium Trust /// issue, it is still required for upgrade purposes. /// - /// The String Source to deserialize - /// The deserialized Hashtable + /// The String Source to deserialize. + /// The deserialized Hashtable. /// ----------------------------------------------------------------------------- public static Hashtable DeserializeHashTableBase64(string Source) { Hashtable objHashTable; - if (!String.IsNullOrEmpty(Source)) + if (!string.IsNullOrEmpty(Source)) { byte[] bits = Convert.FromBase64String(Source); using (var mem = new MemoryStream(bits)) @@ -3610,7 +3747,7 @@ public static Hashtable DeserializeHashTableBase64(string Source) var bin = new BinaryFormatter(); try { - objHashTable = (Hashtable) bin.Deserialize(mem); + objHashTable = (Hashtable)bin.Deserialize(mem); } catch (Exception exc) { @@ -3618,6 +3755,7 @@ public static Hashtable DeserializeHashTableBase64(string Source) objHashTable = new Hashtable(); } + mem.Close(); } } @@ -3625,34 +3763,67 @@ public static Hashtable DeserializeHashTableBase64(string Source) { objHashTable = new Hashtable(); } + return objHashTable; } /// ----------------------------------------------------------------------------- /// - /// DeserializeHashTableXml deserializes a Hashtable using Xml Serialization + /// DeserializeHashTableXml deserializes a Hashtable using Xml Serialization. /// /// - /// This is the preferred method of serialization under Medium Trust + /// This is the preferred method of serialization under Medium Trust. /// - /// The String Source to deserialize - /// The deserialized Hashtable + /// The String Source to deserialize. + /// The deserialized Hashtable. /// ----------------------------------------------------------------------------- public static Hashtable DeserializeHashTableXml(string Source) { return XmlUtils.DeSerializeHashtable(Source, "profile"); } + /// + /// Check whether the Filename matches extensions. + /// + /// The filename. + /// The valid extensions. + /// true if the Filename matches extensions, otherwise, false. + private static bool FilenameMatchesExtensions(string filename, string strExtensions) + { + bool result = string.IsNullOrEmpty(strExtensions); + if (!result) + { + filename = filename.ToUpper(); + strExtensions = strExtensions.ToUpper(); + foreach (string extension in strExtensions.Split(',')) + { + string ext = extension.Trim(); + if (!ext.StartsWith(".")) + { + ext = "." + extension; + } + + result = filename.EndsWith(extension); + if (result) + { + break; + } + } + } + + return result; + } + /// ----------------------------------------------------------------------------- /// - /// SerializeHashTableBase64 serializes a Hashtable using Binary Formatting + /// SerializeHashTableBase64 serializes a Hashtable using Binary Formatting. /// /// /// While this method of serializing is no longer supported (due to Medium Trust /// issue, it is still required for upgrade purposes. /// - /// The Hashtable to serialize - /// The serialized String + /// The Hashtable to serialize. + /// The serialized String. /// ----------------------------------------------------------------------------- public static string SerializeHashTableBase64(Hashtable Source) { @@ -3670,7 +3841,7 @@ public static string SerializeHashTableBase64(Hashtable Source) { Logger.Error(exc); - strString = ""; + strString = string.Empty; } finally { @@ -3679,20 +3850,21 @@ public static string SerializeHashTableBase64(Hashtable Source) } else { - strString = ""; + strString = string.Empty; } + return strString; } /// ----------------------------------------------------------------------------- /// - /// SerializeHashTableXml serializes a Hashtable using Xml Serialization + /// SerializeHashTableXml serializes a Hashtable using Xml Serialization. /// /// - /// This is the preferred method of serialization under Medium Trust + /// This is the preferred method of serialization under Medium Trust. /// - /// The Hashtable to serialize - /// The serialized String + /// The Hashtable to serialize. + /// The serialized String. /// ----------------------------------------------------------------------------- public static string SerializeHashTableXml(Hashtable Source) { @@ -3713,17 +3885,17 @@ public static bool IsHostTab(int tabId) { isHostTab = hostTabs.Any(t => t.Value.TabID == tabId); } + return isHostTab; } - /// /// Return User Profile Picture Formatted Url. UserId, width and height can be passed to build a formatted Avatar Url. /// - /// Formatted url, e.g. http://www.mysite.com/DnnImageHandler.ashx?mode=profilepic&userid={0}&h={1}&w={2} + /// Formatted url, e.g. http://www.mysite.com/DnnImageHandler.ashx?mode=profilepic&userid={0}&h={1}&w={2}. /// /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicFormattedUrl(), userInfo.UserID, 32, 32) + /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicFormattedUrl(), userInfo.UserID, 32, 32). /// [Obsolete("Obsoleted in DNN 7.3.0 as it causes issues in SSL-offloading scenarios - please use UserProfilePicRelativeUrl instead.. Scheduled removal in v11.0.0.")] public static string UserProfilePicFormattedUrl() @@ -3733,10 +3905,12 @@ public static string UserProfilePicFormattedUrl() { avatarUrl = HttpContext.Current.Request.Url.Host; } - avatarUrl = string.Format("{0}://{1}{2}", - UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request) ? "https" : "http", - avatarUrl, - !HttpContext.Current.Request.Url.IsDefaultPort && !avatarUrl.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty); + + avatarUrl = string.Format( + "{0}://{1}{2}", + UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request) ? "https" : "http", + avatarUrl, + !HttpContext.Current.Request.Url.IsDefaultPort && !avatarUrl.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty); avatarUrl += "/DnnImageHandler.ashx?mode=profilepic&userId={0}&h={1}&w={2}"; @@ -3746,10 +3920,10 @@ public static string UserProfilePicFormattedUrl() /// /// Return User Profile Picture relative Url. UserId, width and height can be passed to build a formatted relative Avatar Url. /// - /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal + /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal. /// /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32) + /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). /// [Obsolete("Deprecated in Platform 8.0.0. Please use UserController.Instance.GetUserProfilePictureUrl. Scheduled removal in v11.0.0.")] public static string UserProfilePicRelativeUrl() @@ -3761,10 +3935,10 @@ public static string UserProfilePicRelativeUrl() /// Return User Profile Picture relative Url. UserId, width and height can be passed to build a formatted relative Avatar Url. /// /// Indicates if cdv (Cache Delayed Verification) has to be included in the returned URL. - /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal + /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal. /// /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32) + /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). /// [Obsolete("Deprecated in Platform 8.0.0. Please use UserController.Instance.GetUserProfilePictureUrl. Scheduled removal in v11.0.0.")] public static string UserProfilePicRelativeUrl(bool includeCdv) @@ -3772,29 +3946,25 @@ public static string UserProfilePicRelativeUrl(bool includeCdv) const string query = "/DnnImageHandler.ashx?mode=profilepic&userId={0}&h={1}&w={2}"; var currentAlias = GetPortalSettings().PortalAlias.HTTPAlias; var index = currentAlias.IndexOf('/'); - var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : ""; + var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : string.Empty; - var cdv = ""; + var cdv = string.Empty; if (includeCdv) { cdv = "&cdv=" + DateTime.Now.Ticks; } if (childPortalAlias.StartsWith(ApplicationPath)) + { return childPortalAlias + query + cdv; + } return ApplicationPath + childPortalAlias + query + cdv; - } - #region "Obsolete - retained for Binary Compatability" - // **************************************************************************************** // Constants are inlined in code and would require a rebuild of any module or skinobject // that may be using these constants. - - #region "Html functions moved to HtmlUtils.vb" - [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatEmail. Scheduled removal in v11.0.0.")] public static string FormatEmail(string Email) { @@ -3807,18 +3977,12 @@ public static string FormatWebsite(object Website) return HtmlUtils.FormatWebsite(Website); } - #endregion - - #region "Xml functions moved to XmlUtils.vb" - [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.XmlUtils.XMLEncode. Scheduled removal in v11.0.0.")] public static string XMLEncode(string HTML) { return XmlUtils.XMLEncode(HTML); } - #endregion - [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.Config.GetConnectionString. Scheduled removal in v11.0.0.")] public static string GetDBConnectionString() { @@ -3828,14 +3992,14 @@ public static string GetDBConnectionString() [Obsolete("This method has been deprecated. . Scheduled removal in v11.0.0.")] public static ArrayList GetFileList(DirectoryInfo CurrentDirectory, [Optional, DefaultParameterValue("")] // ERROR: Optional parameters aren't supported in C# string strExtensions, [Optional, DefaultParameterValue(true)] // ERROR: Optional parameters aren't supported in C# - bool NoneSpecified) + bool NoneSpecified) { var arrFileList = new ArrayList(); - string strExtension = ""; + string strExtension = string.Empty; if (NoneSpecified) { - arrFileList.Add(new FileItem("", "<" + Localization.GetString("None_Specified") + ">")); + arrFileList.Add(new FileItem(string.Empty, "<" + Localization.GetString("None_Specified") + ">")); } string File = null; @@ -3847,6 +4011,7 @@ public static ArrayList GetFileList(DirectoryInfo CurrentDirectory, [Optional, D { strExtension = File.Substring(File.LastIndexOf(".") + 1); } + string FileName = File.Substring(CurrentDirectory.FullName.Length); if (strExtensions.IndexOf(strExtension, StringComparison.InvariantCultureIgnoreCase) != -1 || string.IsNullOrEmpty(strExtensions)) { @@ -3871,6 +4036,7 @@ public static string GetSubFolderPath(string strFileNamePath) { ParentFolderName = _portalSettings.HomeDirectoryMapPath.Replace("/", "\\"); } + string strFolderpath = strFileNamePath.Substring(0, strFileNamePath.LastIndexOf("\\") + 1); return strFolderpath.Substring(ParentFolderName.Length).Replace("\\", "/"); @@ -3886,24 +4052,12 @@ public static string LinkClickURL(string Link) [Obsolete("Deprecated PreventSQLInjection Function to consolidate Security Filter functions in the PortalSecurity class. Scheduled removal in v11.0.0.")] public static string PreventSQLInjection(string strSQL) { - return (PortalSecurity.Instance).InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL); + return PortalSecurity.Instance.InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL); } - #endregion - - private static readonly Stopwatch AppStopwatch = Stopwatch.StartNew(); - internal static void ResetAppStartElapseTime() { AppStopwatch.Restart(); } - - public static TimeSpan ElapsedSinceAppStart - { - get - { - return AppStopwatch.Elapsed; - } - } } } diff --git a/DNN Platform/Library/Common/Guard.cs b/DNN Platform/Library/Common/Guard.cs index a8c43e9ae49..800ad1b3a27 100644 --- a/DNN Platform/Library/Common/Guard.cs +++ b/DNN Platform/Library/Common/Guard.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common { - /// Specifies that a certain condition is an error + using System; + using System.Globalization; + + /// Specifies that a certain condition is an error. public static class Guard { /// @@ -24,7 +19,7 @@ public static class Guard /// placeholders, like ). /// /// An array of objects to fill in the placeholders in . - /// When is true + /// When is true. public static void Against(bool condition, string message, params object[] args) { Against(condition, string.Format(CultureInfo.CurrentUICulture, message, args)); @@ -36,10 +31,10 @@ public static void Against(bool condition, string message, params object[] args) /// /// if set to true, throws an . /// A message that describes the error condition. - /// When is true + /// When is true. public static void Against(bool condition, string message) { - if ((condition)) + if (condition) { throw new InvalidOperationException(message); } diff --git a/DNN Platform/Library/Common/HttpContextSource.cs b/DNN Platform/Library/Common/HttpContextSource.cs index fd9fbcfcaa0..368b57031ca 100644 --- a/DNN Platform/Library/Common/HttpContextSource.cs +++ b/DNN Platform/Library/Common/HttpContextSource.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common { + using System; + using System.Web; + /// - /// A unit testable alternative to HttpContext.Current + /// A unit testable alternative to HttpContext.Current. /// public class HttpContextSource { private static HttpContextBase _fakeContext; /// - /// Gets the current HttpContext + /// Gets the current HttpContext. /// public static HttpContextBase Current { @@ -30,14 +30,15 @@ public static HttpContextBase Current { return new HttpContextWrapper(HttpContext.Current); } + return null; } } /// - /// Injects a fake/mock context for unit testing + /// Injects a fake/mock context for unit testing. /// - /// The fake context to inject + /// The fake context to inject. public static void RegisterInstance(HttpContextBase instance) { _fakeContext = instance; diff --git a/DNN Platform/Library/Common/Initialize.cs b/DNN Platform/Library/Common/Initialize.cs index 5e52e2c9b46..98a49bac67c 100644 --- a/DNN Platform/Library/Common/Initialize.cs +++ b/DNN Platform/Library/Common/Initialize.cs @@ -1,38 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Reflection; -using System.Threading; -using System.Web; -using System.Web.Hosting; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Connections; -using DotNetNuke.Services.EventQueue; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Upgrade; -using DotNetNuke.UI.Modules; -using DotNetNuke.Services.Installer.Blocker; -using Microsoft.Win32; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common { + using System; + using System.Collections; + using System.IO; + using System.Reflection; + using System.Threading; + using System.Web; + using System.Web.Hosting; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Connections; + using DotNetNuke.Services.EventQueue; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Installer.Blocker; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Upgrade; + using DotNetNuke.UI.Modules; + using Microsoft.Win32; + /// /// The Object to initialize application. /// @@ -42,6 +38,55 @@ public class Initialize private static bool InitializedAlready; private static readonly object InitializeLock = new object(); + /// ----------------------------------------------------------------------------- + /// + /// Inits the app. + /// + /// The app. + /// ----------------------------------------------------------------------------- + public static void Init(HttpApplication app) + { + string redirect; + + // Check if app is initialised + if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) + { + return; + } + + lock (InitializeLock) + { + // Double-Check if app was initialised by another request + if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) + { + return; + } + + // Initialize ... + redirect = InitializeApp(app, ref InitializedAlready); + } + + if (!string.IsNullOrEmpty(redirect)) + { + app.Response.Redirect(redirect, true); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// LogStart logs the Application Start Event. + /// + /// ----------------------------------------------------------------------------- + public static void LogStart() + { + var log = new LogInfo + { + BypassBuffering = true, + LogTypeKey = EventLogController.EventLogType.APPLICATION_START.ToString(), + }; + LogController.Instance.AddLog(log); + } + private static string CheckVersion(HttpApplication app) { HttpServerUtility Server = app.Server; @@ -49,7 +94,7 @@ private static string CheckVersion(HttpApplication app) bool autoUpgrade = Config.GetSetting("AutoUpgrade") == null || bool.Parse(Config.GetSetting("AutoUpgrade")); bool useWizard = Config.GetSetting("UseInstallWizard") == null || bool.Parse(Config.GetSetting("UseInstallWizard")); - //Determine the Upgrade status and redirect as neccessary to InstallWizard.aspx + // Determine the Upgrade status and redirect as neccessary to InstallWizard.aspx string retValue = Null.NullString; switch (Globals.Status) { @@ -64,6 +109,7 @@ private static string CheckVersion(HttpApplication app) retValue = "~/Install/UnderConstruction.htm"; Logger.Info("UnderConstruction page was shown because application needs to be installed, and both the AutoUpgrade and UseWizard AppSettings in web.config are false. Use /install/install.aspx?mode=install to install application. "); } + break; case Globals.UpgradeStatus.Upgrade: if (autoUpgrade || useWizard) @@ -76,6 +122,7 @@ private static string CheckVersion(HttpApplication app) retValue = "~/Install/UnderConstruction.htm"; Logger.Info("UnderConstruction page was shown because application needs to be upgraded, and both the AutoUpgrade and UseInstallWizard AppSettings in web.config are false. Use /install/install.aspx?mode=upgrade to upgrade application. "); } + break; case Globals.UpgradeStatus.Error: // here we need to check if the application is already installed @@ -92,8 +139,8 @@ private static string CheckVersion(HttpApplication app) } else { - //500 Error - Redirect to ErrorPage - if ((HttpContext.Current != null)) + // 500 Error - Redirect to ErrorPage + if (HttpContext.Current != null) { if (!isInstalled) { @@ -103,6 +150,7 @@ private static string CheckVersion(HttpApplication app) { Logger.Error("The connection to the database has failed, however, the application is already completely installed, a 500 error page will be shown to visitors"); } + string url = "~/ErrorPage.aspx?status=500&error=Site Unavailable&error2=Connection To The Database Failed"; HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer(url); @@ -111,12 +159,13 @@ private static string CheckVersion(HttpApplication app) break; } + return retValue; } private static void CreateUnderConstructionPage(HttpServerUtility server) { - //create an UnderConstruction page if it does not exist already + // create an UnderConstruction page if it does not exist already if (!File.Exists(server.MapPath("~/Install/UnderConstruction.htm"))) { if (File.Exists(server.MapPath("~/Install/UnderConstruction.template.htm"))) @@ -133,15 +182,17 @@ private static Version GetDatabaseEngineVersion() private static Version GetNETFrameworkVersion() { - //Obtain the .NET Framework version, 9.4.0 and later requires .NET 4.7.2 or later + // Obtain the .NET Framework version, 9.4.0 and later requires .NET 4.7.2 or later var version = Environment.Version.ToString(2); - //If unknown version return as is. - if (version != "4.0") - return new Version(version); - - //Otherwise utilize release DWORD from registry to determine version - //Reference List: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies + // If unknown version return as is. + if (version != "4.0") + { + return new Version(version); + } + + // Otherwise utilize release DWORD from registry to determine version + // Reference List: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies var release = GetDotNet4ReleaseNumberFromRegistry(); if (release >= 528040) { @@ -170,8 +221,9 @@ private static int GetDotNet4ReleaseNumberFromRegistry() } catch (Exception) { - //ignore + // ignore } + return -1; } @@ -182,30 +234,35 @@ private static string InitializeApp(HttpApplication app, ref bool initialized) Logger.Trace("Request " + request.Url.LocalPath); - //Don't process some of the AppStart methods if we are installing + // Don't process some of the AppStart methods if we are installing if (!IsUpgradeOrInstallRequest(app.Request)) { - //Check whether the current App Version is the same as the DB Version + // Check whether the current App Version is the same as the DB Version redirect = CheckVersion(app); if (string.IsNullOrEmpty(redirect) && !InstallBlocker.Instance.IsInstallInProgress()) { Logger.Info("Application Initializing"); - //Set globals + + // Set globals Globals.IISAppName = request.ServerVariables["APPL_MD_PATH"]; Globals.OperatingSystemVersion = Environment.OSVersion.Version; Globals.NETFrameworkVersion = GetNETFrameworkVersion(); Globals.DatabaseEngineVersion = GetDatabaseEngineVersion(); - //Try and Upgrade to Current Framewok + + // Try and Upgrade to Current Framewok Upgrade.TryUpgradeNETFramework(); Upgrade.CheckFipsCompilanceAssemblies(); - //Log Server information + // Log Server information ServerController.UpdateServerActivity(new ServerInfo()); - //Start Scheduler + + // Start Scheduler StartScheduler(); - //Log Application Start + + // Log Application Start LogStart(); - //Process any messages in the EventQueue for the Application_Start event + + // Process any messages in the EventQueue for the Application_Start event EventQueueController.ProcessMessages("Application_Start"); ServicesRoutingManager.RegisterServiceRoutes(); @@ -214,7 +271,7 @@ private static string InitializeApp(HttpApplication app, ref bool initialized) ConnectionsManager.Instance.RegisterConnections(); - //Set Flag so we can determine the first Page Request after Application Start + // Set Flag so we can determine the first Page Request after Application Start app.Context.Items.Add("FirstRequest", true); Logger.Info("Application Initialized"); @@ -224,11 +281,12 @@ private static string InitializeApp(HttpApplication app, ref bool initialized) } else { - //NET Framework version is neeed by Upgrade + // NET Framework version is neeed by Upgrade Globals.NETFrameworkVersion = GetNETFrameworkVersion(); Globals.IISAppName = request.ServerVariables["APPL_MD_PATH"]; Globals.OperatingSystemVersion = Environment.OSVersion.Version; } + return redirect; } @@ -243,52 +301,7 @@ private static bool IsUpgradeOrInstallRequest(HttpRequest request) /// ----------------------------------------------------------------------------- /// - /// Inits the app. - /// - /// The app. - /// ----------------------------------------------------------------------------- - public static void Init(HttpApplication app) - { - string redirect; - //Check if app is initialised - if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) - { - return; - } - lock (InitializeLock) - { - //Double-Check if app was initialised by another request - if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) - { - return; - } - //Initialize ... - redirect = InitializeApp(app, ref InitializedAlready); - } - if (!string.IsNullOrEmpty(redirect)) - { - app.Response.Redirect(redirect, true); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// LogStart logs the Application Start Event - /// - /// ----------------------------------------------------------------------------- - public static void LogStart() - { - var log = new LogInfo - { - BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.APPLICATION_START.ToString() - }; - LogController.Instance.AddLog(log); - } - - /// ----------------------------------------------------------------------------- - /// - /// LogEnd logs the Application Start Event + /// LogEnd logs the Application Start Event. /// /// ----------------------------------------------------------------------------- public static void LogEnd() @@ -345,16 +358,18 @@ public static void LogEnd() shutdownDetail = "Shutdown reason: " + shutdownReason; break; } + var log = new LogInfo { BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.APPLICATION_SHUTTING_DOWN.ToString() + LogTypeKey = EventLogController.EventLogType.APPLICATION_SHUTTING_DOWN.ToString(), }; log.AddProperty("Shutdown Details", shutdownDetail); LogController.Instance.AddLog(log); // enhanced shutdown logging - var runtime = typeof(HttpRuntime).InvokeMember("_theRuntime", + var runtime = typeof(HttpRuntime).InvokeMember( + "_theRuntime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null) as HttpRuntime; @@ -364,11 +379,13 @@ public static void LogEnd() } else { - var shutDownMessage = runtime.GetType().InvokeMember("_shutDownMessage", + var shutDownMessage = runtime.GetType().InvokeMember( + "_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null) as string; - var shutDownStack = runtime.GetType().InvokeMember("_shutDownStack", + var shutDownStack = runtime.GetType().InvokeMember( + "_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null) as string; @@ -381,18 +398,19 @@ public static void LogEnd() { Exceptions.LogException(exc); } + if (Globals.Status != Globals.UpgradeStatus.Install) { - //purge log buffer + // purge log buffer LoggingProvider.Instance().PurgeLogBuffer(); } } - - + /// ----------------------------------------------------------------------------- /// - /// Tests whether this request should be processed in an HttpModule - /// + /// Tests whether this request should be processed in an HttpModule. + /// + /// /// ----------------------------------------------------------------------------- public static bool ProcessHttpModule(HttpRequest request, bool allowUnknownExtensions, bool checkOmitFromRewriteProcessing) { @@ -428,9 +446,9 @@ public static void RunSchedule(HttpRequest request) { if (SchedulingProvider.SchedulerMode == SchedulerMode.REQUEST_METHOD && SchedulingProvider.ReadyForPoll) { - Logger.Trace("Running Schedule " + (SchedulingProvider.SchedulerMode)); + Logger.Trace("Running Schedule " + SchedulingProvider.SchedulerMode); var scheduler = SchedulingProvider.Instance(); - var requestScheduleThread = new Thread(scheduler.ExecuteTasks) {IsBackground = true}; + var requestScheduleThread = new Thread(scheduler.ExecuteTasks) { IsBackground = true }; requestScheduleThread.Start(); SchedulingProvider.ScheduleLastPolled = DateTime.Now; } @@ -444,7 +462,7 @@ public static void RunSchedule(HttpRequest request) /// ----------------------------------------------------------------------------- /// - /// StartScheduler starts the Scheduler + /// StartScheduler starts the Scheduler. /// /// Whether reset app start elapse time before running schedule tasks. /// @@ -456,17 +474,18 @@ public static void StartScheduler(bool resetAppStartElapseTime = false) { Globals.ResetAppStartElapseTime(); } + var scheduler = SchedulingProvider.Instance(); scheduler.RunEventSchedule(EventName.APPLICATION_START); - //instantiate APPLICATION_START scheduled jobs + // instantiate APPLICATION_START scheduled jobs if (SchedulingProvider.SchedulerMode == SchedulerMode.TIMER_METHOD) { Logger.Trace("Running Schedule " + SchedulingProvider.SchedulerMode); var newThread = new Thread(scheduler.Start) { IsBackground = true, - Name = "Scheduler Thread" + Name = "Scheduler Thread", }; newThread.Start(); } @@ -474,14 +493,14 @@ public static void StartScheduler(bool resetAppStartElapseTime = false) /// ----------------------------------------------------------------------------- /// - /// StopScheduler stops the Scheduler + /// StopScheduler stops the Scheduler. /// /// /// /// ----------------------------------------------------------------------------- public static void StopScheduler() { - //stop scheduled jobs + // stop scheduled jobs SchedulingProvider.Instance().Halt("Stopped by Application_End"); } } diff --git a/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs b/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs index 4861245d477..db0cd3bf2e6 100644 --- a/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs +++ b/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; - -using DotNetNuke.ComponentModel; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.Instrumentation; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ConvertPropertyToExpressionBody - namespace DotNetNuke.Common.Internal { - internal class EventHandlersContainer : ComponentBase, EventHandlersContainer>, IEventHandlersContainer + using System; + using System.Collections.Generic; + using System.ComponentModel.Composition; + + using DotNetNuke.ComponentModel; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.Instrumentation; + + internal class EventHandlersContainer : ComponentBase, EventHandlersContainer>, IEventHandlersContainer { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(EventHandlersContainer)); @@ -24,11 +24,12 @@ public EventHandlersContainer() { try { - if (GetCurrentStatus() != Globals.UpgradeStatus.None) + if (this.GetCurrentStatus() != Globals.UpgradeStatus.None) { return; } - ExtensionPointManager.ComposeParts(this); + + ExtensionPointManager.ComposeParts(this); } catch (Exception ex) { @@ -40,7 +41,7 @@ public IEnumerable> EventHandlers { get { - return _eventHandlers; + return this._eventHandlers; } } diff --git a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs index ceadbbfe240..e2478453b3a 100644 --- a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs +++ b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs @@ -1,25 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text; -using System.Web; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.UI.UserControls; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Internal { + using System; + using System.Text; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.UI.UserControls; + using Microsoft.Extensions.DependencyInjection; + public class GlobalsImpl : IGlobals { - protected INavigationManager NavigationManager { get; } public GlobalsImpl() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } public string ApplicationPath @@ -31,6 +31,8 @@ public string HostMapPath { get { return Globals.HostMapPath; } } + + protected INavigationManager NavigationManager { get; } public string GetSubFolderPath(string strFileNamePath, int portalId) { @@ -44,7 +46,7 @@ public string LinkClick(string link, int tabId, int moduleId) public string LinkClick(string link, int tabID, int moduleID, bool trackClicks, bool forceDownload, int portalId, bool enableUrlLanguage, string portalGuid) { - return Globals.LinkClick(link, tabID, moduleID, trackClicks, forceDownload, portalId, enableUrlLanguage,portalGuid); + return Globals.LinkClick(link, tabID, moduleID, trackClicks, forceDownload, portalId, enableUrlLanguage, portalGuid); } public string ResolveUrl(string url) @@ -69,7 +71,7 @@ public string GetPortalDomainName(string strPortalAlias, HttpRequest Request, bo public string GetDomainName(Uri requestedUri) { - return GetDomainName(requestedUri, false); + return this.GetDomainName(requestedUri, false); } public string GetDomainName(Uri requestedUri, bool parsePortNumber) @@ -83,15 +85,17 @@ public string GetDomainName(Uri requestedUri, bool parsePortNumber) // Binary, else '?' isn't taken literally; only interested in one (left) string string uri = requestedUri.ToString(); string hostHeader = Config.GetSetting("HostHeader"); - if (!String.IsNullOrEmpty(hostHeader)) + if (!string.IsNullOrEmpty(hostHeader)) { - uri = uri.ToLowerInvariant().Replace(hostHeader.ToLowerInvariant(), ""); + uri = uri.ToLowerInvariant().Replace(hostHeader.ToLowerInvariant(), string.Empty); } + int queryIndex = uri.IndexOf("?", StringComparison.Ordinal); if (queryIndex > -1) { uri = uri.Substring(0, queryIndex); } + string[] url = uri.Split('/'); for (queryIndex = 2; queryIndex <= url.GetUpperBound(0); queryIndex++) { @@ -114,34 +118,38 @@ public string GetDomainName(Uri requestedUri, bool parsePortNumber) // we'll use reverse match, // - but that means we are checking position of left end of the match; // - and to do that, we need to ensure the string we test against is long enough; - if ((url[queryIndex].Length >= ".aspx".Length)) + if (url[queryIndex].Length >= ".aspx".Length) { - if (url[queryIndex].LastIndexOf(".aspx", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - (".aspx".Length)) || - url[queryIndex].LastIndexOf(".axd", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - (".axd".Length)) || - url[queryIndex].LastIndexOf(".ashx", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - (".ashx".Length))) + if (url[queryIndex].LastIndexOf(".aspx", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - ".aspx".Length) || + url[queryIndex].LastIndexOf(".axd", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - ".axd".Length) || + url[queryIndex].LastIndexOf(".ashx", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - ".ashx".Length)) { break; } } + // non of the exclusionary names found - domainName.Append((!String.IsNullOrEmpty(domainName.ToString()) ? "/" : "") + url[queryIndex]); + domainName.Append((!string.IsNullOrEmpty(domainName.ToString()) ? "/" : string.Empty) + url[queryIndex]); break; } + if (needExit) { break; } } + if (parsePortNumber) { if (domainName.ToString().IndexOf(":", StringComparison.Ordinal) != -1) { if (!Globals.UsePortNumber()) { - domainName = domainName.Replace(":" + requestedUri.Port, ""); + domainName = domainName.Replace(":" + requestedUri.Port, string.Empty); } } } + return domainName.ToString(); } @@ -172,57 +180,57 @@ public string LoginURL(string returnURL, bool @override) public string NavigateURL() { - return NavigationManager.NavigateURL(); + return this.NavigationManager.NavigateURL(); } public string NavigateURL(int tabID) { - return NavigationManager.NavigateURL(tabID); + return this.NavigationManager.NavigateURL(tabID); } public string NavigateURL(int tabID, bool isSuperTab) { - return NavigationManager.NavigateURL(tabID, isSuperTab); + return this.NavigationManager.NavigateURL(tabID, isSuperTab); } public string NavigateURL(string controlKey) { - return NavigationManager.NavigateURL(controlKey); + return this.NavigationManager.NavigateURL(controlKey); } public string NavigateURL(string controlKey, params string[] additionalParameters) { - return NavigationManager.NavigateURL(controlKey, additionalParameters); + return this.NavigationManager.NavigateURL(controlKey, additionalParameters); } public string NavigateURL(int tabID, string controlKey) { - return NavigationManager.NavigateURL(tabID, controlKey); + return this.NavigationManager.NavigateURL(tabID, controlKey); } public string NavigateURL(int tabID, string controlKey, params string[] additionalParameters) { - return NavigationManager.NavigateURL(tabID, controlKey, additionalParameters); + return this.NavigationManager.NavigateURL(tabID, controlKey, additionalParameters); } public string NavigateURL(int tabID, PortalSettings settings, string controlKey, params string[] additionalParameters) { - return NavigationManager.NavigateURL(tabID, settings, controlKey, additionalParameters); + return this.NavigationManager.NavigateURL(tabID, settings, controlKey, additionalParameters); } public string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, params string[] additionalParameters) { - return NavigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, additionalParameters); + return this.NavigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, additionalParameters); } public string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, params string[] additionalParameters) { - return NavigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, additionalParameters); + return this.NavigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, additionalParameters); } public string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, string pageName, params string[] additionalParameters) { - return NavigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); + return this.NavigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); } public string FriendlyUrl(TabInfo tab, string path) diff --git a/DNN Platform/Library/Common/Internal/IEventHandlersContainer.cs b/DNN Platform/Library/Common/Internal/IEventHandlersContainer.cs index 1a2673cd6b1..f35b9f24b43 100644 --- a/DNN Platform/Library/Common/Internal/IEventHandlersContainer.cs +++ b/DNN Platform/Library/Common/Internal/IEventHandlersContainer.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Internal { + using System; + using System.Collections.Generic; + internal interface IEventHandlersContainer { IEnumerable> EventHandlers { get; } diff --git a/DNN Platform/Library/Common/Internal/IGlobals.cs b/DNN Platform/Library/Common/Internal/IGlobals.cs index 3ab692f7eab..c752df32d55 100644 --- a/DNN Platform/Library/Common/Internal/IGlobals.cs +++ b/DNN Platform/Library/Common/Internal/IGlobals.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Internal { - + using System; + using System.Web; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + public interface IGlobals { /// @@ -18,16 +18,17 @@ public interface IGlobals string ApplicationPath { get; } /// - /// Gets or sets the host map path. + /// Gets the host map path. /// - /// ApplicationMapPath + "Portals\_default\" + /// ApplicationMapPath + "Portals\_default\". string HostMapPath { get; } /// - /// Returns the folder path under the root for the portal + /// Returns the folder path under the root for the portal. /// - /// The folder the absolute path + /// The folder the absolute path. /// Portal Id. + /// string GetSubFolderPath(string fileNamePath, int portalId); /// @@ -42,25 +43,25 @@ public interface IGlobals /// /// Gets Link click url. /// - /// The link - /// The Tab ID - /// The Module ID - /// Check whether it has to track clicks - /// Check whether it has to force the download - /// The Portal ID - /// Check whether the portal has enabled ulr languages - /// The Portal GUID + /// The link. + /// The Tab ID. + /// The Module ID. + /// Check whether it has to track clicks. + /// Check whether it has to force the download. + /// The Portal ID. + /// Check whether the portal has enabled ulr languages. + /// The Portal GUID. /// string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks, bool ForceDownload, int PortalId, bool EnableUrlLanguage, string portalGuid); /// - /// Generates the correctly formatted url + /// Generates the correctly formatted url. /// /// /// /// The url to format. - /// The formatted (resolved) url + /// The formatted (resolved) url. string ResolveUrl(string url); /// @@ -71,10 +72,10 @@ string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks, bool Fo bool IsHostTab(int tabId); /// - /// Adds the current request's protocol ("http://" or "https://") to the given URL, if it does not already have a protocol specified + /// Adds the current request's protocol ("http://" or "https://") to the given URL, if it does not already have a protocol specified. /// - /// The URL - /// The formatted URL + /// The URL. + /// The formatted URL. string AddHTTP(string strURL); /// @@ -83,22 +84,22 @@ string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks, bool Fo /// The portal alias. /// The request or null. /// if set to true calls on the result. - /// domain name + /// domain name. string GetPortalDomainName(string strPortalAlias, HttpRequest Request, bool blnAddHTTP); - + /// /// Gets the name of the domain. /// - /// The requested Uri - /// domain name + /// The requested Uri. + /// domain name. string GetDomainName(Uri requestedUri); /// - /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ) + /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ). /// - /// The requested Uri + /// The requested Uri. /// if set to true [parse port number]. - /// domain name + /// domain name. string GetDomainName(Uri requestedUri, bool parsePortNumber); /// @@ -123,14 +124,14 @@ string LinkClick(string Link, int TabID, int ModuleID, bool TrackClicks, bool Fo /// /// Get the URL to show the "access denied" message. /// - /// URL to access denied view + /// URL to access denied view. string AccessDeniedURL(); /// /// Get the URL to show the "access denied" message. /// /// The message to display. - /// URL to access denied view + /// URL to access denied view. string AccessDeniedURL(string Message); /// @@ -257,63 +258,63 @@ string NavigateURL( /// Generates the correctly formatted friendly URL. /// /// - /// Assumes Default.aspx, and that portalsettings are saved to Context + /// Assumes Default.aspx, and that portalsettings are saved to Context. /// - /// The current tab + /// The current tab. /// The path to format. - /// The formatted (friendly) URL + /// The formatted (friendly) URL. string FriendlyUrl(TabInfo tab, string path); /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// /// This overload includes an optional page to include in the url. /// - /// The current tab + /// The current tab. /// The path to format. /// The page to include in the url. - /// The formatted (friendly) URL + /// The formatted (friendly) URL. string FriendlyUrl(TabInfo tab, string path, string pageName); /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// - /// This overload includes the portal settings for the site + /// This overload includes the portal settings for the site. /// - /// The current tab + /// The current tab. /// The path to format. - /// The portal settings - /// The formatted (friendly) URL + /// The portal settings. + /// The formatted (friendly) URL. string FriendlyUrl(TabInfo tab, string path, PortalSettings settings); /// - /// Generates the correctly formatted friendly URL + /// Generates the correctly formatted friendly URL. /// /// - /// This overload includes an optional page to include in the URL, and the portal - /// settings for the site + /// This overload includes an optional page to include in the URL, and the portal + /// settings for the site. /// - /// The current tab + /// The current tab. /// The path to format. /// The page to include in the URL. - /// The portal settings - /// The formatted (friendly) url + /// The portal settings. + /// The formatted (friendly) url. string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings); /// - /// Generates the correctly formatted friendly url + /// Generates the correctly formatted friendly url. /// /// - /// This overload includes an optional page to include in the url, and the portal - /// alias for the site + /// This overload includes an optional page to include in the url, and the portal + /// alias for the site. /// - /// The current tab + /// The current tab. /// The path to format. /// The page to include in the URL. - /// The portal alias for the site - /// The formatted (friendly) URL + /// The portal alias for the site. + /// The formatted (friendly) URL. string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias); } } diff --git a/DNN Platform/Library/Common/Internal/ServicesRoutingManager.cs b/DNN Platform/Library/Common/Internal/ServicesRoutingManager.cs index 60783848ed7..012bf67a2b5 100644 --- a/DNN Platform/Library/Common/Internal/ServicesRoutingManager.cs +++ b/DNN Platform/Library/Common/Internal/ServicesRoutingManager.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Internal { + using System; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + public static class ServicesRoutingManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ServicesRoutingManager)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServicesRoutingManager)); public static void RegisterServiceRoutes() { @@ -18,7 +19,7 @@ public static void RegisterServiceRoutes() try { - //new ServicesRoutingManager().RegisterRoutes(); + // new ServicesRoutingManager().RegisterRoutes(); var instance = Activator.CreateInstance("DotNetNuke.Web", "DotNetNuke.Web.Api.Internal.ServicesRoutingManager"); var method = instance.Unwrap().GetType().GetMethod("RegisterRoutes"); @@ -37,9 +38,9 @@ public static void RegisterServiceRoutes() public static void ReRegisterServiceRoutesWhileSiteIsRunning() { - //by clearing a "fake" key on the caching provider we can echo this - //command to all the members of a web farm - //the caching provider will call to make the actual registration of new routes + // by clearing a "fake" key on the caching provider we can echo this + // command to all the members of a web farm + // the caching provider will call to make the actual registration of new routes CachingProvider.Instance().Clear("ServiceFrameworkRoutes", "-1"); } } diff --git a/DNN Platform/Library/Common/Internal/TestableGlobals.cs b/DNN Platform/Library/Common/Internal/TestableGlobals.cs index fe05df60fa5..e315188323b 100644 --- a/DNN Platform/Library/Common/Internal/TestableGlobals.cs +++ b/DNN Platform/Library/Common/Internal/TestableGlobals.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Internal { + using System; + + using DotNetNuke.Framework; + public class TestableGlobals : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Common/Lists/CachedCountryList.cs b/DNN Platform/Library/Common/Lists/CachedCountryList.cs index e2c4625549f..bbfc1a91e4b 100644 --- a/DNN Platform/Library/Common/Lists/CachedCountryList.cs +++ b/DNN Platform/Library/Common/Lists/CachedCountryList.cs @@ -1,82 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using DotNetNuke.Common.Utilities; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Lists { - [Serializable] - public class CachedCountryList : Dictionary - { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; - #region " Structures " + using DotNetNuke.Common.Utilities; - [Serializable] - public struct Country - { - public int Id; - public string Name; - public string Code; - public string FullName; - public string NormalizedFullName; - } + [Serializable] + public class CachedCountryList : Dictionary + { + public CachedCountryList(string locale) + : base() + { + foreach (ListEntryInfo li in new ListController().GetListEntryInfoItems("Country")) + { + string text = li.Text; + Country c = new Country + { + Id = li.EntryID, + Code = li.Value, + FullName = string.Format("{0} ({1})", text, li.Value), + Name = text, + }; + c.NormalizedFullName = c.FullName.NormalizeString(); + this.Add(li.Value, c); + } + } - #endregion + public static CachedCountryList GetCountryList(string locale) + { + CachedCountryList res = null; + try + { + res = (CachedCountryList)DotNetNuke.Common.Utilities.DataCache.GetCache(CacheKey(locale)); + } + catch (Exception) + { + // do nothing here. + } - #region " Constructors " - public CachedCountryList(string locale) - : base() - { + if (res == null) + { + res = new CachedCountryList(locale); + DotNetNuke.Common.Utilities.DataCache.SetCache(CacheKey(locale), res); + } - foreach (ListEntryInfo li in (new ListController()).GetListEntryInfoItems("Country")) - { - string text = li.Text; - Country c = new Country - { - Id = li.EntryID, - Code = li.Value, - FullName = string.Format("{0} ({1})", text, li.Value), - Name = text - }; - c.NormalizedFullName = c.FullName.NormalizeString(); - Add(li.Value, c); - } + return res; + } - } - #endregion + public static string CacheKey(string locale) + { + return string.Format("CountryList:{0}", locale); + } - #region " Static Methods " - public static CachedCountryList GetCountryList(string locale) - { - - CachedCountryList res = null; - try - { - res = (CachedCountryList)DotNetNuke.Common.Utilities.DataCache.GetCache(CacheKey(locale)); - } - catch (Exception) - { - //do nothing here. - } - if (res == null) - { - res = new CachedCountryList(locale); - DotNetNuke.Common.Utilities.DataCache.SetCache(CacheKey(locale), res); - } - return res; - - } - - public static string CacheKey(string locale) - { - return string.Format("CountryList:{0}", locale); - } - #endregion - - } + [Serializable] + public struct Country + { + public int Id; + public string Name; + public string Code; + public string FullName; + public string NormalizedFullName; + } + } } diff --git a/DNN Platform/Library/Common/Lists/ListController.cs b/DNN Platform/Library/Common/Lists/ListController.cs index 88f9a49efdc..c048a43ea9d 100644 --- a/DNN Platform/Library/Common/Lists/ListController.cs +++ b/DNN Platform/Library/Common/Lists/ListController.cs @@ -1,35 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Linq; -using System.Threading; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Lists { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Linq; + using System.Threading; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + public class ListController { + public readonly string[] NonLocalizedLists = { "ContentTypes", "Processor", "DataType", "ProfanityFilter", "BannedPasswords" }; + + /// + /// Adds a new list entry to the database. If the current thread locale is not "en-US" then the text value will also be + /// persisted to a resource file under App_GlobalResources using the list's name and the value as key. + /// + /// The list entry. + /// + public int AddListEntry(ListEntryInfo listEntry) + { + bool enableSortOrder = listEntry.SortOrder > 0; + this.ClearListCache(listEntry.PortalID); + int entryId = DataProvider.Instance().AddListEntry( + listEntry.ListName, + listEntry.Value, + listEntry.TextNonLocalized, + listEntry.ParentID, + listEntry.Level, + enableSortOrder, + listEntry.DefinitionID, + listEntry.Description, + listEntry.PortalID, + listEntry.SystemList, + UserController.Instance.GetCurrentUserInfo().UserID); - public readonly string[] NonLocalizedLists = { "ContentTypes", "Processor", "DataType", "ProfanityFilter", "BannedPasswords" }; - - #region Private Methods + if (entryId != Null.NullInteger) + { + EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LISTENTRY_CREATED); + } + + if (Thread.CurrentThread.CurrentCulture.Name != Localization.SystemLocale && !this.NonLocalizedLists.Contains(listEntry.ListName)) + { + if (string.IsNullOrEmpty(listEntry.ParentKey)) + { + LocalizationProvider.Instance.SaveString(listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); + } + else + { + LocalizationProvider.Instance.SaveString(listEntry.ParentKey + "." + listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); + } + } + + this.ClearEntriesCache(listEntry.ListName, listEntry.PortalID); + return entryId; + } + public void DeleteList(string listName, string parentKey) + { + this.DeleteList(listName, parentKey, Null.NullInteger); + } + private void ClearListCache(int portalId) { DataCache.ClearListsCache(portalId); @@ -44,6 +86,7 @@ private void ClearEntriesCache(string listName, int portalId) private ListInfo FillListInfo(IDataReader dr, bool CheckForOpenDataReader) { ListInfo list = null; + // read datareader bool canContinue = true; if (CheckForOpenDataReader) @@ -54,6 +97,7 @@ private ListInfo FillListInfo(IDataReader dr, bool CheckForOpenDataReader) canContinue = true; } } + if (canContinue) { list = new ListInfo(Convert.ToString(dr["ListName"])); @@ -66,10 +110,11 @@ private ListInfo FillListInfo(IDataReader dr, bool CheckForOpenDataReader) list.ParentKey = Convert.ToString(dr["ParentKey"]); list.Parent = Convert.ToString(dr["Parent"]); list.ParentList = Convert.ToString(dr["ParentList"]); - list.EnableSortOrder = (Convert.ToInt32(dr["MaxSortOrder"]) > 0); + list.EnableSortOrder = Convert.ToInt32(dr["MaxSortOrder"]) > 0; list.SystemList = Convert.ToInt32(dr["SystemList"]) > 0; } } + return list; } @@ -81,7 +126,7 @@ private Dictionary FillListInfoDictionary(IDataReader dr) while (dr.Read()) { // fill business object - ListInfo list = FillListInfo(dr, false); + ListInfo list = this.FillListInfo(dr, false); if (!dic.ContainsKey(list.Key)) { dic.Add(list.Key, list); @@ -97,85 +142,41 @@ private Dictionary FillListInfoDictionary(IDataReader dr) // close datareader CBO.CloseDataReader(dr, true); } + return dic; } private Dictionary GetListInfoDictionary(int portalId) { string cacheKey = string.Format(DataCache.ListsCacheKey, portalId); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.ListsCacheTimeOut, - DataCache.ListsCachePriority), - c => FillListInfoDictionary(DataProvider.Instance().GetLists(portalId))); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.ListsCacheTimeOut, + DataCache.ListsCachePriority), + c => this.FillListInfoDictionary(DataProvider.Instance().GetLists(portalId))); } private IEnumerable GetListEntries(string listName, int portalId) { - string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.ListsCacheTimeOut, - DataCache.ListsCachePriority), - c => CBO.FillCollection(DataProvider.Instance().GetListEntriesByListName(listName, String.Empty, portalId))); - } - - #endregion - - /// - /// Adds a new list entry to the database. If the current thread locale is not "en-US" then the text value will also be - /// persisted to a resource file under App_GlobalResources using the list's name and the value as key. - /// - /// The list entry. - /// - public int AddListEntry(ListEntryInfo listEntry) - { - bool enableSortOrder = listEntry.SortOrder > 0; - ClearListCache(listEntry.PortalID); - int entryId = DataProvider.Instance().AddListEntry(listEntry.ListName, - listEntry.Value, - listEntry.TextNonLocalized, - listEntry.ParentID, - listEntry.Level, - enableSortOrder, - listEntry.DefinitionID, - listEntry.Description, - listEntry.PortalID, - listEntry.SystemList, - UserController.Instance.GetCurrentUserInfo().UserID); - - if (entryId != Null.NullInteger) - { - EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LISTENTRY_CREATED); - } - if (Thread.CurrentThread.CurrentCulture.Name != Localization.SystemLocale && !NonLocalizedLists.Contains(listEntry.ListName)) - { - if (string.IsNullOrEmpty(listEntry.ParentKey)) - { - LocalizationProvider.Instance.SaveString(listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); - } - else - { - LocalizationProvider.Instance.SaveString(listEntry.ParentKey + "." + listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); - } - } - ClearEntriesCache(listEntry.ListName, listEntry.PortalID); - return entryId; - } - - public void DeleteList(string listName, string parentKey) - { - DeleteList(listName, parentKey, Null.NullInteger); - } + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.ListsCacheTimeOut, + DataCache.ListsCachePriority), + c => CBO.FillCollection(DataProvider.Instance().GetListEntriesByListName(listName, string.Empty, portalId))); + } public void DeleteList(string listName, string parentKey, int portalId) { - ListInfo list = GetListInfo(listName, parentKey, portalId); + ListInfo list = this.GetListInfo(listName, parentKey, portalId); EventLogController.Instance.AddLog("ListName", listName, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.LISTENTRY_DELETED); DataProvider.Instance().DeleteList(listName, parentKey); if (list != null) { - ClearListCache(list.PortalID); - ClearEntriesCache(list.Name, list.PortalID); + this.ClearListCache(list.PortalID); + this.ClearEntriesCache(list.Name, list.PortalID); } } @@ -188,38 +189,40 @@ public void DeleteList(ListInfo list, bool includeChildren) var lists = new SortedList(); lists.Add(list.Key, list); - //add Children + + // add Children if (includeChildren) { - foreach (KeyValuePair listPair in GetListInfoDictionary(list.PortalID)) + foreach (KeyValuePair listPair in this.GetListInfoDictionary(list.PortalID)) { - if ((listPair.Value.ParentList.StartsWith(list.Key))) + if (listPair.Value.ParentList.StartsWith(list.Key)) { lists.Add(listPair.Value.Key.Replace(":", "."), listPair.Value); } } } - //Delete items in reverse order so deeper descendants are removed before their parents + + // Delete items in reverse order so deeper descendants are removed before their parents for (int i = lists.Count - 1; i >= 0; i += -1) { - DeleteList(lists.Values[i].Name, lists.Values[i].ParentKey, lists.Values[i].PortalID); + this.DeleteList(lists.Values[i].Name, lists.Values[i].ParentKey, lists.Values[i].PortalID); } } public void DeleteListEntryByID(int entryId, bool deleteChild) { - ListEntryInfo entry = GetListEntryInfo(entryId); + ListEntryInfo entry = this.GetListEntryInfo(entryId); DataProvider.Instance().DeleteListEntryByID(entryId, deleteChild); - ClearListCache(entry.PortalID); - ClearEntriesCache(entry.ListName, entry.PortalID); + this.ClearListCache(entry.PortalID); + this.ClearEntriesCache(entry.ListName, entry.PortalID); } public void DeleteListEntryByListName(string listName, string listValue, bool deleteChild) { - ListEntryInfo entry = GetListEntryInfo(listName, listValue); + ListEntryInfo entry = this.GetListEntryInfo(listName, listValue); DataProvider.Instance().DeleteListEntryByListName(listName, listValue, deleteChild); - ClearListCache(entry.PortalID); - ClearEntriesCache(listName, entry.PortalID); + this.ClearListCache(entry.PortalID); + this.ClearEntriesCache(listName, entry.PortalID); } public ListEntryInfo GetListEntryInfo(int entryId) @@ -229,60 +232,60 @@ public ListEntryInfo GetListEntryInfo(int entryId) public ListEntryInfo GetListEntryInfo(string listName, int entryId) { - return GetListEntries(listName, Null.NullInteger).SingleOrDefault(l => l.EntryID == entryId); + return this.GetListEntries(listName, Null.NullInteger).SingleOrDefault(l => l.EntryID == entryId); } public ListEntryInfo GetListEntryInfo(string listName, string listValue) { - return GetListEntries(listName, Null.NullInteger).SingleOrDefault(l => l.Value == listValue); + return this.GetListEntries(listName, Null.NullInteger).SingleOrDefault(l => l.Value == listValue); } public IEnumerable GetListEntryInfoItems(string listName) { - return GetListEntries(listName, Null.NullInteger); + return this.GetListEntries(listName, Null.NullInteger); } public IEnumerable GetListEntryInfoItems(string listName, string parentKey) { - return GetListEntries(listName, Null.NullInteger).Where(l => l.ParentKey == parentKey); + return this.GetListEntries(listName, Null.NullInteger).Where(l => l.ParentKey == parentKey); } public IEnumerable GetListEntryInfoItems(string listName, string parentKey, int portalId) { - return GetListEntries(listName, portalId).Where(l => l.ParentKey == parentKey); + return this.GetListEntries(listName, portalId).Where(l => l.ParentKey == parentKey); } public Dictionary GetListEntryInfoDictionary(string listName) { - return GetListEntryInfoDictionary(listName, "", Null.NullInteger); + return this.GetListEntryInfoDictionary(listName, string.Empty, Null.NullInteger); } public Dictionary GetListEntryInfoDictionary(string listName, string parentKey) { - return GetListEntryInfoDictionary(listName, parentKey, Null.NullInteger); + return this.GetListEntryInfoDictionary(listName, parentKey, Null.NullInteger); } public Dictionary GetListEntryInfoDictionary(string listName, string parentKey, int portalId) { - return ListEntryInfoItemsToDictionary(GetListEntryInfoItems(listName, parentKey, portalId)); + return ListEntryInfoItemsToDictionary(this.GetListEntryInfoItems(listName, parentKey, portalId)); } - private static Dictionary ListEntryInfoItemsToDictionary(IEnumerable items) + public ListInfo GetListInfo(string listName) { - var dict = new Dictionary(); - items.ToList().ForEach(x => dict.Add(x.Key, x)); - - return dict; + return this.GetListInfo(listName, string.Empty); } - public ListInfo GetListInfo(string listName) + public ListInfo GetListInfo(string listName, string parentKey) { - return GetListInfo(listName, ""); + return this.GetListInfo(listName, parentKey, -1); } - public ListInfo GetListInfo(string listName, string parentKey) + private static Dictionary ListEntryInfoItemsToDictionary(IEnumerable items) { - return GetListInfo(listName, parentKey, -1); + var dict = new Dictionary(); + items.ToList().ForEach(x => dict.Add(x.Key, x)); + + return dict; } public ListInfo GetListInfo(string listName, string parentKey, int portalId) @@ -293,42 +296,44 @@ public ListInfo GetListInfo(string listName, string parentKey, int portalId) { key = parentKey + ":"; } + key += listName; - Dictionary dicLists = GetListInfoDictionary(portalId); + Dictionary dicLists = this.GetListInfoDictionary(portalId); if (!dicLists.TryGetValue(key, out list)) { IDataReader dr = DataProvider.Instance().GetList(listName, parentKey, portalId); try { - list = FillListInfo(dr, true); + list = this.FillListInfo(dr, true); } finally { CBO.CloseDataReader(dr, true); } } + return list; } public ListInfoCollection GetListInfoCollection() { - return GetListInfoCollection(""); + return this.GetListInfoCollection(string.Empty); } public ListInfoCollection GetListInfoCollection(string listName) { - return GetListInfoCollection(listName, ""); + return this.GetListInfoCollection(listName, string.Empty); } public ListInfoCollection GetListInfoCollection(string listName, string parentKey) { - return GetListInfoCollection(listName, parentKey, -1); + return this.GetListInfoCollection(listName, parentKey, -1); } public ListInfoCollection GetListInfoCollection(string listName, string parentKey, int portalId) { IList lists = new ListInfoCollection(); - foreach (KeyValuePair listPair in GetListInfoDictionary(portalId).OrderBy(l => l.Value.DisplayName)) + foreach (KeyValuePair listPair in this.GetListInfoDictionary(portalId).OrderBy(l => l.Value.DisplayName)) { ListInfo list = listPair.Value; if ((list.Name == listName || string.IsNullOrEmpty(listName)) && (list.ParentKey == parentKey || string.IsNullOrEmpty(parentKey)) && @@ -337,68 +342,74 @@ public ListInfoCollection GetListInfoCollection(string listName, string parentKe lists.Add(list); } } + return (ListInfoCollection)lists; } /// /// Updates the list entry in the database using the values set on the listEntry. Note that if the current thread locale is not "en-US" then the - /// text value will be persisted to a resource file under App_GlobalResources using the list's name and the value as key. Also the supplied text value + /// text value will be persisted to a resource file under App_GlobalResources using the list's name and the value as key. Also the supplied text value /// will *not* be written to the database in this case (i.e. we expect the text value in the database to be the en-US text value). /// /// The list entry info item to update. public void UpdateListEntry(ListEntryInfo listEntry) { - if (Thread.CurrentThread.CurrentCulture.Name == Localization.SystemLocale || NonLocalizedLists.Contains(listEntry.ListName)) + if (Thread.CurrentThread.CurrentCulture.Name == Localization.SystemLocale || this.NonLocalizedLists.Contains(listEntry.ListName)) { DataProvider.Instance().UpdateListEntry(listEntry.EntryID, listEntry.Value, listEntry.TextNonLocalized, listEntry.Description, UserController.Instance.GetCurrentUserInfo().UserID); } else { - var oldItem = GetListEntryInfo(listEntry.EntryID); // look up existing db record to be able to just update the value or description and not touch the en-US text value + var oldItem = this.GetListEntryInfo(listEntry.EntryID); // look up existing db record to be able to just update the value or description and not touch the en-US text value DataProvider.Instance().UpdateListEntry(listEntry.EntryID, listEntry.Value, oldItem.TextNonLocalized, listEntry.Description, UserController.Instance.GetCurrentUserInfo().UserID); var key = string.IsNullOrEmpty(listEntry.ParentKey) ? listEntry.Value + ".Text" : listEntry.ParentKey + "." + listEntry.Value + ".Text"; - LocalizationProvider.Instance.SaveString(key, listEntry.TextNonLocalized, listEntry.ResourceFileRoot, + LocalizationProvider.Instance.SaveString(key, listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); } - EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LISTENTRY_UPDATED); - ClearListCache(listEntry.PortalID); - ClearEntriesCache(listEntry.ListName, listEntry.PortalID); + + EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LISTENTRY_UPDATED); + this.ClearListCache(listEntry.PortalID); + this.ClearEntriesCache(listEntry.ListName, listEntry.PortalID); } public void UpdateListSortOrder(int EntryID, bool MoveUp) { DataProvider.Instance().UpdateListSortOrder(EntryID, MoveUp); - ListEntryInfo entry = GetListEntryInfo(EntryID); - ClearListCache(entry.PortalID); - ClearEntriesCache(entry.ListName, entry.PortalID); + ListEntryInfo entry = this.GetListEntryInfo(EntryID); + this.ClearListCache(entry.PortalID); + this.ClearEntriesCache(entry.ListName, entry.PortalID); } - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string) instead. Scheduled removal in v10.0.0."), EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string) instead. Scheduled removal in v10.0.0.")] + [EditorBrowsable(EditorBrowsableState.Never)] public ListEntryInfoCollection GetListEntryInfoCollection(string listName) { - return GetListEntryInfoCollection(listName, "", Null.NullInteger); + return this.GetListEntryInfoCollection(listName, string.Empty, Null.NullInteger); } - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0."), EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] + [EditorBrowsable(EditorBrowsableState.Never)] public ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey) { - return GetListEntryInfoCollection(listName, parentKey, Null.NullInteger); + return this.GetListEntryInfoCollection(listName, parentKey, Null.NullInteger); } - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0."), EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] + [EditorBrowsable(EditorBrowsableState.Never)] public ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey, int portalId) { - var items = GetListEntryInfoItems(listName, parentKey, portalId); + var items = this.GetListEntryInfoItems(listName, parentKey, portalId); var collection = new ListEntryInfoCollection(); if (items != null) { items.ToList().ForEach(x => collection.Add(x.Key, x)); } + return collection; } } diff --git a/DNN Platform/Library/Common/Lists/ListEntryCollection.cs b/DNN Platform/Library/Common/Lists/ListEntryCollection.cs index c9d7a7eb378..fd4daa01bd2 100644 --- a/DNN Platform/Library/Common/Lists/ListEntryCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListEntryCollection.cs @@ -1,31 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.ComponentModel; - -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Lists { + using System; + using System.Collections; + using System.ComponentModel; + + using DotNetNuke.Instrumentation; + [Serializable] - [Obsolete("Obsoleted in 6.0.1. Replaced by using generic collections of ListEntryInfo objects. Scheduled removal in v10.0.0."), EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Obsoleted in 6.0.1. Replaced by using generic collections of ListEntryInfo objects. Scheduled removal in v10.0.0.")] + [EditorBrowsable(EditorBrowsableState.Never)] public class ListEntryInfoCollection : CollectionBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ListEntryInfoCollection)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ListEntryInfoCollection)); private readonly Hashtable _keyIndexLookup = new Hashtable(); public ListEntryInfo Item(int index) { try { - return (ListEntryInfo) base.List[index]; + return (ListEntryInfo)this.List[index]; } catch (Exception exc) { @@ -37,10 +33,11 @@ public ListEntryInfo Item(int index) public ListEntryInfo Item(string key) { int index; - // + + // try { - if (_keyIndexLookup[key.ToLowerInvariant()] == null) + if (this._keyIndexLookup[key.ToLowerInvariant()] == null) { return null; } @@ -50,33 +47,34 @@ public ListEntryInfo Item(string key) Logger.Error(exc); return null; } - index = Convert.ToInt32(_keyIndexLookup[key.ToLowerInvariant()]); - return (ListEntryInfo) base.List[index]; + + index = Convert.ToInt32(this._keyIndexLookup[key.ToLowerInvariant()]); + return (ListEntryInfo)this.List[index]; } public ListEntryInfo GetChildren(string parentName) { - return Item(parentName); - } - - internal new void Clear() - { - _keyIndexLookup.Clear(); - base.Clear(); + return this.Item(parentName); } public void Add(string key, ListEntryInfo value) { int index; - try //Do validation first + try // Do validation first { - index = base.List.Add(value); - _keyIndexLookup.Add(key.ToLowerInvariant(), index); + index = this.List.Add(value); + this._keyIndexLookup.Add(key.ToLowerInvariant(), index); } catch (Exception exc) { Logger.Error(exc); } } + + internal new void Clear() + { + this._keyIndexLookup.Clear(); + base.Clear(); + } } } diff --git a/DNN Platform/Library/Common/Lists/ListEntryInfo.cs b/DNN Platform/Library/Common/Lists/ListEntryInfo.cs index 3f89b060f07..783151feb1a 100644 --- a/DNN Platform/Library/Common/Lists/ListEntryInfo.cs +++ b/DNN Platform/Library/Common/Lists/ListEntryInfo.cs @@ -1,30 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Linq; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Lists { + using System; + using System.IO; + using System.Linq; + + using DotNetNuke.Common.Utilities; + [Serializable] public class ListEntryInfo { + private string _Text = Null.NullString; + public ListEntryInfo() { - ParentKey = Null.NullString; - Parent = Null.NullString; - Description = Null.NullString; - Text = Null.NullString; - Value = Null.NullString; - ListName = Null.NullString; + this.ParentKey = Null.NullString; + this.Parent = Null.NullString; + this.Description = Null.NullString; + this.Text = Null.NullString; + this.Value = Null.NullString; + this.ListName = Null.NullString; } public int EntryID { get; set; } @@ -35,12 +32,13 @@ public string Key { get { - string _Key = ParentKey.Replace(":", "."); + string _Key = this.ParentKey.Replace(":", "."); if (!string.IsNullOrEmpty(_Key)) { _Key += "."; } - return _Key + ListName + ":" + Value; + + return _Key + this.ListName + ":" + this.Value; } } @@ -50,19 +48,18 @@ public string DisplayName { get { - return ListName + ":" + Text; + return this.ListName + ":" + this.Text; } } public string Value { get; set; } - - private string _Text = Null.NullString; + /// - /// Localized text value of the list entry item. An attempt is made to look up the key "[ParentKey].[Value].Text" in the resource file + /// Gets or sets localized text value of the list entry item. An attempt is made to look up the key "[ParentKey].[Value].Text" in the resource file /// "App_GlobalResources/List_[ListName]". If not found the original (database) value is used. /// /// - /// Localized text value + /// Localized text value. /// public string Text { @@ -72,27 +69,33 @@ public string Text try { string key; - if (string.IsNullOrEmpty(ParentKey)) + if (string.IsNullOrEmpty(this.ParentKey)) { - key = Value + ".Text"; + key = this.Value + ".Text"; } else { - key = ParentKey + '.' + Value + ".Text"; + key = this.ParentKey + '.' + this.Value + ".Text"; } - res = Services.Localization.Localization.GetString(key, ResourceFileRoot); + res = Services.Localization.Localization.GetString(key, this.ResourceFileRoot); } catch { - //ignore + // ignore } - if (string.IsNullOrEmpty(res)) { res = _Text; }; + + if (string.IsNullOrEmpty(res)) + { + res = this._Text; + } + return res; } + set { - _Text = value; + this._Text = value; } } @@ -106,7 +109,7 @@ public string TextNonLocalized { get { - return _Text; + return this._Text; } } @@ -128,18 +131,18 @@ public string TextNonLocalized public bool SystemList { get; set; } - internal string ResourceFileRoot - { - get - { - var listName = ListName.Replace(":", "."); - if (listName.IndexOfAny(Path.GetInvalidFileNameChars()) > -1) - { - listName = Globals.CleanFileName(listName); - } - - return "~/App_GlobalResources/List_" + listName + ".resx"; - } - } + internal string ResourceFileRoot + { + get + { + var listName = this.ListName.Replace(":", "."); + if (listName.IndexOfAny(Path.GetInvalidFileNameChars()) > -1) + { + listName = Globals.CleanFileName(listName); + } + + return "~/App_GlobalResources/List_" + listName + ".resx"; + } + } } } diff --git a/DNN Platform/Library/Common/Lists/ListInfo.cs b/DNN Platform/Library/Common/Lists/ListInfo.cs index f80c8676089..beebf4c9b15 100644 --- a/DNN Platform/Library/Common/Lists/ListInfo.cs +++ b/DNN Platform/Library/Common/Lists/ListInfo.cs @@ -1,33 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Lists { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + [Serializable] public class ListInfo : BaseEntityInfo { - public ListInfo() : this(String.Empty) { } + public ListInfo() + : this(string.Empty) + { + } public ListInfo(string Name) { - SystemList = Null.NullBoolean; - EnableSortOrder = Null.NullBoolean; - IsPopulated = Null.NullBoolean; - ParentList = Null.NullString; - Parent = Null.NullString; - ParentKey = Null.NullString; - PortalID = Null.NullInteger; - DefinitionID = Null.NullInteger; + this.SystemList = Null.NullBoolean; + this.EnableSortOrder = Null.NullBoolean; + this.IsPopulated = Null.NullBoolean; + this.ParentList = Null.NullString; + this.Parent = Null.NullString; + this.ParentKey = Null.NullString; + this.PortalID = Null.NullInteger; + this.DefinitionID = Null.NullInteger; this.Name = Name; } @@ -37,12 +35,13 @@ public string DisplayName { get { - string _DisplayName = Parent; + string _DisplayName = this.Parent; if (!string.IsNullOrEmpty(_DisplayName)) { _DisplayName += ":"; } - return _DisplayName + Name; + + return _DisplayName + this.Name; } } @@ -56,12 +55,13 @@ public string Key { get { - string _Key = ParentKey; + string _Key = this.ParentKey; if (!string.IsNullOrEmpty(_Key)) { _Key += ":"; } - return _Key + Name; + + return _Key + this.Name; } } diff --git a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs index d94d7af4d6c..cd3108ca966 100644 --- a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs @@ -1,43 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Lists { + using System; + using System.Collections; + + using DotNetNuke.Instrumentation; + [Serializable] public class ListInfoCollection : CollectionBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ListInfoCollection)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ListInfoCollection)); private readonly Hashtable mKeyIndexLookup = new Hashtable(); public ListInfo GetChildren(string ParentName) { - return (ListInfo) Item(ParentName); - } - - internal new void Clear() - { - mKeyIndexLookup.Clear(); - base.Clear(); + return (ListInfo)this.Item(ParentName); } public void Add(string key, object value) { int index; - // + + // try { - index = base.List.Add(value); - mKeyIndexLookup.Add(key.ToLowerInvariant(), index); + index = this.List.Add(value); + this.mKeyIndexLookup.Add(key.ToLowerInvariant(), index); } catch (Exception exc) { @@ -50,7 +40,7 @@ public object Item(int index) try { object obj; - obj = base.List[index]; + obj = this.List[index]; return obj; } catch (Exception exc) @@ -60,13 +50,19 @@ public object Item(int index) } } + internal new void Clear() + { + this.mKeyIndexLookup.Clear(); + base.Clear(); + } + public object Item(string key) { int index; object obj; - try //Do validation first + try // Do validation first { - if (mKeyIndexLookup[key.ToLowerInvariant()] == null) + if (this.mKeyIndexLookup[key.ToLowerInvariant()] == null) { return null; } @@ -76,8 +72,9 @@ public object Item(string key) Logger.Error(exc); return null; } - index = Convert.ToInt32(mKeyIndexLookup[key.ToLowerInvariant()]); - obj = base.List[index]; + + index = Convert.ToInt32(this.mKeyIndexLookup[key.ToLowerInvariant()]); + obj = this.List[index]; return obj; } @@ -87,9 +84,9 @@ public object Item(string key, bool Cache) int index; object obj = null; bool itemExists = false; - try //Do validation first + try // Do validation first { - if (mKeyIndexLookup[key.ToLowerInvariant()] != null) + if (this.mKeyIndexLookup[key.ToLowerInvariant()] != null) { itemExists = true; } @@ -98,38 +95,42 @@ public object Item(string key, bool Cache) { Logger.Error(exc); } - //key will be in format Country.US:Region + + // key will be in format Country.US:Region if (!itemExists) { var ctlLists = new ListController(); string listName = key.Substring(key.IndexOf(":") + 1); - string parentKey = key.Replace(listName, "").TrimEnd(':'); + string parentKey = key.Replace(listName, string.Empty).TrimEnd(':'); ListInfo listInfo = ctlLists.GetListInfo(listName, parentKey); - //the collection has been cache, so add this entry list into it if specified + + // the collection has been cache, so add this entry list into it if specified if (Cache) { - Add(listInfo.Key, listInfo); + this.Add(listInfo.Key, listInfo); return listInfo; } } else { - index = Convert.ToInt32(mKeyIndexLookup[key.ToLowerInvariant()]); - obj = base.List[index]; + index = Convert.ToInt32(this.mKeyIndexLookup[key.ToLowerInvariant()]); + obj = this.List[index]; } + return obj; } public ArrayList GetChild(string ParentKey) { var childList = new ArrayList(); - foreach (object child in List) + foreach (object child in this.List) { - if (((ListInfo) child).Key.IndexOf(ParentKey.ToLowerInvariant()) > -1) + if (((ListInfo)child).Key.IndexOf(ParentKey.ToLowerInvariant()) > -1) { childList.Add(child); } } + return childList; } } diff --git a/DNN Platform/Library/Common/NavigationManager.cs b/DNN Platform/Library/Common/NavigationManager.cs index 8c8d797e89e..f0257b2b86c 100644 --- a/DNN Platform/Library/Common/NavigationManager.cs +++ b/DNN Platform/Library/Common/NavigationManager.cs @@ -1,26 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Abstractions; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; -using System; -using System.Linq; -using System.Threading; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common { + using System; + using System.Linq; + using System.Threading; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + internal class NavigationManager : INavigationManager { private readonly IPortalController _portalController; + public NavigationManager(IPortalController portalController) { - _portalController = portalController; + this._portalController = portalController; } /// @@ -29,8 +31,8 @@ public NavigationManager(IPortalController portalController) /// Formatted URL. public string NavigateURL() { - PortalSettings portalSettings = _portalController.GetCurrentPortalSettings(); - return NavigateURL(portalSettings.ActiveTab.TabID, Null.NullString); + PortalSettings portalSettings = this._portalController.GetCurrentPortalSettings(); + return this.NavigateURL(portalSettings.ActiveTab.TabID, Null.NullString); } /// @@ -40,7 +42,7 @@ public string NavigateURL() /// Formatted URL. public string NavigateURL(int tabID) { - return NavigateURL(tabID, Null.NullString); + return this.NavigateURL(tabID, Null.NullString); } /// @@ -51,9 +53,9 @@ public string NavigateURL(int tabID) /// Formatted URL. public string NavigateURL(int tabID, bool isSuperTab) { - IPortalSettings _portalSettings = _portalController.GetCurrentSettings(); + IPortalSettings _portalSettings = this._portalController.GetCurrentSettings(); string cultureCode = Globals.GetCultureCode(tabID, isSuperTab, _portalSettings); - return NavigateURL(tabID, isSuperTab, _portalSettings, Null.NullString, cultureCode); + return this.NavigateURL(tabID, isSuperTab, _portalSettings, Null.NullString, cultureCode); } /// @@ -69,8 +71,8 @@ public string NavigateURL(string controlKey) } else { - PortalSettings _portalSettings = _portalController.GetCurrentPortalSettings(); - return NavigateURL(_portalSettings.ActiveTab.TabID, controlKey); + PortalSettings _portalSettings = this._portalController.GetCurrentPortalSettings(); + return this.NavigateURL(_portalSettings.ActiveTab.TabID, controlKey); } } @@ -82,8 +84,8 @@ public string NavigateURL(string controlKey) /// Formatted URL. public string NavigateURL(string controlKey, params string[] additionalParameters) { - PortalSettings _portalSettings = _portalController.GetCurrentPortalSettings(); - return NavigateURL(_portalSettings?.ActiveTab?.TabID ?? -1, controlKey, additionalParameters); + PortalSettings _portalSettings = this._portalController.GetCurrentPortalSettings(); + return this.NavigateURL(_portalSettings?.ActiveTab?.TabID ?? -1, controlKey, additionalParameters); } /// @@ -94,8 +96,8 @@ public string NavigateURL(string controlKey, params string[] additionalParameter /// Formatted URL. public string NavigateURL(int tabID, string controlKey) { - PortalSettings _portalSettings = _portalController.GetCurrentPortalSettings(); - return NavigateURL(tabID, _portalSettings, controlKey, null); + PortalSettings _portalSettings = this._portalController.GetCurrentPortalSettings(); + return this.NavigateURL(tabID, _portalSettings, controlKey, null); } /// @@ -107,8 +109,8 @@ public string NavigateURL(int tabID, string controlKey) /// Formatted URL. public string NavigateURL(int tabID, string controlKey, params string[] additionalParameters) { - PortalSettings _portalSettings = _portalController.GetCurrentPortalSettings(); - return NavigateURL(tabID, _portalSettings, controlKey, additionalParameters); + PortalSettings _portalSettings = this._portalController.GetCurrentPortalSettings(); + return this.NavigateURL(tabID, _portalSettings, controlKey, additionalParameters); } /// @@ -123,7 +125,7 @@ public string NavigateURL(int tabID, IPortalSettings settings, string controlKey { bool isSuperTab = Globals.IsHostTab(tabID); - return NavigateURL(tabID, isSuperTab, settings, controlKey, additionalParameters); + return this.NavigateURL(tabID, isSuperTab, settings, controlKey, additionalParameters); } /// @@ -138,7 +140,7 @@ public string NavigateURL(int tabID, IPortalSettings settings, string controlKey public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, string controlKey, params string[] additionalParameters) { string cultureCode = Globals.GetCultureCode(tabID, isSuperTab, settings); - return NavigateURL(tabID, isSuperTab, settings, controlKey, cultureCode, additionalParameters); + return this.NavigateURL(tabID, isSuperTab, settings, controlKey, cultureCode, additionalParameters); } /// @@ -153,7 +155,7 @@ public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, /// Formatted URL. public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, string controlKey, string language, params string[] additionalParameters) { - return NavigateURL(tabID, isSuperTab, settings, controlKey, language, Globals.glbDefaultPage, additionalParameters); + return this.NavigateURL(tabID, isSuperTab, settings, controlKey, language, Globals.glbDefaultPage, additionalParameters); } /// @@ -170,14 +172,16 @@ public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, string controlKey, string language, string pageName, params string[] additionalParameters) { string url = tabID == Null.NullInteger ? Globals.ApplicationURL() : Globals.ApplicationURL(tabID); - if (!String.IsNullOrEmpty(controlKey)) + if (!string.IsNullOrEmpty(controlKey)) { url += "&ctl=" + controlKey; } + if (additionalParameters != null) { url = additionalParameters.Where(parameter => !string.IsNullOrEmpty(parameter)).Aggregate(url, (current, parameter) => current + ("&" + parameter)); } + if (isSuperTab) { url += "&portalid=" + settings.PortalId; @@ -190,12 +194,12 @@ public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, tab = TabController.Instance.GetTab(tabID, isSuperTab ? Null.NullInteger : settings.PortalId, false); } - //only add language to url if more than one locale is enabled + // only add language to url if more than one locale is enabled if (settings != null && language != null && LocaleController.Instance.GetLocales(settings.PortalId).Count > 1) { if (settings.ContentLocalizationEnabled) { - if (language == "") + if (language == string.Empty) { if (tab != null && !string.IsNullOrEmpty(tab.CultureCode)) { @@ -209,8 +213,8 @@ public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, } else if (settings.EnableUrlLanguage) { - //legacy pre 5.5 behavior - if (language == "") + // legacy pre 5.5 behavior + if (language == string.Empty) { url += "&language=" + Thread.CurrentThread.CurrentCulture.Name; } @@ -223,7 +227,7 @@ public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, if (Host.UseFriendlyUrls || Config.GetFriendlyUrlProvider() == "advanced") { - if (String.IsNullOrEmpty(pageName)) + if (string.IsNullOrEmpty(pageName)) { pageName = Globals.glbDefaultPage; } diff --git a/DNN Platform/Library/Common/Requires.cs b/DNN Platform/Library/Common/Requires.cs index 0c968111142..dd0b3c7eca9 100644 --- a/DNN Platform/Library/Common/Requires.cs +++ b/DNN Platform/Library/Common/Requires.cs @@ -1,43 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common { - /// - /// Assert Class. - /// + using System; + + using DotNetNuke.Services.Localization; + + /// + /// Assert Class. + /// public static class Requires { - /// - /// Determines whether argValue is type of T. - /// - /// - /// Name of the arg. - /// The arg value. - /// + /// + /// Determines whether argValue is type of T. + /// + /// + /// Name of the arg. + /// The arg value. + /// public static void IsTypeOf(string argName, object argValue) { - if (!((argValue) is T)) + if (!(argValue is T)) { - throw new ArgumentException(Localization.GetExceptionMessage("ValueMustBeOfType", "The argument '{0}' must be of type '{1}'.", argName, typeof (T).FullName)); + throw new ArgumentException(Localization.GetExceptionMessage("ValueMustBeOfType", "The argument '{0}' must be of type '{1}'.", argName, typeof(T).FullName)); } } - /// - /// Determines whether argValue is less than zero. - /// - /// Name of the arg. - /// The arg value. - /// + /// + /// Determines whether argValue is less than zero. + /// + /// Name of the arg. + /// The arg value. + /// public static void NotNegative(string argName, int argValue) { if (argValue < 0) @@ -73,12 +68,12 @@ public static void NotNull(string argName, object argValue) } } - /// - /// Determines whether the argValue is null or empty. - /// - /// Name of the arg. - /// The arg value. - /// + /// + /// Determines whether the argValue is null or empty. + /// + /// Name of the arg. + /// The arg value. + /// public static void NotNullOrEmpty(string argName, string argValue) { if (string.IsNullOrEmpty(argValue)) @@ -109,7 +104,7 @@ public static void NotNullOrHasNoWhiteSpace(string argName, string argValue) /// public static void PropertyNotNegative(T item, string propertyName) { - //Check first if the item is null + // Check first if the item is null NotNull(item); var type = typeof(T); @@ -120,7 +115,8 @@ public static void PropertyNotNegative(T item, string propertyName) if (intValue < 0) { - throw new ArgumentOutOfRangeException(propertyName, + throw new ArgumentOutOfRangeException( + propertyName, Localization.GetExceptionMessage("PropertyCannotBeNegative", "The property '{1}' in object '{0}' cannot be negative.", typeof(T).Name, propertyName)); } } @@ -136,8 +132,9 @@ public static void PropertyNotNegative(string argName, string argProperty, int p { if (propertyValue < 0) { - throw new ArgumentOutOfRangeException(argName, - Localization.GetExceptionMessage("PropertyCannotBeNegative", "The property '{1}' in object '{0}' cannot be negative.", argName, argProperty)); + throw new ArgumentOutOfRangeException( + argName, + Localization.GetExceptionMessage("PropertyCannotBeNegative", "The property '{1}' in object '{0}' cannot be negative.", argName, argProperty)); } } @@ -158,9 +155,10 @@ public static void PropertyNotNull(string argName, string argValue) /// The object to test. /// Name of the property. /// - public static void PropertyNotNull(T item, string propertyName) where T : class + public static void PropertyNotNull(T item, string propertyName) + where T : class { - //Check first if the item is null + // Check first if the item is null NotNull(item); var type = typeof(T); @@ -181,7 +179,7 @@ public static void PropertyNotNull(T item, string propertyName) where T : cla /// public static void PropertyNotNullOrEmpty(T item, string propertyName) { - //Check first if the item is null + // Check first if the item is null NotNull(item); var type = typeof(T); @@ -206,21 +204,23 @@ public static void PropertyNotNullOrEmpty(string argName, string argProperty, st { if (string.IsNullOrEmpty(propertyValue)) { - throw new ArgumentException(argName, - Localization.GetExceptionMessage("PropertyCannotBeNullOrEmpty", "The property '{1}' in object '{0}' cannot be null or empty.", argName, argProperty)); + throw new ArgumentException( + argName, + Localization.GetExceptionMessage("PropertyCannotBeNullOrEmpty", "The property '{1}' in object '{0}' cannot be null or empty.", argName, argProperty)); } } - /// - /// Determines whether propertyValue equal to testValue. - /// - /// The type of the value. - /// Name of the arg. - /// The arg property. - /// The property value. - /// The test value. - /// - public static void PropertyNotEqualTo(string argName, string argProperty, TValue propertyValue, TValue testValue) where TValue : IEquatable + /// + /// Determines whether propertyValue equal to testValue. + /// + /// The type of the value. + /// Name of the arg. + /// The arg property. + /// The property value. + /// The test value. + /// + public static void PropertyNotEqualTo(string argName, string argProperty, TValue propertyValue, TValue testValue) + where TValue : IEquatable { if (propertyValue.Equals(testValue)) { diff --git a/DNN Platform/Library/Common/SerializableKeyValuePair.cs b/DNN Platform/Library/Common/SerializableKeyValuePair.cs index 94740830499..754be62587c 100644 --- a/DNN Platform/Library/Common/SerializableKeyValuePair.cs +++ b/DNN Platform/Library/Common/SerializableKeyValuePair.cs @@ -1,33 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Common.Utilities; + [DataContract] public class SerializableKeyValuePair { + public SerializableKeyValuePair(TKey key, TValue value) + { + this.Key = key; + this.Value = value; + } + [DataMember(Name = "key")] public TKey Key { get; set; } [DataMember(Name = "value")] public TValue Value { get; set; } - public SerializableKeyValuePair(TKey key, TValue value) - { - Key = key; - Value = value; - } - public override string ToString() { return Json.Serialize(this); } } - } diff --git a/DNN Platform/Library/Common/Utilities/CBO.cs b/DNN Platform/Library/Common/Utilities/CBO.cs index 1680cef91e7..94f93369189 100644 --- a/DNN Platform/Library/Common/Utilities/CBO.cs +++ b/DNN Platform/Library/Common/Utilities/CBO.cs @@ -1,55 +1,130 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; -using System.Xml.Serialization; - -using DotNetNuke.Entities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Text; + using System.Text.RegularExpressions; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Entities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Scheduling; + /// /// The CBO class generates objects. /// public partial class CBO : ServiceLocator, ICBO - { - #region Private Constants - + { private const string defaultPrimaryKey = "ItemID"; - private const string objectMapCacheKey = "ObjectMap_"; - - #endregion + private const string objectMapCacheKey = "ObjectMap_"; + + /// ----------------------------------------------------------------------------- + /// + /// CloneObject clones an object. + /// + /// The Object to Clone. + /// + /// ----------------------------------------------------------------------------- + public static object CloneObject(object objObject) + { + try + { + Type objType = objObject.GetType(); + object objNewObject = Activator.CreateInstance(objType); + + // get cached object mapping for type + ObjectMappingInfo objMappingInfo = GetObjectMapping(objType); + foreach (KeyValuePair kvp in objMappingInfo.Properties) + { + PropertyInfo objProperty = kvp.Value; + if (objProperty.CanWrite) + { + // Check if property is ICloneable + var objPropertyClone = objProperty.GetValue(objObject, null) as ICloneable; + if (objPropertyClone == null) + { + objProperty.SetValue(objNewObject, objProperty.GetValue(objObject, null), null); + } + else + { + objProperty.SetValue(objNewObject, objPropertyClone.Clone(), null); + } + + // Check if Property is IEnumerable + var enumerable = objProperty.GetValue(objObject, null) as IEnumerable; + if (enumerable != null) + { + var list = objProperty.GetValue(objNewObject, null) as IList; + if (list != null) + { + foreach (object obj in enumerable) + { + list.Add(CloneObject(obj)); + } + } + + var dic = objProperty.GetValue(objNewObject, null) as IDictionary; + if (dic != null) + { + foreach (DictionaryEntry de in enumerable) + { + dic.Add(de.Key, CloneObject(de.Value)); + } + } + } + } + } + + return objNewObject; + } + catch (Exception exc) + { + Exceptions.LogException(exc); + return null; + } + } + + public static void CloseDataReader(IDataReader dr, bool closeReader) + { + // close datareader + if (dr != null && closeReader) + { + using (dr) + { + dr.Close(); + } + } + } + + List ICBO.FillCollection(IDataReader dr) + { + return (List)FillListFromReader(dr, new List(), true); + } + TObject ICBO.FillObject(IDataReader dr) + { + return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); + } + protected override Func GetFactory() { return () => new CBO(); - } - - #region Private Shared Methods - - #region Object Creation/Hydration Helper Methods - + } + private static object CreateObjectInternal(Type objType, bool initialise) { object objObject = Activator.CreateInstance(objType); @@ -58,8 +133,8 @@ private static object CreateObjectInternal(Type objType, bool initialise) { InitializeObject(objObject); } + return objObject; - } private static object CreateObjectFromReader(Type objType, IDataReader dr, bool closeReader) @@ -71,33 +146,38 @@ private static object CreateObjectFromReader(Type objType, IDataReader dr, bool if (closeReader) { canRead = false; - //read datareader + + // read datareader if (dr.Read()) { canRead = true; } } + try { if (canRead) { - //Create the Object + // Create the Object objObject = CreateObjectInternal(objType, false); - //hydrate the custom business object + // hydrate the custom business object FillObjectFromReader(objObject, dr); } + isSuccess = true; } finally { - //Ensure DataReader is closed - if ((!isSuccess)) + // Ensure DataReader is closed + if (!isSuccess) { closeReader = true; } + CloseDataReader(dr, closeReader); } + return objObject; } @@ -112,52 +192,55 @@ private static IDictionary FillDictionaryFromReader( try { - //iterate datareader + // iterate datareader while (dr.Read()) { - //Create the Object - objObject = (TValue) CreateObjectFromReader(typeof (TValue), dr, false); + // Create the Object + objObject = (TValue)CreateObjectFromReader(typeof(TValue), dr, false); if (keyField == "KeyID" && objObject is IHydratable) { - //Get the value of the key field from the KeyID - keyValue = (TKey) Null.SetNull(((IHydratable) objObject).KeyID, keyValue); + // Get the value of the key field from the KeyID + keyValue = (TKey)Null.SetNull(((IHydratable)objObject).KeyID, keyValue); } else { - //Get the value of the key field from the DataReader - if (typeof (TKey).Name == "Int32" && dr[keyField].GetType().Name == "Decimal") + // Get the value of the key field from the DataReader + if (typeof(TKey).Name == "Int32" && dr[keyField].GetType().Name == "Decimal") { - keyValue = (TKey) Convert.ChangeType(Null.SetNull(dr[keyField], keyValue), typeof (TKey)); + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], keyValue), typeof(TKey)); } - else if (typeof (TKey).Name.Equals("string", StringComparison.OrdinalIgnoreCase) && + else if (typeof(TKey).Name.Equals("string", StringComparison.OrdinalIgnoreCase) && dr[keyField].GetType().Name.Equals("dbnull", StringComparison.OrdinalIgnoreCase)) { - keyValue = (TKey) Convert.ChangeType(Null.SetNull(dr[keyField], ""), typeof (TKey)); + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); } else { - keyValue = (TKey) Convert.ChangeType(Null.SetNull(dr[keyField], ""), typeof (TKey)); + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); } } - //add to dictionary + + // add to dictionary if (objObject != null) { objDictionary[keyValue] = objObject; } } + isSuccess = true; } finally { - //Ensure DataReader is closed - if ((!isSuccess)) + // Ensure DataReader is closed + if (!isSuccess) { closeReader = true; } + CloseDataReader(dr, closeReader); } - - //Return the dictionary + + // Return the dictionary return objDictionary; } @@ -167,25 +250,29 @@ private static IList FillListFromReader(Type objType, IDataReader dr, IList objL bool isSuccess = Null.NullBoolean; try { - //iterate datareader + // iterate datareader while (dr.Read()) { - //Create the Object + // Create the Object objObject = CreateObjectFromReader(objType, dr, false); - //add to collection + + // add to collection objList.Add(objObject); } + isSuccess = true; } finally { - //Ensure DataReader is closed - if ((!isSuccess)) + // Ensure DataReader is closed + if (!isSuccess) { closeReader = true; } + CloseDataReader(dr, closeReader); } + return objList; } @@ -195,25 +282,29 @@ private static IList FillListFromReader(IDataReader dr, IList ICBO.FillCollection(IDataReader dr) - { - return (List)FillListFromReader(dr, new List(), true); - } - - TObject ICBO.FillObject(IDataReader dr) - { - return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); - } + } TObject ICBO.GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary) { return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired, saveInDictionary); - } - - #endregion - - #region Public Shared Methods - - #region Clone Object - - /// ----------------------------------------------------------------------------- - /// - /// CloneObject clones an object - /// - /// The Object to Clone - /// ----------------------------------------------------------------------------- - public static object CloneObject(object objObject) - { - try - { - Type objType = objObject.GetType(); - object objNewObject = Activator.CreateInstance(objType); - //get cached object mapping for type - ObjectMappingInfo objMappingInfo = GetObjectMapping(objType); - foreach (KeyValuePair kvp in objMappingInfo.Properties) - { - PropertyInfo objProperty = kvp.Value; - if (objProperty.CanWrite) - { - //Check if property is ICloneable - var objPropertyClone = objProperty.GetValue(objObject, null) as ICloneable; - if (objPropertyClone == null) - { - objProperty.SetValue(objNewObject, objProperty.GetValue(objObject, null), null); - } - else - { - objProperty.SetValue(objNewObject, objPropertyClone.Clone(), null); - } - //Check if Property is IEnumerable - var enumerable = objProperty.GetValue(objObject, null) as IEnumerable; - if (enumerable != null) - { - var list = objProperty.GetValue(objNewObject, null) as IList; - if (list != null) - { - foreach (object obj in enumerable) - { - list.Add(CloneObject(obj)); - } - } - var dic = objProperty.GetValue(objNewObject, null) as IDictionary; - if (dic != null) - { - foreach (DictionaryEntry de in enumerable) - { - dic.Add(de.Key, CloneObject(de.Value)); - } - } - } - } - } - return objNewObject; - } - catch (Exception exc) - { - Exceptions.LogException(exc); - return null; - } - } - - #endregion - - #region CloseDataReader - - public static void CloseDataReader(IDataReader dr, bool closeReader) - { - //close datareader - if (dr != null && closeReader) - { - using (dr) { dr.Close(); } - } - } - - #endregion - - #region Create Object - + } + /// ----------------------------------------------------------------------------- /// /// CreateObject creates a new object of Type TObject. /// /// The type of object to create. /// A flag that indicates whether to initialise the - /// object. + /// object. + /// /// ----------------------------------------------------------------------------- public static TObject CreateObject(bool initialise) { return (TObject)CreateObjectInternal(typeof(TObject), initialise); - } - - #endregion - - #region DeserializeObject - + } + public static TObject DeserializeObject(string fileName) { return DeserializeObject(XmlReader.Create(new FileStream(fileName, FileMode.Open, FileAccess.Read))); @@ -567,60 +564,61 @@ public static TObject DeserializeObject(TextReader reader) public static TObject DeserializeObject(XmlReader reader) { - //First Create the Object + // First Create the Object var objObject = CreateObject(true); - //Try to cast the Object as IXmlSerializable + + // Try to cast the Object as IXmlSerializable var xmlSerializableObject = objObject as IXmlSerializable; if (xmlSerializableObject == null) { - //Use XmlSerializer + // Use XmlSerializer var serializer = new XmlSerializer(objObject.GetType()); - objObject = (TObject) serializer.Deserialize(reader); + objObject = (TObject)serializer.Deserialize(reader); } else { - //Use XmlReader + // Use XmlReader xmlSerializableObject.ReadXml(reader); } + return objObject; - } - - #endregion - - #region FillCollection - + } + /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader + /// FillCollection fills a Collection of objects from a DataReader. /// - /// The Data Reader - /// The type of the Object + /// The Data Reader. + /// The type of the Object. + /// /// ----------------------------------------------------------------------------- public static ArrayList FillCollection(IDataReader dr, Type objType) { - return (ArrayList) FillListFromReader(objType, dr, new ArrayList(), true); + return (ArrayList)FillListFromReader(objType, dr, new ArrayList(), true); } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader + /// FillCollection fills a Collection of objects from a DataReader. /// - /// The Data Reader - /// The type of the Object - /// Flag that indicates whether the Data Reader should be closed. + /// The Data Reader. + /// The type of the Object. + /// Flag that indicates whether the Data Reader should be closed. + /// /// ----------------------------------------------------------------------------- public static ArrayList FillCollection(IDataReader dr, Type objType, bool closeReader) { - return (ArrayList) FillListFromReader(objType, dr, new ArrayList(), closeReader); + return (ArrayList)FillListFromReader(objType, dr, new ArrayList(), closeReader); } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader + /// FillCollection fills a Collection of objects from a DataReader. /// - /// The Data Reader - /// The type of the Object - /// An IList to fill + /// The Data Reader. + /// The type of the Object. + /// An IList to fill. + /// /// ----------------------------------------------------------------------------- public static IList FillCollection(IDataReader dr, Type objType, ref IList objToFill) { @@ -629,23 +627,25 @@ public static IList FillCollection(IDataReader dr, Type objType, ref IList objTo /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader + /// FillCollection fills a Collection of objects from a DataReader. /// - /// The type of object - /// The Data Reader + /// The type of object. + /// The Data Reader. + /// /// ----------------------------------------------------------------------------- public static List FillCollection(IDataReader dr) { - return (List) FillListFromReader(dr, new List(), true); + return (List)FillListFromReader(dr, new List(), true); } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader + /// FillCollection fills a Collection of objects from a DataReader. /// - /// The type of object - /// The List to fill - /// The Data Reader + /// The type of object. + /// The List to fill. + /// The Data Reader. + /// /// ----------------------------------------------------------------------------- public static IList FillCollection(IDataReader dr, ref IList objToFill) { @@ -654,12 +654,13 @@ public static IList FillCollection(IDataReader dr, ref IList - /// FillCollection fills a List of objects from a DataReader + /// FillCollection fills a List of objects from a DataReader. /// - /// The type of the Object - /// The List to fill - /// The Data Reader - /// A flag that indicates whether the DataReader should be closed + /// The type of the Object. + /// The List to fill. + /// The Data Reader. + /// A flag that indicates whether the DataReader should be closed. + /// /// ----------------------------------------------------------------------------- public static IList FillCollection(IDataReader dr, IList objToFill, bool closeReader) { @@ -668,23 +669,23 @@ public static IList FillCollection(IDataReader dr, IList ob /// ----------------------------------------------------------------------------- /// - /// Generic version of FillCollection fills a List custom business object of a specified type - /// from the supplied DataReader + /// Generic version of FillCollection fills a List custom business object of a specified type + /// from the supplied DataReader. /// - /// The IDataReader to use to fill the object - /// The type of the Object - /// The total No of records - /// A List of custom business objects + /// The IDataReader to use to fill the object. + /// The type of the Object. + /// The total No of records. + /// A List of custom business objects. /// /// ----------------------------------------------------------------------------- public static ArrayList FillCollection(IDataReader dr, ref Type objType, ref int totalRecords) { - var objFillCollection = (ArrayList) FillListFromReader(objType, dr, new ArrayList(), false); + var objFillCollection = (ArrayList)FillListFromReader(objType, dr, new ArrayList(), false); try { if (dr.NextResult()) { - //Get the total no of records from the second result + // Get the total no of records from the second result totalRecords = Globals.GetTotalRecords(ref dr); } } @@ -694,21 +695,22 @@ public static ArrayList FillCollection(IDataReader dr, ref Type objType, ref int } finally { - //Ensure DataReader is closed + // Ensure DataReader is closed CloseDataReader(dr, true); } + return objFillCollection; } /// ----------------------------------------------------------------------------- /// - /// Generic version of FillCollection fills a List custom business object of a specified type - /// from the supplied DataReader + /// Generic version of FillCollection fills a List custom business object of a specified type + /// from the supplied DataReader. /// - /// The type of the business object - /// The IDataReader to use to fill the object + /// The type of the business object. + /// The IDataReader to use to fill the object. /// - /// A List of custom business objects + /// A List of custom business objects. /// /// ----------------------------------------------------------------------------- public static List FillCollection(IDataReader dr, ref int totalRecords) @@ -718,7 +720,7 @@ public static List FillCollection(IDataReader dr, ref int totalRecords) { if (dr.NextResult()) { - //Get the total no of records from the second result + // Get the total no of records from the second result totalRecords = Globals.GetTotalRecords(ref dr); } } @@ -728,88 +730,84 @@ public static List FillCollection(IDataReader dr, ref int totalRecords) } finally { - //Ensure DataReader is closed + // Ensure DataReader is closed CloseDataReader(dr, true); } - return (List) objFillCollection; - } - - #endregion - - #region FillDictionary - + + return (List)objFillCollection; + } + /// - /// FillDictionary fills a Dictionary of objects from a DataReader + /// FillDictionary fills a Dictionary of objects from a DataReader. /// - /// The key for the Dictionary - /// The value for the Dictionary Item - /// The key field used for the Key - /// The Data Reader + /// The key for the Dictionary. + /// The value for the Dictionary Item. + /// The key field used for the Key. + /// The Data Reader. + /// public static Dictionary FillDictionary(string keyField, IDataReader dr) { return - (Dictionary) FillDictionaryFromReader(keyField, dr, new Dictionary(), true); + (Dictionary)FillDictionaryFromReader(keyField, dr, new Dictionary(), true); } /// - /// FillDictionary fills a Dictionary of objects from a DataReader + /// FillDictionary fills a Dictionary of objects from a DataReader. /// - /// The key for the Dictionary - /// The value for the Dictionary Item - /// The key field used for the Key - /// The Data Reader - /// A flag indicating whether to close the reader. + /// The key for the Dictionary. + /// The value for the Dictionary Item. + /// The key field used for the Key. + /// The Data Reader. + /// A flag indicating whether to close the reader. + /// public static Dictionary FillDictionary(string keyField, IDataReader dr, bool closeReader) { - return (Dictionary) FillDictionaryFromReader(keyField, dr, new Dictionary(), closeReader); + return (Dictionary)FillDictionaryFromReader(keyField, dr, new Dictionary(), closeReader); } /// ----------------------------------------------------------------------------- /// - /// FillDictionary fills a Dictionary of objects from a DataReader + /// FillDictionary fills a Dictionary of objects from a DataReader. /// - /// The key for the Dictionary - /// The value for the Dictionary Item - /// The key field used for the Key - /// The Dictionary to fill - /// The Data Reader + /// The key for the Dictionary. + /// The value for the Dictionary Item. + /// The key field used for the Key. + /// The Dictionary to fill. + /// The Data Reader. + /// /// ----------------------------------------------------------------------------- public static Dictionary FillDictionary(string keyField, IDataReader dr, IDictionary objDictionary) { - return (Dictionary) FillDictionaryFromReader(keyField, dr, objDictionary, true); - } - - #endregion - - #region FillObject - + return (Dictionary)FillDictionaryFromReader(keyField, dr, objDictionary, true); + } + /// ----------------------------------------------------------------------------- /// - /// FillObject fills an object from a DataReader + /// FillObject fills an object from a DataReader. /// - /// The type of the object - /// The Data Reader + /// The type of the object. + /// The Data Reader. + /// /// ----------------------------------------------------------------------------- public static TObject FillObject(IDataReader dr) { - return (TObject) CreateObjectFromReader(typeof (TObject), dr, true); + return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); } /// ----------------------------------------------------------------------------- /// - /// FillObject fills an object from a DataReader + /// FillObject fills an object from a DataReader. /// - /// The type of the object - /// The Data Reader - /// A flag that indicates the reader should be closed + /// The type of the object. + /// The Data Reader. + /// A flag that indicates the reader should be closed. + /// /// ----------------------------------------------------------------------------- public static TObject FillObject(IDataReader dr, bool closeReader) { - return (TObject) CreateObjectFromReader(typeof (TObject), dr, closeReader); - } - - #endregion - + return (TObject)CreateObjectFromReader(typeof(TObject), dr, closeReader); + } + public static IQueryable FillQueryable(IDataReader dr) { return FillListFromReader(dr, new List(), true).AsQueryable(); @@ -817,17 +815,18 @@ public static IQueryable FillQueryable(IDataReader dr) /// ----------------------------------------------------------------------------- /// - /// FillSortedList fills a SortedList of objects from a DataReader + /// FillSortedList fills a SortedList of objects from a DataReader. /// - /// The key for the SortedList - /// The value for the SortedList Item - /// The key field used for the Key - /// The Data Reader + /// The key for the SortedList. + /// The value for the SortedList Item. + /// The key field used for the Key. + /// The Data Reader. + /// /// ----------------------------------------------------------------------------- public static SortedList FillSortedList(string keyField, IDataReader dr) { return - (SortedList) FillDictionaryFromReader(keyField, dr, new SortedList(), true); + (SortedList)FillDictionaryFromReader(keyField, dr, new SortedList(), true); } public static void DeserializeSettings(IDictionary dictionary, XmlNode rootNode, string elementName) @@ -844,15 +843,15 @@ public static void DeserializeSettings(IDictionary dictionary, XmlNode rootNode, } } - /// - /// Iterates items in a IDictionary object and generates XML nodes - /// - ///The IDictionary to iterate - ///The XML document the node should be added to - ///Path at which to serialize settings - ///The name of the new element created - /// - /// + /// + /// Iterates items in a IDictionary object and generates XML nodes. + /// + /// The IDictionary to iterate. + /// The XML document the node should be added to. + /// Path at which to serialize settings. + /// The name of the new element created. + /// + /// public static void SerializeSettings(IDictionary dictionary, XmlDocument document, string targetPath, string elementName) { @@ -876,26 +875,25 @@ public static void SerializeSettings(IDictionary dictionary, XmlDocument documen nodeSettingName.InnerText = sKey.ToString(); nodeSettingValue = nodeSetting.AppendChild(document.CreateElement("settingvalue")); - nodeSettingValue.InnerText = dictionary[sKey].ToString(); - } + nodeSettingValue.InnerText = dictionary[sKey].ToString(); + } } else { throw new ArgumentException("Invalid Target Path"); } - } - - #region "GetCachedObject" - + } + /// ----------------------------------------------------------------------------- /// - /// GetCachedObject gets an object from the Cache + /// GetCachedObject gets an object from the Cache. /// - /// The type of th object to fetch + /// The type of th object to fetch. /// A CacheItemArgs object that provides parameters to manage the - /// cache AND to fetch the item if the cache has expired + /// cache AND to fetch the item if the cache has expired. /// A CacheItemExpiredCallback delegate that is used to repopulate - /// the cache if the item has expired + /// the cache if the item has expired. + /// /// ----------------------------------------------------------------------------- public static TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) { @@ -905,48 +903,42 @@ public static TObject GetCachedObject(CacheItemArgs cacheItemArgs, Cach public static TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary) { return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired, saveInDictionary); - } - - #endregion - - #region "GetProperties" - + } + /// ----------------------------------------------------------------------------- /// - /// GetProperties gets a Dictionary of the Properties for an object + /// GetProperties gets a Dictionary of the Properties for an object. /// - /// The type of the object + /// The type of the object. + /// /// ----------------------------------------------------------------------------- public static Dictionary GetProperties() { - return GetObjectMapping(typeof (TObject)).Properties; + return GetObjectMapping(typeof(TObject)).Properties; } /// ----------------------------------------------------------------------------- /// - /// GetProperties gets a Dictionary of the Properties for an object + /// GetProperties gets a Dictionary of the Properties for an object. /// - /// The type of the object + /// The type of the object. + /// /// ----------------------------------------------------------------------------- public static Dictionary GetProperties(Type objType) { return GetObjectMapping(objType).Properties; - } - - #endregion - - #region "InitializeObject" - + } + /// ----------------------------------------------------------------------------- /// - /// InitializeObject initialises all the properties of an object to their + /// InitializeObject initialises all the properties of an object to their /// Null Values. /// - /// The object to Initialise + /// The object to Initialise. /// ----------------------------------------------------------------------------- public static void InitializeObject(object objObject) { - //initialize properties + // initialize properties foreach (PropertyInfo objPropertyInfo in GetObjectMapping(objObject.GetType()).Properties.Values) { if (objPropertyInfo.CanWrite) @@ -958,15 +950,16 @@ public static void InitializeObject(object objObject) /// ----------------------------------------------------------------------------- /// - /// InitializeObject initialises all the properties of an object to their + /// InitializeObject initialises all the properties of an object to their /// Null Values. /// - /// The object to Initialise - /// The type of the object + /// The object to Initialise. + /// The type of the object. + /// /// ----------------------------------------------------------------------------- public static object InitializeObject(object objObject, Type objType) { - //initialize properties + // initialize properties foreach (PropertyInfo objPropertyInfo in GetObjectMapping(objType).Properties.Values) { if (objPropertyInfo.CanWrite) @@ -974,19 +967,16 @@ public static object InitializeObject(object objObject, Type objType) objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null); } } + return objObject; - } - - #endregion - - #region "SerializeObject" - + } + /// ----------------------------------------------------------------------------- /// - /// SerializeObject serializes an Object + /// SerializeObject serializes an Object. /// - /// The object to Initialise - /// A filename for the resulting serialized xml + /// The object to Initialise. + /// A filename for the resulting serialized xml. /// ----------------------------------------------------------------------------- public static void SerializeObject(object objObject, string fileName) { @@ -1000,34 +990,34 @@ public static void SerializeObject(object objObject, string fileName) /// ----------------------------------------------------------------------------- /// - /// SerializeObject serializes an Object + /// SerializeObject serializes an Object. /// - /// The object to Initialise - /// An XmlDocument to serialize to + /// The object to Initialise. + /// An XmlDocument to serialize to. /// ----------------------------------------------------------------------------- public static void SerializeObject(object objObject, XmlDocument document) { var sb = new StringBuilder(); using (var writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Document))) { - //Serialize the object + // Serialize the object SerializeObject(objObject, writer); - //Load XmlDocument + + // Load XmlDocument document.LoadXml(sb.ToString()); } } /// ----------------------------------------------------------------------------- /// - /// SerializeObject serializes an Object + /// SerializeObject serializes an Object. /// - /// The object to Initialise - /// A Stream to serialize to + /// The object to Initialise. + /// A Stream to serialize to. /// ----------------------------------------------------------------------------- public static void SerializeObject(object objObject, Stream stream) { - using (XmlWriter writer = XmlWriter.Create(stream, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment)) - ) + using (XmlWriter writer = XmlWriter.Create(stream, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) { SerializeObject(objObject, writer); writer.Flush(); @@ -1036,16 +1026,15 @@ public static void SerializeObject(object objObject, Stream stream) /// ----------------------------------------------------------------------------- /// - /// SerializeObject serializes an Object + /// SerializeObject serializes an Object. /// - /// The object to Initialise - /// A TextWriter to serialize to + /// The object to Initialise. + /// A TextWriter to serialize to. /// ----------------------------------------------------------------------------- public static void SerializeObject(object objObject, TextWriter textWriter) { using ( - XmlWriter writer = XmlWriter.Create(textWriter, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment)) - ) + XmlWriter writer = XmlWriter.Create(textWriter, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) { SerializeObject(objObject, writer); writer.Flush(); @@ -1054,30 +1043,26 @@ public static void SerializeObject(object objObject, TextWriter textWriter) /// ----------------------------------------------------------------------------- /// - /// SerializeObject serializes an Object + /// SerializeObject serializes an Object. /// - /// The object to Initialise - /// An XmlWriter to serialize to + /// The object to Initialise. + /// An XmlWriter to serialize to. /// ----------------------------------------------------------------------------- public static void SerializeObject(object objObject, XmlWriter writer) { - //Try to cast the Object as IXmlSerializable + // Try to cast the Object as IXmlSerializable var xmlSerializableObject = objObject as IXmlSerializable; if (xmlSerializableObject == null) { - //Use XmlSerializer + // Use XmlSerializer var serializer = new XmlSerializer(objObject.GetType()); serializer.Serialize(writer, objObject); } else { - //Use XmlWriter + // Use XmlWriter xmlSerializableObject.WriteXml(writer); } - } - - #endregion - - #endregion + } } } diff --git a/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs b/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs index 9395eee3794..fa70065a2dd 100644 --- a/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs +++ b/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.Web.Caching; - -using DotNetNuke.Services.Cache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System.Collections; + using System.Web.Caching; + + using DotNetNuke.Services.Cache; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Common.Utilities @@ -20,146 +15,152 @@ namespace DotNetNuke.Common.Utilities /// ----------------------------------------------------------------------------- /// /// The CacheItemArgs class provides an EventArgs implementation for the - /// CacheItemExpiredCallback delegate + /// CacheItemExpiredCallback delegate. /// /// ----------------------------------------------------------------------------- public class CacheItemArgs { - private ArrayList _paramList; - - ///----------------------------------------------------------------------------- - /// - /// Constructs a new CacheItemArgs Object + private ArrayList _paramList; + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new CacheItemArgs Object. /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public CacheItemArgs(string key) : this(key, 20, CacheItemPriority.Default, null) { - } - - ///----------------------------------------------------------------------------- - /// - /// Constructs a new CacheItemArgs Object + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new CacheItemArgs Object. /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public CacheItemArgs(string key, int timeout) : this(key, timeout, CacheItemPriority.Default, null) { - } - - ///----------------------------------------------------------------------------- - /// - /// Constructs a new CacheItemArgs Object + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new CacheItemArgs Object. /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public CacheItemArgs(string key, CacheItemPriority priority) : this(key, 20, priority, null) { - } - - ///----------------------------------------------------------------------------- - /// - /// Constructs a new CacheItemArgs Object + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new CacheItemArgs Object. /// /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public CacheItemArgs(string key, int timeout, CacheItemPriority priority) : this(key, timeout, priority, null) { - } - - ///----------------------------------------------------------------------------- - /// - /// Constructs a new CacheItemArgs Object + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new CacheItemArgs Object. /// /// /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public CacheItemArgs(string key, int timeout, CacheItemPriority priority, params object[] parameters) { - CacheKey = key; - CacheTimeOut = timeout; - CachePriority = priority; - Params = parameters; + this.CacheKey = key; + this.CacheTimeOut = timeout; + this.CachePriority = priority; + this.Params = parameters; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Cache Item's CacheItemRemovedCallback delegate + /// Gets or sets and sets the Cache Item's CacheItemRemovedCallback delegate. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public CacheItemRemovedCallback CacheCallback { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Cache Item's CacheDependency + /// Gets or sets and sets the Cache Item's CacheDependency. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public DNNCacheDependency CacheDependency { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets the Cache Item's Key + /// Gets or sets the Cache Item's Key. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public string CacheKey { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets the Cache Item's priority (defaults to Default) + /// Gets or sets the Cache Item's priority (defaults to Default). /// /// Note: DotNetNuke currently doesn't support the ASP.NET Cache's /// ItemPriority, but this is included for possible future use. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public CacheItemPriority CachePriority { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets the Cache Item's Timeout + /// Gets or sets the Cache Item's Timeout. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public int CacheTimeOut { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets the Cache Item's Parameter List + /// Gets the Cache Item's Parameter List. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ArrayList ParamList { get { - if (_paramList == null) + if (this._paramList == null) { - _paramList = new ArrayList(); - //add additional params to this list if its not null - if (Params != null) - { - foreach (object param in Params) - { - _paramList.Add(param); - } - } + this._paramList = new ArrayList(); + + // add additional params to this list if its not null + if (this.Params != null) + { + foreach (object param in this.Params) + { + this._paramList.Add(param); + } + } } - return _paramList; + return this._paramList; } } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets the Cache Item's Parameter Array + /// Gets the Cache Item's Parameter Array. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public object[] Params { get; private set; } public string ProcedureName { get; set; } diff --git a/DNN Platform/Library/Common/Utilities/CacheItemExpiredCallback.cs b/DNN Platform/Library/Common/Utilities/CacheItemExpiredCallback.cs index 46c68d1b2f8..8ca6061e99f 100644 --- a/DNN Platform/Library/Common/Utilities/CacheItemExpiredCallback.cs +++ b/DNN Platform/Library/Common/Utilities/CacheItemExpiredCallback.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { /// ----------------------------------------------------------------------------- @@ -11,8 +11,9 @@ namespace DotNetNuke.Common.Utilities /// ----------------------------------------------------------------------------- /// /// The CacheItemExpiredCallback delegate defines a callback method that notifies - /// the application when a CacheItem is Expired (when an attempt is made to get the item) - /// + /// the application when a CacheItem is Expired (when an attempt is made to get the item). + /// + /// /// ----------------------------------------------------------------------------- public delegate object CacheItemExpiredCallback(CacheItemArgs dataArgs); } diff --git a/DNN Platform/Library/Common/Utilities/Calendar.cs b/DNN Platform/Library/Common/Utilities/Calendar.cs index d322e4b74f2..21a1078c628 100644 --- a/DNN Platform/Library/Common/Utilities/Calendar.cs +++ b/DNN Platform/Library/Common/Utilities/Calendar.cs @@ -1,64 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Globalization; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System.Globalization; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + public class Calendar { /// ----------------------------------------------------------------------------- /// - /// Opens a popup Calendar + /// Opens a popup Calendar. /// - /// TextBox to return the date value + /// TextBox to return the date value. /// /// /// /// ----------------------------------------------------------------------------- public static string InvokePopupCal(TextBox Field) { - //Define character array to trim from language strings - char[] TrimChars = {',', ' '}; - //Get culture array of month names and convert to string for - //passing to the popup calendar + // Define character array to trim from language strings + char[] TrimChars = { ',', ' ' }; + + // Get culture array of month names and convert to string for + // passing to the popup calendar var monthBuilder = new StringBuilder(); foreach (string Month in DateTimeFormatInfo.CurrentInfo.MonthNames) { monthBuilder.AppendFormat("{0},", Month); } + var MonthNameString = monthBuilder.ToString().TrimEnd(TrimChars); - //Get culture array of day names and convert to string for - //passing to the popup calendar + + // Get culture array of day names and convert to string for + // passing to the popup calendar var dayBuilder = new StringBuilder(); foreach (string Day in DateTimeFormatInfo.CurrentInfo.AbbreviatedDayNames) { dayBuilder.AppendFormat("{0},", Day); } + var DayNameString = dayBuilder.ToString().TrimEnd(TrimChars); - //Get the short date pattern for the culture + + // Get the short date pattern for the culture string FormatString = DateTimeFormatInfo.CurrentInfo.ShortDatePattern; if (!Field.Page.ClientScript.IsClientScriptIncludeRegistered("PopupCalendar.js")) { ScriptManager.RegisterClientScriptInclude(Field.Page, Field.Page.GetType(), "PopupCalendar.js", ClientAPI.ScriptPath + "PopupCalendar.js"); } + string strToday = ClientAPI.GetSafeJSString(Localization.GetString("Today")); string strClose = ClientAPI.GetSafeJSString(Localization.GetString("Close")); string strCalendar = ClientAPI.GetSafeJSString(Localization.GetString("Calendar")); return string.Concat("javascript:popupCal('Cal','", Field.ClientID, "','", FormatString, "','", MonthNameString, "','", DayNameString, "','", strToday, "','", strClose, "','", strCalendar, "',", - (int) DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek, ");"); + (int)DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek, ");"); } } } diff --git a/DNN Platform/Library/Common/Utilities/Config.cs b/DNN Platform/Library/Common/Utilities/Config.cs index 34e4c68992e..26235644079 100644 --- a/DNN Platform/Library/Common/Utilities/Config.cs +++ b/DNN Platform/Library/Common/Utilities/Config.cs @@ -1,105 +1,97 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; -using System.IO; -using System.Threading; -using System.Web.Configuration; -using System.Xml; -using System.Xml.XPath; -using DotNetNuke.Common.Utilities.Internal; -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Globalization; + using System.IO; + using System.Threading; + using System.Web.Configuration; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities.Internal; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + /// ----------------------------------------------------------------------------- /// - /// The Config class provides access to the web.config file + /// The Config class provides access to the web.config file. /// /// /// /// ----------------------------------------------------------------------------- public class Config { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Config)); - #region ConfigFileType enum - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Config)); + public enum ConfigFileType { DotNetNuke, - //compatible with glbDotNetNukeConfig + + // compatible with glbDotNetNukeConfig SiteAnalytics, Compression, SiteUrls, - SolutionsExplorer - } - - #endregion - - #region FcnMode enum - + SolutionsExplorer, + } + public enum FcnMode { Default, Disabled, - NotSet, - Single - } - - #endregion - - /// + NotSet, + Single, + } + + /// /// Adds a new AppSetting to Web.Config. The update parameter allows you to define if, - /// when the key already exists, this need to be updated or not + /// when the key already exists, this need to be updated or not. /// - /// xml representation of the web.config file - /// key to be created - /// value to be created - /// If setting already exists, it will be updated if this parameter true + /// xml representation of the web.config file. + /// key to be created. + /// value to be created. + /// If setting already exists, it will be updated if this parameter true. /// public static XmlDocument AddAppSetting(XmlDocument xmlDoc, string key, string value, bool update) { - //retrieve the appSettings node + // retrieve the appSettings node XmlNode xmlAppSettings = xmlDoc.SelectSingleNode("//appSettings"); if (xmlAppSettings != null) { XmlElement xmlElement; - //get the node based on key - XmlNode xmlNode = xmlAppSettings.SelectSingleNode(("//add[@key='" + key + "']")); + + // get the node based on key + XmlNode xmlNode = xmlAppSettings.SelectSingleNode("//add[@key='" + key + "']"); if (update && xmlNode != null) { - //update the existing element + // update the existing element xmlElement = (XmlElement)xmlNode; xmlElement.SetAttribute("value", value); } else { - //create a new element + // create a new element xmlElement = xmlDoc.CreateElement("add"); xmlElement.SetAttribute("key", key); xmlElement.SetAttribute("value", value); xmlAppSettings.AppendChild(xmlElement); } } - //return the xml doc + + // return the xml doc return xmlDoc; } /// - /// Adds a new AppSetting to Web.Config. If the key already exists, it will be updated with the new value + /// Adds a new AppSetting to Web.Config. If the key already exists, it will be updated with the new value. /// - /// xml representation of the web.config file - /// key to be created - /// value to be created + /// xml representation of the web.config file. + /// key to be created. + /// value to be created. /// public static XmlDocument AddAppSetting(XmlDocument xmlDoc, string key, string value) { @@ -112,16 +104,17 @@ public static void AddCodeSubDirectory(string name) XmlNode xmlCompilation = xmlConfig.SelectSingleNode("configuration/system.web/compilation"); if (xmlCompilation == null) { - //Try location node + // Try location node xmlCompilation = xmlConfig.SelectSingleNode("configuration/location/system.web/compilation"); } - //Get the CodeSubDirectories Node + + // Get the CodeSubDirectories Node if (xmlCompilation != null) { XmlNode xmlSubDirectories = xmlCompilation.SelectSingleNode("codeSubDirectories"); if (xmlSubDirectories == null) { - //Add Node + // Add Node xmlSubDirectories = xmlConfig.CreateElement("codeSubDirectories"); xmlCompilation.AppendChild(xmlSubDirectories); } @@ -133,29 +126,32 @@ public static void AddCodeSubDirectory(string name) codeSubDirectoryName = name.Substring(0, length); } - //Check if the node is already present + // Check if the node is already present XmlNode xmlSubDirectory = xmlSubDirectories.SelectSingleNode("add[@directoryName='" + codeSubDirectoryName + "']"); if (xmlSubDirectory == null) { - //Add Node + // Add Node xmlSubDirectory = xmlConfig.CreateElement("add"); XmlUtils.CreateAttribute(xmlConfig, xmlSubDirectory, "directoryName", codeSubDirectoryName); xmlSubDirectories.AppendChild(xmlSubDirectory); } } + Save(xmlConfig); } public static void BackupConfig() { string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); - //save the current config files + + // save the current config files try { if (!Directory.Exists(Globals.ApplicationMapPath + backupFolder)) { Directory.CreateDirectory(Globals.ApplicationMapPath + backupFolder); } + if (File.Exists(Globals.ApplicationMapPath + "\\web.config")) { File.Copy(Globals.ApplicationMapPath + "\\web.config", Globals.ApplicationMapPath + backupFolder + "web_old.config", true); @@ -171,7 +167,7 @@ public static void BackupConfig() /// /// Gets the default connection String as specified in the provider. /// - /// The connection String + /// The connection String. /// /// ----------------------------------------------------------------------------- public static string GetConnectionString() @@ -181,39 +177,42 @@ public static string GetConnectionString() /// ----------------------------------------------------------------------------- /// - /// Gets the specified connection String + /// Gets the specified connection String. /// - /// Name of Connection String to return - /// The connection String + /// Name of Connection String to return. + /// The connection String. /// /// ----------------------------------------------------------------------------- public static string GetConnectionString(string name) { - string connectionString = ""; - //First check if connection string is specified in (ASP.NET 2.0 / DNN v4.x) - if (!String.IsNullOrEmpty(name)) + string connectionString = string.Empty; + + // First check if connection string is specified in (ASP.NET 2.0 / DNN v4.x) + if (!string.IsNullOrEmpty(name)) { - //ASP.NET 2 version connection string (in ) - //This will be for new v4.x installs or upgrades from v4.x + // ASP.NET 2 version connection string (in ) + // This will be for new v4.x installs or upgrades from v4.x connectionString = WebConfigurationManager.ConnectionStrings[name].ConnectionString; } - if (String.IsNullOrEmpty(connectionString)) + + if (string.IsNullOrEmpty(connectionString)) { - if (!String.IsNullOrEmpty(name)) + if (!string.IsNullOrEmpty(name)) { - //Next check if connection string is specified in (ASP.NET 1.1 / DNN v3.x) - //This will accomodate upgrades from v3.x + // Next check if connection string is specified in (ASP.NET 1.1 / DNN v3.x) + // This will accomodate upgrades from v3.x connectionString = GetSetting(name); } } + return connectionString; } /// ----------------------------------------------------------------------------- /// - /// Returns the decryptionkey from webconfig machinekey + /// Returns the decryptionkey from webconfig machinekey. /// - /// decryption key + /// decryption key. /// ----------------------------------------------------------------------------- public static string GetDecryptionkey() { @@ -223,28 +222,28 @@ public static string GetDecryptionkey() /// ----------------------------------------------------------------------------- /// - /// Returns the fcnMode from webconfig httpRuntime + /// Returns the fcnMode from webconfig httpRuntime. /// - /// decryption key + /// decryption key. /// ----------------------------------------------------------------------------- public static string GetFcnMode() { var section = System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; var mode = section?.FcnMode; - return ((ValueType) mode ?? FcnMode.NotSet).ToString(); + return ((ValueType)mode ?? FcnMode.NotSet).ToString(); } /// ----------------------------------------------------------------------------- /// - /// Returns the maximum file size allowed to be uploaded to the application in bytes + /// Returns the maximum file size allowed to be uploaded to the application in bytes. /// - /// Size in bytes + /// Size in bytes. /// ----------------------------------------------------------------------------- public static long GetMaxUploadSize() { var configNav = Load(); - var httpNode = configNav.SelectSingleNode("configuration//system.web//httpRuntime") ?? + var httpNode = configNav.SelectSingleNode("configuration//system.web//httpRuntime") ?? configNav.SelectSingleNode("configuration//location//system.web//httpRuntime"); long maxRequestLength = 0; if (httpNode != null) @@ -272,14 +271,14 @@ public static long GetMaxUploadSize() /// ----------------------------------------------------------------------------- /// - /// Returns the maximum file size allowed to be uploaded based on the request filter limit + /// Returns the maximum file size allowed to be uploaded based on the request filter limit. /// - /// Size in megabytes + /// Size in megabytes. /// ----------------------------------------------------------------------------- public static long GetRequestFilterSize() { var configNav = Load(); - const int defaultRequestFilter = 30000000/1024/1024; + const int defaultRequestFilter = 30000000 / 1024 / 1024; var httpNode = configNav.SelectSingleNode("configuration//system.webServer//security//requestFiltering//requestLimits") ?? configNav.SelectSingleNode("configuration//location//system.webServer//security//requestFiltering//requestLimits"); if (httpNode == null && Iis7AndAbove()) @@ -292,17 +291,21 @@ public static long GetRequestFilterSize() var maxAllowedContentLength = XmlUtils.GetAttributeValueAsLong(httpNode.CreateNavigator(), "maxAllowedContentLength", 30000000); return maxAllowedContentLength / 1024 / 1024; } + return defaultRequestFilter; } /// ----------------------------------------------------------------------------- /// - /// Sets the maximum file size allowed to be uploaded to the application in bytes + /// Sets the maximum file size allowed to be uploaded to the application in bytes. /// /// ----------------------------------------------------------------------------- public static void SetMaxUploadSize(long newSize) { - if (newSize < 12582912) { newSize = 12582912; }; // 12 Mb minimum + if (newSize < 12582912) + { + newSize = 12582912; + } // 12 Mb minimum var configNav = Load(); @@ -324,16 +327,11 @@ public static void SetMaxUploadSize(long newSize) Save(configNav); } - private static bool Iis7AndAbove() - { - return Environment.OSVersion.Version.Major >= 6; - } - /// ----------------------------------------------------------------------------- /// - /// Gets the specified upgrade connection string + /// Gets the specified upgrade connection string. /// - /// The connection String + /// The connection String. /// /// ----------------------------------------------------------------------------- public static string GetUpgradeConnectionString() @@ -343,25 +341,32 @@ public static string GetUpgradeConnectionString() /// ----------------------------------------------------------------------------- /// - /// Gets the specified database owner + /// Gets the specified database owner. /// - /// The database owner + /// The database owner. /// /// ----------------------------------------------------------------------------- public static string GetDataBaseOwner() { string databaseOwner = GetDefaultProvider("data").Attributes["databaseOwner"]; - if (!String.IsNullOrEmpty(databaseOwner) && databaseOwner.EndsWith(".") == false) + if (!string.IsNullOrEmpty(databaseOwner) && databaseOwner.EndsWith(".") == false) { databaseOwner += "."; } + return databaseOwner; } + private static bool Iis7AndAbove() + { + return Environment.OSVersion.Version.Major >= 6; + } + public static Provider GetDefaultProvider(string type) { ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(type); - //Read the configuration specific information for this provider + + // Read the configuration specific information for this provider return (Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider]; } @@ -402,29 +407,32 @@ public static string GetFriendlyUrlProvider() /// ----------------------------------------------------------------------------- /// - /// Gets the specified object qualifier + /// Gets the specified object qualifier. /// - /// The object qualifier + /// The object qualifier. /// /// ----------------------------------------------------------------------------- public static string GetObjectQualifer() { Provider provider = GetDefaultProvider("data"); string objectQualifier = provider.Attributes["objectQualifier"]; - if (!String.IsNullOrEmpty(objectQualifier) && objectQualifier.EndsWith("_") == false) + if (!string.IsNullOrEmpty(objectQualifier) && objectQualifier.EndsWith("_") == false) { objectQualifier += "_"; } + return objectQualifier; } public static int GetAuthCookieTimeout() { XPathNavigator configNav = Load().CreateNavigator(); - //Select the location node + + // Select the location node XPathNavigator locationNav = configNav.SelectSingleNode("configuration/location"); XPathNavigator formsNav; - //Test for the existence of the location node if it exists then include that in the nodes of the XPath Query + + // Test for the existence of the location node if it exists then include that in the nodes of the XPath Query if (locationNav == null) { formsNav = configNav.SelectSingleNode("configuration/system.web/authentication/forms"); @@ -433,21 +441,21 @@ public static int GetAuthCookieTimeout() { formsNav = configNav.SelectSingleNode("configuration/location/system.web/authentication/forms"); } - return (formsNav != null) ? XmlUtils.GetAttributeValueAsInteger(formsNav, "timeout", 30) : 30; ; - + + return (formsNav != null) ? XmlUtils.GetAttributeValueAsInteger(formsNav, "timeout", 30) : 30; } /// - /// Get's optional persistent cookie timeout value from web.config + /// Get's optional persistent cookie timeout value from web.config. /// - /// persistent cookie value + /// persistent cookie value. /// - /// allows users to override default asp.net values + /// allows users to override default asp.net values. /// public static int GetPersistentCookieTimeout() { int persistentCookieTimeout = 0; - if (!String.IsNullOrEmpty(GetSetting("PersistentCookieTimeout"))) + if (!string.IsNullOrEmpty(GetSetting("PersistentCookieTimeout"))) { persistentCookieTimeout = int.Parse(GetSetting("PersistentCookieTimeout")); } @@ -458,15 +466,16 @@ public static int GetPersistentCookieTimeout() public static Provider GetProvider(string type, string name) { ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(type); - //Read the configuration specific information for this provider + + // Read the configuration specific information for this provider return (Provider)providerConfiguration.Providers[name]; } /// ----------------------------------------------------------------------------- /// - /// Gets the specified provider path + /// Gets the specified provider path. /// - /// The provider path + /// The provider path. /// /// ----------------------------------------------------------------------------- public static string GetProviderPath(string type) @@ -493,9 +502,9 @@ public static XmlDocument Load() public static string GetCustomErrorMode() { - XPathNavigator configNav = Load().CreateNavigator(); - //Select the location node + + // Select the location node var customErrorsNav = configNav.SelectSingleNode("//configuration/system.web/customErrors|//configuration/location/system.web/customErrors"); string customErrorMode = XmlUtils.GetAttributeValue(customErrorsNav, "mode"); @@ -503,40 +512,44 @@ public static string GetCustomErrorMode() { customErrorMode = "RemoteOnly"; } - return (customErrorsNav != null) ? customErrorMode : "RemoteOnly"; ; - + + return (customErrorsNav != null) ? customErrorMode : "RemoteOnly"; } public static XmlDocument Load(string filename) { - //open the config file + // open the config file var xmlDoc = new XmlDocument { XmlResolver = null }; xmlDoc.Load(Globals.ApplicationMapPath + "\\" + filename); - //test for namespace added by Web Admin Tool - if (!String.IsNullOrEmpty(xmlDoc.DocumentElement.GetAttribute("xmlns"))) + + // test for namespace added by Web Admin Tool + if (!string.IsNullOrEmpty(xmlDoc.DocumentElement.GetAttribute("xmlns"))) { - //remove namespace - string strDoc = xmlDoc.InnerXml.Replace("xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\"", ""); + // remove namespace + string strDoc = xmlDoc.InnerXml.Replace("xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\"", string.Empty); xmlDoc.LoadXml(strDoc); } + return xmlDoc; } public static void RemoveCodeSubDirectory(string name) { XmlDocument xmlConfig = Load(); - //Select the location node + + // Select the location node XmlNode xmlCompilation = xmlConfig.SelectSingleNode("configuration/system.web/compilation"); if (xmlCompilation == null) { - //Try location node + // Try location node xmlCompilation = xmlConfig.SelectSingleNode("configuration/location/system.web/compilation"); } - //Get the CodeSubDirectories Node + + // Get the CodeSubDirectories Node XmlNode xmlSubDirectories = xmlCompilation.SelectSingleNode("codeSubDirectories"); if (xmlSubDirectories == null) { - //Parent doesn't exist so subDirectory node can't exist + // Parent doesn't exist so subDirectory node can't exist return; } @@ -547,11 +560,11 @@ public static void RemoveCodeSubDirectory(string name) codeSubDirectoryName = name.Substring(0, length); } - //Check if the node is present + // Check if the node is present XmlNode xmlSubDirectory = xmlSubDirectories.SelectSingleNode("add[@directoryName='" + codeSubDirectoryName + "']"); if (xmlSubDirectory != null) { - //Remove Node + // Remove Node xmlSubDirectories.RemoveChild(xmlSubDirectory); Save(xmlConfig); @@ -572,9 +585,10 @@ public static string Save(XmlDocument xmlDoc, string filename) var objFileAttributes = FileAttributes.Normal; if (File.Exists(strFilePath)) { - //save current file attributes + // save current file attributes objFileAttributes = File.GetAttributes(strFilePath); - //change to normal ( in case it is flagged as read-only ) + + // change to normal ( in case it is flagged as read-only ) File.SetAttributes(strFilePath, FileAttributes.Normal); } @@ -586,7 +600,7 @@ public static string Save(XmlDocument xmlDoc, string filename) { try { - //save the config file + // save the config file var settings = new XmlWriterSettings { CloseOutput = true, Indent = true }; using (var writer = XmlWriter.Create(strFilePath, settings)) { @@ -594,6 +608,7 @@ public static string Save(XmlDocument xmlDoc, string filename) writer.Flush(); writer.Close(); } + break; } catch (IOException exc) @@ -605,11 +620,11 @@ public static string Save(XmlDocument xmlDoc, string filename) } // try incremental delay; maybe the file lock is released by then - Thread.Sleep(((int)(miltiplier * (maxRetires - retry + 1)) * 1000)); + Thread.Sleep((int)(miltiplier * (maxRetires - retry + 1)) * 1000); } } - //reset file attributes + // reset file attributes File.SetAttributes(strFilePath, objFileAttributes); } catch (Exception exc) @@ -642,15 +657,15 @@ public static void UpdateConnectionString(string conn) XmlDocument xmlConfig = Load(); string name = GetDefaultProvider("data").Attributes["connectionStringName"]; - //Update ConnectionStrings + // Update ConnectionStrings XmlNode xmlConnection = xmlConfig.SelectSingleNode("configuration/connectionStrings/add[@name='" + name + "']"); XmlUtils.UpdateAttribute(xmlConnection, "connectionString", conn); - //Update AppSetting + // Update AppSetting XmlNode xmlAppSetting = xmlConfig.SelectSingleNode("configuration/appSettings/add[@key='" + name + "']"); XmlUtils.UpdateAttribute(xmlAppSetting, "value", conn); - //Save changes + // Save changes Save(xmlConfig); } @@ -658,18 +673,18 @@ public static void UpdateDataProvider(string name, string databaseOwner, string { XmlDocument xmlConfig = Load(); - //Update provider + // Update provider XmlNode xmlProvider = xmlConfig.SelectSingleNode("configuration/dotnetnuke/data/providers/add[@name='" + name + "']"); XmlUtils.UpdateAttribute(xmlProvider, "databaseOwner", databaseOwner); XmlUtils.UpdateAttribute(xmlProvider, "objectQualifier", objectQualifier); - //Save changes + // Save changes Save(xmlConfig); } /// ----------------------------------------------------------------------------- /// - /// Updates the specified upgrade connection string + /// Updates the specified upgrade connection string. /// /// /// ----------------------------------------------------------------------------- @@ -677,30 +692,29 @@ public static void UpdateUpgradeConnectionString(string name, string upgradeConn { XmlDocument xmlConfig = Load(); - //Update provider + // Update provider XmlNode xmlProvider = xmlConfig.SelectSingleNode("configuration/dotnetnuke/data/providers/add[@name='" + name + "']"); XmlUtils.UpdateAttribute(xmlProvider, "upgradeConnectionString", upgradeConnectionString); - //Save changes + // Save changes Save(xmlConfig); } public static string UpdateMachineKey() { - string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); + string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); var xmlConfig = new XmlDocument { XmlResolver = null }; - string strError = ""; + string strError = string.Empty; - //save the current config files + // save the current config files BackupConfig(); try { - //open the web.config + // open the web.config xmlConfig = Load(); - //create random keys for the Membership machine keys + // create random keys for the Membership machine keys xmlConfig = UpdateMachineKey(xmlConfig); - } catch (Exception ex) { @@ -708,10 +722,10 @@ public static string UpdateMachineKey() strError += ex.Message; } - //save a copy of the web.config + // save a copy of the web.config strError += Save(xmlConfig, backupFolder + "web_.config"); - //save the web.config + // save the web.config strError += Save(xmlConfig); return strError; @@ -734,18 +748,18 @@ public static XmlDocument UpdateMachineKey(XmlDocument xmlConfig) public static string UpdateValidationKey() { - string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); + string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); var xmlConfig = new XmlDocument { XmlResolver = null }; - string strError = ""; + string strError = string.Empty; - //save the current config files + // save the current config files BackupConfig(); try { - //open the web.config + // open the web.config xmlConfig = Load(); - //create random keys for the Membership machine keys + // create random keys for the Membership machine keys xmlConfig = UpdateValidationKey(xmlConfig); } catch (Exception ex) @@ -754,10 +768,10 @@ public static string UpdateValidationKey() strError += ex.Message; } - //save a copy of the web.config + // save a copy of the web.config strError += Save(xmlConfig, backupFolder + "web_.config"); - //save the web.config + // save the web.config strError += Save(xmlConfig); return strError; } @@ -771,16 +785,17 @@ public static XmlDocument UpdateValidationKey(XmlDocument xmlConfig) string validationKey = objSecurity.CreateKey(20); XmlUtils.UpdateAttribute(xmlMachineKey, "validationKey", validationKey); } + return xmlConfig; } /// - /// Gets the path for the specificed Config file + /// Gets the path for the specificed Config file. /// - /// The config.file to get the path for - /// fully qualified path to the file + /// The config.file to get the path for. + /// fully qualified path to the file. /// - /// Will copy the file from the template directory as requried + /// Will copy the file from the template directory as requried. /// public static string GetPathToFile(ConfigFileType file) { @@ -788,13 +803,13 @@ public static string GetPathToFile(ConfigFileType file) } /// - /// Gets the path for the specificed Config file + /// Gets the path for the specificed Config file. /// - /// The config.file to get the path for - /// force an overwrite of the config file - /// fully qualified path to the file + /// The config.file to get the path for. + /// force an overwrite of the config file. + /// fully qualified path to the file. /// - /// Will copy the file from the template directory as requried + /// Will copy the file from the template directory as requried. /// public static string GetPathToFile(ConfigFileType file, bool overwrite) { @@ -803,9 +818,9 @@ public static string GetPathToFile(ConfigFileType file, bool overwrite) if (!File.Exists(path) || overwrite) { - //Copy from \Config + // Copy from \Config string pathToDefault = Path.Combine(Globals.ApplicationMapPath + Globals.glbConfigFolder, fileName); - if ((File.Exists(pathToDefault))) + if (File.Exists(pathToDefault)) { File.Copy(pathToDefault, path, true); } @@ -814,42 +829,30 @@ public static string GetPathToFile(ConfigFileType file, bool overwrite) return path; } - private static string EnumToFileName(ConfigFileType file) - { - switch (file) - { - case ConfigFileType.SolutionsExplorer: - return "SolutionsExplorer.opml.config"; - default: - return file + ".config"; - } - } - /// - /// UpdateInstallVersion, but only if the setting does not already exist + /// UpdateInstallVersion, but only if the setting does not already exist. /// /// public static string UpdateInstallVersion(Version version) { - string strError = ""; + string strError = string.Empty; var installVersion = GetSetting("InstallVersion"); if (string.IsNullOrEmpty(installVersion)) { // we need to add the InstallVersion - - string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); + string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); var xmlConfig = new XmlDocument { XmlResolver = null }; - //save the current config files + + // save the current config files BackupConfig(); try { - //open the web.config + // open the web.config xmlConfig = Load(); - //Update the InstallVersion + // Update the InstallVersion xmlConfig = UpdateInstallVersion(xmlConfig, version); - } catch (Exception ex) { @@ -857,25 +860,16 @@ public static string UpdateInstallVersion(Version version) strError += ex.Message; } - //save a copy of the web.config + // save a copy of the web.config strError += Save(xmlConfig, backupFolder + "web_.config"); - //save the web.config + // save the web.config strError += Save(xmlConfig); - } return strError; } - private static XmlDocument UpdateInstallVersion(XmlDocument xmlConfig, Version version) - { - // only update appsetting if necessary - xmlConfig = AddAppSetting(xmlConfig, "InstallVersion", Globals.FormatVersion(version), false); - - return xmlConfig; - } - public static bool IsNet45OrNewer() { // Class "ReflectionContext" exists from .NET 4.5 onwards. @@ -886,27 +880,46 @@ public static string AddFCNMode(FcnMode fcnMode) { try { - - //check current .net version and if attribute has been added already - if ((IsNet45OrNewer()) && GetFcnMode() != fcnMode.ToString()) + // check current .net version and if attribute has been added already + if (IsNet45OrNewer() && GetFcnMode() != fcnMode.ToString()) { - //open the web.config + // open the web.config var xmlConfig = Load(); var xmlhttpRunTimeKey = xmlConfig.SelectSingleNode("configuration/system.web/httpRuntime") ?? xmlConfig.SelectSingleNode("configuration/location/system.web/httpRuntime"); XmlUtils.CreateAttribute(xmlConfig, xmlhttpRunTimeKey, "fcnMode", fcnMode.ToString()); - //save the web.config + // save the web.config Save(xmlConfig); } } catch (Exception ex) { - //in case of error installation shouldn't be stopped, log into log4net + // in case of error installation shouldn't be stopped, log into log4net Logger.Error(ex); } - return ""; + + return string.Empty; + } + + private static string EnumToFileName(ConfigFileType file) + { + switch (file) + { + case ConfigFileType.SolutionsExplorer: + return "SolutionsExplorer.opml.config"; + default: + return file + ".config"; + } + } + + private static XmlDocument UpdateInstallVersion(XmlDocument xmlConfig, Version version) + { + // only update appsetting if necessary + xmlConfig = AddAppSetting(xmlConfig, "InstallVersion", Globals.FormatVersion(version), false); + + return xmlConfig; } } } diff --git a/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs b/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs index e89a0f1a8cf..db817ba14ea 100644 --- a/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs +++ b/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Security.Cryptography; -// ReSharper disable InconsistentNaming - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable InconsistentNaming namespace DotNetNuke.Common.Utilities { + using System.Security.Cryptography; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Common.Utilities /// Project: DotNetNuke /// Class: CryptographyUtils /// ----------------------------------------------------------------------------- /// - /// CryptographyUtils is a Utility class that provides Cryptography Utility constants + /// CryptographyUtils is a Utility class that provides Cryptography Utility constants. /// /// /// @@ -39,7 +34,7 @@ public static class CryptographyUtils private const string _SHA512Cng = "System.Security.Cryptography.SHA512Cng"; private const string _SHA512CryptoServiceProvider = "System.Security.Cryptography.SHA512CryptoServiceProvider"; - + public static SHA1 CreateSHA1() { return SHA1.Create(CryptoConfig.AllowOnlyFipsAlgorithms ? _SHA1CryptoServiceProvider : _SHA1Cng); diff --git a/DNN Platform/Library/Common/Utilities/DataCache.cs b/DNN Platform/Library/Common/Utilities/DataCache.cs index ecd3fb61455..c0ce514ecd0 100644 --- a/DNN Platform/Library/Common/Utilities/DataCache.cs +++ b/DNN Platform/Library/Common/Utilities/DataCache.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading; -using System.Web.Caching; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.OutputCache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Web.Caching; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.OutputCache; + public enum CoreCacheType { Host = 1, Portal = 2, - Tab = 3 + Tab = 3, } /// ----------------------------------------------------------------------------- @@ -38,20 +33,21 @@ public enum CoreCacheType /// Class: DataCache /// ----------------------------------------------------------------------------- /// - /// The DataCache class is a facade class for the CachingProvider Instance's + /// The DataCache class is a facade class for the CachingProvider Instance's. /// /// ----------------------------------------------------------------------------- public class DataCache { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DataCache)); - //Host keys + // Host keys public const string SecureHostSettingsCacheKey = "SecureHostSettings"; public const string UnSecureHostSettingsCacheKey = "UnsecureHostSettings"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataCache)); public const string HostSettingsCacheKey = "HostSettings"; public const CacheItemPriority HostSettingsCachePriority = CacheItemPriority.NotRemovable; public const int HostSettingsCacheTimeOut = 20; - //Portal keys + // Portal keys public const string PortalAliasCacheKey = "PortalAlias"; public const CacheItemPriority PortalAliasCachePriority = CacheItemPriority.NotRemovable; public const int PortalAliasCacheTimeOut = 200; @@ -68,9 +64,9 @@ public class DataCache public const CacheItemPriority PortalCachePriority = CacheItemPriority.High; public const int PortalCacheTimeOut = 20; - public const string AllPortalsCacheKey = "AllPortals"; - public const CacheItemPriority AllPortalsCachePriority = CacheItemPriority.High; - public const int AllPortalsCacheTimeOut = 20; + public const string AllPortalsCacheKey = "AllPortals"; + public const CacheItemPriority AllPortalsCachePriority = CacheItemPriority.High; + public const int AllPortalsCacheTimeOut = 20; public const string PortalUserCountCacheKey = "PortalUserCount{0}"; public const CacheItemPriority PortalUserCountCachePriority = CacheItemPriority.High; @@ -80,7 +76,7 @@ public class DataCache public const CacheItemPriority PortalGroupsCachePriority = CacheItemPriority.High; public const int PortalGroupsCacheTimeOut = 20; - //Tab cache keys + // Tab cache keys public const string TabCacheKey = "Tab_Tabs{0}"; public const string TabSettingsCacheKey = "TabSettings{0}"; public const CacheItemPriority TabCachePriority = CacheItemPriority.High; @@ -106,7 +102,7 @@ public class DataCache public const string TabVersionDetailsCacheKey = "Tab_TabVersionDetails{0}"; public const CacheItemPriority TabVersionDetailsCachePriority = CacheItemPriority.High; public const int TabVersionDetailsCacheTimeOut = 20; - + public const string AuthenticationServicesCacheKey = "AuthenticationServices"; public const CacheItemPriority AuthenticationServicesCachePriority = CacheItemPriority.NotRemovable; public const int AuthenticationServicesCacheTimeOut = 20; @@ -234,13 +230,13 @@ public class DataCache public const CacheItemPriority BannersCachePriority = CacheItemPriority.Normal; public const int BannersCacheTimeOut = 20; - public const string RedirectionsCacheKey = "Redirections:{0}"; - public const CacheItemPriority RedirectionsCachePriority = CacheItemPriority.Default; - public const int RedirectionsCacheTimeOut = 20; + public const string RedirectionsCacheKey = "Redirections:{0}"; + public const CacheItemPriority RedirectionsCachePriority = CacheItemPriority.Default; + public const int RedirectionsCacheTimeOut = 20; - public const string PreviewProfilesCacheKey = "PreviewProfiles:{0}"; - public const CacheItemPriority PreviewProfilesCachePriority = CacheItemPriority.Default; - public const int PreviewProfilesCacheTimeOut = 20; + public const string PreviewProfilesCacheKey = "PreviewProfiles:{0}"; + public const CacheItemPriority PreviewProfilesCachePriority = CacheItemPriority.Default; + public const int PreviewProfilesCacheTimeOut = 20; public const string RelationshipTypesCacheKey = "RelationshipTypes"; public const CacheItemPriority RelationshipTypesCachePriority = CacheItemPriority.Default; @@ -275,10 +271,10 @@ public class DataCache public const CacheItemPriority SubscriptionTypesCachePriority = CacheItemPriority.Default; public const int SubscriptionTypesTimeOut = 20; - public const string PackagesCacheKey = "Packages_{0}"; + public const string PackagesCacheKey = "Packages_{0}"; public const string PackageDependenciesCacheKey = "Packages_Dependencies"; public const CacheItemPriority PackagesCachePriority = CacheItemPriority.Default; - public const int PackagesCacheTimeout = 20; + public const int PackagesCacheTimeout = 20; public const string ContentTypesCacheKey = "ContentTypes"; public const CacheItemPriority ContentTypesCachePriority = CacheItemPriority.AboveNormal; @@ -292,9 +288,9 @@ public class DataCache public const CacheItemPriority PackageTypesCachePriority = CacheItemPriority.AboveNormal; public const int PackageTypesCacheTimeout = 20; - public const string JavaScriptLibrariesCacheKey = "JavaScriptLibraries"; - public const CacheItemPriority JavaScriptLibrariesCachePriority = CacheItemPriority.AboveNormal; - public const int JavaScriptLibrariesCacheTimeout = 20; + public const string JavaScriptLibrariesCacheKey = "JavaScriptLibraries"; + public const CacheItemPriority JavaScriptLibrariesCachePriority = CacheItemPriority.AboveNormal; + public const int JavaScriptLibrariesCacheTimeout = 20; public const string CaptchaCacheKey = "Captcha_{0}"; public const CacheItemPriority CaptchaCachePriority = CacheItemPriority.NotRemovable; @@ -305,10 +301,10 @@ public class DataCache public const CacheItemPriority WorkflowsCachePriority = CacheItemPriority.Low; public const int WorkflowsCacheTimeout = 2; - private static string _CachePersistenceEnabled = ""; - public const string ScopeTypesCacheKey = "ScopeTypes"; public const string VocabularyCacheKey = "Vocabularies"; + + private static string _CachePersistenceEnabled = string.Empty; public const string TermCacheKey = "Terms_{0}"; internal const string UserIdListToClearDiskImageCacheKey = "UserIdListToClearDiskImage_{0}"; @@ -318,31 +314,43 @@ public class DataCache private static readonly SharedDictionary dictionaryCache = new SharedDictionary(); + private static readonly TimeSpan _5seconds = new TimeSpan(0, 0, 5); + public static bool CachePersistenceEnabled { get { - if (String.IsNullOrEmpty(_CachePersistenceEnabled)) + if (string.IsNullOrEmpty(_CachePersistenceEnabled)) { _CachePersistenceEnabled = Config.GetSetting("EnableCachePersistence") ?? "false"; } - return Boolean.Parse(_CachePersistenceEnabled); + + return bool.Parse(_CachePersistenceEnabled); } } - private static string GetDnnCacheKey(string CacheKey) + public static void ClearCache() { - return CachingProvider.GetCacheKey(CacheKey); + CachingProvider.Instance().Clear("Prefix", "DNN_"); + using (dictionaryCache.GetWriteLock()) + { + dictionaryCache.Clear(); + } + + // log the cache clear event + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.CACHE_REFRESH.ToString() }; + log.LogProperties.Add(new LogDetailInfo("*", "Refresh")); + LogController.Instance.AddLog(log); } - private static string CleanCacheKey(string cacheKey) + public static void ClearCache(string cachePrefix) { - return CachingProvider.CleanCacheKey(cacheKey); + CachingProvider.Instance().Clear("Prefix", GetDnnCacheKey(cachePrefix)); } internal static void ItemRemovedCallback(string key, object value, CacheItemRemovedReason removedReason) { - //if the item was removed from the cache, log the key and reason to the event log + // if the item was removed from the cache, log the key and reason to the event log try { if (Globals.Status == Globals.UpgradeStatus.None) @@ -363,34 +371,26 @@ internal static void ItemRemovedCallback(string key, object value, CacheItemRemo log.LogTypeKey = EventLogController.EventLogType.CACHE_DEPENDENCYCHANGED.ToString(); break; } + log.LogProperties.Add(new LogDetailInfo(key, removedReason.ToString())); LogController.Instance.AddLog(log); } } catch (Exception exc) { - //Swallow exception + // Swallow exception Logger.Error(exc); } } - public static void ClearCache() + private static string GetDnnCacheKey(string CacheKey) { - CachingProvider.Instance().Clear("Prefix", "DNN_"); - using (dictionaryCache.GetWriteLock()) - { - dictionaryCache.Clear(); - } - - //log the cache clear event - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.CACHE_REFRESH.ToString()}; - log.LogProperties.Add(new LogDetailInfo("*", "Refresh")); - LogController.Instance.AddLog(log); + return CachingProvider.GetCacheKey(CacheKey); } - public static void ClearCache(string cachePrefix) + private static string CleanCacheKey(string cacheKey) { - CachingProvider.Instance().Clear("Prefix", GetDnnCacheKey(cachePrefix)); + return CachingProvider.CleanCacheKey(cacheKey); } public static void ClearFolderCache(int PortalId) @@ -406,7 +406,7 @@ public static void ClearHostCache(bool Cascade) } else { - CachingProvider.Instance().Clear("Host", ""); + CachingProvider.Instance().Clear("Host", string.Empty); } } @@ -427,8 +427,8 @@ public static void ClearModuleCache(int TabId) } var portalId = portals[TabId]; - RemoveCache(String.Format(SharedModulesByPortalCacheKey, portalId)); - RemoveCache(String.Format(SharedModulesWithPortalCacheKey, portalId)); + RemoveCache(string.Format(SharedModulesByPortalCacheKey, portalId)); + RemoveCache(string.Format(SharedModulesWithPortalCacheKey, portalId)); } } @@ -449,7 +449,7 @@ public static void ClearTabsCache(int PortalId) public static void ClearDefinitionsCache(int PortalId) { - RemoveCache(String.Format(ProfileDefinitionsCacheKey, PortalId)); + RemoveCache(string.Format(ProfileDefinitionsCacheKey, PortalId)); } public static void ClearDesktopModulePermissionsCache() @@ -459,29 +459,30 @@ public static void ClearDesktopModulePermissionsCache() public static void ClearFolderPermissionsCache(int PortalId) { - PermissionProvider.ResetCacheDependency(PortalId, - () => RemoveCache(String.Format(FolderPermissionCacheKey, PortalId))); + PermissionProvider.ResetCacheDependency( + PortalId, + () => RemoveCache(string.Format(FolderPermissionCacheKey, PortalId))); } public static void ClearListsCache(int PortalId) { - RemoveCache(String.Format(ListsCacheKey, PortalId)); + RemoveCache(string.Format(ListsCacheKey, PortalId)); } public static void ClearModulePermissionsCache(int TabId) { - RemoveCache(String.Format(ModulePermissionCacheKey, TabId)); + RemoveCache(string.Format(ModulePermissionCacheKey, TabId)); } public static void ClearTabPermissionsCache(int PortalId) { - RemoveCache(String.Format(TabPermissionCacheKey, PortalId)); + RemoveCache(string.Format(TabPermissionCacheKey, PortalId)); } public static void ClearUserCache(int PortalId, string username) { - RemoveCache(String.Format(UserCacheKey, PortalId, username)); - RemoveCache(String.Format(UserProfileCacheKey, PortalId, username)); + RemoveCache(string.Format(UserCacheKey, PortalId, username)); + RemoveCache(string.Format(UserProfileCacheKey, PortalId, username)); } public static void ClearPortalUserCountCache(int portalID) @@ -491,13 +492,50 @@ public static void ClearPortalUserCountCache(int portalID) public static void ClearUserPersonalizationCache(int portalId, int userId) { - RemoveCache(String.Format(UserPersonalizationCacheKey, portalId, userId)); + RemoveCache(string.Format(UserPersonalizationCacheKey, portalId, userId)); } - public static void ClearPackagesCache(int portalId) - { - RemoveCache(String.Format(PackagesCacheKey, portalId)); - } + public static void ClearPackagesCache(int portalId) + { + RemoveCache(string.Format(PackagesCacheKey, portalId)); + } + + public static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) + { + // declare local object and try and retrieve item from the cache + return GetCachedData(cacheItemArgs, cacheItemExpired, false); + } + + public static TObject GetCache(string CacheKey) + { + object objObject = GetCache(CacheKey); + if (objObject == null) + { + return default(TObject); + } + + return (TObject)objObject; + } + + public static object GetCache(string CacheKey) + { + return CachingProvider.Instance().GetItem(GetDnnCacheKey(CacheKey)); + } + + internal static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool storeInDictionary) + { + object objObject = storeInDictionary + ? GetCachedDataFromDictionary(cacheItemArgs, cacheItemExpired) + : GetCachedDataFromRuntimeCache(cacheItemArgs, cacheItemExpired); + + // return the object + if (objObject == null) + { + return default(TObject); + } + + return (TObject)objObject; + } private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) { @@ -506,7 +544,7 @@ private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, // if item is not cached if (objObject == null) { - //Get Unique Lock for cacheKey + // Get Unique Lock for cacheKey object @lock = GetUniqueLockObject(cacheItemArgs.CacheKey); // prevent other threads from entering this block while we regenerate the cache @@ -516,7 +554,6 @@ private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, objObject = GetCache(cacheItemArgs.CacheKey); // if object was still not retrieved - if (objObject == null) { // get object from data source using delegate @@ -537,26 +574,26 @@ private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, if (objObject != null && timeOut > 0) { // save the object in the cache - SetCache(cacheItemArgs.CacheKey, - objObject, - cacheItemArgs.CacheDependency, - Cache.NoAbsoluteExpiration, - TimeSpan.FromMinutes(timeOut), - cacheItemArgs.CachePriority, - cacheItemArgs.CacheCallback); + SetCache( + cacheItemArgs.CacheKey, + objObject, + cacheItemArgs.CacheDependency, + Cache.NoAbsoluteExpiration, + TimeSpan.FromMinutes(timeOut), + cacheItemArgs.CachePriority, + cacheItemArgs.CacheCallback); // check if the item was actually saved in the cache - if (GetCache(cacheItemArgs.CacheKey) == null) { // log the event if the item was not saved in the cache ( likely because we are out of memory ) - var log = new LogInfo{ LogTypeKey = EventLogController.EventLogType.CACHE_OVERFLOW.ToString() }; + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.CACHE_OVERFLOW.ToString() }; log.LogProperties.Add(new LogDetailInfo(cacheItemArgs.CacheKey, "Overflow - Item Not Cached")); LogController.Instance.AddLog(log); } } - //This thread won so remove unique Lock from collection + // This thread won so remove unique Lock from collection RemoveUniqueLockObject(cacheItemArgs.CacheKey); } } @@ -603,28 +640,6 @@ private static object GetCachedDataFromDictionary(CacheItemArgs cacheItemArgs, C return cachedObject; } - public static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) - { - // declare local object and try and retrieve item from the cache - return GetCachedData(cacheItemArgs, cacheItemExpired, false); - } - - internal static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool storeInDictionary) - { - object objObject = storeInDictionary - ? GetCachedDataFromDictionary(cacheItemArgs, cacheItemExpired) - : GetCachedDataFromRuntimeCache(cacheItemArgs, cacheItemExpired); - - // return the object - if (objObject == null) - { - return default(TObject); - } - return (TObject)objObject; - } - - private static readonly TimeSpan _5seconds = new TimeSpan(0, 0, 5); - private static object GetUniqueLockObject(string key) { object @lock = null; @@ -632,7 +647,7 @@ private static object GetUniqueLockObject(string key) { try { - //Try to get lock Object (for key) from Dictionary + // Try to get lock Object (for key) from Dictionary if (lockDictionary.ContainsKey(key)) { @lock = lockDictionary[key]; @@ -643,19 +658,21 @@ private static object GetUniqueLockObject(string key) dictionaryLock.ExitReadLock(); } } + if (@lock == null) { if (dictionaryLock.TryEnterWriteLock(_5seconds)) { try { - //Double check dictionary + // Double check dictionary if (!lockDictionary.ContainsKey(key)) { - //Create new lock + // Create new lock lockDictionary[key] = new object(); } - //Retrieve lock + + // Retrieve lock @lock = lockDictionary[key]; } finally @@ -664,18 +681,23 @@ private static object GetUniqueLockObject(string key) } } } + return @lock; } private static void RemoveUniqueLockObject(string key) { - if (!dictionaryLock.TryEnterWriteLock(_5seconds)) return; + if (!dictionaryLock.TryEnterWriteLock(_5seconds)) + { + return; + } + try { - //check dictionary + // check dictionary if (lockDictionary.ContainsKey(key)) { - //Remove lock + // Remove lock lockDictionary.Remove(key); } } @@ -685,21 +707,6 @@ private static void RemoveUniqueLockObject(string key) } } - public static TObject GetCache(string CacheKey) - { - object objObject = GetCache(CacheKey); - if (objObject == null) - { - return default(TObject); - } - return (TObject)objObject; - } - - public static object GetCache(string CacheKey) - { - return CachingProvider.Instance().GetItem(GetDnnCacheKey(CacheKey)); - } - public static void RemoveCache(string CacheKey) { CachingProvider.Instance().Remove(GetDnnCacheKey(CacheKey)); @@ -743,13 +750,14 @@ public static void SetCache(string CacheKey, object objObject, DNNCacheDependenc { if (objObject != null) { - //if no OnRemoveCallback value is specified, use the default method + // if no OnRemoveCallback value is specified, use the default method if (OnRemoveCallback == null) { OnRemoveCallback = ItemRemovedCallback; } + CachingProvider.Instance().Insert(GetDnnCacheKey(CacheKey), objObject, objDependency, AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback); } - } + } } } diff --git a/DNN Platform/Library/Common/Utilities/DateUtils.cs b/DNN Platform/Library/Common/Utilities/DateUtils.cs index ae3d62bd9ca..5ac236f9e66 100644 --- a/DNN Platform/Library/Common/Utilities/DateUtils.cs +++ b/DNN Platform/Library/Common/Utilities/DateUtils.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System; - -using DotNetNuke.Data; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + + using DotNetNuke.Data; + using DotNetNuke.Services.Localization; + /// - /// Provides utility methods to work with Dates + /// Provides utility methods to work with Dates. /// public class DateUtils { - private static DateTime _lastUpdateUtc = DateTime.MinValue; private static DateTime _lastUpdateLocal = DateTime.MinValue; @@ -28,7 +23,7 @@ public class DateUtils /// /// Gets the database time. /// - /// Date/time of the database in UTC + /// Date/time of the database in UTC. [Obsolete("Deprecated in DNN 9.1.0. Replaced by GetDatabaseUtcTime. Scheduled removal in v11.0.0.")] public static DateTime GetDatabaseTime() { @@ -36,9 +31,9 @@ public static DateTime GetDatabaseTime() } /// - /// Gets DateTime Offset of current DB + /// Gets DateTime Offset of current DB. /// - /// DateTimeOffset object + /// DateTimeOffset object. public static TimeZoneInfo GetDatabaseDateTimeOffset() { var dateTimeOffset = DataProvider.Instance().GetDatabaseTimeOffset(); @@ -50,7 +45,7 @@ public static TimeZoneInfo GetDatabaseDateTimeOffset() /// /// Gets the database server's time in UTC. /// - /// Date/time of the database in UTC + /// Date/time of the database in UTC. public static DateTime GetDatabaseUtcTime() { try @@ -74,7 +69,7 @@ public static DateTime GetDatabaseUtcTime() /// /// Gets the database server's local time of the DB server and not the web server's local time. /// - /// Date/time of the database in UTC + /// Date/time of the database in UTC. public static DateTime GetDatabaseLocalTime() { try @@ -94,70 +89,69 @@ public static DateTime GetDatabaseLocalTime() return DateTime.Now + _driftLocal; } - - + /// /// Returns a string with the pretty printed amount of time since the specified date. /// - /// DateTime in UTC - /// String representing the required date for display + /// DateTime in UTC. + /// String representing the required date for display. public static string CalculateDateForDisplay(DateTime date) { var utcTimeDifference = GetDatabaseUtcTime() - date; if (utcTimeDifference.TotalSeconds < 60) { - return String.Format(Localization.GetString("SecondsAgo"), (int) utcTimeDifference.TotalSeconds); + return string.Format(Localization.GetString("SecondsAgo"), (int)utcTimeDifference.TotalSeconds); } if (utcTimeDifference.TotalMinutes < 60) { if (utcTimeDifference.TotalMinutes < 2) { - return String.Format(Localization.GetString("MinuteAgo"), (int) utcTimeDifference.TotalMinutes); + return string.Format(Localization.GetString("MinuteAgo"), (int)utcTimeDifference.TotalMinutes); } - return String.Format(Localization.GetString("MinutesAgo"), (int)utcTimeDifference.TotalMinutes); + return string.Format(Localization.GetString("MinutesAgo"), (int)utcTimeDifference.TotalMinutes); } if (utcTimeDifference.TotalHours < 24) { if (utcTimeDifference.TotalHours < 2) { - return String.Format(Localization.GetString("HourAgo"), (int)utcTimeDifference.TotalHours); + return string.Format(Localization.GetString("HourAgo"), (int)utcTimeDifference.TotalHours); } - return String.Format(Localization.GetString("HoursAgo"), (int)utcTimeDifference.TotalHours); + return string.Format(Localization.GetString("HoursAgo"), (int)utcTimeDifference.TotalHours); } if (utcTimeDifference.TotalDays < 7) { if (utcTimeDifference.TotalDays < 2) { - return String.Format(Localization.GetString("DayAgo"), (int)utcTimeDifference.TotalDays); + return string.Format(Localization.GetString("DayAgo"), (int)utcTimeDifference.TotalDays); } - return String.Format(Localization.GetString("DaysAgo"), (int)utcTimeDifference.TotalDays); + return string.Format(Localization.GetString("DaysAgo"), (int)utcTimeDifference.TotalDays); } if (utcTimeDifference.TotalDays < 30) { if (utcTimeDifference.TotalDays < 14) { - return String.Format(Localization.GetString("WeekAgo"), (int)utcTimeDifference.TotalDays / 7); + return string.Format(Localization.GetString("WeekAgo"), (int)utcTimeDifference.TotalDays / 7); } - return String.Format(Localization.GetString("WeeksAgo"), (int)utcTimeDifference.TotalDays / 7); + return string.Format(Localization.GetString("WeeksAgo"), (int)utcTimeDifference.TotalDays / 7); } if (utcTimeDifference.TotalDays < 180) { if (utcTimeDifference.TotalDays < 60) { - return String.Format(Localization.GetString("MonthAgo"), (int)utcTimeDifference.TotalDays / 30); + return string.Format(Localization.GetString("MonthAgo"), (int)utcTimeDifference.TotalDays / 30); } - return String.Format(Localization.GetString("MonthsAgo"), (int)utcTimeDifference.TotalDays / 30); + return string.Format(Localization.GetString("MonthsAgo"), (int)utcTimeDifference.TotalDays / 30); } // anything else (this is the only time we have to personalize it to the user) diff --git a/DNN Platform/Library/Common/Utilities/DictionaryExtensions.cs b/DNN Platform/Library/Common/Utilities/DictionaryExtensions.cs index f187d95d665..f5fa1e917ff 100644 --- a/DNN Platform/Library/Common/Utilities/DictionaryExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/DictionaryExtensions.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + public static class DictionaryExtensions { public static T GetValue(this IDictionary bag, object key, T defaultValue) diff --git a/DNN Platform/Library/Common/Utilities/EnumExtensions.cs b/DNN Platform/Library/Common/Utilities/EnumExtensions.cs index 3e56f227fb0..bfea083e577 100644 --- a/DNN Platform/Library/Common/Utilities/EnumExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/EnumExtensions.cs @@ -1,16 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System; -using System.Collections.Generic; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections.Generic; + /// - /// Extensions for enumeration of KeyValue Paire + /// Extensions for enumeration of KeyValue Paire. /// public static class EnumExtensions { @@ -18,17 +15,18 @@ public static class EnumExtensions /// To the key value pairs. /// /// Type of the enum defined by GetType. - /// A list of Key Value pairs + /// A list of Key Value pairs. public static List> ToKeyValuePairs(this Enum enumType) { var pairs = new List>(); - + var names = Enum.GetNames(enumType.GetType()); var values = Enum.GetValues(enumType.GetType()); for (var i = 0; i < values.Length; i++) { - pairs.Add(new KeyValuePair((int) values.GetValue(i), names[i])); + pairs.Add(new KeyValuePair((int)values.GetValue(i), names[i])); } + return pairs; } } diff --git a/DNN Platform/Library/Common/Utilities/EscapedString.cs b/DNN Platform/Library/Common/Utilities/EscapedString.cs index 82d6c8e1971..bcb9527414b 100644 --- a/DNN Platform/Library/Common/Utilities/EscapedString.cs +++ b/DNN Platform/Library/Common/Utilities/EscapedString.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + using System.Collections.Generic; + public static class EscapedString { private const char EscapeSequence = '\\'; @@ -15,27 +15,27 @@ public static class EscapedString private const char DefaultSeperator = ','; /// - /// Combine the string values of the enumerable into an escaped string + /// Combine the string values of the enumerable into an escaped string. /// - /// An IEnumerable of values to combine - /// An escaped string that is seperated using the specified characeter. The escape character is '\'. + /// An IEnumerable of values to combine. + /// An escaped string that is seperated using the specified characeter. The escape character is '\'. /// The string returned by .ToString() is used as the value of each item in the IEnumerable. - /// The seperator char is ',' + /// The seperator char is ','. public static string Combine(IEnumerable enumerable) { return Combine(enumerable, DefaultSeperator); } /// - /// Combine the string values of the enumerable into an escaped string + /// Combine the string values of the enumerable into an escaped string. /// - /// An IEnumerable of values to combine - /// The character to use as a seperator - /// An escaped string that is seperated using the specified characeter. The escape character is '\'. + /// An IEnumerable of values to combine. + /// The character to use as a seperator. + /// An escaped string that is seperated using the specified characeter. The escape character is '\'. /// The string returned by .ToString() is used as the value of each item in the IEnumerable. public static string Combine(IEnumerable enumerable, char seperator) { - string result = ""; + string result = string.Empty; foreach (var item in enumerable) { @@ -45,45 +45,45 @@ public static string Combine(IEnumerable enumerable, char seperator) result += s + seperator; } - return String.IsNullOrEmpty(result) ? "" : result.Substring(0, result.Length - 1); + return string.IsNullOrEmpty(result) ? string.Empty : result.Substring(0, result.Length - 1); } /// - /// Takes an escaped string and splits it into an IEnumerable of seperate strings + /// Takes an escaped string and splits it into an IEnumerable of seperate strings. /// - /// The string to seperate - /// IEnumerable of all the seperated strings - /// The escape character is '\', the seperator char is ',' + /// The string to seperate. + /// IEnumerable of all the seperated strings. + /// The escape character is '\', the seperator char is ','. public static IEnumerable Seperate(string combinedString) { return Seperate(combinedString, DefaultSeperator); } /// - /// Takes an escaped string and splits it into an IEnumerable of seperate strings + /// Takes an escaped string and splits it into an IEnumerable of seperate strings. /// - /// The string to seperate - /// The character on which to split - /// IEnumerable of all the seperated strings - /// The escape character is '\' + /// The string to seperate. + /// The character on which to split. + /// IEnumerable of all the seperated strings. + /// The escape character is '\'. public static IEnumerable Seperate(string combinedString, char seperator) { var result = new List(); - if(String.IsNullOrEmpty(combinedString)) + if (string.IsNullOrEmpty(combinedString)) { return result; } - - var segments = combinedString.Split(new[] {seperator}); - for(int i = 0; i < segments.Length; i++) + var segments = combinedString.Split(new[] { seperator }); + + for (int i = 0; i < segments.Length; i++) { var current = segments[i]; - while(current.EndsWith(EscapeSequence.ToString())) + while (current.EndsWith(EscapeSequence.ToString())) { - if(EndsInEscapeMode(current)) + if (EndsInEscapeMode(current)) { i++; current = current.Substring(0, current.Length - 1) + seperator + segments[i]; @@ -96,7 +96,7 @@ public static IEnumerable Seperate(string combinedString, char seperator result.Add(current.Replace(DoubleEscapseSequence, EscapeSequence.ToString())); } - + return result; } @@ -104,10 +104,10 @@ private static bool EndsInEscapeMode(string s) { int escapeCount = 0; - //count the number of escape chars on end of string - for(int i = s.Length - 1; i > -1; i--) + // count the number of escape chars on end of string + for (int i = s.Length - 1; i > -1; i--) { - if(s.Substring(i, 1) == EscapeSequence.ToString()) + if (s.Substring(i, 1) == EscapeSequence.ToString()) { escapeCount++; } @@ -117,7 +117,7 @@ private static bool EndsInEscapeMode(string s) } } - return escapeCount%2 == 1; //odd count means escape mode is active + return escapeCount % 2 == 1; // odd count means escape mode is active } } } diff --git a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs index 9f8fdccd3c0..8f9a8f273c5 100644 --- a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs +++ b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs @@ -1,80 +1,80 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections.Generic; + using System.Linq; + public class FileExtensionWhitelist { - private readonly List _extensions; - - /// - /// Initializes a new instance of the FileExtensionWhiteList class. + private readonly List _extensions; + + /// + /// Initializes a new instance of the class. /// - /// a comma seperated list of file extensions with no '.' + /// a comma seperated list of file extensions with no '.'. /// should match the format used in the FileExtensions Host setting specifically it - /// should not have an '.' in the extensions (e.g. txt,jpg,png,doc) + /// should not have an '.' in the extensions (e.g. txt,jpg,png,doc). public FileExtensionWhitelist(string extensionList) { - _extensions = EscapedString.Seperate(extensionList.ToLowerInvariant()).Select(item => "." + item).ToList(); + this._extensions = EscapedString.Seperate(extensionList.ToLowerInvariant()).Select(item => "." + item).ToList(); } /// - /// Returns a string suitale for display to an end user + /// Gets the list of extensions in the whitelist. /// - /// A String of the whitelist extensions formatted for display to an end user - public string ToDisplayString() + /// All extensions are lowercase and prefixed with a '.'. + public IEnumerable AllowedExtensions { - return ToDisplayString(null); + get + { + return this._extensions; + } } /// - /// Formats the extension whitelist appropriate for display to an end user + /// Returns a string suitale for display to an end user. /// - /// A list of additionalExtensions to add to the current extensions - /// case and '.' prefix will be corrected, and duplicates will be excluded from the string - /// A String of the whitelist extensions formatted for storage display to an end user - public string ToDisplayString(IEnumerable additionalExtensions) + /// A String of the whitelist extensions formatted for display to an end user. + public string ToDisplayString() { - IEnumerable allExtensions = CombineLists(additionalExtensions); - return "*" + string.Join(", *", allExtensions.ToArray()); + return this.ToDisplayString(null); } /// - /// The list of extensions in the whitelist. + /// Formats the extension whitelist appropriate for display to an end user. /// - /// All extensions are lowercase and prefixed with a '.' - public IEnumerable AllowedExtensions + /// A list of additionalExtensions to add to the current extensions. + /// case and '.' prefix will be corrected, and duplicates will be excluded from the string. + /// A String of the whitelist extensions formatted for storage display to an end user. + public string ToDisplayString(IEnumerable additionalExtensions) { - get - { - return _extensions; - } + IEnumerable allExtensions = this.CombineLists(additionalExtensions); + return "*" + string.Join(", *", allExtensions.ToArray()); } /// - /// Indicates if the file extension is permitted by the Host Whitelist + /// Indicates if the file extension is permitted by the Host Whitelist. /// - /// The file extension with or without preceding '.' + /// The file extension with or without preceding '.'. /// True if extension is in whitelist or whitelist is empty. False otherwise. - public bool IsAllowedExtension(String extension) + public bool IsAllowedExtension(string extension) { - return IsAllowedExtension(extension, null); + return this.IsAllowedExtension(extension, null); } /// - /// Indicates if the file extension is permitted by the Host Whitelist + /// Indicates if the file extension is permitted by the Host Whitelist. /// - /// The file extension with or without preceding '.' + /// The file extension with or without preceding '.'. /// /// True if extension is in whitelist or whitelist is empty. False otherwise. public bool IsAllowedExtension(string extension, IEnumerable additionalExtensions) { - List allExtensions = CombineLists(additionalExtensions).ToList(); + List allExtensions = this.CombineLists(additionalExtensions).ToList(); if (!allExtensions.Any()) { return true; @@ -94,58 +94,58 @@ public bool IsAllowedExtension(string extension, IEnumerable additionalE public override string ToString() { - return ToDisplayString(); + return this.ToDisplayString(); } /// - /// Formats the extension whitelist appropriate for storage in the Host setting + /// Formats the extension whitelist appropriate for storage in the Host setting. /// - /// A String of the whitelist extensions formatted for storage as a Host setting + /// A String of the whitelist extensions formatted for storage as a Host setting. public string ToStorageString() { - return ToStorageString(null); + return this.ToStorageString(null); } /// - /// Formats the extension whitelist appropriate for storage in the Host setting + /// Formats the extension whitelist appropriate for storage in the Host setting. /// - /// A list of additionalExtensions to add to the current extensions - /// case and '.' prefix will be corrected, and duplicates will be excluded from the string - /// A String of the whitelist extensions formatted for storage as a Host setting + /// A list of additionalExtensions to add to the current extensions. + /// case and '.' prefix will be corrected, and duplicates will be excluded from the string. + /// A String of the whitelist extensions formatted for storage as a Host setting. public string ToStorageString(IEnumerable additionalExtensions) { - IEnumerable allExtensions = CombineLists(additionalExtensions); + IEnumerable allExtensions = this.CombineLists(additionalExtensions); var leadingDotRemoved = allExtensions.Select(ext => ext.Substring(1)); return EscapedString.Combine(leadingDotRemoved); } + public FileExtensionWhitelist RestrictBy(FileExtensionWhitelist parentList) + { + var filter = parentList._extensions; + return new FileExtensionWhitelist(string.Join(",", this._extensions.Where(x => filter.Contains(x)).Select(s => s.Substring(1)))); + } + private IEnumerable CombineLists(IEnumerable additionalExtensions) { if (additionalExtensions == null) { - return _extensions; + return this._extensions; } - //toList required to ensure that multiple enumerations of the list are possible + // toList required to ensure that multiple enumerations of the list are possible var additionalExtensionsList = additionalExtensions.ToList(); if (!additionalExtensionsList.Any()) { - return _extensions; + return this._extensions; } - var normalizedExtensions = NormalizeExtensions(additionalExtensionsList); - return _extensions.Union(normalizedExtensions); + var normalizedExtensions = this.NormalizeExtensions(additionalExtensionsList); + return this._extensions.Union(normalizedExtensions); } private IEnumerable NormalizeExtensions(IEnumerable additionalExtensions) { return additionalExtensions.Select(ext => (ext.StartsWith(".") ? ext : "." + ext).ToLowerInvariant()); } - - public FileExtensionWhitelist RestrictBy(FileExtensionWhitelist parentList) - { - var filter = parentList._extensions; - return new FileExtensionWhitelist(string.Join(",", _extensions.Where(x => filter.Contains(x)).Select(s => s.Substring(1)))); - } } } diff --git a/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs b/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs index bf539332ed2..6867f4f57da 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs @@ -1,7 +1,11 @@ -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + public static class FileSystemExtensions { public static void CheckZipEntry(this ICSharpCode.SharpZipLib.Zip.ZipEntry input) diff --git a/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs b/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs index cd2245fda3e..c87526d905d 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs @@ -1,68 +1,98 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; - -using DotNetNuke.Common.Utilities.Internal; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.IO; + + using DotNetNuke.Common.Utilities.Internal; + using DotNetNuke.Instrumentation; + /// - /// Verifies the abililty to create and delete files and folders + /// Verifies the abililty to create and delete files and folders. /// /// /// This class is not meant for use in modules, or in any other manner outside the DotNetNuke core. /// public class FileSystemPermissionVerifier { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FileSystemPermissionVerifier)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemPermissionVerifier)); private readonly string _basePath; - private int _retryTimes = 30; + private int _retryTimes = 30; + + public FileSystemPermissionVerifier(string basePath) + { + this._basePath = basePath; + } + + public FileSystemPermissionVerifier(string basePath, int retryTimes) + : this(basePath) + { + this._retryTimes = retryTimes; + } /// - /// Base path need to verify permission. + /// Gets base path need to verify permission. /// public string BasePath { get { - return _basePath; + return this._basePath; } } - public FileSystemPermissionVerifier(string basePath) + public bool VerifyAll() { - _basePath = basePath; + lock (typeof(FileSystemPermissionVerifier)) + { + // All these steps must be executed in this sequence as one unit + return this.VerifyFolderCreate() && + this.VerifyFileCreate() && + this.VerifyFileDelete() && + this.VerifyFolderDelete(); + } } - public FileSystemPermissionVerifier(string basePath, int retryTimes) : this(basePath) - { + private static void FileCreateAction(string verifyPath) + { + if (File.Exists(verifyPath)) + { + File.Delete(verifyPath); + } - _retryTimes = retryTimes; - } + using (File.Create(verifyPath)) + { + // do nothing just let it close + } + } + + private static void FolderCreateAction(string verifyPath) + { + if (Directory.Exists(verifyPath)) + { + Directory.Delete(verifyPath, true); + } + + Directory.CreateDirectory(verifyPath); + } /// ----------------------------------------------------------------------------- /// - /// VerifyFileCreate checks whether a file can be created + /// VerifyFileCreate checks whether a file can be created. /// /// ----------------------------------------------------------------------------- private bool VerifyFileCreate() { - string verifyPath = Path.Combine(_basePath, "Verify\\Verify.txt"); + string verifyPath = Path.Combine(this._basePath, "Verify\\Verify.txt"); bool verified = true; - //Attempt to create the File + // Attempt to create the File try { - Try(() => FileCreateAction(verifyPath), "Creating verification file"); + this.Try(() => FileCreateAction(verifyPath), "Creating verification file"); } catch (Exception exc) { @@ -73,33 +103,20 @@ private bool VerifyFileCreate() return verified; } - private static void FileCreateAction(string verifyPath) - { - if (File.Exists(verifyPath)) - { - File.Delete(verifyPath); - } - - using(File.Create(verifyPath)) - { - //do nothing just let it close - } - } - /// ----------------------------------------------------------------------------- /// - /// VerifyFileDelete checks whether a file can be deleted + /// VerifyFileDelete checks whether a file can be deleted. /// /// ----------------------------------------------------------------------------- private bool VerifyFileDelete() { - string verifyPath = Path.Combine(_basePath, "Verify\\Verify.txt"); + string verifyPath = Path.Combine(this._basePath, "Verify\\Verify.txt"); bool verified = true; - //Attempt to delete the File + // Attempt to delete the File try { - Try(() => File.Delete(verifyPath), "Deleting verification file"); + this.Try(() => File.Delete(verifyPath), "Deleting verification file"); } catch (Exception exc) { @@ -112,18 +129,18 @@ private bool VerifyFileDelete() /// ----------------------------------------------------------------------------- /// - /// VerifyFolderCreate checks whether a folder can be created + /// VerifyFolderCreate checks whether a folder can be created. /// /// ----------------------------------------------------------------------------- private bool VerifyFolderCreate() { - string verifyPath = Path.Combine(_basePath, "Verify"); + string verifyPath = Path.Combine(this._basePath, "Verify"); bool verified = true; - //Attempt to create the Directory + // Attempt to create the Directory try { - Try(() => FolderCreateAction(verifyPath), "Creating verification folder"); + this.Try(() => FolderCreateAction(verifyPath), "Creating verification folder"); } catch (Exception exc) { @@ -134,30 +151,20 @@ private bool VerifyFolderCreate() return verified; } - private static void FolderCreateAction(string verifyPath) - { - if (Directory.Exists(verifyPath)) - { - Directory.Delete(verifyPath, true); - } - - Directory.CreateDirectory(verifyPath); - } - /// ----------------------------------------------------------------------------- /// - /// VerifyFolderDelete checks whether a folder can be deleted + /// VerifyFolderDelete checks whether a folder can be deleted. /// /// ----------------------------------------------------------------------------- private bool VerifyFolderDelete() { - string verifyPath = Path.Combine(_basePath, "Verify"); + string verifyPath = Path.Combine(this._basePath, "Verify"); bool verified = true; - //Attempt to delete the Directory + // Attempt to delete the Directory try { - Try(() => Directory.Delete(verifyPath, true), "Deleting verification folder"); + this.Try(() => Directory.Delete(verifyPath, true), "Deleting verification folder"); } catch (Exception exc) { @@ -168,21 +175,9 @@ private bool VerifyFolderDelete() return verified; } - public bool VerifyAll() + private void Try(Action action, string description) { - lock (typeof(FileSystemPermissionVerifier)) - { - // All these steps must be executed in this sequence as one unit - return VerifyFolderCreate() && - VerifyFileCreate() && - VerifyFileDelete() && - VerifyFolderDelete(); - } + new RetryableAction(action, description, this._retryTimes, TimeSpan.FromSeconds(1)).TryIt(); } - - private void Try(Action action, string description) - { - new RetryableAction(action, description, _retryTimes, TimeSpan.FromSeconds(1)).TryIt(); - } } } diff --git a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs index 460cf316028..a92dad9ba10 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs @@ -1,50 +1,104 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading; -using System.Web; - -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; - -using ICSharpCode.SharpZipLib.Checksums; -using ICSharpCode.SharpZipLib.Zip; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; -using Directory = SchwabenCode.QuickIO.QuickIODirectory; -using File = SchwabenCode.QuickIO.QuickIOFile; -using DirectoryInfo = SchwabenCode.QuickIO.QuickIODirectoryInfo; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Drawing; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Threading; + using System.Web; + + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using ICSharpCode.SharpZipLib.Checksums; + using ICSharpCode.SharpZipLib.Zip; + + using Directory = SchwabenCode.QuickIO.QuickIODirectory; + using DirectoryInfo = SchwabenCode.QuickIO.QuickIODirectoryInfo; + using File = SchwabenCode.QuickIO.QuickIOFile; + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + public class FileSystemUtils { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FileSystemUtils)); - #region Private Methods + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemUtils)); + + /// ----------------------------------------------------------------------------- + /// + /// Adds a File to a Zip File. + /// + /// ----------------------------------------------------------------------------- + public static void AddToZip(ref ZipOutputStream ZipFile, string filePath, string fileName, string folder) + { + FileStream fs = null; + try + { + // Open File Stream + fs = File.OpenRead(FixPath(filePath)); + + // Read file into byte array buffer + var buffer = new byte[fs.Length]; + var len = fs.Read(buffer, 0, buffer.Length); + if (len != fs.Length) + { + Logger.ErrorFormat( + "Reading from " + filePath + " didn't read all data in buffer. " + + "Requested to read {0} bytes, but was read {1} bytes", fs.Length, len); + } + + // Create Zip Entry + var entry = new ZipEntry(Path.Combine(folder, fileName)); + entry.DateTime = DateTime.Now; + entry.Size = fs.Length; + fs.Close(); + + // Compress file and add to Zip file + ZipFile.PutNextEntry(entry); + ZipFile.Write(buffer, 0, buffer.Length); + } + finally + { + if (fs != null) + { + fs.Close(); + fs.Dispose(); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Tries to copy a file in the file system. + /// + /// The name of the source file. + /// The name of the destination file. + /// ----------------------------------------------------------------------------- + public static void CopyFile(string sourceFileName, string destFileName) + { + if (File.Exists(destFileName)) + { + File.SetAttributes(destFileName, FileAttributes.Normal); + } + + File.Copy(sourceFileName, destFileName, true); + } + private static string CreateFile(IFolderInfo folder, string fileName, string contentType, Stream fileContent, bool unzip, bool overwrite, bool checkPermissions) { - var strMessage = ""; + var strMessage = string.Empty; var fileManager = FileManager.Instance; try @@ -79,13 +133,13 @@ private static string CreateFile(IFolderInfo folder, string fileName, string con /// ----------------------------------------------------------------------------- /// - /// Gets the filename for a file path + /// Gets the filename for a file path. /// - /// The full name of the file + /// The full name of the file. /// ----------------------------------------------------------------------------- private static string GetFileName(string filePath) { - return Path.GetFileName(filePath).Replace(Globals.glbProtectedExtension, ""); + return Path.GetFileName(filePath).Replace(Globals.glbProtectedExtension, string.Empty); } private static int GetFolderPortalID(PortalSettings settings) @@ -111,41 +165,41 @@ private static void RemoveOrphanedFile(FileInfo objFile, int PortalId) /// ----------------------------------------------------------------------------- /// - /// Writes a Stream to the appropriate File Storage + /// Writes a Stream to the appropriate File Storage. /// - /// The Id of the File - /// The Input Stream + /// The Id of the File. + /// The Input Stream. /// /// /// ----------------------------------------------------------------------------- private static void WriteStream(HttpResponse objResponse, Stream objStream) { - //Buffer to read 10K bytes in chunk: + // Buffer to read 10K bytes in chunk: var bytBuffer = new byte[10000]; - //Length of the file: + // Length of the file: int intLength; - //Total bytes to read: + // Total bytes to read: long lngDataToRead; try { - //Total bytes to read: + // Total bytes to read: lngDataToRead = objStream.Length; - //Read the bytes. + // Read the bytes. while (lngDataToRead > 0) { - //Verify that the client is connected. + // Verify that the client is connected. if (objResponse.IsClientConnected) { - //Read the data in buffer + // Read the data in buffer intLength = objStream.Read(bytBuffer, 0, 10000); - //Write the data to the current output stream. + // Write the data to the current output stream. objResponse.OutputStream.Write(bytBuffer, 0, intLength); - //Flush the data to the HTML output. + // Flush the data to the HTML output. objResponse.Flush(); lngDataToRead = lngDataToRead - intLength; @@ -169,88 +223,28 @@ private static void WriteStream(HttpResponse objResponse, Stream objStream) objStream.Dispose(); } } - } - - #endregion - - /// ----------------------------------------------------------------------------- - /// - /// Adds a File to a Zip File - /// - /// ----------------------------------------------------------------------------- - public static void AddToZip(ref ZipOutputStream ZipFile, string filePath, string fileName, string folder) - { - FileStream fs = null; - try - { - //Open File Stream - fs = File.OpenRead(FixPath(filePath)); - - //Read file into byte array buffer - var buffer = new byte[fs.Length]; - - var len = fs.Read(buffer, 0, buffer.Length); - if (len != fs.Length) - { - Logger.ErrorFormat("Reading from " + filePath + " didn't read all data in buffer. " + - "Requested to read {0} bytes, but was read {1} bytes", fs.Length, len); - } - - //Create Zip Entry - var entry = new ZipEntry(Path.Combine(folder, fileName)); - entry.DateTime = DateTime.Now; - entry.Size = fs.Length; - fs.Close(); - - //Compress file and add to Zip file - ZipFile.PutNextEntry(entry); - ZipFile.Write(buffer, 0, buffer.Length); - } - finally - { - if (fs != null) - { - fs.Close(); - fs.Dispose(); - } - } - } + } /// ----------------------------------------------------------------------------- /// - /// Tries to copy a file in the file system - /// - /// The name of the source file - /// The name of the destination file - /// ----------------------------------------------------------------------------- - public static void CopyFile(string sourceFileName, string destFileName) - { - if (File.Exists(destFileName)) - { - File.SetAttributes(destFileName, FileAttributes.Normal); - } - File.Copy(sourceFileName, destFileName, true); - } - - /// ----------------------------------------------------------------------------- - /// - /// Deletes file in areas with a high degree of concurrent file access (i.e. caching, logging) + /// Deletes file in areas with a high degree of concurrent file access (i.e. caching, logging) /// This solves file concurrency issues under heavy load. /// - /// String - /// Int16 - /// Int16 - /// Boolean + /// String. + /// Int16. + /// Int16. + /// Boolean. /// /// /// ----------------------------------------------------------------------------- - public static bool DeleteFileWithWait(string fileName, Int16 waitInMilliseconds, Int16 maxAttempts) + public static bool DeleteFileWithWait(string fileName, short waitInMilliseconds, short maxAttempts) { fileName = FixPath(fileName); if (!File.Exists(fileName)) { return true; } + bool fileDeleted = false; int i = 0; while (fileDeleted != true) @@ -259,6 +253,7 @@ public static bool DeleteFileWithWait(string fileName, Int16 waitInMilliseconds, { break; } + i = i + 1; try { @@ -266,26 +261,29 @@ public static bool DeleteFileWithWait(string fileName, Int16 waitInMilliseconds, { File.Delete(fileName); } - fileDeleted = true; //we don't care if it didn't exist...the operation didn't fail, that's what we care about + + fileDeleted = true; // we don't care if it didn't exist...the operation didn't fail, that's what we care about } catch (Exception exc) { Logger.Error(exc); fileDeleted = false; } + if (fileDeleted == false) { Thread.Sleep(waitInMilliseconds); } } + return fileDeleted; } /// ----------------------------------------------------------------------------- /// - /// Tries to delete a file from the file system + /// Tries to delete a file from the file system. /// - /// The name of the file + /// The name of the file. /// ----------------------------------------------------------------------------- public static void DeleteFile(string fileName) { @@ -314,6 +312,7 @@ public static string ReadFile(string filePath) reader.Dispose(); } } + return fileContent; } @@ -332,6 +331,7 @@ public static void UnzipResources(ZipInputStream zipStream, string destPath) { Directory.Create(Path.Combine(destPath, relativeDir), true); } + if (!zipEntry.IsDirectory && (!string.IsNullOrEmpty(localFileName))) { var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); @@ -342,6 +342,7 @@ public static void UnzipResources(ZipInputStream zipStream, string destPath) File.SetAttributes(fileNamePath, FileAttributes.Normal); File.Delete(fileNamePath); } + FileStream objFileStream = null; try { @@ -365,11 +366,12 @@ public static void UnzipResources(ZipInputStream zipStream, string destPath) } } } - catch(Exception ex) + catch (Exception ex) { - Logger.Error(ex); + Logger.Error(ex); } } + zipEntry = zipStream.GetNextEntry(); } } @@ -385,10 +387,10 @@ public static void UnzipResources(ZipInputStream zipStream, string destPath) public static string DeleteFiles(Array arrPaths) { - var strExceptions = ""; + var strExceptions = string.Empty; for (var i = 0; i < arrPaths.Length; i++) { - var strPath = (arrPaths.GetValue(i) ?? "").ToString(); + var strPath = (arrPaths.GetValue(i) ?? string.Empty).ToString(); var pos = strPath.IndexOf("'", StringComparison.Ordinal); if (pos != -1) { @@ -436,12 +438,13 @@ public static string DeleteFiles(Array arrPaths) } } } + return strExceptions; } public static void DeleteFilesRecursive(string strRoot, string filter) { - if (!String.IsNullOrEmpty(strRoot)) + if (!string.IsNullOrEmpty(strRoot)) { strRoot = FixPath(strRoot); if (Directory.Exists(strRoot)) @@ -454,6 +457,7 @@ public static void DeleteFilesRecursive(string strRoot, string filter) DeleteFilesRecursive(strFolder, filter); } } + foreach (string strFile in Directory.EnumerateFilePaths(strRoot).Where(f => f.Contains(filter))) { try @@ -473,7 +477,8 @@ public static void DeleteFolderRecursive(string strRoot) { strRoot = FixPath(strRoot); if (string.IsNullOrEmpty(strRoot) || !Directory.Exists(strRoot)) - { Logger.Info(strRoot + " does not exist. "); + { + Logger.Info(strRoot + " does not exist. "); return; } diff --git a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs index c36e82dda1c..66214a1ea8e 100644 --- a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs @@ -1,46 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.Services.Upgrade; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Services.Upgrade; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Common.Utilities /// Project: DotNetNuke /// Class: HtmlUtils /// ----------------------------------------------------------------------------- /// - /// HtmlUtils is a Utility class that provides Html Utility methods + /// HtmlUtils is a Utility class that provides Html Utility methods. /// /// /// /// ----------------------------------------------------------------------------- public class HtmlUtils { + // Create Regular Expression objects + private const string PunctuationMatch = "[~!#\\$%\\^&*\\(\\)-+=\\{\\[\\}\\]\\|;:\\x22'<,>\\.\\?\\\\\\t\\r\\v\\f\\n]"; + private static readonly Regex HtmlDetectionRegex = new Regex("<(.*\\s*)>", RegexOptions.Compiled); private static readonly Regex StripWhiteSpaceRegex = new Regex("\\s+", RegexOptions.Compiled); private static readonly Regex StripNonWordRegex = new Regex("\\W*", RegexOptions.Compiled); private static readonly Regex StripTagsRegex = new Regex("<[^<>]*>", RegexOptions.Compiled); private static readonly Regex RemoveInlineStylesRegEx = new Regex("", RegexOptions.Compiled | RegexOptions.Multiline); - - //Match all variants of
    tag (
    ,
    ,
    , including embedded space - private static readonly Regex ReplaceHtmlNewLinesRegex = new Regex("\\s*<\\s*[bB][rR]\\s*/\\s*>\\s*", RegexOptions.Compiled); - //Create Regular Expression objects - private const string PunctuationMatch = "[~!#\\$%\\^&*\\(\\)-+=\\{\\[\\}\\]\\|;:\\x22'<,>\\.\\?\\\\\\t\\r\\v\\f\\n]"; + // Match all variants of
    tag (
    ,
    ,
    , including embedded space + private static readonly Regex ReplaceHtmlNewLinesRegex = new Regex("\\s*<\\s*[bB][rR]\\s*/\\s*>\\s*", RegexOptions.Compiled); private static readonly Regex AfterRegEx = new Regex(PunctuationMatch + "\\s", RegexOptions.Compiled); private static readonly Regex BeforeRegEx = new Regex("\\s" + PunctuationMatch, RegexOptions.Compiled); private static readonly Regex EntityRegEx = new Regex("&[^;]+;", RegexOptions.Compiled); @@ -49,14 +44,14 @@ public class HtmlUtils /// ----------------------------------------------------------------------------- /// /// Clean removes any HTML Tags, Entities (and optionally any punctuation) from - /// a string + /// a string. /// /// - /// Encoded Tags are getting decoded, as they are part of the content! + /// Encoded Tags are getting decoded, as they are part of the content!. /// - /// The Html to clean - /// A flag indicating whether to remove punctuation - /// The cleaned up string + /// The Html to clean. + /// A flag indicating whether to remove punctuation. + /// The cleaned up string. /// ----------------------------------------------------------------------------- public static string Clean(string HTML, bool RemovePunctuation) { @@ -71,18 +66,19 @@ public static string Clean(string HTML, bool RemovePunctuation) HTML = HttpUtility.HtmlDecode(HTML); } - //First remove any HTML Tags ("<....>") + // First remove any HTML Tags ("<....>") HTML = StripTags(HTML, true); - //Second replace any HTML entities (  < etc) through their char symbol + // Second replace any HTML entities (  < etc) through their char symbol HTML = HttpUtility.HtmlDecode(HTML); - //Thirdly remove any punctuation + // Thirdly remove any punctuation if (RemovePunctuation) { HTML = StripPunctuation(HTML, true); + // When RemovePunctuation is false, HtmlDecode() would have already had removed these - //Finally remove extra whitespace + // Finally remove extra whitespace HTML = StripWhiteSpace(HTML, true); } @@ -96,7 +92,7 @@ public static string Clean(string HTML, bool RemovePunctuation) /// /// /// - /// The cleaned up string + /// The cleaned up string. /// /// /// ----------------------------------------------------------------------------- @@ -107,31 +103,30 @@ public static string CleanWithTagInfo(string html, string tagsFilter, bool remov return string.Empty; } - //First remove unspecified HTML Tags ("<....>") + // First remove unspecified HTML Tags ("<....>") html = StripUnspecifiedTags(html, tagsFilter, true); - //Second replace any HTML entities (  < etc) through their char symbol + // Second replace any HTML entities (  < etc) through their char symbol html = HttpUtility.HtmlDecode(html); - //Thirdly remove any punctuation + // Thirdly remove any punctuation if (removePunctuation) { html = StripPunctuation(html, true); } - //Finally remove extra whitespace + // Finally remove extra whitespace html = StripWhiteSpace(html, true); return html; } - - + /// ----------------------------------------------------------------------------- /// - /// Formats an Email address + /// Formats an Email address. /// - /// The email address to format - /// The formatted email address + /// The email address to format. + /// The formatted email address. /// ----------------------------------------------------------------------------- public static string FormatEmail(string Email) { @@ -140,15 +135,15 @@ public static string FormatEmail(string Email) /// ----------------------------------------------------------------------------- /// - /// Formats an Email address + /// Formats an Email address. /// - /// The email address to format - /// A flag that indicates whether the text should be cloaked - /// The formatted email address + /// The email address to format. + /// A flag that indicates whether the text should be cloaked. + /// The formatted email address. /// ----------------------------------------------------------------------------- public static string FormatEmail(string Email, bool cloak) { - string formatEmail = ""; + string formatEmail = string.Empty; if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Email.Trim())) { if (Email.IndexOf("@", StringComparison.Ordinal) != -1) @@ -160,41 +155,41 @@ public static string FormatEmail(string Email, bool cloak) formatEmail = Email; } } + if (cloak) { formatEmail = Globals.CloakText(formatEmail); } + return formatEmail; } /// ----------------------------------------------------------------------------- /// - /// FormatText replaces
    tags by LineFeed characters + /// FormatText replaces
    tags by LineFeed characters. ///
    /// /// - /// The HTML content to clean up - /// Whether ratain Space - /// The cleaned up string + /// The HTML content to clean up. + /// Whether ratain Space. + /// The cleaned up string. /// ----------------------------------------------------------------------------- public static string FormatText(string HTML, bool RetainSpace) { return ReplaceHtmlNewLinesRegex.Replace(HTML, Environment.NewLine); } - - + /// ----------------------------------------------------------------------------- /// - /// Formats String as Html by replacing linefeeds by
    + /// Formats String as Html by replacing linefeeds by.
    ///
    /// /// - /// Text to format - /// The formatted html + /// Text to format. + /// The formatted html. /// ----------------------------------------------------------------------------- public static string ConvertToHtml(string strText) { - if (!string.IsNullOrEmpty(strText)) { var htmlBuilder = new StringBuilder(strText); @@ -209,12 +204,12 @@ public static string ConvertToHtml(string strText) /// ----------------------------------------------------------------------------- /// - /// Formats Html as text by removing
    tags and replacing by linefeeds + /// Formats Html as text by removing
    tags and replacing by linefeeds. ///
    /// /// - /// Html to format - /// The formatted text + /// Html to format. + /// The formatted text. /// ----------------------------------------------------------------------------- public static string ConvertToText(string strHtml) { @@ -222,36 +217,35 @@ public static string ConvertToText(string strHtml) if (!string.IsNullOrEmpty(strText)) { - //First remove white space (html does not render white space anyway and it screws up the conversion to text) - //Replace it by a single space + // First remove white space (html does not render white space anyway and it screws up the conversion to text) + // Replace it by a single space strText = StripWhiteSpace(strText, true); - //Replace all variants of
    by Linefeeds + // Replace all variants of
    by Linefeeds strText = FormatText(strText, false); } - - + return strText; } /// ----------------------------------------------------------------------------- /// - /// Format a domain name including link + /// Format a domain name including link. /// - /// The domain name to format - /// The formatted domain name + /// The domain name to format. + /// The formatted domain name. /// ----------------------------------------------------------------------------- public static string FormatWebsite(object Website) { - string formatWebsite = ""; + string formatWebsite = string.Empty; if (Website != DBNull.Value) { - if (!String.IsNullOrEmpty(Website.ToString().Trim())) + if (!string.IsNullOrEmpty(Website.ToString().Trim())) { if (Website.ToString().IndexOf(".", StringComparison.Ordinal) > -1) { formatWebsite = string.Format("{0}", Website, - (Website.ToString().IndexOf("://", StringComparison.Ordinal) > -1 ? "" : "http://")); + Website.ToString().IndexOf("://", StringComparison.Ordinal) > -1 ? string.Empty : "http://"); } else { @@ -259,19 +253,20 @@ public static string FormatWebsite(object Website) } } } + return formatWebsite; } /// ----------------------------------------------------------------------------- /// - /// Shorten returns the first (x) characters of a string + /// Shorten returns the first (x) characters of a string. /// /// /// - /// The text to reduces - /// The max number of characters to return - /// An optional suffic to append to the shortened string - /// The shortened string + /// The text to reduces. + /// The max number of characters to return. + /// An optional suffic to append to the shortened string. + /// The shortened string. /// ----------------------------------------------------------------------------- public static string Shorten(string txt, int length, string suffix) { @@ -285,30 +280,31 @@ public static string Shorten(string txt, int length, string suffix) /// ----------------------------------------------------------------------------- /// - /// StripEntities removes the HTML Entities from the content + /// StripEntities removes the HTML Entities from the content. /// /// /// - /// The HTML content to clean up - /// Indicates whether to replace the Entity by a space (true) or nothing (false) - /// The cleaned up string + /// The HTML content to clean up. + /// Indicates whether to replace the Entity by a space (true) or nothing (false). + /// The cleaned up string. /// ----------------------------------------------------------------------------- [Obsolete("This method has been deprecated. Please use System.Web.HtmlUtility.HtmlDecode. Scheduled removal in v11.0.0.")] public static string StripEntities(string HTML, bool RetainSpace) { - var repString = RetainSpace ? " " : ""; - //Replace Entities by replacement String and return mofified string + var repString = RetainSpace ? " " : string.Empty; + + // Replace Entities by replacement String and return mofified string return EntityRegEx.Replace(HTML, repString); } /// ----------------------------------------------------------------------------- /// - /// Checks whether the string contains any HTML Entity or not + /// Checks whether the string contains any HTML Entity or not. /// /// /// - /// The HTML content to clean up - /// True if the string contains any entity + /// The HTML content to clean up. + /// True if the string contains any entity. /// ----------------------------------------------------------------------------- public static bool ContainsEntity(string html) { @@ -317,10 +313,10 @@ public static bool ContainsEntity(string html) /// ----------------------------------------------------------------------------- /// - /// Checks whether the string contains any URL encoded entity or not + /// Checks whether the string contains any URL encoded entity or not. /// - /// The string check - /// True if the string contains any URL encoded entity + /// The string check. + /// True if the string contains any URL encoded entity. /// ----------------------------------------------------------------------------- public static bool IsUrlEncoded(string text) { @@ -328,40 +324,39 @@ public static bool IsUrlEncoded(string text) } /// - /// Removes Inline CSS Styles + /// Removes Inline CSS Styles. /// - /// The HTML content to clean up - /// The cleaned up string + /// The HTML content to clean up. + /// The cleaned up string. public static string RemoveInlineStyle(string HTML) { - return RemoveInlineStylesRegEx.Replace(HTML, ""); - + return RemoveInlineStylesRegEx.Replace(HTML, string.Empty); } + /// ----------------------------------------------------------------------------- /// - /// StripTags removes the HTML Tags from the content + /// StripTags removes the HTML Tags from the content. /// /// /// - /// The HTML content to clean up - /// Indicates whether to replace the Tag by a space (true) or nothing (false) - /// The cleaned up string + /// The HTML content to clean up. + /// Indicates whether to replace the Tag by a space (true) or nothing (false). + /// The cleaned up string. /// ----------------------------------------------------------------------------- public static string StripTags(string HTML, bool RetainSpace) { - return StripTagsRegex.Replace(HTML, RetainSpace ? " " : ""); + return StripTagsRegex.Replace(HTML, RetainSpace ? " " : string.Empty); } - - + /// ----------------------------------------------------------------------------- /// - /// StripUnspecifiedTags removes the HTML tags from the content -- leaving behind the info + /// StripUnspecifiedTags removes the HTML tags from the content -- leaving behind the info /// for the specified HTML tags. /// /// /// /// - /// The cleaned up string + /// The cleaned up string. /// /// /// ----------------------------------------------------------------------------- @@ -374,13 +369,13 @@ public static string StripUnspecifiedTags(string html, string specifiedTags, boo var result = new StringBuilder(); - //Set up Replacement String - var repString = retainSpace ? " " : ""; + // Set up Replacement String + var repString = retainSpace ? " " : string.Empty; - //Stripped HTML + // Stripped HTML result.Append(StripTagsRegex.Replace(html, repString)); - //Adding Tag info from specified tags + // Adding Tag info from specified tags foreach (Match m in Regex.Matches(html, "(?<=(" + specifiedTags + ")=)\"(?.*?)\"")) { if (m.Value.Length > 0) @@ -391,17 +386,16 @@ public static string StripUnspecifiedTags(string html, string specifiedTags, boo return result.ToString(); } - - + /// ----------------------------------------------------------------------------- /// - /// StripPunctuation removes the Punctuation from the content + /// StripPunctuation removes the Punctuation from the content. /// /// /// - /// The HTML content to clean up - /// Indicates whether to replace the Punctuation by a space (true) or nothing (false) - /// The cleaned up string + /// The HTML content to clean up. + /// Indicates whether to replace the Punctuation by a space (true) or nothing (false). + /// The cleaned up string. /// ----------------------------------------------------------------------------- public static string StripPunctuation(string HTML, bool RetainSpace) { @@ -410,66 +404,71 @@ public static string StripPunctuation(string HTML, bool RetainSpace) return string.Empty; } - //Define return string - string retHTML = HTML + " "; //Make sure any punctuation at the end of the String is removed + // Define return string + string retHTML = HTML + " "; // Make sure any punctuation at the end of the String is removed - //Set up Replacement String - var repString = RetainSpace ? " " : ""; + // Set up Replacement String + var repString = RetainSpace ? " " : string.Empty; while (BeforeRegEx.IsMatch(retHTML)) { retHTML = BeforeRegEx.Replace(retHTML, repString); } + while (AfterRegEx.IsMatch(retHTML)) { retHTML = AfterRegEx.Replace(retHTML, repString); } + // Return modified string after trimming leading and ending quotation marks return retHTML.Trim('"'); } - - + /// ----------------------------------------------------------------------------- /// - /// StripWhiteSpace removes the WhiteSpace from the content + /// StripWhiteSpace removes the WhiteSpace from the content. /// /// /// - /// The HTML content to clean up - /// Indicates whether to replace the WhiteSpace by a space (true) or nothing (false) - /// The cleaned up string + /// The HTML content to clean up. + /// Indicates whether to replace the WhiteSpace by a space (true) or nothing (false). + /// The cleaned up string. /// ----------------------------------------------------------------------------- public static string StripWhiteSpace(string HTML, bool RetainSpace) { - if (string.IsNullOrWhiteSpace(HTML)) - return Null.NullString; - - return StripWhiteSpaceRegex.Replace(HTML, RetainSpace ? " " : ""); + if (string.IsNullOrWhiteSpace(HTML)) + { + return Null.NullString; + } + + return StripWhiteSpaceRegex.Replace(HTML, RetainSpace ? " " : string.Empty); } /// ----------------------------------------------------------------------------- /// - /// StripNonWord removes any Non-Word Character from the content + /// StripNonWord removes any Non-Word Character from the content. /// /// /// - /// The HTML content to clean up - /// Indicates whether to replace the Non-Word Character by a space (true) or nothing (false) - /// The cleaned up string + /// The HTML content to clean up. + /// Indicates whether to replace the Non-Word Character by a space (true) or nothing (false). + /// The cleaned up string. /// ----------------------------------------------------------------------------- public static string StripNonWord(string HTML, bool RetainSpace) { - if (string.IsNullOrWhiteSpace(HTML)) - return HTML; - - string RepString = RetainSpace ? " " : ""; + if (string.IsNullOrWhiteSpace(HTML)) + { + return HTML; + } + + string RepString = RetainSpace ? " " : string.Empty; return StripNonWordRegex.Replace(HTML, RepString); } /// - /// Determines wether or not the passed in string contains any HTML tags + /// Determines wether or not the passed in string contains any HTML tags. /// - /// Text to be inspected - /// True for HTML and False for plain text + /// Text to be inspected. + /// True for HTML and False for plain text. /// /// public static bool IsHtml(string text) @@ -484,13 +483,13 @@ public static bool IsHtml(string text) /// ----------------------------------------------------------------------------- /// - /// WriteError outputs an Error Message during Install/Upgrade etc + /// WriteError outputs an Error Message during Install/Upgrade etc. /// /// /// - /// The ASP.Net Response object - /// The filename where the Error Occurred - /// The error message + /// The ASP.Net Response object. + /// The filename where the Error Occurred. + /// The error message. /// ----------------------------------------------------------------------------- public static void WriteError(HttpResponse response, string file, string message) { @@ -505,31 +504,31 @@ public static void WriteError(HttpResponse response, string file, string message /// ----------------------------------------------------------------------------- /// - /// WriteFeedback outputs a Feedback Line during Install/Upgrade etc + /// WriteFeedback outputs a Feedback Line during Install/Upgrade etc. /// /// /// - /// The ASP.Net Response object - /// The indent for this feedback message - /// The feedback message + /// The ASP.Net Response object. + /// The indent for this feedback message. + /// The feedback message. /// ----------------------------------------------------------------------------- - public static void WriteFeedback(HttpResponse response, Int32 indent, string message) + public static void WriteFeedback(HttpResponse response, int indent, string message) { WriteFeedback(response, indent, message, true); } /// ----------------------------------------------------------------------------- /// - /// WriteFeedback outputs a Feedback Line during Install/Upgrade etc + /// WriteFeedback outputs a Feedback Line during Install/Upgrade etc. /// /// /// - /// The ASP.Net Response object - /// The indent for this feedback message - /// The feedback message - /// Show the timespan before the message + /// The ASP.Net Response object. + /// The indent for this feedback message. + /// The feedback message. + /// Show the timespan before the message. /// ----------------------------------------------------------------------------- - public static void WriteFeedback(HttpResponse response, Int32 indent, string message, bool showtime) + public static void WriteFeedback(HttpResponse response, int indent, string message, bool showtime) { try { @@ -537,17 +536,19 @@ public static void WriteFeedback(HttpResponse response, Int32 indent, string mes string configSetting = Config.GetSetting("ShowInstallationMessages") ?? "true"; if (bool.TryParse(configSetting, out showInstallationMessages) && showInstallationMessages) { - //Get the time of the feedback + // Get the time of the feedback TimeSpan timeElapsed = Upgrade.RunTime; - string strMessage = ""; + string strMessage = string.Empty; if (showtime) { strMessage += timeElapsed.ToString().Substring(0, timeElapsed.ToString().LastIndexOf(".", StringComparison.Ordinal) + 4) + " -"; } + for (int i = 0; i <= indent; i++) { strMessage += " "; } + strMessage += message; response.Write(strMessage); response.Flush(); @@ -561,7 +562,7 @@ public static void WriteFeedback(HttpResponse response, Int32 indent, string mes } /// - /// This method adds an empty char to the response stream to avoid closing http connection on long running tasks + /// This method adds an empty char to the response stream to avoid closing http connection on long running tasks. /// public static void WriteKeepAlive() { @@ -573,17 +574,16 @@ public static void WriteKeepAlive() response.Write(" "); response.Flush(); } - } } /// ----------------------------------------------------------------------------- /// - /// WriteFooter outputs the Footer during Install/Upgrade etc + /// WriteFooter outputs the Footer during Install/Upgrade etc. /// /// /// - /// The ASP.Net Response object + /// The ASP.Net Response object. /// ----------------------------------------------------------------------------- public static void WriteFooter(HttpResponse response) { @@ -594,19 +594,19 @@ public static void WriteFooter(HttpResponse response) /// ----------------------------------------------------------------------------- /// - /// WriteHeader outputs the Header during Install/Upgrade etc + /// WriteHeader outputs the Header during Install/Upgrade etc. /// /// /// - /// The ASP.Net Response object - /// The mode Install/Upgrade etc + /// The ASP.Net Response object. + /// The mode Install/Upgrade etc. /// ----------------------------------------------------------------------------- public static void WriteHeader(HttpResponse response, string mode) { - //Set Response buffer to False + // Set Response buffer to False response.Buffer = false; - //create an install page if it does not exist already + // create an install page if it does not exist already if (!File.Exists(HttpContext.Current.Server.MapPath("~/Install/Install.htm"))) { if (File.Exists(HttpContext.Current.Server.MapPath("~/Install/Install.template.htm"))) @@ -614,11 +614,13 @@ public static void WriteHeader(HttpResponse response, string mode) File.Copy(HttpContext.Current.Server.MapPath("~/Install/Install.template.htm"), HttpContext.Current.Server.MapPath("~/Install/Install.htm")); } } - //read install page and insert into response stream + + // read install page and insert into response stream if (File.Exists(HttpContext.Current.Server.MapPath("~/Install/Install.htm"))) { response.Write(FileSystemUtils.ReadFile(HttpContext.Current.Server.MapPath("~/Install/Install.htm"))); } + switch (mode) { case "install": @@ -649,6 +651,7 @@ public static void WriteHeader(HttpResponse response, string mode) response.Write("

    " + mode + "

    "); break; } + response.Flush(); } @@ -670,11 +673,11 @@ public static void WriteScriptSuccessError(HttpResponse response, bool bSuccess, } /// - /// Searches the provided html for absolute hrefs that match the provided aliases and converts them to relative urls + /// Searches the provided html for absolute hrefs that match the provided aliases and converts them to relative urls. /// - /// The input html - /// a list of aliases that should be made into relative urls - /// html string + /// The input html. + /// a list of aliases that should be made into relative urls. + /// html string. public static string AbsoluteToRelativeUrls(string html, IEnumerable aliases) { if (string.IsNullOrWhiteSpace(html)) @@ -704,6 +707,5 @@ public static string AbsoluteToRelativeUrls(string html, IEnumerable ali return html; } - } } diff --git a/DNN Platform/Library/Common/Utilities/ICBO.cs b/DNN Platform/Library/Common/Utilities/ICBO.cs index 312bba40d5f..043ded5ea9a 100644 --- a/DNN Platform/Library/Common/Utilities/ICBO.cs +++ b/DNN Platform/Library/Common/Utilities/ICBO.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Data; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System.Collections.Generic; + using System.Data; + public interface ICBO { - List FillCollection(IDataReader dr) where TObject : new(); - - TObject FillObject(IDataReader dr) where TObject : new(); + List FillCollection(IDataReader dr) + where TObject : new(); - //SortedList FillSortedList(string keyField, IDataReader dr); + TObject FillObject(IDataReader dr) + where TObject : new(); + // SortedList FillSortedList(string keyField, IDataReader dr); TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary); } } diff --git a/DNN Platform/Library/Common/Utilities/IJavaScriptUtils.cs b/DNN Platform/Library/Common/Utilities/IJavaScriptUtils.cs index c0acb240517..d66b33322bf 100644 --- a/DNN Platform/Library/Common/Utilities/IJavaScriptUtils.cs +++ b/DNN Platform/Library/Common/Utilities/IJavaScriptUtils.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Web.UI; + public interface IJavaScriptUtils { /// - /// Registers a javascript variable in a page with its value + /// Registers a javascript variable in a page with its value. /// - /// Variable name and also the name of the registered code - /// Object to be assigned to the variable - /// Page where the varialbe will be registered - /// Type + /// Variable name and also the name of the registered code. + /// Object to be assigned to the variable. + /// Page where the varialbe will be registered. + /// Type. void RegisterJavascriptVariable(string variableName, object value, Page page, Type type); } } diff --git a/DNN Platform/Library/Common/Utilities/IPathUtils.cs b/DNN Platform/Library/Common/Utilities/IPathUtils.cs index 811dff16107..1d4928ddac3 100644 --- a/DNN Platform/Library/Common/Utilities/IPathUtils.cs +++ b/DNN Platform/Library/Common/Utilities/IPathUtils.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + + using DotNetNuke.Entities.Users; + public interface IPathUtils { /// @@ -26,17 +26,20 @@ public interface IPathUtils /// /// Gets the physical path for the specified relative path. - /// + /// + /// string GetPhysicalPath(int portalID, string relativePath); /// /// Gets the relative path for the specified physical path. - /// + ///
    + /// string GetRelativePath(int portalID, string physicalPath); /// - /// Gets the physical root folder path for the specified portal - /// + /// Gets the physical root folder path for the specified portal. + ///
    + /// string GetRootFolderMapPath(int portalID); /// @@ -58,13 +61,13 @@ public interface IPathUtils /// /// The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server. /// - /// Specifies the relative or virtual path to map to a physical directory. If Path starts with either - /// a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path. If Path - /// doesn't start with a slash, the MapPath method returns a path relative to the directory of the .asp file being processed + /// Specifies the relative or virtual path to map to a physical directory. If Path starts with either + /// a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path. If Path + /// doesn't start with a slash, the MapPath method returns a path relative to the directory of the .asp file being processed. /// /// - /// If path is a null reference (Nothing in Visual Basic), then the MapPath method returns the full physical path - /// of the directory that contains the current application + /// If path is a null reference (Nothing in Visual Basic), then the MapPath method returns the full physical path + /// of the directory that contains the current application. /// string MapPath(string path); diff --git a/DNN Platform/Library/Common/Utilities/ImageUtils.cs b/DNN Platform/Library/Common/Utilities/ImageUtils.cs index 8b89575f97d..c6b346988c2 100644 --- a/DNN Platform/Library/Common/Utilities/ImageUtils.cs +++ b/DNN Platform/Library/Common/Utilities/ImageUtils.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.IO; - -using DotNetNuke.Services.FileSystem.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Imaging; + using System.IO; + + using DotNetNuke.Services.FileSystem.Internal; + public class ImageUtils { public static Size GetSize(string sPath) @@ -23,9 +23,9 @@ public static Size GetSize(string sPath) } /// - /// return height of image + /// return height of image. /// - /// file path of image + /// file path of image. /// public static int GetHeight(string sPath) { @@ -36,9 +36,9 @@ public static int GetHeight(string sPath) } /// - /// return width of image + /// return width of image. /// - /// file path of image + /// file path of image. /// public static int GetWidth(string sPath) { @@ -49,22 +49,22 @@ public static int GetWidth(string sPath) } /// - /// return height of image + /// return height of image. /// - /// Stream of image + /// Stream of image. /// public static int GetHeightFromStream(Stream sFile) { Image g = Image.FromStream(sFile, true); - int h = g.Height; + int h = g.Height; g.Dispose(); return h; } /// - /// width of image + /// width of image. /// - /// Steam of image + /// Steam of image. /// public static int GetWidthFromStream(Stream sFile) { @@ -75,9 +75,9 @@ public static int GetWidthFromStream(Stream sFile) } /// - /// create an image + /// create an image. /// - /// path of load image file - will be resized according to height and width set + /// path of load image file - will be resized according to height and width set. /// public static string CreateImage(string sFile) { @@ -89,11 +89,11 @@ public static string CreateImage(string sFile) } /// - /// create an image + /// create an image. /// - /// path of image file - /// height - /// width + /// path of image file. + /// height. + /// width. /// public static string CreateImage(string sFile, int intHeight, int intWidth) { @@ -108,7 +108,7 @@ public static string CreateImage(string sFile, int intHeight, int intWidth) File.Copy(sFile, tmp); using (var fileContent = File.OpenRead(tmp)) - using(var content = CreateImage(fileContent, intHeight, intWidth, fi.Extension)) + using (var content = CreateImage(fileContent, intHeight, intWidth, fi.Extension)) { string sFileExt = fi.Extension; string sFileNoExtension = Path.GetFileNameWithoutExtension(sFile); @@ -142,14 +142,13 @@ public static string CreateImage(string sFile, int intHeight, int intWidth) } } } - + if (FileWrapper.Instance.Exists(tmp)) { FileWrapper.Instance.SetAttributes(tmp, FileAttributes.Normal); FileWrapper.Instance.Delete(tmp); } - - + return sFile; } @@ -179,8 +178,16 @@ public static Stream CreateImage(Stream stream, int intHeight, int intWidth, str imgWidth = original.Width; } - if (imgWidth < 1) imgWidth = 1; - if (imgHeight < 1) imgHeight = 1; + if (imgWidth < 1) + { + imgWidth = 1; + } + + if (imgHeight < 1) + { + imgHeight = 1; + } + imgSize = new Size(imgWidth, imgHeight); using (var newImg = new Bitmap(imgWidth, imgHeight, format)) @@ -201,7 +208,7 @@ public static Stream CreateImage(Stream stream, int intHeight, int intWidth, str canvas.DrawImage(original, 0, 0, imgSize.Width, imgSize.Height); - //newImg.Save + // newImg.Save ImageFormat imgFormat = ImageFormat.Bmp; if (extension.Equals(".png", StringComparison.InvariantCultureIgnoreCase)) { @@ -225,11 +232,11 @@ public static Stream CreateImage(Stream stream, int intHeight, int intWidth, str } /// - /// create a JPG image + /// create a JPG image. /// - /// name of image - /// bitmap of image - /// image quality + /// name of image. + /// bitmap of image. + /// image quality. /// public static string CreateJPG(string sFile, Bitmap img, int compressionLevel) { @@ -249,34 +256,34 @@ public static string CreateJPG(string sFile, Bitmap img, int compressionLevel) { File.Delete(sFile); } + try { img.Save(sFile, myImageCodecInfo, myEncoderParameters); } catch (Exception) { - //suppress unexpected exceptions + // suppress unexpected exceptions } - - + img.Dispose(); bmpOutput.Dispose(); return sFile; } /// - /// create an image based on a stream (read from a database) + /// create an image based on a stream (read from a database). /// - /// image name - /// height - /// width - /// steam + /// image name. + /// height. + /// width. + /// steam. public static MemoryStream CreateImageForDB(Stream sFile, int intHeight, int intWidth) { var newStream = new MemoryStream(); Image g = Image.FromStream(sFile); int imgHeight, imgWidth; - + if (intHeight > 0 & intWidth > 0) { int newHeight = intHeight; @@ -318,9 +325,9 @@ public static MemoryStream CreateImageForDB(Stream sFile, int intHeight, int int } /// - /// return the approriate encoded for the mime-type of the image being created + /// return the approriate encoded for the mime-type of the image being created. /// - /// mime type (e.g jpg/png) + /// mime type (e.g jpg/png). /// public static ImageCodecInfo GetEncoderInfo(string myMimeType) { @@ -330,11 +337,12 @@ public static ImageCodecInfo GetEncoderInfo(string myMimeType) ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); for (i = 0; i <= (encoders.Length - 1); i++) { - if ((encoders[i].MimeType == myMimeType)) + if (encoders[i].MimeType == myMimeType) { return encoders[i]; } } + return null; } catch @@ -344,13 +352,13 @@ public static ImageCodecInfo GetEncoderInfo(string myMimeType) } /// - /// scale an image based on existing dimensions and updated requirement + /// scale an image based on existing dimensions and updated requirement. /// - /// current width - /// current height - /// new width - /// new height - /// updated calculated height/width minesions + /// current width. + /// current height. + /// new width. + /// new height. + /// updated calculated height/width minesions. public static Size NewImageSize(int currentWidth, int currentHeight, int newWidth, int newHeight) { decimal decScale = ((decimal)currentWidth / (decimal)newWidth) > ((decimal)currentHeight / (decimal)newHeight) ? Convert.ToDecimal((decimal)currentWidth / (decimal)newWidth) : Convert.ToDecimal((decimal)currentHeight / (decimal)newHeight); diff --git a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs index 59509c77aa8..d2cf665ac6e 100644 --- a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs +++ b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System; -using System.Text; -using System.Web; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Text; +using System.Web; public class JavaScriptObjectDictionary : IEnumerable> { @@ -17,28 +17,19 @@ internal OrderedDictionary Dictionary { get { - return _dictionary ?? (_dictionary = new OrderedDictionary()); + return this._dictionary ?? (this._dictionary = new OrderedDictionary()); } } - public void AddMethodBody(string name, string methodBody) - { - AddMethod(name, "function() { " + methodBody + "; }"); - } - - public void AddMethod(string name, string method) - { - Dictionary[name] = method; - } - - private static string ToJsonString(IEnumerable> methods) + public static string ToJavaScriptArrayString(IEnumerable> methods) { if (methods == null) { return "null"; } + var builder = new StringBuilder(); - builder.Append('{'); + builder.Append('['); var isFirstPair = true; foreach (var keyValuePair in methods) { @@ -50,32 +41,26 @@ private static string ToJsonString(IEnumerable> met { builder.Append(','); } - builder.Append('"'); - builder.Append(HttpUtility.JavaScriptStringEncode(keyValuePair.Key)); - builder.Append('"'); - builder.Append(':'); + var methodValue = string.IsNullOrEmpty(keyValuePair.Value) ? "null" : keyValuePair.Value; builder.Append(methodValue); } - builder.Append('}'); + + builder.Append(']'); return builder.ToString(); } - public string ToJsonString() - { - return ToJsonString(this); - } - - public static string ToJavaScriptArrayString(IEnumerable> methods) + public static string ToJavaScriptArrayString(IEnumerable methods) { if (methods == null) { return "null"; } + var builder = new StringBuilder(); builder.Append('['); var isFirstPair = true; - foreach (var keyValuePair in methods) + foreach (var method in methods) { if (isFirstPair) { @@ -85,23 +70,41 @@ public static string ToJavaScriptArrayString(IEnumerable methods) + public void AddMethodBody(string name, string methodBody) + { + this.AddMethod(name, "function() { " + methodBody + "; }"); + } + + public void AddMethod(string name, string method) + { + this.Dictionary[name] = method; + } + + public string ToJsonString() + { + return ToJsonString(this); + } + + private static string ToJsonString(IEnumerable> methods) { if (methods == null) { return "null"; } + var builder = new StringBuilder(); - builder.Append('['); + builder.Append('{'); var isFirstPair = true; - foreach (var method in methods) + foreach (var keyValuePair in methods) { if (isFirstPair) { @@ -111,10 +114,16 @@ public static string ToJavaScriptArrayString(IEnumerable methods) { builder.Append(','); } - var methodValue = string.IsNullOrEmpty(method) ? "null" : method; + + builder.Append('"'); + builder.Append(HttpUtility.JavaScriptStringEncode(keyValuePair.Key)); + builder.Append('"'); + builder.Append(':'); + var methodValue = string.IsNullOrEmpty(keyValuePair.Value) ? "null" : keyValuePair.Value; builder.Append(methodValue); } - builder.Append(']'); + + builder.Append('}'); return builder.ToString(); } @@ -125,24 +134,25 @@ public string ToJavaScriptArrayString() public IEnumerator> GetEnumerator() { - var enumerator = Dictionary.GetEnumerator(); + var enumerator = this.Dictionary.GetEnumerator(); while (enumerator.MoveNext()) { yield return new KeyValuePair(enumerator.Key.ToString(), enumerator.Value.ToString()); } } - - private IEnumerator GetEnumeratorPrivate() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() { - return GetEnumeratorPrivate(); + return this.GetEnumeratorPrivate(); } public override string ToString() { - return _dictionary == null ? string.Empty : _dictionary.ToString(); + return this._dictionary == null ? string.Empty : this._dictionary.ToString(); + } + + private IEnumerator GetEnumeratorPrivate() + { + return this.GetEnumerator(); } } diff --git a/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs b/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs index c4e8e5f27ef..6d06f06784b 100644 --- a/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs +++ b/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { - public class JavaScriptUtils: ServiceLocator, IJavaScriptUtils + using System; + using System.Web.UI; + + using DotNetNuke.Framework; + + public class JavaScriptUtils : ServiceLocator, IJavaScriptUtils { public void RegisterJavascriptVariable(string variableName, object value, Page page, Type type) { diff --git a/DNN Platform/Library/Common/Utilities/Json.cs b/DNN Platform/Library/Common/Utilities/Json.cs index ff70da22a6f..04cacd61086 100644 --- a/DNN Platform/Library/Common/Utilities/Json.cs +++ b/DNN Platform/Library/Common/Utilities/Json.cs @@ -1,21 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Runtime.Serialization.Json; -using System.Text; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.IO; + using System.Runtime.Serialization.Json; + using System.Text; + + using Newtonsoft.Json; + /// - /// Serialize or Deserialize Json + /// Serialize or Deserialize Json. /// public static class Json { @@ -26,7 +22,7 @@ public static T Deserialize(string json) public static string Serialize(T obj) { - return JsonConvert.SerializeObject(obj); + return JsonConvert.SerializeObject(obj); } } } diff --git a/DNN Platform/Library/Common/Utilities/JsonExtensions.cs b/DNN Platform/Library/Common/Utilities/JsonExtensions.cs index d0c9bf75594..d1467856504 100644 --- a/DNN Platform/Library/Common/Utilities/JsonExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/JsonExtensions.cs @@ -1,29 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.Script.Serialization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Web.Script.Serialization; + /// - /// Json Extensions based on the JavaScript Serializer in System.web + /// Json Extensions based on the JavaScript Serializer in System.web. /// public static class JsonExtensionsWeb { - private static JavaScriptSerializer SerializerFactory() - { - // Allow large JSON strings to be serialized and deserialized. - return new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue}; - } - /// - /// Serializes a type to Json. Note the type must be marked Serializable + /// Serializes a type to Json. Note the type must be marked Serializable /// or include a DataContract attribute. /// /// @@ -36,7 +25,7 @@ public static string ToJsonString(object value) } /// - /// Extension method on object that serializes the value to Json. + /// Extension method on object that serializes the value to Json. /// Note the type must be marked Serializable or include a DataContract attribute. /// /// @@ -45,9 +34,15 @@ public static string ToJson(this object value) { return ToJsonString(value); } + + private static JavaScriptSerializer SerializerFactory() + { + // Allow large JSON strings to be serialized and deserialized. + return new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; + } /// - /// Deserializes a json string into a specific type. + /// Deserializes a json string into a specific type. /// Note that the type specified must be serializable. /// /// @@ -55,16 +50,16 @@ public static string ToJson(this object value) /// public static object FromJsonString(string json, Type type) { - // *** Have to use Reflection with a 'dynamic' non constant type instance + // *** Have to use Reflection with a 'dynamic' non constant type instance var ser = SerializerFactory(); - object result = ser.GetType().GetMethod("Deserialize").MakeGenericMethod(type).Invoke(ser, new object[1] {json}); + object result = ser.GetType().GetMethod("Deserialize").MakeGenericMethod(type).Invoke(ser, new object[1] { json }); return result; } /// - /// Extension method to string that deserializes a json string - /// into a specific type. + /// Extension method to string that deserializes a json string + /// into a specific type. /// Note that the type specified must be serializable. /// /// diff --git a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs index 6ee9cbf010b..b4fca6b7458 100644 --- a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs +++ b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs @@ -1,21 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utils { + using System; + using System.Linq; + using System.Net; + using System.Net.Sockets; + using System.Web; + /// - /// Utility functions for network information + /// Enumration of IP AddressTyes. + /// + public enum AddressType + { + IPv4, + IPv6, + } + + /// + /// Utility functions for network information. /// public class NetworkUtils { @@ -24,7 +28,7 @@ public class NetworkUtils /// /// The host. /// The address format. - /// Returns IP address + /// Returns IP address. /// public static string GetAddress(string Host, AddressType AddressFormat) { @@ -38,11 +42,13 @@ public static string GetAddress(string Host, AddressType AddressFormat) addrFamily = AddressFamily.InterNetworkV6; break; } + IPHostEntry IPE = Dns.GetHostEntry(Host); if (Host != IPE.HostName) { IPE = Dns.GetHostEntry(IPE.HostName); } + foreach (IPAddress IPA in IPE.AddressList) { if (IPA.AddressFamily == addrFamily) @@ -50,76 +56,72 @@ public static string GetAddress(string Host, AddressType AddressFormat) return IPA.ToString(); } } + return string.Empty; } + /// - /// Convert IP address to long integer + /// Convert IP address to long integer. /// - /// The ip address - /// IP Address in long + /// The ip address. + /// IP Address in long. public static long IPtoLong(IPAddress ip) { - //convert IP to number - + // convert IP to number byte[] addressBytes = ip.GetAddressBytes(); - //get the octets + + // get the octets long addr = 0; - //accumulator for address - + + // accumulator for address for (int x = 0; x <= 3; x++) { - addr = addr | (Convert.ToInt64(addressBytes[x]) << (3 - x) * 8); + addr = addr | (Convert.ToInt64(addressBytes[x]) << ((3 - x) * 8)); } + return addr; } /// /// Longs to ip address. /// - /// The ip address - /// IP Number as formatted string + /// The ip address. + /// IP Number as formatted string. public static string LongToIp(long ip) { - //convert number back to IP - + // convert number back to IP var ipByte = new byte[4]; - //4 octets - string addr = ""; - //accumulator for address - + + // 4 octets + string addr = string.Empty; + + // accumulator for address long mask8 = MaskFromCidr(8); - //create eight bit mask + + // create eight bit mask - //get the octets + // get the octets for (int x = 0; x <= 3; x++) { ipByte[x] = Convert.ToByte((ip & mask8) >> ((3 - x) * 8)); mask8 = mask8 >> 8; addr += ipByte[x].ToString() + "."; - //add current octet to string + + // add current octet to string } + return addr.TrimEnd('.'); } - /// - /// Masks from cidr. - /// - /// The Classless Inter-Domain Routing (cidr) - /// - private static long MaskFromCidr(int cidr) - { - return Convert.ToInt64(Math.Pow(2, ((32 - cidr))) - 1) ^ 4294967295L; - } - /// /// Formats as cidr. /// /// The start ip. /// The subnet mask. - /// Classless Inter-Domain Routing + /// Classless Inter-Domain Routing. public static string FormatAsCidr(string startIP, string subnetMask) { - if (String.IsNullOrEmpty(subnetMask)) + if (string.IsNullOrEmpty(subnetMask)) { return startIP; } @@ -130,16 +132,21 @@ public static string FormatAsCidr(string startIP, string subnetMask) long ipL = IPtoLong(ipAddress); long maskL = IPtoLong(mask); - //Convert Mask to CIDR(1-30) + // Convert Mask to CIDR(1-30) long oneBit = 0x80000000L; int cidr = 0; for (int x = 31; x >= 0; x += -1) { - if ((maskL & oneBit) == oneBit) - cidr += 1; - else - break; + if ((maskL & oneBit) == oneBit) + { + cidr += 1; + } + else + { + break; + } + oneBit = oneBit >> 1; } @@ -181,17 +188,27 @@ public static void Network2IpRange(string sNetwork, out uint startIP, out uint e } catch (Exception) { - //catch case where IP cannot be resolved such as when debugger is attached + // catch case where IP cannot be resolved such as when debugger is attached startIP = 0; endIP = 0; } } /// - /// Convert IP to Integer + /// Masks from cidr. + /// + /// The Classless Inter-Domain Routing (cidr). + /// + private static long MaskFromCidr(int cidr) + { + return Convert.ToInt64(Math.Pow(2, 32 - cidr) - 1) ^ 4294967295L; + } + + /// + /// Convert IP to Integer. /// /// The ip number. - /// IP number as integer + /// IP number as integer. public static uint IP2Int(string ipNumber) { uint ip = 0; @@ -203,6 +220,7 @@ public static uint IP2Int(string ipNumber) ip += Convert.ToUInt32(elements[2]) << 8; ip += Convert.ToUInt32(elements[3]); } + return ip; } @@ -212,21 +230,27 @@ public static uint IP2Int(string ipNumber) /// The current ip. /// The start ip. /// The subnetmask. - /// True or False + /// True or False. public static bool IsIPInRange(string currentIP, string startIP, string subnetmask) { try { - //handle case where local adapter is localhost - if (currentIP=="::1") + // handle case where local adapter is localhost + if (currentIP == "::1") { currentIP = "127.0.0.1"; } - //handle case where we are matching on a single IP - if (String.IsNullOrEmpty(subnetmask)) if (currentIP == startIP) return true; - - //handle case where we have to build a CIDR, convert to an IP range and compare + // handle case where we are matching on a single IP + if (string.IsNullOrEmpty(subnetmask)) + { + if (currentIP == startIP) + { + return true; + } + } + + // handle case where we have to build a CIDR, convert to an IP range and compare string cidr = FormatAsCidr(startIP, subnetmask); uint fromIP, toIP; Network2IpRange(cidr, out fromIP, out toIP); @@ -239,9 +263,10 @@ public static bool IsIPInRange(string currentIP, string startIP, string subnetma } catch (Exception) { - //catch case where IP cannot be resolved such as when debugger is attached + // catch case where IP cannot be resolved such as when debugger is attached return false; } + return false; } @@ -263,15 +288,4 @@ public static string GetClientIpAddress(HttpRequest request) return ipAddress; } } - - /// - /// Enumration of IP AddressTyes - /// - public enum AddressType - { - IPv4, - IPv6 - } - - } diff --git a/DNN Platform/Library/Common/Utilities/Null.cs b/DNN Platform/Library/Common/Utilities/Null.cs index 27977fc1d9e..32c952fdf3b 100644 --- a/DNN Platform/Library/Common/Utilities/Null.cs +++ b/DNN Platform/Library/Common/Utilities/Null.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Reflection; + public class Null { public static short NullShort @@ -73,7 +68,7 @@ public static string NullString { get { - return ""; + return string.Empty; } } @@ -93,7 +88,7 @@ public static Guid NullGuid } } - //sets a field to an application encoded null value ( used in BLL layer ) + // sets a field to an application encoded null value ( used in BLL layer ) public static object SetNull(object objValue, object objField) { object returnValue = null; @@ -139,19 +134,20 @@ public static object SetNull(object objValue, object objField) { returnValue = NullGuid; } - else //complex object + else // complex object { returnValue = null; } } - else //return value + else // return value { returnValue = objValue; } + return returnValue; } - //sets a field to an application encoded null value ( used in BLL layer ) + // sets a field to an application encoded null value ( used in BLL layer ) public static object SetNull(PropertyInfo objPropertyInfo) { object returnValue = null; @@ -190,20 +186,22 @@ public static object SetNull(PropertyInfo objPropertyInfo) returnValue = NullGuid; break; default: - //Enumerations default to the first entry + // Enumerations default to the first entry Type pType = objPropertyInfo.PropertyType; - if (pType.BaseType.Equals(typeof (Enum))) + if (pType.BaseType.Equals(typeof(Enum))) { Array objEnumValues = Enum.GetValues(pType); Array.Sort(objEnumValues); returnValue = Enum.ToObject(pType, objEnumValues.GetValue(0)); } - else //complex object + else // complex object { returnValue = null; } + break; } + return returnValue; } @@ -238,10 +236,11 @@ public static Guid SetNullGuid(object objValue) { return new Guid(objValue.ToString()); } + return Guid.Empty; } - //convert an application encoded null value to a database null value ( used in DAL ) + // convert an application encoded null value to a database null value ( used in DAL ) public static object GetNull(object objField, object objDBNull) { object returnValue = objField; @@ -293,7 +292,7 @@ public static object GetNull(object objField, object objDBNull) } else if (objField is DateTime) { - //compare the Date part of the DateTime with the DatePart of the NullDate ( this avoids subtle time differences ) + // compare the Date part of the DateTime with the DatePart of the NullDate ( this avoids subtle time differences ) if (Convert.ToDateTime(objField).Date == NullDate.Date) { returnValue = objDBNull; @@ -322,15 +321,16 @@ public static object GetNull(object objField, object objDBNull) } else if (objField is Guid) { - if (((Guid) objField).Equals(NullGuid)) + if (((Guid)objField).Equals(NullGuid)) { returnValue = objDBNull; } } + return returnValue; } - //checks if a field contains an application encoded null value + // checks if a field contains an application encoded null value public static bool IsNull(object objField) { bool isNull = false; @@ -362,7 +362,7 @@ public static bool IsNull(object objField) } else if (objField is DateTime) { - var objDate = (DateTime) objField; + var objDate = (DateTime)objField; isNull = objDate.Date.Equals(NullDate.Date); } else if (objField is string) @@ -377,7 +377,7 @@ public static bool IsNull(object objField) { isNull = objField.Equals(NullGuid); } - else //complex object + else // complex object { isNull = false; } @@ -386,6 +386,7 @@ public static bool IsNull(object objField) { isNull = true; } + return isNull; } } diff --git a/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs b/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs index 67da97a6cd9..e8a48c76ff7 100644 --- a/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs +++ b/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections.Generic; + using System.Reflection; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Common.Utilities @@ -36,22 +31,23 @@ public class ObjectMappingInfo private int _CacheTimeOutMultiplier; private string _ObjectType; private string _PrimaryKey; - private string _TableName; - - ///----------------------------------------------------------------------------- - /// - /// Constructs a new ObjectMappingInfo Object + private string _TableName; + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new ObjectMappingInfo Object. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ObjectMappingInfo() { - _Properties = new Dictionary(); - _ColumnNames = new Dictionary(); + this._Properties = new Dictionary(); + this._ColumnNames = new Dictionary(); } /// ----------------------------------------------------------------------------- /// - /// CacheKey gets the root value of the key used to identify the cached collection + /// Gets cacheKey gets the root value of the key used to identify the cached collection /// in the ASP.NET Cache. /// /// ----------------------------------------------------------------------------- @@ -59,19 +55,20 @@ public string CacheKey { get { - string _CacheKey = RootCacheKey + TableName + "_"; - if (!string.IsNullOrEmpty(CacheByProperty)) + string _CacheKey = RootCacheKey + this.TableName + "_"; + if (!string.IsNullOrEmpty(this.CacheByProperty)) { - _CacheKey += CacheByProperty + "_"; + _CacheKey += this.CacheByProperty + "_"; } + return _CacheKey; } } /// ----------------------------------------------------------------------------- /// - /// CacheByProperty gets and sets the property that is used to cache collections - /// of the object. For example: Modules are cached by the "TabId" proeprty. Tabs + /// Gets or sets cacheByProperty gets and sets the property that is used to cache collections + /// of the object. For example: Modules are cached by the "TabId" proeprty. Tabs /// are cached by the PortalId property. /// /// If empty, a collection of all the instances of the object is cached. @@ -80,17 +77,18 @@ public string CacheByProperty { get { - return _CacheByProperty; + return this._CacheByProperty; } + set { - _CacheByProperty = value; + this._CacheByProperty = value; } } /// ----------------------------------------------------------------------------- /// - /// CacheTimeOutMultiplier gets and sets the multiplier used to determine how long + /// Gets or sets cacheTimeOutMultiplier gets and sets the multiplier used to determine how long /// the cached collection should be cached. It is multiplied by the Performance /// Setting - which in turn can be modified by the Host Account. /// @@ -100,78 +98,81 @@ public int CacheTimeOutMultiplier { get { - return _CacheTimeOutMultiplier; + return this._CacheTimeOutMultiplier; } + set { - _CacheTimeOutMultiplier = value; + this._CacheTimeOutMultiplier = value; } } /// ----------------------------------------------------------------------------- /// - /// ColumnNames gets a dictionary of Database Column Names for the Object + /// Gets columnNames gets a dictionary of Database Column Names for the Object. /// /// ----------------------------------------------------------------------------- public Dictionary ColumnNames { get { - return _ColumnNames; + return this._ColumnNames; } } /// ----------------------------------------------------------------------------- /// - /// ObjectType gets and sets the type of the object + /// Gets or sets objectType gets and sets the type of the object. /// /// ----------------------------------------------------------------------------- public string ObjectType { get { - return _ObjectType; + return this._ObjectType; } + set { - _ObjectType = value; + this._ObjectType = value; } } /// ----------------------------------------------------------------------------- /// - /// PrimaryKey gets and sets the property of the object that corresponds to the - /// primary key in the database + /// Gets or sets primaryKey gets and sets the property of the object that corresponds to the + /// primary key in the database. /// /// ----------------------------------------------------------------------------- public string PrimaryKey { get { - return _PrimaryKey; + return this._PrimaryKey; } + set { - _PrimaryKey = value; + this._PrimaryKey = value; } } /// ----------------------------------------------------------------------------- /// - /// Properties gets a dictionary of Properties for the Object + /// Gets properties gets a dictionary of Properties for the Object. /// /// ----------------------------------------------------------------------------- public Dictionary Properties { get { - return _Properties; + return this._Properties; } } /// ----------------------------------------------------------------------------- /// - /// TableName gets and sets the name of the database table that is used to + /// Gets or sets tableName gets and sets the name of the database table that is used to /// persist the object. /// /// ----------------------------------------------------------------------------- @@ -179,11 +180,12 @@ public string TableName { get { - return _TableName; + return this._TableName; } + set { - _TableName = value; + this._TableName = value; } } } diff --git a/DNN Platform/Library/Common/Utilities/PathUtils.cs b/DNN Platform/Library/Common/Utilities/PathUtils.cs index 056a74f685d..f7ae64f0b32 100644 --- a/DNN Platform/Library/Common/Utilities/PathUtils.cs +++ b/DNN Platform/Library/Common/Utilities/PathUtils.cs @@ -1,44 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.IO; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Globalization; + using System.IO; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + public class PathUtils : ComponentBase, IPathUtils { - private static readonly Regex FolderPathRx = new Regex("^0\\\\", RegexOptions.Compiled); - - #region Constructor - + private static readonly Regex FolderPathRx = new Regex("^0\\\\", RegexOptions.Compiled); + internal PathUtils() { - } - - #endregion - - #region Public Enums - + } + public enum UserFolderElement { Root = 0, - SubFolder = 1 - } - - #endregion - - #region Public Methods - + SubFolder = 1, + } + /// /// Adds backslash to the specified source. /// @@ -58,24 +48,25 @@ public virtual string AddTrailingSlash(string source) /// The formatted path. public virtual string FormatFolderPath(string folderPath) { - //Can not call trim on folderpath since folder passed in might have a legit space - //at the begingin of its name " MyFolder/Test" is not same physical folder as "MyFoler/Test" - if (String.IsNullOrEmpty(folderPath) || String.IsNullOrEmpty(folderPath.Trim())) + // Can not call trim on folderpath since folder passed in might have a legit space + // at the begingin of its name " MyFolder/Test" is not same physical folder as "MyFoler/Test" + if (string.IsNullOrEmpty(folderPath) || string.IsNullOrEmpty(folderPath.Trim())) { - return ""; + return string.Empty; } - return folderPath.EndsWith("/") ? folderPath.Trim() : folderPath.Trim() + "/"; + return folderPath.EndsWith("/") ? folderPath.Trim() : folderPath.Trim() + "/"; } /// /// Gets the physical path for the specified relative path. - /// + /// + /// public virtual string GetPhysicalPath(int portalID, string relativePath) { Requires.PropertyNotNull("relativePath", relativePath); - var path1 = GetRootFolderMapPath(portalID); + var path1 = this.GetRootFolderMapPath(portalID); var path2 = relativePath.Replace("/", "\\"); if (Path.IsPathRooted(path2)) @@ -85,12 +76,13 @@ public virtual string GetPhysicalPath(int portalID, string relativePath) var physicalPath = Path.Combine(path1, path2); - return RemoveTrailingSlash(physicalPath); + return this.RemoveTrailingSlash(physicalPath); } /// /// Gets the relative path for the specified physical path. - /// + ///
    + /// public virtual string GetRelativePath(int portalID, string physicalPath) { Requires.PropertyNotNull("physicalPath", physicalPath); @@ -100,7 +92,7 @@ public virtual string GetRelativePath(int portalID, string physicalPath) throw new ArgumentException("The argument 'physicalPath' is not a valid path. " + physicalPath); } - var rootFolderMapPath = RemoveTrailingSlash(GetRootFolderMapPath(portalID)); + var rootFolderMapPath = this.RemoveTrailingSlash(this.GetRootFolderMapPath(portalID)); string relativePath; @@ -120,12 +112,13 @@ public virtual string GetRelativePath(int portalID, string physicalPath) throw new ArgumentException("The argument 'physicalPath' is not a valid path."); } - return FormatFolderPath(relativePath); + return this.FormatFolderPath(relativePath); } /// - /// Gets the physical root folder path for the specified portal - /// + /// Gets the physical root folder path for the specified portal. + ///
    + /// public virtual string GetRootFolderMapPath(int portalID) { return (portalID == Null.NullInteger) ? GetHostMapPath() : GetPortalMapPath(portalID); @@ -140,7 +133,7 @@ public virtual string GetUserFolderPath(UserInfo user) { return FolderManager.Instance.GetUserFolder(user).FolderPath; } - + /// /// Get elements from the user folder path. /// @@ -149,36 +142,7 @@ public virtual string GetUserFolderPath(UserInfo user) /// The element from the user folder path. public virtual string GetUserFolderPathElement(int userID, UserFolderElement mode) { - return GetUserFolderPathElementInternal(userID, mode); - } - - internal string GetUserFolderPathElementInternal(int userId, UserFolderElement mode) - { - const int subfolderSeedLength = 2; - const int byteOffset = 255; - var element = ""; - - switch (mode) - { - case UserFolderElement.Root: - element = (Convert.ToInt32(userId) & byteOffset).ToString("000"); - break; - case UserFolderElement.SubFolder: - element = userId.ToString("00").Substring(userId.ToString("00").Length - subfolderSeedLength, subfolderSeedLength); - break; - } - - return element; - } - - internal string GetUserFolderPathInternal(UserInfo user) - { - var rootFolder = GetUserFolderPathElementInternal(user.UserID, UserFolderElement.Root); - var subFolder = GetUserFolderPathElementInternal(user.UserID, UserFolderElement.SubFolder); - - var fullPath = Path.Combine(Path.Combine(rootFolder, subFolder), user.UserID.ToString(CultureInfo.InvariantCulture)); - - return String.Format("Users/{0}/", fullPath.Replace("\\", "/")); + return this.GetUserFolderPathElementInternal(userID, mode); } /// @@ -188,7 +152,7 @@ internal string GetUserFolderPathInternal(UserInfo user) /// True if the folderPath is a default protected folder. False otherwise. public virtual bool IsDefaultProtectedPath(string folderPath) { - return String.IsNullOrEmpty(folderPath) || + return string.IsNullOrEmpty(folderPath) || folderPath.Equals("skins", StringComparison.InvariantCultureIgnoreCase) || folderPath.Equals("containers", StringComparison.InvariantCultureIgnoreCase) || folderPath.StartsWith("skins/", StringComparison.InvariantCultureIgnoreCase) || @@ -198,13 +162,13 @@ public virtual bool IsDefaultProtectedPath(string folderPath) /// /// The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server. /// - /// Specifies the relative or virtual path to map to a physical directory. If Path starts with either - /// a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path. If Path - /// doesn't start with a slash, the MapPath method returns a path relative to the directory of the .asp file being processed + /// Specifies the relative or virtual path to map to a physical directory. If Path starts with either + /// a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path. If Path + /// doesn't start with a slash, the MapPath method returns a path relative to the directory of the .asp file being processed. /// /// - /// If path is a null reference (Nothing in Visual Basic), then the MapPath method returns the full physical path - /// of the directory that contains the current application + /// If path is a null reference (Nothing in Visual Basic), then the MapPath method returns the full physical path + /// of the directory that contains the current application. /// public virtual string MapPath(string path) { @@ -224,7 +188,7 @@ public virtual string MapPath(string path) if (path.StartsWith("~") | path.StartsWith(".") | path.StartsWith("/")) { - convertedPath = convertedPath.Length > 1 ? string.Concat(AddTrailingSlash(applicationMapPath), convertedPath.Substring(1)) : applicationMapPath; + convertedPath = convertedPath.Length > 1 ? string.Concat(this.AddTrailingSlash(applicationMapPath), convertedPath.Substring(1)) : applicationMapPath; } convertedPath = Path.GetFullPath(convertedPath); @@ -237,6 +201,35 @@ public virtual string MapPath(string path) return convertedPath; } + internal string GetUserFolderPathElementInternal(int userId, UserFolderElement mode) + { + const int subfolderSeedLength = 2; + const int byteOffset = 255; + var element = string.Empty; + + switch (mode) + { + case UserFolderElement.Root: + element = (Convert.ToInt32(userId) & byteOffset).ToString("000"); + break; + case UserFolderElement.SubFolder: + element = userId.ToString("00").Substring(userId.ToString("00").Length - subfolderSeedLength, subfolderSeedLength); + break; + } + + return element; + } + + internal string GetUserFolderPathInternal(UserInfo user) + { + var rootFolder = this.GetUserFolderPathElementInternal(user.UserID, UserFolderElement.Root); + var subFolder = this.GetUserFolderPathElementInternal(user.UserID, UserFolderElement.SubFolder); + + var fullPath = Path.Combine(Path.Combine(rootFolder, subFolder), user.UserID.ToString(CultureInfo.InvariantCulture)); + + return string.Format("Users/{0}/", fullPath.Replace("\\", "/")); + } + /// /// Removes the trailing slash or backslash from the specified source. /// @@ -244,9 +237,9 @@ public virtual string MapPath(string path) /// The original string minus the trailing slash. public virtual string RemoveTrailingSlash(string source) { - if (String.IsNullOrEmpty(source)) + if (string.IsNullOrEmpty(source)) { - return ""; + return string.Empty; } if (source.EndsWith("\\") || source.EndsWith("/")) @@ -268,16 +261,12 @@ public virtual string StripFolderPath(string originalPath) if (originalPath.IndexOf("\\", StringComparison.InvariantCulture) >= 0) { - return FolderPathRx.Replace(originalPath, ""); + return FolderPathRx.Replace(originalPath, string.Empty); } return originalPath.StartsWith("0") ? originalPath.Substring(1) : originalPath; - } - - #endregion - - #region Private Methods - + } + private static string GetHostMapPath() { return Globals.HostMapPath; @@ -287,8 +276,6 @@ private static string GetPortalMapPath(int portalId) { var portalInfo = PortalController.Instance.GetPortal(portalId); return portalInfo.HomeDirectoryMapPath; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Common/Utilities/RegexUtils.cs b/DNN Platform/Library/Common/Utilities/RegexUtils.cs index 408c75a57a6..d959686910d 100644 --- a/DNN Platform/Library/Common/Utilities/RegexUtils.cs +++ b/DNN Platform/Library/Common/Utilities/RegexUtils.cs @@ -1,19 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text.RegularExpressions; -using System.Web.Caching; -using DotNetNuke.Services.Cache; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Text.RegularExpressions; + using System.Web.Caching; + + using DotNetNuke.Services.Cache; + public class RegexUtils { /// - /// Creates and caches a Regex object for later use and retrieves it in a later call if it is cacehd - /// + /// Creates and caches a Regex object for later use and retrieves it in a later call if it is cacehd. + /// + /// public static Regex GetCachedRegex(string pattern, RegexOptions options = RegexOptions.None, int timeoutSeconds = 2) { Requires.NotNull("pattern", pattern); @@ -30,9 +32,15 @@ public static Regex GetCachedRegex(string pattern, RegexOptions options = RegexO key = string.Join(":", "REGEX_ITEM", options.ToString("X"), key.GetHashCode().ToString("X")); // limit timeout between 1 and 10 seconds - if (timeoutSeconds < 1) timeoutSeconds = 1; - else if (timeoutSeconds > 10) timeoutSeconds = 10; - + if (timeoutSeconds < 1) + { + timeoutSeconds = 1; + } + else if (timeoutSeconds > 10) + { + timeoutSeconds = 10; + } + var cache = CachingProvider.Instance(); var regex = cache.GetItem(key) as Regex; if (regex == null) diff --git a/DNN Platform/Library/Common/Utilities/RetryableAction.cs b/DNN Platform/Library/Common/Utilities/RetryableAction.cs index 12b22ea7cb9..9b233cf7b3b 100644 --- a/DNN Platform/Library/Common/Utilities/RetryableAction.cs +++ b/DNN Platform/Library/Common/Utilities/RetryableAction.cs @@ -1,44 +1,74 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Threading; - -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities.Internal { + using System; + using System.Threading; + + using DotNetNuke.Instrumentation; + /// /// Allows an action to be run and retried after a delay when an exception is thrown. /// If the action never succeeds the final exception will be re-thrown for the caller to catch. /// public class RetryableAction { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (RetryableAction)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RetryableAction)); + + static RetryableAction() + { + SleepAction = GoToSleep; + } + + public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay) + : this(action, description, maxRetries, delay, 1) + { + } + + public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay, float delayMultiplier) + { + if (delay.TotalMilliseconds > int.MaxValue) + { + throw new ArgumentException(string.Format("delay must be less than {0} milliseconds", int.MaxValue)); + } + + this.Action = action; + this.Description = description; + this.MaxRetries = maxRetries; + this.Delay = delay; + this.DelayMultiplier = delayMultiplier; + } + + /// + /// Gets or sets method that allows thread to sleep until next retry meant for unit testing purposes. + /// + public static Action SleepAction { get; set; } + /// - /// The Action to execute + /// Gets or sets the Action to execute. /// public Action Action { get; set; } /// - /// A message describing the action. The primary purpose is to make the action identifiable in the log output. + /// Gets or sets a message describing the action. The primary purpose is to make the action identifiable in the log output. /// public string Description { get; set; } /// - /// The maximum number of retries to attempt + /// Gets or sets the maximum number of retries to attempt. /// public int MaxRetries { get; set; } /// - /// The number of milliseconds to wait between retries. + /// Gets or sets the number of milliseconds to wait between retries. /// The delay period is approximate and will be affected by the demands of other threads on the system. /// public TimeSpan Delay { get; set; } /// - /// A factor by which the delay is adjusted after each retry. Default is 1. + /// Gets or sets a factor by which the delay is adjusted after each retry. Default is 1. /// To double the delay with every retry use a factor of 2, retrys will be 1s, 2s, 4s, 8s... /// To quarter the delay with every retry use a factor of 0.25, retrys will be 1s, 0.25, 0.0625, 0.015625s... /// @@ -54,71 +84,53 @@ public static void Retry5TimesWith2SecondsDelay(Action action, string descriptio new RetryableAction(action, description, 5, TimeSpan.FromSeconds(2)).TryIt(); } - /// - /// Method that allows thread to sleep until next retry meant for unit testing purposes - /// - public static Action SleepAction { get; set; } - - static RetryableAction() - { - SleepAction = GoToSleep; - } - - private static void GoToSleep(int delay) - { - Thread.Sleep(delay); - } - - public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay) : this(action, description, maxRetries, delay, 1) {} - - public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay, float delayMultiplier) - { - if(delay.TotalMilliseconds > int.MaxValue) - { - throw new ArgumentException(string.Format("delay must be less than {0} milliseconds", int.MaxValue)); - } - - Action = action; - Description = description; - MaxRetries = maxRetries; - Delay = delay; - DelayMultiplier = delayMultiplier; - } - public void TryIt() { - var currentDelay = (int) Delay.TotalMilliseconds; - int retrysRemaining = MaxRetries; + var currentDelay = (int)this.Delay.TotalMilliseconds; + int retrysRemaining = this.MaxRetries; do { try { - Action(); - if (Logger.IsTraceEnabled) - Logger.TraceFormat("Action succeeded - {0}", Description); + this.Action(); + if (Logger.IsTraceEnabled) + { + Logger.TraceFormat("Action succeeded - {0}", this.Description); + } + return; } - catch(Exception) + catch (Exception) { if (retrysRemaining <= 0) { - Logger.WarnFormat("All retries of action failed - {0}", Description); + Logger.WarnFormat("All retries of action failed - {0}", this.Description); throw; } - if (Logger.IsTraceEnabled) - Logger.TraceFormat("Retrying action {0} - {1}", retrysRemaining, Description); + if (Logger.IsTraceEnabled) + { + Logger.TraceFormat("Retrying action {0} - {1}", retrysRemaining, this.Description); + } + SleepAction.Invoke(currentDelay); const double epsilon = 0.0001; - if(Math.Abs(DelayMultiplier - 1) > epsilon) + if (Math.Abs(this.DelayMultiplier - 1) > epsilon) { - currentDelay = (int)(currentDelay * DelayMultiplier); + currentDelay = (int)(currentDelay * this.DelayMultiplier); } } + retrysRemaining--; - } while (true); + } + while (true); + } + + private static void GoToSleep(int delay) + { + Thread.Sleep(delay); } } } diff --git a/DNN Platform/Library/Common/Utilities/SessionVariable.cs b/DNN Platform/Library/Common/Utilities/SessionVariable.cs index a56818c056b..ccf4c57a7d4 100644 --- a/DNN Platform/Library/Common/Utilities/SessionVariable.cs +++ b/DNN Platform/Library/Common/Utilities/SessionVariable.cs @@ -1,38 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.SessionState; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { - + using System; + using System.Web; + using System.Web.SessionState; + /// - /// Wrapper class for + /// Wrapper class for . /// - /// The type of the value to be stored + /// The type of the value to be stored. public class SessionVariable : StateVariable - { - - /// - /// Initializes a new HttpContext.Session item variable + { + /// + /// Initializes a new instance of the class. + /// Initializes a new HttpContext.Session item variable. /// /// - /// The key to use for storing the value in the items + /// The key to use for storing the value in the items. /// - public SessionVariable(string key) : base(key) + public SessionVariable(string key) + : base(key) { - } - - /// - /// Initializes a new HttpContext.Session item variable with a initializer + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new HttpContext.Session item variable with a initializer. /// - /// The key to use for storing the value in the HttpContext.Current.Session - /// A function that is called in order to create a default value per HttpContext.Current.Session + /// The key to use for storing the value in the HttpContext.Current.Session. + /// A function that is called in order to create a default value per HttpContext.Current.Session. /// - public SessionVariable(string key, Func initializer) : base(key, initializer) + public SessionVariable(string key, Func initializer) + : base(key, initializer) { } @@ -45,11 +47,13 @@ private static HttpSessionState CurrentItems { throw new InvalidOperationException("No HttpContext is not available."); } + var items = current.Session; if (items == null) { throw new InvalidOperationException("No Session State available on current HttpContext."); } + return items; } } @@ -60,6 +64,7 @@ protected override object this[string key] { return CurrentItems[key]; } + set { CurrentItems[key] = value; @@ -70,7 +75,5 @@ protected override void Remove(string key) { CurrentItems.Remove(key); } - } - } diff --git a/DNN Platform/Library/Common/Utilities/SizeExtensions.cs b/DNN Platform/Library/Common/Utilities/SizeExtensions.cs index de9336cd96f..e2982f64d00 100644 --- a/DNN Platform/Library/Common/Utilities/SizeExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/SizeExtensions.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { - + using System.Drawing; + using System.Web.UI.WebControls; + public static class SizeExtensions { public static Orientation Orientation(this Size size) diff --git a/DNN Platform/Library/Common/Utilities/SqlUtils.cs b/DNN Platform/Library/Common/Utilities/SqlUtils.cs index 902621e88cc..89f351d369d 100644 --- a/DNN Platform/Library/Common/Utilities/SqlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/SqlUtils.cs @@ -1,33 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Data.SqlClient; -using System.Text; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System.Data.SqlClient; + using System.Text; + /// ----------------------------------------------------------------------------- /// - /// The SqlUtils class provides Shared/Static methods for working with SQL Server related code + /// The SqlUtils class provides Shared/Static methods for working with SQL Server related code. /// /// /// /// ----------------------------------------------------------------------------- public class SqlUtils - { - #region "Public Methods" - - #endregion - + { /// - /// function to translate sql exceptions to readable messages. + /// function to translate sql exceptions to readable messages. /// It also captures cases where sql server is not available and guards against - /// database connection details being leaked + /// database connection details being leaked. /// /// /// @@ -63,6 +54,7 @@ public static string TranslateSQLException(SqlException exc) errorMessages.Append("Index #: " + i + "
    " + "Source: " + sqlError.Source + "
    " + "Class: " + sqlError.Class + "
    " + "Number: " + sqlError.Number + "
    " + "Procedure: " + sqlError.Procedure + "
    " + "Message: " + filteredMessage + "
    "); } + return errorMessages.ToString(); } } diff --git a/DNN Platform/Library/Common/Utilities/StateVariable.cs b/DNN Platform/Library/Common/Utilities/StateVariable.cs index b62f27f0ba0..8293595fddc 100644 --- a/DNN Platform/Library/Common/Utilities/StateVariable.cs +++ b/DNN Platform/Library/Common/Utilities/StateVariable.cs @@ -1,12 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { - + using System; + /// /// Wrapper class for any object that maps string key onto the object value (like Dictionary). /// @@ -14,15 +13,15 @@ namespace DotNetNuke.Common.Utilities /// public abstract class StateVariable { - private readonly string _key; - private readonly Func _initializer; - - /// - /// Initializes a new item variable + private readonly Func _initializer; + + /// + /// Initializes a new instance of the class. + /// Initializes a new item variable. /// /// - /// The key to use for storing the value in the items + /// The key to use for storing the value in the items. /// protected StateVariable(string key) { @@ -30,109 +29,115 @@ protected StateVariable(string key) { throw new ArgumentNullException("key"); } - _key = key + GetType().FullName; - } - - /// - /// Initializes a new item variable with a initializer + + this._key = key + this.GetType().FullName; + } + + /// + /// Initializes a new instance of the class. + /// Initializes a new item variable with a initializer. /// - /// The key to use for storing the value in the dictionary - /// A function that is called in order to create a default value per dictionary + /// The key to use for storing the value in the dictionary. + /// A function that is called in order to create a default value per dictionary. /// - protected StateVariable(string key, Func initializer) : this(key) + protected StateVariable(string key, Func initializer) + : this(key) { if (initializer == null) { throw new ArgumentNullException("initializer"); } + this._initializer = initializer; } - private object GetInitializedInternalValue() - { - var value = this[_key]; - if (value == null && _initializer != null) - { - value = _initializer(); - this[_key] = value; - } - return value; - } - - /// - /// Get/sets the value in associated dictionary/map - /// - /// Value key - /// - /// - /// - protected abstract object this[string key] { get; set; } - - /// - /// Removes the value in associated dictionary according - /// - /// Value key - /// - protected abstract void Remove(string key); - /// - /// Indicates wether there is a value present or not + /// Gets a value indicating whether indicates wether there is a value present or not. /// public bool HasValue { get { - return this[_key] != null; + return this[this._key] != null; } } /// - /// Sets or gets the value in the current items + /// Gets or sets or gets the value in the current items. /// /// - /// If you try to get a value while none is set use for safe access + /// If you try to get a value while none is set use for safe access. /// public T Value { get { - var returnedValue = GetInitializedInternalValue(); + var returnedValue = this.GetInitializedInternalValue(); if (returnedValue == null) { - throw new InvalidOperationException("There is no value for the '" + _key + "' key."); + throw new InvalidOperationException("There is no value for the '" + this._key + "' key."); } + return (T)returnedValue; } + set { - this[_key] = value; + this[this._key] = value; } } /// - /// Gets the value in the current items or if none is available default(T) + /// Gets the value in the current items or if none is available default(T). /// public T ValueOrDefault { get { - var returnedValue = GetInitializedInternalValue(); + var returnedValue = this.GetInitializedInternalValue(); if (returnedValue == null) { return default(T); } + return (T)returnedValue; } } /// - /// Clears the value in the current items + /// Get/sets the value in associated dictionary/map. /// - public void Clear() + /// Value key. + /// + /// + /// + protected abstract object this[string key] { get; set; } + + /// + /// Removes the value in associated dictionary according. + /// + /// Value key. + /// + protected abstract void Remove(string key); + + private object GetInitializedInternalValue() { - Remove(_key); + var value = this[this._key]; + if (value == null && this._initializer != null) + { + value = this._initializer(); + this[this._key] = value; + } + + return value; } + /// + /// Clears the value in the current items. + /// + public void Clear() + { + this.Remove(this._key); + } } - } diff --git a/DNN Platform/Library/Common/Utilities/StringExtensions.cs b/DNN Platform/Library/Common/Utilities/StringExtensions.cs index 3ca8363d1cd..c6ed72e4040 100644 --- a/DNN Platform/Library/Common/Utilities/StringExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/StringExtensions.cs @@ -1,14 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Text; -using System.Text.RegularExpressions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System.Text; + using System.Text.RegularExpressions; + public static class StringExtensions { + private static readonly Encoding Iso8859Encoding = Encoding.GetEncoding("iso-8859-8"); + public static string TrimToLength(this string source, int maxLength) { return source == null || source.Length <= maxLength @@ -22,10 +24,12 @@ public static string Append(this string stringValue, string stringToLink, string { return stringToLink; } + if (string.IsNullOrEmpty(stringToLink)) { return stringValue; } + return stringValue + delimiter + stringToLink; } @@ -35,19 +39,19 @@ public static string ValueOrEmpty(this string stringValue) } /// - /// Takes a string and removes any diacritics + /// Takes a string and removes any diacritics. /// - /// String to normalize - /// String without diacritics - public static string NormalizeString(this string input) - { - return string.IsNullOrEmpty(input) + /// String to normalize. + /// String without diacritics. + public static string NormalizeString(this string input) + { + return string.IsNullOrEmpty(input) ? input : Iso8859Encoding.GetString(Encoding.Convert(Encoding.UTF8, Iso8859Encoding, Encoding.UTF8.GetBytes(input))).ToLowerInvariant(); - } + } /// - /// Alternative to that supports case insensitive replacement + /// Alternative to that supports case insensitive replacement. /// /// The source. /// The old value. @@ -59,10 +63,8 @@ public static string ReplaceIgnoreCase(this string source, string oldValue, stri { return source; } + return Regex.Replace(source, Regex.Escape(oldValue), newValue, RegexOptions.IgnoreCase); } - - private static readonly Encoding Iso8859Encoding = Encoding.GetEncoding("iso-8859-8"); } - } diff --git a/DNN Platform/Library/Common/Utilities/UrlController.cs b/DNN Platform/Library/Common/Utilities/UrlController.cs index f669752eacf..1d1d61517f3 100644 --- a/DNN Platform/Library/Common/Utilities/UrlController.cs +++ b/DNN Platform/Library/Common/Utilities/UrlController.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; - -using DotNetNuke.Data; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + using System.IO; + + using DotNetNuke.Data; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + public class UrlController { public ArrayList GetUrls(int PortalID) { - return CBO.FillCollection(DataProvider.Instance().GetUrls(PortalID), typeof (UrlInfo)); + return CBO.FillCollection(DataProvider.Instance().GetUrls(PortalID), typeof(UrlInfo)); } public UrlInfo GetUrl(int PortalID, string Url) @@ -38,21 +33,22 @@ public UrlTrackingInfo GetUrlTracking(int PortalID, string Url, int ModuleId) public void UpdateUrl(int PortalID, string Url, string UrlType, bool LogActivity, bool TrackClicks, int ModuleID, bool NewWindow) { - UpdateUrl(PortalID, Url, UrlType, 0, Null.NullDate, Null.NullDate, LogActivity, TrackClicks, ModuleID, NewWindow); + this.UpdateUrl(PortalID, Url, UrlType, 0, Null.NullDate, Null.NullDate, LogActivity, TrackClicks, ModuleID, NewWindow); } public void UpdateUrl(int PortalID, string Url, string UrlType, int Clicks, DateTime LastClick, DateTime CreatedDate, bool LogActivity, bool TrackClicks, int ModuleID, bool NewWindow) { - if (!String.IsNullOrEmpty(Url)) + if (!string.IsNullOrEmpty(Url)) { if (UrlType == "U") { - if (GetUrl(PortalID, Url) == null) + if (this.GetUrl(PortalID, Url) == null) { DataProvider.Instance().AddUrl(PortalID, Url.Replace(@"\", @"/")); } } - UrlTrackingInfo objURLTracking = GetUrlTracking(PortalID, Url, ModuleID); + + UrlTrackingInfo objURLTracking = this.GetUrlTracking(PortalID, Url, ModuleID); if (objURLTracking == null) { DataProvider.Instance().AddUrlTracking(PortalID, Url, UrlType, LogActivity, TrackClicks, ModuleID, NewWindow); @@ -74,7 +70,7 @@ public void UpdateUrlTracking(int PortalID, string Url, int ModuleId, int UserID TabType UrlType = Globals.GetURLType(Url); if (UrlType == TabType.File && Url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false) { - //to handle legacy scenarios before the introduction of the FileServerHandler + // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(Url); var folderPath = Url.Substring(0, Url.LastIndexOf(fileName)); @@ -84,7 +80,8 @@ public void UpdateUrlTracking(int PortalID, string Url, int ModuleId, int UserID Url = "FileID=" + file.FileId; } - UrlTrackingInfo objUrlTracking = GetUrlTracking(PortalID, Url, ModuleId); + + UrlTrackingInfo objUrlTracking = this.GetUrlTracking(PortalID, Url, ModuleId); if (objUrlTracking != null) { if (objUrlTracking.TrackClicks) @@ -96,6 +93,7 @@ public void UpdateUrlTracking(int PortalID, string Url, int ModuleId, int UserID { UserID = UserController.Instance.GetCurrentUserInfo().UserID; } + DataProvider.Instance().AddUrlLog(objUrlTracking.UrlTrackingID, UserID); } } @@ -105,11 +103,12 @@ public void UpdateUrlTracking(int PortalID, string Url, int ModuleId, int UserID public ArrayList GetUrlLog(int PortalID, string Url, int ModuleId, DateTime StartDate, DateTime EndDate) { ArrayList arrUrlLog = null; - UrlTrackingInfo objUrlTracking = GetUrlTracking(PortalID, Url, ModuleId); + UrlTrackingInfo objUrlTracking = this.GetUrlTracking(PortalID, Url, ModuleId); if (objUrlTracking != null) { - arrUrlLog = CBO.FillCollection(DataProvider.Instance().GetUrlLog(objUrlTracking.UrlTrackingID, StartDate, EndDate), typeof (UrlLogInfo)); + arrUrlLog = CBO.FillCollection(DataProvider.Instance().GetUrlLog(objUrlTracking.UrlTrackingID, StartDate, EndDate), typeof(UrlLogInfo)); } + return arrUrlLog; } } diff --git a/DNN Platform/Library/Common/Utilities/UrlInfo.cs b/DNN Platform/Library/Common/Utilities/UrlInfo.cs index ec131bfc754..8c7e6082bd7 100644 --- a/DNN Platform/Library/Common/Utilities/UrlInfo.cs +++ b/DNN Platform/Library/Common/Utilities/UrlInfo.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { public class UrlInfo diff --git a/DNN Platform/Library/Common/Utilities/UrlLogInfo.cs b/DNN Platform/Library/Common/Utilities/UrlLogInfo.cs index 7df13df26ae..6687a119a2e 100644 --- a/DNN Platform/Library/Common/Utilities/UrlLogInfo.cs +++ b/DNN Platform/Library/Common/Utilities/UrlLogInfo.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + public class UrlLogInfo { public int UrlLogID { get; set; } diff --git a/DNN Platform/Library/Common/Utilities/UrlTrackingInfo.cs b/DNN Platform/Library/Common/Utilities/UrlTrackingInfo.cs index 4289affd317..4c1e435b613 100644 --- a/DNN Platform/Library/Common/Utilities/UrlTrackingInfo.cs +++ b/DNN Platform/Library/Common/Utilities/UrlTrackingInfo.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + [Serializable] public class UrlTrackingInfo { diff --git a/DNN Platform/Library/Common/Utilities/UrlUtils.cs b/DNN Platform/Library/Common/Utilities/UrlUtils.cs index 109a3eaa735..48d117df5a8 100644 --- a/DNN Platform/Library/Common/Utilities/UrlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/UrlUtils.cs @@ -1,38 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security; -using DotNetNuke.UI; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Abstractions; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.UI; + using DotNetNuke.UI.Skins; + using Microsoft.Extensions.DependencyInjection; + public class UrlUtils { private static readonly INavigationManager _navigationManager = Globals.DependencyProvider.GetRequiredService(); public static string Combine(string baseUrl, string relativeUrl) { - if (baseUrl.Length == 0) - return relativeUrl; - if (relativeUrl.Length == 0) - return baseUrl; + if (baseUrl.Length == 0) + { + return relativeUrl; + } + + if (relativeUrl.Length == 0) + { + return baseUrl; + } + return string.Format("{0}/{1}", baseUrl.TrimEnd(new[] { '/', '\\' }), relativeUrl.TrimStart(new[] { '/', '\\' })); } @@ -51,7 +53,8 @@ public static string DecryptParameter(string value) public static string DecryptParameter(string value, string encryptionKey) { var objSecurity = PortalSecurity.Instance; - //[DNN-8257] - Can't do URLEncode/URLDecode as it introduces issues on decryption (with / = %2f), so we use a modifed Base64 + + // [DNN-8257] - Can't do URLEncode/URLDecode as it introduces issues on decryption (with / = %2f), so we use a modifed Base64 var toDecrypt = new StringBuilder(value); toDecrypt.Replace("_", "/"); toDecrypt.Replace("-", "+"); @@ -79,7 +82,7 @@ public static string EncryptParameter(string value, string encryptionKey) var objSecurity = PortalSecurity.Instance; var parameterValue = new StringBuilder(objSecurity.Encrypt(encryptionKey, value)); - //[DNN-8257] - Can't do URLEncode/URLDecode as it introduces issues on decryption (with / = %2f), so we use a modifed Base64 + // [DNN-8257] - Can't do URLEncode/URLDecode as it introduces issues on decryption (with / = %2f), so we use a modifed Base64 parameterValue.Replace("/", "_"); parameterValue.Replace("+", "-"); parameterValue.Replace("=", "%3d"); @@ -99,7 +102,8 @@ public static string GetParameterValue(string pair) { return nameValues[1]; } - return ""; + + return string.Empty; } /// @@ -107,11 +111,12 @@ public static string GetParameterValue(string pair) /// in order to prep for navigateUrl. /// we don't ever want a tabid, a ctl and a language parameter in the qs /// either, the portalid param is not allowed when the tab is a supertab - /// (because NavigateUrl adds the portalId param to the qs) - /// + /// (because NavigateUrl adds the portalId param to the qs). + /// + /// public static string[] GetQSParamsForNavigateURL() { - string returnValue = ""; + string returnValue = string.Empty; var coll = HttpContext.Current.Request.QueryString; string[] keys = coll.AllKeys; for (var i = 0; i <= keys.GetUpperBound(0); i++) @@ -123,53 +128,53 @@ public static string[] GetQSParamsForNavigateURL() case "tabid": case "ctl": case "language": - //skip parameter + // skip parameter break; default: - if ((keys[i].Equals("portalid", StringComparison.InvariantCultureIgnoreCase)) && Globals.GetPortalSettings().ActiveTab.IsSuperTab) + if (keys[i].Equals("portalid", StringComparison.InvariantCultureIgnoreCase) && Globals.GetPortalSettings().ActiveTab.IsSuperTab) { - //skip parameter - //navigateURL adds portalid to querystring if tab is superTab - + // skip parameter + // navigateURL adds portalid to querystring if tab is superTab } else { string[] values = coll.GetValues(i); for (int j = 0; j <= values.GetUpperBound(0); j++) { - if (!String.IsNullOrEmpty(returnValue)) + if (!string.IsNullOrEmpty(returnValue)) { returnValue += "&"; } + returnValue += keys[i] + "=" + values[j]; } } + break; } } } - //return the new querystring as a string array + + // return the new querystring as a string array return returnValue.Split('&'); - } /// /// check if connection is HTTPS - /// or is HTTP but with ssloffload enabled on a secure page + /// or is HTTP but with ssloffload enabled on a secure page. /// - /// current request - /// true if HTTPS or if HTTP with an SSL offload header value, false otherwise + /// current request. + /// true if HTTPS or if HTTP with an SSL offload header value, false otherwise. public static bool IsSecureConnectionOrSslOffload(HttpRequest request) { - var isSecureTab = PortalController.Instance.GetCurrentPortalSettings()?.ActiveTab.IsSecure ?? false; - return request.IsSecureConnection || (IsSslOffloadEnabled(request) && isSecureTab); + return request.IsSecureConnection || IsSslOffloadEnabled(request); } public static bool IsSslOffloadEnabled(HttpRequest request) { - var ssloffloadheader = HostController.Instance.GetString("SSLOffloadHeader", ""); + var ssloffloadheader = HostController.Instance.GetString("SSLOffloadHeader", string.Empty); - //if the ssloffloadheader variable has been set check to see if a request header with that type exists + // if the ssloffloadheader variable has been set check to see if a request header with that type exists if (!string.IsNullOrEmpty(ssloffloadheader)) { var ssloffloadValue = string.Empty; @@ -182,10 +187,11 @@ public static bool IsSslOffloadEnabled(HttpRequest request) string ssloffload = request.Headers[ssloffloadheader]; if (!string.IsNullOrEmpty(ssloffload) && (string.IsNullOrWhiteSpace(ssloffloadValue) || ssloffloadValue == ssloffload)) - { - return true; + { + return true; } } + return false; } @@ -211,40 +217,41 @@ public static string PopUpUrl(string url, PortalSettings portalSettings, bool on public static string PopUpUrl(string url, Control control, PortalSettings portalSettings, bool onClickEvent, bool responseRedirect, int windowHeight, int windowWidth, bool refresh, string closingUrl) { - if (UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request)) { url = url.Replace("http://", "https://"); } + var popUpUrl = url; - //ensure delimiters are not used - if (!popUpUrl.Contains("dnnModal.show")) - { - popUpUrl = Uri.EscapeUriString(url); - popUpUrl = popUpUrl.Replace("\"", ""); - popUpUrl = popUpUrl.Replace("'", ""); - } + + // ensure delimiters are not used + if (!popUpUrl.Contains("dnnModal.show")) + { + popUpUrl = Uri.EscapeUriString(url); + popUpUrl = popUpUrl.Replace("\"", string.Empty); + popUpUrl = popUpUrl.Replace("'", string.Empty); + } var delimiter = popUpUrl.Contains("?") ? "&" : "?"; - var popUpScriptFormat = String.Empty; + var popUpScriptFormat = string.Empty; - //create a the querystring for use on a Response.Redirect + // create a the querystring for use on a Response.Redirect if (responseRedirect) { popUpScriptFormat = "{0}{1}popUp=true"; - popUpUrl = String.Format(popUpScriptFormat, popUpUrl, delimiter); + popUpUrl = string.Format(popUpScriptFormat, popUpUrl, delimiter); } else { if (!popUpUrl.Contains("dnnModal.show")) { popUpScriptFormat = "dnnModal.show('{0}{1}popUp=true',/*showReturn*/{2},{3},{4},{5},'{6}')"; - closingUrl = (closingUrl != Null.NullString) ? closingUrl : String.Empty; - popUpUrl = "javascript:" + String.Format(popUpScriptFormat, popUpUrl, delimiter, onClickEvent.ToString().ToLowerInvariant(), windowHeight, windowWidth, refresh.ToString().ToLower(), closingUrl); + closingUrl = (closingUrl != Null.NullString) ? closingUrl : string.Empty; + popUpUrl = "javascript:" + string.Format(popUpScriptFormat, popUpUrl, delimiter, onClickEvent.ToString().ToLowerInvariant(), windowHeight, windowWidth, refresh.ToString().ToLower(), closingUrl); } else { - //Determines if the resulting JS call should return or not. + // Determines if the resulting JS call should return or not. if (popUpUrl.Contains("/*showReturn*/false")) { popUpUrl = popUpUrl.Replace("/*showReturn*/false", "/*showReturn*/" + onClickEvent.ToString().ToLowerInvariant()); @@ -257,19 +264,25 @@ public static string PopUpUrl(string url, Control control, PortalSettings portal } // Removes the javascript txt for onClick scripts - if (onClickEvent && popUpUrl.StartsWith("javascript:")) popUpUrl = popUpUrl.Replace("javascript:", ""); - + if (onClickEvent && popUpUrl.StartsWith("javascript:")) + { + popUpUrl = popUpUrl.Replace("javascript:", string.Empty); + } + return popUpUrl; } - public static string ClosePopUp(Boolean refresh, string url, bool onClickEvent) + public static string ClosePopUp(bool refresh, string url, bool onClickEvent) { var closePopUpStr = "dnnModal.closePopUp({0}, {1})"; closePopUpStr = "javascript:" + string.Format(closePopUpStr, refresh.ToString().ToLowerInvariant(), "'" + url + "'"); // Removes the javascript txt for onClick scripts) - if (onClickEvent && closePopUpStr.StartsWith("javascript:")) closePopUpStr = closePopUpStr.Replace("javascript:", ""); - + if (onClickEvent && closePopUpStr.StartsWith("javascript:")) + { + closePopUpStr = closePopUpStr.Replace("javascript:", string.Empty); + } + return closePopUpStr; } @@ -303,24 +316,24 @@ public static string ValidReturnUrl(string url) { if (string.IsNullOrEmpty(url)) { - //DNN-10193: returns the same value as passed in rather than empty string + // DNN-10193: returns the same value as passed in rather than empty string return url; } url = url.Replace("\\", "/"); if (url.ToLowerInvariant().Contains("data:")) { - return ""; + return string.Empty; } - //clean the return url to avoid possible XSS attack. + // clean the return url to avoid possible XSS attack. var cleanUrl = PortalSecurity.Instance.InputFilter(url, PortalSecurity.FilterFlag.NoScripting); if (url != cleanUrl) { - return ""; + return string.Empty; } - //redirect url should never contain a protocol ( if it does, it is likely a cross-site request forgery attempt ) + // redirect url should never contain a protocol ( if it does, it is likely a cross-site request forgery attempt ) var urlWithNoQuery = url; if (urlWithNoQuery.Contains("?")) { @@ -337,13 +350,13 @@ public static string ValidReturnUrl(string url) // protocol switching (HTTP <=> HTTPS) is allowed by not being checked here if (!string.Equals(uri1.DnsSafeHost, uri2.DnsSafeHost, StringComparison.CurrentCultureIgnoreCase)) { - return ""; + return string.Empty; } // this check is mainly for child portals if (!uri1.AbsolutePath.StartsWith(uri2.AbsolutePath, StringComparison.InvariantCultureIgnoreCase)) { - return ""; + return string.Empty; } } @@ -356,10 +369,11 @@ public static string ValidReturnUrl(string url) { var urlWithNoProtocol = url.Substring(2); var portalSettings = PortalSettings.Current; + // note: this can redirict from parent to childe and vice versa if (!urlWithNoProtocol.StartsWith(portalSettings.PortalAlias.HTTPAlias + "/", StringComparison.InvariantCultureIgnoreCase)) { - return ""; + return string.Empty; } } @@ -367,11 +381,11 @@ public static string ValidReturnUrl(string url) } catch (UriFormatException) { - return ""; + return string.Empty; } } - //Whether current page is show in popup. + // Whether current page is show in popup. public static bool InPopUp() { return HttpContext.Current != null && HttpContext.Current.Request.Url.ToString().IndexOf("popUp=true", StringComparison.OrdinalIgnoreCase) >= 0; @@ -379,7 +393,7 @@ public static bool InPopUp() public static bool IsPopUp(string url) { - return url .IndexOf("popUp=true", StringComparison.OrdinalIgnoreCase) >= 0; + return url.IndexOf("popUp=true", StringComparison.OrdinalIgnoreCase) >= 0; } /// diff --git a/DNN Platform/Library/Common/Utilities/ValidationUtils.cs b/DNN Platform/Library/Common/Utilities/ValidationUtils.cs index 4ecb629d733..956d8294068 100644 --- a/DNN Platform/Library/Common/Utilities/ValidationUtils.cs +++ b/DNN Platform/Library/Common/Utilities/ValidationUtils.cs @@ -1,19 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DotNetNuke.Entities.Host; -using DotNetNuke.Security; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + using DotNetNuke.Entities.Host; + using DotNetNuke.Security; + public sealed class ValidationUtils { internal static string GetDecryptionKey() { var machineKey = Config.GetDecryptionkey(); - var key = $"{machineKey ?? ""}{Host.GUID.Replace("-", string.Empty)}"; + var key = $"{machineKey ?? string.Empty}{Host.GUID.Replace("-", string.Empty)}"; return FIPSCompliant.EncryptAES(key, key, Host.GUID); } diff --git a/DNN Platform/Library/Common/Utilities/XmlExtensions.cs b/DNN Platform/Library/Common/Utilities/XmlExtensions.cs index e9d74f05d22..9619c41e3ba 100644 --- a/DNN Platform/Library/Common/Utilities/XmlExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/XmlExtensions.cs @@ -1,22 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using System.Xml.Serialization; -using System.Xml.XPath; -using System.Xml.Xsl; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Xml; + using System.Xml.Serialization; + using System.Xml.XPath; + using System.Xml.Xsl; + /// - /// The XmlExtensions class allows you to write more efficient code to manage Xml documents + /// The XmlExtensions class allows you to write more efficient code to manage Xml documents. /// public static class XmlExtensions { @@ -27,7 +24,7 @@ public static class XmlExtensions /// Name of the element. /// The element value. /// - /// The added element + /// The added element. /// public static XmlNode AddElement(this XmlNode node, string elementName, string elementValue) { @@ -42,7 +39,7 @@ public static XmlNode AddElement(this XmlNode node, string elementName, string e /// The element value. /// if set to true use a CData encapsulation. /// - /// The added element + /// The added element. /// public static XmlNode AddElement(this XmlNode node, string elementName, string elementValue, bool useCData) { @@ -56,6 +53,7 @@ public static XmlNode AddElement(this XmlNode node, string elementName, string e { newElement.InnerText = elementValue; } + node.AppendChild(newElement); return newElement; } @@ -70,7 +68,7 @@ public static XmlNode AddElement(this XmlNode node, string elementName, string e /// The namespace URI. /// The namespace abbreviation. /// - /// The added node + /// The added node. /// public static XmlNode AddElement(this XmlNode node, string elementName, string elementValue, bool useCData, string namespaceUri, string namespaceAbbr) { @@ -84,6 +82,7 @@ public static XmlNode AddElement(this XmlNode node, string elementName, string e { newElement.InnerText = elementValue; } + node.AppendChild(newElement); return newElement; } @@ -94,7 +93,7 @@ public static XmlNode AddElement(this XmlNode node, string elementName, string e /// The node to add the attribute to. /// Name of the attribute. /// The attribute value. - /// The node the attribute was added to + /// The node the attribute was added to. public static XmlNode AddAttribute(this XmlNode node, string attributeName, string attributeValue) { XmlAttribute newAttribute = node.OwnerDocument.CreateAttribute(attributeName); @@ -111,7 +110,7 @@ public static XmlNode AddAttribute(this XmlNode node, string attributeName, stri /// The attribute value. /// The namespace URI. /// The namespace abbreviation. - /// The node the attribute was added to + /// The node the attribute was added to. public static XmlNode AddAttribute(this XmlNode node, string attributeName, string attributeValue, string namespaceUri, string namespaceAbbr) { XmlAttribute newAttribute = node.OwnerDocument.CreateAttribute(namespaceAbbr + ":" + attributeName, namespaceUri); diff --git a/DNN Platform/Library/Common/Utilities/XmlUtils.cs b/DNN Platform/Library/Common/Utilities/XmlUtils.cs index f083c6f4547..5836ed3247e 100644 --- a/DNN Platform/Library/Common/Utilities/XmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/XmlUtils.cs @@ -1,40 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Net; -using System.Text; -using System.Xml; -using System.Xml.Serialization; -using System.Xml.XPath; -using System.Xml.Xsl; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Net; + using System.Text; + using System.Xml; + using System.Xml.Serialization; + using System.Xml.XPath; + using System.Xml.Xsl; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + /// ----------------------------------------------------------------------------- /// - /// The XmlUtils class provides Shared/Static methods for manipulating xml files + /// The XmlUtils class provides Shared/Static methods for manipulating xml files. /// /// /// /// ----------------------------------------------------------------------------- public class XmlUtils { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (XmlUtils)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(XmlUtils)); + public static void AppendElement(ref XmlDocument objDoc, XmlNode objNode, string attName, string attValue, bool includeIfEmpty) { AppendElement(ref objDoc, objNode, attName, attValue, includeIfEmpty, false); @@ -42,10 +38,11 @@ public static void AppendElement(ref XmlDocument objDoc, XmlNode objNode, string public static void AppendElement(ref XmlDocument objDoc, XmlNode objNode, string attName, string attValue, bool includeIfEmpty, bool cdata) { - if (String.IsNullOrEmpty(attValue) && !includeIfEmpty) + if (string.IsNullOrEmpty(attValue) && !includeIfEmpty) { return; } + if (cdata) { objNode.AppendChild(CreateCDataElement(objDoc, attName, attValue)); @@ -93,24 +90,28 @@ public static object Deserialize(Stream objStream, Type type) obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } + var moduleDic = obj as Dictionary; if (moduleDic != null) { obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } + var tabPermDic = obj as Dictionary; if (tabPermDic != null) { obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } + var modPermDic = obj as Dictionary; if (modPermDic != null) { obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } + var serializer = new XmlSerializer(type); using (TextReader tr = new StreamReader(objStream)) { @@ -133,28 +134,29 @@ public static Dictionary DeSerializeDictionary(Stream objSt var objValue = Activator.CreateInstance(); - //Create the XmlSerializer + // Create the XmlSerializer var xser = new XmlSerializer(objValue.GetType()); - //A reader is needed to read the XML document. + // A reader is needed to read the XML document. var reader = new XmlTextReader(new StringReader(xmlItem.InnerXml)) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; - //Use the Deserialize method to restore the object's state, and store it - //in the Hashtable + // Use the Deserialize method to restore the object's state, and store it + // in the Hashtable objDictionary.Add(key, (TValue)xser.Deserialize(reader)); } + return objDictionary; } public static Hashtable DeSerializeHashtable(string xmlSource, string rootname) { - var hashTable = new Hashtable(); + var hashTable = new Hashtable(); - if (!String.IsNullOrEmpty(xmlSource)) + if (!string.IsNullOrEmpty(xmlSource)) { try { @@ -166,24 +168,24 @@ public static Hashtable DeSerializeHashtable(string xmlSource, string rootname) string key = xmlItem.GetAttribute("key"); string typeName = xmlItem.GetAttribute("type"); - //Create the XmlSerializer + // Create the XmlSerializer var xser = new XmlSerializer(Type.GetType(typeName)); - //A reader is needed to read the XML document. + // A reader is needed to read the XML document. var reader = new XmlTextReader(new StringReader(xmlItem.InnerXml)) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; - //Use the Deserialize method to restore the object's state, and store it - //in the Hashtable + // Use the Deserialize method to restore the object's state, and store it + // in the Hashtable hashTable.Add(key, xser.Deserialize(reader)); } } catch (Exception) { - //Logger.Error(ex); /*Ignore Log because if failed on profile this will log on every request.*/ + // Logger.Error(ex); /*Ignore Log because if failed on profile this will log on every request.*/ } } @@ -192,15 +194,15 @@ public static Hashtable DeSerializeHashtable(string xmlSource, string rootname) /// ----------------------------------------------------------------------------- /// - /// Gets the value of an attribute + /// Gets the value of an attribute. /// - /// Parent XPathNavigator - /// Thename of the Attribute + /// Parent XPathNavigator. + /// Thename of the Attribute. /// /// ----------------------------------------------------------------------------- public static string GetAttributeValue(XPathNavigator nav, string attributeName) { - return nav.GetAttribute(attributeName, ""); + return nav.GetAttribute(attributeName, string.Empty); } public static bool GetAttributeValueAsBoolean(XPathNavigator navigator, string attributeName, bool defaultValue) @@ -211,6 +213,7 @@ public static bool GetAttributeValueAsBoolean(XPathNavigator navigator, string a { boolValue = Convert.ToBoolean(strValue); } + return boolValue; } @@ -222,6 +225,7 @@ public static int GetAttributeValueAsInteger(XPathNavigator navigator, string at { intValue = Convert.ToInt32(strValue); } + return intValue; } @@ -238,20 +242,20 @@ public static long GetAttributeValueAsLong(XPathNavigator navigator, string attr return intValue; } - /// Gets the value of a child node as a - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// The value of the node or if the node doesn't exist or doesn't have a value + /// Gets the value of a child node as a . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// The value of the node or if the node doesn't exist or doesn't have a value. public static string GetNodeValue(XPathNavigator navigator, string path) { return GetNodeValue(navigator, path, string.Empty); } - /// Gets the value of a child node as a - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// Default value to return if the node doesn't exist or doesn't have a value - /// The value of the node or + /// Gets the value of a child node as a . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// Default value to return if the node doesn't exist or doesn't have a value. + /// The value of the node or . public static string GetNodeValue(XPathNavigator navigator, string path, string defaultValue) { var childNodeNavigator = navigator.SelectSingleNode(path); @@ -268,30 +272,29 @@ public static string GetNodeValue(XPathNavigator navigator, string path, string return strValue; } - - + /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for + /// Parent node. + /// Child node to look for. /// /// /// If the node does not exist or it causes any error the default value will be returned. /// public static string GetNodeValue(XmlNode objNode, string nodeName) { - return GetNodeValue(objNode, nodeName, String.Empty); + return GetNodeValue(objNode, nodeName, string.Empty); } - + /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for - /// Default value to return + /// Parent node. + /// Child node to look for. + /// Default value to return. /// /// /// If the node does not exist or it causes any error the default value will be returned. @@ -300,23 +303,24 @@ public static string GetNodeValue(XmlNode objNode, string nodeName) public static string GetNodeValue(XmlNode objNode, string nodeName, string defaultValue) { string strValue = defaultValue; - if ((objNode[nodeName] != null)) + if (objNode[nodeName] != null) { strValue = objNode[nodeName].InnerText; - if (String.IsNullOrEmpty(strValue) && !String.IsNullOrEmpty(defaultValue)) + if (string.IsNullOrEmpty(strValue) && !string.IsNullOrEmpty(defaultValue)) { strValue = defaultValue; } } + return strValue; } /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for + /// Parent node. + /// Child node to look for. /// /// /// If the node does not exist or it causes any error the default value (False) will be returned. @@ -329,11 +333,11 @@ public static bool GetNodeValueBoolean(XmlNode objNode, string nodeName) /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for - /// Default value to return + /// Parent node. + /// Child node to look for. + /// Default value to return. /// /// /// If the node does not exist or it causes any error the default value will be returned. @@ -342,7 +346,7 @@ public static bool GetNodeValueBoolean(XmlNode objNode, string nodeName) public static bool GetNodeValueBoolean(XmlNode objNode, string nodeName, bool defaultValue) { bool bValue = defaultValue; - if ((objNode[nodeName] != null)) + if (objNode[nodeName] != null) { string strValue = objNode[nodeName].InnerText; if (!string.IsNullOrEmpty(strValue)) @@ -350,23 +354,24 @@ public static bool GetNodeValueBoolean(XmlNode objNode, string nodeName, bool de bValue = Convert.ToBoolean(strValue); } } + return bValue; } - /// Gets the value of a child node as a - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// The value of the node or false if the node doesn't exist or doesn't have a value + /// Gets the value of a child node as a . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// The value of the node or false if the node doesn't exist or doesn't have a value. public static bool GetNodeValueBoolean(XPathNavigator navigator, string path) { return GetNodeValueBoolean(navigator, path, false); } - /// Gets the value of a child node as a - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// Default value to return if the node doesn't exist or doesn't have a value - /// The value of the node or + /// Gets the value of a child node as a . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// Default value to return if the node doesn't exist or doesn't have a value. + /// The value of the node or . public static bool GetNodeValueBoolean(XPathNavigator navigator, string path, bool defaultValue) { var childNodeNavigator = navigator.SelectSingleNode(path); @@ -386,11 +391,11 @@ public static bool GetNodeValueBoolean(XPathNavigator navigator, string path, bo /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for - /// Default value to return + /// Parent node. + /// Child node to look for. + /// Default value to return. /// /// /// If the node does not exist or it causes any error the default value will be returned. @@ -399,7 +404,7 @@ public static bool GetNodeValueBoolean(XPathNavigator navigator, string path, bo public static DateTime GetNodeValueDate(XmlNode objNode, string nodeName, DateTime defaultValue) { DateTime dateValue = defaultValue; - if ((objNode[nodeName] != null)) + if (objNode[nodeName] != null) { string strValue = objNode[nodeName].InnerText; if (!string.IsNullOrEmpty(strValue)) @@ -411,14 +416,15 @@ public static DateTime GetNodeValueDate(XmlNode objNode, string nodeName, DateTi } } } + return dateValue; } - /// Gets the value of a child node as a - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// Default value to return if the node doesn't exist or doesn't have a value - /// The value of the node or + /// Gets the value of a child node as a . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// Default value to return if the node doesn't exist or doesn't have a value. + /// The value of the node or . public static DateTime GetNodeValueDate(XPathNavigator navigator, string path, DateTime defaultValue) { var childNodeNavigator = navigator.SelectSingleNode(path); @@ -444,10 +450,10 @@ public static DateTime GetNodeValueDate(XPathNavigator navigator, string path, D /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for + /// Parent node. + /// Child node to look for. /// /// /// If the node does not exist or it causes any error the default value (0) will be returned. @@ -460,11 +466,11 @@ public static int GetNodeValueInt(XmlNode node, string nodeName) /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for - /// Default value to return + /// Parent node. + /// Child node to look for. + /// Default value to return. /// /// /// If the node does not exist or it causes any error the default value will be returned. @@ -473,7 +479,7 @@ public static int GetNodeValueInt(XmlNode node, string nodeName) public static int GetNodeValueInt(XmlNode node, string nodeName, int defaultValue) { int intValue = defaultValue; - if ((node[nodeName] != null)) + if (node[nodeName] != null) { string strValue = node[nodeName].InnerText; if (!string.IsNullOrEmpty(strValue)) @@ -481,23 +487,24 @@ public static int GetNodeValueInt(XmlNode node, string nodeName, int defaultValu intValue = Convert.ToInt32(strValue); } } + return intValue; } - /// Gets the value of a child node as an - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// The value of the node or 0 if the node doesn't exist or doesn't have a value + /// Gets the value of a child node as an . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// The value of the node or 0 if the node doesn't exist or doesn't have a value. public static int GetNodeValueInt(XPathNavigator navigator, string path) { return GetNodeValueInt(navigator, path, 0); } - /// Gets the value of a child node as an - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// Default value to return if the node doesn't exist or doesn't have a value - /// The value of the node or + /// Gets the value of a child node as an . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// Default value to return if the node doesn't exist or doesn't have a value. + /// The value of the node or . public static int GetNodeValueInt(XPathNavigator navigator, string path, int defaultValue) { var childNodeNavigator = navigator.SelectSingleNode(path); @@ -517,10 +524,10 @@ public static int GetNodeValueInt(XPathNavigator navigator, string path, int def /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for + /// Parent node. + /// Child node to look for. /// /// /// If the node does not exist or it causes any error the default value (0) will be returned. @@ -533,11 +540,11 @@ public static float GetNodeValueSingle(XmlNode node, string nodeName) /// ----------------------------------------------------------------------------- /// - /// Gets the value of node + /// Gets the value of node. /// - /// Parent node - /// Child node to look for - /// Default value to return + /// Parent node. + /// Child node to look for. + /// Default value to return. /// /// /// If the node does not exist or it causes any error the default value will be returned. @@ -546,7 +553,7 @@ public static float GetNodeValueSingle(XmlNode node, string nodeName) public static float GetNodeValueSingle(XmlNode node, string nodeName, float defaultValue) { float sValue = defaultValue; - if ((node[nodeName] != null)) + if (node[nodeName] != null) { string strValue = node[nodeName].InnerText; if (!string.IsNullOrEmpty(strValue)) @@ -554,23 +561,24 @@ public static float GetNodeValueSingle(XmlNode node, string nodeName, float defa sValue = Convert.ToSingle(strValue, CultureInfo.InvariantCulture); } } + return sValue; } - /// Gets the value of a child node as a - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// The value of the node or 0 if the node doesn't exist or doesn't have a value + /// Gets the value of a child node as a . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// The value of the node or 0 if the node doesn't exist or doesn't have a value. public static float GetNodeValueSingle(XPathNavigator navigator, string path) { return GetNodeValueSingle(navigator, path, 0); } - /// Gets the value of a child node as a - /// A navigator pointing to the parent node - /// An XPath expression to find the child node - /// Default value to return if the node doesn't exist or doesn't have a value - /// The value of the node or + /// Gets the value of a child node as a . + /// A navigator pointing to the parent node. + /// An XPath expression to find the child node. + /// Default value to return if the node doesn't exist or doesn't have a value. + /// The value of the node or . public static float GetNodeValueSingle(XPathNavigator navigator, string path, float defaultValue) { var childNodeNavigator = navigator.SelectSingleNode(path); @@ -586,15 +594,15 @@ public static float GetNodeValueSingle(XPathNavigator navigator, string path, fl } return Convert.ToSingle(strValue, CultureInfo.InvariantCulture); - } - + } + /// ----------------------------------------------------------------------------- /// - /// Gets an XmlWriterSettings object + /// Gets an XmlWriterSettings object. /// - /// Conformance Level - /// An XmlWriterSettings - /// ----------------------------------------------------------------------------- + /// Conformance Level. + /// An XmlWriterSettings. + /// ----------------------------------------------------------------------------- public static XmlWriterSettings GetXmlWriterSettings(ConformanceLevel conformance) { var settings = new XmlWriterSettings(); @@ -618,31 +626,33 @@ public static string SerializeDictionary(IDictionary source, string rootName) foreach (var key in source.Keys) { - //Create the item Node + // Create the item Node XmlElement xmlItem = xmlDoc.CreateElement("item"); - //Save the key name and the object type + // Save the key name and the object type xmlItem.SetAttribute("key", Convert.ToString(key)); xmlItem.SetAttribute("type", source[key].GetType().AssemblyQualifiedName); - //Serialize the object + // Serialize the object var xmlObject = new XmlDocument { XmlResolver = null }; xser = new XmlSerializer(source[key].GetType()); sw = new StringWriter(); xser.Serialize(sw, source[key]); xmlObject.LoadXml(sw.ToString()); - //import and append the node to the root + // import and append the node to the root xmlItem.AppendChild(xmlDoc.ImportNode(xmlObject.DocumentElement, true)); xmlRoot.AppendChild(xmlItem); } - //Return the OuterXml of the profile + + // Return the OuterXml of the profile strString = xmlDoc.OuterXml; } else { - strString = ""; + strString = string.Empty; } + return strString; } @@ -665,34 +675,33 @@ public static void SerializeHashtable(Hashtable hashtable, XmlDocument xmlDocume nodeSettingValue.InnerText = hashtable[key].ToString(); } } - - + public static void UpdateAttribute(XmlNode node, string attName, string attValue) { - if ((node != null)) + if (node != null) { XmlAttribute attrib = node.Attributes[attName]; attrib.InnerText = attValue; } } - ///----------------------------------------------------------------------------- - /// - /// Xml Encodes HTML - /// - ///The HTML to encode - /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Xml Encodes HTML. + /// + /// The HTML to encode. + /// + /// ----------------------------------------------------------------------------- public static string XMLEncode(string html) { return ""; } /// - /// Removes control characters and other non-UTF-8 characters + /// Removes control characters and other non-UTF-8 characters. /// - /// The string to process - /// A string with no control characters or entities above 0x00FD + /// The string to process. + /// A string with no control characters or entities above 0x00FD. public static string RemoveInvalidXmlCharacters(string content) { if (string.IsNullOrEmpty(content)) @@ -708,15 +717,16 @@ public static string RemoveInvalidXmlCharacters(string content) newString.Append(ch); } } + return newString.ToString(); - } public static void XSLTransform(XmlDocument doc, ref StreamWriter writer, string xsltUrl) { var xslt = new XslCompiledTransform(); xslt.Load(xsltUrl); - //Transform the file. + + // Transform the file. xslt.Transform(doc, null, writer); } @@ -724,7 +734,7 @@ public static string Serialize(object obj) { string xmlObject; var dic = obj as IDictionary; - if ((dic != null)) + if (dic != null) { xmlObject = SerializeDictionary(dic, "dictionary"); } @@ -743,13 +753,14 @@ public static string Serialize(object obj) xmlObject = xmlDocEl.OuterXml; } + return xmlObject; } /// /// Produce an XPath literal equal to the value if possible; if not, produce /// an XPath expression that will match the value. - /// + /// /// Note that this function will produce very long XPath expressions if a value /// contains a long run of double quotes. /// @@ -757,7 +768,7 @@ public static string Serialize(object obj) /// If the value contains only single or double quotes, an XPath /// literal equal to the value. If it contains both, an XPath expression, /// using concat(), that evaluates to the value. - /// From Stack Overflow () + /// From Stack Overflow (). public static string XPathLiteral(string value) { // if the value contains only single or double quotes, construct @@ -766,6 +777,7 @@ public static string XPathLiteral(string value) { return "\"" + value + "\""; } + if (!value.Contains("'")) { return "'" + value + "'"; @@ -788,35 +800,39 @@ public static string XPathLiteral(string value) { sb.Append(", "); } + sb.Append("\""); sb.Append(substrings[i]); sb.Append("\""); needComma = true; } + if (i < substrings.Length - 1) { if (needComma) { sb.Append(", "); } + sb.Append("'\"'"); } } + sb.Append(")"); return sb.ToString(); } + [Obsolete("This method is obsolete. Use .Net XmlDocument.Load instead. Scheduled removal in v11.0.0.")] public static XmlDocument GetXMLContent(string contentUrl) { - //This function reads an Xml document via a Url and returns it as an XmlDocument object - + // This function reads an Xml document via a Url and returns it as an XmlDocument object var functionReturnValue = new XmlDocument { XmlResolver = null }; var req = WebRequest.Create(contentUrl); var result = req.GetResponse(); var objXmlReader = new XmlTextReader(result.GetResponseStream()) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; functionReturnValue.Load(objXmlReader); return functionReturnValue; diff --git a/DNN Platform/Library/Common/XmlValidatorBase.cs b/DNN Platform/Library/Common/XmlValidatorBase.cs index 712a4c3be32..59240292440 100644 --- a/DNN Platform/Library/Common/XmlValidatorBase.cs +++ b/DNN Platform/Library/Common/XmlValidatorBase.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.IO; -using System.Xml; -using System.Xml.Schema; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common { - /// - /// Base class od XmlValidator - /// + using System.Collections; + using System.IO; + using System.Xml; + using System.Xml.Schema; + + /// + /// Base class od XmlValidator. + /// public class XmlValidatorBase { private readonly XmlSchemaSet _schemaSet; @@ -24,106 +19,110 @@ public class XmlValidatorBase public XmlValidatorBase() { - _errs = new ArrayList(); - _schemaSet = new XmlSchemaSet(); + this._errs = new ArrayList(); + this._schemaSet = new XmlSchemaSet(); } - /// - /// Gets or sets the errors. - /// - /// - /// The errors. - /// + /// + /// Gets or sets the errors. + /// + /// + /// The errors. + /// public ArrayList Errors { get { - return _errs; + return this._errs; } + set { - _errs = value; + this._errs = value; } } - /// - /// Gets the schema set. - /// + /// + /// Gets the schema set. + /// public XmlSchemaSet SchemaSet { get { - return _schemaSet; + return this._schemaSet; } } - /// - /// Validations the call back. - /// - /// The sender. - /// The instance containing the event data. - protected void ValidationCallBack(object sender, ValidationEventArgs args) - { - _errs.Add(args.Message); - } - - /// - /// Determines whether this instance is valid. - /// - /// - /// true if this instance is valid; otherwise, false. - /// + /// + /// Determines whether this instance is valid. + /// + /// + /// true if this instance is valid; otherwise, false. + /// public bool IsValid() { - //There is a bug here which I haven't been able to fix. - //If the XML Instance does not include a reference to the - //schema, then the validation fails. If the reference exists - //the the validation works correctly. + // There is a bug here which I haven't been able to fix. + // If the XML Instance does not include a reference to the + // schema, then the validation fails. If the reference exists + // the the validation works correctly. - //Create a validating reader + // Create a validating reader var settings = new XmlReaderSettings(); - settings.Schemas = _schemaSet; + settings.Schemas = this._schemaSet; settings.ValidationType = ValidationType.Schema; - //Set the validation event handler. - settings.ValidationEventHandler += ValidationCallBack; - XmlReader vreader = XmlReader.Create(_reader, settings); - //Read and validate the XML data. + + // Set the validation event handler. + settings.ValidationEventHandler += this.ValidationCallBack; + XmlReader vreader = XmlReader.Create(this._reader, settings); + + // Read and validate the XML data. while (vreader.Read()) { } + vreader.Close(); - return (_errs.Count == 0); + return this._errs.Count == 0; } - /// - /// Validates the specified XML stream. - /// - /// The XML stream. - /// + /// + /// Validates the specified XML stream. + /// + /// The XML stream. + /// public virtual bool Validate(Stream xmlStream) { xmlStream.Seek(0, SeekOrigin.Begin); - _reader = new XmlTextReader(xmlStream) + this._reader = new XmlTextReader(xmlStream) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; - return IsValid(); + return this.IsValid(); + } + + /// + /// Validations the call back. + /// + /// The sender. + /// The instance containing the event data. + protected void ValidationCallBack(object sender, ValidationEventArgs args) + { + this._errs.Add(args.Message); } - /// - /// Validates the specified filename. - /// - /// The filename. - /// + /// + /// Validates the specified filename. + /// + /// The filename. + /// public virtual bool Validate(string filename) { - _reader = new XmlTextReader(filename) + this._reader = new XmlTextReader(filename) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; - return IsValid(); + return this.IsValid(); } } } diff --git a/DNN Platform/Library/ComponentModel/AbstractContainer.cs b/DNN Platform/Library/ComponentModel/AbstractContainer.cs index 281b403f291..3d19b7e3509 100644 --- a/DNN Platform/Library/ComponentModel/AbstractContainer.cs +++ b/DNN Platform/Library/ComponentModel/AbstractContainer.cs @@ -1,20 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + using System.Collections; + public abstract class AbstractContainer : IContainer - { - #region IContainer Members - + { public abstract string Name { get; } public abstract object GetComponent(string name); @@ -25,124 +18,128 @@ public abstract class AbstractContainer : IContainer public virtual TContract GetComponent() { - return (TContract) GetComponent(typeof (TContract)); + return (TContract)this.GetComponent(typeof(TContract)); } public virtual TContract GetComponent(string name) { - return (TContract) GetComponent(name, typeof (TContract)); + return (TContract)this.GetComponent(name, typeof(TContract)); } public abstract string[] GetComponentList(Type contractType); public virtual string[] GetComponentList() { - return GetComponentList(typeof (TContract)); + return this.GetComponentList(typeof(TContract)); } public abstract IDictionary GetComponentSettings(string name); public virtual IDictionary GetComponentSettings(Type component) { - return GetComponentSettings(component.FullName); + return this.GetComponentSettings(component.FullName); } public IDictionary GetComponentSettings() { - return GetComponentSettings(typeof (TComponent).FullName); + return this.GetComponentSettings(typeof(TComponent).FullName); } public abstract void RegisterComponent(string name, Type contractType, Type componentType, ComponentLifeStyleType lifestyle); public virtual void RegisterComponent(string name, Type contractType, Type componentType) { - RegisterComponent(name, contractType, componentType, ComponentLifeStyleType.Singleton); + this.RegisterComponent(name, contractType, componentType, ComponentLifeStyleType.Singleton); } public virtual void RegisterComponent(string name, Type componentType) { - RegisterComponent(name, componentType, componentType, ComponentLifeStyleType.Singleton); + this.RegisterComponent(name, componentType, componentType, ComponentLifeStyleType.Singleton); } public virtual void RegisterComponent(Type contractType, Type componentType) { - RegisterComponent(componentType.FullName, contractType, componentType, ComponentLifeStyleType.Singleton); + this.RegisterComponent(componentType.FullName, contractType, componentType, ComponentLifeStyleType.Singleton); } public virtual void RegisterComponent(Type contractType, Type componentType, ComponentLifeStyleType lifestyle) { - RegisterComponent(componentType.FullName, contractType, componentType, lifestyle); + this.RegisterComponent(componentType.FullName, contractType, componentType, lifestyle); } public virtual void RegisterComponent(Type componentType) { - RegisterComponent(componentType.FullName, componentType, componentType, ComponentLifeStyleType.Singleton); + this.RegisterComponent(componentType.FullName, componentType, componentType, ComponentLifeStyleType.Singleton); } - public virtual void RegisterComponent() where TComponent : class + public virtual void RegisterComponent() + where TComponent : class { - RegisterComponent(typeof (TComponent)); + this.RegisterComponent(typeof(TComponent)); } - public virtual void RegisterComponent(string name) where TComponent : class + public virtual void RegisterComponent(string name) + where TComponent : class { - RegisterComponent(name, typeof (TComponent), typeof (TComponent), ComponentLifeStyleType.Singleton); + this.RegisterComponent(name, typeof(TComponent), typeof(TComponent), ComponentLifeStyleType.Singleton); } - public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) where TComponent : class + public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class { - RegisterComponent(name, typeof (TComponent), typeof (TComponent), lifestyle); + this.RegisterComponent(name, typeof(TComponent), typeof(TComponent), lifestyle); } - public virtual void RegisterComponent() where TComponent : class + public virtual void RegisterComponent() + where TComponent : class { - RegisterComponent(typeof (TContract), typeof (TComponent)); + this.RegisterComponent(typeof(TContract), typeof(TComponent)); } - public virtual void RegisterComponent(string name) where TComponent : class + public virtual void RegisterComponent(string name) + where TComponent : class { - RegisterComponent(name, typeof (TContract), typeof (TComponent), ComponentLifeStyleType.Singleton); + this.RegisterComponent(name, typeof(TContract), typeof(TComponent), ComponentLifeStyleType.Singleton); } - public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) where TComponent : class + public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class { - RegisterComponent(name, typeof (TContract), typeof (TComponent), lifestyle); + this.RegisterComponent(name, typeof(TContract), typeof(TComponent), lifestyle); } public abstract void RegisterComponentSettings(string name, IDictionary dependencies); public virtual void RegisterComponentSettings(Type component, IDictionary dependencies) { - RegisterComponentSettings(component.FullName, dependencies); + this.RegisterComponentSettings(component.FullName, dependencies); } public virtual void RegisterComponentSettings(IDictionary dependencies) { - RegisterComponentSettings(typeof (TComponent).FullName, dependencies); + this.RegisterComponentSettings(typeof(TComponent).FullName, dependencies); } public abstract void RegisterComponentInstance(string name, Type contractType, object instance); public void RegisterComponentInstance(string name, object instance) { - RegisterComponentInstance(name, instance.GetType(), instance); + this.RegisterComponentInstance(name, instance.GetType(), instance); } public void RegisterComponentInstance(object instance) { - RegisterComponentInstance(instance.GetType().FullName, typeof (TContract), instance); + this.RegisterComponentInstance(instance.GetType().FullName, typeof(TContract), instance); } public void RegisterComponentInstance(string name, object instance) { - RegisterComponentInstance(name, typeof (TContract), instance); - } - - #endregion - + this.RegisterComponentInstance(name, typeof(TContract), instance); + } + public virtual IDictionary GetCustomDependencies() { - return GetComponentSettings(typeof (TComponent).FullName); + return this.GetComponentSettings(typeof(TComponent).FullName); } } } diff --git a/DNN Platform/Library/ComponentModel/ComponentBase.cs b/DNN Platform/Library/ComponentModel/ComponentBase.cs index 305d5e6fb4d..9f94b556c4b 100644 --- a/DNN Platform/Library/ComponentModel/ComponentBase.cs +++ b/DNN Platform/Library/ComponentModel/ComponentBase.cs @@ -1,16 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { - public abstract class ComponentBase where TType : class, TContract + using System; + + public abstract class ComponentBase + where TType : class, TContract { private static TContract _testableInstance; private static bool _useTestable = false; @@ -19,14 +15,16 @@ public static TContract Instance { get { - if (_useTestable && _testableInstance != null) - return _testableInstance; - + if (_useTestable && _testableInstance != null) + { + return _testableInstance; + } + var component = ComponentFactory.GetComponent(); if (component == null) { - component = (TContract) Activator.CreateInstance(typeof (TType), true); + component = (TContract)Activator.CreateInstance(typeof(TType), true); ComponentFactory.RegisterComponentInstance(component); } @@ -34,10 +32,18 @@ public static TContract Instance } } + public static void RegisterInstance(TContract instance) + { + if (ComponentFactory.GetComponent() == null) + { + ComponentFactory.RegisterComponentInstance(instance); + } + } + /// - /// Registers an instance to use for the Singleton + /// Registers an instance to use for the Singleton. /// - /// Intended for unit testing purposes, not thread safe + /// Intended for unit testing purposes, not thread safe. /// internal static void SetTestableInstance(TContract instance) { @@ -46,21 +52,13 @@ internal static void SetTestableInstance(TContract instance) } /// - /// Clears the current instance, a new instance will be initialized when next requested + /// Clears the current instance, a new instance will be initialized when next requested. /// - /// Intended for unit testing purposes, not thread safe + /// Intended for unit testing purposes, not thread safe. internal static void ClearInstance() { _useTestable = false; _testableInstance = default(TContract); } - - public static void RegisterInstance(TContract instance) - { - if ((ComponentFactory.GetComponent() == null)) - { - ComponentFactory.RegisterComponentInstance(instance); - } - } } } diff --git a/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs b/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs index 2b0b4e8c321..721e853a628 100644 --- a/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs +++ b/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Collections.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using DotNetNuke.Collections.Internal; + internal class ComponentBuilderCollection : SharedDictionary { internal IComponentBuilder DefaultBuilder { get; set; } internal void AddBuilder(IComponentBuilder builder, bool setDefault) { - if (!ContainsKey(builder.Name)) + if (!this.ContainsKey(builder.Name)) { this[builder.Name] = builder; - if (setDefault && DefaultBuilder == null) + if (setDefault && this.DefaultBuilder == null) { - DefaultBuilder = builder; + this.DefaultBuilder = builder; } } } diff --git a/DNN Platform/Library/ComponentModel/ComponentFactory.cs b/DNN Platform/Library/ComponentModel/ComponentFactory.cs index e35a4d981a0..a4c54fe992f 100644 --- a/DNN Platform/Library/ComponentModel/ComponentFactory.cs +++ b/DNN Platform/Library/ComponentModel/ComponentFactory.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + using System.Collections; + using System.Collections.Generic; + public static class ComponentFactory { public static IContainer Container { get; set; } @@ -22,6 +17,7 @@ public static void InstallComponents(params IComponentInstaller[] installers) { throw new ArgumentNullException("installers"); } + VerifyContainer(); foreach (IComponentInstaller installer in installers) { @@ -29,18 +25,11 @@ public static void InstallComponents(params IComponentInstaller[] installers) { throw new ArgumentNullException("installers"); } + installer.InstallComponents(Container); } } - private static void VerifyContainer() - { - if (Container == null) - { - Container = new SimpleContainer(); - } - } - public static object GetComponent(string name) { VerifyContainer(); @@ -53,6 +42,14 @@ public static TContract GetComponent() return Container.GetComponent(); } + private static void VerifyContainer() + { + if (Container == null) + { + Container = new SimpleContainer(); + } + } + public static object GetComponent(Type contractType) { VerifyContainer(); @@ -91,6 +88,7 @@ public static Dictionary GetComponents() { components[componentName] = GetComponent(componentName); } + return components; } @@ -112,13 +110,15 @@ public static IDictionary GetComponentSettings() return Container.GetComponentSettings(); } - public static void RegisterComponent() where TComponent : class + public static void RegisterComponent() + where TComponent : class { VerifyContainer(); Container.RegisterComponent(); } - public static void RegisterComponent() where TComponent : class + public static void RegisterComponent() + where TComponent : class { VerifyContainer(); Container.RegisterComponent(); @@ -136,13 +136,15 @@ public static void RegisterComponent(Type contractType, Type componentType) Container.RegisterComponent(contractType, componentType); } - public static void RegisterComponent(string name) where TComponent : class + public static void RegisterComponent(string name) + where TComponent : class { VerifyContainer(); Container.RegisterComponent(name); } - public static void RegisterComponent(string name) where TComponent : class + public static void RegisterComponent(string name) + where TComponent : class { VerifyContainer(); Container.RegisterComponent(name); diff --git a/DNN Platform/Library/ComponentModel/ComponentLifeStyleType.cs b/DNN Platform/Library/ComponentModel/ComponentLifeStyleType.cs index 2581e5eeaed..6854f7eaf30 100644 --- a/DNN Platform/Library/ComponentModel/ComponentLifeStyleType.cs +++ b/DNN Platform/Library/ComponentModel/ComponentLifeStyleType.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel { public enum ComponentLifeStyleType { Singleton, - Transient + Transient, } } diff --git a/DNN Platform/Library/ComponentModel/ComponentType.cs b/DNN Platform/Library/ComponentModel/ComponentType.cs index cdac693b4f4..c47dcd74588 100644 --- a/DNN Platform/Library/ComponentModel/ComponentType.cs +++ b/DNN Platform/Library/ComponentModel/ComponentType.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + internal class ComponentType { private readonly Type _BaseType; - private readonly ComponentBuilderCollection _ComponentBuilders = new ComponentBuilderCollection(); - - /// - /// Initializes a new instance of the ComponentType class. - /// - /// The base type of Components of this ComponentType - public ComponentType(Type baseType) + private readonly ComponentBuilderCollection _ComponentBuilders = new ComponentBuilderCollection(); + + /// + /// Initializes a new instance of the class. + /// + /// The base type of Components of this ComponentType. + public ComponentType(Type baseType) { - _BaseType = baseType; + this._BaseType = baseType; } public Type BaseType { get { - return _BaseType; + return this._BaseType; } } @@ -36,7 +31,7 @@ public ComponentBuilderCollection ComponentBuilders { get { - return _ComponentBuilders; + return this._ComponentBuilders; } } } diff --git a/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs b/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs index 65121023a31..9ef892488d6 100644 --- a/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs +++ b/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Collections.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + + using DotNetNuke.Collections.Internal; + internal class ComponentTypeCollection : SharedDictionary { } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs index 6df62f621c0..ae18526393c 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs @@ -1,66 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.Caching; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + using System.Web.Caching; + public class CacheableAttribute : Attribute - { - /// - /// Construct a new CacheableAttribute + { + /// + /// Initializes a new instance of the class. + /// Construct a new CacheableAttribute. /// public CacheableAttribute() { - CachePriority = CacheItemPriority.Default; - CacheTimeOut = 20; - } - - /// - /// Construct a new CacheableAttribute + this.CachePriority = CacheItemPriority.Default; + this.CacheTimeOut = 20; + } + + /// + /// Initializes a new instance of the class. + /// Construct a new CacheableAttribute. /// - /// The cacheKey to use - public CacheableAttribute(string cacheKey) : this(cacheKey, CacheItemPriority.Default, 20) {} - - /// - /// Construct a new CacheableAttribute + /// The cacheKey to use. + public CacheableAttribute(string cacheKey) + : this(cacheKey, CacheItemPriority.Default, 20) + { + } + + /// + /// Initializes a new instance of the class. + /// Construct a new CacheableAttribute. /// - /// The cacheKey to use - /// The priority of the cached item - public CacheableAttribute(string cacheKey, CacheItemPriority priority) : this(cacheKey, priority, 20) { } - - /// - /// Construct a new CacheableAttribute + /// The cacheKey to use. + /// The priority of the cached item. + public CacheableAttribute(string cacheKey, CacheItemPriority priority) + : this(cacheKey, priority, 20) + { + } + + /// + /// Initializes a new instance of the class. + /// Construct a new CacheableAttribute. /// - /// The cacheKey to use - /// The priority of the cached item - /// The timeout multiplier used to cache the item + /// The cacheKey to use. + /// The priority of the cached item. + /// The timeout multiplier used to cache the item. public CacheableAttribute(string cacheKey, CacheItemPriority priority, int timeOut) { - CacheKey = cacheKey; - CachePriority = priority; - CacheTimeOut = timeOut; + this.CacheKey = cacheKey; + this.CachePriority = priority; + this.CacheTimeOut = timeOut; } /// - /// The root key to use for the cache + /// Gets or sets the root key to use for the cache. /// public string CacheKey { get; set; } /// - /// The priority of the cached item. The default value is CacheItemPriority.Default + /// Gets or sets the priority of the cached item. The default value is CacheItemPriority.Default. /// public CacheItemPriority CachePriority { get; set; } /// - /// The timeout multiplier used to cache the item. This value is multiple by the Host - /// Performance Setting to determine the actual timeout value. The default value is 20. + /// Gets or sets the timeout multiplier used to cache the item. This value is multiple by the Host + /// Performance Setting to determine the actual timeout value. The default value is 20. /// public int CacheTimeOut { get; set; } } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs index 2a0194a459a..328e33b72f8 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class ColumnNameAttribute : Attribute { public ColumnNameAttribute(string columnName) { - ColumnName = columnName; + this.ColumnName = columnName; } public string ColumnName { get; set; } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs index 53ff996811c..59461499559 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class DeclareColumnsAttribute : Attribute { } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs index 6093e9d310e..90926d830b7 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class IgnoreColumnAttribute : Attribute { } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs index 227bdcb57b1..fb43075ead4 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class IncludeColumnAttribute : Attribute { } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs index 4b86d49a062..6e09a197ce0 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs @@ -1,31 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class PrimaryKeyAttribute : Attribute { - public PrimaryKeyAttribute(string columnName) : this(columnName, columnName) + public PrimaryKeyAttribute(string columnName) + : this(columnName, columnName) { } public PrimaryKeyAttribute(string columnName, string propertyName) { - ColumnName = columnName; - PropertyName = propertyName; - AutoIncrement = true; + this.ColumnName = columnName; + this.PropertyName = propertyName; + this.AutoIncrement = true; } public bool AutoIncrement { get; set; } + public string ColumnName { get; set; } + public string PropertyName { get; set; } - } } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs index ccc5c1c5738..f14e03820b3 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class ReadOnlyColumnAttribute : Attribute { } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs index 682feb7d109..0b22368805a 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs @@ -1,23 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class ScopeAttribute : Attribute { - public ScopeAttribute(string scope) { - Scope = scope; + this.Scope = scope; } /// - /// The property to use to scope the cache. The default is an empty string. + /// Gets or sets the property to use to scope the cache. The default is an empty string. /// public string Scope { get; set; } - } } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs index 756f8b85829..7609925560c 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel.DataAnnotations { + using System; + public class TableNameAttribute : Attribute { public TableNameAttribute(string tableName) { - TableName = tableName; + this.TableName = tableName; } public string TableName { get; set; } diff --git a/DNN Platform/Library/ComponentModel/IComponentBuilder.cs b/DNN Platform/Library/ComponentModel/IComponentBuilder.cs index 3d9e08a9042..11092bea5e4 100644 --- a/DNN Platform/Library/ComponentModel/IComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/IComponentBuilder.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel { public interface IComponentBuilder diff --git a/DNN Platform/Library/ComponentModel/IComponentInstaller.cs b/DNN Platform/Library/ComponentModel/IComponentInstaller.cs index e6b3c5c553f..f2c6f0a598d 100644 --- a/DNN Platform/Library/ComponentModel/IComponentInstaller.cs +++ b/DNN Platform/Library/ComponentModel/IComponentInstaller.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel { public interface IComponentInstaller diff --git a/DNN Platform/Library/ComponentModel/IContainer.cs b/DNN Platform/Library/ComponentModel/IContainer.cs index b0d34cd7a6d..a1cb3719315 100644 --- a/DNN Platform/Library/ComponentModel/IContainer.cs +++ b/DNN Platform/Library/ComponentModel/IContainer.cs @@ -1,31 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + using System.Collections; + public interface IContainer { string Name { get; } - void RegisterComponent() where TComponent : class; + void RegisterComponent() + where TComponent : class; - void RegisterComponent(string name) where TComponent : class; + void RegisterComponent(string name) + where TComponent : class; - void RegisterComponent(string name, ComponentLifeStyleType lifestyle) where TComponent : class; + void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class; - void RegisterComponent() where TComponent : class; + void RegisterComponent() + where TComponent : class; - void RegisterComponent(string name) where TComponent : class; + void RegisterComponent(string name) + where TComponent : class; - void RegisterComponent(string name, ComponentLifeStyleType lifestyle) where TComponent : class; + void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class; void RegisterComponent(Type componentType); diff --git a/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs b/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs index e578f2f9a9e..d913a4a446c 100644 --- a/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs @@ -1,40 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ComponentModel { internal class InstanceComponentBuilder : IComponentBuilder { private readonly object _Instance; - private readonly string _Name; - - /// - /// Initializes a new instance of the InstanceComponentBuilder class. + private readonly string _Name; + + /// + /// Initializes a new instance of the class. /// /// /// public InstanceComponentBuilder(string name, object instance) { - _Name = name; - _Instance = instance; - } - - #region IComponentBuilder Members - - public object BuildComponent() - { - return _Instance; - } + this._Name = name; + this._Instance = instance; + } public string Name { get { - return _Name; + return this._Name; } + } + + public object BuildComponent() + { + return this._Instance; } - - #endregion } } diff --git a/DNN Platform/Library/ComponentModel/ProviderInstaller.cs b/DNN Platform/Library/ComponentModel/ProviderInstaller.cs index 35a783cbfbe..adc1d5abc12 100644 --- a/DNN Platform/Library/ComponentModel/ProviderInstaller.cs +++ b/DNN Platform/Library/ComponentModel/ProviderInstaller.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Web.Compilation; - -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + using System.Collections.Generic; + using System.Configuration; + using System.Web.Compilation; + + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + public class ProviderInstaller : IComponentInstaller { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ProviderInstaller)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProviderInstaller)); private readonly ComponentLifeStyleType _ComponentLifeStyle; private readonly Type _ProviderInterface; private readonly string _ProviderType; @@ -27,66 +22,63 @@ public class ProviderInstaller : IComponentInstaller public ProviderInstaller(string providerType, Type providerInterface) { - _ComponentLifeStyle = ComponentLifeStyleType.Singleton; - _ProviderType = providerType; - _ProviderInterface = providerInterface; + this._ComponentLifeStyle = ComponentLifeStyleType.Singleton; + this._ProviderType = providerType; + this._ProviderInterface = providerInterface; } public ProviderInstaller(string providerType, Type providerInterface, Type defaultProvider) { - _ComponentLifeStyle = ComponentLifeStyleType.Singleton; - _ProviderType = providerType; - _ProviderInterface = providerInterface; - _defaultProvider = defaultProvider; + this._ComponentLifeStyle = ComponentLifeStyleType.Singleton; + this._ProviderType = providerType; + this._ProviderInterface = providerInterface; + this._defaultProvider = defaultProvider; } public ProviderInstaller(string providerType, Type providerInterface, ComponentLifeStyleType lifeStyle) { - _ComponentLifeStyle = lifeStyle; - _ProviderType = providerType; - _ProviderInterface = providerInterface; - } - - #region IComponentInstaller Members - + this._ComponentLifeStyle = lifeStyle; + this._ProviderType = providerType; + this._ProviderInterface = providerInterface; + } + public void InstallComponents(IContainer container) { - ProviderConfiguration config = ProviderConfiguration.GetProviderConfiguration(_ProviderType); - //Register the default provider first (so it is the first component registered for its service interface - if (config != null) + ProviderConfiguration config = ProviderConfiguration.GetProviderConfiguration(this._ProviderType); + + // Register the default provider first (so it is the first component registered for its service interface + if (config != null) { - InstallProvider(container, (Provider) config.Providers[config.DefaultProvider]); + this.InstallProvider(container, (Provider)config.Providers[config.DefaultProvider]); - //Register the others + // Register the others foreach (Provider provider in config.Providers.Values) { - //Skip the default because it was registered above + // Skip the default because it was registered above if (!config.DefaultProvider.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { - InstallProvider(container, provider); + this.InstallProvider(container, provider); } } } - } - - #endregion - + } + private void InstallProvider(IContainer container, Provider provider) { if (provider != null) { Type type = null; - //Get the provider type + // Get the provider type try { - type = BuildManager.GetType(provider.Type, false, true); - } + type = BuildManager.GetType(provider.Type, false, true); + } catch (TypeLoadException) { - if (_defaultProvider != null) + if (this._defaultProvider != null) { - type = _defaultProvider; + type = this._defaultProvider; } } @@ -96,16 +88,17 @@ private void InstallProvider(IContainer container, Provider provider) } else { - //Register the component - container.RegisterComponent(provider.Name, _ProviderInterface, type, _ComponentLifeStyle); + // Register the component + container.RegisterComponent(provider.Name, this._ProviderInterface, type, this._ComponentLifeStyle); - //Load the settings into a dictionary + // Load the settings into a dictionary var settingsDict = new Dictionary { { "providerName", provider.Name } }; foreach (string key in provider.Attributes.Keys) { settingsDict.Add(key, provider.Attributes.Get(key)); } - //Register the settings as dependencies + + // Register the settings as dependencies container.RegisterComponentSettings(type.FullName, settingsDict); } } diff --git a/DNN Platform/Library/ComponentModel/SimpleContainer.cs b/DNN Platform/Library/ComponentModel/SimpleContainer.cs index 85b3622a7ff..60b72ec9809 100644 --- a/DNN Platform/Library/ComponentModel/SimpleContainer.cs +++ b/DNN Platform/Library/ComponentModel/SimpleContainer.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Collections.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Collections.Internal; + public class SimpleContainer : AbstractContainer { private readonly string _name; @@ -23,33 +18,51 @@ public class SimpleContainer : AbstractContainer private readonly ComponentTypeCollection _componentTypes = new ComponentTypeCollection(); - private readonly SharedDictionary _registeredComponents = new SharedDictionary(); - - #region "Constructors" - - /// - /// Initializes a new instance of the SimpleContainer class. + private readonly SharedDictionary _registeredComponents = new SharedDictionary(); + + /// + /// Initializes a new instance of the class. /// - public SimpleContainer() : this(string.Format("Container_{0}", Guid.NewGuid())) + public SimpleContainer() + : this(string.Format("Container_{0}", Guid.NewGuid())) { - } - - /// - /// Initializes a new instance of the SimpleContainer class. + } + + /// + /// Initializes a new instance of the class. /// /// public SimpleContainer(string name) { - _name = name; + this._name = name; + } + + public override string Name + { + get + { + return this._name; + } } - #endregion + public override void RegisterComponent(string name, Type type) + { + using (this._registeredComponents.GetWriteLock()) + { + this._registeredComponents[type] = name; + } + } - #region "Private Methods" + public override object GetComponent(string name) + { + IComponentBuilder builder = this.GetComponentBuilder(name); + return this.GetComponent(builder); + } + private void AddBuilder(Type contractType, IComponentBuilder builder) { - ComponentType componentType = GetComponentType(contractType); + ComponentType componentType = this.GetComponentType(contractType); if (componentType != null) { ComponentBuilderCollection builders = componentType.ComponentBuilders; @@ -59,24 +72,24 @@ private void AddBuilder(Type contractType, IComponentBuilder builder) builders.AddBuilder(builder, true); } - using (_componentBuilders.GetWriteLock()) + using (this._componentBuilders.GetWriteLock()) { - _componentBuilders.AddBuilder(builder, false); + this._componentBuilders.AddBuilder(builder, false); } } } private void AddComponentType(Type contractType) { - ComponentType componentType = GetComponentType(contractType); + ComponentType componentType = this.GetComponentType(contractType); if (componentType == null) { componentType = new ComponentType(contractType); - using (_componentTypes.GetWriteLock()) + using (this._componentTypes.GetWriteLock()) { - _componentTypes[componentType.BaseType] = componentType; + this._componentTypes[componentType.BaseType] = componentType; } } } @@ -92,6 +105,7 @@ private object GetComponent(IComponentBuilder builder) { component = builder.BuildComponent(); } + return component; } @@ -99,9 +113,9 @@ private IComponentBuilder GetComponentBuilder(string name) { IComponentBuilder builder; - using (_componentBuilders.GetReadLock()) + using (this._componentBuilders.GetReadLock()) { - _componentBuilders.TryGetValue(name, out builder); + this._componentBuilders.TryGetValue(name, out builder); } return builder; @@ -123,42 +137,17 @@ private ComponentType GetComponentType(Type contractType) { ComponentType componentType; - using (_componentTypes.GetReadLock()) + using (this._componentTypes.GetReadLock()) { - _componentTypes.TryGetValue(contractType, out componentType); + this._componentTypes.TryGetValue(contractType, out componentType); } return componentType; } - public override void RegisterComponent(string name, Type type) - { - using (_registeredComponents.GetWriteLock()) - { - _registeredComponents[type] = name; - } - } - - #endregion - - public override string Name - { - get - { - return _name; - } - } - - public override object GetComponent(string name) - { - IComponentBuilder builder = GetComponentBuilder(name); - - return GetComponent(builder); - } - public override object GetComponent(Type contractType) { - ComponentType componentType = GetComponentType(contractType); + ComponentType componentType = this.GetComponentType(contractType); object component = null; if (componentType != null) @@ -172,9 +161,9 @@ public override object GetComponent(Type contractType) if (builderCount > 0) { - IComponentBuilder builder = GetDefaultComponentBuilder(componentType); + IComponentBuilder builder = this.GetDefaultComponentBuilder(componentType); - component = GetComponent(builder); + component = this.GetComponent(builder); } } @@ -183,15 +172,16 @@ public override object GetComponent(Type contractType) public override object GetComponent(string name, Type contractType) { - ComponentType componentType = GetComponentType(contractType); + ComponentType componentType = this.GetComponentType(contractType); object component = null; if (componentType != null) { - IComponentBuilder builder = GetComponentBuilder(name); + IComponentBuilder builder = this.GetComponentBuilder(name); - component = GetComponent(builder); + component = this.GetComponent(builder); } + return component; } @@ -199,9 +189,9 @@ public override string[] GetComponentList(Type contractType) { var components = new List(); - using (_registeredComponents.GetReadLock()) + using (this._registeredComponents.GetReadLock()) { - foreach (KeyValuePair kvp in _registeredComponents) + foreach (KeyValuePair kvp in this._registeredComponents) { if (contractType.IsAssignableFrom(kvp.Key)) { @@ -209,22 +199,24 @@ public override string[] GetComponentList(Type contractType) } } } + return components.ToArray(); } public override IDictionary GetComponentSettings(string name) { IDictionary settings; - using (_componentDependencies.GetReadLock()) + using (this._componentDependencies.GetReadLock()) { - settings = _componentDependencies[name]; + settings = this._componentDependencies[name]; } + return settings; } public override void RegisterComponent(string name, Type contractType, Type type, ComponentLifeStyleType lifestyle) { - AddComponentType(contractType); + this.AddComponentType(contractType); IComponentBuilder builder = null; switch (lifestyle) @@ -236,25 +228,26 @@ public override void RegisterComponent(string name, Type contractType, Type type builder = new SingletonComponentBuilder(name, type); break; } - AddBuilder(contractType, builder); + + this.AddBuilder(contractType, builder); - RegisterComponent(name, type); + this.RegisterComponent(name, type); } public override void RegisterComponentInstance(string name, Type contractType, object instance) { - AddComponentType(contractType); + this.AddComponentType(contractType); - AddBuilder(contractType, new InstanceComponentBuilder(name, instance)); + this.AddBuilder(contractType, new InstanceComponentBuilder(name, instance)); - RegisterComponent(name, instance.GetType()); + this.RegisterComponent(name, instance.GetType()); } public override void RegisterComponentSettings(string name, IDictionary dependencies) { - using (_componentDependencies.GetWriteLock()) + using (this._componentDependencies.GetWriteLock()) { - _componentDependencies[name] = dependencies; + this._componentDependencies[name] = dependencies; } } } diff --git a/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs b/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs index 6beedcf1e5b..64eb7b592c6 100644 --- a/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs @@ -1,58 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + + using DotNetNuke.Framework; + internal class SingletonComponentBuilder : IComponentBuilder { private readonly string _Name; private readonly Type _Type; - private object _Instance; - - /// - /// Initializes a new instance of the SingletonComponentBuilder class. + private object _Instance; + + /// + /// Initializes a new instance of the class. /// - /// The name of the component - /// The type of the component + /// The name of the component. + /// The type of the component. public SingletonComponentBuilder(string name, Type type) { - _Name = name; - _Type = type; - } - - #region IComponentBuilder Members + this._Name = name; + this._Type = type; + } - public object BuildComponent() + public string Name { - if (_Instance == null) + get { - CreateInstance(); + return this._Name; } - return _Instance; - } - - public string Name + } + + public object BuildComponent() { - get + if (this._Instance == null) { - return _Name; + this.CreateInstance(); } + + return this._Instance; } - - #endregion - + private void CreateInstance() { - _Instance = Reflection.CreateObject(_Type); + this._Instance = Reflection.CreateObject(this._Type); } } } diff --git a/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs b/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs index ee28c2c6871..e58f9b229d4 100644 --- a/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs @@ -1,48 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.ComponentModel { + using System; + + using DotNetNuke.Framework; + internal class TransientComponentBuilder : IComponentBuilder { private readonly string _Name; - private readonly Type _Type; - - /// - /// Initializes a new instance of the TransientComponentBuilder class. + private readonly Type _Type; + + /// + /// Initializes a new instance of the class. /// - /// The name of the component - /// The type of the component + /// The name of the component. + /// The type of the component. public TransientComponentBuilder(string name, Type type) { - _Name = name; - _Type = type; - } - - #region IComponentBuilder Members - - public object BuildComponent() - { - return Reflection.CreateObject(_Type); - } + this._Name = name; + this._Type = type; + } public string Name { get { - return _Name; + return this._Name; } + } + + public object BuildComponent() + { + return Reflection.CreateObject(this._Type); } - - #endregion } } diff --git a/DNN Platform/Library/Data/ControllerBase.cs b/DNN Platform/Library/Data/ControllerBase.cs index a2fe344cf94..9596af4fc83 100644 --- a/DNN Platform/Library/Data/ControllerBase.cs +++ b/DNN Platform/Library/Data/ControllerBase.cs @@ -1,36 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Common; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data { - public abstract class ControllerBase : ServiceLocator where TSelf : ServiceLocator, new() where TEntity : class + using System; + using System.Collections.Generic; + + using DotNetNuke.Common; + using DotNetNuke.Framework; + + public abstract class ControllerBase : ServiceLocator + where TSelf : ServiceLocator, new() + where TEntity : class { protected readonly IDataContext DataContext; - protected ControllerBase() { } + protected ControllerBase() + { + } protected ControllerBase(IDataContext dataContext) { - //Argument Contract + // Argument Contract Requires.NotNull("dataContext", dataContext); - DataContext = dataContext; + this.DataContext = dataContext; } public void Add(TEntity entity) { - //Argument Contract + // Argument Contract Requires.NotNull(entity); - using (DataContext) + using (this.DataContext) { - var rep = DataContext.GetRepository(); + var rep = this.DataContext.GetRepository(); rep.Insert(entity); } @@ -38,16 +43,16 @@ public void Add(TEntity entity) public void Delete(TEntity entity) { - //Argument Contract + // Argument Contract Requires.NotNull(entity); - var primaryKey = DataUtil.GetPrimaryKeyProperty(typeof(TEntity), String.Empty); + var primaryKey = DataUtil.GetPrimaryKeyProperty(typeof(TEntity), string.Empty); Requires.PropertyNotNull(entity, primaryKey); Requires.PropertyNotNegative(entity, primaryKey); - using (DataContext) + using (this.DataContext) { - var rep = DataContext.GetRepository(); + var rep = this.DataContext.GetRepository(); rep.Delete(entity); } @@ -56,23 +61,22 @@ public void Delete(TEntity entity) public IEnumerable Find(string sqlCondition, params object[] args) { IEnumerable entities; - using (DataContext) + using (this.DataContext) { - var rep = DataContext.GetRepository(); + var rep = this.DataContext.GetRepository(); entities = rep.Find(sqlCondition, args); } return entities; - } public IEnumerable Get() { IEnumerable entities; - using (DataContext) + using (this.DataContext) { - var rep = DataContext.GetRepository(); + var rep = this.DataContext.GetRepository(); entities = rep.Get(); } @@ -83,9 +87,9 @@ public IEnumerable Get() public IEnumerable Get(TScope scope) { IEnumerable contentTypes; - using (DataContext) + using (this.DataContext) { - var rep = DataContext.GetRepository(); + var rep = this.DataContext.GetRepository(); contentTypes = rep.Get(scope); } @@ -95,16 +99,16 @@ public IEnumerable Get(TScope scope) public void Update(TEntity entity) { - //Argument Contract + // Argument Contract Requires.NotNull(entity); - var primaryKey = DataUtil.GetPrimaryKeyProperty(typeof(TEntity), String.Empty); + var primaryKey = DataUtil.GetPrimaryKeyProperty(typeof(TEntity), string.Empty); Requires.PropertyNotNull(entity, primaryKey); Requires.PropertyNotNegative(entity, primaryKey); - using (DataContext) + using (this.DataContext) { - var rep = DataContext.GetRepository(); + var rep = this.DataContext.GetRepository(); rep.Update(entity); } diff --git a/DNN Platform/Library/Data/DataContext.cs b/DNN Platform/Library/Data/DataContext.cs index 0fc32f51643..c9ad97c4bdf 100644 --- a/DNN Platform/Library/Data/DataContext.cs +++ b/DNN Platform/Library/Data/DataContext.cs @@ -1,21 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Configuration; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.UI.Containers; -using PetaPoco; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Data { + using System; + using System.Collections.Generic; + using System.Configuration; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.UI.Containers; + using global::PetaPoco; + public class DataContext { public static IDataContext Instance() diff --git a/DNN Platform/Library/Data/DataProvider.cs b/DNN Platform/Library/Data/DataProvider.cs index 0bf3d7ee6d3..6c1dfbe5b1d 100644 --- a/DNN Platform/Library/Data/DataProvider.cs +++ b/DNN Platform/Library/Data/DataProvider.cs @@ -1,67 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Data.SqlTypes; -using System.Globalization; -using System.IO; -using System.Text; -using System.Web.Hosting; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Search.Entities; -using Microsoft.ApplicationBlocks.Data; - -#endregion - -// ReSharper disable InconsistentNaming - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable InconsistentNaming namespace DotNetNuke.Data { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Data.Common; + using System.Data.SqlClient; + using System.Data.SqlTypes; + using System.Globalization; + using System.IO; + using System.Text; + using System.Web.Hosting; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Search.Entities; + using Microsoft.ApplicationBlocks.Data; + public abstract class DataProvider { + private const int DuplicateKey = 2601; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataProvider)); - - private const int DuplicateKey = 2601; - - #region Shared/Static Methods - - public static DataProvider Instance() - { - return ComponentFactory.GetComponent(); - } - - #endregion - - #region Public Properties - + public virtual string ConnectionString { get { - //Get Connection string from web.config + // Get Connection string from web.config string connectionString = Config.GetConnectionString(); if (string.IsNullOrEmpty(connectionString)) { - //Use connection string specified in provider - connectionString = Settings["connectionString"]; + // Use connection string specified in provider + connectionString = this.Settings["connectionString"]; } + return connectionString; } } @@ -70,11 +54,12 @@ public virtual string DatabaseOwner { get { - string databaseOwner = Settings["databaseOwner"]; + string databaseOwner = this.Settings["databaseOwner"]; if (!string.IsNullOrEmpty(databaseOwner) && databaseOwner.EndsWith(".") == false) { databaseOwner += "."; } + return databaseOwner; } } @@ -83,6 +68,11 @@ public string DefaultProviderName { get { return Instance().ProviderName; } } + + public static DataProvider Instance() + { + return ComponentFactory.GetComponent(); + } public abstract bool IsConnectionValid { get; } @@ -90,23 +80,24 @@ public virtual string ObjectQualifier { get { - string objectQualifier = Settings["objectQualifier"]; + string objectQualifier = this.Settings["objectQualifier"]; if (!string.IsNullOrEmpty(objectQualifier) && objectQualifier.EndsWith("_") == false) { objectQualifier += "_"; } + return objectQualifier; } } public virtual string ProviderName { - get { return Settings["providerName"]; } + get { return this.Settings["providerName"]; } } public virtual string ProviderPath { - get { return Settings["providerPath"]; } + get { return this.Settings["providerPath"]; } } public abstract Dictionary Settings { get; } @@ -115,25 +106,29 @@ public virtual string UpgradeConnectionString { get { - return !String.IsNullOrEmpty(Settings["upgradeConnectionString"]) - ? Settings["upgradeConnectionString"] - : ConnectionString; + return !string.IsNullOrEmpty(this.Settings["upgradeConnectionString"]) + ? this.Settings["upgradeConnectionString"] + : this.ConnectionString; } - } - - #endregion - - #region Private Methods - + } + + public abstract void ExecuteNonQuery(string procedureName, params object[] commandParameters); + + public abstract void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters); + private static DateTime FixDate(DateTime dateToFix) { - //Fix for Sql Dates having a minimum value of January 1, 1753 + // Fix for Sql Dates having a minimum value of January 1, 1753 // or maximum value of December 31, 9999 - if (dateToFix <= SqlDateTime.MinValue.Value) - dateToFix = SqlDateTime.MinValue.Value.AddDays(1); - else if (dateToFix >= SqlDateTime.MaxValue.Value) - dateToFix = SqlDateTime.MaxValue.Value.AddDays(-1); - + if (dateToFix <= SqlDateTime.MinValue.Value) + { + dateToFix = SqlDateTime.MinValue.Value.AddDays(1); + } + else if (dateToFix >= SqlDateTime.MaxValue.Value) + { + dateToFix = SqlDateTime.MaxValue.Value.AddDays(-1); + } + return dateToFix; } @@ -143,52 +138,46 @@ private object GetRoleNull(int RoleID) { return DBNull.Value; } + return RoleID; - } - - #endregion - - #region Abstract Methods - - #region DAL + Methods - - public abstract void ExecuteNonQuery(string procedureName, params object[] commandParameters); - public abstract void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters); + } public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable); + public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec); + public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters); + public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec, Dictionary commandParameters); public abstract IDataReader ExecuteReader(string procedureName, params object[] commandParameters); + public abstract IDataReader ExecuteReader(int timeoutSec, string procedureName, params object[] commandParameters); public abstract T ExecuteScalar(string procedureName, params object[] commandParameters); + public abstract T ExecuteScalar(int timeoutSec, string procedureName, params object[] commandParameters); public abstract IDataReader ExecuteSQL(string sql); - public abstract IDataReader ExecuteSQL(string sql, int timeoutSec); - - #endregion - - #region ExecuteScript Methods - + + public abstract IDataReader ExecuteSQL(string sql, int timeoutSec); + public abstract string ExecuteScript(string script); + public abstract string ExecuteScript(string script, int timeoutSec); public abstract string ExecuteScript(string connectionString, string sql); + public abstract string ExecuteScript(string connectionString, string sql, int timeoutSec); public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql); + public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec); public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, out string errorMessage); - public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage); - - #endregion - - #region Transaction Methods - + + public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage); + public virtual void CommitTransaction(DbTransaction transaction) { try @@ -206,7 +195,7 @@ public virtual void CommitTransaction(DbTransaction transaction) public virtual DbTransaction GetTransaction() { - var Conn = new SqlConnection(UpgradeConnectionString); + var Conn = new SqlConnection(this.UpgradeConnectionString); Conn.Open(); SqlTransaction transaction = Conn.BeginTransaction(); return transaction; @@ -225,20 +214,16 @@ public virtual void RollbackTransaction(DbTransaction transaction) transaction.Connection.Close(); } } - } - - #endregion - + } + public virtual object GetNull(object Field) { return Null.GetNull(Field, DBNull.Value); - } - - #region Upgrade Methods - + } + public virtual IDataReader FindDatabaseVersion(int Major, int Minor, int Build) { - return ExecuteReader("FindDatabaseVersion", Major, Minor, Build); + return this.ExecuteReader("FindDatabaseVersion", Major, Minor, Build); } public virtual Version GetDatabaseEngineVersion() @@ -247,7 +232,7 @@ public virtual Version GetDatabaseEngineVersion() IDataReader dr = null; try { - dr = ExecuteReader("GetDatabaseServer"); + dr = this.ExecuteReader("GetDatabaseServer"); if (dr.Read()) { version = dr["Version"].ToString(); @@ -257,37 +242,73 @@ public virtual Version GetDatabaseEngineVersion() { CBO.CloseDataReader(dr, true); } + return new Version(version); } public virtual IDataReader GetDatabaseVersion() { - return ExecuteReader("GetDatabaseVersion"); + return this.ExecuteReader("GetDatabaseVersion"); } public virtual IDataReader GetDatabaseInstallVersion() { - return ExecuteReader("GetDatabaseInstallVersion"); + return this.ExecuteReader("GetDatabaseInstallVersion"); } public virtual Version GetVersion() { - return GetVersionInternal(true); + return this.GetVersionInternal(true); } public virtual Version GetInstallVersion() { - return GetVersionInternal(false); + return this.GetVersionInternal(false); + } + + public virtual DbConnectionStringBuilder GetConnectionStringBuilder() + { + return new SqlConnectionStringBuilder(); } + public virtual string GetProviderPath() + { + string path = this.ProviderPath; + if (!string.IsNullOrEmpty(path)) + { + path = HostingEnvironment.MapPath(path); + // ReSharper disable AssignNullToNotNullAttribute + if (Directory.Exists(path)) + + // ReSharper restore AssignNullToNotNullAttribute + { + if (!this.IsConnectionValid) + { + path = "ERROR: Could not connect to database specified in connectionString for SqlDataProvider"; + } + } + else + { + path = "ERROR: providerPath folder " + path + + " specified for SqlDataProvider does not exist on web server"; + } + } + else + { + path = "ERROR: providerPath folder value not specified in web.config for SqlDataProvider"; + } + + return path; + } + private Version GetVersionInternal(bool current) { Version version = null; IDataReader dr = null; try { - dr = current ? GetDatabaseVersion() : GetDatabaseInstallVersion(); + dr = current ? this.GetDatabaseVersion() : this.GetDatabaseInstallVersion(); if (dr.Read()) { version = new Version(Convert.ToInt32(dr["Major"]), Convert.ToInt32(dr["Minor"]), @@ -300,7 +321,7 @@ private Version GetVersionInternal(bool current) for (int i = 0; i <= ex.Errors.Count - 1; i++) { SqlError sqlError = ex.Errors[i]; - if (sqlError.Number == 2812 && sqlError.Class == 16) //2812 - 16 means SP could not be found + if (sqlError.Number == 2812 && sqlError.Class == 16) // 2812 - 16 means SP could not be found { noStoredProc = true; break; @@ -316,43 +337,10 @@ private Version GetVersionInternal(bool current) { CBO.CloseDataReader(dr, true); } + return version; } - public virtual DbConnectionStringBuilder GetConnectionStringBuilder() - { - return new SqlConnectionStringBuilder(); - } - - public virtual string GetProviderPath() - { - string path = ProviderPath; - if (!String.IsNullOrEmpty(path)) - { - path = HostingEnvironment.MapPath(path); - - // ReSharper disable AssignNullToNotNullAttribute - if (Directory.Exists(path)) - // ReSharper restore AssignNullToNotNullAttribute - { - if (!IsConnectionValid) - { - path = "ERROR: Could not connect to database specified in connectionString for SqlDataProvider"; - } - } - else - { - path = "ERROR: providerPath folder " + path + - " specified for SqlDataProvider does not exist on web server"; - } - } - else - { - path = "ERROR: providerPath folder value not specified in web.config for SqlDataProvider"; - } - return path; - } - public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, string Owner, string Qualifier) { var sqlBuilder = builder as SqlConnectionStringBuilder; @@ -380,7 +368,8 @@ public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, bError = false; break; } - string filteredMessage = String.Empty; + + string filteredMessage = string.Empty; switch (sqlError.Number) { case 17: @@ -396,11 +385,13 @@ public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, filteredMessage = "Sql deadlock victim"; break; } + errorMessages.Append("Index #: " + i + "
    " + "Source: " + sqlError.Source + "
    " + "Class: " + sqlError.Class + "
    " + "Number: " + sqlError.Number + "
    " + "Message: " + filteredMessage + "

    "); } + if (bError) { connectionString = message + errorMessages; @@ -411,93 +402,82 @@ public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, CBO.CloseDataReader(dr, true); } } + return connectionString; } public virtual void UpdateDatabaseVersion(int Major, int Minor, int Build, string Name) { - if ((Major >= 5 || (Major == 4 && Minor == 9 && Build > 0))) + if (Major >= 5 || (Major == 4 && Minor == 9 && Build > 0)) { - //If the version > 4.9.0 use the new sproc, which is added in 4.9.1 script - ExecuteNonQuery("UpdateDatabaseVersionAndName", Major, Minor, Build, Name); + // If the version > 4.9.0 use the new sproc, which is added in 4.9.1 script + this.ExecuteNonQuery("UpdateDatabaseVersionAndName", Major, Minor, Build, Name); } else { - ExecuteNonQuery("UpdateDatabaseVersion", Major, Minor, Build); + this.ExecuteNonQuery("UpdateDatabaseVersion", Major, Minor, Build); } } public virtual void UpdateDatabaseVersionIncrement(int Major, int Minor, int Build, int Increment, string AppName) { - ExecuteNonQuery("UpdateDatabaseVersionIncrement", Major, Minor, Build, Increment, AppName); + this.ExecuteNonQuery("UpdateDatabaseVersionIncrement", Major, Minor, Build, Increment, AppName); } public virtual int GetLastAppliedIteration(int Major, int Minor, int Build) { - return ExecuteScalar("GetLastAppliedIteration", Major, Minor, Build); + return this.ExecuteScalar("GetLastAppliedIteration", Major, Minor, Build); } public virtual string GetUnappliedIterations(string version) { - return ExecuteScalar("GetUnappliedIterations", version); - } - - #endregion - - #region Host Settings Methods - + return this.ExecuteScalar("GetUnappliedIterations", version); + } + public virtual IDataReader GetHostSetting(string SettingName) { - return ExecuteReader("GetHostSetting", SettingName); + return this.ExecuteReader("GetHostSetting", SettingName); } public virtual IDataReader GetHostSettings() { - return ExecuteReader("GetHostSettings"); + return this.ExecuteReader("GetHostSettings"); } public virtual void UpdateHostSetting(string SettingName, string SettingValue, bool SettingIsSecure, int LastModifiedByUserID) { - ExecuteNonQuery("UpdateHostSetting", SettingName, SettingValue, SettingIsSecure, LastModifiedByUserID); - } - - #endregion - - #region Server Methods - + this.ExecuteNonQuery("UpdateHostSetting", SettingName, SettingValue, SettingIsSecure, LastModifiedByUserID); + } + public virtual void DeleteServer(int ServerId) { - ExecuteNonQuery("DeleteServer", ServerId); + this.ExecuteNonQuery("DeleteServer", ServerId); } public virtual IDataReader GetServers() { - return ExecuteReader("GetServers"); + return this.ExecuteReader("GetServers"); } public virtual void UpdateServer(int serverId, string url, string uniqueId, bool enabled, string group) { - ExecuteNonQuery("UpdateServer", serverId, url, uniqueId, enabled, group); + this.ExecuteNonQuery("UpdateServer", serverId, url, uniqueId, enabled, group); } public virtual int UpdateServerActivity(string serverName, string iisAppName, DateTime createdDate, DateTime lastActivityDate, int pingFailureCount, bool enabled) { - return ExecuteScalar("UpdateServerActivity", serverName, iisAppName, createdDate, lastActivityDate, pingFailureCount, enabled); - } - - #endregion - - #region Portal Methods - + return this.ExecuteScalar("UpdateServerActivity", serverName, iisAppName, createdDate, lastActivityDate, pingFailureCount, enabled); + } + [Obsolete("Deprecated in Platform 7.4.0, please use CreatePortal version that contain's culturecode. Scheduled removal in v10.0.0.")] public virtual int CreatePortal(string portalname, string currency, DateTime ExpiryDate, double HostFee, double HostSpace, int PageQuota, int UserQuota, int SiteLogHistory, - string HomeDirectory, int CreatedByUserID) + string HomeDirectory, int CreatedByUserID) { return - CreatePortal( + this.CreatePortal( PortalSecurity.Instance.InputFilter(portalname, PortalSecurity.FilterFlag.NoMarkup), currency, ExpiryDate, @@ -513,41 +493,42 @@ public virtual int CreatePortal(string portalname, string currency, DateTime Exp public virtual int CreatePortal(string portalname, string currency, DateTime ExpiryDate, double HostFee, double HostSpace, int PageQuota, int UserQuota, int SiteLogHistory, - string HomeDirectory, string CultureCode, int CreatedByUserID) + string HomeDirectory, string CultureCode, int CreatedByUserID) { return - ExecuteScalar("AddPortalInfo", - PortalSecurity.Instance.InputFilter(portalname, PortalSecurity.FilterFlag.NoMarkup), - currency, - GetNull(ExpiryDate), - HostFee, - HostSpace, - PageQuota, - UserQuota, - GetNull(SiteLogHistory), - HomeDirectory, - CultureCode, - CreatedByUserID); + this.ExecuteScalar( + "AddPortalInfo", + PortalSecurity.Instance.InputFilter(portalname, PortalSecurity.FilterFlag.NoMarkup), + currency, + this.GetNull(ExpiryDate), + HostFee, + HostSpace, + PageQuota, + UserQuota, + this.GetNull(SiteLogHistory), + HomeDirectory, + CultureCode, + CreatedByUserID); } public virtual void DeletePortalInfo(int PortalId) { - ExecuteNonQuery("DeletePortalInfo", PortalId); + this.ExecuteNonQuery("DeletePortalInfo", PortalId); } public virtual void DeletePortalSetting(int PortalId, string SettingName, string CultureCode) { - ExecuteNonQuery("DeletePortalSetting", PortalId, SettingName, CultureCode); + this.ExecuteNonQuery("DeletePortalSetting", PortalId, SettingName, CultureCode); } public virtual void DeletePortalSettings(int PortalId, string CultureCode) { - ExecuteNonQuery("DeletePortalSettings", PortalId, CultureCode); + this.ExecuteNonQuery("DeletePortalSettings", PortalId, CultureCode); } public virtual IDataReader GetExpiredPortals() { - return ExecuteReader("GetExpiredPortals"); + return this.ExecuteReader("GetExpiredPortals"); } public virtual IDataReader GetPortals(string CultureCode) @@ -555,52 +536,39 @@ public virtual IDataReader GetPortals(string CultureCode) IDataReader reader; if (Globals.Status == Globals.UpgradeStatus.Upgrade && Globals.DataBaseVersion < new Version(6, 1, 0)) { - reader = ExecuteReader("GetPortals"); + reader = this.ExecuteReader("GetPortals"); } else { - reader = ExecuteReader("GetPortals", CultureCode); + reader = this.ExecuteReader("GetPortals", CultureCode); } + return reader; } public virtual IDataReader GetAllPortals() { - return ExecuteReader("GetAllPortals"); + return this.ExecuteReader("GetAllPortals"); } public virtual IDataReader GetPortalsByName(string nameToMatch, int pageIndex, int pageSize) { - return ExecuteReader("GetPortalsByName", nameToMatch, pageIndex, pageSize); + return this.ExecuteReader("GetPortalsByName", nameToMatch, pageIndex, pageSize); } public virtual IDataReader GetPortalsByUser(int userId) { - return ExecuteReader("GetPortalsByUser", userId); + return this.ExecuteReader("GetPortalsByUser", userId); } - - + public virtual IDataReader GetPortalSettings(int PortalId, string CultureCode) { - return ExecuteReader("GetPortalSettings", PortalId, CultureCode); - } - - internal virtual IDictionary GetPortalSettingsBySetting(string settingName, string cultureCode) - { - var result = new Dictionary(); - using (var reader = ExecuteReader("GetPortalSettingsBySetting", settingName, cultureCode)) - { - while (reader.Read()) - { - result[reader.GetInt32(0)] = reader.GetString(1); - } - } - return result; + return this.ExecuteReader("GetPortalSettings", PortalId, CultureCode); } public virtual IDataReader GetPortalSpaceUsed(int PortalId) { - return ExecuteReader("GetPortalSpaceUsed", GetNull(PortalId)); + return this.ExecuteReader("GetPortalSpaceUsed", this.GetNull(PortalId)); } /// @@ -651,48 +619,63 @@ public virtual void UpdatePortalInfo(int portalId, int portalGroupId, string por int termsTabId, int privacyTabId, string defaultLanguage, string homeDirectory, int lastModifiedByUserID, string cultureCode) { - ExecuteNonQuery("UpdatePortalInfo", - portalId, - portalGroupId, - PortalSecurity.Instance.InputFilter(portalName, PortalSecurity.FilterFlag.NoMarkup), - GetNull(logoFile), - GetNull(footerText), - GetNull(expiryDate), - userRegistration, - bannerAdvertising, - currency, - GetNull(administratorId), - hostFee, - hostSpace, - pageQuota, - userQuota, - GetNull(paymentProcessor), - GetNull(processorUserId), - GetNull(processorPassword), - GetNull(description), - GetNull(keyWords), - GetNull(backgroundFile), - GetNull(siteLogHistory), - GetNull(splashTabId), - GetNull(homeTabId), - GetNull(loginTabId), - GetNull(registerTabId), - GetNull(userTabId), - GetNull(searchTabId), - GetNull(custom404TabId), - GetNull(custom500TabId), - GetNull(termsTabId), - GetNull(privacyTabId), - GetNull(defaultLanguage), - homeDirectory, - lastModifiedByUserID, - cultureCode); + this.ExecuteNonQuery( + "UpdatePortalInfo", + portalId, + portalGroupId, + PortalSecurity.Instance.InputFilter(portalName, PortalSecurity.FilterFlag.NoMarkup), + this.GetNull(logoFile), + this.GetNull(footerText), + this.GetNull(expiryDate), + userRegistration, + bannerAdvertising, + currency, + this.GetNull(administratorId), + hostFee, + hostSpace, + pageQuota, + userQuota, + this.GetNull(paymentProcessor), + this.GetNull(processorUserId), + this.GetNull(processorPassword), + this.GetNull(description), + this.GetNull(keyWords), + this.GetNull(backgroundFile), + this.GetNull(siteLogHistory), + this.GetNull(splashTabId), + this.GetNull(homeTabId), + this.GetNull(loginTabId), + this.GetNull(registerTabId), + this.GetNull(userTabId), + this.GetNull(searchTabId), + this.GetNull(custom404TabId), + this.GetNull(custom500TabId), + this.GetNull(termsTabId), + this.GetNull(privacyTabId), + this.GetNull(defaultLanguage), + homeDirectory, + lastModifiedByUserID, + cultureCode); + } + + internal virtual IDictionary GetPortalSettingsBySetting(string settingName, string cultureCode) + { + var result = new Dictionary(); + using (var reader = this.ExecuteReader("GetPortalSettingsBySetting", settingName, cultureCode)) + { + while (reader.Read()) + { + result[reader.GetInt32(0)] = reader.GetString(1); + } + } + + return result; } public virtual void UpdatePortalSetting(int portalId, string settingName, string settingValue, int userId, string cultureCode, bool isSecure) { - ExecuteNonQuery("UpdatePortalSetting", portalId, settingName, settingValue, userId, cultureCode, isSecure); + this.ExecuteNonQuery("UpdatePortalSetting", portalId, settingName, settingValue, userId, cultureCode, isSecure); } public virtual void UpdatePortalSetup(int portalId, int administratorId, int administratorRoleId, @@ -701,305 +684,303 @@ public virtual void UpdatePortalSetup(int portalId, int administratorId, int adm int userTabId, int searchTabId, int custom404TabId, int custom500TabId, int termsTabId, int privacyTabId, int adminTabId, string cultureCode) { - ExecuteNonQuery("UpdatePortalSetup", - portalId, - administratorId, - administratorRoleId, - registeredRoleId, - splashTabId, - homeTabId, - loginTabId, - registerTabId, - userTabId, - searchTabId, - custom404TabId, - custom500TabId, - termsTabId, - privacyTabId, - adminTabId, - cultureCode); - } - - #endregion - - #region Tab Methods - - + this.ExecuteNonQuery( + "UpdatePortalSetup", + portalId, + administratorId, + administratorRoleId, + registeredRoleId, + splashTabId, + homeTabId, + loginTabId, + registerTabId, + userTabId, + searchTabId, + custom404TabId, + custom500TabId, + termsTabId, + privacyTabId, + adminTabId, + cultureCode); + } + public virtual int AddTabAfter(TabInfo tab, int afterTabId, int createdByUserID) { - return ExecuteScalar("AddTabAfter", - afterTabId, - tab.ContentItemId, - GetNull(tab.PortalID), - tab.UniqueId, - tab.VersionGuid, - GetNull(tab.DefaultLanguageGuid), - tab.LocalizedVersionGuid, - tab.TabName, - tab.IsVisible, - tab.DisableLink, - GetNull(tab.ParentId), - tab.IconFile, - tab.IconFileLarge, - tab.Title, - tab.Description, - tab.KeyWords, - tab.Url, - GetNull(tab.SkinSrc), - GetNull(tab.ContainerSrc), - GetNull(tab.StartDate), - GetNull(tab.EndDate), - GetNull(tab.RefreshInterval), - GetNull(tab.PageHeadText), - tab.IsSecure, - tab.PermanentRedirect, - tab.SiteMapPriority, - createdByUserID, - GetNull(tab.CultureCode), - tab.IsSystem); + return this.ExecuteScalar( + "AddTabAfter", + afterTabId, + tab.ContentItemId, + this.GetNull(tab.PortalID), + tab.UniqueId, + tab.VersionGuid, + this.GetNull(tab.DefaultLanguageGuid), + tab.LocalizedVersionGuid, + tab.TabName, + tab.IsVisible, + tab.DisableLink, + this.GetNull(tab.ParentId), + tab.IconFile, + tab.IconFileLarge, + tab.Title, + tab.Description, + tab.KeyWords, + tab.Url, + this.GetNull(tab.SkinSrc), + this.GetNull(tab.ContainerSrc), + this.GetNull(tab.StartDate), + this.GetNull(tab.EndDate), + this.GetNull(tab.RefreshInterval), + this.GetNull(tab.PageHeadText), + tab.IsSecure, + tab.PermanentRedirect, + tab.SiteMapPriority, + createdByUserID, + this.GetNull(tab.CultureCode), + tab.IsSystem); } public virtual int AddTabBefore(TabInfo tab, int beforeTabId, int createdByUserID) { - return ExecuteScalar("AddTabBefore", - beforeTabId, - tab.ContentItemId, - GetNull(tab.PortalID), - tab.UniqueId, - tab.VersionGuid, - GetNull(tab.DefaultLanguageGuid), - tab.LocalizedVersionGuid, - tab.TabName, - tab.IsVisible, - tab.DisableLink, - GetNull(tab.ParentId), - tab.IconFile, - tab.IconFileLarge, - tab.Title, - tab.Description, - tab.KeyWords, - tab.Url, - GetNull(tab.SkinSrc), - GetNull(tab.ContainerSrc), - GetNull(tab.StartDate), - GetNull(tab.EndDate), - GetNull(tab.RefreshInterval), - GetNull(tab.PageHeadText), - tab.IsSecure, - tab.PermanentRedirect, - tab.SiteMapPriority, - createdByUserID, - GetNull(tab.CultureCode), - tab.IsSystem); - } - - + return this.ExecuteScalar( + "AddTabBefore", + beforeTabId, + tab.ContentItemId, + this.GetNull(tab.PortalID), + tab.UniqueId, + tab.VersionGuid, + this.GetNull(tab.DefaultLanguageGuid), + tab.LocalizedVersionGuid, + tab.TabName, + tab.IsVisible, + tab.DisableLink, + this.GetNull(tab.ParentId), + tab.IconFile, + tab.IconFileLarge, + tab.Title, + tab.Description, + tab.KeyWords, + tab.Url, + this.GetNull(tab.SkinSrc), + this.GetNull(tab.ContainerSrc), + this.GetNull(tab.StartDate), + this.GetNull(tab.EndDate), + this.GetNull(tab.RefreshInterval), + this.GetNull(tab.PageHeadText), + tab.IsSecure, + tab.PermanentRedirect, + tab.SiteMapPriority, + createdByUserID, + this.GetNull(tab.CultureCode), + tab.IsSystem); + } + public virtual int AddTabToEnd(TabInfo tab, int createdByUserID) { - return ExecuteScalar("AddTabToEnd", - tab.ContentItemId, - GetNull(tab.PortalID), - tab.UniqueId, - tab.VersionGuid, - GetNull(tab.DefaultLanguageGuid), - tab.LocalizedVersionGuid, - tab.TabName, - tab.IsVisible, - tab.DisableLink, - GetNull(tab.ParentId), - tab.IconFile, - tab.IconFileLarge, - tab.Title, - tab.Description, - tab.KeyWords, - tab.Url, - GetNull(tab.SkinSrc), - GetNull(tab.ContainerSrc), - GetNull(tab.StartDate), - GetNull(tab.EndDate), - GetNull(tab.RefreshInterval), - GetNull(tab.PageHeadText), - tab.IsSecure, - tab.PermanentRedirect, - tab.SiteMapPriority, - createdByUserID, - GetNull(tab.CultureCode), - tab.IsSystem); + return this.ExecuteScalar( + "AddTabToEnd", + tab.ContentItemId, + this.GetNull(tab.PortalID), + tab.UniqueId, + tab.VersionGuid, + this.GetNull(tab.DefaultLanguageGuid), + tab.LocalizedVersionGuid, + tab.TabName, + tab.IsVisible, + tab.DisableLink, + this.GetNull(tab.ParentId), + tab.IconFile, + tab.IconFileLarge, + tab.Title, + tab.Description, + tab.KeyWords, + tab.Url, + this.GetNull(tab.SkinSrc), + this.GetNull(tab.ContainerSrc), + this.GetNull(tab.StartDate), + this.GetNull(tab.EndDate), + this.GetNull(tab.RefreshInterval), + this.GetNull(tab.PageHeadText), + tab.IsSecure, + tab.PermanentRedirect, + tab.SiteMapPriority, + createdByUserID, + this.GetNull(tab.CultureCode), + tab.IsSystem); } public virtual void DeleteTab(int tabId) { - ExecuteNonQuery("DeleteTab", tabId); + this.ExecuteNonQuery("DeleteTab", tabId); } public virtual void DeleteTabSetting(int TabId, string SettingName) { - ExecuteNonQuery("DeleteTabSetting", TabId, SettingName); + this.ExecuteNonQuery("DeleteTabSetting", TabId, SettingName); } public virtual void DeleteTabSettings(int TabId) { - ExecuteNonQuery("DeleteTabSettings", TabId); + this.ExecuteNonQuery("DeleteTabSettings", TabId); } public virtual void DeleteTabUrl(int tabId, int seqNum) { - ExecuteNonQuery("DeleteTabUrl", tabId, seqNum); + this.ExecuteNonQuery("DeleteTabUrl", tabId, seqNum); } public virtual void DeleteTabVersion(int tabVersionId) { - ExecuteNonQuery("DeleteTabVersion", tabVersionId); + this.ExecuteNonQuery("DeleteTabVersion", tabVersionId); } public virtual void DeleteTabVersionDetail(int tabVersionDetailId) { - ExecuteNonQuery("DeleteTabVersionDetail", tabVersionDetailId); + this.ExecuteNonQuery("DeleteTabVersionDetail", tabVersionDetailId); } public virtual void DeleteTabVersionDetailByModule(int moduleId) { - ExecuteNonQuery("DeleteTabVersionDetailByModule", moduleId); + this.ExecuteNonQuery("DeleteTabVersionDetailByModule", moduleId); } public virtual void DeleteTranslatedTabs(int tabId, string cultureCode) { - ExecuteNonQuery("DeleteTranslatedTabs", tabId, cultureCode); + this.ExecuteNonQuery("DeleteTranslatedTabs", tabId, cultureCode); } public virtual void EnsureNeutralLanguage(int portalId, string cultureCode) { - ExecuteNonQuery("EnsureNeutralLanguage", portalId, cultureCode); + this.ExecuteNonQuery("EnsureNeutralLanguage", portalId, cultureCode); } public virtual void ConvertTabToNeutralLanguage(int portalId, int tabId, string cultureCode) { - ExecuteNonQuery("ConvertTabToNeutralLanguage", portalId, tabId, cultureCode); + this.ExecuteNonQuery("ConvertTabToNeutralLanguage", portalId, tabId, cultureCode); } public virtual IDataReader GetAllTabs() { - return ExecuteReader("GetAllTabs"); + return this.ExecuteReader("GetAllTabs"); } public virtual IDataReader GetTab(int tabId) { - return ExecuteReader("GetTab", tabId); + return this.ExecuteReader("GetTab", tabId); } public virtual IDataReader GetTabByUniqueID(Guid uniqueId) { - return ExecuteReader("GetTabByUniqueID", uniqueId); + return this.ExecuteReader("GetTabByUniqueID", uniqueId); } public virtual IDataReader GetTabPanes(int tabId) { - return ExecuteReader("GetTabPanes", tabId); + return this.ExecuteReader("GetTabPanes", tabId); } public virtual IDataReader GetTabPaths(int portalId, string cultureCode) { - return ExecuteReader("GetTabPaths", GetNull(portalId), cultureCode); + return this.ExecuteReader("GetTabPaths", this.GetNull(portalId), cultureCode); } public virtual IDataReader GetTabs(int portalId) { - return ExecuteReader("GetTabs", GetNull(portalId)); + return this.ExecuteReader("GetTabs", this.GetNull(portalId)); } public virtual IDataReader GetTabsByModuleID(int moduleID) { - return ExecuteReader("GetTabsByModuleID", moduleID); + return this.ExecuteReader("GetTabsByModuleID", moduleID); } public virtual IDataReader GetTabsByTabModuleID(int tabModuleID) { - return ExecuteReader("GetTabsByTabModuleID", tabModuleID); + return this.ExecuteReader("GetTabsByTabModuleID", tabModuleID); } public virtual IDataReader GetTabsByPackageID(int portalID, int packageID, bool forHost) { - return ExecuteReader("GetTabsByPackageID", GetNull(portalID), packageID, forHost); + return this.ExecuteReader("GetTabsByPackageID", this.GetNull(portalID), packageID, forHost); } public virtual IDataReader GetTabSetting(int TabID, string SettingName) { - return ExecuteReader("GetTabSetting", TabID, SettingName); + return this.ExecuteReader("GetTabSetting", TabID, SettingName); } public virtual IDataReader GetTabSettings(int portalId) { - return ExecuteReader("GetTabSettings", GetNull(portalId)); + return this.ExecuteReader("GetTabSettings", this.GetNull(portalId)); } public virtual IDataReader GetTabAliasSkins(int portalId) { - return ExecuteReader("GetTabAliasSkins", GetNull(portalId)); + return this.ExecuteReader("GetTabAliasSkins", this.GetNull(portalId)); } public virtual IDataReader GetTabCustomAliases(int portalId) { - return ExecuteReader("GetTabCustomAliases", GetNull(portalId)); + return this.ExecuteReader("GetTabCustomAliases", this.GetNull(portalId)); } public virtual IDataReader GetTabUrls(int portalId) { - return ExecuteReader("GetTabUrls", GetNull(portalId)); + return this.ExecuteReader("GetTabUrls", this.GetNull(portalId)); } public virtual IDataReader GetTabVersions(int tabId) { - return ExecuteReader("GetTabVersions", GetNull(tabId)); + return this.ExecuteReader("GetTabVersions", this.GetNull(tabId)); } public virtual IDataReader GetTabVersionDetails(int tabVersionId) { - return ExecuteReader("GetTabVersionDetails", GetNull(tabVersionId)); + return this.ExecuteReader("GetTabVersionDetails", this.GetNull(tabVersionId)); } public virtual IDataReader GetTabVersionDetailsHistory(int tabId, int version) { - return ExecuteReader("GetTabVersionDetailsHistory", GetNull(tabId), GetNull(version)); + return this.ExecuteReader("GetTabVersionDetailsHistory", this.GetNull(tabId), this.GetNull(version)); } public virtual IDataReader GetCustomAliasesForTabs() { - return ExecuteReader("GetCustomAliasesForTabs"); + return this.ExecuteReader("GetCustomAliasesForTabs"); } public virtual void LocalizeTab(int tabId, string cultureCode, int lastModifiedByUserID) { - ExecuteNonQuery("LocalizeTab", tabId, cultureCode, lastModifiedByUserID); + this.ExecuteNonQuery("LocalizeTab", tabId, cultureCode, lastModifiedByUserID); } public virtual void MoveTabAfter(int tabId, int afterTabId, int lastModifiedByUserID) { - ExecuteNonQuery("MoveTabAfter", tabId, afterTabId, lastModifiedByUserID); + this.ExecuteNonQuery("MoveTabAfter", tabId, afterTabId, lastModifiedByUserID); } public virtual void MoveTabBefore(int tabId, int beforeTabId, int lastModifiedByUserID) { - ExecuteNonQuery("MoveTabBefore", tabId, beforeTabId, lastModifiedByUserID); + this.ExecuteNonQuery("MoveTabBefore", tabId, beforeTabId, lastModifiedByUserID); } public virtual void MoveTabToParent(int tabId, int parentId, int lastModifiedByUserID) { - ExecuteNonQuery("MoveTabToParent", tabId, GetNull(parentId), lastModifiedByUserID); + this.ExecuteNonQuery("MoveTabToParent", tabId, this.GetNull(parentId), lastModifiedByUserID); } public virtual void SaveTabUrl(int tabId, int seqNum, int portalAliasId, int portalAliasUsage, string url, string queryString, string cultureCode, string httpStatus, bool isSystem, int modifiedByUserID) { - ExecuteNonQuery("SaveTabUrl", tabId, seqNum, GetNull(portalAliasId), portalAliasUsage, url, queryString, cultureCode, httpStatus, isSystem, modifiedByUserID); + this.ExecuteNonQuery("SaveTabUrl", tabId, seqNum, this.GetNull(portalAliasId), portalAliasUsage, url, queryString, cultureCode, httpStatus, isSystem, modifiedByUserID); } public virtual int SaveTabVersion(int tabVersionId, int tabId, DateTime timeStamp, int version, bool isPublished, int createdByUserID, int modifiedByUserID) { - return ExecuteScalar("SaveTabVersion", tabVersionId, tabId, timeStamp, version, isPublished, createdByUserID, modifiedByUserID); + return this.ExecuteScalar("SaveTabVersion", tabVersionId, tabId, timeStamp, version, isPublished, createdByUserID, modifiedByUserID); } public virtual int SaveTabVersionDetail(int tabVersionDetailId, int tabVersionId, int moduleId, int moduleVersion, string paneName, int moduleOrder, int action, int createdByUserID, int modifiedByUserID) { - return ExecuteScalar("SaveTabVersionDetail", tabVersionDetailId, tabVersionId, moduleId, moduleVersion, paneName, moduleOrder, action, createdByUserID, modifiedByUserID); + return this.ExecuteScalar("SaveTabVersionDetail", tabVersionDetailId, tabVersionId, moduleId, moduleVersion, paneName, moduleOrder, action, createdByUserID, modifiedByUserID); } public virtual void UpdateTab(int tabId, int contentItemId, int portalId, Guid versionGuid, @@ -1012,88 +993,85 @@ public virtual void UpdateTab(int tabId, int contentItemId, int portalId, Guid v bool permanentRedirect, float siteMapPriority, int lastModifiedByuserID, string cultureCode, bool IsSystem) { - ExecuteNonQuery("UpdateTab", - tabId, - contentItemId, - GetNull(portalId), - versionGuid, - GetNull(defaultLanguageGuid), - localizedVersionGuid, - tabName, - isVisible, - disableLink, - GetNull(parentId), - iconFile, - iconFileLarge, - title, - description, - keyWords, - isDeleted, - url, - GetNull(skinSrc), - GetNull(containerSrc), - GetNull(startDate), - GetNull(endDate), - GetNull(refreshInterval), - GetNull(pageHeadText), - isSecure, - permanentRedirect, - siteMapPriority, - lastModifiedByuserID, - GetNull(cultureCode), - IsSystem); + this.ExecuteNonQuery( + "UpdateTab", + tabId, + contentItemId, + this.GetNull(portalId), + versionGuid, + this.GetNull(defaultLanguageGuid), + localizedVersionGuid, + tabName, + isVisible, + disableLink, + this.GetNull(parentId), + iconFile, + iconFileLarge, + title, + description, + keyWords, + isDeleted, + url, + this.GetNull(skinSrc), + this.GetNull(containerSrc), + this.GetNull(startDate), + this.GetNull(endDate), + this.GetNull(refreshInterval), + this.GetNull(pageHeadText), + isSecure, + permanentRedirect, + siteMapPriority, + lastModifiedByuserID, + this.GetNull(cultureCode), + IsSystem); } public virtual void UpdateTabOrder(int tabId, int tabOrder, int parentId, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateTabOrder", tabId, tabOrder, GetNull(parentId), lastModifiedByUserID); + this.ExecuteNonQuery("UpdateTabOrder", tabId, tabOrder, this.GetNull(parentId), lastModifiedByUserID); } public virtual void UpdateTabSetting(int TabId, string SettingName, string SettingValue, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateTabSetting", TabId, SettingName, SettingValue, lastModifiedByUserID); + this.ExecuteNonQuery("UpdateTabSetting", TabId, SettingName, SettingValue, lastModifiedByUserID); } public virtual void UpdateTabTranslationStatus(int tabId, Guid localizedVersionGuid, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateTabTranslationStatus", tabId, localizedVersionGuid, lastModifiedByUserID); + this.ExecuteNonQuery("UpdateTabTranslationStatus", tabId, localizedVersionGuid, lastModifiedByUserID); } public virtual void MarkAsPublished(int tabId) { - ExecuteNonQuery("PublishTab", tabId); + this.ExecuteNonQuery("PublishTab", tabId); } public virtual void UpdateTabVersion(int tabId, Guid versionGuid) { - ExecuteNonQuery("UpdateTabVersion", tabId, versionGuid); - } - - #endregion - - #region Module Methods - + this.ExecuteNonQuery("UpdateTabVersion", tabId, versionGuid); + } + public virtual int AddModule(int contentItemId, int portalId, int moduleDefId, bool allTabs, DateTime startDate, DateTime endDate, bool inheritViewPermissions, bool isShareable, bool isShareableViewOnly, - bool isDeleted, int createdByUserID) - { - return ExecuteScalar("AddModule", - contentItemId, - GetNull(portalId), - moduleDefId, - allTabs, - GetNull(startDate), - GetNull(endDate), - inheritViewPermissions, - isShareable, - isShareableViewOnly, - isDeleted, - createdByUserID); + bool isDeleted, int createdByUserID) + { + return this.ExecuteScalar( + "AddModule", + contentItemId, + this.GetNull(portalId), + moduleDefId, + allTabs, + this.GetNull(startDate), + this.GetNull(endDate), + inheritViewPermissions, + isShareable, + isShareableViewOnly, + isDeleted, + createdByUserID); } - - + public virtual void AddTabModule(int TabId, int ModuleId, string ModuleTitle, string Header, string Footer, int ModuleOrder, string PaneName, int CacheTime, string CacheMethod, string Alignment, string Color, string Border, string IconFile, int Visibility, @@ -1103,208 +1081,209 @@ public virtual void AddTabModule(int TabId, int ModuleId, string ModuleTitle, st Guid DefaultLanguageGuid, Guid LocalizedVersionGuid, string CultureCode, int createdByUserID) { - ExecuteNonQuery("AddTabModule", - TabId, - ModuleId, - ModuleTitle, - GetNull(Header), - GetNull(Footer), - ModuleOrder, - PaneName, - CacheTime, - GetNull(CacheMethod), - GetNull(Alignment), - GetNull(Color), - GetNull(Border), - GetNull(IconFile), - Visibility, - GetNull(ContainerSrc), - DisplayTitle, - DisplayPrint, - DisplaySyndicate, - IsWebSlice, - WebSliceTitle, - GetNull(WebSliceExpiryDate), - WebSliceTTL, - UniqueId, - VersionGuid, - GetNull(DefaultLanguageGuid), - LocalizedVersionGuid, - CultureCode, - createdByUserID); - } - - + this.ExecuteNonQuery( + "AddTabModule", + TabId, + ModuleId, + ModuleTitle, + this.GetNull(Header), + this.GetNull(Footer), + ModuleOrder, + PaneName, + CacheTime, + this.GetNull(CacheMethod), + this.GetNull(Alignment), + this.GetNull(Color), + this.GetNull(Border), + this.GetNull(IconFile), + Visibility, + this.GetNull(ContainerSrc), + DisplayTitle, + DisplayPrint, + DisplaySyndicate, + IsWebSlice, + WebSliceTitle, + this.GetNull(WebSliceExpiryDate), + WebSliceTTL, + UniqueId, + VersionGuid, + this.GetNull(DefaultLanguageGuid), + LocalizedVersionGuid, + CultureCode, + createdByUserID); + } + public virtual void DeleteModule(int moduleId) { - ExecuteNonQuery("DeleteModule", moduleId); + this.ExecuteNonQuery("DeleteModule", moduleId); } public virtual void DeleteModuleSetting(int moduleId, string settingName) { - ExecuteNonQuery("DeleteModuleSetting", moduleId, settingName); + this.ExecuteNonQuery("DeleteModuleSetting", moduleId, settingName); } public virtual void DeleteModuleSettings(int moduleId) { - ExecuteNonQuery("DeleteModuleSettings", moduleId); + this.ExecuteNonQuery("DeleteModuleSettings", moduleId); } public virtual void DeleteTabModule(int tabId, int moduleId, bool softDelete, int lastModifiedByUserId = -1) { - ExecuteNonQuery("DeleteTabModule", tabId, moduleId, softDelete, lastModifiedByUserId); + this.ExecuteNonQuery("DeleteTabModule", tabId, moduleId, softDelete, lastModifiedByUserId); } public virtual void DeleteTabModuleSetting(int tabModuleId, string settingName) { - ExecuteNonQuery("DeleteTabModuleSetting", tabModuleId, settingName); + this.ExecuteNonQuery("DeleteTabModuleSetting", tabModuleId, settingName); } public virtual void DeleteTabModuleSettings(int tabModuleId) { - ExecuteNonQuery("DeleteTabModuleSettings", tabModuleId); + this.ExecuteNonQuery("DeleteTabModuleSettings", tabModuleId); } public virtual IDataReader GetTabModuleSettingsByName(int portalId, string settingName) { - return ExecuteReader("GetTabModuleSettingsByName", portalId, settingName); + return this.ExecuteReader("GetTabModuleSettingsByName", portalId, settingName); } public virtual IDataReader GetTabModuleIdsBySettingNameAndValue(int portalId, string settingName, string expectedValue) { - return ExecuteReader("GetTabModuleIdsBySettingNameAndValue", portalId, settingName, expectedValue); + return this.ExecuteReader("GetTabModuleIdsBySettingNameAndValue", portalId, settingName, expectedValue); } public virtual IDataReader GetAllModules() { - return ExecuteReader("GetAllModules"); + return this.ExecuteReader("GetAllModules"); } public virtual IDataReader GetAllTabsModules(int portalId, bool allTabs) { - return ExecuteReader("GetAllTabsModules", portalId, allTabs); + return this.ExecuteReader("GetAllTabsModules", portalId, allTabs); } public virtual IDataReader GetAllTabsModulesByModuleID(int moduleId) { - return ExecuteReader("GetAllTabsModulesByModuleID", moduleId); + return this.ExecuteReader("GetAllTabsModulesByModuleID", moduleId); } public virtual IDataReader GetModule(int moduleId, int tabId) { - return ExecuteReader("GetModule", moduleId, GetNull(tabId)); + return this.ExecuteReader("GetModule", moduleId, this.GetNull(tabId)); } public virtual IDataReader GetModuleByDefinition(int portalId, string definitionName) { - return ExecuteReader("GetModuleByDefinition", GetNull(portalId), definitionName); + return this.ExecuteReader("GetModuleByDefinition", this.GetNull(portalId), definitionName); } public virtual IDataReader GetModuleByUniqueID(Guid uniqueId) { - return ExecuteReader("GetModuleByUniqueID", uniqueId); + return this.ExecuteReader("GetModuleByUniqueID", uniqueId); } public virtual IDataReader GetModules(int portalId) { - return ExecuteReader("GetModules", portalId); + return this.ExecuteReader("GetModules", portalId); } public virtual IDataReader GetModuleSetting(int moduleId, string settingName) { - return ExecuteReader("GetModuleSetting", moduleId, settingName); + return this.ExecuteReader("GetModuleSetting", moduleId, settingName); } public virtual IDataReader GetModuleSettings(int moduleId) { - return ExecuteReader("GetModuleSettings", moduleId); + return this.ExecuteReader("GetModuleSettings", moduleId); } public virtual IDataReader GetModuleSettingsByTab(int tabId) { - return ExecuteReader("GetModuleSettingsByTab", tabId); + return this.ExecuteReader("GetModuleSettingsByTab", tabId); } public virtual IDataReader GetSearchModules(int portalId) { - return ExecuteReader("GetSearchModules", GetNull(portalId)); + return this.ExecuteReader("GetSearchModules", this.GetNull(portalId)); } public virtual IDataReader GetTabModule(int tabModuleId) { - return ExecuteReader("GetTabModule", tabModuleId); + return this.ExecuteReader("GetTabModule", tabModuleId); } public virtual IDataReader GetTabModuleOrder(int tabId, string paneName) { - return ExecuteReader("GetTabModuleOrder", tabId, paneName); + return this.ExecuteReader("GetTabModuleOrder", tabId, paneName); } public virtual IDataReader GetTabModules(int tabId) { - return ExecuteReader("GetTabModules", tabId); + return this.ExecuteReader("GetTabModules", tabId); } public virtual IDataReader GetTabModuleSetting(int tabModuleId, string settingName) { - return ExecuteReader("GetTabModuleSetting", tabModuleId, settingName); + return this.ExecuteReader("GetTabModuleSetting", tabModuleId, settingName); } public virtual IDataReader GetTabModuleSettings(int tabModuleId) { - return ExecuteReader("GetTabModuleSettings", tabModuleId); + return this.ExecuteReader("GetTabModuleSettings", tabModuleId); } public virtual IDataReader GetTabModuleSettingsByTab(int tabId) { - return ExecuteReader("GetTabModuleSettingsByTab", tabId); + return this.ExecuteReader("GetTabModuleSettingsByTab", tabId); } public virtual void MoveTabModule(int fromTabId, int moduleId, int toTabId, string toPaneName, int lastModifiedByUserID) { - ExecuteNonQuery("MoveTabModule", fromTabId, moduleId, toTabId, toPaneName, lastModifiedByUserID); + this.ExecuteNonQuery("MoveTabModule", fromTabId, moduleId, toTabId, toPaneName, lastModifiedByUserID); } public virtual void RestoreTabModule(int tabId, int moduleId) { - ExecuteNonQuery("RestoreTabModule", tabId, moduleId); + this.ExecuteNonQuery("RestoreTabModule", tabId, moduleId); } public virtual void UpdateModule(int moduleId, int moduleDefId, int contentItemId, bool allTabs, DateTime startDate, DateTime endDate, bool inheritViewPermissions, bool isShareable, bool isShareableViewOnly, - bool isDeleted, int lastModifiedByUserID) - { - ExecuteNonQuery("UpdateModule", - moduleId, - moduleDefId, - contentItemId, - allTabs, - GetNull(startDate), - GetNull(endDate), - inheritViewPermissions, - isShareable, - isShareableViewOnly, - isDeleted, - lastModifiedByUserID); + bool isDeleted, int lastModifiedByUserID) + { + this.ExecuteNonQuery( + "UpdateModule", + moduleId, + moduleDefId, + contentItemId, + allTabs, + this.GetNull(startDate), + this.GetNull(endDate), + inheritViewPermissions, + isShareable, + isShareableViewOnly, + isDeleted, + lastModifiedByUserID); } public virtual void UpdateModuleLastContentModifiedOnDate(int moduleId) { - ExecuteNonQuery("UpdateModuleLastContentModifiedOnDate", moduleId); + this.ExecuteNonQuery("UpdateModuleLastContentModifiedOnDate", moduleId); } public virtual void UpdateModuleOrder(int tabId, int moduleId, int moduleOrder, string paneName) { - ExecuteNonQuery("UpdateModuleOrder", tabId, moduleId, moduleOrder, paneName); + this.ExecuteNonQuery("UpdateModuleOrder", tabId, moduleId, moduleOrder, paneName); } public virtual void UpdateModuleSetting(int moduleId, string settingName, string settingValue, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateModuleSetting", moduleId, settingName, settingValue, lastModifiedByUserID); + this.ExecuteNonQuery("UpdateModuleSetting", moduleId, settingName, settingValue, lastModifiedByUserID); } public virtual void UpdateTabModule(int TabModuleId, int TabId, int ModuleId, string ModuleTitle, string Header, @@ -1317,108 +1296,106 @@ public virtual void UpdateTabModule(int TabModuleId, int TabId, int ModuleId, st Guid DefaultLanguageGuid, Guid LocalizedVersionGuid, string CultureCode, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateTabModule", - TabModuleId, - TabId, - ModuleId, - ModuleTitle, - GetNull(Header), - GetNull(Footer), - ModuleOrder, - PaneName, - CacheTime, - GetNull(CacheMethod), - GetNull(Alignment), - GetNull(Color), - GetNull(Border), - GetNull(IconFile), - Visibility, - GetNull(ContainerSrc), - DisplayTitle, - DisplayPrint, - DisplaySyndicate, - IsWebSlice, - WebSliceTitle, - GetNull(WebSliceExpiryDate), - WebSliceTTL, - VersionGuid, - GetNull(DefaultLanguageGuid), - LocalizedVersionGuid, - CultureCode, - lastModifiedByUserID); + this.ExecuteNonQuery( + "UpdateTabModule", + TabModuleId, + TabId, + ModuleId, + ModuleTitle, + this.GetNull(Header), + this.GetNull(Footer), + ModuleOrder, + PaneName, + CacheTime, + this.GetNull(CacheMethod), + this.GetNull(Alignment), + this.GetNull(Color), + this.GetNull(Border), + this.GetNull(IconFile), + Visibility, + this.GetNull(ContainerSrc), + DisplayTitle, + DisplayPrint, + DisplaySyndicate, + IsWebSlice, + WebSliceTitle, + this.GetNull(WebSliceExpiryDate), + WebSliceTTL, + VersionGuid, + this.GetNull(DefaultLanguageGuid), + LocalizedVersionGuid, + CultureCode, + lastModifiedByUserID); } public virtual void UpdateTabModuleTranslationStatus(int tabModuleId, Guid localizedVersionGuid, int lastModifiedByUserId) { - ExecuteNonQuery("UpdateTabModuleTranslationStatus", tabModuleId, localizedVersionGuid, lastModifiedByUserId); + this.ExecuteNonQuery("UpdateTabModuleTranslationStatus", tabModuleId, localizedVersionGuid, lastModifiedByUserId); } public virtual void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateTabModuleSetting", tabModuleId, settingName, settingValue, lastModifiedByUserID); + this.ExecuteNonQuery("UpdateTabModuleSetting", tabModuleId, settingName, settingValue, lastModifiedByUserID); } public virtual void UpdateTabModuleVersion(int tabModuleId, Guid versionGuid) { - ExecuteNonQuery("UpdateTabModuleVersion", tabModuleId, versionGuid); + this.ExecuteNonQuery("UpdateTabModuleVersion", tabModuleId, versionGuid); } public virtual void UpdateTabModuleVersionByModule(int moduleId) { - ExecuteNonQuery("UpdateTabModuleVersionByModule", moduleId); + this.ExecuteNonQuery("UpdateTabModuleVersionByModule", moduleId); } public virtual IDataReader GetInstalledModules() { - return ExecuteReader("GetInstalledModules"); - } - - #endregion - - #region DesktopModule Methods - + return this.ExecuteReader("GetInstalledModules"); + } + public virtual int AddDesktopModule(int packageID, string moduleName, string folderName, string friendlyName, string description, string version, bool isPremium, bool isAdmin, string businessControllerClass, int supportedFeatures, int shareable, string compatibleVersions, string dependencies, string permissions, - int contentItemId, int createdByUserID, string adminPage, string hostPage) - { - return ExecuteScalar("AddDesktopModule", - packageID, - moduleName, - folderName, - friendlyName, - GetNull(description), - GetNull(version), - isPremium, - isAdmin, - businessControllerClass, - supportedFeatures, - shareable, - GetNull(compatibleVersions), - GetNull(dependencies), - GetNull(permissions), - contentItemId, - createdByUserID, - adminPage, - hostPage); + int contentItemId, int createdByUserID, string adminPage, string hostPage) + { + return this.ExecuteScalar( + "AddDesktopModule", + packageID, + moduleName, + folderName, + friendlyName, + this.GetNull(description), + this.GetNull(version), + isPremium, + isAdmin, + businessControllerClass, + supportedFeatures, + shareable, + this.GetNull(compatibleVersions), + this.GetNull(dependencies), + this.GetNull(permissions), + contentItemId, + createdByUserID, + adminPage, + hostPage); } public virtual void DeleteDesktopModule(int desktopModuleId) { - ExecuteNonQuery("DeleteDesktopModule", desktopModuleId); + this.ExecuteNonQuery("DeleteDesktopModule", desktopModuleId); } public virtual IDataReader GetDesktopModules() { - return ExecuteReader("GetDesktopModules"); + return this.ExecuteReader("GetDesktopModules"); } public virtual IDataReader GetDesktopModulesByPortal(int portalId) { - return ExecuteReader("GetDesktopModulesByPortal", portalId); + return this.ExecuteReader("GetDesktopModulesByPortal", portalId); } public virtual void UpdateDesktopModule(int desktopModuleId, int packageID, string moduleName, string folderName, @@ -1426,107 +1403,97 @@ public virtual void UpdateDesktopModule(int desktopModuleId, int packageID, stri bool isAdmin, string businessControllerClass, int supportedFeatures, int shareable, string compatibleVersions, string dependencies, string permissions, - int contentItemId, int lastModifiedByUserID, string adminpage, string hostpage) - { - ExecuteNonQuery("UpdateDesktopModule", - desktopModuleId, - packageID, - moduleName, - folderName, - friendlyName, - GetNull(description), - GetNull(version), - isPremium, - isAdmin, - businessControllerClass, - supportedFeatures, - shareable, - GetNull(compatibleVersions), - GetNull(dependencies), - GetNull(permissions), - contentItemId, - lastModifiedByUserID, - adminpage, - hostpage); - } - - #endregion - - #region PortalDesktopModule Methods - + int contentItemId, int lastModifiedByUserID, string adminpage, string hostpage) + { + this.ExecuteNonQuery( + "UpdateDesktopModule", + desktopModuleId, + packageID, + moduleName, + folderName, + friendlyName, + this.GetNull(description), + this.GetNull(version), + isPremium, + isAdmin, + businessControllerClass, + supportedFeatures, + shareable, + this.GetNull(compatibleVersions), + this.GetNull(dependencies), + this.GetNull(permissions), + contentItemId, + lastModifiedByUserID, + adminpage, + hostpage); + } + public virtual int AddPortalDesktopModule(int portalId, int desktopModuleId, int createdByUserID) { - return ExecuteScalar("AddPortalDesktopModule", portalId, desktopModuleId, createdByUserID); + return this.ExecuteScalar("AddPortalDesktopModule", portalId, desktopModuleId, createdByUserID); } public virtual void DeletePortalDesktopModules(int portalId, int desktopModuleId) { - ExecuteNonQuery("DeletePortalDesktopModules", GetNull(portalId), GetNull(desktopModuleId)); + this.ExecuteNonQuery("DeletePortalDesktopModules", this.GetNull(portalId), this.GetNull(desktopModuleId)); } public virtual IDataReader GetPortalDesktopModules(int portalId, int desktopModuleId) { - return ExecuteReader("GetPortalDesktopModules", GetNull(portalId), GetNull(desktopModuleId)); - } - - #endregion - - #region ModuleDefinition Methods - + return this.ExecuteReader("GetPortalDesktopModules", this.GetNull(portalId), this.GetNull(desktopModuleId)); + } + public virtual int AddModuleDefinition(int desktopModuleId, string friendlyName, string definitionName, int defaultCacheTime, int createdByUserID) { - return ExecuteScalar("AddModuleDefinition", desktopModuleId, friendlyName, definitionName, + return this.ExecuteScalar("AddModuleDefinition", desktopModuleId, friendlyName, definitionName, defaultCacheTime, createdByUserID); } public virtual void DeleteModuleDefinition(int moduleDefId) { - ExecuteNonQuery("DeleteModuleDefinition", moduleDefId); + this.ExecuteNonQuery("DeleteModuleDefinition", moduleDefId); } public virtual IDataReader GetModuleDefinitions() { - return ExecuteReader("GetModuleDefinitions"); + return this.ExecuteReader("GetModuleDefinitions"); } public virtual void UpdateModuleDefinition(int moduleDefId, string friendlyName, string definitionName, int defaultCacheTime, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateModuleDefinition", moduleDefId, friendlyName, definitionName, defaultCacheTime, + this.ExecuteNonQuery("UpdateModuleDefinition", moduleDefId, friendlyName, definitionName, defaultCacheTime, lastModifiedByUserID); - } - - #endregion - - #region ModuleControl Methods - + } + public virtual int AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, int controlType, int viewOrder, string helpUrl, bool supportsPartialRendering, bool supportsPopUps, int createdByUserID) { - return ExecuteScalar("AddModuleControl", - GetNull(moduleDefId), - GetNull(controlKey), - GetNull(controlTitle), - controlSrc, - GetNull(iconFile), - controlType, - GetNull(viewOrder), - GetNull(helpUrl), - supportsPartialRendering, - supportsPopUps, - createdByUserID); + return this.ExecuteScalar( + "AddModuleControl", + this.GetNull(moduleDefId), + this.GetNull(controlKey), + this.GetNull(controlTitle), + controlSrc, + this.GetNull(iconFile), + controlType, + this.GetNull(viewOrder), + this.GetNull(helpUrl), + supportsPartialRendering, + supportsPopUps, + createdByUserID); } public virtual void DeleteModuleControl(int moduleControlId) { - ExecuteNonQuery("DeleteModuleControl", moduleControlId); + this.ExecuteNonQuery("DeleteModuleControl", moduleControlId); } public virtual IDataReader GetModuleControls() { - return ExecuteReader("GetModuleControls"); + return this.ExecuteReader("GetModuleControls"); } public virtual void UpdateModuleControl(int moduleControlId, int moduleDefId, string controlKey, @@ -1536,80 +1503,78 @@ public virtual void UpdateModuleControl(int moduleControlId, int moduleDefId, st bool supportsPartialRendering, bool supportsPopUps, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateModuleControl", - moduleControlId, - GetNull(moduleDefId), - GetNull(controlKey), - GetNull(controlTitle), - controlSrc, - GetNull(iconFile), - controlType, - GetNull(viewOrder), - GetNull(helpUrl), - supportsPartialRendering, - supportsPopUps, - lastModifiedByUserID); - } - - #endregion - - #region Folder Methods - + this.ExecuteNonQuery( + "UpdateModuleControl", + moduleControlId, + this.GetNull(moduleDefId), + this.GetNull(controlKey), + this.GetNull(controlTitle), + controlSrc, + this.GetNull(iconFile), + controlType, + this.GetNull(viewOrder), + this.GetNull(helpUrl), + supportsPartialRendering, + supportsPopUps, + lastModifiedByUserID); + } + public virtual int AddFolder(int portalId, Guid uniqueId, Guid versionGuid, string folderPath, string mappedPath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated, int createdByUserId, int folderMappingId, bool isVersioned, int workflowId, int parentId) { - return ExecuteScalar("AddFolder", - GetNull(portalId), - uniqueId, - versionGuid, - folderPath, - mappedPath, - storageLocation, - isProtected, - isCached, - GetNull(lastUpdated), - createdByUserId, - folderMappingId, - isVersioned, - GetNull(workflowId), - GetNull(parentId)); + return this.ExecuteScalar( + "AddFolder", + this.GetNull(portalId), + uniqueId, + versionGuid, + folderPath, + mappedPath, + storageLocation, + isProtected, + isCached, + this.GetNull(lastUpdated), + createdByUserId, + folderMappingId, + isVersioned, + this.GetNull(workflowId), + this.GetNull(parentId)); } public virtual void DeleteFolder(int portalId, string folderPath) { - ExecuteNonQuery("DeleteFolder", GetNull(portalId), folderPath); + this.ExecuteNonQuery("DeleteFolder", this.GetNull(portalId), folderPath); } public virtual IDataReader GetFolder(int folderId) { - return ExecuteReader("GetFolderByFolderID", folderId); + return this.ExecuteReader("GetFolderByFolderID", folderId); } public virtual IDataReader GetFolder(int portalId, string folderPath) { - return ExecuteReader("GetFolderByFolderPath", GetNull(portalId), folderPath); + return this.ExecuteReader("GetFolderByFolderPath", this.GetNull(portalId), folderPath); } public virtual IDataReader GetFolderByUniqueID(Guid uniqueId) { - return ExecuteReader("GetFolderByUniqueID", uniqueId); + return this.ExecuteReader("GetFolderByUniqueID", uniqueId); } public virtual IDataReader GetFoldersByPortal(int portalId) { - return ExecuteReader("GetFolders", GetNull(portalId)); + return this.ExecuteReader("GetFolders", this.GetNull(portalId)); } public virtual IDataReader GetFoldersByPortalAndPermissions(int portalId, string permissions, int userId) { - return ExecuteReader("GetFoldersByPermissions", GetNull(portalId), GetNull(permissions), GetNull(userId), -1, ""); + return this.ExecuteReader("GetFoldersByPermissions", this.GetNull(portalId), this.GetNull(permissions), this.GetNull(userId), -1, string.Empty); } public virtual int GetLegacyFolderCount() { - return ExecuteScalar("GetLegacyFolderCount"); + return this.ExecuteScalar("GetLegacyFolderCount"); } public virtual void UpdateFolder(int portalId, Guid versionGuid, int folderId, string folderPath, @@ -1617,555 +1582,536 @@ public virtual void UpdateFolder(int portalId, Guid versionGuid, int folderId, s bool isProtected, bool isCached, DateTime lastUpdated, int lastModifiedByUserID, int folderMappingID, bool isVersioned, int workflowID, int parentID) { - ExecuteNonQuery("UpdateFolder", - GetNull(portalId), - versionGuid, - folderId, - folderPath, - mappedPath, - storageLocation, - isProtected, - isCached, - GetNull(lastUpdated), - lastModifiedByUserID, - folderMappingID, - isVersioned, - GetNull(workflowID), - GetNull(parentID)); + this.ExecuteNonQuery( + "UpdateFolder", + this.GetNull(portalId), + versionGuid, + folderId, + folderPath, + mappedPath, + storageLocation, + isProtected, + isCached, + this.GetNull(lastUpdated), + lastModifiedByUserID, + folderMappingID, + isVersioned, + this.GetNull(workflowID), + this.GetNull(parentID)); } public virtual void UpdateFolderVersion(int folderId, Guid versionGuid) { - ExecuteNonQuery("UpdateFolderVersion", folderId, versionGuid); + this.ExecuteNonQuery("UpdateFolderVersion", folderId, versionGuid); } public virtual IDataReader UpdateLegacyFolders() { - return ExecuteReader("UpdateLegacyFolders"); - } - - #endregion - - #region File Methods - + return this.ExecuteReader("UpdateLegacyFolders"); + } + public virtual int AddFile(int portalId, Guid uniqueId, Guid versionGuid, string fileName, string extension, long size, int width, int height, string contentType, string folder, int folderId, int createdByUserID, string hash, DateTime lastModificationTime, string title, string description, DateTime startDate, DateTime endDate, bool enablePublishPeriod, int contentItemId) { - return ExecuteScalar("AddFile", - GetNull(portalId), - uniqueId, - versionGuid, - fileName, - extension, - size, - GetNull(width), - GetNull(height), - contentType, - folder, - folderId, - createdByUserID, - hash, - lastModificationTime, - title, - description, - enablePublishPeriod, - startDate, - GetNull(endDate), - GetNull(contentItemId)); + return this.ExecuteScalar( + "AddFile", + this.GetNull(portalId), + uniqueId, + versionGuid, + fileName, + extension, + size, + this.GetNull(width), + this.GetNull(height), + contentType, + folder, + folderId, + createdByUserID, + hash, + lastModificationTime, + title, + description, + enablePublishPeriod, + startDate, + this.GetNull(endDate), + this.GetNull(contentItemId)); } public virtual void SetFileHasBeenPublished(int fileId, bool hasBeenPublished) { - ExecuteNonQuery("SetFileHasBeenPublished", fileId, hasBeenPublished); + this.ExecuteNonQuery("SetFileHasBeenPublished", fileId, hasBeenPublished); } public virtual int CountLegacyFiles() { - return ExecuteScalar("CountLegacyFiles"); + return this.ExecuteScalar("CountLegacyFiles"); } public virtual void ClearFileContent(int fileId) { - ExecuteNonQuery("ClearFileContent", fileId); + this.ExecuteNonQuery("ClearFileContent", fileId); } public virtual void DeleteFile(int portalId, string fileName, int folderId) { - ExecuteNonQuery("DeleteFile", GetNull(portalId), fileName, folderId); + this.ExecuteNonQuery("DeleteFile", this.GetNull(portalId), fileName, folderId); } public virtual void DeleteFiles(int portalId) { - ExecuteNonQuery("DeleteFiles", GetNull(portalId)); + this.ExecuteNonQuery("DeleteFiles", this.GetNull(portalId)); } public virtual DataTable GetAllFiles() { - return Globals.ConvertDataReaderToDataTable(ExecuteReader("GetAllFiles")); + return Globals.ConvertDataReaderToDataTable(this.ExecuteReader("GetAllFiles")); } public virtual IDataReader GetFile(string fileName, int folderId, bool retrieveUnpublishedFiles = false) { - return ExecuteReader("GetFile", fileName, folderId, retrieveUnpublishedFiles); + return this.ExecuteReader("GetFile", fileName, folderId, retrieveUnpublishedFiles); } public virtual IDataReader GetFileById(int fileId, bool retrieveUnpublishedFiles = false) { - return ExecuteReader("GetFileById", fileId, retrieveUnpublishedFiles); + return this.ExecuteReader("GetFileById", fileId, retrieveUnpublishedFiles); } public virtual IDataReader GetFileByUniqueID(Guid uniqueId) { - return ExecuteReader("GetFileByUniqueID", uniqueId); + return this.ExecuteReader("GetFileByUniqueID", uniqueId); } public virtual IDataReader GetFileContent(int fileId) { - return ExecuteReader("GetFileContent", fileId); + return this.ExecuteReader("GetFileContent", fileId); } public virtual IDataReader GetFileVersionContent(int fileId, int version) { - return ExecuteReader("GetFileVersionContent", fileId, version); + return this.ExecuteReader("GetFileVersionContent", fileId, version); } public virtual IDataReader GetFiles(int folderId, bool retrieveUnpublishedFiles, bool recursive) { - return ExecuteReader("GetFiles", folderId, retrieveUnpublishedFiles, recursive); + return this.ExecuteReader("GetFiles", folderId, retrieveUnpublishedFiles, recursive); } /// /// This is an internal method for communication between DNN business layer and SQL database. /// Do not use in custom modules, please use API (DotNetNuke.Services.FileSystem.FileManager.UpdateFile) - /// + /// /// Stores information about a specific file, stored in DNN filesystem - /// calling petapoco method to call the underlying stored procedure "UpdateFile" + /// calling petapoco method to call the underlying stored procedure "UpdateFile". /// - /// ID of the (already existing) file - /// GUID of this file version (should usually not be modified) - /// Name of the file in the file system (including extension) - /// File type - should meet extension in FileName - /// Size of file (bytes) - /// Width of images/video (lazy load: pass Null, might be retrieved by DNN platform on db file sync) - /// Height of images/video (lazy load: pass Null, might be retrieved by DNN platform on db file snyc) - /// MIME type of the file - /// ID of the folder, the file resides in - /// ID of the user, who performed last update of file or file info - /// SHa1 hash of the file content, used for file versioning (lazy load: pass Null, will be generated by DNN platform on db file sync) - /// timestamp, when last update of file or file info happened - /// Display title of the file - optional (pass Null if not provided) + /// ID of the (already existing) file. + /// GUID of this file version (should usually not be modified). + /// Name of the file in the file system (including extension). + /// File type - should meet extension in FileName. + /// Size of file (bytes). + /// Width of images/video (lazy load: pass Null, might be retrieved by DNN platform on db file sync). + /// Height of images/video (lazy load: pass Null, might be retrieved by DNN platform on db file snyc). + /// MIME type of the file. + /// ID of the folder, the file resides in. + /// ID of the user, who performed last update of file or file info. + /// SHa1 hash of the file content, used for file versioning (lazy load: pass Null, will be generated by DNN platform on db file sync). + /// timestamp, when last update of file or file info happened. + /// Display title of the file - optional (pass Null if not provided). /// Description of the file. - /// date and time (server TZ), from which the file should be displayed/accessible (according to folder permission) - /// date and time (server TZ), until which the file should be displayed/accessible (according to folder permission) - /// shall startdate/end date be used? - /// ID of the associated contentitem with description etc. (optional) + /// date and time (server TZ), from which the file should be displayed/accessible (according to folder permission). + /// date and time (server TZ), until which the file should be displayed/accessible (according to folder permission). + /// shall startdate/end date be used?. + /// ID of the associated contentitem with description etc. (optional). public virtual void UpdateFile(int fileId, Guid versionGuid, string fileName, string extension, long size, int width, int height, string contentType, int folderId, int lastModifiedByUserID, string hash, DateTime lastModificationTime, string title, string description, DateTime startDate, DateTime endDate, bool enablePublishPeriod, int contentItemId) { - ExecuteNonQuery("UpdateFile", - fileId, - versionGuid, - fileName, - extension, - size, - GetNull(width), - GetNull(height), - contentType, - folderId, - lastModifiedByUserID, - hash, - lastModificationTime, - title, - description, - enablePublishPeriod, - startDate, - GetNull(endDate), - GetNull(contentItemId)); + this.ExecuteNonQuery( + "UpdateFile", + fileId, + versionGuid, + fileName, + extension, + size, + this.GetNull(width), + this.GetNull(height), + contentType, + folderId, + lastModifiedByUserID, + hash, + lastModificationTime, + title, + description, + enablePublishPeriod, + startDate, + this.GetNull(endDate), + this.GetNull(contentItemId)); } public virtual void UpdateFileLastModificationTime(int fileId, DateTime lastModificationTime) { - ExecuteNonQuery("UpdateFileLastModificationTime", - fileId, - lastModificationTime); + this.ExecuteNonQuery( + "UpdateFileLastModificationTime", + fileId, + lastModificationTime); } public virtual void UpdateFileHashCode(int fileId, string hashCode) { - ExecuteNonQuery("UpdateFileHashCode", - fileId, - hashCode); + this.ExecuteNonQuery( + "UpdateFileHashCode", + fileId, + hashCode); } public virtual void UpdateFileContent(int fileId, byte[] content) { - ExecuteNonQuery("UpdateFileContent", fileId, GetNull(content)); + this.ExecuteNonQuery("UpdateFileContent", fileId, this.GetNull(content)); } - - + public virtual void UpdateFileVersion(int fileId, Guid versionGuid) { - ExecuteNonQuery("UpdateFileVersion", fileId, versionGuid); - } - - #endregion - - #region Permission Methods - + this.ExecuteNonQuery("UpdateFileVersion", fileId, versionGuid); + } + public virtual int AddPermission(string permissionCode, int moduleDefID, string permissionKey, string permissionName, int createdByUserID) { - return ExecuteScalar("AddPermission", moduleDefID, permissionCode, permissionKey, permissionName, createdByUserID); + return this.ExecuteScalar("AddPermission", moduleDefID, permissionCode, permissionKey, permissionName, createdByUserID); } public virtual void DeletePermission(int permissionID) { - ExecuteNonQuery("DeletePermission", permissionID); + this.ExecuteNonQuery("DeletePermission", permissionID); } public virtual void UpdatePermission(int permissionID, string permissionCode, int moduleDefID, string permissionKey, string permissionName, int lastModifiedByUserID) { - ExecuteNonQuery("UpdatePermission", permissionID, permissionCode, moduleDefID, permissionKey, permissionName, lastModifiedByUserID); - } - - #endregion - - #region Module Permission Methods - + this.ExecuteNonQuery("UpdatePermission", permissionID, permissionCode, moduleDefID, permissionKey, permissionName, lastModifiedByUserID); + } + public virtual int AddModulePermission(int moduleId, int portalId, int permissionId, int roleId, bool allowAccess, int userId, - int createdByUserId) + int createdByUserId) { - return ExecuteScalar("AddModulePermission", - moduleId, - portalId, - permissionId, - GetRoleNull(roleId), - allowAccess, - GetNull(userId), - createdByUserId); + return this.ExecuteScalar( + "AddModulePermission", + moduleId, + portalId, + permissionId, + this.GetRoleNull(roleId), + allowAccess, + this.GetNull(userId), + createdByUserId); } public virtual void DeleteModulePermission(int modulePermissionId) { - ExecuteNonQuery("DeleteModulePermission", modulePermissionId); + this.ExecuteNonQuery("DeleteModulePermission", modulePermissionId); } public virtual void DeleteModulePermissionsByModuleID(int moduleId, int portalId) { - ExecuteNonQuery("DeleteModulePermissionsByModuleID", moduleId, portalId); + this.ExecuteNonQuery("DeleteModulePermissionsByModuleID", moduleId, portalId); } public virtual void DeleteModulePermissionsByUserID(int portalId, int userId) { - ExecuteNonQuery("DeleteModulePermissionsByUserID", portalId, userId); + this.ExecuteNonQuery("DeleteModulePermissionsByUserID", portalId, userId); } public virtual IDataReader GetModulePermission(int modulePermissionId) { - return ExecuteReader("GetModulePermission", modulePermissionId); + return this.ExecuteReader("GetModulePermission", modulePermissionId); } public virtual IDataReader GetModulePermissionsByModuleID(int moduleID, int permissionId) { - return ExecuteReader("GetModulePermissionsByModuleID", moduleID, permissionId); + return this.ExecuteReader("GetModulePermissionsByModuleID", moduleID, permissionId); } public virtual IDataReader GetModulePermissionsByPortal(int portalId) { - return ExecuteReader("GetModulePermissionsByPortal", portalId); + return this.ExecuteReader("GetModulePermissionsByPortal", portalId); } public virtual IDataReader GetModulePermissionsByTabID(int tabId) { - return ExecuteReader("GetModulePermissionsByTabID", tabId); + return this.ExecuteReader("GetModulePermissionsByTabID", tabId); } public virtual void UpdateModulePermission(int modulePermissionId, int moduleId, int portalId, int permissionId, int roleId, - bool allowAccess, int userId, int lastModifiedByUserId) + bool allowAccess, int userId, int lastModifiedByUserId) { - ExecuteNonQuery("UpdateModulePermission", - modulePermissionId, - moduleId, - portalId, - permissionId, - GetRoleNull(roleId), - allowAccess, - GetNull(userId), - lastModifiedByUserId); - } - - #endregion - - #region TabPermission Methods - + this.ExecuteNonQuery( + "UpdateModulePermission", + modulePermissionId, + moduleId, + portalId, + permissionId, + this.GetRoleNull(roleId), + allowAccess, + this.GetNull(userId), + lastModifiedByUserId); + } + public virtual int AddTabPermission(int tabId, int permissionId, int roleID, bool allowAccess, int userId, int createdByUserID) { - return ExecuteScalar("AddTabPermission", - tabId, - permissionId, - GetRoleNull(roleID), - allowAccess, - GetNull(userId), - createdByUserID); + return this.ExecuteScalar( + "AddTabPermission", + tabId, + permissionId, + this.GetRoleNull(roleID), + allowAccess, + this.GetNull(userId), + createdByUserID); } public virtual void DeleteTabPermission(int tabPermissionId) { - ExecuteNonQuery("DeleteTabPermission", tabPermissionId); + this.ExecuteNonQuery("DeleteTabPermission", tabPermissionId); } public virtual void DeleteTabPermissionsByTabID(int tabId) { - ExecuteNonQuery("DeleteTabPermissionsByTabID", tabId); + this.ExecuteNonQuery("DeleteTabPermissionsByTabID", tabId); } public virtual void DeleteTabPermissionsByUserID(int portalId, int userId) { - ExecuteNonQuery("DeleteTabPermissionsByUserID", portalId, userId); + this.ExecuteNonQuery("DeleteTabPermissionsByUserID", portalId, userId); } public virtual IDataReader GetTabPermissionsByPortal(int portalId) { - return ExecuteReader("GetTabPermissionsByPortal", GetNull(portalId)); + return this.ExecuteReader("GetTabPermissionsByPortal", this.GetNull(portalId)); } public virtual IDataReader GetTabPermissionsByTabID(int tabId, int permissionId) { - return ExecuteReader("GetTabPermissionsByTabID", tabId, permissionId); + return this.ExecuteReader("GetTabPermissionsByTabID", tabId, permissionId); } public virtual void UpdateTabPermission(int tabPermissionId, int tabId, int permissionId, int roleID, bool allowAccess, - int userId, int lastModifiedByUserID) + int userId, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateTabPermission", - tabPermissionId, - tabId, - permissionId, - GetRoleNull(roleID), - allowAccess, - GetNull(userId), - lastModifiedByUserID); - } - - #endregion - - #region FolderPermission Methods - + this.ExecuteNonQuery( + "UpdateTabPermission", + tabPermissionId, + tabId, + permissionId, + this.GetRoleNull(roleID), + allowAccess, + this.GetNull(userId), + lastModifiedByUserID); + } + public virtual int AddFolderPermission(int folderId, int permissionId, int roleID, bool allowAccess, int userId, int createdByUserID) { - return ExecuteScalar("AddFolderPermission", - folderId, - permissionId, - GetRoleNull(roleID), - allowAccess, - GetNull(userId), - createdByUserID); + return this.ExecuteScalar( + "AddFolderPermission", + folderId, + permissionId, + this.GetRoleNull(roleID), + allowAccess, + this.GetNull(userId), + createdByUserID); } public virtual void DeleteFolderPermission(int folderPermissionId) { - ExecuteNonQuery("DeleteFolderPermission", folderPermissionId); + this.ExecuteNonQuery("DeleteFolderPermission", folderPermissionId); } public virtual void DeleteFolderPermissionsByFolderPath(int portalId, string folderPath) { - ExecuteNonQuery("DeleteFolderPermissionsByFolderPath", GetNull(portalId), folderPath); + this.ExecuteNonQuery("DeleteFolderPermissionsByFolderPath", this.GetNull(portalId), folderPath); } public virtual void DeleteFolderPermissionsByUserID(int portalId, int userId) { - ExecuteNonQuery("DeleteFolderPermissionsByUserID", portalId, userId); + this.ExecuteNonQuery("DeleteFolderPermissionsByUserID", portalId, userId); } public virtual IDataReader GetFolderPermission(int folderPermissionId) { - return ExecuteReader("GetFolderPermission", folderPermissionId); + return this.ExecuteReader("GetFolderPermission", folderPermissionId); } public virtual IDataReader GetFolderPermissionsByFolderPath(int portalId, string folderPath, int permissionId) { - return ExecuteReader("GetFolderPermissionsByFolderPath", GetNull(portalId), folderPath, permissionId); + return this.ExecuteReader("GetFolderPermissionsByFolderPath", this.GetNull(portalId), folderPath, permissionId); } public virtual IDataReader GetFolderPermissionsByPortal(int portalId) { - return ExecuteReader("GetFolderPermissionsByPortal", GetNull(portalId)); + return this.ExecuteReader("GetFolderPermissionsByPortal", this.GetNull(portalId)); } public virtual IDataReader GetFolderPermissionsByPortalAndPath(int portalId, string pathName) { - return ExecuteReader("GetFolderPermissionsByPortalAndPath", GetNull(portalId), pathName ?? ""); + return this.ExecuteReader("GetFolderPermissionsByPortalAndPath", this.GetNull(portalId), pathName ?? string.Empty); } public virtual void UpdateFolderPermission(int FolderPermissionID, int FolderID, int PermissionID, int roleID, bool AllowAccess, int UserID, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateFolderPermission", - FolderPermissionID, - FolderID, - PermissionID, - GetRoleNull(roleID), - AllowAccess, - GetNull(UserID), - lastModifiedByUserID); - } - - #endregion - - #region DesktopModulePermission Methods - + this.ExecuteNonQuery( + "UpdateFolderPermission", + FolderPermissionID, + FolderID, + PermissionID, + this.GetRoleNull(roleID), + AllowAccess, + this.GetNull(UserID), + lastModifiedByUserID); + } + public virtual int AddDesktopModulePermission(int portalDesktopModuleID, int permissionID, int roleID, bool allowAccess, int userID, int createdByUserID) { - return ExecuteScalar("AddDesktopModulePermission", - portalDesktopModuleID, - permissionID, - GetRoleNull(roleID), - allowAccess, - GetNull(userID), - createdByUserID); + return this.ExecuteScalar( + "AddDesktopModulePermission", + portalDesktopModuleID, + permissionID, + this.GetRoleNull(roleID), + allowAccess, + this.GetNull(userID), + createdByUserID); } public virtual void DeleteDesktopModulePermission(int desktopModulePermissionID) { - ExecuteNonQuery("DeleteDesktopModulePermission", desktopModulePermissionID); + this.ExecuteNonQuery("DeleteDesktopModulePermission", desktopModulePermissionID); } public virtual void DeleteDesktopModulePermissionsByPortalDesktopModuleID(int portalDesktopModuleID) { - ExecuteNonQuery("DeleteDesktopModulePermissionsByPortalDesktopModuleID", portalDesktopModuleID); + this.ExecuteNonQuery("DeleteDesktopModulePermissionsByPortalDesktopModuleID", portalDesktopModuleID); } public virtual void DeleteDesktopModulePermissionsByUserID(int userID, int portalID) { - ExecuteNonQuery("DeleteDesktopModulePermissionsByUserID", userID, portalID); + this.ExecuteNonQuery("DeleteDesktopModulePermissionsByUserID", userID, portalID); } public virtual IDataReader GetDesktopModulePermission(int desktopModulePermissionID) { - return ExecuteReader("GetDesktopModulePermission", desktopModulePermissionID); + return this.ExecuteReader("GetDesktopModulePermission", desktopModulePermissionID); } public virtual IDataReader GetDesktopModulePermissions() { - return ExecuteReader("GetDesktopModulePermissions"); + return this.ExecuteReader("GetDesktopModulePermissions"); } public virtual IDataReader GetDesktopModulePermissionsByPortalDesktopModuleID(int portalDesktopModuleID) { - return ExecuteReader("GetDesktopModulePermissionsByPortalDesktopModuleID", portalDesktopModuleID); + return this.ExecuteReader("GetDesktopModulePermissionsByPortalDesktopModuleID", portalDesktopModuleID); } public virtual void UpdateDesktopModulePermission(int desktopModulePermissionID, int portalDesktopModuleID, int permissionID, int roleID, bool allowAccess, int userID, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateDesktopModulePermission", - desktopModulePermissionID, - portalDesktopModuleID, - permissionID, - GetRoleNull(roleID), - allowAccess, - GetNull(userID), - lastModifiedByUserID); - } - - #endregion - - #region RoleGroup Methods - + this.ExecuteNonQuery( + "UpdateDesktopModulePermission", + desktopModulePermissionID, + portalDesktopModuleID, + permissionID, + this.GetRoleNull(roleID), + allowAccess, + this.GetNull(userID), + lastModifiedByUserID); + } + public virtual int AddRoleGroup(int portalId, string groupName, string description, int createdByUserID) { - return ExecuteScalar("AddRoleGroup", portalId, groupName, description, createdByUserID); + return this.ExecuteScalar("AddRoleGroup", portalId, groupName, description, createdByUserID); } public virtual void DeleteRoleGroup(int roleGroupId) { - ExecuteNonQuery("DeleteRoleGroup", roleGroupId); + this.ExecuteNonQuery("DeleteRoleGroup", roleGroupId); } public virtual IDataReader GetRoleGroup(int portalId, int roleGroupId) { - return ExecuteReader("GetRoleGroup", portalId, roleGroupId); + return this.ExecuteReader("GetRoleGroup", portalId, roleGroupId); } public virtual IDataReader GetRoleGroupByName(int portalID, string roleGroupName) { - return ExecuteReader("GetRoleGroupByName", portalID, roleGroupName); + return this.ExecuteReader("GetRoleGroupByName", portalID, roleGroupName); } public virtual IDataReader GetRoleGroups(int portalId) { - return ExecuteReader("GetRoleGroups", portalId); + return this.ExecuteReader("GetRoleGroups", portalId); } public virtual void UpdateRoleGroup(int roleGroupId, string groupName, string description, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateRoleGroup", roleGroupId, groupName, description, lastModifiedByUserID); - } - - #endregion - - #region Role Methods - + this.ExecuteNonQuery("UpdateRoleGroup", roleGroupId, groupName, description, lastModifiedByUserID); + } + public virtual int AddRole(int portalId, int roleGroupId, string roleName, string description, float serviceFee, string billingPeriod, string billingFrequency, float trialFee, int trialPeriod, string trialFrequency, bool isPublic, bool autoAssignment, string rsvpCode, string iconFile, int createdByUserID, int status, int securityMode, bool isSystemRole) { - return ExecuteScalar("AddRole", - portalId, - GetNull(roleGroupId), - roleName, - description, - serviceFee, - billingPeriod, - GetNull(billingFrequency), - trialFee, - trialPeriod, - GetNull(trialFrequency), - isPublic, - autoAssignment, - rsvpCode, - iconFile, - createdByUserID, - status, - securityMode, - isSystemRole); + return this.ExecuteScalar( + "AddRole", + portalId, + this.GetNull(roleGroupId), + roleName, + description, + serviceFee, + billingPeriod, + this.GetNull(billingFrequency), + trialFee, + trialPeriod, + this.GetNull(trialFrequency), + isPublic, + autoAssignment, + rsvpCode, + iconFile, + createdByUserID, + status, + securityMode, + isSystemRole); } public virtual void DeleteRole(int roleId) { - ExecuteNonQuery("DeleteRole", roleId); + this.ExecuteNonQuery("DeleteRole", roleId); } public virtual IDataReader GetPortalRoles(int portalId) { - return ExecuteReader("GetPortalRoles", portalId); + return this.ExecuteReader("GetPortalRoles", portalId); } public virtual IDataReader GetRoles() { - return ExecuteReader("GetRoles"); + return this.ExecuteReader("GetRoles"); } public virtual IDataReader GetRolesBasicSearch(int portalID, int pageIndex, int pageSize, string filterBy) { - return ExecuteReader("GetRolesBasicSearch", portalID, pageIndex, pageSize, filterBy); + return this.ExecuteReader("GetRolesBasicSearch", portalID, pageIndex, pageSize, filterBy); } public virtual IDataReader GetRoleSettings(int roleId) { - return ExecuteReader("GetRoleSettings", roleId); + return this.ExecuteReader("GetRoleSettings", roleId); } public virtual void UpdateRole(int roleId, int roleGroupId, string roleName, string description, @@ -2175,146 +2121,145 @@ public virtual void UpdateRole(int roleId, int roleGroupId, string roleName, str string iconFile, int lastModifiedByUserID, int status, int securityMode, bool isSystemRole) { - ExecuteNonQuery("UpdateRole", - roleId, - GetNull(roleGroupId), - roleName, - description, - serviceFee, - billingPeriod, - GetNull(billingFrequency), - trialFee, - trialPeriod, - GetNull(trialFrequency), - isPublic, - autoAssignment, - rsvpCode, - iconFile, - lastModifiedByUserID, - status, - securityMode, - isSystemRole); + this.ExecuteNonQuery( + "UpdateRole", + roleId, + this.GetNull(roleGroupId), + roleName, + description, + serviceFee, + billingPeriod, + this.GetNull(billingFrequency), + trialFee, + trialPeriod, + this.GetNull(trialFrequency), + isPublic, + autoAssignment, + rsvpCode, + iconFile, + lastModifiedByUserID, + status, + securityMode, + isSystemRole); } public virtual void UpdateRoleSetting(int roleId, string settingName, string settingValue, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateRoleSetting", - roleId, - settingName, - settingValue, - lastModifiedByUserID); - } - - #endregion - - #region User Methods - + this.ExecuteNonQuery( + "UpdateRoleSetting", + roleId, + settingName, + settingValue, + lastModifiedByUserID); + } + public virtual int AddUser(int portalID, string username, string firstName, string lastName, int affiliateId, bool isSuperUser, string email, string displayName, bool updatePassword, bool isApproved, int createdByUserID) { - return ExecuteScalar("AddUser", - portalID, - username, - firstName, - lastName, - GetNull(affiliateId), - isSuperUser, - email, - displayName, - updatePassword, - isApproved, - createdByUserID); + return this.ExecuteScalar( + "AddUser", + portalID, + username, + firstName, + lastName, + this.GetNull(affiliateId), + isSuperUser, + email, + displayName, + updatePassword, + isApproved, + createdByUserID); } public virtual void AddUserPortal(int portalId, int userId) { - ExecuteNonQuery("AddUserPortal", portalId, userId); + this.ExecuteNonQuery("AddUserPortal", portalId, userId); } public virtual void ChangeUsername(int userId, string newUsername) { - ExecuteNonQuery("ChangeUsername", userId, newUsername); + this.ExecuteNonQuery("ChangeUsername", userId, newUsername); } public virtual void DeleteUserFromPortal(int userId, int portalId) { - ExecuteNonQuery("DeleteUserPortal", userId, GetNull(portalId)); + this.ExecuteNonQuery("DeleteUserPortal", userId, this.GetNull(portalId)); } public virtual IDataReader GetAllUsers(int portalID, int pageIndex, int pageSize, bool includeDeleted, bool superUsersOnly) { - return ExecuteReader("GetAllUsers", GetNull(portalID), pageIndex, pageSize, includeDeleted, superUsersOnly); + return this.ExecuteReader("GetAllUsers", this.GetNull(portalID), pageIndex, pageSize, includeDeleted, superUsersOnly); } public virtual IDataReader GetDeletedUsers(int portalId) { - return ExecuteReader("GetDeletedUsers", GetNull(portalId)); + return this.ExecuteReader("GetDeletedUsers", this.GetNull(portalId)); } public virtual IDataReader GetUnAuthorizedUsers(int portalId, bool includeDeleted, bool superUsersOnly) { - return ExecuteReader("GetUnAuthorizedUsers", GetNull(portalId), includeDeleted, superUsersOnly); + return this.ExecuteReader("GetUnAuthorizedUsers", this.GetNull(portalId), includeDeleted, superUsersOnly); } public virtual IDataReader GetUser(int portalId, int userId) { - return ExecuteReader("GetUser", portalId, userId); + return this.ExecuteReader("GetUser", portalId, userId); } public virtual IDataReader GetUserByAuthToken(int portalID, string userToken, string authType) { - return ExecuteReader("GetUserByAuthToken", portalID, userToken, authType); + return this.ExecuteReader("GetUserByAuthToken", portalID, userToken, authType); } public virtual IDataReader GetUserByDisplayName(int portalId, string displayName) { - return ExecuteReader("GetUserByDisplayName", GetNull(portalId), displayName); + return this.ExecuteReader("GetUserByDisplayName", this.GetNull(portalId), displayName); } public virtual IDataReader GetUserByUsername(int portalId, string username) { - return ExecuteReader("GetUserByUsername", GetNull(portalId), username); + return this.ExecuteReader("GetUserByUsername", this.GetNull(portalId), username); } public virtual IDataReader GetUserByUsername(string username, string spaceReplacement) { - return ExecuteReader("GetUserByUsernameForUrl", username, spaceReplacement); + return this.ExecuteReader("GetUserByUsernameForUrl", username, spaceReplacement); } public virtual IDataReader GetUserByVanityUrl(int portalId, string vanityUrl) { - return ExecuteReader("GetUserByVanityUrl", GetNull(portalId), vanityUrl); + return this.ExecuteReader("GetUserByVanityUrl", this.GetNull(portalId), vanityUrl); } public virtual IDataReader GetUserByPasswordResetToken(int portalId, string resetToken) { - return ExecuteReader("GetUserByPasswordResetToken", GetNull(portalId), resetToken); + return this.ExecuteReader("GetUserByPasswordResetToken", this.GetNull(portalId), resetToken); } public virtual IDataReader GetDisplayNameForUser(int userId, string spaceReplacement) { - return ExecuteReader("GetDisplayNameForUser", userId, spaceReplacement); + return this.ExecuteReader("GetDisplayNameForUser", userId, spaceReplacement); } public virtual int GetUserCountByPortal(int portalId) { - return ExecuteScalar("GetUserCountByPortal", portalId); + return this.ExecuteScalar("GetUserCountByPortal", portalId); } public virtual IDataReader GetUsersAdvancedSearch(int portalId, int userId, int filterUserId, int fitlerRoleId, int relationTypeId, bool isAdmin, int pageIndex, int pageSize, string sortColumn, bool sortAscending, - string propertyNames, string propertyValues) + string propertyNames, string propertyValues) { var ps = PortalSecurity.Instance; string filterSort = ps.InputFilter(sortColumn, PortalSecurity.FilterFlag.NoSQL); string filterName = ps.InputFilter(propertyNames, PortalSecurity.FilterFlag.NoSQL); string filterValue = ps.InputFilter(propertyValues, PortalSecurity.FilterFlag.NoSQL); - return ExecuteReader("GetUsersAdvancedSearch", portalId, userId, filterUserId, fitlerRoleId, relationTypeId, + return this.ExecuteReader("GetUsersAdvancedSearch", portalId, userId, filterUserId, fitlerRoleId, relationTypeId, isAdmin, pageSize, pageIndex, filterSort, sortAscending, filterName, filterValue); } @@ -2325,14 +2270,14 @@ public virtual IDataReader GetUsersBasicSearch(int portalId, int pageIndex, int string filterSort = ps.InputFilter(sortColumn, PortalSecurity.FilterFlag.NoSQL); string filterName = ps.InputFilter(propertyName, PortalSecurity.FilterFlag.NoSQL); string filterValue = ps.InputFilter(propertyValue, PortalSecurity.FilterFlag.NoSQL); - return ExecuteReader("GetUsersBasicSearch", portalId, pageSize, pageIndex, filterSort, sortAscending, + return this.ExecuteReader("GetUsersBasicSearch", portalId, pageSize, pageIndex, filterSort, sortAscending, filterName, filterValue); } public virtual IDataReader GetUsersByEmail(int portalID, string email, int pageIndex, int pageSize, bool includeDeleted, bool superUsersOnly) { - return ExecuteReader("GetUsersByEmail", GetNull(portalID), email, pageIndex, pageSize, includeDeleted, + return this.ExecuteReader("GetUsersByEmail", this.GetNull(portalID), email, pageIndex, pageSize, includeDeleted, superUsersOnly); } @@ -2340,52 +2285,52 @@ public virtual IDataReader GetUsersByProfileProperty(int portalID, string proper int pageIndex, int pageSize, bool includeDeleted, bool superUsersOnly) { - return ExecuteReader("GetUsersByProfileProperty", GetNull(portalID), propertyName, propertyValue, pageIndex, + return this.ExecuteReader("GetUsersByProfileProperty", this.GetNull(portalID), propertyName, propertyValue, pageIndex, pageSize, includeDeleted, superUsersOnly); } public virtual IDataReader GetUsersByRolename(int portalID, string rolename) { - return ExecuteReader("GetUsersByRolename", GetNull(portalID), rolename); + return this.ExecuteReader("GetUsersByRolename", this.GetNull(portalID), rolename); } public virtual IDataReader GetUsersByUsername(int portalID, string username, int pageIndex, int pageSize, bool includeDeleted, bool superUsersOnly) { - return ExecuteReader("GetUsersByUsername", GetNull(portalID), username, pageIndex, pageSize, includeDeleted, + return this.ExecuteReader("GetUsersByUsername", this.GetNull(portalID), username, pageIndex, pageSize, includeDeleted, superUsersOnly); } public virtual IDataReader GetUsersByDisplayname(int portalId, string name, int pageIndex, int pageSize, bool includeDeleted, bool superUsersOnly) { - return ExecuteReader("GetUsersByDisplayname", GetNull(portalId), name, pageIndex, pageSize, includeDeleted, + return this.ExecuteReader("GetUsersByDisplayname", this.GetNull(portalId), name, pageIndex, pageSize, includeDeleted, superUsersOnly); } public virtual int GetDuplicateEmailCount(int portalId) { - return ExecuteScalar("GetDuplicateEmailCount", portalId); + return this.ExecuteScalar("GetDuplicateEmailCount", portalId); } public virtual int GetSingleUserByEmail(int portalId, string emailToMatch) { - return ExecuteScalar("GetSingleUserByEmail", portalId, emailToMatch); + return this.ExecuteScalar("GetSingleUserByEmail", portalId, emailToMatch); } public virtual void RemoveUser(int userId, int portalId) { - ExecuteNonQuery("RemoveUser", userId, GetNull(portalId)); + this.ExecuteNonQuery("RemoveUser", userId, this.GetNull(portalId)); } public virtual void ResetTermsAgreement(int portalId) { - ExecuteNonQuery("ResetTermsAgreement", portalId); + this.ExecuteNonQuery("ResetTermsAgreement", portalId); } public virtual void RestoreUser(int userId, int portalId) { - ExecuteNonQuery("RestoreUser", userId, GetNull(portalId)); + this.ExecuteNonQuery("RestoreUser", userId, this.GetNull(portalId)); } public virtual void UpdateUser(int userId, int portalID, string firstName, string lastName, bool isSuperUser, @@ -2393,133 +2338,123 @@ public virtual void UpdateUser(int userId, int portalID, string firstName, strin bool isApproved, bool refreshRoles, string lastIpAddress, Guid passwordResetToken, DateTime passwordResetExpiration, bool isDeleted, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateUser", - userId, - GetNull(portalID), - firstName, - lastName, - isSuperUser, - email, - displayName, - vanityUrl, - updatePassword, - isApproved, - refreshRoles, - lastIpAddress, - GetNull(passwordResetToken), - GetNull(passwordResetExpiration), - isDeleted, - lastModifiedByUserID); + this.ExecuteNonQuery( + "UpdateUser", + userId, + this.GetNull(portalID), + firstName, + lastName, + isSuperUser, + email, + displayName, + vanityUrl, + updatePassword, + isApproved, + refreshRoles, + lastIpAddress, + this.GetNull(passwordResetToken), + this.GetNull(passwordResetExpiration), + isDeleted, + lastModifiedByUserID); } public virtual void UpdateUserLastIpAddress(int userId, string lastIpAddress) { - ExecuteNonQuery("UpdateUserLastIpAddress", userId, lastIpAddress); + this.ExecuteNonQuery("UpdateUserLastIpAddress", userId, lastIpAddress); } public virtual void UserAgreedToTerms(int portalId, int userId) { - ExecuteNonQuery("UserAgreedToTerms", portalId, userId); + this.ExecuteNonQuery("UserAgreedToTerms", portalId, userId); } public virtual void UserRequestsRemoval(int portalId, int userId, bool remove) { - ExecuteNonQuery("UserRequestsRemoval", portalId, userId, remove); - } - - #endregion - - #region UserRole Methods - + this.ExecuteNonQuery("UserRequestsRemoval", portalId, userId, remove); + } + public virtual int AddUserRole(int portalId, int userId, int roleId, int status, bool isOwner, DateTime effectiveDate, DateTime expiryDate, int createdByUserID) { - return ExecuteScalar("AddUserRole", portalId, userId, roleId, status, isOwner, GetNull(effectiveDate), - GetNull(expiryDate), createdByUserID); + return this.ExecuteScalar("AddUserRole", portalId, userId, roleId, status, isOwner, this.GetNull(effectiveDate), + this.GetNull(expiryDate), createdByUserID); } public virtual void DeleteUserRole(int userId, int roleId) { - ExecuteNonQuery("DeleteUserRole", userId, roleId); + this.ExecuteNonQuery("DeleteUserRole", userId, roleId); } public virtual IDataReader GetServices(int portalId, int userId) { - return ExecuteReader("GetServices", portalId, GetNull(userId)); + return this.ExecuteReader("GetServices", portalId, this.GetNull(userId)); } public virtual IDataReader GetUserRole(int portalID, int userId, int roleId) { - return ExecuteReader("GetUserRole", portalID, userId, roleId); + return this.ExecuteReader("GetUserRole", portalID, userId, roleId); } public virtual IDataReader GetUserRoles(int portalID, int userId) { - return ExecuteReader("GetUserRoles", portalID, userId); + return this.ExecuteReader("GetUserRoles", portalID, userId); } public virtual IDataReader GetUserRolesByUsername(int portalID, string username, string rolename) { - return ExecuteReader("GetUserRolesByUsername", portalID, GetNull(username), GetNull(rolename)); + return this.ExecuteReader("GetUserRolesByUsername", portalID, this.GetNull(username), this.GetNull(rolename)); } public virtual void UpdateUserRole(int userRoleId, int status, bool isOwner, DateTime effectiveDate, DateTime expiryDate, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateUserRole", userRoleId, status, isOwner, GetNull(effectiveDate), GetNull(expiryDate), + this.ExecuteNonQuery("UpdateUserRole", userRoleId, status, isOwner, this.GetNull(effectiveDate), this.GetNull(expiryDate), lastModifiedByUserID); - } - - #endregion - - #region Users Online Methods - + } + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public virtual void DeleteUsersOnline(int timeWindow) { - ExecuteNonQuery("DeleteUsersOnline", timeWindow); + this.ExecuteNonQuery("DeleteUsersOnline", timeWindow); } [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public virtual IDataReader GetOnlineUser(int userId) { - return ExecuteReader("GetOnlineUser", userId); + return this.ExecuteReader("GetOnlineUser", userId); } [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public virtual IDataReader GetOnlineUsers(int portalId) { - return ExecuteReader("GetOnlineUsers", portalId); + return this.ExecuteReader("GetOnlineUsers", portalId); } [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public virtual void UpdateUsersOnline(Hashtable userList) { - if ((userList.Count == 0)) + if (userList.Count == 0) { - //No users to process, quit method + // No users to process, quit method return; } + foreach (string key in userList.Keys) { var info = userList[key] as AnonymousUserInfo; if (info != null) { var user = info; - ExecuteNonQuery("UpdateAnonymousUser", user.UserID, user.PortalID, user.TabID, user.LastActiveDate); + this.ExecuteNonQuery("UpdateAnonymousUser", user.UserID, user.PortalID, user.TabID, user.LastActiveDate); } else if (userList[key] is OnlineUserInfo) { var user = (OnlineUserInfo)userList[key]; - ExecuteNonQuery("UpdateOnlineUser", user.UserID, user.PortalID, user.TabID, user.LastActiveDate); + this.ExecuteNonQuery("UpdateOnlineUser", user.UserID, user.PortalID, user.TabID, user.LastActiveDate); } } - } - - #endregion - - #region UserProfile Methods - + } + public virtual int AddPropertyDefinition(int portalId, int moduleDefId, int dataType, string defaultValue, string propertyCategory, string propertyName, bool readOnly, bool required, string validationExpression, int viewOrder, @@ -2528,66 +2463,68 @@ public virtual int AddPropertyDefinition(int portalId, int moduleDefId, int data int retValue; try { - retValue = ExecuteScalar("AddPropertyDefinition", - GetNull(portalId), - moduleDefId, - dataType, - defaultValue, - propertyCategory, - propertyName, - readOnly, - required, - validationExpression, - viewOrder, - visible, - length, - defaultVisibility, - createdByUserId); + retValue = this.ExecuteScalar( + "AddPropertyDefinition", + this.GetNull(portalId), + moduleDefId, + dataType, + defaultValue, + propertyCategory, + propertyName, + readOnly, + required, + validationExpression, + viewOrder, + visible, + length, + defaultVisibility, + createdByUserId); } catch (SqlException ex) { Logger.Debug(ex); - //If not a duplicate (throw an Exception) + // If not a duplicate (throw an Exception) retValue = -ex.Number; if (ex.Number != DuplicateKey) { throw; } } + return retValue; } public virtual void DeletePropertyDefinition(int definitionId) { - ExecuteNonQuery("DeletePropertyDefinition", definitionId); + this.ExecuteNonQuery("DeletePropertyDefinition", definitionId); } public virtual IDataReader GetPropertyDefinition(int definitionId) { - return ExecuteReader("GetPropertyDefinition", definitionId); + return this.ExecuteReader("GetPropertyDefinition", definitionId); } public virtual IDataReader GetPropertyDefinitionByName(int portalId, string name) { - return ExecuteReader("GetPropertyDefinitionByName", GetNull(portalId), name); + return this.ExecuteReader("GetPropertyDefinitionByName", this.GetNull(portalId), name); } public virtual IDataReader GetPropertyDefinitionsByPortal(int portalId) { - return ExecuteReader("GetPropertyDefinitionsByPortal", GetNull(portalId)); + return this.ExecuteReader("GetPropertyDefinitionsByPortal", this.GetNull(portalId)); } public virtual IDataReader GetUserProfile(int userId) { - return ExecuteReader("GetUserProfile", userId); + return this.ExecuteReader("GetUserProfile", userId); } public virtual void UpdateProfileProperty(int profileId, int userId, int propertyDefinitionID, string propertyValue, - int visibility, string extendedVisibility, DateTime lastUpdatedDate) + int visibility, string extendedVisibility, DateTime lastUpdatedDate) { - ExecuteNonQuery("UpdateUserProfileProperty", GetNull(profileId), userId, propertyDefinitionID, propertyValue, + this.ExecuteNonQuery("UpdateUserProfileProperty", this.GetNull(profileId), userId, propertyDefinitionID, propertyValue, visibility, extendedVisibility, lastUpdatedDate); } @@ -2596,260 +2533,240 @@ public virtual void UpdatePropertyDefinition(int propertyDefinitionId, int dataT bool required, string validation, int viewOrder, bool visible, int length, int defaultVisibility, int lastModifiedByUserId) { - ExecuteNonQuery("UpdatePropertyDefinition", - propertyDefinitionId, - dataType, - defaultValue, - propertyCategory, - propertyName, - readOnly, - required, - validation, - viewOrder, - visible, - length, - defaultVisibility, - lastModifiedByUserId); + this.ExecuteNonQuery( + "UpdatePropertyDefinition", + propertyDefinitionId, + dataType, + defaultValue, + propertyCategory, + propertyName, + readOnly, + required, + validation, + viewOrder, + visible, + length, + defaultVisibility, + lastModifiedByUserId); } public virtual IDataReader SearchProfilePropertyValues(int portalId, string propertyName, string searchString) { - return ExecuteReader("SearchProfilePropertyValues", portalId, propertyName, searchString); - } - - #endregion - - #region SkinControls - + return this.ExecuteReader("SearchProfilePropertyValues", portalId, propertyName, searchString); + } + public virtual int AddSkinControl(int packageID, string ControlKey, string ControlSrc, bool SupportsPartialRendering, - int CreatedByUserID) + int CreatedByUserID) { - return ExecuteScalar("AddSkinControl", - GetNull(packageID), - GetNull(ControlKey), - ControlSrc, - SupportsPartialRendering, - CreatedByUserID); + return this.ExecuteScalar( + "AddSkinControl", + this.GetNull(packageID), + this.GetNull(ControlKey), + ControlSrc, + SupportsPartialRendering, + CreatedByUserID); } public virtual void DeleteSkinControl(int skinControlID) { - ExecuteNonQuery("DeleteSkinControl", skinControlID); + this.ExecuteNonQuery("DeleteSkinControl", skinControlID); } public virtual IDataReader GetSkinControls() { - return ExecuteReader("GetSkinControls"); + return this.ExecuteReader("GetSkinControls"); } public virtual IDataReader GetSkinControl(int skinControlID) { - return ExecuteReader("GetSkinControl", skinControlID); + return this.ExecuteReader("GetSkinControl", skinControlID); } public virtual IDataReader GetSkinControlByKey(string controlKey) { - return ExecuteReader("GetSkinControlByKey", controlKey); + return this.ExecuteReader("GetSkinControlByKey", controlKey); } public virtual IDataReader GetSkinControlByPackageID(int packageID) { - return ExecuteReader("GetSkinControlByPackageID", packageID); + return this.ExecuteReader("GetSkinControlByPackageID", packageID); } public virtual void UpdateSkinControl(int skinControlID, int packageID, string ControlKey, string ControlSrc, bool SupportsPartialRendering, int LastModifiedByUserID) { - ExecuteNonQuery("UpdateSkinControl", - skinControlID, - GetNull(packageID), - GetNull(ControlKey), - ControlSrc, - SupportsPartialRendering, - LastModifiedByUserID); - } - - #endregion - - #region Skins/Containers - + this.ExecuteNonQuery( + "UpdateSkinControl", + skinControlID, + this.GetNull(packageID), + this.GetNull(ControlKey), + ControlSrc, + SupportsPartialRendering, + LastModifiedByUserID); + } + public virtual int AddSkin(int skinPackageID, string skinSrc) { - return ExecuteScalar("AddSkin", skinPackageID, skinSrc); + return this.ExecuteScalar("AddSkin", skinPackageID, skinSrc); } public virtual int AddSkinPackage(int packageID, int portalID, string skinName, string skinType, int createdByUserId) { - return ExecuteScalar("AddSkinPackage", packageID, GetNull(portalID), skinName, skinType, + return this.ExecuteScalar("AddSkinPackage", packageID, this.GetNull(portalID), skinName, skinType, createdByUserId); } public virtual bool CanDeleteSkin(string skinType, string skinFoldername) { - return ExecuteScalar("CanDeleteSkin", skinType, skinFoldername) == 1; + return this.ExecuteScalar("CanDeleteSkin", skinType, skinFoldername) == 1; } public virtual void DeleteSkin(int skinID) { - ExecuteNonQuery("DeleteSkin", skinID); + this.ExecuteNonQuery("DeleteSkin", skinID); } public virtual void DeleteSkinPackage(int skinPackageID) { - ExecuteNonQuery("DeleteSkinPackage", skinPackageID); + this.ExecuteNonQuery("DeleteSkinPackage", skinPackageID); } public virtual IDataReader GetSkinByPackageID(int packageID) { - return ExecuteReader("GetSkinPackageByPackageID", packageID); + return this.ExecuteReader("GetSkinPackageByPackageID", packageID); } public virtual IDataReader GetSkinPackage(int portalID, string skinName, string skinType) { - return ExecuteReader("GetSkinPackage", GetNull(portalID), skinName, skinType); + return this.ExecuteReader("GetSkinPackage", this.GetNull(portalID), skinName, skinType); } public virtual void UpdateSkin(int skinID, string skinSrc) { - ExecuteNonQuery("UpdateSkin", skinID, skinSrc); + this.ExecuteNonQuery("UpdateSkin", skinID, skinSrc); } public virtual void UpdateSkinPackage(int skinPackageID, int packageID, int portalID, string skinName, string skinType, int LastModifiedByUserID) { - ExecuteNonQuery("UpdateSkinPackage", skinPackageID, packageID, GetNull(portalID), skinName, skinType, + this.ExecuteNonQuery("UpdateSkinPackage", skinPackageID, packageID, this.GetNull(portalID), skinName, skinType, LastModifiedByUserID); - } - - #endregion - - #region Personalization - + } + public virtual void AddProfile(int userId, int portalId) { - ExecuteNonQuery("AddProfile", userId, portalId); + this.ExecuteNonQuery("AddProfile", userId, portalId); } public virtual IDataReader GetAllProfiles() { - return ExecuteReader("GetAllProfiles"); + return this.ExecuteReader("GetAllProfiles"); } public virtual IDataReader GetProfile(int userId, int portalId) { - return ExecuteReader("GetProfile", userId, portalId); + return this.ExecuteReader("GetProfile", userId, portalId); } public virtual void UpdateProfile(int userId, int portalId, string profileData) { - ExecuteNonQuery("UpdateProfile", userId, portalId, profileData); - } - - #endregion - - #region Urls - + this.ExecuteNonQuery("UpdateProfile", userId, portalId, profileData); + } + public virtual void AddUrl(int PortalID, string Url) { - ExecuteNonQuery("AddUrl", PortalID, Url); + this.ExecuteNonQuery("AddUrl", PortalID, Url); } public virtual void AddUrlLog(int UrlTrackingID, int UserID) { - ExecuteNonQuery("AddUrlLog", UrlTrackingID, GetNull(UserID)); + this.ExecuteNonQuery("AddUrlLog", UrlTrackingID, this.GetNull(UserID)); } public virtual void AddUrlTracking(int PortalID, string Url, string UrlType, bool LogActivity, bool TrackClicks, int ModuleID, bool NewWindow) { - ExecuteNonQuery("AddUrlTracking", PortalID, Url, UrlType, LogActivity, TrackClicks, GetNull(ModuleID), + this.ExecuteNonQuery("AddUrlTracking", PortalID, Url, UrlType, LogActivity, TrackClicks, this.GetNull(ModuleID), NewWindow); } public virtual void DeleteUrl(int PortalID, string Url) { - ExecuteNonQuery("DeleteUrl", PortalID, Url); + this.ExecuteNonQuery("DeleteUrl", PortalID, Url); } public virtual void DeleteUrlTracking(int PortalID, string Url, int ModuleID) { - ExecuteNonQuery("DeleteUrlTracking", PortalID, Url, GetNull(ModuleID)); + this.ExecuteNonQuery("DeleteUrlTracking", PortalID, Url, this.GetNull(ModuleID)); } public virtual IDataReader GetUrl(int PortalID, string Url) { - return ExecuteReader("GetUrl", PortalID, Url); + return this.ExecuteReader("GetUrl", PortalID, Url); } public virtual IDataReader GetUrlLog(int UrlTrackingID, DateTime StartDate, DateTime EndDate) { - return ExecuteReader("GetUrlLog", UrlTrackingID, GetNull(StartDate), GetNull(EndDate)); + return this.ExecuteReader("GetUrlLog", UrlTrackingID, this.GetNull(StartDate), this.GetNull(EndDate)); } public virtual IDataReader GetUrls(int PortalID) { - return ExecuteReader("GetUrls", PortalID); + return this.ExecuteReader("GetUrls", PortalID); } public virtual IDataReader GetUrlTracking(int PortalID, string Url, int ModuleID) { - return ExecuteReader("GetUrlTracking", PortalID, Url, GetNull(ModuleID)); + return this.ExecuteReader("GetUrlTracking", PortalID, Url, this.GetNull(ModuleID)); } public virtual void UpdateUrlTracking(int PortalID, string Url, bool LogActivity, bool TrackClicks, int ModuleID, bool NewWindow) { - ExecuteNonQuery("UpdateUrlTracking", PortalID, Url, LogActivity, TrackClicks, GetNull(ModuleID), NewWindow); + this.ExecuteNonQuery("UpdateUrlTracking", PortalID, Url, LogActivity, TrackClicks, this.GetNull(ModuleID), NewWindow); } public virtual void UpdateUrlTrackingStats(int PortalID, string Url, int ModuleID) { - ExecuteNonQuery("UpdateUrlTrackingStats", PortalID, Url, GetNull(ModuleID)); - } - - #endregion - - #region Search - + this.ExecuteNonQuery("UpdateUrlTrackingStats", PortalID, Url, this.GetNull(ModuleID)); + } + public virtual IDataReader GetDefaultLanguageByModule(string ModuleList) { - return ExecuteReader("GetDefaultLanguageByModule", ModuleList); + return this.ExecuteReader("GetDefaultLanguageByModule", ModuleList); } public virtual IDataReader GetSearchCommonWordsByLocale(string Locale) { - return ExecuteReader("GetSearchCommonWordsByLocale", Locale); + return this.ExecuteReader("GetSearchCommonWordsByLocale", Locale); } public virtual IDataReader GetSearchIndexers() { - return ExecuteReader("GetSearchIndexers"); + return this.ExecuteReader("GetSearchIndexers"); } public virtual IDataReader GetSearchResultModules(int PortalID) { - return ExecuteReader("GetSearchResultModules", PortalID); + return this.ExecuteReader("GetSearchResultModules", PortalID); } public virtual IDataReader GetSearchSettings(int ModuleId) { - return ExecuteReader("GetSearchSettings", ModuleId); - } - - #endregion - - #region Lists - + return this.ExecuteReader("GetSearchSettings", ModuleId); + } + public virtual int AddListEntry(string ListName, string Value, string Text, int ParentID, int Level, bool EnableSortOrder, int DefinitionID, string Description, int PortalID, bool SystemList, - int CreatedByUserID) + int CreatedByUserID) { try { - return ExecuteScalar("AddListEntry", + return this.ExecuteScalar( + "AddListEntry", ListName, Value, Text, @@ -2875,276 +2792,263 @@ public virtual int AddListEntry(string ListName, string Value, string Text, int public virtual void DeleteList(string ListName, string ParentKey) { - ExecuteNonQuery("DeleteList", ListName, ParentKey); + this.ExecuteNonQuery("DeleteList", ListName, ParentKey); } public virtual void DeleteListEntryByID(int EntryID, bool DeleteChild) { - ExecuteNonQuery("DeleteListEntryByID", EntryID, DeleteChild); + this.ExecuteNonQuery("DeleteListEntryByID", EntryID, DeleteChild); } public virtual void DeleteListEntryByListName(string ListName, string Value, bool DeleteChild) { - ExecuteNonQuery("DeleteListEntryByListName", ListName, Value, DeleteChild); + this.ExecuteNonQuery("DeleteListEntryByListName", ListName, Value, DeleteChild); } public virtual IDataReader GetList(string ListName, string ParentKey, int PortalID) { - return ExecuteReader("GetList", ListName, ParentKey, PortalID); + return this.ExecuteReader("GetList", ListName, ParentKey, PortalID); } public virtual IDataReader GetListEntriesByListName(string ListName, string ParentKey, int PortalID) { - return ExecuteReader("GetListEntries", ListName, ParentKey, GetNull(PortalID)); + return this.ExecuteReader("GetListEntries", ListName, ParentKey, this.GetNull(PortalID)); } public virtual IDataReader GetListEntry(string ListName, string Value) { - return ExecuteReader("GetListEntry", ListName, Value, -1); + return this.ExecuteReader("GetListEntry", ListName, Value, -1); } public virtual IDataReader GetListEntry(int EntryID) { - return ExecuteReader("GetListEntry", "", "", EntryID); + return this.ExecuteReader("GetListEntry", string.Empty, string.Empty, EntryID); } public virtual IDataReader GetLists(int PortalID) { - return ExecuteReader("GetLists", PortalID); + return this.ExecuteReader("GetLists", PortalID); } public virtual void UpdateListEntry(int EntryID, string Value, string Text, string Description, int LastModifiedByUserID) { - ExecuteNonQuery("UpdateListEntry", EntryID, Value, Text, Description, LastModifiedByUserID); + this.ExecuteNonQuery("UpdateListEntry", EntryID, Value, Text, Description, LastModifiedByUserID); } public virtual void UpdateListSortOrder(int EntryID, bool MoveUp) { - ExecuteNonQuery("UpdateListSortOrder", EntryID, MoveUp); - } - - #endregion - - #region Portal Aliases - + this.ExecuteNonQuery("UpdateListSortOrder", EntryID, MoveUp); + } + public virtual int AddPortalAlias(int PortalID, string HTTPAlias, string cultureCode, string skin, string browserType, bool isPrimary, int createdByUserID) { - return ExecuteScalar("AddPortalAlias", PortalID, HTTPAlias, GetNull(cultureCode), GetNull(skin), GetNull(browserType), isPrimary, createdByUserID); + return this.ExecuteScalar("AddPortalAlias", PortalID, HTTPAlias, this.GetNull(cultureCode), this.GetNull(skin), this.GetNull(browserType), isPrimary, createdByUserID); } public virtual void DeletePortalAlias(int PortalAliasID) { - ExecuteNonQuery("DeletePortalAlias", PortalAliasID); + this.ExecuteNonQuery("DeletePortalAlias", PortalAliasID); } public virtual IDataReader GetPortalAliases() { - return ExecuteReader("GetPortalAliases"); + return this.ExecuteReader("GetPortalAliases"); } public virtual IDataReader GetPortalByPortalAliasID(int PortalAliasId) { - return ExecuteReader("GetPortalByPortalAliasID", PortalAliasId); + return this.ExecuteReader("GetPortalByPortalAliasID", PortalAliasId); } public virtual void UpdatePortalAlias(string PortalAlias, int lastModifiedByUserID) { - ExecuteNonQuery("UpdatePortalAliasOnInstall", PortalAlias, lastModifiedByUserID); + this.ExecuteNonQuery("UpdatePortalAliasOnInstall", PortalAlias, lastModifiedByUserID); } public virtual void UpdatePortalAliasInfo(int PortalAliasID, int PortalID, string HTTPAlias, string cultureCode, string skin, string browserType, bool isPrimary, int lastModifiedByUserID) { - ExecuteNonQuery("UpdatePortalAlias", PortalAliasID, PortalID, HTTPAlias, GetNull(cultureCode), GetNull(skin), GetNull(browserType), isPrimary, lastModifiedByUserID); - } - - #endregion - - #region Event Queue - + this.ExecuteNonQuery("UpdatePortalAlias", PortalAliasID, PortalID, HTTPAlias, this.GetNull(cultureCode), this.GetNull(skin), this.GetNull(browserType), isPrimary, lastModifiedByUserID); + } + public virtual int AddEventMessage(string eventName, int priority, string processorType, string processorCommand, string body, string sender, string subscriberId, string authorizedRoles, string exceptionMessage, DateTime sentDate, DateTime expirationDate, string attributes) { - return ExecuteScalar("AddEventMessage", - eventName, - priority, - processorType, - processorCommand, - body, - sender, - subscriberId, - authorizedRoles, - exceptionMessage, - sentDate, - expirationDate, - attributes); + return this.ExecuteScalar( + "AddEventMessage", + eventName, + priority, + processorType, + processorCommand, + body, + sender, + subscriberId, + authorizedRoles, + exceptionMessage, + sentDate, + expirationDate, + attributes); } public virtual IDataReader GetEventMessages(string eventName) { - return ExecuteReader("GetEventMessages", eventName); + return this.ExecuteReader("GetEventMessages", eventName); } public virtual IDataReader GetEventMessagesBySubscriber(string eventName, string subscriberId) { - return ExecuteReader("GetEventMessagesBySubscriber", eventName, subscriberId); + return this.ExecuteReader("GetEventMessagesBySubscriber", eventName, subscriberId); } public virtual void SetEventMessageComplete(int eventMessageId) { - ExecuteNonQuery("SetEventMessageComplete", eventMessageId); - } - - #endregion - - #region Authentication - + this.ExecuteNonQuery("SetEventMessageComplete", eventMessageId); + } + public virtual int AddAuthentication(int packageID, string authenticationType, bool isEnabled, string settingsControlSrc, string loginControlSrc, string logoffControlSrc, int CreatedByUserID) { - return ExecuteScalar("AddAuthentication", - packageID, - authenticationType, - isEnabled, - settingsControlSrc, - loginControlSrc, - logoffControlSrc, - CreatedByUserID); + return this.ExecuteScalar( + "AddAuthentication", + packageID, + authenticationType, + isEnabled, + settingsControlSrc, + loginControlSrc, + logoffControlSrc, + CreatedByUserID); } public virtual int AddUserAuthentication(int userID, string authenticationType, string authenticationToken, int CreatedByUserID) { - return ExecuteScalar("AddUserAuthentication", userID, authenticationType, authenticationToken, + return this.ExecuteScalar("AddUserAuthentication", userID, authenticationType, authenticationToken, CreatedByUserID); } /// - /// Get a User Authentication record from slq database. DNN-4016 + /// Get a User Authentication record from slq database. DNN-4016. /// /// - /// UserAuthentication record + /// UserAuthentication record. public virtual IDataReader GetUserAuthentication(int userID) { - return ExecuteReader("GetUserAuthentication", userID); + return this.ExecuteReader("GetUserAuthentication", userID); } public virtual void DeleteAuthentication(int authenticationID) { - ExecuteNonQuery("DeleteAuthentication", authenticationID); + this.ExecuteNonQuery("DeleteAuthentication", authenticationID); } public virtual IDataReader GetAuthenticationService(int authenticationID) { - return ExecuteReader("GetAuthenticationService", authenticationID); + return this.ExecuteReader("GetAuthenticationService", authenticationID); } public virtual IDataReader GetAuthenticationServiceByPackageID(int packageID) { - return ExecuteReader("GetAuthenticationServiceByPackageID", packageID); + return this.ExecuteReader("GetAuthenticationServiceByPackageID", packageID); } public virtual IDataReader GetAuthenticationServiceByType(string authenticationType) { - return ExecuteReader("GetAuthenticationServiceByType", authenticationType); + return this.ExecuteReader("GetAuthenticationServiceByType", authenticationType); } public virtual IDataReader GetAuthenticationServices() { - return ExecuteReader("GetAuthenticationServices"); + return this.ExecuteReader("GetAuthenticationServices"); } public virtual IDataReader GetEnabledAuthenticationServices() { - return ExecuteReader("GetEnabledAuthenticationServices"); + return this.ExecuteReader("GetEnabledAuthenticationServices"); } public virtual void UpdateAuthentication(int authenticationID, int packageID, string authenticationType, bool isEnabled, string settingsControlSrc, string loginControlSrc, - string logoffControlSrc, int LastModifiedByUserID) - { - ExecuteNonQuery("UpdateAuthentication", - authenticationID, - packageID, - authenticationType, - isEnabled, - settingsControlSrc, - loginControlSrc, - logoffControlSrc, - LastModifiedByUserID); - } - - #endregion - - #region Packages - + string logoffControlSrc, int LastModifiedByUserID) + { + this.ExecuteNonQuery( + "UpdateAuthentication", + authenticationID, + packageID, + authenticationType, + isEnabled, + settingsControlSrc, + loginControlSrc, + logoffControlSrc, + LastModifiedByUserID); + } + public virtual int AddPackage(int portalID, string name, string friendlyName, string description, string type, string version, string license, string manifest, string owner, string organization, string url, string email, string releaseNotes, bool isSystemPackage, int createdByUserID, string folderName, string iconFile) { - return ExecuteScalar("AddPackage", - GetNull(portalID), - name, - friendlyName, - description, - type, - version, - license, - manifest, - owner, - organization, - url, - email, - releaseNotes, - isSystemPackage, - createdByUserID, - folderName, - iconFile); + return this.ExecuteScalar( + "AddPackage", + this.GetNull(portalID), + name, + friendlyName, + description, + type, + version, + license, + manifest, + owner, + organization, + url, + email, + releaseNotes, + isSystemPackage, + createdByUserID, + folderName, + iconFile); } public virtual void DeletePackage(int packageID) { - ExecuteNonQuery("DeletePackage", packageID); + this.ExecuteNonQuery("DeletePackage", packageID); } public virtual IDataReader GetModulePackagesInUse(int portalID, bool forHost) { - return ExecuteReader("GetModulePackagesInUse", portalID, forHost); + return this.ExecuteReader("GetModulePackagesInUse", portalID, forHost); } public virtual IDataReader GetPackageDependencies() { - return ExecuteReader("GetPackageDependencies"); + return this.ExecuteReader("GetPackageDependencies"); } - - + public virtual IDataReader GetPackages(int portalID) { - return ExecuteReader("GetPackages", GetNull(portalID)); + return this.ExecuteReader("GetPackages", this.GetNull(portalID)); } public virtual IDataReader GetPackageTypes() { - return ExecuteReader("GetPackageTypes"); + return this.ExecuteReader("GetPackageTypes"); } public virtual int RegisterAssembly(int packageID, string assemblyName, string version) { - return ExecuteScalar("RegisterAssembly", GetNull(packageID), assemblyName, version); + return this.ExecuteScalar("RegisterAssembly", this.GetNull(packageID), assemblyName, version); } public virtual int SavePackageDependency(int packageDependencyId, int packageId, string packageName, string version) { - return ExecuteScalar("SavePackageDependency", packageDependencyId, packageId, packageName, version); + return this.ExecuteScalar("SavePackageDependency", packageDependencyId, packageId, packageName, version); } public virtual bool UnRegisterAssembly(int packageID, string assemblyName) { - return ExecuteScalar("UnRegisterAssembly", packageID, assemblyName) == 1; + return this.ExecuteScalar("UnRegisterAssembly", packageID, assemblyName) == 1; } public virtual void UpdatePackage(int packageID, int portalID, string friendlyName, string description, @@ -3153,194 +3057,183 @@ public virtual void UpdatePackage(int packageID, int portalID, string friendlyNa bool isSystemPackage, int lastModifiedByUserID, string folderName, string iconFile) { - ExecuteNonQuery("UpdatePackage", - packageID, - GetNull(portalID), - friendlyName, - description, - type, - version, - license, - manifest, - owner, - organization, - url, - email, - releaseNotes, - isSystemPackage, - lastModifiedByUserID, - folderName, - iconFile); + this.ExecuteNonQuery( + "UpdatePackage", + packageID, + this.GetNull(portalID), + friendlyName, + description, + type, + version, + license, + manifest, + owner, + organization, + url, + email, + releaseNotes, + isSystemPackage, + lastModifiedByUserID, + folderName, + iconFile); } public virtual void SetCorePackageVersions() { - ExecuteNonQuery("SetCorePackageVersions"); - } - - #endregion - - #region Languages/Localization - + this.ExecuteNonQuery("SetCorePackageVersions"); + } + public virtual int AddLanguage(string cultureCode, string cultureName, string fallbackCulture, int CreatedByUserID) { - return ExecuteScalar("AddLanguage", cultureCode, cultureName, fallbackCulture, CreatedByUserID); + return this.ExecuteScalar("AddLanguage", cultureCode, cultureName, fallbackCulture, CreatedByUserID); } public virtual int AddLanguagePack(int packageID, int languageID, int dependentPackageID, int CreatedByUserID) { - return ExecuteScalar("AddLanguagePack", packageID, languageID, dependentPackageID, CreatedByUserID); + return this.ExecuteScalar("AddLanguagePack", packageID, languageID, dependentPackageID, CreatedByUserID); } public virtual int AddPortalLanguage(int portalID, int languageID, bool IsPublished, int CreatedByUserID) { - return ExecuteScalar("AddPortalLanguage", portalID, languageID, IsPublished, CreatedByUserID); + return this.ExecuteScalar("AddPortalLanguage", portalID, languageID, IsPublished, CreatedByUserID); } public virtual void DeleteLanguage(int languageID) { - ExecuteNonQuery("DeleteLanguage", languageID); + this.ExecuteNonQuery("DeleteLanguage", languageID); } public virtual void DeleteLanguagePack(int languagePackID) { - ExecuteNonQuery("DeleteLanguagePack", languagePackID); + this.ExecuteNonQuery("DeleteLanguagePack", languagePackID); } public virtual void DeletePortalLanguages(int portalID, int languageID) { - ExecuteNonQuery("DeletePortalLanguages", GetNull(portalID), GetNull(languageID)); + this.ExecuteNonQuery("DeletePortalLanguages", this.GetNull(portalID), this.GetNull(languageID)); } public virtual void EnsureLocalizationExists(int portalID, string CultureCode) { - ExecuteNonQuery("EnsureLocalizationExists", portalID, CultureCode); + this.ExecuteNonQuery("EnsureLocalizationExists", portalID, CultureCode); } public virtual void RemovePortalLocalization(int portalID, string CultureCode) { - ExecuteNonQuery("RemovePortalLocalization", portalID, CultureCode); + this.ExecuteNonQuery("RemovePortalLocalization", portalID, CultureCode); } public virtual IDataReader GetPortalLocalizations(int portalID) { - return ExecuteReader("GetPortalLocalizations", portalID); + return this.ExecuteReader("GetPortalLocalizations", portalID); } public virtual IDataReader GetLanguages() { - return ExecuteReader("GetLanguages"); + return this.ExecuteReader("GetLanguages"); } public virtual IDataReader GetLanguagePackByPackage(int packageID) { - return ExecuteReader("GetLanguagePackByPackage", packageID); + return this.ExecuteReader("GetLanguagePackByPackage", packageID); } public virtual IDataReader GetLanguagesByPortal(int portalID) { - return ExecuteReader("GetLanguagesByPortal", portalID); + return this.ExecuteReader("GetLanguagesByPortal", portalID); } public virtual string GetPortalDefaultLanguage(int portalID) { - return ExecuteScalar("GetPortalDefaultLanguage", portalID); + return this.ExecuteScalar("GetPortalDefaultLanguage", portalID); } public virtual void UpdateLanguage(int languageID, string cultureCode, string cultureName, string fallbackCulture, int LastModifiedByUserID) { - ExecuteNonQuery("UpdateLanguage", languageID, cultureCode, cultureName, fallbackCulture, + this.ExecuteNonQuery("UpdateLanguage", languageID, cultureCode, cultureName, fallbackCulture, LastModifiedByUserID); } public virtual int UpdateLanguagePack(int languagePackID, int packageID, int languageID, int dependentPackageID, int LastModifiedByUserID) { - return ExecuteScalar("UpdateLanguagePack", languagePackID, packageID, languageID, dependentPackageID, + return this.ExecuteScalar("UpdateLanguagePack", languagePackID, packageID, languageID, dependentPackageID, LastModifiedByUserID); } public virtual void UpdatePortalDefaultLanguage(int portalID, string CultureCode) { - ExecuteNonQuery("UpdatePortalDefaultLanguage", portalID, CultureCode); + this.ExecuteNonQuery("UpdatePortalDefaultLanguage", portalID, CultureCode); } public virtual void UpdatePortalLanguage(int portalID, int languageID, bool IsPublished, int UpdatedByUserID) { - ExecuteNonQuery("UpdatePortalLanguage", portalID, languageID, IsPublished, UpdatedByUserID); - } - - #endregion - - #region Folder Mappings - + this.ExecuteNonQuery("UpdatePortalLanguage", portalID, languageID, IsPublished, UpdatedByUserID); + } + public virtual void AddDefaultFolderTypes(int portalID) { - ExecuteNonQuery("AddDefaultFolderTypes", portalID); + this.ExecuteNonQuery("AddDefaultFolderTypes", portalID); } public virtual int AddFolderMapping(int portalID, string mappingName, string folderProviderType, int createdByUserID) { - return ExecuteScalar("AddFolderMapping", GetNull(portalID), mappingName, folderProviderType, + return this.ExecuteScalar("AddFolderMapping", this.GetNull(portalID), mappingName, folderProviderType, createdByUserID); } public virtual void AddFolderMappingSetting(int folderMappingID, string settingName, string settingValue, int createdByUserID) { - ExecuteNonQuery("AddFolderMappingsSetting", folderMappingID, settingName, settingValue, createdByUserID); + this.ExecuteNonQuery("AddFolderMappingsSetting", folderMappingID, settingName, settingValue, createdByUserID); } public virtual void DeleteFolderMapping(int folderMappingID) { - ExecuteNonQuery("DeleteFolderMapping", folderMappingID); + this.ExecuteNonQuery("DeleteFolderMapping", folderMappingID); } public virtual IDataReader GetFolderMapping(int folderMappingID) { - return ExecuteReader("GetFolderMapping", folderMappingID); + return this.ExecuteReader("GetFolderMapping", folderMappingID); } public virtual IDataReader GetFolderMappingByMappingName(int portalID, string mappingName) { - return ExecuteReader("GetFolderMappingByMappingName", portalID, mappingName); + return this.ExecuteReader("GetFolderMappingByMappingName", portalID, mappingName); } public virtual IDataReader GetFolderMappings(int portalID) { - return ExecuteReader("GetFolderMappings", GetNull(portalID)); + return this.ExecuteReader("GetFolderMappings", this.GetNull(portalID)); } public virtual IDataReader GetFolderMappingSetting(int folderMappingID, string settingName) { - return ExecuteReader("GetFolderMappingsSetting", folderMappingID, settingName); + return this.ExecuteReader("GetFolderMappingsSetting", folderMappingID, settingName); } public virtual IDataReader GetFolderMappingSettings(int folderMappingID) { - return ExecuteReader("GetFolderMappingsSettings", folderMappingID); + return this.ExecuteReader("GetFolderMappingsSettings", folderMappingID); } public virtual void UpdateFolderMapping(int folderMappingID, string mappingName, int priority, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateFolderMapping", folderMappingID, mappingName, priority, lastModifiedByUserID); + this.ExecuteNonQuery("UpdateFolderMapping", folderMappingID, mappingName, priority, lastModifiedByUserID); } public virtual void UpdateFolderMappingSetting(int folderMappingID, string settingName, string settingValue, int lastModifiedByUserID) { - ExecuteNonQuery("UpdateFolderMappingsSetting", folderMappingID, settingName, settingValue, + this.ExecuteNonQuery("UpdateFolderMappingsSetting", folderMappingID, settingName, settingValue, lastModifiedByUserID); - } - - #endregion - - #region Password History - + } + [Obsolete("Deprecated in Platform 9.2.0, please use the overload that takes passwordsRetained and daysRetained. Scheduled removal in v11.0.0.")] public virtual IDataReader GetPasswordHistory(int userId) { @@ -3349,7 +3242,7 @@ public virtual IDataReader GetPasswordHistory(int userId) public virtual IDataReader GetPasswordHistory(int userId, int passwordsRetained, int daysRetained) { - return ExecuteReader("GetPasswordHistory", GetNull(userId), passwordsRetained, daysRetained); + return this.ExecuteReader("GetPasswordHistory", this.GetNull(userId), passwordsRetained, daysRetained); } [Obsolete("Deprecated in Platform 9.2.0, please use the overload that takes daysRetained. Scheduled removal in v11.0.0.")] @@ -3360,75 +3253,67 @@ public virtual void AddPasswordHistory(int userId, string password, string passw public virtual void AddPasswordHistory(int userId, string password, string passwordHistory, int passwordsRetained, int daysRetained) { - ExecuteNonQuery("AddPasswordHistory", GetNull(userId), password, passwordHistory, passwordsRetained, daysRetained, GetNull(userId)); - } - - #endregion - - #region Date/Time Utiliies - + this.ExecuteNonQuery("AddPasswordHistory", this.GetNull(userId), password, passwordHistory, passwordsRetained, daysRetained, this.GetNull(userId)); + } + public virtual DateTime GetDatabaseTimeUtc() { - return ExecuteScalar("GetDatabaseTimeUtc"); + return this.ExecuteScalar("GetDatabaseTimeUtc"); } public virtual DateTime GetDatabaseTime() { - return ExecuteScalar("GetDatabaseTime"); + return this.ExecuteScalar("GetDatabaseTime"); } public virtual DateTimeOffset GetDatabaseTimeOffset() { - using (var reader = (SqlDataReader)ExecuteSQL("SELECT SYSDATETIMEOFFSET()")) + using (var reader = (SqlDataReader)this.ExecuteSQL("SELECT SYSDATETIMEOFFSET()")) { reader.Read(); return reader.GetDateTimeOffset(0); } - } - - #endregion - - #region Mobile Stuff - + } + public virtual void DeletePreviewProfile(int id) { - ExecuteNonQuery("Mobile_DeletePreviewProfile", id); + this.ExecuteNonQuery("Mobile_DeletePreviewProfile", id); } public virtual void DeleteRedirection(int id) { - ExecuteNonQuery("Mobile_DeleteRedirection", id); + this.ExecuteNonQuery("Mobile_DeleteRedirection", id); } public virtual void DeleteRedirectionRule(int id) { - ExecuteNonQuery("Mobile_DeleteRedirectionRule", id); + this.ExecuteNonQuery("Mobile_DeleteRedirectionRule", id); } public virtual IDataReader GetAllRedirections() { - return ExecuteReader("Mobile_GetAllRedirections"); + return this.ExecuteReader("Mobile_GetAllRedirections"); } public virtual IDataReader GetPreviewProfiles(int portalId) { - return ExecuteReader("Mobile_GetPreviewProfiles", portalId); + return this.ExecuteReader("Mobile_GetPreviewProfiles", portalId); } public virtual IDataReader GetRedirectionRules(int redirectionId) { - return ExecuteReader("Mobile_GetRedirectionRules", redirectionId); + return this.ExecuteReader("Mobile_GetRedirectionRules", redirectionId); } public virtual IDataReader GetRedirections(int portalId) { - return ExecuteReader("Mobile_GetRedirections", portalId); + return this.ExecuteReader("Mobile_GetRedirections", portalId); } public virtual int SavePreviewProfile(int id, int portalId, string name, int width, int height, string userAgent, int sortOrder, int userId) { - return ExecuteScalar("Mobile_SavePreviewProfile", id, portalId, name, width, height, userAgent, + return this.ExecuteScalar("Mobile_SavePreviewProfile", id, portalId, name, width, height, userAgent, sortOrder, userId); } @@ -3436,76 +3321,79 @@ public virtual int SaveRedirection(int id, int portalId, string name, int type, bool includeChildTabs, int targetType, object targetValue, bool enabled, int userId) { - return ExecuteScalar("Mobile_SaveRedirection", id, portalId, name, type, sortOrder, sourceTabId, + return this.ExecuteScalar("Mobile_SaveRedirection", id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled, userId); } public virtual void SaveRedirectionRule(int id, int redirectionId, string capbility, string expression) { - ExecuteNonQuery("Mobile_SaveRedirectionRule", id, redirectionId, capbility, expression); - } - - #endregion - - #region Logging - + this.ExecuteNonQuery("Mobile_SaveRedirectionRule", id, redirectionId, capbility, expression); + } + public virtual void AddLog(string logGUID, string logTypeKey, int logUserID, string logUserName, int logPortalID, string logPortalName, DateTime logCreateDate, string logServerName, - string logProperties, int logConfigID, ExceptionInfo exception, bool notificationActive) + string logProperties, int logConfigID, ExceptionInfo exception, bool notificationActive) { if (exception != null) { - if (!string.IsNullOrEmpty(exception.ExceptionHash)) - ExecuteNonQuery("AddException", - exception.ExceptionHash, - exception.Message, - exception.StackTrace, - exception.InnerMessage, - exception.InnerStackTrace, - exception.Source); - - - // DNN-6218 + DNN-6239 + DNN-6242: Due to change in the AddEventLog stored - // procedure in 7.4.0, we need to try a fallback especially during upgrading + if (!string.IsNullOrEmpty(exception.ExceptionHash)) + { + this.ExecuteNonQuery( + "AddException", + exception.ExceptionHash, + exception.Message, + exception.StackTrace, + exception.InnerMessage, + exception.InnerStackTrace, + exception.Source); + } + + // DNN-6218 + DNN-6239 + DNN-6242: Due to change in the AddEventLog stored + // procedure in 7.4.0, we need to try a fallback especially during upgrading int logEventID; try { - logEventID = ExecuteScalar("AddEventLog", + logEventID = this.ExecuteScalar( + "AddEventLog", logGUID, logTypeKey, - GetNull(logUserID), - GetNull(logUserName), - GetNull(logPortalID), - GetNull(logPortalName), + this.GetNull(logUserID), + this.GetNull(logUserName), + this.GetNull(logPortalID), + this.GetNull(logPortalName), logCreateDate, logServerName, logProperties, logConfigID, - GetNull(exception.ExceptionHash), + this.GetNull(exception.ExceptionHash), notificationActive); } catch (SqlException) { - var s = ExecuteScalar("AddEventLog", + var s = this.ExecuteScalar( + "AddEventLog", logGUID, logTypeKey, - GetNull(logUserID), - GetNull(logUserName), - GetNull(logPortalID), - GetNull(logPortalName), + this.GetNull(logUserID), + this.GetNull(logUserName), + this.GetNull(logPortalID), + this.GetNull(logPortalName), logCreateDate, logServerName, logProperties, logConfigID); // old SPROC wasn't returning anything; trying a workaround - if (!int.TryParse(s ?? "-1", out logEventID)) - logEventID = Null.NullInteger; + if (!int.TryParse(s ?? "-1", out logEventID)) + { + logEventID = Null.NullInteger; + } } if (!string.IsNullOrEmpty(exception.AssemblyVersion) && exception.AssemblyVersion != "-1") { - ExecuteNonQuery("AddExceptionEvent", + this.ExecuteNonQuery( + "AddExceptionEvent", logEventID, exception.AssemblyVersion, exception.PortalId, @@ -3518,26 +3406,27 @@ public virtual void AddLog(string logGUID, string logTypeKey, int logUserID, str } else { - ExecuteScalar("AddEventLog", - logGUID, - logTypeKey, - GetNull(logUserID), - GetNull(logUserName), - GetNull(logPortalID), - GetNull(logPortalName), - logCreateDate, - logServerName, - logProperties, - logConfigID, - DBNull.Value, - notificationActive); + this.ExecuteScalar( + "AddEventLog", + logGUID, + logTypeKey, + this.GetNull(logUserID), + this.GetNull(logUserName), + this.GetNull(logPortalID), + this.GetNull(logPortalName), + logCreateDate, + logServerName, + logProperties, + logConfigID, + DBNull.Value, + notificationActive); } } public virtual void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner) { - ExecuteNonQuery("AddEventLogType", logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeOwner, + this.ExecuteNonQuery("AddEventLogType", logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeOwner, logTypeCSSClass); } @@ -3549,8 +3438,9 @@ public virtual void AddLogTypeConfigInfo(bool loggingIsActive, string logTypeKey int portalID; if (logTypeKey == "*") { - logTypeKey = ""; + logTypeKey = string.Empty; } + if (logTypePortalID == "*") { portalID = -1; @@ -3559,92 +3449,94 @@ public virtual void AddLogTypeConfigInfo(bool loggingIsActive, string logTypeKey { portalID = Convert.ToInt32(logTypePortalID); } - ExecuteNonQuery("AddEventLogConfig", - GetNull(logTypeKey), - GetNull(portalID), - loggingIsActive, - keepMostRecent, - emailNotificationIsActive, - GetNull(threshold), - GetNull(notificationThresholdTime), - GetNull(notificationThresholdTimeType), - mailFromAddress, - mailToAddress); + + this.ExecuteNonQuery( + "AddEventLogConfig", + this.GetNull(logTypeKey), + this.GetNull(portalID), + loggingIsActive, + keepMostRecent, + emailNotificationIsActive, + this.GetNull(threshold), + this.GetNull(notificationThresholdTime), + this.GetNull(notificationThresholdTimeType), + mailFromAddress, + mailToAddress); } public virtual void ClearLog() { - ExecuteNonQuery("DeleteEventLog", DBNull.Value); + this.ExecuteNonQuery("DeleteEventLog", DBNull.Value); } public virtual void DeleteLog(string logGUID) { - ExecuteNonQuery("DeleteEventLog", logGUID); + this.ExecuteNonQuery("DeleteEventLog", logGUID); } public virtual void DeleteLogType(string logTypeKey) { - ExecuteNonQuery("DeleteEventLogType", logTypeKey); + this.ExecuteNonQuery("DeleteEventLogType", logTypeKey); } public virtual void DeleteLogTypeConfigInfo(string id) { - ExecuteNonQuery("DeleteEventLogConfig", id); + this.ExecuteNonQuery("DeleteEventLogConfig", id); } public virtual IDataReader GetEventLogPendingNotif(int logConfigID) { - return ExecuteReader("GetEventLogPendingNotif", logConfigID); + return this.ExecuteReader("GetEventLogPendingNotif", logConfigID); } public virtual IDataReader GetEventLogPendingNotifConfig() { - return ExecuteReader("GetEventLogPendingNotifConfig"); + return this.ExecuteReader("GetEventLogPendingNotifConfig"); } public virtual IDataReader GetLogs(int portalID, string logType, int pageSize, int pageIndex) { - return ExecuteReader("GetEventLog", GetNull(portalID), GetNull(logType), pageSize, pageIndex); + return this.ExecuteReader("GetEventLog", this.GetNull(portalID), this.GetNull(logType), pageSize, pageIndex); } public virtual IDataReader GetLogTypeConfigInfo() { - return ExecuteReader("GetEventLogConfig", DBNull.Value); + return this.ExecuteReader("GetEventLogConfig", DBNull.Value); } public virtual IDataReader GetLogTypeConfigInfoByID(int id) { - return ExecuteReader("GetEventLogConfig", id); + return this.ExecuteReader("GetEventLogConfig", id); } public virtual IDataReader GetLogTypeInfo() { - return ExecuteReader("GetEventLogType"); + return this.ExecuteReader("GetEventLogType"); } public virtual IDataReader GetSingleLog(string logGUID) { - return ExecuteReader("GetEventLogByLogGUID", logGUID); + return this.ExecuteReader("GetEventLogByLogGUID", logGUID); } public virtual void PurgeLog() { - //Because event log is run on application end, app may not be fully installed, so check for the sproc first - string sql = "IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'" + DatabaseOwner + ObjectQualifier + + // Because event log is run on application end, app may not be fully installed, so check for the sproc first + string sql = "IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'" + this.DatabaseOwner + this.ObjectQualifier + "PurgeEventLog') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) " + " BEGIN " + - " EXEC " + DatabaseOwner + ObjectQualifier + "PurgeEventLog" + " END "; - PetaPocoHelper.ExecuteNonQuery(ConnectionString, CommandType.Text, sql); + " EXEC " + this.DatabaseOwner + this.ObjectQualifier + "PurgeEventLog" + " END "; + PetaPocoHelper.ExecuteNonQuery(this.ConnectionString, CommandType.Text, sql); } public virtual void UpdateEventLogPendingNotif(int logConfigID) { - ExecuteNonQuery("UpdateEventLogPendingNotif", logConfigID); + this.ExecuteNonQuery("UpdateEventLogPendingNotif", logConfigID); } public virtual void UpdateLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner) { - ExecuteNonQuery("UpdateEventLogType", logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeOwner, + this.ExecuteNonQuery("UpdateEventLogType", logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeOwner, logTypeCSSClass); } @@ -3658,8 +3550,9 @@ public virtual void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, str int portalID; if (logTypeKey == "*") { - logTypeKey = ""; + logTypeKey = string.Empty; } + if (logTypePortalID == "*") { portalID = -1; @@ -3668,105 +3561,104 @@ public virtual void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, str { portalID = Convert.ToInt32(logTypePortalID); } - ExecuteNonQuery("UpdateEventLogConfig", - id, - GetNull(logTypeKey), - GetNull(portalID), - loggingIsActive, - keepMostRecent, - emailNotificationIsActive, - GetNull(threshold), - GetNull(notificationThresholdTime), - GetNull(notificationThresholdTimeType), - mailFromAddress, - mailToAddress); - } - - #endregion - - #region Scheduling - + + this.ExecuteNonQuery( + "UpdateEventLogConfig", + id, + this.GetNull(logTypeKey), + this.GetNull(portalID), + loggingIsActive, + keepMostRecent, + emailNotificationIsActive, + this.GetNull(threshold), + this.GetNull(notificationThresholdTime), + this.GetNull(notificationThresholdTimeType), + mailFromAddress, + mailToAddress); + } + public virtual int AddSchedule(string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, int CreatedByUserID, string FriendlyName, DateTime ScheduleStartDate) { - return ExecuteScalar("AddSchedule", - TypeFullName, - TimeLapse, - TimeLapseMeasurement, - RetryTimeLapse, - RetryTimeLapseMeasurement, - RetainHistoryNum, - AttachToEvent, - CatchUpEnabled, - Enabled, - ObjectDependencies, - GetNull(Servers), - CreatedByUserID, - FriendlyName, - GetNull(ScheduleStartDate)); + return this.ExecuteScalar( + "AddSchedule", + TypeFullName, + TimeLapse, + TimeLapseMeasurement, + RetryTimeLapse, + RetryTimeLapseMeasurement, + RetainHistoryNum, + AttachToEvent, + CatchUpEnabled, + Enabled, + ObjectDependencies, + this.GetNull(Servers), + CreatedByUserID, + FriendlyName, + this.GetNull(ScheduleStartDate)); } public virtual int AddScheduleHistory(int ScheduleID, DateTime StartDate, string Server) { - return ExecuteScalar("AddScheduleHistory", ScheduleID, FixDate(StartDate), Server); + return this.ExecuteScalar("AddScheduleHistory", ScheduleID, FixDate(StartDate), Server); } public virtual void AddScheduleItemSetting(int ScheduleID, string Name, string Value) { - ExecuteNonQuery("AddScheduleItemSetting", ScheduleID, Name, Value); + this.ExecuteNonQuery("AddScheduleItemSetting", ScheduleID, Name, Value); } public virtual void DeleteSchedule(int ScheduleID) { - ExecuteNonQuery("DeleteSchedule", ScheduleID); + this.ExecuteNonQuery("DeleteSchedule", ScheduleID); } public virtual IDataReader GetNextScheduledTask(string Server) { - return ExecuteReader("GetScheduleNextTask", GetNull(Server)); + return this.ExecuteReader("GetScheduleNextTask", this.GetNull(Server)); } public virtual IDataReader GetSchedule() { - return ExecuteReader("GetSchedule", DBNull.Value); + return this.ExecuteReader("GetSchedule", DBNull.Value); } public virtual IDataReader GetSchedule(string Server) { - return ExecuteReader("GetSchedule", GetNull(Server)); + return this.ExecuteReader("GetSchedule", this.GetNull(Server)); } public virtual IDataReader GetSchedule(int ScheduleID) { - return ExecuteReader("GetScheduleByScheduleID", ScheduleID); + return this.ExecuteReader("GetScheduleByScheduleID", ScheduleID); } public virtual IDataReader GetSchedule(string TypeFullName, string Server) { - return ExecuteReader("GetScheduleByTypeFullName", TypeFullName, GetNull(Server)); + return this.ExecuteReader("GetScheduleByTypeFullName", TypeFullName, this.GetNull(Server)); } public virtual IDataReader GetScheduleByEvent(string EventName, string Server) { - return ExecuteReader("GetScheduleByEvent", EventName, GetNull(Server)); + return this.ExecuteReader("GetScheduleByEvent", EventName, this.GetNull(Server)); } public virtual IDataReader GetScheduleHistory(int ScheduleID) { - return ExecuteReader("GetScheduleHistory", ScheduleID); + return this.ExecuteReader("GetScheduleHistory", ScheduleID); } public virtual IDataReader GetScheduleItemSettings(int ScheduleID) { - return ExecuteReader("GetScheduleItemSettings", ScheduleID); + return this.ExecuteReader("GetScheduleItemSettings", ScheduleID); } public virtual void PurgeScheduleHistory() { - ExecuteNonQuery(90, "PurgeScheduleHistory"); + this.ExecuteNonQuery(90, "PurgeScheduleHistory"); } public virtual void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeLapse, @@ -3776,117 +3668,107 @@ public virtual void UpdateSchedule(int ScheduleID, string TypeFullName, int Time string ObjectDependencies, string Servers, int LastModifiedByUserID, string FriendlyName, DateTime ScheduleStartDate) { - ExecuteNonQuery("UpdateSchedule", - ScheduleID, - TypeFullName, - TimeLapse, - TimeLapseMeasurement, - RetryTimeLapse, - RetryTimeLapseMeasurement, - RetainHistoryNum, - AttachToEvent, - CatchUpEnabled, - Enabled, - ObjectDependencies, - GetNull(Servers), - LastModifiedByUserID, - FriendlyName, - GetNull(ScheduleStartDate)); + this.ExecuteNonQuery( + "UpdateSchedule", + ScheduleID, + TypeFullName, + TimeLapse, + TimeLapseMeasurement, + RetryTimeLapse, + RetryTimeLapseMeasurement, + RetainHistoryNum, + AttachToEvent, + CatchUpEnabled, + Enabled, + ObjectDependencies, + this.GetNull(Servers), + LastModifiedByUserID, + FriendlyName, + this.GetNull(ScheduleStartDate)); } public virtual void UpdateScheduleHistory(int ScheduleHistoryID, DateTime EndDate, bool Succeeded, string LogNotes, DateTime NextStart) { - ExecuteNonQuery("UpdateScheduleHistory", ScheduleHistoryID, FixDate(EndDate), GetNull(Succeeded), LogNotes, FixDate(NextStart)); - } - - #endregion - - #region Extension Url Providers - - public virtual int AddExtensionUrlProvider(int providerId, - int desktopModuleId, - string providerName, - string providerType, - string settingsControlSrc, - bool isActive, - bool rewriteAllUrls, - bool redirectAllUrls, - bool replaceAllUrls) - { - return ExecuteScalar("AddExtensionUrlProvider", - providerId, - desktopModuleId, - providerName, - providerType, - settingsControlSrc, - isActive, - rewriteAllUrls, - redirectAllUrls, - replaceAllUrls); + this.ExecuteNonQuery("UpdateScheduleHistory", ScheduleHistoryID, FixDate(EndDate), this.GetNull(Succeeded), LogNotes, FixDate(NextStart)); + } + + public virtual int AddExtensionUrlProvider( + int providerId, + int desktopModuleId, + string providerName, + string providerType, + string settingsControlSrc, + bool isActive, + bool rewriteAllUrls, + bool redirectAllUrls, + bool replaceAllUrls) + { + return this.ExecuteScalar( + "AddExtensionUrlProvider", + providerId, + desktopModuleId, + providerName, + providerType, + settingsControlSrc, + isActive, + rewriteAllUrls, + redirectAllUrls, + replaceAllUrls); } public virtual void DeleteExtensionUrlProvider(int providerId) { - ExecuteNonQuery("DeleteExtensionUrlProvider", providerId); + this.ExecuteNonQuery("DeleteExtensionUrlProvider", providerId); } public virtual IDataReader GetExtensionUrlProviders(int portalId) { - return ExecuteReader("GetExtensionUrlProviders", GetNull(portalId)); + return this.ExecuteReader("GetExtensionUrlProviders", this.GetNull(portalId)); } public virtual void SaveExtensionUrlProviderSetting(int providerId, int portalId, string settingName, string settingValue) { - ExecuteNonQuery("SaveExtensionUrlProviderSetting", providerId, portalId, settingName, settingValue); + this.ExecuteNonQuery("SaveExtensionUrlProviderSetting", providerId, portalId, settingName, settingValue); } public virtual void UpdateExtensionUrlProvider(int providerId, bool isActive) { - ExecuteNonQuery("UpdateExtensionUrlProvider", providerId, isActive); - } - - #endregion - - #region IP Filter - - + this.ExecuteNonQuery("UpdateExtensionUrlProvider", providerId, isActive); + } + public virtual IDataReader GetIPFilters() { - return ExecuteReader("GetIPFilters"); + return this.ExecuteReader("GetIPFilters"); } public virtual int AddIPFilter(string ipAddress, string subnetMask, int ruleType, int createdByUserId) { - return ExecuteScalar("AddIPFilter", ipAddress, subnetMask, ruleType, createdByUserId); + return this.ExecuteScalar("AddIPFilter", ipAddress, subnetMask, ruleType, createdByUserId); } public virtual void DeleteIPFilter(int ipFilterid) { - ExecuteNonQuery("DeleteIPFilter", ipFilterid); + this.ExecuteNonQuery("DeleteIPFilter", ipFilterid); } public virtual void UpdateIPFilter(int ipFilterid, string ipAddress, string subnetMask, int ruleType, int lastModifiedByUserId) { - ExecuteNonQuery("UpdateIPFilter", ipFilterid, ipAddress, subnetMask, ruleType, lastModifiedByUserId); + this.ExecuteNonQuery("UpdateIPFilter", ipFilterid, ipAddress, subnetMask, ruleType, lastModifiedByUserId); } public virtual IDataReader GetIPFilter(int ipf) { - return ExecuteReader("GetIPFilter", ipf); - } - - #endregion - - #region File Versions - + return this.ExecuteReader("GetIPFilter", ipf); + } + public virtual IDataReader GetFileVersions(int fileId) { - return ExecuteReader("GetFileVersions", fileId); + return this.ExecuteReader("GetFileVersions", fileId); } public virtual IDataReader GetFileVersionsInFolder(int folderId) { - return ExecuteReader("GetFileVersionsInFolder", folderId); + return this.ExecuteReader("GetFileVersionsInFolder", folderId); } public virtual int AddFileVersion(int fileId, Guid uniqueId, Guid versionGuid, string fileName, string extension, @@ -3896,96 +3778,96 @@ public virtual int AddFileVersion(int fileId, Guid uniqueId, Guid versionGuid, s { if (content == null) { - return ExecuteScalar("AddFileVersion", - fileId, - uniqueId, - versionGuid, - fileName, - extension, - size, - GetNull(width), - GetNull(height), - contentType, - folder, - folderId, - userId, - hash, - lastModificationTime, - title, - enablePublishPeriod, - startDate, - GetNull(endDate), - GetNull(contentItemID), - published); + return this.ExecuteScalar( + "AddFileVersion", + fileId, + uniqueId, + versionGuid, + fileName, + extension, + size, + this.GetNull(width), + this.GetNull(height), + contentType, + folder, + folderId, + userId, + hash, + lastModificationTime, + title, + enablePublishPeriod, + startDate, + this.GetNull(endDate), + this.GetNull(contentItemID), + published); } - return ExecuteScalar("AddFileVersion", - fileId, - uniqueId, - versionGuid, - fileName, - extension, - size, - GetNull(width), - GetNull(height), - contentType, - folder, - folderId, - userId, - hash, - lastModificationTime, - title, - enablePublishPeriod, - startDate, - GetNull(endDate), - GetNull(contentItemID), - published, - GetNull(content)); + + return this.ExecuteScalar( + "AddFileVersion", + fileId, + uniqueId, + versionGuid, + fileName, + extension, + size, + this.GetNull(width), + this.GetNull(height), + contentType, + folder, + folderId, + userId, + hash, + lastModificationTime, + title, + enablePublishPeriod, + startDate, + this.GetNull(endDate), + this.GetNull(contentItemID), + published, + this.GetNull(content)); } public virtual int DeleteFileVersion(int fileId, int version) { - return ExecuteScalar("DeleteFileVersion", fileId, version); + return this.ExecuteScalar("DeleteFileVersion", fileId, version); } public virtual void ResetFilePublishedVersion(int fileId) { - ExecuteNonQuery("ResetFilePublishedVersion", fileId); + this.ExecuteNonQuery("ResetFilePublishedVersion", fileId); } public virtual IDataReader GetFileVersion(int fileId, int version) { - return ExecuteReader("GetFileVersion", fileId, version); + return this.ExecuteReader("GetFileVersion", fileId, version); } public void SetPublishedVersion(int fileId, int newPublishedVersion) { - ExecuteNonQuery("SetPublishedVersion", fileId, newPublishedVersion); - } - - #endregion - - #region Content Workflow - + this.ExecuteNonQuery("SetPublishedVersion", fileId, newPublishedVersion); + } + public virtual int GetContentWorkflowUsageCount(int workflowId) { - return ExecuteScalar("GetContentWorkflowUsageCount", workflowId); + return this.ExecuteScalar("GetContentWorkflowUsageCount", workflowId); } public virtual IDataReader GetContentWorkflowUsage(int workflowId, int pageIndex, int pageSize) { - return ExecuteReader("GetContentWorkflowUsage", workflowId, pageIndex, pageSize); + return this.ExecuteReader("GetContentWorkflowUsage", workflowId, pageIndex, pageSize); } public virtual int GetContentWorkflowStateUsageCount(int stateId) { - return ExecuteScalar("GetContentWorkflowStateUsageCount", stateId); + return this.ExecuteScalar("GetContentWorkflowStateUsageCount", stateId); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual int AddContentWorkflow(int portalId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) { - return ExecuteScalar("AddContentWorkflow", - GetNull(portalId), + return this.ExecuteScalar( + "AddContentWorkflow", + this.GetNull(portalId), workflowName, description, isDeleted, @@ -3997,19 +3879,20 @@ public virtual int AddContentWorkflow(int portalId, string workflowName, string [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual IDataReader GetContentWorkflow(int workflowId) { - return ExecuteReader("GetContentWorkflow", workflowId); + return this.ExecuteReader("GetContentWorkflow", workflowId); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual IDataReader GetContentWorkflows(int portalId) { - return ExecuteReader("GetContentWorkflows", portalId); + return this.ExecuteReader("GetContentWorkflows", portalId); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual void UpdateContentWorkflow(int workflowId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) { - ExecuteNonQuery("UpdateContentWorkflow", + this.ExecuteNonQuery( + "UpdateContentWorkflow", workflowId, workflowName, description, @@ -4025,7 +3908,8 @@ public virtual int AddContentWorkflowState(int workflowId, string stateName, int string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) { - return ExecuteScalar("AddContentWorkflowState", + return this.ExecuteScalar( + "AddContentWorkflowState", workflowId, stateName, order, @@ -4042,7 +3926,7 @@ public virtual int AddContentWorkflowState(int workflowId, string stateName, int [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual void DeleteContentWorkflowState(int stateId) { - ExecuteNonQuery("DeleteContentWorkflowState", stateId); + this.ExecuteNonQuery("DeleteContentWorkflowState", stateId); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] @@ -4051,7 +3935,8 @@ public virtual void UpdateContentWorkflowState(int stateId, string stateName, in string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) { - ExecuteNonQuery("UpdateContentWorkflowState", + this.ExecuteNonQuery( + "UpdateContentWorkflowState", stateId, stateName, order, @@ -4068,19 +3953,20 @@ public virtual void UpdateContentWorkflowState(int stateId, string stateName, in [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual IDataReader GetContentWorkflowState(int stateId) { - return ExecuteReader("GetContentWorkflowState", stateId); + return this.ExecuteReader("GetContentWorkflowState", stateId); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual IDataReader GetContentWorkflowStates(int workflowId) { - return ExecuteReader("GetContentWorkflowStates", workflowId); + return this.ExecuteReader("GetContentWorkflowStates", workflowId); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger.AddWorkflowLog. Scheduled removal in v10.0.0.")] public virtual int AddContentWorkflowLog(string action, string comment, int user, int workflowId, int contentItemId) { - return ExecuteScalar("AddContentWorkflowLog", + return this.ExecuteScalar( + "AddContentWorkflowLog", action, comment, user, @@ -4091,91 +3977,86 @@ public virtual int AddContentWorkflowLog(string action, string comment, int user [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger.GetWorkflowLogs. Scheduled removal in v10.0.0.")] public virtual IDataReader GetContentWorkflowLogs(int contentItemId, int workflowId) { - return ExecuteReader("GetContentWorkflowLogs", contentItemId, workflowId); + return this.ExecuteReader("GetContentWorkflowLogs", contentItemId, workflowId); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual int DeleteContentWorkflowLogs(int contentItemId, int workflowId) { - return ExecuteScalar("DeleteContentWorkflowLogs", contentItemId, workflowId); + return this.ExecuteScalar("DeleteContentWorkflowLogs", contentItemId, workflowId); } public virtual int AddContentWorkflowStatePermission(int stateId, int permissionId, int roleId, bool allowAccess, int userId, int createdByUserId) { - return ExecuteScalar("AddContentWorkflowStatePermission", + return this.ExecuteScalar( + "AddContentWorkflowStatePermission", stateId, permissionId, - GetNull(roleId), + this.GetNull(roleId), allowAccess, - GetNull(userId), - GetNull(createdByUserId)); + this.GetNull(userId), + this.GetNull(createdByUserId)); } public virtual void UpdateContentWorkflowStatePermission(int workflowStatePermissionId, int stateId, int permissionId, int roleId, bool allowAccess, int userId, int lastModifiedByUserId) { - ExecuteNonQuery("UpdateContentWorkflowStatePermission", + this.ExecuteNonQuery( + "UpdateContentWorkflowStatePermission", workflowStatePermissionId, stateId, permissionId, - GetNull(roleId), + this.GetNull(roleId), allowAccess, - GetNull(userId), - GetNull(lastModifiedByUserId)); + this.GetNull(userId), + this.GetNull(lastModifiedByUserId)); } public virtual void DeleteContentWorkflowStatePermission(int workflowStatePermissionId) { - ExecuteNonQuery("DeleteContentWorkflowStatePermission", workflowStatePermissionId); + this.ExecuteNonQuery("DeleteContentWorkflowStatePermission", workflowStatePermissionId); } public virtual IDataReader GetContentWorkflowStatePermission(int workflowStatePermissionId) { - return ExecuteReader("GetContentWorkflowStatePermission", workflowStatePermissionId); + return this.ExecuteReader("GetContentWorkflowStatePermission", workflowStatePermissionId); } public virtual IDataReader GetContentWorkflowStatePermissions() { - return ExecuteReader("GetContentWorkflowStatePermissions"); + return this.ExecuteReader("GetContentWorkflowStatePermissions"); } public virtual IDataReader GetContentWorkflowStatePermissionsByStateID(int stateId) { - return ExecuteReader("GetContentWorkflowStatePermissionsByStateID", stateId); + return this.ExecuteReader("GetContentWorkflowStatePermissionsByStateID", stateId); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual IDataReader GetContentWorkflowSource(int workflowId, string sourceName) { - return ExecuteReader("GetContentWorkflowSource", workflowId, sourceName); + return this.ExecuteReader("GetContentWorkflowSource", workflowId, sourceName); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual int AddContentWorkflowSource(int workflowId, string sourceName, string sourceType) { - return ExecuteScalar("AddContentWorkflowSource", workflowId, sourceName, sourceType); - } - - #endregion - - #region Search Crawler - + return this.ExecuteScalar("AddContentWorkflowSource", workflowId, sourceName, sourceType); + } + public virtual IDataReader GetAllSearchTypes() { - return ExecuteReader("SearchTypes_GetAll"); - } - - #endregion - - #region Search Synonyms Groups - + return this.ExecuteReader("SearchTypes_GetAll"); + } + public virtual IDataReader GetAllSynonymsGroups(int portalId, string cultureCode) { - return ExecuteReader("GetAllSynonymsGroups", portalId, cultureCode); + return this.ExecuteReader("GetAllSynonymsGroups", portalId, cultureCode); } public virtual int AddSynonymsGroup(string synonymsTags, int createdByUserId, int portalId, string cultureCode) { - return ExecuteScalar("AddSynonymsGroup", + return this.ExecuteScalar( + "AddSynonymsGroup", synonymsTags, createdByUserId, portalId, @@ -4184,47 +4065,39 @@ public virtual int AddSynonymsGroup(string synonymsTags, int createdByUserId, in public virtual void UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int lastModifiedUserId) { - ExecuteNonQuery("UpdateSynonymsGroup", synonymsGroupId, synonymsTags, lastModifiedUserId); + this.ExecuteNonQuery("UpdateSynonymsGroup", synonymsGroupId, synonymsTags, lastModifiedUserId); } public virtual void DeleteSynonymsGroup(int synonymsGroupId) { - ExecuteNonQuery("DeleteSynonymsGroup", synonymsGroupId); - } - - #endregion - - #region Search Stop Words - + this.ExecuteNonQuery("DeleteSynonymsGroup", synonymsGroupId); + } + public virtual IDataReader GetSearchStopWords(int portalId, string cultureCode) { - return ExecuteReader("GetSearchStopWords", portalId, cultureCode); + return this.ExecuteReader("GetSearchStopWords", portalId, cultureCode); } public virtual int AddSearchStopWords(string stopWords, int createdByUserId, int portalId, string cultureCode) { - return ExecuteScalar("InsertSearchStopWords", stopWords, createdByUserId, portalId, cultureCode); + return this.ExecuteScalar("InsertSearchStopWords", stopWords, createdByUserId, portalId, cultureCode); } public virtual void UpdateSearchStopWords(int stopWordsId, string stopWords, int lastModifiedUserId) { - ExecuteNonQuery("UpdateSearchStopWords", stopWordsId, stopWords, lastModifiedUserId); + this.ExecuteNonQuery("UpdateSearchStopWords", stopWordsId, stopWords, lastModifiedUserId); } public virtual void DeleteSearchStopWords(int stopWordsId) { - ExecuteNonQuery("DeleteSearchStopWords", stopWordsId); - } - - #endregion - - #region Search deleted items related methods - + this.ExecuteNonQuery("DeleteSearchStopWords", stopWordsId); + } + public void AddSearchDeletedItems(SearchDocumentToDelete deletedIDocument) { try { - ExecuteNonQuery("SearchDeletedItems_Add", deletedIDocument.ToJsonString()); + this.ExecuteNonQuery("SearchDeletedItems_Add", deletedIDocument.ToJsonString()); } catch (SqlException ex) { @@ -4236,7 +4109,7 @@ public void DeleteProcessedSearchDeletedItems(DateTime cutoffTime) { try { - ExecuteNonQuery("SearchDeletedItems_DeleteProcessed", cutoffTime); + this.ExecuteNonQuery("SearchDeletedItems_DeleteProcessed", cutoffTime); } catch (SqlException ex) { @@ -4246,22 +4119,14 @@ public void DeleteProcessedSearchDeletedItems(DateTime cutoffTime) public IDataReader GetSearchDeletedItems(DateTime cutoffTime) { - return ExecuteReader("SearchDeletedItems_Select", cutoffTime); - } - - #endregion - - #region User Index Methods - + return this.ExecuteReader("SearchDeletedItems_Select", cutoffTime); + } + public virtual IDataReader GetAvailableUsersForIndex(int portalId, DateTime startDate, int startUserId, int numberOfUsers) { - return ExecuteReader(90, "GetAvailableUsersForIndex", portalId, startDate, startUserId, numberOfUsers); - } - - #endregion - - #region OutputCache Methods - + return this.ExecuteReader(90, "GetAvailableUsersForIndex", portalId, startDate, startUserId, numberOfUsers); + } + public virtual void AddOutputCacheItem(int itemId, string cacheKey, string output, DateTime expiration) { Instance().ExecuteNonQuery("OutputCacheAddItem", itemId, cacheKey, output, expiration); @@ -4300,67 +4165,53 @@ public virtual void PurgeOutputCache() public virtual void RemoveOutputCacheItem(int itemId) { Instance().ExecuteNonQuery("OutputCacheRemoveItem", itemId); - } - - #endregion - - #region Redirec Display Messages - + } + public virtual Guid AddRedirectMessage(int userId, int tabId, string text) { - return ExecuteScalar("AddRedirectMessage", userId, tabId, text); + return this.ExecuteScalar("AddRedirectMessage", userId, tabId, text); } public virtual string GetRedirectMessage(Guid id) { - return ExecuteScalar("GetRedirectMessage", id); + return this.ExecuteScalar("GetRedirectMessage", id); } public virtual void DeleteOldRedirectMessage(DateTime cutofDateTime) { - ExecuteNonQuery("DeleteOldRedirectMessage", FixDate(cutofDateTime)); - } - - #endregion - - #region User Cookies persistence - + this.ExecuteNonQuery("DeleteOldRedirectMessage", FixDate(cutofDateTime)); + } + public virtual void UpdateAuthCookie(string cookieValue, DateTime utcExpiry, int userId) { - ExecuteNonQuery("AuthCookies_Update", cookieValue, FixDate(utcExpiry), userId); + this.ExecuteNonQuery("AuthCookies_Update", cookieValue, FixDate(utcExpiry), userId); } public virtual IDataReader FindAuthCookie(string cookieValue) { - return ExecuteReader("AuthCookies_Find", cookieValue); + return this.ExecuteReader("AuthCookies_Find", cookieValue); } public virtual void DeleteAuthCookie(string cookieValue) { - ExecuteNonQuery("AuthCookies_DeleteByValue", cookieValue); + this.ExecuteNonQuery("AuthCookies_DeleteByValue", cookieValue); } public virtual void DeleteExpiredAuthCookies(DateTime utcExpiredBefore) { - ExecuteNonQuery("AuthCookies_DeleteOld", FixDate(utcExpiredBefore)); - } - - #endregion - - #endregion - - #region Obsolete Methods - + this.ExecuteNonQuery("AuthCookies_DeleteOld", FixDate(utcExpiredBefore)); + } + [Obsolete("Deprecated in 7.0.0. This method is unneccessary. You can get a reader and convert it to a DataSet. Scheduled removal in v10.0.0.")] public virtual DataSet ExecuteDataSet(string procedureName, params object[] commandParameters) { - return Globals.ConvertDataReaderToDataSet(ExecuteReader(procedureName, commandParameters)); + return Globals.ConvertDataReaderToDataSet(this.ExecuteReader(procedureName, commandParameters)); } [Obsolete("Deprecated in 7.0.0. This method is unneccessary. Use the generic version ExecuteScalar.. Scheduled removal in v10.0.0.")] public virtual object ExecuteScalar(string procedureName, params object[] commandParameters) { - return ExecuteScalar(procedureName, commandParameters); + return this.ExecuteScalar(procedureName, commandParameters); } [Obsolete("Temporarily Added in DNN 5.4.2. This will be removed and replaced with named instance support.. Scheduled removal in v10.0.0.")] @@ -4375,14 +4226,15 @@ public virtual IDataReader ExecuteSQL(string sql, params IDataParameter[] comman sqlCommandParameters[intIndex] = (SqlParameter)commandParameters[intIndex]; } } + sql = DataUtil.ReplaceTokens(sql); try { - return SqlHelper.ExecuteReader(ConnectionString, CommandType.Text, sql, sqlCommandParameters); + return SqlHelper.ExecuteReader(this.ConnectionString, CommandType.Text, sql, sqlCommandParameters); } catch { - //error in SQL query + // error in SQL query return null; } } @@ -4390,10 +4242,7 @@ public virtual IDataReader ExecuteSQL(string sql, params IDataParameter[] comman [Obsolete("Obsoleted in 9.3.0, please use GetFiles(int, bool, boo) instead. schedule to remove in 11.0.0.")] public virtual IDataReader GetFiles(int folderId, bool retrieveUnpublishedFiles = false) { - return GetFiles(folderId, retrieveUnpublishedFiles, false); - } - - #endregion - + return this.GetFiles(folderId, retrieveUnpublishedFiles, false); + } } } diff --git a/DNN Platform/Library/Data/DataUtil.cs b/DNN Platform/Library/Data/DataUtil.cs index fd36435f88f..1f7fecbe2a9 100644 --- a/DNN Platform/Library/Data/DataUtil.cs +++ b/DNN Platform/Library/Data/DataUtil.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.Globalization; -using System.Reflection; -using System.Text; -using DotNetNuke.Collections; -using DotNetNuke.ComponentModel.DataAnnotations; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data { + using System; + using System.Data; + using System.Globalization; + using System.Reflection; + using System.Text; + + using DotNetNuke.Collections; + using DotNetNuke.ComponentModel.DataAnnotations; + internal static class DataUtil { internal static string GenerateExecuteStoredProcedureSql(string procedureName, params object[] args) @@ -31,6 +32,7 @@ internal static string GenerateExecuteStoredProcedureSql(string procedureName, p { // Add output for output params parameterFormat += " output"; } + parameterName = param.ParameterName; } @@ -91,15 +93,15 @@ internal static string GetColumnName(PropertyInfo propertyInfo, string defaultNa internal static bool GetIsCacheable(Type type) { - return (GetAttribute(type) != null); + return GetAttribute(type) != null; } internal static TProperty GetPrimaryKey(TEntity item) { Type modelType = typeof(TEntity); - //Get the primary key - var primaryKeyName = GetPrimaryKeyProperty(modelType, String.Empty); + // Get the primary key + var primaryKeyName = GetPrimaryKeyProperty(modelType, string.Empty); return GetPropertyValue(item, primaryKeyName); } @@ -140,7 +142,7 @@ internal static TProperty GetPropertyValue(TEntity item, str internal static string GetTableName(Type type) { - return GetTableName(type, String.Empty); + return GetTableName(type, string.Empty); } internal static string GetTableName(Type type, string defaultName) @@ -159,7 +161,7 @@ internal static string GetTableName(Type type, string defaultName) internal static string ReplaceTokens(string sql) { var isSqlCe = DataProvider.Instance().Settings.GetValueOrDefault("isSqlCe", false); - return sql.Replace("{databaseOwner}", (isSqlCe) ? String.Empty : DataProvider.Instance().DatabaseOwner) + return sql.Replace("{databaseOwner}", isSqlCe ? string.Empty : DataProvider.Instance().DatabaseOwner) .Replace("{objectQualifier}", DataProvider.Instance().ObjectQualifier); } } diff --git a/DNN Platform/Library/Data/DatabaseConnectionProvider.cs b/DNN Platform/Library/Data/DatabaseConnectionProvider.cs index b13a46961f5..b55504066ce 100644 --- a/DNN Platform/Library/Data/DatabaseConnectionProvider.cs +++ b/DNN Platform/Library/Data/DatabaseConnectionProvider.cs @@ -1,31 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region usings - -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Data { + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.ComponentModel; + public abstract class DatabaseConnectionProvider - { - #region Shared/Static Methods - + { public static DatabaseConnectionProvider Instance() { return ComponentFactory.GetComponent(); - } - - #endregion - - #region Public Methods - + } + public abstract int ExecuteNonQuery(string connectionString, CommandType commandType, int commandTimeout, string query); public abstract void ExecuteNonQuery(string connectionString, CommandType commandType, int commandTimeout, string procedure, object[] commandParameters); @@ -38,8 +27,6 @@ public static DatabaseConnectionProvider Instance() public abstract void BulkInsert(string connectionString, int commandTimeout, string procedureName, string tableParameterName, DataTable dataTable); - public abstract void BulkInsert(string connectionString, int commandTimeout, string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters); - - #endregion + public abstract void BulkInsert(string connectionString, int commandTimeout, string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters); } } diff --git a/DNN Platform/Library/Data/IDataContext.cs b/DNN Platform/Library/Data/IDataContext.cs index 4cbe902ddbc..1aa6def0802 100644 --- a/DNN Platform/Library/Data/IDataContext.cs +++ b/DNN Platform/Library/Data/IDataContext.cs @@ -1,24 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data { + using System; + using System.Collections.Generic; + using System.Data; + public interface IDataContext : IDisposable { void BeginTransaction(); + void Commit(); void Execute(CommandType type, string sql, params object[] args); + IEnumerable ExecuteQuery(CommandType type, string sql, params object[] args); + T ExecuteScalar(CommandType type, string sql, params object[] args); + T ExecuteSingleOrDefault(CommandType type, string sql, params object[] args); - IRepository GetRepository() where T : class; + IRepository GetRepository() + where T : class; + void RollbackTransaction(); } } diff --git a/DNN Platform/Library/Data/IRepository.cs b/DNN Platform/Library/Data/IRepository.cs index a4e23461e35..d12644d3ebd 100644 --- a/DNN Platform/Library/Data/IRepository.cs +++ b/DNN Platform/Library/Data/IRepository.cs @@ -1,134 +1,135 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - -using DotNetNuke.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data { - public interface IRepository where T : class + using System.Collections.Generic; + + using DotNetNuke.Collections; + + public interface IRepository + where T : class { /// - /// Delete an Item from the repository + /// Delete an Item from the repository. /// - /// The item to be deleted + /// The item to be deleted. void Delete(T item); /// - /// Delete items from the repository based on a sql Condition + /// Delete items from the repository based on a sql Condition. /// - /// The sql condition e.g. "WHERE ArticleId = {0}" - /// A collection of arguments to be mapped to the tokens in the sqlCondition + /// The sql condition e.g. "WHERE ArticleId = {0}". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. void Delete(string sqlCondition, params object[] args); /// - /// Find items from the repository based on a sql condition + /// Find items from the repository based on a sql condition. /// - /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." - /// as well as a SQL condition like "WHERE ..." - /// The sql condition e.g. "WHERE ArticleId = @0" - /// A collection of arguments to be mapped to the tokens in the sqlCondition - /// Find("where ArticleId = @0 and UserId = @1", articleId, userId) - /// A list of items + /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." + /// as well as a SQL condition like "WHERE ...". + /// The sql condition e.g. "WHERE ArticleId = @0". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. + /// Find("where ArticleId = @0 and UserId = @1", articleId, userId). + /// A list of items. IEnumerable Find(string sqlCondition, params object[] args); /// - /// Find a GetPage of items from the repository based on a sql condition + /// Find a GetPage of items from the repository based on a sql condition. /// - /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." - /// as well as a SQL condition like "WHERE ..." - /// The page Index to fetch - /// The size of the page to fetch - /// The sql condition e.g. "WHERE ArticleId = @0" - /// A collection of arguments to be mapped to the tokens in the sqlCondition - /// A list of items + /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." + /// as well as a SQL condition like "WHERE ...". + /// The page Index to fetch. + /// The size of the page to fetch. + /// The sql condition e.g. "WHERE ArticleId = @0". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. + /// A list of items. IPagedList Find(int pageIndex, int pageSize, string sqlCondition, params object[] args); /// - /// Returns all the items in the repository as an enumerable list + /// Returns all the items in the repository as an enumerable list. /// - /// The list of items + /// The list of items. IEnumerable Get(); /// - /// Returns an enumerable list of items filtered by scope + /// Returns an enumerable list of items filtered by scope. /// /// - /// This overload should be used to get a list of items for a specific module - /// instance or for a specific portal dependening on how the items in the repository + /// This overload should be used to get a list of items for a specific module + /// instance or for a specific portal dependening on how the items in the repository /// are scoped. /// - /// The type of the scope field - /// The value of the scope to filter by - /// The list of items + /// The type of the scope field. + /// The value of the scope to filter by. + /// The list of items. IEnumerable Get(TScopeType scopeValue); /// - /// Get an individual item based on the items Id field + /// Get an individual item based on the items Id field. /// - /// The type of the Id field - /// The value of the Id field - /// An item + /// The type of the Id field. + /// The value of the Id field. + /// An item. T GetById(TProperty id); /// - /// Get an individual item based on the items Id field + /// Get an individual item based on the items Id field. /// /// /// This overload should be used to get an item for a specific module - /// instance or for a specific portal dependening on how the items in the repository + /// instance or for a specific portal dependening on how the items in the repository /// are scoped. This will allow the relevant cache to be searched first. /// - /// The type of the Id field - /// The value of the Id field - /// The type of the scope field - /// The value of the scope to filter by - /// An item + /// The type of the Id field. + /// The value of the Id field. + /// The type of the scope field. + /// The value of the scope to filter by. + /// An item. T GetById(TProperty id, TScopeType scopeValue); /// - /// Returns a page of items in the repository as a paged list + /// Returns a page of items in the repository as a paged list. /// - /// The page Index to fetch - /// The size of the page to fetch - /// The list of items + /// The page Index to fetch. + /// The size of the page to fetch. + /// The list of items. IPagedList GetPage(int pageIndex, int pageSize); /// - /// Returns a page of items in the repository as a paged list filtered by scope + /// Returns a page of items in the repository as a paged list filtered by scope. /// /// - /// This overload should be used to get a list of items for a specific module - /// instance or for a specific portal dependening on how the items in the repository + /// This overload should be used to get a list of items for a specific module + /// instance or for a specific portal dependening on how the items in the repository /// are scoped. /// - /// The type of the scope field - /// The value of the scope to filter by - /// The page Index to fetch - /// The size of the page to fetch - /// The list of items + /// The type of the scope field. + /// The value of the scope to filter by. + /// The page Index to fetch. + /// The size of the page to fetch. + /// The list of items. IPagedList GetPage(TScopeType scopeValue, int pageIndex, int pageSize); /// - /// Inserts an Item into the repository + /// Inserts an Item into the repository. /// - /// The item to be inserted + /// The item to be inserted. void Insert(T item); /// - /// Updates an Item in the repository + /// Updates an Item in the repository. /// - /// The item to be updated + /// The item to be updated. void Update(T item); /// - /// Update items in the repository based on a sql Condition + /// Update items in the repository based on a sql Condition. /// - /// The sql condition e.g. "SET ArticelName = @1 WHERE ArticleId = @0" - /// A collection of arguments to be mapped to the tokens in the sqlCondition - /// Update("SET Age=@1, Name=@2 WHERE ID=@0", 1, 21, "scooby"); + /// The sql condition e.g. "SET ArticelName = @1 WHERE ArticleId = @0". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. + /// Update("SET Age=@1, Name=@2 WHERE ID=@0", 1, 21, "scooby"). void Update(string sqlCondition, params object[] args); } } diff --git a/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs b/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs index 3a6d2b7a7ea..f7173eda2c0 100644 --- a/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs +++ b/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs @@ -1,31 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// -// Influenced by http://sameproblemmorecode.blogspot.nl/2013/07/petapoco-as-its-meant-to-be-with.html -// https://github.com/luuksommers/PetaPoco - -using System; -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data.PetaPoco { + using System; + using global::PetaPoco; + [CLSCompliant(false)] public class FluentColumnMap { + public FluentColumnMap() + { + } + + public FluentColumnMap(ColumnInfo columnInfo) + : this(columnInfo, null) + { + } + + public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConverter) + : this(columnInfo, fromDbConverter, null) + { + } + public ColumnInfo ColumnInfo { get; set; } + public Func FromDbConverter { get; set; } + public Func ToDbConverter { get; set; } - - public FluentColumnMap() { } - public FluentColumnMap(ColumnInfo columnInfo) : this(columnInfo, null) { } - public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConverter) : this(columnInfo, fromDbConverter, null) { } + public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConverter, Func toDbConverter) { - ColumnInfo = columnInfo; - FromDbConverter = fromDbConverter; - ToDbConverter = toDbConverter; + this.ColumnInfo = columnInfo; + this.FromDbConverter = fromDbConverter; + this.ToDbConverter = toDbConverter; } } } diff --git a/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs b/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs index 1dc5de5418f..c3a1f9be247 100644 --- a/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs +++ b/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs @@ -1,19 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// -// Influenced by http://sameproblemmorecode.blogspot.nl/2013/07/petapoco-as-its-meant-to-be-with.html -// https://github.com/luuksommers/PetaPoco - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Web.Caching; -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data.PetaPoco { + using System; + using System.Collections.Generic; + using System.Reflection; + using System.Web.Caching; + using global::PetaPoco; + [CLSCompliant(false)] public class FluentMapper : IMapper { @@ -21,13 +17,13 @@ public class FluentMapper : IMapper public FluentMapper(string tablePrefix) { - CacheKey = String.Empty; - CachePriority = CacheItemPriority.Default; - CacheTimeOut = 0; - Mappings = new Dictionary(); - Scope = String.Empty; - TableInfo = new TableInfo(); - _tablePrefix = tablePrefix; + this.CacheKey = string.Empty; + this.CachePriority = CacheItemPriority.Default; + this.CacheTimeOut = 0; + this.Mappings = new Dictionary(); + this.Scope = string.Empty; + this.TableInfo = new TableInfo(); + this._tablePrefix = tablePrefix; } public string CacheKey { get; set; } @@ -44,14 +40,17 @@ public FluentMapper(string tablePrefix) public TableInfo GetTableInfo(Type pocoType) { - return TableInfo; + return this.TableInfo; } public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) { var fluentMap = default(FluentColumnMap); - if (Mappings.TryGetValue(pocoProperty.Name, out fluentMap)) - return fluentMap.ColumnInfo; + if (this.Mappings.TryGetValue(pocoProperty.Name, out fluentMap)) + { + return fluentMap.ColumnInfo; + } + return null; } @@ -59,8 +58,11 @@ public Func GetFromDbConverter(PropertyInfo targetProperty, Type { // ReSharper disable once RedundantAssignment var fluentMap = default(FluentColumnMap); - if (Mappings.TryGetValue(targetProperty.Name, out fluentMap)) - return fluentMap.FromDbConverter; + if (this.Mappings.TryGetValue(targetProperty.Name, out fluentMap)) + { + return fluentMap.FromDbConverter; + } + return null; } @@ -68,14 +70,17 @@ public Func GetToDbConverter(PropertyInfo sourceProperty) { // ReSharper disable once RedundantAssignment var fluentMap = default(FluentColumnMap); - if (Mappings.TryGetValue(sourceProperty.Name, out fluentMap)) - return fluentMap.ToDbConverter; + if (this.Mappings.TryGetValue(sourceProperty.Name, out fluentMap)) + { + return fluentMap.ToDbConverter; + } + return null; } public string GetTablePrefix() { - return _tablePrefix; + return this._tablePrefix; } } } diff --git a/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs b/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs index bad0b3f9fbb..61989f76a5e 100644 --- a/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs +++ b/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs @@ -1,18 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// -// Influenced by http://sameproblemmorecode.blogspot.nl/2013/07/petapoco-as-its-meant-to-be-with.html -// https://github.com/luuksommers/PetaPoco - -using System; -using System.Linq.Expressions; -using System.Web.Caching; -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data.PetaPoco { + using System; + using System.Linq.Expressions; + using System.Web.Caching; + + using global::PetaPoco; + public static class FluentMapperExtensions { public static FluentMapper AddFluentMapper(this IDataContext dataContext) @@ -38,17 +35,20 @@ public static FluentMapper Cache(this FluentMapper mappe return mapper; } - public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, bool primaryKey = false, bool readOnly = false) where TModel : class + public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, bool primaryKey = false, bool readOnly = false) + where TModel : class { return mapper.Property(action, column, null, primaryKey, readOnly); } - public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, bool primaryKey = false, bool readOnly = false) where TModel : class + public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, bool primaryKey = false, bool readOnly = false) + where TModel : class { return mapper.Property(action, column, fromDbConverter, null, primaryKey, readOnly); } - public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, Func toDbConverter, bool primaryKey = false, bool readOnly = false) where TModel : class + public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, Func toDbConverter, bool primaryKey = false, bool readOnly = false) + where TModel : class { var expression = (MemberExpression)action.Body; string name = expression.Member.Name; @@ -57,10 +57,14 @@ public static FluentMapper Property(this FluentMapper if (primaryKey) { - if (!string.IsNullOrEmpty(mapper.TableInfo.PrimaryKey)) - mapper.TableInfo.PrimaryKey += ","; + if (!string.IsNullOrEmpty(mapper.TableInfo.PrimaryKey)) + { + mapper.TableInfo.PrimaryKey += ","; + } + mapper.TableInfo.PrimaryKey += column; } + return mapper; } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs index 2c3d28c0b71..3edb093489d 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using DotNetNuke.Common; -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data.PetaPoco { + using System; + using System.Collections.Generic; + using System.Configuration; + using System.Data; + + using DotNetNuke.Common; + using global::PetaPoco; + [CLSCompliant(false)] public class PetaPocoDataContext : IDataContext - { - #region Private Members - + { private readonly Database _database; - private readonly IMapper _mapper; - - #endregion - - #region Constructors - + private readonly IMapper _mapper; + public PetaPocoDataContext() - : this(ConfigurationManager.ConnectionStrings[0].Name, String.Empty) + : this(ConfigurationManager.ConnectionStrings[0].Name, string.Empty) { } public PetaPocoDataContext(string connectionStringName) - : this(connectionStringName, String.Empty, new Dictionary()) + : this(connectionStringName, string.Empty, new Dictionary()) { } @@ -42,34 +37,30 @@ public PetaPocoDataContext(string connectionStringName, string tablePrefix, Dict { Requires.NotNullOrEmpty("connectionStringName", connectionStringName); - _database = new Database(connectionStringName); - _mapper = new PetaPocoMapper(tablePrefix); - TablePrefix = tablePrefix; - FluentMappers = mappers; - } - - #endregion - + this._database = new Database(connectionStringName); + this._mapper = new PetaPocoMapper(tablePrefix); + this.TablePrefix = tablePrefix; + this.FluentMappers = mappers; + } + public Dictionary FluentMappers { get; private set; } - public string TablePrefix { get; private set; } - - #region Implementation of IDataContext + public string TablePrefix { get; private set; } - public void BeginTransaction() + public bool EnableAutoSelect { - _database.BeginTransaction(); + get { return this._database.EnableAutoSelect; } + set { this._database.EnableAutoSelect = value; } } - - public void Commit() + + public void BeginTransaction() { - _database.CompleteTransaction(); + this._database.BeginTransaction(); } - public bool EnableAutoSelect + public void Commit() { - get { return _database.EnableAutoSelect; } - set { _database.EnableAutoSelect = value; } + this._database.CompleteTransaction(); } public void Execute(CommandType type, string sql, params object[] args) @@ -79,18 +70,18 @@ public void Execute(CommandType type, string sql, params object[] args) sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); } - _database.Execute(DataUtil.ReplaceTokens(sql), args); + this._database.Execute(DataUtil.ReplaceTokens(sql), args); } public IEnumerable ExecuteQuery(CommandType type, string sql, params object[] args) { - PetaPocoMapper.SetMapper(_mapper); + PetaPocoMapper.SetMapper(this._mapper); if (type == CommandType.StoredProcedure) { sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); } - return _database.Fetch(DataUtil.ReplaceTokens(sql), args); + return this._database.Fetch(DataUtil.ReplaceTokens(sql), args); } public T ExecuteScalar(CommandType type, string sql, params object[] args) @@ -100,37 +91,38 @@ public T ExecuteScalar(CommandType type, string sql, params object[] args) sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); } - return _database.ExecuteScalar(DataUtil.ReplaceTokens(sql), args); + return this._database.ExecuteScalar(DataUtil.ReplaceTokens(sql), args); } public T ExecuteSingleOrDefault(CommandType type, string sql, params object[] args) { - PetaPocoMapper.SetMapper(_mapper); + PetaPocoMapper.SetMapper(this._mapper); if (type == CommandType.StoredProcedure) { sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); } - return _database.SingleOrDefault(DataUtil.ReplaceTokens(sql), args); + return this._database.SingleOrDefault(DataUtil.ReplaceTokens(sql), args); } - public IRepository GetRepository() where T : class + public IRepository GetRepository() + where T : class { PetaPocoRepository rep = null; - //Determine whether to use a Fluent Mapper - if (FluentMappers.ContainsKey(typeof (T))) + // Determine whether to use a Fluent Mapper + if (this.FluentMappers.ContainsKey(typeof(T))) { - var fluentMapper = FluentMappers[typeof(T)] as FluentMapper; + var fluentMapper = this.FluentMappers[typeof(T)] as FluentMapper; if (fluentMapper != null) { - rep = new PetaPocoRepository(_database, fluentMapper); + rep = new PetaPocoRepository(this._database, fluentMapper); rep.Initialize(fluentMapper.CacheKey, fluentMapper.CacheTimeOut, fluentMapper.CachePriority, fluentMapper.Scope); } } else { - rep = new PetaPocoRepository(_database, _mapper); + rep = new PetaPocoRepository(this._database, this._mapper); } return rep; @@ -138,18 +130,12 @@ public IRepository GetRepository() where T : class public void RollbackTransaction() { - _database.AbortTransaction(); - } - - #endregion - - #region Implementation of IDisposable - + this._database.AbortTransaction(); + } + public void Dispose() { - _database.Dispose(); - } - - #endregion + this._database.Dispose(); + } } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs index 7df6af72644..78f6ae9d857 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; - -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data.PetaPoco { + using System; + using System.Data; + + using global::PetaPoco; + public static class PetaPocoExt { public static IDataReader ExecuteReader(this Database database, string sql, params object[] args) @@ -30,10 +30,11 @@ public static IDataReader ExecuteReader(this Database database, string sql, para { throw; } + reader = null; } + return reader; - } } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs index c247806dea7..d2957d2e824 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data.PetaPoco { + using System; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using global::PetaPoco; + public static class PetaPocoHelper { + private const string SqlProviderName = "System.Data.SqlClient"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PetaPocoHelper)); - - private const string SqlProviderName = "System.Data.SqlClient"; - - #region Public Methods - + public static void ExecuteNonQuery(string connectionString, CommandType type, string sql, params object[] args) { ExecuteNonQuery(connectionString, type, Null.NullInteger, sql, args); @@ -63,12 +62,16 @@ public static void BulkInsert(string connectionString, int timeoutSec, string pr using (var con = new SqlConnection(connectionString)) using (var cmd = new SqlCommand(procedureName, con)) { - if (!tableParameterName.StartsWith("@")) - tableParameterName = "@" + tableParameterName; - - if (timeoutSec > 0) - cmd.CommandTimeout = timeoutSec; - + if (!tableParameterName.StartsWith("@")) + { + tableParameterName = "@" + tableParameterName; + } + + if (timeoutSec > 0) + { + cmd.CommandTimeout = timeoutSec; + } + cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue(tableParameterName, dataTable); con.Open(); @@ -81,10 +84,12 @@ public static void BulkInsert(string connectionString, int timeoutSec, string pr Logger.Error("[2] Error executing SQL: " + cmd.CommandText + Environment.NewLine + ex.Message); throw; } + con.Close(); } } } + public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable, Dictionary args) { BulkInsert(connectionString, procedureName, tableParameterName, dataTable, Null.NullInteger, args); @@ -97,18 +102,23 @@ public static void BulkInsert(string connectionString, string procedureName, str using (var con = new SqlConnection(connectionString)) using (var cmd = new SqlCommand(procedureName, con)) { - if (!tableParameterName.StartsWith("@")) - tableParameterName = "@" + tableParameterName; - - if (timeoutSec > 0) - cmd.CommandTimeout = timeoutSec; - + if (!tableParameterName.StartsWith("@")) + { + tableParameterName = "@" + tableParameterName; + } + + if (timeoutSec > 0) + { + cmd.CommandTimeout = timeoutSec; + } + cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue(tableParameterName, dataTable); foreach (var arg in args) { cmd.Parameters.AddWithValue(arg.Key, arg.Value); } + con.Open(); try { @@ -119,6 +129,7 @@ public static void BulkInsert(string connectionString, string procedureName, str Logger.Error("[2] Error executing SQL: " + cmd.CommandText); throw; } + con.Close(); } } @@ -154,6 +165,7 @@ public static IDataReader ExecuteReader(string connectionString, CommandType typ { Logger.Error("[3] Error executing SQL: " + sql + Environment.NewLine + ex.Message); } + throw; } } @@ -215,8 +227,6 @@ public static void ExecuteSQL(string connectionString, string sql, int timeoutSe throw; } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs index 9e83f995cb2..a1135e2eaf5 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs @@ -1,41 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Reflection; -using System.Threading; -using DotNetNuke.ComponentModel.DataAnnotations; -using PetaPoco; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Data.PetaPoco { + using System; + using System.Reflection; + using System.Threading; + + using DotNetNuke.ComponentModel.DataAnnotations; + using global::PetaPoco; + public class PetaPocoMapper : IMapper { private static IMapper _defaultMapper; - private readonly string _tablePrefix; private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); + private readonly string _tablePrefix; public PetaPocoMapper(string tablePrefix) { - _tablePrefix = tablePrefix; + this._tablePrefix = tablePrefix; _defaultMapper = new StandardMapper(); + } + + public static void SetMapper(IMapper mapper) + { + _lock.EnterWriteLock(); + try + { + if (Mappers.GetMapper(typeof(T), _defaultMapper) is StandardMapper) + { + Mappers.Register(typeof(T), mapper); + } + } + finally + { + _lock.ExitWriteLock(); + } } - - #region Implementation of IMapper - + public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) { bool includeColumn = true; - //Check if the class has the ExplictColumnsAttribute - bool declareColumns = pocoProperty.DeclaringType != null + // Check if the class has the ExplictColumnsAttribute + bool declareColumns = pocoProperty.DeclaringType != null && pocoProperty.DeclaringType.GetCustomAttributes(typeof(DeclareColumnsAttribute), true).Length > 0; - + if (declareColumns) { if (pocoProperty.GetCustomAttributes(typeof(IncludeColumnAttribute), true).Length == 0) @@ -48,8 +58,8 @@ public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) if (pocoProperty.GetCustomAttributes(typeof(IgnoreColumnAttribute), true).Length > 0) { includeColumn = false; - } - } + } + } ColumnInfo ci = null; if (includeColumn) @@ -57,7 +67,7 @@ public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) ci = ColumnInfo.FromProperty(pocoProperty); ci.ColumnName = DataUtil.GetColumnName(pocoProperty, ci.ColumnName); - ci.ResultColumn = (pocoProperty.GetCustomAttributes(typeof(ReadOnlyColumnAttribute), true).Length > 0); + ci.ResultColumn = pocoProperty.GetCustomAttributes(typeof(ReadOnlyColumnAttribute), true).Length > 0; } return ci; @@ -67,12 +77,12 @@ public TableInfo GetTableInfo(Type pocoType) { TableInfo ti = TableInfo.FromPoco(pocoType); - //Table Name + // Table Name ti.TableName = DataUtil.GetTableName(pocoType, ti.TableName + "s"); - ti.TableName = _tablePrefix + ti.TableName; + ti.TableName = this._tablePrefix + ti.TableName; - //Primary Key + // Primary Key ti.PrimaryKey = DataUtil.GetPrimaryKeyColumn(pocoType, ti.PrimaryKey); ti.AutoIncrement = DataUtil.GetAutoIncrement(pocoType, true); @@ -88,24 +98,6 @@ public Func GetFromDbConverter(PropertyInfo pi, Type SourceType) public Func GetToDbConverter(PropertyInfo SourceProperty) { return null; - } - - #endregion - - public static void SetMapper(IMapper mapper) - { - _lock.EnterWriteLock(); - try - { - if (Mappers.GetMapper(typeof (T), _defaultMapper) is StandardMapper) - { - Mappers.Register(typeof(T), mapper); - } - } - finally - { - _lock.ExitWriteLock(); - } - } + } } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs index 756a3cf7e9e..072057e91ef 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs @@ -1,114 +1,102 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Collections; -using DotNetNuke.Common; - -using PetaPoco; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Data.PetaPoco { - public class PetaPocoRepository : RepositoryBase where T : class + using System; + using System.Collections.Generic; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using global::PetaPoco; + + public class PetaPocoRepository : RepositoryBase + where T : class { private readonly Database _database; - private readonly IMapper _mapper; - - #region Constructors - + private readonly IMapper _mapper; + public PetaPocoRepository(Database database, IMapper mapper) { Requires.NotNull("database", database); - _database = database; - _mapper = mapper; + this._database = database; + this._mapper = mapper; PetaPocoMapper.SetMapper(mapper); - } - - #endregion - - #region IRepository Implementation - + } + public override void Delete(string sqlCondition, params object[] args) { - _database.Delete(DataUtil.ReplaceTokens(sqlCondition), args); + this._database.Delete(DataUtil.ReplaceTokens(sqlCondition), args); } public override IEnumerable Find(string sqlCondition, params object[] args) { - return _database.Fetch(DataUtil.ReplaceTokens(sqlCondition), args); + return this._database.Fetch(DataUtil.ReplaceTokens(sqlCondition), args); } public override IPagedList Find(int pageIndex, int pageSize, string sqlCondition, params object[] args) { - //Make sure that the sql Condition contains an ORDER BY Clause - if(!sqlCondition.ToUpperInvariant().Contains("ORDER BY")) + // Make sure that the sql Condition contains an ORDER BY Clause + if (!sqlCondition.ToUpperInvariant().Contains("ORDER BY")) { - sqlCondition = String.Format("{0} ORDER BY {1}", sqlCondition, _mapper.GetTableInfo(typeof(T)).PrimaryKey); + sqlCondition = string.Format("{0} ORDER BY {1}", sqlCondition, this._mapper.GetTableInfo(typeof(T)).PrimaryKey); } - Page petaPocoPage = _database.Page(pageIndex + 1, pageSize, DataUtil.ReplaceTokens(sqlCondition), args); + + Page petaPocoPage = this._database.Page(pageIndex + 1, pageSize, DataUtil.ReplaceTokens(sqlCondition), args); return new PagedList(petaPocoPage.Items, (int)petaPocoPage.TotalItems, pageIndex, pageSize); } public override void Update(string sqlCondition, params object[] args) { - _database.Update(DataUtil.ReplaceTokens(sqlCondition), args); - } - - #endregion - + this._database.Update(DataUtil.ReplaceTokens(sqlCondition), args); + } + protected override void DeleteInternal(T item) { - _database.Delete(item); + this._database.Delete(item); } protected override IEnumerable GetInternal() { - return _database.Fetch(String.Empty); + return this._database.Fetch(string.Empty); } protected override IPagedList GetPageInternal(int pageIndex, int pageSize) { - return Find(pageIndex, pageSize, String.Empty); + return this.Find(pageIndex, pageSize, string.Empty); } protected override IEnumerable GetByScopeInternal(object propertyValue) { - return _database.Fetch(GetScopeSql(), propertyValue); + return this._database.Fetch(this.GetScopeSql(), propertyValue); } protected override IPagedList GetPageByScopeInternal(object propertyValue, int pageIndex, int pageSize) { - return Find(pageIndex, pageSize, GetScopeSql(), propertyValue); + return this.Find(pageIndex, pageSize, this.GetScopeSql(), propertyValue); } protected override T GetByIdInternal(object id) { - return _database.SingleOrDefault(id); + return this._database.SingleOrDefault(id); } protected override void InsertInternal(T item) { - _database.Insert(item); + this._database.Insert(item); } protected override void UpdateInternal(T item) { - _database.Update(item); + this._database.Update(item); } private string GetScopeSql() { - return String.Format("WHERE {0} = @0", DataUtil.GetColumnName(typeof (T), Scope)); + return string.Format("WHERE {0} = @0", DataUtil.GetColumnName(typeof(T), this.Scope)); } } } diff --git a/DNN Platform/Library/Data/RepositoryBase.cs b/DNN Platform/Library/Data/RepositoryBase.cs index 4d2ac4f9fcb..2b335f04a08 100644 --- a/DNN Platform/Library/Data/RepositoryBase.cs +++ b/DNN Platform/Library/Data/RepositoryBase.cs @@ -1,35 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Caching; -using DotNetNuke.Collections; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel.DataAnnotations; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Data { - public abstract class RepositoryBase : IRepository where T : class - { - #region Constructors - + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.Caching; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel.DataAnnotations; + + public abstract class RepositoryBase : IRepository + where T : class + { protected RepositoryBase() { - InitializeInternal(); - } - - #endregion + this.InitializeInternal(); + } + + protected CacheItemArgs CacheArgs { get; private set; } - #region IRepository Implementation + protected string Scope { get; private set; } + protected bool IsCacheable { get; private set; } + public void Delete(T item) { - DeleteInternal(item); - ClearCache(item); + this.DeleteInternal(item); + this.ClearCache(item); } public abstract void Delete(string sqlCondition, params object[] args); @@ -40,76 +42,72 @@ public void Delete(T item) public IEnumerable Get() { - return IsCacheable && !IsScoped - ? DataCache.GetCachedData>(CacheArgs, c => GetInternal()) - : GetInternal(); + return this.IsCacheable && !this.IsScoped + ? DataCache.GetCachedData>(this.CacheArgs, c => this.GetInternal()) + : this.GetInternal(); } public IEnumerable Get(TScopeType scopeValue) { - CheckIfScoped(); + this.CheckIfScoped(); - if(IsCacheable) + if (this.IsCacheable) { - CacheArgs.CacheKey = String.Format(CacheArgs.CacheKey, scopeValue); + this.CacheArgs.CacheKey = string.Format(this.CacheArgs.CacheKey, scopeValue); } - return IsCacheable - ? DataCache.GetCachedData>(CacheArgs, c => GetByScopeInternal(scopeValue)) - : GetByScopeInternal(scopeValue); + return this.IsCacheable + ? DataCache.GetCachedData>(this.CacheArgs, c => this.GetByScopeInternal(scopeValue)) + : this.GetByScopeInternal(scopeValue); } public T GetById(TProperty id) { - return IsCacheable && !IsScoped - ? Get().SingleOrDefault(t => CompareTo(GetPrimaryKey(t), id) == 0) - : GetByIdInternal(id); + return this.IsCacheable && !this.IsScoped + ? this.Get().SingleOrDefault(t => this.CompareTo(this.GetPrimaryKey(t), id) == 0) + : this.GetByIdInternal(id); } public T GetById(TProperty id, TScopeType scopeValue) { - CheckIfScoped(); + this.CheckIfScoped(); - return Get(scopeValue).SingleOrDefault(t => CompareTo(GetPrimaryKey(t), id) == 0); + return this.Get(scopeValue).SingleOrDefault(t => this.CompareTo(this.GetPrimaryKey(t), id) == 0); } public IPagedList GetPage(int pageIndex, int pageSize) { - return IsCacheable && !IsScoped - ? Get().InPagesOf(pageSize).GetPage(pageIndex) - : GetPageInternal(pageIndex, pageSize); + return this.IsCacheable && !this.IsScoped + ? this.Get().InPagesOf(pageSize).GetPage(pageIndex) + : this.GetPageInternal(pageIndex, pageSize); } public IPagedList GetPage(TScopeType scopeValue, int pageIndex, int pageSize) { - CheckIfScoped(); + this.CheckIfScoped(); - return IsCacheable - ? Get(scopeValue).InPagesOf(pageSize).GetPage(pageIndex) - : GetPageByScopeInternal(scopeValue, pageIndex, pageSize); + return this.IsCacheable + ? this.Get(scopeValue).InPagesOf(pageSize).GetPage(pageIndex) + : this.GetPageByScopeInternal(scopeValue, pageIndex, pageSize); } public void Insert(T item) { - InsertInternal(item); - ClearCache(item); + this.InsertInternal(item); + this.ClearCache(item); } public void Update(T item) { - UpdateInternal(item); - ClearCache(item); + this.UpdateInternal(item); + this.ClearCache(item); } - public abstract void Update(string sqlCondition, params object[] args); - - #endregion - - #region Private Methods - + public abstract void Update(string sqlCondition, params object[] args); + private void CheckIfScoped() { - if (!IsScoped) + if (!this.IsScoped) { throw new NotSupportedException("This method requires the model to be cacheable and have a cache scope defined"); } @@ -117,74 +115,83 @@ private void CheckIfScoped() private void ClearCache(T item) { - if (IsCacheable) + if (this.IsCacheable) { - DataCache.RemoveCache(IsScoped - ? String.Format(CacheArgs.CacheKey, GetScopeValue(item)) - : CacheArgs.CacheKey); + DataCache.RemoveCache(this.IsScoped + ? string.Format(this.CacheArgs.CacheKey, this.GetScopeValue(item)) + : this.CacheArgs.CacheKey); } } private void InitializeInternal() { - var type = typeof (T); - Scope = String.Empty; - IsCacheable = false; - IsScoped = false; - CacheArgs = null; + var type = typeof(T); + this.Scope = string.Empty; + this.IsCacheable = false; + this.IsScoped = false; + this.CacheArgs = null; var scopeAttribute = DataUtil.GetAttribute(type); if (scopeAttribute != null) { - Scope = scopeAttribute.Scope; + this.Scope = scopeAttribute.Scope; } - IsScoped = (!String.IsNullOrEmpty(Scope)); + this.IsScoped = !string.IsNullOrEmpty(this.Scope); var cacheableAttribute = DataUtil.GetAttribute(type); if (cacheableAttribute != null) { - IsCacheable = true; - var cacheKey = !String.IsNullOrEmpty(cacheableAttribute.CacheKey) + this.IsCacheable = true; + var cacheKey = !string.IsNullOrEmpty(cacheableAttribute.CacheKey) ? cacheableAttribute.CacheKey - : String.Format("OR_{0}", type.Name); + : string.Format("OR_{0}", type.Name); var cachePriority = cacheableAttribute.CachePriority; var cacheTimeOut = cacheableAttribute.CacheTimeOut; - if (IsScoped) + if (this.IsScoped) { - cacheKey += "_" + Scope + "_{0}"; + cacheKey += "_" + this.Scope + "_{0}"; } - CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); + this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); } - } - - #endregion - - #region Protected Properties - - protected CacheItemArgs CacheArgs { get; private set; } - - protected string Scope { get; private set; } - - protected bool IsCacheable { get; private set; } - - protected bool IsScoped { get; private set; } - - #endregion + } + protected bool IsScoped { get; private set; } + + public void Initialize(string cacheKey, int cacheTimeOut = 20, CacheItemPriority cachePriority = CacheItemPriority.Default, string scope = "") + { + this.Scope = scope; + this.IsScoped = !string.IsNullOrEmpty(this.Scope); + this.IsCacheable = !string.IsNullOrEmpty(cacheKey); + if (this.IsCacheable) + { + if (this.IsScoped) + { + cacheKey += "_" + this.Scope + "_{0}"; + } + + this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); + } + else + { + this.CacheArgs = null; + } + } + protected int CompareTo(TProperty first, TProperty second) { Requires.IsTypeOf("first", first); Requires.IsTypeOf("second", second); var firstComparable = first as IComparable; - var secondComparable = second as IComparable; - -// ReSharper disable PossibleNullReferenceException - return firstComparable.CompareTo(secondComparable); -// ReSharper restore PossibleNullReferenceException + var secondComparable = second as IComparable; + + // ReSharper disable PossibleNullReferenceException + return firstComparable.CompareTo(secondComparable); + + // ReSharper restore PossibleNullReferenceException } protected TProperty GetPropertyValue(T item, string propertyName) @@ -199,11 +206,9 @@ protected TProperty GetPrimaryKey(T item) protected TProperty GetScopeValue(T item) { - return DataUtil.GetPropertyValue(item, Scope); - } - - #region Abstract Methods - + return DataUtil.GetPropertyValue(item, this.Scope); + } + protected abstract void DeleteInternal(T item); protected abstract IEnumerable GetInternal(); @@ -218,27 +223,6 @@ protected TProperty GetScopeValue(T item) protected abstract void InsertInternal(T item); - protected abstract void UpdateInternal(T item); - - #endregion - - public void Initialize(string cacheKey, int cacheTimeOut = 20, CacheItemPriority cachePriority = CacheItemPriority.Default, string scope = "") - { - Scope = scope; - IsScoped = (!String.IsNullOrEmpty(Scope)); - IsCacheable = (!String.IsNullOrEmpty(cacheKey)); - if (IsCacheable) - { - if (IsScoped) - { - cacheKey += "_" + Scope + "_{0}"; - } - CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); - } - else - { - CacheArgs = null; - } - } + protected abstract void UpdateInternal(T item); } } diff --git a/DNN Platform/Library/Data/SqlDataProvider.cs b/DNN Platform/Library/Data/SqlDataProvider.cs index 850b23f545e..de691cd3be6 100644 --- a/DNN Platform/Library/Data/SqlDataProvider.cs +++ b/DNN Platform/Library/Data/SqlDataProvider.cs @@ -1,45 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Linq; -using System.Text.RegularExpressions; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Data { + using System; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + using System.Linq; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Log.EventLog; + public sealed class SqlDataProvider : DataProvider { + private const string ScriptDelimiter = "(?<=(?:[^\\w]+|^))GO(?=(?: |\\t)*?(?:\\r?\\n|$))"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SqlDataProvider)); - private static DatabaseConnectionProvider _dbConnectionProvider = DatabaseConnectionProvider.Instance() ?? new SqlDatabaseConnectionProvider(); - - #region Private Members - - private const string ScriptDelimiter = "(?<=(?:[^\\w]+|^))GO(?=(?: |\\t)*?(?:\\r?\\n|$))"; - - #endregion - - #region Public Properties - + private static DatabaseConnectionProvider _dbConnectionProvider = DatabaseConnectionProvider.Instance() ?? new SqlDatabaseConnectionProvider(); + public override bool IsConnectionValid { get { - return CanConnect(ConnectionString, DatabaseOwner, ObjectQualifier); + return CanConnect(this.ConnectionString, this.DatabaseOwner, this.ObjectQualifier); } } @@ -49,12 +37,18 @@ public override Dictionary Settings { return ComponentFactory.GetComponentSettings() as Dictionary; } + } + + public override void ExecuteNonQuery(string procedureName, params object[] commandParameters) + { + _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); } - #endregion - - #region Private Methods - + public override void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters) + { + _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); + } + private static bool CanConnect(string connectionString, string owner, string qualifier) { bool connectionValid = true; @@ -76,16 +70,15 @@ private static bool CanConnect(string connectionString, string owner, string qua private string ExecuteScriptInternal(string connectionString, string script, int timeoutSec = 0) { - string exceptions = ""; + string exceptions = string.Empty; var sqlDelimiterRegex = RegexUtils.GetCachedRegex(ScriptDelimiter, RegexOptions.IgnoreCase | RegexOptions.Multiline); string[] sqlStatements = sqlDelimiterRegex.Split(script); foreach (string statement in sqlStatements) { var sql = statement.Trim(); - if (!String.IsNullOrEmpty(sql)) + if (!string.IsNullOrEmpty(sql)) { - // script dynamic substitution sql = DataUtil.ReplaceTokens(sql); @@ -109,7 +102,7 @@ private string ExecuteScriptInternal(string connectionString, string script, int private IDataReader ExecuteSQLInternal(string connectionString, string sql, int timeoutSec = 0) { string errorMessage; - return ExecuteSQLInternal(connectionString, sql, timeoutSec, out errorMessage); + return this.ExecuteSQLInternal(connectionString, sql, timeoutSec, out errorMessage); } private IDataReader ExecuteSQLInternal(string connectionString, string sql, int timeoutSec, out string errorMessage) @@ -117,16 +110,18 @@ private IDataReader ExecuteSQLInternal(string connectionString, string sql, int try { sql = DataUtil.ReplaceTokens(sql); - errorMessage = ""; - - if (string.IsNullOrEmpty(connectionString)) - throw new ArgumentNullException(nameof(connectionString)); + errorMessage = string.Empty; + if (string.IsNullOrEmpty(connectionString)) + { + throw new ArgumentNullException(nameof(connectionString)); + } + return _dbConnectionProvider.ExecuteSql(connectionString, CommandType.Text, timeoutSec, sql); } catch (SqlException sqlException) { - //error in SQL query + // error in SQL query Logger.Error(sqlException); errorMessage = sqlException.Message; } @@ -135,6 +130,7 @@ private IDataReader ExecuteSQLInternal(string connectionString, string sql, int Logger.Error(ex); errorMessage = ex.ToString(); } + errorMessage += Environment.NewLine + Environment.NewLine + sql + Environment.NewLine + Environment.NewLine; return null; } @@ -143,9 +139,9 @@ private string GetConnectionStringUserID() { string DBUser = "public"; - //If connection string does not use integrated security, then get user id. - //Normalize to uppercase before all of the comparisons - var connectionStringUppercase = ConnectionString.ToUpper(); + // If connection string does not use integrated security, then get user id. + // Normalize to uppercase before all of the comparisons + var connectionStringUppercase = this.ConnectionString.ToUpper(); if (connectionStringUppercase.Contains("USER ID") || connectionStringUppercase.Contains("UID") || connectionStringUppercase.Contains("USER")) { string[] ConnSettings = connectionStringUppercase.Split(';'); @@ -162,12 +158,13 @@ private string GetConnectionStringUserID() } } } + return DBUser; } private string GrantStoredProceduresPermission(string Permission, string LoginOrRole) { - //grant rights to a login or role for all stored procedures + // grant rights to a login or role for all stored procedures var sql = "if exists (select * from dbo.sysusers where name='" + LoginOrRole + "')" + " begin" + " declare @exec nvarchar(2000) " @@ -177,7 +174,7 @@ private string GrantStoredProceduresPermission(string Permission, string LoginOr + " where ( OBJECTPROPERTY(o.id, N'IsProcedure') = 1 or OBJECTPROPERTY(o.id, N'IsExtendedProc') = 1 or OBJECTPROPERTY(o.id, N'IsReplProc') = 1 ) " + " and OBJECTPROPERTY(o.id, N'IsMSShipped') = 0 " + " and o.name not like N'#%%' " - + " and (left(o.name,len('" + ObjectQualifier + "')) = '" + ObjectQualifier + "' or left(o.name,7) = 'aspnet_') " + + " and (left(o.name,len('" + this.ObjectQualifier + "')) = '" + this.ObjectQualifier + "' or left(o.name,7) = 'aspnet_') " + " open sp_cursor " + " fetch sp_cursor into @name " + " while @@fetch_status >= 0 " @@ -189,12 +186,12 @@ private string GrantStoredProceduresPermission(string Permission, string LoginOr + " deallocate sp_cursor" + " end "; - return ExecuteUpgradedConnectionQuery(sql); + return this.ExecuteUpgradedConnectionQuery(sql); } private string GrantUserDefinedFunctionsPermission(string ScalarPermission, string TablePermission, string LoginOrRole) { - //grant EXECUTE rights to a login or role for all functions + // grant EXECUTE rights to a login or role for all functions var sql = "if exists (select * from dbo.sysusers where name='" + LoginOrRole + "')" + " begin" + " declare @exec nvarchar(2000) " @@ -206,7 +203,7 @@ private string GrantUserDefinedFunctionsPermission(string ScalarPermission, stri + " where ( OBJECTPROPERTY(o.id, N'IsScalarFunction') = 1 OR OBJECTPROPERTY(o.id, N'IsTableFunction') = 1 ) " + " and OBJECTPROPERTY(o.id, N'IsMSShipped') = 0 " + " and o.name not like N'#%%' " - + " and (left(o.name,len('" + ObjectQualifier + "')) = '" + ObjectQualifier + "' or left(o.name,7) = 'aspnet_') " + + " and (left(o.name,len('" + this.ObjectQualifier + "')) = '" + this.ObjectQualifier + "' or left(o.name,7) = 'aspnet_') " + " open sp_cursor " + " fetch sp_cursor into @name, @isscalarfunction " + " while @@fetch_status >= 0 " @@ -227,7 +224,7 @@ private string GrantUserDefinedFunctionsPermission(string ScalarPermission, stri + " deallocate sp_cursor" + " end "; - return ExecuteUpgradedConnectionQuery(sql); + return this.ExecuteUpgradedConnectionQuery(sql); } private string ExecuteUpgradedConnectionQuery(string sql) @@ -236,7 +233,7 @@ private string ExecuteUpgradedConnectionQuery(string sql) try { - _dbConnectionProvider.ExecuteNonQuery(UpgradeConnectionString, CommandType.Text, 0, sql); + _dbConnectionProvider.ExecuteNonQuery(this.UpgradeConnectionString, CommandType.Text, 0, sql); } catch (SqlException objException) { @@ -244,82 +241,69 @@ private string ExecuteUpgradedConnectionQuery(string sql) exceptions += objException + Environment.NewLine + Environment.NewLine + sql + Environment.NewLine + Environment.NewLine; } + return exceptions; - } - - #endregion - - #region Abstract Methods - - public override void ExecuteNonQuery(string procedureName, params object[] commandParameters) - { - _dbConnectionProvider.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, 0, DatabaseOwner + ObjectQualifier + procedureName, commandParameters); - } - - public override void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters) - { - _dbConnectionProvider.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, timeoutSec, DatabaseOwner + ObjectQualifier + procedureName, commandParameters); - } + } public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable) { - _dbConnectionProvider.BulkInsert(ConnectionString, 0, DatabaseOwner + ObjectQualifier + procedureName, tableParameterName, dataTable); + _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable); } public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec) { - _dbConnectionProvider.BulkInsert(ConnectionString, timeoutSec, DatabaseOwner + ObjectQualifier + procedureName, tableParameterName, dataTable); + _dbConnectionProvider.BulkInsert(this.ConnectionString, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable); } public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters) { - _dbConnectionProvider.BulkInsert(ConnectionString, 0, DatabaseOwner + ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); + _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); } public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec, Dictionary commandParameters) { - _dbConnectionProvider.BulkInsert(ConnectionString, 0, DatabaseOwner + ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); + _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); } public override IDataReader ExecuteReader(string procedureName, params object[] commandParameters) { - return _dbConnectionProvider.ExecuteReader(ConnectionString, CommandType.StoredProcedure, 0, DatabaseOwner + ObjectQualifier + procedureName, commandParameters); + return _dbConnectionProvider.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); } public override IDataReader ExecuteReader(int timeoutSec, string procedureName, params object[] commandParameters) { - return _dbConnectionProvider.ExecuteReader(ConnectionString, CommandType.StoredProcedure, timeoutSec, DatabaseOwner + ObjectQualifier + procedureName, commandParameters); + return _dbConnectionProvider.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); } public override T ExecuteScalar(string procedureName, params object[] commandParameters) { - return _dbConnectionProvider.ExecuteScalar(ConnectionString, CommandType.StoredProcedure, 0, DatabaseOwner + ObjectQualifier + procedureName, commandParameters); + return _dbConnectionProvider.ExecuteScalar(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); } public override T ExecuteScalar(int timeoutSec, string procedureName, params object[] commandParameters) { - return _dbConnectionProvider.ExecuteScalar(ConnectionString, CommandType.StoredProcedure, timeoutSec, DatabaseOwner + ObjectQualifier + procedureName, commandParameters); + return _dbConnectionProvider.ExecuteScalar(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); } public override string ExecuteScript(string script) { - return ExecuteScript(script, 0); + return this.ExecuteScript(script, 0); } public override string ExecuteScript(string script, int timeoutSec) { - string exceptions = ExecuteScriptInternal(UpgradeConnectionString, script, timeoutSec); + string exceptions = this.ExecuteScriptInternal(this.UpgradeConnectionString, script, timeoutSec); - //if the upgrade connection string is specified or or db_owner setting is not set to dbo - if (UpgradeConnectionString != ConnectionString || !DatabaseOwner.Trim().Equals("dbo.", StringComparison.InvariantCultureIgnoreCase)) + // if the upgrade connection string is specified or or db_owner setting is not set to dbo + if (this.UpgradeConnectionString != this.ConnectionString || !this.DatabaseOwner.Trim().Equals("dbo.", StringComparison.InvariantCultureIgnoreCase)) { try { - //grant execute rights to the public role or userid for all stored procedures. This is - //necesary because the UpgradeConnectionString will create stored procedures - //which restrict execute permissions for the ConnectionString user account. This is also - //necessary when db_owner is not set to "dbo" - exceptions += GrantStoredProceduresPermission("EXECUTE", GetConnectionStringUserID()); + // grant execute rights to the public role or userid for all stored procedures. This is + // necesary because the UpgradeConnectionString will create stored procedures + // which restrict execute permissions for the ConnectionString user account. This is also + // necessary when db_owner is not set to "dbo" + exceptions += this.GrantStoredProceduresPermission("EXECUTE", this.GetConnectionStringUserID()); } catch (SqlException objException) { @@ -330,12 +314,12 @@ public override string ExecuteScript(string script, int timeoutSec) try { - //grant execute or select rights to the public role or userid for all user defined functions based - //on what type of function it is (scalar function or table function). This is - //necesary because the UpgradeConnectionString will create user defined functions - //which restrict execute permissions for the ConnectionString user account. This is also - //necessary when db_owner is not set to "dbo" - exceptions += GrantUserDefinedFunctionsPermission("EXECUTE", "SELECT", GetConnectionStringUserID()); + // grant execute or select rights to the public role or userid for all user defined functions based + // on what type of function it is (scalar function or table function). This is + // necesary because the UpgradeConnectionString will create user defined functions + // which restrict execute permissions for the ConnectionString user account. This is also + // necessary when db_owner is not set to "dbo" + exceptions += this.GrantUserDefinedFunctionsPermission("EXECUTE", "SELECT", this.GetConnectionStringUserID()); } catch (SqlException objException) { @@ -344,51 +328,50 @@ public override string ExecuteScript(string script, int timeoutSec) exceptions += objException + Environment.NewLine + Environment.NewLine + script + Environment.NewLine + Environment.NewLine; } } + return exceptions; } public override string ExecuteScript(string connectionString, string script) { - return ExecuteScriptInternal(connectionString, script); + return this.ExecuteScriptInternal(connectionString, script); } public override string ExecuteScript(string connectionString, string script, int timeoutSec) { - return ExecuteScriptInternal(connectionString, script, timeoutSec); + return this.ExecuteScriptInternal(connectionString, script, timeoutSec); } public override IDataReader ExecuteSQL(string sql) { - return ExecuteSQLInternal(ConnectionString, sql); + return this.ExecuteSQLInternal(this.ConnectionString, sql); } public override IDataReader ExecuteSQL(string sql, int timeoutSec) { - return ExecuteSQLInternal(ConnectionString, sql, timeoutSec); + return this.ExecuteSQLInternal(this.ConnectionString, sql, timeoutSec); } public override IDataReader ExecuteSQLTemp(string connectionString, string sql) { string errorMessage; - return ExecuteSQLTemp(connectionString, sql, out errorMessage); + return this.ExecuteSQLTemp(connectionString, sql, out errorMessage); } public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec) { string errorMessage; - return ExecuteSQLTemp(connectionString, sql, timeoutSec, out errorMessage); + return this.ExecuteSQLTemp(connectionString, sql, timeoutSec, out errorMessage); } public override IDataReader ExecuteSQLTemp(string connectionString, string sql, out string errorMessage) { - return ExecuteSQLInternal(connectionString, sql, 0, out errorMessage); + return this.ExecuteSQLInternal(connectionString, sql, 0, out errorMessage); } public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage) { - return ExecuteSQLInternal(connectionString, sql, timeoutSec, out errorMessage); - } - - #endregion + return this.ExecuteSQLInternal(connectionString, sql, timeoutSec, out errorMessage); + } } } diff --git a/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs b/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs index c02fc145a27..5d7bcffc38a 100644 --- a/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs +++ b/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region usings - -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using DotNetNuke.Data.PetaPoco; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Data { + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + + using DotNetNuke.Data.PetaPoco; + public class SqlDatabaseConnectionProvider : DatabaseConnectionProvider { public override int ExecuteNonQuery(string connectionString, CommandType commandType, int commandTimeout, string query) @@ -20,9 +16,11 @@ public override int ExecuteNonQuery(string connectionString, CommandType command using (var connection = new SqlConnection(connectionString)) using (var command = new SqlCommand(query, connection)) { - if (commandTimeout > 0) - command.CommandTimeout = commandTimeout; - + if (commandTimeout > 0) + { + command.CommandTimeout = commandTimeout; + } + connection.Open(); try { @@ -42,7 +40,7 @@ public override void ExecuteNonQuery(string connectionString, CommandType comman public override IDataReader ExecuteSql(string connectionString, CommandType commandType, int commandTimeout, string query) { - //return SqlHelper.ExecuteReader(ConnectionString, CommandType, Query); + // return SqlHelper.ExecuteReader(ConnectionString, CommandType, Query); return PetaPocoHelper.ExecuteReader(connectionString, commandType, commandTimeout, query); } diff --git a/DNN Platform/Library/DotNetNuke.Library.csproj b/DNN Platform/Library/DotNetNuke.Library.csproj index 11ae2e85768..6a73fd64eb6 100644 --- a/DNN Platform/Library/DotNetNuke.Library.csproj +++ b/DNN Platform/Library/DotNetNuke.Library.csproj @@ -815,6 +815,7 @@ + @@ -1744,6 +1745,9 @@ + + stylecop.json + Designer @@ -1872,6 +1876,10 @@ DotNetNuke.WebUtility + + + + $(MSBuildProjectDirectory)\..\.. diff --git a/DNN Platform/Library/Entities/BaseEntityInfo.cs b/DNN Platform/Library/Entities/BaseEntityInfo.cs index 48ae1806a26..5317e6ad3de 100644 --- a/DNN Platform/Library/Entities/BaseEntityInfo.cs +++ b/DNN Platform/Library/Entities/BaseEntityInfo.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities { + using System; + using System.ComponentModel; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities - /// Class : BaseEntityInfo + /// Class : BaseEntityInfo /// ----------------------------------------------------------------------------- /// /// BaseEntityInfo provides auditing fields for Core tables. @@ -30,110 +25,116 @@ public abstract class BaseEntityInfo { protected BaseEntityInfo() { - CreatedByUserID = Null.NullInteger; - LastModifiedByUserID = Null.NullInteger; + this.CreatedByUserID = Null.NullInteger; + this.LastModifiedByUserID = Null.NullInteger; } /// ----------------------------------------------------------------------------- /// - /// Gets the CreatedByUserID + /// Gets the CreatedByUserID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- - [Browsable(false), XmlIgnore] + [Browsable(false)] + [XmlIgnore] public int CreatedByUserID { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets the CreatedOnDate + /// Gets the CreatedOnDate. /// - /// A DateTime + /// A DateTime. /// ----------------------------------------------------------------------------- - [Browsable(false), XmlIgnore] + [Browsable(false)] + [XmlIgnore] public DateTime CreatedOnDate { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the LastModifiedByUserID + /// Gets the LastModifiedByUserID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- - [Browsable(false), XmlIgnore] + [Browsable(false)] + [XmlIgnore] public int LastModifiedByUserID { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets the LastModifiedOnDate + /// Gets the LastModifiedOnDate. /// - /// A DateTime + /// A DateTime. /// ----------------------------------------------------------------------------- - [Browsable(false), XmlIgnore] + [Browsable(false)] + [XmlIgnore] public DateTime LastModifiedOnDate { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the UserInfo object associated with this user + /// Gets the UserInfo object associated with this user. /// - /// The PortalID associated with the desired user - /// A UserInfo object + /// The PortalID associated with the desired user. + /// A UserInfo object. /// ----------------------------------------------------------------------------- public UserInfo CreatedByUser(int portalId) { - if (CreatedByUserID > Null.NullInteger) + if (this.CreatedByUserID > Null.NullInteger) { - UserInfo user = UserController.GetUserById(portalId, CreatedByUserID); + UserInfo user = UserController.GetUserById(portalId, this.CreatedByUserID); return user; } + return null; } /// ----------------------------------------------------------------------------- /// - /// Gets the UserInfo object associated with this user + /// Gets the UserInfo object associated with this user. /// - /// The PortalID associated with the desired user - /// A UserInfo object + /// The PortalID associated with the desired user. + /// A UserInfo object. /// ----------------------------------------------------------------------------- public UserInfo LastModifiedByUser(int portalId) { - if (LastModifiedByUserID > Null.NullInteger) + if (this.LastModifiedByUserID > Null.NullInteger) { - UserInfo user = UserController.GetUserById(portalId, LastModifiedByUserID); + UserInfo user = UserController.GetUserById(portalId, this.LastModifiedByUserID); return user; } + return null; } + /// + /// method used by cbo to fill readonly properties ignored by HydrateObject reflection. + /// + /// the data reader to use. + /// + internal void FillBaseProperties(IDataReader dr) + { + this.FillInternal(dr); + } + /// ----------------------------------------------------------------------------- /// - /// Fills a BaseEntityInfo from a Data Reader + /// Fills a BaseEntityInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- protected virtual void FillInternal(IDataReader dr) { - CreatedByUserID = Null.SetNullInteger(dr["CreatedByUserID"]); - CreatedOnDate = Null.SetNullDateTime(dr["CreatedOnDate"]); - LastModifiedByUserID = Null.SetNullInteger(dr["LastModifiedByUserID"]); - LastModifiedOnDate = Null.SetNullDateTime(dr["LastModifiedOnDate"]); + this.CreatedByUserID = Null.SetNullInteger(dr["CreatedByUserID"]); + this.CreatedOnDate = Null.SetNullDateTime(dr["CreatedOnDate"]); + this.LastModifiedByUserID = Null.SetNullInteger(dr["LastModifiedByUserID"]); + this.LastModifiedOnDate = Null.SetNullDateTime(dr["LastModifiedOnDate"]); } - protected void CloneBaseProperties(BaseEntityInfo clonedItem, BaseEntityInfo originalItem) - { - clonedItem.CreatedByUserID = originalItem.CreatedByUserID; - clonedItem.CreatedOnDate = originalItem.CreatedOnDate; - clonedItem.LastModifiedByUserID = originalItem.LastModifiedByUserID; - clonedItem.LastModifiedOnDate = originalItem.LastModifiedOnDate; - } - - /// - /// method used by cbo to fill readonly properties ignored by HydrateObject reflection - /// - /// the data reader to use - /// - internal void FillBaseProperties(IDataReader dr) + protected void CloneBaseProperties(BaseEntityInfo clonedItem, BaseEntityInfo originalItem) { - FillInternal(dr); + clonedItem.CreatedByUserID = originalItem.CreatedByUserID; + clonedItem.CreatedOnDate = originalItem.CreatedOnDate; + clonedItem.LastModifiedByUserID = originalItem.LastModifiedByUserID; + clonedItem.LastModifiedOnDate = originalItem.LastModifiedOnDate; } } } diff --git a/DNN Platform/Library/Entities/ConfigurationSetting.cs b/DNN Platform/Library/Entities/ConfigurationSetting.cs index f6170801a51..77fbd81d5db 100644 --- a/DNN Platform/Library/Entities/ConfigurationSetting.cs +++ b/DNN Platform/Library/Entities/ConfigurationSetting.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities { public class ConfigurationSetting diff --git a/DNN Platform/Library/Entities/Content/AttachmentController.cs b/DNN Platform/Library/Entities/Content/AttachmentController.cs index b00a3da695f..4fe9da98180 100644 --- a/DNN Platform/Library/Entities/Content/AttachmentController.cs +++ b/DNN Platform/Library/Entities/Content/AttachmentController.cs @@ -1,24 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + /// Implementation of . public class AttachmentController : IAttachmentController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (AttachmentController)); + internal const string FilesKey = "Files"; + internal const string ImageKey = "Images"; + internal const string VideoKey = "Videos"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AttachmentController)); + + private readonly IContentController _contentController; + public AttachmentController() : this(Util.GetContentController()) { @@ -26,99 +34,68 @@ public AttachmentController() public AttachmentController(IContentController contentController) { - _contentController = contentController; + this._contentController = contentController; } - private readonly IContentController _contentController; - - #region Implementation of IFileController + public void AddFileToContent(int contentItemId, IFileInfo fileInfo) + { + this.AddFilesToContent(contentItemId, new[] { fileInfo }); + } + public void AddFilesToContent(int contentItemId, IEnumerable fileInfo) + { + this.AddToContent(contentItemId, contentItem => contentItem.Files.AddRange(fileInfo)); + } + private void AddToContent(int contentItemId, Action action) { - var contentItem = _contentController.GetContentItem(contentItemId); + var contentItem = this._contentController.GetContentItem(contentItemId); action(contentItem); - - _contentController.UpdateContentItem(contentItem); - } - public void AddFileToContent(int contentItemId, IFileInfo fileInfo) - { - AddFilesToContent(contentItemId, new[] { fileInfo }); + this._contentController.UpdateContentItem(contentItem); } - public void AddFilesToContent(int contentItemId, IEnumerable fileInfo) - { - AddToContent(contentItemId, contentItem => contentItem.Files.AddRange(fileInfo)); - } - public void AddVideoToContent(int contentItemId, IFileInfo fileInfo) { - AddVideosToContent(contentItemId, new[] { fileInfo }); + this.AddVideosToContent(contentItemId, new[] { fileInfo }); } public void AddVideosToContent(int contentItemId, IEnumerable fileInfo) { - AddToContent(contentItemId, contentItem => contentItem.Videos.AddRange(fileInfo)); + this.AddToContent(contentItemId, contentItem => contentItem.Videos.AddRange(fileInfo)); } public void AddImageToContent(int contentItemId, IFileInfo fileInfo) { - AddImagesToContent(contentItemId, new[] { fileInfo }); + this.AddImagesToContent(contentItemId, new[] { fileInfo }); } public void AddImagesToContent(int contentItemId, IEnumerable fileInfo) { - AddToContent(contentItemId, contentItem => contentItem.Images.AddRange(fileInfo)); + this.AddToContent(contentItemId, contentItem => contentItem.Images.AddRange(fileInfo)); } public IList GetVideosByContent(int contentItemId) { - var files = GetFilesByContent(contentItemId, VideoKey); + var files = this.GetFilesByContent(contentItemId, VideoKey); return files.Select(fileId => FileManager.Instance.GetFile(fileId)).ToList(); } public IList GetImagesByContent(int contentItemId) { - var files = GetFilesByContent(contentItemId, ImageKey); + var files = this.GetFilesByContent(contentItemId, ImageKey); return files.Select(fileId => FileManager.Instance.GetFile(fileId)).ToList(); } public IList GetFilesByContent(int contentItemId) { - var files = GetFilesByContent(contentItemId, FilesKey); + var files = this.GetFilesByContent(contentItemId, FilesKey); return files.Select(fileId => FileManager.Instance.GetFile(fileId)).ToList(); - } - - #endregion - - #region Internal utility methods - - private static void SerializeToMetadata(IList files, NameValueCollection nvc, string key) - { - var remove = !files.Any(); - if (remove == false) - { - var serialized = SerializeFileInfo(files); - - if (string.IsNullOrEmpty(serialized)) - { - remove = true; - } - else - { - nvc[key] = serialized; - } - } - - if (remove) - { - nvc.Remove(key); - } - } + } internal static void SerializeAttachmentMetadata(ContentItem contentItem) { @@ -127,39 +104,13 @@ internal static void SerializeAttachmentMetadata(ContentItem contentItem) SerializeToMetadata(contentItem.Images, contentItem.Metadata, ImageKey); } - private IEnumerable GetFilesByContent(int contentItemId, string type) - { - var contentItem = _contentController.GetContentItem(contentItemId); - if (contentItem == null) - { - throw new ApplicationException(string.Format("Cannot find ContentItem ID {0}", contentItemId)); - } - - var serialized = contentItem.Metadata[type]; - - if (string.IsNullOrEmpty(serialized)) - { - return new int[0]; - } - - try - { - return serialized.FromJson().ToArray(); - } - catch (FormatException ex) - { - throw new ApplicationException( - string.Format("ContentItem metadata has become corrupt (ID {0}): invalid file ID", contentItemId), ex); - } - } - internal static IEnumerable DeserializeFileInfo(string content) { if (string.IsNullOrEmpty(content)) { yield break; } - + foreach (var file in content.FromJson().ToArray()) { IFileInfo fileInfo = null; @@ -174,7 +125,6 @@ internal static IEnumerable DeserializeFileInfo(string content) // On second thought, I don't know how much sense it makes to be throwing an exception here. If the file // has been deleted or is otherwise unavailable, there's really no reason we can't continue on handling the // ContentItem without its attachment. Better than the yellow screen of death? --cbond - Logger.WarnFormat("Unable to load file properties for File ID {0}", file); } @@ -194,17 +144,56 @@ internal static string SerializeFileInfo(IEnumerable files) } return fileList.ToJson(); + } + + private static void SerializeToMetadata(IList files, NameValueCollection nvc, string key) + { + var remove = !files.Any(); + if (remove == false) + { + var serialized = SerializeFileInfo(files); + + if (string.IsNullOrEmpty(serialized)) + { + remove = true; + } + else + { + nvc[key] = serialized; + } + } + + if (remove) + { + nvc.Remove(key); + } } - #endregion + private IEnumerable GetFilesByContent(int contentItemId, string type) + { + var contentItem = this._contentController.GetContentItem(contentItemId); + if (contentItem == null) + { + throw new ApplicationException(string.Format("Cannot find ContentItem ID {0}", contentItemId)); + } - #region Private + var serialized = contentItem.Metadata[type]; - internal const string FilesKey = "Files"; - internal const string ImageKey = "Images"; - internal const string VideoKey = "Videos"; - internal const string TitleKey = "Title"; + if (string.IsNullOrEmpty(serialized)) + { + return new int[0]; + } - #endregion + try + { + return serialized.FromJson().ToArray(); + } + catch (FormatException ex) + { + throw new ApplicationException( + string.Format("ContentItem metadata has become corrupt (ID {0}): invalid file ID", contentItemId), ex); + } + } + internal const string TitleKey = "Title"; } } diff --git a/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs b/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs index 93aaf2ea3ab..60dfe004b90 100644 --- a/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs +++ b/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; - + using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Content.Data; using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Services.FileSystem; - -#endregion - +using DotNetNuke.Services.FileSystem; + namespace DotNetNuke.Entities.Content { [Obsolete("Moving ContentExtensions to the DotNetNuke.Entities.Content namespace was an error. Please use DotNetNuke.Entities.Content.Common.ContentExtensions. Scheduled removal in v10.0.0.")] public static class ContentExtensions { - //only forwarding public methods that existed as of 6.1.0 - //calls to internal methods will be fixed in the source + // only forwarding public methods that existed as of 6.1.0 + // calls to internal methods will be fixed in the source public static string ToDelimittedString(this List terms, string delimiter) { return Common.ContentExtensions.ToDelimittedString(terms, delimiter); @@ -38,100 +33,98 @@ public static string ToDelimittedString(this List terms, string format, st namespace DotNetNuke.Entities.Content.Common { - /// - /// Extension methods for Term, Vocabulary, ContentItem. - /// - /// + /// + /// Extension methods for Term, Vocabulary, ContentItem. + /// + /// public static class ContentExtensions - { - #region "Term Extensions" - - /// - /// Gets the child terms. - /// - /// The term. - /// The term id. - /// The vocabulary id. - /// term collection which's parent is the specific term. - internal static List GetChildTerms(this Term Term, int termId, int vocabularyId) - { - ITermController ctl = Util.GetTermController(); - - IQueryable terms = from term in ctl.GetTermsByVocabulary(vocabularyId) where term.ParentTermId == termId select term; - - return terms.ToList(); - } - - /// - /// Gets the vocabulary. - /// - /// The term. - /// The vocabulary id. - /// Vocabulary - internal static Vocabulary GetVocabulary(this Term term, int vocabularyId) - { - IVocabularyController ctl = Util.GetVocabularyController(); - - return (from v in ctl.GetVocabularies() where v.VocabularyId == vocabularyId select v).SingleOrDefault(); - } - - /// - /// Toes the delimitted string. - /// - /// The terms. - /// The delimitter. - /// terms' name as a string and split with the given delimitter order by name A-Z. + { + /// + /// Toes the delimitted string. + /// + /// The terms. + /// The delimitter. + /// terms' name as a string and split with the given delimitter order by name A-Z. public static string ToDelimittedString(this List terms, string delimitter) { var sb = new StringBuilder(); if (terms != null) { - foreach (Term _Term in (from term in terms orderby term.Name ascending select term)) + foreach (Term _Term in from term in terms orderby term.Name ascending select term) { if (sb.Length > 0) { sb.Append(delimitter); } + sb.Append(_Term.Name); } } + return sb.ToString(); } - /// - /// Toes the delimitted string. - /// - /// The terms. - /// The format. - /// The delimitter. - /// formatted terms' name as a string and split with the given delimitter order by name A-Z. + /// + /// Toes the delimitted string. + /// + /// The terms. + /// The format. + /// The delimitter. + /// formatted terms' name as a string and split with the given delimitter order by name A-Z. public static string ToDelimittedString(this List terms, string format, string delimitter) { var sb = new StringBuilder(); if (terms != null) { - foreach (Term _Term in (from term in terms orderby term.Name ascending select term)) + foreach (Term _Term in from term in terms orderby term.Name ascending select term) { if (sb.Length > 0) { sb.Append(delimitter); } + sb.Append(string.Format(format, _Term.Name)); } } + return sb.ToString(); - } + } + + /// + /// Gets the child terms. + /// + /// The term. + /// The term id. + /// The vocabulary id. + /// term collection which's parent is the specific term. + internal static List GetChildTerms(this Term Term, int termId, int vocabularyId) + { + ITermController ctl = Util.GetTermController(); - #endregion + IQueryable terms = from term in ctl.GetTermsByVocabulary(vocabularyId) where term.ParentTermId == termId select term; - #region "Vocabulary Extensions" + return terms.ToList(); + } + + /// + /// Gets the vocabulary. + /// + /// The term. + /// The vocabulary id. + /// Vocabulary. + internal static Vocabulary GetVocabulary(this Term term, int vocabularyId) + { + IVocabularyController ctl = Util.GetVocabularyController(); - /// - /// Gets the type of the scope. - /// - /// The voc. - /// The scope type id. - /// scope type. + return (from v in ctl.GetVocabularies() where v.VocabularyId == vocabularyId select v).SingleOrDefault(); + } + + /// + /// Gets the type of the scope. + /// + /// The voc. + /// The scope type id. + /// scope type. internal static ScopeType GetScopeType(this Vocabulary voc, int scopeTypeId) { IScopeTypeController ctl = Util.GetScopeTypeController(); @@ -139,29 +132,25 @@ internal static ScopeType GetScopeType(this Vocabulary voc, int scopeTypeId) return ctl.GetScopeTypes().Where(s => s.ScopeTypeId == scopeTypeId).SingleOrDefault(); } - /// - /// Gets the terms by vocabularyId. - /// - /// The voc. - /// The vocabulary id. - /// term collection. + /// + /// Gets the terms by vocabularyId. + /// + /// The voc. + /// The vocabulary id. + /// term collection. internal static List GetTerms(this Vocabulary voc, int vocabularyId) { ITermController ctl = Util.GetTermController(); return ctl.GetTermsByVocabulary(vocabularyId).ToList(); - } - - #endregion - - #region "ContentItem Extensions" - - /// - /// Gets the meta data. - /// - /// The item. - /// The content item id. - /// meta data collection + } + + /// + /// Gets the meta data. + /// + /// The item. + /// The content item id. + /// meta data collection. internal static NameValueCollection GetMetaData(this ContentItem item, int contentItemId) { IContentController ctl = Util.GetContentController(); @@ -179,12 +168,12 @@ internal static NameValueCollection GetMetaData(this ContentItem item, int conte return _MetaData; } - /// - /// Gets the terms by content item id. - /// - /// The item. - /// The content item id. - /// term collection + /// + /// Gets the terms by content item id. + /// + /// The item. + /// The content item id. + /// term collection. internal static List GetTerms(this ContentItem item, int contentItemId) { ITermController ctl = Util.GetTermController(); @@ -200,8 +189,6 @@ internal static List GetTerms(this ContentItem item, int contentItemId) } return _Terms; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs b/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs index 657dd4bbb8f..482ca939565 100644 --- a/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs +++ b/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs @@ -1,15 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Common { + using System.Collections.Generic; + internal class ContentItemEqualityComparer : IEqualityComparer - { - #region Implementation of IEqualityComparer - + { public bool Equals(ContentItem x, ContentItem y) { return x.ContentItemId == y.ContentItemId; @@ -18,8 +16,6 @@ public bool Equals(ContentItem x, ContentItem y) public int GetHashCode(ContentItem obj) { return obj.ContentItemId.GetHashCode(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs b/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs index 1c8177377f7..53a7e905081 100644 --- a/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs +++ b/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs @@ -1,15 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Common { + using System.Collections.Generic; + internal class NameValueEqualityComparer : IEqualityComparer> - { - #region Implementation of IEqualityComparer> - + { public bool Equals(KeyValuePair x, KeyValuePair y) { return x.Key == y.Key && x.Value == y.Value; @@ -18,8 +16,6 @@ public bool Equals(KeyValuePair x, KeyValuePair public int GetHashCode(KeyValuePair obj) { return obj.Key.GetHashCode() ^ obj.Value.GetHashCode(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Common/Util.cs b/DNN Platform/Library/Entities/Content/Common/Util.cs index 63cb23f944a..dc470846edf 100644 --- a/DNN Platform/Library/Entities/Content/Common/Util.cs +++ b/DNN Platform/Library/Entities/Content/Common/Util.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Content.Taxonomy; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Common { - /// - /// Utility Methods for Content. - /// + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + + /// + /// Utility Methods for Content. + /// public static class Util { - /// - /// Gets the data service. - /// - /// data service instance from ComponentFactory. + /// + /// Gets the data service. + /// + /// data service instance from ComponentFactory. public static IDataService GetDataService() { var ds = ComponentFactory.GetComponent(); @@ -30,13 +25,14 @@ public static IDataService GetDataService() ds = new DataService(); ComponentFactory.RegisterComponentInstance(ds); } + return ds; } - /// - /// Gets the content controller. - /// - /// ContentController from ComponentFactory. + /// + /// Gets the content controller. + /// + /// ContentController from ComponentFactory. public static IContentController GetContentController() { var ctl = ComponentFactory.GetComponent(); @@ -46,13 +42,14 @@ public static IContentController GetContentController() ctl = new ContentController(); ComponentFactory.RegisterComponentInstance(ctl); } + return ctl; } - /// - /// Gets the scope type controller. - /// - /// ScopeTypeController from ComponentFactory. + /// + /// Gets the scope type controller. + /// + /// ScopeTypeController from ComponentFactory. public static IScopeTypeController GetScopeTypeController() { var ctl = ComponentFactory.GetComponent(); @@ -62,13 +59,14 @@ public static IScopeTypeController GetScopeTypeController() ctl = new ScopeTypeController(); ComponentFactory.RegisterComponentInstance(ctl); } + return ctl; } - /// - /// Gets the term controller. - /// - /// TermController from ComponentFactory. + /// + /// Gets the term controller. + /// + /// TermController from ComponentFactory. public static ITermController GetTermController() { var ctl = ComponentFactory.GetComponent(); @@ -78,13 +76,14 @@ public static ITermController GetTermController() ctl = new TermController(); ComponentFactory.RegisterComponentInstance(ctl); } + return ctl; } - /// - /// Gets the vocabulary controller. - /// - /// VocabularyController from ComponentFactory. + /// + /// Gets the vocabulary controller. + /// + /// VocabularyController from ComponentFactory. public static IVocabularyController GetVocabularyController() { var ctl = ComponentFactory.GetComponent(); @@ -94,6 +93,7 @@ public static IVocabularyController GetVocabularyController() ctl = new VocabularyController(); ComponentFactory.RegisterComponentInstance(ctl); } + return ctl; } } diff --git a/DNN Platform/Library/Entities/Content/ContentController.cs b/DNN Platform/Library/Entities/Content/ContentController.cs index 2992d510735..4e91d8cacc8 100644 --- a/DNN Platform/Library/Entities/Content/ContentController.cs +++ b/DNN Platform/Library/Entities/Content/ContentController.cs @@ -1,70 +1,67 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + public class ContentController : ServiceLocator, IContentController { private readonly IDataService _dataService; - protected override Func GetFactory() - { - return () => new ContentController(); - } - - public ContentController() : this(Util.GetDataService()) + public ContentController() + : this(Util.GetDataService()) { } public ContentController(IDataService dataService) { - _dataService = dataService; + this._dataService = dataService; } - public int AddContentItem(ContentItem contentItem) + public int AddContentItem(ContentItem contentItem) { - //Argument Contract + // Argument Contract Requires.NotNull("contentItem", contentItem); var currentUser = UserController.Instance.GetCurrentUserInfo(); var createdByUserId = currentUser.UserID; - if(contentItem.CreatedByUserID != currentUser.UserID) + if (contentItem.CreatedByUserID != currentUser.UserID) { createdByUserId = contentItem.CreatedByUserID; } - - contentItem.ContentItemId = _dataService.AddContentItem(contentItem, createdByUserId); + + contentItem.ContentItemId = this._dataService.AddContentItem(contentItem, createdByUserId); contentItem.CreatedByUserID = createdByUserId; contentItem.LastModifiedByUserID = currentUser.UserID; - SaveMetadataDelta(contentItem); + this.SaveMetadataDelta(contentItem); - UpdateContentItemsCache(contentItem); + UpdateContentItemsCache(contentItem); return contentItem.ContentItemId; } + protected override Func GetFactory() + { + return () => new ContentController(); + } + public void DeleteContentItem(ContentItem contentItem) { - //Argument Contract + // Argument Contract Requires.NotNull("contentItem", contentItem); Requires.PropertyNotNegative("contentItem", "ContentItemId", contentItem.ContentItemId); @@ -73,110 +70,112 @@ public void DeleteContentItem(ContentItem contentItem) UniqueKey = contentItem.ContentItemId.ToString("D"), ModuleId = contentItem.ModuleID, TabId = contentItem.TabID, - SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId + SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, }; DotNetNuke.Data.DataProvider.Instance().AddSearchDeletedItems(searrchDoc); - _dataService.DeleteContentItem(contentItem.ContentItemId); + this._dataService.DeleteContentItem(contentItem.ContentItemId); UpdateContentItemsCache(contentItem, false); } public void DeleteContentItem(int contentItemId) { - var contentItem = GetContentItem(contentItemId); - DeleteContentItem(contentItem); + var contentItem = this.GetContentItem(contentItemId); + this.DeleteContentItem(contentItem); } - + public ContentItem GetContentItem(int contentItemId) { - //Argument Contract + // Argument Contract Requires.NotNegative("contentItemId", contentItemId); return CBO.GetCachedObject( new CacheItemArgs(GetContentItemCacheKey(contentItemId), DataCache.ContentItemsCacheTimeOut, DataCache.ContentItemsCachePriority), - c => CBO.FillObject(_dataService.GetContentItem(contentItemId))); + c => CBO.FillObject(this._dataService.GetContentItem(contentItemId))); } public IQueryable GetContentItems(int contentTypeId, int tabId, int moduleId) { - return CBO.FillQueryable(_dataService.GetContentItems(contentTypeId, tabId, moduleId)); + return CBO.FillQueryable(this._dataService.GetContentItems(contentTypeId, tabId, moduleId)); } public IQueryable GetContentItemsByTerm(string term) { - //Argument Contract + // Argument Contract Requires.NotNullOrEmpty("term", term); - return CBO.FillQueryable(_dataService.GetContentItemsByTerm(term)); + return CBO.FillQueryable(this._dataService.GetContentItemsByTerm(term)); } public IQueryable GetContentItemsByTerm(Term term) - { - return GetContentItemsByTerm(term.Name); - } - - public IQueryable GetContentItemsByContentType(int contentTypeId) - { - return CBO.FillQueryable(_dataService.GetContentItemsByContentType(contentTypeId)); - } + { + return this.GetContentItemsByTerm(term.Name); + } - /// Get a list of content items by ContentType. + public IQueryable GetContentItemsByContentType(int contentTypeId) + { + return CBO.FillQueryable(this._dataService.GetContentItemsByContentType(contentTypeId)); + } + + /// Get a list of content items by ContentType. + /// public IQueryable GetContentItemsByContentType(ContentType contentType) { - return GetContentItemsByContentType(contentType.ContentTypeId); + return this.GetContentItemsByContentType(contentType.ContentTypeId); } - public IQueryable GetContentItemsByTerms(IList terms) + public IQueryable GetContentItemsByTerms(IList terms) { - return GetContentItemsByTerms(terms.Select(t => t.Name).ToArray()); + return this.GetContentItemsByTerms(terms.Select(t => t.Name).ToArray()); } - public IQueryable GetContentItemsByTerms(string[] terms) + public IQueryable GetContentItemsByTerms(string[] terms) { var union = new List(); - union = terms.Aggregate(union, + union = terms.Aggregate( + union, (current, term) => !current.Any() - ? GetContentItemsByTerm(term).ToList() - : current.Intersect(GetContentItemsByTerm(term), new ContentItemEqualityComparer()).ToList()); + ? this.GetContentItemsByTerm(term).ToList() + : current.Intersect(this.GetContentItemsByTerm(term), new ContentItemEqualityComparer()).ToList()); return union.AsQueryable(); } public IQueryable GetContentItemsByTabId(int tabId) { - return CBO.FillQueryable(_dataService.GetContentItemsByTabId(tabId)); + return CBO.FillQueryable(this._dataService.GetContentItemsByTabId(tabId)); } - public IQueryable GetContentItemsByVocabularyId(int vocabularyId) + public IQueryable GetContentItemsByVocabularyId(int vocabularyId) { - return CBO.FillQueryable(_dataService.GetContentItemsByVocabularyId(vocabularyId)); + return CBO.FillQueryable(this._dataService.GetContentItemsByVocabularyId(vocabularyId)); } public IQueryable GetUnIndexedContentItems() { - return CBO.FillQueryable(_dataService.GetUnIndexedContentItems()); + return CBO.FillQueryable(this._dataService.GetUnIndexedContentItems()); } public IQueryable GetContentItemsByModuleId(int moduleId) { - return CBO.FillQueryable(_dataService.GetContentItemsByModuleId(moduleId)); + return CBO.FillQueryable(this._dataService.GetContentItemsByModuleId(moduleId)); } public void UpdateContentItem(ContentItem contentItem) { - //Argument Contract + // Argument Contract Requires.NotNull("contentItem", contentItem); Requires.PropertyNotNegative("contentItem", "ContentItemId", contentItem.ContentItemId); - + AttachmentController.SerializeAttachmentMetadata(contentItem); - SaveMetadataDelta(contentItem); + this.SaveMetadataDelta(contentItem); var userId = UserController.Instance.GetCurrentUserInfo().UserID; - _dataService.UpdateContentItem(contentItem, userId); + this._dataService.UpdateContentItem(contentItem, userId); contentItem.LastModifiedByUserID = userId; UpdateContentItemsCache(contentItem); @@ -184,24 +183,24 @@ public void UpdateContentItem(ContentItem contentItem) public void AddMetaData(ContentItem contentItem, string name, string value) { - //Argument Contract + // Argument Contract Requires.NotNull("contentItem", contentItem); Requires.PropertyNotNegative("contentItem", "ContentItemId", contentItem.ContentItemId); Requires.NotNullOrEmpty("name", name); - _dataService.AddMetaData(contentItem, name, value); + this._dataService.AddMetaData(contentItem, name, value); UpdateContentItemsCache(contentItem, false); } public void DeleteMetaData(ContentItem contentItem, string name, string value) { - //Argument Contract + // Argument Contract Requires.NotNull("contentItem", contentItem); Requires.PropertyNotNegative("contentItem", "ContentItemId", contentItem.ContentItemId); Requires.NotNullOrEmpty("name", name); - _dataService.DeleteMetaData(contentItem, name, value); + this._dataService.DeleteMetaData(contentItem, name, value); UpdateContentItemsCache(contentItem, false); } @@ -210,18 +209,18 @@ public void DeleteMetaData(ContentItem contentItem, string name) { if (contentItem.Metadata.AllKeys.Contains(name)) { - DeleteMetaData(contentItem, name, contentItem.Metadata[name]); + this.DeleteMetaData(contentItem, name, contentItem.Metadata[name]); } } public NameValueCollection GetMetaData(int contentItemId) { - //Argument Contract + // Argument Contract Requires.NotNegative("contentItemId", contentItemId); var metadata = new NameValueCollection(); - using (var dr = _dataService.GetMetaData(contentItemId)) + using (var dr = this._dataService.GetMetaData(contentItemId)) { if (dr != null) { @@ -232,12 +231,31 @@ public NameValueCollection GetMetaData(int contentItemId) } } - return metadata; + return metadata; } - + + private static bool MetaDataChanged( + IEnumerable> lh, + IEnumerable> rh) + { + return lh.SequenceEqual(rh, new NameValueEqualityComparer()) == false; + } + + private static void UpdateContentItemsCache(ContentItem contentItem, bool readdItem = true) + { + DataCache.RemoveCache(GetContentItemCacheKey(contentItem.ContentItemId)); // remove first to synch web-farm servers + if (readdItem) + { + CBO.GetCachedObject( + new CacheItemArgs( + GetContentItemCacheKey(contentItem.ContentItemId), + DataCache.ContentItemsCacheTimeOut, DataCache.ContentItemsCachePriority), c => contentItem); + } + } + private void SaveMetadataDelta(ContentItem contentItem) { - var persisted = GetMetaData(contentItem.ContentItemId); + var persisted = this.GetMetaData(contentItem.ContentItemId); var lh = persisted.AllKeys.ToDictionary(x => x, x => persisted[x]); @@ -254,30 +272,11 @@ private void SaveMetadataDelta(ContentItem contentItem) // Items included in the object but missing from the database (newly added). var added = rh.Except(lh).ToArray(); - _dataService.SynchronizeMetaData(contentItem, added, deleted); + this._dataService.SynchronizeMetaData(contentItem, added, deleted); UpdateContentItemsCache(contentItem, false); } - private static bool MetaDataChanged( - IEnumerable> lh, - IEnumerable> rh) - { - return lh.SequenceEqual(rh, new NameValueEqualityComparer()) == false; - } - - private static void UpdateContentItemsCache(ContentItem contentItem, bool readdItem = true) - { - - DataCache.RemoveCache(GetContentItemCacheKey(contentItem.ContentItemId)); // remove first to synch web-farm servers - if (readdItem) - { - CBO.GetCachedObject(new CacheItemArgs( - GetContentItemCacheKey(contentItem.ContentItemId), - DataCache.ContentItemsCacheTimeOut, DataCache.ContentItemsCachePriority), c => contentItem); - } - } - private static string GetContentItemCacheKey(int contetnItemId) { return string.Format(DataCache.ContentItemsCacheKey, contetnItemId); diff --git a/DNN Platform/Library/Entities/Content/ContentItem.cs b/DNN Platform/Library/Entities/Content/ContentItem.cs index 4569d72e081..5c56a31c1ef 100644 --- a/DNN Platform/Library/Entities/Content/ContentItem.cs +++ b/DNN Platform/Library/Entities/Content/ContentItem.cs @@ -1,227 +1,221 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Data; -using System.Linq; -using System.Web.Script.Serialization; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.FileSystem; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content { - /// - /// The ContentItem class which itself inherits from BaseEntityInfo paves the way for easily adding support for taxonomy, - /// tagging and other ContentItem dependant features to your DotNetNuke extensions. - /// - /// - /// - /// Content Items are a collection of individual pieces of content in a DotNetNuke site. Each content item is associated with a single Content Type. - /// - /// - /// Only modules that implement content items (done so by the module developers) can take advantage of some of its benefits, such as Taxonomy. - /// - /// - /// Because ContentItem already implements IHydratable, you will not do so in your custom entity class. Instead, - /// you will need to create overrides of the KeyID property and the Fill method already implemented in the ContentItem class. - /// Don't forget to call ContentItem's FillInternal method in your Fill method override. - /// - /// - /// - /// - /// [Serializable] + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Data; + using System.Linq; + using System.Web.Script.Serialization; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.FileSystem; + + /// + /// The ContentItem class which itself inherits from BaseEntityInfo paves the way for easily adding support for taxonomy, + /// tagging and other ContentItem dependant features to your DotNetNuke extensions. + /// + /// + /// + /// Content Items are a collection of individual pieces of content in a DotNetNuke site. Each content item is associated with a single Content Type. + /// + /// + /// Only modules that implement content items (done so by the module developers) can take advantage of some of its benefits, such as Taxonomy. + /// + /// + /// Because ContentItem already implements IHydratable, you will not do so in your custom entity class. Instead, + /// you will need to create overrides of the KeyID property and the Fill method already implemented in the ContentItem class. + /// Don't forget to call ContentItem's FillInternal method in your Fill method override. + /// + /// + /// + /// + /// [Serializable] /// public class DesktopModuleInfo : ContentItem, IXmlSerializable /// { - /// #region IHydratable Members - /// - /// public override void Fill(IDataReader dr) - /// { - /// DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); - /// PackageID = Null.SetNullInteger(dr["PackageID"]); - /// ModuleName = Null.SetNullString(dr["ModuleName"]); - /// FriendlyName = Null.SetNullString(dr["FriendlyName"]); - /// Description = Null.SetNullString(dr["Description"]); - /// FolderName = Null.SetNullString(dr["FolderName"]); - /// Version = Null.SetNullString(dr["Version"]); - /// base.FillInternal(dr); - /// } - /// - /// #endregion + /// #region IHydratable Members + /// + /// public override void Fill(IDataReader dr) + /// { + /// DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); + /// PackageID = Null.SetNullInteger(dr["PackageID"]); + /// ModuleName = Null.SetNullString(dr["ModuleName"]); + /// FriendlyName = Null.SetNullString(dr["FriendlyName"]); + /// Description = Null.SetNullString(dr["Description"]); + /// FolderName = Null.SetNullString(dr["FolderName"]); + /// Version = Null.SetNullString(dr["Version"]); + /// base.FillInternal(dr); + /// } + /// + /// #endregion /// } - /// - /// - [Serializable] + /// + /// + [Serializable] public class ContentItem : BaseEntityInfo, IHydratable { private NameValueCollection _metadata; private List _terms; - private List _files; - private List _videos; - private List _images; - + private List _files; + private List _videos; + private List _images; + public ContentItem() { - TabID = Null.NullInteger; - ModuleID = Null.NullInteger; - ContentTypeId = Null.NullInteger; - ContentItemId = Null.NullInteger; - StateID = Null.NullInteger; - } - - #region Public Properties - - /// - /// Gets or sets the content item id. - /// - /// - /// The content item id. - /// + this.TabID = Null.NullInteger; + this.ModuleID = Null.NullInteger; + this.ContentTypeId = Null.NullInteger; + this.ContentItemId = Null.NullInteger; + this.StateID = Null.NullInteger; + } + + /// + /// Gets or sets the content item id. + /// + /// + /// The content item id. + /// [XmlIgnore] [ScriptIgnore] public int ContentItemId { get; set; } - /// - /// Gets or sets the content. - /// - /// - /// The content. - /// + /// + /// Gets or sets the content. + /// + /// + /// The content. + /// [XmlElement("content")] public string Content { get; set; } - /// - /// Gets or sets the content key. - /// - /// - /// The content key. - /// - [XmlElement("contentKey")] + /// + /// Gets or sets the content key. + /// + /// + /// The content key. + /// + [XmlElement("contentKey")] public string ContentKey { get; set; } - /// - /// Gets or sets the content type id. - /// - /// - /// The content type id. - /// - /// + /// + /// Gets or sets the content type id. + /// + /// + /// The content type id. + /// + /// [XmlIgnore] [ScriptIgnore] public int ContentTypeId { get; set; } - /// - /// Gets or sets a value indicating whether this is indexed. - /// - /// - /// true if indexed; otherwise, false. - /// + /// + /// Gets or sets a value indicating whether this is indexed. + /// + /// + /// true if indexed; otherwise, false. + /// [XmlIgnore] [ScriptIgnore] public bool Indexed { get; set; } - /// - /// Gets the metadata. - /// - /// metadata collection + /// + /// Gets the metadata. + /// + /// metadata collection. [XmlIgnore] [ScriptIgnore] public NameValueCollection Metadata { get { - return _metadata ?? (_metadata = this.GetMetaData(ContentItemId)); + return this._metadata ?? (this._metadata = this.GetMetaData(this.ContentItemId)); } } - /// - /// Gets or sets the module ID. - /// - /// - /// The module ID. - /// + /// + /// Gets or sets the module ID. + /// + /// + /// The module ID. + /// [XmlElement("moduleID")] public int ModuleID { get; set; } - /// - /// Gets or sets the tab ID. - /// - /// - /// The tab ID. - /// + /// + /// Gets or sets the tab ID. + /// + /// + /// The tab ID. + /// [XmlElement("tabid")] public int TabID { get; set; } - /// - /// Gets the terms. - /// - /// Terms Collection + /// + /// Gets the terms. + /// + /// Terms Collection. [XmlIgnore] [ScriptIgnore] public List Terms { get { - return _terms ?? (_terms = this.GetTerms(ContentItemId)); + return this._terms ?? (this._terms = this.GetTerms(this.ContentItemId)); } } - /// The title of the ContentItem. - [XmlElement("contentTitle")] - public string ContentTitle - { - get - { - return Metadata[AttachmentController.TitleKey]; - } + /// Gets or sets the title of the ContentItem. + [XmlElement("contentTitle")] + public string ContentTitle + { + get + { + return this.Metadata[AttachmentController.TitleKey]; + } + set { - Metadata[AttachmentController.TitleKey] = value; + this.Metadata[AttachmentController.TitleKey] = value; } - } + } - /// - /// Files that are attached to this ContentItem. - /// - [XmlIgnore] + /// + /// Gets files that are attached to this ContentItem. + /// + [XmlIgnore] [ScriptIgnore] - public List Files - { - get { return _files ?? (_files = AttachmentController.DeserializeFileInfo(Metadata[AttachmentController.FilesKey]).ToList()); } - } + public List Files + { + get { return this._files ?? (this._files = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.FilesKey]).ToList()); } + } - /// - /// Video files attached to this ContentItem. + /// + /// Gets video files attached to this ContentItem. /// [XmlIgnore] [ScriptIgnore] public List Videos - { - get { return _videos ?? (_videos = AttachmentController.DeserializeFileInfo(Metadata[AttachmentController.VideoKey]).ToList()); } - } + { + get { return this._videos ?? (this._videos = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.VideoKey]).ToList()); } + } /// - /// Images associated with this ContentItem. + /// Gets images associated with this ContentItem. /// [XmlIgnore] [ScriptIgnore] public List Images - { - get { return _images ?? (_images = AttachmentController.DeserializeFileInfo(Metadata[AttachmentController.ImageKey]).ToList()); } - } + { + get { return this._images ?? (this._images = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.ImageKey]).ToList()); } + } /// /// Gets or sets the Content Workflow State ID. @@ -230,91 +224,82 @@ public List Images /// The Content Workflow State ID. /// [XmlIgnore] - public int StateID { get; set; } - - #endregion - - #region Protected Methods + public int StateID { get; set; } - /// - /// Fills the internal. - /// - /// The data reader contains module information. - /// - /// Please remember to call base.FillInternal or base.Fill method in your Fill method. - /// + /// + /// Gets or sets the key ID. + /// + /// + /// The key ID. + /// + /// + /// If you derive class has its own key id, please override this property and set the value to your own key id. + /// + [XmlIgnore] + public virtual int KeyID + { + get + { + return this.ContentItemId; + } + + set + { + this.ContentItemId = value; + } + } + + /// + /// Fill this content object will the information from data reader. + /// + /// The data reader. + /// + public virtual void Fill(IDataReader dr) + { + this.FillInternal(dr); + } + + /// + /// Fills the internal. + /// + /// The data reader contains module information. + /// + /// Please remember to call base.FillInternal or base.Fill method in your Fill method. + /// protected override void FillInternal(IDataReader dr) { base.FillInternal(dr); - ContentItemId = Null.SetNullInteger(dr["ContentItemID"]); - Content = Null.SetNullString(dr["Content"]); - ContentTypeId = Null.SetNullInteger(dr["ContentTypeID"]); - TabID = Null.SetNullInteger(dr["TabID"]); - ModuleID = Null.SetNullInteger(dr["ModuleID"]); - ContentKey = Null.SetNullString(dr["ContentKey"]); - Indexed = Null.SetNullBoolean(dr["Indexed"]); + this.ContentItemId = Null.SetNullInteger(dr["ContentItemID"]); + this.Content = Null.SetNullString(dr["Content"]); + this.ContentTypeId = Null.SetNullInteger(dr["ContentTypeID"]); + this.TabID = Null.SetNullInteger(dr["TabID"]); + this.ModuleID = Null.SetNullInteger(dr["ModuleID"]); + this.ContentKey = Null.SetNullString(dr["ContentKey"]); + this.Indexed = Null.SetNullBoolean(dr["Indexed"]); var schema = dr.GetSchemaTable(); if (schema != null) { if (schema.Select("ColumnName = 'StateID'").Length > 0) { - StateID = Null.SetNullInteger(dr["StateID"]); + this.StateID = Null.SetNullInteger(dr["StateID"]); } } } - protected void Clone(ContentItem cloneItem, ContentItem originalItem) - { - CloneBaseProperties(cloneItem, originalItem); - - cloneItem.ContentItemId = originalItem.ContentItemId; - cloneItem.Content = originalItem.Content; - cloneItem.ContentTypeId = originalItem.ContentTypeId; - cloneItem.TabID = originalItem.TabID; - cloneItem.ModuleID = originalItem.ModuleID; - cloneItem.ContentKey = originalItem.ContentKey; + protected void Clone(ContentItem cloneItem, ContentItem originalItem) + { + this.CloneBaseProperties(cloneItem, originalItem); + + cloneItem.ContentItemId = originalItem.ContentItemId; + cloneItem.Content = originalItem.Content; + cloneItem.ContentTypeId = originalItem.ContentTypeId; + cloneItem.TabID = originalItem.TabID; + cloneItem.ModuleID = originalItem.ModuleID; + cloneItem.ContentKey = originalItem.ContentKey; cloneItem.Indexed = originalItem.Indexed; cloneItem.StateID = originalItem.StateID; - } - - #endregion - - #region IHydratable Implementation - - /// - /// Fill this content object will the information from data reader. - /// - /// The data reader. - /// - public virtual void Fill(IDataReader dr) - { - FillInternal(dr); - } - - /// - /// Gets or sets the key ID. - /// - /// - /// The key ID. - /// - /// - /// If you derive class has its own key id, please override this property and set the value to your own key id. - /// - [XmlIgnore] - public virtual int KeyID - { - get - { - return ContentItemId; - } - set - { - ContentItemId = value; - } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/ContentType.cs b/DNN Platform/Library/Entities/Content/ContentType.cs index e8063e2341d..9cbca0334c9 100644 --- a/DNN Platform/Library/Entities/Content/ContentType.cs +++ b/DNN Platform/Library/Entities/Content/ContentType.cs @@ -1,59 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content { + using System; + using System.Data; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// /// Content type of a content item. /// /// - /// Content Types, simply put, are a way of telling the framework what module/functionality is associated with a Content Item. + /// Content Types, simply put, are a way of telling the framework what module/functionality is associated with a Content Item. /// Each product (ie. module) that wishes to allow categorization of data (via Taxonomy or Folksonomy) for it's content items - /// will likely need to create its own content type. + /// will likely need to create its own content type. /// [Serializable] public class ContentType : ContentTypeMemberNameFixer, IHydratable - { - #region Private Members - + { + private const string desktopModuleContentTypeName = "DesktopModule"; + private const string moduleContentTypeName = "Module"; + private static ContentType _desktopModule; private static ContentType _module; private static ContentType _tab; - - private const string desktopModuleContentTypeName = "DesktopModule"; - private const string moduleContentTypeName = "Module"; - private const string tabContentTypeName = "Tab"; - - #endregion - - #region Constructors - - public ContentType() : this(Null.NullString) + private const string tabContentTypeName = "Tab"; + + public ContentType() + : this(Null.NullString) { } public ContentType(string contentType) { - ContentTypeId = Null.NullInteger; - ContentType = contentType; - } - - #endregion - - #region Public Static Properties - + this.ContentTypeId = Null.NullInteger; + this.ContentType = contentType; + } + public static ContentType DesktopModule { get @@ -76,60 +62,55 @@ public static ContentType Tab { return _tab ?? (_tab = new ContentTypeController().GetContentTypes().FirstOrDefault(type => type.ContentType == tabContentTypeName)); } - } - - #endregion - + } + /// - /// Gets or sets the content type id. - /// - /// - /// The content type id. - /// - public int ContentTypeId { get; set; } - - #region IHydratable Implementation - - /// - /// Fill this content object will the information from data reader. + /// Gets or sets the content type id. /// - /// The data reader. - /// - public void Fill(IDataReader dr) - { - ContentTypeId = Null.SetNullInteger(dr["ContentTypeID"]); - ContentType = Null.SetNullString(dr["ContentType"]); - } + /// + /// The content type id. + /// + public int ContentTypeId { get; set; } /// /// Gets or sets the key ID. /// /// - /// ContentTypeID + /// ContentTypeID. /// public int KeyID { get { - return ContentTypeId; + return this.ContentTypeId; } + set { - ContentTypeId = value; + this.ContentTypeId = value; } + } + + /// + /// Fill this content object will the information from data reader. + /// + /// The data reader. + /// + public void Fill(IDataReader dr) + { + this.ContentTypeId = Null.SetNullInteger(dr["ContentTypeID"]); + this.ContentType = Null.SetNullString(dr["ContentType"]); } - - #endregion - + /// - /// override ToString to return content type + /// override ToString to return content type. /// /// /// property ContentType's value. /// public override string ToString() { - return ContentType; + return this.ContentType; } } } diff --git a/DNN Platform/Library/Entities/Content/ContentTypeController.cs b/DNN Platform/Library/Entities/Content/ContentTypeController.cs index 590797fb35f..9c57927bc1d 100644 --- a/DNN Platform/Library/Entities/Content/ContentTypeController.cs +++ b/DNN Platform/Library/Entities/Content/ContentTypeController.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content { + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Data; + /// /// ContentTypeController provides the business layer of ContentType. /// @@ -36,23 +31,18 @@ namespace DotNetNuke.Entities.Content /// public class ContentTypeController : IContentTypeController { - private readonly IDataService _DataService; - - #region Constructors - - public ContentTypeController() : this(Util.GetDataService()) + private readonly IDataService _DataService; + + public ContentTypeController() + : this(Util.GetDataService()) { } public ContentTypeController(IDataService dataService) { - _DataService = dataService; - } - - #endregion - - #region Public Methods - + this._DataService = dataService; + } + /// /// Adds the type of the content. /// @@ -62,14 +52,14 @@ public ContentTypeController(IDataService dataService) /// contentType.ContentType is empty. public int AddContentType(ContentType contentType) { - //Argument Contract + // Argument Contract Requires.NotNull("contentType", contentType); Requires.PropertyNotNullOrEmpty("contentType", "ContentType", contentType.ContentType); - contentType.ContentTypeId = _DataService.AddContentType(contentType); + contentType.ContentTypeId = this._DataService.AddContentType(contentType); - //Refresh cached collection of types - ClearContentTypeCache(); + // Refresh cached collection of types + this.ClearContentTypeCache(); return contentType.ContentTypeId; } @@ -90,14 +80,14 @@ public void ClearContentTypeCache() /// content type id is less than 0. public void DeleteContentType(ContentType contentType) { - //Argument Contract + // Argument Contract Requires.NotNull("contentType", contentType); Requires.PropertyNotNegative("contentType", "ContentTypeId", contentType.ContentTypeId); - _DataService.DeleteContentType(contentType); + this._DataService.DeleteContentType(contentType); - //Refresh cached collection of types - ClearContentTypeCache(); + // Refresh cached collection of types + this.ClearContentTypeCache(); } /// @@ -106,10 +96,12 @@ public void DeleteContentType(ContentType contentType) /// content type collection. public IQueryable GetContentTypes() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.ContentTypesCacheKey, - DataCache.ContentTypesCacheTimeOut, - DataCache.ContentTypesCachePriority), - c => CBO.FillQueryable(_DataService.GetContentTypes()).ToList()).AsQueryable(); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.ContentTypesCacheKey, + DataCache.ContentTypesCacheTimeOut, + DataCache.ContentTypesCachePriority), + c => CBO.FillQueryable(this._DataService.GetContentTypes()).ToList()).AsQueryable(); } /// @@ -121,17 +113,15 @@ public IQueryable GetContentTypes() /// contentType.ContentType is empty. public void UpdateContentType(ContentType contentType) { - //Argument Contract + // Argument Contract Requires.NotNull("contentType", contentType); Requires.PropertyNotNegative("contentType", "ContentTypeId", contentType.ContentTypeId); Requires.PropertyNotNullOrEmpty("contentType", "ContentType", contentType.ContentType); - _DataService.UpdateContentType(contentType); - - //Refresh cached collection of types - ClearContentTypeCache(); - } + this._DataService.UpdateContentType(contentType); - #endregion + // Refresh cached collection of types + this.ClearContentTypeCache(); + } } } diff --git a/DNN Platform/Library/Entities/Content/ContentTypeMemberNameFixer.cs b/DNN Platform/Library/Entities/Content/ContentTypeMemberNameFixer.cs index 6249ff3bba5..c16e376b315 100644 --- a/DNN Platform/Library/Entities/Content/ContentTypeMemberNameFixer.cs +++ b/DNN Platform/Library/Entities/Content/ContentTypeMemberNameFixer.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content { + using System; + /// /// This class exists solely to maintain compatibility between the original VB version /// which supported ContentType.ContentType and the c# version which doesn't allow members with - /// the same naem as their parent type + /// the same naem as their parent type. /// [Serializable] public abstract class ContentTypeMemberNameFixer diff --git a/DNN Platform/Library/Entities/Content/Data/DataService.cs b/DNN Platform/Library/Entities/Content/Data/DataService.cs index 97ceb4de501..70048ac1d56 100644 --- a/DNN Platform/Library/Entities/Content/Data/DataService.cs +++ b/DNN Platform/Library/Entities/Content/Data/DataService.cs @@ -1,83 +1,78 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Services.FileSystem; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Data { - /// - /// Persistent data of content with DataProvider instance. - /// - /// - /// It's better to use Util.GetDataService instead of create new instance directly. - /// - /// - /// - /// public ContentController() : this(Util.GetDataService()) + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Text; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Services.FileSystem; + + /// + /// Persistent data of content with DataProvider instance. + /// + /// + /// It's better to use Util.GetDataService instead of create new instance directly. + /// + /// + /// + /// public ContentController() : this(Util.GetDataService()) /// { /// } /// public ContentController(IDataService dataService) /// { /// _dataService = dataService; /// } - /// - /// + /// + /// public class DataService : IDataService { - private readonly DataProvider _provider = DataProvider.Instance(); - - #region "ContentItem Methods" - - /// - /// Adds the content item. - /// - /// The content item. - /// The created by user id. - /// content item id. + private readonly DataProvider _provider = DataProvider.Instance(); + + /// + /// Adds the content item. + /// + /// The content item. + /// The created by user id. + /// content item id. public int AddContentItem(ContentItem contentItem, int createdByUserId) { - return _provider.ExecuteScalar("AddContentItem", - contentItem.Content, - contentItem.ContentTypeId, - contentItem.TabID, - contentItem.ModuleID, - contentItem.ContentKey, - contentItem.Indexed, - createdByUserId, - _provider.GetNull(contentItem.StateID)); - } - - /// - /// Deletes the content item. - /// - /// The content item ID. + return this._provider.ExecuteScalar( + "AddContentItem", + contentItem.Content, + contentItem.ContentTypeId, + contentItem.TabID, + contentItem.ModuleID, + contentItem.ContentKey, + contentItem.Indexed, + createdByUserId, + this._provider.GetNull(contentItem.StateID)); + } + + /// + /// Deletes the content item. + /// + /// The content item ID. public void DeleteContentItem(int contentItemId) { - _provider.ExecuteNonQuery("DeleteContentItem", contentItemId); + this._provider.ExecuteNonQuery("DeleteContentItem", contentItemId); } - /// - /// Gets the content item. - /// - /// The content item id. - /// data reader. + /// + /// Gets the content item. + /// + /// The content item id. + /// data reader. public IDataReader GetContentItem(int contentItemId) { - return _provider.ExecuteReader("GetContentItem", contentItemId); + return this._provider.ExecuteReader("GetContentItem", contentItemId); } /// @@ -89,99 +84,100 @@ public IDataReader GetContentItem(int contentItemId) /// data reader. public IDataReader GetContentItems(int contentTypeId, int tabId, int moduleId) { - return _provider.ExecuteReader("GetContentItems", _provider.GetNull(contentTypeId), - _provider.GetNull(tabId), - _provider.GetNull(moduleId)); + return this._provider.ExecuteReader("GetContentItems", this._provider.GetNull(contentTypeId), + this._provider.GetNull(tabId), + this._provider.GetNull(moduleId)); } - - /// - /// Gets the content items by term. - /// - /// The term. - /// data reader. + + /// + /// Gets the content items by term. + /// + /// The term. + /// data reader. public IDataReader GetContentItemsByTerm(string term) { - return _provider.ExecuteReader("GetContentItemsByTerm", term); + return this._provider.ExecuteReader("GetContentItemsByTerm", term); } /// /// Get a list of content items of the specified content type, . /// - /// The type of content items you are searching for - public IDataReader GetContentItemsByContentType(int contentTypeId) + /// The type of content items you are searching for. + /// + public IDataReader GetContentItemsByContentType(int contentTypeId) { - return _provider.ExecuteReader("GetContentItemsByContentType", contentTypeId); + return this._provider.ExecuteReader("GetContentItemsByContentType", contentTypeId); } /// /// Get a list of content items based on TabID (PageID). /// - /// The TabID (or "Page ID") that the content items are associated with + /// The TabID (or "Page ID") that the content items are associated with. + /// public IDataReader GetContentItemsByTabId(int tabId) { - return _provider.ExecuteReader("GetContentItemsByTabId", tabId); + return this._provider.ExecuteReader("GetContentItemsByTabId", tabId); } /// /// Retrieve all content items associated with a articular Module ID, . - /// + /// + /// public IDataReader GetContentItemsByModuleId(int moduleId) { - return _provider.ExecuteReader("GetContentItemsByModuleId", moduleId); + return this._provider.ExecuteReader("GetContentItemsByModuleId", moduleId); } /// /// Retrieve a list of content items containg terms from the specified Vocabulary ID. - /// + /// + /// public IDataReader GetContentItemsByVocabularyId(int vocabularyId) { - return _provider.ExecuteReader("GetContentItemsByVocabularyId", vocabularyId); + return this._provider.ExecuteReader("GetContentItemsByVocabularyId", vocabularyId); } - /// - /// Gets the un indexed content items. - /// - /// data reader. + /// + /// Gets the un indexed content items. + /// + /// data reader. public IDataReader GetUnIndexedContentItems() { - return _provider.ExecuteReader("GetUnIndexedContentItems"); + return this._provider.ExecuteReader("GetUnIndexedContentItems"); } - /// - /// Updates the content item. - /// - /// The content item. - /// The created by user id. + /// + /// Updates the content item. + /// + /// The content item. + /// The created by user id. public void UpdateContentItem(ContentItem contentItem, int createdByUserId) { - _provider.ExecuteNonQuery("UpdateContentItem", - contentItem.ContentItemId, - contentItem.Content, - contentItem.ContentTypeId, - contentItem.TabID, - contentItem.ModuleID, - contentItem.ContentKey, - contentItem.Indexed, - createdByUserId, - _provider.GetNull(contentItem.StateID)); - } - - #endregion - - #region "MetaData Methods" - - /// - /// Adds the meta data. - /// - /// The content item. - /// The name. - /// The value. + this._provider.ExecuteNonQuery( + "UpdateContentItem", + contentItem.ContentItemId, + contentItem.Content, + contentItem.ContentTypeId, + contentItem.TabID, + contentItem.ModuleID, + contentItem.ContentKey, + contentItem.Indexed, + createdByUserId, + this._provider.GetNull(contentItem.StateID)); + } + + /// + /// Adds the meta data. + /// + /// The content item. + /// The name. + /// The value. public void AddMetaData(ContentItem contentItem, string name, string value) { - _provider.ExecuteNonQuery("AddMetaData", contentItem.ContentItemId, name, value); + this._provider.ExecuteNonQuery("AddMetaData", contentItem.ContentItemId, name, value); } - - public void SynchronizeMetaData(ContentItem contentItem, IEnumerable> added, IEnumerable> deleted) + + public void SynchronizeMetaData(ContentItem contentItem, IEnumerable> added, IEnumerable> deleted) { #if false //TODO: fixing the original code requires adding new DataProvider methods. Reason: @@ -214,41 +210,37 @@ public void SynchronizeMetaData(ContentItem contentItem, IEnumerable - /// Deletes the meta data. - /// - /// The content item. - /// The name. - /// The value. + /// + /// Deletes the meta data. + /// + /// The content item. + /// The name. + /// The value. public void DeleteMetaData(ContentItem contentItem, string name, string value) { - _provider.ExecuteNonQuery("DeleteMetaData", contentItem.ContentItemId, name, value); + this._provider.ExecuteNonQuery("DeleteMetaData", contentItem.ContentItemId, name, value); } - /// - /// Gets the meta data. - /// - /// The content item id. - /// data reader. + /// + /// Gets the meta data. + /// + /// The content item id. + /// data reader. public IDataReader GetMetaData(int contentItemId) { - return _provider.ExecuteReader("GetMetaData", contentItemId); - } - - #endregion - - #region "ContentType Methods" - + return this._provider.ExecuteReader("GetMetaData", contentItemId); + } + /// /// Adds the type of the content. /// @@ -256,12 +248,12 @@ public IDataReader GetMetaData(int contentItemId) /// content type id. public int AddContentType(ContentType contentType) { - return _provider.ExecuteScalar("AddContentType", contentType.ContentType); + return this._provider.ExecuteScalar("AddContentType", contentType.ContentType); } public void DeleteContentType(ContentType contentType) { - _provider.ExecuteNonQuery("DeleteContentType", contentType.ContentTypeId); + this._provider.ExecuteNonQuery("DeleteContentType", contentType.ContentTypeId); } /// @@ -270,7 +262,7 @@ public void DeleteContentType(ContentType contentType) /// data reader. public IDataReader GetContentTypes() { - return _provider.ExecuteReader("GetContentTypes"); + return this._provider.ExecuteReader("GetContentTypes"); } /// @@ -279,13 +271,9 @@ public IDataReader GetContentTypes() /// Type of the content. public void UpdateContentType(ContentType contentType) { - _provider.ExecuteNonQuery("UpdateContentType", contentType.ContentTypeId, contentType.ContentType); - } - - #endregion - - #region "ScopeType Methods" - + this._provider.ExecuteNonQuery("UpdateContentType", contentType.ContentTypeId, contentType.ContentType); + } + /// /// Adds the type of the scope. /// @@ -293,210 +281,203 @@ public void UpdateContentType(ContentType contentType) /// scope type id. public int AddScopeType(ScopeType scopeType) { - return _provider.ExecuteScalar("AddScopeType", scopeType.ScopeType); + return this._provider.ExecuteScalar("AddScopeType", scopeType.ScopeType); } - /// - /// Deletes the type of the scope. - /// - /// Type of the scope. + /// + /// Deletes the type of the scope. + /// + /// Type of the scope. public void DeleteScopeType(ScopeType scopeType) { - _provider.ExecuteNonQuery("DeleteScopeType", scopeType.ScopeTypeId); + this._provider.ExecuteNonQuery("DeleteScopeType", scopeType.ScopeTypeId); } - /// - /// Gets the scope types. - /// - /// data reader. + /// + /// Gets the scope types. + /// + /// data reader. public IDataReader GetScopeTypes() { - return _provider.ExecuteReader("GetScopeTypes"); + return this._provider.ExecuteReader("GetScopeTypes"); } - /// - /// Updates the type of the scope. - /// - /// Type of the scope. + /// + /// Updates the type of the scope. + /// + /// Type of the scope. public void UpdateScopeType(ScopeType scopeType) { - _provider.ExecuteNonQuery("UpdateScopeType", scopeType.ScopeTypeId, scopeType.ScopeType); - } - - #endregion - - #region "Term Methods" - - /// - /// Adds the heirarchical term. - /// - /// The term. - /// The created by user id. - /// term id. + this._provider.ExecuteNonQuery("UpdateScopeType", scopeType.ScopeTypeId, scopeType.ScopeType); + } + + /// + /// Adds the heirarchical term. + /// + /// The term. + /// The created by user id. + /// term id. public int AddHeirarchicalTerm(Term term, int createdByUserId) { - return _provider.ExecuteScalar("AddHeirarchicalTerm", term.VocabularyId, term.ParentTermId, term.Name, term.Description, term.Weight, createdByUserId); + return this._provider.ExecuteScalar("AddHeirarchicalTerm", term.VocabularyId, term.ParentTermId, term.Name, term.Description, term.Weight, createdByUserId); } - /// - /// Adds the simple term. - /// - /// The term. - /// The created by user id. - /// term id. + /// + /// Adds the simple term. + /// + /// The term. + /// The created by user id. + /// term id. public int AddSimpleTerm(Term term, int createdByUserId) { - return _provider.ExecuteScalar("AddSimpleTerm", term.VocabularyId, term.Name, term.Description, term.Weight, createdByUserId); + return this._provider.ExecuteScalar("AddSimpleTerm", term.VocabularyId, term.Name, term.Description, term.Weight, createdByUserId); } public void AddTermToContent(Term term, ContentItem contentItem) { - _provider.ExecuteNonQuery("AddTermToContent", term.TermId, contentItem.ContentItemId); + this._provider.ExecuteNonQuery("AddTermToContent", term.TermId, contentItem.ContentItemId); } - /// - /// Deletes the simple term. - /// - /// The term. + /// + /// Deletes the simple term. + /// + /// The term. public void DeleteSimpleTerm(Term term) { - _provider.ExecuteNonQuery("DeleteSimpleTerm", term.TermId); + this._provider.ExecuteNonQuery("DeleteSimpleTerm", term.TermId); } - /// - /// Deletes the heirarchical term. - /// - /// The term. + /// + /// Deletes the heirarchical term. + /// + /// The term. public void DeleteHeirarchicalTerm(Term term) { - _provider.ExecuteNonQuery("DeleteHeirarchicalTerm", term.TermId); + this._provider.ExecuteNonQuery("DeleteHeirarchicalTerm", term.TermId); } - /// - /// Gets the term. - /// - /// The term id. - /// data reader. + /// + /// Gets the term. + /// + /// The term id. + /// data reader. public IDataReader GetTerm(int termId) { - return _provider.ExecuteReader("GetTerm", termId); + return this._provider.ExecuteReader("GetTerm", termId); } /// /// Retrieve term usage data for the specified Term ID, . - /// - public IDataReader GetTermUsage(int termId) + /// + /// + public IDataReader GetTermUsage(int termId) { - return _provider.ExecuteReader("GetTermUsage", termId); + return this._provider.ExecuteReader("GetTermUsage", termId); } - /// - /// Gets the content of the terms by. - /// - /// The content item id. - /// data reader. + /// + /// Gets the content of the terms by. + /// + /// The content item id. + /// data reader. public IDataReader GetTermsByContent(int contentItemId) { - return _provider.ExecuteReader("GetTermsByContent", contentItemId); + return this._provider.ExecuteReader("GetTermsByContent", contentItemId); } - /// - /// Gets the terms by vocabulary. - /// - /// The vocabulary id. - /// data reader. + /// + /// Gets the terms by vocabulary. + /// + /// The vocabulary id. + /// data reader. public IDataReader GetTermsByVocabulary(int vocabularyId) { - return _provider.ExecuteReader("GetTermsByVocabulary", vocabularyId); + return this._provider.ExecuteReader("GetTermsByVocabulary", vocabularyId); } - /// - /// Removes the content of the terms from. - /// - /// The content item. + /// + /// Removes the content of the terms from. + /// + /// The content item. public void RemoveTermsFromContent(ContentItem contentItem) { - _provider.ExecuteNonQuery("RemoveTermsFromContent", contentItem.ContentItemId); + this._provider.ExecuteNonQuery("RemoveTermsFromContent", contentItem.ContentItemId); } - /// - /// Updates the heirarchical term. - /// - /// The term. - /// The last modified by user id. + /// + /// Updates the heirarchical term. + /// + /// The term. + /// The last modified by user id. public void UpdateHeirarchicalTerm(Term term, int lastModifiedByUserId) { - _provider.ExecuteNonQuery("UpdateHeirarchicalTerm", term.TermId, term.VocabularyId, term.ParentTermId, term.Name, term.Description, term.Weight, lastModifiedByUserId); + this._provider.ExecuteNonQuery("UpdateHeirarchicalTerm", term.TermId, term.VocabularyId, term.ParentTermId, term.Name, term.Description, term.Weight, lastModifiedByUserId); } - /// - /// Updates the simple term. - /// - /// The term. - /// The last modified by user id. + /// + /// Updates the simple term. + /// + /// The term. + /// The last modified by user id. public void UpdateSimpleTerm(Term term, int lastModifiedByUserId) { - _provider.ExecuteNonQuery("UpdateSimpleTerm", term.TermId, term.VocabularyId, term.Name, term.Description, term.Weight, lastModifiedByUserId); - } - - #endregion - - #region "Vocabulary Methods" - - /// - /// Adds the vocabulary. - /// - /// The vocabulary. - /// The created by user id. - /// Vocabulary id. + this._provider.ExecuteNonQuery("UpdateSimpleTerm", term.TermId, term.VocabularyId, term.Name, term.Description, term.Weight, lastModifiedByUserId); + } + + /// + /// Adds the vocabulary. + /// + /// The vocabulary. + /// The created by user id. + /// Vocabulary id. public int AddVocabulary(Vocabulary vocabulary, int createdByUserId) { - return _provider.ExecuteScalar("AddVocabulary", - vocabulary.Type, - vocabulary.Name, - vocabulary.Description, - vocabulary.Weight, - _provider.GetNull(vocabulary.ScopeId), - vocabulary.ScopeTypeId, - createdByUserId); + return this._provider.ExecuteScalar( + "AddVocabulary", + vocabulary.Type, + vocabulary.Name, + vocabulary.Description, + vocabulary.Weight, + this._provider.GetNull(vocabulary.ScopeId), + vocabulary.ScopeTypeId, + createdByUserId); } - /// - /// Deletes the vocabulary. - /// - /// The vocabulary. + /// + /// Deletes the vocabulary. + /// + /// The vocabulary. public void DeleteVocabulary(Vocabulary vocabulary) { - _provider.ExecuteNonQuery("DeleteVocabulary", vocabulary.VocabularyId); + this._provider.ExecuteNonQuery("DeleteVocabulary", vocabulary.VocabularyId); } - /// - /// Gets the vocabularies. - /// - /// data reader. + /// + /// Gets the vocabularies. + /// + /// data reader. public IDataReader GetVocabularies() { - return _provider.ExecuteReader("GetVocabularies"); + return this._provider.ExecuteReader("GetVocabularies"); } - /// - /// Updates the vocabulary. - /// - /// The vocabulary. - /// The last modified by user id. + /// + /// Updates the vocabulary. + /// + /// The vocabulary. + /// The last modified by user id. public void UpdateVocabulary(Vocabulary vocabulary, int lastModifiedByUserId) { - _provider.ExecuteNonQuery("UpdateVocabulary", - vocabulary.VocabularyId, - vocabulary.Type, - vocabulary.Name, - vocabulary.Description, - vocabulary.Weight, - vocabulary.ScopeId, - vocabulary.ScopeTypeId, - lastModifiedByUserId); - } - - #endregion + this._provider.ExecuteNonQuery( + "UpdateVocabulary", + vocabulary.VocabularyId, + vocabulary.Type, + vocabulary.Name, + vocabulary.Description, + vocabulary.Weight, + vocabulary.ScopeId, + vocabulary.ScopeTypeId, + lastModifiedByUserId); + } } } diff --git a/DNN Platform/Library/Entities/Content/Data/IDataService.cs b/DNN Platform/Library/Entities/Content/Data/IDataService.cs index 3fdc65af0aa..2ce355bd773 100644 --- a/DNN Platform/Library/Entities/Content/Data/IDataService.cs +++ b/DNN Platform/Library/Entities/Content/Data/IDataService.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Services.FileSystem; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Data { - /// - /// Interface of DataService. - /// - /// + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Services.FileSystem; + + /// + /// Interface of DataService. + /// + /// public interface IDataService { - //Content Item Methods + // Content Item Methods int AddContentItem(ContentItem contentItem, int createdByUserId); void DeleteContentItem(int contentItemId); IDataReader GetContentItem(int contentItemId); - IDataReader GetContentItems(int contentTypeId, int tabId, int moduleId); + IDataReader GetContentItems(int contentTypeId, int tabId, int moduleId); IDataReader GetContentItemsByTerm(string term); @@ -35,26 +30,27 @@ public interface IDataService IDataReader GetContentItemsByModuleId(int moduleId); - IDataReader GetContentItemsByTabId(int tabId); + IDataReader GetContentItemsByTabId(int tabId); - IDataReader GetContentItemsByVocabularyId(int vocabularyId); + IDataReader GetContentItemsByVocabularyId(int vocabularyId); IDataReader GetUnIndexedContentItems(); void UpdateContentItem(ContentItem contentItem, int lastModifiedByUserId); - //Content MetaData Methods + // Content MetaData Methods void AddMetaData(ContentItem contentItem, string name, string value); void DeleteMetaData(ContentItem contentItem, string name, string value); - + IDataReader GetMetaData(int contentItemId); - void SynchronizeMetaData(ContentItem contentItem, - IEnumerable> added, - IEnumerable> deleted); + void SynchronizeMetaData( + ContentItem contentItem, + IEnumerable> added, + IEnumerable> deleted); - //ContentType Methods + // ContentType Methods int AddContentType(ContentType contentType); void DeleteContentType(ContentType contentType); @@ -62,8 +58,8 @@ void SynchronizeMetaData(ContentItem contentItem, IDataReader GetContentTypes(); void UpdateContentType(ContentType contentType); - - //ScopeType Methods + + // ScopeType Methods int AddScopeType(ScopeType scopeType); void DeleteScopeType(ScopeType scopeType); @@ -72,7 +68,7 @@ void SynchronizeMetaData(ContentItem contentItem, void UpdateScopeType(ScopeType scopeType); - //Term Methods + // Term Methods int AddHeirarchicalTerm(Term term, int createdByUserId); int AddSimpleTerm(Term term, int createdByUserId); @@ -85,7 +81,7 @@ void SynchronizeMetaData(ContentItem contentItem, IDataReader GetTerm(int termId); - IDataReader GetTermUsage(int termId); + IDataReader GetTermUsage(int termId); IDataReader GetTermsByContent(int contentItemId); @@ -97,7 +93,7 @@ void SynchronizeMetaData(ContentItem contentItem, void UpdateSimpleTerm(Term term, int lastModifiedByUserId); - //Vocabulary Methods + // Vocabulary Methods int AddVocabulary(Vocabulary vocabulary, int createdByUserId); void DeleteVocabulary(Vocabulary vocabulary); diff --git a/DNN Platform/Library/Entities/Content/IAttachmentController.cs b/DNN Platform/Library/Entities/Content/IAttachmentController.cs index 2b4794b00a1..c5f05596ae1 100644 --- a/DNN Platform/Library/Entities/Content/IAttachmentController.cs +++ b/DNN Platform/Library/Entities/Content/IAttachmentController.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content { - /// Interface of FileController + using System.Collections.Generic; + + using DotNetNuke.Services.FileSystem; + + /// Interface of FileController. /// public interface IAttachmentController { /// /// Add a generic file to a . /// - /// The content item - /// A file registered in the DotNetNuke + /// The content item. + /// A file registered in the DotNetNuke. void AddFileToContent(int contentItemId, IFileInfo fileInfo); void AddFilesToContent(int contentItemId, IEnumerable fileInfo); @@ -23,8 +24,8 @@ public interface IAttachmentController /// /// Add a video file to a . /// - /// The content item - /// A file registered in the DotNetNuke + /// The content item. + /// A file registered in the DotNetNuke. void AddVideoToContent(int contentItemId, IFileInfo fileInfo); void AddVideosToContent(int contentItemId, IEnumerable fileInfo); @@ -32,8 +33,8 @@ public interface IAttachmentController /// /// Attach an image to a ContentItem. /// - /// The content item - /// A file registered in the DotNetNuke + /// The content item. + /// A file registered in the DotNetNuke. void AddImageToContent(int contentItemId, IFileInfo fileInfo); void AddImagesToContent(int contentItemId, IEnumerable fileInfo); @@ -41,7 +42,7 @@ public interface IAttachmentController IList GetFilesByContent(int contentItemId); IList GetVideosByContent(int contentItemId); - + IList GetImagesByContent(int contentItemId); } } diff --git a/DNN Platform/Library/Entities/Content/IContentController.cs b/DNN Platform/Library/Entities/Content/IContentController.cs index b4c6d2157b8..113bcd371ae 100644 --- a/DNN Platform/Library/Entities/Content/IContentController.cs +++ b/DNN Platform/Library/Entities/Content/IContentController.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; - -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content { + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + /// /// IContentController provides the business layer of ContentItem. /// @@ -47,9 +42,9 @@ public interface IContentController void DeleteContentItem(ContentItem contentItem); /// Delete a ContentItem object by ID. - /// The ID of the ContentItem object (ContentItemId) - void DeleteContentItem(int contentItemId); - + /// The ID of the ContentItem object (ContentItemId). + void DeleteContentItem(int contentItemId); + /// /// Gets the content item. /// @@ -59,32 +54,38 @@ public interface IContentController ContentItem GetContentItem(int contentItemId); /// Return ContentItems that have the specified term attached. - /// Term name is empty. - IQueryable GetContentItemsByTerm(string term); + /// Term name is empty. + /// + IQueryable GetContentItemsByTerm(string term); /// Return ContentItems that have the specified term attached. - /// Term name is empty. + /// Term name is empty. + /// IQueryable GetContentItemsByTerm(Term term); /// /// Get a list of content items by ContentType ID. /// - /// The Content Type ID of the content items we want to query - IQueryable GetContentItemsByContentType(int contentTypeId); + /// The Content Type ID of the content items we want to query. + /// + IQueryable GetContentItemsByContentType(int contentTypeId); /// /// Get a list of content items by ContentType. /// - /// The Content Type of the content items we want to query - IQueryable GetContentItemsByContentType(ContentType contentType); + /// The Content Type of the content items we want to query. + /// + IQueryable GetContentItemsByContentType(ContentType contentType); /// /// Return a list of ContentItems that have all of the specified terms attached. /// - /// A list of terms that should be attached to the ContentItems returned - IQueryable GetContentItemsByTerms(IList terms); - - /// Return a list of ContentItems that have all of the specified terms attached. + /// A list of terms that should be attached to the ContentItems returned. + /// + IQueryable GetContentItemsByTerms(IList terms); + + /// Return a list of ContentItems that have all of the specified terms attached. + /// IQueryable GetContentItemsByTerms(string[] terms); /// @@ -96,19 +97,22 @@ public interface IContentController /// /// Retrieve all content items associated with the specified module ID, . /// - /// The module ID to use in the content item lookup - IQueryable GetContentItemsByModuleId(int moduleId); + /// The module ID to use in the content item lookup. + /// + IQueryable GetContentItemsByModuleId(int moduleId); /// /// Retrieve all content items on the specified page (tab). /// - /// The page ID to use in the lookup of content items - IQueryable GetContentItemsByTabId(int tabId); + /// The page ID to use in the lookup of content items. + /// + IQueryable GetContentItemsByTabId(int tabId); /// /// Get a list of content items tagged with terms from the specified Vocabulary ID. - /// - IQueryable GetContentItemsByVocabularyId(int vocabularyId); + /// + /// + IQueryable GetContentItemsByVocabularyId(int vocabularyId); /// /// Updates the content item. @@ -143,7 +147,7 @@ public interface IContentController /// /// Similar to DeleteMetaData that requires a value, but this one looks it up for you. /// - void DeleteMetaData(ContentItem contentItem, string name); + void DeleteMetaData(ContentItem contentItem, string name); /// /// Gets the meta data. diff --git a/DNN Platform/Library/Entities/Content/IContentTypeController.cs b/DNN Platform/Library/Entities/Content/IContentTypeController.cs index 40381308d7a..72059b47c17 100644 --- a/DNN Platform/Library/Entities/Content/IContentTypeController.cs +++ b/DNN Platform/Library/Entities/Content/IContentTypeController.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content { - /// - /// Interface of ContentTypeController. - /// - /// + using System; + using System.Linq; + + /// + /// Interface of ContentTypeController. + /// + /// public interface IContentTypeController { /// diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/IScopeTypeController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/IScopeTypeController.cs index f583a49ec17..26d87b50cd2 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/IScopeTypeController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/IScopeTypeController.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Linq; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// Interface of ScopeTypeController. - /// - /// + using System.Linq; + + /// + /// Interface of ScopeTypeController. + /// + /// public interface IScopeTypeController { int AddScopeType(ScopeType scopeType); diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/ITermController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/ITermController.cs index f3b4dca5eee..b022f62837c 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/ITermController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/ITermController.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Linq; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// Interface of TermController. - /// - /// + using System.Linq; + + /// + /// Interface of TermController. + /// + /// public interface ITermController { int AddTerm(Term term); diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/IVocabularyController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/IVocabularyController.cs index d6926ff3c42..4b60a032686 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/IVocabularyController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/IVocabularyController.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Linq; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// Interface of VocabularyController. - /// - /// + using System.Linq; + + /// + /// Interface of VocabularyController. + /// + /// public interface IVocabularyController { int AddVocabulary(Vocabulary vocabulary); diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs index 52c8a462a69..74572ea423e 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// /// This class exists solely to maintain compatibility between the original VB version /// which supported ScopeType.ScopeType and the c# version which doesn't allow members with - /// the same naem as their parent type + /// the same naem as their parent type. /// [Serializable] public abstract class ScopeTypeMemberNameFixer @@ -25,46 +20,48 @@ public abstract class ScopeTypeMemberNameFixer public string ScopeType { get; set; } } - /// - /// Class of ScopeType. - /// - /// + /// + /// Class of ScopeType. + /// + /// [Serializable] public class ScopeType : ScopeTypeMemberNameFixer, IHydratable { - public ScopeType() : this(Null.NullString) + public ScopeType() + : this(Null.NullString) { } public ScopeType(string scopeType) { - ScopeTypeId = Null.NullInteger; - ScopeType = scopeType; + this.ScopeTypeId = Null.NullInteger; + this.ScopeType = scopeType; } public int ScopeTypeId { get; set; } - public void Fill(IDataReader dr) - { - ScopeTypeId = Null.SetNullInteger(dr["ScopeTypeID"]); - ScopeType = Null.SetNullString(dr["ScopeType"]); - } - public int KeyID { get { - return ScopeTypeId; + return this.ScopeTypeId; } + set { - ScopeTypeId = value; + this.ScopeTypeId = value; } } + public void Fill(IDataReader dr) + { + this.ScopeTypeId = Null.SetNullInteger(dr["ScopeTypeID"]); + this.ScopeType = Null.SetNullString(dr["ScopeType"]); + } + public override string ToString() { - return ScopeType; + return this.ScopeType; } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs index 1480111c71c..c59a0cf440e 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs @@ -1,63 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// ScopeTypeController provides the business layer of ScopeType. - /// - /// + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Data; + + /// + /// ScopeTypeController provides the business layer of ScopeType. + /// + /// public class ScopeTypeController : IScopeTypeController { + private const int _CacheTimeOut = 20; private readonly IDataService _DataService; - private const int _CacheTimeOut = 20; - - #region "Constructors" - - public ScopeTypeController() : this(Util.GetDataService()) + + public ScopeTypeController() + : this(Util.GetDataService()) { } public ScopeTypeController(IDataService dataService) { - _DataService = dataService; - } - - #endregion - - #region "Private Methods" - - private object GetScopeTypesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillQueryable(_DataService.GetScopeTypes()).ToList(); - } - - #endregion - - #region "Public Methods" - + this._DataService = dataService; + } + public int AddScopeType(ScopeType scopeType) { - //Argument Contract + // Argument Contract Requires.NotNull("scopeType", scopeType); Requires.PropertyNotNullOrEmpty("scopeType", "ScopeType", scopeType.ScopeType); - scopeType.ScopeTypeId = _DataService.AddScopeType(scopeType); + scopeType.ScopeTypeId = this._DataService.AddScopeType(scopeType); - //Refresh cached collection of types + // Refresh cached collection of types DataCache.RemoveCache(DataCache.ScopeTypesCacheKey); return scopeType.ScopeTypeId; @@ -67,37 +48,40 @@ public void ClearScopeTypeCache() { DataCache.RemoveCache(DataCache.ScopeTypesCacheKey); } + + private object GetScopeTypesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillQueryable(this._DataService.GetScopeTypes()).ToList(); + } public void DeleteScopeType(ScopeType scopeType) { - //Argument Contract + // Argument Contract Requires.NotNull("scopeType", scopeType); Requires.PropertyNotNegative("scopeType", "ScopeTypeId", scopeType.ScopeTypeId); - _DataService.DeleteScopeType(scopeType); + this._DataService.DeleteScopeType(scopeType); - //Refresh cached collection of types + // Refresh cached collection of types DataCache.RemoveCache(DataCache.ScopeTypesCacheKey); } public IQueryable GetScopeTypes() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.ScopeTypesCacheKey, _CacheTimeOut), GetScopeTypesCallBack).AsQueryable(); + return CBO.GetCachedObject>(new CacheItemArgs(DataCache.ScopeTypesCacheKey, _CacheTimeOut), this.GetScopeTypesCallBack).AsQueryable(); } public void UpdateScopeType(ScopeType scopeType) { - //Argument Contract + // Argument Contract Requires.NotNull("scopeType", scopeType); Requires.PropertyNotNegative("scopeType", "ScopeTypeId", scopeType.ScopeTypeId); Requires.PropertyNotNullOrEmpty("scopeType", "ScopeType", scopeType.ScopeType); - _DataService.UpdateScopeType(scopeType); + this._DataService.UpdateScopeType(scopeType); - //Refresh cached collection of types + // Refresh cached collection of types DataCache.RemoveCache(DataCache.ScopeTypesCacheKey); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs index 4b2783b91d1..2cb5d74112f 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs @@ -1,55 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Web; -using System.Web.Script.Serialization; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// Major class of Taxonomy. - /// - /// - /// - /// Taxonomy is defined as “the practice and science of classification” – Wikipedia, - /// while Folksonomy is defined as “collaborative tagging” – Wikipedia. - /// Usually, taxonomy refers to the practice of using hierarchical categories applied to the content by a “content editor”, - /// while folksonomy refers to the practice of free-form tagging of content by users. - /// In DotNetNuke, while we expose both of these at the presentation layer, in the API and Data Layer they are implemented - /// using a common data structure. - /// - /// - /// There are a number of advantages of using a special System Vocabulary for storing user entered tags. - /// One is that both taxonomy terms and folksonomy tags are treated in the API and Data Layer in the same way. - /// This means that we only have to manage one relationship between content and terms rather than two separate relationships. - /// The second benefit of treating tags in this way is that an admin can “manage” the tags – ie remove any offensive or inappropriate tags, - /// or correct spellings of tags, by using the Taxonomy Manager UI. - /// - /// - /// - /// - /// internal static List<Term> GetTerms(this Vocabulary voc, int vocabularyId) - /// { - /// ITermController ctl = Util.GetTermController(); - /// return ctl.GetTermsByVocabulary(vocabularyId).ToList(); - /// } - /// - /// + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Web; + using System.Web.Script.Serialization; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + + /// + /// Major class of Taxonomy. + /// + /// + /// + /// Taxonomy is defined as “the practice and science of classification” – Wikipedia, + /// while Folksonomy is defined as “collaborative tagging” – Wikipedia. + /// Usually, taxonomy refers to the practice of using hierarchical categories applied to the content by a “content editor”, + /// while folksonomy refers to the practice of free-form tagging of content by users. + /// In DotNetNuke, while we expose both of these at the presentation layer, in the API and Data Layer they are implemented + /// using a common data structure. + /// + /// + /// There are a number of advantages of using a special System Vocabulary for storing user entered tags. + /// One is that both taxonomy terms and folksonomy tags are treated in the API and Data Layer in the same way. + /// This means that we only have to manage one relationship between content and terms rather than two separate relationships. + /// The second benefit of treating tags in this way is that an admin can “manage” the tags – ie remove any offensive or inappropriate tags, + /// or correct spellings of tags, by using the Taxonomy Manager UI. + /// + /// + /// + /// + /// internal static List<Term> GetTerms(this Vocabulary voc, int vocabularyId) + /// { + /// ITermController ctl = Util.GetTermController(); + /// return ctl.GetTermsByVocabulary(vocabularyId).ToList(); + /// } + /// + /// [Serializable] public class Term : BaseEntityInfo, IHydratable { @@ -61,58 +56,57 @@ public class Term : BaseEntityInfo, IHydratable private string _name; private int? _parentTermId; private int _right; - private readonly List _synonyms = new List(); + private readonly List _synonyms = new List(); private int _termId; private Vocabulary _vocabulary; private int _vocabularyId; - private int _weight; - - #region "Constructors" - - public Term() : this(Null.NullString, Null.NullString, Null.NullInteger) + private int _weight; + + public Term() + : this(Null.NullString, Null.NullString, Null.NullInteger) { } - public Term(int vocabularyId) : this(Null.NullString, Null.NullString, vocabularyId) + public Term(int vocabularyId) + : this(Null.NullString, Null.NullString, vocabularyId) { } - public Term(string name) : this(name, Null.NullString, Null.NullInteger) + public Term(string name) + : this(name, Null.NullString, Null.NullInteger) { } - public Term(string name, string description) : this(name, description, Null.NullInteger) + public Term(string name, string description) + : this(name, description, Null.NullInteger) { } public Term(string name, string description, int vocabularyId) { - Description = description; - Name = name; - _vocabularyId = vocabularyId; - - ParentTermId = null; - TermId = Null.NullInteger; - _left = 0; - _right = 0; - Weight = 0; - } - - #endregion - - #region "Public Properties" - + this.Description = description; + this.Name = name; + this._vocabularyId = vocabularyId; + + this.ParentTermId = null; + this.TermId = Null.NullInteger; + this._left = 0; + this._right = 0; + this.Weight = 0; + } + [XmlIgnore] [ScriptIgnore] public List ChildTerms { get { - if (_childTerms == null) + if (this._childTerms == null) { - _childTerms = this.GetChildTerms(_termId, _vocabularyId); + this._childTerms = this.GetChildTerms(this._termId, this._vocabularyId); } - return _childTerms; + + return this._childTerms; } } @@ -122,11 +116,12 @@ public string Description { get { - return _description; + return this._description; } + set { - _description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + this._description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } @@ -136,7 +131,7 @@ public bool IsHeirarchical { get { - return (Vocabulary.Type == VocabularyType.Hierarchy); + return this.Vocabulary.Type == VocabularyType.Hierarchy; } } @@ -146,7 +141,7 @@ public int Left { get { - return _left; + return this._left; } } @@ -156,15 +151,22 @@ public string Name { get { - return _name; + return this._name; } + set { - if (HtmlUtils.IsUrlEncoded(value)) - value = System.Net.WebUtility.UrlDecode(value); - if (HtmlUtils.ContainsEntity(value)) - value = System.Net.WebUtility.HtmlDecode(value); - _name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + if (HtmlUtils.IsUrlEncoded(value)) + { + value = System.Net.WebUtility.UrlDecode(value); + } + + if (HtmlUtils.ContainsEntity(value)) + { + value = System.Net.WebUtility.HtmlDecode(value); + } + + this._name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } @@ -174,11 +176,12 @@ public int? ParentTermId { get { - return _parentTermId; + return this._parentTermId; } + set { - _parentTermId = value; + this._parentTermId = value; } } @@ -188,7 +191,7 @@ public int Right { get { - return _right; + return this._right; } } @@ -198,7 +201,7 @@ public List Synonyms { get { - return _synonyms; + return this._synonyms; } } @@ -208,11 +211,12 @@ public int TermId { get { - return _termId; + return this._termId; } + set { - _termId = value; + this._termId = value; } } @@ -222,11 +226,12 @@ public Vocabulary Vocabulary { get { - if (_vocabulary == null && _vocabularyId > Null.NullInteger) + if (this._vocabulary == null && this._vocabularyId > Null.NullInteger) { - _vocabulary = this.GetVocabulary(_vocabularyId); + this._vocabulary = this.GetVocabulary(this._vocabularyId); } - return _vocabulary; + + return this._vocabulary; } } @@ -236,7 +241,7 @@ public int VocabularyId { get { - return _vocabularyId; + return this._vocabularyId; } } @@ -246,72 +251,71 @@ public int Weight { get { - return _weight; + return this._weight; } + set { - _weight = value; + this._weight = value; } - } - - #endregion - - #region "IHydratable Implementation" + } + public int KeyID + { + get + { + return this.TermId; + } + + set + { + this.TermId = value; + } + } + public virtual void Fill(IDataReader dr) { - TermId = Null.SetNullInteger(dr["TermID"]); - Name = Null.SetNullString(dr["Name"]); - Description = Null.SetNullString(dr["Description"]); - Weight = Null.SetNullInteger(dr["Weight"]); - _vocabularyId = Null.SetNullInteger(dr["VocabularyID"]); + this.TermId = Null.SetNullInteger(dr["TermID"]); + this.Name = Null.SetNullString(dr["Name"]); + this.Description = Null.SetNullString(dr["Description"]); + this.Weight = Null.SetNullInteger(dr["Weight"]); + this._vocabularyId = Null.SetNullInteger(dr["VocabularyID"]); if (dr["TermLeft"] != DBNull.Value) { - _left = Convert.ToInt32(dr["TermLeft"]); + this._left = Convert.ToInt32(dr["TermLeft"]); } + if (dr["TermRight"] != DBNull.Value) { - _right = Convert.ToInt32(dr["TermRight"]); + this._right = Convert.ToInt32(dr["TermRight"]); } + if (dr["ParentTermID"] != DBNull.Value) { - ParentTermId = Convert.ToInt32(dr["ParentTermID"]); + this.ParentTermId = Convert.ToInt32(dr["ParentTermID"]); } - //Fill base class properties - FillInternal(dr); + // Fill base class properties + this.FillInternal(dr); } - - public int KeyID - { - get - { - return TermId; - } - set - { - TermId = value; - } - } - - #endregion - + public string GetTermPath() { - string path = "\\\\" + Name; + string path = "\\\\" + this.Name; - if (ParentTermId.HasValue) + if (this.ParentTermId.HasValue) { ITermController ctl = Util.GetTermController(); - Term parentTerm = (from t in ctl.GetTermsByVocabulary(VocabularyId) where t.TermId == ParentTermId select t).SingleOrDefault(); + Term parentTerm = (from t in ctl.GetTermsByVocabulary(this.VocabularyId) where t.TermId == this.ParentTermId select t).SingleOrDefault(); if (parentTerm != null) { path = parentTerm.GetTermPath() + path; } } + return path; } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs index da0627620fb..7111fc64d7b 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs @@ -1,261 +1,245 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Caching; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// The Main Business layer of Taxonomy. - /// - /// - /// - /// internal static List<Term> GetTerms(this Vocabulary voc, int vocabularyId) - /// { - /// ITermController ctl = Util.GetTermController(); - /// return ctl.GetTermsByVocabulary(vocabularyId).ToList(); - /// } - /// - /// + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Users; + + /// + /// The Main Business layer of Taxonomy. + /// + /// + /// + /// internal static List<Term> GetTerms(this Vocabulary voc, int vocabularyId) + /// { + /// ITermController ctl = Util.GetTermController(); + /// return ctl.GetTermsByVocabulary(vocabularyId).ToList(); + /// } + /// + /// public class TermController : ITermController { - private readonly IDataService _DataService; private const CacheItemPriority _CachePriority = CacheItemPriority.Normal; - private const int _CacheTimeOut = 20; - - #region Constructors - - public TermController() : this(Util.GetDataService()) + private const int _CacheTimeOut = 20; + private readonly IDataService _DataService; + + public TermController() + : this(Util.GetDataService()) { } public TermController(IDataService dataService) { - _DataService = dataService; - } - - #endregion - - #region Private Methods - - private object GetTermsCallBack(CacheItemArgs cacheItemArgs) - { - var vocabularyId = (int) cacheItemArgs.ParamList[0]; - return CBO.FillQueryable(_DataService.GetTermsByVocabulary(vocabularyId)).ToList(); - } - - #endregion - - #region Public Methods - - /// - /// Adds the term. - /// - /// The term. - /// term id. - /// term is null. - /// term.VocabularyId is less than 0. - /// term.Name is empty. + this._DataService = dataService; + } + + /// + /// Adds the term. + /// + /// The term. + /// term id. + /// term is null. + /// term.VocabularyId is less than 0. + /// term.Name is empty. public int AddTerm(Term term) { - //Argument Contract + // Argument Contract Requires.NotNull("term", term); Requires.PropertyNotNegative("term", "VocabularyId", term.VocabularyId); Requires.PropertyNotNullOrEmpty("term", "Name", term.Name); - term.Name = HttpUtility.HtmlEncode(term.Name); - - if ((term.IsHeirarchical)) + term.Name = HttpUtility.HtmlEncode(term.Name); + + if (term.IsHeirarchical) { - term.TermId = _DataService.AddHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); + term.TermId = this._DataService.AddHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); } else { - term.TermId = _DataService.AddSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); + term.TermId = this._DataService.AddSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); } - //Clear Cache + // Clear Cache DataCache.RemoveCache(string.Format(DataCache.TermCacheKey, term.VocabularyId)); return term.TermId; } - /// - /// Adds the content of the term to. - /// - /// The term. - /// The content item. - /// term is null. - /// content item is null. + /// + /// Adds the content of the term to. + /// + /// The term. + /// The content item. + /// term is null. + /// content item is null. public void AddTermToContent(Term term, ContentItem contentItem) { - //Argument Contract + // Argument Contract Requires.NotNull("term", term); Requires.NotNull("contentItem", contentItem); - _DataService.AddTermToContent(term, contentItem); + this._DataService.AddTermToContent(term, contentItem); } + + private object GetTermsCallBack(CacheItemArgs cacheItemArgs) + { + var vocabularyId = (int)cacheItemArgs.ParamList[0]; + return CBO.FillQueryable(this._DataService.GetTermsByVocabulary(vocabularyId)).ToList(); + } - /// - /// Deletes the term. - /// - /// The term. - /// term is null. - /// term.TermId is less than 0. + /// + /// Deletes the term. + /// + /// The term. + /// term is null. + /// term.TermId is less than 0. public void DeleteTerm(Term term) { - //Argument Contract + // Argument Contract Requires.NotNull("term", term); Requires.PropertyNotNegative("term", "TermId", term.TermId); - if ((term.IsHeirarchical)) + if (term.IsHeirarchical) { - _DataService.DeleteHeirarchicalTerm(term); + this._DataService.DeleteHeirarchicalTerm(term); } else { - _DataService.DeleteSimpleTerm(term); + this._DataService.DeleteSimpleTerm(term); } - //Clear Cache + // Clear Cache DataCache.RemoveCache(string.Format(DataCache.TermCacheKey, term.VocabularyId)); } - /// - /// Gets the term. - /// - /// The term id. - /// specific term. - /// termId is less than 0. + /// + /// Gets the term. + /// + /// The term id. + /// specific term. + /// termId is less than 0. public Term GetTerm(int termId) { - //Argument Contract + // Argument Contract Requires.NotNegative("termId", termId); - return CBO.FillObject(_DataService.GetTerm(termId)); + return CBO.FillObject(this._DataService.GetTerm(termId)); } - - + /// /// Retrieve usage data for the specified term ID. /// - /// Term ID in question + /// Term ID in question. + /// public TermUsage GetTermUsage(int termId) { Requires.NotNegative("termId", termId); - return CBO.FillObject(_DataService.GetTermUsage(termId)); + return CBO.FillObject(this._DataService.GetTermUsage(termId)); } - /// - /// Gets the content of the terms by content item id. - /// - /// The content item id. - /// term collection - /// ContentItemId is less than 0. + /// + /// Gets the content of the terms by content item id. + /// + /// The content item id. + /// term collection. + /// ContentItemId is less than 0. public IQueryable GetTermsByContent(int contentItemId) { - //Argument Contract + // Argument Contract Requires.NotNegative("contentItemId", contentItemId); - return CBO.FillQueryable(_DataService.GetTermsByContent(contentItemId)); + return CBO.FillQueryable(this._DataService.GetTermsByContent(contentItemId)); } - /// - /// Gets the terms by vocabulary id. - /// - /// The vocabulary id. - /// term collection - /// vocabularyId is less than 0. + /// + /// Gets the terms by vocabulary id. + /// + /// The vocabulary id. + /// term collection. + /// vocabularyId is less than 0. public IQueryable GetTermsByVocabulary(int vocabularyId) { - //Argument Contract + // Argument Contract Requires.NotNegative("vocabularyId", vocabularyId); - return CBO.GetCachedObject>(new CacheItemArgs(string.Format(DataCache.TermCacheKey, vocabularyId), _CacheTimeOut, _CachePriority, vocabularyId), GetTermsCallBack).AsQueryable(); + return CBO.GetCachedObject>(new CacheItemArgs(string.Format(DataCache.TermCacheKey, vocabularyId), _CacheTimeOut, _CachePriority, vocabularyId), this.GetTermsCallBack).AsQueryable(); } - /// - /// Gets the terms by vocabulary name. - /// - /// Name of the vocabulary. - /// term collection - /// vocabularyName is empty. + /// + /// Gets the terms by vocabulary name. + /// + /// Name of the vocabulary. + /// term collection. + /// vocabularyName is empty. public IQueryable GetTermsByVocabulary(string vocabularyName) { - //Argument Contract + // Argument Contract Requires.NotNullOrEmpty("vocabularyName", vocabularyName); IVocabularyController vocabularyController = Util.GetVocabularyController(); - Vocabulary vocabulary = (vocabularyController.GetVocabularies() - .Cast().Where(v => v.Name == vocabularyName)) + Vocabulary vocabulary = vocabularyController.GetVocabularies() + .Cast().Where(v => v.Name == vocabularyName) .SingleOrDefault(); - + if (vocabulary == null) { throw new ArgumentException("Vocabulary does not exist.", "vocabularyName"); } - return GetTermsByVocabulary(vocabulary.VocabularyId); + return this.GetTermsByVocabulary(vocabulary.VocabularyId); } - /// - /// Removes all terms from content item. - /// - /// The content item. - /// content item is null. - public void RemoveTermsFromContent(ContentItem contentItem) + /// + /// Removes all terms from content item. + /// + /// The content item. + /// content item is null. + public void RemoveTermsFromContent(ContentItem contentItem) { - //Argument Contract + // Argument Contract Requires.NotNull("contentItem", contentItem); - _DataService.RemoveTermsFromContent(contentItem); + this._DataService.RemoveTermsFromContent(contentItem); } - /// - /// Updates the term. - /// - /// The term. - /// term is null. - /// term.TermId is less than 0. - /// term.VocabularyId is less than 0. - /// term.Name is empty. + /// + /// Updates the term. + /// + /// The term. + /// term is null. + /// term.TermId is less than 0. + /// term.VocabularyId is less than 0. + /// term.Name is empty. public void UpdateTerm(Term term) { - //Argument Contract + // Argument Contract Requires.NotNull("term", term); Requires.PropertyNotNegative("term", "TermId", term.TermId); Requires.PropertyNotNegative("term", "Vocabulary.VocabularyId", term.VocabularyId); Requires.PropertyNotNullOrEmpty("term", "Name", term.Name); - if ((term.IsHeirarchical)) + if (term.IsHeirarchical) { - _DataService.UpdateHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); + this._DataService.UpdateHeirarchicalTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); } else { - _DataService.UpdateSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); + this._DataService.UpdateSimpleTerm(term, UserController.Instance.GetCurrentUserInfo().UserID); } - //Clear Cache + // Clear Cache DataCache.RemoveCache(string.Format(DataCache.TermCacheKey, term.VocabularyId)); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermHelper.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermHelper.cs index 6ee159bb634..dc7e27a6b72 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermHelper.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermHelper.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Taxonomy { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + public class TermHelper { public const string PageTagsVocabulary = "PageTags"; @@ -26,9 +27,9 @@ public static List ToTabTerms(string pageSettingsTags, int tabPortalId) var termController = new TermController(); var vocabularyController = Util.GetVocabularyController(); - var vocabulary = (vocabularyController.GetVocabularies() + var vocabulary = vocabularyController.GetVocabularies() .Cast() - .Where(v => v.Name == PageTagsVocabulary && v.ScopeId == tabPortalId)) + .Where(v => v.Name == PageTagsVocabulary && v.ScopeId == tabPortalId) .SingleOrDefault(); var vocabularyId = Null.NullInteger; @@ -44,7 +45,7 @@ public static List ToTabTerms(string pageSettingsTags, int tabPortalId) new Vocabulary(PageTagsVocabulary, string.Empty, VocabularyType.Simple) { ScopeTypeId = scopeType.ScopeTypeId, - ScopeId = tabPortalId + ScopeId = tabPortalId, }); } else @@ -52,10 +53,10 @@ public static List ToTabTerms(string pageSettingsTags, int tabPortalId) vocabularyId = vocabulary.VocabularyId; } - //get all terms info + // get all terms info var allTerms = new List(); var vocabularies = from v in vocabularyController.GetVocabularies() - where (v.ScopeType.ScopeType == "Portal" && v.ScopeId == tabPortalId && !v.Name.Equals("Tags", StringComparison.OrdinalIgnoreCase)) + where v.ScopeType.ScopeType == "Portal" && v.ScopeId == tabPortalId && !v.Name.Equals("Tags", StringComparison.OrdinalIgnoreCase) select v; foreach (var v in vocabularies) { diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs index c4f78e973e8..8799294fb7e 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs @@ -1,36 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Taxonomy { public class TermUsage { - public int TotalTermUsage { get; set; } - - public int MonthTermUsage { get; set; } - - public int WeekTermUsage { get; set; } - - public int DayTermUsage { get; set; } - - /// - /// parameterless constructor, so that it can be used in CBO. - /// - public TermUsage() - { - - } + /// + /// Initializes a new instance of the class. + /// parameterless constructor, so that it can be used in CBO. + /// + public TermUsage() + { + } internal TermUsage(int total, int month, int week, int day) { - TotalTermUsage = total; + this.TotalTermUsage = total; - MonthTermUsage = month; + this.MonthTermUsage = month; - WeekTermUsage = week; + this.WeekTermUsage = week; - DayTermUsage = day; + this.DayTermUsage = day; } + + public int TotalTermUsage { get; set; } + + public int MonthTermUsage { get; set; } + + public int WeekTermUsage { get; set; } + + public int DayTermUsage { get; set; } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs b/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs index a1e07b1c31c..9a03a6ffb25 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// Class of Vocabulary. - /// - /// + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + + /// + /// Class of Vocabulary. + /// + /// [Serializable] public class Vocabulary : BaseEntityInfo, IHydratable { @@ -36,51 +31,50 @@ public class Vocabulary : BaseEntityInfo, IHydratable private VocabularyType _Type; private int _VocabularyId; - private int _Weight; - - #region "Constructors" - - public Vocabulary() : this(Null.NullString, Null.NullString, VocabularyType.Simple) + private int _Weight; + + public Vocabulary() + : this(Null.NullString, Null.NullString, VocabularyType.Simple) { } - public Vocabulary(string name) : this(name, Null.NullString, VocabularyType.Simple) + public Vocabulary(string name) + : this(name, Null.NullString, VocabularyType.Simple) { } - public Vocabulary(string name, string description) : this(name, description, VocabularyType.Simple) + public Vocabulary(string name, string description) + : this(name, description, VocabularyType.Simple) { } - public Vocabulary(VocabularyType type) : this(Null.NullString, Null.NullString, type) + public Vocabulary(VocabularyType type) + : this(Null.NullString, Null.NullString, type) { } public Vocabulary(string name, string description, VocabularyType type) { - Description = description; - Name = name; - Type = type; - - ScopeId = Null.NullInteger; - ScopeTypeId = Null.NullInteger; - VocabularyId = Null.NullInteger; - Weight = 0; - } - - #endregion - - #region "Public Properties" + this.Description = description; + this.Name = name; + this.Type = type; + this.ScopeId = Null.NullInteger; + this.ScopeTypeId = Null.NullInteger; + this.VocabularyId = Null.NullInteger; + this.Weight = 0; + } + public string Description { get { - return _Description; + return this._Description; } + set { - _Description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + this._Description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } @@ -88,7 +82,7 @@ public bool IsHeirarchical { get { - return (Type == VocabularyType.Hierarchy); + return this.Type == VocabularyType.Hierarchy; } } @@ -96,11 +90,12 @@ public bool IsSystem { get { - return _IsSystem; + return this._IsSystem; } + set { - _IsSystem = value; + this._IsSystem = value; } } @@ -108,13 +103,17 @@ public string Name { get { - return _Name; + return this._Name; } + set { - if (HtmlUtils.ContainsEntity(value)) - value = System.Net.WebUtility.HtmlDecode(value); - _Name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + if (HtmlUtils.ContainsEntity(value)) + { + value = System.Net.WebUtility.HtmlDecode(value); + } + + this._Name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } @@ -122,11 +121,12 @@ public int ScopeId { get { - return _ScopeId; + return this._ScopeId; } + set { - _ScopeId = value; + this._ScopeId = value; } } @@ -134,12 +134,12 @@ public ScopeType ScopeType { get { - if (_ScopeType == null) + if (this._ScopeType == null) { - _ScopeType = this.GetScopeType(_ScopeTypeId); + this._ScopeType = this.GetScopeType(this._ScopeTypeId); } - return _ScopeType; + return this._ScopeType; } } @@ -147,11 +147,12 @@ public int ScopeTypeId { get { - return _ScopeTypeId; + return this._ScopeTypeId; } + set { - _ScopeTypeId = value; + this._ScopeTypeId = value; } } @@ -159,11 +160,12 @@ public List Terms { get { - if (_Terms == null) + if (this._Terms == null) { - _Terms = this.GetTerms(_VocabularyId); + this._Terms = this.GetTerms(this._VocabularyId); } - return _Terms; + + return this._Terms; } } @@ -171,11 +173,12 @@ public VocabularyType Type { get { - return _Type; + return this._Type; } + set { - _Type = value; + this._Type = value; } } @@ -183,11 +186,12 @@ public int VocabularyId { get { - return _VocabularyId; + return this._VocabularyId; } + set { - _VocabularyId = value; + this._VocabularyId = value; } } @@ -195,53 +199,50 @@ public int Weight { get { - return _Weight; + return this._Weight; } + set { - _Weight = value; + this._Weight = value; } - } - - #endregion - - #region "IHydratable Implementation" + } + public virtual int KeyID + { + get + { + return this.VocabularyId; + } + + set + { + this.VocabularyId = value; + } + } + public virtual void Fill(IDataReader dr) { - VocabularyId = Null.SetNullInteger(dr["VocabularyID"]); + this.VocabularyId = Null.SetNullInteger(dr["VocabularyID"]); switch (Convert.ToInt16(dr["VocabularyTypeID"])) { case 1: - Type = VocabularyType.Simple; + this.Type = VocabularyType.Simple; break; case 2: - Type = VocabularyType.Hierarchy; + this.Type = VocabularyType.Hierarchy; break; } - IsSystem = Null.SetNullBoolean(dr["IsSystem"]); - Name = Null.SetNullString(dr["Name"]); - Description = Null.SetNullString(dr["Description"]); - ScopeId = Null.SetNullInteger(dr["ScopeID"]); - ScopeTypeId = Null.SetNullInteger(dr["ScopeTypeID"]); - Weight = Null.SetNullInteger(dr["Weight"]); - - //Fill base class properties - FillInternal(dr); - } + + this.IsSystem = Null.SetNullBoolean(dr["IsSystem"]); + this.Name = Null.SetNullString(dr["Name"]); + this.Description = Null.SetNullString(dr["Description"]); + this.ScopeId = Null.SetNullInteger(dr["ScopeID"]); + this.ScopeTypeId = Null.SetNullInteger(dr["ScopeTypeID"]); + this.Weight = Null.SetNullInteger(dr["Weight"]); - public virtual int KeyID - { - get - { - return VocabularyId; - } - set - { - VocabularyId = value; - } + // Fill base class properties + this.FillInternal(dr); } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs index 59892b60645..ccc236cd91f 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs @@ -1,65 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// VocabularyController provides the business layer of Vocabulary and VocabularyType. - /// - /// + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Users; + + /// + /// VocabularyController provides the business layer of Vocabulary and VocabularyType. + /// + /// public class VocabularyController : IVocabularyController { + private const int _CacheTimeOut = 20; private readonly IDataService _DataService; - private const int _CacheTimeOut = 20; - - #region Constructors - - public VocabularyController() : this(Util.GetDataService()) + + public VocabularyController() + : this(Util.GetDataService()) { } public VocabularyController(IDataService dataService) { - _DataService = dataService; - } - - #endregion - - #region Private Methods - - private object GetVocabulariesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillQueryable(_DataService.GetVocabularies()).ToList(); - } - - #endregion - - #region Public Methods - + this._DataService = dataService; + } + public int AddVocabulary(Vocabulary vocabulary) { - //Argument Contract + // Argument Contract Requires.NotNull("vocabulary", vocabulary); Requires.PropertyNotNullOrEmpty("vocabulary", "Name", vocabulary.Name); Requires.PropertyNotNegative("vocabulary", "ScopeTypeId", vocabulary.ScopeTypeId); - vocabulary.VocabularyId = _DataService.AddVocabulary(vocabulary, UserController.Instance.GetCurrentUserInfo().UserID); + vocabulary.VocabularyId = this._DataService.AddVocabulary(vocabulary, UserController.Instance.GetCurrentUserInfo().UserID); - //Refresh Cache + // Refresh Cache DataCache.RemoveCache(DataCache.VocabularyCacheKey); return vocabulary.VocabularyId; @@ -69,37 +50,40 @@ public void ClearVocabularyCache() { DataCache.RemoveCache(DataCache.VocabularyCacheKey); } + + private object GetVocabulariesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillQueryable(this._DataService.GetVocabularies()).ToList(); + } public void DeleteVocabulary(Vocabulary vocabulary) { - //Argument Contract + // Argument Contract Requires.NotNull("vocabulary", vocabulary); Requires.PropertyNotNegative("vocabulary", "VocabularyId", vocabulary.VocabularyId); - _DataService.DeleteVocabulary(vocabulary); + this._DataService.DeleteVocabulary(vocabulary); - //Refresh Cache + // Refresh Cache DataCache.RemoveCache(DataCache.VocabularyCacheKey); } public IQueryable GetVocabularies() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.VocabularyCacheKey, _CacheTimeOut), GetVocabulariesCallBack).AsQueryable(); + return CBO.GetCachedObject>(new CacheItemArgs(DataCache.VocabularyCacheKey, _CacheTimeOut), this.GetVocabulariesCallBack).AsQueryable(); } public void UpdateVocabulary(Vocabulary vocabulary) { - //Argument Contract + // Argument Contract Requires.NotNull("vocabulary", vocabulary); Requires.PropertyNotNegative("vocabulary", "VocabularyId", vocabulary.VocabularyId); Requires.PropertyNotNullOrEmpty("vocabulary", "Name", vocabulary.Name); - //Refresh Cache + // Refresh Cache DataCache.RemoveCache(DataCache.VocabularyCacheKey); - _DataService.UpdateVocabulary(vocabulary, UserController.Instance.GetCurrentUserInfo().UserID); - } - - #endregion + this._DataService.UpdateVocabulary(vocabulary, UserController.Instance.GetCurrentUserInfo().UserID); + } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyType.cs b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyType.cs index b6fc6703a96..2ed7f8948b2 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyType.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyType.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Taxonomy { - /// - /// Enumeration of VocabularyType. - /// + /// + /// Enumeration of VocabularyType. + /// public enum VocabularyType { - /// - /// Simple Vocabulary - /// + /// + /// Simple Vocabulary + /// Simple = 1, - /// - /// The Vocabulary can have parent or child nodes. - /// - Hierarchy = 2 + + /// + /// The Vocabulary can have parent or child nodes. + /// + Hierarchy = 2, } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowAction.cs b/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowAction.cs index b1028bb7fbd..5468534156b 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowAction.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowAction.cs @@ -1,40 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Content.Workflow.Dto; -using DotNetNuke.Entities.Content.Workflow.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Actions { + using DotNetNuke.Entities.Content.Workflow.Dto; + using DotNetNuke.Entities.Content.Workflow.Entities; + /// /// This interface represents a point of extension that third party can implement to inject behavior on workflow action inside the Workflow Engine. /// i.e.: Discard State, Complete State, Discard Workflow, Complete Workflow - /// Third party can implement the interface for each one of the 4 actions and then register it using the + /// Third party can implement the interface for each one of the 4 actions and then register it using the . /// public interface IWorkflowAction { /// /// The method gets the action message that will be sent to notify the users depending on the type of action - /// i.e.: with action type Complete Workflow the action message represents the notification sent to the user that started the workflow + /// i.e.: with action type Complete Workflow the action message represents the notification sent to the user that started the workflow. /// - /// State transaction dto - /// Workflow state that represent the current state after the workflow action - /// Action message that the engine will use to send the notification + /// State transaction dto. + /// Workflow state that represent the current state after the workflow action. + /// Action message that the engine will use to send the notification. ActionMessage GetActionMessage(StateTransaction stateTransaction, WorkflowState currentState); /// /// This method implements some action on state changed. - /// i.e.: on Complete Workflow user can implement clear a cache or log some info + /// i.e.: on Complete Workflow user can implement clear a cache or log some info. /// - /// State transaction dto + /// State transaction dto. void DoActionOnStateChanged(StateTransaction stateTransaction); /// /// This method implements some action on state changed. /// i.e.: on Complete Workflow user can implement the publish of a pending content version. /// - /// State transaction dto + /// State transaction dto. void DoActionOnStateChanging(StateTransaction stateTransaction); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowActionManager.cs b/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowActionManager.cs index 1139d4bed98..39323fff0c8 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowActionManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Actions/IWorkflowActionManager.cs @@ -1,30 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Actions { + using System; + /// - /// This class is responsible to manage Workflow Actions + /// This class is responsible to manage Workflow Actions. /// public interface IWorkflowActionManager { /// - /// This method gets an instance of the IWorkflowAction associated to the content type and action type + /// This method gets an instance of the IWorkflowAction associated to the content type and action type. /// - /// Content Item Id - /// Action type - /// IWorkflowAction instance + /// Content Item Id. + /// Action type. + /// IWorkflowAction instance. IWorkflowAction GetWorkflowActionInstance(int contentTypeId, WorkflowActionTypes actionType); /// - /// This method registers a new workflow action + /// This method registers a new workflow action. /// - /// This method checks that the WorkflowAction Source implements the IWorkflowAction interface before register it - /// Workflow action entity - /// Thrown if the ActionSource does not implement the IWorkflowAction interface + /// This method checks that the WorkflowAction Source implements the IWorkflowAction interface before register it. + /// Workflow action entity. + /// Thrown if the ActionSource does not implement the IWorkflowAction interface. void RegisterWorkflowAction(WorkflowAction workflowAction); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowAction.cs b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowAction.cs index 6c39707ca71..018030b2f8c 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowAction.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowAction.cs @@ -1,36 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.ComponentModel.DataAnnotations; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Actions { + using DotNetNuke.ComponentModel.DataAnnotations; + /// - /// This entity represents a workflow action implementation + /// This entity represents a workflow action implementation. /// [PrimaryKey("ActionId")] [TableName("ContentWorkflowActions")] public class WorkflowAction { /// - /// Action Id + /// Gets or sets action Id. /// public int ActionId { get; set; } /// - /// Content item type Id + /// Gets or sets content item type Id. /// public int ContentTypeId { get; set; } /// - /// Action type. This is a string representation of the enum + /// Gets or sets action type. This is a string representation of the enum . /// public string ActionType { get; set; } /// - /// Action Source. This property represents the path to the class that implement the IWorkflowAction interface - /// i.e.: "MyProject.WorkflowActions.WorkflowDiscardction, MyProject" + /// Gets or sets action Source. This property represents the path to the class that implement the IWorkflowAction interface + /// i.e.: "MyProject.WorkflowActions.WorkflowDiscardction, MyProject". /// public string ActionSource { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs index 6f2f924e01e..92b47be73e9 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs @@ -1,31 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common; -using DotNetNuke.Entities.Content.Workflow.Repositories; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Actions { - public class WorkflowActionManager : ServiceLocator , IWorkflowActionManager - { - #region Members - private readonly IWorkflowActionRepository _workflowActionRepository; - #endregion - - #region Constructor + using System; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Content.Workflow.Repositories; + using DotNetNuke.Framework; + + public class WorkflowActionManager : ServiceLocator, IWorkflowActionManager + { + private readonly IWorkflowActionRepository _workflowActionRepository; + public WorkflowActionManager() { - _workflowActionRepository = WorkflowActionRepository.Instance; - } - #endregion - - #region Public Methods + this._workflowActionRepository = WorkflowActionRepository.Instance; + } + public IWorkflowAction GetWorkflowActionInstance(int contentTypeId, WorkflowActionTypes actionType) { - var action = _workflowActionRepository.GetWorkflowAction(contentTypeId, actionType.ToString()); + var action = this._workflowActionRepository.GetWorkflowAction(contentTypeId, actionType.ToString()); if (action == null) { return null; @@ -44,15 +40,12 @@ public void RegisterWorkflowAction(WorkflowAction workflowAction) throw new ArgumentException("The specified ActionSource does not implement the IWorkflowAction interface"); } - _workflowActionRepository.AddWorkflowAction(workflowAction); - } - #endregion - - #region Service Locator + this._workflowActionRepository.AddWorkflowAction(workflowAction); + } + protected override Func GetFactory() { return () => new WorkflowActionManager(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionTypes.cs b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionTypes.cs index 12b8f0285e6..ebbca8ab311 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionTypes.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionTypes.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Actions { /// - /// This enum represents the workflow action types + /// This enum represents the workflow action types. /// public enum WorkflowActionTypes { @@ -13,6 +13,6 @@ public enum WorkflowActionTypes CompleteWorkflow, DiscardState, CompleteState, - StartWorkflow + StartWorkflow, } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Dto/ActionMessage.cs b/DNN Platform/Library/Entities/Content/Workflow/Dto/ActionMessage.cs index ac4d3c170b5..b04110a9dda 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Dto/ActionMessage.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Dto/ActionMessage.cs @@ -1,27 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Dto { /// /// This dto class represents the message that will be sent as notification - /// of a specific action on the Workflow (Complete/Discard state, Complete/Discard workflow) + /// of a specific action on the Workflow (Complete/Discard state, Complete/Discard workflow). /// public class ActionMessage { /// - /// Subject of the message + /// Gets or sets subject of the message. /// public string Subject { get; set; } /// - /// Body of the message + /// Gets or sets body of the message. /// public string Body { get; set; } /// - /// Indicates if the message is going to be toasted or not. By default, it is False + /// Gets or sets a value indicating whether indicates if the message is going to be toasted or not. By default, it is False. /// public bool SendToast { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransaction.cs b/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransaction.cs index 9bedcd9adb0..01d087e99cc 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransaction.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransaction.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Dto { /// @@ -10,22 +10,22 @@ namespace DotNetNuke.Entities.Content.Workflow.Dto public class StateTransaction { /// - /// The content item id that represent the element that is going to change workflow state + /// Gets or sets the content item id that represent the element that is going to change workflow state. /// public int ContentItemId { get; set; } /// - /// The current state of the element + /// Gets or sets the current state of the element. /// public int CurrentStateId { get; set; } /// - /// This property represents the user that performs the state transaction + /// Gets or sets this property represents the user that performs the state transaction. /// public int UserId { get; set; } /// - /// This property represents the message attached to the state transaction + /// Gets or sets this property represents the message attached to the state transaction. /// public StateTransactionMessage Message { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransactionMessage.cs b/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransactionMessage.cs index 70d80217da6..48d9f9a76dc 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransactionMessage.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Dto/StateTransactionMessage.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Dto { /// - /// This class represents the message that will be notified on workflow state transaction + /// This class represents the message that will be notified on workflow state transaction. /// public class StateTransactionMessage { public StateTransactionMessage() { - Params = new string[]{}; + this.Params = new string[] { }; } /// - /// Params of the message + /// Gets or sets params of the message. /// public string[] Params { get; set; } /// - /// User comment + /// Gets or sets user comment. /// public string UserComment { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs index f02582a238e..bb9be995435 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using DotNetNuke.ComponentModel.DataAnnotations; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Entities { + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Linq; + + using DotNetNuke.ComponentModel.DataAnnotations; + /// - /// This entity represents a Workflow + /// This entity represents a Workflow. /// [PrimaryKey("WorkflowID")] [TableName("ContentWorkflows")] @@ -19,66 +20,66 @@ namespace DotNetNuke.Entities.Content.Workflow.Entities public class Workflow { /// - /// Workflow Id + /// Gets or sets workflow Id. /// public int WorkflowID { get; set; } /// - /// Portal Id + /// Gets or sets portal Id. /// public int PortalID { get; set; } /// - /// Workflow Name + /// Gets or sets workflow Name. /// [Required] [StringLength(40)] public string WorkflowName { get; set; } /// - /// Workflow Key. This property can be used to + /// Gets or sets workflow Key. This property can be used to. /// [StringLength(40)] public string WorkflowKey { get; set; } /// - /// Workflow Description + /// Gets or sets workflow Description. /// [StringLength(256)] public string Description { get; set; } /// - /// System workflow have a special behavior. It cannot be deleted and new states cannot be added + /// Gets a value indicating whether system workflow have a special behavior. It cannot be deleted and new states cannot be added. /// public bool IsSystem { get; internal set; } /// - /// Workflow states + /// Gets workflow states. /// [IgnoreColumn] public IEnumerable States { get; internal set; } /// - /// First workflow state + /// Gets first workflow state. /// [IgnoreColumn] public WorkflowState FirstState { get { - return States == null || !States.Any() ? null : States.OrderBy(s => s.Order).FirstOrDefault(); + return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).FirstOrDefault(); } } /// - /// Last workflow state + /// Gets last workflow state. /// [IgnoreColumn] public WorkflowState LastState { get { - return States == null || !States.Any() ? null : States.OrderBy(s => s.Order).LastOrDefault(); + return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).LastOrDefault(); } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLog.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLog.cs index d15102cafe4..7dcc8674db8 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLog.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLog.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.DataAnnotations; -using DotNetNuke.ComponentModel.DataAnnotations; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Entities { + using System; + using System.ComponentModel.DataAnnotations; + + using DotNetNuke.ComponentModel.DataAnnotations; + /// - /// This entity represents a Workflow Log + /// This entity represents a Workflow Log. /// [PrimaryKey("WorkflowLogID")] [TableName("ContentWorkflowLogs")] @@ -17,44 +18,44 @@ namespace DotNetNuke.Entities.Content.Workflow.Entities public class WorkflowLog { /// - /// Workflow log Id + /// Gets or sets workflow log Id. /// public int WorkflowLogID { get; set; } /// - /// Workflow associated to the log entry + /// Gets or sets workflow associated to the log entry. /// public int WorkflowID { get; set; } /// - /// Content Item associated to the log entry + /// Gets or sets content Item associated to the log entry. /// public int ContentItemID { get; set; } /// - /// Type ( enum) + /// Gets or sets type ( enum). /// public int Type { get; set; } /// - /// Action name (usually is a localized representation of the ContentWorkflowLogType) + /// Gets or sets action name (usually is a localized representation of the ContentWorkflowLogType). /// [StringLength(40)] public string Action { get; set; } /// - /// Comment + /// Gets or sets comment. /// [StringLength(256)] public string Comment { get; set; } /// - /// Log date + /// Gets or sets log date. /// public DateTime Date { get; set; } /// - /// User Id associated to the log + /// Gets or sets user Id associated to the log. /// public int User { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLogType.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLogType.cs index a221c85707d..c529be8214a 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLogType.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowLogType.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Entities { /// - /// This enum represents the possible list of WorkflowLogType + /// This enum represents the possible list of WorkflowLogType. /// public enum WorkflowLogType { @@ -17,6 +17,6 @@ public enum WorkflowLogType WorkflowApproved = 5, WorkflowDiscarded = 6, CommentProvided = 10, - WorkflowError = 500 + WorkflowError = 500, } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowState.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowState.cs index 0b1fd7554a2..d207fe9d5c3 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowState.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowState.cs @@ -1,55 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.DataAnnotations; -using DotNetNuke.ComponentModel.DataAnnotations; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Entities { + using System; + using System.ComponentModel.DataAnnotations; + + using DotNetNuke.ComponentModel.DataAnnotations; + /// - /// This entity represents a Workflow State + /// This entity represents a Workflow State. /// [PrimaryKey("StateID")] [TableName("ContentWorkflowStates")] [Serializable] - public class WorkflowState + public class WorkflowState { /// - /// State Id + /// Gets or sets state Id. /// public int StateID { get; set; } /// - /// Workflow associated to the state + /// Gets or sets workflow associated to the state. /// public int WorkflowID { get; set; } /// - /// State name + /// Gets or sets state name. /// [Required] [StringLength(40)] public string StateName { get; set; } /// - /// State Order + /// Gets state Order. /// - public int Order { get; internal set; } + public int Order { get; internal set; } /// - /// Indicates if the state is a system state. System states (i.e.: Draft, Published) have a special behavior. They cannot be deleted or moved. + /// Gets a value indicating whether indicates if the state is a system state. System states (i.e.: Draft, Published) have a special behavior. They cannot be deleted or moved. /// public bool IsSystem { get; internal set; } /// - /// If set to true the Workflow Engine will send system notification to the reviewer of the state when the workflow reach it + /// Gets or sets a value indicating whether if set to true the Workflow Engine will send system notification to the reviewer of the state when the workflow reach it. /// public bool SendNotification { get; set; } /// - /// If set to true the Workflow Engine will send system notification to administrators user when the workflow reach it + /// Gets or sets a value indicating whether if set to true the Workflow Engine will send system notification to administrators user when the workflow reach it. /// public bool SendNotificationToAdministrators { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs index a58e030ae16..9d657c682fc 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs @@ -1,23 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Entities { + using DotNetNuke.Security.Permissions; + /// - /// This entity represents a state permission + /// This entity represents a state permission. /// public class WorkflowStatePermission : PermissionInfoBase { /// - /// Workflow state permission Id + /// Gets or sets workflow state permission Id. /// public int WorkflowStatePermissionID { get; set; } /// - /// State Id + /// Gets or sets state Id. /// public int StateID { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowUsageItem.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowUsageItem.cs index 148038b8ae8..d12704d114e 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowUsageItem.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowUsageItem.cs @@ -1,29 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Entities { + using System; + /// - /// This entity represents an item which is using a Workflow + /// This entity represents an item which is using a Workflow. /// [Serializable] public class WorkflowUsageItem { /// - /// Workflow Id + /// Gets or sets workflow Id. /// public int WorkflowID { get; set; } /// - /// Name of the item + /// Gets or sets name of the item. /// public string ContentName { get; set; } /// - /// Type of the item + /// Gets or sets type of the item. /// public string ContentType { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowConcurrencyException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowConcurrencyException.cs index c080c502847..4100f77d256 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowConcurrencyException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowConcurrencyException.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Exceptions { + using DotNetNuke.Services.Localization; + public class WorkflowConcurrencyException : WorkflowException { public WorkflowConcurrencyException() : base(Localization.GetString("WorkflowConcurrencyException", Localization.ExceptionsResourceFile)) { - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowDoesNotExistException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowDoesNotExistException.cs index 9a685fbb7ff..79793c1e1eb 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowDoesNotExistException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowDoesNotExistException.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Exceptions { + using DotNetNuke.Services.Localization; + public class WorkflowDoesNotExistException : WorkflowException { public WorkflowDoesNotExistException() : base(Localization.GetString("WorkflowDoesNotExistException", Localization.ExceptionsResourceFile)) { - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs index c8bc2f85fce..a8b1166627d 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs @@ -1,26 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Exceptions { + using System; + public class WorkflowException : ApplicationException { public WorkflowException() { - } - public WorkflowException(string message) : base(message) + public WorkflowException(string message) + : base(message) { - } - public WorkflowException(string message, Exception innerException) : base(message, innerException) + public WorkflowException(string message, Exception innerException) + : base(message, innerException) { - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowInvalidOperationException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowInvalidOperationException.cs index 36e5fe01443..031d131afc2 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowInvalidOperationException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowInvalidOperationException.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Exceptions { public class WorkflowInvalidOperationException : WorkflowException @@ -9,12 +9,10 @@ public class WorkflowInvalidOperationException : WorkflowException public WorkflowInvalidOperationException(string message) : base(message) { - } public WorkflowInvalidOperationException() { - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowNameAlreadyExistsException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowNameAlreadyExistsException.cs index 0d873987e02..3416822f585 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowNameAlreadyExistsException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowNameAlreadyExistsException.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Exceptions { + using DotNetNuke.Services.Localization; + public class WorkflowNameAlreadyExistsException : WorkflowException { public WorkflowNameAlreadyExistsException() : base(Localization.GetString("WorkflowNameAlreadyExistsException", Localization.ExceptionsResourceFile)) { - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs index 15f56d49768..3e40c7c2334 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs @@ -1,12 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Exceptions { public class WorkflowSecurityException : WorkflowException { - public WorkflowSecurityException(string message): base(message) - { } + public WorkflowSecurityException(string message) + : base(message) + { + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowStateNameAlreadyExistsException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowStateNameAlreadyExistsException.cs index 9c933b9dc94..e7f3480b426 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowStateNameAlreadyExistsException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowStateNameAlreadyExistsException.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Exceptions { + using DotNetNuke.Services.Localization; + public class WorkflowStateNameAlreadyExistsException : WorkflowException { public WorkflowStateNameAlreadyExistsException() : base(Localization.GetString("WorkflowStateNameAlreadyExistsException", Localization.ExceptionsResourceFile)) { - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/ISystemWorkflowManager.cs b/DNN Platform/Library/Entities/Content/Workflow/ISystemWorkflowManager.cs index 1355a6f93f9..516b724a9f5 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/ISystemWorkflowManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/ISystemWorkflowManager.cs @@ -1,63 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Content.Workflow.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using DotNetNuke.Entities.Content.Workflow.Entities; + /// - /// This class is responsible to manage the system workflows of the portal. - /// It provides creation operation methods and methods to get specifically all system workflows + /// This class is responsible to manage the system workflows of the portal. + /// It provides creation operation methods and methods to get specifically all system workflows. /// public interface ISystemWorkflowManager { /// - /// Creates predefined system workflows + /// Creates predefined system workflows. /// - /// Portal Id where system workflows will be created + /// Portal Id where system workflows will be created. void CreateSystemWorkflows(int portalId); /// - /// Get the 'Direct Publish' system workflow of a specific portal + /// Get the 'Direct Publish' system workflow of a specific portal. /// - /// Portal Id - /// The 'Direct Publish' workflow + /// Portal Id. + /// The 'Direct Publish' workflow. Entities.Workflow GetDirectPublishWorkflow(int portalId); - + /// - /// Get the 'Save Draft' system workflow of a specific portal + /// Get the 'Save Draft' system workflow of a specific portal. /// - /// Portal Id - /// The 'Save Draft' workflow + /// Portal Id. + /// The 'Save Draft' workflow. Entities.Workflow GetSaveDraftWorkflow(int portalId); /// - /// Get the 'Content Approval' system workflow of a specific portal + /// Get the 'Content Approval' system workflow of a specific portal. /// - /// Portal Id - /// The 'Content Approval' workflow + /// Portal Id. + /// The 'Content Approval' workflow. Entities.Workflow GetContentApprovalWorkflow(int portalId); - + /// - /// Gets a default definition of the 'Draft' system state + /// Gets a default definition of the 'Draft' system state. /// - /// Order number to be included in the state definition - /// A 'Draft' state definition + /// Order number to be included in the state definition. + /// A 'Draft' state definition. WorkflowState GetDraftStateDefinition(int order); - + /// - /// Gets a default definition of the 'Published' system state + /// Gets a default definition of the 'Published' system state. /// - /// Order number to be included in the state definition - /// A 'Published' state definition + /// Order number to be included in the state definition. + /// A 'Published' state definition. WorkflowState GetPublishedStateDefinition(int order); /// - /// Gets a default definition of the 'Ready for review' system state + /// Gets a default definition of the 'Ready for review' system state. /// - /// Order number to be included in the state definition - /// A 'Ready for review' state definition + /// Order number to be included in the state definition. + /// A 'Ready for review' state definition. WorkflowState GetReadyForReviewStateDefinition(int order); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs index bd57556749a..daf30addc87 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs @@ -1,116 +1,115 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Content.Workflow.Dto; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System; + + using DotNetNuke.Entities.Content.Workflow.Dto; + using DotNetNuke.Entities.Users; + /// - /// This class represents the Workflow Engine. - /// It allows start, complete/discard and move forward and backward the workflow associated to a ContentItem + /// This class represents the Workflow Engine. + /// It allows start, complete/discard and move forward and backward the workflow associated to a ContentItem. /// public interface IWorkflowEngine { /// - /// This method starts a workflow for a Content Item + /// This method starts a workflow for a Content Item. /// - /// Workflow Id - /// Content item Id - /// User Id of the user that start the workflow - /// Thrown when start a workflow on a Content Item that already has a started workflow. - /// When workflowId param is negative + /// Workflow Id. + /// Content item Id. + /// User Id of the user that start the workflow. + /// Thrown when start a workflow on a Content Item that already has a started workflow. + /// When workflowId param is negative. void StartWorkflow(int workflowId, int contentItemId, int userId); /// /// This method completes a state moving the workflow forward to the next state. - /// If the next state is not the last one it send notifications to the reviewers of the next state, + /// If the next state is not the last one it send notifications to the reviewers of the next state, /// otherwise send the notification to the user that submit the draft in case the workflow complete. /// - /// State transaction Dto - /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto - /// Thrown when the user does not have review permission on the current state + /// State transaction Dto. + /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto. + /// Thrown when the user does not have review permission on the current state. void CompleteState(StateTransaction stateTransaction); /// /// This method discard a state moving the workflow backward to the previous state. - /// If the previous state is not the first one it send notifications to the reviewers of the previous state, + /// If the previous state is not the first one it send notifications to the reviewers of the previous state, /// otherwise send the notification to the user that submit the draft in case the workflow is in the draft state. /// - /// State transaction Dto - /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto - /// Thrown when the user does not have review permission on the current state - /// Thrown when trying to discard a workflow in the last state + /// State transaction Dto. + /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto. + /// Thrown when the user does not have review permission on the current state. + /// Thrown when trying to discard a workflow in the last state. void DiscardState(StateTransaction stateTransaction); /// - /// This method returns true if the workflow associated to the Content Item is completed (it is in the last state) + /// This method returns true if the workflow associated to the Content Item is completed (it is in the last state). /// - /// Content Item without workflow is considered as completed as well - /// Content item Id - /// True if the workflow is completed, false otherwise + /// Content Item without workflow is considered as completed as well. + /// Content item Id. + /// True if the workflow is completed, false otherwise. bool IsWorkflowCompleted(int contentItemId); /// - /// This method returns true if the workflow associated to the Content Item is completed (it is in the last state) + /// This method returns true if the workflow associated to the Content Item is completed (it is in the last state). /// - /// Content Item without workflow is considered as completed as well - /// Content item entity - /// True if the workflow is completed, false otherwise + /// Content Item without workflow is considered as completed as well. + /// Content item entity. + /// True if the workflow is completed, false otherwise. bool IsWorkflowCompleted(ContentItem contentItem); /// - /// This method returns true if the workflow associated to the Content Item is in draft (it is in the first state) + /// This method returns true if the workflow associated to the Content Item is in draft (it is in the first state). /// - /// Content Item without workflow is considered as not in draft - /// Content item Id - /// True if the workflow is in draft, false otherwise + /// Content Item without workflow is considered as not in draft. + /// Content item Id. + /// True if the workflow is in draft, false otherwise. bool IsWorkflowOnDraft(int contentItemId); /// - /// This method returns true if the workflow associated to the Content Item is in draft (it is in the first state) + /// This method returns true if the workflow associated to the Content Item is in draft (it is in the first state). /// - /// Content Item without workflow is considered as not in draft - /// Content item entity - /// True if the workflow is in draft, false otherwise + /// Content Item without workflow is considered as not in draft. + /// Content item entity. + /// True if the workflow is in draft, false otherwise. bool IsWorkflowOnDraft(ContentItem contentItem); /// /// This method discards the workflow no matter what is the current state. /// It also sends a system notification to the user that submit the workflow to let him know about the discard workflow action. /// - /// This method does not check review permission on the current state - /// State transaction Dto - /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto + /// This method does not check review permission on the current state. + /// State transaction Dto. + /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto. void DiscardWorkflow(StateTransaction stateTransaction); /// /// This method completes the workflow no matter what is the current state. /// It also sends a system notification to the user that submit the workflow to let him know about the complete workflow action. /// - /// This method does not check review permission on the current state - /// State transaction Dto - /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto + /// This method does not check review permission on the current state. + /// State transaction Dto. + /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto. void CompleteWorkflow(StateTransaction stateTransaction); - - + /// /// This method returns the user that started the workflow for the contentItem. /// /// If Content Item has no workflow, returns null. - /// ContentItem - /// User Info + /// ContentItem. + /// User Info. UserInfo GetStartedDraftStateUser(ContentItem contentItem); /// /// This method returns the user that submitted the contentItem. /// /// If Content Item has no workflow or the content has not submitted yet, returns null. - /// ContentItem - /// User Info + /// ContentItem. + /// User Info. UserInfo GetSubmittedDraftStateUser(ContentItem contentItem); - } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowLogger.cs b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowLogger.cs index b540ba488d9..4c329c30bac 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowLogger.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowLogger.cs @@ -1,43 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Content.Workflow.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System.Collections.Generic; + + using DotNetNuke.Entities.Content.Workflow.Entities; + /// - /// This class is responsible to manage the workflows logs. - /// It provides addition and get operation methods + /// This class is responsible to manage the workflows logs. + /// It provides addition and get operation methods. /// public interface IWorkflowLogger { /// - /// Adds a log comment regarding a specific workflow + /// Adds a log comment regarding a specific workflow. /// - /// Content item Id related with the log - /// Workflow Id owner of the log - /// Log Type - /// Comment to be added - /// User Id who adds the log + /// Content item Id related with the log. + /// Workflow Id owner of the log. + /// Log Type. + /// Comment to be added. + /// User Id who adds the log. void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string comment, int userId); /// - /// Adds a log comment regarding a specific workflow + /// Adds a log comment regarding a specific workflow. /// - /// Content item Id related with the log - /// Workflow Id owner of the log - /// Custom action related with the log - /// Comment to be added - /// User Id who adds the log + /// Content item Id related with the log. + /// Workflow Id owner of the log. + /// Custom action related with the log. + /// Comment to be added. + /// User Id who adds the log. void AddWorkflowLog(int contentItemId, int workflowId, string action, string comment, int userId); - + /// - /// Gets all logs regarding a specific workflow + /// Gets all logs regarding a specific workflow. /// - /// Content item Id related with the logs - /// Workflow Id owner of logs + /// Content item Id related with the logs. + /// Workflow Id owner of logs. /// IEnumerable GetWorkflowLogs(int contentItemId, int workflowId); } diff --git a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowManager.cs b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowManager.cs index d03547f0582..47e778bcf1b 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowManager.cs @@ -1,75 +1,75 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Content.Workflow.Entities; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System.Collections.Generic; + + using DotNetNuke.Entities.Content.Workflow.Entities; + /// - /// This class is responsible to manage the workflows of the portal. - /// It provides CRUD operation methods and methods to know the usage of the workflow + /// This class is responsible to manage the workflows of the portal. + /// It provides CRUD operation methods and methods to know the usage of the workflow. /// public interface IWorkflowManager { /// - /// This method returns the paginated list of Items that are associated with a workflow + /// This method returns the paginated list of Items that are associated with a workflow. /// - /// Workflow Id - /// Page index (where 1 is the index of the first page) - /// Page size - /// List of Usage Items + /// Workflow Id. + /// Page index (where 1 is the index of the first page). + /// Page size. + /// List of Usage Items. IEnumerable GetWorkflowUsage(int workflowId, int pageIndex, int pageSize); /// - /// This method returns the total number of Content Items that are associated with any State of a workflow (even the Published state) + /// This method returns the total number of Content Items that are associated with any State of a workflow (even the Published state). /// - /// Workflow Id - /// Total count of Content Items that are using the specified workflow + /// Workflow Id. + /// Total count of Content Items that are using the specified workflow. int GetWorkflowUsageCount(int workflowId); - + /// - /// This method return the list of the Workflows defined for the portal + /// This method return the list of the Workflows defined for the portal. /// - /// Portal Id - /// List of the Workflows for the portal + /// Portal Id. + /// List of the Workflows for the portal. IEnumerable GetWorkflows(int portalId); - + /// - /// This method adds a new workflow. It automatically add two system states: "Draft" and "Published" + /// This method adds a new workflow. It automatically add two system states: "Draft" and "Published". /// - /// Workflow Entity - /// Thrown when a workflow with the same name already exist for the portal + /// Workflow Entity. + /// Thrown when a workflow with the same name already exist for the portal. void AddWorkflow(Entities.Workflow workflow); /// /// this method update a existing workflow. /// - /// Workflow Entity - /// Thrown when a workflow with the same name already exist for the portal + /// Workflow Entity. + /// Thrown when a workflow with the same name already exist for the portal. void UpdateWorkflow(Entities.Workflow workflow); /// - /// This method hard deletes a workflow + /// This method hard deletes a workflow. /// - /// Workflow Entity - /// Thrown when a workflow is in use or is a system workflow + /// Workflow Entity. + /// Thrown when a workflow is in use or is a system workflow. void DeleteWorkflow(Entities.Workflow workflow); /// - /// This method returns a workflow entity by Id + /// This method returns a workflow entity by Id. /// - /// Workflow Id - /// Workflow Entity + /// Workflow Id. + /// Workflow Entity. Entities.Workflow GetWorkflow(int workflowId); /// /// This method returns a workflow entity by Content Item Id. It returns null if the Content Item is not under workflow. /// - /// Content Item - /// Workflow Entity + /// Content Item. + /// Workflow Entity. Entities.Workflow GetWorkflow(ContentItem contentItem); - } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowSecurity.cs b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowSecurity.cs index 850d034cc6d..8734edcf8eb 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowSecurity.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowSecurity.cs @@ -1,55 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + /// - /// This class is responsible of provide information around Workflow Review permission + /// This class is responsible of provide information around Workflow Review permission. /// public interface IWorkflowSecurity { /// - /// This method returns true if the user has review permission on the specified state + /// This method returns true if the user has review permission on the specified state. /// - /// Portal settings - /// User entity - /// State Id - /// True if the user has review permission, false otherwise + /// Portal settings. + /// User entity. + /// State Id. + /// True if the user has review permission, false otherwise. bool HasStateReviewerPermission(PortalSettings portalSettings, UserInfo user, int stateId); /// - /// This method returns true if the user has review permission on the specified state + /// This method returns true if the user has review permission on the specified state. /// - /// Portal Id - /// User Id - /// State Id - /// True if the user has review permission, false otherwise + /// Portal Id. + /// User Id. + /// State Id. + /// True if the user has review permission, false otherwise. bool HasStateReviewerPermission(int portalId, int userId, int stateId); /// - /// This method returns true if the current user has review permission on the specified state + /// This method returns true if the current user has review permission on the specified state. /// - /// State Id - /// True if the user has review permission, false otherwise + /// State Id. + /// True if the user has review permission, false otherwise. bool HasStateReviewerPermission(int stateId); /// - /// This method returns true if the user has review permission on at least one workflow state + /// This method returns true if the user has review permission on at least one workflow state. /// - /// Workflow Id - /// User Id - /// True if the user has review permission on at least on workflow state, false otherwise + /// Workflow Id. + /// User Id. + /// True if the user has review permission on at least on workflow state, false otherwise. bool IsWorkflowReviewer(int workflowId, int userId); /// - /// This method gets the PermissionInfo of the State Review permission + /// This method gets the PermissionInfo of the State Review permission. /// - /// PermissionInfo of the State Review permission + /// PermissionInfo of the State Review permission. PermissionInfo GetStateReviewPermission(); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowStateManager.cs b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowStateManager.cs index 4eaeaed7884..7556a16886a 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowStateManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowStateManager.cs @@ -1,112 +1,113 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Content.Workflow.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System.Collections.Generic; + + using DotNetNuke.Entities.Content.Workflow.Entities; + /// - /// This class is responsible to the management of the Workflow States + /// This class is responsible to the management of the Workflow States. /// public interface IWorkflowStateManager { /// - /// This method returns the list of States of a Workflow ordered by State Order ascending + /// This method returns the list of States of a Workflow ordered by State Order ascending. /// - /// Workflow Id - /// List of workflow States ordered by State Order ascending + /// Workflow Id. + /// List of workflow States ordered by State Order ascending. IEnumerable GetWorkflowStates(int workflowId); /// - /// This method returns the total number of Content Items that are associated with the State + /// This method returns the total number of Content Items that are associated with the State. /// - /// State Id - /// Total count of Content Items that are using the specified state + /// State Id. + /// Total count of Content Items that are using the specified state. int GetContentWorkflowStateUsageCount(int stateId); /// - /// This method returns a workflow State by Id + /// This method returns a workflow State by Id. /// - /// State Id - /// State entity + /// State Id. + /// State entity. WorkflowState GetWorkflowState(int stateId); /// - /// This method adds a new State to a workflow. The new state is always added as next to last state. + /// This method adds a new State to a workflow. The new state is always added as next to last state. /// /// This method also takes care on state reordering. - /// State entity - /// Thrown when adding a state to a workflow that does not exist - /// Thrown when adding a state to a system workflow - /// Thrown when already exist a state in the workflow with the same name + /// State entity. + /// Thrown when adding a state to a workflow that does not exist. + /// Thrown when adding a state to a system workflow. + /// Thrown when already exist a state in the workflow with the same name. void AddWorkflowState(WorkflowState state); /// /// This method updates a State. /// /// This method does not update the Order of the state. Use MoveWorkflowStateDown and MoveWorkflowStateUp for this operation. - /// State entity - /// Thrown when updating a state that does not exist - /// Thrown when already exist a state in the workflow with the same name + /// State entity. + /// Thrown when updating a state that does not exist. + /// Thrown when already exist a state in the workflow with the same name. void UpdateWorkflowState(WorkflowState state); /// - /// This method hard deletes a state + /// This method hard deletes a state. /// /// This method takes care of state reordering. - /// State entity - /// Thrown when deleting a system state workflow (i.e.: Draft, Published) or if the workflow state is beign used + /// State entity. + /// Thrown when deleting a system state workflow (i.e.: Draft, Published) or if the workflow state is beign used. void DeleteWorkflowState(WorkflowState state); /// - /// This method move the state down to 1 position in the workflow state order + /// This method move the state down to 1 position in the workflow state order. /// /// This method takes care of state reordering. - /// State Id - /// Thrown when moving a state that does not exist + /// State Id. + /// Thrown when moving a state that does not exist. /// Thrown when state cannot be moved (i.e.: is the first/last state, etc...) void MoveWorkflowStateDown(int stateId); /// - /// This method move the state up to 1 position in the workflow state order + /// This method move the state up to 1 position in the workflow state order. /// /// This method takes care of state reordering. - /// State Id - /// Thrown when moving a state that does not exist + /// State Id. + /// Thrown when moving a state that does not exist. /// Thrown when state cannot be moved (i.e.: is the first/last state, etc...) void MoveWorkflowStateUp(int stateId); /// - /// This method move the state up to index position in the workflow state order + /// This method move the state up to index position in the workflow state order. /// /// This method takes care of state reordering. - /// State Id + /// State Id. /// Index where the stateId will be moved. Since first and last states can't be moved, this index has to be a number between 1 and the number of states minus 2. - /// Thrown when moving a state that does not exist + /// Thrown when moving a state that does not exist. /// Thrown when state cannot be moved (i.e.: is the first/last state, etc...) - /// Thrown when index is not a valid value (index = 0 or index >= number of states - 2) + /// Thrown when index is not a valid value (index = 0 or index >= number of states - 2). void MoveState(int stateId, int index); - + /// - /// This method returns the list of State Permission of a specific state + /// This method returns the list of State Permission of a specific state. /// - /// State Id - /// List of state permissions + /// State Id. + /// List of state permissions. IEnumerable GetWorkflowStatePermissionByState(int stateId); /// - /// This method add a new workflow state permission + /// This method add a new workflow state permission. /// - /// Permission - /// User Id of the user that perform the action + /// Permission. + /// User Id of the user that perform the action. void AddWorkflowStatePermission(WorkflowStatePermission permission, int userId); /// - /// This method deletes a workflow state permission by Id + /// This method deletes a workflow state permission by Id. /// - /// Workflow state permission Id + /// Workflow state permission Id. void DeleteWorkflowStatePermission(int workflowStatePermissionId); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs index 514cd37cd5f..4f3fd42940a 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs @@ -1,36 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + using System.Collections.Generic; + /// - /// This entity represents a Workflow + /// This entity represents a Workflow. /// [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public class ContentWorkflow { /// - /// Workflow Id + /// Gets or sets workflow Id. /// public int WorkflowID { get; set; } /// - /// Portal Id + /// Gets or sets portal Id. /// public int PortalID { get; set; } /// - /// Workflow Name + /// Gets or sets workflow Name. /// public string WorkflowName { get; set; } - + /// - /// Workflow Description + /// Gets or sets workflow Description. /// public string Description { get; set; } @@ -43,9 +45,8 @@ public class ContentWorkflow public bool DispositionEnabled { get; set; } /// - /// Workflow states + /// Gets or sets workflow states. /// public IEnumerable States { get; set; } - } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs index aed3d111839..bec2699951e 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs @@ -1,63 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mail; -using DotNetNuke.Services.Social.Notifications; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.Social.Notifications; + [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public class ContentWorkflowController : ComponentBase, IContentWorkflowController { - private readonly ContentController contentController; private const string ContentWorkflowNotificationType = "ContentWorkflowNotification"; + private readonly ContentController contentController; private ContentWorkflowController() - { - contentController = new ContentController(); - } - - #region Public Methods - #region Obsolete Methods - - #region Engine - + { + this.contentController = new ContentController(); + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void DiscardWorkflow(int contentItemId, string comment, int portalId, int userId) { - var item = contentController.GetContentItem(contentItemId); - var workflow = GetWorkflow(item); - var stateId = GetLastWorkflowStateID(workflow); - AddWorkflowCommentLog(item, comment, userId); - AddWorkflowLog(item, ContentWorkflowLogType.WorkflowDiscarded, userId); - SetWorkflowState(stateId, item); + var item = this.contentController.GetContentItem(contentItemId); + var workflow = this.GetWorkflow(item); + var stateId = this.GetLastWorkflowStateID(workflow); + this.AddWorkflowCommentLog(item, comment, userId); + this.AddWorkflowLog(item, ContentWorkflowLogType.WorkflowDiscarded, userId); + this.SetWorkflowState(stateId, item); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void CompleteWorkflow(int contentItemId, string comment, int portalId, int userId) { - var item = contentController.GetContentItem(contentItemId); - var workflow = GetWorkflow(item); - var lastStateId = GetLastWorkflowStateID(workflow); - AddWorkflowCommentLog(item, comment, userId); - AddWorkflowLog(item, ContentWorkflowLogType.WorkflowApproved, userId); - SetWorkflowState(lastStateId, item); + var item = this.contentController.GetContentItem(contentItemId); + var workflow = this.GetWorkflow(item); + var lastStateId = this.GetLastWorkflowStateID(workflow); + this.AddWorkflowCommentLog(item, comment, userId); + this.AddWorkflowLog(item, ContentWorkflowLogType.WorkflowApproved, userId); + this.SetWorkflowState(lastStateId, item); } [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] @@ -65,12 +61,12 @@ public string ReplaceNotificationTokens(string text, ContentWorkflow workflow, C { var user = UserController.GetUserById(portalID, userID); var datetime = DateTime.Now; - var result = text.Replace("[USER]", user != null ? user.DisplayName : ""); + var result = text.Replace("[USER]", user != null ? user.DisplayName : string.Empty); result = result.Replace("[DATE]", datetime.ToString("d-MMM-yyyy hh:mm") + datetime.ToString("tt").ToLowerInvariant()); - result = result.Replace("[STATE]", state != null ? state.StateName : ""); - result = result.Replace("[WORKFLOW]", workflow != null ? workflow.WorkflowName : ""); - result = result.Replace("[CONTENT]", item != null ? item.ContentTitle : ""); - result = result.Replace("[COMMENT]", !String.IsNullOrEmpty(comment) ? comment : ""); + result = result.Replace("[STATE]", state != null ? state.StateName : string.Empty); + result = result.Replace("[WORKFLOW]", workflow != null ? workflow.WorkflowName : string.Empty); + result = result.Replace("[CONTENT]", item != null ? item.ContentTitle : string.Empty); + result = result.Replace("[COMMENT]", !string.IsNullOrEmpty(comment) ? comment : string.Empty); return result; } @@ -78,115 +74,127 @@ public string ReplaceNotificationTokens(string text, ContentWorkflow workflow, C [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public void CompleteState(int itemID, string subject, string body, string comment, int portalID, int userID) { - CompleteState(itemID, subject, body, comment, portalID, userID, string.Empty); + this.CompleteState(itemID, subject, body, comment, portalID, userID, string.Empty); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void StartWorkflow(int workflowID, int itemID, int userID) { - var item = contentController.GetContentItem(itemID); - var workflow = GetWorkflow(item); + var item = this.contentController.GetContentItem(itemID); + var workflow = this.GetWorkflow(item); - //If already exists a started workflow - if (workflow != null && !IsWorkflowCompleted(workflow, item)) + // If already exists a started workflow + if (workflow != null && !this.IsWorkflowCompleted(workflow, item)) { return; } + if (workflow == null || workflow.WorkflowID != workflowID) { - workflow = GetWorkflowByID(workflowID); + workflow = this.GetWorkflowByID(workflowID); } - //Delete previous logs + // Delete previous logs DataProvider.Instance().DeleteContentWorkflowLogs(itemID, workflowID); - var newStateID = GetFirstWorkflowStateID(workflow); - SetWorkflowState(newStateID, item); - AddWorkflowLog(item, ContentWorkflowLogType.WorkflowStarted, userID); - AddWorkflowLog(item, ContentWorkflowLogType.StateInitiated, userID); + var newStateID = this.GetFirstWorkflowStateID(workflow); + this.SetWorkflowState(newStateID, item); + this.AddWorkflowLog(item, ContentWorkflowLogType.WorkflowStarted, userID); + this.AddWorkflowLog(item, ContentWorkflowLogType.StateInitiated, userID); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void CompleteState(int itemID, string subject, string body, string comment, int portalID, int userID, string source, params string[] parameters) { - var item = contentController.GetContentItem(itemID); - var workflow = GetWorkflow(item); - if (workflow == null) - return; - - if (!IsWorkflowCompleted(workflow, item)) + var item = this.contentController.GetContentItem(itemID); + var workflow = this.GetWorkflow(item); + if (workflow == null) + { + return; + } + + if (!this.IsWorkflowCompleted(workflow, item)) { - var currentState = GetWorkflowStateByID(item.StateID); - if (!String.IsNullOrEmpty(comment)) + var currentState = this.GetWorkflowStateByID(item.StateID); + if (!string.IsNullOrEmpty(comment)) { - AddWorkflowCommentLog(item, comment, userID); + this.AddWorkflowCommentLog(item, comment, userID); } - AddWorkflowLog(item, currentState.StateID == GetFirstWorkflowStateID(workflow) ? ContentWorkflowLogType.DraftCompleted : ContentWorkflowLogType.StateCompleted, userID); + + this.AddWorkflowLog(item, currentState.StateID == this.GetFirstWorkflowStateID(workflow) ? ContentWorkflowLogType.DraftCompleted : ContentWorkflowLogType.StateCompleted, userID); - var endStateID = GetNextWorkflowStateID(workflow, item.StateID); - SetWorkflowState(endStateID, item); - if (endStateID == GetLastWorkflowStateID(workflow)) + var endStateID = this.GetNextWorkflowStateID(workflow, item.StateID); + this.SetWorkflowState(endStateID, item); + if (endStateID == this.GetLastWorkflowStateID(workflow)) { - AddWorkflowLog(item, ContentWorkflowLogType.WorkflowApproved, userID); + this.AddWorkflowLog(item, ContentWorkflowLogType.WorkflowApproved, userID); } else { - AddWorkflowLog(item, ContentWorkflowLogType.StateInitiated, userID); + this.AddWorkflowLog(item, ContentWorkflowLogType.StateInitiated, userID); } - SendNotification(new PortalSettings(portalID), workflow, item, currentState, subject, body, comment, endStateID, userID, source, parameters); + this.SendNotification(new PortalSettings(portalID), workflow, item, currentState, subject, body, comment, endStateID, userID, source, parameters); } } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void DiscardState(int itemID, string subject, string body, string comment, int portalID, int userID) { - var item = contentController.GetContentItem(itemID); - var workflow = GetWorkflow(item); - if (workflow == null) - return; - + var item = this.contentController.GetContentItem(itemID); + var workflow = this.GetWorkflow(item); + if (workflow == null) + { + return; + } - var currentState = GetWorkflowStateByID(item.StateID); - if ((GetFirstWorkflowStateID(workflow) != currentState.StateID) && (GetLastWorkflowStateID(workflow) != currentState.StateID)) + var currentState = this.GetWorkflowStateByID(item.StateID); + if ((this.GetFirstWorkflowStateID(workflow) != currentState.StateID) && (this.GetLastWorkflowStateID(workflow) != currentState.StateID)) { - if (!String.IsNullOrEmpty(comment)) + if (!string.IsNullOrEmpty(comment)) { - AddWorkflowCommentLog(item, comment, userID); + this.AddWorkflowCommentLog(item, comment, userID); } - AddWorkflowLog(item, ContentWorkflowLogType.StateDiscarded, userID); - int previousStateID = GetPreviousWorkflowStateID(workflow, item.StateID); - SetWorkflowState(previousStateID, item); - AddWorkflowLog(item, ContentWorkflowLogType.StateInitiated, userID); - SendNotification(new PortalSettings(portalID), workflow, item, currentState, subject, body, comment, previousStateID, userID, null, null); + + this.AddWorkflowLog(item, ContentWorkflowLogType.StateDiscarded, userID); + int previousStateID = this.GetPreviousWorkflowStateID(workflow, item.StateID); + this.SetWorkflowState(previousStateID, item); + this.AddWorkflowLog(item, ContentWorkflowLogType.StateInitiated, userID); + this.SendNotification(new PortalSettings(portalID), workflow, item, currentState, subject, body, comment, previousStateID, userID, null, null); } } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public bool IsWorkflowCompleted(int itemID) { - var item = contentController.GetContentItem(itemID); //Ensure DB values - var workflow = GetWorkflow(item); - if (workflow == null) return true; // If item has not workflow, then it is considered as completed - return IsWorkflowCompleted(workflow, item); + var item = this.contentController.GetContentItem(itemID); // Ensure DB values + var workflow = this.GetWorkflow(item); + if (workflow == null) + { + return true; // If item has not workflow, then it is considered as completed + } + + return this.IsWorkflowCompleted(workflow, item); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public bool IsWorkflowOnDraft(int itemID) { - var item = contentController.GetContentItem(itemID); //Ensure DB values - var workflow = GetWorkflow(item); - if (workflow == null) return false; // If item has not workflow, then it is not on Draft - return item.StateID == GetFirstWorkflowStateID(workflow); - } - #endregion - - #region Log + var item = this.contentController.GetContentItem(itemID); // Ensure DB values + var workflow = this.GetWorkflow(item); + if (workflow == null) + { + return false; // If item has not workflow, then it is not on Draft + } + + return item.StateID == this.GetFirstWorkflowStateID(workflow); + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger. Scheduled removal in v10.0.0.")] public void AddWorkflowLog(ContentItem item, string action, string comment, int userID) { - var workflow = GetWorkflow(item); + var workflow = this.GetWorkflow(item); - AddWorkflowLog(workflow != null ? workflow.WorkflowID : Null.NullInteger, item, action, comment, userID); + this.AddWorkflowLog(workflow != null ? workflow.WorkflowID : Null.NullInteger, item, action, comment, userID); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger. Scheduled removal in v10.0.0.")] @@ -199,10 +207,8 @@ public IEnumerable GetWorkflowLogs(int contentItemId, int wo public void DeleteWorkflowLogs(int contentItemID, int workflowID) { DataProvider.Instance().DeleteContentWorkflowLogs(contentItemID, workflowID); - } - #endregion - - #region State Permissions + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflowStatePermissionByState(int stateID) { @@ -212,35 +218,34 @@ public IEnumerable GetWorkflowStatePermissionByS [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void AddWorkflowStatePermission(ContentWorkflowStatePermission permission, int lastModifiedByUserID) { - DataProvider.Instance().AddContentWorkflowStatePermission(permission.StateID, - permission.PermissionID, - permission.RoleID, - permission.AllowAccess, - permission.UserID, - lastModifiedByUserID); + DataProvider.Instance().AddContentWorkflowStatePermission( + permission.StateID, + permission.PermissionID, + permission.RoleID, + permission.AllowAccess, + permission.UserID, + lastModifiedByUserID); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void UpdateWorkflowStatePermission(ContentWorkflowStatePermission permission, int lastModifiedByUserID) { - DataProvider.Instance().UpdateContentWorkflowStatePermission(permission.WorkflowStatePermissionID, - permission.StateID, - permission.PermissionID, - permission.RoleID, - permission.AllowAccess, - permission.UserID, - lastModifiedByUserID); + DataProvider.Instance().UpdateContentWorkflowStatePermission( + permission.WorkflowStatePermissionID, + permission.StateID, + permission.PermissionID, + permission.RoleID, + permission.AllowAccess, + permission.UserID, + lastModifiedByUserID); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void DeleteWorkflowStatePermission(int workflowStatePermissionID) { DataProvider.Instance().DeleteContentWorkflowStatePermission(workflowStatePermissionID); - } - #endregion - - #region State - + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public ContentWorkflowState GetWorkflowStateByID(int stateID) { @@ -250,45 +255,44 @@ public ContentWorkflowState GetWorkflowStateByID(int stateID) [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void AddWorkflowState(ContentWorkflowState state) { - var id = DataProvider.Instance().AddContentWorkflowState(state.WorkflowID, - state.StateName, - state.Order, - state.IsActive, - state.SendEmail, - state.SendMessage, - state.IsDisposalState, - state.OnCompleteMessageSubject, - state.OnCompleteMessageBody, - state.OnDiscardMessageSubject, - state.OnDiscardMessageBody); + var id = DataProvider.Instance().AddContentWorkflowState( + state.WorkflowID, + state.StateName, + state.Order, + state.IsActive, + state.SendEmail, + state.SendMessage, + state.IsDisposalState, + state.OnCompleteMessageSubject, + state.OnCompleteMessageBody, + state.OnDiscardMessageSubject, + state.OnDiscardMessageBody); state.StateID = id; } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void UpdateWorkflowState(ContentWorkflowState state) { - DataProvider.Instance().UpdateContentWorkflowState(state.StateID, - state.StateName, - state.Order, - state.IsActive, - state.SendEmail, - state.SendMessage, - state.IsDisposalState, - state.OnCompleteMessageSubject, - state.OnCompleteMessageBody, - state.OnDiscardMessageSubject, - state.OnDiscardMessageBody); + DataProvider.Instance().UpdateContentWorkflowState( + state.StateID, + state.StateName, + state.Order, + state.IsActive, + state.SendEmail, + state.SendMessage, + state.IsDisposalState, + state.OnCompleteMessageSubject, + state.OnCompleteMessageBody, + state.OnDiscardMessageSubject, + state.OnDiscardMessageBody); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflowStates(int workflowID) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflowStates(workflowID)); - } - #endregion - - #region Workflow - + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflows(int portalID) { @@ -298,9 +302,13 @@ public IEnumerable GetWorkflows(int portalID) [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public ContentWorkflow GetWorkflow(ContentItem item) { - var state = GetWorkflowStateByID(item.StateID); - if (state == null) return null; - return GetWorkflowByID(state.WorkflowID); + var state = this.GetWorkflowStateByID(item.StateID); + if (state == null) + { + return null; + } + + return this.GetWorkflowByID(state.WorkflowID); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] @@ -322,18 +330,17 @@ public ContentWorkflow GetWorkflowByID(int workflowID) var workflow = CBO.FillObject(DataProvider.Instance().GetContentWorkflow(workflowID)); if (workflow != null) { - workflow.States = GetWorkflowStates(workflowID); + workflow.States = this.GetWorkflowStates(workflowID); return workflow; } + return null; - } - #endregion - - #region Default Workflows + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead ISystemWorkflowManager. Scheduled removal in v10.0.0.")] public void CreateDefaultWorkflows(int portalId) { - if (GetWorkflows(portalId).Any(w => w.WorkflowName == Localization.GetString("DefaultWorkflowName"))) + if (this.GetWorkflows(portalId).Any(w => w.WorkflowName == Localization.GetString("DefaultWorkflowName"))) { return; } @@ -415,75 +422,71 @@ public void CreateDefaultWorkflows(int portalId) Localization.GetString( "DefaultWorkflowState3.OnDiscardMessageBody") } - } + }, }; - AddWorkflow(worflow); + this.AddWorkflow(worflow); foreach (var state in worflow.States) { state.WorkflowID = worflow.WorkflowID; - AddWorkflowState(state); + this.AddWorkflowState(state); } } [Obsolete("Deprecated in Platform 7.4.0. Use instead ISystemWorkflowManager. Scheduled removal in v10.0.0.")] public ContentWorkflow GetDefaultWorkflow(int portalID) { - var wf = GetWorkflows(portalID).First(); // We assume there is only 1 Workflow. This needs to be changed for other scenarios - wf.States = GetWorkflowStates(wf.WorkflowID); + var wf = this.GetWorkflows(portalID).First(); // We assume there is only 1 Workflow. This needs to be changed for other scenarios + wf.States = this.GetWorkflowStates(wf.WorkflowID); return wf; - } - #endregion - - #region Security Helpers + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsAnyReviewer(int workflowID) { - var workflow = GetWorkflowByID(workflowID); - return workflow.States.Any(contentWorkflowState => IsReviewer(contentWorkflowState.StateID)); + var workflow = this.GetWorkflowByID(workflowID); + return workflow.States.Any(contentWorkflowState => this.IsReviewer(contentWorkflowState.StateID)); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsAnyReviewer(int portalID, int userID, int workflowID) { - var workflow = GetWorkflowByID(workflowID); - return workflow.States.Any(contentWorkflowState => IsReviewer(portalID, userID, contentWorkflowState.StateID)); + var workflow = this.GetWorkflowByID(workflowID); + return workflow.States.Any(contentWorkflowState => this.IsReviewer(portalID, userID, contentWorkflowState.StateID)); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsReviewer(int stateID) { - var permissions = GetWorkflowStatePermissionByState(stateID); + var permissions = this.GetWorkflowStatePermissionByState(stateID); var user = UserController.Instance.GetCurrentUserInfo(); - return IsReviewer(user, PortalSettings.Current, permissions); + return this.IsReviewer(user, PortalSettings.Current, permissions); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsReviewer(int portalID, int userID, int stateID) { - var permissions = GetWorkflowStatePermissionByState(stateID); + var permissions = this.GetWorkflowStatePermissionByState(stateID); var user = UserController.GetUserById(portalID, userID); var portalSettings = new PortalSettings(portalID); - return IsReviewer(user, portalSettings, permissions); + return this.IsReviewer(user, portalSettings, permissions); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsCurrentReviewer(int portalID, int userID, int itemID) { - var item = contentController.GetContentItem(itemID); - return IsReviewer(portalID, userID, item.StateID); + var item = this.contentController.GetContentItem(itemID); + return this.IsReviewer(portalID, userID, item.StateID); } [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsCurrentReviewer(int itemID) { - var item = contentController.GetContentItem(itemID); - return IsReviewer(item.StateID); - } - #endregion - - + var item = this.contentController.GetContentItem(itemID); + return this.IsReviewer(item.StateID); + } + [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public ContentWorkflowSource GetWorkflowSource(int workflowId, string sourceName) { @@ -494,48 +497,70 @@ public ContentWorkflowSource GetWorkflowSource(int workflowId, string sourceName public void SendWorkflowNotification(bool sendEmail, bool sendMessage, PortalSettings settings, IEnumerable roles, IEnumerable users, string subject, string body, string comment, int userID) { - var replacedSubject = ReplaceNotificationTokens(subject, null, null, null, settings.PortalId, userID); - var replacedBody = ReplaceNotificationTokens(body, null, null, null, settings.PortalId, userID); - SendNotification(sendEmail, sendMessage, settings, roles, users, replacedSubject, replacedBody, comment, userID, null, null); + var replacedSubject = this.ReplaceNotificationTokens(subject, null, null, null, settings.PortalId, userID); + var replacedBody = this.ReplaceNotificationTokens(body, null, null, null, settings.PortalId, userID); + this.SendNotification(sendEmail, sendMessage, settings, roles, users, replacedSubject, replacedBody, comment, userID, null, null); + } + + private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) + { + return roles.Any(r => r.RoleName == settings.AdministratorRoleName); + } + + private static IEnumerable IncludeSuperUsers(ICollection users) + { + var superUsers = UserController.GetUsers(false, true, Null.NullInteger); + foreach (UserInfo superUser in superUsers) + { + if (IsSuperUserNotIncluded(users, superUser)) + { + users.Add(superUser); + } + } + + return users; } - #endregion - #endregion - #region Private Methods + private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo superUser) + { + return users.All(u => u.UserID != superUser.UserID); + } + private void AddWorkflowCommentLog(ContentItem item, string userComment, int userID) { - var workflow = GetWorkflow(item); + var workflow = this.GetWorkflow(item); - var logComment = ReplaceNotificationTokens(GetWorkflowActionComment(ContentWorkflowLogType.CommentProvided), workflow, item, workflow.States.FirstOrDefault(s => s.StateID == item.StateID), workflow.PortalID, userID, userComment); - AddWorkflowLog(workflow.WorkflowID, item, GetWorkflowActionText(ContentWorkflowLogType.CommentProvided), logComment, userID); + var logComment = this.ReplaceNotificationTokens(this.GetWorkflowActionComment(ContentWorkflowLogType.CommentProvided), workflow, item, workflow.States.FirstOrDefault(s => s.StateID == item.StateID), workflow.PortalID, userID, userComment); + this.AddWorkflowLog(workflow.WorkflowID, item, this.GetWorkflowActionText(ContentWorkflowLogType.CommentProvided), logComment, userID); } private void SendNotification(bool sendEmail, bool sendMessage, PortalSettings settings, IEnumerable roles, IEnumerable users, string subject, string body, string comment, int userID, string source, string[] parameters) { if (sendEmail) { - SendEmailNotifications(settings, roles, users, subject, body, comment); + this.SendEmailNotifications(settings, roles, users, subject, body, comment); } + if (sendMessage) { - SendMessageNotifications(settings, roles, users, subject, body, comment, userID, source, parameters); + this.SendMessageNotifications(settings, roles, users, subject, body, comment, userID, source, parameters); } } private void SendNotification(PortalSettings settings, ContentWorkflow workflow, ContentItem item, ContentWorkflowState state, string subject, string body, string comment, int destinationStateID, int actionUserID, string source, string[] parameters) { - var permissions = GetWorkflowStatePermissionByState(destinationStateID); - var users = GetUsersFromPermissions(settings, permissions); - var roles = GetRolesFromPermissions(settings, permissions); - var replacedSubject = ReplaceNotificationTokens(subject, workflow, item, GetWorkflowStateByID(destinationStateID), settings.PortalId, actionUserID); - var replacedBody = ReplaceNotificationTokens(body, workflow, item, GetWorkflowStateByID(destinationStateID), settings.PortalId, actionUserID); - - SendNotification(state.SendEmail, state.SendMessage, settings, roles, users, replacedSubject, replacedBody, comment, actionUserID, source, parameters); + var permissions = this.GetWorkflowStatePermissionByState(destinationStateID); + var users = this.GetUsersFromPermissions(settings, permissions); + var roles = this.GetRolesFromPermissions(settings, permissions); + var replacedSubject = this.ReplaceNotificationTokens(subject, workflow, item, this.GetWorkflowStateByID(destinationStateID), settings.PortalId, actionUserID); + var replacedBody = this.ReplaceNotificationTokens(body, workflow, item, this.GetWorkflowStateByID(destinationStateID), settings.PortalId, actionUserID); + + this.SendNotification(state.SendEmail, state.SendMessage, settings, roles, users, replacedSubject, replacedBody, comment, actionUserID, source, parameters); } private void SendMessageNotifications(PortalSettings settings, IEnumerable roles, IEnumerable users, string subject, string body, string comment, int actionUserID, string source, string[] parameters) { - var fullbody = GetFullBody(body, comment); + var fullbody = this.GetFullBody(body, comment); if (!roles.Any() && !users.Any()) { @@ -543,21 +568,22 @@ private void SendMessageNotifications(PortalSettings settings, IEnumerable 0) { source = string.Format("{0};{1}", source, string.Join(";", parameters)); } + notification.Context = source; } @@ -568,10 +594,10 @@ private string GetFullBody(string body, string comment) { return body + "

    " + comment; } - + private void SendEmailNotifications(PortalSettings settings, IEnumerable roles, IEnumerable users, string subject, string body, string comment) { - var fullbody = GetFullBody(body, comment); + var fullbody = this.GetFullBody(body, comment); var emailUsers = users.ToList(); foreach (var role in roles) { @@ -580,7 +606,7 @@ private void SendEmailNotifications(PortalSettings settings, IEnumerable u.Email).Distinct()) - { + { Mail.SendEmail(settings.Email, userMail, subject, fullbody); } } @@ -588,7 +614,7 @@ private void SendEmailNotifications(PortalSettings settings, IEnumerable GetRolesFromPermissions(PortalSettings settings, IEnumerable permissions) { var roles = new List(); - + foreach (var permission in permissions) { if (permission.AllowAccess && permission.RoleID > Null.NullInteger) @@ -597,19 +623,15 @@ private IEnumerable GetRolesFromPermissions(PortalSettings settings, I } } - if(!IsAdministratorRoleAlreadyIncluded(settings, roles)) + if (!IsAdministratorRoleAlreadyIncluded(settings, roles)) { var adminRole = RoleController.Instance.GetRoleByName(settings.PortalId, settings.AdministratorRoleName); roles.Add(adminRole); } + return roles; } - private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) - { - return roles.Any(r => r.RoleName == settings.AdministratorRoleName); - } - private IEnumerable GetUsersFromPermissions(PortalSettings settings, IEnumerable permissions) { var users = new List(); @@ -620,28 +642,10 @@ private IEnumerable GetUsersFromPermissions(PortalSettings settings, I users.Add(UserController.GetUserById(settings.PortalId, permission.UserID)); } } + return IncludeSuperUsers(users); } - private static IEnumerable IncludeSuperUsers(ICollection users) - { - var superUsers = UserController.GetUsers(false, true, Null.NullInteger); - foreach (UserInfo superUser in superUsers) - { - if(IsSuperUserNotIncluded(users, superUser)) - { - users.Add(superUser); - } - } - - return users; - } - - private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo superUser) - { - return users.All(u => u.UserID != superUser.UserID); - } - private bool IsReviewer(UserInfo user, PortalSettings settings, IEnumerable permissions) { var administratorRoleName = settings.AdministratorRoleName; @@ -650,11 +654,11 @@ private bool IsReviewer(UserInfo user, PortalSettings settings, IEnumerable s.StateID == item.StateID), workflow.PortalID, userID); + var comment = this.ReplaceNotificationTokens(this.GetWorkflowActionComment(logType), workflow, item, workflow.States.FirstOrDefault(s => s.StateID == item.StateID), workflow.PortalID, userID); - AddWorkflowLog(workflow.WorkflowID, item, GetWorkflowActionText(logType), comment, userID); + this.AddWorkflowLog(workflow.WorkflowID, item, this.GetWorkflowActionText(logType), comment, userID); } private void AddWorkflowLog(int workflowID, ContentItem item, string action, string comment, int userID) @@ -682,6 +686,7 @@ private int GetFirstWorkflowStateID(ContentWorkflow workflow) { intStateID = states.OrderBy(s => s.Order).FirstOrDefault().StateID; } + return intStateID; } @@ -693,6 +698,7 @@ private int GetLastWorkflowStateID(ContentWorkflow workflow) { intStateID = states.OrderBy(s => s.Order).LastOrDefault().StateID; } + return intStateID; } @@ -709,6 +715,7 @@ private int GetPreviousWorkflowStateID(ContentWorkflow workflow, int stateID) { intPreviousStateID = initState.StateID; } + for (int i = 0; i < states.Count(); i++) { if (states.ElementAt(i).StateID == stateID) @@ -717,6 +724,7 @@ private int GetPreviousWorkflowStateID(ContentWorkflow workflow, int stateID) intItem = i; } } + // get previous active state if (intPreviousStateID == stateID) { @@ -728,6 +736,7 @@ private int GetPreviousWorkflowStateID(ContentWorkflow workflow, int stateID) intPreviousStateID = states.ElementAt(intItem).StateID; break; } + intItem = intItem - 1; } } @@ -735,7 +744,7 @@ private int GetPreviousWorkflowStateID(ContentWorkflow workflow, int stateID) // if none found then reset to first state if (intPreviousStateID == -1) { - intPreviousStateID = GetFirstWorkflowStateID(workflow); + intPreviousStateID = this.GetFirstWorkflowStateID(workflow); } return intPreviousStateID; @@ -768,6 +777,7 @@ private int GetNextWorkflowStateID(ContentWorkflow workflow, int stateID) intNextStateID = states.ElementAt(intItem).StateID; break; } + intItem = intItem + 1; } } @@ -775,7 +785,7 @@ private int GetNextWorkflowStateID(ContentWorkflow workflow, int stateID) // if none found then reset to first state if (intNextStateID == -1) { - intNextStateID = GetFirstWorkflowStateID(workflow); + intNextStateID = this.GetFirstWorkflowStateID(workflow); } return intNextStateID; @@ -784,16 +794,14 @@ private int GetNextWorkflowStateID(ContentWorkflow workflow, int stateID) private void SetWorkflowState(int stateID, ContentItem item) { item.StateID = stateID; - contentController.UpdateContentItem(item); + this.contentController.UpdateContentItem(item); } private bool IsWorkflowCompleted(ContentWorkflow workflow, ContentItem item) { - var endStateID = GetLastWorkflowStateID(workflow); + var endStateID = this.GetLastWorkflowStateID(workflow); return item.StateID == Null.NullInteger || endStateID == item.StateID; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs index c322c3b054e..9d186cba4fb 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs @@ -1,50 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + /// - /// This entity represents a Workflow Log + /// This entity represents a Workflow Log. /// - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public class ContentWorkflowLog { /// - /// Workflow log Id + /// Gets or sets workflow log Id. /// public int WorkflowLogID { get; set; } /// - /// Workflow associated to the log entry + /// Gets or sets workflow associated to the log entry. /// public int WorkflowID { get; set; } /// - /// Content Item associated to the log entry + /// Gets or sets content Item associated to the log entry. /// public int ContentItemID { get; set; } - + /// - /// Action name (usually is a localized representation of the ContentWorkflowLogType) + /// Gets or sets action name (usually is a localized representation of the ContentWorkflowLogType). /// public string Action { get; set; } /// - /// Comment + /// Gets or sets comment. /// public string Comment { get; set; } /// - /// Log date + /// Gets or sets log date. /// public DateTime Date { get; set; } /// - /// User Id associated to the log + /// Gets or sets user Id associated to the log. /// public int User { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs index 8ff207737fb..fc9c353534d 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs @@ -1,16 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + /// - /// This enum represents the possible list of WorkflowLogType + /// This enum represents the possible list of WorkflowLogType. /// - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public enum ContentWorkflowLogType { WorkflowStarted = 0, @@ -21,6 +23,6 @@ public enum ContentWorkflowLogType WorkflowApproved = 5, WorkflowDiscarded = 6, CommentProvided = 10, - WorkflowError = 500 + WorkflowError = 500, } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs index e18c499aeca..d985c7ed9fa 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs @@ -1,12 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public class ContentWorkflowSource { diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs index 2ba57574cf5..c9299a707f6 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs @@ -1,43 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + /// - /// This entity represents a Workflow State + /// This entity represents a Workflow State. /// - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public class ContentWorkflowState + [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] + public class ContentWorkflowState { /// - /// State Id + /// Gets or sets state Id. /// public int StateID { get; set; } /// - /// Workflow associated to the state + /// Gets or sets workflow associated to the state. /// public int WorkflowID { get; set; } /// - /// State name + /// Gets or sets state name. /// public string StateName { get; set; } /// - /// State Order + /// Gets or sets state Order. /// public int Order { get; set; } + public bool IsActive { get; set; } public bool SendEmail { get; set; } - public bool SendMessage { get; set; } + public bool SendMessage { get; set; } public bool IsDisposalState { get; set; } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs index 28dd09cdece..89dc7a9a306 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs @@ -1,27 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + + using DotNetNuke.Security.Permissions; + /// - /// This entity represents a state permission + /// This entity represents a state permission. /// [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public class ContentWorkflowStatePermission : PermissionInfoBase { /// - /// Workflow state permission Id + /// Gets or sets workflow state permission Id. /// public int WorkflowStatePermissionID { get; set; } /// - /// State Id + /// Gets or sets state Id. /// public int StateID { get; set; } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs index fd1f50b64cd..2ed66a109c9 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public interface IContentWorkflowAction { diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs index b89d6e1ef1d..5557ddcc06e 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs @@ -1,16 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Content.Workflow + // ReSharper enable CheckNamespace { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public interface IContentWorkflowController { diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowActionRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowActionRepository.cs index d78238094f6..d6a36c8ad63 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowActionRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowActionRepository.cs @@ -1,28 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Content.Workflow.Actions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using DotNetNuke.Entities.Content.Workflow.Actions; + /// - /// This class is responsible to persist and retrieve workflow action entity + /// This class is responsible to persist and retrieve workflow action entity. /// internal interface IWorkflowActionRepository { /// - /// This method gets the workflow action of a content type Id and action type + /// This method gets the workflow action of a content type Id and action type. /// - /// Content Item Id - /// Action type - /// Workflow action entity + /// Content Item Id. + /// Action type. + /// Workflow action entity. WorkflowAction GetWorkflowAction(int contentTypeId, string actionType); /// - /// This method persists a new workflow action + /// This method persists a new workflow action. /// - /// Workflow action entity + /// Workflow action entity. void AddWorkflowAction(WorkflowAction workflowAction); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs index 0b1fb3d218e..ff7dbd09d28 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs @@ -1,35 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Content.Workflow.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System.Collections.Generic; + + using DotNetNuke.Entities.Content.Workflow.Entities; + /// - /// This class is responsible to persist and retrieve workflow log entity + /// This class is responsible to persist and retrieve workflow log entity. /// internal interface IWorkflowLogRepository { /// - /// This method hard delete all the workflow log of a content items + /// This method hard delete all the workflow log of a content items. /// - /// Content item Id - /// Workflow Id + /// Content item Id. + /// Workflow Id. void DeleteWorkflowLogs(int contentItemId, int workflowId); /// - /// This method persists a workflow log entity + /// This method persists a workflow log entity. /// - /// WorkflowLog entity + /// WorkflowLog entity. void AddWorkflowLog(WorkflowLog workflowLog); /// - /// This method gets all the Content workflow logs + /// This method gets all the Content workflow logs. /// - /// Content item Id - /// Workflow Id + /// Content item Id. + /// Workflow Id. + /// IEnumerable GetWorkflowLogs(int contentItemId, int workflowId); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowRepository.cs index 6f1014528cc..ba26f6b7b2e 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowRepository.cs @@ -1,60 +1,60 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System.Collections.Generic; + /// - /// This class is responsible to persist and retrieve workflow entity + /// This class is responsible to persist and retrieve workflow entity. /// internal interface IWorkflowRepository { /// - /// This method gets the list of system portal workflows + /// This method gets the list of system portal workflows. /// - /// Portal Id - /// List of system workflows of the portal + /// Portal Id. + /// List of system workflows of the portal. IEnumerable GetSystemWorkflows(int portalId); /// - /// This method gets the list of portal workflows + /// This method gets the list of portal workflows. /// - /// Portal Id - /// List of workflows of the portal + /// Portal Id. + /// List of workflows of the portal. IEnumerable GetWorkflows(int portalId); /// - /// This method gets the Workflow by Id + /// This method gets the Workflow by Id. /// - /// Workflow Id - /// Workflow entity + /// Workflow Id. + /// Workflow entity. Entities.Workflow GetWorkflow(int workflowId); /// - /// This method gets the Workflow by Content Item Id + /// This method gets the Workflow by Content Item Id. /// - /// Content Item entity - /// Workflow entity + /// Content Item entity. + /// Workflow entity. Entities.Workflow GetWorkflow(ContentItem contentItem); /// - /// This method persists a new workflow entity + /// This method persists a new workflow entity. /// - /// Workflow entity + /// Workflow entity. void AddWorkflow(Entities.Workflow workflow); /// - /// This method persists changes for a workflow entity + /// This method persists changes for a workflow entity. /// - /// Workflow entity + /// Workflow entity. void UpdateWorkflow(Entities.Workflow workflow); /// - /// This method hard deletes a workflow + /// This method hard deletes a workflow. /// - /// Workflow entity + /// Workflow entity. void DeleteWorkflow(Entities.Workflow workflow); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs index 1d78f554129..fbb1da588d8 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs @@ -1,35 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Content.Workflow.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System.Collections.Generic; + + using DotNetNuke.Entities.Content.Workflow.Entities; + /// - /// This class is responsible to manage the workflow state permission entity + /// This class is responsible to manage the workflow state permission entity. /// internal interface IWorkflowStatePermissionsRepository { /// - /// Gets the registered permissions set for a specific state + /// Gets the registered permissions set for a specific state. /// - /// State Id - /// List of Workflow State Permission entities + /// State Id. + /// List of Workflow State Permission entities. IEnumerable GetWorkflowStatePermissionByState(int stateId); /// - /// Persists a new Workflow State Permission entity + /// Persists a new Workflow State Permission entity. /// - /// Workflow State Permission entity - /// User Id who modifies the permissions set + /// Workflow State Permission entity. + /// User Id who modifies the permissions set. + /// int AddWorkflowStatePermission(WorkflowStatePermission permission, int lastModifiedByUserId); /// - /// Deletes a specific Workflow State Permission entity + /// Deletes a specific Workflow State Permission entity. /// - /// Workflow State Permission Id + /// Workflow State Permission Id. void DeleteWorkflowStatePermission(int workflowStatePermissionId); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStateRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStateRepository.cs index 7765118815f..8f4bd5451d4 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStateRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStateRepository.cs @@ -1,47 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Content.Workflow.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System.Collections.Generic; + + using DotNetNuke.Entities.Content.Workflow.Entities; + /// - /// This class is responsible to persist and retrieve workflow state entity + /// This class is responsible to persist and retrieve workflow state entity. /// internal interface IWorkflowStateRepository { /// - /// Get all states for a specific workflow + /// Get all states for a specific workflow. /// - /// Workflow Id - /// List of workflow states + /// Workflow Id. + /// List of workflow states. IEnumerable GetWorkflowStates(int workflowId); /// - /// Get a workflow state by Id + /// Get a workflow state by Id. /// - /// State Id - /// Workflow State entity + /// State Id. + /// Workflow State entity. WorkflowState GetWorkflowStateByID(int stateID); /// - /// Persists a new workflow state entity + /// Persists a new workflow state entity. /// - /// Workflow State entity + /// Workflow State entity. void AddWorkflowState(WorkflowState state); /// - /// Persists changes for a workflow state entity + /// Persists changes for a workflow state entity. /// - /// Workflow State entity + /// Workflow State entity. void UpdateWorkflowState(WorkflowState state); /// - /// This method hard deletes a workflow state entity + /// This method hard deletes a workflow state entity. /// - /// Workflow State entity + /// Workflow State entity. void DeleteWorkflowState(WorkflowState state); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs index 72e9131941c..045ef053138 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs @@ -1,25 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Workflow.Actions; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System; + using System.Linq; + + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Workflow.Actions; + using DotNetNuke.Framework; + internal class WorkflowActionRepository : ServiceLocator, IWorkflowActionRepository - { - #region Service Locator - protected override Func GetFactory() - { - return () => new WorkflowActionRepository(); - } - #endregion - - #region Public Methods + { public WorkflowAction GetWorkflowAction(int contentTypeId, string type) { using (var context = DataContext.Instance()) @@ -36,7 +29,11 @@ public void AddWorkflowAction(WorkflowAction action) var rep = context.GetRepository(); rep.Insert(action); } - } - #endregion + } + + protected override Func GetFactory() + { + return () => new WorkflowActionRepository(); + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs index 3d122be9cd3..1a59897a45c 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { - internal class WorkflowLogRepository : ServiceLocator , IWorkflowLogRepository - { - #region Public Methods + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Framework; + + internal class WorkflowLogRepository : ServiceLocator, IWorkflowLogRepository + { public IEnumerable GetWorkflowLogs(int contentItemId, int workflowId) { using (var context = DataContext.Instance()) { var rep = context.GetRepository(); var workflowLogs = rep.Find("WHERE (ContentItemID = @0 AND WorkflowID = @1)", contentItemId, workflowId).ToArray(); - + return workflowLogs; } } @@ -42,14 +42,11 @@ public void AddWorkflowLog(WorkflowLog workflowLog) rep.Insert(workflowLog); } - } - #endregion - - #region Service Locator + } + protected override Func GetFactory() { return () => new WorkflowLogRepository(); - } - #endregion - } + } + } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs index f923de2d79f..6ce3039c9c7 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs @@ -1,33 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Workflow.Exceptions; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Workflow.Exceptions; + using DotNetNuke.Framework; + // TODO: add interface metadata documentation // TODO: removed unused SPRoc and DataProvider layer internal class WorkflowRepository : ServiceLocator, IWorkflowRepository - { - #region Members - private readonly IWorkflowStateRepository _stateRepository; - #endregion - - #region Constructor + { + private readonly IWorkflowStateRepository _stateRepository; + public WorkflowRepository() { - _stateRepository = WorkflowStateRepository.Instance; - } - #endregion - - #region Public Methods + this._stateRepository = WorkflowStateRepository.Instance; + } + public IEnumerable GetWorkflows(int portalId) { using (var context = DataContext.Instance()) @@ -38,7 +34,7 @@ public WorkflowRepository() // Worfklow States eager loading foreach (var workflow in workflows) { - workflow.States = _stateRepository.GetWorkflowStates(workflow.WorkflowID); + workflow.States = this._stateRepository.GetWorkflowStates(workflow.WorkflowID); } return workflows; @@ -51,11 +47,11 @@ public WorkflowRepository() { var rep = context.GetRepository(); var workflows = rep.Find("WHERE (PortalId = @0 OR PortalId IS NULL) AND IsSystem = 1", portalId).ToArray(); - + // Worfklow States eager loading foreach (var workflow in workflows) { - workflow.States = _stateRepository.GetWorkflowStates(workflow.WorkflowID); + workflow.States = this._stateRepository.GetWorkflowStates(workflow.WorkflowID); } return workflows; @@ -64,7 +60,8 @@ public WorkflowRepository() public Entities.Workflow GetWorkflow(int workflowId) { - return CBO.GetCachedObject(new CacheItemArgs( + return CBO.GetCachedObject( + new CacheItemArgs( GetWorkflowItemKey(workflowId), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => { @@ -80,15 +77,15 @@ public Entities.Workflow GetWorkflow(int workflowId) return null; } - workflow.States = _stateRepository.GetWorkflowStates(workflowId); + workflow.States = this._stateRepository.GetWorkflowStates(workflowId); return workflow; }); } public Entities.Workflow GetWorkflow(ContentItem item) { - var state = _stateRepository.GetWorkflowStateByID(item.StateID); - return state == null ? null : GetWorkflow(state.WorkflowID); + var state = this._stateRepository.GetWorkflowStateByID(item.StateID); + return state == null ? null : this.GetWorkflow(state.WorkflowID); } // TODO: validation @@ -102,6 +99,7 @@ public void AddWorkflow(Entities.Workflow workflow) { throw new WorkflowNameAlreadyExistsException(); } + rep.Insert(workflow); } @@ -119,6 +117,7 @@ public void UpdateWorkflow(Entities.Workflow workflow) { throw new WorkflowNameAlreadyExistsException(); } + rep.Update(workflow); } @@ -135,10 +134,18 @@ public void DeleteWorkflow(Entities.Workflow workflow) } DataCache.RemoveCache(GetWorkflowItemKey(workflow.WorkflowID)); - } - #endregion + } - #region Private Methods + internal static string GetWorkflowItemKey(int workflowId) + { + return string.Format(DataCache.ContentWorkflowCacheKey, workflowId); + } + + protected override Func GetFactory() + { + return () => new WorkflowRepository(); + } + private static bool DoesExistWorkflow(Entities.Workflow workflow, IRepository rep) { return rep.Find( @@ -146,27 +153,15 @@ private static bool DoesExistWorkflow(Entities.Workflow workflow, IRepository 0) { - CBO.GetCachedObject(new CacheItemArgs(GetWorkflowItemKey(workflow.WorkflowID), + CBO.GetCachedObject( + new CacheItemArgs( + GetWorkflowItemKey(workflow.WorkflowID), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => workflow); } - } - - #endregion - - #region Service Locator - protected override Func GetFactory() - { - return () => new WorkflowRepository(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs index 71bf151ce86..d9be683435d 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Framework; + internal class WorkflowStatePermissionsRepository : ServiceLocator, IWorkflowStatePermissionsRepository - { - #region Public Methods + { public IEnumerable GetWorkflowStatePermissionByState(int stateId) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflowStatePermissionsByStateID(stateId)); @@ -21,25 +21,23 @@ public IEnumerable GetWorkflowStatePermissionByState(in public int AddWorkflowStatePermission(WorkflowStatePermission permission, int lastModifiedByUserId) { - return DataProvider.Instance().AddContentWorkflowStatePermission(permission.StateID, - permission.PermissionID, - permission.RoleID, - permission.AllowAccess, - permission.UserID, - lastModifiedByUserId); + return DataProvider.Instance().AddContentWorkflowStatePermission( + permission.StateID, + permission.PermissionID, + permission.RoleID, + permission.AllowAccess, + permission.UserID, + lastModifiedByUserId); } public void DeleteWorkflowStatePermission(int workflowStatePermissionId) { DataProvider.Instance().DeleteContentWorkflowStatePermission(workflowStatePermissionId); - } - #endregion - - #region Service Locator + } + protected override Func GetFactory() { return () => new WorkflowStatePermissionsRepository(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs index 371e027299e..25e43ecef37 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Content.Workflow.Exceptions; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow.Repositories { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Content.Workflow.Exceptions; + using DotNetNuke.Framework; + internal class WorkflowStateRepository : ServiceLocator, IWorkflowStateRepository - { - #region Public Methods + { public IEnumerable GetWorkflowStates(int workflowId) { using (var context = DataContext.Instance()) @@ -28,7 +28,8 @@ public IEnumerable GetWorkflowStates(int workflowId) public WorkflowState GetWorkflowStateByID(int stateId) { - return CBO.GetCachedObject(new CacheItemArgs( + return CBO.GetCachedObject( + new CacheItemArgs( GetWorkflowStateKey(stateId), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => { @@ -39,7 +40,7 @@ public WorkflowState GetWorkflowStateByID(int stateId) } }); } - + public void AddWorkflowState(WorkflowState state) { Requires.NotNull("state", state); @@ -56,9 +57,9 @@ public void AddWorkflowState(WorkflowState state) rep.Insert(state); } - CacheWorkflowState(state); + this.CacheWorkflowState(state); } - + public void UpdateWorkflowState(WorkflowState state) { Requires.NotNull("state", state); @@ -78,7 +79,7 @@ public void UpdateWorkflowState(WorkflowState state) DataCache.RemoveCache(GetWorkflowStateKey(state.StateID)); DataCache.RemoveCache(WorkflowRepository.GetWorkflowItemKey(state.WorkflowID)); - CacheWorkflowState(state); + this.CacheWorkflowState(state); } public void DeleteWorkflowState(WorkflowState state) @@ -94,11 +95,13 @@ public void DeleteWorkflowState(WorkflowState state) DataCache.RemoveCache(GetWorkflowStateKey(state.StateID)); DataCache.RemoveCache(WorkflowRepository.GetWorkflowItemKey(state.WorkflowID)); - } - #endregion - - #region Private Methods - + } + + protected override Func GetFactory() + { + return () => new WorkflowStateRepository(); + } + private static bool DoesExistWorkflowState(WorkflowState state, IRepository rep) { return rep.Find( @@ -115,18 +118,11 @@ private void CacheWorkflowState(WorkflowState state) { if (state.StateID > 0) { - CBO.GetCachedObject(new CacheItemArgs( + CBO.GetCachedObject( + new CacheItemArgs( GetWorkflowStateKey(state.StateID), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), - _ => state); + _ => state); } - } - #endregion - - #region Service Locator - protected override Func GetFactory() - { - return () => new WorkflowStateRepository(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs b/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs index 38ac17b589d..4bbbf358a2f 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs @@ -1,38 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Content.Workflow.Repositories; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System; + using System.Linq; + + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Content.Workflow.Repositories; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + public class SystemWorkflowManager : ServiceLocator, ISystemWorkflowManager - { - #region Public Constants + { public const string DirectPublishWorkflowKey = "DirectPublish"; public const string SaveDraftWorkflowKey = "SaveDraft"; - public const string ContentAprovalWorkflowKey = "ContentApproval"; - #endregion - - #region Members + public const string ContentAprovalWorkflowKey = "ContentApproval"; private readonly IWorkflowRepository _workflowRepository; - private readonly IWorkflowStateRepository _workflowStateRepository; - #endregion - - #region Constructor + private readonly IWorkflowStateRepository _workflowStateRepository; + public SystemWorkflowManager() { - _workflowRepository = WorkflowRepository.Instance; - _workflowStateRepository = WorkflowStateRepository.Instance; + this._workflowRepository = WorkflowRepository.Instance; + this._workflowStateRepository = WorkflowStateRepository.Instance; + } + + public void CreateSystemWorkflows(int portalId) + { + this.CreateDirectPublishWorkflow(portalId); + this.CreateSaveDraftWorkflow(portalId); + this.CreateContentApprovalWorkflow(portalId); } - #endregion - #region Private Methods + public Entities.Workflow GetDirectPublishWorkflow(int portalId) + { + return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == DirectPublishWorkflowKey); + } + private WorkflowState GetDefaultWorkflowState(int order) { return new WorkflowState @@ -40,7 +45,7 @@ private WorkflowState GetDefaultWorkflowState(int order) IsSystem = true, SendNotification = true, SendNotificationToAdministrators = false, - Order = order + Order = order, }; } @@ -52,12 +57,12 @@ private void CreateDirectPublishWorkflow(int portalId) Description = Localization.GetString("DefaultDirectPublishWorkflowDescription"), WorkflowKey = DirectPublishWorkflowKey, IsSystem = true, - PortalID = portalId + PortalID = portalId, }; - _workflowRepository.AddWorkflow(workflow); - var publishedState = GetPublishedStateDefinition(1); + this._workflowRepository.AddWorkflow(workflow); + var publishedState = this.GetPublishedStateDefinition(1); publishedState.WorkflowID = workflow.WorkflowID; - _workflowStateRepository.AddWorkflowState(publishedState); + this._workflowStateRepository.AddWorkflowState(publishedState); } private void CreateSaveDraftWorkflow(int portalId) @@ -68,17 +73,17 @@ private void CreateSaveDraftWorkflow(int portalId) Description = Localization.GetString("DefaultSaveDraftWorkflowDescription"), WorkflowKey = SaveDraftWorkflowKey, IsSystem = true, - PortalID = portalId + PortalID = portalId, }; - _workflowRepository.AddWorkflow(workflow); + this._workflowRepository.AddWorkflow(workflow); - var state = GetDraftStateDefinition(1); + var state = this.GetDraftStateDefinition(1); state.WorkflowID = workflow.WorkflowID; - _workflowStateRepository.AddWorkflowState(state); + this._workflowStateRepository.AddWorkflowState(state); - state = GetPublishedStateDefinition(2); + state = this.GetPublishedStateDefinition(2); state.WorkflowID = workflow.WorkflowID; - _workflowStateRepository.AddWorkflowState(state); + this._workflowStateRepository.AddWorkflowState(state); } private void CreateContentApprovalWorkflow(int portalId) @@ -89,76 +94,59 @@ private void CreateContentApprovalWorkflow(int portalId) Description = Localization.GetString("DefaultWorkflowDescription"), WorkflowKey = ContentAprovalWorkflowKey, IsSystem = true, - PortalID = portalId + PortalID = portalId, }; - _workflowRepository.AddWorkflow(workflow); + this._workflowRepository.AddWorkflow(workflow); - var state = GetDraftStateDefinition(1); + var state = this.GetDraftStateDefinition(1); state.WorkflowID = workflow.WorkflowID; - _workflowStateRepository.AddWorkflowState(state); + this._workflowStateRepository.AddWorkflowState(state); - state = GetReadyForReviewStateDefinition(2); + state = this.GetReadyForReviewStateDefinition(2); state.WorkflowID = workflow.WorkflowID; - _workflowStateRepository.AddWorkflowState(state); + this._workflowStateRepository.AddWorkflowState(state); - state = GetPublishedStateDefinition(3); + state = this.GetPublishedStateDefinition(3); state.WorkflowID = workflow.WorkflowID; - _workflowStateRepository.AddWorkflowState(state); - } - #endregion - - #region Public Methods - public void CreateSystemWorkflows(int portalId) - { - CreateDirectPublishWorkflow(portalId); - CreateSaveDraftWorkflow(portalId); - CreateContentApprovalWorkflow(portalId); - } - - public Entities.Workflow GetDirectPublishWorkflow(int portalId) - { - return _workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == DirectPublishWorkflowKey); - } + this._workflowStateRepository.AddWorkflowState(state); + } public Entities.Workflow GetSaveDraftWorkflow(int portalId) { - return _workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == SaveDraftWorkflowKey); + return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == SaveDraftWorkflowKey); } public Entities.Workflow GetContentApprovalWorkflow(int portalId) { - return _workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == ContentAprovalWorkflowKey); + return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == ContentAprovalWorkflowKey); } public WorkflowState GetDraftStateDefinition(int order) { - var state = GetDefaultWorkflowState(order); + var state = this.GetDefaultWorkflowState(order); state.StateName = Localization.GetString("DefaultWorkflowState1.StateName"); return state; } public WorkflowState GetPublishedStateDefinition(int order) { - var state = GetDefaultWorkflowState(order); + var state = this.GetDefaultWorkflowState(order); state.StateName = Localization.GetString("DefaultWorkflowState3.StateName"); return state; } public WorkflowState GetReadyForReviewStateDefinition(int order) { - var state = GetDefaultWorkflowState(order); + var state = this.GetDefaultWorkflowState(order); state.StateName = Localization.GetString("DefaultWorkflowState2.StateName"); state.SendNotification = true; state.SendNotificationToAdministrators = true; return state; - } - #endregion - - #region Service Locator + } + protected override Func GetFactory() { return () => new SystemWorkflowManager(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs index be9521a6aea..5a8956f79be 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs @@ -1,37 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Workflow.Actions; -using DotNetNuke.Entities.Content.Workflow.Dto; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Content.Workflow.Exceptions; -using DotNetNuke.Entities.Content.Workflow.Repositories; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Notifications; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Workflow.Actions; + using DotNetNuke.Entities.Content.Workflow.Dto; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Content.Workflow.Exceptions; + using DotNetNuke.Entities.Content.Workflow.Repositories; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Notifications; + public class WorkflowEngine : ServiceLocator, IWorkflowEngine - { - #region Constants + { private const string ContentWorkflowNotificationType = "ContentWorkflowNotification"; private const string ContentWorkflowNotificationNoActionType = "ContentWorkflowNoActionNotification"; - private const string ContentWorkflowNotificatioStartWorkflowType = "ContentWorkflowStartWorkflowNotification"; - #endregion - - #region Members + private const string ContentWorkflowNotificatioStartWorkflowType = "ContentWorkflowStartWorkflowNotification"; private readonly IContentController _contentController; private readonly IWorkflowRepository _workflowRepository; private readonly IWorkflowStateRepository _workflowStateRepository; @@ -43,29 +40,46 @@ public class WorkflowEngine : ServiceLocator, I private readonly INotificationsController _notificationsController; private readonly IWorkflowManager _workflowManager; private readonly IWorkflowLogger _workflowLogger; - private readonly ISystemWorkflowManager _systemWorkflowManager; - #endregion - - #region Constructor + private readonly ISystemWorkflowManager _systemWorkflowManager; + public WorkflowEngine() { - _contentController = Util.GetContentController(); - _workflowRepository = WorkflowRepository.Instance; - _workflowStateRepository = WorkflowStateRepository.Instance; - _workflowStatePermissionsRepository = WorkflowStatePermissionsRepository.Instance; - _workflowLogRepository = WorkflowLogRepository.Instance; - _workflowActionManager = WorkflowActionManager.Instance; - _workflowSecurity = WorkflowSecurity.Instance; - _userController = UserController.Instance; - _notificationsController = NotificationsController.Instance; - _workflowManager = WorkflowManager.Instance; - _workflowLogger = WorkflowLogger.Instance; - _systemWorkflowManager = SystemWorkflowManager.Instance; + this._contentController = Util.GetContentController(); + this._workflowRepository = WorkflowRepository.Instance; + this._workflowStateRepository = WorkflowStateRepository.Instance; + this._workflowStatePermissionsRepository = WorkflowStatePermissionsRepository.Instance; + this._workflowLogRepository = WorkflowLogRepository.Instance; + this._workflowActionManager = WorkflowActionManager.Instance; + this._workflowSecurity = WorkflowSecurity.Instance; + this._userController = UserController.Instance; + this._notificationsController = NotificationsController.Instance; + this._workflowManager = WorkflowManager.Instance; + this._workflowLogger = WorkflowLogger.Instance; + this._systemWorkflowManager = SystemWorkflowManager.Instance; + } + + public UserInfo GetStartedDraftStateUser(ContentItem contentItem) + { + return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.WorkflowStarted); } - #endregion - #region Private Methods + public UserInfo GetSubmittedDraftStateUser(ContentItem contentItem) + { + return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.DraftCompleted); + } + private static List GetRolesFromPermissions(PortalSettings settings, IEnumerable permissions) + { + return (from permission in permissions + where permission.AllowAccess && permission.RoleID > Null.NullInteger + select RoleController.Instance.GetRoleById(settings.PortalId, permission.RoleID)).ToList(); + } + + private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) + { + return roles.Any(r => r.RoleName == settings.AdministratorRoleName); + } + private StateTransaction CreateInitialTransaction(int contentItemId, int stateId, int userId) { return new StateTransaction @@ -73,14 +87,14 @@ private StateTransaction CreateInitialTransaction(int contentItemId, int stateId ContentItemId = contentItemId, CurrentStateId = stateId, UserId = userId, - Message = new StateTransactionMessage() + Message = new StateTransactionMessage(), }; } private void PerformWorkflowActionOnStateChanged(StateTransaction stateTransaction, WorkflowActionTypes actionType) { - var contentItem = _contentController.GetContentItem(stateTransaction.ContentItemId); - var workflowAction = GetWorkflowActionInstance(contentItem, actionType); + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + var workflowAction = this.GetWorkflowActionInstance(contentItem, actionType); if (workflowAction != null) { workflowAction.DoActionOnStateChanged(stateTransaction); @@ -89,8 +103,8 @@ private void PerformWorkflowActionOnStateChanged(StateTransaction stateTransacti private void PerformWorkflowActionOnStateChanging(StateTransaction stateTransaction, WorkflowActionTypes actionType) { - var contentItem = _contentController.GetContentItem(stateTransaction.ContentItemId); - var workflowAction = GetWorkflowActionInstance(contentItem, actionType); + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + var workflowAction = this.GetWorkflowActionInstance(contentItem, actionType); if (workflowAction != null) { workflowAction.DoActionOnStateChanging(stateTransaction); @@ -99,44 +113,45 @@ private void PerformWorkflowActionOnStateChanging(StateTransaction stateTransact private IWorkflowAction GetWorkflowActionInstance(ContentItem contentItem, WorkflowActionTypes actionType) { - return _workflowActionManager.GetWorkflowActionInstance(contentItem.ContentTypeId, actionType); + return this._workflowActionManager.GetWorkflowActionInstance(contentItem.ContentTypeId, actionType); } private void UpdateContentItemWorkflowState(int stateId, ContentItem item) { item.StateID = stateId; - _contentController.UpdateContentItem(item); + this._contentController.UpdateContentItem(item); } private UserInfo GetUserThatHaveStartedOrSubmittedDraftState(Entities.Workflow workflow, ContentItem contentItem, StateTransaction stateTransaction) { - bool wasDraftSubmitted = WasDraftSubmitted(workflow, stateTransaction.CurrentStateId); + bool wasDraftSubmitted = this.WasDraftSubmitted(workflow, stateTransaction.CurrentStateId); if (wasDraftSubmitted) { - return GetSubmittedDraftStateUser(contentItem); + return this.GetSubmittedDraftStateUser(contentItem); } - return GetStartedDraftStateUser(contentItem); + return this.GetStartedDraftStateUser(contentItem); } private UserInfo GetUserByWorkflowLogType(ContentItem contentItem, WorkflowLogType type) { - var workflow = _workflowManager.GetWorkflow(contentItem); + var workflow = this._workflowManager.GetWorkflow(contentItem); if (workflow == null) { return null; } - var logs = _workflowLogRepository.GetWorkflowLogs(contentItem.ContentItemId, workflow.WorkflowID); + var logs = this._workflowLogRepository.GetWorkflowLogs(contentItem.ContentItemId, workflow.WorkflowID); var logDraftCompleted = logs .OrderByDescending(l => l.Date) - .FirstOrDefault(l => l.Type == (int) type); + .FirstOrDefault(l => l.Type == (int)type); if (logDraftCompleted != null && logDraftCompleted.User != Null.NullInteger) { - return _userController.GetUserById(workflow.PortalID, logDraftCompleted.User); + return this._userController.GetUserById(workflow.PortalID, logDraftCompleted.User); } + return null; } @@ -145,9 +160,8 @@ private bool WasDraftSubmitted(Entities.Workflow workflow, int currentStateId) var isDirectPublishWorkflow = workflow.IsSystem && workflow.States.Count() == 1; var draftSubmitted = workflow.FirstState.StateID != currentStateId; return !(isDirectPublishWorkflow || !draftSubmitted); - } - - #region Notification utilities + } + private string GetWorkflowNotificationContext(ContentItem contentItem, WorkflowState state) { return string.Format("{0}:{1}:{2}", contentItem.ContentItemId, state.WorkflowID, state.StateID); @@ -155,19 +169,19 @@ private string GetWorkflowNotificationContext(ContentItem contentItem, WorkflowS private void DeleteWorkflowNotifications(ContentItem contentItem, WorkflowState state) { - var context = GetWorkflowNotificationContext(contentItem, state); - var notificationTypeId = _notificationsController.GetNotificationType(ContentWorkflowNotificationType).NotificationTypeId; - DeleteNotificationsByType(notificationTypeId, context); - notificationTypeId = _notificationsController.GetNotificationType(ContentWorkflowNotificatioStartWorkflowType).NotificationTypeId; - DeleteNotificationsByType(notificationTypeId, context); + var context = this.GetWorkflowNotificationContext(contentItem, state); + var notificationTypeId = this._notificationsController.GetNotificationType(ContentWorkflowNotificationType).NotificationTypeId; + this.DeleteNotificationsByType(notificationTypeId, context); + notificationTypeId = this._notificationsController.GetNotificationType(ContentWorkflowNotificatioStartWorkflowType).NotificationTypeId; + this.DeleteNotificationsByType(notificationTypeId, context); } private void DeleteNotificationsByType(int notificationTypeId, string context) { - var notifications = _notificationsController.GetNotificationByContext(notificationTypeId, context); + var notifications = this._notificationsController.GetNotificationByContext(notificationTypeId, context); foreach (var notification in notifications) { - _notificationsController.DeleteAllNotificationRecipients(notification.NotificationID); + this._notificationsController.DeleteAllNotificationRecipients(notification.NotificationID); } } @@ -180,10 +194,10 @@ private void SendNotificationToAuthor(StateTransaction stateTransaction, Workflo return; } - var user = GetUserThatHaveStartedOrSubmittedDraftState(workflow, contentItem, stateTransaction); + var user = this.GetUserThatHaveStartedOrSubmittedDraftState(workflow, contentItem, stateTransaction); if (user == null) { - //Services.Exceptions.Exceptions.LogException(new WorkflowException(Localization.GetExceptionMessage("WorkflowAuthorNotFound", "Author cannot be found. Notification won't be sent"))); + // Services.Exceptions.Exceptions.LogException(new WorkflowException(Localization.GetExceptionMessage("WorkflowAuthorNotFound", "Author cannot be found. Notification won't be sent"))); return; } @@ -192,7 +206,7 @@ private void SendNotificationToAuthor(StateTransaction stateTransaction, Workflo return; } - var workflowAction = GetWorkflowActionInstance(contentItem, workflowActionType); + var workflowAction = this.GetWorkflowActionInstance(contentItem, workflowActionType); if (workflowAction == null) { return; @@ -200,15 +214,14 @@ private void SendNotificationToAuthor(StateTransaction stateTransaction, Workflo var message = workflowAction.GetActionMessage(stateTransaction, state); - var notification = GetNotification(GetWorkflowNotificationContext(contentItem, state), stateTransaction, message, ContentWorkflowNotificationNoActionType); - - - _notificationsController.SendNotification(notification, workflow.PortalID, null, new[] { user }); + var notification = this.GetNotification(this.GetWorkflowNotificationContext(contentItem, state), stateTransaction, message, ContentWorkflowNotificationNoActionType); + + this._notificationsController.SendNotification(notification, workflow.PortalID, null, new[] { user }); } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); - } + } } private void SendNotificationToWorkflowStarter(StateTransaction stateTransaction, Entities.Workflow workflow, ContentItem contentItem, int starterUserId, WorkflowActionTypes workflowActionType) @@ -220,26 +233,24 @@ private void SendNotificationToWorkflowStarter(StateTransaction stateTransaction return; } - var workflowAction = GetWorkflowActionInstance(contentItem, workflowActionType); + var workflowAction = this.GetWorkflowActionInstance(contentItem, workflowActionType); if (workflowAction == null) { return; } - var user = _userController.GetUser(workflow.PortalID, starterUserId); + var user = this._userController.GetUser(workflow.PortalID, starterUserId); var message = workflowAction.GetActionMessage(stateTransaction, workflow.FirstState); - var notification = GetNotification( GetWorkflowNotificationContext(contentItem, workflow.FirstState), stateTransaction, message, ContentWorkflowNotificatioStartWorkflowType); - - - _notificationsController.SendNotification(notification, workflow.PortalID, null, new[] { user }); + var notification = this.GetNotification(this.GetWorkflowNotificationContext(contentItem, workflow.FirstState), stateTransaction, message, ContentWorkflowNotificatioStartWorkflowType); + + this._notificationsController.SendNotification(notification, workflow.PortalID, null, new[] { user }); } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); } - } private void SendNotificationsToReviewers(ContentItem contentItem, WorkflowState state, StateTransaction stateTransaction, WorkflowActionTypes workflowActionType, PortalSettings portalSettings) @@ -251,14 +262,14 @@ private void SendNotificationsToReviewers(ContentItem contentItem, WorkflowState return; } - var reviewers = GetUserAndRolesForStateReviewers(portalSettings, state); + var reviewers = this.GetUserAndRolesForStateReviewers(portalSettings, state); if (!reviewers.Roles.Any() && !reviewers.Users.Any()) { return; // If there are no receivers, the notification is avoided } - var workflowAction = GetWorkflowActionInstance(contentItem, workflowActionType); + var workflowAction = this.GetWorkflowActionInstance(contentItem, workflowActionType); if (workflowAction == null) { return; @@ -266,14 +277,14 @@ private void SendNotificationsToReviewers(ContentItem contentItem, WorkflowState var message = workflowAction.GetActionMessage(stateTransaction, state); - var notification = GetNotification(GetWorkflowNotificationContext(contentItem, state), stateTransaction, message, ContentWorkflowNotificationType); + var notification = this.GetNotification(this.GetWorkflowNotificationContext(contentItem, state), stateTransaction, message, ContentWorkflowNotificationType); - _notificationsController.SendNotification(notification, portalSettings.PortalId, reviewers.Roles.ToList(), reviewers.Users.ToList()); + this._notificationsController.SendNotification(notification, portalSettings.PortalId, reviewers.Roles.ToList(), reviewers.Users.ToList()); } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); - } + } } private Notification GetNotification(string workflowContext, StateTransaction stateTransaction, @@ -282,35 +293,27 @@ private Notification GetNotification(string workflowContext, StateTransaction st var notification = new Notification { NotificationTypeID = - _notificationsController.GetNotificationType(notificationType).NotificationTypeId, + this._notificationsController.GetNotificationType(notificationType).NotificationTypeId, Subject = message.Subject, Body = message.Body, IncludeDismissAction = true, SenderUserID = stateTransaction.UserId, Context = workflowContext, - SendToast = message.SendToast + SendToast = message.SendToast, }; return notification; } - - private class ReviewersDto - { - public List Roles { get; set; } - - public List Users { get; set; } - } - private ReviewersDto GetUserAndRolesForStateReviewers(PortalSettings portalSettings, WorkflowState state) { - var reviewers = new ReviewersDto - { - Roles = new List(), - Users = new List() - }; + var reviewers = new ReviewersDto + { + Roles = new List(), + Users = new List(), + }; if (state.SendNotification) { - var permissions = _workflowStatePermissionsRepository.GetWorkflowStatePermissionByState(state.StateID).ToArray(); + var permissions = this._workflowStatePermissionsRepository.GetWorkflowStatePermissionByState(state.StateID).ToArray(); reviewers.Users = GetUsersFromPermissions(portalSettings, permissions); reviewers.Roles = GetRolesFromPermissions(portalSettings, permissions); } @@ -328,24 +331,19 @@ private ReviewersDto GetUserAndRolesForStateReviewers(PortalSettings portalSetti return reviewers; } - - private static List GetRolesFromPermissions(PortalSettings settings, IEnumerable permissions) + + private class ReviewersDto { - return (from permission in permissions - where permission.AllowAccess && permission.RoleID > Null.NullInteger - select RoleController.Instance.GetRoleById(settings.PortalId, permission.RoleID)).ToList(); - } + public List Roles { get; set; } - private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) - { - return roles.Any(r => r.RoleName == settings.AdministratorRoleName); + public List Users { get; set; } } private static List GetUsersFromPermissions(PortalSettings settings, IEnumerable permissions) { - return (from permission in permissions - where permission.AllowAccess && permission.UserID > Null.NullInteger - select UserController.GetUserById(settings.PortalId, permission.UserID)).ToList(); + return (from permission in permissions + where permission.AllowAccess && permission.UserID > Null.NullInteger + select UserController.GetUserById(settings.PortalId, permission.UserID)).ToList(); } private static List IncludeSuperUsers(ICollection users) @@ -358,45 +356,53 @@ private static List IncludeSuperUsers(ICollection users) users.Add(superUser); } } + return users.ToList(); } private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo superUser) { return users.All(u => u.UserID != superUser.UserID); - } - #endregion + } - #region Log Workflow utilities + private static string GetWorkflowActionComment(WorkflowLogType logType) + { + var logName = Enum.GetName(typeof(WorkflowLogType), logType); + return Localization.GetString(logName + ".Comment"); + } + private void AddWorkflowCommentLog(ContentItem contentItem, int userId, string userComment) { if (string.IsNullOrEmpty(userComment)) { return; } - var state = _workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); - AddWorkflowLog(contentItem, state, WorkflowLogType.CommentProvided, userId, userComment); + + var state = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + this.AddWorkflowLog(contentItem, state, WorkflowLogType.CommentProvided, userId, userComment); } + private void AddWorkflowCommentLog(ContentItem contentItem, WorkflowState state, int userId, string userComment) { if (string.IsNullOrEmpty(userComment)) { return; } - AddWorkflowLog(contentItem, state, WorkflowLogType.CommentProvided, userId, userComment); + + this.AddWorkflowLog(contentItem, state, WorkflowLogType.CommentProvided, userId, userComment); } private void AddWorkflowLog(ContentItem contentItem, WorkflowLogType logType, int userId, string userComment = null) { - var state = _workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); - AddWorkflowLog(contentItem, state, logType, userId, userComment); + var state = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + this.AddWorkflowLog(contentItem, state, logType, userId, userComment); } private void AddWorkflowLog(ContentItem contentItem, WorkflowState state, WorkflowLogType logType, int userId, string userComment = null) { try { - TryAddWorkflowLog(contentItem, state, logType, userId, userComment); + this.TryAddWorkflowLog(contentItem, state, logType, userId, userComment); } catch (Exception ex) { @@ -406,28 +412,22 @@ private void AddWorkflowLog(ContentItem contentItem, WorkflowState state, Workfl private void TryAddWorkflowLog(ContentItem contentItem, WorkflowState state, WorkflowLogType logType, int userId, string userComment) { - var workflow = _workflowManager.GetWorkflow(contentItem); + var workflow = this._workflowManager.GetWorkflow(contentItem); var logTypeText = GetWorkflowActionComment(logType); - var logComment = ReplaceNotificationTokens(logTypeText, workflow, contentItem, state, userId, userComment); - _workflowLogger.AddWorkflowLog(contentItem.ContentItemId, workflow.WorkflowID, logType, logComment, userId); - } - - private static string GetWorkflowActionComment(WorkflowLogType logType) - { - var logName = Enum.GetName(typeof(WorkflowLogType), logType); - return Localization.GetString(logName + ".Comment"); + var logComment = this.ReplaceNotificationTokens(logTypeText, workflow, contentItem, state, userId, userComment); + this._workflowLogger.AddWorkflowLog(contentItem.ContentItemId, workflow.WorkflowID, logType, logComment, userId); } private string ReplaceNotificationTokens(string text, Entities.Workflow workflow, ContentItem item, WorkflowState state, int userId, string comment = "") { - var user = _userController.GetUserById(workflow.PortalID, userId); + var user = this._userController.GetUserById(workflow.PortalID, userId); var datetime = DateTime.UtcNow; - var result = text.Replace("[USER]", user != null ? user.DisplayName : ""); + var result = text.Replace("[USER]", user != null ? user.DisplayName : string.Empty); result = result.Replace("[DATE]", datetime.ToString("F", CultureInfo.CurrentCulture)); - result = result.Replace("[STATE]", state != null ? state.StateName : ""); + result = result.Replace("[STATE]", state != null ? state.StateName : string.Empty); result = result.Replace("[WORKFLOW]", workflow.WorkflowName); - result = result.Replace("[CONTENT]", item != null ? item.ContentTitle : ""); - result = result.Replace("[COMMENT]", !String.IsNullOrEmpty(comment) ? comment : ""); + result = result.Replace("[CONTENT]", item != null ? item.ContentTitle : string.Empty); + result = result.Replace("[COMMENT]", !string.IsNullOrEmpty(comment) ? comment : string.Empty); return result; } @@ -451,6 +451,7 @@ private WorkflowState GetNextWorkflowState(Entities.Workflow workflow, int state { nextState = states.ElementAt(index); } + return nextState ?? workflow.FirstState; } @@ -476,74 +477,60 @@ private WorkflowState GetPreviousWorkflowState(Entities.Workflow workflow, int s } return previousState ?? workflow.LastState; - } - #endregion - - #endregion - - #region Public Methods - public UserInfo GetStartedDraftStateUser(ContentItem contentItem) - { - return GetUserByWorkflowLogType(contentItem, WorkflowLogType.WorkflowStarted); - } - - public UserInfo GetSubmittedDraftStateUser(ContentItem contentItem) - { - return GetUserByWorkflowLogType(contentItem, WorkflowLogType.DraftCompleted); - } + } public void StartWorkflow(int workflowId, int contentItemId, int userId) { Requires.NotNegative("workflowId", workflowId); - var contentItem = _contentController.GetContentItem(contentItemId); - var workflow = _workflowManager.GetWorkflow(contentItem); + var contentItem = this._contentController.GetContentItem(contentItemId); + var workflow = this._workflowManager.GetWorkflow(contentItem); - //If already exists a started workflow - if (workflow != null && !IsWorkflowCompleted(contentItem)) + // If already exists a started workflow + if (workflow != null && !this.IsWorkflowCompleted(contentItem)) { throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowAlreadyStarted", "Workflow cannot get started for this Content Item. It already has a started workflow.")); } if (workflow == null || workflow.WorkflowID != workflowId) { - workflow = _workflowRepository.GetWorkflow(workflowId); + workflow = this._workflowRepository.GetWorkflow(workflowId); } - var initialTransaction = CreateInitialTransaction(contentItemId, workflow.FirstState.StateID, userId); + var initialTransaction = this.CreateInitialTransaction(contentItemId, workflow.FirstState.StateID, userId); - //Perform action before starting workflow - PerformWorkflowActionOnStateChanging( initialTransaction, WorkflowActionTypes.StartWorkflow); - UpdateContentItemWorkflowState(workflow.FirstState.StateID, contentItem); + // Perform action before starting workflow + this.PerformWorkflowActionOnStateChanging(initialTransaction, WorkflowActionTypes.StartWorkflow); + this.UpdateContentItemWorkflowState(workflow.FirstState.StateID, contentItem); - //Send notifications to stater - if (workflow.WorkflowID != _systemWorkflowManager.GetDirectPublishWorkflow(workflow.PortalID).WorkflowID) //This notification is not sent in Direct Publish WF + // Send notifications to stater + if (workflow.WorkflowID != this._systemWorkflowManager.GetDirectPublishWorkflow(workflow.PortalID).WorkflowID) // This notification is not sent in Direct Publish WF { - SendNotificationToWorkflowStarter(initialTransaction, workflow, contentItem, userId, WorkflowActionTypes.StartWorkflow); + this.SendNotificationToWorkflowStarter(initialTransaction, workflow, contentItem, userId, WorkflowActionTypes.StartWorkflow); } // Delete previous logs - _workflowLogRepository.DeleteWorkflowLogs(contentItemId, workflowId); + this._workflowLogRepository.DeleteWorkflowLogs(contentItemId, workflowId); // Add logs - AddWorkflowLog(contentItem, WorkflowLogType.WorkflowStarted, userId); - AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, userId); + this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowStarted, userId); + this.AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, userId); - //Perform action after starting workflow - PerformWorkflowActionOnStateChanged(initialTransaction, WorkflowActionTypes.StartWorkflow); + // Perform action after starting workflow + this.PerformWorkflowActionOnStateChanged(initialTransaction, WorkflowActionTypes.StartWorkflow); } public void CompleteState(StateTransaction stateTransaction) { - var contentItem = _contentController.GetContentItem(stateTransaction.ContentItemId); - var workflow = _workflowManager.GetWorkflow(contentItem); + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + var workflow = this._workflowManager.GetWorkflow(contentItem); if (workflow == null) { return; } - - if (IsWorkflowCompleted(contentItem) + + if (this.IsWorkflowCompleted(contentItem) && !(workflow.IsSystem && workflow.States.Count() == 1)) { throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowSystemWorkflowStateCannotComplete", "System workflow state cannot be completed.")); @@ -551,51 +538,52 @@ public void CompleteState(StateTransaction stateTransaction) var isFirstState = workflow.FirstState.StateID == contentItem.StateID; - if (!isFirstState && !_workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) + if (!isFirstState && !this._workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) { throw new WorkflowSecurityException(Localization.GetExceptionMessage("UserCannotReviewWorkflowState", "User cannot review the workflow state")); } - var currentState = _workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); if (currentState.StateID != stateTransaction.CurrentStateId) { throw new WorkflowConcurrencyException(); } - var nextState = GetNextWorkflowState(workflow, contentItem.StateID); + var nextState = this.GetNextWorkflowState(workflow, contentItem.StateID); if (nextState.StateID == workflow.LastState.StateID) { - CompleteWorkflow(stateTransaction); + this.CompleteWorkflow(stateTransaction); return; } // before-change action - PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteState); - UpdateContentItemWorkflowState(nextState.StateID, contentItem); + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteState); + this.UpdateContentItemWorkflowState(nextState.StateID, contentItem); // Add logs - AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); - AddWorkflowLog(contentItem, currentState, + this.AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, currentState, currentState.StateID == workflow.FirstState.StateID ? WorkflowLogType.DraftCompleted : WorkflowLogType.StateCompleted, stateTransaction.UserId); - AddWorkflowLog(contentItem, + this.AddWorkflowLog( + contentItem, nextState.StateID == workflow.LastState.StateID ? WorkflowLogType.WorkflowApproved : WorkflowLogType.StateInitiated, stateTransaction.UserId); - SendNotificationsToReviewers(contentItem, nextState, stateTransaction, WorkflowActionTypes.CompleteState, new PortalSettings(workflow.PortalID)); - - DeleteWorkflowNotifications(contentItem, currentState); + this.SendNotificationsToReviewers(contentItem, nextState, stateTransaction, WorkflowActionTypes.CompleteState, new PortalSettings(workflow.PortalID)); + + this.DeleteWorkflowNotifications(contentItem, currentState); // after-change action - PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteState); + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteState); } public void DiscardState(StateTransaction stateTransaction) { - var contentItem = _contentController.GetContentItem(stateTransaction.ContentItemId); - var workflow = _workflowManager.GetWorkflow(contentItem); + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + var workflow = this._workflowManager.GetWorkflow(contentItem); if (workflow == null) { return; @@ -603,145 +591,149 @@ public void DiscardState(StateTransaction stateTransaction) var isFirstState = workflow.FirstState.StateID == contentItem.StateID; var isLastState = workflow.LastState.StateID == contentItem.StateID; - + if (isLastState) { - throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowCannotDiscard", "Cannot discard on last workflow state")); + throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowCannotDiscard", "Cannot discard on last workflow state")); } - if (!isFirstState && !_workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) + if (!isFirstState && !this._workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) { throw new WorkflowSecurityException(Localization.GetExceptionMessage("UserCannotReviewWorkflowState", "User cannot review the workflow state")); } - var currentState = _workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); if (currentState.StateID != stateTransaction.CurrentStateId) { throw new WorkflowConcurrencyException(); } - var previousState = GetPreviousWorkflowState(workflow, contentItem.StateID); + var previousState = this.GetPreviousWorkflowState(workflow, contentItem.StateID); if (previousState.StateID == workflow.LastState.StateID) { - DiscardWorkflow(stateTransaction); + this.DiscardWorkflow(stateTransaction); return; } // before-change action - PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardState); + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardState); - UpdateContentItemWorkflowState(previousState.StateID, contentItem); + this.UpdateContentItemWorkflowState(previousState.StateID, contentItem); // Add logs - AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); - AddWorkflowLog(contentItem, currentState, WorkflowLogType.StateDiscarded, stateTransaction.UserId); - AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, stateTransaction.UserId); + this.AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, currentState, WorkflowLogType.StateDiscarded, stateTransaction.UserId); + this.AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, stateTransaction.UserId); if (previousState.StateID == workflow.FirstState.StateID) { // Send to author - workflow comes back to draft state - SendNotificationToAuthor(stateTransaction, previousState, workflow, contentItem, WorkflowActionTypes.DiscardState); + this.SendNotificationToAuthor(stateTransaction, previousState, workflow, contentItem, WorkflowActionTypes.DiscardState); } else { - SendNotificationsToReviewers(contentItem, previousState, stateTransaction, WorkflowActionTypes.DiscardState, new PortalSettings(workflow.PortalID)); + this.SendNotificationsToReviewers(contentItem, previousState, stateTransaction, WorkflowActionTypes.DiscardState, new PortalSettings(workflow.PortalID)); } - DeleteWorkflowNotifications(contentItem, currentState); + this.DeleteWorkflowNotifications(contentItem, currentState); // after-change action - PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardState); + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardState); } - + public bool IsWorkflowCompleted(int contentItemId) { - var contentItem = _contentController.GetContentItem(contentItemId); - return IsWorkflowCompleted(contentItem); + var contentItem = this._contentController.GetContentItem(contentItemId); + return this.IsWorkflowCompleted(contentItem); } public bool IsWorkflowCompleted(ContentItem contentItem) { - var workflow = _workflowManager.GetWorkflow(contentItem); - if (workflow == null) return true; // If item has not workflow, then it is considered as completed - + var workflow = this._workflowManager.GetWorkflow(contentItem); + if (workflow == null) + { + return true; // If item has not workflow, then it is considered as completed + } + return contentItem.StateID == Null.NullInteger || workflow.LastState.StateID == contentItem.StateID; } public bool IsWorkflowOnDraft(int contentItemId) { - var contentItem = _contentController.GetContentItem(contentItemId); //Ensure DB values - return IsWorkflowOnDraft(contentItem); + var contentItem = this._contentController.GetContentItem(contentItemId); // Ensure DB values + return this.IsWorkflowOnDraft(contentItem); } public bool IsWorkflowOnDraft(ContentItem contentItem) { - var workflow = _workflowManager.GetWorkflow(contentItem); - if (workflow == null) return false; // If item has not workflow, then it is not on Draft + var workflow = this._workflowManager.GetWorkflow(contentItem); + if (workflow == null) + { + return false; // If item has not workflow, then it is not on Draft + } + return contentItem.StateID == workflow.FirstState.StateID; } public void DiscardWorkflow(StateTransaction stateTransaction) { - var contentItem = _contentController.GetContentItem(stateTransaction.ContentItemId); + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); - var currentState = _workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); if (currentState.StateID != stateTransaction.CurrentStateId) { throw new WorkflowConcurrencyException(); } // before-change action - PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardWorkflow); + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardWorkflow); - var workflow =_workflowManager.GetWorkflow(contentItem); - UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); + var workflow = this._workflowManager.GetWorkflow(contentItem); + this.UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); // Logs - AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); - AddWorkflowLog(contentItem, WorkflowLogType.WorkflowDiscarded, stateTransaction.UserId); + this.AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowDiscarded, stateTransaction.UserId); // Notifications - SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.DiscardWorkflow); - DeleteWorkflowNotifications(contentItem, currentState); + this.SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.DiscardWorkflow); + this.DeleteWorkflowNotifications(contentItem, currentState); // after-change action - PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardWorkflow); + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardWorkflow); } public void CompleteWorkflow(StateTransaction stateTransaction) { - var contentItem = _contentController.GetContentItem(stateTransaction.ContentItemId); + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); - var currentState = _workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); if (currentState.StateID != stateTransaction.CurrentStateId) { throw new WorkflowConcurrencyException(); } // before-change action - PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteWorkflow); + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteWorkflow); + + var workflow = this._workflowManager.GetWorkflow(contentItem); + this.UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); - var workflow = _workflowManager.GetWorkflow(contentItem); - UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); - // Logs - AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); - AddWorkflowLog(contentItem, WorkflowLogType.WorkflowApproved, stateTransaction.UserId); + this.AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowApproved, stateTransaction.UserId); // Notifications - SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.CompleteWorkflow); - DeleteWorkflowNotifications(contentItem, currentState); + this.SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.CompleteWorkflow); + this.DeleteWorkflowNotifications(contentItem, currentState); // after-change action - PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteWorkflow); - } - #endregion - - #region Service Locator + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteWorkflow); + } + protected override Func GetFactory() { return () => new WorkflowEngine(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs index c4994c2e5d3..288a120bb32 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs @@ -1,30 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Content.Workflow.Repositories; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Content.Workflow.Repositories; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + public class WorkflowLogger : ServiceLocator, IWorkflowLogger - { - #region Members - private readonly IWorkflowLogRepository _workflowLogRepository; - #endregion - - #region Constructor + { + private readonly IWorkflowLogRepository _workflowLogRepository; + public WorkflowLogger() { - _workflowLogRepository = WorkflowLogRepository.Instance; + this._workflowLogRepository = WorkflowLogRepository.Instance; + } + + public IEnumerable GetWorkflowLogs(int contentItemId, int workflowId) + { + return this._workflowLogRepository.GetWorkflowLogs(contentItemId, workflowId); } - #endregion - - #region Private Methods + + public void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string comment, int userId) + { + this.AddWorkflowLog(contentItemId, workflowId, type, this.GetWorkflowActionText(type), comment, userId); + } + private void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string action, string comment, int userId) { var workflowLog = new WorkflowLog @@ -35,41 +41,25 @@ private void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType t Action = action, Comment = comment, User = userId, - Date = DateTime.UtcNow + Date = DateTime.UtcNow, }; - _workflowLogRepository.AddWorkflowLog(workflowLog); + this._workflowLogRepository.AddWorkflowLog(workflowLog); } private string GetWorkflowActionText(WorkflowLogType logType) { var logName = Enum.GetName(typeof(WorkflowLogType), logType); return Localization.GetString(logName + ".Action"); - } - #endregion - - #region Public Methods - public IEnumerable GetWorkflowLogs(int contentItemId, int workflowId) - { - return _workflowLogRepository.GetWorkflowLogs(contentItemId, workflowId); - } - - - public void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string comment, int userId) - { - AddWorkflowLog(contentItemId, workflowId, type, GetWorkflowActionText(type), comment, userId); - } + } public void AddWorkflowLog(int contentItemId, int workflowId, string action, string comment, int userId) { - AddWorkflowLog(contentItemId, workflowId, WorkflowLogType.CommentProvided, action, comment, userId); - } - #endregion - - #region Service Locator + this.AddWorkflowLog(contentItemId, workflowId, WorkflowLogType.CommentProvided, action, comment, userId); + } + protected override Func GetFactory() { return () => new WorkflowLogger(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs index e5fb6ccb272..c3c21c568fe 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs @@ -1,42 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Content.Workflow.Exceptions; -using DotNetNuke.Entities.Content.Workflow.Repositories; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Content.Workflow.Exceptions; + using DotNetNuke.Entities.Content.Workflow.Repositories; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + public class WorkflowManager : ServiceLocator, IWorkflowManager - { - #region Members + { private readonly DataProvider _dataProvider; private readonly IWorkflowRepository _workflowRepository; private readonly IWorkflowStateRepository _workflowStateRepository; - private readonly ISystemWorkflowManager _systemWorkflowManager; - #endregion - - #region Constructor + private readonly ISystemWorkflowManager _systemWorkflowManager; + public WorkflowManager() { - _dataProvider = DataProvider.Instance(); - _workflowRepository = WorkflowRepository.Instance; - _workflowStateRepository = WorkflowStateRepository.Instance; - _systemWorkflowManager = SystemWorkflowManager.Instance; - } - #endregion - - #region Public Methods - + this._dataProvider = DataProvider.Instance(); + this._workflowRepository = WorkflowRepository.Instance; + this._workflowStateRepository = WorkflowStateRepository.Instance; + this._systemWorkflowManager = SystemWorkflowManager.Instance; + } + public void DeleteWorkflow(Entities.Workflow workflow) { - var workflowToDelete = _workflowRepository.GetWorkflow(workflow.WorkflowID); + var workflowToDelete = this._workflowRepository.GetWorkflow(workflow.WorkflowID); if (workflowToDelete == null) { return; @@ -47,18 +42,18 @@ public void DeleteWorkflow(Entities.Workflow workflow) throw new WorkflowInvalidOperationException(Localization.GetString("SystemWorkflowDeletionException", Localization.ExceptionsResourceFile)); } - var usageCount = GetWorkflowUsageCount(workflowToDelete.WorkflowID); + var usageCount = this.GetWorkflowUsageCount(workflowToDelete.WorkflowID); if (usageCount > 0) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowInUsageException", Localization.ExceptionsResourceFile)); } - _workflowRepository.DeleteWorkflow(workflowToDelete); + this._workflowRepository.DeleteWorkflow(workflowToDelete); } public Entities.Workflow GetWorkflow(int workflowId) { - return _workflowRepository.GetWorkflow(workflowId); + return this._workflowRepository.GetWorkflow(workflowId); } public Entities.Workflow GetWorkflow(ContentItem contentItem) @@ -67,56 +62,54 @@ public Entities.Workflow GetWorkflow(ContentItem contentItem) { return null; } + var state = WorkflowStateRepository.Instance.GetWorkflowStateByID(contentItem.StateID); - return state == null ? null : GetWorkflow(state.WorkflowID); + return state == null ? null : this.GetWorkflow(state.WorkflowID); } public IEnumerable GetWorkflows(int portalId) { - return _workflowRepository.GetWorkflows(portalId); + return this._workflowRepository.GetWorkflows(portalId); } public void AddWorkflow(Entities.Workflow workflow) { - _workflowRepository.AddWorkflow(workflow); + this._workflowRepository.AddWorkflow(workflow); - var firstDefaultState = _systemWorkflowManager.GetDraftStateDefinition(1); - var lastDefaultState = _systemWorkflowManager.GetPublishedStateDefinition(2); + var firstDefaultState = this._systemWorkflowManager.GetDraftStateDefinition(1); + var lastDefaultState = this._systemWorkflowManager.GetPublishedStateDefinition(2); firstDefaultState.WorkflowID = workflow.WorkflowID; lastDefaultState.WorkflowID = workflow.WorkflowID; - _workflowStateRepository.AddWorkflowState(firstDefaultState); - _workflowStateRepository.AddWorkflowState(lastDefaultState); + this._workflowStateRepository.AddWorkflowState(firstDefaultState); + this._workflowStateRepository.AddWorkflowState(lastDefaultState); workflow.States = new List { firstDefaultState, - lastDefaultState + lastDefaultState, }; } public void UpdateWorkflow(Entities.Workflow workflow) { - _workflowRepository.UpdateWorkflow(workflow); + this._workflowRepository.UpdateWorkflow(workflow); } public IEnumerable GetWorkflowUsage(int workflowId, int pageIndex, int pageSize) { - return CBO.FillCollection(_dataProvider.GetContentWorkflowUsage(workflowId, pageIndex, pageSize)); + return CBO.FillCollection(this._dataProvider.GetContentWorkflowUsage(workflowId, pageIndex, pageSize)); } public int GetWorkflowUsageCount(int workflowId) { - return _dataProvider.GetContentWorkflowUsageCount(workflowId); - } - #endregion - - #region Service Locator + return this._dataProvider.GetContentWorkflowUsageCount(workflowId); + } + protected override System.Func GetFactory() { return () => new WorkflowManager(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs index 14803c2190b..f9c3e03659d 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.Entities.Content.Workflow.Repositories; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System; + using System.Linq; + + using DotNetNuke.Entities.Content.Workflow.Repositories; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + public class WorkflowSecurity : ServiceLocator, IWorkflowSecurity - { - #region Constants + { private const string ReviewPermissionKey = "REVIEW"; - private const string ReviewPermissionCode = "SYSTEM_CONTENTWORKFLOWSTATE"; - #endregion - - #region Members + private const string ReviewPermissionCode = "SYSTEM_CONTENTWORKFLOWSTATE"; private readonly IUserController _userController = UserController.Instance; private readonly IWorkflowManager _workflowManager = WorkflowManager.Instance; - private readonly IWorkflowStatePermissionsRepository _statePermissionsRepository = WorkflowStatePermissionsRepository.Instance; - #endregion - - #region Public Methods + private readonly IWorkflowStatePermissionsRepository _statePermissionsRepository = WorkflowStatePermissionsRepository.Instance; + public bool HasStateReviewerPermission(PortalSettings settings, UserInfo user, int stateId) { - var permissions = _statePermissionsRepository.GetWorkflowStatePermissionByState(stateId); + var permissions = this._statePermissionsRepository.GetWorkflowStatePermissionByState(stateId); return user.IsSuperUser || PortalSecurity.IsInRoles(user, settings, settings.AdministratorRoleName) || @@ -38,34 +33,31 @@ public bool HasStateReviewerPermission(PortalSettings settings, UserInfo user, i public bool HasStateReviewerPermission(int portalId, int userId, int stateId) { - var user = _userController.GetUserById(portalId, userId); + var user = this._userController.GetUserById(portalId, userId); var portalSettings = new PortalSettings(portalId); - return HasStateReviewerPermission(portalSettings, user, stateId); + return this.HasStateReviewerPermission(portalSettings, user, stateId); } public bool HasStateReviewerPermission(int stateId) { - var user = _userController.GetCurrentUserInfo(); - return HasStateReviewerPermission(PortalSettings.Current, user, stateId); + var user = this._userController.GetCurrentUserInfo(); + return this.HasStateReviewerPermission(PortalSettings.Current, user, stateId); } public bool IsWorkflowReviewer(int workflowId, int userId) { - var workflow = _workflowManager.GetWorkflow(workflowId); - return workflow.States.Any(contentWorkflowState => HasStateReviewerPermission(workflow.PortalID, userId, contentWorkflowState.StateID)); + var workflow = this._workflowManager.GetWorkflow(workflowId); + return workflow.States.Any(contentWorkflowState => this.HasStateReviewerPermission(workflow.PortalID, userId, contentWorkflowState.StateID)); } public PermissionInfo GetStateReviewPermission() { return (PermissionInfo)new PermissionController().GetPermissionByCodeAndKey(ReviewPermissionCode, ReviewPermissionKey)[0]; - } - #endregion - - #region Service Locator + } + protected override Func GetFactory() { return () => new WorkflowSecurity(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs index 4e99b13d45a..d2b5ad8a3a0 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs @@ -1,49 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Content.Workflow.Exceptions; -using DotNetNuke.Entities.Content.Workflow.Repositories; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Content.Workflow { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Content.Workflow.Exceptions; + using DotNetNuke.Entities.Content.Workflow.Repositories; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + public class WorkflowStateManager : ServiceLocator, IWorkflowStateManager - { - #region Members + { private readonly DataProvider _dataProvider; private readonly IWorkflowRepository _workflowRepository = WorkflowRepository.Instance; private readonly IWorkflowStateRepository _workflowStateRepository = WorkflowStateRepository.Instance; - private readonly IWorkflowStatePermissionsRepository _workflowStatePermissionsRepository = WorkflowStatePermissionsRepository.Instance; - #endregion - - #region Constructor + private readonly IWorkflowStatePermissionsRepository _workflowStatePermissionsRepository = WorkflowStatePermissionsRepository.Instance; + public WorkflowStateManager() { - _dataProvider = DataProvider.Instance(); - } - #endregion - - #region Public Methods + this._dataProvider = DataProvider.Instance(); + } + public IEnumerable GetWorkflowStates(int workflowId) { - return _workflowStateRepository.GetWorkflowStates(workflowId); + return this._workflowStateRepository.GetWorkflowStates(workflowId); } public WorkflowState GetWorkflowState(int stateId) { - return _workflowStateRepository.GetWorkflowStateByID(stateId); + return this._workflowStateRepository.GetWorkflowStateByID(stateId); } public void AddWorkflowState(WorkflowState state) { - var workflow = _workflowRepository.GetWorkflow(state.WorkflowID); + var workflow = this._workflowRepository.GetWorkflow(state.WorkflowID); if (workflow == null) { throw new WorkflowDoesNotExistException(); @@ -60,13 +56,13 @@ public void AddWorkflowState(WorkflowState state) state.Order = lastState.Order; lastState.Order++; - _workflowStateRepository.AddWorkflowState(state); - _workflowStateRepository.UpdateWorkflowState(lastState); // Update last state order + this._workflowStateRepository.AddWorkflowState(state); + this._workflowStateRepository.UpdateWorkflowState(lastState); // Update last state order } public void DeleteWorkflowState(WorkflowState state) { - var stateToDelete = _workflowStateRepository.GetWorkflowStateByID(state.StateID); + var stateToDelete = this._workflowStateRepository.GetWorkflowStateByID(state.StateID); if (stateToDelete == null) { return; @@ -77,12 +73,12 @@ public void DeleteWorkflowState(WorkflowState state) throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowSystemWorkflowStateCannotBeDeleted", Localization.ExceptionsResourceFile)); } - if (_dataProvider.GetContentWorkflowStateUsageCount(state.StateID) > 0) + if (this._dataProvider.GetContentWorkflowStateUsageCount(state.StateID) > 0) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowStateInUsageException", Localization.ExceptionsResourceFile)); } - _workflowStateRepository.DeleteWorkflowState(stateToDelete); + this._workflowStateRepository.DeleteWorkflowState(stateToDelete); // Reorder states order using (var context = DataContext.Instance()) @@ -94,23 +90,24 @@ public void DeleteWorkflowState(WorkflowState state) public void UpdateWorkflowState(WorkflowState state) { - var workflowState = _workflowStateRepository.GetWorkflowStateByID(state.StateID); + var workflowState = this._workflowStateRepository.GetWorkflowStateByID(state.StateID); if (workflowState == null) { throw new WorkflowDoesNotExistException(); } - _workflowStateRepository.UpdateWorkflowState(state); + + this._workflowStateRepository.UpdateWorkflowState(state); } public void MoveWorkflowStateDown(int stateId) { - var state = _workflowStateRepository.GetWorkflowStateByID(stateId); + var state = this._workflowStateRepository.GetWorkflowStateByID(stateId); if (state == null) { throw new WorkflowDoesNotExistException(); } - var states = _workflowStateRepository.GetWorkflowStates(state.WorkflowID).ToArray(); + var states = this._workflowStateRepository.GetWorkflowStates(state.WorkflowID).ToArray(); if (states.Length == 3) { @@ -122,9 +119,12 @@ public void MoveWorkflowStateDown(int stateId) for (var i = 0; i < states.Length; i++) { - if (states[i].StateID != stateId) continue; - - // First and Second workflow state cannot be moved down + if (states[i].StateID != stateId) + { + continue; + } + + // First and Second workflow state cannot be moved down if (i <= 1) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowStateCannotBeMoved", Localization.ExceptionsResourceFile)); @@ -144,19 +144,19 @@ public void MoveWorkflowStateDown(int stateId) stateToMoveDown.Order = stateToMoveUp.Order; stateToMoveUp.Order = orderTmp; - _workflowStateRepository.UpdateWorkflowState(stateToMoveUp); - _workflowStateRepository.UpdateWorkflowState(stateToMoveDown); + this._workflowStateRepository.UpdateWorkflowState(stateToMoveUp); + this._workflowStateRepository.UpdateWorkflowState(stateToMoveDown); } public void MoveWorkflowStateUp(int stateId) { - var state = _workflowStateRepository.GetWorkflowStateByID(stateId); + var state = this._workflowStateRepository.GetWorkflowStateByID(stateId); if (state == null) { throw new WorkflowDoesNotExistException(); } - var states = _workflowStateRepository.GetWorkflowStates(state.WorkflowID).ToArray(); + var states = this._workflowStateRepository.GetWorkflowStates(state.WorkflowID).ToArray(); if (states.Length == 3) { @@ -168,9 +168,12 @@ public void MoveWorkflowStateUp(int stateId) for (var i = 0; i < states.Length; i++) { - if (states[i].StateID != stateId) continue; - - // Last and Next to Last workflow state cannot be moved up + if (states[i].StateID != stateId) + { + continue; + } + + // Last and Next to Last workflow state cannot be moved up if (i >= states.Length - 2) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowStateCannotBeMoved", Localization.ExceptionsResourceFile)); @@ -190,25 +193,25 @@ public void MoveWorkflowStateUp(int stateId) stateToMoveDown.Order = stateToMoveUp.Order; stateToMoveUp.Order = orderTmp; - _workflowStateRepository.UpdateWorkflowState(stateToMoveUp); - _workflowStateRepository.UpdateWorkflowState(stateToMoveDown); + this._workflowStateRepository.UpdateWorkflowState(stateToMoveUp); + this._workflowStateRepository.UpdateWorkflowState(stateToMoveDown); } public void MoveState(int stateId, int index) { - var state = _workflowStateRepository.GetWorkflowStateByID(stateId); + var state = this._workflowStateRepository.GetWorkflowStateByID(stateId); if (state == null) { throw new WorkflowDoesNotExistException(); } - var states = _workflowStateRepository.GetWorkflowStates(state.WorkflowID).ToArray(); + var states = this._workflowStateRepository.GetWorkflowStates(state.WorkflowID).ToArray(); if (index < 1 || index > states.Length - 2) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowStateCannotBeMoved", Localization.ExceptionsResourceFile)); } - var currentIndex = GetStateIndex(states, state); + var currentIndex = this.GetStateIndex(states, state); if (currentIndex == 0 || currentIndex == states.Length - 1) @@ -216,31 +219,34 @@ public void MoveState(int stateId, int index) throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowStateCannotBeMoved", Localization.ExceptionsResourceFile)); } - MoveState(state, index, currentIndex); + this.MoveState(state, index, currentIndex); } public IEnumerable GetWorkflowStatePermissionByState(int stateId) { - return _workflowStatePermissionsRepository.GetWorkflowStatePermissionByState(stateId); + return this._workflowStatePermissionsRepository.GetWorkflowStatePermissionByState(stateId); } public void AddWorkflowStatePermission(WorkflowStatePermission permission, int userId) { - permission.WorkflowStatePermissionID = _workflowStatePermissionsRepository.AddWorkflowStatePermission(permission, userId); + permission.WorkflowStatePermissionID = this._workflowStatePermissionsRepository.AddWorkflowStatePermission(permission, userId); } public void DeleteWorkflowStatePermission(int workflowStatePermissionId) { - _workflowStatePermissionsRepository.DeleteWorkflowStatePermission(workflowStatePermissionId); + this._workflowStatePermissionsRepository.DeleteWorkflowStatePermission(workflowStatePermissionId); } public int GetContentWorkflowStateUsageCount(int stateId) { - return _dataProvider.GetContentWorkflowStateUsageCount(stateId); - } - #endregion - - #region Private Methods + return this._dataProvider.GetContentWorkflowStateUsageCount(stateId); + } + + protected override Func GetFactory() + { + return () => new WorkflowStateManager(); + } + private int GetStateIndex(WorkflowState[] states, WorkflowState currentState) { int i = 0; @@ -251,11 +257,13 @@ private int GetStateIndex(WorkflowState[] states, WorkflowState currentState) { return i; } + i++; } return i; } + private void MoveState(WorkflowState state, int targetIndex, int currentIndex) { if (currentIndex == targetIndex) @@ -270,20 +278,13 @@ private void MoveState(WorkflowState state, int targetIndex, int currentIndex) { if (moveUp) { - MoveWorkflowStateUp(state.StateID); + this.MoveWorkflowStateUp(state.StateID); } else { - MoveWorkflowStateDown(state.StateID); + this.MoveWorkflowStateDown(state.StateID); } } - } - #endregion - #region Service Locator - protected override Func GetFactory() - { - return () => new WorkflowStateManager(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Controllers/HostController.cs b/DNN Platform/Library/Entities/Controllers/HostController.cs index 478117983ca..5a634996629 100644 --- a/DNN Platform/Library/Entities/Controllers/HostController.cs +++ b/DNN Platform/Library/Entities/Controllers/HostController.cs @@ -1,75 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Log.EventLog; - -using System.Globalization; -using DotNetNuke.Web.Client; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Controllers { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Web.Client; + /// - /// HostController provides business layer of host settings. - /// - /// - /// - /// public static bool CheckUpgrade + /// HostController provides business layer of host settings. + ///
    + /// + /// + /// public static bool CheckUpgrade /// { /// get /// { /// return HostController.Instance.GetBoolean("CheckUpgrade", true); /// } /// } - /// - /// + /// + /// public class HostController : ComponentBase, IHostController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (HostController)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(HostController)); + /// - /// Initializes a new instance of the HostController class + /// Initializes a new instance of the class. /// internal HostController() { } - #region IHostController Members - - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// host setting's value. - /// key is empty. + /// + /// Gets the setting value by the specific key. + /// + /// The key. + /// host setting's value. + /// key is empty. public bool GetBoolean(string key) { - return GetBoolean(key, Null.NullBoolean); + return this.GetBoolean(key, Null.NullBoolean); } - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// this value will be return if setting's value is empty. - /// host setting's value. - /// key is empty. + /// + /// Gets the setting value by the specific key. + /// + /// The key. + /// this value will be return if setting's value is empty. + /// host setting's value. + /// key is empty. public bool GetBoolean(string key, bool defaultValue) { Requires.NotNullOrEmpty("key", key); @@ -78,9 +71,9 @@ public bool GetBoolean(string key, bool defaultValue) try { string setting = string.Empty; - if ((GetSettings().ContainsKey(key))) + if (this.GetSettings().ContainsKey(key)) { - setting = GetSettings()[key].Value; + setting = this.GetSettings()[key].Value; } if (string.IsNullOrEmpty(setting)) @@ -89,42 +82,44 @@ public bool GetBoolean(string key, bool defaultValue) } else { - retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); } } catch (Exception exc) { Logger.Error(exc); - //we just want to trap the error as we may not be installed so there will be no Settings + + // we just want to trap the error as we may not be installed so there will be no Settings } + return retValue; } - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// host setting's value. - /// key is empty. + /// + /// Gets the setting value by the specific key. + /// + /// The key. + /// host setting's value. + /// key is empty. public double GetDouble(string key) { - return GetDouble(key, Null.NullDouble); + return this.GetDouble(key, Null.NullDouble); } - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// this value will be return if setting's value is empty. - /// host setting's value. - /// key is empty. + /// + /// Gets the setting value by the specific key. + /// + /// The key. + /// this value will be return if setting's value is empty. + /// host setting's value. + /// key is empty. public double GetDouble(string key, double defaultValue) { Requires.NotNullOrEmpty("key", key); double retValue; - if ((!GetSettings().ContainsKey(key) || !double.TryParse(GetSettings()[key].Value, out retValue))) + if (!this.GetSettings().ContainsKey(key) || !double.TryParse(this.GetSettings()[key].Value, out retValue)) { retValue = defaultValue; } @@ -132,31 +127,31 @@ public double GetDouble(string key, double defaultValue) return retValue; } - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// host setting's value. - /// key is empty. + /// + /// Gets the setting value by the specific key. + /// + /// The key. + /// host setting's value. + /// key is empty. public int GetInteger(string key) { - return GetInteger(key, Null.NullInteger); + return this.GetInteger(key, Null.NullInteger); } - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// this value will be return if setting's value is empty. - /// host setting's value. - /// key is empty. + /// + /// Gets the setting value by the specific key. + /// + /// The key. + /// this value will be return if setting's value is empty. + /// host setting's value. + /// key is empty. public int GetInteger(string key, int defaultValue) { Requires.NotNullOrEmpty("key", key); int retValue; - if ((!GetSettings().ContainsKey(key) || !int.TryParse(GetSettings()[key].Value, out retValue))) + if (!this.GetSettings().ContainsKey(key) || !int.TryParse(this.GetSettings()[key].Value, out retValue)) { retValue = defaultValue; } @@ -164,102 +159,102 @@ public int GetInteger(string key, int defaultValue) return retValue; } - /// - /// Gets all host settings. - /// - /// host setting. + /// + /// Gets all host settings. + /// + /// host setting. public Dictionary GetSettings() { return CBO.GetCachedObject>( - new CacheItemArgs(DataCache.HostSettingsCacheKey, - DataCache.HostSettingsCacheTimeOut, - DataCache.HostSettingsCachePriority), - GetSettingsDictionaryCallBack, + new CacheItemArgs( + DataCache.HostSettingsCacheKey, + DataCache.HostSettingsCacheTimeOut, + DataCache.HostSettingsCachePriority), + GetSettingsDictionaryCallBack, true); } - /// - /// Gets all host settings as dictionary. - /// - /// host setting's value. + /// + /// Gets all host settings as dictionary. + /// + /// host setting's value. public Dictionary GetSettingsDictionary() { - return GetSettings().ToDictionary(c => c.Key, c => c.Value.Value); + return this.GetSettings().ToDictionary(c => c.Key, c => c.Value.Value); } /// - /// takes in a text value, decrypts it with a FIPS compliant algorithm and returns the value + /// takes in a text value, decrypts it with a FIPS compliant algorithm and returns the value. /// - /// the host setting to read - /// the pass phrase used for encryption/decryption - /// The setting value as a + /// the host setting to read. + /// the pass phrase used for encryption/decryption. + /// The setting value as a . public string GetEncryptedString(string key, string passPhrase) { Requires.NotNullOrEmpty("key", key); Requires.NotNullOrEmpty("passPhrase", passPhrase); - var cipherText = GetString(key); + var cipherText = this.GetString(key); return Security.FIPSCompliant.DecryptAES(cipherText, passPhrase, Entities.Host.Host.GUID); } - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// host setting's value. - /// key is empty. + /// Gets the setting value by the specific key. + ///
    + /// The key. + /// host setting's value. + /// key is empty. public string GetString(string key) { - return GetString(key, string.Empty); + return this.GetString(key, string.Empty); } - /// - /// Gets the setting value by the specific key. - /// - /// The key. - /// this value will be return if setting's value is empty. - /// host setting's value. - /// key is empty. + /// + /// Gets the setting value by the specific key. + /// + /// The key. + /// this value will be return if setting's value is empty. + /// host setting's value. + /// key is empty. public string GetString(string key, string defaultValue) { Requires.NotNullOrEmpty("key", key); - if (!GetSettings().ContainsKey(key) || GetSettings()[key].Value == null) + if (!this.GetSettings().ContainsKey(key) || this.GetSettings()[key].Value == null) { return defaultValue; } - return GetSettings()[key].Value; + return this.GetSettings()[key].Value; } - /// - /// Updates the specified settings. - /// - /// The settings. + /// + /// Updates the specified settings. + /// + /// The settings. public void Update(Dictionary settings) { foreach (KeyValuePair settingKvp in settings) { - Update(settingKvp.Key, settingKvp.Value, false); + this.Update(settingKvp.Key, settingKvp.Value, false); } DataCache.ClearHostCache(false); } - /// - /// Updates the specified config. - /// - /// The config. + /// + /// Updates the specified config. + /// + /// The config. public void Update(ConfigurationSetting config) { - Update(config, true); + this.Update(config, true); } - /// - /// Updates the specified config. - /// - /// The config. - /// if set to true will clear cache after updating the setting. + /// + /// Updates the specified config. + /// + /// The config. + /// if set to true will clear cache after updating the setting. public void Update(ConfigurationSetting config, bool clearCache) { try @@ -275,21 +270,23 @@ public void Update(ConfigurationSetting config, bool clearCache) if (currentconfig != null && currentconfig.Value != config.Value) { dbProvider.UpdateHostSetting(config.Key, config.Value, config.IsSecure, userId); - EventLogController.Instance.AddLog(config.Key, - config.Value, - portalSettings, - userId, - EventLogController.EventLogType.HOST_SETTING_UPDATED); + EventLogController.Instance.AddLog( + config.Key, + config.Value, + portalSettings, + userId, + EventLogController.EventLogType.HOST_SETTING_UPDATED); } } else { dbProvider.UpdateHostSetting(config.Key, config.Value, config.IsSecure, userId); - EventLogController.Instance.AddLog(config.Key, - config.Value, - portalSettings, - userId, - EventLogController.EventLogType.HOST_SETTING_CREATED); + EventLogController.Instance.AddLog( + config.Key, + config.Value, + portalSettings, + userId, + EventLogController.EventLogType.HOST_SETTING_CREATED); } } catch (Exception ex) @@ -303,51 +300,51 @@ public void Update(ConfigurationSetting config, bool clearCache) } } - /// - /// Updates the specified key. - /// - /// The key. - /// The value. - /// if set to true will clear cache after update settings. + /// + /// Updates the specified key. + /// + /// The key. + /// The value. + /// if set to true will clear cache after update settings. public void Update(string key, string value, bool clearCache) { - Update(new ConfigurationSetting { Key = key, Value = value }, clearCache); + this.Update(new ConfigurationSetting { Key = key, Value = value }, clearCache); } - /// - /// Updates the setting for a specified key. - /// - /// The key. - /// The value. + /// + /// Updates the setting for a specified key. + /// + /// The key. + /// The value. public void Update(string key, string value) { - Update(key, value, true); + this.Update(key, value, true); } /// /// Takes in a value, encrypts it with a FIPS compliant algorithm and stores it. /// - /// host settings key - /// host settings value - /// pass phrase to allow encryption/decryption + /// host settings key. + /// host settings value. + /// pass phrase to allow encryption/decryption. public void UpdateEncryptedString(string key, string value, string passPhrase) { Requires.NotNullOrEmpty("key", key); Requires.PropertyNotNull("value", value); Requires.NotNullOrEmpty("passPhrase", passPhrase); var cipherText = Security.FIPSCompliant.EncryptAES(value, passPhrase, Entities.Host.Host.GUID); - Update(key, cipherText); + this.Update(key, cipherText); } /// - /// Increments the Client Resource Manager (CRM) version to bust local cache + /// Increments the Client Resource Manager (CRM) version to bust local cache. /// - /// If true also forces a CRM version increment on portals that have non-default settings for CRM + /// If true also forces a CRM version increment on portals that have non-default settings for CRM. public void IncrementCrmVersion(bool includeOverridingPortals) { var currentVersion = Host.Host.CrmVersion; var newVersion = currentVersion + 1; - Update(ClientResourceSettings.VersionKey, newVersion.ToString(CultureInfo.InvariantCulture), true); + this.Update(ClientResourceSettings.VersionKey, newVersion.ToString(CultureInfo.InvariantCulture), true); if (includeOverridingPortals) { @@ -355,12 +352,10 @@ public void IncrementCrmVersion(bool includeOverridingPortals) } } - #endregion - /// - /// Gets all settings from the databse + /// Gets all settings from the databse. /// - /// <, > + /// private static Dictionary GetSettingsFromDatabase() { var dicSettings = new Dictionary(); @@ -372,11 +367,11 @@ private static Dictionary GetSettingsFromDatabase( { string key = dr.GetString(0); var config = new ConfigurationSetting - { - Key = key, - IsSecure = Convert.ToBoolean(dr[2]), - Value = dr.IsDBNull(1) ? string.Empty : dr.GetString(1) - }; + { + Key = key, + IsSecure = Convert.ToBoolean(dr[2]), + Value = dr.IsDBNull(1) ? string.Empty : dr.GetString(1), + }; dicSettings.Add(key, config); } @@ -389,6 +384,7 @@ private static Dictionary GetSettingsFromDatabase( { CBO.CloseDataReader(dr, true); } + return dicSettings; } diff --git a/DNN Platform/Library/Entities/Controllers/IHostController.cs b/DNN Platform/Library/Entities/Controllers/IHostController.cs index 0faea9c6b6d..ad1d48b8a55 100644 --- a/DNN Platform/Library/Entities/Controllers/IHostController.cs +++ b/DNN Platform/Library/Entities/Controllers/IHostController.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Controllers { + using System.Collections.Generic; + /// /// Interface of HostController. /// @@ -28,131 +23,131 @@ namespace DotNetNuke.Entities.Controllers public interface IHostController { /// - /// Gets the setting value for the specific key + /// Gets the setting value for the specific key. /// - /// The setting key string - /// host setting as a boolean + /// The setting key string. + /// host setting as a boolean. bool GetBoolean(string key); /// - /// Gets the setting value for the specific key + /// Gets the setting value for the specific key. /// - /// The setting key string - /// Default value returned if the setting is not found or not compatible with the requested type - /// host setting or the provided default value as a + /// The setting key string. + /// Default value returned if the setting is not found or not compatible with the requested type. + /// host setting or the provided default value as a . bool GetBoolean(string key, bool defaultValue); /// - /// Gets the setting value for the specific key + /// Gets the setting value for the specific key. /// - /// The setting key string - /// Default value returned if the setting is not found or not compatible with the requested type - /// Host setting or the provided default value as a + /// The setting key string. + /// Default value returned if the setting is not found or not compatible with the requested type. + /// Host setting or the provided default value as a . double GetDouble(string key, double defaultValue); /// - /// Gets the setting value for the specific key + /// Gets the setting value for the specific key. /// - /// The setting key string - /// Host setting as a + /// The setting key string. + /// Host setting as a . double GetDouble(string key); /// - /// Gets the setting value for the specific key + /// Gets the setting value for the specific key. /// - /// The setting key string - /// Host setting as an + /// The setting key string. + /// Host setting as an . int GetInteger(string key); /// - /// Gets the setting value for the specific key + /// Gets the setting value for the specific key. /// - /// The setting key string - /// Default value returned if the setting is not found or not compatible with the requested type - /// Host setting or provided default value as a + /// The setting key string. + /// Default value returned if the setting is not found or not compatible with the requested type. + /// Host setting or provided default value as a . int GetInteger(string key, int defaultValue); /// - /// Gets the host settings + /// Gets the host settings. /// - /// Host settings as a <, > + /// Host settings as a . Dictionary GetSettings(); /// - /// Gets the host settings + /// Gets the host settings. /// - /// Host settings as a <, > + /// Host settings as a . Dictionary GetSettingsDictionary(); /// - /// Gets an encrypted host setting as a + /// Gets an encrypted host setting as a . /// - /// The setting key string - /// The passPhrase used to decrypt the setting value - /// The setting value as a - string GetEncryptedString(string key,string passPhrase); + /// The setting key string. + /// The passPhrase used to decrypt the setting value. + /// The setting value as a . + string GetEncryptedString(string key, string passPhrase); /// - /// Gets the setting value for a specific key + /// Gets the setting value for a specific key. /// - /// The setting key string - /// The setting value as a + /// The setting key string. + /// The setting value as a . string GetString(string key); /// - /// Gets the setting value for a specific key + /// Gets the setting value for a specific key. /// - /// The seeting key string + /// The seeting key string. /// - /// Default value returned if the setting is not found + /// Default value returned if the setting is not found. string GetString(string key, string defaultValue); /// - /// Updates the specified settings + /// Updates the specified settings. /// - /// The settings to update + /// The settings to update. void Update(Dictionary settings); /// - /// Updates the specified config + /// Updates the specified config. /// - /// The configuration setting + /// The configuration setting. void Update(ConfigurationSetting config); /// - /// Updates the specified config, ontionally clearing the cache + /// Updates the specified config, ontionally clearing the cache. /// - /// The configuaration setting + /// The configuaration setting. /// If set to true, will clear the cache after updating the setting. void Update(ConfigurationSetting config, bool clearCache); /// - /// Updates the setting for a specific key + /// Updates the setting for a specific key. /// - /// The setting key string - /// The value to update - /// If set to true, will clear the cache after updating the setting + /// The setting key string. + /// The value to update. + /// If set to true, will clear the cache after updating the setting. void Update(string key, string value, bool clearCache); /// - /// Updates the setting for a specific key + /// Updates the setting for a specific key. /// - /// The setting key string - /// The value to update + /// The setting key string. + /// The value to update. void Update(string key, string value); /// - /// Takes in a value, encrypts it with a FIPS compliant algorithm and stores + /// Takes in a value, encrypts it with a FIPS compliant algorithm and stores. /// - /// host settings key - /// host settings value - /// pass phrase to allow encryption/decryption + /// host settings key. + /// host settings value. + /// pass phrase to allow encryption/decryption. void UpdateEncryptedString(string key, string value, string passPhrase); /// - /// Increments the Client Resource Manager (CRM) version to bust local cache + /// Increments the Client Resource Manager (CRM) version to bust local cache. /// - /// If true also forces a CRM version increment on portals that have non-default settings for CRM + /// If true also forces a CRM version increment on portals that have non-default settings for CRM. void IncrementCrmVersion(bool includeOverridingPortals); } } diff --git a/DNN Platform/Library/Entities/DataStructures/NTree.cs b/DNN Platform/Library/Entities/DataStructures/NTree.cs index c78db9c8b57..b0dfd2d97d0 100644 --- a/DNN Platform/Library/Entities/DataStructures/NTree.cs +++ b/DNN Platform/Library/Entities/DataStructures/NTree.cs @@ -1,33 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.DataStructures { + using System; + using System.Collections.Generic; + using System.Runtime.Serialization; + [Serializable] [DataContract] public class NTree { - public NTree() - { - Children = new List>(); - } - [DataMember(Name = "data")] public T Data; [DataMember(Name = "children")] public List> Children; + + public NTree() + { + this.Children = new List>(); + } public bool HasChildren() { - return Children != null && Children.Count > 0; + return this.Children != null && this.Children.Count > 0; } - } - } diff --git a/DNN Platform/Library/Entities/EventManager.cs b/DNN Platform/Library/Entities/EventManager.cs index 7ae9737052e..ce874f2520d 100644 --- a/DNN Platform/Library/Entities/EventManager.cs +++ b/DNN Platform/Library/Entities/EventManager.cs @@ -1,188 +1,213 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Friends; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Tabs.Actions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.EventArgs; -using DotNetNuke.Services.Log.EventLog; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable UseNullPropagation - namespace DotNetNuke.Entities { + using System; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Friends; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Tabs.Actions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.EventArgs; + using DotNetNuke.Services.Log.EventLog; + public class EventManager : ServiceLocator, IEventManager { - private event EventHandler FileAdded; - private event EventHandler FileChanged; - private event EventHandler FileDeleted; - private event EventHandler FileMetadataChanged; - private event EventHandler FileMoved; - private event EventHandler FileOverwritten; - private event EventHandler FileRenamed; - private event EventHandler FileDownloaded; - - private event EventHandler FolderAdded; - private event EventHandler FolderDeleted; - private event EventHandler FolderMoved; - private event EventHandler FolderRenamed; - - private event EventHandler FollowRequested; - private event EventHandler UnfollowRequested; - - private event EventHandler FriendshipAccepted; - private event EventHandler FriendshipDeleted; - private event EventHandler FriendshipRequested; - - private event EventHandler ModuleCreated; - private event EventHandler ModuleUpdated; - private event EventHandler ModuleRemoved; // soft delete - private event EventHandler ModuleDeleted; // hard delete - - private event EventHandler PortalCreated; - private event EventHandler PortalTemplateCreated; - private event EventHandler PortalSettingUpdated; - - private event EventHandler ProfileUpdated; - - private event EventHandler RoleCreated; - private event EventHandler RoleDeleted; - private event EventHandler RoleJoined; - private event EventHandler RoleLeft; - - private event EventHandler TabCreated; - private event EventHandler TabUpdated; - private event EventHandler TabRemoved; // soft delete - private event EventHandler TabDeleted; // hard delete - private event EventHandler TabRestored; - private event EventHandler TabMarkedAsPublished; - - private event EventHandler TabSerialize; // soft delete - private event EventHandler TabDeserialize; // hard delete - - private event EventHandler UserApproved; - private event EventHandler UserAuthenticated; - private event EventHandler UserCreated; - private event EventHandler UserDeleted; - private event EventHandler UserRemoved; - private event EventHandler UserUpdated; - - public EventManager() { foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - FileChanged += handler.Value.FileOverwritten; - FileDeleted += handler.Value.FileDeleted; - FileRenamed += handler.Value.FileRenamed; - FileMoved += handler.Value.FileMoved; - FileAdded += handler.Value.FileAdded; - FileOverwritten += handler.Value.FileOverwritten; - FileMetadataChanged += handler.Value.FileMetadataChanged; - FileDownloaded += handler.Value.FileDownloaded; + this.FileChanged += handler.Value.FileOverwritten; + this.FileDeleted += handler.Value.FileDeleted; + this.FileRenamed += handler.Value.FileRenamed; + this.FileMoved += handler.Value.FileMoved; + this.FileAdded += handler.Value.FileAdded; + this.FileOverwritten += handler.Value.FileOverwritten; + this.FileMetadataChanged += handler.Value.FileMetadataChanged; + this.FileDownloaded += handler.Value.FileDownloaded; - FolderAdded += handler.Value.FolderAdded; - FolderDeleted += handler.Value.FolderDeleted; - FolderMoved += handler.Value.FolderMoved; - FolderRenamed += handler.Value.FolderRenamed; + this.FolderAdded += handler.Value.FolderAdded; + this.FolderDeleted += handler.Value.FolderDeleted; + this.FolderMoved += handler.Value.FolderMoved; + this.FolderRenamed += handler.Value.FolderRenamed; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - FollowRequested += handler.Value.FollowRequested; - UnfollowRequested += handler.Value.UnfollowRequested; + this.FollowRequested += handler.Value.FollowRequested; + this.UnfollowRequested += handler.Value.UnfollowRequested; } foreach (var handlers in EventHandlersContainer.Instance.EventHandlers) { - FriendshipRequested += handlers.Value.FriendshipRequested; - FriendshipAccepted += handlers.Value.FriendshipAccepted; - FriendshipDeleted += handlers.Value.FriendshipDeleted; + this.FriendshipRequested += handlers.Value.FriendshipRequested; + this.FriendshipAccepted += handlers.Value.FriendshipAccepted; + this.FriendshipDeleted += handlers.Value.FriendshipDeleted; } foreach (var handlers in EventHandlersContainer.Instance.EventHandlers) { - ModuleCreated += handlers.Value.ModuleCreated; - ModuleUpdated += handlers.Value.ModuleUpdated; - ModuleRemoved += handlers.Value.ModuleRemoved; - ModuleDeleted += handlers.Value.ModuleDeleted; + this.ModuleCreated += handlers.Value.ModuleCreated; + this.ModuleUpdated += handlers.Value.ModuleUpdated; + this.ModuleRemoved += handlers.Value.ModuleRemoved; + this.ModuleDeleted += handlers.Value.ModuleDeleted; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - PortalCreated += handler.Value.PortalCreated; + this.PortalCreated += handler.Value.PortalCreated; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - PortalSettingUpdated += handler.Value.PortalSettingUpdated; + this.PortalSettingUpdated += handler.Value.PortalSettingUpdated; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - PortalTemplateCreated += handler.Value.TemplateCreated; + this.PortalTemplateCreated += handler.Value.TemplateCreated; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - ProfileUpdated += handler.Value.ProfileUpdated; + this.ProfileUpdated += handler.Value.ProfileUpdated; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - RoleCreated += handler.Value.RoleCreated; - RoleDeleted += handler.Value.RoleDeleted; - RoleJoined += handler.Value.RoleJoined; - RoleLeft += handler.Value.RoleLeft; + this.RoleCreated += handler.Value.RoleCreated; + this.RoleDeleted += handler.Value.RoleDeleted; + this.RoleJoined += handler.Value.RoleJoined; + this.RoleLeft += handler.Value.RoleLeft; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - TabCreated += handler.Value.TabCreated; - TabUpdated += handler.Value.TabUpdated; - TabRemoved += handler.Value.TabRemoved; - TabDeleted += handler.Value.TabDeleted; - TabRestored += handler.Value.TabRestored; - TabMarkedAsPublished += handler.Value.TabMarkedAsPublished; + this.TabCreated += handler.Value.TabCreated; + this.TabUpdated += handler.Value.TabUpdated; + this.TabRemoved += handler.Value.TabRemoved; + this.TabDeleted += handler.Value.TabDeleted; + this.TabRestored += handler.Value.TabRestored; + this.TabMarkedAsPublished += handler.Value.TabMarkedAsPublished; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - TabSerialize += handler.Value.TabSerialize; - TabDeserialize += handler.Value.TabDeserialize; + this.TabSerialize += handler.Value.TabSerialize; + this.TabDeserialize += handler.Value.TabDeserialize; } foreach (var handler in EventHandlersContainer.Instance.EventHandlers) { - UserAuthenticated += handler.Value.UserAuthenticated; - UserCreated += handler.Value.UserCreated; - UserDeleted += handler.Value.UserDeleted; - UserRemoved += handler.Value.UserRemoved; - UserApproved += handler.Value.UserApproved; - UserUpdated += handler.Value.UserUpdated; + this.UserAuthenticated += handler.Value.UserAuthenticated; + this.UserCreated += handler.Value.UserCreated; + this.UserDeleted += handler.Value.UserDeleted; + this.UserRemoved += handler.Value.UserRemoved; + this.UserApproved += handler.Value.UserApproved; + this.UserUpdated += handler.Value.UserUpdated; } - } + + private event EventHandler FileAdded; + + private event EventHandler FileChanged; + + private event EventHandler FileDeleted; + + private event EventHandler FileMetadataChanged; + + private event EventHandler FileMoved; + + private event EventHandler FileOverwritten; + + private event EventHandler FileRenamed; + + private event EventHandler FileDownloaded; - protected override Func GetFactory() - { - return () => new EventManager(); - } + private event EventHandler FolderAdded; + + private event EventHandler FolderDeleted; + + private event EventHandler FolderMoved; + + private event EventHandler FolderRenamed; + + private event EventHandler FollowRequested; + + private event EventHandler UnfollowRequested; + + private event EventHandler FriendshipAccepted; + + private event EventHandler FriendshipDeleted; + + private event EventHandler FriendshipRequested; + + private event EventHandler ModuleCreated; + + private event EventHandler ModuleUpdated; + + private event EventHandler ModuleRemoved; // soft delete + + private event EventHandler ModuleDeleted; // hard delete + + private event EventHandler PortalCreated; + + private event EventHandler PortalTemplateCreated; + + private event EventHandler PortalSettingUpdated; + + private event EventHandler ProfileUpdated; + + private event EventHandler RoleCreated; + + private event EventHandler RoleDeleted; + + private event EventHandler RoleJoined; + + private event EventHandler RoleLeft; + + private event EventHandler TabCreated; + + private event EventHandler TabUpdated; + + private event EventHandler TabRemoved; // soft delete + + private event EventHandler TabDeleted; // hard delete + + private event EventHandler TabRestored; + + private event EventHandler TabMarkedAsPublished; + + private event EventHandler TabSerialize; // soft delete + + private event EventHandler TabDeserialize; // hard delete + + private event EventHandler UserApproved; + + private event EventHandler UserAuthenticated; + + private event EventHandler UserCreated; + + private event EventHandler UserDeleted; + + private event EventHandler UserRemoved; + + private event EventHandler UserUpdated; public virtual void OnFileAdded(FileAddedEventArgs args) { - if (FileAdded != null) + if (this.FileAdded != null) { - FileAdded(this, args); + this.FileAdded(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_ADDED); @@ -190,19 +215,24 @@ public virtual void OnFileAdded(FileAddedEventArgs args) public virtual void OnFileChanged(FileChangedEventArgs args) { - if (FileChanged != null) + if (this.FileChanged != null) { - FileChanged(this, args); + this.FileChanged(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_CHANGED); } + protected override Func GetFactory() + { + return () => new EventManager(); + } + public virtual void OnFileDeleted(FileDeletedEventArgs args) { - if (FileDeleted != null) + if (this.FileDeleted != null) { - FileDeleted(this, args); + this.FileDeleted(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_DELETED); @@ -210,9 +240,9 @@ public virtual void OnFileDeleted(FileDeletedEventArgs args) public virtual void OnFileMetadataChanged(FileChangedEventArgs args) { - if (FileMetadataChanged != null) + if (this.FileMetadataChanged != null) { - FileMetadataChanged(this, args); + this.FileMetadataChanged(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_METADATACHANGED); @@ -220,9 +250,9 @@ public virtual void OnFileMetadataChanged(FileChangedEventArgs args) public virtual void OnFileDownloaded(FileDownloadedEventArgs args) { - if (FileDownloaded != null) + if (this.FileDownloaded != null) { - FileDownloaded(this, args); + this.FileDownloaded(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_DOWNLOADED); @@ -230,9 +260,9 @@ public virtual void OnFileDownloaded(FileDownloadedEventArgs args) public virtual void OnFileMoved(FileMovedEventArgs args) { - if (FileMoved != null) + if (this.FileMoved != null) { - FileMoved(this, args); + this.FileMoved(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_MOVED); @@ -240,9 +270,9 @@ public virtual void OnFileMoved(FileMovedEventArgs args) public virtual void OnFileOverwritten(FileChangedEventArgs args) { - if (FileOverwritten != null) + if (this.FileOverwritten != null) { - FileOverwritten(this, args); + this.FileOverwritten(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_OVERWRITTEN); @@ -250,9 +280,9 @@ public virtual void OnFileOverwritten(FileChangedEventArgs args) public virtual void OnFileRenamed(FileRenamedEventArgs args) { - if (FileRenamed != null) + if (this.FileRenamed != null) { - FileRenamed(this, args); + this.FileRenamed(this, args); } AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_RENAMED); @@ -260,281 +290,281 @@ public virtual void OnFileRenamed(FileRenamedEventArgs args) public virtual void OnFolderAdded(FolderChangedEventArgs args) { - if (FolderAdded != null) + if (this.FolderAdded != null) { - FolderAdded(this, args); + this.FolderAdded(this, args); } } public virtual void OnFolderDeleted(FolderDeletedEventArgs args) { - if (FolderDeleted != null) + if (this.FolderDeleted != null) { - FolderDeleted(this, args); + this.FolderDeleted(this, args); } } public virtual void OnFolderMoved(FolderMovedEventArgs args) { - if (FolderMoved != null) + if (this.FolderMoved != null) { - FolderMoved(this, args); + this.FolderMoved(this, args); } } public virtual void OnFolderRenamed(FolderRenamedEventArgs args) { - if (FolderRenamed != null) + if (this.FolderRenamed != null) { - FolderRenamed(this, args); + this.FolderRenamed(this, args); } } public virtual void OnFollowRequested(RelationshipEventArgs args) { - if (FollowRequested != null) + if (this.FollowRequested != null) { - FollowRequested(this, args); + this.FollowRequested(this, args); } } public virtual void OnFriendshipAccepted(RelationshipEventArgs args) { - if (FriendshipAccepted != null) + if (this.FriendshipAccepted != null) { - FriendshipAccepted(this, args); + this.FriendshipAccepted(this, args); } } public virtual void OnFriendshipDeleted(RelationshipEventArgs args) { - if (FriendshipDeleted != null) + if (this.FriendshipDeleted != null) { - FriendshipDeleted(this, args); + this.FriendshipDeleted(this, args); } } public virtual void OnFriendshipRequested(RelationshipEventArgs args) { - if (FriendshipRequested != null) + if (this.FriendshipRequested != null) { - FriendshipRequested(this, args); + this.FriendshipRequested(this, args); } } public virtual void OnModuleCreated(ModuleEventArgs args) { - if (ModuleCreated != null) + if (this.ModuleCreated != null) { - ModuleCreated(this, args); + this.ModuleCreated(this, args); } } public virtual void OnModuleDeleted(ModuleEventArgs args) { - if (ModuleDeleted != null) + if (this.ModuleDeleted != null) { - ModuleDeleted(this, args); + this.ModuleDeleted(this, args); } } public virtual void OnModuleRemoved(ModuleEventArgs args) { - if (ModuleRemoved != null) + if (this.ModuleRemoved != null) { - ModuleRemoved(this, args); + this.ModuleRemoved(this, args); } } public virtual void OnModuleUpdated(ModuleEventArgs args) { - if (ModuleUpdated != null) + if (this.ModuleUpdated != null) { - ModuleUpdated(this, args); + this.ModuleUpdated(this, args); } } public virtual void OnPortalCreated(PortalCreatedEventArgs args) { - if (PortalCreated != null) + if (this.PortalCreated != null) { - PortalCreated(this, args); + this.PortalCreated(this, args); } } public virtual void OnPortalSettingUpdated(PortalSettingUpdatedEventArgs args) { - if (PortalSettingUpdated != null) + if (this.PortalSettingUpdated != null) { - PortalSettingUpdated(this, args); + this.PortalSettingUpdated(this, args); } } public virtual void OnPortalTemplateCreated(PortalTemplateEventArgs args) { - if (PortalTemplateCreated != null) + if (this.PortalTemplateCreated != null) { - PortalTemplateCreated(this, args); + this.PortalTemplateCreated(this, args); } } public virtual void OnProfileUpdated(ProfileEventArgs args) { - if (ProfileUpdated != null) + if (this.ProfileUpdated != null) { - ProfileUpdated(this, args); + this.ProfileUpdated(this, args); } } public virtual void OnRoleCreated(RoleEventArgs args) { - if (RoleCreated != null) + if (this.RoleCreated != null) { - RoleCreated(this, args); + this.RoleCreated(this, args); } } public virtual void OnRoleDeleted(RoleEventArgs args) { - if (RoleDeleted != null) + if (this.RoleDeleted != null) { - RoleDeleted(this, args); + this.RoleDeleted(this, args); } } public virtual void OnRoleJoined(RoleEventArgs args) { - if (RoleJoined != null) + if (this.RoleJoined != null) { - RoleJoined(this, args); + this.RoleJoined(this, args); } } public virtual void OnRoleLeft(RoleEventArgs args) { - if (RoleLeft != null) + if (this.RoleLeft != null) { - RoleLeft(this, args); + this.RoleLeft(this, args); } } public virtual void OnTabCreated(TabEventArgs args) { - if (TabCreated != null) + if (this.TabCreated != null) { - TabCreated(this, args); + this.TabCreated(this, args); } } public virtual void OnTabDeleted(TabEventArgs args) { - if (TabDeleted != null) + if (this.TabDeleted != null) { - TabDeleted(this, args); + this.TabDeleted(this, args); } } public virtual void OnTabDeserialize(TabSyncEventArgs args) { - if (TabDeserialize != null) + if (this.TabDeserialize != null) { - TabDeserialize(this, args); + this.TabDeserialize(this, args); } } public virtual void OnTabMarkedAsPublished(TabEventArgs args) { - if (TabMarkedAsPublished != null) + if (this.TabMarkedAsPublished != null) { - TabMarkedAsPublished(this, args); + this.TabMarkedAsPublished(this, args); } } public virtual void OnTabRemoved(TabEventArgs args) { - if (TabRemoved != null) + if (this.TabRemoved != null) { - TabRemoved(this, args); + this.TabRemoved(this, args); } } public virtual void OnTabRestored(TabEventArgs args) { - if (TabRestored != null) + if (this.TabRestored != null) { - TabRestored(this, args); + this.TabRestored(this, args); } } public virtual void OnTabSerialize(TabSyncEventArgs args) { - if (TabSerialize != null) + if (this.TabSerialize != null) { - TabSerialize(this, args); + this.TabSerialize(this, args); } } public virtual void OnTabUpdated(TabEventArgs args) { - if (TabUpdated != null) + if (this.TabUpdated != null) { - TabUpdated(this, args); + this.TabUpdated(this, args); } } public virtual void OnUnfollowRequested(RelationshipEventArgs args) { - if (UnfollowRequested != null) + if (this.UnfollowRequested != null) { - UnfollowRequested(this, args); + this.UnfollowRequested(this, args); } } public virtual void OnUserApproved(UserEventArgs args) { - if (UserApproved != null) + if (this.UserApproved != null) { - UserApproved(this, args); + this.UserApproved(this, args); } } public virtual void OnUserAuthenticated(UserEventArgs args) { - if (UserAuthenticated != null) + if (this.UserAuthenticated != null) { - UserAuthenticated(this, args); + this.UserAuthenticated(this, args); } } public virtual void OnUserCreated(UserEventArgs args) { - if (UserCreated != null) + if (this.UserCreated != null) { - UserCreated(this, args); + this.UserCreated(this, args); } } public virtual void OnUserDeleted(UserEventArgs args) { - if (UserDeleted != null) + if (this.UserDeleted != null) { - UserDeleted(this, args); + this.UserDeleted(this, args); } } public virtual void OnUserRemoved(UserEventArgs args) { - if (UserRemoved != null) + if (this.UserRemoved != null) { - UserRemoved(this, args); + this.UserRemoved(this, args); } } public virtual void OnUserUpdated(UpdateUserEventArgs args) { - if (UserUpdated != null) + if (this.UserUpdated != null) { - UserUpdated(this, args); + this.UserUpdated(this, args); } } @@ -542,8 +572,8 @@ public void RefreshTabSyncHandlers() { foreach (var handlers in new EventHandlersContainer().EventHandlers) { - TabSerialize += handlers.Value.TabSerialize; - TabDeserialize += handlers.Value.TabDeserialize; + this.TabSerialize += handlers.Value.TabSerialize; + this.TabDeserialize += handlers.Value.TabDeserialize; } } @@ -554,7 +584,7 @@ private static void AddLog(IFileInfo fileInfo, int userId, EventLogController.Ev return; } - EventLogController.Instance.AddLog(fileInfo, PortalSettings.Current, userId, "", logType); + EventLogController.Instance.AddLog(fileInfo, PortalSettings.Current, userId, string.Empty, logType); } } } diff --git a/DNN Platform/Library/Entities/Host/Host.cs b/DNN Platform/Library/Entities/Host/Host.cs index 3423d4e50ab..7de4b75dd14 100644 --- a/DNN Platform/Library/Entities/Host/Host.cs +++ b/DNN Platform/Library/Entities/Host/Host.cs @@ -1,47 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Web; -using System.Web.Caching; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Framework; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; using DotNetNuke.Entities.Portals; - - using Web.Client; + using DotNetNuke.Framework; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.UI.Skins; + using DotNetNuke.Web.Client; /// - /// Contains most of the host settings. - /// + /// Contains most of the host settings. + ///
    [Serializable] public class Host : BaseEntityInfo { - #region Public Shared Properties + private static Globals.PerformanceSettings? _performanceSetting; /// ----------------------------------------------------------------------------- /// - /// Gets the AutoAccountUnlockDuration + /// Gets the AutoAccountUnlockDuration. /// /// - /// Defaults to 10 + /// Defaults to 10. /// /// ----------------------------------------------------------------------------- public static int AutoAccountUnlockDuration @@ -54,10 +47,10 @@ public static int AutoAccountUnlockDuration /// ----------------------------------------------------------------------------- /// - /// Gets the AuthenticatedCacheability + /// Gets the AuthenticatedCacheability. /// /// - /// Defaults to HttpCacheability.ServerAndNoCache + /// Defaults to HttpCacheability.ServerAndNoCache. /// /// ----------------------------------------------------------------------------- public static string AuthenticatedCacheability @@ -77,7 +70,7 @@ public static string UnauthenticatedCacheability } /// - /// gets whether or not CDN has been enabled for all registered javascript libraries + /// Gets a value indicating whether gets whether or not CDN has been enabled for all registered javascript libraries. /// public static bool CdnEnabled { @@ -87,13 +80,12 @@ public static bool CdnEnabled } } - /// ----------------------------------------------------------------------------- /// - /// Gets whether the Upgrade Indicator is enabled + /// Gets a value indicating whether gets whether the Upgrade Indicator is enabled. /// /// - /// Defaults to True + /// Defaults to True. /// /// ----------------------------------------------------------------------------- public static bool CheckUpgrade @@ -106,10 +98,10 @@ public static bool CheckUpgrade /// ----------------------------------------------------------------------------- /// - /// Gets the Control Panel + /// Gets the Control Panel. /// /// - /// Defaults to glbDefaultControlPanel constant + /// Defaults to glbDefaultControlPanel constant. /// /// ----------------------------------------------------------------------------- public static string ControlPanel @@ -121,9 +113,9 @@ public static string ControlPanel } /// - /// setting to control where the control panel is loaded by the core and allowed to control it's own visibility. + /// Gets a value indicating whether setting to control where the control panel is loaded by the core and allowed to control it's own visibility. /// this is useful when the control panel needs to be visible for all users regardless of edit page/module permissions. - /// it's also for backwards compatibility, prior to 7.2 the control panel was always loaded. + /// it's also for backwards compatibility, prior to 7.2 the control panel was always loaded. /// public static bool AllowControlPanelToDetermineVisibility { @@ -135,7 +127,7 @@ public static bool AllowControlPanelToDetermineVisibility /// ----------------------------------------------------------------------------- /// - /// Indicates whether Composite Files are enabled at the host level. + /// Gets a value indicating whether indicates whether Composite Files are enabled at the host level. /// /// ----------------------------------------------------------------------------- public static bool CrmEnableCompositeFiles @@ -148,7 +140,7 @@ public static bool CrmEnableCompositeFiles /// ----------------------------------------------------------------------------- /// - /// Indicates whether CSS Minification is enabled at the host level. + /// Gets a value indicating whether indicates whether CSS Minification is enabled at the host level. /// /// ----------------------------------------------------------------------------- public static bool CrmMinifyCss @@ -161,7 +153,7 @@ public static bool CrmMinifyCss /// ----------------------------------------------------------------------------- /// - /// Indicates whether JS Minification is enabled at the host level. + /// Gets a value indicating whether indicates whether JS Minification is enabled at the host level. /// /// ----------------------------------------------------------------------------- public static bool CrmMinifyJs @@ -174,10 +166,10 @@ public static bool CrmMinifyJs /// ----------------------------------------------------------------------------- /// - /// Returns the Client Resource Management version number. + /// Gets the Client Resource Management version number. /// /// - /// Defaults to 1 + /// Defaults to 1. /// /// ----------------------------------------------------------------------------- public static int CrmVersion @@ -190,7 +182,7 @@ public static int CrmVersion /// ----------------------------------------------------------------------------- /// - /// Gets the Default Admin Container + /// Gets the Default Admin Container. /// /// ----------------------------------------------------------------------------- public static string DefaultAdminContainer @@ -202,13 +194,14 @@ public static string DefaultAdminContainer { setting = SkinController.GetDefaultAdminContainer(); } + return setting; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Default Admin Skin + /// Gets the Default Admin Skin. /// /// ----------------------------------------------------------------------------- public static string DefaultAdminSkin @@ -220,13 +213,14 @@ public static string DefaultAdminSkin { setting = SkinController.GetDefaultAdminSkin(); } + return setting; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Default Doc Type + /// Gets the Default Doc Type. /// /// ----------------------------------------------------------------------------- public static string DefaultDocType @@ -253,13 +247,14 @@ public static string DefaultDocType break; } } + return doctype; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Default Portal Container + /// Gets the Default Portal Container. /// /// ----------------------------------------------------------------------------- public static string DefaultPortalContainer @@ -271,13 +266,14 @@ public static string DefaultPortalContainer { setting = SkinController.GetDefaultPortalContainer(); } + return setting; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Default Portal Skin + /// Gets the Default Portal Skin. /// /// ----------------------------------------------------------------------------- public static string DefaultPortalSkin @@ -289,16 +285,17 @@ public static string DefaultPortalSkin { setting = SkinController.GetDefaultPortalSkin(); } + return setting; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Demo Period for new portals + /// Gets the Demo Period for new portals. /// /// - /// Defaults to -1 + /// Defaults to -1. /// /// ----------------------------------------------------------------------------- public static int DemoPeriod @@ -311,10 +308,10 @@ public static int DemoPeriod /// ----------------------------------------------------------------------------- /// - /// Gets whether demo signups are enabled + /// Gets a value indicating whether gets whether demo signups are enabled. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool DemoSignup @@ -327,10 +324,10 @@ public static bool DemoSignup /// ----------------------------------------------------------------------------- /// - /// Gets whether to dislpay the beta notice + /// Gets a value indicating whether gets whether to dislpay the beta notice. /// /// - /// Defaults to True + /// Defaults to True. /// /// ----------------------------------------------------------------------------- public static bool DisplayBetaNotice @@ -343,10 +340,10 @@ public static bool DisplayBetaNotice /// ----------------------------------------------------------------------------- /// - /// Gets whether to dislpay the copyright + /// Gets a value indicating whether gets whether to dislpay the copyright. /// /// - /// Defaults to True + /// Defaults to True. /// /// ----------------------------------------------------------------------------- public static bool DisplayCopyright @@ -358,7 +355,7 @@ public static bool DisplayCopyright } /// - /// Enable checking for banned words when setting password during registration + /// Gets a value indicating whether enable checking for banned words when setting password during registration. /// public static bool EnableBannedList { @@ -367,14 +364,13 @@ public static bool EnableBannedList return HostController.Instance.GetBoolean("EnableBannedList", true); } } - /// ----------------------------------------------------------------------------- /// - /// Gets whether Browser Language Detection is Enabled + /// Gets a value indicating whether gets whether Browser Language Detection is Enabled. /// /// - /// Defaults to True + /// Defaults to True. /// /// ----------------------------------------------------------------------------- public static bool EnableBrowserLanguage @@ -395,7 +391,7 @@ public static bool EnableContentLocalization /// ----------------------------------------------------------------------------- /// - /// Gets whether the installation runs in debug mode. This property can be used + /// Gets a value indicating whether gets whether the installation runs in debug mode. This property can be used /// by the framework and extensions alike to write more verbose logs/onscreen /// information, etc. It is set in the host settings page. /// @@ -410,7 +406,7 @@ public static bool DebugMode /// ----------------------------------------------------------------------------- /// - /// Gets whether the installation participates in the improvements program. + /// Gets a value indicating whether gets whether the installation participates in the improvements program. /// /// ----------------------------------------------------------------------------- public static bool ParticipateInImprovementProg @@ -423,10 +419,10 @@ public static bool ParticipateInImprovementProg /// ----------------------------------------------------------------------------- /// - /// Gets whether a css class based on the Module Name is automatically rendered + /// Gets a value indicating whether gets whether a css class based on the Module Name is automatically rendered. /// /// - /// Defaults to True + /// Defaults to True. /// /// ----------------------------------------------------------------------------- public static bool EnableCustomModuleCssClass @@ -438,7 +434,7 @@ public static bool EnableCustomModuleCssClass } /// - /// Whether force upgrade wizard open in ssl channel. + /// Gets a value indicating whether whether force upgrade wizard open in ssl channel. /// public static bool UpgradeForceSsl { @@ -449,7 +445,7 @@ public static bool UpgradeForceSsl } /// - /// The domain used when upgrade wizard forced to shown in ssl channel. + /// Gets the domain used when upgrade wizard forced to shown in ssl channel. /// public static string SslDomain { @@ -461,10 +457,10 @@ public static string SslDomain /// ----------------------------------------------------------------------------- /// - /// Gets whether File AutoSync is Enabled + /// Gets a value indicating whether gets whether File AutoSync is Enabled. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool EnableFileAutoSync @@ -476,7 +472,7 @@ public static bool EnableFileAutoSync } /// - /// enable whether the IP address of the user is checked against a list during login + /// Gets a value indicating whether enable whether the IP address of the user is checked against a list during login. /// public static bool EnableIPChecking { @@ -488,10 +484,10 @@ public static bool EnableIPChecking /// ----------------------------------------------------------------------------- /// - /// Gets whether Module Online Help is Enabled + /// Gets a value indicating whether gets whether Module Online Help is Enabled. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool EnableModuleOnLineHelp @@ -504,10 +500,10 @@ public static bool EnableModuleOnLineHelp /// ----------------------------------------------------------------------------- /// - /// Gets whether the Request Filters are Enabled + /// Gets a value indicating whether gets whether the Request Filters are Enabled. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool EnableRequestFilters @@ -519,7 +515,7 @@ public static bool EnableRequestFilters } /// - /// enable whether a client-side password strength meter is shown on registration screen + /// Gets a value indicating whether enable whether a client-side password strength meter is shown on registration screen. /// public static bool EnableStrengthMeter { @@ -530,7 +526,7 @@ public static bool EnableStrengthMeter } /// - /// enable whether a previous passwords are stored to check if user is reusing them + /// Gets a value indicating whether enable whether a previous passwords are stored to check if user is reusing them. /// public static bool EnablePasswordHistory { @@ -542,10 +538,10 @@ public static bool EnablePasswordHistory /// ----------------------------------------------------------------------------- /// - /// Gets whether to use the Language in the Url + /// Gets a value indicating whether gets whether to use the Language in the Url. /// /// - /// Defaults to True + /// Defaults to True. /// /// ----------------------------------------------------------------------------- public static bool EnableUrlLanguage @@ -558,12 +554,12 @@ public static bool EnableUrlLanguage /// ----------------------------------------------------------------------------- /// - /// Gets whether Users Online are Enabled + /// Gets a value indicating whether gets whether Users Online are Enabled. /// /// - /// Defaults to False + /// Defaults to False. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public static bool EnableUsersOnline { @@ -575,10 +571,10 @@ public static bool EnableUsersOnline /// ----------------------------------------------------------------------------- /// - /// Gets whether SSL is Enabled for SMTP + /// Gets a value indicating whether gets whether SSL is Enabled for SMTP. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool EnableSMTPSSL @@ -589,16 +585,17 @@ public static bool EnableSMTPSSL { return PortalController.GetPortalSettingAsBoolean("SMTPEnableSSL", PortalSettings.Current.PortalId, false); } + return HostController.Instance.GetBoolean("SMTPEnableSSL", false); } } - + /// ----------------------------------------------------------------------------- /// - /// Gets whether the Event Log Buffer is Enabled + /// Gets a value indicating whether gets whether the Event Log Buffer is Enabled. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool EventLogBuffer @@ -621,7 +618,7 @@ public static FileExtensionWhitelist AllowedExtensionWhitelist } /// - /// Default list of extensions an end user is allowed to upload. + /// Gets default list of extensions an end user is allowed to upload. /// public static FileExtensionWhitelist DefaultEndUserExtensionWhitelist { @@ -633,7 +630,7 @@ public static FileExtensionWhitelist DefaultEndUserExtensionWhitelist /// ----------------------------------------------------------------------------- /// - /// Gets the GUID + /// Gets the GUID. /// /// ----------------------------------------------------------------------------- public static string GUID @@ -646,7 +643,7 @@ public static string GUID /// ----------------------------------------------------------------------------- /// - /// Gets the Help URL + /// Gets the Help URL. /// /// ----------------------------------------------------------------------------- public static string HelpURL @@ -659,10 +656,10 @@ public static string HelpURL /// ----------------------------------------------------------------------------- /// - /// Gets the Host Currency + /// Gets the Host Currency. /// /// - /// Defaults to USD + /// Defaults to USD. /// /// ----------------------------------------------------------------------------- public static string HostCurrency @@ -674,13 +671,14 @@ public static string HostCurrency { setting = "USD"; } + return setting; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Host Email + /// Gets the Host Email. /// /// ----------------------------------------------------------------------------- public static string HostEmail @@ -693,10 +691,10 @@ public static string HostEmail /// ----------------------------------------------------------------------------- /// - /// Gets the Host Fee + /// Gets the Host Fee. /// /// - /// Defaults to 0 + /// Defaults to 0. /// /// ----------------------------------------------------------------------------- public static double HostFee @@ -709,10 +707,10 @@ public static double HostFee /// ----------------------------------------------------------------------------- /// - /// Gets the Host Portal's PortalId + /// Gets the Host Portal's PortalId. /// /// - /// Defaults to Null.NullInteger + /// Defaults to Null.NullInteger. /// /// ----------------------------------------------------------------------------- public static int HostPortalID @@ -725,10 +723,10 @@ public static int HostPortalID /// ----------------------------------------------------------------------------- /// - /// Gets the Host Space + /// Gets the Host Space. /// /// - /// Defaults to 0 + /// Defaults to 0. /// /// ----------------------------------------------------------------------------- public static double HostSpace @@ -741,7 +739,7 @@ public static double HostSpace /// ----------------------------------------------------------------------------- /// - /// Gets the Host Title + /// Gets the Host Title. /// /// ----------------------------------------------------------------------------- public static string HostTitle @@ -754,7 +752,7 @@ public static string HostTitle /// ----------------------------------------------------------------------------- /// - /// Gets the Host URL + /// Gets the Host URL. /// /// ----------------------------------------------------------------------------- public static string HostURL @@ -767,10 +765,10 @@ public static string HostURL /// ----------------------------------------------------------------------------- /// - /// Gets the HttpCompression Algorithm + /// Gets the HttpCompression Algorithm. /// /// - /// Defaults to Null.NullInteger(None) + /// Defaults to Null.NullInteger(None). /// /// ----------------------------------------------------------------------------- public static int HttpCompressionAlgorithm @@ -783,22 +781,22 @@ public static int HttpCompressionAlgorithm /// ----------------------------------------------------------------------------- /// - /// Returns size of the batch used to determine how many emails are sent per CoreMessaging Scheduler run + /// Gets size of the batch used to determine how many emails are sent per CoreMessaging Scheduler run. /// /// - /// Defaults to 50 + /// Defaults to 50. /// /// ----------------------------------------------------------------------------- public static int MessageSchedulerBatchSize { get { - return HostController.Instance.GetInteger("MessageSchedulerBatchSize",50); + return HostController.Instance.GetInteger("MessageSchedulerBatchSize", 50); } } /// - /// set length of time (in minutes) that reset links are valid for - default is 60 + /// Gets set length of time (in minutes) that reset links are valid for - default is 60. /// public static int MembershipResetLinkValidity { @@ -809,7 +807,7 @@ public static int MembershipResetLinkValidity } /// - /// set length of time (in minutes) that reset links are valid for - default is 24 hours (1440 min) + /// Gets set length of time (in minutes) that reset links are valid for - default is 24 hours (1440 min). /// public static int AdminMembershipResetLinkValidity { @@ -820,7 +818,7 @@ public static int AdminMembershipResetLinkValidity } /// - /// set number of passwords stored for password change comparison operations - default is 5 + /// Gets set number of passwords stored for password change comparison operations - default is 5. /// public static int MembershipNumberPasswords { @@ -831,7 +829,7 @@ public static int MembershipNumberPasswords } /// - /// Gets the number of days that must pass before a password can be reused - default is 0 (i.e. password reuse is only governed by and ) + /// Gets the number of days that must pass before a password can be reused - default is 0 (i.e. password reuse is only governed by and ). /// public static int MembershipDaysBeforePasswordReuse { @@ -842,8 +840,8 @@ public static int MembershipDaysBeforePasswordReuse } /// - /// sets the HTTP Status code returned if IP address filtering is enabled on login - /// and the users IP does not meet criteria -default is 403 + /// Gets the HTTP Status code returned if IP address filtering is enabled on login + /// and the users IP does not meet criteria -default is 403. /// public static string MembershipFailedIPException { @@ -853,11 +851,9 @@ public static string MembershipFailedIPException } } - - /// ----------------------------------------------------------------------------- /// - /// Gets the Module Caching method + /// Gets the Module Caching method. /// /// ----------------------------------------------------------------------------- public static string ModuleCachingMethod @@ -870,7 +866,7 @@ public static string ModuleCachingMethod /// ----------------------------------------------------------------------------- /// - /// Gets the Page Caching method + /// Gets the Page Caching method. /// /// ----------------------------------------------------------------------------- public static string PageCachingMethod @@ -883,10 +879,10 @@ public static string PageCachingMethod /// ----------------------------------------------------------------------------- /// - /// Gets the Page Quota + /// Gets the Page Quota. /// /// - /// Defaults to 0 + /// Defaults to 0. /// /// ----------------------------------------------------------------------------- public static int PageQuota @@ -899,7 +895,7 @@ public static int PageQuota /// ----------------------------------------------------------------------------- /// - /// Gets the PageState Persister + /// Gets the PageState Persister. /// /// ----------------------------------------------------------------------------- public static string PageStatePersister @@ -911,16 +907,17 @@ public static string PageStatePersister { setting = "P"; } + return setting; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Password Expiry + /// Gets the Password Expiry. /// /// - /// Defaults to 0 + /// Defaults to 0. /// /// ----------------------------------------------------------------------------- public static int PasswordExpiry @@ -933,10 +930,10 @@ public static int PasswordExpiry /// ----------------------------------------------------------------------------- /// - /// Gets the Password Expiry Reminder window + /// Gets the Password Expiry Reminder window. /// /// - /// Defaults to 7 (1 week) + /// Defaults to 7 (1 week). /// /// ----------------------------------------------------------------------------- public static int PasswordExpiryReminder @@ -949,7 +946,7 @@ public static int PasswordExpiryReminder /// ----------------------------------------------------------------------------- /// - /// Gets the Payment Processor + /// Gets the Payment Processor. /// /// ----------------------------------------------------------------------------- public static string PaymentProcessor @@ -960,14 +957,12 @@ public static string PaymentProcessor } } - private static Globals.PerformanceSettings? _performanceSetting; - /// ----------------------------------------------------------------------------- /// - /// Gets the PerformanceSettings + /// Gets or sets the PerformanceSettings. /// /// - /// Defaults to PerformanceSettings.ModerateCaching + /// Defaults to PerformanceSettings.ModerateCaching. /// /// ----------------------------------------------------------------------------- public static Globals.PerformanceSettings PerformanceSetting @@ -987,12 +982,13 @@ public static Globals.PerformanceSettings PerformanceSetting return _performanceSetting.Value; } + set { _performanceSetting = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Payment Processor Password + /// Gets the Payment Processor Password. /// /// ----------------------------------------------------------------------------- public static string ProcessorPassword @@ -1005,7 +1001,7 @@ public static string ProcessorPassword /// ----------------------------------------------------------------------------- /// - /// Gets the Payment Processor User Id + /// Gets the Payment Processor User Id. /// /// ----------------------------------------------------------------------------- public static string ProcessorUserId @@ -1018,7 +1014,7 @@ public static string ProcessorUserId /// ----------------------------------------------------------------------------- /// - /// Gets the Proxy Server Password + /// Gets the Proxy Server Password. /// /// ----------------------------------------------------------------------------- public static string ProxyPassword @@ -1031,7 +1027,7 @@ public static string ProxyPassword /// ----------------------------------------------------------------------------- /// - /// Gets the Proxy Server Port + /// Gets the Proxy Server Port. /// /// ----------------------------------------------------------------------------- public static int ProxyPort @@ -1044,7 +1040,7 @@ public static int ProxyPort /// ----------------------------------------------------------------------------- /// - /// Gets the Proxy Server + /// Gets the Proxy Server. /// /// ----------------------------------------------------------------------------- public static string ProxyServer @@ -1057,7 +1053,7 @@ public static string ProxyServer /// ----------------------------------------------------------------------------- /// - /// Gets the Proxy Server UserName + /// Gets the Proxy Server UserName. /// /// ----------------------------------------------------------------------------- public static string ProxyUsername @@ -1070,10 +1066,10 @@ public static string ProxyUsername /// ----------------------------------------------------------------------------- /// - /// Gets whether to use the remember me checkbox + /// Gets a value indicating whether gets whether to use the remember me checkbox. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool RememberCheckbox @@ -1086,10 +1082,10 @@ public static bool RememberCheckbox /// ----------------------------------------------------------------------------- /// - /// Gets the Scheduler Mode + /// Gets the Scheduler Mode. /// /// - /// Defaults to SchedulerMode.TIMER_METHOD + /// Defaults to SchedulerMode.TIMER_METHOD. /// /// ----------------------------------------------------------------------------- public static SchedulerMode SchedulerMode @@ -1100,17 +1096,19 @@ public static SchedulerMode SchedulerMode string s = HostController.Instance.GetString("SchedulerMode"); if (!string.IsNullOrEmpty(s)) { - setting = (SchedulerMode) Enum.Parse(typeof (SchedulerMode), s); + setting = (SchedulerMode)Enum.Parse(typeof(SchedulerMode), s); } + return setting; } } + /// ----------------------------------------------------------------------------- /// - /// Gets the delayAtAppStart value + /// Gets the delayAtAppStart value. /// /// - /// Defaults is 1 min(60 sec) + /// Defaults is 1 min(60 sec). /// /// ----------------------------------------------------------------------------- public static int SchedulerdelayAtAppStart @@ -1120,12 +1118,13 @@ public static int SchedulerdelayAtAppStart return HostController.Instance.GetInteger("SchedulerdelayAtAppStart", 1); } } + /// ----------------------------------------------------------------------------- /// - /// Gets whether to inlcude Common Words in the Search Index + /// Gets a value indicating whether gets whether to inlcude Common Words in the Search Index. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool SearchIncludeCommon @@ -1138,10 +1137,10 @@ public static bool SearchIncludeCommon /// ----------------------------------------------------------------------------- /// - /// Gets whether to inlcude Numbers in the Search Index + /// Gets a value indicating whether gets whether to inlcude Numbers in the Search Index. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool SearchIncludeNumeric @@ -1154,10 +1153,10 @@ public static bool SearchIncludeNumeric /// ----------------------------------------------------------------------------- /// - /// Gets the maximum Search Word length to index + /// Gets the maximum Search Word length to index. /// /// - /// Defaults to 25 + /// Defaults to 25. /// /// ----------------------------------------------------------------------------- public static int SearchMaxWordlLength @@ -1170,10 +1169,10 @@ public static int SearchMaxWordlLength /// ----------------------------------------------------------------------------- /// - /// Gets the maximum Search Word length to index + /// Gets the maximum Search Word length to index. /// /// - /// Defaults to 3 + /// Defaults to 3. /// /// ----------------------------------------------------------------------------- public static int SearchMinWordlLength @@ -1186,22 +1185,22 @@ public static int SearchMinWordlLength /// ----------------------------------------------------------------------------- /// - /// Gets the filter used for inclusion of tag info + /// Gets the filter used for inclusion of tag info. /// /// - /// Defaults to "" + /// Defaults to "". /// /// ----------------------------------------------------------------------------- public static string SearchIncludedTagInfoFilter { get { - return HostController.Instance.GetString("SearchIncludedTagInfoFilter", ""); + return HostController.Instance.GetString("SearchIncludedTagInfoFilter", string.Empty); } } /// - /// display the text of errors injected via the error querystring parameter + /// Gets a value indicating whether display the text of errors injected via the error querystring parameter. /// public static bool ShowCriticalErrors { @@ -1213,10 +1212,10 @@ public static bool ShowCriticalErrors /// ----------------------------------------------------------------------------- /// - /// Gets the Site Log Buffer size + /// Gets the Site Log Buffer size. /// /// - /// Defaults to 1 + /// Defaults to 1. /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] @@ -1230,10 +1229,10 @@ public static int SiteLogBuffer /// ----------------------------------------------------------------------------- /// - /// Gets the Site Log History + /// Gets the Site Log History. /// /// - /// Defaults to -1 + /// Defaults to -1. /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] @@ -1247,10 +1246,10 @@ public static int SiteLogHistory /// ----------------------------------------------------------------------------- /// - /// Gets the Site Log Storage location + /// Gets the Site Log Storage location. /// /// - /// Defaults to "D" + /// Defaults to "D". /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] @@ -1264,7 +1263,7 @@ public static string SiteLogStorage /// ----------------------------------------------------------------------------- /// - /// Gets the SMTP Authentication + /// Gets the SMTP Authentication. /// /// ----------------------------------------------------------------------------- public static string SMTPAuthentication @@ -1277,51 +1276,7 @@ public static string SMTPAuthentication /// ----------------------------------------------------------------------------- /// - /// Gets the SMTP mode (portal|host) - /// - /// ----------------------------------------------------------------------------- - internal static bool SMTPPortalEnabled - { - get - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - - if (portalSettings == null || portalSettings.ActiveTab == null) - { - //without portal settings or active tab, we can't continue - return false; - } - - //we don't want to load the portal smtp server when on a host tab. - if (portalSettings.ActiveTab.PortalID == Null.NullInteger) - { - return false; - } - - var currentSmtpMode = PortalController.GetPortalSetting("SMTPmode", portalSettings.PortalId, Null.NullString); - - return currentSmtpMode.Equals("P", StringComparison.OrdinalIgnoreCase); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Get's the SMTP setting, if portal smtp is configured, it will return items from the portal settings collection. - /// - /// ----------------------------------------------------------------------------- - private static string GetSmtpSetting(string settingName) - { - if (SMTPPortalEnabled) - { - return PortalController.GetPortalSetting(settingName, PortalSettings.Current.PortalId, Null.NullString); - } - - return HostController.Instance.GetString(settingName); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the SMTP Password + /// Gets the SMTP Password. /// /// ----------------------------------------------------------------------------- public static string SMTPPassword @@ -1341,7 +1296,7 @@ public static string SMTPPassword } catch (Exception) { - //fixes case where smtppassword failed to encrypt due to failing upgrade + // fixes case where smtppassword failed to encrypt due to failing upgrade var current = HostController.Instance.GetString("SMTPPassword"); if (!string.IsNullOrEmpty(current)) { @@ -1353,6 +1308,7 @@ public static string SMTPPassword decryptedText = string.Empty; } } + return decryptedText; } } @@ -1360,7 +1316,7 @@ public static string SMTPPassword /// ----------------------------------------------------------------------------- /// - /// Gets the SMTP Server + /// Gets the SMTP Server. /// /// ----------------------------------------------------------------------------- public static string SMTPServer @@ -1373,7 +1329,7 @@ public static string SMTPServer /// ----------------------------------------------------------------------------- /// - /// Gets the SMTP Username + /// Gets the SMTP Username. /// /// ----------------------------------------------------------------------------- public static string SMTPUsername @@ -1386,7 +1342,51 @@ public static string SMTPUsername /// ----------------------------------------------------------------------------- /// - /// Gets the SMTP Connection Limit + /// Gets a value indicating whether gets the SMTP mode (portal|host). + /// + /// ----------------------------------------------------------------------------- + internal static bool SMTPPortalEnabled + { + get + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + + if (portalSettings == null || portalSettings.ActiveTab == null) + { + // without portal settings or active tab, we can't continue + return false; + } + + // we don't want to load the portal smtp server when on a host tab. + if (portalSettings.ActiveTab.PortalID == Null.NullInteger) + { + return false; + } + + var currentSmtpMode = PortalController.GetPortalSetting("SMTPmode", portalSettings.PortalId, Null.NullString); + + return currentSmtpMode.Equals("P", StringComparison.OrdinalIgnoreCase); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Get's the SMTP setting, if portal smtp is configured, it will return items from the portal settings collection. + /// + /// ----------------------------------------------------------------------------- + private static string GetSmtpSetting(string settingName) + { + if (SMTPPortalEnabled) + { + return PortalController.GetPortalSetting(settingName, PortalSettings.Current.PortalId, Null.NullString); + } + + return HostController.Instance.GetString(settingName); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the SMTP Connection Limit. /// /// ----------------------------------------------------------------------------- public static int SMTPConnectionLimit @@ -1397,12 +1397,14 @@ public static int SMTPConnectionLimit { return PortalController.GetPortalSettingAsInteger("SMTPConnectionLimit", PortalSettings.Current.PortalId, 2); } + return HostController.Instance.GetInteger("SMTPConnectionLimit", 2); } } + /// ----------------------------------------------------------------------------- /// - /// Gets the SMTP MaxIdleTime + /// Gets the SMTP MaxIdleTime. /// /// ----------------------------------------------------------------------------- public static int SMTPMaxIdleTime @@ -1413,15 +1415,17 @@ public static int SMTPMaxIdleTime { return PortalController.GetPortalSettingAsInteger("SMTPMaxIdleTime", PortalSettings.Current.PortalId, 100000); } + return HostController.Instance.GetInteger("SMTPMaxIdleTime", 100000); } } + /// ----------------------------------------------------------------------------- /// - /// Gets whether Exceptions are rethrown + /// Gets a value indicating whether gets whether Exceptions are rethrown. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool ThrowCBOExceptions @@ -1434,10 +1438,10 @@ public static bool ThrowCBOExceptions /// ----------------------------------------------------------------------------- /// - /// Gets whether Friendly Urls is Enabled + /// Gets a value indicating whether gets whether Friendly Urls is Enabled. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool UseFriendlyUrls @@ -1450,10 +1454,10 @@ public static bool UseFriendlyUrls /// ----------------------------------------------------------------------------- /// - /// Gets whether Custom Error Messages is Enabled + /// Gets a value indicating whether gets whether Custom Error Messages is Enabled. /// /// - /// Defaults to False + /// Defaults to False. /// /// ----------------------------------------------------------------------------- public static bool UseCustomErrorMessages @@ -1466,10 +1470,10 @@ public static bool UseCustomErrorMessages /// ----------------------------------------------------------------------------- /// - /// Gets the User Quota + /// Gets the User Quota. /// /// - /// Defaults to 0 + /// Defaults to 0. /// /// ----------------------------------------------------------------------------- public static int UserQuota @@ -1482,10 +1486,10 @@ public static int UserQuota /// ----------------------------------------------------------------------------- /// - /// Gets the window to use in minutes when determining if the user is online + /// Gets the window to use in minutes when determining if the user is online. /// /// - /// Defaults to 15 + /// Defaults to 15. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -1499,10 +1503,10 @@ public static int UsersOnlineTimeWindow /// ----------------------------------------------------------------------------- /// - /// Gets the WebRequest Timeout value + /// Gets the WebRequest Timeout value. /// /// - /// Defaults to 10000 + /// Defaults to 10000. /// /// ----------------------------------------------------------------------------- public static int WebRequestTimeout @@ -1514,10 +1518,10 @@ public static int WebRequestTimeout } /// - /// Gets whether to use the minified or debug version of the jQuery scripts + /// Gets a value indicating whether gets whether to use the minified or debug version of the jQuery scripts. /// /// - /// Defaults to False + /// Defaults to False. /// [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool jQueryDebug @@ -1529,10 +1533,10 @@ public static bool jQueryDebug } /// - /// Gets whether to use a hosted version of the jQuery script file + /// Gets a value indicating whether gets whether to use a hosted version of the jQuery script file. /// /// - /// Defaults to False + /// Defaults to False. /// [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool jQueryHosted @@ -1544,7 +1548,7 @@ public static bool jQueryHosted } /// - /// Gets the Url for a hosted version of jQuery + /// Gets the Url for a hosted version of jQuery. /// /// /// Defaults to the DefaultHostedUrl constant in the jQuery class. @@ -1566,31 +1570,31 @@ public static string jQueryUrl } } - /// - /// Gets the Url for a hosted version of jQuery Migrate plugin. - /// - /// - /// Defaults to the DefaultHostedUrl constant in the jQuery class. - /// The framework will default to the latest released 1.x version hosted on Google. - /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string jQueryMigrateUrl - { - get - { - if (HttpContext.Current.Request.IsSecureConnection) - { - return HostController.Instance.GetString("jQueryMigrateUrl", string.Empty).Replace("http://", "https://"); - } - else - { - return HostController.Instance.GetString("jQueryMigrateUrl", string.Empty); - } - } - } - - /// - /// Gets the Url for a hosted version of jQuery UI + /// + /// Gets the Url for a hosted version of jQuery Migrate plugin. + /// + /// + /// Defaults to the DefaultHostedUrl constant in the jQuery class. + /// The framework will default to the latest released 1.x version hosted on Google. + /// + [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + public static string jQueryMigrateUrl + { + get + { + if (HttpContext.Current.Request.IsSecureConnection) + { + return HostController.Instance.GetString("jQueryMigrateUrl", string.Empty).Replace("http://", "https://"); + } + else + { + return HostController.Instance.GetString("jQueryMigrateUrl", string.Empty); + } + } + } + + /// + /// Gets the Url for a hosted version of jQuery UI. /// /// /// Defaults to the DefaultUIHostedUrl constant in the jQuery class. @@ -1612,84 +1616,82 @@ public static string jQueryUIUrl } } - /// - /// Gets whether to use a hosted version of the MS Ajax Library - /// - /// - /// Defaults to False - /// - public static bool EnableMsAjaxCdn - { - get - { - return HostController.Instance.GetBoolean("EnableMsAjaxCDN", false); - } - } - - /// - /// Gets whether to use a hosted version of the Telerik Library - /// - /// - /// Defaults to False - /// - [Obsolete("Not used anymore. Scheduled removal in v10.0.0.")] - public static bool EnableTelerikCdn - { - get - { - return HostController.Instance.GetBoolean("EnableTelerikCDN", false); - } - } - - /// - /// Get Telerik CDN Basic Path. + /// + /// Gets a value indicating whether gets whether to use a hosted version of the MS Ajax Library. + /// + /// + /// Defaults to False. + /// + public static bool EnableMsAjaxCdn + { + get + { + return HostController.Instance.GetBoolean("EnableMsAjaxCDN", false); + } + } + + /// + /// Gets a value indicating whether gets whether to use a hosted version of the Telerik Library. + /// + /// + /// Defaults to False. + /// + [Obsolete("Not used anymore. Scheduled removal in v10.0.0.")] + public static bool EnableTelerikCdn + { + get + { + return HostController.Instance.GetBoolean("EnableTelerikCDN", false); + } + } + + /// + /// Gets get Telerik CDN Basic Path. /// [Obsolete("Not used anymore. Scheduled removal in v10.0.0.")] public static string TelerikCdnBasicUrl - { - get - { - return HostController.Instance.GetString("TelerikCDNBasicUrl"); - } - } + { + get + { + return HostController.Instance.GetString("TelerikCDNBasicUrl"); + } + } /// - /// Get Telerik CDN Secure Path. + /// Gets get Telerik CDN Secure Path. /// [Obsolete("Not used anymore. Scheduled removal in v10.0.0.")] public static string TelerikCdnSecureUrl - { - get - { - return HostController.Instance.GetString("TelerikCDNSecureUrl"); - } - } - - /// - /// Get the time, in seconds, before asynchronous postbacks time out if no response is received. - /// - public static int AsyncTimeout - { - get - { - var timeout = HostController.Instance.GetInteger("AsyncTimeout", 90); - if (timeout < 90) - { - timeout = 90; - } - - return timeout; - } - } - - /// - /// Get a value indicating whether to put the entire instance into maintenance mode + { + get + { + return HostController.Instance.GetString("TelerikCDNSecureUrl"); + } + } + + /// + /// Gets get the time, in seconds, before asynchronous postbacks time out if no response is received. + /// + public static int AsyncTimeout + { + get + { + var timeout = HostController.Instance.GetInteger("AsyncTimeout", 90); + if (timeout < 90) + { + timeout = 90; + } + + return timeout; + } + } + + /// + /// Gets a value indicating whether get a value indicating whether to put the entire instance into maintenance mode. /// public static bool IsLocked { get { return HostController.Instance.GetBoolean("IsLocked", false); } } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs b/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs index 919577779c8..ed713a12dcc 100644 --- a/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs +++ b/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Globalization; - -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { + using System.Globalization; + + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Tokens; + public class HostPropertyAccess : DictionaryPropertyAccess { - public HostPropertyAccess() : base(HostController.Instance.GetSettingsDictionary()) + public HostPropertyAccess() + : base(HostController.Instance.GetSettingsDictionary()) { } diff --git a/DNN Platform/Library/Entities/Host/IServerWebRequestAdapter.cs b/DNN Platform/Library/Entities/Host/IServerWebRequestAdapter.cs index 74c2d26564a..5923c67a015 100644 --- a/DNN Platform/Library/Entities/Host/IServerWebRequestAdapter.cs +++ b/DNN Platform/Library/Entities/Host/IServerWebRequestAdapter.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Net; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Host { + using System.Net; + using System.Web; + /// /// IServerWebRequestAdapter used to get server's info when new server added into server collections. /// Also it can process the request when send to a server, like sync cache, detect server etc. diff --git a/DNN Platform/Library/Entities/Host/ServerController.cs b/DNN Platform/Library/Entities/Host/ServerController.cs index 69968045ed5..408b3deb583 100644 --- a/DNN Platform/Library/Entities/Host/ServerController.cs +++ b/DNN Platform/Library/Entities/Host/ServerController.cs @@ -1,31 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Caching; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Log.EventLog; + public class ServerController { - public const string DefaultUrlAdapter = "DotNetNuke.Entities.Host.ServerWebRequestAdapter, DotNetNuke"; private const string cacheKey = "WebServers"; @@ -43,6 +37,7 @@ public static bool UseAppName { uniqueServers[server.ServerName] = server.IISAppName; } + return uniqueServers.Count < GetEnabledServers().Count; } } @@ -72,6 +67,7 @@ public static List GetEnabledServers() } } } + return servers; } @@ -82,6 +78,7 @@ public static string GetExecutingServerName() { executingServerName += "-" + Globals.IISAppName; } + Logger.Debug("GetExecutingServerName:" + executingServerName); return executingServerName; } @@ -93,6 +90,7 @@ public static string GetServerName(ServerInfo webServer) { serverName += "-" + webServer.IISAppName; } + Logger.Debug("GetServerName:" + serverName); return serverName; } @@ -113,27 +111,27 @@ public static void UpdateServerActivity(ServerInfo server) { var existServer = GetServers().FirstOrDefault(s => s.ServerName == server.ServerName && s.IISAppName == server.IISAppName); var serverId = DataProvider.Instance().UpdateServerActivity(server.ServerName, server.IISAppName, server.CreatedDate, server.LastActivityDate, server.PingFailureCount, server.Enabled); - + server.ServerID = serverId; if (existServer == null || string.IsNullOrEmpty(existServer.Url) || (string.IsNullOrEmpty(existServer.UniqueId) && !string.IsNullOrEmpty(GetServerUniqueId()))) { - //try to detect the server url from url adapter. + // try to detect the server url from url adapter. server.Url = existServer == null || string.IsNullOrEmpty(existServer.Url) ? GetServerUrl() : existServer.Url; - //try to detect the server unique id from url adapter. + + // try to detect the server unique id from url adapter. server.UniqueId = existServer == null || string.IsNullOrEmpty(existServer.UniqueId) ? GetServerUniqueId() : existServer.UniqueId; UpdateServer(server); } - - - //log the server info + + // log the server info var log = new LogInfo(); log.AddProperty(existServer != null ? "Server Updated" : "Add New Server", server.ServerName); log.AddProperty("IISAppName", server.IISAppName); log.AddProperty("Last Activity Date", server.LastActivityDate.ToString()); - log.LogTypeKey = existServer != null ? EventLogController.EventLogType.WEBSERVER_UPDATED.ToString() + log.LogTypeKey = existServer != null ? EventLogController.EventLogType.WEBSERVER_UPDATED.ToString() : EventLogController.EventLogType.WEBSERVER_CREATED.ToString(); LogController.Instance.AddLog(log); diff --git a/DNN Platform/Library/Entities/Host/ServerInfo.cs b/DNN Platform/Library/Entities/Host/ServerInfo.cs index 1a8923eb27d..3fcfc5b0eb3 100644 --- a/DNN Platform/Library/Entities/Host/ServerInfo.cs +++ b/DNN Platform/Library/Entities/Host/ServerInfo.cs @@ -1,35 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { + using System; + using System.Data; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + [Serializable] public class ServerInfo : IHydratable { - public ServerInfo() : this(DateTime.Now, DateTime.Now) + public ServerInfo() + : this(DateTime.Now, DateTime.Now) { } public ServerInfo(DateTime created, DateTime lastactivity) { - IISAppName = Globals.IISAppName; - ServerName = Globals.ServerName; - ServerGroup = String.Empty; - CreatedDate = created; - LastActivityDate = lastactivity; - Enabled = true; + this.IISAppName = Globals.IISAppName; + this.ServerName = Globals.ServerName; + this.ServerGroup = string.Empty; + this.CreatedDate = created; + this.LastActivityDate = lastactivity; + this.Enabled = true; } public int ServerID { get; set; } @@ -50,62 +46,61 @@ public ServerInfo(DateTime created, DateTime lastactivity) public int PingFailureCount { get; set; } - public string UniqueId { get; set; } - - #region IHydratable Members + public string UniqueId { get; set; } /// ----------------------------------------------------------------------------- /// - /// Fills a ServerInfo from a Data Reader + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public int KeyID + { + get + { + return this.ServerID; + } + + set + { + this.ServerID = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a ServerInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- public void Fill(IDataReader dr) { - ServerID = Null.SetNullInteger(dr["ServerID"]); - IISAppName = Null.SetNullString(dr["IISAppName"]); - ServerName = Null.SetNullString(dr["ServerName"]); - Url = Null.SetNullString(dr["URL"]); - Enabled = Null.SetNullBoolean(dr["Enabled"]); - CreatedDate = Null.SetNullDateTime(dr["CreatedDate"]); - LastActivityDate = Null.SetNullDateTime(dr["LastActivityDate"]); + this.ServerID = Null.SetNullInteger(dr["ServerID"]); + this.IISAppName = Null.SetNullString(dr["IISAppName"]); + this.ServerName = Null.SetNullString(dr["ServerName"]); + this.Url = Null.SetNullString(dr["URL"]); + this.Enabled = Null.SetNullBoolean(dr["Enabled"]); + this.CreatedDate = Null.SetNullDateTime(dr["CreatedDate"]); + this.LastActivityDate = Null.SetNullDateTime(dr["LastActivityDate"]); var schema = dr.GetSchemaTable(); if (schema != null) { if (schema.Select("ColumnName = 'PingFailureCount'").Length > 0) { - PingFailureCount = Null.SetNullInteger(dr["PingFailureCount"]); + this.PingFailureCount = Null.SetNullInteger(dr["PingFailureCount"]); } + if (schema.Select("ColumnName = 'ServerGroup'").Length > 0) { - ServerGroup = Null.SetNullString(dr["ServerGroup"]); + this.ServerGroup = Null.SetNullString(dr["ServerGroup"]); } + if (schema.Select("ColumnName = 'UniqueId'").Length > 0) { - UniqueId = Null.SetNullString(dr["UniqueId"]); + this.UniqueId = Null.SetNullString(dr["UniqueId"]); } } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer - /// ----------------------------------------------------------------------------- - public int KeyID - { - get - { - return ServerID; - } - set - { - ServerID = value; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs b/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs index 3bbb31de63c..f67194e9f27 100644 --- a/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs +++ b/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Host { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + public class ServerWebRequestAdapter : IServerWebRequestAdapter { /// @@ -27,7 +28,7 @@ public virtual string GetServerUrl() if (HttpContext.Current != null) { domainName = Globals.GetDomainName(HttpContext.Current.Request); - + if (domainName.Contains("/")) { domainName = domainName.Substring(0, domainName.IndexOf("/")); diff --git a/DNN Platform/Library/Entities/IEventManager.cs b/DNN Platform/Library/Entities/IEventManager.cs index 2250a98c01f..d34b471af85 100644 --- a/DNN Platform/Library/Entities/IEventManager.cs +++ b/DNN Platform/Library/Entities/IEventManager.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Tabs.Actions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem.EventArgs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities { + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Tabs.Actions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem.EventArgs; + public interface IEventManager { void OnFileAdded(FileAddedEventArgs args); diff --git a/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs b/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs index a374e88f57a..dc9338367fb 100644 --- a/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs +++ b/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Host { + using System; + using System.Collections.Generic; + /// /// Do not implement. This interface is meant for reference and unit test purposes only. /// There is no guarantee that this interface will not change. diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs index 6f9c53a5695..e93f132a812 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs @@ -1,57 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Common.Utils; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Common.Utils; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + public class IPFilterController : ComponentBase, IIPFilterController - { - #region Private - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (IPFilterController)); - - private enum FilterType - { - Allow=1, - Deny=2 - } - #endregion - - #region Constructor - + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IPFilterController)); + internal IPFilterController() { - } - - #endregion - - #region IIPFilterController Members + } + private enum FilterType + { + Allow = 1, + Deny = 2, + } + /// - /// add a new IP filter + /// add a new IP filter. /// - /// filter details - /// filter id + /// filter details. + /// filter id. public int AddIPFilter(IPFilterInfo ipFilter) { Requires.NotNull("ipFilter", ipFilter); @@ -62,9 +48,9 @@ public int AddIPFilter(IPFilterInfo ipFilter) } /// - /// update an existing IP filter + /// update an existing IP filter. /// - /// filter details + /// filter details. public void UpdateIPFilter(IPFilterInfo ipFilter) { Requires.NotNull("ipFilter", ipFilter); @@ -80,19 +66,19 @@ public void DeleteIPFilter(IPFilterInfo ipFilter) } /// - /// get an IP filter + /// get an IP filter. /// - /// filter details - /// the selected IP filter + /// filter details. + /// the selected IP filter. public IPFilterInfo GetIPFilter(int ipFilter) { - return CBO.FillObject(DataProvider.Instance().GetIPFilter(ipFilter)); + return CBO.FillObject(DataProvider.Instance().GetIPFilter(ipFilter)); } - + /// - /// get the list of IP filters + /// get the list of IP filters. /// - /// list of IP filters + /// list of IP filters. IList IIPFilterController.GetIPFilters() { return CBO.FillCollection(DataProvider.Instance().GetIPFilters()); @@ -101,73 +87,30 @@ IList IIPFilterController.GetIPFilters() [Obsolete("deprecated with 7.1.0 - please use IsIPBanned instead to return the value and apply your own logic. Scheduled removal in v10.0.0.")] public void IsIPAddressBanned(string ipAddress) { - if (CheckIfBannedIPAddress(ipAddress)) - {//should throw 403.6 - throw new HttpException(403, ""); + if (this.CheckIfBannedIPAddress(ipAddress)) + {// should throw 403.6 + throw new HttpException(403, string.Empty); } } /// - /// Check the set of rules to see if an IP address is banned (used on login) + /// Check the set of rules to see if an IP address is banned (used on login). /// - /// IP address - /// true if banned + /// IP address. + /// true if banned. public bool IsIPBanned(string ipAddress) { - - return CheckIfBannedIPAddress(ipAddress); - } - - private bool CheckIfBannedIPAddress(string ipAddress) - { - IList filterList = Instance.GetIPFilters(); - bool ipAllowed = true; - foreach (var ipFilterInfo in filterList) - { - //if a single deny exists, this win's - if (ipFilterInfo.RuleType == (int)FilterType.Deny) - { - if (NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) - { - //log - LogBannedIPAttempt(ipAddress); - return true; - - } - } - //check any allows - if one exists set flag but let processing continue to verify no deny overrides - if (ipFilterInfo.RuleType == (int)FilterType.Allow) - { - if (ipFilterInfo.IPAddress=="*" || NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) - { - ipAllowed = false; - - } - } - } - return ipAllowed; - } - - - - private void LogBannedIPAttempt(string ipAddress) - { - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString() - }; - log.LogProperties.Add(new LogDetailInfo("HostAddress", ipAddress)); - LogController.Instance.AddLog(log); + return this.CheckIfBannedIPAddress(ipAddress); } /// /// Check if an IP address range can still access based on a set of rules - /// note: this set is typically the list of IP filter rules minus a proposed delete + /// note: this set is typically the list of IP filter rules minus a proposed delete. /// - /// IP address - /// list of IP filters - /// true if IP can access, false otherwise - public bool CanIPStillAccess(string myip,IList filterList) + /// IP address. + /// list of IP filters. + /// true if IP can access, false otherwise. + public bool CanIPStillAccess(string myip, IList filterList) { var allowAllIPs = false; var globalAllow = (from p in filterList @@ -186,14 +129,15 @@ public bool CanIPStillAccess(string myip,IList filterList) var denyRules = (from p in filterList where p.RuleType == (int)FilterType.Deny select p).ToList(); - //if global allow and no deny - if (allowAllIPs & denyRules.Count==0) + + // if global allow and no deny + if (allowAllIPs & denyRules.Count == 0) { return true; } - //if global allow, check if a deny rule would override - if (allowAllIPs & denyRules.Count>0) + // if global allow, check if a deny rule would override + if (allowAllIPs & denyRules.Count > 0) { if (denyRules.Any(ipf => NetworkUtils.IsIPInRange(myip, ipf.IPAddress, ipf.SubnetMask))) { @@ -201,8 +145,8 @@ public bool CanIPStillAccess(string myip,IList filterList) } } - //if no global allow, check if a deny rule would apply - if (allowAllIPs==false & denyRules.Count > 0) + // if no global allow, check if a deny rule would apply + if (allowAllIPs == false & denyRules.Count > 0) { if (denyRules.Any(ipf => NetworkUtils.IsIPInRange(myip, ipf.IPAddress, ipf.SubnetMask))) { @@ -210,7 +154,7 @@ public bool CanIPStillAccess(string myip,IList filterList) } } - //if no global allow, and no deny rules check if an allow rule would apply + // if no global allow, and no deny rules check if an allow rule would apply if (allowAllIPs == false & denyRules.Count == 0) { if (allowRules.Any(ipf => NetworkUtils.IsIPInRange(myip, ipf.IPAddress, ipf.SubnetMask))) @@ -223,14 +167,14 @@ public bool CanIPStillAccess(string myip,IList filterList) } /// - /// Check if a new rule would block the existing IP address + /// Check if a new rule would block the existing IP address. /// - /// current IP address - /// new propose rule - /// true if rule would not block current IP, false otherwise + /// current IP address. + /// new propose rule. + /// true if rule would not block current IP, false otherwise. public bool IsAllowableDeny(string currentIP, IPFilterInfo ipFilter) { - if (ipFilter.RuleType==(int)FilterType.Allow) + if (ipFilter.RuleType == (int)FilterType.Allow) { return true; } @@ -239,11 +183,50 @@ public bool IsAllowableDeny(string currentIP, IPFilterInfo ipFilter) { return false; } + return true; - } - - #endregion + } + private bool CheckIfBannedIPAddress(string ipAddress) + { + IList filterList = Instance.GetIPFilters(); + bool ipAllowed = true; + foreach (var ipFilterInfo in filterList) + { + // if a single deny exists, this win's + if (ipFilterInfo.RuleType == (int)FilterType.Deny) + { + if (NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) + { + // log + this.LogBannedIPAttempt(ipAddress); + return true; + } + } + + // check any allows - if one exists set flag but let processing continue to verify no deny overrides + if (ipFilterInfo.RuleType == (int)FilterType.Allow) + { + if (ipFilterInfo.IPAddress == "*" || NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) + { + ipAllowed = false; + } + } + } + + return ipAllowed; + } + + private void LogBannedIPAttempt(string ipAddress) + { + var log = new LogInfo + { + LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), + }; + log.LogProperties.Add(new LogDetailInfo("HostAddress", ipAddress)); + LogController.Instance.AddLog(log); + } + private static void AssertValidIPFilter(IPFilterInfo ipFilter) { IPAddress parsed; diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs index dfb9004cb54..430003c7d08 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs @@ -1,113 +1,94 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { - + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + [Serializable] public class IPFilterInfo : BaseEntityInfo, IHydratable - { - - #region Constructors - - /// - /// Create new IPFilterInfo instance + { + /// + /// Initializes a new instance of the class. + /// Create new IPFilterInfo instance. /// /// /// public IPFilterInfo(string ipAddress, string subnetMask, int ruleType) { - IPAddress = ipAddress; - SubnetMask = subnetMask; - RuleType = ruleType; + this.IPAddress = ipAddress; + this.SubnetMask = subnetMask; + this.RuleType = ruleType; } public IPFilterInfo() { - IPAddress = String.Empty; - SubnetMask = String.Empty; - RuleType = -1; - } - - #endregion - - #region Auto_Properties - + this.IPAddress = string.Empty; + this.SubnetMask = string.Empty; + this.RuleType = -1; + } + public int IPFilterID { get; set; } public string IPAddress { get; set; } public string SubnetMask { get; set; } - public int RuleType { get; set; } - - #endregion - - - #region IHydratable Members + public int RuleType { get; set; } /// - /// Fills an IPFilterInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// Standard IHydratable.Fill implementation - /// - public void Fill(IDataReader dr) + /// KeyId of the IHydratable.Key. + /// + public int KeyID { - IPFilterID = Null.SetNullInteger(dr["IPFilterID"]); - - try + get { - IPFilterID = Null.SetNullInteger(dr["IPFilterID"]); + return this.IPFilterID; } - catch (IndexOutOfRangeException) + + set { - - //else swallow the error + this.IPFilterID = value; } - - IPAddress = Null.SetNullString(dr["IPAddress"]); - SubnetMask = Null.SetNullString(dr["SubnetMask"]); - RuleType = Null.SetNullInteger(dr["RuleType"]); - - FillInternal(dr); - } - + } + /// - /// Gets and sets the Key ID + /// Fills an IPFilterInfo from a Data Reader. /// - /// KeyId of the IHydratable.Key - /// - public int KeyID + /// The Data Reader to use. + /// Standard IHydratable.Fill implementation. + /// + public void Fill(IDataReader dr) { - get + this.IPFilterID = Null.SetNullInteger(dr["IPFilterID"]); + + try { - return IPFilterID; + this.IPFilterID = Null.SetNullInteger(dr["IPFilterID"]); } - set + catch (IndexOutOfRangeException) { - IPFilterID = value; + // else swallow the error } - } - #endregion + this.IPAddress = Null.SetNullString(dr["IPAddress"]); + this.SubnetMask = Null.SetNullString(dr["SubnetMask"]); + this.RuleType = Null.SetNullInteger(dr["RuleType"]); + + this.FillInternal(dr); + } } } diff --git a/DNN Platform/Library/Entities/Icons/IconController.cs b/DNN Platform/Library/Entities/Icons/IconController.cs index 82798a32f5a..414220f0316 100644 --- a/DNN Platform/Library/Entities/Icons/IconController.cs +++ b/DNN Platform/Library/Entities/Icons/IconController.cs @@ -1,41 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Web; -using System.Web.Hosting; -using System.Xml; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Icons { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; + using System.Web; + using System.Web.Hosting; + using System.Xml; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + /// /// IconController provides all operation to icons. /// @@ -46,24 +41,21 @@ namespace DotNetNuke.Entities.Icons /// public class IconController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (IconController)); - #region Constants - public const string DefaultIconSize = "16X16"; public const string DefaultLargeIconSize = "32X32"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IconController)); public const string DefaultIconStyle = "Standard"; public const string IconKeyName = "IconKey"; public const string IconSizeName = "IconSize"; - public const string IconStyleName = "IconStyle"; - - #endregion - + public const string IconStyleName = "IconStyle"; + private static readonly SharedDictionary _iconsStatusOnDisk = new SharedDictionary(); + /// /// Gets the Icon URL. /// - /// Key to icon, e.g. edit - /// Link to the image, e.g. /Icons/Sigma/edit_16x16_standard.png + /// Key to icon, e.g. edit. + /// Link to the image, e.g. /Icons/Sigma/edit_16x16_standard.png. public static string IconURL(string key) { return IconURL(key, DefaultIconSize, DefaultIconStyle); @@ -72,9 +64,9 @@ public static string IconURL(string key) /// /// Gets the Icon URL. /// - /// Key to icon, e.g. edit - /// Size of icon, e.g.16x16 (default) or 32x32 - /// Link to the image, e.g. /Icons/Sigma/edit_16x16_standard.png + /// Key to icon, e.g. edit. + /// Size of icon, e.g.16x16 (default) or 32x32. + /// Link to the image, e.g. /Icons/Sigma/edit_16x16_standard.png. public static string IconURL(string key, string size) { return IconURL(key, size, DefaultIconStyle); @@ -83,24 +75,30 @@ public static string IconURL(string key, string size) /// /// Gets the Icon URL. /// - /// Key to icon, e.g. edit - /// Size of icon, e.g.16x16 (default) or 32x32 - /// Style of icon, e.g. Standard (default) - /// Link to the image, e.g. /Icons/Sigma/edit_16x16_standard.png + /// Key to icon, e.g. edit. + /// Size of icon, e.g.16x16 (default) or 32x32. + /// Style of icon, e.g. Standard (default). + /// Link to the image, e.g. /Icons/Sigma/edit_16x16_standard.png. public static string IconURL(string key, string size, string style) { - if (string.IsNullOrEmpty(key)) - return string.Empty; - - if (string.IsNullOrEmpty(size)) - size = DefaultIconSize; - - if (string.IsNullOrEmpty(style)) - style = DefaultIconStyle; - + if (string.IsNullOrEmpty(key)) + { + return string.Empty; + } + + if (string.IsNullOrEmpty(size)) + { + size = DefaultIconSize; + } + + if (string.IsNullOrEmpty(style)) + { + style = DefaultIconStyle; + } + string fileName = string.Format("{0}/{1}_{2}_{3}.png", PortalSettings.Current.DefaultIconLocation, key, size, style); - //In debug mode, we want to warn (onluy once) if icon is not present on disk + // In debug mode, we want to warn (onluy once) if icon is not present on disk #if DEBUG CheckIconOnDisk(fileName); #endif @@ -113,16 +111,35 @@ public static string GetFileIconUrl(string extension) { return IconURL("Ext" + extension, "32x32", "Standard"); } + return IconURL("ExtFile", "32x32", "Standard"); } - private static readonly SharedDictionary _iconsStatusOnDisk = new SharedDictionary(); + public static string[] GetIconSets() + { + string iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, "icons"); + var iconRootDir = new DirectoryInfo(iconPhysicalPath); + string result = string.Empty; + foreach (var iconDir in iconRootDir.EnumerateDirectories()) + { + string testFile = Path.Combine(iconDir.FullName, "About_16x16_Standard.png"); + if (File.Exists(testFile)) + { + result += iconDir.Name + ","; + } + } + + return result.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + } + private static void CheckIconOnDisk(string path) - { + { using (_iconsStatusOnDisk.GetReadLock()) - { - if (_iconsStatusOnDisk.ContainsKey(path)) - return; + { + if (_iconsStatusOnDisk.ContainsKey(path)) + { + return; + } } using (_iconsStatusOnDisk.GetWriteLock()) @@ -131,24 +148,12 @@ private static void CheckIconOnDisk(string path) { _iconsStatusOnDisk.Add(path, true); string iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, path.Replace('/', '\\')); - if (!File.Exists(iconPhysicalPath)) - Logger.WarnFormat(string.Format("Icon Not Present on Disk {0}", iconPhysicalPath)); + if (!File.Exists(iconPhysicalPath)) + { + Logger.WarnFormat(string.Format("Icon Not Present on Disk {0}", iconPhysicalPath)); + } } - } - } - - public static string[] GetIconSets() - { - string iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, "icons"); - var iconRootDir = new DirectoryInfo(iconPhysicalPath); - string result = ""; - foreach (var iconDir in iconRootDir.EnumerateDirectories()) - { - string testFile = Path.Combine(iconDir.FullName,"About_16x16_Standard.png"); - if (File.Exists(testFile)) - result += iconDir.Name + ","; } - return result.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs b/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs index b3eda2ae960..8c202bab36d 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs @@ -1,70 +1,70 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Actions { - ///----------------------------------------------------------------------------- - /// Project : DotNetNuke + using System; + + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke /// Namespace : DotNetNuke.Entities.Modules.Actions - /// Class : ActionEventArgs - ///----------------------------------------------------------------------------- + /// Class : ActionEventArgs + /// ----------------------------------------------------------------------------- /// - /// ActionEventArgs provides a custom EventARgs class for Action Events + /// ActionEventArgs provides a custom EventARgs class for Action Events. /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class ActionEventArgs : EventArgs { private readonly ModuleAction _action; - private readonly ModuleInfo _moduleConfiguration; - - ///----------------------------------------------------------------------------- - /// + private readonly ModuleInfo _moduleConfiguration; + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. /// /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ActionEventArgs(ModuleAction Action, ModuleInfo ModuleConfiguration) { - _action = Action; - _moduleConfiguration = ModuleConfiguration; + this._action = Action; + this._moduleConfiguration = ModuleConfiguration; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// + /// /// - /// + /// + /// + /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleAction Action { get { - return _action; + return this._action; } } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// + /// /// - /// + /// + /// + /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleInfo ModuleConfiguration { get { - return _moduleConfiguration; + return this._moduleConfiguration; } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs b/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs index ea0387163cc..6a9cbfc41bc 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Actions { /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs b/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs index a1a8256d349..c09e4a491ed 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs @@ -1,14 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Actions { public interface IModuleEventHandler { void ModuleCreated(object sender, ModuleEventArgs args); + void ModuleUpdated(object sender, ModuleEventArgs args); + void ModuleRemoved(object sender, ModuleEventArgs args); + void ModuleDeleted(object sender, ModuleEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs index 415aa7bd5b4..88899e1d2d3 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Actions { - ///----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : ModuleAction - ///----------------------------------------------------------------------------- + using System; + + using DotNetNuke.Security; + + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke + /// Class : ModuleAction + /// ----------------------------------------------------------------------------- /// /// Each Module Action represents a separate functional action as defined by the /// associated module. @@ -25,27 +20,31 @@ namespace DotNetNuke.Entities.Modules.Actions /// user. These actions may be presented as a menu, a dropdown list or even a group /// of linkbuttons. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class ModuleAction { - public ModuleAction(int id) : this(id, "", "", "", "", "", "", false, SecurityAccessLevel.Anonymous, true, false) + public ModuleAction(int id) + : this(id, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } - public ModuleAction(int id, string title, string cmdName) : this(id, title, cmdName, "", "", "", "", false, SecurityAccessLevel.Anonymous, true, false) + public ModuleAction(int id, string title, string cmdName) + : this(id, title, cmdName, string.Empty, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } - public ModuleAction(int id, string title, string cmdName, string cmdArg) : this(id, title, cmdName, cmdArg, "", "", "", false, SecurityAccessLevel.Anonymous, true, false) + public ModuleAction(int id, string title, string cmdName, string cmdArg) + : this(id, title, cmdName, cmdArg, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } - public ModuleAction(int id, string title, string cmdName, string cmdArg, string icon) : this(id, title, cmdName, cmdArg, icon, "", "", false, SecurityAccessLevel.Anonymous, true, false) + public ModuleAction(int id, string title, string cmdName, string cmdArg, string icon) + : this(id, title, cmdName, cmdArg, icon, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } public ModuleAction(int id, string title, string cmdName, string cmdArg, string icon, string url) - : this(id, title, cmdName, cmdArg, icon, url, "", false, SecurityAccessLevel.Anonymous, true, false) + : this(id, title, cmdName, cmdArg, icon, url, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } @@ -69,48 +68,48 @@ public ModuleAction(int id, string title, string cmdName, string cmdArg, string { } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Initializes a new instance of the class - /// using the specified parameters + /// Initializes a new instance of the class + /// using the specified parameters. /// /// This is the identifier to use for this action. - /// This is the title that will be displayed for this action - /// The command name passed to the client when this action is + /// This is the title that will be displayed for this action. + /// The command name passed to the client when this action is /// clicked. - /// The command argument passed to the client when this action is + /// The command argument passed to the client when this action is /// clicked. - /// The URL of the Icon to place next to this action + /// The URL of the Icon to place next to this action. /// The destination URL to redirect the client browser when this action is clicked. /// - /// Determines whether client will receive an event notification - /// The security access level required for access to this action - /// Whether this action will be displayed + /// Determines whether client will receive an event notification. + /// The security access level required for access to this action. + /// Whether this action will be displayed. /// - /// The moduleaction constructor is used to set the various properties of + /// The moduleaction constructor is used to set the various properties of /// the class at the time the instance is created. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleAction(int id, string title, string cmdName, string cmdArg, string icon, string url, string clientScript, bool useActionEvent, SecurityAccessLevel secure, bool visible, bool newWindow) { - ID = id; - Title = title; - CommandName = cmdName; - CommandArgument = cmdArg; - Icon = icon; - Url = url; - ClientScript = clientScript; - UseActionEvent = useActionEvent; - Secure = secure; - Visible = visible; - NewWindow = newWindow; - Actions = new ModuleActionCollection(); + this.ID = id; + this.Title = title; + this.CommandName = cmdName; + this.CommandArgument = cmdArg; + this.Icon = icon; + this.Url = url; + this.ClientScript = clientScript; + this.UseActionEvent = useActionEvent; + this.Secure = secure; + this.Visible = visible; + this.NewWindow = newWindow; + this.Actions = new ModuleActionCollection(); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// The Actions property allows the user to create a hierarchy of actions, with + /// Gets or sets the Actions property allows the user to create a hierarchy of actions, with /// each action having sub-actions. /// /// Returns a collection of ModuleActions. @@ -118,140 +117,142 @@ public ModuleAction(int id, string title, string cmdName, string cmdArg, string /// the control, these subactions are /// shown as sub-menus. If other Action controls are implemented, then /// sub-actions may or may not be supported for that control type. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleActionCollection Actions { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// A Module Action ID is a identifier that can be used in a Module Action Collection - /// to find a specific Action. + /// Gets or sets a Module Action ID is a identifier that can be used in a Module Action Collection + /// to find a specific Action. /// /// The integer ID of the current . - /// When building a hierarchy of ModuleActions, + /// When building a hierarchy of ModuleActions, /// the ID is used to link the child and parent actions. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public int ID { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the current action should be displayed. + /// Gets or sets a value indicating whether gets or sets whether the current action should be displayed. /// - /// A boolean value that determines if the current action should be displayed + /// A boolean value that determines if the current action should be displayed. /// If Visible is false, then the action is always hidden. If Visible /// is true then the action may be visible depending on the security access rights /// specified by the property. By /// utilizing a custom method in your module, you can encapsulate specific business /// rules to determine if the Action should be visible. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public bool Visible { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Gets or sets the value indicating the that is required /// to access this . /// /// The value indicating the that is required - /// to access this + /// to access this . /// The security access level determines the roles required by the current user in /// order to access this module action. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public SecurityAccessLevel Secure { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// A Module Action CommandName represents a string used by the ModuleTitle to notify + /// Gets or sets a Module Action CommandName represents a string used by the ModuleTitle to notify /// the parent module that a given Module Action was selected in the Module Menu. /// /// The name of the command to perform. /// - /// Use the CommandName property to determine the command to perform. The CommandName - /// property can contain any string set by the programmer. The programmer can then + /// Use the CommandName property to determine the command to perform. The CommandName + /// property can contain any string set by the programmer. The programmer can then /// identify the command name in code and perform the appropriate tasks. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public string CommandName { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// A Module Action CommandArgument provides additional information and + /// Gets or sets a Module Action CommandArgument provides additional information and /// complements the CommandName. /// /// A string that contains the argument for the command. /// - /// The CommandArgument can contain any string set by the programmer. The - /// CommandArgument property complements the - /// property by allowing you to provide any additional information for the command. - /// For example, you can set the CommandName property to "Sort" and set the - /// CommandArgument property to "Ascending" to specify a command to sort in ascending + /// The CommandArgument can contain any string set by the programmer. The + /// CommandArgument property complements the + /// property by allowing you to provide any additional information for the command. + /// For example, you can set the CommandName property to "Sort" and set the + /// CommandArgument property to "Ascending" to specify a command to sort in ascending /// order. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public string CommandArgument { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the string that is displayed in the Module Menu + /// that represents a given menu action. + /// + /// The string value that is displayed to represent the module action. + /// The title property is displayed by the Actions control for each module + /// action. + /// ----------------------------------------------------------------------------- + public string Title { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the URL for the icon file that is displayed for the given + /// . + /// + /// The URL for the icon that is displayed with the module action. + /// The URL for the icon is a simple string and is not checked for formatting. + /// ----------------------------------------------------------------------------- + public string Icon { get; set; } + internal string ControlKey { get { - string controlKey = String.Empty; - if (!String.IsNullOrEmpty(Url)) + string controlKey = string.Empty; + if (!string.IsNullOrEmpty(this.Url)) { - int startIndex = Url.IndexOf("/ctl/"); + int startIndex = this.Url.IndexOf("/ctl/"); int endIndex = -1; if (startIndex > -1) { startIndex += 4; - endIndex = Url.IndexOf("/", startIndex + 1); + endIndex = this.Url.IndexOf("/", startIndex + 1); } else { - startIndex = Url.IndexOf("ctl="); + startIndex = this.Url.IndexOf("ctl="); if (startIndex > -1) { startIndex += 4; - endIndex = Url.IndexOf("&", startIndex + 1); + endIndex = this.Url.IndexOf("&", startIndex + 1); } } + if (startIndex > -1) { - controlKey = endIndex > -1 ? Url.Substring(startIndex + 1, endIndex - startIndex - 1) : Url.Substring(startIndex + 1); + controlKey = endIndex > -1 ? this.Url.Substring(startIndex + 1, endIndex - startIndex - 1) : this.Url.Substring(startIndex + 1); } } + return controlKey; } } - ///----------------------------------------------------------------------------- - /// - /// Gets or sets the string that is displayed in the Module Menu - /// that represents a given menu action. - /// - /// The string value that is displayed to represent the module action. - /// The title property is displayed by the Actions control for each module - /// action. - ///----------------------------------------------------------------------------- - public string Title { get; set; } - - ///----------------------------------------------------------------------------- - /// - /// Gets or sets the URL for the icon file that is displayed for the given - /// . - /// - /// The URL for the icon that is displayed with the module action. - /// The URL for the icon is a simple string and is not checked for formatting. - ///----------------------------------------------------------------------------- - public string Icon { get; set; } - - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets or sets the URL to which the user is redirected when the - /// associated Module Menu Action is selected. + /// Gets or sets the URL to which the user is redirected when the + /// associated Module Menu Action is selected. /// - /// The URL to which the user is redirected when the + /// The URL to which the user is redirected when the /// associated Module Menu Action is selected. - /// If the URL is present then the Module Action Event is not fired. - /// If the URL is empty then the Action Event is fired and is passed the value + /// If the URL is present then the Module Action Event is not fired. + /// If the URL is empty then the Action Event is fired and is passed the value /// of the associated Command property. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public string Url { get; set; } /// ----------------------------------------------------------------------------- @@ -259,39 +260,39 @@ internal string ControlKey /// Gets or sets javascript which will be run in the clients browser /// when the associated Module menu Action is selected. prior to a postback. /// - /// The Javascript which will be run during the menuClick event + /// The Javascript which will be run during the menuClick event. /// If the ClientScript property is present then it is called prior /// to the postback occuring. If the ClientScript returns false then the postback - /// is canceled. If the ClientScript is empty then the Action Event is fired and + /// is canceled. If the ClientScript is empty then the Action Event is fired and /// is passed the value of the associated Command property. /// ----------------------------------------------------------------------------- public string ClientScript { get; set; } /// - /// Gets or sets a value that determines if a local ActionEvent is fired when the - /// contains a URL. + /// Gets or sets a value indicating whether gets or sets a value that determines if a local ActionEvent is fired when the + /// contains a URL. /// /// A boolean indicating whether to fire the ActionEvent. - /// When a MenuAction is clicked, an event is fired within the Actions + /// When a MenuAction is clicked, an event is fired within the Actions /// control. If the UseActionEvent is true then the Actions control will forward /// the event to the parent skin which will then attempt to raise the event to /// the appropriate module. If the UseActionEvent is false, and the URL property /// is set, then the Actions control will redirect the response to the URL. In /// all cases, an ActionEvent is raised if the URL is not set. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public bool UseActionEvent { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets or sets a value that determines if a new window is opened when the - /// DoAction() method is called. + /// Gets or sets a value indicating whether gets or sets a value that determines if a new window is opened when the + /// DoAction() method is called. /// /// A boolean indicating whether to open a new window. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public bool NewWindow { get; set; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Determines whether the action node contains any child actions. /// @@ -300,10 +301,10 @@ internal string ControlKey /// property. When displayed via /// the control, these subactions are /// shown as sub-menus. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public bool HasChildren() { - return (Actions.Count > 0); + return this.Actions.Count > 0; } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs index 58876bdbf2b..7020e63cdd4 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs @@ -1,148 +1,145 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Actions { - ///----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : ModuleActionCollection - ///----------------------------------------------------------------------------- + using System.Collections; + + using DotNetNuke.Security; + + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke + /// Class : ModuleActionCollection + /// ----------------------------------------------------------------------------- /// /// Represents a collection of objects. /// /// The ModuleActionCollection is a custom collection of ModuleActions. /// Each ModuleAction in the collection has it's own /// collection which provides the ability to create a hierarchy of ModuleActions. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class ModuleActionCollection : CollectionBase - { - ///----------------------------------------------------------------------------- - /// + { + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. /// Initializes a new, empty instance of the class. /// /// The default constructor creates an empty collection of /// objects. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleActionCollection() { } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Initializes a new instance of the + /// Initializes a new instance of the /// class containing the elements of the specified source collection. /// /// A with which to initialize the collection. /// This overloaded constructor copies the s /// from the indicated collection. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleActionCollection(ModuleActionCollection value) { - AddRange(value); + this.AddRange(value); } /// ----------------------------------------------------------------------------- /// - /// Initializes a new instance of the + /// Initializes a new instance of the /// class containing the specified array of objects. /// - /// An array of objects + /// An array of objects /// with which to initialize the collection. /// This overloaded constructor copies the s /// from the indicated array. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleActionCollection(ModuleAction[] value) { - AddRange(value); + this.AddRange(value); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets or sets the at the + /// Gets or sets the at the /// specified index in the collection. /// - /// In VB.Net, this property is the indexer for the class. + /// In VB.Net, this property is the indexer for the class. /// /// /// The index of the collection to access. - /// A at each valid index. + /// A at each valid index. /// This method is an indexer that can be used to access the collection. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleAction this[int index] { get { - return (ModuleAction) List[index]; + return (ModuleAction)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Add an element of the specified to the end of the collection. + /// Add an element of the specified to the end of the collection. /// - /// An object of type to add to the collection. - /// The index of the newly added - ///----------------------------------------------------------------------------- + /// An object of type to add to the collection. + /// The index of the newly added . + /// ----------------------------------------------------------------------------- public int Add(ModuleAction value) { - return List.Add(value); + return this.List.Add(value); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Add an element of the specified to the end of the collection. /// /// This is the identifier to use for this action. - /// This is the title that will be displayed for this action - /// The command name passed to the client when this action is + /// This is the title that will be displayed for this action. + /// The command name passed to the client when this action is /// clicked. - /// The index of the newly added + /// The index of the newly added . /// This method creates a new with the specified /// values, adds it to the collection and returns the index of the newly created ModuleAction. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleAction Add(int ID, string Title, string CmdName) { - return Add(ID, Title, CmdName, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false); + return this.Add(ID, Title, CmdName, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Add an element of the specified to the end of the collection. + /// Add an element of the specified to the end of the collection. /// /// This is the identifier to use for this action. - /// This is the title that will be displayed for this action - /// The command name passed to the client when this action is + /// This is the title that will be displayed for this action. + /// The command name passed to the client when this action is /// clicked. - /// The command argument passed to the client when this action is + /// The command argument passed to the client when this action is /// clicked. - /// The URL of the Icon to place next to this action - /// The destination URL to redirect the client browser when this + /// The URL of the Icon to place next to this action. + /// The destination URL to redirect the client browser when this /// action is clicked. /// Determines whether client will receive an event - /// notification - /// The security access level required for access to this action - /// Whether this action will be displayed + /// notification. + /// The security access level required for access to this action. + /// Whether this action will be displayed. /// Whether open in new window. - /// The index of the newly added - /// This method creates a new with the specified + /// The index of the newly added . + /// This method creates a new with the specified /// values, adds it to the collection and returns the index of the newly created ModuleAction. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleAction Add(int ID, string Title, string CmdName, string CmdArg, string Icon, string Url, bool UseActionEvent, SecurityAccessLevel Secure, bool Visible, bool NewWindow) { - return Add(ID, Title, CmdName, CmdArg, Icon, Url, "", UseActionEvent, Secure, Visible, NewWindow); + return this.Add(ID, Title, CmdName, CmdArg, Icon, Url, string.Empty, UseActionEvent, Secure, Visible, NewWindow); } /// ----------------------------------------------------------------------------- @@ -150,23 +147,23 @@ public ModuleAction Add(int ID, string Title, string CmdName, string CmdArg, str /// Add an element of the specified to the end of the collection. /// /// This is the identifier to use for this action. - /// This is the title that will be displayed for this action - /// The command name passed to the client when this action is + /// This is the title that will be displayed for this action. + /// The command name passed to the client when this action is /// clicked. - /// The command argument passed to the client when this action is + /// The command argument passed to the client when this action is /// clicked. - /// The URL of the Icon to place next to this action - /// The destination URL to redirect the client browser when this + /// The URL of the Icon to place next to this action. + /// The destination URL to redirect the client browser when this /// action is clicked. - /// Client side script to be run when the this action is + /// Client side script to be run when the this action is /// clicked. /// Determines whether client will receive an event - /// notification - /// The security access level required for access to this action - /// Whether this action will be displayed + /// notification. + /// The security access level required for access to this action. + /// Whether this action will be displayed. /// Whether open in new window. - /// The index of the newly added - /// This method creates a new with the specified + /// The index of the newly added . + /// This method creates a new with the specified /// values, adds it to the collection and returns the index of the newly created ModuleAction. /// /// ----------------------------------------------------------------------------- @@ -174,44 +171,44 @@ public ModuleAction Add(int ID, string Title, string CmdName, string CmdArg, str bool NewWindow) { var ModAction = new ModuleAction(ID, Title, CmdName, CmdArg, Icon, Url, ClientScript, UseActionEvent, Secure, Visible, NewWindow); - Add(ModAction); + this.Add(ModAction); return ModAction; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Copies the elements of the specified /// array to the end of the collection. /// /// An array of type /// containing the objects to add to the collection. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public void AddRange(ModuleAction[] value) { int i; for (i = 0; i <= value.Length - 1; i++) { - Add(value[i]); + this.Add(value[i]); } } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Adds the contents of another /// to the end of the collection. /// - /// A containing + /// A containing /// the objects to add to the collection. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public void AddRange(ModuleActionCollection value) { foreach (ModuleAction mA in value) { - Add(mA); + this.Add(mA); } } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether the collection contains the specified . /// @@ -219,7 +216,7 @@ public void AddRange(ModuleActionCollection value) /// true if the collection contains the specified object; otherwise, false. /// /// - /// ' Tests for the presence of a ModuleAction in the + /// ' Tests for the presence of a ModuleAction in the /// ' collection, and retrieves its index if it is found. /// Dim testModuleAction = New ModuleAction(5, "Edit Action", "Edit") /// Dim itemIndex As Integer = -1 @@ -228,26 +225,27 @@ public void AddRange(ModuleActionCollection value) /// End If /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public bool Contains(ModuleAction value) { - //If value is not of type ModuleAction, this will return false. - return List.Contains(value); + // If value is not of type ModuleAction, this will return false. + return this.List.Contains(value); } public ModuleAction GetActionByCommandName(string name) { ModuleAction retAction = null; - //Check each action in the List - foreach (ModuleAction modAction in List) + // Check each action in the List + foreach (ModuleAction modAction in this.List) { if (modAction.CommandName == name) { retAction = modAction; break; } - //If action has children check them + + // If action has children check them if (modAction.HasChildren()) { ModuleAction childAction = modAction.Actions.GetActionByCommandName(name); @@ -258,6 +256,7 @@ public ModuleAction GetActionByCommandName(string name) } } } + return retAction; } @@ -265,19 +264,21 @@ public ModuleActionCollection GetActionsByCommandName(string name) { var retActions = new ModuleActionCollection(); - //Check each action in the List - foreach (ModuleAction modAction in List) + // Check each action in the List + foreach (ModuleAction modAction in this.List) { if (modAction.CommandName == name) { retActions.Add(modAction); } - //If action has children check them + + // If action has children check them if (modAction.HasChildren()) { retActions.AddRange(modAction.Actions.GetActionsByCommandName(name)); } } + return retActions; } @@ -285,15 +286,16 @@ public ModuleAction GetActionByID(int id) { ModuleAction retAction = null; - //Check each action in the List - foreach (ModuleAction modAction in List) + // Check each action in the List + foreach (ModuleAction modAction in this.List) { if (modAction.ID == id) { retAction = modAction; break; } - //If action has children check them + + // If action has children check them if (modAction.HasChildren()) { ModuleAction childAction = modAction.Actions.GetActionByID(id); @@ -304,12 +306,13 @@ public ModuleAction GetActionByID(int id) } } } + return retAction; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets the index in the collection of the specified , + /// Gets the index in the collection of the specified , /// if it exists in the collection. /// /// The to locate in the collection. @@ -324,47 +327,47 @@ public ModuleAction GetActionByID(int id) /// End If /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public int IndexOf(ModuleAction value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Add an element of the specified to the + /// Add an element of the specified to the /// collection at the designated index. /// /// An Integer to indicate the location to add the object to the collection. /// An object of type to add to the collection. /// /// - /// ' Inserts a ModuleAction at index 0 of the collection. + /// ' Inserts a ModuleAction at index 0 of the collection. /// collection.Insert(0, New ModuleAction(5, "Edit Action", "Edit")) /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public void Insert(int index, ModuleAction value) { - List.Insert(index, value); + this.List.Insert(index, value); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Remove the specified object of type from the collection. /// /// An object of type to remove from the collection. /// /// - /// ' Removes the specified ModuleAction from the collection. + /// ' Removes the specified ModuleAction from the collection. /// Dim testModuleAction = New ModuleAction(5, "Edit Action", "Edit") /// collection.Remove(testModuleAction) /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public void Remove(ModuleAction value) { - List.Remove(value); + this.List.Remove(value); } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs index f63b11c2745..3593d23fd59 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs @@ -1,65 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Actions { - ///----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : ModuleActionEventListener + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke + /// Class : ModuleActionEventListener /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class ModuleActionEventListener { private readonly ActionEventHandler _actionEvent; - private readonly int _moduleID; - - ///----------------------------------------------------------------------------- - /// - /// + private readonly int _moduleID; + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. /// /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ModuleActionEventListener(int ModID, ActionEventHandler e) { - _moduleID = ModID; - _actionEvent = e; + this._moduleID = ModID; + this._actionEvent = e; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// + /// /// - /// + /// + /// + /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public int ModuleID { get { - return _moduleID; + return this._moduleID; } } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// + /// /// - /// + /// + /// + /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public ActionEventHandler ActionEvent { get { - return _actionEvent; + return this._actionEvent; } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionType.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionType.cs index bcd01eef944..d7f210390bf 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionType.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionType.cs @@ -1,91 +1,91 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Actions { - ///----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : ModuleActionType - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke + /// Class : ModuleActionType + /// ----------------------------------------------------------------------------- /// - /// Identifies common module action types + /// Identifies common module action types. /// /// /// Common action types can be specified in the CommandName attribute of the - /// ModuleAction class + /// ModuleAction class. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class ModuleActionType { - /// An action to create new content + /// An action to create new content. public const string AddContent = "AddContent.Action"; - - /// An action to edit existing content + + /// An action to edit existing content. public const string EditContent = "EditContent.Action"; - - /// An action to configure the module + + /// An action to configure the module. public const string ContentOptions = "ContentOptions.Action"; - - /// An action to access the RSS feed of a module + + /// An action to access the RSS feed of a module. public const string SyndicateModule = "SyndicateModule.Action"; - - /// An action to import content into a module + + /// An action to import content into a module. public const string ImportModule = "ImportModule.Action"; - - /// An action to export the content of a module + + /// An action to export the content of a module. public const string ExportModule = "ExportModule.Action"; - + public const string OnlineHelp = "OnlineHelp.Action"; - - /// An action to view the help for a module + + /// An action to view the help for a module. public const string ModuleHelp = "ModuleHelp.Action"; - + public const string HelpText = "ModuleHelp.Text"; - - /// An action to print a module's content + + /// An action to print a module's content. public const string PrintModule = "PrintModule.Action"; - - /// An action to access the module's settings + + /// An action to access the module's settings. public const string ModuleSettings = "ModuleSettings.Action"; - - /// An action to delete the module + + /// An action to delete the module. public const string DeleteModule = "DeleteModule.Action"; - - /// An action to clear the module's cache + + /// An action to clear the module's cache. public const string ClearCache = "ClearCache.Action"; - - /// An action to move the module to the top of its pane + + /// An action to move the module to the top of its pane. public const string MoveTop = "MoveTop.Action"; - - /// An action to move the module up in its pane + + /// An action to move the module up in its pane. public const string MoveUp = "MoveUp.Action"; - - /// An action to move the module down in its pane + + /// An action to move the module down in its pane. public const string MoveDown = "MoveDown.Action"; - - /// An action to move the module to the bottom of its pane + + /// An action to move the module to the bottom of its pane. public const string MoveBottom = "MoveBottom.Action"; - - /// An action to move the module to a different pane + + /// An action to move the module to a different pane. public const string MovePane = "MovePane.Action"; - - /// An action that contains move actions + + /// An action that contains move actions. public const string MoveRoot = "MoveRoot.Action"; - - /// An action to view the source code of a module + + /// An action to view the source code of a module. public const string ViewSource = "ViewSource.Action"; - - /// An action to create a localized version of a module + + /// An action to create a localized version of a module. public const string LocalizeModule = "Localize.Action"; - - /// An action to remove localization for a module + + /// An action to remove localization for a module. public const string DeLocalizeModule = "DeLocalize.Action"; - - /// An action to create a translated version of a module + + /// An action to create a translated version of a module. public const string TranslateModule = "Translate.Action"; - - /// An action to remove a translation of a module + + /// An action to remove a translation of a module. public const string UnTranslateModule = "UnTranslate.Action"; } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleEventArgs.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleEventArgs.cs index 5a1d3439efa..fe07ea9d714 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleEventArgs.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleEventArgs.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Actions { + using System; + public class ModuleEventArgs : EventArgs { public ModuleInfo Module { get; internal set; } diff --git a/DNN Platform/Library/Entities/Modules/Communications/IModuleCommunicator.cs b/DNN Platform/Library/Entities/Modules/Communications/IModuleCommunicator.cs index 6322afc27e6..c43a10c4906 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/IModuleCommunicator.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/IModuleCommunicator.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Communications { public interface IModuleCommunicator diff --git a/DNN Platform/Library/Entities/Modules/Communications/IModuleListener.cs b/DNN Platform/Library/Entities/Modules/Communications/IModuleListener.cs index 5a561470596..90146e75bd4 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/IModuleListener.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/IModuleListener.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Communications { public interface IModuleListener diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs index 4adb8e6b836..b01b51604ed 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Communications { + using System.Web.UI; + /// - /// Specifies communications between modules. - /// There are listeners and communicators + /// Specifies communications between modules. + /// There are listeners and communicators. /// public class ModuleCommunicate { @@ -30,7 +25,7 @@ public ModuleCommunicators ModuleCommunicators { get { - return _ModuleCommunicators; + return this._ModuleCommunicators; } } @@ -44,52 +39,50 @@ public ModuleListeners ModuleListeners { get { - return _ModuleListeners; + return this._ModuleListeners; } } - - + /// /// Loads the communicator. /// /// The control. public void LoadCommunicator(Control ctrl) { - // Check and see if the module implements IModuleCommunicator + // Check and see if the module implements IModuleCommunicator if (ctrl is IModuleCommunicator) { - Add((IModuleCommunicator) ctrl); + this.Add((IModuleCommunicator)ctrl); } - // Check and see if the module implements IModuleListener + // Check and see if the module implements IModuleListener if (ctrl is IModuleListener) { - Add((IModuleListener) ctrl); + this.Add((IModuleListener)ctrl); } } private int Add(IModuleCommunicator item) { - int returnData = _ModuleCommunicators.Add(item); + int returnData = this._ModuleCommunicators.Add(item); int i = 0; - for (i = 0; i <= _ModuleListeners.Count - 1; i++) + for (i = 0; i <= this._ModuleListeners.Count - 1; i++) { - item.ModuleCommunication += _ModuleListeners[i].OnModuleCommunication; + item.ModuleCommunication += this._ModuleListeners[i].OnModuleCommunication; } - - + return returnData; } private int Add(IModuleListener item) { - int returnData = _ModuleListeners.Add(item); + int returnData = this._ModuleListeners.Add(item); int i = 0; - for (i = 0; i <= _ModuleCommunicators.Count - 1; i++) + for (i = 0; i <= this._ModuleCommunicators.Count - 1; i++) { - _ModuleCommunicators[i].ModuleCommunication += item.OnModuleCommunication; + this._ModuleCommunicators[i].ModuleCommunication += item.OnModuleCommunication; } return returnData; diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventArgs.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventArgs.cs index 7727e78d57e..22f3302906d 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventArgs.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventArgs.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Communications { + using System; + public class ModuleCommunicationEventArgs : EventArgs { public ModuleCommunicationEventArgs() @@ -18,15 +13,15 @@ public ModuleCommunicationEventArgs() public ModuleCommunicationEventArgs(string text) { - Text = text; + this.Text = text; } public ModuleCommunicationEventArgs(string type, object value, string sender, string target) { - Type = type; - Value = value; - Sender = sender; - Target = target; + this.Type = type; + this.Value = value; + this.Sender = sender; + this.Target = target; } public string Sender { get; set; } diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs index 03885523194..09ec41adf44 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Communications { public delegate void ModuleCommunicationEventHandler(object sender, ModuleCommunicationEventArgs e); diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs index 7cb6fc302c3..499f5900467 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs @@ -1,32 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Communications { + using System.Collections; + public class ModuleCommunicators : CollectionBase { public IModuleCommunicator this[int index] { get { - return (IModuleCommunicator) List[index]; + return (IModuleCommunicator)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } public int Add(IModuleCommunicator item) { - return List.Add(item); + return this.List.Add(item); } } } diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs index 4f04f96c9ed..63f1ac81ef4 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs @@ -1,32 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Communications { + using System.Collections; + public class ModuleListeners : CollectionBase { public IModuleListener this[int index] { get { - return (IModuleListener) List[index]; + return (IModuleListener)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } public int Add(IModuleListener item) { - return List.Add(item); + return this.List.Add(item); } } } diff --git a/DNN Platform/Library/Entities/Modules/Communications/RoleChangeEventArgs.cs b/DNN Platform/Library/Entities/Modules/Communications/RoleChangeEventArgs.cs index 663da97546e..1655bf9eccb 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/RoleChangeEventArgs.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/RoleChangeEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Communications { public class RoleChangeEventArgs : ModuleCommunicationEventArgs diff --git a/DNN Platform/Library/Entities/Modules/ControlInfo.cs b/DNN Platform/Library/Entities/Modules/ControlInfo.cs index 12c5afe924d..feef6f6ad06 100644 --- a/DNN Platform/Library/Entities/Modules/ControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ControlInfo.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Data; + using System.Xml; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : ControlInfo + /// Class : ControlInfo /// ----------------------------------------------------------------------------- /// - /// ControlInfo provides a base class for Module Controls and SkinControls + /// ControlInfo provides a base class for Module Controls and SkinControls. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -28,47 +23,47 @@ public abstract class ControlInfo : BaseEntityInfo { protected ControlInfo() { - SupportsPartialRendering = Null.NullBoolean; + this.SupportsPartialRendering = Null.NullBoolean; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Control Key + /// Gets or sets and sets the Control Key. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlKey { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Control Source + /// Gets or sets and sets the Control Source. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - public string ControlSrc { get; set; } + public string ControlSrc { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a flag that determines whether the control support the AJAX - /// Update Panel + /// Gets or sets a value indicating whether gets and sets a flag that determines whether the control support the AJAX + /// Update Panel. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- - public bool SupportsPartialRendering { get; set; } + public bool SupportsPartialRendering { get; set; } /// ----------------------------------------------------------------------------- /// - /// Fills a ControlInfo from a Data Reader + /// Fills a ControlInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- protected override void FillInternal(IDataReader dr) { - //Call EntityBaseInfo's implementation + // Call EntityBaseInfo's implementation base.FillInternal(dr); - ControlKey = Null.SetNullString(dr["ControlKey"]); - ControlSrc = Null.SetNullString(dr["ControlSrc"]); - SupportsPartialRendering = Null.SetNullBoolean(dr["SupportsPartialRendering"]); + this.ControlKey = Null.SetNullString(dr["ControlKey"]); + this.ControlSrc = Null.SetNullString(dr["ControlSrc"]); + this.SupportsPartialRendering = Null.SetNullBoolean(dr["SupportsPartialRendering"]); } protected void ReadXmlInternal(XmlReader reader) @@ -76,27 +71,28 @@ protected void ReadXmlInternal(XmlReader reader) switch (reader.Name) { case "controlKey": - ControlKey = reader.ReadElementContentAsString(); + this.ControlKey = reader.ReadElementContentAsString(); break; case "controlSrc": - ControlSrc = reader.ReadElementContentAsString(); + this.ControlSrc = reader.ReadElementContentAsString(); break; case "supportsPartialRendering": string elementvalue = reader.ReadElementContentAsString(); if (!string.IsNullOrEmpty(elementvalue)) { - SupportsPartialRendering = bool.Parse(elementvalue); + this.SupportsPartialRendering = bool.Parse(elementvalue); } + break; } } protected void WriteXmlInternal(XmlWriter writer) { - //write out properties - writer.WriteElementString("controlKey", ControlKey); - writer.WriteElementString("controlSrc", ControlSrc); - writer.WriteElementString("supportsPartialRendering", SupportsPartialRendering.ToString()); + // write out properties + writer.WriteElementString("controlKey", this.ControlKey); + writer.WriteElementString("controlSrc", this.ControlSrc); + writer.WriteElementString("supportsPartialRendering", this.SupportsPartialRendering.ToString()); } } } diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs index 0c0f39e44eb..8dc4a36c3c9 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs @@ -1,131 +1,126 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Definitions { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Search.Entities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules.Definitions - /// Class : ModuleDefinitionController + /// Class : ModuleDefinitionController /// ----------------------------------------------------------------------------- /// - /// ModuleDefinitionController provides the Business Layer for Module Definitions + /// ModuleDefinitionController provides the Business Layer for Module Definitions. /// /// ----------------------------------------------------------------------------- public class ModuleDefinitionController { private const string key = "ModuleDefID"; - private static readonly DataProvider dataProvider = DataProvider.Instance(); - - #region Private Members + private static readonly DataProvider dataProvider = DataProvider.Instance(); /// ----------------------------------------------------------------------------- /// - /// GetModuleDefinitionsCallBack gets a Dictionary of Module Definitions from - /// the Database. + /// GetModuleDefinitionByID gets a Module Definition by its ID. /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call + /// The ID of the Module Definition. + /// /// ----------------------------------------------------------------------------- - private static object GetModuleDefinitionsCallBack(CacheItemArgs cacheItemArgs) + public static ModuleDefinitionInfo GetModuleDefinitionByID(int moduleDefID) { - return CBO.FillDictionary(key, dataProvider.GetModuleDefinitions(), new Dictionary()); + return (from kvp in GetModuleDefinitions() + where kvp.Value.ModuleDefID == moduleDefID + select kvp.Value) + .FirstOrDefault(); } - #endregion + /// ----------------------------------------------------------------------------- + /// + /// GetModuleDefinitionByFriendlyName gets a Module Definition by its Friendly + /// Name (and DesktopModuleID). + /// + /// The friendly name. + /// + /// ----------------------------------------------------------------------------- + public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string friendlyName) + { + Requires.NotNullOrEmpty("friendlyName", friendlyName); + return (from kvp in GetModuleDefinitions() + where kvp.Value.FriendlyName == friendlyName + select kvp.Value) + .FirstOrDefault(); + } + /// ----------------------------------------------------------------------------- /// - /// GetModuleDefinitionByID gets a Module Definition by its ID + /// GetModuleDefinitionByID gets a Module Definition by its ID. /// - /// The object of the Module Definition + /// The object of the Module Definition. /// ----------------------------------------------------------------------------- public void DeleteModuleDefinition(ModuleDefinitionInfo objModuleDefinition) { - DeleteModuleDefinition(objModuleDefinition.ModuleDefID); + this.DeleteModuleDefinition(objModuleDefinition.ModuleDefID); } /// ----------------------------------------------------------------------------- /// - /// DeleteModuleDefinition deletes a Module Definition By ID + /// DeleteModuleDefinition deletes a Module Definition By ID. /// - /// The ID of the Module Definition to delete + /// The ID of the Module Definition to delete. /// ----------------------------------------------------------------------------- public void DeleteModuleDefinition(int moduleDefinitionId) { - //Delete associated permissions + // Delete associated permissions var permissionController = new PermissionController(); foreach (PermissionInfo permission in permissionController.GetPermissionsByModuleDefID(moduleDefinitionId)) { permissionController.DeletePermission(permission.PermissionID); } + dataProvider.DeleteModuleDefinition(moduleDefinitionId); DataCache.ClearHostCache(true); // queue remove module definition from search index var document = new SearchDocumentToDelete { - ModuleDefId = moduleDefinitionId + ModuleDefId = moduleDefinitionId, }; DataProvider.Instance().AddSearchDeletedItems(document); } - + /// ----------------------------------------------------------------------------- /// - /// GetModuleDefinitionByID gets a Module Definition by its ID + /// GetModuleDefinitionsCallBack gets a Dictionary of Module Definitions from + /// the Database. /// - /// The ID of the Module Definition + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. /// ----------------------------------------------------------------------------- - public static ModuleDefinitionInfo GetModuleDefinitionByID(int moduleDefID) - { - return (from kvp in GetModuleDefinitions() - where kvp.Value.ModuleDefID == moduleDefID - select kvp.Value) - .FirstOrDefault(); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetModuleDefinitionByFriendlyName gets a Module Definition by its Friendly - /// Name (and DesktopModuleID) - /// - /// The friendly name - /// ----------------------------------------------------------------------------- - public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string friendlyName) + private static object GetModuleDefinitionsCallBack(CacheItemArgs cacheItemArgs) { - Requires.NotNullOrEmpty("friendlyName", friendlyName); - - return (from kvp in GetModuleDefinitions() - where kvp.Value.FriendlyName == friendlyName - select kvp.Value) - .FirstOrDefault(); - } + return CBO.FillDictionary(key, dataProvider.GetModuleDefinitions(), new Dictionary()); + } /// ----------------------------------------------------------------------------- /// /// GetModuleDefinitionByFriendlyName gets a Module Definition by its Friendly - /// Name (and DesktopModuleID) + /// Name (and DesktopModuleID). /// - /// The friendly name - /// The ID of the Dekstop Module + /// The friendly name. + /// The ID of the Dekstop Module. + /// /// ----------------------------------------------------------------------------- public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string friendlyName, int desktopModuleID) { @@ -141,13 +136,16 @@ public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string frie /// ----------------------------------------------------------------------------- /// /// GetModuleDefinitions gets a Dictionary of Module Definitions. - /// + /// + /// /// ----------------------------------------------------------------------------- public static Dictionary GetModuleDefinitions() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.ModuleDefinitionCacheKey, - DataCache.ModuleDefinitionCachePriority), - GetModuleDefinitionsCallBack); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.ModuleDefinitionCacheKey, + DataCache.ModuleDefinitionCachePriority), + GetModuleDefinitionsCallBack); } /// ----------------------------------------------------------------------------- @@ -155,21 +153,22 @@ public static Dictionary GetModuleDefinitions() /// GetModuleDefinitionsByDesktopModuleID gets a Dictionary of Module Definitions /// with a particular DesktopModuleID, keyed by the FriendlyName. /// - /// The ID of the Desktop Module + /// The ID of the Desktop Module. + /// /// ----------------------------------------------------------------------------- public static Dictionary GetModuleDefinitionsByDesktopModuleID(int desktopModuleID) { - //Iterate through cached Dictionary to get all Module Definitions with the correct DesktopModuleID + // Iterate through cached Dictionary to get all Module Definitions with the correct DesktopModuleID return GetModuleDefinitions().Where(kvp => kvp.Value.DesktopModuleID == desktopModuleID) .ToDictionary(kvp => kvp.Value.FriendlyName, kvp => kvp.Value); } /// - /// Get ModuleDefinition by DefinitionName + /// Get ModuleDefinition by DefinitionName. /// - /// The defintion name - /// The ID of the Dekstop Module - /// A ModuleDefinition or null if not found + /// The defintion name. + /// The ID of the Dekstop Module. + /// A ModuleDefinition or null if not found. public static ModuleDefinitionInfo GetModuleDefinitionByDefinitionName(string definitionName, int desktopModuleID) { Requires.NotNullOrEmpty("definitionName", definitionName); @@ -183,41 +182,44 @@ public static ModuleDefinitionInfo GetModuleDefinitionByDefinitionName(string de /// ----------------------------------------------------------------------------- /// - /// SaveModuleDefinition saves the Module Definition to the database + /// SaveModuleDefinition saves the Module Definition to the database. /// - /// The Module Definition to save - /// A flag that determines whether the child objects are also saved - /// A flag that determines whether to clear the host cache + /// The Module Definition to save. + /// A flag that determines whether the child objects are also saved. + /// A flag that determines whether to clear the host cache. + /// /// ----------------------------------------------------------------------------- public static int SaveModuleDefinition(ModuleDefinitionInfo moduleDefinition, bool saveChildren, bool clearCache) { int moduleDefinitionID = moduleDefinition.ModuleDefID; if (moduleDefinitionID == Null.NullInteger) { - //Add new Module Definition - moduleDefinitionID = dataProvider.AddModuleDefinition(moduleDefinition.DesktopModuleID, - moduleDefinition.FriendlyName, - moduleDefinition.DefinitionName, - moduleDefinition.DefaultCacheTime, - UserController.Instance.GetCurrentUserInfo().UserID); + // Add new Module Definition + moduleDefinitionID = dataProvider.AddModuleDefinition( + moduleDefinition.DesktopModuleID, + moduleDefinition.FriendlyName, + moduleDefinition.DefinitionName, + moduleDefinition.DefaultCacheTime, + UserController.Instance.GetCurrentUserInfo().UserID); } else { - //Upgrade Module Definition + // Upgrade Module Definition dataProvider.UpdateModuleDefinition(moduleDefinition.ModuleDefID, moduleDefinition.FriendlyName, moduleDefinition.DefinitionName, moduleDefinition.DefaultCacheTime, UserController.Instance.GetCurrentUserInfo().UserID); } + if (saveChildren) { foreach (KeyValuePair kvp in moduleDefinition.Permissions) { kvp.Value.ModuleDefID = moduleDefinitionID; - //check if permission exists + // check if permission exists var permissionController = new PermissionController(); ArrayList permissions = permissionController.GetPermissionByCodeAndKey(kvp.Value.PermissionCode, kvp.Value.PermissionKey); if (permissions != null && permissions.Count == 1) { - var permission = (PermissionInfo) permissions[0]; + var permission = (PermissionInfo)permissions[0]; kvp.Value.PermissionID = permission.PermissionID; permissionController.UpdatePermission(kvp.Value); } @@ -226,23 +228,27 @@ public static int SaveModuleDefinition(ModuleDefinitionInfo moduleDefinition, bo permissionController.AddPermission(kvp.Value); } } + foreach (KeyValuePair kvp in moduleDefinition.ModuleControls) { kvp.Value.ModuleDefID = moduleDefinitionID; - //check if definition exists + // check if definition exists ModuleControlInfo moduleControl = ModuleControlController.GetModuleControlByControlKey(kvp.Value.ControlKey, kvp.Value.ModuleDefID); if (moduleControl != null) { kvp.Value.ModuleControlID = moduleControl.ModuleControlID; } + ModuleControlController.SaveModuleControl(kvp.Value, clearCache); } } + if (clearCache) { DataCache.ClearHostCache(true); } + return moduleDefinitionID; } } diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs index f55738f98e4..f9106b2abd3 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Definitions { + using System; + using System.Collections.Generic; + using System.Data; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security.Permissions; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules.Definitions - /// Class : ModuleDefinitionInfo + /// Class : ModuleDefinitionInfo /// ----------------------------------------------------------------------------- /// - /// ModuleDefinitionInfo provides the Entity Layer for Module Definitions + /// ModuleDefinitionInfo provides the Entity Layer for Module Definitions. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -35,133 +30,130 @@ public class ModuleDefinitionInfo : IXmlSerializable, IHydratable public ModuleDefinitionInfo() { - Permissions = new Dictionary(); - DesktopModuleID = Null.NullInteger; - ModuleDefID = Null.NullInteger; + this.Permissions = new Dictionary(); + this.DesktopModuleID = Null.NullInteger; + this.ModuleDefID = Null.NullInteger; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Module Definition ID + /// Gets or sets and sets the Module Definition ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int ModuleDefID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Default Cache Time + /// Gets or sets and sets the Default Cache Time. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int DefaultCacheTime { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the associated Desktop Module ID + /// Gets or sets and sets the associated Desktop Module ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int DesktopModuleID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Friendly Name + /// Gets or sets and sets the Friendly Name. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string FriendlyName { get; set; } /// - /// Gets the DefinitionName + /// Gets or sets the DefinitionName. /// public string DefinitionName { get { - if(String.IsNullOrEmpty(_definitionName)) + if (string.IsNullOrEmpty(this._definitionName)) { - return FriendlyName; + return this.FriendlyName; } - return _definitionName; + return this._definitionName; } - set { _definitionName = value; } + set { this._definitionName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Dictionary of ModuleControls that are part of this definition + /// Gets the Dictionary of ModuleControls that are part of this definition. /// - /// A Dictionary(Of String, ModuleControlInfo) + /// A Dictionary(Of String, ModuleControlInfo). /// ----------------------------------------------------------------------------- public Dictionary ModuleControls { get { - if (_ModuleControls == null) + if (this._ModuleControls == null) { - LoadControls(); + this.LoadControls(); } - return _ModuleControls; + + return this._ModuleControls; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Dictionary of Permissions that are part of this definition - /// - /// A String - /// ----------------------------------------------------------------------------- - public Dictionary Permissions { get; private set; } - - #region IHydratable Members - - /// ----------------------------------------------------------------------------- - /// - /// Fills a ModuleDefinitionInfo from a Data Reader + /// Gets the Dictionary of Permissions that are part of this definition. /// - /// The Data Reader to use + /// A String. /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); - DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); - DefaultCacheTime = Null.SetNullInteger(dr["DefaultCacheTime"]); - FriendlyName = Null.SetNullString(dr["FriendlyName"]); - if (dr.GetSchemaTable().Select("ColumnName = 'DefinitionName'").Length > 0) - { - DefinitionName = Null.SetNullString(dr["DefinitionName"]); - } - } + public Dictionary Permissions { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Key ID + /// Gets or sets and sets the Key ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int KeyID { get { - return ModuleDefID; + return this.ModuleDefID; } + set { - ModuleDefID = value; + this.ModuleDefID = value; } - } - - #endregion - - #region IXmlSerializable Members - + } + /// ----------------------------------------------------------------------------- /// - /// Gets an XmlSchema for the ModuleDefinitionInfo + /// Fills a ModuleDefinitionInfo from a Data Reader. /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); + this.DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); + this.DefaultCacheTime = Null.SetNullInteger(dr["DefaultCacheTime"]); + this.FriendlyName = Null.SetNullString(dr["FriendlyName"]); + if (dr.GetSchemaTable().Select("ColumnName = 'DefinitionName'").Length > 0) + { + this.DefinitionName = Null.SetNullString(dr["DefinitionName"]); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets an XmlSchema for the ModuleDefinitionInfo. + /// + /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() { @@ -170,9 +162,9 @@ public XmlSchema GetSchema() /// ----------------------------------------------------------------------------- /// - /// Reads a ModuleDefinitionInfo from an XmlReader + /// Reads a ModuleDefinitionInfo from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { @@ -182,13 +174,15 @@ public void ReadXml(XmlReader reader) { break; } + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } + if (reader.NodeType == XmlNodeType.Element && reader.Name == "moduleControls") { - ReadModuleControls(reader); + this.ReadModuleControls(reader); } else { @@ -197,26 +191,28 @@ public void ReadXml(XmlReader reader) case "moduleDefinition": break; case "friendlyName": - FriendlyName = reader.ReadElementContentAsString(); + this.FriendlyName = reader.ReadElementContentAsString(); break; case "defaultCacheTime": string elementvalue = reader.ReadElementContentAsString(); if (!string.IsNullOrEmpty(elementvalue)) { - DefaultCacheTime = int.Parse(elementvalue); + this.DefaultCacheTime = int.Parse(elementvalue); } + break; - case "permissions": //Ignore permissons node + case "permissions": // Ignore permissons node reader.Skip(); break; case "definitionName": - DefinitionName = reader.ReadElementContentAsString(); + this.DefinitionName = reader.ReadElementContentAsString(); break; default: - if(reader.NodeType == XmlNodeType.Element && !String.IsNullOrEmpty(reader.Name)) + if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } + break; } } @@ -225,46 +221,46 @@ public void ReadXml(XmlReader reader) /// ----------------------------------------------------------------------------- /// - /// Writes a ModuleDefinitionInfo to an XmlWriter + /// Writes a ModuleDefinitionInfo to an XmlWriter. /// - /// The XmlWriter to use + /// The XmlWriter to use. /// ----------------------------------------------------------------------------- public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("moduleDefinition"); - //write out properties - writer.WriteElementString("friendlyName", FriendlyName); - writer.WriteElementString("definitionName", DefinitionName); - writer.WriteElementString("defaultCacheTime", DefaultCacheTime.ToString()); + // write out properties + writer.WriteElementString("friendlyName", this.FriendlyName); + writer.WriteElementString("definitionName", this.DefinitionName); + writer.WriteElementString("defaultCacheTime", this.DefaultCacheTime.ToString()); - //Write start of Module Controls + // Write start of Module Controls writer.WriteStartElement("moduleControls"); - //Iterate through controls - foreach (ModuleControlInfo control in ModuleControls.Values) + + // Iterate through controls + foreach (ModuleControlInfo control in this.ModuleControls.Values) { control.WriteXml(writer); } - //Write end of Module Controls + + // Write end of Module Controls writer.WriteEndElement(); - //Write end of main element + // Write end of main element writer.WriteEndElement(); - } - - #endregion - + } + public void LoadControls() { - _ModuleControls = ModuleDefID > Null.NullInteger ? ModuleControlController.GetModuleControlsByModuleDefinitionID(ModuleDefID) : new Dictionary(); + this._ModuleControls = this.ModuleDefID > Null.NullInteger ? ModuleControlController.GetModuleControlsByModuleDefinitionID(this.ModuleDefID) : new Dictionary(); } /// ----------------------------------------------------------------------------- /// - /// Reads the ModuleControls from an XmlReader + /// Reads the ModuleControls from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- private void ReadModuleControls(XmlReader reader) { @@ -274,8 +270,9 @@ private void ReadModuleControls(XmlReader reader) reader.ReadStartElement("moduleControl"); var moduleControl = new ModuleControlInfo(); moduleControl.ReadXml(reader); - ModuleControls.Add(moduleControl.ControlKey, moduleControl); - } while (reader.ReadToNextSibling("moduleControl")); + this.ModuleControls.Add(moduleControl.ControlKey, moduleControl); + } + while (reader.ReadToNextSibling("moduleControl")); } } } diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs index 1cd60457c9f..2f623a9b90d 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Definitions { + using System; + using System.IO; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + public enum ModuleDefinitionVersion { VUnknown = 0, @@ -24,45 +19,11 @@ public enum ModuleDefinitionVersion V2 = 2, V2_Skin = 3, V2_Provider = 4, - V3 = 5 + V3 = 5, } public class ModuleDefinitionValidator : XmlValidatorBase { - private string GetDnnSchemaPath(Stream xmlStream) - { - ModuleDefinitionVersion Version = GetModuleDefinitionVersion(xmlStream); - string schemaPath = ""; - switch (Version) - { - case ModuleDefinitionVersion.V2: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V2.xsd"; - break; - case ModuleDefinitionVersion.V3: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V3.xsd"; - break; - case ModuleDefinitionVersion.V2_Skin: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Skin.xsd"; - break; - case ModuleDefinitionVersion.V2_Provider: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Provider.xsd"; - break; - case ModuleDefinitionVersion.VUnknown: - throw new Exception(GetLocalizedString("EXCEPTION_LoadFailed")); - } - return Path.Combine(Globals.ApplicationMapPath, schemaPath); - } - - private static string GetLocalizedString(string key) - { - var objPortalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"]; - if (objPortalSettings == null) - { - return key; - } - return Localization.GetString(key, objPortalSettings); - } - public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) { ModuleDefinitionVersion retValue; @@ -70,11 +31,11 @@ public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) var xmlReader = new XmlTextReader(xmlStream) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; xmlReader.MoveToContent(); - //This test assumes provides a simple validation + // This test assumes provides a simple validation switch (xmlReader.LocalName.ToLowerInvariant()) { case "module": @@ -95,6 +56,7 @@ public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) default: return ModuleDefinitionVersion.VUnknown; } + break; case "SkinObject": retValue = ModuleDefinitionVersion.V2_Skin; @@ -106,18 +68,56 @@ public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) retValue = ModuleDefinitionVersion.VUnknown; break; } + break; default: retValue = ModuleDefinitionVersion.VUnknown; break; } + return retValue; } public override bool Validate(Stream XmlStream) { - SchemaSet.Add("", GetDnnSchemaPath(XmlStream)); + this.SchemaSet.Add(string.Empty, this.GetDnnSchemaPath(XmlStream)); return base.Validate(XmlStream); } + + private static string GetLocalizedString(string key) + { + var objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; + if (objPortalSettings == null) + { + return key; + } + + return Localization.GetString(key, objPortalSettings); + } + + private string GetDnnSchemaPath(Stream xmlStream) + { + ModuleDefinitionVersion Version = this.GetModuleDefinitionVersion(xmlStream); + string schemaPath = string.Empty; + switch (Version) + { + case ModuleDefinitionVersion.V2: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V2.xsd"; + break; + case ModuleDefinitionVersion.V3: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V3.xsd"; + break; + case ModuleDefinitionVersion.V2_Skin: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Skin.xsd"; + break; + case ModuleDefinitionVersion.V2_Provider: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Provider.xsd"; + break; + case ModuleDefinitionVersion.VUnknown: + throw new Exception(GetLocalizedString("EXCEPTION_LoadFailed")); + } + + return Path.Combine(Globals.ApplicationMapPath, schemaPath); + } } } diff --git a/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs b/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs index a56100cebd1..cf82a74dc5f 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs @@ -1,110 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Xml; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.EventQueue; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Upgrade; -using Microsoft.VisualBasic.Logging; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.EventQueue; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Upgrade; + using Microsoft.VisualBasic.Logging; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : DesktopModuleController + /// Class : DesktopModuleController /// ----------------------------------------------------------------------------- /// - /// DesktopModuleController provides the Busines Layer for Desktop Modules + /// DesktopModuleController provides the Busines Layer for Desktop Modules. /// /// ----------------------------------------------------------------------------- public class DesktopModuleController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DesktopModuleController)); - #region Private Methods - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DesktopModuleController)); private static readonly DataProvider DataProvider = DataProvider.Instance(); - - private static Dictionary GetDesktopModulesInternal(int portalID) - { - string cacheKey = string.Format(DataCache.DesktopModuleCacheKey, portalID); - var args = new CacheItemArgs(cacheKey, DataCache.DesktopModuleCacheTimeOut, DataCache.DesktopModuleCachePriority, portalID); - Dictionary desktopModules = (portalID == Null.NullInteger) - ? CBO.GetCachedObject>(args, GetDesktopModulesCallBack) - : CBO.GetCachedObject>(args, GetDesktopModulesByPortalCallBack); - return desktopModules; - } - - private static object GetDesktopModulesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModules(), new Dictionary()); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetDesktopModulesByPortalCallBack gets a Dictionary of Desktop Modules by - /// Portal from the the Database. - /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call - /// ----------------------------------------------------------------------------- - private static object GetDesktopModulesByPortalCallBack(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModulesByPortal(portalId), new Dictionary()); - } - - private static object GetPortalDesktopModulesByPortalIDCallBack(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - return CBO.FillDictionary("PortalDesktopModuleID", DataProvider.Instance().GetPortalDesktopModules(portalId, Null.NullInteger), new Dictionary()); - } - - private static void CreateContentItem(DesktopModuleInfo desktopModule) - { - IContentTypeController typeController = new ContentTypeController(); - ContentType contentType = ContentType.DesktopModule; - - if (contentType == null) - { - contentType = new ContentType { ContentType = "DesktopModule" }; - contentType.ContentTypeId = typeController.AddContentType(contentType); - } - - IContentController contentController = Util.GetContentController(); - desktopModule.Content = desktopModule.FriendlyName; - desktopModule.Indexed = false; - desktopModule.ContentTypeId = contentType.ContentTypeId; - desktopModule.ContentItemId = contentController.AddContentItem(desktopModule); - } - - #endregion - - #region DesktopModule Methods - + public static void AddModuleCategory(string category) { var termController = Util.GetTermController(); @@ -132,37 +68,9 @@ public static void AddModuleCategory(string category) /// ----------------------------------------------------------------------------- /// - /// DeleteDesktopModule deletes a Desktop Module + /// DeleteDesktopModule deletes a Desktop Module. /// - /// Desktop Module Info - /// ----------------------------------------------------------------------------- - public void DeleteDesktopModule(DesktopModuleInfo objDesktopModule) - { - DeleteDesktopModule(objDesktopModule.DesktopModuleID); - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteDesktopModule deletes a Desktop Module By ID - /// - /// The ID of the Desktop Module to delete - /// ----------------------------------------------------------------------------- - public void DeleteDesktopModule(int desktopModuleID) - { - DataProvider.DeleteDesktopModule(desktopModuleID); - EventLogController.Instance.AddLog("DesktopModuleID", - desktopModuleID.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.DESKTOPMODULE_DELETED); - DataCache.ClearHostCache(true); - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteDesktopModule deletes a Desktop Module - /// - /// The Name of the Desktop Module to delete + /// The Name of the Desktop Module to delete. /// ----------------------------------------------------------------------------- public static void DeleteDesktopModule(string moduleName) { @@ -171,20 +79,22 @@ public static void DeleteDesktopModule(string moduleName) { var controller = new DesktopModuleController(); controller.DeleteDesktopModule(desktopModule.DesktopModuleID); - //Delete the Package + + // Delete the Package PackageController.Instance.DeleteExtensionPackage(PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == desktopModule.PackageID)); } } /// ----------------------------------------------------------------------------- /// - /// GetDesktopModule gets a Desktop Module by its ID + /// GetDesktopModule gets a Desktop Module by its ID. /// /// This method uses the cached Dictionary of DesktopModules. It first checks /// if the DesktopModule is in the cache. If it is not in the cache it then makes a call /// to the Dataprovider. - /// The ID of the Desktop Module to get - /// The ID of the portal + /// The ID of the Desktop Module to get. + /// The ID of the portal. + /// /// ----------------------------------------------------------------------------- public static DesktopModuleInfo GetDesktopModule(int desktopModuleID, int portalID) { @@ -201,17 +111,102 @@ public static DesktopModuleInfo GetDesktopModule(int desktopModuleID, int portal .FirstOrDefault(); } - if (module == null) - Logger.WarnFormat("Unable to find module by module ID. ID:{0} PortalID:{1}", desktopModuleID, portalID); - + if (module == null) + { + Logger.WarnFormat("Unable to find module by module ID. ID:{0} PortalID:{1}", desktopModuleID, portalID); + } + return module; } /// ----------------------------------------------------------------------------- /// - /// GetDesktopModuleByPackageID gets a Desktop Module by its Package ID + /// DeleteDesktopModule deletes a Desktop Module. + /// + /// Desktop Module Info. + /// ----------------------------------------------------------------------------- + public void DeleteDesktopModule(DesktopModuleInfo objDesktopModule) + { + this.DeleteDesktopModule(objDesktopModule.DesktopModuleID); + } + + private static Dictionary GetDesktopModulesInternal(int portalID) + { + string cacheKey = string.Format(DataCache.DesktopModuleCacheKey, portalID); + var args = new CacheItemArgs(cacheKey, DataCache.DesktopModuleCacheTimeOut, DataCache.DesktopModuleCachePriority, portalID); + Dictionary desktopModules = (portalID == Null.NullInteger) + ? CBO.GetCachedObject>(args, GetDesktopModulesCallBack) + : CBO.GetCachedObject>(args, GetDesktopModulesByPortalCallBack); + return desktopModules; + } + + private static object GetDesktopModulesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModules(), new Dictionary()); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetDesktopModulesByPortalCallBack gets a Dictionary of Desktop Modules by + /// Portal from the the Database. /// - /// The ID of the Package + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. + /// ----------------------------------------------------------------------------- + private static object GetDesktopModulesByPortalCallBack(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModulesByPortal(portalId), new Dictionary()); + } + + private static object GetPortalDesktopModulesByPortalIDCallBack(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + return CBO.FillDictionary("PortalDesktopModuleID", DataProvider.Instance().GetPortalDesktopModules(portalId, Null.NullInteger), new Dictionary()); + } + + private static void CreateContentItem(DesktopModuleInfo desktopModule) + { + IContentTypeController typeController = new ContentTypeController(); + ContentType contentType = ContentType.DesktopModule; + + if (contentType == null) + { + contentType = new ContentType { ContentType = "DesktopModule" }; + contentType.ContentTypeId = typeController.AddContentType(contentType); + } + + IContentController contentController = Util.GetContentController(); + desktopModule.Content = desktopModule.FriendlyName; + desktopModule.Indexed = false; + desktopModule.ContentTypeId = contentType.ContentTypeId; + desktopModule.ContentItemId = contentController.AddContentItem(desktopModule); + } + + /// ----------------------------------------------------------------------------- + /// + /// DeleteDesktopModule deletes a Desktop Module By ID. + /// + /// The ID of the Desktop Module to delete. + /// ----------------------------------------------------------------------------- + public void DeleteDesktopModule(int desktopModuleID) + { + DataProvider.DeleteDesktopModule(desktopModuleID); + EventLogController.Instance.AddLog( + "DesktopModuleID", + desktopModuleID.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.DESKTOPMODULE_DELETED); + DataCache.ClearHostCache(true); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetDesktopModuleByPackageID gets a Desktop Module by its Package ID. + /// + /// The ID of the Package. + /// /// ----------------------------------------------------------------------------- public static DesktopModuleInfo GetDesktopModuleByPackageID(int packageID) { @@ -220,21 +215,24 @@ public static DesktopModuleInfo GetDesktopModuleByPackageID(int packageID) select kvp.Value) .FirstOrDefault(); - if (desktopModuleByPackageID == null) - Logger.WarnFormat("Unable to find module by package ID. ID:{0}", packageID); - + if (desktopModuleByPackageID == null) + { + Logger.WarnFormat("Unable to find module by package ID. ID:{0}", packageID); + } + return desktopModuleByPackageID; } /// ----------------------------------------------------------------------------- /// - /// GetDesktopModuleByModuleName gets a Desktop Module by its Name + /// GetDesktopModuleByModuleName gets a Desktop Module by its Name. /// /// This method uses the cached Dictionary of DesktopModules. It first checks /// if the DesktopModule is in the cache. If it is not in the cache it then makes a call /// to the Dataprovider. - /// The name of the Desktop Module to get - /// The ID of the portal + /// The name of the Desktop Module to get. + /// The ID of the portal. + /// /// ----------------------------------------------------------------------------- public static DesktopModuleInfo GetDesktopModuleByModuleName(string moduleName, int portalID) { @@ -242,18 +240,21 @@ public static DesktopModuleInfo GetDesktopModuleByModuleName(string moduleName, where kvp.Value.ModuleName == moduleName select kvp.Value).FirstOrDefault(); - if (desktopModuleByModuleName == null) - Logger.WarnFormat("Unable to find module by name. Name:{0} portalId:{1}", moduleName, portalID); - + if (desktopModuleByModuleName == null) + { + Logger.WarnFormat("Unable to find module by name. Name:{0} portalId:{1}", moduleName, portalID); + } + return desktopModuleByModuleName; } /// ----------------------------------------------------------------------------- /// - /// GetDesktopModules gets a Dictionary of Desktop Modules + /// GetDesktopModules gets a Dictionary of Desktop Modules. /// /// The ID of the Portal (Use PortalID = Null.NullInteger (-1) to get - /// all the DesktopModules including Modules not allowed for the current portal + /// all the DesktopModules including Modules not allowed for the current portal. + /// /// ----------------------------------------------------------------------------- public static Dictionary GetDesktopModules(int portalID) { @@ -264,214 +265,223 @@ public static DesktopModuleInfo GetDesktopModuleByFriendlyName(string friendlyNa { var module = (from kvp in GetDesktopModulesInternal(Null.NullInteger) where kvp.Value.FriendlyName == friendlyName select kvp.Value).FirstOrDefault(); - if (module== null) - Logger.WarnFormat("Unable to find module by friendly name. Name:{0}", friendlyName); - + if (module == null) + { + Logger.WarnFormat("Unable to find module by friendly name. Name:{0}", friendlyName); + } + return module; } /// ----------------------------------------------------------------------------- /// - /// SaveDesktopModule saves the Desktop Module to the database + /// SaveDesktopModule saves the Desktop Module to the database. /// - /// The Desktop Module to save - /// A flag that determines whether the child objects are also saved - /// A flag that determines whether to clear the host cache + /// The Desktop Module to save. + /// A flag that determines whether the child objects are also saved. + /// A flag that determines whether to clear the host cache. + /// /// ----------------------------------------------------------------------------- public static int SaveDesktopModule(DesktopModuleInfo desktopModule, bool saveChildren, bool clearCache) { return SaveDesktopModule(desktopModule, saveChildren, clearCache, true); } - - internal static int SaveDesktopModule(DesktopModuleInfo desktopModule, bool saveChildren, bool clearCache, bool saveTerms) + + public static int AddDesktopModuleToPortal(int portalID, DesktopModuleInfo desktopModule, DesktopModulePermissionCollection permissions, bool clearCache) { - var desktopModuleID = desktopModule.DesktopModuleID; - if (desktopModuleID == Null.NullInteger) - { - CreateContentItem(desktopModule); - desktopModuleID = DataProvider.AddDesktopModule(desktopModule.PackageID, - desktopModule.ModuleName, - desktopModule.FolderName, - desktopModule.FriendlyName, - desktopModule.Description, - desktopModule.Version, - desktopModule.IsPremium, - desktopModule.IsAdmin, - desktopModule.BusinessControllerClass, - desktopModule.SupportedFeatures, - (int)desktopModule.Shareable, - desktopModule.CompatibleVersions, - desktopModule.Dependencies, - desktopModule.Permissions, - desktopModule.ContentItemId, - UserController.Instance.GetCurrentUserInfo().UserID, - desktopModule.AdminPage, desktopModule.HostPage); - EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.DESKTOPMODULE_CREATED); - } - else + int portalDesktopModuleID = AddDesktopModuleToPortal(portalID, desktopModule.DesktopModuleID, false, clearCache); + if (portalDesktopModuleID > Null.NullInteger) { - //Update ContentItem If neccessary - if (desktopModule.ContentItemId == Null.NullInteger) + DesktopModulePermissionController.DeleteDesktopModulePermissionsByPortalDesktopModuleID(portalDesktopModuleID); + foreach (DesktopModulePermissionInfo permission in permissions) { - CreateContentItem(desktopModule); + permission.PortalDesktopModuleID = portalDesktopModuleID; + DesktopModulePermissionController.AddDesktopModulePermission(permission); } + } + + return portalDesktopModuleID; + } - DataProvider.UpdateDesktopModule(desktopModule.DesktopModuleID, - desktopModule.PackageID, - desktopModule.ModuleName, - desktopModule.FolderName, - desktopModule.FriendlyName, - desktopModule.Description, - desktopModule.Version, - desktopModule.IsPremium, - desktopModule.IsAdmin, - desktopModule.BusinessControllerClass, - desktopModule.SupportedFeatures, - (int)desktopModule.Shareable, - desktopModule.CompatibleVersions, - desktopModule.Dependencies, - desktopModule.Permissions, - desktopModule.ContentItemId, - UserController.Instance.GetCurrentUserInfo().UserID, - desktopModule.AdminPage, - desktopModule.HostPage); - - //Update Tags - if (saveTerms) + public static int AddDesktopModuleToPortal(int portalId, int desktopModuleId, bool addPermissions, bool clearCache) + { + int portalDesktopModuleID; + PortalDesktopModuleInfo portalDesktopModule = GetPortalDesktopModule(portalId, desktopModuleId); + if (portalDesktopModule == null) + { + portalDesktopModuleID = DataProvider.Instance().AddPortalDesktopModule(portalId, desktopModuleId, UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog( + "PortalDesktopModuleID", + portalDesktopModuleID.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALDESKTOPMODULE_CREATED); + if (addPermissions) { - var termController = Util.GetTermController(); - termController.RemoveTermsFromContent(desktopModule); - foreach (var term in desktopModule.Terms) + ArrayList permissions = PermissionController.GetPermissionsByPortalDesktopModule(); + if (permissions.Count > 0) { - termController.AddTermToContent(term, desktopModule); + var permission = permissions[0] as PermissionInfo; + PortalInfo objPortal = PortalController.Instance.GetPortal(portalId); + if (permission != null && objPortal != null) + { + var desktopModulePermission = new DesktopModulePermissionInfo(permission) { RoleID = objPortal.AdministratorRoleId, AllowAccess = true, PortalDesktopModuleID = portalDesktopModuleID }; + DesktopModulePermissionController.AddDesktopModulePermission(desktopModulePermission); + } } } - - EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.DESKTOPMODULE_UPDATED); } - if (saveChildren) + else { - foreach (var definition in desktopModule.ModuleDefinitions.Values) - { - definition.DesktopModuleID = desktopModuleID; - var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName(definition.DefinitionName, desktopModuleID); - if (moduleDefinition != null) - { - definition.ModuleDefID = moduleDefinition.ModuleDefID; - } - ModuleDefinitionController.SaveModuleDefinition(definition, true, clearCache); - } + portalDesktopModuleID = portalDesktopModule.PortalDesktopModuleID; } + if (clearCache) { - DataCache.ClearHostCache(true); + DataCache.ClearPortalCache(portalId, true); } - return desktopModuleID; + + return portalDesktopModuleID; } public void UpdateModuleInterfaces(ref DesktopModuleInfo desktopModuleInfo) { - UpdateModuleInterfaces(ref desktopModuleInfo, (UserController.Instance.GetCurrentUserInfo() == null) ? "" : UserController.Instance.GetCurrentUserInfo().Username, true); + this.UpdateModuleInterfaces(ref desktopModuleInfo, (UserController.Instance.GetCurrentUserInfo() == null) ? string.Empty : UserController.Instance.GetCurrentUserInfo().Username, true); } public void UpdateModuleInterfaces(ref DesktopModuleInfo desktopModuleInfo, string sender, bool forceAppRestart) { - CheckInterfacesImplementation(ref desktopModuleInfo); + this.CheckInterfacesImplementation(ref desktopModuleInfo); var oAppStartMessage = new EventMessage { Sender = sender, Priority = MessagePriority.High, ExpirationDate = DateTime.Now.AddYears(-1), SentDate = DateTime.Now, - Body = "", + Body = string.Empty, ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", - ProcessorCommand = "UpdateSupportedFeatures" + ProcessorCommand = "UpdateSupportedFeatures", }; oAppStartMessage.Attributes.Add("BusinessControllerClass", desktopModuleInfo.BusinessControllerClass); oAppStartMessage.Attributes.Add("DesktopModuleId", desktopModuleInfo.DesktopModuleID.ToString()); EventQueueController.SendMessage(oAppStartMessage, "Application_Start"); - if ((forceAppRestart)) + if (forceAppRestart) { Config.Touch(); } - } - private void CheckInterfacesImplementation(ref DesktopModuleInfo desktopModuleInfo) - { - var businessController = Reflection.CreateType(desktopModuleInfo.BusinessControllerClass); - var controller = Reflection.CreateObject(desktopModuleInfo.BusinessControllerClass, desktopModuleInfo.BusinessControllerClass); - - desktopModuleInfo.IsPortable = businessController.GetInterfaces().Contains(typeof (IPortable)); -#pragma warning disable 0618 - desktopModuleInfo.IsSearchable = (controller is ModuleSearchBase) || businessController.GetInterfaces().Contains(typeof(ISearchable)); -#pragma warning restore 0618 - desktopModuleInfo.IsUpgradeable = businessController.GetInterfaces().Contains(typeof(IUpgradeable)); - } - - #endregion - - #region PortalDesktopModuleMethods - - public static int AddDesktopModuleToPortal(int portalID, DesktopModuleInfo desktopModule, DesktopModulePermissionCollection permissions, bool clearCache) + internal static int SaveDesktopModule(DesktopModuleInfo desktopModule, bool saveChildren, bool clearCache, bool saveTerms) { - int portalDesktopModuleID = AddDesktopModuleToPortal(portalID, desktopModule.DesktopModuleID, false, clearCache); - if (portalDesktopModuleID > Null.NullInteger) + var desktopModuleID = desktopModule.DesktopModuleID; + if (desktopModuleID == Null.NullInteger) { - DesktopModulePermissionController.DeleteDesktopModulePermissionsByPortalDesktopModuleID(portalDesktopModuleID); - foreach (DesktopModulePermissionInfo permission in permissions) + CreateContentItem(desktopModule); + desktopModuleID = DataProvider.AddDesktopModule( + desktopModule.PackageID, + desktopModule.ModuleName, + desktopModule.FolderName, + desktopModule.FriendlyName, + desktopModule.Description, + desktopModule.Version, + desktopModule.IsPremium, + desktopModule.IsAdmin, + desktopModule.BusinessControllerClass, + desktopModule.SupportedFeatures, + (int)desktopModule.Shareable, + desktopModule.CompatibleVersions, + desktopModule.Dependencies, + desktopModule.Permissions, + desktopModule.ContentItemId, + UserController.Instance.GetCurrentUserInfo().UserID, + desktopModule.AdminPage, desktopModule.HostPage); + EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.DESKTOPMODULE_CREATED); + } + else + { + // Update ContentItem If neccessary + if (desktopModule.ContentItemId == Null.NullInteger) { - permission.PortalDesktopModuleID = portalDesktopModuleID; - DesktopModulePermissionController.AddDesktopModulePermission(permission); + CreateContentItem(desktopModule); } - } - return portalDesktopModuleID; - } - public static int AddDesktopModuleToPortal(int portalId, int desktopModuleId, bool addPermissions, bool clearCache) - { - int portalDesktopModuleID; - PortalDesktopModuleInfo portalDesktopModule = GetPortalDesktopModule(portalId, desktopModuleId); - if (portalDesktopModule == null) - { - portalDesktopModuleID = DataProvider.Instance().AddPortalDesktopModule(portalId, desktopModuleId, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog("PortalDesktopModuleID", - portalDesktopModuleID.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTALDESKTOPMODULE_CREATED); - if (addPermissions) + DataProvider.UpdateDesktopModule( + desktopModule.DesktopModuleID, + desktopModule.PackageID, + desktopModule.ModuleName, + desktopModule.FolderName, + desktopModule.FriendlyName, + desktopModule.Description, + desktopModule.Version, + desktopModule.IsPremium, + desktopModule.IsAdmin, + desktopModule.BusinessControllerClass, + desktopModule.SupportedFeatures, + (int)desktopModule.Shareable, + desktopModule.CompatibleVersions, + desktopModule.Dependencies, + desktopModule.Permissions, + desktopModule.ContentItemId, + UserController.Instance.GetCurrentUserInfo().UserID, + desktopModule.AdminPage, + desktopModule.HostPage); + + // Update Tags + if (saveTerms) { - ArrayList permissions = PermissionController.GetPermissionsByPortalDesktopModule(); - if (permissions.Count > 0) + var termController = Util.GetTermController(); + termController.RemoveTermsFromContent(desktopModule); + foreach (var term in desktopModule.Terms) { - var permission = permissions[0] as PermissionInfo; - PortalInfo objPortal = PortalController.Instance.GetPortal(portalId); - if (permission != null && objPortal != null) - { - var desktopModulePermission = new DesktopModulePermissionInfo(permission) { RoleID = objPortal.AdministratorRoleId, AllowAccess = true, PortalDesktopModuleID = portalDesktopModuleID }; - DesktopModulePermissionController.AddDesktopModulePermission(desktopModulePermission); - } + termController.AddTermToContent(term, desktopModule); } } + + EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.DESKTOPMODULE_UPDATED); } - else + + if (saveChildren) { - portalDesktopModuleID = portalDesktopModule.PortalDesktopModuleID; + foreach (var definition in desktopModule.ModuleDefinitions.Values) + { + definition.DesktopModuleID = desktopModuleID; + var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName(definition.DefinitionName, desktopModuleID); + if (moduleDefinition != null) + { + definition.ModuleDefID = moduleDefinition.ModuleDefID; + } + + ModuleDefinitionController.SaveModuleDefinition(definition, true, clearCache); + } } + if (clearCache) { - DataCache.ClearPortalCache(portalId, true); + DataCache.ClearHostCache(true); } - return portalDesktopModuleID; + + return desktopModuleID; } + private void CheckInterfacesImplementation(ref DesktopModuleInfo desktopModuleInfo) + { + var businessController = Reflection.CreateType(desktopModuleInfo.BusinessControllerClass); + var controller = Reflection.CreateObject(desktopModuleInfo.BusinessControllerClass, desktopModuleInfo.BusinessControllerClass); + + desktopModuleInfo.IsPortable = businessController.GetInterfaces().Contains(typeof(IPortable)); +#pragma warning disable 0618 + desktopModuleInfo.IsSearchable = (controller is ModuleSearchBase) || businessController.GetInterfaces().Contains(typeof(ISearchable)); +#pragma warning restore 0618 + desktopModuleInfo.IsUpgradeable = businessController.GetInterfaces().Contains(typeof(IUpgradeable)); + } + public static void AddDesktopModuleToPortals(int desktopModuleId) { foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { AddDesktopModuleToPortal(portal.PortalID, desktopModuleId, true, false); } + DataCache.ClearHostCache(true); } @@ -490,9 +500,9 @@ public static void AddDesktopModulesToPortal(int portalId) { AddDesktopModuleToPortal(portalId, desktopModule.DesktopModuleID, !desktopModule.IsAdmin, false); } - } } + DataCache.ClearPortalCache(portalId, true); } @@ -525,17 +535,19 @@ public static SortedList GetPortalDesktopModule lstModules.Add(desktopModule.FriendlyName, desktopModule); } } + return lstModules; } public static void RemoveDesktopModuleFromPortal(int portalId, int desktopModuleId, bool clearCache) { DataProvider.Instance().DeletePortalDesktopModules(portalId, desktopModuleId); - EventLogController.Instance.AddLog("DesktopModuleID", - desktopModuleId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); + EventLogController.Instance.AddLog( + "DesktopModuleID", + desktopModuleId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); if (clearCache) { DataCache.ClearPortalCache(portalId, false); @@ -545,22 +557,24 @@ public static void RemoveDesktopModuleFromPortal(int portalId, int desktopModule public static void RemoveDesktopModuleFromPortals(int desktopModuleId) { DataProvider.Instance().DeletePortalDesktopModules(Null.NullInteger, desktopModuleId); - EventLogController.Instance.AddLog("DesktopModuleID", - desktopModuleId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); + EventLogController.Instance.AddLog( + "DesktopModuleID", + desktopModuleId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); DataCache.ClearHostCache(true); } public static void RemoveDesktopModulesFromPortal(int portalId) { DataProvider.Instance().DeletePortalDesktopModules(portalId, Null.NullInteger); - EventLogController.Instance.AddLog("PortalID", - portalId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); + EventLogController.Instance.AddLog( + "PortalID", + portalId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); DataCache.ClearPortalCache(portalId, true); } @@ -581,14 +595,14 @@ public static void SerializePortalDesktopModules(XmlWriter writer, int portalId) writer.WriteElementString("rolename", permission.RoleName); writer.WriteEndElement(); } + writer.WriteEndElement(); writer.WriteEndElement(); } + writer.WriteEndElement(); - } - - #region Interal Methods - + } + internal static void AddDesktopModulePageToPortal(DesktopModuleInfo desktopModule, string pageName, int portalId, ref bool createdNewPage, ref bool addedNewModule) { var tabPath = string.Format("//{0}//{1}", portalId == Null.NullInteger ? "Host" : "Admin", pageName); @@ -598,20 +612,22 @@ internal static void AddDesktopModulePageToPortal(DesktopModuleInfo desktopModul { if (portalId == Null.NullInteger) { - existTab = Upgrade.AddHostPage(pageName, - desktopModule.Page.Description, - desktopModule.Page.Icon, - desktopModule.Page.LargeIcon, - true); + existTab = Upgrade.AddHostPage( + pageName, + desktopModule.Page.Description, + desktopModule.Page.Icon, + desktopModule.Page.LargeIcon, + true); } else { - existTab = Upgrade.AddAdminPage(PortalController.Instance.GetPortal(portalId), - pageName, - desktopModule.Page.Description, - desktopModule.Page.Icon, - desktopModule.Page.LargeIcon, - true); + existTab = Upgrade.AddAdminPage( + PortalController.Instance.GetPortal(portalId), + pageName, + desktopModule.Page.Description, + desktopModule.Page.Icon, + desktopModule.Page.LargeIcon, + true); } createdNewPage = true; @@ -641,7 +657,8 @@ internal static void AddDesktopModuleToPage(DesktopModuleInfo desktopModule, Tab { if (tabModules.All(m => m.ModuleDefinition.ModuleDefID != moduleDefinition.ModuleDefID)) { - Upgrade.AddModuleToPage(tab, + Upgrade.AddModuleToPage( + tab, moduleDefinition.ModuleDefID, desktopModule.Page.Description, desktopModule.Page.Icon, @@ -650,11 +667,6 @@ internal static void AddDesktopModuleToPage(DesktopModuleInfo desktopModule, Tab addedNewModule = true; } } - - } - - #endregion - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs b/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs index 1a780f88c27..7b6676d4d14 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs @@ -1,45 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Web.UI; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Web.UI; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : DesktopModuleInfo + /// Class : DesktopModuleInfo /// ----------------------------------------------------------------------------- /// - /// DesktopModuleInfo provides the Entity Layer for Desktop Modules + /// DesktopModuleInfo provides the Entity Layer for Desktop Modules. /// /// ----------------------------------------------------------------------------- [Serializable] public class DesktopModuleInfo : ContentItem, IXmlSerializable - { - #region Inner Classes + { + private Dictionary _moduleDefinitions; + private PageInfo _pageInfo; + public DesktopModuleInfo() + { + this.IsPremium = Null.NullBoolean; + this.IsAdmin = Null.NullBoolean; + this.CodeSubDirectory = Null.NullString; + this.PackageID = Null.NullInteger; + this.DesktopModuleID = Null.NullInteger; + this.SupportedFeatures = Null.NullInteger; + this.Shareable = ModuleSharing.Unknown; + } + [Serializable] public class PageInfo : IXmlSerializable { @@ -63,15 +70,14 @@ public class PageInfo : IXmlSerializable public bool HasAdminPage() { - return Type.IndexOf("admin", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; + return this.Type.IndexOf("admin", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; } public bool HasHostPage() { - return Type.IndexOf("host", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; + return this.Type.IndexOf("host", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; } - - + public XmlSchema GetSchema() { return null; @@ -101,26 +107,26 @@ public void ReadXml(XmlReader reader) switch (reader.Name) { case "page": - Type = reader.GetAttribute("type"); + this.Type = reader.GetAttribute("type"); var commonValue = reader.GetAttribute("common"); if (!string.IsNullOrEmpty(commonValue)) { - IsCommon = commonValue.Equals("true", StringComparison.InvariantCultureIgnoreCase); + this.IsCommon = commonValue.Equals("true", StringComparison.InvariantCultureIgnoreCase); } reader.Read(); break; case "name": - Name = reader.ReadElementContentAsString(); + this.Name = reader.ReadElementContentAsString(); break; case "icon": - Icon = reader.ReadElementContentAsString(); + this.Icon = reader.ReadElementContentAsString(); break; case "largeIcon": - LargeIcon = reader.ReadElementContentAsString(); + this.LargeIcon = reader.ReadElementContentAsString(); break; case "description": - Description = reader.ReadElementContentAsString(); + this.Description = reader.ReadElementContentAsString(); break; default: reader.Read(); @@ -131,66 +137,48 @@ public void ReadXml(XmlReader reader) public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("page"); - writer.WriteAttributeString("type", Type); - writer.WriteAttributeString("common", IsCommon.ToString().ToLowerInvariant()); + writer.WriteAttributeString("type", this.Type); + writer.WriteAttributeString("common", this.IsCommon.ToString().ToLowerInvariant()); - //write out properties - writer.WriteElementString("name", Name); - writer.WriteElementString("icon", Icon); - writer.WriteElementString("largeIcon", LargeIcon); - writer.WriteElementString("description", Description); + // write out properties + writer.WriteElementString("name", this.Name); + writer.WriteElementString("icon", this.Icon); + writer.WriteElementString("largeIcon", this.LargeIcon); + writer.WriteElementString("description", this.Description); - //Write end of main element + // Write end of main element writer.WriteEndElement(); } - } - - #endregion - - private Dictionary _moduleDefinitions; - private PageInfo _pageInfo; - - public DesktopModuleInfo() - { - IsPremium = Null.NullBoolean; - IsAdmin = Null.NullBoolean; - CodeSubDirectory = Null.NullString; - PackageID = Null.NullInteger; - DesktopModuleID = Null.NullInteger; - SupportedFeatures = Null.NullInteger; - Shareable = ModuleSharing.Unknown; - } - - #region "Public Properties" - + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ID of the Desktop Module + /// Gets or sets and sets the ID of the Desktop Module. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int DesktopModuleID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ID of the Package for this Desktop Module + /// Gets or sets and sets the ID of the Package for this Desktop Module. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int PackageID { get; set; } /// - /// returns whether this has an associated Admin page + /// Gets or sets whether this has an associated Admin page. /// public string AdminPage { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the BusinessControllerClass of the Desktop Module + /// Gets or sets and sets the BusinessControllerClass of the Desktop Module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string BusinessControllerClass { get; set; } @@ -198,211 +186,216 @@ public string Category { get { - Term term = (from Term t in Terms select t).FirstOrDefault(); - return (term != null) ? term.Name : String.Empty; - } + Term term = (from Term t in this.Terms select t).FirstOrDefault(); + return (term != null) ? term.Name : string.Empty; + } + set { - Terms.Clear(); + this.Terms.Clear(); ITermController termController = Util.GetTermController(); - var term = (from Term t in termController.GetTermsByVocabulary("Module_Categories") - where t.Name == value + var term = (from Term t in termController.GetTermsByVocabulary("Module_Categories") + where t.Name == value select t) .FirstOrDefault(); if (term != null) { - Terms.Add(term); + this.Terms.Add(term); } } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the AppCode Folder Name of the Desktop Module + /// Gets or sets and sets the AppCode Folder Name of the Desktop Module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string CodeSubDirectory { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a Regular Expression that matches the versions of the core - /// that this module is compatible with + /// Gets or sets and sets a Regular Expression that matches the versions of the core + /// that this module is compatible with. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string CompatibleVersions { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a list of Dependencies for the module + /// Gets or sets and sets a list of Dependencies for the module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Dependencies { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Description of the Desktop Module + /// Gets or sets and sets the Description of the Desktop Module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Description { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Folder Name of the Desktop Module + /// Gets or sets and sets the Folder Name of the Desktop Module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string FolderName { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Friendly Name of the Desktop Module + /// Gets or sets the Friendly Name of the Desktop Module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string FriendlyName { get; set; } /// - /// returns whether this has an associated hostpage + /// Gets or sets whether this has an associated hostpage. /// public string HostPage { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Module is an Admin Module + /// Gets or sets a value indicating whether gets and sets whether the Module is an Admin Module. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool IsAdmin { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Module is Portable + /// Gets or sets a value indicating whether gets and sets whether the Module is Portable. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool IsPortable { get { - return GetFeature(DesktopModuleSupportedFeature.IsPortable); + return this.GetFeature(DesktopModuleSupportedFeature.IsPortable); } + set { - UpdateFeature(DesktopModuleSupportedFeature.IsPortable, value); + this.UpdateFeature(DesktopModuleSupportedFeature.IsPortable, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Module is a Premium Module + /// Gets or sets a value indicating whether gets and sets whether the Module is a Premium Module. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool IsPremium { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Module is Searchable + /// Gets or sets a value indicating whether gets and sets whether the Module is Searchable. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool IsSearchable { get { - return GetFeature(DesktopModuleSupportedFeature.IsSearchable); + return this.GetFeature(DesktopModuleSupportedFeature.IsSearchable); } + set { - UpdateFeature(DesktopModuleSupportedFeature.IsSearchable, value); + this.UpdateFeature(DesktopModuleSupportedFeature.IsSearchable, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Module is Upgradable + /// Gets or sets a value indicating whether gets and sets whether the Module is Upgradable. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool IsUpgradeable { get { - return GetFeature(DesktopModuleSupportedFeature.IsUpgradeable); + return this.GetFeature(DesktopModuleSupportedFeature.IsUpgradeable); } + set { - UpdateFeature(DesktopModuleSupportedFeature.IsUpgradeable, value); + this.UpdateFeature(DesktopModuleSupportedFeature.IsUpgradeable, value); } } /// - /// Is the module allowed to be shared across sites? + /// Gets or sets is the module allowed to be shared across sites?. /// public ModuleSharing Shareable { get; - set; + set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Module Definitions for this Desktop Module + /// Gets the Module Definitions for this Desktop Module. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public Dictionary ModuleDefinitions { get { - if (_moduleDefinitions == null) + if (this._moduleDefinitions == null) { - if (DesktopModuleID > Null.NullInteger) + if (this.DesktopModuleID > Null.NullInteger) { - _moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(DesktopModuleID); + this._moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(this.DesktopModuleID); } else { - _moduleDefinitions = new Dictionary(); + this._moduleDefinitions = new Dictionary(); } } - return _moduleDefinitions; + + return this._moduleDefinitions; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Name of the Desktop Module + /// Gets or sets and sets the Name of the Desktop Module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ModuleName { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a list of Permissions for the module + /// Gets or sets and sets a list of Permissions for the module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Permissions { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Supported Features of the Module + /// Gets or sets and sets the Supported Features of the Module. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int SupportedFeatures { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Version of the Desktop Module + /// Gets or sets and sets the Version of the Desktop Module. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Version { get; set; } @@ -410,9 +403,9 @@ public PageInfo Page { get { - if (_pageInfo == null && PackageID > Null.NullInteger) + if (this._pageInfo == null && this.PackageID > Null.NullInteger) { - var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == PackageID); + var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == this.PackageID); if (package != null && !string.IsNullOrEmpty(package.Manifest)) { var xmlDocument = new XmlDocument { XmlResolver = null }; @@ -420,61 +413,56 @@ public PageInfo Page var pageNode = xmlDocument.SelectSingleNode("//package//components//component[@type=\"Module\"]//page"); if (pageNode != null) { - _pageInfo = CBO.DeserializeObject(new StringReader(pageNode.OuterXml)); + this._pageInfo = CBO.DeserializeObject(new StringReader(pageNode.OuterXml)); } } } - return _pageInfo; + return this._pageInfo; } + set { - _pageInfo = value; + this._pageInfo = value; } - } - - #endregion - - #region IHydratable Members - - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- /// - /// Fills a DesktopModuleInfo from a Data Reader + /// Fills a DesktopModuleInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- public override void Fill(IDataReader dr) { - DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); - PackageID = Null.SetNullInteger(dr["PackageID"]); - ModuleName = Null.SetNullString(dr["ModuleName"]); - FriendlyName = Null.SetNullString(dr["FriendlyName"]); - Description = Null.SetNullString(dr["Description"]); - FolderName = Null.SetNullString(dr["FolderName"]); - Version = Null.SetNullString(dr["Version"]); - Description = Null.SetNullString(dr["Description"]); - IsPremium = Null.SetNullBoolean(dr["IsPremium"]); - IsAdmin = Null.SetNullBoolean(dr["IsAdmin"]); - BusinessControllerClass = Null.SetNullString(dr["BusinessControllerClass"]); - SupportedFeatures = Null.SetNullInteger(dr["SupportedFeatures"]); - CompatibleVersions = Null.SetNullString(dr["CompatibleVersions"]); - Dependencies = Null.SetNullString(dr["Dependencies"]); - Permissions = Null.SetNullString(dr["Permissions"]); - Shareable = (ModuleSharing)Null.SetNullInteger(dr["Shareable"]); - AdminPage = Null.SetNullString(dr["AdminPage"]); - HostPage = Null.SetNullString(dr["HostPage"]); - //Call the base classes fill method to populate base class proeprties - base.FillInternal(dr); - } - - #endregion - - #region IXmlSerializable Members - - /// ----------------------------------------------------------------------------- - /// - /// Gets an XmlSchema for the DesktopModule - /// + this.DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); + this.PackageID = Null.SetNullInteger(dr["PackageID"]); + this.ModuleName = Null.SetNullString(dr["ModuleName"]); + this.FriendlyName = Null.SetNullString(dr["FriendlyName"]); + this.Description = Null.SetNullString(dr["Description"]); + this.FolderName = Null.SetNullString(dr["FolderName"]); + this.Version = Null.SetNullString(dr["Version"]); + this.Description = Null.SetNullString(dr["Description"]); + this.IsPremium = Null.SetNullBoolean(dr["IsPremium"]); + this.IsAdmin = Null.SetNullBoolean(dr["IsAdmin"]); + this.BusinessControllerClass = Null.SetNullString(dr["BusinessControllerClass"]); + this.SupportedFeatures = Null.SetNullInteger(dr["SupportedFeatures"]); + this.CompatibleVersions = Null.SetNullString(dr["CompatibleVersions"]); + this.Dependencies = Null.SetNullString(dr["Dependencies"]); + this.Permissions = Null.SetNullString(dr["Permissions"]); + this.Shareable = (ModuleSharing)Null.SetNullInteger(dr["Shareable"]); + this.AdminPage = Null.SetNullString(dr["AdminPage"]); + this.HostPage = Null.SetNullString(dr["HostPage"]); + + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets an XmlSchema for the DesktopModule. + /// + /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() { @@ -483,9 +471,9 @@ public XmlSchema GetSchema() /// ----------------------------------------------------------------------------- /// - /// Reads a DesktopModuleInfo from an XmlReader + /// Reads a DesktopModuleInfo from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { @@ -495,25 +483,27 @@ public void ReadXml(XmlReader reader) { break; } + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } + if (reader.NodeType == XmlNodeType.Element && reader.Name == "moduleDefinitions" && !reader.IsEmptyElement) { - ReadModuleDefinitions(reader); + this.ReadModuleDefinitions(reader); } else if (reader.NodeType == XmlNodeType.Element && reader.Name == "supportedFeatures" && !reader.IsEmptyElement) { - ReadSupportedFeatures(reader); + this.ReadSupportedFeatures(reader); } else if (reader.NodeType == XmlNodeType.Element && reader.Name == "shareable" && !reader.IsEmptyElement) { - ReadModuleSharing(reader); + this.ReadModuleSharing(reader); } else if (reader.NodeType == XmlNodeType.Element && reader.Name == "page" && !reader.IsEmptyElement) { - ReadPageInfo(reader); + this.ReadPageInfo(reader); } else { @@ -522,108 +512,110 @@ public void ReadXml(XmlReader reader) case "desktopModule": break; case "moduleName": - ModuleName = reader.ReadElementContentAsString(); + this.ModuleName = reader.ReadElementContentAsString(); break; case "foldername": - FolderName = reader.ReadElementContentAsString(); + this.FolderName = reader.ReadElementContentAsString(); break; case "businessControllerClass": - BusinessControllerClass = reader.ReadElementContentAsString(); + this.BusinessControllerClass = reader.ReadElementContentAsString(); break; case "codeSubDirectory": - CodeSubDirectory = reader.ReadElementContentAsString(); + this.CodeSubDirectory = reader.ReadElementContentAsString(); break; case "page": - ReadPageInfo(reader); + this.ReadPageInfo(reader); - if (Page.HasAdminPage()) + if (this.Page.HasAdminPage()) { - AdminPage = Page.Name; + this.AdminPage = this.Page.Name; } - if (Page.HasHostPage()) + if (this.Page.HasHostPage()) { - HostPage = Page.Name; + this.HostPage = this.Page.Name; } + break; case "isAdmin": bool isAdmin; - Boolean.TryParse(reader.ReadElementContentAsString(), out isAdmin); - IsAdmin = isAdmin; + bool.TryParse(reader.ReadElementContentAsString(), out isAdmin); + this.IsAdmin = isAdmin; break; case "isPremium": bool isPremium; - Boolean.TryParse(reader.ReadElementContentAsString(), out isPremium); - IsPremium = isPremium; + bool.TryParse(reader.ReadElementContentAsString(), out isPremium); + this.IsPremium = isPremium; break; default: - if(reader.NodeType == XmlNodeType.Element && !String.IsNullOrEmpty(reader.Name)) + if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } + break; } } } } - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Writes a DesktopModuleInfo to an XmlWriter + /// Writes a DesktopModuleInfo to an XmlWriter. /// - /// The XmlWriter to use + /// The XmlWriter to use. /// ----------------------------------------------------------------------------- - public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("desktopModule"); - //write out properties - writer.WriteElementString("moduleName", ModuleName); - writer.WriteElementString("foldername", FolderName); - writer.WriteElementString("businessControllerClass", BusinessControllerClass); - if (!string.IsNullOrEmpty(CodeSubDirectory)) + // write out properties + writer.WriteElementString("moduleName", this.ModuleName); + writer.WriteElementString("foldername", this.FolderName); + writer.WriteElementString("businessControllerClass", this.BusinessControllerClass); + if (!string.IsNullOrEmpty(this.CodeSubDirectory)) { - writer.WriteElementString("codeSubDirectory", CodeSubDirectory); + writer.WriteElementString("codeSubDirectory", this.CodeSubDirectory); } - - //Write out Supported Features + + // Write out Supported Features writer.WriteStartElement("supportedFeatures"); - if (IsPortable) + if (this.IsPortable) { writer.WriteStartElement("supportedFeature"); writer.WriteAttributeString("type", "Portable"); writer.WriteEndElement(); } - if (IsSearchable) + + if (this.IsSearchable) { writer.WriteStartElement("supportedFeature"); writer.WriteAttributeString("type", "Searchable"); writer.WriteEndElement(); } - if (IsUpgradeable) + + if (this.IsUpgradeable) { writer.WriteStartElement("supportedFeature"); writer.WriteAttributeString("type", "Upgradeable"); writer.WriteEndElement(); } - //Write end of Supported Features + // Write end of Supported Features writer.WriteEndElement(); - //Write admin/host page info. - if (Page != null) + // Write admin/host page info. + if (this.Page != null) { - Page.WriteXml(writer); + this.Page.WriteXml(writer); } // Module sharing - - if(Shareable != ModuleSharing.Unknown) + if (this.Shareable != ModuleSharing.Unknown) { writer.WriteStartElement("shareable"); - switch (Shareable) + switch (this.Shareable) { case ModuleSharing.Supported: writer.WriteString("Supported"); @@ -632,90 +624,88 @@ public void WriteXml(XmlWriter writer) writer.WriteString("Unsupported"); break; } + writer.WriteEndElement(); } - //Write start of Module Definitions + // Write start of Module Definitions writer.WriteStartElement("moduleDefinitions"); - //Iterate through definitions - foreach (ModuleDefinitionInfo definition in ModuleDefinitions.Values) + // Iterate through definitions + foreach (ModuleDefinitionInfo definition in this.ModuleDefinitions.Values) { definition.WriteXml(writer); } - //Write end of Module Definitions + + // Write end of Module Definitions writer.WriteEndElement(); - //Write end of main element + // Write end of main element writer.WriteEndElement(); - } - - #endregion - - #region "Private Helper Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// Clears a Feature from the Features + /// Clears a Feature from the Features. /// - /// The feature to Clear + /// The feature to Clear. /// ----------------------------------------------------------------------------- private void ClearFeature(DesktopModuleSupportedFeature feature) { - //And with the 1's complement of Feature to Clear the Feature flag - SupportedFeatures = SupportedFeatures & ~((int) feature); + // And with the 1's complement of Feature to Clear the Feature flag + this.SupportedFeatures = this.SupportedFeatures & ~((int)feature); } /// ----------------------------------------------------------------------------- /// - /// Gets a Feature from the Features + /// Gets a Feature from the Features. /// - /// The feature to Get + /// The feature to Get. /// ----------------------------------------------------------------------------- private bool GetFeature(DesktopModuleSupportedFeature feature) { - return SupportedFeatures > Null.NullInteger && (SupportedFeatures & (int) feature) == (int) feature; + return this.SupportedFeatures > Null.NullInteger && (this.SupportedFeatures & (int)feature) == (int)feature; } /// ----------------------------------------------------------------------------- /// - /// Sets a Feature in the Features + /// Sets a Feature in the Features. /// - /// The feature to Set + /// The feature to Set. /// ----------------------------------------------------------------------------- private void SetFeature(DesktopModuleSupportedFeature feature) { - SupportedFeatures |= (int) feature; + this.SupportedFeatures |= (int)feature; } /// ----------------------------------------------------------------------------- /// - /// Updates a Feature in the Features + /// Updates a Feature in the Features. /// - /// The feature to Set - /// A Boolean indicating whether to set or clear the feature + /// The feature to Set. + /// A Boolean indicating whether to set or clear the feature. /// ----------------------------------------------------------------------------- private void UpdateFeature(DesktopModuleSupportedFeature feature, bool isSet) { if (isSet) { - SetFeature(feature); + this.SetFeature(feature); } else { - ClearFeature(feature); + this.ClearFeature(feature); } } /// ----------------------------------------------------------------------------- /// - /// Reads a Supported Features from an XmlReader + /// Reads a Supported Features from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- private void ReadSupportedFeatures(XmlReader reader) { - SupportedFeatures = 0; + this.SupportedFeatures = 0; reader.ReadStartElement("supportedFeatures"); do { @@ -725,17 +715,18 @@ private void ReadSupportedFeatures(XmlReader reader) switch (reader.ReadContentAsString()) { case "Portable": - IsPortable = true; + this.IsPortable = true; break; case "Searchable": - IsSearchable = true; + this.IsSearchable = true; break; case "Upgradeable": - IsUpgradeable = true; + this.IsUpgradeable = true; break; } } - } while (reader.ReadToNextSibling("supportedFeature")); + } + while (reader.ReadToNextSibling("supportedFeature")); } private void ReadModuleSharing(XmlReader reader) @@ -744,21 +735,21 @@ private void ReadModuleSharing(XmlReader reader) if (string.IsNullOrEmpty(sharing)) { - Shareable = ModuleSharing.Unknown; + this.Shareable = ModuleSharing.Unknown; } else { switch (sharing.ToLowerInvariant()) { case "supported": - Shareable = ModuleSharing.Supported; + this.Shareable = ModuleSharing.Supported; break; case "unsupported": - Shareable = ModuleSharing.Unsupported; + this.Shareable = ModuleSharing.Unsupported; break; default: case "unknown": - Shareable = ModuleSharing.Unknown; + this.Shareable = ModuleSharing.Unknown; break; } } @@ -766,9 +757,9 @@ private void ReadModuleSharing(XmlReader reader) /// ----------------------------------------------------------------------------- /// - /// Reads a Module Definitions from an XmlReader + /// Reads a Module Definitions from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- private void ReadModuleDefinitions(XmlReader reader) { @@ -777,34 +768,34 @@ private void ReadModuleDefinitions(XmlReader reader) { reader.ReadStartElement("moduleDefinition"); - //Create new ModuleDefinition object + // Create new ModuleDefinition object var moduleDefinition = new ModuleDefinitionInfo(); - //Load it from the Xml + // Load it from the Xml moduleDefinition.ReadXml(reader); - //Add to the collection - ModuleDefinitions.Add(moduleDefinition.FriendlyName, moduleDefinition); - } while (reader.ReadToNextSibling("moduleDefinition")); - } + // Add to the collection + this.ModuleDefinitions.Add(moduleDefinition.FriendlyName, moduleDefinition); + } + while (reader.ReadToNextSibling("moduleDefinition")); + } private void ReadPageInfo(XmlReader reader) { - Page = new PageInfo(); - //Load it from the Xml - Page.ReadXml(reader.ReadSubtree()); + this.Page = new PageInfo(); + + // Load it from the Xml + this.Page.ReadXml(reader.ReadSubtree()); - if (Page.HasAdminPage()) + if (this.Page.HasAdminPage()) { - AdminPage = Page.Name; + this.AdminPage = this.Page.Name; } - if (Page.HasHostPage()) + if (this.Page.HasHostPage()) { - HostPage = Page.Name; + this.HostPage = this.Page.Name; } - } - - #endregion - } + } + } } diff --git a/DNN Platform/Library/Entities/Modules/DesktopModuleSupportedFeature.cs b/DNN Platform/Library/Entities/Modules/DesktopModuleSupportedFeature.cs index dde561db6bf..208bcfed6d2 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleSupportedFeature.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleSupportedFeature.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { + using System; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : DesktopModuleSupportedFeature + /// Class : DesktopModuleSupportedFeature /// ----------------------------------------------------------------------------- /// /// The DesktopModuleSupportedFeature enum provides an enumeration of Supported - /// Features + /// Features. /// /// ----------------------------------------------------------------------------- [Flags] @@ -21,6 +21,6 @@ public enum DesktopModuleSupportedFeature { IsPortable = 1, IsSearchable = 2, - IsUpgradeable = 4 + IsUpgradeable = 4, } } diff --git a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs index 83d83bd735f..bdb3fbd5839 100644 --- a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs +++ b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs @@ -1,42 +1,93 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.EventQueue; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.EventQueue; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; + public class EventMessageProcessor : EventMessageProcessorBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (EventMessageProcessor)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(EventMessageProcessor)); + + public static void CreateImportModuleMessage(ModuleInfo objModule, string content, string version, int userID) + { + var appStartMessage = new EventMessage + { + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(-1), + SentDate = DateTime.Now, + Body = string.Empty, + ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", + ProcessorCommand = "ImportModule", + }; + + // Add custom Attributes for this message + appStartMessage.Attributes.Add("BusinessControllerClass", objModule.DesktopModule.BusinessControllerClass); + appStartMessage.Attributes.Add("ModuleId", objModule.ModuleID.ToString()); + appStartMessage.Attributes.Add("Content", content); + appStartMessage.Attributes.Add("Version", version); + appStartMessage.Attributes.Add("UserID", userID.ToString()); + + // send it to occur on next App_Start Event + EventQueueController.SendMessage(appStartMessage, "Application_Start_FirstRequest"); + } + + public override bool ProcessMessage(EventMessage message) + { + try + { + switch (message.ProcessorCommand) + { + case "UpdateSupportedFeatures": + UpdateSupportedFeatures(message); + break; + case "UpgradeModule": + UpgradeModule(message); + break; + case "ImportModule": + ImportModule(message); + break; + default: + // other events can be added here + break; + } + } + catch (Exception ex) + { + Logger.Error(ex); + message.ExceptionMessage = ex.Message; + return false; + } + + return true; + } + private static void ImportModule(EventMessage message) { try { string BusinessControllerClass = message.Attributes["BusinessControllerClass"]; - object controller = Reflection.CreateObject(BusinessControllerClass, ""); + object controller = Reflection.CreateObject(BusinessControllerClass, string.Empty); if (controller is IPortable) { int ModuleId = Convert.ToInt32(message.Attributes["ModuleId"]); string Content = HttpUtility.HtmlDecode(message.Attributes["Content"]); string Version = message.Attributes["Version"]; int UserID = Convert.ToInt32(message.Attributes["UserId"]); - //call the IPortable interface for the module/version - ((IPortable) controller).ImportModule(ModuleId, Content, Version, UserID); - //Synchronize Module Cache + + // call the IPortable interface for the module/version + ((IPortable)controller).ImportModule(ModuleId, Content, Version, UserID); + + // Synchronize Module Cache ModuleController.SynchronizeModule(ModuleId); } } @@ -54,26 +105,29 @@ private static void UpgradeModule(EventMessage message) var desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger); string BusinessControllerClass = message.Attributes["BusinessControllerClass"]; - object controller = Reflection.CreateObject(BusinessControllerClass, ""); + object controller = Reflection.CreateObject(BusinessControllerClass, string.Empty); if (controller is IUpgradeable) { - //get the list of applicable versions + // get the list of applicable versions string[] UpgradeVersions = message.Attributes["UpgradeVersionsList"].Split(','); foreach (string Version in UpgradeVersions) { - //call the IUpgradeable interface for the module/version - string Results = ((IUpgradeable) controller).UpgradeModule(Version); - //log the upgrade results - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.MODULE_UPDATED.ToString()}; + // call the IUpgradeable interface for the module/version + string Results = ((IUpgradeable)controller).UpgradeModule(Version); + + // log the upgrade results + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_UPDATED.ToString() }; log.AddProperty("Module Upgraded", BusinessControllerClass); log.AddProperty("Version", Version); if (!string.IsNullOrEmpty(Results)) { log.AddProperty("Results", Results); } + LogController.Instance.AddLog(log); } } + UpdateSupportedFeatures(controller, Convert.ToInt32(message.Attributes["DesktopModuleId"])); } catch (Exception exc) @@ -85,7 +139,7 @@ private static void UpgradeModule(EventMessage message) private static void UpdateSupportedFeatures(EventMessage message) { string BusinessControllerClass = message.Attributes["BusinessControllerClass"]; - object controller = Reflection.CreateObject(BusinessControllerClass, ""); + object controller = Reflection.CreateObject(BusinessControllerClass, string.Empty); UpdateSupportedFeatures(controller, Convert.ToInt32(message.Attributes["DesktopModuleId"])); } @@ -94,23 +148,23 @@ private static void UpdateSupportedFeatures(object objController, int desktopMod try { DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger); - if ((desktopModule != null)) + if (desktopModule != null) { - //Initialise the SupportedFeatures + // Initialise the SupportedFeatures desktopModule.SupportedFeatures = 0; - //Test the interfaces - desktopModule.IsPortable = (objController is IPortable); + // Test the interfaces + desktopModule.IsPortable = objController is IPortable; #pragma warning disable 0618 desktopModule.IsSearchable = (objController is ModuleSearchBase) || (objController is ISearchable); #pragma warning restore 0618 - desktopModule.IsUpgradeable = (objController is IUpgradeable); + desktopModule.IsUpgradeable = objController is IUpgradeable; DesktopModuleController.SaveDesktopModule(desktopModule, false, false, false); foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - DataCache.RemoveCache(String.Format(DataCache.DesktopModuleCacheKey, portal.PortalID)); - DataCache.RemoveCache(String.Format(DataCache.PortalDesktopModuleCacheKey, portal.PortalID)); + DataCache.RemoveCache(string.Format(DataCache.DesktopModuleCacheKey, portal.PortalID)); + DataCache.RemoveCache(string.Format(DataCache.PortalDesktopModuleCacheKey, portal.PortalID)); } } } @@ -119,57 +173,5 @@ private static void UpdateSupportedFeatures(object objController, int desktopMod Exceptions.LogException(exc); } } - - public static void CreateImportModuleMessage(ModuleInfo objModule, string content, string version, int userID) - { - var appStartMessage = new EventMessage - { - Priority = MessagePriority.High, - ExpirationDate = DateTime.Now.AddYears(-1), - SentDate = DateTime.Now, - Body = "", - ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", - ProcessorCommand = "ImportModule" - }; - - //Add custom Attributes for this message - appStartMessage.Attributes.Add("BusinessControllerClass", objModule.DesktopModule.BusinessControllerClass); - appStartMessage.Attributes.Add("ModuleId", objModule.ModuleID.ToString()); - appStartMessage.Attributes.Add("Content", content); - appStartMessage.Attributes.Add("Version", version); - appStartMessage.Attributes.Add("UserID", userID.ToString()); - - //send it to occur on next App_Start Event - EventQueueController.SendMessage(appStartMessage, "Application_Start_FirstRequest"); - } - - public override bool ProcessMessage(EventMessage message) - { - try - { - switch (message.ProcessorCommand) - { - case "UpdateSupportedFeatures": - UpdateSupportedFeatures(message); - break; - case "UpgradeModule": - UpgradeModule(message); - break; - case "ImportModule": - ImportModule(message); - break; - default: - //other events can be added here - break; - } - } - catch (Exception ex) - { - Logger.Error(ex); - message.ExceptionMessage = ex.Message; - return false; - } - return true; - } } } diff --git a/DNN Platform/Library/Entities/Modules/IActionable.cs b/DNN Platform/Library/Entities/Modules/IActionable.cs index 4d4583dc160..985eb179d7e 100644 --- a/DNN Platform/Library/Entities/Modules/IActionable.cs +++ b/DNN Platform/Library/Entities/Modules/IActionable.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules.Actions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using DotNetNuke.Entities.Modules.Actions; + public interface IActionable { ModuleActionCollection ModuleActions { get; } diff --git a/DNN Platform/Library/Entities/Modules/ICustomTokenProvider.cs b/DNN Platform/Library/Entities/Modules/ICustomTokenProvider.cs index 6ba9be9b9a7..f20f34c72cc 100644 --- a/DNN Platform/Library/Entities/Modules/ICustomTokenProvider.cs +++ b/DNN Platform/Library/Entities/Modules/ICustomTokenProvider.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; -using System.Collections.Generic; -using DotNetNuke.UI.Modules; -using DotNetNuke.Services.Tokens; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { + using System.Collections.Generic; + using System.Web.UI; + + using DotNetNuke.Services.Tokens; + using DotNetNuke.UI.Modules; + public interface ICustomTokenProvider { IDictionary GetTokens(Page page, ModuleInstanceContext moduleContext); diff --git a/DNN Platform/Library/Entities/Modules/IHydratable.cs b/DNN Platform/Library/Entities/Modules/IHydratable.cs index 27c482531f9..aea9ede1df8 100644 --- a/DNN Platform/Library/Entities/Modules/IHydratable.cs +++ b/DNN Platform/Library/Entities/Modules/IHydratable.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System.Data; + public interface IHydratable { int KeyID { get; set; } diff --git a/DNN Platform/Library/Entities/Modules/IModuleController.cs b/DNN Platform/Library/Entities/Modules/IModuleController.cs index 08816f19706..d87cc2871a1 100644 --- a/DNN Platform/Library/Entities/Modules/IModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/IModuleController.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -18,14 +19,14 @@ namespace DotNetNuke.Entities.Modules public interface IModuleController { /// - /// add a module to a page + /// add a module to a page. /// - /// moduleInfo for the module to create - /// ID of the created module + /// moduleInfo for the module to create. + /// ID of the created module. int AddModule(ModuleInfo module); /// - /// Clears the module cache based on the page (tabid) + /// Clears the module cache based on the page (tabid). /// /// The tab id. void ClearCache(int TabId); @@ -59,76 +60,76 @@ public interface IModuleController /// /// This method provides two functions: /// 1. Check and ensure that the "Module" content item type exists - if not create it - /// 2. add a content item + /// 2. add a content item. /// - /// the module to add a content item for + /// the module to add a content item for. void CreateContentItem(ModuleInfo module); /// /// DeleteAllModules deletes all instances of a Module (from a collection). This overload - /// soft deletes the instances + /// soft deletes the instances. /// - /// The Id of the module to copy - /// The Id of the current tab - /// An ArrayList of TabItem objects + /// The Id of the module to copy. + /// The Id of the current tab. + /// An ArrayList of TabItem objects. void DeleteAllModules(int moduleId, int tabId, List fromTabs, bool softDelete, bool includeCurrent, bool deleteBaseModule); /// - /// Delete a module instance permanently from the database + /// Delete a module instance permanently from the database. /// - /// ID of the module instance + /// ID of the module instance. void DeleteModule(int moduleId); /// - /// Delete a Setting of a module instance + /// Delete a Setting of a module instance. /// - /// ID of the affected module - /// Name of the setting to be deleted + /// ID of the affected module. + /// Name of the setting to be deleted. void DeleteModuleSetting(int moduleId, string settingName); /// /// Delete a module reference permanently from the database. - /// if there are no other references, the module instance is deleted as well + /// if there are no other references, the module instance is deleted as well. /// - /// ID of the page - /// ID of the module instance - /// A flag that determines whether the instance should be soft-deleted + /// ID of the page. + /// ID of the module instance. + /// A flag that determines whether the instance should be soft-deleted. void DeleteTabModule(int tabId, int moduleId, bool softDelete); /// - /// Delete a specific setting of a tabmodule reference + /// Delete a specific setting of a tabmodule reference. /// - /// ID of the affected tabmodule - /// Name of the setting to remove + /// ID of the affected tabmodule. + /// Name of the setting to remove. void DeleteTabModuleSetting(int tabModuleId, string settingName); /// /// Des the localize module. /// /// The source module. - /// new module id + /// new module id. int DeLocalizeModule(ModuleInfo sourceModule); /// - /// get info of all modules in any portal of the installation + /// get info of all modules in any portal of the installation. /// - /// moduleInfo of all modules - /// created for upgrade purposes + /// moduleInfo of all modules. + /// created for upgrade purposes. ArrayList GetAllModules(); /// - /// get Module objects of a portal, either only those, to be placed on all tabs or not + /// get Module objects of a portal, either only those, to be placed on all tabs or not. /// - /// ID of the portal - /// specify, whether to return modules to be shown on all tabs or those to be shown on specified tabs - /// ArrayList of TabModuleInfo objects + /// ID of the portal. + /// specify, whether to return modules to be shown on all tabs or those to be shown on specified tabs. + /// ArrayList of TabModuleInfo objects. ArrayList GetAllTabsModules(int portalID, bool allTabs); /// - /// get TabModule objects that are linked to a particular ModuleID + /// get TabModule objects that are linked to a particular ModuleID. /// - /// ID of the module - /// ArrayList of TabModuleInfo objects + /// ID of the module. + /// ArrayList of TabModuleInfo objects. ArrayList GetAllTabsModulesByModuleID(int moduleID); /// @@ -136,31 +137,31 @@ public interface IModuleController /// /// The module ID. /// The tab ID. - /// Optionally bypass the cache - /// module info + /// Optionally bypass the cache. + /// module info. ModuleInfo GetModule(int moduleId, int tabId, bool ignoreCache); /// - /// get Module by specific locale + /// get Module by specific locale. /// - /// ID of the module - /// ID of the tab - /// ID of the portal - /// The wanted locale - /// ModuleInfo associated to submitted locale + /// ID of the module. + /// ID of the tab. + /// ID of the portal. + /// The wanted locale. + /// ModuleInfo associated to submitted locale. ModuleInfo GetModuleByCulture(int ModuleId, int tabid, int portalId, Locale locale); /// - /// Get ModuleInfo object of first module instance with a given name of the module definition + /// Get ModuleInfo object of first module instance with a given name of the module definition. /// - /// ID of the portal, where to look for the module - /// The name of module definition (NOTE: this looks at , not ) - /// ModuleInfo of first module instance - /// preferably used for admin and host modules + /// ID of the portal, where to look for the module. + /// The name of module definition (NOTE: this looks at , not ). + /// ModuleInfo of first module instance. + /// preferably used for admin and host modules. ModuleInfo GetModuleByDefinition(int portalId, string definitionName); /// - /// get a Module object + /// get a Module object. /// /// /// @@ -169,10 +170,10 @@ public interface IModuleController ModuleInfo GetModuleByUniqueID(Guid uniqueID); /// - /// get all Module objects of a portal + /// get all Module objects of a portal. /// - /// ID of the portal - /// ArrayList of ModuleInfo objects + /// ID of the portal. + /// ArrayList of ModuleInfo objects. ArrayList GetModules(int portalID); /// @@ -180,57 +181,57 @@ public interface IModuleController /// /// The portal ID. /// The name of the module definition. - /// module collection + /// module collection. ArrayList GetModulesByDefinition(int portalID, string definitionName); /// /// Gets the modules by DesktopModuleId. /// /// The Desktop Module Id. - /// module collection + /// module collection. ArrayList GetModulesByDesktopModuleId(int desktopModuleId); /// /// For a portal get a list of all active module and tabmodule references that are Searchable /// either by inheriting from ModuleSearchBase or implementing the older ISearchable interface. /// - /// ID of the portal to be searched + /// ID of the portal to be searched. /// Arraylist of ModuleInfo for modules supporting search. ArrayList GetSearchModules(int portalID); /// - /// get a Module object + /// get a Module object. /// - /// ID of the tabmodule - /// An ModuleInfo object + /// ID of the tabmodule. + /// An ModuleInfo object. ModuleInfo GetTabModule(int tabModuleID); /// - /// Get all Module references on a tab + /// Get all Module references on a tab. /// /// - /// Dictionary of ModuleID and ModuleInfo + /// Dictionary of ModuleID and ModuleInfo. Dictionary GetTabModules(int tabId); /// - /// Get a list of all TabModule references of a module instance + /// Get a list of all TabModule references of a module instance. /// - /// ID of the Module - /// ArrayList of ModuleInfo + /// ID of the Module. + /// ArrayList of ModuleInfo. IList GetTabModulesByModule(int moduleID); - + void InitialModulePermission(ModuleInfo module, int tabId, int permissionType); void LocalizeModule(ModuleInfo sourceModule, Locale locale); /// /// MoveModule moes a Module from one Tab to another including all the - /// TabModule settings + /// TabModule settings. /// - /// The Id of the module to move - /// The Id of the source tab - /// The Id of the destination tab - /// The name of the Pane on the destination tab where the module will end up + /// The Id of the module to move. + /// The Id of the source tab. + /// The Id of the destination tab. + /// The name of the Pane on the destination tab where the module will end up. void MoveModule(int moduleId, int fromTabId, int toTabId, string toPaneName); /// @@ -240,42 +241,42 @@ public interface IModuleController void RestoreModule(ModuleInfo objModule); /// - /// Update module settings and permissions in database from ModuleInfo + /// Update module settings and permissions in database from ModuleInfo. /// - /// ModuleInfo of the module to update + /// ModuleInfo of the module to update. void UpdateModule(ModuleInfo module); /// - /// set/change the module position within a pane on a page + /// set/change the module position within a pane on a page. /// - /// ID of the page - /// ID of the module on the page - /// position within the controls list on page, -1 if to be added at the end - /// name of the pane, the module is placed in on the page + /// ID of the page. + /// ID of the module on the page. + /// position within the controls list on page, -1 if to be added at the end. + /// name of the pane, the module is placed in on the page. void UpdateModuleOrder(int TabId, int ModuleId, int ModuleOrder, string PaneName); /// - /// Adds or updates a module's setting value + /// Adds or updates a module's setting value. /// - /// ID of the tabmodule, the setting belongs to - /// name of the setting property + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. /// value of the setting (String). - /// Empty SettingValue will remove the setting + /// Empty SettingValue will remove the setting. void UpdateModuleSetting(int moduleId, string settingName, string settingValue); /// - /// set/change all module's positions within a page + /// set/change all module's positions within a page. /// - /// ID of the page + /// ID of the page. void UpdateTabModuleOrder(int TabId); /// - /// Adds or updates a tab module's setting value + /// Adds or updates a tab module's setting value. /// - /// ID of the tabmodule, the setting belongs to - /// name of the setting property + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. /// value of the setting (String). - /// Empty SettingValue will remove the setting + /// Empty SettingValue will remove the setting. void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue); /// @@ -286,17 +287,17 @@ public interface IModuleController void UpdateTranslationStatus(ModuleInfo localizedModule, bool isTranslated); /// - /// Check if a ModuleInfo belongs to the referenced Tab or not + /// Check if a ModuleInfo belongs to the referenced Tab or not. /// - /// A ModuleInfo object to be checked - /// True is TabId points to a different tab from initial Tab where the module was added. Otherwise, False + /// A ModuleInfo object to be checked. + /// True is TabId points to a different tab from initial Tab where the module was added. Otherwise, False. bool IsSharedModule(ModuleInfo module); - + /// - /// Get the Tab ID corresponding to the initial Tab where the module was added + /// Get the Tab ID corresponding to the initial Tab where the module was added. /// - /// A ModuleInfo object to be checked - /// The Tab Id from initial Tab where the module was added + /// A ModuleInfo object to be checked. + /// The Tab Id from initial Tab where the module was added. int GetMasterTabId(ModuleInfo module); } } diff --git a/DNN Platform/Library/Entities/Modules/IPortable.cs b/DNN Platform/Library/Entities/Modules/IPortable.cs index a130a57aaa8..bb622e03876 100644 --- a/DNN Platform/Library/Entities/Modules/IPortable.cs +++ b/DNN Platform/Library/Entities/Modules/IPortable.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { - /// A contract specifying the ability to import and export the content of a module + /// A contract specifying the ability to import and export the content of a module. public interface IPortable { - /// Exports the content of this module - /// The ID of the module to export - /// The module's content serialized as a + /// Exports the content of this module. + /// The ID of the module to export. + /// The module's content serialized as a . string ExportModule(int ModuleID); - /// Imports the content of a module - /// The ID of the module into which the content is being imported - /// The content to import - /// The version of the module from which the content is coming - /// The ID of the user performing the import + /// Imports the content of a module. + /// The ID of the module into which the content is being imported. + /// The content to import. + /// The version of the module from which the content is coming. + /// The ID of the user performing the import. void ImportModule(int ModuleID, string Content, string Version, int UserID); } } diff --git a/DNN Platform/Library/Entities/Modules/ISearchable.cs b/DNN Platform/Library/Entities/Modules/ISearchable.cs index 8816b1bf9e7..9b7f27f7347 100644 --- a/DNN Platform/Library/Entities/Modules/ISearchable.cs +++ b/DNN Platform/Library/Entities/Modules/ISearchable.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { - [Obsolete("Deprecated in DNN 7.1. Replaced by ModuleSearchBase. Scheduled removal in v10.0.0.")] + using System; + + using DotNetNuke.Services.Search; + + [Obsolete("Deprecated in DNN 7.1. Replaced by ModuleSearchBase. Scheduled removal in v10.0.0.")] public interface ISearchable { [Obsolete("Deprecated in DNN 7.1. Replaced by ModuleSearchBase.GetModifiedSearchDocuments. Scheduled removal in v10.0.0.")] diff --git a/DNN Platform/Library/Entities/Modules/IShareable.cs b/DNN Platform/Library/Entities/Modules/IShareable.cs index 1440b386665..4bd15d3bacd 100644 --- a/DNN Platform/Library/Entities/Modules/IShareable.cs +++ b/DNN Platform/Library/Entities/Modules/IShareable.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { public interface IShareable { - /// Does this module support Module Sharing (i.e., sharing modules between sites within a SiteGroup)? + /// Gets or sets does this module support Module Sharing (i.e., sharing modules between sites within a SiteGroup)?. ModuleSharing SharingSupport { get; set; } } } diff --git a/DNN Platform/Library/Entities/Modules/IUpgradeable.cs b/DNN Platform/Library/Entities/Modules/IUpgradeable.cs index 8b6da616e28..4ebc738c679 100644 --- a/DNN Platform/Library/Entities/Modules/IUpgradeable.cs +++ b/DNN Platform/Library/Entities/Modules/IUpgradeable.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { public interface IUpgradeable diff --git a/DNN Platform/Library/Entities/Modules/IVersionable.cs b/DNN Platform/Library/Entities/Modules/IVersionable.cs index e69757133c8..41e0e46f6ce 100644 --- a/DNN Platform/Library/Entities/Modules/IVersionable.cs +++ b/DNN Platform/Library/Entities/Modules/IVersionable.cs @@ -1,49 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { /// - /// This interface allow the page to interact with his modules to delete/rollback or publish a specific version. + /// This interface allow the page to interact with his modules to delete/rollback or publish a specific version. /// The module that wants support page versioning need to implement it in the Bussiness controller. /// public interface IVersionable { /// - /// This method deletes a concrete version of the module + /// This method deletes a concrete version of the module. /// - /// ModuleId - /// Version number + /// ModuleId. + /// Version number. void DeleteVersion(int moduleId, int version); /// - /// This method performs a rollback of a concrete version of the module + /// This method performs a rollback of a concrete version of the module. /// - /// Module Id - /// Version number that need to be rollback - /// New version number created after the rollback process + /// Module Id. + /// Version number that need to be rollback. + /// New version number created after the rollback process. int RollBackVersion(int moduleId, int version); /// - /// This method publishes a version of the module + /// This method publishes a version of the module. /// - /// Module Id - /// Version number + /// Module Id. + /// Version number. void PublishVersion(int moduleId, int version); /// - /// This method returns the version number of the current published module version + /// This method returns the version number of the current published module version. /// - /// Module Id - /// Version number of the current published content version + /// Module Id. + /// Version number of the current published content version. int GetPublishedVersion(int moduleId); /// - /// This method returns the latest version number of the current module + /// This method returns the latest version number of the current module. /// - /// Module Id - /// Version number of the current published content version + /// Module Id. + /// Version number of the current published content version. int GetLatestVersion(int moduleId); } } diff --git a/DNN Platform/Library/Entities/Modules/IVersionableControl.cs b/DNN Platform/Library/Entities/Modules/IVersionableControl.cs index d7faaa21c33..46cd25e6ec8 100644 --- a/DNN Platform/Library/Entities/Modules/IVersionableControl.cs +++ b/DNN Platform/Library/Entities/Modules/IVersionableControl.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { /// /// This interface is implemented by module control to let the page tell to the control what - /// content version it should be render + /// content version it should be render. /// public interface IVersionableControl { /// - /// Indicate to the module control what content version need to be shown on rendering + /// Indicate to the module control what content version need to be shown on rendering. /// - /// Version number + /// Version number. void SetModuleVersion(int version); } } diff --git a/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs b/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs index dbaedec8e50..73d77ab475e 100644 --- a/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System.Xml; + public class InstalledModuleInfo { public int DesktopModuleId { get; set; } @@ -24,15 +19,15 @@ public class InstalledModuleInfo public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("module"); - writer.WriteElementString("moduleName", ModuleName); - writer.WriteElementString("friendlyName", FriendlyName); - writer.WriteElementString("version", Version); - writer.WriteElementString("instances", Instances.ToString()); + writer.WriteElementString("moduleName", this.ModuleName); + writer.WriteElementString("friendlyName", this.FriendlyName); + writer.WriteElementString("version", this.Version); + writer.WriteElementString("instances", this.Instances.ToString()); - //Write end of Host Info + // Write end of Host Info writer.WriteEndElement(); } } diff --git a/DNN Platform/Library/Entities/Modules/InstalledModulesController.cs b/DNN Platform/Library/Entities/Modules/InstalledModulesController.cs index 99c3e1ed201..aa57389e84b 100644 --- a/DNN Platform/Library/Entities/Modules/InstalledModulesController.cs +++ b/DNN Platform/Library/Entities/Modules/InstalledModulesController.cs @@ -1,17 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + public class InstalledModulesController { public static List GetInstalledModules() diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs index e4ec0a70060..105d66e4ed5 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : ModuleControlController + /// Class : ModuleControlController /// ----------------------------------------------------------------------------- /// - /// ModuleControlController provides the Business Layer for Module Controls + /// ModuleControlController provides the Business Layer for Module Controls. /// /// ----------------------------------------------------------------------------- public class ModuleControlController @@ -34,62 +29,65 @@ public class ModuleControlController /// ----------------------------------------------------------------------------- /// - /// GetModuleControls gets a Dictionary of Module Controls from - /// the Cache. + /// AddModuleControl adds a new Module Control to the database. /// + /// The Module Control to save. /// ----------------------------------------------------------------------------- - private static Dictionary GetModuleControls() + public static void AddModuleControl(ModuleControlInfo objModuleControl) { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.ModuleControlsCacheKey, - DataCache.ModuleControlsCacheTimeOut, - DataCache.ModuleControlsCachePriority), - GetModuleControlsCallBack); + SaveModuleControl(objModuleControl, true); } /// ----------------------------------------------------------------------------- /// - /// GetModuleControlsCallBack gets a Dictionary of Module Controls from - /// the Database. + /// DeleteModuleControl deletes a Module Control in the database. /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call + /// The ID of the Module Control to delete. /// ----------------------------------------------------------------------------- - private static object GetModuleControlsCallBack(CacheItemArgs cacheItemArgs) + public static void DeleteModuleControl(int moduleControlID) { - return CBO.FillDictionary(key, dataProvider.GetModuleControls(), new Dictionary()); + dataProvider.DeleteModuleControl(moduleControlID); + DataCache.ClearHostCache(true); } /// ----------------------------------------------------------------------------- /// - /// AddModuleControl adds a new Module Control to the database + /// GetModuleControls gets a Dictionary of Module Controls from + /// the Cache. /// - /// The Module Control to save /// ----------------------------------------------------------------------------- - public static void AddModuleControl(ModuleControlInfo objModuleControl) + private static Dictionary GetModuleControls() { - SaveModuleControl(objModuleControl, true); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.ModuleControlsCacheKey, + DataCache.ModuleControlsCacheTimeOut, + DataCache.ModuleControlsCachePriority), + GetModuleControlsCallBack); } /// ----------------------------------------------------------------------------- /// - /// DeleteModuleControl deletes a Module Control in the database + /// GetModuleControlsCallBack gets a Dictionary of Module Controls from + /// the Database. /// - /// The ID of the Module Control to delete + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. /// ----------------------------------------------------------------------------- - public static void DeleteModuleControl(int moduleControlID) + private static object GetModuleControlsCallBack(CacheItemArgs cacheItemArgs) { - dataProvider.DeleteModuleControl(moduleControlID); - DataCache.ClearHostCache(true); + return CBO.FillDictionary(key, dataProvider.GetModuleControls(), new Dictionary()); } /// ----------------------------------------------------------------------------- /// - /// GetModuleControl gets a single Module Control from the database + /// GetModuleControl gets a single Module Control from the database. /// - /// The ID of the Module Control to fetch + /// The ID of the Module Control to fetch. + /// /// ----------------------------------------------------------------------------- public static ModuleControlInfo GetModuleControl(int moduleControlID) - { + { return (from kvp in GetModuleControls() where kvp.Key == moduleControlID select kvp.Value) @@ -98,9 +96,10 @@ public static ModuleControlInfo GetModuleControl(int moduleControlID) /// ----------------------------------------------------------------------------- /// - /// GetModuleControl gets a Dictionary of Module Controls by Module Definition + /// GetModuleControl gets a Dictionary of Module Controls by Module Definition. /// - /// The ID of the Module Definition + /// The ID of the Module Definition. + /// /// ----------------------------------------------------------------------------- public static Dictionary GetModuleControlsByModuleDefinitionID(int moduleDefID) { @@ -110,10 +109,11 @@ public static Dictionary GetModuleControlsByModuleDef /// ----------------------------------------------------------------------------- /// - /// GetModuleControlByControlKey gets a single Module Control from the database + /// GetModuleControlByControlKey gets a single Module Control from the database. /// - /// The key for the control - /// The ID of the Module Definition + /// The key for the control. + /// The ID of the Module Definition. + /// /// ----------------------------------------------------------------------------- public static ModuleControlInfo GetModuleControlByControlKey(string controlKey, int moduleDefID) { @@ -126,57 +126,62 @@ where kvp.Value.ControlKey.Equals(controlKey, StringComparison.InvariantCultureI /// ----------------------------------------------------------------------------- /// - /// SaveModuleControl updates a Module Control in the database + /// SaveModuleControl updates a Module Control in the database. /// - /// The Module Control to save - /// A flag that determines whether to clear the host cache + /// The Module Control to save. + /// A flag that determines whether to clear the host cache. + /// /// ----------------------------------------------------------------------------- public static int SaveModuleControl(ModuleControlInfo moduleControl, bool clearCache) { int moduleControlID = moduleControl.ModuleControlID; if (moduleControlID == Null.NullInteger) { - //Add new Module Definition - moduleControlID = dataProvider.AddModuleControl(moduleControl.ModuleDefID, - moduleControl.ControlKey, - moduleControl.ControlTitle, - moduleControl.ControlSrc, - moduleControl.IconFile, - Convert.ToInt32(moduleControl.ControlType), - moduleControl.ViewOrder, - moduleControl.HelpURL, - moduleControl.SupportsPartialRendering, - moduleControl.SupportsPopUps, - UserController.Instance.GetCurrentUserInfo().UserID); + // Add new Module Definition + moduleControlID = dataProvider.AddModuleControl( + moduleControl.ModuleDefID, + moduleControl.ControlKey, + moduleControl.ControlTitle, + moduleControl.ControlSrc, + moduleControl.IconFile, + Convert.ToInt32(moduleControl.ControlType), + moduleControl.ViewOrder, + moduleControl.HelpURL, + moduleControl.SupportsPartialRendering, + moduleControl.SupportsPopUps, + UserController.Instance.GetCurrentUserInfo().UserID); } else { - //Upgrade Module Control - dataProvider.UpdateModuleControl(moduleControl.ModuleControlID, - moduleControl.ModuleDefID, - moduleControl.ControlKey, - moduleControl.ControlTitle, - moduleControl.ControlSrc, - moduleControl.IconFile, - Convert.ToInt32(moduleControl.ControlType), - moduleControl.ViewOrder, - moduleControl.HelpURL, - moduleControl.SupportsPartialRendering, - moduleControl.SupportsPopUps, - UserController.Instance.GetCurrentUserInfo().UserID); + // Upgrade Module Control + dataProvider.UpdateModuleControl( + moduleControl.ModuleControlID, + moduleControl.ModuleDefID, + moduleControl.ControlKey, + moduleControl.ControlTitle, + moduleControl.ControlSrc, + moduleControl.IconFile, + Convert.ToInt32(moduleControl.ControlType), + moduleControl.ViewOrder, + moduleControl.HelpURL, + moduleControl.SupportsPartialRendering, + moduleControl.SupportsPopUps, + UserController.Instance.GetCurrentUserInfo().UserID); } + if (clearCache) { DataCache.ClearHostCache(true); } + return moduleControlID; } /// ----------------------------------------------------------------------------- /// - /// UpdateModuleControl updates a Module Control in the database + /// UpdateModuleControl updates a Module Control in the database. /// - /// The Module Control to save + /// The Module Control to save. /// ----------------------------------------------------------------------------- public static void UpdateModuleControl(ModuleControlInfo objModuleControl) { diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs index e7b23ebf148..deb8d88bb88 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs @@ -1,155 +1,147 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { - /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Namespace: DotNetNuke.Entities.Modules - /// Class : ModuleControlInfo - /// ----------------------------------------------------------------------------- - /// - /// ModuleControlInfo provides the Entity Layer for Module Controls - /// - /// ----------------------------------------------------------------------------- + using System; + using System.Data; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security; + + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke + /// Namespace: DotNetNuke.Entities.Modules + /// Class : ModuleControlInfo + /// ----------------------------------------------------------------------------- + /// + /// ModuleControlInfo provides the Entity Layer for Module Controls. + /// + /// ----------------------------------------------------------------------------- [Serializable] public class ModuleControlInfo : ControlInfo, IXmlSerializable, IHydratable { public ModuleControlInfo() { - ModuleControlID = Null.NullInteger; - ModuleDefID = Null.NullInteger; - ControlType = SecurityAccessLevel.Anonymous; - SupportsPopUps = false; + this.ModuleControlID = Null.NullInteger; + this.ModuleDefID = Null.NullInteger; + this.ControlType = SecurityAccessLevel.Anonymous; + this.SupportsPopUps = false; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Control Title + /// Gets or sets and sets the Control Title. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlTitle { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Control Type + /// Gets or sets and sets the Control Type. /// - /// A SecurityAccessLevel + /// A SecurityAccessLevel. /// ----------------------------------------------------------------------------- public SecurityAccessLevel ControlType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Help URL + /// Gets or sets and sets the Help URL. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string HelpURL { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Icon Source + /// Gets or sets and sets the Icon Source. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconFile { get; set; } - - /// ----------------------------------------------------------------------------- + + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Module Control ID + /// Gets or sets and sets the Module Control ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int ModuleControlID { get; set; } - - /// ----------------------------------------------------------------------------- + + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Module Definition ID + /// Gets or sets and sets the Module Definition ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int ModuleDefID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether to support popup. + /// Gets or sets a value indicating whether gets and sets whether to support popup. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- public bool SupportsPopUps { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the View Order + /// Gets or sets and sets the View Order. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- - public int ViewOrder { get; set; } - - #region IHydratable Members + public int ViewOrder { get; set; } /// ----------------------------------------------------------------------------- /// - /// Fills a ModuleControlInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - ModuleControlID = Null.SetNullInteger(dr["ModuleControlID"]); - FillInternal(dr); - ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); - ControlTitle = Null.SetNullString(dr["ControlTitle"]); - IconFile = Null.SetNullString(dr["IconFile"]); - HelpURL = Null.SetNullString(dr["HelpUrl"]); - ControlType = (SecurityAccessLevel) Enum.Parse(typeof (SecurityAccessLevel), Null.SetNullString(dr["ControlType"])); - ViewOrder = Null.SetNullInteger(dr["ViewOrder"]); - SupportsPopUps = Null.SetNullBoolean(dr["SupportsPopUps"]); - //Call the base classes fill method to populate base class proeprties - base.FillInternal(dr); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int KeyID { get { - return ModuleControlID; + return this.ModuleControlID; } + set { - ModuleControlID = value; + this.ModuleControlID = value; } - } - - #endregion - - #region IXmlSerializable Members - + } + /// ----------------------------------------------------------------------------- /// - /// Gets an XmlSchema for the ModuleControlInfo + /// Fills a ModuleControlInfo from a Data Reader. /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.ModuleControlID = Null.SetNullInteger(dr["ModuleControlID"]); + this.FillInternal(dr); + this.ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); + this.ControlTitle = Null.SetNullString(dr["ControlTitle"]); + this.IconFile = Null.SetNullString(dr["IconFile"]); + this.HelpURL = Null.SetNullString(dr["HelpUrl"]); + this.ControlType = (SecurityAccessLevel)Enum.Parse(typeof(SecurityAccessLevel), Null.SetNullString(dr["ControlType"])); + this.ViewOrder = Null.SetNullInteger(dr["ViewOrder"]); + this.SupportsPopUps = Null.SetNullBoolean(dr["SupportsPopUps"]); + + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets an XmlSchema for the ModuleControlInfo. + /// + /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() { @@ -158,9 +150,9 @@ public XmlSchema GetSchema() /// ----------------------------------------------------------------------------- /// - /// Reads a ModuleControlInfo from an XmlReader + /// Reads a ModuleControlInfo from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { @@ -170,40 +162,44 @@ public void ReadXml(XmlReader reader) { break; } + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - ReadXmlInternal(reader); + + this.ReadXmlInternal(reader); switch (reader.Name) { case "controlTitle": - ControlTitle = reader.ReadElementContentAsString(); + this.ControlTitle = reader.ReadElementContentAsString(); break; case "controlType": - ControlType = (SecurityAccessLevel) Enum.Parse(typeof (SecurityAccessLevel), reader.ReadElementContentAsString()); + this.ControlType = (SecurityAccessLevel)Enum.Parse(typeof(SecurityAccessLevel), reader.ReadElementContentAsString()); break; case "iconFile": - IconFile = reader.ReadElementContentAsString(); + this.IconFile = reader.ReadElementContentAsString(); break; case "helpUrl": - HelpURL = reader.ReadElementContentAsString(); + this.HelpURL = reader.ReadElementContentAsString(); break; case "supportsPopUps": - SupportsPopUps = Boolean.Parse(reader.ReadElementContentAsString()); + this.SupportsPopUps = bool.Parse(reader.ReadElementContentAsString()); break; case "viewOrder": string elementvalue = reader.ReadElementContentAsString(); if (!string.IsNullOrEmpty(elementvalue)) { - ViewOrder = int.Parse(elementvalue); + this.ViewOrder = int.Parse(elementvalue); } + break; default: - if(reader.NodeType == XmlNodeType.Element && !String.IsNullOrEmpty(reader.Name)) + if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } + break; } } @@ -211,30 +207,29 @@ public void ReadXml(XmlReader reader) /// ----------------------------------------------------------------------------- /// - /// Writes a ModuleControlInfo to an XmlWriter + /// Writes a ModuleControlInfo to an XmlWriter. /// - /// The XmlWriter to use + /// The XmlWriter to use. /// ----------------------------------------------------------------------------- public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("moduleControl"); - //write out properties - WriteXmlInternal(writer); - writer.WriteElementString("controlTitle", ControlTitle); - writer.WriteElementString("controlType", ControlType.ToString()); - writer.WriteElementString("iconFile", IconFile); - writer.WriteElementString("helpUrl", HelpURL); - writer.WriteElementString("supportsPopUps", SupportsPopUps.ToString()); - if (ViewOrder > Null.NullInteger) + // write out properties + this.WriteXmlInternal(writer); + writer.WriteElementString("controlTitle", this.ControlTitle); + writer.WriteElementString("controlType", this.ControlType.ToString()); + writer.WriteElementString("iconFile", this.IconFile); + writer.WriteElementString("helpUrl", this.HelpURL); + writer.WriteElementString("supportsPopUps", this.SupportsPopUps.ToString()); + if (this.ViewOrder > Null.NullInteger) { - writer.WriteElementString("viewOrder", ViewOrder.ToString()); + writer.WriteElementString("viewOrder", this.ViewOrder.ToString()); } - //Write end of main element + + // Write end of main element writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleController.cs b/DNN Platform/Library/Entities/Modules/ModuleController.cs index 4d83f3275d8..b96d593cde3 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleController.cs @@ -1,65 +1,346 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Web; -using System.Xml; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.ModuleCache; -using DotNetNuke.Services.OutputCache; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.ModuleCache; + using DotNetNuke.Services.OutputCache; + using DotNetNuke.Services.Search.Entities; + /// - /// ModuleController provides the Business Layer for Modules + /// ModuleController provides the Business Layer for Modules. /// public partial class ModuleController : ServiceLocator, IModuleController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ModuleController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleController)); private static readonly DataProvider dataProvider = DataProvider.Instance(); + private static Hashtable ParsedLocalizedModuleGuid + { + get + { + if (HttpContext.Current.Items["ParsedLocalizedModuleGuid"] == null) + { + HttpContext.Current.Items["ParsedLocalizedModuleGuid"] = new Hashtable(); + } + + return (Hashtable)HttpContext.Current.Items["ParsedLocalizedModuleGuid"]; + } + } + + /// + /// Deserializes the module. + /// + /// The node module. + /// ModuleInfo of current module. + /// The portal id. + /// The tab id. + public static void DeserializeModule(XmlNode nodeModule, ModuleInfo module, int portalId, int tabId) + { + var moduleDefinition = GetModuleDefinition(nodeModule); + + // Create dummy pane node for private DeserializeModule method + var docPane = new XmlDocument { XmlResolver = null }; + docPane.LoadXml(string.Format("{0}", module.PaneName)); + + // Create ModuleInfo of Xml + ModuleInfo sourceModule = DeserializeModule(nodeModule, docPane.DocumentElement, portalId, tabId, moduleDefinition.ModuleDefID); + + // Copy properties from sourceModule to given (actual) module + module.ModuleTitle = sourceModule.ModuleTitle; + module.ModuleDefID = sourceModule.ModuleDefID; + module.CacheTime = sourceModule.CacheTime; + module.CacheMethod = sourceModule.CacheMethod; + module.Alignment = sourceModule.Alignment; + module.IconFile = sourceModule.IconFile; + module.AllTabs = sourceModule.AllTabs; + module.Visibility = sourceModule.Visibility; + module.Color = sourceModule.Color; + module.Border = sourceModule.Border; + module.Header = sourceModule.Header; + module.Footer = sourceModule.Footer; + module.InheritViewPermissions = sourceModule.InheritViewPermissions; + module.IsShareable = sourceModule.IsShareable; + module.IsShareableViewOnly = sourceModule.IsShareableViewOnly; + module.StartDate = sourceModule.StartDate; + module.EndDate = sourceModule.EndDate; + module.ContainerSrc = sourceModule.ContainerSrc; + module.DisplayTitle = sourceModule.DisplayTitle; + module.DisplayPrint = sourceModule.DisplayPrint; + module.DisplaySyndicate = sourceModule.DisplaySyndicate; + module.IsWebSlice = sourceModule.IsWebSlice; + + if (module.IsWebSlice) + { + module.WebSliceTitle = sourceModule.WebSliceTitle; + module.WebSliceExpiryDate = sourceModule.WebSliceExpiryDate; + module.WebSliceTTL = sourceModule.WebSliceTTL; + } + + // DNN-24983 get culture from page + var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); + if (tabInfo != null) + { + module.CultureCode = tabInfo.CultureCode; + } + + // save changes + Instance.UpdateModule(module); + + // deserialize Module's settings + XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); + DeserializeModuleSettings(nodeModuleSettings, module); + + XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); + DeserializeTabModuleSettings(nodeTabModuleSettings, module); + + // deserialize Content (if included) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content"))) + { + GetModuleContent(nodeModule, module.ModuleID, tabId, portalId); + } + + // deserialize Permissions + XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); + DeserializeModulePermissions(nodeModulePermissions, portalId, module); + + // Persist the permissions to the Data base + ModulePermissionController.SaveModulePermissions(module); + } + + /// + /// Deserializes the module. + /// + /// The node module. + /// The node pane. + /// The portal id. + /// The tab id. + /// The merge tabs. + /// The modules. + public static void DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules) + { + var moduleDefinition = GetModuleDefinition(nodeModule); + + // will be instance or module? + int templateModuleID = XmlUtils.GetNodeValueInt(nodeModule, "moduleID"); + bool isInstance = CheckIsInstance(templateModuleID, hModules); + if (moduleDefinition != null) + { + // If Mode is Merge Check if Module exists + if (!FindModule(nodeModule, tabId, mergeTabs)) + { + ModuleInfo module = DeserializeModule(nodeModule, nodePane, portalId, tabId, moduleDefinition.ModuleDefID); + + // if the module is marked as show on all tabs, then check whether the module is exist in current website and it also + // still marked as shown on all tabs, this action will make sure there is no duplicate modules created on new tab. + if (module.AllTabs) + { + var existModule = Instance.GetModule(templateModuleID, Null.NullInteger, false); + if (existModule != null && !existModule.IsDeleted && existModule.AllTabs && existModule.PortalID == portalId) + { + return; + } + } + + // deserialize Module's settings + XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); + DeserializeModuleSettings(nodeModuleSettings, module); + XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); + DeserializeTabModuleSettings(nodeTabModuleSettings, module); + + // DNN-24983 get culture from page + var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); + if (tabInfo != null) + { + module.CultureCode = tabInfo.CultureCode; + } + + int intModuleId; + if (!isInstance) + { + // Add new module + intModuleId = Instance.AddModule(module); + if (templateModuleID > 0) + { + hModules.Add(templateModuleID, intModuleId); + } + } + else + { + // Add instance + module.ModuleID = Convert.ToInt32(hModules[templateModuleID]); + intModuleId = Instance.AddModule(module); + } + + // save localization info + string oldGuid = XmlUtils.GetNodeValue(nodeModule, "uniqueId"); + if (!ParsedLocalizedModuleGuid.ContainsKey(oldGuid)) + { + ParsedLocalizedModuleGuid.Add(oldGuid, module.UniqueId.ToString()); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content")) && !isInstance) + { + GetModuleContent(nodeModule, intModuleId, tabId, portalId); + } + + // Process permissions only once + if (!isInstance && portalId != Null.NullInteger) + { + XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); + DeserializeModulePermissions(nodeModulePermissions, portalId, module); + + // Persist the permissions to the Data base + ModulePermissionController.SaveModulePermissions(module); + } + } + } + } + + /// + /// Check if a ModuleInfo belongs to the referenced Tab or not. + /// + /// A ModuleInfo object to be checked. + /// True is TabId points to a different tab from initial Tab where the module was added. Otherwise, False. + public bool IsSharedModule(ModuleInfo module) + { + var contentController = Util.GetContentController(); + var content = contentController.GetContentItem(module.ContentItemId); + return module.TabID != content.TabID; + } + + /// + /// Get the Tab ID corresponding to the initial Tab where the module was added. + /// + /// A ModuleInfo object to be checked. + /// The Tab Id from initial Tab where the module was added. + public int GetMasterTabId(ModuleInfo module) + { + var contentController = Util.GetContentController(); + var content = contentController.GetContentItem(module.ContentItemId); + return content.TabID; + } + + internal Hashtable GetModuleSettings(int moduleId, int tabId) + { + string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tabId); + + var moduleSettings = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.ModuleCacheTimeOut, + DataCache.ModuleCachePriority), + c => + { + var moduleSettingsDic = new Dictionary(); + IDataReader dr = DataProvider.Instance().GetModuleSettingsByTab(tabId); + while (dr.Read()) + { + int mId = dr.GetInt32(0); + Hashtable settings; + if (!moduleSettingsDic.TryGetValue(mId, out settings)) + { + settings = new Hashtable(); + moduleSettingsDic[mId] = settings; + } + + if (!dr.IsDBNull(2)) + { + settings[dr.GetString(1)] = dr.GetString(2); + } + else + { + settings[dr.GetString(1)] = string.Empty; + } + } + + CBO.CloseDataReader(dr, true); + return moduleSettingsDic; + }); + + return moduleSettings.ContainsKey(moduleId) ? moduleSettings[moduleId] : new Hashtable(); + } + + internal Hashtable GetTabModuleSettings(int tabmoduleId, int tabId) + { + string cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tabId); + + var tabModuleSettings = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.TabModuleCacheTimeOut, + DataCache.TabModuleCachePriority), + c => + { + var tabModuleSettingsDic = new Dictionary(); + using (IDataReader dr = DataProvider.Instance().GetTabModuleSettingsByTab(tabId)) + { + while (dr.Read()) + { + int tMId = dr.GetInt32(0); + Hashtable settings; + if (!tabModuleSettingsDic.TryGetValue(tMId, out settings)) + { + settings = new Hashtable(); + tabModuleSettingsDic[tMId] = settings; + } + + if (!dr.IsDBNull(2)) + { + settings[dr.GetString(1)] = dr.GetString(2); + } + else + { + settings[dr.GetString(1)] = string.Empty; + } + } + } + + return tabModuleSettingsDic; + }); + + return tabModuleSettings.ContainsKey(tabmoduleId) ? tabModuleSettings[tabmoduleId] : new Hashtable(); + } + protected override Func GetFactory() { return () => new ModuleController(); } - #region Private Methods private static void AddContent(XmlNode nodeModule, ModuleInfo module) { - if (!String.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && module.DesktopModule.IsPortable) + if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && module.DesktopModule.IsPortable) { try { @@ -68,11 +349,11 @@ private static void AddContent(XmlNode nodeModule, ModuleInfo module) if (controller != null) { string content = Convert.ToString(controller.ExportModule(module.ModuleID)); - if (!String.IsNullOrEmpty(content)) + if (!string.IsNullOrEmpty(content)) { content = XmlUtils.RemoveInvalidXmlCharacters(content); - //add attributes to XML document + // add attributes to XML document if (nodeModule.OwnerDocument != null) { var existing = nodeModule.OwnerDocument.GetElementById("content"); @@ -88,12 +369,14 @@ private static void AddContent(XmlNode nodeModule, ModuleInfo module) { newnode.Attributes.Append(xmlattr); } + xmlattr = nodeModule.OwnerDocument.CreateAttribute("version"); xmlattr.Value = module.DesktopModule.Version; if (newnode.Attributes != null) { newnode.Attributes.Append(xmlattr); } + content = HttpContext.Current.Server.HtmlEncode(content); newnode.InnerXml = XmlUtils.XMLEncode(content); nodeModule.AppendChild(newnode); @@ -108,52 +391,17 @@ private static void AddContent(XmlNode nodeModule, ModuleInfo module) } } - private void AddModuleInternal(ModuleInfo module) - { - // add module - if (Null.IsNull(module.ModuleID)) - { - var currentUser = UserController.Instance.GetCurrentUserInfo(); - CreateContentItem(module); - - //Add Module - module.ModuleID = dataProvider.AddModule(module.ContentItemId, - module.PortalID, - module.ModuleDefID, - module.AllTabs, - module.StartDate, - module.EndDate, - module.InheritViewPermissions, - module.IsShareable, - module.IsShareableViewOnly, - module.IsDeleted, - currentUser.UserID); - - //Now we have the ModuleID - update the contentItem - var contentController = Util.GetContentController(); - contentController.UpdateContentItem(module); - - EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, "", EventLogController.EventLogType.MODULE_CREATED); - - // set module permissions - ModulePermissionController.SaveModulePermissions(module); - } - - //Save ModuleSettings - UpdateModuleSettings(module); - - EventManager.Instance.OnModuleCreated(new ModuleEventArgs { Module = module }); - } - private static void AddModulePermission(ref ModuleInfo module, int portalId, string roleName, PermissionInfo permission, string permissionKey) { var perm = module.ModulePermissions.Where(tp => tp.RoleName == roleName && tp.PermissionKey == permissionKey).SingleOrDefault(); if (permission != null && perm == null) { var modulePermission = new ModulePermissionInfo(permission); -// ReSharper disable ImplicitlyCapturedClosure + + // ReSharper disable ImplicitlyCapturedClosure var role = RoleController.Instance.GetRole(portalId, r => (r.RoleName == roleName)); -// ReSharper restore ImplicitlyCapturedClosure + + // ReSharper restore ImplicitlyCapturedClosure if (role != null) { modulePermission.RoleID = role.RoleID; @@ -164,164 +412,110 @@ private static void AddModulePermission(ref ModuleInfo module, int portalId, str } } - private ModulePermissionInfo AddModulePermission(ModuleInfo module, PermissionInfo permission, int roleId, int userId, bool allowAccess) - { - var modulePermission = new ModulePermissionInfo - { - ModuleID = module.ModuleID, - PermissionID = permission.PermissionID, - RoleID = roleId, - UserID = userId, - PermissionKey = permission.PermissionKey, - AllowAccess = allowAccess - }; - - // add the permission to the collection - if (!module.ModulePermissions.Contains(modulePermission)) - { - module.ModulePermissions.Add(modulePermission); - } - - return modulePermission; - } - private static bool CheckIsInstance(int templateModuleID, Hashtable hModules) { - //will be instance or module? + // will be instance or module? bool IsInstance = false; if (templateModuleID > 0) { if (hModules[templateModuleID] != null) { - //this module has already been processed -> process as instance - IsInstance = true; - } - } - return IsInstance; - } - - private static void ClearModuleSettingsCache(int moduleId) - { - foreach (var tab in TabController.Instance.GetTabsByModuleID(moduleId).Values) - { - string cacheKey = String.Format(DataCache.ModuleSettingsCacheKey, tab.TabID); - DataCache.RemoveCache(cacheKey); - } - } - - private static void ClearTabModuleSettingsCache(int tabModuleId, string settingName) - { - var portalId = -1; - foreach (var tab in TabController.Instance.GetTabsByTabModuleID(tabModuleId).Values) - { - var cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tab.TabID); - DataCache.RemoveCache(cacheKey); - - if (portalId != tab.PortalID) - { - portalId = tab.PortalID; - cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? ""); - DataCache.RemoveCache(cacheKey); + // this module has already been processed -> process as instance + IsInstance = true; } } + + return IsInstance; } - private void CopyTabModuleSettingsInternal(ModuleInfo fromModule, ModuleInfo toModule) + private static void ClearModuleSettingsCache(int moduleId) { - //Copy each setting to the new TabModule instance - foreach (DictionaryEntry setting in fromModule.TabModuleSettings) + foreach (var tab in TabController.Instance.GetTabsByModuleID(moduleId).Values) { - UpdateTabModuleSetting(toModule.TabModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tab.TabID); + DataCache.RemoveCache(cacheKey); } } - /// - /// Checks whether module VIEW permission is inherited from its tab - /// - /// The module - /// The module permission. - private bool IsModuleViewPermissionInherited(ModuleInfo module, ModulePermissionInfo permission) + private void AddModuleInternal(ModuleInfo module) { - Requires.NotNull(module); - - Requires.NotNull(permission); + // add module + if (Null.IsNull(module.ModuleID)) + { + var currentUser = UserController.Instance.GetCurrentUserInfo(); + this.CreateContentItem(module); + + // Add Module + module.ModuleID = dataProvider.AddModule( + module.ContentItemId, + module.PortalID, + module.ModuleDefID, + module.AllTabs, + module.StartDate, + module.EndDate, + module.InheritViewPermissions, + module.IsShareable, + module.IsShareableViewOnly, + module.IsDeleted, + currentUser.UserID); + + // Now we have the ModuleID - update the contentItem + var contentController = Util.GetContentController(); + contentController.UpdateContentItem(module); - var permissionViewKey = "VIEW"; + EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.MODULE_CREATED); - if (!module.InheritViewPermissions || permission.PermissionKey != permissionViewKey) - { - return false; + // set module permissions + ModulePermissionController.SaveModulePermissions(module); } - var tabPermissions = TabPermissionController.GetTabPermissions(module.TabID, module.PortalID); - - return tabPermissions?.Where(x => x.RoleID == permission.RoleID && x.PermissionKey == permissionViewKey).Any() == true; + // Save ModuleSettings + this.UpdateModuleSettings(module); + + EventManager.Instance.OnModuleCreated(new ModuleEventArgs { Module = module }); } - /// - /// Checks whether given permission is granted for translator role - /// - /// The module permission. - /// The portal ID. - /// The culture code. - private bool IsTranslatorRolePermission(ModulePermissionInfo permission, int portalId, string culture) + private ModulePermissionInfo AddModulePermission(ModuleInfo module, PermissionInfo permission, int roleId, int userId, bool allowAccess) { - Requires.NotNull(permission); + var modulePermission = new ModulePermissionInfo + { + ModuleID = module.ModuleID, + PermissionID = permission.PermissionID, + RoleID = roleId, + UserID = userId, + PermissionKey = permission.PermissionKey, + AllowAccess = allowAccess, + }; - if (string.IsNullOrWhiteSpace(culture) || portalId == Null.NullInteger) + // add the permission to the collection + if (!module.ModulePermissions.Contains(modulePermission)) { - return false; + module.ModulePermissions.Add(modulePermission); } - var translatorSettingKey = $"DefaultTranslatorRoles-{ culture }"; - - var translatorSettingValue = - PortalController.GetPortalSetting(translatorSettingKey, portalId, null) ?? - HostController.Instance.GetString(translatorSettingKey, null); - - var translatorRoles = - translatorSettingValue?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - - return translatorRoles?.Any(r => r.Equals(permission.RoleName, StringComparison.OrdinalIgnoreCase)) == true; + return modulePermission; } - /// - /// Copies permissions from source to new tab - /// - /// Source module. - /// New module. - private void CopyModulePermisions(ModuleInfo sourceModule, ModuleInfo newModule) + private static void ClearTabModuleSettingsCache(int tabModuleId, string settingName) { - Requires.NotNull(sourceModule); - - Requires.NotNull(newModule); - - foreach (ModulePermissionInfo permission in sourceModule.ModulePermissions) + var portalId = -1; + foreach (var tab in TabController.Instance.GetTabsByTabModuleID(tabModuleId).Values) { - // skip inherited view and translator permissions - if (IsModuleViewPermissionInherited(newModule, permission) || - IsTranslatorRolePermission(permission, sourceModule.PortalID, sourceModule.CultureCode)) + var cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tab.TabID); + DataCache.RemoveCache(cacheKey); + + if (portalId != tab.PortalID) { - continue; + portalId = tab.PortalID; + cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? string.Empty); + DataCache.RemoveCache(cacheKey); } - - // need to force vew permission to be copied - permission.PermissionKey = newModule.InheritViewPermissions && permission.PermissionKey == "VIEW" ? - null : - permission.PermissionKey; - - AddModulePermission( - newModule, - permission, - permission.RoleID, - permission.UserID, - permission.AllowAccess); } } private static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, int moduleDefId) { - //Create New Module + // Create New Module var module = new ModuleInfo { PortalID = portalId, @@ -335,7 +529,7 @@ private static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane Alignment = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "alignment"), IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "iconfile")), AllTabs = XmlUtils.GetNodeValueBoolean(nodeModule, "alltabs"), - CultureCode = XmlUtils.GetNodeValue(nodeModule, "cultureCode") + CultureCode = XmlUtils.GetNodeValue(nodeModule, "cultureCode"), }; // Localization @@ -361,19 +555,21 @@ private static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane module.Visibility = VisibilityState.None; break; } - module.Color = XmlUtils.GetNodeValue(nodeModule, "color", ""); - module.Border = XmlUtils.GetNodeValue(nodeModule, "border", ""); - module.Header = XmlUtils.GetNodeValue(nodeModule, "header", ""); - module.Footer = XmlUtils.GetNodeValue(nodeModule, "footer", ""); + + module.Color = XmlUtils.GetNodeValue(nodeModule, "color", string.Empty); + module.Border = XmlUtils.GetNodeValue(nodeModule, "border", string.Empty); + module.Header = XmlUtils.GetNodeValue(nodeModule, "header", string.Empty); + module.Footer = XmlUtils.GetNodeValue(nodeModule, "footer", string.Empty); module.InheritViewPermissions = XmlUtils.GetNodeValueBoolean(nodeModule, "inheritviewpermissions", false); module.IsShareable = XmlUtils.GetNodeValueBoolean(nodeModule, "isshareable", true); module.IsShareableViewOnly = XmlUtils.GetNodeValueBoolean(nodeModule, "isshareableviewonly", true); module.StartDate = XmlUtils.GetNodeValueDate(nodeModule, "startdate", Null.NullDate); module.EndDate = XmlUtils.GetNodeValueDate(nodeModule, "enddate", Null.NullDate); - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule, "containersrc", ""))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule, "containersrc", string.Empty))) { - module.ContainerSrc = XmlUtils.GetNodeValue(nodeModule, "containersrc", ""); + module.ContainerSrc = XmlUtils.GetNodeValue(nodeModule, "containersrc", string.Empty); } + module.DisplayTitle = XmlUtils.GetNodeValueBoolean(nodeModule, "displaytitle", true); module.DisplayPrint = XmlUtils.GetNodeValueBoolean(nodeModule, "displayprint", true); module.DisplaySyndicate = XmlUtils.GetNodeValueBoolean(nodeModule, "displaysyndicate", false); @@ -384,6 +580,7 @@ private static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane module.WebSliceExpiryDate = XmlUtils.GetNodeValueDate(nodeModule, "websliceexpirydate", module.EndDate); module.WebSliceTTL = XmlUtils.GetNodeValueInt(nodeModule, "webslicettl", module.CacheTime / 60); } + return module; } @@ -410,8 +607,10 @@ private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissio { roleID = role.RoleID; } + break; } + if (roleID != int.MinValue) { int permissionID = -1; @@ -422,7 +621,7 @@ private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissio permissionID = permission.PermissionID; } - //if role was found add, otherwise ignore + // if role was found add, otherwise ignore if (permissionID != -1) { var modulePermission = new ModulePermissionInfo @@ -430,7 +629,7 @@ private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissio ModuleID = module.ModuleID, PermissionID = permissionID, RoleID = roleID, - AllowAccess = Convert.ToBoolean(XmlUtils.GetNodeValue(node.CreateNavigator(), "allowaccess")) + AllowAccess = Convert.ToBoolean(XmlUtils.GetNodeValue(node.CreateNavigator(), "allowaccess")), }; // do not add duplicate ModulePermissions @@ -448,6 +647,99 @@ private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissio } } + private void CopyTabModuleSettingsInternal(ModuleInfo fromModule, ModuleInfo toModule) + { + // Copy each setting to the new TabModule instance + foreach (DictionaryEntry setting in fromModule.TabModuleSettings) + { + this.UpdateTabModuleSetting(toModule.TabModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + } + } + + /// + /// Checks whether module VIEW permission is inherited from its tab. + /// + /// The module. + /// The module permission. + private bool IsModuleViewPermissionInherited(ModuleInfo module, ModulePermissionInfo permission) + { + Requires.NotNull(module); + + Requires.NotNull(permission); + + var permissionViewKey = "VIEW"; + + if (!module.InheritViewPermissions || permission.PermissionKey != permissionViewKey) + { + return false; + } + + var tabPermissions = TabPermissionController.GetTabPermissions(module.TabID, module.PortalID); + + return tabPermissions?.Where(x => x.RoleID == permission.RoleID && x.PermissionKey == permissionViewKey).Any() == true; + } + + /// + /// Checks whether given permission is granted for translator role. + /// + /// The module permission. + /// The portal ID. + /// The culture code. + private bool IsTranslatorRolePermission(ModulePermissionInfo permission, int portalId, string culture) + { + Requires.NotNull(permission); + + if (string.IsNullOrWhiteSpace(culture) || portalId == Null.NullInteger) + { + return false; + } + + var translatorSettingKey = $"DefaultTranslatorRoles-{culture}"; + + var translatorSettingValue = + PortalController.GetPortalSetting(translatorSettingKey, portalId, null) ?? + HostController.Instance.GetString(translatorSettingKey, null); + + var translatorRoles = + translatorSettingValue?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + + return translatorRoles?.Any(r => r.Equals(permission.RoleName, StringComparison.OrdinalIgnoreCase)) == true; + } + + /// + /// Copies permissions from source to new tab. + /// + /// Source module. + /// New module. + private void CopyModulePermisions(ModuleInfo sourceModule, ModuleInfo newModule) + { + Requires.NotNull(sourceModule); + + Requires.NotNull(newModule); + + foreach (ModulePermissionInfo permission in sourceModule.ModulePermissions) + { + // skip inherited view and translator permissions + if (this.IsModuleViewPermissionInherited(newModule, permission) || + this.IsTranslatorRolePermission(permission, sourceModule.PortalID, sourceModule.CultureCode)) + { + continue; + } + + // need to force vew permission to be copied + permission.PermissionKey = newModule.InheritViewPermissions && permission.PermissionKey == "VIEW" ? + null : + permission.PermissionKey; + + this.AddModulePermission( + newModule, + permission, + permission.RoleID, + permission.UserID, + permission.AllowAccess); + } + } + private static void DeserializeModuleSettings(XmlNodeList nodeModuleSettings, ModuleInfo objModule) { foreach (XmlNode moduleSettingNode in nodeModuleSettings) @@ -481,6 +773,7 @@ private static bool FindModule(XmlNode nodeModule, int tabId, PortalTemplateModu moduleFound = true; } } + return moduleFound; } @@ -493,17 +786,17 @@ private static void GetModuleContent(XmlNode nodeModule, int ModuleId, int TabId string version = nodeModule.SelectSingleNode("content").Attributes["version"].Value; string content = nodeModule.SelectSingleNode("content").InnerXml; content = content.Substring(9, content.Length - 12); - if (!String.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && !String.IsNullOrEmpty(content)) + if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && !string.IsNullOrEmpty(content)) { var portal = PortalController.Instance.GetPortal(PortalId); - //Determine if the Module is copmpletely installed - //(ie are we running in the same request that installed the module). + // Determine if the Module is copmpletely installed + // (ie are we running in the same request that installed the module). if (module.DesktopModule.SupportedFeatures == Null.NullInteger) { - //save content in eventqueue for processing after an app restart, - //as modules Supported Features are not updated yet so we - //cannot determine if the module supports IsPortable + // save content in eventqueue for processing after an app restart, + // as modules Supported Features are not updated yet so we + // cannot determine if the module supports IsPortable EventMessageProcessor.CreateImportModuleMessage(module, content, version, portal.AdministratorId); } else @@ -522,12 +815,13 @@ private static void GetModuleContent(XmlNode nodeModule, int ModuleId, int TabId } catch { - //if there is an error then the type cannot be loaded at this time, so add to EventQueue + // if there is an error then the type cannot be loaded at this time, so add to EventQueue EventMessageProcessor.CreateImportModuleMessage(module, content, version, portal.AdministratorId); } } } } + // ReSharper restore PossibleNullReferenceException } } @@ -536,23 +830,23 @@ private static ModuleDefinitionInfo GetModuleDefinition(XmlNode nodeModule) { ModuleDefinitionInfo moduleDefinition = null; - //Templates prior to v4.3.5 only have the node to define the Module Type - //This node was populated with the DesktopModuleInfo.ModuleName property - //Thus there is no mechanism to determine to which module definition the module belongs. + // Templates prior to v4.3.5 only have the node to define the Module Type + // This node was populated with the DesktopModuleInfo.ModuleName property + // Thus there is no mechanism to determine to which module definition the module belongs. // - //Template from v4.3.5 on also have the element that is populated - //with the ModuleDefinitionInfo.FriendlyName. Therefore the module Instance identifies - //which Module Definition it belongs to. + // Template from v4.3.5 on also have the element that is populated + // with the ModuleDefinitionInfo.FriendlyName. Therefore the module Instance identifies + // which Module Definition it belongs to. - //Get the DesktopModule defined by the element + // Get the DesktopModule defined by the element var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "definition"), Null.NullInteger); if (desktopModule != null) { - //Get the moduleDefinition from the element + // Get the moduleDefinition from the element string friendlyName = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "moduledefinition"); if (string.IsNullOrEmpty(friendlyName)) { - //Module is pre 4.3.5 so get the first Module Definition (at least it won't throw an error then) + // Module is pre 4.3.5 so get the first Module Definition (at least it won't throw an error then) foreach (ModuleDefinitionInfo md in ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModule.DesktopModuleID).Values) { moduleDefinition = md; @@ -561,86 +855,24 @@ private static ModuleDefinitionInfo GetModuleDefinition(XmlNode nodeModule) } else { - //Module is 4.3.5 or later so get the Module Defeinition by its friendly name + // Module is 4.3.5 or later so get the Module Defeinition by its friendly name moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(friendlyName, desktopModule.DesktopModuleID); } } + return moduleDefinition; } - internal Hashtable GetModuleSettings(int moduleId, int tabId) + private static void SetCloneModuleContext(bool cloneModuleContext) { - string cacheKey = String.Format(DataCache.ModuleSettingsCacheKey, tabId); - - var moduleSettings = CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.ModuleCacheTimeOut, - DataCache.ModuleCachePriority), - c => - { - var moduleSettingsDic = new Dictionary(); - IDataReader dr = DataProvider.Instance().GetModuleSettingsByTab(tabId); - while (dr.Read()) - { - int mId = dr.GetInt32(0); - Hashtable settings; - if (!moduleSettingsDic.TryGetValue(mId, out settings)) - { - settings = new Hashtable(); - moduleSettingsDic[mId] = settings; - } - - if (!dr.IsDBNull(2)) - { - settings[dr.GetString(1)] = dr.GetString(2); - } - else - { - settings[dr.GetString(1)] = ""; - } - } - CBO.CloseDataReader(dr, true); - return moduleSettingsDic; - }); - - return moduleSettings.ContainsKey(moduleId) ? moduleSettings[moduleId] : new Hashtable(); + Thread.SetData( + Thread.GetNamedDataSlot("CloneModuleContext"), + cloneModuleContext ? bool.TrueString : bool.FalseString); } - internal Hashtable GetTabModuleSettings(int tabmoduleId, int tabId) + private static void UpdateTabModuleVersion(int tabModuleId) { - string cacheKey = String.Format(DataCache.TabModuleSettingsCacheKey, tabId); - - var tabModuleSettings = CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.TabModuleCacheTimeOut, - DataCache.TabModuleCachePriority), - c => - { - var tabModuleSettingsDic = new Dictionary(); - using (IDataReader dr = DataProvider.Instance().GetTabModuleSettingsByTab(tabId)) - { - while (dr.Read()) - { - int tMId = dr.GetInt32(0); - Hashtable settings; - if (!tabModuleSettingsDic.TryGetValue(tMId, out settings)) - { - settings = new Hashtable(); - tabModuleSettingsDic[tMId] = settings; - } - - if (!dr.IsDBNull(2)) - { - settings[dr.GetString(1)] = dr.GetString(2); - } - else - { - settings[dr.GetString(1)] = ""; - } - } - } - return tabModuleSettingsDic; - }); - - return (tabModuleSettings.ContainsKey(tabmoduleId)) ? tabModuleSettings[tabmoduleId] : new Hashtable(); + dataProvider.UpdateTabModuleVersion(tabModuleId, Guid.NewGuid()); } private int LocalizeModuleInternal(ModuleInfo sourceModule) @@ -653,22 +885,22 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) var newModule = sourceModule.Clone(); newModule.ModuleID = Null.NullInteger; - string translatorRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", sourceModule.CultureCode), sourceModule.PortalID, "").TrimEnd(';'); + string translatorRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", sourceModule.CultureCode), sourceModule.PortalID, string.Empty).TrimEnd(';'); - //Add the default translators for this language, view and edit permissions + // Add the default translators for this language, view and edit permissions var permissionController = new PermissionController(); var viewPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); var editPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "EDIT"); PermissionInfo viewPermisison = null; PermissionInfo editPermisison = null; - //View + // View if (viewPermissionsList != null && viewPermissionsList.Count > 0) { viewPermisison = (PermissionInfo)viewPermissionsList[0]; } - //Edit + // Edit if (editPermissionsList != null && editPermissionsList.Count > 0) { editPermisison = (PermissionInfo)editPermissionsList[0]; @@ -684,53 +916,54 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) } // copy permisions from source to new module - CopyModulePermisions(sourceModule, newModule); + this.CopyModulePermisions(sourceModule, newModule); - //Add Module - AddModuleInternal(newModule); + // Add Module + this.AddModuleInternal(newModule); - //copy module settings - DataCache.RemoveCache(string.Format(DataCache.ModuleSettingsCacheKey, sourceModule.TabID)); - var settings = GetModuleSettings(sourceModule.ModuleID, sourceModule.TabID); + // copy module settings + DataCache.RemoveCache(string.Format(DataCache.ModuleSettingsCacheKey, sourceModule.TabID)); + var settings = this.GetModuleSettings(sourceModule.ModuleID, sourceModule.TabID); // update tabmodule - var currentUser = UserController.Instance.GetCurrentUserInfo(); - dataProvider.UpdateTabModule(newModule.TabModuleID, - newModule.TabID, - newModule.ModuleID, - newModule.ModuleTitle, - newModule.Header, - newModule.Footer, - newModule.ModuleOrder, - newModule.PaneName, - newModule.CacheTime, - newModule.CacheMethod, - newModule.Alignment, - newModule.Color, - newModule.Border, - newModule.IconFile, - (int)newModule.Visibility, - newModule.ContainerSrc, - newModule.DisplayTitle, - newModule.DisplayPrint, - newModule.DisplaySyndicate, - newModule.IsWebSlice, - newModule.WebSliceTitle, - newModule.WebSliceExpiryDate, - newModule.WebSliceTTL, - newModule.VersionGuid, - newModule.DefaultLanguageGuid, - newModule.LocalizedVersionGuid, - newModule.CultureCode, - currentUser.UserID); + var currentUser = UserController.Instance.GetCurrentUserInfo(); + dataProvider.UpdateTabModule( + newModule.TabModuleID, + newModule.TabID, + newModule.ModuleID, + newModule.ModuleTitle, + newModule.Header, + newModule.Footer, + newModule.ModuleOrder, + newModule.PaneName, + newModule.CacheTime, + newModule.CacheMethod, + newModule.Alignment, + newModule.Color, + newModule.Border, + newModule.IconFile, + (int)newModule.Visibility, + newModule.ContainerSrc, + newModule.DisplayTitle, + newModule.DisplayPrint, + newModule.DisplaySyndicate, + newModule.IsWebSlice, + newModule.WebSliceTitle, + newModule.WebSliceExpiryDate, + newModule.WebSliceTTL, + newModule.VersionGuid, + newModule.DefaultLanguageGuid, + newModule.LocalizedVersionGuid, + newModule.CultureCode, + currentUser.UserID); DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); - //Copy each setting to the new TabModule instance + // Copy each setting to the new TabModule instance foreach (DictionaryEntry setting in settings) - { - UpdateModuleSetting(newModule.ModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); - } + { + this.UpdateModuleSetting(newModule.ModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + } if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass)) { @@ -753,7 +986,6 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) { SetCloneModuleContext(false); } - } } catch (Exception ex) @@ -764,29 +996,12 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) moduleId = newModule.ModuleID; - //Clear Caches - ClearCache(newModule.TabID); - ClearCache(sourceModule.TabID); + // Clear Caches + this.ClearCache(newModule.TabID); + this.ClearCache(sourceModule.TabID); } - return moduleId; - } - - private static void SetCloneModuleContext(bool cloneModuleContext) - { - Thread.SetData(Thread.GetNamedDataSlot("CloneModuleContext"), - cloneModuleContext ? bool.TrueString : bool.FalseString); - } - - private static Hashtable ParsedLocalizedModuleGuid - { - get - { - if (HttpContext.Current.Items["ParsedLocalizedModuleGuid"] == null) - HttpContext.Current.Items["ParsedLocalizedModuleGuid"] = new Hashtable(); - - return (Hashtable)HttpContext.Current.Items["ParsedLocalizedModuleGuid"]; - } + return moduleId; } private void UpdateModuleSettingInternal(int moduleId, string settingName, string settingValue, bool updateVersion) @@ -797,32 +1012,34 @@ private void UpdateModuleSettingInternal(int moduleId, string settingName, strin var currentUser = UserController.Instance.GetCurrentUserInfo(); dr = dataProvider.GetModuleSetting(moduleId, settingName); - string existValue = null; + string existValue = null; if (dr.Read()) { - existValue = dr.GetString(1); + existValue = dr.GetString(1); } - dr.Close(); + dr.Close(); if (existValue == null) { dataProvider.UpdateModuleSetting(moduleId, settingName, settingValue, currentUser.UserID); - EventLogController.AddSettingLog(EventLogController.EventLogType.MODULE_SETTING_CREATED, + EventLogController.AddSettingLog( + EventLogController.EventLogType.MODULE_SETTING_CREATED, "ModuleId", moduleId, settingName, settingValue, currentUser.UserID); - } + } else if (existValue != settingValue) { dataProvider.UpdateModuleSetting(moduleId, settingName, settingValue, currentUser.UserID); - EventLogController.AddSettingLog(EventLogController.EventLogType.MODULE_SETTING_UPDATED, - "ModuleId", moduleId, settingName, settingValue, - currentUser.UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.MODULE_SETTING_UPDATED, + "ModuleId", moduleId, settingName, settingValue, + currentUser.UserID); } if (updateVersion) { - UpdateTabModuleVersionsByModuleID(moduleId); + this.UpdateTabModuleVersionsByModuleID(moduleId); } } catch (Exception ex) @@ -832,10 +1049,10 @@ private void UpdateModuleSettingInternal(int moduleId, string settingName, strin finally { // Ensure DataReader is closed - if (dr != null && !dr.IsClosed) - { - CBO.CloseDataReader(dr, true); - } + if (dr != null && !dr.IsClosed) + { + CBO.CloseDataReader(dr, true); + } } ClearModuleSettingsCache(moduleId); @@ -846,81 +1063,78 @@ private void UpdateModuleSettings(ModuleInfo updatedModule) foreach (string key in updatedModule.ModuleSettings.Keys) { string sKey = key; - UpdateModuleSettingInternal(updatedModule.ModuleID, sKey, Convert.ToString(updatedModule.ModuleSettings[sKey]), false); + this.UpdateModuleSettingInternal(updatedModule.ModuleID, sKey, Convert.ToString(updatedModule.ModuleSettings[sKey]), false); } - UpdateTabModuleVersionsByModuleID(updatedModule.ModuleID); + + this.UpdateTabModuleVersionsByModuleID(updatedModule.ModuleID); } private void UpdateTabModuleSettings(ModuleInfo updatedTabModule) { foreach (string sKey in updatedTabModule.TabModuleSettings.Keys) { - UpdateTabModuleSetting(updatedTabModule.TabModuleID, sKey, Convert.ToString(updatedTabModule.TabModuleSettings[sKey])); + this.UpdateTabModuleSetting(updatedTabModule.TabModuleID, sKey, Convert.ToString(updatedTabModule.TabModuleSettings[sKey])); } } - private static void UpdateTabModuleVersion(int tabModuleId) - { - dataProvider.UpdateTabModuleVersion(tabModuleId, Guid.NewGuid()); - } - private void UpdateTabModuleVersionsByModuleID(int moduleID) { // Update the version guid of each TabModule linked to the updated module - foreach (ModuleInfo modInfo in GetAllTabsModulesByModuleID(moduleID)) + foreach (ModuleInfo modInfo in this.GetAllTabsModulesByModuleID(moduleID)) { - ClearCache(modInfo.TabID); + this.ClearCache(modInfo.TabID); } + dataProvider.UpdateTabModuleVersionByModule(moduleID); } private bool HasModuleOrderOrPaneChanged(ModuleInfo module) { - var storedModuleInfo = GetTabModule(module.TabModuleID); + var storedModuleInfo = this.GetTabModule(module.TabModuleID); return storedModuleInfo == null || storedModuleInfo.ModuleOrder != module.ModuleOrder || storedModuleInfo.PaneName != module.PaneName; } private void UncopyModule(int tabId, int moduleId, bool softDelete, int originalTabId) { - ModuleInfo moduleInfo = GetModule(moduleId, tabId, false); - DeleteTabModuleInternal(moduleInfo, softDelete, true); + ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); + this.DeleteTabModuleInternal(moduleInfo, softDelete, true); var userId = UserController.Instance.GetCurrentUserInfo().UserID; - TabChangeTracker.Instance.TrackModuleUncopy(moduleInfo, Null.NullInteger, originalTabId, userId); + TabChangeTracker.Instance.TrackModuleUncopy(moduleInfo, Null.NullInteger, originalTabId, userId); } private void DeleteTabModuleInternal(ModuleInfo moduleInfo, bool softDelete, bool uncopy = false) { - //save moduleinfo - + // save moduleinfo if (moduleInfo != null) { - //delete the module instance for the tab + // delete the module instance for the tab dataProvider.DeleteTabModule(moduleInfo.TabID, moduleInfo.ModuleID, softDelete, UserController.Instance.GetCurrentUserInfo().UserID); var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TABMODULE_DELETED.ToString() }; log.LogProperties.Add(new LogDetailInfo("tabId", moduleInfo.TabID.ToString(CultureInfo.InvariantCulture))); log.LogProperties.Add(new LogDetailInfo("moduleId", moduleInfo.ModuleID.ToString(CultureInfo.InvariantCulture))); LogController.Instance.AddLog(log); - //reorder all modules on tab + // reorder all modules on tab if (!uncopy) { - UpdateTabModuleOrder(moduleInfo.TabID); - //ModuleRemove is only raised when doing a soft delete of the module + this.UpdateTabModuleOrder(moduleInfo.TabID); + + // ModuleRemove is only raised when doing a soft delete of the module if (softDelete) - { + { EventManager.Instance.OnModuleRemoved(new ModuleEventArgs { Module = moduleInfo }); } } - //check if all modules instances have been deleted - if (GetModule(moduleInfo.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) + // check if all modules instances have been deleted + if (this.GetModule(moduleInfo.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) { - //hard delete the module - DeleteModule(moduleInfo.ModuleID); + // hard delete the module + this.DeleteModule(moduleInfo.ModuleID); } - + DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID)); - ClearCache(moduleInfo.TabID); + this.ClearCache(moduleInfo.TabID); } } @@ -938,102 +1152,75 @@ private void UpdateContentItem(ModuleInfo module) } } - #endregion - - #region Public Methods - - /// - /// Check if a ModuleInfo belongs to the referenced Tab or not - /// - /// A ModuleInfo object to be checked - /// True is TabId points to a different tab from initial Tab where the module was added. Otherwise, False - public bool IsSharedModule(ModuleInfo module) - { - var contentController = Util.GetContentController(); - var content = contentController.GetContentItem(module.ContentItemId); - return module.TabID != content.TabID; - } - - /// - /// Get the Tab ID corresponding to the initial Tab where the module was added - /// - /// A ModuleInfo object to be checked - /// The Tab Id from initial Tab where the module was added - public int GetMasterTabId(ModuleInfo module) - { - var contentController = Util.GetContentController(); - var content = contentController.GetContentItem(module.ContentItemId); - return content.TabID; - } - /// - /// add a module to a page + /// add a module to a page. /// - /// moduleInfo for the module to create - /// ID of the created module + /// moduleInfo for the module to create. + /// ID of the created module. public int AddModule(ModuleInfo module) { - //add module - AddModuleInternal(module); + // add module + this.AddModuleInternal(module); var currentUser = UserController.Instance.GetCurrentUserInfo(); - //Lets see if the module already exists - ModuleInfo tmpModule = GetModule(module.ModuleID, module.TabID, false); + // Lets see if the module already exists + ModuleInfo tmpModule = this.GetModule(module.ModuleID, module.TabID, false); if (tmpModule != null) { - //Module Exists already + // Module Exists already if (tmpModule.IsDeleted) { var order = module.ModuleOrder; var pane = module.PaneName; - //Restore Module - RestoreModule(module); + // Restore Module + this.RestoreModule(module); TabChangeTracker.Instance.TrackModuleAddition(module, 1, currentUser.UserID); - //Set Module Order as expected - UpdateModuleOrder(module.TabID, module.ModuleID, order, pane); - UpdateTabModuleOrder(module.TabID); + // Set Module Order as expected + this.UpdateModuleOrder(module.TabID, module.ModuleID, order, pane); + this.UpdateTabModuleOrder(module.TabID); } } else { - //add tabmodule - dataProvider.AddTabModule(module.TabID, - module.ModuleID, - module.ModuleTitle, - module.Header, - module.Footer, - module.ModuleOrder, - module.PaneName, - module.CacheTime, - module.CacheMethod, - module.Alignment, - module.Color, - module.Border, - module.IconFile, - (int)module.Visibility, - module.ContainerSrc, - module.DisplayTitle, - module.DisplayPrint, - module.DisplaySyndicate, - module.IsWebSlice, - module.WebSliceTitle, - module.WebSliceExpiryDate, - module.WebSliceTTL, - module.UniqueId, - module.VersionGuid, - module.DefaultLanguageGuid, - module.LocalizedVersionGuid, - module.CultureCode, - currentUser.UserID); + // add tabmodule + dataProvider.AddTabModule( + module.TabID, + module.ModuleID, + module.ModuleTitle, + module.Header, + module.Footer, + module.ModuleOrder, + module.PaneName, + module.CacheTime, + module.CacheMethod, + module.Alignment, + module.Color, + module.Border, + module.IconFile, + (int)module.Visibility, + module.ContainerSrc, + module.DisplayTitle, + module.DisplayPrint, + module.DisplaySyndicate, + module.IsWebSlice, + module.WebSliceTitle, + module.WebSliceExpiryDate, + module.WebSliceTTL, + module.UniqueId, + module.VersionGuid, + module.DefaultLanguageGuid, + module.LocalizedVersionGuid, + module.CultureCode, + currentUser.UserID); var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TABMODULE_CREATED.ToString(), - LogPortalID = module.PortalID + LogPortalID = module.PortalID, }; log.LogProperties.Add(new LogDetailInfo("TabPath", module.ParentTab.TabPath)); log.LogProperties.Add(new LogDetailInfo("Module Type", module.ModuleDefinition.FriendlyName)); @@ -1045,28 +1232,30 @@ public int AddModule(ModuleInfo module) if (module.ModuleOrder == -1) { - //position module at bottom of pane - UpdateModuleOrder(module.TabID, module.ModuleID, module.ModuleOrder, module.PaneName); + // position module at bottom of pane + this.UpdateModuleOrder(module.TabID, module.ModuleID, module.ModuleOrder, module.PaneName); } else { - //position module in pane - UpdateTabModuleOrder(module.TabID); + // position module in pane + this.UpdateTabModuleOrder(module.TabID); } } - //Save ModuleSettings + // Save ModuleSettings if (module.TabModuleID == -1) { if (tmpModule == null) { - tmpModule = GetModule(module.ModuleID, module.TabID, false); + tmpModule = this.GetModule(module.ModuleID, module.TabID, false); } + module.TabModuleID = tmpModule.TabModuleID; } - UpdateTabModuleSettings(module); - ClearCache(module.TabID); + this.UpdateTabModuleSettings(module); + + this.ClearCache(module.TabID); return module.ModuleID; } @@ -1090,41 +1279,41 @@ public void CopyModule(ModuleInfo sourceModule, TabInfo destinationTab, string t { PortalInfo portal = PortalController.Instance.GetPortal(destinationTab.PortalID); - //Clone Module + // Clone Module ModuleInfo destinationModule = sourceModule.Clone(); - if (!String.IsNullOrEmpty(toPaneName)) + if (!string.IsNullOrEmpty(toPaneName)) { destinationModule.PaneName = toPaneName; } destinationModule.TabID = destinationTab.TabID; - //The new reference copy should have the same culture as the destination Tab + // The new reference copy should have the same culture as the destination Tab destinationModule.UniqueId = Guid.NewGuid(); destinationModule.CultureCode = destinationTab.CultureCode; destinationModule.VersionGuid = Guid.NewGuid(); destinationModule.LocalizedVersionGuid = Guid.NewGuid(); - //Figure out the DefaultLanguage Guid - if (!String.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode == portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && - !String.IsNullOrEmpty(destinationModule.CultureCode)) + // Figure out the DefaultLanguage Guid + if (!string.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode == portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && + !string.IsNullOrEmpty(destinationModule.CultureCode)) { - //Tab is localized so set Default language Guid reference + // Tab is localized so set Default language Guid reference destinationModule.DefaultLanguageGuid = sourceModule.UniqueId; } - else if (!String.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode != portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && - !String.IsNullOrEmpty(destinationModule.CultureCode)) + else if (!string.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode != portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && + !string.IsNullOrEmpty(destinationModule.CultureCode)) { // tab is localized, but the source is not in the default language (it was on a single culture page) - // this wires up all the connections + // this wires up all the connections sourceModule.DefaultLanguageGuid = destinationModule.UniqueId; - UpdateModule(sourceModule); + this.UpdateModule(sourceModule); } else if (sourceModule.AllTabs && sourceModule.CultureCode != portal.DefaultLanguage) { if (sourceModule.DefaultLanguageModule != null && destinationTab.DefaultLanguageTab != null) { - ModuleInfo defaultLanguageModule = GetModule(sourceModule.DefaultLanguageModule.ModuleID, destinationTab.DefaultLanguageTab.TabID, false); + ModuleInfo defaultLanguageModule = this.GetModule(sourceModule.DefaultLanguageModule.ModuleID, destinationTab.DefaultLanguageTab.TabID, false); if (defaultLanguageModule != null) { @@ -1133,45 +1322,47 @@ public void CopyModule(ModuleInfo sourceModule, TabInfo destinationTab, string t } } - //This will fail if the page already contains this module + // This will fail if the page already contains this module try { var userId = UserController.Instance.GetCurrentUserInfo().UserID; - //Add a copy of the module to the bottom of the Pane for the new Tab - dataProvider.AddTabModule(destinationModule.TabID, - destinationModule.ModuleID, - destinationModule.ModuleTitle, - destinationModule.Header, - destinationModule.Footer, - destinationModule.ModuleOrder, - destinationModule.PaneName, - destinationModule.CacheTime, - destinationModule.CacheMethod, - destinationModule.Alignment, - destinationModule.Color, - destinationModule.Border, - destinationModule.IconFile, - (int)destinationModule.Visibility, - destinationModule.ContainerSrc, - destinationModule.DisplayTitle, - destinationModule.DisplayPrint, - destinationModule.DisplaySyndicate, - destinationModule.IsWebSlice, - destinationModule.WebSliceTitle, - destinationModule.WebSliceExpiryDate, - destinationModule.WebSliceTTL, - destinationModule.UniqueId, - destinationModule.VersionGuid, - destinationModule.DefaultLanguageGuid, - destinationModule.LocalizedVersionGuid, - destinationModule.CultureCode, - userId); + + // Add a copy of the module to the bottom of the Pane for the new Tab + dataProvider.AddTabModule( + destinationModule.TabID, + destinationModule.ModuleID, + destinationModule.ModuleTitle, + destinationModule.Header, + destinationModule.Footer, + destinationModule.ModuleOrder, + destinationModule.PaneName, + destinationModule.CacheTime, + destinationModule.CacheMethod, + destinationModule.Alignment, + destinationModule.Color, + destinationModule.Border, + destinationModule.IconFile, + (int)destinationModule.Visibility, + destinationModule.ContainerSrc, + destinationModule.DisplayTitle, + destinationModule.DisplayPrint, + destinationModule.DisplaySyndicate, + destinationModule.IsWebSlice, + destinationModule.WebSliceTitle, + destinationModule.WebSliceExpiryDate, + destinationModule.WebSliceTTL, + destinationModule.UniqueId, + destinationModule.VersionGuid, + destinationModule.DefaultLanguageGuid, + destinationModule.LocalizedVersionGuid, + destinationModule.CultureCode, + userId); TabChangeTracker.Instance.TrackModuleCopy(destinationModule, 1, sourceModule.TabID, userId); - //Optionally copy the TabModuleSettings + // Optionally copy the TabModuleSettings if (includeSettings) { - CopyTabModuleSettingsInternal(sourceModule, destinationModule); + this.CopyTabModuleSettingsInternal(sourceModule, destinationModule); } } catch (Exception exc) @@ -1180,14 +1371,14 @@ public void CopyModule(ModuleInfo sourceModule, TabInfo destinationTab, string t Logger.Error(exc); } - ClearCache(sourceModule.TabID); - ClearCache(destinationTab.TabID); + this.ClearCache(sourceModule.TabID); + this.ClearCache(destinationTab.TabID); - //Optionally copy the TabModuleSettings + // Optionally copy the TabModuleSettings if (includeSettings) { - destinationModule = GetModule(destinationModule.ModuleID, destinationModule.TabID, false); - CopyTabModuleSettingsInternal(sourceModule, destinationModule); + destinationModule = this.GetModule(destinationModule.ModuleID, destinationModule.TabID, false); + this.CopyTabModuleSettingsInternal(sourceModule, destinationModule); } } @@ -1199,7 +1390,7 @@ public void CopyModule(ModuleInfo sourceModule, TabInfo destinationTab, string t /// if set to true will use source module directly, else will create new module info by source module. public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asReference) { - CopyModules(sourceTab, destinationTab, asReference, false); + this.CopyModules(sourceTab, destinationTab, asReference, false); } /// @@ -1211,7 +1402,7 @@ public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asRefere /// if set to true will include modules which shown on all pages, this is used when create localized copy. public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asReference, bool includeAllTabsMobules) { - foreach (KeyValuePair kvp in GetTabModules(sourceTab.TabID)) + foreach (KeyValuePair kvp in this.GetTabModules(sourceTab.TabID)) { ModuleInfo sourceModule = kvp.Value; @@ -1221,16 +1412,16 @@ public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asRefere { if (!asReference) { - //Deep Copy + // Deep Copy var newModule = sourceModule.Clone(); newModule.ModuleID = Null.NullInteger; newModule.TabID = destinationTab.TabID; - AddModule(newModule); + this.AddModule(newModule); } else { - //Shallow (Reference Copy) - CopyModule(sourceModule, destinationTab, Null.NullString, true); + // Shallow (Reference Copy) + this.CopyModule(sourceModule, destinationTab, Null.NullString, true); } } } @@ -1243,9 +1434,10 @@ public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asRefere /// public void CreateContentItem(ModuleInfo module) { - ContentType contentType = ContentType.Module; - //This module does not have a valid ContentItem - //create ContentItem + ContentType contentType = ContentType.Module; + + // This module does not have a valid ContentItem + // create ContentItem IContentController contentController = Util.GetContentController(); module.Content = module.ModuleTitle; module.Indexed = false; @@ -1253,47 +1445,49 @@ public void CreateContentItem(ModuleInfo module) { module.ContentTypeId = contentType.ContentTypeId; } + module.ContentItemId = contentController.AddContentItem(module); } /// /// DeleteAllModules deletes all instances of a Module (from a collection), optionally excluding the - /// current instance, and optionally including deleting the Module itself. + /// current instance, and optionally including deleting the Module itself. /// /// - /// Note - the base module is not removed unless both the flags are set, indicating - /// to delete all instances AND to delete the Base Module + /// Note - the base module is not removed unless both the flags are set, indicating + /// to delete all instances AND to delete the Base Module. /// - /// The Id of the module to copy - /// The Id of the current tab - /// A flag that determines whether the instance should be soft-deleted - /// An ArrayList of TabItem objects - /// A flag to indicate whether to delete from the current tab - /// as identified ny tabId - /// A flag to indicate whether to delete the Module itself + /// The Id of the module to copy. + /// The Id of the current tab. + /// A flag that determines whether the instance should be soft-deleted. + /// An ArrayList of TabItem objects. + /// A flag to indicate whether to delete from the current tab + /// as identified ny tabId. + /// A flag to indicate whether to delete the Module itself. public void DeleteAllModules(int moduleId, int tabId, List fromTabs, bool softDelete, bool includeCurrent, bool deleteBaseModule) { - var moduleInfo = GetModule(moduleId, tabId, false); + var moduleInfo = this.GetModule(moduleId, tabId, false); - //Iterate through collection deleting the module from each Tab (except the current) + // Iterate through collection deleting the module from each Tab (except the current) foreach (TabInfo objTab in fromTabs) { if (objTab.TabID != tabId || includeCurrent) { - UncopyModule(objTab.TabID, moduleId, softDelete, tabId); //uncopy existing modules + this.UncopyModule(objTab.TabID, moduleId, softDelete, tabId); // uncopy existing modules } } - //Optionally delete the Module + + // Optionally delete the Module if (includeCurrent && deleteBaseModule && !softDelete) { - DeleteModule(moduleId); - ClearCache(tabId); + this.DeleteModule(moduleId); + this.ClearCache(tabId); } else { - ClearCache(tabId); + this.ClearCache(tabId); - //ModuleRemove is only raised when doing a soft delete of the module + // ModuleRemove is only raised when doing a soft delete of the module if (softDelete) { EventManager.Instance.OnModuleRemoved(new ModuleEventArgs { Module = moduleInfo }); @@ -1302,31 +1496,32 @@ public void DeleteAllModules(int moduleId, int tabId, List fromTabs, bo } /// - /// Delete a module instance permanently from the database + /// Delete a module instance permanently from the database. /// - /// ID of the module instance + /// ID of the module instance. public void DeleteModule(int moduleId) { - //Get the module - ModuleInfo module = GetModule(moduleId, Null.NullInteger, true); - //Delete Module + // Get the module + ModuleInfo module = this.GetModule(moduleId, Null.NullInteger, true); + + // Delete Module dataProvider.DeleteModule(moduleId); - //Remove the Content Item + // Remove the Content Item if (module != null && module.ContentItemId > Null.NullInteger) { IContentController contentController = Util.GetContentController(); contentController.DeleteContentItem(module); } - //Log deletion + // Log deletion EventLogController.Instance.AddLog("ModuleId", moduleId.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.MODULE_DELETED); // queue remove module from search index var document = new SearchDocumentToDelete { - ModuleId = moduleId + ModuleId = moduleId, }; DataProvider.Instance().AddSearchDeletedItems(document); @@ -1335,32 +1530,32 @@ public void DeleteModule(int moduleId) } /// - /// Delete a Setting of a module instance + /// Delete a Setting of a module instance. /// - /// ID of the affected module - /// Name of the setting to be deleted + /// ID of the affected module. + /// Name of the setting to be deleted. public void DeleteModuleSetting(int moduleId, string settingName) { dataProvider.DeleteModuleSetting(moduleId, settingName); - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString()}; + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString() }; log.LogProperties.Add(new LogDetailInfo("ModuleId", moduleId.ToString(CultureInfo.InvariantCulture))); log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); LogController.Instance.AddLog(log); - UpdateTabModuleVersionsByModuleID(moduleId); + this.UpdateTabModuleVersionsByModuleID(moduleId); ClearModuleSettingsCache(moduleId); } /// /// Delete a module reference permanently from the database. - /// if there are no other references, the module instance is deleted as well + /// if there are no other references, the module instance is deleted as well. /// - /// ID of the page - /// ID of the module instance - /// A flag that determines whether the instance should be soft-deleted + /// ID of the page. + /// ID of the module instance. + /// A flag that determines whether the instance should be soft-deleted. public void DeleteTabModule(int tabId, int moduleId, bool softDelete) { - ModuleInfo moduleInfo = GetModule(moduleId, tabId, false); - DeleteTabModuleInternal(moduleInfo, softDelete); + ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); + this.DeleteTabModuleInternal(moduleInfo, softDelete); var userId = UserController.Instance.GetCurrentUserInfo().UserID; if (softDelete) { @@ -1369,17 +1564,17 @@ public void DeleteTabModule(int tabId, int moduleId, bool softDelete) } /// - /// Delete a specific setting of a tabmodule reference + /// Delete a specific setting of a tabmodule reference. /// - /// ID of the affected tabmodule - /// Name of the setting to remove + /// ID of the affected tabmodule. + /// Name of the setting to remove. public void DeleteTabModuleSetting(int tabModuleId, string settingName) { dataProvider.DeleteTabModuleSetting(tabModuleId, settingName); UpdateTabModuleVersion(tabModuleId); var log = new LogInfo { - LogTypeKey = EventLogController.EventLogType.TABMODULE_SETTING_DELETED.ToString() + LogTypeKey = EventLogController.EventLogType.TABMODULE_SETTING_DELETED.ToString(), }; log.LogProperties.Add(new LogDetailInfo("TabModuleId", tabModuleId.ToString(CultureInfo.InvariantCulture))); log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); @@ -1391,7 +1586,7 @@ public void DeleteTabModuleSetting(int tabModuleId, string settingName) /// Des the localize module. /// /// The source module. - /// new module id + /// new module id. public int DeLocalizeModule(ModuleInfo sourceModule) { int moduleId = Null.NullInteger; @@ -1401,169 +1596,172 @@ public int DeLocalizeModule(ModuleInfo sourceModule) // clone the module object ( to avoid creating an object reference to the data cache ) ModuleInfo newModule = sourceModule.Clone(); - //Get the Module ID of the default language instance + // Get the Module ID of the default language instance newModule.ModuleID = sourceModule.DefaultLanguageModule.ModuleID; if (newModule.ModuleID != sourceModule.ModuleID) { // update tabmodule - dataProvider.UpdateTabModule(newModule.TabModuleID, - newModule.TabID, - newModule.ModuleID, - newModule.ModuleTitle, - newModule.Header, - newModule.Footer, - newModule.ModuleOrder, - newModule.PaneName, - newModule.CacheTime, - newModule.CacheMethod, - newModule.Alignment, - newModule.Color, - newModule.Border, - newModule.IconFile, - (int)newModule.Visibility, - newModule.ContainerSrc, - newModule.DisplayTitle, - newModule.DisplayPrint, - newModule.DisplaySyndicate, - newModule.IsWebSlice, - newModule.WebSliceTitle, - newModule.WebSliceExpiryDate, - newModule.WebSliceTTL, - newModule.VersionGuid, - newModule.DefaultLanguageGuid, - newModule.LocalizedVersionGuid, - newModule.CultureCode, - UserController.Instance.GetCurrentUserInfo().UserID); + dataProvider.UpdateTabModule( + newModule.TabModuleID, + newModule.TabID, + newModule.ModuleID, + newModule.ModuleTitle, + newModule.Header, + newModule.Footer, + newModule.ModuleOrder, + newModule.PaneName, + newModule.CacheTime, + newModule.CacheMethod, + newModule.Alignment, + newModule.Color, + newModule.Border, + newModule.IconFile, + (int)newModule.Visibility, + newModule.ContainerSrc, + newModule.DisplayTitle, + newModule.DisplayPrint, + newModule.DisplaySyndicate, + newModule.IsWebSlice, + newModule.WebSliceTitle, + newModule.WebSliceExpiryDate, + newModule.WebSliceTTL, + newModule.VersionGuid, + newModule.DefaultLanguageGuid, + newModule.LocalizedVersionGuid, + newModule.CultureCode, + UserController.Instance.GetCurrentUserInfo().UserID); DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); - //Update tab version details of old and new modules + // Update tab version details of old and new modules var userId = UserController.Instance.GetCurrentUserInfo().UserID; TabChangeTracker.Instance.TrackModuleDeletion(sourceModule, Null.NullInteger, userId); TabChangeTracker.Instance.TrackModuleCopy(newModule, Null.NullInteger, newModule.TabID, userId); - //check if all modules instances have been deleted - if (GetModule(sourceModule.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) + // check if all modules instances have been deleted + if (this.GetModule(sourceModule.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) { - //delete the deep copy "module info" - DeleteModule(sourceModule.ModuleID); + // delete the deep copy "module info" + this.DeleteModule(sourceModule.ModuleID); } } moduleId = newModule.ModuleID; - //Clear Caches - ClearCache(newModule.TabID); - ClearCache(sourceModule.TabID); + // Clear Caches + this.ClearCache(newModule.TabID); + this.ClearCache(sourceModule.TabID); } return moduleId; } /// - /// get info of all modules in any portal of the installation + /// get info of all modules in any portal of the installation. /// - /// moduleInfo of all modules - /// created for upgrade purposes + /// moduleInfo of all modules. + /// created for upgrade purposes. public ArrayList GetAllModules() { return CBO.FillCollection(dataProvider.GetAllModules(), typeof(ModuleInfo)); } /// - /// get Module objects of a portal, either only those, to be placed on all tabs or not + /// get Module objects of a portal, either only those, to be placed on all tabs or not. /// - /// ID of the portal - /// specify, whether to return modules to be shown on all tabs or those to be shown on specified tabs - /// ArrayList of TabModuleInfo objects + /// ID of the portal. + /// specify, whether to return modules to be shown on all tabs or those to be shown on specified tabs. + /// ArrayList of TabModuleInfo objects. public ArrayList GetAllTabsModules(int portalID, bool allTabs) { return CBO.FillCollection(dataProvider.GetAllTabsModules(portalID, allTabs), typeof(ModuleInfo)); } /// - /// get TabModule objects that are linked to a particular ModuleID + /// get TabModule objects that are linked to a particular ModuleID. /// - /// ID of the module - /// ArrayList of TabModuleInfo objects + /// ID of the module. + /// ArrayList of TabModuleInfo objects. public ArrayList GetAllTabsModulesByModuleID(int moduleID) { return CBO.FillCollection(dataProvider.GetAllTabsModulesByModuleID(moduleID), typeof(ModuleInfo)); } /// - /// get a Module object + /// get a Module object. /// - /// ID of the module - /// ModuleInfo object + /// ID of the module. + /// ModuleInfo object. /// This overload ignores any cached values and always retrieves the latest data /// from the database. public ModuleInfo GetModule(int moduleID) { - return GetModule(moduleID, Null.NullInteger, true); + return this.GetModule(moduleID, Null.NullInteger, true); } /// - /// get a Module object + /// get a Module object. /// - /// ID of the module - /// ID of the page - /// ModuleInfo object + /// ID of the module. + /// ID of the page. + /// ModuleInfo object. public ModuleInfo GetModule(int moduleID, int tabID) { - return GetModule(moduleID, tabID, false); + return this.GetModule(moduleID, tabID, false); } /// - /// get a Module object + /// get a Module object. /// - /// ID of the module - /// ID of the page - /// flag, if data shall not be taken from cache - /// ModuleInfo object + /// ID of the module. + /// ID of the page. + /// flag, if data shall not be taken from cache. + /// ModuleInfo object. public ModuleInfo GetModule(int moduleID, int tabID, bool ignoreCache) { ModuleInfo modInfo = null; bool bFound = false; if (!ignoreCache) { - //First try the cache - var dicModules = GetTabModules(tabID); + // First try the cache + var dicModules = this.GetTabModules(tabID); bFound = dicModules.TryGetValue(moduleID, out modInfo); } + if (ignoreCache || !bFound) { modInfo = CBO.FillObject(dataProvider.GetModule(moduleID, tabID)); } + return modInfo; } /// - /// get Module by specific locale + /// get Module by specific locale. /// - /// ID of the module - /// ID of the tab - /// ID of the portal - /// The wanted locale - /// ModuleInfo associated to submitted locale + /// ID of the module. + /// ID of the tab. + /// ID of the portal. + /// The wanted locale. + /// ModuleInfo associated to submitted locale. public ModuleInfo GetModuleByCulture(int ModuleId, int tabid, int portalId, Locale locale) { ModuleInfo localizedModule = null; - //Get Module specified by Id - ModuleInfo originalModule = GetModule(ModuleId, tabid, false); + // Get Module specified by Id + ModuleInfo originalModule = this.GetModule(ModuleId, tabid, false); if (locale != null && originalModule != null) { - //Check if tab is in the requested culture + // Check if tab is in the requested culture if (string.IsNullOrEmpty(originalModule.CultureCode) || originalModule.CultureCode == locale.Code) { localizedModule = originalModule; } else { - //See if tab exists for culture + // See if tab exists for culture if (originalModule.IsDefaultLanguage) { originalModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule); @@ -1587,25 +1785,26 @@ public ModuleInfo GetModuleByCulture(int ModuleId, int tabid, int portalId, Loca } } } + return localizedModule; } /// - /// Get ModuleInfo object of first module instance with a given name of the module definition + /// Get ModuleInfo object of first module instance with a given name of the module definition. /// - /// ID of the portal, where to look for the module - /// The name of module definition (NOTE: this looks at , not ) - /// ModuleInfo of first module instance - /// preferably used for admin and host modules + /// ID of the portal, where to look for the module. + /// The name of module definition (NOTE: this looks at , not ). + /// ModuleInfo of first module instance. + /// preferably used for admin and host modules. public ModuleInfo GetModuleByDefinition(int portalId, string definitionName) { - //declare return object + // declare return object ModuleInfo module; - //format cache key + // format cache key string key = string.Format(DataCache.ModuleCacheKey, portalId); - //get module dictionary from cache + // get module dictionary from cache var modules = DataCache.GetCache>(key) ?? new Dictionary(); if (modules.ContainsKey(definitionName)) { @@ -1613,44 +1812,47 @@ public ModuleInfo GetModuleByDefinition(int portalId, string definitionName) } else { - //clone the dictionary so that we have a local copy + // clone the dictionary so that we have a local copy var clonemodules = new Dictionary(); foreach (ModuleInfo m in modules.Values) { clonemodules[m.ModuleDefinition.DefinitionName] = m; } - //get from database + + // get from database IDataReader dr = DataProvider.Instance().GetModuleByDefinition(portalId, definitionName); try { - //hydrate object + // hydrate object module = CBO.FillObject(dr); } finally { - //close connection + // close connection CBO.CloseDataReader(dr, true); } + if (module != null) { - //add the module to the dictionary + // add the module to the dictionary clonemodules[module.ModuleDefinition.FriendlyName] = module; - //set module caching settings - Int32 timeOut = DataCache.ModuleCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); + // set module caching settings + int timeOut = DataCache.ModuleCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); - //cache module dictionary + // cache module dictionary if (timeOut > 0) { DataCache.SetCache(key, clonemodules, TimeSpan.FromMinutes(timeOut)); } } } + return module; } /// - /// get a Module object + /// get a Module object. /// /// /// @@ -1662,10 +1864,10 @@ public ModuleInfo GetModuleByUniqueID(Guid uniqueID) } /// - /// get all Module objects of a portal + /// get all Module objects of a portal. /// - /// ID of the portal - /// ArrayList of ModuleInfo objects + /// ID of the portal. + /// ArrayList of ModuleInfo objects. public ArrayList GetModules(int portalID) { return CBO.FillCollection(dataProvider.GetModules(portalID), typeof(ModuleInfo)); @@ -1676,7 +1878,7 @@ public ArrayList GetModules(int portalID) /// /// The portal ID. /// The name of the module definition. - /// module collection + /// module collection. public ArrayList GetModulesByDefinition(int portalID, string definitionName) { return CBO.FillCollection(DataProvider.Instance().GetModuleByDefinition(portalID, definitionName), typeof(ModuleInfo)); @@ -1686,7 +1888,7 @@ public ArrayList GetModulesByDefinition(int portalID, string definitionName) /// Gets the modules by DesktopModuleId. /// /// The Desktop Module Id. - /// module collection + /// module collection. public ArrayList GetModulesByDesktopModuleId(int desktopModuleId) { var moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId); @@ -1696,9 +1898,10 @@ public ArrayList GetModulesByDesktopModuleId(int desktopModuleId) var portals = PortalController.Instance.GetPortals(); foreach (PortalInfo portal in portals) { - modules.AddRange(GetModulesByDefinition(portal.PortalID, moduleDefinition.Value.DefinitionName)); + modules.AddRange(this.GetModulesByDefinition(portal.PortalID, moduleDefinition.Value.DefinitionName)); } } + return modules; } @@ -1706,7 +1909,7 @@ public ArrayList GetModulesByDesktopModuleId(int desktopModuleId) /// For a portal get a list of all active module and tabmodule references that are Searchable /// either by inheriting from ModuleSearchBase or implementing the older ISearchable interface. /// - /// ID of the portal to be searched + /// ID of the portal to be searched. /// Arraylist of ModuleInfo for modules supporting search. public ArrayList GetSearchModules(int portalID) { @@ -1714,49 +1917,39 @@ public ArrayList GetSearchModules(int portalID) } /// - /// get a Module object + /// get a Module object. /// - /// ID of the tabmodule - /// An ModuleInfo object + /// ID of the tabmodule. + /// An ModuleInfo object. public ModuleInfo GetTabModule(int tabModuleID) { var cacheKey = string.Format(DataCache.SingleTabModuleCacheKey, tabModuleID); return CBO.GetCachedObject( new CacheItemArgs(cacheKey, DataCache.TabModuleCacheTimeOut, DataCache.TabModuleCachePriority), - c => CBO.FillObject(dataProvider.GetTabModule(tabModuleID))); + c => CBO.FillObject(dataProvider.GetTabModule(tabModuleID))); } /// - /// Get all Module references on a tab + /// Get all Module references on a tab. /// /// - /// Dictionary of ModuleID and ModuleInfo + /// Dictionary of ModuleID and ModuleInfo. public Dictionary GetTabModules(int tabId) { var cacheKey = string.Format(DataCache.TabModuleCacheKey, tabId); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.TabModuleCacheTimeOut, - DataCache.TabModuleCachePriority), - c => GetModulesCurrentPage(tabId)); - } - - private Dictionary GetModulesCurrentPage(int tabId) - { - var modules = CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); - - var dictionary = new Dictionary(); - foreach (var module in modules) - { - dictionary[module.ModuleID] = module; - } - return dictionary; + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.TabModuleCacheTimeOut, + DataCache.TabModuleCachePriority), + c => this.GetModulesCurrentPage(tabId)); } /// - /// Get a list of all TabModule references of a module instance + /// Get a list of all TabModule references of a module instance. /// - /// ID of the Module - /// ArrayList of ModuleInfo + /// ID of the Module. + /// ArrayList of ModuleInfo. public IList GetTabModulesByModule(int moduleID) { return CBO.FillCollection(dataProvider.GetModule(moduleID, Null.NullInteger)); @@ -1777,12 +1970,13 @@ public void InitialModulePermission(ModuleInfo module, int tabId, int permission { if (tabPermission.PermissionKey == "VIEW" && permissionType == 0) { - //Don't need to explicitly add View permisisons if "Same As Page" + // Don't need to explicitly add View permisisons if "Same As Page" continue; } // get the system module permissions for the permissionkey ArrayList systemModulePermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", tabPermission.PermissionKey); + // loop through the system module permissions int j; for (j = 0; j <= systemModulePermissions.Count - 1; j++) @@ -1791,21 +1985,21 @@ public void InitialModulePermission(ModuleInfo module, int tabId, int permission var systemModulePermission = (PermissionInfo)systemModulePermissions[j]; if (systemModulePermission.PermissionKey == "VIEW" && permissionType == 1 && tabPermission.PermissionKey != "EDIT") { - //Only Page Editors get View permissions if "Page Editors Only" + // Only Page Editors get View permissions if "Page Editors Only" continue; } - ModulePermissionInfo modulePermission = AddModulePermission(module, systemModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); + ModulePermissionInfo modulePermission = this.AddModulePermission(module, systemModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); // ensure that every EDIT permission which allows access also provides VIEW permission if (modulePermission.PermissionKey == "EDIT" && modulePermission.AllowAccess) { - AddModulePermission(module, (PermissionInfo)systemModuleViewPermissions[0], modulePermission.RoleID, modulePermission.UserID, true); + this.AddModulePermission(module, (PermissionInfo)systemModuleViewPermissions[0], modulePermission.RoleID, modulePermission.UserID, true); } } - //Get the custom Module Permissions, Assume that roles with Edit Tab Permissions - //are automatically assigned to the Custom Module Permissions + // Get the custom Module Permissions, Assume that roles with Edit Tab Permissions + // are automatically assigned to the Custom Module Permissions if (tabPermission.PermissionKey == "EDIT") { ArrayList customModulePermissions = permissionController.GetPermissionsByModuleDefID(module.ModuleDefID); @@ -1816,17 +2010,30 @@ public void InitialModulePermission(ModuleInfo module, int tabId, int permission // create the module permission var customModulePermission = (PermissionInfo)customModulePermissions[j]; - AddModulePermission(module, customModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); + this.AddModulePermission(module, customModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); } } } } + private Dictionary GetModulesCurrentPage(int tabId) + { + var modules = CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); + + var dictionary = new Dictionary(); + foreach (var module in modules) + { + dictionary[module.ModuleID] = module; + } + + return dictionary; + } + public void LocalizeModule(ModuleInfo sourceModule, Locale locale) { try { - // we could be working from a single culture page that is not in the default language, + // we could be working from a single culture page that is not in the default language, // so we need to test whether or not the module is going to be localized for the default locale var defaultLocale = LocaleController.Instance.GetDefaultLocale(sourceModule.PortalID); ModuleInfo defaultModule = locale.Code == defaultLocale.Code ? sourceModule : sourceModule.DefaultLanguageModule; @@ -1836,15 +2043,15 @@ public void LocalizeModule(ModuleInfo sourceModule, Locale locale) ModuleInfo localizedModule; var alreadyLocalized = defaultModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule) && localizedModule.ModuleID != defaultModule.ModuleID; - var tabModules = GetTabModulesByModule(defaultModule.ModuleID); + var tabModules = this.GetTabModulesByModule(defaultModule.ModuleID); if (tabModules.Count > 1) { - //default language version is a reference copy + // default language version is a reference copy - //Localize first tabModule - var newModuleId = alreadyLocalized ? localizedModule.ModuleID : LocalizeModuleInternal(sourceModule); + // Localize first tabModule + var newModuleId = alreadyLocalized ? localizedModule.ModuleID : this.LocalizeModuleInternal(sourceModule); - //Update Reference Copies + // Update Reference Copies foreach (ModuleInfo tm in tabModules) { if (tm.IsDefaultLanguage) @@ -1853,15 +2060,15 @@ public void LocalizeModule(ModuleInfo sourceModule, Locale locale) if (tm.LocalizedModules.TryGetValue(locale.Code, out localModule)) { localModule.ModuleID = newModuleId; - UpdateModule(localModule); + this.UpdateModule(localModule); } } } } else if (!alreadyLocalized) { - LocalizeModuleInternal(sourceModule); - } + this.LocalizeModuleInternal(sourceModule); + } } } catch (Exception ex) @@ -1872,18 +2079,18 @@ public void LocalizeModule(ModuleInfo sourceModule, Locale locale) /// /// MoveModule moes a Module from one Tab to another including all the - /// TabModule settings + /// TabModule settings. /// - /// The Id of the module to move - /// The Id of the source tab - /// The Id of the destination tab - /// The name of the Pane on the destination tab where the module will end up + /// The Id of the module to move. + /// The Id of the source tab. + /// The Id of the destination tab. + /// The name of the Pane on the destination tab where the module will end up. public void MoveModule(int moduleId, int fromTabId, int toTabId, string toPaneName) { - //Move the module to the Tab + // Move the module to the Tab dataProvider.MoveTabModule(fromTabId, moduleId, toTabId, toPaneName, UserController.Instance.GetCurrentUserInfo().UserID); - //Update the Tab reference for the module's ContentItems + // Update the Tab reference for the module's ContentItems var contentController = Util.GetContentController(); var contentItems = contentController.GetContentItemsByModuleId(moduleId); if (contentItems != null) @@ -1898,11 +2105,11 @@ public void MoveModule(int moduleId, int fromTabId, int toTabId, string toPaneNa } } - //Update Module Order for source tab, also updates the tabmodule version guid - UpdateTabModuleOrder(fromTabId); + // Update Module Order for source tab, also updates the tabmodule version guid + this.UpdateTabModuleOrder(fromTabId); - //Update Module Order for target tab, also updates the tabmodule version guid - UpdateTabModuleOrder(toTabId); + // Update Module Order for target tab, also updates the tabmodule version guid + this.UpdateTabModuleOrder(toTabId); } /// @@ -1914,44 +2121,45 @@ public void RestoreModule(ModuleInfo objModule) dataProvider.RestoreTabModule(objModule.TabID, objModule.ModuleID); var userId = UserController.Instance.GetCurrentUserInfo().UserID; TabChangeTracker.Instance.TrackModuleAddition(objModule, 1, userId); - ClearCache(objModule.TabID); + this.ClearCache(objModule.TabID); } /// - /// Update module settings and permissions in database from ModuleInfo + /// Update module settings and permissions in database from ModuleInfo. /// - /// ModuleInfo of the module to update + /// ModuleInfo of the module to update. public void UpdateModule(ModuleInfo module) { - //Update ContentItem If neccessary + // Update ContentItem If neccessary if (module.ModuleID != Null.NullInteger) { if (module.ContentItemId == Null.NullInteger) { - CreateContentItem(module); + this.CreateContentItem(module); } else { - UpdateContentItem(module); + this.UpdateContentItem(module); } } var currentUser = UserController.Instance.GetCurrentUserInfo(); - //update module - dataProvider.UpdateModule(module.ModuleID, - module.ModuleDefID, - module.ContentItemId, - module.AllTabs, - module.StartDate, - module.EndDate, - module.InheritViewPermissions, - module.IsShareable, - module.IsShareableViewOnly, - module.IsDeleted, - currentUser.UserID); - - //Update Tags + // update module + dataProvider.UpdateModule( + module.ModuleID, + module.ModuleDefID, + module.ContentItemId, + module.AllTabs, + module.StartDate, + module.EndDate, + module.InheritViewPermissions, + module.IsShareable, + module.IsShareableViewOnly, + module.IsDeleted, + currentUser.UserID); + + // Update Tags ITermController termController = Util.GetTermController(); termController.RemoveTermsFromContent(module); foreach (Term term in module.Terms) @@ -1959,71 +2167,73 @@ public void UpdateModule(ModuleInfo module) termController.AddTermToContent(term, module); } - EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, "", EventLogController.EventLogType.MODULE_UPDATED); + EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.MODULE_UPDATED); - //save module permissions + // save module permissions ModulePermissionController.SaveModulePermissions(module); - UpdateModuleSettings(module); + this.UpdateModuleSettings(module); module.VersionGuid = Guid.NewGuid(); module.LocalizedVersionGuid = Guid.NewGuid(); if (!Null.IsNull(module.TabID)) { - var hasModuleOrderOrPaneChanged = HasModuleOrderOrPaneChanged(module); - - //update tabmodule - dataProvider.UpdateTabModule(module.TabModuleID, - module.TabID, - module.ModuleID, - module.ModuleTitle, - module.Header, - module.Footer, - module.ModuleOrder, - module.PaneName, - module.CacheTime, - module.CacheMethod, - module.Alignment, - module.Color, - module.Border, - module.IconFile, - (int)module.Visibility, - module.ContainerSrc, - module.DisplayTitle, - module.DisplayPrint, - module.DisplaySyndicate, - module.IsWebSlice, - module.WebSliceTitle, - module.WebSliceExpiryDate, - module.WebSliceTTL, - module.VersionGuid, - module.DefaultLanguageGuid, - module.LocalizedVersionGuid, - module.CultureCode, - currentUser.UserID); + var hasModuleOrderOrPaneChanged = this.HasModuleOrderOrPaneChanged(module); + + // update tabmodule + dataProvider.UpdateTabModule( + module.TabModuleID, + module.TabID, + module.ModuleID, + module.ModuleTitle, + module.Header, + module.Footer, + module.ModuleOrder, + module.PaneName, + module.CacheTime, + module.CacheMethod, + module.Alignment, + module.Color, + module.Border, + module.IconFile, + (int)module.Visibility, + module.ContainerSrc, + module.DisplayTitle, + module.DisplayPrint, + module.DisplaySyndicate, + module.IsWebSlice, + module.WebSliceTitle, + module.WebSliceExpiryDate, + module.WebSliceTTL, + module.VersionGuid, + module.DefaultLanguageGuid, + module.LocalizedVersionGuid, + module.CultureCode, + currentUser.UserID); DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, module.TabModuleID)); - EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, "", EventLogController.EventLogType.TABMODULE_UPDATED); + EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.TABMODULE_UPDATED); if (hasModuleOrderOrPaneChanged) { - //update module order in pane - UpdateModuleOrder(module.TabID, module.ModuleID, module.ModuleOrder, module.PaneName); + // update module order in pane + this.UpdateModuleOrder(module.TabID, module.ModuleID, module.ModuleOrder, module.PaneName); } - //set the default module + // set the default module if (PortalSettings.Current != null) { if (module.IsDefaultModule) { if (module.ModuleID != PortalSettings.Current.DefaultModuleId) { - //Update Setting + // Update Setting PortalController.UpdatePortalSetting(module.PortalID, "defaultmoduleid", module.ModuleID.ToString(CultureInfo.InvariantCulture)); } + if (module.TabID != PortalSettings.Current.DefaultTabId) { - //Update Setting + // Update Setting PortalController.UpdatePortalSetting(module.PortalID, "defaulttabid", module.TabID.ToString(CultureInfo.InvariantCulture)); } } @@ -2031,81 +2241,84 @@ public void UpdateModule(ModuleInfo module) { if (module.ModuleID == PortalSettings.Current.DefaultModuleId && module.TabID == PortalSettings.Current.DefaultTabId) { - //Clear setting + // Clear setting PortalController.DeletePortalSetting(module.PortalID, "defaultmoduleid"); PortalController.DeletePortalSetting(module.PortalID, "defaulttabid"); } } } - //apply settings to all desktop modules in portal + + // apply settings to all desktop modules in portal if (module.AllModules) { foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(module.PortalID)) { TabInfo tab = tabPair.Value; - foreach (KeyValuePair modulePair in GetTabModules(tab.TabID)) + foreach (KeyValuePair modulePair in this.GetTabModules(tab.TabID)) { var targetModule = modulePair.Value; targetModule.VersionGuid = Guid.NewGuid(); targetModule.LocalizedVersionGuid = Guid.NewGuid(); - dataProvider.UpdateTabModule(targetModule.TabModuleID, - targetModule.TabID, - targetModule.ModuleID, - targetModule.ModuleTitle, - targetModule.Header, - targetModule.Footer, - targetModule.ModuleOrder, - targetModule.PaneName, - targetModule.CacheTime, - targetModule.CacheMethod, - module.Alignment, - module.Color, - module.Border, - module.IconFile, - (int)module.Visibility, - module.ContainerSrc, - module.DisplayTitle, - module.DisplayPrint, - module.DisplaySyndicate, - module.IsWebSlice, - module.WebSliceTitle, - module.WebSliceExpiryDate, - module.WebSliceTTL, - targetModule.VersionGuid, - targetModule.DefaultLanguageGuid, - targetModule.LocalizedVersionGuid, - targetModule.CultureCode, - currentUser.UserID); + dataProvider.UpdateTabModule( + targetModule.TabModuleID, + targetModule.TabID, + targetModule.ModuleID, + targetModule.ModuleTitle, + targetModule.Header, + targetModule.Footer, + targetModule.ModuleOrder, + targetModule.PaneName, + targetModule.CacheTime, + targetModule.CacheMethod, + module.Alignment, + module.Color, + module.Border, + module.IconFile, + (int)module.Visibility, + module.ContainerSrc, + module.DisplayTitle, + module.DisplayPrint, + module.DisplaySyndicate, + module.IsWebSlice, + module.WebSliceTitle, + module.WebSliceExpiryDate, + module.WebSliceTTL, + targetModule.VersionGuid, + targetModule.DefaultLanguageGuid, + targetModule.LocalizedVersionGuid, + targetModule.CultureCode, + currentUser.UserID); DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, targetModule.TabModuleID)); - ClearCache(targetModule.TabID); + this.ClearCache(targetModule.TabID); } } } } - //Clear Cache for all TabModules - foreach (ModuleInfo tabModule in GetTabModulesByModule(module.ModuleID)) + + // Clear Cache for all TabModules + foreach (ModuleInfo tabModule in this.GetTabModulesByModule(module.ModuleID)) { - ClearCache(tabModule.TabID); + this.ClearCache(tabModule.TabID); } EventManager.Instance.OnModuleUpdated(new ModuleEventArgs { Module = module }); } - + /// - /// set/change the module position within a pane on a page + /// set/change the module position within a pane on a page. /// - /// ID of the page - /// ID of the module on the page - /// position within the controls list on page, -1 if to be added at the end - /// name of the pane, the module is placed in on the page + /// ID of the page. + /// ID of the module on the page. + /// position within the controls list on page, -1 if to be added at the end. + /// name of the pane, the module is placed in on the page. public void UpdateModuleOrder(int tabId, int moduleId, int moduleOrder, string paneName) { - ModuleInfo moduleInfo = GetModule(moduleId, tabId, false); + ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); if (moduleInfo != null) { - //adding a module to a new pane - places the module at the bottom of the pane + // adding a module to a new pane - places the module at the bottom of the pane if (moduleOrder == -1) { IDataReader dr = null; @@ -2125,31 +2338,34 @@ public void UpdateModuleOrder(int tabId, int moduleId, int moduleOrder, string p { CBO.CloseDataReader(dr, true); } + moduleOrder += 2; } + dataProvider.UpdateModuleOrder(tabId, moduleId, moduleOrder, paneName); - TabChangeTracker.Instance.TrackModuleModification(GetModule(moduleId, tabId, true), Null.NullInteger, UserController.Instance.GetCurrentUserInfo().UserID); - //clear cache - ClearCache(tabId); + TabChangeTracker.Instance.TrackModuleModification(this.GetModule(moduleId, tabId, true), Null.NullInteger, UserController.Instance.GetCurrentUserInfo().UserID); + + // clear cache + this.ClearCache(tabId); } } /// - /// Adds or updates a module's setting value + /// Adds or updates a module's setting value. /// - /// ID of the module, the setting belongs to - /// name of the setting property + /// ID of the module, the setting belongs to. + /// name of the setting property. /// value of the setting (String). - /// empty SettingValue will remove the setting, if not preserveIfEmpty is true + /// empty SettingValue will remove the setting, if not preserveIfEmpty is true. public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) { - UpdateModuleSettingInternal(moduleId, settingName, settingValue, true); + this.UpdateModuleSettingInternal(moduleId, settingName, settingValue, true); } /// - /// set/change all module's positions within a page + /// set/change all module's positions within a page. /// - /// ID of the page + /// ID of the page. public void UpdateTabModuleOrder(int tabId) { IDataReader dr = dataProvider.GetTabPanes(tabId); @@ -2171,12 +2387,16 @@ public void UpdateTabModuleOrder(int tabId) var existingOrder = Convert.ToInt32(dr2["ModuleOrder"]); var newOrder = (moduleCounter * 2) - 1; - if (existingOrder == newOrder) continue; + if (existingOrder == newOrder) + { + continue; + } + dataProvider.UpdateModuleOrder(tabId, moduleId, newOrder, paneName); if (!isDeleted) { - var moduleInfo = GetModule(moduleId, tabId, true); + var moduleInfo = this.GetModule(moduleId, tabId, true); var userInfo = UserController.Instance.GetCurrentUserInfo(); TabChangeTracker.Instance.TrackModuleModification(moduleInfo, Null.NullInteger, userInfo.UserID); @@ -2201,17 +2421,18 @@ public void UpdateTabModuleOrder(int tabId) { CBO.CloseDataReader(dr, true); } - //clear module cache - ClearCache(tabId); + + // clear module cache + this.ClearCache(tabId); } /// - /// Adds or updates a module's setting value + /// Adds or updates a module's setting value. /// - /// ID of the tabmodule, the setting belongs to - /// name of the setting property + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. /// value of the setting (String). - /// empty SettingValue will relove the setting + /// empty SettingValue will relove the setting. public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) { IDataReader dr = dataProvider.GetTabModuleSetting(tabModuleId, settingName); @@ -2223,18 +2444,20 @@ public void UpdateTabModuleSetting(int tabModuleId, string settingName, string s if (dr.GetString(1) != settingValue) { dataProvider.UpdateTabModuleSetting(tabModuleId, settingName, settingValue, currentUser.UserID); - EventLogController.AddSettingLog(EventLogController.EventLogType.MODULE_SETTING_UPDATED, - "TabModuleId", tabModuleId, settingName, settingValue, - currentUser.UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.MODULE_SETTING_UPDATED, + "TabModuleId", tabModuleId, settingName, settingValue, + currentUser.UserID); UpdateTabModuleVersion(tabModuleId); } } else { dataProvider.UpdateTabModuleSetting(tabModuleId, settingName, settingValue, currentUser.UserID); - EventLogController.AddSettingLog(EventLogController.EventLogType.TABMODULE_SETTING_CREATED, - "TabModuleId", tabModuleId, settingName, settingValue, - currentUser.UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.TABMODULE_SETTING_CREATED, + "TabModuleId", tabModuleId, settingName, settingValue, + currentUser.UserID); UpdateTabModuleVersion(tabModuleId); } } @@ -2244,9 +2467,10 @@ public void UpdateTabModuleSetting(int tabModuleId, string settingName, string s } finally { - //Ensure DataReader is closed + // Ensure DataReader is closed CBO.CloseDataReader(dr, true); } + ClearTabModuleSettingsCache(tabModuleId, settingName); } @@ -2265,185 +2489,20 @@ public void UpdateTranslationStatus(ModuleInfo localizedModule, bool isTranslate { localizedModule.LocalizedVersionGuid = Guid.NewGuid(); } - DataProvider.Instance().UpdateTabModuleTranslationStatus(localizedModule.TabModuleID, localizedModule.LocalizedVersionGuid, UserController.Instance.GetCurrentUserInfo().UserID); - - //Clear Tab Caches - ClearCache(localizedModule.TabID); - } - - #endregion - - #region Static Methods - - /// - /// Deserializes the module. - /// - /// The node module. - /// ModuleInfo of current module - /// The portal id. - /// The tab id. - public static void DeserializeModule(XmlNode nodeModule, ModuleInfo module, int portalId, int tabId) - { - var moduleDefinition = GetModuleDefinition(nodeModule); - - // Create dummy pane node for private DeserializeModule method - var docPane = new XmlDocument { XmlResolver = null }; - docPane.LoadXml(String.Format("{0}", module.PaneName)); - - // Create ModuleInfo of Xml - ModuleInfo sourceModule = DeserializeModule(nodeModule, docPane.DocumentElement, portalId, tabId, moduleDefinition.ModuleDefID); - - // Copy properties from sourceModule to given (actual) module - module.ModuleTitle = sourceModule.ModuleTitle; - module.ModuleDefID = sourceModule.ModuleDefID; - module.CacheTime = sourceModule.CacheTime; - module.CacheMethod = sourceModule.CacheMethod; - module.Alignment = sourceModule.Alignment; - module.IconFile = sourceModule.IconFile; - module.AllTabs = sourceModule.AllTabs; - module.Visibility = sourceModule.Visibility; - module.Color = sourceModule.Color; - module.Border = sourceModule.Border; - module.Header = sourceModule.Header; - module.Footer = sourceModule.Footer; - module.InheritViewPermissions = sourceModule.InheritViewPermissions; - module.IsShareable = sourceModule.IsShareable; - module.IsShareableViewOnly = sourceModule.IsShareableViewOnly; - module.StartDate = sourceModule.StartDate; - module.EndDate = sourceModule.EndDate; - module.ContainerSrc = sourceModule.ContainerSrc; - module.DisplayTitle = sourceModule.DisplayTitle; - module.DisplayPrint = sourceModule.DisplayPrint; - module.DisplaySyndicate = sourceModule.DisplaySyndicate; - module.IsWebSlice = sourceModule.IsWebSlice; - - if (module.IsWebSlice) - { - module.WebSliceTitle = sourceModule.WebSliceTitle; - module.WebSliceExpiryDate = sourceModule.WebSliceExpiryDate; - module.WebSliceTTL = sourceModule.WebSliceTTL; - } - - // DNN-24983 get culture from page - var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); - if (tabInfo != null) - { - module.CultureCode = tabInfo.CultureCode; - } - - // save changes - Instance.UpdateModule(module); - - //deserialize Module's settings - XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); - DeserializeModuleSettings(nodeModuleSettings, module); - - XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); - DeserializeTabModuleSettings(nodeTabModuleSettings, module); - - //deserialize Content (if included) - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content"))) - { - GetModuleContent(nodeModule, module.ModuleID, tabId, portalId); - } - - //deserialize Permissions - XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); - DeserializeModulePermissions(nodeModulePermissions, portalId, module); - - //Persist the permissions to the Data base - ModulePermissionController.SaveModulePermissions(module); - } - - /// - /// Deserializes the module. - /// - /// The node module. - /// The node pane. - /// The portal id. - /// The tab id. - /// The merge tabs. - /// The modules. - public static void DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules) - { - var moduleDefinition = GetModuleDefinition(nodeModule); - //will be instance or module? - int templateModuleID = XmlUtils.GetNodeValueInt(nodeModule, "moduleID"); - bool isInstance = CheckIsInstance(templateModuleID, hModules); - if (moduleDefinition != null) - { - //If Mode is Merge Check if Module exists - if (!FindModule(nodeModule, tabId, mergeTabs)) - { - ModuleInfo module = DeserializeModule(nodeModule, nodePane, portalId, tabId, moduleDefinition.ModuleDefID); - //if the module is marked as show on all tabs, then check whether the module is exist in current website and it also - //still marked as shown on all tabs, this action will make sure there is no duplicate modules created on new tab. - if (module.AllTabs) - { - var existModule = Instance.GetModule(templateModuleID, Null.NullInteger, false); - if (existModule != null && !existModule.IsDeleted && existModule.AllTabs && existModule.PortalID == portalId) - { - return; - } - } - //deserialize Module's settings - XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); - DeserializeModuleSettings(nodeModuleSettings, module); - XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); - DeserializeTabModuleSettings(nodeTabModuleSettings, module); - - // DNN-24983 get culture from page - var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); - if (tabInfo != null) - { - module.CultureCode = tabInfo.CultureCode; - } - - int intModuleId; - if (!isInstance) - { - //Add new module - intModuleId = Instance.AddModule(module); - if (templateModuleID > 0) - { - hModules.Add(templateModuleID, intModuleId); - } - } - else - { - //Add instance - module.ModuleID = Convert.ToInt32(hModules[templateModuleID]); - intModuleId = Instance.AddModule(module); - } - - // save localization info - string oldGuid = XmlUtils.GetNodeValue(nodeModule, "uniqueId"); - if (!ParsedLocalizedModuleGuid.ContainsKey(oldGuid)) - ParsedLocalizedModuleGuid.Add(oldGuid, module.UniqueId.ToString()); - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content")) && !isInstance) - { - GetModuleContent(nodeModule, intModuleId, tabId, portalId); - } - //Process permissions only once - if (!isInstance && portalId != Null.NullInteger) - { - XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); - DeserializeModulePermissions(nodeModulePermissions, portalId, module); + DataProvider.Instance().UpdateTabModuleTranslationStatus(localizedModule.TabModuleID, localizedModule.LocalizedVersionGuid, UserController.Instance.GetCurrentUserInfo().UserID); - //Persist the permissions to the Data base - ModulePermissionController.SaveModulePermissions(module); - } - } - } + // Clear Tab Caches + this.ClearCache(localizedModule.TabID); } /// - /// SerializeModule + /// SerializeModule. /// - /// The Xml Document to use for the Module - /// The ModuleInfo object to serialize + /// The Xml Document to use for the Module. + /// The ModuleInfo object to serialize. /// A flak that determines whether the content of the module is serialised. + /// public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo module, bool includeContent) { var serializer = new XmlSerializer(typeof(ModuleInfo)); @@ -2460,7 +2519,7 @@ public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo module, moduleNode.Attributes.Remove(moduleNode.Attributes["xmlns:xsi"]); } - //remove unwanted elements + // remove unwanted elements moduleNode.RemoveChild(moduleNode.SelectSingleNode("portalid")); moduleNode.RemoveChild(moduleNode.SelectSingleNode("tabid")); moduleNode.RemoveChild(moduleNode.SelectSingleNode("tabmoduleid")); @@ -2472,12 +2531,13 @@ public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo module, moduleNode.RemoveChild(moduleNode.SelectSingleNode("content")); // support for localized templates - //moduleNode.RemoveChild(moduleNode.SelectSingleNode("uniqueId")); - //moduleNode.RemoveChild(moduleNode.SelectSingleNode("defaultLanguageGuid")); - //moduleNode.RemoveChild(moduleNode.SelectSingleNode("cultureCode")); - + // moduleNode.RemoveChild(moduleNode.SelectSingleNode("uniqueId")); + // moduleNode.RemoveChild(moduleNode.SelectSingleNode("defaultLanguageGuid")); + // moduleNode.RemoveChild(moduleNode.SelectSingleNode("cultureCode")); if (Null.IsNull(module.DefaultLanguageGuid)) + { moduleNode.RemoveChild(moduleNode.SelectSingleNode("defaultLanguageGuid")); + } var xmlNodeList = moduleNode.SelectNodes("modulepermissions/permission"); if (xmlNodeList != null) @@ -2493,16 +2553,19 @@ public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo module, nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); } } + if (includeContent) { AddContent(moduleNode, module); } - //serialize ModuleSettings and TabModuleSettings + + // serialize ModuleSettings and TabModuleSettings XmlUtils.SerializeHashtable(module.ModuleSettings, xmlModule, moduleNode, "modulesetting", "settingname", "settingvalue"); XmlUtils.SerializeHashtable(module.TabModuleSettings, xmlModule, moduleNode, "tabmodulesetting", "settingname", "settingvalue"); // ReSharper restore AssignNullToNotNullAttribute } + XmlNode newNode = xmlModule.CreateElement("definition"); ModuleDefinitionInfo objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(module.ModuleDefID); newNode.InnerText = DesktopModuleController.GetDesktopModule(objModuleDef.DesktopModuleID, module.PortalID).ModuleName; @@ -2510,13 +2573,15 @@ public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo module, { moduleNode.AppendChild(newNode); } - //Add Module Definition Info + + // Add Module Definition Info XmlNode definitionNode = xmlModule.CreateElement("moduledefinition"); definitionNode.InnerText = objModuleDef.FriendlyName; if (moduleNode != null) { moduleNode.AppendChild(definitionNode); } + return moduleNode; } @@ -2548,23 +2613,21 @@ public static void SynchronizeModule(int moduleID) } } - //Synchronize module is called when a module needs to indicate that the content - //has changed and the cache's should be refreshed. So we can update the Version - //and also the LastContentModificationDate + // Synchronize module is called when a module needs to indicate that the content + // has changed and the cache's should be refreshed. So we can update the Version + // and also the LastContentModificationDate UpdateTabModuleVersion(module.TabModuleID); dataProvider.UpdateModuleLastContentModifiedOnDate(module.ModuleID); - //We should also indicate that the Transalation Status has changed + // We should also indicate that the Transalation Status has changed if (PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", module.PortalID, false)) { Instance.UpdateTranslationStatus(module, false); } + // and clear the cache Instance.ClearCache(module.TabID); } } - - - #endregion } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs index 16dd610eec0..b2437dedddd 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs @@ -1,49 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Linq; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.ModuleCache; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.ModuleCache; + using DotNetNuke.Services.Tokens; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : ModuleInfo + /// Class : ModuleInfo /// ----------------------------------------------------------------------------- /// - /// ModuleInfo provides the Entity Layer for Modules + /// ModuleInfo provides the Entity Layer for Modules. /// /// ----------------------------------------------------------------------------- [XmlRoot("module", IsNullable = false)] [Serializable] public class ModuleInfo : ContentItem, IPropertyAccess { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ModuleInfo)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleInfo)); private string _authorizedEditRoles; private string _authorizedViewRoles; private string _cultureCode; @@ -58,41 +53,40 @@ public class ModuleInfo : ContentItem, IPropertyAccess private TabInfo _parentTab; private Hashtable _moduleSettings; private Hashtable _tabModuleSettings; - - + public ModuleInfo() { - //initialize the properties that can be null - //in the database - PortalID = Null.NullInteger; - OwnerPortalID = Null.NullInteger; - TabModuleID = Null.NullInteger; - DesktopModuleID = Null.NullInteger; - ModuleDefID = Null.NullInteger; - ModuleTitle = Null.NullString; - ModuleVersion = Null.NullInteger; - _authorizedEditRoles = Null.NullString; - _authorizedViewRoles = Null.NullString; - Alignment = Null.NullString; - Color = Null.NullString; - Border = Null.NullString; - IconFile = Null.NullString; - Header = Null.NullString; - Footer = Null.NullString; - StartDate = Null.NullDate; - EndDate = Null.NullDate; - ContainerSrc = Null.NullString; - DisplayTitle = true; - DisplayPrint = true; - DisplaySyndicate = false; - - //Guid, Version Guid, and Localized Version Guid should be initialised to a new value - UniqueId = Guid.NewGuid(); - VersionGuid = Guid.NewGuid(); - _localizedVersionGuid = Guid.NewGuid(); - - //Default Language Guid should be initialised to a null Guid - _defaultLanguageGuid = Null.NullGuid; + // initialize the properties that can be null + // in the database + this.PortalID = Null.NullInteger; + this.OwnerPortalID = Null.NullInteger; + this.TabModuleID = Null.NullInteger; + this.DesktopModuleID = Null.NullInteger; + this.ModuleDefID = Null.NullInteger; + this.ModuleTitle = Null.NullString; + this.ModuleVersion = Null.NullInteger; + this._authorizedEditRoles = Null.NullString; + this._authorizedViewRoles = Null.NullString; + this.Alignment = Null.NullString; + this.Color = Null.NullString; + this.Border = Null.NullString; + this.IconFile = Null.NullString; + this.Header = Null.NullString; + this.Footer = Null.NullString; + this.StartDate = Null.NullDate; + this.EndDate = Null.NullDate; + this.ContainerSrc = Null.NullString; + this.DisplayTitle = true; + this.DisplayPrint = true; + this.DisplaySyndicate = false; + + // Guid, Version Guid, and Localized Version Guid should be initialised to a new value + this.UniqueId = Guid.NewGuid(); + this.VersionGuid = Guid.NewGuid(); + this._localizedVersionGuid = Guid.NewGuid(); + + // Default Language Guid should be initialised to a null Guid + this._defaultLanguageGuid = Null.NullGuid; } [XmlElement("alignment")] @@ -124,26 +118,27 @@ public ModuleInfo() /// ----------------------------------------------------------------------------- /// - /// Gets the Associated Desktop Module + /// Gets the Associated Desktop Module. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public DesktopModuleInfo DesktopModule { - get { - return _desktopModule ?? - (_desktopModule = DesktopModuleID > Null.NullInteger - ? DesktopModuleController.GetDesktopModule(DesktopModuleID, PortalID) + get + { + return this._desktopModule ?? + (this._desktopModule = this.DesktopModuleID > Null.NullInteger + ? DesktopModuleController.GetDesktopModule(this.DesktopModuleID, this.PortalID) : new DesktopModuleInfo()); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ID of the Associated Desktop Module + /// Gets or sets and sets the ID of the Associated Desktop Module. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public int DesktopModuleID { get; set; } @@ -171,14 +166,14 @@ public bool HideAdminBorder { get { - object setting = TabModuleSettings["hideadminborder"]; + object setting = this.TabModuleSettings["hideadminborder"]; if (setting == null || string.IsNullOrEmpty(setting.ToString())) { return false; } bool val; - Boolean.TryParse(setting.ToString(), out val); + bool.TryParse(setting.ToString(), out val); return val; } } @@ -201,7 +196,7 @@ public bool HideAdminBorder [XmlIgnore] public bool IsShared { - get { return OwnerPortalID != PortalID; } + get { return this.OwnerPortalID != this.PortalID; } } [XmlIgnore] @@ -215,10 +210,11 @@ public bool IsShared public ModuleControlInfo ModuleControl { - get { - return _moduleControl ?? - (_moduleControl = ModuleControlId > Null.NullInteger - ? ModuleControlController.GetModuleControl(ModuleControlId) + get + { + return this._moduleControl ?? + (this._moduleControl = this.ModuleControlId > Null.NullInteger + ? ModuleControlController.GetModuleControl(this.ModuleControlId) : new ModuleControlInfo()); } } @@ -228,26 +224,27 @@ public ModuleControlInfo ModuleControl /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ID of the Associated Module Definition + /// Gets or sets and sets the ID of the Associated Module Definition. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public int ModuleDefID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Associated Module Definition + /// Gets the Associated Module Definition. /// - /// A ModuleDefinitionInfo + /// A ModuleDefinitionInfo. /// ----------------------------------------------------------------------------- [XmlIgnore] public ModuleDefinitionInfo ModuleDefinition { - get { - return _moduleDefinition ?? - (_moduleDefinition = ModuleDefID > Null.NullInteger - ? ModuleDefinitionController.GetModuleDefinitionByID(ModuleDefID) + get + { + return this._moduleDefinition ?? + (this._moduleDefinition = this.ModuleDefID > Null.NullInteger + ? ModuleDefinitionController.GetModuleDefinitionByID(this.ModuleDefID) : new ModuleDefinitionInfo()); } } @@ -256,25 +253,27 @@ public ModuleDefinitionInfo ModuleDefinition public int ModuleOrder { get; set; } /// - /// Get the ModulePermissions for the Module DO NOT USE THE SETTTER + /// Gets or sets get the ModulePermissions for the Module DO NOT USE THE SETTTER. /// /// Since 5.0 the setter has been obsolete, directly setting the ModulePermissionCollection is likely an error, change the contenst of the collection instead. /// The setter still exists to preserve binary compatibility without the obsolete attribute since c# will not allow only a setter to be obsolete. /// /// - [XmlArray("modulepermissions"), XmlArrayItem("permission")] + [XmlArray("modulepermissions")] + [XmlArrayItem("permission")] public ModulePermissionCollection ModulePermissions { get { - return _modulePermissions ?? - (_modulePermissions = ModuleID > 0 - ? new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(ModuleID, TabID)) + return this._modulePermissions ?? + (this._modulePermissions = this.ModuleID > 0 + ? new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(this.ModuleID, this.TabID)) : new ModulePermissionCollection()); } + set { - _modulePermissions = value; + this._modulePermissions = value; } } @@ -283,18 +282,19 @@ public Hashtable ModuleSettings { get { - if (_moduleSettings == null) + if (this._moduleSettings == null) { - if (ModuleID == Null.NullInteger) + if (this.ModuleID == Null.NullInteger) { - _moduleSettings = new Hashtable(); + this._moduleSettings = new Hashtable(); } else { - _moduleSettings = new ModuleController().GetModuleSettings(ModuleID, TabID); + this._moduleSettings = new ModuleController().GetModuleSettings(this.ModuleID, this.TabID); } } - return _moduleSettings; + + return this._moduleSettings; } } @@ -330,19 +330,19 @@ public Hashtable TabModuleSettings { get { - if (_tabModuleSettings == null) + if (this._tabModuleSettings == null) { - if (TabModuleID == Null.NullInteger) + if (this.TabModuleID == Null.NullInteger) { - _tabModuleSettings = new Hashtable(); + this._tabModuleSettings = new Hashtable(); } else { - _tabModuleSettings = new ModuleController().GetTabModuleSettings(TabModuleID, TabID); + this._tabModuleSettings = new ModuleController().GetTabModuleSettings(this.TabModuleID, this.TabID); } } - return _tabModuleSettings; + return this._tabModuleSettings; } } @@ -362,20 +362,19 @@ public Hashtable TabModuleSettings public string WebSliceTitle { get; set; } [XmlElement("webslicettl")] - public int WebSliceTTL { get; set; } - - #region Localization Properties - + public int WebSliceTTL { get; set; } + [XmlElement("cultureCode")] public string CultureCode { get { - return _cultureCode; + return this._cultureCode; } + set { - _cultureCode = value; + this._cultureCode = value; } } @@ -384,11 +383,12 @@ public Guid DefaultLanguageGuid { get { - return _defaultLanguageGuid; + return this._defaultLanguageGuid; } + set { - _defaultLanguageGuid = value; + this._defaultLanguageGuid = value; } } @@ -397,12 +397,13 @@ public ModuleInfo DefaultLanguageModule { get { - if (_defaultLanguageModule == null && (!DefaultLanguageGuid.Equals(Null.NullGuid)) && ParentTab != null && ParentTab.DefaultLanguageTab != null && - ParentTab.DefaultLanguageTab.ChildModules != null) + if (this._defaultLanguageModule == null && (!this.DefaultLanguageGuid.Equals(Null.NullGuid)) && this.ParentTab != null && this.ParentTab.DefaultLanguageTab != null && + this.ParentTab.DefaultLanguageTab.ChildModules != null) { - _defaultLanguageModule = (from kvp in ParentTab.DefaultLanguageTab.ChildModules where kvp.Value.UniqueId == DefaultLanguageGuid select kvp.Value).SingleOrDefault(); + this._defaultLanguageModule = (from kvp in this.ParentTab.DefaultLanguageTab.ChildModules where kvp.Value.UniqueId == this.DefaultLanguageGuid select kvp.Value).SingleOrDefault(); } - return _defaultLanguageModule; + + return this._defaultLanguageModule; } } @@ -410,7 +411,7 @@ public bool IsDefaultLanguage { get { - return (DefaultLanguageGuid == Null.NullGuid); + return this.DefaultLanguageGuid == Null.NullGuid; } } @@ -419,11 +420,12 @@ public bool IsLocalized get { bool isLocalized = true; - if (DefaultLanguageModule != null) + if (this.DefaultLanguageModule != null) { - //Child language - isLocalized = ModuleID != DefaultLanguageModule.ModuleID; + // Child language + isLocalized = this.ModuleID != this.DefaultLanguageModule.ModuleID; } + return isLocalized; } } @@ -432,7 +434,7 @@ public bool IsNeutralCulture { get { - return string.IsNullOrEmpty(CultureCode); + return string.IsNullOrEmpty(this.CultureCode); } } @@ -442,11 +444,12 @@ public bool IsTranslated get { bool isTranslated = true; - if (DefaultLanguageModule != null) + if (this.DefaultLanguageModule != null) { - //Child language - isTranslated = (LocalizedVersionGuid == DefaultLanguageModule.LocalizedVersionGuid); + // Child language + isTranslated = this.LocalizedVersionGuid == this.DefaultLanguageModule.LocalizedVersionGuid; } + return isTranslated; } } @@ -456,23 +459,24 @@ public Dictionary LocalizedModules { get { - if (_localizedModules == null && (DefaultLanguageGuid.Equals(Null.NullGuid)) && ParentTab != null && ParentTab.LocalizedTabs != null) + if (this._localizedModules == null && this.DefaultLanguageGuid.Equals(Null.NullGuid) && this.ParentTab != null && this.ParentTab.LocalizedTabs != null) { - //Cycle through all localized tabs looking for this module - _localizedModules = new Dictionary(); - foreach (TabInfo t in ParentTab.LocalizedTabs.Values) + // Cycle through all localized tabs looking for this module + this._localizedModules = new Dictionary(); + foreach (TabInfo t in this.ParentTab.LocalizedTabs.Values) { foreach (ModuleInfo m in t.ChildModules.Values) { ModuleInfo tempModuleInfo; - if (m.DefaultLanguageGuid == UniqueId && !m.IsDeleted && !_localizedModules.TryGetValue(m.CultureCode, out tempModuleInfo)) + if (m.DefaultLanguageGuid == this.UniqueId && !m.IsDeleted && !this._localizedModules.TryGetValue(m.CultureCode, out tempModuleInfo)) { - _localizedModules.Add(m.CultureCode, m); + this._localizedModules.Add(m.CultureCode, m); } } } } - return _localizedModules; + + return this._localizedModules; } } @@ -481,161 +485,161 @@ public Guid LocalizedVersionGuid { get { - return _localizedVersionGuid; + return this._localizedVersionGuid; } + set { - _localizedVersionGuid = value; + this._localizedVersionGuid = value; } - } - - #endregion - - #region Tab Properties - + } + public TabInfo ParentTab { get { - if (_parentTab == null) + if (this._parentTab == null) { - if (PortalID == Null.NullInteger || string.IsNullOrEmpty(CultureCode)) + if (this.PortalID == Null.NullInteger || string.IsNullOrEmpty(this.CultureCode)) { - _parentTab = TabController.Instance.GetTab(TabID, PortalID, false); + this._parentTab = TabController.Instance.GetTab(this.TabID, this.PortalID, false); } else { - Locale locale = LocaleController.Instance.GetLocale(CultureCode); - _parentTab = TabController.Instance.GetTabByCulture(TabID, PortalID, locale); + Locale locale = LocaleController.Instance.GetLocale(this.CultureCode); + this._parentTab = TabController.Instance.GetTabByCulture(this.TabID, this.PortalID, locale); } } - return _parentTab; + + return this._parentTab; } - } - - #endregion - - #region IHydratable Members + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public override int KeyID + { + get + { + return this.ModuleID; + } + + set + { + this.ModuleID = value; + } + } + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + /// ----------------------------------------------------------------------------- /// - /// Fills a ModuleInfo from a Data Reader + /// Fills a ModuleInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- public override void Fill(IDataReader dr) { - //Call the base classes fill method to populate base class properties - base.FillInternal(dr); - - UniqueId = Null.SetNullGuid(dr["UniqueId"]); - VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); - DefaultLanguageGuid = Null.SetNullGuid(dr["DefaultLanguageGuid"]); - LocalizedVersionGuid = Null.SetNullGuid(dr["LocalizedVersionGuid"]); - CultureCode = Null.SetNullString(dr["CultureCode"]); - - PortalID = Null.SetNullInteger(dr["PortalID"]); - if (dr.GetSchemaTable().Select("ColumnName = 'OwnerPortalID'").Length > 0) - { - OwnerPortalID = Null.SetNullInteger(dr["OwnerPortalID"]); - } - - ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); - ModuleTitle = Null.SetNullString(dr["ModuleTitle"]); - AllTabs = Null.SetNullBoolean(dr["AllTabs"]); - IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); - InheritViewPermissions = Null.SetNullBoolean(dr["InheritViewPermissions"]); - - if (dr.GetSchemaTable().Select("ColumnName = 'IsShareable'").Length > 0) - { - IsShareable = Null.SetNullBoolean(dr["IsShareable"]); - } - - if (dr.GetSchemaTable().Select("ColumnName = 'IsShareableViewOnly'").Length > 0) - { - IsShareableViewOnly = Null.SetNullBoolean(dr["IsShareableViewOnly"]); - } - - Header = Null.SetNullString(dr["Header"]); - Footer = Null.SetNullString(dr["Footer"]); - StartDate = Null.SetNullDateTime(dr["StartDate"]); - EndDate = Null.SetNullDateTime(dr["EndDate"]); - LastContentModifiedOnDate = Null.SetNullDateTime(dr["LastContentModifiedOnDate"]); + // Call the base classes fill method to populate base class properties + this.FillInternal(dr); + + this.UniqueId = Null.SetNullGuid(dr["UniqueId"]); + this.VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); + this.DefaultLanguageGuid = Null.SetNullGuid(dr["DefaultLanguageGuid"]); + this.LocalizedVersionGuid = Null.SetNullGuid(dr["LocalizedVersionGuid"]); + this.CultureCode = Null.SetNullString(dr["CultureCode"]); + + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + if (dr.GetSchemaTable().Select("ColumnName = 'OwnerPortalID'").Length > 0) + { + this.OwnerPortalID = Null.SetNullInteger(dr["OwnerPortalID"]); + } + + this.ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); + this.ModuleTitle = Null.SetNullString(dr["ModuleTitle"]); + this.AllTabs = Null.SetNullBoolean(dr["AllTabs"]); + this.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); + this.InheritViewPermissions = Null.SetNullBoolean(dr["InheritViewPermissions"]); + + if (dr.GetSchemaTable().Select("ColumnName = 'IsShareable'").Length > 0) + { + this.IsShareable = Null.SetNullBoolean(dr["IsShareable"]); + } + + if (dr.GetSchemaTable().Select("ColumnName = 'IsShareableViewOnly'").Length > 0) + { + this.IsShareableViewOnly = Null.SetNullBoolean(dr["IsShareableViewOnly"]); + } + + this.Header = Null.SetNullString(dr["Header"]); + this.Footer = Null.SetNullString(dr["Footer"]); + this.StartDate = Null.SetNullDateTime(dr["StartDate"]); + this.EndDate = Null.SetNullDateTime(dr["EndDate"]); + this.LastContentModifiedOnDate = Null.SetNullDateTime(dr["LastContentModifiedOnDate"]); try { - TabModuleID = Null.SetNullInteger(dr["TabModuleID"]); - ModuleOrder = Null.SetNullInteger(dr["ModuleOrder"]); - PaneName = Null.SetNullString(dr["PaneName"]); - CacheTime = Null.SetNullInteger(dr["CacheTime"]); - CacheMethod = Null.SetNullString(dr["CacheMethod"]); - Alignment = Null.SetNullString(dr["Alignment"]); - Color = Null.SetNullString(dr["Color"]); - Border = Null.SetNullString(dr["Border"]); - IconFile = Null.SetNullString(dr["IconFile"]); + this.TabModuleID = Null.SetNullInteger(dr["TabModuleID"]); + this.ModuleOrder = Null.SetNullInteger(dr["ModuleOrder"]); + this.PaneName = Null.SetNullString(dr["PaneName"]); + this.CacheTime = Null.SetNullInteger(dr["CacheTime"]); + this.CacheMethod = Null.SetNullString(dr["CacheMethod"]); + this.Alignment = Null.SetNullString(dr["Alignment"]); + this.Color = Null.SetNullString(dr["Color"]); + this.Border = Null.SetNullString(dr["Border"]); + this.IconFile = Null.SetNullString(dr["IconFile"]); int visible = Null.SetNullInteger(dr["Visibility"]); if (visible == Null.NullInteger) { - Visibility = VisibilityState.Maximized; + this.Visibility = VisibilityState.Maximized; } else { switch (visible) { case 0: - Visibility = VisibilityState.Maximized; + this.Visibility = VisibilityState.Maximized; break; case 1: - Visibility = VisibilityState.Minimized; + this.Visibility = VisibilityState.Minimized; break; case 2: - Visibility = VisibilityState.None; + this.Visibility = VisibilityState.None; break; } } - ContainerSrc = Null.SetNullString(dr["ContainerSrc"]); - DisplayTitle = Null.SetNullBoolean(dr["DisplayTitle"]); - DisplayPrint = Null.SetNullBoolean(dr["DisplayPrint"]); - DisplaySyndicate = Null.SetNullBoolean(dr["DisplaySyndicate"]); - IsWebSlice = Null.SetNullBoolean(dr["IsWebSlice"]); - if (IsWebSlice) + + this.ContainerSrc = Null.SetNullString(dr["ContainerSrc"]); + this.DisplayTitle = Null.SetNullBoolean(dr["DisplayTitle"]); + this.DisplayPrint = Null.SetNullBoolean(dr["DisplayPrint"]); + this.DisplaySyndicate = Null.SetNullBoolean(dr["DisplaySyndicate"]); + this.IsWebSlice = Null.SetNullBoolean(dr["IsWebSlice"]); + if (this.IsWebSlice) { - WebSliceTitle = Null.SetNullString(dr["WebSliceTitle"]); - WebSliceExpiryDate = Null.SetNullDateTime(dr["WebSliceExpiryDate"]); - WebSliceTTL = Null.SetNullInteger(dr["WebSliceTTL"]); + this.WebSliceTitle = Null.SetNullString(dr["WebSliceTitle"]); + this.WebSliceExpiryDate = Null.SetNullDateTime(dr["WebSliceExpiryDate"]); + this.WebSliceTTL = Null.SetNullInteger(dr["WebSliceTTL"]); } - DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); - ModuleControlId = Null.SetNullInteger(dr["ModuleControlID"]); + + this.DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); + this.ModuleControlId = Null.SetNullInteger(dr["ModuleControlID"]); } catch (Exception exc) { Logger.Error(exc); } } - - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public override int KeyID - { - get - { - return ModuleID; - } - set - { - ModuleID = value; - } - } - - #endregion - - #region IPropertyAccess Members - + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { string outputFormat = string.Empty; @@ -643,11 +647,13 @@ public string GetProperty(string propertyName, string format, CultureInfo format { outputFormat = "g"; } + if (currentScope == Scope.NoSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } + propertyNotFound = true; string result = string.Empty; bool isPublic = true; @@ -655,368 +661,360 @@ public string GetProperty(string propertyName, string format, CultureInfo format { case "portalid": propertyNotFound = false; - result = (PortalID.ToString(outputFormat, formatProvider)); + result = this.PortalID.ToString(outputFormat, formatProvider); break; case "displayportalid": propertyNotFound = false; - result = (OwnerPortalID.ToString(outputFormat, formatProvider)); + result = this.OwnerPortalID.ToString(outputFormat, formatProvider); break; case "tabid": propertyNotFound = false; - result = (TabID.ToString(outputFormat, formatProvider)); + result = this.TabID.ToString(outputFormat, formatProvider); break; case "tabmoduleid": propertyNotFound = false; - result = (TabModuleID.ToString(outputFormat, formatProvider)); + result = this.TabModuleID.ToString(outputFormat, formatProvider); break; case "moduleid": propertyNotFound = false; - result = (ModuleID.ToString(outputFormat, formatProvider)); + result = this.ModuleID.ToString(outputFormat, formatProvider); break; case "moduledefid": isPublic = false; propertyNotFound = false; - result = (ModuleDefID.ToString(outputFormat, formatProvider)); + result = this.ModuleDefID.ToString(outputFormat, formatProvider); break; case "moduleorder": isPublic = false; propertyNotFound = false; - result = (ModuleOrder.ToString(outputFormat, formatProvider)); + result = this.ModuleOrder.ToString(outputFormat, formatProvider); break; case "panename": propertyNotFound = false; - result = PropertyAccess.FormatString(PaneName, format); + result = PropertyAccess.FormatString(this.PaneName, format); break; case "moduletitle": propertyNotFound = false; - result = PropertyAccess.FormatString(ModuleTitle, format); + result = PropertyAccess.FormatString(this.ModuleTitle, format); break; case "cachetime": isPublic = false; propertyNotFound = false; - result = (CacheTime.ToString(outputFormat, formatProvider)); + result = this.CacheTime.ToString(outputFormat, formatProvider); break; case "cachemethod": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(CacheMethod, format); + result = PropertyAccess.FormatString(this.CacheMethod, format); break; case "alignment": propertyNotFound = false; - result = PropertyAccess.FormatString(Alignment, format); + result = PropertyAccess.FormatString(this.Alignment, format); break; case "color": propertyNotFound = false; - result = PropertyAccess.FormatString(Color, format); + result = PropertyAccess.FormatString(this.Color, format); break; case "border": propertyNotFound = false; - result = PropertyAccess.FormatString(Border, format); + result = PropertyAccess.FormatString(this.Border, format); break; case "iconfile": propertyNotFound = false; - result = PropertyAccess.FormatString(IconFile, format); + result = PropertyAccess.FormatString(this.IconFile, format); break; case "alltabs": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(AllTabs, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.AllTabs, formatProvider); break; case "isdeleted": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsDeleted, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsDeleted, formatProvider); break; case "header": propertyNotFound = false; - result = PropertyAccess.FormatString(Header, format); + result = PropertyAccess.FormatString(this.Header, format); break; case "footer": propertyNotFound = false; - result = PropertyAccess.FormatString(Footer, format); + result = PropertyAccess.FormatString(this.Footer, format); break; case "startdate": isPublic = false; propertyNotFound = false; - result = (StartDate.ToString(outputFormat, formatProvider)); + result = this.StartDate.ToString(outputFormat, formatProvider); break; case "enddate": isPublic = false; propertyNotFound = false; - result = (EndDate.ToString(outputFormat, formatProvider)); + result = this.EndDate.ToString(outputFormat, formatProvider); break; case "containersrc": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(ContainerSrc, format); + result = PropertyAccess.FormatString(this.ContainerSrc, format); break; case "displaytitle": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DisplayTitle, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DisplayTitle, formatProvider); break; case "displayprint": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DisplayPrint, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DisplayPrint, formatProvider); break; case "displaysyndicate": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DisplaySyndicate, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DisplaySyndicate, formatProvider); break; case "iswebslice": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsWebSlice, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsWebSlice, formatProvider); break; case "webslicetitle": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(WebSliceTitle, format); + result = PropertyAccess.FormatString(this.WebSliceTitle, format); break; case "websliceexpirydate": isPublic = false; propertyNotFound = false; - result = (WebSliceExpiryDate.ToString(outputFormat, formatProvider)); + result = this.WebSliceExpiryDate.ToString(outputFormat, formatProvider); break; case "webslicettl": isPublic = false; propertyNotFound = false; - result = (WebSliceTTL.ToString(outputFormat, formatProvider)); + result = this.WebSliceTTL.ToString(outputFormat, formatProvider); break; case "inheritviewpermissions": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(InheritViewPermissions, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.InheritViewPermissions, formatProvider); break; case "isshareable": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsShareable, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsShareable, formatProvider); break; case "isshareableviewonly": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsShareableViewOnly, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsShareableViewOnly, formatProvider); break; case "desktopmoduleid": isPublic = false; propertyNotFound = false; - result = (DesktopModuleID.ToString(outputFormat, formatProvider)); + result = this.DesktopModuleID.ToString(outputFormat, formatProvider); break; case "friendlyname": propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.FriendlyName, format); + result = PropertyAccess.FormatString(this.DesktopModule.FriendlyName, format); break; case "foldername": propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.FolderName, format); + result = PropertyAccess.FormatString(this.DesktopModule.FolderName, format); break; case "description": propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.Description, format); + result = PropertyAccess.FormatString(this.DesktopModule.Description, format); break; case "version": propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.Version, format); + result = PropertyAccess.FormatString(this.DesktopModule.Version, format); break; case "ispremium": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DesktopModule.IsPremium, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DesktopModule.IsPremium, formatProvider); break; case "isadmin": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DesktopModule.IsAdmin, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DesktopModule.IsAdmin, formatProvider); break; case "businesscontrollerclass": propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.BusinessControllerClass, format); + result = PropertyAccess.FormatString(this.DesktopModule.BusinessControllerClass, format); break; case "modulename": propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.ModuleName, format); + result = PropertyAccess.FormatString(this.DesktopModule.ModuleName, format); break; case "supportedfeatures": isPublic = false; propertyNotFound = false; - result = (DesktopModule.SupportedFeatures.ToString(outputFormat, formatProvider)); + result = this.DesktopModule.SupportedFeatures.ToString(outputFormat, formatProvider); break; case "compatibleversions": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.CompatibleVersions, format); + result = PropertyAccess.FormatString(this.DesktopModule.CompatibleVersions, format); break; case "dependencies": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.Dependencies, format); + result = PropertyAccess.FormatString(this.DesktopModule.Dependencies, format); break; case "permissions": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.Permissions, format); + result = PropertyAccess.FormatString(this.DesktopModule.Permissions, format); break; case "defaultcachetime": isPublic = false; propertyNotFound = false; - result = (ModuleDefinition.DefaultCacheTime.ToString(outputFormat, formatProvider)); + result = this.ModuleDefinition.DefaultCacheTime.ToString(outputFormat, formatProvider); break; case "modulecontrolid": isPublic = false; propertyNotFound = false; - result = (ModuleControlId.ToString(outputFormat, formatProvider)); + result = this.ModuleControlId.ToString(outputFormat, formatProvider); break; case "controlsrc": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(ModuleControl.ControlSrc, format); + result = PropertyAccess.FormatString(this.ModuleControl.ControlSrc, format); break; case "controltitle": propertyNotFound = false; - result = PropertyAccess.FormatString(ModuleControl.ControlTitle, format); + result = PropertyAccess.FormatString(this.ModuleControl.ControlTitle, format); break; case "helpurl": propertyNotFound = false; - result = PropertyAccess.FormatString(ModuleControl.HelpURL, format); + result = PropertyAccess.FormatString(this.ModuleControl.HelpURL, format); break; case "supportspartialrendering": propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(ModuleControl.SupportsPartialRendering, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.ModuleControl.SupportsPartialRendering, formatProvider); break; case "containerpath": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(ContainerPath, format); + result = PropertyAccess.FormatString(this.ContainerPath, format); break; case "panemoduleindex": isPublic = false; propertyNotFound = false; - result = (PaneModuleIndex.ToString(outputFormat, formatProvider)); + result = this.PaneModuleIndex.ToString(outputFormat, formatProvider); break; case "panemodulecount": isPublic = false; propertyNotFound = false; - result = (PaneModuleCount.ToString(outputFormat, formatProvider)); + result = this.PaneModuleCount.ToString(outputFormat, formatProvider); break; case "isdefaultmodule": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsDefaultModule, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsDefaultModule, formatProvider); break; case "allmodules": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(AllModules, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.AllModules, formatProvider); break; case "isportable": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DesktopModule.IsPortable, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DesktopModule.IsPortable, formatProvider); break; case "issearchable": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DesktopModule.IsSearchable, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DesktopModule.IsSearchable, formatProvider); break; case "isupgradeable": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DesktopModule.IsUpgradeable, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DesktopModule.IsUpgradeable, formatProvider); break; case "adminpage": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.AdminPage, format); + result = PropertyAccess.FormatString(this.DesktopModule.AdminPage, format); break; case "hostpage": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(DesktopModule.HostPage, format); + result = PropertyAccess.FormatString(this.DesktopModule.HostPage, format); break; } + if (!isPublic && currentScope != Scope.Debug) { propertyNotFound = true; result = PropertyAccess.ContentLocked; } + return result; } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - - #endregion - + public ModuleInfo Clone() { - var objModuleInfo = new ModuleInfo - { - PortalID = PortalID, - OwnerPortalID = OwnerPortalID, - TabID = TabID, - TabModuleID = TabModuleID, - ModuleID = ModuleID, - ModuleOrder = ModuleOrder, - PaneName = PaneName, - ModuleTitle = ModuleTitle, - CacheTime = CacheTime, - CacheMethod = CacheMethod, - Alignment = Alignment, - Color = Color, - Border = Border, - IconFile = IconFile, - AllTabs = AllTabs, - Visibility = Visibility, - IsDeleted = IsDeleted, - Header = Header, - Footer = Footer, - StartDate = StartDate, - EndDate = EndDate, - ContainerSrc = ContainerSrc, - DisplayTitle = DisplayTitle, - DisplayPrint = DisplayPrint, - DisplaySyndicate = DisplaySyndicate, - IsWebSlice = IsWebSlice, - WebSliceTitle = WebSliceTitle, - WebSliceExpiryDate = WebSliceExpiryDate, - WebSliceTTL = WebSliceTTL, - InheritViewPermissions = InheritViewPermissions, - IsShareable = IsShareable, - IsShareableViewOnly = IsShareableViewOnly, - DesktopModuleID = DesktopModuleID, - ModuleDefID = ModuleDefID, - ModuleControlId = ModuleControlId, - ContainerPath = ContainerPath, - PaneModuleIndex = PaneModuleIndex, - PaneModuleCount = PaneModuleCount, - IsDefaultModule = IsDefaultModule, - AllModules = AllModules, - UniqueId = Guid.NewGuid(), - VersionGuid = Guid.NewGuid(), - DefaultLanguageGuid = DefaultLanguageGuid, - LocalizedVersionGuid = LocalizedVersionGuid, - CultureCode = CultureCode - }; - - //localized properties - Clone(objModuleInfo, this); + var objModuleInfo = new ModuleInfo + { + PortalID = this.PortalID, + OwnerPortalID = this.OwnerPortalID, + TabID = this.TabID, + TabModuleID = this.TabModuleID, + ModuleID = this.ModuleID, + ModuleOrder = this.ModuleOrder, + PaneName = this.PaneName, + ModuleTitle = this.ModuleTitle, + CacheTime = this.CacheTime, + CacheMethod = this.CacheMethod, + Alignment = this.Alignment, + Color = this.Color, + Border = this.Border, + IconFile = this.IconFile, + AllTabs = this.AllTabs, + Visibility = this.Visibility, + IsDeleted = this.IsDeleted, + Header = this.Header, + Footer = this.Footer, + StartDate = this.StartDate, + EndDate = this.EndDate, + ContainerSrc = this.ContainerSrc, + DisplayTitle = this.DisplayTitle, + DisplayPrint = this.DisplayPrint, + DisplaySyndicate = this.DisplaySyndicate, + IsWebSlice = this.IsWebSlice, + WebSliceTitle = this.WebSliceTitle, + WebSliceExpiryDate = this.WebSliceExpiryDate, + WebSliceTTL = this.WebSliceTTL, + InheritViewPermissions = this.InheritViewPermissions, + IsShareable = this.IsShareable, + IsShareableViewOnly = this.IsShareableViewOnly, + DesktopModuleID = this.DesktopModuleID, + ModuleDefID = this.ModuleDefID, + ModuleControlId = this.ModuleControlId, + ContainerPath = this.ContainerPath, + PaneModuleIndex = this.PaneModuleIndex, + PaneModuleCount = this.PaneModuleCount, + IsDefaultModule = this.IsDefaultModule, + AllModules = this.AllModules, + UniqueId = Guid.NewGuid(), + VersionGuid = Guid.NewGuid(), + DefaultLanguageGuid = this.DefaultLanguageGuid, + LocalizedVersionGuid = this.LocalizedVersionGuid, + CultureCode = this.CultureCode, + }; + + // localized properties + this.Clone(objModuleInfo, this); return objModuleInfo; } public string GetEffectiveCacheMethod() { string effectiveCacheMethod; - if (!string.IsNullOrEmpty(CacheMethod)) + if (!string.IsNullOrEmpty(this.CacheMethod)) { - effectiveCacheMethod = CacheMethod; + effectiveCacheMethod = this.CacheMethod; } else if (!string.IsNullOrEmpty(Host.Host.ModuleCachingMethod)) { @@ -1027,66 +1025,68 @@ public string GetEffectiveCacheMethod() var defaultModuleCache = ComponentFactory.GetComponent(); effectiveCacheMethod = (from provider in ModuleCachingProvider.GetProviderList() where provider.Value.Equals(defaultModuleCache) select provider.Key).SingleOrDefault(); } + if (string.IsNullOrEmpty(effectiveCacheMethod)) { throw new InvalidOperationException(Localization.GetString("EXCEPTION_ModuleCacheMissing")); } + return effectiveCacheMethod; } public void Initialize(int portalId) { - PortalID = portalId; - OwnerPortalID = portalId; - ModuleDefID = Null.NullInteger; - ModuleOrder = Null.NullInteger; - PaneName = Null.NullString; - ModuleTitle = Null.NullString; - CacheTime = 0; - CacheMethod = Null.NullString; - Alignment = Null.NullString; - Color = Null.NullString; - Border = Null.NullString; - IconFile = Null.NullString; - AllTabs = Null.NullBoolean; - Visibility = VisibilityState.Maximized; - IsDeleted = Null.NullBoolean; - Header = Null.NullString; - Footer = Null.NullString; - StartDate = Null.NullDate; - EndDate = Null.NullDate; - DisplayTitle = true; - DisplayPrint = false; - DisplaySyndicate = Null.NullBoolean; - IsWebSlice = Null.NullBoolean; - WebSliceTitle = ""; - WebSliceExpiryDate = Null.NullDate; - WebSliceTTL = 0; - InheritViewPermissions = Null.NullBoolean; - IsShareable = true; - IsShareableViewOnly = true; - ContainerSrc = Null.NullString; - DesktopModuleID = Null.NullInteger; - ModuleControlId = Null.NullInteger; - ContainerPath = Null.NullString; - PaneModuleIndex = 0; - PaneModuleCount = 0; - IsDefaultModule = Null.NullBoolean; - AllModules = Null.NullBoolean; + this.PortalID = portalId; + this.OwnerPortalID = portalId; + this.ModuleDefID = Null.NullInteger; + this.ModuleOrder = Null.NullInteger; + this.PaneName = Null.NullString; + this.ModuleTitle = Null.NullString; + this.CacheTime = 0; + this.CacheMethod = Null.NullString; + this.Alignment = Null.NullString; + this.Color = Null.NullString; + this.Border = Null.NullString; + this.IconFile = Null.NullString; + this.AllTabs = Null.NullBoolean; + this.Visibility = VisibilityState.Maximized; + this.IsDeleted = Null.NullBoolean; + this.Header = Null.NullString; + this.Footer = Null.NullString; + this.StartDate = Null.NullDate; + this.EndDate = Null.NullDate; + this.DisplayTitle = true; + this.DisplayPrint = false; + this.DisplaySyndicate = Null.NullBoolean; + this.IsWebSlice = Null.NullBoolean; + this.WebSliceTitle = string.Empty; + this.WebSliceExpiryDate = Null.NullDate; + this.WebSliceTTL = 0; + this.InheritViewPermissions = Null.NullBoolean; + this.IsShareable = true; + this.IsShareableViewOnly = true; + this.ContainerSrc = Null.NullString; + this.DesktopModuleID = Null.NullInteger; + this.ModuleControlId = Null.NullInteger; + this.ContainerPath = Null.NullString; + this.PaneModuleIndex = 0; + this.PaneModuleCount = 0; + this.IsDefaultModule = Null.NullBoolean; + this.AllModules = Null.NullBoolean; if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger) { ModuleInfo objModule = ModuleController.Instance.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true); if (objModule != null) { - Alignment = objModule.Alignment; - Color = objModule.Color; - Border = objModule.Border; - IconFile = objModule.IconFile; - Visibility = objModule.Visibility; - ContainerSrc = objModule.ContainerSrc; - DisplayTitle = objModule.DisplayTitle; - DisplayPrint = objModule.DisplayPrint; - DisplaySyndicate = objModule.DisplaySyndicate; + this.Alignment = objModule.Alignment; + this.Color = objModule.Color; + this.Border = objModule.Border; + this.IconFile = objModule.IconFile; + this.Visibility = objModule.Visibility; + this.ContainerSrc = objModule.ContainerSrc; + this.DisplayTitle = objModule.DisplayTitle; + this.DisplayPrint = objModule.DisplayPrint; + this.DisplaySyndicate = objModule.DisplaySyndicate; } } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleSearchBase.cs b/DNN Platform/Library/Entities/Modules/ModuleSearchBase.cs index 356d7e30c28..dc84eb9c3eb 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleSearchBase.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleSearchBase.cs @@ -1,37 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Entities; + /// - /// Modules participating in Search should inherit from this class. A scheduled job will call the methods from this class. + /// Modules participating in Search should inherit from this class. A scheduled job will call the methods from this class. /// - /// Since the methods will be called through a Scheduled job, there will be no Portal Context available by the module to take advantage of + /// Since the methods will be called through a Scheduled job, there will be no Portal Context available by the module to take advantage of. public abstract class ModuleSearchBase { /// /// Return a list of Modified Search Documents based on date. The documents will be stored in Search Index. /// - /// Module Info - /// Provide modified content from this time in Utc - /// Collection of SearchDocument - /// Module must return New, Updated and Deleted Search Documents. - /// It is important to include all the relevant Properties for Updated content (sames as supplied for New document), as partial SearchDocument cannot be Updated in Search Index. + /// Module Info. + /// Provide modified content from this time in Utc. + /// Collection of SearchDocument. + /// Module must return New, Updated and Deleted Search Documents. + /// It is important to include all the relevant Properties for Updated content (sames as supplied for New document), as partial SearchDocument cannot be Updated in Search Index. /// This is different from standard SQL Update where selective columns can updated. In this case, entire Document must be supplied during Update or else information will be lost. /// For Deleted content, set IsActive = false property. /// When IsActive = true, an attempt is made to delete any existing document with same UniqueKey, PortalId, SearchTypeId=Module, ModuleDefitionId and ModuleId(if specified). /// System calls the module based on Scheduler Frequency. This call is performed for modules that have indicated supportedFeature type="Searchable" in manifest. - /// Call is performed for every Module Definition defined by the Module. If a module has more than one Module Defition, module must return data for the main Module Defition, + /// Call is performed for every Module Definition defined by the Module. If a module has more than one Module Defition, module must return data for the main Module Defition, /// or else duplicate content may get stored. /// Module must include ModuleDefition Id in the SearchDocument. In addition ModuleId and / or TabId can also be specified if module has TabId / ModuleId specific content. public abstract IList GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDateUtc); diff --git a/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs b/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs index 1ef359a79b9..1e4a98cda04 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs @@ -1,26 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.ComponentModel; -using DotNetNuke.Common; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.ComponentModel; + + using DotNetNuke.Common; + using DotNetNuke.UI.Modules; + public class ModuleSettingsBase : PortalModuleBase, ISettingsControl { public Hashtable ModuleSettings { get { - return ModuleContext.Configuration.ModuleSettings; + return this.ModuleContext.Configuration.ModuleSettings; } } @@ -28,20 +24,16 @@ public Hashtable TabModuleSettings { get { - return ModuleContext.Configuration.TabModuleSettings; + return this.ModuleContext.Configuration.TabModuleSettings; } - } - - #region ISettingsControl Members - + } + public virtual void LoadSettings() { } public virtual void UpdateSettings() { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleSharing.cs b/DNN Platform/Library/Entities/Modules/ModuleSharing.cs index 23f527d6a8c..bac8d9cb71f 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleSharing.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleSharing.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { + using System; + public enum ModuleSharing { Unknown, Unsupported, - Supported + Supported, } } diff --git a/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs b/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs index aca31e30ef2..623973496ea 100644 --- a/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security.Permissions; + [Serializable] public class PortalDesktopModuleInfo : BaseEntityInfo { @@ -28,13 +23,15 @@ public DesktopModuleInfo DesktopModule { get { - if (_desktopModule == null) + if (this._desktopModule == null) { - _desktopModule = DesktopModuleID > Null.NullInteger ? DesktopModuleController.GetDesktopModule(DesktopModuleID, PortalID) : new DesktopModuleInfo(); + this._desktopModule = this.DesktopModuleID > Null.NullInteger ? DesktopModuleController.GetDesktopModule(this.DesktopModuleID, this.PortalID) : new DesktopModuleInfo(); } - return _desktopModule; + + return this._desktopModule; } } + [XmlIgnore] public int DesktopModuleID { get; set; } @@ -44,11 +41,12 @@ public DesktopModulePermissionCollection Permissions { get { - if (_permissions == null) + if (this._permissions == null) { - _permissions = new DesktopModulePermissionCollection(DesktopModulePermissionController.GetDesktopModulePermissions(PortalDesktopModuleID)); + this._permissions = new DesktopModulePermissionCollection(DesktopModulePermissionController.GetDesktopModulePermissions(this.PortalDesktopModuleID)); } - return _permissions; + + return this._permissions; } } diff --git a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs index ca3363861fc..05e5eac65d7 100644 --- a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.ComponentModel; -using System.IO; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.ComponentModel; + using System.IO; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : PortalModuleBase + /// Project : DotNetNuke + /// Class : PortalModuleBase /// /// ----------------------------------------------------------------------------- /// @@ -36,7 +31,7 @@ namespace DotNetNuke.Entities.Modules /// desktop portal modules within the Portal. /// /// The PortalModuleBase class defines portal specific properties - /// that are used by the portal framework to correctly display portal modules + /// that are used by the portal framework to correctly display portal modules. /// /// /// @@ -50,47 +45,50 @@ public class PortalModuleBase : UserControlBase, IModuleControl private string _localResourceFile; private ModuleInstanceContext _moduleContext; - /// - /// Gets or sets the Dependency Provider to resolve registered - /// services with the container. - /// - /// - /// The Dependency Service. - /// - protected IServiceProvider DependencyProvider { get; } - public PortalModuleBase() { - DependencyProvider = Globals.DependencyProvider; + this.DependencyProvider = Globals.DependencyProvider; } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ModuleActionCollection Actions { get { - return ModuleContext.Actions; + return this.ModuleContext.Actions; } + set { - ModuleContext.Actions = value; + this.ModuleContext.Actions = value; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Control ContainerControl { get { - return Globals.FindControlRecursive(this, "ctr" + ModuleId); + return Globals.FindControlRecursive(this, "ctr" + this.ModuleId); } } + /// + /// Gets the Dependency Provider to resolve registered + /// services with the container. + /// + /// + /// The Dependency Service. + /// + protected IServiceProvider DependencyProvider { get; } + /// ----------------------------------------------------------------------------- /// - /// The EditMode property is used to determine whether the user is in the + /// Gets a value indicating whether the EditMode property is used to determine whether the user is in the /// Administrator role - /// Cache + /// Cache. /// /// /// @@ -99,7 +97,7 @@ public bool EditMode { get { - return ModuleContext.EditMode; + return this.ModuleContext.EditMode; } } @@ -107,123 +105,135 @@ public string HelpURL { get { - return ModuleContext.HelpURL; + return this.ModuleContext.HelpURL; } + set { - ModuleContext.HelpURL = value; + this.ModuleContext.HelpURL = value; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsEditable { get { - return ModuleContext.IsEditable; + return this.ModuleContext.IsEditable; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ModuleInfo ModuleConfiguration { get { - return ModuleContext.Configuration; + return this.ModuleContext.Configuration; } + set { - ModuleContext.Configuration = value; + this.ModuleContext.Configuration = value; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int PortalId { get { - return ModuleContext.PortalId; + return this.ModuleContext.PortalId; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int TabId { get { - return ModuleContext.TabId; + return this.ModuleContext.TabId; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int TabModuleId { get { - return ModuleContext.TabModuleId; + return this.ModuleContext.TabModuleId; } + set { - ModuleContext.TabModuleId = value; + this.ModuleContext.TabModuleId = value; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int ModuleId { get { - return ModuleContext.ModuleId; + return this.ModuleContext.ModuleId; } + set { - ModuleContext.ModuleId = value; + this.ModuleContext.ModuleId = value; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UserInfo UserInfo { get { - return PortalSettings.UserInfo; + return this.PortalSettings.UserInfo; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int UserId { get { - return PortalSettings.UserId; + return this.PortalSettings.UserId; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalAliasInfo PortalAlias { get { - return PortalSettings.PortalAlias; + return this.PortalSettings.PortalAlias; } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Hashtable Settings { get { - return ModuleContext.Settings; + return this.ModuleContext.Settings; } - } - - #region IModuleControl Members - + } + /// ----------------------------------------------------------------------------- /// - /// Gets the underlying base control for this ModuleControl + /// Gets the underlying base control for this ModuleControl. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public Control Control { @@ -235,136 +245,210 @@ public Control Control /// ----------------------------------------------------------------------------- /// - /// Gets the Path for this control (used primarily for UserControls) + /// Gets the Path for this control (used primarily for UserControls). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlPath { get { - return TemplateSourceDirectory + "/"; + return this.TemplateSourceDirectory + "/"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Name for this control + /// Gets the Name for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlName { get { - return GetType().Name.Replace("_", "."); + return this.GetType().Name.Replace("_", "."); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the local resource file for this control + /// Gets or sets and sets the local resource file for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string LocalResourceFile { get { string fileRoot; - if (string.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = Path.Combine(ControlPath, Localization.LocalResourceDirectory + "/" + ID); + fileRoot = Path.Combine(this.ControlPath, Localization.LocalResourceDirectory + "/" + this.ID); } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Module Context for this control + /// Gets the Module Context for this control. /// - /// A ModuleInstanceContext + /// A ModuleInstanceContext. /// ----------------------------------------------------------------------------- public ModuleInstanceContext ModuleContext { get { - if (_moduleContext == null) + if (this._moduleContext == null) { - _moduleContext = new ModuleInstanceContext(this); + this._moduleContext = new ModuleInstanceContext(this); } - return _moduleContext; + + return this._moduleContext; + } + } + + // CONVERSION: Remove obsoleted methods (FYI some core modules use these, such as Links) + + /// ----------------------------------------------------------------------------- + /// + /// Gets the CacheDirectory property is used to return the location of the "Cache" + /// Directory for the Module. + /// + /// + /// + /// ----------------------------------------------------------------------------- + [Obsolete("This property is deprecated. Plaese use ModuleController.CacheDirectory(). Scheduled removal in v11.0.0.")] + public string CacheDirectory + { + get + { + return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache"; } } - #endregion - - protected override void OnInit(EventArgs e) + /// ----------------------------------------------------------------------------- + /// + /// Gets the CacheFileName property is used to store the FileName for this Module's + /// Cache. + /// + /// + /// + /// ----------------------------------------------------------------------------- + [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] + public string CacheFileName { - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"PortalModuleBase.OnInit Start (TabId:{PortalSettings.ActiveTab.TabID},ModuleId:{ModuleId}): {GetType()}"); - base.OnInit(e); - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"PortalModuleBase.OnInit End (TabId:{PortalSettings.ActiveTab.TabID},ModuleId:{ModuleId}): {GetType()}"); + get + { + string strCacheKey = "TabModule:"; + strCacheKey += this.TabModuleId + ":"; + strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); + return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + "\\" + Globals.CleanFileName(strCacheKey) + ".resources"; + } } - protected override void OnLoad(EventArgs e) + + [Obsolete("This property is deprecated. Please use ModuleController.CacheKey(TabModuleID). Scheduled removal in v11.0.0.")] + public string CacheKey { - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"PortalModuleBase.OnLoad Start (TabId:{PortalSettings.ActiveTab.TabID},ModuleId:{ModuleId}): {GetType()}"); - base.OnLoad(e); - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"PortalModuleBase.OnLoad End (TabId:{PortalSettings.ActiveTab.TabID},ModuleId:{ModuleId}): {GetType()}"); + get + { + string strCacheKey = "TabModule:"; + strCacheKey += this.TabModuleId + ":"; + strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); + return strCacheKey; + } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl() { - return ModuleContext.EditUrl(); + return this.ModuleContext.EditUrl(); } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(string ControlKey) { - return ModuleContext.EditUrl(ControlKey); + return this.ModuleContext.EditUrl(ControlKey); + } + + protected override void OnInit(EventArgs e) + { + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnInit Start (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } + + base.OnInit(e); + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnInit End (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } + } + + protected override void OnLoad(EventArgs e) + { + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnLoad Start (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } + + base.OnLoad(e); + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnLoad End (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(string KeyName, string KeyValue) { - return ModuleContext.EditUrl(KeyName, KeyValue); + return this.ModuleContext.EditUrl(KeyName, KeyValue); } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(string KeyName, string KeyValue, string ControlKey) { - return ModuleContext.EditUrl(KeyName, KeyValue, ControlKey); + return this.ModuleContext.EditUrl(KeyName, KeyValue, ControlKey); } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(string KeyName, string KeyValue, string ControlKey, params string[] AdditionalParameters) { - return ModuleContext.EditUrl(KeyName, KeyValue, ControlKey, AdditionalParameters); + return this.ModuleContext.EditUrl(KeyName, KeyValue, ControlKey, AdditionalParameters); } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(int TabID, string ControlKey, bool PageRedirect, params string[] AdditionalParameters) { - return ModuleContext.NavigateUrl(TabID, ControlKey, PageRedirect, AdditionalParameters); + return this.ModuleContext.NavigateUrl(TabID, ControlKey, PageRedirect, AdditionalParameters); } + + public int GetNextActionID() + { + return this.ModuleContext.GetNextActionID(); + } /// ----------------------------------------------------------------------------- /// - /// Helper method that can be used to add an ActionEventHandler to the Skin for this - /// Module Control + /// Helper method that can be used to add an ActionEventHandler to the Skin for this + /// Module Control. /// /// /// @@ -374,76 +458,18 @@ protected void AddActionHandler(ActionEventHandler e) UI.Skins.Skin ParentSkin = UI.Skins.Skin.GetParentSkin(this); if (ParentSkin != null) { - ParentSkin.RegisterModuleActionEvent(ModuleId, e); + ParentSkin.RegisterModuleActionEvent(this.ModuleId, e); } } protected string LocalizeString(string key) { - return Localization.GetString(key, LocalResourceFile); + return Localization.GetString(key, this.LocalResourceFile); } protected string LocalizeSafeJsString(string key) { - return Localization.GetSafeJSString(key, LocalResourceFile); - } - - - public int GetNextActionID() - { - return ModuleContext.GetNextActionID(); - } - - #region "Obsolete methods" - - // CONVERSION: Remove obsoleted methods (FYI some core modules use these, such as Links) - /// ----------------------------------------------------------------------------- - /// - /// The CacheDirectory property is used to return the location of the "Cache" - /// Directory for the Module - /// - /// - /// - /// ----------------------------------------------------------------------------- - [Obsolete("This property is deprecated. Plaese use ModuleController.CacheDirectory(). Scheduled removal in v11.0.0.")] - public string CacheDirectory - { - get - { - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache"; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The CacheFileName property is used to store the FileName for this Module's - /// Cache - /// - /// - /// - /// ----------------------------------------------------------------------------- - [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] - public string CacheFileName - { - get - { - string strCacheKey = "TabModule:"; - strCacheKey += TabModuleId + ":"; - strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + "\\" + Globals.CleanFileName(strCacheKey) + ".resources"; - } - } - - [Obsolete("This property is deprecated. Please use ModuleController.CacheKey(TabModuleID). Scheduled removal in v11.0.0.")] - public string CacheKey - { - get - { - string strCacheKey = "TabModule:"; - strCacheKey += TabModuleId + ":"; - strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); - return strCacheKey; - } + return Localization.GetSafeJSString(key, this.LocalResourceFile); } [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] @@ -467,9 +493,7 @@ public string GetCacheKey(int tabModuleId) [Obsolete("This method is deprecated. Plaese use ModuleController.SynchronizeModule(ModuleId). Scheduled removal in v11.0.0.")] public void SynchronizeModule() { - ModuleController.SynchronizeModule(ModuleId); - } - - #endregion + ModuleController.SynchronizeModule(this.ModuleId); + } } } diff --git a/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs b/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs index 2a27316ef7a..4a353dce7d3 100644 --- a/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs +++ b/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : ProfileUserControlBase + /// Class : ProfileUserControlBase /// ----------------------------------------------------------------------------- /// /// The ProfileUserControlBase class defines a custom base class for the profile Control. @@ -24,31 +19,32 @@ namespace DotNetNuke.Entities.Modules public class ProfileUserControlBase : UserModuleBase { public event EventHandler ProfileUpdated; + public event EventHandler ProfileUpdateCompleted; /// ----------------------------------------------------------------------------- /// - /// Raises the OnProfileUpdateCompleted Event + /// Raises the OnProfileUpdateCompleted Event. /// /// ----------------------------------------------------------------------------- public void OnProfileUpdateCompleted(EventArgs e) { - if (ProfileUpdateCompleted != null) + if (this.ProfileUpdateCompleted != null) { - ProfileUpdateCompleted(this, e); + this.ProfileUpdateCompleted(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the ProfileUpdated Event + /// Raises the ProfileUpdated Event. /// /// ----------------------------------------------------------------------------- public void OnProfileUpdated(EventArgs e) { - if (ProfileUpdated != null) + if (this.ProfileUpdated != null) { - ProfileUpdated(this, e); + this.ProfileUpdated(this, e); } } } diff --git a/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs b/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs index a2f8cc639aa..640b2153c19 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs @@ -1,12 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Settings { - public interface ISettingsRepository where T : class + public interface ISettingsRepository + where T : class { T GetSettings(ModuleInfo moduleContext); + void SaveSettings(ModuleInfo moduleContext, T settings); } } diff --git a/DNN Platform/Library/Entities/Modules/Settings/ISettingsSerializer.cs b/DNN Platform/Library/Entities/Modules/Settings/ISettingsSerializer.cs index 6720746d6ed..04f1fcb7b9b 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ISettingsSerializer.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ISettingsSerializer.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Settings { /// @@ -18,7 +18,7 @@ public interface ISettingsSerializer /// Serialize the property value into a string. /// /// The value of the associated settings property. - /// String + /// String. string Serialize(T value); /// diff --git a/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs b/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs index ed5385cefa1..aac1d7d9175 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Settings { + using System; + /// /// When applied to a property this attribute persists the value of the property in the DNN ModuleSettings referenced by the ModuleId within the context. /// diff --git a/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs b/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs index 78e048afefb..0335b9d9382 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs @@ -1,40 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Settings { + using System; + /// - /// Base class for attributes that are used to decorate properties (parameters) related to + /// Base class for attributes that are used to decorate properties (parameters) related to /// application settings (storage) or parameters (control) like query string parameters. /// [Serializable] public abstract class ParameterAttributeBase : Attribute { /// - /// The prefix to use when naming the setting in the settings table. + /// Gets or sets the prefix to use when naming the setting in the settings table. /// /// /// The settings tables are shared by the core platform and the extensions. Extensions - /// should use a unique prefix to ensure that name clashes do not occur with settings + /// should use a unique prefix to ensure that name clashes do not occur with settings /// defined by the core or other extensions. /// public string Prefix { get; set; } /// - /// The name of the setting that will be stored in the settings table. + /// Gets or sets the name of the setting that will be stored in the settings table. /// /// /// If parametername is not defined, then the name of the property will be used. If /// a prefix is defined, then that will be concatenated with the parametername (or the - /// property name if no parametername is provided) + /// property name if no parametername is provided). /// public string ParameterName { get; set; } /// - /// The serializer to use when saving or retrieving the setting value. + /// Gets or sets the serializer to use when saving or retrieving the setting value. /// /// /// The serializer must implement the interface. diff --git a/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs b/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs index 70cf2a46399..58ac981c7ce 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs @@ -1,21 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Settings { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + [Serializable] public class ParameterMapping - { - #region Constructors - + { /// /// Initializes a new instance of the class. /// @@ -38,18 +36,12 @@ public ParameterMapping(ParameterAttributeBase attribute, PropertyInfo property) } this.FullParameterName = parameterName; - } - - #endregion - - #region Properties - + } + public ParameterAttributeBase Attribute { get; set; } public string FullParameterName { get; set; } - public PropertyInfo Property { get; set; } - - #endregion + public PropertyInfo Property { get; set; } } } diff --git a/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs b/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs index 052f41b0816..ccdda747885 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Settings { + using System; + /// /// When applied to a property this attribute persists the value of the property in the DNN PortalSettings referenced by the PortalId within the context. /// diff --git a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs index edbbfefe7cb..4736a7b222c 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs @@ -1,52 +1,60 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Globalization; -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Web.Caching; -using DotNetNuke.Common; -using DotNetNuke.Collections; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Common.Utilities; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Settings { - public abstract class SettingsRepository : ISettingsRepository where T : class, new() + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Globalization; + using System.Linq; + using System.Reflection; + using System.Text.RegularExpressions; + using System.Web.Caching; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + + public abstract class SettingsRepository : ISettingsRepository + where T : class, new() { - #region Properties - - private IList Mapping { get; } + public const string CachePrefix = "ModuleSettingsPersister_"; private readonly IModuleController _moduleController; - #endregion - protected SettingsRepository() { - Mapping = LoadMapping(); - _moduleController = ModuleController.Instance; + this.Mapping = this.LoadMapping(); + this._moduleController = ModuleController.Instance; + } + + protected virtual string MappingCacheKey + { + get + { + var type = typeof(T); + return SettingsRepository.CachePrefix + type.FullName.Replace(".", "_"); + } } + private IList Mapping { get; } + public T GetSettings(ModuleInfo moduleContext) { - return CBO.GetCachedObject(new CacheItemArgs(CacheKey(moduleContext.TabModuleID), 20, CacheItemPriority.AboveNormal, moduleContext), Load, false); + return CBO.GetCachedObject(new CacheItemArgs(this.CacheKey(moduleContext.TabModuleID), 20, CacheItemPriority.AboveNormal, moduleContext), this.Load, false); } - #region Serialization public void SaveSettings(ModuleInfo moduleContext, T settings) { Requires.NotNull("settings", settings); Requires.NotNull("ctlModule", moduleContext); - Mapping.ForEach(mapping => + this.Mapping.ForEach(mapping => { var attribute = mapping.Attribute; var property = mapping.Property; @@ -67,11 +75,13 @@ public void SaveSettings(ModuleInfo moduleContext, T settings) if (attribute is ModuleSettingAttribute) { - _moduleController.UpdateModuleSetting(moduleContext.ModuleID, mapping.FullParameterName, settingValueAsString); + this._moduleController.UpdateModuleSetting(moduleContext.ModuleID, mapping.FullParameterName, settingValueAsString); + moduleContext.ModuleSettings[mapping.FullParameterName] = settingValueAsString; // temporary fix for issue 3692 } else if (attribute is TabModuleSettingAttribute) { - _moduleController.UpdateTabModuleSetting(moduleContext.TabModuleID, mapping.FullParameterName, settingValueAsString); + this._moduleController.UpdateTabModuleSetting(moduleContext.TabModuleID, mapping.FullParameterName, settingValueAsString); + moduleContext.TabModuleSettings[mapping.FullParameterName] = settingValueAsString; // temporary fix for issue 3692 } else if (attribute is PortalSettingAttribute) { @@ -79,29 +89,9 @@ public void SaveSettings(ModuleInfo moduleContext, T settings) } } }); - DataCache.SetCache(CacheKey(moduleContext.TabModuleID), settings); + DataCache.SetCache(this.CacheKey(moduleContext.TabModuleID), settings); } - private static string GetSettingValueAsString(object settingValue) - { - var dateTimeValue = settingValue as DateTime?; - if (dateTimeValue != null) - { - return dateTimeValue.Value.ToString("o", CultureInfo.InvariantCulture); - } - - var timeSpanValue = settingValue as TimeSpan?; - if (timeSpanValue != null) - { - return timeSpanValue.Value.ToString("c", CultureInfo.InvariantCulture); - } - - return Convert.ToString(settingValue, CultureInfo.InvariantCulture); - } - - #endregion - - #region Mappings protected IList LoadMapping() { var cacheKey = this.MappingCacheKey; @@ -109,7 +99,8 @@ protected IList LoadMapping() if (mapping == null) { mapping = this.CreateMapping(); - // HARDCODED: 2 hour expiration. + + // HARDCODED: 2 hour expiration. // Note that "caching" can also be accomplished with a static dictionary since the Attribute/Property mapping does not change unless the module is updated. CachingProvider.Instance().Insert(cacheKey, mapping, (DNNCacheDependency)null, DateTime.Now.AddHours(2), Cache.NoSlidingExpiration); } @@ -117,16 +108,6 @@ protected IList LoadMapping() return mapping; } - public const string CachePrefix = "ModuleSettingsPersister_"; - protected virtual string MappingCacheKey - { - get - { - var type = typeof(T); - return SettingsRepository.CachePrefix + type.FullName.Replace(".", "_"); - } - } - protected virtual IList CreateMapping() { var mapping = new List(); @@ -141,15 +122,49 @@ protected virtual IList CreateMapping() return mapping; } - #endregion - #region Deserialization + private static string GetSettingValueAsString(object settingValue) + { + var dateTimeValue = settingValue as DateTime?; + if (dateTimeValue != null) + { + return dateTimeValue.Value.ToString("o", CultureInfo.InvariantCulture); + } + + var timeSpanValue = settingValue as TimeSpan?; + if (timeSpanValue != null) + { + return timeSpanValue.Value.ToString("c", CultureInfo.InvariantCulture); + } + + return Convert.ToString(settingValue, CultureInfo.InvariantCulture); + } + + private static object CallSerializerMethod(string serializerTypeName, Type typeArgument, object value, string methodName) + { + var serializerType = Framework.Reflection.CreateType(serializerTypeName, true); + if (serializerType == null) + { + return null; + } + + var serializer = Framework.Reflection.CreateInstance(serializerType); + if (serializer == null) + { + return null; + } + + var serializerInterfaceType = typeof(ISettingsSerializer<>).MakeGenericType(typeArgument); + var method = serializerInterfaceType.GetMethod(methodName); + return method.Invoke(serializer, new[] { value, }); + } + private T Load(CacheItemArgs args) { var ctlModule = (ModuleInfo)args.ParamList[0]; var settings = new T(); - Mapping.ForEach(mapping => + this.Mapping.ForEach(mapping => { string settingValue = null; @@ -172,7 +187,7 @@ private T Load(CacheItemArgs args) if (settingValue != null && property.CanWrite) { - DeserializeProperty(settings, property, attribute, settingValue); + this.DeserializeProperty(settings, property, attribute, settingValue); } }); @@ -262,7 +277,7 @@ private void DeserializeProperty(T settings, PropertyInfo property, ParameterAtt if (propertyType.GetInterface(typeof(IConvertible).FullName) != null) { - propertyValue = ChangeFormatForBooleansIfNeeded(propertyType, propertyValue); + propertyValue = this.ChangeFormatForBooleansIfNeeded(propertyType, propertyValue); property.SetValue(settings, Convert.ChangeType(propertyValue, propertyType, CultureInfo.InvariantCulture), null); return; } @@ -276,7 +291,8 @@ private void DeserializeProperty(T settings, PropertyInfo property, ParameterAtt catch (Exception exception) { // TODO: Localize exception - throw new InvalidCastException(string.Format(CultureInfo.CurrentUICulture, "Could not cast {0} to property {1} of type {2}", + throw new InvalidCastException( + string.Format(CultureInfo.CurrentUICulture, "Could not cast {0} to property {1} of type {2}", propertyValue, property.Name, property.PropertyType), exception); @@ -300,6 +316,7 @@ private string ChangeFormatForBooleansIfNeeded(Type propertyType, string propert { return bool.TrueString; } + if (propertyValue.Equals("0")) { return bool.FalseString; @@ -307,26 +324,5 @@ private string ChangeFormatForBooleansIfNeeded(Type propertyType, string propert return propertyValue; } - - #endregion - - private static object CallSerializerMethod(string serializerTypeName, Type typeArgument, object value, string methodName) - { - var serializerType = Framework.Reflection.CreateType(serializerTypeName, true); - if (serializerType == null) - { - return null; - } - - var serializer = Framework.Reflection.CreateInstance(serializerType); - if (serializer == null) - { - return null; - } - - var serializerInterfaceType = typeof(ISettingsSerializer<>).MakeGenericType(typeArgument); - var method = serializerInterfaceType.GetMethod(methodName); - return method.Invoke(serializer, new[] { value, }); - } } } diff --git a/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs b/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs index 860787a5cd0..9640a1de105 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Settings { + using System; + /// /// When applied to a property this attribute persists the value of the property in the DNN TabModuleSettings referenced by the TabModuleId within the context. /// diff --git a/DNN Platform/Library/Entities/Modules/SkinControlController.cs b/DNN Platform/Library/Entities/Modules/SkinControlController.cs index 93864aee942..6dfb050fbcc 100644 --- a/DNN Platform/Library/Entities/Modules/SkinControlController.cs +++ b/DNN Platform/Library/Entities/Modules/SkinControlController.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : ModuleControlController + /// Class : ModuleControlController /// ----------------------------------------------------------------------------- /// - /// ModuleControlController provides the Business Layer for Module Controls + /// ModuleControlController provides the Business Layer for Module Controls. /// /// ----------------------------------------------------------------------------- public class SkinControlController @@ -31,21 +26,22 @@ public class SkinControlController /// ----------------------------------------------------------------------------- /// - /// DeleteSkinControl deletes a Skin Control in the database + /// DeleteSkinControl deletes a Skin Control in the database. /// - /// The Skin Control to delete + /// The Skin Control to delete. /// ----------------------------------------------------------------------------- public static void DeleteSkinControl(SkinControlInfo skinControl) { dataProvider.DeleteSkinControl(skinControl.SkinControlID); - EventLogController.Instance.AddLog(skinControl, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.SKINCONTROL_DELETED); + EventLogController.Instance.AddLog(skinControl, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINCONTROL_DELETED); } /// ----------------------------------------------------------------------------- /// - /// GetSkinControl gets a single Skin Control from the database + /// GetSkinControl gets a single Skin Control from the database. /// - /// The ID of the SkinControl + /// The ID of the SkinControl. + /// /// ----------------------------------------------------------------------------- public static SkinControlInfo GetSkinControl(int skinControlID) { @@ -54,9 +50,10 @@ public static SkinControlInfo GetSkinControl(int skinControlID) /// ----------------------------------------------------------------------------- /// - /// GetSkinControlByPackageID gets a single Skin Control from the database + /// GetSkinControlByPackageID gets a single Skin Control from the database. /// - /// The ID of the Package + /// The ID of the Package. + /// /// ----------------------------------------------------------------------------- public static SkinControlInfo GetSkinControlByPackageID(int packageID) { @@ -65,9 +62,10 @@ public static SkinControlInfo GetSkinControlByPackageID(int packageID) /// ----------------------------------------------------------------------------- /// - /// GetSkinControlByKey gets a single Skin Control from the database + /// GetSkinControlByKey gets a single Skin Control from the database. /// - /// The key of the Control + /// The key of the Control. + /// /// ----------------------------------------------------------------------------- public static SkinControlInfo GetSkinControlByKey(string key) { @@ -76,8 +74,9 @@ public static SkinControlInfo GetSkinControlByKey(string key) /// ----------------------------------------------------------------------------- /// - /// GetSkinControls gets all the Skin Controls from the database - /// + /// GetSkinControls gets all the Skin Controls from the database. + /// + /// /// ----------------------------------------------------------------------------- public static Dictionary GetSkinControls() { @@ -86,34 +85,38 @@ public static Dictionary GetSkinControls() /// ----------------------------------------------------------------------------- /// - /// SaveSkinControl updates a Skin Control in the database + /// SaveSkinControl updates a Skin Control in the database. /// - /// The Skin Control to save + /// The Skin Control to save. + /// /// ----------------------------------------------------------------------------- public static int SaveSkinControl(SkinControlInfo skinControl) { int skinControlID = skinControl.SkinControlID; if (skinControlID == Null.NullInteger) { - //Add new Skin Control - skinControlID = dataProvider.AddSkinControl(skinControl.PackageID, - skinControl.ControlKey, - skinControl.ControlSrc, - skinControl.SupportsPartialRendering, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(skinControl, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.SKINCONTROL_CREATED); + // Add new Skin Control + skinControlID = dataProvider.AddSkinControl( + skinControl.PackageID, + skinControl.ControlKey, + skinControl.ControlSrc, + skinControl.SupportsPartialRendering, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(skinControl, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINCONTROL_CREATED); } else { - //Upgrade Skin Control - dataProvider.UpdateSkinControl(skinControl.SkinControlID, - skinControl.PackageID, - skinControl.ControlKey, - skinControl.ControlSrc, - skinControl.SupportsPartialRendering, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(skinControl, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.SKINCONTROL_UPDATED); + // Upgrade Skin Control + dataProvider.UpdateSkinControl( + skinControl.SkinControlID, + skinControl.PackageID, + skinControl.ControlKey, + skinControl.ControlSrc, + skinControl.SupportsPartialRendering, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(skinControl, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINCONTROL_UPDATED); } + return skinControlID; } } diff --git a/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs b/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs index 02ca9b2a3c4..3911d5f537e 100644 --- a/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Data; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : SkinControlInfo + /// Class : SkinControlInfo /// ----------------------------------------------------------------------------- /// - /// SkinControlInfo provides the Entity Layer for Skin Controls (SkinObjects) + /// SkinControlInfo provides the Entity Layer for Skin Controls (SkinObjects). /// /// ----------------------------------------------------------------------------- [Serializable] @@ -30,67 +25,63 @@ public class SkinControlInfo : ControlInfo, IXmlSerializable, IHydratable { public SkinControlInfo() { - PackageID = Null.NullInteger; - SkinControlID = Null.NullInteger; + this.PackageID = Null.NullInteger; + this.SkinControlID = Null.NullInteger; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the SkinControl ID + /// Gets or sets and sets the SkinControl ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int SkinControlID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ID of the Package for this Desktop Module + /// Gets or sets and sets the ID of the Package for this Desktop Module. /// - /// An Integer - /// ----------------------------------------------------------------------------- - public int PackageID { get; set; } - - #region IHydratable Members - + /// An Integer. /// ----------------------------------------------------------------------------- - /// - /// Fills a SkinControlInfo from a Data Reader - /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - SkinControlID = Null.SetNullInteger(dr["SkinControlID"]); - PackageID = Null.SetNullInteger(dr["PackageID"]); - FillInternal(dr); - } + public int PackageID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Key ID + /// Gets or sets and sets the Key ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int KeyID { get { - return SkinControlID; + return this.SkinControlID; } + set { - SkinControlID = value; + this.SkinControlID = value; } - } - - #endregion - - #region IXmlSerializable Members - + } + /// ----------------------------------------------------------------------------- /// - /// Gets an XmlSchema for the SkinControlInfo + /// Fills a SkinControlInfo from a Data Reader. /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.SkinControlID = Null.SetNullInteger(dr["SkinControlID"]); + this.PackageID = Null.SetNullInteger(dr["PackageID"]); + this.FillInternal(dr); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets an XmlSchema for the SkinControlInfo. + /// + /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() { @@ -99,9 +90,9 @@ public XmlSchema GetSchema() /// ----------------------------------------------------------------------------- /// - /// Reads a SkinControlInfo from an XmlReader + /// Reads a SkinControlInfo from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { @@ -111,32 +102,32 @@ public void ReadXml(XmlReader reader) { break; } + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - ReadXmlInternal(reader); + + this.ReadXmlInternal(reader); } } /// ----------------------------------------------------------------------------- /// - /// Writes a SkinControlInfo to an XmlWriter + /// Writes a SkinControlInfo to an XmlWriter. /// - /// The XmlWriter to use + /// The XmlWriter to use. /// ----------------------------------------------------------------------------- public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("moduleControl"); - //write out properties - WriteXmlInternal(writer); + // write out properties + this.WriteXmlInternal(writer); - //Write end of main element + // Write end of main element writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs index 027d7094336..bfc0c6d5947 100644 --- a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs @@ -1,47 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Web.Caching; - -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mail; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.WebControls; + public enum DisplayMode { All = 0, FirstLetter = 1, - None = 2 + None = 2, } public enum UsersControl { Combo = 0, - TextBox = 1 + TextBox = 1, } /// @@ -55,96 +50,152 @@ public class UserModuleBase : PortalModuleBase private UserInfo _User; /// - /// Gets whether we are in Add User mode + /// Gets or sets and sets the User associated with this control. + /// + public UserInfo User + { + get + { + return this._User ?? (this._User = this.AddUser ? this.InitialiseUser() : UserController.GetUserById(this.UserPortalID, this.UserId)); + } + + set + { + this._User = value; + if (this._User != null) + { + this.UserId = this._User.UserID; + } + } + } + + /// + /// Gets or sets and sets the UserId associated with this control. + /// + public new int UserId + { + get + { + int _UserId = Null.NullInteger; + if (this.ViewState["UserId"] == null) + { + if (this.Request.QueryString["userid"] != null) + { + int userId; + + // Use Int32.MaxValue as invalid UserId + _UserId = int.TryParse(this.Request.QueryString["userid"], out userId) ? userId : int.MaxValue; + this.ViewState["UserId"] = _UserId; + } + } + else + { + _UserId = Convert.ToInt32(this.ViewState["UserId"]); + } + + return _UserId; + } + + set + { + this.ViewState["UserId"] = value; + } + } + + /// + /// Gets a value indicating whether gets whether we are in Add User mode. /// protected virtual bool AddUser { get { - return (UserId == Null.NullInteger); + return this.UserId == Null.NullInteger; } } /// - /// Gets whether the current user is an Administrator (or SuperUser) + /// Gets a value indicating whether gets whether the current user is an Administrator (or SuperUser). /// protected bool IsAdmin { get { - return Request.IsAuthenticated && PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); + return this.Request.IsAuthenticated && PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); } } /// - /// gets whether this is the current user or admin + /// Gets a value indicating whether gets whether this is the current user or admin. /// - /// + /// + /// gets whether this is the current user or admin + /// /// /// protected bool IsUserOrAdmin { get { - return IsUser || IsAdmin; + return this.IsUser || this.IsAdmin; } } /// - /// Gets whether this control is in the Host menu + /// Gets a value indicating whether gets whether this control is in the Host menu. /// protected bool IsHostTab { get { - return base.IsHostMenu; + return this.IsHostMenu; } } /// - /// Gets whether the control is being called form the User Accounts module + /// Gets a value indicating whether gets whether the control is being called form the User Accounts module. /// protected bool IsEdit { get { bool _IsEdit = false; - if (Request.QueryString["ctl"] != null) + if (this.Request.QueryString["ctl"] != null) { - string ctl = Request.QueryString["ctl"]; + string ctl = this.Request.QueryString["ctl"]; if (ctl.Equals("edit", StringComparison.InvariantCultureIgnoreCase)) { _IsEdit = true; } } + return _IsEdit; } } /// - /// Gets whether the current user is modifying their profile + /// Gets a value indicating whether gets whether the current user is modifying their profile. /// protected bool IsProfile { get { bool _IsProfile = false; - if (IsUser) + if (this.IsUser) { - if (PortalSettings.UserTabId != -1) + if (this.PortalSettings.UserTabId != -1) { - //user defined tab - if (PortalSettings.ActiveTab.TabID == PortalSettings.UserTabId) + // user defined tab + if (this.PortalSettings.ActiveTab.TabID == this.PortalSettings.UserTabId) { _IsProfile = true; } } else { - //admin tab - if (Request.QueryString["ctl"] != null) + // admin tab + if (this.Request.QueryString["ctl"] != null) { - string ctl = Request.QueryString["ctl"]; + string ctl = this.Request.QueryString["ctl"]; if (ctl.Equals("profile", StringComparison.InvariantCultureIgnoreCase)) { _IsProfile = true; @@ -152,97 +203,50 @@ protected bool IsProfile } } } + return _IsProfile; } } /// - /// Gets whether an anonymous user is trying to register + /// Gets a value indicating whether gets whether an anonymous user is trying to register. /// protected bool IsRegister { get { - return !IsAdmin && !IsUser; + return !this.IsAdmin && !this.IsUser; } } /// - /// Gets whether the User is editing their own information + /// Gets a value indicating whether gets whether the User is editing their own information. /// protected bool IsUser { get { - return Request.IsAuthenticated && (UserId == UserInfo.UserID); + return this.Request.IsAuthenticated && (this.UserId == this.UserInfo.UserID); } } /// - /// Gets the PortalId to use for this control + /// Gets the PortalId to use for this control. /// protected int UserPortalID { get { - return IsHostTab ? Null.NullInteger : PortalId; - } - } - - /// - /// Gets and sets the User associated with this control - /// - public UserInfo User - { - get - { - return _User ?? (_User = AddUser ? InitialiseUser() : UserController.GetUserById(UserPortalID, UserId)); - } - set - { - _User = value; - if (_User != null) - { - UserId = _User.UserID; - } - } - } - - /// - /// Gets and sets the UserId associated with this control - /// - public new int UserId - { - get - { - int _UserId = Null.NullInteger; - if (ViewState["UserId"] == null) - { - if (Request.QueryString["userid"] != null) - { - int userId; - // Use Int32.MaxValue as invalid UserId - _UserId = Int32.TryParse(Request.QueryString["userid"], out userId) ? userId : Int32.MaxValue; - ViewState["UserId"] = _UserId; - } - } - else - { - _UserId = Convert.ToInt32(ViewState["UserId"]); - } - return _UserId; - } - set - { - ViewState["UserId"] = value; + return this.IsHostTab ? Null.NullInteger : this.PortalId; } } /// - /// Gets a Setting for the Module + /// Gets a Setting for the Module. /// /// - /// + /// + /// public static object GetSetting(int portalId, string settingKey) { Hashtable settings = UserController.GetUserSettings(portalId); @@ -250,6 +254,7 @@ public static object GetSetting(int portalId, string settingKey) { settings = UserController.GetUserSettings(portalId, settings); } + return settings[settingKey]; } @@ -257,7 +262,7 @@ public static void UpdateSetting(int portalId, string key, string setting) { if (portalId == Null.NullInteger) { - HostController.Instance.Update(new ConfigurationSetting {Value = setting, Key = key}); + HostController.Instance.Update(new ConfigurationSetting { Value = setting, Key = key }); } else { @@ -266,7 +271,7 @@ public static void UpdateSetting(int portalId, string key, string setting) } /// - /// Updates the Settings for the Module + /// Updates the Settings for the Module. /// public static void UpdateSettings(int portalId, Hashtable settings) { @@ -282,32 +287,57 @@ public static void UpdateSettings(int portalId, Hashtable settings) } /// - /// InitialiseUser initialises a "new" user + /// AddLocalizedModuleMessage adds a localized module message. + /// + /// The localized message. + /// The type of message. + /// A flag that determines whether the message should be displayed. + protected void AddLocalizedModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) + { + if (display) + { + UI.Skins.Skin.AddModuleMessage(this, message, type); + } + } + + /// + /// AddModuleMessage adds a module message. + /// + /// The message. + /// The type of message. + /// A flag that determines whether the message should be displayed. + protected void AddModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) + { + this.AddLocalizedModuleMessage(Localization.GetString(message, this.LocalResourceFile), type, display); + } + + /// + /// InitialiseUser initialises a "new" user. /// private UserInfo InitialiseUser() { var newUser = new UserInfo(); - if (IsHostMenu && !IsRegister) + if (this.IsHostMenu && !this.IsRegister) { newUser.IsSuperUser = true; } else { - newUser.PortalID = PortalId; + newUser.PortalID = this.PortalId; } - //Initialise the ProfileProperties Collection + // Initialise the ProfileProperties Collection string lc = new Localization().CurrentUICulture; - newUser.Profile.InitialiseProfile(PortalId); - newUser.Profile.PreferredTimeZone = PortalSettings.TimeZone; + newUser.Profile.InitialiseProfile(this.PortalId); + newUser.Profile.PreferredTimeZone = this.PortalSettings.TimeZone; newUser.Profile.PreferredLocale = lc; - //Set default countr + // Set default countr string country = Null.NullString; - country = LookupCountry(); - if (!String.IsNullOrEmpty(country)) + country = this.LookupCountry(); + if (!string.IsNullOrEmpty(country)) { ListController listController = new ListController(); var listitem = listController.GetListEntryInfo("Country", country); @@ -318,12 +348,14 @@ private UserInfo InitialiseUser() newUser.Profile.Country = country; } - //Set AffiliateId + + // Set AffiliateId int AffiliateId = Null.NullInteger; - if (Request.Cookies["AffiliateId"] != null) + if (this.Request.Cookies["AffiliateId"] != null) { - AffiliateId = int.Parse(Request.Cookies["AffiliateId"].Value); + AffiliateId = int.Parse(this.Request.Cookies["AffiliateId"].Value); } + newUser.AffiliateID = AffiliateId; return newUser; } @@ -335,49 +367,52 @@ private string LookupCountry() bool _CacheGeoIPData = true; string _GeoIPFile; _GeoIPFile = "controls/CountryListBox/Data/GeoIP.dat"; - if (Page.Request.UserHostAddress == "127.0.0.1") + if (this.Page.Request.UserHostAddress == "127.0.0.1") { - //'The country cannot be detected because the user is local. + // 'The country cannot be detected because the user is local. IsLocal = true; - //Set the IP address in case they didn't specify LocalhostCountryCode - IP = Page.Request.UserHostAddress; + + // Set the IP address in case they didn't specify LocalhostCountryCode + IP = this.Page.Request.UserHostAddress; } else { - //Set the IP address so we can find the country - IP = Page.Request.UserHostAddress; + // Set the IP address so we can find the country + IP = this.Page.Request.UserHostAddress; } - //Check to see if we need to generate the Cache for the GeoIPData file - if (Context.Cache.Get("GeoIPData") == null && _CacheGeoIPData) + + // Check to see if we need to generate the Cache for the GeoIPData file + if (this.Context.Cache.Get("GeoIPData") == null && _CacheGeoIPData) { - //Store it as well as setting a dependency on the file - Context.Cache.Insert("GeoIPData", CountryLookup.FileToMemory(Context.Server.MapPath(_GeoIPFile)), new CacheDependency(Context.Server.MapPath(_GeoIPFile))); + // Store it as well as setting a dependency on the file + this.Context.Cache.Insert("GeoIPData", CountryLookup.FileToMemory(this.Context.Server.MapPath(_GeoIPFile)), new CacheDependency(this.Context.Server.MapPath(_GeoIPFile))); } - - //Check to see if the request is a localhost request - //and see if the LocalhostCountryCode is specified + + // Check to see if the request is a localhost request + // and see if the LocalhostCountryCode is specified if (IsLocal) { return Null.NullString; } - - //Either this is a remote request or it is a local - //request with no LocalhostCountryCode specified + + // Either this is a remote request or it is a local + // request with no LocalhostCountryCode specified CountryLookup _CountryLookup; - //Check to see if we are using the Cached - //version of the GeoIPData file + // Check to see if we are using the Cached + // version of the GeoIPData file if (_CacheGeoIPData) { - //Yes, get it from cache - _CountryLookup = new CountryLookup((MemoryStream) Context.Cache.Get("GeoIPData")); + // Yes, get it from cache + _CountryLookup = new CountryLookup((MemoryStream)this.Context.Cache.Get("GeoIPData")); } else { - //No, get it from file - _CountryLookup = new CountryLookup(Context.Server.MapPath(_GeoIPFile)); + // No, get it from file + _CountryLookup = new CountryLookup(this.Context.Server.MapPath(_GeoIPFile)); } - //Get the country code based on the IP address + + // Get the country code based on the IP address string country = Null.NullString; try { @@ -387,105 +422,81 @@ private string LookupCountry() { Exceptions.LogException(ex); } + return country; } - /// - /// AddLocalizedModuleMessage adds a localized module message - /// - /// The localized message - /// The type of message - /// A flag that determines whether the message should be displayed - protected void AddLocalizedModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) - { - if (display) - { - UI.Skins.Skin.AddModuleMessage(this, message, type); - } - } - - /// - /// AddModuleMessage adds a module message - /// - /// The message - /// The type of message - /// A flag that determines whether the message should be displayed - protected void AddModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) - { - AddLocalizedModuleMessage(Localization.GetString(message, LocalResourceFile), type, display); - } - protected string CompleteUserCreation(UserCreateStatus createStatus, UserInfo newUser, bool notify, bool register) { - var strMessage = ""; + var strMessage = string.Empty; var message = ModuleMessage.ModuleMessageType.RedError; if (register) { - //send notification to portal administrator of new user registration - //check the receive notification setting first, but if register type is Private, we will always send the notification email. - //because the user need administrators to do the approve action so that he can continue use the website. - if (PortalSettings.EnableRegisterNotification || PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration) - { - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, PortalSettings); - SendAdminNotification(newUser, PortalSettings); - } + // send notification to portal administrator of new user registration + // check the receive notification setting first, but if register type is Private, we will always send the notification email. + // because the user need administrators to do the approve action so that he can continue use the website. + if (this.PortalSettings.EnableRegisterNotification || this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration) + { + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, this.PortalSettings); + this.SendAdminNotification(newUser, this.PortalSettings); + } var loginStatus = UserLoginStatus.LOGIN_FAILURE; - //complete registration - switch (PortalSettings.UserRegistration) + // complete registration + switch (this.PortalSettings.UserRegistration) { - case (int) Globals.PortalRegistrationType.PrivateRegistration: - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPrivate, PortalSettings); + case (int)Globals.PortalRegistrationType.PrivateRegistration: + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPrivate, this.PortalSettings); - //show a message that a portal administrator has to verify the user credentials + // show a message that a portal administrator has to verify the user credentials if (string.IsNullOrEmpty(strMessage)) { strMessage += Localization.GetString("PrivateConfirmationMessage", Localization.SharedResourceFile); message = ModuleMessage.ModuleMessageType.GreenSuccess; } + break; - case (int) Globals.PortalRegistrationType.PublicRegistration: - Mail.SendMail(newUser, MessageType.UserRegistrationPublic, PortalSettings); - UserController.UserLogin(PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, "", PortalSettings.PortalName, "", ref loginStatus, false); + case (int)Globals.PortalRegistrationType.PublicRegistration: + Mail.SendMail(newUser, MessageType.UserRegistrationPublic, this.PortalSettings); + UserController.UserLogin(this.PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, string.Empty, this.PortalSettings.PortalName, string.Empty, ref loginStatus, false); break; - case (int) Globals.PortalRegistrationType.VerifiedRegistration: - Mail.SendMail(newUser, MessageType.UserRegistrationVerified, PortalSettings); - UserController.UserLogin(PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, "", PortalSettings.PortalName, "", ref loginStatus, false); + case (int)Globals.PortalRegistrationType.VerifiedRegistration: + Mail.SendMail(newUser, MessageType.UserRegistrationVerified, this.PortalSettings); + UserController.UserLogin(this.PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, string.Empty, this.PortalSettings.PortalName, string.Empty, ref loginStatus, false); break; } - //store preferredlocale in cookie + + // store preferredlocale in cookie Localization.SetLanguage(newUser.Profile.PreferredLocale); - if (IsRegister && message == ModuleMessage.ModuleMessageType.RedError) + if (this.IsRegister && message == ModuleMessage.ModuleMessageType.RedError) { - AddLocalizedModuleMessage(string.Format(Localization.GetString("SendMail.Error", Localization.SharedResourceFile), strMessage), message, (!String.IsNullOrEmpty(strMessage))); + this.AddLocalizedModuleMessage(string.Format(Localization.GetString("SendMail.Error", Localization.SharedResourceFile), strMessage), message, !string.IsNullOrEmpty(strMessage)); } else { - AddLocalizedModuleMessage(strMessage, message, (!String.IsNullOrEmpty(strMessage))); + this.AddLocalizedModuleMessage(strMessage, message, !string.IsNullOrEmpty(strMessage)); } } else { if (notify) { - //Send Notification to User - if (PortalSettings.UserRegistration == (int) Globals.PortalRegistrationType.VerifiedRegistration) + // Send Notification to User + if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) { - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationVerified, PortalSettings); + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationVerified, this.PortalSettings); } else { - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPublic, PortalSettings); + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPublic, this.PortalSettings); } } } - - return strMessage; - } - - #region Private methods + return strMessage; + } + private void SendAdminNotification(UserInfo newUser, PortalSettings portalSettings) { var notificationType = newUser.Membership.Approved ? "NewUserRegistration" : "NewUnauthorizedUserRegistration"; @@ -495,9 +506,9 @@ private void SendAdminNotification(UserInfo newUser, PortalSettings portalSettin NotificationTypeID = NotificationsController.Instance.GetNotificationType(notificationType).NotificationTypeId, IncludeDismissAction = newUser.Membership.Approved, SenderUserID = portalSettings.AdministratorId, - Subject = GetNotificationSubject(locale, newUser, portalSettings), - Body = GetNotificationBody(locale, newUser, portalSettings), - Context = newUser.UserID.ToString(CultureInfo.InvariantCulture) + Subject = this.GetNotificationSubject(locale, newUser, portalSettings), + Body = this.GetNotificationBody(locale, newUser, portalSettings), + Context = newUser.UserID.ToString(CultureInfo.InvariantCulture), }; var adminrole = RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.AdministratorRoleId); var roles = new List { adminrole }; @@ -507,21 +518,19 @@ private void SendAdminNotification(UserInfo newUser, PortalSettings portalSettin private string GetNotificationBody(string locale, UserInfo newUser, PortalSettings portalSettings) { const string text = "EMAIL_USER_REGISTRATION_ADMINISTRATOR_BODY"; - return LocalizeNotificationText(text, locale, newUser, portalSettings); + return this.LocalizeNotificationText(text, locale, newUser, portalSettings); } private string LocalizeNotificationText(string text, string locale, UserInfo user, PortalSettings portalSettings) { - //This method could need a custom ArrayList in future notification types. Currently it is null - return Localization.GetSystemMessage(locale, portalSettings, text, user, Localization.GlobalResourceFile, null, "", portalSettings.AdministratorId); + // This method could need a custom ArrayList in future notification types. Currently it is null + return Localization.GetSystemMessage(locale, portalSettings, text, user, Localization.GlobalResourceFile, null, string.Empty, portalSettings.AdministratorId); } private string GetNotificationSubject(string locale, UserInfo newUser, PortalSettings portalSettings) { const string text = "EMAIL_USER_REGISTRATION_ADMINISTRATOR_SUBJECT"; - return LocalizeNotificationText(text, locale, newUser, portalSettings); - } - - #endregion + return this.LocalizeNotificationText(text, locale, newUser, portalSettings); + } } } diff --git a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs index 9f1a04d52e3..7265adeccfb 100644 --- a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Membership; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : UserUserControlBase + /// Class : UserUserControlBase /// ----------------------------------------------------------------------------- /// /// The UserUserControlBase class defines a custom base class for the User Control. @@ -25,358 +20,340 @@ namespace DotNetNuke.Entities.Modules /// /// ----------------------------------------------------------------------------- public class UserUserControlBase : UserModuleBase - { - #region Delegates + { public delegate void UserCreatedEventHandler(object sender, UserCreatedEventArgs e); + public delegate void UserDeletedEventHandler(object sender, UserDeletedEventArgs e); + public delegate void UserRestoredEventHandler(object sender, UserRestoredEventArgs e); + public delegate void UserRemovedEventHandler(object sender, UserRemovedEventArgs e); - public delegate void UserUpdateErrorEventHandler(object sender, UserUpdateErrorArgs e); - #endregion - - #region "Events" + + public delegate void UserUpdateErrorEventHandler(object sender, UserUpdateErrorArgs e); + public event UserCreatedEventHandler UserCreated; + public event UserCreatedEventHandler UserCreateCompleted; + public event UserDeletedEventHandler UserDeleted; + public event UserUpdateErrorEventHandler UserDeleteError; + public event UserRestoredEventHandler UserRestored; + public event UserUpdateErrorEventHandler UserRestoreError; + public event UserRemovedEventHandler UserRemoved; + public event UserUpdateErrorEventHandler UserRemoveError; + public event EventHandler UserUpdated; + public event EventHandler UserUpdateCompleted; - public event UserUpdateErrorEventHandler UserUpdateError; - #endregion - - #region "Event Methods" - + + public event UserUpdateErrorEventHandler UserUpdateError; + + protected override bool AddUser => !this.Request.IsAuthenticated || base.AddUser; + /// ----------------------------------------------------------------------------- /// - /// Raises the UserCreateCompleted Event + /// Raises the UserCreateCompleted Event. /// /// ----------------------------------------------------------------------------- public void OnUserCreateCompleted(UserCreatedEventArgs e) { - if (UserCreateCompleted != null) + if (this.UserCreateCompleted != null) { - UserCreateCompleted(this, e); + this.UserCreateCompleted(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the UserCreated Event + /// Raises the UserCreated Event. /// /// ----------------------------------------------------------------------------- public void OnUserCreated(UserCreatedEventArgs e) { - if (UserCreated != null) + if (this.UserCreated != null) { - UserCreated(this, e); + this.UserCreated(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the UserDeleted Event + /// Raises the UserDeleted Event. /// /// ----------------------------------------------------------------------------- public void OnUserDeleted(UserDeletedEventArgs e) { - if (UserDeleted != null) + if (this.UserDeleted != null) { - UserDeleted(this, e); + this.UserDeleted(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the UserDeleteError Event + /// Raises the UserDeleteError Event. /// /// ----------------------------------------------------------------------------- public void OnUserDeleteError(UserUpdateErrorArgs e) { - if (UserDeleteError != null) + if (this.UserDeleteError != null) { - UserDeleteError(this, e); + this.UserDeleteError(this, e); } } public void OnUserRestored(UserRestoredEventArgs e) { - if (UserRestored != null) + if (this.UserRestored != null) { - UserRestored(this, e); + this.UserRestored(this, e); } } public void OnUserRestoreError(UserUpdateErrorArgs e) { - if (UserRestoreError != null) + if (this.UserRestoreError != null) { - UserRestoreError(this, e); + this.UserRestoreError(this, e); } } public void OnUserRemoved(UserRemovedEventArgs e) { - if (UserRemoved != null) + if (this.UserRemoved != null) { - UserRemoved(this, e); + this.UserRemoved(this, e); } } public void OnUserRemoveError(UserUpdateErrorArgs e) { - if (UserRemoveError != null) + if (this.UserRemoveError != null) { - UserRemoveError(this, e); + this.UserRemoveError(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the UserUpdated Event + /// Raises the UserUpdated Event. /// /// ----------------------------------------------------------------------------- public void OnUserUpdated(EventArgs e) { - if (UserUpdated != null) + if (this.UserUpdated != null) { - UserUpdated(this, e); + this.UserUpdated(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the UserUpdated Event + /// Raises the UserUpdated Event. /// /// ----------------------------------------------------------------------------- public void OnUserUpdateCompleted(EventArgs e) { - if (UserUpdateCompleted != null) + if (this.UserUpdateCompleted != null) { - UserUpdateCompleted(this, e); + this.UserUpdateCompleted(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the UserUpdateError Event + /// Raises the UserUpdateError Event. /// /// ----------------------------------------------------------------------------- public void OnUserUpdateError(UserUpdateErrorArgs e) { - if (UserUpdateError != null) + if (this.UserUpdateError != null) { - UserUpdateError(this, e); + this.UserUpdateError(this, e); } - } - - #endregion - - #region "Properties" - - protected override bool AddUser => !Request.IsAuthenticated || base.AddUser; - - #endregion - - #region Nested type: BaseUserEventArgs - + } + /// ----------------------------------------------------------------------------- /// - /// The BaseUserEventArgs class provides a base for User EventArgs classes + /// The BaseUserEventArgs class provides a base for User EventArgs classes. /// /// ----------------------------------------------------------------------------- public class BaseUserEventArgs { /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Id of the User + /// Gets or sets and sets the Id of the User. /// /// ----------------------------------------------------------------------------- public int UserId { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Id of the User + /// Gets or sets and sets the Id of the User. /// /// ----------------------------------------------------------------------------- public string UserName { get; set; } - } - - #endregion - - #region Nested type: UserCreatedEventArgs - + } + /// ----------------------------------------------------------------------------- /// /// The UserCreatedEventArgs class provides a customised EventArgs class for - /// the UserCreated Event + /// the UserCreated Event. /// /// ----------------------------------------------------------------------------- public class UserCreatedEventArgs { - private UserCreateStatus _createStatus = UserCreateStatus.Success; - + private UserCreateStatus _createStatus = UserCreateStatus.Success; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new UserCreatedEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new UserCreatedEventArgs. /// - /// The newly Created User + /// The newly Created User. /// ----------------------------------------------------------------------------- public UserCreatedEventArgs(UserInfo newUser) { - NewUser = newUser; + this.NewUser = newUser; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Create Status + /// Gets or sets and sets the Create Status. /// /// ----------------------------------------------------------------------------- public UserCreateStatus CreateStatus { get { - return _createStatus; + return this._createStatus; } + set { - _createStatus = value; + this._createStatus = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the New User + /// Gets or sets and sets the New User. /// /// ----------------------------------------------------------------------------- public UserInfo NewUser { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a flag whether to Notify the new User of the Creation + /// Gets or sets a value indicating whether gets and sets a flag whether to Notify the new User of the Creation. /// /// ----------------------------------------------------------------------------- public bool Notify { get; set; } - } - - #endregion - - #region Nested type: UserDeletedEventArgs - + } + /// ----------------------------------------------------------------------------- /// /// The UserDeletedEventArgs class provides a customised EventArgs class for - /// the UserDeleted Event + /// the UserDeleted Event. /// /// ----------------------------------------------------------------------------- public class UserDeletedEventArgs : BaseUserEventArgs - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new UserDeletedEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new UserDeletedEventArgs. /// - /// The Id of the User - /// The user name of the User + /// The Id of the User. + /// The user name of the User. /// ----------------------------------------------------------------------------- public UserDeletedEventArgs(int id, string name) { - UserId = id; - UserName = name; + this.UserId = id; + this.UserName = name; } - } - - #endregion - - #region Nested type: UserRestoredEventArgs - - /// ----------------------------------------------------------------------------- - /// - /// The UserRestoredEventArgs class provides a customised EventArgs class for - /// the UserRestored Event - /// - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// The UserRestoredEventArgs class provides a customised EventArgs class for + /// the UserRestored Event. + /// + /// ----------------------------------------------------------------------------- public class UserRestoredEventArgs : BaseUserEventArgs - { - /// ----------------------------------------------------------------------------- - /// - /// Constructs a new UserRestoredEventArgs - /// - /// The Id of the User - /// The user name of the User - /// ----------------------------------------------------------------------------- + { + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new UserRestoredEventArgs. + /// + /// The Id of the User. + /// The user name of the User. + /// ----------------------------------------------------------------------------- public UserRestoredEventArgs(int id, string name) { - UserId = id; - UserName = name; + this.UserId = id; + this.UserName = name; } - } - - #endregion - - #region Nested type: UserRemovedEventArgs - - /// ----------------------------------------------------------------------------- - /// - /// The UserRemovedEventArgs class provides a customised EventArgs class for - /// the UserRemoved Event - /// - /// ----------------------------------------------------------------------------- - + } + + /// ----------------------------------------------------------------------------- + /// + /// The UserRemovedEventArgs class provides a customised EventArgs class for + /// the UserRemoved Event. + /// + /// ----------------------------------------------------------------------------- public class UserRemovedEventArgs : BaseUserEventArgs - { - /// ----------------------------------------------------------------------------- - /// - /// Constructs a new UserRemovedEventArgs - /// - /// The Id of the User - /// The user name of the User - /// ----------------------------------------------------------------------------- - public UserRemovedEventArgs(int id, string name) + { + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new UserRemovedEventArgs. + /// + /// The Id of the User. + /// The user name of the User. + /// ----------------------------------------------------------------------------- + public UserRemovedEventArgs(int id, string name) { - UserId = id; - UserName = name; + this.UserId = id; + this.UserName = name; } - } - - - #endregion - - #region Nested type: UserUpdateErrorArgs - + } + /// ----------------------------------------------------------------------------- /// /// The UserUpdateErrorArgs class provides a customised EventArgs class for - /// the UserUpdateError Event + /// the UserUpdateError Event. /// /// ----------------------------------------------------------------------------- public class UserUpdateErrorArgs : BaseUserEventArgs - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new UserUpdateErrorArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new UserUpdateErrorArgs. /// - /// The Id of the User - /// The user name of the User - /// The error message + /// The Id of the User. + /// The user name of the User. + /// The error message. /// ----------------------------------------------------------------------------- public UserUpdateErrorArgs(int id, string name, string message) { - UserId = id; - UserName = name; - Message = message; + this.UserId = id; + this.UserName = name; + this.Message = message; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the error message + /// Gets or sets and sets the error message. /// /// ----------------------------------------------------------------------------- public string Message { get; set; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Modules/VisibilityState.cs b/DNN Platform/Library/Entities/Modules/VisibilityState.cs index c8f83c433a8..1dfd6c89bff 100644 --- a/DNN Platform/Library/Entities/Modules/VisibilityState.cs +++ b/DNN Platform/Library/Entities/Modules/VisibilityState.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules { /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Entities.Modules - /// Class : VisibilityState + /// Class : VisibilityState /// ----------------------------------------------------------------------------- /// - /// The VisibilityState enum provides an enumeration of the Visibility options + /// The VisibilityState enum provides an enumeration of the Visibility options. /// /// ----------------------------------------------------------------------------- public enum VisibilityState { Maximized, Minimized, - None + None, } } diff --git a/DNN Platform/Library/Entities/Portals/Data/DataService.cs b/DNN Platform/Library/Entities/Portals/Data/DataService.cs index c1a029cc846..5084175e0fe 100644 --- a/DNN Platform/Library/Entities/Portals/Data/DataService.cs +++ b/DNN Platform/Library/Entities/Portals/Data/DataService.cs @@ -1,59 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Data; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals.Data { + using System.Data; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + public class DataService : ComponentBase, IDataService { private readonly DataProvider _provider = DataProvider.Instance(); public int AddPortalGroup(PortalGroupInfo portalGroup, int createdByUserId) { - return _provider.ExecuteScalar("AddPortalGroup", - portalGroup.PortalGroupName, - portalGroup.PortalGroupDescription, - portalGroup.MasterPortalId, - portalGroup.AuthenticationDomain, - createdByUserId); + return this._provider.ExecuteScalar( + "AddPortalGroup", + portalGroup.PortalGroupName, + portalGroup.PortalGroupDescription, + portalGroup.MasterPortalId, + portalGroup.AuthenticationDomain, + createdByUserId); } public void DeletePortalGroup(PortalGroupInfo portalGroup) { - _provider.ExecuteNonQuery("DeletePortalGroup", portalGroup.PortalGroupId); + this._provider.ExecuteNonQuery("DeletePortalGroup", portalGroup.PortalGroupId); } public IDataReader GetPortalGroups() { - return _provider.ExecuteReader("GetPortalGroups"); + return this._provider.ExecuteReader("GetPortalGroups"); } public void UpdatePortalGroup(PortalGroupInfo portalGroup, int lastModifiedByUserId) { - _provider.ExecuteNonQuery("UpdatePortalGroup", - portalGroup.PortalGroupId, - portalGroup.PortalGroupName, - portalGroup.PortalGroupDescription, - portalGroup.AuthenticationDomain, - lastModifiedByUserId); + this._provider.ExecuteNonQuery( + "UpdatePortalGroup", + portalGroup.PortalGroupId, + portalGroup.PortalGroupName, + portalGroup.PortalGroupDescription, + portalGroup.AuthenticationDomain, + lastModifiedByUserId); } public IDataReader GetSharedModulesWithPortal(PortalInfo portal) { - return _provider.ExecuteReader("GetSharedModulesWithPortal", portal.PortalID); + return this._provider.ExecuteReader("GetSharedModulesWithPortal", portal.PortalID); } public IDataReader GetSharedModulesByPortal(PortalInfo portal) { - return _provider.ExecuteReader("GetSharedModulesByPortal", portal.PortalID); + return this._provider.ExecuteReader("GetSharedModulesByPortal", portal.PortalID); } } } diff --git a/DNN Platform/Library/Entities/Portals/Data/IDataService.cs b/DNN Platform/Library/Entities/Portals/Data/IDataService.cs index 170f5359be7..0e3351d53d0 100644 --- a/DNN Platform/Library/Entities/Portals/Data/IDataService.cs +++ b/DNN Platform/Library/Entities/Portals/Data/IDataService.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals.Data { + using System.Data; + public interface IDataService { int AddPortalGroup(PortalGroupInfo portalGroup, int createdByUserId); @@ -21,18 +16,17 @@ public interface IDataService void UpdatePortalGroup(PortalGroupInfo portalGroup, int lastModifiedByUserId); /// - /// Gets all shared modules with the specified Portal by another owner portals + /// Gets all shared modules with the specified Portal by another owner portals. /// - /// The Portal - /// A list of ModuleInfo objects + /// The Portal. + /// A list of ModuleInfo objects. IDataReader GetSharedModulesWithPortal(PortalInfo portal); /// - /// Gets all shared modules by the specified Portal with another portals + /// Gets all shared modules by the specified Portal with another portals. /// - /// The owner Portal - /// A list of ModuleInfo objects + /// The owner Portal. + /// A list of ModuleInfo objects. IDataReader GetSharedModulesByPortal(PortalInfo portal); - } } diff --git a/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs b/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs index 1397d054fc3..6424e2724eb 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System.Collections.Generic; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -13,39 +13,39 @@ namespace DotNetNuke.Entities.Portals public interface IPortalAliasController { /// - /// Add a new Portal Alias + /// Add a new Portal Alias. /// - /// The portal alias to add - /// The Id of the newly added portal alias + /// The portal alias to add. + /// The Id of the newly added portal alias. int AddPortalAlias(PortalAliasInfo portalAlias); /// - /// Delete a Portal Alias + /// Delete a Portal Alias. /// - /// The portal alias to remove + /// The portal alias to remove. void DeletePortalAlias(PortalAliasInfo portalAlias); /// /// Gets the portal alias info. /// /// The portal alias. - /// Portal alias info + /// Portal alias info. PortalAliasInfo GetPortalAlias(string alias); /// /// Gets the portal alias info. /// /// The portal alias. - /// The Id of the portal in question - /// Portal alias info + /// The Id of the portal in question. + /// Portal alias info. PortalAliasInfo GetPortalAlias(string alias, int portalId); PortalAliasInfo GetPortalAliasByPortalAliasID(int portalAliasId); /// - /// Gets all the portal aliases defined + /// Gets all the portal aliases defined. /// - /// A dictionary keyed by the HTTP Alias + /// A dictionary keyed by the HTTP Alias. PortalAliasCollection GetPortalAliases(); /// diff --git a/DNN Platform/Library/Entities/Portals/IPortalController.cs b/DNN Platform/Library/Entities/Portals/IPortalController.cs index 3f0321abb41..7df0a10a52f 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalController.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalController.cs @@ -1,27 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Entities.Users; + /// /// Do not implement. This interface is meant for reference and unit test purposes only. /// There is no guarantee that this interface will not change. /// - public interface IPortalController + public interface IPortalController { /// ----------------------------------------------------------------------------- /// - /// Creates a new portal alias + /// Creates a new portal alias. /// - /// Id of the portal - /// Portal Alias to be created + /// Id of the portal. + /// Portal Alias to be created. /// ----------------------------------------------------------------------------- void AddPortalAlias(int portalId, string portalAlias); @@ -67,9 +68,9 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal); /// - /// Get all the available portal templates grouped by culture + /// Get all the available portal templates grouped by culture. /// - /// List of PortalTemplateInfo objects + /// List of PortalTemplateInfo objects. IList GetAvailablePortalTemplates(); /// @@ -86,18 +87,18 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri IPortalSettings GetCurrentSettings(); /// - /// Gets information of a portal + /// Gets information of a portal. /// - /// Id of the portal - /// PortalInfo object with portal definition + /// Id of the portal. + /// PortalInfo object with portal definition. PortalInfo GetPortal(int portalId); /// - /// Gets information of a portal + /// Gets information of a portal. /// - /// Id of the portal + /// Id of the portal. /// The culture code. - /// PortalInfo object with portal definition + /// PortalInfo object with portal definition. PortalInfo GetPortal(int portalId, string cultureCode); /// @@ -115,9 +116,9 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri List GetPortalList(string cultureCode); /// - /// Gets information from all portals + /// Gets information from all portals. /// - /// ArrayList of PortalInfo objects + /// ArrayList of PortalInfo objects. ArrayList GetPortals(); /// @@ -131,7 +132,7 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri /// Gets the portal settings dictionary. /// /// The portal ID. - /// The culture code + /// The culture code. /// portal settings. Dictionary GetPortalSettings(int portalId, string cultureCode); @@ -139,35 +140,35 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri /// Gets the portal space used bytes. /// /// The portal id. - /// Space used in bytes + /// Space used in bytes. long GetPortalSpaceUsedBytes(int portalId = -1); /// - /// Load info for a portal template + /// Load info for a portal template. /// - /// The file name of the portal template - /// the culture code if any for the localization of the portal template - /// A portal template + /// The file name of the portal template. + /// the culture code if any for the localization of the portal template. + /// A portal template. PortalController.PortalTemplateInfo GetPortalTemplate(string templateFileName, string cultureCode); /// - /// Verifies if there's enough space to upload a new file on the given portal + /// Verifies if there's enough space to upload a new file on the given portal. /// - /// Id of the portal - /// Size of the file being uploaded - /// True if there's enough space available to upload the file + /// Id of the portal. + /// Size of the file being uploaded. + /// True if there's enough space available to upload the file. bool HasSpaceAvailable(int portalId, long fileSizeBytes); /// /// Remaps the Special Pages such as Home, Profile, Search - /// to their localized versions + /// to their localized versions. /// /// /// void MapLocalizedSpecialPages(int portalId, string cultureCode); /// - /// Removes the related PortalLocalization record from the database, adds optional clear cache + /// Removes the related PortalLocalization record from the database, adds optional clear cache. /// /// /// @@ -177,9 +178,9 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri /// /// Processess a template file for the new portal. /// - /// PortalId of the new portal - /// The template - /// UserId for the portal administrator. This is used to assign roles to this user + /// PortalId of the new portal. + /// The template. + /// UserId for the portal administrator. This is used to assign roles to this user. /// Flag to determine whether Module content is merged. /// Flag to determine is the template is applied to an existing portal or a new one. /// @@ -188,10 +189,10 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri void ParseTemplate(int portalId, PortalController.PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal); /// - /// Processes the resource file for the template file selected + /// Processes the resource file for the template file selected. /// - /// New portal's folder - /// full path to the resource file + /// New portal's folder. + /// full path to the resource file. /// /// The resource file is a zip file with the same name as the selected template file and with /// an extension of .resources (to disable this file being downloaded). @@ -207,7 +208,7 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri void UpdatePortalExpiry(int portalId, string cultureCode); /// - /// Updates basic portal information + /// Updates basic portal information. /// /// void UpdatePortalInfo(PortalInfo portal); @@ -220,6 +221,4 @@ int CreatePortal(string portalName, UserInfo adminUser, string description, stri /// void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure); } -} - - +} diff --git a/DNN Platform/Library/Entities/Portals/IPortalEventHandlers.cs b/DNN Platform/Library/Entities/Portals/IPortalEventHandlers.cs index ea01a6fa8db..cf320c890d0 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalEventHandlers.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalEventHandlers.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { public interface IPortalEventHandlers diff --git a/DNN Platform/Library/Entities/Portals/IPortalGroupController.cs b/DNN Platform/Library/Entities/Portals/IPortalGroupController.cs index b02173b45ae..a7d28fcd934 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalGroupController.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalGroupController.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections.Generic; + public interface IPortalGroupController { int AddPortalGroup(PortalGroupInfo portalGroup); diff --git a/DNN Platform/Library/Entities/Portals/IPortalSettingHandlers.cs b/DNN Platform/Library/Entities/Portals/IPortalSettingHandlers.cs index 13d9ec6b705..eaae424b8bb 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalSettingHandlers.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalSettingHandlers.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { public interface IPortalSettingHandlers diff --git a/DNN Platform/Library/Entities/Portals/IPortalSettingsController.cs b/DNN Platform/Library/Entities/Portals/IPortalSettingsController.cs index 485c4a34c43..dccc85c2d62 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalSettingsController.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalSettingsController.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + public interface IPortalSettingsController { void ConfigureActiveTab(PortalSettings portalSetting); @@ -16,38 +17,38 @@ public interface IPortalSettingsController /// ----------------------------------------------------------------------------- /// - /// The GetActiveTab method gets the active Tab for the current request + /// The GetActiveTab method gets the active Tab for the current request. /// /// - /// The current tab's id - /// The current PortalSettings + /// The current tab's id. + /// The current PortalSettings. /// ----------------------------------------------------------------------------- TabInfo GetActiveTab(int tabId, PortalSettings portalSettings); /// ----------------------------------------------------------------------------- /// - /// The GetTabModules method gets the list of modules for the active Tab + /// The GetTabModules method gets the list of modules for the active Tab. /// /// - /// The current PortalSettings + /// The current PortalSettings. /// ----------------------------------------------------------------------------- IList GetTabModules(PortalSettings portalSettings); - /// ----------------------------------------------------------------------------- - /// - /// The LoadPortal method loads the properties of the portal object into the Portal Settings + /// ----------------------------------------------------------------------------- + /// + /// The LoadPortal method loads the properties of the portal object into the Portal Settings. /// - /// The Portal object - /// The Portal Settings object - /// ----------------------------------------------------------------------------- + /// The Portal object. + /// The Portal Settings object. + /// ----------------------------------------------------------------------------- void LoadPortal(PortalInfo portal, PortalSettings portalSettings); - /// ----------------------------------------------------------------------------- - /// - /// The LoadPortalSettings method loads the settings into the Portal Settings + /// ----------------------------------------------------------------------------- + /// + /// The LoadPortalSettings method loads the settings into the Portal Settings. /// - /// The Portal Settings object - /// ----------------------------------------------------------------------------- + /// The Portal Settings object. + /// ----------------------------------------------------------------------------- void LoadPortalSettings(PortalSettings portalSettings); } } diff --git a/DNN Platform/Library/Entities/Portals/IPortalTemplateEventHandlers.cs b/DNN Platform/Library/Entities/Portals/IPortalTemplateEventHandlers.cs index 865cc9d7be2..2545131ed2d 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalTemplateEventHandlers.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalTemplateEventHandlers.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { public interface IPortalTemplateEventHandlers diff --git a/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs b/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs index f5e689fe2a1..5349061bbd7 100644 --- a/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs +++ b/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs @@ -1,19 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.Collections.Generic; + using System.IO; + public interface IPortalTemplateIO { IEnumerable EnumerateTemplates(); + IEnumerable EnumerateLanguageFiles(); + string GetResourceFilePath(string templateFilePath); + string GetLanguageFilePath(string templateFilePath, string cultureCode); + TextReader OpenTextReader(string filePath); } } diff --git a/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs b/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs index 0c4885dad53..64c02e67441 100644 --- a/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs +++ b/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs @@ -1,27 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities.Internal; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities.Internal; + using DotNetNuke.Framework; + public class PortalTemplateIO : ServiceLocator, IPortalTemplateIO { - protected override Func GetFactory() - { - return () => new PortalTemplateIO(); - } - - #region IPortalTemplateIO Members - public IEnumerable EnumerateTemplates() { string path = Globals.HostMapPath; @@ -43,6 +36,11 @@ public IEnumerable EnumerateLanguageFiles() return new string[0]; } + + protected override Func GetFactory() + { + return () => new PortalTemplateIO(); + } public string GetResourceFilePath(string templateFilePath) { @@ -57,7 +55,7 @@ public string GetLanguageFilePath(string templateFilePath, string cultureCode) public TextReader OpenTextReader(string filePath) { StreamReader reader = null; - + var retryable = new RetryableAction( () => reader = new StreamReader(File.Open(filePath, FileMode.Open)), filePath, 10, TimeSpan.FromMilliseconds(50), 2); @@ -69,8 +67,6 @@ public TextReader OpenTextReader(string filePath) private static string CheckFilePath(string path) { return File.Exists(path) ? path : string.Empty; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs index 83d9289c808..d16205619d6 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs @@ -1,72 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections; + [Serializable] public class PortalAliasCollection : DictionaryBase { - /// - /// Gets or sets the value associated with the specified key. - /// - public PortalAliasInfo this[string key] + /// + /// Gets a value indicating whether gets a value indicating if the collection contains keys that are not null. + /// + public bool HasKeys { get { - return (PortalAliasInfo) Dictionary[key]; - } - set - { - Dictionary[key] = value; + return this.Dictionary.Keys.Count > 0; } } - /// - /// Gets a value indicating if the collection contains keys that are not null. - /// - public Boolean HasKeys + public ICollection Keys { get { - return Dictionary.Keys.Count > 0; + return this.Dictionary.Keys; } } - public ICollection Keys + public ICollection Values { get { - return Dictionary.Keys; + return this.Dictionary.Values; } } - - public ICollection Values + + /// + /// Gets or sets the value associated with the specified key. + /// + public PortalAliasInfo this[string key] { get { - return Dictionary.Values; + return (PortalAliasInfo)this.Dictionary[key]; + } + + set + { + this.Dictionary[key] = value; } } - public bool Contains(String key) + public bool Contains(string key) { - return Dictionary.Contains(key); + return this.Dictionary.Contains(key); } - /// - /// Adds an entry to the collection. - /// - public void Add(String key, PortalAliasInfo value) + /// + /// Adds an entry to the collection. + /// + public void Add(string key, PortalAliasInfo value) { - Dictionary.Add(key, value); + this.Dictionary.Add(key, value); } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs index 81b6ac8842b..10605964014 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs @@ -1,46 +1,162 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals.Internal; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { - /// - /// PortalAliasController provides method to manage portal alias. - /// - /// - /// For DotNetNuke to know what site a request should load, it uses a system of portal aliases. - /// When a request is recieved by DotNetNuke from IIS, it extracts the domain name portion and does a comparison against - /// the list of portal aliases and then redirects to the relevant portal to load the approriate page. - /// + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals.Internal; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Log.EventLog; + + /// + /// PortalAliasController provides method to manage portal alias. + /// + /// + /// For DotNetNuke to know what site a request should load, it uses a system of portal aliases. + /// When a request is recieved by DotNetNuke from IIS, it extracts the domain name portion and does a comparison against + /// the list of portal aliases and then redirects to the relevant portal to load the approriate page. + /// public partial class PortalAliasController : ServiceLocator, IPortalAliasController { - protected override Func GetFactory() + /// + /// Gets the portal alias by portal. + /// + /// The portal id. + /// The portal alias. + /// Portal alias. + public static string GetPortalAliasByPortal(int portalId, string portalAlias) { - return () => new PortalAliasController(); + string retValue = string.Empty; + bool foundAlias = false; + PortalAliasInfo portalAliasInfo = Instance.GetPortalAlias(portalAlias, portalId); + if (portalAliasInfo != null) + { + retValue = portalAliasInfo.HTTPAlias; + foundAlias = true; + } + + if (!foundAlias) + { + // searching from longest to shortest alias ensures that the most specific portal is matched first + // In some cases this method has been called with "portalaliases" that were not exactly the real portal alias + // the startswith behaviour is preserved here to support those non-specific uses + var controller = new PortalAliasController(); + var portalAliases = controller.GetPortalAliasesInternal(); + var portalAliasCollection = portalAliases.OrderByDescending(k => k.Key.Length); + + foreach (var currentAlias in portalAliasCollection) + { + // check if the alias key starts with the portal alias value passed in - we use + // StartsWith because child portals are redirected to the parent portal domain name + // eg. child = 'www.domain.com/child' and parent is 'www.domain.com' + // this allows the parent domain name to resolve to the child alias ( the tabid still identifies the child portalid ) + string httpAlias = currentAlias.Value.HTTPAlias.ToLowerInvariant(); + if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) + { + retValue = currentAlias.Value.HTTPAlias; + break; + } + + httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); + if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) + { + retValue = currentAlias.Value.HTTPAlias; + break; + } + } + } + + return retValue; + } + + /// + /// Gets the portal alias by tab. + /// + /// The tab ID. + /// The portal alias. + /// Portal alias. + public static string GetPortalAliasByTab(int tabId, string portalAlias) + { + string retValue = Null.NullString; + int intPortalId = -2; + + // get the tab + TabInfo tab = TabController.Instance.GetTab(tabId, Null.NullInteger); + if (tab != null) + { + // ignore deleted tabs + if (!tab.IsDeleted) + { + intPortalId = tab.PortalID; + } + } + + switch (intPortalId) + { + case -2: // tab does not exist + break; + case -1: // host tab + // host tabs are not verified to determine if they belong to the portal alias + retValue = portalAlias; + break; + default: // portal tab + retValue = GetPortalAliasByPortal(intPortalId, portalAlias); + break; + } + + return retValue; + } + + public int AddPortalAlias(PortalAliasInfo portalAlias) + { + // Add Alias + var dataProvider = DataProvider.Instance(); + int Id = dataProvider.AddPortalAlias( + portalAlias.PortalID, + portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), + portalAlias.CultureCode, + portalAlias.Skin, + portalAlias.BrowserType.ToString(), + portalAlias.IsPrimary, + UserController.Instance.GetCurrentUserInfo().UserID); + + // Log Event + LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_CREATED); + + // clear portal alias cache + ClearCache(true); + + return Id; } - #region Private Methods + public void DeletePortalAlias(PortalAliasInfo portalAlias) + { + // Delete Alias + DataProvider.Instance().DeletePortalAlias(portalAlias.PortalAliasID); + + // Log Event + LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_DELETED); + // clear portal alias cache + ClearCache(false, portalAlias.PortalID); + } + + protected override Func GetFactory() + { + return () => new PortalAliasController(); + } + private static void ClearCache(bool refreshServiceRoutes, int portalId = -1) { DataCache.RemoveCache(DataCache.PortalAliasCacheKey); @@ -57,142 +173,111 @@ private static void ClearCache(bool refreshServiceRoutes, int portalId = -1) } } - private PortalAliasInfo GetPortalAliasLookupInternal(string alias) - { - return GetPortalAliasesInternal().SingleOrDefault(pa => pa.Key == alias).Value; + private static void LogEvent(PortalAliasInfo portalAlias, EventLogController.EventLogType logType) + { + int userId = UserController.Instance.GetCurrentUserInfo().UserID; + EventLogController.Instance.AddLog(portalAlias, PortalController.Instance.GetCurrentPortalSettings(), userId, string.Empty, logType); + } + + private static bool ValidateAlias(string portalAlias, bool ischild, bool isDomain) + { + string validChars = "abcdefghijklmnopqrstuvwxyz0123456789-/"; + if (!ischild) + { + validChars += ".:"; + } + + if (!isDomain) + { + validChars += "_"; + } + + return portalAlias.All(c => validChars.Contains(c.ToString())); + } + + private PortalAliasInfo GetPortalAliasLookupInternal(string alias) + { + return this.GetPortalAliasesInternal().SingleOrDefault(pa => pa.Key == alias).Value; } private PortalAliasInfo GetPortalAliasInternal(string httpAlias) - { + { string strPortalAlias; - //try the specified alias first - PortalAliasInfo portalAlias = GetPortalAliasLookupInternal(httpAlias.ToLowerInvariant()); + // try the specified alias first + PortalAliasInfo portalAlias = this.GetPortalAliasLookupInternal(httpAlias.ToLowerInvariant()); - //domain.com and www.domain.com should be synonymous + // domain.com and www.domain.com should be synonymous if (portalAlias == null) { if (httpAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) { - //try alias without the "www." prefix - strPortalAlias = httpAlias.Replace("www.", ""); + // try alias without the "www." prefix + strPortalAlias = httpAlias.Replace("www.", string.Empty); } - else //try the alias with the "www." prefix + else // try the alias with the "www." prefix { strPortalAlias = string.Concat("www.", httpAlias); } - //perform the lookup - portalAlias = GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); + + // perform the lookup + portalAlias = this.GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); } - //allow domain wildcards + + // allow domain wildcards if (portalAlias == null) { - //remove the domain prefix ( ie. anything.domain.com = domain.com ) + // remove the domain prefix ( ie. anything.domain.com = domain.com ) if (httpAlias.IndexOf(".", StringComparison.Ordinal) != -1) { strPortalAlias = httpAlias.Substring(httpAlias.IndexOf(".", StringComparison.Ordinal) + 1); } - else //be sure we have a clean string (without leftovers from preceding 'if' block) + else // be sure we have a clean string (without leftovers from preceding 'if' block) { strPortalAlias = httpAlias; } - //try an explicit lookup using the wildcard entry ( ie. *.domain.com ) - portalAlias = GetPortalAliasLookupInternal("*." + strPortalAlias.ToLowerInvariant()) ?? - GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); + + // try an explicit lookup using the wildcard entry ( ie. *.domain.com ) + portalAlias = this.GetPortalAliasLookupInternal("*." + strPortalAlias.ToLowerInvariant()) ?? + this.GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); if (portalAlias == null) { - //try a lookup using "www." + raw domain - portalAlias = GetPortalAliasLookupInternal("www." + strPortalAlias.ToLowerInvariant()); + // try a lookup using "www." + raw domain + portalAlias = this.GetPortalAliasLookupInternal("www." + strPortalAlias.ToLowerInvariant()); } } + if (portalAlias == null) { - //check if this is a fresh install ( no alias values in collection ) + // check if this is a fresh install ( no alias values in collection ) var controller = new PortalAliasController(); var portalAliases = controller.GetPortalAliasesInternal(); if (portalAliases.Keys.Count == 0 || (portalAliases.Count == 1 && portalAliases.ContainsKey("_default"))) { - //relate the PortalAlias to the default portal on a fresh database installation + // relate the PortalAlias to the default portal on a fresh database installation DataProvider.Instance().UpdatePortalAlias(httpAlias.ToLowerInvariant().Trim('/'), UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog("PortalAlias", - httpAlias, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTALALIAS_UPDATED); - - //clear the cachekey "GetPortalByAlias" otherwise portalalias "_default" stays in cache after first install + EventLogController.Instance.AddLog( + "PortalAlias", + httpAlias, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALALIAS_UPDATED); + + // clear the cachekey "GetPortalByAlias" otherwise portalalias "_default" stays in cache after first install DataCache.RemoveCache("GetPortalByAlias"); - //try again - portalAlias = GetPortalAliasLookupInternal(httpAlias.ToLowerInvariant()); + + // try again + portalAlias = this.GetPortalAliasLookupInternal(httpAlias.ToLowerInvariant()); } } + return portalAlias; - - } - - private static void LogEvent(PortalAliasInfo portalAlias, EventLogController.EventLogType logType) - { - int userId = UserController.Instance.GetCurrentUserInfo().UserID; - EventLogController.Instance.AddLog(portalAlias, PortalController.Instance.GetCurrentPortalSettings(), userId, "", logType); - } - - private static bool ValidateAlias(string portalAlias, bool ischild, bool isDomain) - { - string validChars = "abcdefghijklmnopqrstuvwxyz0123456789-/"; - if (!ischild) - { - validChars += ".:"; - } - - if (!isDomain) - { - validChars += "_"; - } - - return portalAlias.All(c => validChars.Contains(c.ToString())); - } - - #endregion - - #region Public Methods - - public int AddPortalAlias(PortalAliasInfo portalAlias) - { - //Add Alias - var dataProvider = DataProvider.Instance(); - int Id = dataProvider.AddPortalAlias(portalAlias.PortalID, - portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), - portalAlias.CultureCode, - portalAlias.Skin, - portalAlias.BrowserType.ToString(), - portalAlias.IsPrimary, - UserController.Instance.GetCurrentUserInfo().UserID); - - //Log Event - LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_CREATED); - - //clear portal alias cache - ClearCache(true); - - return Id; - } - - public void DeletePortalAlias(PortalAliasInfo portalAlias) - { - //Delete Alias - DataProvider.Instance().DeletePortalAlias(portalAlias.PortalAliasID); - - //Log Event - LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_DELETED); - - //clear portal alias cache - ClearCache(false, portalAlias.PortalID); } public PortalAliasInfo GetPortalAlias(string alias) { - return GetPortalAliasInternal(alias); + return this.GetPortalAliasInternal(alias); } /// @@ -203,7 +288,7 @@ public PortalAliasInfo GetPortalAlias(string alias) /// Portal Alias Info. public PortalAliasInfo GetPortalAlias(string alias, int portalId) { - return GetPortalAliasesInternal().SingleOrDefault(pa => pa.Key.Equals(alias, StringComparison.InvariantCultureIgnoreCase) && pa.Value.PortalID == portalId).Value; + return this.GetPortalAliasesInternal().SingleOrDefault(pa => pa.Key.Equals(alias, StringComparison.InvariantCultureIgnoreCase) && pa.Value.PortalID == portalId).Value; } /// @@ -213,37 +298,40 @@ public PortalAliasInfo GetPortalAlias(string alias, int portalId) /// Portal alias info. public PortalAliasInfo GetPortalAliasByPortalAliasID(int portalAliasId) { - return GetPortalAliasesInternal().SingleOrDefault(pa => pa.Value.PortalAliasID == portalAliasId).Value; + return this.GetPortalAliasesInternal().SingleOrDefault(pa => pa.Value.PortalAliasID == portalAliasId).Value; } - internal Dictionary GetPortalAliasesInternal() + public PortalAliasCollection GetPortalAliases() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.PortalAliasCacheKey, - DataCache.PortalAliasCacheTimeOut, - DataCache.PortalAliasCachePriority), - c => - { - var dic = CBO.FillDictionary("HTTPAlias", - DataProvider.Instance().GetPortalAliases()); - return dic.Keys.ToDictionary(key => key.ToLowerInvariant(), key => dic[key]); - }, - true); - } - - public PortalAliasCollection GetPortalAliases() - { - var aliasCollection = new PortalAliasCollection(); - foreach (var alias in GetPortalAliasesInternal().Values) - { - aliasCollection.Add(alias.HTTPAlias, alias); - } + var aliasCollection = new PortalAliasCollection(); + foreach (var alias in this.GetPortalAliasesInternal().Values) + { + aliasCollection.Add(alias.HTTPAlias, alias); + } return aliasCollection; } public IEnumerable GetPortalAliasesByPortalId(int portalId) { - return GetPortalAliasesInternal().Values.Where(alias => alias.PortalID == portalId).ToList(); + return this.GetPortalAliasesInternal().Values.Where(alias => alias.PortalID == portalId).ToList(); + } + + internal Dictionary GetPortalAliasesInternal() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PortalAliasCacheKey, + DataCache.PortalAliasCacheTimeOut, + DataCache.PortalAliasCachePriority), + c => + { + var dic = CBO.FillDictionary( + "HTTPAlias", + DataProvider.Instance().GetPortalAliases()); + return dic.Keys.ToDictionary(key => key.ToLowerInvariant(), key => dic[key]); + }, + true); } /// @@ -258,110 +346,23 @@ public PortalInfo GetPortalByPortalAliasID(int PortalAliasId) public void UpdatePortalAlias(PortalAliasInfo portalAlias) { - //Update Alias - DataProvider.Instance().UpdatePortalAliasInfo(portalAlias.PortalAliasID, - portalAlias.PortalID, - portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), - portalAlias.CultureCode, - portalAlias.Skin, - portalAlias.BrowserType.ToString(), - portalAlias.IsPrimary, - UserController.Instance.GetCurrentUserInfo().UserID); - //Log Event + // Update Alias + DataProvider.Instance().UpdatePortalAliasInfo( + portalAlias.PortalAliasID, + portalAlias.PortalID, + portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), + portalAlias.CultureCode, + portalAlias.Skin, + portalAlias.BrowserType.ToString(), + portalAlias.IsPrimary, + UserController.Instance.GetCurrentUserInfo().UserID); + + // Log Event LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_UPDATED); - //clear portal alias cache + // clear portal alias cache ClearCache(false); - } - - #endregion - - #region Public Static Helper Methods - - /// - /// Gets the portal alias by portal. - /// - /// The portal id. - /// The portal alias. - /// Portal alias. - public static string GetPortalAliasByPortal(int portalId, string portalAlias) - { - string retValue = ""; - bool foundAlias = false; - PortalAliasInfo portalAliasInfo = Instance.GetPortalAlias(portalAlias, portalId); - if (portalAliasInfo != null) - { - retValue = portalAliasInfo.HTTPAlias; - foundAlias = true; - } - - if (!foundAlias) - { - //searching from longest to shortest alias ensures that the most specific portal is matched first - //In some cases this method has been called with "portalaliases" that were not exactly the real portal alias - //the startswith behaviour is preserved here to support those non-specific uses - var controller = new PortalAliasController(); - var portalAliases = controller.GetPortalAliasesInternal(); - var portalAliasCollection = portalAliases.OrderByDescending(k => k.Key.Length); - - foreach (var currentAlias in portalAliasCollection) - { - // check if the alias key starts with the portal alias value passed in - we use - // StartsWith because child portals are redirected to the parent portal domain name - // eg. child = 'www.domain.com/child' and parent is 'www.domain.com' - // this allows the parent domain name to resolve to the child alias ( the tabid still identifies the child portalid ) - string httpAlias = currentAlias.Value.HTTPAlias.ToLowerInvariant(); - if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) - { - retValue = currentAlias.Value.HTTPAlias; - break; - } - httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", "") : string.Concat("www.", httpAlias); - if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) - { - retValue = currentAlias.Value.HTTPAlias; - break; - } - } - } - return retValue; - } - - /// - /// Gets the portal alias by tab. - /// - /// The tab ID. - /// The portal alias. - /// Portal alias. - public static string GetPortalAliasByTab(int tabId, string portalAlias) - { - string retValue = Null.NullString; - int intPortalId = -2; - - //get the tab - TabInfo tab = TabController.Instance.GetTab(tabId, Null.NullInteger); - if (tab != null) - { - //ignore deleted tabs - if (!tab.IsDeleted) - { - intPortalId = tab.PortalID; - } - } - switch (intPortalId) - { - case -2: //tab does not exist - break; - case -1: //host tab - //host tabs are not verified to determine if they belong to the portal alias - retValue = portalAlias; - break; - default: //portal tab - retValue = GetPortalAliasByPortal(intPortalId, portalAlias); - break; - } - return retValue; - } + } /// /// Validates the alias. @@ -375,15 +376,15 @@ public static bool ValidateAlias(string portalAlias, bool ischild) { return ValidateAlias(portalAlias, true, false); } - //validate the domain + + // validate the domain Uri result; if (Uri.TryCreate(Globals.AddHTTP(portalAlias), UriKind.Absolute, out result)) { return ValidateAlias(result.Host, false, true) && ValidateAlias(portalAlias, false, false); } + return false; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs b/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs index 3e35806dee0..4bc9bfb4e88 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs @@ -1,28 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web; - -using DotNetNuke.Entities.Urls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Web; + + using DotNetNuke.Entities.Urls; + public static class PortalAliasExtensions { public static bool ContainsAlias(this IEnumerable aliases, int portalId, string httpAlias) { return aliases.Where(alias => alias.PortalID == portalId || portalId == -1) - .Any(alias => String.Compare(alias.HTTPAlias, httpAlias, StringComparison.OrdinalIgnoreCase) == 0); + .Any(alias => string.Compare(alias.HTTPAlias, httpAlias, StringComparison.OrdinalIgnoreCase) == 0); } public static bool ContainsSpecificSkins(this IEnumerable aliases) { - return aliases.Any(alias => !String.IsNullOrEmpty(alias.Skin)); + return aliases.Any(alias => !string.IsNullOrEmpty(alias.Skin)); } public static Dictionary GetAliasesAndCulturesForPortalId(this IEnumerable aliases, int portalId) @@ -35,11 +35,12 @@ public static Dictionary GetAliasesAndCulturesForPortalId(this I aliasCultures.Add(cpa.HTTPAlias.ToLowerInvariant(), cpa.CultureCode); } } + return aliasCultures; } /// - /// Returns the chosen portal alias for a specific portal Id and culture Code + /// Returns the chosen portal alias for a specific portal Id and culture Code. /// /// /// @@ -49,13 +50,15 @@ public static Dictionary GetAliasesAndCulturesForPortalId(this I public static PortalAliasInfo GetAliasByPortalIdAndSettings(this IEnumerable aliases, int portalId, UrlAction result, string cultureCode, FriendlyUrlSettings settings) { var browserType = BrowserTypes.Normal; - //if required, and possible, detect browser type + + // if required, and possible, detect browser type if (HttpContext.Current != null && settings != null) { HttpRequest request = HttpContext.Current.Request; HttpResponse response = HttpContext.Current.Response; browserType = FriendlyUrlController.GetBrowserType(request, response, settings); } + return GetAliasByPortalIdAndSettings(aliases, portalId, result, cultureCode, browserType); } @@ -63,7 +66,8 @@ public static PortalAliasInfo GetAliasByPortalIdAndSettings(this IEnumerable - /// Returns a ChosenPortalAlias object where the portalId, culture code and isMobile matches + /// Returns a ChosenPortalAlias object where the portalId, culture code and isMobile matches. /// /// /// /// /// /// - /// A ChosenPOrtalAlias - /// Note will return a best-match by portal if no specific culture Code match found + /// A ChosenPOrtalAlias. + /// Note will return a best-match by portal if no specific culture Code match found. public static PortalAliasInfo GetAliasByPortalIdAndSettings(this IEnumerable aliases, int portalId, UrlAction result, string cultureCode, BrowserTypes browserType) { var aliasList = aliases.ToList(); - //First check if our current alias is already a perfect match. + // First check if our current alias is already a perfect match. PortalAliasInfo foundAlias = null; if (result != null && !string.IsNullOrEmpty(result.HttpAlias)) { - //try to find exact match + // try to find exact match foundAlias = aliasList.FirstOrDefault(a => a.BrowserType == browserType && - (String.Compare(a.CultureCode, cultureCode, + (string.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0) && a.PortalID == portalId && a.HTTPAlias == result.HttpAlias); - if (foundAlias == null) //let us try again using Startswith() to find matching Hosts + if (foundAlias == null) // let us try again using Startswith() to find matching Hosts { foundAlias = aliasList.FirstOrDefault(a => a.BrowserType == browserType && - (String.Compare(a.CultureCode, cultureCode, + (string.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0) && a.PortalID == portalId && a.HTTPAlias.StartsWith(result.HttpAlias.Split('/')[0])); } } - //27138 : Redirect loop caused by duplicate primary aliases. Changed to only check by browserType/Culture code which makes a primary alias + + // 27138 : Redirect loop caused by duplicate primary aliases. Changed to only check by browserType/Culture code which makes a primary alias if (foundAlias == null) { foundAlias = aliasList.Where(a => a.BrowserType == browserType - && (String.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0 || String.IsNullOrEmpty(a.CultureCode)) + && (string.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0 || string.IsNullOrEmpty(a.CultureCode)) && a.PortalID == portalId) .OrderByDescending(a => a.IsPrimary) .ThenByDescending(a => a.CultureCode) .FirstOrDefault(); } - //JIRA DNN-4882 : DevPCI fix bug with url Mobile -> Search alias with culture code + // JIRA DNN-4882 : DevPCI fix bug with url Mobile -> Search alias with culture code // START DNN-4882 if (foundAlias == null) { - foundAlias = aliasList.Where(a => (String.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0 || String.IsNullOrEmpty(a.CultureCode)) + foundAlias = aliasList.Where(a => (string.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0 || string.IsNullOrEmpty(a.CultureCode)) && a.PortalID == portalId) .OrderByDescending(a => a.IsPrimary) .ThenByDescending(a => a.CultureCode) .FirstOrDefault(); } + // END DNN-4882 - if (foundAlias != null) { if (result != null && result.PortalAlias != null) @@ -181,13 +187,14 @@ public static List GetAliasesForPortalId(this IEnumerable aliases, int portalId, string alias) { return (from cpa in aliases - where cpa.PortalID == portalId && String.Compare(alias, cpa.HTTPAlias, StringComparison.OrdinalIgnoreCase) == 0 + where cpa.PortalID == portalId && string.Compare(alias, cpa.HTTPAlias, StringComparison.OrdinalIgnoreCase) == 0 select cpa.CultureCode) .FirstOrDefault(); } @@ -196,21 +203,20 @@ public static void GetSettingsByPortalIdAndAlias(this IEnumerable - /// PoralController provides business layer of poatal. - /// - /// - /// DotNetNuke supports the concept of virtualised sites in a single install. This means that multiple sites, - /// each potentially with multiple unique URL's, can exist in one instance of DotNetNuke i.e. one set of files and one database. - /// + /// PoralController provides business layer of poatal. + /// + /// + /// DotNetNuke supports the concept of virtualised sites in a single install. This means that multiple sites, + /// each potentially with multiple unique URL's, can exist in one instance of DotNetNuke i.e. one set of files and one database. + /// public partial class PortalController : ServiceLocator, IPortalController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); - public const string HtmlText_TimeToAutoSave = "HtmlText_TimeToAutoSave"; public const string HtmlText_AutoSaveEnabled = "HtmlText_AutoSaveEnabled"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); + protected const string HttpContextKeyPortalSettingsDictionary = "PortalSettingsDictionary{0}{1}"; - protected override Func GetFactory() + /// + /// Adds the portal dictionary. + /// + /// The portal id. + /// The tab id. + public static void AddPortalDictionary(int portalId, int tabId) { - return () => new PortalController(); + var portalDic = GetPortalDictionary(); + portalDic[tabId] = portalId; + DataCache.SetCache(DataCache.PortalDictionaryCacheKey, portalDic); } - #region Private Methods + /// + /// Creates the root folder for a child portal. + /// + /// + /// If call this method, it will create the specific folder if the folder doesn't exist; + /// and will copy subhost.aspx to the folder if there is no 'Default.aspx'. + /// + /// The child path. + /// + /// If the method executed successful, it will return NullString, otherwise return error message. + /// + /// + /// + /// string childPhysicalPath = Server.MapPath(childPath); + /// message = PortalController.CreateChildPortalFolder(childPhysicalPath); + /// + /// + public static string CreateChildPortalFolder(string ChildPath) + { + string message = Null.NullString; + + // Set up Child Portal + try + { + // create the subdirectory for the new portal + if (!Directory.Exists(ChildPath)) + { + Directory.CreateDirectory(ChildPath); + } - private void AddFolderPermissions(int portalId, int folderId) + // create the subhost default.aspx file + if (!File.Exists(ChildPath + "\\" + Globals.glbDefaultPage)) + { + File.Copy(Globals.HostMapPath + "subhost.aspx", ChildPath + "\\" + Globals.glbDefaultPage); + } + } + catch (Exception Exc) + { + Logger.Error(Exc); + message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; + } + + return message; + } + + /// + /// Creates a new portal alias. + /// + /// Id of the portal. + /// Portal Alias to be created. + public void AddPortalAlias(int portalId, string portalAlias) { - var portal = GetPortal(portalId); - var folderManager = FolderManager.Instance; - var folder = folderManager.GetFolder(folderId); - var permissionController = new PermissionController(); - foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "")) + // Check if the Alias exists + PortalAliasInfo portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalId); + + // If alias does not exist add new + if (portalAliasInfo == null) { - var folderPermission = new FolderPermissionInfo(permission) + portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = portalAlias, IsPrimary = true }; + PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); + } + } + + /// + /// Copies the page template. + /// + /// The template file. + /// The mapped home directory. + public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) + { + string hostTemplateFile = string.Format("{0}Templates\\{1}", Globals.HostMapPath, templateFile); + if (File.Exists(hostTemplateFile)) + { + string portalTemplateFolder = string.Format("{0}Templates\\", mappedHomeDirectory); + if (!Directory.Exists(portalTemplateFolder)) { - FolderID = folder.FolderID, - RoleID = portal.AdministratorRoleId, - AllowAccess = true - }; + // Create Portal Templates folder + Directory.CreateDirectory(portalTemplateFolder); + } - folder.FolderPermissions.Add(folderPermission); - if (permission.PermissionKey == "READ") + string portalTemplateFile = portalTemplateFolder + templateFile; + if (!File.Exists(portalTemplateFile)) { - //add READ permissions to the All Users Role - folderManager.AddAllUserReadPermission(folder, permission); + File.Copy(hostTemplateFile, portalTemplateFile); } } - FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); + } + + internal static void EnsureRequiredEventLogTypesExist() + { + if (!DoesLogTypeExists(EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString())) + { + // Add 404 Log + var logTypeInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), + LogTypeFriendlyName = "HTTP Error Code 404 Page Not Found", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeInfo); + + // Add LogType + var logTypeConf = new LogTypeConfigInfo + { + LoggingIsActive = true, + LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeConf); + } + + if (!DoesLogTypeExists(EventLogController.EventLogType.IP_LOGIN_BANNED.ToString())) + { + // Add IP filter log type + var logTypeFilterInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), + LogTypeFriendlyName = "HTTP Error Code Forbidden IP address rejected", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeFilterInfo); + + // Add LogType + var logTypeFilterConf = new LogTypeConfigInfo + { + LoggingIsActive = true, + LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); + } + + if (!DoesLogTypeExists(EventLogController.EventLogType.TABURL_CREATED.ToString())) + { + var logTypeInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), + LogTypeFriendlyName = "TabURL created", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationSuccess", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeInfo); + + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL updated"; + LogController.Instance.AddLogType(logTypeInfo); + + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; + LogController.Instance.AddLogType(logTypeInfo); + + // Add LogType + var logTypeUrlConf = new LogTypeConfigInfo + { + LoggingIsActive = false, + LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + + logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + + logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + } + + if (!DoesLogTypeExists(EventLogController.EventLogType.SCRIPT_COLLISION.ToString())) + { + // Add IP filter log type + var logTypeFilterInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), + LogTypeFriendlyName = "Javscript library registration resolved script collision", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeFilterInfo); + + // Add LogType + var logTypeFilterConf = new LogTypeConfigInfo + { + LoggingIsActive = true, + LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); + } + } + + protected override Func GetFactory() + { + return () => new PortalController(); } private static void CreateDefaultPortalRoles(int portalId, int administratorId, ref int administratorRoleId, ref int registeredRoleId, ref int subscriberRoleId, int unverifiedRoleId) { - //create required roles if not already created + // create required roles if not already created if (administratorRoleId == -1) { administratorRoleId = CreateRole(portalId, "Administrators", "Administrators of this Website", 0, 0, "M", 0, 0, "N", false, false); } + if (registeredRoleId == -1) { registeredRoleId = CreateRole(portalId, "Registered Users", "Registered Users", 0, 0, "M", 0, 0, "N", false, true); } + if (subscriberRoleId == -1) { subscriberRoleId = CreateRole(portalId, "Subscribers", "A public role for site subscriptions", 0, 0, "M", 0, 0, "N", true, true); } + if (unverifiedRoleId == -1) { CreateRole(portalId, "Unverified Users", "Unverified Users", 0, 0, "M", 0, 0, "N", false, false); } + RoleController.Instance.AddUserRole(portalId, administratorId, administratorRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); RoleController.Instance.AddUserRole(portalId, administratorId, registeredRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); RoleController.Instance.AddUserRole(portalId, administratorId, subscriberRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); } + private static string CreateProfileDefinitions(int portalId, string templateFilePath) + { + string strMessage = Null.NullString; + try + { + // add profile definitions + XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; + + // open the XML template file + try + { + xmlDoc.Load(templateFilePath); + } + catch (Exception ex) + { + Logger.Error(ex); + } + + // parse profile definitions if available + var node = xmlDoc.SelectSingleNode("//portal/profiledefinitions"); + if (node != null) + { + ParseProfileDefinitions(node, portalId); + } + else // template does not contain profile definitions ( ie. was created prior to DNN 3.3.0 ) + { + ProfileController.AddDefaultDefinitions(portalId); + } + } + catch (Exception ex) + { + strMessage = Localization.GetString("CreateProfileDefinitions.Error"); + Exceptions.LogException(ex); + } + + return strMessage; + } + + private static int CreatePortal(string portalName, string homeDirectory, string cultureCode) + { + // add portal + int PortalId = -1; + try + { + // Use host settings as default values for these parameters + // This can be overwritten on the portal template + var datExpiryDate = Host.Host.DemoPeriod > Null.NullInteger + ? Convert.ToDateTime(Globals.GetMediumDate(DateTime.Now.AddDays(Host.Host.DemoPeriod).ToString(CultureInfo.InvariantCulture))) + : Null.NullDate; + + PortalId = DataProvider.Instance().CreatePortal( + portalName, + Host.Host.HostCurrency, + datExpiryDate, + Host.Host.HostFee, + Host.Host.HostSpace, + Host.Host.PageQuota, + Host.Host.UserQuota, + 0, // site log history function has been removed. + homeDirectory, + cultureCode, + UserController.Instance.GetCurrentUserInfo().UserID); + + // clear portal cache + DataCache.ClearHostCache(true); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + try + { + EnsureRequiredEventLogTypesExist(); + } + catch (Exception) + { + // should be no exception, but suppress just in case + } + + return PortalId; + } + + private void AddFolderPermissions(int portalId, int folderId) + { + var portal = this.GetPortal(portalId); + var folderManager = FolderManager.Instance; + var folder = folderManager.GetFolder(folderId); + var permissionController = new PermissionController(); + foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey("SYSTEM_FOLDER", string.Empty)) + { + var folderPermission = new FolderPermissionInfo(permission) + { + FolderID = folder.FolderID, + RoleID = portal.AdministratorRoleId, + AllowAccess = true, + }; + + folder.FolderPermissions.Add(folderPermission); + if (permission.PermissionKey == "READ") + { + // add READ permissions to the All Users Role + folderManager.AddAllUserReadPermission(folder, permission); + } + } + + FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); + } + private void CreatePortalInternal(int portalId, string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal, ref string message) { @@ -138,14 +453,15 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi } string templatePath, templateFile; - PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); + this.PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); string mergedTemplatePath = Path.Combine(templatePath, templateFile); - if (String.IsNullOrEmpty(homeDirectory)) + if (string.IsNullOrEmpty(homeDirectory)) { homeDirectory = "Portals/" + portalId; } - string mappedHomeDirectory = String.Format(Globals.ApplicationMapPath + "\\" + homeDirectory + "\\").Replace("/", "\\"); + + string mappedHomeDirectory = string.Format(Globals.ApplicationMapPath + "\\" + homeDirectory + "\\").Replace("/", "\\"); if (Directory.Exists(mappedHomeDirectory)) { @@ -155,11 +471,11 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi message += CreateProfileDefinitions(portalId, mergedTemplatePath); - if (String.IsNullOrEmpty(message)) + if (string.IsNullOrEmpty(message)) { try { - //the upload directory may already exist if this is a new DB working with a previously installed application + // the upload directory may already exist if this is a new DB working with a previously installed application if (Directory.Exists(mappedHomeDirectory)) { Globals.DeleteFolderRecursive(mappedHomeDirectory); @@ -171,7 +487,7 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi message += Localization.GetString("DeleteUploadFolder.Error") + Exc.Message + Exc.StackTrace; } - //Set up Child Portal + // Set up Child Portal if (message == Null.NullString) { if (isChildPortal) @@ -188,29 +504,30 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi { try { - //create the upload directory for the new portal + // create the upload directory for the new portal Directory.CreateDirectory(mappedHomeDirectory); - //ensure that the Templates folder exists - string templateFolder = String.Format("{0}Templates", mappedHomeDirectory); + + // ensure that the Templates folder exists + string templateFolder = string.Format("{0}Templates", mappedHomeDirectory); if (!Directory.Exists(templateFolder)) { Directory.CreateDirectory(templateFolder); } - //ensure that the Users folder exists - string usersFolder = String.Format("{0}Users", mappedHomeDirectory); + // ensure that the Users folder exists + string usersFolder = string.Format("{0}Users", mappedHomeDirectory); if (!Directory.Exists(usersFolder)) { Directory.CreateDirectory(usersFolder); } - //copy the default page template - CopyPageTemplate("Default.page.template", mappedHomeDirectory); + // copy the default page template + this.CopyPageTemplate("Default.page.template", mappedHomeDirectory); // process zip resource file if present if (File.Exists(template.ResourceFilePath)) { - ProcessResourceFileExplicit(mappedHomeDirectory, template.ResourceFilePath); + this.ProcessResourceFileExplicit(mappedHomeDirectory, template.ResourceFilePath); } } catch (Exception Exc) @@ -246,8 +563,8 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi { try { - CreatePredefinedFolderTypes(portalId); - ParseTemplateInternal(portalId, templatePath, templateFile, adminUser.UserID, PortalTemplateModuleAction.Replace, true, out newPortalLocales); + this.CreatePredefinedFolderTypes(portalId); + this.ParseTemplateInternal(portalId, templatePath, templateFile, adminUser.UserID, PortalTemplateModuleAction.Replace, true, out newPortalLocales); } catch (Exception Exc) { @@ -259,10 +576,10 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi { throw new Exception(message); } + if (message == Null.NullString) { - - var portal = GetPortal(portalId); + var portal = this.GetPortal(portalId); portal.Description = description; portal.KeyWords = keyWords; portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//UserProfile", portal.CultureCode); @@ -270,8 +587,9 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi { portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//ActivityFeed", portal.CultureCode); } + portal.SearchTabId = TabController.GetTabByTabPath(portal.PortalID, "//SearchResults", portal.CultureCode); - UpdatePortalInfo(portal); + this.UpdatePortalInfo(portal); adminUser.Profile.PreferredLocale = portal.DefaultLanguage; var portalSettings = new PortalSettings(portal); @@ -280,7 +598,7 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi DesktopModuleController.AddDesktopModulesToPortal(portalId); - AddPortalAlias(portalId, portalAlias); + this.AddPortalAlias(portalId, portalAlias); UpdatePortalSetting(portalId, "DefaultPortalAlias", portalAlias, false); @@ -293,7 +611,7 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi Localization.AddLanguageToPortal(portalId, newPortalLocale.LanguageId, false); if (portalSettings.ContentLocalizationEnabled) { - MapLocalizedSpecialPages(portalId, newPortalLocale.Code); + this.MapLocalizedSpecialPages(portalId, newPortalLocale.Code); } } } @@ -307,7 +625,7 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi Logger.Error(Exc); } - //add profanity list to new portal + // add profanity list to new portal try { const string listName = "ProfanityFilter"; @@ -316,17 +634,16 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi { PortalID = portalId, SystemList = false, - ListName = listName + "-" + portalId + ListName = listName + "-" + portalId, }; listController.AddListEntry(entry); - } catch (Exception Exc) { Logger.Error(Exc); } - //add banned password list to new portal + // add banned password list to new portal try { const string listName = "BannedPasswords"; @@ -335,10 +652,9 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi { PortalID = portalId, SystemList = false, - ListName = listName + "-" + portalId + ListName = listName + "-" + portalId, }; listController.AddListEntry(entry); - } catch (Exception Exc) { @@ -352,7 +668,7 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi var log = new LogInfo { BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.PORTAL_CREATED.ToString() + LogTypeKey = EventLogController.EventLogType.PORTAL_CREATED.ToString(), }; log.LogProperties.Add(new LogDetailInfo("Install Portal:", portalName)); log.LogProperties.Add(new LogDetailInfo("FirstName:", adminUser.FirstName)); @@ -389,90 +705,11 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi } } - private static string CreateProfileDefinitions(int portalId, string templateFilePath) - { - string strMessage = Null.NullString; - try - { - //add profile definitions - XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; - //open the XML template file - try - { - xmlDoc.Load(templateFilePath); - } - catch (Exception ex) - { - Logger.Error(ex); - } - //parse profile definitions if available - var node = xmlDoc.SelectSingleNode("//portal/profiledefinitions"); - if (node != null) - { - ParseProfileDefinitions(node, portalId); - } - else //template does not contain profile definitions ( ie. was created prior to DNN 3.3.0 ) - { - ProfileController.AddDefaultDefinitions(portalId); - } - } - catch (Exception ex) - { - strMessage = Localization.GetString("CreateProfileDefinitions.Error"); - Exceptions.LogException(ex); - } - return strMessage; - } - - private static int CreatePortal(string portalName, string homeDirectory, string cultureCode) - { - //add portal - int PortalId = -1; - try - { - //Use host settings as default values for these parameters - //This can be overwritten on the portal template - var datExpiryDate = Host.Host.DemoPeriod > Null.NullInteger - ? Convert.ToDateTime(Globals.GetMediumDate(DateTime.Now.AddDays(Host.Host.DemoPeriod).ToString(CultureInfo.InvariantCulture))) - : Null.NullDate; - - PortalId = DataProvider.Instance().CreatePortal(portalName, - Host.Host.HostCurrency, - datExpiryDate, - Host.Host.HostFee, - Host.Host.HostSpace, - Host.Host.PageQuota, - Host.Host.UserQuota, - 0, //site log history function has been removed. - homeDirectory, - cultureCode, - UserController.Instance.GetCurrentUserInfo().UserID); - - //clear portal cache - DataCache.ClearHostCache(true); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - try - { - EnsureRequiredEventLogTypesExist(); - } - catch (Exception) - { - //should be no exception, but suppress just in case - } - - return PortalId; - } - private static int CreateRole(RoleInfo role) { int roleId; - //First check if the role exists + // First check if the role exists var objRoleInfo = RoleController.Instance.GetRole(role.PortalID, r => r.RoleName == role.RoleName); if (objRoleInfo == null) { @@ -482,6 +719,7 @@ private static int CreateRole(RoleInfo role) { roleId = objRoleInfo.RoleID; } + return roleId; } @@ -506,198 +744,65 @@ private static int CreateRole(int portalId, string roleName, string description, private static void CreateRoleGroup(RoleGroupInfo roleGroup) { - //First check if the role exists - var objRoleGroupInfo = RoleController.GetRoleGroupByName(roleGroup.PortalID, roleGroup.RoleGroupName); - - if (objRoleGroupInfo == null) - { - roleGroup.RoleGroupID = RoleController.AddRoleGroup(roleGroup); - } - else - { - roleGroup.RoleGroupID = objRoleGroupInfo.RoleGroupID; - } - } - - private static void DeletePortalInternal(int portalId) - { - UserController.DeleteUsers(portalId, false, true); - - var portal = Instance.GetPortal(portalId); - - DataProvider.Instance().DeletePortalInfo(portalId); - - try - { - var log = new LogInfo - { - BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.PORTAL_DELETED.ToString() - }; - log.LogProperties.Add(new LogDetailInfo("Delete Portal:", portal.PortalName)); - log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); - LogController.Instance.AddLog(log); - } - catch (Exception exc) - { - Logger.Error(exc); - } - - DataCache.ClearHostCache(true); - - // queue remove portal from search index - var document = new SearchDocumentToDelete - { - PortalId = portalId, - }; - - DataProvider.Instance().AddSearchDeletedItems(document); - } - - private static bool DoesLogTypeExists(string logTypeKey) - { - LogTypeInfo logType; - Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); - logTypeDictionary.TryGetValue(logTypeKey, out logType); - if (logType == null) - { - return false; - } - return true; - } - - internal static void EnsureRequiredEventLogTypesExist() - { - if (!DoesLogTypeExists(EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString())) - { - //Add 404 Log - var logTypeInfo = new LogTypeInfo - { - LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), - LogTypeFriendlyName = "HTTP Error Code 404 Page Not Found", - LogTypeDescription = "", - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" - }; - LogController.Instance.AddLogType(logTypeInfo); - - //Add LogType - var logTypeConf = new LogTypeConfigInfo - { - LoggingIsActive = true, - LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*" - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeConf); - } - - - if (!DoesLogTypeExists(EventLogController.EventLogType.IP_LOGIN_BANNED.ToString())) - { - //Add IP filter log type - var logTypeFilterInfo = new LogTypeInfo - { - LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), - LogTypeFriendlyName = "HTTP Error Code Forbidden IP address rejected", - LogTypeDescription = "", - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" - }; - LogController.Instance.AddLogType(logTypeFilterInfo); - - //Add LogType - var logTypeFilterConf = new LogTypeConfigInfo - { - LoggingIsActive = true, - LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*" - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); - } - - if (!DoesLogTypeExists(EventLogController.EventLogType.TABURL_CREATED.ToString())) - { - var logTypeInfo = new LogTypeInfo - { - LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), - LogTypeFriendlyName = "TabURL created", - LogTypeDescription = "", - LogTypeCSSClass = "OperationSuccess", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" - }; - LogController.Instance.AddLogType(logTypeInfo); - - logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); - logTypeInfo.LogTypeFriendlyName = "TabURL updated"; - LogController.Instance.AddLogType(logTypeInfo); - - logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); - logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; - LogController.Instance.AddLogType(logTypeInfo); - - //Add LogType - var logTypeUrlConf = new LogTypeConfigInfo - { - LoggingIsActive = false, - LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*" - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); - - logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + // First check if the role exists + var objRoleGroupInfo = RoleController.GetRoleGroupByName(roleGroup.PortalID, roleGroup.RoleGroupName); - logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + if (objRoleGroupInfo == null) + { + roleGroup.RoleGroupID = RoleController.AddRoleGroup(roleGroup); + } + else + { + roleGroup.RoleGroupID = objRoleGroupInfo.RoleGroupID; } + } - if (!DoesLogTypeExists(EventLogController.EventLogType.SCRIPT_COLLISION.ToString())) + private static void DeletePortalInternal(int portalId) + { + UserController.DeleteUsers(portalId, false, true); + + var portal = Instance.GetPortal(portalId); + + DataProvider.Instance().DeletePortalInfo(portalId); + + try { - //Add IP filter log type - var logTypeFilterInfo = new LogTypeInfo + var log = new LogInfo { - LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), - LogTypeFriendlyName = "Javscript library registration resolved script collision", - LogTypeDescription = "", - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" + BypassBuffering = true, + LogTypeKey = EventLogController.EventLogType.PORTAL_DELETED.ToString(), }; - LogController.Instance.AddLogType(logTypeFilterInfo); + log.LogProperties.Add(new LogDetailInfo("Delete Portal:", portal.PortalName)); + log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); + LogController.Instance.AddLog(log); + } + catch (Exception exc) + { + Logger.Error(exc); + } - //Add LogType - var logTypeFilterConf = new LogTypeConfigInfo - { - LoggingIsActive = true, - LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*" - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); + DataCache.ClearHostCache(true); + + // queue remove portal from search index + var document = new SearchDocumentToDelete + { + PortalId = portalId, + }; + + DataProvider.Instance().AddSearchDeletedItems(document); + } + + private static bool DoesLogTypeExists(string logTypeKey) + { + LogTypeInfo logType; + Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); + logTypeDictionary.TryGetValue(logTypeKey, out logType); + if (logType == null) + { + return false; } + return true; } private static PortalSettings GetCurrentPortalSettingsInternal() @@ -707,6 +812,7 @@ private static PortalSettings GetCurrentPortalSettingsInternal() { objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; } + return objPortalSettings; } @@ -726,14 +832,14 @@ private static object GetPortalDictionaryCallback(CacheItemArgs cacheItemArgs) var portalDic = new Dictionary(); if (Host.Host.PerformanceSetting != Globals.PerformanceSettings.NoCaching) { - //get all tabs + // get all tabs int intField = 0; IDataReader dr = DataProvider.Instance().GetTabPaths(Null.NullInteger, Null.NullString); try { while (dr.Read()) { - //add to dictionary + // add to dictionary portalDic[Convert.ToInt32(Null.SetNull(dr["TabID"], intField))] = Convert.ToInt32(Null.SetNull(dr["PortalID"], intField)); } } @@ -743,10 +849,11 @@ private static object GetPortalDictionaryCallback(CacheItemArgs cacheItemArgs) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } } + return portalDic; } @@ -755,19 +862,26 @@ private static object GetPortalSettingsDictionaryCallback(CacheItemArgs cacheIte var portalId = (int)cacheItemArgs.ParamList[0]; var dicSettings = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - if (portalId <= -1) return dicSettings; + if (portalId <= -1) + { + return dicSettings; + } var cultureCode = Convert.ToString(cacheItemArgs.ParamList[1]); if (string.IsNullOrEmpty(cultureCode)) { cultureCode = GetActivePortalLanguage(portalId); } + var dr = DataProvider.Instance().GetPortalSettings(portalId, cultureCode); try { while (dr.Read()) { - if (dr.IsDBNull(1)) continue; + if (dr.IsDBNull(1)) + { + continue; + } var key = dr.GetString(0); if (dicSettings.ContainsKey(key)) @@ -775,7 +889,7 @@ private static object GetPortalSettingsDictionaryCallback(CacheItemArgs cacheIte dicSettings[key] = dr.GetString(1); var log = new LogInfo { - LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() + LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(), }; log.AddProperty("Duplicate PortalSettings Key", key); LogController.Instance.AddLog(log); @@ -794,6 +908,7 @@ private static object GetPortalSettingsDictionaryCallback(CacheItemArgs cacheIte { CBO.CloseDataReader(dr, true); } + return dicSettings; } @@ -805,10 +920,13 @@ private static void ParseFiles(XmlNodeList nodeFiles, int portalId, FolderInfo f { var fileName = XmlUtils.GetNodeValue(node.CreateNavigator(), "filename"); - //First check if the file exists + // First check if the file exists var file = fileManager.GetFile(folder, fileName); - if (file != null) continue; + if (file != null) + { + continue; + } file = new FileInfo { @@ -822,17 +940,17 @@ private static void ParseFiles(XmlNodeList nodeFiles, int portalId, FolderInfo f SHA1Hash = XmlUtils.GetNodeValue(node.CreateNavigator(), "sha1hash"), FolderId = folder.FolderID, Folder = folder.FolderPath, - Title = "", + Title = string.Empty, StartDate = DateTime.Now, EndDate = Null.NullDate, EnablePublishPeriod = false, - ContentItemID = Null.NullInteger + ContentItemID = Null.NullInteger, }; - //Save new File + // Save new File try { - //Initially, install files are on local system, then we need the Standard folder provider to read the content regardless the target folderprovider + // Initially, install files are on local system, then we need the Standard folder provider to read the content regardless the target folderprovider using (var fileContent = FolderProvider.Instance("StandardFolderProvider").GetFileStream(file)) { var contentType = FileContentTypeManager.Instance.GetContentType(Path.GetExtension(fileName)); @@ -842,7 +960,7 @@ private static void ParseFiles(XmlNodeList nodeFiles, int portalId, FolderInfo f fileManager.UpdateFile(file); } - catch (InvalidFileExtensionException ex) //when the file is not allowed, we should not break parse process, but just log the error. + catch (InvalidFileExtensionException ex) // when the file is not allowed, we should not break parse process, but just log the error. { Logger.Error(ex.Message); } @@ -854,7 +972,7 @@ private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, in PermissionController permissionController = new PermissionController(); int permissionId = 0; - //Clear the current folder permissions + // Clear the current folder permissions folder.FolderPermissions.Clear(); foreach (XmlNode xmlFolderPermission in nodeFolderPermissions) { @@ -866,6 +984,7 @@ private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, in { permissionId = permission.PermissionID; } + int roleId = int.MinValue; switch (roleName) { @@ -881,10 +1000,11 @@ private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, in { roleId = objRole.RoleID; } + break; } - //if role was found add, otherwise ignore + // if role was found add, otherwise ignore if (roleId != int.MinValue) { var folderPermission = new FolderPermissionInfo @@ -893,7 +1013,7 @@ private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, in PermissionID = permissionId, RoleID = roleId, UserID = Null.NullInteger, - AllowAccess = allowAccess + AllowAccess = allowAccess, }; bool canAdd = !folder.FolderPermissions.Cast() @@ -907,9 +1027,31 @@ private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, in } } } + FolderPermissionController.SaveFolderPermissions(folder); } + private static void EnsureRequiredProvidersForFolderTypes() + { + if (ComponentFactory.GetComponent() == null) + { + ComponentFactory.InstallComponents(new ProviderInstaller("cryptography", typeof(CryptographyProvider), typeof(FipsCompilanceCryptographyProvider))); + ComponentFactory.RegisterComponentInstance(new FipsCompilanceCryptographyProvider()); + } + } + + private static void EnsureFolderProviderRegistration(FolderTypeConfig folderTypeConfig, XmlDocument webConfig) + where TAbstract : class + { + var providerBusinessClassNode = webConfig.SelectSingleNode("configuration/dotnetnuke/folder/providers/add[@name='" + folderTypeConfig.Provider + "']"); + + var typeClass = Type.GetType(providerBusinessClassNode.Attributes["type"].Value); + if (typeClass != null) + { + ComponentFactory.RegisterComponentInstance(folderTypeConfig.Provider, Activator.CreateInstance(typeClass)); + } + } + private void CreatePredefinedFolderTypes(int portalId) { try @@ -920,13 +1062,15 @@ private void CreatePredefinedFolderTypes(int portalId) { Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error"), ex); } + var webConfig = Config.Load(); foreach (FolderTypeConfig folderTypeConfig in FolderMappingsConfigController.Instance.FolderTypes) { try { EnsureFolderProviderRegistration(folderTypeConfig, webConfig); - FolderMappingController.Instance.AddFolderMapping(GetFolderMappingFromConfig(folderTypeConfig, + FolderMappingController.Instance.AddFolderMapping(this.GetFolderMappingFromConfig( + folderTypeConfig, portalId)); } catch (Exception ex) @@ -936,25 +1080,87 @@ private void CreatePredefinedFolderTypes(int portalId) } } - private static void EnsureRequiredProvidersForFolderTypes() + private static bool EnableBrowserLanguageInDefault(int portalId) { - if (ComponentFactory.GetComponent() == null) + bool retValue = Null.NullBoolean; + try { - ComponentFactory.InstallComponents(new ProviderInstaller("cryptography", typeof(CryptographyProvider), typeof(FipsCompilanceCryptographyProvider))); - ComponentFactory.RegisterComponentInstance(new FipsCompilanceCryptographyProvider()); + string setting; + GetPortalSettingsDictionary(portalId, Localization.SystemLocale).TryGetValue("EnableBrowserLanguage", out setting); + if (string.IsNullOrEmpty(setting)) + { + retValue = Host.Host.EnableBrowserLanguage; + } + else + { + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); + } } + catch (Exception exc) + { + Logger.Error(exc); + } + + return retValue; } - private static void EnsureFolderProviderRegistration(FolderTypeConfig folderTypeConfig, XmlDocument webConfig) - where TAbstract : class + private static Dictionary GetPortalSettingsDictionary(int portalId, string cultureCode) { - var providerBusinessClassNode = webConfig.SelectSingleNode("configuration/dotnetnuke/folder/providers/add[@name='" + folderTypeConfig.Provider + "']"); + var httpContext = HttpContext.Current; - var typeClass = Type.GetType(providerBusinessClassNode.Attributes["type"].Value); - if (typeClass != null) + if (string.IsNullOrEmpty(cultureCode) && portalId > -1) { - ComponentFactory.RegisterComponentInstance(folderTypeConfig.Provider, Activator.CreateInstance(typeClass)); + cultureCode = GetActivePortalLanguageFromHttpContext(httpContext, portalId); + } + + // Get PortalSettings from Context or from cache + var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalId, cultureCode); + Dictionary dictionary = null; + if (httpContext != null) + { + dictionary = httpContext.Items[dictionaryKey] as Dictionary; + } + + if (dictionary == null) + { + var cacheKey = string.Format(DataCache.PortalSettingsCacheKey, portalId, cultureCode); + dictionary = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.PortalSettingsCacheTimeOut, + DataCache.PortalSettingsCachePriority, portalId, cultureCode), + GetPortalSettingsDictionaryCallback, + true); + if (httpContext != null) + { + httpContext.Items[dictionaryKey] = dictionary; + } + } + + return dictionary; + } + + private static string GetActivePortalLanguageFromHttpContext(HttpContext httpContext, int portalId) + { + var cultureCode = string.Empty; + + // Lookup culturecode but cache it in the HttpContext for performance + var activeLanguageKey = string.Format("ActivePortalLanguage{0}", portalId); + if (httpContext != null) + { + cultureCode = (string)httpContext.Items[activeLanguageKey]; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + cultureCode = GetActivePortalLanguage(portalId); + if (httpContext != null) + { + httpContext.Items[activeLanguageKey] = cultureCode; + } } + + return cultureCode; } private void ParseExtensionUrlProviders(XPathNavigator providersNavigator, int portalId) @@ -993,29 +1199,6 @@ private void ParseExtensionUrlProviders(XPathNavigator providersNavigator, int p } } - private static bool EnableBrowserLanguageInDefault(int portalId) - { - bool retValue = Null.NullBoolean; - try - { - string setting; - GetPortalSettingsDictionary(portalId, Localization.SystemLocale).TryGetValue("EnableBrowserLanguage", out setting); - if (string.IsNullOrEmpty(setting)) - { - retValue = Host.Host.EnableBrowserLanguage; - } - else - { - retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); - } - } - catch (Exception exc) - { - Logger.Error(exc); - } - return retValue; - } - private string EnsureSettingValue(string folderProviderType, FolderTypeSettingConfig settingNode, int portalId) { var ensuredSettingValue = @@ -1023,108 +1206,50 @@ private string EnsureSettingValue(string folderProviderType, FolderTypeSettingCo if (settingNode.Encrypt) { return FolderProvider.Instance(folderProviderType).EncryptValue(ensuredSettingValue); - //return PortalSecurity.Instance.Encrypt(Host.Host.GUID, ensuredSettingValue.Trim()); - } - return ensuredSettingValue; - } - - private string GetCultureCode(string languageFileName) - { - //e.g. "default template.template.en-US.resx" - return languageFileName.GetLocaleCodeFromFileName(); - } - - private FolderMappingInfo GetFolderMappingFromConfig(FolderTypeConfig node, int portalId) - { - var folderMapping = new FolderMappingInfo - { - PortalID = portalId, - MappingName = node.Name, - FolderProviderType = node.Provider - }; - - foreach (FolderTypeSettingConfig settingNode in node.Settings) - { - var settingValue = EnsureSettingValue(folderMapping.FolderProviderType, settingNode, portalId); - folderMapping.FolderMappingSettings.Add(settingNode.Name, settingValue); - } - - return folderMapping; - } - - private FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) - { - var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); - switch (storageLocation) - { - case (int)FolderController.StorageLocationTypes.SecureFileSystem: - return FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"); - case (int)FolderController.StorageLocationTypes.DatabaseSecure: - return FolderMappingController.Instance.GetFolderMapping(portalId, "Database"); - default: - return FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - } - } - - private static Dictionary GetPortalSettingsDictionary(int portalId, string cultureCode) - { - var httpContext = HttpContext.Current; - - if (string.IsNullOrEmpty(cultureCode) && portalId > -1) - { - cultureCode = GetActivePortalLanguageFromHttpContext(httpContext, portalId); - } - - //Get PortalSettings from Context or from cache - var dictionaryKey = String.Format(HttpContextKeyPortalSettingsDictionary, portalId, cultureCode); - Dictionary dictionary = null; - if (httpContext != null) - { - dictionary = httpContext.Items[dictionaryKey] as Dictionary; - } - if (dictionary == null) - { - var cacheKey = string.Format(DataCache.PortalSettingsCacheKey, portalId, cultureCode); - dictionary = CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.PortalSettingsCacheTimeOut, - DataCache.PortalSettingsCachePriority, portalId, cultureCode), - GetPortalSettingsDictionaryCallback, - true); - if (httpContext != null) - { - httpContext.Items[dictionaryKey] = dictionary; - } + // return PortalSecurity.Instance.Encrypt(Host.Host.GUID, ensuredSettingValue.Trim()); } - return dictionary; + + return ensuredSettingValue; } - private static string GetActivePortalLanguageFromHttpContext(HttpContext httpContext, int portalId) + private string GetCultureCode(string languageFileName) { - var cultureCode = string.Empty; + // e.g. "default template.template.en-US.resx" + return languageFileName.GetLocaleCodeFromFileName(); + } - //Lookup culturecode but cache it in the HttpContext for performance - var activeLanguageKey = String.Format("ActivePortalLanguage{0}", portalId); - if (httpContext != null) + private FolderMappingInfo GetFolderMappingFromConfig(FolderTypeConfig node, int portalId) + { + var folderMapping = new FolderMappingInfo { - cultureCode = (string)httpContext.Items[activeLanguageKey]; - } - if (string.IsNullOrEmpty(cultureCode)) + PortalID = portalId, + MappingName = node.Name, + FolderProviderType = node.Provider, + }; + + foreach (FolderTypeSettingConfig settingNode in node.Settings) { - cultureCode = GetActivePortalLanguage(portalId); - if (httpContext != null) - { - httpContext.Items[activeLanguageKey] = cultureCode; - } + var settingValue = this.EnsureSettingValue(folderMapping.FolderProviderType, settingNode, portalId); + folderMapping.FolderMappingSettings.Add(settingNode.Name, settingValue); } - return cultureCode; + return folderMapping; } - private string GetTemplateName(string languageFileName) + private FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) { - //e.g. "default template.template.en-US.resx" - return languageFileName.GetFileNameFromLocalizedResxFile(); + var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); + + switch (storageLocation) + { + case (int)FolderController.StorageLocationTypes.SecureFileSystem: + return FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"); + case (int)FolderController.StorageLocationTypes.DatabaseSecure: + return FolderMappingController.Instance.GetFolderMapping(portalId, "Database"); + default: + return FolderMappingController.Instance.GetDefaultFolderMapping(portalId); + } } private static LocaleCollection ParseEnabledLocales(XmlNode nodeEnabledLocales, int portalId) @@ -1149,75 +1274,13 @@ private static LocaleCollection ParseEnabledLocales(XmlNode nodeEnabledLocales, returnCollection.Add(locale.Code, locale); } } + if (clearCache) { DataCache.ClearHostCache(true); } - return returnCollection; - } - - private void ParseFolders(XmlNode nodeFolders, int portalId) - { - var folderManager = FolderManager.Instance; - var folderMappingController = FolderMappingController.Instance; - var xmlNodeList = nodeFolders.SelectNodes("//folder"); - if (xmlNodeList != null) - { - foreach (XmlNode node in xmlNodeList) - { - HtmlUtils.WriteKeepAlive(); - var folderPath = XmlUtils.GetNodeValue(node.CreateNavigator(), "folderpath"); - - //First check if the folder exists - var objInfo = folderManager.GetFolder(portalId, folderPath); - - if (objInfo == null) - { - FolderMappingInfo folderMapping; - try - { - folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, folderPath) - ?? GetFolderMappingFromStorageLocation(portalId, node); - } - catch (Exception ex) - { - Logger.Error(ex); - folderMapping = folderMappingController.GetDefaultFolderMapping(portalId); - } - var isProtected = XmlUtils.GetNodeValueBoolean(node, "isprotected"); - - try - { - //Save new folder - objInfo = folderManager.AddFolder(folderMapping, folderPath); - } - catch (Exception ex) - { - Logger.Error(ex); - //Retry with default folderMapping - var defaultFolderMapping = folderMappingController.GetDefaultFolderMapping(portalId); - if (folderMapping.FolderMappingID != defaultFolderMapping.FolderMappingID) - { - objInfo = folderManager.AddFolder(defaultFolderMapping, folderPath); - } - else - { - throw; - } - } - objInfo.IsProtected = isProtected; - - folderManager.UpdateFolder(objInfo); - } - - var nodeFolderPermissions = node.SelectNodes("folderpermissions/permission"); - ParseFolderPermissions(nodeFolderPermissions, portalId, (FolderInfo)objInfo); - - var nodeFiles = node.SelectNodes("files/file"); - ParseFiles(nodeFiles, portalId, (FolderInfo)objInfo); - } - } + return returnCollection; } private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int portalId) @@ -1236,9 +1299,10 @@ private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int { typeInfo = colDataTypes["DataType:Unknown"]; } + objProfileDefinition = new ProfilePropertyDefinition(portalId); objProfileDefinition.DataType = typeInfo.EntryID; - objProfileDefinition.DefaultValue = ""; + objProfileDefinition.DefaultValue = string.Empty; objProfileDefinition.ModuleDefId = Null.NullInteger; objProfileDefinition.PropertyCategory = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertycategory"); objProfileDefinition.PropertyName = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertyname"); @@ -1268,7 +1332,7 @@ private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int ProfileController.AddPropertyDefinition(objProfileDefinition); } - //6.0 requires the old TimeZone property to be marked as Deleted + // 6.0 requires the old TimeZone property to be marked as Deleted ProfilePropertyDefinition pdf = ProfileController.GetPropertyDefinitionByName(portalId, "TimeZone"); if (pdf != null) { @@ -1289,7 +1353,7 @@ private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int objProfileDefinition = new ProfilePropertyDefinition(portalId); objProfileDefinition.DataType = typeInfo.EntryID; - objProfileDefinition.DefaultValue = ""; + objProfileDefinition.DefaultValue = string.Empty; objProfileDefinition.ModuleDefId = Null.NullInteger; objProfileDefinition.PropertyCategory = "Preferences"; objProfileDefinition.PropertyName = "PreferredTimeZone"; @@ -1313,7 +1377,7 @@ private static void ParsePortalDesktopModules(XPathNavigator nav, int portalID) var desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); if (desktopModule != null) { - //Parse the permissions + // Parse the permissions DesktopModulePermissionCollection permissions = new DesktopModulePermissionCollection(); foreach (XPathNavigator permissionNav in desktopModuleNav.Select("portalDesktopModulePermissions/portalDesktopModulePermission")) @@ -1330,6 +1394,7 @@ private static void ParsePortalDesktopModules(XPathNavigator nav, int portalID) desktopModulePermission = new DesktopModulePermissionInfo(permission); } } + desktopModulePermission.AllowAccess = bool.Parse(XmlUtils.GetNodeValue(permissionNav, "allowaccess")); string rolename = XmlUtils.GetNodeValue(permissionNav, "rolename"); if (!string.IsNullOrEmpty(rolename)) @@ -1340,102 +1405,214 @@ private static void ParsePortalDesktopModules(XPathNavigator nav, int portalID) desktopModulePermission.RoleID = role.RoleID; } } + permissions.Add(desktopModulePermission); } + DesktopModuleController.AddDesktopModuleToPortal(portalID, desktopModule, permissions, false); } } } } + private string GetTemplateName(string languageFileName) + { + // e.g. "default template.template.en-US.resx" + return languageFileName.GetFileNameFromLocalizedResxFile(); + } + + private void ParseFolders(XmlNode nodeFolders, int portalId) + { + var folderManager = FolderManager.Instance; + var folderMappingController = FolderMappingController.Instance; + var xmlNodeList = nodeFolders.SelectNodes("//folder"); + if (xmlNodeList != null) + { + foreach (XmlNode node in xmlNodeList) + { + HtmlUtils.WriteKeepAlive(); + var folderPath = XmlUtils.GetNodeValue(node.CreateNavigator(), "folderpath"); + + // First check if the folder exists + var objInfo = folderManager.GetFolder(portalId, folderPath); + + if (objInfo == null) + { + FolderMappingInfo folderMapping; + try + { + folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, folderPath) + ?? this.GetFolderMappingFromStorageLocation(portalId, node); + } + catch (Exception ex) + { + Logger.Error(ex); + folderMapping = folderMappingController.GetDefaultFolderMapping(portalId); + } + + var isProtected = XmlUtils.GetNodeValueBoolean(node, "isprotected"); + + try + { + // Save new folder + objInfo = folderManager.AddFolder(folderMapping, folderPath); + } + catch (Exception ex) + { + Logger.Error(ex); + + // Retry with default folderMapping + var defaultFolderMapping = folderMappingController.GetDefaultFolderMapping(portalId); + if (folderMapping.FolderMappingID != defaultFolderMapping.FolderMappingID) + { + objInfo = folderManager.AddFolder(defaultFolderMapping, folderPath); + } + else + { + throw; + } + } + + objInfo.IsProtected = isProtected; + + folderManager.UpdateFolder(objInfo); + } + + var nodeFolderPermissions = node.SelectNodes("folderpermissions/permission"); + ParseFolderPermissions(nodeFolderPermissions, portalId, (FolderInfo)objInfo); + + var nodeFiles = node.SelectNodes("files/file"); + + ParseFiles(nodeFiles, portalId, (FolderInfo)objInfo); + } + } + } + + private static void UpdatePortalSettingInternal(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) + { + string currentSetting = GetPortalSetting(settingName, portalID, string.Empty, cultureCode); + + if (currentSetting != settingValue) + { + if (isSecure && !string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) + { + settingValue = Security.FIPSCompliant.EncryptAES(settingValue, Config.GetDecryptionkey(), Host.Host.GUID); + } + + DataProvider.Instance().UpdatePortalSetting(portalID, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID, cultureCode, isSecure); + EventLogController.Instance.AddLog(settingName + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), settingValue, GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_UPDATED); + if (clearCache) + { + DataCache.ClearPortalCache(portalID, false); + DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); + + var httpContext = HttpContext.Current; + if (httpContext != null) + { + var cultureCodeForKey = GetActivePortalLanguageFromHttpContext(httpContext, portalID); + var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalID, cultureCodeForKey); + httpContext.Items[dictionaryKey] = null; + } + } + + EventManager.Instance.OnPortalSettingUpdated(new PortalSettingUpdatedEventArgs + { + PortalId = portalID, + SettingName = settingName, + SettingValue = settingValue, + }); + } + } + private void ParsePortalSettings(XmlNode nodeSettings, int portalId) { - String currentCulture = GetActivePortalLanguage(portalId); - var objPortal = GetPortal(portalId); + string currentCulture = GetActivePortalLanguage(portalId); + var objPortal = this.GetPortal(portalId); objPortal.LogoFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "logofile")); objPortal.FooterText = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "footertext"); if (nodeSettings.SelectSingleNode("expirydate") != null) { objPortal.ExpiryDate = XmlUtils.GetNodeValueDate(nodeSettings, "expirydate", Null.NullDate); } + objPortal.UserRegistration = XmlUtils.GetNodeValueInt(nodeSettings, "userregistration"); objPortal.BannerAdvertising = XmlUtils.GetNodeValueInt(nodeSettings, "banneradvertising"); - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"))) { objPortal.Currency = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostfee"))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostfee"))) { objPortal.HostFee = XmlUtils.GetNodeValueSingle(nodeSettings, "hostfee"); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostspace"))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostspace"))) { objPortal.HostSpace = XmlUtils.GetNodeValueInt(nodeSettings, "hostspace"); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "pagequota"))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "pagequota"))) { objPortal.PageQuota = XmlUtils.GetNodeValueInt(nodeSettings, "pagequota"); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "userquota"))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "userquota"))) { objPortal.UserQuota = XmlUtils.GetNodeValueInt(nodeSettings, "userquota"); } + objPortal.BackgroundFile = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "backgroundfile"); objPortal.PaymentProcessor = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "paymentprocessor"); objPortal.DefaultLanguage = XmlUtils.GetNodeValue(nodeSettings, "defaultlanguage", "en-US"); - UpdatePortalInfo(objPortal); + this.UpdatePortalInfo(objPortal); - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrc", ""))) - { - UpdatePortalSetting(portalId, "DefaultPortalSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrc", ""), true, currentCulture); - } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", ""))) - { - UpdatePortalSetting(portalId, "DefaultAdminSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", ""), true, currentCulture); - } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrc", ""))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrc", string.Empty))) { - UpdatePortalSetting(portalId, "DefaultPortalContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrc", ""), true, currentCulture); + UpdatePortalSetting(portalId, "DefaultPortalSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrc", string.Empty), true, currentCulture); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", ""))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", string.Empty))) { - UpdatePortalSetting(portalId, "DefaultAdminContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", ""), true, currentCulture); + UpdatePortalSetting(portalId, "DefaultAdminSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", string.Empty), true, currentCulture); } - //Enable Skin Widgets Setting - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", ""))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrc", string.Empty))) { - UpdatePortalSetting(portalId, "EnableSkinWidgets", XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", "")); + UpdatePortalSetting(portalId, "DefaultPortalContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrc", string.Empty), true, currentCulture); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", ""))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", string.Empty))) { - UpdatePortalSetting(portalId, "ShowCookieConsent", XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", "False")); + UpdatePortalSetting(portalId, "DefaultAdminContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", string.Empty), true, currentCulture); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", ""))) + + // Enable Skin Widgets Setting + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", string.Empty))) { - UpdatePortalSetting(portalId, "CookieMoreLink", XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", ""), true, currentCulture); + UpdatePortalSetting(portalId, "EnableSkinWidgets", XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", string.Empty)); } - //Enable AutoSAve feature - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableautosave", ""))) + // Enable AutoSAve feature + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableautosave", string.Empty))) { - UpdatePortalSetting(portalId, HtmlText_AutoSaveEnabled, XmlUtils.GetNodeValue(nodeSettings, "enableautosave", "")); - //Time to autosave, only if enableautosave exists - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", ""))) + UpdatePortalSetting(portalId, HtmlText_AutoSaveEnabled, XmlUtils.GetNodeValue(nodeSettings, "enableautosave", string.Empty)); + + // Time to autosave, only if enableautosave exists + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", string.Empty))) { - UpdatePortalSetting(portalId, HtmlText_TimeToAutoSave, XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", "")); + UpdatePortalSetting(portalId, HtmlText_TimeToAutoSave, XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", string.Empty)); } } - //Set Auto alias mapping - + // Set Auto alias mapping if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL"))) { UpdatePortalSetting(portalId, "PortalAliasMapping", XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL").ToUpperInvariant()); } - //Set Time Zone maping + + // Set Time Zone maping if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone))) { UpdatePortalSetting(portalId, "TimeZone", XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone)); @@ -1458,43 +1635,89 @@ private void ParsePortalSettings(XmlNode nodeSettings, int portalId) if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled"))) { - UpdatePortalSetting(portalId, "HideFoldersEnabled", XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled")); + UpdatePortalSetting(portalId, "HideFoldersEnabled", XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled")); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode"))) + { + UpdatePortalSetting(portalId, "ControlPanelMode", XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode")); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity"))) + { + UpdatePortalSetting(portalId, "ControlPanelSecurity", XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity")); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility"))) + { + UpdatePortalSetting(portalId, "ControlPanelVisibility", XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility")); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", string.Empty))) + { + UpdatePortalSetting(portalId, "PageHeadText", XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", string.Empty)); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", string.Empty))) + { + UpdatePortalSetting(portalId, "InjectModuleHyperLink", XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", string.Empty)); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", string.Empty))) + { + UpdatePortalSetting(portalId, "AddCompatibleHttpHeader", XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", string.Empty)); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", string.Empty))) + { + UpdatePortalSetting(portalId, "AllowUserUICulture", XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", string.Empty)); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", string.Empty))) + { + UpdatePortalSetting(portalId, "EnableBrowserLanguage", XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", string.Empty)); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode"))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", string.Empty))) { - UpdatePortalSetting(portalId, "ControlPanelMode", XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode")); + UpdatePortalSetting(portalId, "ShowCookieConsent", XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", "False")); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity"))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", string.Empty))) { - UpdatePortalSetting(portalId, "ControlPanelSecurity", XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity")); + UpdatePortalSetting(portalId, "CookieMoreLink", XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", string.Empty), true, currentCulture); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility"))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentactive", string.Empty))) { - UpdatePortalSetting(portalId, "ControlPanelVisibility", XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility")); + UpdatePortalSetting(portalId, "DataConsentActive", XmlUtils.GetNodeValue(nodeSettings, "dataconsentactive", "False")); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", ""))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsenttermslastchange", string.Empty))) { - UpdatePortalSetting(portalId, "PageHeadText", XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", "")); + UpdatePortalSetting(portalId, "DataConsentTermsLastChange", XmlUtils.GetNodeValue(nodeSettings, "dataconsenttermslastchange", string.Empty), true, currentCulture); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", ""))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentconsentredirect", string.Empty))) { - UpdatePortalSetting(portalId, "InjectModuleHyperLink", XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", "")); + UpdatePortalSetting(portalId, "DataConsentConsentRedirect", XmlUtils.GetNodeValue(nodeSettings, "dataconsentconsentredirect", string.Empty), true, currentCulture); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", ""))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentuserdeleteaction", string.Empty))) { - UpdatePortalSetting(portalId, "AddCompatibleHttpHeader", XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", "")); + UpdatePortalSetting(portalId, "DataConsentUserDeleteAction", XmlUtils.GetNodeValue(nodeSettings, "dataconsentuserdeleteaction", string.Empty), true, currentCulture); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", ""))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelay", string.Empty))) { - UpdatePortalSetting(portalId, "AllowUserUICulture", XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", "")); + UpdatePortalSetting(portalId, "DataConsentDelay", XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelay", string.Empty), true, currentCulture); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", ""))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelaymeasurement", string.Empty))) { - UpdatePortalSetting(portalId, "EnableBrowserLanguage", XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", "")); + UpdatePortalSetting(portalId, "DataConsentDelayMeasurement", XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelaymeasurement", string.Empty), true, currentCulture); } + } private void ParseRoleGroups(XPathNavigator nav, int portalID, int administratorId) @@ -1513,6 +1736,7 @@ private void ParseRoleGroups(XPathNavigator nav, int portalID, int administrator roleGroup.PortalID = portalID; CreateRoleGroup(roleGroup); } + foreach (var role in roleGroup.Roles.Values) { role.PortalID = portalID; @@ -1538,26 +1762,28 @@ private void ParseRoleGroups(XPathNavigator nav, int portalID, int administrator } } } + CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); - //update portal setup - var portal = GetPortal(portalID); - UpdatePortalSetup(portalID, - administratorId, - administratorRoleId, - registeredRoleId, - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.AdminTabId, - GetActivePortalLanguage(portalID)); + // update portal setup + var portal = this.GetPortal(portalID); + this.UpdatePortalSetup( + portalID, + administratorId, + administratorRoleId, + registeredRoleId, + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.AdminTabId, + GetActivePortalLanguage(portalID)); } private void ParseRoles(XPathNavigator nav, int portalID, int administratorId) @@ -1593,61 +1819,65 @@ private void ParseRoles(XPathNavigator nav, int portalID, int administratorId) } } - //create required roles if not already created + // create required roles if not already created CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); - //update portal setup - var portal = GetPortal(portalID); - UpdatePortalSetup(portalID, - administratorId, - administratorRoleId, - registeredRoleId, - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.AdminTabId, - GetActivePortalLanguage(portalID)); + // update portal setup + var portal = this.GetPortal(portalID); + this.UpdatePortalSetup( + portalID, + administratorId, + administratorRoleId, + registeredRoleId, + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.AdminTabId, + GetActivePortalLanguage(portalID)); } private void ParseTab(XmlNode nodeTab, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, ref Hashtable hModules, ref Hashtable hTabs, bool isNewPortal) { TabInfo tab = null; string strName = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "name"); - var portal = GetPortal(portalId); - if (!String.IsNullOrEmpty(strName)) + var portal = this.GetPortal(portalId); + if (!string.IsNullOrEmpty(strName)) { - if (!isNewPortal) //running from wizard: try to find the tab by path + if (!isNewPortal) // running from wizard: try to find the tab by path { - string parenttabname = ""; - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent"))) + string parenttabname = string.Empty; + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent"))) { parenttabname = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent") + "/"; } + if (hTabs[parenttabname + strName] != null) { tab = TabController.Instance.GetTab(Convert.ToInt32(hTabs[parenttabname + strName]), portalId, false); } } + if (tab == null || isNewPortal) { tab = TabController.DeserializeTab(nodeTab, null, hTabs, portalId, isAdminTemplate, mergeTabs, hModules); } - //when processing the template we should try and identify the Admin tab + // when processing the template we should try and identify the Admin tab var logType = "AdminTab"; if (tab.TabName == "Admin") { portal.AdminTabId = tab.TabID; } - //when processing the template we can find: hometab, usertab, logintab - switch (XmlUtils.GetNodeValue(nodeTab, "tabtype", "").ToLowerInvariant()) + + // when processing the template we can find: hometab, usertab, logintab + switch (XmlUtils.GetNodeValue(nodeTab, "tabtype", string.Empty).ToLowerInvariant()) { case "splashtab": portal.SplashTabId = tab.TabID; @@ -1677,42 +1907,53 @@ private void ParseTab(XmlNode nodeTab, int portalId, bool isAdminTemplate, Porta portal.Custom500TabId = tab.TabID; logType = "Custom500Tab"; break; + case "termstab": + portal.TermsTabId = tab.TabID; + logType = "TermsTabId"; + break; + case "privacytab": + portal.PrivacyTabId = tab.TabID; + logType = "PrivacyTabId"; + break; } - UpdatePortalSetup(portalId, - portal.AdministratorId, - portal.AdministratorRoleId, - portal.RegisteredRoleId, - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.AdminTabId, - GetActivePortalLanguage(portalId)); - EventLogController.Instance.AddLog(logType, - tab.TabID.ToString(), - GetCurrentPortalSettingsInternal(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTAL_SETTING_UPDATED); + + this.UpdatePortalSetup( + portalId, + portal.AdministratorId, + portal.AdministratorRoleId, + portal.RegisteredRoleId, + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.AdminTabId, + GetActivePortalLanguage(portalId)); + EventLogController.Instance.AddLog( + logType, + tab.TabID.ToString(), + GetCurrentPortalSettingsInternal(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTAL_SETTING_UPDATED); } } private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { - //used to control if modules are true modules or instances - //will hold module ID from template / new module ID so new instances can reference right moduleid - //only first one from the template will be create as a true module, - //others will be moduleinstances (tabmodules) + // used to control if modules are true modules or instances + // will hold module ID from template / new module ID so new instances can reference right moduleid + // only first one from the template will be create as a true module, + // others will be moduleinstances (tabmodules) Hashtable hModules = new Hashtable(); Hashtable hTabs = new Hashtable(); - //if running from wizard we need to pre populate htabs with existing tabs so ParseTab - //can find all existing ones + // if running from wizard we need to pre populate htabs with existing tabs so ParseTab + // can find all existing ones if (!isNewPortal) { Hashtable hTabNames = new Hashtable(); @@ -1726,11 +1967,12 @@ private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, Por { tabname = Convert.ToString(hTabNames[objTab.ParentId]) + "/" + objTab.TabName; } + hTabNames.Add(objTab.TabID, tabname); } } - //when parsing tabs we will need tabid given tabname + // when parsing tabs we will need tabid given tabname foreach (int i in hTabNames.Keys) { if (hTabs[hTabNames[i]] == null) @@ -1738,15 +1980,17 @@ private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, Por hTabs.Add(hTabNames[i], i); } } + hTabNames.Clear(); } + foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab")) { HtmlUtils.WriteKeepAlive(); - ParseTab(nodeTab, portalId, isAdminTemplate, mergeTabs, ref hModules, ref hTabs, isNewPortal); + this.ParseTab(nodeTab, portalId, isAdminTemplate, mergeTabs, ref hModules, ref hTabs, isNewPortal); } - //Process tabs that are linked to tabs + // Process tabs that are linked to tabs foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'Tab']")) { HtmlUtils.WriteKeepAlive(); @@ -1759,9 +2003,11 @@ private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, Por TabController.Instance.UpdateTab(objTab); } } + var folderManager = FolderManager.Instance; var fileManager = FileManager.Instance; - //Process tabs that are linked to files + + // Process tabs that are linked to files foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'File']")) { HtmlUtils.WriteKeepAlive(); @@ -1787,7 +2033,7 @@ private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, Por private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { LocaleCollection localeCollection; - ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal, out localeCollection); + this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal, out localeCollection); } private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal, out LocaleCollection localeCollection) @@ -1804,12 +2050,14 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem { Logger.Error(ex); } + var node = xmlPortal.SelectSingleNode("//portal/settings"); if (node != null && isNewPortal) { HtmlUtils.WriteKeepAlive(); - ParsePortalSettings(node, portalId); + this.ParsePortalSettings(node, portalId); } + node = xmlPortal.SelectSingleNode("//locales"); if (node != null && isNewPortal) { @@ -1825,18 +2073,22 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem defaultLocale = new Locale { Code = portalInfo.DefaultLanguage, Fallback = Localization.SystemLocale, Text = CultureInfo.GetCultureInfo(portalInfo.DefaultLanguage).NativeName }; Localization.SaveLanguage(defaultLocale, false); } + localeCollection = new LocaleCollection { { defaultLocale.Code, defaultLocale } }; } + node = xmlPortal.SelectSingleNode("//portal/rolegroups"); if (node != null) { - ParseRoleGroups(node.CreateNavigator(), portalId, administratorId); + this.ParseRoleGroups(node.CreateNavigator(), portalId, administratorId); } + node = xmlPortal.SelectSingleNode("//portal/roles"); if (node != null) { - ParseRoles(node.CreateNavigator(), portalId, administratorId); + this.ParseRoles(node.CreateNavigator(), portalId, administratorId); } + node = xmlPortal.SelectSingleNode("//portal/portalDesktopModules"); if (node != null) { @@ -1846,23 +2098,24 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem node = xmlPortal.SelectSingleNode("//portal/folders"); if (node != null) { - ParseFolders(node, portalId); + this.ParseFolders(node, portalId); } + node = xmlPortal.SelectSingleNode("//portal/extensionUrlProviders"); if (node != null) { - ParseExtensionUrlProviders(node.CreateNavigator(), portalId); + this.ParseExtensionUrlProviders(node.CreateNavigator(), portalId); } var defaultFolderMapping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - if (FolderManager.Instance.GetFolder(portalId, "") == null) + if (FolderManager.Instance.GetFolder(portalId, string.Empty) == null) { - objFolder = FolderManager.Instance.AddFolder(defaultFolderMapping, ""); + objFolder = FolderManager.Instance.AddFolder(defaultFolderMapping, string.Empty); objFolder.IsProtected = true; FolderManager.Instance.UpdateFolder(objFolder); - AddFolderPermissions(portalId, objFolder.FolderID); + this.AddFolderPermissions(portalId, objFolder.FolderID); } if (FolderManager.Instance.GetFolder(portalId, "Templates/") == null) @@ -1872,7 +2125,7 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem objFolder.IsProtected = true; FolderManager.Instance.UpdateFolder(objFolder); - //AddFolderPermissions(PortalId, objFolder.FolderID); + // AddFolderPermissions(PortalId, objFolder.FolderID); } // force creation of users folder if not present on template @@ -1883,7 +2136,7 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem objFolder.IsProtected = true; FolderManager.Instance.UpdateFolder(objFolder); - //AddFolderPermissions(PortalId, objFolder.FolderID); + // AddFolderPermissions(PortalId, objFolder.FolderID); } if (mergeTabs == PortalTemplateModuleAction.Replace) @@ -1902,6 +2155,7 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem } } } + node = xmlPortal.SelectSingleNode("//portal/tabs"); if (node != null) { @@ -1914,8 +2168,8 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem string path = Path.Combine(templatePath, "admin.template"); if (!File.Exists(path)) { - //if the template is a merged copy of a localized templte the - //admin.template may be one director up + // if the template is a merged copy of a localized templte the + // admin.template may be one director up path = Path.Combine(templatePath, "..\admin.template"); } @@ -1932,7 +2186,8 @@ private void ParseTemplateInternal(int portalId, string templatePath, string tem Logger.Error(ex); } } - ParseTabs(node, portalId, false, mergeTabs, isNewPortal); + + this.ParseTabs(node, portalId, false, mergeTabs, isNewPortal); } CachingProvider.EnableCacheExpiration(); @@ -1942,7 +2197,7 @@ private void PrepareLocalizedPortalTemplate(PortalTemplateInfo template, out str { if (string.IsNullOrEmpty(template.LanguageFilePath)) { - //no language to merge + // no language to merge templatePath = Path.GetDirectoryName(template.TemplateFilePath) + @"\"; templateFile = Path.GetFileName(template.TemplateFilePath); return; @@ -1990,160 +2245,79 @@ private void UpdatePortalInternal(PortalInfo portal, bool clearCache) processorPassword = Security.FIPSCompliant.EncryptAES(processorPassword, Config.GetDecryptionkey(), Host.Host.GUID); } - DataProvider.Instance().UpdatePortalInfo(portal.PortalID, - portal.PortalGroupID, - portal.PortalName, - portal.LogoFile, - portal.FooterText, - portal.ExpiryDate, - portal.UserRegistration, - portal.BannerAdvertising, - portal.Currency, - portal.AdministratorId, - portal.HostFee, - portal.HostSpace, - portal.PageQuota, - portal.UserQuota, - portal.PaymentProcessor, - portal.ProcessorUserId, - processorPassword, - portal.Description, - portal.KeyWords, - portal.BackgroundFile, - 0, //site log history function has been removed. - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.DefaultLanguage, - portal.HomeDirectory, - UserController.Instance.GetCurrentUserInfo().UserID, - portal.CultureCode); + DataProvider.Instance().UpdatePortalInfo( + portal.PortalID, + portal.PortalGroupID, + portal.PortalName, + portal.LogoFile, + portal.FooterText, + portal.ExpiryDate, + portal.UserRegistration, + portal.BannerAdvertising, + portal.Currency, + portal.AdministratorId, + portal.HostFee, + portal.HostSpace, + portal.PageQuota, + portal.UserQuota, + portal.PaymentProcessor, + portal.ProcessorUserId, + processorPassword, + portal.Description, + portal.KeyWords, + portal.BackgroundFile, + 0, // site log history function has been removed. + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.DefaultLanguage, + portal.HomeDirectory, + UserController.Instance.GetCurrentUserInfo().UserID, + portal.CultureCode); EventLogController.Instance.AddLog("PortalId", portal.PortalID.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); - //ensure a localization item exists (in case a new default language has been set) + // ensure a localization item exists (in case a new default language has been set) DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, portal.DefaultLanguage); - //clear portal cache + // clear portal cache if (clearCache) { DataCache.ClearHostCache(true); } } - private static void UpdatePortalSettingInternal(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) - { - string currentSetting = GetPortalSetting(settingName, portalID, string.Empty, cultureCode); - - if (currentSetting != settingValue) - { - if (isSecure && !string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) - { - settingValue = Security.FIPSCompliant.EncryptAES(settingValue, Config.GetDecryptionkey(), Host.Host.GUID); - } - - DataProvider.Instance().UpdatePortalSetting(portalID, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID, cultureCode, isSecure); - EventLogController.Instance.AddLog(settingName + ((cultureCode == Null.NullString) ? String.Empty : " (" + cultureCode + ")"), settingValue, GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_UPDATED); - if (clearCache) - { - DataCache.ClearPortalCache(portalID, false); - DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); - - var httpContext = HttpContext.Current; - if (httpContext != null) - { - var cultureCodeForKey = GetActivePortalLanguageFromHttpContext(httpContext, portalID); - var dictionaryKey = String.Format(HttpContextKeyPortalSettingsDictionary, portalID, cultureCodeForKey); - httpContext.Items[dictionaryKey] = null; - } - } - - EventManager.Instance.OnPortalSettingUpdated(new PortalSettingUpdatedEventArgs - { - PortalId = portalID, - SettingName = settingName, - SettingValue = settingValue - }); - } - } - private void UpdatePortalSetup(int portalId, int administratorId, int administratorRoleId, int registeredRoleId, int splashTabId, int homeTabId, int loginTabId, int registerTabId, int userTabId, int searchTabId, int custom404TabId, int custom500TabId, int termsTabId, int privacyTabId, int adminTabId, string cultureCode) { - DataProvider.Instance().UpdatePortalSetup(portalId, - administratorId, - administratorRoleId, - registeredRoleId, - splashTabId, - homeTabId, - loginTabId, - registerTabId, - userTabId, - searchTabId, - custom404TabId, - custom500TabId, - termsTabId, - privacyTabId, - adminTabId, - cultureCode); + DataProvider.Instance().UpdatePortalSetup( + portalId, + administratorId, + administratorRoleId, + registeredRoleId, + splashTabId, + homeTabId, + loginTabId, + registerTabId, + userTabId, + searchTabId, + custom404TabId, + custom500TabId, + termsTabId, + privacyTabId, + adminTabId, + cultureCode); EventLogController.Instance.AddLog("PortalId", portalId.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); DataCache.ClearHostCache(true); } - #endregion - - #region Public Methods - - /// - /// Creates a new portal alias - /// - /// Id of the portal - /// Portal Alias to be created - public void AddPortalAlias(int portalId, string portalAlias) - { - - //Check if the Alias exists - PortalAliasInfo portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalId); - - //If alias does not exist add new - if (portalAliasInfo == null) - { - portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = portalAlias, IsPrimary = true }; - PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); - } - } - - /// - /// Copies the page template. - /// - /// The template file. - /// The mapped home directory. - public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) - { - string hostTemplateFile = string.Format("{0}Templates\\{1}", Globals.HostMapPath, templateFile); - if (File.Exists(hostTemplateFile)) - { - string portalTemplateFolder = string.Format("{0}Templates\\", mappedHomeDirectory); - if (!Directory.Exists(portalTemplateFolder)) - { - //Create Portal Templates folder - Directory.CreateDirectory(portalTemplateFolder); - } - string portalTemplateFile = portalTemplateFolder + templateFile; - if (!File.Exists(portalTemplateFile)) - { - File.Copy(hostTemplateFile, portalTemplateFile); - } - } - } - /// /// Creates the portal. /// @@ -2161,10 +2335,10 @@ public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) public int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { - //Attempt to create a new portal + // Attempt to create a new portal int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); - //Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. + // Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("CreatingPortalId", portalId); @@ -2174,14 +2348,14 @@ public int CreatePortal(string portalName, int adminUserId, string description, if (portalId != -1) { - //add administrator + // add administrator int administratorId = adminUserId; var adminUser = new UserInfo(); - //add userportal record + // add userportal record UserController.AddUserPortal(portalId, administratorId); - //retrieve existing administrator + // retrieve existing administrator try { adminUser = UserController.GetUserById(portalId, administratorId); @@ -2193,7 +2367,7 @@ public int CreatePortal(string portalName, int adminUserId, string description, if (administratorId > 0) { - CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); + this.CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); } } else @@ -2201,16 +2375,17 @@ public int CreatePortal(string portalName, int adminUserId, string description, message += Localization.GetString("CreatePortal.Error"); throw new Exception(message); } + try { EnsureRequiredEventLogTypesExist(); } catch (Exception) { - //should be no exception, but suppress just in case + // should be no exception, but suppress just in case } - //remove the portal id from http context as there is no exception. + // remove the portal id from http context as there is no exception. if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) { HttpContext.Current.Items.Remove("CreatingPortalId"); @@ -2236,10 +2411,10 @@ public int CreatePortal(string portalName, int adminUserId, string description, public int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { - //Attempt to create a new portal + // Attempt to create a new portal int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); - //Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. + // Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("CreatingPortalId", portalId); @@ -2249,7 +2424,7 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio if (portalId != -1) { - //add administrator + // add administrator int administratorId = Null.NullInteger; adminUser.PortalID = portalId; try @@ -2258,8 +2433,9 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio if (createStatus == UserCreateStatus.Success) { administratorId = adminUser.UserID; - //reload the UserInfo as when it was first created, it had no portal id and therefore - //used host profile definitions + + // reload the UserInfo as when it was first created, it had no portal id and therefore + // used host profile definitions adminUser = UserController.GetUserById(adminUser.PortalID, adminUser.UserID); } else @@ -2275,7 +2451,7 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio if (administratorId > 0) { - CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); + this.CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); } } else @@ -2283,16 +2459,17 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio message += Localization.GetString("CreatePortal.Error"); throw new Exception(message); } + try { EnsureRequiredEventLogTypesExist(); } catch (Exception) { - //should be no exception, but suppress just in case + // should be no exception, but suppress just in case } - //remove the portal id from http context as there is no exception. + // remove the portal id from http context as there is no exception. if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) { HttpContext.Current.Items.Remove("CreatingPortalId"); @@ -2302,9 +2479,9 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio } /// - /// Get all the available portal templates grouped by culture + /// Get all the available portal templates grouped by culture. /// - /// List of PortalTemplateInfo objects + /// List of PortalTemplateInfo objects. public IList GetAvailablePortalTemplates() { var list = new List(); @@ -2315,7 +2492,7 @@ public IList GetAvailablePortalTemplates() foreach (string templateFilePath in templateFilePaths) { var currentFileName = Path.GetFileName(templateFilePath); - var langs = languageFileNames.Where(x => GetTemplateName(x).Equals(currentFileName, StringComparison.InvariantCultureIgnoreCase)).Select(x => GetCultureCode(x)).Distinct().ToList(); + var langs = languageFileNames.Where(x => this.GetTemplateName(x).Equals(currentFileName, StringComparison.InvariantCultureIgnoreCase)).Select(x => this.GetCultureCode(x)).Distinct().ToList(); if (langs.Any()) { @@ -2323,7 +2500,7 @@ public IList GetAvailablePortalTemplates() } else { - //DNN-6544 portal creation requires valid culture, if template has no culture defined, then use portal's default language. + // DNN-6544 portal creation requires valid culture, if template has no culture defined, then use portal's default language. var portalSettings = PortalSettings.Current; var cultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; list.Add(new PortalTemplateInfo(templateFilePath, cultureCode)); @@ -2348,10 +2525,10 @@ IAbPortalSettings IPortalController.GetCurrentSettings() } /// - /// Gets information of a portal + /// Gets information of a portal. /// - /// Id of the portal - /// PortalInfo object with portal definition + /// Id of the portal. + /// PortalInfo object with portal definition. public PortalInfo GetPortal(int portalId) { if (portalId == -1) @@ -2360,21 +2537,23 @@ public PortalInfo GetPortal(int portalId) } string defaultLanguage = GetActivePortalLanguage(portalId); - PortalInfo portal = GetPortal(portalId, defaultLanguage); + PortalInfo portal = this.GetPortal(portalId, defaultLanguage); if (portal == null) { - //Active language may not be valid, so fallback to default language + // Active language may not be valid, so fallback to default language defaultLanguage = GetPortalDefaultLanguage(portalId); - portal = GetPortal(portalId, defaultLanguage); + portal = this.GetPortal(portalId, defaultLanguage); } + return portal; } /// - /// Gets information of a portal + /// Gets information of a portal. /// - /// Id of the portal + /// Id of the portal. /// The culture code. + /// public PortalInfo GetPortal(int portalId, string cultureCode) { if (portalId == -1) @@ -2388,22 +2567,28 @@ public PortalInfo GetPortal(int portalId, string cultureCode) { if (portal == null) { - //Get Fallback language + // Get Fallback language string fallbackLanguage = string.Empty; - if (string.IsNullOrEmpty(cultureCode)) cultureCode = GetPortalDefaultLanguage(portalId); + if (string.IsNullOrEmpty(cultureCode)) + { + cultureCode = GetPortalDefaultLanguage(portalId); + } Locale userLocale = LocaleController.Instance.GetLocale(cultureCode); if (userLocale != null && !string.IsNullOrEmpty(userLocale.Fallback)) { fallbackLanguage = userLocale.Fallback; } - if (String.IsNullOrEmpty(fallbackLanguage)) + + if (string.IsNullOrEmpty(fallbackLanguage)) { fallbackLanguage = Localization.SystemLocale; } + portal = GetPortalInternal(portalId, fallbackLanguage); - //if we cannot find any fallback, it mean's it's a non portal default langauge + + // if we cannot find any fallback, it mean's it's a non portal default langauge if (portal == null) { DataProvider.Instance().EnsureLocalizationExists(portalId, GetActivePortalLanguage(portalId)); @@ -2412,6 +2597,7 @@ public PortalInfo GetPortal(int portalId, string cultureCode) } } } + return portal; } @@ -2422,16 +2608,16 @@ public PortalInfo GetPortal(int portalId, string cultureCode) /// Portal info. public PortalInfo GetPortal(Guid uniqueId) { - return GetPortalList(Null.NullString).SingleOrDefault(p => p.GUID == uniqueId); + return this.GetPortalList(Null.NullString).SingleOrDefault(p => p.GUID == uniqueId); } /// - /// Gets information from all portals + /// Gets information from all portals. /// - /// ArrayList of PortalInfo objects + /// ArrayList of PortalInfo objects. public ArrayList GetPortals() { - return new ArrayList(GetPortalList(Null.NullString)); + return new ArrayList(this.GetPortalList(Null.NullString)); } /// @@ -2441,10 +2627,10 @@ public ArrayList GetPortals() /// public List GetPortalList(string cultureCode) { - string cacheKey = String.Format(DataCache.PortalCacheKey, Null.NullInteger, cultureCode); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, cultureCode), - c => CBO.FillCollection(DataProvider.Instance().GetPortals(cultureCode)) - ); + string cacheKey = string.Format(DataCache.PortalCacheKey, Null.NullInteger, cultureCode); + return CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, cultureCode), + c => CBO.FillCollection(DataProvider.Instance().GetPortals(cultureCode))); } /// @@ -2461,7 +2647,7 @@ public Dictionary GetPortalSettings(int portalId) /// Gets the portal settings dictionary. /// /// The portal ID. - /// The culture code + /// The culture code. /// portal settings. public Dictionary GetPortalSettings(int portalId, string cultureCode) { @@ -2469,11 +2655,11 @@ public Dictionary GetPortalSettings(int portalId, string culture } /// - /// Load info for a portal template + /// Load info for a portal template. /// - /// Full path to the portal template - /// the culture code if any for the localization of the portal template - /// A portal template + /// Full path to the portal template. + /// the culture code if any for the localization of the portal template. + /// A portal template. public PortalTemplateInfo GetPortalTemplate(string templatePath, string cultureCode) { var template = new PortalTemplateInfo(templatePath, cultureCode); @@ -2487,10 +2673,10 @@ public PortalTemplateInfo GetPortalTemplate(string templatePath, string cultureC } /// - /// Gets the portal space used bytes. - /// - /// The portal id. - /// Space used in bytes + /// Gets the portal space used bytes. + /// + /// The portal id. + /// Space used in bytes. public long GetPortalSpaceUsedBytes(int portalId) { long size = 0; @@ -2513,15 +2699,16 @@ public long GetPortalSpaceUsedBytes(int portalId) { CBO.CloseDataReader(dr, true); } + return size; } /// - /// Verifies if there's enough space to upload a new file on the given portal + /// Verifies if there's enough space to upload a new file on the given portal. /// - /// Id of the portal - /// Size of the file being uploaded - /// True if there's enough space available to upload the file + /// Id of the portal. + /// Size of the file being uploaded. + /// True if there's enough space available to upload the file. public bool HasSpaceAvailable(int portalId, long fileSizeBytes) { int hostSpace; @@ -2538,16 +2725,17 @@ public bool HasSpaceAvailable(int portalId, long fileSizeBytes) } else { - PortalInfo portal = GetPortal(portalId); + PortalInfo portal = this.GetPortal(portalId); hostSpace = portal.HostSpace; } } - return (((GetPortalSpaceUsedBytes(portalId) + fileSizeBytes) / Math.Pow(1024, 2)) <= hostSpace) || hostSpace == 0; + + return (((this.GetPortalSpaceUsedBytes(portalId) + fileSizeBytes) / Math.Pow(1024, 2)) <= hostSpace) || hostSpace == 0; } /// /// Remaps the Special Pages such as Home, Profile, Search - /// to their localized versions + /// to their localized versions. /// /// /// @@ -2556,8 +2744,8 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) DataCache.ClearHostCache(true); DataProvider.Instance().EnsureLocalizationExists(portalId, cultureCode); - PortalInfo defaultPortal = GetPortal(portalId, GetPortalDefaultLanguage(portalId)); - PortalInfo targetPortal = GetPortal(portalId, cultureCode); + PortalInfo defaultPortal = this.GetPortal(portalId, GetPortalDefaultLanguage(portalId)); + PortalInfo targetPortal = this.GetPortal(portalId, cultureCode); Locale targetLocale = LocaleController.Instance.GetLocale(cultureCode); TabInfo tempTab; @@ -2569,6 +2757,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.HomeTabId = tempTab.TabID; } } + if (defaultPortal.LoginTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.LoginTabId, portalId, targetLocale); @@ -2577,6 +2766,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.LoginTabId = tempTab.TabID; } } + if (defaultPortal.RegisterTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.RegisterTabId, portalId, targetLocale); @@ -2585,6 +2775,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.RegisterTabId = tempTab.TabID; } } + if (defaultPortal.SplashTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SplashTabId, portalId, targetLocale); @@ -2593,6 +2784,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.SplashTabId = tempTab.TabID; } } + if (defaultPortal.UserTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.UserTabId, portalId, targetLocale); @@ -2601,6 +2793,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.UserTabId = tempTab.TabID; } } + if (defaultPortal.SearchTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SearchTabId, portalId, targetLocale); @@ -2609,6 +2802,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.SearchTabId = tempTab.TabID; } } + if (defaultPortal.Custom404TabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom404TabId, portalId, targetLocale); @@ -2617,6 +2811,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.Custom404TabId = tempTab.TabID; } } + if (defaultPortal.Custom500TabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom500TabId, portalId, targetLocale); @@ -2625,6 +2820,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.Custom500TabId = tempTab.TabID; } } + if (defaultPortal.TermsTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.TermsTabId, portalId, targetLocale); @@ -2633,6 +2829,7 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) targetPortal.TermsTabId = tempTab.TabID; } } + if (defaultPortal.PrivacyTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.PrivacyTabId, portalId, targetLocale); @@ -2642,11 +2839,11 @@ public void MapLocalizedSpecialPages(int portalId, string cultureCode) } } - UpdatePortalInternal(targetPortal, false); + this.UpdatePortalInternal(targetPortal, false); } /// - /// Removes the related PortalLocalization record from the database, adds optional clear cache + /// Removes the related PortalLocalization record from the database, adds optional clear cache. /// /// /// @@ -2663,9 +2860,9 @@ public void RemovePortalLocalization(int portalId, string cultureCode, bool clea /// /// Processess a template file for the new portal. /// - /// PortalId of the new portal - /// The template - /// UserId for the portal administrator. This is used to assign roles to this user + /// PortalId of the new portal. + /// The template. + /// UserId for the portal administrator. This is used to assign roles to this user. /// Flag to determine whether Module content is merged. /// Flag to determine is the template is applied to an existing portal or a new one. /// @@ -2674,16 +2871,16 @@ public void RemovePortalLocalization(int portalId, string cultureCode, bool clea public void ParseTemplate(int portalId, PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { string templatePath, templateFile; - PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); + this.PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); - ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal); + this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal); } /// - /// Processes the resource file for the template file selected + /// Processes the resource file for the template file selected. /// - /// New portal's folder - /// full path to the resource file + /// New portal's folder. + /// full path to the resource file. /// /// The resource file is a zip file with the same name as the selected template file and with /// an extension of .resources (to disable this file being downloaded). @@ -2708,24 +2905,25 @@ public void ProcessResourceFileExplicit(string portalPath, string resoureceFile) /// The culture code. public void UpdatePortalExpiry(int portalId, string cultureCode) { - var portal = GetPortal(portalId, cultureCode); + var portal = this.GetPortal(portalId, cultureCode); if (portal.ExpiryDate == Null.NullDate) { portal.ExpiryDate = DateTime.Now; } + portal.ExpiryDate = portal.ExpiryDate.AddMonths(1); - UpdatePortalInfo(portal); + this.UpdatePortalInfo(portal); } /// - /// Updates basic portal information + /// Updates basic portal information. /// /// public void UpdatePortalInfo(PortalInfo portal) { - UpdatePortalInternal(portal, true); + this.UpdatePortalInternal(portal, true); } [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] @@ -2742,67 +2940,6 @@ void IPortalController.UpdatePortalSetting(int portalID, string settingName, str UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); } - #endregion - - #region Public Static Methods - - /// - /// Adds the portal dictionary. - /// - /// The portal id. - /// The tab id. - public static void AddPortalDictionary(int portalId, int tabId) - { - var portalDic = GetPortalDictionary(); - portalDic[tabId] = portalId; - DataCache.SetCache(DataCache.PortalDictionaryCacheKey, portalDic); - } - - /// - /// Creates the root folder for a child portal. - /// - /// - /// If call this method, it will create the specific folder if the folder doesn't exist; - /// and will copy subhost.aspx to the folder if there is no 'Default.aspx'; - /// - /// The child path. - /// - /// If the method executed successful, it will return NullString, otherwise return error message. - /// - /// - /// - /// string childPhysicalPath = Server.MapPath(childPath); - /// message = PortalController.CreateChildPortalFolder(childPhysicalPath); - /// - /// - public static string CreateChildPortalFolder(string ChildPath) - { - string message = Null.NullString; - - //Set up Child Portal - try - { - // create the subdirectory for the new portal - if (!Directory.Exists(ChildPath)) - { - Directory.CreateDirectory(ChildPath); - } - - // create the subhost default.aspx file - if (!File.Exists(ChildPath + "\\" + Globals.glbDefaultPage)) - { - File.Copy(Globals.HostMapPath + "subhost.aspx", ChildPath + "\\" + Globals.glbDefaultPage); - } - } - catch (Exception Exc) - { - Logger.Error(Exc); - message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; - } - - return message; - } - /// /// Deletes all expired portals. /// @@ -2825,16 +2962,16 @@ public static string DeletePortal(PortalInfo portal, string serverPath) { string message = string.Empty; - //check if this is the last portal + // check if this is the last portal var portals = Instance.GetPortals(); if (portals.Count > 1) { if (portal != null) { - //delete custom resource files + // delete custom resource files Globals.DeleteFilesRecursive(serverPath, ".Portal-" + portal.PortalID + ".resx"); - //If child portal delete child folder + // If child portal delete child folder var arr = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); if (arr.Count > 0) { @@ -2844,15 +2981,18 @@ public static string DeletePortal(PortalInfo portal, string serverPath) { portalName = GetPortalFolder(portalAliasInfo.HTTPAlias); } - if (!String.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) + + if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) { DeletePortalFolder(serverPath, portalName); } } - //delete upload directory + + // delete upload directory if (!string.IsNullOrEmpty(portal.HomeDirectory)) { var homeDirectory = portal.HomeDirectoryMapPath; + // check whether home directory is not used by other portal // it happens when new portal creation failed, but home directory defined by user is already in use with other portal var homeDirectoryInUse = portals.OfType().Any(x => @@ -2867,7 +3007,8 @@ public static string DeletePortal(PortalInfo portal, string serverPath) } } } - //remove database references + + // remove database references DeletePortalInternal(portal.PortalID); } } @@ -2875,6 +3016,7 @@ public static string DeletePortal(PortalInfo portal, string serverPath) { message = Localization.GetString("LastPortal"); } + return message; } @@ -2903,7 +3045,7 @@ public static void DeletePortalFolder(string serverPath, string portalFolder) var physicalPath = serverPath + portalFolder; Globals.DeleteFolderRecursive(physicalPath); - //remove parent folder if its empty. + // remove parent folder if its empty. var parentFolder = Directory.GetParent(physicalPath); while (parentFolder != null && !parentFolder.FullName.Equals(serverPath.TrimEnd('\\'), StringComparison.InvariantCultureIgnoreCase)) { @@ -2931,13 +3073,13 @@ public static Dictionary GetPortalDictionary() /// ----------------------------------------------------------------------------- /// - /// GetPortalsByName gets all the portals whose name matches a provided filter expression + /// GetPortalsByName gets all the portals whose name matches a provided filter expression. /// /// /// /// The email address to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of PortalInfo objects. /// ----------------------------------------------------------------------------- @@ -2948,6 +3090,7 @@ public static ArrayList GetPortalsByName(string nameToMatch, int pageIndex, int pageIndex = 0; pageSize = int.MaxValue; } + Type type = typeof(PortalInfo); return CBO.FillCollection(DataProvider.Instance().GetPortalsByName(nameToMatch, pageIndex, pageSize), ref type, ref totalRecords); } @@ -3006,11 +3149,13 @@ public static bool IsChildPortal(PortalInfo portal, string serverPath) { portalName = GetPortalFolder(portalAlias.HTTPAlias); } - if (!String.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) + + if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) { isChild = true; } } + return isChild; } @@ -3032,15 +3177,15 @@ public static void DeletePortalSetting(int portalID, string settingName) } /// - /// Deletes the portal setting in this language. - /// + /// Deletes the portal setting in this language. + /// /// The portal ID. /// Name of the setting. - /// The culture code. - public static void DeletePortalSetting(int portalID, string settingName, string cultureCode) + /// The culture code. + public static void DeletePortalSetting(int portalID, string settingName, string cultureCode) { DataProvider.Instance().DeletePortalSetting(portalID, settingName, cultureCode.ToLowerInvariant()); - EventLogController.Instance.AddLog("SettingName", settingName + ((cultureCode == Null.NullString) ? String.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); + EventLogController.Instance.AddLog("SettingName", settingName + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); DataCache.ClearHostCache(true); } @@ -3060,15 +3205,15 @@ public static void DeletePortalSettings(int portalID) public static void DeletePortalSettings(int portalID, string cultureCode) { DataProvider.Instance().DeletePortalSettings(portalID, cultureCode); - EventLogController.Instance.AddLog("PortalID", portalID.ToString() + ((cultureCode == Null.NullString) ? String.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); + EventLogController.Instance.AddLog("PortalID", portalID.ToString() + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); DataCache.ClearHostCache(true); } /// - /// takes in a text value, decrypts it with a FIPS compliant algorithm and returns the value + /// takes in a text value, decrypts it with a FIPS compliant algorithm and returns the value. /// - /// the setting to read - /// the pass phrase used for encryption/decryption + /// the setting to read. + /// the pass phrase used for encryption/decryption. /// public static string GetEncryptedString(string settingName, int portalID, string passPhrase) { @@ -3100,18 +3245,19 @@ public static string GetPortalSetting(string settingName, int portalID, string d { Logger.Error(exc); } + return retValue; } /// - /// Gets the portal setting for a specific language (or neutral). - /// - /// Name of the setting. - /// The portal ID. - /// The default value. - /// culture code of the language to retrieve (not empty) - /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. - public static string GetPortalSetting(string settingName, int portalID, string defaultValue, string cultureCode) + /// Gets the portal setting for a specific language (or neutral). + /// + /// Name of the setting. + /// The portal ID. + /// The default value. + /// culture code of the language to retrieve (not empty). + /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. + public static string GetPortalSetting(string settingName, int portalID, string defaultValue, string cultureCode) { var retValue = Null.NullString; try @@ -3124,6 +3270,7 @@ public static string GetPortalSetting(string settingName, int portalID, string d { Logger.Error(exc); } + return retValue; } @@ -3147,25 +3294,26 @@ public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defa } else { - retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); } } catch (Exception exc) { Logger.Error(exc); } + return retValue; } /// - /// Gets the portal setting as boolean for a specific language (or neutral). - /// - /// The key. - /// The portal ID. - /// default value. - /// culture code of the language to retrieve (not empty) - /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. - public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue, string cultureCode) + /// Gets the portal setting as boolean for a specific language (or neutral). + /// + /// The key. + /// The portal ID. + /// default value. + /// culture code of the language to retrieve (not empty). + /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. + public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue, string cultureCode) { bool retValue = Null.NullBoolean; try @@ -3178,13 +3326,14 @@ public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defa } else { - retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); } } catch (Exception exc) { Logger.Error(exc); } + return retValue; } @@ -3215,11 +3364,12 @@ public static int GetPortalSettingAsInteger(string key, int portalID, int defaul { Logger.Error(exc); } + return retValue; } /// - /// Gets the portal setting as double. + /// Gets the portal setting as double. /// /// The key. /// The portal Id. @@ -3245,18 +3395,19 @@ public static double GetPortalSettingAsDouble(string key, int portalId, double d { Logger.Error(exc); } + return retValue; } /// - /// Gets the portal setting as integer for a specific language (or neutral). - /// - /// The key. - /// The portal ID. - /// The default value. - /// culture code of the language to retrieve (not empty) - /// Returns setting's value if portal contains the specific setting (for specified lang, otherwise return defaultValue. - public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue, string cultureCode) + /// Gets the portal setting as integer for a specific language (or neutral). + /// + /// The key. + /// The portal ID. + /// The default value. + /// culture code of the language to retrieve (not empty). + /// Returns setting's value if portal contains the specific setting (for specified lang, otherwise return defaultValue. + public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue, string cultureCode) { int retValue = Null.NullInteger; try @@ -3276,15 +3427,17 @@ public static int GetPortalSettingAsInteger(string key, int portalID, int defaul { Logger.Error(exc); } + return retValue; } + /// - /// takes in a text value, encrypts it with a FIPS compliant algorithm and stores + /// takes in a text value, encrypts it with a FIPS compliant algorithm and stores. /// /// The portal ID. - /// host settings key - /// host settings value - /// pass phrase to allow encryption/decryption + /// host settings key. + /// host settings value. + /// pass phrase to allow encryption/decryption. public static void UpdateEncryptedString(int portalID, string settingName, string settingValue, string passPhrase) { Requires.NotNullOrEmpty("key", settingName); @@ -3308,8 +3461,8 @@ public static void UpdatePortalSetting(int portalID, string settingName, string } /// - /// Updates a single neutral (not language specific) portal setting, optionally without clearing the cache. - /// + /// Updates a single neutral (not language specific) portal setting, optionally without clearing the cache. + /// /// The portal ID. /// Name of the setting. /// The setting value. @@ -3333,30 +3486,30 @@ public static void UpdatePortalSetting(int portalID, string settingName, string } /// - /// Updates a language specific or neutral portal setting and optionally clears it from the cache. - /// + /// Updates a language specific or neutral portal setting and optionally clears it from the cache. + /// /// The portal ID. /// Name of the setting. /// The setting value. /// if set to true [clear cache]. - /// culture code for language specific settings, null string ontherwise. - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) + /// culture code for language specific settings, null string ontherwise. + public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) { UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, false); } /// - /// Updates a language specific or neutral portal setting and optionally clears it from the cache. + /// Updates a language specific or neutral portal setting and optionally clears it from the cache. /// All overloaded methors will not encrypt the setting value. Therefore, call this method whenever /// there is a need to encrypt the setting value before storing it in the datanbase. - /// + /// /// The portal ID. /// Name of the setting. /// The setting value. /// if set to true [clear cache]. - /// culture code for language specific settings, null string ontherwise. - /// When true it encrypt the value before storing it in the database - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) + /// culture code for language specific settings, null string ontherwise. + /// When true it encrypt the value before storing it in the database. + public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) { Instance.UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); } @@ -3381,8 +3534,8 @@ public static string CheckDesktopModulesInstalled(XPathNavigator nav) desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); if (desktopModule == null) { - //PE and EE templates have HTML as friendly name so check to make sure - //there is really no HTML module installed + // PE and EE templates have HTML as friendly name so check to make sure + // there is really no HTML module installed if (friendlyName == "HTML") { desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName("HTML Pro"); @@ -3400,12 +3553,13 @@ public static string CheckDesktopModulesInstalled(XPathNavigator nav) } } } + return modulesNotInstalled.ToString(); } /// /// function provides the language for portalinfo requests - /// in case where language has not been installed yet, will return the core install default of en-us + /// in case where language has not been installed yet, will return the core install default of en-us. /// /// /// @@ -3417,41 +3571,43 @@ public static string GetActivePortalLanguage(int portalID) string Language = Localization.SystemLocale; string tmpLanguage = GetPortalDefaultLanguage(portalID); var isDefaultLanguage = false; - if (!String.IsNullOrEmpty(tmpLanguage)) + if (!string.IsNullOrEmpty(tmpLanguage)) { Language = tmpLanguage; isDefaultLanguage = true; } - //handles case where portalcontroller methods invoked before a language is installed + + // handles case where portalcontroller methods invoked before a language is installed if (portalID > Null.NullInteger && Globals.Status == Globals.UpgradeStatus.None && Localization.ActiveLanguagesByPortalID(portalID) == 1) { return Language; } + if (HttpContext.Current != null && Globals.Status == Globals.UpgradeStatus.None) { - if ((HttpContext.Current.Request.QueryString["language"] != null)) + if (HttpContext.Current.Request.QueryString["language"] != null) { Language = HttpContext.Current.Request.QueryString["language"]; } else { PortalSettings _PortalSettings = GetCurrentPortalSettingsInternal(); - if (_PortalSettings != null && _PortalSettings.ActiveTab != null && !String.IsNullOrEmpty(_PortalSettings.ActiveTab.CultureCode)) + if (_PortalSettings != null && _PortalSettings.ActiveTab != null && !string.IsNullOrEmpty(_PortalSettings.ActiveTab.CultureCode)) { Language = _PortalSettings.ActiveTab.CultureCode; } else { - //PortalSettings IS Nothing - probably means we haven't set it yet (in Begin Request) - //so try detecting the user's cookie + // PortalSettings IS Nothing - probably means we haven't set it yet (in Begin Request) + // so try detecting the user's cookie if (HttpContext.Current.Request["language"] != null) { Language = HttpContext.Current.Request["language"]; isDefaultLanguage = false; } - //if no cookie - try detecting browser - if ((String.IsNullOrEmpty(Language) || isDefaultLanguage) && EnableBrowserLanguageInDefault(portalID)) + // if no cookie - try detecting browser + if ((string.IsNullOrEmpty(Language) || isDefaultLanguage) && EnableBrowserLanguageInDefault(portalID)) { CultureInfo Culture = Localization.GetBrowserCulture(portalID); @@ -3468,7 +3624,7 @@ public static string GetActivePortalLanguage(int portalID) } /// - /// return the current DefaultLanguage value from the Portals table for the requested Portalid + /// return the current DefaultLanguage value from the Portals table for the requested Portalid. /// /// /// @@ -3476,13 +3632,13 @@ public static string GetActivePortalLanguage(int portalID) /// public static string GetPortalDefaultLanguage(int portalID) { - string cacheKey = String.Format("PortalDefaultLanguage_{0}", portalID); + string cacheKey = string.Format("PortalDefaultLanguage_{0}", portalID); return CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, portalID), GetPortalDefaultLanguageCallBack); } /// /// set the required DefaultLanguage in the Portals table for a particular portal - /// saves having to update an entire PortalInfo object + /// saves having to update an entire PortalInfo object. /// /// /// @@ -3491,8 +3647,9 @@ public static string GetPortalDefaultLanguage(int portalID) public static void UpdatePortalDefaultLanguage(int portalID, string CultureCode) { DataProvider.Instance().UpdatePortalDefaultLanguage(portalID, CultureCode); - //ensure localization record exists as new portal default language may be relying on fallback chain - //of which it is now the final part + + // ensure localization record exists as new portal default language may be relying on fallback chain + // of which it is now the final part DataProvider.Instance().EnsureLocalizationExists(portalID, CultureCode); } @@ -3523,36 +3680,47 @@ public static void IncrementOverridingPortalsCrmVersion() } } - #endregion - public class PortalTemplateInfo { - private string _resourceFilePath; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); + private string _resourceFilePath; public PortalTemplateInfo(string templateFilePath, string cultureCode) { - TemplateFilePath = templateFilePath; + this.TemplateFilePath = templateFilePath; + + this.InitLocalizationFields(cultureCode); + this.InitNameAndDescription(); + } + + public string Name { get; private set; } + + public string CultureCode { get; private set; } + + public string TemplateFilePath { get; private set; } - InitLocalizationFields(cultureCode); - InitNameAndDescription(); + private static string ReadLanguageFileValue(XDocument xmlDoc, string name) + { + return (from f in xmlDoc.Descendants("data") + where (string)f.Attribute("name") == name + select (string)f.Element("value")).SingleOrDefault(); } private void InitNameAndDescription() { - if (!String.IsNullOrEmpty(LanguageFilePath)) + if (!string.IsNullOrEmpty(this.LanguageFilePath)) { - LoadNameAndDescriptionFromLanguageFile(); + this.LoadNameAndDescriptionFromLanguageFile(); } - if (String.IsNullOrEmpty(Name)) + if (string.IsNullOrEmpty(this.Name)) { - Name = Path.GetFileNameWithoutExtension(TemplateFilePath); + this.Name = Path.GetFileNameWithoutExtension(this.TemplateFilePath); } - if (String.IsNullOrEmpty(Description)) + if (string.IsNullOrEmpty(this.Description)) { - LoadDescriptionFromTemplateFile(); + this.LoadDescriptionFromTemplateFile(); } } @@ -3561,16 +3729,16 @@ private void LoadDescriptionFromTemplateFile() try { XDocument xmlDoc; - using (var reader = PortalTemplateIO.Instance.OpenTextReader(TemplateFilePath)) + using (var reader = PortalTemplateIO.Instance.OpenTextReader(this.TemplateFilePath)) { xmlDoc = XDocument.Load(reader); } - Description = xmlDoc.Elements("portal").Elements("description").SingleOrDefault().Value; + this.Description = xmlDoc.Elements("portal").Elements("description").SingleOrDefault().Value; } catch (Exception e) { - Logger.Error("Error while parsing: " + TemplateFilePath, e); + Logger.Error("Error while parsing: " + this.TemplateFilePath, e); } } @@ -3578,58 +3746,50 @@ private void LoadNameAndDescriptionFromLanguageFile() { try { - using (var reader = PortalTemplateIO.Instance.OpenTextReader(LanguageFilePath)) + using (var reader = PortalTemplateIO.Instance.OpenTextReader(this.LanguageFilePath)) { var xmlDoc = XDocument.Load(reader); - Name = ReadLanguageFileValue(xmlDoc, "LocalizedTemplateName.Text"); - Description = ReadLanguageFileValue(xmlDoc, "PortalDescription.Text"); + this.Name = ReadLanguageFileValue(xmlDoc, "LocalizedTemplateName.Text"); + this.Description = ReadLanguageFileValue(xmlDoc, "PortalDescription.Text"); } } catch (Exception e) { - Logger.Error("Error while parsing: " + TemplateFilePath, e); + Logger.Error("Error while parsing: " + this.TemplateFilePath, e); } } - static string ReadLanguageFileValue(XDocument xmlDoc, string name) - { - return (from f in xmlDoc.Descendants("data") - where (string)f.Attribute("name") == name - select (string)f.Element("value")).SingleOrDefault(); - } - private void InitLocalizationFields(string cultureCode) { - LanguageFilePath = PortalTemplateIO.Instance.GetLanguageFilePath(TemplateFilePath, cultureCode); - if (!String.IsNullOrEmpty(LanguageFilePath)) + this.LanguageFilePath = PortalTemplateIO.Instance.GetLanguageFilePath(this.TemplateFilePath, cultureCode); + if (!string.IsNullOrEmpty(this.LanguageFilePath)) { - CultureCode = cultureCode; + this.CultureCode = cultureCode; } else { var portalSettings = PortalSettings.Current; - //DNN-6544 portal creation requires valid culture, if template has no culture defined, then use default language. - CultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; + + // DNN-6544 portal creation requires valid culture, if template has no culture defined, then use default language. + this.CultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; } } - public string Name { get; private set; } - public string CultureCode { get; private set; } - public string TemplateFilePath { get; private set; } public string LanguageFilePath { get; private set; } + public string Description { get; private set; } public string ResourceFilePath { get { - if (_resourceFilePath == null) + if (this._resourceFilePath == null) { - _resourceFilePath = PortalTemplateIO.Instance.GetResourceFilePath(TemplateFilePath); + this._resourceFilePath = PortalTemplateIO.Instance.GetResourceFilePath(this.TemplateFilePath); } - return _resourceFilePath; + return this._resourceFilePath; } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalCreatedEventArgs.cs b/DNN Platform/Library/Entities/Portals/PortalCreatedEventArgs.cs index 8839c31eae8..3d6ddb4cce2 100644 --- a/DNN Platform/Library/Entities/Portals/PortalCreatedEventArgs.cs +++ b/DNN Platform/Library/Entities/Portals/PortalCreatedEventArgs.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System; + public class PortalCreatedEventArgs : EventArgs { public int PortalId { get; set; } diff --git a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs index 2302545b47c..d983fc31f9b 100644 --- a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs @@ -1,39 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Internal; -using DotNetNuke.Entities.Portals.Data; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Internal; + using DotNetNuke.Entities.Portals.Data; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Log.EventLog; + public class PortalGroupController : ComponentBase, IPortalGroupController { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalGroupController)); private readonly IDataService _dataService; private readonly IPortalController _portalController; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalGroupController)); - - #region Constructors - + public PortalGroupController() : this(DataService.Instance, PortalController.Instance) { @@ -41,84 +34,195 @@ public PortalGroupController() public PortalGroupController(IDataService dataService, IPortalController portalController) { - //Argument Contract + // Argument Contract Requires.NotNull("dataService", dataService); Requires.NotNull("portalController", portalController); - _dataService = dataService; - _portalController = portalController; + this._dataService = dataService; + this._portalController = portalController; + } + + public void AddPortalToGroup(PortalInfo portal, PortalGroupInfo portalGroup, UserCopiedCallback callback) + { + Requires.NotNull("portal", portal); + Requires.PropertyNotNegative("portal", "PortalId", portal.PortalID); + Requires.NotNull("portalGroup", portalGroup); + Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); + Requires.PropertyNotNegative("portalGroup", "MasterPortalId", portalGroup.MasterPortalId); + + this.OnAddPortalToGroupStart(callback, portal); + + var users = UserController.GetUsers(portal.PortalID); + var masterUsers = UserController.GetUsers(portalGroup.MasterPortalId); + var totalUsers = users.Count + masterUsers.Count; + var userNo = 0; + + if (users.Count > 0) + { + var masterPortal = this._portalController.GetPortal(portalGroup.MasterPortalId); + + foreach (UserInfo user in users) + { + userNo += 1; + + UserController.MoveUserToPortal(user, masterPortal, true); + + this.OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); + } + } + + if (masterUsers.Count > 0) + { + var autoAssignRoles = RoleController.Instance.GetRoles( + portal.PortalID, + role => + role.AutoAssignment && + role.Status == RoleStatus.Approved); + foreach (UserInfo user in masterUsers) + { + userNo += 1; + foreach (var autoAssignRole in autoAssignRoles) + { + RoleController.Instance.AddUserRole(portalGroup.MasterPortalId, user.UserID, autoAssignRole.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + + this.OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); + } + } + + this.OnAddPortalToGroupFinishing(callback, portal, users.Count); + + this.RemoveProfileDefinitions(portal); + + // Add portal to group + portal.PortalGroupID = portalGroup.PortalGroupId; + PortalController.Instance.UpdatePortalInfo(portal); + this.LogEvent(EventLogController.EventLogType.PORTAL_ADDEDTOPORTALGROUP, portalGroup, portal); + + this.OnAddPortalToGroupFinished(callback, portal, portalGroup, users.Count); } - #endregion + public int AddPortalGroup(PortalGroupInfo portalGroup) + { + // Argument Contract + Requires.NotNull("portalGroup", portalGroup); - #region Private Methods + portalGroup.PortalGroupId = this._dataService.AddPortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); - private object GetPortalGroupsCallback(CacheItemArgs cacheItemArgs) + // Update portal + var portal = this._portalController.GetPortal(portalGroup.MasterPortalId); + if (portal != null) + { + portal.PortalGroupID = portalGroup.PortalGroupId; + this._portalController.UpdatePortalInfo(portal); + } + + this.LogEvent(EventLogController.EventLogType.PORTALGROUP_CREATED, portalGroup, null); + + ClearCache(); + + return portalGroup.PortalGroupId; + } + + public void DeletePortalGroup(PortalGroupInfo portalGroup) { - return CBO.FillCollection(_dataService.GetPortalGroups()); + // Argument Contract + Requires.NotNull("portalGroup", portalGroup); + Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); + + // Update portal + var portal = this._portalController.GetPortal(portalGroup.MasterPortalId); + if (portal != null) + { + this.DeleteSharedModules(portal); + portal.PortalGroupID = -1; + PortalController.Instance.UpdatePortalInfo(portal); + } + + this._dataService.DeletePortalGroup(portalGroup); + this.LogEvent(EventLogController.EventLogType.PORTALGROUP_DELETED, portalGroup, null); + + ClearCache(); } private static void ClearCache() { DataCache.RemoveCache(DataCache.PortalGroupsCacheKey); } + + private object GetPortalGroupsCallback(CacheItemArgs cacheItemArgs) + { + return CBO.FillCollection(this._dataService.GetPortalGroups()); + } private void OnAddPortalToGroupStart(UserCopiedCallback callback, PortalInfo portal) { - if (callback == null) return; - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = 0, UserNo = 0, - UserName = "", + UserName = string.Empty, PortalName = portal.PortalName, - Stage = "starting" + Stage = "starting", }; callback(args); } private void OnUserAddedToSiteGroup(UserCopiedCallback callback, PortalInfo portal, UserInfo currentUser, int totalUsers, int currentUserNumber) { - if (callback == null) return; - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = totalUsers, UserNo = currentUserNumber, UserName = currentUser.Username, - PortalName = portal.PortalName + PortalName = portal.PortalName, }; callback(args); } private void OnAddPortalToGroupFinishing(UserCopiedCallback callback, PortalInfo portal, int totalUsers) { - if (callback == null) return; - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = totalUsers, UserNo = totalUsers, - UserName = "", + UserName = string.Empty, PortalName = portal.PortalName, - Stage = "finalizing" + Stage = "finalizing", }; callback(args); } private void OnAddPortalToGroupFinished(UserCopiedCallback callback, PortalInfo portal, PortalGroupInfo portalGroup, int totalUsers) { - if (callback == null) return; - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = totalUsers, UserNo = totalUsers, - UserName = "", + UserName = string.Empty, PortalName = portal.PortalName, Stage = "finished", - PortalGroupId = portalGroup.PortalGroupId + PortalGroupId = portalGroup.PortalGroupId, }; callback(args); } @@ -130,7 +234,7 @@ private void LogEvent(EventLogController.EventLogType eventType, PortalGroupInfo var log = new LogInfo { BypassBuffering = true, - LogTypeKey = eventType.ToString() + LogTypeKey = eventType.ToString(), }; log.LogProperties.Add(new LogDetailInfo("PortalGroup:", portalGroup.PortalGroupName)); log.LogProperties.Add(new LogDetailInfo("PortalGroupID:", portalGroup.PortalGroupId.ToString())); @@ -139,75 +243,14 @@ private void LogEvent(EventLogController.EventLogType eventType, PortalGroupInfo log.LogProperties.Add(new LogDetailInfo("Portal:", portal.PortalName)); log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); } + LogController.Instance.AddLog(log); } catch (Exception exc) { Logger.Error(exc); } - } - - #endregion - - #region IPortalGroupController Members - - public void AddPortalToGroup(PortalInfo portal, PortalGroupInfo portalGroup, UserCopiedCallback callback) - { - Requires.NotNull("portal", portal); - Requires.PropertyNotNegative("portal", "PortalId", portal.PortalID); - Requires.NotNull("portalGroup", portalGroup); - Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); - Requires.PropertyNotNegative("portalGroup", "MasterPortalId", portalGroup.MasterPortalId); - - OnAddPortalToGroupStart(callback, portal); - - var users = UserController.GetUsers(portal.PortalID); - var masterUsers = UserController.GetUsers(portalGroup.MasterPortalId); - var totalUsers = users.Count + masterUsers.Count; - var userNo = 0; - - if (users.Count > 0) - { - var masterPortal = _portalController.GetPortal(portalGroup.MasterPortalId); - - foreach (UserInfo user in users) - { - userNo += 1; - - UserController.MoveUserToPortal(user, masterPortal, true); - - OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); - } - } - - if (masterUsers.Count > 0) - { - var autoAssignRoles = RoleController.Instance.GetRoles(portal.PortalID, - role => - role.AutoAssignment && - role.Status == RoleStatus.Approved); - foreach (UserInfo user in masterUsers) - { - userNo += 1; - foreach (var autoAssignRole in autoAssignRoles) - { - RoleController.Instance.AddUserRole(portalGroup.MasterPortalId, user.UserID, autoAssignRole.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); - } - } - - OnAddPortalToGroupFinishing(callback, portal, users.Count); - - RemoveProfileDefinitions(portal); - - //Add portal to group - portal.PortalGroupID = portalGroup.PortalGroupId; - PortalController.Instance.UpdatePortalInfo(portal); - LogEvent(EventLogController.EventLogType.PORTAL_ADDEDTOPORTALGROUP, portalGroup, portal); - - OnAddPortalToGroupFinished(callback, portal, portalGroup, users.Count); - } + } private void RemoveProfileDefinitions(PortalInfo portal) { @@ -230,13 +273,13 @@ private void CopyPropertyDefinitions(int portalId, int masterPortalId) private void DeleteSharedModules(PortalInfo portal) { - var sharedModules = GetSharedModulesWithPortal(portal); + var sharedModules = this.GetSharedModulesWithPortal(portal); foreach (var sharedModule in sharedModules) { ModuleController.Instance.DeleteTabModule(sharedModule.TabID, sharedModule.ModuleID, false); } - sharedModules = GetSharedModulesByPortal(portal); + sharedModules = this.GetSharedModulesByPortal(portal); foreach (var sharedModule in sharedModules) { ModuleController.Instance.DeleteTabModule(sharedModule.TabID, sharedModule.ModuleID, false); @@ -245,70 +288,34 @@ private void DeleteSharedModules(PortalInfo portal) private IEnumerable GetSharedModulesWithPortal(PortalInfo portal) { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.SharedModulesWithPortalCacheKey, - DataCache.SharedModulesWithPortalCacheTimeOut, - DataCache.SharedModulesWithPortalCachePriority, - portal), - (p) => CBO.FillCollection(_dataService.GetSharedModulesWithPortal(portal))); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.SharedModulesWithPortalCacheKey, + DataCache.SharedModulesWithPortalCacheTimeOut, + DataCache.SharedModulesWithPortalCachePriority, + portal), + (p) => CBO.FillCollection(this._dataService.GetSharedModulesWithPortal(portal))); } private IEnumerable GetSharedModulesByPortal(PortalInfo portal) { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.SharedModulesByPortalCacheKey, - DataCache.SharedModulesByPortalCacheTimeOut, - DataCache.SharedModulesByPortalCachePriority, - portal), - (p) => CBO.FillCollection(_dataService.GetSharedModulesByPortal(portal))); - } - - public int AddPortalGroup(PortalGroupInfo portalGroup) - { - //Argument Contract - Requires.NotNull("portalGroup", portalGroup); - - portalGroup.PortalGroupId = _dataService.AddPortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); - - //Update portal - var portal = _portalController.GetPortal(portalGroup.MasterPortalId); - if (portal != null) - { - portal.PortalGroupID = portalGroup.PortalGroupId; - _portalController.UpdatePortalInfo(portal); - } - LogEvent(EventLogController.EventLogType.PORTALGROUP_CREATED, portalGroup, null); - - ClearCache(); - - return portalGroup.PortalGroupId; - } - - public void DeletePortalGroup(PortalGroupInfo portalGroup) - { - //Argument Contract - Requires.NotNull("portalGroup", portalGroup); - Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); - - //Update portal - var portal = _portalController.GetPortal(portalGroup.MasterPortalId); - if (portal != null) - { - DeleteSharedModules(portal); - portal.PortalGroupID = -1; - PortalController.Instance.UpdatePortalInfo(portal); - } - - _dataService.DeletePortalGroup(portalGroup); - LogEvent(EventLogController.EventLogType.PORTALGROUP_DELETED, portalGroup, null); - - ClearCache(); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.SharedModulesByPortalCacheKey, + DataCache.SharedModulesByPortalCacheTimeOut, + DataCache.SharedModulesByPortalCachePriority, + portal), + (p) => CBO.FillCollection(this._dataService.GetSharedModulesByPortal(portal))); } public IEnumerable GetPortalGroups() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.PortalGroupsCacheKey, - DataCache.PortalGroupsCacheTimeOut, - DataCache.PortalGroupsCachePriority), - GetPortalGroupsCallback); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PortalGroupsCacheKey, + DataCache.PortalGroupsCacheTimeOut, + DataCache.PortalGroupsCachePriority), + this.GetPortalGroupsCallback); } public IEnumerable GetPortalsByGroup(int portalGroupId) @@ -322,31 +329,31 @@ public IEnumerable GetPortalsByGroup(int portalGroupId) public void RemovePortalFromGroup(PortalInfo portal, PortalGroupInfo portalGroup, bool copyUsers, UserCopiedCallback callback) { - //Argument Contract + // Argument Contract Requires.NotNull("portal", portal); Requires.PropertyNotNegative("portal", "PortalId", portal.PortalID); Requires.NotNull("portalGroup", portalGroup); Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); Requires.PropertyNotNegative("portalGroup", "MasterPortalId", portalGroup.MasterPortalId); - //Callback to update progress bar + // Callback to update progress bar var args = new UserCopiedEventArgs { TotalUsers = 0, UserNo = 0, - UserName = "", + UserName = string.Empty, PortalName = portal.PortalName, - Stage = "startingremove" + Stage = "startingremove", }; callback(args); - //Remove portal from group - DeleteSharedModules(portal); + // Remove portal from group + this.DeleteSharedModules(portal); portal.PortalGroupID = -1; PortalController.Instance.UpdatePortalInfo(portal); - LogEvent(EventLogController.EventLogType.PORTAL_REMOVEDFROMPORTALGROUP, portalGroup, portal); + this.LogEvent(EventLogController.EventLogType.PORTAL_REMOVEDFROMPORTALGROUP, portalGroup, portal); - CopyPropertyDefinitions(portal.PortalID, portalGroup.MasterPortalId); + this.CopyPropertyDefinitions(portal.PortalID, portalGroup.MasterPortalId); var userNo = 0; if (copyUsers) @@ -358,13 +365,13 @@ public void RemovePortalFromGroup(PortalInfo portal, PortalGroupInfo portalGroup UserController.CopyUserToPortal(masterUser, portal, false); - //Callback to update progress bar + // Callback to update progress bar args = new UserCopiedEventArgs { TotalUsers = users.Count, UserNo = userNo, UserName = masterUser.Username, - PortalName = portal.PortalName + PortalName = portal.PortalName, }; callback(args); @@ -372,7 +379,7 @@ public void RemovePortalFromGroup(PortalInfo portal, PortalGroupInfo portalGroup } else { - //Get admin users + // Get admin users var adminUsers = RoleController.Instance.GetUsersByRole(Null.NullInteger, portal.AdministratorRoleName) .Where(u => RoleController.Instance.GetUserRole(portal.PortalID, u.UserID, portal.AdministratorRoleId) != null); @@ -380,48 +387,51 @@ public void RemovePortalFromGroup(PortalInfo portal, PortalGroupInfo portalGroup { UserController.CopyUserToPortal(user, portal, false); - //Callback to update progress bar + // Callback to update progress bar args = new UserCopiedEventArgs { TotalUsers = 1, UserNo = ++userNo, UserName = user.Username, - PortalName = portal.PortalName + PortalName = portal.PortalName, }; callback(args); } } - //Callback to update progress bar + + // Callback to update progress bar args = new UserCopiedEventArgs { TotalUsers = 1, UserNo = userNo, - UserName = "", + UserName = string.Empty, PortalName = portal.PortalName, Stage = "finishedremove", - PortalGroupId = portalGroup.PortalGroupId + PortalGroupId = portalGroup.PortalGroupId, }; callback(args); } public void UpdatePortalGroup(PortalGroupInfo portalGroup) { - //Argument Contract + // Argument Contract Requires.NotNull("portalGroup", portalGroup); Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); - _dataService.UpdatePortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); + this._dataService.UpdatePortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); ClearCache(); } public bool IsModuleShared(int moduleId, PortalInfo portal) { - if (portal == null) return false; - return GetSharedModulesWithPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted) || GetSharedModulesByPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted); - } - - #endregion + if (portal == null) + { + return false; + } + + return this.GetSharedModulesWithPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted) || this.GetSharedModulesByPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted); + } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs b/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs index 2b3eb36c7e9..bc3d2f292fd 100644 --- a/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs @@ -1,24 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel.DataAnnotations; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { + using System; + using System.ComponentModel.DataAnnotations; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + [Serializable] public class PortalGroupInfo : BaseEntityInfo, IHydratable { - public int PortalGroupId { get; set; } public string AuthenticationDomain { get; set; } @@ -29,50 +23,48 @@ public string MasterPortalName { get { - string portalName = String.Empty; - if (MasterPortalId > -1) + string portalName = string.Empty; + if (this.MasterPortalId > -1) { - var portal = PortalController.Instance.GetPortal(MasterPortalId); + var portal = PortalController.Instance.GetPortal(this.MasterPortalId); if (portal != null) { portalName = portal.PortalName; } } + return portalName; } } - [Required()] + [Required] public string PortalGroupDescription { get; set; } - [Required()] - public string PortalGroupName { get; set; } - - #region IHydratable Members - + [Required] + public string PortalGroupName { get; set; } + public int KeyID { get { - return PortalGroupId; + return this.PortalGroupId; } + set { - PortalGroupId = value; + this.PortalGroupId = value; } } public void Fill(IDataReader dr) { - FillInternal(dr); - - PortalGroupId = Null.SetNullInteger(dr["PortalGroupID"]); - PortalGroupName = Null.SetNullString(dr["PortalGroupName"]); - PortalGroupDescription = Null.SetNullString(dr["PortalGroupDescription"]); - MasterPortalId = Null.SetNullInteger(dr["MasterPortalID"]); - AuthenticationDomain = Null.SetNullString(dr["AuthenticationDomain"]); - } + this.FillInternal(dr); - #endregion + this.PortalGroupId = Null.SetNullInteger(dr["PortalGroupID"]); + this.PortalGroupName = Null.SetNullString(dr["PortalGroupName"]); + this.PortalGroupDescription = Null.SetNullString(dr["PortalGroupDescription"]); + this.MasterPortalId = Null.SetNullInteger(dr["MasterPortalID"]); + this.AuthenticationDomain = Null.SetNullString(dr["AuthenticationDomain"]); + } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalInfo.cs b/DNN Platform/Library/Entities/Portals/PortalInfo.cs index 76626a7f520..851f9d25fa1 100644 --- a/DNN Platform/Library/Entities/Portals/PortalInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalInfo.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Security.Cryptography; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { + using System; + using System.Data; + using System.Security.Cryptography; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + /// /// PortalInfo provides a base class for Portal information - /// This class inherites from the BaseEntityInfo and is Hydratable + /// This class inherites from the BaseEntityInfo and is Hydratable. /// /// /// This example shows how the PortalInfo class is used to get physical file names @@ -48,26 +43,23 @@ namespace DotNetNuke.Entities.Portals /// End If /// Return _PhysicalPath.Replace("/", "\") /// End Get - /// End Property + /// End Property /// /// /// [XmlRoot("settings", IsNullable = false)] [Serializable] public class PortalInfo : BaseEntityInfo, IHydratable - { - #region "Private Members" - + { private string _administratorRoleName; private int _pages = Null.NullInteger; - private string _registeredRoleName; - - #endregion + private string _registeredRoleName; - #region Constructors - - /// - /// Create new Portalinfo instance + private int _users; + + /// + /// Initializes a new instance of the class. + /// Create new Portalinfo instance. /// /// /// This example illustrates the creation of a new PortalInfo object @@ -81,18 +73,14 @@ public class PortalInfo : BaseEntityInfo, IHydratable /// public PortalInfo() { - Users = Null.NullInteger; - } - - #endregion - - #region Auto_Properties - + this.Users = Null.NullInteger; + } + /// - /// UserID of the user who is the admininistrator of the portal + /// Gets or sets userID of the user who is the admininistrator of the portal. /// - /// UserId of the user who is the portal admin - /// UserId of the user who is the portal admin + /// UserId of the user who is the portal admin. + /// UserId of the user who is the portal admin. /// This show the usage of the AdministratorId /// /// Dim Arr As ArrayList = objRoleController.GetUserRolesByRoleName(intPortalId, objPortal.AdministratorRoleName) @@ -104,15 +92,15 @@ public PortalInfo() /// If Not cboAdministratorId.Items.FindByValue(objPortal.AdministratorId.ToString) Is Nothing Then /// cboAdministratorId.Items.FindByValue(objPortal.AdministratorId.ToString).Selected = True /// End If - /// + /// [XmlElement("administratorid")] public int AdministratorId { get; set; } /// - /// The RoleId of the Security Role of the Administrators group of the portal + /// Gets or sets the RoleId of the Security Role of the Administrators group of the portal. /// - /// RoleId of de Administrators Security Role - /// RoleId of de Administrators Security Role + /// RoleId of de Administrators Security Role. + /// RoleId of de Administrators Security Role. /// This shows the usage of the AdministratoprRoleId /// /// Dim objPortal As PortalInfo = New PortalController().GetPortal(PortalID) @@ -130,34 +118,34 @@ public PortalInfo() public int AdministratorRoleId { get; set; } /// - /// TabId at which admin tasks start + /// Gets or sets tabId at which admin tasks start. /// - /// TabID of admin tasks - /// TabID of admin tasks + /// TabID of admin tasks. + /// TabID of admin tasks. /// [XmlElement("admintabid")] public int AdminTabId { get; set; } /// - /// Image (bitmap) file that is used as background for the portal + /// Gets or sets image (bitmap) file that is used as background for the portal. /// - /// Name of the file that is used as background - /// Name of the file that is used as background + /// Name of the file that is used as background. + /// Name of the file that is used as background. /// [XmlElement("backgroundfile")] public string BackgroundFile { get; set; } /// - /// Current host version + /// Gets or sets current host version. /// [XmlElement("crmversion")] public string CrmVersion { get; set; } /// - /// Setting for the type of banner advertising in the portal + /// Gets or sets setting for the type of banner advertising in the portal. /// - /// Type of banner advertising - /// Type of banner advertising + /// Type of banner advertising. + /// Type of banner advertising. /// This show the usage of BannerAdvertising setting /// /// optBanners.SelectedIndex = objPortal.BannerAdvertising @@ -169,10 +157,10 @@ public PortalInfo() public string CultureCode { get; set; } /// - /// Curreny format that is used in the portal + /// Gets or sets curreny format that is used in the portal. /// - /// Currency of the portal - /// Currency of the portal + /// Currency of the portal. + /// Currency of the portal. /// This exampels show the usage of the Currentcy property /// /// cboCurrency.DataSource = colList @@ -187,19 +175,19 @@ public PortalInfo() public string Currency { get; set; } /// - /// Default language for the portal + /// Gets or sets default language for the portal. /// - /// Default language of the portal - /// Default language of the portal + /// Default language of the portal. + /// Default language of the portal. /// [XmlElement("defaultlanguage")] public string DefaultLanguage { get; set; } /// - /// Description of the portal + /// Gets or sets description of the portal. /// - /// Description of the portal - /// Description of the portal + /// Description of the portal. + /// Description of the portal. /// This show the usage of the Description property /// /// Dim objPortalController As New PortalController @@ -212,19 +200,19 @@ public PortalInfo() public string Description { get; set; } /// - /// The default e-mail to be used in the porta; + /// Gets or sets the default e-mail to be used in the porta. /// - /// E-mail of the portal - /// E-mail of the portal + /// E-mail of the portal. + /// E-mail of the portal. /// [XmlElement("email")] public string Email { get; set; } /// - /// Date at which the portal expires + /// Gets or sets date at which the portal expires. /// - /// Date of expiration of the portal - /// Date of expiration of the portal + /// Date of expiration of the portal. + /// Date of expiration of the portal. /// This show the Portal expiration date usage /// /// If Not Null.IsNull(objPortal.ExpiryDate) Then @@ -239,10 +227,10 @@ public PortalInfo() public DateTime ExpiryDate { get; set; } /// - /// The footer text as specified in the Portal settings + /// Gets or sets the footer text as specified in the Portal settings. /// - /// Footer text of the portal - /// Returns the the footer text of the portal + /// Footer text of the portal. + /// Returns the the footer text of the portal. /// /// This show the usage of the FooterText property /// @@ -254,48 +242,49 @@ public PortalInfo() public string FooterText { get; set; } /// - /// GUID of the portal info object + /// Gets or sets gUID of the portal info object. /// - /// Portal info Object GUID - /// GUD of the portal info object + /// Portal info Object GUID. + /// GUD of the portal info object. /// [XmlIgnore] public Guid GUID { get; set; } /// - /// Home directory of the portal (logical path) + /// Gets or sets home directory of the portal (logical path). /// - /// Portal home directory - /// Portal home directory + /// Portal home directory. + /// Portal home directory. /// [XmlElement("homedirectory")] public string HomeDirectory { get; set; } /// - /// Home System (local) directory of the portal (logical path) + /// Gets home System (local) directory of the portal (logical path). /// - /// Portal home system directory - /// Portal home system directory in local filesystem + /// Portal home system directory. + /// Portal home system directory in local filesystem. /// [XmlElement("homesystemdirectory")] - public string HomeSystemDirectory { - get { return String.Format("{0}-System", HomeDirectory); } + public string HomeSystemDirectory + { + get { return string.Format("{0}-System", this.HomeDirectory); } } /// - /// TabdId of the Home page + /// Gets or sets tabdId of the Home page. /// - /// TabId of the Home page - /// TabId of the Home page + /// TabId of the Home page. + /// TabId of the Home page. /// [XmlElement("hometabid")] public int HomeTabId { get; set; } /// - /// Amount of currency that is used as a hosting fee of the portal + /// Gets or sets amount of currency that is used as a hosting fee of the portal. /// - /// Currency amount hosting fee - /// Currency amount hosting fee + /// Currency amount hosting fee. + /// Currency amount hosting fee. /// This show the Portal HostFeeusage /// /// If Not Null.IsNull(objPortal.ExpiryDate) Then @@ -310,10 +299,10 @@ public string HomeSystemDirectory { public float HostFee { get; set; } /// - /// Total disk space allowed for the portal (Mb). 0 means not limited + /// Gets or sets total disk space allowed for the portal (Mb). 0 means not limited. /// - /// Diskspace allowed for the portal - /// Diskspace allowed for the portal + /// Diskspace allowed for the portal. + /// Diskspace allowed for the portal. /// This show the Portal HostSpaceusage /// /// If Not Null.IsNull(objPortal.ExpiryDate) Then @@ -325,13 +314,13 @@ public string HomeSystemDirectory { /// txtUserQuota.Text = objPortal.UserQuota.ToString /// [XmlElement("hostspace")] - public int HostSpace { get; set; } - - /// - /// Keywords (separated by ,) for this portal + public int HostSpace { get; set; } + + /// + /// Gets or sets keywords (separated by ,) for this portal. /// - /// Keywords seperated by , - /// Keywords for this portal + /// Keywords seperated by . + /// Keywords for this portal. /// This show the usage of the KeyWords property /// /// Dim objPortalController As New PortalController @@ -340,35 +329,35 @@ public string HomeSystemDirectory { /// txtDescription.Text = objPortal.Description /// txtKeyWords.Text = objPortal.KeyWords /// - [XmlElement("keywords")] + [XmlElement("keywords")] public string KeyWords { get; set; } /// - /// TabId with the login control, page to login + /// Gets or sets tabId with the login control, page to login. /// - /// TabId of the Login page - /// TabId of the Login page + /// TabId of the Login page. + /// TabId of the Login page. /// [XmlElement("logintabid")] public int LoginTabId { get; set; } /// - /// The portal has a logo (bitmap) associated with the portal. Teh admin can set the logo in the portal settings + /// Gets or sets the portal has a logo (bitmap) associated with the portal. Teh admin can set the logo in the portal settings. /// - /// URL of the logo - /// URL of the Portal logo + /// URL of the logo. + /// URL of the Portal logo. /// /// urlLogo.Url = objPortal.LogoFile /// urlLogo.FileFilter = glbImageFileTypes - /// + /// [XmlElement("logofile")] public string LogoFile { get; set; } /// - /// Number of portal pages allowed in the portal. 0 means not limited + /// Gets or sets number of portal pages allowed in the portal. 0 means not limited. /// - /// Number of portal pages allowed - /// Number of portal pages allowed + /// Number of portal pages allowed. + /// Number of portal pages allowed. /// This show the Portal PageQuotausage /// /// If Not Null.IsNull(objPortal.ExpiryDate) Then @@ -383,37 +372,37 @@ public string HomeSystemDirectory { public int PageQuota { get; set; } /// - /// Name of the Payment processor that is used for portal payments, e.g. PayPal + /// Gets or sets name of the Payment processor that is used for portal payments, e.g. PayPal. /// - /// Name of the portal payment processor - /// Name of the portal payment processor + /// Name of the portal payment processor. + /// Name of the portal payment processor. /// [XmlElement("paymentprocessor")] public string PaymentProcessor { get; set; } /// - /// Unique idenitifier of the Portal within the site + /// Gets or sets unique idenitifier of the Portal within the site. /// - /// Portal identifier - /// Portal Identifier + /// Portal identifier. + /// Portal Identifier. /// [XmlElement("portalid")] public int PortalID { get; set; } /// - /// Contains the id of the portal group that the portal belongs to - /// Will be null or -1 (null.nullinteger) if the portal does not belong to a portal group + /// Gets or sets contains the id of the portal group that the portal belongs to + /// Will be null or -1 (null.nullinteger) if the portal does not belong to a portal group. /// - /// Portal Group identifier - /// Portal Group Identifier + /// Portal Group identifier. + /// Portal Group Identifier. /// public int PortalGroupID { get; set; } /// - /// Name of the portal. Can be set at creation time, Admin can change the name in the portal settings + /// Gets or sets name of the portal. Can be set at creation time, Admin can change the name in the portal settings. /// - /// Name of the portal - /// Name of the portal + /// Name of the portal. + /// Name of the portal. /// This show the usage of the PortalName property /// /// Dim objPortalController As New PortalController @@ -426,9 +415,9 @@ public string HomeSystemDirectory { public string PortalName { get; set; } /// - /// Password to use in the payment processor + /// Gets or sets password to use in the payment processor. /// - /// Payment Processor password + /// Payment Processor password. /// /// This shows the usage of the payment processing /// @@ -450,9 +439,11 @@ public string HomeSystemDirectory { public string ProcessorPassword { get; set; } /// - /// Payment Processor userId + /// Gets or sets payment Processor userId. /// - /// + /// + /// Payment Processor userId + /// /// /// /// This shows the usage of the payment processing @@ -475,106 +466,106 @@ public string HomeSystemDirectory { public string ProcessorUserId { get; set; } /// - /// The RoleId of the Registered users group of the portal. + /// Gets or sets the RoleId of the Registered users group of the portal. /// - /// RoleId of the Registered users - /// RoleId of the Registered users + /// RoleId of the Registered users. + /// RoleId of the Registered users. /// [XmlElement("registeredroleid")] public int RegisteredRoleId { get; set; } /// - /// Tabid of the Registration page + /// Gets or sets tabid of the Registration page. /// - /// TabId of the Registration page - /// TabId of the Registration page + /// TabId of the Registration page. + /// TabId of the Registration page. /// /// [XmlElement("registertabid")] public int RegisterTabId { get; set; } /// - /// Tabid of the Search profile page + /// Gets or sets tabid of the Search profile page. /// - /// TabdId of the Search Results page - /// TabdId of the Search Results page + /// TabdId of the Search Results page. + /// TabdId of the Search Results page. /// /// [XmlElement("searchtabid")] public int SearchTabId { get; set; } /// - /// Tabid of the Custom 404 page + /// Gets or sets tabid of the Custom 404 page. /// - /// Tabid of the Custom 404 page - /// Tabid of the Custom 404 page + /// Tabid of the Custom 404 page. + /// Tabid of the Custom 404 page. /// /// [XmlElement("custom404tabid")] public int Custom404TabId { get; set; } /// - /// Tabid of the Custom 500 error page + /// Gets or sets tabid of the Custom 500 error page. /// - /// Tabid of the Custom 500 error page - /// Tabid of the Custom 500 error page + /// Tabid of the Custom 500 error page. + /// Tabid of the Custom 500 error page. /// /// [XmlElement("custom500tabid")] public int Custom500TabId { get; set; } /// - /// Tabid of the Terms of Use page + /// Gets or sets tabid of the Terms of Use page. /// - /// Tabid of the Terms of Use page - /// Tabid of the Terms of Use page + /// Tabid of the Terms of Use page. + /// Tabid of the Terms of Use page. /// /// [XmlElement("termstabid")] public int TermsTabId { get; set; } /// - /// Tabid of the Privacy Statement page + /// Gets or sets tabid of the Privacy Statement page. /// - /// Tabid of the Privacy Statement page - /// Tabid of the Privacy Statement page + /// Tabid of the Privacy Statement page. + /// Tabid of the Privacy Statement page. /// /// [XmlElement("privacytabid")] public int PrivacyTabId { get; set; } /// - /// # of days that Site log history should be kept. 0 means unlimited + /// Gets or sets # of days that Site log history should be kept. 0 means unlimited. /// - /// # of days sitelog history - /// # of days sitelog history + /// # of days sitelog history. + /// # of days sitelog history. [XmlElement("siteloghistory")] [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] public int SiteLogHistory { get; set; } /// - /// TabdId of the splash page. If 0, there is no splash page + /// Gets or sets tabdId of the splash page. If 0, there is no splash page. /// - /// TabdId of the Splash page - /// TabdId of the Splash page + /// TabdId of the Splash page. + /// TabdId of the Splash page. /// [XmlElement("splashtabid")] public int SplashTabId { get; set; } /// - /// TabId at which Host tasks start + /// Gets or sets tabId at which Host tasks start. /// - /// TabId of Host tasks - /// TabId of Host tasks + /// TabId of Host tasks. + /// TabId of Host tasks. /// [XmlElement("supertabid")] public int SuperTabId { get; set; } /// - /// Number of registered users allowed in the portal. 0 means not limited + /// Gets or sets number of registered users allowed in the portal. 0 means not limited. /// - /// Number of registered users allowed - /// Number of registered users allowed + /// Number of registered users allowed. + /// Number of registered users allowed. /// This show the Portal userQuota usage /// /// If Not Null.IsNull(objPortal.ExpiryDate) Then @@ -589,10 +580,10 @@ public string HomeSystemDirectory { public int UserQuota { get; set; } /// - /// Type of registration that the portal supports + /// Gets or sets type of registration that the portal supports. /// - /// Type of registration - /// Type of registration + /// Type of registration. + /// Type of registration. /// Registration type /// /// optUserRegistration.SelectedIndex = objPortal.UserRegistration @@ -601,283 +592,287 @@ public string HomeSystemDirectory { public int UserRegistration { get; set; } /// - /// Tabid of the User profile page + /// Gets or sets tabid of the User profile page. /// - /// TabdId of the User profile page - /// TabdId of the User profile page + /// TabdId of the User profile page. + /// TabdId of the User profile page. /// [XmlElement("usertabid")] public int UserTabId { get; set; } - private int _users; - /// - /// Actual number of actual users for this portal + /// Gets or sets actual number of actual users for this portal. /// - /// Number of users for the portal - /// Number of users for the portal + /// Number of users for the portal. + /// Number of users for the portal. /// [XmlElement("users")] public int Users { get { - if (_users < 0) + if (this._users < 0) { - _users = UserController.GetUserCountByPortal(PortalID); + this._users = UserController.GetUserCountByPortal(this.PortalID); } - return _users; + + return this._users; } - set { _users = value; } + + set { this._users = value; } } /// - /// DNN Version # of the portal installation + /// Gets or sets dNN Version # of the portal installation. /// - /// Version # of the portal installation - /// Version # of the portal installation + /// Version # of the portal installation. + /// Version # of the portal installation. /// [XmlElement("version")] - public string Version { get; set; } - - #endregion - - #region Properties - + public string Version { get; set; } + /// - /// The actual name of the Administrators group of the portal. - /// This name is retrieved from the RoleController object + /// Gets or sets the actual name of the Administrators group of the portal. + /// This name is retrieved from the RoleController object. /// - /// The name of the Administrators group - /// The name of the Administrators group + /// The name of the Administrators group. + /// The name of the Administrators group. /// [XmlElement("administratorrolename")] public string AdministratorRoleName { get { - if (_administratorRoleName == Null.NullString && AdministratorRoleId > Null.NullInteger) + if (this._administratorRoleName == Null.NullString && this.AdministratorRoleId > Null.NullInteger) { - //Get Role Name - RoleInfo adminRole = RoleController.Instance.GetRole(PortalID, r => r.RoleID == AdministratorRoleId); + // Get Role Name + RoleInfo adminRole = RoleController.Instance.GetRole(this.PortalID, r => r.RoleID == this.AdministratorRoleId); if (adminRole != null) { - _administratorRoleName = adminRole.RoleName; + this._administratorRoleName = adminRole.RoleName; } } - return _administratorRoleName; + + return this._administratorRoleName; } + set { - _administratorRoleName = value; + this._administratorRoleName = value; } } /// - /// Fysical path on disk of the home directory of the portal + /// Gets fysical path on disk of the home directory of the portal. /// - /// - /// Fully qualified path of the home directory + /// + /// Fysical path on disk of the home directory of the portal + /// + /// Fully qualified path of the home directory. /// [XmlIgnore] public string HomeDirectoryMapPath { get { - return String.Format("{0}\\{1}\\", Globals.ApplicationMapPath, HomeDirectory.Replace("/", "\\")); + return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeDirectory.Replace("/", "\\")); } } /// - /// Fysical path on disk of the home directory of the portal + /// Gets fysical path on disk of the home directory of the portal. /// - /// - /// Fully qualified path of the home system (local) directory + /// + /// Fysical path on disk of the home directory of the portal + /// + /// Fully qualified path of the home system (local) directory. /// [XmlIgnore] public string HomeSystemDirectoryMapPath { get { - return String.Format("{0}\\{1}\\", Globals.ApplicationMapPath, HomeSystemDirectory.Replace("/", "\\")); + return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeSystemDirectory.Replace("/", "\\")); } } /// - /// Actual number of pages of the portal + /// Gets or sets actual number of pages of the portal. /// - /// Number of pages of the portal - /// Number of pages of the portal + /// Number of pages of the portal. + /// Number of pages of the portal. /// [XmlElement("pages")] public int Pages { get { - if (_pages < 0) + if (this._pages < 0) { - _pages = TabController.Instance.GetUserTabsByPortal(PortalID).Count; + this._pages = TabController.Instance.GetUserTabsByPortal(this.PortalID).Count; } - return _pages; + + return this._pages; } + set { - _pages = value; + this._pages = value; } } /// - /// The actual name of the Registerd Users group of the portal. - /// This name is retrieved from the RoleController object + /// Gets or sets the actual name of the Registerd Users group of the portal. + /// This name is retrieved from the RoleController object. /// - /// The name of the Registerd Users group - /// The name of the Registerd Users group + /// The name of the Registerd Users group. + /// The name of the Registerd Users group. /// [XmlElement("registeredrolename")] public string RegisteredRoleName { get { - if (_registeredRoleName == Null.NullString && RegisteredRoleId > Null.NullInteger) + if (this._registeredRoleName == Null.NullString && this.RegisteredRoleId > Null.NullInteger) { - //Get Role Name - RoleInfo regUsersRole = RoleController.Instance.GetRole(PortalID, r => r.RoleID == RegisteredRoleId); + // Get Role Name + RoleInfo regUsersRole = RoleController.Instance.GetRole(this.PortalID, r => r.RoleID == this.RegisteredRoleId); if (regUsersRole != null) { - _registeredRoleName = regUsersRole.RoleName; + this._registeredRoleName = regUsersRole.RoleName; } } - return _registeredRoleName; + + return this._registeredRoleName; } + set { - _registeredRoleName = value; + this._registeredRoleName = value; } - } - - #endregion - + } + [XmlIgnore] [Obsolete("Deprecated in DNN 6.0. Scheduled removal in v10.0.0.")] - public int TimeZoneOffset { get; set; } - - #region IHydratable Members + public int TimeZoneOffset { get; set; } /// - /// Fills a PortalInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// Standard IHydratable.Fill implementation + /// KeyId of the IHydratable.Key. + /// + public int KeyID + { + get + { + return this.PortalID; + } + + set + { + this.PortalID = value; + } + } + + /// + /// Fills a PortalInfo from a Data Reader. + /// + /// The Data Reader to use. + /// Standard IHydratable.Fill implementation. /// public void Fill(IDataReader dr) { - PortalID = Null.SetNullInteger(dr["PortalID"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); try { - PortalGroupID = Null.SetNullInteger(dr["PortalGroupID"]); + this.PortalGroupID = Null.SetNullInteger(dr["PortalGroupID"]); } catch (IndexOutOfRangeException) { - if(Globals.Status == Globals.UpgradeStatus.None) + if (Globals.Status == Globals.UpgradeStatus.None) { - //this should not happen outside of an upgrade situation + // this should not happen outside of an upgrade situation throw; } - //else swallow the error + // else swallow the error } - - PortalName = Null.SetNullString(dr["PortalName"]); - LogoFile = Null.SetNullString(dr["LogoFile"]); - FooterText = Null.SetNullString(dr["FooterText"]); - ExpiryDate = Null.SetNullDateTime(dr["ExpiryDate"]); - UserRegistration = Null.SetNullInteger(dr["UserRegistration"]); - BannerAdvertising = Null.SetNullInteger(dr["BannerAdvertising"]); - AdministratorId = Null.SetNullInteger(dr["AdministratorID"]); - Email = Null.SetNullString(dr["Email"]); - Currency = Null.SetNullString(dr["Currency"]); - HostFee = Null.SetNullInteger(dr["HostFee"]); - HostSpace = Null.SetNullInteger(dr["HostSpace"]); - PageQuota = Null.SetNullInteger(dr["PageQuota"]); - UserQuota = Null.SetNullInteger(dr["UserQuota"]); - AdministratorRoleId = Null.SetNullInteger(dr["AdministratorRoleID"]); - RegisteredRoleId = Null.SetNullInteger(dr["RegisteredRoleID"]); - Description = Null.SetNullString(dr["Description"]); - KeyWords = Null.SetNullString(dr["KeyWords"]); - BackgroundFile = Null.SetNullString(dr["BackGroundFile"]); - GUID = new Guid(Null.SetNullString(dr["GUID"])); - PaymentProcessor = Null.SetNullString(dr["PaymentProcessor"]); - ProcessorUserId = Null.SetNullString(dr["ProcessorUserId"]); + + this.PortalName = Null.SetNullString(dr["PortalName"]); + this.LogoFile = Null.SetNullString(dr["LogoFile"]); + this.FooterText = Null.SetNullString(dr["FooterText"]); + this.ExpiryDate = Null.SetNullDateTime(dr["ExpiryDate"]); + this.UserRegistration = Null.SetNullInteger(dr["UserRegistration"]); + this.BannerAdvertising = Null.SetNullInteger(dr["BannerAdvertising"]); + this.AdministratorId = Null.SetNullInteger(dr["AdministratorID"]); + this.Email = Null.SetNullString(dr["Email"]); + this.Currency = Null.SetNullString(dr["Currency"]); + this.HostFee = Null.SetNullInteger(dr["HostFee"]); + this.HostSpace = Null.SetNullInteger(dr["HostSpace"]); + this.PageQuota = Null.SetNullInteger(dr["PageQuota"]); + this.UserQuota = Null.SetNullInteger(dr["UserQuota"]); + this.AdministratorRoleId = Null.SetNullInteger(dr["AdministratorRoleID"]); + this.RegisteredRoleId = Null.SetNullInteger(dr["RegisteredRoleID"]); + this.Description = Null.SetNullString(dr["Description"]); + this.KeyWords = Null.SetNullString(dr["KeyWords"]); + this.BackgroundFile = Null.SetNullString(dr["BackGroundFile"]); + this.GUID = new Guid(Null.SetNullString(dr["GUID"])); + this.PaymentProcessor = Null.SetNullString(dr["PaymentProcessor"]); + this.ProcessorUserId = Null.SetNullString(dr["ProcessorUserId"]); var p = Null.SetNullString(dr["ProcessorPassword"]); try { - ProcessorPassword = string.IsNullOrEmpty(p) + this.ProcessorPassword = string.IsNullOrEmpty(p) ? p : Security.FIPSCompliant.DecryptAES(p, Config.GetDecryptionkey(), Host.Host.GUID); } catch (Exception ex) when (ex is FormatException || ex is CryptographicException) { // for backward compatibility - ProcessorPassword = p; + this.ProcessorPassword = p; } - SplashTabId = Null.SetNullInteger(dr["SplashTabID"]); - HomeTabId = Null.SetNullInteger(dr["HomeTabID"]); - LoginTabId = Null.SetNullInteger(dr["LoginTabID"]); - RegisterTabId = Null.SetNullInteger(dr["RegisterTabID"]); - UserTabId = Null.SetNullInteger(dr["UserTabID"]); - SearchTabId = Null.SetNullInteger(dr["SearchTabID"]); - - Custom404TabId = Custom500TabId = Null.NullInteger; + + this.SplashTabId = Null.SetNullInteger(dr["SplashTabID"]); + this.HomeTabId = Null.SetNullInteger(dr["HomeTabID"]); + this.LoginTabId = Null.SetNullInteger(dr["LoginTabID"]); + this.RegisterTabId = Null.SetNullInteger(dr["RegisterTabID"]); + this.UserTabId = Null.SetNullInteger(dr["UserTabID"]); + this.SearchTabId = Null.SetNullInteger(dr["SearchTabID"]); + + this.Custom404TabId = this.Custom500TabId = Null.NullInteger; var schema = dr.GetSchemaTable(); if (schema != null) { if (schema.Select("ColumnName = 'Custom404TabId'").Length > 0) { - Custom404TabId = Null.SetNullInteger(dr["Custom404TabId"]); + this.Custom404TabId = Null.SetNullInteger(dr["Custom404TabId"]); } + if (schema.Select("ColumnName = 'Custom500TabId'").Length > 0) { - Custom500TabId = Null.SetNullInteger(dr["Custom500TabId"]); + this.Custom500TabId = Null.SetNullInteger(dr["Custom500TabId"]); } } - TermsTabId = Null.SetNullInteger(dr["TermsTabId"]); - PrivacyTabId = Null.SetNullInteger(dr["PrivacyTabId"]); + + this.TermsTabId = Null.SetNullInteger(dr["TermsTabId"]); + this.PrivacyTabId = Null.SetNullInteger(dr["PrivacyTabId"]); - DefaultLanguage = Null.SetNullString(dr["DefaultLanguage"]); + this.DefaultLanguage = Null.SetNullString(dr["DefaultLanguage"]); #pragma warning disable 612,618 //needed for upgrades and backwards compatibility - TimeZoneOffset = Null.SetNullInteger(dr["TimeZoneOffset"]); + this.TimeZoneOffset = Null.SetNullInteger(dr["TimeZoneOffset"]); #pragma warning restore 612,618 - AdminTabId = Null.SetNullInteger(dr["AdminTabID"]); - HomeDirectory = Null.SetNullString(dr["HomeDirectory"]); - SuperTabId = Null.SetNullInteger(dr["SuperTabId"]); - CultureCode = Null.SetNullString(dr["CultureCode"]); - - FillInternal(dr); - AdministratorRoleName = Null.NullString; - RegisteredRoleName = Null.NullString; + this.AdminTabId = Null.SetNullInteger(dr["AdminTabID"]); + this.HomeDirectory = Null.SetNullString(dr["HomeDirectory"]); + this.SuperTabId = Null.SetNullInteger(dr["SuperTabId"]); + this.CultureCode = Null.SetNullString(dr["CultureCode"]); - Users = Null.NullInteger; - Pages = Null.NullInteger; - } + this.FillInternal(dr); + this.AdministratorRoleName = Null.NullString; + this.RegisteredRoleName = Null.NullString; - /// - /// Gets and sets the Key ID - /// - /// KeyId of the IHydratable.Key - /// - public int KeyID - { - get - { - return PortalID; - } - set - { - PortalID = value; - } + this.Users = Null.NullInteger; + this.Pages = Null.NullInteger; } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Portals/PortalSettingUpdatedEventArgs.cs b/DNN Platform/Library/Entities/Portals/PortalSettingUpdatedEventArgs.cs index f7b575375e4..0d85cab5d5a 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettingUpdatedEventArgs.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettingUpdatedEventArgs.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System; + public class PortalSettingUpdatedEventArgs : EventArgs { public int PortalId { get; set; } @@ -13,6 +13,5 @@ public class PortalSettingUpdatedEventArgs : EventArgs public string SettingName { get; set; } public string SettingValue { get; set; } - } } diff --git a/DNN Platform/Library/Entities/Portals/PortalSettings.cs b/DNN Platform/Library/Entities/Portals/PortalSettings.cs index 397021a9d2a..8203daa6e72 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettings.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettings.cs @@ -1,29 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; -using System.Linq; -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Services.Personalization; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Common; -using DotNetNuke.Abstractions.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { + using System; + using System.Globalization; + using System.Linq; + using System.Web; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Services.Personalization; + using DotNetNuke.Services.Tokens; + /// ----------------------------------------------------------------------------- /// - /// The PortalSettings class encapsulates all of the settings for the Portal, + /// The PortalSettings class encapsulates all of the settings for the Portal, /// as well as the configuration settings required to execute the current tab /// view within the portal. /// @@ -31,87 +27,72 @@ namespace DotNetNuke.Entities.Portals [Serializable] public partial class PortalSettings : BaseEntityInfo, IPropertyAccess, IPortalSettings { - #region ControlPanelPermission enum + public PortalSettings() + { + this.Registration = new RegistrationSettings(); + } - public enum ControlPanelPermission + public PortalSettings(int portalId) + : this(Null.NullInteger, portalId) { - TabEditor, - ModuleEditor } - #endregion + public PortalSettings(int tabId, int portalId) + { + this.PortalId = portalId; + var portal = PortalController.Instance.GetPortal(portalId); + this.BuildPortalSettings(tabId, portal); + } - #region Mode enum + public enum ControlPanelPermission + { + TabEditor, + ModuleEditor, + } public enum Mode { View, Edit, - Layout + Layout, } - #endregion - - #region PortalAliasMapping enum - public enum PortalAliasMapping { None, CanonicalUrl, - Redirect + Redirect, } - #endregion - - #region Data Consent UserDeleteAction enum public enum UserDeleteAction { Off = 0, Manual = 1, DelayedHardDelete = 2, - HardDelete = 3 - } - #endregion - - #region Constructors - - public PortalSettings() - { - Registration = new RegistrationSettings(); - } - - public PortalSettings(int portalId) - : this(Null.NullInteger, portalId) - { - } - - public PortalSettings(int tabId, int portalId) - { - PortalId = portalId; - var portal = PortalController.Instance.GetPortal(portalId); - BuildPortalSettings(tabId, portal); + HardDelete = 3, } /// ----------------------------------------------------------------------------- /// + /// Initializes a new instance of the class. /// The PortalSettings Constructor encapsulates all of the logic /// necessary to obtain configuration settings necessary to render /// a Portal Tab view for a given request. /// /// /// - /// The current tab - /// The current portal + /// The current tab. + /// The current portal. /// ----------------------------------------------------------------------------- public PortalSettings(int tabId, PortalAliasInfo portalAliasInfo) { - PortalId = portalAliasInfo.PortalID; - PortalAlias = portalAliasInfo; + this.PortalId = portalAliasInfo.PortalID; + this.PortalAlias = portalAliasInfo; var portal = string.IsNullOrEmpty(portalAliasInfo.CultureCode) ? PortalController.Instance.GetPortal(portalAliasInfo.PortalID) : PortalController.Instance.GetPortal(portalAliasInfo.PortalID, portalAliasInfo.CultureCode); - BuildPortalSettings(tabId, portal); + this.BuildPortalSettings(tabId, portal); } public PortalSettings(PortalInfo portal) @@ -121,15 +102,32 @@ public PortalSettings(PortalInfo portal) public PortalSettings(int tabId, PortalInfo portal) { - PortalId = portal != null ? portal.PortalID : Null.NullInteger; - BuildPortalSettings(tabId, portal); + this.PortalId = portal != null ? portal.PortalID : Null.NullInteger; + this.BuildPortalSettings(tabId, portal); + } + + public static PortalSettings Current + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } } + public TabInfo ActiveTab { get; set; } + + public int AdministratorId { get; set; } + + public int AdministratorRoleId { get; set; } + private void BuildPortalSettings(int tabId, PortalInfo portal) { PortalSettingsController.Instance().LoadPortalSettings(this); - if (portal == null) return; + if (portal == null) + { + return; + } PortalSettingsController.Instance().LoadPortal(portal, this); @@ -137,85 +135,75 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) var items = HttpContext.Current != null ? HttpContext.Current.Items : null; if (items != null && items.Contains(key)) { - ActiveTab = items[key] as TabInfo; + this.ActiveTab = items[key] as TabInfo; } else { - ActiveTab = PortalSettingsController.Instance().GetActiveTab(tabId, this); - if (items != null && ActiveTab != null) + this.ActiveTab = PortalSettingsController.Instance().GetActiveTab(tabId, this); + if (items != null && this.ActiveTab != null) { - items[key] = ActiveTab; + items[key] = this.ActiveTab; } } } - #endregion - - #region Auto-Properties - - public TabInfo ActiveTab { get; set; } - - public int AdministratorId { get; set; } - - public int AdministratorRoleId { get; set; } + public string AdministratorRoleName { get; set; } - public string AdministratorRoleName { get; set; } + public int AdminTabId { get; set; } - public int AdminTabId { get; set; } + public string BackgroundFile { get; set; } - public string BackgroundFile { get; set; } + public int BannerAdvertising { get; set; } - public int BannerAdvertising { get; set; } + public string CultureCode { get; set; } - public string CultureCode { get; set; } + public string Currency { get; set; } - public string Currency { get; set; } + public string DefaultLanguage { get; set; } - public string DefaultLanguage { get; set; } + public string Description { get; set; } - public string Description { get; set; } - - public string Email { get; set; } + public string Email { get; set; } public DateTime ExpiryDate { get; set; } - public string FooterText { get; set; } + public string FooterText { get; set; } - public Guid GUID { get; set; } + public Guid GUID { get; set; } - public string HomeDirectory { get; set; } + public string HomeDirectory { get; set; } - public string HomeSystemDirectory { get; set; } + public string HomeSystemDirectory { get; set; } - public int HomeTabId { get; set; } + public int HomeTabId { get; set; } - public float HostFee { get; set; } + public float HostFee { get; set; } - public int HostSpace { get; set; } + public int HostSpace { get; set; } - public string KeyWords { get; set; } + public string KeyWords { get; set; } - public int LoginTabId { get; set; } + public int LoginTabId { get; set; } - public string LogoFile { get; set; } + public string LogoFile { get; set; } - public int PageQuota { get; set; } + public int PageQuota { get; set; } - public int Pages { get; set; } + public int Pages { get; set; } - public int PortalId { get; set; } + public int PortalId { get; set; } - public PortalAliasInfo PortalAlias { get; set; } + public PortalAliasInfo PortalAlias { get; set; } - public PortalAliasInfo PrimaryAlias { get; set; } + public PortalAliasInfo PrimaryAlias { get; set; } - public string PortalName { get; set; } + public string PortalName { get; set; } - public int RegisteredRoleId { get; set; } + public int RegisteredRoleId { get; set; } - public string RegisteredRoleName { get; set; } + public string RegisteredRoleName { get; set; } - public int RegisterTabId { get; set; } + public int RegisterTabId { get; set; } public RegistrationSettings Registration { get; set; } @@ -224,33 +212,29 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) [Obsolete("Deprecated in 8.0.0. Scheduled removal in v10.0.0.")] public int SiteLogHistory { get; set; } - public int SplashTabId { get; set; } + public int SplashTabId { get; set; } - public int SuperTabId { get; set; } + public int SuperTabId { get; set; } - public int UserQuota { get; set; } + public int UserQuota { get; set; } - public int UserRegistration { get; set; } + public int UserRegistration { get; set; } - public int Users { get; set; } + public int Users { get; set; } - public int UserTabId { get; set; } + public int UserTabId { get; set; } public int TermsTabId { get; set; } - public int PrivacyTabId { get; set; } - - #endregion - - #region Read-Only Properties + public int PrivacyTabId { get; set; } /// ----------------------------------------------------------------------------- /// - /// Allows users to select their own UI culture. + /// Gets a value indicating whether allows users to select their own UI culture. /// When set to false (default) framework will allways same culture for both - /// CurrentCulture (content) and CurrentUICulture (interface) + /// CurrentCulture (content) and CurrentUICulture (interface). /// - /// Defaults to False + /// Defaults to False. /// ----------------------------------------------------------------------------- public bool AllowUserUICulture { get; internal set; } @@ -274,9 +258,9 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) /// ----------------------------------------------------------------------------- /// - /// Gets the Default Module Id + /// Gets the Default Module Id. /// - /// Defaults to Null.NullInteger + /// Defaults to Null.NullInteger. /// ----------------------------------------------------------------------------- public int DefaultModuleId { get; internal set; } @@ -288,17 +272,17 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) /// ----------------------------------------------------------------------------- /// - /// Gets the Default Tab Id + /// Gets the Default Tab Id. /// - /// Defaults to Null.NullInteger + /// Defaults to Null.NullInteger. /// ----------------------------------------------------------------------------- public int DefaultTabId { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether Browser Language Detection is Enabled + /// Gets a value indicating whether gets whether Browser Language Detection is Enabled. /// - /// Defaults to True + /// Defaults to True. /// ----------------------------------------------------------------------------- public bool EnableBrowserLanguage { get; internal set; } @@ -306,53 +290,53 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) /// ----------------------------------------------------------------------------- /// - /// Gets whether to use the module effect in edit mode. + /// Gets a value indicating whether gets whether to use the module effect in edit mode. /// - /// Defaults to True + /// Defaults to True. /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public bool EnableModuleEffect { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether to use the popup. + /// Gets a value indicating whether gets whether to use the popup. /// - /// Defaults to True + /// Defaults to True. /// ----------------------------------------------------------------------------- public bool EnablePopUps { get; internal set; } /// - /// Website Administrator whether receive the notification email when new user register. + /// Gets a value indicating whether website Administrator whether receive the notification email when new user register. /// public bool EnableRegisterNotification { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the Skin Widgets are enabled/supported + /// Gets a value indicating whether gets whether the Skin Widgets are enabled/supported. /// - /// Defaults to True + /// Defaults to True. /// ----------------------------------------------------------------------------- public bool EnableSkinWidgets { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether a cookie consent popup should be shown + /// Gets a value indicating whether gets whether a cookie consent popup should be shown. /// - /// Defaults to False + /// Defaults to False. /// ----------------------------------------------------------------------------- public bool ShowCookieConsent { get; internal set; } /// - /// Link for the user to find out more about cookies. If not specified the link - /// shown will point to cookiesandyou.com + /// Gets link for the user to find out more about cookies. If not specified the link + /// shown will point to cookiesandyou.com. /// public string CookieMoreLink { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether enable url language. + /// Gets a value indicating whether gets whether enable url language. /// - /// Defaults to True + /// Defaults to True. /// ----------------------------------------------------------------------------- public bool EnableUrlLanguage { get; internal set; } @@ -361,19 +345,19 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) public int ErrorPage500 { get; internal set; } /// ----------------------------------------------------------------------------- - /// - /// Gets whether folders which are hidden or whose name begins with underscore - /// are included in folder synchronization. - /// - /// - /// Defaults to True - /// - /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether folders which are hidden or whose name begins with underscore + /// are included in folder synchronization. + /// + /// + /// Defaults to True. + /// + /// ----------------------------------------------------------------------------- public bool HideFoldersEnabled { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether hide the login link. + /// Gets a value indicating whether gets whether hide the login link. /// /// Defaults to False. /// ----------------------------------------------------------------------------- @@ -384,52 +368,52 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) public string HomeSystemDirectoryMapPath { get; internal set; } /// ----------------------------------------------------------------------------- - /// - /// Gets whether the Inline Editor is enabled - /// - /// Defaults to True - /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether the Inline Editor is enabled. + /// + /// Defaults to True. + /// ----------------------------------------------------------------------------- public bool InlineEditorEnabled { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether to inlcude Common Words in the Search Index + /// Gets a value indicating whether gets whether to inlcude Common Words in the Search Index. /// - /// Defaults to False + /// Defaults to False. /// ----------------------------------------------------------------------------- public bool SearchIncludeCommon { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether to inlcude Numbers in the Search Index + /// Gets a value indicating whether gets whether to inlcude Numbers in the Search Index. /// - /// Defaults to False + /// Defaults to False. /// ----------------------------------------------------------------------------- public bool SearchIncludeNumeric { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets the filter used for inclusion of tag info + /// Gets the filter used for inclusion of tag info. /// /// - /// Defaults to "" + /// Defaults to "". /// /// ----------------------------------------------------------------------------- public string SearchIncludedTagInfoFilter { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets the maximum Search Word length to index + /// Gets the maximum Search Word length to index. /// - /// Defaults to 3 + /// Defaults to 3. /// ----------------------------------------------------------------------------- public int SearchMaxWordlLength { get; internal set; } /// ----------------------------------------------------------------------------- /// - /// Gets the minum Search Word length to index + /// Gets the minum Search Word length to index. /// - /// Defaults to 3 + /// Defaults to 3. /// ----------------------------------------------------------------------------- public int SearchMinWordlLength { get; internal set; } @@ -445,10 +429,6 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) public int SMTPMaxIdleTime { get; internal set; } - #endregion - - #region Public Properties - public CacheLevel Cacheability { get @@ -461,16 +441,8 @@ public bool ControlPanelVisible { get { - var setting = Convert.ToString(Personalization.GetProfile("Usability", "ControlPanelVisible" + PortalId)); - return String.IsNullOrEmpty(setting) ? DefaultControlPanelVisibility : Convert.ToBoolean(setting); - } - } - - public static PortalSettings Current - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); + var setting = Convert.ToString(Personalization.GetProfile("Usability", "ControlPanelVisible" + this.PortalId)); + return string.IsNullOrEmpty(setting) ? this.DefaultControlPanelVisibility : Convert.ToBoolean(setting); } } @@ -478,11 +450,12 @@ public string DefaultPortalAlias { get { - foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(PortalId).Where(alias => alias.IsPrimary)) + foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId).Where(alias => alias.IsPrimary)) { return alias.HTTPAlias; } - return String.Empty; + + return string.Empty; } } @@ -490,27 +463,28 @@ public PortalAliasMapping PortalAliasMappingMode { get { - return PortalSettingsController.Instance().GetPortalAliasMappingMode(PortalId); + return PortalSettingsController.Instance().GetPortalAliasMappingMode(this.PortalId); } } /// Gets the currently logged in user identifier. /// The user identifier. - public int UserId + public int UserId { get { if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) { - return UserInfo.UserID; + return this.UserInfo.UserID; } + return Null.NullInteger; } } /// Gets the currently logged in user. /// The current user information. - public UserInfo UserInfo + public UserInfo UserInfo { get { @@ -525,8 +499,8 @@ public Mode UserMode Mode mode; if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) { - mode = DefaultControlPanelMode; - string setting = Convert.ToString(Personalization.GetProfile("Usability", "UserMode" + PortalId)); + mode = this.DefaultControlPanelMode; + string setting = Convert.ToString(Personalization.GetProfile("Usability", "UserMode" + this.PortalId)); switch (setting.ToUpper()) { case "VIEW": @@ -544,24 +518,25 @@ public Mode UserMode { mode = Mode.View; } + return mode; } } /// - /// Get a value indicating whether the current portal is in maintenance mode (if either this specific portal or the entire instance is locked). If locked, any actions which update the database should be disabled. + /// Gets a value indicating whether get a value indicating whether the current portal is in maintenance mode (if either this specific portal or the entire instance is locked). If locked, any actions which update the database should be disabled. /// public bool IsLocked { - get { return IsThisPortalLocked || Host.Host.IsLocked; } + get { return this.IsThisPortalLocked || Host.Host.IsLocked; } } /// - /// Get a value indicating whether the current portal is in maintenance mode (note, the entire instance may still be locked, this only indicates whether this portal is specifically locked). If locked, any actions which update the database should be disabled. + /// Gets a value indicating whether get a value indicating whether the current portal is in maintenance mode (note, the entire instance may still be locked, this only indicates whether this portal is specifically locked). If locked, any actions which update the database should be disabled. /// public bool IsThisPortalLocked { - get { return PortalController.GetPortalSettingAsBoolean("IsLocked", PortalId, false); } + get { return PortalController.GetPortalSettingAsBoolean("IsLocked", this.PortalId, false); } } public TimeZoneInfo TimeZone { get; set; } = TimeZoneInfo.Local; @@ -573,33 +548,35 @@ public string PageHeadText // For New Install string pageHead = ""; string setting; - if (PortalController.Instance.GetPortalSettings(PortalId).TryGetValue("PageHeadText", out setting)) + if (PortalController.Instance.GetPortalSettings(this.PortalId).TryGetValue("PageHeadText", out setting)) { // Hack to store empty string portalsetting with non empty default value - pageHead = (setting == "false") ? "" : setting; + pageHead = (setting == "false") ? string.Empty : setting; } + return pageHead; } } /* * add on the top of the module - * + * * Desactivate this remove the html5 compatibility warnings * (and make the output smaller) - * + * */ public bool InjectModuleHyperLink { get { - return PortalController.GetPortalSettingAsBoolean("InjectModuleHyperLink", PortalId, true); + return PortalController.GetPortalSettingAsBoolean("InjectModuleHyperLink", this.PortalId, true); } } + /* * generates a : Page.Response.AddHeader("X-UA-Compatible", ""); - * - + * + */ public string AddCompatibleHttpHeader { @@ -607,79 +584,77 @@ public string AddCompatibleHttpHeader { string CompatibleHttpHeader = "IE=edge"; string setting; - if (PortalController.Instance.GetPortalSettings(PortalId).TryGetValue("AddCompatibleHttpHeader", out setting)) + if (PortalController.Instance.GetPortalSettings(this.PortalId).TryGetValue("AddCompatibleHttpHeader", out setting)) { // Hack to store empty string portalsetting with non empty default value - CompatibleHttpHeader = (setting == "false") ? "" : setting; + CompatibleHttpHeader = (setting == "false") ? string.Empty : setting; } + return CompatibleHttpHeader; } } /// - /// If true then add a cachebuster parameter to generated file URI's. + /// Gets a value indicating whether if true then add a cachebuster parameter to generated file URI's. /// public bool AddCachebusterToResourceUris { get { - return PortalController.GetPortalSettingAsBoolean("AddCachebusterToResourceUris", PortalId, true); + return PortalController.GetPortalSettingAsBoolean("AddCachebusterToResourceUris", this.PortalId, true); } } /// - /// If this is true, then regular users can't send message to specific user/group. + /// Gets a value indicating whether if this is true, then regular users can't send message to specific user/group. /// public bool DisablePrivateMessage { get { - return PortalController.GetPortalSetting("DisablePrivateMessage", PortalId, "N") == "Y"; + return PortalController.GetPortalSetting("DisablePrivateMessage", this.PortalId, "N") == "Y"; } } /// - /// If true then all users will be pushed through the data consent workflow + /// Gets a value indicating whether if true then all users will be pushed through the data consent workflow. /// public bool DataConsentActive { get; internal set; } /// - /// Last time the terms and conditions have been changed. This will determine if the user needs to + /// Gets last time the terms and conditions have been changed. This will determine if the user needs to /// reconsent or not. Legally once the terms have changed, users need to sign again. This value is set /// by the "reset consent" button on the UI. /// public DateTime DataConsentTermsLastChange { get; internal set; } /// - /// If set this is a tab id of a page where the user will be redirected to for consent. If not set then + /// Gets if set this is a tab id of a page where the user will be redirected to for consent. If not set then /// the platform's default logic is used. /// public int DataConsentConsentRedirect { get; internal set; } /// - /// Sets what should happen to the user account if a user has been deleted. This is important as - /// under certain circumstances you may be required by law to destroy the user's data within a + /// Gets what should happen to the user account if a user has been deleted. This is important as + /// under certain circumstances you may be required by law to destroy the user's data within a /// certain timeframe after a user has requested deletion. /// public UserDeleteAction DataConsentUserDeleteAction { get; internal set; } /// - /// Sets the delay time (in conjunction with DataConsentDelayMeasurement) for the DataConsentUserDeleteAction + /// Gets the delay time (in conjunction with DataConsentDelayMeasurement) for the DataConsentUserDeleteAction. /// public int DataConsentDelay { get; internal set; } /// - /// Units for DataConsentDelay + /// Gets units for DataConsentDelay. /// public string DataConsentDelayMeasurement { get; internal set; } /// - /// Whitelist of file extensions for end users + /// Gets whitelist of file extensions for end users. /// public FileExtensionWhitelist AllowedExtensionsWhitelist { get; internal set; } - #endregion - - #region IPropertyAccess Members public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { @@ -688,188 +663,195 @@ public string GetProperty(string propertyName, string format, CultureInfo format { outputFormat = "g"; } + var lowerPropertyName = propertyName.ToLowerInvariant(); if (accessLevel == Scope.NoSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } + propertyNotFound = true; var result = string.Empty; var isPublic = true; switch (lowerPropertyName) { + case "scheme": + propertyNotFound = false; + result = SSLEnabled ? "https" : "http"; + break; case "url": propertyNotFound = false; - result = PropertyAccess.FormatString(PortalAlias.HTTPAlias, format); + result = PropertyAccess.FormatString(this.PortalAlias.HTTPAlias, format); break; - case "fullurl": //return portal alias with protocol + case "fullurl": // return portal alias with protocol - note this depends on HttpContext propertyNotFound = false; - result = PropertyAccess.FormatString(Globals.AddHTTP(PortalAlias.HTTPAlias), format); + result = PropertyAccess.FormatString(Globals.AddHTTP(this.PortalAlias.HTTPAlias), format); break; - case "passwordreminderurl": //if regsiter page defined in portal settings, then get that page url, otherwise return home page. + case "passwordreminderurl": // if regsiter page defined in portal settings, then get that page url, otherwise return home page. - note this depends on HttpContext propertyNotFound = false; - var reminderUrl = Globals.AddHTTP(PortalAlias.HTTPAlias); - if (RegisterTabId > Null.NullInteger) + var reminderUrl = Globals.AddHTTP(this.PortalAlias.HTTPAlias); + if (this.RegisterTabId > Null.NullInteger) { reminderUrl = Globals.RegisterURL(string.Empty, string.Empty); } + result = PropertyAccess.FormatString(reminderUrl, format); break; case "portalid": propertyNotFound = false; - result = (PortalId.ToString(outputFormat, formatProvider)); + result = this.PortalId.ToString(outputFormat, formatProvider); break; case "portalname": propertyNotFound = false; - result = PropertyAccess.FormatString(PortalName, format); + result = PropertyAccess.FormatString(this.PortalName, format); break; case "homedirectory": propertyNotFound = false; - result = PropertyAccess.FormatString(HomeDirectory, format); + result = PropertyAccess.FormatString(this.HomeDirectory, format); break; case "homedirectorymappath": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(HomeDirectoryMapPath, format); + result = PropertyAccess.FormatString(this.HomeDirectoryMapPath, format); break; case "logofile": propertyNotFound = false; - result = PropertyAccess.FormatString(LogoFile, format); + result = PropertyAccess.FormatString(this.LogoFile, format); break; case "footertext": propertyNotFound = false; - var footerText = FooterText.Replace("[year]", DateTime.Now.Year.ToString()); + var footerText = this.FooterText.Replace("[year]", DateTime.Now.Year.ToString()); result = PropertyAccess.FormatString(footerText, format); break; case "expirydate": isPublic = false; propertyNotFound = false; - result = (ExpiryDate.ToString(outputFormat, formatProvider)); + result = this.ExpiryDate.ToString(outputFormat, formatProvider); break; case "userregistration": isPublic = false; propertyNotFound = false; - result = (UserRegistration.ToString(outputFormat, formatProvider)); + result = this.UserRegistration.ToString(outputFormat, formatProvider); break; case "banneradvertising": isPublic = false; propertyNotFound = false; - result = (BannerAdvertising.ToString(outputFormat, formatProvider)); + result = this.BannerAdvertising.ToString(outputFormat, formatProvider); break; case "currency": propertyNotFound = false; - result = PropertyAccess.FormatString(Currency, format); + result = PropertyAccess.FormatString(this.Currency, format); break; case "administratorid": isPublic = false; propertyNotFound = false; - result = (AdministratorId.ToString(outputFormat, formatProvider)); + result = this.AdministratorId.ToString(outputFormat, formatProvider); break; case "email": propertyNotFound = false; - result = PropertyAccess.FormatString(Email, format); + result = PropertyAccess.FormatString(this.Email, format); break; case "hostfee": isPublic = false; propertyNotFound = false; - result = (HostFee.ToString(outputFormat, formatProvider)); + result = this.HostFee.ToString(outputFormat, formatProvider); break; case "hostspace": isPublic = false; propertyNotFound = false; - result = (HostSpace.ToString(outputFormat, formatProvider)); + result = this.HostSpace.ToString(outputFormat, formatProvider); break; case "pagequota": isPublic = false; propertyNotFound = false; - result = (PageQuota.ToString(outputFormat, formatProvider)); + result = this.PageQuota.ToString(outputFormat, formatProvider); break; case "userquota": isPublic = false; propertyNotFound = false; - result = (UserQuota.ToString(outputFormat, formatProvider)); + result = this.UserQuota.ToString(outputFormat, formatProvider); break; case "administratorroleid": isPublic = false; propertyNotFound = false; - result = (AdministratorRoleId.ToString(outputFormat, formatProvider)); + result = this.AdministratorRoleId.ToString(outputFormat, formatProvider); break; case "administratorrolename": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(AdministratorRoleName, format); + result = PropertyAccess.FormatString(this.AdministratorRoleName, format); break; case "registeredroleid": isPublic = false; propertyNotFound = false; - result = (RegisteredRoleId.ToString(outputFormat, formatProvider)); + result = this.RegisteredRoleId.ToString(outputFormat, formatProvider); break; case "registeredrolename": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(RegisteredRoleName, format); + result = PropertyAccess.FormatString(this.RegisteredRoleName, format); break; case "description": propertyNotFound = false; - result = PropertyAccess.FormatString(Description, format); + result = PropertyAccess.FormatString(this.Description, format); break; case "keywords": propertyNotFound = false; - result = PropertyAccess.FormatString(KeyWords, format); + result = PropertyAccess.FormatString(this.KeyWords, format); break; case "backgroundfile": propertyNotFound = false; - result = PropertyAccess.FormatString(BackgroundFile, format); + result = PropertyAccess.FormatString(this.BackgroundFile, format); break; case "admintabid": isPublic = false; propertyNotFound = false; - result = AdminTabId.ToString(outputFormat, formatProvider); + result = this.AdminTabId.ToString(outputFormat, formatProvider); break; case "supertabid": isPublic = false; propertyNotFound = false; - result = SuperTabId.ToString(outputFormat, formatProvider); + result = this.SuperTabId.ToString(outputFormat, formatProvider); break; case "splashtabid": isPublic = false; propertyNotFound = false; - result = SplashTabId.ToString(outputFormat, formatProvider); + result = this.SplashTabId.ToString(outputFormat, formatProvider); break; case "hometabid": isPublic = false; propertyNotFound = false; - result = HomeTabId.ToString(outputFormat, formatProvider); + result = this.HomeTabId.ToString(outputFormat, formatProvider); break; case "logintabid": isPublic = false; propertyNotFound = false; - result = LoginTabId.ToString(outputFormat, formatProvider); + result = this.LoginTabId.ToString(outputFormat, formatProvider); break; case "registertabid": isPublic = false; propertyNotFound = false; - result = RegisterTabId.ToString(outputFormat, formatProvider); + result = this.RegisterTabId.ToString(outputFormat, formatProvider); break; case "usertabid": isPublic = false; propertyNotFound = false; - result = UserTabId.ToString(outputFormat, formatProvider); + result = this.UserTabId.ToString(outputFormat, formatProvider); break; case "defaultlanguage": propertyNotFound = false; - result = PropertyAccess.FormatString(DefaultLanguage, format); + result = PropertyAccess.FormatString(this.DefaultLanguage, format); break; case "users": isPublic = false; propertyNotFound = false; - result = Users.ToString(outputFormat, formatProvider); + result = this.Users.ToString(outputFormat, formatProvider); break; case "pages": isPublic = false; propertyNotFound = false; - result = Pages.ToString(outputFormat, formatProvider); + result = this.Pages.ToString(outputFormat, formatProvider); break; case "contentvisible": isPublic = false; @@ -877,26 +859,22 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "controlpanelvisible": isPublic = false; propertyNotFound = false; - result = PropertyAccess.Boolean2LocalizedYesNo(ControlPanelVisible, formatProvider); + result = PropertyAccess.Boolean2LocalizedYesNo(this.ControlPanelVisible, formatProvider); break; } + if (!isPublic && accessLevel != Scope.Debug) { propertyNotFound = true; result = PropertyAccess.ContentLocked; } + return result; } - #endregion - - #region Public Methods - public PortalSettings Clone() { - return (PortalSettings)MemberwiseClone(); + return (PortalSettings)this.MemberwiseClone(); } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs index de00c012397..12450eb24e0 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Collections; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Web.Client; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins; + using DotNetNuke.Web.Client; + public class PortalSettingsController : IPortalSettingsController { public static IPortalSettingsController Instance() @@ -37,11 +38,14 @@ public virtual void ConfigureActiveTab(PortalSettings portalSettings) { var activeTab = portalSettings.ActiveTab; - if (activeTab == null || activeTab.TabID == Null.NullInteger) return; - - UpdateSkinSettings(activeTab, portalSettings); + if (activeTab == null || activeTab.TabID == Null.NullInteger) + { + return; + } + + this.UpdateSkinSettings(activeTab, portalSettings); - activeTab.BreadCrumbs = new ArrayList(GetBreadcrumbs(activeTab.TabID, portalSettings.PortalId)); + activeTab.BreadCrumbs = new ArrayList(this.GetBreadcrumbs(activeTab.TabID, portalSettings.PortalId)); } public virtual TabInfo GetActiveTab(int tabId, PortalSettings portalSettings) @@ -50,11 +54,11 @@ public virtual TabInfo GetActiveTab(int tabId, PortalSettings portalSettings) var portalTabs = TabController.Instance.GetTabsByPortal(portalId); var hostTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger); - //Check portal + // Check portal var activeTab = GetTab(tabId, portalTabs) - ?? GetTab(tabId, hostTabs) //check host - ?? GetSpecialTab(portalId, portalSettings.SplashTabId) //check splash tab - ?? GetSpecialTab(portalId, portalSettings.HomeTabId); //check home tab + ?? GetTab(tabId, hostTabs) // check host + ?? GetSpecialTab(portalId, portalSettings.SplashTabId) // check splash tab + ?? GetSpecialTab(portalId, portalSettings.HomeTabId); // check home tab if (activeTab == null) { @@ -72,6 +76,7 @@ public virtual TabInfo GetActiveTab(int tabId, PortalSettings portalSettings) { activeTab.StartDate = DateTime.MinValue; } + if (Null.IsNull(activeTab.EndDate)) { activeTab.EndDate = DateTime.MaxValue; @@ -81,36 +86,6 @@ public virtual TabInfo GetActiveTab(int tabId, PortalSettings portalSettings) return activeTab; } - protected List GetBreadcrumbs(int tabId, int portalId) - { - var breadCrumbs = new List(); - GetBreadCrumbs(breadCrumbs, tabId, portalId); - return breadCrumbs; - } - - private static void GetBreadCrumbs(IList breadCrumbs, int tabId, int portalId) - { - var portalTabs = TabController.Instance.GetTabsByPortal(portalId); - var hostTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger); - while (true) - { - TabInfo tab; - if (portalTabs.TryGetValue(tabId, out tab) || hostTabs.TryGetValue(tabId, out tab)) - { - //add tab to breadcrumb collection - breadCrumbs.Insert(0, tab.Clone()); - - //get the tab parent - if (!Null.IsNull(tab.ParentId) && tabId != tab.ParentId) - { - tabId = tab.ParentId; - continue; - } - } - break; - } - } - public virtual PortalSettings.PortalAliasMapping GetPortalAliasMappingMode(int portalId) { var aliasMapping = PortalSettings.PortalAliasMapping.None; @@ -130,36 +105,10 @@ public virtual PortalSettings.PortalAliasMapping GetPortalAliasMappingMode(int p break; } } + return aliasMapping; } - private static TabInfo GetSpecialTab(int portalId, int tabId) - { - TabInfo activeTab = null; - - if (tabId > 0) - { - var tab = TabController.Instance.GetTab(tabId, portalId, false); - if (tab != null) - { - activeTab = tab.Clone(); - } - } - - return activeTab; - } - - // This method is called few times wiht each request; it would be - // better to have it cache the "activeTab" for a short period. - private static TabInfo GetTab(int tabId, TabCollection tabs) - { - TabInfo tab; - var activeTab = tabId != Null.NullInteger && tabs.TryGetValue(tabId, out tab) && !tab.IsDeleted - ? tab.Clone() - : null; - return activeTab; - } - public virtual IList GetTabModules(PortalSettings portalSettings) { return portalSettings.ActiveTab.Modules.Cast().Select(m => m).ToList(); @@ -210,16 +159,74 @@ public virtual void LoadPortal(PortalInfo portal, PortalSettings portalSettings) portalSettings.CultureCode = portal.CultureCode; } + protected List GetBreadcrumbs(int tabId, int portalId) + { + var breadCrumbs = new List(); + GetBreadCrumbs(breadCrumbs, tabId, portalId); + return breadCrumbs; + } + + private static void GetBreadCrumbs(IList breadCrumbs, int tabId, int portalId) + { + var portalTabs = TabController.Instance.GetTabsByPortal(portalId); + var hostTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger); + while (true) + { + TabInfo tab; + if (portalTabs.TryGetValue(tabId, out tab) || hostTabs.TryGetValue(tabId, out tab)) + { + // add tab to breadcrumb collection + breadCrumbs.Insert(0, tab.Clone()); + + // get the tab parent + if (!Null.IsNull(tab.ParentId) && tabId != tab.ParentId) + { + tabId = tab.ParentId; + continue; + } + } + + break; + } + } + + private static TabInfo GetSpecialTab(int portalId, int tabId) + { + TabInfo activeTab = null; + + if (tabId > 0) + { + var tab = TabController.Instance.GetTab(tabId, portalId, false); + if (tab != null) + { + activeTab = tab.Clone(); + } + } + + return activeTab; + } + + // This method is called few times wiht each request; it would be + // better to have it cache the "activeTab" for a short period. + private static TabInfo GetTab(int tabId, TabCollection tabs) + { + TabInfo tab; + var activeTab = tabId != Null.NullInteger && tabs.TryGetValue(tabId, out tab) && !tab.IsDeleted + ? tab.Clone() + : null; + return activeTab; + } + public virtual void LoadPortalSettings(PortalSettings portalSettings) { var settings = PortalController.Instance.GetPortalSettings(portalSettings.PortalId); portalSettings.Registration = new RegistrationSettings(settings); var clientResourcesSettings = new ClientResourceSettings(); - Boolean overridingDefaultSettings = clientResourcesSettings.IsOverridingDefaultSettingsEnabled(); + bool overridingDefaultSettings = clientResourcesSettings.IsOverridingDefaultSettingsEnabled(); int crmVersion; - if(overridingDefaultSettings) + if (overridingDefaultSettings) { int? globalVersion = new ClientResourceSettings().GetVersion(); crmVersion = globalVersion ?? default(int); @@ -228,7 +235,7 @@ public virtual void LoadPortalSettings(PortalSettings portalSettings) { crmVersion = settings.GetValueOrDefault("CrmVersion", HostController.Instance.GetInteger("CrmVersion")); } - + portalSettings.AllowUserUICulture = settings.GetValueOrDefault("AllowUserUICulture", false); portalSettings.CdfVersion = crmVersion; portalSettings.ContentLocalizationEnabled = settings.GetValueOrDefault("ContentLocalizationEnabled", false); @@ -265,37 +272,40 @@ public virtual void LoadPortalSettings(PortalSettings portalSettings) portalSettings.SMTPMaxIdleTime = settings.GetValueOrDefault("SMTPMaxIdleTime", 100000); portalSettings.ControlPanelSecurity = PortalSettings.ControlPanelPermission.ModuleEditor; - string setting = settings.GetValueOrDefault("ControlPanelSecurity", ""); + string setting = settings.GetValueOrDefault("ControlPanelSecurity", string.Empty); if (setting.Equals("TAB", StringComparison.InvariantCultureIgnoreCase)) { portalSettings.ControlPanelSecurity = PortalSettings.ControlPanelPermission.TabEditor; } portalSettings.DefaultControlPanelMode = PortalSettings.Mode.View; - setting = settings.GetValueOrDefault("ControlPanelMode", ""); + setting = settings.GetValueOrDefault("ControlPanelMode", string.Empty); if (setting.Equals("EDIT", StringComparison.InvariantCultureIgnoreCase)) { portalSettings.DefaultControlPanelMode = PortalSettings.Mode.Edit; } - setting = settings.GetValueOrDefault("ControlPanelVisibility", ""); + setting = settings.GetValueOrDefault("ControlPanelVisibility", string.Empty); portalSettings.DefaultControlPanelVisibility = !setting.Equals("MIN", StringComparison.InvariantCultureIgnoreCase); - setting = settings.GetValueOrDefault("TimeZone", ""); + setting = settings.GetValueOrDefault("TimeZone", string.Empty); if (!string.IsNullOrEmpty(setting)) { var timeZone = TimeZoneInfo.FindSystemTimeZoneById(setting); - if (timeZone != null) - portalSettings.TimeZone = timeZone; + if (timeZone != null) + { + portalSettings.TimeZone = timeZone; + } } setting = settings.GetValueOrDefault("DataConsentActive", "False"); portalSettings.DataConsentActive = bool.Parse(setting); - setting = settings.GetValueOrDefault("DataConsentTermsLastChange", ""); + setting = settings.GetValueOrDefault("DataConsentTermsLastChange", string.Empty); if (!string.IsNullOrEmpty(setting)) { portalSettings.DataConsentTermsLastChange = DateTime.Parse(setting, System.Globalization.CultureInfo.InvariantCulture); } + setting = settings.GetValueOrDefault("DataConsentConsentRedirect", "-1"); portalSettings.DataConsentConsentRedirect = int.Parse(setting); setting = settings.GetValueOrDefault("DataConsentUserDeleteAction", "0"); @@ -312,30 +322,31 @@ protected virtual void UpdateSkinSettings(TabInfo activeTab, PortalSettings port { if (Globals.IsAdminSkin()) { - //DNN-6170 ensure skin value is culture specific - activeTab.SkinSrc = String.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultAdminSkin", portalSettings.PortalId, + // DNN-6170 ensure skin value is culture specific + activeTab.SkinSrc = string.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultAdminSkin", portalSettings.PortalId, Host.Host.DefaultAdminSkin, portalSettings.CultureCode)) ? portalSettings.DefaultAdminSkin : PortalController.GetPortalSetting("DefaultAdminSkin", portalSettings.PortalId, Host.Host.DefaultAdminSkin, portalSettings.CultureCode); } - else if (String.IsNullOrEmpty(activeTab.SkinSrc)) + else if (string.IsNullOrEmpty(activeTab.SkinSrc)) { - //DNN-6170 ensure skin value is culture specific - activeTab.SkinSrc = String.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultPortalSkin", portalSettings.PortalId, + // DNN-6170 ensure skin value is culture specific + activeTab.SkinSrc = string.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultPortalSkin", portalSettings.PortalId, Host.Host.DefaultPortalSkin, portalSettings.CultureCode)) ? portalSettings.DefaultPortalSkin : PortalController.GetPortalSetting("DefaultPortalSkin", portalSettings.PortalId, Host.Host.DefaultPortalSkin, portalSettings.CultureCode); } + activeTab.SkinSrc = SkinController.FormatSkinSrc(activeTab.SkinSrc, portalSettings); activeTab.SkinPath = SkinController.FormatSkinPath(activeTab.SkinSrc); if (Globals.IsAdminSkin()) { - activeTab.ContainerSrc = String.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultAdminContainer", portalSettings.PortalId, + activeTab.ContainerSrc = string.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultAdminContainer", portalSettings.PortalId, Host.Host.DefaultAdminContainer, portalSettings.CultureCode)) ? portalSettings.DefaultAdminContainer : PortalController.GetPortalSetting("DefaultAdminContainer", portalSettings.PortalId, Host.Host.DefaultAdminContainer, portalSettings.CultureCode); } - else if (String.IsNullOrEmpty(activeTab.ContainerSrc)) + else if (string.IsNullOrEmpty(activeTab.ContainerSrc)) { - activeTab.ContainerSrc = String.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultPortalContainer", portalSettings.PortalId, + activeTab.ContainerSrc = string.IsNullOrEmpty(PortalController.GetPortalSetting("DefaultPortalContainer", portalSettings.PortalId, Host.Host.DefaultPortalContainer, portalSettings.CultureCode)) ? portalSettings.DefaultPortalContainer : PortalController.GetPortalSetting("DefaultPortalContainer", portalSettings.PortalId, Host.Host.DefaultPortalContainer, portalSettings.CultureCode); } diff --git a/DNN Platform/Library/Entities/Portals/PortalSettingsExtensions.cs b/DNN Platform/Library/Entities/Portals/PortalSettingsExtensions.cs index de0f750084b..f38f0b0d2c6 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettingsExtensions.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettingsExtensions.cs @@ -1,18 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Web; + public static class PortalSettingsExtensions { - /// /// Detect whether current page is custom error page. /// diff --git a/DNN Platform/Library/Entities/Portals/PortalTemplateEventArgs.cs b/DNN Platform/Library/Entities/Portals/PortalTemplateEventArgs.cs index 1cf45636e00..bc51a26e51d 100644 --- a/DNN Platform/Library/Entities/Portals/PortalTemplateEventArgs.cs +++ b/DNN Platform/Library/Entities/Portals/PortalTemplateEventArgs.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { + using System; + public class PortalTemplateEventArgs : EventArgs { public int PortalId { get; set; } diff --git a/DNN Platform/Library/Entities/Portals/PortalTemplateModuleAction.cs b/DNN Platform/Library/Entities/Portals/PortalTemplateModuleAction.cs index cecd18c6599..44709969b6b 100644 --- a/DNN Platform/Library/Entities/Portals/PortalTemplateModuleAction.cs +++ b/DNN Platform/Library/Entities/Portals/PortalTemplateModuleAction.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { public enum PortalTemplateModuleAction { Ignore, Merge, - Replace + Replace, } } diff --git a/DNN Platform/Library/Entities/Portals/PortalTemplateValidator.cs b/DNN Platform/Library/Entities/Portals/PortalTemplateValidator.cs index bd7fb8c2f5c..cdd756a99f5 100644 --- a/DNN Platform/Library/Entities/Portals/PortalTemplateValidator.cs +++ b/DNN Platform/Library/Entities/Portals/PortalTemplateValidator.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { + using DotNetNuke.Common; + /// ----------------------------------------------------------------------------- /// - /// The PortalTemplateValidator Class is used to validate the Portal Template + /// The PortalTemplateValidator Class is used to validate the Portal Template. /// /// /// @@ -20,8 +15,8 @@ public class PortalTemplateValidator : XmlValidatorBase { public bool Validate(string xmlFilename, string schemaFileName) { - SchemaSet.Add("", schemaFileName); - return Validate(xmlFilename); + this.SchemaSet.Add(string.Empty, schemaFileName); + return this.Validate(xmlFilename); } } } diff --git a/DNN Platform/Library/Entities/Portals/UserCopiedCallback.cs b/DNN Platform/Library/Entities/Portals/UserCopiedCallback.cs index 3452f6ec52a..70a581f1b03 100644 --- a/DNN Platform/Library/Entities/Portals/UserCopiedCallback.cs +++ b/DNN Platform/Library/Entities/Portals/UserCopiedCallback.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { public delegate void UserCopiedCallback(UserCopiedEventArgs e); diff --git a/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs b/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs index 372b3d89b59..98380d61e29 100644 --- a/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs +++ b/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs @@ -1,17 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals { public class UserCopiedEventArgs { public bool Cancel { get; set; } + public string PortalName { get; set; } + public float TotalUsers { get; set; } + public string UserName { get; set; } + public float UserNo { get; set; } + public string Stage { get; set; } + public int PortalGroupId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Profile/IProfileEventHandlers.cs b/DNN Platform/Library/Entities/Profile/IProfileEventHandlers.cs index 2c406595c23..23facb0cac4 100644 --- a/DNN Platform/Library/Entities/Profile/IProfileEventHandlers.cs +++ b/DNN Platform/Library/Entities/Profile/IProfileEventHandlers.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Profile { public interface IProfileEventHandlers diff --git a/DNN Platform/Library/Entities/Profile/ProfileController.cs b/DNN Platform/Library/Entities/Profile/ProfileController.cs index 094c2b1f5d8..a8463561b1b 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileController.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileController.cs @@ -1,31 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Text.RegularExpressions; -using System.Web; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Profile; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Profile { + using System; + using System.Collections.Generic; + using System.Data; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Profile; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Profile @@ -33,29 +29,96 @@ namespace DotNetNuke.Entities.Profile /// ----------------------------------------------------------------------------- /// /// The ProfileController class provides Business Layer methods for profiles and - /// for profile property Definitions + /// for profile property Definitions. /// /// /// /// ----------------------------------------------------------------------------- public class ProfileController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProfileController)); - - #region Private Members - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProfileController)); private static readonly DataProvider _dataProvider = DataProvider.Instance(); private static readonly ProfileProvider _profileProvider = ProfileProvider.Instance(); - private static int _orderCounter; + private static int _orderCounter; + + /// ----------------------------------------------------------------------------- + /// + /// Adds the default property definitions for a portal. + /// + /// Id of the Portal. + /// ----------------------------------------------------------------------------- + public static void AddDefaultDefinitions(int portalId) + { + portalId = GetEffectivePortalId(portalId); - #endregion + _orderCounter = 1; + var listController = new ListController(); + Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); - #region Private Methdods + AddDefaultDefinition(portalId, "Name", "Prefix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "FirstName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "MiddleName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "LastName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "Suffix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Address", "Unit", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "Street", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "City", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "Region", "Region", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "Country", "Country", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "PostalCode", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Telephone", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Cell", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Fax", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Website", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "IM", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "Biography", "Multi-line Text", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "TimeZone", "TimeZone", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "PreferredTimeZone", "TimeZoneInfo", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "PreferredLocale", "Locale", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "Photo", "Image", 0, UserVisibilityMode.AllUsers, dataTypes); - private static void AddDefaultDefinition(int portalId, string category, string name, string strType, int length, UserVisibilityMode defaultVisibility, Dictionary types) + // 6.0 requires the old TimeZone property to be marked as Deleted + ProfilePropertyDefinition pdf = GetPropertyDefinitionByName(portalId, "TimeZone"); + if (pdf != null) + { + DeletePropertyDefinition(pdf); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Adds a Property Defintion to the Data Store. + /// + /// An ProfilePropertyDefinition object. + /// The Id of the definition (or if negative the errorcode of the error). + /// ----------------------------------------------------------------------------- + public static int AddPropertyDefinition(ProfilePropertyDefinition definition) { - _orderCounter += 2; - AddDefaultDefinition(portalId, category, name, strType, length, _orderCounter, defaultVisibility, types); + int portalId = GetEffectivePortalId(definition.PortalId); + if (definition.Required) + { + definition.Visible = true; + } + + int intDefinition = _dataProvider.AddPropertyDefinition( + portalId, + definition.ModuleDefId, + definition.DataType, + definition.DefaultValue, + definition.PropertyCategory, + definition.PropertyName, + definition.ReadOnly, + definition.Required, + definition.ValidationExpression, + definition.ViewOrder, + definition.Visible, + definition.Length, + (int)definition.DefaultVisibility, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PROFILEPROPERTY_CREATED); + ClearProfileDefinitionCache(definition.PortalId); + ClearAllUsersInfoProfileCacheByPortal(definition.PortalId); + return intDefinition; } internal static void AddDefaultDefinition(int portalId, string category, string name, string type, int length, int viewOrder, UserVisibilityMode defaultVisibility, @@ -65,7 +128,7 @@ internal static void AddDefaultDefinition(int portalId, string category, string var propertyDefinition = new ProfilePropertyDefinition(portalId) { DataType = typeInfo.EntryID, - DefaultValue = "", + DefaultValue = string.Empty, ModuleDefId = Null.NullInteger, PropertyCategory = category, PropertyName = name, @@ -73,10 +136,16 @@ internal static void AddDefaultDefinition(int portalId, string category, string ViewOrder = viewOrder, Visible = true, Length = length, - DefaultVisibility = defaultVisibility + DefaultVisibility = defaultVisibility, }; AddPropertyDefinition(propertyDefinition); } + + private static void AddDefaultDefinition(int portalId, string category, string name, string strType, int length, UserVisibilityMode defaultVisibility, Dictionary types) + { + _orderCounter += 2; + AddDefaultDefinition(portalId, category, name, strType, length, _orderCounter, defaultVisibility, types); + } private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader dr) { @@ -93,6 +162,7 @@ private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader { CBO.CloseDataReader(dr, true); } + return definition; } @@ -100,7 +170,7 @@ private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader { ProfilePropertyDefinition definition = null; - //read datareader + // read datareader bool canContinue = true; if (checkForOpenDataReader) { @@ -110,6 +180,7 @@ private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader canContinue = true; } } + if (canContinue) { int portalid = 0; @@ -126,6 +197,7 @@ private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader { definition.ReadOnly = Convert.ToBoolean(Null.SetNull(dr["ReadOnly"], definition.ReadOnly)); } + definition.Required = Convert.ToBoolean(Null.SetNull(dr["Required"], definition.Required)); definition.ValidationExpression = Convert.ToString(Null.SetNull(dr["ValidationExpression"], definition.ValidationExpression)); definition.ViewOrder = Convert.ToInt32(Null.SetNull(dr["ViewOrder"], definition.ViewOrder)); @@ -133,10 +205,11 @@ private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader definition.DefaultVisibility = (UserVisibilityMode)Convert.ToInt32(Null.SetNull(dr["DefaultVisibility"], definition.DefaultVisibility)); definition.ProfileVisibility = new ProfileVisibility { - VisibilityMode = definition.DefaultVisibility + VisibilityMode = definition.DefaultVisibility, }; definition.Deleted = Convert.ToBoolean(Null.SetNull(dr["Deleted"], definition.Deleted)); } + return definition; } @@ -147,9 +220,10 @@ private static List FillPropertyDefinitionInfoCollect { while (dr.Read()) { - //fill business object + // fill business object ProfilePropertyDefinition definition = FillPropertyDefinitionInfo(dr, false); - //add to collection + + // add to collection arr.Add(definition); } } @@ -159,9 +233,10 @@ private static List FillPropertyDefinitionInfoCollect } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } + return arr; } @@ -172,115 +247,34 @@ private static int GetEffectivePortalId(int portalId) private static IEnumerable GetPropertyDefinitions(int portalId) { - //Get the Cache Key + // Get the Cache Key string key = string.Format(DataCache.ProfileDefinitionsCacheKey, portalId); - //Try fetching the List from the Cache + // Try fetching the List from the Cache var definitions = (List)DataCache.GetCache(key); if (definitions == null) { - //definitions caching settings - Int32 timeOut = DataCache.ProfileDefinitionsCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); + // definitions caching settings + int timeOut = DataCache.ProfileDefinitionsCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); - //Get the List from the database + // Get the List from the database definitions = FillPropertyDefinitionInfoCollection(_dataProvider.GetPropertyDefinitionsByPortal(portalId)); - //Cache the List + // Cache the List if (timeOut > 0) { DataCache.SetCache(key, definitions, TimeSpan.FromMinutes(timeOut)); } } + return definitions; - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// Adds the default property definitions for a portal - /// - /// Id of the Portal - /// ----------------------------------------------------------------------------- - public static void AddDefaultDefinitions(int portalId) - { - portalId = GetEffectivePortalId(portalId); - - _orderCounter = 1; - var listController = new ListController(); - Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); - - AddDefaultDefinition(portalId, "Name", "Prefix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "FirstName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "MiddleName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "LastName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "Suffix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Address", "Unit", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "Street", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "City", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "Region", "Region", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "Country", "Country", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "PostalCode", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Telephone", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Cell", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Fax", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Website", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "IM", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "Biography", "Multi-line Text", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "TimeZone", "TimeZone", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "PreferredTimeZone", "TimeZoneInfo", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "PreferredLocale", "Locale", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "Photo", "Image", 0, UserVisibilityMode.AllUsers, dataTypes); - - //6.0 requires the old TimeZone property to be marked as Deleted - ProfilePropertyDefinition pdf = GetPropertyDefinitionByName(portalId, "TimeZone"); - if (pdf != null) - { - DeletePropertyDefinition(pdf); - } - } + } /// ----------------------------------------------------------------------------- /// - /// Adds a Property Defintion to the Data Store + /// Clears the Profile Definitions Cache. /// - /// An ProfilePropertyDefinition object - /// The Id of the definition (or if negative the errorcode of the error) - /// ----------------------------------------------------------------------------- - public static int AddPropertyDefinition(ProfilePropertyDefinition definition) - { - int portalId = GetEffectivePortalId(definition.PortalId); - if (definition.Required) - { - definition.Visible = true; - } - int intDefinition = _dataProvider.AddPropertyDefinition(portalId, - definition.ModuleDefId, - definition.DataType, - definition.DefaultValue, - definition.PropertyCategory, - definition.PropertyName, - definition.ReadOnly, - definition.Required, - definition.ValidationExpression, - definition.ViewOrder, - definition.Visible, - definition.Length, - (int)definition.DefaultVisibility, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PROFILEPROPERTY_CREATED); - ClearProfileDefinitionCache(definition.PortalId); - ClearAllUsersInfoProfileCacheByPortal(definition.PortalId); - return intDefinition; - } - - /// ----------------------------------------------------------------------------- - /// - /// Clears the Profile Definitions Cache - /// - /// Id of the Portal + /// Id of the Portal. /// ----------------------------------------------------------------------------- public static void ClearProfileDefinitionCache(int portalId) { @@ -289,21 +283,21 @@ public static void ClearProfileDefinitionCache(int portalId) /// ----------------------------------------------------------------------------- /// - /// Deletes a Property Defintion from the Data Store + /// Deletes a Property Defintion from the Data Store. /// - /// The ProfilePropertyDefinition object to delete + /// The ProfilePropertyDefinition object to delete. /// ----------------------------------------------------------------------------- public static void DeletePropertyDefinition(ProfilePropertyDefinition definition) { _dataProvider.DeletePropertyDefinition(definition.PropertyDefinitionId); - EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PROFILEPROPERTY_DELETED); + EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PROFILEPROPERTY_DELETED); ClearProfileDefinitionCache(definition.PortalId); ClearAllUsersInfoProfileCacheByPortal(definition.PortalId); } /// ----------------------------------------------------------------------------- /// - /// Clear profiles of all users by portal Id + /// Clear profiles of all users by portal Id. /// /// ----------------------------------------------------------------------------- public static void ClearAllUsersInfoProfileCacheByPortal(int portalId) @@ -314,11 +308,11 @@ public static void ClearAllUsersInfoProfileCacheByPortal(int portalId) /// ----------------------------------------------------------------------------- /// - /// Gets a Property Defintion from the Data Store by id + /// Gets a Property Defintion from the Data Store by id. /// - /// The id of the ProfilePropertyDefinition object to retrieve + /// The id of the ProfilePropertyDefinition object to retrieve. /// Portal Id. - /// The ProfilePropertyDefinition object + /// The ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- public static ProfilePropertyDefinition GetPropertyDefinition(int definitionId, int portalId) { @@ -333,21 +327,23 @@ public static ProfilePropertyDefinition GetPropertyDefinition(int definitionId, break; } } + if (!bFound) { - //Try Database + // Try Database definition = FillPropertyDefinitionInfo(_dataProvider.GetPropertyDefinition(definitionId)); } + return definition; } /// ----------------------------------------------------------------------------- /// - /// Gets a Property Defintion from the Data Store by name + /// Gets a Property Defintion from the Data Store by name. /// - /// The id of the Portal - /// The name of the ProfilePropertyDefinition object to retrieve - /// The ProfilePropertyDefinition object + /// The id of the Portal. + /// The name of the ProfilePropertyDefinition object to retrieve. + /// The ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- public static ProfilePropertyDefinition GetPropertyDefinitionByName(int portalId, string name) { @@ -364,21 +360,23 @@ public static ProfilePropertyDefinition GetPropertyDefinitionByName(int portalId break; } } + if (!bFound) { - //Try Database + // Try Database definition = FillPropertyDefinitionInfo(_dataProvider.GetPropertyDefinitionByName(portalId, name)); } + return definition; } /// ----------------------------------------------------------------------------- /// - /// Gets a collection of Property Defintions from the Data Store by category + /// Gets a collection of Property Defintions from the Data Store by category. /// - /// The id of the Portal - /// The category of the Property Defintions to retrieve - /// A ProfilePropertyDefinitionCollection object + /// The id of the Portal. + /// The category of the Property Defintions to retrieve. + /// A ProfilePropertyDefinitionCollection object. /// ----------------------------------------------------------------------------- public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByCategory(int portalId, string category) { @@ -392,15 +390,16 @@ public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByCatego definitions.Add(definition); } } + return definitions; } /// ----------------------------------------------------------------------------- /// - /// Gets a collection of Property Defintions from the Data Store by portal + /// Gets a collection of Property Defintions from the Data Store by portal. /// - /// The id of the Portal - /// A ProfilePropertyDefinitionCollection object + /// The id of the Portal. + /// A ProfilePropertyDefinitionCollection object. /// ----------------------------------------------------------------------------- public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByPortal(int portalId) { @@ -409,11 +408,11 @@ public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByPortal /// ----------------------------------------------------------------------------- /// - /// Gets a collection of Property Defintions from the Data Store by portal + /// Gets a collection of Property Defintions from the Data Store by portal. /// - /// The id of the Portal + /// The id of the Portal. /// Whether to use a clone object. - /// A ProfilePropertyDefinitionCollection object + /// A ProfilePropertyDefinitionCollection object. /// ----------------------------------------------------------------------------- public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByPortal(int portalId, bool clone) { @@ -422,12 +421,12 @@ public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByPortal /// ----------------------------------------------------------------------------- /// - /// Gets a collection of Property Defintions from the Data Store by portal + /// Gets a collection of Property Defintions from the Data Store by portal. /// - /// The id of the Portal + /// The id of the Portal. /// Whether to use a clone object. /// Whether to include deleted profile properties. - /// A ProfilePropertyDefinitionCollection object + /// A ProfilePropertyDefinitionCollection object. /// ----------------------------------------------------------------------------- public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByPortal(int portalId, bool clone, bool includeDeleted) { @@ -441,12 +440,13 @@ public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByPortal definitions.Add(clone ? definition.Clone() : definition); } } + return definitions; } /// ----------------------------------------------------------------------------- /// - /// Gets the Profile Information for the User + /// Gets the Profile Information for the User. /// /// /// The user whose Profile information we are retrieving. @@ -462,40 +462,41 @@ public static void GetUserProfile(ref UserInfo user) /// ----------------------------------------------------------------------------- /// - /// Updates a Property Defintion in the Data Store + /// Updates a Property Defintion in the Data Store. /// - /// The ProfilePropertyDefinition object to update + /// The ProfilePropertyDefinition object to update. /// ----------------------------------------------------------------------------- public static void UpdatePropertyDefinition(ProfilePropertyDefinition definition) { - if (definition.Required) { definition.Visible = true; } - _dataProvider.UpdatePropertyDefinition(definition.PropertyDefinitionId, - definition.DataType, - definition.DefaultValue, - definition.PropertyCategory, - definition.PropertyName, - definition.ReadOnly, - definition.Required, - definition.ValidationExpression, - definition.ViewOrder, - definition.Visible, - definition.Length, - (int)definition.DefaultVisibility, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PROFILEPROPERTY_UPDATED); + + _dataProvider.UpdatePropertyDefinition( + definition.PropertyDefinitionId, + definition.DataType, + definition.DefaultValue, + definition.PropertyCategory, + definition.PropertyName, + definition.ReadOnly, + definition.Required, + definition.ValidationExpression, + definition.ViewOrder, + definition.Visible, + definition.Length, + (int)definition.DefaultVisibility, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PROFILEPROPERTY_UPDATED); ClearProfileDefinitionCache(definition.PortalId); ClearAllUsersInfoProfileCacheByPortal(definition.PortalId); } /// ----------------------------------------------------------------------------- /// - /// Updates a User's Profile + /// Updates a User's Profile. /// - /// The use to update + /// The use to update. /// /// /// ----------------------------------------------------------------------------- @@ -514,20 +515,20 @@ public static void UpdateUserProfile(UserInfo user) _profileProvider.UpdateUserProfile(user); - //Remove the UserInfo from the Cache, as it has been modified + // Remove the UserInfo from the Cache, as it has been modified DataCache.ClearUserCache(user.PortalID, user.Username); - //Raise Profile updated event + // Raise Profile updated event EventManager.Instance.OnProfileUpdated(new ProfileEventArgs { User = user, OldProfile = oldUser.Profile }); } /// ----------------------------------------------------------------------------- /// - /// Updates a User's Profile + /// Updates a User's Profile. /// - /// The use to update - /// The collection of profile properties - /// The updated User + /// The use to update. + /// The collection of profile properties. + /// The updated User. /// ----------------------------------------------------------------------------- public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitionCollection profileProperties) { @@ -535,7 +536,8 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio user.PortalID = portalId; var photoChanged = Null.NullBoolean; - //Iterate through the Definitions + + // Iterate through the Definitions if (profileProperties != null) { foreach (ProfilePropertyDefinition propertyDefinition in profileProperties) @@ -553,7 +555,7 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio } } - //if user's photo changed, then create different size thumbnails of profile pictures. + // if user's photo changed, then create different size thumbnails of profile pictures. if (photoChanged) { try @@ -567,48 +569,22 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio { Logger.Error(ex); } - } UserController.UpdateUser(portalId, user); } + return user; } - private static void CreateThumbnails(int fileId) - { - CreateThumbnail(fileId, "l", 64, 64); - CreateThumbnail(fileId, "s", 50, 50); - CreateThumbnail(fileId, "xs", 32, 32); - } - - private static void CreateThumbnail(int fileId, string type, int width, int height) - { - var file = FileManager.Instance.GetFile(fileId); - if (file != null) - { - var folder = FolderManager.Instance.GetFolder(file.FolderId); - var extension = "." + file.Extension; - var sizedPhoto = file.FileName.Replace(extension, "_" + type + extension); - if (!FileManager.Instance.FileExists(folder, sizedPhoto)) - { - using (var content = FileManager.Instance.GetFileContent(file)) - { - var sizedContent = ImageUtils.CreateImage(content, height, width, extension); - - FileManager.Instance.AddFile(folder, sizedPhoto, sizedContent); - } - } - } - } - /// ----------------------------------------------------------------------------- /// /// Validates the Profile properties for the User (determines if all required properties - /// have been set) + /// have been set). /// /// The Id of the portal. - /// The profile. + /// The profile. + /// /// ----------------------------------------------------------------------------- public static bool ValidateProfile(int portalId, UserProfile objProfile) { @@ -622,6 +598,7 @@ public static bool ValidateProfile(int portalId, UserProfile objProfile) break; } } + return isValid; } @@ -631,7 +608,7 @@ public static bool ValidateProfile(int portalId, UserProfile objProfile) /// The portal identifier. /// Name of the property. /// The search string. - /// List of matching values + /// List of matching values. public static List SearchProfilePropertyValues(int portalId, string propertyName, string searchString) { var res = new List { }; @@ -641,6 +618,7 @@ public static List SearchProfilePropertyValues(int portalId, string prop { return res; } + using ( IDataReader ir = Data.DataProvider.Instance() .SearchProfilePropertyValues(portalId, propertyName, searchString)) @@ -650,19 +628,41 @@ public static List SearchProfilePropertyValues(int portalId, string prop res.Add(Convert.ToString(ir[0])); } } + return res; - } + } - #endregion + private static void CreateThumbnails(int fileId) + { + CreateThumbnail(fileId, "l", 64, 64); + CreateThumbnail(fileId, "s", 50, 50); + CreateThumbnail(fileId, "xs", 32, 32); + } - #region Obsolete Methods + private static void CreateThumbnail(int fileId, string type, int width, int height) + { + var file = FileManager.Instance.GetFile(fileId); + if (file != null) + { + var folder = FolderManager.Instance.GetFolder(file.FolderId); + var extension = "." + file.Extension; + var sizedPhoto = file.FileName.Replace(extension, "_" + type + extension); + if (!FileManager.Instance.FileExists(folder, sizedPhoto)) + { + using (var content = FileManager.Instance.GetFileContent(file)) + { + var sizedContent = ImageUtils.CreateImage(content, height, width, extension); + FileManager.Instance.AddFile(folder, sizedPhoto, sizedContent); + } + } + } + } + [Obsolete("This method has been deprecated. Please use GetPropertyDefinition(ByVal definitionId As Integer, ByVal portalId As Integer) instead. Scheduled removal in v11.0.0.")] public static ProfilePropertyDefinition GetPropertyDefinition(int definitionId) { return CBO.FillObject(_dataProvider.GetPropertyDefinition(definitionId)); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfileEventArgs.cs b/DNN Platform/Library/Entities/Profile/ProfileEventArgs.cs index 3af3525aefb..5abbb25760c 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileEventArgs.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileEventArgs.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Profile -{ +{ + using System; + + using DotNetNuke.Entities.Users; + public class ProfileEventArgs : EventArgs { /// - /// The user whom's profile has been changed. This includes the Profile property with the updated profile + /// Gets or sets the user whom's profile has been changed. This includes the Profile property with the updated profile. /// public UserInfo User { get; set; } /// - /// The user's profile, as it was before the change + /// Gets or sets the user's profile, as it was before the change. /// public UserProfile OldProfile { get; set; } } diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs index 9bbc634a3f8..150b1897082 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Profile { - /// ----------------------------------------------------------------------------- + using System; + using System.ComponentModel; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.UI.WebControls; + + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Profile /// Class: ProfilePropertyDefinition /// ----------------------------------------------------------------------------- /// - /// The ProfilePropertyDefinition class provides a Business Layer entity for - /// property Definitions + /// The ProfilePropertyDefinition class provides a Business Layer entity for + /// property Definitions. /// /// /// @@ -28,57 +28,49 @@ namespace DotNetNuke.Entities.Profile [XmlRoot("profiledefinition", IsNullable = false)] [Serializable] public class ProfilePropertyDefinition : BaseEntityInfo - { - #region Private Members - + { private int _dataType = Null.NullInteger; private string _defaultValue; private UserVisibilityMode _defaultVisibility = UserVisibilityMode.AdminOnly; private bool _deleted; - private int _length; + private int _length; private int _moduleDefId = Null.NullInteger; private int _portalId; - private ProfileVisibility _profileVisibility = new ProfileVisibility - { - VisibilityMode = UserVisibilityMode.AdminOnly - }; + private ProfileVisibility _profileVisibility = new ProfileVisibility + { + VisibilityMode = UserVisibilityMode.AdminOnly, + }; + private string _propertyCategory; - private string _propertyName; + private string _propertyName; private string _propertyValue; private bool _readOnly; private bool _required; private string _ValidationExpression; private int _viewOrder; - private bool _visible; - - #endregion - - #region Constructors - + private bool _visible; + public ProfilePropertyDefinition() { - PropertyDefinitionId = Null.NullInteger; - //Get the default PortalSettings + this.PropertyDefinitionId = Null.NullInteger; + + // Get the default PortalSettings PortalSettings _Settings = PortalController.Instance.GetCurrentPortalSettings(); - PortalId = _Settings.PortalId; + this.PortalId = _Settings.PortalId; } public ProfilePropertyDefinition(int portalId) { - PropertyDefinitionId = Null.NullInteger; - PortalId = portalId; - } - - #endregion - - #region Public Properties - + this.PropertyDefinitionId = Null.NullInteger; + this.PortalId = portalId; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Data Type of the Profile Property + /// Gets or sets and sets the Data Type of the Profile Property. /// /// ----------------------------------------------------------------------------- - [Editor("DotNetNuke.UI.WebControls.DNNListEditControl, DotNetNuke", typeof (EditControl))] + [Editor("DotNetNuke.UI.WebControls.DNNListEditControl, DotNetNuke", typeof(EditControl))] [List("DataType", "", ListBoundField.Id, ListBoundField.Value)] [IsReadOnly(true)] [Required(true)] @@ -88,21 +80,23 @@ public int DataType { get { - return _dataType; + return this._dataType; } + set { - if (_dataType != value) + if (this._dataType != value) { - IsDirty = true; + this.IsDirty = true; } - _dataType = value; + + this._dataType = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Default Value of the Profile Property + /// Gets or sets and sets the Default Value of the Profile Property. /// /// ----------------------------------------------------------------------------- [SortOrder(4)] @@ -111,21 +105,23 @@ public string DefaultValue { get { - return _defaultValue; + return this._defaultValue; } + set { - if (_defaultValue != value) + if (this._defaultValue != value) { - IsDirty = true; + this.IsDirty = true; } - _defaultValue = value; + + this._defaultValue = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Default Visibility of the Profile Property + /// Gets or sets and sets the Default Visibility of the Profile Property. /// /// ----------------------------------------------------------------------------- [SortOrder(10)] @@ -134,21 +130,23 @@ public UserVisibilityMode DefaultVisibility { get { - return _defaultVisibility; + return this._defaultVisibility; } + set { - if (_defaultVisibility != value) + if (this._defaultVisibility != value) { - IsDirty = true; + this.IsDirty = true; } - _defaultVisibility = value; + + this._defaultVisibility = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Deleted + /// Gets or sets a value indicating whether gets and sets the Deleted. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -157,26 +155,27 @@ public bool Deleted { get { - return _deleted; + return this._deleted; } + set { - _deleted = value; + this._deleted = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets whether the Definition has been modified since it has been retrieved - /// - /// ----------------------------------------------------------------------------- - [Browsable(false)] + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether the Definition has been modified since it has been retrieved. + /// + /// ----------------------------------------------------------------------------- + [Browsable(false)] [XmlIgnore] - public bool IsDirty { get; private set; } + public bool IsDirty { get; private set; } - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Length of the Profile Property + /// Gets or sets and sets the Length of the Profile Property. /// /// ----------------------------------------------------------------------------- [SortOrder(3)] @@ -185,21 +184,23 @@ public int Length { get { - return _length; + return this._length; } + set { - if (_length != value) + if (this._length != value) { - IsDirty = true; + this.IsDirty = true; } - _length = value; + + this._length = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleDefId + /// Gets or sets and sets the ModuleDefId. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -208,17 +209,18 @@ public int ModuleDefId { get { - return _moduleDefId; + return this._moduleDefId; } + set { - _moduleDefId = value; + this._moduleDefId = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the PortalId + /// Gets or sets and sets the PortalId. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -227,17 +229,18 @@ public int PortalId { get { - return _portalId; + return this._portalId; } + set { - _portalId = value; + this._portalId = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Category of the Profile Property + /// Gets or sets and sets the Category of the Profile Property. /// /// ----------------------------------------------------------------------------- [Required(true)] @@ -247,30 +250,32 @@ public string PropertyCategory { get { - return _propertyCategory; + return this._propertyCategory; } + set { - if (_propertyCategory != value) + if (this._propertyCategory != value) { - IsDirty = true; + this.IsDirty = true; } - _propertyCategory = value; + + this._propertyCategory = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Id of the ProfilePropertyDefinition - /// - /// ----------------------------------------------------------------------------- - [Browsable(false)] + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Id of the ProfilePropertyDefinition. + /// + /// ----------------------------------------------------------------------------- + [Browsable(false)] [XmlIgnore] - public int PropertyDefinitionId { get; set; } + public int PropertyDefinitionId { get; set; } - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Name of the Profile Property + /// Gets or sets and sets the Name of the Profile Property. /// /// ----------------------------------------------------------------------------- [Required(true)] @@ -282,21 +287,23 @@ public string PropertyName { get { - return _propertyName; + return this._propertyName; } + set { - if (_propertyName != value) + if (this._propertyName != value) { - IsDirty = true; + this.IsDirty = true; } - _propertyName = value; + + this._propertyName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Value of the Profile Property + /// Gets or sets and sets the Value of the Profile Property. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -305,21 +312,23 @@ public string PropertyValue { get { - return _propertyValue; + return this._propertyValue; } + set { - if (_propertyValue != value) + if (this._propertyValue != value) { - IsDirty = true; + this.IsDirty = true; } - _propertyValue = value; + + this._propertyValue = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the property is read only + /// Gets or sets a value indicating whether gets and sets whether the property is read only. /// /// ----------------------------------------------------------------------------- [SortOrder(7)] @@ -328,21 +337,23 @@ public bool ReadOnly { get { - return _readOnly; + return this._readOnly; } + set { - if (_readOnly != value) + if (this._readOnly != value) { - IsDirty = true; + this.IsDirty = true; } - _readOnly = value; + + this._readOnly = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the property is required + /// Gets or sets a value indicating whether gets and sets whether the property is required. /// /// ----------------------------------------------------------------------------- [SortOrder(6)] @@ -351,21 +362,23 @@ public bool Required { get { - return _required; + return this._required; } + set { - if (_required != value) + if (this._required != value) { - IsDirty = true; + this.IsDirty = true; } - _required = value; + + this._required = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a Validation Expression (RegEx) for the Profile Property + /// Gets or sets and sets a Validation Expression (RegEx) for the Profile Property. /// /// ----------------------------------------------------------------------------- [SortOrder(5)] @@ -374,21 +387,23 @@ public string ValidationExpression { get { - return _ValidationExpression; + return this._ValidationExpression; } + set { - if (_ValidationExpression != value) + if (this._ValidationExpression != value) { - IsDirty = true; + this.IsDirty = true; } - _ValidationExpression = value; + + this._ValidationExpression = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the View Order of the Property + /// Gets or sets and sets the View Order of the Property. /// /// ----------------------------------------------------------------------------- [IsReadOnly(true)] @@ -398,21 +413,23 @@ public int ViewOrder { get { - return _viewOrder; + return this._viewOrder; } + set { - if (_viewOrder != value) + if (this._viewOrder != value) { - IsDirty = true; + this.IsDirty = true; } - _viewOrder = value; + + this._viewOrder = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the property is visible + /// Gets or sets a value indicating whether gets and sets whether the property is visible. /// /// ----------------------------------------------------------------------------- [SortOrder(8)] @@ -421,88 +438,45 @@ public bool Visible { get { - return _visible; + return this._visible; } + set { - if (_visible != value) + if (this._visible != value) { - IsDirty = true; + this.IsDirty = true; } - _visible = value; + + this._visible = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the property is visible + /// Gets or sets and sets whether the property is visible. /// /// ----------------------------------------------------------------------------- [Browsable(false)] [XmlIgnore] public ProfileVisibility ProfileVisibility - { + { get { - return _profileVisibility; + return this._profileVisibility; } + set { - if (_profileVisibility != value) + if (this._profileVisibility != value) { - IsDirty = true; + this.IsDirty = true; } - _profileVisibility = value; - } - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// Clears the IsDirty Flag - /// - /// ----------------------------------------------------------------------------- - public void ClearIsDirty() - { - IsDirty = false; - } - - /// - /// Clone a ProfilePropertyDefinition - /// - /// A ProfilePropertyDefinition - public ProfilePropertyDefinition Clone() - { - var clone = new ProfilePropertyDefinition(PortalId) - { - DataType = DataType, - DefaultValue = DefaultValue, - Length = Length, - ModuleDefId = ModuleDefId, - PropertyCategory = PropertyCategory, - PropertyDefinitionId = PropertyDefinitionId, - PropertyName = PropertyName, - PropertyValue = PropertyValue, - ReadOnly = ReadOnly, - Required = Required, - ValidationExpression = ValidationExpression, - ViewOrder = ViewOrder, - DefaultVisibility = DefaultVisibility, - ProfileVisibility = ProfileVisibility.Clone(), - Visible = Visible, - Deleted = Deleted - }; - clone.ClearIsDirty(); - return clone; - } - - #endregion - - #region Obsolete - + + this._profileVisibility = value; + } + } + [Obsolete("Deprecated in 6.2 as profile visibility has been extended, keep for compatible with upgrade.. Scheduled removal in v10.0.0.")] [Browsable(false)] [XmlIgnore] @@ -510,18 +484,57 @@ public UserVisibilityMode Visibility { get { - return ProfileVisibility.VisibilityMode; + return this.ProfileVisibility.VisibilityMode; } + set { - if (ProfileVisibility.VisibilityMode != value) + if (this.ProfileVisibility.VisibilityMode != value) { - IsDirty = true; + this.IsDirty = true; } - ProfileVisibility.VisibilityMode = value; + + this.ProfileVisibility.VisibilityMode = value; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Clears the IsDirty Flag. + /// + /// ----------------------------------------------------------------------------- + public void ClearIsDirty() + { + this.IsDirty = false; } - #endregion + /// + /// Clone a ProfilePropertyDefinition. + /// + /// A ProfilePropertyDefinition. + public ProfilePropertyDefinition Clone() + { + var clone = new ProfilePropertyDefinition(this.PortalId) + { + DataType = this.DataType, + DefaultValue = this.DefaultValue, + Length = this.Length, + ModuleDefId = this.ModuleDefId, + PropertyCategory = this.PropertyCategory, + PropertyDefinitionId = this.PropertyDefinitionId, + PropertyName = this.PropertyName, + PropertyValue = this.PropertyValue, + ReadOnly = this.ReadOnly, + Required = this.Required, + ValidationExpression = this.ValidationExpression, + ViewOrder = this.ViewOrder, + DefaultVisibility = this.DefaultVisibility, + ProfileVisibility = this.ProfileVisibility.Clone(), + Visible = this.Visible, + Deleted = this.Deleted, + }; + clone.ClearIsDirty(); + return clone; + } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs index 123a1b01e6d..436f61f3ff7 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs @@ -1,60 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Profile { + using System; + using System.Collections; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Profile /// Class: ProfilePropertyDefinitionCollection /// ----------------------------------------------------------------------------- /// - /// The ProfilePropertyDefinitionCollection class provides Business Layer methods for - /// a collection of property Definitions + /// The ProfilePropertyDefinitionCollection class provides Business Layer methods for + /// a collection of property Definitions. /// /// /// /// ----------------------------------------------------------------------------- [Serializable] public class ProfilePropertyDefinitionCollection : CollectionBase - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new default collection + /// + /// Initializes a new instance of the class. + /// Constructs a new default collection. /// /// ----------------------------------------------------------------------------- public ProfilePropertyDefinitionCollection() { - } - + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new Collection from an ArrayList of ProfilePropertyDefinition objects + /// + /// Initializes a new instance of the class. + /// Constructs a new Collection from an ArrayList of ProfilePropertyDefinition objects. /// - /// An ArrayList of ProfilePropertyDefinition objects + /// An ArrayList of ProfilePropertyDefinition objects. /// ----------------------------------------------------------------------------- public ProfilePropertyDefinitionCollection(ArrayList definitionsList) { - AddRange(definitionsList); - } - + this.AddRange(definitionsList); + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new Collection from a ProfilePropertyDefinitionCollection + /// + /// Initializes a new instance of the class. + /// Constructs a new Collection from a ProfilePropertyDefinitionCollection. /// - /// A ProfilePropertyDefinitionCollection + /// A ProfilePropertyDefinitionCollection. /// ----------------------------------------------------------------------------- public ProfilePropertyDefinitionCollection(ProfilePropertyDefinitionCollection collection) { - AddRange(collection); + this.AddRange(collection); } /// ----------------------------------------------------------------------------- @@ -62,18 +60,19 @@ public ProfilePropertyDefinitionCollection(ProfilePropertyDefinitionCollection c /// Gets and sets an item in the collection. /// /// This overload returns the item by its index. - /// The index to get - /// A ProfilePropertyDefinition object + /// The index to get. + /// A ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- public ProfilePropertyDefinition this[int index] { get { - return (ProfilePropertyDefinition) List[index]; + return (ProfilePropertyDefinition)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } @@ -81,15 +80,15 @@ public ProfilePropertyDefinition this[int index] /// /// Gets an item in the collection. /// - /// This overload returns the item by its name - /// The name of the Property to get - /// A ProfilePropertyDefinition object + /// This overload returns the item by its name. + /// The name of the Property to get. + /// A ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- public ProfilePropertyDefinition this[string name] { get { - return GetByName(name); + return this.GetByName(name); } } @@ -97,71 +96,72 @@ public ProfilePropertyDefinition this[string name] /// /// Adds a property Definition to the collectio. /// - /// A ProfilePropertyDefinition object - /// The index of the property Definition in the collection + /// A ProfilePropertyDefinition object. + /// The index of the property Definition in the collection. /// ----------------------------------------------------------------------------- public int Add(ProfilePropertyDefinition value) { - return List.Add(value); + return this.List.Add(value); } /// ----------------------------------------------------------------------------- /// - /// Add an ArrayList of ProfilePropertyDefinition objects + /// Add an ArrayList of ProfilePropertyDefinition objects. /// - /// An ArrayList of ProfilePropertyDefinition objects + /// An ArrayList of ProfilePropertyDefinition objects. /// ----------------------------------------------------------------------------- public void AddRange(ArrayList definitionsList) { foreach (ProfilePropertyDefinition objProfilePropertyDefinition in definitionsList) { - Add(objProfilePropertyDefinition); + this.Add(objProfilePropertyDefinition); } } /// ----------------------------------------------------------------------------- /// - /// Add an existing ProfilePropertyDefinitionCollection + /// Add an existing ProfilePropertyDefinitionCollection. /// - /// A ProfilePropertyDefinitionCollection + /// A ProfilePropertyDefinitionCollection. /// ----------------------------------------------------------------------------- public void AddRange(ProfilePropertyDefinitionCollection collection) { foreach (ProfilePropertyDefinition objProfilePropertyDefinition in collection) { - Add(objProfilePropertyDefinition); + this.Add(objProfilePropertyDefinition); } } /// ----------------------------------------------------------------------------- /// - /// Determines whether the collection contains a property definition + /// Determines whether the collection contains a property definition. /// - /// A ProfilePropertyDefinition object - /// A Boolean True/False + /// A ProfilePropertyDefinition object. + /// A Boolean True/False. /// ----------------------------------------------------------------------------- public bool Contains(ProfilePropertyDefinition value) { - return List.Contains(value); + return this.List.Contains(value); } /// ----------------------------------------------------------------------------- /// /// Gets a sub-collection of items in the collection by category. /// - /// The category to get - /// A ProfilePropertyDefinitionCollection object + /// The category to get. + /// A ProfilePropertyDefinitionCollection object. /// ----------------------------------------------------------------------------- public ProfilePropertyDefinitionCollection GetByCategory(string category) { var collection = new ProfilePropertyDefinitionCollection(); - foreach (ProfilePropertyDefinition profileProperty in InnerList) + foreach (ProfilePropertyDefinition profileProperty in this.InnerList) { if (profileProperty.PropertyCategory == category) { collection.Add(profileProperty); } } + return collection; } @@ -169,19 +169,20 @@ public ProfilePropertyDefinitionCollection GetByCategory(string category) /// /// Gets an item in the collection by Id. /// - /// The id of the Property to get - /// A ProfilePropertyDefinition object + /// The id of the Property to get. + /// A ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- public ProfilePropertyDefinition GetById(int id) { ProfilePropertyDefinition profileItem = null; - foreach (ProfilePropertyDefinition profileProperty in InnerList) + foreach (ProfilePropertyDefinition profileProperty in this.InnerList) { if (profileProperty.PropertyDefinitionId == id) { profileItem = profileProperty; } } + return profileItem; } @@ -189,66 +190,67 @@ public ProfilePropertyDefinition GetById(int id) /// /// Gets an item in the collection by name. /// - /// The name of the Property to get - /// A ProfilePropertyDefinition object + /// The name of the Property to get. + /// A ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- public ProfilePropertyDefinition GetByName(string name) { ProfilePropertyDefinition profileItem = null; - foreach (ProfilePropertyDefinition profileProperty in InnerList) + foreach (ProfilePropertyDefinition profileProperty in this.InnerList) { if (profileProperty?.PropertyName == name) { - //Found Profile property + // Found Profile property profileItem = profileProperty; } } + return profileItem; } /// ----------------------------------------------------------------------------- /// - /// Gets the index of a property Definition + /// Gets the index of a property Definition. /// - /// A ProfilePropertyDefinition object - /// The index of the property Definition in the collection + /// A ProfilePropertyDefinition object. + /// The index of the property Definition in the collection. /// ----------------------------------------------------------------------------- public int IndexOf(ProfilePropertyDefinition value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } /// ----------------------------------------------------------------------------- /// /// Inserts a property Definition into the collectio. /// - /// A ProfilePropertyDefinition object - /// The index to insert the item at + /// A ProfilePropertyDefinition object. + /// The index to insert the item at. /// ----------------------------------------------------------------------------- public void Insert(int index, ProfilePropertyDefinition value) { - List.Insert(index, value); + this.List.Insert(index, value); } /// ----------------------------------------------------------------------------- /// - /// Removes a property definition from the collection + /// Removes a property definition from the collection. /// - /// The ProfilePropertyDefinition object to remove + /// The ProfilePropertyDefinition object to remove. /// ----------------------------------------------------------------------------- public void Remove(ProfilePropertyDefinition value) { - List.Remove(value); + this.List.Remove(value); } /// ----------------------------------------------------------------------------- /// - /// Sorts the collection using the ProfilePropertyDefinitionComparer (ie by ViewOrder) + /// Sorts the collection using the ProfilePropertyDefinitionComparer (ie by ViewOrder). /// /// ----------------------------------------------------------------------------- public void Sort() { - InnerList.Sort(new ProfilePropertyDefinitionComparer()); + this.InnerList.Sort(new ProfilePropertyDefinitionComparer()); } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs index 41cf23cf80a..6ec3fca6964 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Profile { + using System.Collections; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Profile @@ -17,28 +12,24 @@ namespace DotNetNuke.Entities.Profile /// ----------------------------------------------------------------------------- /// /// The ProfilePropertyDefinitionComparer class provides an implementation of - /// IComparer to sort the ProfilePropertyDefinitionCollection by ViewOrder + /// IComparer to sort the ProfilePropertyDefinitionCollection by ViewOrder. /// /// /// /// ----------------------------------------------------------------------------- public class ProfilePropertyDefinitionComparer : IComparer - { - #region IComparer Members - + { /// ----------------------------------------------------------------------------- /// - /// Compares two ProfilePropertyDefinition objects + /// Compares two ProfilePropertyDefinition objects. /// - /// A ProfilePropertyDefinition object - /// A ProfilePropertyDefinition object - /// An integer indicating whether x greater than y, x=y or x less than y + /// A ProfilePropertyDefinition object. + /// A ProfilePropertyDefinition object. + /// An integer indicating whether x greater than y, x=y or x less than y. /// ----------------------------------------------------------------------------- public int Compare(object x, object y) { - return ((ProfilePropertyDefinition) x).ViewOrder.CompareTo(((ProfilePropertyDefinition) y).ViewOrder); - } - - #endregion + return ((ProfilePropertyDefinition)x).ViewOrder.CompareTo(((ProfilePropertyDefinition)y).ViewOrder); + } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs index 028a69d7c63..44baf3c7f44 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs @@ -1,57 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Profile { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Text; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + [Serializable] public class ProfileVisibility { public ProfileVisibility() { - RoleVisibilities = new List(); - RelationshipVisibilities = new List(); + this.RoleVisibilities = new List(); + this.RelationshipVisibilities = new List(); } - public ProfileVisibility(int portalId, string extendedVisibility) : this() + public ProfileVisibility(int portalId, string extendedVisibility) + : this() { - if (!String.IsNullOrEmpty(extendedVisibility)) + if (!string.IsNullOrEmpty(extendedVisibility)) { var relationshipController = new RelationshipController(); var lists = extendedVisibility.Split(';'); - if (!String.IsNullOrEmpty(lists[0].Substring(2).TrimEnd(','))) + if (!string.IsNullOrEmpty(lists[0].Substring(2).TrimEnd(','))) { var roles = lists[0].Substring(2).TrimEnd(',').Split(','); foreach (var role in roles) { - int roleId = Int32.Parse(role); + int roleId = int.Parse(role); RoleInfo userRole = RoleController.Instance.GetRole(portalId, r => r.RoleID == roleId); - RoleVisibilities.Add(userRole); + this.RoleVisibilities.Add(userRole); } } - if (!String.IsNullOrEmpty(lists[1].Substring(2).TrimEnd(','))) + + if (!string.IsNullOrEmpty(lists[1].Substring(2).TrimEnd(','))) { var relationships = lists[1].Substring(2).TrimEnd(',').Split(','); foreach (var relationship in relationships) { - Relationship userRelationship = RelationshipController.Instance.GetRelationship(Int32.Parse(relationship)); - RelationshipVisibilities.Add(userRelationship); + Relationship userRelationship = RelationshipController.Instance.GetRelationship(int.Parse(relationship)); + this.RelationshipVisibilities.Add(userRelationship); } } } - } public UserVisibilityMode VisibilityMode { get; set; } @@ -62,27 +63,28 @@ public ProfileVisibility(int portalId, string extendedVisibility) : this() public ProfileVisibility Clone() { - var pv = new ProfileVisibility() - { - VisibilityMode = VisibilityMode, - RoleVisibilities = new List(RoleVisibilities), - RelationshipVisibilities = new List(RelationshipVisibilities) - }; + var pv = new ProfileVisibility() + { + VisibilityMode = this.VisibilityMode, + RoleVisibilities = new List(this.RoleVisibilities), + RelationshipVisibilities = new List(this.RelationshipVisibilities), + }; return pv; } public string ExtendedVisibilityString() { - if (VisibilityMode == UserVisibilityMode.FriendsAndGroups) + if (this.VisibilityMode == UserVisibilityMode.FriendsAndGroups) { var sb = new StringBuilder(); sb.Append("G:"); - foreach (var role in RoleVisibilities) + foreach (var role in this.RoleVisibilities) { sb.Append(role.RoleID.ToString(CultureInfo.InvariantCulture) + ","); } + sb.Append(";R:"); - foreach (var relationship in RelationshipVisibilities) + foreach (var relationship in this.RelationshipVisibilities) { sb.Append(relationship.RelationshipId.ToString(CultureInfo.InvariantCulture) + ","); } @@ -90,7 +92,7 @@ public string ExtendedVisibilityString() return sb.ToString(); } - return String.Empty; + return string.Empty; } } } diff --git a/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs b/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs index 21174952a9f..1014a19205b 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs @@ -1,16 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.Actions { public interface ITabEventHandler { void TabCreated(object sender, TabEventArgs args); + void TabUpdated(object sender, TabEventArgs args); + void TabRemoved(object sender, TabEventArgs args); + void TabDeleted(object sender, TabEventArgs args); + void TabRestored(object sender, TabEventArgs args); + void TabMarkedAsPublished(object sender, TabEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs b/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs index ad3ce153fa8..14a78ebbf30 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.Actions { public interface ITabSyncEventHandler { void TabSerialize(object sender, TabSyncEventArgs args); + void TabDeserialize(object sender, TabSyncEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Tabs/Actions/TabEventArgs.cs b/DNN Platform/Library/Entities/Tabs/Actions/TabEventArgs.cs index a5cddd94a8c..03a4763365d 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/TabEventArgs.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/TabEventArgs.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.Actions { + using System; + public class TabEventArgs : EventArgs { public TabInfo Tab { get; internal set; } diff --git a/DNN Platform/Library/Entities/Tabs/Actions/TabSyncEventArgs.cs b/DNN Platform/Library/Entities/Tabs/Actions/TabSyncEventArgs.cs index 9d086bfb426..c5e1a1d6c92 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/TabSyncEventArgs.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/TabSyncEventArgs.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Xml; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.Actions { + using System; + using System.Xml; + public class TabSyncEventArgs : TabEventArgs { public XmlNode TabNode { get; set; } diff --git a/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs b/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs index 4921f7da6b9..4199a3638f3 100644 --- a/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs +++ b/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.Dto { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + /// /// Class that represents the full state of a tab regarding if versioning and workflow are enabled. /// @@ -21,7 +21,7 @@ public class ChangeControlState /// The portal id. /// public int PortalId { get; set; } - + /// /// Gets or sets the tab id. /// @@ -31,25 +31,26 @@ public class ChangeControlState public int TabId { get; set; } /// - /// Gets if change control is enabled for the tab. + /// Gets a value indicating whether gets if change control is enabled for the tab. /// /// /// True if versioning or workflow are enabled, false otherwise. /// public bool IsChangeControlEnabledForTab { - get { return IsVersioningEnabledForTab || IsWorkflowEnabledForTab; } + get { return this.IsVersioningEnabledForTab || this.IsWorkflowEnabledForTab; } } /// - /// Gets if versioning is enabled for the tab. + /// Gets or sets a value indicating whether gets if versioning is enabled for the tab. /// /// /// True if versioning is enabled, false otherwise. /// public bool IsVersioningEnabledForTab { get; set; } + /// - /// Gets if workflow is enabled for the tab. + /// Gets or sets a value indicating whether gets if workflow is enabled for the tab. /// /// /// True if workflow is enabled, false otherwise. diff --git a/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs b/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs index 4f5e311bf09..b86e1515c0b 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs @@ -1,29 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Tabs.Dto; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using DotNetNuke.Entities.Tabs.Dto; + /// - /// Class responsible to provide settings for Tab Changes + /// Class responsible to provide settings for Tab Changes. /// public interface ITabChangeSettings { /// - /// Get the status of the tab changes control in a specific tab and its master portal + /// Get the status of the tab changes control in a specific tab and its master portal. /// - /// Portal Id - /// Tab Id - /// Returns true if changes control is available for both Portal and Tab, false otherwise + /// Portal Id. + /// Tab Id. + /// Returns true if changes control is available for both Portal and Tab, false otherwise. bool IsChangeControlEnabled(int portalId, int tabId); /// - /// Get the full state of the tab changes control in a specific tab and its master portal + /// Get the full state of the tab changes control in a specific tab and its master portal. /// - /// Portal Id - /// Tab Id + /// Portal Id. + /// Tab Id. + /// ChangeControlState GetChangeControlState(int portalId, int tabId); } } diff --git a/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs b/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs index b6b4466ab8b..b6b20dfaed2 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs @@ -1,53 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using DotNetNuke.Entities.Modules; + public interface ITabChangeTracker { /// - /// Tracks a change when a module is added to a page + /// Tracks a change when a module is added to a page. /// - /// Module which tracks the change - /// Version number corresponding to the change - /// User Id who provokes the change + /// Module which tracks the change. + /// Version number corresponding to the change. + /// User Id who provokes the change. void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId); /// - /// Tracks a change when a module is modified on a page + /// Tracks a change when a module is modified on a page. /// - /// Module which tracks the change - /// Version number corresponding to the change - /// User Id who provokes the change + /// Module which tracks the change. + /// Version number corresponding to the change. + /// User Id who provokes the change. void TrackModuleModification(ModuleInfo module, int moduleVersion, int userId); /// - /// Tracks a change when a module is deleted from a page + /// Tracks a change when a module is deleted from a page. /// - /// Module which tracks the change - /// Version number corresponding to the change - /// User Id who provokes the change + /// Module which tracks the change. + /// Version number corresponding to the change. + /// User Id who provokes the change. void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId); /// - /// Tracks a change when a module is copied from an exisitng page + /// Tracks a change when a module is copied from an exisitng page. /// - /// Module which tracks the change - /// Version number corresponding to the change - /// Tab Id where the module originally is - /// User Id who provokes the change + /// Module which tracks the change. + /// Version number corresponding to the change. + /// Tab Id where the module originally is. + /// User Id who provokes the change. void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); /// - /// Tracks a change when a copied module is deleted from an exisitng page + /// Tracks a change when a copied module is deleted from an exisitng page. /// - /// Module which tracks the change - /// Version number corresponding to the change - /// Tab Id where the module originally is - /// User Id who provokes the change + /// Module which tracks the change. + /// Version number corresponding to the change. + /// Tab Id where the module originally is. + /// User Id who provokes the change. void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); } } diff --git a/DNN Platform/Library/Entities/Tabs/ITabController.cs b/DNN Platform/Library/Entities/Tabs/ITabController.cs index d682aeec3ee..15297f65202 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabController.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabController.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -18,40 +18,44 @@ namespace DotNetNuke.Entities.Tabs public interface ITabController { /// - /// Adds localized copies of the page in all missing languages + /// Adds localized copies of the page in all missing languages. /// /// /// void AddMissingLanguages(int portalId, int tabId); /// - /// Adds a tab + /// Adds a tab. /// - /// The tab to be added - /// The tab is added to the end of the current Level. + /// The tab to be added. + /// The tab is added to the end of the current Level. + /// int AddTab(TabInfo tab); /// - /// Adds a tab + /// Adds a tab. /// - /// The tab to be added + /// The tab to be added. /// Flag that indicates whether to add the "AllTabs" - /// Modules - /// The tab is added to the end of the current Level. + /// Modules. + /// The tab is added to the end of the current Level. + /// int AddTab(TabInfo tab, bool includeAllTabsModules); /// - /// Adds a tab after the specified tab + /// Adds a tab after the specified tab. /// - /// The tab to be added - /// Id of the tab after which this tab is added + /// The tab to be added. + /// Id of the tab after which this tab is added. + /// int AddTabAfter(TabInfo tab, int afterTabId); /// - /// Adds a tab before the specified tab + /// Adds a tab before the specified tab. /// - /// The tab to be added - /// Id of the tab before which this tab is added + /// The tab to be added. + /// Id of the tab before which this tab is added. + /// int AddTabBefore(TabInfo objTab, int beforeTabId); /// @@ -62,14 +66,14 @@ public interface ITabController /// /// Converts one single tab to a neutral culture - /// clears the tab cache optionally + /// clears the tab cache optionally. /// /// /// /// /// void ConvertTabToNeutralLanguage(int portalId, int tabId, string cultureCode, bool clearCache); - + /// /// Creates content item for the tab.. /// @@ -87,21 +91,21 @@ public interface ITabController /// /// The original tab. /// The locale. - /// Clear the cache? + /// Clear the cache?. void CreateLocalizedCopy(TabInfo originalTab, Locale locale, bool clearCache); /// - /// Deletes a tab permanently from the database + /// Deletes a tab permanently from the database. /// - /// TabId of the tab to be deleted - /// PortalId of the portal + /// TabId of the tab to be deleted. + /// PortalId of the portal. /// /// The tab will not delete if it has child tab(s). /// void DeleteTab(int tabId, int portalId); /// - /// Deletes a tab permanently from the database + /// Deletes a tab permanently from the database. /// /// The tab id. /// The portal id. @@ -109,38 +113,39 @@ public interface ITabController void DeleteTab(int tabId, int portalId, bool deleteDescendants); /// - /// Delete a Setting of a tab instance + /// Delete a Setting of a tab instance. /// - /// ID of the affected tab - /// Name of the setting to be deleted + /// ID of the affected tab. + /// Name of the setting to be deleted. void DeleteTabSetting(int tabId, string settingName); /// - /// Delete all Settings of a tab instance + /// Delete all Settings of a tab instance. /// - /// ID of the affected tab + /// ID of the affected tab. void DeleteTabSettings(int tabId); /// - /// Delete a taburl + /// Delete a taburl. /// - /// the taburl - /// the portal - /// whether to clear the cache + /// the taburl. + /// the portal. + /// whether to clear the cache. void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache); /// /// Deletes all tabs for a specific language. Double checks if we are not deleting pages for the default language - /// Clears the tab cache optionally + /// Clears the tab cache optionally. /// /// /// - /// + /// + /// bool DeleteTranslatedTabs(int portalId, string cultureCode, bool clearCache); /// /// Reverts page culture back to Neutral (Null), to ensure a non localized site - /// clears the tab cache optionally + /// clears the tab cache optionally. /// /// /// @@ -148,19 +153,19 @@ public interface ITabController void EnsureNeutralLanguage(int portalId, string cultureCode, bool clearCache); /// - /// Get the list of skins per alias at tab level + /// Get the list of skins per alias at tab level. /// - /// the tab id - /// the portal id - /// list of TabAliasSkinInfo + /// the tab id. + /// the portal id. + /// list of TabAliasSkinInfo. List GetAliasSkins(int tabId, int portalId); /// - /// Get the list of custom aliases associated with a page (tab) + /// Get the list of custom aliases associated with a page (tab). /// - /// the tab id - /// the portal id - /// dictionary of tabid and aliases + /// the tab id. + /// the portal id. + /// dictionary of tabid and aliases. Dictionary GetCustomAliases(int tabId, int portalId); /// @@ -203,14 +208,14 @@ public interface ITabController /// Name of the tab. /// The portal id. /// The parent id. - /// tab info + /// tab info. TabInfo GetTabByName(string tabName, int portalId, int parentId); /// /// Gets the tabs which use the module. /// /// The module ID. - /// tab collection + /// tab collection. IDictionary GetTabsByModuleID(int moduleID); /// @@ -219,48 +224,47 @@ public interface ITabController /// The portal ID. /// The package ID. /// if set to true [for host]. - /// tab collection + /// tab collection. IDictionary GetTabsByPackageID(int portalID, int packageID, bool forHost); - + /// /// Gets the tabs by portal. /// /// The portal id. - /// tab collection + /// tab collection. TabCollection GetUserTabsByPortal(int portalId); - - + /// - /// Get the actual visible tabs for a given portal id. + /// Get the actual visible tabs for a given portal id. /// System Tabs and Admin Tabs are excluded from the result set. /// /// - /// - /// tab collection + /// + /// tab collection. TabCollection GetTabsByPortal(int portalId); /// /// Gets the tabs which use the module. /// /// The tabmodule ID. - /// tab collection + /// tab collection. IDictionary GetTabsByTabModuleID(int tabModuleId); - + /// - /// read all settings for a tab from TabSettings table + /// read all settings for a tab from TabSettings table. /// - /// ID of the Tab to query + /// ID of the Tab to query. /// - /// (cached) hashtable containing all settings + /// (cached) hashtable containing all settings. /// Hashtable GetTabSettings(int tabId); /// - /// Get the list of url's associated with a page (tab) + /// Get the list of url's associated with a page (tab). /// - /// the tab id - /// the portal id - /// list of urls associated with a tab + /// the tab id. + /// the portal id. + /// list of urls associated with a tab. List GetTabUrls(int tabId, int portalId); /// @@ -269,9 +273,9 @@ public interface ITabController /// The localized tab. /// The users. void GiveTranslatorRoleEditRights(TabInfo localizedTab, Dictionary users); - + /// - /// Returns True if a page is missing a translated version in at least one other language + /// Returns True if a page is missing a translated version in at least one other language. /// /// /// @@ -279,10 +283,10 @@ public interface ITabController bool HasMissingLanguages(int portalId, int tabId); /// - /// Checks whether the tab is published. Published means: view permissions of tab are identical to the DefaultLanguageTab + /// Checks whether the tab is published. Published means: view permissions of tab are identical to the DefaultLanguageTab. /// - /// The tab that is checked - /// true if tab is published + /// The tab that is checked. + /// true if tab is published. bool IsTabPublished(TabInfo publishTab); /// @@ -291,7 +295,7 @@ public interface ITabController /// The tab info. /// bool IsHostOrAdminPage(TabInfo tab); - + /// /// Localizes the tab. /// @@ -300,7 +304,7 @@ public interface ITabController void LocalizeTab(TabInfo originalTab, Locale locale); /// - /// Localizes the tab, with optional clear cache + /// Localizes the tab, with optional clear cache. /// /// /// @@ -322,7 +326,7 @@ public interface ITabController void MoveTabBefore(TabInfo tab, int beforeTabId); /// - /// Moves the tab to a new parent + /// Moves the tab to a new parent. /// /// The tab want to move. /// will move tab to this parent. @@ -343,23 +347,23 @@ public interface ITabController void PopulateBreadCrumbs(int portalID, ref ArrayList breadCrumbs, int tabID); /// - /// Publishes the tab. Set the VIEW permissions to All Users + /// Publishes the tab. Set the VIEW permissions to All Users. /// /// The publish tab. void PublishTab(TabInfo publishTab); /// - /// Publishes the tab. Set the VIEW permissions to All Users + /// Publishes the tab. Set the VIEW permissions to All Users. /// /// The tabs. void PublishTabs(List tabs); /// - /// It marks a page as published at least once + /// It marks a page as published at least once. /// - /// The Tab to be marked + /// The Tab to be marked. void MarkAsPublished(TabInfo tab); - + /// /// Restores the tab. /// @@ -368,11 +372,11 @@ public interface ITabController void RestoreTab(TabInfo tab, PortalSettings portalSettings); /// - /// Save url information for a page (tab) + /// Save url information for a page (tab). /// - /// the tab url - /// the portal id - /// whether to clear the cache + /// the tab url. + /// the portal id. + /// whether to clear the cache. void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache); /// @@ -390,12 +394,12 @@ public interface ITabController void UpdateTab(TabInfo updatedTab); /// - /// Adds or updates a tab's setting value + /// Adds or updates a tab's setting value. /// - /// ID of the tab to update - /// name of the setting property + /// ID of the tab to update. + /// name of the setting property. /// value of the setting (String). - /// empty SettingValue will remove the setting, if not preserveIfEmpty is true + /// empty SettingValue will remove the setting, if not preserveIfEmpty is true. void UpdateTabSetting(int tabId, string settingName, string settingValue); /// diff --git a/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs b/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs index 761df62f7fe..8dd0174c309 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs @@ -1,34 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + public interface ITabModulesController { /// - /// Returns an array of Modules well configured to be used into a Skin + /// Returns an array of Modules well configured to be used into a Skin. /// - /// TabInfo object + /// TabInfo object. + /// ArrayList GetTabModules(TabInfo tab); /// /// Gets a collection of all setting values of that contains the /// setting name in its collection of settings. /// - /// Name of the setting to look for + /// Name of the setting to look for. + /// Dictionary GetTabModuleSettingsByName(string settingName); /// /// Gets a collection of all ID's of that contains the setting name and /// specific value in its collection of settings. /// - /// Name of the setting to look for - /// Value of the setting to look for + /// Name of the setting to look for. + /// Value of the setting to look for. + /// IList GetTabModuleIdsBySetting(string settingName, string expectedValue); } } diff --git a/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs b/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs index eb67036b3fc..62f2abcd520 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs @@ -1,33 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using System; + public interface ITabPublishingController { /// /// Check if a page is published or not. /// - /// Tha tab Id - /// The portal ID where the tab is + /// Tha tab Id. + /// The portal ID where the tab is. + /// bool IsTabPublished(int tabID, int portalID); /// - /// Set a page as published or unpublished + /// Set a page as published or unpublished. /// - /// The tab ID - /// The portal ID where the tab is - /// A boolean value where True means the page is going to be published and otherwise unpublished + /// The tab ID. + /// The portal ID where the tab is. + /// A boolean value where True means the page is going to be published and otherwise unpublished. void SetTabPublishing(int tabID, int portalID, bool publish); /// - /// Check if Publish/Unpublish page actions can be performed + /// Check if Publish/Unpublish page actions can be performed. /// - /// The tab ID - /// The portal ID where the tab is + /// The tab ID. + /// The portal ID where the tab is. + /// bool CanPublishingBePerformed(int tabID, int portalID); } } diff --git a/DNN Platform/Library/Entities/Tabs/ITabWorkflowSettings.cs b/DNN Platform/Library/Entities/Tabs/ITabWorkflowSettings.cs index 68327a9b4b8..3409e6a4412 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabWorkflowSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabWorkflowSettings.cs @@ -1,58 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { /// - /// This interface is responsible to provide the tab workflow settings + /// This interface is responsible to provide the tab workflow settings. /// public interface ITabWorkflowSettings { /// - /// This method returns the default tab workflow of the portal + /// This method returns the default tab workflow of the portal. /// - /// Portal Id - /// If no default workflow is defined for a portal the method returns the Direct Publish system workflow - /// The workflow Id of the portal default workflow + /// Portal Id. + /// If no default workflow is defined for a portal the method returns the Direct Publish system workflow. + /// The workflow Id of the portal default workflow. int GetDefaultTabWorkflowId(int portalId); - + /// - /// This method sets the default workflow for a portal + /// This method sets the default workflow for a portal. /// - /// Portal Id - /// Workflow Id + /// Portal Id. + /// Workflow Id. void SetDefaultTabWorkflowId(int portalId, int workflowId); /// - /// This method enables or disables the tab workflow for the entire portal + /// This method enables or disables the tab workflow for the entire portal. /// - /// Portal Id - /// true for enable it, false for disable it + /// Portal Id. + /// true for enable it, false for disable it. void SetWorkflowEnabled(int portalId, bool enabled); /// - /// This method enables or disables the tab workflow for a specific tab + /// This method enables or disables the tab workflow for a specific tab. /// - /// Portal Id - /// Tab Id - /// true for enable it, false for disable it - /// this won't enable workflow of a tab if the tab workflow is disabled at portal level + /// Portal Id. + /// Tab Id. + /// true for enable it, false for disable it. + /// this won't enable workflow of a tab if the tab workflow is disabled at portal level. void SetWorkflowEnabled(int portalId, int tabId, bool enabled); /// - /// The method returns true if the workflow is enabled for a tab + /// The method returns true if the workflow is enabled for a tab. /// - /// Portal Id - /// Tab Id - /// True if the workflow is enabled, false otherwise + /// Portal Id. + /// Tab Id. + /// True if the workflow is enabled, false otherwise. bool IsWorkflowEnabled(int portalId, int tabId); /// - /// The method returns true is the workflow is enabled at portal level + /// The method returns true is the workflow is enabled at portal level. /// - /// Portal Id - /// True if the workflow is enabled, false otherwise + /// Portal Id. + /// True if the workflow is enabled, false otherwise. bool IsWorkflowEnabled(int portalId); } } diff --git a/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs b/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs index 95310939d5e..4cb6359980c 100644 --- a/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs +++ b/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { + using System; + public class PermissionsNotMetException : TabException { - public PermissionsNotMetException(int tabId, string message) : base(tabId, message) - { + public PermissionsNotMetException(int tabId, string message) + : base(tabId, message) + { } - } } diff --git a/DNN Platform/Library/Entities/Tabs/PortalAliasUsageType.cs b/DNN Platform/Library/Entities/Tabs/PortalAliasUsageType.cs index 8b6e6a5e2d1..82eefa6a2e1 100644 --- a/DNN Platform/Library/Entities/Tabs/PortalAliasUsageType.cs +++ b/DNN Platform/Library/Entities/Tabs/PortalAliasUsageType.cs @@ -1,13 +1,6 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { public enum PortalAliasUsageType @@ -15,6 +8,6 @@ public enum PortalAliasUsageType Default = 0, ChildPagesInherit = 1, ChildPagesDoNotInherit = 2, - InheritedFromParent = 3 + InheritedFromParent = 3, } } diff --git a/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs b/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs index cee64af408e..b39d71d24f4 100644 --- a/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs @@ -1,50 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { - /// - ///Class to represent a TabAliasSkinInfo object - /// + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + + /// + /// Class to represent a TabAliasSkinInfo object. + /// [Serializable] public class TabAliasSkinInfo : BaseEntityInfo, IHydratable - { - #region Public Properties - + { public int TabAliasSkinId { get; set; } + public string HttpAlias { get; set; } + public int PortalAliasId { get; set; } + public string SkinSrc { get; set; } - public int TabId { get; set; } - - #endregion - - public int KeyID - { - get { return TabAliasSkinId; } - set { TabAliasSkinId = value; } + + public int TabId { get; set; } + + public int KeyID + { + get { return this.TabAliasSkinId; } + set { this.TabAliasSkinId = value; } } public void Fill(IDataReader dr) { - base.FillInternal(dr); + this.FillInternal(dr); - TabAliasSkinId = Null.SetNullInteger(dr["TabAliasSkinId"]); - HttpAlias = Null.SetNullString(dr["HttpAlias"]); - PortalAliasId = Null.SetNullInteger(dr["PortalAliasId"]); - SkinSrc = Null.SetNullString(dr["SkinSrc"]); - TabId = Null.SetNullInteger(dr["TabId"]); + this.TabAliasSkinId = Null.SetNullInteger(dr["TabAliasSkinId"]); + this.HttpAlias = Null.SetNullString(dr["HttpAlias"]); + this.PortalAliasId = Null.SetNullInteger(dr["PortalAliasId"]); + this.SkinSrc = Null.SetNullString(dr["SkinSrc"]); + this.TabId = Null.SetNullInteger(dr["TabId"]); } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs b/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs index e00a472a7e9..f8220845720 100644 --- a/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs.Dto; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs.Dto; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Framework; + public class TabChangeSettings : ServiceLocator, ITabChangeSettings - { - - #region Public Methods + { public bool IsChangeControlEnabled(int portalId, int tabId) { if (portalId == Null.NullInteger) { return false; } - var isVersioningEnabled = TabVersionSettings.Instance.IsVersioningEnabled(portalId, tabId); + + var isVersioningEnabled = TabVersionSettings.Instance.IsVersioningEnabled(portalId, tabId); var isWorkflowEnable = TabWorkflowSettings.Instance.IsWorkflowEnabled(portalId, tabId); return isVersioningEnabled || isWorkflowEnable; } @@ -32,17 +32,13 @@ public ChangeControlState GetChangeControlState(int portalId, int tabId) PortalId = portalId, TabId = tabId, IsVersioningEnabledForTab = TabVersionSettings.Instance.IsVersioningEnabled(portalId, tabId), - IsWorkflowEnabledForTab = TabWorkflowSettings.Instance.IsWorkflowEnabled(portalId, tabId) + IsWorkflowEnabledForTab = TabWorkflowSettings.Instance.IsWorkflowEnabled(portalId, tabId), }; - } - - #endregion - - #region Service Locator + } + protected override Func GetFactory() { return () => new TabChangeSettings(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs b/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs index 8e685ceabfe..fd51404dd1c 100644 --- a/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + public class TabChangeTracker : ServiceLocator, ITabChangeTracker { public void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId) @@ -20,6 +21,7 @@ public void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId { TabVersionTracker.Instance.TrackModuleAddition(module, moduleVersion, userId); } + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(module.PortalID, module.TabID) && unPublishedVersion == null) { TabWorkflowTracker.Instance.TrackModuleAddition(module, moduleVersion, userId); @@ -30,8 +32,9 @@ public void TrackModuleModification(ModuleInfo module, int moduleVersion, int us { if (ModuleController.Instance.IsSharedModule(module) && moduleVersion != Null.NullInteger) { - throw new InvalidOperationException(Localization.GetExceptionMessage("ModuleDoesNotBelongToPage", - "This module does not belong to the page. Please, move to its master page to change the module")); + throw new InvalidOperationException(Localization.GetExceptionMessage( + "ModuleDoesNotBelongToPage", + "This module does not belong to the page. Please, move to its master page to change the module")); } var unPublishedVersion = TabVersionBuilder.Instance.GetUnPublishedVersion(module.TabID); @@ -45,7 +48,7 @@ public void TrackModuleModification(ModuleInfo module, int moduleVersion, int us TabWorkflowTracker.Instance.TrackModuleModification(module, moduleVersion, userId); } } - + public void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId) { var unPublishedVersion = TabVersionBuilder.Instance.GetUnPublishedVersion(module.TabID); @@ -53,28 +56,29 @@ public void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId { TabVersionTracker.Instance.TrackModuleDeletion(module, moduleVersion, userId); } + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(module.PortalID, module.TabID) && unPublishedVersion == null) { TabWorkflowTracker.Instance.TrackModuleDeletion(module, moduleVersion, userId); } } - + public void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId) { - if (module != null && TabChangeSettings.Instance.IsChangeControlEnabled(module.PortalID, module.TabID)) + if (module != null && TabChangeSettings.Instance.IsChangeControlEnabled(module.PortalID, module.TabID)) { TabVersionTracker.Instance.TrackModuleUncopy(module, moduleVersion, originalTabId, userId); - } + } } - + public void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId) { if (TabChangeSettings.Instance.IsChangeControlEnabled(module.PortalID, module.TabID)) { TabVersionTracker.Instance.TrackModuleCopy(module, moduleVersion, originalTabId, userId); - } + } } - + protected override Func GetFactory() { return () => new TabChangeTracker(); diff --git a/DNN Platform/Library/Entities/Tabs/TabCollection.cs b/DNN Platform/Library/Entities/Tabs/TabCollection.cs index efd51bb29a1..d5009f5ee78 100644 --- a/DNN Platform/Library/Entities/Tabs/TabCollection.cs +++ b/DNN Platform/Library/Entities/Tabs/TabCollection.cs @@ -1,123 +1,143 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Security; -using DotNetNuke.Collections; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.Serialization; + using System.Security; + + using DotNetNuke.Collections; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + /// - /// Represents the collection of Tabs for a portal + /// Represents the collection of Tabs for a portal. /// /// [Serializable] public class TabCollection : Dictionary { - //This is used to provide a collection of children + // This is used to provide a collection of children [NonSerialized] private readonly Dictionary> _children; - //This is used to return a sorted List + // This is used to return a sorted List [NonSerialized] private readonly List _list; - - //This is used to provide a culture based set of tabs - [NonSerialized] - private readonly Dictionary> _localizedTabs; - - #region Constructors + // This is used to provide a culture based set of tabs + [NonSerialized] + private readonly Dictionary> _localizedTabs; + public TabCollection() { - _list = new List(); - _children = new Dictionary>(); - _localizedTabs = new Dictionary>(); + this._list = new List(); + this._children = new Dictionary>(); + this._localizedTabs = new Dictionary>(); } // The special constructor is used to deserialize values. public TabCollection(SerializationInfo info, StreamingContext context) : base(info, context) { - _list = new List(); - _children = new Dictionary>(); - _localizedTabs = new Dictionary>(); + this._list = new List(); + this._children = new Dictionary>(); + this._localizedTabs = new Dictionary>(); } + public TabCollection(IEnumerable tabs) + : this() + { + this.AddRange(tabs); + } + public override void OnDeserialization(object sender) { base.OnDeserialization(sender); - foreach (var tab in Values) + foreach (var tab in this.Values) { - //Update all child collections - AddInternal(tab); + // Update all child collections + this.AddInternal(tab); } } - - public TabCollection(IEnumerable tabs) : this() + + public void Add(TabInfo tab) { - AddRange(tabs); + // Call base class to add to base Dictionary + this.Add(tab.TabID, tab); + + // Update all child collections + this.AddInternal(tab); } - #endregion + public void AddRange(IEnumerable tabs) + { + foreach (TabInfo tab in tabs) + { + this.Add(tab); + } + } - #region Private Methods + private static bool IsLocalizationEnabled() + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return (portalSettings != null) ? portalSettings.ContentLocalizationEnabled : Null.NullBoolean; + } + private static bool IsLocalizationEnabled(int portalId) + { + return PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalId, false); + } + private void AddInternal(TabInfo tab) { if (tab.ParentId == Null.NullInteger) { - //Add tab to Children collection - AddToChildren(tab); + // Add tab to Children collection + this.AddToChildren(tab); - //Add to end of List as all zero-level tabs are returned in order first - _list.Add(tab); + // Add to end of List as all zero-level tabs are returned in order first + this._list.Add(tab); } else { - //Find Parent in list - for (int index = 0; index <= _list.Count - 1; index++) + // Find Parent in list + for (int index = 0; index <= this._list.Count - 1; index++) { - TabInfo parentTab = _list[index]; + TabInfo parentTab = this._list[index]; if (parentTab.TabID == tab.ParentId) { - int childCount = AddToChildren(tab); + int childCount = this.AddToChildren(tab); - //Insert tab in master List - _list.Insert(index + childCount, tab); + // Insert tab in master List + this._list.Insert(index + childCount, tab); } } } - //Add to localized tabs + + // Add to localized tabs if (tab.PortalID == Null.NullInteger || IsLocalizationEnabled(tab.PortalID)) { - AddToLocalizedTabs(tab); - } + this.AddToLocalizedTabs(tab); + } } private int AddToChildren(TabInfo tab) { List childList; - if (!_children.TryGetValue(tab.ParentId, out childList)) + if (!this._children.TryGetValue(tab.ParentId, out childList)) { childList = new List(); - _children.Add(tab.ParentId, childList); + this._children.Add(tab.ParentId, childList); } - - //Add tab to end of child list as children are returned in order + + // Add tab to end of child list as children are returned in order childList.Add(tab); return childList.Count; } @@ -127,13 +147,13 @@ private void AddToLocalizedTabCollection(TabInfo tab, string cultureCode) List localizedTabCollection; var key = cultureCode.ToLowerInvariant(); - if (!_localizedTabs.TryGetValue(key, out localizedTabCollection)) + if (!this._localizedTabs.TryGetValue(key, out localizedTabCollection)) { localizedTabCollection = new List(); - _localizedTabs.Add(key, localizedTabCollection); + this._localizedTabs.Add(key, localizedTabCollection); } - //Add tab to end of localized tabs + // Add tab to end of localized tabs localizedTabCollection.Add(tab); } @@ -141,39 +161,39 @@ private void AddToLocalizedTabs(TabInfo tab) { if (string.IsNullOrEmpty(tab.CultureCode)) { - //Add to all cultures + // Add to all cultures foreach (var locale in LocaleController.Instance.GetLocales(tab.PortalID).Values) { - AddToLocalizedTabCollection(tab, locale.Code); + this.AddToLocalizedTabCollection(tab, locale.Code); } } else { - AddToLocalizedTabCollection(tab, tab.CultureCode); + this.AddToLocalizedTabCollection(tab, tab.CultureCode); } } private List GetDescendants(int tabId, int tabLevel) { var descendantTabs = new List(); - for (int index = 0; index <= _list.Count - 1; index++) + for (int index = 0; index <= this._list.Count - 1; index++) { - TabInfo parentTab = _list[index]; + TabInfo parentTab = this._list[index]; if (parentTab.TabID == tabId) { - //Found Parent - so add descendents - for (int descendantIndex = index + 1; descendantIndex <= _list.Count - 1; descendantIndex++) + // Found Parent - so add descendents + for (int descendantIndex = index + 1; descendantIndex <= this._list.Count - 1; descendantIndex++) { - TabInfo descendantTab = _list[descendantIndex]; + TabInfo descendantTab = this._list[descendantIndex]; - if ((tabLevel == Null.NullInteger)) + if (tabLevel == Null.NullInteger) { tabLevel = parentTab.Level; } if (descendantTab.Level > tabLevel) { - //Descendant so add to collection + // Descendant so add to collection descendantTabs.Add(descendantTab); } else @@ -181,163 +201,137 @@ private List GetDescendants(int tabId, int tabLevel) break; } } + break; } } + return descendantTabs; } - private static bool IsLocalizationEnabled() - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return (portalSettings != null) ? portalSettings.ContentLocalizationEnabled : Null.NullBoolean; - } - - private static bool IsLocalizationEnabled(int portalId) - { - return PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalId, false); - } - - #endregion - - #region Public Methods - - public void Add(TabInfo tab) - { - //Call base class to add to base Dictionary - Add(tab.TabID, tab); - - //Update all child collections - AddInternal(tab); - } - - public void AddRange(IEnumerable tabs) - { - foreach (TabInfo tab in tabs) - { - Add(tab); - } - } - public List AsList() { - return _list; + return this._list; } public List DescendentsOf(int tabId) { - return GetDescendants(tabId, Null.NullInteger); + return this.GetDescendants(tabId, Null.NullInteger); } public List DescendentsOf(int tabId, int originalTabLevel) { - return GetDescendants(tabId, originalTabLevel); + return this.GetDescendants(tabId, originalTabLevel); } public bool IsDescendentOf(int ancestorId, int testTabId) { - return DescendentsOf(ancestorId).Any(tab => tab.TabID == testTabId); + return this.DescendentsOf(ancestorId).Any(tab => tab.TabID == testTabId); } public ArrayList ToArrayList() { - return new ArrayList(_list); + return new ArrayList(this._list); } - public TabCollection WithCulture(string cultureCode, bool includeNeutral) - { - return WithCulture(cultureCode, includeNeutral, IsLocalizationEnabled()); - } + public TabCollection WithCulture(string cultureCode, bool includeNeutral) + { + return this.WithCulture(cultureCode, includeNeutral, IsLocalizationEnabled()); + } + public TabCollection WithCulture(string cultureCode, bool includeNeutral, bool localizationEnabled) { TabCollection collection; - if (localizationEnabled) + if (localizationEnabled) { if (string.IsNullOrEmpty(cultureCode)) { - //No culture passed in - so return all tabs + // No culture passed in - so return all tabs collection = this; } else { cultureCode = cultureCode.ToLowerInvariant(); List tabs; - if (!_localizedTabs.TryGetValue(cultureCode, out tabs)) + if (!this._localizedTabs.TryGetValue(cultureCode, out tabs)) { collection = new TabCollection(new List()); } else { - collection = !includeNeutral - ? new TabCollection(from t in tabs + collection = !includeNeutral + ? new TabCollection(from t in tabs where t.CultureCode.ToLowerInvariant() == cultureCode - select t) + select t) : new TabCollection(tabs); } } } else { - //Return all tabs + // Return all tabs collection = this; } + return collection; } public List WithParentId(int parentId) { List tabs; - if (!_children.TryGetValue(parentId, out tabs)) + if (!this._children.TryGetValue(parentId, out tabs)) { tabs = new List(); } + return tabs; } public TabInfo WithTabId(int tabId) { TabInfo t = null; - if (ContainsKey(tabId)) + if (this.ContainsKey(tabId)) { t = this[tabId]; } + return t; } public TabInfo WithTabNameAndParentId(string tabName, int parentId) { - return (from t in _list where t.TabName.Equals(tabName, StringComparison.InvariantCultureIgnoreCase) && t.ParentId == parentId select t).SingleOrDefault(); + return (from t in this._list where t.TabName.Equals(tabName, StringComparison.InvariantCultureIgnoreCase) && t.ParentId == parentId select t).SingleOrDefault(); } public TabInfo WithTabName(string tabName) { - return (from t in _list where !string.IsNullOrEmpty(t.TabName) && t.TabName.Equals(tabName, StringComparison.InvariantCultureIgnoreCase) select t).FirstOrDefault(); + return (from t in this._list where !string.IsNullOrEmpty(t.TabName) && t.TabName.Equals(tabName, StringComparison.InvariantCultureIgnoreCase) select t).FirstOrDefault(); } internal void RefreshCache(int tabId, TabInfo updatedTab) { - if (ContainsKey(tabId)) + if (this.ContainsKey(tabId)) { - if (updatedTab == null) //the tab has been deleted + if (updatedTab == null) // the tab has been deleted { - Remove(tabId); - _list.RemoveAll(t => t.TabID == tabId); - _localizedTabs.ForEach(kvp => + this.Remove(tabId); + this._list.RemoveAll(t => t.TabID == tabId); + this._localizedTabs.ForEach(kvp => { kvp.Value.RemoveAll(t => t.TabID == tabId); }); - _children.Remove(tabId); + this._children.Remove(tabId); } else { this[tabId] = updatedTab; - var index = _list.FindIndex(t => t.TabID == tabId); + var index = this._list.FindIndex(t => t.TabID == tabId); if (index > Null.NullInteger) { - _list[index] = updatedTab; + this._list[index] = updatedTab; } - _localizedTabs.ForEach(kvp => + this._localizedTabs.ForEach(kvp => { var localizedIndex = kvp.Value.FindIndex(t => t.TabID == tabId); if (localizedIndex > Null.NullInteger) @@ -347,8 +341,6 @@ internal void RefreshCache(int tabId, TabInfo updatedTab) }); } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabController.cs b/DNN Platform/Library/Entities/Tabs/TabController.cs index d7669a71c9b..0bd83530206 100644 --- a/DNN Platform/Library/Entities/Tabs/TabController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabController.cs @@ -1,46 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs.Actions; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs.Actions; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Search.Entities; + /// /// TabController provides all operation to tabinfo. /// @@ -49,19 +44,19 @@ namespace DotNetNuke.Entities.Tabs /// Tabs will be a sitemap for a poatal, and every request at first need to check whether there is valid tab information /// include in the url, if not it will use default tab to display information. /// - public partial class TabController : ServiceLocator , ITabController + public partial class TabController : ServiceLocator, ITabController { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabController)); + private static readonly Regex TabNameCheck1 = new Regex("^LPT[1-9]$|^COM[1-9]$", RegexOptions.IgnoreCase); + private static readonly Regex TabNameCheck2 = new Regex("^AUX$|^CON$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$|^LOGIN$|^REGISTER$", RegexOptions.IgnoreCase); + + private readonly DataProvider _dataProvider = DataProvider.Instance(); + protected override Func GetFactory() { return () => new TabController(); } - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabController)); - private readonly DataProvider _dataProvider = DataProvider.Instance(); - - private static readonly Regex TabNameCheck1 = new Regex("^LPT[1-9]$|^COM[1-9]$", RegexOptions.IgnoreCase); - private static readonly Regex TabNameCheck2 = new Regex("^AUX$|^CON$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$|^LOGIN$|^REGISTER$", RegexOptions.IgnoreCase); - /// /// Gets the current page in current http request. /// @@ -75,47 +70,164 @@ public static TabInfo CurrentPage { tab = PortalController.Instance.GetCurrentPortalSettings().ActiveTab; } + return tab; } } - #region Private Methods - private bool IsAdminTab(TabInfo tab) + /// + /// Copies the design to children. + /// + /// The parent tab. + /// The skin SRC. + /// The container SRC. + public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc) { - var portal = PortalController.Instance.GetPortal(tab.PortalID); - return portal.AdminTabId == tab.TabID || IsAdminTabRecursive(tab, portal.AdminTabId); + CopyDesignToChildren(parentTab, skinSrc, containerSrc, + PortalController.GetActivePortalLanguage(parentTab.PortalID)); } - private bool IsAdminTabRecursive(TabInfo tab, int adminTabId) + /// + /// Copies the design to children. + /// + /// The parent tab. + /// The skin SRC. + /// The container SRC. + /// The culture code. + public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc, string cultureCode) { - if (tab.ParentId == Null.NullInteger) + bool clearCache = Null.NullBoolean; + List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); + foreach (TabInfo tab in childTabs) { - return false; + if (TabPermissionController.CanAdminPage(tab)) + { + // Update ContentItem If neccessary + if (tab.ContentItemId == Null.NullInteger && tab.TabID != Null.NullInteger) + { + Instance.CreateContentItem(tab); + } + + DataProvider.Instance().UpdateTab( + tab.TabID, + tab.ContentItemId, + tab.PortalID, + tab.VersionGuid, + tab.DefaultLanguageGuid, + tab.LocalizedVersionGuid, + tab.TabName, + tab.IsVisible, + tab.DisableLink, + tab.ParentId, + tab.IconFileRaw, + tab.IconFileLargeRaw, + tab.Title, + tab.Description, + tab.KeyWords, + tab.IsDeleted, + tab.Url, + skinSrc, + containerSrc, + tab.StartDate, + tab.EndDate, + tab.RefreshInterval, + tab.PageHeadText, + tab.IsSecure, + tab.PermanentRedirect, + tab.SiteMapPriority, + UserController.Instance.GetCurrentUserInfo().UserID, + tab.CultureCode, + tab.IsSystem); + + UpdateTabVersion(tab.TabID); + + EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, + EventLogController.EventLogType.TAB_UPDATED); + clearCache = true; + } } - if (tab.ParentId == adminTabId) + if (clearCache) { - return true; + DataCache.ClearTabsCache(childTabs[0].PortalID); } + } - var parentTab = GetTab(tab.ParentId, tab.PortalID); - return IsAdminTabRecursive(parentTab, adminTabId); + /// + /// Adds localized copies of the page in all missing languages. + /// + /// + /// + public void AddMissingLanguages(int portalId, int tabId) + { + var currentTab = this.GetTab(tabId, portalId, false); + if (currentTab.CultureCode != null) + { + var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); + var workingTab = currentTab; + if (workingTab.CultureCode != defaultLocale.Code && workingTab.DefaultLanguageTab == null) + { + // we are adding missing languages to a single culture page that is not in the default language + // so we must first add a page in the default culture + this.CreateLocalizedCopyInternal(workingTab, defaultLocale, false, true, insertAfterOriginal: true); + } + + if (currentTab.DefaultLanguageTab != null) + { + workingTab = currentTab.DefaultLanguageTab; + } + + foreach (Locale locale in LocaleController.Instance.GetLocales(portalId).Values) + { + if (!LocaleController.Instance.IsDefaultLanguage(locale.Code)) + { + bool missing = true; + foreach (var localizedTab in workingTab.LocalizedTabs.Values.Where(localizedTab => localizedTab.CultureCode == locale.Code)) + { + missing = false; + } + + if (missing) + { + this.CreateLocalizedCopyInternal(workingTab, locale, false, true, insertAfterOriginal: true); + } + } + } + } } - private bool IsHostTab(TabInfo tab) + /// + /// Adds a tab. + /// + /// The tab to be added. + /// The tab is added to the end of the current Level. + /// + public int AddTab(TabInfo tab) { - return tab.PortalID == Null.NullInteger; + return this.AddTab(tab, true); } + internal Dictionary> GetTabUrls(int portalId) + { + string cacheKey = string.Format(DataCache.TabUrlCacheKey, portalId); + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabUrlCacheTimeOut, + DataCache.TabUrlCachePriority, + portalId), + this.GetTabUrlsCallback); + } private static void AddAllTabsModules(TabInfo tab) { var portalSettings = new PortalSettings(tab.TabID, tab.PortalID); foreach (ModuleInfo allTabsModule in ModuleController.Instance.GetAllTabsModules(tab.PortalID, true)) { - //[DNN-6276]We need to check that the Module is not implicitly deleted. ie If all instances are on Pages - //that are all "deleted" then even if the Module itself is not deleted, we would not expect the - //Module to be added + // [DNN-6276]We need to check that the Module is not implicitly deleted. ie If all instances are on Pages + // that are all "deleted" then even if the Module itself is not deleted, we would not expect the + // Module to be added var canAdd = (from ModuleInfo allTabsInstance in ModuleController.Instance.GetTabModulesByModule(allTabsModule.ModuleID) select Instance.GetTab(allTabsInstance.TabID, tab.PortalID, false)).Any( t => !t.IsDeleted) && (!portalSettings.ContentLocalizationEnabled || allTabsModule.CultureCode == tab.CultureCode); @@ -126,27 +238,135 @@ private static void AddAllTabsModules(TabInfo tab) } } + private static void DeserializeTabSettings(XmlNodeList nodeTabSettings, TabInfo objTab) + { + foreach (XmlNode oTabSettingNode in nodeTabSettings) + { + string sKey = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingname"); + string sValue = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingvalue"); + objTab.TabSettings[sKey] = sValue; + } + } + + private static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, TabInfo tab, bool isAdminTemplate) + { + var permissionController = new PermissionController(); + int permissionID = 0; + foreach (XmlNode tabPermissionNode in nodeTabPermissions) + { + string permissionKey = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissionkey"); + string permissionCode = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissioncode"); + string roleName = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "rolename"); + bool allowAccess = XmlUtils.GetNodeValueBoolean(tabPermissionNode, "allowaccess"); + ArrayList arrPermissions = permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); + int i; + for (i = 0; i <= arrPermissions.Count - 1; i++) + { + var permission = (PermissionInfo)arrPermissions[i]; + permissionID = permission.PermissionID; + } + + int roleID = int.MinValue; + switch (roleName) + { + case Globals.glbRoleAllUsersName: + roleID = Convert.ToInt32(Globals.glbRoleAllUsers); + break; + case Globals.glbRoleUnauthUserName: + roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); + break; + default: + var portal = PortalController.Instance.GetPortal(tab.PortalID); + var role = RoleController.Instance.GetRole( + portal.PortalID, + r => r.RoleName == roleName); + if (role != null) + { + roleID = role.RoleID; + } + else + { + if (isAdminTemplate && roleName.ToLowerInvariant() == "administrators") + { + roleID = portal.AdministratorRoleId; + } + } + + break; + } + + if (roleID != int.MinValue) + { + var tabPermission = new TabPermissionInfo + { + TabID = tab.TabID, + PermissionID = permissionID, + RoleID = roleID, + UserID = Null.NullInteger, + AllowAccess = allowAccess, + }; + + bool canAdd = !tab.TabPermissions.Cast() + .Any(tp => tp.TabID == tabPermission.TabID + && tp.PermissionID == tabPermission.PermissionID + && tp.RoleID == tabPermission.RoleID + && tp.UserID == tabPermission.UserID); + if (canAdd) + { + tab.TabPermissions.Add(tabPermission); + } + } + } + } + + private bool IsAdminTab(TabInfo tab) + { + var portal = PortalController.Instance.GetPortal(tab.PortalID); + return portal.AdminTabId == tab.TabID || this.IsAdminTabRecursive(tab, portal.AdminTabId); + } + + private bool IsAdminTabRecursive(TabInfo tab, int adminTabId) + { + if (tab.ParentId == Null.NullInteger) + { + return false; + } + + if (tab.ParentId == adminTabId) + { + return true; + } + + var parentTab = this.GetTab(tab.ParentId, tab.PortalID); + return this.IsAdminTabRecursive(parentTab, adminTabId); + } + + private bool IsHostTab(TabInfo tab) + { + return tab.PortalID == Null.NullInteger; + } + private int AddTabInternal(TabInfo tab, int afterTabId, int beforeTabId, bool includeAllTabsModules) { ValidateTabPath(tab); - //First create ContentItem as we need the ContentItemID - CreateContentItem(tab); + // First create ContentItem as we need the ContentItemID + this.CreateContentItem(tab); - //Add Tab + // Add Tab if (afterTabId > 0) { - tab.TabID = _dataProvider.AddTabAfter(tab, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); + tab.TabID = this._dataProvider.AddTabAfter(tab, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); } else { tab.TabID = beforeTabId > 0 - ? _dataProvider.AddTabBefore(tab, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID) - : _dataProvider.AddTabToEnd(tab, UserController.Instance.GetCurrentUserInfo().UserID); + ? this._dataProvider.AddTabBefore(tab, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID) + : this._dataProvider.AddTabToEnd(tab, UserController.Instance.GetCurrentUserInfo().UserID); } - //Clear the Cache - ClearCache(tab.PortalID); + // Clear the Cache + this.ClearCache(tab.PortalID); ITermController termController = Util.GetTermController(); termController.RemoveTermsFromContent(tab); @@ -156,31 +376,31 @@ private int AddTabInternal(TabInfo tab, int afterTabId, int beforeTabId, bool in } EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, - "", EventLogController.EventLogType.TAB_CREATED); + string.Empty, EventLogController.EventLogType.TAB_CREATED); - //Add Tab Permissions + // Add Tab Permissions TabPermissionController.SaveTabPermissions(tab); - //Add TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist + // Add TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist try { - UpdateTabSettings(ref tab); + this.UpdateTabSettings(ref tab); } catch (Exception ex) { Exceptions.LogException(ex); } - //Add AllTabs Modules + // Add AllTabs Modules if (includeAllTabsModules && tab.PortalID != Null.NullInteger) { AddAllTabsModules(tab); } - //Check Tab Versioning + // Check Tab Versioning if (tab.PortalID == Null.NullInteger || !TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID, tab.TabID)) { - MarkAsPublished(tab); + this.MarkAsPublished(tab); } EventManager.Instance.OnTabCreated(new TabEventArgs { Tab = tab }); @@ -190,126 +410,126 @@ private int AddTabInternal(TabInfo tab, int afterTabId, int beforeTabId, bool in private void CreateLocalizedCopyInternal(TabInfo originalTab, Locale locale, bool allTabsModulesFromDefault, bool clearCache, bool insertAfterOriginal = false) { - try - { - Logger.TraceFormat("Localizing TabId: {0}, TabPath: {1}, Locale: {2}", originalTab.TabID, originalTab.TabPath, locale.Code); - var defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); - - //First Clone the Tab - TabInfo localizedCopy = originalTab.Clone(); - localizedCopy.TabID = Null.NullInteger; - localizedCopy.StateID = Null.NullInteger; - localizedCopy.ContentItemId = Null.NullInteger; - - //Set Guids and Culture Code - localizedCopy.UniqueId = Guid.NewGuid(); - localizedCopy.VersionGuid = Guid.NewGuid(); - localizedCopy.LocalizedVersionGuid = Guid.NewGuid(); - localizedCopy.CultureCode = locale.Code; - localizedCopy.TabName = localizedCopy.TabName + " (" + locale.Code + ")"; - - //copy page tags - foreach (var term in originalTab.Terms) - { - localizedCopy.Terms.Add(term); - } + try + { + Logger.TraceFormat("Localizing TabId: {0}, TabPath: {1}, Locale: {2}", originalTab.TabID, originalTab.TabPath, locale.Code); + var defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); + + // First Clone the Tab + TabInfo localizedCopy = originalTab.Clone(); + localizedCopy.TabID = Null.NullInteger; + localizedCopy.StateID = Null.NullInteger; + localizedCopy.ContentItemId = Null.NullInteger; + + // Set Guids and Culture Code + localizedCopy.UniqueId = Guid.NewGuid(); + localizedCopy.VersionGuid = Guid.NewGuid(); + localizedCopy.LocalizedVersionGuid = Guid.NewGuid(); + localizedCopy.CultureCode = locale.Code; + localizedCopy.TabName = localizedCopy.TabName + " (" + locale.Code + ")"; + + // copy page tags + foreach (var term in originalTab.Terms) + { + localizedCopy.Terms.Add(term); + } if (locale == defaultLocale) - { - originalTab.DefaultLanguageGuid = localizedCopy.UniqueId; - UpdateTab(originalTab); - } - else - { - localizedCopy.DefaultLanguageGuid = originalTab.UniqueId; - } - - //Copy Permissions from original Tab for Admins only - //If original tab is user tab or its parent tab is user tab, then copy full permission - //from original tab. - PortalInfo portal = PortalController.Instance.GetPortal(originalTab.PortalID); - if (originalTab.TabID == portal.UserTabId || originalTab.ParentId == portal.UserTabId) - { - localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions); - } - else - { - localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions.Where(p => p.RoleID == portal.AdministratorRoleId)); - } - - //Get the original Tabs Parent - //check the original whether have parent. - if (!Null.IsNull(originalTab.ParentId)) - { - TabInfo originalParent = GetTab(originalTab.ParentId, originalTab.PortalID, false); - - //Get the localized parent - TabInfo localizedParent = GetTabByCulture(originalParent.TabID, originalParent.PortalID, locale); + { + originalTab.DefaultLanguageGuid = localizedCopy.UniqueId; + this.UpdateTab(originalTab); + } + else + { + localizedCopy.DefaultLanguageGuid = originalTab.UniqueId; + } + + // Copy Permissions from original Tab for Admins only + // If original tab is user tab or its parent tab is user tab, then copy full permission + // from original tab. + PortalInfo portal = PortalController.Instance.GetPortal(originalTab.PortalID); + if (originalTab.TabID == portal.UserTabId || originalTab.ParentId == portal.UserTabId) + { + localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions); + } + else + { + localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions.Where(p => p.RoleID == portal.AdministratorRoleId)); + } + + // Get the original Tabs Parent + // check the original whether have parent. + if (!Null.IsNull(originalTab.ParentId)) + { + TabInfo originalParent = this.GetTab(originalTab.ParentId, originalTab.PortalID, false); + + // Get the localized parent + TabInfo localizedParent = this.GetTabByCulture(originalParent.TabID, originalParent.PortalID, locale); localizedCopy.ParentId = localizedParent.TabID; } - //Save Tab + // Save Tab var afterTabId = insertAfterOriginal ? originalTab.TabID : -1; const int beforeTabId = -1; const bool includeAllModules = false; - AddTabInternal(localizedCopy, afterTabId, beforeTabId, includeAllModules); //not include modules show on all page, it will handled in copy modules action. + this.AddTabInternal(localizedCopy, afterTabId, beforeTabId, includeAllModules); // not include modules show on all page, it will handled in copy modules action. - //if the tab has custom stylesheet defined, then also copy the stylesheet to the localized version. - if (originalTab.TabSettings.ContainsKey("CustomStylesheet")) - { - UpdateTabSetting(localizedCopy.TabID, "CustomStylesheet", originalTab.TabSettings["CustomStylesheet"].ToString()); - } + // if the tab has custom stylesheet defined, then also copy the stylesheet to the localized version. + if (originalTab.TabSettings.ContainsKey("CustomStylesheet")) + { + this.UpdateTabSetting(localizedCopy.TabID, "CustomStylesheet", originalTab.TabSettings["CustomStylesheet"].ToString()); + } - /* Tab versioning and workflow is disabled - * during the creation of the Localized copy - */ + /* Tab versioning and workflow is disabled + * during the creation of the Localized copy + */ DisableTabVersioningAndWorkflow(localizedCopy); - //Make shallow copies of all modules - ModuleController.Instance.CopyModules(originalTab, localizedCopy, true, allTabsModulesFromDefault); - - //Convert these shallow copies to deep copies - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(localizedCopy.TabID)) - { - ModuleController.Instance.LocalizeModule(kvp.Value, locale); - } - - //if not copy modules which show on all pages from default language, we need add all modules in current culture. - if (!allTabsModulesFromDefault) - { - AddAllTabsModules(localizedCopy); - } - - //Add Translator Role - GiveTranslatorRoleEditRights(localizedCopy, null); - - /* Tab versioning and workflow is re-enabled - * when the Localized copy is created - */ - EnableTabVersioningAndWorkflow(localizedCopy); - MarkAsPublished(localizedCopy); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - throw; - } - - //Clear the Cache - if (clearCache) - { - ClearCache(originalTab.PortalID); - } + // Make shallow copies of all modules + ModuleController.Instance.CopyModules(originalTab, localizedCopy, true, allTabsModulesFromDefault); + + // Convert these shallow copies to deep copies + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(localizedCopy.TabID)) + { + ModuleController.Instance.LocalizeModule(kvp.Value, locale); + } + + // if not copy modules which show on all pages from default language, we need add all modules in current culture. + if (!allTabsModulesFromDefault) + { + AddAllTabsModules(localizedCopy); + } + + // Add Translator Role + this.GiveTranslatorRoleEditRights(localizedCopy, null); + + /* Tab versioning and workflow is re-enabled + * when the Localized copy is created + */ + EnableTabVersioningAndWorkflow(localizedCopy); + this.MarkAsPublished(localizedCopy); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + throw; + } + + // Clear the Cache + if (clearCache) + { + this.ClearCache(originalTab.PortalID); + } } private void ClearTabSettingsCache(int tabId) { var portalId = GetPortalId(tabId, -1); - string cacheKey = String.Format(DataCache.TabSettingsCacheKey, portalId); + string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); DataCache.RemoveCache(cacheKey); - //aslo clear the settings from tab object in cache. - var tab = GetTab(tabId, portalId, false); + // aslo clear the settings from tab object in cache. + var tab = this.GetTab(tabId, portalId, false); if (tab != null) { tab.ClearSettingsCache(); @@ -320,16 +540,15 @@ private void CreateTabRedirect(TabInfo tab) { var settings = PortalController.Instance.GetCurrentPortalSettings(); - if (settings != null && tab.TabID != settings.HomeTabId && tab.TabUrls.Count(u => u.HttpStatus == "200") == 0) { var domainRoot = TestableGlobals.Instance.AddHTTP(settings.PortalAlias.HTTPAlias); - if (!String.IsNullOrEmpty(domainRoot)) + if (!string.IsNullOrEmpty(domainRoot)) { var url = TestableGlobals.Instance.NavigateURL(tab.TabID); - url = url.Replace(domainRoot, ""); + url = url.Replace(domainRoot, string.Empty); var seqNum = (tab.TabUrls.Count > 0) ? tab.TabUrls.Max(t => t.SeqNum) + 1 : 1; var tabUrl = new TabUrlInfo @@ -339,128 +558,71 @@ private void CreateTabRedirect(TabInfo tab) PortalAliasId = -1, PortalAliasUsage = PortalAliasUsageType.Default, Url = url, - QueryString = String.Empty, + QueryString = string.Empty, CultureCode = tab.CultureCode, HttpStatus = "301", - IsSystem = true + IsSystem = true, }; - SaveTabUrl(tabUrl, tab.PortalID, false); + this.SaveTabUrl(tabUrl, tab.PortalID, false); } } } private void CreateTabRedirects(TabInfo tab) { - CreateTabRedirect(tab); + this.CreateTabRedirect(tab); - var descendants = GetTabsByPortal(tab.PortalID).DescendentsOf(tab.TabID); + var descendants = this.GetTabsByPortal(tab.PortalID).DescendentsOf(tab.TabID); - //Create Redirect for descendant tabs + // Create Redirect for descendant tabs foreach (TabInfo descendantTab in descendants) { - CreateTabRedirect(descendantTab); + this.CreateTabRedirect(descendantTab); } } - private static void DeserializeTabSettings(XmlNodeList nodeTabSettings, TabInfo objTab) + private static void DeserializeTabUrls(XmlNode nodeTabUrl, TabUrlInfo objTabUrl) { - foreach (XmlNode oTabSettingNode in nodeTabSettings) - { - string sKey = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingname"); - string sValue = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingvalue"); - objTab.TabSettings[sKey] = sValue; - } + objTabUrl.SeqNum = XmlUtils.GetAttributeValueAsInteger(nodeTabUrl.CreateNavigator(), "SeqNum", 0); + objTabUrl.Url = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url")) ? "/" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url"); + objTabUrl.QueryString = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "QueryString"); + objTabUrl.CultureCode = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "CultureCode"); + objTabUrl.HttpStatus = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus")) ? "200" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus"); + objTabUrl.IsSystem = XmlUtils.GetAttributeValueAsBoolean(nodeTabUrl.CreateNavigator(), "IsSystem", true); + objTabUrl.PortalAliasId = Null.NullInteger; + objTabUrl.PortalAliasUsage = PortalAliasUsageType.Default; } - private static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, TabInfo tab, bool isAdminTemplate) + private static int GetIndexOfTab(TabInfo objTab, IEnumerable tabs) { - var permissionController = new PermissionController(); - int permissionID = 0; - foreach (XmlNode tabPermissionNode in nodeTabPermissions) + return Null.NullInteger + tabs.TakeWhile(tab => tab.TabID != objTab.TabID).Count(); + } + + private static int GetPortalId(int tabId, int portalId) + { + if (Null.IsNull(portalId)) { - string permissionKey = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissionkey"); - string permissionCode = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissioncode"); - string roleName = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "rolename"); - bool allowAccess = XmlUtils.GetNodeValueBoolean(tabPermissionNode, "allowaccess"); - ArrayList arrPermissions = permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); - int i; - for (i = 0; i <= arrPermissions.Count - 1; i++) - { - var permission = (PermissionInfo)arrPermissions[i]; - permissionID = permission.PermissionID; - } - int roleID = int.MinValue; - switch (roleName) - { - case Globals.glbRoleAllUsersName: - roleID = Convert.ToInt32(Globals.glbRoleAllUsers); - break; - case Globals.glbRoleUnauthUserName: - roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); - break; - default: - var portal = PortalController.Instance.GetPortal(tab.PortalID); - var role = RoleController.Instance.GetRole(portal.PortalID, - r => r.RoleName == roleName); - if (role != null) - { - roleID = role.RoleID; - } - else - { - if (isAdminTemplate && roleName.ToLowerInvariant() == "administrators") - { - roleID = portal.AdministratorRoleId; - } - } - break; - } - if (roleID != int.MinValue) + Dictionary portalDic = PortalController.GetPortalDictionary(); + if (portalDic != null && portalDic.ContainsKey(tabId)) { - var tabPermission = new TabPermissionInfo - { - TabID = tab.TabID, - PermissionID = permissionID, - RoleID = roleID, - UserID = Null.NullInteger, - AllowAccess = allowAccess - }; - - bool canAdd = !tab.TabPermissions.Cast() - .Any(tp => tp.TabID == tabPermission.TabID - && tp.PermissionID == tabPermission.PermissionID - && tp.RoleID == tabPermission.RoleID - && tp.UserID == tabPermission.UserID); - if (canAdd) - { - tab.TabPermissions.Add(tabPermission); - } + portalId = portalDic[tabId]; } } - } - private static void DeserializeTabUrls(XmlNode nodeTabUrl, TabUrlInfo objTabUrl) - { - objTabUrl.SeqNum = XmlUtils.GetAttributeValueAsInteger(nodeTabUrl.CreateNavigator(), "SeqNum", 0); - objTabUrl.Url = String.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url")) ? "/" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url") ; - objTabUrl.QueryString = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "QueryString"); - objTabUrl.CultureCode = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "CultureCode"); - objTabUrl.HttpStatus = String.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus")) ? "200" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus"); - objTabUrl.IsSystem = XmlUtils.GetAttributeValueAsBoolean(nodeTabUrl.CreateNavigator(), "IsSystem", true); - objTabUrl.PortalAliasId = Null.NullInteger; - objTabUrl.PortalAliasUsage = PortalAliasUsageType.Default; + return portalId; } - + private Dictionary> GetAliasSkins(int portalId) { string cacheKey = string.Format(DataCache.TabAliasSkinCacheKey, portalId); - return CBO.GetCachedObject>>(new CacheItemArgs(cacheKey, - DataCache.TabAliasSkinCacheTimeOut, - DataCache.TabAliasSkinCachePriority, - portalId), - GetAliasSkinsCallback); - + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabAliasSkinCacheTimeOut, + DataCache.TabAliasSkinCachePriority, + portalId), + this.GetAliasSkinsCallback); } private object GetAliasSkinsCallback(CacheItemArgs cacheItemArgs) @@ -474,21 +636,21 @@ private object GetAliasSkinsCallback(CacheItemArgs cacheItemArgs) { while (dr.Read()) { - //fill business object + // fill business object var tabAliasSkin = CBO.FillObject(dr, false); - //add Tab Alias Skin to dictionary + // add Tab Alias Skin to dictionary if (dic.ContainsKey(tabAliasSkin.TabId)) { - //Add Tab Alias Skin to Tab Alias Skin Collection already in dictionary for TabId + // Add Tab Alias Skin to Tab Alias Skin Collection already in dictionary for TabId dic[tabAliasSkin.TabId].Add(tabAliasSkin); } else { - //Create new Tab Alias Skin Collection for TabId + // Create new Tab Alias Skin Collection for TabId var collection = new List { tabAliasSkin }; - //Add Collection to Dictionary + // Add Collection to Dictionary dic.Add(tabAliasSkin.TabId, collection); } } @@ -499,22 +661,24 @@ private object GetAliasSkinsCallback(CacheItemArgs cacheItemArgs) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } } + return dic; } private Dictionary> GetCustomAliases(int portalId) { string cacheKey = string.Format(DataCache.TabCustomAliasCacheKey, portalId); - return CBO.GetCachedObject>>(new CacheItemArgs(cacheKey, - DataCache.TabCustomAliasCacheTimeOut, - DataCache.TabCustomAliasCachePriority, - portalId), - GetCustomAliasesCallback); - + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabCustomAliasCacheTimeOut, + DataCache.TabCustomAliasCachePriority, + portalId), + this.GetCustomAliasesCallback); } private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) @@ -528,23 +692,23 @@ private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) { while (dr.Read()) { - //fill business object + // fill business object var tabId = (int)dr["TabId"]; var customAlias = (string)dr["httpAlias"]; var cultureCode = (string)dr["cultureCode"]; - //add Custom Alias to dictionary + // add Custom Alias to dictionary if (dic.ContainsKey(tabId)) { - //Add Custom Alias to Custom Alias Collection already in dictionary for TabId + // Add Custom Alias to Custom Alias Collection already in dictionary for TabId dic[tabId][cultureCode] = customAlias; } else { - //Create new Custom Alias Collection for TabId + // Create new Custom Alias Collection for TabId var collection = new Dictionary { { cultureCode, customAlias } }; - //Add Collection to Dictionary + // Add Collection to Dictionary dic.Add(tabId, collection); } } @@ -555,34 +719,12 @@ private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } } - return dic; - } - - private static int GetIndexOfTab(TabInfo objTab, IEnumerable tabs) - { - return Null.NullInteger + tabs.TakeWhile(tab => tab.TabID != objTab.TabID).Count(); - } - private static int GetPortalId(int tabId, int portalId) - { - if (Null.IsNull(portalId)) - { - Dictionary portalDic = PortalController.GetPortalDictionary(); - if (portalDic != null && portalDic.ContainsKey(tabId)) - { - portalId = portalDic[tabId]; - } - } - return portalId; - } - - private IEnumerable GetSiblingTabs(TabInfo objTab) - { - return GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); + return dic; } private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) @@ -606,19 +748,47 @@ private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) { CBO.CloseDataReader(dr, true); } + return tabpathDic; } + private static void UpdateTabVersion(int tabId) + { + DataProvider.Instance().UpdateTabVersion(tabId, Guid.NewGuid()); + } + + private static void ValidateTabPath(TabInfo tab) + { + string tabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); + int tabId = GetTabByTabPath(tab.PortalID, tabPath, tab.CultureCode); + if (tabId > Null.NullInteger) + { + // Tab exists so Throw + throw new TabExistsException( + tabId, + string.Format( + "Page Exists in portal: {0}, path: {1}, culture: {2}", + tab.PortalID, tab.TabPath, tab.CultureCode)); + } + } + + private IEnumerable GetSiblingTabs(TabInfo objTab) + { + return this.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); + } + private Dictionary GetTabSettingsByPortal(int portalId) { - string cacheKey = String.Format(DataCache.TabSettingsCacheKey, portalId); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.TabCacheTimeOut, - DataCache.TabCachePriority), - c => + string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.TabCacheTimeOut, + DataCache.TabCachePriority), + c => { var tabSettings = new Dictionary(); - using (var dr = _dataProvider.GetTabSettings(portalId)) + using (var dr = this._dataProvider.GetTabSettings(portalId)) { while (dr.Read()) { @@ -636,25 +806,15 @@ private Dictionary GetTabSettingsByPortal(int portalId) } else { - settings[dr.GetString(1)] = ""; + settings[dr.GetString(1)] = string.Empty; } } } + return tabSettings; }); } - internal Dictionary> GetTabUrls(int portalId) - { - string cacheKey = string.Format(DataCache.TabUrlCacheKey, portalId); - return CBO.GetCachedObject>>(new CacheItemArgs(cacheKey, - DataCache.TabUrlCacheTimeOut, - DataCache.TabUrlCachePriority, - portalId), - GetTabUrlsCallback); - - } - private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) { var portalID = (int)cacheItemArgs.ParamList[0]; @@ -667,21 +827,21 @@ private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) { while (dr.Read()) { - //fill business object + // fill business object var tabRedirect = CBO.FillObject(dr, false); - //add Tab Redirect to dictionary + // add Tab Redirect to dictionary if (dic.ContainsKey(tabRedirect.TabId)) { - //Add Tab Redirect to Tab Redirect Collection already in dictionary for TabId + // Add Tab Redirect to Tab Redirect Collection already in dictionary for TabId dic[tabRedirect.TabId].Add(tabRedirect); } else { - //Create new Tab Redirect Collection for TabId + // Create new Tab Redirect Collection for TabId var collection = new List { tabRedirect }; - //Add Collection to Dictionary + // Add Collection to Dictionary dic.Add(tabRedirect.TabId, collection); } } @@ -692,42 +852,44 @@ private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } } + return dic; } private void HardDeleteTabInternal(int tabId, int portalId) { - //Delete all tabModule Instances + // Delete all tabModule Instances foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabId).Values) { ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, false); } - var tab = GetTab(tabId, portalId, false); + var tab = this.GetTab(tabId, portalId, false); - //Delete Tab - _dataProvider.DeleteTab(tabId); + // Delete Tab + this._dataProvider.DeleteTab(tabId); - //Log deletion - EventLogController.Instance.AddLog("TabID", - tabId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.TAB_DELETED); + // Log deletion + EventLogController.Instance.AddLog( + "TabID", + tabId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.TAB_DELETED); // queue remove tab/page from search index var document = new SearchDocumentToDelete { - TabId = tabId + TabId = tabId, }; DataProvider.Instance().AddSearchDeletedItems(document); - //Remove the Content Item + // Remove the Content Item if (tab != null && tab.ContentItemId > Null.NullInteger) { IContentController contentController = Util.GetContentController(); @@ -742,12 +904,13 @@ private bool SoftDeleteChildTabs(int intTabid, PortalSettings portalSettings) bool bDeleted = true; foreach (TabInfo objtab in GetTabsByParent(intTabid, portalSettings.PortalId)) { - bDeleted = SoftDeleteTabInternal(objtab, portalSettings); + bDeleted = this.SoftDeleteTabInternal(objtab, portalSettings); if (!bDeleted) { break; } } + return bDeleted; } @@ -756,7 +919,8 @@ private bool SoftDeleteTabInternal(TabInfo tabToDelete, PortalSettings portalSet Dto.ChangeControlState changeControlStateForTab = null; if (tabToDelete.PortalID > -1) { - changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState(tabToDelete.PortalID, + changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState( + tabToDelete.PortalID, tabToDelete.TabID); if (changeControlStateForTab.IsChangeControlEnabledForTab) { @@ -768,17 +932,17 @@ private bool SoftDeleteTabInternal(TabInfo tabToDelete, PortalSettings portalSet var deleted = false; if (!IsSpecialTab(tabToDelete.TabID, portalSettings)) { - if (SoftDeleteChildTabs(tabToDelete.TabID, portalSettings)) + if (this.SoftDeleteChildTabs(tabToDelete.TabID, portalSettings)) { tabToDelete.IsDeleted = true; - UpdateTab(tabToDelete); + this.UpdateTab(tabToDelete); foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabToDelete.TabID).Values) { ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, true); } - EventLogController.Instance.AddLog(tabToDelete, portalSettings, portalSettings.UserId, "", + EventLogController.Instance.AddLog(tabToDelete, portalSettings, portalSettings.UserId, string.Empty, EventLogController.EventLogType.TAB_SENT_TO_RECYCLE_BIN); deleted = true; @@ -797,34 +961,37 @@ private bool SoftDeleteTabInternal(TabInfo tabToDelete, PortalSettings portalSet private void UpdateTabSettingInternal(int tabId, string settingName, string settingValue, bool clearCache) { - using (var dr = _dataProvider.GetTabSetting(tabId, settingName)) + using (var dr = this._dataProvider.GetTabSetting(tabId, settingName)) { if (dr.Read()) { if (dr.GetString(0) != settingValue) { - _dataProvider.UpdateTabSetting(tabId, settingName, settingValue, + this._dataProvider.UpdateTabSetting(tabId, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.AddSettingLog(EventLogController.EventLogType.TAB_SETTING_UPDATED, + EventLogController.AddSettingLog( + EventLogController.EventLogType.TAB_SETTING_UPDATED, "TabId", tabId, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); } } else { - _dataProvider.UpdateTabSetting(tabId, settingName, settingValue, + this._dataProvider.UpdateTabSetting(tabId, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.AddSettingLog(EventLogController.EventLogType.TAB_SETTING_CREATED, + EventLogController.AddSettingLog( + EventLogController.EventLogType.TAB_SETTING_CREATED, "TabId", tabId, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); } + dr.Close(); } UpdateTabVersion(tabId); if (clearCache) { - ClearTabSettingsCache(tabId); + this.ClearTabSettingsCache(tabId); } } @@ -833,25 +1000,7 @@ private void UpdateTabSettings(ref TabInfo updatedTab) foreach (string sKeyLoopVariable in updatedTab.TabSettings.Keys) { string sKey = sKeyLoopVariable; - UpdateTabSettingInternal(updatedTab.TabID, sKey, Convert.ToString(updatedTab.TabSettings[sKey]), false); - } - } - - private static void UpdateTabVersion(int tabId) - { - DataProvider.Instance().UpdateTabVersion(tabId, Guid.NewGuid()); - } - - private static void ValidateTabPath(TabInfo tab) - { - string tabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); - int tabId = GetTabByTabPath(tab.PortalID, tabPath, tab.CultureCode); - if (tabId > Null.NullInteger) - { - //Tab exists so Throw - throw new TabExistsException(tabId, - string.Format("Page Exists in portal: {0}, path: {1}, culture: {2}", - tab.PortalID, tab.TabPath, tab.CultureCode)); + this.UpdateTabSettingInternal(updatedTab.TabID, sKey, Convert.ToString(updatedTab.TabSettings[sKey]), false); } } @@ -870,110 +1019,55 @@ private void UpdateContentItem(TabInfo tab) } } - #endregion - - #region Public Methods - - /// - /// Adds localized copies of the page in all missing languages - /// - /// - /// - public void AddMissingLanguages(int portalId, int tabId) - { - var currentTab = GetTab(tabId, portalId, false); - if (currentTab.CultureCode != null) - { - var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); - var workingTab = currentTab; - if (workingTab.CultureCode != defaultLocale.Code && workingTab.DefaultLanguageTab == null) - { - // we are adding missing languages to a single culture page that is not in the default language - // so we must first add a page in the default culture - - CreateLocalizedCopyInternal(workingTab, defaultLocale, false, true, insertAfterOriginal: true); - } - - if (currentTab.DefaultLanguageTab != null) - { - workingTab = currentTab.DefaultLanguageTab; - } - - foreach (Locale locale in LocaleController.Instance.GetLocales(portalId).Values) - { - if (!LocaleController.Instance.IsDefaultLanguage(locale.Code)) - { - bool missing = true; - foreach (var localizedTab in workingTab.LocalizedTabs.Values.Where(localizedTab => localizedTab.CultureCode == locale.Code)) - { - missing = false; - } - if (missing) - { - CreateLocalizedCopyInternal(workingTab, locale, false, true, insertAfterOriginal: true); - } - } - } - - } - } - - /// - /// Adds a tab - /// - /// The tab to be added - /// The tab is added to the end of the current Level. - public int AddTab(TabInfo tab) - { - return AddTab(tab, true); - } - /// - /// Adds a tab + /// Adds a tab. /// - /// The tab to be added + /// The tab to be added. /// Flag that indicates whether to add the "AllTabs" - /// Modules + /// Modules. /// The tab is added to the end of the current Level. + /// public int AddTab(TabInfo tab, bool includeAllTabsModules) { - //Add tab to store - int tabID = AddTabInternal(tab, -1, -1, includeAllTabsModules); + // Add tab to store + int tabID = this.AddTabInternal(tab, -1, -1, includeAllTabsModules); - //Clear the Cache - ClearCache(tab.PortalID); + // Clear the Cache + this.ClearCache(tab.PortalID); return tabID; } /// - /// Adds a tab after the specified tab + /// Adds a tab after the specified tab. /// - /// The tab to be added - /// Id of the tab after which this tab is added + /// The tab to be added. + /// Id of the tab after which this tab is added. + /// public int AddTabAfter(TabInfo tab, int afterTabId) { - //Add tab to store - int tabID = AddTabInternal(tab, afterTabId, -1, true); + // Add tab to store + int tabID = this.AddTabInternal(tab, afterTabId, -1, true); - //Clear the Cache - ClearCache(tab.PortalID); + // Clear the Cache + this.ClearCache(tab.PortalID); return tabID; } /// - /// Adds a tab before the specified tab + /// Adds a tab before the specified tab. /// - /// The tab to be added - /// Id of the tab before which this tab is added + /// The tab to be added. + /// Id of the tab before which this tab is added. + /// public int AddTabBefore(TabInfo objTab, int beforeTabId) { - //Add tab to store - int tabID = AddTabInternal(objTab, -1, beforeTabId, true); + // Add tab to store + int tabID = this.AddTabInternal(objTab, -1, beforeTabId, true); - //Clear the Cache - ClearCache(objTab.PortalID); + // Clear the Cache + this.ClearCache(objTab.PortalID); return tabID; } @@ -986,7 +1080,7 @@ public void ClearCache(int portalId) { DataCache.ClearTabsCache(portalId); - //Clear the Portal cache so the Pages count is correct + // Clear the Portal cache so the Pages count is correct DataCache.ClearPortalCache(portalId, false); DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); @@ -996,17 +1090,17 @@ public void ClearCache(int portalId) public void RefreshCache(int portalId, int tabId) { - var portalTabs = GetTabsByPortal(portalId); + var portalTabs = this.GetTabsByPortal(portalId); if (portalTabs.WithTabId(tabId) != null) { - var updateTab = GetTab(tabId, portalId, true); + var updateTab = this.GetTab(tabId, portalId, true); portalTabs.RefreshCache(tabId, updateTab); } } /// /// Converts one single tab to a neutral culture - /// clears the tab cache optionally + /// clears the tab cache optionally. /// /// /// @@ -1014,24 +1108,23 @@ public void RefreshCache(int portalId, int tabId) /// public void ConvertTabToNeutralLanguage(int portalId, int tabId, string cultureCode, bool clearCache) { - //parent tabs can not be deleted - if (GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) + // parent tabs can not be deleted + if (this.GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) { // delete all translated / localized tabs for this tab - var tab = GetTab(tabId, portalId, true); + var tab = this.GetTab(tabId, portalId, true); foreach (var localizedTab in tab.LocalizedTabs.Values) { - HardDeleteTabInternal(localizedTab.TabID, portalId); + this.HardDeleteTabInternal(localizedTab.TabID, portalId); } // reset culture of current tab back to neutral - _dataProvider.ConvertTabToNeutralLanguage(portalId, tabId, cultureCode); + this._dataProvider.ConvertTabToNeutralLanguage(portalId, tabId, cultureCode); if (clearCache) { - ClearCache(portalId); + this.ClearCache(portalId); } } - } /// @@ -1040,15 +1133,16 @@ public void ConvertTabToNeutralLanguage(int portalId, int tabId, string cultureC /// The updated tab. public void CreateContentItem(TabInfo tab) { - //First create ContentItem as we need the ContentItemID + // First create ContentItem as we need the ContentItemID ContentType contentType = ContentType.Tab; IContentController contentController = Util.GetContentController(); - tab.Content = String.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; + tab.Content = string.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; if (contentType != null) { tab.ContentTypeId = contentType.ContentTypeId; } + tab.Indexed = false; contentController.AddContentItem(tab); } @@ -1064,7 +1158,7 @@ public void CreateLocalizedCopies(TabInfo originalTab) { if (subLocale.Code != defaultLocale.Code) { - CreateLocalizedCopyInternal(originalTab, subLocale, false, true); + this.CreateLocalizedCopyInternal(originalTab, subLocale, false, true); } } } @@ -1074,136 +1168,142 @@ public void CreateLocalizedCopies(TabInfo originalTab) /// /// The original tab. /// The locale. - /// Clear the cache? + /// Clear the cache?. public void CreateLocalizedCopy(TabInfo originalTab, Locale locale, bool clearCache) { - CreateLocalizedCopyInternal(originalTab, locale, true, clearCache); - } - - private static void EnableTabVersioningAndWorkflow(TabInfo tab) - { - if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) - { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, true); - } - if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) - { - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, true); - } - } - - private static void DisableTabVersioningAndWorkflow(TabInfo tab) - { - if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) - { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); - } - if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) - { - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); - } + this.CreateLocalizedCopyInternal(originalTab, locale, true, clearCache); } /// - /// Deletes a tab permanently from the database + /// Deletes a tab permanently from the database. /// - /// TabId of the tab to be deleted - /// PortalId of the portal + /// TabId of the tab to be deleted. + /// PortalId of the portal. /// /// The tab will not delete if it has child tab(s). /// public void DeleteTab(int tabId, int portalId) { - //parent tabs can not be deleted - if (GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) + // parent tabs can not be deleted + if (this.GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) { - HardDeleteTabInternal(tabId, portalId); + this.HardDeleteTabInternal(tabId, portalId); } - ClearCache(portalId); + + this.ClearCache(portalId); } /// - /// Deletes a tab permanently from the database + /// Deletes a tab permanently from the database. /// /// The tab id. /// The portal id. /// if set to true will delete all child tabs. public void DeleteTab(int tabId, int portalId, bool deleteDescendants) { - List descendantList = GetTabsByPortal(portalId).DescendentsOf(tabId); + List descendantList = this.GetTabsByPortal(portalId).DescendentsOf(tabId); if (deleteDescendants && descendantList.Count > 0) { - //Iterate through descendants from bottom - which will remove children first + // Iterate through descendants from bottom - which will remove children first for (int i = descendantList.Count - 1; i >= 0; i += -1) { - HardDeleteTabInternal(descendantList[i].TabID, portalId); + this.HardDeleteTabInternal(descendantList[i].TabID, portalId); } } - DeleteTab(tabId, portalId); + + this.DeleteTab(tabId, portalId); + } + + private static void EnableTabVersioningAndWorkflow(TabInfo tab) + { + if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, true); + } + + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) + { + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, true); + } + } + + private static void DisableTabVersioningAndWorkflow(TabInfo tab) + { + if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); + } + + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) + { + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); + } } /// - /// Delete a Setting of a tab instance + /// Delete a Setting of a tab instance. /// - /// ID of the affected tab - /// Name of the setting to be deleted + /// ID of the affected tab. + /// Name of the setting to be deleted. public void DeleteTabSetting(int tabId, string settingName) { - _dataProvider.DeleteTabSetting(tabId, settingName); - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.TAB_SETTING_DELETED.ToString()}; + this._dataProvider.DeleteTabSetting(tabId, settingName); + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TAB_SETTING_DELETED.ToString() }; log.LogProperties.Add(new LogDetailInfo("TabID", tabId.ToString())); log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); LogController.Instance.AddLog(log); UpdateTabVersion(tabId); - ClearTabSettingsCache(tabId); + this.ClearTabSettingsCache(tabId); } /// - /// Delete all Settings of a tab instance + /// Delete all Settings of a tab instance. /// - /// ID of the affected tab + /// ID of the affected tab. public void DeleteTabSettings(int tabId) { - _dataProvider.DeleteTabSettings(tabId); - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.TAB_SETTING_DELETED.ToString()}; + this._dataProvider.DeleteTabSettings(tabId); + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TAB_SETTING_DELETED.ToString() }; log.LogProperties.Add(new LogDetailInfo("TabId", tabId.ToString())); LogController.Instance.AddLog(log); UpdateTabVersion(tabId); - ClearTabSettingsCache(tabId); + this.ClearTabSettingsCache(tabId); } /// - /// Delete a taburl + /// Delete a taburl. /// - /// the taburl - /// the portal - /// whether to clear the cache + /// the taburl. + /// the portal. + /// whether to clear the cache. public void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) { DataProvider.Instance().DeleteTabUrl(tabUrl.TabId, tabUrl.SeqNum); - EventLogController.Instance.AddLog("tabUrl.TabId", - tabUrl.TabId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.TABURL_DELETED); + EventLogController.Instance.AddLog( + "tabUrl.TabId", + tabUrl.TabId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.TABURL_DELETED); if (clearCache) { - DataCache.RemoveCache(String.Format(DataCache.TabUrlCacheKey, portalId)); + DataCache.RemoveCache(string.Format(DataCache.TabUrlCacheKey, portalId)); CacheController.ClearCustomAliasesCache(); - var tab = GetTab(tabUrl.TabId, portalId); + var tab = this.GetTab(tabUrl.TabId, portalId); tab.ClearTabUrls(); } } /// /// Deletes all tabs for a specific language. Double checks if we are not deleting pages for the default language - /// Clears the tab cache optionally + /// Clears the tab cache optionally. /// /// /// /// + /// public bool DeleteTranslatedTabs(int portalId, string cultureCode, bool clearCache) { if (PortalController.Instance.GetCurrentPortalSettings() != null) @@ -1211,75 +1311,77 @@ public bool DeleteTranslatedTabs(int portalId, string cultureCode, bool clearCac var defaultLanguage = PortalController.Instance.GetCurrentPortalSettings().DefaultLanguage; if (cultureCode != defaultLanguage) { - _dataProvider.DeleteTranslatedTabs(portalId, cultureCode); + this._dataProvider.DeleteTranslatedTabs(portalId, cultureCode); if (clearCache) { - ClearCache(portalId); + this.ClearCache(portalId); } - } } + return true; } /// /// Reverts page culture back to Neutral (Null), to ensure a non localized site - /// clears the tab cache optionally + /// clears the tab cache optionally. /// /// /// /// public void EnsureNeutralLanguage(int portalId, string cultureCode, bool clearCache) { - _dataProvider.EnsureNeutralLanguage(portalId, cultureCode); + this._dataProvider.EnsureNeutralLanguage(portalId, cultureCode); if (clearCache) { - ClearCache(portalId); + this.ClearCache(portalId); } } /// - /// Get the list of skins per alias at tab level + /// Get the list of skins per alias at tab level. /// - /// the tab id - /// the portal id - /// list of TabAliasSkinInfo + /// the tab id. + /// the portal id. + /// list of TabAliasSkinInfo. public List GetAliasSkins(int tabId, int portalId) { - //Get the Portal AliasSkin Dictionary - Dictionary> dicTabAliases = GetAliasSkins(portalId); + // Get the Portal AliasSkin Dictionary + Dictionary> dicTabAliases = this.GetAliasSkins(portalId); - //Get the Collection from the Dictionary + // Get the Collection from the Dictionary List tabAliases; bool bFound = dicTabAliases.TryGetValue(tabId, out tabAliases); if (!bFound) { - //Return empty collection + // Return empty collection tabAliases = new List(); } + return tabAliases; } /// - /// Get the list of custom aliases associated with a page (tab) + /// Get the list of custom aliases associated with a page (tab). /// - /// the tab id - /// the portal id - /// dictionary of tabid and aliases + /// the tab id. + /// the portal id. + /// dictionary of tabid and aliases. public Dictionary GetCustomAliases(int tabId, int portalId) { - //Get the Portal CustomAlias Dictionary - Dictionary> dicCustomAliases = GetCustomAliases(portalId); + // Get the Portal CustomAlias Dictionary + Dictionary> dicCustomAliases = this.GetCustomAliases(portalId); - //Get the Collection from the Dictionary + // Get the Collection from the Dictionary Dictionary customAliases; bool bFound = dicCustomAliases.TryGetValue(tabId, out customAliases); if (!bFound) { - //Return empty collection + // Return empty collection customAliases = new Dictionary(); } + return customAliases; } @@ -1291,7 +1393,7 @@ public Dictionary GetCustomAliases(int tabId, int portalId) /// tab info. public TabInfo GetTab(int tabId, int portalId) { - return GetTab(tabId, portalId, false); + return this.GetTab(tabId, portalId, false); } /// @@ -1311,29 +1413,29 @@ public TabInfo GetTab(int tabId, int portalId, bool ignoreCache) } else if (ignoreCache || Host.Host.PerformanceSetting == Globals.PerformanceSettings.NoCaching) { - //if we are using the cache - tab = CBO.FillObject(_dataProvider.GetTab(tabId)); + // if we are using the cache + tab = CBO.FillObject(this._dataProvider.GetTab(tabId)); } else { - //if we do not know the PortalId then try to find it in the Portals Dictionary using the TabId + // if we do not know the PortalId then try to find it in the Portals Dictionary using the TabId portalId = GetPortalId(tabId, portalId); - //if we have the PortalId then try to get the TabInfo object - tab = GetTabsByPortal(portalId).WithTabId(tabId) ?? - GetTabsByPortal(GetPortalId(tabId, Null.NullInteger)).WithTabId(tabId); + // if we have the PortalId then try to get the TabInfo object + tab = this.GetTabsByPortal(portalId).WithTabId(tabId) ?? + this.GetTabsByPortal(GetPortalId(tabId, Null.NullInteger)).WithTabId(tabId); if (tab == null) { - //recheck the info directly from database to make sure we can avoid error if the cache doesn't update + // recheck the info directly from database to make sure we can avoid error if the cache doesn't update // correctly, this may occurred when install is set up in web farm. - tab = CBO.FillObject(_dataProvider.GetTab(tabId)); + tab = CBO.FillObject(this._dataProvider.GetTab(tabId)); // if tab is not null means that the cache doesn't update correctly, we need clear the cache // and let it rebuild cache when request next time. if (tab != null) { - ClearCache(tab.PortalID); + this.ClearCache(tab.PortalID); } else { @@ -1355,21 +1457,21 @@ public TabInfo GetTab(int tabId, int portalId, bool ignoreCache) public TabInfo GetTabByCulture(int tabId, int portalId, Locale locale) { TabInfo localizedTab = null; - TabCollection tabs = GetTabsByPortal(portalId); + TabCollection tabs = this.GetTabsByPortal(portalId); - //Get Tab specified by Id + // Get Tab specified by Id TabInfo originalTab = tabs.WithTabId(tabId); if (locale != null && originalTab != null) { - //Check if tab is in the requested culture + // Check if tab is in the requested culture if (string.IsNullOrEmpty(originalTab.CultureCode) || originalTab.CultureCode == locale.Code) { localizedTab = originalTab; } else { - //See if tab exists for culture + // See if tab exists for culture if (originalTab.IsDefaultLanguage) { originalTab.LocalizedTabs.TryGetValue(locale.Code, out localizedTab); @@ -1385,8 +1487,9 @@ public TabInfo GetTabByCulture(int tabId, int portalId, Locale locale) else { if ( - !originalTab.DefaultLanguageTab.LocalizedTabs.TryGetValue(locale.Code, - out localizedTab)) + !originalTab.DefaultLanguageTab.LocalizedTabs.TryGetValue( + locale.Code, + out localizedTab)) { localizedTab = originalTab.DefaultLanguageTab; } @@ -1395,6 +1498,7 @@ public TabInfo GetTabByCulture(int tabId, int portalId, Locale locale) } } } + return localizedTab; } @@ -1406,7 +1510,7 @@ public TabInfo GetTabByCulture(int tabId, int portalId, Locale locale) /// tab info. public TabInfo GetTabByName(string tabName, int portalId) { - return GetTabsByPortal(portalId).WithTabName(tabName); + return this.GetTabsByPortal(portalId).WithTabName(tabName); } /// @@ -1415,30 +1519,30 @@ public TabInfo GetTabByName(string tabName, int portalId) /// Name of the tab. /// The portal id. /// The parent id. - /// tab info + /// tab info. public TabInfo GetTabByName(string tabName, int portalId, int parentId) { - return GetTabsByPortal(portalId).WithTabNameAndParentId(tabName, parentId); + return this.GetTabsByPortal(portalId).WithTabNameAndParentId(tabName, parentId); } /// /// Gets the tabs which use the module. /// /// The module ID. - /// tab collection + /// tab collection. public IDictionary GetTabsByModuleID(int moduleID) { - return CBO.FillDictionary("TabID", _dataProvider.GetTabsByModuleID(moduleID)); + return CBO.FillDictionary("TabID", this._dataProvider.GetTabsByModuleID(moduleID)); } /// /// Gets the tabs which use the module. /// /// The tabmodule ID. - /// tab collection + /// tab collection. public IDictionary GetTabsByTabModuleID(int tabModuleId) { - return CBO.FillDictionary("TabID", _dataProvider.GetTabsByTabModuleID(tabModuleId)); + return CBO.FillDictionary("TabID", this._dataProvider.GetTabsByTabModuleID(tabModuleId)); } /// @@ -1447,40 +1551,42 @@ public IDictionary GetTabsByTabModuleID(int tabModuleId) /// The portal ID. /// The package ID. /// if set to true [for host]. - /// tab collection + /// tab collection. public IDictionary GetTabsByPackageID(int portalID, int packageID, bool forHost) { - return CBO.FillDictionary("TabID", _dataProvider.GetTabsByPackageID(portalID, packageID, forHost)); + return CBO.FillDictionary("TabID", this._dataProvider.GetTabsByPackageID(portalID, packageID, forHost)); } /// /// Gets the tabs by portal. /// /// The portal id. - /// tab collection + /// tab collection. public TabCollection GetTabsByPortal(int portalId) { string cacheKey = string.Format(DataCache.TabCacheKey, portalId); - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, - DataCache.TabCacheTimeOut, - DataCache.TabCachePriority), - c => + return CBO.GetCachedObject( + new CacheItemArgs( + cacheKey, + DataCache.TabCacheTimeOut, + DataCache.TabCachePriority), + c => { - List tabs = CBO.FillCollection(_dataProvider.GetTabs(portalId)); + List tabs = CBO.FillCollection(this._dataProvider.GetTabs(portalId)); return new TabCollection(tabs); }); } /// - /// Get the actual visible tabs for a given portal id. + /// Get the actual visible tabs for a given portal id. /// System Tabs and Admin Tabs are excluded from the result set. /// /// - /// + /// /// public TabCollection GetUserTabsByPortal(int portalId) { - var tabs = GetTabsByPortal(portalId); + var tabs = this.GetTabsByPortal(portalId); var portal = PortalController.Instance.GetPortal(portalId); IEnumerable filteredList = from tab in tabs @@ -1493,42 +1599,44 @@ public TabCollection GetUserTabsByPortal(int portalId) } /// - /// read all settings for a tab from TabSettings table + /// read all settings for a tab from TabSettings table. /// - /// ID of the Tab to query + /// ID of the Tab to query. /// - /// (cached) hashtable containing all settings + /// (cached) hashtable containing all settings. /// public Hashtable GetTabSettings(int tabId) { var portalId = GetPortalId(tabId, -1); Hashtable settings; - if (!GetTabSettingsByPortal(portalId).TryGetValue(tabId, out settings)) + if (!this.GetTabSettingsByPortal(portalId).TryGetValue(tabId, out settings)) { settings = new Hashtable(); } + return settings; } /// - /// Get the list of url's associated with a page (tab) + /// Get the list of url's associated with a page (tab). /// - /// the tab id - /// the portal id - /// list of urls associated with a tab + /// the tab id. + /// the portal id. + /// list of urls associated with a tab. public List GetTabUrls(int tabId, int portalId) { - //Get the Portal TabUrl Dictionary - Dictionary> dicTabUrls = GetTabUrls(portalId); + // Get the Portal TabUrl Dictionary + Dictionary> dicTabUrls = this.GetTabUrls(portalId); - //Get the Collection from the Dictionary + // Get the Collection from the Dictionary List tabRedirects; bool bFound = dicTabUrls.TryGetValue(tabId, out tabRedirects); if (!bFound) { - //Return empty collection + // Return empty collection tabRedirects = new List(); } + return tabRedirects; } @@ -1542,7 +1650,7 @@ public void GiveTranslatorRoleEditRights(TabInfo localizedTab, Dictionary r.RoleName == roleName); + RoleInfo role = RoleController.Instance.GetRole( + localizedTab.PortalID, + r => r.RoleName == roleName); if (role != null) { TabPermissionInfo perm = @@ -1566,15 +1675,15 @@ public void GiveTranslatorRoleEditRights(TabInfo localizedTab, Dictionary tp.RoleID == role.RoleID && tp.PermissionKey == "EDIT").SingleOrDefault(); if (perm == null) { - //Create Permission + // Create Permission var tabTranslatePermission = new TabPermissionInfo(translatePermisison) { RoleID = role.RoleID, AllowAccess = true, - RoleName = roleName + RoleName = roleName, }; localizedTab.TabPermissions.Add(tabTranslatePermission); - UpdateTab(localizedTab); + this.UpdateTab(localizedTab); } } } @@ -1582,14 +1691,14 @@ public void GiveTranslatorRoleEditRights(TabInfo localizedTab, Dictionary - /// Returns True if a page is missing a translated version in at least one other language + /// Returns True if a page is missing a translated version in at least one other language. /// /// /// /// public bool HasMissingLanguages(int portalId, int tabId) { - var currentTab = GetTab(tabId, portalId, false); + var currentTab = this.GetTab(tabId, portalId, false); var workingTab = currentTab; var locales = LocaleController.Instance.GetLocales(portalId); var LocaleCount = locales.Count; @@ -1602,19 +1711,19 @@ public bool HasMissingLanguages(int portalId, int tabId) locales.Values.Where(locale => !LocaleController.Instance.IsDefaultLanguage(locale.Code)) .Count(locale => workingTab.LocalizedTabs.Values.Any(localizedTab => localizedTab.CultureCode == locale.Code)); - return ((LocaleCount - localizedCount) != 0); - + return (LocaleCount - localizedCount) != 0; } /// - /// Checks whether the tab is published. Published means: view permissions of tab are identical to the DefaultLanguageTab + /// Checks whether the tab is published. Published means: view permissions of tab are identical to the DefaultLanguageTab. /// - /// The tab that is checked - /// true if tab is published + /// The tab that is checked. + /// true if tab is published. public bool IsTabPublished(TabInfo publishTab) { bool returnValue = true; - //To publish a subsidiary language tab we need to enable the View Permissions + + // To publish a subsidiary language tab we need to enable the View Permissions if (publishTab != null && publishTab.DefaultLanguageTab != null) { foreach (TabPermissionInfo perm in @@ -1634,6 +1743,7 @@ public bool IsTabPublished(TabInfo publishTab) } } } + return returnValue; } @@ -1644,21 +1754,21 @@ public bool IsTabPublished(TabInfo publishTab) /// The locale. public void LocalizeTab(TabInfo originalTab, Locale locale) { - LocalizeTab(originalTab, locale, true); + this.LocalizeTab(originalTab, locale, true); } /// - /// Localizes the tab, with optional clear cache + /// Localizes the tab, with optional clear cache. /// /// /// /// public void LocalizeTab(TabInfo originalTab, Locale locale, bool clearCache) { - _dataProvider.LocalizeTab(originalTab.TabID, locale.Code, UserController.Instance.GetCurrentUserInfo().UserID); + this._dataProvider.LocalizeTab(originalTab.TabID, locale.Code, UserController.Instance.GetCurrentUserInfo().UserID); if (clearCache) { - DataCache.ClearTabsCache(originalTab.PortalID); + DataCache.ClearTabsCache(originalTab.PortalID); DataCache.ClearModuleCache(originalTab.TabID); } } @@ -1670,23 +1780,23 @@ public void LocalizeTab(TabInfo originalTab, Locale locale, bool clearCache) /// will move objTab after this tab. public void MoveTabAfter(TabInfo tab, int afterTabId) { - //Get AfterTab - var afterTab = GetTab(afterTabId, tab.PortalID, false); + // Get AfterTab + var afterTab = this.GetTab(afterTabId, tab.PortalID, false); - //Create Tab Redirects + // Create Tab Redirects if (afterTab.ParentId != tab.ParentId) { - CreateTabRedirects(tab); + this.CreateTabRedirects(tab); } - //Move Tab - _dataProvider.MoveTabAfter(tab.TabID, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); + // Move Tab + this._dataProvider.MoveTabAfter(tab.TabID, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); - //Clear the Cache - ClearCache(tab.PortalID); + // Clear the Cache + this.ClearCache(tab.PortalID); var portalId = GetPortalId(tab.TabID, -1); - var updatedTab = GetTab(tab.TabID, portalId, true); + var updatedTab = this.GetTab(tab.TabID, portalId, true); EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); } @@ -1697,47 +1807,47 @@ public void MoveTabAfter(TabInfo tab, int afterTabId) /// will move objTab before this tab. public void MoveTabBefore(TabInfo tab, int beforeTabId) { - //Get AfterTab - var beforeTab = GetTab(beforeTabId, tab.PortalID, false); + // Get AfterTab + var beforeTab = this.GetTab(beforeTabId, tab.PortalID, false); - //Create Tab Redirects + // Create Tab Redirects if (beforeTab.ParentId != tab.ParentId) { - CreateTabRedirects(tab); + this.CreateTabRedirects(tab); } - //Move Tab - _dataProvider.MoveTabBefore(tab.TabID, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID); + // Move Tab + this._dataProvider.MoveTabBefore(tab.TabID, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID); - //Clear the Cache - ClearCache(tab.PortalID); + // Clear the Cache + this.ClearCache(tab.PortalID); var portalId = GetPortalId(tab.TabID, -1); - var updatedTab = GetTab(tab.TabID, portalId, true); + var updatedTab = this.GetTab(tab.TabID, portalId, true); EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); } /// - /// Moves the tab to a new parent + /// Moves the tab to a new parent. /// /// The tab want to move. /// will move tab to this parent. public void MoveTabToParent(TabInfo tab, int parentId) { - //Create Tab Redirects + // Create Tab Redirects if (parentId != tab.ParentId) { - CreateTabRedirects(tab); + this.CreateTabRedirects(tab); } - //Move Tab - _dataProvider.MoveTabToParent(tab.TabID, parentId, UserController.Instance.GetCurrentUserInfo().UserID); + // Move Tab + this._dataProvider.MoveTabToParent(tab.TabID, parentId, UserController.Instance.GetCurrentUserInfo().UserID); - //Clear the Cache - ClearCache(tab.PortalID); + // Clear the Cache + this.ClearCache(tab.PortalID); var portalId = GetPortalId(tab.TabID, -1); - var updatedTab = GetTab(tab.TabID, portalId, true); + var updatedTab = this.GetTab(tab.TabID, portalId, true); EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); } @@ -1747,10 +1857,10 @@ public void MoveTabToParent(TabInfo tab, int parentId) /// The tab. public void PopulateBreadCrumbs(ref TabInfo tab) { - if ((tab.BreadCrumbs == null)) + if (tab.BreadCrumbs == null) { var crumbs = new ArrayList(); - PopulateBreadCrumbs(tab.PortalID, ref crumbs, tab.TabID); + this.PopulateBreadCrumbs(tab.PortalID, ref crumbs, tab.TabID); tab.BreadCrumbs = crumbs; } } @@ -1763,35 +1873,36 @@ public void PopulateBreadCrumbs(ref TabInfo tab) /// The tab ID. public void PopulateBreadCrumbs(int portalID, ref ArrayList breadCrumbs, int tabID) { - //find the tab in the tabs collection + // find the tab in the tabs collection TabInfo tab; - TabCollection portalTabs = GetTabsByPortal(portalID); - TabCollection hostTabs = GetTabsByPortal(Null.NullInteger); + TabCollection portalTabs = this.GetTabsByPortal(portalID); + TabCollection hostTabs = this.GetTabsByPortal(Null.NullInteger); bool found = portalTabs.TryGetValue(tabID, out tab); if (!found) { found = hostTabs.TryGetValue(tabID, out tab); } - //if tab was found + + // if tab was found if (found) { breadCrumbs.Insert(0, tab.Clone()); - //get the tab parent + // get the tab parent if (!Null.IsNull(tab.ParentId)) { - PopulateBreadCrumbs(portalID, ref breadCrumbs, tab.ParentId); + this.PopulateBreadCrumbs(portalID, ref breadCrumbs, tab.ParentId); } } } /// - /// Publishes the tab. Set the VIEW permission + /// Publishes the tab. Set the VIEW permission. /// /// The publish tab. public void PublishTab(TabInfo publishTab) { - //To publish a subsidiary language tab we need to enable the View Permissions + // To publish a subsidiary language tab we need to enable the View Permissions if (publishTab != null && publishTab.DefaultLanguageTab != null) { foreach (TabPermissionInfo perm in @@ -1824,7 +1935,7 @@ public void PublishTabs(List tabs) { if (t.IsTranslated) { - PublishTab(t); + this.PublishTab(t); } } } @@ -1838,22 +1949,22 @@ public void RestoreTab(TabInfo tab, PortalSettings portalSettings) { if (tab.DefaultLanguageTab != null) { - //We are trying to restore the child, so recall this function with the master language's tab id - RestoreTab(tab.DefaultLanguageTab, portalSettings); + // We are trying to restore the child, so recall this function with the master language's tab id + this.RestoreTab(tab.DefaultLanguageTab, portalSettings); return; } tab.IsDeleted = false; - UpdateTab(tab); + this.UpdateTab(tab); - //Restore any localized children + // Restore any localized children foreach (TabInfo localizedtab in tab.LocalizedTabs.Values) { localizedtab.IsDeleted = false; - UpdateTab(localizedtab); + this.UpdateTab(localizedtab); } - EventLogController.Instance.AddLog(tab, portalSettings, portalSettings.UserId, "", EventLogController.EventLogType.TAB_RESTORED); + EventLogController.Instance.AddLog(tab, portalSettings, portalSettings.UserId, string.Empty, EventLogController.EventLogType.TAB_RESTORED); ArrayList allTabsModules = ModuleController.Instance.GetAllTabsModules(tab.PortalID, true); var tabModules = ModuleController.Instance.GetTabModules(tab.TabID); @@ -1865,17 +1976,17 @@ public void RestoreTab(TabInfo tab, PortalSettings portalSettings) } } - ClearCache(tab.PortalID); + this.ClearCache(tab.PortalID); EventManager.Instance.OnTabRestored(new TabEventArgs { Tab = tab }); } /// - /// Save url information for a page (tab) + /// Save url information for a page (tab). /// - /// the tab url - /// the portal id - /// whether to clear the cache + /// the tab url. + /// the portal id. + /// whether to clear the cache. public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) { var portalAliasId = (tabUrl.PortalAliasUsage == PortalAliasUsageType.Default) @@ -1887,12 +1998,11 @@ public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) if (tabUrl.HttpStatus == "200") { saveLog = EventLogController.EventLogType.TABURL_CREATED; - } else { - //need to see if sequence number exists to decide if insert or update - List t = GetTabUrls(portalId, tabUrl.TabId); + // need to see if sequence number exists to decide if insert or update + List t = this.GetTabUrls(portalId, tabUrl.TabId); var existingSeq = t.FirstOrDefault(r => r.SeqNum == tabUrl.SeqNum); if (existingSeq == null) { @@ -1902,18 +2012,19 @@ public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) DataProvider.Instance().SaveTabUrl(tabUrl.TabId, tabUrl.SeqNum, portalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog("tabUrl", - tabUrl.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - saveLog); + EventLogController.Instance.AddLog( + "tabUrl", + tabUrl.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + saveLog); if (clearCache) { - DataCache.RemoveCache(String.Format(DataCache.TabUrlCacheKey, portalId)); + DataCache.RemoveCache(string.Format(DataCache.TabUrlCacheKey, portalId)); CacheController.ClearCustomAliasesCache(); - ClearCache(portalId); - var tab = GetTab(tabUrl.TabId, portalId); + this.ClearCache(portalId); + var tab = this.GetTab(tabUrl.TabId, portalId); tab.ClearTabUrls(); } } @@ -1927,24 +2038,24 @@ public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) public bool SoftDeleteTab(int tabId, PortalSettings portalSettings) { bool deleted; - TabInfo tab = GetTab(tabId, portalSettings.PortalId, false); + TabInfo tab = this.GetTab(tabId, portalSettings.PortalId, false); if (tab != null) { if (tab.DefaultLanguageTab != null && LocaleController.Instance.GetLocales(portalSettings.PortalId).ContainsKey(tab.CultureCode)) { - //We are trying to delete the child, so recall this function with the master language's tab id - return SoftDeleteTab(tab.DefaultLanguageTab.TabID, portalSettings); + // We are trying to delete the child, so recall this function with the master language's tab id + return this.SoftDeleteTab(tab.DefaultLanguageTab.TabID, portalSettings); } - //Delete the Tab - deleted = SoftDeleteTabInternal(tab, portalSettings); + // Delete the Tab + deleted = this.SoftDeleteTabInternal(tab, portalSettings); - //Delete any localized children + // Delete any localized children if (deleted) { foreach (TabInfo localizedtab in tab.LocalizedTabs.Values) { - SoftDeleteTabInternal(localizedtab, portalSettings); + this.SoftDeleteTabInternal(localizedtab, portalSettings); } } } @@ -1952,6 +2063,7 @@ public bool SoftDeleteTab(int tabId, PortalSettings portalSettings) { deleted = false; } + return deleted; } @@ -1961,59 +2073,60 @@ public bool SoftDeleteTab(int tabId, PortalSettings portalSettings) /// The updated tab. public void UpdateTab(TabInfo updatedTab) { - TabInfo originalTab = GetTab(updatedTab.TabID, updatedTab.PortalID, true); + TabInfo originalTab = this.GetTab(updatedTab.TabID, updatedTab.PortalID, true); - //Update ContentItem If neccessary + // Update ContentItem If neccessary if (updatedTab.TabID != Null.NullInteger) { if (updatedTab.ContentItemId == Null.NullInteger) { - CreateContentItem(updatedTab); + this.CreateContentItem(updatedTab); } else { - UpdateContentItem(updatedTab); + this.UpdateContentItem(updatedTab); } } - //Create Tab Redirects + // Create Tab Redirects if (originalTab.ParentId != updatedTab.ParentId || originalTab.TabName != updatedTab.TabName) { - CreateTabRedirects(updatedTab); - } - - //Update Tab to DataStore - _dataProvider.UpdateTab(updatedTab.TabID, - updatedTab.ContentItemId, - updatedTab.PortalID, - updatedTab.VersionGuid, - updatedTab.DefaultLanguageGuid, - updatedTab.LocalizedVersionGuid, - updatedTab.TabName, - updatedTab.IsVisible, - updatedTab.DisableLink, - updatedTab.ParentId, - updatedTab.IconFileRaw, - updatedTab.IconFileLargeRaw, - updatedTab.Title, - updatedTab.Description, - updatedTab.KeyWords, - updatedTab.IsDeleted, - updatedTab.Url, - updatedTab.SkinSrc, - updatedTab.ContainerSrc, - updatedTab.StartDate, - updatedTab.EndDate, - updatedTab.RefreshInterval, - updatedTab.PageHeadText, - updatedTab.IsSecure, - updatedTab.PermanentRedirect, - updatedTab.SiteMapPriority, - UserController.Instance.GetCurrentUserInfo().UserID, - updatedTab.CultureCode, - updatedTab.IsSystem); - - //Update Tags + this.CreateTabRedirects(updatedTab); + } + + // Update Tab to DataStore + this._dataProvider.UpdateTab( + updatedTab.TabID, + updatedTab.ContentItemId, + updatedTab.PortalID, + updatedTab.VersionGuid, + updatedTab.DefaultLanguageGuid, + updatedTab.LocalizedVersionGuid, + updatedTab.TabName, + updatedTab.IsVisible, + updatedTab.DisableLink, + updatedTab.ParentId, + updatedTab.IconFileRaw, + updatedTab.IconFileLargeRaw, + updatedTab.Title, + updatedTab.Description, + updatedTab.KeyWords, + updatedTab.IsDeleted, + updatedTab.Url, + updatedTab.SkinSrc, + updatedTab.ContainerSrc, + updatedTab.StartDate, + updatedTab.EndDate, + updatedTab.RefreshInterval, + updatedTab.PageHeadText, + updatedTab.IsSecure, + updatedTab.PermanentRedirect, + updatedTab.SiteMapPriority, + UserController.Instance.GetCurrentUserInfo().UserID, + updatedTab.CultureCode, + updatedTab.IsSystem); + + // Update Tags List terms = updatedTab.Terms; ITermController termController = Util.GetTermController(); termController.RemoveTermsFromContent(updatedTab); @@ -2023,45 +2136,45 @@ public void UpdateTab(TabInfo updatedTab) } EventLogController.Instance.AddLog(updatedTab, PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, "", + UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.TAB_UPDATED); - //Update Tab permissions + // Update Tab permissions TabPermissionController.SaveTabPermissions(updatedTab); - //Update TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist + // Update TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist try { - UpdateTabSettings(ref updatedTab); + this.UpdateTabSettings(ref updatedTab); } catch (Exception ex) { Exceptions.LogException(ex); } - //Update Tab Version + // Update Tab Version UpdateTabVersion(updatedTab.TabID); - //Clear Tab Caches - ClearCache(updatedTab.PortalID); + // Clear Tab Caches + this.ClearCache(updatedTab.PortalID); if (updatedTab.PortalID != originalTab.PortalID) { - ClearCache(originalTab.PortalID); + this.ClearCache(originalTab.PortalID); } EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); } /// - /// Adds or updates a tab's setting value + /// Adds or updates a tab's setting value. /// - /// ID of the tab to update - /// name of the setting property + /// ID of the tab to update. + /// name of the setting property. /// value of the setting (String). - /// empty SettingValue will remove the setting, if not preserveIfEmpty is true + /// empty SettingValue will remove the setting, if not preserveIfEmpty is true. public void UpdateTabSetting(int tabId, string settingName, string settingValue) { - UpdateTabSettingInternal(tabId, settingName, settingValue, true); + this.UpdateTabSettingInternal(tabId, settingName, settingValue, true); } /// @@ -2079,107 +2192,27 @@ public void UpdateTranslationStatus(TabInfo localizedTab, bool isTranslated) { localizedTab.LocalizedVersionGuid = Guid.NewGuid(); } + DataProvider.Instance() .UpdateTabTranslationStatus(localizedTab.TabID, localizedTab.LocalizedVersionGuid, UserController.Instance.GetCurrentUserInfo().UserID); - //Clear Tab Caches - ClearCache(localizedTab.PortalID); + // Clear Tab Caches + this.ClearCache(localizedTab.PortalID); } /// - /// It marks a page as published at least once + /// It marks a page as published at least once. /// - /// The Tab to be marked + /// The Tab to be marked. public void MarkAsPublished(TabInfo tab) { - _dataProvider.MarkAsPublished(tab.TabID); - - //Clear Tab Caches - ClearCache(tab.PortalID); - - EventManager.Instance.OnTabMarkedAsPublished(new TabEventArgs { Tab = tab }); - } - - #endregion - - #region Static Methods - - /// - /// Copies the design to children. - /// - /// The parent tab. - /// The skin SRC. - /// The container SRC. - public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc) - { - CopyDesignToChildren(parentTab, skinSrc, containerSrc, - PortalController.GetActivePortalLanguage(parentTab.PortalID)); - } - - /// - /// Copies the design to children. - /// - /// The parent tab. - /// The skin SRC. - /// The container SRC. - /// The culture code. - public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc, string cultureCode) - { - bool clearCache = Null.NullBoolean; - List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); - foreach (TabInfo tab in childTabs) - { - if (TabPermissionController.CanAdminPage(tab)) - { - //Update ContentItem If neccessary - if (tab.ContentItemId == Null.NullInteger && tab.TabID != Null.NullInteger) - { - Instance.CreateContentItem(tab); - } - - DataProvider.Instance().UpdateTab(tab.TabID, - tab.ContentItemId, - tab.PortalID, - tab.VersionGuid, - tab.DefaultLanguageGuid, - tab.LocalizedVersionGuid, - tab.TabName, - tab.IsVisible, - tab.DisableLink, - tab.ParentId, - tab.IconFileRaw, - tab.IconFileLargeRaw, - tab.Title, - tab.Description, - tab.KeyWords, - tab.IsDeleted, - tab.Url, - skinSrc, - containerSrc, - tab.StartDate, - tab.EndDate, - tab.RefreshInterval, - tab.PageHeadText, - tab.IsSecure, - tab.PermanentRedirect, - tab.SiteMapPriority, - UserController.Instance.GetCurrentUserInfo().UserID, - tab.CultureCode, - tab.IsSystem); + this._dataProvider.MarkAsPublished(tab.TabID); - UpdateTabVersion(tab.TabID); + // Clear Tab Caches + this.ClearCache(tab.PortalID); - EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, "", - EventLogController.EventLogType.TAB_UPDATED); - clearCache = true; - } - } - if (clearCache) - { - DataCache.ClearTabsCache(childTabs[0].PortalID); - } + EventManager.Instance.OnTabMarkedAsPublished(new TabEventArgs { Tab = tab }); } /// @@ -2202,6 +2235,7 @@ public static void CopyPermissionsToChildren(TabInfo parentTab, TabPermissionCol clearCache = true; } } + if (clearCache) { DataCache.ClearTabsCache(childTabs[0].PortalID); @@ -2210,11 +2244,11 @@ public static void CopyPermissionsToChildren(TabInfo parentTab, TabPermissionCol /// ----------------------------------------------------------------------------- /// - /// Processes all panes and modules in the template file + /// Processes all panes and modules in the template file. /// - /// Template file node for the panes is current tab - /// PortalId of the new portal - /// Tab being processed + /// Template file node for the panes is current tab. + /// PortalId of the new portal. + /// Tab being processed. /// Tabs need to merge. /// Modules Hashtable. /// @@ -2224,13 +2258,14 @@ public static void DeserializePanes(XmlNode nodePanes, int portalId, int tabId, { Dictionary dicModules = ModuleController.Instance.GetTabModules(tabId); - //If Mode is Replace remove all the modules already on this Tab + // If Mode is Replace remove all the modules already on this Tab if (mergeTabs == PortalTemplateModuleAction.Replace) { foreach (KeyValuePair kvp in dicModules) { var module = kvp.Value; - //when the modules show on all pages are included by the same import process, it need removed. + + // when the modules show on all pages are included by the same import process, it need removed. if (!module.AllTabs || hModules.ContainsValue(module.ModuleID)) { ModuleController.Instance.DeleteTabModule(tabId, kvp.Value.ModuleID, false); @@ -2238,10 +2273,10 @@ public static void DeserializePanes(XmlNode nodePanes, int portalId, int tabId, } } - //iterate through the panes + // iterate through the panes foreach (XmlNode nodePane in nodePanes.ChildNodes) { - //iterate through the modules + // iterate through the modules if (nodePane.SelectSingleNode("modules") != null) { XmlNode selectSingleNode = nodePane.SelectSingleNode("modules"); @@ -2256,7 +2291,7 @@ public static void DeserializePanes(XmlNode nodePanes, int portalId, int tabId, } } - //if deserialize tab from install wizard, we need parse desiralize handlers first. + // if deserialize tab from install wizard, we need parse desiralize handlers first. var installFromWizard = HttpContext.Current != null && HttpContext.Current.Items.Contains("InstallFromWizard"); if (installFromWizard) { @@ -2297,12 +2332,13 @@ public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tab Hashtable modules) { string tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "name"); - if (!String.IsNullOrEmpty(tabName)) + if (!string.IsNullOrEmpty(tabName)) { if (tab == null) { tab = new TabInfo { TabID = Null.NullInteger, ParentId = Null.NullInteger, TabName = tabName }; } + tab.PortalID = portalId; if (string.IsNullOrEmpty(tab.Title)) { @@ -2318,18 +2354,20 @@ public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tab tab.IsVisible = XmlUtils.GetNodeValueBoolean(tabNode, "visible", true); tab.DisableLink = XmlUtils.GetNodeValueBoolean(tabNode, "disabled"); tab.IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfile")); - tab.IconFileLarge = Globals.ImportFile(portalId, - XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfilelarge")); + tab.IconFileLarge = Globals.ImportFile( + portalId, + XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfilelarge")); tab.Url = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "url"); tab.StartDate = XmlUtils.GetNodeValueDate(tabNode, "startdate", Null.NullDate); tab.EndDate = XmlUtils.GetNodeValueDate(tabNode, "enddate", Null.NullDate); tab.RefreshInterval = XmlUtils.GetNodeValueInt(tabNode, "refreshinterval", Null.NullInteger); tab.PageHeadText = XmlUtils.GetNodeValue(tabNode, "pageheadtext", Null.NullString); tab.IsSecure = XmlUtils.GetNodeValueBoolean(tabNode, "issecure", false); - tab.SiteMapPriority = XmlUtils.GetNodeValueSingle(tabNode, "sitemappriority", (float)0.5); + tab.SiteMapPriority = XmlUtils.GetNodeValueSingle(tabNode, "sitemappriority", 0.5F); tab.CultureCode = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "cultureCode"); - //objTab.UniqueId = New Guid(XmlUtils.GetNodeValue(nodeTab, "guid", Guid.NewGuid.ToString())); - //objTab.VersionGuid = New Guid(XmlUtils.GetNodeValue(nodeTab, "versionGuid", Guid.NewGuid.ToString())); + + // objTab.UniqueId = New Guid(XmlUtils.GetNodeValue(nodeTab, "guid", Guid.NewGuid.ToString())); + // objTab.VersionGuid = New Guid(XmlUtils.GetNodeValue(nodeTab, "versionGuid", Guid.NewGuid.ToString())); tab.UseBaseFriendlyUrls = XmlUtils.GetNodeValueBoolean(tabNode, "UseBaseFriendlyUrls", false); tab.TabPermissions.Clear(); @@ -2337,30 +2375,31 @@ public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tab DeserializeTabSettings(tabNode.SelectNodes("tabsettings/tabsetting"), tab); - //set tab skin and container - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "skinsrc", ""))) + // set tab skin and container + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty))) { - tab.SkinSrc = XmlUtils.GetNodeValue(tabNode, "skinsrc", ""); + tab.SkinSrc = XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty); } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "containersrc", ""))) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty))) { - tab.ContainerSrc = XmlUtils.GetNodeValue(tabNode, "containersrc", ""); + tab.ContainerSrc = XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty); } tabName = tab.TabName; - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"))) { if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")] != null) { - //parent node specifies the path (tab1/tab2/tab3), use saved tabid + // parent node specifies the path (tab1/tab2/tab3), use saved tabid tab.ParentId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")]); tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent") + "/" + tab.TabName; } else { - //Parent node doesn't spcecify the path, search by name. - //Possible incoherence if tabname not unique - TabInfo objParent = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"),portalId); + // Parent node doesn't spcecify the path, search by name. + // Possible incoherence if tabname not unique + TabInfo objParent = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"), portalId); if (objParent != null) { tab.ParentId = objParent.TabID; @@ -2368,18 +2407,18 @@ public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tab } else { - //parent tab not found! + // parent tab not found! tab.ParentId = Null.NullInteger; tabName = tab.TabName; } } } - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"))) { if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")] != null) { - //parent node specifies the path (tab1/tab2/tab3), use saved tabid + // parent node specifies the path (tab1/tab2/tab3), use saved tabid int defaultLanguageTabId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")]); TabInfo defaultLanguageTab = Instance.GetTab(defaultLanguageTabId, portalId, false); if (defaultLanguageTab != null) @@ -2389,8 +2428,8 @@ public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tab } else { - //Parent node doesn't spcecify the path, search by name. - //Possible incoherence if tabname not unique + // Parent node doesn't spcecify the path, search by name. + // Possible incoherence if tabname not unique TabInfo defaultLanguageTab = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"), portalId); if (defaultLanguageTab != null) { @@ -2399,38 +2438,38 @@ public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tab } } - //create/update tab + // create/update tab if (tab.TabID == Null.NullInteger) { tab.TabID = TabController.Instance.AddTab(tab); } else { - Instance.UpdateTab(tab); + Instance.UpdateTab(tab); } - //UpdateTabUrls + // UpdateTabUrls foreach (XmlNode oTabUrlNode in tabNode.SelectNodes("tabUrls/tabUrl")) { var tabUrl = new TabUrlInfo(); DeserializeTabUrls(oTabUrlNode, tabUrl); DataProvider.Instance().SaveTabUrl(tab.TabID, tabUrl.SeqNum, tabUrl.PortalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); } - - //extra check for duplicate tabs in same level + + // extra check for duplicate tabs in same level if (tabs[tabName] == null) { tabs.Add(tabName, tab.TabID); } } - //Parse Panes + // Parse Panes if (tabNode.SelectSingleNode("panes") != null) { DeserializePanes(tabNode.SelectSingleNode("panes"), portalId, tab.TabID, mergeTabs, modules); } - //Finally add "tabid" to node + // Finally add "tabid" to node tabNode.AppendChild(XmlUtils.CreateElement(tabNode.OwnerDocument, "tabid", tab.TabID.ToString())); return tab; } @@ -2446,16 +2485,17 @@ public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tab public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, bool includeHidden) { - return GetPortalTabs(GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - "<" + Localization.GetString("None_Specified") + ">", - includeHidden, - false, - false, - false, - false, - true); + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + "<" + Localization.GetString("None_Specified") + ">", + includeHidden, + false, + false, + false, + false, + true); } /// @@ -2471,16 +2511,17 @@ public static List GetPortalTabs(int portalId, int excludeTabId, bool i public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, bool includeHidden, bool includeDeleted, bool includeURL) { - return GetPortalTabs(GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - "<" + Localization.GetString("None_Specified") + ">", - includeHidden, - includeDeleted, - includeURL, - false, - false, - true); + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + "<" + Localization.GetString("None_Specified") + ">", + includeHidden, + includeDeleted, + includeURL, + false, + false, + true); } /// @@ -2500,16 +2541,17 @@ public static List GetPortalTabs(int portalId, int excludeTabId, bool i string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, bool checkViewPermisison, bool checkEditPermission) { - return GetPortalTabs(GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - noneSpecifiedText, - includeHidden, - includeDeleted, - includeURL, - checkViewPermisison, - checkEditPermission, - true); + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + noneSpecifiedText, + includeHidden, + includeDeleted, + includeURL, + checkViewPermisison, + checkEditPermission, + true); } /// @@ -2574,6 +2616,7 @@ public static List GetPortalTabs( var tab = new TabInfo { TabID = -1, TabName = noneSpecifiedText, TabOrder = 0, ParentId = -2 }; listTabs.Add(tab); } + foreach (TabInfo tab in tabs) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -2583,7 +2626,7 @@ public static List GetPortalTabs( if ((tab.IsVisible || includeHidden) && tab.HasAVisibleVersion && (tab.IsDeleted == false || includeDeleted) && (tab.TabType == TabType.Normal || includeURL)) { - //Check if User has View/Edit Permission for this tab + // Check if User has View/Edit Permission for this tab if (checkEditPermission || checkViewPermisison) { const string permissionList = "ADD,COPY,EDIT,MANAGE"; @@ -2599,7 +2642,7 @@ public static List GetPortalTabs( } else { - //Add Tab to List + // Add Tab to List listTabs.Add(tab); } } @@ -2608,6 +2651,7 @@ public static List GetPortalTabs( tab.HasChildren = tab.HasChildren && (includeDeletedChildren || GetTabsByParent(tab.TabID, tab.PortalID).Any(a => !a.IsDeleted)); } } + return listTabs; } @@ -2625,6 +2669,7 @@ public static int GetTabByTabPath(int portalId, string tabPath, string cultureCo { return tabpathDic[tabPath]; } + return -1; } @@ -2668,11 +2713,11 @@ public static List GetTabsBySortOrder(int portalId, string cultureCode, } /// - /// Get all TabInfo for the current culture in SortOrder + /// Get all TabInfo for the current culture in SortOrder. /// - /// The portalid to load tabs for + /// The portalid to load tabs for. /// - /// List of TabInfo oredered by default SortOrder + /// List of TabInfo oredered by default SortOrder. /// /// /// This method uses the Active culture. There is an overload @@ -2708,16 +2753,6 @@ public static bool IsSpecialTab(int tabId, int portalId) return isSpecial; } - /// - /// Determines whether is host or admin tab. - /// - /// The tab info. - /// - public bool IsHostOrAdminPage(TabInfo tab) - { - return IsHostTab(tab) || IsAdminTab(tab); - } - /// /// Determines whether is special tab. /// @@ -2734,24 +2769,36 @@ public static bool IsSpecialTab(int tabId, PortalSettings portalSettings) } /// - /// SerializeTab + /// SerializeTab. /// - /// The Xml Document to use for the Tab - /// The TabInfo object to serialize - /// A flag used to determine if the Module content is included + /// The Xml Document to use for the Tab. + /// The TabInfo object to serialize. + /// A flag used to determine if the Module content is included. + /// public static XmlNode SerializeTab(XmlDocument tabXml, TabInfo objTab, bool includeContent) { return SerializeTab(tabXml, null, objTab, null, includeContent); } /// - /// SerializeTab + /// Determines whether is host or admin tab. + /// + /// The tab info. + /// + public bool IsHostOrAdminPage(TabInfo tab) + { + return this.IsHostTab(tab) || this.IsAdminTab(tab); + } + + /// + /// SerializeTab. /// - /// The Xml Document to use for the Tab - /// A Hashtable used to store the names of the tabs - /// The TabInfo object to serialize - /// The Portal object to which the tab belongs - /// A flag used to determine if the Module content is included + /// The Xml Document to use for the Tab. + /// A Hashtable used to store the names of the tabs. + /// The TabInfo object to serialize. + /// The Portal object to which the tab belongs. + /// A flag used to determine if the Module content is included. + /// public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo tab, PortalInfo portal, bool includeContent) { @@ -2767,7 +2814,7 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsi"]); } - //remove unwanted elements + // remove unwanted elements // ReSharper disable AssignNullToNotNullAttribute tabNode.RemoveChild(tabNode.SelectSingleNode("tabid")); tabNode.RemoveChild(tabNode.SelectSingleNode("moduleID")); @@ -2786,7 +2833,7 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t if (xmlNodeList != null && xmlNodeList.Count == 0) { // for some reason serialization of permissions did not work - // we are using a different method here to make sure that + // we are using a different method here to make sure that // permissions are included in the tabinfo xml XmlDocument tabPermissions = new XmlDocument { XmlResolver = null }; CBO.SerializeObject(tab.TabPermissions, tabPermissions); @@ -2802,11 +2849,13 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t permissionsNode.AppendChild(newNode); } } + tabNode.AppendChild(permissionsNode); // re-select the permissions node xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); } + if (xmlNodeList != null) { foreach (XmlNode nodePermission in xmlNodeList) @@ -2820,10 +2869,11 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); } } + // ReSharper restore AssignNullToNotNullAttribute } - //Manage Url + // Manage Url XmlNode urlNode = tabXml.SelectSingleNode("tab/url"); switch (tab.TabType) { @@ -2832,16 +2882,18 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t break; case TabType.Tab: urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Tab")); - //Get the tab being linked to - TabInfo tempTab = TabController.Instance.GetTab(Int32.Parse(tab.Url), tab.PortalID, false); + + // Get the tab being linked to + TabInfo tempTab = TabController.Instance.GetTab(int.Parse(tab.Url), tab.PortalID, false); if (tempTab != null) { urlNode.InnerXml = tempTab.TabPath; } + break; case TabType.File: urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "File")); - IFileInfo file = FileManager.Instance.GetFile(Int32.Parse(tab.Url.Substring(7))); + IFileInfo file = FileManager.Instance.GetFile(int.Parse(tab.Url.Substring(7))); urlNode.InnerXml = file.RelativePath; break; case TabType.Url: @@ -2849,8 +2901,7 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t break; } - - //serialize TabSettings + // serialize TabSettings XmlUtils.SerializeHashtable(tab.TabSettings, tabXml, tabNode, "tabsetting", "settingname", "settingvalue"); if (portal != null) { @@ -2909,29 +2960,29 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t tabNode.AppendChild(newnode); } } + if (tabs != null) { - //Manage Parent Tab + // Manage Parent Tab if (!Null.IsNull(tab.ParentId)) { newnode = tabXml.CreateElement("parent"); newnode.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.ParentId].ToString()); tabNode.AppendChild(newnode); - //save tab as: ParentTabName/CurrentTabName + // save tab as: ParentTabName/CurrentTabName tabs.Add(tab.TabID, tabs[tab.ParentId] + "/" + tab.TabName); } else { - //save tab as: CurrentTabName + // save tab as: CurrentTabName tabs.Add(tab.TabID, tab.TabName); } } - //Manage Content Localization + // Manage Content Localization if (tab.DefaultLanguageTab != null) { - try { newnode = tabXml.CreateElement("defaultLanguageTab"); @@ -2940,7 +2991,7 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t } catch { - //ignore + // ignore } } @@ -2952,7 +3003,7 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t XmlDocument moduleXml; ModuleInfo module; - //Serialize modules + // Serialize modules panesNode = tabNode.AppendChild(tabXml.CreateElement("panes")); foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(tab.TabID)) { @@ -2963,21 +3014,22 @@ public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo t moduleNode = ModuleController.SerializeModule(moduleXml, module, includeContent); if (panesNode.SelectSingleNode("descendant::pane[name='" + module.PaneName + "']") == null) { - //new pane found + // new pane found paneNode = moduleXml.CreateElement("pane"); nameNode = paneNode.AppendChild(moduleXml.CreateElement("name")); nameNode.InnerText = module.PaneName; paneNode.AppendChild(moduleXml.CreateElement("modules")); panesNode.AppendChild(tabXml.ImportNode(paneNode, true)); } + modulesNode = panesNode.SelectSingleNode("descendant::pane[name='" + module.PaneName + "']/modules"); modulesNode.AppendChild(tabXml.ImportNode(moduleNode, true)); } } - //Serialize TabUrls + // Serialize TabUrls var tabUrlsNode = tabNode.AppendChild(tabXml.CreateElement("tabUrls")); - foreach (var tabUrl in TabController.Instance.GetTabUrls(tab.TabID, tab.PortalID)) + foreach (var tabUrl in TabController.Instance.GetTabUrls(tab.TabID, tab.PortalID)) { var tabUrlXml = new XmlDocument { XmlResolver = null }; XmlNode tabUrlNode = tabUrlXml.CreateElement("tabUrl"); @@ -3041,8 +3093,8 @@ public static bool IsValidTabName(string tabName, out string invalidType) if (Config.GetFriendlyUrlProvider() == "advanced" && PortalSettings.Current != null) { var doNotRewriteRegex = new FriendlyUrlSettings(PortalSettings.Current.PortalId).DoNotRewriteRegex; - if (!string.IsNullOrEmpty(doNotRewriteRegex) && - (Regex.IsMatch(cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) + if (!string.IsNullOrEmpty(doNotRewriteRegex) && + (Regex.IsMatch(cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) || Regex.IsMatch("/" + cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) || Regex.IsMatch("/" + cleanTabName + "/", doNotRewriteRegex, RegexOptions.IgnoreCase))) { @@ -3053,7 +3105,5 @@ public static bool IsValidTabName(string tabName, out string invalidType) return true; } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Tabs/TabException.cs b/DNN Platform/Library/Entities/Tabs/TabException.cs index 31e7ea9ddcf..43e3c569481 100644 --- a/DNN Platform/Library/Entities/Tabs/TabException.cs +++ b/DNN Platform/Library/Entities/Tabs/TabException.cs @@ -1,20 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { + using System; + public class TabException : Exception { - public TabException(int tabId, string message) : base(message) + public TabException(int tabId, string message) + : base(message) { - TabId = tabId; + this.TabId = tabId; } public int TabId { get; private set; } diff --git a/DNN Platform/Library/Entities/Tabs/TabExistsException.cs b/DNN Platform/Library/Entities/Tabs/TabExistsException.cs index 2b2308fea27..1f24cec22ab 100644 --- a/DNN Platform/Library/Entities/Tabs/TabExistsException.cs +++ b/DNN Platform/Library/Entities/Tabs/TabExistsException.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { + using System; + public class TabExistsException : TabException { - public TabExistsException(int tabId, string message) : base(tabId, message) - { + public TabExistsException(int tabId, string message) + : base(tabId, message) + { } - } } diff --git a/DNN Platform/Library/Entities/Tabs/TabExtensions.cs b/DNN Platform/Library/Entities/Tabs/TabExtensions.cs index 07805388637..50a7fc2fb1a 100644 --- a/DNN Platform/Library/Entities/Tabs/TabExtensions.cs +++ b/DNN Platform/Library/Entities/Tabs/TabExtensions.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using System.Collections.Generic; + using System.Linq; + public static class TabExtensions { public static bool ContainsAlias(this List aliases, string httpAlias) { - return aliases.Any(tas => System.String.Compare(httpAlias, tas.HttpAlias, System.StringComparison.OrdinalIgnoreCase) == 0); + return aliases.Any(tas => string.Compare(httpAlias, tas.HttpAlias, System.StringComparison.OrdinalIgnoreCase) == 0); } public static TabAliasSkinInfo FindByHttpAlias(this List aliases, string httpAlias) { - return aliases.FirstOrDefault(tas => System.String.Compare(httpAlias, tas.HttpAlias, System.StringComparison.OrdinalIgnoreCase) == 0); + return aliases.FirstOrDefault(tas => string.Compare(httpAlias, tas.HttpAlias, System.StringComparison.OrdinalIgnoreCase) == 0); } public static int GetNextAvailableSeqNum(this List redirects, bool positive) @@ -29,7 +29,8 @@ public static int GetNextAvailableSeqNum(this List redirects, bool p if (redirect.SeqNum >= seqNum) { seqNum = redirect.SeqNum + 1; - //602 : when seqnum == 0, then duplicate key problems arise + + // 602 : when seqnum == 0, then duplicate key problems arise if (seqNum == 0) { seqNum++; @@ -42,7 +43,8 @@ public static int GetNextAvailableSeqNum(this List redirects, bool p if (redirect.SeqNum <= seqNum) { seqNum = redirect.SeqNum - 1; - //602 : don't allow seqnum to become zero + + // 602 : don't allow seqnum to become zero if (seqNum == 0) { seqNum--; @@ -50,6 +52,7 @@ public static int GetNextAvailableSeqNum(this List redirects, bool p } } } + return seqNum; } @@ -77,7 +80,8 @@ public static TabUrlInfo CurrentUrl(this List redirects, string cult } } } - //look at the results + + // look at the results if (lastCustomUrl != null) { result = lastCustomUrl; @@ -86,6 +90,7 @@ public static TabUrlInfo CurrentUrl(this List redirects, string cult { result = lastSystemUrl; } + return result; } } diff --git a/DNN Platform/Library/Entities/Tabs/TabInfo.cs b/DNN Platform/Library/Entities/Tabs/TabInfo.cs index e129defa271..47e49957304 100644 --- a/DNN Platform/Library/Entities/Tabs/TabInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabInfo.cs @@ -1,47 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using System.Xml; -using System.Xml.Serialization; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Tokens; + [XmlRoot("tab", IsNullable = false)] [Serializable] public class TabInfo : ContentItem, IPropertyAccess { - #region Private Members + private static readonly Regex SkinSrcRegex = new Regex(@"([^/]+$)", RegexOptions.CultureInvariant); + private static Dictionary _docTypeCache = new Dictionary(); + private static ReaderWriterLockSlim _docTypeCacheLock = new ReaderWriterLockSlim(); private string _administratorRoles; private string _authorizedRoles; @@ -62,64 +59,53 @@ public class TabInfo : ContentItem, IPropertyAccess private List _tabUrls; private ArrayList _modules; - - #endregion - - #region Constructors - public TabInfo() : this(new SharedDictionary(), new SharedDictionary()) { - } - private TabInfo(SharedDictionary localizedTabNameDictionary, SharedDictionary fullUrlDictionary) { - _localizedTabNameDictionary = localizedTabNameDictionary; - _fullUrlDictionary = fullUrlDictionary; - - PortalID = Null.NullInteger; - _authorizedRoles = Null.NullString; - ParentId = Null.NullInteger; - IconFile = Null.NullString; - IconFileLarge = Null.NullString; - _administratorRoles = Null.NullString; - Title = Null.NullString; - Description = Null.NullString; - KeyWords = Null.NullString; - Url = Null.NullString; - SkinSrc = Null.NullString; - _skinDoctype = Null.NullString; - ContainerSrc = Null.NullString; - TabPath = Null.NullString; - StartDate = Null.NullDate; - EndDate = Null.NullDate; - RefreshInterval = Null.NullInteger; - PageHeadText = Null.NullString; - SiteMapPriority = 0.5F; - - //UniqueId, Version Guid, and Localized Version Guid should be initialised to a new value - UniqueId = Guid.NewGuid(); - VersionGuid = Guid.NewGuid(); - LocalizedVersionGuid = Guid.NewGuid(); - - //Default Language Guid should be initialised to a null Guid - DefaultLanguageGuid = Null.NullGuid; - - IsVisible = true; - HasBeenPublished = true; - DisableLink = false; - - Panes = new ArrayList(); - - IsSystem = false; + this._localizedTabNameDictionary = localizedTabNameDictionary; + this._fullUrlDictionary = fullUrlDictionary; + + this.PortalID = Null.NullInteger; + this._authorizedRoles = Null.NullString; + this.ParentId = Null.NullInteger; + this.IconFile = Null.NullString; + this.IconFileLarge = Null.NullString; + this._administratorRoles = Null.NullString; + this.Title = Null.NullString; + this.Description = Null.NullString; + this.KeyWords = Null.NullString; + this.Url = Null.NullString; + this.SkinSrc = Null.NullString; + this._skinDoctype = Null.NullString; + this.ContainerSrc = Null.NullString; + this.TabPath = Null.NullString; + this.StartDate = Null.NullDate; + this.EndDate = Null.NullDate; + this.RefreshInterval = Null.NullInteger; + this.PageHeadText = Null.NullString; + this.SiteMapPriority = 0.5F; + + // UniqueId, Version Guid, and Localized Version Guid should be initialised to a new value + this.UniqueId = Guid.NewGuid(); + this.VersionGuid = Guid.NewGuid(); + this.LocalizedVersionGuid = Guid.NewGuid(); + + // Default Language Guid should be initialised to a null Guid + this.DefaultLanguageGuid = Null.NullGuid; + + this.IsVisible = true; + this.HasBeenPublished = true; + this.DisableLink = false; + + this.Panes = new ArrayList(); + + this.IsSystem = false; } - #endregion - - #region Auto-Properties - [XmlIgnore] public ArrayList BreadCrumbs { get; set; } @@ -169,10 +155,11 @@ private TabInfo(SharedDictionary localizedTabNameDictionary, Sha public bool HasBeenPublished { get; set; } [XmlIgnore] - public bool HasAVisibleVersion { + public bool HasAVisibleVersion + { get { - return HasBeenPublished || TabVersionUtils.CanSeeVersionedPages(this); + return this.HasBeenPublished || TabVersionUtils.CanSeeVersionedPages(this); } } @@ -186,16 +173,17 @@ public bool HasAVisibleVersion { public Guid LocalizedVersionGuid { get; set; } [XmlIgnore] - public ArrayList Modules + public ArrayList Modules { get { - return _modules ?? (_modules = TabModulesController.Instance.GetTabModules(this)); + return this._modules ?? (this._modules = TabModulesController.Instance.GetTabModules(this)); } + set { - _modules = value; - } + this._modules = value; + } } [XmlElement("pageheadtext")] @@ -246,16 +234,12 @@ public ArrayList Modules [XmlElement("versionguid")] public Guid VersionGuid { get; set; } - #endregion - - #region Public Properties - [XmlIgnore] public Dictionary ChildModules { get { - return ModuleController.Instance.GetTabModules(TabID); + return ModuleController.Instance.GetTabModules(this.TabID); } } @@ -264,11 +248,12 @@ public TabInfo DefaultLanguageTab { get { - if (_defaultLanguageTab == null && (!DefaultLanguageGuid.Equals(Null.NullGuid))) + if (this._defaultLanguageTab == null && (!this.DefaultLanguageGuid.Equals(Null.NullGuid))) { - _defaultLanguageTab = (from kvp in TabController.Instance.GetTabsByPortal(PortalID) where kvp.Value.UniqueId == DefaultLanguageGuid select kvp.Value).SingleOrDefault(); + this._defaultLanguageTab = (from kvp in TabController.Instance.GetTabsByPortal(this.PortalID) where kvp.Value.UniqueId == this.DefaultLanguageGuid select kvp.Value).SingleOrDefault(); } - return _defaultLanguageTab; + + return this._defaultLanguageTab; } } @@ -278,14 +263,15 @@ public bool DoNotRedirect get { bool doNotRedirect; - if (TabSettings.ContainsKey("DoNotRedirect") && !string.IsNullOrEmpty(TabSettings["DoNotRedirect"].ToString())) + if (this.TabSettings.ContainsKey("DoNotRedirect") && !string.IsNullOrEmpty(this.TabSettings["DoNotRedirect"].ToString())) { - doNotRedirect = bool.Parse(TabSettings["DoNotRedirect"].ToString()); + doNotRedirect = bool.Parse(this.TabSettings["DoNotRedirect"].ToString()); } else { doNotRedirect = false; } + return doNotRedirect; } } @@ -295,14 +281,14 @@ public string IconFile { get { - IconFileGetter(ref _iconFile, IconFileRaw); - return _iconFile; + this.IconFileGetter(ref this._iconFile, this.IconFileRaw); + return this._iconFile; } set { - IconFileRaw = value; - _iconFile = null; + this.IconFileRaw = value; + this._iconFile = null; } } @@ -311,14 +297,14 @@ public string IconFileLarge { get { - IconFileGetter(ref _iconFileLarge, IconFileLargeRaw); - return _iconFileLarge; + this.IconFileGetter(ref this._iconFileLarge, this.IconFileLargeRaw); + return this._iconFileLarge; } set { - IconFileLargeRaw = value; - _iconFileLarge = null; + this.IconFileLargeRaw = value; + this._iconFileLarge = null; } } @@ -328,11 +314,12 @@ public string IndentedTabName get { string indentedTabName = Null.NullString; - for (int intCounter = 1; intCounter <= Level; intCounter++) + for (int intCounter = 1; intCounter <= this.Level; intCounter++) { indentedTabName += "..."; } - indentedTabName += LocalizedTabName; + + indentedTabName += this.LocalizedTabName; return indentedTabName; } } @@ -342,7 +329,7 @@ public bool IsDefaultLanguage { get { - return (DefaultLanguageGuid == Null.NullGuid); + return this.DefaultLanguageGuid == Null.NullGuid; } } @@ -351,7 +338,7 @@ public bool IsNeutralCulture { get { - return string.IsNullOrEmpty(CultureCode); + return string.IsNullOrEmpty(this.CultureCode); } } @@ -360,16 +347,18 @@ public bool IsSuperTab { get { - if (_superTabIdSet) + if (this._superTabIdSet) { - return _isSuperTab; + return this._isSuperTab; } - return (PortalID == Null.NullInteger); + + return this.PortalID == Null.NullInteger; } + set { - _isSuperTab = value; - _superTabIdSet = true; + this._isSuperTab = value; + this._superTabIdSet = true; } } @@ -379,11 +368,12 @@ public bool IsTranslated get { bool isTranslated = true; - if (DefaultLanguageTab != null) + if (this.DefaultLanguageTab != null) { - //Child language - isTranslated = (LocalizedVersionGuid == DefaultLanguageTab.LocalizedVersionGuid); + // Child language + isTranslated = this.LocalizedVersionGuid == this.DefaultLanguageTab.LocalizedVersionGuid; } + return isTranslated; } } @@ -393,11 +383,12 @@ public override int KeyID { get { - return TabID; + return this.TabID; } + set { - TabID = value; + this.TabID = value; } } @@ -406,28 +397,31 @@ public string LocalizedTabName { get { - if (String.IsNullOrEmpty(TabPath)) return TabName; + if (string.IsNullOrEmpty(this.TabPath)) + { + return this.TabName; + } var key = Thread.CurrentThread.CurrentUICulture.ToString(); string localizedTabName; - using (_localizedTabNameDictionary.GetReadLock()) + using (this._localizedTabNameDictionary.GetReadLock()) { - _localizedTabNameDictionary.TryGetValue(key, out localizedTabName); + this._localizedTabNameDictionary.TryGetValue(key, out localizedTabName); } - if (String.IsNullOrEmpty(localizedTabName)) + if (string.IsNullOrEmpty(localizedTabName)) { - using (_localizedTabNameDictionary.GetWriteLock()) + using (this._localizedTabNameDictionary.GetWriteLock()) { - localizedTabName = Localization.GetString(TabPath + ".String", Localization.GlobalResourceFile, true); + localizedTabName = Localization.GetString(this.TabPath + ".String", Localization.GlobalResourceFile, true); if (string.IsNullOrEmpty(localizedTabName)) { - localizedTabName = TabName; + localizedTabName = this.TabName; } - if (!_localizedTabNameDictionary.ContainsKey(key)) + if (!this._localizedTabNameDictionary.ContainsKey(key)) { - _localizedTabNameDictionary.Add(key, localizedTabName.Trim()); + this._localizedTabNameDictionary.Add(key, localizedTabName.Trim()); } } } @@ -441,14 +435,15 @@ public Dictionary LocalizedTabs { get { - if (_localizedTabs == null) + if (this._localizedTabs == null) { - _localizedTabs = - (from kvp in TabController.Instance.GetTabsByPortal(PortalID) - where kvp.Value.DefaultLanguageGuid == UniqueId && LocaleController.Instance.GetLocale(PortalID, kvp.Value.CultureCode) != null + this._localizedTabs = + (from kvp in TabController.Instance.GetTabsByPortal(this.PortalID) + where kvp.Value.DefaultLanguageGuid == this.UniqueId && LocaleController.Instance.GetLocale(this.PortalID, kvp.Value.CultureCode) != null select kvp.Value).ToDictionary(t => t.CultureCode); } - return _localizedTabs; + + return this._localizedTabs; } } @@ -457,28 +452,31 @@ public string SkinDoctype { get { - if (string.IsNullOrEmpty(SkinSrc) == false && string.IsNullOrEmpty(_skinDoctype)) + if (string.IsNullOrEmpty(this.SkinSrc) == false && string.IsNullOrEmpty(this._skinDoctype)) { - _skinDoctype = CheckIfDoctypeConfigExists(); - if (string.IsNullOrEmpty(_skinDoctype)) + this._skinDoctype = this.CheckIfDoctypeConfigExists(); + if (string.IsNullOrEmpty(this._skinDoctype)) { - _skinDoctype = Host.Host.DefaultDocType; + this._skinDoctype = Host.Host.DefaultDocType; } } - return _skinDoctype; + + return this._skinDoctype; } + set { - _skinDoctype = value; + this._skinDoctype = value; } } - [XmlArray("tabpermissions"), XmlArrayItem("permission")] + [XmlArray("tabpermissions")] + [XmlArrayItem("permission")] public TabPermissionCollection TabPermissions { get { - return _permissions ?? (_permissions = new TabPermissionCollection(TabPermissionController.GetTabPermissions(TabID, PortalID))); + return this._permissions ?? (this._permissions = new TabPermissionCollection(TabPermissionController.GetTabPermissions(this.TabID, this.PortalID))); } } @@ -487,7 +485,7 @@ public Hashtable TabSettings { get { - return _settings ?? (_settings = (TabID == Null.NullInteger) ? new Hashtable() : TabController.Instance.GetTabSettings(TabID)); + return this._settings ?? (this._settings = (this.TabID == Null.NullInteger) ? new Hashtable() : TabController.Instance.GetTabSettings(this.TabID)); } } @@ -496,20 +494,16 @@ public TabType TabType { get { - return Globals.GetURLType(Url); + return Globals.GetURLType(this.Url); } } - #endregion - - #region Url Properties - [XmlIgnore] public List AliasSkins { get { - return _aliasSkins ?? (_aliasSkins = (TabID == Null.NullInteger) ? new List() : TabController.Instance.GetAliasSkins(TabID, PortalID)); + return this._aliasSkins ?? (this._aliasSkins = (this.TabID == Null.NullInteger) ? new List() : TabController.Instance.GetAliasSkins(this.TabID, this.PortalID)); } } @@ -518,7 +512,7 @@ public Dictionary CustomAliases { get { - return _customAliases ?? (_customAliases = (TabID == Null.NullInteger) ? new Dictionary() : TabController.Instance.GetCustomAliases(TabID, PortalID)); + return this._customAliases ?? (this._customAliases = (this.TabID == Null.NullInteger) ? new Dictionary() : TabController.Instance.GetCustomAliases(this.TabID, this.PortalID)); } } @@ -531,40 +525,40 @@ public string FullUrl Thread.CurrentThread.CurrentCulture); string fullUrl; - using (_fullUrlDictionary.GetReadLock()) + using (this._fullUrlDictionary.GetReadLock()) { - _fullUrlDictionary.TryGetValue(key, out fullUrl); + this._fullUrlDictionary.TryGetValue(key, out fullUrl); } - if (String.IsNullOrEmpty(fullUrl)) + if (string.IsNullOrEmpty(fullUrl)) { - using (_fullUrlDictionary.GetWriteLock()) + using (this._fullUrlDictionary.GetWriteLock()) { - switch (TabType) + switch (this.TabType) { case TabType.Normal: - //normal tab - fullUrl = TestableGlobals.Instance.NavigateURL(TabID, IsSuperTab); + // normal tab + fullUrl = TestableGlobals.Instance.NavigateURL(this.TabID, this.IsSuperTab); break; case TabType.Tab: - //alternate tab url - fullUrl = TestableGlobals.Instance.NavigateURL(Convert.ToInt32(Url)); + // alternate tab url + fullUrl = TestableGlobals.Instance.NavigateURL(Convert.ToInt32(this.Url)); break; case TabType.File: - //file url - fullUrl = TestableGlobals.Instance.LinkClick(Url, TabID, Null.NullInteger); + // file url + fullUrl = TestableGlobals.Instance.LinkClick(this.Url, this.TabID, Null.NullInteger); break; case TabType.Url: - //external url - fullUrl = Url; + // external url + fullUrl = this.Url; break; } - if (!_fullUrlDictionary.ContainsKey(key)) + if (!this._fullUrlDictionary.ContainsKey(key)) { if (fullUrl != null) { - _fullUrlDictionary.Add(key, fullUrl.Trim()); + this._fullUrlDictionary.Add(key, fullUrl.Trim()); } } } @@ -585,7 +579,7 @@ public List TabUrls { get { - return _tabUrls ?? (_tabUrls = (TabID == Null.NullInteger) ? new List() : TabController.Instance.GetTabUrls(TabID, PortalID)); + return this._tabUrls ?? (this._tabUrls = (this.TabID == Null.NullInteger) ? new List() : TabController.Instance.GetTabUrls(this.TabID, this.PortalID)); } } @@ -595,9 +589,13 @@ public List TabUrls [XmlIgnore] public bool UseBaseFriendlyUrls { get; set; } - #endregion - - #region IPropertyAccess Members + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { @@ -613,6 +611,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } + propertyNotFound = true; string result = string.Empty; @@ -621,161 +620,264 @@ public string GetProperty(string propertyName, string format, CultureInfo format { case "tabid": propertyNotFound = false; - result = (TabID.ToString(outputFormat, formatProvider)); + result = this.TabID.ToString(outputFormat, formatProvider); break; case "taborder": isPublic = false; propertyNotFound = false; - result = (TabOrder.ToString(outputFormat, formatProvider)); + result = this.TabOrder.ToString(outputFormat, formatProvider); break; case "portalid": propertyNotFound = false; - result = (PortalID.ToString(outputFormat, formatProvider)); + result = this.PortalID.ToString(outputFormat, formatProvider); break; case "tabname": propertyNotFound = false; - result = PropertyAccess.FormatString(LocalizedTabName, format); + result = PropertyAccess.FormatString(this.LocalizedTabName, format); break; case "isvisible": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsVisible, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsVisible, formatProvider); break; case "parentid": isPublic = false; propertyNotFound = false; - result = (ParentId.ToString(outputFormat, formatProvider)); + result = this.ParentId.ToString(outputFormat, formatProvider); break; case "level": isPublic = false; propertyNotFound = false; - result = (Level.ToString(outputFormat, formatProvider)); + result = this.Level.ToString(outputFormat, formatProvider); break; case "iconfile": propertyNotFound = false; - result = PropertyAccess.FormatString(IconFile, format); + result = PropertyAccess.FormatString(this.IconFile, format); break; case "iconfilelarge": propertyNotFound = false; - result = PropertyAccess.FormatString(IconFileLarge, format); + result = PropertyAccess.FormatString(this.IconFileLarge, format); break; case "disablelink": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(DisableLink, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.DisableLink, formatProvider); break; case "title": propertyNotFound = false; - result = PropertyAccess.FormatString(Title, format); + result = PropertyAccess.FormatString(this.Title, format); break; case "description": propertyNotFound = false; - result = PropertyAccess.FormatString(Description, format); + result = PropertyAccess.FormatString(this.Description, format); break; case "keywords": propertyNotFound = false; - result = PropertyAccess.FormatString(KeyWords, format); + result = PropertyAccess.FormatString(this.KeyWords, format); break; case "isdeleted": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsDeleted, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsDeleted, formatProvider); break; case "url": propertyNotFound = false; - result = PropertyAccess.FormatString(Url, format); + result = PropertyAccess.FormatString(this.Url, format); break; case "skinsrc": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(SkinSrc, format); + result = PropertyAccess.FormatString(this.SkinSrc, format); break; case "containersrc": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(ContainerSrc, format); + result = PropertyAccess.FormatString(this.ContainerSrc, format); break; case "tabpath": propertyNotFound = false; - result = PropertyAccess.FormatString(TabPath, format); + result = PropertyAccess.FormatString(this.TabPath, format); break; case "startdate": isPublic = false; propertyNotFound = false; - result = (StartDate.ToString(outputFormat, formatProvider)); + result = this.StartDate.ToString(outputFormat, formatProvider); break; case "enddate": isPublic = false; propertyNotFound = false; - result = (EndDate.ToString(outputFormat, formatProvider)); + result = this.EndDate.ToString(outputFormat, formatProvider); break; case "haschildren": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(HasChildren, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.HasChildren, formatProvider); break; case "refreshinterval": isPublic = false; propertyNotFound = false; - result = (RefreshInterval.ToString(outputFormat, formatProvider)); + result = this.RefreshInterval.ToString(outputFormat, formatProvider); break; case "pageheadtext": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(PageHeadText, format); + result = PropertyAccess.FormatString(this.PageHeadText, format); break; case "skinpath": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(SkinPath, format); + result = PropertyAccess.FormatString(this.SkinPath, format); break; case "skindoctype": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(SkinDoctype, format); + result = PropertyAccess.FormatString(this.SkinDoctype, format); break; case "containerpath": isPublic = false; propertyNotFound = false; - result = PropertyAccess.FormatString(ContainerPath, format); + result = PropertyAccess.FormatString(this.ContainerPath, format); break; case "issupertab": isPublic = false; propertyNotFound = false; - result = (PropertyAccess.Boolean2LocalizedYesNo(IsSuperTab, formatProvider)); + result = PropertyAccess.Boolean2LocalizedYesNo(this.IsSuperTab, formatProvider); break; case "fullurl": propertyNotFound = false; - result = PropertyAccess.FormatString(FullUrl, format); + result = PropertyAccess.FormatString(this.FullUrl, format); break; case "sitemappriority": propertyNotFound = false; - result = PropertyAccess.FormatString(SiteMapPriority.ToString(), format); + result = PropertyAccess.FormatString(this.SiteMapPriority.ToString(), format); break; } + if (!isPublic && currentScope != Scope.Debug) { propertyNotFound = true; result = PropertyAccess.ContentLocked; } + return result; } - public CacheLevel Cacheability + public TabInfo Clone() { - get + var clonedTab = new TabInfo(this._localizedTabNameDictionary, this._fullUrlDictionary) + { + TabID = this.TabID, + TabOrder = this.TabOrder, + PortalID = this.PortalID, + TabName = this.TabName, + IsVisible = this.IsVisible, + HasBeenPublished = this.HasBeenPublished, + ParentId = this.ParentId, + Level = this.Level, + IconFile = this.IconFileRaw, + IconFileLarge = this.IconFileLargeRaw, + DisableLink = this.DisableLink, + Title = this.Title, + Description = this.Description, + KeyWords = this.KeyWords, + IsDeleted = this.IsDeleted, + Url = this.Url, + SkinSrc = this.SkinSrc, + ContainerSrc = this.ContainerSrc, + TabPath = this.TabPath, + StartDate = this.StartDate, + EndDate = this.EndDate, + HasChildren = this.HasChildren, + SkinPath = this.SkinPath, + ContainerPath = this.ContainerPath, + IsSuperTab = this.IsSuperTab, + RefreshInterval = this.RefreshInterval, + PageHeadText = this.PageHeadText, + IsSecure = this.IsSecure, + PermanentRedirect = this.PermanentRedirect, + IsSystem = this.IsSystem, + }; + + if (this.BreadCrumbs != null) { - return CacheLevel.fullyCacheable; + clonedTab.BreadCrumbs = new ArrayList(); + foreach (TabInfo t in this.BreadCrumbs) + { + clonedTab.BreadCrumbs.Add(t.Clone()); + } } + + this.Clone(clonedTab, this); + + // localized properties + clonedTab.UniqueId = this.UniqueId; + clonedTab.VersionGuid = this.VersionGuid; + clonedTab.DefaultLanguageGuid = this.DefaultLanguageGuid; + clonedTab.LocalizedVersionGuid = this.LocalizedVersionGuid; + clonedTab.CultureCode = this.CultureCode; + + clonedTab.Panes = new ArrayList(); + clonedTab.Modules = this._modules; + + return clonedTab; } - #endregion + /// ----------------------------------------------------------------------------- + /// + /// Fills a TabInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public override void Fill(IDataReader dr) + { + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); + this.UniqueId = Null.SetNullGuid(dr["UniqueId"]); + this.VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); + this.DefaultLanguageGuid = Null.SetNullGuid(dr["DefaultLanguageGuid"]); + this.LocalizedVersionGuid = Null.SetNullGuid(dr["LocalizedVersionGuid"]); + this.CultureCode = Null.SetNullString(dr["CultureCode"]); + + this.TabOrder = Null.SetNullInteger(dr["TabOrder"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.TabName = Null.SetNullString(dr["TabName"]); + this.IsVisible = Null.SetNullBoolean(dr["IsVisible"]); + this.HasBeenPublished = Null.SetNullBoolean(dr["HasBeenPublished"]); + this.ParentId = Null.SetNullInteger(dr["ParentId"]); + this.Level = Null.SetNullInteger(dr["Level"]); + this.IconFile = Null.SetNullString(dr["IconFile"]); + this.IconFileLarge = Null.SetNullString(dr["IconFileLarge"]); + this.DisableLink = Null.SetNullBoolean(dr["DisableLink"]); + this.Title = Null.SetNullString(dr["Title"]); + this.Description = Null.SetNullString(dr["Description"]); + this.KeyWords = Null.SetNullString(dr["KeyWords"]); + this.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); + this.Url = Null.SetNullString(dr["Url"]); + this.SkinSrc = Null.SetNullString(dr["SkinSrc"]); + this.ContainerSrc = Null.SetNullString(dr["ContainerSrc"]); + this.TabPath = Null.SetNullString(dr["TabPath"]); + this.StartDate = Null.SetNullDateTime(dr["StartDate"]); + this.EndDate = Null.SetNullDateTime(dr["EndDate"]); + this.HasChildren = Null.SetNullBoolean(dr["HasChildren"]); + this.RefreshInterval = Null.SetNullInteger(dr["RefreshInterval"]); + this.PageHeadText = Null.SetNullString(dr["PageHeadText"]); + this.IsSecure = Null.SetNullBoolean(dr["IsSecure"]); + this.PermanentRedirect = Null.SetNullBoolean(dr["PermanentRedirect"]); + this.SiteMapPriority = Null.SetNullSingle(dr["SiteMapPriority"]); + this.BreadCrumbs = null; + this.Modules = null; + this.IsSystem = Null.SetNullBoolean(dr["IsSystem"]); + } - #region Private Methods + internal void ClearTabUrls() + { + this._tabUrls = null; + } - private static Dictionary _docTypeCache = new Dictionary(); - private static ReaderWriterLockSlim _docTypeCacheLock = new ReaderWriterLockSlim(); - private static readonly Regex SkinSrcRegex = new Regex(@"([^/]+$)", RegexOptions.CultureInvariant); + internal void ClearSettingsCache() + { + this._settings = null; + } /// /// Look for skin level doctype configuration file, and inject the value into the top of default.aspx @@ -785,48 +887,58 @@ public CacheLevel Cacheability /// private string CheckIfDoctypeConfigExists() { - if (string.IsNullOrEmpty(SkinSrc)) + if (string.IsNullOrEmpty(this.SkinSrc)) + { return string.Empty; + } // loading an XML document from disk for each page request is expensive // let's implement some local caching - if (!_docTypeCache.ContainsKey(SkinSrc)) { + if (!_docTypeCache.ContainsKey(this.SkinSrc)) + { // appply lock after IF, locking is more expensive than worst case scenario (check disk twice) _docTypeCacheLock.EnterWriteLock(); - try { - - var docType = LoadDocType(); - _docTypeCache[SkinSrc] = docType == null ? string.Empty : docType.FirstChild.InnerText; - - } catch (Exception ex) { + try + { + var docType = this.LoadDocType(); + _docTypeCache[this.SkinSrc] = docType == null ? string.Empty : docType.FirstChild.InnerText; + } + catch (Exception ex) + { Exceptions.LogException(ex); - } finally { + } + finally + { _docTypeCacheLock.ExitWriteLock(); } } // return if file exists from cache _docTypeCacheLock.EnterReadLock(); - try { - return _docTypeCache[SkinSrc]; - } finally { + try + { + return _docTypeCache[this.SkinSrc]; + } + finally + { _docTypeCacheLock.ExitReadLock(); } } - XmlDocument LoadDocType() + private XmlDocument LoadDocType() { var xmlSkinDocType = new XmlDocument { XmlResolver = null }; // default to the skinname.doctype.xml to allow the individual skin to override the skin package - var skinFileName = HttpContext.Current.Server.MapPath(SkinSrc.Replace(".ascx", ".doctype.xml")); - if (File.Exists(skinFileName)) { + var skinFileName = HttpContext.Current.Server.MapPath(this.SkinSrc.Replace(".ascx", ".doctype.xml")); + if (File.Exists(skinFileName)) + { xmlSkinDocType.Load(skinFileName); return xmlSkinDocType; } // use the skin.doctype.xml file - var packageFileName = HttpContext.Current.Server.MapPath(SkinSrcRegex.Replace(SkinSrc, "skin.doctype.xml")); + var packageFileName = HttpContext.Current.Server.MapPath(SkinSrcRegex.Replace(this.SkinSrc, "skin.doctype.xml")); if (File.Exists(packageFileName)) { xmlSkinDocType.Load(packageFileName); @@ -839,11 +951,11 @@ XmlDocument LoadDocType() private void IconFileGetter(ref string iconFile, string iconRaw) { - if ((!String.IsNullOrEmpty(iconRaw) && iconRaw.StartsWith("~")) || PortalID == Null.NullInteger) + if ((!string.IsNullOrEmpty(iconRaw) && iconRaw.StartsWith("~")) || this.PortalID == Null.NullInteger) { iconFile = iconRaw; } - else if (iconFile == null && !String.IsNullOrEmpty(iconRaw) && PortalID != Null.NullInteger) + else if (iconFile == null && !string.IsNullOrEmpty(iconRaw) && this.PortalID != Null.NullInteger) { IFileInfo fileInfo; if (iconRaw.StartsWith("FileID=", StringComparison.InvariantCultureIgnoreCase)) @@ -853,157 +965,31 @@ private void IconFileGetter(ref string iconFile, string iconRaw) } else { - fileInfo = FileManager.Instance.GetFile(PortalID, iconRaw); + fileInfo = FileManager.Instance.GetFile(this.PortalID, iconRaw); } iconFile = fileInfo != null ? FileManager.Instance.GetUrl(fileInfo) : iconRaw; } } - #endregion - - #region Internal Methods - - internal void ClearTabUrls() - { - _tabUrls = null; - } - - internal void ClearSettingsCache() - { - _settings = null; - } - - #endregion - - #region Public Methods - - public TabInfo Clone() - { - var clonedTab = new TabInfo(_localizedTabNameDictionary, _fullUrlDictionary) - { - TabID = TabID, - TabOrder = TabOrder, - PortalID = PortalID, - TabName = TabName, - IsVisible = IsVisible, - HasBeenPublished = HasBeenPublished, - ParentId = ParentId, - Level = Level, - IconFile = IconFileRaw, - IconFileLarge = IconFileLargeRaw, - DisableLink = DisableLink, - Title = Title, - Description = Description, - KeyWords = KeyWords, - IsDeleted = IsDeleted, - Url = Url, - SkinSrc = SkinSrc, - ContainerSrc = ContainerSrc, - TabPath = TabPath, - StartDate = StartDate, - EndDate = EndDate, - HasChildren = HasChildren, - SkinPath = SkinPath, - ContainerPath = ContainerPath, - IsSuperTab = IsSuperTab, - RefreshInterval = RefreshInterval, - PageHeadText = PageHeadText, - IsSecure = IsSecure, - PermanentRedirect = PermanentRedirect, - IsSystem = IsSystem - }; - - if (BreadCrumbs != null) - { - clonedTab.BreadCrumbs = new ArrayList(); - foreach (TabInfo t in BreadCrumbs) - { - clonedTab.BreadCrumbs.Add(t.Clone()); - } - } - - Clone(clonedTab, this); - - //localized properties - clonedTab.UniqueId = UniqueId; - clonedTab.VersionGuid = VersionGuid; - clonedTab.DefaultLanguageGuid = DefaultLanguageGuid; - clonedTab.LocalizedVersionGuid = LocalizedVersionGuid; - clonedTab.CultureCode = CultureCode; - - clonedTab.Panes = new ArrayList(); - clonedTab.Modules = _modules; - - return clonedTab; - } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a TabInfo from a Data Reader - /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public override void Fill(IDataReader dr) - { - //Call the base classes fill method to populate base class proeprties - base.FillInternal(dr); - UniqueId = Null.SetNullGuid(dr["UniqueId"]); - VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); - DefaultLanguageGuid = Null.SetNullGuid(dr["DefaultLanguageGuid"]); - LocalizedVersionGuid = Null.SetNullGuid(dr["LocalizedVersionGuid"]); - CultureCode = Null.SetNullString(dr["CultureCode"]); - - TabOrder = Null.SetNullInteger(dr["TabOrder"]); - PortalID = Null.SetNullInteger(dr["PortalID"]); - TabName = Null.SetNullString(dr["TabName"]); - IsVisible = Null.SetNullBoolean(dr["IsVisible"]); - HasBeenPublished = Null.SetNullBoolean(dr["HasBeenPublished"]); - ParentId = Null.SetNullInteger(dr["ParentId"]); - Level = Null.SetNullInteger(dr["Level"]); - IconFile = Null.SetNullString(dr["IconFile"]); - IconFileLarge = Null.SetNullString(dr["IconFileLarge"]); - DisableLink = Null.SetNullBoolean(dr["DisableLink"]); - Title = Null.SetNullString(dr["Title"]); - Description = Null.SetNullString(dr["Description"]); - KeyWords = Null.SetNullString(dr["KeyWords"]); - IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); - Url = Null.SetNullString(dr["Url"]); - SkinSrc = Null.SetNullString(dr["SkinSrc"]); - ContainerSrc = Null.SetNullString(dr["ContainerSrc"]); - TabPath = Null.SetNullString(dr["TabPath"]); - StartDate = Null.SetNullDateTime(dr["StartDate"]); - EndDate = Null.SetNullDateTime(dr["EndDate"]); - HasChildren = Null.SetNullBoolean(dr["HasChildren"]); - RefreshInterval = Null.SetNullInteger(dr["RefreshInterval"]); - PageHeadText = Null.SetNullString(dr["PageHeadText"]); - IsSecure = Null.SetNullBoolean(dr["IsSecure"]); - PermanentRedirect = Null.SetNullBoolean(dr["PermanentRedirect"]); - SiteMapPriority = Null.SetNullSingle(dr["SiteMapPriority"]); - BreadCrumbs = null; - Modules = null; - IsSystem = Null.SetNullBoolean(dr["IsSystem"]); - } - public string GetCurrentUrl(string cultureCode) { string url = null; - if (_tabUrls != null && _tabUrls.Count > 0) + if (this._tabUrls != null && this._tabUrls.Count > 0) { - TabUrlInfo tabUrl = _tabUrls.CurrentUrl(cultureCode); + TabUrlInfo tabUrl = this._tabUrls.CurrentUrl(cultureCode); if (tabUrl != null) { url = tabUrl.Url; } } - return url ?? (""); + + return url ?? string.Empty; } public string GetTags() { - return string.Join(",", Terms.Select(t => t.Name)); + return string.Join(",", this.Terms.Select(t => t.Name)); } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs index cc5e5d85b79..0c430ba545f 100644 --- a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs @@ -1,26 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Framework; -using DotNetNuke.UI.Skins; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { - public class TabModulesController: ServiceLocator, ITabModulesController - { - #region Public Methods - + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Framework; + using DotNetNuke.UI.Skins; + + public class TabModulesController : ServiceLocator, ITabModulesController + { public ArrayList GetTabModules(TabInfo tab) { var objPaneModules = new Dictionary(); @@ -35,14 +34,17 @@ public ArrayList GetTabModules(TabInfo tab) { objPaneModules.Add(configuringModule.PaneName, 0); } + configuringModule.PaneModuleCount = 0; if (!configuringModule.IsDeleted) { objPaneModules[configuringModule.PaneName] = objPaneModules[configuringModule.PaneName] + 1; configuringModule.PaneModuleIndex = objPaneModules[configuringModule.PaneName] - 1; } + configuredModules.Add(configuringModule); } + foreach (ModuleInfo module in configuredModules) { module.PaneModuleCount = objPaneModules[module.PaneName]; @@ -51,7 +53,7 @@ public ArrayList GetTabModules(TabInfo tab) return configuredModules; } - public Dictionary GetTabModuleSettingsByName(string settingName) + public Dictionary GetTabModuleSettingsByName(string settingName) { var portalId = PortalSettings.Current.PortalId; var dataProvider = DataProvider.Instance(); @@ -67,6 +69,7 @@ public Dictionary GetTabModuleSettingsByName(string settingName) { result[dr.GetInt32(0)] = dr.GetString(1); } + return result; } }); @@ -76,7 +79,7 @@ public Dictionary GetTabModuleSettingsByName(string settingName) public IList GetTabModuleIdsBySetting(string settingName, string expectedValue) { - var items = GetTabModuleSettingsByName(settingName); + var items = this.GetTabModuleSettingsByName(settingName); var matches = items.Where(e => e.Value.Equals(expectedValue, StringComparison.CurrentCultureIgnoreCase)); var keyValuePairs = matches as KeyValuePair[] ?? matches.ToArray(); if (keyValuePairs.Any()) @@ -93,24 +96,29 @@ public IList GetTabModuleIdsBySetting(string settingName, string expectedVa { result.Add(dr.GetInt32(0)); } + return result; } + } + + protected override Func GetFactory() + { + return () => new TabModulesController(); } - - #endregion - - #region Private Methods + private static void ConfigureModule(ModuleInfo cloneModule, TabInfo tab) { if (Null.IsNull(cloneModule.StartDate)) { cloneModule.StartDate = DateTime.MinValue; } + if (Null.IsNull(cloneModule.EndDate)) { cloneModule.EndDate = DateTime.MaxValue; } - if (String.IsNullOrEmpty(cloneModule.ContainerSrc)) + + if (string.IsNullOrEmpty(cloneModule.ContainerSrc)) { cloneModule.ContainerSrc = tab.ContainerSrc; } @@ -126,19 +134,13 @@ private static IEnumerable GetModules(TabInfo tab) { return TabVersionBuilder.Instance.GetVersionModules(tab.TabID, urlVersion); } - + if (Globals.IsEditMode()) { return TabVersionBuilder.Instance.GetUnPublishedVersionModules(tab.TabID); } return TabVersionBuilder.Instance.GetCurrentModules(tab.TabID); - } - #endregion - - protected override Func GetFactory() - { - return () => new TabModulesController(); - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabMoveType.cs b/DNN Platform/Library/Entities/Tabs/TabMoveType.cs index b96d81c9cb4..67c6736b2fb 100644 --- a/DNN Platform/Library/Entities/Tabs/TabMoveType.cs +++ b/DNN Platform/Library/Entities/Tabs/TabMoveType.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { - ///----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : TabMoveType - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke + /// Class : TabMoveType + /// ----------------------------------------------------------------------------- /// - /// Identifies common tab move types + /// Identifies common tab move types. /// /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public enum TabMoveType { Up, @@ -21,6 +21,6 @@ public enum TabMoveType Top, Bottom, Promote, - Demote + Demote, } } diff --git a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs index e91507a9ac4..58b0ece57eb 100644 --- a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs @@ -1,31 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { - public class TabPublishingController: ServiceLocator, ITabPublishingController + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + + public class TabPublishingController : ServiceLocator, ITabPublishingController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabPublishingController)); public bool IsTabPublished(int tabID, int portalID) { - var allUsersRoleId = Int32.Parse(Globals.glbRoleAllUsers); + var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); var tab = TabController.Instance.GetTab(tabID, portalID); - var existPermission = GetAlreadyPermission(tab, "VIEW", allUsersRoleId); + var existPermission = this.GetAlreadyPermission(tab, "VIEW", allUsersRoleId); return existPermission != null && existPermission.AllowAccess; } @@ -42,11 +43,11 @@ public void SetTabPublishing(int tabID, int portalID, bool publish) if (publish) { - PublishTabInternal(tab); + this.PublishTabInternal(tab); } else { - UnpublishTabInternal(tab); + this.UnpublishTabInternal(tab); } } @@ -55,39 +56,42 @@ public bool CanPublishingBePerformed(int tabID, int portalID) var tab = TabController.Instance.GetTab(tabID, portalID); if (!TabPermissionController.CanAdminPage(tab)) { - return false; //User has no permission + return false; // User has no permission } - + Hashtable settings = TabController.Instance.GetTabSettings(tabID); if (settings["WorkflowID"] != null) { - return Convert.ToInt32(settings["WorkflowID"]) == 1; //If workflowID is 1, then the Page workflow is Direct Publish + return Convert.ToInt32(settings["WorkflowID"]) == 1; // If workflowID is 1, then the Page workflow is Direct Publish } - //If workflowID is 1, then the Page workflow is Direct Publish - //If WorkflowID is -1, then there is no Workflow setting + // If workflowID is 1, then the Page workflow is Direct Publish + // If WorkflowID is -1, then there is no Workflow setting var workflowID = Convert.ToInt32(PortalController.GetPortalSetting("WorkflowID", portalID, "-1")); return (workflowID == 1) || (workflowID == -1); - + } + + protected override Func GetFactory() + { + return () => new TabPublishingController(); } - - #region private Methods + private void PublishTabInternal(TabInfo tab) { - var allUsersRoleId = Int32.Parse(Globals.glbRoleAllUsers); + var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); - var existPermission = GetAlreadyPermission(tab, "VIEW", allUsersRoleId); + var existPermission = this.GetAlreadyPermission(tab, "VIEW", allUsersRoleId); if (existPermission != null) { tab.TabPermissions.Remove(existPermission); } - tab.TabPermissions.Add(GetTabPermissionByRole(tab.TabID, "VIEW", allUsersRoleId)); + tab.TabPermissions.Add(this.GetTabPermissionByRole(tab.TabID, "VIEW", allUsersRoleId)); TabPermissionController.SaveTabPermissions(tab); - ClearTabCache(tab); + this.ClearTabCache(tab); } - + private void UnpublishTabInternal(TabInfo tab) { var administratorsRoleID = PortalController.Instance.GetPortal(tab.PortalID).AdministratorRoleId; @@ -97,14 +101,16 @@ private void UnpublishTabInternal(TabInfo tab) { tab.TabPermissions.Remove(tab.TabPermissions.Cast().SingleOrDefault(p => p.TabPermissionID == tabPermissionId)); } + TabPermissionController.SaveTabPermissions(tab); - ClearTabCache(tab); + this.ClearTabCache(tab); } private void ClearTabCache(TabInfo tabInfo) { TabController.Instance.ClearCache(tabInfo.PortalID); - //Clear the Tab's Cached modules + + // Clear the Tab's Cached modules DataCache.ClearModuleCache(tabInfo.TabID); } @@ -120,23 +126,17 @@ private TabPermissionInfo GetAlreadyPermission(TabInfo tab, string permissionKey private TabPermissionInfo GetTabPermissionByRole(int tabID, string permissionKey, int roleID) { var permission = PermissionController.GetPermissionsByTab().Cast().SingleOrDefault(p => p.PermissionKey == permissionKey); - var tabPermission = new TabPermissionInfo - { - TabID = tabID, - PermissionID = permission.PermissionID, - PermissionKey = permission.PermissionKey, - PermissionName = permission.PermissionName, - RoleID = roleID, - UserID = Null.NullInteger, - AllowAccess = true - }; + var tabPermission = new TabPermissionInfo + { + TabID = tabID, + PermissionID = permission.PermissionID, + PermissionKey = permission.PermissionKey, + PermissionName = permission.PermissionName, + RoleID = roleID, + UserID = Null.NullInteger, + AllowAccess = true, + }; return tabPermission; - } - #endregion - - protected override Func GetFactory() - { - return () => new TabPublishingController(); - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabType.cs b/DNN Platform/Library/Entities/Tabs/TabType.cs index 24fe6030d14..39b83b79763 100644 --- a/DNN Platform/Library/Entities/Tabs/TabType.cs +++ b/DNN Platform/Library/Entities/Tabs/TabType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { public enum TabType @@ -10,6 +10,6 @@ public enum TabType Normal, Tab, Url, - Member + Member, } } diff --git a/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs b/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs index 2115f2c11d2..af4ce973ff1 100644 --- a/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs @@ -1,42 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { - /// - ///Class to represent a TabUrl object - /// - [Serializable] //584 support sql session state + using System; + + /// + /// Class to represent a TabUrl object. + /// + [Serializable] // 584 support sql session state public class TabUrlInfo - { - #region Constructors - + { public TabUrlInfo() { - PortalAliasUsage = PortalAliasUsageType.Default; - } - - #endregion - - #region Public Properties - + this.PortalAliasUsage = PortalAliasUsageType.Default; + } + public string CultureCode { get; set; } + public string HttpStatus { get; set; } + public bool IsSystem { get; set; } + public int PortalAliasId { get; set; } + public PortalAliasUsageType PortalAliasUsage { get; set; } + public string QueryString { get; set; } + public int SeqNum { get; set; } + public int TabId { get; set; } + public int? CreatedByUserId { get; set; } + public int? LastModifiedByUserId { get; set; } - public string Url { get; set; } - - #endregion - + public string Url { get; set; } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs index b03726aaeec..dab4342acfc 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs @@ -1,31 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions.Exceptions { + using System; + /// - /// Exception to notify error about managing tab versions + /// Exception to notify error about managing tab versions. /// public class DnnTabVersionException : ApplicationException - { - /// + { + /// + /// Initializes a new instance of the class. /// Constructs an instance of class with the specified message. /// - /// The message to associate with the exception - public DnnTabVersionException(string message) : base(message) + /// The message to associate with the exception. + public DnnTabVersionException(string message) + : base(message) { - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Constructs an instance of class with the specified message and /// inner exception. /// - /// The message to associate with the exception - /// The exception which caused this error - public DnnTabVersionException(string message, Exception innerException) : base(message, innerException) + /// The message to associate with the exception. + /// The exception which caused this error. + public DnnTabVersionException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs index a2f37cfa449..ab49c4277c5 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs @@ -1,115 +1,115 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + public interface ITabVersionBuilder { /// - /// Creates a new Tab Version checking current portal settings - /// - /// This method will need the Portal Id from the current context - /// Tab Id whose version will be added - /// User Id which creates the version - /// TabVersion filled with the new version data + /// Creates a new Tab Version checking current portal settings. + /// + /// This method will need the Portal Id from the current context. + /// Tab Id whose version will be added. + /// User Id which creates the version. + /// TabVersion filled with the new version data. TabVersion CreateNewVersion(int tabId, int createdByUserId); /// - /// Creates a new Tab Version + /// Creates a new Tab Version. /// - /// Tab Id whose version will be added - /// User Id which creates the version - /// TabVersion filled with the new version data + /// Tab Id whose version will be added. + /// User Id which creates the version. + /// TabVersion filled with the new version data. TabVersion CreateNewVersion(int portalid, int tabId, int createdByUserId); - - + /// - /// Publish a Tab Version + /// Publish a Tab Version. /// - /// Portal Id where the version is - /// Tab Id whose version will be published - /// User Id which publishes the version + /// Portal Id where the version is. + /// Tab Id whose version will be published. + /// User Id which publishes the version. void Publish(int portalId, int tabId, int createdByUserId); /// /// Discards a Tab Version. If the tab only has an unpublished version, the page will keep but with no content and not published. /// - /// Tab Id whose version will be discarded - /// User Id which discards the version + /// Tab Id whose version will be discarded. + /// User Id which discards the version. void Discard(int tabId, int createdByUserId); - + /// - /// Get all Modules Info associated with an specific version - /// - /// Tab Id to be checked - /// Version Number whose modules will be get - /// List of ModuleInfo objects + /// Get all Modules Info associated with an specific version. + /// + /// Tab Id to be checked. + /// Version Number whose modules will be get. + /// List of ModuleInfo objects. IEnumerable GetVersionModules(int tabId, int versionNumber); /// - /// Get the current pusblished version of the page + /// Get the current pusblished version of the page. /// - /// The Tab Id to be queried - /// If true, the method will not use the Caching Storage - /// TabVersion filled with the current version data - /// If Tab has not a published version yet, it will return null + /// The Tab Id to be queried. + /// If true, the method will not use the Caching Storage. + /// TabVersion filled with the current version data. + /// If Tab has not a published version yet, it will return null. TabVersion GetCurrentVersion(int tabId, bool ignoreCache = false); - + /// - /// Get the unpublished version or Null if Tab has not any unpublished version + /// Get the unpublished version or Null if Tab has not any unpublished version. /// /// - /// TabVersion filled with the unpublished version data - /// If Tab has not an unpublished version yet, it will return null + /// TabVersion filled with the unpublished version data. + /// If Tab has not an unpublished version yet, it will return null. TabVersion GetUnPublishedVersion(int tabId); - + /// /// Get all ModuleInfo objects associated with the unpublished version of a page. - /// + /// /// - /// List of ModuleInfo objects + /// List of ModuleInfo objects. IEnumerable GetUnPublishedVersionModules(int tabId); /// - /// Get all Modules Info associated with the last published version of the page - /// - /// Tab Id w - /// List of ModuleInfo objects + /// Get all Modules Info associated with the last published version of the page. + /// + /// Tab Id w. + /// List of ModuleInfo objects. IEnumerable GetCurrentModules(int tabId); - + /// - /// Rolls back an existing version + /// Rolls back an existing version. /// - /// The Tab Id to be queried - /// User Id which rolls back the version - /// Version Number of the version to be rolled back + /// The Tab Id to be queried. + /// User Id which rolls back the version. + /// Version Number of the version to be rolled back. + /// TabVersion RollBackVesion(int tabId, int createdByUserId, int versionNumber); /// - /// Deletes an existing Tab Version + /// Deletes an existing Tab Version. /// - /// The Tab Id to be queried - /// User Id which deletes the version - /// Version Number of the version to be deleted + /// The Tab Id to be queried. + /// User Id which deletes the version. + /// Version Number of the version to be deleted. void DeleteVersion(int tabId, int createdByUserId, int version); /// - /// Setup a first version for existing tab with modules. This method is used to create version 1 for pages created when versioning was not enabled + /// Setup a first version for existing tab with modules. This method is used to create version 1 for pages created when versioning was not enabled. /// - /// portalId - /// tabId + /// portalId. + /// tabId. void SetupFirstVersionForExistingTab(int portalId, int tabId); /// - /// Get the latest version or 1 if module is not versionable + /// Get the latest version or 1 if module is not versionable. /// - /// The ModuleInfo to be queried - /// The latest version of the module + /// The ModuleInfo to be queried. + /// The latest version of the module. int GetModuleContentLatestVersion(ModuleInfo module); - } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionController.cs index 1602ea33ea7..f63857285c8 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionController.cs @@ -1,74 +1,74 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { + using System.Collections.Generic; + /// - /// Controller interface responsible to manage tab versions + /// Controller interface responsible to manage tab versions. /// public interface ITabVersionController { /// - /// Gets a Tab Version object of an existing Tab - /// - /// The Tab Version Id to be get - /// The Tab Id to be queried - /// If true, the method will not use the Caching Storage - /// TabVersion filled with the specific version data + /// Gets a Tab Version object of an existing Tab. + /// + /// The Tab Version Id to be get. + /// The Tab Id to be queried. + /// If true, the method will not use the Caching Storage. + /// TabVersion filled with the specific version data. TabVersion GetTabVersion(int tabVersionId, int tabId, bool ignoreCache = false); /// - /// Gets all Tab Versions of an existing Tab - /// - /// Tha Tab ID to be quiered - /// If true, the method will not use the Caching Storage - /// List of TabVersion objects + /// Gets all Tab Versions of an existing Tab. + /// + /// Tha Tab ID to be quiered. + /// If true, the method will not use the Caching Storage. + /// List of TabVersion objects. IEnumerable GetTabVersions(int tabId, bool ignoreCache = false); /// - /// Saves a Tab Version object. Adds or updates an existing one - /// - /// TabVersion object to be saved - /// User Id who creates the TabVersion + /// Saves a Tab Version object. Adds or updates an existing one. + /// + /// TabVersion object to be saved. + /// User Id who creates the TabVersion. void SaveTabVersion(TabVersion tabVersion, int createdByUserId); /// - /// Saves a Tab Version object. Adds or updates an existing one - /// - /// TabVersion object to be saved - /// User Id who creates the TabVersion - /// User Id who modifies the TabVersion + /// Saves a Tab Version object. Adds or updates an existing one. + /// + /// TabVersion object to be saved. + /// User Id who creates the TabVersion. + /// User Id who modifies the TabVersion. void SaveTabVersion(TabVersion tabVersion, int createdByUserId, int modifiedByUserId); - + /// - /// Saves a Tab Version object. Adds or updates an existing one - /// - /// TabVersion object to be saved + /// Saves a Tab Version object. Adds or updates an existing one. + /// + /// TabVersion object to be saved. void SaveTabVersion(TabVersion tabVersion); /// - /// Creates a new version for a existing Tab + /// Creates a new version for a existing Tab. /// - /// The Tab Id to be queried - /// User Id who creates the version - /// If true, the version is automatically published - /// TabVersion filled with the new version data + /// The Tab Id to be queried. + /// User Id who creates the version. + /// If true, the version is automatically published. + /// TabVersion filled with the new version data. TabVersion CreateTabVersion(int tabId, int createdByUserId, bool isPublished = false); - + /// - /// Deletes a Tab Version + /// Deletes a Tab Version. /// - /// The Tab Id to be queried - /// The TabVersion Id to be deleted + /// The Tab Id to be queried. + /// The TabVersion Id to be deleted. void DeleteTabVersion(int tabId, int tabVersionId); /// - /// Deletes a Tab Version details for a module + /// Deletes a Tab Version details for a module. /// - /// The Module Id to be queried + /// The Module Id to be queried. void DeleteTabVersionDetailByModule(int moduleId); } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionDetailController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionDetailController.cs index 8f3ba06ea28..d1cd8138c31 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionDetailController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionDetailController.cs @@ -1,67 +1,67 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { + using System.Collections.Generic; + /// - /// Interface controller responsible to manage the tab version details + /// Interface controller responsible to manage the tab version details. /// public interface ITabVersionDetailController { /// - /// Gets a Tab Version Detail object of an existing Tab Version - /// - /// The Tab Version Detail Id to be get - /// The Tab Version Id to be queried - /// If true, the method will not use the Caching Storage - /// TabVersionDetail object filled with specific data + /// Gets a Tab Version Detail object of an existing Tab Version. + /// + /// The Tab Version Detail Id to be get. + /// The Tab Version Id to be queried. + /// If true, the method will not use the Caching Storage. + /// TabVersionDetail object filled with specific data. TabVersionDetail GetTabVersionDetail(int tabVersionDetailId, int tabVersionId, bool ignoreCache = false); /// - /// Get all Tab Version Details of a existing version and earlier + /// Get all Tab Version Details of a existing version and earlier. /// - /// The Tab Id to be queried - /// The Tab Id to be queried - /// List of TabVersionDetail objects + /// The Tab Id to be queried. + /// The Tab Id to be queried. + /// List of TabVersionDetail objects. IEnumerable GetVersionHistory(int tabId, int version); - + /// - /// Gets all TabVersionDetail objects of an existing TabVersion - /// - /// Tha TabVersion Id to be quiered - /// If true, the method will not use the Caching Storage - /// List of TabVersionDetail objects + /// Gets all TabVersionDetail objects of an existing TabVersion. + /// + /// Tha TabVersion Id to be quiered. + /// If true, the method will not use the Caching Storage. + /// List of TabVersionDetail objects. IEnumerable GetTabVersionDetails(int tabVersionId, bool ignoreCache = false); /// - /// Saves a Tab Version Detail object. Adds or updates an existing one - /// - /// TabVersionDetail object to be saved + /// Saves a Tab Version Detail object. Adds or updates an existing one. + /// + /// TabVersionDetail object to be saved. void SaveTabVersionDetail(TabVersionDetail tabVersionDetail); - + /// - /// Saves a TabVersionDetail object. Adds or updates an existing one - /// - /// TabVersionDetail object to be saved - /// User Id who creates the TabVersionDetail + /// Saves a TabVersionDetail object. Adds or updates an existing one. + /// + /// TabVersionDetail object to be saved. + /// User Id who creates the TabVersionDetail. void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdByUserId); /// - /// Saves a TabVersionDetail object. Adds or updates an existing one - /// - /// TabVersionDetail object to be saved - /// User Id who created the TabVersionDetail - /// User Id who modifies the TabVersionDetail + /// Saves a TabVersionDetail object. Adds or updates an existing one. + /// + /// TabVersionDetail object to be saved. + /// User Id who created the TabVersionDetail. + /// User Id who modifies the TabVersionDetail. void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdByUserId, int modifiedByUserId); /// - /// Deletes a TabVersionDetail + /// Deletes a TabVersionDetail. /// - /// The TabVersion Id to be queried - /// The TabVersionDetail Id to be deleted + /// The TabVersion Id to be queried. + /// The TabVersionDetail Id to be deleted. void DeleteTabVersionDetail(int tabVersionId, int tabVersionDetailId); /// diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionSettings.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionSettings.cs index d73a7738768..2aa1deb8f71 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionSettings.cs @@ -1,47 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { /// - /// Class responsible to provide settings for Tab Versioning + /// Class responsible to provide settings for Tab Versioning. /// public interface ITabVersionSettings { /// - /// Get the maximum number of version that the portal will kept for a tab + /// Get the maximum number of version that the portal will kept for a tab. /// - /// Portal Id - /// Max number of version + /// Portal Id. + /// Max number of version. int GetMaxNumberOfVersions(int portalId); /// - /// Set the maximum number of version that the portal will kept for a tab + /// Set the maximum number of version that the portal will kept for a tab. /// - /// Portal Id - /// Max number of version + /// Portal Id. + /// Max number of version. void SetMaxNumberOfVersions(int portalId, int maxNumberOfVersions); /// - /// Set the status of the tab versioning for the portal + /// Set the status of the tab versioning for the portal. /// - /// Portal Id - /// true for enable it, false otherwise + /// Portal Id. + /// true for enable it, false otherwise. void SetEnabledVersioningForPortal(int portalId, bool enabled); /// - /// Set the status of the tab versioning for a tab + /// Set the status of the tab versioning for a tab. /// - /// Tab Id - /// true for enable it, false otherwise + /// Tab Id. + /// true for enable it, false otherwise. void SetEnabledVersioningForTab(int tabId, bool enabled); /// - /// Get the status of the tab versioning for the portal + /// Get the status of the tab versioning for the portal. /// - /// Portal Id - /// Returns true if tab versioning is enabled for the portal, false otherwise + /// Portal Id. + /// Returns true if tab versioning is enabled for the portal, false otherwise. bool IsVersioningEnabled(int portalId); /// @@ -50,16 +50,16 @@ public interface ITabVersionSettings /// /// If versioning is disabled at portal level, the versioning for tabs will be disabled too. /// - /// Portal Id - /// Tab Id to be checked - /// Returns true if tab versioning is enabled for the portal and for the tab, false otherwise + /// Portal Id. + /// Tab Id to be checked. + /// Returns true if tab versioning is enabled for the portal and for the tab, false otherwise. bool IsVersioningEnabled(int portalId, int tabId); /// - /// Get the query string parameter name to especify a Tab Version using the version number (i.e.: ?version=1) + /// Get the query string parameter name to especify a Tab Version using the version number (i.e.: ?version=1). /// - /// Portal Id - /// Query string parameter name + /// Portal Id. + /// Query string parameter name. string GetTabVersionQueryStringParameter(int portalId); } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs index 3b317672083..c7c1c6890f3 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs @@ -1,43 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { - /// - ///Class to represent a Tab Version object - /// + using System; + + /// + /// Class to represent a Tab Version object. + /// [Serializable] public class TabVersion : BaseEntityInfo - { - #region Public Properties - + { /// - /// Id of the TabVersion object + /// Gets or sets id of the TabVersion object. /// public int TabVersionId { get; set; } /// - /// Id of the related Tab + /// Gets or sets id of the related Tab. /// public int TabId { get; set; } /// - /// Version number of the TabVersion + /// Gets or sets version number of the TabVersion. /// public int Version { get; set; } /// - /// Timestamp of the version + /// Gets or sets timestamp of the version. /// public DateTime TimeStamp { get; set; } /// - /// True if the version is published. False if it is not published yet + /// Gets or sets a value indicating whether true if the version is published. False if it is not published yet. /// - public bool IsPublished { get; set; } - #endregion + public bool IsPublished { get; set; } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs index 3d878a5ce46..bc3a2f92985 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs @@ -1,207 +1,204 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs.TabVersions.Exceptions; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { + using System; + using System.Collections.Generic; + using System.Data.SqlClient; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs.TabVersions.Exceptions; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + public class TabVersionBuilder : ServiceLocator, ITabVersionBuilder { + private const int DefaultVersionNumber = 1; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabVersionBuilder)); - private const int DefaultVersionNumber = 1; - - #region Members private readonly ITabController _tabController; private readonly IModuleController _moduleController; private readonly ITabVersionSettings _tabVersionSettings; private readonly ITabVersionController _tabVersionController; private readonly ITabVersionDetailController _tabVersionDetailController; - private readonly PortalSettings _portalSettings; - #endregion - - #region Constructor + private readonly PortalSettings _portalSettings; + public TabVersionBuilder() { - _tabController = TabController.Instance; - _moduleController = ModuleController.Instance; - _tabVersionSettings = TabVersionSettings.Instance; - _tabVersionController = TabVersionController.Instance; - _tabVersionDetailController = TabVersionDetailController.Instance; - _portalSettings = PortalSettings.Current; - } - #endregion - - #region Public Methods - + this._tabController = TabController.Instance; + this._moduleController = ModuleController.Instance; + this._tabVersionSettings = TabVersionSettings.Instance; + this._tabVersionController = TabVersionController.Instance; + this._tabVersionDetailController = TabVersionDetailController.Instance; + this._portalSettings = PortalSettings.Current; + } + public void SetupFirstVersionForExistingTab(int portalId, int tabId) { - if (!_tabVersionSettings.IsVersioningEnabled(portalId, tabId)) + if (!this._tabVersionSettings.IsVersioningEnabled(portalId, tabId)) { return; } // Check if already exist at least one version for the tab - if (_tabVersionController.GetTabVersions(tabId).Any()) + if (this._tabVersionController.GetTabVersions(tabId).Any()) { return; } - var tab = _tabController.GetTab(tabId, portalId); - var modules = _moduleController.GetTabModules(tabId).Where(m => m.Value.IsDeleted == false).Select(m => m.Value).ToArray(); - + var tab = this._tabController.GetTab(tabId, portalId); + var modules = this._moduleController.GetTabModules(tabId).Where(m => m.Value.IsDeleted == false).Select(m => m.Value).ToArray(); + // Check if the page has modules if (!modules.Any()) { return; } - CreateFirstTabVersion(tabId, tab, modules); + this.CreateFirstTabVersion(tabId, tab, modules); } - + public void Publish(int portalId, int tabId, int createdByUserId) { - var tabVersion = GetUnPublishedVersion(tabId); + var tabVersion = this.GetUnPublishedVersion(tabId); if (tabVersion == null) - { - throw new InvalidOperationException(String.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); + { + throw new InvalidOperationException(string.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); } + if (tabVersion.IsPublished) { - throw new InvalidOperationException(String.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); + throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); } - var previousPublishVersion = GetCurrentVersion(tabId); - PublishVersion(portalId, tabId, createdByUserId, tabVersion); + var previousPublishVersion = this.GetCurrentVersion(tabId); + this.PublishVersion(portalId, tabId, createdByUserId, tabVersion); - if (!_tabVersionSettings.IsVersioningEnabled(portalId, tabId) + if (!this._tabVersionSettings.IsVersioningEnabled(portalId, tabId) && previousPublishVersion != null) { - ForceDeleteVersion(tabId, previousPublishVersion.Version); + this.ForceDeleteVersion(tabId, previousPublishVersion.Version); } } public void Discard(int tabId, int createdByUserId) { - var tabVersion = GetUnPublishedVersion(tabId); + var tabVersion = this.GetUnPublishedVersion(tabId); if (tabVersion == null) { - throw new InvalidOperationException(String.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); + throw new InvalidOperationException(string.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); } + if (tabVersion.IsPublished) { - throw new InvalidOperationException(String.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); - } - DiscardVersion(tabId, tabVersion); - } - - private void DiscardVersion(int tabId, TabVersion tabVersion) - { - var unPublishedDetails = _tabVersionDetailController.GetTabVersionDetails(tabVersion.TabVersionId); - - var currentPublishedVersion = GetCurrentVersion(tabId); - TabVersionDetail[] publishedChanges = null; - - if (currentPublishedVersion != null) - { - publishedChanges = GetVersionModulesDetails(tabId, GetCurrentVersion(tabId).Version).ToArray(); - } - - foreach (var unPublishedDetail in unPublishedDetails) - { - if (publishedChanges == null) - { - DiscardDetailWithoutPublishedTabVersions(tabId, unPublishedDetail); - } - else - { - DiscardDetailWithPublishedTabVersions(tabId, unPublishedDetail, publishedChanges); - } + throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); } - - _tabVersionController.DeleteTabVersion(tabId, tabVersion.TabVersionId); + + this.DiscardVersion(tabId, tabVersion); } public void DeleteVersion(int tabId, int createdByUserId, int version) { - CheckVersioningEnabled(tabId); + this.CheckVersioningEnabled(tabId); - ForceDeleteVersion(tabId, version); + this.ForceDeleteVersion(tabId, version); } - - + public TabVersion RollBackVesion(int tabId, int createdByUserId, int version) { - CheckVersioningEnabled(tabId); + this.CheckVersioningEnabled(tabId); - if (GetUnPublishedVersion(tabId) != null) - { - throw new InvalidOperationException(String.Format(Localization.GetString("TabVersionCannotBeRolledBack_UnpublishedVersionExists", Localization.ExceptionsResourceFile), tabId, version)); + if (this.GetUnPublishedVersion(tabId) != null) + { + throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeRolledBack_UnpublishedVersionExists", Localization.ExceptionsResourceFile), tabId, version)); } - var lastTabVersion = _tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); + var lastTabVersion = this._tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); if (lastTabVersion == null || lastTabVersion.Version == version) { - throw new InvalidOperationException(String.Format(Localization.GetString("TabVersionCannotBeRolledBack_LastVersion", Localization.ExceptionsResourceFile), tabId, version)); + throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeRolledBack_LastVersion", Localization.ExceptionsResourceFile), tabId, version)); } - var publishedDetails = GetVersionModulesDetails(tabId, lastTabVersion.Version).ToArray(); + var publishedDetails = this.GetVersionModulesDetails(tabId, lastTabVersion.Version).ToArray(); + + var rollbackDetails = this.CopyVersionDetails(this.GetVersionModulesDetails(tabId, version)).ToArray(); + var newVersion = this.CreateNewVersion(tabId, createdByUserId); + + // Save Reset detail + this._tabVersionDetailController.SaveTabVersionDetail(this.GetResetTabVersionDetail(newVersion), createdByUserId); - var rollbackDetails = CopyVersionDetails(GetVersionModulesDetails(tabId, version)).ToArray(); - var newVersion = CreateNewVersion(tabId, createdByUserId); - - //Save Reset detail - _tabVersionDetailController.SaveTabVersionDetail(GetResetTabVersionDetail(newVersion), createdByUserId); - foreach (var rollbackDetail in rollbackDetails) { rollbackDetail.TabVersionId = newVersion.TabVersionId; try { - rollbackDetail.ModuleVersion = RollBackDetail(tabId, rollbackDetail); + rollbackDetail.ModuleVersion = this.RollBackDetail(tabId, rollbackDetail); } catch (DnnTabVersionException e) { Logger.Error(string.Format("There was a problem making rollbak of the module {0}. Message: {1}.", rollbackDetail.ModuleId, e.Message)); continue; } - _tabVersionDetailController.SaveTabVersionDetail(rollbackDetail, createdByUserId); + + this._tabVersionDetailController.SaveTabVersionDetail(rollbackDetail, createdByUserId); - //Check if restoring version contains modules to restore + // Check if restoring version contains modules to restore if (publishedDetails.All(tv => tv.ModuleId != rollbackDetail.ModuleId)) { - RestoreModuleInfo(tabId, rollbackDetail); + this.RestoreModuleInfo(tabId, rollbackDetail); } else { - UpdateModuleOrder(tabId, rollbackDetail); - } + this.UpdateModuleOrder(tabId, rollbackDetail); + } } - - //Check if current version contains modules not existing in restoring version + + // Check if current version contains modules not existing in restoring version foreach (var publishedDetail in publishedDetails.Where(publishedDetail => rollbackDetails.All(tvd => tvd.ModuleId != publishedDetail.ModuleId))) { - _moduleController.DeleteTabModule(tabId, publishedDetail.ModuleId, true); + this._moduleController.DeleteTabModule(tabId, publishedDetail.ModuleId, true); } - + // Publish Version - return PublishVersion(GetCurrentPortalId(), tabId, createdByUserId, newVersion); + return this.PublishVersion(this.GetCurrentPortalId(), tabId, createdByUserId, newVersion); + } + + private void DiscardVersion(int tabId, TabVersion tabVersion) + { + var unPublishedDetails = this._tabVersionDetailController.GetTabVersionDetails(tabVersion.TabVersionId); + + var currentPublishedVersion = this.GetCurrentVersion(tabId); + TabVersionDetail[] publishedChanges = null; + + if (currentPublishedVersion != null) + { + publishedChanges = this.GetVersionModulesDetails(tabId, this.GetCurrentVersion(tabId).Version).ToArray(); + } + + foreach (var unPublishedDetail in unPublishedDetails) + { + if (publishedChanges == null) + { + this.DiscardDetailWithoutPublishedTabVersions(tabId, unPublishedDetail); + } + else + { + this.DiscardDetailWithPublishedTabVersions(tabId, unPublishedDetail, publishedChanges); + } + } + + this._tabVersionController.DeleteTabVersion(tabId, tabVersion.TabVersionId); } public TabVersion CreateNewVersion(int tabId, int createdByUserId) { - return CreateNewVersion(GetCurrentPortalId(), tabId, createdByUserId); + return this.CreateNewVersion(this.GetCurrentPortalId(), tabId, createdByUserId); } public TabVersion CreateNewVersion(int portalid, int tabId, int createdByUserId) @@ -211,104 +208,160 @@ public TabVersion CreateNewVersion(int portalid, int tabId, int createdByUserId) throw new InvalidOperationException(Localization.GetString("TabVersioningNotEnabled", Localization.ExceptionsResourceFile)); } - SetupFirstVersionForExistingTab(portalid, tabId); + this.SetupFirstVersionForExistingTab(portalid, tabId); - DeleteOldestVersionIfTabHasMaxNumberOfVersions(portalid, tabId); + this.DeleteOldestVersionIfTabHasMaxNumberOfVersions(portalid, tabId); try { - return _tabVersionController.CreateTabVersion(tabId, createdByUserId); + return this._tabVersionController.CreateTabVersion(tabId, createdByUserId); } catch (InvalidOperationException e) { Services.Exceptions.Exceptions.LogException(e); - throw new InvalidOperationException(String.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId), e); + throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId), e); } catch (SqlException sqlException) { Services.Exceptions.Exceptions.LogException(sqlException); - throw new InvalidOperationException(String.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId)); + throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId)); } } public IEnumerable GetUnPublishedVersionModules(int tabId) { - var unPublishedVersion = GetUnPublishedVersion(tabId); + var unPublishedVersion = this.GetUnPublishedVersion(tabId); if (unPublishedVersion == null) { return CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); } - return GetVersionModules(tabId, unPublishedVersion.TabVersionId); + return this.GetVersionModules(tabId, unPublishedVersion.TabVersionId); } public TabVersion GetCurrentVersion(int tabId, bool ignoreCache = false) { - return _tabVersionController.GetTabVersions(tabId, ignoreCache) + return this._tabVersionController.GetTabVersions(tabId, ignoreCache) .Where(tv => tv.IsPublished).OrderByDescending(tv => tv.CreatedOnDate).FirstOrDefault(); } public TabVersion GetUnPublishedVersion(int tabId) { - return _tabVersionController.GetTabVersions(tabId, true) + return this._tabVersionController.GetTabVersions(tabId, true) .SingleOrDefault(tv => !tv.IsPublished); } public IEnumerable GetCurrentModules(int tabId) { var cacheKey = string.Format(DataCache.PublishedTabModuleCacheKey, tabId); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.PublishedTabModuleCacheTimeOut, - DataCache.PublishedTabModuleCachePriority), - c => GetCurrentModulesInternal(tabId)); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.PublishedTabModuleCacheTimeOut, + DataCache.PublishedTabModuleCachePriority), + c => this.GetCurrentModulesInternal(tabId)); } - + public IEnumerable GetVersionModules(int tabId, int version) { - return ConvertToModuleInfo(GetVersionModulesDetails(tabId, version), tabId); + return this.ConvertToModuleInfo(this.GetVersionModulesDetails(tabId, version), tabId); } public int GetModuleContentLatestVersion(ModuleInfo module) { - var versionableController = GetVersionableController(module); + var versionableController = this.GetVersionableController(module); return versionableController != null ? versionableController.GetLatestVersion(module.ModuleID) : DefaultVersionNumber; + } + + protected override Func GetFactory() + { + return () => new TabVersionBuilder(); + } + + private static IEnumerable GetSnapShot(IEnumerable tabVersionDetails) + { + var versionModules = new Dictionary(); + foreach (var tabVersionDetail in tabVersionDetails) + { + switch (tabVersionDetail.Action) + { + case TabVersionDetailAction.Added: + case TabVersionDetailAction.Modified: + if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) + { + versionModules[tabVersionDetail.ModuleId] = JoinVersionDetails(versionModules[tabVersionDetail.ModuleId], tabVersionDetail); + } + else + { + versionModules.Add(tabVersionDetail.ModuleId, tabVersionDetail); + } + + break; + case TabVersionDetailAction.Deleted: + if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) + { + versionModules.Remove(tabVersionDetail.ModuleId); + } + + break; + case TabVersionDetailAction.Reset: + versionModules.Clear(); + break; + } + } + + // Return Snapshot ordering by PaneName and ModuleOrder (this is required as Skin.cs does not order by these fields) + return versionModules.Values + .OrderBy(m => m.PaneName) + .ThenBy(m => m.ModuleOrder) + .ToList(); } - #endregion - #region Private Methods + private static TabVersionDetail JoinVersionDetails(TabVersionDetail tabVersionDetail, TabVersionDetail newVersionDetail) + { + // Movement changes have not ModuleVersion + if (newVersionDetail.ModuleVersion == Null.NullInteger) + { + newVersionDetail.ModuleVersion = tabVersionDetail.ModuleVersion; + } + + return newVersionDetail; + } + private IEnumerable GetCurrentModulesInternal(int tabId) { - var versioningEnabled = _portalSettings != null && - _tabVersionSettings.IsVersioningEnabled(_portalSettings.PortalId, tabId); + var versioningEnabled = this._portalSettings != null && + this._tabVersionSettings.IsVersioningEnabled(this._portalSettings.PortalId, tabId); if (!versioningEnabled) { return CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); } - - // If versionins is enabled but the tab doesn't have versions history, + + // If versionins is enabled but the tab doesn't have versions history, // then it's a tab never edited after version enabling. - var tabWithoutVersions = !_tabVersionController.GetTabVersions(tabId).Any(); + var tabWithoutVersions = !this._tabVersionController.GetTabVersions(tabId).Any(); if (tabWithoutVersions) { return CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); } - var currentVersion = GetCurrentVersion(tabId); + var currentVersion = this.GetCurrentVersion(tabId); if (currentVersion == null) { - //Only when a tab is on a first version and it is not published, the currentVersion object can be null + // Only when a tab is on a first version and it is not published, the currentVersion object can be null return new List(); } - return GetVersionModules(tabId, currentVersion.Version); + return this.GetVersionModules(tabId, currentVersion.Version); } private void DiscardDetailWithoutPublishedTabVersions(int tabId, TabVersionDetail unPublishedDetail) { if (unPublishedDetail.ModuleVersion != Null.NullInteger) { - DiscardDetail(tabId, unPublishedDetail); + this.DiscardDetail(tabId, unPublishedDetail); } - _moduleController.DeleteTabModule(tabId, unPublishedDetail.ModuleId, true); + + this._moduleController.DeleteTabModule(tabId, unPublishedDetail.ModuleId, true); } private void DiscardDetailWithPublishedTabVersions(int tabId, TabVersionDetail unPublishedDetail, @@ -319,14 +372,15 @@ private void DiscardDetailWithPublishedTabVersions(int tabId, TabVersionDetail u var restoredModuleDetail = publishedChanges.SingleOrDefault(tv => tv.ModuleId == unPublishedDetail.ModuleId); if (restoredModuleDetail != null) { - RestoreModuleInfo(tabId, restoredModuleDetail); + this.RestoreModuleInfo(tabId, restoredModuleDetail); } + return; } if (publishedChanges.All(tv => tv.ModuleId != unPublishedDetail.ModuleId)) { - _moduleController.DeleteTabModule(tabId, unPublishedDetail.ModuleId, true); + this._moduleController.DeleteTabModule(tabId, unPublishedDetail.ModuleId, true); return; } @@ -336,34 +390,35 @@ private void DiscardDetailWithPublishedTabVersions(int tabId, TabVersionDetail u if (publishDetail.PaneName != unPublishedDetail.PaneName || publishDetail.ModuleOrder != unPublishedDetail.ModuleOrder) { - _moduleController.UpdateModuleOrder(tabId, publishDetail.ModuleId, publishDetail.ModuleOrder, + this._moduleController.UpdateModuleOrder(tabId, publishDetail.ModuleId, publishDetail.ModuleOrder, publishDetail.PaneName); } if (unPublishedDetail.ModuleVersion != Null.NullInteger) { - DiscardDetail(tabId, unPublishedDetail); + this.DiscardDetail(tabId, unPublishedDetail); } } } private void ForceDeleteVersion(int tabId, int version) { - var unpublishedVersion = GetUnPublishedVersion(tabId); - if (unpublishedVersion != null + var unpublishedVersion = this.GetUnPublishedVersion(tabId); + if (unpublishedVersion != null && unpublishedVersion.Version == version) { throw new InvalidOperationException( - String.Format( - Localization.GetString("TabVersionCannotBeDeleted_UnpublishedVersion", + string.Format( + Localization.GetString( + "TabVersionCannotBeDeleted_UnpublishedVersion", Localization.ExceptionsResourceFile), tabId, version)); } - var tabVersions = _tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version); + var tabVersions = this._tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version); if (tabVersions.Count() <= 1) { throw new InvalidOperationException( - String.Format( + string.Format( Localization.GetString("TabVersionCannotBeDiscarded_OnlyOneVersion", Localization.ExceptionsResourceFile), tabId, version)); } @@ -374,29 +429,29 @@ private void ForceDeleteVersion(int tabId, int version) if (versionToDelete.Version == version) { var restoreMaxNumberOfVersions = false; - var portalId = _portalSettings.PortalId; - var maxNumberOfVersions = _tabVersionSettings.GetMaxNumberOfVersions(portalId); + var portalId = this._portalSettings.PortalId; + var maxNumberOfVersions = this._tabVersionSettings.GetMaxNumberOfVersions(portalId); // If we already have reached the maxNumberOfVersions we need to extend to 1 this limit to allow the tmp version if (tabVersions.Count() == maxNumberOfVersions) { - _tabVersionSettings.SetMaxNumberOfVersions(portalId, maxNumberOfVersions + 1); + this._tabVersionSettings.SetMaxNumberOfVersions(portalId, maxNumberOfVersions + 1); restoreMaxNumberOfVersions = true; } try { var previousVersion = tabVersions.ElementAt(1); - var previousVersionDetails = GetVersionModulesDetails(tabId, previousVersion.Version).ToArray(); + var previousVersionDetails = this.GetVersionModulesDetails(tabId, previousVersion.Version).ToArray(); var versionToDeleteDetails = - _tabVersionDetailController.GetTabVersionDetails(versionToDelete.TabVersionId); + this._tabVersionDetailController.GetTabVersionDetails(versionToDelete.TabVersionId); foreach (var versionToDeleteDetail in versionToDeleteDetails) { switch (versionToDeleteDetail.Action) { case TabVersionDetailAction.Added: - _moduleController.DeleteTabModule(tabId, versionToDeleteDetail.ModuleId, true); + this._moduleController.DeleteTabModule(tabId, versionToDeleteDetail.ModuleId, true); break; case TabVersionDetailAction.Modified: var peviousVersionDetail = @@ -405,27 +460,29 @@ private void ForceDeleteVersion(int tabId, int version) (peviousVersionDetail.PaneName != versionToDeleteDetail.PaneName || peviousVersionDetail.ModuleOrder != versionToDeleteDetail.ModuleOrder)) { - _moduleController.UpdateModuleOrder(tabId, peviousVersionDetail.ModuleId, + this._moduleController.UpdateModuleOrder(tabId, peviousVersionDetail.ModuleId, peviousVersionDetail.ModuleOrder, peviousVersionDetail.PaneName); } if (versionToDeleteDetail.ModuleVersion != Null.NullInteger) { - DiscardDetail(tabId, versionToDeleteDetail); + this.DiscardDetail(tabId, versionToDeleteDetail); } + break; } } - DeleteTmpVersionIfExists(tabId, versionToDelete); - _tabVersionController.DeleteTabVersion(tabId, versionToDelete.TabVersionId); - ManageModulesToBeRestored(tabId, previousVersionDetails); - _moduleController.ClearCache(tabId); + + this.DeleteTmpVersionIfExists(tabId, versionToDelete); + this._tabVersionController.DeleteTabVersion(tabId, versionToDelete.TabVersionId); + this.ManageModulesToBeRestored(tabId, previousVersionDetails); + this._moduleController.ClearCache(tabId); } finally { if (restoreMaxNumberOfVersions) { - _tabVersionSettings.SetMaxNumberOfVersions(portalId, maxNumberOfVersions); + this._tabVersionSettings.SetMaxNumberOfVersions(portalId, maxNumberOfVersions); } } } @@ -435,8 +492,8 @@ private void ForceDeleteVersion(int tabId, int version) { if (tabVersions.ElementAt(i).Version == version) { - CreateSnapshotOverVersion(tabId, tabVersions.ElementAtOrDefault(i - 1), tabVersions.ElementAt(i)); - _tabVersionController.DeleteTabVersion(tabId, tabVersions.ElementAt(i).TabVersionId); + this.CreateSnapshotOverVersion(tabId, tabVersions.ElementAtOrDefault(i - 1), tabVersions.ElementAt(i)); + this._tabVersionController.DeleteTabVersion(tabId, tabVersions.ElementAt(i).TabVersionId); break; } } @@ -447,47 +504,50 @@ private void ManageModulesToBeRestored(int tabId, TabVersionDetail[] versionDeta { foreach (var detail in versionDetails) { - var module = _moduleController.GetModule(detail.ModuleId, tabId, true); + var module = this._moduleController.GetModule(detail.ModuleId, tabId, true); if (module.IsDeleted) { - _moduleController.RestoreModule(module); + this._moduleController.RestoreModule(module); } } } private void DeleteTmpVersionIfExists(int tabId, TabVersion versionToDelete) { - var tmpVersion = _tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); + var tmpVersion = this._tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); if (tmpVersion != null && tmpVersion.Version > versionToDelete.Version) { - _tabVersionController.DeleteTabVersion(tabId, tmpVersion.TabVersionId); + this._tabVersionController.DeleteTabVersion(tabId, tmpVersion.TabVersionId); } } - + private void DeleteOldestVersionIfTabHasMaxNumberOfVersions(int portalId, int tabId) { - var maxVersionsAllowed = GetMaxNumberOfVersions(portalId); - var tabVersionsOrdered = _tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version); + var maxVersionsAllowed = this.GetMaxNumberOfVersions(portalId); + var tabVersionsOrdered = this._tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version); - if (tabVersionsOrdered.Count() < maxVersionsAllowed) return; - - //The last existing version is going to be deleted, therefore we need to add the snapshot to the previous one + if (tabVersionsOrdered.Count() < maxVersionsAllowed) + { + return; + } + + // The last existing version is going to be deleted, therefore we need to add the snapshot to the previous one var snapShotTabVersion = tabVersionsOrdered.ElementAtOrDefault(maxVersionsAllowed - 2); - CreateSnapshotOverVersion(tabId, snapShotTabVersion); - DeleteOldVersions(tabVersionsOrdered, snapShotTabVersion); + this.CreateSnapshotOverVersion(tabId, snapShotTabVersion); + this.DeleteOldVersions(tabVersionsOrdered, snapShotTabVersion); } - + private int GetMaxNumberOfVersions(int portalId) - { - return _tabVersionSettings.GetMaxNumberOfVersions(portalId); + { + return this._tabVersionSettings.GetMaxNumberOfVersions(portalId); } private void UpdateModuleOrder(int tabId, TabVersionDetail detailToRestore) { - var restoredModule = _moduleController.GetModule(detailToRestore.ModuleId, tabId, true); + var restoredModule = this._moduleController.GetModule(detailToRestore.ModuleId, tabId, true); if (restoredModule != null) { - UpdateModuleInfoOrder(restoredModule, detailToRestore); + this.UpdateModuleInfoOrder(restoredModule, detailToRestore); } } @@ -495,7 +555,7 @@ private void UpdateModuleInfoOrder(ModuleInfo module, TabVersionDetail detailToR { module.PaneName = detailToRestore.PaneName; module.ModuleOrder = detailToRestore.ModuleOrder; - _moduleController.UpdateModule(module); + this._moduleController.UpdateModule(module); } private TabVersionDetail GetResetTabVersionDetail(TabVersion tabVersion) @@ -506,68 +566,69 @@ private TabVersionDetail GetResetTabVersionDetail(TabVersion tabVersion) TabVersionId = tabVersion.TabVersionId, Action = TabVersionDetailAction.Reset, ModuleId = Null.NullInteger, - ModuleVersion = Null.NullInteger + ModuleVersion = Null.NullInteger, }; } - private void RestoreModuleInfo(int tabId, TabVersionDetail detailsToRestore ) + private void RestoreModuleInfo(int tabId, TabVersionDetail detailsToRestore) { - var restoredModule = _moduleController.GetModule(detailsToRestore.ModuleId, tabId, true); + var restoredModule = this._moduleController.GetModule(detailsToRestore.ModuleId, tabId, true); if (restoredModule != null) { - _moduleController.RestoreModule(restoredModule); - UpdateModuleInfoOrder(restoredModule, detailsToRestore); + this._moduleController.RestoreModule(restoredModule); + this.UpdateModuleInfoOrder(restoredModule, detailsToRestore); } } private IEnumerable GetVersionModulesDetails(int tabId, int version) { - var tabVersionDetails = _tabVersionDetailController.GetVersionHistory(tabId, version); + var tabVersionDetails = this._tabVersionDetailController.GetVersionHistory(tabId, version); return GetSnapShot(tabVersionDetails); } private TabVersion PublishVersion(int portalId, int tabId, int createdByUserID, TabVersion tabVersion) { - var unPublishedDetails = _tabVersionDetailController.GetTabVersionDetails(tabVersion.TabVersionId); + var unPublishedDetails = this._tabVersionDetailController.GetTabVersionDetails(tabVersion.TabVersionId); foreach (var unPublishedDetail in unPublishedDetails) { if (unPublishedDetail.ModuleVersion != Null.NullInteger) { - PublishDetail(tabId, unPublishedDetail); + this.PublishDetail(tabId, unPublishedDetail); } } tabVersion.IsPublished = true; - _tabVersionController.SaveTabVersion(tabVersion, tabVersion.CreatedByUserID, createdByUserID); + this._tabVersionController.SaveTabVersion(tabVersion, tabVersion.CreatedByUserID, createdByUserID); var tab = TabController.Instance.GetTab(tabId, portalId); if (!tab.HasBeenPublished) { TabController.Instance.MarkAsPublished(tab); } - _moduleController.ClearCache(tabId); + + this._moduleController.ClearCache(tabId); return tabVersion; } private IEnumerable CopyVersionDetails(IEnumerable tabVersionDetails) { - return tabVersionDetails.Select(tabVersionDetail => new TabVersionDetail - { - ModuleId = tabVersionDetail.ModuleId, - ModuleOrder = tabVersionDetail.ModuleOrder, - ModuleVersion = tabVersionDetail.ModuleVersion, - PaneName = tabVersionDetail.PaneName, - Action = tabVersionDetail.Action - }).ToList(); + return tabVersionDetails.Select(tabVersionDetail => new TabVersionDetail + { + ModuleId = tabVersionDetail.ModuleId, + ModuleOrder = tabVersionDetail.ModuleOrder, + ModuleVersion = tabVersionDetail.ModuleVersion, + PaneName = tabVersionDetail.PaneName, + Action = tabVersionDetail.Action, + }).ToList(); } private void CheckVersioningEnabled(int tabId) { - CheckVersioningEnabled(GetCurrentPortalId(), tabId); + this.CheckVersioningEnabled(this.GetCurrentPortalId(), tabId); } private void CheckVersioningEnabled(int portalId, int tabId) - { - if (portalId == Null.NullInteger || !_tabVersionSettings.IsVersioningEnabled(portalId, tabId)) + { + if (portalId == Null.NullInteger || !this._tabVersionSettings.IsVersioningEnabled(portalId, tabId)) { throw new InvalidOperationException(Localization.GetString("TabVersioningNotEnabled", Localization.ExceptionsResourceFile)); } @@ -575,14 +636,14 @@ private void CheckVersioningEnabled(int portalId, int tabId) private int GetCurrentPortalId() { - return _portalSettings == null ? Null.NullInteger : _portalSettings.PortalId; + return this._portalSettings == null ? Null.NullInteger : this._portalSettings.PortalId; } private void CreateSnapshotOverVersion(int tabId, TabVersion snapshotTabVersion, TabVersion deletedTabVersion = null) { - var snapShotTabVersionDetails = GetVersionModulesDetails(tabId, snapshotTabVersion.Version).ToArray(); - var existingTabVersionDetails = _tabVersionDetailController.GetTabVersionDetails(snapshotTabVersion.TabVersionId).ToArray(); - + var snapShotTabVersionDetails = this.GetVersionModulesDetails(tabId, snapshotTabVersion.Version).ToArray(); + var existingTabVersionDetails = this._tabVersionDetailController.GetTabVersionDetails(snapshotTabVersion.TabVersionId).ToArray(); + for (var i = existingTabVersionDetails.Count(); i > 0; i--) { var existingDetail = existingTabVersionDetails.ElementAtOrDefault(i - 1); @@ -591,32 +652,34 @@ private void CreateSnapshotOverVersion(int tabId, TabVersion snapshotTabVersion, { if (snapShotTabVersionDetails.All(tvd => tvd.TabVersionDetailId != existingDetail.TabVersionDetailId)) { - _tabVersionDetailController.DeleteTabVersionDetail(existingDetail.TabVersionId, + this._tabVersionDetailController.DeleteTabVersionDetail( + existingDetail.TabVersionId, existingDetail.TabVersionDetailId); } } - else if (existingDetail.Action == TabVersionDetailAction.Deleted) + else if (existingDetail.Action == TabVersionDetailAction.Deleted) { - IEnumerable deletedTabVersionDetails = _tabVersionDetailController.GetTabVersionDetails(deletedTabVersion.TabVersionId); + IEnumerable deletedTabVersionDetails = this._tabVersionDetailController.GetTabVersionDetails(deletedTabVersion.TabVersionId); var moduleAddedAndDeleted = deletedTabVersionDetails.Any( deleteDetail => deleteDetail.ModuleId == existingDetail.ModuleId && deleteDetail.Action == TabVersionDetailAction.Added); if (moduleAddedAndDeleted) { - _tabVersionDetailController.DeleteTabVersionDetail(existingDetail.TabVersionId, + this._tabVersionDetailController.DeleteTabVersionDetail( + existingDetail.TabVersionId, existingDetail.TabVersionDetailId); } } } - UpdateDeletedTabDetails(snapshotTabVersion, deletedTabVersion, snapShotTabVersionDetails); + this.UpdateDeletedTabDetails(snapshotTabVersion, deletedTabVersion, snapShotTabVersionDetails); } private void UpdateDeletedTabDetails(TabVersion snapshotTabVersion, TabVersion deletedTabVersion, TabVersionDetail[] snapShotTabVersionDetails) { - var tabVersionDetailsToBeUpdated = deletedTabVersion != null ? _tabVersionDetailController.GetTabVersionDetails(deletedTabVersion.TabVersionId).ToArray() + var tabVersionDetailsToBeUpdated = deletedTabVersion != null ? this._tabVersionDetailController.GetTabVersionDetails(deletedTabVersion.TabVersionId).ToArray() : snapShotTabVersionDetails; foreach (var tabVersionDetail in tabVersionDetailsToBeUpdated) @@ -630,10 +693,9 @@ private void UpdateDeletedTabDetails(TabVersion snapshotTabVersion, TabVersion d { var previousTabVersionId = tabVersionDetail.TabVersionId; tabVersionDetail.TabVersionId = snapshotTabVersion.TabVersionId; - _tabVersionDetailController.SaveTabVersionDetail(tabVersionDetail); - _tabVersionDetailController.ClearCache(previousTabVersionId); + this._tabVersionDetailController.SaveTabVersionDetail(tabVersionDetail); + this._tabVersionDetailController.ClearCache(previousTabVersionId); } - } } @@ -643,29 +705,31 @@ private void DeleteOldVersions(IEnumerable tabVersionsOrdered, TabVe for (var i = oldVersions.Count(); i > 0; i--) { var oldVersion = oldVersions.ElementAtOrDefault(i - 1); - var oldVersionDetails = _tabVersionDetailController.GetTabVersionDetails(oldVersion.TabVersionId).ToArray(); + var oldVersionDetails = this._tabVersionDetailController.GetTabVersionDetails(oldVersion.TabVersionId).ToArray(); for (var j = oldVersionDetails.Count(); j > 0; j--) { var oldVersionDetail = oldVersionDetails.ElementAtOrDefault(j - 1); - _tabVersionDetailController.DeleteTabVersionDetail(oldVersionDetail.TabVersionId, oldVersionDetail.TabVersionDetailId); + this._tabVersionDetailController.DeleteTabVersionDetail(oldVersionDetail.TabVersionId, oldVersionDetail.TabVersionDetailId); } - _tabVersionController.DeleteTabVersion(oldVersion.TabId, oldVersion.TabVersionId); + + this._tabVersionController.DeleteTabVersion(oldVersion.TabId, oldVersion.TabVersionId); } } - private IEnumerable ConvertToModuleInfo(IEnumerable details, int tabId) + private IEnumerable ConvertToModuleInfo(IEnumerable details, int tabId) { var modules = new List(); try { foreach (var detail in details) { - var module = _moduleController.GetModule(detail.ModuleId, tabId, false); + var module = this._moduleController.GetModule(detail.ModuleId, tabId, false); if (module == null) { continue; } - var moduleVersion = _moduleController.IsSharedModule(module) + + var moduleVersion = this._moduleController.IsSharedModule(module) ? Null.NullInteger : detail.ModuleVersion; var cloneModule = module.Clone(); @@ -677,25 +741,30 @@ private IEnumerable ConvertToModuleInfo(IEnumerable GetSnapShot(IEnumerable tabVersionDetails) - { - var versionModules = new Dictionary(); - foreach (var tabVersionDetail in tabVersionDetails) - { - switch (tabVersionDetail.Action) - { - case TabVersionDetailAction.Added: - case TabVersionDetailAction.Modified: - if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) - { - versionModules[tabVersionDetail.ModuleId] = JoinVersionDetails(versionModules[tabVersionDetail.ModuleId], tabVersionDetail); - } - else - { - versionModules.Add(tabVersionDetail.ModuleId, tabVersionDetail); - } - break; - case TabVersionDetailAction.Deleted: - if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) - { - versionModules.Remove(tabVersionDetail.ModuleId); - } - break; - case TabVersionDetailAction.Reset: - versionModules.Clear(); - break; - } - } - - // Return Snapshot ordering by PaneName and ModuleOrder (this is required as Skin.cs does not order by these fields) - return versionModules.Values - .OrderBy(m => m.PaneName) - .ThenBy(m => m.ModuleOrder) - .ToList(); - } - - private static TabVersionDetail JoinVersionDetails(TabVersionDetail tabVersionDetail, TabVersionDetail newVersionDetail) - { - // Movement changes have not ModuleVersion - if (newVersionDetail.ModuleVersion == Null.NullInteger) - { - newVersionDetail.ModuleVersion = tabVersionDetail.ModuleVersion; - } - - return newVersionDetail; - } - private void CreateFirstTabVersion(int tabId, TabInfo tab, IEnumerable modules) { - var tabVersion = _tabVersionController.CreateTabVersion(tabId, tab.CreatedByUserID, true); + var tabVersion = this._tabVersionController.CreateTabVersion(tabId, tab.CreatedByUserID, true); foreach (var module in modules) { - var moduleVersion = GetModuleContentPublishedVersion(module); - _tabVersionDetailController.SaveTabVersionDetail(new TabVersionDetail - { - Action = TabVersionDetailAction.Added, - ModuleId = module.ModuleID, - ModuleOrder = module.ModuleOrder, - ModuleVersion = moduleVersion, - PaneName = module.PaneName, - TabVersionId = tabVersion.TabVersionId - }, module.CreatedByUserID); + var moduleVersion = this.GetModuleContentPublishedVersion(module); + this._tabVersionDetailController.SaveTabVersionDetail( + new TabVersionDetail + { + Action = TabVersionDetailAction.Added, + ModuleId = module.ModuleID, + ModuleOrder = module.ModuleOrder, + ModuleVersion = moduleVersion, + PaneName = module.PaneName, + TabVersionId = tabVersion.TabVersionId, + }, module.CreatedByUserID); } } private int GetModuleContentPublishedVersion(ModuleInfo module) { - var versionableController = GetVersionableController(module); + var versionableController = this.GetVersionableController(module); return versionableController != null ? versionableController.GetPublishedVersion(module.ModuleID) : Null.NullInteger; - } - #endregion - - protected override Func GetFactory() - { - return () => new TabVersionBuilder(); - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs index 388efe4e918..882c2c17867 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs @@ -1,110 +1,110 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { - public class TabVersionController: ServiceLocator, ITabVersionController + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + + public class TabVersionController : ServiceLocator, ITabVersionController { - private static readonly DataProvider Provider = DataProvider.Instance(); - - #region Public Methods + private static readonly DataProvider Provider = DataProvider.Instance(); + public TabVersion GetTabVersion(int tabVersionId, int tabId, bool ignoreCache = false) { - return GetTabVersions(tabId, ignoreCache).SingleOrDefault(tv => tv.TabVersionId == tabVersionId); + return this.GetTabVersions(tabId, ignoreCache).SingleOrDefault(tv => tv.TabVersionId == tabVersionId); } - + public IEnumerable GetTabVersions(int tabId, bool ignoreCache = false) { - //if we are not using the cache, then remove from cache and re-add loaded items when needed later + // if we are not using the cache, then remove from cache and re-add loaded items when needed later var tabCacheKey = GetTabVersionsCacheKey(tabId); if (ignoreCache || Host.Host.PerformanceSetting == Globals.PerformanceSettings.NoCaching) { DataCache.RemoveCache(tabCacheKey); } - var tabVersions = CBO.Instance.GetCachedObject>(new CacheItemArgs(tabCacheKey, - DataCache.TabVersionsCacheTimeOut, - DataCache.TabVersionsCachePriority), - c => CBO.FillCollection(Provider.GetTabVersions(tabId)), - false - ); + + var tabVersions = CBO.Instance.GetCachedObject>( + new CacheItemArgs( + tabCacheKey, + DataCache.TabVersionsCacheTimeOut, + DataCache.TabVersionsCachePriority), + c => CBO.FillCollection(Provider.GetTabVersions(tabId)), + false); return tabVersions; } + public void SaveTabVersion(TabVersion tabVersion) { - SaveTabVersion(tabVersion, tabVersion.CreatedByUserID, tabVersion.LastModifiedByUserID); + this.SaveTabVersion(tabVersion, tabVersion.CreatedByUserID, tabVersion.LastModifiedByUserID); } public void SaveTabVersion(TabVersion tabVersion, int createdByUserID) { - SaveTabVersion(tabVersion, createdByUserID, createdByUserID); + this.SaveTabVersion(tabVersion, createdByUserID, createdByUserID); } public void SaveTabVersion(TabVersion tabVersion, int createdByUserID, int modifiedByUserID) { tabVersion.TabVersionId = Provider.SaveTabVersion(tabVersion.TabVersionId, tabVersion.TabId, tabVersion.TimeStamp, tabVersion.Version, tabVersion.IsPublished, createdByUserID, modifiedByUserID); - ClearCache(tabVersion.TabId); + this.ClearCache(tabVersion.TabId); } public TabVersion CreateTabVersion(int tabId, int createdByUserID, bool isPublished = false) { - var lastTabVersion = GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); + var lastTabVersion = this.GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); var newVersion = 1; if (lastTabVersion != null) { if (!lastTabVersion.IsPublished && !isPublished) { - throw new InvalidOperationException(String.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExists", Localization.ExceptionsResourceFile))); + throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExists", Localization.ExceptionsResourceFile))); } + newVersion = lastTabVersion.Version + 1; } - + var tabVersionId = Provider.SaveTabVersion(0, tabId, DateTime.UtcNow, newVersion, isPublished, createdByUserID, createdByUserID); - ClearCache(tabId); + this.ClearCache(tabId); - return GetTabVersion(tabVersionId, tabId); + return this.GetTabVersion(tabVersionId, tabId); } public void DeleteTabVersion(int tabId, int tabVersionId) { Provider.DeleteTabVersion(tabVersionId); - ClearCache(tabId); + this.ClearCache(tabId); } public void DeleteTabVersionDetailByModule(int moduleId) { Provider.DeleteTabVersionDetailByModule(moduleId); - } - #endregion - - #region Private Methods - private void ClearCache(int tabId) + } + + protected override Func GetFactory() { - DataCache.RemoveCache(GetTabVersionsCacheKey(tabId)); + return () => new TabVersionController(); } private static string GetTabVersionsCacheKey(int tabId) { return string.Format(DataCache.TabVersionsCacheKey, tabId); - } - - #endregion - - protected override Func GetFactory() + } + + private void ClearCache(int tabId) { - return () => new TabVersionController(); + DataCache.RemoveCache(GetTabVersionsCacheKey(tabId)); } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs index e7672ae0cb1..20da0efa000 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs @@ -1,54 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { - /// - ///Class to represent a Tab Version Detail object. Each detail is related with a TabVersion and also with a ModuleInfo - /// + using System; + + /// + /// Class to represent a Tab Version Detail object. Each detail is related with a TabVersion and also with a ModuleInfo. + /// [Serializable] - public class TabVersionDetail: BaseEntityInfo - { - #region Public Properties - + public class TabVersionDetail : BaseEntityInfo + { /// - /// Id of TabVersionDetail + /// Gets or sets id of TabVersionDetail. /// public int TabVersionDetailId { get; set; } /// - /// Id of the related TabVersion master of the detail + /// Gets or sets id of the related TabVersion master of the detail. /// public int TabVersionId { get; set; } /// - /// Id of the Module which tracks the detail + /// Gets or sets id of the Module which tracks the detail. /// public int ModuleId { get; set; } /// - /// Version number of the module when the detail was tracked + /// Gets or sets version number of the module when the detail was tracked. /// public int ModuleVersion { get; set; } /// - /// Pane name where the Module was when the detail was tracked + /// Gets or sets pane name where the Module was when the detail was tracked. /// public string PaneName { get; set; } /// - /// Order into the pane where the Module was when the detail was tracked + /// Gets or sets order into the pane where the Module was when the detail was tracked. /// public int ModuleOrder { get; set; } /// - /// Action which provoked the detail + /// Gets or sets action which provoked the detail. /// - public TabVersionDetailAction Action { get; set; } - - #endregion + public TabVersionDetailAction Action { get; set; } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailAction.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailAction.cs index 9d25838346a..ffb0ed780b0 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailAction.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailAction.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { /// - /// This enum represents the possible list of action that can be done in a Tab Version (i.e.: add module, modified module, deleted module, reset (restore version)) + /// This enum represents the possible list of action that can be done in a Tab Version (i.e.: add module, modified module, deleted module, reset (restore version)). /// public enum TabVersionDetailAction { Added, Modified, Deleted, - Reset + Reset, } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs index 894f3164488..79cddbc2617 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs @@ -1,38 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { - public class TabVersionDetailController: ServiceLocator, ITabVersionDetailController + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Framework; + + public class TabVersionDetailController : ServiceLocator, ITabVersionDetailController { - private static readonly DataProvider Provider = DataProvider.Instance(); - - #region Public Methods + private static readonly DataProvider Provider = DataProvider.Instance(); + public TabVersionDetail GetTabVersionDetail(int tabVersionDetailId, int tabVersionId, bool ignoreCache = false) { - return GetTabVersionDetails(tabVersionId, ignoreCache).SingleOrDefault(tvd => tvd.TabVersionDetailId == tabVersionDetailId); + return this.GetTabVersionDetails(tabVersionId, ignoreCache).SingleOrDefault(tvd => tvd.TabVersionDetailId == tabVersionDetailId); } - + public IEnumerable GetTabVersionDetails(int tabVersionId, bool ignoreCache = false) { - //if we are not using the cache + // if we are not using the cache if (ignoreCache || Host.Host.PerformanceSetting == Globals.PerformanceSettings.NoCaching) { return CBO.FillCollection(Provider.GetTabVersionDetails(tabVersionId)); } - return CBO.GetCachedObject>(new CacheItemArgs(GetTabVersionDetailCacheKey(tabVersionId), - DataCache.TabVersionDetailsCacheTimeOut, - DataCache.TabVersionDetailsCachePriority), - c => CBO.FillCollection(Provider.GetTabVersionDetails(tabVersionId))); + return CBO.GetCachedObject>( + new CacheItemArgs( + GetTabVersionDetailCacheKey(tabVersionId), + DataCache.TabVersionDetailsCacheTimeOut, + DataCache.TabVersionDetailsCachePriority), + c => CBO.FillCollection(Provider.GetTabVersionDetails(tabVersionId))); } public IEnumerable GetVersionHistory(int tabId, int version) @@ -42,46 +44,43 @@ public IEnumerable GetVersionHistory(int tabId, int version) public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail) { - SaveTabVersionDetail(tabVersionDetail, tabVersionDetail.CreatedByUserID, tabVersionDetail.LastModifiedByUserID); + this.SaveTabVersionDetail(tabVersionDetail, tabVersionDetail.CreatedByUserID, tabVersionDetail.LastModifiedByUserID); } public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdByUserID) { - SaveTabVersionDetail(tabVersionDetail, createdByUserID, createdByUserID); + this.SaveTabVersionDetail(tabVersionDetail, createdByUserID, createdByUserID); } - + public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdByUserID, int modifiedByUserID) { - tabVersionDetail.TabVersionDetailId = Provider.SaveTabVersionDetail(tabVersionDetail.TabVersionDetailId, + tabVersionDetail.TabVersionDetailId = Provider.SaveTabVersionDetail( + tabVersionDetail.TabVersionDetailId, tabVersionDetail.TabVersionId, tabVersionDetail.ModuleId, tabVersionDetail.ModuleVersion, tabVersionDetail.PaneName, tabVersionDetail.ModuleOrder, (int)tabVersionDetail.Action, createdByUserID, modifiedByUserID); - ClearCache(tabVersionDetail.TabVersionId); + this.ClearCache(tabVersionDetail.TabVersionId); } public void DeleteTabVersionDetail(int tabVersionId, int tabVersionDetailId) { Provider.DeleteTabVersionDetail(tabVersionDetailId); - ClearCache(tabVersionId); + this.ClearCache(tabVersionId); } public void ClearCache(int tabVersionId) { DataCache.RemoveCache(GetTabVersionDetailCacheKey(tabVersionId)); - } - #endregion - - #region Private Methods - private static string GetTabVersionDetailCacheKey(int tabVersionId) - { - return string.Format(DataCache.TabVersionDetailsCacheKey, tabVersionId); - } - - #endregion - + } + protected override System.Func GetFactory() { return () => new TabVersionDetailController(); } + + private static string GetTabVersionDetailCacheKey(int tabVersionId) + { + return string.Format(DataCache.TabVersionDetailsCacheKey, tabVersionId); + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs index fd37eff00bf..f268091876e 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs @@ -1,24 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { + using System; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + public class TabVersionSettings : ServiceLocator, ITabVersionSettings - { - #region Constants + { private const int TabVersionsMaxNumber = 5; private const string TabVersionQueryStringParam = "DnnTabVersion"; - private const string TabVersioningSettingKey = "TabVersioningSettingKey"; - #endregion - + private const string TabVersioningSettingKey = "TabVersioningSettingKey"; + public int GetMaxNumberOfVersions(int portalId) { Requires.NotNegative("portalId", portalId); @@ -48,7 +47,7 @@ public bool IsVersioningEnabled(int portalId) { Requires.NotNegative("portalId", portalId); return - Convert.ToBoolean(PortalController.GetPortalSetting("TabVersionsEnabled", portalId, Boolean.FalseString)); + Convert.ToBoolean(PortalController.GetPortalSetting("TabVersionsEnabled", portalId, bool.FalseString)); } public bool IsVersioningEnabled(int portalId, int tabId) @@ -56,7 +55,7 @@ public bool IsVersioningEnabled(int portalId, int tabId) Requires.NotNegative("portalId", portalId); Requires.NotNegative("tabId", tabId); - if (!IsVersioningEnabled(portalId)) + if (!this.IsVersioningEnabled(portalId)) { return false; } @@ -69,13 +68,12 @@ public bool IsVersioningEnabled(int portalId, int tabId) } var settings = TabController.Instance.GetTabSettings(tabId); - var isVersioningEnableForTab = settings[TabVersioningSettingKey] == null + var isVersioningEnableForTab = settings[TabVersioningSettingKey] == null || Convert.ToBoolean(settings[TabVersioningSettingKey]); return isVersioningEnableForTab; } - - + public string GetTabVersionQueryStringParameter(int portalId) { Requires.NotNegative("portalId", portalId); diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs index 31442df824e..96f15b8950d 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs @@ -1,26 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { - class TabVersionTracker : ServiceLocator, ITabChangeTracker - { - #region Public Methods - + using System; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + + internal class TabVersionTracker : ServiceLocator, ITabChangeTracker + { /// - /// Tracks a version detail when a module is added to a page + /// Tracks a version detail when a module is added to a page. /// - /// Module which tracks the version detail - /// Version number corresponding to the version detail - /// User Id who provokes the version detail + /// Module which tracks the version detail. + /// Version number corresponding to the version detail. + /// User Id who provokes the version detail. public void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId) { Requires.NotNull("module", module); @@ -38,11 +37,11 @@ public void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId } /// - /// Tracks a version detail when a module is modified on a page + /// Tracks a version detail when a module is modified on a page. /// - /// Module which tracks the version detail - /// Version number corresponding to the version detail - /// User Id who provokes the version detail + /// Module which tracks the version detail. + /// Version number corresponding to the version detail. + /// User Id who provokes the version detail. public void TrackModuleModification(ModuleInfo module, int moduleVersion, int userId) { Requires.NotNull("module", module); @@ -77,7 +76,7 @@ public void TrackModuleModification(ModuleInfo module, int moduleVersion, int us } catch (InvalidOperationException) { - throw; + throw; } catch (Exception ex) { @@ -86,11 +85,11 @@ public void TrackModuleModification(ModuleInfo module, int moduleVersion, int us } /// - /// Tracks a version detail when a module is deleted from a page + /// Tracks a version detail when a module is deleted from a page. /// - /// Module which tracks the version detail - /// Version number corresponding to the version detail - /// User Id who provokes the version detail + /// Module which tracks the version detail. + /// Version number corresponding to the version detail. + /// User Id who provokes the version detail. public void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId) { Requires.NotNull("module", module); @@ -108,12 +107,12 @@ public void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId } /// - /// Tracks a version detail when a module is copied from an exisitng page + /// Tracks a version detail when a module is copied from an exisitng page. /// - /// Module which tracks the version detail - /// Version number corresponding to the version detail - /// Tab Id where the module originally is - /// /// User Id who provokes the version detail + /// Module which tracks the version detail. + /// Version number corresponding to the version detail. + /// Tab Id where the module originally is. + /// /// User Id who provokes the version detail. public void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId) { Requires.NotNull("module", module); @@ -136,12 +135,12 @@ public void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTa } /// - /// Tracks a version detail when a copied module is deleted from an exisitng page + /// Tracks a version detail when a copied module is deleted from an exisitng page. /// - /// Module which tracks the version detail - /// Version number corresponding to the version detail - /// Tab Id where the module originally is - /// User Id who provokes the version detail + /// Module which tracks the version detail. + /// Version number corresponding to the version detail. + /// Tab Id where the module originally is. + /// User Id who provokes the version detail. public void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId) { Requires.NotNull("module", module); @@ -162,26 +161,28 @@ public void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int original { Services.Exceptions.Exceptions.LogException(ex); } - } - - #endregion - - #region Private Statics Methods - + } + + protected override Func GetFactory() + { + return () => new TabVersionTracker(); + } + private static void ProcessAdditionDetail(ModuleInfo module, int moduleVersion, int userId, TabVersion targetVersion) { if (IsHostModule(module)) { return; } - - //Module could be restored in the same version + + // Module could be restored in the same version var existingTabDetails = TabVersionDetailController.Instance.GetTabVersionDetails(targetVersion.TabVersionId) .Where(tvd => tvd.ModuleId == module.ModuleID); foreach (var existingTabDetail in existingTabDetails) { - TabVersionDetailController.Instance.DeleteTabVersionDetail(existingTabDetail.TabVersionId, + TabVersionDetailController.Instance.DeleteTabVersionDetail( + existingTabDetail.TabVersionId, existingTabDetail.TabVersionDetailId); } @@ -202,17 +203,18 @@ private static void ProcessDeletionDetail(ModuleInfo module, int moduleVersion, .SingleOrDefault(tvd => tvd.ModuleId == module.ModuleID); if (existingTabDetail != null) { - TabVersionDetailController.Instance.DeleteTabVersionDetail(existingTabDetail.TabVersionId, + TabVersionDetailController.Instance.DeleteTabVersionDetail( + existingTabDetail.TabVersionId, existingTabDetail.TabVersionDetailId); - - //When a module is added in the same version, then we should do nothing with it + + // When a module is added in the same version, then we should do nothing with it if (existingTabDetail.Action == TabVersionDetailAction.Added) { return; } } - //Do not add module to Tab Version Details if it has been hard deleted + // Do not add module to Tab Version Details if it has been hard deleted ModuleInfo moduleInfo = ModuleController.Instance.GetModule(module.ModuleID, module.TabID, false); if (moduleInfo != null) { @@ -245,7 +247,7 @@ private static TabVersionDetail CreateNewTabVersionDetailObjectFromModule(int ta ModuleVersion = moduleVersion, ModuleOrder = module.ModuleOrder, PaneName = module.PaneName, - Action = action + Action = action, }; } @@ -259,16 +261,8 @@ private static TabVersionDetail CreateNewTabVersionDetailObjectFromModule(int ta ModuleVersion = moduleVersion, ModuleOrder = moduleOrder, PaneName = paneName, - Action = action + Action = action, }; - } - #endregion - - #region Service Locator - protected override Func GetFactory() - { - return () => new TabVersionTracker(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs index c68bf33d355..611f6855525 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs @@ -1,54 +1,54 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Threading; -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.TabVersions { + using System; + using System.Threading; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + /// - /// This Class ofers a set of methods useful and reusable along the Tab Version API + /// This Class ofers a set of methods useful and reusable along the Tab Version API. /// internal static class TabVersionUtils - { - #region Internal Methods - + { /// - /// Try to get the version number from the current URL + /// Try to get the version number from the current URL. /// - /// Version number obtained. Null Integer if it is not available - /// True if version number is available and valid from URL. Otherwise, False + /// Version number obtained. Null Integer if it is not available. + /// True if version number is available and valid from URL. Otherwise, False. internal static bool TryGetUrlVersion(out int versionInt) { var version = GetTabVersionQueryStringValue(); - if (String.IsNullOrEmpty(version)) + if (string.IsNullOrEmpty(version)) { versionInt = Null.NullInteger; return false; } + return int.TryParse(version, out versionInt); } /// - /// Check if current user can see the current page + /// Check if current user can see the current page. /// - /// True if current user can see the current page. Otherwise, False + /// True if current user can see the current page. Otherwise, False. internal static bool CanSeeVersionedPages() { return CanSeeVersionedPages(TabController.CurrentPage); } /// - /// Check if current user can see a specific page + /// Check if current user can see a specific page. /// - /// The TabInfo to be checked - /// True if current user can see the specific page. Otherwise, False + /// The TabInfo to be checked. + /// True if current user can see the specific page. Otherwise, False. internal static bool CanSeeVersionedPages(TabInfo tab) { if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) @@ -61,6 +61,7 @@ internal static bool CanSeeVersionedPages(TabInfo tab) { return false; } + var isAdminUser = currentPortalSettings.UserInfo.IsSuperUser || PortalSecurity.IsInRole(currentPortalSettings.AdministratorRoleName); if (isAdminUser) { @@ -68,17 +69,14 @@ internal static bool CanSeeVersionedPages(TabInfo tab) } return TabPermissionController.HasTabPermission(tab.TabPermissions, "EDIT,CONTENT,MANAGE"); - } - #endregion - - #region Private Methods + } + private static string GetTabVersionQueryStringValue() { var currentPortal = PortalController.Instance.GetCurrentPortalSettings(); - return currentPortal == null ? - string.Empty : + return currentPortal == null ? + string.Empty : HttpContext.Current.Request.QueryString[TabVersionSettings.Instance.GetTabVersionQueryStringParameter(currentPortal.PortalId)]; - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs b/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs index 96c747c1fb1..2d17f3ea904 100644 --- a/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs @@ -1,51 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { + using System; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + public class TabWorkflowSettings : ServiceLocator, ITabWorkflowSettings - { - #region Constants + { private const string DefaultTabWorkflowKey = "DefaultTabWorkflowKey"; - private const string TabWorkflowEnableKey = "TabWorkflowEnabledKey"; - #endregion - - #region Private Members + private const string TabWorkflowEnableKey = "TabWorkflowEnabledKey"; private readonly ITabController _tabController; - private readonly ISystemWorkflowManager _systemWorkflowManager; - #endregion - - #region Constructor - + private readonly ISystemWorkflowManager _systemWorkflowManager; + public TabWorkflowSettings() { - _tabController = TabController.Instance; - _systemWorkflowManager = SystemWorkflowManager.Instance; - } - #endregion - - #region Public Methods + this._tabController = TabController.Instance; + this._systemWorkflowManager = SystemWorkflowManager.Instance; + } + public int GetDefaultTabWorkflowId(int portalId) { var workflowId = PortalController.GetPortalSettingAsInteger(DefaultTabWorkflowKey, portalId, Null.NullInteger); if (workflowId == Null.NullInteger) { - var workflow = _systemWorkflowManager.GetDirectPublishWorkflow(portalId); + var workflow = this._systemWorkflowManager.GetDirectPublishWorkflow(portalId); workflowId = (workflow != null) ? workflow.WorkflowID : Null.NullInteger; if (workflowId != Null.NullInteger) { - PortalController.UpdatePortalSetting(portalId, DefaultTabWorkflowKey, workflowId.ToString(CultureInfo.InvariantCulture), true); + PortalController.UpdatePortalSetting(portalId, DefaultTabWorkflowKey, workflowId.ToString(CultureInfo.InvariantCulture), true); } } + return workflowId; } @@ -65,20 +58,20 @@ public void SetWorkflowEnabled(int portalId, int tabId, bool enabled) { Requires.NotNegative("tabId", tabId); - _tabController.UpdateTabSetting(tabId, TabWorkflowEnableKey, enabled.ToString(CultureInfo.InvariantCulture)); + this._tabController.UpdateTabSetting(tabId, TabWorkflowEnableKey, enabled.ToString(CultureInfo.InvariantCulture)); } public bool IsWorkflowEnabled(int portalId, int tabId) { - if (!IsWorkflowEnabled(portalId)) + if (!this.IsWorkflowEnabled(portalId)) { return false; } - var tabInfo = _tabController.GetTab(tabId, portalId); - var settings = _tabController.GetTabSettings(tabId); + var tabInfo = this._tabController.GetTab(tabId, portalId); + var settings = this._tabController.GetTabSettings(tabId); - return !_tabController.IsHostOrAdminPage(tabInfo) && (settings[TabWorkflowEnableKey] == null || Convert.ToBoolean(settings[TabWorkflowEnableKey])); + return !this._tabController.IsHostOrAdminPage(tabInfo) && (settings[TabWorkflowEnableKey] == null || Convert.ToBoolean(settings[TabWorkflowEnableKey])); } public bool IsWorkflowEnabled(int portalId) @@ -88,15 +81,12 @@ public bool IsWorkflowEnabled(int portalId) return false; } - return Convert.ToBoolean(PortalController.GetPortalSetting(TabWorkflowEnableKey, portalId, Boolean.FalseString)); - } - #endregion - - #region Service Locator + return Convert.ToBoolean(PortalController.GetPortalSetting(TabWorkflowEnableKey, portalId, bool.FalseString)); + } + protected override Func GetFactory() { return () => new TabWorkflowSettings(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs b/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs index dd3ec3420e5..01318ca0ac3 100644 --- a/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs @@ -1,139 +1,131 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs { - class TabWorkflowTracker : ServiceLocator, ITabChangeTracker + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + + internal class TabWorkflowTracker : ServiceLocator, ITabChangeTracker { - private static readonly DnnLogger Logger = DnnLogger.GetClassLogger(typeof(TabWorkflowTracker)); - - #region Members + private static readonly DnnLogger Logger = DnnLogger.GetClassLogger(typeof(TabWorkflowTracker)); private readonly ITabController _tabController; private readonly IWorkflowEngine _workflowEngine; private readonly IWorkflowManager _workflowManager; - private readonly ITabWorkflowSettings _tabWorkflowSettings; - #endregion - + private readonly ITabWorkflowSettings _tabWorkflowSettings; + public TabWorkflowTracker() { - _tabController = TabController.Instance; - _workflowEngine = WorkflowEngine.Instance; - _workflowManager = WorkflowManager.Instance; - _tabWorkflowSettings = TabWorkflowSettings.Instance; - } - - protected override Func GetFactory() - { - return () => new TabWorkflowTracker(); + this._tabController = TabController.Instance; + this._workflowEngine = WorkflowEngine.Instance; + this._workflowManager = WorkflowManager.Instance; + this._tabWorkflowSettings = TabWorkflowSettings.Instance; } - - + /// - /// Tracks a workflow instance when a module is added to a page + /// Tracks a workflow instance when a module is added to a page. /// - /// Module which tracks the workflow instance - /// Version number corresponding to the module - /// User Id related with the workflow instance + /// Module which tracks the workflow instance. + /// Version number corresponding to the module. + /// User Id related with the workflow instance. public void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId) { - NotifyWorkflowAboutChanges(module.PortalID, module.TabID, userId); + this.NotifyWorkflowAboutChanges(module.PortalID, module.TabID, userId); } - + /// - /// Tracks a workflow instance when a module is modified on a page + /// Tracks a workflow instance when a module is modified on a page. /// - /// Module which tracks the workflow instance - /// Version number corresponding to the module - /// User Id related with the workflow instance + /// Module which tracks the workflow instance. + /// Version number corresponding to the module. + /// User Id related with the workflow instance. public void TrackModuleModification(ModuleInfo module, int moduleVersion, int userId) { - NotifyWorkflowAboutChanges(module.PortalID, module.TabID, userId); + this.NotifyWorkflowAboutChanges(module.PortalID, module.TabID, userId); } - + protected override Func GetFactory() + { + return () => new TabWorkflowTracker(); + } + /// - /// Tracks a workflow instance when a module is deleted from a page + /// Tracks a workflow instance when a module is deleted from a page. /// - /// Module which tracks the workflow instance - /// Version number corresponding to the module - /// User Id related with the workflow instance + /// Module which tracks the workflow instance. + /// Version number corresponding to the module. + /// User Id related with the workflow instance. public void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId) { - NotifyWorkflowAboutChanges(module.PortalID, module.TabID, userId); + this.NotifyWorkflowAboutChanges(module.PortalID, module.TabID, userId); } /// - /// Tracks a workflow instance when a module is copied from an exisitng page + /// Tracks a workflow instance when a module is copied from an exisitng page. /// - /// Module which tracks the workflow instance - /// Version number corresponding to the module - /// Tab Id where the module originally is - /// User Id related with the workflow instance + /// Module which tracks the workflow instance. + /// Version number corresponding to the module. + /// Tab Id where the module originally is. + /// User Id related with the workflow instance. public void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId) { - TrackModuleAddition(module, moduleVersion, userId); + this.TrackModuleAddition(module, moduleVersion, userId); } - - + /// - /// Tracks a workflow instance when a copied module is deleted from an exisitng page + /// Tracks a workflow instance when a copied module is deleted from an exisitng page. /// - /// Module which tracks the workflow instance - /// Version number corresponding to the module - /// Tab Id where the module originally is - /// User Id related with the workflow instance + /// Module which tracks the workflow instance. + /// Version number corresponding to the module. + /// Tab Id where the module originally is. + /// User Id related with the workflow instance. public void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId) { - TrackModuleDeletion(module, moduleVersion, userId); - } - - #region Private Statics Methods + this.TrackModuleDeletion(module, moduleVersion, userId); + } + private void NotifyWorkflowAboutChanges(int portalId, int tabId, int userId) { try { - var tabInfo = _tabController.GetTab(tabId, portalId); - if (tabInfo!= null && !tabInfo.IsDeleted && _workflowEngine.IsWorkflowCompleted(tabInfo)) + var tabInfo = this._tabController.GetTab(tabId, portalId); + if (tabInfo != null && !tabInfo.IsDeleted && this._workflowEngine.IsWorkflowCompleted(tabInfo)) { - var workflow = GetCurrentOrDefaultWorkflow(tabInfo, portalId); + var workflow = this.GetCurrentOrDefaultWorkflow(tabInfo, portalId); if (workflow == null) { Logger.Warn("Current Workflow and Default workflow are not found on NotifyWorkflowAboutChanges"); return; } - _workflowEngine.StartWorkflow(workflow.WorkflowID, tabInfo.ContentItemId, userId); - _tabController.RefreshCache(portalId, tabId); + this._workflowEngine.StartWorkflow(workflow.WorkflowID, tabInfo.ContentItemId, userId); + this._tabController.RefreshCache(portalId, tabId); } } catch (Exception ex) { Exceptions.LogException(ex); } - } private Workflow GetCurrentOrDefaultWorkflow(ContentItem item, int portalId) { if (item.StateID != Null.NullInteger) { - return _workflowManager.GetWorkflow(item); + return this._workflowManager.GetWorkflow(item); } - var defaultWorkflow = _tabWorkflowSettings.GetDefaultTabWorkflowId(portalId); - return _workflowManager.GetWorkflow(defaultWorkflow); - } - #endregion + var defaultWorkflow = this._tabWorkflowSettings.GetDefaultTabWorkflowId(portalId); + return this._workflowManager.GetWorkflow(defaultWorkflow); + } } } diff --git a/DNN Platform/Library/Entities/Urls/ActionType.cs b/DNN Platform/Library/Entities/Urls/ActionType.cs index 8c491617e61..0e1ace0f6b8 100644 --- a/DNN Platform/Library/Entities/Urls/ActionType.cs +++ b/DNN Platform/Library/Entities/Urls/ActionType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum ActionType @@ -13,6 +13,6 @@ public enum ActionType CheckFor301, Redirect302, Output404, - Output500 + Output500, } } diff --git a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs index d6febc71392..458d69258d7 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs @@ -1,56 +1,150 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + using System.Reflection; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + public class AdvancedFriendlyUrlProvider : FriendlyUrlProviderBase { + private const string CodePattern = @"(?:\&|\?)language=(?[A-Za-z]{2,3}-[A-Za-z0-9]{2,4}(-[A-Za-z]{2}){0,1})"; + private static readonly Regex FriendlyPathRegex = new Regex("(.[^\\\\?]*)\\\\?(.*)", RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex DefaultPageRegex = new Regex(Globals.glbDefaultPage, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex AumDebugRegex = new Regex("/_aumdebug/(?:true|false)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex LangMatchRegex = new Regex("/language/(?.[^/]+)(?:/|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - - const string CodePattern = @"(?:\&|\?)language=(?[A-Za-z]{2,3}-[A-Za-z0-9]{2,4}(-[A-Za-z]{2}){0,1})"; private static readonly Regex CodePatternRegex = new Regex(CodePattern, RegexOptions.Compiled); - #region Constructor - internal AdvancedFriendlyUrlProvider(NameValueCollection attributes) : base(attributes) { } - #endregion + /// + /// Return a full-improved Friendly Url for the supplied tab. + /// + /// The current page. + /// The non-friendly path to the page. + /// The name of the page. + /// The current portal alias to use. + /// If true, then the Friendly Url will be constructed without using any custom redirects. + /// The current Friendly Url Settings to use. + /// + /// + public static string ImprovedFriendlyUrl( + TabInfo tab, + string path, + string pageName, + string httpAlias, + bool ignoreCustomRedirects, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + List messages; + return ImprovedFriendlyUrlWithMessages( + tab, + path, + pageName, + httpAlias, + ignoreCustomRedirects, + settings, + out messages, + parentTraceId); + } + + /// + /// Return a FriendlyUrl for the supplied Tab, but don't improve it past the standard DNN Friendly Url version. + /// + /// + internal static string BaseFriendlyUrl(TabInfo tab, string path, string pageName, string httpAlias, FriendlyUrlSettings settings) + { + bool cultureSpecificAlias; + + // Call GetFriendlyAlias to get the Alias part of the url + string friendlyPath = GetFriendlyAlias( + path, + ref httpAlias, + tab.PortalID, + settings, + null, + out cultureSpecificAlias); + + // Call GetFriendlyQueryString to get the QueryString part of the url + friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, settings); + + return friendlyPath; + } + + internal static string ImprovedFriendlyUrlWithMessages( + TabInfo tab, + string path, + string pageName, + string httpAlias, + bool ignoreCustomRedirects, + FriendlyUrlSettings settings, + out List messages, + Guid parentTraceId) + { + messages = new List(); + bool cultureSpecificAlias; - #region Overriden methods + // Call GetFriendlyAlias to get the Alias part of the url + string friendlyPath = GetFriendlyAlias( + path, + ref httpAlias, + tab.PortalID, + settings, + new PortalSettings(tab.PortalID), + out cultureSpecificAlias); + + // Call GetFriendlyQueryString to get the QueryString part of the url + friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, settings); + + // ImproveFriendlyUrl will attempt to remove tabid/nn and other information from the Url + // 700 : avoid null alias if a tab.portalid / httpAlias mismatch + PortalAliasInfo alias = GetAliasForPortal(httpAlias, tab.PortalID, ref messages); + if (alias != null) + { + var portalSettings = new PortalSettings(tab.TabID, alias); + friendlyPath = ImproveFriendlyUrlWithMessages( + tab, + friendlyPath, + pageName, + portalSettings, + ignoreCustomRedirects, + settings, + ref messages, + cultureSpecificAlias, + parentTraceId); + + friendlyPath = ForceLowerCaseIfAllowed(tab, friendlyPath, settings); + } + + OutputFriendlyUrlMessages(tab, path, "base/messages", messages, friendlyPath, settings); + return friendlyPath; + } internal override string FriendlyUrl(TabInfo tab, string path) { - return FriendlyUrl(tab, path, Globals.glbDefaultPage, PortalController.Instance.GetCurrentPortalSettings()); + return this.FriendlyUrl(tab, path, Globals.glbDefaultPage, PortalController.Instance.GetCurrentPortalSettings()); } internal override string FriendlyUrl(TabInfo tab, string path, string pageName) { - return FriendlyUrl(tab, path, pageName, PortalController.Instance.GetCurrentPortalSettings()); + return this.FriendlyUrl(tab, path, pageName, PortalController.Instance.GetCurrentPortalSettings()); } internal override string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings portalSettings) @@ -59,116 +153,71 @@ internal override string FriendlyUrl(TabInfo tab, string path, string pageName, { throw new ArgumentNullException("portalSettings"); } - return FriendlyUrlInternal(tab, path, pageName, String.Empty, (PortalSettings)portalSettings); + + return this.FriendlyUrlInternal(tab, path, pageName, string.Empty, (PortalSettings)portalSettings); } internal override string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) { - return FriendlyUrlInternal(tab, path, pageName, portalAlias, null); + return this.FriendlyUrlInternal(tab, path, pageName, portalAlias, null); } - #endregion - - #region Addvanced Friendly Url Methods - - /// - /// Return a FriendlyUrl for the supplied Tab, but don't improve it past the standard DNN Friendly Url version - /// - internal static string BaseFriendlyUrl(TabInfo tab, string path, string pageName, string httpAlias, FriendlyUrlSettings settings) + internal static string GetCultureOfPath(string path) { - bool cultureSpecificAlias; - - //Call GetFriendlyAlias to get the Alias part of the url - string friendlyPath = GetFriendlyAlias(path, - ref httpAlias, - tab.PortalID, - settings, - null, - out cultureSpecificAlias); - - //Call GetFriendlyQueryString to get the QueryString part of the url - friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, settings); - - return friendlyPath; - } + string code = string.Empty; + MatchCollection matches = CodePatternRegex.Matches(path); + if (matches.Count > 0) + { + foreach (Match langMatch in matches) + { + if (langMatch.Success) + { + Group langGroup = langMatch.Groups["cc"]; + if (langGroup.Success) + { + code = langGroup.Value; + break; + } + } + } + } - /// - /// Return a full-improved Friendly Url for the supplied tab - /// - /// The current page - /// The non-friendly path to the page - /// The name of the page - /// The current portal alias to use - /// If true, then the Friendly Url will be constructed without using any custom redirects - /// The current Friendly Url Settings to use - /// - /// - public static string ImprovedFriendlyUrl(TabInfo tab, - string path, - string pageName, - string httpAlias, - bool ignoreCustomRedirects, - FriendlyUrlSettings settings, - Guid parentTraceId) - { - List messages; - return ImprovedFriendlyUrlWithMessages(tab, - path, - pageName, - httpAlias, - ignoreCustomRedirects, - settings, - out messages, - parentTraceId); + return code; } - internal static string ImprovedFriendlyUrlWithMessages(TabInfo tab, - string path, - string pageName, - string httpAlias, - bool ignoreCustomRedirects, - FriendlyUrlSettings settings, - out List messages, - Guid parentTraceId) + internal static string ForceLowerCaseIfAllowed(TabInfo tab, string url, FriendlyUrlSettings settings) { - messages = new List(); - bool cultureSpecificAlias; - - //Call GetFriendlyAlias to get the Alias part of the url - string friendlyPath = GetFriendlyAlias(path, - ref httpAlias, - tab.PortalID, - settings, - new PortalSettings(tab.PortalID), - out cultureSpecificAlias); - - //Call GetFriendlyQueryString to get the QueryString part of the url - friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, settings); - - //ImproveFriendlyUrl will attempt to remove tabid/nn and other information from the Url - //700 : avoid null alias if a tab.portalid / httpAlias mismatch - PortalAliasInfo alias = GetAliasForPortal(httpAlias, tab.PortalID, ref messages); - if (alias != null) + // 606 : include regex to stop lower case in certain circumstances + // 840 : change to re-introduce lower case restrictions on admin / host tabs + if (tab != null) { - var portalSettings = new PortalSettings(tab.TabID, alias); - friendlyPath = ImproveFriendlyUrlWithMessages(tab, - friendlyPath, - pageName, - portalSettings, - ignoreCustomRedirects, - settings, - ref messages, - cultureSpecificAlias, - parentTraceId); + if (!(tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings))) + { + bool forceLowerCase = settings.ForceLowerCase; + if (forceLowerCase) + { + if (!string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) + { + var rx = RegexUtils.GetCachedRegex(settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + forceLowerCase = !rx.IsMatch(url); + } + } - friendlyPath = ForceLowerCaseIfAllowed(tab, friendlyPath, settings); + if (forceLowerCase) + { + // don't force lower case for Urls excluded from being 'friendly' + forceLowerCase = !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, false); + } + + if (forceLowerCase) + { + url = url.ToLowerInvariant(); + } + } } - OutputFriendlyUrlMessages(tab, path, "base/messages", messages, friendlyPath, settings); - return friendlyPath; - } - #endregion - #region Private Methods + return url; + } private static string AddPage(string path, string pageName) { @@ -188,6 +237,7 @@ private static string AddPage(string path, string pageName) friendlyPath = friendlyPath + "/" + pageName; } } + return friendlyPath; } @@ -195,7 +245,7 @@ private static PortalSettings CheckAndUpdatePortalSettingsForNewAlias(PortalSett { if (cultureSpecificAlias && portalAlias != portalSettings.PortalAlias.HTTPAlias) { - //was a change in alias, need to update the portalSettings with a new portal alias + // was a change in alias, need to update the portalSettings with a new portal alias PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalSettings.PortalId); if (pa != null) { @@ -209,36 +259,40 @@ private static PortalSettings CheckAndUpdatePortalSettingsForNewAlias(PortalSett private static string CheckForDebug(HttpRequest request) { - string debugValue = ""; + string debugValue = string.Empty; const string debugToken = "_FUGDEBUG"; - //798 : change reference to debug parameters + + // 798 : change reference to debug parameters if (request != null) { - debugValue = (request.Params.Get("HTTP_" + debugToken)); + debugValue = request.Params.Get("HTTP_" + debugToken); } + if (debugValue == null) { debugValue = "false"; } + return debugValue.ToLowerInvariant(); } - private static string CreateFriendlyUrl(string portalAlias, - string newTabPath, - string newPath, - string pageAndExtension, - string newPageName, - string qs, - string langParms, - ref List messages, - bool builtInUrl, - bool changeToSiteRoot, - bool dropLangParms, - bool isHomePage) + private static string CreateFriendlyUrl( + string portalAlias, + string newTabPath, + string newPath, + string pageAndExtension, + string newPageName, + string qs, + string langParms, + ref List messages, + bool builtInUrl, + bool changeToSiteRoot, + bool dropLangParms, + bool isHomePage) { var finalPathBuilder = new StringBuilder(); - if (changeToSiteRoot) //no page path if changing to site root because of parameter replacement rule (593) + if (changeToSiteRoot) // no page path if changing to site root because of parameter replacement rule (593) { if (newPath.StartsWith("/")) { @@ -246,7 +300,8 @@ private static string CreateFriendlyUrl(string portalAlias, } finalPathBuilder.Append(Globals.AddHTTP(portalAlias + "/")); - //don't show lang parms for site-root set values + + // don't show lang parms for site-root set values finalPathBuilder.Append(newPath); finalPathBuilder.Append(newPageName); finalPathBuilder.Append(pageAndExtension); @@ -259,22 +314,23 @@ private static string CreateFriendlyUrl(string portalAlias, ? Globals.AddHTTP(portalAlias + langParms + "/") : Globals.AddHTTP(portalAlias + "/")); - //685 : When final value no longer includes a path, and it's for the home page, don't use the path + // 685 : When final value no longer includes a path, and it's for the home page, don't use the path // this happens when items are removed from 'newPath' and shifted to 'qs' because of the 'doNotINcludeInPath' regex // It's true this could be solved by taking the items from the path earlier in the chain (in the original routine that takes them // from the querystring and includes them in the path), but the intention is to leave the primary friendly url generation similar // to the original DNN logic, and have all the 'improved' logic in this routine. - if (newPath == "" //no path (no querystring when rewritten) - && (isHomePage && newTabPath == "/") //is the home page, and we're not using 'home' for it - && (langParms == "" || dropLangParms) - //doesn't have any language parms, or we're intentionally getting rid of them - && !builtInUrl) //builtin Url == login, terms, privacy, register + if (newPath == string.Empty // no path (no querystring when rewritten) + && (isHomePage && newTabPath == "/") // is the home page, and we're not using 'home' for it + && (langParms == string.Empty || dropLangParms) + + // doesn't have any language parms, or we're intentionally getting rid of them + && !builtInUrl) // builtin Url == login, terms, privacy, register { - //Url is home page, and there's no friendly path to add, so we don't need the home page path (ie, /home is unneeded, just use the site root) + // Url is home page, and there's no friendly path to add, so we don't need the home page path (ie, /home is unneeded, just use the site root) if (newPageName.Length == 0 && pageAndExtension.StartsWith(".")) { - //when the newPageName isn't specified, and the pageAndExtension is just an extension - //just add the querystring on the end + // when the newPageName isn't specified, and the pageAndExtension is just an extension + // just add the querystring on the end finalPathBuilder.Append(qs); } else @@ -285,9 +341,10 @@ private static string CreateFriendlyUrl(string portalAlias, } } else - //this is the normal case + + // this is the normal case { - //finalPath += newTabPath.TrimStart('/') + newPath + newPageName + pageAndExtension + qs; + // finalPath += newTabPath.TrimStart('/') + newPath + newPageName + pageAndExtension + qs; finalPathBuilder.Append(newTabPath.TrimStart('/')); finalPathBuilder.Append(newPath); finalPathBuilder.Append(newPageName); @@ -295,43 +352,46 @@ private static string CreateFriendlyUrl(string portalAlias, finalPathBuilder.Append(qs); } } + return finalPathBuilder.ToString(); } private static string DetermineExtension(bool isHomePage, string pageName, FriendlyUrlSettings settings) { - string extension = ""; - if (!isHomePage) //no pageAndExtension for the home page when no query string specified + string extension = string.Empty; + if (!isHomePage) // no pageAndExtension for the home page when no query string specified { - //the ending of the url depends on the current page pageAndExtension settings + // the ending of the url depends on the current page pageAndExtension settings if (settings.PageExtensionUsageType == PageExtensionUsageType.AlwaysUse || settings.PageExtensionUsageType == PageExtensionUsageType.PageOnly) { - //check whether a 'custom' (other than default.aspx) page was supplied, and insert that as the pageAndExtension - if (String.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) != 0) + // check whether a 'custom' (other than default.aspx) page was supplied, and insert that as the pageAndExtension + if (string.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) != 0) { extension = "/" + pageName.Replace(".aspx", settings.PageExtension); } else { extension = settings.PageExtension; - //default page pageAndExtension + + // default page pageAndExtension } } else { - if (String.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) != 0) + if (string.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) != 0) { - //get rid of the .aspx on the page if it was there - extension = "/" + pageName.Replace(".aspx", ""); // +"/"; //610 : don't always end with / + // get rid of the .aspx on the page if it was there + extension = "/" + pageName.Replace(".aspx", string.Empty); // +"/"; //610 : don't always end with / } else { - //no pageAndExtension - extension = ""; //610 dont always end with "/"; + // no pageAndExtension + extension = string.Empty; // 610 dont always end with "/"; } } } + return extension; } @@ -354,14 +414,16 @@ private static string DeterminePageNameAndExtension(ref string pageName, Friendl } else { - pageAndExtension = "/" + pageName.Replace(".aspx", ""); //610 + "/"; - //get rid of the .aspx on the page if it was there + pageAndExtension = "/" + pageName.Replace(".aspx", string.Empty); // 610 + "/"; + + // get rid of the .aspx on the page if it was there } } else { - pageAndExtension = ""; //610 don't end with "/"; - //no pageAndExtension + pageAndExtension = string.Empty; // 610 don't end with "/"; + + // no pageAndExtension } } else @@ -385,12 +447,51 @@ private static string DeterminePageNameAndExtension(ref string pageName, Friendl else { pageAndExtension = settings.PageExtension; - //default page extension + + // default page extension } } + return pageAndExtension; } + private static PortalAliasInfo GetAliasForPortal(string httpAlias, int portalId, ref List messages) + { + // if no match found, then call database to find (don't rely on cache for this one, because it is an exception event, not an expected event) + PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAlias(httpAlias, portalId); + if (alias == null) + { + // no match between alias and portal id + var aliasArray = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); + if (aliasArray.Count > 0) + { + alias = aliasArray[0]; // nab the first one here + messages.Add("Portal Id " + portalId.ToString() + " does not match http alias " + httpAlias + + " - " + alias.HTTPAlias + " was used instead"); + } + else + { + messages.Add("Portal Id " + portalId.ToString() + + " does not match http alias and no usable alias could be found"); + } + } + + return alias; + } + + private static string GetCultureOfSettings(PortalSettings portalSettings) + { + // note! should be replaced with compiled call to portalSettings.CultureCode property when base supported version is increased. + string cultureCode = string.Empty; + PropertyInfo cultureCodePi = portalSettings.GetType().GetProperty("CultureCode"); + if (cultureCodePi != null) + { + cultureCode = (string)cultureCodePi.GetValue(portalSettings, null); + } + + return cultureCode; + } + private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, string portalAlias, PortalSettings portalSettings) { Guid parentTraceId = Guid.Empty; @@ -398,31 +499,33 @@ private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, st bool cultureSpecificAlias; var localSettings = new FriendlyUrlSettings(portalId); - //Call GetFriendlyAlias to get the Alias part of the url - if (String.IsNullOrEmpty(portalAlias) && portalSettings != null) + // Call GetFriendlyAlias to get the Alias part of the url + if (string.IsNullOrEmpty(portalAlias) && portalSettings != null) { portalAlias = portalSettings.PortalAlias.HTTPAlias; } - string friendlyPath = GetFriendlyAlias(path, - ref portalAlias, - portalId, - localSettings, - portalSettings, - out cultureSpecificAlias); + + string friendlyPath = GetFriendlyAlias( + path, + ref portalAlias, + portalId, + localSettings, + portalSettings, + out cultureSpecificAlias); if (portalSettings != null) { portalSettings = CheckAndUpdatePortalSettingsForNewAlias(portalSettings, cultureSpecificAlias, portalAlias); } - if (tab == null && path == "~/" && String.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) == 0) + if (tab == null && path == "~/" && string.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) == 0) { - //this is a request for the site root for he dnn logo skin object (642) - //do nothing, the friendly alias is already correct - we don't want to append 'default.aspx' on the end + // this is a request for the site root for he dnn logo skin object (642) + // do nothing, the friendly alias is already correct - we don't want to append 'default.aspx' on the end } else { - //Get friendly path gets the standard dnn-style friendly path + // Get friendly path gets the standard dnn-style friendly path friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, localSettings); if (portalSettings == null) @@ -431,25 +534,28 @@ private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, st portalSettings = new PortalSettings(tab.TabID, alias); } - //ImproveFriendlyUrl will attempt to remove tabid/nn and other information from the Url - friendlyPath = ImproveFriendlyUrl(tab, - friendlyPath, - pageName, - portalSettings, - false, - cultureSpecificAlias, - localSettings, - parentTraceId); + + // ImproveFriendlyUrl will attempt to remove tabid/nn and other information from the Url + friendlyPath = ImproveFriendlyUrl( + tab, + friendlyPath, + pageName, + portalSettings, + false, + cultureSpecificAlias, + localSettings, + parentTraceId); } - //set it to lower case if so allowed by settings + + // set it to lower case if so allowed by settings friendlyPath = ForceLowerCaseIfAllowed(tab, friendlyPath, localSettings); - // Replace http:// by https:// if SSL is enabled and site is marked as secure + // Replace http:// by https:// if SSL is enabled and site is marked as secure // (i.e. requests to http://... will be redirected to https://...) if (tab != null && portalSettings.SSLEnabled && tab.IsSecure && friendlyPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { - friendlyPath = "https://" + friendlyPath.Substring("http://".Length); + friendlyPath = "https://" + friendlyPath.Substring("http://".Length); // If portal's "SSL URL" setting is defined: Use "SSL URL" instaed of current portal alias var sslUrl = portalSettings.SSLURL; @@ -462,93 +568,40 @@ private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, st return friendlyPath; } - private static PortalAliasInfo GetAliasForPortal(string httpAlias, int portalId, ref List messages) - { - //if no match found, then call database to find (don't rely on cache for this one, because it is an exception event, not an expected event) - PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAlias(httpAlias, portalId); - if (alias == null) - { - //no match between alias and portal id - var aliasArray = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - if (aliasArray.Count > 0) - { - alias = aliasArray[0]; //nab the first one here - messages.Add("Portal Id " + portalId.ToString() + " does not match http alias " + httpAlias + - " - " + alias.HTTPAlias + " was used instead"); - } - else - { - messages.Add("Portal Id " + portalId.ToString() + - " does not match http alias and no usable alias could be found"); - } - } - return alias; - } - - internal static string GetCultureOfPath(string path) - { - string code = ""; - MatchCollection matches = CodePatternRegex.Matches(path); - if (matches.Count > 0) - { - foreach (Match langMatch in matches) - { - if (langMatch.Success) - { - Group langGroup = langMatch.Groups["cc"]; - if (langGroup.Success) - { - code = langGroup.Value; - break; - } - } - } - } - return code; - } - - private static string GetCultureOfSettings(PortalSettings portalSettings) - { - //note! should be replaced with compiled call to portalSettings.CultureCode property when base supported version is increased. - string cultureCode = ""; - PropertyInfo cultureCodePi = portalSettings.GetType().GetProperty("CultureCode"); - if (cultureCodePi != null) - { - cultureCode = (string)cultureCodePi.GetValue(portalSettings, null); - } - return cultureCode; - } - - private static string GetFriendlyAlias(string path, - ref string httpAlias, - int portalId, - FriendlyUrlSettings settings, - PortalSettings portalSettings, - out bool cultureSpecificAlias) + private static string GetFriendlyAlias( + string path, + ref string httpAlias, + int portalId, + FriendlyUrlSettings settings, + PortalSettings portalSettings, + out bool cultureSpecificAlias) { cultureSpecificAlias = false; string friendlyPath = path; bool done = false; string httpAliasFull = null; - //this regex identifies if the correct http(s)://portalAlias already is in the path + + // this regex identifies if the correct http(s)://portalAlias already is in the path var portalMatchRegex = RegexUtils.GetCachedRegex("^https?://" + httpAlias, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); string cultureCode = GetCultureOfPath(path); if (portalSettings != null) { - if (portalMatchRegex.IsMatch(path) == false || !String.IsNullOrEmpty(cultureCode)) + if (portalMatchRegex.IsMatch(path) == false || !string.IsNullOrEmpty(cultureCode)) { - //get the portal alias mapping for this portal, which tells whether to enforce a primary portal alias or not + // get the portal alias mapping for this portal, which tells whether to enforce a primary portal alias or not PortalSettings.PortalAliasMapping aliasMapping = PortalSettingsController.Instance().GetPortalAliasMappingMode(portalId); - //check to see if we should be specifying this based on the culture code + + // check to see if we should be specifying this based on the culture code var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - //799: if there was no culture code in the path and the portal settings culture was supplied, then use that - //essentially we are ignoring the portal alias of the portal settings object and driving the alias from the supplied portal settings culture code - //this is because the calling module cannot be guaranteed to be supplying the right culture Code / portal alias combination. + // 799: if there was no culture code in the path and the portal settings culture was supplied, then use that + // essentially we are ignoring the portal alias of the portal settings object and driving the alias from the supplied portal settings culture code + // this is because the calling module cannot be guaranteed to be supplying the right culture Code / portal alias combination. if (string.IsNullOrEmpty(cultureCode)) { cultureCode = GetCultureOfSettings(portalSettings); - //lookup the culture code of the portal settings object + + // lookup the culture code of the portal settings object } PortalAliasInfo redirectAlias; @@ -560,83 +613,88 @@ private static string GetFriendlyAlias(string path, } else { - redirectAlias = primaryAliases.GetAliasByPortalIdAndSettings(portalId, httpAlias, cultureCode, settings); + redirectAlias = primaryAliases.GetAliasByPortalIdAndSettings(portalId, httpAlias, cultureCode, settings); } if (redirectAlias != null) { - if (!String.IsNullOrEmpty(redirectAlias.CultureCode) - && String.Compare(redirectAlias.HTTPAlias, httpAlias, StringComparison.OrdinalIgnoreCase) != 0) + if (!string.IsNullOrEmpty(redirectAlias.CultureCode) + && string.Compare(redirectAlias.HTTPAlias, httpAlias, StringComparison.OrdinalIgnoreCase) != 0) { - //found the primary alias, and it's different from the supplied portal alias - //and the site is using a redirect portal alias mapping - //substitute in the primary Alias for the supplied alias - friendlyPath = friendlyPath.Replace(Globals.AddHTTP(httpAlias), String.Empty); + // found the primary alias, and it's different from the supplied portal alias + // and the site is using a redirect portal alias mapping + // substitute in the primary Alias for the supplied alias + friendlyPath = friendlyPath.Replace(Globals.AddHTTP(httpAlias), string.Empty); httpAlias = redirectAlias.HTTPAlias; if (!string.IsNullOrEmpty(redirectAlias.CultureCode)) { cultureSpecificAlias = true; } - else if (redirectAlias.CultureCode == "") + else if (redirectAlias.CultureCode == string.Empty) { cultureSpecificAlias = true; - //770: hacking this so that a change is forced to portal settings when a non-chosen alias is requested. + + // 770: hacking this so that a change is forced to portal settings when a non-chosen alias is requested. } } else { - //check to see if we matched for this alias - if so, it's a culture specific alias - if (String.Compare(redirectAlias.HTTPAlias, httpAlias, StringComparison.OrdinalIgnoreCase) == 0 && + // check to see if we matched for this alias - if so, it's a culture specific alias + if (string.Compare(redirectAlias.HTTPAlias, httpAlias, StringComparison.OrdinalIgnoreCase) == 0 && !string.IsNullOrEmpty(redirectAlias.CultureCode)) { cultureSpecificAlias = true; } } - //852 : check to see if the skinSrc is explicityl specified, which we don't want to duplicate if the alias also specifies this + // 852 : check to see if the skinSrc is explicityl specified, which we don't want to duplicate if the alias also specifies this if (path.ToLowerInvariant().Contains("skinsrc=") && primaryAliases.ContainsSpecificSkins()) { - //path has a skin specified and (at least one) alias has a skin specified + // path has a skin specified and (at least one) alias has a skin specified string[] parms = path.Split('&'); foreach (string parmPair in parms) { if (parmPair.ToLowerInvariant().Contains("skinsrc=")) { - //splits the key/value pair into a two-element array + // splits the key/value pair into a two-element array string[] keyValue = parmPair.Split('='); - //check to see if it was a full skinsrc=xyz pair + + // check to see if it was a full skinsrc=xyz pair if (keyValue.GetUpperBound(0) >= 1) { - friendlyPath = path.Replace("&" + parmPair, ""); + friendlyPath = path.Replace("&" + parmPair, string.Empty); } } } } } - //the portal alias is not in the path already, so we need to get it in there + // the portal alias is not in the path already, so we need to get it in there if (friendlyPath.StartsWith("~/")) { friendlyPath = friendlyPath.Substring(1); } + if (friendlyPath.StartsWith("/") == false) { friendlyPath = "/" + friendlyPath; } - //should now have a standard /path/path/page.aspx?key=value style of Url + + // should now have a standard /path/path/page.aspx?key=value style of Url httpAliasFull = Globals.AddHTTP(httpAlias); if (HttpContext.Current != null && HttpContext.Current.Items["UrlRewrite:OriginalUrl"] != null) { string originalUrl = HttpContext.Current.Items["UrlRewrite:OriginalUrl"].ToString(); - //confirming this portal was the original one requested, making all the generated aliases - //for the same portal + + // confirming this portal was the original one requested, making all the generated aliases + // for the same portal var fullALiasRx = RegexUtils.GetCachedRegex("^" + httpAliasFull, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); Match portalMatch = fullALiasRx.Match(originalUrl); if (portalMatch.Success == false) { - //Manage the special case where original url contains the alias as - //http://www.domain.com/Default.aspx?alias=www.domain.com/child" + // Manage the special case where original url contains the alias as + // http://www.domain.com/Default.aspx?alias=www.domain.com/child" var httpAliasRx = RegexUtils.GetCachedRegex("^?alias=" + httpAlias, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); portalMatch = httpAliasRx.Match(originalUrl); if (portalMatch.Success) @@ -659,8 +717,10 @@ private static string GetFriendlyAlias(string path, { httpAliasFull = Globals.AddHTTP(httpAlias); } + friendlyPath = httpAliasFull + friendlyPath; } + return friendlyPath; } @@ -668,19 +728,21 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa { string friendlyPath = path; Match queryStringMatch = FriendlyPathRegex.Match(friendlyPath); - string queryStringSpecialChars = ""; + string queryStringSpecialChars = string.Empty; if (!ReferenceEquals(queryStringMatch, Match.Empty)) { friendlyPath = queryStringMatch.Groups[1].Value; - friendlyPath = DefaultPageRegex.Replace(friendlyPath, ""); - if (String.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) != 0) - //take out the end page name, it will get re-added + friendlyPath = DefaultPageRegex.Replace(friendlyPath, string.Empty); + if (string.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) != 0) + + // take out the end page name, it will get re-added { var pgNameRx = RegexUtils.GetCachedRegex(pageName, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - friendlyPath = pgNameRx.Replace(friendlyPath, ""); + friendlyPath = pgNameRx.Replace(friendlyPath, string.Empty); } + string queryString = queryStringMatch.Groups[2].Value.Replace("&", "&"); - if ((queryString.StartsWith("?"))) + if (queryString.StartsWith("?")) { queryString = queryString.TrimStart('?'); } @@ -688,17 +750,17 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa string[] nameValuePairs = queryString.Split('&'); for (int i = 0; i <= nameValuePairs.Length - 1; i++) { - string pathToAppend = ""; + string pathToAppend = string.Empty; string[] pair = nameValuePairs[i].Split('='); - var illegalPageNames = new[]{"con", "aux", "nul", "prn"}; + var illegalPageNames = new[] { "con", "aux", "nul", "prn" }; if (!illegalPageNames.Contains(pair[0].ToLowerInvariant()) && (pair.Length == 1 || !illegalPageNames.Contains(pair[1].ToLowerInvariant()))) { - //Add name part of name/value pair + // Add name part of name/value pair if (friendlyPath.EndsWith("/")) { - if (pair[0].Equals("tabid", StringComparison.InvariantCultureIgnoreCase)) //always lowercase the tabid part of the path + if (pair[0].Equals("tabid", StringComparison.InvariantCultureIgnoreCase)) // always lowercase the tabid part of the path { pathToAppend = pathToAppend + pair[0].ToLowerInvariant(); } @@ -719,11 +781,11 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa var rx = RegexUtils.GetCachedRegex(settings.RegexMatch); if (rx.IsMatch(pair[1]) == false) { - // Contains Non-AlphaNumeric Characters + // Contains Non-AlphaNumeric Characters if (pair[0].ToLowerInvariant() == "tabid") { int tabId; - if (Int32.TryParse(pair[1], out tabId)) + if (int.TryParse(pair[1], out tabId)) { if (tab != null && tab.TabID == tabId) { @@ -733,23 +795,26 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa { pathToAppend = "/" + pathToAppend; } + pathToAppend = tab.TabPath.Replace("//", "/").TrimStart('/').TrimEnd('/') + pathToAppend; } } } } + if (pair[1].Contains(" ")) { if (tab != null && (tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings))) { - //741 : check admin paths to make sure they aren't using + encoding + // 741 : check admin paths to make sure they aren't using + encoding pathToAppend = pathToAppend + "/" + pair[1].Replace(" ", "%20"); } else { pathToAppend = pathToAppend + "/" + pair[1].Replace(" ", settings.SpaceEncodingValue); - //625 : replace space with specified url encoding value + + // 625 : replace space with specified url encoding value } } else @@ -761,9 +826,11 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa { var valueBuilder = new StringBuilder(pair.GetUpperBound(0)); string key = pair[0]; - //string value = pair[1]; + + // string value = pair[1]; valueBuilder.Append(pair[1]); - //if the querystring has been decoded and has a '=' in it, the value will get split more times. Put those back together with a loop. + + // if the querystring has been decoded and has a '=' in it, the value will get split more times. Put those back together with a loop. if (pair.GetUpperBound(0) > 1) { for (int j = 2; j <= pair.GetUpperBound(0); j++) @@ -772,7 +839,8 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa valueBuilder.Append(pair[j]); } } - // Rewrite into URL, contains only alphanumeric and the % or space + + // Rewrite into URL, contains only alphanumeric and the % or space if (queryStringSpecialChars.Length == 0) { queryStringSpecialChars = key + "=" + valueBuilder; @@ -781,13 +849,15 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa { queryStringSpecialChars = queryStringSpecialChars + "&" + key + "=" + valueBuilder; } - pathToAppend = ""; + + pathToAppend = string.Empty; } } else { pathToAppend = pathToAppend + "/" + settings.SpaceEncodingValue; - //625 : replace with specified space encoding value + + // 625 : replace with specified space encoding value } } } @@ -810,67 +880,73 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa } } - if ((queryStringSpecialChars.Length > 0)) + if (queryStringSpecialChars.Length > 0) { return AddPage(friendlyPath, pageName) + "?" + queryStringSpecialChars; } + return AddPage(friendlyPath, pageName); } - private static string ImproveFriendlyUrl(TabInfo tab, - string friendlyPath, - string pageName, - PortalSettings portalSettings, - bool ignoreCustomRedirects, - bool cultureSpecificAlias, - FriendlyUrlSettings settings, - Guid parentTraceId) + private static string ImproveFriendlyUrl( + TabInfo tab, + string friendlyPath, + string pageName, + PortalSettings portalSettings, + bool ignoreCustomRedirects, + bool cultureSpecificAlias, + FriendlyUrlSettings settings, + Guid parentTraceId) { - //older overload does not include informational/debug messages on return + // older overload does not include informational/debug messages on return List messages = null; - string url = ImproveFriendlyUrlWithMessages(tab, - friendlyPath, - pageName, - portalSettings, - ignoreCustomRedirects, - settings, - ref messages, - cultureSpecificAlias, - parentTraceId); + string url = ImproveFriendlyUrlWithMessages( + tab, + friendlyPath, + pageName, + portalSettings, + ignoreCustomRedirects, + settings, + ref messages, + cultureSpecificAlias, + parentTraceId); OutputFriendlyUrlMessages(tab, friendlyPath, "base/private", messages, url, settings); return url; } - private static string ImproveFriendlyUrlWithMessages(TabInfo tab, - string friendlyPath, - string pageName, - PortalSettings portalSettings, - bool ignoreCustomRedirects, - FriendlyUrlSettings settings, - ref List messages, - bool cultureSpecificAlias, - Guid parentTraceId) + private static string ImproveFriendlyUrlWithMessages( + TabInfo tab, + string friendlyPath, + string pageName, + PortalSettings portalSettings, + bool ignoreCustomRedirects, + FriendlyUrlSettings settings, + ref List messages, + bool cultureSpecificAlias, + Guid parentTraceId) { if (messages == null) { messages = new List(); } + string httpAlias = portalSettings.PortalAlias.HTTPAlias; - //invalid call just return the path + + // invalid call just return the path if (tab == null) { return friendlyPath; } - //no improved friendly urls for super tabs, admin tabs - if ((tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings)) && settings.FriendlyAdminHostUrls == false) //811 : allow for friendly admin/host urls + // no improved friendly urls for super tabs, admin tabs + if ((tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings)) && settings.FriendlyAdminHostUrls == false) // 811 : allow for friendly admin/host urls { return friendlyPath; } - //655 : no friendly url if matched with regex + // 655 : no friendly url if matched with regex if (!string.IsNullOrEmpty(settings.NoFriendlyUrlRegex)) { var rx = RegexUtils.GetCachedRegex(settings.NoFriendlyUrlRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); @@ -881,24 +957,28 @@ private static string ImproveFriendlyUrlWithMessages(TabInfo tab, } string result = friendlyPath; - //821 : new 'CustomOnly' setting which allows keeping base Urls but also using Custom Urls. Basically keeps search friendly - //but allows for customised urls and redirects + + // 821 : new 'CustomOnly' setting which allows keeping base Urls but also using Custom Urls. Basically keeps search friendly + // but allows for customised urls and redirects bool customOnly = settings.UrlFormat.Equals("customonly", StringComparison.InvariantCultureIgnoreCase); FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); - //determine if an improved friendly Url is wanted at all + + // determine if an improved friendly Url is wanted at all if ((settings.UrlFormat.Equals("advanced", StringComparison.InvariantCultureIgnoreCase) || customOnly) && !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, false)) { string newTabPath; string customHttpAlias; bool isHomePage = TabPathHelper.IsTabHomePage(tab, portalSettings); - //do a regex check on the base friendly Path, to see if there is parameters on the end or not - var tabOnlyRegex = RegexUtils.GetCachedRegex("[^?]*/tabId/(?\\d+)/" + pageName + "($|\\?(?.+$))", + + // do a regex check on the base friendly Path, to see if there is parameters on the end or not + var tabOnlyRegex = RegexUtils.GetCachedRegex( + "[^?]*/tabId/(?\\d+)/" + pageName + "($|\\?(?.+$))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); if (tabOnlyRegex.IsMatch(friendlyPath)) { MatchCollection tabOnlyMatches = tabOnlyRegex.Matches(friendlyPath); - string qs = ""; + string qs = string.Empty; if (tabOnlyMatches.Count > 0) { Match rgxMatch = tabOnlyMatches[0]; @@ -907,76 +987,84 @@ private static string ImproveFriendlyUrlWithMessages(TabInfo tab, qs = "?" + rgxMatch.Groups["qs"].Value; } } + bool dropLangParms; - //736: observe the culture code of the tab + + // 736: observe the culture code of the tab string cultureCode = tab.CultureCode; bool isDefaultLanguage = false; - if (cultureCode == "") + if (cultureCode == string.Empty) { cultureCode = portalSettings.DefaultLanguage; isDefaultLanguage = true; - //751 when using the default culture code, the redirect doesn't need an explicit language + + // 751 when using the default culture code, the redirect doesn't need an explicit language } + bool isCustomUrl; - newTabPath = TabPathHelper.GetTabPath(tab, - settings, - options, - ignoreCustomRedirects, - true, - isHomePage, - cultureCode, - isDefaultLanguage, - false, - out dropLangParms, - out customHttpAlias, - out isCustomUrl, - parentTraceId); - //770 : custom http alias found, merge into overall result + newTabPath = TabPathHelper.GetTabPath( + tab, + settings, + options, + ignoreCustomRedirects, + true, + isHomePage, + cultureCode, + isDefaultLanguage, + false, + out dropLangParms, + out customHttpAlias, + out isCustomUrl, + parentTraceId); + + // 770 : custom http alias found, merge into overall result if (!string.IsNullOrEmpty(customHttpAlias)) { httpAlias = customHttpAlias; messages.Add("Uses page-specific alias: " + customHttpAlias); } - //it is a straight page.aspx reference, with just the tabid to specify parameters, so get the extension that should be used (no pagename is used by design) - string extension = customHttpAlias != null && newTabPath == "" - ? "" + // it is a straight page.aspx reference, with just the tabid to specify parameters, so get the extension that should be used (no pagename is used by design) + string extension = customHttpAlias != null && newTabPath == string.Empty + ? string.Empty : DetermineExtension(isHomePage, pageName, settings); - if (customOnly && isCustomUrl || customOnly == false) + if ((customOnly && isCustomUrl) || customOnly == false) { result = Globals.AddHTTP(httpAlias + "/" + newTabPath.TrimStart('/') + extension) + qs; } } else { - //When the home page is requested with a querystring value, the path for the home page is included. This is because path items without the home page - //qualifier are incorrectly checked for as dnn pages, and will result in a 404. Ie domain.com/key/value will fail looking for a DNN path called 'key/value'. - //This gets around the problem because it places the path aas /home/key/value - which correctly identifies the tab as '/Home' and the key/value parameters as + // When the home page is requested with a querystring value, the path for the home page is included. This is because path items without the home page + // qualifier are incorrectly checked for as dnn pages, and will result in a 404. Ie domain.com/key/value will fail looking for a DNN path called 'key/value'. + // This gets around the problem because it places the path aas /home/key/value - which correctly identifies the tab as '/Home' and the key/value parameters as // &key=value. - //there are parameters on the base friendly url path, so split them off and process separately - //this regex splits the incoming friendly path pagename/tabid/56/default.aspx into the non-tabid path, and individual parms for each /parm/ in the friendly path - //550 : add in \. to allow '.' in the parameter path. - //667 : allow non-word characters (specifically %) in the path - var rgx = RegexUtils.GetCachedRegex("[^?]*(?/tabId/(?\\d+))(?(?(?:(?:/[^/?]+){1})+))(?:/" + pageName + ")(?:$|\\?(?.+$))", + // there are parameters on the base friendly url path, so split them off and process separately + // this regex splits the incoming friendly path pagename/tabid/56/default.aspx into the non-tabid path, and individual parms for each /parm/ in the friendly path + // 550 : add in \. to allow '.' in the parameter path. + // 667 : allow non-word characters (specifically %) in the path + var rgx = RegexUtils.GetCachedRegex( + "[^?]*(?/tabId/(?\\d+))(?(?(?:(?:/[^/?]+){1})+))(?:/" + pageName + ")(?:$|\\?(?.+$))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); MatchCollection matches = rgx.Matches(friendlyPath); if (matches.Count > 0) { - //it is a friendly url with other parameters in it - //format it up with the parameters in the end, keeping the same page name - //find the first param name in the params of the Url (the first path piece after the tabid/nn/ value) + // it is a friendly url with other parameters in it + // format it up with the parameters in the end, keeping the same page name + // find the first param name in the params of the Url (the first path piece after the tabid/nn/ value) Match rgxMatch = matches[0]; bool hasParms = false; string cultureCode = null; string defaultCode = null; const string newPageName = ""; - string newPath = ""; - string qs = ""; - string langParms = ""; - //check we matched on some parms in the path + string newPath = string.Empty; + string qs = string.Empty; + string langParms = string.Empty; + + // check we matched on some parms in the path if (rgxMatch.Groups["parms"] != null && rgxMatch.Groups["parms"].Success) { if (rgxMatch.Groups["parms"].Captures.Count > 0) @@ -987,104 +1075,110 @@ private static string ImproveFriendlyUrlWithMessages(TabInfo tab, Match langMatch = LangMatchRegex.Match(newPath); if (langMatch.Success) { - //a language specifier parameter is in the string - //this is always the last parameter in the list, which - //gives nasty pagename results, so shift the language query to before the page name + // a language specifier parameter is in the string + // this is always the last parameter in the list, which + // gives nasty pagename results, so shift the language query to before the page name // ie home/tabid/66/language/en-us/default.aspx will give home/language/en-us.aspx // we really want language/en-us/home.aspx langParms = langMatch.Value; langParms = langParms.TrimEnd('/'); - newPath = newPath.Replace(langParms, ""); + newPath = newPath.Replace(langParms, string.Empty); cultureCode = langMatch.Groups["code"].Value; - //obtain the culture code for this language + + // obtain the culture code for this language defaultCode = portalSettings.DefaultLanguage; } else { - //no language settings, use default + // no language settings, use default cultureCode = portalSettings.DefaultLanguage; defaultCode = cultureCode; } } } + bool dropLangParms; - //determine if we allow the home page to be shown as the site root. This is if : - //cultureCode = default culture, newPath is blank after removing languageParms - //allow site root for home page if it is the default culture and no other path items, or there is a specific alias for this culture and there are no other path items - bool homePageSiteRoot = (cultureCode == defaultCode && newPath == "") || (cultureSpecificAlias && newPath == ""); - bool hasPath = (newPath != ""); - - //871 : case insensitive comparison for culture - bool isDefaultLanguage = (String.Compare(cultureCode, defaultCode, StringComparison.OrdinalIgnoreCase) == 0); + + // determine if we allow the home page to be shown as the site root. This is if : + // cultureCode = default culture, newPath is blank after removing languageParms + // allow site root for home page if it is the default culture and no other path items, or there is a specific alias for this culture and there are no other path items + bool homePageSiteRoot = (cultureCode == defaultCode && newPath == string.Empty) || (cultureSpecificAlias && newPath == string.Empty); + bool hasPath = newPath != string.Empty; + + // 871 : case insensitive comparison for culture + bool isDefaultLanguage = string.Compare(cultureCode, defaultCode, StringComparison.OrdinalIgnoreCase) == 0; bool isCustomUrl; - newTabPath = TabPathHelper.GetTabPath(tab, - settings, - options, - ignoreCustomRedirects, - homePageSiteRoot, - isHomePage, - cultureCode, - isDefaultLanguage, - hasPath, - out dropLangParms, - out customHttpAlias, - out isCustomUrl, - parentTraceId); + newTabPath = TabPathHelper.GetTabPath( + tab, + settings, + options, + ignoreCustomRedirects, + homePageSiteRoot, + isHomePage, + cultureCode, + isDefaultLanguage, + hasPath, + out dropLangParms, + out customHttpAlias, + out isCustomUrl, + parentTraceId); if (hasParms) { bool changeToSiteRoot; - //remove any parts of the path excluded by regex + // remove any parts of the path excluded by regex RemoveExcludedPartsOfPath(settings, ref newPath, ref qs); - if (newPath == "" && isHomePage) + if (newPath == string.Empty && isHomePage) { - //956 : recheck the test for the homePagebeing a site root Url - homePageSiteRoot = (cultureCode == defaultCode && newPath == "") || (cultureSpecificAlias && newPath == ""); - hasPath = (newPath != ""); + // 956 : recheck the test for the homePagebeing a site root Url + homePageSiteRoot = (cultureCode == defaultCode && newPath == string.Empty) || (cultureSpecificAlias && newPath == string.Empty); + hasPath = newPath != string.Empty; if (homePageSiteRoot) { - //special case - if the newPath is empty after removing the parameters, and it is the home page, and the home page is only to show the site root - //then re-get the home page Url with no params (hasPath=false) - //done like this to re-run all rules relating the url - newTabPath = TabPathHelper.GetTabPath(tab, - settings, - options, - ignoreCustomRedirects, - homePageSiteRoot, - isHomePage, - cultureCode, - isDefaultLanguage, - hasPath, - out dropLangParms, - out customHttpAlias, - out isCustomUrl, - parentTraceId); + // special case - if the newPath is empty after removing the parameters, and it is the home page, and the home page is only to show the site root + // then re-get the home page Url with no params (hasPath=false) + // done like this to re-run all rules relating the url + newTabPath = TabPathHelper.GetTabPath( + tab, + settings, + options, + ignoreCustomRedirects, + homePageSiteRoot, + isHomePage, + cultureCode, + isDefaultLanguage, + hasPath, + out dropLangParms, + out customHttpAlias, + out isCustomUrl, + parentTraceId); } } - //check for parameter regex replacement + // check for parameter regex replacement string changedPath; bool allowOtherParameters; - if (FriendlyUrlPathController.CheckUserProfileReplacement(newPath, - tab, - portalSettings, - settings, - options, - out changedPath, - out changeToSiteRoot, - out allowOtherParameters, - ref messages, - parentTraceId)) + if (FriendlyUrlPathController.CheckUserProfileReplacement( + newPath, + tab, + portalSettings, + settings, + options, + out changedPath, + out changeToSiteRoot, + out allowOtherParameters, + ref messages, + parentTraceId)) { messages.Add("User Profile Replacement: Old Path=" + newPath + "; Changed Path=" + changedPath); newPath = changedPath; } - //transform is ctl/privacy, ctl/login etc + // transform is ctl/privacy, ctl/login etc bool builtInUrl = TransformStandardPath(ref newPath, ref newTabPath); - //770 : custom http alias found, merge into overall result (except if builtin url, which don't get to use custom aliases) - //820 : allow for custom http aliases for builtin urls as well (reverses 770). Otherwise, can't log in to other aliases. + // 770 : custom http alias found, merge into overall result (except if builtin url, which don't get to use custom aliases) + // 820 : allow for custom http aliases for builtin urls as well (reverses 770). Otherwise, can't log in to other aliases. if (!string.IsNullOrEmpty(customHttpAlias)) { httpAlias = customHttpAlias; @@ -1093,81 +1187,87 @@ private static string ImproveFriendlyUrlWithMessages(TabInfo tab, if (allowOtherParameters) { - //738 : check for transformation by module specific provider - //894 : allow module providers to be disabled + // 738 : check for transformation by module specific provider + // 894 : allow module providers to be disabled bool customModuleUrl = false; if (settings.EnableCustomProviders) { - customModuleUrl = ExtensionUrlProviderController.GetUrlFromExtensionUrlProviders(portalSettings.PortalId, - tab, - settings, - newPath, - cultureCode, - ref pageName, - out changedPath, - out changeToSiteRoot, - ref messages, - parentTraceId); + customModuleUrl = ExtensionUrlProviderController.GetUrlFromExtensionUrlProviders( + portalSettings.PortalId, + tab, + settings, + newPath, + cultureCode, + ref pageName, + out changedPath, + out changeToSiteRoot, + ref messages, + parentTraceId); } - //when no custom module Urls, check for any regex replacements by way of the friendlyurlparms.config file + + // when no custom module Urls, check for any regex replacements by way of the friendlyurlparms.config file if (!customModuleUrl) { - if (FriendlyUrlPathController.CheckParameterRegexReplacement(newPath, - tab, - settings, - portalSettings.PortalId, - out changedPath, - ref messages, - out changeToSiteRoot, - parentTraceId)) + if (FriendlyUrlPathController.CheckParameterRegexReplacement( + newPath, + tab, + settings, + portalSettings.PortalId, + out changedPath, + ref messages, + out changeToSiteRoot, + parentTraceId)) { newPath = changedPath; } } else { - //update path value with custom Url returned from module provider(s) + // update path value with custom Url returned from module provider(s) newPath = changedPath; } } - //start constructing the url - //get the page and extension - //770 : when using a custom http alias, and there is no Url for that path, there's no extension regardless of settings - //because it's treated like a site root (quasi home page if you like) - string pageAndExtension = customHttpAlias != null && newTabPath == "" - ? "" + // start constructing the url + // get the page and extension + // 770 : when using a custom http alias, and there is no Url for that path, there's no extension regardless of settings + // because it's treated like a site root (quasi home page if you like) + string pageAndExtension = customHttpAlias != null && newTabPath == string.Empty + ? string.Empty : DeterminePageNameAndExtension(ref pageName, settings); - //prepend querystring qualifier if necessary - qs = !string.IsNullOrEmpty(qs) ? "?" + qs : ""; - //string it all together + // prepend querystring qualifier if necessary + qs = !string.IsNullOrEmpty(qs) ? "?" + qs : string.Empty; + + // string it all together if (!dropLangParms) { - //871 : case insensitive culture comparisons - //drop the language parameters when the defaultCode is the cultureCode for this Url, or the portal alias defines the culture code + // 871 : case insensitive culture comparisons + // drop the language parameters when the defaultCode is the cultureCode for this Url, or the portal alias defines the culture code dropLangParms = isDefaultLanguage || cultureSpecificAlias; - // (defaultCode.ToLower() == cultureCode.ToLower()) || cultureSpecificAlias; + + // (defaultCode.ToLower() == cultureCode.ToLower()) || cultureSpecificAlias; } - string finalPath = CreateFriendlyUrl(httpAlias, - newTabPath, - newPath, - pageAndExtension, - newPageName, - qs, - langParms, - ref messages, - builtInUrl, - changeToSiteRoot, - dropLangParms, - isHomePage); - - //702: look for _aumdebug=true|false and remove if so - never want it part of the output friendly url path - - finalPath = AumDebugRegex.Replace(finalPath, ""); - - //'and we're done! - if (customOnly && isCustomUrl || customOnly == false || builtInUrl) + + string finalPath = CreateFriendlyUrl( + httpAlias, + newTabPath, + newPath, + pageAndExtension, + newPageName, + qs, + langParms, + ref messages, + builtInUrl, + changeToSiteRoot, + dropLangParms, + isHomePage); + + // 702: look for _aumdebug=true|false and remove if so - never want it part of the output friendly url path + finalPath = AumDebugRegex.Replace(finalPath, string.Empty); + + // 'and we're done! + if ((customOnly && isCustomUrl) || customOnly == false || builtInUrl) { result = Globals.AddHTTP(finalPath); } @@ -1176,10 +1276,10 @@ private static string ImproveFriendlyUrlWithMessages(TabInfo tab, else { var re = RegexUtils.GetCachedRegex("[^?]*/tabId/(\\d+)/ctl/([A-Z][a-z]+)/" + pageName + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - if ((re.IsMatch(friendlyPath))) + if (re.IsMatch(friendlyPath)) { Match sesMatch = re.Match(friendlyPath); - if ((sesMatch.Groups.Count > 2)) + if (sesMatch.Groups.Count > 2) { switch (sesMatch.Groups[2].Value.ToLowerInvariant()) { @@ -1204,24 +1304,27 @@ private static string ImproveFriendlyUrlWithMessages(TabInfo tab, } } } + return result; } - private static void OutputFriendlyUrlMessages(TabInfo tab, - string path, - string method, - List messages, - string resultUrl, - FriendlyUrlSettings settings) + private static void OutputFriendlyUrlMessages( + TabInfo tab, + string path, + string method, + List messages, + string resultUrl, + FriendlyUrlSettings settings) { if (settings != null && settings.AllowDebugCode && HttpContext.Current != null) { HttpRequest request = HttpContext.Current.Request; string debugCheck = CheckForDebug(request); - if (debugCheck != "" && debugCheck != "false") + if (debugCheck != string.Empty && debugCheck != "false") { int id = DateTime.Now.Millisecond; - //append the friendly url headers + + // append the friendly url headers HttpResponse response = HttpContext.Current.Response; string msgId = id.ToString("000"); int tabId = -1; @@ -1231,12 +1334,14 @@ private static void OutputFriendlyUrlMessages(TabInfo tab, tabId = tab.TabID; tabName = tab.TabName; } + msgId += "-" + tabId.ToString("000"); if (messages != null && messages.Count > 0) { - response.AppendHeader("X-Friendly-Url-" + msgId + ".00", - "Messages for Tab " + tabId.ToString() + ", " + tabName + ", " + path + " calltype:" + method); + response.AppendHeader( + "X-Friendly-Url-" + msgId + ".00", + "Messages for Tab " + tabId.ToString() + ", " + tabName + ", " + path + " calltype:" + method); int i = 1; foreach (string msg in messages) @@ -1244,33 +1349,41 @@ private static void OutputFriendlyUrlMessages(TabInfo tab, response.AppendHeader("X-Friendly-Url-" + msgId + "." + i.ToString("00"), msg); i++; } + if (resultUrl != null) { - response.AppendHeader("X-Friendly-Url-" + msgId + ".99", - "Path : " + path + " Generated Url : " + resultUrl); + response.AppendHeader( + "X-Friendly-Url-" + msgId + ".99", + "Path : " + path + " Generated Url : " + resultUrl); } } else { if (debugCheck == "all") { - response.AppendHeader("X-Friendly-Url-" + msgId + ".00", - "Path : " + path + " Generated Url: " + resultUrl); + response.AppendHeader( + "X-Friendly-Url-" + msgId + ".00", + "Path : " + path + " Generated Url: " + resultUrl); } } } } } - private static void RemoveExcludedPartsOfPath(FriendlyUrlSettings settings, ref string newPath, ref string qs) { // Do nothing, if path is empty - if (string.IsNullOrWhiteSpace(newPath)) return; + if (string.IsNullOrWhiteSpace(newPath)) + { + return; + } // Do nothing, if DoNotIncludeInPathRegex is not defined - if (string.IsNullOrWhiteSpace(settings.DoNotIncludeInPathRegex)) return; - + if (string.IsNullOrWhiteSpace(settings.DoNotIncludeInPathRegex)) + { + return; + } + // Split path by "/" to extract keys and values var pathParts = newPath.Trim('/').Split('/'); @@ -1283,7 +1396,7 @@ private static void RemoveExcludedPartsOfPath(FriendlyUrlSettings settings, ref for (var i = 0; i < pathParts.Length; i = i + 2) { // Just append to path, if no value exists - if (pathParts.Length <= i+1) + if (pathParts.Length <= i + 1) { pathBuilder.Append(string.Format("/{0}", pathParts[i])); continue; @@ -1294,7 +1407,11 @@ private static void RemoveExcludedPartsOfPath(FriendlyUrlSettings settings, ref var value = pathParts[i + 1]; if (notInPath.IsMatch(string.Format("/{0}/{1}", key, value))) { - if (queryStringBuilder.Length > 0) queryStringBuilder.Append("&"); + if (queryStringBuilder.Length > 0) + { + queryStringBuilder.Append("&"); + } + queryStringBuilder.Append(string.Format("{0}={1}", key, value)); } else @@ -1304,21 +1421,23 @@ private static void RemoveExcludedPartsOfPath(FriendlyUrlSettings settings, ref } // No param was added to query string, return (newPath remain unchanged) - if (queryStringBuilder.Length == 0) return; + if (queryStringBuilder.Length == 0) + { + return; + } // Build new path and query string newPath = pathBuilder.ToString(); - qs = string.IsNullOrWhiteSpace(qs) ? - queryStringBuilder.ToString() : + qs = string.IsNullOrWhiteSpace(qs) ? + queryStringBuilder.ToString() : string.Format("{0}&{1}", qs, queryStringBuilder); - } private static bool TransformStandardPath(ref string newPath, ref string newTabPath) { - //615 : output simple urls for login, privacy, register and terms urls + // 615 : output simple urls for login, privacy, register and terms urls bool builtInUrl = false; - if (newPath != "/" && newPath != "" && "/ctl/privacy|/ctl/login|/ctl/register|/ctl/terms".Contains(newPath.ToLowerInvariant())) + if (newPath != "/" && newPath != string.Empty && "/ctl/privacy|/ctl/login|/ctl/register|/ctl/terms".Contains(newPath.ToLowerInvariant())) { builtInUrl = true; var lowerNewPath = newPath.ToLowerInvariant(); @@ -1326,61 +1445,24 @@ private static bool TransformStandardPath(ref string newPath, ref string newTabP { case "/ctl/privacy": newTabPath = "Privacy"; - newPath = lowerNewPath.Replace("/ctl/privacy", ""); + newPath = lowerNewPath.Replace("/ctl/privacy", string.Empty); break; case "/ctl/login": newTabPath = "Login"; - newPath = lowerNewPath.Replace("/ctl/login", ""); + newPath = lowerNewPath.Replace("/ctl/login", string.Empty); break; case "/ctl/register": newTabPath = "Register"; - newPath = lowerNewPath.Replace("/ctl/register", ""); + newPath = lowerNewPath.Replace("/ctl/register", string.Empty); break; case "/ctl/terms": newTabPath = "Terms"; - newPath = lowerNewPath.Replace("/ctl/terms", ""); + newPath = lowerNewPath.Replace("/ctl/terms", string.Empty); break; } } - return builtInUrl; - } - -#endregion - -#region Internal Methods - internal static string ForceLowerCaseIfAllowed(TabInfo tab, string url, FriendlyUrlSettings settings) - { - //606 : include regex to stop lower case in certain circumstances - //840 : change to re-introduce lower case restrictions on admin / host tabs - if (tab != null) - { - if (!(tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings))) - { - bool forceLowerCase = (settings.ForceLowerCase); - if (forceLowerCase) - { - if (!string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) - { - var rx = RegexUtils.GetCachedRegex(settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - forceLowerCase = !rx.IsMatch(url); - } - } - if (forceLowerCase) - { - //don't force lower case for Urls excluded from being 'friendly' - forceLowerCase = (!RewriteController.IsExcludedFromFriendlyUrls(tab, settings, false)); - } - - if (forceLowerCase) - { - url = url.ToLowerInvariant(); - } - } - } - return url; + return builtInUrl; } - -#endregion } } diff --git a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs index d1ca00ed79a..84b7d9d416c 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs @@ -1,2881 +1,3110 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Security.Principal; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using System.Web.Configuration; -using System.Web.Security; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Services.EventQueue; - -#endregion - -namespace DotNetNuke.Entities.Urls -{ - public class AdvancedUrlRewriter : UrlRewriterBase - { - private static readonly Regex DefaultPageRegex = new Regex(@"(?.[^&]+)=$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex UrlSlashesRegex = new Regex("[\\\\/]\\.\\.[\\\\/]", RegexOptions.Compiled); - private static readonly Regex AliasUrlRegex = new Regex(@"(?:^(?http[s]{0,1}://){0,1})(?:(?_ALIAS_)(?$|\?[\w]*|/[\w]*))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - - #region Private Members - - private const string _productName = "AdvancedUrlRewriter"; - private FriendlyUrlSettings _settings; - - #endregion - - #region Overridden Methods - - internal override void RewriteUrl(object sender, EventArgs e) - { - Guid parentTraceId = Guid.Empty; - const bool debug = true; - bool failedInitialization = false; - bool ignoreForInstall = false; - var app = (HttpApplication) sender; - try - { - //875 : completely ignore install/upgrade requests immediately - ignoreForInstall = IgnoreRequestForInstall(app.Request); - - if (ignoreForInstall == false) - { - _settings = new FriendlyUrlSettings(-1); - - SecurityCheck(app); - } - - } - catch (Exception ex) - { - //exception handling for advanced Url Rewriting requests - failedInitialization = true; - DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); - if (app.Context != null) - { - ShowDebugData(app.Context, app.Request.Url.AbsoluteUri, null, ex); - var action = new UrlAction(app.Request) { Action = ActionType.Output404 }; - Handle404OrException(_settings, app.Context, ex, action, false, debug); - } - else - { - throw; - } - } - if (!failedInitialization && !ignoreForInstall) - { - //if made it through there and not installing, go to next call. Not in exception catch because it implements it's own top-level exception handling - var request = app.Context.Request; - - //829 : change constructor to stop using physical path - var result = new UrlAction(request) - { - IsSecureConnection = request.IsSecureConnection, - IsSSLOffloaded = UrlUtils.IsSslOffloadEnabled(request), - RawUrl = request.RawUrl - }; - ProcessRequest(app.Context, - app.Context.Request.Url, - Host.Host.UseFriendlyUrls, - result, - _settings, - true, - parentTraceId); - } - } - - #endregion - - #region Public Methods - - public void ProcessTestRequestWithContext(HttpContext context, - Uri requestUri, - bool useFriendlyUrls, - UrlAction result, - FriendlyUrlSettings settings) - { - Guid parentTraceId = Guid.Empty; - _settings = settings; - ProcessRequest(context, - requestUri, - useFriendlyUrls, - result, - settings, - false, - parentTraceId); - } - - #endregion - - #region Private Methods - - private PortalAliasInfo GetPortalAlias(FriendlyUrlSettings settings, string requestUrl, out bool redirectAlias, out bool isPrimaryAlias, out string wrongAlias) - { - PortalAliasInfo aliasInfo = null; - redirectAlias = false; - wrongAlias = null; - isPrimaryAlias = false; - OrderedDictionary portalAliases = TabIndexController.GetPortalAliases(settings); - foreach (string alias in portalAliases.Keys) - { - var urlToMatch = requestUrl; - // in fact, requested url should contain alias - // for better performance, need to check whether we want to proceed with a whole url matching or not - // if alias is not a part of url -> let's proceed to the next iteration - var aliasIndex = urlToMatch.IndexOf(alias, StringComparison.InvariantCultureIgnoreCase); - if (aliasIndex < 0) - { - continue; - } - else - { - // we do not accept URL if the first occurence of alias is presented somewhere in the query string - var queryIndex = urlToMatch.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); - if (queryIndex >= 0 && queryIndex < aliasIndex) - { - // alias is in the query string, go to the next alias - continue; - } - // we are fine here, lets prepare URL to be validated in regex - urlToMatch = urlToMatch.ReplaceIgnoreCase(alias, "_ALIAS_"); - } - // check whether requested URL has the right URL format containing existing alias - // i.e. url is http://dnndev.me/site1/query?string=test, alias is dnndev.me/site1 - // in the below expression we will validate following value http://_ALIAS_/query?string=test - var aliasMatch = AliasUrlRegex.Match(urlToMatch); - if (aliasMatch.Success) - { - //check for mobile browser and matching - var aliasEx = (PortalAliasInfo)portalAliases[alias]; - redirectAlias = aliasEx.Redirect; - if (redirectAlias) - { - wrongAlias = alias; - } - isPrimaryAlias = aliasEx.IsPrimary; - aliasInfo = aliasEx; - break; - } - } - return aliasInfo; - } - - private void ProcessRequest(HttpContext context, - Uri requestUri, - bool useFriendlyUrls, - UrlAction result, - FriendlyUrlSettings settings, - bool allowSettingsChange, - Guid parentTraceId) - { - bool finished = false; - bool showDebug = false; - bool postRequest = false; - - HttpRequest request = context.Request; - HttpResponse response = context.Response; - string requestType = request.RequestType; - NameValueCollection queryStringCol = request.QueryString; - - try - { - - string fullUrl, querystring; - //699: get the full url based on the request and the quersytring, rather than the requestUri.ToString() - //there is a difference in encoding, which can corrupt results when an encoded value is in the querystring - RewriteController.GetUrlWithQuerystring(request, requestUri, out fullUrl, out querystring); - - showDebug = CheckForDebug(request, queryStringCol, settings.AllowDebugCode); - string ignoreRegex = settings.IgnoreRegex; - bool ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); - bool redirectAlias = false; - if (!ignoreRequest) - { - //set original path - context.Items["UrlRewrite:OriginalUrl"] = requestUri.AbsoluteUri; - - //set the path of the result object, and determine if a redirect is allowed on this request - result.SetOriginalPath(requestUri.ToString(), settings); - //737 : set the mobile browser - result.SetBrowserType(request, response, settings); - //add to context - context.Items["UrlRewrite:BrowserType"] = result.BrowserType.ToString(); - - //839 : split out this check - result.SetRedirectAllowed(result.OriginalPath, settings); - - //find the portal alias first - string wrongAlias; - bool isPrimaryAlias; - var requestedAlias = GetPortalAlias(settings, fullUrl, out redirectAlias, out isPrimaryAlias, out wrongAlias); - - if (requestedAlias != null) - { - //827 : now get the correct settings for this portal (if not a test request) - //839 : separate out redirect check as well and move above first redirect test (ConfigurePortalAliasRedirect) - if (allowSettingsChange) - { - settings = new FriendlyUrlSettings(requestedAlias.PortalID); - result.SetRedirectAllowed(result.OriginalPath, settings); - } - result.PortalAlias = requestedAlias; - result.PrimaryAlias = requestedAlias;//this is the primary alias - result.PortalId = requestedAlias.PortalID; - result.CultureCode = requestedAlias.CultureCode; - //get the portal alias mapping for this portal - result.PortalAliasMapping = PortalSettingsController.Instance().GetPortalAliasMappingMode(requestedAlias.PortalID); - - //if requested alias wasn't the primary, we have a replacement, redirects are allowed and the portal alias mapping mode is redirect - //then do a redirect based on the wrong portal - if ((redirectAlias && wrongAlias != null) && result.RedirectAllowed && result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) - { - //this is the alias, we are going to enforce it as the primary alias - result.PortalAlias = requestedAlias; - result.PrimaryAlias = requestedAlias; - //going to redirect this alias because it is incorrect - //or do we just want to mark as 'check for 301??' - redirectAlias = ConfigurePortalAliasRedirect(ref result, - wrongAlias, - requestedAlias.HTTPAlias, - false, - settings.InternalAliasList, - settings); - } - else - { - //do not redirect the wrong alias, but set the primary alias value - if (wrongAlias != null) - { - //get the portal alias info for the requested alias (which is the wrong one) - //and set that as the alias, but also set the found alias as the primary - PortalAliasInfo wrongAliasInfo = PortalAliasController.Instance.GetPortalAlias(wrongAlias); - if (wrongAliasInfo != null) - { - result.PortalAlias = wrongAliasInfo; - result.PrimaryAlias = requestedAlias; - } - - } - } - } - } - ignoreRegex = settings.IgnoreRegex; - ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); - if (!ignoreRequest) - { - //check to see if a post request - if (request.RequestType == "POST") - { - postRequest = true; - } - - //check the portal alias again. This time, in more depth now that the portal Id is known - //this check handles browser types/language specific aliases & mobile aliases - string primaryHttpAlias; - if (!redirectAlias && IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryHttpAlias)) - { - //it was an incorrect alias - PortalAliasInfo primaryAlias = PortalAliasController.Instance.GetPortalAlias(primaryHttpAlias); - if (primaryAlias != null) result.PrimaryAlias = primaryAlias; - //try and redirect the alias if the settings allow it - redirectAlias = RedirectPortalAlias(primaryHttpAlias, ref result, settings); - } - - if (redirectAlias) - { - //not correct alias for portal : will be redirected - //perform a 301 redirect if one has already been found - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl, false); - finished = true; - } - if (!finished) - { - //Check to see if this to be rewritten into default.aspx?tabId=nn format - //this call is the main rewriting matching call. It makes the decision on whether it is a - //physical file, whether it is toe be rewritten or redirected by way of a stored rule - - //Check if we have a standard url - var uri = new Uri(fullUrl); - if (uri.PathAndQuery.StartsWith("/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - result.DoRewrite = true; - result.Action = ActionType.CheckFor301; - result.RewritePath = Globals.glbDefaultPage + uri.Query; - } - else - { - bool isPhysicalResource; - CheckForRewrite(fullUrl, querystring, result, useFriendlyUrls, queryStringCol, settings, out isPhysicalResource, parentTraceId); - } - - //return 404 if there is no portal alias for a rewritten request - if (result.DoRewrite && result.PortalAlias == null) - { - //882 : move this logic in from where it was before to here - //so that non-rewritten requests don't trip over it - //no portal alias found for the request : that's a 404 error - result.Action = ActionType.Output404; - result.Reason = RedirectReason.No_Portal_Alias; - - Handle404OrException(settings, context, null, result, false, showDebug); - finished = true; //cannot fulfil request unless correct portal alias specified - } - } - - if (!finished && result.DoRewrite) - { - //check the identified portal alias details for any extra rewrite information required - //this includes the culture and the skin, which can be placed into the rewrite path - //This logic is here because it will catch any Urls which are excluded from rewriting - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - - if (result.PortalId > -1 && result.HttpAlias != null) - { - string culture; - string skin; - BrowserTypes browserType; - primaryAliases.GetSettingsByPortalIdAndAlias(result.PortalId, result.HttpAlias, - out culture, - out browserType, - out skin); - //add language code to path if it exists (not null) and if it's not already there - string rewritePath = result.RewritePath; - if (RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, culture)) - { - result.CultureCode = culture; - } - - //852: add skinSrc to path if it exists and if it's not already there - string debugMessage; - RewriteController.AddSkinToRewritePath(result.TabId, result.PortalId, ref rewritePath, skin, out debugMessage); - result.RewritePath = rewritePath; //reset back from ref temp var - if (debugMessage != null) - { - result.DebugMessages.Add(debugMessage); - } - } - } - - if (!finished && result.DoRewrite) - { - //if so, do the rewrite - if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false) - { - if (result.RewritePath.Contains(Globals.glbDefaultPage) == false) - { - RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); - } - else - { - //if there is no TabId and we have the domain - if (!result.RewritePath.ToLowerInvariant().Contains("tabId=")) - { - RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); - } - else - { - RewriterUtils.RewriteUrl(context, result.RewritePath); - } - } - } - else - { - RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); - } - } - - //confirm which portal the request is for - if (!finished) - { - IdentifyPortalAlias(context, request, requestUri, result, queryStringCol, settings, parentTraceId); - if (result.Action == ActionType.Redirect302Now) - { - //performs a 302 redirect if requested - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl, false); - finished = true; - } - else - { - if (result.Action == ActionType.Redirect301 && !string.IsNullOrEmpty(result.FinalUrl)) - { - finished = true; - //perform a 301 redirect if one has already been found - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl, false); - } - } - } - - if (!finished) - { - //check to see if this tab has an external url that should be forwared or not - finished = CheckForTabExternalForwardOrRedirect(context, ref result, response, settings, parentTraceId); - } - - //check for a parameter redirect (we had to do all the previous processing to know we are on the right portal and identify the tabid) - //if the CustomParmRewrite flag is set, it means we already rewrote these parameters, so they have to be correct, and aren't subject to - //redirection. The only reason to do a custom parm rewrite is to interpret already-friendly parameters - if (!finished - && !postRequest /* either request is null, or it's not a post - 551 */ - && result.HttpAlias != null /* must have a http alias */ - && !result.CustomParmRewrite && /* not custom rewritten parms */ - ((settings.EnableCustomProviders && - RedirectController.CheckForModuleProviderRedirect(requestUri, ref result, queryStringCol, settings, parentTraceId)) - //894 : allow disable of all custom providers - || - RedirectController.CheckForParameterRedirect(requestUri, ref result, queryStringCol, settings))) - { - //301 redirect to new location based on parameter match - if (response != null) - { - switch (result.Action) - { - case ActionType.Redirect301: - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - break; - case ActionType.Redirect302: - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl); - break; - case ActionType.Output404: - response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); - Handle404OrException(settings, context, null, result, true, showDebug); - break; - } - } - finished = true; - } - - //shifted until after the 301 redirect code to allow redirects to be checked for pages which have no rewrite value - //look for a 404 result from the rewrite, because of a deleted page or rule - if (!finished && result.Action == ActionType.Output404) - { - if (result.OriginalPath.Equals(result.HttpAlias, StringComparison.InvariantCultureIgnoreCase) - && result.PortalAlias != null - && result.Reason != RedirectReason.Deleted_Page - && result.Reason != RedirectReason.Disabled_Page) - { - //Request for domain with no page identified (and no home page set in Site Settings) - result.Action = ActionType.Continue; - } - else - { - finished = true; - response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); - - if (showDebug) - { - ShowDebugData(context, requestUri.AbsoluteUri, result, null); - } - //show the 404 page if configured - result.Reason = RedirectReason.Requested_404; - Handle404OrException(settings, context, null, result, true, showDebug); - } - } - - if (!finished) - { - //add the portal settings to the app context if the portal alias has been found and is correct - if (result.PortalId != -1 && result.PortalAlias != null) - { - //for invalid tab id other than -1, show the 404 page - TabInfo tabInfo = TabController.Instance.GetTab(result.TabId, result.PortalId, false); - if (tabInfo == null && result.TabId > -1) - { - finished = true; - - if (showDebug) - { - ShowDebugData(context, requestUri.AbsoluteUri, result, null); - } - - //show the 404 page if configured - result.Action = ActionType.Output404; - result.Reason = RedirectReason.Requested_404; - response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); - Handle404OrException(settings, context, null, result, true, showDebug); - } - else - { - Globals.SetApplicationName(result.PortalId); - // load the PortalSettings into current context - var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); - //set the primary alias if one was specified - if (result.PrimaryAlias != null) portalSettings.PrimaryAlias = result.PrimaryAlias; - - if (result.CultureCode != null && fullUrl.Contains(result.CultureCode) && - portalSettings.DefaultLanguage == result.CultureCode) - { - //when the request culture code is the same as the portal default, check for a 301 redirect, because we try and remove the language from the url where possible - result.Action = ActionType.CheckFor301; - } - - int portalHomeTabId = portalSettings.HomeTabId; - if (context != null && portalSettings != null && !context.Items.Contains("PortalSettings")) - { - context.Items.Add("PortalSettings", portalSettings); - - // load PortalSettings and HostSettings dictionaries into current context - // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way - context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalSettings.PortalId)); - context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary()); - } - //check if a secure redirection is needed - //this would be done earlier in the piece, but need to know the portal settings, tabid etc before processing it - bool redirectSecure = CheckForSecureRedirect(portalSettings, requestUri, result, queryStringCol, settings); - if (redirectSecure) - { - if (response != null) - { - //702 : don't check final url until checked for null reference first - if (result.FinalUrl != null) - { - if (result.FinalUrl.StartsWith("https://")) - { - if (showDebug) - { - /* - string debugMsg = "{0}, {1}, {2}, {3}, {4}"; - string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); - response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); - */ - ShowDebugData(context, fullUrl, result, null); - } - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - finished = true; - } - else - { - if (settings.SSLClientRedirect) - { - //redirect back to http version, use client redirect - response.Clear(); - // add a refresh header to the response - response.AddHeader("Refresh", "0;URL=" + result.FinalUrl); - // add the clientside javascript redirection script - var finalUrl = HttpUtility.HtmlEncode(result.FinalUrl); - response.Write(""); - response.Write(@""); - response.Write(""); - if (showDebug) - { - /* - string debugMsg = "{0}, {1}, {2}, {3}, {4}"; - string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); - response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); - */ - ShowDebugData(context, fullUrl, result, null); - } - // send the response - //891 : reinstate the response.end to stop the entire page loading - response.End(); - finished = true; - } - else - { - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - finished = true; - } - } - } - } - } - else - { - //check for, and do a 301 redirect if required - if (CheckForRedirects(requestUri, fullUrl, queryStringCol, result, requestType, settings, portalHomeTabId)) - { - if (response != null) - { - if (result.Action == ActionType.Redirect301) - { - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl, false); - finished = true; - } - else if (result.Action == ActionType.Redirect302) - { - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl, false); - finished = true; - } - } - } - else - { - //612 : Don't clear out a 302 redirect if set - if (result.Action != ActionType.Redirect302 && - result.Action != ActionType.Redirect302Now) - { - result.Reason = RedirectReason.Not_Redirected; - result.FinalUrl = null; - } - } - } - } - } - else - { - // alias does not exist in database - // and all attempts to find another have failed - //this should only happen if the HostPortal does not have any aliases - result.Action = ActionType.Output404; - if (response != null) - { - if (showDebug) - { - ShowDebugData(context, fullUrl, result, null); - } - result.Reason = RedirectReason.Requested_404; - //912 : change 404 type to transfer to allow transfer to main portal in single-portal installs - Handle404OrException(settings, context, null, result, true, showDebug); - finished = true; - } - } - } - - //404 page ?? - if (settings.TabId404 > 0 && settings.TabId404 == result.TabId) - { - string status = queryStringCol["status"]; - if (status == "404") - { - //respond with a 404 error - result.Action = ActionType.Output404; - result.Reason = RedirectReason.Requested_404_In_Url; - Handle404OrException(settings, context, null, result, true, showDebug); - } - } - else - { - if (result.DoRewrite == false && result.CanRewrite != StateBoolean.False && !finished && - result.Action == ActionType.Continue) - { - //739 : catch no-extension 404 errors - string pathWithNoQs = result.OriginalPath; - if (pathWithNoQs.Contains("?")) - { - pathWithNoQs = pathWithNoQs.Substring(0, pathWithNoQs.IndexOf("?", StringComparison.Ordinal)); - } - if (!pathWithNoQs.Substring(pathWithNoQs.Length - 5, 5).Contains(".")) - { - //no page extension, output a 404 if the Url is not found - //766 : check for physical path before passing off as a 404 error - //829 : change to use action physical path - //893 : filter by regex pattern to exclude urls which are valid, but show up as extensionless - if ((request != null && Directory.Exists(result.PhysicalPath)) - || - Regex.IsMatch(pathWithNoQs, settings.ValidExtensionlessUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) - { - //do nothing : it's a request for a valid physical path, maybe including a default document - result.VirtualPath = StateBoolean.False; - } - else - { - if (!Globals.ServicesFrameworkRegex.IsMatch(context.Request.RawUrl)) - { - //no physical path, intercept the request and hand out a 404 error - result.Action = ActionType.Output404; - result.Reason = RedirectReason.Page_404; - result.VirtualPath = StateBoolean.True; - //add in a message to explain this 404, becaue it can be cryptic - result.DebugMessages.Add("404 Reason : Not found and no extension"); - Handle404OrException(settings, context, null, result, true, showDebug); - } - } - } - } - } - - // show debug messages after extensionless-url special 404 handling - if (showDebug) - { - ShowDebugData(context, fullUrl, result, null); - } - } - } - catch (ThreadAbortException) - { - //do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest - //level try/catch block, so we handle it here. - Thread.ResetAbort(); - } - catch (Exception ex) - { - if (showDebug) - { - Services.Exceptions.Exceptions.LogException(ex); - } - if (response != null) - { - if (showDebug) - { - ShowDebugData(context, requestUri.AbsoluteUri, result, ex); - } - if (result != null) - { - result.Ex = ex; - result.Reason = RedirectReason.Exception; - } - Handle404OrException(settings, context, ex, result, false, showDebug); - } - else - { - if (result != null && result.DebugMessages != null) - { - result.DebugMessages.Add("Exception: " + ex.Message); - result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); - } - throw; - } - } - finally - { - //809 : add in new code copied from urlRewrite class in standard Url Rewrite module - if (context != null && context.Items["FirstRequest"] != null) - { - context.Items.Remove("FirstRequest"); - //process any messages in the eventQueue for the Application_Start_FIrstRequest event - EventQueueController.ProcessMessages("Application_Start_FirstRequest"); - } - } - } - - private static void ShowDebugData(HttpContext context, string requestUri, UrlAction result, Exception ex) - { - if (context != null) - { - HttpResponse response = context.Response; - - //handle null responses wherever they might be found - this routine must be tolerant to all kinds of invalid inputs - if (requestUri == null) - { - requestUri = "null Uri"; - } - string finalUrl = "null final Url"; - string rewritePath = "null rewrite path"; - string action = "null action"; - if (result != null) - { - finalUrl = result.FinalUrl; - action = result.Action.ToString(); - rewritePath = result.RewritePath; - } - //format up the error message to show - const string debugMsg = "{0}, {1}, {2}, {3}, {4}, {5}, {6}"; - string productVer = DotNetNukeContext.Current.Application.Version.ToString(); - string portalSettings = ""; - string browser = "Unknown"; - //949 : don't rely on 'result' being non-null - if (result != null) - { - browser = result.BrowserType.ToString(); - } - if (context.Items.Contains("PortalSettings")) - { - var ps = (PortalSettings) context.Items["PortalSettings"]; - if (ps != null) - { - portalSettings = ps.PortalId.ToString(); - if (ps.PortalAlias != null) - { - portalSettings += ":" + ps.PortalAlias.HTTPAlias; - } - } - } - response.AppendHeader("X-" + _productName + "-Debug", - string.Format(debugMsg, requestUri, finalUrl, rewritePath, action, productVer, - portalSettings, browser)); - int msgNum = 1; - if (result != null) - { - foreach (string msg in result.DebugMessages) - { - response.AppendHeader("X-" + _productName + "-Debug-" + msgNum.ToString("00"), msg); - msgNum++; - } - } - if (ex != null) - { - response.AppendHeader("X-" + _productName + "-Ex", ex.Message); - } - } - } - - private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug) - { - //handle Auto-Add Alias - if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias()) - { - //Need to determine if this is a real 404 or a possible new alias. - var portalId = Host.Host.HostPortalID; - if (portalId > Null.NullInteger) - { - if (string.IsNullOrEmpty(result.DomainName)) - { - result.DomainName = Globals.GetDomainName(context.Request); //parse the domain name out of the request - } - - //Get all the existing aliases - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - - bool autoaddAlias; - bool isPrimary = false; - if (!aliases.Any()) - { - autoaddAlias = true; - isPrimary = true; - } - else - { - autoaddAlias = true; - foreach (var alias in aliases) - { - if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0 - && result.DomainName.Length >= alias.HTTPAlias.Length) - { - autoaddAlias = false; - break; - } - } - } - - if (autoaddAlias) - { - var portalAliasInfo = new PortalAliasInfo - { - PortalID = portalId, - HTTPAlias = result.DomainName, - IsPrimary = isPrimary - }; - PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); - - context.Response.Redirect(context.Request.Url.ToString(), true); - } - } - } - - - if (context != null) - { - HttpRequest request = context.Request; - HttpResponse response = context.Response; - HttpServerUtility server = context.Server; - - const string errorPageHtmlHeader = @"{0}"; - const string errorPageHtmlFooter = @""; - var errorPageHtml = new StringWriter(); - CustomErrorsSection ceSection = null; - //876 : security catch for custom error reading - try - { - ceSection = (CustomErrorsSection) WebConfigurationManager.GetSection("system.web/customErrors"); - } -// ReSharper disable EmptyGeneralCatchClause - catch (Exception) -// ReSharper restore EmptyGeneralCatchClause - { - //on some medium trust environments, this will throw an exception for trying to read the custom Errors - //do nothing - } - - /* 454 new 404/500 error handling routine */ - bool useDNNTab = false; - int errTabId = -1; - string errUrl = null; - string status = ""; - bool isPostback = false; - if (settings != null) - { - if (request.RequestType == "POST") - { - isPostback = true; - } - if (result != null && ex != null) - { - result.DebugMessages.Add("Exception: " + ex.Message); - result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); - if (ex.InnerException != null) - { - result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message); - result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace); - } - else - { - result.DebugMessages.Add("Inner Ex : null"); - } - } - string errRH; - string errRV; - int statusCode; - if (result != null && result.Action != ActionType.Output404) - { - //output everything but 404 (usually 500) - if (settings.TabId500 > -1) //tabid specified for 500 error page, use that - { - useDNNTab = true; - errTabId = settings.TabId500; - } - errUrl = settings.Url500; - errRH = "X-UrlRewriter-500"; - errRV = "500 Rewritten to {0} : {1}"; - statusCode = 500; - status = "500 Internal Server Error"; - } - else //output 404 error - { - if (settings.TabId404 > -1) //if the tabid is specified for a 404 page, then use that - { - useDNNTab = true; - errTabId = settings.TabId404; - } - if (!String.IsNullOrEmpty(settings.Regex404)) - //with 404 errors, there's an option to catch certain urls and use an external url for extra processing. - { - try - { - //944 : check the original Url in case the requested Url has been rewritten before discovering it's a 404 error - string requestedUrl = request.Url.ToString(); - if (result != null && !string.IsNullOrEmpty(result.OriginalPath)) - { - requestedUrl = result.OriginalPath; - } - if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) - { - useDNNTab = false; - //if we have a match in the 404 regex value, then don't use the tabid - } - } - catch (Exception regexEx) - { - //.some type of exception : output in response header, and go back to using the tabid - response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message); - } - } - errUrl = settings.Url404; - errRH = "X-UrlRewriter-404"; - errRV = "404 Rewritten to {0} : {1} : Reason {2}"; - status = "404 Not Found"; - statusCode = 404; - } - - // check for 404 logging - if ((result == null || result.Action == ActionType.Output404)) - { - //Log 404 errors to Event Log - UrlRewriterUtils.Log404(request, settings, result); - } - //912 : use unhandled 404 switch - string reason404 = null; - bool unhandled404 = true; - if (useDNNTab && errTabId > -1) - { - unhandled404 = false; //we're handling it here - TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true); - if (errTab != null) - { - bool redirect = false; - //ok, valid tabid. what we're going to do is to load up this tab via a rewrite of the url, and then change the output status - string reason = "Not Found"; - if (result != null) - { - reason = result.Reason.ToString(); - } - response.AppendHeader(errRH, string.Format(errRV, "DNN Tab", - errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", - reason)); - //show debug messages even if in debug mode - if (context != null && response != null && result != null && showDebug) - { - ShowDebugData(context, result.OriginalPath, result, null); - } - if (!isPostback) - { - response.ClearContent(); - response.StatusCode = statusCode; - response.Status = status; - } - else - { - redirect = true; - //redirect postbacks as you can't postback successfully to a server.transfer - } - errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, ""); - //have to update the portal settings with the new tabid - PortalSettings ps = null; - if (context != null && context.Items != null) - { - if (context.Items.Contains("PortalSettings")) - { - ps = (PortalSettings) context.Items["PortalSettings"]; - context.Items.Remove("PortalSettings"); //nix it from the context - } - } - if (ps != null && ps.PortalAlias != null) - { - ps = new PortalSettings(errTabId, ps.PortalAlias); - } - else - { - if (result.HttpAlias != null && result.PortalId > -1) - { - PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId); - ps = new PortalSettings(errTabId, pa); - } - else - { - //912 : handle 404 when no valid portal can be identified - //results when iis is configured to handle portal alias, but - //DNN isn't. This always returns 404 because a multi-portal site - //can't just show the 404 page of the host site. - ArrayList portals = PortalController.Instance.GetPortals(); - if (portals != null && portals.Count == 1) - { - //single portal install, load up portal settings for this portal - var singlePortal = (PortalInfo) portals[0]; - //list of aliases from database - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(singlePortal.PortalID).ToList(); - //list of aliases from Advanced Url settings - List chosen = aliases.GetAliasesForPortalId(singlePortal.PortalID); - PortalAliasInfo useFor404 = null; - //go through all aliases and either get the first valid one, or the first - //as chosen in the advanced url management settings - foreach (var pa in aliases) - { - if (useFor404 == null) - { - useFor404 = pa; //first one by default - } - - //matching? - if (chosen != null && chosen.Count > 0) - { - if (chosen.Contains(pa.HTTPAlias)) - { - useFor404 = pa; - } - } - else - { - break; //no further checking - } - } - //now configure that as the portal settings - if (useFor404 != null) - { - //create portal settings context for identified portal alias in single portal install - ps = new PortalSettings(errTabId, useFor404); - } - } - else - { - reason404 = "Requested domain name is not configured as valid website"; - unhandled404 = true; - } - } - } - if (ps != null) - { - //re-add the context items portal settings back in - context.Items.Add("PortalSettings", ps); - } - if (redirect) - { - errUrl = TestableGlobals.Instance.NavigateURL(); - response.Redirect(errUrl, true); //redirect and end response. - //It will mean the user will have to postback again, but it will work the second time - } - else - { - if (transfer) - { - //execute a server transfer to the default.aspx?tabid=xx url - //767 : object not set error on extensionless 404 errors - if (context.User == null) - { - context.User = GetCurrentPrincipal(context); - } - response.TrySkipIisCustomErrors = true; - //881 : spoof the basePage object so that the client dependency framework - //is satisfied it's working with a page-based handler - IHttpHandler spoofPage = new CDefault(); - context.Handler = spoofPage; - server.Transfer("~/" + errUrl, true); - } - else - { - context.RewritePath("~/Default.aspx", false); - response.TrySkipIisCustomErrors = true; - response.Status = "404 Not Found"; - response.StatusCode = 404; - } - } - } - } - //912 : change to new if statement to handle cases where the TabId404 couldn't be handled correctly - if (unhandled404) - { - //proces the error on the external Url by rewriting to the external url - if (!String.IsNullOrEmpty(errUrl)) - { - response.ClearContent(); - response.TrySkipIisCustomErrors = true; - string reason = "Not Found"; - if (result != null) - { - reason = result.Reason.ToString(); - } - response.AppendHeader(errRH, string.Format(errRV, "Url", errUrl, reason)); - if (reason404 != null) - { - response.AppendHeader("X-Url-Master-404-Data", reason404); - } - response.StatusCode = statusCode; - response.Status = status; - server.Transfer("~/" + errUrl, true); - } - else - { - errorPageHtml.Write(status + "
    The requested Url does not return any valid content."); - if (reason404 != null) - { - errorPageHtml.Write(status + "
    " + reason404); - } - errorPageHtml.Write("
    Administrators
    "); - errorPageHtml.Write("
    Change this message by configuring a specific 404 Error Page or Url for this website.
    "); - - //output a reason for the 404 - string reason = ""; - if (result != null) - { - reason = result.Reason.ToString(); - } - if (!string.IsNullOrEmpty(errRH) && !string.IsNullOrEmpty(reason)) - { - response.AppendHeader(errRH, reason); - } - response.StatusCode = statusCode; - response.Status = status; - } - } - } - else - { - //fallback output if not valid settings - if (result != null && result.Action == ActionType.Output404) - { - //don't restate the requested Url to prevent cross site scripting - errorPageHtml.Write("404 Not Found
    The requested Url does not return any valid content."); - response.StatusCode = 404; - response.Status = "404 Not Found"; - } - else - { - //error, especially if invalid result object - - errorPageHtml.Write("500 Server Error
    An error occured during processing : if possible, check the event log of the server
    "); - response.StatusCode = 500; - response.Status = "500 Internal Server Error"; - if (result != null) - { - result.Action = ActionType.Output500; - } - } - } - - if (ex != null) - { - if (context != null) - { - if (context.Items.Contains("UrlRewrite:Exception") == false) - { - context.Items.Add("UrlRewrite:Exception", ex.Message); - context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace); - } - } - - if (ceSection != null && ceSection.Mode == CustomErrorsMode.Off) - { - errorPageHtml.Write(errorPageHtmlHeader); - errorPageHtml.Write("
    Exception:
    " + ex.Message + "
    "); - errorPageHtml.Write("
    Stack Trace:
    " + ex.StackTrace + "
    "); - errorPageHtml.Write("
    Administrators
    "); - errorPageHtml.Write("
    You can see this exception because the customErrors attribute in the web.config is set to 'off'. Change this value to 'on' or 'RemoteOnly' to show Error Handling
    "); - try - { - if (errUrl != null && errUrl.StartsWith("~")) - { - errUrl = VirtualPathUtility.ToAbsolute(errUrl); - } - } - finally - { - if (errUrl != null) - { - errorPageHtml.Write("
    The error handling would have shown this page : " + errUrl + "
    "); - } - else - { - errorPageHtml.Write("
    The error handling could not determine the correct page to show.
    "); - } - } - } - } - - string errorPageHtmlBody = errorPageHtml.ToString(); - if (errorPageHtmlBody.Length > 0) - { - response.Write(errorPageHtmlHeader); - response.Write(errorPageHtmlBody); - response.Write(errorPageHtmlFooter); - } - if (ex != null) - { - UrlRewriterUtils.LogExceptionInRequest(ex, status, result); - } - } - } - - private static IPrincipal GetCurrentPrincipal(HttpContext context) - { - // Extract the forms authentication cookie - var authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; - var currentPrincipal = new GenericPrincipal(new GenericIdentity(string.Empty), new string[0]); - - try - { - if (authCookie != null) - { - var authTicket = FormsAuthentication.Decrypt(authCookie.Value); - if (authTicket != null && !authTicket.Expired) - { - var roles = authTicket.UserData.Split('|'); - var id = new FormsIdentity(authTicket); - currentPrincipal = new GenericPrincipal(id, roles); - } - } - } - catch (Exception) - { - //do nothing here. - } - - return currentPrincipal; - } - - private static bool CheckForDebug(HttpRequest request, NameValueCollection queryStringCol, bool debugEnabled) - { - string debugValue = ""; - bool retVal = false; - - if (debugEnabled) - { - const string debugToken = "_aumdebug"; - if (queryStringCol != null && queryStringCol[debugToken] != null) - { - debugValue = queryStringCol[debugToken]; - } - else - { - if (request != null) - { - debugValue = (request.Params.Get("HTTP_" + debugToken.ToUpper())); - } - if (debugValue == null) - { - debugValue = "false"; - } - } - } - - switch (debugValue.ToLowerInvariant()) - { - case "true": - retVal = true; - break; - } - return retVal; - } - - private static bool CheckForTabExternalForwardOrRedirect(HttpContext context, - ref UrlAction result, - HttpResponse response, - FriendlyUrlSettings settings, - Guid parentTraceId) - { - bool finished = false; - HttpRequest request = null; - if (context != null) - { - request = context.Request; - } - - try - { - //check for external forwarding or a permanent redirect request - //592 : check for permanent redirect (823 : moved location from 'checkForRedirects') - if (result.TabId > -1 && result.PortalId > -1 && - (settings.ForwardExternalUrlsType != DNNPageForwardType.NoForward || - result.Reason == RedirectReason.Tab_Permanent_Redirect)) - { - bool allowRedirect = !(result.RewritePath != null && result.RewritePath.ToLowerInvariant().Contains("&ctl=tab")); - //594 : do not redirect settings pages for external urls - if (allowRedirect) - { - TabInfo tab; - allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings); - if (allowRedirect) - { - //772 : not redirecting file type Urls when requested. - bool permanentRedirect = false; - string redirectUrl = null; - string cleanPath = null; - bool doRedirect = false; - switch (tab.TabType) - { - case TabType.File: - //have to fudge in a portal settings object for this to work - shortcoming of LinkClick URl generation - var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); - if (context != null) - { - context.Items.Add("PortalSettings", portalSettings); - result.Reason = RedirectReason.File_Url; - string fileUrl = Globals.LinkClick(tab.Url, tab.TabID, -1); - context.Items.Remove("PortalSettings"); - //take back out again, because it will be done further downstream - //do a check to make sure we're not repeating the Url again, because the tabid is set but we don't want to touch - //a linkclick url - if (!result.OriginalPathNoAlias.EndsWith(HttpUtility.UrlDecode(fileUrl), true, CultureInfo.InvariantCulture)) - { - redirectUrl = fileUrl; - } - } - if (redirectUrl != null) - { - doRedirect = true; - } - break; - case TabType.Url: - result.Reason = RedirectReason.Tab_External_Url; - redirectUrl = tab.Url; - if (redirectUrl != null) - { - doRedirect = true; - if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) - { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Tab_External_Url; - } - else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) - { - result.Action = ActionType.Redirect302; - result.Reason = RedirectReason.Tab_External_Url; - } - } - break; - case TabType.Tab: - // if a tabType.tab is specified, it's either an external url or a permanent redirect - - //get the redirect path of the specific tab, as long as we have a valid request to work from - if (request != null) - { - //get the rewrite or requested path in a clean format, suitable for input to the friendly url provider - cleanPath = RewriteController.GetRewriteOrRequestedPath(result, request.Url); - //727 prevent redirectLoop with do301 in querystring - if (result.Action == ActionType.Redirect301 || - result.Action == ActionType.Redirect302) - { - cleanPath = RedirectTokens.RemoveAnyRedirectTokens(cleanPath, - request.QueryString); - } - //get the redirect Url from the friendly url provider using the tab, path and settings - redirectUrl = RedirectController.GetTabRedirectUrl(tab, settings, cleanPath, result, - out permanentRedirect, - parentTraceId); - } - //check to make sure there isn't a blank redirect Url - if (redirectUrl == null) - { - //problem : no redirect Url to redirect to - //solution : cancel the redirect - string message = "Permanent Redirect chosen for Tab " + - tab.TabPath.Replace("//", "/") + - " but forwarding Url was not valid"; - RedirectController.CancelRedirect(ref result, context, settings, message); - } - else - { - //if there was a redirect Url, set the redirect action and set the type of redirect going to use - doRedirect = true; - if (permanentRedirect) - { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Tab_Permanent_Redirect; - //should be already set, anyway - result.RewritePath = cleanPath; - } - else - { - //not a permanent redirect, check if the page forwarding is set - if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) - { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Tab_External_Url; - } - else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) - { - result.Action = ActionType.Redirect302; - result.Reason = RedirectReason.Tab_External_Url; - } - } - } - break; - default: - //only concern here is if permanent redirect is requested, but there is no external url specified - if (result.Reason == RedirectReason.Tab_Permanent_Redirect) - { - bool permRedirect = tab.PermanentRedirect; - if (permRedirect) - { - //problem : permanent redirect marked, but no forwarding url supplied - //solution : cancel redirect - string message = "Permanent Redirect chosen for Tab " + - tab.TabPath.Replace("//", "/") + - " but no forwarding Url Supplied"; - RedirectController.CancelRedirect(ref result, context, settings, message); - } - } - break; - } - - //do the redirect we have specified - if (doRedirect && - (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302)) - { - result.FinalUrl = redirectUrl; - if (result.Action == ActionType.Redirect301) - { - if (response != null) - { - //perform a 301 redirect to the external url of the tab - response.AppendHeader("X-Redirect-Reason", - result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - } - } - else - { - if (result.Action == ActionType.Redirect302) - { - if (response != null) - { - //perform a 301 redirect to the external url of the tab - response.AppendHeader("X-Redirect-Reason", - result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl); - } - } - } - finished = true; - } - } - } - } - - } - catch (ThreadAbortException) - { - //do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest - //level try/catch block, so we handle it here. - } - return finished; - } - - private bool CheckForSecureRedirect(PortalSettings portalSettings, - Uri requestUri, - UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings) - { - bool redirectSecure = false; - string url = requestUri.ToString(); - //889 : don't run secure redirect code for physical resources or requests that aren't a rewritten Url - if (result.IsPhysicalResource == false && result.TabId >= 0) - // no secure redirection for physical resources, only tab-specific requests can be redirected for ssl connections - { - if (portalSettings.ActiveTab != null) - { - result.DebugMessages.Add("ActiveTab: " + portalSettings.ActiveTab.TabID.ToString() + "/" + - portalSettings.ActiveTab.TabName + " IsSecure: " + - portalSettings.ActiveTab.IsSecure.ToString()); - - //check ssl enabled - if (portalSettings.SSLEnabled) - { - //717 : check page is secure, connection is not secure - //952 : support SSl Offloading in DNN 6.2+ - if (portalSettings.ActiveTab.IsSecure && !result.IsSecureConnection && !result.IsSSLOffloaded) - { - redirectSecure = true; - string stdUrl = portalSettings.STDURL; - string sslUrl = portalSettings.SSLURL; - if (string.IsNullOrEmpty(result.HttpAlias) == false) - { - stdUrl = result.HttpAlias; - } - url = url.Replace("http://", "https://"); - url = ReplaceDomainName(url, stdUrl, sslUrl); - } - } - //check ssl enforced - if (portalSettings.SSLEnforced) - { - // Prevent browser's mixed-content error in case we open a secure PopUp or a secure iframe - // from an unsecure page - if (!portalSettings.ActiveTab.IsSecure && - result.IsSecureConnection && - !UrlUtils.IsPopUp(url)) - { - //has connection already been forced to secure? - if (queryStringCol["ssl"] == null) - { - //no? well this page shouldn't be secure - string stdUrl = portalSettings.STDURL; - string sslUrl = portalSettings.SSLURL; - url = url.Replace("https://", "http://"); - url = ReplaceDomainName(url, sslUrl, stdUrl); - redirectSecure = true; - } - } - } - } - - - if (redirectSecure) - { - //now check to see if excluded. Why now? because less requests are made to redirect secure, - //so we don't have to check the exclusion as often. - bool exclude = false; - string doNotRedirectSecureRegex = settings.DoNotRedirectSecureRegex; - if (!string.IsNullOrEmpty(doNotRedirectSecureRegex)) - { - //match the raw url - exclude = (Regex.IsMatch(result.RawUrl, doNotRedirectSecureRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)); - } - if (!exclude) - { - result.Action = ActionType.Redirect302Now; - result.Reason = RedirectReason.Secure_Page_Requested; - //760 : get the culture specific home page tabid for a redirect comparison - int homePageTabId = portalSettings.HomeTabId; - homePageTabId = TabPathHelper.GetHomePageTabIdForCulture(portalSettings.DefaultLanguage, - portalSettings.PortalId, - result.CultureCode, homePageTabId); - if (result.TabId == homePageTabId) - { - //replace the /default.aspx in the Url if it was found - url = DefaultPageRegex.Replace(url, "/"); - } - result.FinalUrl = url; - } - else - { - //702 : change return value if exclusion has occured - redirectSecure = false; - } - } - } - return redirectSecure; - } - - private string ReplaceDomainName(string url, string replaceDomain, string withDomain) - { - if (replaceDomain != "" && withDomain != "") - { - //951 : change find/replace routine to regex for more accurate replacement - //(previous method gives false positives if the SSL Url is contained within the STD url) - string find = @"(?<=https?://)" + Regex.Escape(withDomain); - if (Regex.IsMatch(url, find, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) == false) - { - string replaceFind = @"(?<=https?://)" + Regex.Escape(replaceDomain); - url = Regex.Replace(url, replaceFind, withDomain, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - } - return url; - } - - protected bool IsPortalAliasIncorrect(HttpContext context, - HttpRequest request, - Uri requestUri, - UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - Guid parentTraceId, - out string httpAlias) - { - //now check to make sure it's the primary portal alias for this portal/language/browser - bool incorrectAlias = false; - httpAlias = null; - //if (result.RedirectAllowed && result.PortalId > -1) - if (result.PortalId > -1) //portal has been identified - { - var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - - if (queryStringCol != null && queryStringCol["forceAlias"] != "true") - { - if (portalAliases.Count > 0) - { - string checkAlias = result.HttpAlias; - bool continueLoop = true; - bool triedWWW = false; - while (httpAlias == null && continueLoop) - { - if (portalAliases.ContainsAlias(result.PortalId, checkAlias)) - { - if (portalAliases.Count > 0) - { - //var cpa = portalAliases.GetAliasByPortalIdAndSettings(result); - string url = requestUri.ToString(); - RewriteController.CheckLanguageMatch(ref url, result); - var cpa = portalAliases - .Where(a => a.IsPrimary || result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) - .GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, result.BrowserType); - - if (cpa != null) - { - httpAlias = cpa.HTTPAlias; - continueLoop = false; - } - if (String.IsNullOrEmpty(result.CultureCode) && cpa == null) - { - //if there is a specific culture for this portal alias, then check that - string culture = portalAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); - //if this matches the alias of the request, then we know we have the correct alias because it is a specific culture - if (!string.IsNullOrEmpty(culture)) - { - continueLoop = false; - } - } - } - } - //check whether to still go on or not - if (continueLoop) - { - //this alias doesn't exist in the list - //check if it has a www on it - if not, try adding, if it does, try removing - if (!triedWWW) - { - triedWWW = true; //now tried adding/removing www - if (checkAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) - { - checkAlias = checkAlias.Substring(4); - } - else - { - checkAlias = "www." + checkAlias; - } - } - else - { - //last thing to try, get the default language and see if there is a portal alias for that - //thus, any aliases not identified as belonging to a language are redirected back to the - //alias named for the default language - continueLoop = false; - //735 : switch to custom method for getting portal - PortalInfo pi = CacheController.GetPortal(result.PortalId, false); - if (pi != null) - { - string cultureCode = pi.DefaultLanguage; - if (!string.IsNullOrEmpty(cultureCode)) - { - var primaryPortalAlias = portalAliases.GetAliasByPortalIdAndSettings(result.PortalId, result,cultureCode,settings); - if (primaryPortalAlias != null) - { - httpAlias = primaryPortalAlias.HTTPAlias; - } - } - } - } - } - } - } - - - //check to see if it is a custom tab alais - in that case, it is allowed to be requested for the tab - if (CheckIfAliasIsCustomTabAlias(ref result, httpAlias, settings)) - { - //change the primary alias to the custom tab alias that has been requested. - result.PrimaryAlias = result.PortalAlias; - } - else - if (httpAlias != null && String.Compare(httpAlias, result.HttpAlias, StringComparison.OrdinalIgnoreCase) != 0) - { - incorrectAlias = true; - } - } - } - return incorrectAlias; - } - /// - /// Redirects an alias if that is allowed by the settings - /// - /// - /// - /// - /// - - private static bool RedirectPortalAlias(string httpAlias, ref UrlAction result, FriendlyUrlSettings settings) - { - bool redirected = false; - //redirect to primary alias - if (result.PortalAliasMapping == PortalSettings.PortalAliasMapping.Redirect && result.RedirectAllowed) - { - if (result.Reason == RedirectReason.Wrong_Portal_Alias_For_Browser_Type || result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture || - result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) - { - redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, result.Reason, settings.InternalAliasList, settings); - } - else - { - redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, settings.InternalAliasList, settings); - } - } - - return redirected; - } - - private static bool ConfigurePortalAliasRedirect(ref UrlAction result, - string wrongAlias, - string rightAlias, - bool ignoreCustomAliasTabs, - List internalAliases, - FriendlyUrlSettings settings) - { - return ConfigurePortalAliasRedirect(ref result, - wrongAlias, - rightAlias, - ignoreCustomAliasTabs, - RedirectReason.Wrong_Portal_Alias, - internalAliases, - settings); - } - /// - /// Checks to see whether the specified alias is a customTabAlias - /// - /// - /// - /// - /// - private static bool CheckIfAliasIsCustomTabAlias(ref UrlAction result, string httpAlias, FriendlyUrlSettings settings) - { - List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); - bool isACustomTabAlias = false; - if (customAliasesForTabs != null && customAliasesForTabs.Count > 0) - { - //remove any customAliases that are also primary aliases. - foreach (var cpa in PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId)) - { - if (cpa.IsPrimary == true && customAliasesForTabs.Contains(cpa.HTTPAlias)) - { - customAliasesForTabs.Remove(cpa.HTTPAlias); - } - } - isACustomTabAlias = customAliasesForTabs.Contains(httpAlias.ToLowerInvariant()); - } - return isACustomTabAlias; - } - /// - /// Configures the result object to set the correct Alias redirect - /// parameters and destination URL - /// - /// - /// - /// - /// - /// - /// - /// - /// - private static bool ConfigurePortalAliasRedirect(ref UrlAction result, - string wrongAlias, - string rightAlias, - bool ignoreCustomAliasTabs, - RedirectReason redirectReason, - List internalAliases, - FriendlyUrlSettings settings) - { - //wrong alias for the portal - //check to see if the wrong portal alias could be a custom alias for a tab - bool doRedirect; - if (ignoreCustomAliasTabs == false) //check out custom alias tabs collection - { - //if an alias is a custom tab alias for a specific tab, then don't redirect - if (CheckIfAliasIsCustomTabAlias(ref result, wrongAlias, settings)) - doRedirect = false; - else - { - doRedirect = true; - } - } - else - { - doRedirect = true; //do redirect, ignore custom alias entries for tabs - } - //check to see if it is an internal alias. These are used to block redirects - //to allow for reverse proxy requests, which must change the rewritten alias - //while leaving the requested alias - bool internalAliasFound = false; - if (doRedirect && internalAliases != null && internalAliases.Count > 0) - { - if (internalAliases.Any(ia => String.Compare(ia.HttpAlias, wrongAlias, StringComparison.OrdinalIgnoreCase) == 0)) - { - internalAliasFound = true; - doRedirect = false; - } - } - //if still need to do redirect, then set the settings that will cause the redirect (redirect not done here) - if (doRedirect) - { - result.Action = ActionType.Redirect301; - result.Reason = redirectReason; - var destUrl = result.OriginalPath; - if (result.OriginalPath.Contains(wrongAlias)) - { - destUrl = result.OriginalPath.Replace(wrongAlias, rightAlias); - } - else if (result.OriginalPath.ToLowerInvariant().Contains(wrongAlias)) - { - - destUrl = result.OriginalPath.ToLowerInvariant().Replace(wrongAlias, rightAlias); - } - - if (redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture || - redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) - { - destUrl = destUrl.Replace("/language/" + result.CultureCode, ""); - } - destUrl = CheckForSiteRootRedirect(rightAlias, destUrl); - result.FinalUrl = destUrl; - } - else - { - //838 : don't overwrite the reason if already have checkfor301 - // and don't do a check on the basis that an internal alias was found - if (result.Action != ActionType.CheckFor301 && internalAliasFound == false) - { - //set status to 'check for redirect' - result.Action = ActionType.CheckFor301; - result.Reason = RedirectReason.Custom_Tab_Alias; - } - } - return doRedirect; - } - - private void IdentifyPortalAlias(HttpContext context, - HttpRequest request, - Uri requestUri, UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - Guid parentTraceId) - { - //get the domain name of the request, if it isn't already supplied - if (request != null && string.IsNullOrEmpty(result.DomainName)) - { - result.DomainName = Globals.GetDomainName(request); //parse the domain name out of the request - } - - // get tabId from querystring ( this is mandatory for maintaining portal context for child portals ) - if (queryStringCol["tabid"] != null) - { - string raw = queryStringCol["tabid"]; - int tabId; - if (Int32.TryParse(raw, out tabId)) - { - result.TabId = tabId; - } - else - { - //couldn't parse tab id - //split in two? - string[] tabids = raw.Split(','); - if (tabids.GetUpperBound(0) > 0) - { - //hmm more than one tabid - if (Int32.TryParse(tabids[0], out tabId)) - { - result.TabId = tabId; - //but we want to warn against this! - var ex = - new Exception( - "Illegal request exception : Two TabId parameters provided in a single request: " + - requestUri); - UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); - - result.Ex = ex; - } - else - { - //yeah, nothing, divert to 404 - result.Action = ActionType.Output404; - var ex = - new Exception( - "Illegal request exception : TabId parameters in query string, but invalid TabId requested : " + - requestUri); - UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); - result.Ex = ex; - } - } - } - } - // get PortalId from querystring ( this is used for host menu options as well as child portal navigation ) - if (queryStringCol["portalid"] != null) - { - string raw = queryStringCol["portalid"]; - int portalId; - if (Int32.TryParse(raw, out portalId)) - { - //848 : if portal already found is different to portal id in querystring, then load up different alias - //this is so the portal settings will be loaded correctly. - if (result.PortalId != portalId) - { - //portal id different to what we expected - result.PortalId = portalId; - //check the loaded portal alias, because it might be wrong - if (result.PortalAlias != null && result.PortalAlias.PortalID != portalId) - { - //yes, the identified portal alias is wrong. Find the correct alias for this portal - PortalAliasInfo pa = TabIndexController.GetPortalAliasByPortal(portalId, result.DomainName); - if (pa != null) - { - //note: sets portal id and portal alias - result.PortalAlias = pa; - } - } - } - } - } - else - { - //check for a portal alias if there's no portal Id in the query string - //check for absence of captcha value, because the captcha string re-uses the alias querystring value - if (queryStringCol["alias"] != null && queryStringCol["captcha"] == null) - { - string alias = queryStringCol["alias"]; - PortalAliasInfo portalAlias = PortalAliasController.Instance.GetPortalAlias(alias); - if (portalAlias != null) - { - //ok the portal alias was found by the alias name - // check if the alias contains the domain name - if (alias.Contains(result.DomainName) == false) - { - // replaced to the domain defined in the alias - if (request != null) - { - string redirectDomain = Globals.GetPortalDomainName(alias, request, true); - //retVal.Url = redirectDomain; - result.FinalUrl = redirectDomain; - result.Action = ActionType.Redirect302Now; - result.Reason = RedirectReason.Alias_In_Url; - } - } - else - { - // the alias is the same as the current domain - result.HttpAlias = portalAlias.HTTPAlias; - result.PortalAlias = portalAlias; - result.PortalId = portalAlias.PortalID; - //don't use this crap though - we don't want ?alias=portalAlias in our Url - if (result.RedirectAllowed) - { - string redirect = requestUri.Scheme + Uri.SchemeDelimiter + result.PortalAlias.HTTPAlias + - "/"; - result.Action = ActionType.Redirect301; - result.FinalUrl = redirect; - result.Reason = RedirectReason.Unfriendly_Url_Child_Portal; - } - } - } - } - } - //first try and identify the portal using the tabId, but only if we identified this tab by looking up the tabid - //from the original url - //668 : error in child portal redirects to child portal home page because of mismatch in tab/domain name - if (result.TabId != -1 && result.FriendlyRewrite == false) - { - // get the alias from the tabid, but only if it is for a tab in that domain - // 2.0 : change to compare retrieved alias to the already-set httpAlias - string httpAliasFromTab = PortalAliasController.GetPortalAliasByTab(result.TabId, result.DomainName); - if (httpAliasFromTab != null) - { - //882 : account for situation when portalAlias is null. - if (result.PortalAlias != null && String.Compare(result.PortalAlias.HTTPAlias, httpAliasFromTab, StringComparison.OrdinalIgnoreCase) != 0 - || result.PortalAlias == null) - { - //691 : change logic to force change in portal alias context rather than force back. - //This is because the tabid in the query string should take precedence over the portal alias - //to handle parent.com/default.aspx?tabid=xx where xx lives in parent.com/child/ - var tab = TabController.Instance.GetTab(result.TabId, Null.NullInteger, false); - //when result alias is null or result alias is different from tab-identified portalAlias - if (tab != null && (result.PortalAlias == null || tab.PortalID != result.PortalAlias.PortalID)) - { - //the tabid is different to the identified portalid from the original alias identified - //so get a new alias - PortalAliasInfo tabPortalAlias = PortalAliasController.Instance.GetPortalAlias(httpAliasFromTab, tab.PortalID); - if (tabPortalAlias != null) - { - result.PortalId = tabPortalAlias.PortalID; - result.PortalAlias = tabPortalAlias; - result.Action = ActionType.CheckFor301; - result.Reason = RedirectReason.Wrong_Portal; - } - } - } - } - } - //if no alias, try and set by using the identified http alias or domain name - if (result.PortalAlias == null) - { - if (!string.IsNullOrEmpty(result.HttpAlias)) - { - result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias); - } - else - { - result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); - if (result.PortalAlias == null && result.DomainName.EndsWith("/")) - { - result.DomainName = result.DomainName.TrimEnd('/'); - result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); - } - } - } - - if (result.PortalId == -1) - { - if (!requestUri.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - // allows requests for aspx pages in custom folder locations to be processed - return; - } - //the domain name was not found so try using the host portal's first alias - if (Host.Host.HostPortalID != -1) - { - result.PortalId = Host.Host.HostPortalID; - // use the host portal, but replaced to the host portal home page - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (aliases.Count > 0) - { - string alias = null; - - //get the alias as the chosen portal alias for the host portal based on the result culture code - var cpa = aliases.GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, settings); - if (cpa != null) - { - alias = cpa.HTTPAlias; - } - - if (alias != null) - { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Host_Portal_Used; - string destUrl = MakeUrlWithAlias(requestUri, alias); - destUrl = CheckForSiteRootRedirect(alias, destUrl); - result.FinalUrl = destUrl; - } - else - { - //Get the first Alias for the host portal - result.PortalAlias = aliases[result.PortalId]; - string url = MakeUrlWithAlias(requestUri, result.PortalAlias); - if (result.TabId != -1) - { - url += requestUri.Query; - } - result.FinalUrl = url; - result.Reason = RedirectReason.Host_Portal_Used; - result.Action = ActionType.Redirect302Now; - } - } - } - } - - //double check to make sure we still have the correct alias now that all other information is known (ie tab, portal, culture) - //770 : redirect alias based on tab id when custom alias used - if (result.TabId == -1 && result.Action == ActionType.CheckFor301 && - result.Reason == RedirectReason.Custom_Tab_Alias) - { - //here because the portal alias matched, but no tab was found, and because there are custom tab aliases used for this portal - //need to redirect back to the chosen portal alias and keep the current path. - string wrongAlias = result.HttpAlias; //it's a valid alias, but only for certain tabs - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (primaryAliases != null && result.PortalId > -1) - { - //going to look for the correct alias based on the culture of the request - string requestCultureCode = result.CultureCode; - //if that didn't work use the default language of the portal - if (requestCultureCode == null) - { - //this might end up in a double redirect if the path of the Url is for a specific language as opposed - //to a path belonging to the default language domain - PortalInfo portal = PortalController.Instance.GetPortal(result.PortalId); - if (portal != null) - { - requestCultureCode = portal.DefaultLanguage; - } - } - //now that the culture code is known, look up the correct portal alias for this portalid/culture code - var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, requestCultureCode, settings); - if (cpa != null) - { - //if an alias was found that matches the request and the culture code, then run with that - string rightAlias = cpa.HTTPAlias; - //will cause a redirect to the primary portal alias - we know now that there was no custom alias tab - //found, so it's just a plain wrong alias - ConfigurePortalAliasRedirect(ref result, wrongAlias, rightAlias, true, - settings.InternalAliasList, settings); - } - } - } - else - { - //then check to make sure it's the chosen portal alias for this portal - //627 : don't do it if we're redirecting to the host portal - if (result.RedirectAllowed && result.Reason != RedirectReason.Host_Portal_Used) - { - string primaryAlias; - //checking again in case the rewriting operation changed the values for the valid portal alias - bool incorrectAlias = IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryAlias); - if (incorrectAlias) RedirectPortalAlias(primaryAlias, ref result, settings); - } - } - - //check to see if we have to avoid the core 302 redirect for the portal alias that is in the /defualt.aspx - //for child portals - //exception to that is when a custom alias is used but no rewrite has taken place - if (result.DoRewrite == false && (result.Action == ActionType.Continue - || - (result.Action == ActionType.CheckFor301 && - result.Reason == RedirectReason.Custom_Tab_Alias))) - { - string aliasQuerystring; - bool isChildAliasRootUrl = CheckForChildPortalRootUrl(requestUri.AbsoluteUri, result, out aliasQuerystring); - if (isChildAliasRootUrl) - { - RewriteAsChildAliasRoot(context, result, aliasQuerystring, settings); - } - } - } - - internal static void RewriteAsChildAliasRoot(HttpContext context, - UrlAction result, - string aliasQueryString, - FriendlyUrlSettings settings) - { - string culture = null; - //look for specific alias to rewrite language parameter - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (result.PortalId > -1 && result.HttpAlias != null) - { - culture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); - } - if (string.IsNullOrEmpty(culture)) - //732 : when no culture returned can be "" as well as null : no culture causes no rewrite, which results in redirect to parent alias - { - //set the default culture code here - //735 : switch to custom method for getting portal - PortalInfo pi = CacheController.GetPortal(result.PortalId, false); - if (pi != null) - { - culture = pi.DefaultLanguage; - } - } - if (!string.IsNullOrEmpty(culture)) //a culture was identified for the alias root - { - if (RewriteController.AddLanguageCodeToRewritePath(ref aliasQueryString, culture)) - { - result.CultureCode = culture; - } - result.DoRewrite = true; - result.RewritePath = "~/" + Globals.glbDefaultPage + aliasQueryString; - //the expected /default.aspx path (defaultPageUrl) matches the requested Url (/default.aspx) - if (context != null) - { - //only do if not testing - RewriterUtils.RewriteUrl(context, result.RewritePath); - } - } - } - - internal static bool CheckForChildPortalRootUrl(string requestUrl, UrlAction result, out string aliasQueryString) - { - bool isChildPortalRootUrl = false; - //what we are going to test for here is that if this is a child portal request, for the /default.aspx of the child portal - //then we are going to avoid the core 302 redirect to ?alias=portalALias by rewriting to the /default.aspx of the site root - //684 : don't convert querystring items to lower case - //do the check by constructing what a child alias url would look like and compare it with the requested urls - //912 : when requested without a valid portal alias, portalALias is null. Refuse and return false. - aliasQueryString = null; - if (result.PortalAlias != null && result.PortalAlias.HTTPAlias != null) - { - string defaultPageUrl = result.Scheme + result.PortalAlias.HTTPAlias + "/" + - Globals.glbDefaultPage.ToLowerInvariant(); //child alias Url with /default.aspx - //660 : look for a querystring on the site root for a child portal, and handle it if so - if (String.CompareOrdinal(requestUrl.ToLowerInvariant(), defaultPageUrl) == 0) - { - //exact match : that's the alias root - isChildPortalRootUrl = true; - aliasQueryString = ""; - } - if (!isChildPortalRootUrl && requestUrl.Contains("?")) - { - //is we didn't get an exact match but there is a querystring, then investigate - string[] requestUrlParts = requestUrl.Split('?'); - if (requestUrlParts.GetUpperBound(0) > 0) - { - string rootPart = requestUrlParts[0]; - string queryString = requestUrlParts[1]; - if (String.Compare(rootPart, defaultPageUrl, StringComparison.OrdinalIgnoreCase) == 0) - { - //rewrite, but put in the querystring on the rewrite path - isChildPortalRootUrl = true; - aliasQueryString = "?" + queryString; - //674: check for 301 if this value is a tabid/xx - otherwise the url will just evaluate as is - if (queryString.ToLowerInvariant().StartsWith("tabid=")) - { - result.Action = ActionType.CheckFor301; - } - } - } - } - } - return isChildPortalRootUrl; - } - - private static string MakeUrlWithAlias(Uri requestUri, string httpAlias) - { - return requestUri.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) - ? "https://" + httpAlias.Replace("*.", "") + "/" - : "http://" + httpAlias.Replace("*.", "") + "/"; - } - - private static string MakeUrlWithAlias(Uri requestUri, PortalAliasInfo alias) - { - return MakeUrlWithAlias(requestUri, alias.HTTPAlias); - } - - /// - /// Determines if this is a request from an install / upgrade url - /// - /// - /// - /// - /// - /// - /// - /// //875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1 - /// - private static bool IgnoreRequestForInstall(string physicalPath, string refererPath, string requestedDomain, string refererDomain) - { - if (physicalPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) - || physicalPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) - || physicalPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture) - || Globals.Status == Globals.UpgradeStatus.Install - || Globals.Status == Globals.UpgradeStatus.Upgrade) - { - return true; - } - - //954 : DNN 7.0 compatibility - //check for /default.aspx which is default Url launched from the Upgrade/Install wizard page - //961 : check domain as well as path for the referer - if (physicalPath.EndsWith(Globals.glbDefaultPage, true, CultureInfo.InvariantCulture) == false - && refererPath != null - && String.Compare(requestedDomain, refererDomain, StringComparison.OrdinalIgnoreCase) == 0 - && (refererPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) - || refererPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) - || refererPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture) - )) - { - return true; - } - return false; - } - - private static bool IgnoreRequestForWebServer(string requestedPath) - { - //Should standardize comparison methods - if (requestedPath.IndexOf("synchronizecache.aspx", StringComparison.OrdinalIgnoreCase) > 1 - || requestedPath.EndsWith("keepalive.aspx", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - //Get the root - var rootPath = requestedPath.Substring(0, requestedPath.LastIndexOf("/", StringComparison.Ordinal)); - rootPath = rootPath.Substring(rootPath.IndexOf("://", StringComparison.Ordinal) + 3); - - //Check if this is a WebServer and not a portalalias. - //if can auto add portal alias enabled, then return false, alias will add later. - var alias = PortalAliasController.Instance.GetPortalAlias(rootPath); - if (alias != null || CanAutoAddPortalAlias()) - { - return false; - } - - //Check if this is a WebServer - var server = ServerController.GetEnabledServers().SingleOrDefault(s => s.Url == rootPath); - if (server != null) - { - return true; - } - return false; - } - - private static bool IgnoreRequestForInstall(HttpRequest request) - { - try - { - string physicalPath = request.PhysicalPath; - string requestedDomain = request.Url.Host; - string refererPath = null, refererDomain = null; - if (request.UrlReferrer != null) - { - refererDomain = request.UrlReferrer.Host; - refererPath = request.UrlReferrer.LocalPath; - } - return IgnoreRequestForInstall(physicalPath, refererPath, requestedDomain, refererDomain); - } - catch (PathTooLongException) - { - //catch and handle this exception, caused by an excessively long file path based on the - //mapped virtual url - return false; - } - catch (ArgumentException) - { - //catch and handle this exception, caused by an invalid character in the file path based on the - //mapped virtual url - return false; - } - } - - private static bool IgnoreRequest(UrlAction result, string requestedPath, string ignoreRegex, HttpRequest request) - { - bool retVal = false; - //check if we are upgrading/installing - //829 : use result physical path instead of requset physical path - //875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1 - if (request != null && (IgnoreRequestForInstall(request) || IgnoreRequestForWebServer(requestedPath))) - { - //ignore all install requests - retVal = true; - } - else if (request != null && request.Path.EndsWith("imagechallenge.captcha.aspx", StringComparison.InvariantCultureIgnoreCase)) - { - retVal = true; - } - else - { - try - { - if ((ignoreRegex.Length > 0)) - { - if (Regex.IsMatch(requestedPath, ignoreRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) - { - retVal = true; - } - } - } - catch (Exception ex) - { - UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); - result.Ex = ex; - } - } - return retVal; - } - - private static void CheckForRewrite(string fullUrl, - string querystring, - UrlAction result, - bool useFriendlyUrls, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - out bool isPhysicalResource, - Guid parentTraceId) - { - bool checkForRewrites; - //just check to make sure it isn't a physical resource on the server - RewriteController.IdentifyByPhysicalResource(result.PhysicalPath, - fullUrl, - queryStringCol, - ref result, - useFriendlyUrls, - settings, - out isPhysicalResource, - out checkForRewrites, - parentTraceId); - - if (checkForRewrites && RewriteController.CanRewriteRequest(result, fullUrl, settings)) - { - bool doSiteUrlProcessing = false; - //728 new regex expression to pass values straight onto the siteurls.config file - if (!string.IsNullOrEmpty(settings.UseSiteUrlsRegex)) - { - doSiteUrlProcessing = Regex.IsMatch(fullUrl, settings.UseSiteUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - - if (!doSiteUrlProcessing) - //if a virtual request, and not starting with the siteUrls.config file, go on to find the rewritten path - { - //looks up the page index to find the correct Url - bool doRewrite = RewriteController.IdentifyByTabPathEx(fullUrl, querystring, result, queryStringCol, settings, parentTraceId); - if (!doRewrite) - { - doSiteUrlProcessing = true; - } - } - if (doSiteUrlProcessing) - { - //728 : compare requests against the siteurls.config file, either if no other match was found, or if we want to skip the rest of the processing - // the standard DNN way of rewriting, using expressions found in the siteurls.config file - RewriteController.IdentifyByRegEx(fullUrl, querystring, result.ApplicationPath, ref result, settings, parentTraceId); - } - } - } - - private void SecurityCheck(HttpApplication app) - { - HttpRequest request = app.Request; - HttpServerUtility server = app.Server; - - //675 : unnecessarily strict url validation - // URL validation - // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server - // the application should always use the exact relative location of the resource it is requesting - var strURL = request.Url.AbsolutePath; - var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.Url.AbsolutePath)) ?? ""; - if (UrlSlashesRegex.Match(strURL).Success || UrlSlashesRegex.Match(strDoubleDecodeURL).Success) - { - throw new HttpException(404, "Not Found"); - } - } - - private static bool CheckForRedirects(Uri requestUri, - string fullUrl, - NameValueCollection queryStringCol, - UrlAction result, - string requestType, - FriendlyUrlSettings settings, - int portalHomeTabId) - { - bool redirected = false; - if (queryStringCol["error"] == null && queryStringCol["message"] == null && requestType != "POST") - { - //if the / is missing from an extension-less request, then check for a 301 redirect - if (settings.PageExtensionUsageType == PageExtensionUsageType.Never) - { - //575 check on absolutePath instead of absoluteUri : this ignores query strings and fragments like # - //610 don't always end with '/' - reverses previous setting - //687 don't double-check 301 redirects. 'CheckFor301' is less concise than 'Redirect301' - // DNN-21906: if the redirect is for splash page, then we should continue the 302 redirect. - if (requestUri.AbsolutePath.EndsWith("/") && result.Action != ActionType.Redirect301 && result.Reason != RedirectReason.Requested_SplashPage) - { - result.Action = ActionType.CheckFor301; - } - } - if (settings.RedirectWrongCase && result.Action == ActionType.Continue) - { - result.Action = ActionType.CheckFor301; - } - string scheme = requestUri.Scheme + Uri.SchemeDelimiter; - bool queryStringHas301Parm = (queryStringCol["do301"] != null); - //727 : keep a bool value if there is a do301 request in the querystring - //check for a 301 request in the query string, or an explicit 301 or 302 request - //2.0 - check for explicit do301=true instead of just do301 key - string do301Val = queryStringCol["do301"]; - if (result.TabId > -1 //valid tab - && (result.Action == ActionType.Redirect301 //specific 301 redirect - || (do301Val != null && do301Val == "true") //or rewrite hint for specific 301 redirect - || result.Action == ActionType.Redirect302)) //or specific 302 redirect - { - //we have ordered a 301 redirect earlier in the code - //get the url for redirection by re-submitting the path into the Friendly Url Provider - string pathOnly = RewriteController.GetRewriteOrRequestedPath(result, requestUri); - //727 prevent redirectLoop with do301 in querystring - if (result.Action == ActionType.Redirect301 || queryStringHas301Parm || result.Action == ActionType.Redirect302) - { - pathOnly = RedirectTokens.RemoveAnyRedirectTokens(pathOnly, queryStringCol); - } - - //check for exclusion by regex for this url - if (result.RedirectAllowed) - { - //get the tab so we know where to go - TabInfo tab; - bool checkRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); - - if (checkRedirect) - { - if ((result.Reason == RedirectReason.Deleted_Page || result.Reason == RedirectReason.Disabled_Page) - && portalHomeTabId > 0 - && settings.DeletedTabHandlingType == DeletedTabHandlingType.Do301RedirectToPortalHome) - { - //redirecting to home page - TabInfo homeTab = TabController.Instance.GetTab(portalHomeTabId, result.PortalId, false); - if (homeTab != null) - { - string homePageUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(homeTab, - pathOnly, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - Guid.Empty); - result.Action = ActionType.Redirect301; - result.FinalUrl = homePageUrl; - result.RewritePath = pathOnly; - redirected = true; - } - } - else - { - //get the rewrite or requested path in a clean format, suitable for input to the friendly url provider - string cleanPath = RewriteController.GetRewriteOrRequestedPath(result, requestUri); - - //727 prevent redirectLoop with do301 in querystring - //also check for existing in path of do301 token - if (result.Action == ActionType.Redirect301 || do301Val != null || result.Action == ActionType.Redirect302) - { - cleanPath = RedirectTokens.RemoveAnyRedirectTokens(cleanPath, queryStringCol); - } - - //get best friendly url from friendly url provider - string bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - cleanPath, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - Guid.Empty); - - //get what the friendly Url for this tab should be and stick it in as the redirect - //727 : using boolean because we wanted to get rid of the do301 before calculating the correct url - if (queryStringHas301Parm) - { - result.Action = ActionType.Redirect301; - if (result.Reason == RedirectReason.Not_Redirected) - { - result.Reason = RedirectReason.Unfriendly_Url_1; - } - } - result.FinalUrl = bestFriendlyUrl; - result.RewritePath = pathOnly; - redirected = true; //mark as redirected - } - } - else - { - //redirect disallowed - //618: dont' clear if 302 redirect selected - if (result.Action != ActionType.Redirect302Now || result.Action != ActionType.Redirect302) - { - RedirectController.CancelRedirect(ref result, null, settings, "Redirect requested but cancelled because disallowed"); - } - } - } - } - else if (result.TabId > -1 && result.RedirectAllowed && result.Action == ActionType.CheckFor301) - { - //301 check was requested in earlier processing - //get the tab controller and retrieve the tab the request is for - //don't redirect unless allowed, the tab is valid, and it's not an admin or super tab - if (settings.RedirectUnfriendly) - { - TabInfo tab; - bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); - if (allowRedirect && tab != null) - { - //remove the http alias from the url. Do this by putting the url back together from the request and removing the alias - string rewritePathOnly; - if (result.DoRewrite) - { - rewritePathOnly = result.RewritePath; - var pos = rewritePathOnly.IndexOf("default.aspx", StringComparison.OrdinalIgnoreCase); - if (pos > Null.NullInteger) - { - rewritePathOnly = rewritePathOnly.Substring(pos); - } - } - else - { - rewritePathOnly = requestUri.Host + requestUri.PathAndQuery; - } - - //remove the http alias from the path - var pathAliasEnd = rewritePathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase); - var queryStringIndex = rewritePathOnly.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); - if (pathAliasEnd > Null.NullInteger && (queryStringIndex == Null.NullInteger || pathAliasEnd < queryStringIndex)) - { - rewritePathOnly = rewritePathOnly.Substring(pathAliasEnd + result.PortalAlias.HTTPAlias.Length); - } - - //now check to see if need to remove /default.aspx from the end of the requested Url - string requestedUrl = fullUrl; - int requestedUrlAliasEnd = requestedUrl.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) - + (result.PortalAlias.HTTPAlias + "/").Length; - if (requestedUrlAliasEnd > Null.NullInteger) - { - //818 : when a site root is used for a custom page Url, then check for max length within bounds - if ((requestedUrl.Length - requestedUrlAliasEnd) >= 12 && requestedUrl.Substring(requestedUrlAliasEnd).Equals("default.aspx", StringComparison.InvariantCultureIgnoreCase)) - { - requestedUrl = requestedUrl.Substring(0, requestedUrl.Length - 12); - //12 = default.aspx length - } - } - - //what happens here is that the request is reverse-engineered to see if it matches what the friendly Url shoudl have been - //get what the friendly Url for this tab should be - string bestFriendlyUrl; - //819 : leaving /do301/check in Url because not using cleanPath to remove from - - string cleanPath = RedirectTokens.RemoveAnyRedirectTokensAndReasons(rewritePathOnly); - //string cleanPath = rewritePathOnly.Replace("&do301=check","");//remove check parameter if it exists - //cleanPath = cleanPath.Replace("&do301=true", "");//don't pass through internal redirect check parameter - cleanPath = cleanPath.Replace("&_aumdebug=true", ""); //remove debug parameter if it exists - - Match match = RewritePathRx.Match(rewritePathOnly ?? ""); - if (match.Success) - { - //when the pathOnly value ends with '=' it means there is a query string pair with a key and no value - //make the assumption that this was passed in as a page name OTHER than default page - string pageName = match.Groups["parm"].Value; //get the last parameter in the list - - cleanPath = cleanPath.Replace(match.Value, ""); - //remove the last parameter from the path - - //generate teh friendly URl name with the last parameter as the page name, not a query string parameter - bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - cleanPath, - pageName + settings.PageExtension, - result.HttpAlias, - false, - settings, - Guid.Empty); - } - else - { - bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - cleanPath, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - Guid.Empty); - } - - //if the incoming request doesn't match the 'most friendly' url, a 301 Moved Permanently status is returned, along with the friendly url - //check the bestFriendlyUrl against either the url, or rawUrl (with and without host) - //in each case, the aumdebug parameter will be searched for and replaced - var urlDecode = HttpUtility.UrlDecode(requestedUrl); - if (urlDecode != null) - { - string rawUrlWithHost = StripDebugParameter(urlDecode.ToLowerInvariant()); - //string rawUrlWithHost = StripDebugParameter(System.Web.HttpUtility.UrlDecode(scheme + requestUri.Host + requestUri.PathAndQuery).ToLowerInvariant()); - string rawUrlWithHostNoScheme = StripDebugParameter(rawUrlWithHost.Replace(scheme, "")); - string bestFriendlyNoScheme = StripDebugParameter(bestFriendlyUrl.ToLowerInvariant().Replace(scheme, "")); - string requestedPathNoScheme = StripDebugParameter(requestUri.AbsoluteUri.Replace(scheme, "").ToLowerInvariant()); - string rawUrlLowerCase = StripDebugParameter(requestUri.AbsoluteUri.ToLowerInvariant()); - - //check to see if just an alias redirect of an internal alias - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - - if (settings.InternalAliasList != null && settings.InternalAliasList.Count > 0 && primaryAliases.Count > 0) - { - var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result); - if (cpa != null) - { - string chosenAlias = cpa.HTTPAlias.ToLowerInvariant(); - foreach (InternalAlias ia in settings.InternalAliasList) - { - string internalAlias = ia.HttpAlias.ToLowerInvariant(); - if (requestedPathNoScheme.Contains(internalAlias)) - { - //an internal alias has been used. - //replace this in the comparison charts to do a 'fair' comparison - requestedPathNoScheme = requestedPathNoScheme.Replace(internalAlias,chosenAlias); - rawUrlWithHost = rawUrlWithHost.Replace(scheme + internalAlias,scheme + chosenAlias); - rawUrlWithHostNoScheme = rawUrlWithHostNoScheme.Replace(internalAlias,chosenAlias); - rawUrlLowerCase = rawUrlLowerCase.Replace(internalAlias, chosenAlias); - break; - } - } - } - } - - //DNN-9158: prevent SSL Offloading infinite redirects - if (!result.IsSecureConnection && result.IsSSLOffloaded && bestFriendlyNoScheme.StartsWith("https")) - { - bestFriendlyNoScheme = $"http://{bestFriendlyNoScheme.Substring(8)}"; - } - - if (!(bestFriendlyNoScheme == requestedPathNoScheme - || bestFriendlyNoScheme == rawUrlWithHost - || bestFriendlyNoScheme == rawUrlWithHostNoScheme - || bestFriendlyNoScheme == HttpUtility.UrlDecode(requestedPathNoScheme) - || HttpUtility.UrlDecode(bestFriendlyNoScheme) == HttpUtility.UrlDecode(requestedPathNoScheme) - || bestFriendlyNoScheme == rawUrlLowerCase)) - { - redirected = true; - result.Action = ActionType.Redirect301; - result.FinalUrl = bestFriendlyUrl; - if (result.Reason != RedirectReason.Custom_Tab_Alias && - result.Reason != RedirectReason.Deleted_Page && - result.Reason != RedirectReason.Disabled_Page) - { - result.Reason = RedirectReason.Unfriendly_Url_2; - } - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + requestedPathNoScheme + " [requested with no scheme]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHost + " [requested with host and scheme]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHostNoScheme + " [requested with host, no scheme]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + HttpUtility.UrlDecode(requestedPathNoScheme) + " [requested and decoded]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlLowerCase + " [requested raw Url]"); - } - } - } - } - } - - if (result.RedirectAllowed && settings.RedirectWrongCase) - { - //check for redirects where a redirectToSubDomain is specified, - //redirect for Wrong case is specified, and there is a valid tab and it's not already redirected somewhere else - bool doRedirect = false; - string redirectPath = redirected ? result.FinalUrl : requestUri.AbsoluteUri; - string redirectPathOnly = redirectPath; - if (redirectPathOnly.Contains("?")) - { - redirectPathOnly = redirectPathOnly.Substring(0, redirectPathOnly.IndexOf("?", StringComparison.Ordinal)); - } - // Thanks Etienne for the fix for Diacritic Characters Terminal Loop! - // if the url contains url encoded characters, they appear here uppercase -> %C3%83%C2 - // decode the url to get back the original character and do proper casing comparison - string urlDecodedRedirectPath = HttpUtility.UrlDecode(redirectPathOnly); - - //check for wrong case redirection - if (urlDecodedRedirectPath != null && (settings.RedirectWrongCase && String.CompareOrdinal(urlDecodedRedirectPath, urlDecodedRedirectPath.ToLowerInvariant()) != 0)) - { - TabInfo tab; - bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); - - if (allowRedirect && !string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) - { - //don't allow redirect if excluded from redirecting in the force lower case regex pattern (606) - allowRedirect = !Regex.IsMatch(redirectPath, settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - - if (allowRedirect) - { - //special case : when IIS automatically places /default.aspx on the end of the string, - //then don't try and redirect to the lower case /default.aspx, just let it through. - //we don't know whether IIS appended /Default.aspx on the end, however, we can guess - //if the redirectDefault.aspx is turned on (511) - if (settings.RedirectDefaultPage == false && redirectPathOnly.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - //ignore this, because it's just a redirect of the /Default.aspx to /default.aspx - } - else - { - redirectPath = redirectPath.Replace(redirectPathOnly, redirectPathOnly.ToLowerInvariant()); - doRedirect = true; - result.Reason = RedirectReason.Not_Lower_Case; - } - } - } - if (doRedirect) - { - result.Action = ActionType.Redirect301; - result.FinalUrl = CheckForSiteRootRedirect(result.PortalAlias.HTTPAlias, redirectPath); - redirected = true; - } - } - } - return redirected; - } - - private static string StripDebugParameter(string url) - { - return AumDebugRegex.Replace(url, ""); - } - - private static bool CheckFor301RedirectExclusion(int tabId, int portalId, bool checkBaseUrls, out TabInfo tab, FriendlyUrlSettings settings) - { - bool doRedirect = false; - tab = TabController.Instance.GetTab(tabId, portalId, false); - //don't redirect unless allowed, the tab is valid, and it's not an admin or super tab - if (tab != null && tab.IsSuperTab == false && !tab.DoNotRedirect) - { - if (checkBaseUrls) - { - //no redirect for friendly url purposes if the tab is in the 'base friendly urls' section - doRedirect = !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, true); - } - else - { - doRedirect = true; - } - } - return doRedirect; - } - - /// - /// Make sure any redirect to the site root doesn't append the nasty /default.aspx on the end - /// - /// - /// - /// - internal static string CheckForSiteRootRedirect(string alias, string destUrl) - { - //540 - don't append /default.aspx onto the end of a site root redirect. - if (destUrl.EndsWith(alias + "/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - //this is just the portal alias root + /defualt.aspx. - //we don't want that, just the portalAliasRoot + "/" - string aliasPlusSlash = alias + "/"; - //get everything up to the end of the portal alias - destUrl = destUrl.Substring(0, destUrl.IndexOf(aliasPlusSlash, StringComparison.Ordinal) + aliasPlusSlash.Length); - } - return destUrl; - } - - #endregion - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Entities.Urls +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Security.Principal; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Web.Configuration; + using System.Web.Security; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Services.EventQueue; + + public class AdvancedUrlRewriter : UrlRewriterBase + { + private static readonly Regex DefaultPageRegex = new Regex(@"(?.[^&]+)=$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex UrlSlashesRegex = new Regex("[\\\\/]\\.\\.[\\\\/]", RegexOptions.Compiled); + private static readonly Regex AliasUrlRegex = new Regex(@"(?:^(?http[s]{0,1}://){0,1})(?:(?_ALIAS_)(?$|\?[\w]*|/[\w]*))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private const string _productName = "AdvancedUrlRewriter"; + private FriendlyUrlSettings _settings; + + internal override void RewriteUrl(object sender, EventArgs e) + { + Guid parentTraceId = Guid.Empty; + const bool debug = true; + bool failedInitialization = false; + bool ignoreForInstall = false; + var app = (HttpApplication)sender; + try + { + // 875 : completely ignore install/upgrade requests immediately + ignoreForInstall = IgnoreRequestForInstall(app.Request); + + if (ignoreForInstall == false) + { + this._settings = new FriendlyUrlSettings(-1); + + this.SecurityCheck(app); + } + } + catch (Exception ex) + { + // exception handling for advanced Url Rewriting requests + failedInitialization = true; + DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); + if (app.Context != null) + { + ShowDebugData(app.Context, app.Request.Url.AbsoluteUri, null, ex); + var action = new UrlAction(app.Request) { Action = ActionType.Output404 }; + Handle404OrException(this._settings, app.Context, ex, action, false, debug); + } + else + { + throw; + } + } + + if (!failedInitialization && !ignoreForInstall) + { + // if made it through there and not installing, go to next call. Not in exception catch because it implements it's own top-level exception handling + var request = app.Context.Request; + + // 829 : change constructor to stop using physical path + var result = new UrlAction(request) + { + IsSecureConnection = request.IsSecureConnection, + IsSSLOffloaded = UrlUtils.IsSslOffloadEnabled(request), + RawUrl = request.RawUrl, + }; + this.ProcessRequest( + app.Context, + app.Context.Request.Url, + Host.UseFriendlyUrls, + result, + this._settings, + true, + parentTraceId); + } + } + + public void ProcessTestRequestWithContext( + HttpContext context, + Uri requestUri, + bool useFriendlyUrls, + UrlAction result, + FriendlyUrlSettings settings) + { + Guid parentTraceId = Guid.Empty; + this._settings = settings; + this.ProcessRequest( + context, + requestUri, + useFriendlyUrls, + result, + settings, + false, + parentTraceId); + } + + private PortalAliasInfo GetPortalAlias(FriendlyUrlSettings settings, string requestUrl, out bool redirectAlias, out bool isPrimaryAlias, out string wrongAlias) + { + PortalAliasInfo aliasInfo = null; + redirectAlias = false; + wrongAlias = null; + isPrimaryAlias = false; + OrderedDictionary portalAliases = TabIndexController.GetPortalAliases(settings); + foreach (string alias in portalAliases.Keys) + { + var urlToMatch = requestUrl; + + // in fact, requested url should contain alias + // for better performance, need to check whether we want to proceed with a whole url matching or not + // if alias is not a part of url -> let's proceed to the next iteration + var aliasIndex = urlToMatch.IndexOf(alias, StringComparison.InvariantCultureIgnoreCase); + if (aliasIndex < 0) + { + continue; + } + else + { + // we do not accept URL if the first occurence of alias is presented somewhere in the query string + var queryIndex = urlToMatch.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); + if (queryIndex >= 0 && queryIndex < aliasIndex) + { + // alias is in the query string, go to the next alias + continue; + } + + // we are fine here, lets prepare URL to be validated in regex + urlToMatch = urlToMatch.ReplaceIgnoreCase(alias, "_ALIAS_"); + } + + // check whether requested URL has the right URL format containing existing alias + // i.e. url is http://dnndev.me/site1/query?string=test, alias is dnndev.me/site1 + // in the below expression we will validate following value http://_ALIAS_/query?string=test + var aliasMatch = AliasUrlRegex.Match(urlToMatch); + if (aliasMatch.Success) + { + // check for mobile browser and matching + var aliasEx = (PortalAliasInfo)portalAliases[alias]; + redirectAlias = aliasEx.Redirect; + if (redirectAlias) + { + wrongAlias = alias; + } + + isPrimaryAlias = aliasEx.IsPrimary; + aliasInfo = aliasEx; + break; + } + } + + return aliasInfo; + } + + private void ProcessRequest( + HttpContext context, + Uri requestUri, + bool useFriendlyUrls, + UrlAction result, + FriendlyUrlSettings settings, + bool allowSettingsChange, + Guid parentTraceId) + { + bool finished = false; + bool showDebug = false; + bool postRequest = false; + + HttpRequest request = context.Request; + HttpResponse response = context.Response; + string requestType = request.RequestType; + NameValueCollection queryStringCol = request.QueryString; + + try + { + string fullUrl, querystring; + + // 699: get the full url based on the request and the quersytring, rather than the requestUri.ToString() + // there is a difference in encoding, which can corrupt results when an encoded value is in the querystring + RewriteController.GetUrlWithQuerystring(request, requestUri, out fullUrl, out querystring); + + showDebug = CheckForDebug(request, queryStringCol, settings.AllowDebugCode); + string ignoreRegex = settings.IgnoreRegex; + bool ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); + bool redirectAlias = false; + if (!ignoreRequest) + { + // set original path + context.Items["UrlRewrite:OriginalUrl"] = requestUri.AbsoluteUri; + + // set the path of the result object, and determine if a redirect is allowed on this request + result.SetOriginalPath(requestUri.ToString(), settings); + + // 737 : set the mobile browser + result.SetBrowserType(request, response, settings); + + // add to context + context.Items["UrlRewrite:BrowserType"] = result.BrowserType.ToString(); + + // 839 : split out this check + result.SetRedirectAllowed(result.OriginalPath, settings); + + // find the portal alias first + string wrongAlias; + bool isPrimaryAlias; + var requestedAlias = this.GetPortalAlias(settings, fullUrl, out redirectAlias, out isPrimaryAlias, out wrongAlias); + + if (requestedAlias != null) + { + // 827 : now get the correct settings for this portal (if not a test request) + // 839 : separate out redirect check as well and move above first redirect test (ConfigurePortalAliasRedirect) + if (allowSettingsChange) + { + settings = new FriendlyUrlSettings(requestedAlias.PortalID); + result.SetRedirectAllowed(result.OriginalPath, settings); + } + + result.PortalAlias = requestedAlias; + result.PrimaryAlias = requestedAlias; // this is the primary alias + result.PortalId = requestedAlias.PortalID; + result.CultureCode = requestedAlias.CultureCode; + + // get the portal alias mapping for this portal + result.PortalAliasMapping = PortalSettingsController.Instance().GetPortalAliasMappingMode(requestedAlias.PortalID); + + // if requested alias wasn't the primary, we have a replacement, redirects are allowed and the portal alias mapping mode is redirect + // then do a redirect based on the wrong portal + if ((redirectAlias && wrongAlias != null) && result.RedirectAllowed && result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) + { + // this is the alias, we are going to enforce it as the primary alias + result.PortalAlias = requestedAlias; + result.PrimaryAlias = requestedAlias; + + // going to redirect this alias because it is incorrect + // or do we just want to mark as 'check for 301??' + redirectAlias = ConfigurePortalAliasRedirect( + ref result, + wrongAlias, + requestedAlias.HTTPAlias, + false, + settings.InternalAliasList, + settings); + } + else + { + // do not redirect the wrong alias, but set the primary alias value + if (wrongAlias != null) + { + // get the portal alias info for the requested alias (which is the wrong one) + // and set that as the alias, but also set the found alias as the primary + PortalAliasInfo wrongAliasInfo = PortalAliasController.Instance.GetPortalAlias(wrongAlias); + if (wrongAliasInfo != null) + { + result.PortalAlias = wrongAliasInfo; + result.PrimaryAlias = requestedAlias; + } + } + } + } + } + + ignoreRegex = settings.IgnoreRegex; + ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); + if (!ignoreRequest) + { + // check to see if a post request + if (request.RequestType == "POST") + { + postRequest = true; + } + + // check the portal alias again. This time, in more depth now that the portal Id is known + // this check handles browser types/language specific aliases & mobile aliases + string primaryHttpAlias; + if (!redirectAlias && this.IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryHttpAlias)) + { + // it was an incorrect alias + PortalAliasInfo primaryAlias = PortalAliasController.Instance.GetPortalAlias(primaryHttpAlias); + if (primaryAlias != null) + { + result.PrimaryAlias = primaryAlias; + } + + // try and redirect the alias if the settings allow it + redirectAlias = RedirectPortalAlias(primaryHttpAlias, ref result, settings); + } + + if (redirectAlias) + { + // not correct alias for portal : will be redirected + // perform a 301 redirect if one has already been found + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl, false); + finished = true; + } + + if (!finished) + { + // Check to see if this to be rewritten into default.aspx?tabId=nn format + // this call is the main rewriting matching call. It makes the decision on whether it is a + // physical file, whether it is toe be rewritten or redirected by way of a stored rule + + // Check if we have a standard url + var uri = new Uri(fullUrl); + if (uri.PathAndQuery.StartsWith("/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + { + result.DoRewrite = true; + result.Action = ActionType.CheckFor301; + result.RewritePath = Globals.glbDefaultPage + uri.Query; + } + else + { + bool isPhysicalResource; + CheckForRewrite(fullUrl, querystring, result, useFriendlyUrls, queryStringCol, settings, out isPhysicalResource, parentTraceId); + } + + // return 404 if there is no portal alias for a rewritten request + if (result.DoRewrite && result.PortalAlias == null) + { + // 882 : move this logic in from where it was before to here + // so that non-rewritten requests don't trip over it + // no portal alias found for the request : that's a 404 error + result.Action = ActionType.Output404; + result.Reason = RedirectReason.No_Portal_Alias; + + Handle404OrException(settings, context, null, result, false, showDebug); + finished = true; // cannot fulfil request unless correct portal alias specified + } + } + + // now we may know the TabId. If the current alias is not the same as the primary alias, + // we should check if the current alias is indeed a valid custom alias for the current tab. + if (result.TabId > 0 && result.HttpAlias != result.PrimaryAlias.HTTPAlias && !CheckIfAliasIsCurrentTabCustomTabAlias(ref result, settings)) + { + //it was an incorrect alias + //try and redirect the alias if the settings allow it + if( RedirectPortalAlias(result.PrimaryAlias.HTTPAlias, ref result, settings)) + { + //not correct alias for tab : will be redirected + //perform a 301 redirect if one has already been found + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl, false); + finished = true; + } + } + + if (!finished && result.DoRewrite) + { + // check the identified portal alias details for any extra rewrite information required + // this includes the culture and the skin, which can be placed into the rewrite path + // This logic is here because it will catch any Urls which are excluded from rewriting + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + + if (result.PortalId > -1 && result.HttpAlias != null) + { + string culture; + string skin; + BrowserTypes browserType; + primaryAliases.GetSettingsByPortalIdAndAlias(result.PortalId, result.HttpAlias, + out culture, + out browserType, + out skin); + + // add language code to path if it exists (not null) and if it's not already there + string rewritePath = result.RewritePath; + if (RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, culture)) + { + result.CultureCode = culture; + } + + // 852: add skinSrc to path if it exists and if it's not already there + string debugMessage; + RewriteController.AddSkinToRewritePath(result.TabId, result.PortalId, ref rewritePath, skin, out debugMessage); + result.RewritePath = rewritePath; // reset back from ref temp var + if (debugMessage != null) + { + result.DebugMessages.Add(debugMessage); + } + } + } + + if (!finished && result.DoRewrite) + { + // if so, do the rewrite + if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false) + { + if (result.RewritePath.Contains(Globals.glbDefaultPage) == false) + { + RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); + } + else + { + // if there is no TabId and we have the domain + if (!result.RewritePath.ToLowerInvariant().Contains("tabId=")) + { + RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); + } + else + { + RewriterUtils.RewriteUrl(context, result.RewritePath); + } + } + } + else + { + RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); + } + } + + // confirm which portal the request is for + if (!finished) + { + this.IdentifyPortalAlias(context, request, requestUri, result, queryStringCol, settings, parentTraceId); + if (result.Action == ActionType.Redirect302Now) + { + // performs a 302 redirect if requested + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl, false); + finished = true; + } + else + { + if (result.Action == ActionType.Redirect301 && !string.IsNullOrEmpty(result.FinalUrl)) + { + finished = true; + + // perform a 301 redirect if one has already been found + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl, false); + } + } + } + + if (!finished) + { + // check to see if this tab has an external url that should be forwared or not + finished = CheckForTabExternalForwardOrRedirect(context, ref result, response, settings, parentTraceId); + } + + // check for a parameter redirect (we had to do all the previous processing to know we are on the right portal and identify the tabid) + // if the CustomParmRewrite flag is set, it means we already rewrote these parameters, so they have to be correct, and aren't subject to + // redirection. The only reason to do a custom parm rewrite is to interpret already-friendly parameters + if (!finished + && !postRequest /* either request is null, or it's not a post - 551 */ + && result.HttpAlias != null /* must have a http alias */ + && !result.CustomParmRewrite && /* not custom rewritten parms */ + ((settings.EnableCustomProviders && + RedirectController.CheckForModuleProviderRedirect(requestUri, ref result, queryStringCol, settings, parentTraceId)) + + // 894 : allow disable of all custom providers + || + RedirectController.CheckForParameterRedirect(requestUri, ref result, queryStringCol, settings))) + { + // 301 redirect to new location based on parameter match + if (response != null) + { + switch (result.Action) + { + case ActionType.Redirect301: + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl); + break; + case ActionType.Redirect302: + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl); + break; + case ActionType.Output404: + response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); + Handle404OrException(settings, context, null, result, true, showDebug); + break; + } + } + + finished = true; + } + + // shifted until after the 301 redirect code to allow redirects to be checked for pages which have no rewrite value + // look for a 404 result from the rewrite, because of a deleted page or rule + if (!finished && result.Action == ActionType.Output404) + { + if (result.OriginalPath.Equals(result.HttpAlias, StringComparison.InvariantCultureIgnoreCase) + && result.PortalAlias != null + && result.Reason != RedirectReason.Deleted_Page + && result.Reason != RedirectReason.Disabled_Page) + { + // Request for domain with no page identified (and no home page set in Site Settings) + result.Action = ActionType.Continue; + } + else + { + finished = true; + response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); + + if (showDebug) + { + ShowDebugData(context, requestUri.AbsoluteUri, result, null); + } + + // show the 404 page if configured + result.Reason = RedirectReason.Requested_404; + Handle404OrException(settings, context, null, result, true, showDebug); + } + } + + if (!finished) + { + // add the portal settings to the app context if the portal alias has been found and is correct + if (result.PortalId != -1 && result.PortalAlias != null) + { + // for invalid tab id other than -1, show the 404 page + TabInfo tabInfo = TabController.Instance.GetTab(result.TabId, result.PortalId, false); + if (tabInfo == null && result.TabId > -1) + { + finished = true; + + if (showDebug) + { + ShowDebugData(context, requestUri.AbsoluteUri, result, null); + } + + // show the 404 page if configured + result.Action = ActionType.Output404; + result.Reason = RedirectReason.Requested_404; + response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); + Handle404OrException(settings, context, null, result, true, showDebug); + } + else + { + Globals.SetApplicationName(result.PortalId); + + // load the PortalSettings into current context + var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); + + // set the primary alias if one was specified + if (result.PrimaryAlias != null) + { + portalSettings.PrimaryAlias = result.PrimaryAlias; + } + + if (result.CultureCode != null && fullUrl.Contains(result.CultureCode) && + portalSettings.DefaultLanguage == result.CultureCode) + { + // when the request culture code is the same as the portal default, check for a 301 redirect, because we try and remove the language from the url where possible + result.Action = ActionType.CheckFor301; + } + + int portalHomeTabId = portalSettings.HomeTabId; + if (context != null && portalSettings != null && !context.Items.Contains("PortalSettings")) + { + context.Items.Add("PortalSettings", portalSettings); + + // load PortalSettings and HostSettings dictionaries into current context + // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way + context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalSettings.PortalId)); + context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary()); + } + + // check if a secure redirection is needed + // this would be done earlier in the piece, but need to know the portal settings, tabid etc before processing it + bool redirectSecure = this.CheckForSecureRedirect(portalSettings, requestUri, result, queryStringCol, settings); + if (redirectSecure) + { + if (response != null) + { + // 702 : don't check final url until checked for null reference first + if (result.FinalUrl != null) + { + if (result.FinalUrl.StartsWith("https://")) + { + if (showDebug) + { + /* + string debugMsg = "{0}, {1}, {2}, {3}, {4}"; + string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); + response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); + */ + ShowDebugData(context, fullUrl, result, null); + } + + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl); + finished = true; + } + else + { + if (settings.SSLClientRedirect) + { + // redirect back to http version, use client redirect + response.Clear(); + + // add a refresh header to the response + response.AddHeader("Refresh", "0;URL=" + result.FinalUrl); + + // add the clientside javascript redirection script + var finalUrl = HttpUtility.HtmlEncode(result.FinalUrl); + response.Write(""); + response.Write(@""); + response.Write(""); + if (showDebug) + { + /* + string debugMsg = "{0}, {1}, {2}, {3}, {4}"; + string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); + response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); + */ + ShowDebugData(context, fullUrl, result, null); + } + + // send the response + // 891 : reinstate the response.end to stop the entire page loading + response.End(); + finished = true; + } + else + { + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl); + finished = true; + } + } + } + } + } + else + { + // check for, and do a 301 redirect if required + if (CheckForRedirects(requestUri, fullUrl, queryStringCol, result, requestType, settings, portalHomeTabId)) + { + if (response != null) + { + if (result.Action == ActionType.Redirect301) + { + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl, false); + finished = true; + } + else if (result.Action == ActionType.Redirect302) + { + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl, false); + finished = true; + } + } + } + else + { + // 612 : Don't clear out a 302 redirect if set + if (result.Action != ActionType.Redirect302 && + result.Action != ActionType.Redirect302Now) + { + result.Reason = RedirectReason.Not_Redirected; + result.FinalUrl = null; + } + } + } + } + } + else + { + // alias does not exist in database + // and all attempts to find another have failed + // this should only happen if the HostPortal does not have any aliases + result.Action = ActionType.Output404; + if (response != null) + { + if (showDebug) + { + ShowDebugData(context, fullUrl, result, null); + } + + result.Reason = RedirectReason.Requested_404; + + // 912 : change 404 type to transfer to allow transfer to main portal in single-portal installs + Handle404OrException(settings, context, null, result, true, showDebug); + finished = true; + } + } + } + + // 404 page ?? + if (settings.TabId404 > 0 && settings.TabId404 == result.TabId) + { + string status = queryStringCol["status"]; + if (status == "404") + { + // respond with a 404 error + result.Action = ActionType.Output404; + result.Reason = RedirectReason.Requested_404_In_Url; + Handle404OrException(settings, context, null, result, true, showDebug); + } + } + else + { + if (result.DoRewrite == false && result.CanRewrite != StateBoolean.False && !finished && + result.Action == ActionType.Continue) + { + // 739 : catch no-extension 404 errors + string pathWithNoQs = result.OriginalPath; + if (pathWithNoQs.Contains("?")) + { + pathWithNoQs = pathWithNoQs.Substring(0, pathWithNoQs.IndexOf("?", StringComparison.Ordinal)); + } + + if (!pathWithNoQs.Substring(pathWithNoQs.Length - 5, 5).Contains(".")) + { + // no page extension, output a 404 if the Url is not found + // 766 : check for physical path before passing off as a 404 error + // 829 : change to use action physical path + // 893 : filter by regex pattern to exclude urls which are valid, but show up as extensionless + if ((request != null && Directory.Exists(result.PhysicalPath)) + || + Regex.IsMatch(pathWithNoQs, settings.ValidExtensionlessUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + { + // do nothing : it's a request for a valid physical path, maybe including a default document + result.VirtualPath = StateBoolean.False; + } + else + { + if (!Globals.ServicesFrameworkRegex.IsMatch(context.Request.RawUrl)) + { + // no physical path, intercept the request and hand out a 404 error + result.Action = ActionType.Output404; + result.Reason = RedirectReason.Page_404; + result.VirtualPath = StateBoolean.True; + + // add in a message to explain this 404, becaue it can be cryptic + result.DebugMessages.Add("404 Reason : Not found and no extension"); + Handle404OrException(settings, context, null, result, true, showDebug); + } + } + } + } + } + + // show debug messages after extensionless-url special 404 handling + if (showDebug) + { + ShowDebugData(context, fullUrl, result, null); + } + } + } + catch (ThreadAbortException) + { + // do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest + // level try/catch block, so we handle it here. + Thread.ResetAbort(); + } + catch (Exception ex) + { + if (showDebug) + { + Services.Exceptions.Exceptions.LogException(ex); + } + + if (response != null) + { + if (showDebug) + { + ShowDebugData(context, requestUri.AbsoluteUri, result, ex); + } + + if (result != null) + { + result.Ex = ex; + result.Reason = RedirectReason.Exception; + } + + Handle404OrException(settings, context, ex, result, false, showDebug); + } + else + { + if (result != null && result.DebugMessages != null) + { + result.DebugMessages.Add("Exception: " + ex.Message); + result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + } + + throw; + } + } + finally + { + // 809 : add in new code copied from urlRewrite class in standard Url Rewrite module + if (context != null && context.Items["FirstRequest"] != null) + { + context.Items.Remove("FirstRequest"); + + // process any messages in the eventQueue for the Application_Start_FIrstRequest event + EventQueueController.ProcessMessages("Application_Start_FirstRequest"); + } + } + } + + private static void ShowDebugData(HttpContext context, string requestUri, UrlAction result, Exception ex) + { + if (context != null) + { + HttpResponse response = context.Response; + + // handle null responses wherever they might be found - this routine must be tolerant to all kinds of invalid inputs + if (requestUri == null) + { + requestUri = "null Uri"; + } + + string finalUrl = "null final Url"; + string rewritePath = "null rewrite path"; + string action = "null action"; + if (result != null) + { + finalUrl = result.FinalUrl; + action = result.Action.ToString(); + rewritePath = result.RewritePath; + } + + // format up the error message to show + const string debugMsg = "{0}, {1}, {2}, {3}, {4}, {5}, {6}"; + string productVer = DotNetNukeContext.Current.Application.Version.ToString(); + string portalSettings = string.Empty; + string browser = "Unknown"; + + // 949 : don't rely on 'result' being non-null + if (result != null) + { + browser = result.BrowserType.ToString(); + } + + if (context.Items.Contains("PortalSettings")) + { + var ps = (PortalSettings)context.Items["PortalSettings"]; + if (ps != null) + { + portalSettings = ps.PortalId.ToString(); + if (ps.PortalAlias != null) + { + portalSettings += ":" + ps.PortalAlias.HTTPAlias; + } + } + } + + response.AppendHeader( + "X-" + _productName + "-Debug", + string.Format(debugMsg, requestUri, finalUrl, rewritePath, action, productVer, + portalSettings, browser)); + int msgNum = 1; + if (result != null) + { + foreach (string msg in result.DebugMessages) + { + response.AppendHeader("X-" + _productName + "-Debug-" + msgNum.ToString("00"), msg); + msgNum++; + } + } + + if (ex != null) + { + response.AppendHeader("X-" + _productName + "-Ex", ex.Message); + } + } + } + + private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug) + { + // handle Auto-Add Alias + if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias()) + { + // Need to determine if this is a real 404 or a possible new alias. + var portalId = Host.HostPortalID; + if (portalId > Null.NullInteger) + { + if (string.IsNullOrEmpty(result.DomainName)) + { + result.DomainName = Globals.GetDomainName(context.Request); // parse the domain name out of the request + } + + // Get all the existing aliases + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); + + bool autoaddAlias; + bool isPrimary = false; + if (!aliases.Any()) + { + autoaddAlias = true; + isPrimary = true; + } + else + { + autoaddAlias = true; + foreach (var alias in aliases) + { + if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0 + && result.DomainName.Length >= alias.HTTPAlias.Length) + { + autoaddAlias = false; + break; + } + } + } + + if (autoaddAlias) + { + var portalAliasInfo = new PortalAliasInfo + { + PortalID = portalId, + HTTPAlias = result.DomainName, + IsPrimary = isPrimary, + }; + PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); + + context.Response.Redirect(context.Request.Url.ToString(), true); + } + } + } + + if (context != null) + { + HttpRequest request = context.Request; + HttpResponse response = context.Response; + HttpServerUtility server = context.Server; + + const string errorPageHtmlHeader = @"{0}"; + const string errorPageHtmlFooter = @""; + var errorPageHtml = new StringWriter(); + CustomErrorsSection ceSection = null; + + // 876 : security catch for custom error reading + try + { + ceSection = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); + } + +// ReSharper disable EmptyGeneralCatchClause + catch (Exception) + +// ReSharper restore EmptyGeneralCatchClause + { + // on some medium trust environments, this will throw an exception for trying to read the custom Errors + // do nothing + } + + /* 454 new 404/500 error handling routine */ + bool useDNNTab = false; + int errTabId = -1; + string errUrl = null; + string status = string.Empty; + bool isPostback = false; + if (settings != null) + { + if (request.RequestType == "POST") + { + isPostback = true; + } + + if (result != null && ex != null) + { + result.DebugMessages.Add("Exception: " + ex.Message); + result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + if (ex.InnerException != null) + { + result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message); + result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace); + } + else + { + result.DebugMessages.Add("Inner Ex : null"); + } + } + + string errRH; + string errRV; + int statusCode; + if (result != null && result.Action != ActionType.Output404) + { + // output everything but 404 (usually 500) + if (settings.TabId500 > -1) // tabid specified for 500 error page, use that + { + useDNNTab = true; + errTabId = settings.TabId500; + } + + errUrl = settings.Url500; + errRH = "X-UrlRewriter-500"; + errRV = "500 Rewritten to {0} : {1}"; + statusCode = 500; + status = "500 Internal Server Error"; + } + else // output 404 error + { + if (settings.TabId404 > -1) // if the tabid is specified for a 404 page, then use that + { + useDNNTab = true; + errTabId = settings.TabId404; + } + + if (!string.IsNullOrEmpty(settings.Regex404)) + + // with 404 errors, there's an option to catch certain urls and use an external url for extra processing. + { + try + { + // 944 : check the original Url in case the requested Url has been rewritten before discovering it's a 404 error + string requestedUrl = request.Url.ToString(); + if (result != null && !string.IsNullOrEmpty(result.OriginalPath)) + { + requestedUrl = result.OriginalPath; + } + + if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + { + useDNNTab = false; + + // if we have a match in the 404 regex value, then don't use the tabid + } + } + catch (Exception regexEx) + { + // .some type of exception : output in response header, and go back to using the tabid + response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message); + } + } + + errUrl = settings.Url404; + errRH = "X-UrlRewriter-404"; + errRV = "404 Rewritten to {0} : {1} : Reason {2}"; + status = "404 Not Found"; + statusCode = 404; + } + + // check for 404 logging + if (result == null || result.Action == ActionType.Output404) + { + // Log 404 errors to Event Log + UrlRewriterUtils.Log404(request, settings, result); + } + + // 912 : use unhandled 404 switch + string reason404 = null; + bool unhandled404 = true; + if (useDNNTab && errTabId > -1) + { + unhandled404 = false; // we're handling it here + TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true); + if (errTab != null) + { + bool redirect = false; + + // ok, valid tabid. what we're going to do is to load up this tab via a rewrite of the url, and then change the output status + string reason = "Not Found"; + if (result != null) + { + reason = result.Reason.ToString(); + } + + response.AppendHeader(errRH, string.Format(errRV, "DNN Tab", + errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", + reason)); + + // show debug messages even if in debug mode + if (context != null && response != null && result != null && showDebug) + { + ShowDebugData(context, result.OriginalPath, result, null); + } + + if (!isPostback) + { + response.ClearContent(); + response.StatusCode = statusCode; + response.Status = status; + } + else + { + redirect = true; + + // redirect postbacks as you can't postback successfully to a server.transfer + } + + errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, string.Empty); + + // have to update the portal settings with the new tabid + PortalSettings ps = null; + if (context != null && context.Items != null) + { + if (context.Items.Contains("PortalSettings")) + { + ps = (PortalSettings)context.Items["PortalSettings"]; + context.Items.Remove("PortalSettings"); // nix it from the context + } + } + + if (ps != null && ps.PortalAlias != null) + { + ps = new PortalSettings(errTabId, ps.PortalAlias); + } + else + { + if (result.HttpAlias != null && result.PortalId > -1) + { + PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId); + ps = new PortalSettings(errTabId, pa); + } + else + { + // 912 : handle 404 when no valid portal can be identified + // results when iis is configured to handle portal alias, but + // DNN isn't. This always returns 404 because a multi-portal site + // can't just show the 404 page of the host site. + ArrayList portals = PortalController.Instance.GetPortals(); + if (portals != null && portals.Count == 1) + { + // single portal install, load up portal settings for this portal + var singlePortal = (PortalInfo)portals[0]; + + // list of aliases from database + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(singlePortal.PortalID).ToList(); + + // list of aliases from Advanced Url settings + List chosen = aliases.GetAliasesForPortalId(singlePortal.PortalID); + PortalAliasInfo useFor404 = null; + + // go through all aliases and either get the first valid one, or the first + // as chosen in the advanced url management settings + foreach (var pa in aliases) + { + if (useFor404 == null) + { + useFor404 = pa; // first one by default + } + + // matching? + if (chosen != null && chosen.Count > 0) + { + if (chosen.Contains(pa.HTTPAlias)) + { + useFor404 = pa; + } + } + else + { + break; // no further checking + } + } + + // now configure that as the portal settings + if (useFor404 != null) + { + // create portal settings context for identified portal alias in single portal install + ps = new PortalSettings(errTabId, useFor404); + } + } + else + { + reason404 = "Requested domain name is not configured as valid website"; + unhandled404 = true; + } + } + } + + if (ps != null) + { + // re-add the context items portal settings back in + context.Items.Add("PortalSettings", ps); + } + + if (redirect) + { + errUrl = TestableGlobals.Instance.NavigateURL(); + response.Redirect(errUrl, true); // redirect and end response. + + // It will mean the user will have to postback again, but it will work the second time + } + else + { + if (transfer) + { + // execute a server transfer to the default.aspx?tabid=xx url + // 767 : object not set error on extensionless 404 errors + if (context.User == null) + { + context.User = GetCurrentPrincipal(context); + } + + response.TrySkipIisCustomErrors = true; + + // 881 : spoof the basePage object so that the client dependency framework + // is satisfied it's working with a page-based handler + IHttpHandler spoofPage = new CDefault(); + context.Handler = spoofPage; + server.Transfer("~/" + errUrl, true); + } + else + { + context.RewritePath("~/Default.aspx", false); + response.TrySkipIisCustomErrors = true; + response.Status = "404 Not Found"; + response.StatusCode = 404; + } + } + } + } + + // 912 : change to new if statement to handle cases where the TabId404 couldn't be handled correctly + if (unhandled404) + { + // proces the error on the external Url by rewriting to the external url + if (!string.IsNullOrEmpty(errUrl)) + { + response.ClearContent(); + response.TrySkipIisCustomErrors = true; + string reason = "Not Found"; + if (result != null) + { + reason = result.Reason.ToString(); + } + + response.AppendHeader(errRH, string.Format(errRV, "Url", errUrl, reason)); + if (reason404 != null) + { + response.AppendHeader("X-Url-Master-404-Data", reason404); + } + + response.StatusCode = statusCode; + response.Status = status; + server.Transfer("~/" + errUrl, true); + } + else + { + errorPageHtml.Write(status + "
    The requested Url does not return any valid content."); + if (reason404 != null) + { + errorPageHtml.Write(status + "
    " + reason404); + } + + errorPageHtml.Write("
    Administrators
    "); + errorPageHtml.Write("
    Change this message by configuring a specific 404 Error Page or Url for this website.
    "); + + // output a reason for the 404 + string reason = string.Empty; + if (result != null) + { + reason = result.Reason.ToString(); + } + + if (!string.IsNullOrEmpty(errRH) && !string.IsNullOrEmpty(reason)) + { + response.AppendHeader(errRH, reason); + } + + response.StatusCode = statusCode; + response.Status = status; + } + } + } + else + { + // fallback output if not valid settings + if (result != null && result.Action == ActionType.Output404) + { + // don't restate the requested Url to prevent cross site scripting + errorPageHtml.Write("404 Not Found
    The requested Url does not return any valid content."); + response.StatusCode = 404; + response.Status = "404 Not Found"; + } + else + { + // error, especially if invalid result object + errorPageHtml.Write("500 Server Error
    An error occured during processing : if possible, check the event log of the server
    "); + response.StatusCode = 500; + response.Status = "500 Internal Server Error"; + if (result != null) + { + result.Action = ActionType.Output500; + } + } + } + + if (ex != null) + { + if (context != null) + { + if (context.Items.Contains("UrlRewrite:Exception") == false) + { + context.Items.Add("UrlRewrite:Exception", ex.Message); + context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace); + } + } + + if (ceSection != null && ceSection.Mode == CustomErrorsMode.Off) + { + errorPageHtml.Write(errorPageHtmlHeader); + errorPageHtml.Write("
    Exception:
    " + ex.Message + "
    "); + errorPageHtml.Write("
    Stack Trace:
    " + ex.StackTrace + "
    "); + errorPageHtml.Write("
    Administrators
    "); + errorPageHtml.Write("
    You can see this exception because the customErrors attribute in the web.config is set to 'off'. Change this value to 'on' or 'RemoteOnly' to show Error Handling
    "); + try + { + if (errUrl != null && errUrl.StartsWith("~")) + { + errUrl = VirtualPathUtility.ToAbsolute(errUrl); + } + } + finally + { + if (errUrl != null) + { + errorPageHtml.Write("
    The error handling would have shown this page : " + errUrl + "
    "); + } + else + { + errorPageHtml.Write("
    The error handling could not determine the correct page to show.
    "); + } + } + } + } + + string errorPageHtmlBody = errorPageHtml.ToString(); + if (errorPageHtmlBody.Length > 0) + { + response.Write(errorPageHtmlHeader); + response.Write(errorPageHtmlBody); + response.Write(errorPageHtmlFooter); + } + + if (ex != null) + { + UrlRewriterUtils.LogExceptionInRequest(ex, status, result); + } + } + } + + private static IPrincipal GetCurrentPrincipal(HttpContext context) + { + // Extract the forms authentication cookie + var authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; + var currentPrincipal = new GenericPrincipal(new GenericIdentity(string.Empty), new string[0]); + + try + { + if (authCookie != null) + { + var authTicket = FormsAuthentication.Decrypt(authCookie.Value); + if (authTicket != null && !authTicket.Expired) + { + var roles = authTicket.UserData.Split('|'); + var id = new FormsIdentity(authTicket); + currentPrincipal = new GenericPrincipal(id, roles); + } + } + } + catch (Exception) + { + // do nothing here. + } + + return currentPrincipal; + } + + private static bool CheckForDebug(HttpRequest request, NameValueCollection queryStringCol, bool debugEnabled) + { + string debugValue = string.Empty; + bool retVal = false; + + if (debugEnabled) + { + const string debugToken = "_aumdebug"; + if (queryStringCol != null && queryStringCol[debugToken] != null) + { + debugValue = queryStringCol[debugToken]; + } + else + { + if (request != null) + { + debugValue = request.Params.Get("HTTP_" + debugToken.ToUpper()); + } + + if (debugValue == null) + { + debugValue = "false"; + } + } + } + + switch (debugValue.ToLowerInvariant()) + { + case "true": + retVal = true; + break; + } + + return retVal; + } + + private static bool CheckForTabExternalForwardOrRedirect( + HttpContext context, + ref UrlAction result, + HttpResponse response, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + bool finished = false; + HttpRequest request = null; + if (context != null) + { + request = context.Request; + } + + try + { + // check for external forwarding or a permanent redirect request + // 592 : check for permanent redirect (823 : moved location from 'checkForRedirects') + if (result.TabId > -1 && result.PortalId > -1 && + (settings.ForwardExternalUrlsType != DNNPageForwardType.NoForward || + result.Reason == RedirectReason.Tab_Permanent_Redirect)) + { + bool allowRedirect = !(result.RewritePath != null && result.RewritePath.ToLowerInvariant().Contains("&ctl=tab")); + + // 594 : do not redirect settings pages for external urls + if (allowRedirect) + { + TabInfo tab; + allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings); + if (allowRedirect) + { + // 772 : not redirecting file type Urls when requested. + bool permanentRedirect = false; + string redirectUrl = null; + string cleanPath = null; + bool doRedirect = false; + switch (tab.TabType) + { + case TabType.File: + // have to fudge in a portal settings object for this to work - shortcoming of LinkClick URl generation + var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); + if (context != null) + { + context.Items.Add("PortalSettings", portalSettings); + result.Reason = RedirectReason.File_Url; + string fileUrl = Globals.LinkClick(tab.Url, tab.TabID, -1); + context.Items.Remove("PortalSettings"); + + // take back out again, because it will be done further downstream + // do a check to make sure we're not repeating the Url again, because the tabid is set but we don't want to touch + // a linkclick url + if (!result.OriginalPathNoAlias.EndsWith(HttpUtility.UrlDecode(fileUrl), true, CultureInfo.InvariantCulture)) + { + redirectUrl = fileUrl; + } + } + + if (redirectUrl != null) + { + doRedirect = true; + } + + break; + case TabType.Url: + result.Reason = RedirectReason.Tab_External_Url; + redirectUrl = tab.Url; + if (redirectUrl != null) + { + doRedirect = true; + if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) + { + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Tab_External_Url; + } + else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) + { + result.Action = ActionType.Redirect302; + result.Reason = RedirectReason.Tab_External_Url; + } + } + + break; + case TabType.Tab: + // if a tabType.tab is specified, it's either an external url or a permanent redirect + + // get the redirect path of the specific tab, as long as we have a valid request to work from + if (request != null) + { + // get the rewrite or requested path in a clean format, suitable for input to the friendly url provider + cleanPath = RewriteController.GetRewriteOrRequestedPath(result, request.Url); + + // 727 prevent redirectLoop with do301 in querystring + if (result.Action == ActionType.Redirect301 || + result.Action == ActionType.Redirect302) + { + cleanPath = RedirectTokens.RemoveAnyRedirectTokens( + cleanPath, + request.QueryString); + } + + // get the redirect Url from the friendly url provider using the tab, path and settings + redirectUrl = RedirectController.GetTabRedirectUrl(tab, settings, cleanPath, result, + out permanentRedirect, + parentTraceId); + } + + // check to make sure there isn't a blank redirect Url + if (redirectUrl == null) + { + // problem : no redirect Url to redirect to + // solution : cancel the redirect + string message = "Permanent Redirect chosen for Tab " + + tab.TabPath.Replace("//", "/") + + " but forwarding Url was not valid"; + RedirectController.CancelRedirect(ref result, context, settings, message); + } + else + { + // if there was a redirect Url, set the redirect action and set the type of redirect going to use + doRedirect = true; + if (permanentRedirect) + { + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Tab_Permanent_Redirect; + + // should be already set, anyway + result.RewritePath = cleanPath; + } + else + { + // not a permanent redirect, check if the page forwarding is set + if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) + { + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Tab_External_Url; + } + else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) + { + result.Action = ActionType.Redirect302; + result.Reason = RedirectReason.Tab_External_Url; + } + } + } + + break; + default: + // only concern here is if permanent redirect is requested, but there is no external url specified + if (result.Reason == RedirectReason.Tab_Permanent_Redirect) + { + bool permRedirect = tab.PermanentRedirect; + if (permRedirect) + { + // problem : permanent redirect marked, but no forwarding url supplied + // solution : cancel redirect + string message = "Permanent Redirect chosen for Tab " + + tab.TabPath.Replace("//", "/") + + " but no forwarding Url Supplied"; + RedirectController.CancelRedirect(ref result, context, settings, message); + } + } + + break; + } + + // do the redirect we have specified + if (doRedirect && + (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302)) + { + result.FinalUrl = redirectUrl; + if (result.Action == ActionType.Redirect301) + { + if (response != null) + { + // perform a 301 redirect to the external url of the tab + response.AppendHeader( + "X-Redirect-Reason", + result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl); + } + } + else + { + if (result.Action == ActionType.Redirect302) + { + if (response != null) + { + // perform a 301 redirect to the external url of the tab + response.AppendHeader( + "X-Redirect-Reason", + result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl); + } + } + } + + finished = true; + } + } + } + } + } + catch (ThreadAbortException) + { + // do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest + // level try/catch block, so we handle it here. + } + + return finished; + } + + private bool CheckForSecureRedirect( + PortalSettings portalSettings, + Uri requestUri, + UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings) + { + bool redirectSecure = false; + string url = requestUri.ToString(); + + // 889 : don't run secure redirect code for physical resources or requests that aren't a rewritten Url + if (result.IsPhysicalResource == false && result.TabId >= 0) + + // no secure redirection for physical resources, only tab-specific requests can be redirected for ssl connections + { + if (portalSettings.ActiveTab != null) + { + result.DebugMessages.Add("ActiveTab: " + portalSettings.ActiveTab.TabID.ToString() + "/" + + portalSettings.ActiveTab.TabName + " IsSecure: " + + portalSettings.ActiveTab.IsSecure.ToString()); + + // check ssl enabled + if (portalSettings.SSLEnabled) + { + // 717 : check page is secure, connection is not secure + // 952 : support SSl Offloading in DNN 6.2+ + if (portalSettings.ActiveTab.IsSecure && !result.IsSecureConnection && !result.IsSSLOffloaded) + { + redirectSecure = true; + string stdUrl = portalSettings.STDURL; + string sslUrl = portalSettings.SSLURL; + if (string.IsNullOrEmpty(result.HttpAlias) == false) + { + stdUrl = result.HttpAlias; + } + + url = url.Replace("http://", "https://"); + url = this.ReplaceDomainName(url, stdUrl, sslUrl); + } + } + + // check ssl enforced + if (portalSettings.SSLEnforced) + { + // Prevent browser's mixed-content error in case we open a secure PopUp or a secure iframe + // from an unsecure page + if (!portalSettings.ActiveTab.IsSecure && + result.IsSecureConnection && + !UrlUtils.IsPopUp(url)) + { + // has connection already been forced to secure? + if (queryStringCol["ssl"] == null) + { + // no? well this page shouldn't be secure + string stdUrl = portalSettings.STDURL; + string sslUrl = portalSettings.SSLURL; + url = url.Replace("https://", "http://"); + url = this.ReplaceDomainName(url, sslUrl, stdUrl); + redirectSecure = true; + } + } + } + } + + if (redirectSecure) + { + // now check to see if excluded. Why now? because less requests are made to redirect secure, + // so we don't have to check the exclusion as often. + bool exclude = false; + string doNotRedirectSecureRegex = settings.DoNotRedirectSecureRegex; + if (!string.IsNullOrEmpty(doNotRedirectSecureRegex)) + { + // match the raw url + exclude = Regex.IsMatch(result.RawUrl, doNotRedirectSecureRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + + if (!exclude) + { + result.Action = ActionType.Redirect302Now; + result.Reason = RedirectReason.Secure_Page_Requested; + + // 760 : get the culture specific home page tabid for a redirect comparison + int homePageTabId = portalSettings.HomeTabId; + homePageTabId = TabPathHelper.GetHomePageTabIdForCulture( + portalSettings.DefaultLanguage, + portalSettings.PortalId, + result.CultureCode, homePageTabId); + if (result.TabId == homePageTabId) + { + // replace the /default.aspx in the Url if it was found + url = DefaultPageRegex.Replace(url, "/"); + } + + result.FinalUrl = url; + } + else + { + // 702 : change return value if exclusion has occured + redirectSecure = false; + } + } + } + + return redirectSecure; + } + + private string ReplaceDomainName(string url, string replaceDomain, string withDomain) + { + if (replaceDomain != string.Empty && withDomain != string.Empty) + { + // 951 : change find/replace routine to regex for more accurate replacement + // (previous method gives false positives if the SSL Url is contained within the STD url) + string find = @"(?<=https?://)" + Regex.Escape(withDomain); + if (Regex.IsMatch(url, find, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) == false) + { + string replaceFind = @"(?<=https?://)" + Regex.Escape(replaceDomain); + url = Regex.Replace(url, replaceFind, withDomain, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + } + + return url; + } + + protected bool IsPortalAliasIncorrect( + HttpContext context, + HttpRequest request, + Uri requestUri, + UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + Guid parentTraceId, + out string httpAlias) + { + // now check to make sure it's the primary portal alias for this portal/language/browser + bool incorrectAlias = false; + httpAlias = null; + + // if (result.RedirectAllowed && result.PortalId > -1) + if (result.PortalId > -1) // portal has been identified + { + var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + + if (queryStringCol != null && queryStringCol["forceAlias"] != "true") + { + if (portalAliases.Count > 0) + { + string checkAlias = result.HttpAlias; + bool continueLoop = true; + bool triedWWW = false; + while (httpAlias == null && continueLoop) + { + if (portalAliases.ContainsAlias(result.PortalId, checkAlias)) + { + if (portalAliases.Count > 0) + { + // var cpa = portalAliases.GetAliasByPortalIdAndSettings(result); + string url = requestUri.ToString(); + RewriteController.CheckLanguageMatch(ref url, result); + var cpa = portalAliases + .Where(a => a.IsPrimary || result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) + .GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, result.BrowserType); + + if (cpa != null) + { + httpAlias = cpa.HTTPAlias; + continueLoop = false; + } + + if (string.IsNullOrEmpty(result.CultureCode) && cpa == null) + { + // if there is a specific culture for this portal alias, then check that + string culture = portalAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); + + // if this matches the alias of the request, then we know we have the correct alias because it is a specific culture + if (!string.IsNullOrEmpty(culture)) + { + continueLoop = false; + } + } + } + } + + // check whether to still go on or not + if (continueLoop) + { + // this alias doesn't exist in the list + // check if it has a www on it - if not, try adding, if it does, try removing + if (!triedWWW) + { + triedWWW = true; // now tried adding/removing www + if (checkAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) + { + checkAlias = checkAlias.Substring(4); + } + else + { + checkAlias = "www." + checkAlias; + } + } + else + { + // last thing to try, get the default language and see if there is a portal alias for that + // thus, any aliases not identified as belonging to a language are redirected back to the + // alias named for the default language + continueLoop = false; + + // 735 : switch to custom method for getting portal + PortalInfo pi = CacheController.GetPortal(result.PortalId, false); + if (pi != null) + { + string cultureCode = pi.DefaultLanguage; + if (!string.IsNullOrEmpty(cultureCode)) + { + var primaryPortalAlias = portalAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, cultureCode, settings); + if (primaryPortalAlias != null) + { + httpAlias = primaryPortalAlias.HTTPAlias; + } + } + } + } + } + } + } + + // check to see if it is a custom tab alais - in that case, it is allowed to be requested for the tab + if (CheckIfAliasIsCustomTabAlias(ref result, httpAlias, settings)) + { + // change the primary alias to the custom tab alias that has been requested. + result.PrimaryAlias = result.PortalAlias; + } + else + if (httpAlias != null && string.Compare(httpAlias, result.HttpAlias, StringComparison.OrdinalIgnoreCase) != 0) + { + incorrectAlias = true; + } + } + } + + return incorrectAlias; + } + + /// + /// Redirects an alias if that is allowed by the settings. + /// + /// + /// + /// + /// + private static bool RedirectPortalAlias(string httpAlias, ref UrlAction result, FriendlyUrlSettings settings) + { + bool redirected = false; + + // redirect to primary alias + if (result.PortalAliasMapping == PortalSettings.PortalAliasMapping.Redirect && result.RedirectAllowed) + { + if (result.Reason == RedirectReason.Wrong_Portal_Alias_For_Browser_Type || result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture || + result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) + { + redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, result.Reason, settings.InternalAliasList, settings); + } + else + { + redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, settings.InternalAliasList, settings); + } + } + + return redirected; + } + + private static bool ConfigurePortalAliasRedirect( + ref UrlAction result, + string wrongAlias, + string rightAlias, + bool ignoreCustomAliasTabs, + List internalAliases, + FriendlyUrlSettings settings) + { + return ConfigurePortalAliasRedirect( + ref result, + wrongAlias, + rightAlias, + ignoreCustomAliasTabs, + RedirectReason.Wrong_Portal_Alias, + internalAliases, + settings); + } + + /// + /// Checks to see whether the specified alias is a customTabAlias. + /// + /// + /// + /// + /// + private static bool CheckIfAliasIsCustomTabAlias(ref UrlAction result, string httpAlias, FriendlyUrlSettings settings) + { + List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); + bool isACustomTabAlias = false; + if (customAliasesForTabs != null && customAliasesForTabs.Count > 0) + { + // remove any customAliases that are also primary aliases. + foreach (var cpa in PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId)) + { + if (cpa.IsPrimary == true && customAliasesForTabs.Contains(cpa.HTTPAlias)) + { + customAliasesForTabs.Remove(cpa.HTTPAlias); + } + } + + isACustomTabAlias = customAliasesForTabs.Contains(httpAlias.ToLowerInvariant()); + } + + return isACustomTabAlias; + } + + /// + /// Checks to see whether the specified alias is a customTabAlias for the TabId in result + /// + /// + /// + /// + /// + private static bool CheckIfAliasIsCurrentTabCustomTabAlias(ref UrlAction result, FriendlyUrlSettings settings) + { + var customAliasesForTab = TabController.Instance.GetCustomAliases(result.TabId, result.PortalId); + bool isCurrentTabCustomTabAlias = false; + if (customAliasesForTab != null && customAliasesForTab.Count > 0) + { + //see if we have a customAlias for the current CultureCode + if (customAliasesForTab.ContainsKey(result.CultureCode)) + { + //if it is for the current culture, we need to know if it's a primary alias + var tabPortalAlias = PortalAliasController.Instance.GetPortalAlias(customAliasesForTab[result.CultureCode]); + if (tabPortalAlias != null && !tabPortalAlias.IsPrimary) + { + // it's not a primary alias, so must be a custom tab alias + isCurrentTabCustomTabAlias = true; + } + } + } + // if it's not a custom alias for the current tab, we'll need to change the result + if (!isCurrentTabCustomTabAlias) + { + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Wrong_Portal_Alias; + } + return isCurrentTabCustomTabAlias; + } + /// + /// Configures the result object to set the correct Alias redirect + /// parameters and destination URL. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private static bool ConfigurePortalAliasRedirect( + ref UrlAction result, + string wrongAlias, + string rightAlias, + bool ignoreCustomAliasTabs, + RedirectReason redirectReason, + List internalAliases, + FriendlyUrlSettings settings) + { + // wrong alias for the portal + // check to see if the wrong portal alias could be a custom alias for a tab + bool doRedirect; + if (ignoreCustomAliasTabs == false) // check out custom alias tabs collection + { + // if an alias is a custom tab alias for a specific tab, then don't redirect + // if we have the TabId, we'll need to check if the alias is valid for the current tab + if (result.TabId > 0 && CheckIfAliasIsCurrentTabCustomTabAlias(ref result, settings)) + { + doRedirect = false; + } + else if (result.TabId < 0 && CheckIfAliasIsCustomTabAlias(ref result, wrongAlias, settings)) + { + doRedirect = false; + } + else + { + doRedirect = true; + } + } + else + { + doRedirect = true; // do redirect, ignore custom alias entries for tabs + } + + // check to see if it is an internal alias. These are used to block redirects + // to allow for reverse proxy requests, which must change the rewritten alias + // while leaving the requested alias + bool internalAliasFound = false; + if (doRedirect && internalAliases != null && internalAliases.Count > 0) + { + if (internalAliases.Any(ia => string.Compare(ia.HttpAlias, wrongAlias, StringComparison.OrdinalIgnoreCase) == 0)) + { + internalAliasFound = true; + doRedirect = false; + } + } + + // if still need to do redirect, then set the settings that will cause the redirect (redirect not done here) + if (doRedirect) + { + result.Action = ActionType.Redirect301; + result.Reason = redirectReason; + var destUrl = result.OriginalPath; + if (result.OriginalPath.Contains(wrongAlias)) + { + destUrl = result.OriginalPath.Replace(wrongAlias, rightAlias); + } + else if (result.OriginalPath.ToLowerInvariant().Contains(wrongAlias)) + { + destUrl = result.OriginalPath.ToLowerInvariant().Replace(wrongAlias, rightAlias); + } + + if (redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture || + redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) + { + destUrl = destUrl.Replace("/language/" + result.CultureCode, string.Empty); + } + + destUrl = CheckForSiteRootRedirect(rightAlias, destUrl); + result.FinalUrl = destUrl; + } + else + { + // 838 : don't overwrite the reason if already have checkfor301 + // and don't do a check on the basis that an internal alias was found + if (result.Action != ActionType.CheckFor301 && internalAliasFound == false) + { + // set status to 'check for redirect' + result.Action = ActionType.CheckFor301; + result.Reason = RedirectReason.Custom_Tab_Alias; + } + } + + return doRedirect; + } + + private void IdentifyPortalAlias( + HttpContext context, + HttpRequest request, + Uri requestUri, UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + // get the domain name of the request, if it isn't already supplied + if (request != null && string.IsNullOrEmpty(result.DomainName)) + { + result.DomainName = Globals.GetDomainName(request); // parse the domain name out of the request + } + + // get tabId from querystring ( this is mandatory for maintaining portal context for child portals ) + if (queryStringCol["tabid"] != null) + { + string raw = queryStringCol["tabid"]; + int tabId; + if (int.TryParse(raw, out tabId)) + { + result.TabId = tabId; + } + else + { + // couldn't parse tab id + // split in two? + string[] tabids = raw.Split(','); + if (tabids.GetUpperBound(0) > 0) + { + // hmm more than one tabid + if (int.TryParse(tabids[0], out tabId)) + { + result.TabId = tabId; + + // but we want to warn against this! + var ex = + new Exception( + "Illegal request exception : Two TabId parameters provided in a single request: " + + requestUri); + UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); + + result.Ex = ex; + } + else + { + // yeah, nothing, divert to 404 + result.Action = ActionType.Output404; + var ex = + new Exception( + "Illegal request exception : TabId parameters in query string, but invalid TabId requested : " + + requestUri); + UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); + result.Ex = ex; + } + } + } + } + + // get PortalId from querystring ( this is used for host menu options as well as child portal navigation ) + if (queryStringCol["portalid"] != null) + { + string raw = queryStringCol["portalid"]; + int portalId; + if (int.TryParse(raw, out portalId)) + { + // 848 : if portal already found is different to portal id in querystring, then load up different alias + // this is so the portal settings will be loaded correctly. + if (result.PortalId != portalId) + { + // portal id different to what we expected + result.PortalId = portalId; + + // check the loaded portal alias, because it might be wrong + if (result.PortalAlias != null && result.PortalAlias.PortalID != portalId) + { + // yes, the identified portal alias is wrong. Find the correct alias for this portal + PortalAliasInfo pa = TabIndexController.GetPortalAliasByPortal(portalId, result.DomainName); + if (pa != null) + { + // note: sets portal id and portal alias + result.PortalAlias = pa; + } + } + } + } + } + else + { + // check for a portal alias if there's no portal Id in the query string + // check for absence of captcha value, because the captcha string re-uses the alias querystring value + if (queryStringCol["alias"] != null && queryStringCol["captcha"] == null) + { + string alias = queryStringCol["alias"]; + PortalAliasInfo portalAlias = PortalAliasController.Instance.GetPortalAlias(alias); + if (portalAlias != null) + { + // ok the portal alias was found by the alias name + // check if the alias contains the domain name + if (alias.Contains(result.DomainName) == false) + { + // replaced to the domain defined in the alias + if (request != null) + { + string redirectDomain = Globals.GetPortalDomainName(alias, request, true); + + // retVal.Url = redirectDomain; + result.FinalUrl = redirectDomain; + result.Action = ActionType.Redirect302Now; + result.Reason = RedirectReason.Alias_In_Url; + } + } + else + { + // the alias is the same as the current domain + result.HttpAlias = portalAlias.HTTPAlias; + result.PortalAlias = portalAlias; + result.PortalId = portalAlias.PortalID; + + // don't use this crap though - we don't want ?alias=portalAlias in our Url + if (result.RedirectAllowed) + { + string redirect = requestUri.Scheme + Uri.SchemeDelimiter + result.PortalAlias.HTTPAlias + + "/"; + result.Action = ActionType.Redirect301; + result.FinalUrl = redirect; + result.Reason = RedirectReason.Unfriendly_Url_Child_Portal; + } + } + } + } + } + + // first try and identify the portal using the tabId, but only if we identified this tab by looking up the tabid + // from the original url + // 668 : error in child portal redirects to child portal home page because of mismatch in tab/domain name + if (result.TabId != -1 && result.FriendlyRewrite == false) + { + // get the alias from the tabid, but only if it is for a tab in that domain + // 2.0 : change to compare retrieved alias to the already-set httpAlias + string httpAliasFromTab = PortalAliasController.GetPortalAliasByTab(result.TabId, result.DomainName); + if (httpAliasFromTab != null) + { + // 882 : account for situation when portalAlias is null. + if ((result.PortalAlias != null && string.Compare(result.PortalAlias.HTTPAlias, httpAliasFromTab, StringComparison.OrdinalIgnoreCase) != 0) + || result.PortalAlias == null) + { + // 691 : change logic to force change in portal alias context rather than force back. + // This is because the tabid in the query string should take precedence over the portal alias + // to handle parent.com/default.aspx?tabid=xx where xx lives in parent.com/child/ + var tab = TabController.Instance.GetTab(result.TabId, Null.NullInteger, false); + + // when result alias is null or result alias is different from tab-identified portalAlias + if (tab != null && (result.PortalAlias == null || tab.PortalID != result.PortalAlias.PortalID)) + { + // the tabid is different to the identified portalid from the original alias identified + // so get a new alias + PortalAliasInfo tabPortalAlias = PortalAliasController.Instance.GetPortalAlias(httpAliasFromTab, tab.PortalID); + if (tabPortalAlias != null) + { + result.PortalId = tabPortalAlias.PortalID; + result.PortalAlias = tabPortalAlias; + result.Action = ActionType.CheckFor301; + result.Reason = RedirectReason.Wrong_Portal; + } + } + } + } + } + + // if no alias, try and set by using the identified http alias or domain name + if (result.PortalAlias == null) + { + if (!string.IsNullOrEmpty(result.HttpAlias)) + { + result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias); + } + else + { + result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); + if (result.PortalAlias == null && result.DomainName.EndsWith("/")) + { + result.DomainName = result.DomainName.TrimEnd('/'); + result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); + } + } + } + + if (result.PortalId == -1) + { + if (!requestUri.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + { + // allows requests for aspx pages in custom folder locations to be processed + return; + } + + // the domain name was not found so try using the host portal's first alias + if (Host.HostPortalID != -1) + { + result.PortalId = Host.HostPortalID; + + // use the host portal, but replaced to the host portal home page + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (aliases.Count > 0) + { + string alias = null; + + // get the alias as the chosen portal alias for the host portal based on the result culture code + var cpa = aliases.GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, settings); + if (cpa != null) + { + alias = cpa.HTTPAlias; + } + + if (alias != null) + { + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Host_Portal_Used; + string destUrl = MakeUrlWithAlias(requestUri, alias); + destUrl = CheckForSiteRootRedirect(alias, destUrl); + result.FinalUrl = destUrl; + } + else + { + // Get the first Alias for the host portal + result.PortalAlias = aliases[result.PortalId]; + string url = MakeUrlWithAlias(requestUri, result.PortalAlias); + if (result.TabId != -1) + { + url += requestUri.Query; + } + + result.FinalUrl = url; + result.Reason = RedirectReason.Host_Portal_Used; + result.Action = ActionType.Redirect302Now; + } + } + } + } + + // double check to make sure we still have the correct alias now that all other information is known (ie tab, portal, culture) + // 770 : redirect alias based on tab id when custom alias used + if (result.TabId == -1 && result.Action == ActionType.CheckFor301 && + result.Reason == RedirectReason.Custom_Tab_Alias) + { + // here because the portal alias matched, but no tab was found, and because there are custom tab aliases used for this portal + // need to redirect back to the chosen portal alias and keep the current path. + string wrongAlias = result.HttpAlias; // it's a valid alias, but only for certain tabs + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (primaryAliases != null && result.PortalId > -1) + { + // going to look for the correct alias based on the culture of the request + string requestCultureCode = result.CultureCode; + + // if that didn't work use the default language of the portal + if (requestCultureCode == null) + { + // this might end up in a double redirect if the path of the Url is for a specific language as opposed + // to a path belonging to the default language domain + PortalInfo portal = PortalController.Instance.GetPortal(result.PortalId); + if (portal != null) + { + requestCultureCode = portal.DefaultLanguage; + } + } + + // now that the culture code is known, look up the correct portal alias for this portalid/culture code + var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, requestCultureCode, settings); + if (cpa != null) + { + // if an alias was found that matches the request and the culture code, then run with that + string rightAlias = cpa.HTTPAlias; + + // will cause a redirect to the primary portal alias - we know now that there was no custom alias tab + // found, so it's just a plain wrong alias + ConfigurePortalAliasRedirect(ref result, wrongAlias, rightAlias, true, + settings.InternalAliasList, settings); + } + } + } + else + { + // then check to make sure it's the chosen portal alias for this portal + // 627 : don't do it if we're redirecting to the host portal + if (result.RedirectAllowed && result.Reason != RedirectReason.Host_Portal_Used) + { + string primaryAlias; + + // checking again in case the rewriting operation changed the values for the valid portal alias + bool incorrectAlias = this.IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryAlias); + if (incorrectAlias) + { + RedirectPortalAlias(primaryAlias, ref result, settings); + } + } + } + + // check to see if we have to avoid the core 302 redirect for the portal alias that is in the /defualt.aspx + // for child portals + // exception to that is when a custom alias is used but no rewrite has taken place + if (result.DoRewrite == false && (result.Action == ActionType.Continue + || + (result.Action == ActionType.CheckFor301 && + result.Reason == RedirectReason.Custom_Tab_Alias))) + { + string aliasQuerystring; + bool isChildAliasRootUrl = CheckForChildPortalRootUrl(requestUri.AbsoluteUri, result, out aliasQuerystring); + if (isChildAliasRootUrl) + { + RewriteAsChildAliasRoot(context, result, aliasQuerystring, settings); + } + } + } + + internal static void RewriteAsChildAliasRoot( + HttpContext context, + UrlAction result, + string aliasQueryString, + FriendlyUrlSettings settings) + { + string culture = null; + + // look for specific alias to rewrite language parameter + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (result.PortalId > -1 && result.HttpAlias != null) + { + culture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); + } + + if (string.IsNullOrEmpty(culture)) + + // 732 : when no culture returned can be "" as well as null : no culture causes no rewrite, which results in redirect to parent alias + { + // set the default culture code here + // 735 : switch to custom method for getting portal + PortalInfo pi = CacheController.GetPortal(result.PortalId, false); + if (pi != null) + { + culture = pi.DefaultLanguage; + } + } + + if (!string.IsNullOrEmpty(culture)) // a culture was identified for the alias root + { + if (RewriteController.AddLanguageCodeToRewritePath(ref aliasQueryString, culture)) + { + result.CultureCode = culture; + } + + result.DoRewrite = true; + result.RewritePath = "~/" + Globals.glbDefaultPage + aliasQueryString; + + // the expected /default.aspx path (defaultPageUrl) matches the requested Url (/default.aspx) + if (context != null) + { + // only do if not testing + RewriterUtils.RewriteUrl(context, result.RewritePath); + } + } + } + + internal static bool CheckForChildPortalRootUrl(string requestUrl, UrlAction result, out string aliasQueryString) + { + bool isChildPortalRootUrl = false; + + // what we are going to test for here is that if this is a child portal request, for the /default.aspx of the child portal + // then we are going to avoid the core 302 redirect to ?alias=portalALias by rewriting to the /default.aspx of the site root + // 684 : don't convert querystring items to lower case + // do the check by constructing what a child alias url would look like and compare it with the requested urls + // 912 : when requested without a valid portal alias, portalALias is null. Refuse and return false. + aliasQueryString = null; + if (result.PortalAlias != null && result.PortalAlias.HTTPAlias != null) + { + string defaultPageUrl = result.Scheme + result.PortalAlias.HTTPAlias + "/" + + Globals.glbDefaultPage.ToLowerInvariant(); // child alias Url with /default.aspx + + // 660 : look for a querystring on the site root for a child portal, and handle it if so + if (string.CompareOrdinal(requestUrl.ToLowerInvariant(), defaultPageUrl) == 0) + { + // exact match : that's the alias root + isChildPortalRootUrl = true; + aliasQueryString = string.Empty; + } + + if (!isChildPortalRootUrl && requestUrl.Contains("?")) + { + // is we didn't get an exact match but there is a querystring, then investigate + string[] requestUrlParts = requestUrl.Split('?'); + if (requestUrlParts.GetUpperBound(0) > 0) + { + string rootPart = requestUrlParts[0]; + string queryString = requestUrlParts[1]; + if (string.Compare(rootPart, defaultPageUrl, StringComparison.OrdinalIgnoreCase) == 0) + { + // rewrite, but put in the querystring on the rewrite path + isChildPortalRootUrl = true; + aliasQueryString = "?" + queryString; + + // 674: check for 301 if this value is a tabid/xx - otherwise the url will just evaluate as is + if (queryString.ToLowerInvariant().StartsWith("tabid=")) + { + result.Action = ActionType.CheckFor301; + } + } + } + } + } + + return isChildPortalRootUrl; + } + + private static string MakeUrlWithAlias(Uri requestUri, string httpAlias) + { + return requestUri.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) + ? "https://" + httpAlias.Replace("*.", string.Empty) + "/" + : "http://" + httpAlias.Replace("*.", string.Empty) + "/"; + } + + private static string MakeUrlWithAlias(Uri requestUri, PortalAliasInfo alias) + { + return MakeUrlWithAlias(requestUri, alias.HTTPAlias); + } + + /// + /// Determines if this is a request from an install / upgrade url. + /// + /// + /// + /// + /// + /// + /// + /// //875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1. + /// + private static bool IgnoreRequestForInstall(string physicalPath, string refererPath, string requestedDomain, string refererDomain) + { + if (physicalPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) + || physicalPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) + || physicalPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture) + || Globals.Status == Globals.UpgradeStatus.Install + || Globals.Status == Globals.UpgradeStatus.Upgrade) + { + return true; + } + + // 954 : DNN 7.0 compatibility + // check for /default.aspx which is default Url launched from the Upgrade/Install wizard page + // 961 : check domain as well as path for the referer + if (physicalPath.EndsWith(Globals.glbDefaultPage, true, CultureInfo.InvariantCulture) == false + && refererPath != null + && string.Compare(requestedDomain, refererDomain, StringComparison.OrdinalIgnoreCase) == 0 + && (refererPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) + || refererPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) + || refererPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture))) + { + return true; + } + + return false; + } + + private static bool IgnoreRequestForWebServer(string requestedPath) + { + // Should standardize comparison methods + if (requestedPath.IndexOf("synchronizecache.aspx", StringComparison.OrdinalIgnoreCase) > 1 + || requestedPath.EndsWith("keepalive.aspx", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + // Get the root + var rootPath = requestedPath.Substring(0, requestedPath.LastIndexOf("/", StringComparison.Ordinal)); + rootPath = rootPath.Substring(rootPath.IndexOf("://", StringComparison.Ordinal) + 3); + + // Check if this is a WebServer and not a portalalias. + // if can auto add portal alias enabled, then return false, alias will add later. + var alias = PortalAliasController.Instance.GetPortalAlias(rootPath); + if (alias != null || CanAutoAddPortalAlias()) + { + return false; + } + + // Check if this is a WebServer + var server = ServerController.GetEnabledServers().SingleOrDefault(s => s.Url == rootPath); + if (server != null) + { + return true; + } + + return false; + } + + private static bool IgnoreRequestForInstall(HttpRequest request) + { + try + { + string physicalPath = request.PhysicalPath; + string requestedDomain = request.Url.Host; + string refererPath = null, refererDomain = null; + if (request.UrlReferrer != null) + { + refererDomain = request.UrlReferrer.Host; + refererPath = request.UrlReferrer.LocalPath; + } + + return IgnoreRequestForInstall(physicalPath, refererPath, requestedDomain, refererDomain); + } + catch (PathTooLongException) + { + // catch and handle this exception, caused by an excessively long file path based on the + // mapped virtual url + return false; + } + catch (ArgumentException) + { + // catch and handle this exception, caused by an invalid character in the file path based on the + // mapped virtual url + return false; + } + } + + private static bool IgnoreRequest(UrlAction result, string requestedPath, string ignoreRegex, HttpRequest request) + { + bool retVal = false; + + // check if we are upgrading/installing + // 829 : use result physical path instead of requset physical path + // 875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1 + if (request != null && (IgnoreRequestForInstall(request) || IgnoreRequestForWebServer(requestedPath))) + { + // ignore all install requests + retVal = true; + } + else if (request != null && request.Path.EndsWith("imagechallenge.captcha.aspx", StringComparison.InvariantCultureIgnoreCase)) + { + retVal = true; + } + else + { + try + { + if (ignoreRegex.Length > 0) + { + if (Regex.IsMatch(requestedPath, ignoreRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + { + retVal = true; + } + } + } + catch (Exception ex) + { + UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); + result.Ex = ex; + } + } + + return retVal; + } + + private static void CheckForRewrite( + string fullUrl, + string querystring, + UrlAction result, + bool useFriendlyUrls, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + out bool isPhysicalResource, + Guid parentTraceId) + { + bool checkForRewrites; + + // just check to make sure it isn't a physical resource on the server + RewriteController.IdentifyByPhysicalResource( + result.PhysicalPath, + fullUrl, + queryStringCol, + ref result, + useFriendlyUrls, + settings, + out isPhysicalResource, + out checkForRewrites, + parentTraceId); + + if (checkForRewrites && RewriteController.CanRewriteRequest(result, fullUrl, settings)) + { + bool doSiteUrlProcessing = false; + + // 728 new regex expression to pass values straight onto the siteurls.config file + if (!string.IsNullOrEmpty(settings.UseSiteUrlsRegex)) + { + doSiteUrlProcessing = Regex.IsMatch(fullUrl, settings.UseSiteUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + + if (!doSiteUrlProcessing) + + // if a virtual request, and not starting with the siteUrls.config file, go on to find the rewritten path + { + // looks up the page index to find the correct Url + bool doRewrite = RewriteController.IdentifyByTabPathEx(fullUrl, querystring, result, queryStringCol, settings, parentTraceId); + if (!doRewrite) + { + doSiteUrlProcessing = true; + } + } + + if (doSiteUrlProcessing) + { + // 728 : compare requests against the siteurls.config file, either if no other match was found, or if we want to skip the rest of the processing + // the standard DNN way of rewriting, using expressions found in the siteurls.config file + RewriteController.IdentifyByRegEx(fullUrl, querystring, result.ApplicationPath, ref result, settings, parentTraceId); + } + } + } + + private void SecurityCheck(HttpApplication app) + { + HttpRequest request = app.Request; + HttpServerUtility server = app.Server; + + // 675 : unnecessarily strict url validation + // URL validation + // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server + // the application should always use the exact relative location of the resource it is requesting + var strURL = request.Url.AbsolutePath; + var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.Url.AbsolutePath)) ?? string.Empty; + if (UrlSlashesRegex.Match(strURL).Success || UrlSlashesRegex.Match(strDoubleDecodeURL).Success) + { + throw new HttpException(404, "Not Found"); + } + } + + private static bool CheckForRedirects( + Uri requestUri, + string fullUrl, + NameValueCollection queryStringCol, + UrlAction result, + string requestType, + FriendlyUrlSettings settings, + int portalHomeTabId) + { + bool redirected = false; + if (queryStringCol["error"] == null && queryStringCol["message"] == null && requestType != "POST") + { + // if the / is missing from an extension-less request, then check for a 301 redirect + if (settings.PageExtensionUsageType == PageExtensionUsageType.Never) + { + // 575 check on absolutePath instead of absoluteUri : this ignores query strings and fragments like # + // 610 don't always end with '/' - reverses previous setting + // 687 don't double-check 301 redirects. 'CheckFor301' is less concise than 'Redirect301' + // DNN-21906: if the redirect is for splash page, then we should continue the 302 redirect. + if (requestUri.AbsolutePath.EndsWith("/") && result.Action != ActionType.Redirect301 && result.Reason != RedirectReason.Requested_SplashPage) + { + result.Action = ActionType.CheckFor301; + } + } + + if (settings.RedirectWrongCase && result.Action == ActionType.Continue) + { + result.Action = ActionType.CheckFor301; + } + + string scheme = requestUri.Scheme + Uri.SchemeDelimiter; + bool queryStringHas301Parm = queryStringCol["do301"] != null; + + // 727 : keep a bool value if there is a do301 request in the querystring + // check for a 301 request in the query string, or an explicit 301 or 302 request + // 2.0 - check for explicit do301=true instead of just do301 key + string do301Val = queryStringCol["do301"]; + if (result.TabId > -1 // valid tab + && (result.Action == ActionType.Redirect301 // specific 301 redirect + || (do301Val != null && do301Val == "true") // or rewrite hint for specific 301 redirect + || result.Action == ActionType.Redirect302)) // or specific 302 redirect + { + // we have ordered a 301 redirect earlier in the code + // get the url for redirection by re-submitting the path into the Friendly Url Provider + string pathOnly = RewriteController.GetRewriteOrRequestedPath(result, requestUri); + + // 727 prevent redirectLoop with do301 in querystring + if (result.Action == ActionType.Redirect301 || queryStringHas301Parm || result.Action == ActionType.Redirect302) + { + pathOnly = RedirectTokens.RemoveAnyRedirectTokens(pathOnly, queryStringCol); + } + + // check for exclusion by regex for this url + if (result.RedirectAllowed) + { + // get the tab so we know where to go + TabInfo tab; + bool checkRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); + + if (checkRedirect) + { + if ((result.Reason == RedirectReason.Deleted_Page || result.Reason == RedirectReason.Disabled_Page) + && portalHomeTabId > 0 + && settings.DeletedTabHandlingType == DeletedTabHandlingType.Do301RedirectToPortalHome) + { + // redirecting to home page + TabInfo homeTab = TabController.Instance.GetTab(portalHomeTabId, result.PortalId, false); + if (homeTab != null) + { + string homePageUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + homeTab, + pathOnly, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + Guid.Empty); + result.Action = ActionType.Redirect301; + result.FinalUrl = homePageUrl; + result.RewritePath = pathOnly; + redirected = true; + } + } + else + { + // get the rewrite or requested path in a clean format, suitable for input to the friendly url provider + string cleanPath = RewriteController.GetRewriteOrRequestedPath(result, requestUri); + + // 727 prevent redirectLoop with do301 in querystring + // also check for existing in path of do301 token + if (result.Action == ActionType.Redirect301 || do301Val != null || result.Action == ActionType.Redirect302) + { + cleanPath = RedirectTokens.RemoveAnyRedirectTokens(cleanPath, queryStringCol); + } + + // get best friendly url from friendly url provider + string bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + cleanPath, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + Guid.Empty); + + // get what the friendly Url for this tab should be and stick it in as the redirect + // 727 : using boolean because we wanted to get rid of the do301 before calculating the correct url + if (queryStringHas301Parm) + { + result.Action = ActionType.Redirect301; + if (result.Reason == RedirectReason.Not_Redirected) + { + result.Reason = RedirectReason.Unfriendly_Url_1; + } + } + + result.FinalUrl = bestFriendlyUrl; + result.RewritePath = pathOnly; + redirected = true; // mark as redirected + } + } + else + { + // redirect disallowed + // 618: dont' clear if 302 redirect selected + if (result.Action != ActionType.Redirect302Now || result.Action != ActionType.Redirect302) + { + RedirectController.CancelRedirect(ref result, null, settings, "Redirect requested but cancelled because disallowed"); + } + } + } + } + else if (result.TabId > -1 && result.RedirectAllowed && result.Action == ActionType.CheckFor301) + { + // 301 check was requested in earlier processing + // get the tab controller and retrieve the tab the request is for + // don't redirect unless allowed, the tab is valid, and it's not an admin or super tab + if (settings.RedirectUnfriendly) + { + TabInfo tab; + bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); + if (allowRedirect && tab != null) + { + // remove the http alias from the url. Do this by putting the url back together from the request and removing the alias + string rewritePathOnly; + if (result.DoRewrite) + { + rewritePathOnly = result.RewritePath; + var pos = rewritePathOnly.IndexOf("default.aspx", StringComparison.OrdinalIgnoreCase); + if (pos > Null.NullInteger) + { + rewritePathOnly = rewritePathOnly.Substring(pos); + } + } + else + { + rewritePathOnly = requestUri.Host + requestUri.PathAndQuery; + } + + // remove the http alias from the path + var pathAliasEnd = rewritePathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase); + var queryStringIndex = rewritePathOnly.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); + if (pathAliasEnd > Null.NullInteger && (queryStringIndex == Null.NullInteger || pathAliasEnd < queryStringIndex)) + { + rewritePathOnly = rewritePathOnly.Substring(pathAliasEnd + result.PortalAlias.HTTPAlias.Length); + } + + // now check to see if need to remove /default.aspx from the end of the requested Url + string requestedUrl = fullUrl; + int requestedUrlAliasEnd = requestedUrl.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) + + (result.PortalAlias.HTTPAlias + "/").Length; + if (requestedUrlAliasEnd > Null.NullInteger) + { + // 818 : when a site root is used for a custom page Url, then check for max length within bounds + if ((requestedUrl.Length - requestedUrlAliasEnd) >= 12 && requestedUrl.Substring(requestedUrlAliasEnd).Equals("default.aspx", StringComparison.InvariantCultureIgnoreCase)) + { + requestedUrl = requestedUrl.Substring(0, requestedUrl.Length - 12); + + // 12 = default.aspx length + } + } + + // what happens here is that the request is reverse-engineered to see if it matches what the friendly Url shoudl have been + // get what the friendly Url for this tab should be + string bestFriendlyUrl; + + // 819 : leaving /do301/check in Url because not using cleanPath to remove from + string cleanPath = RedirectTokens.RemoveAnyRedirectTokensAndReasons(rewritePathOnly); + + // string cleanPath = rewritePathOnly.Replace("&do301=check","");//remove check parameter if it exists + // cleanPath = cleanPath.Replace("&do301=true", "");//don't pass through internal redirect check parameter + cleanPath = cleanPath.Replace("&_aumdebug=true", string.Empty); // remove debug parameter if it exists + + Match match = RewritePathRx.Match(rewritePathOnly ?? string.Empty); + if (match.Success) + { + // when the pathOnly value ends with '=' it means there is a query string pair with a key and no value + // make the assumption that this was passed in as a page name OTHER than default page + string pageName = match.Groups["parm"].Value; // get the last parameter in the list + + cleanPath = cleanPath.Replace(match.Value, string.Empty); + + // remove the last parameter from the path + + // generate teh friendly URl name with the last parameter as the page name, not a query string parameter + bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + cleanPath, + pageName + settings.PageExtension, + result.HttpAlias, + false, + settings, + Guid.Empty); + } + else + { + bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + cleanPath, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + Guid.Empty); + } + + // if the incoming request doesn't match the 'most friendly' url, a 301 Moved Permanently status is returned, along with the friendly url + // check the bestFriendlyUrl against either the url, or rawUrl (with and without host) + // in each case, the aumdebug parameter will be searched for and replaced + var urlDecode = HttpUtility.UrlDecode(requestedUrl); + if (urlDecode != null) + { + string rawUrlWithHost = StripDebugParameter(urlDecode.ToLowerInvariant()); + + // string rawUrlWithHost = StripDebugParameter(System.Web.HttpUtility.UrlDecode(scheme + requestUri.Host + requestUri.PathAndQuery).ToLowerInvariant()); + string rawUrlWithHostNoScheme = StripDebugParameter(rawUrlWithHost.Replace(scheme, string.Empty)); + string bestFriendlyNoScheme = StripDebugParameter(bestFriendlyUrl.ToLowerInvariant().Replace(scheme, string.Empty)); + string requestedPathNoScheme = StripDebugParameter(requestUri.AbsoluteUri.Replace(scheme, string.Empty).ToLowerInvariant()); + string rawUrlLowerCase = StripDebugParameter(requestUri.AbsoluteUri.ToLowerInvariant()); + + // check to see if just an alias redirect of an internal alias + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + + if (settings.InternalAliasList != null && settings.InternalAliasList.Count > 0 && primaryAliases.Count > 0) + { + var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result); + if (cpa != null) + { + string chosenAlias = cpa.HTTPAlias.ToLowerInvariant(); + foreach (InternalAlias ia in settings.InternalAliasList) + { + string internalAlias = ia.HttpAlias.ToLowerInvariant(); + if (requestedPathNoScheme.Contains(internalAlias)) + { + // an internal alias has been used. + // replace this in the comparison charts to do a 'fair' comparison + requestedPathNoScheme = requestedPathNoScheme.Replace(internalAlias, chosenAlias); + rawUrlWithHost = rawUrlWithHost.Replace(scheme + internalAlias, scheme + chosenAlias); + rawUrlWithHostNoScheme = rawUrlWithHostNoScheme.Replace(internalAlias, chosenAlias); + rawUrlLowerCase = rawUrlLowerCase.Replace(internalAlias, chosenAlias); + break; + } + } + } + } + + // DNN-9158: prevent SSL Offloading infinite redirects + if (!result.IsSecureConnection && result.IsSSLOffloaded && bestFriendlyNoScheme.StartsWith("https")) + { + bestFriendlyNoScheme = $"http://{bestFriendlyNoScheme.Substring(8)}"; + } + + if (!(bestFriendlyNoScheme == requestedPathNoScheme + || bestFriendlyNoScheme == rawUrlWithHost + || bestFriendlyNoScheme == rawUrlWithHostNoScheme + || bestFriendlyNoScheme == HttpUtility.UrlDecode(requestedPathNoScheme) + || HttpUtility.UrlDecode(bestFriendlyNoScheme) == HttpUtility.UrlDecode(requestedPathNoScheme) + || bestFriendlyNoScheme == rawUrlLowerCase)) + { + redirected = true; + result.Action = ActionType.Redirect301; + result.FinalUrl = bestFriendlyUrl; + if (result.Reason != RedirectReason.Custom_Tab_Alias && + result.Reason != RedirectReason.Deleted_Page && + result.Reason != RedirectReason.Disabled_Page) + { + result.Reason = RedirectReason.Unfriendly_Url_2; + } + + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + requestedPathNoScheme + " [requested with no scheme]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHost + " [requested with host and scheme]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHostNoScheme + " [requested with host, no scheme]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + HttpUtility.UrlDecode(requestedPathNoScheme) + " [requested and decoded]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlLowerCase + " [requested raw Url]"); + } + } + } + } + } + + if (result.RedirectAllowed && settings.RedirectWrongCase) + { + // check for redirects where a redirectToSubDomain is specified, + // redirect for Wrong case is specified, and there is a valid tab and it's not already redirected somewhere else + bool doRedirect = false; + string redirectPath = redirected ? result.FinalUrl : requestUri.AbsoluteUri; + string redirectPathOnly = redirectPath; + if (redirectPathOnly.Contains("?")) + { + redirectPathOnly = redirectPathOnly.Substring(0, redirectPathOnly.IndexOf("?", StringComparison.Ordinal)); + } + + // Thanks Etienne for the fix for Diacritic Characters Terminal Loop! + // if the url contains url encoded characters, they appear here uppercase -> %C3%83%C2 + // decode the url to get back the original character and do proper casing comparison + string urlDecodedRedirectPath = HttpUtility.UrlDecode(redirectPathOnly); + + // check for wrong case redirection + if (urlDecodedRedirectPath != null && (settings.RedirectWrongCase && string.CompareOrdinal(urlDecodedRedirectPath, urlDecodedRedirectPath.ToLowerInvariant()) != 0)) + { + TabInfo tab; + bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); + + if (allowRedirect && !string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) + { + // don't allow redirect if excluded from redirecting in the force lower case regex pattern (606) + allowRedirect = !Regex.IsMatch(redirectPath, settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + + if (allowRedirect) + { + // special case : when IIS automatically places /default.aspx on the end of the string, + // then don't try and redirect to the lower case /default.aspx, just let it through. + // we don't know whether IIS appended /Default.aspx on the end, however, we can guess + // if the redirectDefault.aspx is turned on (511) + if (settings.RedirectDefaultPage == false && redirectPathOnly.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + { + // ignore this, because it's just a redirect of the /Default.aspx to /default.aspx + } + else + { + redirectPath = redirectPath.Replace(redirectPathOnly, redirectPathOnly.ToLowerInvariant()); + doRedirect = true; + result.Reason = RedirectReason.Not_Lower_Case; + } + } + } + + if (doRedirect) + { + result.Action = ActionType.Redirect301; + result.FinalUrl = CheckForSiteRootRedirect(result.PortalAlias.HTTPAlias, redirectPath); + redirected = true; + } + } + } + + return redirected; + } + + private static string StripDebugParameter(string url) + { + return AumDebugRegex.Replace(url, string.Empty); + } + + private static bool CheckFor301RedirectExclusion(int tabId, int portalId, bool checkBaseUrls, out TabInfo tab, FriendlyUrlSettings settings) + { + bool doRedirect = false; + tab = TabController.Instance.GetTab(tabId, portalId, false); + + // don't redirect unless allowed, the tab is valid, and it's not an admin or super tab + if (tab != null && tab.IsSuperTab == false && !tab.DoNotRedirect) + { + if (checkBaseUrls) + { + // no redirect for friendly url purposes if the tab is in the 'base friendly urls' section + doRedirect = !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, true); + } + else + { + doRedirect = true; + } + } + + return doRedirect; + } + + /// + /// Make sure any redirect to the site root doesn't append the nasty /default.aspx on the end. + /// + /// + /// + /// + internal static string CheckForSiteRootRedirect(string alias, string destUrl) + { + // 540 - don't append /default.aspx onto the end of a site root redirect. + if (destUrl.EndsWith(alias + "/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + { + // this is just the portal alias root + /defualt.aspx. + // we don't want that, just the portalAliasRoot + "/" + string aliasPlusSlash = alias + "/"; + + // get everything up to the end of the portal alias + destUrl = destUrl.Substring(0, destUrl.IndexOf(aliasPlusSlash, StringComparison.Ordinal) + aliasPlusSlash.Length); + } + + return destUrl; + } + } +} diff --git a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs index d24447534f3..688693413a4 100644 --- a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs @@ -1,76 +1,78 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Text.RegularExpressions; -using System.Web; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + internal class BasicFriendlyUrlProvider : FriendlyUrlProviderBase { private const string RegexMatchExpression = "[^a-zA-Z0-9 ]"; + private static readonly Regex FriendlyPathRx = new Regex("(.[^\\\\?]*)\\\\?(.*)", RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex DefaultPageRx = new Regex(Globals.glbDefaultPage, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private readonly string _fileExtension; private readonly bool _includePageName; private readonly string _regexMatch; - private static readonly Regex FriendlyPathRx = new Regex("(.[^\\\\?]*)\\\\?(.*)", RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex DefaultPageRx = new Regex(Globals.glbDefaultPage, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - internal BasicFriendlyUrlProvider(NameValueCollection attributes) : base(attributes) { - //Read the attributes for this provider - _includePageName = String.IsNullOrEmpty(attributes["includePageName"]) || bool.Parse(attributes["includePageName"]); - _regexMatch = !String.IsNullOrEmpty(attributes["regexMatch"]) ? attributes["regexMatch"] : RegexMatchExpression; - _fileExtension = !String.IsNullOrEmpty(attributes["fileExtension"]) ? attributes["fileExtension"] : ".aspx"; + // Read the attributes for this provider + this._includePageName = string.IsNullOrEmpty(attributes["includePageName"]) || bool.Parse(attributes["includePageName"]); + this._regexMatch = !string.IsNullOrEmpty(attributes["regexMatch"]) ? attributes["regexMatch"] : RegexMatchExpression; + this._fileExtension = !string.IsNullOrEmpty(attributes["fileExtension"]) ? attributes["fileExtension"] : ".aspx"; } - #region Public Properties - public string FileExtension { - get { return _fileExtension; } + get { return this._fileExtension; } } public bool IncludePageName { - get { return _includePageName; } + get { return this._includePageName; } } public string RegexMatch { - get { return _regexMatch; } + get { return this._regexMatch; } } - #endregion + internal override string FriendlyUrl(TabInfo tab, string path) + { + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this.FriendlyUrl(tab, path, Globals.glbDefaultPage, _portalSettings); + } - #region Private Methods + internal override string FriendlyUrl(TabInfo tab, string path, string pageName) + { + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this.FriendlyUrl(tab, path, pageName, _portalSettings); + } /// ----------------------------------------------------------------------------- /// - /// AddPage adds the page to the friendly url + /// AddPage adds the page to the friendly url. /// /// /// /// The path to format. /// The page name. - /// The formatted url + /// The formatted url. private string AddPage(string path, string pageName) { string friendlyPath = path; - if ((friendlyPath.EndsWith("/"))) + if (friendlyPath.EndsWith("/")) { friendlyPath = friendlyPath + pageName; } @@ -78,6 +80,7 @@ private string AddPage(string path, string pageName) { friendlyPath = friendlyPath + "/" + pageName; } + return friendlyPath; } @@ -87,23 +90,24 @@ private string CheckPathLength(string friendlyPath, string originalpath) { return Globals.ResolveUrl(originalpath); } + return friendlyPath; } /// ----------------------------------------------------------------------------- /// - /// GetFriendlyAlias gets the Alias root of the friendly url + /// GetFriendlyAlias gets the Alias root of the friendly url. /// /// /// /// The path to format. /// The portal alias of the site. /// Whether is a relative page path. - /// The formatted url + /// The formatted url. private string GetFriendlyAlias(string path, string portalAlias, bool isPagePath) { string friendlyPath = path; - string matchString = ""; + string matchString = string.Empty; if (string.IsNullOrEmpty(portalAlias) == false) { string httpAlias = Globals.AddHTTP(portalAlias).ToLowerInvariant(); @@ -116,10 +120,11 @@ private string GetFriendlyAlias(string path, string portalAlias, bool isPagePath { matchString = httpAlias; } - if ((String.IsNullOrEmpty(matchString))) + + if (string.IsNullOrEmpty(matchString)) { - //Manage the special case where original url contains the alias as - //http://www.domain.com/Default.aspx?alias=www.domain.com/child" + // Manage the special case where original url contains the alias as + // http://www.domain.com/Default.aspx?alias=www.domain.com/child" Match portalMatch = Regex.Match(originalUrl, "^?alias=" + portalAlias, RegexOptions.IgnoreCase); if (!ReferenceEquals(portalMatch, Match.Empty)) { @@ -127,10 +132,10 @@ private string GetFriendlyAlias(string path, string portalAlias, bool isPagePath } } - if ((String.IsNullOrEmpty(matchString))) + if (string.IsNullOrEmpty(matchString)) { - //Manage the special case of child portals - //http://www.domain.com/child/default.aspx + // Manage the special case of child portals + // http://www.domain.com/child/default.aspx string tempurl = HttpContext.Current.Request.Url.Host + Globals.ResolveUrl(friendlyPath); if (!tempurl.Contains(portalAlias)) { @@ -138,7 +143,7 @@ private string GetFriendlyAlias(string path, string portalAlias, bool isPagePath } } - if ((String.IsNullOrEmpty(matchString))) + if (string.IsNullOrEmpty(matchString)) { // manage the case where the current hostname is www.domain.com and the portalalias is domain.com // (this occurs when www.domain.com is not listed as portal alias for the portal, but domain.com is) @@ -154,9 +159,10 @@ private string GetFriendlyAlias(string path, string portalAlias, bool isPagePath matchString = httpAlias; } } - if ((!String.IsNullOrEmpty(matchString))) + + if (!string.IsNullOrEmpty(matchString)) { - if ((path.IndexOf("~", StringComparison.Ordinal) != -1)) + if (path.IndexOf("~", StringComparison.Ordinal) != -1) { friendlyPath = friendlyPath.Replace(matchString.EndsWith("/") ? "~/" : "~", matchString); } @@ -169,45 +175,48 @@ private string GetFriendlyAlias(string path, string portalAlias, bool isPagePath { friendlyPath = Globals.ResolveUrl(friendlyPath); } + if (friendlyPath.StartsWith("//") && isPagePath) { friendlyPath = friendlyPath.Substring(1); } + return friendlyPath; } /// ----------------------------------------------------------------------------- /// - /// GetFriendlyQueryString gets the Querystring part of the friendly url + /// GetFriendlyQueryString gets the Querystring part of the friendly url. /// /// /// /// The tab whose url is being formatted. /// The path to format. /// The Page name. - /// The formatted url + /// The formatted url. private string GetFriendlyQueryString(TabInfo tab, string path, string pageName) { string friendlyPath = path; Match queryStringMatch = FriendlyPathRx.Match(friendlyPath); - string queryStringSpecialChars = ""; + string queryStringSpecialChars = string.Empty; if (!ReferenceEquals(queryStringMatch, Match.Empty)) { friendlyPath = queryStringMatch.Groups[1].Value; - friendlyPath = DefaultPageRx.Replace(friendlyPath, ""); + friendlyPath = DefaultPageRx.Replace(friendlyPath, string.Empty); string queryString = queryStringMatch.Groups[2].Value.Replace("&", "&"); - if ((queryString.StartsWith("?"))) + if (queryString.StartsWith("?")) { queryString = queryString.TrimStart(Convert.ToChar("?")); } + string[] nameValuePairs = queryString.Split(Convert.ToChar("&")); for (int i = 0; i <= nameValuePairs.Length - 1; i++) { - string pathToAppend = ""; + string pathToAppend = string.Empty; string[] pair = nameValuePairs[i].Split(Convert.ToChar("=")); - //Add name part of name/value pair - if ((friendlyPath.EndsWith("/"))) + // Add name part of name/value pair + if (friendlyPath.EndsWith("/")) { pathToAppend = pathToAppend + pair[0]; } @@ -215,23 +224,24 @@ private string GetFriendlyQueryString(TabInfo tab, string path, string pageName) { pathToAppend = pathToAppend + "/" + pair[0]; } - if ((pair.Length > 1)) + + if (pair.Length > 1) { - if ((!String.IsNullOrEmpty(pair[1]))) + if (!string.IsNullOrEmpty(pair[1])) { - if ((Regex.IsMatch(pair[1], _regexMatch) == false)) + if (Regex.IsMatch(pair[1], this._regexMatch) == false) { - //Contains Non-AlphaNumeric Characters - if ((pair[0].ToLowerInvariant() == "tabid")) + // Contains Non-AlphaNumeric Characters + if (pair[0].ToLowerInvariant() == "tabid") { if (Globals.NumberMatchRegex.IsMatch(pair[1])) { if (tab != null) { int tabId = Convert.ToInt32(pair[1]); - if ((tab.TabID == tabId)) + if (tab.TabID == tabId) { - if ((string.IsNullOrEmpty(tab.TabPath) == false) && IncludePageName) + if ((string.IsNullOrEmpty(tab.TabPath) == false) && this.IncludePageName) { pathToAppend = tab.TabPath.Replace("//", "/").TrimStart('/') + "/" + pathToAppend; } @@ -239,12 +249,13 @@ private string GetFriendlyQueryString(TabInfo tab, string path, string pageName) } } } + pathToAppend = pathToAppend + "/" + HttpUtility.UrlPathEncode(pair[1]); } else { - //Rewrite into URL, contains only alphanumeric and the % or space - if (String.IsNullOrEmpty(queryStringSpecialChars)) + // Rewrite into URL, contains only alphanumeric and the % or space + if (string.IsNullOrEmpty(queryStringSpecialChars)) { queryStringSpecialChars = pair[0] + "=" + pair[1]; } @@ -252,34 +263,38 @@ private string GetFriendlyQueryString(TabInfo tab, string path, string pageName) { queryStringSpecialChars = queryStringSpecialChars + "&" + pair[0] + "=" + pair[1]; } - pathToAppend = ""; + + pathToAppend = string.Empty; } } else { - pathToAppend = pathToAppend + "/" + HttpUtility.UrlPathEncode((' ').ToString()); + pathToAppend = pathToAppend + "/" + HttpUtility.UrlPathEncode(' '.ToString()); } } + friendlyPath = friendlyPath + pathToAppend; } } - if ((!String.IsNullOrEmpty(queryStringSpecialChars))) + + if (!string.IsNullOrEmpty(queryStringSpecialChars)) { - return AddPage(friendlyPath, pageName) + "?" + queryStringSpecialChars; + return this.AddPage(friendlyPath, pageName) + "?" + queryStringSpecialChars; } - return AddPage(friendlyPath, pageName); + + return this.AddPage(friendlyPath, pageName); } private Dictionary GetQueryStringDictionary(string path) { string[] parts = path.Split('?'); var results = new Dictionary(StringComparer.OrdinalIgnoreCase); - if ((parts.Length == 2)) + if (parts.Length == 2) { foreach (string part in parts[1].Split('&')) { string[] keyvalue = part.Split('='); - if ((keyvalue.Length == 2)) + if (keyvalue.Length == 2) { results[keyvalue[0]] = keyvalue[1]; } @@ -289,60 +304,46 @@ private Dictionary GetQueryStringDictionary(string path) return results; } - #endregion - - #region Internal Methods - - internal override string FriendlyUrl(TabInfo tab, string path) - { - PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return FriendlyUrl(tab, path, Globals.glbDefaultPage, _portalSettings); - } - - internal override string FriendlyUrl(TabInfo tab, string path, string pageName) - { - PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return FriendlyUrl(tab, path, pageName, _portalSettings); - } - internal override string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings) { - return FriendlyUrl(tab, path, pageName, ((PortalSettings)settings)?.PortalAlias.HTTPAlias, settings); + return this.FriendlyUrl(tab, path, pageName, ((PortalSettings)settings)?.PortalAlias.HTTPAlias, settings); } internal override string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) { - return FriendlyUrl(tab, path, pageName, portalAlias, null); + return this.FriendlyUrl(tab, path, pageName, portalAlias, null); } private string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias, IPortalSettings portalSettings) { string friendlyPath = path; - bool isPagePath = (tab != null); + bool isPagePath = tab != null; - if ((UrlFormat == UrlFormatType.HumanFriendly)) + if (this.UrlFormat == UrlFormatType.HumanFriendly) { - if ((tab != null)) + if (tab != null) { - Dictionary queryStringDic = GetQueryStringDictionary(path); - if ((queryStringDic.Count == 0 || (queryStringDic.Count == 1 && queryStringDic.ContainsKey("tabid")))) + Dictionary queryStringDic = this.GetQueryStringDictionary(path); + if (queryStringDic.Count == 0 || (queryStringDic.Count == 1 && queryStringDic.ContainsKey("tabid"))) { - friendlyPath = GetFriendlyAlias("~/" + tab.TabPath.Replace("//", "/").TrimStart('/') + ".aspx", portalAlias, true); + friendlyPath = this.GetFriendlyAlias("~/" + tab.TabPath.Replace("//", "/").TrimStart('/') + ".aspx", portalAlias, true); } - else if ((queryStringDic.Count == 2 && queryStringDic.ContainsKey("tabid") && queryStringDic.ContainsKey("language"))) + else if (queryStringDic.Count == 2 && queryStringDic.ContainsKey("tabid") && queryStringDic.ContainsKey("language")) { if (!tab.IsNeutralCulture) { - friendlyPath = GetFriendlyAlias("~/" + tab.CultureCode + "/" + tab.TabPath.Replace("//", "/").TrimStart('/') + ".aspx", - portalAlias, - true) + friendlyPath = this.GetFriendlyAlias( + "~/" + tab.CultureCode + "/" + tab.TabPath.Replace("//", "/").TrimStart('/') + ".aspx", + portalAlias, + true) .ToLowerInvariant(); } else { - friendlyPath = GetFriendlyAlias("~/" + queryStringDic["language"] + "/" + tab.TabPath.Replace("//", "/").TrimStart('/') + ".aspx", - portalAlias, - true) + friendlyPath = this.GetFriendlyAlias( + "~/" + queryStringDic["language"] + "/" + tab.TabPath.Replace("//", "/").TrimStart('/') + ".aspx", + portalAlias, + true) .ToLowerInvariant(); } } @@ -353,41 +354,41 @@ private string FriendlyUrl(TabInfo tab, string path, string pageName, string por switch (queryStringDic["ctl"].ToLowerInvariant()) { case "terms": - friendlyPath = GetFriendlyAlias("~/terms.aspx", portalAlias, true); + friendlyPath = this.GetFriendlyAlias("~/terms.aspx", portalAlias, true); break; case "privacy": - friendlyPath = GetFriendlyAlias("~/privacy.aspx", portalAlias, true); + friendlyPath = this.GetFriendlyAlias("~/privacy.aspx", portalAlias, true); break; case "login": - friendlyPath = (queryStringDic.ContainsKey("returnurl")) - ? GetFriendlyAlias("~/login.aspx?ReturnUrl=" + queryStringDic["returnurl"], portalAlias, true) - : GetFriendlyAlias("~/login.aspx", portalAlias, true); + friendlyPath = queryStringDic.ContainsKey("returnurl") + ? this.GetFriendlyAlias("~/login.aspx?ReturnUrl=" + queryStringDic["returnurl"], portalAlias, true) + : this.GetFriendlyAlias("~/login.aspx", portalAlias, true); break; case "register": - friendlyPath = (queryStringDic.ContainsKey("returnurl")) - ? GetFriendlyAlias("~/register.aspx?returnurl=" + queryStringDic["returnurl"], portalAlias, true) - : GetFriendlyAlias("~/register.aspx", portalAlias, true); + friendlyPath = queryStringDic.ContainsKey("returnurl") + ? this.GetFriendlyAlias("~/register.aspx?returnurl=" + queryStringDic["returnurl"], portalAlias, true) + : this.GetFriendlyAlias("~/register.aspx", portalAlias, true); break; default: - //Return Search engine friendly version - return GetFriendlyQueryString(tab, GetFriendlyAlias(path, portalAlias, true), pageName); + // Return Search engine friendly version + return this.GetFriendlyQueryString(tab, this.GetFriendlyAlias(path, portalAlias, true), pageName); } } else { - //Return Search engine friendly version - return GetFriendlyQueryString(tab, GetFriendlyAlias(path, portalAlias, true), pageName); + // Return Search engine friendly version + return this.GetFriendlyQueryString(tab, this.GetFriendlyAlias(path, portalAlias, true), pageName); } } } } else { - //Return Search engine friendly version - friendlyPath = GetFriendlyQueryString(tab, GetFriendlyAlias(path, portalAlias, isPagePath), pageName); + // Return Search engine friendly version + friendlyPath = this.GetFriendlyQueryString(tab, this.GetFriendlyAlias(path, portalAlias, isPagePath), pageName); } - friendlyPath = CheckPathLength(Globals.ResolveUrl(friendlyPath), path); + friendlyPath = this.CheckPathLength(Globals.ResolveUrl(friendlyPath), path); // Replace http:// by https:// if SSL is enabled and site is marked as secure // (i.e. requests to http://... will be redirected to https://...) @@ -407,7 +408,5 @@ private string FriendlyUrl(TabInfo tab, string path, string pageName, string por return friendlyPath; } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Urls/BrowserTypes.cs b/DNN Platform/Library/Entities/Urls/BrowserTypes.cs index bc1a7b3191c..0b65b119418 100644 --- a/DNN Platform/Library/Entities/Urls/BrowserTypes.cs +++ b/DNN Platform/Library/Entities/Urls/BrowserTypes.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum BrowserTypes { Normal, - Mobile + Mobile, } } diff --git a/DNN Platform/Library/Entities/Urls/CacheController.cs b/DNN Platform/Library/Entities/Urls/CacheController.cs index 5ed87d189f3..b961049b907 100644 --- a/DNN Platform/Library/Entities/Urls/CacheController.cs +++ b/DNN Platform/Library/Entities/Urls/CacheController.cs @@ -1,40 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Configuration; -using System.IO; -using System.Threading; -using System.Web.Caching; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Configuration; + using System.IO; + using System.Threading; + using System.Web.Caching; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Log.EventLog; + public class CacheController { - private static CacheItemRemovedReason cacheItemRemovedReason; - private static bool LogRemovedReason; - private CacheItemRemovedCallback onRemovePageIndex; - - #region Cache Keys - + internal const string VanityUrlLookupKey = "url_VanityUrlLookup_{0}"; + private const string PageIndexKey = "url_PageIndex"; private const string PageIndexDepthKey = "url_PageIndexDepth"; + private static CacheItemRemovedReason cacheItemRemovedReason; + private static bool LogRemovedReason; + private CacheItemRemovedCallback onRemovePageIndex; private const string UrlDictKey = "url_UrlDict"; private const string UrlPortalsKey = "url_UrlPortals"; private const string CustomAliasTabsKey = "url_CustomAliasTabsKey"; @@ -52,85 +46,26 @@ public class CacheController private const string AlwaysCallProviderTabsKey = "url_AlwaysCallProviderTabs_{0}"; private const string HomePageSkinsKey = "url_HomePageSkins_{0}"; private const string TabPathsKey = "url_TabPathsKey_{0}"; - - internal const string VanityUrlLookupKey = "url_VanityUrlLookup_{0}"; - - #endregion - - #region Private Methods - - private static CacheDependency GetPortalsCacheDependency() - { - var keys = new List {"DNN_PortalDictionary"}; - var portalsDepedency = new CacheDependency(null, keys.ToArray()); - return portalsDepedency; - } - - private CacheDependency GetTabsCacheDependency(IEnumerable portalIds) - { - var keys = new List(); - foreach (int portalId in portalIds) - { - const string cacheKey = DataCache.TabCacheKey; - string key = string.Format(cacheKey, portalId); - key = "DNN_" + key; //add on the DNN_ prefix - keys.Add(key); - } - //get the portals list dependency - var portalKeys = new List(); - if (portalKeys.Count > 0) - { - keys.AddRange(portalKeys); - } - var tabsDependency = new CacheDependency(null, keys.ToArray()); - return tabsDependency; - } - - private static void SetPageCache(string key, object value, FriendlyUrlSettings settings) - { - SetPageCache(key, value, null, settings, null); - } - - private static void SetPageCache(string key, object value, DNNCacheDependency dependency, FriendlyUrlSettings settings, CacheItemRemovedCallback callback) + + public static void FlushFriendlyUrlSettingsFromCache() { - DateTime absoluteExpiration = DateTime.Now.Add(settings.CacheTime); - DataCache.SetCache(key, - value, - dependency, - absoluteExpiration, - Cache.NoSlidingExpiration, - CacheItemPriority.AboveNormal, - callback); + DataCache.RemoveCache(FriendlyUrlSettingsKey); } - private static void SetPortalCache(string key, object value, FriendlyUrlSettings settings) + public static void FlushPageIndexFromCache() { - var absoluteExpiration = DateTime.Now.Add(new TimeSpan(24, 0, 0)); - if (settings != null) - { - absoluteExpiration = DateTime.Now.Add(settings.CacheTime); - } - //857 : use cache dependency for portal alias cache - if (settings != null) - { - DataCache.SetCache(key, - value, - new DNNCacheDependency(GetPortalsCacheDependency()), - absoluteExpiration, - Cache.NoSlidingExpiration); - } - else - { - DataCache.SetCache(key, value, absoluteExpiration); - } + DataCache.RemoveCache(UrlDictKey); + DataCache.RemoveCache(PageIndexKey); + DataCache.RemoveCache(PageIndexDepthKey); + DataCache.RemoveCache(UrlPortalsKey); + DataCache.RemoveCache(UserProfileActionsKey); + DataCache.RemoveCache(PortalAliasListKey); + DataCache.RemoveCache(PortalAliasesKey); + DataCache.RemoveCache(TabPathsKey); } - - #endregion - - #region Internal Methods - + /// - /// Finds the best match friendlyurlparms.config file path + /// Finds the best match friendlyurlparms.config file path. /// /// The portalId to search for. -1 if all portals required. /// @@ -139,42 +74,43 @@ private static void SetPortalCache(string key, object value, FriendlyUrlSettings /// First priority is a file called n.friendlyurlparms.config, in the root path /// Next priority is a file called portals\n\friendlyurlparms.config, in the portal path /// Last priority is the friendlyurlparms.config file, in the root path - /// Task no 807 + /// Task no 807. /// internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool portalSpecificFound) { - string result = ""; + string result = string.Empty; portalSpecificFound = false; const string fileName = "friendlyUrlParms.config"; string rootPath = Globals.ApplicationMapPath + "\\"; string filePath; - if (portalId > -1) //specific portal + if (portalId > -1) // specific portal { - //first look in the root folder with the portalid as a prefix + // first look in the root folder with the portalid as a prefix filePath = rootPath + portalId.ToString() + "." + fileName; } - else //no specific portal + else // no specific portal { filePath = rootPath + fileName; // just the pathname } + if (File.Exists(filePath)) { result = filePath; - if (portalId > -1) //if there was a portal specified, this was a portal specific path + if (portalId > -1) // if there was a portal specified, this was a portal specific path { portalSpecificFound = true; } } else { - //no portal specific name in the root folder + // no portal specific name in the root folder if (portalId > Null.NullInteger) // at this point, only interested if a specific portal is requested { var portal = PortalController.Instance.GetPortal(portalId); if (portal != null) { - //looking for the file in the portal folder + // looking for the file in the portal folder var portalPath = portal.HomeDirectoryMapPath; filePath = portalPath + fileName; // just the pathname if (File.Exists(filePath)) @@ -184,9 +120,10 @@ internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool } } } - if (String.IsNullOrEmpty(result)) + + if (string.IsNullOrEmpty(result)) { - //nothing matching found : now just looking for the root path + // nothing matching found : now just looking for the root path filePath = rootPath + fileName; if (File.Exists(filePath)) { @@ -195,6 +132,7 @@ internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool } } } + return result; } @@ -207,53 +145,91 @@ internal static List GetAlwaysCallProviderTabs(int portalId) { result = new List(tabIdsToAlwaysCall); } + return result; } + + private static CacheDependency GetPortalsCacheDependency() + { + var keys = new List { "DNN_PortalDictionary" }; + var portalsDepedency = new CacheDependency(null, keys.ToArray()); + return portalsDepedency; + } - //770 : customised portal alias per-tab - internal static List GetCustomAliasesFromCache() + private static void SetPageCache(string key, object value, FriendlyUrlSettings settings) { - object raw = DataCache.GetCache(CustomPortalAliasesKey); - return (raw != null) ? (List)raw : null; + SetPageCache(key, value, null, settings, null); } - internal static void ClearCustomAliasesCache() + private static void SetPageCache(string key, object value, DNNCacheDependency dependency, FriendlyUrlSettings settings, CacheItemRemovedCallback callback) { - DataCache.ClearCache(CustomPortalAliasesKey); + DateTime absoluteExpiration = DateTime.Now.Add(settings.CacheTime); + DataCache.SetCache( + key, + value, + dependency, + absoluteExpiration, + Cache.NoSlidingExpiration, + CacheItemPriority.AboveNormal, + callback); } - /// - /// Retrieve the Url Dictionary for the installation. - /// - /// - /// - /// - /// - /// - internal void GetFriendlyUrlIndexFromCache(out SharedDictionary> urlDict, - out ConcurrentBag urlPortals, - out SharedDictionary customAliasTabs) + private CacheDependency GetTabsCacheDependency(IEnumerable portalIds) { - urlDict = null; - urlPortals = null; - customAliasTabs = null; - object rawDict = DataCache.GetCache(UrlDictKey); //contains a dictionary of tabs for all portals - object rawPortals = DataCache.GetCache(UrlPortalsKey); - //contains a list of portals for which we have retrieved the tabs - object rawCustomAliasTabs = DataCache.GetCache(CustomAliasTabsKey); - //contains a dictionary of tabs with custom aliases, for all portals - if (rawDict != null) + var keys = new List(); + foreach (int portalId in portalIds) { - urlDict = (SharedDictionary>)rawDict; + const string cacheKey = DataCache.TabCacheKey; + string key = string.Format(cacheKey, portalId); + key = "DNN_" + key; // add on the DNN_ prefix + keys.Add(key); } - if (rawPortals != null) + + // get the portals list dependency + var portalKeys = new List(); + if (portalKeys.Count > 0) { - urlPortals = (ConcurrentBag)rawPortals; + keys.AddRange(portalKeys); } - if (rawCustomAliasTabs != null) + + var tabsDependency = new CacheDependency(null, keys.ToArray()); + return tabsDependency; + } + + private static void SetPortalCache(string key, object value, FriendlyUrlSettings settings) + { + var absoluteExpiration = DateTime.Now.Add(new TimeSpan(24, 0, 0)); + if (settings != null) { - customAliasTabs = (SharedDictionary)rawCustomAliasTabs; + absoluteExpiration = DateTime.Now.Add(settings.CacheTime); + } + + // 857 : use cache dependency for portal alias cache + if (settings != null) + { + DataCache.SetCache( + key, + value, + new DNNCacheDependency(GetPortalsCacheDependency()), + absoluteExpiration, + Cache.NoSlidingExpiration); } + else + { + DataCache.SetCache(key, value, absoluteExpiration); + } + } + + // 770 : customised portal alias per-tab + internal static List GetCustomAliasesFromCache() + { + object raw = DataCache.GetCache(CustomPortalAliasesKey); + return (raw != null) ? (List)raw : null; + } + + internal static void ClearCustomAliasesCache() + { + DataCache.ClearCache(CustomPortalAliasesKey); } internal static Hashtable GetHomePageSkinsFromCache(int portalId) @@ -272,47 +248,72 @@ internal static List GetListOfTabsWithProviders(int portalId, FriendlyUrlSe { result = new List(tabIdsForPortal); } + return result; } - internal void GetPageIndexFromCache(out SharedDictionary dict, - out SharedDictionary portalDepthInfo, - FriendlyUrlSettings settings) + /// + /// Retrieve the Url Dictionary for the installation. + /// + /// + /// + /// + /// + /// + internal void GetFriendlyUrlIndexFromCache( + out SharedDictionary> urlDict, + out ConcurrentBag urlPortals, + out SharedDictionary customAliasTabs) { - object raw = DataCache.GetCache(PageIndexKey); - if (raw != null) + urlDict = null; + urlPortals = null; + customAliasTabs = null; + object rawDict = DataCache.GetCache(UrlDictKey); // contains a dictionary of tabs for all portals + object rawPortals = DataCache.GetCache(UrlPortalsKey); + + // contains a list of portals for which we have retrieved the tabs + object rawCustomAliasTabs = DataCache.GetCache(CustomAliasTabsKey); + + // contains a dictionary of tabs with custom aliases, for all portals + if (rawDict != null) { - dict = (SharedDictionary)raw; - raw = DataCache.GetCache(PageIndexDepthKey); - portalDepthInfo = (SharedDictionary)raw; + urlDict = (SharedDictionary>)rawDict; } - else + + if (rawPortals != null) { - dict = null; - portalDepthInfo = null; + urlPortals = (ConcurrentBag)rawPortals; + } + + if (rawCustomAliasTabs != null) + { + customAliasTabs = (SharedDictionary)rawCustomAliasTabs; } } internal static Dictionary> GetParameterRedirects(FriendlyUrlSettings settings, int portalId, ref List messages) { - string redirectActionKey = string.Format(RedirectActionsKey, portalId); //cached one portal at a time + string redirectActionKey = string.Format(RedirectActionsKey, portalId); // cached one portal at a time if (messages == null) { messages = new List(); } + var redirectActions = (Dictionary>)DataCache.GetCache(redirectActionKey); if (redirectActions == null) { try { redirectActions = new Dictionary>(); - //807 : look for portal specific files + + // 807 : look for portal specific files bool portalSpecific; string fileName = FindFriendlyUrlParmsConfigFilePath(portalId, out portalSpecific); - if (fileName != "") + if (fileName != string.Empty) { redirectActions.LoadFromXmlFile(fileName, portalId, portalSpecific, ref messages); } + CacheDependency fileDependency = null; if (File.Exists(fileName)) { @@ -331,11 +332,12 @@ internal static Dictionary> GetParameterRedir } catch (Exception ex) { - //log the exception + // log the exception Services.Exceptions.Exceptions.LogException(ex); messages.Add("Exception: " + ex.Message + "\n" + ex.StackTrace); } } + return redirectActions; } @@ -347,6 +349,7 @@ internal static Dictionary> GetParameterReplac { messages = new List(); } + if (replaceActions == null) { replaceActions = new Dictionary>(); @@ -358,10 +361,11 @@ internal static Dictionary> GetParameterReplac { replaceActions.LoadFromXmlFile(fileName, portalId, portalSpecific, ref messages); } + CacheDependency cacheDependency = null; if (replaceActions.Count > 0) { - //only set filename dependency if file exists + // only set filename dependency if file exists cacheDependency = new CacheDependency(fileName); } @@ -374,9 +378,29 @@ internal static Dictionary> GetParameterReplac messages.Add("Exception: " + ex.Message + "\n" + ex.StackTrace); } } + return replaceActions; } + internal void GetPageIndexFromCache( + out SharedDictionary dict, + out SharedDictionary portalDepthInfo, + FriendlyUrlSettings settings) + { + object raw = DataCache.GetCache(PageIndexKey); + if (raw != null) + { + dict = (SharedDictionary)raw; + raw = DataCache.GetCache(PageIndexDepthKey); + portalDepthInfo = (SharedDictionary)raw; + } + else + { + dict = null; + portalDepthInfo = null; + } + } + internal static Dictionary> GetParameterRewrites(int portalId, ref List messages, Guid parentTraceId) { string rewriteActionKey = string.Format(RewriteActionsKey, portalId.ToString()); @@ -384,6 +408,7 @@ internal static Dictionary> GetParameter { messages = new List(); } + var rewriteActions = (Dictionary>)DataCache.GetCache(rewriteActionKey); if (rewriteActions == null) { @@ -391,12 +416,14 @@ internal static Dictionary> GetParameter { rewriteActions = new Dictionary>(); bool portalSpecific; - //807 : new change to look for portal rule files in portal specific locations + + // 807 : new change to look for portal rule files in portal specific locations string filename = FindFriendlyUrlParmsConfigFilePath(portalId, out portalSpecific); if (!string.IsNullOrEmpty(filename)) { rewriteActions.LoadFromXmlFile(filename, portalId, portalSpecific, ref messages); } + CacheDependency fileDependency = null; if (File.Exists(filename)) { @@ -411,6 +438,7 @@ internal static Dictionary> GetParameter messages.Add("Exception: " + ex.Message + "\n" + ex.StackTrace); } } + return rewriteActions; } @@ -420,18 +448,19 @@ internal static OrderedDictionary GetPortalAliasesFromCache() return (raw != null) ? (OrderedDictionary)raw : null; } - internal static List GetProvidersForTabAndPortal(int tabId, - int portalId, - FriendlyUrlSettings settings, - out bool noSuchProvider, - Guid parentTraceId) + internal static List GetProvidersForTabAndPortal( + int tabId, + int portalId, + FriendlyUrlSettings settings, + out bool noSuchProvider, + Guid parentTraceId) { - //get list of tabids in this portal that have providers + // get list of tabids in this portal that have providers noSuchProvider = false; List allCachedProviders = null; List tabsWithProviders = GetListOfTabsWithProviders(portalId, settings); - bool checkThisTab = true, checkAllTabs = true; //going to check all tabs, unless find otherwise in the cache + bool checkThisTab = true, checkAllTabs = true; // going to check all tabs, unless find otherwise in the cache if (tabsWithProviders != null) { checkAllTabs = tabsWithProviders.Contains(RewriteController.AllTabsRewrite); @@ -440,13 +469,13 @@ internal static List GetProvidersForTabAndPortal(int tabId if (!checkThisTab && !checkAllTabs) { - noSuchProvider = true; //we got the list of tabs, there is no provider for this tab + noSuchProvider = true; // we got the list of tabs, there is no provider for this tab } } if (checkAllTabs) { - //the portal has an 'all tabs' provider in it + // the portal has an 'all tabs' provider in it string allTabsKey = string.Format(PortalModuleProvidersAllTabsKey, portalId); var cachedAllTabsProviders = (List)DataCache.GetCache(allTabsKey); if (cachedAllTabsProviders != null) @@ -456,9 +485,9 @@ internal static List GetProvidersForTabAndPortal(int tabId } } - if (checkThisTab) //the specified tab + if (checkThisTab) // the specified tab { - //tab exists, get the providers for this tab + // tab exists, get the providers for this tab string key = string.Format(PortalModuleProvidersForTabKey, portalId, tabId); var cachedTabProviders = (List)DataCache.GetCache(key); if (cachedTabProviders != null) @@ -467,9 +496,11 @@ internal static List GetProvidersForTabAndPortal(int tabId { allCachedProviders = new List(); } + allCachedProviders.AddRange(cachedTabProviders); } } + return allCachedProviders; } @@ -497,58 +528,6 @@ internal static void StoreCustomAliasesInCache(List aliases, FriendlyUrl DataCache.SetCache(CustomPortalAliasesKey, aliases, absoluteExpiration); } - /// - /// Store the Url Dictionary (all tab urls / tabids) for the installation - /// - /// - /// - /// - /// - /// - /// - /// - internal void StoreFriendlyUrlIndexInCache(SharedDictionary> urlDict, - ConcurrentBag urlPortals, - SharedDictionary customAliasTabs, - FriendlyUrlSettings settings, - string reason) - { - if (settings.LogCacheMessages) - { - onRemovePageIndex = RemovedPageIndexCallBack; - } - else - { - onRemovePageIndex = null; - } - - LogRemovedReason = settings.LogCacheMessages; - - SetPageCache(UrlDictKey, urlDict, new DNNCacheDependency(GetTabsCacheDependency(urlPortals)), settings, onRemovePageIndex); - SetPageCache(UrlPortalsKey, urlPortals, settings); - SetPageCache(CustomAliasTabsKey, customAliasTabs, settings); - - if (settings.LogCacheMessages) - { - - var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; - log.AddProperty("Url Rewriting Caching Message", "Friendly Url Index built and Stored in Cache."); - log.AddProperty("Build Reason", reason); - log.AddProperty("Cache Key", UrlDictKey); - using (urlDict.GetReadLock()) - { - log.AddProperty("Item Count", urlDict.Values.Count.ToString()); - } - log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); - log.AddProperty("Item added to cache", "Url Portals object added to cache. Key:" + UrlPortalsKey + " Items: " + urlPortals.Count.ToString()); - using (customAliasTabs.GetReadLock()) - { - log.AddProperty("Item added to cache", "Custom Alias Tabs added to cache. Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString()); - } - LogController.Instance.AddLog(log); - } - } - internal static void StoreHomePageSkinsInCache(int portalId, Hashtable homePageSkins) { if (homePageSkins != null && homePageSkins.Count > 0) @@ -561,15 +540,15 @@ internal static void StoreHomePageSkinsInCache(int portalId, Hashtable homePageS /// This method stores a list of tabIds for the specific portal in the cache /// This is used to lookup and see if there are any providers to load for a tab, /// without having to store individual tabid/portaldId provider lists for every tab - /// If a tab doesn't appear on this cached list, then the cache isn't checked - /// for that particular tabid/portalId combination + /// If a tab doesn't appear on this cached list, then the cache isn't checked + /// for that particular tabid/portalId combination. ///
    /// /// /// internal static void StoreListOfTabsWithProviders(List providers, int portalId, FriendlyUrlSettings settings) { - //go through the list of providers and store all the tabs that they are configured for + // go through the list of providers and store all the tabs that they are configured for var providersWithTabs = new List(); var providersWithTabsStr = new List(); foreach (ExtensionUrlProvider provider in providers) @@ -582,6 +561,7 @@ internal static void StoreListOfTabsWithProviders(List pro providersWithTabsStr.Add("AllTabs"); } } + if (provider.AlwaysUsesDnnPagePath(portalId) == false) { if (providersWithTabs.Contains(RewriteController.SiteRootRewrite) == false) @@ -590,6 +570,7 @@ internal static void StoreListOfTabsWithProviders(List pro providersWithTabsStr.Add("NoPath"); } } + foreach (int providerTabId in provider.ProviderConfig.TabIds) { if (providersWithTabs.Contains(providerTabId) == false) @@ -600,7 +581,7 @@ internal static void StoreListOfTabsWithProviders(List pro } } - //store list as array in cache + // store list as array in cache string key = string.Format(PortalModuleProviderTabsKey, portalId); SetPageCache(key, providersWithTabs.ToArray(), settings); if (settings.LogCacheMessages) @@ -615,13 +596,69 @@ internal static void StoreListOfTabsWithProviders(List pro } } + /// + /// Store the Url Dictionary (all tab urls / tabids) for the installation. + /// + /// + /// + /// + /// + /// + /// + /// + internal void StoreFriendlyUrlIndexInCache( + SharedDictionary> urlDict, + ConcurrentBag urlPortals, + SharedDictionary customAliasTabs, + FriendlyUrlSettings settings, + string reason) + { + if (settings.LogCacheMessages) + { + this.onRemovePageIndex = this.RemovedPageIndexCallBack; + } + else + { + this.onRemovePageIndex = null; + } + + LogRemovedReason = settings.LogCacheMessages; + + SetPageCache(UrlDictKey, urlDict, new DNNCacheDependency(this.GetTabsCacheDependency(urlPortals)), settings, this.onRemovePageIndex); + SetPageCache(UrlPortalsKey, urlPortals, settings); + SetPageCache(CustomAliasTabsKey, customAliasTabs, settings); + + if (settings.LogCacheMessages) + { + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + log.AddProperty("Url Rewriting Caching Message", "Friendly Url Index built and Stored in Cache."); + log.AddProperty("Build Reason", reason); + log.AddProperty("Cache Key", UrlDictKey); + using (urlDict.GetReadLock()) + { + log.AddProperty("Item Count", urlDict.Values.Count.ToString()); + } + + log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); + log.AddProperty("Item added to cache", "Url Portals object added to cache. Key:" + UrlPortalsKey + " Items: " + urlPortals.Count.ToString()); + using (customAliasTabs.GetReadLock()) + { + log.AddProperty("Item added to cache", "Custom Alias Tabs added to cache. Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString()); + } + + LogController.Instance.AddLog(log); + } + } + internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSettings settings, List providers) { - //get the key for the portal module providers + // get the key for the portal module providers string allTabsKey = string.Format(PortalModuleProvidersAllTabsKey, portalId); - //get the providers that are on all tabs + + // get the providers that are on all tabs var allTabsProviders = new List(); - //holds all providers, indexed by tabId + + // holds all providers, indexed by tabId var tabsProviders = new Dictionary>(); var tabIdStr = new List(); int providerCount = 0; @@ -640,7 +677,7 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett { thisTabProviders = tabsProviders[tabId]; thisTabProviders.Add(provider); - tabsProviders[tabId] = thisTabProviders; //assign back to position in tabs + tabsProviders[tabId] = thisTabProviders; // assign back to position in tabs } else { @@ -649,21 +686,25 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett tabIdStr.Add(tabId.ToString()); } } + providerCount++; } - //store the list of providers where the provider might be called with no valid TabId, because - //the provider allows for Urls with no DNN Page path, which means the TabId can't be identified - //by the Url Rewriter. This identifies the Provider as using a 'siteRootRewrite' + + // store the list of providers where the provider might be called with no valid TabId, because + // the provider allows for Urls with no DNN Page path, which means the TabId can't be identified + // by the Url Rewriter. This identifies the Provider as using a 'siteRootRewrite' if (provider.AlwaysUsesDnnPagePath(portalId) == false) { List noPathProviders; - //add this one + + // add this one if (tabsProviders.ContainsKey(RewriteController.SiteRootRewrite)) { noPathProviders = tabsProviders[RewriteController.SiteRootRewrite]; noPathProviders.Add(provider); tabsProviders[RewriteController.SiteRootRewrite] = noPathProviders; - //assign back to position in tabs + + // assign back to position in tabs } else { @@ -673,11 +714,13 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett } } } - //now add the two collections to the cache + + // now add the two collections to the cache if (allTabsProviders.Count > 0) { SetPageCache(allTabsKey, allTabsProviders, settings); } + if (tabsProviders.Count > 0) { foreach (int tabId in tabsProviders.Keys) @@ -698,23 +741,33 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett } } + internal static void StorePortalAliasesInCache(SharedDictionary aliases, FriendlyUrlSettings settings) + { + SetPortalCache(PortalAliasListKey, aliases, settings); + } - internal void StorePageIndexInCache(SharedDictionary tabDictionary, - SharedDictionary portalDepthInfo, - FriendlyUrlSettings settings, - string reason) + internal static void StorePortalAliasesInCache(OrderedDictionary aliasList, FriendlyUrlSettings settings) { - onRemovePageIndex = settings.LogCacheMessages ? (CacheItemRemovedCallback) RemovedPageIndexCallBack : null; + SetPortalCache(PortalAliasesKey, aliasList, settings); + } + + internal void StorePageIndexInCache( + SharedDictionary tabDictionary, + SharedDictionary portalDepthInfo, + FriendlyUrlSettings settings, + string reason) + { + this.onRemovePageIndex = settings.LogCacheMessages ? (CacheItemRemovedCallback)this.RemovedPageIndexCallBack : null; - //get list of portal ids for the portals we are storing in the page index + // get list of portal ids for the portals we are storing in the page index var portalIds = new List(); using (portalDepthInfo.GetReadLock()) { portalIds.AddRange(portalDepthInfo.Keys); } - //783 : use cache dependency to manage page index instead of triggerDictionaryRebuild regex. - SetPageCache(PageIndexKey, tabDictionary, new DNNCacheDependency(GetTabsCacheDependency(portalIds)), settings, onRemovePageIndex); + // 783 : use cache dependency to manage page index instead of triggerDictionaryRebuild regex. + SetPageCache(PageIndexKey, tabDictionary, new DNNCacheDependency(this.GetTabsCacheDependency(portalIds)), settings, this.onRemovePageIndex); SetPageCache(PageIndexDepthKey, portalDepthInfo, settings); @@ -722,7 +775,7 @@ internal void StorePageIndexInCache(SharedDictionary tabDictiona if (settings.LogCacheMessages) { - var log = new LogInfo {LogTypeKey = "HOST_ALERT"}; + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; log.AddProperty("Url Rewriting Caching Message", "Page Index built and Stored in Cache"); log.AddProperty("Reason", reason); @@ -731,53 +784,24 @@ internal void StorePageIndexInCache(SharedDictionary tabDictiona { log.AddProperty("Item Count", tabDictionary.Count.ToString()); } + log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); LogController.Instance.AddLog(log); } } - internal static void StorePortalAliasesInCache(SharedDictionary aliases, FriendlyUrlSettings settings) - { - SetPortalCache(PortalAliasListKey, aliases, settings); - } - - internal static void StorePortalAliasesInCache(OrderedDictionary aliasList, FriendlyUrlSettings settings) - { - SetPortalCache(PortalAliasesKey, aliasList, settings); - } - internal void StoreTabPathsInCache(int portalId, SharedDictionary tabPathDictionary, FriendlyUrlSettings settings) { - SetPageCache(string.Format(TabPathsKey, portalId), - tabPathDictionary, - new DNNCacheDependency(GetTabsCacheDependency(new List { portalId })), - settings, - null); - } - - #endregion - - #region Public Methods - - public static void FlushFriendlyUrlSettingsFromCache() - { - DataCache.RemoveCache(FriendlyUrlSettingsKey); - } - - public static void FlushPageIndexFromCache() - { - DataCache.RemoveCache(UrlDictKey); - DataCache.RemoveCache(PageIndexKey); - DataCache.RemoveCache(PageIndexDepthKey); - DataCache.RemoveCache(UrlPortalsKey); - DataCache.RemoveCache(UserProfileActionsKey); - DataCache.RemoveCache(PortalAliasListKey); - DataCache.RemoveCache(PortalAliasesKey); - DataCache.RemoveCache(TabPathsKey); - } + SetPageCache( + string.Format(TabPathsKey, portalId), + tabPathDictionary, + new DNNCacheDependency(this.GetTabsCacheDependency(new List { portalId })), + settings, + null); + } /// - /// Returns a portal info object for the portal + /// Returns a portal info object for the portal. /// /// /// @@ -786,7 +810,8 @@ public static void FlushPageIndexFromCache() public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) { PortalInfo pi = null; - //775 : change to use threadsafe dictionary + + // 775 : change to use threadsafe dictionary SharedDictionary portals = (SharedDictionary)DataCache.GetCache(PortalsKey) ?? new SharedDictionary(); @@ -794,34 +819,35 @@ public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) { if (portals.ContainsKey(portalId)) { - //portal found, return + // portal found, return pi = portals[portalId]; } else { try { - //if not found, get from database + // if not found, get from database pi = PortalController.Instance.GetPortal(portalId); if (pi == null) { // Home page redirect loop when using default language not en-US and first request with secondary language - //calls get portal using culture code to support + // calls get portal using culture code to support string cultureCode = PortalController.GetActivePortalLanguage(portalId); pi = PortalController.Instance.GetPortal(portalId, cultureCode); } + if (pi != null) { // Home page redirect loop when using default language not en-US and first request with secondary language - //check for correct, default language code in portal object + // check for correct, default language code in portal object string portalCultureCode = pi.CultureCode; if (portalCultureCode != null && - String.CompareOrdinal(portalCultureCode, pi.DefaultLanguage) != 0) + string.CompareOrdinal(portalCultureCode, pi.DefaultLanguage) != 0) { - //portal culture code and default culture code are not the same. - //this means we will get the incorrect home page tab id - //call back and get the correct one as per the default language + // portal culture code and default culture code are not the same. + // this means we will get the incorrect home page tab id + // call back and get the correct one as per the default language PortalInfo defaultLangPortal = PortalController.Instance.GetPortal(portalId, pi.DefaultLanguage); if (defaultLangPortal != null) { @@ -829,20 +855,23 @@ public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) } } } + if (pi != null) { - //add to dictionary and re-store in cache + // add to dictionary and re-store in cache portals.Add(pi.PortalID, pi); - DataCache.SetCache(PortalsKey, portals); //store back in dictionary + DataCache.SetCache(PortalsKey, portals); // store back in dictionary } - } -// ReSharper disable EmptyGeneralCatchClause - catch -// ReSharper restore EmptyGeneralCatchClause + } + + // ReSharper disable EmptyGeneralCatchClause + catch + + // ReSharper restore EmptyGeneralCatchClause { - //912: capture as fall back any exception resulting from doing a portal lookup in 6.x - //this happens when portalId = -1 - //no long, no handling, just passonwards with null portal + // 912: capture as fall back any exception resulting from doing a portal lookup in 6.x + // this happens when portalId = -1 + // no long, no handling, just passonwards with null portal } } } @@ -851,13 +880,14 @@ public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) { throw new NullReferenceException("No Portal Found for portalid : " + portalId.ToString()); } + return pi; } public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason r) { cacheItemRemovedReason = r; -#if (DEBUG) +#if DEBUG if (LogRemovedReason) { var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; @@ -869,16 +899,18 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason { case "DNN_" + PageIndexKey: itemName = "Page Index"; - //user profile actions + + // user profile actions try { DataCache.RemoveCache(UserProfileActionsKey); } catch (ConfigurationErrorsException) { - //do nothing, this means the web.config file was overwritten, and thus the cache - //was cleared. + // do nothing, this means the web.config file was overwritten, and thus the cache + // was cleared. } + if (v != null && v.GetType() == typeof(SharedDictionary)) { count = "Item Count: " + ((SharedDictionary)v).Values.Count.ToString(); @@ -889,7 +921,7 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason } break; - case "DNN_" + UrlDictKey: + case "DNN_" + UrlDictKey: itemName = "Friendly Url List"; if (v != null && v.GetType() == typeof(SharedDictionary>)) @@ -913,13 +945,15 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason { count = "N/a"; } + break; default: itemName = "Url Rewriter Cache Item"; - count = ""; + count = string.Empty; break; } - //add log values + + // add log values log.AddProperty("Url Rewriting Caching Message", itemName + " Cache item Removed."); log.AddProperty("Reason", cacheItemRemovedReason.ToString()); log.AddProperty("Cache Item Key", k); @@ -933,12 +967,11 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason i++; } } - //System.Diagnostics.Trace.Assert(k != null, "k == " + k); + + // System.Diagnostics.Trace.Assert(k != null, "k == " + k); LogController.Instance.AddLog(log); } #endif - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs b/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs index 6e2d6d47456..ad8f266b654 100644 --- a/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs +++ b/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; - -using DotNetNuke.Collections.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + + using DotNetNuke.Collections.Internal; + public static class CollectionExtensions { public static void LoadFromXmlFile(this Dictionary> actions, string fileName, int portalId, bool portalSpecific, ref List messages) @@ -19,13 +19,14 @@ public static void LoadFromXmlFile(this Dictionary(); if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; while (rdr.Read()) { @@ -34,14 +35,15 @@ public static void LoadFromXmlFile(this Dictionary(); actions.Add(action.TabId, tabActionCol); } + tabActionCol.Add(action); actionCount++; @@ -82,12 +85,14 @@ public static void LoadFromXmlFile(this Dictionary - /// Returns all the redirect rules for the specified portal + /// Returns all the redirect rules for the specified portal. ///
    /// /// /// /// If true, all rules belong to supplied portalId, even if not specified. /// - /// 807 : change to allow specificatoin of assumption that all rules belong to the supplied portal + /// 807 : change to allow specificatoin of assumption that all rules belong to the supplied portal. public static void LoadFromXmlFile(this Dictionary> actions, string fileName, int portalId, bool portalSpecific, ref List messages) { if (messages == null) { messages = new List(); } + if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; while (rdr.Read()) { @@ -127,19 +133,23 @@ public static void LoadFromXmlFile(this Dictionary(); int actionCount = 0; - //now set up the action + + // now set up the action string portalIdRaw = rdr.GetAttribute("rulePortalId"); if (string.IsNullOrEmpty(portalIdRaw)) { portalIdRaw = rdr.GetAttribute("portalId"); } + int rulePortalId = -1; if (portalIdRaw != null) { - Int32.TryParse(portalIdRaw, out rulePortalId); + int.TryParse(portalIdRaw, out rulePortalId); } + if (rulePortalId == portalId || rulePortalId == -1 || portalSpecific) - //if portal specific, all rules are assumed to belong to the portal + + // if portal specific, all rules are assumed to belong to the portal { string tabIdRaw = rdr.GetAttribute("tabIds"); string tabNames = rdr.GetAttribute("tabNames"); @@ -165,23 +175,25 @@ public static void LoadFromXmlFile(this Dictionary tabActionCol; if (actions.ContainsKey(action.TabId)) { @@ -192,22 +204,27 @@ public static void LoadFromXmlFile(this Dictionary(); actions.Add(action.TabId, tabActionCol); } + tabActionCol.Add(action); actionCount++; } + messages.Add(name + " redirect actions added:" + actionCount.ToString()); } + if (tabMessages.Count > 0) { messages.AddRange(tabMessages); } } + break; case XmlNodeType.EndElement: break; } } + rdr.Close(); } } @@ -218,12 +235,13 @@ public static void LoadFromXmlFile(this Dictionary(); } + if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName) { XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit + DtdProcessing = DtdProcessing.Prohibit, }; while (rdr.Read()) { @@ -237,11 +255,12 @@ public static void LoadFromXmlFile(this Dictionary(); actions.Add(action.TabId, tabActionCol); } + tabActionCol.Add(action); actionCount++; } + messages.Add(name + " rewrite actions added:" + actionCount.ToString()); } } - - + break; case XmlNodeType.EndElement: break; } } + rdr.Close(); } else @@ -307,12 +328,12 @@ public static Dictionary CreateDictionaryFromString(string delim { var dictionary = new Dictionary(); - if(!String.IsNullOrEmpty(delimitedString)) + if (!string.IsNullOrEmpty(delimitedString)) { var pairs = delimitedString.Split(pairSeparator); - foreach (string pair in pairs) + foreach (string pair in pairs) { - if (!String.IsNullOrEmpty(pair)) + if (!string.IsNullOrEmpty(pair)) { var chars = pair.Split(separator); dictionary[chars[0]] = chars[1]; diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs index ea14000f71a..c0d73733e95 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs @@ -1,86 +1,84 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml.Serialization; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls.Config { - [Serializable, XmlRoot("RewriterConfig")] + using System; + using System.IO; + using System.Xml.Serialization; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Log.EventLog; + + [Serializable] + [XmlRoot("RewriterConfig")] public class RewriterConfiguration { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (RewriterConfiguration)); - private static readonly object _threadLocker = new object(); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RewriterConfiguration)); + private static readonly object _threadLocker = new object(); private RewriterRuleCollection _rules; public RewriterRuleCollection Rules { get { - return _rules; + return this._rules; } + set { - _rules = value; + this._rules = value; } } public static RewriterConfiguration GetConfig() { - var config = new RewriterConfiguration {Rules = new RewriterRuleCollection()}; + var config = new RewriterConfiguration { Rules = new RewriterRuleCollection() }; FileStream fileReader = null; - string filePath = ""; + string filePath = string.Empty; try { - config = (RewriterConfiguration) DataCache.GetCache("RewriterConfig"); + config = (RewriterConfiguration)DataCache.GetCache("RewriterConfig"); if (config == null) { - lock (_threadLocker) - { - config = (RewriterConfiguration) DataCache.GetCache("RewriterConfig"); - if (config == null) - { - filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.SiteUrls); + lock (_threadLocker) + { + config = (RewriterConfiguration)DataCache.GetCache("RewriterConfig"); + if (config == null) + { + filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.SiteUrls); - //Create a FileStream for the Config file - fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); - var doc = new XPathDocument(fileReader); - config = new RewriterConfiguration {Rules = new RewriterRuleCollection()}; - foreach (XPathNavigator nav in doc.CreateNavigator().Select("RewriterConfig/Rules/RewriterRule")) - { - var rule = new RewriterRule - { - LookFor = nav.SelectSingleNode("LookFor").Value, - SendTo = nav.SelectSingleNode("SendTo").Value - }; - config.Rules.Add(rule); - } - if (File.Exists(filePath)) - { - //Set back into Cache - DataCache.SetCache("RewriterConfig", config, new DNNCacheDependency(filePath)); - } - } - } + // Create a FileStream for the Config file + fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); + var doc = new XPathDocument(fileReader); + config = new RewriterConfiguration { Rules = new RewriterRuleCollection() }; + foreach (XPathNavigator nav in doc.CreateNavigator().Select("RewriterConfig/Rules/RewriterRule")) + { + var rule = new RewriterRule + { + LookFor = nav.SelectSingleNode("LookFor").Value, + SendTo = nav.SelectSingleNode("SendTo").Value, + }; + config.Rules.Add(rule); + } + + if (File.Exists(filePath)) + { + // Set back into Cache + DataCache.SetCache("RewriterConfig", config, new DNNCacheDependency(filePath)); + } + } + } } } catch (Exception ex) { - //log it - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + // log it + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("UrlRewriter.RewriterConfiguration", "GetConfig Failed"); log.AddProperty("FilePath", filePath); log.AddProperty("ExceptionMessage", ex.Message); @@ -91,10 +89,11 @@ public static RewriterConfiguration GetConfig() { if (fileReader != null) { - //Close the Reader + // Close the Reader fileReader.Close(); } } + return config; } @@ -102,30 +101,31 @@ public static void SaveConfig(RewriterRuleCollection rules) { if (rules != null) { - var config = new RewriterConfiguration {Rules = rules}; - - //Create a new Xml Serializer - var ser = new XmlSerializer(typeof (RewriterConfiguration)); - - //Create a FileStream for the Config file + var config = new RewriterConfiguration { Rules = rules }; + + // Create a new Xml Serializer + var ser = new XmlSerializer(typeof(RewriterConfiguration)); + + // Create a FileStream for the Config file var filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.SiteUrls); if (File.Exists(filePath)) { - //make sure file is not read-only + // make sure file is not read-only File.SetAttributes(filePath, FileAttributes.Normal); } + using (var fileWriter = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write)) using (var writer = new StreamWriter(fileWriter)) { - //Serialize the RewriterConfiguration + // Serialize the RewriterConfiguration ser.Serialize(writer, config); - //Close the Writers + // Close the Writers writer.Close(); fileWriter.Close(); } - //Set Cache + // Set Cache DataCache.SetCache("RewriterConfig", config, new DNNCacheDependency(filePath)); } } diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs index e5967cdf676..f303f84c881 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs @@ -1,60 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text.RegularExpressions; -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls.Config { + using System; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Utilities; + [Serializable] public class RewriterRule - { - [NonSerialized] - private Regex _matchRx; - - private string _lookFor; - private string _sendTo; - + { + [NonSerialized] + private Regex _matchRx; + + private string _lookFor; + private string _sendTo; + public string LookFor { get { - return _lookFor; + return this._lookFor; } + set { - if (_lookFor != value) + if (this._lookFor != value) { - _lookFor = value; - _matchRx = null; + this._lookFor = value; + this._matchRx = null; } } - } - + } + public string SendTo { get { - return _sendTo; + return this._sendTo; } + set { - _sendTo = value; + this._sendTo = value; } - } - - //HACK: we cache this in the first call assuming applicationPath never changes during the whole lifetime of the application - // also don't worry about locking; the worst case this will be created more than once + } + + // HACK: we cache this in the first call assuming applicationPath never changes during the whole lifetime of the application + // also don't worry about locking; the worst case this will be created more than once public Regex GetRuleRegex(string applicationPath) { - return _matchRx ?? (_matchRx = - RegexUtils.GetCachedRegex("^" + RewriterUtils.ResolveUrl(applicationPath, LookFor) + "$", + return this._matchRx ?? (this._matchRx = + RegexUtils.GetCachedRegex( + "^" + RewriterUtils.ResolveUrl(applicationPath, this.LookFor) + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)); } } diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs index a93d244041a..b15a49f476e 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls.Config { + using System; + using System.Collections; + [Serializable] public class RewriterRuleCollection : CollectionBase { @@ -18,17 +13,18 @@ public virtual RewriterRule this[int index] { get { - return (RewriterRule) List[index]; + return (RewriterRule)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } public void Add(RewriterRule r) { - InnerList.Add(r); + this.InnerList.Add(r); } } } diff --git a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs index 9d80daf51f3..cdbc03c5243 100644 --- a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs +++ b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs @@ -1,29 +1,96 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + internal static class CustomUrlDictController - { - #region Private Methods + { + /// + /// returns a tabId indexed dictionary of Friendly Urls. + /// + /// + /// + /// + /// + /// + /// + /// + internal static SharedDictionary> FetchCustomUrlDictionary( + int portalId, + bool forceRebuild, + bool bypassCache, + FriendlyUrlSettings settings, + out SharedDictionary customAliasForTabs, + Guid parentTraceId) + { + SharedDictionary> urlDict; + + // this contains a list of all tabs for all the portals that have been retrieved + ConcurrentBag urlPortals; // this contains a list of the portals that have been retrieved + + // get the objects from the cache + var cc = new CacheController(); + cc.GetFriendlyUrlIndexFromCache(out urlDict, out urlPortals, out customAliasForTabs); + + if (urlDict != null && forceRebuild == false && bypassCache == false) + { + if (urlPortals == null) + + // no portals retrieved from cache, but was a dictionary. Bit weird, but we'll run with it + { + urlPortals = new ConcurrentBag(); + } + // check to see if this portal has been included in the dict + if (urlPortals.Contains(portalId) == false) + { + // ok, there is a url dictionary, but this portal isn't in it, so + // put it in and get the urls for this portal + // this call appends extra portals to the list + urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); + urlPortals.Add(portalId); + + cc.StoreFriendlyUrlIndexInCache( + urlDict, + urlPortals, + customAliasForTabs, settings, + "Portal Id " + portalId.ToString() + " added to index."); + } + } + else // either values are null (Not in cache) or we want to force the rebuild, or we want to bypass the cache + { + // rebuild the dictionary for this portal + urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); + urlPortals = new ConcurrentBag { portalId }; // always rebuild the portal list + if (bypassCache == false) // if we are to cache this item (byPassCache = false) + { + // cache these items + string reason = forceRebuild ? "Force Rebuild of Index" : "Index not in cache"; + cc.StoreFriendlyUrlIndexInCache(urlDict, urlPortals, customAliasForTabs, settings, reason); + } + } + + return urlDict; + } + + internal static void InvalidateDictionary() + { + CacheController.FlushPageIndexFromCache(); + } + /// /// Returns a list of tab and redirects from the database, for the specified portal - /// Assumes that the dictionary should have any existing items replaced if the portalid is specified + /// Assumes that the dictionary should have any existing items replaced if the portalid is specified /// and the portal tabs already exist in the dictionary. /// /// @@ -31,35 +98,36 @@ internal static class CustomUrlDictController /// /// /// - /// Each dictionary entry in the return value is a complex data type of another dictionary that is indexed by the url culture. If there is + /// Each dictionary entry in the return value is a complex data type of another dictionary that is indexed by the url culture. If there is /// only one culture for the Url, it will be that culture. /// /// - private static SharedDictionary> BuildUrlDictionary(SharedDictionary> existingTabs, - int portalId, - FriendlyUrlSettings settings, - ref SharedDictionary customAliasTabs) + private static SharedDictionary> BuildUrlDictionary( + SharedDictionary> existingTabs, + int portalId, + FriendlyUrlSettings settings, + ref SharedDictionary customAliasTabs) { - //fetch tabs with redirects + // fetch tabs with redirects var tabs = FriendlyUrlController.GetTabs(portalId, false, null, settings); if (existingTabs == null) { existingTabs = new SharedDictionary>(); } + if (customAliasTabs == null) { customAliasTabs = new SharedDictionary(); } - - - //go through each tab in the found list + + // go through each tab in the found list foreach (TabInfo tab in tabs.Values) { - //check the custom alias tabs collection and add to the dictionary where necessary + // check the custom alias tabs collection and add to the dictionary where necessary foreach (var customAlias in tab.CustomAliases) { string key = tab.TabID.ToString() + ":" + customAlias.Key; - using (customAliasTabs.GetWriteLock()) //obtain write lock on custom alias Tabs + using (customAliasTabs.GetWriteLock()) // obtain write lock on custom alias Tabs { if (customAliasTabs.ContainsKey(key) == false) { @@ -73,10 +141,11 @@ private static SharedDictionary> BuildUrlD if (redirect.HttpStatus == "200") { string url = redirect.Url; - //770 : add in custom alias into the tab path for the custom Urls + + // 770 : add in custom alias into the tab path for the custom Urls if (redirect.PortalAliasUsage != PortalAliasUsageType.Default && redirect.PortalAliasId > 0) { - //there is a custom http alias specified for this portal alias + // there is a custom http alias specified for this portal alias PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAliasByPortalAliasID(redirect.PortalAliasId); if (alias != null) { @@ -84,11 +153,12 @@ private static SharedDictionary> BuildUrlD url = customHttpAlias + "::" + url; } } + string cultureKey = redirect.CultureCode.ToLowerInvariant(); var locales = LocaleController.Instance.GetLocales(portalId).Values; - if (String.IsNullOrEmpty(cultureKey)) + if (string.IsNullOrEmpty(cultureKey)) { - //Add entry for each culture + // Add entry for each culture foreach (Locale locale in locales) { AddEntryToDictionary(existingTabs, portalId, tab, locale.Code.ToLowerInvariant(), url); @@ -101,11 +171,10 @@ private static SharedDictionary> BuildUrlD } } } + return existingTabs; - } - - #endregion - + } + private static void AddEntryToDictionary(SharedDictionary> existingTabs, int portalId, TabInfo tab, string cultureKey, string url) { int tabid = tab.TabID; @@ -118,21 +187,23 @@ private static void AddEntryToDictionary(SharedDictionary entry = existingTabs[tabid]; - //replace tab if existing but was retreieved from tabs call + + // replace tab if existing but was retreieved from tabs call if (tab.PortalID == portalId || portalId == -1) { using (entry.GetWriteLock()) { if (entry.ContainsKey(cultureKey) == false) { - //add the culture and set in parent dictionary - //871 : use lower case culture code as key + // add the culture and set in parent dictionary + // 871 : use lower case culture code as key entry.Add(cultureKey, url); existingTabs[tabid] = entry; } @@ -140,77 +211,6 @@ private static void AddEntryToDictionary(SharedDictionary - /// returns a tabId indexed dictionary of Friendly Urls - ///
    - /// - /// - /// - /// - /// - /// - /// - internal static SharedDictionary> FetchCustomUrlDictionary(int portalId, - bool forceRebuild, - bool bypassCache, - FriendlyUrlSettings settings, - out SharedDictionary customAliasForTabs, - Guid parentTraceId) - { - SharedDictionary> urlDict; - //this contains a list of all tabs for all the portals that have been retrieved - ConcurrentBag urlPortals; //this contains a list of the portals that have been retrieved - //get the objects from the cache - var cc = new CacheController(); - cc.GetFriendlyUrlIndexFromCache(out urlDict, out urlPortals, out customAliasForTabs); - - if (urlDict != null && forceRebuild == false && bypassCache == false) - { - if (urlPortals == null) - //no portals retrieved from cache, but was a dictionary. Bit weird, but we'll run with it - { - urlPortals = new ConcurrentBag(); - } - - //check to see if this portal has been included in the dict - if (urlPortals.Contains(portalId) == false) - { - //ok, there is a url dictionary, but this portal isn't in it, so - //put it in and get the urls for this portal - //this call appends extra portals to the list - urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); - urlPortals.Add(portalId); - - cc.StoreFriendlyUrlIndexInCache(urlDict, - urlPortals, - customAliasForTabs, settings, - "Portal Id " + portalId.ToString() + " added to index."); - } - } - else //either values are null (Not in cache) or we want to force the rebuild, or we want to bypass the cache - { - //rebuild the dictionary for this portal - urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); - urlPortals = new ConcurrentBag { portalId }; //always rebuild the portal list - if (bypassCache == false) //if we are to cache this item (byPassCache = false) - { - //cache these items - string reason = forceRebuild ? "Force Rebuild of Index" : "Index not in cache"; - cc.StoreFriendlyUrlIndexInCache(urlDict, urlPortals, customAliasForTabs, settings, reason); - } - } - return urlDict; - } - - internal static void InvalidateDictionary() - { - CacheController.FlushPageIndexFromCache(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Urls/DNNPageForwardType.cs b/DNN Platform/Library/Entities/Urls/DNNPageForwardType.cs index 058a32d63b4..07ee6e89a84 100644 --- a/DNN Platform/Library/Entities/Urls/DNNPageForwardType.cs +++ b/DNN Platform/Library/Entities/Urls/DNNPageForwardType.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum DNNPageForwardType { NoForward, Redirect302, - Redirect301 + Redirect301, } } diff --git a/DNN Platform/Library/Entities/Urls/DeletedTabHandlingType.cs b/DNN Platform/Library/Entities/Urls/DeletedTabHandlingType.cs index 1466ffe53e0..25ab75d2162 100644 --- a/DNN Platform/Library/Entities/Urls/DeletedTabHandlingType.cs +++ b/DNN Platform/Library/Entities/Urls/DeletedTabHandlingType.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum DeletedTabHandlingType { Do301RedirectToPortalHome, - Do404Error + Do404Error, } } diff --git a/DNN Platform/Library/Entities/Urls/DupKeyCheck.cs b/DNN Platform/Library/Entities/Urls/DupKeyCheck.cs index f7d19cd7d6e..ed218a86555 100644 --- a/DNN Platform/Library/Entities/Urls/DupKeyCheck.cs +++ b/DNN Platform/Library/Entities/Urls/DupKeyCheck.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { /// @@ -11,15 +11,18 @@ internal class DupKeyCheck { public DupKeyCheck(string tabKey, string tabIdOriginal, string tabPath, bool isDeleted) { - TabKey = tabKey; - TabIdOriginal = tabIdOriginal; - TabPath = tabPath; - IsDeleted = isDeleted; + this.TabKey = tabKey; + this.TabIdOriginal = tabIdOriginal; + this.TabPath = tabPath; + this.IsDeleted = isDeleted; } public string TabKey { get; set; } + public string TabIdOriginal { get; set; } + public string TabPath { get; set; } + public bool IsDeleted { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs index 1da790170b5..2ca2945b421 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs @@ -1,35 +1,61 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Data; -using System.Text; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Data; + using System.Text; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + /// /// This abstract class is to provide a inherited base class for a custom module friendly url provider. All public methods must be overridden to provide the basis for a custom module provider. /// [Serializable] public abstract class ExtensionUrlProvider { - public ExtensionUrlProviderInfo ProviderConfig { get; internal set; } - - #region Protected Methods + public ExtensionUrlProviderInfo ProviderConfig { get; internal set; } + + /// + /// When true, output Urls from the provider for the specified portalId always include the current DotNetNuke page path (ie example.com/pagename/friendlyUrl) + /// When false, output Urls from the provider for the specified portalId may sometimes not include the current DotNetNUke page path (ie example.com/friendlyUrl). + /// + /// + /// Defaults to true. Must be set to false by the provider if any call to the 'ChangeFriendlyUrl' method results in the output + /// parameter 'useDnnPagePath' is false. If 'false' is possible, then 'false' must be returned in this method. + /// + /// + public abstract bool AlwaysUsesDnnPagePath(int portalId); + /// + /// Generates a new friendly Url based on the parameters supplied. + /// + /// The current Tab the Friendly Url is for. + /// The current friendly Url Path (minus alias) as generated by the Advanced Friendly Url provider. + /// The current friendly Url options that apply to the current portal, as configured within the Extension Url Provider settings. These include space replacement values and other settings which should be incorporated into the Friendly Url generation. + /// The 'pageName' value that comes from the FriendlyUrl API of DNN. Normally this is the 'default.aspx' value (DotNetNuke.Common.Globals.glbDefaultPage). A value of 'default.aspx' is discarded. However, it may be a different value for other modules and if not default.aspx will be appended to the end of the Url. + /// This is a ref parameter, so it can either be left as-is, or changed to default.aspx or "" if no specific value is required. + /// Output parameter, must be set by module Friendly Url Provider. If true, the /pagename/ part of the Url will be removed, and the Url path will be relative from the site root (example.com/custom-module-path instead of example.com/pagename/custom-module-path). + /// A list of information messages used for both debug output and UI information. Add any informational message to this collection if desired. + /// Note using 'useDnnPagePath' = true requires having a specific tab returned from the TransformFriendlyUrlToQueryString below. Usage of the 'useDnnPagePath' implies the TransformFriendlyUrlToQueryString method returns a ?tabid=xx value in the querystring. + /// It also means the provider level property 'AlwaysUsesDnnPagePath' must return 'false'. + /// Friendly Url for specified values. Return friendlyUrlPath if no change is made. + public abstract string ChangeFriendlyUrl( + TabInfo tab, + string friendlyUrlPath, + FriendlyUrlOptions options, + string cultureCode, + ref string endingPageName, + out bool useDnnPagePath, + ref List messages); + protected string CleanNameForUrl(string urlValue, FriendlyUrlOptions options) { bool changed; @@ -47,7 +73,7 @@ protected string CleanNameForUrl(string urlValue, FriendlyUrlOptions options, ou protected string CreateQueryStringFromParameters(string[] urlParms, int skipUpToPosition) { - string result = ""; + string result = string.Empty; int i = 0; bool odd = true; int size = urlParms.GetUpperBound(0) - skipUpToPosition; @@ -56,7 +82,7 @@ protected string CreateQueryStringFromParameters(string[] urlParms, int skipUpTo var qs = new StringBuilder(urlParms.GetUpperBound(0)); foreach (string urlPathPart in urlParms) { - if (i > skipUpToPosition) //skip over the parts we don't want + if (i > skipUpToPosition) // skip over the parts we don't want { if (odd) { @@ -66,57 +92,27 @@ protected string CreateQueryStringFromParameters(string[] urlParms, int skipUpTo { qs.Append("=" + urlPathPart); } - //switch odd/even + + // switch odd/even odd = !odd; } + i++; } + result = qs.ToString(); } + return result; } protected string EnsureLeadingChar(string leading, string path) { return FriendlyUrlController.EnsureLeadingChar(leading, path); - } - - #endregion - - #region Abstract Methods - - /// - /// When true, output Urls from the provider for the specified portalId always include the current DotNetNuke page path (ie example.com/pagename/friendlyUrl) - /// When false, output Urls from the provider for the specified portalId may sometimes not include the current DotNetNUke page path (ie example.com/friendlyUrl) - /// - /// - /// Defaults to true. Must be set to false by the provider if any call to the 'ChangeFriendlyUrl' method results in the output - /// parameter 'useDnnPagePath' is false. If 'false' is possible, then 'false' must be returned in this method. - /// - public abstract bool AlwaysUsesDnnPagePath(int portalId); - - /// - /// Generates a new friendly Url based on the parameters supplied - /// - /// The current Tab the Friendly Url is for - /// The current friendly Url Path (minus alias) as generated by the Advanced Friendly Url provider - /// The current friendly Url options that apply to the current portal, as configured within the Extension Url Provider settings. These include space replacement values and other settings which should be incorporated into the Friendly Url generation. - /// The 'pageName' value that comes from the FriendlyUrl API of DNN. Normally this is the 'default.aspx' value (DotNetNuke.Common.Globals.glbDefaultPage). A value of 'default.aspx' is discarded. However, it may be a different value for other modules and if not default.aspx will be appended to the end of the Url. - /// This is a ref parameter, so it can either be left as-is, or changed to default.aspx or "" if no specific value is required. - /// Output parameter, must be set by module Friendly Url Provider. If true, the /pagename/ part of the Url will be removed, and the Url path will be relative from the site root (example.com/custom-module-path instead of example.com/pagename/custom-module-path) - /// A list of information messages used for both debug output and UI information. Add any informational message to this collection if desired. - /// Note using 'useDnnPagePath' = true requires having a specific tab returned from the TransformFriendlyUrlToQueryString below. Usage of the 'useDnnPagePath' implies the TransformFriendlyUrlToQueryString method returns a ?tabid=xx value in the querystring. - /// It also means the provider level property 'AlwaysUsesDnnPagePath' must return 'false' - /// Friendly Url for specified values. Return friendlyUrlPath if no change is made. - public abstract string ChangeFriendlyUrl(TabInfo tab, - string friendlyUrlPath, - FriendlyUrlOptions options, - string cultureCode, - ref string endingPageName, - out bool useDnnPagePath, - ref List messages); + } + /// - /// + /// /// /// /// @@ -125,28 +121,29 @@ public abstract string ChangeFriendlyUrl(TabInfo tab, /// /// /// - public abstract bool CheckForRedirect(int tabId, - int portalid, - string httpAlias, - Uri requestUri, - NameValueCollection queryStringCol, - FriendlyUrlOptions options, - out string redirectLocation, - ref List messages); + public abstract bool CheckForRedirect( + int tabId, + int portalid, + string httpAlias, + Uri requestUri, + NameValueCollection queryStringCol, + FriendlyUrlOptions options, + out string redirectLocation, + ref List messages); /// /// This module returns any custom settings for the provider in a key/value pair. This is used when any customised settings are saved to the web.config file. /// - /// A dictionary of key/value pairs, where the key represents the web.config attribute name, and the value is the value to be stored in the web.config file + /// A dictionary of key/value pairs, where the key represents the web.config attribute name, and the value is the value to be stored in the web.config file. /// Note: the key values are case sensitive, and should match any values read from the attributes collection in the provider constructor. If the provider has no custom attributes, return null or an empty dictionary. To remove a setting, add the value as a null. Null values in the dictionary are removed as attributes. public abstract Dictionary GetProviderPortalSettings(); /// /// Transforms a friendly Url into a querystring. Used as input into the rewriting process, after the Url Rewriting process has identified the correct DNN Page. /// - /// string array of the friendly Url Path elements, separated by / - /// TabId of page the Friendly Url - /// PortalId of the Friendly Url + /// string array of the friendly Url Path elements, separated by /. + /// TabId of page the Friendly Url. + /// PortalId of the Friendly Url. /// This method will be only called if there is no match between the Page Index entries this Provider supplies via the 'CreatePageIndex' method. This method is called /// when a DNN page match is found in the requested path, and there are other parameters behind the page path. You should only return a TabId in the querystring, when the ChangeFriendlyUrl function is returning 'true' for the output value of 'useDnnPagePath'. /// @@ -155,23 +152,20 @@ public abstract bool CheckForRedirect(int tabId, /// Warning: It's unwise to do a specific database lookup for each call of this method. This method needs to be high-performance so should use a stateless method (ie, regex parse) or, if looking up database values, cached hashtables or thread-safe dictionaries. /// /// Querystring value in key=value format, which will be used as an input to the rewriting function. - public abstract string TransformFriendlyUrlToQueryString(string[] urlParms, - int tabId, int portalId, - FriendlyUrlOptions options, - string cultureCode, - PortalAliasInfo portalAlias, - ref List messages, - out int status, - out string location); - - #endregion - - #region Public Methods - + public abstract string TransformFriendlyUrlToQueryString( + string[] urlParms, + int tabId, int portalId, + FriendlyUrlOptions options, + string cultureCode, + PortalAliasInfo portalAlias, + ref List messages, + out int status, + out string location); + /// - /// This method is called to check whether to do a Url Rewrite on all Tabs specified by the provider + /// This method is called to check whether to do a Url Rewrite on all Tabs specified by the provider. /// - /// The current portalId + /// The current portalId. /// True if the rewriter should be called, even if there are no Url parameters (ie, just plain DNN page Url). False if not. /// Does not affect the calling of this provider when there are parameters supplied in the Url - that is determined by the tabIds property /// of the provider. @@ -183,8 +177,6 @@ public virtual bool AlwaysCallForRewrite(int portalId) public string EnsureNotLeadingChar(string leading, string path) { return FriendlyUrlController.EnsureNotLeadingChar(leading, path); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs index 47db7d5de1a..cc2cadf9d66 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs @@ -1,116 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Data; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Caching; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Services.Log.EventLog; - -using Assembly = System.Reflection.Assembly; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Data; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Services.Log.EventLog; + + using Assembly = System.Reflection.Assembly; + public class ExtensionUrlProviderController { private static readonly object providersBuildLock = new object(); - private static readonly Regex RewrittenUrlRegex = new Regex(@"(?(?:\?|&)tabid=\d+)(?&[^=]+=[^&]*)*", - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - - #region Private Methods - - private static void ClearCache() - { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - ClearCache(portal.PortalID); - } - } - - private static void ClearCache(int portalId) + private static readonly Regex RewrittenUrlRegex = new Regex( + @"(?(?:\?|&)tabid=\d+)(?&[^=]+=[^&]*)*", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + + public static void DeleteProvider(ExtensionUrlProviderInfo urlProvider) { - var cacheKey = String.Format("ExtensionUrlProviders_{0}", portalId); - DataCache.RemoveCache(cacheKey); + DataProvider.Instance().DeleteExtensionUrlProvider(urlProvider.ExtensionUrlProviderId); + ClearCache(); } - - /// - /// Returns the providers to call. Returns tabid matches first, and any portal id matches after that. - /// - /// - /// - /// - /// - /// - private static List GetProvidersToCall(int tabId, - int portalId, - FriendlyUrlSettings settings, - Guid parentTraceId) + public static void DisableProvider(int providerId, int portalId) { - List providers; - - //887 : introduce lockable code to prevent caching race errors - lock (providersBuildLock) - { - bool definitelyNoProvider; - //887 : use cached list of tabs instead of per-tab cache of provider - //get the list of providers to call based on the tab and the portal - var providersToCall = CacheController.GetProvidersForTabAndPortal(tabId, - portalId, - settings, - out definitelyNoProvider, - parentTraceId); - if (definitelyNoProvider == false && providersToCall == null) - //nothing in the cache, and we don't have a definitive 'no' that there isn't a provider - { - //get all providers for the portal - var allProviders = GetModuleProviders(portalId).Where(p => p.ProviderConfig.IsActive).ToList(); - - //store the list of tabs for this portal that have a provider attached - CacheController.StoreListOfTabsWithProviders(allProviders, portalId, settings); - - //stash the provider portals in the cache - CacheController.StoreModuleProvidersForPortal(portalId, settings, allProviders); - - //now check if there is a provider for this tab/portal combination - if (allProviders.Count > 0) - { - //find if a module is specific to a tab - providersToCall = new List(); - providersToCall.AddRange(allProviders); - } - } - //always return an instantiated provider collection - providers = providersToCall ?? (new List()); - } - - //return the collection of module providers - return providers; + DataProvider.Instance().UpdateExtensionUrlProvider(providerId, false); + ClearCache(portalId); } - - #endregion - - #region Internal Methods - + /// - /// Checks to see if any providers are marked as 'always call for rewrites' + /// Checks to see if any providers are marked as 'always call for rewrites'. /// /// /// @@ -123,12 +56,13 @@ internal static bool CheckForAlwaysCallProviders(int portalId, int tabId, Friend bool checkForAlwaysCallResult = false; if (alwaysCallTabids == null) { - alwaysCallTabids = new List(); //create new list - //nothing in cache, build list + alwaysCallTabids = new List(); // create new list + + // nothing in cache, build list List providers = GetModuleProviders(portalId).Where(p => p.ProviderConfig.IsActive).ToList(); foreach (ExtensionUrlProvider provider in providers) { - //check the always call property + // check the always call property if (provider.AlwaysCallForRewrite(portalId)) { if (provider.ProviderConfig.AllTabs) @@ -150,26 +84,30 @@ internal static bool CheckForAlwaysCallProviders(int portalId, int tabId, Friend } } } - //now store back in cache + + // now store back in cache CacheController.StoreAlwaysCallProviderTabs(portalId, alwaysCallTabids, settings); } + if (alwaysCallTabids.Contains(tabId) || alwaysCallTabids.Contains(RewriteController.AllTabsRewrite)) { checkForAlwaysCallResult = true; } + return checkForAlwaysCallResult; } - internal static bool CheckForRedirect(Uri requestUri, - UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - out string location, - ref List messages, - Guid parentTraceId) + internal static bool CheckForRedirect( + Uri requestUri, + UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + out string location, + ref List messages, + Guid parentTraceId) { bool redirected = false; - location = ""; + location = string.Empty; ExtensionUrlProvider activeProvider = null; try { @@ -180,7 +118,7 @@ internal static bool CheckForRedirect(Uri requestUri, FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); foreach (ExtensionUrlProvider provider in providersToCall) { - activeProvider = provider; //for error handling + activeProvider = provider; // for error handling redirected = provider.CheckForRedirect(result.TabId, result.PortalId, result.HttpAlias, requestUri, queryStringCol, options, out location, ref messages); @@ -195,47 +133,123 @@ internal static bool CheckForRedirect(Uri requestUri, } catch (Exception ex) { - //log module provider exception + // log module provider exception LogModuleProviderExceptionInRequest(ex, "500 Internal Server Error", activeProvider, result, messages); - //return defaults + + // return defaults redirected = false; - location = ""; + location = string.Empty; string providerName = "Unknown"; if (activeProvider != null) { providerName = activeProvider.ProviderConfig.ProviderName; } + if (result != null) { result.DebugMessages.Add("Exception in provider [" + providerName + "] :" + ex.Message); } } + return redirected; } + + private static void ClearCache() + { + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + ClearCache(portal.PortalID); + } + } + + private static void ClearCache(int portalId) + { + var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); + DataCache.RemoveCache(cacheKey); + } + + /// + /// Returns the providers to call. Returns tabid matches first, and any portal id matches after that. + /// + /// + /// + /// + /// + /// + private static List GetProvidersToCall( + int tabId, + int portalId, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + List providers; + + // 887 : introduce lockable code to prevent caching race errors + lock (providersBuildLock) + { + bool definitelyNoProvider; + + // 887 : use cached list of tabs instead of per-tab cache of provider + // get the list of providers to call based on the tab and the portal + var providersToCall = CacheController.GetProvidersForTabAndPortal( + tabId, + portalId, + settings, + out definitelyNoProvider, + parentTraceId); + if (definitelyNoProvider == false && providersToCall == null) + + // nothing in the cache, and we don't have a definitive 'no' that there isn't a provider + { + // get all providers for the portal + var allProviders = GetModuleProviders(portalId).Where(p => p.ProviderConfig.IsActive).ToList(); + + // store the list of tabs for this portal that have a provider attached + CacheController.StoreListOfTabsWithProviders(allProviders, portalId, settings); + + // stash the provider portals in the cache + CacheController.StoreModuleProvidersForPortal(portalId, settings, allProviders); + + // now check if there is a provider for this tab/portal combination + if (allProviders.Count > 0) + { + // find if a module is specific to a tab + providersToCall = new List(); + providersToCall.AddRange(allProviders); + } + } + + // always return an instantiated provider collection + providers = providersToCall ?? new List(); + } + + // return the collection of module providers + return providers; + } /// - /// Returns boolean value is any loaded providers require checking of rewrite / redirect values from the site root (ie, not dnn tab path) + /// Returns boolean value is any loaded providers require checking of rewrite / redirect values from the site root (ie, not dnn tab path). /// /// internal static bool CheckForSiteRootRewrite(int portalId, FriendlyUrlSettings settings, Guid parentTraceId) { var providers = GetProvidersToCall(RewriteController.SiteRootRewrite, portalId, settings, parentTraceId); - //list should have returned all providers with site root rewrite, but double check here in case of faulty third-party logic + // list should have returned all providers with site root rewrite, but double check here in case of faulty third-party logic return providers.Any(provider => provider.AlwaysUsesDnnPagePath(portalId) == false); } - - - internal static bool GetUrlFromExtensionUrlProviders(int portalId, - TabInfo tab, - FriendlyUrlSettings settings, - string friendlyUrlPath, - string cultureCode, - ref string endingPageName, - out string changedPath, - out bool changeToSiteRoot, - ref List messages, - Guid parentTraceId) + + internal static bool GetUrlFromExtensionUrlProviders( + int portalId, + TabInfo tab, + FriendlyUrlSettings settings, + string friendlyUrlPath, + string cultureCode, + ref string endingPageName, + out string changedPath, + out bool changeToSiteRoot, + ref List messages, + Guid parentTraceId) { bool wasChanged = false; changedPath = friendlyUrlPath; @@ -245,6 +259,7 @@ internal static bool GetUrlFromExtensionUrlProviders(int portalId, { messages = new List(); } + try { List providersToCall = GetProvidersToCall(tab.TabID, portalId, settings, @@ -252,33 +267,36 @@ internal static bool GetUrlFromExtensionUrlProviders(int portalId, FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); foreach (ExtensionUrlProvider provider in providersToCall) { - activeProvider = provider; //keep for exception purposes + activeProvider = provider; // keep for exception purposes bool useDnnPagePath; - //go through and call each provider to generate the friendly urls for the module - string customPath = provider.ChangeFriendlyUrl(tab, - friendlyUrlPath, - options, - cultureCode, - ref endingPageName, - out useDnnPagePath, - ref messages); + + // go through and call each provider to generate the friendly urls for the module + string customPath = provider.ChangeFriendlyUrl( + tab, + friendlyUrlPath, + options, + cultureCode, + ref endingPageName, + out useDnnPagePath, + ref messages); if (string.IsNullOrEmpty(endingPageName)) { - endingPageName = Globals.glbDefaultPage; //set back to default.aspx if provider cleared it + endingPageName = Globals.glbDefaultPage; // set back to default.aspx if provider cleared it } - //now check to see if a change was made or not. Don't trust the provider. + + // now check to see if a change was made or not. Don't trust the provider. if (!string.IsNullOrEmpty(customPath)) { - //was customPath any different to friendlyUrlPath? - if (String.CompareOrdinal(customPath, friendlyUrlPath) != 0) + // was customPath any different to friendlyUrlPath? + if (string.CompareOrdinal(customPath, friendlyUrlPath) != 0) { wasChanged = true; changedPath = customPath.Trim(); - changeToSiteRoot = !useDnnPagePath; //useDNNpagePath means no change to site root. + changeToSiteRoot = !useDnnPagePath; // useDNNpagePath means no change to site root. const string format = "Path returned from {0} -> path:{1}, ending Page:{2}, use Page Path:{3}"; messages.Add(string.Format(format, provider.ProviderConfig.ProviderName, customPath, endingPageName, useDnnPagePath)); - break; //first module provider to change the Url is the only one used + break; // first module provider to change the Url is the only one used } } } @@ -286,24 +304,27 @@ internal static bool GetUrlFromExtensionUrlProviders(int portalId, catch (Exception ex) { LogModuleProviderExceptionInRequest(ex, "500 Internal Server Error", activeProvider, null, messages); - //reset all values to defaults + + // reset all values to defaults wasChanged = false; changedPath = friendlyUrlPath; changeToSiteRoot = false; } + return wasChanged; } - internal static bool TransformFriendlyUrlPath(string newUrl, - string tabKeyVal, - string[] urlParms, - bool isSiteRootMatch, - ref UrlAction result, - FriendlyUrlSettings settings, - out string rewrittenUrl, - out bool newAction, - ref List messages, - Guid parentTraceId) + internal static bool TransformFriendlyUrlPath( + string newUrl, + string tabKeyVal, + string[] urlParms, + bool isSiteRootMatch, + ref UrlAction result, + FriendlyUrlSettings settings, + out string rewrittenUrl, + out bool newAction, + ref List messages, + Guid parentTraceId) { bool rewriteDone = false; rewrittenUrl = newUrl; @@ -316,15 +337,18 @@ internal static bool TransformFriendlyUrlPath(string newUrl, { tabId = RewriteController.SiteRootRewrite; } - List providersToCall = GetProvidersToCall(tabId, - result.PortalId, - settings, - parentTraceId); + + List providersToCall = GetProvidersToCall( + tabId, + result.PortalId, + settings, + parentTraceId); if (providersToCall != null && providersToCall.Count > 0) { - //now check for providers by calling the providers + // now check for providers by calling the providers int upperBound = urlParms.GetUpperBound(0); - //clean extension off parameters array + + // clean extension off parameters array var parms = new string[upperBound + 1]; Array.ConstrainedCopy(urlParms, 0, parms, 0, upperBound + 1); if (upperBound >= 0) @@ -332,64 +356,71 @@ internal static bool TransformFriendlyUrlPath(string newUrl, bool replaced; parms[upperBound] = RewriteController.CleanExtension(parms[upperBound], settings, out replaced); } - //get options from current settings + + // get options from current settings FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); foreach (ExtensionUrlProvider provider in providersToCall) { - //set active provider for exception handling + // set active provider for exception handling activeProvider = provider; - //call down to specific providers and see if we get a rewrite + + // call down to specific providers and see if we get a rewrite string location; int status; - string queryString = provider.TransformFriendlyUrlToQueryString(parms, - result.TabId, - result.PortalId, - options, - result.CultureCode, - result.PortalAlias, - ref messages, - out status, - out location); - if (status == 0 || status == 200) //either not set, or set to '200 OK'. + string queryString = provider.TransformFriendlyUrlToQueryString( + parms, + result.TabId, + result.PortalId, + options, + result.CultureCode, + result.PortalAlias, + ref messages, + out status, + out location); + if (status == 0 || status == 200) // either not set, or set to '200 OK'. { if (!string.IsNullOrEmpty(queryString) && queryString != newUrl) { rewriteDone = true; - //check for duplicate tabIds. + + // check for duplicate tabIds. string qsRemainder = null; if (Regex.IsMatch(queryString, @"tabid=\d+", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { - //930 : look for other querystring information in the rewritten Url, or invalid rewritten urls can be created - //pattern to determine which tab matches - //look for any other querystirng information in the already rewritten Url (ie language parameters) + // 930 : look for other querystring information in the rewritten Url, or invalid rewritten urls can be created + // pattern to determine which tab matches + // look for any other querystirng information in the already rewritten Url (ie language parameters) Match rewrittenUrlMatch = RewrittenUrlRegex.Match(rewrittenUrl); if (rewrittenUrlMatch.Groups["qs"].Success) { - //keep any other querystring remainders - qsRemainder = rewrittenUrlMatch.Groups["qs"].Captures.Cast().Aggregate("", (current, qsCapture) => current + qsCapture.Value); //initialise + // keep any other querystring remainders + qsRemainder = rewrittenUrlMatch.Groups["qs"].Captures.Cast().Aggregate(string.Empty, (current, qsCapture) => current + qsCapture.Value); // initialise } - //supplied value overwrites existing value, so remove from the rewritten url - rewrittenUrl = RewrittenUrlRegex.Replace(rewrittenUrl, ""); + + // supplied value overwrites existing value, so remove from the rewritten url + rewrittenUrl = RewrittenUrlRegex.Replace(rewrittenUrl, string.Empty); } + if (rewrittenUrl.Contains("?") == false) { - //use a leading ?, not a leading & + // use a leading ?, not a leading & queryString = FriendlyUrlController.EnsureNotLeadingChar("&", queryString); queryString = FriendlyUrlController.EnsureLeadingChar("?", queryString); } else { - //use a leading &, not a leading ? + // use a leading &, not a leading ? queryString = FriendlyUrlController.EnsureNotLeadingChar("?", queryString); queryString = FriendlyUrlController.EnsureLeadingChar("&", queryString); } - //add querystring onto rewritten Url + // add querystring onto rewritten Url rewrittenUrl += queryString; if (qsRemainder != null) { rewrittenUrl += qsRemainder; } + break; } } @@ -414,7 +445,8 @@ internal static bool TransformFriendlyUrlPath(string newUrl, result.Action = ActionType.Output500; break; } - newAction = true; //not doing a 200 status + + newAction = true; // not doing a 200 status break; } } @@ -422,9 +454,10 @@ internal static bool TransformFriendlyUrlPath(string newUrl, } catch (Exception ex) { - //log module provider exception + // log module provider exception LogModuleProviderExceptionInRequest(ex, "500 Internal Server Error", activeProvider, result, messages); - //reset values to initial + + // reset values to initial rewriteDone = false; rewrittenUrl = newUrl; newAction = false; @@ -433,29 +466,15 @@ internal static bool TransformFriendlyUrlPath(string newUrl, { providerName = activeProvider.ProviderConfig.ProviderName; } + if (result != null) { result.DebugMessages.Add("Exception in provider [" + providerName + "] :" + ex.Message); } } + return rewriteDone; - } - - #endregion - - #region Public Methods - - public static void DeleteProvider(ExtensionUrlProviderInfo urlProvider) - { - DataProvider.Instance().DeleteExtensionUrlProvider(urlProvider.ExtensionUrlProviderId); - ClearCache(); - } - - public static void DisableProvider(int providerId, int portalId) - { - DataProvider.Instance().UpdateExtensionUrlProvider(providerId, false); - ClearCache(portalId); - } + } public static void EnableProvider(int providerId, int portalId) { @@ -469,19 +488,21 @@ public static List GetProviders(int portalId) } /// - /// Loads the module providers + /// Loads the module providers. /// /// /// - /// Note : similar copy for UI purposes in ConfigurationController.cs + /// Note : similar copy for UI purposes in ConfigurationController.cs. public static List GetModuleProviders(int portalId) { - var cacheKey = String.Format("ExtensionUrlProviders_{0}", portalId); - var moduleProviders = CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - 60, - CacheItemPriority.High, - portalId), - c => + var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); + var moduleProviders = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + 60, + CacheItemPriority.High, + portalId), + c => { var id = (int)c.Params[0]; IDataReader dr = DataProvider.Instance().GetExtensionUrlProviders(id); @@ -511,7 +532,7 @@ public static List GetModuleProviders(int portalId) if (dr.NextResult()) { - //Setup Settings + // Setup Settings while (dr.Read()) { var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); @@ -528,7 +549,7 @@ public static List GetModuleProviders(int portalId) if (dr.NextResult()) { - //Setup Tabs + // Setup Tabs while (dr.Read()) { var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); @@ -546,7 +567,7 @@ public static List GetModuleProviders(int portalId) } finally { - //Close reader + // Close reader CBO.CloseDataReader(dr, true); } }); @@ -560,7 +581,7 @@ public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings sett { PunctuationReplacement = (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) ? settings.ReplaceSpaceWith - : String.Empty, + : string.Empty, SpaceEncoding = settings.SpaceEncodingValue, MaxUrlPathLength = 200, ConvertDiacriticChars = settings.AutoAsciiConvert, @@ -569,12 +590,12 @@ public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings sett ReplaceChars = settings.ReplaceChars, ReplaceDoubleChars = settings.ReplaceDoubleChars, ReplaceCharWithChar = settings.ReplaceCharacterDictionary, - PageExtension = settings.PageExtensionUsageType == PageExtensionUsageType.Never ? "" : settings.PageExtension + PageExtension = settings.PageExtensionUsageType == PageExtensionUsageType.Never ? string.Empty : settings.PageExtension, }; } /// - /// logs an exception related to a module provider once per cache-lifetime + /// logs an exception related to a module provider once per cache-lifetime. /// /// /// @@ -582,7 +603,7 @@ public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings sett /// /// public static void LogModuleProviderExceptionInRequest(Exception ex, string status, - ExtensionUrlProvider provider, + ExtensionUrlProvider provider, UrlAction result, List messages) { @@ -595,23 +616,27 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat moduleProviderName = provider.ProviderConfig.ProviderName; moduleProviderVersion = provider.GetType().Assembly.GetName(false).Version.ToString(); } - //this logic prevents a site logging an exception for every request made. Instead - //the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. - //create a cache key for this exception type + + // this logic prevents a site logging an exception for every request made. Instead + // the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. + // create a cache key for this exception type string cacheKey = ex.GetType().ToString(); - //see if there is an existing object logged for this exception type + + // see if there is an existing object logged for this exception type object existingEx = DataCache.GetCache(cacheKey); if (existingEx == null) { - //if there was no existing object logged for this exception type, this is a new exception + // if there was no existing object logged for this exception type, this is a new exception DateTime expire = DateTime.Now.AddHours(1); DataCache.SetCache(cacheKey, cacheKey, expire); - //just store the cache key - it doesn't really matter - //create a log event + + // just store the cache key - it doesn't really matter + // create a log event string productVer = DotNetNukeContext.Current.Application.Version.ToString(); - var log = new LogInfo {LogTypeKey = "GENERAL_EXCEPTION"}; - log.AddProperty("Url Rewriting Extension Url Provider Exception", - "Exception in Url Rewriting Process"); + var log = new LogInfo { LogTypeKey = "GENERAL_EXCEPTION" }; + log.AddProperty( + "Url Rewriting Extension Url Provider Exception", + "Exception in Url Rewriting Process"); log.AddProperty("Provider Name", moduleProviderName); log.AddProperty("Provider Version", moduleProviderVersion); log.AddProperty("Http Status", status); @@ -625,8 +650,8 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat log.AddProperty("Rewrite Result", !string.IsNullOrEmpty(result.RewritePath) ? result.RewritePath : "[no rewrite]"); - log.AddProperty("Redirect Location", string.IsNullOrEmpty(result.FinalUrl) - ? "[no redirect]" + log.AddProperty("Redirect Location", string.IsNullOrEmpty(result.FinalUrl) + ? "[no redirect]" : result.FinalUrl); log.AddProperty("Action", result.Action.ToString()); log.AddProperty("Reason", result.Reason.ToString()); @@ -644,6 +669,7 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat { msg = "[message was null]"; } + log.AddProperty("Debug Message[result] " + i.ToString(), msg); i++; } @@ -653,6 +679,7 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat { log.AddProperty("Result", "Result value null"); } + if (messages != null) { int i = 1; @@ -662,6 +689,7 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat i++; } } + log.AddProperty("Exception Type", ex.GetType().ToString()); log.AddProperty("Message", ex.Message); log.AddProperty("Stack Trace", ex.StackTrace); @@ -670,6 +698,7 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat log.AddProperty("Inner Exception Message", ex.InnerException.Message); log.AddProperty("Inner Exception Stacktrace", ex.InnerException.StackTrace); } + log.BypassBuffering = true; LogController.Instance.AddLog(log); } @@ -694,9 +723,6 @@ public static void SaveSetting(int providerId, int portalId, string settingName, { DataProvider.Instance().SaveExtensionUrlProviderSetting(providerId, portalId, settingName, settingValue); ClearCache(portalId); - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs index 6045fba549e..917e61a1dc8 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs @@ -1,33 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + [Serializable] public class ExtensionUrlProviderInfo : IHydratable { public ExtensionUrlProviderInfo() { - ExtensionUrlProviderId = -1; - Settings = new Dictionary(); - TabIds = new List(); + this.ExtensionUrlProviderId = -1; + this.Settings = new Dictionary(); + this.TabIds = new List(); } /// - /// When true, the module provider will be used for all tabs in the current portal. Including a specific tabid switches value to false. + /// Gets a value indicating whether when true, the module provider will be used for all tabs in the current portal. Including a specific tabid switches value to false. /// - public bool AllTabs { get { return TabIds.Count == 0; } } + public bool AllTabs + { + get { return this.TabIds.Count == 0; } + } /// - /// The DesktopModuleId is used to associate a particular Extension Url Provider with a specific DotNetNuke extension. + /// Gets or sets the DesktopModuleId is used to associate a particular Extension Url Provider with a specific DotNetNuke extension. /// /// /// If the Extension provider is not associated with any particular DotNetNuke extension, return null. @@ -37,7 +40,7 @@ public ExtensionUrlProviderInfo() public int ExtensionUrlProviderId { get; set; } /// - /// When true, provider is active + /// Gets or sets a value indicating whether when true, provider is active. /// public bool IsActive { get; set; } @@ -48,20 +51,20 @@ public ExtensionUrlProviderInfo() public string ProviderType { get; set; } /// - /// When true, TransformFriendlyUrl is called for every Url in the portal - /// When false, TransformFriendlyUrl is called only for tabs in the TabIds list + /// Gets or sets a value indicating whether when true, TransformFriendlyUrl is called for every Url in the portal + /// When false, TransformFriendlyUrl is called only for tabs in the TabIds list. /// public bool RewriteAllUrls { get; set; } /// - /// When true, CheckForRedirect is called for every Url in the portal - /// When false, CheckForRedirect is called only for tabs in the TabIds list + /// Gets or sets a value indicating whether when true, CheckForRedirect is called for every Url in the portal + /// When false, CheckForRedirect is called only for tabs in the TabIds list. /// public bool RedirectAllUrls { get; set; } /// - /// When true, ChangeFriendlyUrl is called for every generated Url called through the NavigateUrl API - /// When false, ChangeFriendlyUrl is called only for tabs in the TabIds list + /// Gets or sets a value indicating whether when true, ChangeFriendlyUrl is called for every generated Url called through the NavigateUrl API + /// When false, ChangeFriendlyUrl is called only for tabs in the TabIds list. /// public bool ReplaceAllUrls { get; set; } @@ -70,7 +73,7 @@ public ExtensionUrlProviderInfo() public Dictionary Settings { get; private set; } /// - /// Returns a list of TabIds where the module provider should be called when generating friendly urls + /// Gets a list of TabIds where the module provider should be called when generating friendly urls. /// public List TabIds { get; private set; } @@ -78,17 +81,16 @@ public ExtensionUrlProviderInfo() public void Fill(IDataReader dr) { - ExtensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderId"]); - PortalId = Null.SetNullInteger(dr["PortalId"]); - DesktopModuleId = Null.SetNullInteger(dr["DesktopModuleId"]); - ProviderName = Null.SetNullString(dr["ProviderName"]); - ProviderType = Null.SetNullString(dr["ProviderType"]); - SettingsControlSrc = Null.SetNullString(dr["SettingsControlSrc"]); - IsActive = Null.SetNullBoolean(dr["IsActive"]); - RewriteAllUrls = Null.SetNullBoolean(dr["RewriteAllUrls"]); - RedirectAllUrls = Null.SetNullBoolean(dr["RedirectAllUrls"]); - ReplaceAllUrls = Null.SetNullBoolean(dr["ReplaceAllUrls"]); + this.ExtensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderId"]); + this.PortalId = Null.SetNullInteger(dr["PortalId"]); + this.DesktopModuleId = Null.SetNullInteger(dr["DesktopModuleId"]); + this.ProviderName = Null.SetNullString(dr["ProviderName"]); + this.ProviderType = Null.SetNullString(dr["ProviderType"]); + this.SettingsControlSrc = Null.SetNullString(dr["SettingsControlSrc"]); + this.IsActive = Null.SetNullBoolean(dr["IsActive"]); + this.RewriteAllUrls = Null.SetNullBoolean(dr["RewriteAllUrls"]); + this.RedirectAllUrls = Null.SetNullBoolean(dr["RedirectAllUrls"]); + this.ReplaceAllUrls = Null.SetNullBoolean(dr["ReplaceAllUrls"]); } - } } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs index d4112d0d855..e78a517aa02 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs @@ -1,625 +1,609 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.ClientCapability; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.ClientCapability; + using DotNetNuke.Services.Exceptions; + public class FriendlyUrlController { - #region Constants - - private const string DisableMobileRedirectCookieName = "disablemobileredirect"; //dnn cookies - private const string DisableRedirectPresistCookieName = "disableredirectpresist"; //dnn cookies + private const string DisableMobileRedirectCookieName = "disablemobileredirect"; // dnn cookies + private const string DisableRedirectPresistCookieName = "disableredirectpresist"; // dnn cookies private const string DisableMobileRedirectQueryStringName = "nomo"; - //google uses the same name nomo=1 means do not redirect to mobile + // google uses the same name nomo=1 means do not redirect to mobile private const string MobileViewSiteCookieName = "dnn_IsMobile"; private const string DisableMobileViewCookieName = "dnn_NoMobile"; - #endregion - - #region Friendly Url Settings Control - public static FriendlyUrlSettings GetCurrentSettings(int portalId) { return new FriendlyUrlSettings(portalId); } - #endregion - - #region Friendly Url Provider methods /* - /// - /// Determines if the tab is excluded from FriendlyUrl Processing - /// - /// - /// - /// If true, we are checking for rewriting purposes, if false, we are checking for friendly Url Generating. - /// - private static bool IsExcludedFromFriendlyUrls(TabInfo tab, FriendlyUrlSettings settings, bool rewriting) - { - //note this is a duplicate of another method in RewriteController.cs - bool exclude = false; - string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLower(); - if (settings.UseBaseFriendlyUrls != null) - { - exclude = settings.UseBaseFriendlyUrls.ToLower().Contains(tabPath); - } +/// +/// Determines if the tab is excluded from FriendlyUrl Processing +/// +/// +/// +/// If true, we are checking for rewriting purposes, if false, we are checking for friendly Url Generating. +/// +private static bool IsExcludedFromFriendlyUrls(TabInfo tab, FriendlyUrlSettings settings, bool rewriting) +{ + //note this is a duplicate of another method in RewriteController.cs + bool exclude = false; + string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLower(); + if (settings.UseBaseFriendlyUrls != null) + { + exclude = settings.UseBaseFriendlyUrls.ToLower().Contains(tabPath); + } - return exclude; - } + return exclude; +} - private static void SetExclusionProperties(TabInfo tab, FriendlyUrlSettings settings) - { - string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLower(); - tab.UseBaseFriendlyUrls = settings.UseBaseFriendlyUrls != null && settings.UseBaseFriendlyUrls.ToLower().Contains(tabPath); - } +private static void SetExclusionProperties(TabInfo tab, FriendlyUrlSettings settings) +{ + string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLower(); + tab.UseBaseFriendlyUrls = settings.UseBaseFriendlyUrls != null && settings.UseBaseFriendlyUrls.ToLower().Contains(tabPath); +} - /// - /// Builds up a collection of the Friendly Urls for a tab - /// - /// The TabInfoEx object - /// Whether to add in the redirects for the 'standard' DNN urls - /// - /// The current friendly Url settings - /// Updated to insert where an ascii replacement or spaces-replaced replacement has been made (562) - private static void BuildFriendlyUrls(TabInfo tab, bool includeStdUrls, PortalSettings portalSettings, FriendlyUrlSettings settings) +/// +/// Builds up a collection of the Friendly Urls for a tab +/// +/// The TabInfoEx object +/// Whether to add in the redirects for the 'standard' DNN urls +/// +/// The current friendly Url settings +/// Updated to insert where an ascii replacement or spaces-replaced replacement has been made (562) +private static void BuildFriendlyUrls(TabInfo tab, bool includeStdUrls, PortalSettings portalSettings, FriendlyUrlSettings settings) +{ + + //unfriendly Url + if (includeStdUrls) + { + string stdUrl = Globals.glbDefaultPage + "?TabId=" + tab.TabID.ToString(); + string stdHttpStatus = "200"; + string httpAlias = portalSettings.PortalAlias.HTTPAlias; + string defaultCulture = portalSettings.DefaultLanguage; + var locales = LocaleController.Instance.GetLocales(portalSettings.PortalId); + + string baseFriendlyHttpStatus = "200"; + int seqNum = -1; + //check for custom redirects + //bool tabHasCustom200 = false; + var culturesWithCustomUrls = new List(); + if (tab.TabUrls.Count > 0) { - - //unfriendly Url - if (includeStdUrls) + //there are custom redirects for this tab + //cycle through all and collect the list of cultures where a + //custom redirect has been implemented + foreach (TabUrlInfo redirect in tab.TabUrls) { - string stdUrl = Globals.glbDefaultPage + "?TabId=" + tab.TabID.ToString(); - string stdHttpStatus = "200"; - string httpAlias = portalSettings.PortalAlias.HTTPAlias; - string defaultCulture = portalSettings.DefaultLanguage; - var locales = LocaleController.Instance.GetLocales(portalSettings.PortalId); - - string baseFriendlyHttpStatus = "200"; - int seqNum = -1; - //check for custom redirects - //bool tabHasCustom200 = false; - var culturesWithCustomUrls = new List(); - if (tab.TabUrls.Count > 0) + if (redirect.HttpStatus == "200" && !redirect.IsSystem) { - //there are custom redirects for this tab - //cycle through all and collect the list of cultures where a - //custom redirect has been implemented - foreach (TabUrlInfo redirect in tab.TabUrls) + //there is a custom redirect for this culture + //751 : use the default culture if the redirect doesn't have a valid culture set + string redirectCulture = redirect.CultureCode; + if (string.IsNullOrEmpty(redirectCulture)) { - if (redirect.HttpStatus == "200" && !redirect.IsSystem) - { - //there is a custom redirect for this culture - //751 : use the default culture if the redirect doesn't have a valid culture set - string redirectCulture = redirect.CultureCode; - if (string.IsNullOrEmpty(redirectCulture)) - { - redirectCulture = portalSettings.DefaultLanguage; - } + redirectCulture = portalSettings.DefaultLanguage; + } - if (!culturesWithCustomUrls.Contains(redirectCulture)) - { - culturesWithCustomUrls.Add(redirectCulture); - } - } + if (!culturesWithCustomUrls.Contains(redirectCulture)) + { + culturesWithCustomUrls.Add(redirectCulture); } } + } + } - //add friendly urls first (sequence number goes in reverse) - if (Host.Host.UseFriendlyUrls) + //add friendly urls first (sequence number goes in reverse) + if (Host.Host.UseFriendlyUrls) + { + //determine whether post process or use base by looking at current settings + SetExclusionProperties(tab, settings); + + //friendly Urls are switched on + //std = default.aspx?tabId=xx + //and page not excluded from redirects + bool onlyBaseUrls = tab.UseBaseFriendlyUrls; + //use base means only use Base Friendly Urls (searchFriendly) + + //if not using base urls, and redirect all unfriendly, and not in the list of pages to not redirect + if (!onlyBaseUrls & settings.RedirectUnfriendly && !tab.DoNotRedirect) + { + //all base urls will be 301 + baseFriendlyHttpStatus = "301"; + stdHttpStatus = "301"; + //default url 301'd if friendly Urls on and redirect unfriendly switch 'on' + } + var localeCodes = new List(); + if (!string.IsNullOrEmpty(tab.CultureCode)) + { + //the tab culture is specified, so skip all locales and only process those for the locale + localeCodes.Add(tab.CultureCode); + } + else + { + localeCodes.AddRange(from Locale lc in locales.Values select lc.Code); + } + foreach (string cultureCode in localeCodes) //go through and generate the urls for each language + { + string langQs = "&language=" + cultureCode; + if (cultureCode == defaultCulture) { - //determine whether post process or use base by looking at current settings - SetExclusionProperties(tab, settings); + langQs = ""; + } + + var improvedFriendlyUrls = new Dictionary(); + //call friendly url provider to get current friendly url (uses all settings) + string baseFriendlyUrl = GetFriendlyUrl(tab, + stdUrl + langQs, + Globals.glbDefaultPage, + portalSettings.PortalAlias.HTTPAlias, + settings); - //friendly Urls are switched on - //std = default.aspx?tabId=xx - //and page not excluded from redirects - bool onlyBaseUrls = tab.UseBaseFriendlyUrls; - //use base means only use Base Friendly Urls (searchFriendly) + if (onlyBaseUrls == false) + { + //get the improved friendly Url for this tab + //improved friendly Url = 'human friendly' url generated by Advanced Friendly Url Provider : note call is made to ignore custom redirects + //this temp switch is to clear out the useBaseFriendlyUrls setting. The post-process setting means the generated + //friendly url will be a base url, and then replaced later when the page is finished. Because we want to pretend we're + //looking at the finished product, we clear out the value and restore it after the friendly url generation + string improvedFriendlyUrl = GetImprovedFriendlyUrl(tab, + stdUrl + langQs, + Globals.glbDefaultPage, + portalSettings, + true, + settings); - //if not using base urls, and redirect all unfriendly, and not in the list of pages to not redirect - if (!onlyBaseUrls & settings.RedirectUnfriendly && !tab.DoNotRedirect) + improvedFriendlyUrls.Add("hfurl:" + cultureCode, improvedFriendlyUrl); + //get any other values + bool autoAsciiConvert = false; + bool replaceSpacesWith = false; + if (settings.AutoAsciiConvert) { - //all base urls will be 301 - baseFriendlyHttpStatus = "301"; - stdHttpStatus = "301"; - //default url 301'd if friendly Urls on and redirect unfriendly switch 'on' + //check to see that the ascii conversion would actually produce a different result + string changedTabPath = ReplaceDiacritics(tab.TabPath); + if (changedTabPath != tab.TabPath) + { + autoAsciiConvert = true; + } + } + if (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) + { + if (tab.TabName.Contains(" ")) + { + string tabPath = BuildTabPathWithReplacement(tab, " ", settings.ReplaceSpaceWith); + if (tabPath != tab.TabPath) + { + replaceSpacesWith = true; + } + } } - var localeCodes = new List(); - if (!string.IsNullOrEmpty(tab.CultureCode)) + if (autoAsciiConvert && replaceSpacesWith) { - //the tab culture is specified, so skip all locales and only process those for the locale - localeCodes.Add(tab.CultureCode); + string replaceSpaceWith = settings.ReplaceSpaceWith; + settings.ReplaceSpaceWith = "None"; + settings.AutoAsciiConvert = false; + //get one without auto ascii convert, and replace spaces off + string impUrl = GetImprovedFriendlyUrl(tab, + stdUrl + langQs, + Globals.glbDefaultPage, + httpAlias, + true, + settings); + improvedFriendlyUrls.Add("aac:rsw:" + cultureCode, impUrl); + settings.AutoAsciiConvert = true; + //now get one with ascii convert on, and replace spaces still off + //impUrl = GetImprovedFriendlyUrl(tab, stdUrl, Globals.glbDefaultPage, httpAlias, true, settings); + //improvedFriendlyUrls.Add("aac", impUrl); + settings.ReplaceSpaceWith = replaceSpaceWith; } - else + if (autoAsciiConvert && !replaceSpacesWith) { - localeCodes.AddRange(from Locale lc in locales.Values select lc.Code); + settings.AutoAsciiConvert = false; + //get one with auto ascii convert off + string impUrl = GetImprovedFriendlyUrl(tab, + stdUrl + langQs, + Globals.glbDefaultPage, + httpAlias, + true, + settings); + improvedFriendlyUrls.Add("aac:" + cultureCode, impUrl); + settings.AutoAsciiConvert = true; } - foreach (string cultureCode in localeCodes) //go through and generate the urls for each language + if (!autoAsciiConvert && replaceSpacesWith) { - string langQs = "&language=" + cultureCode; - if (cultureCode == defaultCulture) - { - langQs = ""; - } - - var improvedFriendlyUrls = new Dictionary(); - //call friendly url provider to get current friendly url (uses all settings) - string baseFriendlyUrl = GetFriendlyUrl(tab, - stdUrl + langQs, + string replaceSpaceWith = settings.ReplaceSpaceWith; + settings.ReplaceSpaceWith = "None"; + //get one with replace spaces off + string impUrl = GetImprovedFriendlyUrl(tab, + stdUrl + langQs, Globals.glbDefaultPage, - portalSettings.PortalAlias.HTTPAlias, + httpAlias, + true, settings); - - if (onlyBaseUrls == false) + improvedFriendlyUrls.Add("rsw:" + cultureCode, impUrl); + settings.ReplaceSpaceWith = replaceSpaceWith; + } + bool tabHasCustom200 = culturesWithCustomUrls.Contains(cultureCode); + foreach (string key in improvedFriendlyUrls.Keys) + { + string friendlyUrl = improvedFriendlyUrls[key]; + if (friendlyUrl != baseFriendlyUrl && friendlyUrl != "") { - //get the improved friendly Url for this tab - //improved friendly Url = 'human friendly' url generated by Advanced Friendly Url Provider : note call is made to ignore custom redirects - //this temp switch is to clear out the useBaseFriendlyUrls setting. The post-process setting means the generated - //friendly url will be a base url, and then replaced later when the page is finished. Because we want to pretend we're - //looking at the finished product, we clear out the value and restore it after the friendly url generation - string improvedFriendlyUrl = GetImprovedFriendlyUrl(tab, - stdUrl + langQs, - Globals.glbDefaultPage, - portalSettings, - true, - settings); - - improvedFriendlyUrls.Add("hfurl:" + cultureCode, improvedFriendlyUrl); - //get any other values - bool autoAsciiConvert = false; - bool replaceSpacesWith = false; - if (settings.AutoAsciiConvert) + //if the improved friendly Url is different to the base friendly Url, + //then we will add it in as a 'fixed' url, except if the improved friendly Url + //is actually a redirect in the first place + bool found = false; + foreach (TabUrlInfo redirect in tab.TabUrls) { - //check to see that the ascii conversion would actually produce a different result - string changedTabPath = ReplaceDiacritics(tab.TabPath); - if (changedTabPath != tab.TabPath) + //compare each redirect to the improved friendly Url + //just in case it is the same + if (String.Compare(redirect.Url, friendlyUrl, StringComparison.OrdinalIgnoreCase) == 0) { - autoAsciiConvert = true; + found = true; } } - if (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) + if (!found) { - if (tab.TabName.Contains(" ")) + //ok if hte improved friendly Url isn't a tab redirect record, + //then add in the improved friendly Url as a 'fixed' url + var predefinedRedirect = new TabUrlInfo + { + TabId = tab.TabID, + CultureCode = cultureCode + }; + if (key.StartsWith("hfurl") == false) { - string tabPath = BuildTabPathWithReplacement(tab, " ", settings.ReplaceSpaceWith); - if (tabPath != tab.TabPath) + //this means it's not the actual url, it's either a spaces replace, + //auto ascii or both output. It should be a 301 unless redirectunfriendly + //is off, or the page is excluded from redirects + if (settings.RedirectUnfriendly && !tab.DoNotRedirect) { - replaceSpacesWith = true; + predefinedRedirect.HttpStatus = "301"; //redirect to custom url } - } - } - if (autoAsciiConvert && replaceSpacesWith) - { - string replaceSpaceWith = settings.ReplaceSpaceWith; - settings.ReplaceSpaceWith = "None"; - settings.AutoAsciiConvert = false; - //get one without auto ascii convert, and replace spaces off - string impUrl = GetImprovedFriendlyUrl(tab, - stdUrl + langQs, - Globals.glbDefaultPage, - httpAlias, - true, - settings); - improvedFriendlyUrls.Add("aac:rsw:" + cultureCode, impUrl); - settings.AutoAsciiConvert = true; - //now get one with ascii convert on, and replace spaces still off - //impUrl = GetImprovedFriendlyUrl(tab, stdUrl, Globals.glbDefaultPage, httpAlias, true, settings); - //improvedFriendlyUrls.Add("aac", impUrl); - settings.ReplaceSpaceWith = replaceSpaceWith; - } - if (autoAsciiConvert && !replaceSpacesWith) - { - settings.AutoAsciiConvert = false; - //get one with auto ascii convert off - string impUrl = GetImprovedFriendlyUrl(tab, - stdUrl + langQs, - Globals.glbDefaultPage, - httpAlias, - true, - settings); - improvedFriendlyUrls.Add("aac:" + cultureCode, impUrl); - settings.AutoAsciiConvert = true; - } - if (!autoAsciiConvert && replaceSpacesWith) - { - string replaceSpaceWith = settings.ReplaceSpaceWith; - settings.ReplaceSpaceWith = "None"; - //get one with replace spaces off - string impUrl = GetImprovedFriendlyUrl(tab, - stdUrl + langQs, - Globals.glbDefaultPage, - httpAlias, - true, - settings); - improvedFriendlyUrls.Add("rsw:" + cultureCode, impUrl); - settings.ReplaceSpaceWith = replaceSpaceWith; - } - bool tabHasCustom200 = culturesWithCustomUrls.Contains(cultureCode); - foreach (string key in improvedFriendlyUrls.Keys) - { - string friendlyUrl = improvedFriendlyUrls[key]; - if (friendlyUrl != baseFriendlyUrl && friendlyUrl != "") - { - //if the improved friendly Url is different to the base friendly Url, - //then we will add it in as a 'fixed' url, except if the improved friendly Url - //is actually a redirect in the first place - bool found = false; - foreach (TabUrlInfo redirect in tab.TabUrls) + else { - //compare each redirect to the improved friendly Url - //just in case it is the same - if (String.Compare(redirect.Url, friendlyUrl, StringComparison.OrdinalIgnoreCase) == 0) - { - found = true; - } - } - if (!found) - { - //ok if hte improved friendly Url isn't a tab redirect record, - //then add in the improved friendly Url as a 'fixed' url - var predefinedRedirect = new TabUrlInfo - { - TabId = tab.TabID, - CultureCode = cultureCode - }; - if (key.StartsWith("hfurl") == false) - { - //this means it's not the actual url, it's either a spaces replace, - //auto ascii or both output. It should be a 301 unless redirectunfriendly - //is off, or the page is excluded from redirects - if (settings.RedirectUnfriendly && !tab.DoNotRedirect) - { - predefinedRedirect.HttpStatus = "301"; //redirect to custom url - } - else - { - predefinedRedirect.HttpStatus = "200"; //allow it to work - } - } - else - { - //the hfurl key is the base human friendly url - if (tabHasCustom200 && (settings.RedirectUnfriendly && !tab.DoNotRedirect)) - { - predefinedRedirect.HttpStatus = "301"; - } - else - { - predefinedRedirect.HttpStatus = "200"; - //if no redirects, or not redirecting unfriendly, then 200 is OK - } - } - predefinedRedirect.Url = friendlyUrl; - predefinedRedirect.IsSystem = true; - predefinedRedirect.SeqNum = seqNum; - tab.TabUrls.Insert(0, predefinedRedirect); - seqNum--; + predefinedRedirect.HttpStatus = "200"; //allow it to work } } else { - //improved Friendly Url same as base Friendly Url, so we 200 this one, regardless of redirection settings - if (tabHasCustom200 == false) + //the hfurl key is the base human friendly url + if (tabHasCustom200 && (settings.RedirectUnfriendly && !tab.DoNotRedirect)) + { + predefinedRedirect.HttpStatus = "301"; + } + else { - baseFriendlyHttpStatus = "200"; + predefinedRedirect.HttpStatus = "200"; + //if no redirects, or not redirecting unfriendly, then 200 is OK } } + predefinedRedirect.Url = friendlyUrl; + predefinedRedirect.IsSystem = true; + predefinedRedirect.SeqNum = seqNum; + tab.TabUrls.Insert(0, predefinedRedirect); + seqNum--; } } - //base friendly url - var baseFriendly = new TabUrlInfo - { - TabId = tab.TabID, - HttpStatus = (settings.RedirectUnfriendly == false || IsExcludedFromFriendlyUrls(tab, settings, true)) - ? "200" - : baseFriendlyHttpStatus, - CultureCode = cultureCode, - Url = baseFriendlyUrl, - IsSystem = true, - SeqNum = seqNum - }; - tab.TabUrls.Insert(0, baseFriendly); - seqNum--; - } - //standard url (/default.aspx?tabid=xx) - var std = new TabUrlInfo + else { + //improved Friendly Url same as base Friendly Url, so we 200 this one, regardless of redirection settings + if (tabHasCustom200 == false) + { + baseFriendlyHttpStatus = "200"; + } + } + } + } + //base friendly url + var baseFriendly = new TabUrlInfo + { TabId = tab.TabID, - HttpStatus = stdHttpStatus, - CultureCode = (tab.CultureCode == "") ? defaultCulture : tab.CultureCode, - Url = stdUrl, + HttpStatus = (settings.RedirectUnfriendly == false || IsExcludedFromFriendlyUrls(tab, settings, true)) + ? "200" + : baseFriendlyHttpStatus, + CultureCode = cultureCode, + Url = baseFriendlyUrl, IsSystem = true, - SeqNum = seqNum, + SeqNum = seqNum }; - tab.TabUrls.Insert(0, std); - seqNum--; - } + tab.TabUrls.Insert(0, baseFriendly); + seqNum--; } + //standard url (/default.aspx?tabid=xx) + var std = new TabUrlInfo + { + TabId = tab.TabID, + HttpStatus = stdHttpStatus, + CultureCode = (tab.CultureCode == "") ? defaultCulture : tab.CultureCode, + Url = stdUrl, + IsSystem = true, + SeqNum = seqNum, + }; + tab.TabUrls.Insert(0, std); + seqNum--; } - - /// - /// A reflection based call to the Friendly Url provider to get the 'base' (dnn standard) urls - /// - /// - /// - /// - /// - /// - /// - internal static string GetFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, + } +} + +/// +/// A reflection based call to the Friendly Url provider to get the 'base' (dnn standard) urls +/// +/// +/// +/// +/// +/// +/// +internal static string GetFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, + FriendlyUrlSettings settings) +{ + List messages; + object result = CallFriendlyUrlProviderMethod("BaseFriendlyUrl", out messages, tab, path, defaultPage, httpAlias, settings); + if (result == null) + { + return Globals.NavigateURL(tab.TabID); + } + return (string) result; +} + +internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, + bool ignoreCustomRedirects) +{ + FriendlyUrlSettings settings = GetCurrentSettings(tab.PortalID); + List messages; + return GetImprovedFriendlyUrl(tab, path, defaultPage, httpAlias, ignoreCustomRedirects, settings, + out messages); +} + +/// +/// A reflection based call to the friendly URl Provider object. Done like this to avoid a circular reference +/// +/// +/// +/// +/// +/// +/// +/// +internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, + bool ignoreCustomRedirects, FriendlyUrlSettings settings) +{ + List messages; + return GetImprovedFriendlyUrl(tab, path, defaultPage, httpAlias, ignoreCustomRedirects, settings, + out messages); +} + +internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, + bool ignoreCustomRedirects, FriendlyUrlSettings settings, + out List messages) +{ + object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithMessages", out messages, tab, path, + defaultPage, httpAlias, ignoreCustomRedirects, settings); + if (result != null) + { + return (string) result; + } + return ""; +} + +internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, + PortalSettings portalSettings, bool ignoreCustomRedirects, FriendlyUrlSettings settings) - { - List messages; - object result = CallFriendlyUrlProviderMethod("BaseFriendlyUrl", out messages, tab, path, defaultPage, httpAlias, settings); - if (result == null) - { - return Globals.NavigateURL(tab.TabID); - } - return (string) result; - } +{ + List messages; + object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithSettings", out messages, tab, path, + defaultPage, portalSettings, ignoreCustomRedirects, settings); + if (result != null) + { + return (string) result; + } + return ""; +} - internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, - bool ignoreCustomRedirects) - { - FriendlyUrlSettings settings = GetCurrentSettings(tab.PortalID); - List messages; - return GetImprovedFriendlyUrl(tab, path, defaultPage, httpAlias, ignoreCustomRedirects, settings, - out messages); - } +internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, + PortalSettings portalSettings, bool ignoreCustomRedirects, + FriendlyUrlSettings settings, out List messages) +{ + object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithSettingsAndMessages", out messages, + tab, path, defaultPage, portalSettings, ignoreCustomRedirects, + settings); + if (result != null) + { + return (string) result; + } + return ""; +} +/* +/// +/// A reflection based called to the Friendly Url Provider object. Done like this to avoid circular references +/// +/// +/// +/// +/// +internal static string BuildTabPathWithReplacement(TabInfo tab, string replaceCharacter, string replaceWith) +{ + object result = CallTabPathHelperMethod("BuildTabPathWithReplacement", tab, replaceCharacter, replaceWith); + if (result != null) + { + return (string) result; + } + return ""; +} - /// - /// A reflection based call to the friendly URl Provider object. Done like this to avoid a circular reference - /// - /// - /// - /// - /// - /// - /// - /// - internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, - bool ignoreCustomRedirects, FriendlyUrlSettings settings) - { - List messages; - return GetImprovedFriendlyUrl(tab, path, defaultPage, httpAlias, ignoreCustomRedirects, settings, - out messages); - } +internal static string ReplaceDiacritics(string tabPath) +{ + object result = CallTabPathHelperMethod("ReplaceDiacritics", tabPath); + if (result != null) + { + return (string) result; + } + return ""; +} - internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, - bool ignoreCustomRedirects, FriendlyUrlSettings settings, - out List messages) - { - object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithMessages", out messages, tab, path, - defaultPage, httpAlias, ignoreCustomRedirects, settings); - if (result != null) - { - return (string) result; - } - return ""; - } - - internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, - PortalSettings portalSettings, bool ignoreCustomRedirects, - FriendlyUrlSettings settings) - { - List messages; - object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithSettings", out messages, tab, path, - defaultPage, portalSettings, ignoreCustomRedirects, settings); - if (result != null) - { - return (string) result; - } - return ""; - } +public static void RebuildCustomUrlDict(string reason, int portalId) +{ + CallTabDictControllerMethod("InvalidateDictionary", reason, null, portalId); +} - internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, - PortalSettings portalSettings, bool ignoreCustomRedirects, - FriendlyUrlSettings settings, out List messages) - { - object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithSettingsAndMessages", out messages, - tab, path, defaultPage, portalSettings, ignoreCustomRedirects, - settings); - if (result != null) - { - return (string) result; - } - return ""; - } - /* - /// - /// A reflection based called to the Friendly Url Provider object. Done like this to avoid circular references - /// - /// - /// - /// - /// - internal static string BuildTabPathWithReplacement(TabInfo tab, string replaceCharacter, string replaceWith) - { - object result = CallTabPathHelperMethod("BuildTabPathWithReplacement", tab, replaceCharacter, replaceWith); - if (result != null) - { - return (string) result; - } - return ""; - } - - internal static string ReplaceDiacritics(string tabPath) - { - object result = CallTabPathHelperMethod("ReplaceDiacritics", tabPath); - if (result != null) - { - return (string) result; - } - return ""; - } - - public static void RebuildCustomUrlDict(string reason, int portalId) - { - CallTabDictControllerMethod("InvalidateDictionary", reason, null, portalId); - } +//internal static void ProcessTestRequest(string httpMethod, Uri requestUri, UrlAction result, NameValueCollection queryString, FriendlyUrlSettings settings, out List messages) +//{ +// //public void ProcessRequest(HttpContext context, HttpRequest request, HttpServerUtility Server, HttpResponse response, bool useFriendlyUrls, string requestType, Uri requestUri, UrlAction result, NameValueCollection queryStringCol, FriendlyUrlSettings settings) +// bool useFriendlyUrls = (DotNetNuke.Entities.Host.HostSettings.GetHostSetting("UseFriendlyUrls") == "Y"); +// object retval = CallUrlRewriterMethod("ProcessTestRequest", out messages, useFriendlyUrls, httpMethod, requestUri, result, queryString, settings); +//} +/// +/// Gets the Reflection MethodInfo object of the FriendlyUrlProvider method, +/// as LONG as the iFInity.UrlMaster.FriendlyUrlProvider can be found +/// +/// This is a heavyweight proc, don't call too much! +/// +/// +private static object CallFriendlyUrlProviderMethod(string methodName, out List messages, + params object[] parameters) +{ + return CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.DNNFriendlyUrlProvider", + out messages, parameters); +} - //internal static void ProcessTestRequest(string httpMethod, Uri requestUri, UrlAction result, NameValueCollection queryString, FriendlyUrlSettings settings, out List messages) - //{ - // //public void ProcessRequest(HttpContext context, HttpRequest request, HttpServerUtility Server, HttpResponse response, bool useFriendlyUrls, string requestType, Uri requestUri, UrlAction result, NameValueCollection queryStringCol, FriendlyUrlSettings settings) - // bool useFriendlyUrls = (DotNetNuke.Entities.Host.HostSettings.GetHostSetting("UseFriendlyUrls") == "Y"); - // object retval = CallUrlRewriterMethod("ProcessTestRequest", out messages, useFriendlyUrls, httpMethod, requestUri, result, queryString, settings); - //} - /// - /// Gets the Reflection MethodInfo object of the FriendlyUrlProvider method, - /// as LONG as the iFInity.UrlMaster.FriendlyUrlProvider can be found - /// - /// This is a heavyweight proc, don't call too much! - /// - /// - private static object CallFriendlyUrlProviderMethod(string methodName, out List messages, - params object[] parameters) - { - return CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.DNNFriendlyUrlProvider", - out messages, parameters); - } +private static void CallTabDictControllerMethod(string methodName, params object[] parameters) +{ + CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.TabDictController", + parameters); +} - private static void CallTabDictControllerMethod(string methodName, params object[] parameters) - { - CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.TabDictController", - parameters); - } +private static object CallTabPathHelperMethod(string methodName, params object[] parameters) +{ + return CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.TabPathHelper", + parameters); +} - private static object CallTabPathHelperMethod(string methodName, params object[] parameters) - { - return CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.TabPathHelper", - parameters); - } +private static object CallFriendlyUrlProviderDllMethod(string methodName, string typeName, + params object[] parameters) +{ + List messages; + return CallFriendlyUrlProviderDllMethod(methodName, typeName, out messages, parameters); +} - private static object CallFriendlyUrlProviderDllMethod(string methodName, string typeName, - params object[] parameters) - { - List messages; - return CallFriendlyUrlProviderDllMethod(methodName, typeName, out messages, parameters); - } +private static object CallFriendlyUrlProviderDllMethod(string methodName, string typeName, + out List messages, params object[] parameters) +{ + object result = null; + messages = null; + try + { + object providerObj = null; - private static object CallFriendlyUrlProviderDllMethod(string methodName, string typeName, - out List messages, params object[] parameters) + Assembly urlMasterProvider = Assembly.Load("iFinity.UrlMaster.FriendlyUrlProvider"); + Type[] types = urlMasterProvider.GetTypes(); + foreach (Type type in types) { - object result = null; - messages = null; - try + if ((type.FullName == typeName) & (type.IsClass)) { - object providerObj = null; + Type providerType = type; + string providerTypeName = providerType.Name; + //570 : check to see if it is an abstract class before trying to instantiate the + //calling object + if (!providerType.IsAbstract) + { + // get the provider objects from the stored collection if necessary + if (_providerObjects != null) + { + if (_providerObjects.ContainsKey(providerTypeName)) + { + providerObj = _providerObjects[providerTypeName]; + } + } + if (providerObj == null) + { + providerObj = Activator.CreateInstance(providerType); + } - Assembly urlMasterProvider = Assembly.Load("iFinity.UrlMaster.FriendlyUrlProvider"); - Type[] types = urlMasterProvider.GetTypes(); - foreach (Type type in types) + if (_providerObjects == null) + { + _providerObjects = new Dictionary {{providerTypeName, providerObj}}; + } + } + + if (providerObj != null || providerType.IsAbstract) { - if ((type.FullName == typeName) & (type.IsClass)) + MethodInfo method = providerType.GetMethod(methodName); + if (method != null) { - Type providerType = type; - string providerTypeName = providerType.Name; - //570 : check to see if it is an abstract class before trying to instantiate the - //calling object - if (!providerType.IsAbstract) + //new collection + int messageParmIdx = -1; + var parmValues = new List(parameters); + ParameterInfo[] methodParms = method.GetParameters(); + for (int i = 0; i <= methodParms.GetUpperBound(0); i++) { - // get the provider objects from the stored collection if necessary - if (_providerObjects != null) + if (methodParms[i].IsOut && i > parameters.GetUpperBound(0) && + methodParms[i].Name.ToLower() == "messages") { - if (_providerObjects.ContainsKey(providerTypeName)) - { - providerObj = _providerObjects[providerTypeName]; - } - } - if (providerObj == null) - { - providerObj = Activator.CreateInstance(providerType); + //add on another one on the end + parmValues.Add(messages); + messageParmIdx = i; + parameters = parmValues.ToArray(); } - - if (_providerObjects == null) + if (methodParms[i].Name.ToLower() == "parenttraceid" && + i > parameters.GetUpperBound(0)) { - _providerObjects = new Dictionary {{providerTypeName, providerObj}}; + parmValues.Add(Guid.Empty); + parameters = parmValues.ToArray(); } } - - if (providerObj != null || providerType.IsAbstract) + result = method.Invoke(providerObj, parameters); + //get the out messages value + if (messageParmIdx > -1) { - MethodInfo method = providerType.GetMethod(methodName); - if (method != null) - { - //new collection - int messageParmIdx = -1; - var parmValues = new List(parameters); - ParameterInfo[] methodParms = method.GetParameters(); - for (int i = 0; i <= methodParms.GetUpperBound(0); i++) - { - if (methodParms[i].IsOut && i > parameters.GetUpperBound(0) && - methodParms[i].Name.ToLower() == "messages") - { - //add on another one on the end - parmValues.Add(messages); - messageParmIdx = i; - parameters = parmValues.ToArray(); - } - if (methodParms[i].Name.ToLower() == "parenttraceid" && - i > parameters.GetUpperBound(0)) - { - parmValues.Add(Guid.Empty); - parameters = parmValues.ToArray(); - } - } - result = method.Invoke(providerObj, parameters); - //get the out messages value - if (messageParmIdx > -1) - { - messages = (List) parameters[messageParmIdx]; - } - } - break; + messages = (List) parameters[messageParmIdx]; } } - } - //} - } - catch (Exception ex) - { - //get the standard DNN friendly Url by loading up HttpModules - if (messages == null) - { - messages = new List(); - } - messages.Add("Error:[" + ex.Message + "]"); - if (ex.InnerException != null) - { - messages.Add("Inner Error:[ " + ex.InnerException.Message + "]"); - messages.Add("Stack Trace :[ " + ex.InnerException.StackTrace + "]"); + break; } } - return result; } - */ - #endregion - - #region Database methods + //} + } + catch (Exception ex) + { + //get the standard DNN friendly Url by loading up HttpModules + if (messages == null) + { + messages = new List(); + } + messages.Add("Error:[" + ex.Message + "]"); + if (ex.InnerException != null) + { + messages.Add("Inner Error:[ " + ex.InnerException.Message + "]"); + messages.Add("Stack Trace :[ " + ex.InnerException.StackTrace + "]"); + } + } + return result; +} +*/ public static Dictionary GetTabs(int portalId, bool includeStdUrls) { @@ -629,17 +613,19 @@ public static Dictionary GetTabs(int portalId, bool includeStdUrls public static Dictionary GetTabs(int portalId, bool includeStdUrls, FriendlyUrlSettings settings) { PortalSettings portalSettings = null; - //716 just ignore portal settings if we don't actually need it + + // 716 just ignore portal settings if we don't actually need it if (includeStdUrls) { portalSettings = PortalController.Instance.GetCurrentPortalSettings(); } + return GetTabs(portalId, includeStdUrls, portalSettings, settings); } public static Dictionary GetTabs(int portalId, bool includeStdUrls, PortalSettings portalSettings, FriendlyUrlSettings settings) { - //811 : friendly urls for admin/host tabs + // 811 : friendly urls for admin/host tabs var tabs = new Dictionary(); var portalTabs = TabController.Instance.GetTabsByPortal(portalId); var hostTabs = TabController.Instance.GetTabsByPortal(-1); @@ -656,13 +642,15 @@ public static Dictionary GetTabs(int portalId, bool includeStdUrls tabs[tab.TabID] = tab; } } + return tabs; } /// - /// Returns a list of http alias values where that alias is associated with a tab as a custom alias + /// Returns a list of http alias values where that alias is associated with a tab as a custom alias. /// - /// Aliases returned are all in lower case only + /// Aliases returned are all in lower case only. + /// public static List GetCustomAliasesForTabs() { var aliases = new List(); @@ -683,6 +671,7 @@ public static List GetCustomAliasesForTabs() { CBO.CloseDataReader(dr, true); } + return aliases; } @@ -697,148 +686,35 @@ public static TabInfo GetTab(int tabId, bool addStdUrls, PortalSettings portalSe TabInfo tab = TabController.Instance.GetTab(tabId, portalSettings.PortalId, false); if (addStdUrls) { - //Add on the standard Urls that exist for a tab, based on settings like - //replacing spaces, diacritic characters and languages - //BuildFriendlyUrls(tab, true, portalSettings, settings); - } - return tab; - } - - #endregion - - private static bool IsMobileClient() - { - return (HttpContext.Current.Request.Browser != null) && (ClientCapabilityProvider.Instance() != null) && ClientCapabilityProvider.CurrentClientCapability.IsMobile; - } - - private static void CheckIllegalChars(string illegalChars, ref string ch, ref bool replacedUnwantedChars) - { - var resultingCh = new StringBuilder(ch.Length); - foreach (char c in ch) //ch could contain several chars from the pre-defined replacement list - { - if (illegalChars.ToUpperInvariant().Contains(char.ToUpperInvariant(c))) - { - replacedUnwantedChars = true; - } - else - { - resultingCh.Append(c); - } - } - ch = resultingCh.ToString(); - } - - private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string ch, - ref bool replacedUnwantedChars) - { - if (!options.ReplaceChars.ToUpperInvariant().Contains(ch.ToUpperInvariant())) - { - return; - } - - if (ch != " ") // if not replacing spaces, which are implied - { - replacedUnwantedChars = true; + // Add on the standard Urls that exist for a tab, based on settings like + // replacing spaces, diacritic characters and languages + // BuildFriendlyUrls(tab, true, portalSettings, settings); } - ch = options.PunctuationReplacement; //in list of replacment chars - - //If we still have a space ensure it's encoded - if (ch == " ") - { - ch = options.SpaceEncoding; - } - } - - #region Internal Methods - - internal static bool CanUseMobileDevice(HttpRequest request, HttpResponse response) - { - var canUseMobileDevice = true; - int val; - if (int.TryParse(request.QueryString[DisableMobileRedirectQueryStringName], out val)) - { - //the nomo value is in the querystring - if (val == 1) - { - //no, can't do it - canUseMobileDevice = false; - var cookie = new HttpCookie(DisableMobileViewCookieName) - { - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") - }; - response.Cookies.Set(cookie); - } - else - { - //check for disable mobile view cookie name - var cookie = request.Cookies[DisableMobileViewCookieName]; - if (cookie != null) - { - //if exists, expire cookie to allow redirect - cookie = new HttpCookie(DisableMobileViewCookieName) - { - Expires = DateTime.Now.AddMinutes(-1), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") - }; - response.Cookies.Set(cookie); - } - //check the DotNetNuke cookies for allowed - if (request.Cookies[DisableMobileRedirectCookieName] != null - && request.Cookies[DisableRedirectPresistCookieName] != null) //check for cookie - { - //cookies exist, can't use mobile device - canUseMobileDevice = false; - } - } - } - else - { - //look for disable mobile view cookie - var cookie = request.Cookies[DisableMobileViewCookieName]; - if (cookie != null) - { - canUseMobileDevice = false; - } - } - - return canUseMobileDevice; - } - - /// - /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0 - /// - /// The path of the tab //admin//someothername - /// - /// Duplicated in RewriteController.cs - /// - internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) - { - return RewriteController.IsAdminTab(portalId, tabPath, settings); + return tab; } - #endregion - - #region Public Methods - public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, out bool replacedUnwantedChars) { replacedUnwantedChars = false; - //get options + + // get options if (options == null) { options = new FriendlyUrlOptions(); } + bool convertDiacritics = options.ConvertDiacriticChars; Regex regexMatch = options.RegexMatchRegex; - string replaceWith = options.PunctuationReplacement; + string replaceWith = options.PunctuationReplacement; bool replaceDoubleChars = options.ReplaceDoubleChars; Dictionary replacementChars = options.ReplaceCharWithChar; if (urlName == null) { - urlName = ""; + urlName = string.Empty; } + var result = new StringBuilder(urlName.Length); int i = 0; string normalisedUrl = urlName; @@ -847,7 +723,7 @@ public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, normalisedUrl = urlName.Normalize(NormalizationForm.FormD); if (!string.Equals(normalisedUrl, urlName, StringComparison.Ordinal)) { - replacedUnwantedChars = true; //replaced an accented character + replacedUnwantedChars = true; // replaced an accented character } } @@ -855,19 +731,19 @@ public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, bool doublePeriod = false; foreach (char c in normalisedUrl) { - //look for a double period in the name + // look for a double period in the name if (!doublePeriod && i > 0 && c == '.' && normalisedUrl[i - 1] == '.') { doublePeriod = true; } - //use string for manipulation + // use string for manipulation string ch = c.ToString(CultureInfo.InvariantCulture); - //do replacement in pre-defined list? + // do replacement in pre-defined list? if (replacementChars != null && replacementChars.ContainsKey(ch)) { - //replace with value + // replace with value ch = replacementChars[ch]; replacedUnwantedChars = true; } @@ -878,46 +754,49 @@ public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, } else { - //Check if ch is in the replace list + // Check if ch is in the replace list CheckCharsForReplace(options, ref ch, ref replacedUnwantedChars); - //not in replacement list, check if valid char + // not in replacement list, check if valid char if (regexMatch.IsMatch(ch)) { - ch = ""; //not a replacement or allowed char, so doesn't go into Url + ch = string.Empty; // not a replacement or allowed char, so doesn't go into Url replacedUnwantedChars = true; - //if we are here, this character isn't going into the output Url + + // if we are here, this character isn't going into the output Url } } - //Check if the final ch is an illegal char + // Check if the final ch is an illegal char CheckIllegalChars(options.IllegalChars, ref ch, ref replacedUnwantedChars); if (i == last) { - //834 : strip off last character if it is a '.' + // 834 : strip off last character if it is a '.' if (!(ch == "-" || ch == replaceWith || ch == ".")) { - //only append if not the same as the replacement character + // only append if not the same as the replacement character result.Append(ch); } else { - replacedUnwantedChars = true; //last char not added - effectively replaced with nothing. + replacedUnwantedChars = true; // last char not added - effectively replaced with nothing. } } else { result.Append(ch); } - i++; //increment counter + + i++; // increment counter } if (doublePeriod) { - result = result.Replace("..", ""); + result = result.Replace("..", string.Empty); } - //replace any duplicated replacement characters by doing replace twice - //replaces -- with - or --- with - //749 : ampersand not completed replaced + + // replace any duplicated replacement characters by doing replace twice + // replaces -- with - or --- with - //749 : ampersand not completed replaced if (replaceDoubleChars && !string.IsNullOrEmpty(replaceWith)) { result = result.Replace(replaceWith + replaceWith, replaceWith); @@ -928,7 +807,7 @@ public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, } /// - /// Ensures that the path starts with the leading character + /// Ensures that the path starts with the leading character. /// /// /// @@ -936,34 +815,147 @@ public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, public static string EnsureLeadingChar(string leading, string path) { if (leading != null && path != null - && leading.Length <= path.Length && leading != "") + && leading.Length <= path.Length && leading != string.Empty) { string start = path.Substring(0, leading.Length); - if (String.Compare(start, leading, StringComparison.OrdinalIgnoreCase) != 0) + if (string.Compare(start, leading, StringComparison.OrdinalIgnoreCase) != 0) { - //not leading with this + // not leading with this path = leading + path; } } + return path; } + internal static bool CanUseMobileDevice(HttpRequest request, HttpResponse response) + { + var canUseMobileDevice = true; + int val; + if (int.TryParse(request.QueryString[DisableMobileRedirectQueryStringName], out val)) + { + // the nomo value is in the querystring + if (val == 1) + { + // no, can't do it + canUseMobileDevice = false; + var cookie = new HttpCookie(DisableMobileViewCookieName) + { + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }; + response.Cookies.Set(cookie); + } + else + { + // check for disable mobile view cookie name + var cookie = request.Cookies[DisableMobileViewCookieName]; + if (cookie != null) + { + // if exists, expire cookie to allow redirect + cookie = new HttpCookie(DisableMobileViewCookieName) + { + Expires = DateTime.Now.AddMinutes(-1), + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }; + response.Cookies.Set(cookie); + } + + // check the DotNetNuke cookies for allowed + if (request.Cookies[DisableMobileRedirectCookieName] != null + && request.Cookies[DisableRedirectPresistCookieName] != null) // check for cookie + { + // cookies exist, can't use mobile device + canUseMobileDevice = false; + } + } + } + else + { + // look for disable mobile view cookie + var cookie = request.Cookies[DisableMobileViewCookieName]; + if (cookie != null) + { + canUseMobileDevice = false; + } + } + + return canUseMobileDevice; + } + + /// + /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0. + /// + /// The path of the tab //admin//someothername. + /// + /// Duplicated in RewriteController.cs. + /// + internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) + { + return RewriteController.IsAdminTab(portalId, tabPath, settings); + } + + private static bool IsMobileClient() + { + return (HttpContext.Current.Request.Browser != null) && (ClientCapabilityProvider.Instance() != null) && ClientCapabilityProvider.CurrentClientCapability.IsMobile; + } + + private static void CheckIllegalChars(string illegalChars, ref string ch, ref bool replacedUnwantedChars) + { + var resultingCh = new StringBuilder(ch.Length); + foreach (char c in ch) // ch could contain several chars from the pre-defined replacement list + { + if (illegalChars.ToUpperInvariant().Contains(char.ToUpperInvariant(c))) + { + replacedUnwantedChars = true; + } + else + { + resultingCh.Append(c); + } + } + + ch = resultingCh.ToString(); + } + + private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string ch, + ref bool replacedUnwantedChars) + { + if (!options.ReplaceChars.ToUpperInvariant().Contains(ch.ToUpperInvariant())) + { + return; + } + + if (ch != " ") // if not replacing spaces, which are implied + { + replacedUnwantedChars = true; + } + + ch = options.PunctuationReplacement; // in list of replacment chars + + // If we still have a space ensure it's encoded + if (ch == " ") + { + ch = options.SpaceEncoding; + } + } + public static string EnsureNotLeadingChar(string leading, string path) { if (leading != null && path != null - && leading.Length <= path.Length && leading != "") + && leading.Length <= path.Length && leading != string.Empty) { string start = path.Substring(0, leading.Length); - if (String.Compare(start, leading, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(start, leading, StringComparison.OrdinalIgnoreCase) == 0) { - //matches start, take leading off + // matches start, take leading off path = path.Substring(leading.Length); } } + return path; } - //737 : detect mobile and other types of browsers + // 737 : detect mobile and other types of browsers public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse response, FriendlyUrlSettings settings) { var browserType = BrowserTypes.Normal; @@ -978,6 +970,7 @@ public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse resp { isCookieSet = true; } + if (isMobile == false) { if (!isCookieSet) @@ -991,8 +984,8 @@ public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse resp // Store the result as a cookie. if (viewMobileCookie == null) { - response.Cookies.Add(new HttpCookie(MobileViewSiteCookieName, isMobile.ToString()) - { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }); + response.Cookies.Add(new HttpCookie(MobileViewSiteCookieName, isMobile.ToString()) + { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); } else { @@ -1006,10 +999,10 @@ public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse resp } } } + return browserType; } - public static string ValidateUrl(string cleanUrl, int validateUrlForTabId, PortalSettings settings, out bool modified) { modified = false; @@ -1023,35 +1016,38 @@ public static string ValidateUrl(string cleanUrl, int validateUrlForTabId, Porta uniqueUrl = uniqueUrl + counter.ToString(CultureInfo.InvariantCulture); modified = true; } + isUnique = ValidateUrl(uniqueUrl, validateUrlForTabId, settings); counter++; - } while (!isUnique); + } + while (!isUnique); return uniqueUrl; } private static bool ValidateUrl(string url, int validateUrlForTabId, PortalSettings settings) { - //Try and get a user by the url + // Try and get a user by the url var user = UserController.GetUserByVanityUrl(settings.PortalId, url); - bool isUnique = (user == null); + bool isUnique = user == null; if (isUnique) { - //Try and get a tab by the url + // Try and get a tab by the url int tabId = TabController.GetTabByTabPath(settings.PortalId, "//" + url, settings.CultureCode); - isUnique = (tabId == -1 || tabId == validateUrlForTabId); + isUnique = tabId == -1 || tabId == validateUrlForTabId; } - if (isUnique) //check whether have a tab which use the url. + if (isUnique) // check whether have a tab which use the url. { var friendlyUrlSettings = GetCurrentSettings(settings.PortalId); var tabs = TabController.Instance.GetTabsByPortal(settings.PortalId).AsList(); - //DNN-6492: if content localize enabled, only check tab names in current culture. - if (settings.ContentLocalizationEnabled) - { - tabs = tabs.Where(t => t.CultureCode == settings.CultureCode).ToList(); - } + + // DNN-6492: if content localize enabled, only check tab names in current culture. + if (settings.ContentLocalizationEnabled) + { + tabs = tabs.Where(t => t.CultureCode == settings.CultureCode).ToList(); + } foreach (TabInfo tab in tabs) { @@ -1063,15 +1059,16 @@ private static bool ValidateUrl(string url, int validateUrlForTabId, PortalSetti if (tab.TabUrls.Count == 0) { var baseUrl = Globals.AddHTTP(settings.PortalAlias.HTTPAlias) + "/Default.aspx?TabId=" + tab.TabID; - var path = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - baseUrl, - Globals.glbDefaultPage, - settings.PortalAlias.HTTPAlias, - false, - friendlyUrlSettings, - Guid.Empty); + var path = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + baseUrl, + Globals.glbDefaultPage, + settings.PortalAlias.HTTPAlias, + false, + friendlyUrlSettings, + Guid.Empty); - var tabUrl = path.Replace(Globals.AddHTTP(settings.PortalAlias.HTTPAlias), ""); + var tabUrl = path.Replace(Globals.AddHTTP(settings.PortalAlias.HTTPAlias), string.Empty); if (tabUrl.Equals("/" + url, StringComparison.InvariantCultureIgnoreCase)) { @@ -1086,10 +1083,8 @@ private static bool ValidateUrl(string url, int validateUrlForTabId, PortalSetti } } } + return isUnique; } - - - #endregion } } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs index 1c1e923fb5e..a8642a0335a 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs @@ -1,33 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Utilities; + /// - /// This class encapsulates different options used in generating friendly urls + /// This class encapsulates different options used in generating friendly urls. /// [Serializable] public class FriendlyUrlOptions { - private static readonly object _regexLookupLock = new object(); - private static readonly Dictionary _regexLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); - public bool ConvertDiacriticChars; public string IllegalChars; + + private static readonly object _regexLookupLock = new object(); + private static readonly Dictionary _regexLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); public int MaxUrlPathLength; public string PageExtension; public string PunctuationReplacement; - //922 : change to use regexMatch pattern for allowable characters + + // 922 : change to use regexMatch pattern for allowable characters public string RegexMatch; public Dictionary ReplaceCharWithChar = new Dictionary(); public string ReplaceChars; @@ -36,20 +33,20 @@ public class FriendlyUrlOptions public bool CanGenerateNonStandardPath { - //replaces statements like this - //if ((settings.ReplaceSpaceWith != null && settings.ReplaceSpaceWith.Length > 0) || settings.ReplaceCharWithCharDict != null && settings.ReplaceCharWithCharDict.Count > 0) + // replaces statements like this + // if ((settings.ReplaceSpaceWith != null && settings.ReplaceSpaceWith.Length > 0) || settings.ReplaceCharWithCharDict != null && settings.ReplaceCharWithCharDict.Count > 0) get { bool result = false; - if (string.IsNullOrEmpty(PunctuationReplacement) == false) + if (string.IsNullOrEmpty(this.PunctuationReplacement) == false) { result = true; } - else if (ReplaceCharWithChar != null && ReplaceCharWithChar.Count > 0) + else if (this.ReplaceCharWithChar != null && this.ReplaceCharWithChar.Count > 0) { result = true; } - else if (ConvertDiacriticChars) + else if (this.ConvertDiacriticChars) { result = true; } @@ -63,6 +60,23 @@ public Regex RegexMatchRegex get { return GetRegex(this.RegexMatch); } } + public FriendlyUrlOptions Clone() + { + var cloned = new FriendlyUrlOptions + { + PunctuationReplacement = this.PunctuationReplacement, + SpaceEncoding = this.SpaceEncoding, + MaxUrlPathLength = this.MaxUrlPathLength, + ConvertDiacriticChars = this.ConvertDiacriticChars, + PageExtension = this.PageExtension, + RegexMatch = this.RegexMatch, + ReplaceCharWithChar = this.ReplaceCharWithChar, + IllegalChars = this.IllegalChars, + ReplaceChars = this.ReplaceChars, + }; + return cloned; + } + private static Regex GetRegex(string regexText) { Regex compiledRegex; @@ -81,22 +95,5 @@ private static Regex GetRegex(string regexText) return _regexLookup[regexText] = RegexUtils.GetCachedRegex(regexText, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } } - - public FriendlyUrlOptions Clone() - { - var cloned = new FriendlyUrlOptions - { - PunctuationReplacement = PunctuationReplacement, - SpaceEncoding = SpaceEncoding, - MaxUrlPathLength = MaxUrlPathLength, - ConvertDiacriticChars = ConvertDiacriticChars, - PageExtension = PageExtension, - RegexMatch = RegexMatch, - ReplaceCharWithChar = ReplaceCharWithChar, - IllegalChars = IllegalChars, - ReplaceChars = ReplaceChars - }; - return cloned; - } } } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs index eba4fe55cdd..4f575f0b74a 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs @@ -1,127 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + internal class FriendlyUrlPathController - { - #region Private Methods - - /// - /// Splits out the userid value from the supplied Friendly Url Path - /// - /// - /// The 'other' parameters which form the total UserProfile Url (if supplied) - /// - /// The remaining path not associated with the user id - /// - private static void SplitUserIdFromFriendlyUrlPath(string urlPath, - string parmName, - string otherParametersPath, - out string rawUserId, - out string remainingPath) - { - //688 : allow for other parts to be in the url by capturing more with the regex filters - string regexPattern; - rawUserId = null; - remainingPath = ""; - //generally the path will start with a / and not end with one, but it's possible to get all sorts of things - if (!string.IsNullOrEmpty(otherParametersPath)) - { - //remove the trailing slash from otherParamtersPath if it exists, because the other parameters may be anywhere in the path - if (otherParametersPath.EndsWith("/")) - { - otherParametersPath = otherParametersPath.Substring(0, otherParametersPath.Length - 1); - } - const string patternFormatWithParameters = @"/?(?.*)(?=_parm_)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)){0,1}/?(?_otherparm_){0,1}/?(?(?<=/)(?:_parm_)/(?[\d\w]+)){0,1}(?.*)"; - regexPattern = patternFormatWithParameters.Replace("_parm_", parmName); - regexPattern = regexPattern.Replace("_otherparm_", otherParametersPath); - } - else - { - const string patternNoParameters = @"/?(?.*)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)/?)+(?.*)"; - regexPattern = patternNoParameters.Replace("_parm_", parmName); - } - //check the regex match - Match parmMatch = Regex.Match(urlPath, regexPattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - if (parmMatch.Success) - { - //must be nothing in the op1 and op2 values - Group otherParmsGp = parmMatch.Groups["op"]; - Group parm1ValueGp = parmMatch.Groups["p1v"]; - Group parm2ValueGp = parmMatch.Groups["p2v"]; - Group rem1ParmsGp = parmMatch.Groups["rem1"]; //remainder at the start of the match - Group rem2ParmsGp = parmMatch.Groups["rem2"]; //remainder at the end of the match - - if (otherParmsGp != null && otherParmsGp.Success && (parm1ValueGp.Success || parm2ValueGp.Success)) - { - //matched the other parm value and either the p1 or p2 value - rawUserId = parm1ValueGp.Success ? parm1ValueGp.Value : parm2ValueGp.Value; - } - else - { - if ((otherParmsGp == null || otherParmsGp.Success == false) && parm1ValueGp != null && - parm1ValueGp.Success) - { - rawUserId = parm1ValueGp.Value; - } - } - //add back the remainders - if (rem1ParmsGp != null && rem1ParmsGp.Success) - { - remainingPath = rem1ParmsGp.Value; - } - if (rem2ParmsGp != null && rem2ParmsGp.Success) - { - remainingPath += rem2ParmsGp.Value; - } - if (remainingPath.EndsWith("/")) - { - remainingPath = remainingPath.Substring(0, remainingPath.Length - 1); - } - //722: drop out the parts of the remaining path that are in the 'otherParameters' path. - // the other parameters path will be automatically provided upon rewrite - if (otherParametersPath != null) - { - remainingPath = Regex.Replace(remainingPath, Regex.Escape(otherParametersPath), "", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - - if (parmName.Contains("|") && rawUserId != null) - { - //eliminate any dups from the remaining path - string[] vals = parmName.Split('|'); - foreach (string val in vals) - { - string find = "/?" + Regex.Escape(val + "/" + rawUserId); - remainingPath = Regex.Replace(remainingPath, find, "", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - } - if (remainingPath.Length > 0 && remainingPath.StartsWith("/") == false) - { - remainingPath = "/" + remainingPath; - } - } - } - - #endregion - - #region Internal Methods - + { /// - /// This method checks the list of rules for parameter replacement and modifies the parameter path accordingly + /// This method checks the list of rules for parameter replacement and modifies the parameter path accordingly. /// /// /// @@ -132,17 +26,18 @@ private static void SplitUserIdFromFriendlyUrlPath(string urlPath, /// /// /// - internal static bool CheckParameterRegexReplacement(string parameterPath, - TabInfo tab, - FriendlyUrlSettings settings, - int portalId, - out string replacedPath, - ref List messages, - out bool changeToSiteRoot, - Guid parentTraceId) + internal static bool CheckParameterRegexReplacement( + string parameterPath, + TabInfo tab, + FriendlyUrlSettings settings, + int portalId, + out string replacedPath, + ref List messages, + out bool changeToSiteRoot, + Guid parentTraceId) { bool replaced = false; - replacedPath = ""; + replacedPath = string.Empty; changeToSiteRoot = false; if (messages == null) { @@ -157,94 +52,104 @@ internal static bool CheckParameterRegexReplacement(string parameterPath, if (replaceActions.ContainsKey(tabId)) { - //find the right set of replaced actions for this tab + // find the right set of replaced actions for this tab parmReplaces = replaceActions[tabId]; } - //check for 'all tabs' replaceions - if (replaceActions.ContainsKey(-1)) //-1 means 'all tabs' - replacing across all tabs + // check for 'all tabs' replaceions + if (replaceActions.ContainsKey(-1)) // -1 means 'all tabs' - replacing across all tabs { - //initialise to empty collection if there are no specific tab replaces + // initialise to empty collection if there are no specific tab replaces if (parmReplaces == null) { parmReplaces = new List(); } - //add in the all replaces + + // add in the all replaces List allReplaces = replaceActions[-1]; - parmReplaces.AddRange(allReplaces); //add the 'all' range to the tab range + parmReplaces.AddRange(allReplaces); // add the 'all' range to the tab range } + if (parmReplaces != null) { - //OK what we have now is a list of replaces for the currently requested tab (either because it was specified by tab id, + // OK what we have now is a list of replaces for the currently requested tab (either because it was specified by tab id, // or because there is a replaced for 'all tabs' try { foreach (ParameterReplaceAction parmReplace in parmReplaces) { - //do a regex on the 'lookFor' in the parameter path - var parmRegex = RegexUtils.GetCachedRegex(parmReplace.LookFor, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + // do a regex on the 'lookFor' in the parameter path + var parmRegex = RegexUtils.GetCachedRegex( + parmReplace.LookFor, + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); if (parmRegex.IsMatch(parameterPath)) { replacedPath = parmRegex.Replace(parameterPath, parmReplace.ReplaceWith); messages.Add(parmReplace.Name + " replace rule match, replaced : " + parameterPath + " with: " + replacedPath); replaced = true; - //593: if this replacement is marked as a site root replacement, we will be - //removing the page path from the final url + + // 593: if this replacement is marked as a site root replacement, we will be + // removing the page path from the final url changeToSiteRoot = parmReplace.ChangeToSiteRoot; break; } + messages.Add(parmReplace.Name + " replace rule not matched {" + parameterPath + "}"); } } catch (Exception ex) { - //catch exceptions here because most likely to be related to regular expressions - //don't want to kill entire site because of this + // catch exceptions here because most likely to be related to regular expressions + // don't want to kill entire site because of this Services.Exceptions.Exceptions.LogException(ex); messages.Add("Exception : " + ex.Message + "\n" + ex.StackTrace); } } } + return replaced; } - internal static bool CheckUserProfileReplacement(string newPath, - TabInfo tab, - PortalSettings portalSettings, - FriendlyUrlSettings settings, - FriendlyUrlOptions options, - out string changedPath, - out bool changeToSiteRoot, - out bool allowOtherParameters, - ref List meessages, - Guid parentTraceId) + internal static bool CheckUserProfileReplacement( + string newPath, + TabInfo tab, + PortalSettings portalSettings, + FriendlyUrlSettings settings, + FriendlyUrlOptions options, + out string changedPath, + out bool changeToSiteRoot, + out bool allowOtherParameters, + ref List meessages, + Guid parentTraceId) { if (meessages == null) { meessages = new List(); } + bool urlWasChanged = false; - //initialise defaults to always return valid items + // initialise defaults to always return valid items changedPath = newPath; changeToSiteRoot = false; allowOtherParameters = true; - //determine if this url should be converted to a userprofile url by checking the saved rules matching the tab/portalid + // determine if this url should be converted to a userprofile url by checking the saved rules matching the tab/portalid if (portalSettings != null && tab.PortalID == portalSettings.PortalId && (tab.TabID == portalSettings.UserTabId || portalSettings.UserTabId == -1 || - tab.ParentId == portalSettings.UserTabId)) //-1 == all tabs in portal + tab.ParentId == portalSettings.UserTabId)) // -1 == all tabs in portal { int userId; string rawUserId, remainingPath; - //split the userid and other profile parameters from the friendly url path, - //and return the userid and remaining parts as separate items - SplitUserIdFromFriendlyUrlPath(newPath, - "UserId", - "", - out rawUserId, - out remainingPath); + + // split the userid and other profile parameters from the friendly url path, + // and return the userid and remaining parts as separate items + SplitUserIdFromFriendlyUrlPath( + newPath, + "UserId", + string.Empty, + out rawUserId, + out remainingPath); if (rawUserId != null) { meessages.Add("User Profile Url : RawUserId = " + rawUserId + " remainingPath = " + remainingPath); @@ -254,48 +159,50 @@ internal static bool CheckUserProfileReplacement(string newPath, meessages.Add("User Profile Url : RawUserId = " + "null" + " remainingPath = " + remainingPath); } - //the rawuserid is just the string representation of the userid from the path. - //It should be considered 'untrusted' until cleaned up, - //converted to an int and checked against the database - if (!String.IsNullOrEmpty(rawUserId) && Int32.TryParse(rawUserId, out userId)) + // the rawuserid is just the string representation of the userid from the path. + // It should be considered 'untrusted' until cleaned up, + // converted to an int and checked against the database + if (!string.IsNullOrEmpty(rawUserId) && int.TryParse(rawUserId, out userId)) { bool doReplacement = false; - string urlName = String.Empty; + string urlName = string.Empty; - //Get the User + // Get the User var user = UserController.GetUserById(portalSettings.PortalId, userId); - if (user != null && !String.IsNullOrEmpty(user.VanityUrl)) + if (user != null && !string.IsNullOrEmpty(user.VanityUrl)) { doReplacement = true; - urlName = (!String.IsNullOrEmpty(settings.VanityUrlPrefix)) ? String.Format("{0}/{1}", settings.VanityUrlPrefix, user.VanityUrl) : user.VanityUrl; + urlName = (!string.IsNullOrEmpty(settings.VanityUrlPrefix)) ? string.Format("{0}/{1}", settings.VanityUrlPrefix, user.VanityUrl) : user.VanityUrl; urlWasChanged = true; } if (doReplacement) { - //check to see whether this is a match on the parentid or not + // check to see whether this is a match on the parentid or not if (portalSettings.UserTabId == tab.ParentId && portalSettings.UserTabId > -1) { - //replacing for the parent tab id + // replacing for the parent tab id string childTabPath = TabIndexController.GetTabPath(tab, options, parentTraceId); if (string.IsNullOrEmpty(childTabPath) == false) { - //remove the parent tab path from the child tab path + // remove the parent tab path from the child tab path TabInfo profilePage = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false); string profilePagePath = TabIndexController.GetTabPath(profilePage, options, parentTraceId); if (childTabPath.Contains(profilePagePath)) { - //only replace when the child tab path contains the parent path - if it's a custom url that - //doesn't incorporate the parent path, then leave it alone - childTabPath = childTabPath.Replace(profilePagePath, ""); + // only replace when the child tab path contains the parent path - if it's a custom url that + // doesn't incorporate the parent path, then leave it alone + childTabPath = childTabPath.Replace(profilePagePath, string.Empty); childTabPath = childTabPath.Replace("//", "/"); urlName += FriendlyUrlController.EnsureLeadingChar("/", childTabPath); } } } + changedPath = "/" + urlName; - //append any extra remaining path value to the end + + // append any extra remaining path value to the end if (!string.IsNullOrEmpty(remainingPath)) { if (remainingPath.StartsWith("/") == false) @@ -307,10 +214,12 @@ internal static bool CheckUserProfileReplacement(string newPath, changedPath += remainingPath; } } + urlWasChanged = true; - changeToSiteRoot = true; //we will be doing domain.com/urlname + changeToSiteRoot = true; // we will be doing domain.com/urlname allowOtherParameters = false; - //can't have any others (wouldn't have matched in the regex if there were) + + // can't have any others (wouldn't have matched in the regex if there were) } else { @@ -318,9 +227,113 @@ internal static bool CheckUserProfileReplacement(string newPath, } } } + return urlWasChanged; - } + } + + /// + /// Splits out the userid value from the supplied Friendly Url Path. + /// + /// + /// The 'other' parameters which form the total UserProfile Url (if supplied). + /// + /// The remaining path not associated with the user id. + /// + private static void SplitUserIdFromFriendlyUrlPath( + string urlPath, + string parmName, + string otherParametersPath, + out string rawUserId, + out string remainingPath) + { + // 688 : allow for other parts to be in the url by capturing more with the regex filters + string regexPattern; + rawUserId = null; + remainingPath = string.Empty; + + // generally the path will start with a / and not end with one, but it's possible to get all sorts of things + if (!string.IsNullOrEmpty(otherParametersPath)) + { + // remove the trailing slash from otherParamtersPath if it exists, because the other parameters may be anywhere in the path + if (otherParametersPath.EndsWith("/")) + { + otherParametersPath = otherParametersPath.Substring(0, otherParametersPath.Length - 1); + } + + const string patternFormatWithParameters = @"/?(?.*)(?=_parm_)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)){0,1}/?(?_otherparm_){0,1}/?(?(?<=/)(?:_parm_)/(?[\d\w]+)){0,1}(?.*)"; + regexPattern = patternFormatWithParameters.Replace("_parm_", parmName); + regexPattern = regexPattern.Replace("_otherparm_", otherParametersPath); + } + else + { + const string patternNoParameters = @"/?(?.*)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)/?)+(?.*)"; + regexPattern = patternNoParameters.Replace("_parm_", parmName); + } + + // check the regex match + Match parmMatch = Regex.Match(urlPath, regexPattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + if (parmMatch.Success) + { + // must be nothing in the op1 and op2 values + Group otherParmsGp = parmMatch.Groups["op"]; + Group parm1ValueGp = parmMatch.Groups["p1v"]; + Group parm2ValueGp = parmMatch.Groups["p2v"]; + Group rem1ParmsGp = parmMatch.Groups["rem1"]; // remainder at the start of the match + Group rem2ParmsGp = parmMatch.Groups["rem2"]; // remainder at the end of the match + + if (otherParmsGp != null && otherParmsGp.Success && (parm1ValueGp.Success || parm2ValueGp.Success)) + { + // matched the other parm value and either the p1 or p2 value + rawUserId = parm1ValueGp.Success ? parm1ValueGp.Value : parm2ValueGp.Value; + } + else + { + if ((otherParmsGp == null || otherParmsGp.Success == false) && parm1ValueGp != null && + parm1ValueGp.Success) + { + rawUserId = parm1ValueGp.Value; + } + } + + // add back the remainders + if (rem1ParmsGp != null && rem1ParmsGp.Success) + { + remainingPath = rem1ParmsGp.Value; + } + + if (rem2ParmsGp != null && rem2ParmsGp.Success) + { + remainingPath += rem2ParmsGp.Value; + } + + if (remainingPath.EndsWith("/")) + { + remainingPath = remainingPath.Substring(0, remainingPath.Length - 1); + } + + // 722: drop out the parts of the remaining path that are in the 'otherParameters' path. + // the other parameters path will be automatically provided upon rewrite + if (otherParametersPath != null) + { + remainingPath = Regex.Replace(remainingPath, Regex.Escape(otherParametersPath), string.Empty, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } - #endregion + if (parmName.Contains("|") && rawUserId != null) + { + // eliminate any dups from the remaining path + string[] vals = parmName.Split('|'); + foreach (string val in vals) + { + string find = "/?" + Regex.Escape(val + "/" + rawUserId); + remainingPath = Regex.Replace(remainingPath, find, string.Empty, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + } + + if (remainingPath.Length > 0 && remainingPath.StartsWith("/") == false) + { + remainingPath = "/" + remainingPath; + } + } + } } } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs index 816c0723b47..b28facf2d3e 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs @@ -1,45 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Specialized; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + public abstract class FriendlyUrlProviderBase { - protected UrlFormatType UrlFormat { get; private set; } - internal FriendlyUrlProviderBase(NameValueCollection attributes) { - if (!String.IsNullOrEmpty(attributes["urlFormat"])) + if (!string.IsNullOrEmpty(attributes["urlFormat"])) { switch (attributes["urlFormat"].ToLowerInvariant()) { case "searchfriendly": - UrlFormat = UrlFormatType.SearchFriendly; + this.UrlFormat = UrlFormatType.SearchFriendly; break; case "humanfriendly": - UrlFormat = UrlFormatType.HumanFriendly; + this.UrlFormat = UrlFormatType.HumanFriendly; break; case "advanced": case "customonly": - UrlFormat = UrlFormatType.Advanced; + this.UrlFormat = UrlFormatType.Advanced; break; default: - UrlFormat = UrlFormatType.SearchFriendly; + this.UrlFormat = UrlFormatType.SearchFriendly; break; } } } + + protected UrlFormatType UrlFormat { get; private set; } internal abstract string FriendlyUrl(TabInfo tab, string path); diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs index 1c1f904ed7a..1e16d3da195 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs @@ -1,27 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + [Serializable] public class FriendlyUrlSettings - { - #region Private Members - + { + public const string ReplaceSpaceWithNothing = "None"; + public const string SpaceEncodingPlus = "+"; + public const string SpaceEncodingHex = "%20"; + private readonly IHostController _hostControllerInstance = HostController.Instance; - //894 : new switch to disable custom url provider + // 894 : new switch to disable custom url provider private bool? _allowDebugCode; private bool? _autoAsciiConvert; private bool? _checkForDuplicateUrls; @@ -63,21 +60,9 @@ public class FriendlyUrlSettings private string _vanityUrlPrefix; private TimeSpan? _cacheTime; private List _processRequestList; - private Dictionary _replaceCharacterDictionary; - - #endregion - - #region private helper methods - - internal List PortalValues { get; private set; } - - #endregion - - #region Constants - - public const string ReplaceSpaceWithNothing = "None"; - public const string SpaceEncodingPlus = "+"; - public const string SpaceEncodingHex = "%20"; + private Dictionary _replaceCharacterDictionary; + + internal List PortalValues { get; private set; } // Settings Keys public const string DeletedTabHandlingTypeSetting = "AUM_DeletedTabHandlingType"; @@ -121,31 +106,49 @@ public class FriendlyUrlSettings public const string InternalAliasesSetting = "AUM_InternalAliases"; public const string ProcessRequestsSetting = "AUM_ProcessRequests"; public const string CacheTimeSetting = "AUM_CacheTime"; - public const string IncludePageNameSetting = "AUM_IncludePageName"; + public const string IncludePageNameSetting = "AUM_IncludePageName"; + + public FriendlyUrlSettings(int portalId) + { + this.PortalId = portalId < -1 ? -1 : portalId; + this.IsDirty = false; + this.IsLoading = false; - #endregion + this.PortalValues = new List(); - #region Public Properties + this.TabId500 = this.TabId404 = -1; + if (portalId > -1) + { + var portal = PortalController.Instance.GetPortal(portalId); + this.TabId500 = this.TabId404 = portal.Custom404TabId; + + if (this.TabId500 == -1) + { + this.TabId500 = this.TabId404; + } + } + } + public List InternalAliasList { get; private set; } public List ProcessRequestList { get { - if (_processRequestList == null) + if (this._processRequestList == null) { - var processRequests = GetStringSetting(ProcessRequestsSetting, null); + var processRequests = this.GetStringSetting(ProcessRequestsSetting, null); if (processRequests != null) { processRequests = processRequests.ToLowerInvariant(); - _processRequestList = !string.IsNullOrEmpty(processRequests) + this._processRequestList = !string.IsNullOrEmpty(processRequests) ? new List(processRequests.Split(';')) : new List(); } } - return _processRequestList; + return this._processRequestList; } } @@ -159,13 +162,13 @@ public bool AllowDebugCode { get { - if (!_allowDebugCode.HasValue) + if (!this._allowDebugCode.HasValue) { - //703 default debug code to false - _allowDebugCode = Host.Host.DebugMode; + // 703 default debug code to false + this._allowDebugCode = Host.Host.DebugMode; } - return _allowDebugCode.Value; + return this._allowDebugCode.Value; } } @@ -173,25 +176,28 @@ public bool AutoAsciiConvert { get { - if (!_autoAsciiConvert.HasValue) + if (!this._autoAsciiConvert.HasValue) { - //urls to be modified in the output html stream - _autoAsciiConvert = GetBooleanSetting(AutoAsciiConvertSetting, false); + // urls to be modified in the output html stream + this._autoAsciiConvert = this.GetBooleanSetting(AutoAsciiConvertSetting, false); } - return _autoAsciiConvert.Value; + + return this._autoAsciiConvert.Value; } - internal set { _autoAsciiConvert = value; } + + internal set { this._autoAsciiConvert = value; } } public TimeSpan CacheTime { get { - if (!_cacheTime.HasValue) + if (!this._cacheTime.HasValue) { - _cacheTime = new TimeSpan(0, GetIntegerSetting(CacheTimeSetting, 1440), 0); + this._cacheTime = new TimeSpan(0, this.GetIntegerSetting(CacheTimeSetting, 1440), 0); } - return _cacheTime.Value; + + return this._cacheTime.Value; } } @@ -199,12 +205,13 @@ public bool CheckForDuplicateUrls { get { - if (!_checkForDuplicateUrls.HasValue) + if (!this._checkForDuplicateUrls.HasValue) { - //793 : checkforDupUrls not being read - _checkForDuplicateUrls = GetBooleanSetting(CheckForDuplicatedUrlsSetting, true); + // 793 : checkforDupUrls not being read + this._checkForDuplicateUrls = this.GetBooleanSetting(CheckForDuplicatedUrlsSetting, true); } - return _checkForDuplicateUrls.Value; + + return this._checkForDuplicateUrls.Value; } } @@ -212,20 +219,21 @@ public DeletedTabHandlingType DeletedTabHandlingType { get { - if (_deletedTabHandling == null) + if (this._deletedTabHandling == null) { - _deletedTabHandling = PortalController.GetPortalSetting( - DeletedTabHandlingTypeSetting, PortalId, DeletedTabHandlingType.Do404Error.ToString()); + this._deletedTabHandling = PortalController.GetPortalSetting( + DeletedTabHandlingTypeSetting, this.PortalId, DeletedTabHandlingType.Do404Error.ToString()); } - return "do301redirecttoportalhome".Equals(_deletedTabHandling, StringComparison.InvariantCultureIgnoreCase) + return "do301redirecttoportalhome".Equals(this._deletedTabHandling, StringComparison.InvariantCultureIgnoreCase) ? DeletedTabHandlingType.Do301RedirectToPortalHome : DeletedTabHandlingType.Do404Error; } + internal set { var newValue = value.ToString(); - _deletedTabHandling = newValue; + this._deletedTabHandling = newValue; } } @@ -233,79 +241,89 @@ public string DoNotIncludeInPathRegex { get { - //661 : do not include in path - //742 : was not reading and saving value when 'doNotIncludeInPathRegex' used - return _doNotIncludeInPathRegex ?? - (_doNotIncludeInPathRegex = - GetStringSetting(KeepInQueryStringRegexSetting, + // 661 : do not include in path + // 742 : was not reading and saving value when 'doNotIncludeInPathRegex' used + return this._doNotIncludeInPathRegex ?? + (this._doNotIncludeInPathRegex = + this.GetStringSetting( + KeepInQueryStringRegexSetting, @"/nomo/\d+|/runningDefault/[^/]+|/popup/(?:true|false)|/(?:page|category|sort|tags)/[^/]+|tou/[^/]+|(/utm[^/]+/[^/]+)+")); } - internal set { _doNotIncludeInPathRegex = value; } + + internal set { this._doNotIncludeInPathRegex = value; } } public string DoNotRedirectRegex { get { - //541 moved doNotRedirect and doNotRedirectRegex from under 'redirectUnfriendly' code - return _doNotRedirectRegex ?? (_doNotRedirectRegex = GetStringSetting(DoNotRedirectUrlRegexSetting, + // 541 moved doNotRedirect and doNotRedirectRegex from under 'redirectUnfriendly' code + return this._doNotRedirectRegex ?? (this._doNotRedirectRegex = this.GetStringSetting( + DoNotRedirectUrlRegexSetting, @"(\.axd)|/Rss\.aspx|/SiteMap\.aspx|\.ashx|/LinkClick\.aspx|/Providers/|/DesktopModules/|ctl=MobilePreview|/ctl/MobilePreview|/API/")); } - internal set { _doNotRedirectRegex = value; } + + internal set { this._doNotRedirectRegex = value; } } public string DoNotRedirectSecureRegex { get { - //541 moved doNotRedirect and doNotRedirectRegex from under 'redirectUnfriendly' code - return _doNotRedirectSecureRegex ?? (_doNotRedirectSecureRegex = GetStringSetting(DoNotRedirectHttpsUrlRegexSetting, string.Empty)); + // 541 moved doNotRedirect and doNotRedirectRegex from under 'redirectUnfriendly' code + return this._doNotRedirectSecureRegex ?? (this._doNotRedirectSecureRegex = this.GetStringSetting(DoNotRedirectHttpsUrlRegexSetting, string.Empty)); } - internal set { _doNotRedirectSecureRegex = value; } + + internal set { this._doNotRedirectSecureRegex = value; } } public string DoNotRewriteRegex { get { - return _doNotRewriteRegex ?? - (_doNotRewriteRegex = - GetStringSetting(DoNotRewriteRegExSetting, @"/DesktopModules/|/Providers/|/LinkClick\.aspx|/profilepic\.ashx|/DnnImageHandler\.ashx|/__browserLink/|/API/")); + return this._doNotRewriteRegex ?? + (this._doNotRewriteRegex = + this.GetStringSetting(DoNotRewriteRegExSetting, @"/DesktopModules/|/Providers/|/LinkClick\.aspx|/profilepic\.ashx|/DnnImageHandler\.ashx|/__browserLink/|/API/")); } - internal set { _doNotRewriteRegex = value; } + + internal set { this._doNotRewriteRegex = value; } } public bool ForceLowerCase { get { - if (!_forceLowerCase.HasValue) + if (!this._forceLowerCase.HasValue) { - _forceLowerCase = GetBooleanSetting(ForceLowerCaseSetting, false); + this._forceLowerCase = this.GetBooleanSetting(ForceLowerCaseSetting, false); } - return _forceLowerCase.Value; + + return this._forceLowerCase.Value; } - internal set { _forceLowerCase = value; } + + internal set { this._forceLowerCase = value; } } public string ForceLowerCaseRegex { - get { return _forceLowerCaseRegex ?? (_forceLowerCaseRegex = GetStringSetting(PreventLowerCaseUrlRegexSetting, string.Empty)); } - internal set { _forceLowerCaseRegex = value; } + get { return this._forceLowerCaseRegex ?? (this._forceLowerCaseRegex = this.GetStringSetting(PreventLowerCaseUrlRegexSetting, string.Empty)); } + internal set { this._forceLowerCaseRegex = value; } } public bool ForcePortalDefaultLanguage { get { - if (!_forcePortalDefaultLanguage.HasValue) + if (!this._forcePortalDefaultLanguage.HasValue) { - //810 : allow forcing of default language in rewrites - _forcePortalDefaultLanguage = GetBooleanSetting(UsePortalDefaultLanguageSetting, true); + // 810 : allow forcing of default language in rewrites + this._forcePortalDefaultLanguage = this.GetBooleanSetting(UsePortalDefaultLanguageSetting, true); } - return _forcePortalDefaultLanguage.Value; + + return this._forcePortalDefaultLanguage.Value; } - internal set { _forcePortalDefaultLanguage = value; } + + internal set { this._forcePortalDefaultLanguage = value; } } public DNNPageForwardType ForwardExternalUrlsType @@ -320,25 +338,28 @@ public bool FriendlyAdminHostUrls { get { - if (!_friendlyAdminHostUrls.HasValue) + if (!this._friendlyAdminHostUrls.HasValue) { - _friendlyAdminHostUrls = GetBooleanSetting(FriendlyAdminHostUrlsSetting, true); + this._friendlyAdminHostUrls = this.GetBooleanSetting(FriendlyAdminHostUrlsSetting, true); } - return _friendlyAdminHostUrls.Value; + + return this._friendlyAdminHostUrls.Value; } - internal set { _friendlyAdminHostUrls = value; } + + internal set { this._friendlyAdminHostUrls = value; } } public bool EnableCustomProviders { get { - if (!_enableCustomProviders.HasValue) + if (!this._enableCustomProviders.HasValue) { - //894 : new switch to disable custom providers if necessary - _enableCustomProviders = GetBooleanSetting(EnableCustomProvidersSetting, true); + // 894 : new switch to disable custom providers if necessary + this._enableCustomProviders = this.GetBooleanSetting(EnableCustomProvidersSetting, true); } - return _enableCustomProviders.Value; + + return this._enableCustomProviders.Value; } } @@ -346,20 +367,22 @@ public string IgnoreRegex { get { - return _ignoreRegex ?? - (_ignoreRegex = - GetStringSetting(IgnoreRegexSetting, + return this._ignoreRegex ?? + (this._ignoreRegex = + this.GetStringSetting( + IgnoreRegexSetting, @"(?/\?:&=+|%#")); + // 922 : new options for allowing user-configured replacement of characters + return this._illegalChars ?? (this._illegalChars = this.GetStringSetting(IllegalCharsSetting, @"<>/\?:&=+|%#")); } } @@ -367,25 +390,27 @@ public bool IncludePageName { get { - if (!_includePageName.HasValue) + if (!this._includePageName.HasValue) { - _includePageName = GetBooleanSetting(IncludePageNameSetting, true); + this._includePageName = this.GetBooleanSetting(IncludePageNameSetting, true); } - return _includePageName.Value; + return this._includePageName.Value; } - internal set { _includePageName = value; } + + internal set { this._includePageName = value; } } public bool LogCacheMessages { get { - if (!_logCacheMessages.HasValue) + if (!this._logCacheMessages.HasValue) { - _logCacheMessages = GetBooleanSetting(LogCacheMessagesSetting, false); + this._logCacheMessages = this.GetBooleanSetting(LogCacheMessagesSetting, false); } - return _logCacheMessages.Value; + + return this._logCacheMessages.Value; } } @@ -393,29 +418,30 @@ public string NoFriendlyUrlRegex { get { - //655 : new noFriendlyUrlRegex value to ignore generation of certain urls - return _noFriendlyUrlRegex ?? (_noFriendlyUrlRegex = GetStringSetting(DoNotUseFriendlyUrlRegexSetting, @"/Rss\.aspx")); + // 655 : new noFriendlyUrlRegex value to ignore generation of certain urls + return this._noFriendlyUrlRegex ?? (this._noFriendlyUrlRegex = this.GetStringSetting(DoNotUseFriendlyUrlRegexSetting, @"/Rss\.aspx")); } - internal set { _noFriendlyUrlRegex = value; } + + internal set { this._noFriendlyUrlRegex = value; } } public string PageExtension { - get { return _pageExtension ?? (_pageExtension = GetStringSetting(PageExtensionSetting, ".aspx")); } - internal set { _pageExtension = value; } + get { return this._pageExtension ?? (this._pageExtension = this.GetStringSetting(PageExtensionSetting, ".aspx")); } + internal set { this._pageExtension = value; } } public PageExtensionUsageType PageExtensionUsageType { get { - if (_pageExtensionUsage == null) + if (this._pageExtensionUsage == null) { - _pageExtensionUsage = GetStringSetting(PageExtensionUsageSetting, PageExtensionUsageType.Never.ToString()); + this._pageExtensionUsage = this.GetStringSetting(PageExtensionUsageSetting, PageExtensionUsageType.Never.ToString()); } PageExtensionUsageType val; - switch (_pageExtensionUsage.ToLowerInvariant()) + switch (this._pageExtensionUsage.ToLowerInvariant()) { case "always": case "alwaysuse": @@ -431,12 +457,14 @@ public PageExtensionUsageType PageExtensionUsageType val = PageExtensionUsageType.Never; break; } + return val; } + internal set { var newValue = value.ToString(); - _pageExtensionUsage = newValue; + this._pageExtensionUsage = newValue; } } @@ -444,75 +472,84 @@ public bool RedirectDefaultPage { get { - if (!_redirectDefaultPage.HasValue) + if (!this._redirectDefaultPage.HasValue) { - _redirectDefaultPage = GetBooleanSetting(RedirectDefaultPageSetting, false); + this._redirectDefaultPage = this.GetBooleanSetting(RedirectDefaultPageSetting, false); } - return _redirectDefaultPage.Value; + + return this._redirectDefaultPage.Value; } - internal set { _redirectUnfriendly = value; } + + internal set { this._redirectUnfriendly = value; } } public bool RedirectOldProfileUrl { get { - if (!_redirectOldProfileUrl.HasValue) + if (!this._redirectOldProfileUrl.HasValue) { - _redirectOldProfileUrl = PortalController.GetPortalSettingAsBoolean(RedirectOldProfileUrlSetting, PortalId, true); + this._redirectOldProfileUrl = PortalController.GetPortalSettingAsBoolean(RedirectOldProfileUrlSetting, this.PortalId, true); } - return _redirectOldProfileUrl.Value; + + return this._redirectOldProfileUrl.Value; } - internal set { _redirectOldProfileUrl = value; } + + internal set { this._redirectOldProfileUrl = value; } } public bool RedirectUnfriendly { get { - if (!_redirectUnfriendly.HasValue) + if (!this._redirectUnfriendly.HasValue) { - _redirectUnfriendly = GetBooleanSetting(RedirectUnfriendlySetting, true); + this._redirectUnfriendly = this.GetBooleanSetting(RedirectUnfriendlySetting, true); } - return _redirectUnfriendly.Value; + + return this._redirectUnfriendly.Value; } - internal set { _redirectUnfriendly = value; } + + internal set { this._redirectUnfriendly = value; } } public bool RedirectWrongCase { get { - if (!_redirectWrongCase.HasValue) + if (!this._redirectWrongCase.HasValue) { - _redirectWrongCase = GetBooleanSetting(RedirectMixedCaseSetting, false); + this._redirectWrongCase = this.GetBooleanSetting(RedirectMixedCaseSetting, false); } - return _redirectWrongCase.Value; + + return this._redirectWrongCase.Value; } - internal set { _redirectWrongCase = value; } + + internal set { this._redirectWrongCase = value; } } public string Regex404 { - get { return _regex404 ?? (_regex404 = GetStringSetting(Regex404Setting, string.Empty)); } + get { return this._regex404 ?? (this._regex404 = this.GetStringSetting(Regex404Setting, string.Empty)); } } public string RegexMatch { - get { return _regexMatch ?? (_regexMatch = GetStringSetting(ValidFriendlyUrlRegexSetting, @"[^\w\d _-]")); } - internal set { _regexMatch = value; } + get { return this._regexMatch ?? (this._regexMatch = this.GetStringSetting(ValidFriendlyUrlRegexSetting, @"[^\w\d _-]")); } + internal set { this._regexMatch = value; } } public Dictionary ReplaceCharacterDictionary { get { - if (_replaceCharacterDictionary == null) + if (this._replaceCharacterDictionary == null) { - var replaceCharwithChar = GetStringSetting(ReplaceCharWithCharSetting, string.Empty); - _replaceCharacterDictionary = CollectionExtensions.CreateDictionaryFromString(replaceCharwithChar == "[]" ? string.Empty : replaceCharwithChar, ';', ','); + var replaceCharwithChar = this.GetStringSetting(ReplaceCharWithCharSetting, string.Empty); + this._replaceCharacterDictionary = CollectionExtensions.CreateDictionaryFromString(replaceCharwithChar == "[]" ? string.Empty : replaceCharwithChar, ';', ','); } - return _replaceCharacterDictionary; + + return this._replaceCharacterDictionary; } } @@ -520,8 +557,8 @@ public string ReplaceChars { get { - //922 : new options for allowing user-configured replacement of characters - return _replaceChars ?? (_replaceChars = GetStringSetting(ReplaceCharsSetting, @" &$+,/?~#<>()¿¡«»!""")); + // 922 : new options for allowing user-configured replacement of characters + return this._replaceChars ?? (this._replaceChars = this.GetStringSetting(ReplaceCharsSetting, @" &$+,/?~#<>()¿¡«»!""")); } } @@ -529,12 +566,13 @@ public bool ReplaceDoubleChars { get { - if (!_replaceDoubleChars.HasValue) + if (!this._replaceDoubleChars.HasValue) { - //922 : new options for allowing user-configured replacement of characters - _replaceDoubleChars = GetBooleanSetting(ReplaceDoubleCharsSetting, true); + // 922 : new options for allowing user-configured replacement of characters + this._replaceDoubleChars = this.GetBooleanSetting(ReplaceDoubleCharsSetting, true); } - return _replaceDoubleChars.Value; + + return this._replaceDoubleChars.Value; } } @@ -542,29 +580,32 @@ public string ReplaceSpaceWith { get { - //791 : use threadlocking option - return _replaceSpaceWith ?? (_replaceSpaceWith = GetStringSetting(ReplaceSpaceWithSetting, "-")); + // 791 : use threadlocking option + return this._replaceSpaceWith ?? (this._replaceSpaceWith = this.GetStringSetting(ReplaceSpaceWithSetting, "-")); } - internal set { _replaceSpaceWith = value; } + + internal set { this._replaceSpaceWith = value; } } public string SpaceEncodingValue { - get { return _spaceEncodingValue ?? (_spaceEncodingValue = GetStringSetting(SpaceEncodingValueSetting, SpaceEncodingHex)); } - internal set { _spaceEncodingValue = value; } + get { return this._spaceEncodingValue ?? (this._spaceEncodingValue = this.GetStringSetting(SpaceEncodingValueSetting, SpaceEncodingHex)); } + internal set { this._spaceEncodingValue = value; } } public bool SSLClientRedirect { get { - if (!_sslClientRedirect.HasValue) + if (!this._sslClientRedirect.HasValue) { - _sslClientRedirect = GetBooleanSetting(SslClientRedirectSetting, false); + this._sslClientRedirect = this.GetBooleanSetting(SslClientRedirectSetting, false); } - return _sslClientRedirect.Value; + + return this._sslClientRedirect.Value; } - internal set { _sslClientRedirect = value; } + + internal set { this._sslClientRedirect = value; } } public int TabId404 { get; private set; } @@ -573,101 +614,104 @@ public bool SSLClientRedirect public string Url404 { - get { return _url404 ?? (_url404 = GetStringSetting(Url404Setting, string.Empty)); } + get { return this._url404 ?? (this._url404 = this.GetStringSetting(Url404Setting, string.Empty)); } } public string Url500 { - get { return _url500 ?? (_url500 = GetStringSetting(Url500Setting, null) ?? Url404); } + get { return this._url500 ?? (this._url500 = this.GetStringSetting(Url500Setting, null) ?? this.Url404); } } public string UrlFormat { get { - return _urlFormat ?? (_urlFormat = GetStringSetting(UrlFormatSetting, "advanced")); + return this._urlFormat ?? (this._urlFormat = this.GetStringSetting(UrlFormatSetting, "advanced")); } - internal set { _urlFormat = value; } + + internal set { this._urlFormat = value; } } public string UseBaseFriendlyUrls { get { - if (_useBaseFriendlyUrls == null) + if (this._useBaseFriendlyUrls == null) { - _useBaseFriendlyUrls = GetStringSetting(UseBaseFriendlyUrlsSetting, string.Empty); - if (!string.IsNullOrEmpty(UseBaseFriendlyUrls) && !UseBaseFriendlyUrls.EndsWith(";")) + this._useBaseFriendlyUrls = this.GetStringSetting(UseBaseFriendlyUrlsSetting, string.Empty); + if (!string.IsNullOrEmpty(this.UseBaseFriendlyUrls) && !this.UseBaseFriendlyUrls.EndsWith(";")) { - _useBaseFriendlyUrls += ";"; + this._useBaseFriendlyUrls += ";"; } } - return _useBaseFriendlyUrls; + + return this._useBaseFriendlyUrls; } - internal set { _useBaseFriendlyUrls = value; } + + internal set { this._useBaseFriendlyUrls = value; } } public string UseSiteUrlsRegex { get { - return _useSiteUrlsRegex ?? - (_useSiteUrlsRegex = - GetStringSetting(SiteUrlsOnlyRegexSetting, + return this._useSiteUrlsRegex ?? + (this._useSiteUrlsRegex = + this.GetStringSetting( + SiteUrlsOnlyRegexSetting, @"/rss\.aspx|Telerik.RadUploadProgressHandler\.ashx|BannerClickThrough\.aspx|(?:/[^/]+)*/Tabid/\d+/.*default\.aspx")); } - internal set { _useSiteUrlsRegex = value; } + + internal set { this._useSiteUrlsRegex = value; } } public string ValidExtensionlessUrlsRegex { get { - //893 : new extensionless Urls check for validating urls which have no extension but aren't 404 - return _validExtensionlessUrlsRegex ?? - (_validExtensionlessUrlsRegex = GetStringSetting(UrlsWithNoExtensionRegexSetting, @"\.asmx/|\.ashx/|\.svc/|\.aspx/|\.axd/")); + // 893 : new extensionless Urls check for validating urls which have no extension but aren't 404 + return this._validExtensionlessUrlsRegex ?? + (this._validExtensionlessUrlsRegex = this.GetStringSetting(UrlsWithNoExtensionRegexSetting, @"\.asmx/|\.ashx/|\.svc/|\.aspx/|\.axd/")); } - internal set { _validExtensionlessUrlsRegex = value; } + + internal set { this._validExtensionlessUrlsRegex = value; } } public string InternalAliases { get { - if (_internalAliases == null) + if (this._internalAliases == null) { // allow for a list of internal aliases - InternalAliases = GetStringSetting(InternalAliasesSetting, string.Empty); // calls the setter + this.InternalAliases = this.GetStringSetting(InternalAliasesSetting, string.Empty); // calls the setter } - return _internalAliases; + + return this._internalAliases; } internal set { - _internalAliases = value; - ParseInternalAliases(); //splits into list + this._internalAliases = value; + this.ParseInternalAliases(); // splits into list } } public string VanityUrlPrefix { - get { return _vanityUrlPrefix ?? (_vanityUrlPrefix = GetStringSetting(VanityUrlPrefixSetting, "users")); } - internal set { _vanityUrlPrefix = value; } - } - - #endregion - - #region initialization methods - + get { return this._vanityUrlPrefix ?? (this._vanityUrlPrefix = this.GetStringSetting(VanityUrlPrefixSetting, "users")); } + internal set { this._vanityUrlPrefix = value; } + } + private bool GetBooleanSetting(string key, bool defaultValue) { - //First Get the Host Value using the passed in value as default - var returnValue = _hostControllerInstance.GetBoolean(key, defaultValue); + // First Get the Host Value using the passed in value as default + var returnValue = this._hostControllerInstance.GetBoolean(key, defaultValue); - if (PortalId > -1) + if (this.PortalId > -1) { - //Next check if there is a Portal Value, using the Host value as default - returnValue = PortalController.GetPortalSettingAsBoolean(key, PortalId, returnValue); + // Next check if there is a Portal Value, using the Host value as default + returnValue = PortalController.GetPortalSettingAsBoolean(key, this.PortalId, returnValue); } return returnValue; @@ -675,13 +719,13 @@ private bool GetBooleanSetting(string key, bool defaultValue) private int GetIntegerSetting(string key, int defaultValue) { - //First Get the Host Value using the passed in value as default - var returnValue = _hostControllerInstance.GetInteger(key, defaultValue); + // First Get the Host Value using the passed in value as default + var returnValue = this._hostControllerInstance.GetInteger(key, defaultValue); - if (PortalId > -1) + if (this.PortalId > -1) { - //Next check if there is a Portal Value, using the Host value as default - returnValue = PortalController.GetPortalSettingAsInteger(key, PortalId, returnValue); + // Next check if there is a Portal Value, using the Host value as default + returnValue = PortalController.GetPortalSettingAsInteger(key, this.PortalId, returnValue); } return returnValue; @@ -689,64 +733,36 @@ private int GetIntegerSetting(string key, int defaultValue) private string GetStringSetting(string key, string defaultValue) { - //First Get the Host Value using the passed in value as default - var returnValue = _hostControllerInstance.GetString(key, defaultValue); + // First Get the Host Value using the passed in value as default + var returnValue = this._hostControllerInstance.GetString(key, defaultValue); - if (PortalId > -1) + if (this.PortalId > -1) { - //Next check if there is a Portal Value, using the Host value as default - returnValue = PortalController.GetPortalSetting(key, PortalId, returnValue); + // Next check if there is a Portal Value, using the Host value as default + returnValue = PortalController.GetPortalSetting(key, this.PortalId, returnValue); } return returnValue; - } - - #endregion - - #region others - - public FriendlyUrlSettings(int portalId) - { - PortalId = portalId < -1 ? -1 : portalId; - IsDirty = false; - IsLoading = false; - - PortalValues = new List(); - - TabId500 = TabId404 = -1; - - if (portalId > -1) - { - var portal = PortalController.Instance.GetPortal(portalId); - TabId500 = TabId404 = portal.Custom404TabId; - - if (TabId500 == -1) - { - TabId500 = TabId404; - } - } - } + } private void ParseInternalAliases() { - if (!string.IsNullOrEmpty(_internalAliases)) + if (!string.IsNullOrEmpty(this._internalAliases)) { - InternalAliasList = new List(); - var raw = _internalAliases.Split(';'); + this.InternalAliasList = new List(); + var raw = this._internalAliases.Split(';'); foreach (var rawVal in raw) { if (rawVal.Length > 0) { var ia = new InternalAlias { HttpAlias = rawVal }; - if (InternalAliasList.Contains(ia) == false) + if (this.InternalAliasList.Contains(ia) == false) { - InternalAliasList.Add(ia); + this.InternalAliasList.Add(ia); } } } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Urls/IExtensionUrlProviderSettingsControl.cs b/DNN Platform/Library/Entities/Urls/IExtensionUrlProviderSettingsControl.cs index 698cd87dd13..5366d758e6a 100644 --- a/DNN Platform/Library/Entities/Urls/IExtensionUrlProviderSettingsControl.cs +++ b/DNN Platform/Library/Entities/Urls/IExtensionUrlProviderSettingsControl.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System.Collections.Generic; + public interface IExtensionUrlProviderSettingsControl { ExtensionUrlProviderInfo Provider { get; set; } @@ -13,7 +13,7 @@ public interface IExtensionUrlProviderSettingsControl void LoadSettings(); /// - /// Build the Settings Dictionary and return it to the caller to persist to the database + /// Build the Settings Dictionary and return it to the caller to persist to the database. /// /// Dictionary SaveSettings(); diff --git a/DNN Platform/Library/Entities/Urls/InternalAlias.cs b/DNN Platform/Library/Entities/Urls/InternalAlias.cs index 46cebdb5605..3d29e08028a 100644 --- a/DNN Platform/Library/Entities/Urls/InternalAlias.cs +++ b/DNN Platform/Library/Entities/Urls/InternalAlias.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + [Serializable] public class InternalAlias { diff --git a/DNN Platform/Library/Entities/Urls/PageExtensionUsageType.cs b/DNN Platform/Library/Entities/Urls/PageExtensionUsageType.cs index 628128d3158..043a2d946a5 100644 --- a/DNN Platform/Library/Entities/Urls/PageExtensionUsageType.cs +++ b/DNN Platform/Library/Entities/Urls/PageExtensionUsageType.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum PageExtensionUsageType { AlwaysUse, PageOnly, - Never + Never, } } diff --git a/DNN Platform/Library/Entities/Urls/PageIndexData.cs b/DNN Platform/Library/Entities/Urls/PageIndexData.cs index c096274da4b..1b62730dd46 100644 --- a/DNN Platform/Library/Entities/Urls/PageIndexData.cs +++ b/DNN Platform/Library/Entities/Urls/PageIndexData.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + /// /// The PageIndexData class is used during the page index build process. /// diff --git a/DNN Platform/Library/Entities/Urls/PageUsage.cs b/DNN Platform/Library/Entities/Urls/PageUsage.cs index c1e251e63c8..69752c75360 100644 --- a/DNN Platform/Library/Entities/Urls/PageUsage.cs +++ b/DNN Platform/Library/Entities/Urls/PageUsage.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum PageUsage { NoTabs = -1, ThisTab = 0, - //AnotherTab = 1, - //AllTabs = 2 + + // AnotherTab = 1, + // AllTabs = 2 } } diff --git a/DNN Platform/Library/Entities/Urls/PagingInfo.cs b/DNN Platform/Library/Entities/Urls/PagingInfo.cs index a6a0840c0a1..12cb21a0542 100644 --- a/DNN Platform/Library/Entities/Urls/PagingInfo.cs +++ b/DNN Platform/Library/Entities/Urls/PagingInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { /// - /// Class used as a utility to help manage paging in database queries + /// Class used as a utility to help manage paging in database queries. /// public class PagingInfo { public PagingInfo(int pageNumber, int pageSize) { - PageNumber = pageNumber; - PageSize = pageSize; + this.PageNumber = pageNumber; + this.PageSize = pageSize; } public int PageNumber { get; private set; } @@ -31,7 +31,7 @@ public bool IsLastPage { get { - if (LastRow >= (TotalRows)) + if (this.LastRow >= this.TotalRows) { return true; } @@ -44,10 +44,10 @@ public bool IsLastPage public void UpdatePageResults(int firstRow, int lastRow, int totalRows, int totalPages) { - FirstRow = firstRow; - LastRow = lastRow; - TotalRows = totalRows; - TotalPages = totalPages; + this.FirstRow = firstRow; + this.LastRow = lastRow; + this.TotalRows = totalRows; + this.TotalPages = totalPages; } } } diff --git a/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs b/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs index d7bb47817ac..c9957cd76d5 100644 --- a/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs +++ b/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs @@ -1,21 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + [Serializable] public class ParameterRedirectAction { public string Action { get; set; } + public bool ChangeToSiteRoot { get; set; } + public bool ForDefaultPage { get; set; } + public string LookFor { get; set; } + public string Name { get; set; } + public int PortalId { get; set; } + public string RedirectTo { get; set; } + public int TabId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs b/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs index 3b3b0b2bafd..55720826aab 100644 --- a/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs +++ b/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs @@ -1,19 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + [Serializable] public class ParameterReplaceAction { public bool ChangeToSiteRoot { get; set; } + public string LookFor { get; set; } + public string Name { get; set; } + public int PortalId { get; set; } + public string ReplaceWith { get; set; } + public int TabId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs b/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs index ca3382e48b7..c737dc4a4e2 100644 --- a/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs +++ b/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs @@ -1,19 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + [Serializable] public class ParameterRewriteAction { public bool ForSiteRoot { get; set; } + public string LookFor { get; set; } + public string Name { get; set; } + public int PortalId { get; set; } + public string RewriteTo { get; set; } + public int TabId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/PathSizes.cs b/DNN Platform/Library/Entities/Urls/PathSizes.cs index fb210ce3f8b..8656a61c8bc 100644 --- a/DNN Platform/Library/Entities/Urls/PathSizes.cs +++ b/DNN Platform/Library/Entities/Urls/PathSizes.cs @@ -1,45 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + [Serializable] public class PathSizes { public int MaxAliasDepth { get; set; } - public int MaxTabPathDepth{ get; set; } + + public int MaxTabPathDepth { get; set; } + public int MinAliasDepth { get; set; } + public int MinTabPathDepth { get; set; } public void SetAliasDepth(string httpAlias) { - int aliasPathDepth = httpAlias.Length - httpAlias.Replace("/", "").Length; - if (aliasPathDepth > MaxAliasDepth) + int aliasPathDepth = httpAlias.Length - httpAlias.Replace("/", string.Empty).Length; + if (aliasPathDepth > this.MaxAliasDepth) { - MaxAliasDepth = aliasPathDepth; + this.MaxAliasDepth = aliasPathDepth; } - if (aliasPathDepth < MinAliasDepth) + + if (aliasPathDepth < this.MinAliasDepth) { - MinAliasDepth = aliasPathDepth; + this.MinAliasDepth = aliasPathDepth; } } public void SetTabPathDepth(int tabPathDepth) { - if (tabPathDepth > MaxTabPathDepth) + if (tabPathDepth > this.MaxTabPathDepth) { - MaxTabPathDepth = tabPathDepth; + this.MaxTabPathDepth = tabPathDepth; } - if (tabPathDepth < MinTabPathDepth) + + if (tabPathDepth < this.MinTabPathDepth) { - MinTabPathDepth = tabPathDepth; + this.MinTabPathDepth = tabPathDepth; } } } diff --git a/DNN Platform/Library/Entities/Urls/RedirectController.cs b/DNN Platform/Library/Entities/Urls/RedirectController.cs index c4cc9a80600..db2d75682cd 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectController.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectController.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + internal class RedirectController { /// - /// Cancels a redirect + /// Cancels a redirect. /// /// /// @@ -33,25 +28,30 @@ internal static void CancelRedirect(ref UrlAction result, HttpContext context, F result.Action = ActionType.Continue; result.Reason = RedirectReason.Not_Redirected; result.FinalUrl = null; - //clean the path for the rewrite + + // clean the path for the rewrite NameValueCollection queryString = null; if (context != null) { queryString = context.Request.QueryString; } + result.RewritePath = RedirectTokens.RemoveAnyRedirectTokens(result.RewritePath, queryString); - //redo the rewrite to fix up the problem. The user has ticked 'permanent redirect' but hasn't supplied a forwarding Url + + // redo the rewrite to fix up the problem. The user has ticked 'permanent redirect' but hasn't supplied a forwarding Url if (context != null) - //if no context supplied, means no rewrite was required because querystring didn't contain do301 action + + // if no context supplied, means no rewrite was required because querystring didn't contain do301 action { - //RewriterUtils.RewriteUrl(context, result.RewritePath, settings.RebaseClientPath); + // RewriterUtils.RewriteUrl(context, result.RewritePath, settings.RebaseClientPath); RewriterUtils.RewriteUrl(context, result.RewritePath); } + result.DebugMessages.Add(message); } /// - /// Checks for a redirect based on a module friendly url provider rule + /// Checks for a redirect based on a module friendly url provider rule. /// /// /// @@ -59,116 +59,129 @@ internal static void CancelRedirect(ref UrlAction result, HttpContext context, F /// /// /// - internal static bool CheckForModuleProviderRedirect(Uri requestUri, - ref UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - Guid parentTraceId) + internal static bool CheckForModuleProviderRedirect( + Uri requestUri, + ref UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + Guid parentTraceId) { var messages = new List(); string location; - bool redirected = ExtensionUrlProviderController.CheckForRedirect(requestUri, - result, - queryStringCol, - settings, - out location, - ref messages, - parentTraceId); + bool redirected = ExtensionUrlProviderController.CheckForRedirect( + requestUri, + result, + queryStringCol, + settings, + out location, + ref messages, + parentTraceId); if (messages != null) { result.DebugMessages.AddRange(messages); } + if (redirected) { result.FinalUrl = location; result.Action = ActionType.Redirect301; result.Reason = RedirectReason.Custom_Redirect; } + return redirected; } - internal static bool CheckForParameterRedirect(Uri requestUri, - ref UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings) + internal static bool CheckForParameterRedirect( + Uri requestUri, + ref UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings) { - //check for parameter replaced works by inspecting the parameters on a rewritten request, comparing - //them agains the list of regex expressions on the friendlyurls.config file, and redirecting to the same page - //but with new parameters, if there was a match + // check for parameter replaced works by inspecting the parameters on a rewritten request, comparing + // them agains the list of regex expressions on the friendlyurls.config file, and redirecting to the same page + // but with new parameters, if there was a match bool redirect = false; - //get the redirect actions for this portal + + // get the redirect actions for this portal var messages = new List(); Dictionary> redirectActions = CacheController.GetParameterRedirects(settings, result.PortalId, ref messages); if (redirectActions != null && redirectActions.Count > 0) { try - { - #region trycatch block - + { string rewrittenUrl = result.RewritePath ?? result.RawUrl; List parmRedirects = null; - //find the matching redirects for the tabid + + // find the matching redirects for the tabid int tabId = result.TabId; if (tabId > -1) { if (redirectActions.ContainsKey(tabId)) { - //find the right set of replaced actions for this tab + // find the right set of replaced actions for this tab parmRedirects = redirectActions[tabId]; } } - //check for 'all tabs' redirections - if (redirectActions.ContainsKey(-1)) //-1 means 'all tabs' - rewriting across all tabs + + // check for 'all tabs' redirections + if (redirectActions.ContainsKey(-1)) // -1 means 'all tabs' - rewriting across all tabs { - //initialise to empty collection if there are no specific tab redirects + // initialise to empty collection if there are no specific tab redirects if (parmRedirects == null) { parmRedirects = new List(); } - //add in the all redirects + + // add in the all redirects List allRedirects = redirectActions[-1]; - parmRedirects.AddRange(allRedirects); //add the 'all' range to the tab range + parmRedirects.AddRange(allRedirects); // add the 'all' range to the tab range tabId = result.TabId; } + if (redirectActions.ContainsKey(-2) && result.OriginalPath.ToLowerInvariant().Contains("default.aspx")) { - //for the default.aspx page + // for the default.aspx page if (parmRedirects == null) { parmRedirects = new List(); } + List defaultRedirects = redirectActions[-2]; - parmRedirects.AddRange(defaultRedirects); //add the default.aspx redirects to the list + parmRedirects.AddRange(defaultRedirects); // add the default.aspx redirects to the list tabId = result.TabId; } - //726 : allow for site-root redirects, ie redirects where no page match + + // 726 : allow for site-root redirects, ie redirects where no page match if (redirectActions.ContainsKey(-3)) { - //request is for site root + // request is for site root if (parmRedirects == null) { parmRedirects = new List(); } + List siteRootRedirects = redirectActions[-3]; - parmRedirects.AddRange(siteRootRedirects); //add the site root redirects to the collection + parmRedirects.AddRange(siteRootRedirects); // add the site root redirects to the collection } - //OK what we have now is a list of redirects for the currently requested tab (either because it was specified by tab id, + + // OK what we have now is a list of redirects for the currently requested tab (either because it was specified by tab id, // or because there is a replaced for 'all tabs' - if (parmRedirects != null && parmRedirects.Count > 0 && rewrittenUrl != null) { foreach (ParameterRedirectAction parmRedirect in parmRedirects) { - //regex test each replaced to see if there is a match between the parameter string - //and the parmRedirect + // regex test each replaced to see if there is a match between the parameter string + // and the parmRedirect string compareWith = rewrittenUrl; - var redirectRegex = RegexUtils.GetCachedRegex(parmRedirect.LookFor, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + var redirectRegex = RegexUtils.GetCachedRegex( + parmRedirect.LookFor, + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); Match regexMatch = redirectRegex.Match(compareWith); bool success = regexMatch.Success; bool siteRootTried = false; - //if no match, but there is a site root redirect to try + + // if no match, but there is a site root redirect to try if (!success && parmRedirect.TabId == -3) { siteRootTried = true; @@ -176,6 +189,7 @@ internal static bool CheckForParameterRedirect(Uri requestUri, regexMatch = redirectRegex.Match(compareWith); success = regexMatch.Success; } + if (!success) { result.DebugMessages.Add(parmRedirect.Name + " redirect not matched (" + rewrittenUrl + @@ -188,7 +202,7 @@ internal static bool CheckForParameterRedirect(Uri requestUri, } else { - //success! there was a match in the parameters + // success! there was a match in the parameters string parms = redirectRegex.Replace(compareWith, parmRedirect.RedirectTo); if (siteRootTried) { @@ -200,26 +214,30 @@ internal static bool CheckForParameterRedirect(Uri requestUri, result.DebugMessages.Add(parmRedirect.Name + " redirect matched with (" + compareWith + "), replaced with " + parms); } - string finalUrl = ""; - //now we need to generate the friendly Url + + string finalUrl = string.Empty; + + // now we need to generate the friendly Url - //first check to see if the parameter replacement string has a destination tabid specified + // first check to see if the parameter replacement string has a destination tabid specified if (parms.ToLowerInvariant().Contains("tabid/")) { - //if so, using a feature whereby the dest tabid can be changed within the parameters, which will - //redirect the page as well as redirecting the parameter values + // if so, using a feature whereby the dest tabid can be changed within the parameters, which will + // redirect the page as well as redirecting the parameter values string[] parmParts = parms.Split('/'); bool tabIdNext = false; foreach (string parmPart in parmParts) { if (tabIdNext) { - //changes the tabid of page, effects a page redirect along with a parameter redirect - Int32.TryParse(parmPart, out tabId); - parms = parms.Replace("tabid/" + tabId.ToString(), ""); - //remove the tabid/xx from the path - break; //that's it, we're finished + // changes the tabid of page, effects a page redirect along with a parameter redirect + int.TryParse(parmPart, out tabId); + parms = parms.Replace("tabid/" + tabId.ToString(), string.Empty); + + // remove the tabid/xx from the path + break; // that's it, we're finished } + if (parmPart.Equals("tabid", StringComparison.InvariantCultureIgnoreCase)) { tabIdNext = true; @@ -228,39 +246,43 @@ internal static bool CheckForParameterRedirect(Uri requestUri, } else if (tabId == -1) { - //find the home tabid for this portal - //735 : switch to custom method for getting portal + // find the home tabid for this portal + // 735 : switch to custom method for getting portal PortalInfo portal = CacheController.GetPortal(result.PortalId, true); tabId = portal.HomeTabId; } + if (parmRedirect.ChangeToSiteRoot) { - //when change to siteroot requested, new path goes directly off the portal alias - //so set the finalUrl as the poratl alias + // when change to siteroot requested, new path goes directly off the portal alias + // so set the finalUrl as the poratl alias finalUrl = result.Scheme + result.HttpAlias + "/"; } else { - //if the tabid has been supplied, do a friendly url provider lookup to get the correct format for the tab url + // if the tabid has been supplied, do a friendly url provider lookup to get the correct format for the tab url if (tabId > -1) { TabInfo tab = TabController.Instance.GetTab(tabId, result.PortalId, false); if (tab != null) { - string path = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tab.TabID, ""); - string friendlyUrlNoParms = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - path, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - Guid.Empty); + string path = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tab.TabID, string.Empty); + string friendlyUrlNoParms = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + path, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + Guid.Empty); if (friendlyUrlNoParms.EndsWith("/") == false) { friendlyUrlNoParms += "/"; } + finalUrl = friendlyUrlNoParms; } + if (tab == null) { result.DebugMessages.Add(parmRedirect.Name + @@ -279,10 +301,12 @@ internal static bool CheckForParameterRedirect(Uri requestUri, } } } + if (parms.StartsWith("//")) { parms = parms.Substring(2); } + if (parms.StartsWith("/")) { parms = parms.Substring(1); @@ -294,36 +318,40 @@ internal static bool CheckForParameterRedirect(Uri requestUri, { parms = parms.TrimEnd('/'); } + if (parms.Length > 0) { - //we are adding more parms onto the end, so remove the page extension - //from the parameter list - //946 : exception when settings.PageExtension value is empty + // we are adding more parms onto the end, so remove the page extension + // from the parameter list + // 946 : exception when settings.PageExtension value is empty parms += settings.PageExtension; - //816: if page extension is /, then don't do this + + // 816: if page extension is /, then don't do this if (settings.PageExtension != "/" && string.IsNullOrEmpty(settings.PageExtension) == false) { - finalUrl = finalUrl.Replace(settings.PageExtension, ""); + finalUrl = finalUrl.Replace(settings.PageExtension, string.Empty); } } else { - //we are removing all the parms altogether, so - //the url needs to end in the page extension only - //816: if page extension is /, then don't do this + // we are removing all the parms altogether, so + // the url needs to end in the page extension only + // 816: if page extension is /, then don't do this if (settings.PageExtension != "/" && string.IsNullOrEmpty(settings.PageExtension) == false) { - finalUrl = finalUrl.Replace(settings.PageExtension + "/", - settings.PageExtension); + finalUrl = finalUrl.Replace( + settings.PageExtension + "/", + settings.PageExtension); } } } - //put the replaced parms back on the end + + // put the replaced parms back on the end finalUrl += parms; - //set the final url + // set the final url result.FinalUrl = finalUrl; result.Reason = RedirectReason.Custom_Redirect; switch (parmRedirect.Action) @@ -338,13 +366,12 @@ internal static bool CheckForParameterRedirect(Uri requestUri, result.Action = ActionType.Output404; break; } + redirect = true; break; } } - } - - #endregion + } } catch (Exception ex) { @@ -359,6 +386,7 @@ internal static bool CheckForParameterRedirect(Uri requestUri, } } } + return redirect; } @@ -373,50 +401,54 @@ internal static bool CheckForParameterRedirect(Uri requestUri, /// /// /// - /// 823 : Moved from CheckForRedirects to allow call earlier in pipeline - internal static string GetTabRedirectUrl(TabInfo tab, - FriendlyUrlSettings settings, - string cleanPath, - UrlAction result, - out bool permRedirect, - Guid parentTraceId) + /// 823 : Moved from CheckForRedirects to allow call earlier in pipeline. + internal static string GetTabRedirectUrl( + TabInfo tab, + FriendlyUrlSettings settings, + string cleanPath, + UrlAction result, + out bool permRedirect, + Guid parentTraceId) { string bestFriendlyUrl = null; - //592 : check for permanent redirect + + // 592 : check for permanent redirect permRedirect = tab.PermanentRedirect; int redirectTabId; if (int.TryParse(tab.Url, out redirectTabId)) { - //ok, redirecting to a new tab, specified by the tabid in the Url field + // ok, redirecting to a new tab, specified by the tabid in the Url field TabInfo redirectTab = TabController.Instance.GetTab(redirectTabId, tab.PortalID, false); if (redirectTab != null) { - //now get the friendly url for that tab - bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(redirectTab, - cleanPath, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - parentTraceId); + // now get the friendly url for that tab + bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + redirectTab, + cleanPath, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + parentTraceId); } } else { - //use the url, as specified in the dnn tab url property - //776 : when no url, don't redirect - if (tab.Url != "") + // use the url, as specified in the dnn tab url property + // 776 : when no url, don't redirect + if (tab.Url != string.Empty) { bestFriendlyUrl = tab.Url; } else { - //776: no actual Url for the 'perm redirect'. - //this is a mistake on the part of the person who created the perm redirect - //but don't create a redirect or there will be a terminal loop + // 776: no actual Url for the 'perm redirect'. + // this is a mistake on the part of the person who created the perm redirect + // but don't create a redirect or there will be a terminal loop permRedirect = false; } } + return bestFriendlyUrl; } } diff --git a/DNN Platform/Library/Entities/Urls/RedirectReason.cs b/DNN Platform/Library/Entities/Urls/RedirectReason.cs index 2f1f5757ac7..48900af2f05 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectReason.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectReason.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum RedirectReason @@ -42,6 +42,6 @@ public enum RedirectReason Diacritic_Characters, Module_Provider_Rewrite_Redirect, Module_Provider_Redirect, - Requested_SplashPage + Requested_SplashPage, } } diff --git a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs index 31ed68b3982..7927efcf1ba 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs @@ -1,149 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Text.RegularExpressions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Text.RegularExpressions; + /// /// This class contains helpers which set the redirect action and reason tokens. These are fake additions to the rewritten query string - /// which are used as a type of property to store intent of a particular url in the page index. This is done to keep the base type + /// which are used as a type of property to store intent of a particular url in the page index. This is done to keep the base type /// stored in the page index dictionary as a value type (string) rather than a object type with properties. So the two 'properties' - /// of a Url are the action (ie 301 redirect, 302 redirect, 404, etc) and the reason (home page redirect, etc) are stored as + /// of a Url are the action (ie 301 redirect, 302 redirect, 404, etc) and the reason (home page redirect, etc) are stored as /// part of the rewritten querystring in the index. These then have to be removed and translated back to 'action' parameters /// when the rewriting actually happens. So all methods in this class are to do with either storing or retrieving these tokens. /// internal static class RedirectTokens { - private static readonly Regex RewritePathRx = new Regex(@"&rr=(?[^&].)", - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - - private static readonly Regex RedirectTokensRx = new Regex(@"(?<=(?

    &|\?))(?do301|do302|do404)=(?[^&]+)", + private static readonly Regex RewritePathRx = new Regex( + @"&rr=(?[^&].)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - #region Private Methods - - ///

    - /// Returns the list of tokens found in a rewrite path as a key/value dictionary - /// - /// - /// Rewritten Url path - /// - /// - /// - /// Returns a list of the redirect tokens found in the querystring - /// - /// - private static List GetRedirectReasonTokensFromRewritePath(string rewritePath) - { - var reasons = new List(); - MatchCollection matches = RewritePathRx.Matches(rewritePath); - foreach (Match match in matches) - { - if (match.Success) - { - Group rrG = match.Groups["rr"]; - if (rrG.Success) - { - string rr = match.Groups["rr"].Value; - reasons.Add(rr); - } - } - } - return reasons; - } - - private static void GetRedirectActionTokenAndValue(ActionType action, out string token, out string value) - { - switch (action) - { - case ActionType.CheckFor301: - token = "do301"; - value = "check"; - break; - case ActionType.Redirect301: - token = "do301"; - value = "true"; - break; - case ActionType.Output404: - token = "do404"; - value = "true"; - break; - case ActionType.Redirect302: - token = "do302"; - value = "true"; - break; - default: - token = ""; - value = ""; - break; - } - } - - private static string GetRedirectReasonRewriteToken(RedirectReason reason) - { - string result = ""; - switch (reason) - { - case RedirectReason.Deleted_Page: - result = "&rr=dl"; - break; - case RedirectReason.Disabled_Page: - //838 : handle disabled page separately - result = "&rr=db"; - break; - case RedirectReason.Tab_Permanent_Redirect: - result = "&rr=pr"; - break; - case RedirectReason.Spaces_Replaced: - result = "&rr=sr"; - break; - case RedirectReason.Site_Root_Home: - result = "&rr=hp"; - break; - case RedirectReason.Diacritic_Characters: - result = "&rr=dc"; - break; - case RedirectReason.User_Profile_Url: - result = "&rr=up"; - break; - case RedirectReason.Custom_Redirect: - result = "&rr=cr"; - break; - } - return result; - } - - private static Dictionary GetRedirectTokensAndValuesFromRewritePath(string rewritePath, out bool hasDupes) - { - hasDupes = false; - var results = new Dictionary(); - MatchCollection matches = RedirectTokensRx.Matches(rewritePath); - foreach (Match tokenMatch in matches) - { - string tk = tokenMatch.Groups["tk"].Value; - string val = tokenMatch.Groups["val"].Value; - if (results.ContainsKey(tk)) - { - hasDupes = true; - } - else - { - results.Add(tk, val); - } - } - return results; - } - - #endregion - - #region Internal Methods - + private static readonly Regex RedirectTokensRx = new Regex( + @"(?<=(?

    &|\?))(?do301|do302|do404)=(?[^&]+)", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + ///

    - /// Adds on a redirect reason to the rewrite path + /// Adds on a redirect reason to the rewrite path. /// /// /// @@ -156,14 +40,17 @@ internal static string AddRedirectReasonToRewritePath(string existingRewritePath GetRedirectActionTokenAndValue(action, out token, out value); string tokenAndValue = token + "=" + value; bool addToken = true; - //look for existing action + + // look for existing action bool hasDupes; - Dictionary tokensAndValues = GetRedirectTokensAndValuesFromRewritePath(existingRewritePath, - out hasDupes); - //can't overwrite existing tokens in certain cases + Dictionary tokensAndValues = GetRedirectTokensAndValuesFromRewritePath( + existingRewritePath, + out hasDupes); + + // can't overwrite existing tokens in certain cases if (tokensAndValues.Count > 0) { - //only case we allow is an ovewrite of a do301=check by a do301=true or do302=true + // only case we allow is an ovewrite of a do301=check by a do301=true or do302=true if (token == "do301" || token == "do302") { if (tokensAndValues.ContainsKey("do301") && tokensAndValues["do301"] == "check") @@ -171,8 +58,10 @@ internal static string AddRedirectReasonToRewritePath(string existingRewritePath result = existingRewritePath.Replace("do301=check", tokenAndValue); } } - addToken = false; //already done + + addToken = false; // already done } + if (addToken) { if (result.Contains(tokenAndValue) == false) @@ -186,75 +75,78 @@ internal static string AddRedirectReasonToRewritePath(string existingRewritePath result += "?" + tokenAndValue; } - //the reasonToken helps the rewrite process determine why a redirect is required - //after the token is stored in the page dictionary + // the reasonToken helps the rewrite process determine why a redirect is required + // after the token is stored in the page dictionary string reasonToken = GetRedirectReasonRewriteToken(reason); - if (reasonToken != "") + if (reasonToken != string.Empty) { result += reasonToken; } } else { - //special case : add the number of times a 301 has been requested + // special case : add the number of times a 301 has been requested if (tokenAndValue == "do301=true" && reason == RedirectReason.User_Profile_Url) { result += "&num301=2"; } } } + return result; } /// - /// DetermineRedirectReasonAndAction extracts the redirect value from the rewrite url and - /// returns the new rewritten url, and the reason for the redirection, and an action value for the type of redirect + /// DetermineRedirectReasonAndAction extracts the redirect value from the rewrite url and + /// returns the new rewritten url, and the reason for the redirection, and an action value for the type of redirect. /// - /// Rewritten url as found in page dictionary + /// Rewritten url as found in page dictionary. /// The current rewrite result. - /// true if there are parameters in the path, false if not - /// current FriendlyUrlSettings object - /// New action value for UrlAction object - /// New redirect reason value for UrlAction object - /// Url to used for rewrite process - /// the new Url, with any replacements done. Replacements occur when a reason token - /// was stored in the tab dictionary entry just to indicate a redirect reason. - internal static void DetermineRedirectReasonAndAction(string rewrittenUrl, - UrlAction result, - bool wasParms, - FriendlyUrlSettings settings, - out string newUrl, - out RedirectReason reason, - out ActionType action) + /// true if there are parameters in the path, false if not. + /// current FriendlyUrlSettings object. + /// New action value for UrlAction object. + /// New redirect reason value for UrlAction object. + /// Url to used for rewrite process. + internal static void DetermineRedirectReasonAndAction( + string rewrittenUrl, + UrlAction result, + bool wasParms, + FriendlyUrlSettings settings, + out string newUrl, + out RedirectReason reason, + out ActionType action) { - //init parms + // init parms newUrl = rewrittenUrl; action = result.Action; reason = result.Reason; - //get the action type from the rewrite path + // get the action type from the rewrite path ActionType foundAction; bool actionInPath = GetActionFromRewritePath(rewrittenUrl, out foundAction); - //only overrwrite action if it was found in the rewrite path + + // only overrwrite action if it was found in the rewrite path if (actionInPath) { action = foundAction; } - //get the list of redirect reason tokens from the url + + // get the list of redirect reason tokens from the url List redirectReasons = GetRedirectReasonTokensFromRewritePath(rewrittenUrl); - //when redirect action in path, and redirect reasons are empty, add custom redirect + // when redirect action in path, and redirect reasons are empty, add custom redirect if (redirectReasons.Count == 0 && action != ActionType.Continue) { redirectReasons.Add("cr"); } + bool clearActionToken = false; foreach (string rrTkn in redirectReasons) { switch (rrTkn) { case "up": - //user profile redirect + // user profile redirect clearActionToken = true; if (wasParms) { @@ -273,9 +165,10 @@ internal static void DetermineRedirectReasonAndAction(string rewrittenUrl, } else { - //if no parms, then we're not doing a userprofileaction redirect + // if no parms, then we're not doing a userprofileaction redirect reason = RedirectReason.Custom_Redirect; - //then check for a 301 redirect + + // then check for a 301 redirect action = ActionType.CheckFor301; } @@ -283,37 +176,38 @@ internal static void DetermineRedirectReasonAndAction(string rewrittenUrl, case "dl": case "db": - //deleted tab dl - //disabled tab db + // deleted tab dl + // disabled tab db clearActionToken = true; - //626 Deleted tab hanlding not working properyly - override + + // 626 Deleted tab hanlding not working properyly - override if (settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error) { - action = ActionType.Output404; //output a 404 as per settings + action = ActionType.Output404; // output a 404 as per settings } - //838 : handle disabled pages separately + // 838 : handle disabled pages separately reason = rrTkn == "dl" ? RedirectReason.Deleted_Page : RedirectReason.Disabled_Page; break; case "pr": - //pr = permanent redirect + // pr = permanent redirect reason = RedirectReason.Tab_Permanent_Redirect; clearActionToken = true; break; case "sr": - //sr = spaces replaced in url + // sr = spaces replaced in url clearActionToken = true; reason = RedirectReason.Spaces_Replaced; break; case "hp": - //hp = home page redirect + // hp = home page redirect if (wasParms) { - //cancel the home page replaced if there were parameters added and page extensions - //are in use - otherwise a 404 will occur for the relative path + // cancel the home page replaced if there were parameters added and page extensions + // are in use - otherwise a 404 will occur for the relative path reason = RedirectReason.Not_Redirected; action = ActionType.Continue; clearActionToken = true; @@ -323,33 +217,150 @@ internal static void DetermineRedirectReasonAndAction(string rewrittenUrl, reason = RedirectReason.Site_Root_Home; clearActionToken = true; } + break; - - + default: - //any other redirect with no reason is a custom redirect + // any other redirect with no reason is a custom redirect if (reason == RedirectReason.Not_Redirected) { reason = RedirectReason.Custom_Redirect; } + clearActionToken = true; break; } } + if (clearActionToken) { - //clear both action and reason + // clear both action and reason newUrl = RemoveAnyRedirectTokensAndReasons(newUrl); } else { - //clear just reason + // clear just reason newUrl = RemoveAnyRedirectReasons(newUrl); } } + + /// + /// Returns the list of tokens found in a rewrite path as a key/value dictionary. + /// + /// + /// Rewritten Url path. + /// + /// + /// + /// Returns a list of the redirect tokens found in the querystring. + /// + /// + private static List GetRedirectReasonTokensFromRewritePath(string rewritePath) + { + var reasons = new List(); + MatchCollection matches = RewritePathRx.Matches(rewritePath); + foreach (Match match in matches) + { + if (match.Success) + { + Group rrG = match.Groups["rr"]; + if (rrG.Success) + { + string rr = match.Groups["rr"].Value; + reasons.Add(rr); + } + } + } + + return reasons; + } + + private static void GetRedirectActionTokenAndValue(ActionType action, out string token, out string value) + { + switch (action) + { + case ActionType.CheckFor301: + token = "do301"; + value = "check"; + break; + case ActionType.Redirect301: + token = "do301"; + value = "true"; + break; + case ActionType.Output404: + token = "do404"; + value = "true"; + break; + case ActionType.Redirect302: + token = "do302"; + value = "true"; + break; + default: + token = string.Empty; + value = string.Empty; + break; + } + } + + private static string GetRedirectReasonRewriteToken(RedirectReason reason) + { + string result = string.Empty; + switch (reason) + { + case RedirectReason.Deleted_Page: + result = "&rr=dl"; + break; + case RedirectReason.Disabled_Page: + // 838 : handle disabled page separately + result = "&rr=db"; + break; + case RedirectReason.Tab_Permanent_Redirect: + result = "&rr=pr"; + break; + case RedirectReason.Spaces_Replaced: + result = "&rr=sr"; + break; + case RedirectReason.Site_Root_Home: + result = "&rr=hp"; + break; + case RedirectReason.Diacritic_Characters: + result = "&rr=dc"; + break; + case RedirectReason.User_Profile_Url: + result = "&rr=up"; + break; + case RedirectReason.Custom_Redirect: + result = "&rr=cr"; + break; + } + + return result; + } + + private static Dictionary GetRedirectTokensAndValuesFromRewritePath(string rewritePath, out bool hasDupes) + { + hasDupes = false; + var results = new Dictionary(); + MatchCollection matches = RedirectTokensRx.Matches(rewritePath); + foreach (Match tokenMatch in matches) + { + string tk = tokenMatch.Groups["tk"].Value; + string val = tokenMatch.Groups["val"].Value; + if (results.ContainsKey(tk)) + { + hasDupes = true; + } + else + { + results.Add(tk, val); + } + } + + return results; + } /// - /// Return the action type from a rewritten Url + /// Return the action type from a rewritten Url. /// /// /// @@ -357,7 +368,7 @@ internal static void DetermineRedirectReasonAndAction(string rewrittenUrl, internal static bool GetActionFromRewritePath(string rewrittenUrl, out ActionType action) { bool found = false; - action = ActionType.Continue; //default + action = ActionType.Continue; // default MatchCollection actionMatches = RedirectTokensRx.Matches(rewrittenUrl); foreach (Match actionMatch in actionMatches) { @@ -380,50 +391,55 @@ internal static bool GetActionFromRewritePath(string rewrittenUrl, out ActionTyp action = ActionType.CheckFor301; } } + break; case "do404": if (val == "true") { action = ActionType.Output404; } + break; case "do302": if (val == "true") { action = ActionType.Redirect302; } + break; } - //if there is more than one match, if we have a solid action, then break + + // if there is more than one match, if we have a solid action, then break if (action != ActionType.Continue) { - break; //this should, by rights, not happen in normal operation + break; // this should, by rights, not happen in normal operation } } } + return found; } /// - /// Removes any reason tokens from the querystring + /// Removes any reason tokens from the querystring. /// /// /// internal static string RemoveAnyRedirectReasons(string rewritePath) { - return RewritePathRx.Replace(rewritePath, ""); + return RewritePathRx.Replace(rewritePath, string.Empty); } /// - /// Removes any redirect tokens from the rewrite path + /// Removes any redirect tokens from the rewrite path. /// /// /// /// internal static string RemoveAnyRedirectTokens(string path, NameValueCollection queryStringCol) { - //don't really care what the value is, but need it for replacing - //the do301 is an internal value, used to control redirects from the page index + // don't really care what the value is, but need it for replacing + // the do301 is an internal value, used to control redirects from the page index if (string.IsNullOrEmpty(path) == false) { string val = null; @@ -431,49 +447,56 @@ internal static string RemoveAnyRedirectTokens(string path, NameValueCollection { val = queryStringCol["do301"]; } + if (string.IsNullOrEmpty(val)) { val = "true"; } - //nix the 301 redirect query string value or terminal loops-a-plenty - path = path.Replace("&do301=" + val, ""); - path = path.Replace("?do301=" + val, ""); + + // nix the 301 redirect query string value or terminal loops-a-plenty + path = path.Replace("&do301=" + val, string.Empty); + path = path.Replace("?do301=" + val, string.Empty); - //911 : object not set error + // 911 : object not set error if (queryStringCol != null) { val = queryStringCol["do302"]; } + if (string.IsNullOrEmpty(val)) { val = "true"; } - //nix the 302 redirect query string value or terminal loops-a-plenty - path = path.Replace("&do302=" + val, ""); - path = path.Replace("?do302=" + val, ""); + + // nix the 302 redirect query string value or terminal loops-a-plenty + path = path.Replace("&do302=" + val, string.Empty); + path = path.Replace("?do302=" + val, string.Empty); } + return path; } /// - /// Removes and redirect tokens and redirect reasons from the rewritePath + /// Removes and redirect tokens and redirect reasons from the rewritePath. /// /// /// internal static string RemoveAnyRedirectTokensAndReasons(string rewritePath) { string result = RemoveAnyRedirectReasons(rewritePath); - //regex expression matches a token and removes it + + // regex expression matches a token and removes it Match tokenMatch = RedirectTokensRx.Match(result); if (tokenMatch.Success) { - //tokenAndValue is the do301=true + // tokenAndValue is the do301=true string tokenAndValue = tokenMatch.Value; - //p is either a ? or a & + + // p is either a ? or a & string p = tokenMatch.Groups["p"].Value; if (p == "?") { - result = result.Replace(tokenAndValue, ""); + result = result.Replace(tokenAndValue, string.Empty); if (result.Contains("?&")) { result = result.Replace("?&", "?"); @@ -482,15 +505,15 @@ internal static string RemoveAnyRedirectTokensAndReasons(string rewritePath) { if (result.EndsWith("?") || result.EndsWith("&")) { - //trim end + // trim end result = result.Substring(0, result.Length - 1); } } } else { - //p == "&" - result = result.Replace("&" + tokenAndValue, ""); + // p == "&" + result = result.Replace("&" + tokenAndValue, string.Empty); } } @@ -498,7 +521,7 @@ internal static string RemoveAnyRedirectTokensAndReasons(string rewritePath) } /// - /// Sets the Action and Reason values in the UrlAction parameter + /// Sets the Action and Reason values in the UrlAction parameter. /// /// /// @@ -512,8 +535,6 @@ internal static void SetRedirectReasonAndAction(ref UrlAction result, FriendlyUr result.Action = action; result.Reason = reason; result.RewritePath = newUrl; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Urls/RewriteController.cs b/DNN Platform/Library/Entities/Urls/RewriteController.cs index 295c284959b..e338bec765f 100644 --- a/DNN Platform/Library/Entities/Urls/RewriteController.cs +++ b/DNN Platform/Library/Entities/Urls/RewriteController.cs @@ -1,78 +1,190 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Caching; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls.Config; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.IO; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls.Config; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + public class RewriteController { internal const int SiteRootRewrite = -3; internal const int AllTabsRewrite = -1; - private static readonly Regex TabIdRegex = new Regex(@"(?:\?|\&)tabid\=(?[\d]+)", + private static readonly Regex TabIdRegex = new Regex( + @"(?:\?|\&)tabid\=(?[\d]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex UrlParamsRegex = new Regex(@"&[^=]+(?:&|$)", RegexOptions.Compiled); - private static readonly Regex CultureMatchRegex = new Regex("([A-Za-z]{2})-([A-Za-z]{2})", + private static readonly Regex CultureMatchRegex = new Regex( + "([A-Za-z]{2})-([A-Za-z]{2})", RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex LangMatchRegex = new Regex("/language/(?.[^/]+)(?:/|$)", + private static readonly Regex LangMatchRegex = new Regex( + "/language/(?.[^/]+)(?:/|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex RewriteParamsRegex = new Regex(@"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex RewriteParamsRegex = new Regex( + @"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))", + RegexOptions.IgnoreCase | RegexOptions.Compiled); - #region Private Methods + internal static string CheckLanguageMatch(ref string url, UrlAction result) + { + // ok now scan for the language modifier + Match langMatch = LangMatchRegex.Match(url); + + // searches for a string like language/en-US/ in the url + string langParms = string.Empty; + if (langMatch.Success) + { + // OK there is a language modifier in the path + // we want to shift this so it is back on the end where it belongs + langParms = langMatch.Value.TrimEnd('/'); // in the format of /language/en-US only + + // it doesn't matter if you get /home.aspx/language/en-US in the url field because the .aspx gets + // removed when matching with the tab dictionary + url = url.Replace(langParms, string.Empty) + langParms; + result.CultureCode = langMatch.Groups["code"].Value; // get the culture code in the requested url + + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (primaryAliases.Count > 0) + { + string aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); + if (aliasCulture != null) + { + // want to do a 301 check because this potentially has a duplicate of portal alias and culture code in the url, which + // is not the best combination + if (result.Action == ActionType.Continue) + { + result.Action = ActionType.CheckFor301; + } + } + } + } + + return langParms; + } + + /// + /// appends a language/culture code value if it is not already present in the rewrite path. + /// + /// + /// + /// + internal static bool AddLanguageCodeToRewritePath(ref string rewritePath, string cultureCode) + { + bool changed = false; + + // 758 : check for any language identifier in the Url before adding a new one, not just the same one + if (!string.IsNullOrEmpty(cultureCode) && !rewritePath.ToLowerInvariant().Contains("language=")) + { + changed = true; + if (rewritePath.Contains("?")) + { + rewritePath += "&language=" + cultureCode; + } + else + { + rewritePath += "?language=" + cultureCode; + } + } + + return changed; + } + /// + /// appends a skin value to the rewrite path, as long as there is no existing skin in the path. + /// + /// + /// The current rewrite path. + /// The selected skin. + /// + /// + /// 852 : Add skin src to rewrite path for specific aliases. + /// + internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string rewritePath, string skin, out string message) + { + bool changed = false; + message = null; + TabInfo tab = null; + if (tabId > 0 && portalId > -1) + { + tab = TabController.Instance.GetTab(tabId, portalId, false); + } + + // don't overwrite specific skin at tab level for rewritten Urls + if (tab == null || string.IsNullOrEmpty(tab.SkinSrc)) + { + if (!string.IsNullOrEmpty(skin) && skin != "default" && !rewritePath.ToLowerInvariant().Contains("skinsrc=")) + { + message = "Added SkinSrc : " + skin; + changed = true; + rewritePath += rewritePath.Contains("?") ? "&SkinSrc=" + skin.Replace(".ascx", string.Empty) : "?SkinSrc=" + skin.Replace(".ascx", string.Empty); + } + } + else + { + if (!string.IsNullOrEmpty(tab.SkinSrc)) + { + message = "Tab " + tab.TabID.ToString() + " has skin specified : " + tab.SkinSrc; + if (skin != tab.SkinSrc) + { + message += " - " + skin + " not applied due to tab specific skin"; + } + } + } + + return changed; + } + private static string AddQueryStringToRewritePath(string rewritePath, string queryString) { - //now add back querystring if they existed - if (queryString != "") + // now add back querystring if they existed + if (queryString != string.Empty) { bool rewritePathHasQuery = rewritePath.IndexOf("?", StringComparison.Ordinal) != -1; if (queryString.StartsWith("?")) { queryString = queryString.Substring(1); } + string[] parms = queryString.Split('&'); + // iterate through the array of parameters for (int i = 0; i < parms.Length; i++) { bool hasValue = false; + // get parameter name string parmName = parms[i]; - //check if parm name contains a value as well + + // check if parm name contains a value as well if (parmName.IndexOf("=", StringComparison.Ordinal) != -1) { - //snip off the =value part of the parm + // snip off the =value part of the parm parmName = parmName.Substring(0, parmName.IndexOf("=", StringComparison.Ordinal)); hasValue = true; } - //597 : do a compare with the '=' on the end to only - //compare the entire parmname, not just the start + + // 597 : do a compare with the '=' on the end to only + // compare the entire parmname, not just the start string comparePath1 = "?" + parmName.ToLowerInvariant(); string comparePath2 = "&" + parmName.ToLowerInvariant(); if (hasValue) @@ -80,18 +192,20 @@ private static string AddQueryStringToRewritePath(string rewritePath, string que comparePath1 += "="; comparePath2 += "="; } + // check if parameter already exists in the rewrite path - // we only want to add the querystring back on if the + // we only want to add the querystring back on if the // query string keys were not already shown in the friendly // url path if (!rewritePath.ToLowerInvariant().Contains(comparePath1) && !rewritePath.ToLowerInvariant().Contains(comparePath2)) { - //622 : remove encoding from querystring paths - //699 : reverses 622 because works from Request.QUeryString instead of Request.Url.Query - //string queryStringPiece = System.Web.HttpUtility.UrlDecode(parms[i]); + // 622 : remove encoding from querystring paths + // 699 : reverses 622 because works from Request.QUeryString instead of Request.Url.Query + // string queryStringPiece = System.Web.HttpUtility.UrlDecode(parms[i]); string queryStringPiece = parms[i]; - //no decoding - querystring passes through rewriting process untouched + + // no decoding - querystring passes through rewriting process untouched // add parameter to SendTo value if (rewritePathHasQuery) { @@ -105,6 +219,7 @@ private static string AddQueryStringToRewritePath(string rewritePath, string que } } } + return rewritePath; } @@ -114,18 +229,19 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst bool reWritten = false; string defaultPage = Globals.glbDefaultPage.ToLowerInvariant(); - string portalAliasUrl = url.ToLowerInvariant().Replace("/" + defaultPage, ""); - //if there is a straight match on a portal alias, it's the home page for that portal requested + string portalAliasUrl = url.ToLowerInvariant().Replace("/" + defaultPage, string.Empty); + + // if there is a straight match on a portal alias, it's the home page for that portal requested var portalAlias = PortalAliasController.Instance.GetPortalAlias(portalAliasUrl); if (portalAlias != null) { - //special case : sometimes, some servers issue root/default.aspx when root/ was requested, sometimes not. It depends - //on other server software installed (apparently) - //so check the raw Url and the url, and see if they are the same except for the /default.aspx + // special case : sometimes, some servers issue root/default.aspx when root/ was requested, sometimes not. It depends + // on other server software installed (apparently) + // so check the raw Url and the url, and see if they are the same except for the /default.aspx string rawUrl = result.RawUrl; if (url.ToLowerInvariant().EndsWith(rawUrl + defaultPage.ToLowerInvariant())) { - //special case - change the url to be equal to the raw Url + // special case - change the url to be equal to the raw Url url = url.Substring(0, url.Length - defaultPage.Length); } @@ -139,8 +255,8 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst } else { - //special case -> look in the tabdict for a blank intercept - //735 : switch to custom method for getting portal + // special case -> look in the tabdict for a blank intercept + // 735 : switch to custom method for getting portal PortalInfo portal = CacheController.GetPortal(portalAlias.PortalID, true); if (portal.HomeTabId == -1) { @@ -149,6 +265,7 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst { tabKey = tabKey.TrimEnd('/'); } + tabKey += "::"; using (tabDict.GetReadLock()) { @@ -158,54 +275,59 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst reWritten = true; } } - //if no home tab, but matched a portal alias, and no trailing /default.aspx - //and no 'newUrl' value because not rewritten, then append the /default.aspx - //and ask for a rewrite on that one. - //DNNDEV-27291 + + // if no home tab, but matched a portal alias, and no trailing /default.aspx + // and no 'newUrl' value because not rewritten, then append the /default.aspx + // and ask for a rewrite on that one. + // DNNDEV-27291 if (reWritten == false) { - //Need to determine if this is a child alias + // Need to determine if this is a child alias newUrl = "/" + Globals.glbDefaultPage; reWritten = true; } } else { - //set rewrite to home page of site - //760: check for portal alias specific culture before choosing home tabid + // set rewrite to home page of site + // 760: check for portal alias specific culture before choosing home tabid bool checkForCustomAlias = false; bool customTabAlias = false; - //check for culture-specific aliases + + // check for culture-specific aliases string culture = null; var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); - //if there are chosen portal aliases, check to see if the found alias is one of them - //if not, then will check for a custom alias per tab + // if there are chosen portal aliases, check to see if the found alias is one of them + // if not, then will check for a custom alias per tab if (!portalAliases.ContainsAlias(portal.PortalID, portalAlias.HTTPAlias)) { checkForCustomAlias = true; } else { - //check for a specific culture for the alias + // check for a specific culture for the alias culture = portalAliases.GetCultureByPortalIdAndAlias(portal.PortalID, portalAlias.HTTPAlias); } + if (checkForCustomAlias) { - //ok, this isnt' a chosen portal alias, check the list of custom aliases + // ok, this isnt' a chosen portal alias, check the list of custom aliases List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); if (customAliasesForTabs != null && customAliasesForTabs.Contains(portalAlias.HTTPAlias.ToLowerInvariant())) { - //ok, the alias is used as a custom tab, so now look in the dictionary to see if it's used a 'root' context + // ok, the alias is used as a custom tab, so now look in the dictionary to see if it's used a 'root' context string tabKey = url.ToLowerInvariant(); if (tabKey.EndsWith("/")) { tabKey = tabKey.TrimEnd('/'); } + if (tabKey.EndsWith("/default.aspx")) { - tabKey = tabKey.Substring(0, tabKey.Length - 13); //13 = "/default.aspx".length + tabKey = tabKey.Substring(0, tabKey.Length - 13); // 13 = "/default.aspx".length } + tabKey += "::"; using (tabDict.GetReadLock()) { @@ -213,29 +335,30 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst { newUrl = tabDict[tabKey]; reWritten = true; - customTabAlias = true; //this alias is used as the alias for a custom tab + customTabAlias = true; // this alias is used as the alias for a custom tab } } } } + if (customTabAlias == false) { int tabId; - if (!String.IsNullOrEmpty(querystringCol["TabId"])) + if (!string.IsNullOrEmpty(querystringCol["TabId"])) { tabId = Convert.ToInt32(querystringCol["TabId"]); result.Action = ActionType.CheckFor301; } else { - //not a custom alias for a specific tab, so it must be the home page for the portal we identified, - //if its first request and splash page defined, then redirec to splash page. + // not a custom alias for a specific tab, so it must be the home page for the portal we identified, + // if its first request and splash page defined, then redirec to splash page. if (portal.SplashTabId > Null.NullInteger && HttpContext.Current != null && !HttpContext.Current.Request.Cookies.AllKeys.Contains("SplashPageView")) { tabId = portal.SplashTabId; HttpContext.Current.Response.Cookies.Add( - new HttpCookie("SplashPageView", "true") { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }); + new HttpCookie("SplashPageView", "true") { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); result.Action = ActionType.Redirect302; result.Reason = RedirectReason.Requested_SplashPage; } @@ -243,35 +366,40 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst { tabId = portal.HomeTabId; } + if (culture == null) { - culture = portal.DefaultLanguage; //set culture to default if not found specifically + culture = portal.DefaultLanguage; // set culture to default if not found specifically } else { - //if there is a specific culture for this alias, and it's different to the default language, then - //go check for a specific culture home page (5.5 and later) - tabId = TabPathHelper.GetHomePageTabIdForCulture(portal.DefaultLanguage, - portal.PortalID, - culture, - tabId); + // if there is a specific culture for this alias, and it's different to the default language, then + // go check for a specific culture home page (5.5 and later) + tabId = TabPathHelper.GetHomePageTabIdForCulture( + portal.DefaultLanguage, + portal.PortalID, + culture, + tabId); } } - //see if there is a skin for the alias/culture combination - string skin = TabPathHelper.GetTabAliasSkinForTabAndAlias(portalAlias.PortalID, - portalAlias.HTTPAlias, culture); + + // see if there is a skin for the alias/culture combination + string skin = TabPathHelper.GetTabAliasSkinForTabAndAlias( + portalAlias.PortalID, + portalAlias.HTTPAlias, culture); if (string.IsNullOrEmpty(skin) == false) { - newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, "", "skinSrc=" + skin); + newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, string.Empty, "skinSrc=" + skin); } else { - newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, ""); + newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, string.Empty); } - //DNN-3789 always call this method as culture is defined by GetPageLocale + // DNN-3789 always call this method as culture is defined by GetPageLocale AddLanguageCodeToRewritePath(ref newUrl, culture); - //add on language specified by current portal alias + + // add on language specified by current portal alias reWritten = true; } } @@ -279,7 +407,7 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst if (reWritten) { - //check for replaced to site root from /default.aspx + // check for replaced to site root from /default.aspx // 838 set redirect reason and action from result SetRewriteParameters(ref result, newUrl); ActionType action; @@ -291,43 +419,52 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst result.Reason = reason; } } + return newUrl; } private static bool CheckSpecialCase(string tabKeyVal, SharedDictionary tabDict) { bool found = false; - int pathStart = tabKeyVal.LastIndexOf("::", StringComparison.Ordinal); //look for portal alias separator + int pathStart = tabKeyVal.LastIndexOf("::", StringComparison.Ordinal); // look for portal alias separator int lastPath = tabKeyVal.LastIndexOf('/'); - //get any path separator in the tab path portion + + // get any path separator in the tab path portion if (pathStart > lastPath) { lastPath = pathStart; } + if (lastPath >= 0) { int defaultStart = tabKeyVal.IndexOf("default", lastPath, StringComparison.OrdinalIgnoreCase); - //no .aspx on the end anymore + + // no .aspx on the end anymore if (defaultStart > 0 && defaultStart > lastPath) - //there is a default in the path, and it's not the entire path (ie pagnamedefault and not default) + + // there is a default in the path, and it's not the entire path (ie pagnamedefault and not default) { tabKeyVal = tabKeyVal.Substring(0, defaultStart); - //get rid of the default.aspx part + + // get rid of the default.aspx part using (tabDict.GetReadLock()) { found = tabDict.ContainsKey(tabKeyVal); - //lookup the tabpath in the tab dictionary again + + // lookup the tabpath in the tab dictionary again } } } + return found; } private static UserInfo GetUser(int portalId, string vanityUrl) { string cacheKey = string.Format(CacheController.VanityUrlLookupKey, portalId); - var vanityUrlLookupDictionary = CBO.GetCachedObject>(new CacheItemArgs(cacheKey, 20, CacheItemPriority.High, portalId), - c => new Dictionary()); + var vanityUrlLookupDictionary = CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, 20, CacheItemPriority.High, portalId), + c => new Dictionary()); if (!vanityUrlLookupDictionary.ContainsKey(vanityUrl)) { @@ -336,33 +473,32 @@ private static UserInfo GetUser(int portalId, string vanityUrl) return vanityUrlLookupDictionary[vanityUrl]; } - - + private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrlSettings settings, SharedDictionary tabDict, ref string newUrl) { bool found; - string userParam = String.Empty; + string userParam = string.Empty; string tabLookUpKey = tabKeyVal; using (tabDict.GetReadLock()) { - found = tabDict.ContainsKey(tabLookUpKey); //lookup the tabpath in the tab dictionary + found = tabDict.ContainsKey(tabLookUpKey); // lookup the tabpath in the tab dictionary } - //special case, if no extensions and the last part of the tabKeyVal contains default.aspx, then - //split off the default.aspx part and try again - compensating for gemini issue http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=8651&PROJID=39 + // special case, if no extensions and the last part of the tabKeyVal contains default.aspx, then + // split off the default.aspx part and try again - compensating for gemini issue http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=8651&PROJID=39 if (!found && settings.PageExtensionUsageType != PageExtensionUsageType.AlwaysUse) { found = CheckSpecialCase(tabLookUpKey, tabDict); } - //Check for VanityUrl + // Check for VanityUrl var doNotRedirectRegex = RegexUtils.GetCachedRegex(settings.DoNotRedirectRegex); if (!found && !Globals.ServicesFrameworkRegex.IsMatch(result.RawUrl) && !doNotRedirectRegex.IsMatch(result.RawUrl)) { string[] urlParams = tabLookUpKey.Split(new[] { "::" }, StringSplitOptions.None); if (urlParams.Length > 1) { - //Extract the first Url parameter + // Extract the first Url parameter string tabPath = urlParams[1]; var urlSegments = tabPath.Split('/'); @@ -373,25 +509,25 @@ private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrl { string vanityUrl = urlSegments[1]; - //check if its a vanityUrl + // check if its a vanityUrl var user = GetUser(PortalController.GetEffectivePortalId(result.PortalId), vanityUrl); if (user != null) { userParam = "UserId=" + user.UserID.ToString(); - //Get the User profile Tab + // Get the User profile Tab var portal = PortalController.Instance.GetPortal(result.PortalId); var profilePage = TabController.Instance.GetTab(portal.UserTabId, result.PortalId, false); FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); string profilePagePath = TabPathHelper.GetFriendlyUrlTabPath(profilePage, options, Guid.NewGuid()); - //modify lookup key; - tabLookUpKey = tabLookUpKey.Replace("::" + String.Format("{0}/{1}", settings.VanityUrlPrefix, vanityUrl), "::" + profilePagePath.TrimStart('/').ToLowerInvariant()); + // modify lookup key; + tabLookUpKey = tabLookUpKey.Replace("::" + string.Format("{0}/{1}", settings.VanityUrlPrefix, vanityUrl), "::" + profilePagePath.TrimStart('/').ToLowerInvariant()); using (tabDict.GetReadLock()) { - found = tabDict.ContainsKey(tabLookUpKey); //lookup the tabpath in the tab dictionary + found = tabDict.ContainsKey(tabLookUpKey); // lookup the tabpath in the tab dictionary } } } @@ -402,90 +538,58 @@ private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrl { using (tabDict.GetReadLock()) { - //determine what the rewritten URl will be + // determine what the rewritten URl will be newUrl = tabDict[tabLookUpKey]; } - //DNN-6747: if found match doesn't match current culture, then try to find correct match. - if (result.PortalId != Null.NullInteger && newUrl.Contains("language=")) - { - var currentLocale = result.CultureCode; - if (string.IsNullOrEmpty(currentLocale)) - { - currentLocale = Localization.GetPageLocale(new PortalSettings(result.PortalId)).Name; - } - - if (!newUrl.Contains(currentLocale)) - { - var tabPath = tabLookUpKey.Split(new[] {"::"}, StringSplitOptions.None)[1]; - using (tabDict.GetReadLock()) - { - foreach (var key in tabDict.Keys.Where(k => k.EndsWith("::" + tabPath))) - { - if (tabDict[key].Contains("language=" + currentLocale)) - { - newUrl = tabDict[key]; - tabKeyVal = key; - break; - } - } - } - } - } - - if (!String.IsNullOrEmpty(userParam)) + // DNN-6747: if found match doesn't match current culture, then try to find correct match. + if (result.PortalId != Null.NullInteger && newUrl.Contains("language=")) { - newUrl = newUrl + "&" + userParam; - } - //if this is a match on the trigger dictionary rebuild, - //then temporarily store this value in case it's a page name change - //677 : only match if is on actual tabKeyVal match, to prevent site root redirects - //statements were moved into this 'if' statement - result.dictVal = newUrl; - result.dictKey = tabKeyVal; - } - return found; - } - - internal static string CheckLanguageMatch(ref string url, UrlAction result) - { - //ok now scan for the language modifier - Match langMatch = LangMatchRegex.Match(url); - - //searches for a string like language/en-US/ in the url - string langParms = ""; - if (langMatch.Success) - { - //OK there is a language modifier in the path - //we want to shift this so it is back on the end where it belongs - langParms = langMatch.Value.TrimEnd('/'); //in the format of /language/en-US only - //it doesn't matter if you get /home.aspx/language/en-US in the url field because the .aspx gets - //removed when matching with the tab dictionary - url = url.Replace(langParms, "") + langParms; - result.CultureCode = langMatch.Groups["code"].Value; //get the culture code in the requested url + var currentLocale = result.CultureCode; + if (string.IsNullOrEmpty(currentLocale)) + { + currentLocale = Localization.GetPageLocale(new PortalSettings(result.PortalId)).Name; + } - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (primaryAliases.Count > 0) - { - string aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); - if (aliasCulture != null) + if (!newUrl.Contains(currentLocale)) { - //want to do a 301 check because this potentially has a duplicate of portal alias and culture code in the url, which - //is not the best combination - if (result.Action == ActionType.Continue) + var tabPath = tabLookUpKey.Split(new[] { "::" }, StringSplitOptions.None)[1]; + using (tabDict.GetReadLock()) { - result.Action = ActionType.CheckFor301; + foreach (var key in tabDict.Keys.Where(k => k.EndsWith("::" + tabPath))) + { + if (tabDict[key].Contains("language=" + currentLocale)) + { + newUrl = tabDict[key]; + tabKeyVal = key; + break; + } + } } } } + + if (!string.IsNullOrEmpty(userParam)) + { + newUrl = newUrl + "&" + userParam; + } + + // if this is a match on the trigger dictionary rebuild, + // then temporarily store this value in case it's a page name change + // 677 : only match if is on actual tabKeyVal match, to prevent site root redirects + // statements were moved into this 'if' statement + result.dictVal = newUrl; + result.dictKey = tabKeyVal; } - return langParms; + + return found; } private static string ReplaceDefaultPage(string newUrl, string requestUrl, IEnumerable list) { - string url = newUrl; //fall back case: we don't change anything - //iterate the list and replace in the url is a match is found + string url = newUrl; // fall back case: we don't change anything + + // iterate the list and replace in the url is a match is found foreach (string requestPage in list) { if (requestUrl.ToLowerInvariant().Contains(requestPage)) @@ -494,41 +598,45 @@ private static string ReplaceDefaultPage(string newUrl, string requestUrl, IEnum break; } } + return url; } - private static string RewriteParametersFromModuleProvider(string newUrl, - string tabKeyVal, - string[] urlParms, - bool isSiteRootMatch, - UrlAction result, - FriendlyUrlSettings settings, - out bool rewriteParms, - out bool newAction, - ref List messages, - Guid parentTraceId) + private static string RewriteParametersFromModuleProvider( + string newUrl, + string tabKeyVal, + string[] urlParms, + bool isSiteRootMatch, + UrlAction result, + FriendlyUrlSettings settings, + out bool rewriteParms, + out bool newAction, + ref List messages, + Guid parentTraceId) { string rewrittenUrl; - rewriteParms = ExtensionUrlProviderController.TransformFriendlyUrlPath(newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - ref result, - settings, - out rewrittenUrl, - out newAction, - ref messages, - parentTraceId); + rewriteParms = ExtensionUrlProviderController.TransformFriendlyUrlPath( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + ref result, + settings, + out rewrittenUrl, + out newAction, + ref messages, + parentTraceId); if (rewriteParms) { result.CustomParmRewrite = true; } + return rewrittenUrl; } private static void SetRewriteParameters(ref UrlAction result, string rewritePath) { - //split out found replaced and store tabid, rulePortalId and do301 if found + // split out found replaced and store tabid, rulePortalId and do301 if found result.RewritePath = rewritePath; MatchCollection qsItems = RewriteParamsRegex.Matches(rewritePath); foreach (Match itemMatch in qsItems) @@ -539,104 +647,36 @@ private static void SetRewriteParameters(ref UrlAction result, string rewritePat { case "tabid": int tabidtemp; - if (Int32.TryParse(val, out tabidtemp)) + if (int.TryParse(val, out tabidtemp)) { result.TabId = tabidtemp; } + break; case "portalid": int pid; - if (Int32.TryParse(val, out pid)) + if (int.TryParse(val, out pid)) { result.PortalId = pid; } + break; case "language": result.CultureCode = val; break; case "ctl": - //786: force redirect for ctl/terms or ctl/privacy + // 786: force redirect for ctl/terms or ctl/privacy RequestRedirectOnBuiltInUrl(val, rewritePath, result); break; } } - //remove the application path - result.RewritePath = result.RewritePath.Replace(result.ApplicationPath + "/", ""); - } - - #endregion - - #region Internal Methods - - /// - /// appends a language/culture code value if it is not already present in the rewrite path - /// - /// - /// - /// - internal static bool AddLanguageCodeToRewritePath(ref string rewritePath, string cultureCode) - { - bool changed = false; - //758 : check for any language identifier in the Url before adding a new one, not just the same one - if (!string.IsNullOrEmpty(cultureCode) && !rewritePath.ToLowerInvariant().Contains("language=")) - { - changed = true; - if (rewritePath.Contains("?")) - { - rewritePath += "&language=" + cultureCode; - } - else - { - rewritePath += "?language=" + cultureCode; - } - } - return changed; - } - - /// - /// appends a skin value to the rewrite path, as long as there is no existing skin in the path - /// - /// - /// The current rewrite path - /// The selected skin - /// - /// - /// 852 : Add skin src to rewrite path for specific aliases - internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string rewritePath, string skin, out string message) - { - bool changed = false; - message = null; - TabInfo tab = null; - if (tabId > 0 && portalId > -1) - { - tab = TabController.Instance.GetTab(tabId, portalId, false); - } - //don't overwrite specific skin at tab level for rewritten Urls - if (tab == null || string.IsNullOrEmpty(tab.SkinSrc)) - { - if (!string.IsNullOrEmpty(skin) && skin != "default" && !rewritePath.ToLowerInvariant().Contains("skinsrc=")) - { - message = "Added SkinSrc : " + skin; - changed = true; - rewritePath += rewritePath.Contains("?") ? "&SkinSrc=" + skin.Replace(".ascx", "") : "?SkinSrc=" + skin.Replace(".ascx", ""); - } - } - else - { - if (!string.IsNullOrEmpty(tab.SkinSrc)) - { - message = "Tab " + tab.TabID.ToString() + " has skin specified : " + tab.SkinSrc; - if (skin != tab.SkinSrc) - { - message += " - " + skin + " not applied due to tab specific skin"; - } - } - } - return changed; - } + + // remove the application path + result.RewritePath = result.RewritePath.Replace(result.ApplicationPath + "/", string.Empty); + } /// - /// Checks for exclusions on Rewriting the path, based on a regex pattern + /// Checks for exclusions on Rewriting the path, based on a regex pattern. /// /// /// @@ -646,43 +686,45 @@ internal static bool CanRewriteRequest(UrlAction result, string requestedPath, F { bool retVal; try - { - //var uri = new Uri(requestedPath); - //if (uri.PathAndQuery.ToLowerInvariant().StartsWith("/default.aspx")) - //{ - // retVal = false; - // result.CanRewrite = StateBoolean.True; - // result.RewritePath = uri.PathAndQuery.Substring(1); - //} - //else - //{ - if (String.IsNullOrEmpty(settings.DoNotRewriteRegex) || - (!Regex.IsMatch(requestedPath, settings.DoNotRewriteRegex, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))) - { - retVal = true; - result.CanRewrite = StateBoolean.True; - } - else - { - retVal = false; - result.CanRewrite = StateBoolean.False; - } - //} + { + // var uri = new Uri(requestedPath); + // if (uri.PathAndQuery.ToLowerInvariant().StartsWith("/default.aspx")) + // { + // retVal = false; + // result.CanRewrite = StateBoolean.True; + // result.RewritePath = uri.PathAndQuery.Substring(1); + // } + // else + // { + if (string.IsNullOrEmpty(settings.DoNotRewriteRegex) || + (!Regex.IsMatch(requestedPath, settings.DoNotRewriteRegex, + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))) + { + retVal = true; + result.CanRewrite = StateBoolean.True; + } + else + { + retVal = false; + result.CanRewrite = StateBoolean.False; + } + + // } } catch (Exception ex) { - retVal = true; //always rewrite if an error in the regex + retVal = true; // always rewrite if an error in the regex UrlRewriterUtils.LogExceptionInRequest(ex, "NotSet", result); result.Ex = ex; } + return retVal; } internal static string CleanExtension(string value, string extension, out bool replaced) { - return CleanExtension(value, extension, "", out replaced); + return CleanExtension(value, extension, string.Empty, out replaced); } internal static string CleanExtension(string value, FriendlyUrlSettings settings, string langParms, out bool replaced) @@ -692,7 +734,7 @@ internal static string CleanExtension(string value, FriendlyUrlSettings settings internal static string CleanExtension(string value, FriendlyUrlSettings settings, out bool replaced) { - return CleanExtension(value, settings.PageExtension, "", out replaced); + return CleanExtension(value, settings.PageExtension, string.Empty, out replaced); } internal static string CleanExtension(string value, string extension, string langParms, out bool replaced) @@ -700,7 +742,7 @@ internal static string CleanExtension(string value, string extension, string lan string result = value; string ext = extension.ToLowerInvariant(); replaced = false; - if (result.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase) && ext != "") + if (result.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase) && ext != string.Empty) { result = result.Substring(0, result.Length - ext.Length); replaced = true; @@ -714,10 +756,10 @@ internal static string CleanExtension(string value, string extension, string lan } else { - //object not set errors when language parameters used + // object not set errors when language parameters used if (string.IsNullOrEmpty(langParms) == false) { - //safely remove .aspx from the language path without doing a full .aspx -> "" replace on the entire path + // safely remove .aspx from the language path without doing a full .aspx -> "" replace on the entire path if (string.IsNullOrEmpty(result) == false && result.EndsWith(".aspx" + langParms, StringComparison.InvariantCultureIgnoreCase)) { @@ -732,21 +774,22 @@ internal static string CleanExtension(string value, string extension, string lan } } } + return result; } /// - /// Returns either the rewritten path (if a rewrite used) or the requested path (if no rewrite used) + /// Returns either the rewritten path (if a rewrite used) or the requested path (if no rewrite used). /// /// /// - /// Url suitable for input into friendly url generation routine + /// Url suitable for input into friendly url generation routine. internal static string GetRewriteOrRequestedPath(UrlAction result, Uri requestUri) { var pathOnly = result.RewritePath; if (result.DoRewrite == false) { - //if no rewrite, then the path should have been a non-friendly path, and therefore can be passed in to get the friendly Url + // if no rewrite, then the path should have been a non-friendly path, and therefore can be passed in to get the friendly Url pathOnly = requestUri.Authority + requestUri.PathAndQuery; int aliasEnd = pathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) + @@ -755,46 +798,49 @@ internal static string GetRewriteOrRequestedPath(UrlAction result, Uri requestUr { pathOnly = pathOnly.Substring(aliasEnd); } + pathOnly = HttpUtility.UrlDecode(pathOnly, Encoding.UTF8); } + return pathOnly; } internal static string GetTabFromDictionary(string url, NameValueCollection querystringCol, FriendlyUrlSettings settings, UrlAction result, Guid parentTraceId) { - //retrive the tab dictionary from the cache and get the path depth values + // retrive the tab dictionary from the cache and get the path depth values int maxAliasPathDepth; int maxTabPathDepth; int minAliasPathDepth; int minTabPathDepth; int curAliasPathDepth = 0; - var tabDict = TabIndexController.FetchTabDictionary(result.PortalId, - out minTabPathDepth, - out maxTabPathDepth, - out minAliasPathDepth, - out maxAliasPathDepth, - settings, - false, - result.BypassCachedDictionary, - parentTraceId); - - //clean up and prepare the url for scanning + var tabDict = TabIndexController.FetchTabDictionary( + result.PortalId, + out minTabPathDepth, + out maxTabPathDepth, + out minAliasPathDepth, + out maxAliasPathDepth, + settings, + false, + result.BypassCachedDictionary, + parentTraceId); + + // clean up and prepare the url for scanning if (url.EndsWith("/")) { url = url.TrimEnd('/'); } - //ok now scan for the language modifier + // ok now scan for the language modifier string langParms = CheckLanguageMatch(ref url, result); - //clean off the extension before checking the url matches, but - //remember if an extension existed + // clean off the extension before checking the url matches, but + // remember if an extension existed bool hadExtension; string cleanUrl = CleanExtension(url, settings, langParms, out hadExtension); string[] splitUrl = cleanUrl.Split('/'); - //initialise logic switches + // initialise logic switches bool reWritten = false; bool finished = false; @@ -805,33 +851,34 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer reWritten = true; } - //start looping through the url segments looking for a match in the tab dictionary + // start looping through the url segments looking for a match in the tab dictionary while (finished == false) { - //first, try forming up a key based on alias/tabpath + // first, try forming up a key based on alias/tabpath int lastIndex = splitUrl.GetUpperBound(0); int arraySize = lastIndex + 1; int totalDepth = maxAliasPathDepth + 1 + maxTabPathDepth + 1; - //the maximum depth of segments of a valid url + // the maximum depth of segments of a valid url for (int i = lastIndex; i >= 0; i += -1) { - //only start checking the url when it is in the range of the min->max number of segments - if ((i > minAliasPathDepth & i <= totalDepth)) + // only start checking the url when it is in the range of the min->max number of segments + if (i > minAliasPathDepth & i <= totalDepth) { - //join all the tab path sections together - //flag to remember if the incoming path had a .aspx or other pageAndExtension on it + // join all the tab path sections together + // flag to remember if the incoming path had a .aspx or other pageAndExtension on it int tabPathStart = curAliasPathDepth + 1; int tabPathLength = i - curAliasPathDepth; if ((tabPathStart + tabPathLength) <= arraySize) { - string tabPath = ""; - if ((tabPathLength > -1)) + string tabPath = string.Empty; + if (tabPathLength > -1) { tabPath = string.Join("/", splitUrl, tabPathStart, tabPathLength); } + string aliasPath; - if ((curAliasPathDepth <= lastIndex)) + if (curAliasPathDepth <= lastIndex) { aliasPath = string.Join("/", splitUrl, 0, curAliasPathDepth + 1); } @@ -840,21 +887,23 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer finished = true; break; } + int parmsSize = lastIndex - i; - int parmStart = i + 1; //determine if any parameters on this value + int parmStart = i + 1; // determine if any parameters on this value - //make up the index that is looked for in the Tab Dictionary + // make up the index that is looked for in the Tab Dictionary string urlPart = aliasPath + "::" + tabPath; - //the :: allows separation of pagename and portal alias - - string tabKeyVal = urlPart.ToLowerInvariant(); //force lower case lookup, all keys are lower case + + // the :: allows separation of pagename and portal alias + string tabKeyVal = urlPart.ToLowerInvariant(); // force lower case lookup, all keys are lower case - //Try with querystring first If last Index + // Try with querystring first If last Index bool found = false; if (querystringCol.Count > 0) { found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue) + "?" + querystringCol.ToString().Split('&')[0].ToLowerInvariant(), result, settings, tabDict, ref newUrl); } + if (!found) { found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue), result, settings, tabDict, ref newUrl); @@ -863,7 +912,7 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer bool isSiteRootMatch = false; if (!found && tabPathLength == 1) { - //look for special case where the site root has a * value + // look for special case where the site root has a * value string siteRootLookup = aliasPath + "::" + "*"; using (tabDict.GetReadLock()) { @@ -872,8 +921,8 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer { isSiteRootMatch = true; newUrl = tabDict[siteRootLookup]; - parmsSize++; //re-increase the parameter size - parmStart--; //shift the point of the parms starting back one + parmsSize++; // re-increase the parameter size + parmStart--; // shift the point of the parms starting back one } } } @@ -885,43 +934,45 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer newUrl = ReplaceDefaultPage(newUrl, url, settings.ProcessRequestList); } - //look for a plain match on the default.aspx page which indicates no more rewriting needs to be done + // look for a plain match on the default.aspx page which indicates no more rewriting needs to be done if (!isSiteRootMatch && (newUrl == Globals.glbDefaultPage || newUrl == Globals.glbDefaultPage + "[UseBase]")) { - //the [UseBase] moniker is a shortcut hack. It's used to recognise pages which have been excluded - //from using Friendly Urls. The request will go on to be processed by the dnn siteurls.config processing. - //this stops the loop and exits the function - newUrl = newUrl.Replace("[UseBase]", ""); //get rid of usebase hack pattern - SetRewriteParameters(ref result, newUrl); //set result + // the [UseBase] moniker is a shortcut hack. It's used to recognise pages which have been excluded + // from using Friendly Urls. The request will go on to be processed by the dnn siteurls.config processing. + // this stops the loop and exits the function + newUrl = newUrl.Replace("[UseBase]", string.Empty); // get rid of usebase hack pattern + SetRewriteParameters(ref result, newUrl); // set result finished = true; } else { - //708 : move result rewrite set so that downstream functions know the tabid + // 708 : move result rewrite set so that downstream functions know the tabid SetRewriteParameters(ref result, newUrl); - //found the correct rewrite page, now investigate whether there - //is part of the url path that needs to be converted to tab id's - // Multi Language Urls not being rewritten + + // found the correct rewrite page, now investigate whether there + // is part of the url path that needs to be converted to tab id's + // Multi Language Urls not being rewritten if (parmsSize > 0) { bool rewriteParms = false; - //determine the url action and reason from embedded rewriting tokens + // determine the url action and reason from embedded rewriting tokens ActionType action; RedirectReason reason; string resultingUrl; - RedirectTokens.DetermineRedirectReasonAndAction(newUrl, - result, - true, - settings, - out resultingUrl, - out reason, - out action); + RedirectTokens.DetermineRedirectReasonAndAction( + newUrl, + result, + true, + settings, + out resultingUrl, + out reason, + out action); newUrl = resultingUrl; result.Action = action; result.Reason = reason; - //copy the parms into a separate array + // copy the parms into a separate array var urlParms = new string[parmsSize]; Array.ConstrainedCopy(splitUrl, parmStart, urlParms, 0, parmsSize); @@ -931,113 +982,124 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer newUrl = RedirectTokens.RemoveAnyRedirectTokensAndReasons(newUrl); } - //738 : check for custom module providers - //894 : allow disable of custom url providers functionality + // 738 : check for custom module providers + // 894 : allow disable of custom url providers functionality if (!rewriteParms && settings.EnableCustomProviders) { bool newAction; - //newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. - //call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. + + // newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. + // call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. List messages = result.DebugMessages; - newUrl = RewriteParametersFromModuleProvider(newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - result, - settings, - out rewriteParms, - out newAction, - ref messages, - parentTraceId); + newUrl = RewriteParametersFromModuleProvider( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + result, + settings, + out rewriteParms, + out newAction, + ref messages, + parentTraceId); result.DebugMessages = messages; if (newAction) { finished = true; } } - //do a rewrite on the parameters from the stored parameter regex rewrites + + // do a rewrite on the parameters from the stored parameter regex rewrites if (!rewriteParms) { - newUrl = RewriteParameters(newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - result, - out rewriteParms, - parentTraceId); + newUrl = RewriteParameters( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + result, + out rewriteParms, + parentTraceId); } + if (rewriteParms && isSiteRootMatch) { - //set rewrite parameters to take tabid for site root matches + // set rewrite parameters to take tabid for site root matches SetRewriteParameters(ref result, newUrl); } - //if the parms weren't rewritten by means of a regex, then process them normally + // if the parms weren't rewritten by means of a regex, then process them normally if (!rewriteParms && !isSiteRootMatch) - //can only try other matches if it wasn't a site root match + + // can only try other matches if it wasn't a site root match { - //put those parms on the back of the url as a query string + // put those parms on the back of the url as a query string string cultureCode; - newUrl = RewriteParameters(newUrl, - tabKeyVal, - urlParms, - result, - langParms, - settings, - out cultureCode); - if (cultureCode != null) //set culture code if not already set + newUrl = RewriteParameters( + newUrl, + tabKeyVal, + urlParms, + result, + langParms, + settings, + out cultureCode); + if (cultureCode != null) // set culture code if not already set { result.CultureCode = cultureCode; } } - //now check if the request involved a page pageAndExtension, (.aspx) and shouldn't have + + // now check if the request involved a page pageAndExtension, (.aspx) and shouldn't have if (!finished) { - //944 : don't switch to 301 redirect if action already set to 404 + // 944 : don't switch to 301 redirect if action already set to 404 if ((settings.PageExtensionUsageType == PageExtensionUsageType.Never || settings.PageExtensionUsageType == PageExtensionUsageType.PageOnly) & hadExtension) { - //948 : use new 'no downgrade' method + // 948 : use new 'no downgrade' method result.SetActionWithNoDowngrade(ActionType.CheckFor301); } - else - //866 : redirect back from no extension to extension if it didn't have one + else + + // 866 : redirect back from no extension to extension if it didn't have one if (settings.PageExtensionUsageType != PageExtensionUsageType.Never && - hadExtension == false) - { - //948 : use new 'no downgrade' method - result.SetActionWithNoDowngrade(ActionType.CheckFor301); - } + hadExtension == false) + { + // 948 : use new 'no downgrade' method + result.SetActionWithNoDowngrade(ActionType.CheckFor301); + } } if (isSiteRootMatch && !finished) - //when it was a site root match, this must be matched with a custom parameter regex + + // when it was a site root match, this must be matched with a custom parameter regex { - //only finished if the parms were rewritten by means of a regex rewrite + // only finished if the parms were rewritten by means of a regex rewrite reWritten = rewriteParms; finished = rewriteParms; } else { - //rewriting done + // rewriting done reWritten = true; finished = true; } } else { - //determine the url action and redirect reason from embedded tokens in the url rewrite path + // determine the url action and redirect reason from embedded tokens in the url rewrite path string resultUrl; RedirectReason reason; ActionType action; - //add back language parameters if they were there + + // add back language parameters if they were there if (string.IsNullOrEmpty(langParms) == false) { string[] parms = langParms.Split('/'); if (parms.GetUpperBound(0) >= 1) { - if (parms[0] == "" && parms.GetUpperBound(0) > 1) + if (parms[0] == string.Empty && parms.GetUpperBound(0) > 1) { newUrl += "&" + parms[1] + "=" + parms[2]; } @@ -1047,6 +1109,7 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer } } } + RedirectTokens.DetermineRedirectReasonAndAction(newUrl, result, false, settings, out resultUrl, out reason, out action); @@ -1054,57 +1117,64 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer result.Reason = reason; result.Action = action; - if (settings.EnableCustomProviders && ExtensionUrlProviderController.CheckForAlwaysCallProviders(result.PortalId, - result.TabId, - settings, - parentTraceId)) + if (settings.EnableCustomProviders && ExtensionUrlProviderController.CheckForAlwaysCallProviders( + result.PortalId, + result.TabId, + settings, + parentTraceId)) { bool newAction; - //newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. - //call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. - string[] urlParms = (new List()).ToArray(); //empty parm array + + // newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. + // call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. + string[] urlParms = new List().ToArray(); // empty parm array if (string.IsNullOrEmpty(langParms) == false) { urlParms = langParms.Split('/'); - //split the lang parms into the url Parms + + // split the lang parms into the url Parms } + bool rewriteParms; List messages = result.DebugMessages; - newUrl = RewriteParametersFromModuleProvider(newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - result, - settings, - out rewriteParms, - out newAction, - ref messages, - parentTraceId); + newUrl = RewriteParametersFromModuleProvider( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + result, + settings, + out rewriteParms, + out newAction, + ref messages, + parentTraceId); result.DebugMessages = messages; } - //this is a page only, no parameters to deal with - //944 : don't downgrade to redirect if the current action is a 404 (see 948 for new solution to 944) + // this is a page only, no parameters to deal with + // 944 : don't downgrade to redirect if the current action is a 404 (see 948 for new solution to 944) if (settings.PageExtensionUsageType == PageExtensionUsageType.Never & hadExtension) { - //potentially a 301 replaced because shouldn't be using page extensions - //948 : check to prevent action downgrade, in case already set to redirect + // potentially a 301 replaced because shouldn't be using page extensions + // 948 : check to prevent action downgrade, in case already set to redirect result.SetActionWithNoDowngrade(ActionType.CheckFor301); } else { - //866 : redirect back from no extension to extension if it didn't have one + // 866 : redirect back from no extension to extension if it didn't have one if (settings.PageExtensionUsageType != PageExtensionUsageType.Never && hadExtension == false) { result.SetActionWithNoDowngrade(ActionType.CheckFor301); } } - //rewriting done + + // rewriting done reWritten = true; finished = true; } } + if (finished) { break; @@ -1114,17 +1184,18 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer } } - //next, try forming up a key based on alias1/alias2/tabpath + // next, try forming up a key based on alias1/alias2/tabpath if (!finished) { curAliasPathDepth += 1; - //gone too deep + + // gone too deep if ((curAliasPathDepth > maxAliasPathDepth) && !reWritten) { - // no hope of finding it then + // no hope of finding it then if (!Globals.ServicesFrameworkRegex.IsMatch(url) && result.RedirectAllowed) { - //nothing left to try + // nothing left to try result.Action = (settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error) ? ActionType.Output404 : ActionType.Redirect301; @@ -1149,38 +1220,44 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer internal static void GetUrlWithQuerystring(HttpRequest request, Uri requestUri, out string fullUrl, out string querystring) { - //699: incorrect encoding in absoluteUri.ToString() + // 699: incorrect encoding in absoluteUri.ToString() string urlWoutQuery = requestUri.AbsoluteUri; - if (requestUri.Query != "") + if (requestUri.Query != string.Empty) { - urlWoutQuery = urlWoutQuery.Replace(requestUri.Query, ""); + urlWoutQuery = urlWoutQuery.Replace(requestUri.Query, string.Empty); + // replace the querystring on the reuqest absolute Uri } - //926 : do not use querystring.toString() because of encoding errors that restul, - //the encoding type is changed from utf-8 to latin-1 + + // 926 : do not use querystring.toString() because of encoding errors that restul, + // the encoding type is changed from utf-8 to latin-1 querystring = requestUri.Query; - //get results + + // get results fullUrl = urlWoutQuery; if (fullUrl.EndsWith("/_noext.aspx", StringComparison.InvariantCultureIgnoreCase)) { - fullUrl = fullUrl.Replace("_noext.aspx", ""); - //replace this marker pattern so it looks as though it isn't there *(leave on trailing slash) + fullUrl = fullUrl.Replace("_noext.aspx", string.Empty); + + // replace this marker pattern so it looks as though it isn't there *(leave on trailing slash) } - if (querystring != "") + + if (querystring != string.Empty) { - //set up the querystring and the fullUrl to include the querystring + // set up the querystring and the fullUrl to include the querystring if (querystring.StartsWith("?") == false) { querystring = "?" + querystring; } + fullUrl += querystring; } } /// - /// Identifies a request for a physical file on the system + /// Identifies a request for a physical file on the system. /// - /// The Physical Path propery of the request + /// The Physical Path propery of the request. /// /// /// @@ -1189,25 +1266,25 @@ internal static void GetUrlWithQuerystring(HttpRequest request, Uri requestUri, /// /// /// - /// true if a physical path, false if not - internal static void IdentifyByPhysicalResource(string physicalPath, - string fullUrl, - NameValueCollection queryStringCol, - ref UrlAction result, - bool useFriendlyUrls, - FriendlyUrlSettings settings, - out bool isPhysicalResource, - out bool checkFurtherForRewrite, - Guid parentTraceId) + internal static void IdentifyByPhysicalResource( + string physicalPath, + string fullUrl, + NameValueCollection queryStringCol, + ref UrlAction result, + bool useFriendlyUrls, + FriendlyUrlSettings settings, + out bool isPhysicalResource, + out bool checkFurtherForRewrite, + Guid parentTraceId) { isPhysicalResource = false; checkFurtherForRewrite = true; if (File.Exists(physicalPath) && physicalPath.EndsWith("\\_noext.aspx") == false) { - //resource found + // resource found string appPath = Globals.ApplicationMapPath + "\\default.aspx"; bool isDefaultAspxPath = false; - if (String.Compare(physicalPath, appPath, StringComparison.OrdinalIgnoreCase) != 0) + if (string.Compare(physicalPath, appPath, StringComparison.OrdinalIgnoreCase) != 0) { string aliasQs; if (AdvancedUrlRewriter.CheckForChildPortalRootUrl(fullUrl, result, out aliasQs)) @@ -1216,7 +1293,7 @@ internal static void IdentifyByPhysicalResource(string physicalPath, } else { - //it's not the default.aspx path or a child alias request, so we haven't identifed the resource + // it's not the default.aspx path or a child alias request, so we haven't identifed the resource isPhysicalResource = true; checkFurtherForRewrite = false; result.DebugMessages.Add("Resource Identified No Rewrite Used"); @@ -1227,15 +1304,15 @@ internal static void IdentifyByPhysicalResource(string physicalPath, isDefaultAspxPath = true; } - if (isDefaultAspxPath) //it is the default aspx path + if (isDefaultAspxPath) // it is the default aspx path { - //check to see if it is a /default.aspx?key=value url (not just default.aspx, nor a child alias) - if ((queryStringCol != null && queryStringCol.Count > 0)) + // check to see if it is a /default.aspx?key=value url (not just default.aspx, nor a child alias) + if (queryStringCol != null && queryStringCol.Count > 0) { - //when there is a query string supplied, we don't need to rewrite + // when there is a query string supplied, we don't need to rewrite if (useFriendlyUrls) { - //using friendly URls, so just nab the Tab id from the querystring + // using friendly URls, so just nab the Tab id from the querystring if (queryStringCol["tabId"] != null) { if (result.RedirectAllowed) @@ -1245,31 +1322,34 @@ internal static void IdentifyByPhysicalResource(string physicalPath, } } } + result.DoRewrite = false; checkFurtherForRewrite = false; - //no more checking for rewrites, we have our physical file and our query string - //the default.aspx is still a physical resource, but we want to do the rest of the processing + + // no more checking for rewrites, we have our physical file and our query string + // the default.aspx is still a physical resource, but we want to do the rest of the processing } else { - //could be either default.aspx with no querystring, or a child portal alias root - //if 301 redirects are on, then we want to rewrite and replace this Url to include information like language modifiers - //so return false to indicate that the physical resource couldn't be identified + // could be either default.aspx with no querystring, or a child portal alias root + // if 301 redirects are on, then we want to rewrite and replace this Url to include information like language modifiers + // so return false to indicate that the physical resource couldn't be identified isPhysicalResource = !useFriendlyUrls; } } } - //mark as physical request + // mark as physical request result.IsPhysicalResource = isPhysicalResource; } - internal static bool IdentifyByRegEx(string absoluteUri, - string queryString, - string applicationPath, - ref UrlAction result, - FriendlyUrlSettings settings, - Guid parentTraceId) + internal static bool IdentifyByRegEx( + string absoluteUri, + string queryString, + string applicationPath, + ref UrlAction result, + FriendlyUrlSettings settings, + Guid parentTraceId) { var doRewrite = false; @@ -1277,11 +1357,12 @@ internal static bool IdentifyByRegEx(string absoluteUri, if (rewriterConfig != null) { - var url = absoluteUri; //get local copy because it gets hacked around - // Remove querystring if exists.. - if (queryString != "") + var url = absoluteUri; // get local copy because it gets hacked around + + // Remove querystring if exists.. + if (queryString != string.Empty) { - url = url.Replace(queryString, ""); + url = url.Replace(queryString, string.Empty); } var rules = rewriterConfig.Rules; @@ -1289,25 +1370,28 @@ internal static bool IdentifyByRegEx(string absoluteUri, { throw new NullReferenceException("DotNetNuke.HttpModules.Config.RewriterRuleCollection is null"); } + for (var i = 0; i <= rules.Count - 1; i++) { - //iterate the Config Rules looking for a match + // iterate the Config Rules looking for a match var re = rules[i].GetRuleRegex(applicationPath); if (re.IsMatch(url)) { var sendTo = rules[i].SendTo; - //get a new rewritePath location - - var rewritePath = RewriterUtils.ResolveUrl(applicationPath, re.Replace(url, sendTo)); //no rewrite path unless we match by regex the intended tab + + // get a new rewritePath location + var rewritePath = RewriterUtils.ResolveUrl(applicationPath, re.Replace(url, sendTo)); // no rewrite path unless we match by regex the intended tab var sesMatch = re.Match(url); var sesUrlParams = sesMatch.Groups[2].Value; - //a match by regex means it's probably not a 'friendly' Url, so assume at this stage that this request will end up a 301 + + // a match by regex means it's probably not a 'friendly' Url, so assume at this stage that this request will end up a 301 if (settings.UrlFormat == "advanced" && settings.RedirectUnfriendly) { result.Action = ActionType.CheckFor301; } - //if a match is found here, there is the potential for a 'friendlier' url - if ((sesUrlParams.Trim().Length > 0)) + + // if a match is found here, there is the potential for a 'friendlier' url + if (sesUrlParams.Trim().Length > 0) { sesUrlParams = sesUrlParams.Replace("\\", "/"); var urlParams = sesUrlParams.Split('/'); @@ -1316,22 +1400,23 @@ internal static bool IdentifyByRegEx(string absoluteUri, if (urlParams[x].Trim().Length > 0 && !urlParams[x].Equals(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { - rewritePath = rewritePath + "&" + urlParams[x].Replace(".aspx", "").Trim() + "="; - if ((x < (urlParams.Length - 1))) + rewritePath = rewritePath + "&" + urlParams[x].Replace(".aspx", string.Empty).Trim() + "="; + if (x < (urlParams.Length - 1)) { x += 1; - if ((urlParams[x].Trim() != "")) + if (urlParams[x].Trim() != string.Empty) { - rewritePath = rewritePath + urlParams[x].Replace(".aspx", ""); + rewritePath = rewritePath + urlParams[x].Replace(".aspx", string.Empty); } } } } } - //add back the query string if it was there + + // add back the query string if it was there rewritePath = AddQueryStringToRewritePath(rewritePath, queryString); - //832 : check for leading ~ - if not there, then redirect + // 832 : check for leading ~ - if not there, then redirect if (sendTo.StartsWith("~")) { doRewrite = true; @@ -1341,49 +1426,55 @@ internal static bool IdentifyByRegEx(string absoluteUri, } else { - //we'll assume it's a 301 instead of a 302 + // we'll assume it's a 301 instead of a 302 result.Action = ActionType.Redirect301; result.DoRewrite = false; result.Reason = RedirectReason.SiteUrls_Config_Rule; result.FinalUrl = rewritePath; } - break; //exit loop, match found + + break; // exit loop, match found } - } + } } return doRewrite; } - internal static bool IdentifyByTabPathEx(string absoluteUri, - string queryString, - UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - Guid parentTraceId) + internal static bool IdentifyByTabPathEx( + string absoluteUri, + string queryString, + UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + Guid parentTraceId) { string scheme = result.Scheme; if (absoluteUri.StartsWith(scheme, StringComparison.InvariantCultureIgnoreCase)) { absoluteUri = absoluteUri.Substring(scheme.Length); } - // Remove QueryString if it exists in the Url value - if ((queryString != "")) + + // Remove QueryString if it exists in the Url value + if (queryString != string.Empty) { - absoluteUri = absoluteUri.Replace(queryString, ""); + absoluteUri = absoluteUri.Replace(queryString, string.Empty); } - absoluteUri = HttpUtility.UrlDecode(absoluteUri); //decode the incoming request + + absoluteUri = HttpUtility.UrlDecode(absoluteUri); // decode the incoming request string rewritePath = GetTabFromDictionary(absoluteUri, queryStringCol, settings, result, parentTraceId); - //put the query string back on the end + + // put the query string back on the end rewritePath = AddQueryStringToRewritePath(rewritePath, queryString); - //810 : if a culture code is not specified in the rewrite path + + // 810 : if a culture code is not specified in the rewrite path if (result.DoRewrite && settings.ForcePortalDefaultLanguage && result.PortalId >= 0 && rewritePath.Contains("language=") == false) { - //add the portal default language to the rewrite path + // add the portal default language to the rewrite path PortalInfo portal = CacheController.GetPortal(result.PortalId, false); - - //DNN-3789 - culture is defined by GetPageLocale + + // DNN-3789 - culture is defined by GetPageLocale string currentLocale = Localization.GetPageLocale(new PortalSettings(result.TabId, result.PortalAlias)).Name; if (portal != null && !string.IsNullOrEmpty(currentLocale)) { @@ -1392,7 +1483,8 @@ internal static bool IdentifyByTabPathEx(string absoluteUri, result.DebugMessages.Add("Current Language code " + currentLocale + " added"); } } - //set the rewrite path + + // set the rewrite path result.RewritePath = rewritePath; return result.DoRewrite; } @@ -1404,7 +1496,7 @@ internal static bool IdentifyByTabQueryString(Uri requestUri, NameValueCollectio if (useFriendlyUrls) { - //using friendly URls, so just nab the Tab id from the querystring + // using friendly URls, so just nab the Tab id from the querystring if (result.RedirectAllowed && requestedPath.EndsWith(Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) && (queryStringCol["tabId"] != null)) { @@ -1412,42 +1504,45 @@ internal static bool IdentifyByTabQueryString(Uri requestUri, NameValueCollectio result.Reason = RedirectReason.Unfriendly_Url_TabId; } } + result.DoRewrite = doRewrite; return doRewrite; } /// - /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0 + /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0. /// /// - /// The path of the tab //admin//someothername + /// The path of the tab //admin//someothername. /// - /// /// Duplicated in UrlMasterController.cs + /// /// Duplicated in UrlMasterController.cs. /// internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) { var portal = PortalController.Instance.GetPortal(portalId); var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portalId); - //return false if AdminTabId is -1, it could happen when a portal is in the middle of importing + // return false if AdminTabId is -1, it could happen when a portal is in the middle of importing if (adminTab == null) { return false; } - + string adminPageName = adminTab.TabName; - //we should be checking that the tab path matches //Admin//pagename or //admin - //in this way we should avoid partial matches (ie //Administrators + + // we should be checking that the tab path matches //Admin//pagename or //admin + // in this way we should avoid partial matches (ie //Administrators if (tabPath.StartsWith("//" + adminPageName + "//", StringComparison.CurrentCultureIgnoreCase) - || String.Compare(tabPath, "//" + adminPageName, StringComparison.OrdinalIgnoreCase) == 0) + || string.Compare(tabPath, "//" + adminPageName, StringComparison.OrdinalIgnoreCase) == 0) { return true; } + return false; } /// - /// Determines if the tab is excluded from FriendlyUrl Processing + /// Determines if the tab is excluded from FriendlyUrl Processing. /// /// /// @@ -1457,9 +1552,10 @@ internal static bool IsExcludedFromFriendlyUrls(TabInfo tab, FriendlyUrlSettings { bool exclude = false; string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLowerInvariant(); - //553 change for dnn 5.0 isAdminTab no longer returns true in any case, so - //check custom admin tab path header - //811: allow for admin tabs to be friendly + + // 553 change for dnn 5.0 isAdminTab no longer returns true in any case, so + // check custom admin tab path header + // 811: allow for admin tabs to be friendly if (settings.FriendlyAdminHostUrls == false && IsAdminTab(tab.PortalID, tab.TabPath, settings)) { exclude = true; @@ -1474,18 +1570,18 @@ internal static bool IsExcludedFromFriendlyUrls(TabInfo tab, FriendlyUrlSettings } /// - /// Checks for a current parameter belonging to one of the built in 'ctl' values + /// Checks for a current parameter belonging to one of the built in 'ctl' values. /// /// /// /// - /// Sets the Action parameter of the Result to 'CheckFor301' if suspected. Actual redirect taken care of by friendly url redirection logic + /// Sets the Action parameter of the Result to 'CheckFor301' if suspected. Actual redirect taken care of by friendly url redirection logic. internal static void RequestRedirectOnBuiltInUrl(string urlParm, string rewritePath, UrlAction result) { - //on the lookout for items to potentially redirect + // on the lookout for items to potentially redirect if ("terms|privacy|login|register".Contains(urlParm.ToLowerInvariant())) { - //likely that this should be redirected, because we don't want ctl/terms, ctl/register, etc + // likely that this should be redirected, because we don't want ctl/terms, ctl/register, etc result.Reason = RedirectReason.Built_In_Url; result.Action = ActionType.CheckFor301; result.DebugMessages.Add("Built-in Url found: " + rewritePath); @@ -1493,28 +1589,29 @@ internal static void RequestRedirectOnBuiltInUrl(string urlParm, string rewriteP } /// - /// converts an array of Url path sections into the rewritten string of parameters for the requested Url + /// converts an array of Url path sections into the rewritten string of parameters for the requested Url. /// - /// The current candidate for the rewritten tab path, as found in the tab dictionary - /// The tabKey value which was used to find the current newUrl value - /// The Url path (after the tab name) converted to an array - /// The UrlAction parameter keeping track of the values - /// The raw language/xx-XX values from the requested Url - /// The current friendly url settings + /// The current candidate for the rewritten tab path, as found in the tab dictionary. + /// The tabKey value which was used to find the current newUrl value. + /// The Url path (after the tab name) converted to an array. + /// The UrlAction parameter keeping track of the values. + /// The raw language/xx-XX values from the requested Url. + /// The current friendly url settings. /// an out parameter identifying if a culture code was determined during the process. /// - internal static string RewriteParameters(string newUrl, - string tabKeyVal, - string[] urlParms, - UrlAction result, - string langParms, - FriendlyUrlSettings settings, - out string cultureCode) + internal static string RewriteParameters( + string newUrl, + string tabKeyVal, + string[] urlParms, + UrlAction result, + string langParms, + FriendlyUrlSettings settings, + out string cultureCode) { - cultureCode = null; //culture code is assigned from the langParms value, if it exists + cultureCode = null; // culture code is assigned from the langParms value, if it exists if (urlParms != null) { - //determine page extension value and usage + // determine page extension value and usage string pageExtension = settings.PageExtension; var parmString = new StringBuilder(); @@ -1525,17 +1622,17 @@ internal static string RewriteParameters(string newUrl, string userIdParm = null; var thisPortal = PortalController.Instance.GetPortal(result.PortalId); - //check if there is more than one parm, and keep the value of the primary (first) parm + // check if there is more than one parm, and keep the value of the primary (first) parm if (thisPortal.UserTabId == result.TabId || thisPortal.UserTabId == -1) { - //719 : shift to only remove last parm on pages with 'all' match - stripLoneParm = true; //710 : don't put in username into rewritten parameters + // 719 : shift to only remove last parm on pages with 'all' match + stripLoneParm = true; // 710 : don't put in username into rewritten parameters userIdParm = "UserId"; } - //recheck firstParmLast - just because it is set to be that way in the config doesn't - //mean that the url will come in that way. - //first strip out any language parameters + // recheck firstParmLast - just because it is set to be that way in the config doesn't + // mean that the url will come in that way. + // first strip out any language parameters if (langParms != null) { string[] langValues = langParms.TrimStart('/').Split('/'); @@ -1544,7 +1641,7 @@ internal static string RewriteParameters(string newUrl, int pos1 = -1, pos2 = -1; for (int i = 0; i < urlParms.GetUpperBound(0); i++) { - //match this part of the urlParms with the language parms + // match this part of the urlParms with the language parms if (urlParms[i] == langValues[0] && urlParms[i + 1] == langValues[1]) { pos1 = i; @@ -1552,14 +1649,16 @@ internal static string RewriteParameters(string newUrl, break; } } + if (pos1 > -1 && pos2 > -1) { - //this hacky operation removes the language urls from the array + // this hacky operation removes the language urls from the array var temp = new List(urlParms); temp.RemoveAt(pos2); temp.RemoveAt(pos1); urlParms = temp.ToArray(); - //656 : don't allow forced lower case of the culture identifier - always convert the case to aa-AA to match the standard + + // 656 : don't allow forced lower case of the culture identifier - always convert the case to aa-AA to match the standard string cultureId = langValues[1]; Match cultureMatch = CultureMatchRegex.Match(cultureId); if (cultureMatch.Success) @@ -1567,7 +1666,8 @@ internal static string RewriteParameters(string newUrl, cultureId = cultureMatch.Groups[1].Value + "-" + cultureMatch.Groups[2].ToString().ToUpper(); } - //set procedure level culture code, which indicates a language was found in the path + + // set procedure level culture code, which indicates a language was found in the path cultureCode = cultureId; } } @@ -1575,36 +1675,39 @@ internal static string RewriteParameters(string newUrl, lastParmToProcessTo = urlParms.GetUpperBound(0); - //build up the parameters rewrite string by iterating through the key/value pairs in the Url - //and turn them into &key=value pairs. + // build up the parameters rewrite string by iterating through the key/value pairs in the Url + // and turn them into &key=value pairs. string keyName = null; bool skip = false; bool isUserParm = false; for (int i = 0; i <= lastParmToProcessTo; i++) { string thisParm = urlParms[i]; - //here's the thing - we either take the last one and put it at the start, or just go two-by-two + + // here's the thing - we either take the last one and put it at the start, or just go two-by-two if (!thisParm.Equals(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { if (thisParm.Equals("tabid", StringComparison.InvariantCultureIgnoreCase)) { skip = true; - //discovering the tabid in the list of parameters means that - //it was likely a request for an old-style tab url that - //found a retVal due to match in the tab path. - //while this may mean a 301, we definitely don't want to force a 301, - //just investigate it and let the 301 redirect logic work it out - //we also want to skip the next parameter, because it is the tabid value + + // discovering the tabid in the list of parameters means that + // it was likely a request for an old-style tab url that + // found a retVal due to match in the tab path. + // while this may mean a 301, we definitely don't want to force a 301, + // just investigate it and let the 301 redirect logic work it out + // we also want to skip the next parameter, because it is the tabid value if (result.Reason != RedirectReason.Custom_Redirect) { - //only reason not to let this one through and count on the - //friendly url checking code is if it was a custom redirect set up + // only reason not to let this one through and count on the + // friendly url checking code is if it was a custom redirect set up result.Reason = RedirectReason.Not_Redirected; result.Action = ActionType.CheckFor301; - //set the value field back to false, because, even if the parameter handling is - //first parm last, this was an old style URl desitned to be redirected. - //and we would expect old-style urls to have the correct parameter order - //note this assumes tabid is the first parm in the list. + + // set the value field back to false, because, even if the parameter handling is + // first parm last, this was an old style URl desitned to be redirected. + // and we would expect old-style urls to have the correct parameter order + // note this assumes tabid is the first parm in the list. valueField = false; } } @@ -1613,13 +1716,14 @@ internal static string RewriteParameters(string newUrl, bool extReplaced; string urlParm = CleanExtension(thisParm, pageExtension, out extReplaced); - if (extReplaced && pageExtension == "") //replacing a .aspx extension + if (extReplaced && pageExtension == string.Empty) // replacing a .aspx extension { result.Action = ActionType.CheckFor301; } + if (valueField) { - //this parameter is going into the value half of a &key=value pair + // this parameter is going into the value half of a &key=value pair parmString.Append("="); parmString.Append(urlParm); valueField = false; @@ -1629,7 +1733,8 @@ internal static string RewriteParameters(string newUrl, int.TryParse(urlParm, out userIdVal); isUserParm = false; } - //786 : redirect ctl/terms etc + + // 786 : redirect ctl/terms etc if (keyName != null && keyName.ToLowerInvariant() == "ctl") { RequestRedirectOnBuiltInUrl(urlParm, parmString.ToString(), result); @@ -1637,15 +1742,16 @@ internal static string RewriteParameters(string newUrl, } else { - //this parameter is going into the key half of a &key=value pair + // this parameter is going into the key half of a &key=value pair keyName = urlParm; parmString.Append("&"); parmString.Append(urlParm); valueField = true; - //if we are looking for a userid parameter in this querystring, check for a match + + // if we are looking for a userid parameter in this querystring, check for a match if (userIdParm != null) { - if (String.Compare(keyName, userIdParm, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(keyName, userIdParm, StringComparison.OrdinalIgnoreCase) == 0) { isUserParm = true; } @@ -1659,9 +1765,10 @@ internal static string RewriteParameters(string newUrl, } } - //add back language parameters if they were found + // add back language parameters if they were found AddLanguageCodeToRewritePath(ref newUrl, cultureCode); - //add on the parameter string + + // add on the parameter string newUrl += parmString.ToString(); if (stripLoneParm) @@ -1672,17 +1779,19 @@ internal static string RewriteParameters(string newUrl, newUrl = newUrl.Substring(0, newUrl.Length - 1); } } - //chop the last char off if it is an empty parameter - if ((newUrl[newUrl.Length - 1] == '&')) + + // chop the last char off if it is an empty parameter + if (newUrl[newUrl.Length - 1] == '&') { newUrl = newUrl.Substring(0, newUrl.Length - 1); } } + return newUrl; } /// - /// Scans the collection of Rewrite Parameter rules, and rewrites the parameters if a match is found + /// Scans the collection of Rewrite Parameter rules, and rewrites the parameters if a match is found. /// /// /// @@ -1691,25 +1800,29 @@ internal static string RewriteParameters(string newUrl, /// /// /// - /// The new Url with the parameters rewritten onto the end of hte old Url - internal static string RewriteParameters(string newUrl, - string tabKeyVal, - string[] urlParms, - bool isSiteRoot, - UrlAction urlAction, - out bool rewriteParms, - Guid parentTraceId) + /// The new Url with the parameters rewritten onto the end of hte old Url. + internal static string RewriteParameters( + string newUrl, + string tabKeyVal, + string[] urlParms, + bool isSiteRoot, + UrlAction urlAction, + out bool rewriteParms, + Guid parentTraceId) { string result = newUrl; rewriteParms = false; - //get the actions from the cache + + // get the actions from the cache var messages = new List(); - Dictionary> rewriteActions = CacheController.GetParameterRewrites(urlAction.PortalId, - ref messages, parentTraceId); + Dictionary> rewriteActions = CacheController.GetParameterRewrites( + urlAction.PortalId, + ref messages, parentTraceId); if (messages == null) { messages = new List(); } + try { if (rewriteActions != null && rewriteActions.Count > 0) @@ -1720,62 +1833,69 @@ internal static string RewriteParameters(string newUrl, { string rawTabId = tabMatch.Groups["tabid"].Value; int tabId; - if (Int32.TryParse(rawTabId, out tabId)) + if (int.TryParse(rawTabId, out tabId)) { if (rewriteActions.ContainsKey(tabId)) { - //find the right set of rewrite actions for this tab + // find the right set of rewrite actions for this tab tabRewrites = rewriteActions[tabId]; } } } - if (rewriteActions.ContainsKey(AllTabsRewrite)) //-1 means 'all tabs' - rewriting across all tabs + if (rewriteActions.ContainsKey(AllTabsRewrite)) // -1 means 'all tabs' - rewriting across all tabs { - //initialise to empty collection if there are no specific tab rewrites + // initialise to empty collection if there are no specific tab rewrites if (tabRewrites == null) { tabRewrites = new SharedList(); } - //add in the all rewrites + + // add in the all rewrites SharedList allRewrites = rewriteActions[AllTabsRewrite]; foreach (ParameterRewriteAction rewrite in allRewrites) { - tabRewrites.Add(rewrite); //add the 'all' range to the tab range + tabRewrites.Add(rewrite); // add the 'all' range to the tab range } } + if (isSiteRoot && rewriteActions.ContainsKey(SiteRootRewrite)) { - //initialise to empty collection if there are no specific tab rewrites + // initialise to empty collection if there are no specific tab rewrites if (tabRewrites == null) { tabRewrites = new SharedList(); } + SharedList siteRootRewrites = rewriteActions[SiteRootRewrite]; foreach (ParameterRewriteAction rewrite in siteRootRewrites) { - tabRewrites.Add(rewrite); //add the site root rewrites to the collection + tabRewrites.Add(rewrite); // add the site root rewrites to the collection } } - //get the parms as a string + + // get the parms as a string string parms = string.Join("/", urlParms); if (tabRewrites != null && tabRewrites.Count > 0) { - //process each one until a match is found + // process each one until a match is found foreach (ParameterRewriteAction rewrite in tabRewrites) { var parmRegex = RegexUtils.GetCachedRegex(rewrite.LookFor, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - //check the match, if a match found, do the replacement + + // check the match, if a match found, do the replacement if (parmRegex.IsMatch(parms)) { - //rewrite the parameter + // rewrite the parameter string sendTo = rewrite.RewriteTo; string parmsOriginal = parms; - //replace hte parameter with the rewrite string + + // replace hte parameter with the rewrite string parms = parmRegex.Replace(parms, sendTo); messages.Add(rewrite.Name + " rewrite match (" + parmsOriginal + "), replaced to : " + parms); - //makes sure the newUrl has got a trailing ampersand or a ? to start the query string + + // makes sure the newUrl has got a trailing ampersand or a ? to start the query string if (newUrl.Contains("?")) { if (newUrl.EndsWith("&") == false) @@ -1783,24 +1903,27 @@ internal static string RewriteParameters(string newUrl, newUrl += "&"; } } - else //need to start the querystring off (592: allow for custom rewrites on site root) + else // need to start the querystring off (592: allow for custom rewrites on site root) { newUrl += "?"; } - //makes sure the new parms string hasn't got a starting ampersand + // makes sure the new parms string hasn't got a starting ampersand if (parms.StartsWith("&")) { parms = parms.Substring(1); } - //parameters are added to the back fo the newUrl + + // parameters are added to the back fo the newUrl newUrl += parms; - //it's a rewrite, all right + + // it's a rewrite, all right rewriteParms = true; result = newUrl; urlAction.CustomParmRewrite = true; break; } + messages.Add(rewrite.Name + " rewrite not matched (" + parms + ")"); } } @@ -1814,13 +1937,11 @@ internal static string RewriteParameters(string newUrl, } finally { - //post messages to debug output + // post messages to debug output urlAction.DebugMessages.AddRange(messages); } return result; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Urls/RewriterUtils.cs b/DNN Platform/Library/Entities/Urls/RewriterUtils.cs index f953254a4f3..33240793322 100644 --- a/DNN Platform/Library/Entities/Urls/RewriterUtils.cs +++ b/DNN Platform/Library/Entities/Urls/RewriterUtils.cs @@ -1,36 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Controllers; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Controllers; + public class RewriterUtils { internal static void RewriteUrl(HttpContext context, string sendToUrl) { - //first strip the querystring, if any + // first strip the querystring, if any var queryString = string.Empty; string sendToUrlLessQString = sendToUrl; - if ((sendToUrl.IndexOf("?", StringComparison.Ordinal) > 0)) + if (sendToUrl.IndexOf("?", StringComparison.Ordinal) > 0) { sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf("?", StringComparison.Ordinal)); queryString = sendToUrl.Substring(sendToUrl.IndexOf("?", StringComparison.Ordinal) + 1); - - //Encode querystring values to support unicode characters by M.Kermani - var parameters = new List(); + + // Encode querystring values to support unicode characters by M.Kermani + var parameters = new List(); foreach (var parameter in queryString.Split('&')) { var i = parameter.IndexOf('='); @@ -44,73 +39,80 @@ internal static void RewriteUrl(HttpContext context, string sendToUrl) parameters.Add(parameter); } } - queryString = String.Join("&", parameters); - + + queryString = string.Join("&", parameters); } - - //rewrite the path.. + + // rewrite the path.. context.RewritePath(sendToUrlLessQString, string.Empty, queryString); - //NOTE! The above RewritePath() overload is only supported in the .NET Framework 1.1 - //If you are using .NET Framework 1.0, use the below form instead: - //context.RewritePath(sendToUrl); + + // NOTE! The above RewritePath() overload is only supported in the .NET Framework 1.1 + // If you are using .NET Framework 1.0, use the below form instead: + // context.RewritePath(sendToUrl); } internal static string ResolveUrl(string appPath, string url) { - //String is Empty, just return Url - if (String.IsNullOrEmpty(url)) + // String is Empty, just return Url + if (string.IsNullOrEmpty(url)) { return url; } - - //String does not contain a ~, so just return Url - if ((url.StartsWith("~") == false)) + + // String does not contain a ~, so just return Url + if (url.StartsWith("~") == false) { return url; } - - //There is just the ~ in the Url, return the appPath - if ((url.Length == 1)) + + // There is just the ~ in the Url, return the appPath + if (url.Length == 1) { return appPath; } + var seperatorChar = url.ToCharArray()[1]; if (seperatorChar == '/' || seperatorChar == '\\') { - //Url looks like ~/ or ~\ - if ((appPath.Length > 1)) + // Url looks like ~/ or ~\ + if (appPath.Length > 1) { return appPath + "/" + url.Substring(2); } + return "/" + url.Substring(2); } - //Url look like ~something - if ((appPath.Length > 1)) + + // Url look like ~something + if (appPath.Length > 1) { return appPath + "/" + url.Substring(1); } + return appPath + url.Substring(1); } - static internal bool OmitFromRewriteProcessing(string localPath) + internal static bool OmitFromRewriteProcessing(string localPath) { - var omitSettings = String.Empty; + var omitSettings = string.Empty; if (Globals.Status == Globals.UpgradeStatus.None) { omitSettings = HostController.Instance.GetString("OmitFromRewriteProcessing"); } - if (string.IsNullOrEmpty(omitSettings)) { - omitSettings = "scriptresource.axd|webresource.axd|gif|ico|jpg|jpeg|png|css|js"; - } - omitSettings = omitSettings.ToLowerInvariant(); - localPath = localPath.ToLowerInvariant(); + if (string.IsNullOrEmpty(omitSettings)) + { + omitSettings = "scriptresource.axd|webresource.axd|gif|ico|jpg|jpeg|png|css|js"; + } + + omitSettings = omitSettings.ToLowerInvariant(); + localPath = localPath.ToLowerInvariant(); - var omissions = omitSettings.Split(new[] { '|' }); + var omissions = omitSettings.Split(new[] { '|' }); bool shouldOmit = omissions.Any(x => localPath.EndsWith(x)); - if(!shouldOmit) + if (!shouldOmit) { shouldOmit = Globals.ServicesFrameworkRegex.IsMatch(localPath); } diff --git a/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs b/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs index 00d439fbfe7..e2cad7dc230 100644 --- a/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs +++ b/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs @@ -1,21 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + public class SaveUrlDto { public int Id { get; set; } + public int SiteAliasKey { get; set; } + public string Path { get; set; } + public string QueryString { get; set; } + public int LocaleKey { get; set; } + public int StatusCodeKey { get; set; } + public int SiteAliasUsage { get; set; } + public bool IsSystem { get; set; } } - } diff --git a/DNN Platform/Library/Entities/Urls/StateBoolean.cs b/DNN Platform/Library/Entities/Urls/StateBoolean.cs index 097b098ade3..4ada29764e4 100644 --- a/DNN Platform/Library/Entities/Urls/StateBoolean.cs +++ b/DNN Platform/Library/Entities/Urls/StateBoolean.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum StateBoolean { NotSet = -1, False = 0, - True = 1 + True = 1, } } diff --git a/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs b/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs index b9c3ec83e8f..d7cf44ef4a3 100644 --- a/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs +++ b/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - -/* This code file contains helper classes used for Url Rewriting / Friendly Url generation */ - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +/* This code file contains helper classes used for Url Rewriting / Friendly Url generation */ + namespace DotNetNuke.Entities.Urls { + using System.Collections.Generic; + /// - /// The StringLengthComparer class is a comparer override used for sorting portal aliases by length + /// The StringLengthComparer class is a comparer override used for sorting portal aliases by length. /// internal class StringLengthComparer : Comparer { @@ -23,27 +18,33 @@ public override int Compare(string x, string y) { return 0; } + if (x == null) { return -1; } + if (y == null) { return 1; } + if (x.Length < y.Length) { return -1; } + if (x.Length > y.Length) { return 1; } + if (x.Length == y.Length) { return 0; } - return -1; //should never reach here + + return -1; // should never reach here } } } diff --git a/DNN Platform/Library/Entities/Urls/TabIndexController.cs b/DNN Platform/Library/Entities/Urls/TabIndexController.cs index fc2553beb55..cdb5fc9b2a8 100644 --- a/DNN Platform/Library/Entities/Urls/TabIndexController.cs +++ b/DNN Platform/Library/Entities/Urls/TabIndexController.cs @@ -1,256 +1,324 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Log.EventLog; + internal static class TabIndexController { - private static readonly object tabPathDictBuildLock = new object(); - - #region Private Methods - - private static void AddCustomRedirectsToDictionary(SharedDictionary tabIndex, - Dictionary dupCheck, - string httpAlias, - TabInfo tab, - FriendlyUrlSettings settings, - FriendlyUrlOptions options, - ref string rewritePath, - out int tabPathDepth, - ref List customHttpAliasesUsed, - bool isDeleted, - Guid parentTraceId) + private static readonly object tabPathDictBuildLock = new object(); + + public static void InvalidateDictionary(string reason, PageIndexData rebuildData, int portalId) + { + // if supplied, store the rebuildData for when the dictionary gets rebuilt + // this is a way of storing data between dictionary rebuilds + if (rebuildData != null) + { + DataCache.SetCache("rebuildData", rebuildData); + } + + // add log entry for cache clearance + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + try + { + // 817 : not clearing items correctly from dictionary + CacheController.FlushPageIndexFromCache(); + } + catch (Exception ex) + { + // do nothing ; can be from trying to access cache after system restart + Services.Exceptions.Exceptions.LogException(ex); + } + + log.AddProperty("Url Rewriting Caching Message", "Page Index Cache Cleared. Reason: " + reason); + log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); + LogController.Instance.AddLog(log); + } + + internal static string CreateRewritePath(int tabId, string cultureCode, params string[] keyValuePair) + { + string rewritePath = "?TabId=" + tabId.ToString(); + + // 736 : 5.5 compatibility - identify tab rewriting at source by tab culture code + RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, cultureCode); + return keyValuePair.Aggregate(rewritePath, (current, keyValue) => current + ("&" + keyValue)); + } + + internal static string CreateRewritePath(int tabId, string cultureCode, ActionType action, RedirectReason reason) + { + string rewritePath = CreateRewritePath(tabId, cultureCode); + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, action, reason); + return rewritePath; + } + + private static void AddCustomRedirectsToDictionary( + SharedDictionary tabIndex, + Dictionary dupCheck, + string httpAlias, + TabInfo tab, + FriendlyUrlSettings settings, + FriendlyUrlOptions options, + ref string rewritePath, + out int tabPathDepth, + ref List customHttpAliasesUsed, + bool isDeleted, + Guid parentTraceId) { tabPathDepth = 1; var duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabRedirected; bool checkForDupUrls = settings.CheckForDuplicateUrls; - //697 : custom url rewrites with large number of path depths fail because of incorrect path depth calculation + + // 697 : custom url rewrites with large number of path depths fail because of incorrect path depth calculation int maxTabPathDepth = 1; string origRewritePath = rewritePath; string newRewritePath = rewritePath; string aliasCulture = null; - //get the culture for this alias + + // get the culture for this alias var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID).ToList(); if (primaryAliases.Count > 0) { aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(tab.PortalID, httpAlias); } + foreach (var redirect in tab.TabUrls) { rewritePath = origRewritePath; - //allow for additional qs parameters - if (!String.IsNullOrEmpty(redirect.QueryString)) + + // allow for additional qs parameters + if (!string.IsNullOrEmpty(redirect.QueryString)) { - rewritePath += (redirect.QueryString.StartsWith("&")) ? redirect.QueryString : "&" + redirect.QueryString; + rewritePath += redirect.QueryString.StartsWith("&") ? redirect.QueryString : "&" + redirect.QueryString; } string redirectTabPath = redirect.Url; string redirectedRewritePath = rewritePath; - //770 : allow for custom portal aliases + // 770 : allow for custom portal aliases string redirectAlias = httpAlias; if (redirect.PortalAliasId > 0) { - //has a custom portal alias + // has a custom portal alias PortalAliasInfo customAlias = PortalAliasController.Instance.GetPortalAliasByPortalAliasID(redirect.PortalAliasId); if (customAlias != null) { - //this will be used to add the Url to the dictionary + // this will be used to add the Url to the dictionary redirectAlias = customAlias.HTTPAlias; - //add to the list of custom aliases used by the portal + + // add to the list of custom aliases used by the portal if (customHttpAliasesUsed == null) { customHttpAliasesUsed = new List(); } + if (!customHttpAliasesUsed.Contains(redirectAlias)) { customHttpAliasesUsed.Add(redirectAlias); } } } - //set the redirect status using the httpStatus + + // set the redirect status using the httpStatus switch (redirect.HttpStatus) { case "301": - redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.Redirect301, - RedirectReason.Custom_Redirect); + redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Redirect301, + RedirectReason.Custom_Redirect); break; case "302": - redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.Redirect302, - RedirectReason.Custom_Redirect); + redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Redirect302, + RedirectReason.Custom_Redirect); break; case "404": - redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.Output404, - RedirectReason.Custom_Redirect); + redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Output404, + RedirectReason.Custom_Redirect); break; case "200": - //when there is a 200, then replace the 'standard' path - newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(newRewritePath, - ActionType.CheckFor301, - RedirectReason.Custom_Redirect); - //672 : replacement urls have preference over all redirects, deleted tabs and standard urls + // when there is a 200, then replace the 'standard' path + newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + newRewritePath, + ActionType.CheckFor301, + RedirectReason.Custom_Redirect); + + // 672 : replacement urls have preference over all redirects, deleted tabs and standard urls duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabOK; break; } - //check the culture of the redirect to see if it either doesn't match the alias or needs to specify - //the language when requested - if (!String.IsNullOrEmpty(redirect.CultureCode) && redirect.CultureCode != "Default") + + // check the culture of the redirect to see if it either doesn't match the alias or needs to specify + // the language when requested + if (!string.IsNullOrEmpty(redirect.CultureCode) && redirect.CultureCode != "Default") { - //806 : specify duplicates where the alias culture doesn't match the redirect culture - //so that redirect to the best match between alias culture and redirect culture - //compare the supplied alias culture with the redirect culture - //856 : if alias culture == "" and a custom 301 redirect then redirects are forced + // 806 : specify duplicates where the alias culture doesn't match the redirect culture + // so that redirect to the best match between alias culture and redirect culture + // compare the supplied alias culture with the redirect culture + // 856 : if alias culture == "" and a custom 301 redirect then redirects are forced if (!string.IsNullOrEmpty(aliasCulture) && aliasCulture != redirect.CultureCode) { - //the culture code and the specific culture alias don't match - //set 301 check status and set to delete if a duplicate is found + // the culture code and the specific culture alias don't match + // set 301 check status and set to delete if a duplicate is found redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( redirectedRewritePath, ActionType.CheckFor301, RedirectReason.Custom_Redirect); - newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(newRewritePath, - ActionType.CheckFor301, - RedirectReason.Custom_Redirect); + newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + newRewritePath, + ActionType.CheckFor301, + RedirectReason.Custom_Redirect); duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabRedirected; } - //add on the culture code for the redirect, so that the rewrite silently sets the culture for the page + + // add on the culture code for the redirect, so that the rewrite silently sets the culture for the page RewriteController.AddLanguageCodeToRewritePath(ref redirectedRewritePath, redirect.CultureCode); } - //now add the custom redirect to the tab dictionary - if (String.Compare(httpAlias, redirectAlias, StringComparison.OrdinalIgnoreCase) == 0) + + // now add the custom redirect to the tab dictionary + if (string.Compare(httpAlias, redirectAlias, StringComparison.OrdinalIgnoreCase) == 0) { - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - redirectTabPath, - redirectedRewritePath, - tab.TabID, - duplicateHandlingPreference, - ref tabPathDepth, - checkForDupUrls, - isDeleted); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + redirectTabPath, + redirectedRewritePath, + tab.TabID, + duplicateHandlingPreference, + ref tabPathDepth, + checkForDupUrls, + isDeleted); } else { - //770 : there is a specific alias for this tab - //if not a redirect already, make it a redirect for the wrong (original) rewrite path - string wrongAliasRedirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(redirectedRewritePath, - ActionType.Redirect301, - RedirectReason.Custom_Tab_Alias); - //add in the entry with the specific redirectAlias - if (redirectTabPath == "") + // 770 : there is a specific alias for this tab + // if not a redirect already, make it a redirect for the wrong (original) rewrite path + string wrongAliasRedirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + redirectedRewritePath, + ActionType.Redirect301, + RedirectReason.Custom_Tab_Alias); + + // add in the entry with the specific redirectAlias + if (redirectTabPath == string.Empty) { - //when adding a blank custom Url, also add in a standard tab path url, because any url that also includes querystring data will use the standard tab path + // when adding a blank custom Url, also add in a standard tab path url, because any url that also includes querystring data will use the standard tab path string tabPath = GetTabPath(tab, options, parentTraceId); - string stdDictRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.CheckFor301, - RedirectReason.Custom_Tab_Alias); - AddToTabDict(tabIndex, - dupCheck, - redirectAlias, - tabPath, - stdDictRewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabOK, - ref tabPathDepth, - checkForDupUrls, - isDeleted); - //then add in the portal alias with no tabpath (ie like a site root url) - AddToTabDict(tabIndex, - dupCheck, - redirectAlias, - redirectTabPath, - redirectedRewritePath, - tab.TabID, - duplicateHandlingPreference, - ref tabPathDepth, - checkForDupUrls, - isDeleted); - //838 : disabled tabs with custom aliases - still load the settings page without redirect - //disabled / not active by date / external url pages cannot navigate to settings page + string stdDictRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.CheckFor301, + RedirectReason.Custom_Tab_Alias); + AddToTabDict( + tabIndex, + dupCheck, + redirectAlias, + tabPath, + stdDictRewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabOK, + ref tabPathDepth, + checkForDupUrls, + isDeleted); + + // then add in the portal alias with no tabpath (ie like a site root url) + AddToTabDict( + tabIndex, + dupCheck, + redirectAlias, + redirectTabPath, + redirectedRewritePath, + tab.TabID, + duplicateHandlingPreference, + ref tabPathDepth, + checkForDupUrls, + isDeleted); + + // 838 : disabled tabs with custom aliases - still load the settings page without redirect + // disabled / not active by date / external url pages cannot navigate to settings page if (tab.DisableLink || !string.IsNullOrEmpty(tab.Url) || (tab.EndDate < DateTime.Now && tab.EndDate > DateTime.MinValue) || (tab.StartDate > DateTime.Now && tab.StartDate > DateTime.MinValue)) { string settingsUrl = tabPath + "/ctl/Tab"; string settingsRewritePath = CreateRewritePath(tab.TabID, redirect.CultureCode, "ctl=Tab"); - //no redirect on the ctl/Tab url - //add in the ctl/tab Url for the custom alias, with no redirect so that the page settings can be loaded - AddToTabDict(tabIndex, - dupCheck, - redirectAlias, - settingsUrl, - settingsRewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + + // no redirect on the ctl/Tab url + // add in the ctl/tab Url for the custom alias, with no redirect so that the page settings can be loaded + AddToTabDict( + tabIndex, + dupCheck, + redirectAlias, + settingsUrl, + settingsRewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } } else { - //add in custom entry with different alias - AddToTabDict(tabIndex, - dupCheck, - redirectAlias, - redirectTabPath, - redirectedRewritePath, - tab.TabID, - duplicateHandlingPreference, - ref tabPathDepth, - checkForDupUrls, - isDeleted); - //add in the entry with the original alias, plus an instruction to redirect if it's used - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - redirectTabPath, - wrongAliasRedirectedRewritePath, - tab.TabID, - duplicateHandlingPreference, - ref tabPathDepth, - checkForDupUrls, - isDeleted); + // add in custom entry with different alias + AddToTabDict( + tabIndex, + dupCheck, + redirectAlias, + redirectTabPath, + redirectedRewritePath, + tab.TabID, + duplicateHandlingPreference, + ref tabPathDepth, + checkForDupUrls, + isDeleted); + + // add in the entry with the original alias, plus an instruction to redirect if it's used + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + redirectTabPath, + wrongAliasRedirectedRewritePath, + tab.TabID, + duplicateHandlingPreference, + ref tabPathDepth, + checkForDupUrls, + isDeleted); } } + if (tabPathDepth > maxTabPathDepth) { maxTabPathDepth = tabPathDepth; } } - //return the highest tabpath depth found + + // return the highest tabpath depth found tabPathDepth = maxTabPathDepth; - //return any changes to the rewritePath + + // return any changes to the rewritePath rewritePath = newRewritePath; } - - + private static void AddInternalAliases(FriendlyUrlSettings settings, List usingHttpAliases) { if (settings.InternalAliasList != null && settings.InternalAliasList.Count > 0) @@ -265,102 +333,113 @@ private static void AddInternalAliases(FriendlyUrlSettings settings, List tabIndex, - Dictionary dupCheck, - string httpAlias, - TabInfo tab, - string tabPath, - ref string rewritePath, - ref int tabPathDepth, - bool checkForDupUrls, - bool isDeleted) + private static void AddPermanentRedirectToDictionary( + SharedDictionary tabIndex, + Dictionary dupCheck, + string httpAlias, + TabInfo tab, + string tabPath, + ref string rewritePath, + ref int tabPathDepth, + bool checkForDupUrls, + bool isDeleted) { - //because we have to catch all versions of this in the dictionary, then we have to add the 'base' url - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tab.TabPath + "/tabid/" + tab.TabID + "/default", - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - checkForDupUrls, - isDeleted); - //and put in the name-less one as well, just in case a prior version of the site was runnign without the tabnames (urlformat=sefriendly) - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - "/tabid/" + tab.TabID + "/default", - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - checkForDupUrls, - isDeleted); - //finally, put one in for the ctl/tab combination, so that you can actually get to the page settings - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tabPath.Replace("//", "/") + "/ctl/Tab", - CreateRewritePath(tab.TabID, "", "ctl=Tab"), - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - checkForDupUrls, - isDeleted); + // because we have to catch all versions of this in the dictionary, then we have to add the 'base' url + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tab.TabPath + "/tabid/" + tab.TabID + "/default", + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + checkForDupUrls, + isDeleted); + + // and put in the name-less one as well, just in case a prior version of the site was runnign without the tabnames (urlformat=sefriendly) + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + "/tabid/" + tab.TabID + "/default", + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + checkForDupUrls, + isDeleted); + + // finally, put one in for the ctl/tab combination, so that you can actually get to the page settings + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tabPath.Replace("//", "/") + "/ctl/Tab", + CreateRewritePath(tab.TabID, string.Empty, "ctl=Tab"), + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + checkForDupUrls, + isDeleted); } - private static void AddSiteRootRedirects(PathSizes pathSizes, - SharedDictionary tabIndex, - IEnumerable chosenAliases, - bool hasSiteRootRedirect, - Dictionary dupCheck, - ICollection usingHttpAliases) + private static void AddSiteRootRedirects( + PathSizes pathSizes, + SharedDictionary tabIndex, + IEnumerable chosenAliases, + bool hasSiteRootRedirect, + Dictionary dupCheck, + ICollection usingHttpAliases) { - foreach (PortalAliasInfo alias in chosenAliases) //and that is once per portal alias per portal + foreach (PortalAliasInfo alias in chosenAliases) // and that is once per portal alias per portal { string httpAlias = alias.HTTPAlias; - //check to see if there is a parameter rewrite rule that allows for parameters on the site root + // check to see if there is a parameter rewrite rule that allows for parameters on the site root if (hasSiteRootRedirect) { int tempPathDepth = 0; - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - "*", - "", - -1, - UrlEnums.TabKeyPreference.TabOK, - ref tempPathDepth, - false, - false); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + "*", + string.Empty, + -1, + UrlEnums.TabKeyPreference.TabOK, + ref tempPathDepth, + false, + false); } pathSizes.SetAliasDepth(httpAlias); - //keep track of the http Aliases, this will be used to feed into the tab dictionary (ie, one alias per tab) + // keep track of the http Aliases, this will be used to feed into the tab dictionary (ie, one alias per tab) usingHttpAliases.Add(httpAlias.ToLowerInvariant()); } } - private static void AddStandardPagesToDict(SharedDictionary tabIndex, - Dictionary dupCheck, - string httpAlias, - int portalId, - string cultureCode) + private static void AddStandardPagesToDict( + SharedDictionary tabIndex, + Dictionary dupCheck, + string httpAlias, + int portalId, + string cultureCode) { - int tabDepth = 0; //we ignore tab depth as it is only one for these in-built urls - //850 : add in the culture code to the redirect if supplied + int tabDepth = 0; // we ignore tab depth as it is only one for these in-built urls + + // 850 : add in the culture code to the redirect if supplied string portalRewritePath = "?PortalId=" + portalId.ToString(); - string cultureRewritePath = ""; + string cultureRewritePath = string.Empty; if (!string.IsNullOrEmpty(cultureCode)) { cultureRewritePath += "&language=" + cultureCode; } - //hard coded page paths - using 'tabDeleted' in case there is a clash with an existing page (ie, someone has created a page that takes place of the standard page, created page has preference) - - //need check custom login/register page set in portal and redirect to the specific page. + + // hard coded page paths - using 'tabDeleted' in case there is a clash with an existing page (ie, someone has created a page that takes place of the standard page, created page has preference) + + // need check custom login/register page set in portal and redirect to the specific page. var portal = PortalController.Instance.GetPortal(portalId); var loginRewritePath = portalRewritePath + "&ctl=Login" + cultureRewritePath; var loginPreference = UrlEnums.TabKeyPreference.TabDeleted; @@ -371,16 +450,18 @@ private static void AddStandardPagesToDict(SharedDictionary tabI loginPreference = UrlEnums.TabKeyPreference.TabOK; loginRewritePath = CreateRewritePath(loginTabId, cultureCode); } - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - "login", - loginRewritePath, - loginTabId, - loginPreference, - ref tabDepth, - false, - false); + + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + "login", + loginRewritePath, + loginTabId, + loginPreference, + ref tabDepth, + false, + false); var registerRewritePath = portalRewritePath + "&ctl=Register" + cultureRewritePath; var registerPreference = UrlEnums.TabKeyPreference.TabDeleted; @@ -391,17 +472,20 @@ private static void AddStandardPagesToDict(SharedDictionary tabI registerPreference = UrlEnums.TabKeyPreference.TabOK; registerRewritePath = CreateRewritePath(registerTabId, cultureCode); } - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - "register", - registerRewritePath, - registerTabId, - registerPreference, - ref tabDepth, - false, - false); - AddToTabDict(tabIndex, + + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + "register", + registerRewritePath, + registerTabId, + registerPreference, + ref tabDepth, + false, + false); + AddToTabDict( + tabIndex, dupCheck, httpAlias, "logoff", @@ -411,66 +495,72 @@ private static void AddStandardPagesToDict(SharedDictionary tabI ref tabDepth, false, false); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - "terms", - portalRewritePath + "&ctl=Terms" + cultureRewritePath, - -1, - UrlEnums.TabKeyPreference.TabDeleted, - ref tabDepth, - false, - false); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - "privacy", - portalRewritePath + "&ctl=Privacy" + cultureRewritePath, - -1, - UrlEnums.TabKeyPreference.TabDeleted, - ref tabDepth, - false, - false); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + "terms", + portalRewritePath + "&ctl=Terms" + cultureRewritePath, + -1, + UrlEnums.TabKeyPreference.TabDeleted, + ref tabDepth, + false, + false); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + "privacy", + portalRewritePath + "&ctl=Privacy" + cultureRewritePath, + -1, + UrlEnums.TabKeyPreference.TabDeleted, + ref tabDepth, + false, + false); } - private static int AddTabToTabDict(SharedDictionary tabIndex, - Dictionary dupCheck, - string httpAlias, - string aliasCulture, - string customHttpAlias, - PortalInfo thisPortal, - string tabPath, - ref List customAliasesUsed, - TabInfo tab, - FriendlyUrlSettings settings, - FriendlyUrlOptions options, - int homeTabId, - ref Hashtable homePageSkins, - Guid parentTraceId) + private static int AddTabToTabDict( + SharedDictionary tabIndex, + Dictionary dupCheck, + string httpAlias, + string aliasCulture, + string customHttpAlias, + PortalInfo thisPortal, + string tabPath, + ref List customAliasesUsed, + TabInfo tab, + FriendlyUrlSettings settings, + FriendlyUrlOptions options, + int homeTabId, + ref Hashtable homePageSkins, + Guid parentTraceId) { - string rewritePath = ""; + string rewritePath = string.Empty; int tabPathDepth = 0; - bool customAliasUsedAndNotCurrent = !String.IsNullOrEmpty(customHttpAlias) && customHttpAlias != httpAlias; + bool customAliasUsedAndNotCurrent = !string.IsNullOrEmpty(customHttpAlias) && customHttpAlias != httpAlias; - //592 : check the permanent redirect value - //736 : 5.5 changes : track tab culture code + // 592 : check the permanent redirect value + // 736 : 5.5 changes : track tab culture code string cultureCode = tab.CultureCode; - if (String.IsNullOrEmpty(cultureCode)) + if (string.IsNullOrEmpty(cultureCode)) { cultureCode = aliasCulture; } + bool permanentRedirect = tab.PermanentRedirect; - //determine the rewrite parameter - //for deleted or pages not enabled yet, direct to the home page if the setting is enabled - //534 : tab is disabled, mark as deleted (don't want to cause duplicate tab warnings) - //DNN-6186: add expired pages in dictionary as admin/host user should able to visit/edit them. - bool isDeleted = (tab.IsDeleted || tab.DisableLink); + + // determine the rewrite parameter + // for deleted or pages not enabled yet, direct to the home page if the setting is enabled + // 534 : tab is disabled, mark as deleted (don't want to cause duplicate tab warnings) + // DNN-6186: add expired pages in dictionary as admin/host user should able to visit/edit them. + bool isDeleted = tab.IsDeleted || tab.DisableLink; if (isDeleted) - // don't care what setting is, redirect code will decide whether to redirect or 404 - just mark as page deleted && + + // don't care what setting is, redirect code will decide whether to redirect or 404 - just mark as page deleted && // settings.DeletedTabHandlingValue == DeletedTabHandlingTypes.Do301RedirectToPortalHome) { - //777: force 404 result for all deleted pages instead of relying on 'not found' - //838 : separate handling for disabled pages + // 777: force 404 result for all deleted pages instead of relying on 'not found' + // 838 : separate handling for disabled pages ActionType action = settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error ? ActionType.Output404 : ActionType.Redirect301; @@ -480,18 +570,19 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, } else { - //for all other pages, rewrite to the correct tabId for that page - //592 : new permanentRedirect value + // for all other pages, rewrite to the correct tabId for that page + // 592 : new permanentRedirect value if (permanentRedirect) { - rewritePath = CreateRewritePath(tab.TabID, - cultureCode, - ActionType.Redirect301, - RedirectReason.Tab_Permanent_Redirect); + rewritePath = CreateRewritePath( + tab.TabID, + cultureCode, + ActionType.Redirect301, + RedirectReason.Tab_Permanent_Redirect); } else { - //852 : skin per alias at tab level - if specified + // 852 : skin per alias at tab level - if specified if (tab.AliasSkins != null && tab.AliasSkins.ContainsAlias(httpAlias)) { TabAliasSkinInfo tas = tab.AliasSkins.FindByHttpAlias(httpAlias); @@ -500,11 +591,11 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, string skinSrc = tas.SkinSrc; if (!string.IsNullOrEmpty(skinSrc)) { - //add skin src into rewrite path + // add skin src into rewrite path rewritePath = CreateRewritePath(tab.TabID, cultureCode, "skinSrc=" + skinSrc); } - //now add to the home page skin hashtable if it's the home page. + // now add to the home page skin hashtable if it's the home page. if (homeTabId == tab.TabID) { string key = httpAlias + "::" + cultureCode; @@ -513,6 +604,7 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, { homePageSkins.Add(key, skinSrc); } + if (homePageSkins.ContainsKey(key2) == false) { homePageSkins.Add(key2, skinSrc); @@ -528,35 +620,40 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, if (thisPortal != null && (thisPortal.UserTabId == tab.TabID || thisPortal.UserTabId == tab.ParentId || thisPortal.UserTabId == -1)) { - //user profile action specified. If tabid match for this tab, add a do301 check because we want to make - //sure that the trimmed Url is used when appropriate - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.CheckFor301, - RedirectReason.User_Profile_Url); + // user profile action specified. If tabid match for this tab, add a do301 check because we want to make + // sure that the trimmed Url is used when appropriate + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.CheckFor301, + RedirectReason.User_Profile_Url); } } if (tabPath.Replace("//", "/") != tab.TabPath.Replace("//", "/")) { - //when the generated tab path is different to the standard tab path, character substituion has happened - //this entry is going to have space substitution in it, so it is added into the dictionary with a delete notification and a 301 replaced - //this entry is the 'original' (spaces removed) version ie mypage + // when the generated tab path is different to the standard tab path, character substituion has happened + // this entry is going to have space substitution in it, so it is added into the dictionary with a delete notification and a 301 replaced + // this entry is the 'original' (spaces removed) version ie mypage string substituteRewritePath = rewritePath; if (!isDeleted) - //if it is deleted, we don't care if the spaces were replaced, or anything else, just take care in deleted handling + + // if it is deleted, we don't care if the spaces were replaced, or anything else, just take care in deleted handling { - string replaceSpaceWith = String.Empty; + string replaceSpaceWith = string.Empty; if (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) { replaceSpaceWith = settings.ReplaceSpaceWith; } - substituteRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(substituteRewritePath, - ActionType.Redirect301, - tabPath.Contains(replaceSpaceWith) + + substituteRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + substituteRewritePath, + ActionType.Redirect301, + tabPath.Contains(replaceSpaceWith) ? RedirectReason.Spaces_Replaced : RedirectReason.Custom_Redirect); } - //the preference variable determines what to do if a duplicate tab is found already in the dictionary + + // the preference variable determines what to do if a duplicate tab is found already in the dictionary var preference = UrlEnums.TabKeyPreference.TabRedirected; if (isDeleted) { @@ -564,31 +661,34 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, // are redirected but not deleted should take preference preference = UrlEnums.TabKeyPreference.TabDeleted; } - //Note ; if anything else is wrong with this url, (ie, wrong alias) then that will be corrected in a redirect - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tab.TabPath, - substituteRewritePath, - tab.TabID, - preference, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + + // Note ; if anything else is wrong with this url, (ie, wrong alias) then that will be corrected in a redirect + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tab.TabPath, + substituteRewritePath, + tab.TabID, + preference, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } - //check for permanent redirects as specified in the core dnn permanent redirect property + // check for permanent redirects as specified in the core dnn permanent redirect property if (permanentRedirect) { - AddPermanentRedirectToDictionary(tabIndex, - dupCheck, - httpAlias, - tab, - tabPath, - ref rewritePath, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + AddPermanentRedirectToDictionary( + tabIndex, + dupCheck, + httpAlias, + tab, + tabPath, + ref rewritePath, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } // disabled / not active by date / external url pages cannot navigate to settings page @@ -597,36 +697,38 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, (tab.StartDate > DateTime.Now && tab.StartDate > DateTime.MinValue)) { string settingsUrl = tabPath.Replace("//", "/") + "/ctl/Tab"; - string settingsRewritePath = CreateRewritePath(tab.TabID, "", "ctl=tab"); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - settingsUrl, - settingsRewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + string settingsRewritePath = CreateRewritePath(tab.TabID, string.Empty, "ctl=tab"); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + settingsUrl, + settingsRewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } - //777: every tab is added to the dictionary, including those that are deleted - - //inspect the optional tab redirects and add them as well, keeping track if any are '200' status, meaning the standard Url will be 301, if replaced unfriendly is switched on - //589 : tab with custom 200 redirects not changing base url to 301 statusa - AddCustomRedirectsToDictionary(tabIndex, - dupCheck, - httpAlias, - tab, - settings, - options, - ref rewritePath, - out tabPathDepth, - ref customAliasesUsed, - isDeleted, - parentTraceId); - - //if auto ascii conversion is on, do that as well + // 777: every tab is added to the dictionary, including those that are deleted + + // inspect the optional tab redirects and add them as well, keeping track if any are '200' status, meaning the standard Url will be 301, if replaced unfriendly is switched on + // 589 : tab with custom 200 redirects not changing base url to 301 statusa + AddCustomRedirectsToDictionary( + tabIndex, + dupCheck, + httpAlias, + tab, + settings, + options, + ref rewritePath, + out tabPathDepth, + ref customAliasesUsed, + isDeleted, + parentTraceId); + + // if auto ascii conversion is on, do that as well if (settings.AutoAsciiConvert) { bool replacedDiacritic; @@ -637,100 +739,110 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, RedirectTokens.GetActionFromRewritePath(rewritePath, out existingAction); if (settings.RedirectUnfriendly && existingAction != ActionType.Redirect301) { - //add in a tab path, with 301, for the version with the diacritics in - string diacriticRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.Redirect301, - RedirectReason.Diacritic_Characters); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tabPath, - diacriticRewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabOK, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + // add in a tab path, with 301, for the version with the diacritics in + string diacriticRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Redirect301, + RedirectReason.Diacritic_Characters); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tabPath, + diacriticRewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabOK, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } else { - //add in the standard version so that the page responds to both the diacritic version - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tabPath, - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabOK, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + // add in the standard version so that the page responds to both the diacritic version + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tabPath, + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabOK, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } } - tabPath = asciiTabPath; //switch tabpath to new, ascii-converted version for rest of processing + + tabPath = asciiTabPath; // switch tabpath to new, ascii-converted version for rest of processing } - //add the 'standard' Url in + // add the 'standard' Url in if (tab.TabID == homeTabId && settings.RedirectUnfriendly) { - //home page shoudl be redirected back to the site root - //899: check for redirect on home page - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.CheckFor301, - RedirectReason.Site_Root_Home); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tabPath, - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabOK, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + // home page shoudl be redirected back to the site root + // 899: check for redirect on home page + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.CheckFor301, + RedirectReason.Site_Root_Home); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tabPath, + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabOK, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } else { if (customAliasUsedAndNotCurrent && settings.RedirectUnfriendly) { - //add in the standard page, but it's a redirect to the customAlias - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.Redirect301, - RedirectReason.Custom_Tab_Alias); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tabPath, - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + // add in the standard page, but it's a redirect to the customAlias + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Redirect301, + RedirectReason.Custom_Tab_Alias); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tabPath, + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } else { if (customAliasUsedAndNotCurrent && settings.RedirectUnfriendly) { - //add in the standard page, but it's a redirect to the customAlias - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, - ActionType.Redirect301, - RedirectReason.Custom_Tab_Alias); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tabPath, - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + // add in the standard page, but it's a redirect to the customAlias + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Redirect301, + RedirectReason.Custom_Tab_Alias); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tabPath, + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } else { - //add in the standard page to the dictionary - //931 : don't replace existing custom url if this is a redirect or a check for redirect + // add in the standard page to the dictionary + // 931 : don't replace existing custom url if this is a redirect or a check for redirect ActionType action; var dupCheckPreference = UrlEnums.TabKeyPreference.TabOK; RedirectTokens.GetActionFromRewritePath(rewritePath, out action); @@ -738,119 +850,131 @@ private static int AddTabToTabDict(SharedDictionary tabIndex, { dupCheckPreference = UrlEnums.TabKeyPreference.TabRedirected; } - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tabPath, - rewritePath, - tab.TabID, - dupCheckPreference, - ref tabPathDepth, - settings.CheckForDuplicateUrls, - isDeleted); + + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tabPath, + rewritePath, + tab.TabID, + dupCheckPreference, + ref tabPathDepth, + settings.CheckForDuplicateUrls, + isDeleted); } } } + return tabPathDepth; } - private static void AddToTabDict(SharedDictionary tabIndex, - Dictionary dupCheckDict, - string httpAlias, - string tabPath, - string rewrittenPath, - int tabId, - UrlEnums.TabKeyPreference keyDupAction, - ref int tabPathDepth, - bool checkForDupUrls, - bool isDeleted) + private static void AddToTabDict( + SharedDictionary tabIndex, + Dictionary dupCheckDict, + string httpAlias, + string tabPath, + string rewrittenPath, + int tabId, + UrlEnums.TabKeyPreference keyDupAction, + ref int tabPathDepth, + bool checkForDupUrls, + bool isDeleted) { - //remove leading '/' and convert to lower for all keys + // remove leading '/' and convert to lower for all keys string tabPathSimple = tabPath.Replace("//", "/").ToLowerInvariant(); - //the tabpath depth is only set if it's higher than the running highest tab path depth - int thisTabPathDepth = tabPathSimple.Length - tabPathSimple.Replace("/", "").Length; + + // the tabpath depth is only set if it's higher than the running highest tab path depth + int thisTabPathDepth = tabPathSimple.Length - tabPathSimple.Replace("/", string.Empty).Length; if (thisTabPathDepth > tabPathDepth) { tabPathDepth = thisTabPathDepth; } - if ((tabPathSimple.Length > 0 && tabPathSimple[0] == '/')) + + if (tabPathSimple.Length > 0 && tabPathSimple[0] == '/') { tabPathSimple = tabPathSimple.Substring(1); } - //Contruct the tab key for the dictionary. Using :: allows for separation of portal alias and tab path. + // Contruct the tab key for the dictionary. Using :: allows for separation of portal alias and tab path. string tabKey = (httpAlias + "::" + tabPathSimple).ToLowerInvariant(); - //construct the duplicate key check + // construct the duplicate key check string dupKey = (httpAlias + "/" + tabPathSimple).ToLowerInvariant(); if (dupKey[dupKey.Length - 1] != '/') { dupKey += "/"; } - //now make sure there is NEVER a duplicate key exception by testing for existence first + // now make sure there is NEVER a duplicate key exception by testing for existence first using (tabIndex.GetWriteLock()) { if (tabIndex.ContainsKey(tabKey)) { - //it's possible for a tab to be deleted and the tab path repeated. - //the dictionary must be checked to ascertain whether the existing tab - //should be replaced or not. If the action is 'TabOK' it means - //replace the entry regardless. If the action is 'TabRedirected' it means - //replace the existing dictionary ONLY if the existing dictionary entry is a - //deleted tab. - bool replaceTab = (keyDupAction == UrlEnums.TabKeyPreference.TabOK); //default, replace the tab + // it's possible for a tab to be deleted and the tab path repeated. + // the dictionary must be checked to ascertain whether the existing tab + // should be replaced or not. If the action is 'TabOK' it means + // replace the entry regardless. If the action is 'TabRedirected' it means + // replace the existing dictionary ONLY if the existing dictionary entry is a + // deleted tab. + bool replaceTab = keyDupAction == UrlEnums.TabKeyPreference.TabOK; // default, replace the tab if (replaceTab == false) { - //ok, the tab to be added is either a redirected or deleted tab - //get the existing entry - //775 : don't assume that the duplicate check dictionary has the key + // ok, the tab to be added is either a redirected or deleted tab + // get the existing entry + // 775 : don't assume that the duplicate check dictionary has the key if (dupCheckDict.ContainsKey(dupKey)) { DupKeyCheck foundTab = dupCheckDict[dupKey]; - //a redirected tab will replace a deleted tab + + // a redirected tab will replace a deleted tab if (foundTab.IsDeleted && keyDupAction == UrlEnums.TabKeyPreference.TabRedirected) { replaceTab = true; } + if (foundTab.TabIdOriginal == "-1") { replaceTab = true; } } } - if (replaceTab && !isDeleted) //don't replace if the incoming tab is deleted + + if (replaceTab && !isDeleted) // don't replace if the incoming tab is deleted { - //remove the previous one + // remove the previous one tabIndex.Remove(tabKey); - //add the new one + + // add the new one tabIndex.Add(tabKey, Globals.glbDefaultPage + rewrittenPath); } } else { - //just add the tabkey into the dictionary + // just add the tabkey into the dictionary tabIndex.Add(tabKey, Globals.glbDefaultPage + rewrittenPath); } } - //checking for duplicates means throwing an exception when one is found, but this is just logged to the event log + // checking for duplicates means throwing an exception when one is found, but this is just logged to the event log if (dupCheckDict.ContainsKey(dupKey)) { DupKeyCheck foundTAb = dupCheckDict[dupKey]; - if ((foundTAb.IsDeleted == false && isDeleted == false) //found is not deleted, this tab is not deleted + if ((foundTAb.IsDeleted == false && isDeleted == false) // found is not deleted, this tab is not deleted && keyDupAction == UrlEnums.TabKeyPreference.TabOK && foundTAb.TabIdOriginal != "-1") - //-1 tabs are login, register, privacy etc + + // -1 tabs are login, register, privacy etc { - //check whether to log for this or not + // check whether to log for this or not if (checkForDupUrls && foundTAb.TabIdOriginal != tabId.ToString()) - //dont' show message for where same tab is being added twice) + + // dont' show message for where same tab is being added twice) { - //there is a naming conflict where this alias/tab path could be mistaken + // there is a naming conflict where this alias/tab path could be mistaken int tabIdOriginal; - string tab1Name = "", tab2Name = ""; - var dupInSameCulture = false; + string tab1Name = string.Empty, tab2Name = string.Empty; + var dupInSameCulture = false; if (int.TryParse(foundTAb.TabIdOriginal, out tabIdOriginal)) { Dictionary portalDic = PortalController.GetPortalDictionary(); @@ -866,74 +990,79 @@ private static void AddToTabDict(SharedDictionary tabIndex, { tab1Name = tab1.TabName + " [" + tab1.TabPath + "]"; } + if (tab2 != null) { tab2Name = tab2.TabName + " [" + tab2.TabPath + "]"; } - if (tab1 != null && tab2 != null) - { - dupInSameCulture = !PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalId, false) - || tab1.CultureCode == tab2.CultureCode; - } + if (tab1 != null && tab2 != null) + { + dupInSameCulture = !PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalId, false) + || tab1.CultureCode == tab2.CultureCode; + } + } + + if (dupInSameCulture) + { + string msg = "Page naming conflict. Url of (" + foundTAb.TabPath + + ") resolves to two separate pages (" + tab1Name + " [tabid = " + + foundTAb.TabIdOriginal + "], " + tab2Name + " [tabid = " + tabId.ToString() + + "]). Only the second page will be shown for the url."; + const string msg2 = + "PLEASE NOTE : this is an information message only, this message does not affect site operations in any way."; + + // 771 : change to admin alert instead of exception + // log a host alert + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + log.AddProperty("Advanced Friendly URL Provider Duplicate URL Warning", "Page Naming Conflict"); + log.AddProperty("Duplicate Page Details", msg); + log.AddProperty("Warning Information", msg2); + log.AddProperty("Suggested Action", "Rename one or both of the pages to ensure a unique URL"); + log.AddProperty( + "Hide this message", + "To stop this message from appearing in the log, uncheck the option for 'Produce an Exception in the Site Log if two pages have the same name/path?' in the Advanced Url Rewriting settings."); + log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); + LogController.Instance.AddLog(log); } - - - if (dupInSameCulture) - { - string msg = "Page naming conflict. Url of (" + foundTAb.TabPath + - ") resolves to two separate pages (" + tab1Name + " [tabid = " + - foundTAb.TabIdOriginal + "], " + tab2Name + " [tabid = " + tabId.ToString() + - "]). Only the second page will be shown for the url."; - const string msg2 = - "PLEASE NOTE : this is an information message only, this message does not affect site operations in any way."; - - //771 : change to admin alert instead of exception - //log a host alert - var log = new LogInfo {LogTypeKey = "HOST_ALERT"}; - log.AddProperty("Advanced Friendly URL Provider Duplicate URL Warning", "Page Naming Conflict"); - log.AddProperty("Duplicate Page Details", msg); - log.AddProperty("Warning Information", msg2); - log.AddProperty("Suggested Action", "Rename one or both of the pages to ensure a unique URL"); - log.AddProperty("Hide this message", - "To stop this message from appearing in the log, uncheck the option for 'Produce an Exception in the Site Log if two pages have the same name/path?' in the Advanced Url Rewriting settings."); - log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); - LogController.Instance.AddLog(log); - } } } else { dupCheckDict.Remove(dupKey); - //add this tab to the duplicate key dictionary + + // add this tab to the duplicate key dictionary dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(), dupKey, isDeleted)); } } else { - //add this tab to the duplicate key dictionary - the dup key check dict is always maintained - //regardless of whether checking is employed or not + // add this tab to the duplicate key dictionary - the dup key check dict is always maintained + // regardless of whether checking is employed or not dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(), dupKey, isDeleted)); } } private static OrderedDictionary BuildPortalAliasesDictionary() - { - var aliases = PortalAliasController.Instance.GetPortalAliases(); - //create a new OrderedDictionary. We use this because we - //want to key by the correct regex pattern and return the - //portalAlias that matches, and we want to preserve the - //order of the items, such that the item with the most path separators (/) - //is at the front of the list. - var aliasList = new OrderedDictionary(aliases.Count); - var pathLengths = new List(); + { + var aliases = PortalAliasController.Instance.GetPortalAliases(); + + // create a new OrderedDictionary. We use this because we + // want to key by the correct regex pattern and return the + // portalAlias that matches, and we want to preserve the + // order of the items, such that the item with the most path separators (/) + // is at the front of the list. + var aliasList = new OrderedDictionary(aliases.Count); + var pathLengths = new List(); foreach (string aliasKey in aliases.Keys) { PortalAliasInfo alias = aliases[aliasKey]; - //regex escape the portal alias for inclusion into a regex pattern + + // regex escape the portal alias for inclusion into a regex pattern string plainAlias = alias.HTTPAlias; var aliasesToAdd = new List { plainAlias }; - //check for existence of www. version of domain, if it doesn't have a www. + + // check for existence of www. version of domain, if it doesn't have a www. if (plainAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) { if (plainAlias.Length > 4) @@ -941,7 +1070,7 @@ private static OrderedDictionary BuildPortalAliasesDictionary() string noWWWVersion = plainAlias.Substring(4); if (!aliases.Contains(noWWWVersion)) { - //there is no no-www version of the alias + // there is no no-www version of the alias aliasesToAdd.Add(noWWWVersion); } } @@ -954,56 +1083,63 @@ private static OrderedDictionary BuildPortalAliasesDictionary() aliasesToAdd.Add(wwwVersion); } } + int count = 0; foreach (string aliasToAdd in aliasesToAdd) { - //set flag on object to know whether to redirect or not + // set flag on object to know whether to redirect or not count++; var aliasObject = new PortalAliasInfo(alias) { Redirect = count != 1 }; - //work out how many path separators there are in the portalAlias (ie myalias/mychild = 1 path) + // work out how many path separators there are in the portalAlias (ie myalias/mychild = 1 path) int pathLength = plainAlias.Split('/').GetUpperBound(0); - //now work out where in the list we should put this portalAlias regex pattern - //the list is to be sorted so that those aliases with the most paths - //are at the front of the list : ie, they are tested first + + // now work out where in the list we should put this portalAlias regex pattern + // the list is to be sorted so that those aliases with the most paths + // are at the front of the list : ie, they are tested first int insertPoint = pathLengths.Count - 1; - //walk through the existing list of path lengths, - //and ascertain where in the list this one falls - //if they are all the same path length, then place them in portal alias order + + // walk through the existing list of path lengths, + // and ascertain where in the list this one falls + // if they are all the same path length, then place them in portal alias order for (int i = 0; i < pathLengths.Count; i++) { insertPoint = i; if (pathLength > pathLengths[i]) { - //larger than this position, insert at this value + // larger than this position, insert at this value break; } - insertPoint++; //next one along (if at end, means add) + + insertPoint++; // next one along (if at end, means add) } + if (pathLengths.Count > 0 && insertPoint <= pathLengths.Count - 1) { - //put the new regex pattern into the correct position + // put the new regex pattern into the correct position aliasList.Insert(insertPoint, aliasToAdd, aliasObject); pathLengths.Insert(insertPoint, pathLength); } else { - //put the new regex pattern on the end of the list + // put the new regex pattern on the end of the list aliasList.Add(aliasToAdd, aliasObject); pathLengths.Add(pathLength); } } - } + } + return aliasList; } - private static SharedDictionary BuildTabDictionary(out PathSizes pathSizes, - FriendlyUrlSettings settings, - int buildPortalId, - SharedDictionary tabIndex, - out Hashtable homePageSkins, - out SharedDictionary portalTabPathDictionary, - Guid parentTraceId) + private static SharedDictionary BuildTabDictionary( + out PathSizes pathSizes, + FriendlyUrlSettings settings, + int buildPortalId, + SharedDictionary tabIndex, + out Hashtable homePageSkins, + out SharedDictionary portalTabPathDictionary, + Guid parentTraceId) { if (tabIndex == null) { @@ -1016,21 +1152,22 @@ private static SharedDictionary BuildTabDictionary(out PathSizes portalTabPathDictionary = null; if (buildPortalId >= 0) { - //dictioanry for storing the tab paths in + // dictioanry for storing the tab paths in portalTabPathDictionary = new SharedDictionary(); - //init the duplicate key check dictionary - disposed after the tab dictionary is built + // init the duplicate key check dictionary - disposed after the tab dictionary is built var dupCheck = new Dictionary(); - //get the list of tabs for all portals - //new for 2.0 : only get tabs by portal - //770 : keep track of custom alias tabs + // get the list of tabs for all portals + // new for 2.0 : only get tabs by portal + // 770 : keep track of custom alias tabs Dictionary tabs = FriendlyUrlController.GetTabs(buildPortalId, false, settings); const bool hasSiteRootRedirect = true; /* for the requested build portal, add in the standard urls and special rules */ - //735 : switch to custom method for getting portal + + // 735 : switch to custom method for getting portal PortalInfo thisPortal = CacheController.GetPortal(buildPortalId, true); List chosenAliases; Dictionary chosenAliasesCultures; @@ -1040,29 +1177,29 @@ private static SharedDictionary BuildTabDictionary(out PathSizes GetAliasFromSettings(buildPortalId, out chosenAliases, out chosenAliasesCultures); FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); - //keep a list of cultures specific to an alias + // keep a list of cultures specific to an alias foreach (string culture in chosenAliasesCultures.Values.Where(culture => aliasSpecificCultures.Contains(culture) == false)) { aliasSpecificCultures.Add(culture); } - //the home tabid of the portal - should be the home page for the default language (all others will get page path) + // the home tabid of the portal - should be the home page for the default language (all others will get page path) int homeTabId = thisPortal.HomeTabId; - //Add site root redirects + // Add site root redirects AddSiteRootRedirects(pathSizes, tabIndex, chosenAliases, hasSiteRootRedirect, dupCheck, usingHttpAliases); - //add in any internal aliases as valid aliase + // add in any internal aliases as valid aliase AddInternalAliases(settings, usingHttpAliases); - //loop through each tab and add all of the various Url paths that the tab can be found with, - //for all aliases the tab will be used with + // loop through each tab and add all of the various Url paths that the tab can be found with, + // for all aliases the tab will be used with foreach (TabInfo tab in tabs.Values) { int tabPathDepth = 0; - //935 : get the tab path and add to the tab path dictionary if it's not just a straight conversion of the TabPath value - //bool modified; + // 935 : get the tab path and add to the tab path dictionary if it's not just a straight conversion of the TabPath value + // bool modified; string tabPath = TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId); string tabKey = tab.TabID.ToString(); @@ -1074,97 +1211,106 @@ private static SharedDictionary BuildTabDictionary(out PathSizes } } - //now, go through the list of tabs for this portal and build up the dictionary + // now, go through the list of tabs for this portal and build up the dictionary if ((settings.FriendlyAdminHostUrls && tab.PortalID == -1) || tab.PortalID == buildPortalId) { - //check if this value has been excluded from being a friendly url + // check if this value has been excluded from being a friendly url bool isExcluded = RewriteController.IsExcludedFromFriendlyUrls(tab, settings, true); string tabCulture = tab.CultureCode; - //770 : custom alias per tab (and culture) + // 770 : custom alias per tab (and culture) bool customAliasUsed; - var customHttpAlias = ManageCustomAliases(tabCulture, - thisPortal, - tab, - usingHttpAliases, - customHttpAliasesUsed, - out customAliasUsed); - - //process each entry for the alias + var customHttpAlias = ManageCustomAliases( + tabCulture, + thisPortal, + tab, + usingHttpAliases, + customHttpAliasesUsed, + out customAliasUsed); + + // process each entry for the alias foreach (string httpAlias in usingHttpAliases) { - //string httpAlias = portalAlias.HTTPAlias; - //761 : allow duplicate tab paths between culture-specific aliases - //this is done by ascertaining which culture a particular alias belongs to - //then checking tab cultures as they are added to the dictionary - string aliasCulture = ""; + // string httpAlias = portalAlias.HTTPAlias; + // 761 : allow duplicate tab paths between culture-specific aliases + // this is done by ascertaining which culture a particular alias belongs to + // then checking tab cultures as they are added to the dictionary + string aliasCulture = string.Empty; if (chosenAliasesCultures.ContainsKey(httpAlias.ToLowerInvariant())) { aliasCulture = chosenAliasesCultures[httpAlias.ToLowerInvariant()]; } + bool ignoreTabWrongCulture = false; - //the tab is the wrong culture, so don't add it to the dictionary - - if (aliasCulture != "") + + // the tab is the wrong culture, so don't add it to the dictionary + if (aliasCulture != string.Empty) { - if (tabCulture != aliasCulture - //this is a language-specific alias that's different to the culture for this alias - && !string.IsNullOrEmpty(tabCulture) //and the tab culture is set + if (tabCulture != aliasCulture + + // this is a language-specific alias that's different to the culture for this alias + && !string.IsNullOrEmpty(tabCulture) // and the tab culture is set && aliasSpecificCultures.Contains(tabCulture)) - //and there is a specific alias for this tab culture + + // and there is a specific alias for this tab culture { ignoreTabWrongCulture = true; } } + if (!ignoreTabWrongCulture) { if (!isExcluded) { - //Add this tab to the dictionary - //750 : user profile action not returned as buildPortalId not used - tabPathDepth = AddTabToTabDict(tabIndex, - dupCheck, - httpAlias, - aliasCulture, - customHttpAlias, - thisPortal, - tabPath, - ref customHttpAliasesUsed, - tab, - settings, - options, - homeTabId, - ref homePageSkins, - parentTraceId); + // Add this tab to the dictionary + // 750 : user profile action not returned as buildPortalId not used + tabPathDepth = AddTabToTabDict( + tabIndex, + dupCheck, + httpAlias, + aliasCulture, + customHttpAlias, + thisPortal, + tabPath, + ref customHttpAliasesUsed, + tab, + settings, + options, + homeTabId, + ref homePageSkins, + parentTraceId); } else { - //589 : custom redirects added as 200 status not causing base urls to redirect + // 589 : custom redirects added as 200 status not causing base urls to redirect bool excludeFriendlyUrls = true; - //549 : detect excluded friendly urls by putting a known pattern into the dictionary - //add this tab to the dictionary, but with the hack pattern [UseBase] to capture the fact it's a base Url - //then, if there's redirects for it, add those as well. It's possible to exclude a tab from friendly urls, but - //give it custom redirects + + // 549 : detect excluded friendly urls by putting a known pattern into the dictionary + // add this tab to the dictionary, but with the hack pattern [UseBase] to capture the fact it's a base Url + // then, if there's redirects for it, add those as well. It's possible to exclude a tab from friendly urls, but + // give it custom redirects string rewritePath = null; if (tab.TabUrls.Count > 0) { - rewritePath = CreateRewritePath(tab.TabID, ""); - string rewritePathKeep = rewritePath; //remember this value to compare - AddCustomRedirectsToDictionary(tabIndex, - dupCheck, - httpAlias, - tab, - settings, - options, - ref rewritePath, - out tabPathDepth, - ref customHttpAliasesUsed, - tab.IsDeleted, - parentTraceId); + rewritePath = CreateRewritePath(tab.TabID, string.Empty); + string rewritePathKeep = rewritePath; // remember this value to compare + AddCustomRedirectsToDictionary( + tabIndex, + dupCheck, + httpAlias, + tab, + settings, + options, + ref rewritePath, + out tabPathDepth, + ref customHttpAliasesUsed, + tab.IsDeleted, + parentTraceId); if (rewritePath != rewritePathKeep) - //check to see the rewrite path is still the same, or did it get changed? + + // check to see the rewrite path is still the same, or did it get changed? { - //OK, the rewrite path was modifed by the custom redirects dictionary add + // OK, the rewrite path was modifed by the custom redirects dictionary add excludeFriendlyUrls = false; } } @@ -1172,106 +1318,119 @@ private static SharedDictionary BuildTabDictionary(out PathSizes if (excludeFriendlyUrls) { rewritePath = "[UseBase]"; - //use hack pattern to indicate not to rewrite on this Url + + // use hack pattern to indicate not to rewrite on this Url } - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tab.TabPath, - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - true, - false); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tab.TabPath, + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + true, + false); } } else { - //ignoring this tab because the alias culture doesn't match to the tab culture - //however, we need to add it to the dictionary in case there's an old link (pre-translation/pre-friendly url/pre-alias&culture linked) + // ignoring this tab because the alias culture doesn't match to the tab culture + // however, we need to add it to the dictionary in case there's an old link (pre-translation/pre-friendly url/pre-alias&culture linked) string rewritePath = CreateRewritePath(tab.TabID, tabCulture); - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - tab.TabPath, - rewritePath, - tab.TabID, - UrlEnums.TabKeyPreference.TabRedirected, - ref tabPathDepth, - true, - tab.IsDeleted); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + tab.TabPath, + rewritePath, + tab.TabID, + UrlEnums.TabKeyPreference.TabRedirected, + ref tabPathDepth, + true, + tab.IsDeleted); } + pathSizes.SetTabPathDepth(tabPathDepth); } - if (customHttpAlias != "" && customAliasUsed == false && + + if (customHttpAlias != string.Empty && customAliasUsed == false && usingHttpAliases.Contains(customHttpAlias)) { - //this was using a custom Http Alias, so remove this from the using list if it wasn't already there + // this was using a custom Http Alias, so remove this from the using list if it wasn't already there usingHttpAliases.Remove(customHttpAlias); } } } - //now build the standard Urls for all of the aliases that are used + + // now build the standard Urls for all of the aliases that are used foreach (string httpAlias in usingHttpAliases) { - //750 : using -1 instead of buildPortalId - //850 : set culture code based on httpALias, where specific culture - //is being associated with httpAlias + // 750 : using -1 instead of buildPortalId + // 850 : set culture code based on httpALias, where specific culture + // is being associated with httpAlias string cultureCode = null; if (chosenAliasesCultures.ContainsKey(httpAlias)) { cultureCode = chosenAliasesCultures[httpAlias]; } + AddStandardPagesToDict(tabIndex, dupCheck, httpAlias, buildPortalId, cultureCode); } - //and for any custom urls being used + + // and for any custom urls being used foreach (string httpAlias in customHttpAliasesUsed) { - //750 : using -1 instead of buildPortalId - //is being associated with httpAlias + // 750 : using -1 instead of buildPortalId + // is being associated with httpAlias string cultureCode = null; if (chosenAliasesCultures.ContainsKey(httpAlias)) { cultureCode = chosenAliasesCultures[httpAlias]; } + AddStandardPagesToDict(tabIndex, dupCheck, httpAlias, buildPortalId, cultureCode); - //if any site root, add those as well. So if any module providers or rules work - //on the custom http aliases, they will work as well. + + // if any site root, add those as well. So if any module providers or rules work + // on the custom http aliases, they will work as well. if (hasSiteRootRedirect) { int tempPathDepth = 0; - AddToTabDict(tabIndex, - dupCheck, - httpAlias, - "*", - "", - -1, - UrlEnums.TabKeyPreference.TabOK, - ref tempPathDepth, - false, - false); + AddToTabDict( + tabIndex, + dupCheck, + httpAlias, + "*", + string.Empty, + -1, + UrlEnums.TabKeyPreference.TabOK, + ref tempPathDepth, + false, + false); } } - //do a check of the rebuildData object, to see if there is anything we needed to add to the dictionary + // do a check of the rebuildData object, to see if there is anything we needed to add to the dictionary var rebuildData = (PageIndexData)DataCache.GetCache("rebuildData"); if (rebuildData != null) { - //there was rebuild data stored so we could do things post-dictionary rebuild + // there was rebuild data stored so we could do things post-dictionary rebuild if (rebuildData.LastPageKey != null && rebuildData.LastPageValue != null) { if (tabIndex.ContainsKey(rebuildData.LastPageKey) == false) { - //add this item to the list of pages, even though it no longer exists + // add this item to the list of pages, even though it no longer exists tabIndex.Add(rebuildData.LastPageKey, rebuildData.LastPageValue); } } - //now clear out the rebuildData object, because we've checked and used it + + // now clear out the rebuildData object, because we've checked and used it DataCache.RemoveCache("rebuildData"); } } + return tabIndex; } @@ -1282,18 +1441,22 @@ private static SharedDictionary FetchTabPathDictionary(int porta { tabPathDict = CacheController.GetTabPathsFromCache(portalId); } + return tabPathDict; } - private static void GetAliasFromSettings(int portalId, - out List useAliases, - out Dictionary aliasCultures) + private static void GetAliasFromSettings( + int portalId, + out List useAliases, + out Dictionary aliasCultures) { useAliases = new List(); aliasCultures = new Dictionary(); - //761 : return list of chosen aliases as well, so that Urls can be d + + // 761 : return list of chosen aliases as well, so that Urls can be d var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - //list of portal aliases for this portal + + // list of portal aliases for this portal List chosenAliases = null; var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); if (primaryAliases.Count > 0) @@ -1301,28 +1464,30 @@ private static void GetAliasFromSettings(int portalId, chosenAliases = primaryAliases.GetAliasesForPortalId(portalId); aliasCultures = primaryAliases.GetAliasesAndCulturesForPortalId(portalId); } + if (chosenAliases != null && chosenAliases.Count > 0) { - //add the chosen alias in based on the usePortalAlias setting + // add the chosen alias in based on the usePortalAlias setting useAliases.AddRange(aliases.Where(a => chosenAliases.Contains(a.HTTPAlias.ToLowerInvariant()))); } if (useAliases.Count == 0) { - //nothing found to match, - //add all aliases in + // nothing found to match, + // add all aliases in useAliases.AddRange(aliases); } } - private static string ManageCustomAliases(string tabCulture, - PortalInfo thisPortal, - TabInfo tab, - List httpAliases, - List customHttpAliasesUsed, - out bool customAliasUsed) + private static string ManageCustomAliases( + string tabCulture, + PortalInfo thisPortal, + TabInfo tab, + List httpAliases, + List customHttpAliasesUsed, + out bool customAliasUsed) { - string customHttpAlias = ""; + string customHttpAlias = string.Empty; string currentCulture = tabCulture; if (string.IsNullOrEmpty(tabCulture)) { @@ -1333,11 +1498,13 @@ private static string ManageCustomAliases(string tabCulture, { customHttpAlias = tab.CustomAliases[currentCulture].ToLowerInvariant(); } + customAliasUsed = httpAliases.Contains(customHttpAlias); - //if there is a custom alias for this tab, and it's not one of the ones in the alias list, put it in - //so that this tab will be put into the dictionary with not only the standard alias(es) but also - //the custom alias. Other logic will decide if to redirect the 'wrong' alias if requested with this tab. - if (customAliasUsed == false && customHttpAlias != "") + + // if there is a custom alias for this tab, and it's not one of the ones in the alias list, put it in + // so that this tab will be put into the dictionary with not only the standard alias(es) but also + // the custom alias. Other logic will decide if to redirect the 'wrong' alias if requested with this tab. + if (customAliasUsed == false && customHttpAlias != string.Empty) { httpAliases.Add(customHttpAlias); if (customHttpAliasesUsed.Contains(customHttpAlias) == false) @@ -1345,82 +1512,45 @@ private static string ManageCustomAliases(string tabCulture, customHttpAliasesUsed.Add(customHttpAlias); } } + return customHttpAlias; - } - - #endregion - - #region Internal Methods - - internal static string CreateRewritePath(int tabId, string cultureCode, params string[] keyValuePair) - { - string rewritePath = "?TabId=" + tabId.ToString(); - //736 : 5.5 compatibility - identify tab rewriting at source by tab culture code - RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, cultureCode); - return keyValuePair.Aggregate(rewritePath, (current, keyValue) => current + ("&" + keyValue)); - } - - internal static string CreateRewritePath(int tabId, string cultureCode, ActionType action, RedirectReason reason) - { - string rewritePath = CreateRewritePath(tabId, cultureCode); - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, action, reason); - return rewritePath; - } + } /// - /// Returns whether the portal specified exists in the Tab index or not. - /// - /// The current portalDepths dictionary. - /// The id of the portal to search for. - /// - private static bool PortalExistsInIndex(SharedDictionary portalDepths, int portalId) - { - bool result = false; - - if (portalDepths != null) - { - using (portalDepths.GetReadLock()) - { - result = portalDepths.ContainsKey(portalId); - } - } - return result; - } - - /// - /// Gets the Tab Dictionary from the DataCache memory location, if it's empty or missing, builds a new one. + /// Gets the Tab Dictionary from the DataCache memory location, if it's empty or missing, builds a new one. /// /// - /// ByRef parameter to return the minimum tab path depth (the number of '/' in the tab path) - /// ByRef parameter to return the maximum tab path depth (the number of '/' in the tab path) - /// ByRef parameter to return the minimum alias path depth (the number of '/' in the alias path - /// ByRef parameter to return the maximum alias path depth (the number of '/' in the alias path) + /// ByRef parameter to return the minimum tab path depth (the number of '/' in the tab path). + /// ByRef parameter to return the maximum tab path depth (the number of '/' in the tab path). + /// ByRef parameter to return the minimum alias path depth (the number of '/' in the alias path. + /// ByRef parameter to return the maximum alias path depth (the number of '/' in the alias path). /// /// /// /// - /// Dictionary (string, string) of Tab paths in tab key, with the rewrite path as the value + /// Dictionary (string, string) of Tab paths in tab key, with the rewrite path as the value. /// /// Changes /// Task 608 : Incrementally build tab dictionary instead of building entire dicitionary all at once /// Task 609 : If usePortalAlias is specified, only build dictionary with specific portal alias : ignore others - /// Task 791 : allow for specification of true/false for using thread locking to prevent multiple rebuilds on threads - /// - internal static SharedDictionary FetchTabDictionary(int portalId, - out int minTabPathDepth, - out int maxTabPathDepth, - out int minAliasPathDepth, - out int maxAliasPathDepth, - FriendlyUrlSettings settings, - bool forceRebuild, - bool bypassCache, - Guid parentTraceId) + /// Task 791 : allow for specification of true/false for using thread locking to prevent multiple rebuilds on threads. + /// + internal static SharedDictionary FetchTabDictionary( + int portalId, + out int minTabPathDepth, + out int maxTabPathDepth, + out int minAliasPathDepth, + out int maxAliasPathDepth, + FriendlyUrlSettings settings, + bool forceRebuild, + bool bypassCache, + Guid parentTraceId) { PathSizes depthInfo; - SharedDictionary portalDepths = null; + SharedDictionary portalDepths = null; SharedDictionary dict = null; SharedDictionary portalTabPathDictionary = null; - string reason = ""; + string reason = string.Empty; var cc = new CacheController(); if (bypassCache == false) @@ -1431,11 +1561,11 @@ internal static SharedDictionary FetchTabDictionary(int portalId if (dict == null || portalDepths == null || portalTabPathDictionary == null || !PortalExistsInIndex(portalDepths, portalId) || forceRebuild) { - //place threadlock to prevent two threads getting a null object. Use the same lock object that is used to + // place threadlock to prevent two threads getting a null object. Use the same lock object that is used to lock (tabPathDictBuildLock) { - //check for the tab dictionary in the DataCache again as it could have been cached by another thread - //while waiting for the lock to become available. + // check for the tab dictionary in the DataCache again as it could have been cached by another thread + // while waiting for the lock to become available. if (bypassCache == false) { cc.GetPageIndexFromCache(out dict, out portalDepths, settings); @@ -1444,44 +1574,48 @@ internal static SharedDictionary FetchTabDictionary(int portalId if (dict == null || portalDepths == null || portalTabPathDictionary == null || !PortalExistsInIndex(portalDepths, portalId) || forceRebuild) { - Hashtable homePageSkins; //keeps a list of skins set per home page and culture + Hashtable homePageSkins; // keeps a list of skins set per home page and culture if (!bypassCache && dict == null) { reason += "No Page index in cache;"; } + if (forceRebuild) { reason += "Force Rebuild;"; } + if (bypassCache) { reason += "Bypass Cache;"; } - //PathSizes depthInfo; - //the cached dictionary was null or forceRebuild = true or bypassCache = true, so go get a new dictionary - dict = BuildTabDictionary(out depthInfo, - settings, - portalId, - dict, - out homePageSkins, - out portalTabPathDictionary, - parentTraceId); + + // PathSizes depthInfo; + // the cached dictionary was null or forceRebuild = true or bypassCache = true, so go get a new dictionary + dict = BuildTabDictionary( + out depthInfo, + settings, + portalId, + dict, + out homePageSkins, + out portalTabPathDictionary, + parentTraceId); if (portalDepths == null || forceRebuild) { portalDepths = new SharedDictionary(); } - //store the fact that this portal has been built + // store the fact that this portal has been built using (portalDepths.GetWriteLock()) { - //depthInfo may already exist in index so use indexer to Add/Update rather than using Add method which - //would throw an exception if the portal already existed in the dictionary. + // depthInfo may already exist in index so use indexer to Add/Update rather than using Add method which + // would throw an exception if the portal already existed in the dictionary. portalDepths[portalId] = depthInfo; } - if (bypassCache == false) //only cache if bypass not switched on + if (bypassCache == false) // only cache if bypass not switched on { reason += "Portal " + portalId + " added to index;"; using (dict.GetReadLock()) @@ -1510,7 +1644,7 @@ internal static SharedDictionary FetchTabDictionary(int portalId } else { - //fallback values, should never get here: mainly for compiler wranings + // fallback values, should never get here: mainly for compiler wranings minTabPathDepth = 1; maxTabPathDepth = 10; minAliasPathDepth = 1; @@ -1519,8 +1653,7 @@ internal static SharedDictionary FetchTabDictionary(int portalId return dict; } - - + /// /// Returns a list of aliases that are used in custom tab/alias association. /// @@ -1534,9 +1667,31 @@ internal static List GetCustomPortalAliases(FriendlyUrlSettings settings aliases = FriendlyUrlController.GetCustomAliasesForTabs(); CacheController.StoreCustomAliasesInCache(aliases, settings); } + return aliases; } + /// + /// Returns whether the portal specified exists in the Tab index or not. + /// + /// The current portalDepths dictionary. + /// The id of the portal to search for. + /// + private static bool PortalExistsInIndex(SharedDictionary portalDepths, int portalId) + { + bool result = false; + + if (portalDepths != null) + { + using (portalDepths.GetReadLock()) + { + result = portalDepths.ContainsKey(portalId); + } + } + + return result; + } + /// /// Gets the portal alias by portal. /// @@ -1547,18 +1702,18 @@ internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string port { PortalAliasInfo retValue = null; - //get the portal alias collection from the cache + // get the portal alias collection from the cache var portalAliasCollection = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); bool foundAlias = false; - //Do a specified PortalAlias check first + // Do a specified PortalAlias check first PortalAliasInfo portalAliasInfo = portalAliasCollection.SingleOrDefault(a => a.HTTPAlias == portalAlias.ToLowerInvariant()); if (portalAliasInfo != null) { if (portalAliasInfo.PortalID == portalId) { - //set the alias + // set the alias retValue = portalAliasInfo; foundAlias = true; } @@ -1566,17 +1721,17 @@ internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string port if (!foundAlias) { - //collection to hold aliases sorted by length, longest first + // collection to hold aliases sorted by length, longest first var aliases = (from p in portalAliasCollection select p.HTTPAlias).ToList(); - //get aliases sorted by length of alias + // get aliases sorted by length of alias aliases.Sort(new StringLengthComparer()); - //searching from longest to shortest alias ensures that the most specific portal is matched first - //In some cases this method has been called with "portalaliases" that were not exactly the real portal alias - //the startswith behaviour is preserved here to support those non-specific uses - //IEnumerable aliases = portalAliasCollection.Keys.Cast().OrderByDescending(k => k.Length); + // searching from longest to shortest alias ensures that the most specific portal is matched first + // In some cases this method has been called with "portalaliases" that were not exactly the real portal alias + // the startswith behaviour is preserved here to support those non-specific uses + // IEnumerable aliases = portalAliasCollection.Keys.Cast().OrderByDescending(k => k.Length); foreach (string currentAlias in aliases) { // check if the alias key starts with the portal alias value passed in - we use @@ -1592,7 +1747,8 @@ internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string port retValue = portalAliasInfo; break; } - httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", "") : string.Concat("www.", httpAlias); + + httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && portalAliasInfo.PortalID == portalId) { retValue = portalAliasInfo; @@ -1601,6 +1757,7 @@ internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string port } } } + return retValue; } @@ -1610,23 +1767,24 @@ internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string port /// internal static OrderedDictionary GetPortalAliases(FriendlyUrlSettings settings) { - //object to return + // object to return OrderedDictionary aliasList = CacheController.GetPortalAliasesFromCache(); if (aliasList == null) { aliasList = BuildPortalAliasesDictionary(); CacheController.StorePortalAliasesInCache(aliasList, settings); } + return aliasList; } /// - /// Returns the tab path of the base DNN tab. Ie /Home or /Somepage/SomeOtherPage + /// Returns the tab path of the base DNN tab. Ie /Home or /Somepage/SomeOtherPage. /// /// /// /// - /// Will remove // from the tabPath as stored in the Tabs object/table + /// Will remove // from the tabPath as stored in the Tabs object/table. /// internal static string GetTabPath(TabInfo tab, FriendlyUrlOptions options, Guid parentTraceId) { @@ -1641,7 +1799,7 @@ internal static string GetTabPath(TabInfo tab, FriendlyUrlOptions options, Guid { if (tpd.Count > 0) { - //get the path from the dictionary + // get the path from the dictionary string tabKey = tab.TabID.ToString(); if (tpd.ContainsKey(tabKey)) { @@ -1652,41 +1810,7 @@ internal static string GetTabPath(TabInfo tab, FriendlyUrlOptions options, Guid } } - return tabPath ?? (TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId)); - } - - #endregion - - #region Public Methods - - public static void InvalidateDictionary(string reason, PageIndexData rebuildData, int portalId) - { - //if supplied, store the rebuildData for when the dictionary gets rebuilt - //this is a way of storing data between dictionary rebuilds - if (rebuildData != null) - { - DataCache.SetCache("rebuildData", rebuildData); - } - - //add log entry for cache clearance - var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; - try - { - //817 : not clearing items correctly from dictionary - CacheController.FlushPageIndexFromCache(); - } - catch (Exception ex) - { - //do nothing ; can be from trying to access cache after system restart - Services.Exceptions.Exceptions.LogException(ex); - } - - log.AddProperty("Url Rewriting Caching Message", "Page Index Cache Cleared. Reason: " + reason); - log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); - LogController.Instance.AddLog(log); - } - - #endregion - + return tabPath ?? TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId); + } } } diff --git a/DNN Platform/Library/Entities/Urls/TabPathController.cs b/DNN Platform/Library/Entities/Urls/TabPathController.cs index a83c4855cb1..16d21f1d567 100644 --- a/DNN Platform/Library/Entities/Urls/TabPathController.cs +++ b/DNN Platform/Library/Entities/Urls/TabPathController.cs @@ -1,58 +1,72 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + /// - /// The TabPathHelper class provides helper methods for working with tab urls + /// The TabPathHelper class provides helper methods for working with tab urls. /// public class TabPathHelper - { - #region Private Methods - - private static string AppendToTabPath(string path, TabInfo tab, FriendlyUrlOptions options, out bool modified) + { + public static string BuildTabPathWithReplacement(TabInfo tab, FriendlyUrlOptions options, Guid parentTraceId) { - string tabName = tab.TabName; - var result = new StringBuilder(tabName.Length); - //922 : change to harmonise cleaning of tab + other url name items - tabName = FriendlyUrlController.CleanNameForUrl(tabName, options, out modified); - if (!modified - && string.IsNullOrEmpty(options.PunctuationReplacement) == false - && tab.TabName.Contains(" ") - && tabName.Contains(" ") == false) + string path = string.Empty; + if (tab.ParentId > -1) { - modified = true; - //spaces replaced - the modified parameter is for all other replacements but space replacements + TabInfo parentTab = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false); + + // 822 : don't assume parent tab is going to exist - database might be corrupted + // 896 : check to make sure tabid and parentid are different - or stack overflow occurs with terminal loop + if (parentTab != null && parentTab.TabID != tab.TabID) + { + path = BuildTabPathWithReplacement(parentTab, options, parentTraceId); + } } - result.Append(tabName); - result.Insert(0, "//"); - result.Insert(0, path); //effectively adds result to the end of the path - return result.ToString(); - } - - #endregion + + bool modified; + path = AppendToTabPath(path, tab, options, out modified); - #region Internal Methods + return path; + } /// - /// Get the tab path for the supplied Tab + /// Replaces the diacritic characters in a path with other values. + /// + /// + /// + /// + public static string ReplaceDiacritics(string tabPath, out bool replacedDiacritic) + { + string nmTabPath = tabPath.Normalize(NormalizationForm.FormD); + var sb = new StringBuilder(); + for (int i = 0; i < nmTabPath.Length; i++) + { + char c = nmTabPath[i]; + if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) + { + sb.Append(c); + } + } + + string result = sb.ToString(); + replacedDiacritic = string.CompareOrdinal(tabPath, result) != 0; + return sb.ToString(); + } + + /// + /// Get the tab path for the supplied Tab. /// /// /// @@ -63,46 +77,71 @@ internal static string GetFriendlyUrlTabPath(TabInfo tab, FriendlyUrlOptions opt string baseTabPath = tab.TabPath.Replace("//", "/").TrimStart('/'); if (options.CanGenerateNonStandardPath) { - //build up a non-space version of the tab path + // build up a non-space version of the tab path baseTabPath = BuildTabPathWithReplacement(tab, options, parentTraceId); baseTabPath = baseTabPath.Replace("//", "/"); - //automatic diacritic conversion + // automatic diacritic conversion if (options.ConvertDiacriticChars) { bool diacriticsChanged; baseTabPath = ReplaceDiacritics(baseTabPath, out diacriticsChanged); } } + return baseTabPath; } /// - /// Finds a culture-specific homepage tabid for a non-default language + /// Finds a culture-specific homepage tabid for a non-default language. /// - /// The default culture of the portal + /// The default culture of the portal. /// - /// The default home page tab id + /// The default home page tab id. /// - /// THe valid home page tabid for the portalid and culture - /// Note if no specific home page found for the culture, will return defaultHomeTabId back + /// THe valid home page tabid for the portalid and culture. + /// Note if no specific home page found for the culture, will return defaultHomeTabId back. internal static int GetHomePageTabIdForCulture(string defaultCulture, int portalId, string cultureCode, int defaultHomeTabId) { int homeTabId = defaultHomeTabId; - if (String.Compare(defaultCulture, cultureCode, StringComparison.OrdinalIgnoreCase) != 0) + if (string.Compare(defaultCulture, cultureCode, StringComparison.OrdinalIgnoreCase) != 0) { - //not the default culture, so there could be a different home page for the different cultulre in 5.5+ builds + // not the default culture, so there could be a different home page for the different cultulre in 5.5+ builds var cultureLocale = new Locale { Code = cultureCode, Fallback = cultureCode, Text = cultureCode }; TabInfo tab = TabController.Instance.GetTabByCulture(defaultHomeTabId, portalId, cultureLocale); if (tab != null) { - //this is the culture specific tab of the home page + // this is the culture specific tab of the home page homeTabId = tab.TabID; } } + return homeTabId; } + + private static string AppendToTabPath(string path, TabInfo tab, FriendlyUrlOptions options, out bool modified) + { + string tabName = tab.TabName; + var result = new StringBuilder(tabName.Length); + + // 922 : change to harmonise cleaning of tab + other url name items + tabName = FriendlyUrlController.CleanNameForUrl(tabName, options, out modified); + if (!modified + && string.IsNullOrEmpty(options.PunctuationReplacement) == false + && tab.TabName.Contains(" ") + && tabName.Contains(" ") == false) + { + modified = true; + + // spaces replaced - the modified parameter is for all other replacements but space replacements + } + + result.Append(tabName); + result.Insert(0, "//"); + result.Insert(0, path); // effectively adds result to the end of the path + return result.ToString(); + } internal static string GetTabAliasSkinForTabAndAlias(int portalId, string httpAlias, string culture) { @@ -121,16 +160,17 @@ internal static string GetTabAliasSkinForTabAndAlias(int portalId, string httpAl skin = (string)homePageSkins[key2]; } } + return skin; } /// - /// For the supplied options, return a tab path for the specified tab + /// For the supplied options, return a tab path for the specified tab. /// - /// TabInfo object of selected tab - /// FriendlyUrlSettings + /// TabInfo object of selected tab. + /// FriendlyUrlSettings. /// - /// Whether to add in the customised Tab redirects or not + /// Whether to add in the customised Tab redirects or not. /// /// /// @@ -142,51 +182,56 @@ internal static string GetTabAliasSkinForTabAndAlias(int portalId, string httpAl /// /// 751 : include isDefaultCultureCode flag to determine when using the portal default language /// 770 : include custom http alias output for when the Url uses a specific alias due to custom Url rules - /// : include new out parameter 'isCustomPath' to return whether the Url was generated from Url-Master custom url + /// : include new out parameter 'isCustomPath' to return whether the Url was generated from Url-Master custom url. /// - /// The tab path as specified - internal static string GetTabPath(TabInfo tab, - FriendlyUrlSettings settings, - FriendlyUrlOptions options, - bool ignoreCustomRedirects, - bool homePageSiteRoot, - bool isHomeTab, - string cultureCode, - bool isDefaultCultureCode, - bool hasPath, - out bool dropLangParms, - out string customHttpAlias, - out bool isCustomPath, - Guid parentTraceId) + /// The tab path as specified. + internal static string GetTabPath( + TabInfo tab, + FriendlyUrlSettings settings, + FriendlyUrlOptions options, + bool ignoreCustomRedirects, + bool homePageSiteRoot, + bool isHomeTab, + string cultureCode, + bool isDefaultCultureCode, + bool hasPath, + out bool dropLangParms, + out string customHttpAlias, + out bool isCustomPath, + Guid parentTraceId) { string newTabPath; dropLangParms = false; customHttpAlias = null; isCustomPath = false; if (homePageSiteRoot && isHomeTab && !hasPath) + // && !isDefaultCultureCode - not working for non-language specifc custom root urls { - newTabPath = "/"; //site root for home page + newTabPath = "/"; // site root for home page } else { - //build the tab path and check for space replacement + // build the tab path and check for space replacement string baseTabPath = TabIndexController.GetTabPath(tab, options, parentTraceId); - //this is the new tab path + // this is the new tab path newTabPath = baseTabPath; - //871 : case insensitive compare for culture code, all lookups done on lower case - string cultureCodeKey = ""; + + // 871 : case insensitive compare for culture code, all lookups done on lower case + string cultureCodeKey = string.Empty; if (cultureCode != null) { cultureCodeKey = cultureCode.ToLowerInvariant(); } bool checkForCustomHttpAlias = false; - //get a custom tab name if redirects are being used + + // get a custom tab name if redirects are being used SharedDictionary customAliasForTabs = null; SharedDictionary> urlDict; - //886 : don't fetch custom urls for host tabs (host tabs can't have redirects or custom Urls) + + // 886 : don't fetch custom urls for host tabs (host tabs can't have redirects or custom Urls) if (tab.PortalID > -1) { urlDict = CustomUrlDictController.FetchCustomUrlDictionary(tab.PortalID, false, false, settings, out customAliasForTabs, parentTraceId); @@ -194,19 +239,19 @@ internal static string GetTabPath(TabInfo tab, else { urlDict = new SharedDictionary>(); - //create dummy dictionary for this tab + + // create dummy dictionary for this tab } if (ignoreCustomRedirects == false) { - //if not ignoring the custom redirects, look for the Url of the page in this list - //this will be used as the page path if there is one. - + // if not ignoring the custom redirects, look for the Url of the page in this list + // this will be used as the page path if there is one. using (urlDict.GetReadLock()) { if (urlDict.ContainsKey(tab.TabID)) { - //we want the custom value + // we want the custom value string customTabPath = null; SharedDictionary tabpaths = urlDict[tab.TabID]; @@ -216,20 +261,23 @@ internal static string GetTabPath(TabInfo tab, { customTabPath = tabpaths[cultureCodeKey]; dropLangParms = true; - //the url is based on a custom value which has embedded language parms, therefore don't need them in the url + + // the url is based on a custom value which has embedded language parms, therefore don't need them in the url } else { - if (isDefaultCultureCode && tabpaths.ContainsKey("")) + if (isDefaultCultureCode && tabpaths.ContainsKey(string.Empty)) { - customTabPath = tabpaths[""]; - //dropLangParms = true;//drop the language parms if they exist, because this is the default language + customTabPath = tabpaths[string.Empty]; + + // dropLangParms = true;//drop the language parms if they exist, because this is the default language } } } + if (customTabPath != null) { - //770 : pull out custom http alias if in string + // 770 : pull out custom http alias if in string int aliasSeparator = customTabPath.IndexOf("::", StringComparison.Ordinal); if (aliasSeparator > 0) { @@ -241,14 +289,15 @@ internal static string GetTabPath(TabInfo tab, newTabPath = customTabPath; } } - if (newTabPath == "" && hasPath) + + if (newTabPath == string.Empty && hasPath) { - //can't pass back a custom path which is blank if there are path segments to the requested final Url - newTabPath = baseTabPath; //revert back to the standard DNN page path + // can't pass back a custom path which is blank if there are path segments to the requested final Url + newTabPath = baseTabPath; // revert back to the standard DNN page path } else { - isCustomPath = true; //we are providing a custom Url + isCustomPath = true; // we are providing a custom Url } } else @@ -260,10 +309,11 @@ internal static string GetTabPath(TabInfo tab, else { checkForCustomHttpAlias = true; - //always want to check for custom alias, even when we don't want to see any custom redirects + + // always want to check for custom alias, even when we don't want to see any custom redirects } - //770 : check for custom alias in these tabs + // 770 : check for custom alias in these tabs if (checkForCustomHttpAlias && customAliasForTabs != null) { string key = tab.TabID.ToString() + ":" + cultureCodeKey; @@ -271,9 +321,9 @@ internal static string GetTabPath(TabInfo tab, { if (customAliasForTabs.ContainsKey(key)) { - //this tab uses a custom alias + // this tab uses a custom alias customHttpAlias = customAliasForTabs[key]; - isCustomPath = true; //using custom alias + isCustomPath = true; // using custom alias } } } @@ -284,36 +334,39 @@ internal static string GetTabPath(TabInfo tab, if (!string.IsNullOrEmpty(tabCultureCode)) { dropLangParms = true; - //if the tab has a specified culture code, then drop the language parameters from the friendly Url + + // if the tab has a specified culture code, then drop the language parameters from the friendly Url } } - //make lower case if necessary + + // make lower case if necessary newTabPath = AdvancedFriendlyUrlProvider.ForceLowerCaseIfAllowed(tab, newTabPath, settings); } + return newTabPath; } internal static bool IsTabHomePage(TabInfo tab, PortalSettings portalSettings) { - bool isTabHomePage = (tab.TabID == portalSettings.HomeTabId); + bool isTabHomePage = tab.TabID == portalSettings.HomeTabId; if (!isTabHomePage) { - //756: check if content localization is switched on before checking for other languages + // 756: check if content localization is switched on before checking for other languages if (Host.Host.EnableBrowserLanguage) { - //check the localised versions of the tab + // check the localised versions of the tab TabInfo defaultLangTab = tab.DefaultLanguageTab; if (defaultLangTab != null) { - //is the default language tab the home tab? + // is the default language tab the home tab? if (defaultLangTab.TabID == portalSettings.HomeTabId) { isTabHomePage = true; } else { - //iterate through the other localised versions of this tab and check if they are the same - //as the home tabid + // iterate through the other localised versions of this tab and check if they are the same + // as the home tabid Dictionary localizedTabs = tab.LocalizedTabs; if (localizedTabs.Values.Any(localTab => localTab.TabID == portalSettings.HomeTabId)) { @@ -323,11 +376,11 @@ internal static bool IsTabHomePage(TabInfo tab, PortalSettings portalSettings) } else { - //check if this tab belongs to the default language, in which case it is already the default language tab + // check if this tab belongs to the default language, in which case it is already the default language tab string cultureCode = tab.CultureCode; - if (String.Compare(cultureCode, portalSettings.DefaultLanguage, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(cultureCode, portalSettings.DefaultLanguage, StringComparison.OrdinalIgnoreCase) == 0) { - //get the localized versions and see if this matches + // get the localized versions and see if this matches Dictionary localizedTabs = tab.LocalizedTabs; if (localizedTabs.Values.Any(localTab => localTab.TabID == portalSettings.HomeTabId)) { @@ -337,56 +390,8 @@ internal static bool IsTabHomePage(TabInfo tab, PortalSettings portalSettings) } } } + return isTabHomePage; - } - - #endregion - - #region Public Methods - - public static string BuildTabPathWithReplacement(TabInfo tab, FriendlyUrlOptions options, Guid parentTraceId) - { - string path = ""; - if ((tab.ParentId > -1)) - { - TabInfo parentTab = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false); - //822 : don't assume parent tab is going to exist - database might be corrupted - //896 : check to make sure tabid and parentid are different - or stack overflow occurs with terminal loop - if (parentTab != null && parentTab.TabID != tab.TabID) - { - path = BuildTabPathWithReplacement(parentTab, options, parentTraceId); - } - } - bool modified; - path = AppendToTabPath(path, tab, options, out modified); - - return path; - } - - /// - /// Replaces the diacritic characters in a path with other values - /// - /// - /// - /// - public static string ReplaceDiacritics(string tabPath, out bool replacedDiacritic) - { - string nmTabPath = tabPath.Normalize(NormalizationForm.FormD); - var sb = new StringBuilder(); - for (int i = 0; i < nmTabPath.Length; i++) - { - char c = nmTabPath[i]; - if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) - { - sb.Append(c); - } - } - string result = sb.ToString(); - replacedDiacritic = String.CompareOrdinal(tabPath, result) != 0; - return sb.ToString(); - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Entities/Urls/UrlAction.cs b/DNN Platform/Library/Entities/Urls/UrlAction.cs index 99b8a187c54..9ddc42cd9a0 100644 --- a/DNN Platform/Library/Entities/Urls/UrlAction.cs +++ b/DNN Platform/Library/Entities/Urls/UrlAction.cs @@ -1,118 +1,127 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Entities.Portals; + /// - /// The UrlAction class keeps state of the current Request throughout the rewriting process + /// The UrlAction class keeps state of the current Request throughout the rewriting process. /// public class UrlAction { - //829 add in constructor that works around physical path length restriction + private List _licensedProviders; + private PortalAliasInfo _portalAlias; + + // 829 add in constructor that works around physical path length restriction public UrlAction(HttpRequest request) { - BrowserType = BrowserTypes.Normal; - CanRewrite = StateBoolean.NotSet; - Action = ActionType.Continue; - string physicalPath = ""; + this.BrowserType = BrowserTypes.Normal; + this.CanRewrite = StateBoolean.NotSet; + this.Action = ActionType.Continue; + string physicalPath = string.Empty; try { physicalPath = request.PhysicalPath; } catch (PathTooLongException) { - //don't handle exception, but put something into the physical path - physicalPath = request.ApplicationPath; //will be no file for this location - VirtualPath = StateBoolean.True; + // don't handle exception, but put something into the physical path + physicalPath = request.ApplicationPath; // will be no file for this location + this.VirtualPath = StateBoolean.True; } catch (ArgumentException) { - //don't handle exception, but put something into the physical path - physicalPath = request.ApplicationPath; //will be no file for this location - VirtualPath = StateBoolean.True; + // don't handle exception, but put something into the physical path + physicalPath = request.ApplicationPath; // will be no file for this location + this.VirtualPath = StateBoolean.True; } finally { - Constructor(request.Url.Scheme, request.ApplicationPath, physicalPath); + this.Constructor(request.Url.Scheme, request.ApplicationPath, physicalPath); } } public UrlAction(string scheme, string applicationPath, string physicalPath) { - BrowserType = BrowserTypes.Normal; - CanRewrite = StateBoolean.NotSet; - Action = ActionType.Continue; - Constructor(scheme, applicationPath, physicalPath); + this.BrowserType = BrowserTypes.Normal; + this.CanRewrite = StateBoolean.NotSet; + this.Action = ActionType.Continue; + this.Constructor(scheme, applicationPath, physicalPath); } + + public Uri Url { get; set; } private void Constructor(string scheme, string applicationPath, string physicalPath) { if (scheme.EndsWith("://") == false) { - Scheme = scheme + "://"; + this.Scheme = scheme + "://"; } else { - Scheme = scheme; + this.Scheme = scheme; } - ApplicationPath = applicationPath; - string domainPath = applicationPath.Replace(scheme, ""); - DomainName = domainPath.Contains("/") ? domainPath.Substring(0, domainPath.IndexOf('/')) : domainPath; - PhysicalPath = physicalPath; - PortalId = -1; - TabId = -1; - Reason = RedirectReason.Not_Redirected; - FriendlyRewrite = false; - BypassCachedDictionary = false; - VirtualPath = StateBoolean.NotSet; - IsSecureConnection = false; - IsSSLOffloaded = false; - DebugMessages = new List(); - CultureCode = null; - } - - #region Private Members - - private List _licensedProviders; - private PortalAliasInfo _portalAlias; - - #endregion - - #region Public Properties - - public Uri Url { get; set; } + + this.ApplicationPath = applicationPath; + string domainPath = applicationPath.Replace(scheme, string.Empty); + this.DomainName = domainPath.Contains("/") ? domainPath.Substring(0, domainPath.IndexOf('/')) : domainPath; + this.PhysicalPath = physicalPath; + this.PortalId = -1; + this.TabId = -1; + this.Reason = RedirectReason.Not_Redirected; + this.FriendlyRewrite = false; + this.BypassCachedDictionary = false; + this.VirtualPath = StateBoolean.NotSet; + this.IsSecureConnection = false; + this.IsSSLOffloaded = false; + this.DebugMessages = new List(); + this.CultureCode = null; + } + public bool DoRewrite { get; set; } + public bool FriendlyRewrite { get; set; } - //friendlyRewrite means it was rewritten without looking up the tabid in the url + + // friendlyRewrite means it was rewritten without looking up the tabid in the url public bool BypassCachedDictionary { get; set; } + public string RewritePath { get; set; } + public string RawUrl { get; set; } + public string DebugData { get; set; } + public string PhysicalPath { get; set; } + public StateBoolean VirtualPath { get; set; } + public string ApplicationPath { get; set; } + public bool RebuildRequested { get; set; } + public string FinalUrl { get; set; } + public string Scheme { get; set; } + public bool IsSecureConnection { get; set; } + public bool IsSSLOffloaded { get; set; } + public string DomainName { get; set; } + public Exception Ex { get; set; } + public string dictKey { get; set; } + public string dictVal { get; set; } + public List DebugMessages { get; set; } public int TabId { get; set; } @@ -135,41 +144,42 @@ private void Constructor(string scheme, string applicationPath, string physicalP public StateBoolean CanRewrite { get; set; } - //the alias for the current request + // the alias for the current request public PortalAliasInfo PortalAlias { - get { return _portalAlias; } + get { return this._portalAlias; } + set { if (value != null) { - PortalId = value.PortalID; - HttpAlias = value.HTTPAlias; + this.PortalId = value.PortalID; + this.HttpAlias = value.HTTPAlias; } - _portalAlias = value; + + this._portalAlias = value; } } - //the primary alias, if different to the current alias + + // the primary alias, if different to the current alias public PortalAliasInfo PrimaryAlias { get; set; } - public DotNetNuke.Entities.Portals.PortalSettings.PortalAliasMapping PortalAliasMapping {get; set;} + + public DotNetNuke.Entities.Portals.PortalSettings.PortalAliasMapping PortalAliasMapping { get; set; } + public bool CustomParmRewrite { get; set; } - //737 : mobile browser identificatino + // 737 : mobile browser identificatino public BrowserTypes BrowserType { get; private set; } - public bool IsPhysicalResource { get; set; } - - #endregion - - #region public methods - + public bool IsPhysicalResource { get; set; } + public string UnlicensedProviderMessage { get; set; } public bool UnlicensedProviderCalled { get; set; } /// - /// Sets the action value, but checks to ensure that the action is - /// not being 'downgraded' (example: cannot set 'Redirect301' to 'CheckFor301') + /// Sets the action value, but checks to ensure that the action is + /// not being 'downgraded' (example: cannot set 'Redirect301' to 'CheckFor301'). /// /// public void SetActionWithNoDowngrade(ActionType newAction) @@ -177,78 +187,81 @@ public void SetActionWithNoDowngrade(ActionType newAction) switch (newAction) { case ActionType.CheckFor301: - if (Action != ActionType.Redirect301 - && Action != ActionType.Redirect302 - && Action != ActionType.Redirect302Now - && Action != ActionType.Output404) + if (this.Action != ActionType.Redirect301 + && this.Action != ActionType.Redirect302 + && this.Action != ActionType.Redirect302Now + && this.Action != ActionType.Output404) { - Action = newAction; + this.Action = newAction; } + break; default: - Action = newAction; + this.Action = newAction; break; } } - - + public void AddLicensedProviders(List licensedProviders) { - if (_licensedProviders == null) + if (this._licensedProviders == null) { - _licensedProviders = new List(); + this._licensedProviders = new List(); } + foreach (string lp in licensedProviders) { - if (_licensedProviders.Contains(lp.ToLowerInvariant()) == false) + if (this._licensedProviders.Contains(lp.ToLowerInvariant()) == false) { - _licensedProviders.Add(lp.ToLowerInvariant()); + this._licensedProviders.Add(lp.ToLowerInvariant()); } } } public void AddLicensedProvider(string providerName) { - if (_licensedProviders == null) + if (this._licensedProviders == null) { - _licensedProviders = new List(); + this._licensedProviders = new List(); } - if (_licensedProviders.Contains(providerName.ToLowerInvariant()) == false) + + if (this._licensedProviders.Contains(providerName.ToLowerInvariant()) == false) { - _licensedProviders.Add(providerName.ToLowerInvariant()); + this._licensedProviders.Add(providerName.ToLowerInvariant()); } } public bool IsProviderLicensed(string providerName) { - if (_licensedProviders == null) + if (this._licensedProviders == null) { return false; } - return _licensedProviders.Contains(providerName.ToLowerInvariant()); + + return this._licensedProviders.Contains(providerName.ToLowerInvariant()); } /// - /// Copies the original request path to the OriginalPath variables (originalPath, originanPathNoAlias) + /// Copies the original request path to the OriginalPath variables (originalPath, originanPathNoAlias). /// /// /// public void SetOriginalPath(string path, FriendlyUrlSettings settings) { - OriginalPath = path; - OriginalPathNoAlias = path; - if (!string.IsNullOrEmpty(HttpAlias) && path.Contains(HttpAlias)) + this.OriginalPath = path; + this.OriginalPathNoAlias = path; + if (!string.IsNullOrEmpty(this.HttpAlias) && path.Contains(this.HttpAlias)) { - OriginalPathNoAlias = path.Substring(path.IndexOf(HttpAlias, StringComparison.Ordinal) + HttpAlias.Length); + this.OriginalPathNoAlias = path.Substring(path.IndexOf(this.HttpAlias, StringComparison.Ordinal) + this.HttpAlias.Length); } } public void SetBrowserType(HttpRequest request, HttpResponse response, FriendlyUrlSettings settings) { - //set the mobile browser type + // set the mobile browser type if (request != null && response != null && settings != null) { - BrowserType = FriendlyUrlController.GetBrowserType(request, response, settings); + this.BrowserType = FriendlyUrlController.GetBrowserType(request, response, settings); } } @@ -259,24 +272,22 @@ public void SetRedirectAllowed(string path, FriendlyUrlSettings settings) { if (!string.IsNullOrEmpty(regexExpr)) { - //if a regex match, redirect Not allowed - RedirectAllowed = !Regex.IsMatch(path, regexExpr, RegexOptions.IgnoreCase); + // if a regex match, redirect Not allowed + this.RedirectAllowed = !Regex.IsMatch(path, regexExpr, RegexOptions.IgnoreCase); } else { - RedirectAllowed = true; + this.RedirectAllowed = true; } } catch (Exception ex) { - RedirectAllowed = true; //default : true, unless regex allows it. So if regex causes an exception - //then we should allow the redirect - + this.RedirectAllowed = true; // default : true, unless regex allows it. So if regex causes an exception + + // then we should allow the redirect UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", this); - Ex = ex; + this.Ex = ex; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs b/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs index 82ae0bcf2ac..130d7ee3769 100644 --- a/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs +++ b/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public class UrlEnumHelpers @@ -15,6 +15,7 @@ public static BrowserTypes FromString(string value) result = BrowserTypes.Mobile; break; } + return result; } } diff --git a/DNN Platform/Library/Entities/Urls/UrlEnums.cs b/DNN Platform/Library/Entities/Urls/UrlEnums.cs index d42309cec40..75241274462 100644 --- a/DNN Platform/Library/Entities/Urls/UrlEnums.cs +++ b/DNN Platform/Library/Entities/Urls/UrlEnums.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { internal static class UrlEnums @@ -10,7 +10,7 @@ internal enum TabKeyPreference { TabOK, TabRedirected, - TabDeleted + TabDeleted, } } } diff --git a/DNN Platform/Library/Entities/Urls/UrlFormatType.cs b/DNN Platform/Library/Entities/Urls/UrlFormatType.cs index 55e9f58496a..cc6ee55f162 100644 --- a/DNN Platform/Library/Entities/Urls/UrlFormatType.cs +++ b/DNN Platform/Library/Entities/Urls/UrlFormatType.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum UrlFormatType { SearchFriendly, HumanFriendly, - Advanced + Advanced, } } diff --git a/DNN Platform/Library/Entities/Urls/UrlProcessType.cs b/DNN Platform/Library/Entities/Urls/UrlProcessType.cs index d081243eeee..ec6f491e565 100644 --- a/DNN Platform/Library/Entities/Urls/UrlProcessType.cs +++ b/DNN Platform/Library/Entities/Urls/UrlProcessType.cs @@ -1,15 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { public enum UrlProcessType { - Rewriting - , - Redirecting - , - Replacing + Rewriting, + Redirecting, + Replacing, } } diff --git a/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs b/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs index cb788600349..a8caf77e05e 100644 --- a/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs +++ b/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + /// - /// Abstract class to allow derived classes of different implementations of Url Rewriter + /// Abstract class to allow derived classes of different implementations of Url Rewriter. /// public abstract class UrlRewriterBase { @@ -26,7 +21,8 @@ public abstract class UrlRewriterBase protected static void AutoAddAlias(HttpContext context) { var portalId = Host.Host.HostPortalID; - //the domain name was not found so try using the host portal's first alias + + // the domain name was not found so try using the host portal's first alias if (portalId > Null.NullInteger) { var portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = Globals.GetDomainName(context.Request, true) }; diff --git a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs index 3fa024f37dc..464e17525a8 100644 --- a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs +++ b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs @@ -1,57 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Caching; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; + using System.Reflection; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; + public static class UrlRewriterUtils { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UrlRewriterUtils)); /// - /// Return a FriendlyUrlOptions object from the provider settings + /// Return a FriendlyUrlOptions object from the provider settings. /// /// /// public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings settings) { - var options = new FriendlyUrlOptions - { - PunctuationReplacement = (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) - ? settings.ReplaceSpaceWith - : String.Empty, - SpaceEncoding = settings.SpaceEncodingValue, - MaxUrlPathLength = 200, - ConvertDiacriticChars = settings.AutoAsciiConvert, - RegexMatch = settings.RegexMatch, - IllegalChars = settings.IllegalChars, - ReplaceChars = settings.ReplaceChars, - ReplaceDoubleChars = settings.ReplaceDoubleChars, - ReplaceCharWithChar = settings.ReplaceCharacterDictionary, - PageExtension = (settings.PageExtensionUsageType == PageExtensionUsageType.Never) - ? "" - : settings.PageExtension - }; + var options = new FriendlyUrlOptions + { + PunctuationReplacement = (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) + ? settings.ReplaceSpaceWith + : string.Empty, + SpaceEncoding = settings.SpaceEncodingValue, + MaxUrlPathLength = 200, + ConvertDiacriticChars = settings.AutoAsciiConvert, + RegexMatch = settings.RegexMatch, + IllegalChars = settings.IllegalChars, + ReplaceChars = settings.ReplaceChars, + ReplaceDoubleChars = settings.ReplaceDoubleChars, + ReplaceCharWithChar = settings.ReplaceCharacterDictionary, + PageExtension = (settings.PageExtensionUsageType == PageExtensionUsageType.Never) + ? string.Empty + : settings.PageExtension, + }; return options; } /// - /// Return an extended FriendlyUrlOptions object for Custom URLs checkings + /// Return an extended FriendlyUrlOptions object for Custom URLs checkings. /// /// /// @@ -64,31 +60,31 @@ public static FriendlyUrlOptions ExtendOptionsForCustomURLs(FriendlyUrlOptions o MaxUrlPathLength = options.MaxUrlPathLength, ConvertDiacriticChars = options.ConvertDiacriticChars, RegexMatch = options.RegexMatch.Replace("[^", "[^./"), - IllegalChars = options.IllegalChars.Replace("/", ""), - ReplaceChars = options.ReplaceChars.Replace("/", ""), + IllegalChars = options.IllegalChars.Replace("/", string.Empty), + ReplaceChars = options.ReplaceChars.Replace("/", string.Empty), ReplaceDoubleChars = options.ReplaceDoubleChars, ReplaceCharWithChar = options.ReplaceCharWithChar, - PageExtension = options.PageExtension + PageExtension = options.PageExtension, }; return result; } /// - /// Logs the 404 error to a table for later checking + /// Logs the 404 error to a table for later checking. /// /// /// /// public static void Log404(HttpRequest request, FriendlyUrlSettings settings, UrlAction result) { - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), - LogPortalID = (result.PortalAlias != null) ? result.PortalId : -1 - }; - log.LogProperties.Add(new LogDetailInfo("TabId", (result.TabId > 0) ? result.TabId.ToString() : String.Empty)); - log.LogProperties.Add(new LogDetailInfo("PortalAlias", (result.PortalAlias != null) ? result.PortalAlias.HTTPAlias : String.Empty)); - log.LogProperties.Add(new LogDetailInfo("OriginalUrl", result.RawUrl)); + var log = new LogInfo + { + LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), + LogPortalID = (result.PortalAlias != null) ? result.PortalId : -1, + }; + log.LogProperties.Add(new LogDetailInfo("TabId", (result.TabId > 0) ? result.TabId.ToString() : string.Empty)); + log.LogProperties.Add(new LogDetailInfo("PortalAlias", (result.PortalAlias != null) ? result.PortalAlias.HTTPAlias : string.Empty)); + log.LogProperties.Add(new LogDetailInfo("OriginalUrl", result.RawUrl)); if (request != null) { @@ -103,6 +99,7 @@ public static void Log404(HttpRequest request, FriendlyUrlSettings settings, Url { log.LogProperties.Add(new LogDetailInfo("Referer", request.Headers["Referer"])); } + log.LogProperties.Add(new LogDetailInfo("Url", request.Url.AbsoluteUri)); log.LogProperties.Add(new LogDetailInfo("UserAgent", request.UserAgent)); log.LogProperties.Add(new LogDetailInfo("HostAddress", request.UserHostAddress)); @@ -113,7 +110,7 @@ public static void Log404(HttpRequest request, FriendlyUrlSettings settings, Url } /// - /// logs an exception once per cache-lifetime + /// logs an exception once per cache-lifetime. /// /// /// @@ -122,20 +119,22 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction { if (ex != null) { - //831 : improve exception logging by logging custom properties instead of just the raw exception - //this logic prevents a site logging an exception for every request made. Instead - //the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. - //create a cache key for this exception type + // 831 : improve exception logging by logging custom properties instead of just the raw exception + // this logic prevents a site logging an exception for every request made. Instead + // the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. + // create a cache key for this exception type string cacheKey = ex.GetType().ToString(); - //see if there is an existing object logged for this exception type + + // see if there is an existing object logged for this exception type object existingEx = DataCache.GetCache(cacheKey); if (existingEx == null) { - //if there was no existing object logged for this exception type, this is a new exception + // if there was no existing object logged for this exception type, this is a new exception DateTime expire = DateTime.Now.AddHours(1); DataCache.SetCache(cacheKey, cacheKey, expire); - //just store the cache key - it doesn't really matter - //create a log event + + // just store the cache key - it doesn't really matter + // create a log event var log = new LogInfo { LogTypeKey = "GENERAL_EXCEPTION" }; log.AddProperty("Url Processing Exception", "Exception in Url Rewriting Process"); log.AddProperty("Http Status", status); @@ -173,6 +172,7 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction { log.AddProperty("Result", "Result value null"); } + log.AddProperty("Exception Type", ex.GetType().ToString()); log.AddProperty("Message", ex.Message); log.AddProperty("Stack Trace", ex.StackTrace); @@ -181,26 +181,27 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction log.AddProperty("Inner Exception Message", ex.InnerException.Message); log.AddProperty("Inner Exception Stacktrace", ex.InnerException.StackTrace); } + log.BypassBuffering = true; LogController.Instance.AddLog(log); - //Log this error in lig4net + // Log this error in lig4net Logger.Error(ex); } } } - /// - /// Clean Page name to remove page extension. - /// - /// page name. - /// friendly url settings. - /// language. - /// - public static string CleanExtension(string value, FriendlyUrlSettings settings, string langParms) - { - bool replaced; - return RewriteController.CleanExtension(value, settings, langParms, out replaced); - } + /// + /// Clean Page name to remove page extension. + /// + /// page name. + /// friendly url settings. + /// language. + /// + public static string CleanExtension(string value, FriendlyUrlSettings settings, string langParms) + { + bool replaced; + return RewriteController.CleanExtension(value, settings, langParms, out replaced); + } } } diff --git a/DNN Platform/Library/Entities/Urls/XmlHelpers.cs b/DNN Platform/Library/Entities/Urls/XmlHelpers.cs index 73b6c486fff..af4e292721e 100644 --- a/DNN Platform/Library/Entities/Urls/XmlHelpers.cs +++ b/DNN Platform/Library/Entities/Urls/XmlHelpers.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Entities.Tabs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Urls { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Tabs; + /// - /// The Xml Helpers class is used to read in parameter rewrite/replace/redirect rules from the friendlyUrlParms.config file + /// The Xml Helpers class is used to read in parameter rewrite/replace/redirect rules from the friendlyUrlParms.config file. /// internal static class XmlHelpers { /// - /// Returns a tab id from either a raw tabId, or a list of tab names delimited by ';' + /// Returns a tab id from either a raw tabId, or a list of tab names delimited by ';'. /// /// /// @@ -28,6 +28,7 @@ internal static List TabIdsFromAttributes(string tabIdsRaw, string tabNames { messages = new List(); } + var tabIds = new List(); if (!string.IsNullOrEmpty(tabIdsRaw)) { @@ -35,40 +36,41 @@ internal static List TabIdsFromAttributes(string tabIdsRaw, string tabNames foreach (string rawTabId in rawTabids) { int tabId; - if (Int32.TryParse(rawTabId, out tabId)) + if (int.TryParse(rawTabId, out tabId)) { tabIds.Add(tabId); } } } + if (tabNames != null) { - //get the portal by name + // get the portal by name if (tabNames == "All") { tabIds.Add(-1); } else { - //loop through all specified tab names + // loop through all specified tab names foreach (string tabName in tabNames.Split(';')) { - if (String.Compare(tabName, "default.aspx", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(tabName, "default.aspx", StringComparison.OrdinalIgnoreCase) == 0) { - //default.aspx is marked with a -2 tabid + // default.aspx is marked with a -2 tabid tabIds.Add(-2); } else { - //593 : add in site root rewriting processing + // 593 : add in site root rewriting processing if (tabName == "/") { - //site root marked with a -3 tabid + // site root marked with a -3 tabid tabIds.Add(-3); } else { - //portal id specified : specific portal + // portal id specified : specific portal TabInfo tab = TabController.Instance.GetTabByName(tabName, portalId); if (tab != null) { @@ -83,6 +85,7 @@ internal static List TabIdsFromAttributes(string tabIdsRaw, string tabNames } } } + return tabIds; } } diff --git a/DNN Platform/Library/Entities/Users/Exceptions/InvalidVerificationCodeException.cs b/DNN Platform/Library/Entities/Users/Exceptions/InvalidVerificationCodeException.cs index 8091ad61d10..935ceeab33e 100644 --- a/DNN Platform/Library/Entities/Users/Exceptions/InvalidVerificationCodeException.cs +++ b/DNN Platform/Library/Entities/Users/Exceptions/InvalidVerificationCodeException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + [Serializable] public class InvalidVerificationCodeException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Exceptions/UserAlreadyVerifiedException.cs b/DNN Platform/Library/Entities/Users/Exceptions/UserAlreadyVerifiedException.cs index f0557d85fc8..96d9478b4c1 100644 --- a/DNN Platform/Library/Entities/Users/Exceptions/UserAlreadyVerifiedException.cs +++ b/DNN Platform/Library/Entities/Users/Exceptions/UserAlreadyVerifiedException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + [Serializable] public class UserAlreadyVerifiedException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Exceptions/UserDoesNotExistException.cs b/DNN Platform/Library/Entities/Users/Exceptions/UserDoesNotExistException.cs index 39d1b9fb754..0f1d050581b 100644 --- a/DNN Platform/Library/Entities/Users/Exceptions/UserDoesNotExistException.cs +++ b/DNN Platform/Library/Entities/Users/Exceptions/UserDoesNotExistException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + [Serializable] public class UserDoesNotExistException : Exception { diff --git a/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs b/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs index 71256e08cb5..ef7fc0eecb6 100644 --- a/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs +++ b/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { public interface IFollowerEventHandlers { void FollowRequested(object sender, RelationshipEventArgs args); + void UnfollowRequested(object sender, RelationshipEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs b/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs index 19405b85ab5..afdd6a034d4 100644 --- a/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs +++ b/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Friends { + using DotNetNuke.Entities.Users; + public interface IFriendshipEventHandlers { void FriendshipRequested(object sender, RelationshipEventArgs args); + void FriendshipAccepted(object sender, RelationshipEventArgs args); + void FriendshipDeleted(object sender, RelationshipEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Users/IUserController.cs b/DNN Platform/Library/Entities/Users/IUserController.cs index 50a7f97f0bb..513a74e83d7 100644 --- a/DNN Platform/Library/Entities/Users/IUserController.cs +++ b/DNN Platform/Library/Entities/Users/IUserController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System.Collections.Generic; + public interface IUserController { UserInfo GetCurrentUserInfo(); @@ -13,90 +13,90 @@ public interface IUserController UserInfo GetUser(int portalId, int userId); /// - /// Get a user based on their display name and portal + /// Get a user based on their display name and portal. /// - /// the portalid - /// the displayname - /// The User as a UserInfo object + /// the portalid. + /// the displayname. + /// The User as a UserInfo object. UserInfo GetUserByDisplayname(int portalId, string displayName); /// - /// GetUser retrieves a User from the DataStore + /// GetUser retrieves a User from the DataStore. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The Id of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. UserInfo GetUserById(int portalId, int userId); /// - /// Get a filtered list of users based on a number of criteria and filters - utilised for advanced searches + /// Get a filtered list of users based on a number of criteria and filters - utilised for advanced searches. /// - /// the portalid of the user(s) - /// the userid accessing - for determining correct visibility permissions - /// for filtering relationships on - /// for filtering by roles - /// for filtering by relationships - /// determines visibility - /// 0 based page index - /// page size - /// sort field - /// sort flag indicating whether sort is asc or desc - /// list of property names to filter - /// list of property values to filter - /// Users as a list of UserInfo objects + /// the portalid of the user(s). + /// the userid accessing - for determining correct visibility permissions. + /// for filtering relationships on. + /// for filtering by roles. + /// for filtering by relationships. + /// determines visibility. + /// 0 based page index. + /// page size. + /// sort field. + /// sort flag indicating whether sort is asc or desc. + /// list of property names to filter. + /// list of property values to filter. + /// Users as a list of UserInfo objects. IList GetUsersAdvancedSearch(int portalId, int userId, int filterUserId, int filterRoleId, int relationTypeId, bool isAdmin, int pageIndex, int pageSize, string sortColumn, bool sortAscending, string propertyNames, string propertyValues); /// - /// Get a filtered list of users based on a set of simple filters - utilised for basic searches + /// Get a filtered list of users based on a set of simple filters - utilised for basic searches. /// - /// the portalid of the user(s) - /// 0 based page index - /// page size - /// sort field - /// sort flag indicating whether sort is asc or desc - /// list of property names to filter - /// list of property values to filter - /// Users as a list of UserInfo objects + /// the portalid of the user(s). + /// 0 based page index. + /// page size. + /// sort field. + /// sort flag indicating whether sort is asc or desc. + /// list of property names to filter. + /// list of property values to filter. + /// Users as a list of UserInfo objects. IList GetUsersBasicSearch(int portalId, int pageIndex, int pageSize, string sortColumn, bool sortAscending, string propertyName, string propertyValue); /// - /// Return User Profile Picture relative Url + /// Return User Profile Picture relative Url. /// - /// User Id - /// Width in pixel - /// Height in pixel - /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal + /// User Id. + /// Width in pixel. + /// Height in pixel. + /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal. /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = UserController.Instance.GetUserProfilePictureUrl(userInfo.UserID, 32, 32) + /// code behind - avatar.ImageUrl = UserController.Instance.GetUserProfilePictureUrl(userInfo.UserID, 32, 32). /// string GetUserProfilePictureUrl(int userId, int width, int height); /// - /// Return User Profile Picture relative Url + /// Return User Profile Picture relative Url. /// - /// Portal Id - /// User Id - /// Width in pixel - /// Height in pixel - /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal + /// Portal Id. + /// User Id. + /// Width in pixel. + /// Height in pixel. + /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal. /// IMPORTANT NOTE: this overloaded method does not depend on the current portal setting so it can be used - /// in background threads or scheduler jobs. + /// in background threads or scheduler jobs. /// string GetUserProfilePictureUrl(int portalId, int userId, int width, int height); /// /// Check username parameter against : - /// Invalid charaters, - /// length check for 5 chars, - /// for space between username + /// Invalid charaters, + /// length check for 5 chars, + /// for space between username. /// - /// UserName as string - /// true/false + /// UserName as string. + /// true/false. bool IsValidUserName(string userName); } } diff --git a/DNN Platform/Library/Entities/Users/IUserEventHandlers.cs b/DNN Platform/Library/Entities/Users/IUserEventHandlers.cs index a0c1197dc11..2d53aa74a47 100644 --- a/DNN Platform/Library/Entities/Users/IUserEventHandlers.cs +++ b/DNN Platform/Library/Entities/Users/IUserEventHandlers.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { public interface IUserEventHandlers diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs index f425c34cecd..701ae832ed0 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs @@ -1,35 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Membership { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + public class MembershipPasswordController - { - #region Private Members - - private readonly DataProvider _dataProvider = DataProvider.Instance(); - - #endregion - - #region Private functions + { + private readonly DataProvider _dataProvider = DataProvider.Instance(); + + /// + /// returns the password history of the supplied user. + /// + /// list of PasswordHistory objects. + public List GetPasswordHistory(int userId) + { + return this.GetPasswordHistory(userId, Null.NullInteger); + } + /// + /// returns the password history of the supplied user. + /// + /// portalid - futureproofing against any setting become site level. + /// list of PasswordHistory objects. + public List GetPasswordHistory(int userId, int portalId) + { + var settings = new MembershipPasswordSettings(portalId); + List history = + CBO.FillCollection(this._dataProvider.GetPasswordHistory(userId, settings.NumberOfPasswordsStored, settings.NumberOfDaysBeforePasswordReuse)); + return history; + } + private void AddPasswordHistory(int userId, string password, int passwordsRetained, int daysRetained) { using (HashAlgorithm ha = HashAlgorithm.Create()) { - byte[] newSalt = GetRandomSaltValue(); + byte[] newSalt = this.GetRandomSaltValue(); byte[] bytePassword = Encoding.Unicode.GetBytes(password); var inputBuffer = new byte[bytePassword.Length + 16]; Buffer.BlockCopy(bytePassword, 0, inputBuffer, 0, bytePassword.Length); @@ -37,7 +54,7 @@ private void AddPasswordHistory(int userId, string password, int passwordsRetain byte[] bhashedPassword = ha.ComputeHash(inputBuffer); string hashedPassword = Convert.ToBase64String(bhashedPassword); - _dataProvider.AddPasswordHistory(userId, hashedPassword, Convert.ToBase64String(newSalt), passwordsRetained, daysRetained); + this._dataProvider.AddPasswordHistory(userId, hashedPassword, Convert.ToBase64String(newSalt), passwordsRetained, daysRetained); } } @@ -49,84 +66,62 @@ private byte[] GetRandomSaltValue() rcsp.GetBytes(bSalt); return bSalt; } - } - - #endregion + } /// - /// returns the password history of the supplied user + /// checks to see if the password is in history and adds it if it is not. /// - /// list of PasswordHistory objects - public List GetPasswordHistory(int userId) + /// portalid - futureproofing against any setting become site level. + /// users new password suggestion. + /// true if password has not been used in users history, false otherwise. + public bool IsPasswordInHistory(int userId, int portalId, string newPassword) { - return GetPasswordHistory(userId, Null.NullInteger); + return this.IsPasswordInHistory(userId, portalId, newPassword, true); } /// - /// returns the password history of the supplied user + /// checks to see if the password is in history and adds it if it is not. /// - /// portalid - futureproofing against any setting become site level - /// list of PasswordHistory objects - public List GetPasswordHistory(int userId, int portalId) + /// portalid - futureproofing against any setting become site level. + /// users new password suggestion. + /// If set true then add the password into history if its not used yet. + /// true if password has not been used in users history, false otherwise. + public bool IsPasswordInHistory(int userId, int portalId, string newPassword, bool autoAdd) { + Requires.NotNullOrEmpty("newPassword", newPassword); + bool isPreviouslyUsed = false; var settings = new MembershipPasswordSettings(portalId); - List history = - CBO.FillCollection(_dataProvider.GetPasswordHistory(userId, settings.NumberOfPasswordsStored, settings.NumberOfDaysBeforePasswordReuse)); - return history; - } - - /// - /// checks to see if the password is in history and adds it if it is not - /// - /// portalid - futureproofing against any setting become site level - /// users new password suggestion - /// true if password has not been used in users history, false otherwise - public bool IsPasswordInHistory(int userId, int portalId, string newPassword) - { - return IsPasswordInHistory(userId, portalId, newPassword, true); + if (settings.EnablePasswordHistory) + { + if (!this.IsPasswordPreviouslyUsed(userId, newPassword)) + { + if (autoAdd) + { + this.AddPasswordHistory(userId, newPassword, settings.NumberOfPasswordsStored, settings.NumberOfDaysBeforePasswordReuse); + } + } + else + { + isPreviouslyUsed = true; + } + } + + return isPreviouslyUsed; } - /// - /// checks to see if the password is in history and adds it if it is not - /// - /// portalid - futureproofing against any setting become site level - /// users new password suggestion - /// If set true then add the password into history if its not used yet. - /// true if password has not been used in users history, false otherwise - public bool IsPasswordInHistory(int userId, int portalId, string newPassword, bool autoAdd) - { - Requires.NotNullOrEmpty("newPassword", newPassword); - bool isPreviouslyUsed = false; - var settings = new MembershipPasswordSettings(portalId); - if (settings.EnablePasswordHistory) - { - if (!IsPasswordPreviouslyUsed(userId, newPassword)) - { - if (autoAdd) - { - AddPasswordHistory(userId, newPassword, settings.NumberOfPasswordsStored, settings.NumberOfDaysBeforePasswordReuse); - } - } - else - { - isPreviouslyUsed = true; - } - } - return isPreviouslyUsed; - } - /// - /// checks if the new password matches a previously used password when hashed with the same salt + /// checks if the new password matches a previously used password when hashed with the same salt. /// - /// users entered new password - /// true if previously used, false otherwise + /// users entered new password. + /// true if previously used, false otherwise. public bool IsPasswordPreviouslyUsed(int userId, string password) { bool foundMatch = false; - //use default algorithm (SHA1CryptoServiceProvider ) + + // use default algorithm (SHA1CryptoServiceProvider ) using (HashAlgorithm ha = HashAlgorithm.Create()) { - List history = GetPasswordHistory(userId); + List history = this.GetPasswordHistory(userId); foreach (PasswordHistory ph in history) { string oldEncodedPassword = ph.Password; @@ -138,8 +133,10 @@ public bool IsPasswordPreviouslyUsed(int userId, string password) Buffer.BlockCopy(oldSalt, 0, inputBuffer, bytePassword.Length, 16); byte[] bhashedPassword = ha.ComputeHash(inputBuffer); string hashedPassword = Convert.ToBase64String(bhashedPassword); - if (hashedPassword == oldEncodedPassword) - foundMatch = true; + if (hashedPassword == oldEncodedPassword) + { + foundMatch = true; + } } } @@ -147,11 +144,11 @@ public bool IsPasswordPreviouslyUsed(int userId, string password) } /// - /// checks if the password reset token being used is valid i.e. has not been used before and is within the the expiration period + /// checks if the password reset token being used is valid i.e. has not been used before and is within the the expiration period. /// - /// user attempting to reset their password - /// reset token supplied via email link - /// true if value matches (so has not been used before) and is within expiration window + /// user attempting to reset their password. + /// reset token supplied via email link. + /// true if value matches (so has not been used before) and is within expiration window. public bool IsValidToken(int userId, Guid resetToken) { if (UserController.Instance.GetCurrentUserInfo().PasswordResetToken == resetToken && @@ -159,15 +156,16 @@ public bool IsValidToken(int userId, Guid resetToken) { return true; } + return false; } /// /// Checks if user entered password is on the list of banned passwords - /// combines host level list with current site level list + /// combines host level list with current site level list. /// - /// user entered password - /// true if password found, false otherwise + /// user entered password. + /// true if password found, false otherwise. public bool FoundBannedPassword(string inputString) { const string listName = "BannedPasswords"; @@ -175,10 +173,10 @@ public bool FoundBannedPassword(string inputString) var listController = new ListController(); PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - IEnumerable listEntryHostInfos = listController.GetListEntryInfoItems(listName, "", + IEnumerable listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger); IEnumerable listEntryPortalInfos = - listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, "", settings.PortalId); + listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId); IEnumerable query2 = listEntryHostInfos.Where(test => test.Text == inputString); IEnumerable query3 = listEntryPortalInfos.Where(test => test.Text == inputString); diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs index f4251f81924..e4b7928a62e 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs @@ -1,30 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Security; -using DotNetNuke.Common; -using DotNetNuke.Security.Membership; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Membership { + using System; + using System.Web; + using System.Web.Security; + + using DotNetNuke.Common; + using DotNetNuke.Security.Membership; + public class MembershipPasswordSettings - { - #region Public Properties + { + /// + /// Initializes a new instance of the class. + /// Initialiser for MembershipPasswordSettings provider object. + /// + public MembershipPasswordSettings(int portalId) + { + // portalId not used currently - left in place for potential site specific settings + this.PortalId = portalId; + if (HttpContext.Current != null && !IsInstallRequest(HttpContext.Current.Request)) + { + this.EnableBannedList = Host.Host.EnableBannedList; + this.EnableStrengthMeter = Host.Host.EnableStrengthMeter; + this.EnableIPChecking = Host.Host.EnableIPChecking; + this.EnablePasswordHistory = Host.Host.EnablePasswordHistory; + + this.ResetLinkValidity = Host.Host.MembershipResetLinkValidity; + this.NumberOfPasswordsStored = Host.Host.MembershipNumberPasswords; + this.NumberOfDaysBeforePasswordReuse = Host.Host.MembershipDaysBeforePasswordReuse; + } + else // setup default values during install process. + { + this.EnableStrengthMeter = true; + this.EnableBannedList = true; + this.EnablePasswordHistory = true; + } + } + public bool EnableBannedList { get; set; } + public bool EnableStrengthMeter { get; set; } + public bool EnableIPChecking { get; set; } + public bool EnablePasswordHistory { get; set; } public int NumberOfPasswordsStored { get; set; } + public int NumberOfDaysBeforePasswordReuse { get; set; } + public int ResetLinkValidity { get; set; } /// - /// minimum number of non-alphanumeric characters setting for password strength indicator + /// Gets minimum number of non-alphanumeric characters setting for password strength indicator. /// public int MinNonAlphanumericCharacters { @@ -35,7 +67,7 @@ public int MinNonAlphanumericCharacters } /// - /// minimum length of password setting for password strength indicator + /// Gets minimum length of password setting for password strength indicator. /// public int MinPasswordLength { @@ -46,7 +78,7 @@ public int MinPasswordLength } /// - /// currently configured password format for installation + /// Gets currently configured password format for installation. /// public PasswordFormat PasswordFormat { @@ -65,58 +97,21 @@ public PasswordFormat PasswordFormat } /// - /// Regular Expression to validate password strength. + /// Gets regular Expression to validate password strength. /// public string ValidationExpression { get { return System.Web.Security.Membership.PasswordStrengthRegularExpression; } - } - - #endregion - - #region initialization methods - - /// - /// Initialiser for MembershipPasswordSettings provider object. - /// - public MembershipPasswordSettings(int portalId) - { - //portalId not used currently - left in place for potential site specific settings - PortalId = portalId; - - if (HttpContext.Current != null && !IsInstallRequest(HttpContext.Current.Request)) - { - EnableBannedList = Host.Host.EnableBannedList; - EnableStrengthMeter = Host.Host.EnableStrengthMeter; - EnableIPChecking = Host.Host.EnableIPChecking; - EnablePasswordHistory = Host.Host.EnablePasswordHistory; - - ResetLinkValidity = Host.Host.MembershipResetLinkValidity; - NumberOfPasswordsStored = Host.Host.MembershipNumberPasswords; - NumberOfDaysBeforePasswordReuse = Host.Host.MembershipDaysBeforePasswordReuse; - } - else //setup default values during install process. - { - EnableStrengthMeter = true; - EnableBannedList = true; - EnablePasswordHistory = true; - } - } - - public int PortalId { get; set; } - - #endregion - - #region Private Methods + } + public int PortalId { get; set; } + private static bool IsInstallRequest(HttpRequest request) { var url = request.Url.LocalPath.ToLowerInvariant(); return url.EndsWith("/install.aspx") || url.Contains("/installwizard.aspx"); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs index b84ee3b268c..b936c44b878 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs @@ -1,66 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + using System.Globalization; + + using DotNetNuke.Services.Tokens; + public class MembershipPropertyAccess : IPropertyAccess { private readonly UserInfo objUser; public MembershipPropertyAccess(UserInfo User) { - objUser = User; - } - - #region IPropertyAccess Members + this.objUser = User; + } + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope CurrentScope, ref bool PropertyNotFound) { - UserMembership objMembership = objUser.Membership; - bool UserQueriesHimself = (objUser.UserID == AccessingUser.UserID && objUser.UserID != -1); + UserMembership objMembership = this.objUser.Membership; + bool UserQueriesHimself = this.objUser.UserID == AccessingUser.UserID && this.objUser.UserID != -1; if (CurrentScope < Scope.DefaultSettings || (CurrentScope == Scope.DefaultSettings && !UserQueriesHimself) || - ((CurrentScope != Scope.SystemMessages || objUser.IsSuperUser) - && (propertyName.Equals("password", StringComparison.InvariantCultureIgnoreCase) || propertyName.Equals("passwordanswer", StringComparison.InvariantCultureIgnoreCase) || propertyName.Equals("passwordquestion", StringComparison.InvariantCultureIgnoreCase)) - )) + ((CurrentScope != Scope.SystemMessages || this.objUser.IsSuperUser) + && (propertyName.Equals("password", StringComparison.InvariantCultureIgnoreCase) || propertyName.Equals("passwordanswer", StringComparison.InvariantCultureIgnoreCase) || propertyName.Equals("passwordquestion", StringComparison.InvariantCultureIgnoreCase)))) { PropertyNotFound = true; return PropertyAccess.ContentLocked; } + string OutputFormat = string.Empty; if (format == string.Empty) { OutputFormat = "g"; } + switch (propertyName.ToLowerInvariant()) { case "approved": - return (PropertyAccess.Boolean2LocalizedYesNo(objMembership.Approved, formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo(objMembership.Approved, formatProvider); case "createdondate": - return (objMembership.CreatedDate.ToString(OutputFormat, formatProvider)); + return objMembership.CreatedDate.ToString(OutputFormat, formatProvider); case "isonline": - return (PropertyAccess.Boolean2LocalizedYesNo(objMembership.IsOnLine, formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo(objMembership.IsOnLine, formatProvider); case "lastactivitydate": - return (objMembership.LastActivityDate.ToString(OutputFormat, formatProvider)); + return objMembership.LastActivityDate.ToString(OutputFormat, formatProvider); case "lastlockoutdate": - return (objMembership.LastLockoutDate.ToString(OutputFormat, formatProvider)); + return objMembership.LastLockoutDate.ToString(OutputFormat, formatProvider); case "lastlogindate": - return (objMembership.LastLoginDate.ToString(OutputFormat, formatProvider)); + return objMembership.LastLoginDate.ToString(OutputFormat, formatProvider); case "lastpasswordchangedate": - return (objMembership.LastPasswordChangeDate.ToString(OutputFormat, formatProvider)); + return objMembership.LastPasswordChangeDate.ToString(OutputFormat, formatProvider); case "lockedout": - return (PropertyAccess.Boolean2LocalizedYesNo(objMembership.LockedOut, formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo(objMembership.LockedOut, formatProvider); case "objecthydrated": - return (PropertyAccess.Boolean2LocalizedYesNo(true, formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo(true, formatProvider); case "password": return PropertyAccess.FormatString(objMembership.Password, format); case "passwordanswer": @@ -68,27 +70,18 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "passwordquestion": return PropertyAccess.FormatString(objMembership.PasswordQuestion, format); case "passwordresettoken": - return PropertyAccess.FormatString(Convert.ToString(objUser.PasswordResetToken), format); + return PropertyAccess.FormatString(Convert.ToString(this.objUser.PasswordResetToken), format); case "passwordresetexpiration": - return PropertyAccess.FormatString(objUser.PasswordResetExpiration.ToString(formatProvider), format); + return PropertyAccess.FormatString(this.objUser.PasswordResetExpiration.ToString(formatProvider), format); case "updatepassword": - return (PropertyAccess.Boolean2LocalizedYesNo(objMembership.UpdatePassword, formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo(objMembership.UpdatePassword, formatProvider); case "username": - return (PropertyAccess.FormatString(objUser.Username, format)); + return PropertyAccess.FormatString(this.objUser.Username, format); case "email": - return (PropertyAccess.FormatString(objUser.Email, format)); + return PropertyAccess.FormatString(this.objUser.Email, format); } + return PropertyAccess.GetObjectProperty(objMembership, propertyName, format, formatProvider, ref PropertyNotFound); } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs b/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs index a34ee8f7c89..b6c8a422a92 100644 --- a/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs +++ b/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs @@ -1,20 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using System; -using System.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Membership { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + [Serializable] public class PasswordHistory : BaseEntityInfo { public int PasswordHistoryId { get; set; } + public int UserId { get; set; } - public string Password { get; set; } - public string PasswordSalt { get; set; } + + public string Password { get; set; } + + public string PasswordSalt { get; set; } /// /// Fill the object with data from database. @@ -24,12 +28,11 @@ public void Fill(IDataReader dr) { this.PasswordHistoryId = Convert.ToInt32(dr["PasswordHistoryID"]); this.UserId = Null.SetNullInteger(dr["UserID"]); - this.Password = (dr["Password"]).ToString(); - this.PasswordSalt = (dr["PasswordSalt"]).ToString(); + this.Password = dr["Password"].ToString(); + this.PasswordSalt = dr["PasswordSalt"].ToString(); - //add audit column data - FillInternal(dr); + // add audit column data + this.FillInternal(dr); } - } } diff --git a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs index 587e598ad7a..252a0dc7aae 100644 --- a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs +++ b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; - -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + using System.ComponentModel; + + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users @@ -20,7 +15,7 @@ namespace DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- /// /// The UserMembership class provides Business Layer model for the Users Membership - /// related properties + /// related properties. /// /// /// @@ -31,133 +26,135 @@ public class UserMembership private readonly UserInfo _user; private bool _approved; - public UserMembership() : this(new UserInfo()) + public UserMembership() + : this(new UserInfo()) { } public UserMembership(UserInfo user) { - _approved = true; - _user = user; + this._approved = true; + this._user = user; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the User is Approved + /// Gets or sets a value indicating whether gets and sets whether the User is Approved. /// /// ----------------------------------------------------------------------------- public bool Approved { get { - return _approved; + return this._approved; } + set { - if (!_approved && value) + if (!this._approved && value) { - Approving = true; + this.Approving = true; } - _approved = value; - } - } - - internal bool Approving { get; private set; } - - internal void ConfirmApproved() - { - Approving = false; + this._approved = value; + } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User's Creation Date + /// Gets or sets and sets the User's Creation Date. /// /// ----------------------------------------------------------------------------- public DateTime CreatedDate { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User Whether is deleted. + /// Gets or sets a value indicating whether gets and sets the User Whether is deleted. /// /// ----------------------------------------------------------------------------- public bool IsDeleted { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the User Is Online + /// Gets or sets a value indicating whether gets and sets whether the User Is Online. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public bool IsOnLine { get; set; } + internal bool Approving { get; private set; } + + internal void ConfirmApproved() + { + this.Approving = false; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Last Activity Date of the User + /// Gets or sets and sets the Last Activity Date of the User. /// /// ----------------------------------------------------------------------------- public DateTime LastActivityDate { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Last Lock Out Date of the User + /// Gets or sets and sets the Last Lock Out Date of the User. /// /// ----------------------------------------------------------------------------- public DateTime LastLockoutDate { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Last Login Date of the User + /// Gets or sets and sets the Last Login Date of the User. /// /// ----------------------------------------------------------------------------- public DateTime LastLoginDate { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Last Password Change Date of the User + /// Gets or sets and sets the Last Password Change Date of the User. /// /// ----------------------------------------------------------------------------- public DateTime LastPasswordChangeDate { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the user is locked out + /// Gets or sets a value indicating whether gets and sets whether the user is locked out. /// /// ----------------------------------------------------------------------------- public bool LockedOut { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User's Password + /// Gets or sets and sets the User's Password. /// /// ----------------------------------------------------------------------------- public string Password { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User's Password Answer + /// Gets or sets and sets the User's Password Answer. /// /// ----------------------------------------------------------------------------- public string PasswordAnswer { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User's Password Confirm value + /// Gets or sets and sets the User's Password Confirm value. /// /// ----------------------------------------------------------------------------- public string PasswordConfirm { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User's Password Question + /// Gets or sets and sets the User's Password Question. /// /// ----------------------------------------------------------------------------- public string PasswordQuestion { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a flag that determines whether the password should be updated + /// Gets or sets a value indicating whether gets and sets a flag that determines whether the password should be updated. /// /// ----------------------------------------------------------------------------- public bool UpdatePassword { get; set; } diff --git a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs index 328ee235ffb..f13eaf3482e 100644 --- a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs @@ -1,33 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Security; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information // ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Users + // ReSharper restore CheckNamespace { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Security; + using DotNetNuke.Services.Tokens; + public class ProfilePropertyAccess : IPropertyAccess { private readonly UserInfo user; @@ -37,80 +33,6 @@ public ProfilePropertyAccess(UserInfo user) this.user = user; } - #region Private Members - - private static bool IsAdminUser(PortalSettings portalSettings, UserInfo accessingUser, UserInfo targetUser) - { - bool isAdmin = false; - - if (accessingUser != null) - { - //Is Super User? - isAdmin = accessingUser.IsSuperUser; - - if (!isAdmin && targetUser.PortalID != -1) - { - //Is Administrator - var administratorRoleName = portalSettings != null - ? portalSettings.AdministratorRoleName - : PortalController.Instance.GetPortal(targetUser.PortalID).AdministratorRoleName; - - isAdmin = accessingUser.IsInRole(administratorRoleName); - } - } - - return isAdmin; - } - - private static bool IsMember(UserInfo accessingUser) - { - return (accessingUser != null && accessingUser.UserID != -1); - } - - private static bool IsUser(UserInfo accessingUser, UserInfo targetUser) - { - return (accessingUser != null && accessingUser.UserID == targetUser.UserID); - } - - #endregion - - #region IPropertyAccess Members - - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) - { - if (currentScope >= Scope.DefaultSettings && user != null && user.Profile != null) - { - var profile = user.Profile; - var property = profile.ProfileProperties.Cast() - .SingleOrDefault(p => String.Equals(p.PropertyName, propertyName, StringComparison.CurrentCultureIgnoreCase)); - - if(property != null) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (CheckAccessLevel(portalSettings, property, accessingUser, user)) - { - switch (property.PropertyName.ToLowerInvariant()) - { - case "photo": - return user.Profile.PhotoURL; - case "country": - return user.Profile.Country; - case "region": - return user.Profile.Region; - default: - return GetRichValue(property, format, formatProvider); - } - } - } - - propertyNotFound = true; - return property != null && property.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) - ? Globals.ApplicationPath + "/images/no_avatar.gif" : PropertyAccess.ContentLocked; - } - propertyNotFound = true; - return string.Empty; - } - public CacheLevel Cacheability { get @@ -119,8 +41,6 @@ public CacheLevel Cacheability } } - #endregion - /// /// Checks whether profile property is accessible. /// @@ -133,7 +53,7 @@ public static bool CheckAccessLevel(PortalSettings portalSettings, ProfileProper { var isAdminUser = IsAdminUser(portalSettings, accessingUser, targetUser); - //Use properties visible property but admins and hosts can always see the property + // Use properties visible property but admins and hosts can always see the property var isVisible = property.Visible || isAdminUser; if (isVisible && !isAdminUser) @@ -144,26 +64,27 @@ public static bool CheckAccessLevel(PortalSettings portalSettings, ProfileProper isVisible = IsUser(accessingUser, targetUser); if (!isVisible) { - //Relationships + // Relationships foreach (Relationship relationship in property.ProfileVisibility.RelationshipVisibilities) { if (targetUser.Social.UserRelationships.Any(userRelationship => (userRelationship.RelationshipId == relationship.RelationshipId && userRelationship.Status == RelationshipStatus.Accepted && ((userRelationship.RelatedUserId == accessingUser.UserID && userRelationship.UserId == targetUser.UserID) - || (userRelationship.RelatedUserId == targetUser.UserID && userRelationship.UserId == accessingUser.UserID))) - )) + || (userRelationship.RelatedUserId == targetUser.UserID && userRelationship.UserId == accessingUser.UserID))))) { isVisible = true; break; } } - //Groups/Roles + + // Groups/Roles if (property.ProfileVisibility.RoleVisibilities.Any(role => accessingUser.IsInRole(role.RoleName))) { isVisible = true; } } + break; case UserVisibilityMode.AllUsers: // property is visible to everyone so do nothing @@ -173,7 +94,7 @@ public static bool CheckAccessLevel(PortalSettings portalSettings, ProfileProper isVisible = IsMember(accessingUser); break; case UserVisibilityMode.AdminOnly: - //accessing user not admin user so property is hidden (unless it is the user him/herself) + // accessing user not admin user so property is hidden (unless it is the user him/herself) isVisible = IsUser(accessingUser, targetUser); break; } @@ -184,8 +105,8 @@ public static bool CheckAccessLevel(PortalSettings portalSettings, ProfileProper public static string GetRichValue(ProfilePropertyDefinition property, string formatString, CultureInfo formatProvider) { - string result = ""; - if (!String.IsNullOrEmpty(property.PropertyValue) || DisplayDataType(property).Equals("image", StringComparison.InvariantCultureIgnoreCase)) + string result = string.Empty; + if (!string.IsNullOrEmpty(property.PropertyValue) || DisplayDataType(property).Equals("image", StringComparison.InvariantCultureIgnoreCase)) { switch (DisplayDataType(property).ToLowerInvariant()) { @@ -198,6 +119,7 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for { formatString = "g"; } + result = DateTime.Parse(property.PropertyValue, CultureInfo.InvariantCulture).ToString(formatString, formatProvider); break; case "integer": @@ -205,6 +127,7 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for { formatString = "g"; } + result = int.Parse(property.PropertyValue).ToString(formatString, formatProvider); break; case "page": @@ -217,18 +140,20 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for result = string.Format("{1}", TestableGlobals.Instance.NavigateURL(tabid), tab.LocalizedTabName); } } + break; case "image": - //File is stored as a FileID + // File is stored as a FileID int fileID; - if (Int32.TryParse(property.PropertyValue, out fileID) && fileID > 0) + if (int.TryParse(property.PropertyValue, out fileID) && fileID > 0) { - result = Globals.LinkClick(String.Format("fileid={0}", fileID), Null.NullInteger, Null.NullInteger); + result = Globals.LinkClick(string.Format("fileid={0}", fileID), Null.NullInteger, Null.NullInteger); } else { - result = IconController.IconURL("Spacer","1X1"); + result = IconController.IconURL("Spacer", "1X1"); } + break; case "richtext": var objSecurity = PortalSecurity.Instance; @@ -239,19 +164,90 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for break; } } + return result; } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) + { + if (currentScope >= Scope.DefaultSettings && this.user != null && this.user.Profile != null) + { + var profile = this.user.Profile; + var property = profile.ProfileProperties.Cast() + .SingleOrDefault(p => string.Equals(p.PropertyName, propertyName, StringComparison.CurrentCultureIgnoreCase)); + + if (property != null) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (CheckAccessLevel(portalSettings, property, accessingUser, this.user)) + { + switch (property.PropertyName.ToLowerInvariant()) + { + case "photo": + return this.user.Profile.PhotoURL; + case "country": + return this.user.Profile.Country; + case "region": + return this.user.Profile.Region; + default: + return GetRichValue(property, format, formatProvider); + } + } + } + + propertyNotFound = true; + return property != null && property.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) + ? Globals.ApplicationPath + "/images/no_avatar.gif" : PropertyAccess.ContentLocked; + } + + propertyNotFound = true; + return string.Empty; + } + + private static bool IsAdminUser(PortalSettings portalSettings, UserInfo accessingUser, UserInfo targetUser) + { + bool isAdmin = false; + + if (accessingUser != null) + { + // Is Super User? + isAdmin = accessingUser.IsSuperUser; + + if (!isAdmin && targetUser.PortalID != -1) + { + // Is Administrator + var administratorRoleName = portalSettings != null + ? portalSettings.AdministratorRoleName + : PortalController.Instance.GetPortal(targetUser.PortalID).AdministratorRoleName; + + isAdmin = accessingUser.IsInRole(administratorRoleName); + } + } + + return isAdmin; + } + + private static bool IsMember(UserInfo accessingUser) + { + return accessingUser != null && accessingUser.UserID != -1; + } + + private static bool IsUser(UserInfo accessingUser, UserInfo targetUser) + { + return accessingUser != null && accessingUser.UserID == targetUser.UserID; + } + public static string DisplayDataType(ProfilePropertyDefinition definition) { string cacheKey = string.Format("DisplayDataType:{0}", definition.DataType); - string strDataType = Convert.ToString(DataCache.GetCache(cacheKey)) + ""; + string strDataType = Convert.ToString(DataCache.GetCache(cacheKey)) + string.Empty; if (strDataType == string.Empty) { var objListController = new ListController(); strDataType = objListController.GetListEntryInfo("DataType", definition.DataType).Value; DataCache.SetCache(cacheKey, strDataType); } + return strDataType; } } diff --git a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs index 32ee934b159..84b3a9a2fa3 100644 --- a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs +++ b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs @@ -1,45 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Internal; - -#region Usings - -using System; -using System.ComponentModel; -using System.Globalization; - -using DotNetNuke.Collections; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Services.FileSystem; - -using System.Xml.Serialization; -using DotNetNuke.Common.Lists; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// ReSharper disable CheckNamespace namespace DotNetNuke.Entities.Users + // ReSharper restore CheckNamespace { + using System; + using System.ComponentModel; + using System.Globalization; + using System.Xml.Serialization; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Services.FileSystem; + /// - /// The UserProfile class provides a Business Layer entity for the Users Profile + /// The UserProfile class provides a Business Layer entity for the Users Profile. /// [Serializable] public class UserProfile : IIndexable - { - #region Public Constants - - //Name properties + { + // Name properties public const string USERPROFILE_FirstName = "FirstName"; public const string USERPROFILE_LastName = "LastName"; public const string USERPROFILE_Title = "Title"; - //Address Properties + // Address Properties public const string USERPROFILE_Unit = "Unit"; public const string USERPROFILE_Street = "Street"; public const string USERPROFILE_City = "City"; @@ -47,188 +40,186 @@ public class UserProfile : IIndexable public const string USERPROFILE_Region = "Region"; public const string USERPROFILE_PostalCode = "PostalCode"; - //Phone contact + // Phone contact public const string USERPROFILE_Telephone = "Telephone"; public const string USERPROFILE_Cell = "Cell"; public const string USERPROFILE_Fax = "Fax"; - //Online contact + // Online contact public const string USERPROFILE_Website = "Website"; public const string USERPROFILE_IM = "IM"; - //Preferences + // Preferences public const string USERPROFILE_Photo = "Photo"; public const string USERPROFILE_TimeZone = "TimeZone"; public const string USERPROFILE_PreferredLocale = "PreferredLocale"; public const string USERPROFILE_PreferredTimeZone = "PreferredTimeZone"; - public const string USERPROFILE_Biography = "Biography"; - - #endregion - - #region Private Members - + public const string USERPROFILE_Biography = "Biography"; private bool _IsDirty; private UserInfo _user; - //collection to store all profile properties. - private ProfilePropertyDefinitionCollection _profileProperties; - - #endregion - + // collection to store all profile properties. + private ProfilePropertyDefinitionCollection _profileProperties; + public UserProfile() { } public UserProfile(UserInfo user) { - _user = user; - } - - #region Public Properties - + this._user = user; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Cell/Mobile Phone + /// Gets or sets and sets the Cell/Mobile Phone. /// /// ----------------------------------------------------------------------------- public string Cell { get { - return GetPropertyValue(USERPROFILE_Cell); + return this.GetPropertyValue(USERPROFILE_Cell); } + set { - SetProfileProperty(USERPROFILE_Cell, value); + this.SetProfileProperty(USERPROFILE_Cell, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the City part of the Address + /// Gets or sets and sets the City part of the Address. /// /// ----------------------------------------------------------------------------- public string City { get { - return GetPropertyValue(USERPROFILE_City); + return this.GetPropertyValue(USERPROFILE_City); } + set { - SetProfileProperty(USERPROFILE_City, value); + this.SetProfileProperty(USERPROFILE_City, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Country part of the Address + /// Gets or sets and sets the Country part of the Address. /// /// ----------------------------------------------------------------------------- public string Country { get { - return GetPropertyValue(USERPROFILE_Country); + return this.GetPropertyValue(USERPROFILE_Country); } + set { - SetProfileProperty(USERPROFILE_Country, value); + this.SetProfileProperty(USERPROFILE_Country, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Fax Phone + /// Gets or sets and sets the Fax Phone. /// /// ----------------------------------------------------------------------------- public string Fax { get { - return GetPropertyValue(USERPROFILE_Fax); + return this.GetPropertyValue(USERPROFILE_Fax); } + set { - SetProfileProperty(USERPROFILE_Fax, value); + this.SetProfileProperty(USERPROFILE_Fax, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the First Name + /// Gets or sets and sets the First Name. /// /// ----------------------------------------------------------------------------- public string FirstName { get { - return GetPropertyValue(USERPROFILE_FirstName); + return this.GetPropertyValue(USERPROFILE_FirstName); } + set { - SetProfileProperty(USERPROFILE_FirstName, value); + this.SetProfileProperty(USERPROFILE_FirstName, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Full Name + /// Gets and sets the Full Name. /// /// ----------------------------------------------------------------------------- public string FullName { get { - return FirstName + " " + LastName; + return this.FirstName + " " + this.LastName; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Instant Messenger Handle + /// Gets or sets and sets the Instant Messenger Handle. /// /// ----------------------------------------------------------------------------- public string IM { get { - return GetPropertyValue(USERPROFILE_IM); + return this.GetPropertyValue(USERPROFILE_IM); } + set { - SetProfileProperty(USERPROFILE_IM, value); + this.SetProfileProperty(USERPROFILE_IM, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the property has been changed + /// Gets a value indicating whether gets or sets whether the property has been changed. /// /// ----------------------------------------------------------------------------- public bool IsDirty { get { - return _IsDirty; + return this._IsDirty; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Last Name + /// Gets or sets and sets the Last Name. /// /// ----------------------------------------------------------------------------- public string LastName { get { - return GetPropertyValue(USERPROFILE_LastName); + return this.GetPropertyValue(USERPROFILE_LastName); } + set { - SetProfileProperty(USERPROFILE_LastName, value); + this.SetProfileProperty(USERPROFILE_LastName, value); } } @@ -236,44 +227,46 @@ public string Photo { get { - return GetPropertyValue(USERPROFILE_Photo); + return this.GetPropertyValue(USERPROFILE_Photo); } + set { - SetProfileProperty(USERPROFILE_Photo, value); + this.SetProfileProperty(USERPROFILE_Photo, value); } } /// - /// property will return a URL for the photourl - if the path contains invalid url characters it will return a fileticket + /// Gets property will return a URL for the photourl - if the path contains invalid url characters it will return a fileticket. /// public string PhotoURL { get { string photoURL = Globals.ApplicationPath + "/images/no_avatar.gif"; - ProfilePropertyDefinition photoProperty = GetProperty(USERPROFILE_Photo); - if ((photoProperty != null)) + ProfilePropertyDefinition photoProperty = this.GetProperty(USERPROFILE_Photo); + if (photoProperty != null) { UserInfo user = UserController.Instance.GetCurrentUserInfo(); PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - bool isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, _user); + bool isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, this._user); if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) { var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); - if ((fileInfo != null)) + if (fileInfo != null) { photoURL = FileManager.Instance.GetUrl(fileInfo); } } } + return photoURL; } } /// - /// property will return the file path of the photo url (designed to be used when files are loaded via the filesystem e.g for caching) + /// Gets property will return the file path of the photo url (designed to be used when files are loaded via the filesystem e.g for caching). /// [Obsolete("Obsolete in 7.2.2, Use PhotoUrl instead of it.. Scheduled removal in v10.0.0.")] public string PhotoURLFile @@ -281,13 +274,13 @@ public string PhotoURLFile get { string photoURLFile = Globals.ApplicationPath + "/images/no_avatar.gif"; - ProfilePropertyDefinition photoProperty = GetProperty(USERPROFILE_Photo); - if ((photoProperty != null)) + ProfilePropertyDefinition photoProperty = this.GetProperty(USERPROFILE_Photo); + if (photoProperty != null) { UserInfo user = UserController.Instance.GetCurrentUserInfo(); PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - bool isVisible = (user.UserID == _user.UserID); + bool isVisible = user.UserID == this._user.UserID; if (!isVisible) { switch (photoProperty.ProfileVisibility.VisibilityMode) @@ -305,59 +298,65 @@ public string PhotoURLFile break; } } + if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) { var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); - if ((fileInfo != null)) + if (fileInfo != null) { - string rootFolder = ""; + string rootFolder = string.Empty; if (fileInfo.PortalId == Null.NullInteger) { - //Host + // Host rootFolder = Globals.HostPath; } else { rootFolder = settings.HomeDirectory; } + photoURLFile = TestableGlobals.Instance.ResolveUrl(rootFolder + fileInfo.Folder + fileInfo.FileName); } } } + return photoURLFile; } } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the PostalCode part of the Address + /// Gets or sets and sets the PostalCode part of the Address. /// /// ----------------------------------------------------------------------------- public string PostalCode { get { - return GetPropertyValue(USERPROFILE_PostalCode); + return this.GetPropertyValue(USERPROFILE_PostalCode); } + set { - SetProfileProperty(USERPROFILE_PostalCode, value); + this.SetProfileProperty(USERPROFILE_PostalCode, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Preferred Locale + /// Gets or sets and sets the Preferred Locale. /// /// ----------------------------------------------------------------------------- public string PreferredLocale { get { - return GetPropertyValue(USERPROFILE_PreferredLocale); + return this.GetPropertyValue(USERPROFILE_PreferredLocale); } + set { - SetProfileProperty(USERPROFILE_PreferredLocale, value); + this.SetProfileProperty(USERPROFILE_PreferredLocale, value); } } @@ -366,16 +365,17 @@ public TimeZoneInfo PreferredTimeZone { get { - //First set to Server + // First set to Server TimeZoneInfo _TimeZone = TimeZoneInfo.Local; - //Next check if there is a Property Setting - string _TimeZoneId = GetPropertyValue(USERPROFILE_PreferredTimeZone); + // Next check if there is a Property Setting + string _TimeZoneId = this.GetPropertyValue(USERPROFILE_PreferredTimeZone); if (!string.IsNullOrEmpty(_TimeZoneId)) { _TimeZone = TimeZoneInfo.FindSystemTimeZoneById(_TimeZoneId); } - //Next check if there is a Portal Setting + + // Next check if there is a Portal Setting else { PortalSettings _PortalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -385,143 +385,188 @@ public TimeZoneInfo PreferredTimeZone } } - //still we can't find it or it's somehow set to null - return _TimeZone ?? (TimeZoneInfo.Local); + // still we can't find it or it's somehow set to null + return _TimeZone ?? TimeZoneInfo.Local; } + set { if (value != null) { - SetProfileProperty(USERPROFILE_PreferredTimeZone, value.Id); + this.SetProfileProperty(USERPROFILE_PreferredTimeZone, value.Id); } } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Collection of Profile Properties + /// Gets and sets the Collection of Profile Properties. /// /// ----------------------------------------------------------------------------- public ProfilePropertyDefinitionCollection ProfileProperties { - get { return _profileProperties ?? (_profileProperties = new ProfilePropertyDefinitionCollection()); } + get { return this._profileProperties ?? (this._profileProperties = new ProfilePropertyDefinitionCollection()); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Region part of the Address + /// Gets or sets and sets the Region part of the Address. /// /// ----------------------------------------------------------------------------- public string Region { get { - return GetPropertyValue(USERPROFILE_Region); + return this.GetPropertyValue(USERPROFILE_Region); } + set { - SetProfileProperty(USERPROFILE_Region, value); + this.SetProfileProperty(USERPROFILE_Region, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Street part of the Address + /// Gets or sets and sets the Street part of the Address. /// /// ----------------------------------------------------------------------------- public string Street { get { - return GetPropertyValue(USERPROFILE_Street); + return this.GetPropertyValue(USERPROFILE_Street); } + set { - SetProfileProperty(USERPROFILE_Street, value); + this.SetProfileProperty(USERPROFILE_Street, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Telephone + /// Gets or sets and sets the Telephone. /// /// ----------------------------------------------------------------------------- public string Telephone { get { - return GetPropertyValue(USERPROFILE_Telephone); + return this.GetPropertyValue(USERPROFILE_Telephone); } + set { - SetProfileProperty(USERPROFILE_Telephone, value); + this.SetProfileProperty(USERPROFILE_Telephone, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Title + /// Gets or sets and sets the Title. /// /// ----------------------------------------------------------------------------- public string Title { get { - return GetPropertyValue(USERPROFILE_Title); + return this.GetPropertyValue(USERPROFILE_Title); } + set { - SetProfileProperty(USERPROFILE_Title, value); + this.SetProfileProperty(USERPROFILE_Title, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Unit part of the Address + /// Gets or sets and sets the Unit part of the Address. /// /// ----------------------------------------------------------------------------- public string Unit { get { - return GetPropertyValue(USERPROFILE_Unit); + return this.GetPropertyValue(USERPROFILE_Unit); } + set { - SetProfileProperty(USERPROFILE_Unit, value); + this.SetProfileProperty(USERPROFILE_Unit, value); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Website + /// Gets or sets and sets the Website. /// /// ----------------------------------------------------------------------------- public string Website { get { - return GetPropertyValue(USERPROFILE_Website); + return this.GetPropertyValue(USERPROFILE_Website); } + set { - SetProfileProperty(USERPROFILE_Website, value); + this.SetProfileProperty(USERPROFILE_Website, value); } - } - - #endregion - - #region Public Methods - + } + + public string Biography + { + get + { + return this.GetPropertyValue(USERPROFILE_Biography); + } + + set + { + this.SetProfileProperty(USERPROFILE_Biography, value); + } + } + + public object this[string name] + { + get + { + return this.GetPropertyValue(name); + } + + set + { + string stringValue; + if (value is DateTime) + { + var dateValue = (DateTime)value; + stringValue = dateValue.ToString(CultureInfo.InvariantCulture); + } + else if (value is TimeZoneInfo) + { + var timezoneValue = (TimeZoneInfo)value; + stringValue = timezoneValue.Id; + } + else + { + stringValue = Convert.ToString(value); + } + + this.SetProfileProperty(name, stringValue); + } + } + /// ----------------------------------------------------------------------------- /// - /// Clears the IsDirty Flag + /// Clears the IsDirty Flag. /// /// ----------------------------------------------------------------------------- public void ClearIsDirty() { - _IsDirty = false; - foreach (ProfilePropertyDefinition profProperty in ProfileProperties) + this._IsDirty = false; + foreach (ProfilePropertyDefinition profProperty in this.ProfileProperties) { profProperty?.ClearIsDirty(); } @@ -529,27 +574,29 @@ public void ClearIsDirty() /// ----------------------------------------------------------------------------- /// - /// Gets a Profile Property from the Profile + /// Gets a Profile Property from the Profile. /// /// - /// The name of the property to retrieve. + /// The name of the property to retrieve. + /// /// ----------------------------------------------------------------------------- public ProfilePropertyDefinition GetProperty(string propName) { - return ProfileProperties[propName]; + return this.ProfileProperties[propName]; } /// ----------------------------------------------------------------------------- /// - /// Gets a Profile Property Value from the Profile + /// Gets a Profile Property Value from the Profile. /// /// - /// The name of the propoerty to retrieve. + /// The name of the propoerty to retrieve. + /// /// ----------------------------------------------------------------------------- public string GetPropertyValue(string propName) { string propValue = Null.NullString; - ProfilePropertyDefinition profileProp = GetProperty(propName); + ProfilePropertyDefinition profileProp = this.GetProperty(propName); if (profileProp != null) { propValue = profileProp.PropertyValue; @@ -560,43 +607,29 @@ public string GetPropertyValue(string propName) var dataType = controller.GetListEntryInfo("DataType", profileProp.DataType); if (dataType.Value == "Country" || dataType.Value == "Region") { - propValue = GetListValue(dataType.Value, propValue); + propValue = this.GetListValue(dataType.Value, propValue); } } } + return propValue; } - private string GetListValue(string listName, string value) - { - ListController lc = new ListController(); - int entryId; - if (int.TryParse(value, out entryId)) - { - ListEntryInfo item = lc.GetListEntryInfo(listName, entryId); - if (item != null) - { - return item.Text; - } - } - return value; - } - /// ----------------------------------------------------------------------------- /// - /// Initialises the Profile with an empty collection of profile properties + /// Initialises the Profile with an empty collection of profile properties. /// /// /// The name of the property to retrieve. /// ----------------------------------------------------------------------------- public void InitialiseProfile(int portalId) { - InitialiseProfile(portalId, true); + this.InitialiseProfile(portalId, true); } /// ----------------------------------------------------------------------------- /// - /// Initialises the Profile with an empty collection of profile properties + /// Initialises the Profile with an empty collection of profile properties. /// /// /// The name of the property to retrieve. @@ -605,19 +638,35 @@ public void InitialiseProfile(int portalId) /// ----------------------------------------------------------------------------- public void InitialiseProfile(int portalId, bool useDefaults) { - _profileProperties = ProfileController.GetPropertyDefinitionsByPortal(portalId, true, false); + this._profileProperties = ProfileController.GetPropertyDefinitionsByPortal(portalId, true, false); if (useDefaults) { - foreach (ProfilePropertyDefinition ProfileProperty in _profileProperties) + foreach (ProfilePropertyDefinition ProfileProperty in this._profileProperties) { ProfileProperty.PropertyValue = ProfileProperty.DefaultValue; } } } + private string GetListValue(string listName, string value) + { + ListController lc = new ListController(); + int entryId; + if (int.TryParse(value, out entryId)) + { + ListEntryInfo item = lc.GetListEntryInfo(listName, entryId); + if (item != null) + { + return item.Text; + } + } + + return value; + } + /// ----------------------------------------------------------------------------- /// - /// Sets a Profile Property Value in the Profile + /// Sets a Profile Property Value in the Profile. /// /// /// The name of the propoerty to set. @@ -625,62 +674,17 @@ public void InitialiseProfile(int portalId, bool useDefaults) /// ----------------------------------------------------------------------------- public void SetProfileProperty(string propName, string propValue) { - ProfilePropertyDefinition profileProp = GetProperty(propName); + ProfilePropertyDefinition profileProp = this.GetProperty(propName); if (profileProp != null) { profileProp.PropertyValue = propValue; - //Set the IsDirty flag + // Set the IsDirty flag if (profileProp.IsDirty) { - _IsDirty = true; + this._IsDirty = true; } } - } - - #endregion - - public string Biography - { - get - { - return GetPropertyValue(USERPROFILE_Biography); - } - set - { - SetProfileProperty(USERPROFILE_Biography, value); - } - } - - #region Implement IIndexable - - public object this[string name] - { - get - { - return GetPropertyValue(name); - } - set - { - string stringValue; - if (value is DateTime) - { - var dateValue = (DateTime)value; - stringValue = dateValue.ToString(CultureInfo.InvariantCulture); - } - else if (value is TimeZoneInfo) - { - var timezoneValue = (TimeZoneInfo)value; - stringValue = timezoneValue.Id; - } - else - { - stringValue = Convert.ToString(value); - } - SetProfileProperty(name, stringValue); - } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs b/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs index a216b7f6e3a..0ed42e86d7e 100644 --- a/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs +++ b/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs @@ -1,22 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Services.Description; -using DotNetNuke.Entities.Users.Social; -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Web.Services.Description; + + using DotNetNuke.Entities.Users.Social; + public class RelationshipEventArgs : EventArgs { internal RelationshipEventArgs(UserRelationship relationship, int portalId) { - Relationship = relationship; - PortalID = portalId; + this.Relationship = relationship; + this.PortalID = portalId; } public UserRelationship Relationship { get; private set; } + public int PortalID { get; private set; } } } diff --git a/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs b/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs index cabc28233f1..1e0b2c3901a 100644 --- a/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs +++ b/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs @@ -1,134 +1,113 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social.Data { - internal class DataService : ComponentBase, IDataService + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + + internal class DataService : ComponentBase, IDataService { - private readonly DataProvider _provider = DataProvider.Instance(); - - #region RelationshipType CRUD - + private readonly DataProvider _provider = DataProvider.Instance(); + public IDataReader GetAllRelationshipTypes() { - return _provider.ExecuteReader("GetAllRelationshipTypes"); + return this._provider.ExecuteReader("GetAllRelationshipTypes"); } public IDataReader GetRelationshipType(int relationshipTypeId) { - return _provider.ExecuteReader("GetRelationshipType", relationshipTypeId); + return this._provider.ExecuteReader("GetRelationshipType", relationshipTypeId); } public void DeleteRelationshipType(int relationshipTypeId) - { - _provider.ExecuteNonQuery("DeleteRelationshipType", relationshipTypeId); + { + this._provider.ExecuteNonQuery("DeleteRelationshipType", relationshipTypeId); } public int SaveRelationshipType(RelationshipType relationshipType, int createUpdateUserId) { - return _provider.ExecuteScalar("SaveRelationshipType", relationshipType.RelationshipTypeId, relationshipType.Direction, relationshipType.Name, relationshipType.Description, createUpdateUserId); - } - - #endregion - - #region Relationship CRUD - + return this._provider.ExecuteScalar("SaveRelationshipType", relationshipType.RelationshipTypeId, relationshipType.Direction, relationshipType.Name, relationshipType.Description, createUpdateUserId); + } + public void DeleteRelationship(int relationshipId) { - _provider.ExecuteNonQuery("DeleteRelationship", relationshipId); + this._provider.ExecuteNonQuery("DeleteRelationship", relationshipId); } public IDataReader GetRelationship(int relationshipId) { - return _provider.ExecuteReader("GetRelationship", relationshipId); + return this._provider.ExecuteReader("GetRelationship", relationshipId); } public IDataReader GetRelationshipsByUserId(int userId) { - return _provider.ExecuteReader("GetRelationshipsByUserID", userId); + return this._provider.ExecuteReader("GetRelationshipsByUserID", userId); } public IDataReader GetRelationshipsByPortalId(int portalId) { - return _provider.ExecuteReader("GetRelationshipsByPortalID", portalId); + return this._provider.ExecuteReader("GetRelationshipsByPortalID", portalId); } public int SaveRelationship(Relationship relationship, int createUpdateUserId) { - return _provider.ExecuteScalar("SaveRelationship", relationship.RelationshipId, relationship.RelationshipTypeId, relationship.Name, relationship.Description, _provider.GetNull(relationship.UserId), _provider.GetNull(relationship.PortalId), relationship.DefaultResponse, createUpdateUserId); - } - - #endregion - - #region UserRelationship CRUD - + return this._provider.ExecuteScalar("SaveRelationship", relationship.RelationshipId, relationship.RelationshipTypeId, relationship.Name, relationship.Description, this._provider.GetNull(relationship.UserId), this._provider.GetNull(relationship.PortalId), relationship.DefaultResponse, createUpdateUserId); + } + public void DeleteUserRelationship(int userRelationshipId) { - _provider.ExecuteNonQuery("DeleteUserRelationship", userRelationshipId); + this._provider.ExecuteNonQuery("DeleteUserRelationship", userRelationshipId); } public IDataReader GetUserRelationship(int userRelationshipId) { - return _provider.ExecuteReader("GetUserRelationship", userRelationshipId); + return this._provider.ExecuteReader("GetUserRelationship", userRelationshipId); } public IDataReader GetUserRelationship(int userId, int relatedUserId, int relationshipId, RelationshipDirection relationshipDirection) { - return _provider.ExecuteReader("GetUserRelationshipsByMultipleIDs", userId, relatedUserId, relationshipId, relationshipDirection); + return this._provider.ExecuteReader("GetUserRelationshipsByMultipleIDs", userId, relatedUserId, relationshipId, relationshipDirection); } public IDataReader GetUserRelationships(int userId) { - return _provider.ExecuteReader("GetUserRelationships", userId); + return this._provider.ExecuteReader("GetUserRelationships", userId); } public IDataReader GetUserRelationshipsByRelationshipId(int relationshipId) { - return _provider.ExecuteReader("GetUserRelationshipsByRelationshipID", relationshipId); + return this._provider.ExecuteReader("GetUserRelationshipsByRelationshipID", relationshipId); } public int SaveUserRelationship(UserRelationship userRelationship, int createUpdateUserId) { - return _provider.ExecuteScalar("SaveUserRelationship", userRelationship.UserRelationshipId, userRelationship.UserId, userRelationship.RelatedUserId, userRelationship.RelationshipId, userRelationship.Status, createUpdateUserId); - } - - #endregion - - #region UserRelationshipPreference CRUD - + return this._provider.ExecuteScalar("SaveUserRelationship", userRelationship.UserRelationshipId, userRelationship.UserId, userRelationship.RelatedUserId, userRelationship.RelationshipId, userRelationship.Status, createUpdateUserId); + } + public IDataReader GetUserRelationshipPreferenceById(int preferenceId) { - return _provider.ExecuteReader("GetUserRelationshipPreferenceByID", preferenceId); + return this._provider.ExecuteReader("GetUserRelationshipPreferenceByID", preferenceId); } public IDataReader GetUserRelationshipPreference(int userId, int relationshipId) { - return _provider.ExecuteReader("GetUserRelationshipPreference", userId, relationshipId); + return this._provider.ExecuteReader("GetUserRelationshipPreference", userId, relationshipId); } public void DeleteUserRelationshipPreference(int preferenceId) { - _provider.ExecuteNonQuery("DeleteUserRelationshipPreference", preferenceId); + this._provider.ExecuteNonQuery("DeleteUserRelationshipPreference", preferenceId); } public int SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference, int createUpdateUserId) { - return _provider.ExecuteScalar("SaveUserRelationshipPreference", userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, userRelationshipPreference.RelationshipId, userRelationshipPreference.DefaultResponse, createUpdateUserId); - } - - #endregion + return this._provider.ExecuteScalar("SaveUserRelationshipPreference", userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, userRelationshipPreference.RelationshipId, userRelationshipPreference.DefaultResponse, createUpdateUserId); + } } } diff --git a/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs b/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs index 563e76651bd..3197fb6cd8f 100644 --- a/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs +++ b/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs @@ -1,56 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social.Data { + using System; + using System.Collections.Generic; + using System.Data; + public interface IDataService - { - #region RelationshipType CRUD - + { void DeleteRelationshipType(int relationshipTypeId); + IDataReader GetAllRelationshipTypes(); + IDataReader GetRelationshipType(int relationshipTypeId); - int SaveRelationshipType(RelationshipType relationshipType, int createUpdateUserId); - - #endregion - - #region Relationship CRUD - + + int SaveRelationshipType(RelationshipType relationshipType, int createUpdateUserId); + void DeleteRelationship(int relationshipId); + IDataReader GetRelationship(int relationshipId); + IDataReader GetRelationshipsByUserId(int userId); + IDataReader GetRelationshipsByPortalId(int portalId); - int SaveRelationship(Relationship relationship, int createUpdateUserId); - - #endregion - - #region UserRelationship CRUD - + + int SaveRelationship(Relationship relationship, int createUpdateUserId); + void DeleteUserRelationship(int userRelationshipId); + IDataReader GetUserRelationship(int userRelationshipId); + IDataReader GetUserRelationship(int userId, int relatedUserId, int relationshipId, RelationshipDirection relationshipDirection); + IDataReader GetUserRelationships(int userId); + IDataReader GetUserRelationshipsByRelationshipId(int relationshipId); - int SaveUserRelationship(UserRelationship userRelationship, int createUpdateUserId); - - #endregion - - #region UserRelationshipPreference CRUD - + + int SaveUserRelationship(UserRelationship userRelationship, int createUpdateUserId); + void DeleteUserRelationshipPreference(int preferenceId); + IDataReader GetUserRelationshipPreferenceById(int preferenceId); + IDataReader GetUserRelationshipPreference(int userId, int relationshipId); - int SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference, int createUpdateUserId); - - #endregion + + int SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference, int createUpdateUserId); } } diff --git a/DNN Platform/Library/Entities/Users/Social/DefaultRelationshipTypes.cs b/DNN Platform/Library/Entities/Users/Social/DefaultRelationshipTypes.cs index 19d09bbeeb3..4c7b3482767 100644 --- a/DNN Platform/Library/Entities/Users/Social/DefaultRelationshipTypes.cs +++ b/DNN Platform/Library/Entities/Users/Social/DefaultRelationshipTypes.cs @@ -1,20 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Entities.Modules; + /// - /// DefaultRelationshipType defined in system + /// DefaultRelationshipType defined in system. /// public enum DefaultRelationshipTypes { @@ -31,6 +27,6 @@ public enum DefaultRelationshipTypes /// /// A user-owned custom-list, e.g. my best friends /// - CustomList = 3 + CustomList = 3, } } diff --git a/DNN Platform/Library/Entities/Users/Social/Exceptions/InvalidRelationshipTypeException.cs b/DNN Platform/Library/Entities/Users/Social/Exceptions/InvalidRelationshipTypeException.cs index 632044e1e43..05e85806f1f 100644 --- a/DNN Platform/Library/Entities/Users/Social/Exceptions/InvalidRelationshipTypeException.cs +++ b/DNN Platform/Library/Entities/Users/Social/Exceptions/InvalidRelationshipTypeException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class InvalidRelationshipTypeException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipBlockedException.cs b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipBlockedException.cs index b92a04c277e..f0db836e3d8 100644 --- a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipBlockedException.cs +++ b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipBlockedException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class UserRelationshipBlockedException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipDoesNotExistException.cs b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipDoesNotExistException.cs index 3fb57d68615..5f6278e0aef 100644 --- a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipDoesNotExistException.cs +++ b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipDoesNotExistException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class UserRelationshipDoesNotExistException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipExistsException.cs b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipExistsException.cs index 2f61bb284d2..07f0a2b0adf 100644 --- a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipExistsException.cs +++ b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipExistsException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class UserRelationshipExistsException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForDifferentPortalException.cs b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForDifferentPortalException.cs index f5177af1a10..b0a1669e50f 100644 --- a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForDifferentPortalException.cs +++ b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForDifferentPortalException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class UserRelationshipForDifferentPortalException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForSameUsersException.cs b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForSameUsersException.cs index 308966c3b6c..5cc78a9b26a 100644 --- a/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForSameUsersException.cs +++ b/DNN Platform/Library/Entities/Users/Social/Exceptions/UserRelationshipForSameUsersException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class UserRelationshipForSameUsersException : Exception { diff --git a/DNN Platform/Library/Entities/Users/Social/FollowersController.cs b/DNN Platform/Library/Entities/Users/Social/FollowersController.cs index f08c99a7bbd..1f58317e101 100644 --- a/DNN Platform/Library/Entities/Users/Social/FollowersController.cs +++ b/DNN Platform/Library/Entities/Users/Social/FollowersController.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Users.Social.Internal; -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + + using DotNetNuke.Entities.Users.Social.Internal; + using DotNetNuke.Framework; + public class FollowersController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs index 1b0e6164a4a..94bbedf7716 100644 --- a/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Friends; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Notifications; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Social.Internal { + using System; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Friends; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Notifications; + internal class FollowersControllerImpl : IFollowersController { internal const string FollowerRequest = "FollowerRequest"; @@ -20,26 +21,24 @@ internal class FollowersControllerImpl : IFollowersController /// ----------------------------------------------------------------------------- /// - /// FollowUser - Current User initiates a Follow Request to the Target User - /// - /// UserInfo for Target User - /// UserRelationship object + /// FollowUser - Current User initiates a Follow Request to the Target User. + /// + /// UserInfo for Target User. /// If the Follow Relationship is setup for auto-acceptance (default) at the Portal level, the UserRelationship /// status is set as Accepted, otherwise it is set as Initiated. /// /// ----------------------------------------------------------------------------- public void FollowUser(UserInfo targetUser) { - FollowUser(UserController.Instance.GetCurrentUserInfo(), targetUser); + this.FollowUser(UserController.Instance.GetCurrentUserInfo(), targetUser); } /// ----------------------------------------------------------------------------- /// - /// FollowUser - Initiating User initiates a Follow Request to the Target User - /// - /// UserInfo for Initiating User - /// UserInfo for Target User - /// UserRelationship object + /// FollowUser - Initiating User initiates a Follow Request to the Target User. + /// + /// UserInfo for Initiating User. + /// UserInfo for Target User. /// If the Follow Relationship is setup for auto-acceptance (default) at the Portal level, the UserRelationship /// status is set as Accepted, otherwise it is set as Initiated. /// @@ -58,9 +57,9 @@ public void FollowUser(UserInfo initiatingUser, UserInfo targetUser) /// ----------------------------------------------------------------------------- /// - /// UnFollowUser - Current User initiates an UnFollow Request to the Target User - /// - /// UserInfo for Target User + /// UnFollowUser - Current User initiates an UnFollow Request to the Target User. + /// + /// UserInfo for Target User. /// ----------------------------------------------------------------------------- public void UnFollowUser(UserInfo targetUser) { @@ -75,11 +74,13 @@ public void UnFollowUser(UserInfo targetUser) private static void AddFollowerRequestNotification(UserInfo initiatingUser, UserInfo targetUser) { var notificationType = NotificationsController.Instance.GetNotificationType(IsFollowing(targetUser, initiatingUser) ? FollowerRequest : FollowBackRequest); - var subject = string.Format(Localization.GetString("AddFollowerRequestSubject", Localization.GlobalResourceFile), - initiatingUser.DisplayName); + var subject = string.Format( + Localization.GetString("AddFollowerRequestSubject", Localization.GlobalResourceFile), + initiatingUser.DisplayName); - var body = string.Format(Localization.GetString("AddFollowerRequestBody", Localization.GlobalResourceFile), - initiatingUser.DisplayName); + var body = string.Format( + Localization.GetString("AddFollowerRequestBody", Localization.GlobalResourceFile), + initiatingUser.DisplayName); var notification = new Notification { @@ -88,7 +89,7 @@ private static void AddFollowerRequestNotification(UserInfo initiatingUser, User Body = body, IncludeDismissAction = true, Context = initiatingUser.UserID.ToString(CultureInfo.InvariantCulture), - SenderUserID = initiatingUser.UserID + SenderUserID = initiatingUser.UserID, }; NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, new List { targetUser }); @@ -98,7 +99,7 @@ private static bool IsFollowing(UserInfo user1, UserInfo user2) { var userRelationship = RelationshipController.Instance.GetFollowerRelationship(user1, user2); - return (userRelationship != null && userRelationship.Status == RelationshipStatus.Accepted); + return userRelationship != null && userRelationship.Status == RelationshipStatus.Accepted; } } } diff --git a/DNN Platform/Library/Entities/Users/Social/FriendsController.cs b/DNN Platform/Library/Entities/Users/Social/FriendsController.cs index f0a4ee6fa5f..575a2b5183d 100644 --- a/DNN Platform/Library/Entities/Users/Social/FriendsController.cs +++ b/DNN Platform/Library/Entities/Users/Social/FriendsController.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Users.Social.Internal; -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + + using DotNetNuke.Entities.Users.Social.Internal; + using DotNetNuke.Framework; + public class FriendsController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs index 209a7bafcef..889f0b05b96 100644 --- a/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs @@ -1,33 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Friends; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Notifications; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Social.Internal { + using System; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Friends; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Notifications; + internal class FriendsControllerImpl : IFriendsController { internal const string FriendRequest = "FriendRequest"; - - - //static FriendsControllerImpl() - //{ - //} + + // static FriendsControllerImpl() + // { + // } /// ----------------------------------------------------------------------------- /// - /// AcceptFriend - Current User accepts a Friend Request to the Target User - /// - /// UserInfo for Target User - /// UserRelationship object + /// AcceptFriend - Current User accepts a Friend Request to the Target User. + /// + /// UserInfo for Target User. /// ----------------------------------------------------------------------------- public void AcceptFriend(UserInfo targetUser) { @@ -39,15 +38,14 @@ public void AcceptFriend(UserInfo targetUser) NotificationsController.Instance.GetNotificationType(FriendRequest).NotificationTypeId, friendRelationship.UserRelationshipId.ToString(CultureInfo.InvariantCulture), initiatingUser.UserID); - EventManager.Instance.OnFriendshipAccepted(new RelationshipEventArgs(friendRelationship,initiatingUser.PortalID)); + EventManager.Instance.OnFriendshipAccepted(new RelationshipEventArgs(friendRelationship, initiatingUser.PortalID)); } /// ----------------------------------------------------------------------------- /// - /// AddFriend - Current User initiates a Friend Request to the Target User - /// - /// UserInfo for Target User - /// UserRelationship object + /// AddFriend - Current User initiates a Friend Request to the Target User. + /// + /// UserInfo for Target User. /// If the Friend Relationship is setup for auto-acceptance at the Portal level, the UserRelationship /// status is set as Accepted, otherwise it is set as Initiated. /// @@ -55,16 +53,15 @@ public void AcceptFriend(UserInfo targetUser) public void AddFriend(UserInfo targetUser) { var initiatingUser = UserController.Instance.GetCurrentUserInfo(); - AddFriend(initiatingUser, targetUser); + this.AddFriend(initiatingUser, targetUser); } /// ----------------------------------------------------------------------------- /// - /// AddFriend - Initiating User initiates a Friend Request to the Target User - /// - /// UserInfo for Initiating User - /// UserInfo for Target User - /// UserRelationship object + /// AddFriend - Initiating User initiates a Friend Request to the Target User. + /// + /// UserInfo for Initiating User. + /// UserInfo for Target User. /// If the Friend Relationship is setup for auto-acceptance at the Portal level, the UserRelationship /// status is set as Accepted, otherwise it is set as Initiated. /// @@ -73,8 +70,9 @@ public void AddFriend(UserInfo initiatingUser, UserInfo targetUser) { Requires.NotNull("user1", initiatingUser); - //Check if the friendship has been requested first by target user - var targetUserRelationship = RelationshipController.Instance.GetFriendRelationship(targetUser, + // Check if the friendship has been requested first by target user + var targetUserRelationship = RelationshipController.Instance.GetFriendRelationship( + targetUser, initiatingUser); if (targetUserRelationship != null && targetUserRelationship.Status == RelationshipStatus.Pending) { @@ -82,7 +80,7 @@ public void AddFriend(UserInfo initiatingUser, UserInfo targetUser) return; } - var userRelationship = RelationshipController.Instance.InitiateUserRelationship(initiatingUser, targetUser, + var userRelationship = RelationshipController.Instance.InitiateUserRelationship(initiatingUser, targetUser, RelationshipController.Instance.GetFriendsRelationshipByPortal(initiatingUser.PortalID)); AddFriendRequestNotification(initiatingUser, targetUser, userRelationship); @@ -92,22 +90,22 @@ public void AddFriend(UserInfo initiatingUser, UserInfo targetUser) /// ----------------------------------------------------------------------------- /// - /// DeleteFriend - Current User deletes a friend relationship with the target User + /// DeleteFriend - Current User deletes a friend relationship with the target User. /// - /// UserInfo for Target User + /// UserInfo for Target User. /// ----------------------------------------------------------------------------- public void DeleteFriend(UserInfo targetUser) { var initiatingUser = UserController.Instance.GetCurrentUserInfo(); - DeleteFriend(initiatingUser, targetUser); + this.DeleteFriend(initiatingUser, targetUser); } /// ----------------------------------------------------------------------------- /// - /// DeleteFriend - Initiating User deletes a friend relationship with the target User + /// DeleteFriend - Initiating User deletes a friend relationship with the target User. /// - /// UserInfo for Initiating User - /// UserInfo for Target User + /// UserInfo for Initiating User. + /// UserInfo for Target User. /// ----------------------------------------------------------------------------- public void DeleteFriend(UserInfo initiatingUser, UserInfo targetUser) { @@ -125,11 +123,13 @@ private static void AddFriendRequestNotification(UserInfo initiatingUser, UserIn { var notificationType = NotificationsController.Instance.GetNotificationType(FriendRequest); var language = GetUserPreferredLocale(targetUser)?.Name; - var subject = string.Format(Localization.GetString("AddFriendRequestSubject", Localization.GlobalResourceFile, language), - initiatingUser.DisplayName); + var subject = string.Format( + Localization.GetString("AddFriendRequestSubject", Localization.GlobalResourceFile, language), + initiatingUser.DisplayName); - var body = string.Format(Localization.GetString("AddFriendRequestBody", Localization.GlobalResourceFile, language), - initiatingUser.DisplayName); + var body = string.Format( + Localization.GetString("AddFriendRequestBody", Localization.GlobalResourceFile, language), + initiatingUser.DisplayName); var notification = new Notification { @@ -138,7 +138,7 @@ private static void AddFriendRequestNotification(UserInfo initiatingUser, UserIn Body = body, IncludeDismissAction = true, Context = userRelationship.UserRelationshipId.ToString(CultureInfo.InvariantCulture), - SenderUserID = initiatingUser.UserID + SenderUserID = initiatingUser.UserID, }; NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, new List { targetUser }); diff --git a/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs b/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs index c6ea02c0c90..3863ab1f0e2 100644 --- a/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs +++ b/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Social { public interface IFollowersController { void FollowUser(UserInfo targetUser); + void FollowUser(UserInfo initiatingUser, UserInfo targetUser); void UnFollowUser(UserInfo targetUser); diff --git a/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs b/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs index 78987bad61d..cdcf8c0316f 100644 --- a/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs +++ b/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Social { public interface IFriendsController @@ -9,10 +9,11 @@ public interface IFriendsController void AcceptFriend(UserInfo targetUser); void AddFriend(UserInfo targetUser); + void AddFriend(UserInfo initiatingUser, UserInfo targetUser); void DeleteFriend(UserInfo targetUser); + void DeleteFriend(UserInfo initiatingUser, UserInfo targetUser); - } } diff --git a/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs b/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs index ce66b8604d1..9a6f96ddd8a 100644 --- a/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs +++ b/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs @@ -1,213 +1,201 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Social { + using System.Collections.Generic; + public interface IRelationshipController - { - #region RelationshipType - + { /// ----------------------------------------------------------------------------- /// - /// Delete RelationshipType + /// Delete RelationshipType. /// - /// RelationshipType + /// RelationshipType. /// ----------------------------------------------------------------------------- void DeleteRelationshipType(RelationshipType relationshipType); /// ----------------------------------------------------------------------------- /// - /// Get list of All RelationshipTypes defined in system - /// + /// Get list of All RelationshipTypes defined in system. + /// + /// /// ----------------------------------------------------------------------------- IList GetAllRelationshipTypes(); /// ----------------------------------------------------------------------------- /// - /// Get RelationshipType By RelationshipTypeId - /// - /// RelationshipTypeId + /// Get RelationshipType By RelationshipTypeId. + /// + /// RelationshipTypeId. + /// /// ----------------------------------------------------------------------------- RelationshipType GetRelationshipType(int relationshipTypeId); /// ----------------------------------------------------------------------------- /// - /// Save RelationshipType + /// Save RelationshipType. /// - /// RelationshipType object + /// RelationshipType object. /// - /// If RelationshipTypeId is -1 (Null.NullIntger), then a new RelationshipType is created, - /// else existing RelationshipType is updated + /// If RelationshipTypeId is -1 (Null.NullIntger), then a new RelationshipType is created, + /// else existing RelationshipType is updated. /// /// ----------------------------------------------------------------------------- - void SaveRelationshipType(RelationshipType relationshipType); - - #endregion - - #region Relationship - + void SaveRelationshipType(RelationshipType relationshipType); + /// ----------------------------------------------------------------------------- /// - /// Delete Relationship + /// Delete Relationship. /// - /// Relationship + /// Relationship. /// ----------------------------------------------------------------------------- void DeleteRelationship(Relationship relationship); /// ----------------------------------------------------------------------------- /// - /// Get Relationship By RelationshipId - /// - /// RelationshipId + /// Get Relationship By RelationshipId. + /// + /// RelationshipId. + /// /// ----------------------------------------------------------------------------- Relationship GetRelationship(int relationshipId); /// ----------------------------------------------------------------------------- /// - /// Get Relationships By UserId - /// - /// UserId + /// Get Relationships By UserId. + /// + /// UserId. + /// /// ----------------------------------------------------------------------------- IList GetRelationshipsByUserId(int userId); /// ----------------------------------------------------------------------------- /// - /// Get Relationships By PortalId - /// - /// PortalId + /// Get Relationships By PortalId. + /// + /// PortalId. + /// /// ----------------------------------------------------------------------------- IList GetRelationshipsByPortalId(int portalId); /// ----------------------------------------------------------------------------- /// - /// Save Relationship + /// Save Relationship. /// - /// Relationship object + /// Relationship object. /// - /// If RelationshipId is -1 (Null.NullIntger), then a new Relationship is created, - /// else existing Relationship is updated + /// If RelationshipId is -1 (Null.NullIntger), then a new Relationship is created, + /// else existing Relationship is updated. /// /// ----------------------------------------------------------------------------- - void SaveRelationship(Relationship relationship); - - #endregion - - #region UserRelationship - + void SaveRelationship(Relationship relationship); + /// ----------------------------------------------------------------------------- /// - /// Delete UserRelationship + /// Delete UserRelationship. /// - /// UserRelationship to delete + /// UserRelationship to delete. /// ----------------------------------------------------------------------------- void DeleteUserRelationship(UserRelationship userRelationship); /// ----------------------------------------------------------------------------- /// - /// Get UserRelationship By UserRelationshipId - /// - /// UserRelationshipId + /// Get UserRelationship By UserRelationshipId. + /// + /// UserRelationshipId. + /// /// ----------------------------------------------------------------------------- UserRelationship GetUserRelationship(int userRelationshipId); /// ----------------------------------------------------------------------------- /// - /// Get UserRelationship by its members - /// - /// User - /// Related User - /// Relationship Object + /// Get UserRelationship by its members. + /// + /// User. + /// Related User. + /// Relationship Object. + /// /// ----------------------------------------------------------------------------- UserRelationship GetUserRelationship(UserInfo user, UserInfo relatedUser, Relationship relationship); /// /// This method gets a Dictionary of all the relationships that a User belongs to and the members of thase relationships. /// - /// The user - /// A Dictionary of Lists of UserRelationship, keyed by the Relationship + /// The user. + /// A Dictionary of Lists of UserRelationship, keyed by the Relationship. IList GetUserRelationships(UserInfo user); /// ----------------------------------------------------------------------------- /// - /// Save UserRelationship + /// Save UserRelationship. /// - /// UserRelationship object + /// UserRelationship object. /// - /// If UserRelationshipId is -1 (Null.NullIntger), then a new UserRelationship is created, - /// else existing UserRelationship is updated + /// If UserRelationshipId is -1 (Null.NullIntger), then a new UserRelationship is created, + /// else existing UserRelationship is updated. /// /// ----------------------------------------------------------------------------- - void SaveUserRelationship(UserRelationship userRelationship); - - #endregion - - #region UserRelationshipPreference - + void SaveUserRelationship(UserRelationship userRelationship); + /// ----------------------------------------------------------------------------- /// - /// Delete UserRelationshipPreference + /// Delete UserRelationshipPreference. /// - /// UserRelationshipPreference to delete + /// UserRelationshipPreference to delete. /// ----------------------------------------------------------------------------- void DeleteUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference); /// ----------------------------------------------------------------------------- /// - /// Get UserRelationshipPreference By RelationshipTypeId - /// - /// PreferenceId + /// Get UserRelationshipPreference By RelationshipTypeId. + /// + /// PreferenceId. + /// /// ----------------------------------------------------------------------------- UserRelationshipPreference GetUserRelationshipPreference(int preferenceId); /// ----------------------------------------------------------------------------- /// - /// Get UserRelationshipPreference By UserId and RelationshipId - /// - /// UserId - /// RelationshipId + /// Get UserRelationshipPreference By UserId and RelationshipId. + /// + /// UserId. + /// RelationshipId. + /// /// ----------------------------------------------------------------------------- UserRelationshipPreference GetUserRelationshipPreference(int userId, int relationshipId); /// ----------------------------------------------------------------------------- /// - /// Save UserRelationshipPreference + /// Save UserRelationshipPreference. /// - /// UserRelationshipPreference object + /// UserRelationshipPreference object. /// - /// If PreferenceId is -1 (Null.NullIntger), then a new UserRelationshipPreference is created, - /// else existing UserRelationshipPreference is updated + /// If PreferenceId is -1 (Null.NullIntger), then a new UserRelationshipPreference is created, + /// else existing UserRelationshipPreference is updated. /// /// ----------------------------------------------------------------------------- - void SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference); - - #endregion - - #region Relationship Business APIs - + void SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference); + UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserInfo targetUser, Relationship relationship); - - void AcceptUserRelationship(int userRelationshipId); - - void RemoveUserRelationship(int userRelationshipId); - - #endregion - #region Easy Wrapper APIs + void AcceptUserRelationship(int userRelationshipId); + void RemoveUserRelationship(int userRelationshipId); + UserRelationship GetFollowerRelationship(UserInfo targetUser); + UserRelationship GetFollowerRelationship(UserInfo initiatingUser, UserInfo targetUser); UserRelationship GetFollowingRelationship(UserInfo targetUser); + UserRelationship GetFollowingRelationship(UserInfo initiatingUser, UserInfo targetUser); UserRelationship GetFriendRelationship(UserInfo targetUser); - UserRelationship GetFriendRelationship(UserInfo initiatingUser, UserInfo targetUser); - - #endregion - + + UserRelationship GetFriendRelationship(UserInfo initiatingUser, UserInfo targetUser); + void CreateDefaultRelationshipsForPortal(int portalId); Relationship GetFriendsRelationshipByPortal(int portalId); diff --git a/DNN Platform/Library/Entities/Users/Social/Relationship.cs b/DNN Platform/Library/Entities/Users/Social/Relationship.cs index 9d14437e051..acef3597512 100644 --- a/DNN Platform/Library/Entities/Users/Social/Relationship.cs +++ b/DNN Platform/Library/Entities/Users/Social/Relationship.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users.Social; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Users.Social; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: Relationship /// ----------------------------------------------------------------------------- /// - /// The Relationship class describes the relationships that a user or portal owns. - /// A handful of default Portal-Level Relationships will be be present for every portal (e.g. Friends, Followers, Family). + /// The Relationship class describes the relationships that a user or portal owns. + /// A handful of default Portal-Level Relationships will be be present for every portal (e.g. Friends, Followers, Family). /// Portal-Level Relationship will have a -1 in UserId field. /// Any custom User-Level Relationship created by user will also be defined by this class (e.g. My InLaws, Engineering Group). - /// User-Relationship will always have an associcated PortalId. User-Level Relationship will always be tied to a specific Portal. + /// User-Relationship will always have an associcated PortalId. User-Level Relationship will always be tied to a specific Portal. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -35,88 +30,89 @@ public class Relationship : BaseEntityInfo, IHydratable { public Relationship() { - RelationshipId = -1; + this.RelationshipId = -1; } /// - /// RelationshipId - The primary key + /// Gets or sets relationshipId - The primary key. /// [XmlAttribute] public int RelationshipId { get; set; } /// - /// Relationship Name. + /// Gets or sets relationship Name. /// [XmlAttribute] public string Name { get; set; } /// - /// Relationship Description. + /// Gets or sets relationship Description. /// [XmlAttribute] public string Description { get; set; } /// - /// UserId of the User that owns the Relationship. A value of -1 indicates that it's a Portal-Level Relationship + /// Gets or sets userId of the User that owns the Relationship. A value of -1 indicates that it's a Portal-Level Relationship. /// [XmlAttribute] public int UserId { get; set; } /// - /// PortalId of the User that owns the Relationship. A value of -1 in UserID field indicates that it's a Portal-Level Relationship + /// Gets or sets portalId of the User that owns the Relationship. A value of -1 in UserID field indicates that it's a Portal-Level Relationship. /// [XmlAttribute] public int PortalId { get; set; } /// - /// The ID of the Relationship to which this Relation belongs to (e.g. Friend List or Coworkers) + /// Gets or sets the ID of the Relationship to which this Relation belongs to (e.g. Friend List or Coworkers). /// [XmlAttribute] public int RelationshipTypeId { get; set; } /// - /// Default Relationship Status to be provided to any new Relationship Request + /// Gets or sets default Relationship Status to be provided to any new Relationship Request. /// [XmlAttribute] public RelationshipStatus DefaultResponse { get; set; } /// - /// Is this a Portal-Level Relationship + /// Gets a value indicating whether is this a Portal-Level Relationship. /// [XmlIgnore] - public bool IsPortalList - { + public bool IsPortalList + { get { - return UserId == Null.NullInteger && PortalId >= 0; + return this.UserId == Null.NullInteger && this.PortalId >= 0; } } /// - /// Is this a Host-Level Relationship (very uncommon) + /// Gets a value indicating whether is this a Host-Level Relationship (very uncommon). /// [XmlIgnore] public bool IsHostList { get { - return UserId == Null.NullInteger && PortalId == Null.NullInteger; + return this.UserId == Null.NullInteger && this.PortalId == Null.NullInteger; } } /// - /// Is this a USer-Level Relationship + /// Gets a value indicating whether is this a USer-Level Relationship. /// [XmlIgnore] public bool IsUserList { get { - return UserId > 0 && PortalId >= 0; + return this.UserId > 0 && this.PortalId >= 0; } } + /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID @@ -125,6 +121,7 @@ public int KeyID { return this.RelationshipId; } + set { this.RelationshipId = value; @@ -145,8 +142,8 @@ public void Fill(IDataReader dr) this.DefaultResponse = (RelationshipStatus)Convert.ToInt32(dr["DefaultResponse"]); this.RelationshipTypeId = Convert.ToInt32(dr["RelationshipTypeID"]); - //add audit column data - FillInternal(dr); + // add audit column data + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipController.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipController.cs index f9678bc2ef4..21d4ed05bb7 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipController.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipController.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users.Social.Data; -using DotNetNuke.Entities.Users.Social.Internal; -using DotNetNuke.Framework; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { - /// - /// Business Layer to manage Relationships. Also contains CRUD methods. - /// - public class RelationshipController : ServiceLocator + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users.Social.Data; + using DotNetNuke.Entities.Users.Social.Internal; + using DotNetNuke.Framework; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + + /// + /// Business Layer to manage Relationships. Also contains CRUD methods. + /// + public class RelationshipController : ServiceLocator { protected override Func GetFactory() { diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs index ab99e3208d5..9e33f985a39 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs @@ -1,45 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users.Social.Data; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Social.Notifications; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users.Social.Data; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Social.Notifications; + internal class RelationshipControllerImpl : IRelationshipController - { - #region Constants - + { internal const string FriendRequest = "FriendRequest"; internal const string FollowerRequest = "FollowerRequest"; - internal const string FollowBackRequest = "FollowBackRequest"; - - #endregion - - #region Private Variables - + internal const string FollowBackRequest = "FollowBackRequest"; private readonly IDataService _dataService; - private readonly IEventLogController _eventLogController; - - #endregion - - #region Constructors - + private readonly IEventLogController _eventLogController; + public RelationshipControllerImpl() : this(DataService.Instance, EventLogController.Instance) { @@ -47,50 +31,47 @@ public RelationshipControllerImpl() public RelationshipControllerImpl(IDataService dataService, IEventLogController eventLogController) { - //Argument Contract + // Argument Contract Requires.NotNull("dataService", dataService); Requires.NotNull("eventLogController", eventLogController); - _dataService = dataService; - _eventLogController = eventLogController; - } - - #endregion - - #region IRelationshipController Implementation - - #region RelationshipType CRUD - + this._dataService = dataService; + this._eventLogController = eventLogController; + } + public void DeleteRelationshipType(RelationshipType relationshipType) { Requires.NotNull("relationshipType", relationshipType); - _dataService.DeleteRelationshipType(relationshipType.RelationshipTypeId); + this._dataService.DeleteRelationshipType(relationshipType.RelationshipTypeId); - //log event + // log event string logContent = - string.Format(Localization.GetString("RelationshipType_Deleted", Localization.GlobalResourceFile), - relationshipType.Name, relationshipType.RelationshipTypeId); - AddLog(logContent); + string.Format( + Localization.GetString("RelationshipType_Deleted", Localization.GlobalResourceFile), + relationshipType.Name, relationshipType.RelationshipTypeId); + this.AddLog(logContent); - //clear cache + // clear cache DataCache.RemoveCache(DataCache.RelationshipTypesCacheKey); } public IList GetAllRelationshipTypes() { - var cacheArgs = new CacheItemArgs(DataCache.RelationshipTypesCacheKey, - DataCache.RelationshipTypesCacheTimeOut, - DataCache.RelationshipTypesCachePriority); - return CBO.GetCachedObject>(cacheArgs, - c => + var cacheArgs = new CacheItemArgs( + DataCache.RelationshipTypesCacheKey, + DataCache.RelationshipTypesCacheTimeOut, + DataCache.RelationshipTypesCachePriority); + return CBO.GetCachedObject>( + cacheArgs, + c => CBO.FillCollection( - _dataService.GetAllRelationshipTypes())); + this._dataService.GetAllRelationshipTypes())); } public RelationshipType GetRelationshipType(int relationshipTypeId) { - return GetAllRelationshipTypes().FirstOrDefault(r => r.RelationshipTypeId == relationshipTypeId); + return this.GetAllRelationshipTypes().FirstOrDefault(r => r.RelationshipTypeId == relationshipTypeId); } public void SaveRelationshipType(RelationshipType relationshipType) @@ -101,47 +82,46 @@ public void SaveRelationshipType(RelationshipType relationshipType) ? "RelationshipType_Added" : "RelationshipType_Updated"; - relationshipType.RelationshipTypeId = _dataService.SaveRelationshipType(relationshipType, - UserController.Instance.GetCurrentUserInfo(). + relationshipType.RelationshipTypeId = this._dataService.SaveRelationshipType( + relationshipType, + UserController.Instance.GetCurrentUserInfo(). UserID); - //log event - string logContent = string.Format(Localization.GetString(localizationKey, Localization.GlobalResourceFile), - relationshipType.Name); - AddLog(logContent); + // log event + string logContent = string.Format( + Localization.GetString(localizationKey, Localization.GlobalResourceFile), + relationshipType.Name); + this.AddLog(logContent); - //clear cache + // clear cache DataCache.RemoveCache(DataCache.RelationshipTypesCacheKey); - } - - #endregion - - #region Relationship CRUD - + } + public void DeleteRelationship(Relationship relationship) { Requires.NotNull("relationship", relationship); - _dataService.DeleteRelationship(relationship.RelationshipId); + this._dataService.DeleteRelationship(relationship.RelationshipId); - //log event + // log event string logContent = - string.Format(Localization.GetString("Relationship_Deleted", Localization.GlobalResourceFile), - relationship.Name, relationship.RelationshipId); - AddLog(logContent); + string.Format( + Localization.GetString("Relationship_Deleted", Localization.GlobalResourceFile), + relationship.Name, relationship.RelationshipId); + this.AddLog(logContent); - //clear cache - ClearRelationshipCache(relationship); + // clear cache + this.ClearRelationshipCache(relationship); } public Relationship GetRelationship(int relationshipId) { - return CBO.FillCollection(_dataService.GetRelationship(relationshipId)).FirstOrDefault(); + return CBO.FillCollection(this._dataService.GetRelationship(relationshipId)).FirstOrDefault(); } public IList GetRelationshipsByUserId(int userId) { - return CBO.FillCollection(_dataService.GetRelationshipsByUserId(userId)); + return CBO.FillCollection(this._dataService.GetRelationshipsByUserId(userId)); } public IList GetRelationshipsByPortalId(int portalId) @@ -151,15 +131,18 @@ public IList GetRelationshipsByPortalId(int portalId) { pid = PortalController.GetEffectivePortalId(portalId); } - var cacheArgs = new CacheItemArgs(string.Format(DataCache.RelationshipByPortalIDCacheKey, pid), - DataCache.RelationshipByPortalIDCacheTimeOut, - DataCache.RelationshipByPortalIDCachePriority, - pid); - return CBO.GetCachedObject>(cacheArgs, - c => + + var cacheArgs = new CacheItemArgs( + string.Format(DataCache.RelationshipByPortalIDCacheKey, pid), + DataCache.RelationshipByPortalIDCacheTimeOut, + DataCache.RelationshipByPortalIDCachePriority, + pid); + return CBO.GetCachedObject>( + cacheArgs, + c => CBO.FillCollection( - _dataService.GetRelationshipsByPortalId( - (int) c.ParamList[0]))); + this._dataService.GetRelationshipsByPortalId( + (int)c.ParamList[0]))); } public void SaveRelationship(Relationship relationship) @@ -170,42 +153,41 @@ public void SaveRelationship(Relationship relationship) ? "Relationship_Added" : "Relationship_Updated"; - relationship.RelationshipId = _dataService.SaveRelationship(relationship, - UserController.Instance.GetCurrentUserInfo().UserID); + relationship.RelationshipId = this._dataService.SaveRelationship( + relationship, + UserController.Instance.GetCurrentUserInfo().UserID); - //log event - string logContent = string.Format(Localization.GetString(localizationKey, Localization.GlobalResourceFile), - relationship.Name); - AddLog(logContent); - - //clear cache - ClearRelationshipCache(relationship); - } - - #endregion - - #region UserRelationship CRUD + // log event + string logContent = string.Format( + Localization.GetString(localizationKey, Localization.GlobalResourceFile), + relationship.Name); + this.AddLog(logContent); + // clear cache + this.ClearRelationshipCache(relationship); + } + public void DeleteUserRelationship(UserRelationship userRelationship) { Requires.NotNull("userRelationship", userRelationship); - _dataService.DeleteUserRelationship(userRelationship.UserRelationshipId); + this._dataService.DeleteUserRelationship(userRelationship.UserRelationshipId); - //log event + // log event string logContent = - string.Format(Localization.GetString("UserRelationship_Deleted", Localization.GlobalResourceFile), - userRelationship.UserRelationshipId, userRelationship.UserId, - userRelationship.RelatedUserId); - AddLog(logContent); + string.Format( + Localization.GetString("UserRelationship_Deleted", Localization.GlobalResourceFile), + userRelationship.UserRelationshipId, userRelationship.UserId, + userRelationship.RelatedUserId); + this.AddLog(logContent); - //cache clear - ClearUserCache(userRelationship); + // cache clear + this.ClearUserCache(userRelationship); } public UserRelationship GetUserRelationship(int userRelationshipId) { - return CBO.FillObject(_dataService.GetUserRelationship(userRelationshipId)); + return CBO.FillObject(this._dataService.GetUserRelationship(userRelationshipId)); } public UserRelationship GetUserRelationship(UserInfo user, UserInfo relatedUser, Relationship relationship) @@ -213,19 +195,19 @@ public UserRelationship GetUserRelationship(UserInfo user, UserInfo relatedUser, UserRelationship userRelationship = null; if (relationship != null) { - userRelationship = CBO.FillObject(_dataService.GetUserRelationship(user.UserID, relatedUser.UserID, + userRelationship = CBO.FillObject(this._dataService.GetUserRelationship(user.UserID, relatedUser.UserID, relationship.RelationshipId, - GetRelationshipType( + this.GetRelationshipType( relationship.RelationshipTypeId). Direction)); } + return userRelationship; - } public IList GetUserRelationships(UserInfo user) { - return CBO.FillCollection(_dataService.GetUserRelationships(user.UserID)); + return CBO.FillCollection(this._dataService.GetUserRelationships(user.UserID)); } public void SaveUserRelationship(UserRelationship userRelationship) @@ -236,50 +218,49 @@ public void SaveUserRelationship(UserRelationship userRelationship) ? "UserRelationship_Added" : "UserRelationship_Updated"; - userRelationship.UserRelationshipId = _dataService.SaveUserRelationship(userRelationship, - UserController.Instance.GetCurrentUserInfo(). + userRelationship.UserRelationshipId = this._dataService.SaveUserRelationship( + userRelationship, + UserController.Instance.GetCurrentUserInfo(). UserID); - //log event - string logContent = string.Format(Localization.GetString(localizationKey, Localization.GlobalResourceFile), - userRelationship.UserRelationshipId, userRelationship.UserId, - userRelationship.RelatedUserId); - AddLog(logContent); - - //cache clear - ClearUserCache(userRelationship); - } - - #endregion - - #region UserRelationshipPreference CRUD - + // log event + string logContent = string.Format( + Localization.GetString(localizationKey, Localization.GlobalResourceFile), + userRelationship.UserRelationshipId, userRelationship.UserId, + userRelationship.RelatedUserId); + this.AddLog(logContent); + + // cache clear + this.ClearUserCache(userRelationship); + } + public void DeleteUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference) { Requires.NotNull("userRelationshipPreference", userRelationshipPreference); - _dataService.DeleteUserRelationshipPreference(userRelationshipPreference.PreferenceId); + this._dataService.DeleteUserRelationshipPreference(userRelationshipPreference.PreferenceId); - //log event + // log event string logContent = string.Format( Localization.GetString("UserRelationshipPreference_Deleted", Localization.GlobalResourceFile), userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, userRelationshipPreference.RelationshipId); - AddLog(logContent); + this.AddLog(logContent); } public UserRelationshipPreference GetUserRelationshipPreference(int preferenceId) { return - CBO.FillObject(_dataService.GetUserRelationshipPreferenceById(preferenceId)); + CBO.FillObject(this._dataService.GetUserRelationshipPreferenceById(preferenceId)); } public UserRelationshipPreference GetUserRelationshipPreference(int userId, int relationshipId) { return - CBO.FillObject(_dataService.GetUserRelationshipPreference(userId, - relationshipId)); + CBO.FillObject(this._dataService.GetUserRelationshipPreference( + userId, + relationshipId)); } public void SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference) @@ -291,35 +272,33 @@ public void SaveUserRelationshipPreference(UserRelationshipPreference userRelati : "UserRelationshipPreference_Updated"; userRelationshipPreference.PreferenceId = - _dataService.SaveUserRelationshipPreference(userRelationshipPreference, - UserController.Instance.GetCurrentUserInfo().UserID); - - //log event - string logContent = string.Format(Localization.GetString(localizationKey, Localization.GlobalResourceFile), - userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, - userRelationshipPreference.RelationshipId); - AddLog(logContent); - } - - #endregion - - #region Relationship Business APIs - + this._dataService.SaveUserRelationshipPreference( + userRelationshipPreference, + UserController.Instance.GetCurrentUserInfo().UserID); + + // log event + string logContent = string.Format( + Localization.GetString(localizationKey, Localization.GlobalResourceFile), + userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, + userRelationshipPreference.RelationshipId); + this.AddLog(logContent); + } + /// ----------------------------------------------------------------------------- /// - /// Initiate an UserRelationship Request + /// Initiate an UserRelationship Request. /// - /// UserInfo of the user initiating the request - /// UserInfo of the user being solicited for initiating the request - /// Relationship to associate this request to (Portal-Level Relationship or User-Level Relationship) + /// UserInfo of the user initiating the request. + /// UserInfo of the user being solicited for initiating the request. + /// Relationship to associate this request to (Portal-Level Relationship or User-Level Relationship). /// /// If all conditions are met UserRelationship object belonging to Initiating User is returned. /// /// - /// Relationship object belonging to the initiating user + /// Relationship object belonging to the initiating user. /// - /// Target user has Blocked any relationship request from Initiating user - /// Relationship type does not exist + /// Target user has Blocked any relationship request from Initiating user. + /// Relationship type does not exist. /// ----------------------------------------------------------------------------- public UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserInfo targetUser, Relationship relationship) @@ -336,26 +315,28 @@ public UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserIn Requires.PropertyNotNegative("relationship", "RelationshipId", relationship.RelationshipId); - //cannot be same user + // cannot be same user if (initiatingUser.UserID == targetUser.UserID) { throw new UserRelationshipForSameUsersException( - Localization.GetExceptionMessage("UserRelationshipForSameUsersError", - "Initiating and Target Users cannot have same UserID '{0}'.", - initiatingUser.UserID)); + Localization.GetExceptionMessage( + "UserRelationshipForSameUsersError", + "Initiating and Target Users cannot have same UserID '{0}'.", + initiatingUser.UserID)); } - //users must be from same portal + // users must be from same portal if (initiatingUser.PortalID != targetUser.PortalID) { throw new UserRelationshipForDifferentPortalException( - Localization.GetExceptionMessage("UserRelationshipForDifferentPortalError", - "Portal ID '{0}' of Initiating User is different from Portal ID '{1}' of Target User.", - initiatingUser.PortalID, targetUser.PortalID)); + Localization.GetExceptionMessage( + "UserRelationshipForDifferentPortalError", + "Portal ID '{0}' of Initiating User is different from Portal ID '{1}' of Target User.", + initiatingUser.PortalID, targetUser.PortalID)); } - //check for existing UserRelationship record - UserRelationship existingRelationship = GetUserRelationship(initiatingUser, targetUser, relationship); + // check for existing UserRelationship record + UserRelationship existingRelationship = this.GetUserRelationship(initiatingUser, targetUser, relationship); if (existingRelationship != null) { throw new UserRelationshipExistsException(Localization.GetExceptionMessage( @@ -364,99 +345,93 @@ public UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserIn initiatingUser.UserID, targetUser.UserID, relationship.RelationshipId)); } - //no existing UserRelationship record found - - - //use Relationship DefaultResponse as status + // no existing UserRelationship record found + + // use Relationship DefaultResponse as status RelationshipStatus status = relationship.DefaultResponse; - - - UserRelationshipPreference preference = GetUserRelationshipPreference(targetUser.UserID, - relationship.RelationshipId); + + UserRelationshipPreference preference = this.GetUserRelationshipPreference( + targetUser.UserID, + relationship.RelationshipId); if (preference != null) { status = preference.DefaultResponse; } - - + if (status == RelationshipStatus.None) { status = RelationshipStatus.Pending; } - var userRelationship = new UserRelationship - { - UserRelationshipId = Null.NullInteger, - UserId = initiatingUser.UserID, - RelatedUserId = targetUser.UserID, - RelationshipId = relationship.RelationshipId, - Status = status - }; + var userRelationship = new UserRelationship + { + UserRelationshipId = Null.NullInteger, + UserId = initiatingUser.UserID, + RelatedUserId = targetUser.UserID, + RelationshipId = relationship.RelationshipId, + Status = status, + }; - SaveUserRelationship(userRelationship); + this.SaveUserRelationship(userRelationship); return userRelationship; } /// ----------------------------------------------------------------------------- /// - /// Accept an existing UserRelationship Request + /// Accept an existing UserRelationship Request. /// - /// UserRelationshipId of the UserRelationship + /// UserRelationshipId of the UserRelationship. /// /// Method updates the status of the UserRelationship to Accepted. /// /// ----------------------------------------------------------------------------- public void AcceptUserRelationship(int userRelationshipId) { - ManageUserRelationshipStatus(userRelationshipId, RelationshipStatus.Accepted); + this.ManageUserRelationshipStatus(userRelationshipId, RelationshipStatus.Accepted); } /// ----------------------------------------------------------------------------- /// - /// Remove an existing UserRelationship Request + /// Remove an existing UserRelationship Request. /// - /// UserRelationshipId of the UserRelationship + /// UserRelationshipId of the UserRelationship. /// /// UserRelationship record is physically removed. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public void RemoveUserRelationship(int userRelationshipId) { - UserRelationship userRelationship = VerifyUserRelationshipExist(userRelationshipId); + UserRelationship userRelationship = this.VerifyUserRelationshipExist(userRelationshipId); if (userRelationship != null) { - DeleteUserRelationship(userRelationship); + this.DeleteUserRelationship(userRelationship); } - } - - #endregion - - #region Easy Wrapper APIs - + } + /// ----------------------------------------------------------------------------- /// - /// GetFollowerRelationship - Get the UserRelationship between Current User and the Target Users in Follower Relationship - /// - /// UserInfo for Target User - /// UserRelationship - /// UserRelationship object is returned if a Follower Relationship exists between the two Users. + /// GetFollowerRelationship - Get the UserRelationship between Current User and the Target Users in Follower Relationship. + /// + /// UserInfo for Target User. + /// UserRelationship. + /// UserRelationship object is returned if a Follower Relationship exists between the two Users. /// The relation status can be Any (Initiated / Accepted / Blocked). Follower Relationship can be initited by either of the Users. /// /// ----------------------------------------------------------------------------- public UserRelationship GetFollowerRelationship(UserInfo targetUser) { - return GetFollowerRelationship(UserController.Instance.GetCurrentUserInfo(), targetUser); + return this.GetFollowerRelationship(UserController.Instance.GetCurrentUserInfo(), targetUser); } /// ----------------------------------------------------------------------------- /// - /// GetFollowerRelationship - Get the UserRelationship between InitiatingUser User and the Target Users in Follower Relationship - /// - /// UserInfo for Initiating User - /// UserInfo for Target User - /// UserRelationship - /// UserRelationship object is returned if a Follower Relationship exists between the two Users. + /// GetFollowerRelationship - Get the UserRelationship between InitiatingUser User and the Target Users in Follower Relationship. + /// + /// UserInfo for Initiating User. + /// UserInfo for Target User. + /// UserRelationship. + /// UserRelationship object is returned if a Follower Relationship exists between the two Users. /// The relation status can be Any (Initiated / Accepted / Blocked). Follower Relationship can be initited by either of the Users. /// /// ----------------------------------------------------------------------------- @@ -465,33 +440,33 @@ public UserRelationship GetFollowerRelationship(UserInfo initiatingUser, UserInf Requires.NotNull("user1", initiatingUser); Requires.NotNull("user2", targetUser); - return GetUserRelationship(initiatingUser, targetUser, - GetFollowersRelationshipByPortal(initiatingUser.PortalID)); + return this.GetUserRelationship(initiatingUser, targetUser, + this.GetFollowersRelationshipByPortal(initiatingUser.PortalID)); } /// ----------------------------------------------------------------------------- /// - /// GetFollowingRelationship - Get the UserRelationship between Current User and the Target Users in Following Relationship - /// - /// UserInfo for Target User - /// UserRelationship - /// UserRelationship object is returned if a Following Relationship exists between the two Users. + /// GetFollowingRelationship - Get the UserRelationship between Current User and the Target Users in Following Relationship. + /// + /// UserInfo for Target User. + /// UserRelationship. + /// UserRelationship object is returned if a Following Relationship exists between the two Users. /// The relation status can be Any (Initiated / Accepted / Blocked). /// /// ----------------------------------------------------------------------------- public UserRelationship GetFollowingRelationship(UserInfo targetUser) { - return GetFollowingRelationship(UserController.Instance.GetCurrentUserInfo(), targetUser); + return this.GetFollowingRelationship(UserController.Instance.GetCurrentUserInfo(), targetUser); } /// ----------------------------------------------------------------------------- /// - /// GetFollowingRelationship - Get the UserRelationship between InitiatingUser User and the Target Users in Following Relationship - /// - /// UserInfo for Initiating User - /// UserInfo for Target User - /// UserRelationship - /// UserRelationship object is returned if a Following Relationship exists between the two Users. + /// GetFollowingRelationship - Get the UserRelationship between InitiatingUser User and the Target Users in Following Relationship. + /// + /// UserInfo for Initiating User. + /// UserInfo for Target User. + /// UserRelationship. + /// UserRelationship object is returned if a Following Relationship exists between the two Users. /// The relation status can be Any (Initiated / Accepted / Blocked). /// /// ----------------------------------------------------------------------------- @@ -500,33 +475,33 @@ public UserRelationship GetFollowingRelationship(UserInfo initiatingUser, UserIn Requires.NotNull("user1", initiatingUser); Requires.NotNull("user2", targetUser); - return GetUserRelationship(targetUser, initiatingUser, - GetFollowersRelationshipByPortal(initiatingUser.PortalID)); + return this.GetUserRelationship(targetUser, initiatingUser, + this.GetFollowersRelationshipByPortal(initiatingUser.PortalID)); } /// ----------------------------------------------------------------------------- /// - /// GetFriendRelationship - Get the UserRelationship between Current User and the Target Users in Friend Relationship - /// - /// UserInfo for Target User - /// UserRelationship - /// UserRelationship object is returned if a Friend Relationship exists between the two Users. + /// GetFriendRelationship - Get the UserRelationship between Current User and the Target Users in Friend Relationship. + /// + /// UserInfo for Target User. + /// UserRelationship. + /// UserRelationship object is returned if a Friend Relationship exists between the two Users. /// The relation status can be Any (Initiated / Accepted / Blocked). Friend Relationship can be initited by either of the Users. /// /// ----------------------------------------------------------------------------- public UserRelationship GetFriendRelationship(UserInfo targetUser) { - return GetFriendRelationship(UserController.Instance.GetCurrentUserInfo(), targetUser); + return this.GetFriendRelationship(UserController.Instance.GetCurrentUserInfo(), targetUser); } /// ----------------------------------------------------------------------------- /// - /// GetFriendRelationship - Get the UserRelationship between InitiatingUser User and the Target Users in Friend Relationship - /// - /// UserInfo for Initiating User - /// UserInfo for Target User - /// UserRelationship - /// UserRelationship object is returned if a Friend Relationship exists between the two Users. + /// GetFriendRelationship - Get the UserRelationship between InitiatingUser User and the Target Users in Friend Relationship. + /// + /// UserInfo for Initiating User. + /// UserInfo for Target User. + /// UserRelationship. + /// UserRelationship object is returned if a Friend Relationship exists between the two Users. /// The relation status can be Any (Initiated / Accepted / Blocked). Friend Relationship can be initited by either of the Users. /// /// ----------------------------------------------------------------------------- @@ -535,68 +510,62 @@ public UserRelationship GetFriendRelationship(UserInfo initiatingUser, UserInfo Requires.NotNull("user1", initiatingUser); Requires.NotNull("user2", targetUser); - return GetUserRelationship(initiatingUser, targetUser, - GetFriendsRelationshipByPortal(initiatingUser.PortalID)); - } - - #endregion - + return this.GetUserRelationship(initiatingUser, targetUser, + this.GetFriendsRelationshipByPortal(initiatingUser.PortalID)); + } + public void CreateDefaultRelationshipsForPortal(int portalId) { - //create default Friend Relationship - if (GetFriendsRelationshipByPortal(portalId) == null) + // create default Friend Relationship + if (this.GetFriendsRelationshipByPortal(portalId) == null) { - var friendRelationship = new Relationship - { - RelationshipId = Null.NullInteger, - Name = DefaultRelationshipTypes.Friends.ToString(), - Description = DefaultRelationshipTypes.Friends.ToString(), - PortalId = portalId, - UserId = Null.NullInteger, - DefaultResponse = RelationshipStatus.None, - //default response is None - RelationshipTypeId = (int) DefaultRelationshipTypes.Friends - }; - SaveRelationship(friendRelationship); + var friendRelationship = new Relationship + { + RelationshipId = Null.NullInteger, + Name = DefaultRelationshipTypes.Friends.ToString(), + Description = DefaultRelationshipTypes.Friends.ToString(), + PortalId = portalId, + UserId = Null.NullInteger, + DefaultResponse = RelationshipStatus.None, + + // default response is None + RelationshipTypeId = (int)DefaultRelationshipTypes.Friends, + }; + this.SaveRelationship(friendRelationship); } - //create default Follower Relationship - if (GetFollowersRelationshipByPortal(portalId) == null) + // create default Follower Relationship + if (this.GetFollowersRelationshipByPortal(portalId) == null) { - var followerRelationship = new Relationship - { - RelationshipId = Null.NullInteger, - Name = DefaultRelationshipTypes.Followers.ToString(), - Description = DefaultRelationshipTypes.Followers.ToString(), - PortalId = portalId, - UserId = Null.NullInteger, - DefaultResponse = RelationshipStatus.Accepted, - //default response is Accepted - RelationshipTypeId = (int) DefaultRelationshipTypes.Followers - }; - SaveRelationship(followerRelationship); + var followerRelationship = new Relationship + { + RelationshipId = Null.NullInteger, + Name = DefaultRelationshipTypes.Followers.ToString(), + Description = DefaultRelationshipTypes.Followers.ToString(), + PortalId = portalId, + UserId = Null.NullInteger, + DefaultResponse = RelationshipStatus.Accepted, + + // default response is Accepted + RelationshipTypeId = (int)DefaultRelationshipTypes.Followers, + }; + this.SaveRelationship(followerRelationship); } } public Relationship GetFriendsRelationshipByPortal(int portalId) - { - return GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Friends); + { + return this.GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Friends); } public Relationship GetFollowersRelationshipByPortal(int portalId) { - - return GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Followers); - } - - - #endregion - - #region Private Methods - + return this.GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Followers); + } + private void AddLog(string logContent) { - _eventLogController.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT); + this._eventLogController.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT); } private void ClearRelationshipCache(Relationship relationship) @@ -609,12 +578,12 @@ private void ClearRelationshipCache(Relationship relationship) private void ClearUserCache(UserRelationship userRelationship) { - //Get Portal + // Get Portal PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); if (settings != null) { - //Get User + // Get User UserInfo user = UserController.GetUserById(settings.PortalId, userRelationship.UserId); if (user != null) @@ -622,7 +591,7 @@ private void ClearUserCache(UserRelationship userRelationship) DataCache.ClearUserCache(settings.PortalId, user.Username); } - //Get Related User + // Get Related User UserInfo relatedUser = UserController.GetUserById(settings.PortalId, userRelationship.RelatedUserId); if (relatedUser != null) @@ -634,13 +603,13 @@ private void ClearUserCache(UserRelationship userRelationship) private void ManageUserRelationshipStatus(int userRelationshipId, RelationshipStatus newStatus) { - UserRelationship userRelationship = VerifyUserRelationshipExist(userRelationshipId); + UserRelationship userRelationship = this.VerifyUserRelationshipExist(userRelationshipId); if (userRelationship == null) { return; } - //TODO - apply business rules - throw exception if newStatus requested is not allowed + // TODO - apply business rules - throw exception if newStatus requested is not allowed bool save = false; switch (newStatus) { @@ -658,23 +627,22 @@ private void ManageUserRelationshipStatus(int userRelationshipId, RelationshipSt if (save) { userRelationship.Status = newStatus; - SaveUserRelationship(userRelationship); + this.SaveUserRelationship(userRelationship); } } private UserRelationship VerifyUserRelationshipExist(int userRelationshipId) { - UserRelationship userRelationship = GetUserRelationship(userRelationshipId); + UserRelationship userRelationship = this.GetUserRelationship(userRelationshipId); if (userRelationship == null) { throw new UserRelationshipDoesNotExistException( - Localization.GetExceptionMessage("UserRelationshipDoesNotExistError", - "UserRelationshipID '{0}' does not exist.", userRelationshipId)); + Localization.GetExceptionMessage( + "UserRelationshipDoesNotExistError", + "UserRelationshipID '{0}' does not exist.", userRelationshipId)); } return userRelationship; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipDirection.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipDirection.cs index 99cda327b95..6038a8917e1 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipDirection.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipDirection.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { - public enum RelationshipDirection - { - /// - /// One way relationship, e.g. Follower, where user 1 is following user 2, but user 2 is not following user 1. - /// - OneWay = 1, + using System; + + public enum RelationshipDirection + { + /// + /// One way relationship, e.g. Follower, where user 1 is following user 2, but user 2 is not following user 1. + /// + OneWay = 1, - /// + /// /// Two way relationship, e.g. Friend, where user 1 and user 2 are both friends and mutually following each other. - /// - TwoWay = 2 - } + /// + TwoWay = 2, + } } diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipStatus.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipStatus.cs index ceb169dee48..e48704496e4 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipStatus.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipStatus.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs index 41d61fbbd93..7c10da02b05 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs @@ -1,25 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: RelationshipType /// ----------------------------------------------------------------------------- /// - /// The RelationshipType defines the core relationship types (Friend (2-way), Follower (1-way)) + /// The RelationshipType defines the core relationship types (Friend (2-way), Follower (1-way)). /// /// ----------------------------------------------------------------------------- [Serializable] @@ -28,41 +24,42 @@ public class RelationshipType : BaseEntityInfo, IHydratable private int _relationshipTypeId = -1; /// - /// RelationshipId - The primary key + /// Gets or sets relationshipId - The primary key. /// [XmlAttribute] public int RelationshipTypeId { get { - return _relationshipTypeId; + return this._relationshipTypeId; } + set { - _relationshipTypeId = value; + this._relationshipTypeId = value; } } /// - /// Relationship Type Name. + /// Gets or sets relationship Type Name. /// [XmlAttribute] public string Name { get; set; } /// - /// Relationship Description. + /// Gets or sets relationship Description. /// [XmlAttribute] public string Description { get; set; } /// - /// Relationship Direction. + /// Gets or sets relationship Direction. /// [XmlAttribute] public RelationshipDirection Direction { get; set; } /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID @@ -71,6 +68,7 @@ public int KeyID { return this.RelationshipTypeId; } + set { this.RelationshipTypeId = value; @@ -88,8 +86,8 @@ public void Fill(IDataReader dr) this.Description = dr["Description"].ToString(); this.Direction = (RelationshipDirection)Convert.ToInt32(dr["Direction"]); - //add audit column data - FillInternal(dr); + // add audit column data + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs b/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs index 014dbee1ca7..9354ef368d9 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs @@ -1,27 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: UserRelationship /// ----------------------------------------------------------------------------- /// - /// The UserRelationship class defines the membership of the relationship. - /// The user initiating the relationship is UserId. - /// The target of the relationship is RelatedUserId. + /// The UserRelationship class defines the membership of the relationship. + /// The user initiating the relationship is UserId. + /// The target of the relationship is RelatedUserId. /// Status tracks relationship status as Initiated, Approved, Rejected etc. /// /// ----------------------------------------------------------------------------- @@ -34,37 +30,37 @@ public UserRelationship() } /// - /// UserRelationshipId - The primary key + /// Gets or sets userRelationshipId - The primary key. /// [XmlAttribute] public int UserRelationshipId { get; set; } /// - /// UserId of the User that owns the relationship + /// Gets or sets userId of the User that owns the relationship. /// [XmlAttribute] public int UserId { get; set; } /// - /// The UserId of the Related User + /// Gets or sets the UserId of the Related User. /// [XmlAttribute] public int RelatedUserId { get; set; } /// - /// The ID of the Relationship to which this Relation belongs to (e.g. Friend List or Coworkers) + /// Gets or sets the ID of the Relationship to which this Relation belongs to (e.g. Friend List or Coworkers). /// [XmlAttribute] public int RelationshipId { get; set; } /// - /// The Status of the Relationship (e.g. Initiated, Accepted, Rejected) + /// Gets or sets the Status of the Relationship (e.g. Initiated, Accepted, Rejected). /// [XmlAttribute] public RelationshipStatus Status { get; set; } /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID @@ -73,6 +69,7 @@ public int KeyID { return this.UserRelationshipId; } + set { this.UserRelationshipId = value; @@ -91,8 +88,8 @@ public void Fill(IDataReader dr) this.RelationshipId = Convert.ToInt32(dr["RelationshipID"]); this.Status = (RelationshipStatus)Convert.ToInt32(dr["Status"]); - //add audit column data - FillInternal(dr); + // add audit column data + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs b/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs index 99e090afb41..cc155c197b6 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs @@ -1,17 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; -using DotNetNuke.Entities.Modules; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users @@ -19,7 +16,7 @@ namespace DotNetNuke.Entities.Users.Social /// ----------------------------------------------------------------------------- /// /// The UserRelationshipPreference class defines the relationship preference per user - /// The user initiating the relationship is UserId. + /// The user initiating the relationship is UserId. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -27,46 +24,47 @@ public class UserRelationshipPreference : BaseEntityInfo, IHydratable { public UserRelationshipPreference() { - PreferenceId = -1; + this.PreferenceId = -1; } /// - /// PreferenceId - The primary key + /// Gets or sets preferenceId - The primary key. /// [XmlAttribute] public int PreferenceId { get; set; } /// - /// UserId of the User that owns the relationship + /// Gets or sets userId of the User that owns the relationship. /// [XmlAttribute] public int UserId { get; set; } /// - /// The ID of the Relationship to which this Relation belongs to (e.g. Friend List or Coworkers) + /// Gets or sets the ID of the Relationship to which this Relation belongs to (e.g. Friend List or Coworkers). /// [XmlAttribute] public int RelationshipId { get; set; } /// - /// Default Relationship Status to be provided to any new Relationship Request + /// Gets or sets default Relationship Status to be provided to any new Relationship Request. /// [XmlAttribute] public RelationshipStatus DefaultResponse { get; set; } /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID { get { - return PreferenceId; + return this.PreferenceId; } + set { - PreferenceId = value; + this.PreferenceId = value; } } @@ -76,13 +74,13 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - PreferenceId = Convert.ToInt32(dr["PreferenceID"]); - UserId = Convert.ToInt32(dr["UserID"]); - RelationshipId = Convert.ToInt32(dr["RelationshipID"]); - DefaultResponse = (RelationshipStatus)Convert.ToInt32(dr["DefaultResponse"]); + this.PreferenceId = Convert.ToInt32(dr["PreferenceID"]); + this.UserId = Convert.ToInt32(dr["UserID"]); + this.RelationshipId = Convert.ToInt32(dr["RelationshipID"]); + this.DefaultResponse = (RelationshipStatus)Convert.ToInt32(dr["DefaultResponse"]); - //add audit column data - FillInternal(dr); + // add audit column data + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Entities/Users/Social/UserSocial.cs b/DNN Platform/Library/Entities/Users/Social/UserSocial.cs index 27702b34d78..f348a5e3db1 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserSocial.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserSocial.cs @@ -1,153 +1,132 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Xml.Serialization; - -using DotNetNuke.Security.Roles; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Social { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Xml.Serialization; + + using DotNetNuke.Security.Roles; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: UserSocial /// ----------------------------------------------------------------------------- /// - /// The UserSocial is a high-level class describing social details of a user. + /// The UserSocial is a high-level class describing social details of a user. /// As an example, this class contains Friends, Followers, Follows lists. /// /// ----------------------------------------------------------------------------- [Serializable] public class UserSocial - { - #region Private - + { private IList _relationships; private IList _userRelationships; - private IList _roles; - private readonly UserInfo _userInfo; - - #endregion - - #region Constructor - + private IList _roles; + private readonly UserInfo _userInfo; + public UserSocial(UserInfo userInfo) { - _userInfo = userInfo; - } - - #endregion - - #region Public Properties - + this._userInfo = userInfo; + } + /// - /// Returns the Friend Relationship (if it exists with the current User) + /// Gets the Friend Relationship (if it exists with the current User). /// public UserRelationship Friend { get { - var _friendsRelationship = RelationshipController.Instance.GetFriendsRelationshipByPortal(_userInfo.PortalID); + var _friendsRelationship = RelationshipController.Instance.GetFriendsRelationshipByPortal(this._userInfo.PortalID); var currentUser = UserController.Instance.GetCurrentUserInfo(); - return UserRelationships.SingleOrDefault(ur => (ur.RelationshipId == _friendsRelationship.RelationshipId - && - (ur.UserId == _userInfo.UserID && - ur.RelatedUserId == currentUser.UserID + return this.UserRelationships.SingleOrDefault(ur => (ur.RelationshipId == _friendsRelationship.RelationshipId + && + ((ur.UserId == this._userInfo.UserID && + ur.RelatedUserId == currentUser.UserID) || (ur.UserId == currentUser.UserID && - ur.RelatedUserId == _userInfo.UserID) - ))); + ur.RelatedUserId == this._userInfo.UserID)))); } } /// - /// Returns the Follower Relationship. Does the user in object Follow the current User (with any status) + /// Gets the Follower Relationship. Does the user in object Follow the current User (with any status). /// public UserRelationship Follower { get { - var _followerRelationship = RelationshipController.Instance.GetFollowersRelationshipByPortal(_userInfo.PortalID); + var _followerRelationship = RelationshipController.Instance.GetFollowersRelationshipByPortal(this._userInfo.PortalID); var currentUser = UserController.Instance.GetCurrentUserInfo(); - return UserRelationships.SingleOrDefault(ur => (ur.RelationshipId == _followerRelationship.RelationshipId + return this.UserRelationships.SingleOrDefault(ur => (ur.RelationshipId == _followerRelationship.RelationshipId && - (ur.UserId == _userInfo.UserID && - ur.RelatedUserId == currentUser.UserID - ))); + (ur.UserId == this._userInfo.UserID && + ur.RelatedUserId == currentUser.UserID))); } } /// - /// Returns the Following Relationship (if it exists with the current User) + /// Gets the Following Relationship (if it exists with the current User). /// public UserRelationship Following { get { - var _followerRelationship = RelationshipController.Instance.GetFollowersRelationshipByPortal(_userInfo.PortalID); + var _followerRelationship = RelationshipController.Instance.GetFollowersRelationshipByPortal(this._userInfo.PortalID); var currentUser = UserController.Instance.GetCurrentUserInfo(); - return UserRelationships.SingleOrDefault(ur => (ur.RelationshipId == _followerRelationship.RelationshipId + return this.UserRelationships.SingleOrDefault(ur => (ur.RelationshipId == _followerRelationship.RelationshipId && (ur.UserId == currentUser.UserID && - ur.RelatedUserId == _userInfo.UserID - ))); + ur.RelatedUserId == this._userInfo.UserID))); } } /// - /// A collection of all the relationships the user is a member of. + /// Gets a collection of all the relationships the user is a member of. /// public IList UserRelationships { - get { return _userRelationships ?? (_userRelationships = RelationshipController.Instance.GetUserRelationships(_userInfo)); } + get { return this._userRelationships ?? (this._userRelationships = RelationshipController.Instance.GetUserRelationships(this._userInfo)); } } /// - /// List of Relationships for the User + /// Gets list of Relationships for the User. /// [XmlAttribute] public IList Relationships { get { - if (_relationships == null) + if (this._relationships == null) { - _relationships = RelationshipController.Instance.GetRelationshipsByPortalId(_userInfo.PortalID); + this._relationships = RelationshipController.Instance.GetRelationshipsByPortalId(this._userInfo.PortalID); - foreach (var r in RelationshipController.Instance.GetRelationshipsByUserId(_userInfo.UserID)) + foreach (var r in RelationshipController.Instance.GetRelationshipsByUserId(this._userInfo.UserID)) { - _relationships.Add(r); + this._relationships.Add(r); } } - return _relationships; + return this._relationships; } } /// - /// List of Roles/Groups for the User + /// Gets list of Roles/Groups for the User. /// [XmlAttribute] public IList Roles { - get + get { - return _roles ?? (_roles = (_userInfo.PortalID == -1 && _userInfo.UserID == -1) + return this._roles ?? (this._roles = (this._userInfo.PortalID == -1 && this._userInfo.UserID == -1) ? new List(0) - : RoleController.Instance.GetUserRoles(_userInfo, true) - ); + : RoleController.Instance.GetUserRoles(this._userInfo, true)); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Entities/Users/UpdateUserEventArgs.cs b/DNN Platform/Library/Entities/Users/UpdateUserEventArgs.cs index 13aea1eb6e2..aabc192653b 100644 --- a/DNN Platform/Library/Entities/Users/UpdateUserEventArgs.cs +++ b/DNN Platform/Library/Entities/Users/UpdateUserEventArgs.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + public class UpdateUserEventArgs : UserEventArgs { public UserInfo OldUser { get; set; } diff --git a/DNN Platform/Library/Entities/Users/UserController.cs b/DNN Platform/Library/Entities/Users/UserController.cs index c3e774574f2..c6f4141f230 100644 --- a/DNN Platform/Library/Entities/Users/UserController.cs +++ b/DNN Platform/Library/Entities/Users/UserController.cs @@ -1,46 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users.Membership; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Mail; -using DotNetNuke.Services.Messaging.Data; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Configuration; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users.Membership; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.Messaging.Data; + + using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; + /// - /// The UserController class provides Business Layer methods for Users + /// The UserController class provides Business Layer methods for Users. /// /// - /// DotNetNuke user management is base on asp.net membership provider, but the default implementation of these providers - /// do not satisfy the broad set of use cases which we need to support in DotNetNuke. so The dependency of DotNetNuke on the - /// MemberRole (ASP.NET 2 Membership) components will be abstracted into a DotNetNuke Membership Provider, in order to allow + /// DotNetNuke user management is base on asp.net membership provider, but the default implementation of these providers + /// do not satisfy the broad set of use cases which we need to support in DotNetNuke. so The dependency of DotNetNuke on the + /// MemberRole (ASP.NET 2 Membership) components will be abstracted into a DotNetNuke Membership Provider, in order to allow /// developers complete flexibility in implementing alternate Membership approaches. /// /// This will allow for a number of enhancements to be added @@ -59,174 +61,52 @@ namespace DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- public partial class UserController : ServiceLocator, IUserController { - protected override Func GetFactory() - { - return () => new UserController(); - } - - #region Public Properties - public string DisplayFormat { get; set; } public int PortalId { get; set; } - #endregion - - #region Private Methods - - private static void AddEventLog(int portalId, string username, int userId, string portalName, string ip, UserLoginStatus loginStatus) - { - //initialize log record - var objSecurity = PortalSecurity.Instance; - var log = new LogInfo - { - LogTypeKey = loginStatus.ToString(), - LogPortalID = portalId, - LogPortalName = portalName, - LogUserName = objSecurity.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup), - LogUserID = userId - }; - log.AddProperty("IP", ip); - - //create log record - LogController.Instance.AddLog(log); - } - - private static void AutoAssignUsersToPortalRoles(UserInfo user, int portalId) - { - foreach (var role in RoleController.Instance.GetRoles(portalId, role => role.AutoAssignment && role.Status == RoleStatus.Approved)) - { - RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - - //Clear the roles cache - so the usercount is correct - RoleController.Instance.ClearRoleCache(portalId); - } - - private static void AutoAssignUsersToRoles(UserInfo user, int portalId) - { - var thisPortal = PortalController.Instance.GetPortal(portalId); - - if (IsMemberOfPortalGroup(portalId)) - { - foreach (var portal in PortalGroupController.Instance.GetPortalsByGroup(thisPortal.PortalGroupID)) - { - if (!user.Membership.Approved && portal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) - { - var role = RoleController.Instance.GetRole(portal.PortalID, r => r.RoleName == "Unverified Users"); - RoleController.Instance.AddUserRole(portal.PortalID, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - else - { - AutoAssignUsersToPortalRoles(user, portal.PortalID); - } - } - } - else - { - if (!user.Membership.Approved && thisPortal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) - { - var role = RoleController.Instance.GetRole(portalId, r => r.RoleName == "Unverified Users"); - RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - else - { - AutoAssignUsersToPortalRoles(user, portalId); - } - } - } - - //TODO - Handle Portal Groups - private static void DeleteUserPermissions(UserInfo user) - { - FolderPermissionController.DeleteFolderPermissionsByUser(user); - - //Delete Module Permissions - ModulePermissionController.DeleteModulePermissionsByUser(user); - - //Delete Tab Permissions - TabPermissionController.DeleteTabPermissionsByUser(user); - } - - private static void RestoreUserPermissions(UserInfo user) - { - //restore user's folder permission - var userFolderPath = ((PathUtils)PathUtils.Instance).GetUserFolderPathInternal(user); - var portalId = user.IsSuperUser ? Null.NullInteger : user.PortalID; - var userFolder = FolderManager.Instance.GetFolder(portalId, userFolderPath); - - if (userFolder != null) - { - foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) - { - if (permission.PermissionKey.Equals("READ", StringComparison.OrdinalIgnoreCase) - || permission.PermissionKey.Equals("WRITE", StringComparison.OrdinalIgnoreCase) - || permission.PermissionKey.Equals("BROWSE", StringComparison.OrdinalIgnoreCase)) - { - var folderPermission = new FolderPermissionInfo(permission) - { - FolderID = userFolder.FolderID, - UserID = user.UserID, - RoleID = Int32.Parse(Globals.glbRoleNothing), - AllowAccess = true - }; - - userFolder.FolderPermissions.Add(folderPermission, true); - } - } - - FolderPermissionController.SaveFolderPermissions((FolderInfo)userFolder); - } - } - - private static void FixMemberPortalId(UserInfo user, int portalId) + /// ----------------------------------------------------------------------------- + /// + /// Gets the number count for all duplicate e-mail adresses in the database. + /// + /// + /// ----------------------------------------------------------------------------- + public static int GetDuplicateEmailCount() { - if (user != null) - { - user.PortalID = portalId; - } + return DataProvider.Instance().GetDuplicateEmailCount(PortalSettings.Current.PortalId); } - private static UserInfo GetCurrentUserInternal() + /// + /// add new userportal record (used for creating sites with existing user). + /// + /// portalid. + /// userid. + public static void AddUserPortal(int portalId, int userId) { - UserInfo user; - if ((HttpContext.Current == null)) - { - if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) - { - return new UserInfo(); - } - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (portalSettings != null) - { - user = GetCachedUser(portalSettings.PortalId, Thread.CurrentPrincipal.Identity.Name); - return user ?? new UserInfo(); - } - return new UserInfo(); - } - user = (UserInfo)HttpContext.Current.Items["UserInfo"]; - return user ?? new UserInfo(); - } + Requires.NotNullOrEmpty("portalId", portalId.ToString()); + Requires.NotNullOrEmpty("userId", userId.ToString()); - private static int GetEffectivePortalId(int portalId) - { - return PortalController.GetEffectivePortalId(portalId); + MembershipProvider.Instance().AddUserPortal(portalId, userId); } - private static object GetUserCountByPortalCallBack(CacheItemArgs cacheItemArgs) + UserInfo IUserController.GetCurrentUserInfo() { - var portalId = (int)cacheItemArgs.ParamList[0]; - var portalUserCount = MembershipProvider.Instance().GetUserCountByPortal(portalId); - DataCache.SetCache(cacheItemArgs.CacheKey, portalUserCount); - return portalUserCount; + return GetCurrentUserInternal(); } - private static SharedDictionary GetUserLookupDictionary(int portalId) + /// ----------------------------------------------------------------------------- + /// + /// GetUser retrieves a User from the DataStore. + /// + /// + /// + /// The Id of the Portal. + /// The Id of the user being retrieved from the Data Store. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public UserInfo GetUser(int portalId, int userId) { - var masterPortalId = GetEffectivePortalId(portalId); - var cacheKey = string.Format(DataCache.UserLookupCacheKey, masterPortalId); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.UserLookupCacheTimeOut, - DataCache.UserLookupCachePriority), (c) => new SharedDictionary(), true); + return GetUserById(portalId, userId); } internal static Hashtable GetUserSettings(int portalId, Hashtable settings) @@ -237,38 +117,47 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) { settings["Column_FirstName"] = false; } + if (settings["Column_LastName"] == null) { settings["Column_LastName"] = false; } + if (settings["Column_DisplayName"] == null) { settings["Column_DisplayName"] = true; } + if (settings["Column_Address"] == null) { settings["Column_Address"] = true; } + if (settings["Column_Telephone"] == null) { settings["Column_Telephone"] = true; } + if (settings["Column_Email"] == null) { settings["Column_Email"] = false; } + if (settings["Column_CreatedDate"] == null) { settings["Column_CreatedDate"] = true; } + if (settings["Column_LastLogin"] == null) { settings["Column_LastLogin"] = false; } + if (settings["Column_Authorized"] == null) { settings["Column_Authorized"] = true; } + if (settings["Display_Mode"] == null) { settings["Display_Mode"] = DisplayMode.All; @@ -277,14 +166,17 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) { settings["Display_Mode"] = (DisplayMode)Convert.ToInt32(settings["Display_Mode"]); } + if (settings["Display_SuppressPager"] == null) { settings["Display_SuppressPager"] = false; } + if (settings["Records_PerPage"] == null) { settings["Records_PerPage"] = 10; } + if (settings["Profile_DefaultVisibility"] == null) { settings["Profile_DefaultVisibility"] = UserVisibilityMode.AdminOnly; @@ -293,60 +185,74 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) { settings["Profile_DefaultVisibility"] = (UserVisibilityMode)Convert.ToInt32(settings["Profile_DefaultVisibility"]); } + if (settings["Profile_DisplayVisibility"] == null) { settings["Profile_DisplayVisibility"] = true; } + if (settings["Profile_ManageServices"] == null) { settings["Profile_ManageServices"] = true; } + if (settings["Redirect_AfterLogin"] == null) { settings["Redirect_AfterLogin"] = -1; } + if (settings["Redirect_AfterRegistration"] == null) { settings["Redirect_AfterRegistration"] = -1; } + if (settings["Redirect_AfterLogout"] == null) { settings["Redirect_AfterLogout"] = -1; } + if (settings["Security_CaptchaLogin"] == null) { settings["Security_CaptchaLogin"] = false; } + if (settings["Security_CaptchaRegister"] == null) { settings["Security_CaptchaRegister"] = false; } + if (settings["Security_CaptchaChangePassword"] == null) { settings["Security_CaptchaChangePassword"] = false; } + if (settings["Security_CaptchaRetrivePassword"] == null) { settings["Security_CaptchaRetrivePassword"] = false; } + if (settings["Security_EmailValidation"] == null) { settings["Security_EmailValidation"] = Globals.glbEmailRegEx; } + if (settings["Security_UserNameValidation"] == null) { settings["Security_UserNameValidation"] = Globals.glbUserNameRegEx; } - //Forces a valid profile on registration + + // Forces a valid profile on registration if (settings["Security_RequireValidProfile"] == null) { settings["Security_RequireValidProfile"] = false; } - //Forces a valid profile on login + + // Forces a valid profile on login if (settings["Security_RequireValidProfileAtLogin"] == null) { settings["Security_RequireValidProfileAtLogin"] = true; } + if (settings["Security_UsersControl"] == null) { var portal = PortalController.Instance.GetPortal(portalId); @@ -364,50 +270,225 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) { settings["Security_UsersControl"] = (UsersControl)Convert.ToInt32(settings["Security_UsersControl"]); } - //Display name format + + // Display name format if (settings["Security_DisplayNameFormat"] == null) { - settings["Security_DisplayNameFormat"] = ""; + settings["Security_DisplayNameFormat"] = string.Empty; } + if (settings["Registration_RequireConfirmPassword"] == null) { settings["Registration_RequireConfirmPassword"] = true; } + if (settings["Registration_RandomPassword"] == null) { settings["Registration_RandomPassword"] = false; } + if (settings["Registration_UseEmailAsUserName"] == null) { settings["Registration_UseEmailAsUserName"] = false; } + if (settings["Registration_UseAuthProviders"] == null) { settings["Registration_UseAuthProviders"] = false; } + if (settings["Registration_UseProfanityFilter"] == null) { settings["Registration_UseProfanityFilter"] = false; } + if (settings["Registration_RegistrationFormType"] == null) { settings["Registration_RegistrationFormType"] = 0; } + if (settings["Registration_RegistrationFields"] == null) { - settings["Registration_RegistrationFields"] = String.Empty; + settings["Registration_RegistrationFields"] = string.Empty; } + if (settings["Registration_ExcludeTerms"] == null) { - settings["Registration_ExcludeTerms"] = String.Empty; + settings["Registration_ExcludeTerms"] = string.Empty; } + if (settings["Registration_RequireUniqueDisplayName"] == null) { settings["Registration_RequireUniqueDisplayName"] = false; } + return settings; } + protected override Func GetFactory() + { + return () => new UserController(); + } + + private static void AddEventLog(int portalId, string username, int userId, string portalName, string ip, UserLoginStatus loginStatus) + { + // initialize log record + var objSecurity = PortalSecurity.Instance; + var log = new LogInfo + { + LogTypeKey = loginStatus.ToString(), + LogPortalID = portalId, + LogPortalName = portalName, + LogUserName = objSecurity.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup), + LogUserID = userId, + }; + log.AddProperty("IP", ip); + + // create log record + LogController.Instance.AddLog(log); + } + + private static void AutoAssignUsersToPortalRoles(UserInfo user, int portalId) + { + foreach (var role in RoleController.Instance.GetRoles(portalId, role => role.AutoAssignment && role.Status == RoleStatus.Approved)) + { + RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + + // Clear the roles cache - so the usercount is correct + RoleController.Instance.ClearRoleCache(portalId); + } + + private static void AutoAssignUsersToRoles(UserInfo user, int portalId) + { + var thisPortal = PortalController.Instance.GetPortal(portalId); + + if (IsMemberOfPortalGroup(portalId)) + { + foreach (var portal in PortalGroupController.Instance.GetPortalsByGroup(thisPortal.PortalGroupID)) + { + if (!user.Membership.Approved && portal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) + { + var role = RoleController.Instance.GetRole(portal.PortalID, r => r.RoleName == "Unverified Users"); + RoleController.Instance.AddUserRole(portal.PortalID, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + else + { + AutoAssignUsersToPortalRoles(user, portal.PortalID); + } + } + } + else + { + if (!user.Membership.Approved && thisPortal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) + { + var role = RoleController.Instance.GetRole(portalId, r => r.RoleName == "Unverified Users"); + RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + else + { + AutoAssignUsersToPortalRoles(user, portalId); + } + } + } + + // TODO - Handle Portal Groups + private static void DeleteUserPermissions(UserInfo user) + { + FolderPermissionController.DeleteFolderPermissionsByUser(user); + + // Delete Module Permissions + ModulePermissionController.DeleteModulePermissionsByUser(user); + + // Delete Tab Permissions + TabPermissionController.DeleteTabPermissionsByUser(user); + } + + private static void RestoreUserPermissions(UserInfo user) + { + // restore user's folder permission + var userFolderPath = ((PathUtils)PathUtils.Instance).GetUserFolderPathInternal(user); + var portalId = user.IsSuperUser ? Null.NullInteger : user.PortalID; + var userFolder = FolderManager.Instance.GetFolder(portalId, userFolderPath); + + if (userFolder != null) + { + foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) + { + if (permission.PermissionKey.Equals("READ", StringComparison.OrdinalIgnoreCase) + || permission.PermissionKey.Equals("WRITE", StringComparison.OrdinalIgnoreCase) + || permission.PermissionKey.Equals("BROWSE", StringComparison.OrdinalIgnoreCase)) + { + var folderPermission = new FolderPermissionInfo(permission) + { + FolderID = userFolder.FolderID, + UserID = user.UserID, + RoleID = int.Parse(Globals.glbRoleNothing), + AllowAccess = true, + }; + + userFolder.FolderPermissions.Add(folderPermission, true); + } + } + + FolderPermissionController.SaveFolderPermissions((FolderInfo)userFolder); + } + } + + private static void FixMemberPortalId(UserInfo user, int portalId) + { + if (user != null) + { + user.PortalID = portalId; + } + } + + private static UserInfo GetCurrentUserInternal() + { + UserInfo user; + if (HttpContext.Current == null) + { + if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) + { + return new UserInfo(); + } + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (portalSettings != null) + { + user = GetCachedUser(portalSettings.PortalId, Thread.CurrentPrincipal.Identity.Name); + return user ?? new UserInfo(); + } + + return new UserInfo(); + } + + user = (UserInfo)HttpContext.Current.Items["UserInfo"]; + return user ?? new UserInfo(); + } + + private static int GetEffectivePortalId(int portalId) + { + return PortalController.GetEffectivePortalId(portalId); + } + + private static object GetUserCountByPortalCallBack(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + var portalUserCount = MembershipProvider.Instance().GetUserCountByPortal(portalId); + DataCache.SetCache(cacheItemArgs.CacheKey, portalUserCount); + return portalUserCount; + } + + private static SharedDictionary GetUserLookupDictionary(int portalId) + { + var masterPortalId = GetEffectivePortalId(portalId); + var cacheKey = string.Format(DataCache.UserLookupCacheKey, masterPortalId); + return CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.UserLookupCacheTimeOut, + DataCache.UserLookupCachePriority), (c) => new SharedDictionary(), true); + } + private static bool IsMemberOfPortalGroup(int portalId) { return PortalController.IsMemberOfPortalGroup(portalId); @@ -452,50 +533,28 @@ private static void SendDeleteEmailNotifications(UserInfo user, PortalSettings p var message = new Message(); message.FromUserID = portalSettings.AdministratorId; message.ToUserID = portalSettings.AdministratorId; - message.Subject = Localization.GetSystemMessage(user.Profile.PreferredLocale, - portalSettings, - "EMAIL_USER_UNREGISTER_SUBJECT", - user, - Localization.GlobalResourceFile, - null, - "", - portalSettings.AdministratorId); - message.Body = Localization.GetSystemMessage(user.Profile.PreferredLocale, - portalSettings, - "EMAIL_USER_UNREGISTER_BODY", - user, - Localization.GlobalResourceFile, - null, - "", - portalSettings.AdministratorId); + message.Subject = Localization.GetSystemMessage( + user.Profile.PreferredLocale, + portalSettings, + "EMAIL_USER_UNREGISTER_SUBJECT", + user, + Localization.GlobalResourceFile, + null, + string.Empty, + portalSettings.AdministratorId); + message.Body = Localization.GetSystemMessage( + user.Profile.PreferredLocale, + portalSettings, + "EMAIL_USER_UNREGISTER_BODY", + user, + Localization.GlobalResourceFile, + null, + string.Empty, + portalSettings.AdministratorId); message.Status = MessageStatusType.Unread; Mail.SendEmail(portalSettings.Email, portalSettings.Email, message.Subject, message.Body); } - #endregion - - #region Public Mehods - - UserInfo IUserController.GetCurrentUserInfo() - { - return GetCurrentUserInternal(); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetUser retrieves a User from the DataStore - /// - /// - /// - /// The Id of the Portal - /// The Id of the user being retrieved from the Data Store. - /// The User as a UserInfo object - /// ----------------------------------------------------------------------------- - public UserInfo GetUser(int portalId, int userId) - { - return GetUserById(portalId, userId); - } - public UserInfo GetUserByDisplayname(int portalId, string displayName) { return MembershipProvider.Instance().GetUserByDisplayName(PortalController.GetEffectivePortalId(portalId), displayName); @@ -523,14 +582,14 @@ public IList GetUsersBasicSearch(int portalId, int pageIndex, int page } /// - /// Return User Profile Picture relative Url + /// Return User Profile Picture relative Url. /// - /// User Id - /// Width in pixel - /// Height in pixel - /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal + /// User Id. + /// Width in pixel. + /// Height in pixel. + /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal. /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = UserController.Instance.GetUserProfilePictureUrl(userInfo.UserID, 32, 32) + /// code behind - avatar.ImageUrl = UserController.Instance.GetUserProfilePictureUrl(userInfo.UserID, 32, 32). /// public string GetUserProfilePictureUrl(int userId, int width, int height) { @@ -546,7 +605,7 @@ public string GetUserProfilePictureUrl(int userId, int width, int height) public bool IsValidUserName(string userName) { - // Validate username against bad characters; it must not start or end with space, + // Validate username against bad characters; it must not start or end with space, // must not contain control characters, and not contain special punctuations // Printable ASCII: " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" // Fallback to default if there is no host setting configured @@ -561,7 +620,7 @@ public string GetUserProfilePictureUrl(int portalId, int userId, int width, int { var url = $"/DnnImageHandler.ashx?mode=profilepic&userId={userId}&h={width}&w={height}"; - var childPortalAlias = Globals.ResolveUrl(GetUserProfilePictureUrl(userId, width, height)); + var childPortalAlias = Globals.ResolveUrl(this.GetUserProfilePictureUrl(userId, width, height)); var cdv = GetProfilePictureCdv(portalId, userId); return childPortalAlias.StartsWith(Globals.ApplicationPath) @@ -569,12 +628,29 @@ public string GetUserProfilePictureUrl(int portalId, int userId, int width, int : Globals.ApplicationPath + childPortalAlias + url + cdv; } + /// ----------------------------------------------------------------------------- + /// + /// Update all the Users Display Names. + /// + /// ----------------------------------------------------------------------------- + public void UpdateDisplayNames() + { + int portalId = GetEffectivePortalId(this.PortalId); + + var arrUsers = GetUsers(this.PortalId); + foreach (UserInfo objUser in arrUsers) + { + objUser.UpdateDisplayName(this.DisplayFormat); + UpdateUser(portalId, objUser); + } + } + private static string GetChildPortalAlias() { var settings = PortalController.Instance.GetCurrentPortalSettings(); var currentAlias = settings.PortalAlias.HTTPAlias; var index = currentAlias.IndexOf('/'); - var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : ""; + var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : string.Empty; return childPortalAlias; } @@ -599,6 +675,7 @@ private static string GetProfilePictureCdv(int userId) cdv = "&cdv=" + photoFile.LastModifiedOnDate.Ticks; } } + return cdv; } @@ -622,51 +699,8 @@ private static string GetProfilePictureCdv(int portalId, int userId) cdv = "&cdv=" + photoFile.LastModifiedOnDate.Ticks; } } - return cdv; - } - - /// ----------------------------------------------------------------------------- - /// - /// Update all the Users Display Names - /// - /// ----------------------------------------------------------------------------- - public void UpdateDisplayNames() - { - int portalId = GetEffectivePortalId(PortalId); - - var arrUsers = GetUsers(PortalId); - foreach (UserInfo objUser in arrUsers) - { - objUser.UpdateDisplayName(DisplayFormat); - UpdateUser(portalId, objUser); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the number count for all duplicate e-mail adresses in the database - /// - /// ----------------------------------------------------------------------------- - public static int GetDuplicateEmailCount() - { - return DataProvider.Instance().GetDuplicateEmailCount(PortalSettings.Current.PortalId); - } - - #endregion - - #region Public Helper Methods - - /// - /// add new userportal record (used for creating sites with existing user) - /// - /// portalid - /// userid - public static void AddUserPortal(int portalId, int userId) - { - Requires.NotNullOrEmpty("portalId", portalId.ToString()); - Requires.NotNullOrEmpty("userId", userId.ToString()); - MembershipProvider.Instance().AddUserPortal(portalId, userId); + return cdv; } /// @@ -707,7 +741,7 @@ public static void ResetTermsAgreement(int portalId) /// /// A user may request that their account be removed. This sets a flag on the user portal - /// so further processing may occur manually by the site admins + /// so further processing may occur manually by the site admins. /// /// The user that desires to be removed. public static void UserRequestsRemoval(UserInfo user, bool remove) @@ -718,7 +752,7 @@ public static void UserRequestsRemoval(UserInfo user, bool remove) /// ----------------------------------------------------------------------------- /// - /// ChangePassword attempts to change the users password + /// ChangePassword attempts to change the users password. /// /// /// @@ -731,15 +765,15 @@ public static bool ChangePassword(UserInfo user, string oldPassword, string newP { bool passwordChanged; - //Although we would hope that the caller has already validated the password, - //Validate the new Password + // Although we would hope that the caller has already validated the password, + // Validate the new Password if (ValidatePassword(newPassword)) { passwordChanged = MembershipProvider.Instance().ChangePassword(user, oldPassword, newPassword); if (passwordChanged) { - //Update User + // Update User user.Membership.UpdatePassword = false; UpdateUser(user.PortalID, user); } @@ -748,12 +782,13 @@ public static bool ChangePassword(UserInfo user, string oldPassword, string newP { throw new Exception("Invalid Password"); } + return passwordChanged; } /// /// overload will validate the token and if valid change the password - /// it does not require an old password as it supports hashed passwords + /// it does not require an old password as it supports hashed passwords. /// /// The new password. /// /// The reset token, typically supplied through a password reset email. @@ -765,35 +800,38 @@ public static bool ChangePasswordByToken(int portalid, string username, string n Guid resetTokenGuid = new Guid(resetToken); var user = GetUserByName(portalid, username); - //if user does not exist return false + + // if user does not exist return false if (user == null) { return false; } - //check if the token supplied is the same as the users and is still valid + + // check if the token supplied is the same as the users and is still valid if (user.PasswordResetToken != resetTokenGuid || user.PasswordResetExpiration < DateTime.Now) { return false; } + var m = new MembershipPasswordController(); if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword)) { return false; } - //Although we would hope that the caller has already validated the password, - //Validate the new Password + // Although we would hope that the caller has already validated the password, + // Validate the new Password if (ValidatePassword(newPassword)) { passwordChanged = MembershipProvider.Instance().ResetAndChangePassword(user, newPassword); - //update reset token values to ensure token is 1-time use + // update reset token values to ensure token is 1-time use user.PasswordResetExpiration = DateTime.MinValue; user.PasswordResetToken = Guid.NewGuid(); if (passwordChanged) { - //Update User + // Update User user.Membership.UpdatePassword = false; UpdateUser(user.PortalID, user); } @@ -802,13 +840,14 @@ public static bool ChangePasswordByToken(int portalid, string username, string n { throw new Exception("Invalid Password"); } + return passwordChanged; } /// /// overload will validate the token and if valid change the password /// it does not require an old password as it supports hashed passwords - /// errorMessage will define why reset failed + /// errorMessage will define why reset failed. /// /// The new password. /// The reset token, typically supplied through a password reset email. @@ -820,18 +859,21 @@ public static bool ChangePasswordByToken(int portalid, string username, string n Guid resetTokenGuid = new Guid(resetToken); var user = GetUserByName(portalid, username); - //if user does not exist return false + + // if user does not exist return false if (user == null) { errorMessage = Localization.GetString("PasswordResetFailed_UserUndefined"); return false; } - //check if the token supplied is the same as the users and is still valid + + // check if the token supplied is the same as the users and is still valid if (user.PasswordResetToken != resetTokenGuid || user.PasswordResetExpiration < DateTime.Now) { errorMessage = Localization.GetString("PasswordResetFailed_ResetLinkExpired"); return false; } + var m = new MembershipPasswordController(); if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword, false)) { @@ -839,8 +881,8 @@ public static bool ChangePasswordByToken(int portalid, string username, string n return false; } - //Although we would hope that the caller has already validated the password, - //Validate the new Password + // Although we would hope that the caller has already validated the password, + // Validate the new Password if (ValidatePassword(newPassword)) { try @@ -849,15 +891,15 @@ public static bool ChangePasswordByToken(int portalid, string username, string n if (passwordChanged) { - //update reset token values to ensure token is 1-time use + // update reset token values to ensure token is 1-time use user.PasswordResetExpiration = DateTime.MinValue; user.PasswordResetToken = Guid.NewGuid(); - //Update User + // Update User user.Membership.UpdatePassword = false; UpdateUser(user.PortalID, user); - m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword, true); //add the password into history. + m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword, true); // add the password into history. } else { @@ -869,18 +911,19 @@ public static bool ChangePasswordByToken(int portalid, string username, string n passwordChanged = false; errorMessage = Localization.GetString("PasswordResetFailed_WrongAnswer"); } - } else { throw new Exception("Invalid Password"); } + return passwordChanged; } + /// ----------------------------------------------------------------------------- /// /// ChangePasswordQuestionAndAnswer attempts to change the users password Question - /// and PasswordAnswer + /// and PasswordAnswer. /// /// /// @@ -892,16 +935,16 @@ public static bool ChangePasswordByToken(int portalid, string username, string n /// ----------------------------------------------------------------------------- public static bool ChangePasswordQuestionAndAnswer(UserInfo user, string password, string passwordQuestion, string passwordAnswer) { - EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, "", EventLogController.EventLogType.USER_UPDATED); + EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_UPDATED); return MembershipProvider.Instance().ChangePasswordQuestionAndAnswer(user, password, passwordQuestion, passwordAnswer); } /// /// update username in the system - /// works around membershipprovider limitation + /// works around membershipprovider limitation. /// - /// user id - /// new one + /// user id. + /// new one. public static void ChangeUsername(int userId, string newUsername) { MembershipProvider.Instance().ChangeUsername(userId, newUsername); @@ -913,6 +956,7 @@ public static void CheckInsecurePassword(string username, string password, ref U { loginStatus = UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; } + if (username == "host" && (password == "host" || password == "dnnhost")) { loginStatus = UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD; @@ -922,9 +966,9 @@ public static void CheckInsecurePassword(string username, string password, ref U /// /// Copys a user to a different portal. /// - /// The user to copy - /// The destination portal - /// A flag that indicates whether to merge the original user + /// The user to copy. + /// The destination portal. + /// A flag that indicates whether to merge the original user. public static void CopyUserToPortal(UserInfo user, PortalInfo destinationPortal, bool mergeUser) { var targetUser = GetUserById(destinationPortal.PortalID, user.UserID); @@ -957,11 +1001,11 @@ public static void CopyUserToPortal(UserInfo user, PortalInfo destinationPortal, /// ----------------------------------------------------------------------------- /// - /// Creates a new User in the Data Store + /// Creates a new User in the Data Store. /// /// - /// The userInfo object to persist to the Database - /// The Created status ot the User + /// The userInfo object to persist to the Database. + /// The Created status ot the User. /// ----------------------------------------------------------------------------- public static UserCreateStatus CreateUser(ref UserInfo user) { @@ -970,58 +1014,59 @@ public static UserCreateStatus CreateUser(ref UserInfo user) /// ----------------------------------------------------------------------------- /// - /// Creates a new User in the Data Store + /// Creates a new User in the Data Store. /// /// - /// The userInfo object to persist to the Database - /// The sendEmailNotification flag defines whether registration email will be sent to user - /// The Created status ot the User + /// The userInfo object to persist to the Database. + /// The sendEmailNotification flag defines whether registration email will be sent to user. + /// The Created status ot the User. /// ----------------------------------------------------------------------------- public static UserCreateStatus CreateUser(ref UserInfo user, bool sendEmailNotification) { int portalId = user.PortalID; user.PortalID = GetEffectivePortalId(portalId); - //ensure valid GUID exists (covers case where password is randomly generated - has 24 hr validity as per other Admin user steps + + // ensure valid GUID exists (covers case where password is randomly generated - has 24 hr validity as per other Admin user steps var passwordExpiry = DateTime.Now.AddMinutes(1440); var passwordGuid = Guid.NewGuid(); user.PasswordResetExpiration = passwordExpiry; user.PasswordResetToken = passwordGuid; - //Create the User + // Create the User var createStatus = MembershipProvider.Instance().CreateUser(ref user); if (createStatus == UserCreateStatus.Success) { - //reapply guid/expiry (cleared when user is created) + // reapply guid/expiry (cleared when user is created) user.PasswordResetExpiration = passwordExpiry; user.PasswordResetToken = passwordGuid; UpdateUser(user.PortalID, user); - EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, "", EventLogController.EventLogType.USER_CREATED); + EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_CREATED); CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalId)); if (!user.IsSuperUser) { - //autoassign user to portal roles + // autoassign user to portal roles AutoAssignUsersToRoles(user, portalId); } EventManager.Instance.OnUserCreated(new UserEventArgs { User = user, SendNotification = sendEmailNotification }); } - //Reset PortalId + // Reset PortalId FixMemberPortalId(user, portalId); return createStatus; } /// ----------------------------------------------------------------------------- /// - /// Deletes all Unauthorized Users for a Portal + /// Deletes all Unauthorized Users for a Portal. /// /// - /// The Id of the Portal + /// The Id of the Portal. /// ----------------------------------------------------------------------------- public static void DeleteUnauthorizedUsers(int portalId) { - //DNN-6924 for superusers call GetUsers(includeDeleted, superUsersOnly, portalId) + // DNN-6924 for superusers call GetUsers(includeDeleted, superUsersOnly, portalId) var arrUsers = (portalId == -1) ? GetUsers(true, true, portalId) : GetUnAuthorizedUsers(portalId); for (int i = 0; i < arrUsers.Count; i++) { @@ -1038,20 +1083,20 @@ public static void DeleteUnauthorizedUsers(int portalId) /// ----------------------------------------------------------------------------- /// - /// Deletes an existing User from the Data Store + /// Deletes an existing User from the Data Store. /// /// - /// The userInfo object to delete from the Database - /// A flag that indicates whether an email notification should be sent - /// A flag that indicates whether the Portal Administrator should be deleted - /// A Boolean value that indicates whether the User was successfully deleted + /// The userInfo object to delete from the Database. + /// A flag that indicates whether an email notification should be sent. + /// A flag that indicates whether the Portal Administrator should be deleted. + /// A Boolean value that indicates whether the User was successfully deleted. /// ----------------------------------------------------------------------------- public static bool DeleteUser(ref UserInfo user, bool notify, bool deleteAdmin) { int portalId = user.PortalID; user.PortalID = GetEffectivePortalId(portalId); - // If the HTTP Current Context is unavailable (e.g. when called from within a SchedulerClient) GetCurrentPortalSettings() returns null and the + // If the HTTP Current Context is unavailable (e.g. when called from within a SchedulerClient) GetCurrentPortalSettings() returns null and the // PortalSettings are created/loaded for the portal (originally) assigned to the user. var portalSettings = PortalController.Instance.GetCurrentPortalSettings() ?? new PortalSettings(portalId); @@ -1059,25 +1104,25 @@ public static bool DeleteUser(ref UserInfo user, bool notify, bool deleteAdmin) if (canDelete) { - //Delete Permissions + // Delete Permissions DeleteUserPermissions(user); canDelete = MembershipProvider.Instance().DeleteUser(user); } if (canDelete) { - //Obtain PortalSettings from Current Context or from the users (original) portal if the HTTP Current Context is unavailable. + // Obtain PortalSettings from Current Context or from the users (original) portal if the HTTP Current Context is unavailable. EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_DELETED); if (notify && !user.IsSuperUser) { - //send email notification to portal administrator that the user was removed from the portal + // send email notification to portal administrator that the user was removed from the portal SendDeleteEmailNotifications(user, portalSettings); } DataCache.ClearPortalUserCountCache(user.PortalID); DataCache.ClearUserCache(user.PortalID, user.Username); - //also clear current portal's cache if the user is a host user + // also clear current portal's cache if the user is a host user if (portalSettings.PortalId != portalId) { DataCache.ClearPortalCache(portalSettings.PortalId, false); @@ -1089,7 +1134,7 @@ public static bool DeleteUser(ref UserInfo user, bool notify, bool deleteAdmin) { PortalId = portalId, AuthorUserId = user.UserID, - SearchTypeId = Services.Search.Internals.SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId + SearchTypeId = Services.Search.Internals.SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId, }; DataProvider.Instance().AddSearchDeletedItems(document); @@ -1104,12 +1149,12 @@ public static bool DeleteUser(ref UserInfo user, bool notify, bool deleteAdmin) /// ----------------------------------------------------------------------------- /// - /// Deletes all Users for a Portal + /// Deletes all Users for a Portal. /// /// - /// The Id of the Portal - /// A flag that indicates whether an email notification should be sent - /// A flag that indicates whether the Portal Administrator should be deleted + /// The Id of the Portal. + /// A flag that indicates whether an email notification should be sent. + /// A flag that indicates whether the Portal Administrator should be deleted. /// ----------------------------------------------------------------------------- public static void DeleteUsers(int portalId, bool notify, bool deleteAdmin) { @@ -1123,9 +1168,9 @@ public static void DeleteUsers(int portalId, bool notify, bool deleteAdmin) /// ----------------------------------------------------------------------------- /// - /// Generates a new random password (Length = Minimum Length + 4) + /// Generates a new random password (Length = Minimum Length + 4). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public static string GeneratePassword() { @@ -1134,10 +1179,10 @@ public static string GeneratePassword() /// ----------------------------------------------------------------------------- /// - /// Generates a new random password + /// Generates a new random password. /// /// The length of password to generate. - /// A String + /// A String. /// ----------------------------------------------------------------------------- public static string GeneratePassword(int length) { @@ -1146,18 +1191,19 @@ public static string GeneratePassword(int length) /// ----------------------------------------------------------------------------- /// - /// GetCachedUser retrieves the User from the Cache, or fetches a fresh copy if - /// not in cache or if Cache settings not set to HeavyCaching + /// GetCachedUser retrieves the User from the Cache, or fetches a fresh copy if + /// not in cache or if Cache settings not set to HeavyCaching. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The username of the user being retrieved. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public static UserInfo GetCachedUser(int portalId, string username) { var masterPortalId = GetEffectivePortalId(portalId); + // user is cached inside the MembershipProvider.Instance().GetUserByUserName method var user = MembershipProvider.Instance().GetUserByUserName(masterPortalId, username); FixMemberPortalId(user, portalId); @@ -1181,10 +1227,10 @@ public static ArrayList GetDeletedUsers(int portalId) /// ----------------------------------------------------------------------------- /// - /// Gets a collection of Online Users + /// Gets a collection of Online Users. /// - /// The Id of the Portal - /// An ArrayList of UserInfo objects + /// The Id of the Portal. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public static ArrayList GetOnlineUsers(int portalId) @@ -1194,12 +1240,13 @@ public static ArrayList GetOnlineUsers(int portalId) /// ----------------------------------------------------------------------------- /// - /// Gets the Current Password Information for the User + /// Gets the Current Password Information for the User. /// /// This method will only return the password if the memberProvider supports /// and is using a password encryption method that supports decryption. /// The user whose Password information we are retrieving. /// The answer to the "user's" password Question. + /// /// ----------------------------------------------------------------------------- public static string GetPassword(ref UserInfo user, string passwordAnswer) { @@ -1209,9 +1256,10 @@ public static string GetPassword(ref UserInfo user, string passwordAnswer) } else { - //Throw a configuration exception as password retrieval is not enabled + // Throw a configuration exception as password retrieval is not enabled throw new ConfigurationErrorsException("Password Retrieval is not enabled"); } + return user.Membership.Password; } @@ -1222,11 +1270,11 @@ public static ArrayList GetUnAuthorizedUsers(int portalId, bool includeDeleted, /// ----------------------------------------------------------------------------- /// - /// GetUnAuthorizedUsers gets all the users of the portal, that are not authorized + /// GetUnAuthorizedUsers gets all the users of the portal, that are not authorized. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- public static ArrayList GetUnAuthorizedUsers(int portalId) @@ -1236,13 +1284,13 @@ public static ArrayList GetUnAuthorizedUsers(int portalId) /// ----------------------------------------------------------------------------- /// - /// GetUser retrieves a User from the DataStore + /// GetUser retrieves a User from the DataStore. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The Id of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public static UserInfo GetUserById(int portalId, int userId) { @@ -1261,6 +1309,7 @@ public static UserInfo GetUserById(int portalId, int userId) { userFound = lookUp.TryGetValue(userId, out userName); } + if (userFound) { user = GetCachedUser(portalId, userName); @@ -1277,17 +1326,18 @@ public static UserInfo GetUserById(int portalId, int userId) } } } + return user; } /// ----------------------------------------------------------------------------- /// - /// GetUserByUserName retrieves a User from the DataStore + /// GetUserByUserName retrieves a User from the DataStore. /// /// /// /// The username of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public static UserInfo GetUserByName(string username) { @@ -1296,13 +1346,13 @@ public static UserInfo GetUserByName(string username) /// ----------------------------------------------------------------------------- /// - /// GetUserByUserName retrieves a User from the DataStore + /// GetUserByUserName retrieves a User from the DataStore. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The username of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public static UserInfo GetUserByName(int portalId, string username) { @@ -1323,12 +1373,12 @@ public static UserInfo GetUserByPasswordResetToken(int portalId, string resetTok /// ----------------------------------------------------------------------------- /// - /// GetUserCountByPortal gets the number of users in the portal + /// GetUserCountByPortal gets the number of users in the portal. /// /// /// - /// The Id of the Portal - /// The no of users + /// The Id of the Portal. + /// The no of users. /// ----------------------------------------------------------------------------- public static int GetUserCountByPortal(int portalId) { @@ -1339,10 +1389,10 @@ public static int GetUserCountByPortal(int portalId) /// ----------------------------------------------------------------------------- /// - /// Retruns a String corresponding to the Registration Status of the User + /// Retruns a String corresponding to the Registration Status of the User. /// - /// The AUserCreateStatus - /// A String + /// The AUserCreateStatus. + /// A String. /// ----------------------------------------------------------------------------- public static string GetUserCreateStatus(UserCreateStatus userRegistrationStatus) { @@ -1392,7 +1442,7 @@ public static string GetUserCreateStatus(UserCreateStatus userRegistrationStatus /// ----------------------------------------------------------------------------- /// - /// Gets the Membership Information for the User + /// Gets the Membership Information for the User. /// /// /// The user whose Membership information we are retrieving. @@ -1407,10 +1457,11 @@ public static void GetUserMembership(UserInfo user) /// ----------------------------------------------------------------------------- /// - /// Gets the Default Settings for the Module + /// Gets the Default Settings for the Module. /// /// /// + /// /// ----------------------------------------------------------------------------- public static Hashtable GetDefaultUserSettings() { @@ -1421,17 +1472,18 @@ public static Hashtable GetDefaultUserSettings() { portalId = portalSettings.PortalId; } + return GetUserSettings(portalId, new Hashtable()); } /// ----------------------------------------------------------------------------- /// - /// GetUserSettings retrieves the UserSettings from the User + /// GetUserSettings retrieves the UserSettings from the User. /// /// /// - /// The Id of the Portal - /// The Settings Hashtable + /// The Id of the Portal. + /// The Settings Hashtable. /// ----------------------------------------------------------------------------- public static Hashtable GetUserSettings(int portalId) { @@ -1445,6 +1497,7 @@ public static Hashtable GetUserSettings(int portalId) { currentPortalSettings = PortalController.Instance.GetPortalSettings(portalId); } + if (settingsDictionary != null) { foreach (KeyValuePair kvp in settingsDictionary) @@ -1452,7 +1505,7 @@ public static Hashtable GetUserSettings(int portalId) int index = kvp.Key.IndexOf("_"); if (index > 0) { - //Get the prefix + // Get the prefix string prefix = kvp.Key.Substring(0, index + 1); switch (prefix) { @@ -1475,10 +1528,11 @@ public static Hashtable GetUserSettings(int portalId) settings[kvp.Key] = (UsersControl)Convert.ToInt32(kvp.Value); break; default: - //update value or add any new values + // update value or add any new values settings[kvp.Key] = kvp.Value; break; } + break; } } @@ -1492,16 +1546,17 @@ public static Hashtable GetUserSettings(int portalId) settings[kvp.Key] = kvp.Value; } } + return settings; } /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal + /// GetUsers gets all the users of the portal. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- public static ArrayList GetUsers(int portalId) @@ -1511,11 +1566,11 @@ public static ArrayList GetUsers(int portalId) /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal + /// GetUsers gets all the users of the portal. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// Include Deleted Users. /// Only get super users. /// An ArrayList of UserInfo objects. @@ -1528,13 +1583,13 @@ public static ArrayList GetUsers(bool includeDeleted, bool superUsersOnly, int p /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal, by page + /// GetUsers gets all the users of the portal, by page. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- @@ -1545,13 +1600,13 @@ public static ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal, by page + /// GetUsers gets all the users of the portal, by page. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include Deleted Users. /// Only get super users. @@ -1565,14 +1620,14 @@ public static ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref /// ----------------------------------------------------------------------------- /// /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression + /// filter expression. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The email address to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- @@ -1585,13 +1640,13 @@ public static ArrayList GetUsersByEmail(int portalId, string emailToMatch, int p /// /// GetUserByEmail gets one single user matching the email address provided /// This will only be useful in portals without duplicate email addresses - /// filter expression + /// filter expression. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The email address to use to find a match. - /// A single user object or null if no user found + /// A single user object or null if no user found. /// ----------------------------------------------------------------------------- public static UserInfo GetUserByEmail(int portalId, string emailToMatch) { @@ -1600,20 +1655,21 @@ public static UserInfo GetUserByEmail(int portalId, string emailToMatch) { return GetUserById(portalId, uid); } + return null; } /// ----------------------------------------------------------------------------- /// /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression + /// filter expression. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The email address to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include Deleted Users. /// Only get super users. @@ -1627,15 +1683,15 @@ public static ArrayList GetUsersByEmail(int portalId, string emailToMatch, int p /// ----------------------------------------------------------------------------- /// /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter + /// the profile property pased as a parameter. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The name of the property being matched. /// The value of the property being matched. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- @@ -1647,15 +1703,15 @@ public static ArrayList GetUsersByProfileProperty(int portalId, string propertyN /// ----------------------------------------------------------------------------- /// /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter + /// the profile property pased as a parameter. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The name of the property being matched. /// The value of the property being matched. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include Deleted Users. /// Only get super users. @@ -1669,14 +1725,14 @@ public static ArrayList GetUsersByProfileProperty(int portalId, string propertyN /// ----------------------------------------------------------------------------- /// /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression + /// filter expression. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The username to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- @@ -1688,14 +1744,14 @@ public static ArrayList GetUsersByUserName(int portalId, string userNameToMatch, /// ----------------------------------------------------------------------------- /// /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression + /// filter expression. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The username to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include Deleted Users. /// Only get super users. @@ -1709,14 +1765,14 @@ public static ArrayList GetUsersByUserName(int portalId, string userNameToMatch, /// ----------------------------------------------------------------------------- /// /// GetUsersByDisplayName gets all the users of the portal whose display name matches a provided - /// filter expression + /// filter expression. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The display name to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include Deleted Users. /// Only get super users. @@ -1730,9 +1786,9 @@ public static ArrayList GetUsersByDisplayName(int portalId, string nameToMatch, /// /// Move a user to a different portal. /// - /// The user to move - /// The destination portal - /// A flag that indicates whether to merge the original user + /// The user to move. + /// The destination portal. + /// A flag that indicates whether to merge the original user. public static void MoveUserToPortal(UserInfo user, PortalInfo portal, bool mergeUser) { CopyUserToPortal(user, portal, mergeUser); @@ -1741,9 +1797,9 @@ public static void MoveUserToPortal(UserInfo user, PortalInfo portal, bool merge /// /// Permanently deletes all users marked as deleted from a portal. It will delete the membership - /// user as well if the user has no other portals + /// user as well if the user has no other portals. /// - /// Portal ID to get the deleted users for + /// Portal ID to get the deleted users for. public static void RemoveDeletedUsers(int portalId) { var arrUsers = GetDeletedUsers(portalId); @@ -1758,29 +1814,29 @@ public static void RemoveDeletedUsers(int portalId) } /// - /// Permanently delete a user and the associated user folder on disk. + /// Permanently delete a user and the associated user folder on disk. /// This also deletes the membership user if the user is /// not a member of any other portal. /// - /// The user to delete + /// The user to delete. /// public static bool RemoveUser(UserInfo user) { int portalId = user.PortalID; user.PortalID = GetEffectivePortalId(portalId); - //Remove the User + // Remove the User var retValue = MembershipProvider.Instance().RemoveUser(user); - if ((retValue)) + if (retValue) { // Obtain PortalSettings from Current Context var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - //Log event + // Log event EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_REMOVED); - //Delete userFolder - DNN-3787 + // Delete userFolder - DNN-3787 DeleteUserFolder(user); DataCache.ClearPortalCache(portalId, false); @@ -1789,16 +1845,46 @@ public static bool RemoveUser(UserInfo user) EventManager.Instance.OnUserRemoved(new UserEventArgs { User = user }); } - //Reset PortalId + // Reset PortalId FixMemberPortalId(user, portalId); return retValue; } /// - /// Delete the contents and folder that belongs to a user in a specific portal + /// reset and change password + /// used by admin/host users who do not need to supply an "old" password. + /// + /// user being changed. + /// new password. + /// + public static bool ResetAndChangePassword(UserInfo user, string newPassword) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (GetCurrentUserInternal().IsInRole(portalSettings.AdministratorRoleName)) + { + string resetPassword = ResetPassword(user, string.Empty); + return ChangePassword(user, resetPassword, newPassword); + } + + return false; + } + + public static bool ResetAndChangePassword(UserInfo user, string oldPassword, string newPassword) + { + if (System.Web.Security.Membership.ValidateUser(user.Username, oldPassword)) + { + string resetPassword = ResetPassword(user, string.Empty); + return ChangePassword(user, resetPassword, newPassword); + } + + return false; + } + + /// + /// Delete the contents and folder that belongs to a user in a specific portal. /// - /// The user for whom to delete the folder. + /// The user for whom to delete the folder. /// Note the PortalID is taken to specify which portal to delete the folder from. private static void DeleteUserFolder(UserInfo user) { @@ -1813,7 +1899,7 @@ private static void DeleteUserFolder(UserInfo user) if (notDeletedSubfolders.Count == 0) { - //try to remove the parent folder if there is no other users use this folder. + // try to remove the parent folder if there is no other users use this folder. var parentFolder = FolderManager.Instance.GetFolder(userFolder.ParentID); FolderManager.Instance.Synchronize(folderPortalId, parentFolder.FolderPath, true, true); if (parentFolder != null && !FolderManager.Instance.GetFolders(parentFolder).Any()) @@ -1822,7 +1908,7 @@ private static void DeleteUserFolder(UserInfo user) if (notDeletedSubfolders.Count == 0) { - //try to remove the root folder if there is no other users use this folder. + // try to remove the root folder if there is no other users use this folder. var rootFolder = FolderManager.Instance.GetFolder(parentFolder.ParentID); FolderManager.Instance.Synchronize(folderPortalId, rootFolder.FolderPath, true, true); if (rootFolder != null && !FolderManager.Instance.GetFolders(rootFolder).Any()) @@ -1835,41 +1921,14 @@ private static void DeleteUserFolder(UserInfo user) } } - /// - /// reset and change password - /// used by admin/host users who do not need to supply an "old" password - /// - /// user being changed - /// new password - /// - public static bool ResetAndChangePassword(UserInfo user, string newPassword) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (GetCurrentUserInternal().IsInRole(portalSettings.AdministratorRoleName)) - { - string resetPassword = ResetPassword(user, String.Empty); - return ChangePassword(user, resetPassword, newPassword); - } - return false; - } - - public static bool ResetAndChangePassword(UserInfo user, string oldPassword, string newPassword) - { - if (System.Web.Security.Membership.ValidateUser(user.Username, oldPassword)) - { - string resetPassword = ResetPassword(user, String.Empty); - return ChangePassword(user, resetPassword, newPassword); - } - return false; - } - /// ----------------------------------------------------------------------------- /// - /// Resets the password for the specified user + /// Resets the password for the specified user. /// - /// Resets the user's password + /// Resets the user's password. /// The user whose Password information we are resetting. /// The answer to the "user's" password Question. + /// /// ----------------------------------------------------------------------------- public static string ResetPassword(UserInfo user, string passwordAnswer) { @@ -1879,9 +1938,10 @@ public static string ResetPassword(UserInfo user, string passwordAnswer) } else { - //Throw a configuration exception as password reset is not enabled + // Throw a configuration exception as password reset is not enabled throw new ConfigurationErrorsException("Password Reset is not enabled"); } + return user.Membership.Password; } @@ -1911,6 +1971,7 @@ public static bool ResetPasswordToken(UserInfo user, bool sendEmail) var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); return Mail.SendMail(user, MessageType.PasswordReminder, portalSettings) == string.Empty; } + return true; } @@ -1926,25 +1987,25 @@ public static bool RestoreUser(ref UserInfo user) int portalId = user.PortalID; user.PortalID = GetEffectivePortalId(portalId); - //Restore the User + // Restore the User var retValue = MembershipProvider.Instance().RestoreUser(user); - if ((retValue)) + if (retValue) { - //restore user permissions + // restore user permissions RestoreUserPermissions(user); // Obtain PortalSettings from Current Context var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - //Log event + // Log event EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_RESTORED); DataCache.ClearPortalUserCountCache(user.PortalID); DataCache.ClearUserCache(user.PortalID, user.Username); } - //Reset PortalId + // Reset PortalId FixMemberPortalId(user, portalId); UpdateUser(portalId, GetUserById(portalId, user.UserID)); return retValue; @@ -1957,17 +2018,18 @@ public static string SettingsKey(int portalId) /// ----------------------------------------------------------------------------- /// - /// Unlocks the User's Account + /// Unlocks the User's Account. /// /// /// The user whose account is being Unlocked. + /// /// ----------------------------------------------------------------------------- public static bool UnLockUser(UserInfo user) { int portalId = user.PortalID; user.PortalID = GetEffectivePortalId(portalId); - //Unlock the User + // Unlock the User var retValue = MembershipProvider.Instance().UnLockUser(user); DataCache.ClearUserCache(portalId, user.Username); UpdateUser(portalId, GetUserById(portalId, user.UserID)); @@ -1976,10 +2038,10 @@ public static bool UnLockUser(UserInfo user) /// ----------------------------------------------------------------------------- /// - /// Updates a User + /// Updates a User. /// - /// The Id of the Portal - /// The use to update + /// The Id of the Portal. + /// The use to update. /// /// /// ----------------------------------------------------------------------------- @@ -1990,11 +2052,11 @@ public static void UpdateUser(int portalId, UserInfo user) /// ----------------------------------------------------------------------------- /// - /// updates a user + /// updates a user. /// - /// the portalid of the user - /// the user object - /// whether or not the update calls the eventlog - the eventlogtype must still be enabled for logging to occur + /// the portalid of the user. + /// the user object. + /// whether or not the update calls the eventlog - the eventlogtype must still be enabled for logging to occur. /// /// public static void UpdateUser(int portalId, UserInfo user, bool loggedAction) @@ -2004,11 +2066,11 @@ public static void UpdateUser(int portalId, UserInfo user, bool loggedAction) /// ----------------------------------------------------------------------------- /// - /// updates a user + /// updates a user. /// - /// the portalid of the user - /// the user object - /// whether or not the update calls the eventlog - the eventlogtype must still be enabled for logging to occur + /// the portalid of the user. + /// the user object. + /// whether or not the update calls the eventlog - the eventlogtype must still be enabled for logging to occur. /// Whether to send notification to the user about the update (i.e. a notification if the user was approved). /// /// @@ -2017,80 +2079,22 @@ public static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bo UpdateUser(portalId, user, loggedAction, sendNotification, true); } - /// ----------------------------------------------------------------------------- - /// - /// updates a user - /// - /// the portalid of the user - /// the user object - /// whether or not the update calls the eventlog - the eventlogtype must still be enabled for logging to occur - /// Whether to send notification to the user about the update (i.e. a notification if the user was approved). - /// Whether clear cache after update user. - /// - /// This method is used internal because it should be use carefully, or it will caught cache doesn't clear correctly. - /// - internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bool sendNotification, bool clearCache) - { - var originalPortalId = user.PortalID; - portalId = GetEffectivePortalId(portalId); - user.PortalID = portalId; - - //clear the cache so that can get original info from database. - DataCache.RemoveCache(String.Format(DataCache.UserProfileCacheKey, portalId, user.Username)); - var oldUser = MembershipProvider.Instance().GetUser(user.PortalID, user.UserID); - var oldProfile = oldUser.Profile; //access the profile property to reload data from database. - - //Update the User - MembershipProvider.Instance().UpdateUser(user); - if (loggedAction) - { - //if the httpcontext is null, then get portal settings by portal id. - PortalSettings portalSettings = null; - if (HttpContext.Current != null) - { - portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - } - else if (portalId > Null.NullInteger) - { - portalSettings = new PortalSettings(portalId); - } - - EventLogController.Instance.AddLog(user, portalSettings, GetCurrentUserInternal().UserID, "", EventLogController.EventLogType.USER_UPDATED); - } - - EventManager.Instance.OnUserUpdated(new UpdateUserEventArgs { User = user, OldUser = oldUser }); - - //Reset PortalId - FixMemberPortalId(user, originalPortalId); - - //Remove the UserInfo from the Cache, as it has been modified - if (clearCache) - { - DataCache.ClearUserCache(portalId, user.Username); - } - - if (!user.Membership.Approving) return; - - user.Membership.ConfirmApproved(); - EventManager.Instance.OnUserApproved(new UserEventArgs { User = user }); - } - /// ----------------------------------------------------------------------------- /// /// Validates a User's credentials against the Data Store, and sets the Forms Authentication - /// Ticket - /// - /// The Id of the Portal the user belongs to - /// The user name of the User attempting to log in - /// The password of the User attempting to log in - /// The verification code of the User attempting to log in - /// The name of the Portal - /// The IP Address of the user attempting to log in - /// A UserLoginStatus enumeration that indicates the status of the + /// Ticket. + /// + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The verification code of the User attempting to log in. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. + /// A UserLoginStatus enumeration that indicates the status of the /// Login attempt. This value is returned by reference. - /// A flag that indicates whether the login credentials + /// A flag that indicates whether the login credentials /// should be persisted. - /// The UserInfo object representing a successful login + /// The UserInfo object representing a successful login. /// ----------------------------------------------------------------------------- public static UserInfo UserLogin(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus, bool createPersistentCookie) { @@ -2098,11 +2102,11 @@ public static UserInfo UserLogin(int portalId, string username, string password, loginStatus = UserLoginStatus.LOGIN_FAILURE; - //Validate the user + // Validate the user var objUser = ValidateUser(portalId, username, password, verificationCode, portalName, ip, ref loginStatus); if (objUser != null) { - //Call UserLogin overload + // Call UserLogin overload UserLogin(portalId, objUser, portalName, ip, createPersistentCookie); } else @@ -2110,18 +2114,18 @@ public static UserInfo UserLogin(int portalId, string username, string password, AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus); } - //return the User object + // return the User object return objUser; } /// ----------------------------------------------------------------------------- /// - /// Logs a Validated User in + /// Logs a Validated User in. /// - /// The Id of the Portal the user belongs to - /// The validated User - /// The name of the Portal - /// The IP Address of the user attempting to log in + /// The Id of the Portal the user belongs to. + /// The validated User. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. /// A flag that indicates whether the login credentials should be persisted. /// ----------------------------------------------------------------------------- public static void UserLogin(int portalId, UserInfo user, string portalName, string ip, bool createPersistentCookie) @@ -2132,12 +2136,12 @@ public static void UserLogin(int portalId, UserInfo user, string portalName, str if (user.LastIPAddress != ip) { - //Update User in Database with Last IP used + // Update User in Database with Last IP used user.LastIPAddress = ip; DataProvider.Instance().UpdateUserLastIpAddress(user.UserID, ip); } - //set the forms authentication cookie ( log the user in ) + // set the forms authentication cookie ( log the user in ) var security = PortalSecurity.Instance; security.SignIn(user, createPersistentCookie); @@ -2146,43 +2150,106 @@ public static void UserLogin(int portalId, UserInfo user, string portalName, str /// ----------------------------------------------------------------------------- /// - /// Validates a Password + /// updates a user. + /// + /// the portalid of the user. + /// the user object. + /// whether or not the update calls the eventlog - the eventlogtype must still be enabled for logging to occur. + /// Whether to send notification to the user about the update (i.e. a notification if the user was approved). + /// Whether clear cache after update user. + /// + /// This method is used internal because it should be use carefully, or it will caught cache doesn't clear correctly. + /// + internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bool sendNotification, bool clearCache) + { + var originalPortalId = user.PortalID; + portalId = GetEffectivePortalId(portalId); + user.PortalID = portalId; + + // clear the cache so that can get original info from database. + DataCache.RemoveCache(string.Format(DataCache.UserProfileCacheKey, portalId, user.Username)); + var oldUser = MembershipProvider.Instance().GetUser(user.PortalID, user.UserID); + var oldProfile = oldUser.Profile; // access the profile property to reload data from database. + + // Update the User + MembershipProvider.Instance().UpdateUser(user); + if (loggedAction) + { + // if the httpcontext is null, then get portal settings by portal id. + PortalSettings portalSettings = null; + if (HttpContext.Current != null) + { + portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + } + else if (portalId > Null.NullInteger) + { + portalSettings = new PortalSettings(portalId); + } + + EventLogController.Instance.AddLog(user, portalSettings, GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_UPDATED); + } + + EventManager.Instance.OnUserUpdated(new UpdateUserEventArgs { User = user, OldUser = oldUser }); + + // Reset PortalId + FixMemberPortalId(user, originalPortalId); + + // Remove the UserInfo from the Cache, as it has been modified + if (clearCache) + { + DataCache.ClearUserCache(portalId, user.Username); + } + + if (!user.Membership.Approving) + { + return; + } + + user.Membership.ConfirmApproved(); + EventManager.Instance.OnUserApproved(new UserEventArgs { User = user }); + } + + /// ----------------------------------------------------------------------------- + /// + /// Validates a Password. /// - /// The password to Validate - /// A boolean + /// The password to Validate. + /// A boolean. /// ----------------------------------------------------------------------------- public static bool ValidatePassword(string password) { - //Valid Length + // Valid Length var isValid = password.Length >= MembershipProviderConfig.MinPasswordLength; - //Validate NonAlphaChars + // Validate NonAlphaChars var rx = Globals.NonAlphanumericCharacters; if (rx.Matches(password).Count < MembershipProviderConfig.MinNonAlphanumericCharacters) { isValid = false; } - //Validate Regex - if (!String.IsNullOrEmpty(MembershipProviderConfig.PasswordStrengthRegularExpression) && isValid) + + // Validate Regex + if (!string.IsNullOrEmpty(MembershipProviderConfig.PasswordStrengthRegularExpression) && isValid) { isValid = Regex.IsMatch(password, MembershipProviderConfig.PasswordStrengthRegularExpression); } + return isValid; } /// ----------------------------------------------------------------------------- /// - /// Validates a User's credentials against the Data Store + /// Validates a User's credentials against the Data Store. /// - /// The Id of the Portal the user belongs to - /// The user name of the User attempting to log in - /// The password of the User attempting to log in - /// The verification code of the User attempting to log in - /// The name of the Portal - /// The IP Address of the user attempting to log in - /// A UserLoginStatus enumeration that indicates the status of the + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The verification code of the User attempting to log in. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. + /// A UserLoginStatus enumeration that indicates the status of the /// Login attempt. This value is returned by reference. - /// The UserInfo object representing a valid user + /// The UserInfo object representing a valid user. /// ----------------------------------------------------------------------------- public static UserInfo ValidateUser(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus) { @@ -2191,53 +2258,53 @@ public static UserInfo ValidateUser(int portalId, string username, string passwo /// ----------------------------------------------------------------------------- /// - /// Validates a User's credentials against the Data Store + /// Validates a User's credentials against the Data Store. /// - /// The Id of the Portal the user belongs to - /// The user name of the User attempting to log in - /// The password of the User attempting to log in - /// The type of Authentication Used - /// The verification code of the User attempting to log in - /// The name of the Portal - /// The IP Address of the user attempting to log in - /// A UserLoginStatus enumeration that indicates the status of the + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The type of Authentication Used. + /// The verification code of the User attempting to log in. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. + /// A UserLoginStatus enumeration that indicates the status of the /// Login attempt. This value is returned by reference. - /// The UserInfo object representing a valid user + /// The UserInfo object representing a valid user. /// ----------------------------------------------------------------------------- public static UserInfo ValidateUser(int portalId, string username, string password, string authType, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus) { loginStatus = UserLoginStatus.LOGIN_FAILURE; - //Try and Log the user in + // Try and Log the user in var user = MembershipProvider.Instance().UserLogin(GetEffectivePortalId(portalId), username, password, authType, verificationCode, ref loginStatus); if (loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT || loginStatus == UserLoginStatus.LOGIN_FAILURE || loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED) { - //User Locked Out so log to event log + // User Locked Out so log to event log AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus); } - //Check Default Accounts + // Check Default Accounts if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER) { CheckInsecurePassword(username, password, ref loginStatus); } - //Reset portalId + // Reset portalId FixMemberPortalId(user, portalId); - //return the User object + // return the User object return user; } /// ----------------------------------------------------------------------------- /// - /// Validates a User's Password and Profile + /// Validates a User's Password and Profile. /// - /// This overload takes a valid User (Credentials check out) and check whether the Password and Profile need updating - /// The Id of the Portal the user belongs to - /// The user attempting to log in + /// This overload takes a valid User (Credentials check out) and check whether the Password and Profile need updating. + /// The Id of the Portal the user belongs to. + /// The user attempting to log in. /// Ingore expired user. - /// The UserLoginStatus + /// The UserLoginStatus. /// ----------------------------------------------------------------------------- public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool ignoreExpiring) { @@ -2245,10 +2312,10 @@ public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool var validStatus = UserValidStatus.VALID; - //Check if Password needs to be updated + // Check if Password needs to be updated if (objUser.Membership.UpdatePassword) { - //Admin has forced password update + // Admin has forced password update validStatus = UserValidStatus.UPDATEPASSWORD; } else if (PasswordConfig.PasswordExpiry > 0) @@ -2256,12 +2323,12 @@ public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool var expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry); if (expiryDate < DateTime.Now) { - //Password Expired + // Password Expired validStatus = UserValidStatus.PASSWORDEXPIRED; } else if (expiryDate < DateTime.Now.AddDays(PasswordConfig.PasswordExpiryReminder) && (!ignoreExpiring)) { - //Password update reminder + // Password update reminder validStatus = UserValidStatus.PASSWORDEXPIRING; } } @@ -2278,7 +2345,7 @@ public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool } } - //Check if Profile needs updating + // Check if Profile needs updating if (validStatus == UserValidStatus.VALID) { var validProfile = Convert.ToBoolean(UserModuleBase.GetSetting(portalId, "Security_RequireValidProfileAtLogin")); @@ -2295,7 +2362,6 @@ public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool /// Tries to validate a verification code sent after a user is registered in a portal configured to use a verified registration. /// /// The verification code. - /// An null string if the verification code has been validated and the user has been approved. An error message otherwise. /// Thrown when provided verification code has been already used. /// Thrown when the provided verification code is invalid. /// Thrown when the user does not exist. @@ -2345,14 +2411,14 @@ public static void VerifyUser(string verificationCode) } /// - /// Returns a absolute URL for the user profile image while removing that of the deleted and super users + /// Returns a absolute URL for the user profile image while removing that of the deleted and super users. /// - /// Portal Id - /// user info - /// width in pixel - /// height in pixel - /// true if want show super users user profile picture, false otherwise - /// absolute user profile picture url + /// Portal Id. + /// user info. + /// width in pixel. + /// height in pixel. + /// true if want show super users user profile picture, false otherwise. + /// absolute user profile picture url. /// public static string GetProfileAvatarAbsoluteUrl(int portalId, UserInfo user, int width = 64, int height = 64, bool showSuperUsers = true) @@ -2363,23 +2429,23 @@ public static string GetProfileAvatarAbsoluteUrl(int portalId, UserInfo user, in } /// - /// Returns an absolute url given a relative url + /// Returns an absolute url given a relative url. /// - /// portal Id - /// relative url - /// absolute url + /// portal Id. + /// relative url. + /// absolute url. private static string GetAbsoluteUrl(int portalId, string relativeUrl) { if (relativeUrl.Contains("://")) { return relativeUrl; } + var portalAlias = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).First(p => p.IsPrimary); var domainName = GetDomainName(portalAlias); return Globals.AddHTTP(domainName + relativeUrl); } - private static string GetDomainName(PortalAliasInfo portalAlias) { var httpAlias = portalAlias.HTTPAlias; @@ -2395,8 +2461,5 @@ private static UserInfo GetUserByMembershipUserKey(int portalId, string membersh FixMemberPortalId(user, portalId); return user; } - - #endregion - } } diff --git a/DNN Platform/Library/Entities/Users/UserEventArgs.cs b/DNN Platform/Library/Entities/Users/UserEventArgs.cs index 0eab44e40d5..00a2c643110 100644 --- a/DNN Platform/Library/Entities/Users/UserEventArgs.cs +++ b/DNN Platform/Library/Entities/Users/UserEventArgs.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + public class UserEventArgs : EventArgs { public UserInfo User { get; set; } + public bool SendNotification { get; set; } } } diff --git a/DNN Platform/Library/Entities/Users/UserEventHandlers.cs b/DNN Platform/Library/Entities/Users/UserEventHandlers.cs index ad4b028cfe7..9d0e914f47f 100644 --- a/DNN Platform/Library/Entities/Users/UserEventHandlers.cs +++ b/DNN Platform/Library/Entities/Users/UserEventHandlers.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel.Composition; -using System.Globalization; -using DotNetNuke.Services.Mail; -using DotNetNuke.Services.Social.Notifications; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System.ComponentModel.Composition; + using System.Globalization; + + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.Social.Notifications; + [Export(typeof(IUserEventHandlers))] public class UserEventHandlers : IUserEventHandlers { @@ -41,6 +42,7 @@ public void UserApproved(object sender, UserEventArgs args) { UserRegistrationEmailNotifier.NotifyUser(args.User, MessageType.UserRegistrationPublic); } + DeleteAllNewUnauthorizedUserRegistrationNotifications(args.User.UserID); } diff --git a/DNN Platform/Library/Entities/Users/UserInfo.cs b/DNN Platform/Library/Entities/Users/UserInfo.cs index 9547a6385b4..b79d46ef03f 100644 --- a/DNN Platform/Library/Entities/Users/UserInfo.cs +++ b/DNN Platform/Library/Entities/Users/UserInfo.cs @@ -1,70 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Concurrent; -using System.ComponentModel; -using System.Globalization; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Tokens; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + using System.Collections.Concurrent; + using System.ComponentModel; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Tokens; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: UserInfo /// ----------------------------------------------------------------------------- /// - /// The UserInfo class provides Business Layer model for Users + /// The UserInfo class provides Business Layer model for Users. /// /// /// /// ----------------------------------------------------------------------------- [Serializable] public class UserInfo : BaseEntityInfo, IPropertyAccess - { - #region Private Members - + { private string _administratorRoleName; private UserMembership _membership; private UserProfile _profile; - private readonly ConcurrentDictionary _social = new ConcurrentDictionary(); - - #endregion - - #region Constructors - + private readonly ConcurrentDictionary _social = new ConcurrentDictionary(); + public UserInfo() { - IsDeleted = Null.NullBoolean; - UserID = Null.NullInteger; - PortalID = Null.NullInteger; - IsSuperUser = Null.NullBoolean; - AffiliateID = Null.NullInteger; - } - - #endregion - - #region Public Properties - + this.IsDeleted = Null.NullBoolean; + this.UserID = Null.NullInteger; + this.PortalID = Null.NullInteger; + this.IsSuperUser = Null.NullBoolean; + this.AffiliateID = Null.NullInteger; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the AffiliateId for this user + /// Gets or sets and sets the AffiliateId for this user. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -72,35 +58,41 @@ public UserInfo() /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Display Name + /// Gets or sets and sets the Display Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(3), Required(true), MaxLength(128)] + [SortOrder(3)] + [Required(true)] + [MaxLength(128)] public string DisplayName { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Email Address + /// Gets or sets and sets the Email Address. /// /// ----------------------------------------------------------------------------- - [SortOrder(4), MaxLength(256), Required(true), RegularExpressionValidator(Globals.glbEmailRegEx)] + [SortOrder(4)] + [MaxLength(256)] + [Required(true)] + [RegularExpressionValidator(Globals.glbEmailRegEx)] public string Email { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the First Name + /// Gets or sets and sets the First Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(1), MaxLength(50)] + [SortOrder(1)] + [MaxLength(50)] public string FirstName { - get { return Profile.FirstName; } - set { Profile.FirstName = value; } + get { return this.Profile.FirstName; } + set { this.Profile.FirstName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the User is deleted + /// Gets or sets a value indicating whether gets and sets whether the User is deleted. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -108,32 +100,32 @@ public string FirstName /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the User is a SuperUser + /// Gets or sets a value indicating whether gets and sets whether the User is a SuperUser. /// /// ----------------------------------------------------------------------------- [Browsable(false)] public bool IsSuperUser { get; set; } - - + /// - /// Gets whether the user is in the portal's administrators role + /// Gets a value indicating whether gets whether the user is in the portal's administrators role. /// public bool IsAdmin { get { - if (IsSuperUser) + if (this.IsSuperUser) { return true; } - PortalInfo ps = PortalController.Instance.GetPortal(PortalID); - return ps != null && IsInRole(ps.AdministratorRoleName); + + PortalInfo ps = PortalController.Instance.GetPortal(this.PortalID); + return ps != null && this.IsInRole(ps.AdministratorRoleName); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Last IP address used by user + /// Gets or sets and sets the Last IP address used by user. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -141,19 +133,20 @@ public bool IsAdmin /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Last Name + /// Gets or sets and sets the Last Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(2), MaxLength(50)] + [SortOrder(2)] + [MaxLength(50)] public string LastName { - get { return Profile.LastName; } - set { Profile.LastName = value; } + get { return this.Profile.LastName; } + set { this.Profile.LastName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Membership object + /// Gets or sets and sets the Membership object. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -161,35 +154,36 @@ public UserMembership Membership { get { - if (_membership == null) + if (this._membership == null) { - _membership = new UserMembership(this); - if ((Username != null) && (!String.IsNullOrEmpty(Username))) + this._membership = new UserMembership(this); + if ((this.Username != null) && (!string.IsNullOrEmpty(this.Username))) { UserController.GetUserMembership(this); } } - return _membership; + + return this._membership; } - set { _membership = value; } + + set { this._membership = value; } } /// - /// gets and sets the token created for resetting passwords + /// Gets or sets and sets the token created for resetting passwords. /// [Browsable(false)] public Guid PasswordResetToken { get; set; } /// - /// gets and sets the datetime that the PasswordResetToken is valid + /// Gets or sets and sets the datetime that the PasswordResetToken is valid. /// [Browsable(false)] public DateTime PasswordResetExpiration { get; set; } - - + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the PortalId + /// Gets or sets and sets the PortalId. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -197,7 +191,7 @@ public UserMembership Membership /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the user has agreed to the terms and conditions + /// Gets or sets a value indicating whether gets and sets whether the user has agreed to the terms and conditions. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -205,7 +199,7 @@ public UserMembership Membership /// ----------------------------------------------------------------------------- /// - /// Gets and sets when the user last agreed to the terms and conditions + /// Gets or sets and sets when the user last agreed to the terms and conditions. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -213,7 +207,7 @@ public UserMembership Membership /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the user has requested they be removed from the site + /// Gets or sets a value indicating whether gets and sets whether the user has requested they be removed from the site. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -221,7 +215,7 @@ public UserMembership Membership /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Profile Object + /// Gets or sets and sets the Profile Object. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -229,15 +223,17 @@ public UserProfile Profile { get { - if (_profile == null) + if (this._profile == null) { - _profile = new UserProfile(this); + this._profile = new UserProfile(this); UserInfo userInfo = this; ProfileController.GetUserProfile(ref userInfo); } - return _profile; + + return this._profile; } - set { _profile = value; } + + set { this._profile = value; } } [Browsable(false)] @@ -245,24 +241,27 @@ public string[] Roles { get { - var socialRoles = Social.Roles; - if (socialRoles.Count == 0) - return new string[0]; - - return (from r in Social.Roles + var socialRoles = this.Social.Roles; + if (socialRoles.Count == 0) + { + return new string[0]; + } + + return (from r in this.Social.Roles where r.Status == RoleStatus.Approved && (r.EffectiveDate < DateTime.Now || Null.IsNull(r.EffectiveDate)) && (r.ExpiryDate > DateTime.Now || Null.IsNull(r.ExpiryDate)) - select r.RoleName - ).ToArray(); + select r.RoleName) + .ToArray(); } + set { } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Social property + /// Gets and sets the Social property. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -270,13 +269,13 @@ public UserSocial Social { get { - return _social.GetOrAdd(PortalID, i => new UserSocial(this)); + return this._social.GetOrAdd(this.PortalID, i => new UserSocial(this)); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User Id + /// Gets or sets and sets the User Id. /// /// ----------------------------------------------------------------------------- [Browsable(false)] @@ -284,42 +283,52 @@ public UserSocial Social /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User Name + /// Gets or sets and sets the User Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(0), MaxLength(100), IsReadOnly(true), Required(true)] + [SortOrder(0)] + [MaxLength(100)] + [IsReadOnly(true)] + [Required(true)] public string Username { get; set; } - public string VanityUrl { get; set; } - - - #region IPropertyAccess Members + public string VanityUrl { get; set; } + [Browsable(false)] + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } + /// - /// Property access, initially provided for TokenReplace + /// Property access, initially provided for TokenReplace. /// - /// Name of the Property - /// format string - /// format provider for numbers, dates, currencies - /// userinfo of the user, who queries the data (used to determine permissions) - /// requested maximum access level, might be restricted due to user level + /// Name of the Property. + /// format string. + /// format provider for numbers, dates, currencies. + /// userinfo of the user, who queries the data (used to determine permissions). + /// requested maximum access level, might be restricted due to user level. /// out: flag, if property could be retrieved. - /// current value of the property for this userinfo object + /// current value of the property for this userinfo object. public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { Scope internScope; - if (UserID == -1 && currentScope > Scope.Configuration) + if (this.UserID == -1 && currentScope > Scope.Configuration) { - internScope = Scope.Configuration; //anonymous users only get access to displayname + internScope = Scope.Configuration; // anonymous users only get access to displayname } - else if (UserID != accessingUser.UserID && !isAdminUser(ref accessingUser) && currentScope > Scope.DefaultSettings) + else if (this.UserID != accessingUser.UserID && !this.isAdminUser(ref accessingUser) && currentScope > Scope.DefaultSettings) { - internScope = Scope.DefaultSettings; //registerd users can access username and userID as well + internScope = Scope.DefaultSettings; // registerd users can access username and userID as well } else { - internScope = currentScope; //admins and user himself can access all data + internScope = currentScope; // admins and user himself can access all data } + string outputFormat = format == string.Empty ? "g" : format; switch (propertyName.ToLowerInvariant()) { @@ -329,8 +338,9 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } + var ps = PortalSecurity.Instance; - var code = ps.Encrypt(Config.GetDecryptionkey(), PortalID + "-" + GetMembershipUserId()); + var code = ps.Encrypt(Config.GetDecryptionkey(), this.PortalID + "-" + this.GetMembershipUserId()); return code.Replace("+", ".").Replace("/", "-").Replace("=", "_"); case "affiliateid": if (internScope < Scope.SystemMessages) @@ -338,136 +348,105 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (AffiliateID.ToString(outputFormat, formatProvider)); + + return this.AffiliateID.ToString(outputFormat, formatProvider); case "displayname": if (internScope < Scope.Configuration) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return PropertyAccess.FormatString(DisplayName, format); + + return PropertyAccess.FormatString(this.DisplayName, format); case "email": if (internScope < Scope.DefaultSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (PropertyAccess.FormatString(Email, format)); - case "firstname": //using profile property is recommended! + + return PropertyAccess.FormatString(this.Email, format); + case "firstname": // using profile property is recommended! if (internScope < Scope.DefaultSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (PropertyAccess.FormatString(FirstName, format)); + + return PropertyAccess.FormatString(this.FirstName, format); case "issuperuser": if (internScope < Scope.Debug) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (IsSuperUser.ToString(formatProvider)); - case "lastname": //using profile property is recommended! + + return this.IsSuperUser.ToString(formatProvider); + case "lastname": // using profile property is recommended! if (internScope < Scope.DefaultSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (PropertyAccess.FormatString(LastName, format)); + + return PropertyAccess.FormatString(this.LastName, format); case "portalid": if (internScope < Scope.Configuration) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (PortalID.ToString(outputFormat, formatProvider)); + + return this.PortalID.ToString(outputFormat, formatProvider); case "userid": if (internScope < Scope.DefaultSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (UserID.ToString(outputFormat, formatProvider)); + + return this.UserID.ToString(outputFormat, formatProvider); case "username": if (internScope < Scope.DefaultSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (PropertyAccess.FormatString(Username, format)); - case "fullname": //fullname is obsolete, it will return DisplayName + + return PropertyAccess.FormatString(this.Username, format); + case "fullname": // fullname is obsolete, it will return DisplayName if (internScope < Scope.Configuration) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (PropertyAccess.FormatString(DisplayName, format)); + + return PropertyAccess.FormatString(this.DisplayName, format); case "roles": if (currentScope < Scope.SystemMessages) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - return (PropertyAccess.FormatString(string.Join(", ", Roles), format)); + + return PropertyAccess.FormatString(string.Join(", ", this.Roles), format); } + propertyNotFound = true; return string.Empty; } - - [Browsable(false)] - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } - - #endregion - - #endregion - - #region Private Methods - - /// - /// Determine, if accessing user is Administrator - /// - /// userinfo of the user to query - /// true, if user is portal administrator or superuser - private bool isAdminUser(ref UserInfo accessingUser) - { - if (accessingUser == null || accessingUser.UserID == -1) - { - return false; - } - if (String.IsNullOrEmpty(_administratorRoleName)) - { - PortalInfo ps = PortalController.Instance.GetPortal(accessingUser.PortalID); - _administratorRoleName = ps.AdministratorRoleName; - } - return accessingUser.IsInRole(_administratorRoleName) || accessingUser.IsSuperUser; - } - - private string GetMembershipUserId() - { - return MembershipProvider.Instance().GetProviderUserKey(this)?.Replace("-", string.Empty) ?? string.Empty; - } - - #endregion - - #region Public Methods - + /// ----------------------------------------------------------------------------- /// - /// IsInRole determines whether the user is in the role passed + /// IsInRole determines whether the user is in the role passed. /// - /// The role to check + /// The role to check. /// A Boolean indicating success or failure. /// ----------------------------------------------------------------------------- public bool IsInRole(string role) { - //super users should always be verified. - if (IsSuperUser) + // super users should always be verified. + if (this.IsSuperUser) { return role != "Unverified Users"; } @@ -476,64 +455,94 @@ public bool IsInRole(string role) { return true; } - if (UserID == Null.NullInteger && role == Globals.glbRoleUnauthUserName) + + if (this.UserID == Null.NullInteger && role == Globals.glbRoleUnauthUserName) { return true; } - if ("[" + UserID + "]" == role) + + if ("[" + this.UserID + "]" == role) { return true; } - var roles = Roles; + var roles = this.Roles; if (roles != null) { return roles.Any(s => s == role); } + return false; } /// ----------------------------------------------------------------------------- /// - /// Gets current time in User's timezone - /// - /// ----------------------------------------------------------------------------- + /// Gets current time in User's timezone. + /// + /// + /// ----------------------------------------------------------------------------- public DateTime LocalTime() { - return LocalTime(DateUtils.GetDatabaseUtcTime()); + return this.LocalTime(DateUtils.GetDatabaseUtcTime()); + } + + /// + /// Determine, if accessing user is Administrator. + /// + /// userinfo of the user to query. + /// true, if user is portal administrator or superuser. + private bool isAdminUser(ref UserInfo accessingUser) + { + if (accessingUser == null || accessingUser.UserID == -1) + { + return false; + } + + if (string.IsNullOrEmpty(this._administratorRoleName)) + { + PortalInfo ps = PortalController.Instance.GetPortal(accessingUser.PortalID); + this._administratorRoleName = ps.AdministratorRoleName; + } + + return accessingUser.IsInRole(this._administratorRoleName) || accessingUser.IsSuperUser; } + private string GetMembershipUserId() + { + return MembershipProvider.Instance().GetProviderUserKey(this)?.Replace("-", string.Empty) ?? string.Empty; + } + /// ----------------------------------------------------------------------------- /// - /// Convert utc time in User's timezone + /// Convert utc time in User's timezone. /// - /// Utc time to convert - /// ----------------------------------------------------------------------------- + /// Utc time to convert. + /// + /// ----------------------------------------------------------------------------- public DateTime LocalTime(DateTime utcTime) { - if (UserID > Null.NullInteger) + if (this.UserID > Null.NullInteger) { - return TimeZoneInfo.ConvertTime(utcTime, TimeZoneInfo.Utc, Profile.PreferredTimeZone); + return TimeZoneInfo.ConvertTime(utcTime, TimeZoneInfo.Utc, this.Profile.PreferredTimeZone); } + return TimeZoneInfo.ConvertTime(utcTime, TimeZoneInfo.Utc, PortalController.Instance.GetCurrentPortalSettings().TimeZone); } /// ----------------------------------------------------------------------------- /// - /// UpdateDisplayName updates the displayname to the format provided + /// UpdateDisplayName updates the displayname to the format provided. /// - /// The format to use + /// The format to use. /// ----------------------------------------------------------------------------- public void UpdateDisplayName(string format) { - //Replace Tokens - format = format.Replace("[USERID]", UserID.ToString(CultureInfo.InvariantCulture)); - format = format.Replace("[FIRSTNAME]", FirstName); - format = format.Replace("[LASTNAME]", LastName); - format = format.Replace("[USERNAME]", Username); - DisplayName = format; - } - - #endregion + // Replace Tokens + format = format.Replace("[USERID]", this.UserID.ToString(CultureInfo.InvariantCulture)); + format = format.Replace("[FIRSTNAME]", this.FirstName); + format = format.Replace("[LASTNAME]", this.LastName); + format = format.Replace("[USERNAME]", this.Username); + this.DisplayName = format; + } } } diff --git a/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs b/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs index ba0cd505821..a7361bf83c0 100644 --- a/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs +++ b/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs @@ -1,36 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Mail; -using static DotNetNuke.Common.Globals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Mail; + + using static DotNetNuke.Common.Globals; + public class UserRegistrationEmailNotifier { - private static UserInfo CurrentUser => UserController.Instance.GetCurrentUserInfo(); - public UserRegistrationEmailNotifier() { } + + private static UserInfo CurrentUser => UserController.Instance.GetCurrentUserInfo(); public static void NotifyAdministrator(UserInfo user) { // avoid self-notification (i.e. on site installation/super user creation) - if (CurrentUser != null && + if (CurrentUser != null && (CurrentUser.UserID == Null.NullInteger || CurrentUser.UserID == user.UserID)) { return; } - //send notification to portal administrator of new user registration - //check the receive notification setting first, but if register type is Private, we will always send the notification email. - //because the user need administrators to do the approve action so that he can continue use the website. + // send notification to portal administrator of new user registration + // check the receive notification setting first, but if register type is Private, we will always send the notification email. + // because the user need administrators to do the approve action so that he can continue use the website. if (PortalSettings.Current.EnableRegisterNotification || PortalSettings.Current.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration) { NotifyUser(user, MessageType.UserRegistrationAdmin); diff --git a/DNN Platform/Library/Entities/Users/UserRoleInfo.cs b/DNN Platform/Library/Entities/Users/UserRoleInfo.cs index 80e78b7b1f8..ac5e27bdc99 100644 --- a/DNN Platform/Library/Entities/Users/UserRoleInfo.cs +++ b/DNN Platform/Library/Entities/Users/UserRoleInfo.cs @@ -1,32 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security.Roles; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security.Roles; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: UserRoleInfo /// ----------------------------------------------------------------------------- /// - /// The UserRoleInfo class provides Business Layer model for a User/Role + /// The UserRoleInfo class provides Business Layer model for a User/Role. /// /// /// /// ----------------------------------------------------------------------------- [Serializable] public class UserRoleInfo : RoleInfo - { - #region Public Properties - + { public int UserRoleID { get; set; } public int UserID { get; set; } @@ -40,30 +37,28 @@ public class UserRoleInfo : RoleInfo public DateTime ExpiryDate { get; set; } public bool IsOwner { get; set; } - - public bool IsTrialUsed { get; set; } - - public bool Subscribed { get; set; } - #endregion + public bool IsTrialUsed { get; set; } + public bool Subscribed { get; set; } + public override void Fill(IDataReader dr) { - //Fill base class properties + // Fill base class properties base.Fill(dr); - //Fill this class properties - UserRoleID = Null.SetNullInteger(dr["UserRoleID"]); - UserID = Null.SetNullInteger(dr["UserID"]); - FullName = Null.SetNullString(dr["DisplayName"]); - Email = Null.SetNullString(dr["Email"]); - EffectiveDate = Null.SetNullDateTime(dr["EffectiveDate"]); - ExpiryDate = Null.SetNullDateTime(dr["ExpiryDate"]); - IsOwner = Null.SetNullBoolean(dr["IsOwner"]); - IsTrialUsed = Null.SetNullBoolean(dr["IsTrialUsed"]); - if (UserRoleID > Null.NullInteger) + // Fill this class properties + this.UserRoleID = Null.SetNullInteger(dr["UserRoleID"]); + this.UserID = Null.SetNullInteger(dr["UserID"]); + this.FullName = Null.SetNullString(dr["DisplayName"]); + this.Email = Null.SetNullString(dr["Email"]); + this.EffectiveDate = Null.SetNullDateTime(dr["EffectiveDate"]); + this.ExpiryDate = Null.SetNullDateTime(dr["ExpiryDate"]); + this.IsOwner = Null.SetNullBoolean(dr["IsOwner"]); + this.IsTrialUsed = Null.SetNullBoolean(dr["IsTrialUsed"]); + if (this.UserRoleID > Null.NullInteger) { - Subscribed = true; + this.Subscribed = true; } } } diff --git a/DNN Platform/Library/Entities/Users/UserVisibilityMode.cs b/DNN Platform/Library/Entities/Users/UserVisibilityMode.cs index d849928730b..cc4775abf54 100644 --- a/DNN Platform/Library/Entities/Users/UserVisibilityMode.cs +++ b/DNN Platform/Library/Entities/Users/UserVisibilityMode.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { public enum UserVisibilityMode @@ -9,6 +9,6 @@ public enum UserVisibilityMode AllUsers = 0, MembersOnly = 1, AdminOnly = 2, - FriendsAndGroups = 3 + FriendsAndGroups = 3, } } diff --git a/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs index 60e8b61856f..1301494117c 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- /// - /// The AnonymousUserInfo class provides an Entity for an anonymous user + /// The AnonymousUserInfo class provides an Entity for an anonymous user. /// /// /// @@ -28,7 +23,7 @@ public class AnonymousUserInfo : BaseUserInfo /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User Id for this online user + /// Gets or sets and sets the User Id for this online user. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -36,11 +31,12 @@ public string UserID { get { - return _UserID; + return this._UserID; } + set { - _UserID = value; + this._UserID = value; } } } diff --git a/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs index e8ba9f312b3..eaedfe55329 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: BaseUserInfo /// ----------------------------------------------------------------------------- /// - /// The BaseUserInfo class provides a base Entity for an online user + /// The BaseUserInfo class provides a base Entity for an online user. /// /// /// @@ -32,7 +27,7 @@ public abstract class BaseUserInfo /// ----------------------------------------------------------------------------- /// - /// Gets and sets the PortalId for this online user + /// Gets or sets and sets the PortalId for this online user. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -40,17 +35,18 @@ public int PortalID { get { - return _PortalID; + return this._PortalID; } + set { - _PortalID = value; + this._PortalID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the TabId for this online user + /// Gets or sets and sets the TabId for this online user. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -58,17 +54,18 @@ public int TabID { get { - return _TabID; + return this._TabID; } + set { - _TabID = value; + this._TabID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the CreationDate for this online user + /// Gets or sets and sets the CreationDate for this online user. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -76,17 +73,18 @@ public DateTime CreationDate { get { - return _CreationDate; + return this._CreationDate; } + set { - _CreationDate = value; + this._CreationDate = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the LastActiveDate for this online user + /// Gets or sets and sets the LastActiveDate for this online user. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -94,11 +92,12 @@ public DateTime LastActiveDate { get { - return _LastActiveDate; + return this._LastActiveDate; } + set { - _LastActiveDate = value; + this._LastActiveDate = value; } } } diff --git a/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs index dd4bd492911..4c2c64bd930 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: OnlineUserInfo /// ----------------------------------------------------------------------------- /// - /// The OnlineUserInfo class provides an Entity for an online user + /// The OnlineUserInfo class provides an Entity for an online user. /// /// /// @@ -29,7 +24,7 @@ public class OnlineUserInfo : BaseUserInfo /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User Id for this online user + /// Gets or sets and sets the User Id for this online user. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -37,11 +32,12 @@ public int UserID { get { - return _UserID; + return this._UserID; } + set { - _UserID = value; + this._UserID = value; } } } diff --git a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs index 488ab523fc6..910ba317b1a 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Scheduling; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users @@ -20,75 +15,76 @@ namespace DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- /// /// The PurgeUsersOnline class provides a Scheduler for purging the Users Online - /// data + /// data. /// /// /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public class PurgeUsersOnline : SchedulerClient - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a PurgeUsesOnline SchedulerClient + /// + /// Initializes a new instance of the class. + /// Constructs a PurgeUsesOnline SchedulerClient. /// /// /// - /// A SchedulerHistiryItem + /// A SchedulerHistiryItem. /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public PurgeUsersOnline(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } /// ----------------------------------------------------------------------------- /// - /// UpdateUsersOnline updates the Users Online information + /// DoWork does th4 Scheduler work. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - private void UpdateUsersOnline() + public override void DoWork() { - var objUserOnlineController = new UserOnlineController(); - - //Is Users Online Enabled? - if ((objUserOnlineController.IsEnabled())) + try { - //Update the Users Online records from Cache - Status = "Updating Users Online"; - objUserOnlineController.UpdateUsersOnline(); - Status = "Update Users Online Successfully"; - ScheduleHistoryItem.Succeeded = true; + // notification that the event is progressing + this.Progressing(); // OPTIONAL + this.UpdateUsersOnline(); + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("UsersOnline purge completed."); + } + catch (Exception exc) // REQUIRED + { + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("UsersOnline purge failed." + exc); + + // notification that we have errored + this.Errored(ref exc); + + // log the exception + Exceptions.LogException(exc); } } /// ----------------------------------------------------------------------------- /// - /// DoWork does th4 Scheduler work + /// UpdateUsersOnline updates the Users Online information. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public override void DoWork() + private void UpdateUsersOnline() { - try - { - //notification that the event is progressing - Progressing(); //OPTIONAL - UpdateUsersOnline(); - ScheduleHistoryItem.Succeeded = true; //REQUIRED - ScheduleHistoryItem.AddLogNote("UsersOnline purge completed."); - } - catch (Exception exc) //REQUIRED - { - ScheduleHistoryItem.Succeeded = false; //REQUIRED - ScheduleHistoryItem.AddLogNote("UsersOnline purge failed." + exc); - - //notification that we have errored - Errored(ref exc); + var objUserOnlineController = new UserOnlineController(); - //log the exception - Exceptions.LogException(exc); + // Is Users Online Enabled? + if (objUserOnlineController.IsEnabled()) + { + // Update the Users Online records from Cache + this.Status = "Updating Users Online"; + objUserOnlineController.UpdateUsersOnline(); + this.Status = "Update Users Online Successfully"; + this.ScheduleHistoryItem.Succeeded = true; } } } diff --git a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs index 6c558a0ec43..c1ea8093a47 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs @@ -1,45 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users { + using System; + using System.Collections; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + + using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: UserOnlineController /// ----------------------------------------------------------------------------- /// - /// The UserOnlineController class provides Business Layer methods for Users Online + /// The UserOnlineController class provides Business Layer methods for Users Online. /// /// /// /// ----------------------------------------------------------------------------- - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public class UserOnlineController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (UserOnlineController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserOnlineController)); private static readonly MembershipProvider memberProvider = MembershipProvider.Instance(); private static readonly object Locker = new object(); private static readonly string CacheKey = "OnlineUserList"; /// ----------------------------------------------------------------------------- /// - /// Clears the cached Users Online Information + /// Clears the cached Users Online Information. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -51,8 +47,9 @@ public void ClearUserList() /// ----------------------------------------------------------------------------- /// - /// Gets the Online time window - /// + /// Gets the Online time window. + /// + /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public int GetOnlineTimeWindow() @@ -62,8 +59,9 @@ public int GetOnlineTimeWindow() /// ----------------------------------------------------------------------------- /// - /// Gets the cached Users Online Information - /// + /// Gets the cached Users Online Information. + /// + /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public Hashtable GetUserList() @@ -81,13 +79,15 @@ public Hashtable GetUserList() } } } + return userList; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the Users Online functionality is enabled - /// + /// Gets whether the Users Online functionality is enabled. + /// + /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public bool IsEnabled() @@ -97,23 +97,25 @@ public bool IsEnabled() /// ----------------------------------------------------------------------------- /// - /// Determines whether a User is online - /// + /// Determines whether a User is online. + /// + /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public bool IsUserOnline(UserInfo user) { bool isOnline = false; - if (IsEnabled()) + if (this.IsEnabled()) { isOnline = memberProvider.IsUserOnline(user); } + return isOnline; } /// ----------------------------------------------------------------------------- /// - /// Sets the cached Users Online Information + /// Sets the cached Users Online Information. /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -124,50 +126,113 @@ public void SetUserList(Hashtable userList) /// ----------------------------------------------------------------------------- /// - /// Tracks an Anonymous User + /// Tracks an online User. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + public void TrackUsers() + { + HttpContext context = HttpContext.Current; + + // Have we already done the work for this request? + if (context.Items["CheckedUsersOnlineCookie"] != null) + { + return; + } + else + { + context.Items["CheckedUsersOnlineCookie"] = "true"; + } + + if (context.Request.IsAuthenticated) + { + this.TrackAuthenticatedUser(context); + } + else if (context.Request.Browser.Cookies) + { + this.TrackAnonymousUser(context); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Update the Users Online information. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + public void UpdateUsersOnline() + { + // Get a Current User List + Hashtable userList = this.GetUserList(); + + // Create a shallow copy of the list to Process + var listToProcess = (Hashtable)userList.Clone(); + + // Clear the list + this.ClearUserList(); + + // Persist the current User List + try + { + memberProvider.UpdateUsersOnline(listToProcess); + } + catch (Exception exc) + { + Logger.Error(exc); + } + + // Remove users that have expired + memberProvider.DeleteUsersOnline(this.GetOnlineTimeWindow()); + } + + /// ----------------------------------------------------------------------------- + /// + /// Tracks an Anonymous User. /// - /// An HttpContext Object + /// An HttpContext Object. /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] private void TrackAnonymousUser(HttpContext context) { string cookieName = "DotNetNukeAnonymous"; - var portalSettings = (PortalSettings) context.Items["PortalSettings"]; + var portalSettings = (PortalSettings)context.Items["PortalSettings"]; if (portalSettings == null) { return; } + AnonymousUserInfo user; - Hashtable userList = GetUserList(); + Hashtable userList = this.GetUserList(); string userID; - //Check if the Tracking cookie exists + // Check if the Tracking cookie exists HttpCookie cookie = context.Request.Cookies[cookieName]; - //Track Anonymous User - if ((cookie == null)) - { - //Create a temporary userId + + // Track Anonymous User + if (cookie == null) + { + // Create a temporary userId userID = Guid.NewGuid().ToString(); - //Create a new cookie + // Create a new cookie cookie = new HttpCookie(cookieName, userID) { Expires = DateTime.Now.AddMinutes(20), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; context.Response.Cookies.Add(cookie); - //Create a user + // Create a user user = new AnonymousUserInfo { UserID = userID, PortalID = portalSettings.PortalId, TabID = portalSettings.ActiveTab.TabID, CreationDate = DateTime.Now, - LastActiveDate = DateTime.Now + LastActiveDate = DateTime.Now, }; - //Add the user + // Add the user if (!userList.Contains(userID)) { userList[userID] = user; @@ -175,36 +240,36 @@ private void TrackAnonymousUser(HttpContext context) } else { - if ((cookie.Value == null)) + if (cookie.Value == null) { - //Expire the cookie, there is something wrong with it + // Expire the cookie, there is something wrong with it context.Response.Cookies[cookieName].Expires = new DateTime(1999, 10, 12); - //No need to do anything else + // No need to do anything else return; } - - //Get userID out of cookie + + // Get userID out of cookie userID = cookie.Value; - //Find the cookie in the user list - if ((userList[userID] == null)) + // Find the cookie in the user list + if (userList[userID] == null) { userList[userID] = new AnonymousUserInfo(); - ((AnonymousUserInfo) userList[userID]).CreationDate = DateTime.Now; + ((AnonymousUserInfo)userList[userID]).CreationDate = DateTime.Now; } - - user = (AnonymousUserInfo) userList[userID]; + + user = (AnonymousUserInfo)userList[userID]; user.UserID = userID; user.PortalID = portalSettings.PortalId; user.TabID = portalSettings.ActiveTab.TabID; user.LastActiveDate = DateTime.Now; - //Reset the expiration on the cookie + // Reset the expiration on the cookie cookie = new HttpCookie(cookieName, userID) { Expires = DateTime.Now.AddMinutes(20), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; context.Response.Cookies.Add(cookie); } @@ -212,101 +277,43 @@ private void TrackAnonymousUser(HttpContext context) /// ----------------------------------------------------------------------------- /// - /// Tracks an Authenticated User + /// Tracks an Authenticated User. /// - /// An HttpContext Object + /// An HttpContext Object. /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] private void TrackAuthenticatedUser(HttpContext context) { - //Retrieve Portal Settings - var portalSettings = (PortalSettings) context.Items["PortalSettings"]; + // Retrieve Portal Settings + var portalSettings = (PortalSettings)context.Items["PortalSettings"]; if (portalSettings == null) { return; } - //Get the logged in User ID + + // Get the logged in User ID UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - //Get user list - Hashtable userList = GetUserList(); + // Get user list + Hashtable userList = this.GetUserList(); var user = new OnlineUserInfo(); if (objUserInfo.UserID > 0) { user.UserID = objUserInfo.UserID; } + user.PortalID = portalSettings.PortalId; user.TabID = portalSettings.ActiveTab.TabID; user.LastActiveDate = DateTime.Now; - if ((userList[objUserInfo.UserID.ToString()] == null)) + if (userList[objUserInfo.UserID.ToString()] == null) { user.CreationDate = user.LastActiveDate; } + userList[objUserInfo.UserID.ToString()] = user; - SetUserList(userList); - } - - /// ----------------------------------------------------------------------------- - /// - /// Tracks an online User - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public void TrackUsers() - { - HttpContext context = HttpContext.Current; - - //Have we already done the work for this request? - if (context.Items["CheckedUsersOnlineCookie"] != null) - { - return; - } - else - { - context.Items["CheckedUsersOnlineCookie"] = "true"; - } - if ((context.Request.IsAuthenticated)) - { - TrackAuthenticatedUser(context); - } - else if ((context.Request.Browser.Cookies)) - { - TrackAnonymousUser(context); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Update the Users Online information - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public void UpdateUsersOnline() - { - //Get a Current User List - Hashtable userList = GetUserList(); - - //Create a shallow copy of the list to Process - var listToProcess = (Hashtable) userList.Clone(); - - //Clear the list - ClearUserList(); - - //Persist the current User List - try - { - memberProvider.UpdateUsersOnline(listToProcess); - } - catch (Exception exc) - { - Logger.Error(exc); - - } - - //Remove users that have expired - memberProvider.DeleteUsersOnline(GetOnlineTimeWindow()); + this.SetUserList(userList); } } } diff --git a/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs index 44ec0a3bb38..d7b1b026ac0 100644 --- a/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + [DefaultProperty("Text")] [ToolboxData("<{0}:ContextMenuItemExtensionControl runat=server>")] public class ContextMenuItemExtensionControl : DefaultExtensionControl { - private string content = ""; + private string content = string.Empty; protected override void OnInit(EventArgs e) { @@ -27,7 +28,7 @@ protected override void OnInit(EventArgs e) StringBuilder str = new StringBuilder(); - foreach (var extension in extensionPointManager.GetContextMenuItemExtensionPoints(Module, Group)) + foreach (var extension in extensionPointManager.GetContextMenuItemExtensionPoints(this.Module, this.Group)) { var icon = extension.Icon; if (icon.StartsWith("~/")) @@ -38,17 +39,17 @@ protected override void OnInit(EventArgs e) str.Append(@"
  • - "+extension.Text+@" + " + extension.Text + @"
  • "); } - content = str.ToString(); + this.content = str.ToString(); } protected override void RenderContents(HtmlTextWriter output) { - output.Write(content); + output.Write(this.content); } } } diff --git a/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs index 2a171a78a3f..9931292bae0 100644 --- a/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.UI.Modules; + [DefaultProperty("Text")] [ToolboxData("<{0}:DefaultExtensionControl runat=server>")] public class DefaultExtensionControl : WebControl @@ -19,12 +20,13 @@ public string Module { get { - var s = (string)ViewState["Module"]; + var s = (string)this.ViewState["Module"]; return s ?? string.Empty; } + set { - ViewState["Module"] = value; + this.ViewState["Module"] = value; } } @@ -34,12 +36,13 @@ public string Group { get { - var s = (string)ViewState["Group"]; + var s = (string)this.ViewState["Group"]; return s ?? string.Empty; } + set { - ViewState["Group"] = value; + this.ViewState["Group"] = value; } } @@ -49,12 +52,13 @@ public string Name { get { - var s = (string)ViewState["Name"]; + var s = (string)this.ViewState["Name"]; return s ?? string.Empty; } + set { - ViewState["Name"] = value; + this.ViewState["Name"] = value; } } diff --git a/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs index a24e4fe7e42..1bd6556f22a 100644 --- a/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs @@ -1,57 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.IO; -using System.Web.UI; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.ComponentModel; + using System.IO; + using System.Web.UI; + using System.Web.UI.WebControls; + [DefaultProperty("Text")] [ToolboxData("<{0}:EditPagePanelExtensionControl runat=server>")] public class EditPagePanelExtensionControl : DefaultExtensionControl { - private void LoadControl(IEditPagePanelExtensionPoint extension) - { - var editPanel = new PanelEditPagePanelExtensionControl { PanelId = extension.EditPagePanelId, Text = extension.Text, CssClass = extension.CssClass }; - var control = Page.LoadControl(extension.UserControlSrc); - control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); - editPanel.Controls.Add(control); - Controls.Add(editPanel); - - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - var extensionPointManager = new ExtensionPointManager(); - - if (!String.IsNullOrEmpty(Name)) - { - var extension = extensionPointManager.GetEditPagePanelExtensionPointFirstByPriority(Module, Name); - if (extension != null) - { - LoadControl(extension); - } - } - else - { - foreach (var extension in extensionPointManager.GetEditPagePanelExtensionPoints(Module, Group)) - { - if (extension != null) - { - LoadControl(extension); - } - } - } - } - public void BindAction(int portalId, int tabId, int moduleId) { - foreach (var control in Controls) + foreach (var control in this.Controls) { var panelcontrol = control as PanelEditPagePanelExtensionControl; if (panelcontrol != null) @@ -70,7 +35,7 @@ public void BindAction(int portalId, int tabId, int moduleId) public void SaveAction(int portalId, int tabId, int moduleId) { - foreach (var control in Controls) + foreach (var control in this.Controls) { var panelcontrol = control as PanelEditPagePanelExtensionControl; if (panelcontrol != null) @@ -86,10 +51,44 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + var extensionPointManager = new ExtensionPointManager(); + + if (!string.IsNullOrEmpty(this.Name)) + { + var extension = extensionPointManager.GetEditPagePanelExtensionPointFirstByPriority(this.Module, this.Name); + if (extension != null) + { + this.LoadControl(extension); + } + } + else + { + foreach (var extension in extensionPointManager.GetEditPagePanelExtensionPoints(this.Module, this.Group)) + { + if (extension != null) + { + this.LoadControl(extension); + } + } + } + } + + private void LoadControl(IEditPagePanelExtensionPoint extension) + { + var editPanel = new PanelEditPagePanelExtensionControl { PanelId = extension.EditPagePanelId, Text = extension.Text, CssClass = extension.CssClass }; + var control = this.Page.LoadControl(extension.UserControlSrc); + control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); + editPanel.Controls.Add(control); + this.Controls.Add(editPanel); + } public void CancelAction(int portalId, int tabId, int moduleId) { - foreach (var control in Controls) + foreach (var control in this.Controls) { var panelcontrol = control as PanelEditPagePanelExtensionControl; if (panelcontrol != null) @@ -110,14 +109,14 @@ public void CancelAction(int portalId, int tabId, int moduleId) public class PanelEditPagePanelExtensionControl : WebControl { public string PanelId { get; set; } + public string Text { get; set; } protected override void RenderContents(HtmlTextWriter op) { - - op.Write(@"
    -

    -"+Text+@" + op.Write(@"
    +

    +" + this.Text + @"

    "); base.RenderContents(op); diff --git a/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs index e58a4aebce1..4bfb7c3ab98 100644 --- a/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.IO; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.ComponentModel; + using System.IO; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + [DefaultProperty("Module")] [ToolboxData("<{0}:EditPageTabExtensionControl runat=server>")] public class EditPageTabExtensionControl : DefaultExtensionControl @@ -21,12 +21,13 @@ public string TabControlId { get { - var s = (String)ViewState["TabControlId"]; - return (s ?? String.Empty); + var s = (string)this.ViewState["TabControlId"]; + return s ?? string.Empty; } + set { - ViewState["TabControlId"] = value; + this.ViewState["TabControlId"] = value; } } @@ -36,45 +37,19 @@ public string PanelControlId { get { - var s = (String)ViewState["PanelControlId"]; - return (s ?? String.Empty); + var s = (string)this.ViewState["PanelControlId"]; + return s ?? string.Empty; } + set { - ViewState["PanelControlId"] = value; - } - } - - protected override void OnInit(EventArgs e) - { - var extensionPointManager = new ExtensionPointManager(); - - var tabs = (HtmlGenericControl)Parent.FindControl(TabControlId); - var panel = Parent.FindControl(PanelControlId); - - foreach (var extension in extensionPointManager.GetEditPageTabExtensionPoints(Module, Group)) - { - if (extension.Visible) - { - var liElement = new HtmlGenericControl("li") - { - InnerHtml = "" + extension.Text + "", - }; - liElement.Attributes.Add("class", extension.CssClass); - tabs.Controls.Add(liElement); - - var container = new PanelTabExtensionControl { PanelId = extension.EditPageTabId }; - var control = Page.LoadControl(extension.UserControlSrc); - control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); - container.Controls.Add(control); - panel.Controls.Add(container); - } + this.ViewState["PanelControlId"] = value; } } public void BindAction(int portalId, int tabId, int moduleId) { - var panel = Parent.FindControl(PanelControlId); + var panel = this.Parent.FindControl(this.PanelControlId); foreach (var control in panel.Controls) { @@ -95,7 +70,7 @@ public void BindAction(int portalId, int tabId, int moduleId) public void SaveAction(int portalId, int tabId, int moduleId) { - var panel = Parent.FindControl(PanelControlId); + var panel = this.Parent.FindControl(this.PanelControlId); foreach (var control in panel.Controls) { @@ -114,9 +89,36 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } + protected override void OnInit(EventArgs e) + { + var extensionPointManager = new ExtensionPointManager(); + + var tabs = (HtmlGenericControl)this.Parent.FindControl(this.TabControlId); + var panel = this.Parent.FindControl(this.PanelControlId); + + foreach (var extension in extensionPointManager.GetEditPageTabExtensionPoints(this.Module, this.Group)) + { + if (extension.Visible) + { + var liElement = new HtmlGenericControl("li") + { + InnerHtml = "" + extension.Text + "", + }; + liElement.Attributes.Add("class", extension.CssClass); + tabs.Controls.Add(liElement); + + var container = new PanelTabExtensionControl { PanelId = extension.EditPageTabId }; + var control = this.Page.LoadControl(extension.UserControlSrc); + control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); + container.Controls.Add(control); + panel.Controls.Add(container); + } + } + } + public void CancelAction(int portalId, int tabId, int moduleId) { - var panel = Parent.FindControl(PanelControlId); + var panel = this.Parent.FindControl(this.PanelControlId); foreach (var control in panel.Controls) { @@ -134,7 +136,6 @@ public void CancelAction(int portalId, int tabId, int moduleId) } } } - } public class PanelTabExtensionControl : WebControl @@ -143,19 +144,19 @@ public class PanelTabExtensionControl : WebControl public override void RenderBeginTag(HtmlTextWriter writer) { - writer.Write(""); + writer.Write(string.Empty); } public override void RenderEndTag(HtmlTextWriter writer) { - writer.Write(""); - } + writer.Write(string.Empty); + } protected override void RenderContents(HtmlTextWriter op) { - op.Write("
    "); + op.Write("
    "); base.RenderContents(op); op.Write("
    "); - } + } } } diff --git a/DNN Platform/Library/ExtensionPoints/ExportClientScriptAttribute.cs b/DNN Platform/Library/ExtensionPoints/ExportClientScriptAttribute.cs index c6e91115357..7c548e4fd24 100644 --- a/DNN Platform/Library/ExtensionPoints/ExportClientScriptAttribute.cs +++ b/DNN Platform/Library/ExtensionPoints/ExportClientScriptAttribute.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { using System.ComponentModel.Composition; @@ -11,7 +11,7 @@ public class ExportClientScriptAttribute : ExportAttribute { public ExportClientScriptAttribute() : base(typeof(IScriptItemExtensionPoint)) - { + { } } } diff --git a/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs b/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs index c9708a0cba7..193e0b8c1f3 100644 --- a/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs +++ b/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs @@ -1,23 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.ComponentModel.Composition.Hosting; -using System.IO; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.ExtensionPoints.Filters; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.Collections.Generic; + using System.ComponentModel.Composition; + using System.ComponentModel.Composition.Hosting; + using System.IO; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.ExtensionPoints.Filters; + public class ExtensionPointManager { private static readonly object SyncRoot = new object(); + private static readonly CompositionContainer MefCompositionContainer = InitializeMefCompositionContainer(); + #pragma warning disable 649 [ImportMany] @@ -25,7 +27,7 @@ public class ExtensionPointManager [ImportMany] private IEnumerable> _editPageTabExtensionPoint; - + [ImportMany] private IEnumerable> _toolbarButtonExtensionPoints; @@ -47,18 +49,8 @@ public class ExtensionPointManager #pragma warning restore 649 public ExtensionPointManager() - { - ComposeParts(this); - } - - private static readonly CompositionContainer MefCompositionContainer = InitializeMefCompositionContainer(); - - private static CompositionContainer InitializeMefCompositionContainer() { - var catalog = new AggregateCatalog(); - var path = Path.Combine(Globals.ApplicationMapPath, "bin"); - catalog.Catalogs.Add(new SafeDirectoryCatalog(path)); - return new CompositionContainer(catalog, true); + ComposeParts(this); } public static void ComposeParts(params object[] attributeParts) @@ -71,12 +63,20 @@ public static void ComposeParts(params object[] attributeParts) public IEnumerable GetEditPageTabExtensionPoints(string module) { - return GetEditPageTabExtensionPoints(module, null); + return this.GetEditPageTabExtensionPoints(module, null); + } + + private static CompositionContainer InitializeMefCompositionContainer() + { + var catalog = new AggregateCatalog(); + var path = Path.Combine(Globals.ApplicationMapPath, "bin"); + catalog.Catalogs.Add(new SafeDirectoryCatalog(path)); + return new CompositionContainer(catalog, true); } public IEnumerable GetEditPageTabExtensionPoints(string module, string group) { - return from e in _editPageTabExtensionPoint + return from e in this._editPageTabExtensionPoint where e.Metadata.Module == module && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) orderby e.Value.Order @@ -85,53 +85,52 @@ orderby e.Value.Order public IEnumerable GetToolBarButtonExtensionPoints(string module) { - return GetToolBarButtonExtensionPoints(module, null); + return this.GetToolBarButtonExtensionPoints(module, null); } public IEnumerable GetToolBarButtonExtensionPoints(string module, string group) { - return GetToolBarButtonExtensionPoints(module, group, new NoFilter()); + return this.GetToolBarButtonExtensionPoints(module, group, new NoFilter()); } public IEnumerable GetToolBarButtonExtensionPoints(string module, string group, IExtensionPointFilter filter) - { - return from e in _toolbarButtonExtensionPoints - where FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) + { + return from e in this._toolbarButtonExtensionPoints + where this.FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) orderby e.Value.Order - select e.Value; + select e.Value; } public IToolBarButtonExtensionPoint GetToolBarButtonExtensionPointFirstByPriority(string module, string name) { - return (from e in _toolbarButtonExtensionPoints + return (from e in this._toolbarButtonExtensionPoints where e.Metadata.Module == module && e.Metadata.Name == name orderby e.Metadata.Priority - select e.Value).FirstOrDefault(); + select e.Value).FirstOrDefault(); } - - + public IEnumerable GetScriptItemExtensionPoints(string module) { - return GetScriptItemExtensionPoints(module, null); + return this.GetScriptItemExtensionPoints(module, null); } public IEnumerable GetScriptItemExtensionPoints(string module, string group) { - return from e in _scripts - where e.Metadata.Module == module - && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) - orderby e.Value.Order - select e.Value; + return from e in this._scripts + where e.Metadata.Module == module + && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) + orderby e.Value.Order + select e.Value; } public IEnumerable GetEditPagePanelExtensionPoints(string module) { - return GetEditPagePanelExtensionPoints(module, null); + return this.GetEditPagePanelExtensionPoints(module, null); } public IEnumerable GetEditPagePanelExtensionPoints(string module, string group) { - return from e in _editPagePanelExtensionPoints + return from e in this._editPagePanelExtensionPoints where e.Metadata.Module == module && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) orderby e.Value.Order @@ -140,74 +139,74 @@ orderby e.Value.Order public IEditPagePanelExtensionPoint GetEditPagePanelExtensionPointFirstByPriority(string module, string name) { - return (from e in _editPagePanelExtensionPoints + return (from e in this._editPagePanelExtensionPoints where e.Metadata.Module == module && e.Metadata.Name == name orderby e.Metadata.Priority - select e.Value).FirstOrDefault(); + select e.Value).FirstOrDefault(); } public IEnumerable GetContextMenuItemExtensionPoints(string module) { - return GetContextMenuItemExtensionPoints(module, null); + return this.GetContextMenuItemExtensionPoints(module, null); } public IEnumerable GetContextMenuItemExtensionPoints(string module, string group) - { - return from e in _ctxMenuItemExtensionPoints + { + return from e in this._ctxMenuItemExtensionPoints where e.Metadata.Module == module && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) - orderby e.Value.Order + orderby e.Value.Order select e.Value; } public IUserControlExtensionPoint GetUserControlExtensionPointFirstByPriority(string module, string name) { - return (from e in _userControlExtensionPoints + return (from e in this._userControlExtensionPoints where e.Metadata.Module == module && e.Metadata.Name == name orderby e.Metadata.Priority - select e.Value).FirstOrDefault(); + select e.Value).FirstOrDefault(); } public IEnumerable GetUserControlExtensionPoints(string module, string group) { - return from e in _userControlExtensionPoints - where e.Metadata.Module == module && e.Metadata.Group == @group - orderby e.Value.Order - select e.Value; + return from e in this._userControlExtensionPoints + where e.Metadata.Module == module && e.Metadata.Group == @group + orderby e.Value.Order + select e.Value; } public IEnumerable GetMenuItemExtensionPoints(string module) { - return GetMenuItemExtensionPoints(module, null); + return this.GetMenuItemExtensionPoints(module, null); } public IEnumerable GetMenuItemExtensionPoints(string module, string group) { - return GetMenuItemExtensionPoints(module, group, new NoFilter()); + return this.GetMenuItemExtensionPoints(module, group, new NoFilter()); } public IEnumerable GetMenuItemExtensionPoints(string module, string group, IExtensionPointFilter filter) { - return from e in _menuItems - where FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) - orderby e.Value.Order + return from e in this._menuItems + where this.FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) + orderby e.Value.Order select e.Value; } - + public IEnumerable GetGridColumnExtensionPoints(string module) { - return GetGridColumnExtensionPoints(module, null); + return this.GetGridColumnExtensionPoints(module, null); } public IEnumerable GetGridColumnExtensionPoints(string module, string group) { - return GetGridColumnExtensionPoints(module, group, new NoFilter()); + return this.GetGridColumnExtensionPoints(module, group, new NoFilter()); } public IEnumerable GetGridColumnExtensionPoints(string module, string group, IExtensionPointFilter filter) { - return from e in _gridColumns - where FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) + return from e in this._gridColumns + where this.FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) orderby e.Value.Order select e.Value; } diff --git a/DNN Platform/Library/ExtensionPoints/Filters/CompositeFilter.cs b/DNN Platform/Library/ExtensionPoints/Filters/CompositeFilter.cs index 9ef5184c71d..ad85ca2f3f7 100644 --- a/DNN Platform/Library/ExtensionPoints/Filters/CompositeFilter.cs +++ b/DNN Platform/Library/ExtensionPoints/Filters/CompositeFilter.cs @@ -1,30 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints.Filters { + using System.Collections.Generic; + using System.Linq; + public class CompositeFilter : IExtensionPointFilter { private readonly IList filters; public CompositeFilter() { - filters = new List(); + this.filters = new List(); } public CompositeFilter And(IExtensionPointFilter filter) { - filters.Add(filter); + this.filters.Add(filter); return this; } public bool Condition(IExtensionPointData m) { - return filters.All(f => f.Condition(m)); + return this.filters.All(f => f.Condition(m)); } } } diff --git a/DNN Platform/Library/ExtensionPoints/Filters/FilterByHostMenu.cs b/DNN Platform/Library/ExtensionPoints/Filters/FilterByHostMenu.cs index 2a2d63e037b..d849350cd97 100644 --- a/DNN Platform/Library/ExtensionPoints/Filters/FilterByHostMenu.cs +++ b/DNN Platform/Library/ExtensionPoints/Filters/FilterByHostMenu.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints.Filters { public class FilterByHostMenu : IExtensionPointFilter @@ -15,7 +15,7 @@ public FilterByHostMenu(bool isHostMenu) public bool Condition(IExtensionPointData m) { - return !isHostMenu || !m.DisableOnHost; + return !this.isHostMenu || !m.DisableOnHost; } } } diff --git a/DNN Platform/Library/ExtensionPoints/Filters/FilterByUnauthenticated.cs b/DNN Platform/Library/ExtensionPoints/Filters/FilterByUnauthenticated.cs index fbcf1bdf01c..4b2ac50b57c 100644 --- a/DNN Platform/Library/ExtensionPoints/Filters/FilterByUnauthenticated.cs +++ b/DNN Platform/Library/ExtensionPoints/Filters/FilterByUnauthenticated.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints.Filters { public class FilterByUnauthenticated : IExtensionPointFilter @@ -15,7 +15,7 @@ public FilterByUnauthenticated(bool isAuthenticated) public bool Condition(IExtensionPointData m) { - return isAuthenticated || !m.DisableUnauthenticated; + return this.isAuthenticated || !m.DisableUnauthenticated; } } } diff --git a/DNN Platform/Library/ExtensionPoints/Filters/IExtensionPointFilter.cs b/DNN Platform/Library/ExtensionPoints/Filters/IExtensionPointFilter.cs index 5a63314e47b..8395fe8bb55 100644 --- a/DNN Platform/Library/ExtensionPoints/Filters/IExtensionPointFilter.cs +++ b/DNN Platform/Library/ExtensionPoints/Filters/IExtensionPointFilter.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints.Filters { public interface IExtensionPointFilter diff --git a/DNN Platform/Library/ExtensionPoints/Filters/NoFilter.cs b/DNN Platform/Library/ExtensionPoints/Filters/NoFilter.cs index 3e03b1c1712..db200778b7c 100644 --- a/DNN Platform/Library/ExtensionPoints/Filters/NoFilter.cs +++ b/DNN Platform/Library/ExtensionPoints/Filters/NoFilter.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints.Filters { public class NoFilter : IExtensionPointFilter - { + { public bool Condition(IExtensionPointData m) { return true; diff --git a/DNN Platform/Library/ExtensionPoints/IContextMenuItemExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IContextMenuItemExtensionPoint.cs index 6f93f08f82c..1bd5bb69f4f 100644 --- a/DNN Platform/Library/ExtensionPoints/IContextMenuItemExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IContextMenuItemExtensionPoint.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { public interface IContextMenuItemExtensionPoint : IExtensionPoint diff --git a/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs b/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs index 496c771388e..0ac606cc198 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + public interface IEditPagePanelControlActions { void SaveAction(int portalId, int tabId, int moduleId); + void CancelAction(int portalId, int tabId, int moduleId); + void BindAction(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs index 3aec699cf3a..43ea69cb891 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { - public interface IEditPagePanelExtensionPoint: IUserControlExtensionPoint + using System; + + public interface IEditPagePanelExtensionPoint : IUserControlExtensionPoint { string EditPagePanelId { get; } - string CssClass { get; } + + string CssClass { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs b/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs index e1b08475c79..5f2fa941816 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + public interface IEditPageTabControlActions { void SaveAction(int portalId, int tabId, int moduleId); + void CancelAction(int portalId, int tabId, int moduleId); + void BindAction(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs index f195eb8451c..47b2c4bfc31 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + public interface IEditPageTabExtensionPoint : IUserControlExtensionPoint { string EditPageTabId { get; } + string CssClass { get; } + string Permission { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IExtensionControlRenderer.cs b/DNN Platform/Library/ExtensionPoints/IExtensionControlRenderer.cs index 5278c8e8b6f..706da1fc6b5 100644 --- a/DNN Platform/Library/ExtensionPoints/IExtensionControlRenderer.cs +++ b/DNN Platform/Library/ExtensionPoints/IExtensionControlRenderer.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + public interface IExtensionControlRenderer { string GetOutput(IExtensionPoint extension); diff --git a/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs index 6ee26f3299b..d0837a4c4e1 100644 --- a/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs @@ -1,13 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { public interface IExtensionPoint { string Text { get; } + string Icon { get; } + int Order { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs b/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs index b098c76117b..6344f65b72f 100644 --- a/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs +++ b/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System.ComponentModel; + public interface IExtensionPointData { string Module { get; } diff --git a/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs index aedb25413b7..49800255b8d 100644 --- a/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs @@ -1,20 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System.Web.UI.WebControls; + public interface IGridColumnExtensionPoint : IExtensionPoint { int ColumnAt { get; } + string UniqueName { get; } + string DataField { get; } + string HeaderText { get; } + Unit HeaderStyleWidth { get; } + bool ReadOnly { get; } + bool Reorderable { get; } + string SortExpression { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IMenuButtonItemExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IMenuButtonItemExtensionPoint.cs index 916a62b8a1e..6e986ee6bf8 100644 --- a/DNN Platform/Library/ExtensionPoints/IMenuButtonItemExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IMenuButtonItemExtensionPoint.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + public interface IMenuButtonItemExtensionPoint : IExtensionPoint { string ItemId { get; } diff --git a/DNN Platform/Library/ExtensionPoints/IMenuItemExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IMenuItemExtensionPoint.cs index 24445043243..754d47339e1 100644 --- a/DNN Platform/Library/ExtensionPoints/IMenuItemExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IMenuItemExtensionPoint.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { public interface IMenuItemExtensionPoint : IExtensionPoint diff --git a/DNN Platform/Library/ExtensionPoints/IScriptItemExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IScriptItemExtensionPoint.cs index 00ffd1b90b1..41d11b5b543 100644 --- a/DNN Platform/Library/ExtensionPoints/IScriptItemExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IScriptItemExtensionPoint.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { public interface IScriptItemExtensionPoint : IExtensionPoint diff --git a/DNN Platform/Library/ExtensionPoints/IToolBarButtonExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IToolBarButtonExtensionPoint.cs index 5a1fb4ddddb..9ddc6b41d48 100644 --- a/DNN Platform/Library/ExtensionPoints/IToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IToolBarButtonExtensionPoint.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using DotNetNuke.UI.Modules; + public interface IToolBarButtonExtensionPoint : IExtensionPoint { string ButtonId { get; } diff --git a/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs index 2cab2ce0e0c..0213babfab9 100644 --- a/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { - public interface IToolBarMenuButtonExtensionPoint: IToolBarButtonExtensionPoint + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + public interface IToolBarMenuButtonExtensionPoint : IToolBarButtonExtensionPoint { List Items { get; } + string MenuCssClass { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs b/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs index 5ee567c5628..2ce4e1862c5 100644 --- a/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs +++ b/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + public interface IUserControlActions { void SaveAction(int portalId, int tabId, int moduleId); + void CancelAction(int portalId, int tabId, int moduleId); + void BindAction(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs index a2775a67568..f98f9fdbc40 100644 --- a/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + public interface IUserControlExtensionPoint : IExtensionPoint { string UserControlSrc { get; } + bool Visible { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs b/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs index 4fd026f747e..7d4e6e575e3 100644 --- a/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs +++ b/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition.Hosting; -using System.ComponentModel.Composition.Primitives; -using System.IO; -using System.Linq; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.ComponentModel.Composition.Hosting; + using System.ComponentModel.Composition.Primitives; + using System.IO; + using System.Linq; + using System.Reflection; + public class SafeDirectoryCatalog : ComposablePartCatalog { private readonly AggregateCatalog _catalog; @@ -19,17 +19,20 @@ public SafeDirectoryCatalog(string directory) { var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories); - _catalog = new AggregateCatalog(); + this._catalog = new AggregateCatalog(); foreach (var file in files) { try { - var asmCat = new AssemblyCatalog(file); + var asmCat = new AssemblyCatalog(file); - //Force MEF to load the plugin and figure out if there are any exports - // good assemblies will not throw the RTLE exception and can be added to the catalog - if (asmCat.Parts.ToList().Count > 0) _catalog.Catalogs.Add(asmCat); + // Force MEF to load the plugin and figure out if there are any exports + // good assemblies will not throw the RTLE exception and can be added to the catalog + if (asmCat.Parts.ToList().Count > 0) + { + this._catalog.Catalogs.Add(asmCat); + } } catch (ReflectionTypeLoadException) { @@ -37,9 +40,8 @@ public SafeDirectoryCatalog(string directory) catch (BadImageFormatException) { } - catch (FileLoadException) //ignore when the assembly load failed. + catch (FileLoadException) // ignore when the assembly load failed. { - } } } @@ -48,7 +50,7 @@ public override IQueryable Parts { get { - return _catalog.Parts; + return this._catalog.Parts; } } } diff --git a/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs index 11acafceab7..b51b70e1bae 100644 --- a/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel; -using System.Text; -using System.Web; -using System.Web.UI; - -using DotNetNuke.ExtensionPoints.Filters; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System.ComponentModel; + using System.Text; + using System.Web; + using System.Web.UI; + + using DotNetNuke.ExtensionPoints.Filters; + [DefaultProperty("Text")] [ToolboxData("<{0}:ToolBarButtonExtensionControl runat=server>")] public class ToolBarButtonExtensionControl : DefaultExtensionControl @@ -31,27 +31,27 @@ protected override void RenderContents(HtmlTextWriter output) .And(new FilterByHostMenu(this.IsHost)) .And(new FilterByUnauthenticated(HttpContext.Current.Request.IsAuthenticated)); - foreach (var extension in extensionPointManager.GetToolBarButtonExtensionPoints(Module, Group, filter)) + foreach (var extension in extensionPointManager.GetToolBarButtonExtensionPoints(this.Module, this.Group, filter)) { if (extension is IToolBarMenuButtonExtensionPoint) { - btnRenderer = new ToolBarMenuButtonRenderer(); - str.AppendFormat(btnRenderer.GetOutput(extension)); + this.btnRenderer = new ToolBarMenuButtonRenderer(); + str.AppendFormat(this.btnRenderer.GetOutput(extension)); } else { - extension.ModuleContext = ModuleContext; - btnRenderer = new ToolBarButtonRenderer(); - str.AppendFormat(btnRenderer.GetOutput(extension)); + extension.ModuleContext = this.ModuleContext; + this.btnRenderer = new ToolBarButtonRenderer(); + str.AppendFormat(this.btnRenderer.GetOutput(extension)); } } - + output.Write(str.ToString()); } protected override void Render(HtmlTextWriter writer) { - RenderContents(writer); + this.RenderContents(writer); } } } diff --git a/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs b/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs index 3afc019494c..ad6c73247e1 100644 --- a/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs +++ b/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.Text; + + using DotNetNuke.Common; + public class ToolBarButtonRenderer : IExtensionControlRenderer { public string GetOutput(IExtensionPoint extensionPoint) @@ -37,8 +38,8 @@ public string GetOutput(IExtensionPoint extensionPoint) str.AppendFormat( "{3}", extension.ButtonId, - !extension.ShowText ? "text-indent: -10000000px;" : "", - extension.ShowIcon ? icon : "", + !extension.ShowText ? "text-indent: -10000000px;" : string.Empty, + extension.ShowIcon ? icon : string.Empty, extension.Text); str.AppendLine(""); diff --git a/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs b/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs index 41a7da674cd..eee8a512a06 100644 --- a/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs +++ b/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text; -using System.Web; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.Text; + using System.Web; + + using DotNetNuke.Common; + public class ToolBarMenuButtonRenderer : IExtensionControlRenderer { public string GetOutput(IExtensionPoint extensionPoint) @@ -22,6 +23,7 @@ public string GetOutput(IExtensionPoint extensionPoint) cssClass += " disabled"; action = "void(0);"; } + var icon = extension.Icon; if (icon.StartsWith("~/")) { @@ -36,8 +38,8 @@ public string GetOutput(IExtensionPoint extensionPoint) str.AppendFormat( "{3}", extension.ButtonId, - !extension.ShowText ? "text-indent: -10000000px;" : "", - extension.ShowIcon ? icon : "", + !extension.ShowText ? "text-indent: -10000000px;" : string.Empty, + extension.ShowIcon ? icon : string.Empty, extension.Text); str.AppendLine(""); str.AppendFormat("
    ", extension.MenuCssClass); @@ -45,13 +47,13 @@ public string GetOutput(IExtensionPoint extensionPoint) str.AppendLine("
      "); foreach (var item in extension.Items) { - str.AppendLine(GetItemOutput(item)); - } + str.AppendLine(this.GetItemOutput(item)); + } str.AppendLine("
    "); str.AppendLine("
    "); str.AppendLine("
    "); - + return str.ToString(); } @@ -61,7 +63,7 @@ private string GetItemOutput(IMenuButtonItemExtensionPoint item) { return string.Format("
  • {4}
  • ", item.CssClass, item.ItemId, item.Action, item.Attributes, item.Text); } - + return string.Format("
  • {6}
  • ", item.Type, item.ItemId, item.ItemId, item.Text, item.Attributes, item.Action, item.Text); } } diff --git a/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs index e4ae27858d9..9a0606a89e7 100644 --- a/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs @@ -1,47 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.IO; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.ExtensionPoints { + using System; + using System.ComponentModel; + using System.IO; + using System.Web.UI; + [DefaultProperty("Text")] [ToolboxData("<{0}:UserControlExtensionControl runat=server>")] public class UserControlExtensionControl : DefaultExtensionControl { - private void LoadControl(IUserControlExtensionPoint extension) - { - var control = Page.LoadControl(extension.UserControlSrc); - control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); - Controls.Add(control); - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - var extensionPointManager = new ExtensionPointManager(); - - if (!String.IsNullOrEmpty(Name)) - { - var extension = extensionPointManager.GetUserControlExtensionPointFirstByPriority(Module, Name); - LoadControl(extension); - } - else - { - foreach (var extension in extensionPointManager.GetUserControlExtensionPoints(Module, Group)) - { - LoadControl(extension); - } - } - } - public void BindAction(int portalId, int tabId, int moduleId) { - foreach (var control in Controls) + foreach (var control in this.Controls) { var actionsControl = control as IUserControlActions; if (actionsControl != null) @@ -53,7 +27,7 @@ public void BindAction(int portalId, int tabId, int moduleId) public void SaveAction(int portalId, int tabId, int moduleId) { - foreach (var control in Controls) + foreach (var control in this.Controls) { var actionsControl = control as IUserControlActions; if (actionsControl != null) @@ -62,10 +36,36 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + var extensionPointManager = new ExtensionPointManager(); + + if (!string.IsNullOrEmpty(this.Name)) + { + var extension = extensionPointManager.GetUserControlExtensionPointFirstByPriority(this.Module, this.Name); + this.LoadControl(extension); + } + else + { + foreach (var extension in extensionPointManager.GetUserControlExtensionPoints(this.Module, this.Group)) + { + this.LoadControl(extension); + } + } + } + + private void LoadControl(IUserControlExtensionPoint extension) + { + var control = this.Page.LoadControl(extension.UserControlSrc); + control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); + this.Controls.Add(control); + } public void CancelAction(int portalId, int tabId, int moduleId) { - foreach (var control in Controls) + foreach (var control in this.Controls) { var actionsControl = control as IUserControlActions; if (actionsControl != null) diff --git a/DNN Platform/Library/Framework/AJAX.cs b/DNN Platform/Library/Framework/AJAX.cs index 74299ba2282..4ded65c023a 100644 --- a/DNN Platform/Library/Framework/AJAX.cs +++ b/DNN Platform/Library/Framework/AJAX.cs @@ -1,62 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Host; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Host; + using DotNetNuke.UI.WebControls; + public class AJAX - { - #region "Public Methods" - + { /// ----------------------------------------------------------------------------- /// - /// AddScriptManager is used internally by the framework to add a ScriptManager control to the page + /// AddScriptManager is used internally by the framework to add a ScriptManager control to the page. /// /// /// public static void AddScriptManager(Page page) { - AddScriptManager(page, true); + AddScriptManager(page, true); } - /// - /// AddScriptManager is used internally by the framework to add a ScriptManager control to the page. - /// - /// the page instance. - /// Whether check cdn settings from host settings. + + /// + /// AddScriptManager is used internally by the framework to add a ScriptManager control to the page. + /// + /// the page instance. + /// Whether check cdn settings from host settings. public static void AddScriptManager(Page page, bool checkCdn) { - if (GetScriptManager(page) == null) + if (GetScriptManager(page) == null) { if (page.Form != null) { try { - using (var scriptManager = new ScriptManager //RadScriptManager - { - ID = "ScriptManager", - EnableScriptGlobalization = true, - SupportsPartialRendering = true - }) + using (var scriptManager = new ScriptManager // RadScriptManager + { + ID = "ScriptManager", + EnableScriptGlobalization = true, + SupportsPartialRendering = true, + }) { if (checkCdn) { scriptManager.EnableCdn = Host.EnableMsAjaxCdn; scriptManager.EnableCdnFallback = Host.EnableMsAjaxCdn; } + page.Form.Controls.AddAt(0, scriptManager); } + if (HttpContext.Current.Items["System.Web.UI.ScriptManager"] == null) { HttpContext.Current.Items.Add("System.Web.UI.ScriptManager", true); @@ -64,42 +60,43 @@ public static void AddScriptManager(Page page, bool checkCdn) } catch { - //suppress error adding script manager to support edge-case of module developers custom aspx pages that inherit from basepage and use code blocks + // suppress error adding script manager to support edge-case of module developers custom aspx pages that inherit from basepage and use code blocks } } + if (page.Form != null) { try { - //DNN-9145 TODO - //using (var stylesheetManager = new RadStyleSheetManager { ID = "StylesheetManager", EnableHandlerDetection = false }) - //{ - // if (checkCdn) - // { - // stylesheetManager.CdnSettings.TelerikCdn = Host.EnableTelerikCdn ? TelerikCdnMode.Enabled : TelerikCdnMode.Disabled; - // if (stylesheetManager.CdnSettings.TelerikCdn != TelerikCdnMode.Disabled && !string.IsNullOrEmpty(Host.TelerikCdnBasicUrl)) - // { - // stylesheetManager.CdnSettings.BaseUrl = Host.TelerikCdnBasicUrl; - // } - // if (stylesheetManager.CdnSettings.TelerikCdn != TelerikCdnMode.Disabled && !string.IsNullOrEmpty(Host.TelerikCdnSecureUrl)) - // { - // stylesheetManager.CdnSettings.BaseSecureUrl = Host.TelerikCdnSecureUrl; - // } - // } - // page.Form.Controls.AddAt(0, stylesheetManager); - //} + // DNN-9145 TODO + // using (var stylesheetManager = new RadStyleSheetManager { ID = "StylesheetManager", EnableHandlerDetection = false }) + // { + // if (checkCdn) + // { + // stylesheetManager.CdnSettings.TelerikCdn = Host.EnableTelerikCdn ? TelerikCdnMode.Enabled : TelerikCdnMode.Disabled; + // if (stylesheetManager.CdnSettings.TelerikCdn != TelerikCdnMode.Disabled && !string.IsNullOrEmpty(Host.TelerikCdnBasicUrl)) + // { + // stylesheetManager.CdnSettings.BaseUrl = Host.TelerikCdnBasicUrl; + // } + // if (stylesheetManager.CdnSettings.TelerikCdn != TelerikCdnMode.Disabled && !string.IsNullOrEmpty(Host.TelerikCdnSecureUrl)) + // { + // stylesheetManager.CdnSettings.BaseSecureUrl = Host.TelerikCdnSecureUrl; + // } + // } + // page.Form.Controls.AddAt(0, stylesheetManager); + // } } catch { - //suppress error adding script manager to support edge-case of module developers custom aspx pages that inherit from basepage and use code blocks + // suppress error adding script manager to support edge-case of module developers custom aspx pages that inherit from basepage and use code blocks } } } - } - - /// Gets the current ScriptManager on the page - /// the page instance. - /// The ScriptManager instance, or null + } + + /// Gets the current ScriptManager on the page. + /// the page instance. + /// The ScriptManager instance, or null. public static ScriptManager GetScriptManager(Page objPage) { return objPage.FindControl("ScriptManager") as ScriptManager; @@ -111,7 +108,8 @@ public static ScriptManager GetScriptManager(Page objPage) /// only need one Script Manager per page. /// /// - /// + /// + /// public static bool IsEnabled() { if (HttpContext.Current.Items["System.Web.UI.ScriptManager"] == null) @@ -120,16 +118,17 @@ public static bool IsEnabled() } else { - return (bool) HttpContext.Current.Items["System.Web.UI.ScriptManager"]; + return (bool)HttpContext.Current.Items["System.Web.UI.ScriptManager"]; } } /// ----------------------------------------------------------------------------- /// - /// IsInstalled can be used to determine if AJAX is installed on the server + /// IsInstalled can be used to determine if AJAX is installed on the server. /// /// - /// + /// + /// public static bool IsInstalled() { return true; @@ -137,7 +136,7 @@ public static bool IsInstalled() /// ----------------------------------------------------------------------------- /// - /// Allows a control to be excluded from UpdatePanel async callback + /// Allows a control to be excluded from UpdatePanel async callback. /// /// /// @@ -152,7 +151,7 @@ public static void RegisterPostBackControl(Control objControl) /// ----------------------------------------------------------------------------- /// - /// RegisterScriptManager must be used by developers to instruct the framework that AJAX is required on the page + /// RegisterScriptManager must be used by developers to instruct the framework that AJAX is required on the page. /// /// /// @@ -166,7 +165,7 @@ public static void RegisterScriptManager() /// ----------------------------------------------------------------------------- /// - /// RemoveScriptManager will remove the ScriptManager control during Page Render if the RegisterScriptManager has not been called + /// RemoveScriptManager will remove the ScriptManager control during Page Render if the RegisterScriptManager has not been called. /// /// /// @@ -175,7 +174,7 @@ public static void RemoveScriptManager(Page objPage) if (!IsEnabled()) { Control objControl = objPage.FindControl("ScriptManager"); - if ((objControl != null)) + if (objControl != null) { objPage.Form.Controls.Remove(objControl); } @@ -184,10 +183,11 @@ public static void RemoveScriptManager(Page objPage) /// ----------------------------------------------------------------------------- /// - /// Wraps a control in an update panel + /// Wraps a control in an update panel. /// /// - /// + /// + /// public static Control WrapUpdatePanelControl(Control objControl, bool blnIncludeProgress) { var updatePanel = new UpdatePanel(); @@ -198,24 +198,27 @@ public static Control WrapUpdatePanelControl(Control objControl, bool blnInclude for (int i = 0; i <= objControl.Parent.Controls.Count - 1; i++) { - //find offset of original control + // find offset of original control if (objControl.Parent.Controls[i].ID == objControl.ID) { - //if ID matches + // if ID matches objControl.Parent.Controls.AddAt(i, updatePanel); - //insert update panel in that position + + // insert update panel in that position objContentTemplateContainer.Controls.Add(objControl); - //inject passed in control into update panel + + // inject passed in control into update panel break; } } if (blnIncludeProgress) { - //create image for update progress control + // create image for update progress control var objImage = new Image(); objImage.ImageUrl = "~/images/progressbar.gif"; - //hardcoded + + // hardcoded objImage.AlternateText = "ProgressBar"; var updateProgress = new UpdateProgress(); @@ -227,8 +230,6 @@ public static Control WrapUpdatePanelControl(Control objControl, bool blnInclude } return updatePanel; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Framework/BaseHttpHandler.cs b/DNN Platform/Library/Framework/BaseHttpHandler.cs index f523b582e7c..b2e8a2fbe3b 100644 --- a/DNN Platform/Library/Framework/BaseHttpHandler.cs +++ b/DNN Platform/Library/Framework/BaseHttpHandler.cs @@ -1,54 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Net; -using System.Text; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System; + using System.IO; + using System.Net; + using System.Text; + using System.Web; + public abstract class BaseHttpHandler : IHttpHandler { private HttpContext _context; /// - /// Returns the object for the incoming HTTP request. + /// Gets the object for the incoming HTTP request. /// public HttpContext Context { get { - return _context; + return this._context; } } /// - /// Returns the object for the incoming HTTP request. + /// Gets the object for the incoming HTTP request. /// public HttpRequest Request { get { - return Context.Request; + return this.Context.Request; } } /// - /// Gets the object associated with the Page object. This object + /// Gets the object associated with the Page object. This object /// allows you to send HTTP response data to a client and contains information about that response. /// public HttpResponse Response { get { - return Context.Response; + return this.Context.Response; } } @@ -59,8 +54,8 @@ public string Content { get { - Request.InputStream.Position = 0; - using (var Reader = new StreamReader(Request.InputStream)) + this.Request.InputStream.Position = 0; + using (var Reader = new StreamReader(this.Request.InputStream)) { return Reader.ReadToEnd(); } @@ -88,8 +83,8 @@ public virtual bool RequiresAuthentication /// has the necessary permissions. /// /// - /// By default all authenticated users have permssions. - /// This property is only enforced if is true + /// By default all authenticated users have permssions. + /// This property is only enforced if is true. /// /// /// true if the user has the appropriate permissions @@ -99,14 +94,16 @@ public virtual bool HasPermission { get { - return Context.User.Identity.IsAuthenticated; + return this.Context.User.Identity.IsAuthenticated; } } /// /// Gets the content MIME type for the response object. /// - /// + /// + /// The content MIME type for the response object. + /// public virtual string ContentMimeType { get @@ -118,61 +115,59 @@ public virtual string ContentMimeType /// /// Gets the content encoding for the response object. /// - /// + /// + /// The content encoding for the response object. + /// public virtual Encoding ContentEncoding { get { return Encoding.UTF8; } - } - - #region IHttpHandler Members + } + public virtual bool IsReusable + { + get + { + return true; + } + } + /// /// Processs the incoming HTTP request. /// /// Context. public void ProcessRequest(HttpContext context) { - _context = context; + this._context = context; - SetResponseCachePolicy(Response.Cache); + this.SetResponseCachePolicy(this.Response.Cache); - if (!ValidateParameters()) + if (!this.ValidateParameters()) { - RespondInternalError(); + this.RespondInternalError(); return; } - if (RequiresAuthentication && !HasPermission) + if (this.RequiresAuthentication && !this.HasPermission) { - RespondForbidden(); + this.RespondForbidden(); return; } - Response.ContentType = ContentMimeType; - Response.ContentEncoding = ContentEncoding; + this.Response.ContentType = this.ContentMimeType; + this.Response.ContentEncoding = this.ContentEncoding; - HandleRequest(); + this.HandleRequest(); } - - public virtual bool IsReusable - { - get - { - return true; - } - } - - #endregion - + /// /// Handles the request. This is where you put your /// business logic. /// /// - ///

    This method should result in a call to one + ///

    This method should result in a call to one /// (or more) of the following methods:

    ///

    context.Response.BinaryWrite();

    ///

    context.Response.Write();

    @@ -184,8 +179,8 @@ public virtual bool IsReusable ///

    ///

    etc...

    ///

    - /// If you want a download box to show up with a - /// pre-populated filename, add this call here + /// If you want a download box to show up with a + /// pre-populated filename, add this call here /// (supplying a real filename). ///

    ///

    @@ -201,7 +196,7 @@ public virtual bool IsReusable /// valid, otherwise false. /// /// true if the parameters are valid, - /// otherwise false + /// otherwise false. public abstract bool ValidateParameters(); ///

    @@ -223,8 +218,8 @@ public virtual void SetResponseCachePolicy(HttpCachePolicy cache) /// protected void RespondFileNotFound() { - Response.StatusCode = Convert.ToInt32(HttpStatusCode.NotFound); - Response.End(); + this.Response.StatusCode = Convert.ToInt32(HttpStatusCode.NotFound); + this.Response.End(); } /// @@ -235,8 +230,8 @@ protected void RespondInternalError() { // It's really too bad that StatusCode property // is not of type HttpStatusCode. - Response.StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError); - Response.End(); + this.Response.StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError); + this.Response.End(); } /// @@ -246,8 +241,8 @@ protected void RespondInternalError() /// protected void RespondForbidden() { - Response.StatusCode = Convert.ToInt32(HttpStatusCode.Forbidden); - Response.End(); + this.Response.StatusCode = Convert.ToInt32(HttpStatusCode.Forbidden); + this.Response.End(); } } } diff --git a/DNN Platform/Library/Framework/CDefault.cs b/DNN Platform/Library/Framework/CDefault.cs index e54fa5a9dcf..5d986eeaa23 100644 --- a/DNN Platform/Library/Framework/CDefault.cs +++ b/DNN Platform/Library/Framework/CDefault.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Web.UI; - -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.UI.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { - /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : CDefault - /// ----------------------------------------------------------------------------- - /// ----------------------------------------------------------------------------- + using System; + using System.Linq; + using System.Web.UI; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.UI.Utilities; + + // ----------------------------------------------------------------------------- + // Project : DotNetNuke + // Class : CDefault + // ----------------------------------------------------------------------------- + // ----------------------------------------------------------------------------- public class CDefault : PageBase { public string Author = string.Empty; @@ -36,14 +31,25 @@ public class CDefault : PageBase private static readonly object InstallerFilesRemovedLock = new object(); - protected override void RegisterAjaxScript() + protected string AdvancedSettingsPageUrl { - if (Page.Form != null) + get { - if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) + string result; + var tab = TabController.Instance.GetTabByName("Advanced Settings", this.PortalSettings.PortalId); + var modules = ModuleController.Instance.GetTabModules(tab.TabID).Values; + + if (modules.Count > 0) + { + var pmb = new PortalModuleBase(); + result = pmb.EditUrl(tab.TabID, string.Empty, false, string.Concat("mid=", modules.ElementAt(0).ModuleID), "popUp=true", string.Concat("ReturnUrl=", this.Server.UrlEncode(TestableGlobals.Instance.NavigateURL()))); + } + else { - ServicesFrameworkInternal.Instance.RegisterAjaxScript(Page); + result = TestableGlobals.Instance.NavigateURL(tab.TabID); } + + return result; } } @@ -51,7 +57,7 @@ protected override void RegisterAjaxScript() /// /// Allows the scroll position on the page to be moved to the top of the passed in control. /// - /// Control to scroll to + /// Control to scroll to. /// ----------------------------------------------------------------------------- public void ScrollToControl(Control objControl) { @@ -59,7 +65,18 @@ public void ScrollToControl(Control objControl) { JavaScript.RegisterClientReference(this, ClientAPI.ClientNamespaceReferences.dnn_dom_positioning); ClientAPI.RegisterClientVariable(this, "ScrollToControl", objControl.ClientID, true); - DNNClientAPI.SetScrollTop(Page); + DNNClientAPI.SetScrollTop(this.Page); + } + } + + protected override void RegisterAjaxScript() + { + if (this.Page.Form != null) + { + if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) + { + ServicesFrameworkInternal.Instance.RegisterAjaxScript(this.Page); + } } } @@ -77,27 +94,5 @@ protected void ManageInstallerFiles() } } } - - protected string AdvancedSettingsPageUrl - { - get - { - string result ; - var tab = TabController.Instance.GetTabByName("Advanced Settings", PortalSettings.PortalId); - var modules = ModuleController.Instance.GetTabModules(tab.TabID).Values; - - if (modules.Count > 0) - { - var pmb = new PortalModuleBase(); - result = pmb.EditUrl(tab.TabID, "", false, string.Concat("mid=", modules.ElementAt(0).ModuleID), "popUp=true", string.Concat("ReturnUrl=", Server.UrlEncode(TestableGlobals.Instance.NavigateURL()))); - } - else - { - result = TestableGlobals.Instance.NavigateURL(tab.TabID); - } - - return result; - } - } } } diff --git a/DNN Platform/Library/Framework/CachePageStatePersister.cs b/DNN Platform/Library/Framework/CachePageStatePersister.cs index a0f524eeb5d..ec3316aad0a 100644 --- a/DNN Platform/Library/Framework/CachePageStatePersister.cs +++ b/DNN Platform/Library/Framework/CachePageStatePersister.cs @@ -1,67 +1,66 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text; -using System.Web.Caching; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Cache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System; + using System.Text; + using System.Web.Caching; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Cache; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Framework /// Project: DotNetNuke /// Class: CachePageStatePersister /// ----------------------------------------------------------------------------- /// - /// CachePageStatePersister provides a cache based page state peristence mechanism + /// CachePageStatePersister provides a cache based page state peristence mechanism. /// /// ----------------------------------------------------------------------------- public class CachePageStatePersister : PageStatePersister { - private const string VIEW_STATE_CACHEKEY = "__VIEWSTATE_CACHEKEY"; - + private const string VIEW_STATE_CACHEKEY = "__VIEWSTATE_CACHEKEY"; + /// ----------------------------------------------------------------------------- - /// - /// Creates the CachePageStatePersister + /// + /// Initializes a new instance of the class. + /// Creates the CachePageStatePersister. /// /// ----------------------------------------------------------------------------- - public CachePageStatePersister(Page page) : base(page) + public CachePageStatePersister(Page page) + : base(page) { } /// ----------------------------------------------------------------------------- /// - /// Loads the Page State from the Cache + /// Loads the Page State from the Cache. /// /// ----------------------------------------------------------------------------- public override void Load() { - //Get the cache key from the web form data - string key = Page.Request.Params[VIEW_STATE_CACHEKEY]; + // Get the cache key from the web form data + string key = this.Page.Request.Params[VIEW_STATE_CACHEKEY]; - //Abort if cache key is not available or valid + // Abort if cache key is not available or valid if (string.IsNullOrEmpty(key) || !key.StartsWith("VS_")) { throw new ApplicationException("Missing valid " + VIEW_STATE_CACHEKEY); } + var state = DataCache.GetCache(key); if (state != null) { - //Set view state and control state - ViewState = state.First; - ControlState = state.Second; + // Set view state and control state + this.ViewState = state.First; + this.ControlState = state.Second; } - //Remove this ViewState from the cache as it has served its purpose - if (!Page.IsCallback) + + // Remove this ViewState from the cache as it has served its purpose + if (!this.Page.IsCallback) { DataCache.RemoveCache(key); } @@ -69,35 +68,35 @@ public override void Load() /// ----------------------------------------------------------------------------- /// - /// Saves the Page State to the Cache + /// Saves the Page State to the Cache. /// /// ----------------------------------------------------------------------------- public override void Save() { - //No processing needed if no states available - if (ViewState == null && ControlState == null) + // No processing needed if no states available + if (this.ViewState == null && this.ControlState == null) { return; } - - //Generate a unique cache key + + // Generate a unique cache key var key = new StringBuilder(); { key.Append("VS_"); - key.Append(Page.Session == null ? Guid.NewGuid().ToString() : Page.Session.SessionID); + key.Append(this.Page.Session == null ? Guid.NewGuid().ToString() : this.Page.Session.SessionID); key.Append("_"); key.Append(DateTime.Now.Ticks.ToString()); } - - //Save view state and control state separately - var state = new Pair(ViewState, ControlState); - //Add view state and control state to cache + // Save view state and control state separately + var state = new Pair(this.ViewState, this.ControlState); + + // Add view state and control state to cache DNNCacheDependency objDependency = null; - DataCache.SetCache(key.ToString(), state, objDependency, DateTime.Now.AddMinutes(Page.Session.Timeout), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); + DataCache.SetCache(key.ToString(), state, objDependency, DateTime.Now.AddMinutes(this.Page.Session.Timeout), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); - //Register hidden field to store cache key in - Page.ClientScript.RegisterHiddenField(VIEW_STATE_CACHEKEY, key.ToString()); + // Register hidden field to store cache key in + this.Page.ClientScript.RegisterHiddenField(VIEW_STATE_CACHEKEY, key.ToString()); } } } diff --git a/DNN Platform/Library/Framework/DiskPageStatePersister.cs b/DNN Platform/Library/Framework/DiskPageStatePersister.cs index 135f60ea9a0..3043004cb4a 100644 --- a/DNN Platform/Library/Framework/DiskPageStatePersister.cs +++ b/DNN Platform/Library/Framework/DiskPageStatePersister.cs @@ -1,44 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.Text; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System.IO; + using System.Text; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Framework /// Project: DotNetNuke /// Class: DiskPageStatePersister /// ----------------------------------------------------------------------------- /// - /// DiskPageStatePersister provides a disk (stream) based page state peristence mechanism + /// DiskPageStatePersister provides a disk (stream) based page state peristence mechanism. /// /// ----------------------------------------------------------------------------- public class DiskPageStatePersister : PageStatePersister - { + { /// ----------------------------------------------------------------------------- - /// - /// Creates the DiskPageStatePersister + /// + /// Initializes a new instance of the class. + /// Creates the DiskPageStatePersister. /// /// ----------------------------------------------------------------------------- - public DiskPageStatePersister(Page page) : base(page) + public DiskPageStatePersister(Page page) + : base(page) { } /// ----------------------------------------------------------------------------- /// - /// The CacheDirectory property is used to return the location of the "Cache" - /// Directory for the Portal + /// Gets the CacheDirectory property is used to return the location of the "Cache" + /// Directory for the Portal. /// /// /// @@ -53,7 +50,7 @@ public string CacheDirectory /// ----------------------------------------------------------------------------- /// - /// The StateFileName property is used to store the FileName for the State + /// Gets the StateFileName property is used to store the FileName for the State. /// /// /// @@ -65,36 +62,38 @@ public string StateFileName var key = new StringBuilder(); { key.Append("VIEWSTATE_"); - key.Append(Page.Session.SessionID); + key.Append(this.Page.Session.SessionID); key.Append("_"); - key.Append(Page.Request.RawUrl); + key.Append(this.Page.Request.RawUrl); } - return CacheDirectory + "\\" + Globals.CleanFileName(key.ToString()) + ".txt"; + + return this.CacheDirectory + "\\" + Globals.CleanFileName(key.ToString()) + ".txt"; } } /// ----------------------------------------------------------------------------- /// - /// Loads the Page State from the Cache + /// Loads the Page State from the Cache. /// /// ----------------------------------------------------------------------------- public override void Load() { StreamReader reader = null; - //Read the state string, using the StateFormatter. + + // Read the state string, using the StateFormatter. try { - reader = new StreamReader(StateFileName); + reader = new StreamReader(this.StateFileName); string serializedStatePair = reader.ReadToEnd(); - IStateFormatter formatter = StateFormatter; + IStateFormatter formatter = this.StateFormatter; - //Deserialize returns the Pair object that is serialized in - //the Save method. - var statePair = (Pair) formatter.Deserialize(serializedStatePair); - ViewState = statePair.First; - ControlState = statePair.Second; + // Deserialize returns the Pair object that is serialized in + // the Save method. + var statePair = (Pair)formatter.Deserialize(serializedStatePair); + this.ViewState = statePair.First; + this.ControlState = statePair.Second; } finally { @@ -107,28 +106,29 @@ public override void Load() /// ----------------------------------------------------------------------------- /// - /// Saves the Page State to the Cache + /// Saves the Page State to the Cache. /// /// ----------------------------------------------------------------------------- public override void Save() { - //No processing needed if no states available - if (ViewState == null && ControlState == null) + // No processing needed if no states available + if (this.ViewState == null && this.ControlState == null) { return; } - if (Page.Session != null) + + if (this.Page.Session != null) { - if (!Directory.Exists(CacheDirectory)) + if (!Directory.Exists(this.CacheDirectory)) { - Directory.CreateDirectory(CacheDirectory); + Directory.CreateDirectory(this.CacheDirectory); } - //Write a state string, using the StateFormatter. - using (var writer = new StreamWriter(StateFileName, false)) + // Write a state string, using the StateFormatter. + using (var writer = new StreamWriter(this.StateFileName, false)) { - IStateFormatter formatter = StateFormatter; - var statePair = new Pair(ViewState, ControlState); + IStateFormatter formatter = this.StateFormatter; + var statePair = new Pair(this.ViewState, this.ControlState); string serializedState = formatter.Serialize(statePair); writer.Write(serializedState); writer.Close(); diff --git a/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs b/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs index edc0d3f2431..67e96aed4e8 100644 --- a/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs +++ b/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework { + using System; + using System.Web.UI; + internal interface IServiceFrameworkInternals { bool IsAjaxAntiForgerySupportRequired { get; } - void RegisterAjaxAntiForgery(Page page); - bool IsAjaxScriptSupportRequired { get; } + void RegisterAjaxAntiForgery(Page page); + void RegisterAjaxScript(Page page); } } diff --git a/DNN Platform/Library/Framework/IServicesFramework.cs b/DNN Platform/Library/Framework/IServicesFramework.cs index 04334aeeeee..1bbb3908784 100644 --- a/DNN Platform/Library/Framework/IServicesFramework.cs +++ b/DNN Platform/Library/Framework/IServicesFramework.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework { + using System; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -13,12 +13,12 @@ namespace DotNetNuke.Framework public interface IServicesFramework { /// - /// Will cause anti forgery tokens to be included in the current page + /// Will cause anti forgery tokens to be included in the current page. /// void RequestAjaxAntiForgerySupport(); /// - /// Will cause ajax scripts to be included in the current page + /// Will cause ajax scripts to be included in the current page. /// void RequestAjaxScriptSupport(); } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/CommonJS.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/CommonJS.cs index 603d2023907..3ca569490d1 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/CommonJS.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/CommonJS.cs @@ -1,37 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.JavaScriptLibraries { /// /// this class contains a number of constants that map to s - /// done as a series of constants as enums do not allow hyphens or periods + /// done as a series of constants as enums do not allow hyphens or periods. /// public static class CommonJs { - /// jQuery library name + /// jQuery library name. public const string jQuery = "jQuery"; - /// jQuery Migrate library name + /// jQuery Migrate library name. public const string jQueryMigrate = "jQuery-Migrate"; - /// jQuery UI library name + /// jQuery UI library name. public const string jQueryUI = "jQuery-UI"; - /// Knockout library name + /// Knockout library name. public const string Knockout = "Knockout"; - /// Knockout Mapping library name + /// Knockout Mapping library name. public const string KnockoutMapping = "Knockout.Mapping"; - /// jQuery Fileupload library name + /// jQuery Fileupload library name. public const string jQueryFileUpload = "jQuery.Fileupload"; - /// DNN jQuery plugins library name + /// DNN jQuery plugins library name. public const string DnnPlugins = "DnnPlugins"; - /// HoverIntent library name + /// HoverIntent library name. public const string HoverIntent = "HoverIntent"; } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/IJavaScriptLibraryController.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/IJavaScriptLibraryController.cs index 6a818e0981b..9e9a1c36f7b 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/IJavaScriptLibraryController.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/IJavaScriptLibraryController.cs @@ -1,40 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.JavaScriptLibraries { + using System; + using System.Collections.Generic; + public interface IJavaScriptLibraryController { - /// Delete the library reference from the database - /// Library to be deleted + /// Delete the library reference from the database. + /// Library to be deleted. void DeleteLibrary(JavaScriptLibrary library); - /// Get information about the latest version of a that matches the given - /// A function used to filter the library + /// Get information about the latest version of a that matches the given . + /// A function used to filter the library. /// - /// JavaScriptLibraryController.Instance.GetLibrary(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)) + /// JavaScriptLibraryController.Instance.GetLibrary(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)). /// - /// The highest version instance that matches the , or null if no library matches + /// The highest version instance that matches the , or null if no library matches. JavaScriptLibrary GetLibrary(Func predicate); - /// Gets all of the instances matching the given - /// A function used to filter the library + /// Gets all of the instances matching the given . + /// A function used to filter the library. /// - /// JavaScriptLibraryController.Instance.GetLibraries(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)) + /// JavaScriptLibraryController.Instance.GetLibraries(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)). /// - /// A sequence of instances + /// A sequence of instances. IEnumerable GetLibraries(Func predicate); - /// Gets all of the instances - /// A sequence of instances + /// Gets all of the instances. + /// A sequence of instances. IEnumerable GetLibraries(); - /// Save a library to the database - /// Library to be saved + /// Save a library to the database. + /// Library to be saved. void SaveLibrary(JavaScriptLibrary library); } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs index 7ba84e21a2d..7bbe86f8ebe 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs @@ -1,82 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web; -using System.Web.UI; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework.JavaScriptLibraries { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + + using Globals = DotNetNuke.Common.Globals; + public class JavaScript { private const string ScriptPrefix = "JSL."; private const string LegacyPrefix = "LEGACY."; - #region Public Methods + private const string jQueryUIDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.js"; + private const string jQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js"; + + protected JavaScript() + { + } /// - /// checks whether the script file is a known javascript library + /// checks whether the script file is a known javascript library. /// - /// script identifier + /// script identifier. /// - public static bool IsInstalled(String jsname) + public static bool IsInstalled(string jsname) { JavaScriptLibrary library = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName.Equals(jsname, StringComparison.OrdinalIgnoreCase)); return library != null; } /// - /// determine whether to use the debug script for a file + /// determine whether to use the debug script for a file. /// - /// whether to use the debug script + /// whether to use the debug script. public static bool UseDebugScript() { if (Globals.Status != Globals.UpgradeStatus.None) { return false; } + return HttpContextSource.Current.IsDebuggingEnabled; } /// - /// returns the version of a javascript library from the database + /// returns the version of a javascript library from the database. /// - /// the library name + /// the library name. /// - public static string Version(String jsname) + public static string Version(string jsname) { JavaScriptLibrary library = GetHighestVersionLibrary(jsname); - return library != null ? Convert.ToString(library.Version) : String.Empty; + return library != null ? Convert.ToString(library.Version) : string.Empty; } - /// Requests a script to be added to the page - /// the library name + /// Requests a script to be added to the page. + /// the library name. public static void RequestRegistration(string jsname) { - //handle case where script has no javascript library + // handle case where script has no javascript library switch (jsname) { case CommonJs.jQuery: @@ -95,18 +98,18 @@ public static void RequestRegistration(string jsname) RequestRegistration(jsname, null, SpecificVersion.Latest); } - - /// Requests a script to be added to the page - /// the library name - /// the library's version + + /// Requests a script to be added to the page. + /// the library name. + /// the library's version. public static void RequestRegistration(string jsname, Version version) { RequestRegistration(jsname, version, SpecificVersion.Exact); } - /// Requests a script to be added to the page - /// the library name - /// the library's version + /// Requests a script to be added to the page. + /// the library name. + /// the library's version. /// /// how much of the to pay attention to. /// When is passed, ignore the . @@ -123,7 +126,7 @@ public static void RequestRegistration(string jsname, Version version, SpecificV return; case SpecificVersion.LatestMajor: case SpecificVersion.LatestMinor: - if (RequestLooseVersionLibraryRegistration(jsname, version, specific)) + if (RequestLooseVersionLibraryRegistration(jsname, version, specific)) { return; } @@ -134,15 +137,15 @@ public static void RequestRegistration(string jsname, Version version, SpecificV return; } - //this should only occur if packages are incorrect or a RequestRegistration call has a typo - LogCollision(String.Format("Missing specific version library - {0},{1},{2}", jsname, version, specific)); + // this should only occur if packages are incorrect or a RequestRegistration call has a typo + LogCollision(string.Format("Missing specific version library - {0},{1},{2}", jsname, version, specific)); } /// /// method is called once per page event cycle and will - /// load all scripts requested during that page processing cycle + /// load all scripts requested during that page processing cycle. /// - /// reference to the current page + /// reference to the current page. public static void Register(Page page) { HandlePreInstallorLegacyItemRequests(page); @@ -154,17 +157,16 @@ public static void Register(Page page) } } - #endregion - - #region Contructors - - protected JavaScript() + public static string JQueryUIFile(bool getMinFile) { - } - - #endregion + string jfile = jQueryUIDebugFile; + if (getMinFile) + { + jfile = jQueryUIMinFile; + } - #region Private Methods + return jfile; + } private static void RequestHighestVersionLibraryRegistration(string jsname) { @@ -175,12 +177,12 @@ private static void RequestHighestVersionLibraryRegistration(string jsname) } else { - //covers case where upgrading to 7.2.0 and JSL's are not installed + // covers case where upgrading to 7.2.0 and JSL's are not installed AddPreInstallorLegacyItemRequest(jsname); } } - private static bool RequestLooseVersionLibraryRegistration(string jsname, Version version, SpecificVersion specific) + private static bool RequestLooseVersionLibraryRegistration(string jsname, Version version, SpecificVersion specific) { Func isValidLibrary = specific == SpecificVersion.LatestMajor ? (Func)(l => l.Version.Major == version.Major && l.Version.Minor >= version.Minor) @@ -194,7 +196,7 @@ private static bool RequestLooseVersionLibraryRegistration(string jsname, Versio return true; } - //unable to find a higher major version + // unable to find a higher major version library = GetHighestVersionLibrary(jsname); if (library != null) { @@ -215,8 +217,8 @@ private static void RequestSpecificVersionLibraryRegistration(string jsname, Ver } else { - //this will only occur if a specific library is requested and not available - LogCollision(String.Format("Missing Library request - {0} : {1}", jsname, version)); + // this will only occur if a specific library is requested and not available + LogCollision(string.Format("Missing Library request - {0} : {1}", jsname, version)); } } @@ -266,24 +268,26 @@ private static IEnumerable ResolveVersionConflicts(IEnumerabl finalScripts.Add(processingLibrary); } } + return finalScripts; } - private static JavaScriptLibrary GetHighestVersionLibrary(String jsname) + private static JavaScriptLibrary GetHighestVersionLibrary(string jsname) { - if (Globals.Status == Globals.UpgradeStatus.Install) //if in install process, then do not use JSL but all use the legacy versions. + if (Globals.Status == Globals.UpgradeStatus.Install) // if in install process, then do not use JSL but all use the legacy versions. { return null; } + try { return JavaScriptLibraryController.Instance.GetLibraries(l => l.LibraryName.Equals(jsname, StringComparison.OrdinalIgnoreCase)) .OrderByDescending(l => l.Version) - .FirstOrDefault(); + .FirstOrDefault(); } catch (Exception) { - //no library found (install or upgrade) + // no library found (install or upgrade) return null; } } @@ -292,25 +296,27 @@ private static string GetScriptPath(JavaScriptLibrary js, Page page) { if (Host.CdnEnabled) { - //load custom CDN path setting + // load custom CDN path setting var customCdn = HostController.Instance.GetString("CustomCDN_" + js.LibraryName); if (!string.IsNullOrEmpty(customCdn)) { return customCdn; } - //cdn enabled but jsl does not have one defined - if (!String.IsNullOrEmpty(js.CDNPath)) + // cdn enabled but jsl does not have one defined + if (!string.IsNullOrEmpty(js.CDNPath)) { var cdnPath = js.CDNPath; if (cdnPath.StartsWith("//")) { cdnPath = $"{(UrlUtils.IsSecureConnectionOrSslOffload(page.Request) ? "https" : "http")}:{cdnPath}"; } + return cdnPath; } } - return ("~/Resources/libraries/" + js.LibraryName + "/" + Globals.FormatVersion(js.Version, "00", 3, "_") + "/" + js.FileName); + + return "~/Resources/libraries/" + js.LibraryName + "/" + Globals.FormatVersion(js.Version, "00", 3, "_") + "/" + js.FileName; } private static string GetScriptLocation(JavaScriptLibrary js) @@ -325,7 +331,7 @@ private static string GetScriptLocation(JavaScriptLibrary js) return "DnnBodyProvider"; } - return String.Empty; + return string.Empty; } private static IEnumerable GetScriptVersions() @@ -352,6 +358,7 @@ where item.ToString().StartsWith(ScriptPrefix) } } } + return finalScripts; } @@ -372,17 +379,18 @@ private static IEnumerable GetAllDependencies(JavaScriptLibra private static void LogCollision(string collisionText) { - //need to log an event - EventLogController.Instance.AddLog("Javascript Libraries", - collisionText, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.SCRIPT_COLLISION); + // need to log an event + EventLogController.Instance.AddLog( + "Javascript Libraries", + collisionText, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.SCRIPT_COLLISION); string strMessage = Localization.GetString("ScriptCollision", Localization.SharedResourceFile); var page = HttpContextSource.Current.Handler as Page; if (page != null) { - Skin.AddPageMessage(page, "", strMessage, ModuleMessage.ModuleMessageType.YellowWarning); + Skin.AddPageMessage(page, string.Empty, strMessage, ModuleMessage.ModuleMessageType.YellowWarning); } } @@ -395,14 +403,15 @@ private static void RegisterScript(Page page, JavaScriptLibrary jsl) ClientResourceManager.RegisterScript(page, GetScriptPath(jsl, page), GetFileOrder(jsl), GetScriptLocation(jsl), jsl.LibraryName, jsl.Version.ToString(3)); - //workaround to support IE specific script until we move to IE version that no longer requires this + // workaround to support IE specific script until we move to IE version that no longer requires this if (jsl.LibraryName == CommonJs.jQueryFileUpload) { - ClientResourceManager.RegisterScript(page, + ClientResourceManager.RegisterScript( + page, "~/Resources/Shared/Scripts/jquery/jquery.iframe-transport.js"); } - if (Host.CdnEnabled && !String.IsNullOrEmpty(jsl.ObjectName)) + if (Host.CdnEnabled && !string.IsNullOrEmpty(jsl.ObjectName)) { string pagePortion; switch (jsl.PreferredScriptLocation) @@ -421,11 +430,12 @@ private static void RegisterScript(Page page, JavaScriptLibrary jsl) pagePortion = "BodySCRIPTS"; break; } + Control scriptloader = page.FindControl(pagePortion); var fallback = new DnnJsIncludeFallback(jsl.ObjectName, VirtualPathUtility.ToAbsolute("~/Resources/libraries/" + jsl.LibraryName + "/" + Globals.FormatVersion(jsl.Version, "00", 3, "_") + "/" + jsl.FileName)); if (scriptloader != null) { - //add the fallback control after script loader. + // add the fallback control after script loader. var index = scriptloader.Parent.Controls.IndexOf(scriptloader); scriptloader.Parent.Controls.AddAt(index + 1, fallback); } @@ -445,8 +455,7 @@ private static int GetFileOrder(JavaScriptLibrary jsl) case CommonJs.HoverIntent: return (int)FileOrder.Js.HoverIntent; default: - return jsl.PackageID + (int) FileOrder.Js.DefaultPriority; - + return jsl.PackageID + (int)FileOrder.Js.DefaultPriority; } } @@ -456,7 +465,7 @@ private static void HandlePreInstallorLegacyItemRequests(Page page) where item.ToString().StartsWith(LegacyPrefix) select item.ToString().Substring(7)).ToList(); #pragma warning disable 618 - foreach (string legacyScript in legacyScripts) + foreach (string legacyScript in legacyScripts) { switch (legacyScript) { @@ -466,41 +475,44 @@ where item.ToString().StartsWith(LegacyPrefix) ClientResourceManager.RegisterScript(page, jQuery.GetJQueryScriptReference(), FileOrder.Js.jQuery, "DnnPageHeaderProvider"); } + if (GetHighestVersionLibrary(CommonJs.jQueryMigrate) == null) { ClientResourceManager.RegisterScript(page, jQuery.GetJQueryMigrateScriptReference(), FileOrder.Js.jQueryMigrate, "DnnPageHeaderProvider"); } + break; case CommonJs.jQueryUI: - //register dependency + // register dependency if (GetHighestVersionLibrary(CommonJs.jQuery) == null) { ClientResourceManager.RegisterScript(page, jQuery.GetJQueryScriptReference(), FileOrder.Js.jQuery, "DnnPageHeaderProvider"); } + if (GetHighestVersionLibrary(CommonJs.jQueryMigrate) == null) { ClientResourceManager.RegisterScript(page, jQuery.GetJQueryMigrateScriptReference(), FileOrder.Js.jQueryMigrate, "DnnPageHeaderProvider"); } - //actual jqueryui + + // actual jqueryui if (GetHighestVersionLibrary(CommonJs.jQueryUI) == null) { ClientResourceManager.RegisterScript(page, jQuery.GetJQueryUIScriptReference(), FileOrder.Js.jQueryUI, "DnnPageHeaderProvider"); } + break; case CommonJs.DnnPlugins: - //This method maybe called when Page.Form hasn't initialized yet, in that situation if needed should reference dnn js manually. - //such as call jQuery.RegisterDnnJQueryPlugins in Control.OnInit. + // This method maybe called when Page.Form hasn't initialized yet, in that situation if needed should reference dnn js manually. + // such as call jQuery.RegisterDnnJQueryPlugins in Control.OnInit. if (page.Form != null) { - } - //register dependency - + // register dependency if (GetHighestVersionLibrary(CommonJs.jQuery) == null) { ClientResourceManager.RegisterScript(page, jQuery.GetJQueryScriptReference(), @@ -513,8 +525,7 @@ where item.ToString().StartsWith(LegacyPrefix) FileOrder.Js.jQueryMigrate, "DnnPageHeaderProvider"); } - - //actual jqueryui + // actual jqueryui if (GetHighestVersionLibrary(CommonJs.jQueryUI) == null) { ClientResourceManager.RegisterScript(page, jQuery.GetJQueryUIScriptReference(), @@ -523,46 +534,34 @@ where item.ToString().StartsWith(LegacyPrefix) if (GetHighestVersionLibrary(CommonJs.HoverIntent) == null) { - ClientResourceManager.RegisterScript(page, + ClientResourceManager.RegisterScript( + page, "~/Resources/Shared/Scripts/jquery/jquery.hoverIntent.min.js", FileOrder.Js.HoverIntent); } - //no package for this - CRM will deduplicate + + // no package for this - CRM will deduplicate ClientResourceManager.RegisterScript(page, "~/Resources/Shared/Scripts/dnn.jquery.js"); break; case CommonJs.jQueryFileUpload: - ClientResourceManager.RegisterScript(page, + ClientResourceManager.RegisterScript( + page, "~/Resources/Shared/Scripts/jquery/jquery.iframe-transport.js"); - ClientResourceManager.RegisterScript(page, + ClientResourceManager.RegisterScript( + page, "~/Resources/Shared/Scripts/jquery/jquery.fileupload.js"); break; case CommonJs.HoverIntent: if (GetHighestVersionLibrary(CommonJs.HoverIntent) == null) { - ClientResourceManager.RegisterScript(page, + ClientResourceManager.RegisterScript( + page, "~/Resources/Shared/Scripts/jquery/jquery.hoverIntent.min.js", FileOrder.Js.HoverIntent); } + break; } - } -#pragma warning restore 618 - } - - #endregion - - #region Legacy methods and preinstall support - - private const string jQueryUIDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.js"; - private const string jQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js"; - - - public static string JQueryUIFile(bool getMinFile) - { - string jfile = jQueryUIDebugFile; - if (getMinFile) - { - jfile = jQueryUIMinFile; } - return jfile; +#pragma warning restore 618 } public static string GetJQueryScriptReference() @@ -573,9 +572,10 @@ public static string GetJQueryScriptReference() { scriptsrc = jQuery.JQueryFile(!jQuery.UseDebugScript); } + return scriptsrc; #pragma warning restore 618 - } + } public static void RegisterClientReference(Page page, ClientAPI.ClientNamespaceReferences reference) { @@ -590,7 +590,7 @@ public static void RegisterClientReference(Page page, ClientAPI.ClientNamespaceR ClientResourceManager.RegisterScript(page, ClientAPI.ScriptPath + "dnn.js", 12); HttpContextSource.Current.Items.Add(LegacyPrefix + "dnn.js", true); - page.ClientScript.RegisterClientScriptBlock(page.GetType(), "dnn.js", ""); + page.ClientScript.RegisterClientScriptBlock(page.GetType(), "dnn.js", string.Empty); if (!ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.SingleCharDelimiters)) { @@ -599,8 +599,9 @@ public static void RegisterClientReference(Page page, ClientAPI.ClientNamespaceR if (!ClientAPI.UseExternalScripts) { - ClientAPI.RegisterEmbeddedResource(page, "dnn.scripts.js", typeof (ClientAPI)); + ClientAPI.RegisterEmbeddedResource(page, "dnn.scripts.js", typeof(ClientAPI)); } + break; case ClientAPI.ClientNamespaceReferences.dnn_dom_positioning: RegisterClientReference(page, ClientAPI.ClientNamespaceReferences.dnn); @@ -608,7 +609,5 @@ public static void RegisterClientReference(Page page, ClientAPI.ClientNamespaceR break; } } - - #endregion } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs index 0719e72503b..815596896d7 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs @@ -1,53 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.JavaScriptLibraries { + using System; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + [Serializable] public class JavaScriptLibrary : IXmlSerializable { /// - /// unique identifier id for a javscript library package + /// Gets or sets unique identifier id for a javscript library package. /// public int JavaScriptLibraryID { get; set; } + /// - /// package id associated with the javscript library package + /// Gets or sets package id associated with the javscript library package. /// public int PackageID { get; set; } + /// - /// name of the javscript library package (used when requesting library) + /// Gets or sets name of the javscript library package (used when requesting library). /// public string LibraryName { get; set; } + /// - /// version of the the javscript library package from the database + /// Gets or sets version of the the javscript library package from the database. /// public Version Version { get; set; } + /// - /// main object (where relevant) of the javscript library package - /// used to generate the local file fallback code in the case where the CDN file is not available + /// Gets or sets main object (where relevant) of the javscript library package + /// used to generate the local file fallback code in the case where the CDN file is not available. /// public string ObjectName { get; set; } + /// - /// filename of the script in the filesystem + /// Gets or sets filename of the script in the filesystem. /// public string FileName { get; set; } + /// - /// position in the page the script reference is injected + /// Gets or sets position in the page the script reference is injected. /// public ScriptLocation PreferredScriptLocation { get; set; } + /// - /// location of the content delivery network (CDN) where the script is loaded from when CDN has been enabled in host + /// Gets or sets location of the content delivery network (CDN) where the script is loaded from when CDN has been enabled in host. /// - public string CDNPath { get; set; } - - #region IXmlSerializable Implementation - + public string CDNPath { get; set; } + public XmlSchema GetSchema() { throw new NotImplementedException(); @@ -55,9 +60,9 @@ public XmlSchema GetSchema() /// ----------------------------------------------------------------------------- /// - /// Reads a JavaScriptLibrary from an XmlReader + /// Reads a JavaScriptLibrary from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { @@ -67,6 +72,7 @@ public void ReadXml(XmlReader reader) { break; } + if (reader.NodeType == XmlNodeType.Whitespace) { continue; @@ -78,37 +84,39 @@ public void ReadXml(XmlReader reader) case "javaScriptLibrary": break; case "libraryName": - LibraryName = reader.ReadElementContentAsString(); + this.LibraryName = reader.ReadElementContentAsString(); break; case "objectName": - ObjectName = reader.ReadElementContentAsString(); + this.ObjectName = reader.ReadElementContentAsString(); break; case "fileName": - FileName = reader.ReadElementContentAsString(); + this.FileName = reader.ReadElementContentAsString(); break; case "preferredScriptLocation": var location = reader.ReadElementContentAsString(); switch (location) { case "BodyTop": - PreferredScriptLocation = ScriptLocation.BodyTop; + this.PreferredScriptLocation = ScriptLocation.BodyTop; break; case "BodyBottom": - PreferredScriptLocation = ScriptLocation.BodyBottom; + this.PreferredScriptLocation = ScriptLocation.BodyBottom; break; default: - PreferredScriptLocation = ScriptLocation.PageHead; + this.PreferredScriptLocation = ScriptLocation.PageHead; break; } + break; case "CDNPath": - CDNPath = reader.ReadElementContentAsString(); + this.CDNPath = reader.ReadElementContentAsString(); break; default: - if(reader.NodeType == XmlNodeType.Element && !String.IsNullOrEmpty(reader.Name)) + if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } + break; } } @@ -117,26 +125,24 @@ public void ReadXml(XmlReader reader) /// ----------------------------------------------------------------------------- /// - /// Writes a JavaScriptLibrary to an XmlWriter + /// Writes a JavaScriptLibrary to an XmlWriter. /// - /// The XmlWriter to use + /// The XmlWriter to use. /// ----------------------------------------------------------------------------- public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("javaScriptLibrary"); - //write out properties - writer.WriteElementString("libraryName", LibraryName); - writer.WriteElementString("fileName", FileName); - writer.WriteElementString("objectName", ObjectName); - writer.WriteElementString("preferredScriptLocation", PreferredScriptLocation.ToString()); - writer.WriteElementString("CDNPath", CDNPath); + // write out properties + writer.WriteElementString("libraryName", this.LibraryName); + writer.WriteElementString("fileName", this.FileName); + writer.WriteElementString("objectName", this.ObjectName); + writer.WriteElementString("preferredScriptLocation", this.PreferredScriptLocation.ToString()); + writer.WriteElementString("CDNPath", this.CDNPath); - //Write end of main element + // Write end of main element writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs index e4650b213ed..154603fba3d 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs @@ -1,88 +1,87 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.JavaScriptLibraries { - public class JavaScriptLibraryController - : ServiceLocator - , IJavaScriptLibraryController + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + + public class JavaScriptLibraryController + : ServiceLocator, + IJavaScriptLibraryController { - private void ClearCache() - { - DataCache.RemoveCache(DataCache.JavaScriptLibrariesCacheKey); - } - - protected override Func GetFactory() - { - return () => new JavaScriptLibraryController(); - } - - #region IJavaScriptController Implementation - - /// Delete the library reference from the database - /// Library to be deleted + /// Delete the library reference from the database. + /// Library to be deleted. public void DeleteLibrary(JavaScriptLibrary library) { DataProvider.Instance().ExecuteNonQuery("DeleteJavaScriptLibrary", library.JavaScriptLibraryID); - ClearCache(); + this.ClearCache(); } - /// Get information about the latest version of a that matches the given - /// A function used to filter the library + /// Get information about the latest version of a that matches the given . + /// A function used to filter the library. /// - /// JavaScriptLibraryController.Instance.GetLibrary(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)) + /// JavaScriptLibraryController.Instance.GetLibrary(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)). /// - /// The highest version instance that matches the , or null if no library matches + /// The highest version instance that matches the , or null if no library matches. public JavaScriptLibrary GetLibrary(Func predicate) { - return GetLibraries(predicate).OrderByDescending(l => l.Version).FirstOrDefault(); + return this.GetLibraries(predicate).OrderByDescending(l => l.Version).FirstOrDefault(); + } + + protected override Func GetFactory() + { + return () => new JavaScriptLibraryController(); + } + + private void ClearCache() + { + DataCache.RemoveCache(DataCache.JavaScriptLibrariesCacheKey); } - /// Gets all of the instances matching the given - /// A function used to filter the library + /// Gets all of the instances matching the given . + /// A function used to filter the library. /// - /// JavaScriptLibraryController.Instance.GetLibraries(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)) + /// JavaScriptLibraryController.Instance.GetLibraries(l => string.Equals(l.LibraryName, "Knockout", StringComparison.OrdinalIgnoreCase)). /// - /// A sequence of instances + /// A sequence of instances. public IEnumerable GetLibraries(Func predicate) { - return GetLibraries().Where(predicate); + return this.GetLibraries().Where(predicate); } - /// Gets all of the instances - /// A sequence of instances + /// Gets all of the instances. + /// A sequence of instances. public IEnumerable GetLibraries() - { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.JavaScriptLibrariesCacheKey, - DataCache.JavaScriptLibrariesCacheTimeout, - DataCache.JavaScriptLibrariesCachePriority), - c => CBO.FillCollection(DataProvider.Instance().ExecuteReader("GetJavaScriptLibraries"))); + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.JavaScriptLibrariesCacheKey, + DataCache.JavaScriptLibrariesCacheTimeout, + DataCache.JavaScriptLibrariesCachePriority), + c => CBO.FillCollection(DataProvider.Instance().ExecuteReader("GetJavaScriptLibraries"))); } - /// Save a library to the database - /// Library to be saved + /// Save a library to the database. + /// Library to be saved. public void SaveLibrary(JavaScriptLibrary library) { - library.JavaScriptLibraryID = DataProvider.Instance().ExecuteScalar("SaveJavaScriptLibrary", - library.JavaScriptLibraryID, - library.PackageID, - library.LibraryName, - library.Version.ToString(3), - library.FileName, - library.ObjectName, - library.PreferredScriptLocation, - library.CDNPath); - ClearCache(); - } - - #endregion + library.JavaScriptLibraryID = DataProvider.Instance().ExecuteScalar( + "SaveJavaScriptLibrary", + library.JavaScriptLibraryID, + library.PackageID, + library.LibraryName, + library.Version.ToString(3), + library.FileName, + library.ObjectName, + library.PreferredScriptLocation, + library.CDNPath); + this.ClearCache(); + } } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/ScriptLocation.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/ScriptLocation.cs index f0599810ec4..825c0c25e32 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/ScriptLocation.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/ScriptLocation.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.JavaScriptLibraries { /// - /// determine whereabouts in the page the script (and fallback script when CDN is enabled) is emitted + /// determine whereabouts in the page the script (and fallback script when CDN is enabled) is emitted. /// public enum ScriptLocation { PageHead, BodyTop, - BodyBottom + BodyBottom, } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/SpecificVersion.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/SpecificVersion.cs index f8a6d5a7656..780c2e36345 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/SpecificVersion.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/SpecificVersion.cs @@ -1,20 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.JavaScriptLibraries { /// - /// determine which version of a script is to be used + /// determine which version of a script is to be used. /// public enum SpecificVersion { /// The most recent version Latest, + /// Match the major version LatestMajor, + /// Match the major and minor versions LatestMinor, + /// Match version exactly Exact, } diff --git a/DNN Platform/Library/Framework/PageBase.cs b/DNN Platform/Library/Framework/PageBase.cs index d0e844037f8..cdc6719d6ae 100644 --- a/DNN Platform/Library/Framework/PageBase.cs +++ b/DNN Platform/Library/Framework/PageBase.cs @@ -1,138 +1,120 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Globalization; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System; + using System.Collections; + using System.Collections.Specialized; + using System.Globalization; + using System.Reflection; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Client.ClientResourceManagement; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Framework /// Project: DotNetNuke /// Class: PageBase /// ----------------------------------------------------------------------------- /// - /// PageBase provides a custom DotNetNuke base class for pages + /// PageBase provides a custom DotNetNuke base class for pages. /// /// ----------------------------------------------------------------------------- public abstract class PageBase : Page { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (PageBase)); - private readonly ILog _tracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); - private const string LinkItemPattern = "<(a|link|img|script|input|form|object).[^>]*(href|src|action)=(\\\"|'|)(.[^\\\"']*)(\\\"|'|)[^>]*>"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PageBase)); private static readonly Regex LinkItemMatchRegex = new Regex(LinkItemPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly ILog _tracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); - private PageStatePersister _persister; - #region Private Members - + private PageStatePersister _persister; private readonly NameValueCollection _htmlAttributes = new NameValueCollection(); private readonly ArrayList _localizedControls; private CultureInfo _pageCulture; - private string _localResourceFile; - - #endregion - - #region Constructors - + private string _localResourceFile; + /// ----------------------------------------------------------------------------- - /// - /// Creates the Page + /// + /// Initializes a new instance of the class. + /// Creates the Page. /// /// ----------------------------------------------------------------------------- protected PageBase() { - _localizedControls = new ArrayList(); + this._localizedControls = new ArrayList(); + } + + public PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } } - #endregion - - #region Protected Properties - + public NameValueCollection HtmlAttributes + { + get + { + return this._htmlAttributes; + } + } + /// ----------------------------------------------------------------------------- /// - /// PageStatePersister returns an instance of the class that will be used to persist the Page State + /// Gets pageStatePersister returns an instance of the class that will be used to persist the Page State. /// - /// A System.Web.UI.PageStatePersister + /// A System.Web.UI.PageStatePersister. /// ----------------------------------------------------------------------------- protected override PageStatePersister PageStatePersister { get { - //Set ViewState Persister to default (as defined in Base Class) - if (_persister == null) + // Set ViewState Persister to default (as defined in Base Class) + if (this._persister == null) { - _persister = base.PageStatePersister; + this._persister = base.PageStatePersister; if (Globals.Status == Globals.UpgradeStatus.None) { switch (Host.PageStatePersister) { case "M": - _persister = new CachePageStatePersister(this); + this._persister = new CachePageStatePersister(this); break; case "D": - _persister = new DiskPageStatePersister(this); + this._persister = new DiskPageStatePersister(this); break; } } } - return _persister; + return this._persister; } - } - - #endregion - - #region Public Properties - - public PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - - public NameValueCollection HtmlAttributes - { - get - { - return _htmlAttributes; - } - } + } public CultureInfo PageCulture { get { - return _pageCulture ?? (_pageCulture = Localization.GetPageLocale(PortalSettings)); + return this._pageCulture ?? (this._pageCulture = Localization.GetPageLocale(this.PortalSettings)); } } @@ -141,114 +123,285 @@ public string LocalResourceFile get { string fileRoot; - var page = Request.ServerVariables["SCRIPT_NAME"].Split('/'); - if (String.IsNullOrEmpty(_localResourceFile)) + var page = this.Request.ServerVariables["SCRIPT_NAME"].Split('/'); + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = string.Concat(TemplateSourceDirectory, "/", Localization.LocalResourceDirectory, "/", page[page.GetUpperBound(0)], ".resx"); + fileRoot = string.Concat(this.TemplateSourceDirectory, "/", Localization.LocalResourceDirectory, "/", page[page.GetUpperBound(0)], ".resx"); } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } } - public string CanonicalLinkUrl { get; set; } - - /// - /// Indicate whether http headers has been sent to client. - /// - public bool HeaderIsWritten { get; internal set; } + public string CanonicalLinkUrl { get; set; } - #endregion - - #region Private Methods + /// + /// Gets a value indicating whether indicate whether http headers has been sent to client. + /// + public bool HeaderIsWritten { get; internal set; } - private string GetErrorUrl(string url, Exception exc, bool hideContent = true) + /// + /// RemoveKeyAttribute remove the key attribute from the control. If this isn't done, then the HTML output will have + /// a bad attribute on it which could cause some older browsers problems. + /// + /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. + public static void RemoveKeyAttribute(ArrayList affectedControls) { - if (Request.QueryString["error"] != null) + if (affectedControls == null) { - url += string.Concat((url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&"), "error=terminate"); + return; } - else + + int i; + for (i = 0; i <= affectedControls.Count - 1; i++) { - url += string.Concat( - (url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&"), - "error=", - (exc == null || UserController.Instance.GetCurrentUserInfo() == null || !UserController.Instance.GetCurrentUserInfo().IsSuperUser ? "An unexpected error has occurred" : Server.UrlEncode(exc.Message)) - ); - if (!Globals.IsAdminControl() && hideContent) + var ac = (AttributeCollection)affectedControls[i]; + ac.Remove(Localization.KeyName); + ac.Remove(IconController.IconKeyName); + ac.Remove(IconController.IconSizeName); + ac.Remove(IconController.IconStyleName); + } + } + + /// + /// GetControlAttribute looks a the type of control and does it's best to find an AttributeCollection. + /// + /// Control to find the AttributeCollection on. + /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. + /// Name of key to search for. + /// A string containing the key for the specified control or null if a key attribute wasn't found. + internal static string GetControlAttribute(Control control, ArrayList affectedControls, string attributeName) + { + AttributeCollection attributeCollection = null; + string key = null; + if (!(control is LiteralControl)) + { + var webControl = control as WebControl; + if (webControl != null) { - url += "&content=0"; + attributeCollection = webControl.Attributes; + key = attributeCollection[attributeName]; + } + else + { + var htmlControl = control as HtmlControl; + if (htmlControl != null) + { + attributeCollection = htmlControl.Attributes; + key = attributeCollection[attributeName]; + } + else + { + var userControl = control as UserControl; + if (userControl != null) + { + attributeCollection = userControl.Attributes; + key = attributeCollection[attributeName]; + } + else + { + var controlType = control.GetType(); + var attributeProperty = controlType.GetProperty("Attributes", typeof(AttributeCollection)); + if (attributeProperty != null) + { + attributeCollection = (AttributeCollection)attributeProperty.GetValue(control, null); + key = attributeCollection[attributeName]; + } + } + } } } - - return url; + + if (key != null && affectedControls != null) + { + affectedControls.Add(attributeCollection); + } + + return key; } - private bool IsViewStateFailure(Exception e) + /// + /// ProcessControl peforms the high level localization for a single control and optionally it's children. + /// + /// Control to find the AttributeCollection on. + /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. + /// If true, causes this method to process children of this controls. + /// Root Resource File. + internal void ProcessControl(Control control, ArrayList affectedControls, bool includeChildren, string resourceFileRoot) { - return !User.Identity.IsAuthenticated && e != null && e.InnerException is ViewStateException; - } + if (!control.Visible) + { + return; + } + + // Perform the substitution if a key was found + var key = GetControlAttribute(control, affectedControls, Localization.KeyName); + if (!string.IsNullOrEmpty(key)) + { + // Translation starts here .... + var value = Localization.GetString(key, resourceFileRoot); + this.LocalizeControl(control, value); + } - private void IterateControls(ControlCollection controls, ArrayList affectedControls, string resourceFileRoot) - { - foreach (Control c in controls) + // Translate listcontrol items here + var listControl = control as ListControl; + if (listControl != null) { - ProcessControl(c, affectedControls, true, resourceFileRoot); - LogDnnTrace("PageBase.IterateControls","Info", $"ControlId: {c.ID}"); + for (var i = 0; i <= listControl.Items.Count - 1; i++) + { + var attributeCollection = listControl.Items[i].Attributes; + key = attributeCollection[Localization.KeyName]; + if (key != null) + { + var value = Localization.GetString(key, resourceFileRoot); + if (!string.IsNullOrEmpty(value)) + { + listControl.Items[i].Text = value; + } + } + + if (key != null && affectedControls != null) + { + affectedControls.Add(attributeCollection); + } + } } - } + + // UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl + // Manual Override to ResolveUrl + var image = control as Image; + if (image != null) + { + if (image.ImageUrl.IndexOf("~", StringComparison.Ordinal) != -1) + { + image.ImageUrl = this.Page.ResolveUrl(image.ImageUrl); + } - private void LogDnnTrace(string origin, string action, string message) - { - var tabId = -1; - if (PortalSettings?.ActiveTab != null) + // Check for IconKey + if (string.IsNullOrEmpty(image.ImageUrl)) + { + var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName); + var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName); + var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName); + image.ImageUrl = IconController.IconURL(iconKey, iconSize, iconStyle); + } + } + + // UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl + // Manual Override to ResolveUrl + var htmlImage = control as HtmlImage; + if (htmlImage != null) { - tabId = PortalSettings.ActiveTab.TabID; + if (htmlImage.Src.IndexOf("~", StringComparison.Ordinal) != -1) + { + htmlImage.Src = this.Page.ResolveUrl(htmlImage.Src); + } + + // Check for IconKey + if (string.IsNullOrEmpty(htmlImage.Src)) + { + var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName); + var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName); + var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName); + htmlImage.Src = IconController.IconURL(iconKey, iconSize, iconStyle); + } } - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"{origin} {action} (TabId:{tabId},{message})"); - } - #endregion + // UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl + // Manual Override to ResolveUrl + var ctrl = control as HyperLink; + if (ctrl != null) + { + if (ctrl.NavigateUrl.IndexOf("~", StringComparison.Ordinal) != -1) + { + ctrl.NavigateUrl = this.Page.ResolveUrl(ctrl.NavigateUrl); + } + + if (ctrl.ImageUrl.IndexOf("~", StringComparison.Ordinal) != -1) + { + ctrl.ImageUrl = this.Page.ResolveUrl(ctrl.ImageUrl); + } - #region Protected Methods + // Check for IconKey + if (string.IsNullOrEmpty(ctrl.ImageUrl)) + { + var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName); + var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName); + var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName); + ctrl.ImageUrl = IconController.IconURL(iconKey, iconSize, iconStyle); + } + } + + // Process child controls + if (!includeChildren || !control.HasControls()) + { + return; + } + + var objModuleControl = control as IModuleControl; + if (objModuleControl == null) + { + // Cache results from reflection calls for performance + var pi = control.GetType().GetProperty("LocalResourceFile"); + if (pi != null) + { + // Attempt to get property value + var pv = pi.GetValue(control, null); + // If controls has a LocalResourceFile property use this, otherwise pass the resource file root + this.IterateControls(control.Controls, affectedControls, pv == null ? resourceFileRoot : pv.ToString()); + } + else + { + // Pass Resource File Root through + this.IterateControls(control.Controls, affectedControls, resourceFileRoot); + } + } + else + { + // Get Resource File Root from Controls LocalResourceFile Property + this.IterateControls(control.Controls, affectedControls, objModuleControl.LocalResourceFile); + } + } + protected virtual void RegisterAjaxScript() { if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) { - ServicesFrameworkInternal.Instance.RegisterAjaxScript(Page); + ServicesFrameworkInternal.Instance.RegisterAjaxScript(this.Page); } } protected override void OnError(EventArgs e) { base.OnError(e); - Exception exc = Server.GetLastError(); + Exception exc = this.Server.GetLastError(); Logger.Fatal("An error has occurred while loading page.", exc); string strURL = Globals.ApplicationURL(); - if (exc is HttpException && !IsViewStateFailure(exc)) + if (exc is HttpException && !this.IsViewStateFailure(exc)) { try { - //if the exception's status code set to 404, we need display 404 page if defined or show no found info. + // if the exception's status code set to 404, we need display 404 page if defined or show no found info. var statusCode = (exc as HttpException).GetHttpCode(); if (statusCode == 404) { - UrlUtils.Handle404Exception(Response, PortalSettings); + UrlUtils.Handle404Exception(this.Response, this.PortalSettings); } - if (PortalSettings?.ErrorPage500 != -1) + if (this.PortalSettings?.ErrorPage500 != -1) { - var url = GetErrorUrl(string.Concat("~/Default.aspx?tabid=", PortalSettings.ErrorPage500), exc, + var url = this.GetErrorUrl(string.Concat("~/Default.aspx?tabid=", this.PortalSettings.ErrorPage500), exc, false); HttpContext.Current.Response.Redirect(url); } @@ -262,20 +415,69 @@ protected override void OnError(EventArgs e) { HttpContext.Current.Response.Clear(); var errorMessage = HttpUtility.UrlEncode(Localization.GetString("NoSitesForThisInstallation.Error", Localization.GlobalResourceFile)); - HttpContext.Current.Server.Transfer("~/ErrorPage.aspx?status=503&error="+errorMessage); + HttpContext.Current.Server.Transfer("~/ErrorPage.aspx?status=503&error=" + errorMessage); } } - strURL = GetErrorUrl(strURL, exc); + strURL = this.GetErrorUrl(strURL, exc); Exceptions.ProcessPageLoadException(exc, strURL); } + + private string GetErrorUrl(string url, Exception exc, bool hideContent = true) + { + if (this.Request.QueryString["error"] != null) + { + url += string.Concat(url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&", "error=terminate"); + } + else + { + url += string.Concat( + url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&", + "error=", + exc == null || UserController.Instance.GetCurrentUserInfo() == null || !UserController.Instance.GetCurrentUserInfo().IsSuperUser ? "An unexpected error has occurred" : this.Server.UrlEncode(exc.Message)); + if (!Globals.IsAdminControl() && hideContent) + { + url += "&content=0"; + } + } + + return url; + } + + private bool IsViewStateFailure(Exception e) + { + return !this.User.Identity.IsAuthenticated && e != null && e.InnerException is ViewStateException; + } + + private void IterateControls(ControlCollection controls, ArrayList affectedControls, string resourceFileRoot) + { + foreach (Control c in controls) + { + this.ProcessControl(c, affectedControls, true, resourceFileRoot); + this.LogDnnTrace("PageBase.IterateControls", "Info", $"ControlId: {c.ID}"); + } + } + + private void LogDnnTrace(string origin, string action, string message) + { + var tabId = -1; + if (this.PortalSettings?.ActiveTab != null) + { + tabId = this.PortalSettings.ActiveTab.TabID; + } + + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"{origin} {action} (TabId:{tabId},{message})"); + } + } protected override void OnInit(EventArgs e) { var isInstallPage = HttpContext.Current.Request.Url.LocalPath.ToLowerInvariant().Contains("installwizard.aspx"); if (!isInstallPage) { - Localization.SetThreadCultures(PageCulture, PortalSettings); + Localization.SetThreadCultures(this.PageCulture, this.PortalSettings); } if (ScriptManager.GetCurrent(this) == null) @@ -296,111 +498,53 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - //Because we have delayed registration of the jQuery script, - //Modules can override the standard behavior by including their own script on the page. - //The module must register the script with the "jQuery" key and should notify user - //of potential version conflicts with core jQuery support. - //if (jQuery.IsRequested) - //{ + // Because we have delayed registration of the jQuery script, + // Modules can override the standard behavior by including their own script on the page. + // The module must register the script with the "jQuery" key and should notify user + // of potential version conflicts with core jQuery support. + // if (jQuery.IsRequested) + // { // jQuery.RegisterJQuery(Page); - //} - //if (jQuery.IsUIRequested) - //{ + // } + // if (jQuery.IsUIRequested) + // { // jQuery.RegisterJQueryUI(Page); - //} - //if (jQuery.AreDnnPluginsRequested) - //{ + // } + // if (jQuery.AreDnnPluginsRequested) + // { // jQuery.RegisterDnnJQueryPlugins(Page); - //} - //if (jQuery.IsHoverIntentRequested) - //{ + // } + // if (jQuery.IsHoverIntentRequested) + // { // jQuery.RegisterHoverIntent(Page); - //} - + // } if (ServicesFrameworkInternal.Instance.IsAjaxAntiForgerySupportRequired) { - ServicesFrameworkInternal.Instance.RegisterAjaxAntiForgery(Page); + ServicesFrameworkInternal.Instance.RegisterAjaxAntiForgery(this.Page); } - RegisterAjaxScript(); + this.RegisterAjaxScript(); } protected override void Render(HtmlTextWriter writer) { - LogDnnTrace("PageBase.Render", "Start", $"{Page.Request.Url.AbsoluteUri}"); + this.LogDnnTrace("PageBase.Render", "Start", $"{this.Page.Request.Url.AbsoluteUri}"); - IterateControls(Controls, _localizedControls, LocalResourceFile); - RemoveKeyAttribute(_localizedControls); + this.IterateControls(this.Controls, this._localizedControls, this.LocalResourceFile); + RemoveKeyAttribute(this._localizedControls); AJAX.RemoveScriptManager(this); base.Render(writer); - LogDnnTrace("PageBase.Render", "End", $"{Page.Request.Url.AbsoluteUri}"); - } - - - #endregion - - #region Public Methods - - /// - /// GetControlAttribute looks a the type of control and does it's best to find an AttributeCollection. - /// - /// Control to find the AttributeCollection on - /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. - /// Name of key to search for. - /// A string containing the key for the specified control or null if a key attribute wasn't found - internal static string GetControlAttribute(Control control, ArrayList affectedControls, string attributeName) - { - AttributeCollection attributeCollection = null; - string key = null; - if (!(control is LiteralControl)) - { - var webControl = control as WebControl; - if (webControl != null) - { - attributeCollection = webControl.Attributes; - key = attributeCollection[attributeName]; - } - else - { - var htmlControl = control as HtmlControl; - if (htmlControl != null) - { - attributeCollection = htmlControl.Attributes; - key = attributeCollection[attributeName]; - } - else - { - var userControl = control as UserControl; - if (userControl != null) - { - attributeCollection = userControl.Attributes; - key = attributeCollection[attributeName]; - } - else - { - var controlType = control.GetType(); - var attributeProperty = controlType.GetProperty("Attributes", typeof(AttributeCollection)); - if (attributeProperty != null) - { - attributeCollection = (AttributeCollection)attributeProperty.GetValue(control, null); - key = attributeCollection[attributeName]; - } - } - } - } - } - if (key != null && affectedControls != null) - { - affectedControls.Add(attributeCollection); - } - return key; - } + this.LogDnnTrace("PageBase.Render", "End", $"{this.Page.Request.Url.AbsoluteUri}"); + } private void LocalizeControl(Control control, string value) { - if (string.IsNullOrEmpty(value)) return; - + if (string.IsNullOrEmpty(value)) + { + return; + } + var validator = control as BaseValidator; if (validator != null) { @@ -422,16 +566,21 @@ private void LocalizeControl(Control control, string value) var imgMatches = LinkItemMatchRegex.Matches(value); foreach (Match match in imgMatches) { - if ((match.Groups[match.Groups.Count - 2].Value.IndexOf("~", StringComparison.Ordinal) == -1)) - continue; - var resolvedUrl = Page.ResolveUrl(match.Groups[match.Groups.Count - 2].Value); + if (match.Groups[match.Groups.Count - 2].Value.IndexOf("~", StringComparison.Ordinal) == -1) + { + continue; + } + + var resolvedUrl = this.Page.ResolveUrl(match.Groups[match.Groups.Count - 2].Value); value = value.Replace(match.Groups[match.Groups.Count - 2].Value, resolvedUrl); } + linkButton.Text = value; if (string.IsNullOrEmpty(linkButton.ToolTip)) { linkButton.ToolTip = value; } + return; } @@ -484,165 +633,5 @@ private void LocalizeControl(Control control, string value) textBox.ToolTip = value; } } - - /// - /// ProcessControl peforms the high level localization for a single control and optionally it's children. - /// - /// Control to find the AttributeCollection on - /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. - /// If true, causes this method to process children of this controls. - /// Root Resource File. - internal void ProcessControl(Control control, ArrayList affectedControls, bool includeChildren, string resourceFileRoot) - { - if (!control.Visible) return; - - //Perform the substitution if a key was found - var key = GetControlAttribute(control, affectedControls, Localization.KeyName); - if (!string.IsNullOrEmpty(key)) - { - //Translation starts here .... - var value = Localization.GetString(key, resourceFileRoot); - LocalizeControl(control, value); - } - - //Translate listcontrol items here - var listControl = control as ListControl; - if (listControl != null) - { - for (var i = 0; i <= listControl.Items.Count - 1; i++) - { - var attributeCollection = listControl.Items[i].Attributes; - key = attributeCollection[Localization.KeyName]; - if (key != null) - { - var value = Localization.GetString(key, resourceFileRoot); - if (!String.IsNullOrEmpty(value)) - { - listControl.Items[i].Text = value; - } - } - if (key != null && affectedControls != null) - { - affectedControls.Add(attributeCollection); - } - } - } - - - //UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl - //Manual Override to ResolveUrl - var image = control as Image; - if (image != null) - { - if (image.ImageUrl.IndexOf("~", StringComparison.Ordinal) != -1) - { - image.ImageUrl = Page.ResolveUrl(image.ImageUrl); - } - - //Check for IconKey - if (string.IsNullOrEmpty(image.ImageUrl)) - { - var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName); - var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName); - var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName); - image.ImageUrl = IconController.IconURL(iconKey, iconSize, iconStyle); - } - } - - //UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl - //Manual Override to ResolveUrl - var htmlImage = control as HtmlImage; - if (htmlImage != null) - { - if (htmlImage.Src.IndexOf("~", StringComparison.Ordinal) != -1) - { - htmlImage.Src = Page.ResolveUrl(htmlImage.Src); - } - - //Check for IconKey - if (string.IsNullOrEmpty(htmlImage.Src)) - { - var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName); - var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName); - var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName); - htmlImage.Src = IconController.IconURL(iconKey, iconSize, iconStyle); - } - } - - //UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl - //Manual Override to ResolveUrl - var ctrl = control as HyperLink; - if (ctrl != null) - { - if ((ctrl.NavigateUrl.IndexOf("~", StringComparison.Ordinal) != -1)) - { - ctrl.NavigateUrl = Page.ResolveUrl(ctrl.NavigateUrl); - } - if ((ctrl.ImageUrl.IndexOf("~", StringComparison.Ordinal) != -1)) - { - ctrl.ImageUrl = Page.ResolveUrl(ctrl.ImageUrl); - } - - //Check for IconKey - if (string.IsNullOrEmpty(ctrl.ImageUrl)) - { - var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName); - var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName); - var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName); - ctrl.ImageUrl = IconController.IconURL(iconKey, iconSize, iconStyle); - } - } - - //Process child controls - if (!includeChildren || !control.HasControls()) return; - var objModuleControl = control as IModuleControl; - if (objModuleControl == null) - { - //Cache results from reflection calls for performance - var pi = control.GetType().GetProperty("LocalResourceFile"); - if (pi != null) - { - //Attempt to get property value - var pv = pi.GetValue(control, null); - - //If controls has a LocalResourceFile property use this, otherwise pass the resource file root - IterateControls(control.Controls, affectedControls, pv == null ? resourceFileRoot : pv.ToString()); - } - else - { - //Pass Resource File Root through - IterateControls(control.Controls, affectedControls, resourceFileRoot); - } - } - else - { - //Get Resource File Root from Controls LocalResourceFile Property - IterateControls(control.Controls, affectedControls, objModuleControl.LocalResourceFile); - } - } - - /// - /// RemoveKeyAttribute remove the key attribute from the control. If this isn't done, then the HTML output will have - /// a bad attribute on it which could cause some older browsers problems. - /// - /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. - public static void RemoveKeyAttribute(ArrayList affectedControls) - { - if (affectedControls == null) - { - return; - } - int i; - for (i = 0; i <= affectedControls.Count - 1; i++) - { - var ac = (AttributeCollection)affectedControls[i]; - ac.Remove(Localization.KeyName); - ac.Remove(IconController.IconKeyName); - ac.Remove(IconController.IconSizeName); - ac.Remove(IconController.IconStyleName); - } - } - - #endregion } } diff --git a/DNN Platform/Library/Framework/Providers/Provider.cs b/DNN Platform/Library/Framework/Providers/Provider.cs index a8ec5d64247..6cfafbe5a09 100644 --- a/DNN Platform/Library/Framework/Providers/Provider.cs +++ b/DNN Platform/Library/Framework/Providers/Provider.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Specialized; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework.Providers { + using System.Collections.Specialized; + using System.Xml; + public class Provider { private readonly NameValueCollection _ProviderAttributes = new NameValueCollection(); @@ -19,18 +14,18 @@ public class Provider public Provider(XmlAttributeCollection Attributes) { - //Set the name of the provider - _ProviderName = Attributes["name"].Value; + // Set the name of the provider + this._ProviderName = Attributes["name"].Value; - //Set the type of the provider - _ProviderType = Attributes["type"].Value; + // Set the type of the provider + this._ProviderType = Attributes["type"].Value; - //Store all the attributes in the attributes bucket + // Store all the attributes in the attributes bucket foreach (XmlAttribute Attribute in Attributes) { if (Attribute.Name != "name" && Attribute.Name != "type") { - _ProviderAttributes.Add(Attribute.Name, Attribute.Value); + this._ProviderAttributes.Add(Attribute.Name, Attribute.Value); } } } @@ -39,7 +34,7 @@ public string Name { get { - return _ProviderName; + return this._ProviderName; } } @@ -47,7 +42,7 @@ public string Type { get { - return _ProviderType; + return this._ProviderType; } } @@ -55,7 +50,7 @@ public NameValueCollection Attributes { get { - return _ProviderAttributes; + return this._ProviderAttributes; } } } diff --git a/DNN Platform/Library/Framework/Providers/ProviderConfiguration.cs b/DNN Platform/Library/Framework/Providers/ProviderConfiguration.cs index be704e9da55..c055fd3dd04 100644 --- a/DNN Platform/Library/Framework/Providers/ProviderConfiguration.cs +++ b/DNN Platform/Library/Framework/Providers/ProviderConfiguration.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.Xml; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework.Providers { + using System.Collections; + using System.Xml; + + using DotNetNuke.Common.Utilities; + public class ProviderConfiguration { private readonly Hashtable _Providers = new Hashtable(); @@ -22,7 +17,7 @@ public string DefaultProvider { get { - return _DefaultProvider; + return this._DefaultProvider; } } @@ -30,28 +25,28 @@ public Hashtable Providers { get { - return _Providers; + return this._Providers; } } public static ProviderConfiguration GetProviderConfiguration(string strProvider) { - return (ProviderConfiguration) Config.GetSection("dotnetnuke/" + strProvider); + return (ProviderConfiguration)Config.GetSection("dotnetnuke/" + strProvider); } internal void LoadValuesFromConfigurationXml(XmlNode node) { XmlAttributeCollection attributeCollection = node.Attributes; - //Get the default provider - _DefaultProvider = attributeCollection["defaultProvider"].Value; + // Get the default provider + this._DefaultProvider = attributeCollection["defaultProvider"].Value; - //Read child nodes + // Read child nodes foreach (XmlNode child in node.ChildNodes) { if (child.Name == "providers") { - GetProviders(child); + this.GetProviders(child); } } } @@ -63,13 +58,13 @@ internal void GetProviders(XmlNode node) switch (Provider.Name) { case "add": - Providers.Add(Provider.Attributes["name"].Value, new Provider(Provider.Attributes)); + this.Providers.Add(Provider.Attributes["name"].Value, new Provider(Provider.Attributes)); break; case "remove": - Providers.Remove(Provider.Attributes["name"].Value); + this.Providers.Remove(Provider.Attributes["name"].Value); break; case "clear": - Providers.Clear(); + this.Providers.Clear(); break; } } diff --git a/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs b/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs index fbcab82c8be..582924b8790 100644 --- a/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs +++ b/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs @@ -1,29 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Configuration; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework.Providers { + using System; + using System.Configuration; + using System.Xml; + [Obsolete("This class is obsolete. It is no longer used to load provider configurations, as there are medium trust issues. Scheduled removal in v11.0.0.")] internal class ProviderConfigurationHandler : IConfigurationSectionHandler - { - #region IConfigurationSectionHandler Members - + { public virtual object Create(object parent, object context, XmlNode node) { var objProviderConfiguration = new ProviderConfiguration(); objProviderConfiguration.LoadValuesFromConfigurationXml(node); return objProviderConfiguration; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Framework/Reflection.cs b/DNN Platform/Library/Framework/Reflection.cs index 14896b75fee..d16e4a46cae 100644 --- a/DNN Platform/Library/Framework/Reflection.cs +++ b/DNN Platform/Library/Framework/Reflection.cs @@ -1,45 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Reflection; -using System.Web.Compilation; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System; + using System.Reflection; + using System.Web.Compilation; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Framework - /// Project : DotNetNuke - /// Class : Reflection + /// Project : DotNetNuke + /// Class : Reflection /// ----------------------------------------------------------------------------- /// - /// Library responsible for reflection + /// Library responsible for reflection. /// /// /// /// ----------------------------------------------------------------------------- public class Reflection { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Reflection)); - #region Public Shared Methods - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Reflection)); + /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of Object to create (data/navigation) - /// The created Object - /// Overload for creating an object from a Provider configured in web.config + /// The type of Object to create (data/navigation). + /// The created Object. + /// Overload for creating an object from a Provider configured in web.config. /// ----------------------------------------------------------------------------- public static object CreateObject(string ObjectProviderType) { @@ -48,62 +42,62 @@ public static object CreateObject(string ObjectProviderType) /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of Object to create (data/navigation) - /// Caching switch - /// The created Object - /// Overload for creating an object from a Provider configured in web.config + /// The type of Object to create (data/navigation). + /// Caching switch. + /// The created Object. + /// Overload for creating an object from a Provider configured in web.config. /// ----------------------------------------------------------------------------- public static object CreateObject(string ObjectProviderType, bool UseCache) { - return CreateObject(ObjectProviderType, "", "", "", UseCache); + return CreateObject(ObjectProviderType, string.Empty, string.Empty, string.Empty, UseCache); } /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of Object to create (data/navigation) + /// The type of Object to create (data/navigation). /// The namespace of the object to create. /// The assembly of the object to create. - /// The created Object - /// Overload for creating an object from a Provider including NameSpace and - /// AssemblyName ( this allows derived providers to share the same config ) + /// The created Object. + /// Overload for creating an object from a Provider including NameSpace and + /// AssemblyName ( this allows derived providers to share the same config ). /// ----------------------------------------------------------------------------- public static object CreateObject(string ObjectProviderType, string ObjectNamespace, string ObjectAssemblyName) { - return CreateObject(ObjectProviderType, "", ObjectNamespace, ObjectAssemblyName, true); + return CreateObject(ObjectProviderType, string.Empty, ObjectNamespace, ObjectAssemblyName, true); } /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of Object to create (data/navigation) + /// The type of Object to create (data/navigation). /// The namespace of the object to create. /// The assembly of the object to create. - /// Caching switch - /// The created Object - /// Overload for creating an object from a Provider including NameSpace and - /// AssemblyName ( this allows derived providers to share the same config ) + /// Caching switch. + /// The created Object. + /// Overload for creating an object from a Provider including NameSpace and + /// AssemblyName ( this allows derived providers to share the same config ). /// ----------------------------------------------------------------------------- public static object CreateObject(string ObjectProviderType, string ObjectNamespace, string ObjectAssemblyName, bool UseCache) { - return CreateObject(ObjectProviderType, "", ObjectNamespace, ObjectAssemblyName, UseCache); + return CreateObject(ObjectProviderType, string.Empty, ObjectNamespace, ObjectAssemblyName, UseCache); } /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of Object to create (data/navigation) - /// The name of the Provider + /// The type of Object to create (data/navigation). + /// The name of the Provider. /// The namespace of the object to create. /// The assembly of the object to create. - /// The created Object - /// Overload for creating an object from a Provider including NameSpace, - /// AssemblyName and ProviderName + /// The created Object. + /// Overload for creating an object from a Provider including NameSpace, + /// AssemblyName and ProviderName. /// ----------------------------------------------------------------------------- public static object CreateObject(string ObjectProviderType, string ObjectProviderName, string ObjectNamespace, string ObjectAssemblyName) { @@ -112,16 +106,16 @@ public static object CreateObject(string ObjectProviderType, string ObjectProvid /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of Object to create (data/navigation) - /// The name of the Provider + /// The type of Object to create (data/navigation). + /// The name of the Provider. /// The namespace of the object to create. /// The assembly of the object to create. - /// Caching switch - /// The created Object - /// Overload for creating an object from a Provider including NameSpace, - /// AssemblyName and ProviderName + /// Caching switch. + /// The created Object. + /// Overload for creating an object from a Provider including NameSpace, + /// AssemblyName and ProviderName. /// ----------------------------------------------------------------------------- public static object CreateObject(string ObjectProviderType, string ObjectProviderName, string ObjectNamespace, string ObjectAssemblyName, bool UseCache) { @@ -130,80 +124,81 @@ public static object CreateObject(string ObjectProviderType, string ObjectProvid /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of Object to create (data/navigation) - /// The name of the Provider + /// The type of Object to create (data/navigation). + /// The name of the Provider. /// The namespace of the object to create. /// The assembly of the object to create. - /// Caching switch + /// Caching switch. /// Whether append provider name as part of the assembly name. - /// The created Object - /// Overload for creating an object from a Provider including NameSpace, - /// AssemblyName and ProviderName + /// The created Object. + /// Overload for creating an object from a Provider including NameSpace, + /// AssemblyName and ProviderName. /// ----------------------------------------------------------------------------- public static object CreateObject(string ObjectProviderType, string ObjectProviderName, string ObjectNamespace, string ObjectAssemblyName, bool UseCache, bool fixAssemblyName) { - string TypeName = ""; + string TypeName = string.Empty; - //get the provider configuration based on the type + // get the provider configuration based on the type ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration(ObjectProviderType); - if (!String.IsNullOrEmpty(ObjectNamespace) && !String.IsNullOrEmpty(ObjectAssemblyName)) + if (!string.IsNullOrEmpty(ObjectNamespace) && !string.IsNullOrEmpty(ObjectAssemblyName)) { - //if both the Namespace and AssemblyName are provided then we will construct an "assembly qualified typename" - ie. "NameSpace.ClassName, AssemblyName" - if (String.IsNullOrEmpty(ObjectProviderName)) + // if both the Namespace and AssemblyName are provided then we will construct an "assembly qualified typename" - ie. "NameSpace.ClassName, AssemblyName" + if (string.IsNullOrEmpty(ObjectProviderName)) { - //dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) + // dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) TypeName = ObjectNamespace + "." + objProviderConfiguration.DefaultProvider + ", " + ObjectAssemblyName + (fixAssemblyName ? "." + objProviderConfiguration.DefaultProvider : string.Empty); } else { - //dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) + // dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) TypeName = ObjectNamespace + "." + ObjectProviderName + ", " + ObjectAssemblyName + (fixAssemblyName ? "." + ObjectProviderName : string.Empty); } } else { - //if only the Namespace is provided then we will construct an "full typename" - ie. "NameSpace.ClassName" - if (!String.IsNullOrEmpty(ObjectNamespace)) + // if only the Namespace is provided then we will construct an "full typename" - ie. "NameSpace.ClassName" + if (!string.IsNullOrEmpty(ObjectNamespace)) { - if (String.IsNullOrEmpty(ObjectProviderName)) + if (string.IsNullOrEmpty(ObjectProviderName)) { - //dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) + // dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) TypeName = ObjectNamespace + "." + objProviderConfiguration.DefaultProvider; } else { - //dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) + // dynamically create the typename from the constants ( this enables private assemblies to share the same configuration as the base provider ) TypeName = ObjectNamespace + "." + ObjectProviderName; } } else { - //if neither Namespace or AssemblyName are provided then we will get the typename from the default provider - if (String.IsNullOrEmpty(ObjectProviderName)) + // if neither Namespace or AssemblyName are provided then we will get the typename from the default provider + if (string.IsNullOrEmpty(ObjectProviderName)) { - //get the typename of the default Provider from web.config - TypeName = ((Provider) objProviderConfiguration.Providers[objProviderConfiguration.DefaultProvider]).Type; + // get the typename of the default Provider from web.config + TypeName = ((Provider)objProviderConfiguration.Providers[objProviderConfiguration.DefaultProvider]).Type; } else { - //get the typename of the specified ProviderName from web.config - TypeName = ((Provider) objProviderConfiguration.Providers[ObjectProviderName]).Type; + // get the typename of the specified ProviderName from web.config + TypeName = ((Provider)objProviderConfiguration.Providers[ObjectProviderName]).Type; } } } + return CreateObject(TypeName, TypeName, UseCache); } /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The fully qualified TypeName - /// The Cache Key - /// The created Object - /// Overload that takes a fully-qualified typename and a Cache Key + /// The fully qualified TypeName. + /// The Cache Key. + /// The created Object. + /// Overload that takes a fully-qualified typename and a Cache Key. /// ----------------------------------------------------------------------------- public static object CreateObject(string TypeName, string CacheKey) { @@ -212,13 +207,13 @@ public static object CreateObject(string TypeName, string CacheKey) /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The fully qualified TypeName - /// The Cache Key - /// Caching switch - /// The created Object - /// Overload that takes a fully-qualified typename and a Cache Key + /// The fully qualified TypeName. + /// The Cache Key. + /// Caching switch. + /// The created Object. + /// Overload that takes a fully-qualified typename and a Cache Key. /// ----------------------------------------------------------------------------- public static object CreateObject(string TypeName, string CacheKey, bool UseCache) { @@ -227,23 +222,23 @@ public static object CreateObject(string TypeName, string CacheKey, bool UseCach /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of object to create + /// The type of object to create. /// - /// Generic version + /// Generic version. /// ----------------------------------------------------------------------------- public static T CreateObject() { - //dynamically create the object + // dynamically create the object return Activator.CreateInstance(); } /// ----------------------------------------------------------------------------- /// - /// Creates an object + /// Creates an object. /// - /// The type of object to create + /// The type of object to create. /// /// ----------------------------------------------------------------------------- public static object CreateObject(Type type) @@ -253,12 +248,12 @@ public static object CreateObject(Type type) public static Type CreateType(string TypeName) { - return CreateType(TypeName, "", true, false); + return CreateType(TypeName, string.Empty, true, false); } public static Type CreateType(string TypeName, bool IgnoreErrors) { - return CreateType(TypeName, "", true, IgnoreErrors); + return CreateType(TypeName, string.Empty, true, IgnoreErrors); } public static Type CreateType(string TypeName, string CacheKey, bool UseCache) @@ -268,28 +263,29 @@ public static Type CreateType(string TypeName, string CacheKey, bool UseCache) public static Type CreateType(string TypeName, string CacheKey, bool UseCache, bool IgnoreErrors) { - if (String.IsNullOrEmpty(CacheKey)) + if (string.IsNullOrEmpty(CacheKey)) { CacheKey = TypeName; } + Type type = null; - //use the cache for performance + // use the cache for performance if (UseCache) { - type = (Type) DataCache.GetCache(CacheKey); + type = (Type)DataCache.GetCache(CacheKey); } - - //is the type in the cache? + + // is the type in the cache? if (type == null) { try { - //use reflection to get the type of the class + // use reflection to get the type of the class type = BuildManager.GetType(TypeName, true, true); if (UseCache) { - //insert the type into the cache + // insert the type into the cache DataCache.SetCache(CacheKey, type); } } @@ -297,10 +293,11 @@ public static Type CreateType(string TypeName, string CacheKey, bool UseCache, b { if (!IgnoreErrors) { - Logger.Error(TypeName, exc); ; + Logger.Error(TypeName, exc); } } } + return type; } @@ -308,7 +305,7 @@ public static object CreateInstance(Type Type) { if (Type != null) { - return Type.InvokeMember("", BindingFlags.CreateInstance, null, null, null, null); + return Type.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, null, null); } else { @@ -344,33 +341,31 @@ public static void InvokeMethod(Type Type, string PropertyName, object Target, o } } - //dynamically create a default Provider from a ProviderType - this method was used by the CachingProvider to avoid a circular dependency + // dynamically create a default Provider from a ProviderType - this method was used by the CachingProvider to avoid a circular dependency [Obsolete("This method has been deprecated. Please use CreateObject(ByVal ObjectProviderType As String, ByVal UseCache As Boolean) As Object. Scheduled removal in v11.0.0.")] internal static object CreateObjectNotCached(string ObjectProviderType) { - string TypeName = ""; + string TypeName = string.Empty; Type objType = null; - //get the provider configuration based on the type + // get the provider configuration based on the type ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration(ObjectProviderType); - //get the typename of the Base DataProvider from web.config - TypeName = ((Provider) objProviderConfiguration.Providers[objProviderConfiguration.DefaultProvider]).Type; + // get the typename of the Base DataProvider from web.config + TypeName = ((Provider)objProviderConfiguration.Providers[objProviderConfiguration.DefaultProvider]).Type; try { - //use reflection to get the type of the class + // use reflection to get the type of the class objType = BuildManager.GetType(TypeName, true, true); } catch (Exception exc) { - //could not load the type + // could not load the type Exceptions.LogException(exc); } - //dynamically create the object + // dynamically create the object return Activator.CreateInstance(objType); - } - - #endregion - } + } + } } diff --git a/DNN Platform/Library/Framework/Reflections/AssemblyWrapper.cs b/DNN Platform/Library/Framework/Reflections/AssemblyWrapper.cs index d429aa8782d..0de42185dfc 100644 --- a/DNN Platform/Library/Framework/Reflections/AssemblyWrapper.cs +++ b/DNN Platform/Library/Framework/Reflections/AssemblyWrapper.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Reflection; - -using DotNetNuke.Framework.Internal.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.Reflections { + using System; + using System.Reflection; + + using DotNetNuke.Framework.Internal.Reflection; + public class AssemblyWrapper : IAssembly { private readonly Assembly _assembly; public AssemblyWrapper(Assembly assembly) { - _assembly = assembly; + this._assembly = assembly; } public Type[] GetTypes() { - return _assembly.GetTypes(); + return this._assembly.GetTypes(); } } } diff --git a/DNN Platform/Library/Framework/Reflections/IAssembly.cs b/DNN Platform/Library/Framework/Reflections/IAssembly.cs index 169df2fcfa4..810f5785af6 100644 --- a/DNN Platform/Library/Framework/Reflections/IAssembly.cs +++ b/DNN Platform/Library/Framework/Reflections/IAssembly.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.Internal.Reflection { - //interface to allowing mocking of System.Reflection.Assembly + using System; + + // interface to allowing mocking of System.Reflection.Assembly public interface IAssembly { Type[] GetTypes(); diff --git a/DNN Platform/Library/Framework/Reflections/IAssemblyLocator.cs b/DNN Platform/Library/Framework/Reflections/IAssemblyLocator.cs index 9f9e56c92ae..8edd04208f8 100644 --- a/DNN Platform/Library/Framework/Reflections/IAssemblyLocator.cs +++ b/DNN Platform/Library/Framework/Reflections/IAssemblyLocator.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.Internal.Reflection { + using System.Collections.Generic; + public interface IAssemblyLocator { IEnumerable Assemblies { get; } diff --git a/DNN Platform/Library/Framework/Reflections/ITypeLocator.cs b/DNN Platform/Library/Framework/Reflections/ITypeLocator.cs index 5b7a64801ce..954ca9f52bc 100644 --- a/DNN Platform/Library/Framework/Reflections/ITypeLocator.cs +++ b/DNN Platform/Library/Framework/Reflections/ITypeLocator.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework.Reflections { + using System; + using System.Collections.Generic; + public interface ITypeLocator { IEnumerable GetAllMatchingTypes(Predicate predicate); diff --git a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs index 9e35deba7b7..7c953f2719e 100644 --- a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs +++ b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs @@ -1,31 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -using DotNetNuke.Framework.Internal.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ConvertPropertyToExpressionBody - namespace DotNetNuke.Framework.Reflections { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using DotNetNuke.Framework.Internal.Reflection; + public class TypeLocator : ITypeLocator, IAssemblyLocator { private IAssemblyLocator _assemblyLocator; + IEnumerable IAssemblyLocator.Assemblies + { + // this method is not readily testable as the assemblies in the current app domain + // will vary depending on the test runner and test configuration + get + { + return from assembly in AppDomain.CurrentDomain.GetAssemblies() + where this.CanScan(assembly) + select new AssemblyWrapper(assembly); + } + } + internal IAssemblyLocator AssemblyLocator { - get { return _assemblyLocator ?? (_assemblyLocator = this); } - set { _assemblyLocator = value; } + get { return this._assemblyLocator ?? (this._assemblyLocator = this); } + set { this._assemblyLocator = value; } } public IEnumerable GetAllMatchingTypes(Predicate predicate) { - foreach (var assembly in AssemblyLocator.Assemblies) + foreach (var assembly in this.AssemblyLocator.Assemblies) { Type[] types; try @@ -34,16 +45,16 @@ public IEnumerable GetAllMatchingTypes(Predicate predicate) } catch (ReflectionTypeLoadException ex) { - //some assemblies don't want to be reflected but they still - //expose types in the exception + // some assemblies don't want to be reflected but they still + // expose types in the exception types = ex.Types ?? new Type[0]; } foreach (var type in types) { - if(type != null) + if (type != null) { - if(predicate(type)) + if (predicate(type)) { yield return type; } @@ -86,7 +97,7 @@ private bool CanScan(Assembly assembly) "DotNetNuke.WebUtility", }; - //First eliminate by "class" + // First eliminate by "class" var assemblyName = assembly.FullName.ToLowerInvariant(); bool canScan = !(assemblyName.StartsWith("clientdependency.core") || assemblyName.StartsWith("countrylistbox") || assemblyName.StartsWith("icsharpcode") || assemblyName.StartsWith("fiftyone") @@ -94,12 +105,11 @@ private bool CanScan(Assembly assembly) || assemblyName.StartsWith("newtonsoft") || assemblyName.StartsWith("petapoco") || assemblyName.StartsWith("sharpziplib") || assemblyName.StartsWith("system") || assemblyName.StartsWith("telerik") || assemblyName.StartsWith("webformsmvp") - || assemblyName.StartsWith("webmatrix") || assemblyName.StartsWith("solpart") - ); + || assemblyName.StartsWith("webmatrix") || assemblyName.StartsWith("solpart")); if (canScan) { - //Next eliminate specific assemblies + // Next eliminate specific assemblies if (ignoreAssemblies.Any(ignoreAssembly => assemblyName == ignoreAssembly.ToLowerInvariant())) { canScan = false; @@ -108,17 +118,5 @@ private bool CanScan(Assembly assembly) return canScan; } - - IEnumerable IAssemblyLocator.Assemblies - { - //this method is not readily testable as the assemblies in the current app domain - //will vary depending on the test runner and test configuration - get - { - return (from assembly in AppDomain.CurrentDomain.GetAssemblies() - where CanScan(assembly) - select new AssemblyWrapper(assembly)); - } - } } } diff --git a/DNN Platform/Library/Framework/SecurityPolicy.cs b/DNN Platform/Library/Framework/SecurityPolicy.cs index 017ede1b039..d4e8828da8e 100644 --- a/DNN Platform/Library/Framework/SecurityPolicy.cs +++ b/DNN Platform/Library/Framework/SecurityPolicy.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Net; -using System.Security; -using System.Security.Permissions; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System; + using System.Net; + using System.Security; + using System.Security.Permissions; + using System.Web; + public class SecurityPolicy { public const string ReflectionPermission = "ReflectionPermission"; @@ -30,32 +25,48 @@ public static string Permissions { get { - string strPermissions = ""; + string strPermissions = string.Empty; if (HasReflectionPermission()) { strPermissions += ", " + ReflectionPermission; } + if (HasWebPermission()) { strPermissions += ", " + WebPermission; } + if (HasAspNetHostingPermission()) { strPermissions += ", " + AspNetHostingPermission; } - if (!String.IsNullOrEmpty(strPermissions)) + + if (!string.IsNullOrEmpty(strPermissions)) { strPermissions = strPermissions.Substring(2); } + return strPermissions; } } + public static bool HasAspNetHostingPermission() + { + GetPermissions(); + return m_AspNetHostingPermission; + } + + public static bool HasReflectionPermission() + { + GetPermissions(); + return m_ReflectionPermission; + } + private static void GetPermissions() { if (!m_Initialized) { - //test RelectionPermission + // test RelectionPermission CodeAccessPermission securityTest; try { @@ -65,11 +76,11 @@ private static void GetPermissions() } catch { - //code access security error + // code access security error m_ReflectionPermission = false; } - - //test WebPermission + + // test WebPermission try { securityTest = new WebPermission(PermissionState.Unrestricted); @@ -78,11 +89,11 @@ private static void GetPermissions() } catch { - //code access security error + // code access security error m_WebPermission = false; } - - //test WebHosting Permission (Full Trust) + + // test WebHosting Permission (Full Trust) try { securityTest = new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted); @@ -91,12 +102,13 @@ private static void GetPermissions() } catch { - //code access security error + // code access security error m_AspNetHostingPermission = false; } + m_Initialized = true; - //Test for Unmanaged Code permission + // Test for Unmanaged Code permission try { securityTest = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); @@ -110,18 +122,6 @@ private static void GetPermissions() } } - public static bool HasAspNetHostingPermission() - { - GetPermissions(); - return m_AspNetHostingPermission; - } - - public static bool HasReflectionPermission() - { - GetPermissions(); - return m_ReflectionPermission; - } - public static bool HasWebPermission() { GetPermissions(); @@ -137,11 +137,11 @@ public static bool HasUnManagedCodePermission() public static bool HasPermissions(string permissions, ref string permission) { bool _HasPermission = true; - if (!String.IsNullOrEmpty(permissions)) + if (!string.IsNullOrEmpty(permissions)) { foreach (string per in (permissions + ";").Split(Convert.ToChar(";"))) { - if (!String.IsNullOrEmpty(per.Trim())) + if (!string.IsNullOrEmpty(per.Trim())) { permission = per; switch (permission) @@ -151,29 +151,34 @@ public static bool HasPermissions(string permissions, ref string permission) { _HasPermission = false; } + break; case ReflectionPermission: if (HasReflectionPermission() == false) { _HasPermission = false; } + break; case UnManagedCodePermission: if (HasUnManagedCodePermission() == false) { _HasPermission = false; } + break; case WebPermission: if (HasWebPermission() == false) { _HasPermission = false; } + break; } } } } + return _HasPermission; } diff --git a/DNN Platform/Library/Framework/ServiceLocator.cs b/DNN Platform/Library/Framework/ServiceLocator.cs index 6be0281a44f..4e1e6fae109 100644 --- a/DNN Platform/Library/Framework/ServiceLocator.cs +++ b/DNN Platform/Library/Framework/ServiceLocator.cs @@ -1,47 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework { + using System; + /// - /// Provides a readily testable way to manage a Singleton + /// Provides a readily testable way to manage a Singleton. /// - /// The interface that the controller provides - /// The type of the controller itself, used to call the GetFactory override - public abstract class ServiceLocator where TSelf : ServiceLocator, new() - { -// ReSharper disable StaticFieldInGenericType -// ReSharper disable InconsistentNaming - private static Lazy _instance = new Lazy(InitInstance, true); -// ReSharper restore InconsistentNaming + /// The interface that the controller provides. + /// The type of the controller itself, used to call the GetFactory override. + public abstract class ServiceLocator + where TSelf : ServiceLocator, new() + { + // ReSharper disable StaticFieldInGenericType + // ReSharper disable InconsistentNaming + private static Lazy _instance = new Lazy(InitInstance, true); + + // ReSharper restore InconsistentNaming private static TContract _testableInstance; - private static bool _useTestable; -// ReSharper restore StaticFieldInGenericType - - protected static Func Factory { get; set; } - - private static TContract InitInstance() - { - if (Factory == null) - { - var controllerInstance = new TSelf(); - Factory = controllerInstance.GetFactory(); - } - - return Factory(); - } + private static bool _useTestable; /// - /// Returns a singleton of T + /// Gets a singleton of T. /// public static TContract Instance { get { - if(_useTestable) + if (_useTestable) { return _testableInstance; } @@ -49,11 +37,14 @@ public static TContract Instance return _instance.Value; } } + + // ReSharper restore StaticFieldInGenericType + protected static Func Factory { get; set; } /// - /// Registers an instance to use for the Singleton + /// Registers an instance to use for the Singleton. /// - /// Intended for unit testing purposes, not thread safe + /// Intended for unit testing purposes, not thread safe. /// public static void SetTestableInstance(TContract instance) { @@ -62,9 +53,9 @@ public static void SetTestableInstance(TContract instance) } /// - /// Clears the current instance, a new instance will be initialized when next requested + /// Clears the current instance, a new instance will be initialized when next requested. /// - /// Intended for unit testing purposes, not thread safe + /// Intended for unit testing purposes, not thread safe. public static void ClearInstance() { _useTestable = false; @@ -72,6 +63,17 @@ public static void ClearInstance() _instance = new Lazy(InitInstance, true); } + private static TContract InitInstance() + { + if (Factory == null) + { + var controllerInstance = new TSelf(); + Factory = controllerInstance.GetFactory(); + } + + return Factory(); + } + protected abstract Func GetFactory(); } } diff --git a/DNN Platform/Library/Framework/ServicesFramework.cs b/DNN Platform/Library/Framework/ServicesFramework.cs index ae38881b2e7..f68a1f7a429 100644 --- a/DNN Platform/Library/Framework/ServicesFramework.cs +++ b/DNN Platform/Library/Framework/ServicesFramework.cs @@ -1,38 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework { + using System; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + /// - /// Enables modules to support Services Framework features + /// Enables modules to support Services Framework features. /// public class ServicesFramework : ServiceLocator { - protected override Func GetFactory() - { - return () => new ServicesFrameworkImpl(); - } - public static string GetServiceFrameworkRoot() { var portalSettings = PortalSettings.Current; - if (portalSettings == null) return String.Empty; + if (portalSettings == null) + { + return string.Empty; + } + var path = portalSettings.PortalAlias.HTTPAlias; var index = path.IndexOf('/'); if (index > 0) { path = path.Substring(index); - if (!path.EndsWith("/")) path += "/"; + if (!path.EndsWith("/")) + { + path += "/"; + } } - else - path = "/"; - + else + { + path = "/"; + } + return path; } + + protected override Func GetFactory() + { + return () => new ServicesFrameworkImpl(); + } } } diff --git a/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs b/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs index e901890beb3..5513d244e9b 100644 --- a/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs +++ b/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs @@ -1,49 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Web.Helpers; -using System.Web.UI; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework { + using System; + using System.Globalization; + using System.Web.Helpers; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client.ClientResourceManagement; + internal class ServicesFrameworkImpl : IServicesFramework, IServiceFrameworkInternals { private const string AntiForgeryKey = "dnnAntiForgeryRequested"; private const string ScriptKey = "dnnSFAjaxScriptRequested"; - public void RequestAjaxAntiForgerySupport() + public bool IsAjaxAntiForgerySupportRequired { - RequestAjaxScriptSupport(); - SetKey(AntiForgeryKey); + get { return CheckKey(AntiForgeryKey); } } - public bool IsAjaxAntiForgerySupportRequired + public bool IsAjaxScriptSupportRequired { - get { return CheckKey(AntiForgeryKey); } + get { return CheckKey(ScriptKey); } + } + + public void RequestAjaxAntiForgerySupport() + { + this.RequestAjaxScriptSupport(); + SetKey(AntiForgeryKey); } public void RegisterAjaxAntiForgery(Page page) { var ctl = page.FindControl("ClientResourcesFormBottom"); - if(ctl != null) + if (ctl != null) { ctl.Controls.Add(new LiteralControl(AntiForgery.GetHtml().ToHtmlString())); } } - public bool IsAjaxScriptSupportRequired - { - get{ return CheckKey(ScriptKey); } - } - public void RequestAjaxScriptSupport() { JavaScript.RequestRegistration(CommonJs.jQuery); @@ -53,7 +54,7 @@ public void RequestAjaxScriptSupport() public void RegisterAjaxScript(Page page) { var path = ServicesFramework.GetServiceFrameworkRoot(); - if (String.IsNullOrEmpty(path)) + if (string.IsNullOrEmpty(path)) { return; } @@ -61,9 +62,9 @@ public void RegisterAjaxScript(Page page) JavaScript.RegisterClientReference(page, ClientAPI.ClientNamespaceReferences.dnn); ClientAPI.RegisterClientVariable(page, "sf_siteRoot", path, /*overwrite*/ true); ClientAPI.RegisterClientVariable(page, "sf_tabId", PortalSettings.Current.ActiveTab.TabID.ToString(CultureInfo.InvariantCulture), /*overwrite*/ true); - + string scriptPath; - if(HttpContextSource.Current.IsDebuggingEnabled) + if (HttpContextSource.Current.IsDebuggingEnabled) { scriptPath = "~/js/Debug/dnn.servicesframework.js"; } @@ -71,7 +72,7 @@ public void RegisterAjaxScript(Page page) { scriptPath = "~/js/dnn.servicesframework.js"; } - + ClientResourceManager.RegisterScript(page, scriptPath); } diff --git a/DNN Platform/Library/Framework/ServicesFrameworkInternal.cs b/DNN Platform/Library/Framework/ServicesFrameworkInternal.cs index 8008bd2bb0d..d5e20febdf6 100644 --- a/DNN Platform/Library/Framework/ServicesFrameworkInternal.cs +++ b/DNN Platform/Library/Framework/ServicesFrameworkInternal.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Framework { + using System; + internal class ServicesFrameworkInternal : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Framework/UserControlBase.cs b/DNN Platform/Library/Framework/UserControlBase.cs index c76e5724281..fecaa509d6e 100644 --- a/DNN Platform/Library/Framework/UserControlBase.cs +++ b/DNN Platform/Library/Framework/UserControlBase.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System.ComponentModel; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + /// ----------------------------------------------------------------------------- /// /// The UserControlBase class defines a custom base class inherited by all @@ -27,11 +22,12 @@ public bool IsHostMenu { get { - return Globals.IsHostTab(PortalSettings.ActiveTab.TabID); + return Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { get diff --git a/DNN Platform/Library/Framework/jQuery.cs b/DNN Platform/Library/Framework/jQuery.cs index fc6184ae084..51bceb5c3d0 100644 --- a/DNN Platform/Library/Framework/jQuery.cs +++ b/DNN Platform/Library/Framework/jQuery.cs @@ -1,44 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Caching; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; - -using DataCache = DotNetNuke.UI.Utilities.DataCache; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { + using System; + using System.IO; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Caching; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client.ClientResourceManagement; + + using DataCache = DotNetNuke.UI.Utilities.DataCache; + using Globals = DotNetNuke.Common.Globals; + #pragma warning disable 618 - public class jQuery + public class jQuery { - private const string jQueryDebugFile = "~/Resources/Shared/Scripts/jquery/jquery.js"; - private const string jQueryMinFile = "~/Resources/Shared/Scripts/jquery/jquery.min.js"; - private const string jQueryMigrateDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.js"; - private const string jQueryMigrateMinFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.min.js"; - private const string jQueryVersionKey = "jQueryVersionKey"; - private const string jQueryVersionMatch = "(?<=(jquery|core_version)\\s*[:=]\\s*\")(.*)(?=\")"; - /// - /// Returns the default URL for a hosted version of the jQuery script + /// Returns the default URL for a hosted version of the jQuery script. /// /// /// Google hosts versions of many popular javascript libraries on their CDN. @@ -46,21 +34,28 @@ public class jQuery /// cached in the users browser. /// public const string DefaultHostedUrl = "http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"; + + public const string DefaultUIHostedUrl = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"; + private const string jQueryDebugFile = "~/Resources/Shared/Scripts/jquery/jquery.js"; + private const string jQueryMinFile = "~/Resources/Shared/Scripts/jquery/jquery.min.js"; + private const string jQueryMigrateDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.js"; + private const string jQueryMigrateMinFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.min.js"; + private const string jQueryVersionKey = "jQueryVersionKey"; + private const string jQueryVersionMatch = "(?<=(jquery|core_version)\\s*[:=]\\s*\")(.*)(?=\")"; private const string jQueryUIDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.js"; private const string jQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js"; private const string jQueryUIVersionKey = "jQueryUIVersionKey"; private const string jQueryUIVersionMatch = "(?<=version:\\s\")(.*)(?=\")"; - public const string DefaultUIHostedUrl = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"; - - #region Public Properties - + /// /// Gets the HostSetting for the URL of the hosted version of the jQuery script. /// - /// + /// + /// The HostSetting for the URL of the hosted version of the jQuery script. + /// /// - /// This is a simple wrapper around the Host.jQueryUrl property + /// This is a simple wrapper around the Host.jQueryUrl property. [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string HostedUrl { @@ -68,39 +63,43 @@ public static string HostedUrl { if (Globals.Status != Globals.UpgradeStatus.None) { - return String.Empty; + return string.Empty; } return Host.jQueryUrl; } } - /// - /// Gets the HostSetting for the URL of the hosted version of the jQuery migrated script. - /// - /// - /// - /// This is a simple wrapper around the Host.jQueryUrl property + /// + /// Gets the HostSetting for the URL of the hosted version of the jQuery migrated script. + /// + /// + /// The HostSetting for the URL of the hosted version of the jQuery migrated script. + /// + /// + /// This is a simple wrapper around the Host.jQueryUrl property. [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string HostedMigrateUrl - { - get - { - if (Globals.Status != Globals.UpgradeStatus.None) - { - return String.Empty; - } - - return Host.jQueryMigrateUrl; - } - } + { + get + { + if (Globals.Status != Globals.UpgradeStatus.None) + { + return string.Empty; + } + + return Host.jQueryMigrateUrl; + } + } /// /// Gets the HostSetting for the URL of the hosted version of the jQuery UI script. /// - /// + /// + /// The HostSetting for the URL of the hosted version of the jQuery UI script. + /// /// - /// This is a simple wrapper around the Host.jQueryUIUrl property + /// This is a simple wrapper around the Host.jQueryUIUrl property. [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string HostedUIUrl { @@ -108,7 +107,7 @@ public static string HostedUIUrl { if (Globals.Status != Globals.UpgradeStatus.None) { - return String.Empty; + return string.Empty; } return Host.jQueryUIUrl; @@ -116,7 +115,7 @@ public static string HostedUIUrl } /// - /// Checks whether the jQuery core script file exists locally. + /// Gets a value indicating whether checks whether the jQuery core script file exists locally. /// /// /// This property checks for both the minified version and the full uncompressed version of jQuery. @@ -134,7 +133,7 @@ public static bool IsInstalled } /// - /// Checks whether the jQuery UI core script file exists locally. + /// Gets a value indicating whether checks whether the jQuery UI core script file exists locally. /// /// /// This property checks for both the minified version and the full uncompressed version of jQuery UI. @@ -150,6 +149,7 @@ public static bool IsUIInstalled return File.Exists(minFile) || File.Exists(dbgFile); } } + public static bool IsRequested { get @@ -183,11 +183,13 @@ public static bool IsHoverIntentRequested } /// - /// Gets the HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. + /// Gets a value indicating whether gets the HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. /// - /// + /// + /// The HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. + /// /// - /// This is a simple wrapper around the Host.jQueryDebug property + /// This is a simple wrapper around the Host.jQueryDebug property. [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool UseDebugScript { @@ -203,11 +205,13 @@ public static bool UseDebugScript } /// - /// Gets the HostSetting to determine if we should use a hosted version of the jQuery script. + /// Gets a value indicating whether gets the HostSetting to determine if we should use a hosted version of the jQuery script. /// - /// + /// + /// The HostSetting to determine if we should use a hosted version of the jQuery script. + /// /// - /// This is a simple wrapper around the Host.jQueryHosted property + /// This is a simple wrapper around the Host.jQueryHosted property. [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool UseHostedScript { @@ -223,9 +227,11 @@ public static bool UseHostedScript } /// - /// Gets the version string for the local jQuery script + /// Gets the version string for the local jQuery script. /// - /// + /// + /// The version string for the local jQuery script + /// /// /// /// This only evaluates the version in the full jQuery file and assumes that the minified script @@ -251,14 +257,17 @@ public static string Version ver = Localization.GetString("jQuery.NotInstalled.Text"); } } + return ver; } } /// - /// Gets the version string for the local jQuery UI script + /// Gets the version string for the local jQuery UI script. /// - /// + /// + /// The version string for the local jQuery UI script + /// /// /// /// This only evaluates the version in the full jQuery UI file and assumes that the minified script @@ -284,13 +293,23 @@ public static string UIVersion ver = Localization.GetString("jQueryUI.NotInstalled.Text"); } } + return ver; } + } + + [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + public static string JQueryFileMapPath(bool getMinFile) + { + return HttpContext.Current.Server.MapPath(JQueryFile(getMinFile)); } - #endregion - - #region Private Methods + [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + public static string JQueryUIFileMapPath(bool getMinFile) + { + return HttpContext.Current.Server.MapPath(JQueryUIFile(getMinFile)); + } + private static bool GetSettingAsBoolean(string key, bool defaultValue) { bool retValue = defaultValue; @@ -306,24 +325,9 @@ private static bool GetSettingAsBoolean(string key, bool defaultValue) { Exceptions.LogException(ex); } + return retValue; - } - - #endregion - - #region Public Methods - - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryFileMapPath(bool getMinFile) - { - return HttpContext.Current.Server.MapPath(JQueryFile(getMinFile)); - } - - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryUIFileMapPath(bool getMinFile) - { - return HttpContext.Current.Server.MapPath(JQueryUIFile(getMinFile)); - } + } [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string JQueryFile(bool getMinFile) @@ -333,19 +337,21 @@ public static string JQueryFile(bool getMinFile) { jfile = jQueryMinFile; } + return jfile; } [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string JQueryMigrateFile(bool getMinFile) - { - string jfile = jQueryMigrateDebugFile; - if (getMinFile) - { - jfile = jQueryMigrateMinFile; - } - return jfile; - } + { + string jfile = jQueryMigrateDebugFile; + if (getMinFile) + { + jfile = jQueryMigrateMinFile; + } + + return jfile; + } [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string JQueryUIFile(bool getMinFile) @@ -355,6 +361,7 @@ public static string JQueryUIFile(bool getMinFile) { jfile = jQueryUIMinFile; } + return jfile; } @@ -366,19 +373,21 @@ public static string GetJQueryScriptReference() { scriptsrc = JQueryFile(!UseDebugScript); } + return scriptsrc; } [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string GetJQueryMigrateScriptReference() - { - string scriptsrc = HostedMigrateUrl; - if (!UseHostedScript || string.IsNullOrEmpty(scriptsrc)) - { - scriptsrc = JQueryMigrateFile(!UseDebugScript); - } - return scriptsrc; - } + { + string scriptsrc = HostedMigrateUrl; + if (!UseHostedScript || string.IsNullOrEmpty(scriptsrc)) + { + scriptsrc = JQueryMigrateFile(!UseDebugScript); + } + + return scriptsrc; + } [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string GetJQueryUIScriptReference() @@ -388,38 +397,34 @@ public static string GetJQueryUIScriptReference() { scriptsrc = JQueryUIFile(!UseDebugScript); } + return scriptsrc; } + + /// + /// Active the page with keep alive, so that authentication will not expire. + /// + /// The page instance. + public static void KeepAlive(Page page) + { + var cookieTimeout = Config.GetAuthCookieTimeout(); + if (cookieTimeout <= 0 || page.ClientScript.IsClientScriptBlockRegistered("PageKeepAlive")) + { + return; + } - - - /// - /// Active the page with keep alive, so that authentication will not expire. - /// - /// The page instance. - public static void KeepAlive(Page page) - { - var cookieTimeout = Config.GetAuthCookieTimeout(); - if(cookieTimeout <= 0 || page.ClientScript.IsClientScriptBlockRegistered("PageKeepAlive")) - { - return; - } - - if(cookieTimeout > 5) - { - cookieTimeout = 5; // ping server in 5 minutes to make sure the server is not IDLE. - } + if (cookieTimeout > 5) + { + cookieTimeout = 5; // ping server in 5 minutes to make sure the server is not IDLE. + } + JavaScript.RequestRegistration(CommonJs.jQuery); - var seconds = (cookieTimeout*60 - 30)*1000; //ping server 30 seconds before cookie is time out. - var scriptBlock = string.Format("(function($){{setInterval(function(){{$.get(location.href)}}, {1});}}(jQuery));", Globals.ApplicationPath, seconds); - ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "PageKeepAlive", scriptBlock, true); - } - - #endregion - - #region Obsolete Members - + var seconds = ((cookieTimeout * 60) - 30) * 1000; // ping server 30 seconds before cookie is time out. + var scriptBlock = string.Format("(function($){{setInterval(function(){{$.get(location.href)}}, {1});}}(jQuery));", Globals.ApplicationPath, seconds); + ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "PageKeepAlive", scriptBlock, true); + } + [Obsolete("Obsoleted in 7.2.0 - registration occurs automatically during page load. Scheduled removal in v10.0.0.")] public static void RegisterJQuery(Page page) { @@ -451,13 +456,11 @@ public static void RegisterHoverIntent(Page page) public static void RegisterFileUpload(Page page) { JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); - } [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.jQuery);. Scheduled removal in v10.0.0.")] public static void RequestRegistration() { - JavaScript.RequestRegistration(CommonJs.jQuery); JavaScript.RequestRegistration(CommonJs.jQueryMigrate); } @@ -465,26 +468,20 @@ public static void RequestRegistration() [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.jQueryUI);. Scheduled removal in v10.0.0.")] public static void RequestUIRegistration() { - JavaScript.RequestRegistration(CommonJs.jQueryUI); } [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.DnnPlugins);. Scheduled removal in v10.0.0.")] public static void RequestDnnPluginsRegistration() { - JavaScript.RequestRegistration(CommonJs.DnnPlugins); } [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.HoverIntent);. Scheduled removal in v10.0.0.")] public static void RequestHoverIntentRegistration() { - JavaScript.RequestRegistration(CommonJs.HoverIntent); - } - - - #endregion - } + } + } #pragma warning restore 618 } diff --git a/DNN Platform/Library/Modules/HtmlEditorProvider.cs b/DNN Platform/Library/Modules/HtmlEditorProvider.cs index db55355a4a6..6042cba16e0 100644 --- a/DNN Platform/Library/Modules/HtmlEditorProvider.cs +++ b/DNN Platform/Library/Modules/HtmlEditorProvider.cs @@ -1,32 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.HTMLEditorProvider { + using System.Collections; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Framework; + public abstract class HtmlEditorProvider : UserControlBase { public abstract Control HtmlEditorControl { get; } + public abstract ArrayList AdditionalToolbars { get; set; } + public abstract string ControlID { get; set; } + public abstract string RootImageDirectory { get; set; } + public abstract string Text { get; set; } + public abstract Unit Width { get; set; } + public abstract Unit Height { get; set; } - //return the provider - public static HtmlEditorProvider Instance() + // return the provider + public static HtmlEditorProvider Instance() { return ComponentFactory.GetComponent(); } diff --git a/DNN Platform/Library/Modules/NavigationProvider.cs b/DNN Platform/Library/Modules/NavigationProvider.cs index e420c88c4f5..e64163d15da 100644 --- a/DNN Platform/Library/Modules/NavigationProvider.cs +++ b/DNN Platform/Library/Modules/NavigationProvider.cs @@ -1,85 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Web.UI; - -using DotNetNuke.Framework; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.NavigationProvider { + using System.Collections.Generic; + using System.Web.UI; + + using DotNetNuke.Framework; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.WebControls; + public abstract class NavigationProvider : UserControlBase - { - #region Delegates - + { public delegate void NodeClickEventHandler(NavigationEventArgs args); - public delegate void PopulateOnDemandEventHandler(NavigationEventArgs args); - - #endregion - - #region Alignment enum - + public delegate void PopulateOnDemandEventHandler(NavigationEventArgs args); + + public event NodeClickEventHandler NodeClick; + + public event PopulateOnDemandEventHandler PopulateOnDemand; + public enum Alignment { Left, Right, Center, - Justify - } - - #endregion - - #region HoverAction enum - + Justify, + } + public enum HoverAction { Expand, - None - } - - #endregion - - #region HoverDisplay enum - + None, + } + public enum HoverDisplay { Highlight, Outset, - None - } - - #endregion - - #region Orientation enum - + None, + } + public enum Orientation { Horizontal, - Vertical - } - - #endregion - - #region "Properties" - + Vertical, + } + public abstract Control NavigationControl { get; } + public abstract string ControlID { get; set; } + public abstract bool SupportsPopulateOnDemand { get; } public virtual string PathImage { get { - return ""; + return string.Empty; } + set { } @@ -89,8 +69,9 @@ public virtual string PathSystemImage { get { - return ""; + return string.Empty; } + set { } @@ -100,8 +81,9 @@ public virtual string PathSystemScript { get { - return ""; + return string.Empty; } + set { } @@ -111,8 +93,9 @@ public virtual string WorkImage { get { - return ""; + return string.Empty; } + set { } @@ -122,8 +105,9 @@ public virtual string IndicateChildImageSub { get { - return ""; + return string.Empty; } + set { } @@ -133,8 +117,9 @@ public virtual string IndicateChildImageRoot { get { - return ""; + return string.Empty; } + set { } @@ -144,8 +129,9 @@ public virtual string IndicateChildImageExpandedSub { get { - return ""; + return string.Empty; } + set { } @@ -155,8 +141,9 @@ public virtual string IndicateChildImageExpandedRoot { get { - return ""; + return string.Empty; } + set { } @@ -168,8 +155,9 @@ public virtual string CSSContainerRoot { get { - return ""; + return string.Empty; } + set { } @@ -179,8 +167,9 @@ public virtual string CSSContainerSub { get { - return ""; + return string.Empty; } + set { } @@ -190,8 +179,9 @@ public virtual string CSSNode { get { - return ""; + return string.Empty; } + set { } @@ -201,8 +191,9 @@ public virtual string CSSNodeRoot { get { - return ""; + return string.Empty; } + set { } @@ -212,8 +203,9 @@ public virtual string CSSIcon { get { - return ""; + return string.Empty; } + set { } @@ -223,8 +215,9 @@ public virtual string CSSNodeHover { get { - return ""; + return string.Empty; } + set { } @@ -234,8 +227,9 @@ public virtual string CSSNodeHoverSub { get { - return ""; + return string.Empty; } + set { } @@ -245,8 +239,9 @@ public virtual string CSSNodeHoverRoot { get { - return ""; + return string.Empty; } + set { } @@ -256,8 +251,9 @@ public virtual string CSSBreak { get { - return ""; + return string.Empty; } + set { } @@ -267,8 +263,9 @@ public virtual string CSSIndicateChildSub { get { - return ""; + return string.Empty; } + set { } @@ -278,8 +275,9 @@ public virtual string CSSIndicateChildRoot { get { - return ""; + return string.Empty; } + set { } @@ -289,8 +287,9 @@ public virtual string CSSBreadCrumbSub { get { - return ""; + return string.Empty; } + set { } @@ -300,8 +299,9 @@ public virtual string CSSBreadCrumbRoot { get { - return ""; + return string.Empty; } + set { } @@ -311,8 +311,9 @@ public virtual string CSSNodeSelectedSub { get { - return ""; + return string.Empty; } + set { } @@ -322,8 +323,9 @@ public virtual string CSSNodeSelectedRoot { get { - return ""; + return string.Empty; } + set { } @@ -333,8 +335,9 @@ public virtual string CSSSeparator { get { - return ""; + return string.Empty; } + set { } @@ -344,8 +347,9 @@ public virtual string CSSLeftSeparator { get { - return ""; + return string.Empty; } + set { } @@ -355,8 +359,9 @@ public virtual string CSSRightSeparator { get { - return ""; + return string.Empty; } + set { } @@ -366,8 +371,9 @@ public virtual string CSSLeftSeparatorSelection { get { - return ""; + return string.Empty; } + set { } @@ -377,8 +383,9 @@ public virtual string CSSRightSeparatorSelection { get { - return ""; + return string.Empty; } + set { } @@ -388,8 +395,9 @@ public virtual string CSSLeftSeparatorBreadCrumb { get { - return ""; + return string.Empty; } + set { } @@ -399,8 +407,9 @@ public virtual string CSSRightSeparatorBreadCrumb { get { - return ""; + return string.Empty; } + set { } @@ -410,8 +419,9 @@ public virtual string StyleBackColor { get { - return ""; + return string.Empty; } + set { } @@ -421,8 +431,9 @@ public virtual string StyleForeColor { get { - return ""; + return string.Empty; } + set { } @@ -432,8 +443,9 @@ public virtual string StyleHighlightColor { get { - return ""; + return string.Empty; } + set { } @@ -443,8 +455,9 @@ public virtual string StyleIconBackColor { get { - return ""; + return string.Empty; } + set { } @@ -454,8 +467,9 @@ public virtual string StyleSelectionBorderColor { get { - return ""; + return string.Empty; } + set { } @@ -465,8 +479,9 @@ public virtual string StyleSelectionColor { get { - return ""; + return string.Empty; } + set { } @@ -476,8 +491,9 @@ public virtual string StyleSelectionForeColor { get { - return ""; + return string.Empty; } + set { } @@ -489,6 +505,7 @@ public virtual decimal StyleControlHeight { return 25; } + set { } @@ -500,6 +517,7 @@ public virtual decimal StyleBorderWidth { return 0; } + set { } @@ -511,6 +529,7 @@ public virtual decimal StyleNodeHeight { return 25; } + set { } @@ -522,6 +541,7 @@ public virtual decimal StyleIconWidth { return 0; } + set { } @@ -531,8 +551,9 @@ public virtual string StyleFontNames { get { - return ""; + return string.Empty; } + set { } @@ -544,6 +565,7 @@ public virtual decimal StyleFontSize { return 0; } + set { } @@ -555,6 +577,7 @@ public virtual string StyleFontBold { return "False"; } + set { } @@ -564,8 +587,9 @@ public virtual string StyleRoot { get { - return ""; + return string.Empty; } + set { } @@ -575,8 +599,9 @@ public virtual string StyleSub { get { - return ""; + return string.Empty; } + set { } @@ -586,8 +611,9 @@ public virtual string EffectsStyle { get { - return ""; + return string.Empty; } + set { } @@ -599,6 +625,7 @@ public virtual string EffectsTransition { return "'"; } + set { } @@ -610,6 +637,7 @@ public virtual double EffectsDuration { return -1; } + set { } @@ -619,8 +647,9 @@ public virtual string EffectsShadowColor { get { - return ""; + return string.Empty; } + set { } @@ -630,8 +659,9 @@ public virtual string EffectsShadowDirection { get { - return ""; + return string.Empty; } + set { } @@ -643,6 +673,7 @@ public virtual int EffectsShadowStrength { return -1; } + set { } @@ -654,6 +685,7 @@ public virtual Orientation ControlOrientation { return Orientation.Horizontal; } + set { } @@ -665,6 +697,7 @@ public virtual Alignment ControlAlignment { return Alignment.Left; } + set { } @@ -676,6 +709,7 @@ public virtual string ForceDownLevel { return false.ToString(); } + set { } @@ -687,6 +721,7 @@ public virtual decimal MouseOutHideDelay { return -1; } + set { } @@ -698,6 +733,7 @@ public virtual HoverDisplay MouseOverDisplay { return HoverDisplay.Highlight; } + set { } @@ -709,6 +745,7 @@ public virtual HoverAction MouseOverAction { return HoverAction.Expand; } + set { } @@ -720,6 +757,7 @@ public virtual string ForceCrawlerDisplay { return "False"; } + set { } @@ -731,6 +769,7 @@ public virtual bool IndicateChildren { return true; } + set { } @@ -740,8 +779,9 @@ public virtual string SeparatorHTML { get { - return ""; + return string.Empty; } + set { } @@ -751,8 +791,9 @@ public virtual string SeparatorLeftHTML { get { - return ""; + return string.Empty; } + set { } @@ -762,8 +803,9 @@ public virtual string SeparatorRightHTML { get { - return ""; + return string.Empty; } + set { } @@ -773,8 +815,9 @@ public virtual string SeparatorLeftHTMLActive { get { - return ""; + return string.Empty; } + set { } @@ -784,8 +827,9 @@ public virtual string SeparatorRightHTMLActive { get { - return ""; + return string.Empty; } + set { } @@ -795,8 +839,9 @@ public virtual string SeparatorLeftHTMLBreadCrumb { get { - return ""; + return string.Empty; } + set { } @@ -806,8 +851,9 @@ public virtual string SeparatorRightHTMLBreadCrumb { get { - return ""; + return string.Empty; } + set { } @@ -817,8 +863,9 @@ public virtual string NodeLeftHTMLSub { get { - return ""; + return string.Empty; } + set { } @@ -828,8 +875,9 @@ public virtual string NodeLeftHTMLRoot { get { - return ""; + return string.Empty; } + set { } @@ -839,8 +887,9 @@ public virtual string NodeRightHTMLSub { get { - return ""; + return string.Empty; } + set { } @@ -850,8 +899,9 @@ public virtual string NodeRightHTMLRoot { get { - return ""; + return string.Empty; } + set { } @@ -861,8 +911,9 @@ public virtual string NodeLeftHTMLBreadCrumbSub { get { - return ""; + return string.Empty; } + set { } @@ -872,8 +923,9 @@ public virtual string NodeRightHTMLBreadCrumbSub { get { - return ""; + return string.Empty; } + set { } @@ -883,8 +935,9 @@ public virtual string NodeLeftHTMLBreadCrumbRoot { get { - return ""; + return string.Empty; } + set { } @@ -894,8 +947,9 @@ public virtual string NodeRightHTMLBreadCrumbRoot { get { - return ""; + return string.Empty; } + set { } @@ -907,6 +961,7 @@ public virtual bool PopulateNodesFromClient { return false; } + set { } @@ -918,22 +973,15 @@ public virtual List CustomAttributes { return null; } + set { } - } - - - #endregion - - #region "Methods" - - public event NodeClickEventHandler NodeClick; - public event PopulateOnDemandEventHandler PopulateOnDemand; + } public static NavigationProvider Instance(string FriendlyName) { - return (NavigationProvider) Reflection.CreateObject("navigationControl", FriendlyName, "", ""); + return (NavigationProvider)Reflection.CreateObject("navigationControl", FriendlyName, string.Empty, string.Empty); } public abstract void Initialize(); @@ -946,37 +994,35 @@ public virtual void ClearNodes() protected void RaiseEvent_NodeClick(DNNNode objNode) { - if (NodeClick != null) + if (this.NodeClick != null) { - NodeClick(new NavigationEventArgs(objNode.ID, objNode)); + this.NodeClick(new NavigationEventArgs(objNode.ID, objNode)); } } protected void RaiseEvent_NodeClick(string strID) { - if (NodeClick != null) + if (this.NodeClick != null) { - NodeClick(new NavigationEventArgs(strID, null)); + this.NodeClick(new NavigationEventArgs(strID, null)); } } protected void RaiseEvent_PopulateOnDemand(DNNNode objNode) { - if (PopulateOnDemand != null) + if (this.PopulateOnDemand != null) { - PopulateOnDemand(new NavigationEventArgs(objNode.ID, objNode)); + this.PopulateOnDemand(new NavigationEventArgs(objNode.ID, objNode)); } } protected void RaiseEvent_PopulateOnDemand(string strID) { - if (PopulateOnDemand != null) + if (this.PopulateOnDemand != null) { - PopulateOnDemand(new NavigationEventArgs(strID, null)); + this.PopulateOnDemand(new NavigationEventArgs(strID, null)); } - } - - #endregion + } } public class NavigationEventArgs @@ -986,8 +1032,8 @@ public class NavigationEventArgs public NavigationEventArgs(string strID, DNNNode objNode) { - ID = strID; - Node = objNode; + this.ID = strID; + this.Node = objNode; } } } diff --git a/DNN Platform/Library/Modules/SearchInput/SearchInputController.cs b/DNN Platform/Library/Modules/SearchInput/SearchInputController.cs index b61ca8f3bae..52677b01d00 100644 --- a/DNN Platform/Library/Modules/SearchInput/SearchInputController.cs +++ b/DNN Platform/Library/Modules/SearchInput/SearchInputController.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.SearchInput { + using System.Collections; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + public class SearchInputController { public ArrayList GetSearchResultModules(int PortalID) { - return CBO.FillCollection(DataProvider.Instance().GetSearchResultModules(PortalID), typeof (SearchResultsModuleInfo)); + return CBO.FillCollection(DataProvider.Instance().GetSearchResultModules(PortalID), typeof(SearchResultsModuleInfo)); } } } diff --git a/DNN Platform/Library/Modules/SearchInput/SearchResultsModuleInfo.cs b/DNN Platform/Library/Modules/SearchInput/SearchResultsModuleInfo.cs index 468adbde6ae..dfabe58102a 100644 --- a/DNN Platform/Library/Modules/SearchInput/SearchResultsModuleInfo.cs +++ b/DNN Platform/Library/Modules/SearchInput/SearchResultsModuleInfo.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.SearchInput { public class SearchResultsModuleInfo diff --git a/DNN Platform/Library/Obsolete/CBO.cs b/DNN Platform/Library/Obsolete/CBO.cs index 0f1b3518be5..e613be6f835 100644 --- a/DNN Platform/Library/Obsolete/CBO.cs +++ b/DNN Platform/Library/Obsolete/CBO.cs @@ -1,32 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; -using System.Xml.Serialization; - -using DotNetNuke.Entities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Utilities { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Text; + using System.Text.RegularExpressions; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Entities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Scheduling; + /// /// The CBO class generates objects. /// @@ -48,14 +43,16 @@ public static object CreateObject(Type objType, bool initialise) [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Obsolete in DotNetNuke 7.3. Use FillDictionary(string keyField, IDataReader dr). Scheduled removal in v10.0.0.")] - public static IDictionary FillDictionary(IDataReader dr) where TItem : IHydratable + public static IDictionary FillDictionary(IDataReader dr) + where TItem : IHydratable { return FillDictionaryFromReader("KeyID", dr, new Dictionary(), true); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Obsolete in DotNetNuke 7.3. Use FillDictionary(string keyField, IDataReader dr, IDictionary objDictionary). Scheduled removal in v10.0.0.")] - public static IDictionary FillDictionary(IDataReader dr, ref IDictionary objToFill) where TItem : IHydratable + public static IDictionary FillDictionary(IDataReader dr, ref IDictionary objToFill) + where TItem : IHydratable { return FillDictionaryFromReader("KeyID", dr, objToFill, true); } diff --git a/DNN Platform/Library/Obsolete/IModuleController.cs b/DNN Platform/Library/Obsolete/IModuleController.cs index 2353c82cf20..f0bcfce2802 100644 --- a/DNN Platform/Library/Obsolete/IModuleController.cs +++ b/DNN Platform/Library/Obsolete/IModuleController.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Internal { + using System; + using System.ComponentModel; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -20,25 +20,25 @@ public interface IModuleController /// /// The module ID. /// The tab ID. - /// module info + /// module info. ModuleInfo GetModule(int moduleId, int tabId); /// - /// Adds or updates a module's setting value + /// Adds or updates a module's setting value. /// - /// ID of the tabmodule, the setting belongs to - /// name of the setting property + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. /// value of the setting (String). - /// Empty SettingValue will remove the setting + /// Empty SettingValue will remove the setting. void UpdateModuleSetting(int moduleId, string settingName, string settingValue); /// - /// Adds or updates a tab module's setting value + /// Adds or updates a tab module's setting value. /// - /// ID of the tabmodule, the setting belongs to - /// name of the setting property + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. /// value of the setting (String). - /// Empty SettingValue will remove the setting + /// Empty SettingValue will remove the setting. void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue); } } diff --git a/DNN Platform/Library/Obsolete/IPortalAliasController.cs b/DNN Platform/Library/Obsolete/IPortalAliasController.cs index 6b72ee360ec..7b6652c4baa 100644 --- a/DNN Platform/Library/Obsolete/IPortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/IPortalAliasController.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -17,23 +17,23 @@ namespace DotNetNuke.Entities.Portals.Internal public interface IPortalAliasController { /// - /// Add a new Portal Alias + /// Add a new Portal Alias. /// - /// The portal alias to add - /// The Id of the newly added portal alias + /// The portal alias to add. + /// The Id of the newly added portal alias. int AddPortalAlias(PortalAliasInfo portalAlias); /// - /// Delete a Portal Alias + /// Delete a Portal Alias. /// - /// The portal alias to remove + /// The portal alias to remove. void DeletePortalAlias(PortalAliasInfo portalAlias); /// /// Gets the portal alias info. /// /// The portal alias. - /// Portal alias info + /// Portal alias info. PortalAliasInfo GetPortalAlias(string alias); /// @@ -44,9 +44,9 @@ public interface IPortalAliasController IEnumerable GetPortalAliasesByPortalId(int portalId); /// - /// Gets all the portal aliases defined + /// Gets all the portal aliases defined. /// - /// A dictionary keyed by the HTTP Alias + /// A dictionary keyed by the HTTP Alias. IDictionary GetPortalAliases(); /// diff --git a/DNN Platform/Library/Obsolete/IPortalSettings.cs b/DNN Platform/Library/Obsolete/IPortalSettings.cs index 845feae34bb..58d74ab8d98 100644 --- a/DNN Platform/Library/Obsolete/IPortalSettings.cs +++ b/DNN Platform/Library/Obsolete/IPortalSettings.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.ComponentModel; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalController.Instance.GetCurrentPortalSettings to get a mockable PortalSettings. Scheduled removal in v10.0.0.")] public interface IPortalSettings diff --git a/DNN Platform/Library/Obsolete/IRoleController.cs b/DNN Platform/Library/Obsolete/IRoleController.cs index 42bbf47269d..6820957adb1 100644 --- a/DNN Platform/Library/Obsolete/IRoleController.cs +++ b/DNN Platform/Library/Obsolete/IRoleController.cs @@ -1,117 +1,117 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use version in DotNetNuke.Security.Roles instead. Scheduled removal in v10.0.0.")] public interface IRoleController { /// ----------------------------------------------------------------------------- /// - /// Adds a role + /// Adds a role. /// - /// The Role to Add - /// The Id of the new role + /// The Role to Add. + /// The Id of the new role. /// ----------------------------------------------------------------------------- int AddRole(RoleInfo role); - /// - /// Adds a role - /// - /// The Role to Add - /// Add this role on all exist users if auto assignment is true. - /// The Id of the new role - int AddRole(RoleInfo role, bool addToExistUsers); + /// + /// Adds a role. + /// + /// The Role to Add. + /// Add this role on all exist users if auto assignment is true. + /// The Id of the new role. + int AddRole(RoleInfo role, bool addToExistUsers); /// ----------------------------------------------------------------------------- /// - /// Deletes a role + /// Deletes a role. /// - /// The Role to delete + /// The Role to delete. /// ----------------------------------------------------------------------------- void DeleteRole(RoleInfo role); /// ----------------------------------------------------------------------------- /// - /// Fetch a single role based on a predicate + /// Fetch a single role based on a predicate. /// - /// Id of the portal - /// The predicate (criteria) required - /// A RoleInfo object + /// Id of the portal. + /// The predicate (criteria) required. + /// A RoleInfo object. /// ----------------------------------------------------------------------------- RoleInfo GetRole(int portalId, Func predicate); /// ----------------------------------------------------------------------------- /// - /// Obtains a list of roles from the cache (or for the database if the cache has expired) + /// Obtains a list of roles from the cache (or for the database if the cache has expired). /// - /// The id of the portal - /// The list of roles + /// The id of the portal. + /// The list of roles. /// ----------------------------------------------------------------------------- IList GetRoles(int portalId); /// - /// get a list of roles based on progressive search + /// get a list of roles based on progressive search. /// - /// the id of the portal - /// the number of items to return - /// the text used to trim data + /// the id of the portal. + /// the number of items to return. + /// the text used to trim data. /// IList GetRolesBasicSearch(int portalID, int pageSize, string filterBy); /// ----------------------------------------------------------------------------- /// - /// Get the roles based on a predicate + /// Get the roles based on a predicate. /// - /// Id of the portal - /// The predicate (criteria) required - /// A List of RoleInfo objects + /// Id of the portal. + /// The predicate (criteria) required. + /// A List of RoleInfo objects. /// ----------------------------------------------------------------------------- IList GetRoles(int portalId, Func predicate); /// ----------------------------------------------------------------------------- /// - /// Gets the settings for a role + /// Gets the settings for a role. /// - /// Id of the role - /// A Dictionary of settings + /// Id of the role. + /// A Dictionary of settings. /// ----------------------------------------------------------------------------- IDictionary GetRoleSettings(int roleId); /// ----------------------------------------------------------------------------- /// - /// Persists a role to the Data Store + /// Persists a role to the Data Store. /// - /// The role to persist + /// The role to persist. /// ----------------------------------------------------------------------------- void UpdateRole(RoleInfo role); - /// - /// Persists a role to the Data Store - /// - /// The role to persist - /// Add this role on all exist users if auto assignment is true. - void UpdateRole(RoleInfo role, bool addToExistUsers); + /// + /// Persists a role to the Data Store. + /// + /// The role to persist. + /// Add this role on all exist users if auto assignment is true. + void UpdateRole(RoleInfo role, bool addToExistUsers); /// ----------------------------------------------------------------------------- /// - /// Update the role settings + /// Update the role settings. /// - /// The Role - /// A flag that indicates whether the cache should be cleared + /// The Role. + /// A flag that indicates whether the cache should be cleared. /// ----------------------------------------------------------------------------- void UpdateRoleSettings(RoleInfo role, bool clearCache); /// /// Clears Roles cache for the passed portal ID and for the default ID (-1) as well. /// - /// Id of the portal + /// Id of the portal. void ClearRoleCache(int portalId); } } diff --git a/DNN Platform/Library/Obsolete/ITabController.cs b/DNN Platform/Library/Obsolete/ITabController.cs index 758d1229af0..841bfc10f71 100644 --- a/DNN Platform/Library/Obsolete/ITabController.cs +++ b/DNN Platform/Library/Obsolete/ITabController.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -27,7 +27,7 @@ public interface ITabController TabInfo GetTab(int tabId, int portalId); Dictionary GetCustomAliases(int tabId, int portalId); - + List GetAliasSkins(int tabId, int portalId); List GetTabUrls(int tabId, int portalId); diff --git a/DNN Platform/Library/Obsolete/IUserController.cs b/DNN Platform/Library/Obsolete/IUserController.cs index 504b4f6d29f..bf480fbbe4f 100644 --- a/DNN Platform/Library/Obsolete/IUserController.cs +++ b/DNN Platform/Library/Obsolete/IUserController.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use version in DotNetNuke.Entities.Users instead. Scheduled removal in v10.0.0.")] public interface IUserController diff --git a/DNN Platform/Library/Obsolete/LogController.cs b/DNN Platform/Library/Obsolete/LogController.cs index adb908d8bc9..5feda563775 100644 --- a/DNN Platform/Library/Obsolete/LogController.cs +++ b/DNN Platform/Library/Obsolete/LogController.cs @@ -1,31 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data.SqlClient; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Web; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data.SqlClient; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + public partial class LogController { [EditorBrowsable(EditorBrowsableState.Never)] @@ -48,6 +43,5 @@ public virtual bool SupportsInternalViewer() { return LoggingProvider.Instance().SupportsInternalViewer(); } - } } diff --git a/DNN Platform/Library/Obsolete/ModuleController.cs b/DNN Platform/Library/Obsolete/ModuleController.cs index 9af3534369d..d4a2ee97c8d 100644 --- a/DNN Platform/Library/Obsolete/ModuleController.cs +++ b/DNN Platform/Library/Obsolete/ModuleController.cs @@ -1,62 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.IO; -using System.Linq; -using System.Threading; -using System.Web; -using System.Xml; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Modules.Internal; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.ModuleCache; -using DotNetNuke.Services.OutputCache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Modules.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.ModuleCache; + using DotNetNuke.Services.OutputCache; + public partial class ModuleController { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3. No longer neccessary. Scheduled removal in v10.0.0.")] public void CopyTabModuleSettings(ModuleInfo fromModule, ModuleInfo toModule) { - CopyTabModuleSettingsInternal(fromModule, toModule); + this.CopyTabModuleSettingsInternal(fromModule, toModule); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 7.3. Use an alternate overload. Scheduled removal in v10.0.0.")] public void DeleteAllModules(int moduleId, int tabId, List fromTabs) { - DeleteAllModules(moduleId, tabId, fromTabs, true, false, false); + this.DeleteAllModules(moduleId, tabId, fromTabs, true, false, false); } [EditorBrowsable(EditorBrowsableState.Never)] @@ -64,10 +59,10 @@ public void DeleteAllModules(int moduleId, int tabId, List fromTabs) public void DeleteModuleSettings(int moduleId) { dataProvider.DeleteModuleSettings(moduleId); - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString()}; + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString() }; log.LogProperties.Add(new LogDetailInfo("ModuleId", moduleId.ToString())); LogController.Instance.AddLog(log); - UpdateTabModuleVersionsByModuleID(moduleId); + this.UpdateTabModuleVersionsByModuleID(moduleId); ClearModuleSettingsCache(moduleId); } @@ -77,11 +72,12 @@ public void DeleteTabModuleSettings(int tabModuleId) { dataProvider.DeleteTabModuleSettings(tabModuleId); UpdateTabModuleVersion(tabModuleId); - EventLogController.Instance.AddLog("TabModuleID", - tabModuleId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.TABMODULE_SETTING_DELETED); + EventLogController.Instance.AddLog( + "TabModuleID", + tabModuleId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.TABMODULE_SETTING_DELETED); ClearTabModuleSettingsCache(tabModuleId, null); } @@ -112,9 +108,10 @@ public Hashtable GetModuleSettings(int ModuleId) } finally { - //Ensure DataReader is closed + // Ensure DataReader is closed CBO.CloseDataReader(dr, true); } + return settings; } @@ -122,14 +119,14 @@ public Hashtable GetModuleSettings(int ModuleId) [Obsolete("Deprecated in DNN 7.3. Replaced by GetTabModulesByModule(moduleID). Scheduled removal in v10.0.0.")] public ArrayList GetModuleTabs(int moduleID) { - return new ArrayList(GetTabModulesByModule(moduleID).ToArray()); + return new ArrayList(this.GetTabModulesByModule(moduleID).ToArray()); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 7.3. Replaced by GetModules(portalId). Scheduled removal in v10.0.0.")] public ArrayList GetRecycleModules(int portalID) { - return GetModules(portalID); + return this.GetModules(portalID); } [EditorBrowsable(EditorBrowsableState.Never)] @@ -161,6 +158,7 @@ public Hashtable GetTabModuleSettings(int TabModuleId) { CBO.CloseDataReader(dr, true); } + return settings; } } diff --git a/DNN Platform/Library/Obsolete/PortalAliasController.cs b/DNN Platform/Library/Obsolete/PortalAliasController.cs index c564c3940db..e60ce140b61 100644 --- a/DNN Platform/Library/Obsolete/PortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/PortalAliasController.cs @@ -1,39 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel; - -#region Usings - -using System; -using System.Collections; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Log.EventLog; - -#endregion - -// ReSharper disable once CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// ReSharper disable once CheckNamespace namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections; + using System.ComponentModel; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Log.EventLog; + public partial class PortalAliasController { + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in version 7.3. Replaced by PortalAliasController.Instance.GetPortalAlias. Scheduled removal in v10.0.0.")] + public static PortalAliasInfo GetPortalAliasInfo(string httpAlias) + { + return Instance.GetPortalAlias(httpAlias); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.GetPortalAliases. Scheduled removal in v10.0.0.")] + public static PortalAliasCollection GetPortalAliasLookup() + { + var portalAliasCollection = new PortalAliasCollection(); + var aliasController = new PortalAliasController(); + foreach (var kvp in aliasController.GetPortalAliasesInternal()) + { + portalAliasCollection.Add(kvp.Key, kvp.Value); + } + + return portalAliasCollection; + } + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.DeletePortalAlias. Scheduled removal in v10.0.0.")] public void DeletePortalAlias(int portalAliasId) { - DataProvider.Instance().DeletePortalAlias(portalAliasId); - EventLogController.Instance.AddLog("PortalAliasID", - portalAliasId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTALALIAS_DELETED); + EventLogController.Instance.AddLog( + "PortalAliasID", + portalAliasId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALALIAS_DELETED); DataCache.RemoveCache(DataCache.PortalAliasCacheKey); } @@ -59,27 +75,6 @@ public PortalAliasCollection GetPortalAliasByPortalID(int PortalID) return portalAliasCollection; } - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.3. Replaced by PortalAliasController.Instance.GetPortalAlias. Scheduled removal in v10.0.0.")] - public static PortalAliasInfo GetPortalAliasInfo(string httpAlias) - { - return Instance.GetPortalAlias(httpAlias); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.GetPortalAliases. Scheduled removal in v10.0.0.")] - public static PortalAliasCollection GetPortalAliasLookup() - { - var portalAliasCollection = new PortalAliasCollection(); - var aliasController = new PortalAliasController(); - foreach (var kvp in aliasController.GetPortalAliasesInternal()) - { - portalAliasCollection.Add(kvp.Key, kvp.Value); - } - - return portalAliasCollection; - } - [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in version 7.3. Replaced by PortalAliasController.Instance.GetPortalAlias. Scheduled removal in v10.0.0.")] public static PortalAliasInfo GetPortalAliasLookup(string httpAlias) diff --git a/DNN Platform/Library/Obsolete/PortalController.cs b/DNN Platform/Library/Obsolete/PortalController.cs index 00fe7d8c19d..1015ad4d53a 100644 --- a/DNN Platform/Library/Obsolete/PortalController.cs +++ b/DNN Platform/Library/Obsolete/PortalController.cs @@ -1,40 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#region Usings - -using System; -using System.Collections; -using System.Xml; - -using DotNetNuke.Entities.Tabs; -//using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; - -#endregion - -// ReSharper disable once CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; + +// ReSharper disable once CheckNamespace namespace DotNetNuke.Entities.Portals { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.IO; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + /// - /// PoralController provides business layer of poatal. - /// - /// - /// DotNetNuke supports the concept of virtualised sites in a single install. This means that multiple sites, - /// each potentially with multiple unique URL's, can exist in one instance of DotNetNuke i.e. one set of files and one database. - /// + /// PoralController provides business layer of poatal. + /// + /// + /// DotNetNuke supports the concept of virtualised sites in a single install. This means that multiple sites, + /// each potentially with multiple unique URL's, can exist in one instance of DotNetNuke i.e. one set of files and one database. + /// public partial class PortalController { + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in DotNetNuke 7.3. Replaced by PortalController.Instance.GetCurrentPortalSettings. Scheduled removal in v10.0.0.")] + public static PortalSettings GetCurrentPortalSettings() + { + return GetCurrentPortalSettingsInternal(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in DNN 7.4.0. Replaced by PortalController.Instance.GetPortalSettings. Scheduled removal in v10.0.0.")] + public static Dictionary GetPortalSettingsDictionary(int portalId) + { + return Instance.GetPortalSettings(portalId); + } + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] public int CreatePortal(string portalName, string firstName, string lastName, string username, string password, string email, @@ -47,14 +56,14 @@ public int CreatePortal(string portalName, string firstName, string lastName, st LastName = lastName, Username = username, DisplayName = firstName + " " + lastName, - Membership = {Password = password}, + Membership = { Password = password }, Email = email, - IsSuperUser = false + IsSuperUser = false, }; adminUser.Membership.Approved = true; adminUser.Profile.FirstName = firstName; adminUser.Profile.LastName = lastName; - return CreatePortal(portalName, adminUser, description, keyWords, templatePath, templateFile, homeDirectory, portalAlias, serverPath, childPath, isChildPortal); + return this.CreatePortal(portalName, adminUser, description, keyWords, templatePath, templateFile, homeDirectory, portalAlias, serverPath, childPath, isChildPortal); } [EditorBrowsable(EditorBrowsableState.Never)] @@ -63,9 +72,9 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio string templateFile, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { - var template = GetPortalTemplate(Path.Combine(templatePath, templateFile), null); + var template = this.GetPortalTemplate(Path.Combine(templatePath, templateFile), null); - return CreatePortal(portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, + return this.CreatePortal(portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal); } @@ -82,47 +91,32 @@ public void DeletePortalInfo(int portalId) DataCache.ClearHostCache(true); } - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. Replaced by PortalController.Instance.GetCurrentPortalSettings. Scheduled removal in v10.0.0.")] - public static PortalSettings GetCurrentPortalSettings() - { - return GetCurrentPortalSettingsInternal(); - } - - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.4.0. Replaced by PortalController.Instance.GetPortalSettings. Scheduled removal in v10.0.0.")] - public static Dictionary GetPortalSettingsDictionary(int portalId) - { - return Instance.GetPortalSettings(portalId); - } - [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] public void ParseTemplate(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { - ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal); + this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the other overloads. Scheduled removal in v10.0.0.")] public void ParseTemplate(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal, out LocaleCollection localeCollection) { - ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal, out localeCollection); + this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal, out localeCollection); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3. Replaced by UpdatePortalExpiry(int, string). Scheduled removal in v10.0.0.")] public void UpdatePortalExpiry(int portalId) { - UpdatePortalExpiry(portalId, GetActivePortalLanguage(portalId)); + this.UpdatePortalExpiry(portalId, GetActivePortalLanguage(portalId)); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] public void UpdatePortalInfo(PortalInfo portal, bool clearCache) { - UpdatePortalInternal(portal, clearCache); + this.UpdatePortalInternal(portal, clearCache); } - } + } } diff --git a/DNN Platform/Library/Obsolete/PortalSettings.cs b/DNN Platform/Library/Obsolete/PortalSettings.cs index 86165531121..fe6a975a9f5 100644 --- a/DNN Platform/Library/Obsolete/PortalSettings.cs +++ b/DNN Platform/Library/Obsolete/PortalSettings.cs @@ -1,43 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Globalization; -using System.Linq; -using System.Web; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Collections; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; -using DotNetNuke.Services.Tokens; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Portals { - public partial class PortalSettings - { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Globalization; + using System.Linq; + using System.Web; + + using DotNetNuke.Application; + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + using DotNetNuke.Services.Tokens; + using DotNetNuke.UI.Skins; + + public partial class PortalSettings + { [Obsolete("Deprecated in DNN 7.4. Replaced by PortalSettingsController.Instance().GetPortalAliasMappingMode. Scheduled removal in v10.0.0.")] [EditorBrowsable(EditorBrowsableState.Never)] public static PortalAliasMapping GetPortalAliasMappingMode(int portalId) { return PortalSettingsController.Instance().GetPortalAliasMappingMode(portalId); } - } + } } diff --git a/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs b/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs index af7aa1bb789..3241202279d 100644 --- a/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs +++ b/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs @@ -1,22 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; -using System.Linq; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.IO; + using System.Linq; + + using DotNetNuke.Common; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalTemplateIO. Scheduled removal in v10.0.0.")] public class PortalTemplateIOImpl : IPortalTemplateIO - { - #region IPortalTemplateIO Members - + { public IEnumerable EnumerateTemplates() { string path = Globals.HostMapPath; @@ -61,9 +60,7 @@ private static string CheckFilePath(string path) return path; } - return ""; - } - - #endregion + return string.Empty; + } } } diff --git a/DNN Platform/Library/Obsolete/RoleController.cs b/DNN Platform/Library/Obsolete/RoleController.cs index 68aadde6778..11f918160f0 100644 --- a/DNN Platform/Library/Obsolete/RoleController.cs +++ b/DNN Platform/Library/Obsolete/RoleController.cs @@ -1,25 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.ComponentModel; -using System.Linq; -using System.Web.Services.Description; -using System.Xml; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { + using System; + using System.Collections; + using System.ComponentModel; + using System.Linq; + using System.Web.Services.Description; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + /// - /// The RoleController class provides Business Layer methods for Roles + /// The RoleController class provides Business Layer methods for Roles. /// /// ----------------------------------------------------------------------------- - public partial class RoleController + public partial class RoleController { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.0. This function has been replaced by AddUserRole with additional params. Scheduled removal in v10.0.0.")] @@ -32,22 +32,22 @@ public static void AddUserRole(UserInfo user, RoleInfo role, PortalSettings port [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by overload with extra parameters. Scheduled removal in v10.0.0.")] public void AddUserRole(int portalId, int userId, int roleId, DateTime expiryDate) { - AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, Null.NullDate, expiryDate); + this.AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, Null.NullDate, expiryDate); } public void AddUserRole(int portalId, int userId, int roleId, DateTime effectiveDate, DateTime expiryDate) { - AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, effectiveDate, expiryDate); + this.AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, effectiveDate, expiryDate); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by DeleteRole(role). Scheduled removal in v10.0.0.")] public void DeleteRole(int roleId, int portalId) { - RoleInfo role = GetRole(portalId, r => r.RoleID == roleId); + RoleInfo role = this.GetRole(portalId, r => r.RoleID == roleId); if (role != null) { - DeleteRole(role); + this.DeleteRole(role); } } @@ -62,7 +62,7 @@ public ArrayList GetPortalRoles(int portalId) [Obsolete("Deprecated in DotNetNuke 7.3. This method has been replacd by GetRoleById. Scheduled removal in v10.0.0.")] public RoleInfo GetRole(int roleId, int portalId) { - return GetRoleById(portalId, roleId); + return this.GetRoleById(portalId, roleId); } [EditorBrowsable(EditorBrowsableState.Never)] @@ -95,16 +95,14 @@ public void UpdateRole(RoleInfo role) [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by overload with extra parameters. Scheduled removal in v10.0.0.")] public void UpdateUserRole(int portalId, int userId, int roleId) { - UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, false); + this.UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, false); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by overload with extra parameters. Scheduled removal in v10.0.0.")] public void UpdateUserRole(int portalId, int userId, int roleId, bool cancel) { - UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, cancel); - } - - - } + this.UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, cancel); + } + } } diff --git a/DNN Platform/Library/Obsolete/TabController.cs b/DNN Platform/Library/Obsolete/TabController.cs index 0515487e0f7..227a9c568fb 100644 --- a/DNN Platform/Library/Obsolete/TabController.cs +++ b/DNN Platform/Library/Obsolete/TabController.cs @@ -1,31 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Linq; -using System.Xml; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Linq; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + /// /// TabController provides all operation to tabinfo. /// @@ -42,7 +37,7 @@ public void CreateLocalizedCopy(List tabs, Locale locale) { foreach (TabInfo t in tabs) { - CreateLocalizedCopy(t, locale, true); + this.CreateLocalizedCopy(t, locale, true); } } @@ -50,21 +45,21 @@ public void CreateLocalizedCopy(List tabs, Locale locale) [Obsolete("Deprecated in DotNetNuke 7.3. RUse alternate overload. Scheduled removal in v10.0.0.")] public void CreateLocalizedCopy(TabInfo originalTab, Locale locale) { - CreateLocalizedCopy(originalTab, locale, true); + this.CreateLocalizedCopy(originalTab, locale, true); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 7.3. Method is not scalable. Use GetTabsByPortal. Scheduled removal in v10.0.0.")] public ArrayList GetAllTabs() { - return CBO.FillCollection(_dataProvider.GetAllTabs(), typeof(TabInfo)); + return CBO.FillCollection(this._dataProvider.GetAllTabs(), typeof(TabInfo)); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 7.3. Method is not neccessary. Use LINQ and GetPortalTabs(). Scheduled removal in v10.0.0.")] public List GetCultureTabList(int portalid) { - return (from kvp in GetTabsByPortal(portalid) + return (from kvp in this.GetTabsByPortal(portalid) where !kvp.Value.TabPath.StartsWith("//Admin") && kvp.Value.CultureCode == PortalController.Instance.GetCurrentPortalSettings().DefaultLanguage && !kvp.Value.IsDeleted @@ -75,7 +70,7 @@ public List GetCultureTabList(int portalid) [Obsolete("Deprecated in DNN 7.3. Method is not neccessary. Use LINQ and GetPortalTabs(). Scheduled removal in v10.0.0.")] public List GetDefaultCultureTabList(int portalid) { - return (from kvp in GetTabsByPortal(portalid) + return (from kvp in this.GetTabsByPortal(portalid) where !kvp.Value.TabPath.StartsWith("//Admin") && !kvp.Value.IsDeleted select kvp.Value).ToList(); @@ -85,21 +80,21 @@ public List GetDefaultCultureTabList(int portalid) [Obsolete("This method is obsolete. It has been replaced by GetTab(ByVal TabId As Integer, ByVal PortalId As Integer, ByVal ignoreCache As Boolean) . Scheduled removal in v10.0.0.")] public TabInfo GetTab(int tabId) { - return GetTab(tabId, GetPortalId(tabId, Null.NullInteger), false); + return this.GetTab(tabId, GetPortalId(tabId, Null.NullInteger), false); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 7.3. Use LINQ queries on tab collections thata re cached. Scheduled removal in v10.0.0.")] public TabInfo GetTabByUniqueID(Guid uniqueID) { - return CBO.FillObject(_dataProvider.GetTabByUniqueID(uniqueID)); + return CBO.FillObject(this._dataProvider.GetTabByUniqueID(uniqueID)); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 7.3. Use GetTabsByPortal(portalId).Count. Scheduled removal in v10.0.0.")] public int GetTabCount(int portalId) { - return GetTabsByPortal(portalId).Count; + return this.GetTabsByPortal(portalId).Count; } [EditorBrowsable(EditorBrowsableState.Never)] @@ -113,31 +108,32 @@ public ArrayList GetTabsByParentId(int parentId) [Obsolete("Deprecated in DNN 7.3. Use one of the alternate MoveTabxxx methods). Scheduled removal in v10.0.0.")] public void MoveTab(TabInfo tab, TabMoveType type) { - //Get the List of tabs with the same parent - IOrderedEnumerable siblingTabs = GetSiblingTabs(tab).OrderBy(t => t.TabOrder); + // Get the List of tabs with the same parent + IOrderedEnumerable siblingTabs = this.GetSiblingTabs(tab).OrderBy(t => t.TabOrder); int tabIndex = GetIndexOfTab(tab, siblingTabs); switch (type) { case TabMoveType.Top: - MoveTabBefore(tab, siblingTabs.First().TabID); + this.MoveTabBefore(tab, siblingTabs.First().TabID); break; case TabMoveType.Bottom: - MoveTabAfter(tab, siblingTabs.Last().TabID); + this.MoveTabAfter(tab, siblingTabs.Last().TabID); break; case TabMoveType.Up: - MoveTabBefore(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); + this.MoveTabBefore(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); break; case TabMoveType.Down: - MoveTabAfter(tab, siblingTabs.ElementAt(tabIndex + 1).TabID); + this.MoveTabAfter(tab, siblingTabs.ElementAt(tabIndex + 1).TabID); break; case TabMoveType.Promote: - MoveTabAfter(tab, tab.ParentId); + this.MoveTabAfter(tab, tab.ParentId); break; case TabMoveType.Demote: - MoveTabToParent(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); + this.MoveTabToParent(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); break; } - ClearCache(tab.PortalID); + + this.ClearCache(tab.PortalID); } } } diff --git a/DNN Platform/Library/Obsolete/TestableModuleController.cs b/DNN Platform/Library/Obsolete/TestableModuleController.cs index fd8f3a2a309..4370da78661 100644 --- a/DNN Platform/Library/Obsolete/TestableModuleController.cs +++ b/DNN Platform/Library/Obsolete/TestableModuleController.cs @@ -1,37 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.Reflection; - -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Modules.Internal { + using System; + using System.ComponentModel; + using System.Reflection; + + using DotNetNuke.Framework; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use ModuleController instead. Scheduled removal in v10.0.0.")] public class TestableModuleController : ServiceLocator, IModuleController { + public ModuleInfo GetModule(int moduleId, int tabId) + { + return ModuleController.Instance.GetModule(moduleId, tabId, false); + } + + public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) + { + ModuleController.Instance.UpdateModuleSetting(moduleId, settingName, settingValue); + } + protected override Func GetFactory() { return () => new TestableModuleController(); } - public ModuleInfo GetModule(int moduleId, int tabId) - { - return ModuleController.Instance.GetModule(moduleId, tabId, false); - } - - public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) - { - ModuleController.Instance.UpdateModuleSetting(moduleId, settingName, settingValue); - } - - public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) - { - ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); - } + public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) + { + ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); + } } } diff --git a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs index 00dbed98a58..3578b537a3f 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Framework; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use PortalAliasController instead. Scheduled removal in v10.0.0.")] public class TestablePortalAliasController : ServiceLocator, IPortalAliasController { - protected override Func GetFactory() - { - return () => new TestablePortalAliasController(); - } - public int AddPortalAlias(PortalAliasInfo portalAlias) { return PortalAliasController.Instance.AddPortalAlias(portalAlias); @@ -28,6 +23,11 @@ public void DeletePortalAlias(PortalAliasInfo portalAlias) { PortalAliasController.Instance.DeletePortalAlias(portalAlias); } + + protected override Func GetFactory() + { + return () => new TestablePortalAliasController(); + } public PortalAliasInfo GetPortalAlias(string alias) { diff --git a/DNN Platform/Library/Obsolete/TestablePortalController.cs b/DNN Platform/Library/Obsolete/TestablePortalController.cs index 6aa9089b917..bbd14c9e1bf 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalController.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalController.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; - -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.ComponentModel; + + using DotNetNuke.Framework; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use PortalController instead. Scheduled removal in v10.0.0.")] public class TestablePortalController : ServiceLocator diff --git a/DNN Platform/Library/Obsolete/TestablePortalSettings.cs b/DNN Platform/Library/Obsolete/TestablePortalSettings.cs index b14b917c531..5344fb75a07 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalSettings.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalSettings.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; - -using DotNetNuke.Common; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Portals.Internal { + using System; + using System.ComponentModel; + + using DotNetNuke.Common; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalController.Instance.GetCurrentPortalSettings to get a mockable PortalSettings. Scheduled removal in v10.0.0.")] public class TestablePortalSettings : ComponentBase, IPortalSettings diff --git a/DNN Platform/Library/Obsolete/TestableRoleController.cs b/DNN Platform/Library/Obsolete/TestableRoleController.cs index 511bf5bc53e..9f31cd0f437 100644 --- a/DNN Platform/Library/Obsolete/TestableRoleController.cs +++ b/DNN Platform/Library/Obsolete/TestableRoleController.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Framework; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use RoleController instead. Scheduled removal in v10.0.0.")] public class TestableRoleController : ServiceLocator, IRoleController { - protected override Func GetFactory() - { - return () => new TestableRoleController(); - } - public int AddRole(RoleInfo role) { return RoleController.Instance.AddRole(role); @@ -28,6 +23,11 @@ public int AddRole(RoleInfo role, bool addToExistUsers) { return RoleController.Instance.AddRole(role, addToExistUsers); } + + protected override Func GetFactory() + { + return () => new TestableRoleController(); + } public void DeleteRole(RoleInfo role) { diff --git a/DNN Platform/Library/Obsolete/TestableTabController.cs b/DNN Platform/Library/Obsolete/TestableTabController.cs index ebe874fd203..89756458e56 100644 --- a/DNN Platform/Library/Obsolete/TestableTabController.cs +++ b/DNN Platform/Library/Obsolete/TestableTabController.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Web.Services.Description; - -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Tabs.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Web.Services.Description; + + using DotNetNuke.Framework; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use TabController instead. Scheduled removal in v10.0.0.")] public class TestableTabController : ServiceLocator, ITabController { - protected override Func GetFactory() - { - return () => new TestableTabController(); - } - public void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) { TabController.Instance.DeleteTabUrl(tabUrl, portalId, clearCache); @@ -29,6 +24,11 @@ public TabInfo GetTab(int tabId, int portalId) { return TabController.Instance.GetTab(tabId, portalId); } + + protected override Func GetFactory() + { + return () => new TestableTabController(); + } public Dictionary GetCustomAliases(int tabId, int portalId) { diff --git a/DNN Platform/Library/Obsolete/TestableUserController.cs b/DNN Platform/Library/Obsolete/TestableUserController.cs index a94da004910..d0ed78714e8 100644 --- a/DNN Platform/Library/Obsolete/TestableUserController.cs +++ b/DNN Platform/Library/Obsolete/TestableUserController.cs @@ -1,28 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Users.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Framework; + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This class has been obsoleted in 7.3.0 - please use UserController instead. Scheduled removal in v10.0.0.")] public class TestableUserController : ServiceLocator, IUserController { - protected override Func GetFactory() - { - return () => new TestableUserController(); - } - public UserInfo GetUserByDisplayname(int portalId, string displayName) { return UserController.Instance.GetUserByDisplayname(portalId, displayName); @@ -32,6 +22,11 @@ public UserInfo GetUserById(int portalId, int userId) { return UserController.Instance.GetUserById(portalId, userId); } + + protected override Func GetFactory() + { + return () => new TestableUserController(); + } public IList GetUsersAdvancedSearch(int portalId, int userId, int filterUserId, int filterRoleId, int relationTypeId, bool isAdmin, int pageIndex, int pageSize, string sortColumn, bool sortAscending, string propertyNames, diff --git a/DNN Platform/Library/Obsolete/UserController.cs b/DNN Platform/Library/Obsolete/UserController.cs index e0ea2fa30d8..0876bc8a48a 100644 --- a/DNN Platform/Library/Obsolete/UserController.cs +++ b/DNN Platform/Library/Obsolete/UserController.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.ComponentModel; -using System.Data; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Entities.Users { + using System; + using System.Collections; + using System.ComponentModel; + using System.Data; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Exceptions; + /// - /// The UserController class provides Business Layer methods for Users + /// The UserController class provides Business Layer methods for Users. /// /// - /// DotNetNuke user management is base on asp.net membership provider, but the default implementation of these providers - /// do not satisfy the broad set of use cases which we need to support in DotNetNuke. so The dependency of DotNetNuke on the - /// MemberRole (ASP.NET 2 Membership) components will be abstracted into a DotNetNuke Membership Provider, in order to allow + /// DotNetNuke user management is base on asp.net membership provider, but the default implementation of these providers + /// do not satisfy the broad set of use cases which we need to support in DotNetNuke. so The dependency of DotNetNuke on the + /// MemberRole (ASP.NET 2 Membership) components will be abstracted into a DotNetNuke Membership Provider, in order to allow /// developers complete flexibility in implementing alternate Membership approaches. /// /// This will allow for a number of enhancements to be added @@ -59,19 +60,19 @@ public static UserInfo GetCurrentUserInfo() return GetCurrentUserInternal(); } - /// - /// overload will validate the token and if valid change the password - /// it does not require an old password as it supports hashed passwords - /// errorMessage will define why reset failed - /// - /// The new password. - /// The reset token, typically supplied through a password reset email. - /// A Boolean indicating success or failure. - [Obsolete("Deprecate in 7.4.2, Use ChangePasswordByToken(int portalid, string username, string newPassword, string answer, string resetToken, out string errorMessage).. Scheduled removal in v10.0.0.")] - public static bool ChangePasswordByToken(int portalid, string username, string newPassword, string resetToken, out string errorMessage) - { - return ChangePasswordByToken(portalid, username, newPassword, string.Empty, resetToken, out errorMessage); - } + /// + /// overload will validate the token and if valid change the password + /// it does not require an old password as it supports hashed passwords + /// errorMessage will define why reset failed. + /// + /// The new password. + /// The reset token, typically supplied through a password reset email. + /// A Boolean indicating success or failure. + [Obsolete("Deprecate in 7.4.2, Use ChangePasswordByToken(int portalid, string username, string newPassword, string answer, string resetToken, out string errorMessage).. Scheduled removal in v10.0.0.")] + public static bool ChangePasswordByToken(int portalid, string username, string newPassword, string resetToken, out string errorMessage) + { + return ChangePasswordByToken(portalid, username, newPassword, string.Empty, resetToken, out errorMessage); + } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 6.1, keep this method to compatible with upgrade wizard.. Scheduled removal in v10.0.0.")] @@ -80,20 +81,21 @@ public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeData UserInfo objUserInfo = null; try { - //read datareader + // read datareader var bContinue = true; if (closeDataReader) { bContinue = false; if (dr.Read()) { - //Ensure the data reader returned is valid + // Ensure the data reader returned is valid if (string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase)) { bContinue = true; } } } + if (bContinue) { objUserInfo = new UserInfo @@ -104,7 +106,7 @@ public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeData UserID = Null.SetNullInteger(dr["UserID"]), FirstName = Null.SetNullString(dr["FirstName"]), LastName = Null.SetNullString(dr["LastName"]), - DisplayName = Null.SetNullString(dr["DisplayName"]) + DisplayName = Null.SetNullString(dr["DisplayName"]), }; objUserInfo.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], objUserInfo.AffiliateID)); objUserInfo.Username = Null.SetNullString(dr["Username"]); @@ -119,6 +121,7 @@ public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeData { objUserInfo.PasswordResetExpiration = Null.SetNullDateTime(dr["PasswordResetExpiration"]); } + if (schema.Select("ColumnName = 'PasswordResetToken'").Length > 0) { objUserInfo.PasswordResetToken = Null.SetNullGuid(dr["PasswordResetToken"]); @@ -135,6 +138,7 @@ public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeData { CBO.CloseDataReader(dr, closeDataReader); } + return objUserInfo; } } diff --git a/DNN Platform/Library/Properties/AssemblyInfo.cs b/DNN Platform/Library/Properties/AssemblyInfo.cs index 1367198c9b2..3b224c233a0 100644 --- a/DNN Platform/Library/Properties/AssemblyInfo.cs +++ b/DNN Platform/Library/Properties/AssemblyInfo.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; using System.Runtime.CompilerServices; -using DotNetNuke.Application; -#endregion - -// 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. - -// Review the values of the assembly attributes - +using DotNetNuke.Application; + +// 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. + +// Review the values of the assembly attributes [assembly: AssemblyTitle("DotNetNuke")] [assembly: AssemblyDescription("Open Source Web Application Framework")] [assembly: CLSCompliant(true)] diff --git a/DNN Platform/Library/Security/Cookies/AuthCookieController.cs b/DNN Platform/Library/Security/Cookies/AuthCookieController.cs index 9c441222632..4c99f73016d 100644 --- a/DNN Platform/Library/Security/Cookies/AuthCookieController.cs +++ b/DNN Platform/Library/Security/Cookies/AuthCookieController.cs @@ -1,54 +1,64 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Caching; -using System.Web.Security; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Cookies { + using System; + using System.Web.Caching; + using System.Web.Security; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Framework; + public class AuthCookieController : ServiceLocator, IAuthCookieController { private readonly DataProvider _dataProvider = DataProvider.Instance(); - protected override Func GetFactory() - { - return () => new AuthCookieController(); - } - public void Update(string cookieValue, DateTime utcExpiry, int userId) { - if (string.IsNullOrEmpty(cookieValue)) return; - + if (string.IsNullOrEmpty(cookieValue)) + { + return; + } + DataCache.ClearCache(GetKey(cookieValue)); - _dataProvider.UpdateAuthCookie(cookieValue, utcExpiry, userId); + this._dataProvider.UpdateAuthCookie(cookieValue, utcExpiry, userId); } public PersistedAuthCookie Find(string cookieValue) { - if (string.IsNullOrEmpty(cookieValue)) return null; - + if (string.IsNullOrEmpty(cookieValue)) + { + return null; + } + return CBO.Instance.GetCachedObject( new CacheItemArgs(GetKey(cookieValue), (int)FormsAuthentication.Timeout.TotalMinutes, CacheItemPriority.AboveNormal), - _ => CBO.Instance.FillObject(_dataProvider.FindAuthCookie(cookieValue)), false); + _ => CBO.Instance.FillObject(this._dataProvider.FindAuthCookie(cookieValue)), false); } - public void DeleteByValue(string cookieValue) + protected override Func GetFactory() { - if (string.IsNullOrEmpty(cookieValue)) return; + return () => new AuthCookieController(); + } - // keep in cache so hacking tries don't hit the database; it will expire automatically - //DataCache.ClearCache(GetKey(cookieValue)); - _dataProvider.DeleteAuthCookie(cookieValue); + public void DeleteByValue(string cookieValue) + { + if (string.IsNullOrEmpty(cookieValue)) + { + return; + } + + // keep in cache so hacking tries don't hit the database; it will expire automatically + // DataCache.ClearCache(GetKey(cookieValue)); + this._dataProvider.DeleteAuthCookie(cookieValue); } public void DeleteExpired(DateTime utcExpiredBefore) { - _dataProvider.DeleteExpiredAuthCookies(utcExpiredBefore); + this._dataProvider.DeleteExpiredAuthCookies(utcExpiredBefore); } private static string GetKey(string cookieValue) diff --git a/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs b/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs index 53fafe05626..6d0b2156cd8 100644 --- a/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs +++ b/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs @@ -1,16 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Cookies { + using System; + public interface IAuthCookieController { void Update(string cookieValue, DateTime utcExpiry, int userId); + PersistedAuthCookie Find(string cookieValue); + void DeleteByValue(string cookieValue); + void DeleteExpired(DateTime utcExpiredBefore); } } diff --git a/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs b/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs index afee9f96475..c668f4c3084 100644 --- a/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs +++ b/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs @@ -1,43 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Entities.Modules; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable MemberCanBePrivate.Global - namespace DotNetNuke.Security.Cookies { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Entities.Modules; + [Serializable] [TableName("AuthCookies")] [PrimaryKey("CookieId")] public class PersistedAuthCookie : IHydratable { public int CookieId { get; private set; } + public string CookieValue { get; private set; } + public DateTime ExpiresOn { get; private set; } // UTC public int KeyID { - get { return CookieId; } - set { CookieId = value; } + get { return this.CookieId; } + set { this.CookieId = value; } } public void Fill(IDataReader dr) { - CookieId = Null.SetNullInteger(dr[nameof(CookieId)]); - CookieValue = Null.SetNullString(dr[nameof(CookieValue)]); - ExpiresOn = Null.SetNullDateTime(dr[nameof(ExpiresOn)]); + this.CookieId = Null.SetNullInteger(dr[nameof(this.CookieId)]); + this.CookieValue = Null.SetNullString(dr[nameof(this.CookieValue)]); + this.ExpiresOn = Null.SetNullDateTime(dr[nameof(this.ExpiresOn)]); - if (ExpiresOn.Kind != DateTimeKind.Utc) + if (this.ExpiresOn.Kind != DateTimeKind.Utc) { - ExpiresOn = new DateTime( - ExpiresOn.Year, ExpiresOn.Month, ExpiresOn.Day, - ExpiresOn.Hour, ExpiresOn.Minute, ExpiresOn.Second, - ExpiresOn.Millisecond, DateTimeKind.Utc); + this.ExpiresOn = new DateTime( + this.ExpiresOn.Year, this.ExpiresOn.Month, this.ExpiresOn.Day, + this.ExpiresOn.Hour, this.ExpiresOn.Minute, this.ExpiresOn.Second, + this.ExpiresOn.Millisecond, DateTimeKind.Utc); } } } diff --git a/DNN Platform/Library/Security/FIPSCompliant.cs b/DNN Platform/Library/Security/FIPSCompliant.cs index ade9fee665d..448b502365f 100644 --- a/DNN Platform/Library/Security/FIPSCompliant.cs +++ b/DNN Platform/Library/Security/FIPSCompliant.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security { + using System; + using System.IO; + using System.Security.Cryptography; + using System.Text; + + using DotNetNuke.Common; + /// /// This class implements a number of methods that can be safely used in a FIPS-140 compliant environment /// FIPS compliant Algorithms: @@ -23,19 +24,19 @@ namespace DotNetNuke.Security /// TripleDESCryptoServiceProvider /// Asymmetric algorithms (use a public key for encryption and a private key for decryption) /// DSACryptoServiceProvider - /// RSACryptoServiceProvider + /// RSACryptoServiceProvider. /// public class FIPSCompliant { /// - /// uses the AES FIPS-140 compliant algorithm to encrypt a string + /// uses the AES FIPS-140 compliant algorithm to encrypt a string. /// - /// the text to encrypt - /// the pass phase to do the encryption - /// a salt value to ensure ciphertext using the same text/password is different - /// number of iterations to derive the key (higher is slower but more secure) - optional parameter with a default of 1000 + /// the text to encrypt. + /// the pass phase to do the encryption. + /// a salt value to ensure ciphertext using the same text/password is different. + /// number of iterations to derive the key (higher is slower but more secure) - optional parameter with a default of 1000. /// - public static String EncryptAES(String plainText, String passPhrase, String salt, int iterations = 1000) + public static string EncryptAES(string plainText, string passPhrase, string salt, int iterations = 1000) { VerifyAesSettings(passPhrase, salt); @@ -43,9 +44,9 @@ public static String EncryptAES(String plainText, String passPhrase, String salt using (var aesProvider = new AesCryptoServiceProvider()) { var derivedBytes = new Rfc2898DeriveBytes(passPhrase, saltBytes, iterations); - Byte[] derivedKey = derivedBytes.GetBytes(32); // 256 bits - Byte[] derivedInitVector = derivedBytes.GetBytes(16); // 128 bits - Byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); + byte[] derivedKey = derivedBytes.GetBytes(32); // 256 bits + byte[] derivedInitVector = derivedBytes.GetBytes(16); // 128 bits + byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); aesProvider.KeySize = 256; aesProvider.Padding = PaddingMode.ISO10126; @@ -57,45 +58,34 @@ public static String EncryptAES(String plainText, String passPhrase, String salt { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); - Byte[] cipherTextBytes = memStream.ToArray(); + byte[] cipherTextBytes = memStream.ToArray(); memStream.Close(); cryptoStream.Close(); return Convert.ToBase64String(cipherTextBytes); - } } } - private static void VerifyAesSettings(string passPhrase, string salt) - { - Requires.PropertyNotNull("passPhrase", passPhrase); - Requires.PropertyNotNull("salt", salt); - // Throw exception if the password or salt are too short - if (passPhrase.Length < 8) - throw new CryptographicException("Passphrase must be at least 8 characters long."); - if (salt.Length < 8) throw new CryptographicException("Salt must be at least 8 characters long."); - } - /// - /// uses the AES FIPS-140 compliant algorithm to encrypt a string + /// uses the AES FIPS-140 compliant algorithm to encrypt a string. /// - /// the text to decrypt - /// the pass phase to do the decryption - /// a salt value to ensure ciphertext using the same text/password is different - /// number of iterations to derive the key (higher is slower but more secure) - optional parameter with a default of 1000 + /// the text to decrypt. + /// the pass phase to do the decryption. + /// a salt value to ensure ciphertext using the same text/password is different. + /// number of iterations to derive the key (higher is slower but more secure) - optional parameter with a default of 1000. /// - public static String DecryptAES(String encryptedText, String passPhrase, String salt, int iterations = 1000) + public static string DecryptAES(string encryptedText, string passPhrase, string salt, int iterations = 1000) { VerifyAesSettings(passPhrase, salt); - Byte[] saltBytes = Encoding.ASCII.GetBytes(salt); + byte[] saltBytes = Encoding.ASCII.GetBytes(salt); var aesProvider = new AesCryptoServiceProvider(); var derivedBytes = new Rfc2898DeriveBytes(passPhrase, saltBytes, iterations); - Byte[] derivedKey = derivedBytes.GetBytes(32); // 256 bits - Byte[] derivedInitVector = derivedBytes.GetBytes(16); // 128 bits - Byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); + byte[] derivedKey = derivedBytes.GetBytes(32); // 256 bits + byte[] derivedInitVector = derivedBytes.GetBytes(16); // 128 bits + byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); aesProvider.KeySize = 256; aesProvider.Padding = PaddingMode.ISO10126; @@ -105,13 +95,30 @@ public static String DecryptAES(String encryptedText, String passPhrase, String using (var memStream = new MemoryStream(cipherTextBytes)) using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read)) { - var plainTextBytes = new Byte[cipherTextBytes.Length]; - Int32 byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); + var plainTextBytes = new byte[cipherTextBytes.Length]; + int byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount); } } + + private static void VerifyAesSettings(string passPhrase, string salt) + { + Requires.PropertyNotNull("passPhrase", passPhrase); + Requires.PropertyNotNull("salt", salt); + + // Throw exception if the password or salt are too short + if (passPhrase.Length < 8) + { + throw new CryptographicException("Passphrase must be at least 8 characters long."); + } + + if (salt.Length < 8) + { + throw new CryptographicException("Salt must be at least 8 characters long."); + } + } } } diff --git a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs index a711606a237..fc055df9930 100644 --- a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs @@ -1,37 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Membership; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Exceptions; -//DNN-4016 -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Configuration.Provider; -using System.Data; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Membership { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Configuration.Provider; + using System.Data; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Security; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Membership; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + // DNN-4016 + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Provider.AspNetProvider @@ -39,24 +35,19 @@ namespace DotNetNuke.Security.Membership /// ----------------------------------------------------------------------------- /// /// The AspNetMembershipProvider overrides the default MembershipProvider to provide - /// an AspNet Membership Component (MemberRole) implementation + /// an AspNet Membership Component (MemberRole) implementation. /// /// /// /// ----------------------------------------------------------------------------- public class AspNetMembershipProvider : MembershipProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetMembershipProvider)); - - #region Private Members - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetMembershipProvider)); + private static Random random = new Random(); + private readonly DataProvider _dataProvider = DataProvider.Instance(); - private readonly IEnumerable _socialAuthProviders = new List() { "Facebook", "Google", "Twitter", "LiveID" }; - - #endregion - - #region Public Properties - + private readonly IEnumerable _socialAuthProviders = new List() { "Facebook", "Google", "Twitter", "LiveID" }; + public override bool CanEditProviderProperties { get { return false; } @@ -65,6 +56,7 @@ public override bool CanEditProviderProperties public override int MaxInvalidPasswordAttempts { get { return System.Web.Security.Membership.MaxInvalidPasswordAttempts; } + set { throw new NotSupportedException( @@ -75,6 +67,7 @@ public override int MaxInvalidPasswordAttempts public override int MinNonAlphanumericCharacters { get { return System.Web.Security.Membership.MinRequiredNonAlphanumericCharacters; } + set { throw new NotSupportedException( @@ -85,6 +78,7 @@ public override int MinNonAlphanumericCharacters public override int MinPasswordLength { get { return System.Web.Security.Membership.MinRequiredPasswordLength; } + set { throw new NotSupportedException( @@ -95,6 +89,7 @@ public override int MinPasswordLength public override int PasswordAttemptWindow { get { return System.Web.Security.Membership.PasswordAttemptWindow; } + set { throw new NotSupportedException( @@ -116,6 +111,7 @@ public override PasswordFormat PasswordFormat return PasswordFormat.Clear; } } + set { throw new NotSupportedException( @@ -126,6 +122,7 @@ public override PasswordFormat PasswordFormat public override bool PasswordResetEnabled { get { return System.Web.Security.Membership.EnablePasswordReset; } + set { throw new NotSupportedException( @@ -136,6 +133,7 @@ public override bool PasswordResetEnabled public override bool PasswordRetrievalEnabled { get { return System.Web.Security.Membership.EnablePasswordRetrieval; } + set { throw new NotSupportedException( @@ -146,6 +144,7 @@ public override bool PasswordRetrievalEnabled public override string PasswordStrengthRegularExpression { get { return System.Web.Security.Membership.PasswordStrengthRegularExpression; } + set { throw new NotSupportedException( @@ -156,6 +155,7 @@ public override string PasswordStrengthRegularExpression public override bool RequiresQuestionAndAnswer { get { return System.Web.Security.Membership.RequiresQuestionAndAnswer; } + set { throw new NotSupportedException( @@ -166,109 +166,176 @@ public override bool RequiresQuestionAndAnswer public override bool RequiresUniqueEmail { get { return System.Web.Security.Membership.Provider.RequiresUniqueEmail; } + set { throw new NotSupportedException( "Provider properties for AspNetMembershipProvider must be set in web.config"); } + } + + public static ArrayList FillUserCollection(int portalId, IDataReader dr) + { + // Note: the DataReader returned from this method should contain 2 result sets. The first set + // contains the TotalRecords, that satisfy the filter, the second contains the page + // of data + var arrUsers = new ArrayList(); + try + { + while (dr.Read()) + { + // fill business object + UserInfo user = FillUserInfo(portalId, dr, false); + + // add to collection + arrUsers.Add(user); + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } + + return arrUsers; + } + + public override UserInfo GetUserByAuthToken(int portalId, string userToken, string authType) + { + IDataReader dr = this._dataProvider.GetUserByAuthToken(portalId, userToken, authType); + UserInfo objUserInfo = FillUserInfo(portalId, dr, true); + return objUserInfo; + } + + /// + /// add new userportal record (used for creating sites with existing user). + /// + /// portalid. + /// userid. + public override void AddUserPortal(int portalId, int userId) + { + Requires.NotNullOrEmpty("portalId", portalId.ToString()); + Requires.NotNullOrEmpty("userId", userId.ToString()); + this._dataProvider.AddUserPortal(portalId, userId); } - #endregion + /// + /// function supports the ability change username. + /// + /// user id. + /// updated username. + public override void ChangeUsername(int userId, string newUsername) + { + Requires.NotNull("userId", userId); + Requires.NotNullOrEmpty("newUsername", newUsername); + + var userName = PortalSecurity.Instance.InputFilter( + newUsername, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + + if (!userName.Equals(newUsername)) + { + throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); + } + + var valid = UserController.Instance.IsValidUserName(userName); + + if (!valid) + { + throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); + } + + // read all the user account settings + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (portalSettings != null) + { + var settings = UserController.GetUserSettings(portalSettings.PortalId); + + // User Name Validation + var userNameValidator = this.GetStringSetting(settings, "Security_UserNameValidation"); + if (!string.IsNullOrEmpty(userNameValidator)) + { + var regExp = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); + var matches = regExp.Matches(userName); + if (matches.Count == 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); + } + } + } + + this._dataProvider.ChangeUsername(userId, userName); - #region Private Methods + EventLogController.Instance.AddLog( + "userId", + userId.ToString(), + portalSettings, + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.USERNAME_UPDATED); + DataCache.ClearCache(); + } + private static bool AutoUnlockUser(MembershipUser aspNetUser) { if (Host.AutoAccountUnlockDuration != 0) { if (aspNetUser.LastLockoutDate < DateTime.Now.AddMinutes(-1 * Host.AutoAccountUnlockDuration)) { - //Unlock user in Data Store + // Unlock user in Data Store if (aspNetUser.UnlockUser()) { return true; } } } + return false; } - private UserCreateStatus CreateDNNUser(ref UserInfo user) - { - var objSecurity = PortalSecurity.Instance; - var filterFlags = PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup; - user.Username = objSecurity.InputFilter(user.Username, filterFlags); - user.Email = objSecurity.InputFilter(user.Email, filterFlags); - user.LastName = objSecurity.InputFilter(user.LastName, filterFlags); - user.FirstName = objSecurity.InputFilter(user.FirstName, filterFlags); - user.DisplayName = objSecurity.InputFilter(user.DisplayName, filterFlags); - if (user.DisplayName.Contains("<") || user.DisplayName.Contains(">")) - { - user.DisplayName = HttpUtility.HtmlEncode(user.DisplayName); - } - var updatePassword = user.Membership.UpdatePassword; - var isApproved = user.Membership.Approved; - var createStatus = UserCreateStatus.Success; - try - { - user.UserID = - Convert.ToInt32(_dataProvider.AddUser(user.PortalID, - user.Username, - user.FirstName, - user.LastName, - user.AffiliateID, - user.IsSuperUser, - user.Email, - user.DisplayName, - updatePassword, - isApproved, - UserController.Instance.GetCurrentUserInfo().UserID)); - - //Save the user password history - new MembershipPasswordController().IsPasswordInHistory(user.UserID, user.PortalID, user.Membership.Password); - } - catch (Exception ex) - { - //Clear User (duplicate User information) - Exceptions.LogException(ex); - user = null; - createStatus = UserCreateStatus.ProviderError; - } - return createStatus; - } - private static UserCreateStatus CreateMemberhipUser(UserInfo user) { var portalSecurity = PortalSecurity.Instance; - string userName = portalSecurity.InputFilter(user.Username, - PortalSecurity.FilterFlag.NoScripting | + string userName = portalSecurity.InputFilter( + user.Username, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - string email = portalSecurity.InputFilter(user.Email, - PortalSecurity.FilterFlag.NoScripting | + string email = portalSecurity.InputFilter( + user.Email, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); MembershipCreateStatus status; if (MembershipProviderConfig.RequiresQuestionAndAnswer) { - System.Web.Security.Membership.CreateUser(userName, - user.Membership.Password, - email, - user.Membership.PasswordQuestion, - user.Membership.PasswordAnswer, - true, - out status); + System.Web.Security.Membership.CreateUser( + userName, + user.Membership.Password, + email, + user.Membership.PasswordQuestion, + user.Membership.PasswordAnswer, + true, + out status); } else { - System.Web.Security.Membership.CreateUser(userName, - user.Membership.Password, - email, - null, - null, - true, - out status); + System.Web.Security.Membership.CreateUser( + userName, + user.Membership.Password, + email, + null, + null, + true, + out status); } + var createStatus = UserCreateStatus.Success; switch (status) { @@ -306,6 +373,7 @@ private static UserCreateStatus CreateMemberhipUser(UserInfo user) createStatus = UserCreateStatus.UserRejected; break; } + return createStatus; } @@ -321,9 +389,56 @@ private static void DeleteMembershipUser(UserInfo user) } } + private UserCreateStatus CreateDNNUser(ref UserInfo user) + { + var objSecurity = PortalSecurity.Instance; + var filterFlags = PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup; + user.Username = objSecurity.InputFilter(user.Username, filterFlags); + user.Email = objSecurity.InputFilter(user.Email, filterFlags); + user.LastName = objSecurity.InputFilter(user.LastName, filterFlags); + user.FirstName = objSecurity.InputFilter(user.FirstName, filterFlags); + user.DisplayName = objSecurity.InputFilter(user.DisplayName, filterFlags); + if (user.DisplayName.Contains("<") || user.DisplayName.Contains(">")) + { + user.DisplayName = HttpUtility.HtmlEncode(user.DisplayName); + } + + var updatePassword = user.Membership.UpdatePassword; + var isApproved = user.Membership.Approved; + var createStatus = UserCreateStatus.Success; + try + { + user.UserID = + Convert.ToInt32(this._dataProvider.AddUser( + user.PortalID, + user.Username, + user.FirstName, + user.LastName, + user.AffiliateID, + user.IsSuperUser, + user.Email, + user.DisplayName, + updatePassword, + isApproved, + UserController.Instance.GetCurrentUserInfo().UserID)); + + // Save the user password history + new MembershipPasswordController().IsPasswordInHistory(user.UserID, user.PortalID, user.Membership.Password); + } + catch (Exception ex) + { + // Clear User (duplicate User information) + Exceptions.LogException(ex); + user = null; + createStatus = UserCreateStatus.ProviderError; + } + + return createStatus; + } + private static ArrayList FillUserCollection(int portalId, IDataReader dr, ref int totalRecords) { - //Note: the DataReader returned from this method should contain 2 result sets. The first set + // Note: the DataReader returned from this method should contain 2 result sets. The first set // contains the TotalRecords, that satisfy the filter, the second contains the page // of data var arrUsers = new ArrayList(); @@ -331,15 +446,17 @@ private static ArrayList FillUserCollection(int portalId, IDataReader dr, ref in { while (dr.Read()) { - //fill business object + // fill business object UserInfo user = FillUserInfo(portalId, dr, false); - //add to collection + + // add to collection arrUsers.Add(user); } - //Get the next result (containing the total) + + // Get the next result (containing the total) dr.NextResult(); - //Get the total no of records from the second result + // Get the total no of records from the second result totalRecords = Globals.GetTotalRecords(ref dr); } catch (Exception exc) @@ -348,9 +465,10 @@ private static ArrayList FillUserCollection(int portalId, IDataReader dr, ref in } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } + return arrUsers; } @@ -361,9 +479,10 @@ private static IList FillUserList(int portalId, IDataReader dr) { while (dr.Read()) { - //fill business object + // fill business object UserInfo user = FillUserAndProfile(portalId, dr); - //add to collection + + // add to collection users.Add(user); } } @@ -373,18 +492,19 @@ private static IList FillUserList(int portalId, IDataReader dr) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } + return users; } private static UserInfo FillUserAndProfile(int portalId, IDataReader dr) { UserInfo user = null; - bool bContinue = (String.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase)); + bool bContinue = string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase); - //Ensure the data reader returned is valid + // Ensure the data reader returned is valid if (bContinue) { user = new UserInfo @@ -396,7 +516,7 @@ private static UserInfo FillUserAndProfile(int portalId, IDataReader dr) DisplayName = Null.SetNullString(dr["DisplayName"]), Username = Null.SetNullString(dr["Username"]), Email = Null.SetNullString(dr["Email"]), - AffiliateID = Null.SetNullInteger(dr["AffiliateID"]) + AffiliateID = Null.SetNullInteger(dr["AffiliateID"]), }; user.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], user.AffiliateID)); @@ -406,6 +526,7 @@ private static UserInfo FillUserAndProfile(int portalId, IDataReader dr) { user.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); } + if (user.PortalID == Null.NullInteger) { user.PortalID = portalId; @@ -440,7 +561,7 @@ private static UserInfo FillUserAndProfile(int portalId, IDataReader dr) case "PasswordResetExpiration": break; default: - //Probably a profile property + // Probably a profile property string name = dr.GetName(i); userProfile.SetProfileProperty(name, Null.SetNullString(dr[name])); break; @@ -449,6 +570,7 @@ private static UserInfo FillUserAndProfile(int portalId, IDataReader dr) user.Profile = userProfile; } + return user; } @@ -457,20 +579,21 @@ private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDat UserInfo user = null; try { - //read datareader + // read datareader bool bContinue = true; if (closeDataReader) { bContinue = false; if (dr.Read()) { - //Ensure the data reader returned is valid + // Ensure the data reader returned is valid if (string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase)) { bContinue = true; } } } + if (bContinue) { user = new UserInfo @@ -479,7 +602,7 @@ private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDat IsSuperUser = Null.SetNullBoolean(dr["IsSuperUser"]), UserID = Null.SetNullInteger(dr["UserID"]), DisplayName = Null.SetNullString(dr["DisplayName"]), - LastIPAddress = Null.SetNullString(dr["LastIPAddress"]) + LastIPAddress = Null.SetNullString(dr["LastIPAddress"]), }; var schema = dr.GetSchemaTable(); @@ -489,14 +612,17 @@ private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDat { user.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); } + if (schema.Select("ColumnName = 'VanityUrl'").Length > 0) { user.VanityUrl = Null.SetNullString(dr["VanityUrl"]); } + if (schema.Select("ColumnName = 'HasAgreedToTerms'").Length > 0) { user.HasAgreedToTerms = Null.SetNullBoolean(dr["HasAgreedToTerms"]); } + if (schema.Select("ColumnName = 'HasAgreedToTermsOn'").Length > 0) { user.HasAgreedToTermsOn = Null.SetNullDateTime(dr["HasAgreedToTermsOn"]); @@ -505,14 +631,17 @@ private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDat { user.HasAgreedToTermsOn = Null.NullDate; } + if (schema.Select("ColumnName = 'RequestsRemoval'").Length > 0) { user.RequestsRemoval = Null.SetNullBoolean(dr["RequestsRemoval"]); } + if (schema.Select("ColumnName = 'PasswordResetExpiration'").Length > 0) { user.PasswordResetExpiration = Null.SetNullDateTime(dr["PasswordResetExpiration"]); } + if (schema.Select("ColumnName = 'PasswordResetToken'").Length > 0) { user.PasswordResetToken = Null.SetNullGuid(dr["PasswordResetToken"]); @@ -529,6 +658,7 @@ private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDat { user.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); } + if (user.PortalID == Null.NullInteger) { user.PortalID = portalId; @@ -541,18 +671,20 @@ private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDat { CBO.CloseDataReader(dr, closeDataReader); } + return user; } private static void FillUserMembership(MembershipUser aspNetUser, UserInfo user) { - //Fill Membership Property + // Fill Membership Property if (aspNetUser != null) { if (user.Membership == null) { user.Membership = new UserMembership(user); } + user.Membership.CreatedDate = aspNetUser.CreationDate; user.Membership.LastActivityDate = aspNetUser.LastActivityDate; user.Membership.LastLockoutDate = aspNetUser.LastLockoutDate; @@ -564,7 +696,7 @@ private static void FillUserMembership(MembershipUser aspNetUser, UserInfo user) if (user.IsSuperUser) { - //For superusers the Approved info is stored in aspnet membership + // For superusers the Approved info is stored in aspnet membership user.Membership.Approved = aspNetUser.IsApproved; } } @@ -610,23 +742,16 @@ private static object GetMembershipUserByUserKeyCallBack(CacheItemArgs cacheItem return System.Web.Security.Membership.GetUser(new Guid(userKey)); } - - public override UserInfo GetUserByAuthToken(int portalId, string userToken, string authType) - { - IDataReader dr = _dataProvider.GetUserByAuthToken(portalId, userToken, authType); - UserInfo objUserInfo = FillUserInfo(portalId, dr, true); - return objUserInfo; - } - private static void UpdateUserMembership(UserInfo user) { var portalSecurity = PortalSecurity.Instance; - string email = portalSecurity.InputFilter(user.Email, - PortalSecurity.FilterFlag.NoScripting | + string email = portalSecurity.InputFilter( + user.Email, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - //Persist the Membership Properties to the AspNet Data Store + // Persist the Membership Properties to the AspNet Data Store MembershipUser membershipUser = System.Web.Security.Membership.GetUser(user.Username); membershipUser.Email = email; membershipUser.LastActivityDate = DateTime.Now; @@ -687,6 +812,7 @@ private static UserLoginStatus ValidateLogin(string username, string authType, U } } } + return loginStatus; } @@ -698,83 +824,11 @@ private static bool ValidateUser(string username, string password) private string GetStringSetting(Hashtable settings, string settingKey) { return settings[settingKey] == null ? string.Empty : settings[settingKey].ToString(); - } - - #endregion - - #region Public Methods - /// - /// add new userportal record (used for creating sites with existing user) - /// - /// portalid - /// userid - public override void AddUserPortal(int portalId, int userId) - { - Requires.NotNullOrEmpty("portalId", portalId.ToString()); - Requires.NotNullOrEmpty("userId", userId.ToString()); - _dataProvider.AddUserPortal(portalId, userId); - } - - /// - /// function supports the ability change username - /// - /// user id - /// updated username - public override void ChangeUsername(int userId, string newUsername) - { - Requires.NotNull("userId", userId); - Requires.NotNullOrEmpty("newUsername", newUsername); - - var userName = PortalSecurity.Instance.InputFilter(newUsername, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - - if (!userName.Equals(newUsername)) - { - throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); - } - - var valid = UserController.Instance.IsValidUserName(userName); - - if (!valid) - { - throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); - } - - //read all the user account settings - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (portalSettings != null) - { - var settings = UserController.GetUserSettings(portalSettings.PortalId); - - //User Name Validation - var userNameValidator = GetStringSetting(settings, "Security_UserNameValidation"); - if (!string.IsNullOrEmpty(userNameValidator)) - { - var regExp = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); - var matches = regExp.Matches(userName); - if (matches.Count == 0) - { - throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); - } - } - } - - _dataProvider.ChangeUsername(userId, userName); - - EventLogController.Instance.AddLog("userId", - userId.ToString(), - portalSettings, - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.USERNAME_UPDATED); - - DataCache.ClearCache(); - } + } /// ----------------------------------------------------------------------------- /// - /// ChangePassword attempts to change the users password + /// ChangePassword attempts to change the users password. /// /// /// @@ -798,8 +852,9 @@ public override bool ChangePassword(UserInfo user, string oldPassword, string ne aspnetUser.UnlockUser(); oldPassword = aspnetUser.GetPassword(); } + bool retValue = aspnetUser.ChangePassword(oldPassword, newPassword); - if (retValue && PasswordRetrievalEnabled && !RequiresQuestionAndAnswer) + if (retValue && this.PasswordRetrievalEnabled && !this.RequiresQuestionAndAnswer) { string confirmPassword = aspnetUser.GetPassword(); if (confirmPassword == newPassword) @@ -811,13 +866,14 @@ public override bool ChangePassword(UserInfo user, string oldPassword, string ne retValue = false; } } + return retValue; } /// ----------------------------------------------------------------------------- /// /// ChangePasswordQuestionAndAnswer attempts to change the users password Question - /// and PasswordAnswer + /// and PasswordAnswer. /// /// /// @@ -835,53 +891,13 @@ public override bool ChangePasswordQuestionAndAnswer(UserInfo user, string passw { password = aspnetUser.GetPassword(); } + return aspnetUser.ChangePasswordQuestionAndAnswer(password, passwordQuestion, passwordAnswer); } - private UserCreateStatus ValidateForProfanity(UserInfo user) - { - var portalSecurity = PortalSecurity.Instance; - var createStatus = UserCreateStatus.AddUser; - - Hashtable settings = UserController.GetUserSettings(user.PortalID); - bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"]); - - //Validate Profanity - if (useProfanityFilter) - { - if (!portalSecurity.ValidateInput(user.Username, PortalSecurity.FilterFlag.NoProfanity)) - { - createStatus = UserCreateStatus.InvalidUserName; - } - if (!String.IsNullOrEmpty(user.DisplayName)) - { - if (!portalSecurity.ValidateInput(user.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) - { - createStatus = UserCreateStatus.InvalidDisplayName; - } - } - } - return createStatus; - } - - private void ValidateForDuplicateDisplayName(UserInfo user, ref UserCreateStatus createStatus) - { - Hashtable settings = UserController.GetUserSettings(user.PortalID); - bool requireUniqueDisplayName = Convert.ToBoolean(settings["Registration_RequireUniqueDisplayName"]); - - if (requireUniqueDisplayName) - { - UserInfo duplicateUser = GetUserByDisplayName(user.PortalID, user.DisplayName); - if (duplicateUser != null) - { - createStatus = UserCreateStatus.DuplicateDisplayName; - } - } - } - /// ----------------------------------------------------------------------------- /// - /// CreateUser persists a User to the Data Store + /// CreateUser persists a User to the Data Store. /// /// /// @@ -890,28 +906,28 @@ private void ValidateForDuplicateDisplayName(UserInfo user, ref UserCreateStatus /// ----------------------------------------------------------------------------- public override UserCreateStatus CreateUser(ref UserInfo user) { - UserCreateStatus createStatus = ValidateForProfanity(user); + UserCreateStatus createStatus = this.ValidateForProfanity(user); string service = HttpContext.Current != null ? HttpContext.Current.Request.Params["state"] : string.Empty; if (createStatus == UserCreateStatus.AddUser) { - ValidateForDuplicateDisplayName(user, ref createStatus); + this.ValidateForDuplicateDisplayName(user, ref createStatus); } if (createStatus == UserCreateStatus.AddUser) { try { - //check if username exists in database for any portal - UserInfo objVerifyUser = GetUserByUserName(Null.NullInteger, user.Username); + // check if username exists in database for any portal + UserInfo objVerifyUser = this.GetUserByUserName(Null.NullInteger, user.Username); if (objVerifyUser != null) { - //DNN-4016 - //the username exists so we should now verify the password, DNN-4016 or check for oauth user authentication. + // DNN-4016 + // the username exists so we should now verify the password, DNN-4016 or check for oauth user authentication. if (ValidateUser(user.Username, user.Membership.Password)) { - //check if user exists for the portal specified - objVerifyUser = GetUserByUserName(user.PortalID, user.Username); + // check if user exists for the portal specified + objVerifyUser = this.GetUserByUserName(user.PortalID, user.Username); if (objVerifyUser != null) { if (objVerifyUser.PortalID == user.PortalID && (!user.IsSuperUser || user.PortalID == Null.NullInteger)) @@ -920,7 +936,7 @@ public override UserCreateStatus CreateUser(ref UserInfo user) } else { - //SuperUser who is not part of portal + // SuperUser who is not part of portal createStatus = UserCreateStatus.AddUserToPortal; } } @@ -931,36 +947,36 @@ public override UserCreateStatus CreateUser(ref UserInfo user) } else { - //not the same person - prevent registration + // not the same person - prevent registration createStatus = UserCreateStatus.UsernameAlreadyExists; } } else { - //the user does not exist + // the user does not exist createStatus = UserCreateStatus.AddUser; } - //If new user - add to aspnet membership + // If new user - add to aspnet membership if (createStatus == UserCreateStatus.AddUser) { createStatus = CreateMemberhipUser(user); } - //If asp user has been successfully created or we are adding a existing user - //to a new portal + // If asp user has been successfully created or we are adding a existing user + // to a new portal if (createStatus == UserCreateStatus.Success || createStatus == UserCreateStatus.AddUserToPortal) { - //Create the DNN User Record - createStatus = CreateDNNUser(ref user); + // Create the DNN User Record + createStatus = this.CreateDNNUser(ref user); if (createStatus == UserCreateStatus.Success) { - //Persist the Profile to the Data Store + // Persist the Profile to the Data Store ProfileController.UpdateUserProfile(user); } } } - catch (Exception exc) //an unexpected error occurred + catch (Exception exc) // an unexpected error occurred { Exceptions.LogException(exc); createStatus = UserCreateStatus.UnexpectedError; @@ -972,7 +988,7 @@ public override UserCreateStatus CreateUser(ref UserInfo user) /// ----------------------------------------------------------------------------- /// - /// DeleteUser deletes a single User from the Data Store + /// DeleteUser deletes a single User from the Data Store. /// /// /// @@ -984,83 +1000,127 @@ public override bool DeleteUser(UserInfo user) bool retValue = true; try { - _dataProvider.DeleteUserFromPortal(user.UserID, user.PortalID); + this._dataProvider.DeleteUserFromPortal(user.UserID, user.PortalID); } catch (Exception ex) { Exceptions.LogException(ex); retValue = false; } + return retValue; } + private UserCreateStatus ValidateForProfanity(UserInfo user) + { + var portalSecurity = PortalSecurity.Instance; + var createStatus = UserCreateStatus.AddUser; + + Hashtable settings = UserController.GetUserSettings(user.PortalID); + bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"]); + + // Validate Profanity + if (useProfanityFilter) + { + if (!portalSecurity.ValidateInput(user.Username, PortalSecurity.FilterFlag.NoProfanity)) + { + createStatus = UserCreateStatus.InvalidUserName; + } + + if (!string.IsNullOrEmpty(user.DisplayName)) + { + if (!portalSecurity.ValidateInput(user.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) + { + createStatus = UserCreateStatus.InvalidDisplayName; + } + } + } + + return createStatus; + } + + private void ValidateForDuplicateDisplayName(UserInfo user, ref UserCreateStatus createStatus) + { + Hashtable settings = UserController.GetUserSettings(user.PortalID); + bool requireUniqueDisplayName = Convert.ToBoolean(settings["Registration_RequireUniqueDisplayName"]); + + if (requireUniqueDisplayName) + { + UserInfo duplicateUser = this.GetUserByDisplayName(user.PortalID, user.DisplayName); + if (duplicateUser != null) + { + createStatus = UserCreateStatus.DuplicateDisplayName; + } + } + } + /// ----------------------------------------------------------------------------- /// /// Deletes all UserOnline inof from the database that has activity outside of the - /// time window + /// time window. /// /// /// - /// Time Window in Minutes + /// Time Window in Minutes. /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public override void DeleteUsersOnline(int timeWindow) { - _dataProvider.DeleteUsersOnline(timeWindow); + this._dataProvider.DeleteUsersOnline(timeWindow); } /// ----------------------------------------------------------------------------- /// - /// Generates a new random password (Length = Minimum Length + 4) + /// Generates a new random password (Length = Minimum Length + 4). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public override string GeneratePassword() { - return GeneratePassword(MinPasswordLength + 4); + return this.GeneratePassword(this.MinPasswordLength + 4); } /// ----------------------------------------------------------------------------- /// - /// Generates a new random password + /// Generates a new random password. /// /// The length of password to generate. - /// A String + /// A String. /// ----------------------------------------------------------------------------- public override string GeneratePassword(int length) { - return System.Web.Security.Membership.GeneratePassword(length, MinNonAlphanumericCharacters); + return System.Web.Security.Membership.GeneratePassword(length, this.MinNonAlphanumericCharacters); } public override ArrayList GetDeletedUsers(int portalId) { - return FillUserCollection(portalId, _dataProvider.GetDeletedUsers(portalId)); + return FillUserCollection(portalId, this._dataProvider.GetDeletedUsers(portalId)); } /// ----------------------------------------------------------------------------- /// - /// Gets a collection of Online Users + /// Gets a collection of Online Users. /// - /// The Id of the Portal - /// An ArrayList of UserInfo objects + /// The Id of the Portal. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public override ArrayList GetOnlineUsers(int portalId) { int totalRecords = 0; - return FillUserCollection(portalId, _dataProvider.GetOnlineUsers(portalId), ref totalRecords); + return FillUserCollection(portalId, this._dataProvider.GetOnlineUsers(portalId), ref totalRecords); } /// ----------------------------------------------------------------------------- /// - /// Gets the Current Password Information for the User + /// Gets the Current Password Information for the User. /// /// /// /// The user to delete from the Data Store. /// The answer to the Password Question, ues to confirm the user /// has the right to obtain the password. - /// A String + /// A String. /// ----------------------------------------------------------------------------- public override string GetPassword(UserInfo user, string passwordAnswer) { @@ -1069,50 +1129,52 @@ public override string GetPassword(UserInfo user, string passwordAnswer) { AutoUnlockUser(aspnetUser); } - return RequiresQuestionAndAnswer ? aspnetUser.GetPassword(passwordAnswer) : aspnetUser.GetPassword(); + + return this.RequiresQuestionAndAnswer ? aspnetUser.GetPassword(passwordAnswer) : aspnetUser.GetPassword(); } public override ArrayList GetUnAuthorizedUsers(int portalId) { - return GetUnAuthorizedUsers(portalId, false, false); + return this.GetUnAuthorizedUsers(portalId, false, false); } public override ArrayList GetUnAuthorizedUsers(int portalId, bool includeDeleted, bool superUsersOnly) { - return FillUserCollection(portalId, - _dataProvider.GetUnAuthorizedUsers(portalId, includeDeleted, superUsersOnly)); + return FillUserCollection( + portalId, + this._dataProvider.GetUnAuthorizedUsers(portalId, includeDeleted, superUsersOnly)); } /// ----------------------------------------------------------------------------- /// - /// GetUserByUserName retrieves a User from the DataStore + /// GetUserByUserName retrieves a User from the DataStore. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The id of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public override UserInfo GetUser(int portalId, int userId) { - IDataReader dr = _dataProvider.GetUser(portalId, userId); + IDataReader dr = this._dataProvider.GetUser(portalId, userId); UserInfo objUserInfo = FillUserInfo(portalId, dr, true); return objUserInfo; } /// ----------------------------------------------------------------------------- /// - /// GetUserByDisplayName retrieves a User from the DataStore + /// GetUserByDisplayName retrieves a User from the DataStore. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The displayName of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public override UserInfo GetUserByDisplayName(int portalId, string displayName) { - IDataReader dr = _dataProvider.GetUserByDisplayName(portalId, displayName); + IDataReader dr = this._dataProvider.GetUserByDisplayName(portalId, displayName); UserInfo objUserInfo = FillUserInfo(portalId, dr, true); return objUserInfo; } @@ -1123,61 +1185,64 @@ public override UserInfo GetUserByDisplayName(int portalId, string displayName) /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The username of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public override UserInfo GetUserByUserName(int portalId, string username) { var objUserInfo = CBO.GetCachedObject( - new CacheItemArgs(string.Format(DataCache.UserCacheKey, portalId, username), + new CacheItemArgs( + string.Format(DataCache.UserCacheKey, portalId, username), DataCache.UserCacheTimeOut, DataCache.UserCachePriority), _ => { - return GetUserByUserNameFromDataStore(portalId, username); + return this.GetUserByUserNameFromDataStore(portalId, username); }); return objUserInfo; } /// ----------------------------------------------------------------------------- /// - /// GetUserByVanityUrl retrieves a User from the DataStore + /// GetUserByVanityUrl retrieves a User from the DataStore. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The vanityUrl of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public override UserInfo GetUserByVanityUrl(int portalId, string vanityUrl) { UserInfo user = null; - if (!String.IsNullOrEmpty(vanityUrl)) + if (!string.IsNullOrEmpty(vanityUrl)) { - IDataReader dr = _dataProvider.GetUserByVanityUrl(portalId, vanityUrl); + IDataReader dr = this._dataProvider.GetUserByVanityUrl(portalId, vanityUrl); user = FillUserInfo(portalId, dr, true); } + return user; } /// ----------------------------------------------------------------------------- /// - /// GetUserByPasswordResetToken retrieves a User from the DataStore + /// GetUserByPasswordResetToken retrieves a User from the DataStore. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The password reset token. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public override UserInfo GetUserByPasswordResetToken(int portalId, string resetToken) { UserInfo user = null; - if (!String.IsNullOrEmpty(resetToken)) + if (!string.IsNullOrEmpty(resetToken)) { - IDataReader dr = _dataProvider.GetUserByPasswordResetToken(portalId, resetToken); + IDataReader dr = this._dataProvider.GetUserByPasswordResetToken(portalId, resetToken); user = FillUserInfo(portalId, dr, true); } + return user; } @@ -1194,26 +1259,26 @@ public override UserInfo GetUserByProviderUserKey(int portalId, string providerU return null; } - return GetUserByUserName(portalId, userName); + return this.GetUserByUserName(portalId, userName); } /// ----------------------------------------------------------------------------- /// - /// GetUserCountByPortal gets the number of users in the portal + /// GetUserCountByPortal gets the number of users in the portal. /// /// /// - /// The Id of the Portal - /// The no of users + /// The Id of the Portal. + /// The no of users. /// ----------------------------------------------------------------------------- public override int GetUserCountByPortal(int portalId) { - return _dataProvider.GetUserCountByPortal(portalId); + return this._dataProvider.GetUserCountByPortal(portalId); } /// ----------------------------------------------------------------------------- /// - /// GetUserMembership retrieves the UserMembership information from the Data Store + /// GetUserMembership retrieves the UserMembership information from the Data Store. /// /// /// @@ -1221,40 +1286,40 @@ public override int GetUserCountByPortal(int portalId) /// ----------------------------------------------------------------------------- public override void GetUserMembership(ref UserInfo user) { - //Get AspNet MembershipUser + // Get AspNet MembershipUser MembershipUser aspnetUser = GetMembershipUser(user); - //Fill Membership Property + // Fill Membership Property FillUserMembership(aspnetUser, user); - //Get Online Status - user.Membership.IsOnLine = IsUserOnline(user); + // Get Online Status + user.Membership.IsOnLine = this.IsUserOnline(user); } /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal + /// GetUsers gets all the users of the portal. /// - /// If all records are required, (ie no paging) set pageSize = -1 - /// The Id of the Portal + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords) { - return GetUsers(portalId, pageIndex, pageSize, ref totalRecords, false, false); + return this.GetUsers(portalId, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal + /// GetUsers gets all the users of the portal. /// - /// If all records are required, (ie no paging) set pageSize = -1 - /// The Id of the Portal + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include deleted users. /// Only select super users. @@ -1269,12 +1334,12 @@ public override ArrayList GetUsers(int portalId, int pageIndex, int pageSize, re pageSize = int.MaxValue; } - return FillUserCollection(portalId, _dataProvider.GetAllUsers(portalId, pageIndex, pageSize, includeDeleted, + return FillUserCollection(portalId, this._dataProvider.GetAllUsers(portalId, pageIndex, pageSize, includeDeleted, superUsersOnly), ref totalRecords); } /// - /// + /// /// /// /// @@ -1296,15 +1361,16 @@ public override IList GetUsersAdvancedSearch(int portalId, int userId, bool sortAscending, string propertyNames, string propertyValues) { - return FillUserList(portalId, - _dataProvider.GetUsersAdvancedSearch(portalId, userId, filterUserId, filterRoleId, + return FillUserList( + portalId, + this._dataProvider.GetUsersAdvancedSearch(portalId, userId, filterUserId, filterRoleId, relationshipTypeId, isAdmin, pageIndex, pageSize, sortColumn, sortAscending, propertyNames, propertyValues)); } /// - /// + /// /// /// /// @@ -1318,7 +1384,7 @@ public override IList GetUsersBasicSearch(int portalId, int pageIndex, bool sortAscending, string propertyName, string propertyValue) { - return FillUserList(portalId, _dataProvider.GetUsersBasicSearch(portalId, pageIndex, pageSize, + return FillUserList(portalId, this._dataProvider.GetUsersBasicSearch(portalId, pageIndex, pageSize, sortColumn, sortAscending, propertyName, propertyValue)); } @@ -1326,32 +1392,32 @@ public override IList GetUsersBasicSearch(int portalId, int pageIndex, /// ----------------------------------------------------------------------------- /// /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression + /// filter expression. /// - /// If all records are required, (ie no paging) set pageSize = -1 - /// The Id of the Portal + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. /// The email address to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, ref int totalRecords) { - return GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, ref totalRecords, false, false); + return this.GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression + /// filter expression. /// - /// If all records are required, (ie no paging) set pageSize = -1 - /// The Id of the Portal + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. /// The email address to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include deleted users. /// Only select super users. @@ -1366,40 +1432,41 @@ public override ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageSize = int.MaxValue; } - return FillUserCollection(portalId, - _dataProvider.GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, + return FillUserCollection( + portalId, + this._dataProvider.GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, includeDeleted, superUsersOnly), ref totalRecords); } /// ----------------------------------------------------------------------------- /// /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression + /// filter expression. /// - /// If all records are required, (ie no paging) set pageSize = -1 - /// The Id of the Portal + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. /// The username to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords) { - return GetUsersByUserName(portalId, userNameToMatch, pageIndex, pageSize, ref totalRecords, false, false); + return this.GetUsersByUserName(portalId, userNameToMatch, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression + /// filter expression. /// - /// If all records are required, (ie no paging) set pageSize = -1 - /// The Id of the Portal + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. /// The username to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include deleted users. /// Only select super users. @@ -1414,21 +1481,22 @@ public override ArrayList GetUsersByUserName(int portalId, string userNameToMatc pageSize = int.MaxValue; } - return FillUserCollection(portalId, - _dataProvider.GetUsersByUsername(portalId, userNameToMatch, pageIndex, pageSize, + return FillUserCollection( + portalId, + this._dataProvider.GetUsersByUsername(portalId, userNameToMatch, pageIndex, pageSize, includeDeleted, superUsersOnly), ref totalRecords); } /// ----------------------------------------------------------------------------- /// /// GetUsersByDisplayName gets all the users of the portal whose display name matches a provided - /// filter expression + /// filter expression. /// - /// If all records are required, (ie no paging) set pageSize = -1 - /// The Id of the Portal + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. /// The display name to use to find a match. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include deleted users. /// Only select super users. @@ -1443,45 +1511,46 @@ public override ArrayList GetUsersByDisplayName(int portalId, string nameToMatch pageSize = int.MaxValue; } - return FillUserCollection(portalId, - _dataProvider.GetUsersByDisplayname(portalId, nameToMatch, pageIndex, pageSize, + return FillUserCollection( + portalId, + this._dataProvider.GetUsersByDisplayname(portalId, nameToMatch, pageIndex, pageSize, includeDeleted, superUsersOnly), ref totalRecords); } /// ----------------------------------------------------------------------------- /// /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter + /// the profile property pased as a parameter. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The name of the property being matched. /// The value of the property being matched. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords) { - return GetUsersByProfileProperty(portalId, propertyName, propertyValue, pageIndex, pageSize, + return this.GetUsersByProfileProperty(portalId, propertyName, propertyValue, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter + /// the profile property pased as a parameter. /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The name of the property being matched. /// The value of the property being matched. /// The page of records to return. - /// The size of the page + /// The size of the page. /// The total no of records that satisfy the criteria. /// Include deleted users. /// Only select super users. @@ -1497,15 +1566,16 @@ public override ArrayList GetUsersByProfileProperty(int portalId, string propert pageSize = int.MaxValue; } - return FillUserCollection(portalId, - _dataProvider.GetUsersByProfileProperty(portalId, propertyName, propertyValue, + return FillUserCollection( + portalId, + this._dataProvider.GetUsersByProfileProperty(portalId, propertyName, propertyValue, pageIndex, pageSize, includeDeleted, superUsersOnly), ref totalRecords); } /// ----------------------------------------------------------------------------- /// - /// Gets whether the user in question is online + /// Gets whether the user in question is online. /// /// /// @@ -1527,14 +1597,15 @@ public override bool IsUserOnline(UserInfo user) } else { - //Next try the Database - onlineUser = CBO.FillObject(_dataProvider.GetOnlineUser(user.UserID)); + // Next try the Database + onlineUser = CBO.FillObject(this._dataProvider.GetOnlineUser(user.UserID)); if (onlineUser != null) { isOnline = true; } } } + return isOnline; } @@ -1549,10 +1620,10 @@ public override bool RemoveUser(UserInfo user) RelationshipController.Instance.DeleteUserRelationship(relationship); } - _dataProvider.RemoveUser(user.UserID, user.PortalID); + this._dataProvider.RemoveUser(user.UserID, user.PortalID); - //Prior to removing membership, ensure user is not present in any other portal - UserInfo otherUser = GetUserByUserNameFromDataStore(Null.NullInteger, user.Username); + // Prior to removing membership, ensure user is not present in any other portal + UserInfo otherUser = this.GetUserByUserNameFromDataStore(Null.NullInteger, user.Username); if (otherUser == null) { DeleteMembershipUser(user); @@ -1569,7 +1640,7 @@ public override bool RemoveUser(UserInfo user) /// ----------------------------------------------------------------------------- /// - /// ResetPassword resets a user's password and returns the newly created password + /// ResetPassword resets a user's password and returns the newly created password. /// /// /// @@ -1579,39 +1650,40 @@ public override bool RemoveUser(UserInfo user) /// ----------------------------------------------------------------------------- public override string ResetPassword(UserInfo user, string passwordAnswer) { - //Get AspNet MembershipUser + // Get AspNet MembershipUser MembershipUser aspnetUser = GetMembershipUser(user); - return RequiresQuestionAndAnswer ? aspnetUser.ResetPassword(passwordAnswer) : aspnetUser.ResetPassword(); + return this.RequiresQuestionAndAnswer ? aspnetUser.ResetPassword(passwordAnswer) : aspnetUser.ResetPassword(); } /// /// function sets user specific password reset token and timeout /// works for all PasswordFormats as it resets and then changes the password /// so old password is not required - /// method does not support RequiresQuestionAndAnswer + /// method does not support RequiresQuestionAndAnswer. /// - /// + /// + /// public override bool ResetAndChangePassword(UserInfo user, string newPassword) { - return ResetAndChangePassword(user, newPassword, string.Empty); + return this.ResetAndChangePassword(user, newPassword, string.Empty); } public override bool ResetAndChangePassword(UserInfo user, string newPassword, string answer) { - if (RequiresQuestionAndAnswer && string.IsNullOrEmpty(answer)) + if (this.RequiresQuestionAndAnswer && string.IsNullOrEmpty(answer)) { return false; } - //Get AspNet MembershipUser + // Get AspNet MembershipUser MembershipUser aspnetUser = GetMembershipUser(user); if (aspnetUser.IsLockedOut) { aspnetUser.UnlockUser(); } - string resetPassword = ResetPassword(user, answer); + string resetPassword = this.ResetPassword(user, answer); return aspnetUser.ChangePassword(resetPassword, newPassword); } @@ -1621,7 +1693,7 @@ public override bool RestoreUser(UserInfo user) try { - _dataProvider.RestoreUser(user.UserID, user.PortalID); + this._dataProvider.RestoreUser(user.UserID, user.PortalID); } catch (Exception ex) { @@ -1634,7 +1706,7 @@ public override bool RestoreUser(UserInfo user) /// ----------------------------------------------------------------------------- /// - /// Unlocks the User's Account + /// Unlocks the User's Account. /// /// /// @@ -1649,13 +1721,14 @@ public override bool UnLockUser(UserInfo user) { retValue = membershipUser.UnlockUser(); } + DataCache.RemoveCache(GetCacheKey(user.Username)); return retValue; } /// ----------------------------------------------------------------------------- /// - /// User has agreed to terms and conditions for the portal + /// User has agreed to terms and conditions for the portal. /// /// /// @@ -1663,12 +1736,12 @@ public override bool UnLockUser(UserInfo user) /// ----------------------------------------------------------------------------- public override void UserAgreedToTerms(UserInfo user) { - _dataProvider.UserAgreedToTerms(PortalController.GetEffectivePortalId(user.PortalID), user.UserID); + this._dataProvider.UserAgreedToTerms(PortalController.GetEffectivePortalId(user.PortalID), user.UserID); } /// ----------------------------------------------------------------------------- /// - /// Reset all agreements on portal so all users need to agree again at next login + /// Reset all agreements on portal so all users need to agree again at next login. /// /// /// @@ -1676,30 +1749,22 @@ public override void UserAgreedToTerms(UserInfo user) /// ----------------------------------------------------------------------------- public override void ResetTermsAgreement(int portalId) { - _dataProvider.ResetTermsAgreement(portalId); - } - - private static Random random = new Random(); - private string RandomString(int length) - { - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - return new string(Enumerable.Repeat(chars, length) - .Select(s => s[random.Next(s.Length)]).ToArray()); + this._dataProvider.ResetTermsAgreement(portalId); } /// - /// Sets a boolean on the user portal to indicate this user has requested that their account be deleted + /// Sets a boolean on the user portal to indicate this user has requested that their account be deleted. /// - /// User requesting removal + /// User requesting removal. /// True if user requests removal, false if the value needs to be reset. public override void UserRequestsRemoval(UserInfo user, bool remove) { - _dataProvider.UserRequestsRemoval(user.PortalID, user.UserID, remove); + this._dataProvider.UserRequestsRemoval(user.PortalID, user.UserID, remove); } /// ----------------------------------------------------------------------------- /// - /// UpdateUser persists a user to the Data Store + /// UpdateUser persists a user to the Data Store. /// /// /// @@ -1708,20 +1773,24 @@ public override void UserRequestsRemoval(UserInfo user, bool remove) public override void UpdateUser(UserInfo user) { var objSecurity = PortalSecurity.Instance; - string firstName = objSecurity.InputFilter(user.FirstName, - PortalSecurity.FilterFlag.NoScripting | + string firstName = objSecurity.InputFilter( + user.FirstName, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - string lastName = objSecurity.InputFilter(user.LastName, - PortalSecurity.FilterFlag.NoScripting | + string lastName = objSecurity.InputFilter( + user.LastName, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - string email = objSecurity.InputFilter(user.Email, - PortalSecurity.FilterFlag.NoScripting | + string email = objSecurity.InputFilter( + user.Email, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - string displayName = objSecurity.InputFilter(user.DisplayName, - PortalSecurity.FilterFlag.NoScripting | + string displayName = objSecurity.InputFilter( + user.DisplayName, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); if (displayName.Contains("<")) @@ -1741,112 +1810,120 @@ public override void UpdateUser(UserInfo user) bool updatePassword = user.Membership.UpdatePassword; bool isApproved = user.Membership.Approved; - if (String.IsNullOrEmpty(displayName)) + if (string.IsNullOrEmpty(displayName)) { displayName = firstName + " " + lastName; } - //Persist the Membership to the Data Store + // Persist the Membership to the Data Store UpdateUserMembership(user); - //Persist the DNN User to the Database - _dataProvider.UpdateUser(user.UserID, - user.PortalID, - firstName, - lastName, - user.IsSuperUser, - email, - displayName, - user.VanityUrl, - updatePassword, - isApproved, - false, - user.LastIPAddress, - user.PasswordResetToken, - user.PasswordResetExpiration, - user.IsDeleted, - UserController.Instance.GetCurrentUserInfo().UserID); - - //Persist the Profile to the Data Store + // Persist the DNN User to the Database + this._dataProvider.UpdateUser( + user.UserID, + user.PortalID, + firstName, + lastName, + user.IsSuperUser, + email, + displayName, + user.VanityUrl, + updatePassword, + isApproved, + false, + user.LastIPAddress, + user.PasswordResetToken, + user.PasswordResetExpiration, + user.IsDeleted, + UserController.Instance.GetCurrentUserInfo().UserID); + + // Persist the Profile to the Data Store ProfileController.UpdateUserProfile(user); } + + private string RandomString(int length) + { + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + return new string(Enumerable.Repeat(chars, length) + .Select(s => s[random.Next(s.Length)]).ToArray()); + } /// ----------------------------------------------------------------------------- /// /// Updates UserOnline info - /// time window + /// time window. /// - /// List of users to update + /// List of users to update. /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public override void UpdateUsersOnline(Hashtable userList) { - _dataProvider.UpdateUsersOnline(userList); + this._dataProvider.UpdateUsersOnline(userList); } /// ----------------------------------------------------------------------------- /// - /// UserLogin attempts to log the user in, and returns the User if successful + /// UserLogin attempts to log the user in, and returns the User if successful. /// /// /// - /// The Id of the Portal the user belongs to - /// The user name of the User attempting to log in - /// The password of the User attempting to log in - /// The verification code of the User attempting to log in + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The verification code of the User attempting to log in. /// An enumerated value indicating the login status. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public override UserInfo UserLogin(int portalId, string username, string password, string verificationCode, ref UserLoginStatus loginStatus) { - return UserLogin(portalId, username, password, "DNN", verificationCode, ref loginStatus); + return this.UserLogin(portalId, username, password, "DNN", verificationCode, ref loginStatus); } /// ----------------------------------------------------------------------------- /// - /// UserLogin attempts to log the user in, and returns the User if successful + /// UserLogin attempts to log the user in, and returns the User if successful. /// /// /// - /// The Id of the Portal the user belongs to - /// The user name of the User attempting to log in - /// The password of the User attempting to log in (may not be used by all Auth types) - /// The type of Authentication Used - /// The verification code of the User attempting to log in + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in (may not be used by all Auth types). + /// The type of Authentication Used. + /// The verification code of the User attempting to log in. /// An enumerated value indicating the login status. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- public override UserInfo UserLogin(int portalId, string username, string password, string authType, string verificationCode, ref UserLoginStatus loginStatus) { - //For now, we are going to ignore the possibility that the User may exist in the - //Global Data Store but not in the Local DataStore ie. A shared Global Data Store + // For now, we are going to ignore the possibility that the User may exist in the + // Global Data Store but not in the Local DataStore ie. A shared Global Data Store - //Initialise Login Status to Failure + // Initialise Login Status to Failure loginStatus = UserLoginStatus.LOGIN_FAILURE; DataCache.ClearUserCache(portalId, username); DataCache.ClearCache(GetCacheKey(username)); - //Get a light-weight (unhydrated) DNN User from the Database, we will hydrate it later if neccessary + // Get a light-weight (unhydrated) DNN User from the Database, we will hydrate it later if neccessary UserInfo user = (authType == "DNN") - ? GetUserByUserName(portalId, username) - : GetUserByAuthToken(portalId, verificationCode, authType); + ? this.GetUserByUserName(portalId, username) + : this.GetUserByAuthToken(portalId, verificationCode, authType); if (user != null && !user.IsDeleted) { - //Get AspNet MembershipUser + // Get AspNet MembershipUser MembershipUser aspnetUser = GetMembershipUser(user); - //Fill Membership Property from AspNet MembershipUser + // Fill Membership Property from AspNet MembershipUser FillUserMembership(aspnetUser, user); - //Check if the User is Locked Out (and unlock if AutoUnlock has expired) + // Check if the User is Locked Out (and unlock if AutoUnlock has expired) if (aspnetUser.IsLockedOut) { if (AutoUnlockUser(aspnetUser)) { - //Unlock User + // Unlock User user.Membership.LockedOut = false; } else @@ -1855,12 +1932,11 @@ public override UserInfo UserLogin(int portalId, string username, string passwor } } - //Check in a verified situation whether the user is Approved + // Check in a verified situation whether the user is Approved if (user.Membership.Approved == false && user.IsSuperUser == false) { - - //Check Verification code (skip for FB, Google, Twitter, LiveID as it has no verification code) - if (_socialAuthProviders.Contains(authType) && String.IsNullOrEmpty(verificationCode)) + // Check Verification code (skip for FB, Google, Twitter, LiveID as it has no verification code) + if (this._socialAuthProviders.Contains(authType) && string.IsNullOrEmpty(verificationCode)) { if (PortalController.Instance.GetCurrentPortalSettings().UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) @@ -1886,24 +1962,23 @@ public override UserInfo UserLogin(int portalId, string username, string passwor loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED; } } - } - //Verify User Credentials + // Verify User Credentials bool bValid = false; loginStatus = ValidateLogin(username, authType, user, loginStatus, password, ref bValid, portalId); if (!bValid) { - //Clear the user object + // Clear the user object user = null; - //Clear cache for user so that locked out & other status could be updated + // Clear cache for user so that locked out & other status could be updated DataCache.ClearUserCache(portalId, username); DataCache.ClearCache(GetCacheKey(username)); aspnetUser = System.Web.Security.Membership.GetUser(username); - // If user has been locked out for current invalid attempt + // If user has been locked out for current invalid attempt // return locked out status if (aspnetUser.IsLockedOut) { @@ -1913,41 +1988,12 @@ public override UserInfo UserLogin(int portalId, string username, string passwor } else { - //Clear the user object + // Clear the user object user = null; } + return user; - } - - #endregion - - public static ArrayList FillUserCollection(int portalId, IDataReader dr) - { - //Note: the DataReader returned from this method should contain 2 result sets. The first set - // contains the TotalRecords, that satisfy the filter, the second contains the page - // of data - var arrUsers = new ArrayList(); - try - { - while (dr.Read()) - { - //fill business object - UserInfo user = FillUserInfo(portalId, dr, false); - //add to collection - arrUsers.Add(user); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - //close datareader - CBO.CloseDataReader(dr, true); - } - return arrUsers; - } + } /// ----------------------------------------------------------------------------- /// @@ -1955,13 +2001,13 @@ public static ArrayList FillUserCollection(int portalId, IDataReader dr) /// /// /// - /// The Id of the Portal + /// The Id of the Portal. /// The username of the user being retrieved from the Data Store. - /// The User as a UserInfo object + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- private UserInfo GetUserByUserNameFromDataStore(int portalId, string username) { - using (var dr = _dataProvider.GetUserByUsername(portalId, username)) + using (var dr = this._dataProvider.GetUserByUsername(portalId, username)) { return FillUserInfo(portalId, dr, true); } diff --git a/DNN Platform/Library/Security/Membership/MembershipProvider.cs b/DNN Platform/Library/Security/Membership/MembershipProvider.cs index 626c1293f2e..ba8c9942378 100644 --- a/DNN Platform/Library/Security/Membership/MembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/MembershipProvider.cs @@ -1,79 +1,94 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Membership { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Users; + public abstract class MembershipProvider - { - #region Abstract Properties - - public abstract bool CanEditProviderProperties { get; } + { + public abstract bool CanEditProviderProperties { get; } + public abstract int MaxInvalidPasswordAttempts { get; set; } + public abstract int MinPasswordLength { get; set; } + public abstract int MinNonAlphanumericCharacters { get; set; } + public abstract int PasswordAttemptWindow { get; set; } + public abstract PasswordFormat PasswordFormat { get; set; } + public abstract bool PasswordResetEnabled { get; set; } + public abstract bool PasswordRetrievalEnabled { get; set; } + public abstract string PasswordStrengthRegularExpression { get; set; } + public abstract bool RequiresQuestionAndAnswer { get; set; } - public abstract bool RequiresUniqueEmail { get; set; } - - #endregion - - #region Shared/Static Methods - - //return the provider - public static MembershipProvider Instance() + + public abstract bool RequiresUniqueEmail { get; set; } + + // return the provider + public static MembershipProvider Instance() { return ComponentFactory.GetComponent(); - } - - #endregion - - #region Abstract Methods - - // Users + } + + // Users public abstract bool ChangePassword(UserInfo user, string oldPassword, string newPassword); + public abstract bool ChangePasswordQuestionAndAnswer(UserInfo user, string password, string passwordQuestion, string passwordAnswer); + public abstract UserCreateStatus CreateUser(ref UserInfo user); + public abstract bool DeleteUser(UserInfo user); + public abstract bool RestoreUser(UserInfo user); + public abstract bool RemoveUser(UserInfo user); + public abstract string GeneratePassword(); + public abstract string GeneratePassword(int length); + public abstract string GetPassword(UserInfo user, string passwordAnswer); + public abstract int GetUserCountByPortal(int portalId); + public abstract void GetUserMembership(ref UserInfo user); + public abstract string ResetPassword(UserInfo user, string passwordAnswer); + public abstract bool UnLockUser(UserInfo user); + public abstract void UserAgreedToTerms(UserInfo user); + public abstract void ResetTermsAgreement(int portalId); + public abstract void UserRequestsRemoval(UserInfo user, bool remove); + public abstract void UpdateUser(UserInfo user); + public abstract UserInfo UserLogin(int portalId, string username, string password, string verificationCode, ref UserLoginStatus loginStatus); + public abstract UserInfo UserLogin(int portalId, string username, string password, string authType, string verificationCode, ref UserLoginStatus loginStatus); // Users Online - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public abstract void DeleteUsersOnline(int TimeWindow); + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public abstract ArrayList GetOnlineUsers(int PortalId); + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public abstract bool IsUserOnline(UserInfo user); + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public abstract void UpdateUsersOnline(Hashtable UserList); @@ -84,23 +99,26 @@ public virtual void TransferUsersToMembershipProvider() // Get Users public abstract UserInfo GetUser(int portalId, int userId); + public abstract UserInfo GetUserByUserName(int portalId, string username); + public abstract ArrayList GetUnAuthorizedUsers(int portalId); + public abstract ArrayList GetDeletedUsers(int portalId); - public abstract ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords); + + public abstract ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords); + public abstract ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, ref int totalRecords); - public abstract ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords); - public abstract ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords); - - #endregion - - #region Virtual Methods - + + public abstract ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords); + + public abstract ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords); + public virtual UserInfo GetUserByDisplayName(int portalId, string displayName) { return null; } - + public virtual UserInfo GetUserByVanityUrl(int portalId, string vanityUrl) { return null; @@ -141,10 +159,10 @@ public virtual ArrayList GetUsersByUserName(int portalId, string userNameToMatch throw new NotImplementedException(); } - public virtual ArrayList GetUsersByDisplayName(int portalId, string nameToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) - { - throw new NotImplementedException(); - } + public virtual ArrayList GetUsersByDisplayName(int portalId, string nameToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) + { + throw new NotImplementedException(); + } public virtual ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) { @@ -160,7 +178,7 @@ public virtual IList GetUsersAdvancedSearch(int portalId, int userId, bool isAdmin, int pageIndex, int pageSize, string sortColumn, bool sortAscending, string propertyNames, string propertyValues) { - throw new NotImplementedException(); + throw new NotImplementedException(); } public virtual IList GetUsersBasicSearch(int portalId, int pageIndex, int pageSize, string sortColumn, @@ -174,12 +192,11 @@ public virtual bool ResetAndChangePassword(UserInfo user, string newPassword) throw new NotImplementedException(); } - public virtual bool ResetAndChangePassword(UserInfo user, string newPassword, string answer) - { - throw new NotImplementedException(); - } - - + public virtual bool ResetAndChangePassword(UserInfo user, string newPassword, string answer) + { + throw new NotImplementedException(); + } + public virtual void ChangeUsername(int userId, string newUsername) { throw new NotImplementedException(); @@ -188,9 +205,6 @@ public virtual void ChangeUsername(int userId, string newUsername) public virtual void AddUserPortal(int portalId, int userId) { throw new NotImplementedException(); - } - - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs b/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs index 07b14e89e90..650a9a0d694 100644 --- a/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs +++ b/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; - -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Membership { + using System.ComponentModel; + + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Membership @@ -19,26 +14,20 @@ namespace DotNetNuke.Security.Membership /// ----------------------------------------------------------------------------- /// /// The MembershipProviderConfig class provides a wrapper to the Membership providers - /// configuration + /// configuration. /// /// /// /// ----------------------------------------------------------------------------- public class MembershipProviderConfig - { - #region "Private Shared Members" - - private static readonly MembershipProvider memberProvider = MembershipProvider.Instance(); - - #endregion - - #region "Public Shared Properties" - + { + private static readonly MembershipProvider memberProvider = MembershipProvider.Instance(); + /// ----------------------------------------------------------------------------- /// - /// Gets whether the Provider Properties can be edited + /// Gets a value indicating whether gets whether the Provider Properties can be edited. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- [Browsable(false)] public static bool CanEditProviderProperties @@ -51,17 +40,19 @@ public static bool CanEditProviderProperties /// ----------------------------------------------------------------------------- /// - /// Gets and sets the maximum number of invlaid attempts to login are allowed + /// Gets or sets and sets the maximum number of invlaid attempts to login are allowed. /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(8), Category("Password")] + [SortOrder(8)] + [Category("Password")] public static int MaxInvalidPasswordAttempts { get { return memberProvider.MaxInvalidPasswordAttempts; } + set { memberProvider.MaxInvalidPasswordAttempts = value; @@ -70,17 +61,19 @@ public static int MaxInvalidPasswordAttempts /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Mimimum no of Non AlphNumeric characters required + /// Gets or sets and sets the Mimimum no of Non AlphNumeric characters required. /// /// An Integer. /// ----------------------------------------------------------------------------- - [SortOrder(5), Category("Password")] + [SortOrder(5)] + [Category("Password")] public static int MinNonAlphanumericCharacters { get { return memberProvider.MinNonAlphanumericCharacters; } + set { memberProvider.MinNonAlphanumericCharacters = value; @@ -89,17 +82,19 @@ public static int MinNonAlphanumericCharacters /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Mimimum Password Length + /// Gets or sets and sets the Mimimum Password Length. /// /// An Integer. /// ----------------------------------------------------------------------------- - [SortOrder(4), Category("Password")] + [SortOrder(4)] + [Category("Password")] public static int MinPasswordLength { get { return memberProvider.MinPasswordLength; } + set { memberProvider.MinPasswordLength = value; @@ -108,17 +103,19 @@ public static int MinPasswordLength /// ----------------------------------------------------------------------------- /// - /// Gets and sets the window in minutes that the maxium attempts are tracked for + /// Gets or sets and sets the window in minutes that the maxium attempts are tracked for. /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(9), Category("Password")] + [SortOrder(9)] + [Category("Password")] public static int PasswordAttemptWindow { get { return memberProvider.PasswordAttemptWindow; } + set { memberProvider.PasswordAttemptWindow = value; @@ -127,17 +124,19 @@ public static int PasswordAttemptWindow /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Password Format + /// Gets or sets and sets the Password Format. /// /// A PasswordFormat enumeration. /// ----------------------------------------------------------------------------- - [SortOrder(1), Category("Password")] + [SortOrder(1)] + [Category("Password")] public static PasswordFormat PasswordFormat { get { return memberProvider.PasswordFormat; } + set { memberProvider.PasswordFormat = value; @@ -146,17 +145,19 @@ public static PasswordFormat PasswordFormat /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Users's Password can be reset + /// Gets or sets a value indicating whether gets and sets whether the Users's Password can be reset. /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(3), Category("Password")] + [SortOrder(3)] + [Category("Password")] public static bool PasswordResetEnabled { get { return memberProvider.PasswordResetEnabled; } + set { memberProvider.PasswordResetEnabled = value; @@ -165,24 +166,27 @@ public static bool PasswordResetEnabled /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Users's Password can be retrieved + /// Gets or sets a value indicating whether gets and sets whether the Users's Password can be retrieved. /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(2), Category("Password")] + [SortOrder(2)] + [Category("Password")] public static bool PasswordRetrievalEnabled { get { bool enabled = memberProvider.PasswordRetrievalEnabled; - //If password format is hashed the password cannot be retrieved + // If password format is hashed the password cannot be retrieved if (memberProvider.PasswordFormat == PasswordFormat.Hashed) { enabled = false; } + return enabled; } + set { memberProvider.PasswordRetrievalEnabled = value; @@ -191,17 +195,19 @@ public static bool PasswordRetrievalEnabled /// ----------------------------------------------------------------------------- /// - /// Gets and sets a Regular Expression that determines the strength of the password + /// Gets or sets and sets a Regular Expression that determines the strength of the password. /// /// A String. /// ----------------------------------------------------------------------------- - [SortOrder(7), Category("Password")] + [SortOrder(7)] + [Category("Password")] public static string PasswordStrengthRegularExpression { get { return memberProvider.PasswordStrengthRegularExpression; } + set { memberProvider.PasswordStrengthRegularExpression = value; @@ -210,17 +216,19 @@ public static string PasswordStrengthRegularExpression /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether a Question/Answer is required for Password retrieval + /// Gets or sets a value indicating whether gets and sets whether a Question/Answer is required for Password retrieval. /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(6), Category("Password")] + [SortOrder(6)] + [Category("Password")] public static bool RequiresQuestionAndAnswer { get { return memberProvider.RequiresQuestionAndAnswer; } + set { memberProvider.RequiresQuestionAndAnswer = value; @@ -229,23 +237,23 @@ public static bool RequiresQuestionAndAnswer /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether a Unique Email is required + /// Gets or sets a value indicating whether gets and sets whether a Unique Email is required. /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(0), Category("User")] + [SortOrder(0)] + [Category("User")] public static bool RequiresUniqueEmail { get { return memberProvider.RequiresUniqueEmail; } + set { memberProvider.RequiresUniqueEmail = value; - } - - #endregion + } } } } diff --git a/DNN Platform/Library/Security/Membership/PasswordConfig.cs b/DNN Platform/Library/Security/Membership/PasswordConfig.cs index 16c21f5d597..fbe95d7456c 100644 --- a/DNN Platform/Library/Security/Membership/PasswordConfig.cs +++ b/DNN Platform/Library/Security/Membership/PasswordConfig.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; - -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Membership { + using System.ComponentModel; + + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Membership /// Class: PasswordConfig /// ----------------------------------------------------------------------------- /// - /// The PasswordConfig class provides a wrapper any Portal wide Password Settings + /// The PasswordConfig class provides a wrapper any Portal wide Password Settings. /// /// /// @@ -29,17 +24,19 @@ public class PasswordConfig { /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Password Expiry time in days + /// Gets or sets and sets the Password Expiry time in days. /// /// An integer. /// ----------------------------------------------------------------------------- - [SortOrder(0), Category("Password")] + [SortOrder(0)] + [Category("Password")] public static int PasswordExpiry { get { return Host.PasswordExpiry; } + set { HostController.Instance.Update("PasswordExpiry", value.ToString()); @@ -48,18 +45,20 @@ public static int PasswordExpiry /// ----------------------------------------------------------------------------- /// - /// Gets and sets the a Reminder time in days (to remind the user that theire password - /// is about to expire + /// Gets or sets and sets the a Reminder time in days (to remind the user that theire password + /// is about to expire. /// /// An integer. /// ----------------------------------------------------------------------------- - [SortOrder(1), Category("Password")] + [SortOrder(1)] + [Category("Password")] public static int PasswordExpiryReminder { get { return Host.PasswordExpiryReminder; } + set { HostController.Instance.Update("PasswordExpiryReminder", value.ToString()); diff --git a/DNN Platform/Library/Security/Membership/PasswordFormat.cs b/DNN Platform/Library/Security/Membership/PasswordFormat.cs index b31a1b07ce3..f56b83768bb 100644 --- a/DNN Platform/Library/Security/Membership/PasswordFormat.cs +++ b/DNN Platform/Library/Security/Membership/PasswordFormat.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Membership { public enum PasswordFormat { Clear = 0, Hashed = 1, - Encrypted = 2 + Encrypted = 2, } } diff --git a/DNN Platform/Library/Security/Membership/PasswordUpdateStatus.cs b/DNN Platform/Library/Security/Membership/PasswordUpdateStatus.cs index dfae92c84c0..0adcea83efb 100644 --- a/DNN Platform/Library/Security/Membership/PasswordUpdateStatus.cs +++ b/DNN Platform/Library/Security/Membership/PasswordUpdateStatus.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Membership { public enum PasswordUpdateStatus @@ -14,6 +14,6 @@ public enum PasswordUpdateStatus PasswordMismatch, InvalidPasswordAnswer, InvalidPasswordQuestion, - BannedPasswordUsed + BannedPasswordUsed, } } diff --git a/DNN Platform/Library/Security/Membership/UserCreateStatus.cs b/DNN Platform/Library/Security/Membership/UserCreateStatus.cs index 91fd0e5fcf1..cf2ca0822bc 100644 --- a/DNN Platform/Library/Security/Membership/UserCreateStatus.cs +++ b/DNN Platform/Library/Security/Membership/UserCreateStatus.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Membership { public enum UserCreateStatus @@ -28,6 +28,6 @@ public enum UserCreateStatus DuplicateDisplayName = 19, BannedPasswordUsed = 20, InvalidFirstName = 21, - InvalidLastName = 22 + InvalidLastName = 22, } } diff --git a/DNN Platform/Library/Security/Membership/UserLoginStatus.cs b/DNN Platform/Library/Security/Membership/UserLoginStatus.cs index 9de1b03f58a..cebb50e3c62 100644 --- a/DNN Platform/Library/Security/Membership/UserLoginStatus.cs +++ b/DNN Platform/Library/Security/Membership/UserLoginStatus.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Membership { public enum UserLoginStatus @@ -12,6 +12,6 @@ public enum UserLoginStatus LOGIN_USERLOCKEDOUT = 3, LOGIN_USERNOTAPPROVED = 4, LOGIN_INSECUREADMINPASSWORD = 5, - LOGIN_INSECUREHOSTPASSWORD = 6 + LOGIN_INSECUREHOSTPASSWORD = 6, } } diff --git a/DNN Platform/Library/Security/Membership/UserRegistrationStatus.cs b/DNN Platform/Library/Security/Membership/UserRegistrationStatus.cs index 314c3457b15..d51a6b2c969 100644 --- a/DNN Platform/Library/Security/Membership/UserRegistrationStatus.cs +++ b/DNN Platform/Library/Security/Membership/UserRegistrationStatus.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Membership { public enum UserRegistrationStatus @@ -10,6 +10,6 @@ public enum UserRegistrationStatus AddUserRoles = -1, UsernameAlreadyExists = -2, UserAlreadyRegistered = -3, - UnexpectedError = -4 + UnexpectedError = -4, } } diff --git a/DNN Platform/Library/Security/Membership/UserValidStatus.cs b/DNN Platform/Library/Security/Membership/UserValidStatus.cs index 73a72cce5f1..8160d2ef6eb 100644 --- a/DNN Platform/Library/Security/Membership/UserValidStatus.cs +++ b/DNN Platform/Library/Security/Membership/UserValidStatus.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Membership { public enum UserValidStatus @@ -11,6 +11,6 @@ public enum UserValidStatus PASSWORDEXPIRING = 2, UPDATEPROFILE = 3, UPDATEPASSWORD = 4, - MUSTAGREETOTERMS = 5 + MUSTAGREETOTERMS = 5, } } diff --git a/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs b/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs index 4382bad402d..bbee31214ce 100644 --- a/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs @@ -1,34 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System.Collections; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : CompareDesktopModulePermissions + /// Class : CompareDesktopModulePermissions /// ----------------------------------------------------------------------------- /// /// CompareDesktopModulePermissions provides the a custom IComparer implementation for - /// DesktopModulePermissionInfo objects + /// DesktopModulePermissionInfo objects. /// /// ----------------------------------------------------------------------------- internal class CompareDesktopModulePermissions : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { - return ((DesktopModulePermissionInfo) x).DesktopModulePermissionID.CompareTo(((DesktopModulePermissionInfo) y).DesktopModulePermissionID); - } - - #endregion + return ((DesktopModulePermissionInfo)x).DesktopModulePermissionID.CompareTo(((DesktopModulePermissionInfo)y).DesktopModulePermissionID); + } } } diff --git a/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs b/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs index 03583ea4756..41ebb8aa594 100644 --- a/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs @@ -1,34 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System.Collections; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : CompareTabPermissions + /// Class : CompareTabPermissions /// ----------------------------------------------------------------------------- /// /// CompareTabPermissions provides the a custom IComparer implementation for - /// TabPermissionInfo objects + /// TabPermissionInfo objects. /// /// ----------------------------------------------------------------------------- internal class CompareFolderPermissions : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { - return ((FolderPermissionInfo) x).FolderPermissionID.CompareTo(((FolderPermissionInfo) y).FolderPermissionID); - } - - #endregion + return ((FolderPermissionInfo)x).FolderPermissionID.CompareTo(((FolderPermissionInfo)y).FolderPermissionID); + } } } diff --git a/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs b/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs index 89e61729720..1765e696a26 100644 --- a/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs @@ -1,34 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System.Collections; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : CompareModulePermissions + /// Class : CompareModulePermissions /// ----------------------------------------------------------------------------- /// /// CompareModulePermissions provides the a custom IComparer implementation for - /// ModulePermissionInfo objects + /// ModulePermissionInfo objects. /// /// ----------------------------------------------------------------------------- internal class CompareModulePermissions : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { - return ((ModulePermissionInfo) x).ModulePermissionID.CompareTo(((ModulePermissionInfo) y).ModulePermissionID); - } - - #endregion + return ((ModulePermissionInfo)x).ModulePermissionID.CompareTo(((ModulePermissionInfo)y).ModulePermissionID); + } } } diff --git a/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs b/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs index 968b299a607..4fa5ca8f11e 100644 --- a/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs @@ -1,34 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System.Collections; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : CompareTabPermissions + /// Class : CompareTabPermissions /// ----------------------------------------------------------------------------- /// /// CompareTabPermissions provides the a custom IComparer implementation for - /// TabPermissionInfo objects + /// TabPermissionInfo objects. /// /// ----------------------------------------------------------------------------- internal class CompareTabPermissions : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { - return ((TabPermissionInfo) x).TabPermissionID.CompareTo(((TabPermissionInfo) y).TabPermissionID); - } - - #endregion + return ((TabPermissionInfo)x).TabPermissionID.CompareTo(((TabPermissionInfo)y).TabPermissionID); + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs index 58e63da916e..1884d249a53 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs @@ -1,160 +1,115 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions.Controls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + public class DesktopModulePermissionsGrid : PermissionsGrid - { - #region "Private Members" - + { private DesktopModulePermissionCollection _DesktopModulePermissions; private List _PermissionsList; - private int _PortalDesktopModuleID = -1; - - #endregion - - #region "Protected Properties" - - protected override List PermissionsList - { - get - { - if (_PermissionsList == null && _DesktopModulePermissions != null) - { - _PermissionsList = _DesktopModulePermissions.ToList(); - } - return _PermissionsList; - } - } - - #endregion - - #region "Public Properties" - + private int _PortalDesktopModuleID = -1; + /// ----------------------------------------------------------------------------- /// - /// Gets the Permissions Collection + /// Gets the Permissions Collection. /// /// ----------------------------------------------------------------------------- public DesktopModulePermissionCollection Permissions { get { - //First Update Permissions in case they have been changed - UpdatePermissions(); + // First Update Permissions in case they have been changed + this.UpdatePermissions(); - //Return the DesktopModulePermissions - return _DesktopModulePermissions; + // Return the DesktopModulePermissions + return this._DesktopModulePermissions; } } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Id of the PortalDesktopModule + /// Gets or sets and Sets the Id of the PortalDesktopModule. /// /// ----------------------------------------------------------------------------- public int PortalDesktopModuleID { get { - return _PortalDesktopModuleID; + return this._PortalDesktopModuleID; } + set { - int oldValue = _PortalDesktopModuleID; - _PortalDesktopModuleID = value; - if (_DesktopModulePermissions == null || oldValue != value) + int oldValue = this._PortalDesktopModuleID; + this._PortalDesktopModuleID = value; + if (this._DesktopModulePermissions == null || oldValue != value) { - GetDesktopModulePermissions(); + this.GetDesktopModulePermissions(); } } - } - - #endregion - - #region "Private Methods" - - /// ----------------------------------------------------------------------------- - /// - /// Gets the DesktopModulePermissions from the Data Store - /// - /// ----------------------------------------------------------------------------- - private void GetDesktopModulePermissions() - { - _DesktopModulePermissions = new DesktopModulePermissionCollection(DesktopModulePermissionController.GetDesktopModulePermissions(PortalDesktopModuleID)); - } - - /// ----------------------------------------------------------------------------- - /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState - /// - /// A string array of settings - /// ----------------------------------------------------------------------------- - private DesktopModulePermissionInfo ParseKeys(string[] Settings) + } + + protected override List PermissionsList { - var objDesktopModulePermission = new DesktopModulePermissionInfo(); - - //Call base class to load base properties - base.ParsePermissionKeys(objDesktopModulePermission, Settings); - if (String.IsNullOrEmpty(Settings[2])) - { - objDesktopModulePermission.DesktopModulePermissionID = -1; - } - else + get { - objDesktopModulePermission.DesktopModulePermissionID = Convert.ToInt32(Settings[2]); + if (this._PermissionsList == null && this._DesktopModulePermissions != null) + { + this._PermissionsList = this._DesktopModulePermissions.ToList(); + } + + return this._PermissionsList; } - objDesktopModulePermission.PortalDesktopModuleID = PortalDesktopModuleID; - return objDesktopModulePermission; + } + + public void ResetPermissions() + { + this.GetDesktopModulePermissions(); + this._PermissionsList = null; } - #endregion - - #region "Protected Methods" - + public override void GenerateDataGrid() + { + } + protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) { var objPermission = new DesktopModulePermissionInfo(permission); - objPermission.PortalDesktopModuleID = PortalDesktopModuleID; + objPermission.PortalDesktopModuleID = this.PortalDesktopModuleID; objPermission.RoleID = roleId; objPermission.RoleName = roleName; objPermission.AllowAccess = allowAccess; objPermission.UserID = userId; objPermission.DisplayName = displayName; - _DesktopModulePermissions.Add(objPermission, true); + this._DesktopModulePermissions.Add(objPermission, true); - //Clear Permission List - _PermissionsList = null; + // Clear Permission List + this._PermissionsList = null; } /// ----------------------------------------------------------------------------- /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The user to add + /// The permissions collection. + /// The user to add. /// ----------------------------------------------------------------------------- protected override void AddPermission(ArrayList permissions, UserInfo user) { - //Search DesktopModulePermission Collection for the user + // Search DesktopModulePermission Collection for the user bool isMatch = false; - foreach (DesktopModulePermissionInfo objDesktopModulePermission in _DesktopModulePermissions) + foreach (DesktopModulePermissionInfo objDesktopModulePermission in this._DesktopModulePermissions) { if (objDesktopModulePermission.UserID == user.UserID) { @@ -163,48 +118,84 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) } } - //user not found so add new + // user not found so add new if (!isMatch) { foreach (PermissionInfo objPermission in permissions) { if (objPermission.PermissionKey == "DEPLOY") { - AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); } } } } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the DesktopModulePermissions from the Data Store. + /// + /// ----------------------------------------------------------------------------- + private void GetDesktopModulePermissions() + { + this._DesktopModulePermissions = new DesktopModulePermissionCollection(DesktopModulePermissionController.GetDesktopModulePermissions(this.PortalDesktopModuleID)); + } + + /// ----------------------------------------------------------------------------- + /// + /// Parse the Permission Keys used to persist the Permissions in the ViewState. + /// + /// A string array of settings. + /// ----------------------------------------------------------------------------- + private DesktopModulePermissionInfo ParseKeys(string[] Settings) + { + var objDesktopModulePermission = new DesktopModulePermissionInfo(); + + // Call base class to load base properties + this.ParsePermissionKeys(objDesktopModulePermission, Settings); + if (string.IsNullOrEmpty(Settings[2])) + { + objDesktopModulePermission.DesktopModulePermissionID = -1; + } + else + { + objDesktopModulePermission.DesktopModulePermissionID = Convert.ToInt32(Settings[2]); + } + + objDesktopModulePermission.PortalDesktopModuleID = this.PortalDesktopModuleID; + return objDesktopModulePermission; + } /// ----------------------------------------------------------------------------- /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The roleto add + /// The permissions collection. + /// The roleto add. /// ----------------------------------------------------------------------------- protected override void AddPermission(ArrayList permissions, RoleInfo role) { - //Search TabPermission Collection for the user - if (_DesktopModulePermissions.Cast().Any(p => p.RoleID == role.RoleID)) + // Search TabPermission Collection for the user + if (this._DesktopModulePermissions.Cast().Any(p => p.RoleID == role.RoleID)) { return; } - //role not found so add new + // role not found so add new foreach (PermissionInfo objPermission in permissions) { if (objPermission.PermissionKey == "DEPLOY") { - AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); + this.AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); } } } /// ----------------------------------------------------------------------------- /// - /// Gets the permissions from the Database - /// + /// Gets the permissions from the Database. + /// + /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() { @@ -213,42 +204,42 @@ protected override ArrayList GetPermissions() /// ----------------------------------------------------------------------------- /// - /// Load the ViewState + /// Load the ViewState. /// - /// The saved state + /// The saved state. /// ----------------------------------------------------------------------------- protected override void LoadViewState(object savedState) { if (savedState != null) { - //Load State from the array of objects that was saved with SaveViewState. + // Load State from the array of objects that was saved with SaveViewState. var myState = (object[])savedState; - //Load Base Controls ViewState + // Load Base Controls ViewState if (myState[0] != null) { base.LoadViewState(myState[0]); } - //Load DesktopModuleId + // Load DesktopModuleId if (myState[1] != null) { - PortalDesktopModuleID = Convert.ToInt32(myState[1]); + this.PortalDesktopModuleID = Convert.ToInt32(myState[1]); } - //Load DesktopModulePermissions + // Load DesktopModulePermissions if (myState[2] != null) { - _DesktopModulePermissions = new DesktopModulePermissionCollection(); + this._DesktopModulePermissions = new DesktopModulePermissionCollection(); string state = Convert.ToString(myState[2]); - if (!String.IsNullOrEmpty(state)) + if (!string.IsNullOrEmpty(state)) { - //First Break the String into individual Keys + // First Break the String into individual Keys string[] permissionKeys = state.Split(new[] { "##" }, StringSplitOptions.None); foreach (string key in permissionKeys) { string[] Settings = key.Split('|'); - _DesktopModulePermissions.Add(ParseKeys(Settings)); + this._DesktopModulePermissions.Add(this.ParseKeys(Settings)); } } } @@ -257,32 +248,34 @@ protected override void LoadViewState(object savedState) protected override void RemovePermission(int permissionID, int roleID, int userID) { - _DesktopModulePermissions.Remove(permissionID, roleID, userID); - //Clear Permission List - _PermissionsList = null; + this._DesktopModulePermissions.Remove(permissionID, roleID, userID); + + // Clear Permission List + this._PermissionsList = null; } /// ----------------------------------------------------------------------------- /// - /// Saves the ViewState - /// + /// Saves the ViewState. + /// + /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() { var allStates = new object[3]; - //Save the Base Controls ViewState + // Save the Base Controls ViewState allStates[0] = base.SaveViewState(); - //Save the DesktopModule Id - allStates[1] = PortalDesktopModuleID; + // Save the DesktopModule Id + allStates[1] = this.PortalDesktopModuleID; - //Persist the DesktopModulePermisisons + // Persist the DesktopModulePermisisons var sb = new StringBuilder(); - if (_DesktopModulePermissions != null) + if (this._DesktopModulePermissions != null) { bool addDelimiter = false; - foreach (DesktopModulePermissionInfo objDesktopModulePermission in _DesktopModulePermissions) + foreach (DesktopModulePermissionInfo objDesktopModulePermission in this._DesktopModulePermissions) { if (addDelimiter) { @@ -292,43 +285,31 @@ protected override object SaveViewState() { addDelimiter = true; } - sb.Append(BuildKey(objDesktopModulePermission.AllowAccess, - objDesktopModulePermission.PermissionID, - objDesktopModulePermission.DesktopModulePermissionID, - objDesktopModulePermission.RoleID, - objDesktopModulePermission.RoleName, - objDesktopModulePermission.UserID, - objDesktopModulePermission.DisplayName)); + + sb.Append(this.BuildKey( + objDesktopModulePermission.AllowAccess, + objDesktopModulePermission.PermissionID, + objDesktopModulePermission.DesktopModulePermissionID, + objDesktopModulePermission.RoleID, + objDesktopModulePermission.RoleName, + objDesktopModulePermission.UserID, + objDesktopModulePermission.DisplayName)); } } + allStates[2] = sb.ToString(); return allStates; } /// ----------------------------------------------------------------------------- /// - /// returns whether or not the derived grid supports Deny permissions - /// + /// returns whether or not the derived grid supports Deny permissions. + /// + /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; - } - - #endregion - - #region "Public Methods" - - public void ResetPermissions() - { - GetDesktopModulePermissions(); - _PermissionsList = null; - } - - public override void GenerateDataGrid() - { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs index d1333c058ba..34008a0b45e 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs @@ -1,129 +1,145 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions.Controls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + public class FolderPermissionsGrid : PermissionsGrid - { - #region Private Members - - private string _folderPath = ""; + { protected FolderPermissionCollection FolderPermissions; + private string _folderPath = string.Empty; private List _permissionsList; private bool _refreshGrid; - private IList _systemFolderPermissions; - - #endregion - - #region Protected Properties - - protected override List PermissionsList - { - get - { - if (_permissionsList == null && FolderPermissions != null) - { - _permissionsList = FolderPermissions.ToList(); - } - return _permissionsList; - } - } - - protected override bool RefreshGrid - { - get - { - return _refreshGrid; - } - } - - #endregion - - #region Public Properties - + private IList _systemFolderPermissions; + /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the path of the Folder + /// Gets or sets and Sets the path of the Folder. /// /// ----------------------------------------------------------------------------- public string FolderPath { get { - return _folderPath; + return this._folderPath; } + set { - _folderPath = value; - _refreshGrid = true; - GetFolderPermissions(); + this._folderPath = value; + this._refreshGrid = true; + this.GetFolderPermissions(); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Permission Collection + /// Gets the Permission Collection. /// /// ----------------------------------------------------------------------------- public FolderPermissionCollection Permissions { get { - //First Update Permissions in case they have been changed - UpdatePermissions(); + // First Update Permissions in case they have been changed + this.UpdatePermissions(); - //Return the FolderPermissions - return FolderPermissions; + // Return the FolderPermissions + return this.FolderPermissions; + } + } + + protected override List PermissionsList + { + get + { + if (this._permissionsList == null && this.FolderPermissions != null) + { + this._permissionsList = this.FolderPermissions.ToList(); + } + + return this._permissionsList; } } - #endregion - - #region Private Methods - + protected override bool RefreshGrid + { + get + { + return this._refreshGrid; + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets the TabPermissions from the Data Store + /// Overrides the Base method to Generate the Data Grid. + /// + /// ----------------------------------------------------------------------------- + public override void GenerateDataGrid() + { + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the TabPermissions from the Data Store. /// /// ----------------------------------------------------------------------------- protected virtual void GetFolderPermissions() { - FolderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(PortalId, FolderPath)); - _permissionsList = null; + this.FolderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(this.PortalId, this.FolderPath)); + this._permissionsList = null; + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; + } + + protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) + { + var objPermission = new FolderPermissionInfo(permission) + { + FolderPath = this.FolderPath, + RoleID = roleId, + RoleName = roleName, + AllowAccess = allowAccess, + UserID = userId, + DisplayName = displayName, + }; + this.FolderPermissions.Add(objPermission, true); + + // Clear Permission List + this._permissionsList = null; } /// ----------------------------------------------------------------------------- /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState + /// Parse the Permission Keys used to persist the Permissions in the ViewState. /// - /// A string array of settings + /// A string array of settings. /// ----------------------------------------------------------------------------- private FolderPermissionInfo ParseKeys(string[] settings) { var objFolderPermission = new FolderPermissionInfo(); - //Call base class to load base properties - base.ParsePermissionKeys(objFolderPermission, settings); - if (String.IsNullOrEmpty(settings[2])) + // Call base class to load base properties + this.ParsePermissionKeys(objFolderPermission, settings); + if (string.IsNullOrEmpty(settings[2])) { objFolderPermission.FolderPermissionID = -1; } @@ -131,18 +147,19 @@ private FolderPermissionInfo ParseKeys(string[] settings) { objFolderPermission.FolderPermissionID = Convert.ToInt32(settings[2]); } - objFolderPermission.FolderPath = FolderPath; + + objFolderPermission.FolderPath = this.FolderPath; return objFolderPermission; } - + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) { var item = e.Item; if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) { - var roleID = Int32.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) { var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; if (actionImage != null) @@ -151,46 +168,19 @@ private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA } } } - } - - #endregion - - #region Protected Methods - - protected override void CreateChildControls() - { - base.CreateChildControls(); - rolePermissionsGrid.ItemDataBound += rolePermissionsGrid_ItemDataBound; - } - - protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) - { - var objPermission = new FolderPermissionInfo(permission) - { - FolderPath = FolderPath, - RoleID = roleId, - RoleName = roleName, - AllowAccess = allowAccess, - UserID = userId, - DisplayName = displayName - }; - FolderPermissions.Add(objPermission, true); - - //Clear Permission List - _permissionsList = null; - } + } /// ----------------------------------------------------------------------------- /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The user to add + /// The permissions collection. + /// The user to add. /// ----------------------------------------------------------------------------- protected override void AddPermission(ArrayList permissions, UserInfo user) { bool isMatch = false; - foreach (FolderPermissionInfo objFolderPermission in FolderPermissions) + foreach (FolderPermissionInfo objFolderPermission in this.FolderPermissions) { if (objFolderPermission.UserID == user.UserID) { @@ -199,14 +189,14 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) } } - //user not found so add new + // user not found so add new if (!isMatch) { foreach (PermissionInfo objPermission in permissions) { if (objPermission.PermissionKey == "READ") { - AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); } } } @@ -214,64 +204,66 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) /// ----------------------------------------------------------------------------- /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The role to add + /// The permissions collection. + /// The role to add. /// ----------------------------------------------------------------------------- protected override void AddPermission(ArrayList permissions, RoleInfo role) { - //Search TabPermission Collection for the user - if (FolderPermissions.Cast().Any(p => p.RoleID == role.RoleID)) + // Search TabPermission Collection for the user + if (this.FolderPermissions.Cast().Any(p => p.RoleID == role.RoleID)) { return; } - //role not found so add new + // role not found so add new foreach (PermissionInfo objPermission in permissions) { if (objPermission.PermissionKey == "READ") { - AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); + this.AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); } - } + } } /// ----------------------------------------------------------------------------- /// - /// Gets the Enabled status of the permission + /// Gets the Enabled status of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) { - return !IsImplicitRole(role.PortalID, role.RoleID); + return !this.IsImplicitRole(role.PortalID, role.RoleID); } /// ----------------------------------------------------------------------------- /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. /// Default State. - /// A Boolean (True or False) + /// A Boolean (True or False). /// ----------------------------------------------------------------------------- protected override string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState) { string permission; - if (role.RoleID == AdministratorRoleId && IsPermissionAlwaysGrantedToAdmin(objPerm)) + if (role.RoleID == this.AdministratorRoleId && this.IsPermissionAlwaysGrantedToAdmin(objPerm)) { permission = PermissionTypeGrant; } else { - //Call base class method to handle standard permissions + // Call base class method to handle standard permissions permission = base.GetPermission(objPerm, role, column, defaultState); } + return permission; } @@ -282,108 +274,111 @@ protected override bool IsFullControl(PermissionInfo permissionInfo) protected override bool IsViewPermisison(PermissionInfo permissionInfo) { - return (permissionInfo.PermissionKey == "READ"); - } - - private bool IsPermissionAlwaysGrantedToAdmin(PermissionInfo permissionInfo) - { - return IsSystemFolderPermission(permissionInfo); - } - - private bool IsSystemFolderPermission(PermissionInfo permissionInfo) - { - return _systemFolderPermissions.Any(pi => pi.PermissionID == permissionInfo.PermissionID); - } - - private bool IsImplicitRole(int portalId, int roleId) - { - return FolderPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); + return permissionInfo.PermissionKey == "READ"; } /// ----------------------------------------------------------------------------- /// - /// Gets the permissions from the Database - /// + /// Gets the permissions from the Database. + /// + /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() { ArrayList perms = PermissionController.GetPermissionsByFolder(); - _systemFolderPermissions = perms.Cast().ToList(); + this._systemFolderPermissions = perms.Cast().ToList(); return perms; } /// ----------------------------------------------------------------------------- /// - /// Load the ViewState + /// Load the ViewState. /// - /// The saved state + /// The saved state. /// ----------------------------------------------------------------------------- protected override void LoadViewState(object savedState) { if (savedState != null) { - //Load State from the array of objects that was saved with SaveViewState. + // Load State from the array of objects that was saved with SaveViewState. var myState = (object[])savedState; - //Load Base Controls ViewState + // Load Base Controls ViewState if (myState[0] != null) { base.LoadViewState(myState[0]); } - //Load FolderPath + // Load FolderPath if (myState[1] != null) { - _folderPath = Convert.ToString(myState[1]); + this._folderPath = Convert.ToString(myState[1]); } - //Load FolderPermissions + // Load FolderPermissions if (myState[2] != null) { - FolderPermissions = new FolderPermissionCollection(); + this.FolderPermissions = new FolderPermissionCollection(); string state = Convert.ToString(myState[2]); - if (!String.IsNullOrEmpty(state)) + if (!string.IsNullOrEmpty(state)) { - //First Break the String into individual Keys + // First Break the String into individual Keys string[] permissionKeys = state.Split(new[] { "##" }, StringSplitOptions.None); foreach (string key in permissionKeys) { string[] settings = key.Split('|'); - FolderPermissions.Add(ParseKeys(settings)); + this.FolderPermissions.Add(this.ParseKeys(settings)); } } } } } + private bool IsPermissionAlwaysGrantedToAdmin(PermissionInfo permissionInfo) + { + return this.IsSystemFolderPermission(permissionInfo); + } + + private bool IsSystemFolderPermission(PermissionInfo permissionInfo) + { + return this._systemFolderPermissions.Any(pi => pi.PermissionID == permissionInfo.PermissionID); + } + + private bool IsImplicitRole(int portalId, int roleId) + { + return FolderPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); + } + protected override void RemovePermission(int permissionID, int roleID, int userID) { - FolderPermissions.Remove(permissionID, roleID, userID); - //Clear Permission List - _permissionsList = null; + this.FolderPermissions.Remove(permissionID, roleID, userID); + + // Clear Permission List + this._permissionsList = null; } /// ----------------------------------------------------------------------------- /// - /// Saves the ViewState - /// + /// Saves the ViewState. + /// + /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() { var allStates = new object[3]; - //Save the Base Controls ViewState + // Save the Base Controls ViewState allStates[0] = base.SaveViewState(); - //Save the Tab Id - allStates[1] = FolderPath; + // Save the Tab Id + allStates[1] = this.FolderPath; - //Persist the TabPermisisons + // Persist the TabPermisisons var sb = new StringBuilder(); - if (FolderPermissions != null) + if (this.FolderPermissions != null) { bool addDelimiter = false; - foreach (FolderPermissionInfo objFolderPermission in FolderPermissions) + foreach (FolderPermissionInfo objFolderPermission in this.FolderPermissions) { if (addDelimiter) { @@ -393,42 +388,31 @@ protected override object SaveViewState() { addDelimiter = true; } - sb.Append(BuildKey(objFolderPermission.AllowAccess, - objFolderPermission.PermissionID, - objFolderPermission.FolderPermissionID, - objFolderPermission.RoleID, - objFolderPermission.RoleName, - objFolderPermission.UserID, - objFolderPermission.DisplayName)); + + sb.Append(this.BuildKey( + objFolderPermission.AllowAccess, + objFolderPermission.PermissionID, + objFolderPermission.FolderPermissionID, + objFolderPermission.RoleID, + objFolderPermission.RoleName, + objFolderPermission.UserID, + objFolderPermission.DisplayName)); } } + allStates[2] = sb.ToString(); return allStates; } /// ----------------------------------------------------------------------------- /// - /// returns whether or not the derived grid supports Deny permissions - /// + /// returns whether or not the derived grid supports Deny permissions. + /// + /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { - return IsSystemFolderPermission(permissionInfo); - } - - #endregion - - #region "Public Methods" - - /// ----------------------------------------------------------------------------- - /// - /// Overrides the Base method to Generate the Data Grid - /// - /// ----------------------------------------------------------------------------- - public override void GenerateDataGrid() - { - } - - #endregion + return this.IsSystemFolderPermission(permissionInfo); + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs index 812d0acf65d..62d6e10b4da 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs @@ -1,32 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions.Controls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + public class ModulePermissionsGrid : PermissionsGrid - { - #region Private Members - + { private bool _InheritViewPermissionsFromTab; private int _ModuleID = -1; private ModulePermissionCollection _ModulePermissions; @@ -35,95 +29,130 @@ public class ModulePermissionsGrid : PermissionsGrid public ModulePermissionsGrid() { - TabId = -1; - } - - #endregion - - #region Protected Properties - - protected override List PermissionsList - { - get - { - if (_PermissionsList == null && _ModulePermissions != null) - { - _PermissionsList = _ModulePermissions.ToList(); - } - return _PermissionsList; - } - } - - #endregion - - #region Public Properties - + this.TabId = -1; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and Sets whether the Module inherits the Page's(Tab's) permissions + /// Gets or sets a value indicating whether gets and Sets whether the Module inherits the Page's(Tab's) permissions. /// /// ----------------------------------------------------------------------------- public bool InheritViewPermissionsFromTab { get { - return _InheritViewPermissionsFromTab; + return this._InheritViewPermissionsFromTab; } + set { - _InheritViewPermissionsFromTab = value; - _PermissionsList = null; + this._InheritViewPermissionsFromTab = value; + this._PermissionsList = null; } } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Id of the Module + /// Gets or sets and Sets the Id of the Module. /// /// ----------------------------------------------------------------------------- public int ModuleID { get { - return _ModuleID; + return this._ModuleID; } + set { - _ModuleID = value; - if (!Page.IsPostBack) + this._ModuleID = value; + if (!this.Page.IsPostBack) { - GetModulePermissions(); + this.GetModulePermissions(); } } } + + protected override List PermissionsList + { + get + { + if (this._PermissionsList == null && this._ModulePermissions != null) + { + this._PermissionsList = this._ModulePermissions.ToList(); + } + + return this._PermissionsList; + } + } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Id of the Tab associated with this module + /// Gets or sets and Sets the Id of the Tab associated with this module. /// /// ----------------------------------------------------------------------------- public int TabId { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the ModulePermission Collection + /// Gets the ModulePermission Collection. /// /// ----------------------------------------------------------------------------- public ModulePermissionCollection Permissions { get { - //First Update Permissions in case they have been changed - UpdatePermissions(); + // First Update Permissions in case they have been changed + this.UpdatePermissions(); + + // Return the ModulePermissions + return this._ModulePermissions; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Overrides the Base method to Generate the Data Grid. + /// + /// ----------------------------------------------------------------------------- + public override void GenerateDataGrid() + { + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; + } - //Return the ModulePermissions - return _ModulePermissions; + /// ----------------------------------------------------------------------------- + /// + /// Updates a Permission. + /// + /// The permissions collection. + /// The user to add. + /// ----------------------------------------------------------------------------- + protected override void AddPermission(ArrayList permissions, UserInfo user) + { + bool isMatch = this._ModulePermissions.Cast() + .Any(objModulePermission => objModulePermission.UserID == user.UserID); + + // user not found so add new + if (!isMatch) + { + foreach (PermissionInfo objPermission in permissions) + { + if (objPermission.PermissionKey == "VIEW") + { + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + } + } } } /// ----------------------------------------------------------------------------- /// - /// Check if a role is implicit for Module Permissions + /// Check if a role is implicit for Module Permissions. /// /// ----------------------------------------------------------------------------- private bool IsImplicitRole(int portalId, int roleId) @@ -133,28 +162,28 @@ private bool IsImplicitRole(int portalId, int roleId) /// ----------------------------------------------------------------------------- /// - /// Gets the ModulePermissions from the Data Store + /// Gets the ModulePermissions from the Data Store. /// /// ----------------------------------------------------------------------------- private void GetModulePermissions() { - _ModulePermissions = new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(ModuleID, TabId)); - _PermissionsList = null; + this._ModulePermissions = new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(this.ModuleID, this.TabId)); + this._PermissionsList = null; } /// ----------------------------------------------------------------------------- /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState + /// Parse the Permission Keys used to persist the Permissions in the ViewState. /// - /// A string array of settings + /// A string array of settings. /// ----------------------------------------------------------------------------- private ModulePermissionInfo ParseKeys(string[] Settings) { var objModulePermission = new ModulePermissionInfo(); - //Call base class to load base properties - base.ParsePermissionKeys(objModulePermission, Settings); - if (String.IsNullOrEmpty(Settings[2])) + // Call base class to load base properties + this.ParsePermissionKeys(objModulePermission, Settings); + if (string.IsNullOrEmpty(Settings[2])) { objModulePermission.ModulePermissionID = -1; } @@ -162,19 +191,19 @@ private ModulePermissionInfo ParseKeys(string[] Settings) { objModulePermission.ModulePermissionID = Convert.ToInt32(Settings[2]); } - objModulePermission.ModuleID = ModuleID; + + objModulePermission.ModuleID = this.ModuleID; return objModulePermission; } - - + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) { var item = e.Item; if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) { - var roleID = Int32.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) { var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; if (actionImage != null) @@ -183,139 +212,108 @@ private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA } } } - } - - - #endregion - - #region Protected Methods - - protected override void CreateChildControls() - { - base.CreateChildControls(); - rolePermissionsGrid.ItemDataBound += rolePermissionsGrid_ItemDataBound; - } - - /// ----------------------------------------------------------------------------- - /// - /// Updates a Permission - /// - /// The permissions collection - /// The user to add - /// ----------------------------------------------------------------------------- - protected override void AddPermission(ArrayList permissions, UserInfo user) - { - bool isMatch = _ModulePermissions.Cast() - .Any(objModulePermission => objModulePermission.UserID == user.UserID); - - //user not found so add new - if (!isMatch) - { - foreach (PermissionInfo objPermission in permissions) - { - if (objPermission.PermissionKey == "VIEW") - { - AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); - } - } - } - } + } /// ----------------------------------------------------------------------------- /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The role to add + /// The permissions collection. + /// The role to add. /// ----------------------------------------------------------------------------- protected override void AddPermission(ArrayList permissions, RoleInfo role) { - //Search TabPermission Collection for the user + // Search TabPermission Collection for the user if ( - _ModulePermissions.Cast().Any(p => p.RoleID == role.RoleID)) + this._ModulePermissions.Cast().Any(p => p.RoleID == role.RoleID)) { return; } - //role not found so add new + // role not found so add new foreach (PermissionInfo objPermission in permissions) { if (objPermission.PermissionKey == "VIEW") { - AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); + this.AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); } - } + } } protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) { - var objPermission = new ModulePermissionInfo(permission) - { - ModuleID = ModuleID, - RoleID = roleId, - RoleName = roleName, - AllowAccess = allowAccess, - UserID = userId, - DisplayName = displayName - }; - _ModulePermissions.Add(objPermission, true); - - //Clear Permission List - _PermissionsList = null; + var objPermission = new ModulePermissionInfo(permission) + { + ModuleID = this.ModuleID, + RoleID = roleId, + RoleName = roleName, + AllowAccess = allowAccess, + UserID = userId, + DisplayName = displayName, + }; + this._ModulePermissions.Add(objPermission, true); + + // Clear Permission List + this._PermissionsList = null; } protected override void UpdatePermission(PermissionInfo permission, int roleId, string roleName, string stateKey) { - if (InheritViewPermissionsFromTab && permission.PermissionKey == "VIEW") + if (this.InheritViewPermissionsFromTab && permission.PermissionKey == "VIEW") { return; } + base.UpdatePermission(permission, roleId, roleName, stateKey); } protected override void UpdatePermission(PermissionInfo permission, string displayName, int userId, string stateKey) { - if (InheritViewPermissionsFromTab && permission.PermissionKey == "VIEW") + if (this.InheritViewPermissionsFromTab && permission.PermissionKey == "VIEW") { return; } + base.UpdatePermission(permission, displayName, userId, stateKey); } /// ----------------------------------------------------------------------------- /// - /// Gets the Enabled status of the permission + /// Gets the Enabled status of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) { bool enabled; - if (InheritViewPermissionsFromTab && column == _ViewColumnIndex) + if (this.InheritViewPermissionsFromTab && column == this._ViewColumnIndex) { enabled = false; } else { - enabled = !IsImplicitRole(role.PortalID, role.RoleID); + enabled = !this.IsImplicitRole(role.PortalID, role.RoleID); } + return enabled; } /// ----------------------------------------------------------------------------- /// - /// Gets the Enabled status of the permission + /// Gets the Enabled status of the permission. /// - /// The permission being loaded - /// The user - /// The column of the Grid + /// The permission being loaded. + /// The user. + /// The column of the Grid. + /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column) { bool enabled; - if (InheritViewPermissionsFromTab && column == _ViewColumnIndex) + if (this.InheritViewPermissionsFromTab && column == this._ViewColumnIndex) { enabled = false; } @@ -323,71 +321,75 @@ protected override bool GetEnabled(PermissionInfo objPerm, UserInfo user, int co { enabled = true; } + return enabled; } /// ----------------------------------------------------------------------------- /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. /// Default State. - /// A Boolean (True or False) + /// A Boolean (True or False). /// ----------------------------------------------------------------------------- protected override string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState) { string permission; - if (InheritViewPermissionsFromTab && column == _ViewColumnIndex) + if (this.InheritViewPermissionsFromTab && column == this._ViewColumnIndex) { permission = PermissionTypeNull; } else { - permission = role.RoleID == AdministratorRoleId - ? PermissionTypeGrant + permission = role.RoleID == this.AdministratorRoleId + ? PermissionTypeGrant : base.GetPermission(objPerm, role, column, defaultState); } + return permission; } /// ----------------------------------------------------------------------------- /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. /// Default State. - /// A Boolean (True or False) + /// A Boolean (True or False). /// ----------------------------------------------------------------------------- protected override string GetPermission(PermissionInfo objPerm, UserInfo user, int column, string defaultState) { string permission; - if (InheritViewPermissionsFromTab && column == _ViewColumnIndex) + if (this.InheritViewPermissionsFromTab && column == this._ViewColumnIndex) { permission = PermissionTypeNull; } else { - //Call base class method to handle standard permissions + // Call base class method to handle standard permissions permission = base.GetPermission(objPerm, user, column, defaultState); } + return permission; } /// ----------------------------------------------------------------------------- /// - /// Gets the Permissions from the Data Store - /// + /// Gets the Permissions from the Data Store. + /// + /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() { - var moduleInfo = ModuleController.Instance.GetModule(ModuleID, TabId, false); + var moduleInfo = ModuleController.Instance.GetModule(this.ModuleID, this.TabId, false); var permissionController = new PermissionController(); - var permissions = permissionController.GetPermissionsByModule(ModuleID, TabId); + var permissions = permissionController.GetPermissionsByModule(this.ModuleID, this.TabId); var permissionList = new ArrayList(); for (int i = 0; i <= permissions.Count - 1; i++) @@ -395,7 +397,7 @@ protected override ArrayList GetPermissions() var permission = (PermissionInfo)permissions[i]; if (permission.PermissionKey == "VIEW") { - _ViewColumnIndex = i + 1; + this._ViewColumnIndex = i + 1; permissionList.Add(permission); } else @@ -406,6 +408,7 @@ protected override ArrayList GetPermissions() } } } + return permissionList; } @@ -416,59 +419,59 @@ protected override bool IsFullControl(PermissionInfo permissionInfo) protected override bool IsViewPermisison(PermissionInfo permissionInfo) { - return (permissionInfo.PermissionKey == "VIEW"); + return permissionInfo.PermissionKey == "VIEW"; } /// ----------------------------------------------------------------------------- /// - /// Load the ViewState + /// Load the ViewState. /// - /// The saved state + /// The saved state. /// ----------------------------------------------------------------------------- protected override void LoadViewState(object savedState) { if (savedState != null) { - //Load State from the array of objects that was saved with SaveViewState. + // Load State from the array of objects that was saved with SaveViewState. var myState = (object[])savedState; - //Load Base Controls ViewState + // Load Base Controls ViewState if (myState[0] != null) { base.LoadViewState(myState[0]); } - //Load ModuleID + // Load ModuleID if (myState[1] != null) { - ModuleID = Convert.ToInt32(myState[1]); + this.ModuleID = Convert.ToInt32(myState[1]); } - //Load TabId + // Load TabId if (myState[2] != null) { - TabId = Convert.ToInt32(myState[2]); + this.TabId = Convert.ToInt32(myState[2]); } - //Load InheritViewPermissionsFromTab + // Load InheritViewPermissionsFromTab if (myState[3] != null) { - InheritViewPermissionsFromTab = Convert.ToBoolean(myState[3]); + this.InheritViewPermissionsFromTab = Convert.ToBoolean(myState[3]); } - //Load ModulePermissions + // Load ModulePermissions if (myState[4] != null) { - _ModulePermissions = new ModulePermissionCollection(); + this._ModulePermissions = new ModulePermissionCollection(); string state = Convert.ToString(myState[4]); - if (!String.IsNullOrEmpty(state)) + if (!string.IsNullOrEmpty(state)) { - //First Break the String into individual Keys + // First Break the String into individual Keys string[] permissionKeys = state.Split(new[] { "##" }, StringSplitOptions.None); foreach (string key in permissionKeys) { string[] Settings = key.Split('|'); - _ModulePermissions.Add(ParseKeys(Settings)); + this._ModulePermissions.Add(this.ParseKeys(Settings)); } } } @@ -477,38 +480,40 @@ protected override void LoadViewState(object savedState) protected override void RemovePermission(int permissionID, int roleID, int userID) { - _ModulePermissions.Remove(permissionID, roleID, userID); - //Clear Permission List - _PermissionsList = null; + this._ModulePermissions.Remove(permissionID, roleID, userID); + + // Clear Permission List + this._PermissionsList = null; } /// ----------------------------------------------------------------------------- /// - /// Saves the ViewState - /// + /// Saves the ViewState. + /// + /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() { var allStates = new object[5]; - //Save the Base Controls ViewState + // Save the Base Controls ViewState allStates[0] = base.SaveViewState(); - //Save the ModuleID - allStates[1] = ModuleID; + // Save the ModuleID + allStates[1] = this.ModuleID; - //Save the TabID - allStates[2] = TabId; + // Save the TabID + allStates[2] = this.TabId; - //Save the InheritViewPermissionsFromTab - allStates[3] = InheritViewPermissionsFromTab; + // Save the InheritViewPermissionsFromTab + allStates[3] = this.InheritViewPermissionsFromTab; - //Persist the ModulePermissions + // Persist the ModulePermissions var sb = new StringBuilder(); - if (_ModulePermissions != null) + if (this._ModulePermissions != null) { bool addDelimiter = false; - foreach (ModulePermissionInfo modulePermission in _ModulePermissions) + foreach (ModulePermissionInfo modulePermission in this._ModulePermissions) { if (addDelimiter) { @@ -518,42 +523,31 @@ protected override object SaveViewState() { addDelimiter = true; } - sb.Append(BuildKey(modulePermission.AllowAccess, - modulePermission.PermissionID, - modulePermission.ModulePermissionID, - modulePermission.RoleID, - modulePermission.RoleName, - modulePermission.UserID, - modulePermission.DisplayName)); + + sb.Append(this.BuildKey( + modulePermission.AllowAccess, + modulePermission.PermissionID, + modulePermission.ModulePermissionID, + modulePermission.RoleID, + modulePermission.RoleName, + modulePermission.UserID, + modulePermission.DisplayName)); } } + allStates[4] = sb.ToString(); return allStates; } /// ----------------------------------------------------------------------------- /// - /// returns whether or not the derived grid supports Deny permissions - /// + /// returns whether or not the derived grid supports Deny permissions. + /// + /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// Overrides the Base method to Generate the Data Grid - /// - /// ----------------------------------------------------------------------------- - public override void GenerateDataGrid() - { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs index 9858d083061..33b514b4950 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs @@ -1,45 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Linq; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.WebControls; -using DotNetNuke.UI.WebControls.Internal; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions.Controls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.WebControls; + using DotNetNuke.UI.WebControls.Internal; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + + using Globals = DotNetNuke.Common.Globals; + public abstract class PermissionsGrid : Control, INamingContainer - { - #region Enums - + { protected const string PermissionTypeGrant = "True"; protected const string PermissionTypeDeny = "False"; - protected const string PermissionTypeNull = "Null"; - - #endregion - - #region Private Members - + protected const string PermissionTypeNull = "Null"; + protected DataGrid rolePermissionsGrid; + protected DataGrid userPermissionsGrid; private ArrayList _permissions; private ArrayList _users; private DropDownList cboRoleGroups; @@ -49,118 +41,103 @@ public abstract class PermissionsGrid : Control, INamingContainer private Label lblGroups; private Label lblSelectRole; private Label lblErrorMessage; - private Panel pnlPermissions; + private Panel pnlPermissions; private TextBox txtUser; private HiddenField hiddenUserIds; - private HiddenField roleField; - #endregion + private HiddenField roleField; + + private int unAuthUsersRoleId = int.Parse(Globals.glbRoleUnauthUser); - #region Protected Members - protected DataGrid rolePermissionsGrid; - protected DataGrid userPermissionsGrid; - #endregion - - #region Constructor + private int allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); + public PermissionsGrid() { - dtUserPermissions = new DataTable(); - dtRolePermissions = new DataTable(); - } - - #endregion - - #region private Properties - private int unAuthUsersRoleId = Int32.Parse(Globals.glbRoleUnauthUser); - private int UnAuthUsersRoleId - { - get { return unAuthUsersRoleId; } - } - - private int allUsersRoleId = Int32.Parse(Globals.glbRoleAllUsers); - private int AllUsersRoleId + this.dtUserPermissions = new DataTable(); + this.dtRolePermissions = new DataTable(); + } + + public TableItemStyle AlternatingItemStyle { get { - return allUsersRoleId; - } + return this.rolePermissionsGrid.AlternatingItemStyle; + } } - #endregion - - #region Protected Properties - protected virtual List PermissionsList + public bool AutoGenerateColumns { get { - return null; + return this.rolePermissionsGrid.AutoGenerateColumns; + } + + set + { + this.rolePermissionsGrid.AutoGenerateColumns = value; + this.userPermissionsGrid.AutoGenerateColumns = value; } } - protected virtual bool RefreshGrid + public int CellSpacing { get { - return false; + return this.rolePermissionsGrid.CellSpacing; + } + + set + { + this.rolePermissionsGrid.CellSpacing = value; + this.userPermissionsGrid.CellSpacing = value; } } - - #endregion - - #region Public Properties - - /// - /// Registers the scripts neccesary to make the tri-state controls work inside a RadAjaxPanel - /// - /// - /// No need to call this unless using the PermissionGrid inside an ajax control that omits scripts on postback - /// See DesktopModules/Admin/Tabs.ascx.cs for an example of usage - /// - public void RegisterScriptsForAjaxPanel() - { - PermissionTriState.RegisterScripts(Page, this); - } - - #region "DataGrid Properties" - - public TableItemStyle AlternatingItemStyle + + protected virtual List PermissionsList { get { - return rolePermissionsGrid.AlternatingItemStyle; + return null; } } - public bool AutoGenerateColumns + protected virtual bool RefreshGrid { get { - return rolePermissionsGrid.AutoGenerateColumns; - } - set - { - rolePermissionsGrid.AutoGenerateColumns = value; - userPermissionsGrid.AutoGenerateColumns = value; + return false; } + } + + private int UnAuthUsersRoleId + { + get { return this.unAuthUsersRoleId; } } - - public int CellSpacing + + private int AllUsersRoleId { get { - return rolePermissionsGrid.CellSpacing; - } - set - { - rolePermissionsGrid.CellSpacing = value; - userPermissionsGrid.CellSpacing = value; + return this.allUsersRoleId; } - } + } + + /// + /// Registers the scripts neccesary to make the tri-state controls work inside a RadAjaxPanel. + /// + /// + /// No need to call this unless using the PermissionGrid inside an ajax control that omits scripts on postback + /// See DesktopModules/Admin/Tabs.ascx.cs for an example of usage. + /// + public void RegisterScriptsForAjaxPanel() + { + PermissionTriState.RegisterScripts(this.Page, this); + } public DataGridColumnCollection Columns { get { - return rolePermissionsGrid.Columns; + return this.rolePermissionsGrid.Columns; } } @@ -168,7 +145,7 @@ public TableItemStyle FooterStyle { get { - return rolePermissionsGrid.FooterStyle; + return this.rolePermissionsGrid.FooterStyle; } } @@ -176,12 +153,13 @@ public GridLines GridLines { get { - return rolePermissionsGrid.GridLines; + return this.rolePermissionsGrid.GridLines; } + set { - rolePermissionsGrid.GridLines = value; - userPermissionsGrid.GridLines = value; + this.rolePermissionsGrid.GridLines = value; + this.userPermissionsGrid.GridLines = value; } } @@ -189,7 +167,7 @@ public TableItemStyle HeaderStyle { get { - return rolePermissionsGrid.HeaderStyle; + return this.rolePermissionsGrid.HeaderStyle; } } @@ -197,7 +175,7 @@ public TableItemStyle ItemStyle { get { - return rolePermissionsGrid.ItemStyle; + return this.rolePermissionsGrid.ItemStyle; } } @@ -205,7 +183,7 @@ public DataGridItemCollection Items { get { - return rolePermissionsGrid.Items; + return this.rolePermissionsGrid.Items; } } @@ -213,14 +191,12 @@ public TableItemStyle SelectedItemStyle { get { - return rolePermissionsGrid.SelectedItemStyle; + return this.rolePermissionsGrid.SelectedItemStyle; } - } - - #endregion - + } + /// - /// Gets the Id of the Administrator Role + /// Gets the Id of the Administrator Role. /// public int AdministratorRoleId { @@ -231,7 +207,7 @@ public int AdministratorRoleId } /// - /// Gets the Id of the Registered Users Role + /// Gets the Id of the Registered Users Role. /// public int RegisteredUsersRoleId { @@ -242,41 +218,42 @@ public int RegisteredUsersRoleId } /// - /// Gets and Sets whether a Dynamic Column has been added + /// Gets or sets a value indicating whether gets and Sets whether a Dynamic Column has been added. /// public bool DynamicColumnAdded { get { - return ViewState["ColumnAdded"] != null; + return this.ViewState["ColumnAdded"] != null; } + set { - ViewState["ColumnAdded"] = value; + this.ViewState["ColumnAdded"] = value; } } /// - /// Gets the underlying Permissions Data Table + /// Gets the underlying Permissions Data Table. /// public DataTable dtRolePermissions { get; private set; } /// - /// Gets the underlying Permissions Data Table + /// Gets the underlying Permissions Data Table. /// public DataTable dtUserPermissions { get; private set; } /// - /// Gets the Id of the Portal + /// Gets the Id of the Portal. /// public int PortalId { get { - //Obtain PortalSettings from Current Context + // Obtain PortalSettings from Current Context var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); int portalID; - if (Globals.IsHostTab(portalSettings.ActiveTab.TabID)) //if we are in host filemanager then we need to pass a null portal id + if (Globals.IsHostTab(portalSettings.ActiveTab.TabID)) // if we are in host filemanager then we need to pass a null portal id { portalID = Null.NullInteger; } @@ -284,83 +261,90 @@ public int PortalId { portalID = portalSettings.PortalId; } + return portalID; } } /// - /// Gets and Sets the collection of Roles to display + /// Gets or sets and Sets the collection of Roles to display. /// public ArrayList Roles { get; set; } /// - /// Gets and Sets the ResourceFile to localize permissions + /// Gets or sets and Sets the ResourceFile to localize permissions. /// - public string ResourceFile { get; set; } - - #endregion - - #region Abstract Members - + public string ResourceFile { get; set; } + /// - /// Generate the Data Grid + /// Generate the Data Grid. /// - public abstract void GenerateDataGrid(); - - #endregion + public abstract void GenerateDataGrid(); + + protected virtual void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) + { + } - #region Private Methods - + /// + /// Updates a Permission. + /// + /// The permissions collection. + /// The user to add. + protected virtual void AddPermission(ArrayList permissions, UserInfo user) + { + } + private void BindData() { - EnsureChildControls(); - BindRolesGrid(); - BindUsersGrid(); + this.EnsureChildControls(); + this.BindRolesGrid(); + this.BindUsersGrid(); } private void BindRolesGrid() { - dtRolePermissions.Columns.Clear(); - dtRolePermissions.Rows.Clear(); + this.dtRolePermissions.Columns.Clear(); + this.dtRolePermissions.Rows.Clear(); - //Add Roles Column - dtRolePermissions.Columns.Add(new DataColumn("RoleId")); + // Add Roles Column + this.dtRolePermissions.Columns.Add(new DataColumn("RoleId")); - //Add Roles Column - dtRolePermissions.Columns.Add(new DataColumn("RoleName")); + // Add Roles Column + this.dtRolePermissions.Columns.Add(new DataColumn("RoleName")); - for (int i = 0; i <= _permissions.Count - 1; i++) + for (int i = 0; i <= this._permissions.Count - 1; i++) { - var permissionInfo = (PermissionInfo)_permissions[i]; + var permissionInfo = (PermissionInfo)this._permissions[i]; - //Add Enabled Column - dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName + "_Enabled")); + // Add Enabled Column + this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName + "_Enabled")); - //Add Permission Column - dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName)); + // Add Permission Column + this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName)); } - GetRoles(); + + this.GetRoles(); - UpdateRolePermissions(); - for (int i = 0; i <= Roles.Count - 1; i++) + this.UpdateRolePermissions(); + for (int i = 0; i <= this.Roles.Count - 1; i++) { - var role = (RoleInfo)Roles[i]; - var row = dtRolePermissions.NewRow(); + var role = (RoleInfo)this.Roles[i]; + var row = this.dtRolePermissions.NewRow(); row["RoleId"] = role.RoleID; row["RoleName"] = Localization.LocalizeRole(role.RoleName); int j; - for (j = 0; j <= _permissions.Count - 1; j++) + for (j = 0; j <= this._permissions.Count - 1; j++) { PermissionInfo objPerm; - objPerm = (PermissionInfo)_permissions[j]; - row[objPerm.PermissionName + "_Enabled"] = GetEnabled(objPerm, role, j + 1); - if (SupportsDenyPermissions(objPerm)) + objPerm = (PermissionInfo)this._permissions[j]; + row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, role, j + 1); + if (this.SupportsDenyPermissions(objPerm)) { - row[objPerm.PermissionName] = GetPermission(objPerm, role, j + 1, PermissionTypeNull); + row[objPerm.PermissionName] = this.GetPermission(objPerm, role, j + 1, PermissionTypeNull); } else { - if (GetPermission(objPerm, role, j + 1)) + if (this.GetPermission(objPerm, role, j + 1)) { row[objPerm.PermissionName] = PermissionTypeGrant; } @@ -370,65 +354,68 @@ private void BindRolesGrid() } } } - dtRolePermissions.Rows.Add(row); + + this.dtRolePermissions.Rows.Add(row); } - rolePermissionsGrid.DataSource = dtRolePermissions; - rolePermissionsGrid.DataBind(); + + this.rolePermissionsGrid.DataSource = this.dtRolePermissions; + this.rolePermissionsGrid.DataBind(); } private void BindUsersGrid() { - dtUserPermissions.Columns.Clear(); - dtUserPermissions.Rows.Clear(); + this.dtUserPermissions.Columns.Clear(); + this.dtUserPermissions.Rows.Clear(); - //Add Roles Column + // Add Roles Column var col = new DataColumn("UserId"); - dtUserPermissions.Columns.Add(col); + this.dtUserPermissions.Columns.Add(col); - //Add Roles Column + // Add Roles Column col = new DataColumn("DisplayName"); - dtUserPermissions.Columns.Add(col); + this.dtUserPermissions.Columns.Add(col); int i; - for (i = 0; i <= _permissions.Count - 1; i++) + for (i = 0; i <= this._permissions.Count - 1; i++) { PermissionInfo objPerm; - objPerm = (PermissionInfo)_permissions[i]; + objPerm = (PermissionInfo)this._permissions[i]; - //Add Enabled Column + // Add Enabled Column col = new DataColumn(objPerm.PermissionName + "_Enabled"); - dtUserPermissions.Columns.Add(col); + this.dtUserPermissions.Columns.Add(col); - //Add Permission Column + // Add Permission Column col = new DataColumn(objPerm.PermissionName); - dtUserPermissions.Columns.Add(col); + this.dtUserPermissions.Columns.Add(col); } - if (userPermissionsGrid != null) + + if (this.userPermissionsGrid != null) { - _users = GetUsers(); + this._users = this.GetUsers(); - if (_users.Count != 0) + if (this._users.Count != 0) { - userPermissionsGrid.Visible = true; + this.userPermissionsGrid.Visible = true; DataRow row; - for (i = 0; i <= _users.Count - 1; i++) + for (i = 0; i <= this._users.Count - 1; i++) { - var user = (UserInfo)_users[i]; - row = dtUserPermissions.NewRow(); + var user = (UserInfo)this._users[i]; + row = this.dtUserPermissions.NewRow(); row["UserId"] = user.UserID; row["DisplayName"] = user.DisplayName; int j; - for (j = 0; j <= _permissions.Count - 1; j++) + for (j = 0; j <= this._permissions.Count - 1; j++) { PermissionInfo objPerm; - objPerm = (PermissionInfo)_permissions[j]; - row[objPerm.PermissionName + "_Enabled"] = GetEnabled(objPerm, user, j + 1); - if (SupportsDenyPermissions(objPerm)) + objPerm = (PermissionInfo)this._permissions[j]; + row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, user, j + 1); + if (this.SupportsDenyPermissions(objPerm)) { - row[objPerm.PermissionName] = GetPermission(objPerm, user, j + 1, PermissionTypeNull); + row[objPerm.PermissionName] = this.GetPermission(objPerm, user, j + 1, PermissionTypeNull); } else { - if (GetPermission(objPerm, user, j + 1)) + if (this.GetPermission(objPerm, user, j + 1)) { row[objPerm.PermissionName] = PermissionTypeGrant; } @@ -438,102 +425,107 @@ private void BindUsersGrid() } } } - dtUserPermissions.Rows.Add(row); - } - userPermissionsGrid.DataSource = dtUserPermissions; - userPermissionsGrid.DataBind(); + + this.dtUserPermissions.Rows.Add(row); + } + + this.userPermissionsGrid.DataSource = this.dtUserPermissions; + this.userPermissionsGrid.DataBind(); } else { - dtUserPermissions.Rows.Clear(); - userPermissionsGrid.DataSource = dtUserPermissions; - userPermissionsGrid.DataBind(); - userPermissionsGrid.Visible = false; + this.dtUserPermissions.Rows.Clear(); + this.userPermissionsGrid.DataSource = this.dtUserPermissions; + this.userPermissionsGrid.DataBind(); + this.userPermissionsGrid.Visible = false; } } } private void EnsureRole(RoleInfo role) { - if (Roles.Cast().All(r => r.RoleID != role.RoleID)) + if (this.Roles.Cast().All(r => r.RoleID != role.RoleID)) { - Roles.Add(role); + this.Roles.Add(role); } } private void GetRoles() { - var checkedRoles = GetCheckedRoles(); + var checkedRoles = this.GetCheckedRoles(); var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - Roles = new ArrayList(RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved && checkedRoles.Contains(r.RoleID)).ToArray()); - - if (checkedRoles.Contains(UnAuthUsersRoleId)) + this.Roles = new ArrayList(RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved && checkedRoles.Contains(r.RoleID)).ToArray()); + + if (checkedRoles.Contains(this.UnAuthUsersRoleId)) { - Roles.Add(new RoleInfo { RoleID = UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); - } - if (checkedRoles.Contains(AllUsersRoleId)) + this.Roles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); + } + + if (checkedRoles.Contains(this.AllUsersRoleId)) { - Roles.Add(new RoleInfo { RoleID = AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName=Globals.glbRoleAllUsersName }); + this.Roles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName }); } - //Administrators Role always has implicit permissions, then it should be always in - EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.AdministratorRoleId)); - - //Show also default roles - EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.RegisteredRoleId)); - EnsureRole(new RoleInfo { RoleID = AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName }); - - Roles.Reverse(); - Roles.Sort(new RoleComparer()); + // Administrators Role always has implicit permissions, then it should be always in + this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.AdministratorRoleId)); + + // Show also default roles + this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.RegisteredRoleId)); + this.EnsureRole(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName }); + + this.Roles.Reverse(); + this.Roles.Sort(new RoleComparer()); } private IEnumerable GetCheckedRoles() { - if (PermissionsList == null) + if (this.PermissionsList == null) { return new List(); } - return PermissionsList.Select(r => r.RoleID).Distinct(); + + return this.PermissionsList.Select(r => r.RoleID).Distinct(); } private void SetUpGrid(DataGrid grid, string nameColumnDataField, string idColumnDataField, string permissionHeaderText) { grid.Columns.Clear(); - var nameColumn = new BoundColumn - { - HeaderText = permissionHeaderText, - DataField = nameColumnDataField - }; + var nameColumn = new BoundColumn + { + HeaderText = permissionHeaderText, + DataField = nameColumnDataField, + }; nameColumn.ItemStyle.CssClass = "permissionHeader"; nameColumn.HeaderStyle.CssClass = "permissionHeader"; grid.Columns.Add(nameColumn); - var idColumn = new BoundColumn - { - HeaderText = "", - DataField = idColumnDataField, - Visible = false - }; + var idColumn = new BoundColumn + { + HeaderText = string.Empty, + DataField = idColumnDataField, + Visible = false, + }; grid.Columns.Add(idColumn); - foreach (PermissionInfo permission in _permissions) + foreach (PermissionInfo permission in this._permissions) { var templateCol = new TemplateColumn(); - var columnTemplate = new PermissionTriStateTemplate(permission) - { - IsFullControl = IsFullControl(permission), - IsView = IsViewPermisison(permission), - SupportDenyMode = SupportsDenyPermissions(permission) - }; + var columnTemplate = new PermissionTriStateTemplate(permission) + { + IsFullControl = this.IsFullControl(permission), + IsView = this.IsViewPermisison(permission), + SupportDenyMode = this.SupportsDenyPermissions(permission), + }; templateCol.ItemTemplate = columnTemplate; - var locName = (permission.ModuleDefID <= 0) ? Localization.GetString(permission.PermissionName + ".Permission", PermissionProvider.Instance().LocalResourceFile) //system permission - : (!String.IsNullOrEmpty(ResourceFile) ? Localization.GetString(permission.PermissionName + ".Permission", ResourceFile) //custom permission - : ""); - templateCol.HeaderText = !String.IsNullOrEmpty(locName) ? locName : permission.PermissionName; + var locName = (permission.ModuleDefID <= 0) ? Localization.GetString(permission.PermissionName + ".Permission", PermissionProvider.Instance().LocalResourceFile) // system permission + : (!string.IsNullOrEmpty(this.ResourceFile) ? Localization.GetString(permission.PermissionName + ".Permission", this.ResourceFile) // custom permission + : string.Empty); + templateCol.HeaderText = !string.IsNullOrEmpty(locName) ? locName : permission.PermissionName; templateCol.HeaderStyle.Wrap = true; grid.Columns.Add(templateCol); } + var actionsColumn = new ImageCommandColumn { CommandName = "Delete/" + nameColumnDataField, @@ -541,48 +533,50 @@ private void SetUpGrid(DataGrid grid, string nameColumnDataField, string idColum IconKey = "Delete", IconSize = "16x16", IconStyle = "PermissionGrid", - HeaderText = Localization.GetString("PermissionActionsHeader.Text", PermissionProvider.Instance().LocalResourceFile) + HeaderText = Localization.GetString("PermissionActionsHeader.Text", PermissionProvider.Instance().LocalResourceFile), }; grid.Columns.Add(actionsColumn); - grid.ItemCommand += grid_ItemCommand; + grid.ItemCommand += this.grid_ItemCommand; } - void grid_ItemCommand(object source, DataGridCommandEventArgs e) + private void grid_ItemCommand(object source, DataGridCommandEventArgs e) { var entityID = int.Parse(e.CommandArgument.ToString()); - var command = GetGridCommand(e.CommandName); - var entityType = GetCommandType(e.CommandName); + var command = this.GetGridCommand(e.CommandName); + var entityType = this.GetCommandType(e.CommandName); switch (command) { case "DELETE": if (entityType == "ROLE") { - DeleteRolePermissions(entityID); + this.DeleteRolePermissions(entityID); } else if (entityType == "USER") { - DeleteUserPermissions(entityID); + this.DeleteUserPermissions(entityID); } - BindData(); + + this.BindData(); break; } } private void DeleteRolePermissions(int entityID) { - //PermissionsList.RemoveAll(p => p.RoleID == entityID); - var permissionToDelete = PermissionsList.Where(p => p.RoleID == entityID); + // PermissionsList.RemoveAll(p => p.RoleID == entityID); + var permissionToDelete = this.PermissionsList.Where(p => p.RoleID == entityID); foreach (PermissionInfoBase permission in permissionToDelete) { - RemovePermission(permission.PermissionID, entityID, permission.UserID); + this.RemovePermission(permission.PermissionID, entityID, permission.UserID); } } + private void DeleteUserPermissions(int entityID) { - var permissionToDelete = PermissionsList.Where(p => p.UserID == entityID); + var permissionToDelete = this.PermissionsList.Where(p => p.UserID == entityID); foreach (PermissionInfoBase permission in permissionToDelete) { - RemovePermission(permission.PermissionID, permission.RoleID, entityID); + this.RemovePermission(permission.PermissionID, permission.RoleID, entityID); } } @@ -593,10 +587,12 @@ private string GetCommandType(string commandName) { return "ROLE"; } + if (command.Contains("displayname")) { return "USER"; } + return Null.NullString; } @@ -608,101 +604,88 @@ private string GetGridCommand(string commandName) private void SetUpRolesGrid() { - SetUpGrid(rolePermissionsGrid, "RoleName", "roleid", Localization.GetString("PermissionRoleHeader.Text", PermissionProvider.Instance().LocalResourceFile)); + this.SetUpGrid(this.rolePermissionsGrid, "RoleName", "roleid", Localization.GetString("PermissionRoleHeader.Text", PermissionProvider.Instance().LocalResourceFile)); } private void SetUpUsersGrid() { - if (userPermissionsGrid != null) + if (this.userPermissionsGrid != null) { - SetUpGrid(userPermissionsGrid, "DisplayName", "userid", Localization.GetString("PermissionUserHeader.Text", PermissionProvider.Instance().LocalResourceFile)); + this.SetUpGrid(this.userPermissionsGrid, "DisplayName", "userid", Localization.GetString("PermissionUserHeader.Text", PermissionProvider.Instance().LocalResourceFile)); } } + private void FillSelectRoleComboBox(int selectedRoleGroupId) { - cboSelectRole.Items.Clear(); - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + this.cboSelectRole.Items.Clear(); + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var groupRoles = (selectedRoleGroupId > -2) ? RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.RoleGroupID == selectedRoleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) : RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); if (selectedRoleGroupId < 0) - { - groupRoles.Add(new RoleInfo { RoleID = UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); - groupRoles.Add(new RoleInfo { RoleID = AllUsersRoleId, RoleName = Globals.glbRoleAllUsersName }); + { + groupRoles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); + groupRoles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, RoleName = Globals.glbRoleAllUsersName }); } - - foreach (var role in groupRoles.OrderBy( r => r.RoleName)) + + foreach (var role in groupRoles.OrderBy(r => r.RoleName)) { - cboSelectRole.Items.Add(new ListItem(role.RoleName, role.RoleID.ToString(CultureInfo.InvariantCulture))); - } - int[] defaultRoleIds = {AllUsersRoleId, portalSettings.RegisteredRoleId, portalSettings.AdministratorRoleId}; - var itemToSelect = cboSelectRole.Items.Cast().FirstOrDefault(i => !defaultRoleIds.Contains(int.Parse(i.Value))); + this.cboSelectRole.Items.Add(new ListItem(role.RoleName, role.RoleID.ToString(CultureInfo.InvariantCulture))); + } + + int[] defaultRoleIds = { this.AllUsersRoleId, portalSettings.RegisteredRoleId, portalSettings.AdministratorRoleId }; + var itemToSelect = this.cboSelectRole.Items.Cast().FirstOrDefault(i => !defaultRoleIds.Contains(int.Parse(i.Value))); if (itemToSelect != null) { - cboSelectRole.SelectedValue = itemToSelect.Value; + this.cboSelectRole.SelectedValue = itemToSelect.Value; } } private void SetErrorMessage(string errorKey) { - lblErrorMessage = new Label + this.lblErrorMessage = new Label { - //TODO Remove DEBUG test - Text = "
    " + (errorKey.StartsWith("DEBUG")? errorKey: Localization.GetString(errorKey)), - CssClass = "NormalRed" + // TODO Remove DEBUG test + Text = "
    " + (errorKey.StartsWith("DEBUG") ? errorKey : Localization.GetString(errorKey)), + CssClass = "NormalRed", }; - pnlPermissions.Controls.Add(lblErrorMessage); - } - - #endregion - - #region Protected Methods - - protected virtual void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) - { - } + this.pnlPermissions.Controls.Add(this.lblErrorMessage); + } /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The user to add - protected virtual void AddPermission(ArrayList permissions, UserInfo user) - { - } - - /// - /// Updates a Permission - /// - /// The permissions collection - /// The role to add + /// The permissions collection. + /// The role to add. protected virtual void AddPermission(ArrayList permissions, RoleInfo role) { } /// - /// Builds the key used to store the "permission" information in the ViewState + /// Builds the key used to store the "permission" information in the ViewState. /// - /// The type of permission ( grant / deny ) - /// The Id of the permission - /// The Id of the object permission - /// The role id - /// The role name + /// The type of permission ( grant / deny ). + /// The Id of the permission. + /// The Id of the object permission. + /// The role id. + /// The role name. + /// protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName) { - return BuildKey(allowAccess, permissionId, objectPermissionId, roleId, roleName, Null.NullInteger, Null.NullString); + return this.BuildKey(allowAccess, permissionId, objectPermissionId, roleId, roleName, Null.NullInteger, Null.NullString); } /// - /// Builds the key used to store the "permission" information in the ViewState + /// Builds the key used to store the "permission" information in the ViewState. /// - /// The type of permission ( grant / deny ) - /// The Id of the permission - /// The Id of the object permission - /// The role id - /// The role name - /// The user id - /// The user display name + /// The type of permission ( grant / deny ). + /// The Id of the permission. + /// The Id of the object permission. + /// The role id. + /// The role name. + /// The user id. + /// The user display name. + /// protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName, int userID, string displayName) { string key; @@ -714,12 +697,14 @@ protected string BuildKey(bool allowAccess, int permissionId, int objectPermissi { key = "False"; } + key += "|" + Convert.ToString(permissionId); key += "|"; if (objectPermissionId > -1) { key += Convert.ToString(objectPermissionId); } + key += "|" + roleName; key += "|" + roleId; key += "|" + userID; @@ -729,80 +714,105 @@ protected string BuildKey(bool allowAccess, int permissionId, int objectPermissi } /// - /// Creates the Child Controls + /// Creates the Child Controls. /// protected override void CreateChildControls() { - _permissions = GetPermissions(); + this._permissions = this.GetPermissions(); - pnlPermissions = new Panel { CssClass = "dnnGrid dnnPermissionsGrid" }; + this.pnlPermissions = new Panel { CssClass = "dnnGrid dnnPermissionsGrid" }; - //Optionally Add Role Group Filter - CreateAddRoleControls(); + // Optionally Add Role Group Filter + this.CreateAddRoleControls(); - rolePermissionsGrid = new DataGrid + this.rolePermissionsGrid = new DataGrid { AutoGenerateColumns = false, CellSpacing = 0, CellPadding = 2, GridLines = GridLines.None, - CssClass = "dnnPermissionsGrid" + CssClass = "dnnPermissionsGrid", }; - rolePermissionsGrid.FooterStyle.CssClass = "dnnGridFooter"; - rolePermissionsGrid.HeaderStyle.CssClass = "dnnGridHeader"; - rolePermissionsGrid.ItemStyle.CssClass = "dnnGridItem"; - rolePermissionsGrid.AlternatingItemStyle.CssClass = "dnnGridAltItem"; - rolePermissionsGrid.ItemDataBound += rolePermissionsGrid_ItemDataBound; - SetUpRolesGrid(); - pnlPermissions.Controls.Add(rolePermissionsGrid); - - _users = GetUsers(); - if (_users != null) - { - userPermissionsGrid = new DataGrid + this.rolePermissionsGrid.FooterStyle.CssClass = "dnnGridFooter"; + this.rolePermissionsGrid.HeaderStyle.CssClass = "dnnGridHeader"; + this.rolePermissionsGrid.ItemStyle.CssClass = "dnnGridItem"; + this.rolePermissionsGrid.AlternatingItemStyle.CssClass = "dnnGridAltItem"; + this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; + this.SetUpRolesGrid(); + this.pnlPermissions.Controls.Add(this.rolePermissionsGrid); + + this._users = this.GetUsers(); + if (this._users != null) + { + this.userPermissionsGrid = new DataGrid { AutoGenerateColumns = false, CellSpacing = 0, GridLines = GridLines.None, - CssClass = "dnnPermissionsGrid" + CssClass = "dnnPermissionsGrid", }; - userPermissionsGrid.FooterStyle.CssClass = "dnnGridFooter"; - userPermissionsGrid.HeaderStyle.CssClass = "dnnGridHeader"; - userPermissionsGrid.ItemStyle.CssClass = "dnnGridItem"; - userPermissionsGrid.AlternatingItemStyle.CssClass = "dnnGridAltItem"; + this.userPermissionsGrid.FooterStyle.CssClass = "dnnGridFooter"; + this.userPermissionsGrid.HeaderStyle.CssClass = "dnnGridHeader"; + this.userPermissionsGrid.ItemStyle.CssClass = "dnnGridItem"; + this.userPermissionsGrid.AlternatingItemStyle.CssClass = "dnnGridAltItem"; - SetUpUsersGrid(); - pnlPermissions.Controls.Add(userPermissionsGrid); + this.SetUpUsersGrid(); + this.pnlPermissions.Controls.Add(this.userPermissionsGrid); var divAddUser = new Panel { CssClass = "dnnFormItem" }; - lblErrorMessage = new Label { Text = Localization.GetString("DisplayName") }; - txtUser = new TextBox { ID = "txtUser" }; - lblErrorMessage.AssociatedControlID = txtUser.ID; + this.lblErrorMessage = new Label { Text = Localization.GetString("DisplayName") }; + this.txtUser = new TextBox { ID = "txtUser" }; + this.lblErrorMessage.AssociatedControlID = this.txtUser.ID; - hiddenUserIds = new HiddenField { ID = "hiddenUserIds" }; + this.hiddenUserIds = new HiddenField { ID = "hiddenUserIds" }; - divAddUser.Controls.Add(lblErrorMessage); - divAddUser.Controls.Add(txtUser); - divAddUser.Controls.Add(hiddenUserIds); + divAddUser.Controls.Add(this.lblErrorMessage); + divAddUser.Controls.Add(this.txtUser); + divAddUser.Controls.Add(this.hiddenUserIds); - cmdUser = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" }; - divAddUser.Controls.Add(cmdUser); - cmdUser.Click += AddUser; + this.cmdUser = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" }; + divAddUser.Controls.Add(this.cmdUser); + this.cmdUser.Click += this.AddUser; - pnlPermissions.Controls.Add(divAddUser); + this.pnlPermissions.Controls.Add(divAddUser); } - Controls.Add(pnlPermissions); + + this.Controls.Add(this.pnlPermissions); + } + + /// + /// Gets the Enabled status of the permission. + /// + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// + protected virtual bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) + { + return true; + } + + /// + /// Gets the Enabled status of the permission. + /// + /// The permission being loaded. + /// The user. + /// The column of the Grid. + /// + protected virtual bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column) + { + return true; } - void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) { var item = e.Item; if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - var roleID = Int32.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (roleID == PortalSettings.Current.AdministratorRoleId || roleID == AllUsersRoleId || roleID == PortalSettings.Current.RegisteredRoleId) + { + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (roleID == PortalSettings.Current.AdministratorRoleId || roleID == this.AllUsersRoleId || roleID == PortalSettings.Current.RegisteredRoleId) { var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; if (actionImage != null) @@ -818,91 +828,72 @@ private void CreateAddRoleControls() var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var arrGroups = RoleController.GetRoleGroups(portalSettings.PortalId); - var addRoleControls = new Panel {CssClass = "dnnFormItem"}; - var divRoleGroups = new Panel {CssClass = "leftGroup"}; + var addRoleControls = new Panel { CssClass = "dnnFormItem" }; + var divRoleGroups = new Panel { CssClass = "leftGroup" }; var divSelectRole = new Panel { CssClass = "rightGroup" }; - lblGroups = new Label {Text = Localization.GetString("RoleGroupFilter")}; - cboRoleGroups = new DropDownList { AutoPostBack = true, ID = "cboRoleGroups", ViewStateMode = ViewStateMode.Disabled }; - lblGroups.AssociatedControlID = cboRoleGroups.ID; - divRoleGroups.Controls.Add(lblGroups); + this.lblGroups = new Label { Text = Localization.GetString("RoleGroupFilter") }; + this.cboRoleGroups = new DropDownList { AutoPostBack = true, ID = "cboRoleGroups", ViewStateMode = ViewStateMode.Disabled }; + this.lblGroups.AssociatedControlID = this.cboRoleGroups.ID; + divRoleGroups.Controls.Add(this.lblGroups); - cboRoleGroups.SelectedIndexChanged += RoleGroupsSelectedIndexChanged; - cboRoleGroups.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); - var liItem = new ListItem(Localization.GetString("GlobalRoles"), "-1") {Selected = true}; - cboRoleGroups.Items.Add(liItem); + this.cboRoleGroups.SelectedIndexChanged += this.RoleGroupsSelectedIndexChanged; + this.cboRoleGroups.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); + var liItem = new ListItem(Localization.GetString("GlobalRoles"), "-1") { Selected = true }; + this.cboRoleGroups.Items.Add(liItem); foreach (RoleGroupInfo roleGroup in arrGroups) { - cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture))); + this.cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture))); } - divRoleGroups.Controls.Add(cboRoleGroups); + + divRoleGroups.Controls.Add(this.cboRoleGroups); addRoleControls.Controls.Add(divRoleGroups); - lblSelectRole = new Label { Text = Localization.GetString("RoleSelect") }; - cboSelectRole = new DropDownList { ID = "cboSelectRole", ViewStateMode = ViewStateMode.Disabled }; - lblSelectRole.AssociatedControlID = cboSelectRole.ID; - divSelectRole.Controls.Add(lblSelectRole); + this.lblSelectRole = new Label { Text = Localization.GetString("RoleSelect") }; + this.cboSelectRole = new DropDownList { ID = "cboSelectRole", ViewStateMode = ViewStateMode.Disabled }; + this.lblSelectRole.AssociatedControlID = this.cboSelectRole.ID; + divSelectRole.Controls.Add(this.lblSelectRole); - FillSelectRoleComboBox(-1); //Default Role Group is Global Roles - divSelectRole.Controls.Add(cboSelectRole); + this.FillSelectRoleComboBox(-1); // Default Role Group is Global Roles + divSelectRole.Controls.Add(this.cboSelectRole); - cmdRole = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" }; - cmdRole.Click += AddRole; - divSelectRole.Controls.Add(cmdRole); - roleField = new HiddenField() {ID = "roleField"}; - addRoleControls.Controls.Add(roleField); + this.cmdRole = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" }; + this.cmdRole.Click += this.AddRole; + divSelectRole.Controls.Add(this.cmdRole); + this.roleField = new HiddenField() { ID = "roleField" }; + addRoleControls.Controls.Add(this.roleField); addRoleControls.Controls.Add(divSelectRole); - pnlPermissions.Controls.Add(addRoleControls); - } - - /// - /// Gets the Enabled status of the permission - /// - /// The permission being loaded - /// The role - /// The column of the Grid - protected virtual bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) - { - return true; - } - - /// - /// Gets the Enabled status of the permission - /// - /// The permission being loaded - /// The user - /// The column of the Grid - protected virtual bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column) - { - return true; + this.pnlPermissions.Controls.Add(addRoleControls); } /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// protected virtual bool GetPermission(PermissionInfo objPerm, RoleInfo role, int column) { - return Convert.ToBoolean(GetPermission(objPerm, role, column, PermissionTypeDeny)); + return Convert.ToBoolean(this.GetPermission(objPerm, role, column, PermissionTypeDeny)); } /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid - /// Default State. + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// Default State. + /// protected virtual string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState) { string stateKey = defaultState; - if (PermissionsList != null) + if (this.PermissionsList != null) { - foreach (PermissionInfoBase permission in PermissionsList) + foreach (PermissionInfoBase permission in this.PermissionsList) { if (permission.PermissionID == objPerm.PermissionID && permission.RoleID == role.RoleID) { @@ -914,37 +905,41 @@ protected virtual string GetPermission(PermissionInfo objPerm, RoleInfo role, in { stateKey = PermissionTypeDeny; } + break; } } } + return stateKey; } /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The user - /// The column of the Grid + /// The permission being loaded. + /// The user. + /// The column of the Grid. + /// protected virtual bool GetPermission(PermissionInfo objPerm, UserInfo user, int column) { - return Convert.ToBoolean(GetPermission(objPerm, user, column, PermissionTypeDeny)); + return Convert.ToBoolean(this.GetPermission(objPerm, user, column, PermissionTypeDeny)); } /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The user - /// The column of the Grid - /// Default State. + /// The permission being loaded. + /// The user. + /// The column of the Grid. + /// Default State. + /// protected virtual string GetPermission(PermissionInfo objPerm, UserInfo user, int column, string defaultState) { var stateKey = defaultState; - if (PermissionsList != null) + if (this.PermissionsList != null) { - foreach (var permission in PermissionsList) + foreach (var permission in this.PermissionsList) { if (permission.PermissionID == objPerm.PermissionID && permission.UserID == user.UserID) { @@ -956,31 +951,35 @@ protected virtual string GetPermission(PermissionInfo objPerm, UserInfo user, in { stateKey = PermissionTypeDeny; } + break; } } } + return stateKey; } /// - /// Gets the permissions from the Database - /// + /// Gets the permissions from the Database. + /// + /// protected virtual ArrayList GetPermissions() { return null; } /// - /// Gets the users from the Database - /// + /// Gets the users from the Database. + /// + /// protected virtual ArrayList GetUsers() { var arrUsers = new ArrayList(); UserInfo objUser; - if (PermissionsList != null) + if (this.PermissionsList != null) { - foreach (var permission in PermissionsList) + foreach (var permission in this.PermissionsList) { if (!Null.IsNull(permission.UserID)) { @@ -992,6 +991,7 @@ protected virtual ArrayList GetUsers() blnExists = true; } } + if (!blnExists) { objUser = new UserInfo(); @@ -1003,6 +1003,7 @@ protected virtual ArrayList GetUsers() } } } + return arrUsers; } @@ -1022,33 +1023,31 @@ protected override void OnInit(EventArgs e) ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/Components/Tokeninput/jquery.tokeninput.js"); - ClientResourceManager.RegisterScript(Page, "~/js/dnn.permissiongrid.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Components/Tokeninput/jquery.tokeninput.js"); + ClientResourceManager.RegisterScript(this.Page, "~/js/dnn.permissiongrid.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/Components/Tokeninput/Themes/token-input-facebook.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/Components/Tokeninput/Themes/token-input-facebook.css", FileOrder.Css.ResourceCss); } /// - /// Overrides the base OnPreRender method to Bind the Grid to the Permissions + /// Overrides the base OnPreRender method to Bind the Grid to the Permissions. /// protected override void OnPreRender(EventArgs e) { - BindData(); + this.BindData(); - var script = "var pgm = new dnn.permissionGridManager('" + ClientID + "');"; - if (ScriptManager.GetCurrent(Page) != null) + var script = "var pgm = new dnn.permissionGridManager('" + this.ClientID + "');"; + if (ScriptManager.GetCurrent(this.Page) != null) { // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), ClientID + "PermissionGridManager", script, true); + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID + "PermissionGridManager", script, true); } else { - Page.ClientScript.RegisterStartupScript(GetType(), ClientID + "PermissionGridManager", script, true); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "PermissionGridManager", script, true); } } - - - + protected virtual void ParsePermissionKeys(PermissionInfoBase permission, string[] Settings) { permission.PermissionID = Convert.ToInt32(Settings[1]); @@ -1065,116 +1064,118 @@ protected virtual void RemovePermission(int permissionID, int roleID, int userID protected virtual bool SupportsDenyPermissions(PermissionInfo permissionInfo) { - //to maintain backward compatibility the base implementation must always call the simple parameterless version of this method + // to maintain backward compatibility the base implementation must always call the simple parameterless version of this method return false; } /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permission being updated + /// The permission being updated. /// Rold Id. - /// The name of the role - /// The value of the permission + /// The name of the role. + /// The value of the permission. protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, bool allowAccess) { - UpdatePermission(permission, roleId, roleName, allowAccess ? PermissionTypeGrant : PermissionTypeNull); + this.UpdatePermission(permission, roleId, roleName, allowAccess ? PermissionTypeGrant : PermissionTypeNull); } /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permission being updated + /// The permission being updated. /// Role Id. - /// The name of the role - /// The permission state + /// The name of the role. + /// The permission state. protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, string stateKey) { - RemovePermission(permission.PermissionID, roleId, Null.NullInteger); + this.RemovePermission(permission.PermissionID, roleId, Null.NullInteger); switch (stateKey) { case PermissionTypeGrant: - AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, true); + this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, true); break; case PermissionTypeDeny: - AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, false); + this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, false); break; } } /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permission being updated - /// The user's displayname - /// The user's id - /// The value of the permission + /// The permission being updated. + /// The user's displayname. + /// The user's id. + /// The value of the permission. protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, bool allowAccess) { - UpdatePermission(permission, displayName, userId, allowAccess ? PermissionTypeGrant : PermissionTypeNull); + this.UpdatePermission(permission, displayName, userId, allowAccess ? PermissionTypeGrant : PermissionTypeNull); } /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permission being updated - /// The user's displayname - /// The user's id - /// The permission state + /// The permission being updated. + /// The user's displayname. + /// The user's id. + /// The permission state. protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, string stateKey) { - RemovePermission(permission.PermissionID, int.Parse(Globals.glbRoleNothing), userId); + this.RemovePermission(permission.PermissionID, int.Parse(Globals.glbRoleNothing), userId); switch (stateKey) { case PermissionTypeGrant: - AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, true); + this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, true); break; case PermissionTypeDeny: - AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, false); + this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, false); break; } } + /// - /// Updates the permissions + /// Updates the permissions. /// protected void UpdatePermissions() { - EnsureChildControls(); - GetRoles(); - UpdateRolePermissions(); - _users = GetUsers(); - UpdateUserPermissions(); + this.EnsureChildControls(); + this.GetRoles(); + this.UpdateRolePermissions(); + this._users = this.GetUsers(); + this.UpdateUserPermissions(); } /// - /// Updates the permissions + /// Updates the permissions. /// protected void UpdateRolePermissions() { - if (rolePermissionsGrid != null && !RefreshGrid) + if (this.rolePermissionsGrid != null && !this.RefreshGrid) { - var rolesList = Roles.Cast().ToList(); - foreach (DataGridItem dgi in rolePermissionsGrid.Items) + var rolesList = this.Roles.Cast().ToList(); + foreach (DataGridItem dgi in this.rolePermissionsGrid.Items) { var roleId = int.Parse(dgi.Cells[1].Text); if (rolesList.All(r => r.RoleID != roleId)) { continue; } - for (int i = 2; i <= dgi.Cells.Count - 2; i++) + + for (int i = 2; i <= dgi.Cells.Count - 2; i++) { - //all except first two cells which is role names and role ids and last column is Actions + // all except first two cells which is role names and role ids and last column is Actions if (dgi.Cells[i].Controls.Count > 0) { - var permissionInfo = (PermissionInfo)_permissions[i - 2]; + var permissionInfo = (PermissionInfo)this._permissions[i - 2]; var triState = (PermissionTriState)dgi.Cells[i].Controls[0]; - if (SupportsDenyPermissions(permissionInfo)) + if (this.SupportsDenyPermissions(permissionInfo)) { - UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value); + this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value); } else { - UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value == PermissionTypeGrant); + this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value == PermissionTypeGrant); } } } @@ -1183,130 +1184,126 @@ protected void UpdateRolePermissions() } /// - /// Updates the permissions + /// Updates the permissions. /// protected void UpdateUserPermissions() { - if (userPermissionsGrid != null && !RefreshGrid) + if (this.userPermissionsGrid != null && !this.RefreshGrid) { - var usersList = _users.Cast().ToList(); - foreach (DataGridItem dgi in userPermissionsGrid.Items) - { + var usersList = this._users.Cast().ToList(); + foreach (DataGridItem dgi in this.userPermissionsGrid.Items) + { var userId = int.Parse(dgi.Cells[1].Text); if (usersList.All(u => u.UserID != userId)) { continue; } + for (int i = 2; i <= dgi.Cells.Count - 2; i++) { - //all except first two cells which is displayname and userid and Last column is Actions + // all except first two cells which is displayname and userid and Last column is Actions if (dgi.Cells[i].Controls.Count > 0) { - var permissionInfo = (PermissionInfo)_permissions[i - 2]; + var permissionInfo = (PermissionInfo)this._permissions[i - 2]; var triState = (PermissionTriState)dgi.Cells[i].Controls[0]; - if (SupportsDenyPermissions(permissionInfo)) + if (this.SupportsDenyPermissions(permissionInfo)) { - UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value); + this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value); } else { - UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value == PermissionTypeGrant); + this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value == PermissionTypeGrant); } } } } } - } - - #endregion - - #region Event Handlers - + } + /// - /// RoleGroupsSelectedIndexChanged runs when the Role Group is changed + /// RoleGroupsSelectedIndexChanged runs when the Role Group is changed. /// protected virtual void RoleGroupsSelectedIndexChanged(object sender, EventArgs e) { - FillSelectRoleComboBox(Int32.Parse(cboRoleGroups.SelectedValue)); + this.FillSelectRoleComboBox(int.Parse(this.cboRoleGroups.SelectedValue)); } /// - /// AddUser runs when the Add user linkbutton is clicked + /// AddUser runs when the Add user linkbutton is clicked. /// protected virtual void AddUser(object sender, EventArgs e) { - UpdatePermissions(); - if (!string.IsNullOrEmpty(hiddenUserIds.Value)) + this.UpdatePermissions(); + if (!string.IsNullOrEmpty(this.hiddenUserIds.Value)) { - foreach (var id in hiddenUserIds.Value.Split(',')) + foreach (var id in this.hiddenUserIds.Value.Split(',')) { var userId = Convert.ToInt32(id); - var user = UserController.GetUserById(PortalId, userId); + var user = UserController.GetUserById(this.PortalId, userId); if (user != null) { - AddPermission(_permissions, user); - BindData(); + this.AddPermission(this._permissions, user); + this.BindData(); } } - txtUser.Text = hiddenUserIds.Value = string.Empty; + this.txtUser.Text = this.hiddenUserIds.Value = string.Empty; } } /// - /// AddRole runs when the Add Role linkbutton is clicked + /// AddRole runs when the Add Role linkbutton is clicked. /// - void AddRole(object sender, EventArgs e) + private void AddRole(object sender, EventArgs e) { - UpdatePermissions(); + this.UpdatePermissions(); int selectedRoleId; - if (!Int32.TryParse(roleField.Value, out selectedRoleId)) + if (!int.TryParse(this.roleField.Value, out selectedRoleId)) { - //Role not selected - SetErrorMessage("InvalidRoleId"); + // Role not selected + this.SetErrorMessage("InvalidRoleId"); return; } - //verify role - var role = GetSelectedRole(selectedRoleId); + // verify role + var role = this.GetSelectedRole(selectedRoleId); if (role != null) { - AddPermission(_permissions, role); - BindData(); + this.AddPermission(this._permissions, role); + this.BindData(); } else { - //role does not exist - SetErrorMessage("RoleNotFound"); - } + // role does not exist + this.SetErrorMessage("RoleNotFound"); + } } private RoleInfo GetSelectedRole(int selectedRoleId) { RoleInfo role = null; - if (selectedRoleId == AllUsersRoleId) + if (selectedRoleId == this.AllUsersRoleId) { role = new RoleInfo { - RoleID = AllUsersRoleId, - RoleName = Globals.glbRoleAllUsersName + RoleID = this.AllUsersRoleId, + RoleName = Globals.glbRoleAllUsersName, }; } - else if (selectedRoleId == UnAuthUsersRoleId) + else if (selectedRoleId == this.UnAuthUsersRoleId) { role = new RoleInfo { - RoleID = UnAuthUsersRoleId, - RoleName = Globals.glbRoleUnauthUserName + RoleID = this.UnAuthUsersRoleId, + RoleName = Globals.glbRoleUnauthUserName, }; } else { - role = RoleController.Instance.GetRoleById(PortalId, selectedRoleId); + role = RoleController.Instance.GetRoleById(this.PortalId, selectedRoleId); } + return role; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs index a6c5c58bcb5..7254464461e 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs @@ -1,130 +1,147 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Net.Configuration; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions.Controls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Net.Configuration; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + public class TabPermissionsGrid : PermissionsGrid - { - #region Private Members - + { private List _PermissionsList; private int _TabID = -1; - private TabPermissionCollection _TabPermissions; - - #endregion - - #region Protected Methods - - protected override bool IsFullControl(PermissionInfo permissionInfo) - { - return (permissionInfo.PermissionKey == "EDIT") && PermissionProvider.Instance().SupportsFullControl(); - } - - protected override bool IsViewPermisison(PermissionInfo permissionInfo) - { - return (permissionInfo.PermissionKey == "VIEW"); - } - - protected override List PermissionsList - { - get - { - if (_PermissionsList == null && _TabPermissions != null) - { - _PermissionsList = _TabPermissions.ToList(); - } - return _PermissionsList; - } - } + private TabPermissionCollection _TabPermissions; /// ----------------------------------------------------------------------------- /// - /// Gets the Permissions Collection + /// Gets the Permissions Collection. /// /// ----------------------------------------------------------------------------- public TabPermissionCollection Permissions { get { - //First Update Permissions in case they have been changed - UpdatePermissions(); + // First Update Permissions in case they have been changed + this.UpdatePermissions(); - //Return the TabPermissions - return _TabPermissions; + // Return the TabPermissions + return this._TabPermissions; } } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Id of the Tab + /// Gets or sets and Sets the Id of the Tab. /// /// ----------------------------------------------------------------------------- public int TabID { get { - return _TabID; + return this._TabID; } + set { - _TabID = value; - if (!Page.IsPostBack) + this._TabID = value; + if (!this.Page.IsPostBack) { - GetTabPermissions(); + this.GetTabPermissions(); } } } - /// ----------------------------------------------------------------------------- - /// - /// Gets the TabPermissions from the Data Store - /// - /// ----------------------------------------------------------------------------- - private void GetTabPermissions() + protected override List PermissionsList { - _TabPermissions = new TabPermissionCollection(TabPermissionController.GetTabPermissions(TabID, PortalId)); - _PermissionsList = null; + get + { + if (this._PermissionsList == null && this._TabPermissions != null) + { + this._PermissionsList = this._TabPermissions.ToList(); + } + + return this._PermissionsList; + } + } + + protected override bool IsFullControl(PermissionInfo permissionInfo) + { + return (permissionInfo.PermissionKey == "EDIT") && PermissionProvider.Instance().SupportsFullControl(); + } + + protected override bool IsViewPermisison(PermissionInfo permissionInfo) + { + return permissionInfo.PermissionKey == "VIEW"; } public override void DataBind() { - GetTabPermissions(); + this.GetTabPermissions(); base.DataBind(); } + + public override void GenerateDataGrid() + { + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; + } + + protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) + { + var objPermission = new TabPermissionInfo(permission); + objPermission.TabID = this.TabID; + objPermission.RoleID = roleId; + objPermission.RoleName = roleName; + objPermission.AllowAccess = allowAccess; + objPermission.UserID = userId; + objPermission.DisplayName = displayName; + this._TabPermissions.Add(objPermission, true); + + // Clear Permission List + this._PermissionsList = null; + } /// ----------------------------------------------------------------------------- /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState + /// Gets the TabPermissions from the Data Store. /// - /// A string array of settings + /// ----------------------------------------------------------------------------- + private void GetTabPermissions() + { + this._TabPermissions = new TabPermissionCollection(TabPermissionController.GetTabPermissions(this.TabID, this.PortalId)); + this._PermissionsList = null; + } + + /// ----------------------------------------------------------------------------- + /// + /// Parse the Permission Keys used to persist the Permissions in the ViewState. + /// + /// A string array of settings. /// ----------------------------------------------------------------------------- private TabPermissionInfo ParseKeys(string[] Settings) { var objTabPermission = new TabPermissionInfo(); - //Call base class to load base properties - base.ParsePermissionKeys(objTabPermission, Settings); - if (String.IsNullOrEmpty(Settings[2])) + // Call base class to load base properties + this.ParsePermissionKeys(objTabPermission, Settings); + if (string.IsNullOrEmpty(Settings[2])) { objTabPermission.TabPermissionID = -1; } @@ -132,7 +149,8 @@ private TabPermissionInfo ParseKeys(string[] Settings) { objTabPermission.TabPermissionID = Convert.ToInt32(Settings[2]); } - objTabPermission.TabID = TabID; + + objTabPermission.TabID = this.TabID; return objTabPermission; } @@ -143,8 +161,8 @@ private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) { - var roleID = Int32.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) { var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; if (actionImage != null) @@ -160,39 +178,18 @@ private bool IsImplicitRole(int portalId, int roleId) return TabPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); } - protected override void CreateChildControls() - { - base.CreateChildControls(); - rolePermissionsGrid.ItemDataBound += rolePermissionsGrid_ItemDataBound; - } - - protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) - { - var objPermission = new TabPermissionInfo(permission); - objPermission.TabID = TabID; - objPermission.RoleID = roleId; - objPermission.RoleName = roleName; - objPermission.AllowAccess = allowAccess; - objPermission.UserID = userId; - objPermission.DisplayName = displayName; - _TabPermissions.Add(objPermission, true); - - //Clear Permission List - _PermissionsList = null; - } - /// ----------------------------------------------------------------------------- /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The user to add + /// The permissions collection. + /// The user to add. /// ----------------------------------------------------------------------------- protected override void AddPermission(ArrayList permissions, UserInfo user) { - //Search TabPermission Collection for the user + // Search TabPermission Collection for the user bool isMatch = false; - foreach (TabPermissionInfo objTabPermission in _TabPermissions) + foreach (TabPermissionInfo objTabPermission in this._TabPermissions) { if (objTabPermission.UserID == user.UserID) { @@ -201,14 +198,14 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) } } - //user not found so add new + // user not found so add new if (!isMatch) { foreach (PermissionInfo objPermission in permissions) { if (objPermission.PermissionKey == "VIEW") { - AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); } } } @@ -216,72 +213,75 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) /// ----------------------------------------------------------------------------- /// - /// Updates a Permission + /// Updates a Permission. /// - /// The permissions collection - /// The role to add + /// The permissions collection. + /// The role to add. /// ----------------------------------------------------------------------------- protected override void AddPermission(ArrayList permissions, RoleInfo role) { - //Search TabPermission Collection for the user - if (_TabPermissions.Cast().Any(objTabPermission => objTabPermission.RoleID == role.RoleID)) + // Search TabPermission Collection for the user + if (this._TabPermissions.Cast().Any(objTabPermission => objTabPermission.RoleID == role.RoleID)) { return; } - //role not found so add new + // role not found so add new foreach (PermissionInfo objPermission in permissions) { if (objPermission.PermissionKey == "VIEW") { - AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); + this.AddPermission(objPermission, role.RoleID, role.RoleName, Null.NullInteger, Null.NullString, true); } } } /// ----------------------------------------------------------------------------- /// - /// Gets the Enabled status of the permission + /// Gets the Enabled status of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) { - return !IsImplicitRole(role.PortalID, role.RoleID); + return !this.IsImplicitRole(role.PortalID, role.RoleID); } /// ----------------------------------------------------------------------------- /// - /// Gets the Value of the permission + /// Gets the Value of the permission. /// - /// The permission being loaded - /// The role - /// The column of the Grid + /// The permission being loaded. + /// The role. + /// The column of the Grid. /// Default State. - /// A Boolean (True or False) + /// A Boolean (True or False). /// ----------------------------------------------------------------------------- protected override string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState) { string permission; - if (role.RoleID == AdministratorRoleId) + if (role.RoleID == this.AdministratorRoleId) { permission = PermissionTypeGrant; } else { - //Call base class method to handle standard permissions + // Call base class method to handle standard permissions permission = base.GetPermission(objPerm, role, column, PermissionTypeNull); } + return permission; } /// ----------------------------------------------------------------------------- /// - /// Gets the permissions from the Database - /// + /// Gets the permissions from the Database. + /// + /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() { @@ -290,42 +290,42 @@ protected override ArrayList GetPermissions() /// ----------------------------------------------------------------------------- /// - /// Load the ViewState + /// Load the ViewState. /// - /// The saved state + /// The saved state. /// ----------------------------------------------------------------------------- protected override void LoadViewState(object savedState) { if (savedState != null) { - //Load State from the array of objects that was saved with SaveViewState. + // Load State from the array of objects that was saved with SaveViewState. var myState = (object[])savedState; - //Load Base Controls ViewState + // Load Base Controls ViewState if (myState[0] != null) { base.LoadViewState(myState[0]); } - //Load TabId + // Load TabId if (myState[1] != null) { - TabID = Convert.ToInt32(myState[1]); + this.TabID = Convert.ToInt32(myState[1]); } - //Load TabPermissions + // Load TabPermissions if (myState[2] != null) { - _TabPermissions = new TabPermissionCollection(); + this._TabPermissions = new TabPermissionCollection(); string state = Convert.ToString(myState[2]); - if (!String.IsNullOrEmpty(state)) + if (!string.IsNullOrEmpty(state)) { - //First Break the String into individual Keys + // First Break the String into individual Keys string[] permissionKeys = state.Split(new[] { "##" }, StringSplitOptions.None); foreach (string key in permissionKeys) { string[] Settings = key.Split('|'); - _TabPermissions.Add(ParseKeys(Settings)); + this._TabPermissions.Add(this.ParseKeys(Settings)); } } } @@ -334,32 +334,34 @@ protected override void LoadViewState(object savedState) protected override void RemovePermission(int permissionID, int roleID, int userID) { - _TabPermissions.Remove(permissionID, roleID, userID); - //Clear Permission List - _PermissionsList = null; + this._TabPermissions.Remove(permissionID, roleID, userID); + + // Clear Permission List + this._PermissionsList = null; } /// ----------------------------------------------------------------------------- /// - /// Saves the ViewState - /// + /// Saves the ViewState. + /// + /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() { var allStates = new object[3]; - //Save the Base Controls ViewState + // Save the Base Controls ViewState allStates[0] = base.SaveViewState(); - //Save the Tab Id - allStates[1] = TabID; + // Save the Tab Id + allStates[1] = this.TabID; - //Persist the TabPermisisons + // Persist the TabPermisisons var sb = new StringBuilder(); - if (_TabPermissions != null) + if (this._TabPermissions != null) { bool addDelimiter = false; - foreach (TabPermissionInfo objTabPermission in _TabPermissions) + foreach (TabPermissionInfo objTabPermission in this._TabPermissions) { if (addDelimiter) { @@ -369,37 +371,31 @@ protected override object SaveViewState() { addDelimiter = true; } - sb.Append(BuildKey(objTabPermission.AllowAccess, - objTabPermission.PermissionID, - objTabPermission.TabPermissionID, - objTabPermission.RoleID, - objTabPermission.RoleName, - objTabPermission.UserID, - objTabPermission.DisplayName)); + + sb.Append(this.BuildKey( + objTabPermission.AllowAccess, + objTabPermission.PermissionID, + objTabPermission.TabPermissionID, + objTabPermission.RoleID, + objTabPermission.RoleName, + objTabPermission.UserID, + objTabPermission.DisplayName)); } } + allStates[2] = sb.ToString(); return allStates; } /// ----------------------------------------------------------------------------- /// - /// returns whether or not the derived grid supports Deny permissions - /// + /// returns whether or not the derived grid supports Deny permissions. + /// + /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; - } - - #endregion - - #region Public Methods - - public override void GenerateDataGrid() - { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/CorePermissionProvider.cs b/DNN Platform/Library/Security/Permissions/CorePermissionProvider.cs index 2fd1d6aacf3..d02541153f1 100644 --- a/DNN Platform/Library/Security/Permissions/CorePermissionProvider.cs +++ b/DNN Platform/Library/Security/Permissions/CorePermissionProvider.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Permissions { public class CorePermissionProvider : PermissionProvider diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs index 263e10f2495..4a4a1939eb6 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs @@ -1,27 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : DesktopModulePermissionCollection + /// Class : DesktopModulePermissionCollection /// ----------------------------------------------------------------------------- /// /// DesktopModulePermissionCollection provides the a custom collection for DesktopModulePermissionInfo - /// objects + /// objects. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -33,12 +28,12 @@ public DesktopModulePermissionCollection() public DesktopModulePermissionCollection(ArrayList DesktopModulePermissions) { - AddRange(DesktopModulePermissions); + this.AddRange(DesktopModulePermissions); } public DesktopModulePermissionCollection(DesktopModulePermissionCollection DesktopModulePermissions) { - AddRange(DesktopModulePermissions); + this.AddRange(DesktopModulePermissions); } public DesktopModulePermissionCollection(ArrayList DesktopModulePermissions, int DesktopModulePermissionID) @@ -47,7 +42,7 @@ public DesktopModulePermissionCollection(ArrayList DesktopModulePermissions, int { if (permission.DesktopModulePermissionID == DesktopModulePermissionID) { - Add(permission); + this.Add(permission); } } } @@ -56,17 +51,18 @@ public DesktopModulePermissionInfo this[int index] { get { - return (DesktopModulePermissionInfo) List[index]; + return (DesktopModulePermissionInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } public int Add(DesktopModulePermissionInfo value) { - return List.Add(value); + return this.List.Add(value); } public int Add(DesktopModulePermissionInfo value, bool checkForDuplicates) @@ -74,12 +70,12 @@ public int Add(DesktopModulePermissionInfo value, bool checkForDuplicates) int id = Null.NullInteger; if (!checkForDuplicates) { - id = Add(value); + id = this.Add(value); } else { bool isMatch = false; - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) { @@ -87,9 +83,10 @@ public int Add(DesktopModulePermissionInfo value, bool checkForDuplicates) break; } } + if (!isMatch) { - id = Add(value); + id = this.Add(value); } } @@ -100,7 +97,7 @@ public void AddRange(ArrayList DesktopModulePermissions) { foreach (DesktopModulePermissionInfo permission in DesktopModulePermissions) { - Add(permission); + this.Add(permission); } } @@ -108,55 +105,57 @@ public void AddRange(DesktopModulePermissionCollection DesktopModulePermissions) { foreach (DesktopModulePermissionInfo permission in DesktopModulePermissions) { - Add(permission); + this.Add(permission); } } public bool CompareTo(DesktopModulePermissionCollection objDesktopModulePermissionCollection) { - if (objDesktopModulePermissionCollection.Count != Count) + if (objDesktopModulePermissionCollection.Count != this.Count) { return false; } - InnerList.Sort(new CompareDesktopModulePermissions()); + + this.InnerList.Sort(new CompareDesktopModulePermissions()); objDesktopModulePermissionCollection.InnerList.Sort(new CompareDesktopModulePermissions()); - for (int i = 0; i <= Count - 1; i++) + for (int i = 0; i <= this.Count - 1; i++) { if (objDesktopModulePermissionCollection[i].DesktopModulePermissionID != this[i].DesktopModulePermissionID || objDesktopModulePermissionCollection[i].AllowAccess != this[i].AllowAccess) { return false; } } + return true; } public bool Contains(DesktopModulePermissionInfo value) { - return List.Contains(value); + return this.List.Contains(value); } public int IndexOf(DesktopModulePermissionInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } public void Insert(int index, DesktopModulePermissionInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } public void Remove(DesktopModulePermissionInfo value) { - List.Remove(value); + this.List.Remove(value); } public void Remove(int permissionID, int roleID, int userID) { - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == permissionID && permission.UserID == userID && permission.RoleID == roleID) { - List.Remove(permission); + this.List.Remove(permission); break; } } @@ -165,16 +164,17 @@ public void Remove(int permissionID, int roleID, int userID) public List ToList() { var list = new List(); - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { list.Add(permission); } + return list; } public string ToString(string key) { - return PermissionController.BuildPermissions(List, key); + return PermissionController.BuildPermissions(this.List, key); } } } diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs index 39d74e38dec..1daa26576e3 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs @@ -1,131 +1,131 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : DesktopModulePermissionController + /// Class : DesktopModulePermissionController /// ----------------------------------------------------------------------------- /// - /// DesktopModulePermissionController provides the Business Layer for DesktopModule Permissions + /// DesktopModulePermissionController provides the Business Layer for DesktopModule Permissions. /// /// ----------------------------------------------------------------------------- [Serializable] public class DesktopModulePermissionController { private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - + /// ----------------------------------------------------------------------------- /// - /// ClearPermissionCache clears the DesktopModule Permission Cache + /// AddDesktopModulePermission adds a DesktopModule Permission to the Database. /// + /// The DesktopModule Permission to add. + /// /// ----------------------------------------------------------------------------- - private static void ClearPermissionCache() + public static int AddDesktopModulePermission(DesktopModulePermissionInfo objDesktopModulePermission) { - DataCache.ClearDesktopModulePermissionsCache(); + int Id = DataProvider.Instance().AddDesktopModulePermission( + objDesktopModulePermission.PortalDesktopModuleID, + objDesktopModulePermission.PermissionID, + objDesktopModulePermission.RoleID, + objDesktopModulePermission.AllowAccess, + objDesktopModulePermission.UserID, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog( + objDesktopModulePermission, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + EventLogController.EventLogType.DESKTOPMODULEPERMISSION_CREATED); + ClearPermissionCache(); + return Id; } - #region Public Shared Methods - /// ----------------------------------------------------------------------------- /// - /// AddDesktopModulePermission adds a DesktopModule Permission to the Database + /// DeleteDesktopModulePermission deletes a DesktopModule Permission in the Database. /// - /// The DesktopModule Permission to add + /// The ID of the DesktopModule Permission to delete. /// ----------------------------------------------------------------------------- - public static int AddDesktopModulePermission(DesktopModulePermissionInfo objDesktopModulePermission) + public static void DeleteDesktopModulePermission(int DesktopModulePermissionID) { - int Id = DataProvider.Instance().AddDesktopModulePermission(objDesktopModulePermission.PortalDesktopModuleID, - objDesktopModulePermission.PermissionID, - objDesktopModulePermission.RoleID, - objDesktopModulePermission.AllowAccess, - objDesktopModulePermission.UserID, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(objDesktopModulePermission, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - "", - EventLogController.EventLogType.DESKTOPMODULEPERMISSION_CREATED); + DataProvider.Instance().DeleteDesktopModulePermission(DesktopModulePermissionID); + EventLogController.Instance.AddLog( + "DesktopModulePermissionID", + DesktopModulePermissionID.ToString(CultureInfo.InvariantCulture), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.DESKTOPMODULEPERMISSION_DELETED); ClearPermissionCache(); - return Id; } /// ----------------------------------------------------------------------------- /// - /// DeleteDesktopModulePermission deletes a DesktopModule Permission in the Database + /// ClearPermissionCache clears the DesktopModule Permission Cache. /// - /// The ID of the DesktopModule Permission to delete /// ----------------------------------------------------------------------------- - public static void DeleteDesktopModulePermission(int DesktopModulePermissionID) + private static void ClearPermissionCache() { - DataProvider.Instance().DeleteDesktopModulePermission(DesktopModulePermissionID); - EventLogController.Instance.AddLog("DesktopModulePermissionID", - DesktopModulePermissionID.ToString(CultureInfo.InvariantCulture), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.DESKTOPMODULEPERMISSION_DELETED); - ClearPermissionCache(); - } + DataCache.ClearDesktopModulePermissionsCache(); + } /// ----------------------------------------------------------------------------- /// /// DeleteDesktopModulePermissionsByPortalDesktopModuleID deletes a DesktopModule's - /// DesktopModule Permission in the Database + /// DesktopModule Permission in the Database. /// - /// The ID of the DesktopModule to delete + /// The ID of the DesktopModule to delete. /// ----------------------------------------------------------------------------- public static void DeleteDesktopModulePermissionsByPortalDesktopModuleID(int portalDesktopModuleID) { DataProvider.Instance().DeleteDesktopModulePermissionsByPortalDesktopModuleID(portalDesktopModuleID); - EventLogController.Instance.AddLog("PortalDesktopModuleID", - portalDesktopModuleID.ToString(CultureInfo.InvariantCulture), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.DESKTOPMODULE_DELETED); + EventLogController.Instance.AddLog( + "PortalDesktopModuleID", + portalDesktopModuleID.ToString(CultureInfo.InvariantCulture), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.DESKTOPMODULE_DELETED); ClearPermissionCache(); } /// ----------------------------------------------------------------------------- /// - /// DeleteDesktopModulePermissionsByUserID deletes a user's DesktopModule Permission in the Database + /// DeleteDesktopModulePermissionsByUserID deletes a user's DesktopModule Permission in the Database. /// - /// The user + /// The user. /// ----------------------------------------------------------------------------- public static void DeleteDesktopModulePermissionsByUserID(UserInfo objUser) { DataProvider.Instance().DeleteDesktopModulePermissionsByUserID(objUser.UserID, objUser.PortalID); - EventLogController.Instance.AddLog("UserID", - objUser.UserID.ToString(CultureInfo.InvariantCulture), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.DESKTOPMODULE_DELETED); + EventLogController.Instance.AddLog( + "UserID", + objUser.UserID.ToString(CultureInfo.InvariantCulture), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.DESKTOPMODULE_DELETED); ClearPermissionCache(); } /// ----------------------------------------------------------------------------- /// - /// GetDesktopModulePermission gets a DesktopModule Permission from the Database + /// GetDesktopModulePermission gets a DesktopModule Permission from the Database. /// - /// The ID of the DesktopModule Permission + /// The ID of the DesktopModule Permission. + /// /// ----------------------------------------------------------------------------- public static DesktopModulePermissionInfo GetDesktopModulePermission(int DesktopModulePermissionID) { @@ -134,9 +134,10 @@ public static DesktopModulePermissionInfo GetDesktopModulePermission(int Desktop /// ----------------------------------------------------------------------------- /// - /// GetDesktopModulePermissions gets a DesktopModulePermissionCollection + /// GetDesktopModulePermissions gets a DesktopModulePermissionCollection. /// - /// The ID of the DesktopModule + /// The ID of the DesktopModule. + /// /// ----------------------------------------------------------------------------- public static DesktopModulePermissionCollection GetDesktopModulePermissions(int portalDesktopModuleID) { @@ -145,10 +146,11 @@ public static DesktopModulePermissionCollection GetDesktopModulePermissions(int /// ----------------------------------------------------------------------------- /// - /// HasDesktopModulePermission checks whether the current user has a specific DesktopModule Permission + /// HasDesktopModulePermission checks whether the current user has a specific DesktopModule Permission. /// - /// The Permissions for the DesktopModule - /// The Permission to check + /// The Permissions for the DesktopModule. + /// The Permission to check. + /// /// ----------------------------------------------------------------------------- public static bool HasDesktopModulePermission(DesktopModulePermissionCollection objDesktopModulePermissions, string permissionKey) { @@ -157,27 +159,27 @@ public static bool HasDesktopModulePermission(DesktopModulePermissionCollection /// ----------------------------------------------------------------------------- /// - /// UpdateDesktopModulePermission updates a DesktopModule Permission in the Database + /// UpdateDesktopModulePermission updates a DesktopModule Permission in the Database. /// - /// The DesktopModule Permission to update + /// The DesktopModule Permission to update. /// ----------------------------------------------------------------------------- public static void UpdateDesktopModulePermission(DesktopModulePermissionInfo objDesktopModulePermission) { - DataProvider.Instance().UpdateDesktopModulePermission(objDesktopModulePermission.DesktopModulePermissionID, - objDesktopModulePermission.PortalDesktopModuleID, - objDesktopModulePermission.PermissionID, - objDesktopModulePermission.RoleID, - objDesktopModulePermission.AllowAccess, - objDesktopModulePermission.UserID, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(objDesktopModulePermission, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - "", - EventLogController.EventLogType.DESKTOPMODULEPERMISSION_UPDATED); + DataProvider.Instance().UpdateDesktopModulePermission( + objDesktopModulePermission.DesktopModulePermissionID, + objDesktopModulePermission.PortalDesktopModuleID, + objDesktopModulePermission.PermissionID, + objDesktopModulePermission.RoleID, + objDesktopModulePermission.AllowAccess, + objDesktopModulePermission.UserID, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog( + objDesktopModulePermission, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + EventLogController.EventLogType.DESKTOPMODULEPERMISSION_UPDATED); ClearPermissionCache(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs index c20ce7f58f4..5a8cab91ec0 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs @@ -1,154 +1,137 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : DesktopModulePermissionInfo + /// Class : DesktopModulePermissionInfo /// ----------------------------------------------------------------------------- /// /// DesktopModulePermissionInfo provides the Entity Layer for DesktopModulePermissionInfo - /// Permissions + /// Permissions. /// /// ----------------------------------------------------------------------------- [Serializable] public class DesktopModulePermissionInfo : PermissionInfoBase, IHydratable - { - #region "Private Members" - - //local property declarations + { + // local property declarations private int _desktopModulePermissionID; - private int _portalDesktopModuleID; - - #endregion - - #region "Constructors" - + private int _portalDesktopModuleID; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new DesktopModulePermissionInfo + /// + /// Initializes a new instance of the class. + /// Constructs a new DesktopModulePermissionInfo. /// /// ----------------------------------------------------------------------------- - public DesktopModulePermissionInfo() + public DesktopModulePermissionInfo() { - _desktopModulePermissionID = Null.NullInteger; - _portalDesktopModuleID = Null.NullInteger; - } - - /// ----------------------------------------------------------------------------- - /// - /// Constructs a new DesktopModulePermissionInfo + this._desktopModulePermissionID = Null.NullInteger; + this._portalDesktopModuleID = Null.NullInteger; + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new DesktopModulePermissionInfo. /// - /// A PermissionInfo object + /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public DesktopModulePermissionInfo(PermissionInfo permission) : this() + public DesktopModulePermissionInfo(PermissionInfo permission) + : this() { - ModuleDefID = permission.ModuleDefID; - PermissionCode = permission.PermissionCode; - PermissionID = permission.PermissionID; - PermissionKey = permission.PermissionKey; - PermissionName = permission.PermissionName; - } - - #endregion - - #region "Public Properties" - + this.ModuleDefID = permission.ModuleDefID; + this.PermissionCode = permission.PermissionCode; + this.PermissionID = permission.PermissionID; + this.PermissionKey = permission.PermissionKey; + this.PermissionName = permission.PermissionName; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the DesktopModule Permission ID + /// Gets or sets and sets the DesktopModule Permission ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int DesktopModulePermissionID { get { - return _desktopModulePermissionID; + return this._desktopModulePermissionID; } + set { - _desktopModulePermissionID = value; + this._desktopModulePermissionID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the PortalDesktopModule ID + /// Gets or sets and sets the PortalDesktopModule ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int PortalDesktopModuleID { get { - return _portalDesktopModuleID; + return this._portalDesktopModuleID; } + set { - _portalDesktopModuleID = value; + this._portalDesktopModuleID = value; } - } - - #endregion - - #region IHydratable Members - - /// ----------------------------------------------------------------------------- - /// - /// Fills a DesktopModulePermissionInfo from a Data Reader - /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - base.FillInternal(dr); - DesktopModulePermissionID = Null.SetNullInteger(dr["DesktopModulePermissionID"]); - PortalDesktopModuleID = Null.SetNullInteger(dr["PortalDesktopModuleID"]); - } + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Key ID + /// Gets or sets and sets the Key ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int KeyID { get { - return DesktopModulePermissionID; + return this.DesktopModulePermissionID; } + set { - DesktopModulePermissionID = value; + this.DesktopModulePermissionID = value; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a DesktopModulePermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.FillInternal(dr); + this.DesktopModulePermissionID = Null.SetNullInteger(dr["DesktopModulePermissionID"]); + this.PortalDesktopModuleID = Null.SetNullInteger(dr["PortalDesktopModuleID"]); } - - #endregion - - #region "Public Methods" - + /// ----------------------------------------------------------------------------- /// - /// Compares if two DesktopModulePermissionInfo objects are equivalent/equal + /// Compares if two DesktopModulePermissionInfo objects are equivalent/equal. /// - /// a DesktopModulePermissionObject + /// a DesktopModulePermissionObject. /// true if the permissions being passed represents the same permission - /// in the current object + /// in the current object. /// /// /// This function is needed to prevent adding duplicates to the DesktopModulePermissionCollection. @@ -162,20 +145,22 @@ public bool Equals(DesktopModulePermissionInfo other) { return false; } + if (ReferenceEquals(this, other)) { return true; } - return (AllowAccess == other.AllowAccess) && (PortalDesktopModuleID == other.PortalDesktopModuleID) && (RoleID == other.RoleID) && (PermissionID == other.PermissionID); + + return (this.AllowAccess == other.AllowAccess) && (this.PortalDesktopModuleID == other.PortalDesktopModuleID) && (this.RoleID == other.RoleID) && (this.PermissionID == other.PermissionID); } /// ----------------------------------------------------------------------------- /// - /// Compares if two DesktopModulePermissionInfo objects are equivalent/equal + /// Compares if two DesktopModulePermissionInfo objects are equivalent/equal. /// - /// a DesktopModulePermissionObject + /// a DesktopModulePermissionObject. /// true if the permissions being passed represents the same permission - /// in the current object + /// in the current object. /// /// /// This function is needed to prevent adding duplicates to the DesktopModulePermissionCollection. @@ -189,25 +174,26 @@ public override bool Equals(object obj) { return false; } + if (ReferenceEquals(this, obj)) { return true; } - if (obj.GetType() != typeof (DesktopModulePermissionInfo)) + + if (obj.GetType() != typeof(DesktopModulePermissionInfo)) { return false; } - return Equals((DesktopModulePermissionInfo) obj); + + return this.Equals((DesktopModulePermissionInfo)obj); } public override int GetHashCode() { unchecked { - return (_desktopModulePermissionID*397) ^ _portalDesktopModuleID; + return (this._desktopModulePermissionID * 397) ^ this._portalDesktopModuleID; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs index c5f463cb1a3..ba262ea8e37 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + [Serializable] public class FolderPermissionCollection : CollectionBase { @@ -23,12 +18,12 @@ public FolderPermissionCollection() public FolderPermissionCollection(ArrayList folderPermissions) { - AddRange(folderPermissions); + this.AddRange(folderPermissions); } public FolderPermissionCollection(FolderPermissionCollection folderPermissions) { - AddRange(folderPermissions); + this.AddRange(folderPermissions); } public FolderPermissionCollection(ArrayList folderPermissions, string FolderPath) @@ -37,7 +32,7 @@ public FolderPermissionCollection(ArrayList folderPermissions, string FolderPath { if (permission.FolderPath.Equals(FolderPath, StringComparison.InvariantCultureIgnoreCase)) { - Add(permission); + this.Add(permission); } } } @@ -46,17 +41,18 @@ public FolderPermissionInfo this[int index] { get { - return (FolderPermissionInfo) List[index]; + return (FolderPermissionInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } public int Add(FolderPermissionInfo value) { - return List.Add(value); + return this.List.Add(value); } public int Add(FolderPermissionInfo value, bool checkForDuplicates) @@ -64,12 +60,12 @@ public int Add(FolderPermissionInfo value, bool checkForDuplicates) int id = Null.NullInteger; if (!checkForDuplicates) { - id = Add(value); + id = this.Add(value); } else { bool isMatch = false; - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) { @@ -77,9 +73,10 @@ public int Add(FolderPermissionInfo value, bool checkForDuplicates) break; } } + if (!isMatch) { - id = Add(value); + id = this.Add(value); } } @@ -90,7 +87,7 @@ public void AddRange(ArrayList folderPermissions) { foreach (FolderPermissionInfo permission in folderPermissions) { - List.Add(permission); + this.List.Add(permission); } } @@ -98,32 +95,32 @@ public void AddRange(FolderPermissionCollection folderPermissions) { foreach (FolderPermissionInfo permission in folderPermissions) { - List.Add(permission); + this.List.Add(permission); } } public int IndexOf(FolderPermissionInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } public void Insert(int index, FolderPermissionInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } public void Remove(FolderPermissionInfo value) { - List.Remove(value); + this.List.Remove(value); } public void Remove(int permissionID, int roleID, int userID) { - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == permissionID && permission.UserID == userID && permission.RoleID == roleID) { - List.Remove(permission); + this.List.Remove(permission); break; } } @@ -131,13 +128,13 @@ public void Remove(int permissionID, int roleID, int userID) public bool Contains(FolderPermissionInfo value) { - return List.Contains(value); + return this.List.Contains(value); } public bool Contains(string key, int folderId, int roleId, int userId) { bool result = Null.NullBoolean; - foreach (FolderPermissionInfo permission in List) + foreach (FolderPermissionInfo permission in this.List) { if (permission.PermissionKey == key && permission.FolderID == folderId && permission.RoleID == roleId && permission.UserID == userId) { @@ -145,41 +142,44 @@ public bool Contains(string key, int folderId, int roleId, int userId) break; } } + return result; } - - + public bool CompareTo(FolderPermissionCollection objFolderPermissionCollection) { - if (objFolderPermissionCollection.Count != Count) + if (objFolderPermissionCollection.Count != this.Count) { return false; } - InnerList.Sort(new CompareFolderPermissions()); + + this.InnerList.Sort(new CompareFolderPermissions()); objFolderPermissionCollection.InnerList.Sort(new CompareFolderPermissions()); - for (int i = 0; i <= Count - 1; i++) + for (int i = 0; i <= this.Count - 1; i++) { if (objFolderPermissionCollection[i].FolderPermissionID != this[i].FolderPermissionID || objFolderPermissionCollection[i].AllowAccess != this[i].AllowAccess) { return false; } } + return true; } public List ToList() { var list = new List(); - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { list.Add(permission); } + return list; } public string ToString(string key) { - return PermissionController.BuildPermissions(List, key); + return PermissionController.BuildPermissions(this.List, key); } } } diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs index 2b87fcf7c69..b3db7f2d3b4 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs @@ -1,64 +1,76 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + public partial class FolderPermissionController : ServiceLocator, IFolderPermissionController { private static readonly PermissionProvider provider = PermissionProvider.Instance(); - protected override Func GetFactory() + /// + /// Returns a list with all roles with implicit permissions on Folders. + /// + /// The Portal Id where the Roles are. + /// A List with the implicit roles. + public static IEnumerable ImplicitRoles(int portalId) { - return () => new FolderPermissionController(); + return provider.ImplicitRolesForPages(portalId); } - #region Public Methods - /// - /// Returns a flag indicating whether the current user can add a folder or file + /// Returns a flag indicating whether the current user can add a folder or file. + /// + /// The page. + /// A flag indicating whether the user has permission. + public static bool CanAddFolder(FolderInfo folder) + { + return provider.CanAddFolder(folder); + } + + /// + /// Returns a flag indicating whether the current user can add a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. bool IFolderPermissionController.CanAddFolder(IFolderInfo folder) { return provider.CanAddFolder((FolderInfo)folder); } /// - /// Returns a flag indicating whether the current user can addmister a folder + /// Returns a flag indicating whether the current user can addmister a folder. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. bool IFolderPermissionController.CanAdminFolder(IFolderInfo folder) { return provider.CanAdminFolder((FolderInfo)folder); } + protected override Func GetFactory() + { + return () => new FolderPermissionController(); + } + /// - /// Returns a flag indicating whether the current user can view a folder or file + /// Returns a flag indicating whether the current user can view a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. bool IFolderPermissionController.CanViewFolder(IFolderInfo folder) { return provider.CanViewFolder((FolderInfo)folder); - } - - #endregion - + } + private static void ClearPermissionCache(int PortalID) { DataCache.ClearFolderPermissionsCache(PortalID); @@ -67,80 +79,60 @@ private static void ClearPermissionCache(int PortalID) } /// - /// Returns a list with all roles with implicit permissions on Folders - /// - /// The Portal Id where the Roles are - /// A List with the implicit roles - public static IEnumerable ImplicitRoles(int portalId) - { - return provider.ImplicitRolesForPages(portalId); - } - - /// - /// Returns a flag indicating whether the current user can add a folder or file - /// - /// The page - /// A flag indicating whether the user has permission - public static bool CanAddFolder(FolderInfo folder) - { - return provider.CanAddFolder(folder); - } - - /// - /// Returns a flag indicating whether the current user can addmister a folder + /// Returns a flag indicating whether the current user can addmister a folder. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanAdminFolder(FolderInfo folder) { return provider.CanAdminFolder(folder); } /// - /// Returns a flag indicating whether the current user can browse the folder + /// Returns a flag indicating whether the current user can browse the folder. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanBrowseFolder(FolderInfo folder) { return provider.CanBrowseFolder(folder); } /// - /// Returns a flag indicating whether the current user can copy a folder or file + /// Returns a flag indicating whether the current user can copy a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanCopyFolder(FolderInfo folder) { return provider.CanCopyFolder(folder); } /// - /// Returns a flag indicating whether the current user can delete a folder or file + /// Returns a flag indicating whether the current user can delete a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanDeleteFolder(FolderInfo folder) { return provider.CanDeleteFolder(folder); } /// - /// Returns a flag indicating whether the current user can manage a folder's settings + /// Returns a flag indicating whether the current user can manage a folder's settings. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanManageFolder(FolderInfo folder) { return provider.CanManageFolder(folder); } /// - /// Returns a flag indicating whether the current user can view a folder or file + /// Returns a flag indicating whether the current user can view a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanViewFolder(FolderInfo folder) { return provider.CanViewFolder(folder); @@ -183,6 +175,7 @@ public static bool HasFolderPermission(FolderPermissionCollection objFolderPermi hasPermission = provider.HasFolderPermission(objFolderPermissions, PermissionKey); } } + return hasPermission; } @@ -200,6 +193,27 @@ public static void CopyPermissionsToSubfolders(IFolderInfo folder, FolderPermiss } } + /// ----------------------------------------------------------------------------- + /// + /// SaveFolderPermissions updates a Folder's permissions. + /// + /// The Folder to update. + /// ----------------------------------------------------------------------------- + public static void SaveFolderPermissions(FolderInfo folder) + { + SaveFolderPermissions((IFolderInfo)folder); + } + + /// + /// SaveFolderPermissions updates a Folder's permissions. + /// + /// The Folder to update. + public static void SaveFolderPermissions(IFolderInfo folder) + { + provider.SaveFolderPermissions(folder); + ClearPermissionCache(folder.PortalID); + } + private static bool CopyPermissionsToSubfoldersRecursive(IFolderInfo folder, FolderPermissionCollection newPermissions) { bool clearCache = Null.NullBoolean; @@ -213,30 +227,11 @@ private static bool CopyPermissionsToSubfoldersRecursive(IFolderInfo folder, Fol SaveFolderPermissions(f); clearCache = true; } + clearCache = CopyPermissionsToSubfoldersRecursive(f, newPermissions) || clearCache; } + return clearCache; } - - /// ----------------------------------------------------------------------------- - /// - /// SaveFolderPermissions updates a Folder's permissions - /// - /// The Folder to update - /// ----------------------------------------------------------------------------- - public static void SaveFolderPermissions(FolderInfo folder) - { - SaveFolderPermissions((IFolderInfo)folder); - } - - /// - /// SaveFolderPermissions updates a Folder's permissions - /// - /// The Folder to update - public static void SaveFolderPermissions(IFolderInfo folder) - { - provider.SaveFolderPermissions(folder); - ClearPermissionCache(folder.PortalID); - } } } diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs index 0878d5a2fd8..bb5db6d1ba1 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs @@ -1,77 +1,66 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + [Serializable] public class FolderPermissionInfo : PermissionInfoBase, IHydratable - { - #region "Private Members" - - //local property declarations + { + // local property declarations private int _folderID; private string _folderPath; private int _folderPermissionID; - private int _portalID; - - #endregion - - #region "Constructors" - + private int _portalID; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new FolderPermissionInfo + /// + /// Initializes a new instance of the class. + /// Constructs a new FolderPermissionInfo. /// /// ----------------------------------------------------------------------------- public FolderPermissionInfo() { - _folderPermissionID = Null.NullInteger; - _folderPath = Null.NullString; - _portalID = Null.NullInteger; - _folderID = Null.NullInteger; - } - + this._folderPermissionID = Null.NullInteger; + this._folderPath = Null.NullString; + this._portalID = Null.NullInteger; + this._folderID = Null.NullInteger; + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new FolderPermissionInfo + /// + /// Initializes a new instance of the class. + /// Constructs a new FolderPermissionInfo. /// - /// A PermissionInfo object + /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public FolderPermissionInfo(PermissionInfo permission) : this() + public FolderPermissionInfo(PermissionInfo permission) + : this() { - ModuleDefID = permission.ModuleDefID; - PermissionCode = permission.PermissionCode; - PermissionID = permission.PermissionID; - PermissionKey = permission.PermissionKey; - PermissionName = permission.PermissionName; - } - - #endregion - - #region "Public Properties" - + this.ModuleDefID = permission.ModuleDefID; + this.PermissionCode = permission.PermissionCode; + this.PermissionID = permission.PermissionID; + this.PermissionKey = permission.PermissionKey; + this.PermissionName = permission.PermissionName; + } + [XmlIgnore] public int FolderPermissionID { get { - return _folderPermissionID; + return this._folderPermissionID; } + set { - _folderPermissionID = value; + this._folderPermissionID = value; } } @@ -80,11 +69,12 @@ public int FolderID { get { - return _folderID; + return this._folderID; } + set { - _folderID = value; + this._folderID = value; } } @@ -93,11 +83,12 @@ public int PortalID { get { - return _portalID; + return this._portalID; } + set { - _portalID = value; + this._portalID = value; } } @@ -106,52 +97,48 @@ public string FolderPath { get { - return _folderPath; + return this._folderPath; } + set { - _folderPath = value; + this._folderPath = value; } - } - - #endregion - - #region IHydratable Members - - /// ----------------------------------------------------------------------------- - /// - /// Fills a FolderPermissionInfo from a Data Reader - /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - base.FillInternal(dr); - FolderPermissionID = Null.SetNullInteger(dr["FolderPermissionID"]); - FolderID = Null.SetNullInteger(dr["FolderID"]); - PortalID = Null.SetNullInteger(dr["PortalID"]); - FolderPath = Null.SetNullString(dr["FolderPath"]); - } + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Key ID + /// Gets or sets and sets the Key ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public int KeyID { get { - return FolderPermissionID; + return this.FolderPermissionID; } + set { - FolderPermissionID = value; + this.FolderPermissionID = value; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a FolderPermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.FillInternal(dr); + this.FolderPermissionID = Null.SetNullInteger(dr["FolderPermissionID"]); + this.FolderID = Null.SetNullInteger(dr["FolderID"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.FolderPath = Null.SetNullString(dr["FolderPath"]); } - - #endregion } } diff --git a/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs b/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs index 5b3c19f3590..f2ba0abadc8 100644 --- a/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Permissions { + using DotNetNuke.Services.FileSystem; + public interface IFolderPermissionController { bool CanAddFolder(IFolderInfo folder); + bool CanAdminFolder(IFolderInfo folder); + bool CanViewFolder(IFolderInfo folder); } } diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs index e01c3e2b162..6d9f01a3bac 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : ModulePermissionCollection + /// Class : ModulePermissionCollection /// ----------------------------------------------------------------------------- /// /// ModulePermissionCollection provides the a custom collection for ModulePermissionInfo - /// objects + /// objects. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -35,12 +30,12 @@ public ModulePermissionCollection() public ModulePermissionCollection(ArrayList modulePermissions) { - AddRange(modulePermissions); + this.AddRange(modulePermissions); } public ModulePermissionCollection(ModulePermissionCollection modulePermissions) { - AddRange(modulePermissions); + this.AddRange(modulePermissions); } public ModulePermissionCollection(ArrayList modulePermissions, int ModuleID) @@ -49,7 +44,7 @@ public ModulePermissionCollection(ArrayList modulePermissions, int ModuleID) { if (permission.ModuleID == ModuleID) { - Add(permission); + this.Add(permission); } } } @@ -60,7 +55,7 @@ public ModulePermissionCollection(ModuleInfo objModule) { if (permission.ModuleID == objModule.ModuleID) { - Add(permission); + this.Add(permission); } } } @@ -69,17 +64,18 @@ public ModulePermissionInfo this[int index] { get { - return (ModulePermissionInfo) List[index]; + return (ModulePermissionInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } public int Add(ModulePermissionInfo value) { - return List.Add(value); + return this.List.Add(value); } public int Add(ModulePermissionInfo value, bool checkForDuplicates) @@ -87,12 +83,12 @@ public int Add(ModulePermissionInfo value, bool checkForDuplicates) int id = Null.NullInteger; if (!checkForDuplicates) { - id = Add(value); + id = this.Add(value); } else { bool isMatch = false; - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) { @@ -100,9 +96,10 @@ public int Add(ModulePermissionInfo value, bool checkForDuplicates) break; } } + if (!isMatch) { - id = Add(value); + id = this.Add(value); } } @@ -113,7 +110,7 @@ public void AddRange(ArrayList modulePermissions) { foreach (ModulePermissionInfo permission in modulePermissions) { - Add(permission); + this.Add(permission); } } @@ -121,58 +118,61 @@ public void AddRange(ModulePermissionCollection modulePermissions) { foreach (ModulePermissionInfo permission in modulePermissions) { - Add(permission); + this.Add(permission); } } public bool CompareTo(ModulePermissionCollection objModulePermissionCollection) { - if (objModulePermissionCollection.Count != Count) + if (objModulePermissionCollection.Count != this.Count) { return false; } - InnerList.Sort(new CompareModulePermissions()); + + this.InnerList.Sort(new CompareModulePermissions()); objModulePermissionCollection.InnerList.Sort(new CompareModulePermissions()); - for (int i = 0; i <= Count - 1; i++) + for (int i = 0; i <= this.Count - 1; i++) { if (objModulePermissionCollection[i].ModulePermissionID != this[i].ModulePermissionID || objModulePermissionCollection[i].AllowAccess != this[i].AllowAccess) { return false; } } + return true; } public bool Contains(ModulePermissionInfo value) { - return List.Contains(value); + return this.List.Contains(value); } public int IndexOf(ModulePermissionInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } public void Insert(int index, ModulePermissionInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } public void Remove(ModulePermissionInfo value) { - List.Remove(value); + this.List.Remove(value); } public void Remove(int permissionID, int roleID, int userID) { var idx = 0; - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == permissionID && permission.UserID == userID && permission.RoleID == roleID) { - List.RemoveAt(idx); + this.List.RemoveAt(idx); break; } + idx++; } } @@ -180,16 +180,17 @@ public void Remove(int permissionID, int roleID, int userID) public List ToList() { var list = new List(); - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { list.Add(permission); } + return list; } public string ToString(string key) { - return PermissionController.BuildPermissions(List, key); + return PermissionController.BuildPermissions(this.List, key); } public IEnumerable Where(Func predicate) diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs index 0545989249d..1f283bdc93e 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs @@ -1,129 +1,114 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : ModulePermissionController + /// Class : ModulePermissionController /// ----------------------------------------------------------------------------- /// - /// ModulePermissionController provides the Business Layer for Module Permissions + /// ModulePermissionController provides the Business Layer for Module Permissions. /// /// ----------------------------------------------------------------------------- public class ModulePermissionController - { - #region Private Members - - private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - - #endregion - - #region Private Methods - - private static void ClearPermissionCache(int moduleId) - { - ModuleInfo objModule = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); - DataCache.ClearModulePermissionsCache(objModule.TabID); - } - - #endregion - - #region Public Methods - + { + private static readonly PermissionProvider _provider = PermissionProvider.Instance(); + /// - /// Returns a list with all roles with implicit permissions on Modules + /// Returns a list with all roles with implicit permissions on Modules. /// - /// The Portal Id where the Roles are - /// A List with the implicit roles + /// The Portal Id where the Roles are. + /// A List with the implicit roles. public static IEnumerable ImplicitRoles(int portalId) { return _provider.ImplicitRolesForPages(portalId); } /// - /// Returns a flag indicating whether the current user can administer a module + /// Returns a flag indicating whether the current user can administer a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanAdminModule(ModuleInfo module) { return _provider.CanAdminModule(module); } + + private static void ClearPermissionCache(int moduleId) + { + ModuleInfo objModule = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); + DataCache.ClearModulePermissionsCache(objModule.TabID); + } /// - /// Returns a flag indicating whether the current user can delete a module + /// Returns a flag indicating whether the current user can delete a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanDeleteModule(ModuleInfo module) { return _provider.CanDeleteModule(module); } /// - /// Returns a flag indicating whether the current user can edit module content + /// Returns a flag indicating whether the current user can edit module content. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanEditModuleContent(ModuleInfo module) { return _provider.CanEditModuleContent(module); } /// - /// Returns a flag indicating whether the current user can export a module + /// Returns a flag indicating whether the current user can export a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanExportModule(ModuleInfo module) { return _provider.CanExportModule(module); } /// - /// Returns a flag indicating whether the current user can import a module + /// Returns a flag indicating whether the current user can import a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanImportModule(ModuleInfo module) { return _provider.CanImportModule(module); } /// - /// Returns a flag indicating whether the current user can manage a module's settings + /// Returns a flag indicating whether the current user can manage a module's settings. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanManageModule(ModuleInfo module) { return _provider.CanManageModule(module); } /// - /// Returns a flag indicating whether the current user can view a module + /// Returns a flag indicating whether the current user can view a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanViewModule(ModuleInfo module) { return _provider.CanViewModule(module); @@ -131,9 +116,9 @@ public static bool CanViewModule(ModuleInfo module) /// ----------------------------------------------------------------------------- /// - /// DeleteModulePermissionsByUser deletes a user's Module Permission in the Database + /// DeleteModulePermissionsByUser deletes a user's Module Permission in the Database. /// - /// The user + /// The user. /// ----------------------------------------------------------------------------- public static void DeleteModulePermissionsByUser(UserInfo user) { @@ -143,10 +128,11 @@ public static void DeleteModulePermissionsByUser(UserInfo user) /// ----------------------------------------------------------------------------- /// - /// GetModulePermissions gets a ModulePermissionCollection + /// GetModulePermissions gets a ModulePermissionCollection. /// - /// The ID of the module - /// The ID of the tab + /// The ID of the module. + /// The ID of the tab. + /// /// ----------------------------------------------------------------------------- public static ModulePermissionCollection GetModulePermissions(int moduleId, int tabId) { @@ -155,19 +141,20 @@ public static ModulePermissionCollection GetModulePermissions(int moduleId, int /// ----------------------------------------------------------------------------- /// - /// HasModulePermission checks whether the current user has a specific Module Permission + /// HasModulePermission checks whether the current user has a specific Module Permission. /// /// If you pass in a comma delimited list of permissions (eg "ADD,DELETE", this will return /// true if the user has any one of the permissions. - /// The Permissions for the Module - /// The Permission to check + /// The Permissions for the Module. + /// The Permission to check. + /// /// ----------------------------------------------------------------------------- public static bool HasModulePermission(ModulePermissionCollection modulePermissions, string permissionKey) { return _provider.HasModulePermission(modulePermissions, permissionKey); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Determines if user has the necessary permissions to access an item with the /// designated AccessLevel. @@ -175,12 +162,12 @@ public static bool HasModulePermission(ModulePermissionCollection modulePermissi /// The SecurityAccessLevel required to access a portal module or module action. /// If Security Access is Edit the permissionKey is the actual "edit" permisison required. /// The ModuleInfo object for the associated module. - /// A boolean value indicating if the user has the necessary permissions + /// A boolean value indicating if the user has the necessary permissions. /// Every module control and module action has an associated permission level. This /// function determines whether the user represented by UserName has sufficient permissions, as /// determined by the PortalSettings and ModuleSettings, to access a resource with the /// designated AccessLevel. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public static bool HasModuleAccess(SecurityAccessLevel accessLevel, string permissionKey, ModuleInfo moduleConfiguration) { return _provider.HasModuleAccess(accessLevel, permissionKey, moduleConfiguration); @@ -188,16 +175,14 @@ public static bool HasModuleAccess(SecurityAccessLevel accessLevel, string permi /// ----------------------------------------------------------------------------- /// - /// SaveModulePermissions updates a Module's permissions + /// SaveModulePermissions updates a Module's permissions. /// - /// The Module to update + /// The Module to update. /// ----------------------------------------------------------------------------- public static void SaveModulePermissions(ModuleInfo module) { _provider.SaveModulePermissions(module); DataCache.ClearModulePermissionsCache(module.TabID); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs index 8f744a075f9..c4a650b033c 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs @@ -1,158 +1,141 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : ModulePermissionInfo + /// Class : ModulePermissionInfo /// ----------------------------------------------------------------------------- /// - /// ModulePermissionInfo provides the Entity Layer for Module Permissions + /// ModulePermissionInfo provides the Entity Layer for Module Permissions. /// /// ----------------------------------------------------------------------------- [Serializable] public class ModulePermissionInfo : PermissionInfoBase, IHydratable - { - #region "Private Members" - + { private int _moduleID; - //local property declarations - private int _modulePermissionID; - - #endregion - - #region "Constructors" - + // local property declarations + private int _modulePermissionID; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new ModulePermissionInfo + /// + /// Initializes a new instance of the class. + /// Constructs a new ModulePermissionInfo. /// /// ----------------------------------------------------------------------------- public ModulePermissionInfo() { - _modulePermissionID = Null.NullInteger; - _moduleID = Null.NullInteger; - } - - /// ----------------------------------------------------------------------------- - /// - /// Constructs a new ModulePermissionInfo + this._modulePermissionID = Null.NullInteger; + this._moduleID = Null.NullInteger; + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new ModulePermissionInfo. /// - /// A PermissionInfo object + /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public ModulePermissionInfo(PermissionInfo permission) : this() + public ModulePermissionInfo(PermissionInfo permission) + : this() { - ModuleDefID = permission.ModuleDefID; - PermissionCode = permission.PermissionCode; - PermissionID = permission.PermissionID; - PermissionKey = permission.PermissionKey; - PermissionName = permission.PermissionName; - } - - #endregion - - #region "Public Properties" - + this.ModuleDefID = permission.ModuleDefID; + this.PermissionCode = permission.PermissionCode; + this.PermissionID = permission.PermissionID; + this.PermissionKey = permission.PermissionKey; + this.PermissionName = permission.PermissionName; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Module Permission ID + /// Gets or sets and sets the Module Permission ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlElement("modulepermissionid")] public int ModulePermissionID { get { - return _modulePermissionID; + return this._modulePermissionID; } + set { - _modulePermissionID = value; + this._modulePermissionID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Module ID + /// Gets or sets and sets the Module ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlElement("moduleid")] public int ModuleID { get { - return _moduleID; + return this._moduleID; } + set { - _moduleID = value; + this._moduleID = value; } - } - - #endregion - - #region IHydratable Members + } /// ----------------------------------------------------------------------------- /// - /// Fills a ModulePermissionInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - base.FillInternal(dr); - ModulePermissionID = Null.SetNullInteger(dr["ModulePermissionID"]); - ModuleID = Null.SetNullInteger(dr["ModuleID"]); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public int KeyID { get { - return ModulePermissionID; + return this.ModulePermissionID; } + set { - ModulePermissionID = value; + this.ModulePermissionID = value; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a ModulePermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.FillInternal(dr); + this.ModulePermissionID = Null.SetNullInteger(dr["ModulePermissionID"]); + this.ModuleID = Null.SetNullInteger(dr["ModuleID"]); } - - #endregion - - #region "Public Methods" - + /// ----------------------------------------------------------------------------- /// - /// Compares if two ModulePermissionInfo objects are equivalent/equal + /// Compares if two ModulePermissionInfo objects are equivalent/equal. /// - /// a ModulePermissionObject + /// a ModulePermissionObject. /// true if the permissions being passed represents the same permission - /// in the current object + /// in the current object. /// /// /// This function is needed to prevent adding duplicates to the ModulePermissionCollection. @@ -166,20 +149,22 @@ public bool Equals(ModulePermissionInfo other) { return false; } + if (ReferenceEquals(this, other)) { return true; } - return (AllowAccess == other.AllowAccess) && (ModuleID == other.ModuleID) && (RoleID == other.RoleID) && (PermissionID == other.PermissionID); + + return (this.AllowAccess == other.AllowAccess) && (this.ModuleID == other.ModuleID) && (this.RoleID == other.RoleID) && (this.PermissionID == other.PermissionID); } /// ----------------------------------------------------------------------------- /// - /// Compares if two ModulePermissionInfo objects are equivalent/equal + /// Compares if two ModulePermissionInfo objects are equivalent/equal. /// - /// a ModulePermissionObject + /// a ModulePermissionObject. /// true if the permissions being passed represents the same permission - /// in the current object + /// in the current object. /// /// /// This function is needed to prevent adding duplicates to the ModulePermissionCollection. @@ -193,25 +178,26 @@ public override bool Equals(object obj) { return false; } + if (ReferenceEquals(this, obj)) { return true; } - if (obj.GetType() != typeof (ModulePermissionInfo)) + + if (obj.GetType() != typeof(ModulePermissionInfo)) { return false; } - return Equals((ModulePermissionInfo) obj); + + return this.Equals((ModulePermissionInfo)obj); } public override int GetHashCode() { unchecked { - return (_moduleID*397) ^ _modulePermissionID; + return (this._moduleID * 397) ^ this._modulePermissionID; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/PermissionController.cs b/DNN Platform/Library/Security/Permissions/PermissionController.cs index 5284e5bb8bf..e021dee2301 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionController.cs @@ -1,72 +1,119 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Log.EventLog; + public class PermissionController { private static readonly DataProvider provider = DataProvider.Instance(); - - private static IEnumerable GetPermissions() + + public static string BuildPermissions(IList Permissions, string PermissionKey) { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.PermissionsCacheKey, - DataCache.PermissionsCacheTimeout, - DataCache.PermissionsCachePriority), - c => CBO.FillCollection(provider.ExecuteReader("GetPermissions"))); + var permissionsBuilder = new StringBuilder(); + foreach (PermissionInfoBase permission in Permissions) + { + if (PermissionKey.Equals(permission.PermissionKey, StringComparison.InvariantCultureIgnoreCase)) + { + // Deny permissions are prefixed with a "!" + string prefix = !permission.AllowAccess ? "!" : string.Empty; + + // encode permission + string permissionString; + if (Null.IsNull(permission.UserID)) + { + permissionString = prefix + permission.RoleName + ";"; + } + else + { + permissionString = prefix + "[" + permission.UserID + "];"; + } + + // build permissions string ensuring that Deny permissions are inserted at the beginning and Grant permissions at the end + if (prefix == "!") + { + permissionsBuilder.Insert(0, permissionString); + } + else + { + permissionsBuilder.Append(permissionString); + } + } + } + + // get string + string permissionsString = permissionsBuilder.ToString(); + + // ensure leading delimiter + if (!permissionsString.StartsWith(";")) + { + permissionsString.Insert(0, ";"); + } + + return permissionsString; } - private void ClearCache() + public static ArrayList GetPermissionsByFolder() { - DataCache.RemoveCache(DataCache.PermissionsCacheKey); + return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_FOLDER").ToArray()); } - - #region Public Methods - + public int AddPermission(PermissionInfo permission) { - EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PERMISSION_CREATED); - var permissionId = Convert.ToInt32(provider.AddPermission(permission.PermissionCode, - permission.ModuleDefID, - permission.PermissionKey, - permission.PermissionName, - UserController.Instance.GetCurrentUserInfo().UserID)); - - ClearCache(); + EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_CREATED); + var permissionId = Convert.ToInt32(provider.AddPermission( + permission.PermissionCode, + permission.ModuleDefID, + permission.PermissionKey, + permission.PermissionName, + UserController.Instance.GetCurrentUserInfo().UserID)); + + this.ClearCache(); return permissionId; } public void DeletePermission(int permissionID) { - EventLogController.Instance.AddLog("PermissionID", - permissionID.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PERMISSION_DELETED); + EventLogController.Instance.AddLog( + "PermissionID", + permissionID.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PERMISSION_DELETED); provider.DeletePermission(permissionID); - ClearCache(); + this.ClearCache(); + } + + private static IEnumerable GetPermissions() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PermissionsCacheKey, + DataCache.PermissionsCacheTimeout, + DataCache.PermissionsCachePriority), + c => CBO.FillCollection(provider.ExecuteReader("GetPermissions"))); } + private void ClearCache() + { + DataCache.RemoveCache(DataCache.PermissionsCacheKey); + } + public PermissionInfo GetPermission(int permissionID) { return GetPermissions().SingleOrDefault(p => p.PermissionID == permissionID); @@ -92,68 +139,16 @@ public ArrayList GetPermissionsByModule(int moduleId, int tabId) public void UpdatePermission(PermissionInfo permission) { - EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PERMISSION_UPDATED); - provider.UpdatePermission(permission.PermissionID, - permission.PermissionCode, - permission.ModuleDefID, - permission.PermissionKey, - permission.PermissionName, - UserController.Instance.GetCurrentUserInfo().UserID); - ClearCache(); - } - - #endregion - - #region Shared Methods - - public static string BuildPermissions(IList Permissions, string PermissionKey) - { - var permissionsBuilder = new StringBuilder(); - foreach (PermissionInfoBase permission in Permissions) - { - if (PermissionKey.Equals(permission.PermissionKey, StringComparison.InvariantCultureIgnoreCase)) - { - //Deny permissions are prefixed with a "!" - string prefix = !permission.AllowAccess ? "!" : ""; - - //encode permission - string permissionString; - if (Null.IsNull(permission.UserID)) - { - permissionString = prefix + permission.RoleName + ";"; - } - else - { - permissionString = prefix + "[" + permission.UserID + "];"; - } - - //build permissions string ensuring that Deny permissions are inserted at the beginning and Grant permissions at the end - if (prefix == "!") - { - permissionsBuilder.Insert(0, permissionString); - } - else - { - permissionsBuilder.Append(permissionString); - } - } - } - - //get string - string permissionsString = permissionsBuilder.ToString(); - - //ensure leading delimiter - if (!permissionsString.StartsWith(";")) - { - permissionsString.Insert(0, ";"); - } - return permissionsString; - } - - public static ArrayList GetPermissionsByFolder() - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_FOLDER").ToArray()); - } + EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_UPDATED); + provider.UpdatePermission( + permission.PermissionID, + permission.PermissionCode, + permission.ModuleDefID, + permission.PermissionKey, + permission.PermissionName, + UserController.Instance.GetCurrentUserInfo().UserID); + this.ClearCache(); + } public static ArrayList GetPermissionsByPortalDesktopModule() { @@ -165,20 +160,21 @@ public static ArrayList GetPermissionsByTab() return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_TAB").ToArray()); } - public T RemapPermission(T permission, int portalId) where T : PermissionInfoBase + public T RemapPermission(T permission, int portalId) + where T : PermissionInfoBase { - PermissionInfo permissionInfo = GetPermissionByCodeAndKey(permission.PermissionCode, permission.PermissionKey).ToArray().Cast().FirstOrDefault(); + PermissionInfo permissionInfo = this.GetPermissionByCodeAndKey(permission.PermissionCode, permission.PermissionKey).ToArray().Cast().FirstOrDefault(); T result = null; - if ((permissionInfo != null)) + if (permissionInfo != null) { int RoleID = int.MinValue; int UserID = int.MinValue; - if ((string.IsNullOrEmpty(permission.RoleName))) + if (string.IsNullOrEmpty(permission.RoleName)) { UserInfo _user = UserController.GetUserByName(portalId, permission.Username); - if ((_user != null)) + if (_user != null) { UserID = _user.UserID; } @@ -195,10 +191,11 @@ public T RemapPermission(T permission, int portalId) where T : PermissionInfo break; default: RoleInfo _role = RoleController.Instance.GetRole(portalId, r => r.RoleName == permission.RoleName); - if ((_role != null)) + if (_role != null) { RoleID = _role.RoleID; } + break; } } @@ -207,29 +204,29 @@ public T RemapPermission(T permission, int portalId) where T : PermissionInfo if (RoleID != int.MinValue || UserID != int.MinValue) { permission.PermissionID = permissionInfo.PermissionID; - if ((RoleID != int.MinValue)) + if (RoleID != int.MinValue) { permission.RoleID = RoleID; } - if ((UserID != int.MinValue)) + + if (UserID != int.MinValue) { permission.UserID = UserID; } + result = permission; } } return result; - } - - #endregion - + } + [Obsolete("Deprecated in DNN 7.3.0. Replaced by GetPermissionsByModule(int, int). Scheduled removal in v10.0.0.")] public ArrayList GetPermissionsByModuleID(int moduleId) { var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - return GetPermissionsByModuleDefID(module.ModuleDefID); + return this.GetPermissionsByModuleDefID(module.ModuleDefID); } } } diff --git a/DNN Platform/Library/Security/Permissions/PermissionInfo.cs b/DNN Platform/Library/Security/Permissions/PermissionInfo.cs index ba9fe343dc5..bde9b299f71 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionInfo.cs @@ -1,103 +1,86 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : PermissionInfo + /// Class : PermissionInfo /// ----------------------------------------------------------------------------- /// - /// PermissionInfo provides the Entity Layer for Permissions + /// PermissionInfo provides the Entity Layer for Permissions. /// /// ----------------------------------------------------------------------------- [Serializable] public class PermissionInfo : BaseEntityInfo - { - #region Private Members - - #endregion - - #region Public Properties - + { /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Mdoule Definition ID + /// Gets or sets and sets the Mdoule Definition ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public int ModuleDefID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Permission Code + /// Gets or sets and sets the Permission Code. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- [XmlElement("permissioncode")] public string PermissionCode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Permission ID + /// Gets or sets and sets the Permission ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlElement("permissionid")] public int PermissionID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Permission Key + /// Gets or sets and sets the Permission Key. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- [XmlElement("permissionkey")] public string PermissionKey { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Permission Name + /// Gets or sets and sets the Permission Name. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- [XmlIgnore] - public string PermissionName { get; set; } - - #endregion - - #region "Protected methods" - + public string PermissionName { get; set; } + /// ----------------------------------------------------------------------------- /// - /// FillInternal fills a PermissionInfo from a Data Reader + /// FillInternal fills a PermissionInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- protected override void FillInternal(IDataReader dr) { base.FillInternal(dr); - PermissionID = Null.SetNullInteger(dr["PermissionID"]); - ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); - PermissionCode = Null.SetNullString(dr["PermissionCode"]); - PermissionKey = Null.SetNullString(dr["PermissionKey"]); - PermissionName = Null.SetNullString(dr["PermissionName"]); - } - - #endregion - } + this.PermissionID = Null.SetNullInteger(dr["PermissionID"]); + this.ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); + this.PermissionCode = Null.SetNullString(dr["PermissionCode"]); + this.PermissionKey = Null.SetNullString(dr["PermissionKey"]); + this.PermissionName = Null.SetNullString(dr["PermissionName"]); + } + } } diff --git a/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs b/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs index 0cc8e2fab84..d974abe24d8 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs @@ -1,27 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : PermissionInfoBase + /// Class : PermissionInfoBase /// ----------------------------------------------------------------------------- /// - /// PermissionInfoBase provides a base class for PermissionInfo classes + /// PermissionInfoBase provides a base class for PermissionInfo classes. /// /// All Permission calsses have a common set of properties /// - AllowAccess @@ -30,185 +25,176 @@ namespace DotNetNuke.Security.Permissions /// - UserID /// - Username /// - DisplayName - /// - /// and these are implemented in this base class + /// + /// and these are implemented in this base class. /// /// ----------------------------------------------------------------------------- [Serializable] public abstract class PermissionInfoBase : PermissionInfo - { - #region "Private Members" - + { private bool _AllowAccess; private string _DisplayName; private int _RoleID; private string _RoleName; private int _UserID; - private string _Username; - - #endregion - - #region "Constructors" - + private string _Username; + public PermissionInfoBase() { - _RoleID = int.Parse(Globals.glbRoleNothing); - _AllowAccess = false; - _RoleName = Null.NullString; - _UserID = Null.NullInteger; - _Username = Null.NullString; - _DisplayName = Null.NullString; - } - - #endregion - - #region "Public Properties" - + this._RoleID = int.Parse(Globals.glbRoleNothing); + this._AllowAccess = false; + this._RoleName = Null.NullString; + this._UserID = Null.NullInteger; + this._Username = Null.NullString; + this._DisplayName = Null.NullString; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets aflag that indicates whether the user or role has permission + /// Gets or sets a value indicating whether gets and sets aflag that indicates whether the user or role has permission. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- [XmlElement("allowaccess")] public bool AllowAccess { get { - return _AllowAccess; + return this._AllowAccess; } + set { - _AllowAccess = value; + this._AllowAccess = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User's DisplayName + /// Gets or sets and sets the User's DisplayName. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- [XmlElement("displayname")] public string DisplayName { get { - return _DisplayName; + return this._DisplayName; } + set { - _DisplayName = value; + this._DisplayName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Role ID + /// Gets or sets and sets the Role ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlElement("roleid")] public int RoleID { get { - return _RoleID; + return this._RoleID; } + set { - _RoleID = value; + this._RoleID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Role Name + /// Gets or sets and sets the Role Name. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- [XmlElement("rolename")] public string RoleName { get { - return _RoleName; + return this._RoleName; } + set { - _RoleName = value; + this._RoleName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User ID + /// Gets or sets and sets the User ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlElement("userid")] public int UserID { get { - return _UserID; + return this._UserID; } + set { - _UserID = value; + this._UserID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User Name + /// Gets or sets and sets the User Name. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- [XmlElement("username")] public string Username { get { - return _Username; + return this._Username; } + set { - _Username = value; + this._Username = value; } - } - - #endregion - - #region "Protected Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// FillInternal fills the PermissionInfoBase from a Data Reader + /// FillInternal fills the PermissionInfoBase from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- protected override void FillInternal(IDataReader dr) { - //Call the base classes fill method to populate base class proeprties + // Call the base classes fill method to populate base class proeprties base.FillInternal(dr); - UserID = Null.SetNullInteger(dr["UserID"]); - Username = Null.SetNullString(dr["Username"]); - DisplayName = Null.SetNullString(dr["DisplayName"]); - if (UserID == Null.NullInteger) + this.UserID = Null.SetNullInteger(dr["UserID"]); + this.Username = Null.SetNullString(dr["Username"]); + this.DisplayName = Null.SetNullString(dr["DisplayName"]); + if (this.UserID == Null.NullInteger) { - RoleID = Null.SetNullInteger(dr["RoleID"]); - RoleName = Null.SetNullString(dr["RoleName"]); + this.RoleID = Null.SetNullInteger(dr["RoleID"]); + this.RoleName = Null.SetNullString(dr["RoleName"]); } else { - RoleID = int.Parse(Globals.glbRoleNothing); - RoleName = ""; + this.RoleID = int.Parse(Globals.glbRoleNothing); + this.RoleName = string.Empty; } - AllowAccess = Null.SetNullBoolean(dr["AllowAccess"]); - } - - #endregion + + this.AllowAccess = Null.SetNullBoolean(dr["AllowAccess"]); + } } } diff --git a/DNN Platform/Library/Security/Permissions/PermissionProvider.cs b/DNN Platform/Library/Security/Permissions/PermissionProvider.cs index e36c92447f8..34f530af235 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionProvider.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionProvider.cs @@ -1,37 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + public class PermissionProvider - { - #region Private Members - - //Folder Permission Keys + { + // Folder Permission Keys private const string AdminFolderPermissionKey = "WRITE"; private const string AddFolderPermissionKey = "WRITE"; private const string BrowseFolderPermissionKey = "BROWSE"; @@ -40,7 +34,7 @@ public class PermissionProvider private const string ManageFolderPermissionKey = "WRITE"; private const string ViewFolderPermissionKey = "READ"; - //Module Permission Keys + // Module Permission Keys private const string AdminModulePermissionKey = "EDIT"; private const string ContentModulePermissionKey = "EDIT"; private const string DeleteModulePermissionKey = "EDIT"; @@ -49,7 +43,7 @@ public class PermissionProvider private const string ManageModulePermissionKey = "EDIT"; private const string ViewModulePermissionKey = "VIEW"; - //Page Permission Keys + // Page Permission Keys private const string AddPagePermissionKey = "EDIT"; private const string AdminPagePermissionKey = "EDIT"; private const string ContentPagePermissionKey = "EDIT"; @@ -60,13 +54,11 @@ public class PermissionProvider private const string ManagePagePermissionKey = "EDIT"; private const string NavigatePagePermissionKey = "VIEW"; private const string ViewPagePermissionKey = "VIEW"; - private readonly DataProvider dataProvider = DataProvider.Instance(); - - #endregion - - #region Shared/Static Methods - - //return the provider + private static SharedDictionary _cacheDependencyDict = new SharedDictionary(); + + private readonly DataProvider dataProvider = DataProvider.Instance(); + + // return the provider public virtual string LocalResourceFile { get @@ -79,54 +71,105 @@ public static PermissionProvider Instance() { return ComponentFactory.GetComponent(); } + + public virtual bool SupportsFullControl() + { + return true; + } - private static SharedDictionary _cacheDependencyDict = new SharedDictionary(); + /// + /// The portal editor can edit whole site's content, it should be only administrators by default. + /// + /// + public virtual bool IsPortalEditor() + { + var settings = PortalController.Instance.GetCurrentPortalSettings(); + return settings != null && PortalSecurity.IsInRole(settings.AdministratorRoleName); + } - private static DNNCacheDependency GetCacheDependency(int portalId) + internal static void ResetCacheDependency(int portalId, Action cacehClearAction) { + // first execute the cache clear action then check the dependency change + cacehClearAction.Invoke(); DNNCacheDependency dependency; using (_cacheDependencyDict.GetReadLock()) { _cacheDependencyDict.TryGetValue(portalId, out dependency); } - - if (dependency == null) + + if (dependency != null) { - var startAt = DateTime.UtcNow; - var cacheKey = string.Format(DataCache.FolderPermissionCacheKey, portalId); - DataCache.SetCache(cacheKey, portalId); // no expiration set for this - dependency = new DNNCacheDependency(null, new[] {cacheKey}, startAt); using (_cacheDependencyDict.GetWriteLock()) { - _cacheDependencyDict[portalId] = dependency; + _cacheDependencyDict.Remove(portalId); } + + dependency.Dispose(); } - return dependency; + } + + protected bool HasModulePermission(ModuleInfo moduleConfiguration, string permissionKey) + { + return this.CanViewModule(moduleConfiguration) && + (this.HasModulePermission(moduleConfiguration.ModulePermissions, permissionKey) + || this.HasModulePermission(moduleConfiguration.ModulePermissions, "EDIT")); } - internal static void ResetCacheDependency(int portalId, Action cacehClearAction) + protected bool IsDeniedModulePermission(ModuleInfo moduleConfiguration, string permissionKey) + { + return this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "VIEW") + || this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, permissionKey) + || this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "EDIT"); + } + + private static DNNCacheDependency GetCacheDependency(int portalId) { - // first execute the cache clear action then check the dependency change - cacehClearAction.Invoke(); DNNCacheDependency dependency; using (_cacheDependencyDict.GetReadLock()) { _cacheDependencyDict.TryGetValue(portalId, out dependency); } - if (dependency != null) + + if (dependency == null) { + var startAt = DateTime.UtcNow; + var cacheKey = string.Format(DataCache.FolderPermissionCacheKey, portalId); + DataCache.SetCache(cacheKey, portalId); // no expiration set for this + dependency = new DNNCacheDependency(null, new[] { cacheKey }, startAt); using (_cacheDependencyDict.GetWriteLock()) { - _cacheDependencyDict.Remove(portalId); + _cacheDependencyDict[portalId] = dependency; } - dependency.Dispose(); } + + return dependency; } - #endregion - - #region Private Methods + /// ----------------------------------------------------------------------------- + /// + /// GetDesktopModulePermissions gets a Dictionary of DesktopModulePermissionCollections by + /// DesktopModule. + /// + /// ----------------------------------------------------------------------------- + private static Dictionary GetDesktopModulePermissions() + { + return CBO.GetCachedObject>( + new CacheItemArgs(DataCache.DesktopModulePermissionCacheKey, DataCache.DesktopModulePermissionCachePriority), GetDesktopModulePermissionsCallBack); + } + /// ----------------------------------------------------------------------------- + /// + /// GetDesktopModulePermissionsCallBack gets a Dictionary of DesktopModulePermissionCollections by + /// DesktopModule from the the Database. + /// + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. + /// ----------------------------------------------------------------------------- + private static object GetDesktopModulePermissionsCallBack(CacheItemArgs cacheItemArgs) + { + return FillDesktopModulePermissionDictionary(DataProvider.Instance().GetDesktopModulePermissions()); + } + #if false private object GetFolderPermissionsCallBack(CacheItemArgs cacheItemArgs) { @@ -182,19 +225,19 @@ private Dictionary GetFolderPermissions(int new CacheItemArgs(cacheKey, DataCache.FolderPermissionCacheTimeOut, DataCache.FolderPermissionCachePriority, PortalID), GetFolderPermissionsCallBack); } #endif - + /// ----------------------------------------------------------------------------- /// /// GetModulePermissions gets a Dictionary of ModulePermissionCollections by /// Module. /// - /// The ID of the tab + /// The ID of the tab. /// ----------------------------------------------------------------------------- private Dictionary GetModulePermissions(int tabID) { string cacheKey = string.Format(DataCache.ModulePermissionCacheKey, tabID); return CBO.GetCachedObject>( - new CacheItemArgs(cacheKey, DataCache.ModulePermissionCacheTimeOut, DataCache.ModulePermissionCachePriority, tabID), GetModulePermissionsCallBack); + new CacheItemArgs(cacheKey, DataCache.ModulePermissionCacheTimeOut, DataCache.ModulePermissionCachePriority, tabID), this.GetModulePermissionsCallBack); } /// ----------------------------------------------------------------------------- @@ -203,33 +246,33 @@ private Dictionary GetModulePermissions(int tab /// Module from the the Database. /// /// The CacheItemArgs object that contains the parameters - /// needed for the database call + /// needed for the database call. /// ----------------------------------------------------------------------------- private object GetModulePermissionsCallBack(CacheItemArgs cacheItemArgs) { var tabID = (int)cacheItemArgs.ParamList[0]; - IDataReader dr = dataProvider.GetModulePermissionsByTabID(tabID); + IDataReader dr = this.dataProvider.GetModulePermissionsByTabID(tabID); var dic = new Dictionary(); try { while (dr.Read()) { - //fill business object + // fill business object var modulePermissionInfo = CBO.FillObject(dr, false); - //add Module Permission to dictionary + // add Module Permission to dictionary if (dic.ContainsKey(modulePermissionInfo.ModuleID)) { dic[modulePermissionInfo.ModuleID].Add(modulePermissionInfo); } else { - //Create new ModulePermission Collection for ModuleId - var collection = new ModulePermissionCollection {modulePermissionInfo}; + // Create new ModulePermission Collection for ModuleId + var collection = new ModulePermissionCollection { modulePermissionInfo }; - //Add Permission to Collection + // Add Permission to Collection - //Add Collection to Dictionary + // Add Collection to Dictionary dic.Add(modulePermissionInfo.ModuleID, collection); } } @@ -240,9 +283,10 @@ private object GetModulePermissionsCallBack(CacheItemArgs cacheItemArgs) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } + return dic; } @@ -251,13 +295,14 @@ private object GetModulePermissionsCallBack(CacheItemArgs cacheItemArgs) /// GetTabPermissions gets a Dictionary of TabPermissionCollections by /// Tab. /// - /// The ID of the portal + /// The ID of the portal. /// ----------------------------------------------------------------------------- private Dictionary GetTabPermissions(int portalID) { string cacheKey = string.Format(DataCache.TabPermissionCacheKey, portalID); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.TabPermissionCacheTimeOut, DataCache.TabPermissionCachePriority, portalID), - GetTabPermissionsCallBack); + return CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.TabPermissionCacheTimeOut, DataCache.TabPermissionCachePriority, portalID), + this.GetTabPermissionsCallBack); } /// ----------------------------------------------------------------------------- @@ -266,7 +311,7 @@ private Dictionary GetTabPermissions(int portalID) /// Tab from the the Database. /// /// The CacheItemArgs object that contains the parameters - /// needed for the database call + /// needed for the database call. /// ----------------------------------------------------------------------------- private object GetTabPermissionsCallBack(CacheItemArgs cacheItemArgs) { @@ -275,26 +320,26 @@ private object GetTabPermissionsCallBack(CacheItemArgs cacheItemArgs) if (portalID > -1) { - IDataReader dr = dataProvider.GetTabPermissionsByPortal(portalID); + IDataReader dr = this.dataProvider.GetTabPermissionsByPortal(portalID); try { while (dr.Read()) { - //fill business object + // fill business object var tabPermissionInfo = CBO.FillObject(dr, false); - //add Tab Permission to dictionary + // add Tab Permission to dictionary if (dic.ContainsKey(tabPermissionInfo.TabID)) { - //Add TabPermission to TabPermission Collection already in dictionary for TabId + // Add TabPermission to TabPermission Collection already in dictionary for TabId dic[tabPermissionInfo.TabID].Add(tabPermissionInfo); } else { - //Create new TabPermission Collection for TabId + // Create new TabPermission Collection for TabId var collection = new TabPermissionCollection { tabPermissionInfo }; - //Add Collection to Dictionary + // Add Collection to Dictionary dic.Add(tabPermissionInfo.TabID, collection); } } @@ -305,21 +350,27 @@ private object GetTabPermissionsCallBack(CacheItemArgs cacheItemArgs) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } } + return dic; } private bool HasFolderPermission(FolderInfo folder, string permissionKey) { - if (folder == null) return false; + if (folder == null) + { + return false; + } + return (PortalSecurity.IsInRoles(folder.FolderPermissions.ToString(permissionKey)) || PortalSecurity.IsInRoles(folder.FolderPermissions.ToString(AdminFolderPermissionKey))) && !PortalSecurity.IsDenied(folder.FolderPermissions.ToString(permissionKey)); - //Deny on Edit permission on folder shouldn't take away any other explicitly Allowed - //&& !PortalSecurity.IsDenied(folder.FolderPermissions.ToString(AdminFolderPermissionKey)); + + // Deny on Edit permission on folder shouldn't take away any other explicitly Allowed + // && !PortalSecurity.IsDenied(folder.FolderPermissions.ToString(AdminFolderPermissionKey)); } private bool HasPagePermission(TabInfo tab, string permissionKey) @@ -327,8 +378,9 @@ private bool HasPagePermission(TabInfo tab, string permissionKey) return (PortalSecurity.IsInRoles(tab.TabPermissions.ToString(permissionKey)) || PortalSecurity.IsInRoles(tab.TabPermissions.ToString(AdminPagePermissionKey))) && !PortalSecurity.IsDenied(tab.TabPermissions.ToString(permissionKey)); - //Deny on Edit permission on page shouldn't take away any other explicitly Allowed - //&&!PortalSecurity.IsDenied(tab.TabPermissions.ToString(AdminPagePermissionKey)); + + // Deny on Edit permission on page shouldn't take away any other explicitly Allowed + // &&!PortalSecurity.IsDenied(tab.TabPermissions.ToString(AdminPagePermissionKey)); } private bool IsDeniedModulePermission(ModulePermissionCollection modulePermissions, string permissionKey) @@ -349,6 +401,7 @@ private bool IsDeniedModulePermission(ModulePermissionCollection modulePermissio { isDenied = PortalSecurity.IsDenied(modulePermissions.ToString(permissionKey)); } + return isDenied; } @@ -370,40 +423,16 @@ private bool IsDeniedTabPermission(TabPermissionCollection tabPermissions, strin { isDenied = PortalSecurity.IsDenied(tabPermissions.ToString(permissionKey)); } + return isDenied; } - /// ----------------------------------------------------------------------------- - /// - /// GetDesktopModulePermissions gets a Dictionary of DesktopModulePermissionCollections by - /// DesktopModule. - /// - /// ----------------------------------------------------------------------------- - private static Dictionary GetDesktopModulePermissions() - { - return CBO.GetCachedObject>( - new CacheItemArgs(DataCache.DesktopModulePermissionCacheKey, DataCache.DesktopModulePermissionCachePriority), GetDesktopModulePermissionsCallBack); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetDesktopModulePermissionsCallBack gets a Dictionary of DesktopModulePermissionCollections by - /// DesktopModule from the the Database. - /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call - /// ----------------------------------------------------------------------------- - private static object GetDesktopModulePermissionsCallBack(CacheItemArgs cacheItemArgs) - { - return FillDesktopModulePermissionDictionary(DataProvider.Instance().GetDesktopModulePermissions()); - } - /// ----------------------------------------------------------------------------- /// /// FillDesktopModulePermissionDictionary fills a Dictionary of DesktopModulePermissions from a - /// dataReader + /// dataReader. /// - /// The IDataReader + /// The IDataReader. /// ----------------------------------------------------------------------------- private static Dictionary FillDesktopModulePermissionDictionary(IDataReader dr) { @@ -412,21 +441,21 @@ private static Dictionary FillDesktopMod { while (dr.Read()) { - //fill business object + // fill business object var desktopModulePermissionInfo = CBO.FillObject(dr, false); - //add DesktopModule Permission to dictionary + // add DesktopModule Permission to dictionary if (dic.ContainsKey(desktopModulePermissionInfo.PortalDesktopModuleID)) { - //Add DesktopModulePermission to DesktopModulePermission Collection already in dictionary for TabId + // Add DesktopModulePermission to DesktopModulePermission Collection already in dictionary for TabId dic[desktopModulePermissionInfo.PortalDesktopModuleID].Add(desktopModulePermissionInfo); } else { - //Create new DesktopModulePermission Collection for DesktopModulePermissionID + // Create new DesktopModulePermission Collection for DesktopModulePermissionID var collection = new DesktopModulePermissionCollection { desktopModulePermissionInfo }; - //Add Collection to Dictionary + // Add Collection to Dictionary dic.Add(desktopModulePermissionInfo.PortalDesktopModuleID, collection); } } @@ -437,9 +466,10 @@ private static Dictionary FillDesktopMod } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } + return dic; } @@ -447,134 +477,104 @@ private IEnumerable DefaultImplicitRoles(int portalId) { return new List { - RoleController.Instance.GetRoleById(portalId, - PortalController.Instance.GetPortal(portalId).AdministratorRoleId) + RoleController.Instance.GetRoleById( + portalId, + PortalController.Instance.GetPortal(portalId).AdministratorRoleId), }; - } - -#endregion - - #region Protected Methods - - protected bool HasModulePermission(ModuleInfo moduleConfiguration, string permissionKey) - { - return CanViewModule(moduleConfiguration) && - (HasModulePermission(moduleConfiguration.ModulePermissions, permissionKey) - || HasModulePermission(moduleConfiguration.ModulePermissions, "EDIT")); - } - - protected bool IsDeniedModulePermission(ModuleInfo moduleConfiguration, string permissionKey) - { - return IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "VIEW") - || IsDeniedModulePermission(moduleConfiguration.ModulePermissions, permissionKey) - || IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "EDIT"); - } + } protected bool IsDeniedTabPermission(TabInfo tab, string permissionKey) { - return IsDeniedTabPermission(tab.TabPermissions, "VIEW") - || IsDeniedTabPermission(tab.TabPermissions, permissionKey) - || IsDeniedTabPermission(tab.TabPermissions, "EDIT"); - } - - #endregion - - #region Public Methods - - public virtual bool SupportsFullControl() - { - return true; - } - - /// - /// The portal editor can edit whole site's content, it should be only administrators by default. - /// - /// - public virtual bool IsPortalEditor() - { - var settings = PortalController.Instance.GetCurrentPortalSettings(); - return settings != null && PortalSecurity.IsInRole(settings.AdministratorRoleName); - } - - #region FolderPermission Methods - + return this.IsDeniedTabPermission(tab.TabPermissions, "VIEW") + || this.IsDeniedTabPermission(tab.TabPermissions, permissionKey) + || this.IsDeniedTabPermission(tab.TabPermissions, "EDIT"); + } + /// - /// Returns a flag indicating whether the current user can add a folder or file + /// Returns a flag indicating whether the current user can add a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanAddFolder(FolderInfo folder) { - return HasFolderPermission(folder, AddFolderPermissionKey); + return this.HasFolderPermission(folder, AddFolderPermissionKey); } /// - /// Returns a flag indicating whether the current user can browse the folder + /// Returns a flag indicating whether the current user can browse the folder. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanBrowseFolder(FolderInfo folder) { - if (folder == null) return false; + if (folder == null) + { + return false; + } + return (PortalSecurity.IsInRoles(folder.FolderPermissions.ToString(BrowseFolderPermissionKey)) || PortalSecurity.IsInRoles(folder.FolderPermissions.ToString(ViewFolderPermissionKey))) && !PortalSecurity.IsDenied(folder.FolderPermissions.ToString(BrowseFolderPermissionKey)); } /// - /// Returns a flag indicating whether the current user can addmister a folder + /// Returns a flag indicating whether the current user can addmister a folder. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanAdminFolder(FolderInfo folder) { - if (folder == null) return false; + if (folder == null) + { + return false; + } + return PortalSecurity.IsInRoles(folder.FolderPermissions.ToString(AdminFolderPermissionKey)); } /// - /// Returns a flag indicating whether the current user can copy a folder or file + /// Returns a flag indicating whether the current user can copy a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanCopyFolder(FolderInfo folder) { - return HasFolderPermission(folder, CopyFolderPermissionKey); + return this.HasFolderPermission(folder, CopyFolderPermissionKey); } /// - /// Returns a flag indicating whether the current user can delete a folder or file + /// Returns a flag indicating whether the current user can delete a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanDeleteFolder(FolderInfo folder) { - return HasFolderPermission(folder, DeleteFolderPermissionKey); + return this.HasFolderPermission(folder, DeleteFolderPermissionKey); } /// - /// Returns a flag indicating whether the current user can manage a folder's settings + /// Returns a flag indicating whether the current user can manage a folder's settings. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanManageFolder(FolderInfo folder) { - return HasFolderPermission(folder, ManageFolderPermissionKey); + return this.HasFolderPermission(folder, ManageFolderPermissionKey); } /// - /// Returns a flag indicating whether the current user can view a folder or file + /// Returns a flag indicating whether the current user can view a folder or file. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanViewFolder(FolderInfo folder) { - return HasFolderPermission(folder, ViewFolderPermissionKey); + return this.HasFolderPermission(folder, ViewFolderPermissionKey); } public virtual void DeleteFolderPermissionsByUser(UserInfo objUser) { - dataProvider.DeleteFolderPermissionsByUserID(objUser.PortalID, objUser.UserID); + this.dataProvider.DeleteFolderPermissionsByUserID(objUser.PortalID, objUser.UserID); } public virtual FolderPermissionCollection GetFolderPermissionsCollectionByFolder(int PortalID, string Folder) @@ -602,14 +602,14 @@ public virtual FolderPermissionCollection GetFolderPermissionsCollectionByFolder return CBO.GetCachedObject( new CacheItemArgs(cacheKey, DataCache.FolderPermissionCacheTimeOut, DataCache.FolderPermissionCachePriority) { - CacheDependency = GetCacheDependency(PortalID) + CacheDependency = GetCacheDependency(PortalID), }, _ => { var collection = new FolderPermissionCollection(); try { - using (var dr = dataProvider.GetFolderPermissionsByPortalAndPath(PortalID, Folder)) + using (var dr = this.dataProvider.GetFolderPermissionsByPortalAndPath(PortalID, Folder)) { while (dr.Read()) { @@ -622,6 +622,7 @@ public virtual FolderPermissionCollection GetFolderPermissionsCollectionByFolder { Exceptions.LogException(exc); } + return collection; }); #endif @@ -633,25 +634,25 @@ public virtual bool HasFolderPermission(FolderPermissionCollection objFolderPerm } /// - /// SaveFolderPermissions updates a Folder's permissions + /// SaveFolderPermissions updates a Folder's permissions. /// - /// The Folder to update + /// The Folder to update. public virtual void SaveFolderPermissions(FolderInfo folder) { - SaveFolderPermissions((IFolderInfo)folder); + this.SaveFolderPermissions((IFolderInfo)folder); } /// ----------------------------------------------------------------------------- /// - /// SaveFolderPermissions updates a Folder's permissions + /// SaveFolderPermissions updates a Folder's permissions. /// - /// The Folder to update + /// The Folder to update. /// ----------------------------------------------------------------------------- public virtual void SaveFolderPermissions(IFolderInfo folder) { - if ((folder.FolderPermissions != null)) + if (folder.FolderPermissions != null) { - //Ensure that if role/user has been given a permission that is not Read/Browse then they also need Read/Browse + // Ensure that if role/user has been given a permission that is not Read/Browse then they also need Read/Browse var permController = new PermissionController(); ArrayList permArray = permController.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "READ"); PermissionInfo readPerm = null; @@ -672,25 +673,25 @@ public virtual void SaveFolderPermissions(IFolderInfo folder) { if (folderPermission.PermissionKey != "BROWSE" && folderPermission.PermissionKey != "READ" && folderPermission.AllowAccess) { - //Try to add Read permission - var newFolderPerm = new FolderPermissionInfo(readPerm) - { - FolderID = folderPermission.FolderID, - RoleID = folderPermission.RoleID, - UserID = folderPermission.UserID, - AllowAccess = true - }; + // Try to add Read permission + var newFolderPerm = new FolderPermissionInfo(readPerm) + { + FolderID = folderPermission.FolderID, + RoleID = folderPermission.RoleID, + UserID = folderPermission.UserID, + AllowAccess = true, + }; additionalPermissions.Add(newFolderPerm); - //Try to add Browse permission - newFolderPerm = new FolderPermissionInfo(browsePerm) - { - FolderID = folderPermission.FolderID, - RoleID = folderPermission.RoleID, - UserID = folderPermission.UserID, - AllowAccess = true - }; + // Try to add Browse permission + newFolderPerm = new FolderPermissionInfo(browsePerm) + { + FolderID = folderPermission.FolderID, + RoleID = folderPermission.RoleID, + UserID = folderPermission.UserID, + AllowAccess = true, + }; additionalPermissions.Add(newFolderPerm); } @@ -701,88 +702,85 @@ public virtual void SaveFolderPermissions(IFolderInfo folder) folder.FolderPermissions.Add(folderPermission, true); } - dataProvider.DeleteFolderPermissionsByFolderPath(folder.PortalID, folder.FolderPath); + this.dataProvider.DeleteFolderPermissionsByFolderPath(folder.PortalID, folder.FolderPath); foreach (FolderPermissionInfo folderPermission in folder.FolderPermissions) { - dataProvider.AddFolderPermission(folder.FolderID, - folderPermission.PermissionID, - folderPermission.RoleID, - folderPermission.AllowAccess, - folderPermission.UserID, - UserController.Instance.GetCurrentUserInfo().UserID); - } + this.dataProvider.AddFolderPermission( + folder.FolderID, + folderPermission.PermissionID, + folderPermission.RoleID, + folderPermission.AllowAccess, + folderPermission.UserID, + UserController.Instance.GetCurrentUserInfo().UserID); + } } - } - - #endregion - - #region ModulePermission Methods - + } + /// - /// Returns a flag indicating whether the current user can administer a module + /// Returns a flag indicating whether the current user can administer a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanAdminModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(AdminModulePermissionKey)); } /// - /// Returns a flag indicating whether the current user can delete a module + /// Returns a flag indicating whether the current user can delete a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanDeleteModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(DeleteModulePermissionKey)); } /// - /// Returns a flag indicating whether the current user can edit module content + /// Returns a flag indicating whether the current user can edit module content. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanEditModuleContent(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ContentModulePermissionKey)); } /// - /// Returns a flag indicating whether the current user can export a module + /// Returns a flag indicating whether the current user can export a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanExportModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ExportModulePermissionKey)); } /// - /// Returns a flag indicating whether the current user can import a module + /// Returns a flag indicating whether the current user can import a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanImportModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ImportModulePermissionKey)); } /// - /// Returns a flag indicating whether the current user can manage a module's settings + /// Returns a flag indicating whether the current user can manage a module's settings. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanManageModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ManageModulePermissionKey)); } /// - /// Returns a flag indicating whether the current user can view a module + /// Returns a flag indicating whether the current user can view a module. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanViewModule(ModuleInfo module) { bool canView; @@ -801,40 +799,42 @@ public virtual bool CanViewModule(ModuleInfo module) /// ----------------------------------------------------------------------------- /// - /// DeleteModulePermissionsByUser deletes a user's Module Permission in the Database + /// DeleteModulePermissionsByUser deletes a user's Module Permission in the Database. /// - /// The user + /// The user. /// ----------------------------------------------------------------------------- public virtual void DeleteModulePermissionsByUser(UserInfo user) { - dataProvider.DeleteModulePermissionsByUserID(user.PortalID, user.UserID); + this.dataProvider.DeleteModulePermissionsByUserID(user.PortalID, user.UserID); DataCache.ClearModulePermissionsCachesByPortal(user.PortalID); } /// ----------------------------------------------------------------------------- /// - /// GetModulePermissions gets a ModulePermissionCollection + /// GetModulePermissions gets a ModulePermissionCollection. /// - /// The ID of the module - /// The ID of the tab + /// The ID of the module. + /// The ID of the tab. + /// /// ----------------------------------------------------------------------------- public virtual ModulePermissionCollection GetModulePermissions(int moduleID, int tabID) { - //Get the Tab ModulePermission Dictionary - Dictionary dictionary = GetModulePermissions(tabID); + // Get the Tab ModulePermission Dictionary + Dictionary dictionary = this.GetModulePermissions(tabID); - //Get the Collection from the Dictionary + // Get the Collection from the Dictionary ModulePermissionCollection modulePermissions; bool found = dictionary.TryGetValue(moduleID, out modulePermissions); if (!found) { - //Return empty collection + // Return empty collection modulePermissions = new ModulePermissionCollection(); } + return modulePermissions; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Determines if user has the necessary permissions to access an item with the /// designated AccessLevel. @@ -842,12 +842,12 @@ public virtual ModulePermissionCollection GetModulePermissions(int moduleID, int /// The SecurityAccessLevel required to access a portal module or module action. /// If Security Access is Edit the permissionKey is the actual "edit" permisison required. /// The ModuleInfo object for the associated module. - /// A boolean value indicating if the user has the necessary permissions + /// A boolean value indicating if the user has the necessary permissions. /// Every module control and module action has an associated permission level. This /// function determines whether the user represented by UserName has sufficient permissions, as /// determined by the PortalSettings and ModuleSettings, to access a resource with the /// designated AccessLevel. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public virtual bool HasModuleAccess(SecurityAccessLevel accessLevel, string permissionKey, ModuleInfo moduleConfiguration) { bool isAuthorized = false; @@ -869,6 +869,7 @@ public virtual bool HasModuleAccess(SecurityAccessLevel accessLevel, string perm { isAuthorized = true; } + break; case SecurityAccessLevel.ViewPermissions: isAuthorized = TabPermissionController.CanAddContentToPage(tab); @@ -883,10 +884,10 @@ public virtual bool HasModuleAccess(SecurityAccessLevel accessLevel, string perm if (TabPermissionController.CanAddContentToPage(tab)) { - //Need to check for Deny Edit at the Module Level + // Need to check for Deny Edit at the Module Level if (permissionKey == "CONTENT") { - isAuthorized = !IsDeniedModulePermission(moduleConfiguration, permissionKey); + isAuthorized = !this.IsDeniedModulePermission(moduleConfiguration, permissionKey); } else { @@ -896,32 +897,36 @@ public virtual bool HasModuleAccess(SecurityAccessLevel accessLevel, string perm else { // Need to check if it was denied at Tab level - if (!IsDeniedTabPermission(tab, "CONTENT,EDIT")) + if (!this.IsDeniedTabPermission(tab, "CONTENT,EDIT")) { - isAuthorized = HasModulePermission(moduleConfiguration, permissionKey); + isAuthorized = this.HasModulePermission(moduleConfiguration, permissionKey); } } } + break; case SecurityAccessLevel.Admin: if (!((moduleConfiguration.IsShared && moduleConfiguration.IsShareableViewOnly) && TabPermissionController.CanAddContentToPage(tab))) { isAuthorized = TabPermissionController.CanAddContentToPage(tab); } + break; case SecurityAccessLevel.Host: break; } } + return isAuthorized; } /// ----------------------------------------------------------------------------- /// - /// HasModulePermission checks whether the current user has a specific Module Permission + /// HasModulePermission checks whether the current user has a specific Module Permission. /// - /// The Permissions for the Module - /// The Permission to check + /// The Permissions for the Module. + /// The Permission to check. + /// /// ----------------------------------------------------------------------------- public virtual bool HasModulePermission(ModulePermissionCollection modulePermissions, string permissionKey) { @@ -941,14 +946,15 @@ public virtual bool HasModulePermission(ModulePermissionCollection modulePermiss { hasPermission = PortalSecurity.IsInRoles(modulePermissions.ToString(permissionKey)); } - return hasPermission; + + return hasPermission; } /// ----------------------------------------------------------------------------- /// - /// SaveModulePermissions updates a Module's permissions + /// SaveModulePermissions updates a Module's permissions. /// - /// The Module to update + /// The Module to update. /// ----------------------------------------------------------------------------- public virtual void SaveModulePermissions(ModuleInfo module) { @@ -957,194 +963,194 @@ public virtual void SaveModulePermissions(ModuleInfo module) ModulePermissionCollection modulePermissions = ModulePermissionController.GetModulePermissions(module.ModuleID, module.TabID); if (!modulePermissions.CompareTo(module.ModulePermissions)) { - dataProvider.DeleteModulePermissionsByModuleID(module.ModuleID, module.PortalID); + this.dataProvider.DeleteModulePermissionsByModuleID(module.ModuleID, module.PortalID); foreach (ModulePermissionInfo modulePermission in module.ModulePermissions) { if (!module.IsShared && module.InheritViewPermissions && modulePermission.PermissionKey == "VIEW") { - dataProvider.DeleteModulePermission(modulePermission.ModulePermissionID); + this.dataProvider.DeleteModulePermission(modulePermission.ModulePermissionID); } else { - dataProvider.AddModulePermission(module.ModuleID, - module.PortalID, - modulePermission.PermissionID, - modulePermission.RoleID, - modulePermission.AllowAccess, - modulePermission.UserID, - UserController.Instance.GetCurrentUserInfo().UserID); + this.dataProvider.AddModulePermission( + module.ModuleID, + module.PortalID, + modulePermission.PermissionID, + modulePermission.RoleID, + modulePermission.AllowAccess, + modulePermission.UserID, + UserController.Instance.GetCurrentUserInfo().UserID); } } } } - } - - #endregion - - #region TabPermission Methods - + } + /// - /// Returns a list with all roles with implicit permissions on Tabs + /// Returns a list with all roles with implicit permissions on Tabs. /// - /// The Portal Id where the Roles are - /// A List with the implicit roles + /// The Portal Id where the Roles are. + /// A List with the implicit roles. public virtual IEnumerable ImplicitRolesForPages(int portalId) { - return DefaultImplicitRoles(portalId); + return this.DefaultImplicitRoles(portalId); } /// - /// Returns a list with all roles with implicit permissions on Folders + /// Returns a list with all roles with implicit permissions on Folders. /// - /// The Portal Id where the permissions are - /// A List with the implicit roles + /// The Portal Id where the permissions are. + /// A List with the implicit roles. public virtual IEnumerable ImplicitRolesForFolders(int portalId) { - return DefaultImplicitRoles(portalId); - } + return this.DefaultImplicitRoles(portalId); + } /// - /// Returns a flag indicating whether the current user can add content to a page + /// Returns a flag indicating whether the current user can add content to a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanAddContentToPage(TabInfo tab) { - return HasPagePermission(tab, ContentPagePermissionKey); + return this.HasPagePermission(tab, ContentPagePermissionKey); } /// - /// Returns a flag indicating whether the current user can add a child page to a page + /// Returns a flag indicating whether the current user can add a child page to a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanAddPage(TabInfo tab) { - return HasPagePermission(tab, AddPagePermissionKey); + return this.HasPagePermission(tab, AddPagePermissionKey); } /// - /// Returns a flag indicating whether the current user can administer a page + /// Returns a flag indicating whether the current user can administer a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanAdminPage(TabInfo tab) { return PortalSecurity.IsInRoles(tab.TabPermissions.ToString(AdminPagePermissionKey)); } /// - /// Returns a flag indicating whether the current user can copy a page + /// Returns a flag indicating whether the current user can copy a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanCopyPage(TabInfo tab) { - return HasPagePermission(tab, CopyPagePermissionKey); + return this.HasPagePermission(tab, CopyPagePermissionKey); } /// - /// Returns a flag indicating whether the current user can delete a page + /// Returns a flag indicating whether the current user can delete a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanDeletePage(TabInfo tab) { - return HasPagePermission(tab, DeletePagePermissionKey); + return this.HasPagePermission(tab, DeletePagePermissionKey); } /// - /// Returns a flag indicating whether the current user can export a page + /// Returns a flag indicating whether the current user can export a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanExportPage(TabInfo tab) { - return HasPagePermission(tab, ExportPagePermissionKey); + return this.HasPagePermission(tab, ExportPagePermissionKey); } /// - /// Returns a flag indicating whether the current user can import a page + /// Returns a flag indicating whether the current user can import a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanImportPage(TabInfo tab) { - return HasPagePermission(tab, ImportPagePermissionKey); + return this.HasPagePermission(tab, ImportPagePermissionKey); } /// - /// Returns a flag indicating whether the current user can manage a page's settings + /// Returns a flag indicating whether the current user can manage a page's settings. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanManagePage(TabInfo tab) { - return HasPagePermission(tab, ManagePagePermissionKey); + return this.HasPagePermission(tab, ManagePagePermissionKey); } /// - /// Returns a flag indicating whether the current user can see a page in a navigation object + /// Returns a flag indicating whether the current user can see a page in a navigation object. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanNavigateToPage(TabInfo tab) { - return HasPagePermission(tab, NavigatePagePermissionKey) || HasPagePermission(tab, ViewPagePermissionKey); + return this.HasPagePermission(tab, NavigatePagePermissionKey) || this.HasPagePermission(tab, ViewPagePermissionKey); } /// - /// Returns a flag indicating whether the current user can view a page + /// Returns a flag indicating whether the current user can view a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public virtual bool CanViewPage(TabInfo tab) { - return HasPagePermission(tab, ViewPagePermissionKey); + return this.HasPagePermission(tab, ViewPagePermissionKey); } /// ----------------------------------------------------------------------------- /// - /// DeleteTabPermissionsByUser deletes a user's Tab Permissions in the Database + /// DeleteTabPermissionsByUser deletes a user's Tab Permissions in the Database. /// - /// The user + /// The user. /// ----------------------------------------------------------------------------- public virtual void DeleteTabPermissionsByUser(UserInfo user) { - dataProvider.DeleteTabPermissionsByUserID(user.PortalID, user.UserID); + this.dataProvider.DeleteTabPermissionsByUserID(user.PortalID, user.UserID); DataCache.ClearTabPermissionsCache(user.PortalID); } /// ----------------------------------------------------------------------------- /// - /// GetTabPermissions gets a TabPermissionCollection + /// GetTabPermissions gets a TabPermissionCollection. /// - /// The ID of the tab - /// The ID of the portal + /// The ID of the tab. + /// The ID of the portal. + /// /// ----------------------------------------------------------------------------- public virtual TabPermissionCollection GetTabPermissions(int tabId, int portalId) { - //Get the Portal TabPermission Dictionary - Dictionary dicTabPermissions = GetTabPermissions(portalId); + // Get the Portal TabPermission Dictionary + Dictionary dicTabPermissions = this.GetTabPermissions(portalId); - //Get the Collection from the Dictionary + // Get the Collection from the Dictionary TabPermissionCollection tabPermissions; bool bFound = dicTabPermissions.TryGetValue(tabId, out tabPermissions); if (!bFound) { - //Return empty collection + // Return empty collection tabPermissions = new TabPermissionCollection(); } + return tabPermissions; } /// ----------------------------------------------------------------------------- /// - /// HasTabPermission checks whether the current user has a specific Tab Permission + /// HasTabPermission checks whether the current user has a specific Tab Permission. /// - /// The Permissions for the Tab - /// The Permission to check + /// The Permissions for the Tab. + /// The Permission to check. + /// /// ----------------------------------------------------------------------------- public virtual bool HasTabPermission(TabPermissionCollection tabPermissions, string permissionKey) { @@ -1167,18 +1173,19 @@ public virtual bool HasTabPermission(TabPermissionCollection tabPermissions, str hasPermission = PortalSecurity.IsInRoles(tabPermissions.ToString(permissionKey)); } } + return hasPermission; } /// ----------------------------------------------------------------------------- /// - /// SaveTabPermissions saves a Tab's permissions + /// SaveTabPermissions saves a Tab's permissions. /// - /// The Tab to update + /// The Tab to update. /// ----------------------------------------------------------------------------- public virtual void SaveTabPermissions(TabInfo tab) { - TabPermissionCollection objCurrentTabPermissions = GetTabPermissions(tab.TabID, tab.PortalID); + TabPermissionCollection objCurrentTabPermissions = this.GetTabPermissions(tab.TabID, tab.PortalID); if (!objCurrentTabPermissions.CompareTo(tab.TabPermissions)) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -1186,15 +1193,15 @@ public virtual void SaveTabPermissions(TabInfo tab) if (objCurrentTabPermissions.Count > 0) { - dataProvider.DeleteTabPermissionsByTabID(tab.TabID); - EventLogController.Instance.AddLog(tab, portalSettings, userId, "", EventLogController.EventLogType.TABPERMISSION_DELETED); + this.dataProvider.DeleteTabPermissionsByTabID(tab.TabID); + EventLogController.Instance.AddLog(tab, portalSettings, userId, string.Empty, EventLogController.EventLogType.TABPERMISSION_DELETED); } if (tab.TabPermissions != null && tab.TabPermissions.Count > 0) { foreach (TabPermissionInfo objTabPermission in tab.TabPermissions) { - objTabPermission.TabPermissionID = dataProvider.AddTabPermission( + objTabPermission.TabPermissionID = this.dataProvider.AddTabPermission( tab.TabID, objTabPermission.PermissionID, objTabPermission.RoleID, @@ -1202,20 +1209,18 @@ public virtual void SaveTabPermissions(TabInfo tab) objTabPermission.UserID, userId); } - EventLogController.Instance.AddLog(tab, portalSettings, userId, "", EventLogController.EventLogType.TABPERMISSION_CREATED); + + EventLogController.Instance.AddLog(tab, portalSettings, userId, string.Empty, EventLogController.EventLogType.TABPERMISSION_CREATED); } } - } - - #endregion - - #region DesktopModule Permissions Methods - + } + /// ----------------------------------------------------------------------------- /// - /// GetDesktopModulePermission gets a DesktopModule Permission from the Database + /// GetDesktopModulePermission gets a DesktopModule Permission from the Database. /// - /// The ID of the DesktopModule Permission + /// The ID of the DesktopModule Permission. + /// /// ----------------------------------------------------------------------------- public virtual DesktopModulePermissionInfo GetDesktopModulePermission(int desktopModulePermissionId) { @@ -1224,40 +1229,39 @@ public virtual DesktopModulePermissionInfo GetDesktopModulePermission(int deskto /// ----------------------------------------------------------------------------- /// - /// GetDesktopModulePermissions gets a DesktopModulePermissionCollection + /// GetDesktopModulePermissions gets a DesktopModulePermissionCollection. /// - /// The ID of the DesktopModule + /// The ID of the DesktopModule. + /// /// ----------------------------------------------------------------------------- public virtual DesktopModulePermissionCollection GetDesktopModulePermissions(int portalDesktopModuleId) { - //Get the Tab DesktopModulePermission Dictionary + // Get the Tab DesktopModulePermission Dictionary Dictionary dicDesktopModulePermissions = GetDesktopModulePermissions(); - //Get the Collection from the Dictionary + // Get the Collection from the Dictionary DesktopModulePermissionCollection desktopModulePermissions; bool bFound = dicDesktopModulePermissions.TryGetValue(portalDesktopModuleId, out desktopModulePermissions); if (!bFound) { - //Return empty collection + // Return empty collection desktopModulePermissions = new DesktopModulePermissionCollection(); } + return desktopModulePermissions; } /// ----------------------------------------------------------------------------- /// - /// HasDesktopModulePermission checks whether the current user has a specific DesktopModule Permission + /// HasDesktopModulePermission checks whether the current user has a specific DesktopModule Permission. /// - /// The Permissions for the DesktopModule - /// The Permission to check + /// The Permissions for the DesktopModule. + /// The Permission to check. + /// /// ----------------------------------------------------------------------------- public virtual bool HasDesktopModulePermission(DesktopModulePermissionCollection desktopModulePermissions, string permissionKey) { return PortalSecurity.IsInRoles(desktopModulePermissions.ToString(permissionKey)); - } - - #endregion - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs b/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs index 0cd782cdf15..d4c0895b073 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : TabPermissionCollection + /// Class : TabPermissionCollection /// ----------------------------------------------------------------------------- /// /// TabPermissionCollection provides the a custom collection for TabPermissionInfo - /// objects + /// objects. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -36,12 +31,12 @@ public TabPermissionCollection() public TabPermissionCollection(ArrayList tabPermissions) { - AddRange(tabPermissions); + this.AddRange(tabPermissions); } public TabPermissionCollection(TabPermissionCollection tabPermissions) { - AddRange(tabPermissions); + this.AddRange(tabPermissions); } public TabPermissionCollection(ArrayList tabPermissions, int TabId) @@ -50,7 +45,7 @@ public TabPermissionCollection(ArrayList tabPermissions, int TabId) { if (permission.TabID == TabId) { - Add(permission); + this.Add(permission); } } } @@ -59,17 +54,18 @@ public TabPermissionInfo this[int index] { get { - return (TabPermissionInfo) List[index]; + return (TabPermissionInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } } public int Add(TabPermissionInfo value) { - return List.Add(value); + return this.List.Add(value); } public int Add(TabPermissionInfo value, bool checkForDuplicates) @@ -78,12 +74,12 @@ public int Add(TabPermissionInfo value, bool checkForDuplicates) if (!checkForDuplicates) { - id = Add(value); + id = this.Add(value); } else { bool isMatch = false; - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) { @@ -91,9 +87,10 @@ public int Add(TabPermissionInfo value, bool checkForDuplicates) break; } } + if (!isMatch) { - id = Add(value); + id = this.Add(value); } } @@ -104,7 +101,7 @@ public void AddRange(ArrayList tabPermissions) { foreach (TabPermissionInfo permission in tabPermissions) { - Add(permission); + this.Add(permission); } } @@ -112,7 +109,7 @@ public void AddRange(IEnumerable tabPermissions) { foreach (TabPermissionInfo permission in tabPermissions) { - Add(permission); + this.Add(permission); } } @@ -120,19 +117,20 @@ public void AddRange(TabPermissionCollection tabPermissions) { foreach (TabPermissionInfo permission in tabPermissions) { - Add(permission); + this.Add(permission); } } public bool CompareTo(TabPermissionCollection objTabPermissionCollection) { - if (objTabPermissionCollection.Count != Count) + if (objTabPermissionCollection.Count != this.Count) { return false; } - InnerList.Sort(new CompareTabPermissions()); + + this.InnerList.Sort(new CompareTabPermissions()); objTabPermissionCollection.InnerList.Sort(new CompareTabPermissions()); - for (int i = 0; i <= Count - 1; i++) + for (int i = 0; i <= this.Count - 1; i++) { if (objTabPermissionCollection[i].TabPermissionID != this[i].TabPermissionID || objTabPermissionCollection[i].PermissionID != this[i].PermissionID @@ -143,36 +141,37 @@ public bool CompareTo(TabPermissionCollection objTabPermissionCollection) return false; } } + return true; } public bool Contains(TabPermissionInfo value) { - return List.Contains(value); + return this.List.Contains(value); } public int IndexOf(TabPermissionInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } public void Insert(int index, TabPermissionInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } public void Remove(TabPermissionInfo value) { - List.Remove(value); + this.List.Remove(value); } public void Remove(int permissionID, int roleID, int userID) { - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == permissionID && permission.UserID == userID && permission.RoleID == roleID) { - List.Remove(permission); + this.List.Remove(permission); break; } } @@ -181,16 +180,17 @@ public void Remove(int permissionID, int roleID, int userID) public List ToList() { var list = new List(); - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { list.Add(permission); } + return list; } public string ToString(string key) { - return PermissionController.BuildPermissions(List, key); + return PermissionController.BuildPermissions(this.List, key); } public IEnumerable Where(Func predicate) diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionController.cs b/DNN Platform/Library/Security/Permissions/TabPermissionController.cs index e0b44ae6006..161178e85f9 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionController.cs @@ -1,248 +1,234 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : TabPermissionController + /// Class : TabPermissionController /// ----------------------------------------------------------------------------- /// - /// TabPermissionController provides the Business Layer for Tab Permissions + /// TabPermissionController provides the Business Layer for Tab Permissions. /// /// ----------------------------------------------------------------------------- public class TabPermissionController - { - #region "Private Shared Methods" - - private static void ClearPermissionCache(int tabId) - { - var objTab = TabController.Instance.GetTab(tabId, Null.NullInteger, false); - DataCache.ClearTabPermissionsCache(objTab.PortalID); - } - - #endregion - - #region Private Members - - private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - - #endregion - - #region Public Shared Methods - + { + private static readonly PermissionProvider _provider = PermissionProvider.Instance(); + /// - /// Returns a list with all roles with implicit permissions on Tabs + /// Returns a list with all roles with implicit permissions on Tabs. /// - /// The Portal Id where the Roles are - /// A List with the implicit roles + /// The Portal Id where the Roles are. + /// A List with the implicit roles. public static IEnumerable ImplicitRoles(int portalId) { return _provider.ImplicitRolesForPages(portalId); } /// - /// Returns a flag indicating whether the current user can add content to the current page + /// Returns a flag indicating whether the current user can add content to the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanAddContentToPage() { return CanAddContentToPage(TabController.CurrentPage); } + + private static void ClearPermissionCache(int tabId) + { + var objTab = TabController.Instance.GetTab(tabId, Null.NullInteger, false); + DataCache.ClearTabPermissionsCache(objTab.PortalID); + } /// - /// Returns a flag indicating whether the current user can add content to a page + /// Returns a flag indicating whether the current user can add content to a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanAddContentToPage(TabInfo tab) { return _provider.CanAddContentToPage(tab); } /// - /// Returns a flag indicating whether the current user can add a child page to the current page + /// Returns a flag indicating whether the current user can add a child page to the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanAddPage() { return CanAddPage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can add a child page to a page + /// Returns a flag indicating whether the current user can add a child page to a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanAddPage(TabInfo tab) { return _provider.CanAddPage(tab); } /// - /// Returns a flag indicating whether the current user can administer the current page + /// Returns a flag indicating whether the current user can administer the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanAdminPage() { return CanAdminPage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can administer a page + /// Returns a flag indicating whether the current user can administer a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanAdminPage(TabInfo tab) { return _provider.CanAdminPage(tab); } /// - /// Returns a flag indicating whether the current user can copy the current page + /// Returns a flag indicating whether the current user can copy the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanCopyPage() { return CanCopyPage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can copy a page + /// Returns a flag indicating whether the current user can copy a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanCopyPage(TabInfo tab) { return _provider.CanCopyPage(tab); } /// - /// Returns a flag indicating whether the current user can delete the current page + /// Returns a flag indicating whether the current user can delete the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanDeletePage() { return CanDeletePage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can delete a page + /// Returns a flag indicating whether the current user can delete a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanDeletePage(TabInfo tab) { return _provider.CanDeletePage(tab); } /// - /// Returns a flag indicating whether the current user can export the current page + /// Returns a flag indicating whether the current user can export the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanExportPage() { return CanExportPage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can export a page + /// Returns a flag indicating whether the current user can export a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanExportPage(TabInfo tab) { return _provider.CanExportPage(tab); } /// - /// Returns a flag indicating whether the current user can import the current page + /// Returns a flag indicating whether the current user can import the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanImportPage() { return CanImportPage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can import a page + /// Returns a flag indicating whether the current user can import a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanImportPage(TabInfo tab) { return _provider.CanImportPage(tab); } /// - /// Returns a flag indicating whether the current user can manage the current page's settings + /// Returns a flag indicating whether the current user can manage the current page's settings. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanManagePage() { return CanManagePage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can manage a page's settings + /// Returns a flag indicating whether the current user can manage a page's settings. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanManagePage(TabInfo tab) { return _provider.CanManagePage(tab); } /// - /// Returns a flag indicating whether the current user can see the current page in a navigation object + /// Returns a flag indicating whether the current user can see the current page in a navigation object. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanNavigateToPage() { return CanNavigateToPage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can see a page in a navigation object + /// Returns a flag indicating whether the current user can see a page in a navigation object. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanNavigateToPage(TabInfo tab) { return _provider.CanNavigateToPage(tab); } /// - /// Returns a flag indicating whether the current user can view the current page + /// Returns a flag indicating whether the current user can view the current page. /// - /// A flag indicating whether the user has permission + /// A flag indicating whether the user has permission. public static bool CanViewPage() { return CanViewPage(TabController.CurrentPage); } /// - /// Returns a flag indicating whether the current user can view a page + /// Returns a flag indicating whether the current user can view a page. /// - /// The page - /// A flag indicating whether the user has permission + /// The page. + /// A flag indicating whether the user has permission. public static bool CanViewPage(TabInfo tab) { return _provider.CanViewPage(tab); @@ -250,23 +236,24 @@ public static bool CanViewPage(TabInfo tab) /// ----------------------------------------------------------------------------- /// - /// DeleteTabPermissionsByUser deletes a user's Tab Permissions in the Database + /// DeleteTabPermissionsByUser deletes a user's Tab Permissions in the Database. /// - /// The user + /// The user. /// ----------------------------------------------------------------------------- public static void DeleteTabPermissionsByUser(UserInfo user) { _provider.DeleteTabPermissionsByUser(user); - EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.TABPERMISSION_DELETED); + EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.TABPERMISSION_DELETED); DataCache.ClearTabPermissionsCache(user.PortalID); } /// ----------------------------------------------------------------------------- /// - /// GetTabPermissions gets a TabPermissionCollection + /// GetTabPermissions gets a TabPermissionCollection. /// - /// The ID of the tab - /// The ID of the portal + /// The ID of the tab. + /// The ID of the portal. + /// /// ----------------------------------------------------------------------------- public static TabPermissionCollection GetTabPermissions(int tabId, int portalId) { @@ -275,11 +262,12 @@ public static TabPermissionCollection GetTabPermissions(int tabId, int portalId) /// ----------------------------------------------------------------------------- /// - /// HasTabPermission checks whether the current user has a specific Tab Permission + /// HasTabPermission checks whether the current user has a specific Tab Permission. /// /// If you pass in a comma delimited list of permissions (eg "ADD,DELETE", this will return /// true if the user has any one of the permissions. - /// The Permission to check + /// The Permission to check. + /// /// ----------------------------------------------------------------------------- public static bool HasTabPermission(string permissionKey) { @@ -288,12 +276,13 @@ public static bool HasTabPermission(string permissionKey) /// ----------------------------------------------------------------------------- /// - /// HasTabPermission checks whether the current user has a specific Tab Permission + /// HasTabPermission checks whether the current user has a specific Tab Permission. /// /// If you pass in a comma delimited list of permissions (eg "ADD,DELETE", this will return /// true if the user has any one of the permissions. - /// The Permissions for the Tab - /// The Permission(s) to check + /// The Permissions for the Tab. + /// The Permission(s) to check. + /// /// ----------------------------------------------------------------------------- public static bool HasTabPermission(TabPermissionCollection tabPermissions, string permissionKey) { @@ -302,17 +291,15 @@ public static bool HasTabPermission(TabPermissionCollection tabPermissions, stri /// ----------------------------------------------------------------------------- /// - /// SaveTabPermissions saves a Tab's permissions + /// SaveTabPermissions saves a Tab's permissions. /// - /// The Tab to update + /// The Tab to update. /// ----------------------------------------------------------------------------- public static void SaveTabPermissions(TabInfo tab) { _provider.SaveTabPermissions(tab); - EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.TABPERMISSION_UPDATED); + EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.TABPERMISSION_UPDATED); DataCache.ClearTabPermissionsCache(tab.PortalID); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs b/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs index 137a82e10ef..2b09229797d 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs @@ -1,148 +1,134 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Permissions { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : TabPermissionInfo + /// Class : TabPermissionInfo /// ----------------------------------------------------------------------------- /// - /// TabPermissionInfo provides the Entity Layer for Tab Permissions + /// TabPermissionInfo provides the Entity Layer for Tab Permissions. /// /// ----------------------------------------------------------------------------- [Serializable] [XmlRoot("permission")] public class TabPermissionInfo : PermissionInfoBase, IHydratable - { - #region "Private Members" - + { private int _TabID; - //local property declarations - private int _TabPermissionID; - - #endregion - - #region "Constructors" - - /// ----------------------------------------------------------------------------- - /// - /// Constructs a new TabPermissionInfo + + // local property declarations + private int _TabPermissionID; + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a new TabPermissionInfo. /// /// ----------------------------------------------------------------------------- - public TabPermissionInfo() + public TabPermissionInfo() { - _TabPermissionID = Null.NullInteger; - _TabID = Null.NullInteger; - } - + this._TabPermissionID = Null.NullInteger; + this._TabID = Null.NullInteger; + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new TabPermissionInfo + /// + /// Initializes a new instance of the class. + /// Constructs a new TabPermissionInfo. /// - /// A PermissionInfo object + /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public TabPermissionInfo(PermissionInfo permission) : this() + public TabPermissionInfo(PermissionInfo permission) + : this() { - ModuleDefID = permission.ModuleDefID; - PermissionCode = permission.PermissionCode; - PermissionID = permission.PermissionID; - PermissionKey = permission.PermissionKey; - PermissionName = permission.PermissionName; - } - - #endregion - - #region "Public Properties" - + this.ModuleDefID = permission.ModuleDefID; + this.PermissionCode = permission.PermissionCode; + this.PermissionID = permission.PermissionID; + this.PermissionKey = permission.PermissionKey; + this.PermissionName = permission.PermissionName; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Tab Permission ID + /// Gets or sets and sets the Tab Permission ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlElement("tabpermissionid")] public int TabPermissionID { get { - return _TabPermissionID; + return this._TabPermissionID; } + set { - _TabPermissionID = value; + this._TabPermissionID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Tab ID + /// Gets or sets and sets the Tab ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlElement("tabid")] public int TabID { get { - return _TabID; + return this._TabID; } + set { - _TabID = value; + this._TabID = value; } - } - - #endregion - - #region IHydratable Members + } /// ----------------------------------------------------------------------------- /// - /// Fills a TabPermissionInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - //Call the base classes fill method to ppoulate base class proeprties - base.FillInternal(dr); - TabPermissionID = Null.SetNullInteger(dr["TabPermissionID"]); - TabID = Null.SetNullInteger(dr["TabID"]); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public int KeyID { get { - return TabPermissionID; + return this.TabPermissionID; } + set { - TabPermissionID = value; + this.TabPermissionID = value; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a TabPermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + // Call the base classes fill method to ppoulate base class proeprties + this.FillInternal(dr); + this.TabPermissionID = Null.SetNullInteger(dr["TabPermissionID"]); + this.TabID = Null.SetNullInteger(dr["TabID"]); } - - #endregion } } diff --git a/DNN Platform/Library/Security/PortalSecurity.cs b/DNN Platform/Library/Security/PortalSecurity.cs index 3b5c709f73a..ae44808f205 100644 --- a/DNN Platform/Library/Security/PortalSecurity.cs +++ b/DNN Platform/Library/Security/PortalSecurity.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Security; - -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Security.Cookies; -using DotNetNuke.Services.Cryptography; -// ReSharper disable MemberCanBeMadeStatic.Global - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable MemberCanBeMadeStatic.Global namespace DotNetNuke.Security { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Security; + + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Security.Cookies; + using DotNetNuke.Services.Cryptography; + public class PortalSecurity { public static readonly PortalSecurity Instance = new PortalSecurity(); @@ -36,14 +31,14 @@ public class PortalSecurity private const string RoleFollowerPrefix = "FOLLOWER:"; private const string RoleOwnerPrefix = "OWNER:"; + private const string BadStatementExpression = ";|--|\bcreate\b|\bdrop\b|\bselect\b|\binsert\b|\bdelete\b|\bupdate\b|\bunion\b|sp_|xp_|\bexec\b|\bexecute\b|/\\*.*\\*/|\bdeclare\b|\bwaitfor\b|%|&"; + + private const RegexOptions RxOptions = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled; + private static readonly DateTime OldExpiryTime = new DateTime(1999, 1, 1); private static readonly Regex StripTagsRegex = new Regex("<[^<>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); - - const string BadStatementExpression = ";|--|\bcreate\b|\bdrop\b|\bselect\b|\binsert\b|\bdelete\b|\bupdate\b|\bunion\b|sp_|xp_|\bexec\b|\bexecute\b|/\\*.*\\*/|\bdeclare\b|\bwaitfor\b|%|&"; private static readonly Regex BadStatementRegex = new Regex(BadStatementExpression, RegexOptions.IgnoreCase | RegexOptions.Compiled); - - const RegexOptions RxOptions = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled; private static readonly Regex[] RxListStrings = new[] { new Regex("]*>.*?<]*>", RxOptions), @@ -90,18 +85,16 @@ public class PortalSecurity }; private static readonly Regex DangerElementsRegex = new Regex(@"(<[^>]*?) on.*?\=(['""]*)[\s\S]*?(\2)( *)([^>]*?>)", RxOptions); - private static readonly Regex DangerElementContentRegex = new Regex(@"on.*?\=(['""]*)[\s\S]*?(\1)( *)", RxOptions); - - #region FilterFlag enum - - ///----------------------------------------------------------------------------- + private static readonly Regex DangerElementContentRegex = new Regex(@"on.*?\=(['""]*)[\s\S]*?(\1)( *)", RxOptions); + + /// ----------------------------------------------------------------------------- /// /// The FilterFlag enum determines which filters are applied by the InputFilter /// function. The Flags attribute allows the user to include multiple /// enumerated values in a single variable by OR'ing the individual values /// together. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- [Flags] public enum FilterFlag { @@ -110,43 +103,117 @@ public enum FilterFlag NoScripting = 4, NoSQL = 8, NoAngleBrackets = 16, - NoProfanity = 32 + NoProfanity = 32, } /// - /// Determines the configuration source for the remove and replace functions + /// Determines the configuration source for the remove and replace functions. /// public enum ConfigType { ListController, - ExternalFile + ExternalFile, } /// /// determines whether to use system (host) list, portal specific list, or combine both - /// At present only supported by ConfigType.ListController + /// At present only supported by ConfigType.ListController. /// public enum FilterScope { SystemList, PortalList, - SystemAndPortalList - } - - #endregion - - #region private enum - enum RoleType + SystemAndPortalList, + } + + private enum RoleType { Security, Friend, Follower, - Owner + Owner, + } + + public static void ForceSecureConnection() + { + // get current url + var url = HttpContext.Current.Request.Url.ToString(); + + // if unsecure connection + if (url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) + { + // switch to secure connection + url = "https://" + url.Substring("http://".Length); + + // append ssl parameter to querystring to indicate secure connection processing has already occurred + if (url.IndexOf("?", StringComparison.Ordinal) == -1) + { + url = url + "?ssl=1"; + } + else + { + url = url + "&ssl=1"; + } + + // redirect to secure connection + HttpContext.Current.Response.Redirect(url, true); + } } - #endregion - #region Private Methods + public static string GetCookieDomain(int portalId) + { + string cookieDomain = string.Empty; + if (PortalController.IsMemberOfPortalGroup(portalId)) + { + // set cookie domain for portal group + var groupController = new PortalGroupController(); + var group = groupController.GetPortalGroups().SingleOrDefault(p => p.MasterPortalId == PortalController.GetEffectivePortalId(portalId)); + + if (@group != null + && !string.IsNullOrEmpty(@group.AuthenticationDomain) + && PortalSettings.Current.PortalAlias.HTTPAlias.Contains(@group.AuthenticationDomain)) + { + cookieDomain = @group.AuthenticationDomain; + } + + if (string.IsNullOrEmpty(cookieDomain)) + { + cookieDomain = FormsAuthentication.CookieDomain; + } + } + else + { + // set cookie domain to be consistent with domain specification in web.config + cookieDomain = FormsAuthentication.CookieDomain; + } + + return cookieDomain; + } + + /// ----------------------------------------------------------------------------- + /// + /// This function creates a random key. + /// + /// This is the number of bytes for the key. + /// A random string. + /// + /// This is a public function used for generating SHA1 keys. + /// + public string CreateKey(int numBytes) + { + using (var rng = new RNGCryptoServiceProvider()) + { + var buff = new byte[numBytes]; + rng.GetBytes(buff); + return BytesToHexString(buff); + } + } + public string Decrypt(string strKey, string strData) + { + return CryptographyProvider.Instance().DecryptParameter(strData, strKey); + } + private static void ProcessRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed) { var roleType = GetRoleType(roleName); @@ -203,33 +270,35 @@ private static int GetEntityFromRoleName(string roleName) { var roleParts = roleName.Split(':'); int result; - if (roleParts.Length > 1 && Int32.TryParse(roleParts[1], out result)) + if (roleParts.Length > 1 && int.TryParse(roleParts[1], out result)) { return result; } + return Null.NullInteger; } private static void ProcessSecurityRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed) { roleAllowed = null; - //permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance - if (!String.IsNullOrEmpty(roleName)) + + // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance + if (!string.IsNullOrEmpty(roleName)) { - //Deny permission + // Deny permission if (roleName.StartsWith("!")) { - //Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) + // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) if (settings != null && !(settings.PortalId == user.PortalID && user.IsInRole(settings.AdministratorRoleName))) { - string denyRole = roleName.Replace("!", ""); + string denyRole = roleName.Replace("!", string.Empty); if (denyRole == Globals.glbRoleAllUsersName || user.IsInRole(denyRole)) { roleAllowed = false; } } } - else //Grant permission + else // Grant permission { if (roleName == Globals.glbRoleAllUsersName || user.IsInRole(roleName)) { @@ -245,14 +314,17 @@ private static RoleType GetRoleType(string roleName) { return RoleType.Friend; } + if (roleName.StartsWith(RoleFollowerPrefix, StringComparison.InvariantCultureIgnoreCase)) { return RoleType.Follower; } + if (roleName.StartsWith(RoleOwnerPrefix, StringComparison.InvariantCultureIgnoreCase)) { return RoleType.Owner; } + return RoleType.Security; } @@ -261,26 +333,27 @@ private static string BytesToHexString(IEnumerable bytes) var hexString = new StringBuilder(); foreach (var b in bytes) { - hexString.Append(String.Format("{0:X2}", b)); + hexString.Append(string.Format("{0:X2}", b)); } + return hexString.ToString(); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// This function uses Regex search strings to remove HTML tags which are /// targeted in Cross-site scripting (XSS) attacks. This function will evolve /// to provide more robust checking as additional holes are found. /// - /// This is the string to be filtered - /// Filtered UserInput + /// This is the string to be filtered. + /// Filtered UserInput. /// - /// This is a private function that is used internally by the FormatDisableScripting function + /// This is a private function that is used internally by the FormatDisableScripting function. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- private static string FilterStrings(string strInput) { - //setup up list of search terms as items may be used twice + // setup up list of search terms as items may be used twice var tempInput = strInput; if (string.IsNullOrEmpty(tempInput)) { @@ -289,7 +362,7 @@ private static string FilterStrings(string strInput) const string replacement = " "; - //remove the js event from html tags + // remove the js event from html tags var tagMatches = DangerElementsRegex.Matches(tempInput); foreach (Match match in tagMatches) { @@ -298,14 +371,14 @@ private static string FilterStrings(string strInput) tempInput = tempInput.Replace(tagContent, cleanTagContent); } - //check if text contains encoded angle brackets, if it does it we decode it to check the plain text + // check if text contains encoded angle brackets, if it does it we decode it to check the plain text if (tempInput.Contains(">") || tempInput.Contains("<")) { - //text is encoded, so decode and try again + // text is encoded, so decode and try again tempInput = HttpUtility.HtmlDecode(tempInput); tempInput = RxListStrings.Aggregate(tempInput, (current, s) => s.Replace(current, replacement)); - //Re-encode + // Re-encode tempInput = HttpUtility.HtmlEncode(tempInput); } else @@ -316,117 +389,89 @@ private static string FilterStrings(string strInput) return tempInput; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// This function uses Regex search strings to remove HTML tags which are - /// targeted in Cross-site scripting (XSS) attacks. This function will evolve - /// to provide more robust checking as additional holes are found. + /// This filter removes angle brackets i.e. /// - /// This is the string to be filtered - /// Filtered UserInput + /// This is the string to be filtered. + /// Filtered UserInput. /// - /// This is a private function that is used internally by the InputFilter function + /// This is a private function that is used internally by the InputFilter function. /// - ///----------------------------------------------------------------------------- - private string FormatDisableScripting(string strInput) + /// ----------------------------------------------------------------------------- + private static string FormatAngleBrackets(string strInput) { - return String.IsNullOrWhiteSpace(strInput) - ? strInput - : FilterStrings(strInput); + var tempInput = new StringBuilder(strInput).Replace("<", string.Empty).Replace(">", string.Empty); + return tempInput.ToString(); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// This filter removes angle brackets i.e. + /// This filter removes CrLf characters and inserts br. /// - /// This is the string to be filtered - /// Filtered UserInput + /// This is the string to be filtered. + /// Filtered UserInput. /// - /// This is a private function that is used internally by the InputFilter function + /// This is a private function that is used internally by the InputFilter function. /// - ///----------------------------------------------------------------------------- - private static string FormatAngleBrackets(string strInput) + /// ----------------------------------------------------------------------------- + private static string FormatMultiLine(string strInput) { - var tempInput = new StringBuilder(strInput).Replace("<", "").Replace(">", ""); + const string lbreak = "
    "; + var tempInput = new StringBuilder(strInput).Replace("\r\n", lbreak).Replace("\n", lbreak).Replace("\r", lbreak); return tempInput.ToString(); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// This filter removes CrLf characters and inserts br + /// This function uses Regex search strings to remove HTML tags which are + /// targeted in Cross-site scripting (XSS) attacks. This function will evolve + /// to provide more robust checking as additional holes are found. /// - /// This is the string to be filtered - /// Filtered UserInput + /// This is the string to be filtered. + /// Filtered UserInput. /// - /// This is a private function that is used internally by the InputFilter function + /// This is a private function that is used internally by the InputFilter function. /// - ///----------------------------------------------------------------------------- - private static string FormatMultiLine(string strInput) + /// ----------------------------------------------------------------------------- + private string FormatDisableScripting(string strInput) { - const string lbreak = "
    "; - var tempInput = new StringBuilder(strInput).Replace("\r\n", lbreak).Replace("\n", lbreak).Replace("\r", lbreak); - return tempInput.ToString(); + return string.IsNullOrWhiteSpace(strInput) + ? strInput + : FilterStrings(strInput); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// This function verifies raw SQL statements to prevent SQL injection attacks - /// and replaces a similar function (PreventSQLInjection) from the Common.Globals.vb module + /// and replaces a similar function (PreventSQLInjection) from the Common.Globals.vb module. /// - /// This is the string to be filtered - /// Filtered UserInput + /// This is the string to be filtered. + /// Filtered UserInput. /// - /// This is a private function that is used internally by the InputFilter function + /// This is a private function that is used internally by the InputFilter function. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- private static string FormatRemoveSQL(string strSQL) { // Check for forbidden T-SQL commands. Use word boundaries to filter only real statements. return BadStatementRegex.Replace(strSQL, " ").Replace("'", "''"); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// This function determines if the Input string contains any markup. /// - /// This is the string to be checked - /// True if string contains Markup tag(s) + /// This is the string to be checked. + /// True if string contains Markup tag(s). /// - /// This is a private function that is used internally by the InputFilter function + /// This is a private function that is used internally by the InputFilter function. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- private static bool IncludesMarkup(string strInput) { return StripTagsRegex.IsMatch(strInput); - } - - #endregion - - #region Public Methods - - ///----------------------------------------------------------------------------- - /// - /// This function creates a random key - /// - /// This is the number of bytes for the key - /// A random string - /// - /// This is a public function used for generating SHA1 keys - /// - public string CreateKey(int numBytes) - { - using (var rng = new RNGCryptoServiceProvider()) - { - var buff = new byte[numBytes]; - rng.GetBytes(buff); - return BytesToHexString(buff); - } - } - - public string Decrypt(string strKey, string strData) - { - return CryptographyProvider.Instance().DecryptParameter(strData, strKey); - } + } public string DecryptString(string message, string passphrase) { @@ -443,53 +488,60 @@ public string EncryptString(string message, string passphrase) return CryptographyProvider.Instance().EncryptString(message, passphrase); } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// This function applies security filtering to the UserInput string. /// - /// This is the string to be filtered - /// Flags which designate the filters to be applied - /// Filtered UserInput - ///----------------------------------------------------------------------------- + /// This is the string to be filtered. + /// Flags which designate the filters to be applied. + /// Filtered UserInput. + /// ----------------------------------------------------------------------------- public string InputFilter(string userInput, FilterFlag filterType) { if (userInput == null) { - return ""; + return string.Empty; } + var tempInput = userInput; if ((filterType & FilterFlag.NoAngleBrackets) == FilterFlag.NoAngleBrackets) { - var removeAngleBrackets = Config.GetSetting("RemoveAngleBrackets") != null && Boolean.Parse(Config.GetSetting("RemoveAngleBrackets")); + var removeAngleBrackets = Config.GetSetting("RemoveAngleBrackets") != null && bool.Parse(Config.GetSetting("RemoveAngleBrackets")); if (removeAngleBrackets) { tempInput = FormatAngleBrackets(tempInput); } } + if ((filterType & FilterFlag.NoSQL) == FilterFlag.NoSQL) { tempInput = FormatRemoveSQL(tempInput); } + if ((filterType & FilterFlag.NoMarkup) == FilterFlag.NoMarkup && IncludesMarkup(tempInput)) { tempInput = HttpUtility.HtmlEncode(tempInput); } + if ((filterType & FilterFlag.NoScripting) == FilterFlag.NoScripting) { - tempInput = FormatDisableScripting(tempInput); + tempInput = this.FormatDisableScripting(tempInput); } + if ((filterType & FilterFlag.MultiLine) == FilterFlag.MultiLine) { tempInput = FormatMultiLine(tempInput); } + if ((filterType & FilterFlag.NoProfanity) == FilterFlag.NoProfanity) { - tempInput = Replace(tempInput, ConfigType.ListController, "ProfanityFilter", FilterScope.SystemAndPortalList); + tempInput = this.Replace(tempInput, ConfigType.ListController, "ProfanityFilter", FilterScope.SystemAndPortalList); } + return tempInput; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Replaces profanity words with other words in the provided input string. /// @@ -505,7 +557,7 @@ public string InputFilter(string userInput, FilterFlag filterType) /// The external file to search the words. Ignored when configType is ListController. /// When using ListController configType, this parameter indicates which list(s) to use. /// The original text with the profanity words replaced. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public string Replace(string inputString, ConfigType configType, string configSource, FilterScope filterScope) { switch (configType) @@ -524,22 +576,23 @@ public string Replace(string inputString, ConfigType configType, string configSo switch (filterScope) { case FilterScope.SystemList: - listEntryHostInfos = listController.GetListEntryInfoItems(listName, "", Null.NullInteger); + listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger); inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options)); break; case FilterScope.SystemAndPortalList: settings = PortalController.Instance.GetCurrentPortalSettings(); - listEntryHostInfos = listController.GetListEntryInfoItems(listName, "", Null.NullInteger); - listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, "", settings.PortalId); + listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger); + listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId); inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options)); inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options)); break; case FilterScope.PortalList: settings = PortalController.Instance.GetCurrentPortalSettings(); - listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, "", settings.PortalId); + listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId); inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options)); break; } + break; case ConfigType.ExternalFile: throw new NotImplementedException(); @@ -550,7 +603,7 @@ public string Replace(string inputString, ConfigType configType, string configSo return inputString; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// Removes profanity words in the provided input string. /// @@ -566,7 +619,7 @@ public string Replace(string inputString, ConfigType configType, string configSo /// The external file to search the words. Ignored when configType is ListController. /// When using ListController configType, this parameter indicates which list(s) to use. /// The original text with the profanity words removed. - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public string Remove(string inputString, ConfigType configType, string configSource, FilterScope filterScope) { switch (configType) @@ -585,19 +638,19 @@ public string Remove(string inputString, ConfigType configType, string configSou switch (filterScope) { case FilterScope.SystemList: - listEntryHostInfos = listController.GetListEntryInfoItems(listName, "", Null.NullInteger); + listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger); inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options)); break; case FilterScope.SystemAndPortalList: settings = PortalController.Instance.GetCurrentPortalSettings(); - listEntryHostInfos = listController.GetListEntryInfoItems(listName, "", Null.NullInteger); - listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, "", settings.PortalId); + listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger); + listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId); inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options)); inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options)); break; case FilterScope.PortalList: settings = PortalController.Instance.GetCurrentPortalSettings(); - listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, "", settings.PortalId); + listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId); inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options)); break; } @@ -616,28 +669,30 @@ public void SignIn(UserInfo user, bool createPersistentCookie) { if (PortalController.IsMemberOfPortalGroup(user.PortalID) || createPersistentCookie) { - //Create a custom auth cookie + // Create a custom auth cookie - //first, create the authentication ticket + // first, create the authentication ticket var authenticationTicket = createPersistentCookie ? new FormsAuthenticationTicket(user.Username, true, Config.GetPersistentCookieTimeout()) : new FormsAuthenticationTicket(user.Username, false, Config.GetAuthCookieTimeout()); - //encrypt it + // encrypt it var encryptedAuthTicket = FormsAuthentication.Encrypt(authenticationTicket); - //Create a new Cookie + // Create a new Cookie var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedAuthTicket) { Expires = authenticationTicket.Expiration, Domain = GetCookieDomain(user.PortalID), Path = FormsAuthentication.FormsCookiePath, - Secure = FormsAuthentication.RequireSSL + Secure = FormsAuthentication.RequireSSL, }; - if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) - HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); - + if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) + { + HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); + } + HttpContext.Current.Response.Cookies.Set(authCookie); AuthCookieController.Instance.Update(authCookie.Value, authCookie.Expires.ToUniversalTime(), user.UserID); @@ -649,7 +704,7 @@ public void SignIn(UserInfo user, bool createPersistentCookie) Expires = authenticationTicket.Expiration, Domain = domain, Path = FormsAuthentication.FormsCookiePath, - Secure = FormsAuthentication.RequireSSL + Secure = FormsAuthentication.RequireSSL, }; HttpContext.Current.Response.Cookies.Set(siteGroupCookie); @@ -657,9 +712,11 @@ public void SignIn(UserInfo user, bool createPersistentCookie) } else { - if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) - HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); - + if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) + { + HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); + } + FormsAuthentication.SetAuthCookie(user.Username, false); var authCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName]; if (!string.IsNullOrEmpty(authCookie?.Value)) @@ -674,11 +731,11 @@ public void SignIn(UserInfo user, bool createPersistentCookie) if (user.IsSuperUser) { - //save userinfo object in context to ensure Personalization is saved correctly + // save userinfo object in context to ensure Personalization is saved correctly HttpContext.Current.Items["UserInfo"] = user; } - //Identity the Login is processed by system. + // Identity the Login is processed by system. HttpContext.Current.Items["DNN_UserSignIn"] = true; } @@ -693,20 +750,20 @@ public void SignOut() AuthCookieController.Instance.Update(currentAuthCookie.Value, OldExpiryTime, Null.NullInteger); } - //Log User Off from Cookie Authentication System + // Log User Off from Cookie Authentication System var domainCookie = HttpContext.Current.Request.Cookies["SiteGroup"]; if (domainCookie == null) { - //Forms Authentication's Logout + // Forms Authentication's Logout FormsAuthentication.SignOut(); } else { - //clear custom domain cookie + // clear custom domain cookie var domain = domainCookie.Value; - //Create a new Cookie - var str = String.Empty; + // Create a new Cookie + var str = string.Empty; if (HttpContext.Current.Request.Browser["supportsEmptyStringInCookieValue"] == "false") { str = "NoCookie"; @@ -717,7 +774,7 @@ public void SignOut() Expires = OldExpiryTime, Domain = domain, Path = FormsAuthentication.FormsCookiePath, - Secure = FormsAuthentication.RequireSSL + Secure = FormsAuthentication.RequireSSL, }; HttpContext.Current.Response.Cookies.Set(authCookie); @@ -727,35 +784,35 @@ public void SignOut() Expires = OldExpiryTime, Domain = domain, Path = FormsAuthentication.FormsCookiePath, - Secure = FormsAuthentication.RequireSSL + Secure = FormsAuthentication.RequireSSL, }; HttpContext.Current.Response.Cookies.Set(siteGroupCookie); } - //Remove current userinfo from context items + // Remove current userinfo from context items HttpContext.Current.Items.Remove("UserInfo"); - //remove language cookie + // remove language cookie var httpCookie = HttpContext.Current.Response.Cookies["language"]; if (httpCookie != null) { - httpCookie.Value = ""; + httpCookie.Value = string.Empty; } - //remove authentication type cookie + // remove authentication type cookie var cookie = HttpContext.Current.Response.Cookies["authentication"]; if (cookie != null) { - cookie.Value = ""; + cookie.Value = string.Empty; } - //expire cookies + // expire cookies cookie = HttpContext.Current.Response.Cookies["portalaliasid"]; if (cookie != null) { cookie.Value = null; - cookie.Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/"); + cookie.Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/"; cookie.Expires = DateTime.Now.AddYears(-30); } @@ -763,11 +820,11 @@ public void SignOut() if (cookie != null) { cookie.Value = null; - cookie.Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/"); + cookie.Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/"; cookie.Expires = DateTime.Now.AddYears(-30); } - //clear any authentication provider tokens that match *UserToken convention e.g FacebookUserToken ,TwitterUserToken, LiveUserToken and GoogleUserToken + // clear any authentication provider tokens that match *UserToken convention e.g FacebookUserToken ,TwitterUserToken, LiveUserToken and GoogleUserToken var authCookies = HttpContext.Current.Request.Cookies.AllKeys; foreach (var authCookie in authCookies) { @@ -777,46 +834,36 @@ public void SignOut() if (auth != null) { auth.Value = null; - auth.Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/"); + auth.Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/"; auth.Expires = DateTime.Now.AddYears(-30); } } } } - private static void InvalidateAspNetSession(HttpContext context) - { - if (context.Session != null && !context.Session.IsNewSession) - { - // invalidate existing session so a new one is created - context.Session.Clear(); - context.Session.Abandon(); - } - } - - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// This function applies security filtering to the UserInput string, and reports /// whether the input string is valid. /// - /// This is the string to be filtered - /// Flags which designate the filters to be applied + /// This is the string to be filtered. + /// Flags which designate the filters to be applied. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public bool ValidateInput(string userInput, FilterFlag filterType) { - string filteredInput = InputFilter(userInput, filterType); + string filteredInput = this.InputFilter(userInput, filterType); - return (userInput == filteredInput); + return userInput == filteredInput; } /// /// This function loops through every portal that has set its own AllowedExtensionWhitelist /// and checks that there are no extensions there that are restriced by the host - /// - /// The only time we should call this is if the host allowed extensions list has changed + /// + /// The only time we should call this is if the host allowed extensions list has changed. /// - /// Comma separated list of extensions that govern all users on this installation + /// Comma separated list of extensions that govern all users on this installation. public void CheckAllPortalFileExtensionWhitelists(string newMasterList) { var masterList = new FileExtensionWhitelist(newMasterList); @@ -833,64 +880,16 @@ public void CheckAllPortalFileExtensionWhitelists(string newMasterList) } } } - } - - #endregion + } - #region Public Shared/Static Methods - - public static void ForceSecureConnection() - { - //get current url - var url = HttpContext.Current.Request.Url.ToString(); - //if unsecure connection - if (url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) - { - //switch to secure connection - url = "https://" + url.Substring("http://".Length); - //append ssl parameter to querystring to indicate secure connection processing has already occurred - if (url.IndexOf("?", StringComparison.Ordinal) == -1) - { - url = url + "?ssl=1"; - } - else - { - url = url + "&ssl=1"; - } - //redirect to secure connection - HttpContext.Current.Response.Redirect(url, true); - } - } - - public static string GetCookieDomain(int portalId) + private static void InvalidateAspNetSession(HttpContext context) { - string cookieDomain = String.Empty; - if (PortalController.IsMemberOfPortalGroup(portalId)) - { - //set cookie domain for portal group - var groupController = new PortalGroupController(); - var group = groupController.GetPortalGroups().SingleOrDefault(p => p.MasterPortalId == PortalController.GetEffectivePortalId(portalId)); - - if (@group != null - && !string.IsNullOrEmpty(@group.AuthenticationDomain) - && PortalSettings.Current.PortalAlias.HTTPAlias.Contains(@group.AuthenticationDomain)) - { - cookieDomain = @group.AuthenticationDomain; - } - - if (String.IsNullOrEmpty(cookieDomain)) - { - cookieDomain = FormsAuthentication.CookieDomain; - } - } - else + if (context.Session != null && !context.Session.IsNewSession) { - //set cookie domain to be consistent with domain specification in web.config - cookieDomain = FormsAuthentication.CookieDomain; + // invalidate existing session so a new one is created + context.Session.Clear(); + context.Session.Abandon(); } - - - return cookieDomain; } public static bool IsDenied(string roles) @@ -899,10 +898,10 @@ public static bool IsDenied(string roles) PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); return IsDenied(objUserInfo, settings, roles); } - + public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, string roles) { - //super user always has full access + // super user always has full access if (objUserInfo.IsSuperUser) { return false; @@ -912,18 +911,18 @@ public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, strin if (roles != null) { - //permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance + // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance foreach (string role in roles.Split(new[] { ';' })) { - if (!String.IsNullOrEmpty(role)) + if (!string.IsNullOrEmpty(role)) { - //Deny permission + // Deny permission if (role.StartsWith("!")) { - //Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) + // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) if (settings != null && !(settings.PortalId == objUserInfo.PortalID && objUserInfo.IsInRole(settings.AdministratorRoleName))) { - string denyRole = role.Replace("!", ""); + string denyRole = role.Replace("!", string.Empty); if (denyRole == Globals.glbRoleAllUsersName || objUserInfo.IsInRole(denyRole)) { isDenied = true; @@ -957,7 +956,7 @@ public static bool IsInRoles(string roles) public static bool IsInRoles(UserInfo objUserInfo, PortalSettings settings, string roles) { - //super user always has full access + // super user always has full access bool isInRoles = objUserInfo.IsSuperUser; if (!isInRoles) @@ -976,6 +975,7 @@ public static bool IsInRoles(UserInfo objUserInfo, PortalSettings settings, stri } } } + return isInRoles; } @@ -998,7 +998,6 @@ public static bool IsOwner(int userId) UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); return IsInRoles(objUserInfo, settings, RoleOwnerPrefix + userId); - } - #endregion + } } } diff --git a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs index 210f3c49694..b60d41b4d1c 100644 --- a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs +++ b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs @@ -1,28 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - -// ReSharper disable InconsistentNaming -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable InconsistentNaming +// ReSharper disable CheckNamespace namespace DotNetNuke.Security.Profile + // ReSharper restore CheckNamespace { + using System; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Profile @@ -30,57 +26,20 @@ namespace DotNetNuke.Security.Profile /// ----------------------------------------------------------------------------- /// /// The DNNProfileProvider overrides the default ProfileProvider to provide - /// a purely DotNetNuke implementation + /// a purely DotNetNuke implementation. /// /// /// /// ----------------------------------------------------------------------------- public class DNNProfileProvider : ProfileProvider - { - #region Private Members - - private readonly DataProvider _dataProvider = DataProvider.Instance(); - - #endregion - - #region Private Methods - - private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollection properties) - { - ProfilePropertyDefinition newTimeZone = properties["PreferredTimeZone"]; - ProfilePropertyDefinition oldTimeZone = properties["TimeZone"]; - if (newTimeZone != null && oldTimeZone != null) - { - //Old timezone is present but new is not...we will set that up. - if (!string.IsNullOrEmpty(oldTimeZone.PropertyValue) && string.IsNullOrEmpty(newTimeZone.PropertyValue)) - { - int oldOffset; - int.TryParse(oldTimeZone.PropertyValue, out oldOffset); - TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(oldOffset); - newTimeZone.PropertyValue = timeZoneInfo.Id; - UpdateUserProfile(user); - } - //It's also possible that the new value is set but not the old value. We need to make them backwards compatible - else if (!string.IsNullOrEmpty(newTimeZone.PropertyValue) && string.IsNullOrEmpty(oldTimeZone.PropertyValue)) - { - TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(newTimeZone.PropertyValue); - if (timeZoneInfo != null) - { - oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); - } - } - } - } - - #endregion - - #region Public Methods - + { + private readonly DataProvider _dataProvider = DataProvider.Instance(); + /// ----------------------------------------------------------------------------- /// - /// Gets whether the Provider Properties can be edited + /// Gets a value indicating whether gets whether the Provider Properties can be edited. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public override bool CanEditProviderProperties { @@ -92,7 +51,7 @@ public override bool CanEditProviderProperties /// ----------------------------------------------------------------------------- /// - /// GetUserProfile retrieves the UserProfile information from the Data Store + /// GetUserProfile retrieves the UserProfile information from the Data Store. /// /// /// @@ -105,10 +64,10 @@ public override void GetUserProfile(ref UserInfo user) int portalId = user.IsSuperUser ? Globals.glbSuperUserAppName : user.PortalID; var properties = ProfileController.GetPropertyDefinitionsByPortal(portalId, true, false); - //Load the Profile properties + // Load the Profile properties if (user.UserID > Null.NullInteger) { - var key = GetProfileCacheKey(user); + var key = this.GetProfileCacheKey(user); var cachedProperties = (ProfilePropertyDefinitionCollection)DataCache.GetCache(key); if (cachedProperties != null) { @@ -116,15 +75,16 @@ public override void GetUserProfile(ref UserInfo user) } else { - using (var dr = _dataProvider.GetUserProfile(user.UserID)) + using (var dr = this._dataProvider.GetUserProfile(user.UserID)) { while (dr.Read()) { - //Ensure the data reader returned is valid + // Ensure the data reader returned is valid if (!string.Equals(dr.GetName(0), "ProfileID", StringComparison.InvariantCultureIgnoreCase)) { break; } + int definitionId = Convert.ToInt32(dr["PropertyDefinitionId"]); profProperty = properties.GetById(definitionId); if (profProperty != null) @@ -136,9 +96,10 @@ public override void GetUserProfile(ref UserInfo user) { extendedVisibility = Convert.ToString(dr["ExtendedVisibility"]); } + profProperty.ProfileVisibility = new ProfileVisibility(portalId, extendedVisibility) { - VisibilityMode = (UserVisibilityMode)dr["Visibility"] + VisibilityMode = (UserVisibilityMode)dr["Visibility"], }; } } @@ -150,31 +111,32 @@ public override void GetUserProfile(ref UserInfo user) } } } - - //Clear the profile + + // Clear the profile user.Profile.ProfileProperties.Clear(); - - //Add the properties to the profile - foreach (ProfilePropertyDefinition property in properties) + + // Add the properties to the profile + foreach (ProfilePropertyDefinition property in properties) { profProperty = property; if (string.IsNullOrEmpty(profProperty.PropertyValue) && !string.IsNullOrEmpty(profProperty.DefaultValue)) { profProperty.PropertyValue = profProperty.DefaultValue; } + user.Profile.ProfileProperties.Add(profProperty); } - //Clear IsDirty Flag + // Clear IsDirty Flag user.Profile.ClearIsDirty(); - //Ensure old and new TimeZone properties are in synch - UpdateTimeZoneInfo(user, properties); + // Ensure old and new TimeZone properties are in synch + this.UpdateTimeZoneInfo(user, properties); } /// ----------------------------------------------------------------------------- /// - /// UpdateUserProfile persists a user's Profile to the Data Store + /// UpdateUserProfile persists a user's Profile to the Data Store. /// /// /// @@ -182,47 +144,76 @@ public override void GetUserProfile(ref UserInfo user) /// ----------------------------------------------------------------------------- public override void UpdateUserProfile(UserInfo user) { - var key = GetProfileCacheKey(user); + var key = this.GetProfileCacheKey(user); DataCache.ClearCache(key); ProfilePropertyDefinitionCollection properties = user.Profile.ProfileProperties; - //Ensure old and new TimeZone properties are in synch + // Ensure old and new TimeZone properties are in synch var newTimeZone = properties["PreferredTimeZone"]; var oldTimeZone = properties["TimeZone"]; if (oldTimeZone != null && newTimeZone != null) - { //preference given to new property, if new is changed then old should be updated as well. + { // preference given to new property, if new is changed then old should be updated as well. if (newTimeZone.IsDirty && !string.IsNullOrEmpty(newTimeZone.PropertyValue)) { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(newTimeZone.PropertyValue); - if (timeZoneInfo != null) - oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); + if (timeZoneInfo != null) + { + oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); + } } - //however if old is changed, we need to update new as well + + // however if old is changed, we need to update new as well else if (oldTimeZone.IsDirty) { int oldOffset; int.TryParse(oldTimeZone.PropertyValue, out oldOffset); - newTimeZone.PropertyValue = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(oldOffset).Id; + newTimeZone.PropertyValue = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(oldOffset).Id; } } - + foreach (ProfilePropertyDefinition profProperty in properties) { - if ((profProperty.PropertyValue != null) && (profProperty.IsDirty)) + if ((profProperty.PropertyValue != null) && profProperty.IsDirty) { var objSecurity = PortalSecurity.Instance; string propertyValue = objSecurity.InputFilter(profProperty.PropertyValue, PortalSecurity.FilterFlag.NoScripting); - _dataProvider.UpdateProfileProperty(Null.NullInteger, user.UserID, profProperty.PropertyDefinitionId, - propertyValue, (int) profProperty.ProfileVisibility.VisibilityMode, + this._dataProvider.UpdateProfileProperty(Null.NullInteger, user.UserID, profProperty.PropertyDefinitionId, + propertyValue, (int)profProperty.ProfileVisibility.VisibilityMode, profProperty.ProfileVisibility.ExtendedVisibilityString(), DateTime.Now); - EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", "USERPROFILE_UPDATED"); + EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, "USERPROFILE_UPDATED"); } } - } - - #endregion - + } + + private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollection properties) + { + ProfilePropertyDefinition newTimeZone = properties["PreferredTimeZone"]; + ProfilePropertyDefinition oldTimeZone = properties["TimeZone"]; + if (newTimeZone != null && oldTimeZone != null) + { + // Old timezone is present but new is not...we will set that up. + if (!string.IsNullOrEmpty(oldTimeZone.PropertyValue) && string.IsNullOrEmpty(newTimeZone.PropertyValue)) + { + int oldOffset; + int.TryParse(oldTimeZone.PropertyValue, out oldOffset); + TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(oldOffset); + newTimeZone.PropertyValue = timeZoneInfo.Id; + this.UpdateUserProfile(user); + } + + // It's also possible that the new value is set but not the old value. We need to make them backwards compatible + else if (!string.IsNullOrEmpty(newTimeZone.PropertyValue) && string.IsNullOrEmpty(oldTimeZone.PropertyValue)) + { + TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(newTimeZone.PropertyValue); + if (timeZoneInfo != null) + { + oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); + } + } + } + } + private string GetProfileCacheKey(UserInfo user) { return string.Format(DataCache.UserProfileCacheKey, user.PortalID, user.Username); diff --git a/DNN Platform/Library/Security/Profile/ProfileProvider.cs b/DNN Platform/Library/Security/Profile/ProfileProvider.cs index be9e968650f..313e101c20b 100644 --- a/DNN Platform/Library/Security/Profile/ProfileProvider.cs +++ b/DNN Platform/Library/Security/Profile/ProfileProvider.cs @@ -1,40 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Profile { + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Users; + public abstract class ProfileProvider - { - #region "Abstract Properties" - - public abstract bool CanEditProviderProperties { get; } - - #endregion - - #region "Shared/Static Methods" - - //return the provider - public static ProfileProvider Instance() + { + public abstract bool CanEditProviderProperties { get; } + + // return the provider + public static ProfileProvider Instance() { return ComponentFactory.GetComponent(); - } - - #endregion - - #region "Abstract Methods" - - public abstract void GetUserProfile(ref UserInfo user); - - public abstract void UpdateUserProfile(UserInfo user); + } + + public abstract void GetUserProfile(ref UserInfo user); - #endregion + public abstract void UpdateUserProfile(UserInfo user); } } diff --git a/DNN Platform/Library/Security/Profile/ProfileProviderConfig.cs b/DNN Platform/Library/Security/Profile/ProfileProviderConfig.cs index efe1b0fe595..6c59df4a03e 100644 --- a/DNN Platform/Library/Security/Profile/ProfileProviderConfig.cs +++ b/DNN Platform/Library/Security/Profile/ProfileProviderConfig.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Profile { + using System.ComponentModel; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Profile @@ -17,7 +12,7 @@ namespace DotNetNuke.Security.Profile /// ----------------------------------------------------------------------------- /// /// The ProfileProviderConfig class provides a wrapper to the Profile providers - /// configuration + /// configuration. /// /// /// @@ -28,9 +23,9 @@ public class ProfileProviderConfig /// ----------------------------------------------------------------------------- /// - /// Gets whether the Provider Properties can be edited + /// Gets a value indicating whether gets whether the Provider Properties can be edited. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- [Browsable(false)] public static bool CanEditProviderProperties diff --git a/DNN Platform/Library/Security/RegistrationSettings.cs b/DNN Platform/Library/Security/RegistrationSettings.cs index 6d190aa4aac..40a0e848878 100644 --- a/DNN Platform/Library/Security/RegistrationSettings.cs +++ b/DNN Platform/Library/Security/RegistrationSettings.cs @@ -1,87 +1,101 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Common; -using DotNetNuke.Collections; -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security { - public class RegistrationSettings - { + using System.Collections.Generic; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + + public class RegistrationSettings + { + public RegistrationSettings() + { + this.RandomPassword = false; + this.RedirectAfterRegistration = -1; + this.RedirectAfterLogout = -1; + this.RedirectAfterLogin = -1; + this.RegistrationFields = string.Empty; + this.ExcludeTerms = string.Empty; + this.ExcludeTermsRegex = Null.NullString; + this.RegistrationFormType = 0; + this.RequirePasswordConfirm = true; + this.RequireUniqueDisplayName = false; + this.UseAuthProviders = false; + this.UseEmailAsUserName = false; + this.UseProfanityFilter = false; + this.RequireValidProfile = false; + this.RequireValidProfileAtLogin = true; + this.UseCaptcha = false; + this.UserNameValidator = Globals.glbUserNameRegEx; + this.DisplayNameFormat = string.Empty; + this.EmailValidator = Globals.glbEmailRegEx; + } + + public RegistrationSettings(Dictionary settings) + : this() + { + this.RandomPassword = settings.GetValueOrDefault("Registration_RandomPassword", this.RandomPassword); + this.RedirectAfterRegistration = settings.GetValueOrDefault("Redirect_AfterRegistration", this.RedirectAfterRegistration); + this.RedirectAfterLogout = settings.GetValueOrDefault("Redirect_AfterLogout", this.RedirectAfterLogout); + this.RedirectAfterLogin = settings.GetValueOrDefault("Redirect_AfterLogin", this.RedirectAfterLogin); + this.RegistrationFields = settings.GetValueOrDefault("Registration_RegistrationFields", this.RegistrationFields); + this.ExcludeTerms = settings.GetValueOrDefault("Registration_ExcludeTerms", this.ExcludeTerms); + this.RegistrationFormType = settings.GetValueOrDefault("Registration_RegistrationFormType", this.RegistrationFormType); + this.RequirePasswordConfirm = settings.GetValueOrDefault("Registration_RequireConfirmPassword", this.RequirePasswordConfirm); + this.RequireUniqueDisplayName = settings.GetValueOrDefault("Registration_RequireUniqueDisplayName", this.RequireUniqueDisplayName); + this.UseAuthProviders = settings.GetValueOrDefault("Registration_UseAuthProviders", this.UseAuthProviders); + this.UseEmailAsUserName = settings.GetValueOrDefault("Registration_UseEmailAsUserName", this.UseEmailAsUserName); + this.UseProfanityFilter = settings.GetValueOrDefault("Registration_UseProfanityFilter", this.UseProfanityFilter); + this.RequireValidProfile = settings.GetValueOrDefault("Security_RequireValidProfile", this.RequireValidProfile); + this.RequireValidProfileAtLogin = settings.GetValueOrDefault("Security_RequireValidProfileAtLogin", this.RequireValidProfileAtLogin); + this.UseCaptcha = settings.GetValueOrDefault("Security_CaptchaRegister", this.UseCaptcha); + this.UserNameValidator = settings.GetValueOrDefault("Security_UserNameValidation", this.UserNameValidator); + this.DisplayNameFormat = settings.GetValueOrDefault("Security_DisplayNameFormat", this.DisplayNameFormat); + this.EmailValidator = settings.GetValueOrDefault("Security_EmailValidation", this.EmailValidator); - #region Properties - public bool RandomPassword { get; set; } - public int RedirectAfterRegistration { get; set; } + this.ExcludeTermsRegex = "^(?:(?!" + this.ExcludeTerms.Replace(" ", string.Empty).Replace(",", "|") + ").)*$\\r?\\n?"; + } + + public bool RandomPassword { get; set; } + + public int RedirectAfterRegistration { get; set; } + public int RedirectAfterLogout { get; set; } + public int RedirectAfterLogin { get; set; } + public string RegistrationFields { get; set; } - public string ExcludeTerms { get; set; } - public string ExcludeTermsRegex { get; set; } - public int RegistrationFormType { get; set; } - public bool RequirePasswordConfirm { get; set; } - public bool RequireUniqueDisplayName { get; set; } - public bool UseAuthProviders { get; set; } - public bool UseEmailAsUserName { get; set; } - public bool UseProfanityFilter { get; set; } - public bool RequireValidProfile { get; set; } - public bool RequireValidProfileAtLogin { get; set; } - public bool UseCaptcha { get; set; } - public string UserNameValidator { get; set; } - public string DisplayNameFormat { get; set; } - public string EmailValidator { get; set; } - #endregion - - #region Constructors - - public RegistrationSettings() - { - RandomPassword = false; - RedirectAfterRegistration = -1; - RedirectAfterLogout = -1; - RedirectAfterLogin = -1; - RegistrationFields = string.Empty; - ExcludeTerms = string.Empty; - ExcludeTermsRegex = Null.NullString; - RegistrationFormType = 0; - RequirePasswordConfirm = true; - RequireUniqueDisplayName = false; - UseAuthProviders = false; - UseEmailAsUserName = false; - UseProfanityFilter = false; - RequireValidProfile = false; - RequireValidProfileAtLogin = true; - UseCaptcha = false; - UserNameValidator = Globals.glbUserNameRegEx; - DisplayNameFormat = string.Empty; - EmailValidator = Globals.glbEmailRegEx; - } - public RegistrationSettings(Dictionary settings): this() - { - RandomPassword = settings.GetValueOrDefault("Registration_RandomPassword", RandomPassword); - RedirectAfterRegistration = settings.GetValueOrDefault("Redirect_AfterRegistration", RedirectAfterRegistration); - RedirectAfterLogout = settings.GetValueOrDefault("Redirect_AfterLogout", RedirectAfterLogout); - RedirectAfterLogin = settings.GetValueOrDefault("Redirect_AfterLogin", RedirectAfterLogin); - RegistrationFields = settings.GetValueOrDefault("Registration_RegistrationFields", RegistrationFields); - ExcludeTerms = settings.GetValueOrDefault("Registration_ExcludeTerms", ExcludeTerms); - RegistrationFormType = settings.GetValueOrDefault("Registration_RegistrationFormType", RegistrationFormType); - RequirePasswordConfirm = settings.GetValueOrDefault("Registration_RequireConfirmPassword", RequirePasswordConfirm); - RequireUniqueDisplayName = settings.GetValueOrDefault("Registration_RequireUniqueDisplayName", RequireUniqueDisplayName); - UseAuthProviders = settings.GetValueOrDefault("Registration_UseAuthProviders", UseAuthProviders); - UseEmailAsUserName = settings.GetValueOrDefault("Registration_UseEmailAsUserName", UseEmailAsUserName); - UseProfanityFilter = settings.GetValueOrDefault("Registration_UseProfanityFilter", UseProfanityFilter); - RequireValidProfile = settings.GetValueOrDefault("Security_RequireValidProfile", RequireValidProfile); - RequireValidProfileAtLogin = settings.GetValueOrDefault("Security_RequireValidProfileAtLogin", RequireValidProfileAtLogin); - UseCaptcha = settings.GetValueOrDefault("Security_CaptchaRegister", UseCaptcha); - UserNameValidator = settings.GetValueOrDefault("Security_UserNameValidation", UserNameValidator); - DisplayNameFormat = settings.GetValueOrDefault("Security_DisplayNameFormat", DisplayNameFormat); - EmailValidator = settings.GetValueOrDefault("Security_EmailValidation", EmailValidator); - - ExcludeTermsRegex = "^(?:(?!" + ExcludeTerms.Replace(" ", "").Replace(",", "|") + ").)*$\\r?\\n?"; - } - #endregion - - } + + public string ExcludeTerms { get; set; } + + public string ExcludeTermsRegex { get; set; } + + public int RegistrationFormType { get; set; } + + public bool RequirePasswordConfirm { get; set; } + + public bool RequireUniqueDisplayName { get; set; } + + public bool UseAuthProviders { get; set; } + + public bool UseEmailAsUserName { get; set; } + + public bool UseProfanityFilter { get; set; } + + public bool RequireValidProfile { get; set; } + + public bool RequireValidProfileAtLogin { get; set; } + + public bool UseCaptcha { get; set; } + + public string UserNameValidator { get; set; } + + public string DisplayNameFormat { get; set; } + + public string EmailValidator { get; set; } + } } diff --git a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs index 68bb0182d36..80f2a252687 100644 --- a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs +++ b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Globalization; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Membership; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Roles { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Membership; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Membership @@ -30,34 +25,19 @@ namespace DotNetNuke.Security.Roles /// ----------------------------------------------------------------------------- /// /// The DNNRoleProvider overrides the default MembershipProvider to provide - /// a purely DNN Membership Component implementation + /// a purely DNN Membership Component implementation. /// /// /// /// ----------------------------------------------------------------------------- public class DNNRoleProvider : RoleProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DNNRoleProvider)); - private readonly DataProvider dataProvider = DataProvider.Instance(); - - #region Private Methods - - private void AddDNNUserRole(UserRoleInfo userRole) - { - //Add UserRole to DNN - userRole.UserRoleID = Convert.ToInt32(dataProvider.AddUserRole(userRole.PortalID, userRole.UserID, userRole.RoleID, - (int)userRole.Status, userRole.IsOwner, - userRole.EffectiveDate, userRole.ExpiryDate, - UserController.Instance.GetCurrentUserInfo().UserID)); - } - - #endregion - - #region Role Methods - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DNNRoleProvider)); + private readonly DataProvider dataProvider = DataProvider.Instance(); + /// ----------------------------------------------------------------------------- /// - /// CreateRole persists a Role to the Data Store + /// CreateRole persists a Role to the Data Store. /// /// /// @@ -71,24 +51,25 @@ public override bool CreateRole(RoleInfo role) try { role.RoleID = - Convert.ToInt32(dataProvider.AddRole(role.PortalID, - role.RoleGroupID, - role.RoleName.Trim(), - (role.Description ?? "").Trim(), - role.ServiceFee, - role.BillingPeriod.ToString(CultureInfo.InvariantCulture), - role.BillingFrequency, - role.TrialFee, - role.TrialPeriod, - role.TrialFrequency, - role.IsPublic, - role.AutoAssignment, - role.RSVPCode, - role.IconFile, - UserController.Instance.GetCurrentUserInfo().UserID, - (int)role.Status, - (int)role.SecurityMode, - role.IsSystemRole)); + Convert.ToInt32(this.dataProvider.AddRole( + role.PortalID, + role.RoleGroupID, + role.RoleName.Trim(), + (role.Description ?? string.Empty).Trim(), + role.ServiceFee, + role.BillingPeriod.ToString(CultureInfo.InvariantCulture), + role.BillingFrequency, + role.TrialFee, + role.TrialPeriod, + role.TrialFrequency, + role.IsPublic, + role.AutoAssignment, + role.RSVPCode, + role.IconFile, + UserController.Instance.GetCurrentUserInfo().UserID, + (int)role.Status, + (int)role.SecurityMode, + role.IsSystemRole)); } catch (SqlException e) { @@ -100,106 +81,117 @@ public override bool CreateRole(RoleInfo role) /// ----------------------------------------------------------------------------- /// - /// DeleteRole deletes a Role from the Data Store + /// DeleteRole deletes a Role from the Data Store. /// /// The role to delete from the Data Store. /// ----------------------------------------------------------------------------- public override void DeleteRole(RoleInfo role) { - dataProvider.DeleteRole(role.RoleID); + this.dataProvider.DeleteRole(role.RoleID); } + + private void AddDNNUserRole(UserRoleInfo userRole) + { + // Add UserRole to DNN + userRole.UserRoleID = Convert.ToInt32(this.dataProvider.AddUserRole(userRole.PortalID, userRole.UserID, userRole.RoleID, + (int)userRole.Status, userRole.IsOwner, + userRole.EffectiveDate, userRole.ExpiryDate, + UserController.Instance.GetCurrentUserInfo().UserID)); + } /// ----------------------------------------------------------------------------- /// - /// Get the roles for a portal + /// Get the roles for a portal. /// - /// Id of the portal (If -1 all roles for all portals are + /// Id of the portal (If -1 all roles for all portals are /// retrieved. - /// An ArrayList of RoleInfo objects + /// An ArrayList of RoleInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetRoles(int portalId) { - var arrRoles = CBO.FillCollection(portalId == Null.NullInteger - ? dataProvider.GetRoles() - : dataProvider.GetPortalRoles(portalId), typeof (RoleInfo)); + var arrRoles = CBO.FillCollection( + portalId == Null.NullInteger + ? this.dataProvider.GetRoles() + : this.dataProvider.GetPortalRoles(portalId), typeof(RoleInfo)); return arrRoles; } public override IList GetRolesBasicSearch(int portalID, int pageSize, string filterBy) { - return CBO.FillCollection(dataProvider.GetRolesBasicSearch(portalID, -1, pageSize, filterBy)); + return CBO.FillCollection(this.dataProvider.GetRolesBasicSearch(portalID, -1, pageSize, filterBy)); } public override IDictionary GetRoleSettings(int roleId) { var settings = new Dictionary { }; - using (IDataReader dr = dataProvider.GetRoleSettings(roleId)) { - while (dr.Read()) { + using (IDataReader dr = this.dataProvider.GetRoleSettings(roleId)) + { + while (dr.Read()) + { settings.Add(dr["SettingName"].ToString(), dr["SettingValue"].ToString()); } + dr.Close(); } + return settings; } /// ----------------------------------------------------------------------------- /// - /// Update a role + /// Update a role. /// - /// The role to update + /// The role to update. /// ----------------------------------------------------------------------------- public override void UpdateRole(RoleInfo role) { - dataProvider.UpdateRole(role.RoleID, - role.RoleGroupID, - role.RoleName.Trim(), - (role.Description ?? "").Trim(), - role.ServiceFee, - role.BillingPeriod.ToString(CultureInfo.InvariantCulture), - role.BillingFrequency, - role.TrialFee, - role.TrialPeriod, - role.TrialFrequency, - role.IsPublic, - role.AutoAssignment, - role.RSVPCode, - role.IconFile, - UserController.Instance.GetCurrentUserInfo().UserID, - (int)role.Status, - (int)role.SecurityMode, - role.IsSystemRole); + this.dataProvider.UpdateRole( + role.RoleID, + role.RoleGroupID, + role.RoleName.Trim(), + (role.Description ?? string.Empty).Trim(), + role.ServiceFee, + role.BillingPeriod.ToString(CultureInfo.InvariantCulture), + role.BillingFrequency, + role.TrialFee, + role.TrialPeriod, + role.TrialFrequency, + role.IsPublic, + role.AutoAssignment, + role.RSVPCode, + role.IconFile, + UserController.Instance.GetCurrentUserInfo().UserID, + (int)role.Status, + (int)role.SecurityMode, + role.IsSystemRole); } /// ----------------------------------------------------------------------------- /// - /// Update the role settings for a role + /// Update the role settings for a role. /// - /// The role to update + /// The role to update. /// ----------------------------------------------------------------------------- public override void UpdateRoleSettings(RoleInfo role) { - var currentSettings = GetRoleSettings(role.RoleID); + var currentSettings = this.GetRoleSettings(role.RoleID); foreach (var setting in role.Settings) { if (!currentSettings.ContainsKey(setting.Key) || currentSettings[setting.Key] != setting.Value) { - dataProvider.UpdateRoleSetting(role.RoleID, setting.Key, setting.Value, UserController.Instance.GetCurrentUserInfo().UserID); + this.dataProvider.UpdateRoleSetting(role.RoleID, setting.Key, setting.Value, UserController.Instance.GetCurrentUserInfo().UserID); } } - } - - #endregion - - #region User Role Methods - + } + /// ----------------------------------------------------------------------------- /// - /// AddUserToRole adds a User to a Role + /// AddUserToRole adds a User to a Role. /// /// /// - /// Id of the portal + /// Id of the portal. /// The user to add. /// The role to add the user to. /// A Boolean indicating success or failure. @@ -209,126 +201,114 @@ public override bool AddUserToRole(int portalId, UserInfo user, UserRoleInfo use bool createStatus = true; try { - //Add UserRole to DNN - AddDNNUserRole(userRole); + // Add UserRole to DNN + this.AddDNNUserRole(userRole); } catch (Exception exc) { - //Clear User (duplicate User information) + // Clear User (duplicate User information) Logger.Error(exc); createStatus = false; } + return createStatus; } /// ----------------------------------------------------------------------------- /// - /// GetUserRole gets a User/Role object from the Data Store + /// GetUserRole gets a User/Role object from the Data Store. /// /// /// - /// Id of the portal - /// The Id of the User + /// Id of the portal. + /// The Id of the User. /// The Id of the Role. - /// The UserRoleInfo object + /// The UserRoleInfo object. /// ----------------------------------------------------------------------------- public override UserRoleInfo GetUserRole(int portalId, int userId, int roleId) { - return CBO.FillObject(dataProvider.GetUserRole(portalId, userId, roleId)); + return CBO.FillObject(this.dataProvider.GetUserRole(portalId, userId, roleId)); } /// - /// Gets a list of UserRoles for the user + /// Gets a list of UserRoles for the user. /// - /// A UserInfo object representaing the user + /// A UserInfo object representaing the user. /// Include private roles. - /// A list of UserRoleInfo objects + /// A list of UserRoleInfo objects. public override IList GetUserRoles(UserInfo user, bool includePrivate) { Requires.NotNull("user", user); - return CBO.FillCollection(includePrivate - ? dataProvider.GetUserRoles(user.PortalID, user.UserID) - : dataProvider.GetServices(user.PortalID, user.UserID)); + return CBO.FillCollection(includePrivate + ? this.dataProvider.GetUserRoles(user.PortalID, user.UserID) + : this.dataProvider.GetServices(user.PortalID, user.UserID)); } /// ----------------------------------------------------------------------------- /// - /// GetUserRoles gets a collection of User/Role objects from the Data Store + /// GetUserRoles gets a collection of User/Role objects from the Data Store. /// /// /// - /// Id of the portal - /// The user to fetch roles for - /// The role to fetch users for - /// An ArrayList of UserRoleInfo objects + /// Id of the portal. + /// The user to fetch roles for. + /// The role to fetch users for. + /// An ArrayList of UserRoleInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetUserRoles(int portalId, string userName, string roleName) { - return CBO.FillCollection(dataProvider.GetUserRolesByUsername(portalId, userName, roleName), typeof (UserRoleInfo)); + return CBO.FillCollection(this.dataProvider.GetUserRolesByUsername(portalId, userName, roleName), typeof(UserRoleInfo)); } /// ----------------------------------------------------------------------------- /// - /// Get the users in a role (as User objects) + /// Get the users in a role (as User objects). /// - /// Id of the portal (If -1 all roles for all portals are + /// Id of the portal (If -1 all roles for all portals are /// retrieved. - /// The role to fetch users for - /// An ArrayList of UserInfo objects + /// The role to fetch users for. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetUsersByRoleName(int portalId, string roleName) { - return AspNetMembershipProvider.FillUserCollection(portalId, dataProvider.GetUsersByRolename(portalId, roleName)); + return AspNetMembershipProvider.FillUserCollection(portalId, this.dataProvider.GetUsersByRolename(portalId, roleName)); } /// ----------------------------------------------------------------------------- /// - /// Remove a User from a Role + /// Remove a User from a Role. /// /// /// - /// Id of the portal + /// Id of the portal. /// The user to remove. /// The role to remove the user from. /// ----------------------------------------------------------------------------- public override void RemoveUserFromRole(int portalId, UserInfo user, UserRoleInfo userRole) { - dataProvider.DeleteUserRole(userRole.UserID, userRole.RoleID); + this.dataProvider.DeleteUserRole(userRole.UserID, userRole.RoleID); } /// ----------------------------------------------------------------------------- /// - /// Updates a User/Role + /// Updates a User/Role. /// - /// The User/Role to update + /// The User/Role to update. /// ----------------------------------------------------------------------------- public override void UpdateUserRole(UserRoleInfo userRole) { - dataProvider.UpdateUserRole(userRole.UserRoleID, - (int)userRole.Status, userRole.IsOwner, - userRole.EffectiveDate, userRole.ExpiryDate, - UserController.Instance.GetCurrentUserInfo().UserID); - } - - #endregion - - #region RoleGroup Methods - - private void ClearRoleGroupCache(int portalId) - { - DataCache.ClearCache(GetRoleGroupsCacheKey(portalId)); - } - - private string GetRoleGroupsCacheKey(int portalId) - { - return String.Format(DataCache.RoleGroupsCacheKey, portalId); - } + this.dataProvider.UpdateUserRole( + userRole.UserRoleID, + (int)userRole.Status, userRole.IsOwner, + userRole.EffectiveDate, userRole.ExpiryDate, + UserController.Instance.GetCurrentUserInfo().UserID); + } /// ----------------------------------------------------------------------------- /// - /// CreateRoleGroup persists a RoleGroup to the Data Store + /// CreateRoleGroup persists a RoleGroup to the Data Store. /// /// /// @@ -337,81 +317,89 @@ private string GetRoleGroupsCacheKey(int portalId) /// ----------------------------------------------------------------------------- public override int CreateRoleGroup(RoleGroupInfo roleGroup) { - var roleGroupId = dataProvider.AddRoleGroup(roleGroup.PortalID, roleGroup.RoleGroupName.Trim(), - (roleGroup.Description ?? "").Trim(), + var roleGroupId = this.dataProvider.AddRoleGroup(roleGroup.PortalID, roleGroup.RoleGroupName.Trim(), + (roleGroup.Description ?? string.Empty).Trim(), UserController.Instance.GetCurrentUserInfo().UserID); - ClearRoleGroupCache(roleGroup.PortalID); + this.ClearRoleGroupCache(roleGroup.PortalID); return roleGroupId; } /// ----------------------------------------------------------------------------- /// - /// DeleteRoleGroup deletes a RoleGroup from the Data Store + /// DeleteRoleGroup deletes a RoleGroup from the Data Store. /// /// The RoleGroup to delete from the Data Store. /// ----------------------------------------------------------------------------- public override void DeleteRoleGroup(RoleGroupInfo roleGroup) { - dataProvider.DeleteRoleGroup(roleGroup.RoleGroupID); - ClearRoleGroupCache(roleGroup.PortalID); + this.dataProvider.DeleteRoleGroup(roleGroup.RoleGroupID); + this.ClearRoleGroupCache(roleGroup.PortalID); + } + + private void ClearRoleGroupCache(int portalId) + { + DataCache.ClearCache(this.GetRoleGroupsCacheKey(portalId)); + } + + private string GetRoleGroupsCacheKey(int portalId) + { + return string.Format(DataCache.RoleGroupsCacheKey, portalId); } /// ----------------------------------------------------------------------------- /// - /// GetRoleGroup gets a RoleGroup from the Data Store + /// GetRoleGroup gets a RoleGroup from the Data Store. /// - /// Id of the portal + /// Id of the portal. /// The Id of the RoleGroup to retrieve. - /// A RoleGroupInfo object + /// A RoleGroupInfo object. /// ----------------------------------------------------------------------------- public override RoleGroupInfo GetRoleGroup(int portalId, int roleGroupId) { - return GetRoleGroupsInternal(portalId).SingleOrDefault(r => r.RoleGroupID == roleGroupId); + return this.GetRoleGroupsInternal(portalId).SingleOrDefault(r => r.RoleGroupID == roleGroupId); } public override RoleGroupInfo GetRoleGroupByName(int portalId, string roleGroupName) { roleGroupName = roleGroupName.Trim(); - return GetRoleGroupsInternal(portalId).SingleOrDefault( + return this.GetRoleGroupsInternal(portalId).SingleOrDefault( r => roleGroupName.Equals(r.RoleGroupName.Trim(), StringComparison.InvariantCultureIgnoreCase)); } /// ----------------------------------------------------------------------------- /// - /// Get the RoleGroups for a portal + /// Get the RoleGroups for a portal. /// /// Id of the portal. - /// An ArrayList of RoleGroupInfo objects + /// An ArrayList of RoleGroupInfo objects. /// ----------------------------------------------------------------------------- public override ArrayList GetRoleGroups(int portalId) { - return new ArrayList(GetRoleGroupsInternal(portalId).ToList()); - } - - private IEnumerable GetRoleGroupsInternal(int portalId) - { - var cacheArgs = new CacheItemArgs(GetRoleGroupsCacheKey(portalId), - DataCache.RoleGroupsCacheTimeOut, - DataCache.RoleGroupsCachePriority); - - return CBO.GetCachedObject>(cacheArgs, c => - CBO.FillCollection(dataProvider.GetRoleGroups(portalId))); + return new ArrayList(this.GetRoleGroupsInternal(portalId).ToList()); } /// ----------------------------------------------------------------------------- /// - /// Update a RoleGroup + /// Update a RoleGroup. /// - /// The RoleGroup to update + /// The RoleGroup to update. /// ----------------------------------------------------------------------------- public override void UpdateRoleGroup(RoleGroupInfo roleGroup) { - dataProvider.UpdateRoleGroup(roleGroup.RoleGroupID, roleGroup.RoleGroupName.Trim(), - (roleGroup.Description ?? "").Trim(), UserController.Instance.GetCurrentUserInfo().UserID); - ClearRoleGroupCache(roleGroup.PortalID); - } - + this.dataProvider.UpdateRoleGroup(roleGroup.RoleGroupID, roleGroup.RoleGroupName.Trim(), + (roleGroup.Description ?? string.Empty).Trim(), UserController.Instance.GetCurrentUserInfo().UserID); + this.ClearRoleGroupCache(roleGroup.PortalID); + } + + private IEnumerable GetRoleGroupsInternal(int portalId) + { + var cacheArgs = new CacheItemArgs( + this.GetRoleGroupsCacheKey(portalId), + DataCache.RoleGroupsCacheTimeOut, + DataCache.RoleGroupsCachePriority); - #endregion + return CBO.GetCachedObject>(cacheArgs, c => + CBO.FillCollection(this.dataProvider.GetRoleGroups(portalId))); + } } } diff --git a/DNN Platform/Library/Security/Roles/IRoleController.cs b/DNN Platform/Library/Security/Roles/IRoleController.cs index 8db5830b4ab..eceab59de07 100644 --- a/DNN Platform/Library/Security/Roles/IRoleController.cs +++ b/DNN Platform/Library/Security/Roles/IRoleController.cs @@ -1,180 +1,178 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Users; + public interface IRoleController { /// - /// Adds a role + /// Adds a role. /// - /// The Role to Add - /// The Id of the new role + /// The Role to Add. + /// The Id of the new role. int AddRole(RoleInfo role); /// - /// Adds a role + /// Adds a role. /// - /// The Role to Add + /// The Role to Add. /// Add this role on all exist users if auto assignment is true. - /// The Id of the new role + /// The Id of the new role. int AddRole(RoleInfo role, bool addToExistUsers); /// - /// Adds a User to a Role + /// Adds a User to a Role. /// - /// Overload adds Effective Date - /// The Id of the Portal - /// The Id of the User - /// The Id of the Role - /// The status of the Role - /// If the user is the owner of the Role - /// The expiry Date of the Role membership - /// The expiry Date of the Role membership + /// Overload adds Effective Date. + /// The Id of the Portal. + /// The Id of the User. + /// The Id of the Role. + /// The status of the Role. + /// If the user is the owner of the Role. + /// The expiry Date of the Role membership. + /// The expiry Date of the Role membership. void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, bool isOwner, DateTime effectiveDate, DateTime expiryDate); /// /// Clears Roles cache for the passed portal ID and for the default ID (-1) as well. /// - /// Id of the portal + /// Id of the portal. void ClearRoleCache(int portalId); /// - /// Deletes a role + /// Deletes a role. /// - /// The Role to delete + /// The Role to delete. void DeleteRole(RoleInfo role); /// - /// Fetch a single role based on a predicate + /// Fetch a single role based on a predicate. /// - /// Id of the portal - /// The predicate (criteria) required - /// A RoleInfo object + /// Id of the portal. + /// The predicate (criteria) required. + /// A RoleInfo object. RoleInfo GetRole(int portalId, Func predicate); /// - /// Fetch a single role + /// Fetch a single role. /// - /// the roleid - /// the portalid - /// >A RoleInfo object + /// the roleid. + /// the portalid. + /// >A RoleInfo object. RoleInfo GetRoleById(int portalId, int roleId); /// - /// Fetch a role by rolename and portal id + /// Fetch a role by rolename and portal id. /// - /// the portalid - /// the role name - /// >A RoleInfo object + /// the portalid. + /// the role name. + /// >A RoleInfo object. RoleInfo GetRoleByName(int portalId, string roleName); /// - /// Obtains a list of roles from the cache (or for the database if the cache has expired) + /// Obtains a list of roles from the cache (or for the database if the cache has expired). /// - /// The id of the portal - /// The list of roles + /// The id of the portal. + /// The list of roles. IList GetRoles(int portalId); /// - /// Get the roles based on a predicate + /// Get the roles based on a predicate. /// - /// Id of the portal - /// The predicate (criteria) required - /// A List of RoleInfo objects + /// Id of the portal. + /// The predicate (criteria) required. + /// A List of RoleInfo objects. IList GetRoles(int portalId, Func predicate); /// - /// get a list of roles based on progressive search + /// get a list of roles based on progressive search. /// - /// the id of the portal - /// the number of items to return - /// the text used to trim data + /// the id of the portal. + /// the number of items to return. + /// the text used to trim data. /// IList GetRolesBasicSearch(int portalId, int pageSize, string filterBy); /// - /// Gets the settings for a role + /// Gets the settings for a role. /// - /// Id of the role - /// A Dictionary of settings + /// Id of the role. + /// A Dictionary of settings. IDictionary GetRoleSettings(int roleId); /// - /// Gets a User/Role + /// Gets a User/Role. /// - /// The Id of the Portal - /// The Id of the user - /// The Id of the Role - /// A UserRoleInfo object + /// The Id of the Portal. + /// The Id of the user. + /// The Id of the Role. + /// A UserRoleInfo object. UserRoleInfo GetUserRole(int portalId, int userId, int roleId); /// - /// Gets a list of UserRoles for the user + /// Gets a list of UserRoles for the user. /// - /// A UserInfo object representaing the user + /// A UserInfo object representaing the user. /// Include private roles. - /// A list of UserRoleInfo objects + /// A list of UserRoleInfo objects. IList GetUserRoles(UserInfo user, bool includePrivate); /// - /// Gets a list of UserRoles for the user + /// Gets a list of UserRoles for the user. /// - /// Id of the portal - /// The user to fetch roles for - /// The role to fetch users for - /// A list of UserRoleInfo objects + /// Id of the portal. + /// The user to fetch roles for. + /// The role to fetch users for. + /// A list of UserRoleInfo objects. IList GetUserRoles(int portalId, string userName, string roleName); /// - /// Get the users in a role (as User objects) + /// Get the users in a role (as User objects). /// /// /// Id of the portal (If -1 all roles for all portals are /// retrieved. /// - /// The role to fetch users for - /// A List of UserInfo objects + /// The role to fetch users for. + /// A List of UserInfo objects. IList GetUsersByRole(int portalId, string roleName); /// - /// Persists a role to the Data Store + /// Persists a role to the Data Store. /// - /// The role to persist + /// The role to persist. void UpdateRole(RoleInfo role); /// - /// Persists a role to the Data Store + /// Persists a role to the Data Store. /// - /// The role to persist + /// The role to persist. /// Add this role on all exist users if auto assignment is true. void UpdateRole(RoleInfo role, bool addToExistUsers); /// - /// Update the role settings + /// Update the role settings. /// - /// The Role - /// A flag that indicates whether the cache should be cleared + /// The Role. + /// A flag that indicates whether the cache should be cleared. void UpdateRoleSettings(RoleInfo role, bool clearCache); /// - /// Updates a Service (UserRole) + /// Updates a Service (UserRole). /// - /// The Id of the Portal - /// The Id of the User - /// The Id of the Role - /// The status of the Role - /// If the user is the owner of the Role - /// A flag that indicates whether to cancel (delete) the userrole + /// The Id of the Portal. + /// The Id of the User. + /// The Id of the Role. + /// The status of the Role. + /// If the user is the owner of the Role. + /// A flag that indicates whether to cancel (delete) the userrole. void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus status, bool isOwner, bool cancel); - - - } } diff --git a/DNN Platform/Library/Security/Roles/IRoleEventHandlers.cs b/DNN Platform/Library/Security/Roles/IRoleEventHandlers.cs index c0e898f8145..6ce85d15132 100644 --- a/DNN Platform/Library/Security/Roles/IRoleEventHandlers.cs +++ b/DNN Platform/Library/Security/Roles/IRoleEventHandlers.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { public interface IRoleEventHandlers diff --git a/DNN Platform/Library/Security/Roles/RoleComparer.cs b/DNN Platform/Library/Security/Roles/RoleComparer.cs index 1b1c3ab7086..39eb5f2692c 100644 --- a/DNN Platform/Library/Security/Roles/RoleComparer.cs +++ b/DNN Platform/Library/Security/Roles/RoleComparer.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Roles { + using System.Collections; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Roles @@ -17,26 +12,22 @@ namespace DotNetNuke.Security.Roles /// ----------------------------------------------------------------------------- /// /// The RoleComparer class provides an Implementation of IComparer for - /// RoleInfo objects + /// RoleInfo objects. /// /// ----------------------------------------------------------------------------- public class RoleComparer : IComparer - { - #region IComparer Members - + { /// ----------------------------------------------------------------------------- /// - /// Compares two RoleInfo objects by performing a comparison of their rolenames + /// Compares two RoleInfo objects by performing a comparison of their rolenames. /// - /// One of the items to compare - /// One of the items to compare - /// An Integer that determines whether x is greater, smaller or equal to y + /// One of the items to compare. + /// One of the items to compare. + /// An Integer that determines whether x is greater, smaller or equal to y. /// ----------------------------------------------------------------------------- public int Compare(object x, object y) { - return new CaseInsensitiveComparer().Compare(((RoleInfo) x).RoleName, ((RoleInfo) y).RoleName); - } - - #endregion + return new CaseInsensitiveComparer().Compare(((RoleInfo)x).RoleName, ((RoleInfo)y).RoleName); + } } } diff --git a/DNN Platform/Library/Security/Roles/RoleController.cs b/DNN Platform/Library/Security/Roles/RoleController.cs index a1c8306a5e0..20a86ec9aff 100644 --- a/DNN Platform/Library/Security/Roles/RoleController.cs +++ b/DNN Platform/Library/Security/Roles/RoleController.cs @@ -1,34 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Journal; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Mail; -using DotNetNuke.Services.Messaging.Data; -using DotNetNuke.Services.Search.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Journal; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.Messaging.Data; + using DotNetNuke.Services.Search.Entities; + /// - /// The RoleController class provides Business Layer methods for Roles + /// The RoleController class provides Business Layer methods for Roles. /// /// ----------------------------------------------------------------------------- public partial class RoleController : ServiceLocator, IRoleController @@ -41,47 +42,100 @@ private enum UserRoleActions { add = 0, update = 1, - delete = 2 + delete = 2, } - - protected override Func GetFactory() + + /// ----------------------------------------------------------------------------- + /// + /// Adds a Role Group. + /// + /// The RoleGroup to Add. + /// The Id of the new role. + /// ----------------------------------------------------------------------------- + public static int AddRoleGroup(RoleGroupInfo objRoleGroupInfo) { - return () => new RoleController(); + var id = provider.CreateRoleGroup(objRoleGroupInfo); + EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_CREATED); + return id; } - #region Private Methods - - private void AddMessage(RoleInfo roleInfo, EventLogController.EventLogType logType) + /// + /// Adds a User to a Role. + /// + /// The user to assign. + /// The role to add. + /// The PortalSettings of the Portal. + /// RoleStatus. + /// The expiry Date of the Role membership. + /// The expiry Date of the Role membership. + /// A flag that indicates whether the user should be notified. + /// A flag that indicates whether this user should be one of the group owners. + public static void AddUserRole(UserInfo user, RoleInfo role, PortalSettings portalSettings, RoleStatus status, DateTime effectiveDate, DateTime expiryDate, bool notifyUser, bool isOwner) { - EventLogController.Instance.AddLog(roleInfo, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - "", - logType); + var userRole = Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); + + // update assignment + Instance.AddUserRole(portalSettings.PortalId, user.UserID, role.RoleID, status, isOwner, effectiveDate, expiryDate); + + UserController.UpdateUser(portalSettings.PortalId, user); + if (userRole == null) + { + EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_CREATED); + // send notification + if (notifyUser) + { + SendNotification(user, role, portalSettings, UserRoleActions.@add); + } + } + else + { + EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_UPDATED); + if (notifyUser) + { + RoleController.Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); + SendNotification(user, role, portalSettings, UserRoleActions.update); + } + } + + // Remove the UserInfo from the Cache, as it has been modified + DataCache.ClearUserCache(portalSettings.PortalId, user.Username); + } + + public int AddRole(RoleInfo role) + { + return Instance.AddRole(role, true); } - private void AutoAssignUsers(RoleInfo role) + int IRoleController.AddRole(RoleInfo role, bool addToExistUsers) { - if (role.AutoAssignment) + Requires.NotNull("role", role); + + var roleId = -1; + if (provider.CreateRole(role)) { - //loop through users for portal and add to role - var arrUsers = UserController.GetUsers(role.PortalID); - foreach (UserInfo objUser in arrUsers) + this.AddMessage(role, EventLogController.EventLogType.ROLE_CREATED); + if (addToExistUsers) { - try - { - AddUserRole(role.PortalID, objUser.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - catch (Exception exc) - { - //user already belongs to role - Logger.Error(exc); - } + this.AutoAssignUsers(role); } + + roleId = role.RoleID; + + this.ClearRoleCache(role.PortalID); + + EventManager.Instance.OnRoleCreated(new RoleEventArgs() { Role = role }); } + + return roleId; } + protected override Func GetFactory() + { + return () => new RoleController(); + } + private static bool DeleteUserRoleInternal(int portalId, int userId, int roleId) { var user = UserController.GetUserById(portalId, userId); @@ -93,9 +147,9 @@ private static bool DeleteUserRoleInternal(int portalId, int userId, int roleId) if (CanRemoveUserFromRole(portal, userId, roleId)) { provider.RemoveUserFromRole(portalId, user, userRole); - EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.ROLE_UPDATED); + EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.ROLE_UPDATED); - //Remove the UserInfo from the Cache, as it has been modified + // Remove the UserInfo from the Cache, as it has been modified DataCache.ClearUserCache(portalId, user.Username); Instance.ClearRoleCache(portalId); @@ -106,6 +160,7 @@ private static bool DeleteUserRoleInternal(int portalId, int userId, int roleId) delete = false; } } + return delete; } @@ -121,6 +176,7 @@ private static void SendNotification(UserInfo objUser, RoleInfo objRole, PortalS { preferredLocale = PortalSettings.DefaultLanguage; } + var ci = new CultureInfo(preferredLocale); UserRoleInfo objUserRole = RoleController.Instance.GetUserRole(PortalSettings.PortalId, objUser.UserID, objRole.RoleID); Custom.Add(Null.IsNull(objUserRole.EffectiveDate) @@ -129,9 +185,10 @@ private static void SendNotification(UserInfo objUser, RoleInfo objRole, PortalS Custom.Add(Null.IsNull(objUserRole.ExpiryDate) ? "-" : objUserRole.ExpiryDate.ToString("g", ci)); break; case UserRoleActions.delete: - Custom.Add(""); + Custom.Add(string.Empty); break; } + var _message = new Message { FromUserID = PortalSettings.AdministratorId, @@ -141,58 +198,59 @@ private static void SendNotification(UserInfo objUser, RoleInfo objRole, PortalS "EMAIL_ROLE_" + UserRoleActionsCaption[(int)Action] + "_SUBJECT", objUser), - Body = Localization.GetSystemMessage(objUser.Profile.PreferredLocale, - PortalSettings, - "EMAIL_ROLE_" + + Body = Localization.GetSystemMessage( + objUser.Profile.PreferredLocale, + PortalSettings, + "EMAIL_ROLE_" + UserRoleActionsCaption[(int)Action] + "_BODY", - objUser, - Localization.GlobalResourceFile, - Custom), - Status = MessageStatusType.Unread + objUser, + Localization.GlobalResourceFile, + Custom), + Status = MessageStatusType.Unread, }; - //_messagingController.SaveMessage(_message); + // _messagingController.SaveMessage(_message); Mail.SendEmail(PortalSettings.Email, objUser.Email, _message.Subject, _message.Body); - } - - #endregion - - #region Public Methods - - public int AddRole(RoleInfo role) + } + + private void AddMessage(RoleInfo roleInfo, EventLogController.EventLogType logType) { - return Instance.AddRole(role, true); + EventLogController.Instance.AddLog( + roleInfo, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + logType); } - int IRoleController.AddRole(RoleInfo role, bool addToExistUsers) + private void AutoAssignUsers(RoleInfo role) { - Requires.NotNull("role", role); - - var roleId = -1; - if (provider.CreateRole(role)) + if (role.AutoAssignment) { - AddMessage(role, EventLogController.EventLogType.ROLE_CREATED); - if (addToExistUsers) + // loop through users for portal and add to role + var arrUsers = UserController.GetUsers(role.PortalID); + foreach (UserInfo objUser in arrUsers) { - AutoAssignUsers(role); + try + { + this.AddUserRole(role.PortalID, objUser.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + catch (Exception exc) + { + // user already belongs to role + Logger.Error(exc); + } } - roleId = role.RoleID; - - ClearRoleCache(role.PortalID); - - EventManager.Instance.OnRoleCreated(new RoleEventArgs() { Role = role }); } - - return roleId; } public void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, bool isOwner, DateTime effectiveDate, DateTime expiryDate) { UserInfo user = UserController.GetUserById(portalId, userId); - UserRoleInfo userRole = GetUserRole(portalId, userId, roleId); + UserRoleInfo userRole = this.GetUserRole(portalId, userId, roleId); if (userRole == null) { - //Create new UserRole + // Create new UserRole userRole = new UserRoleInfo { UserID = userId, @@ -201,10 +259,10 @@ public void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, Status = status, IsOwner = isOwner, EffectiveDate = effectiveDate, - ExpiryDate = expiryDate + ExpiryDate = expiryDate, }; provider.AddUserToRole(portalId, user, userRole); - EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_CREATED); + EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_CREATED); } else { @@ -213,21 +271,22 @@ public void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, userRole.EffectiveDate = effectiveDate; userRole.ExpiryDate = expiryDate; provider.UpdateUserRole(userRole); - EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_UPDATED); + EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_UPDATED); } - EventManager.Instance.OnRoleJoined(new RoleEventArgs() { Role = GetRoleById(portalId, roleId), User = user }); - //Remove the UserInfo and Roles from the Cache, as they have been modified + EventManager.Instance.OnRoleJoined(new RoleEventArgs() { Role = this.GetRoleById(portalId, roleId), User = user }); + + // Remove the UserInfo and Roles from the Cache, as they have been modified DataCache.ClearUserCache(portalId, user.Username); Instance.ClearRoleCache(portalId); } public void ClearRoleCache(int portalId) { - DataCache.RemoveCache(String.Format(DataCache.RolesCacheKey, portalId)); + DataCache.RemoveCache(string.Format(DataCache.RolesCacheKey, portalId)); if (portalId != Null.NullInteger) { - DataCache.RemoveCache(String.Format(DataCache.RolesCacheKey, Null.NullInteger)); + DataCache.RemoveCache(string.Format(DataCache.RolesCacheKey, Null.NullInteger)); } } @@ -235,11 +294,11 @@ public void DeleteRole(RoleInfo role) { Requires.NotNull("role", role); - AddMessage(role, EventLogController.EventLogType.ROLE_DELETED); + this.AddMessage(role, EventLogController.EventLogType.ROLE_DELETED); if (role.SecurityMode != SecurityMode.SecurityRole) { - //remove group artifacts + // remove group artifacts var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); IFileManager _fileManager = FileManager.Instance; @@ -251,28 +310,29 @@ public void DeleteRole(RoleInfo role) _fileManager.DeleteFiles(_folderManager.GetFiles(groupFolder)); _folderManager.DeleteFolder(groupFolder); } + JournalController.Instance.SoftDeleteJournalItemByGroupId(portalSettings.PortalId, role.RoleID); } - //Get users before deleting role - var users = role.UserCount > 0 ? GetUsersByRole(role.PortalID, role.RoleName) : Enumerable.Empty(); + // Get users before deleting role + var users = role.UserCount > 0 ? this.GetUsersByRole(role.PortalID, role.RoleName) : Enumerable.Empty(); provider.DeleteRole(role); EventManager.Instance.OnRoleDeleted(new RoleEventArgs() { Role = role }); - //Remove the UserInfo objects of users that have been members of the group from the cache, as they have been modified + // Remove the UserInfo objects of users that have been members of the group from the cache, as they have been modified foreach (var user in users) { DataCache.ClearUserCache(role.PortalID, user.Username); } - ClearRoleCache(role.PortalID); + this.ClearRoleCache(role.PortalID); // queue remove role/group from search index var document = new SearchDocumentToDelete { - //PortalId = role.PortalID, + // PortalId = role.PortalID, RoleId = role.RoleID, // this is unique and sufficient }; @@ -281,30 +341,31 @@ public void DeleteRole(RoleInfo role) public RoleInfo GetRole(int portalId, Func predicate) { - return GetRoles(portalId).Where(predicate).FirstOrDefault(); + return this.GetRoles(portalId).Where(predicate).FirstOrDefault(); } public RoleInfo GetRoleById(int portalId, int roleId) { - return GetRole(portalId, r => r.RoleID == roleId); + return this.GetRole(portalId, r => r.RoleID == roleId); } public RoleInfo GetRoleByName(int portalId, string roleName) { roleName = roleName.Trim(); - return GetRoles(portalId).SingleOrDefault(r => roleName.Equals(r.RoleName.Trim(), StringComparison.InvariantCultureIgnoreCase) && r.PortalID == portalId); + return this.GetRoles(portalId).SingleOrDefault(r => roleName.Equals(r.RoleName.Trim(), StringComparison.InvariantCultureIgnoreCase) && r.PortalID == portalId); } public IList GetRoles(int portalId) { - var cacheKey = String.Format(DataCache.RolesCacheKey, portalId); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.RolesCacheTimeOut, DataCache.RolesCachePriority), - c => provider.GetRoles(portalId).Cast().ToList()); + var cacheKey = string.Format(DataCache.RolesCacheKey, portalId); + return CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.RolesCacheTimeOut, DataCache.RolesCachePriority), + c => provider.GetRoles(portalId).Cast().ToList()); } public IList GetRoles(int portalId, Func predicate) { - return GetRoles(portalId).Where(predicate).ToList(); + return this.GetRoles(portalId).Where(predicate).ToList(); } public IList GetRolesBasicSearch(int portalId, int pageSize, string filterBy) @@ -318,23 +379,23 @@ public IDictionary GetRoleSettings(int roleId) } /// - /// Gets a User/Role + /// Gets a User/Role. /// - /// The Id of the Portal - /// The Id of the user - /// The Id of the Role - /// A UserRoleInfo object + /// The Id of the Portal. + /// The Id of the user. + /// The Id of the Role. + /// A UserRoleInfo object. public UserRoleInfo GetUserRole(int portalId, int userId, int roleId) { return provider.GetUserRole(portalId, userId, roleId); } /// - /// Gets a list of UserRoles for the user + /// Gets a list of UserRoles for the user. /// - /// A UserInfo object representaing the user + /// A UserInfo object representaing the user. /// Include private roles. - /// A list of UserRoleInfo objects + /// A list of UserRoleInfo objects. public IList GetUserRoles(UserInfo user, bool includePrivate) { return provider.GetUserRoles(user, includePrivate); @@ -352,7 +413,7 @@ public IList GetUsersByRole(int portalId, string roleName) void IRoleController.UpdateRole(RoleInfo role) { - UpdateRole(role, true); + this.UpdateRole(role, true); } public void UpdateRole(RoleInfo role, bool addToExistUsers) @@ -360,14 +421,14 @@ public void UpdateRole(RoleInfo role, bool addToExistUsers) Requires.NotNull("role", role); provider.UpdateRole(role); - AddMessage(role, EventLogController.EventLogType.ROLE_UPDATED); + this.AddMessage(role, EventLogController.EventLogType.ROLE_UPDATED); if (addToExistUsers) { - AutoAssignUsers(role); + this.AutoAssignUsers(role); } - ClearRoleCache(role.PortalID); + this.ClearRoleCache(role.PortalID); } public void UpdateRoleSettings(RoleInfo role, bool clearCache) @@ -376,34 +437,35 @@ public void UpdateRoleSettings(RoleInfo role, bool clearCache) if (clearCache) { - ClearRoleCache(role.PortalID); + this.ClearRoleCache(role.PortalID); } } public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus status, bool isOwner, bool cancel) { UserInfo user = UserController.GetUserById(portalId, userId); - UserRoleInfo userRole = GetUserRole(portalId, userId, roleId); + UserRoleInfo userRole = this.GetUserRole(portalId, userId, roleId); if (cancel) { if (userRole != null && userRole.ServiceFee > 0.0 && userRole.IsTrialUsed) { - //Expire Role so we retain trial used data + // Expire Role so we retain trial used data userRole.ExpiryDate = DateTime.Now.AddDays(-1); userRole.Status = status; userRole.IsOwner = isOwner; provider.UpdateUserRole(userRole); - EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_UPDATED); + EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_UPDATED); } else { - //Delete Role + // Delete Role DeleteUserRoleInternal(portalId, userId, roleId); - EventLogController.Instance.AddLog("UserId", - userId.ToString(CultureInfo.InvariantCulture), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.USER_ROLE_DELETED); + EventLogController.Instance.AddLog( + "UserId", + userId.ToString(CultureInfo.InvariantCulture), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.USER_ROLE_DELETED); } } else @@ -413,7 +475,7 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat DateTime EffectiveDate = Null.NullDate; bool IsTrialUsed = false; int Period = 0; - string Frequency = ""; + string Frequency = string.Empty; if (userRole != null) { UserRoleId = userRole.UserRoleID; @@ -421,6 +483,7 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat ExpiryDate = userRole.ExpiryDate; IsTrialUsed = userRole.IsTrialUsed; } + RoleInfo role = Instance.GetRole(portalId, r => r.RoleID == roleId); if (role != null) { @@ -435,14 +498,17 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat Frequency = role.BillingFrequency; } } + if (EffectiveDate < DateTime.Now) { EffectiveDate = Null.NullDate; } + if (ExpiryDate < DateTime.Now) { ExpiryDate = DateTime.Now; } + if (Period == Null.NullInteger) { ExpiryDate = Null.NullDate; @@ -471,133 +537,71 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat break; } } + if (UserRoleId != -1 && userRole != null) { userRole.ExpiryDate = ExpiryDate; userRole.Status = status; userRole.IsOwner = isOwner; provider.UpdateUserRole(userRole); - EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_UPDATED); + EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_UPDATED); } else { - AddUserRole(portalId, userId, roleId, status, isOwner, EffectiveDate, ExpiryDate); + this.AddUserRole(portalId, userId, roleId, status, isOwner, EffectiveDate, ExpiryDate); } } - //Remove the UserInfo from the Cache, as it has been modified + + // Remove the UserInfo from the Cache, as it has been modified DataCache.ClearUserCache(portalId, user.Username); Instance.ClearRoleCache(portalId); - } - - - #endregion - - #region Static Helper Methods - - /// ----------------------------------------------------------------------------- - /// - /// Adds a Role Group - /// - /// The RoleGroup to Add - /// The Id of the new role - /// ----------------------------------------------------------------------------- - public static int AddRoleGroup(RoleGroupInfo objRoleGroupInfo) - { - var id = provider.CreateRoleGroup(objRoleGroupInfo); - EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_CREATED); - return id; - } - - /// - /// Adds a User to a Role - /// - /// The user to assign - /// The role to add - /// The PortalSettings of the Portal - /// RoleStatus - /// The expiry Date of the Role membership - /// The expiry Date of the Role membership - /// A flag that indicates whether the user should be notified - /// A flag that indicates whether this user should be one of the group owners - public static void AddUserRole(UserInfo user, RoleInfo role, PortalSettings portalSettings, RoleStatus status, DateTime effectiveDate, DateTime expiryDate, bool notifyUser, bool isOwner) - { - var userRole = Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); - - //update assignment - Instance.AddUserRole(portalSettings.PortalId, user.UserID, role.RoleID, status, isOwner, effectiveDate, expiryDate); - - UserController.UpdateUser(portalSettings.PortalId, user); - if (userRole == null) - { - EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_CREATED); - - //send notification - if (notifyUser) - { - SendNotification(user, role, portalSettings, UserRoleActions.@add); - } - } - else - { - EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_UPDATED); - if (notifyUser) - { - RoleController.Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); - SendNotification(user, role, portalSettings, UserRoleActions.update); - } - } - - //Remove the UserInfo from the Cache, as it has been modified - DataCache.ClearUserCache(portalSettings.PortalId, user.Username); - } + } /// ----------------------------------------------------------------------------- /// - /// Determines if the specified user can be removed from a role + /// Determines if the specified user can be removed from a role. /// /// /// Roles such as "Registered Users" and "Administrators" can only - /// be removed in certain circumstances + /// be removed in certain circumstances. /// - /// A PortalSettings structure representing the current portal settings - /// The Id of the User that should be checked for role removability - /// The Id of the Role that should be checked for removability + /// A PortalSettings structure representing the current portal settings. + /// The Id of the User that should be checked for role removability. + /// The Id of the Role that should be checked for removability. /// /// ----------------------------------------------------------------------------- public static bool CanRemoveUserFromRole(PortalSettings PortalSettings, int UserId, int RoleId) { - //[DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb - //HACK: Duplicated in CanRemoveUserFromRole(PortalInfo, Integer, Integer) method below - //changes to this method should be reflected in the other method as well + // [DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb + // HACK: Duplicated in CanRemoveUserFromRole(PortalInfo, Integer, Integer) method below + // changes to this method should be reflected in the other method as well return !((PortalSettings.AdministratorId == UserId && PortalSettings.AdministratorRoleId == RoleId) || PortalSettings.RegisteredRoleId == RoleId); } /// ----------------------------------------------------------------------------- /// - /// Determines if the specified user can be removed from a role + /// Determines if the specified user can be removed from a role. /// /// /// Roles such as "Registered Users" and "Administrators" can only - /// be removed in certain circumstances + /// be removed in certain circumstances. /// - /// A PortalInfo structure representing the current portal - /// The Id of the User - /// The Id of the Role that should be checked for removability + /// A PortalInfo structure representing the current portal. + /// The Id of the User. + /// The Id of the Role that should be checked for removability. /// /// ----------------------------------------------------------------------------- public static bool CanRemoveUserFromRole(PortalInfo PortalInfo, int UserId, int RoleId) { - //[DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb - //HACK: Duplicated in CanRemoveUserFromRole(PortalSettings, Integer, Integer) method above - //changes to this method should be reflected in the other method as well - + // [DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb + // HACK: Duplicated in CanRemoveUserFromRole(PortalSettings, Integer, Integer) method above + // changes to this method should be reflected in the other method as well return !((PortalInfo.AdministratorId == UserId && PortalInfo.AdministratorRoleId == RoleId) || PortalInfo.RegisteredRoleId == RoleId); } /// ----------------------------------------------------------------------------- /// - /// Deletes a Role Group + /// Deletes a Role Group. /// /// ----------------------------------------------------------------------------- public static void DeleteRoleGroup(int PortalID, int RoleGroupId) @@ -607,23 +611,24 @@ public static void DeleteRoleGroup(int PortalID, int RoleGroupId) /// ----------------------------------------------------------------------------- /// - /// Deletes a Role Group + /// Deletes a Role Group. /// - /// The RoleGroup to Delete + /// The RoleGroup to Delete. /// ----------------------------------------------------------------------------- public static void DeleteRoleGroup(RoleGroupInfo objRoleGroupInfo) { provider.DeleteRoleGroup(objRoleGroupInfo); - EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_DELETED); + EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_DELETED); } /// - /// Removes a User from a Role + /// Removes a User from a Role. /// - /// The user to remove - /// The role to remove the use from - /// The PortalSettings of the Portal - /// A flag that indicates whether the user should be notified + /// The user to remove. + /// The role to remove the use from. + /// The PortalSettings of the Portal. + /// A flag that indicates whether the user should be notified. + /// public static bool DeleteUserRole(UserInfo objUser, RoleInfo role, PortalSettings portalSettings, bool notifyUser) { bool canDelete = DeleteUserRoleInternal(portalSettings.PortalId, objUser.UserID, role.RoleID); @@ -634,31 +639,16 @@ public static bool DeleteUserRole(UserInfo objUser, RoleInfo role, PortalSetting SendNotification(objUser, role, portalSettings, UserRoleActions.delete); } } + return canDelete; } - /// - /// Completely remove all a user's roles for a specific portal. This method is used when - /// anonymizing a user - /// - /// User for which all roles must be deleted. The PortalId property - /// is used to determine for which portal roles must be removed. - internal static void DeleteUserRoles(UserInfo user) - { - var ctrl = new RoleController(); - var userRoles = ctrl.GetUserRoles(user, true); - foreach (var ur in userRoles.Where(r => r.PortalID == user.PortalID)) - { - provider.RemoveUserFromRole(user.PortalID, user, ur); - } - } - /// ----------------------------------------------------------------------------- /// - /// Fetch a single RoleGroup + /// Fetch a single RoleGroup. /// - /// The Id of the Portal - /// Role Group ID + /// The Id of the Portal. + /// Role Group ID. /// /// /// ----------------------------------------------------------------------------- @@ -669,24 +659,40 @@ public static RoleGroupInfo GetRoleGroup(int portalId, int roleGroupId) /// ----------------------------------------------------------------------------- /// - /// Fetch a single RoleGroup by Name + /// Fetch a single RoleGroup by Name. /// - /// The Id of the Portal - /// Role Group Name + /// The Id of the Portal. + /// Role Group Name. /// /// /// ----------------------------------------------------------------------------- - public static RoleGroupInfo GetRoleGroupByName(int portalId, string roleGroupName) + public static RoleGroupInfo GetRoleGroupByName(int portalId, string roleGroupName) { return provider.GetRoleGroupByName(portalId, roleGroupName); } + /// + /// Completely remove all a user's roles for a specific portal. This method is used when + /// anonymizing a user. + /// + /// User for which all roles must be deleted. The PortalId property + /// is used to determine for which portal roles must be removed. + internal static void DeleteUserRoles(UserInfo user) + { + var ctrl = new RoleController(); + var userRoles = ctrl.GetUserRoles(user, true); + foreach (var ur in userRoles.Where(r => r.PortalID == user.PortalID)) + { + provider.RemoveUserFromRole(user.PortalID, user, ur); + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets an ArrayList of RoleGroups + /// Gets an ArrayList of RoleGroups. /// - /// The Id of the Portal - /// An ArrayList of RoleGroups + /// The Id of the Portal. + /// An ArrayList of RoleGroups. /// ----------------------------------------------------------------------------- public static ArrayList GetRoleGroups(int PortalID) { @@ -695,25 +701,25 @@ public static ArrayList GetRoleGroups(int PortalID) /// ----------------------------------------------------------------------------- /// - /// Serializes the role groups + /// Serializes the role groups. /// - /// An XmlWriter - /// The Id of the Portal + /// An XmlWriter. + /// The Id of the Portal. /// ----------------------------------------------------------------------------- public static void SerializeRoleGroups(XmlWriter writer, int portalID) { - //Serialize Role Groups + // Serialize Role Groups writer.WriteStartElement("rolegroups"); foreach (RoleGroupInfo objRoleGroup in GetRoleGroups(portalID)) { CBO.SerializeObject(objRoleGroup, writer); } - //Serialize Global Roles + // Serialize Global Roles var globalRoleGroup = new RoleGroupInfo(Null.NullInteger, portalID, true) { RoleGroupName = "GlobalRoles", - Description = "A dummy role group that represents the Global roles" + Description = "A dummy role group that represents the Global roles", }; CBO.SerializeObject(globalRoleGroup, writer); writer.WriteEndElement(); @@ -721,9 +727,9 @@ public static void SerializeRoleGroups(XmlWriter writer, int portalID) /// ----------------------------------------------------------------------------- /// - /// Updates a Role Group + /// Updates a Role Group. /// - /// The RoleGroup to Update + /// The RoleGroup to Update. /// ----------------------------------------------------------------------------- public static void UpdateRoleGroup(RoleGroupInfo roleGroup) { @@ -733,18 +739,15 @@ public static void UpdateRoleGroup(RoleGroupInfo roleGroup) public static void UpdateRoleGroup(RoleGroupInfo roleGroup, bool includeRoles) { provider.UpdateRoleGroup(roleGroup); - EventLogController.Instance.AddLog(roleGroup, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_UPDATED); + EventLogController.Instance.AddLog(roleGroup, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_UPDATED); if (includeRoles) { foreach (RoleInfo role in roleGroup.Roles.Values) { Instance.UpdateRole(role); - EventLogController.Instance.AddLog(role, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.ROLE_UPDATED); + EventLogController.Instance.AddLog(role, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.ROLE_UPDATED); } } - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Security/Roles/RoleEventArgs.cs b/DNN Platform/Library/Security/Roles/RoleEventArgs.cs index e014910bc2f..40d6200431a 100644 --- a/DNN Platform/Library/Security/Roles/RoleEventArgs.cs +++ b/DNN Platform/Library/Security/Roles/RoleEventArgs.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { + using System; + + using DotNetNuke.Entities.Users; + public class RoleEventArgs : EventArgs { public RoleInfo Role { get; set; } diff --git a/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs b/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs index 713d66c79c0..551db984134 100644 --- a/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs +++ b/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs @@ -1,204 +1,188 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security.Roles.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Roles { + using System; + using System.Collections.Generic; + using System.Data; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security.Roles.Internal; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Roles /// Class: RoleGroupInfo /// ----------------------------------------------------------------------------- /// - /// The RoleGroupInfo class provides the Entity Layer RoleGroup object + /// The RoleGroupInfo class provides the Entity Layer RoleGroup object. /// /// ----------------------------------------------------------------------------- [Serializable] public class RoleGroupInfo : BaseEntityInfo, IHydratable, IXmlSerializable - { - #region "Private Members" - + { private string _Description; private int _PortalID = Null.NullInteger; private int _RoleGroupID = Null.NullInteger; private string _RoleGroupName; - private Dictionary _Roles; - - #endregion - - #region "Constructors" - + private Dictionary _Roles; + public RoleGroupInfo() { } public RoleGroupInfo(int roleGroupID, int portalID, bool loadRoles) { - _PortalID = portalID; - _RoleGroupID = roleGroupID; + this._PortalID = portalID; + this._RoleGroupID = roleGroupID; if (loadRoles) { - GetRoles(); + this.GetRoles(); } - } - - #endregion - - #region "Public Properties" - + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the RoleGroup Id + /// Gets or sets and sets the RoleGroup Id. /// - /// An Integer representing the Id of the RoleGroup + /// An Integer representing the Id of the RoleGroup. /// ----------------------------------------------------------------------------- public int RoleGroupID { get { - return _RoleGroupID; + return this._RoleGroupID; } + set { - _RoleGroupID = value; + this._RoleGroupID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Portal Id for the RoleGroup + /// Gets or sets and sets the Portal Id for the RoleGroup. /// - /// An Integer representing the Id of the Portal + /// An Integer representing the Id of the Portal. /// ----------------------------------------------------------------------------- public int PortalID { get { - return _PortalID; + return this._PortalID; } + set { - _PortalID = value; + this._PortalID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the RoleGroup Name + /// Gets or sets and sets the RoleGroup Name. /// - /// A string representing the Name of the RoleGroup + /// A string representing the Name of the RoleGroup. /// ----------------------------------------------------------------------------- public string RoleGroupName { get { - return _RoleGroupName; + return this._RoleGroupName; } + set { - _RoleGroupName = value; + this._RoleGroupName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets an sets the Description of the RoleGroup + /// Gets or sets an sets the Description of the RoleGroup. /// - /// A string representing the description of the RoleGroup + /// A string representing the description of the RoleGroup. /// ----------------------------------------------------------------------------- public string Description { get { - return _Description; + return this._Description; } + set { - _Description = value; + this._Description = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Roles for this Role Group + /// Gets the Roles for this Role Group. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public Dictionary Roles { get { - if (_Roles == null && RoleGroupID > Null.NullInteger) + if (this._Roles == null && this.RoleGroupID > Null.NullInteger) { - GetRoles(); + this.GetRoles(); } - return _Roles; + + return this._Roles; } - } - - #endregion - - #region IHydratable Members + } /// ----------------------------------------------------------------------------- /// - /// Fills a RoleGroupInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - RoleGroupID = Null.SetNullInteger(dr["RoleGroupId"]); - PortalID = Null.SetNullInteger(dr["PortalID"]); - RoleGroupName = Null.SetNullString(dr["RoleGroupName"]); - Description = Null.SetNullString(dr["Description"]); - - //Fill base class fields - FillInternal(dr); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int KeyID { get { - return RoleGroupID; + return this.RoleGroupID; } + set { - RoleGroupID = value; + this.RoleGroupID = value; } - } - - #endregion - - #region IXmlSerializable Members - + } + /// ----------------------------------------------------------------------------- /// - /// Gets an XmlSchema for the RoleGroupInfo + /// Fills a RoleGroupInfo from a Data Reader. /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.RoleGroupID = Null.SetNullInteger(dr["RoleGroupId"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.RoleGroupName = Null.SetNullString(dr["RoleGroupName"]); + this.Description = Null.SetNullString(dr["Description"]); + + // Fill base class fields + this.FillInternal(dr); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets an XmlSchema for the RoleGroupInfo. + /// + /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() { @@ -207,9 +191,9 @@ public XmlSchema GetSchema() /// ----------------------------------------------------------------------------- /// - /// Reads a RoleGroupInfo from an XmlReader + /// Reads a RoleGroupInfo from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { @@ -219,10 +203,12 @@ public void ReadXml(XmlReader reader) { break; } + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } + if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name.ToLowerInvariant()) @@ -232,20 +218,22 @@ public void ReadXml(XmlReader reader) case "roles": if (!reader.IsEmptyElement) { - ReadRoles(reader); + this.ReadRoles(reader); } + break; case "rolegroupname": - RoleGroupName = reader.ReadElementContentAsString(); + this.RoleGroupName = reader.ReadElementContentAsString(); break; case "description": - Description = reader.ReadElementContentAsString(); + this.Description = reader.ReadElementContentAsString(); break; default: - if(reader.NodeType == XmlNodeType.Element && !String.IsNullOrEmpty(reader.Name)) + if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } + break; } } @@ -254,66 +242,65 @@ public void ReadXml(XmlReader reader) /// ----------------------------------------------------------------------------- /// - /// Writes a RoleGroupInfo to an XmlWriter + /// Writes a RoleGroupInfo to an XmlWriter. /// - /// The XmlWriter to use + /// The XmlWriter to use. /// ----------------------------------------------------------------------------- public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("rolegroup"); - //write out properties - writer.WriteElementString("rolegroupname", RoleGroupName); - writer.WriteElementString("description", Description); + // write out properties + writer.WriteElementString("rolegroupname", this.RoleGroupName); + writer.WriteElementString("description", this.Description); - //Write start of roles + // Write start of roles writer.WriteStartElement("roles"); - - //Iterate through roles - if (Roles != null) + + // Iterate through roles + if (this.Roles != null) { - foreach (RoleInfo role in Roles.Values) + foreach (RoleInfo role in this.Roles.Values) { role.WriteXml(writer); } } - - //Write end of Roles - writer.WriteEndElement(); - //Write end of main element + // Write end of Roles writer.WriteEndElement(); - } - - #endregion + // Write end of main element + writer.WriteEndElement(); + } + private void GetRoles() { - _Roles = new Dictionary(); - foreach (var role in RoleController.Instance.GetRoles(PortalID, r => r.RoleGroupID == RoleGroupID)) + this._Roles = new Dictionary(); + foreach (var role in RoleController.Instance.GetRoles(this.PortalID, r => r.RoleGroupID == this.RoleGroupID)) { - _Roles[role.RoleName] = role; + this._Roles[role.RoleName] = role; } } /// ----------------------------------------------------------------------------- /// - /// Reads a Roles from an XmlReader + /// Reads a Roles from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- private void ReadRoles(XmlReader reader) { reader.ReadStartElement("roles"); - _Roles = new Dictionary(); + this._Roles = new Dictionary(); do { reader.ReadStartElement("role"); var role = new RoleInfo(); role.ReadXml(reader); - _Roles.Add(role.RoleName, role); - } while (reader.ReadToNextSibling("role")); + this._Roles.Add(role.RoleName, role); + } + while (reader.ReadToNextSibling("role")); } } } diff --git a/DNN Platform/Library/Security/Roles/RoleInfo.cs b/DNN Platform/Library/Security/Roles/RoleInfo.cs index 7b9d35b60de..21d3fd8717d 100644 --- a/DNN Platform/Library/Security/Roles/RoleInfo.cs +++ b/DNN Platform/Library/Security/Roles/RoleInfo.cs @@ -1,39 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Tokens; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Roles { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Web; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Tokens; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Security.Roles /// Class: RoleInfo /// ----------------------------------------------------------------------------- /// - /// The RoleInfo class provides the Entity Layer Role object + /// The RoleInfo class provides the Entity Layer Role object. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -45,32 +40,31 @@ public class RoleInfo : BaseEntityInfo, IHydratable, IXmlSerializable, IProperty public RoleInfo() { - TrialFrequency = "N"; - BillingFrequency = "N"; - RoleID = Null.NullInteger; - IsSystemRole = false; - } - - #region Public Properties + this.TrialFrequency = "N"; + this.BillingFrequency = "N"; + this.RoleID = Null.NullInteger; + this.IsSystemRole = false; + } + /// - /// Gets whether this role is a system role + /// Gets or sets a value indicating whether gets whether this role is a system role. /// /// A boolean representing whether this is a system role such as Administrators, Registered Users etc. public bool IsSystemRole { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether users are automatically assigned to the role + /// Gets or sets a value indicating whether gets and sets whether users are automatically assigned to the role. /// - /// A boolean (True/False) + /// A boolean (True/False). /// ----------------------------------------------------------------------------- public bool AutoAssignment { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Billing Frequency for the role + /// Gets or sets and sets the Billing Frequency for the role. /// - /// A String representing the Billing Frequency of the Role
    + /// A String representing the Billing Frequency of the Role.
    ///
      /// N - None /// O - One time fee @@ -85,118 +79,119 @@ public RoleInfo() /// ----------------------------------------------------------------------------- /// - /// Gets and sets the length of the billing period + /// Gets or sets and sets the length of the billing period. /// - /// An integer representing the length of the billing period + /// An integer representing the length of the billing period. /// ----------------------------------------------------------------------------- public int BillingPeriod { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets an sets the Description of the Role + /// Gets or sets an sets the Description of the Role. /// - /// A string representing the description of the role + /// A string representing the description of the role. /// ----------------------------------------------------------------------------- public string Description { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Icon File for the role + /// Gets or sets and sets the Icon File for the role. /// - /// A string representing the Icon File for the role + /// A string representing the Icon File for the role. /// ----------------------------------------------------------------------------- public string IconFile { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the role is public + /// Gets or sets a value indicating whether gets and sets whether the role is public. /// - /// A boolean (True/False) + /// A boolean (True/False). /// ----------------------------------------------------------------------------- public bool IsPublic { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Portal Id for the Role + /// Gets or sets and sets the Portal Id for the Role. /// - /// An Integer representing the Id of the Portal + /// An Integer representing the Id of the Portal. /// ----------------------------------------------------------------------------- [XmlIgnore] public int PortalID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Role Id + /// Gets or sets and sets the Role Id. /// - /// An Integer representing the Id of the Role + /// An Integer representing the Id of the Role. /// ----------------------------------------------------------------------------- [XmlIgnore] public int RoleID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the RoleGroup Id + /// Gets or sets and sets the RoleGroup Id. /// - /// An Integer representing the Id of the RoleGroup + /// An Integer representing the Id of the RoleGroup. /// ----------------------------------------------------------------------------- [XmlIgnore] public int RoleGroupID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Role Name + /// Gets or sets and sets the Role Name. /// - /// A string representing the name of the role + /// A string representing the name of the role. /// ----------------------------------------------------------------------------- public string RoleName { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Role Type + /// Gets the Role Type. /// - /// A enum representing the type of the role + /// A enum representing the type of the role. /// ----------------------------------------------------------------------------- public RoleType RoleType { get { - if (!_RoleTypeSet) + if (!this._RoleTypeSet) { - GetRoleType(); - _RoleTypeSet = true; + this.GetRoleType(); + this._RoleTypeSet = true; } - return _RoleType; + + return this._RoleType; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the RSVP Code for the role + /// Gets or sets and sets the RSVP Code for the role. /// - /// A string representing the RSVP Code for the role + /// A string representing the RSVP Code for the role. /// ----------------------------------------------------------------------------- public string RSVPCode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the role is a security role and can be used in Permission + /// Gets or sets and sets whether the role is a security role and can be used in Permission /// Grids etc. /// - /// A SecurityMode enum + /// A SecurityMode enum. /// ----------------------------------------------------------------------------- public SecurityMode SecurityMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the fee for the role + /// Gets or sets and sets the fee for the role. /// - /// A single number representing the fee for the role + /// A single number representing the fee for the role. /// ----------------------------------------------------------------------------- public float ServiceFee { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the role settings + /// Gets the role settings. /// /// ----------------------------------------------------------------------------- [XmlIgnore] @@ -204,34 +199,34 @@ public Dictionary Settings { get { - return _settings ?? (_settings = (RoleID == Null.NullInteger) + return this._settings ?? (this._settings = (this.RoleID == Null.NullInteger) ? new Dictionary() - : RoleController.Instance.GetRoleSettings(RoleID) as + : RoleController.Instance.GetRoleSettings(this.RoleID) as Dictionary); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the status for the role + /// Gets or sets and sets the status for the role. /// - /// An enumerated value Pending, Disabled, Approved + /// An enumerated value Pending, Disabled, Approved. /// ----------------------------------------------------------------------------- public RoleStatus Status { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the trial fee for the role + /// Gets or sets and sets the trial fee for the role. /// - /// A single number representing the trial fee for the role + /// A single number representing the trial fee for the role. /// ----------------------------------------------------------------------------- public float TrialFee { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Trial Frequency for the role + /// Gets or sets and sets the Trial Frequency for the role. /// - /// A String representing the Trial Frequency of the Role
      + /// A String representing the Trial Frequency of the Role.
      ///
        /// N - None /// O - One time fee @@ -246,17 +241,17 @@ public Dictionary Settings /// ----------------------------------------------------------------------------- /// - /// Gets and sets the length of the trial period + /// Gets or sets and sets the length of the trial period. /// - /// An integer representing the length of the trial period + /// An integer representing the length of the trial period. /// ----------------------------------------------------------------------------- public int TrialPeriod { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the number of users in the role + /// Gets the number of users in the role. /// - /// An integer representing the number of users + /// An integer representing the number of users. /// ----------------------------------------------------------------------------- public int UserCount { get; private set; } @@ -266,151 +261,117 @@ public string PhotoURL { string photoURL = Globals.ApplicationPath + "/images/sample-group-profile.jpg"; - if ((IconFile != null)) + if (this.IconFile != null) { - if (!string.IsNullOrEmpty(IconFile)) + if (!string.IsNullOrEmpty(this.IconFile)) { IFileInfo fileInfo = - FileManager.Instance.GetFile(int.Parse(IconFile.Replace("FileID=", string.Empty))); - if ((fileInfo != null)) + FileManager.Instance.GetFile(int.Parse(this.IconFile.Replace("FileID=", string.Empty))); + if (fileInfo != null) { photoURL = FileManager.Instance.GetUrl(fileInfo); } } } + return photoURL; } - } - - #endregion + } - #region Private Methods - - private void GetRoleType() + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public virtual int KeyID { - var portal = PortalController.Instance.GetPortal(PortalID); - if (RoleID == portal.AdministratorRoleId) - { - _RoleType = RoleType.Administrator; - } - else if (RoleID == portal.RegisteredRoleId) - { - _RoleType = RoleType.RegisteredUser; - } - else if (RoleName == "Subscribers") - { - _RoleType = RoleType.Subscriber; - } - else if (RoleName == "Unverified Users") - { - _RoleType = RoleType.UnverifiedUser; - } + get { return this.RoleID; } + set { this.RoleID = value; } + } + + public CacheLevel Cacheability + { + get { return CacheLevel.fullyCacheable; } } - - #endregion - - #region IHydratable Members - + /// ----------------------------------------------------------------------------- /// - /// Fills a RoleInfo from a Data Reader + /// Fills a RoleInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- public virtual void Fill(IDataReader dr) { - RoleID = Null.SetNullInteger(dr["RoleId"]); - PortalID = Null.SetNullInteger(dr["PortalID"]); - RoleGroupID = Null.SetNullInteger(dr["RoleGroupId"]); - RoleName = Null.SetNullString(dr["RoleName"]); - Description = Null.SetNullString(dr["Description"]); - ServiceFee = Null.SetNullSingle(dr["ServiceFee"]); - BillingPeriod = Null.SetNullInteger(dr["BillingPeriod"]); - BillingFrequency = Null.SetNullString(dr["BillingFrequency"]); - TrialFee = Null.SetNullSingle(dr["TrialFee"]); - TrialPeriod = Null.SetNullInteger(dr["TrialPeriod"]); - TrialFrequency = Null.SetNullString(dr["TrialFrequency"]); - IsPublic = Null.SetNullBoolean(dr["IsPublic"]); - AutoAssignment = Null.SetNullBoolean(dr["AutoAssignment"]); - RSVPCode = Null.SetNullString(dr["RSVPCode"]); - IconFile = Null.SetNullString(dr["IconFile"]); - - //New properties may not be present if called before 6.2 Upgrade has been executed + this.RoleID = Null.SetNullInteger(dr["RoleId"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.RoleGroupID = Null.SetNullInteger(dr["RoleGroupId"]); + this.RoleName = Null.SetNullString(dr["RoleName"]); + this.Description = Null.SetNullString(dr["Description"]); + this.ServiceFee = Null.SetNullSingle(dr["ServiceFee"]); + this.BillingPeriod = Null.SetNullInteger(dr["BillingPeriod"]); + this.BillingFrequency = Null.SetNullString(dr["BillingFrequency"]); + this.TrialFee = Null.SetNullSingle(dr["TrialFee"]); + this.TrialPeriod = Null.SetNullInteger(dr["TrialPeriod"]); + this.TrialFrequency = Null.SetNullString(dr["TrialFrequency"]); + this.IsPublic = Null.SetNullBoolean(dr["IsPublic"]); + this.AutoAssignment = Null.SetNullBoolean(dr["AutoAssignment"]); + this.RSVPCode = Null.SetNullString(dr["RSVPCode"]); + this.IconFile = Null.SetNullString(dr["IconFile"]); + + // New properties may not be present if called before 6.2 Upgrade has been executed try { int mode = Null.SetNullInteger(dr["SecurityMode"]); switch (mode) { case 0: - SecurityMode = SecurityMode.SecurityRole; + this.SecurityMode = SecurityMode.SecurityRole; break; case 1: - SecurityMode = SecurityMode.SocialGroup; + this.SecurityMode = SecurityMode.SocialGroup; break; default: - SecurityMode = SecurityMode.Both; + this.SecurityMode = SecurityMode.Both; break; } - - + int status = Null.SetNullInteger(dr["Status"]); switch (status) { case -1: - Status = RoleStatus.Pending; + this.Status = RoleStatus.Pending; break; case 0: - Status = RoleStatus.Disabled; + this.Status = RoleStatus.Disabled; break; default: - Status = RoleStatus.Approved; + this.Status = RoleStatus.Approved; break; } - //check for values only relevant to UserRoles + + // check for values only relevant to UserRoles var schema = dr.GetSchemaTable(); if (schema != null) { if (schema.Select("ColumnName = 'UserCount'").Length > 0) { - UserCount = Null.SetNullInteger(dr["UserCount"]); + this.UserCount = Null.SetNullInteger(dr["UserCount"]); } + if (schema.Select("ColumnName = 'IsSystemRole'").Length > 0) { - IsSystemRole = Null.SetNullBoolean(dr["IsSystemRole"]); + this.IsSystemRole = Null.SetNullBoolean(dr["IsSystemRole"]); } } - - } catch (IndexOutOfRangeException) { - //do nothing + // do nothing } - - - //Fill base class fields - FillInternal(dr); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer - /// ----------------------------------------------------------------------------- - public virtual int KeyID - { - get { return RoleID; } - set { RoleID = value; } - } - - #endregion - - #region IPropertyAccess Members - - public CacheLevel Cacheability - { - get { return CacheLevel.fullyCacheable; } + + // Fill base class fields + this.FillInternal(dr); } public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, @@ -425,74 +386,93 @@ public string GetProperty(string propertyName, string format, CultureInfo format { OutputFormat = format; } + string propName = propertyName.ToLowerInvariant(); switch (propName) { case "roleid": - return PropertyAccess.FormatString(RoleID.ToString(), format); + return PropertyAccess.FormatString(this.RoleID.ToString(), format); case "groupid": - return PropertyAccess.FormatString(RoleID.ToString(), format); + return PropertyAccess.FormatString(this.RoleID.ToString(), format); case "status": - return PropertyAccess.FormatString(Status.ToString(), format); + return PropertyAccess.FormatString(this.Status.ToString(), format); case "groupname": - return PropertyAccess.FormatString(RoleName, format); + return PropertyAccess.FormatString(this.RoleName, format); case "rolename": - return PropertyAccess.FormatString(RoleName, format); + return PropertyAccess.FormatString(this.RoleName, format); case "groupdescription": - return PropertyAccess.FormatString(Description, format); + return PropertyAccess.FormatString(this.Description, format); case "description": - return PropertyAccess.FormatString(Description, format); + return PropertyAccess.FormatString(this.Description, format); case "usercount": - return PropertyAccess.FormatString(UserCount.ToString(), format); + return PropertyAccess.FormatString(this.UserCount.ToString(), format); case "street": - return PropertyAccess.FormatString(GetString("Street", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("Street", string.Empty), format); case "city": - return PropertyAccess.FormatString(GetString("City", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("City", string.Empty), format); case "region": - return PropertyAccess.FormatString(GetString("Region", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("Region", string.Empty), format); case "country": - return PropertyAccess.FormatString(GetString("Country", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("Country", string.Empty), format); case "postalcode": - return PropertyAccess.FormatString(GetString("PostalCode", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("PostalCode", string.Empty), format); case "website": - return PropertyAccess.FormatString(GetString("Website", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("Website", string.Empty), format); case "datecreated": - return PropertyAccess.FormatString(CreatedOnDate.ToString(), format); + return PropertyAccess.FormatString(this.CreatedOnDate.ToString(), format); case "photourl": - return PropertyAccess.FormatString(FormatUrl(PhotoURL), format); + return PropertyAccess.FormatString(this.FormatUrl(this.PhotoURL), format); case "stat_status": - return PropertyAccess.FormatString(GetString("stat_status", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("stat_status", string.Empty), format); case "stat_photo": - return PropertyAccess.FormatString(GetString("stat_photo", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("stat_photo", string.Empty), format); case "stat_file": - return PropertyAccess.FormatString(GetString("stat_file", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("stat_file", string.Empty), format); case "url": - return PropertyAccess.FormatString(FormatUrl(GetString("URL", string.Empty)), format); + return PropertyAccess.FormatString(this.FormatUrl(this.GetString("URL", string.Empty)), format); case "issystemrole": - return PropertyAccess.Boolean2LocalizedYesNo(IsSystemRole, formatProvider); + return PropertyAccess.Boolean2LocalizedYesNo(this.IsSystemRole, formatProvider); case "grouptype": - return IsPublic ? "Public.Text" : "Private.Text"; + return this.IsPublic ? "Public.Text" : "Private.Text"; case "groupcreatorname": - return PropertyAccess.FormatString(GetString("GroupCreatorName", string.Empty), format); + return PropertyAccess.FormatString(this.GetString("GroupCreatorName", string.Empty), format); default: - if (Settings.ContainsKey(propertyName)) + if (this.Settings.ContainsKey(propertyName)) { - return PropertyAccess.FormatString(GetString(propertyName, string.Empty), format); + return PropertyAccess.FormatString(this.GetString(propertyName, string.Empty), format); } propertyNotFound = true; return string.Empty; } - } - - #endregion - - #region IXmlSerializable Members - + } + + private void GetRoleType() + { + var portal = PortalController.Instance.GetPortal(this.PortalID); + if (this.RoleID == portal.AdministratorRoleId) + { + this._RoleType = RoleType.Administrator; + } + else if (this.RoleID == portal.RegisteredRoleId) + { + this._RoleType = RoleType.RegisteredUser; + } + else if (this.RoleName == "Subscribers") + { + this._RoleType = RoleType.Subscriber; + } + else if (this.RoleName == "Unverified Users") + { + this._RoleType = RoleType.UnverifiedUser; + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets an XmlSchema for the RoleInfo - /// + /// Gets an XmlSchema for the RoleInfo. + ///
    + /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() { @@ -501,14 +481,14 @@ public XmlSchema GetSchema() /// ----------------------------------------------------------------------------- /// - /// Reads a RoleInfo from an XmlReader + /// Reads a RoleInfo from an XmlReader. /// - /// The XmlReader to use + /// The XmlReader to use. /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { - //Set status to approved by default - Status = RoleStatus.Approved; + // Set status to approved by default + this.Status = RoleStatus.Approved; while (reader.Read()) { @@ -516,10 +496,12 @@ public void ReadXml(XmlReader reader) { break; } + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } + if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name.ToLowerInvariant()) @@ -527,114 +509,122 @@ public void ReadXml(XmlReader reader) case "role": break; case "rolename": - RoleName = reader.ReadElementContentAsString(); + this.RoleName = reader.ReadElementContentAsString(); break; case "description": - Description = reader.ReadElementContentAsString(); + this.Description = reader.ReadElementContentAsString(); break; case "billingfrequency": - BillingFrequency = reader.ReadElementContentAsString(); - if (string.IsNullOrEmpty(BillingFrequency)) + this.BillingFrequency = reader.ReadElementContentAsString(); + if (string.IsNullOrEmpty(this.BillingFrequency)) { - BillingFrequency = "N"; + this.BillingFrequency = "N"; } + break; case "billingperiod": - BillingPeriod = reader.ReadElementContentAsInt(); + this.BillingPeriod = reader.ReadElementContentAsInt(); break; case "servicefee": - ServiceFee = reader.ReadElementContentAsFloat(); - if (ServiceFee < 0) + this.ServiceFee = reader.ReadElementContentAsFloat(); + if (this.ServiceFee < 0) { - ServiceFee = 0; + this.ServiceFee = 0; } + break; case "trialfrequency": - TrialFrequency = reader.ReadElementContentAsString(); - if (string.IsNullOrEmpty(TrialFrequency)) + this.TrialFrequency = reader.ReadElementContentAsString(); + if (string.IsNullOrEmpty(this.TrialFrequency)) { - TrialFrequency = "N"; + this.TrialFrequency = "N"; } + break; case "trialperiod": - TrialPeriod = reader.ReadElementContentAsInt(); + this.TrialPeriod = reader.ReadElementContentAsInt(); break; case "trialfee": - TrialFee = reader.ReadElementContentAsFloat(); - if (TrialFee < 0) + this.TrialFee = reader.ReadElementContentAsFloat(); + if (this.TrialFee < 0) { - TrialFee = 0; + this.TrialFee = 0; } + break; case "ispublic": - IsPublic = reader.ReadElementContentAsBoolean(); + this.IsPublic = reader.ReadElementContentAsBoolean(); break; case "autoassignment": - AutoAssignment = reader.ReadElementContentAsBoolean(); + this.AutoAssignment = reader.ReadElementContentAsBoolean(); break; case "rsvpcode": - RSVPCode = reader.ReadElementContentAsString(); + this.RSVPCode = reader.ReadElementContentAsString(); break; case "iconfile": - IconFile = reader.ReadElementContentAsString(); + this.IconFile = reader.ReadElementContentAsString(); break; case "issystemrole": - IsSystemRole = reader.ReadElementContentAsBoolean(); + this.IsSystemRole = reader.ReadElementContentAsBoolean(); break; case "roletype": switch (reader.ReadElementContentAsString()) { case "adminrole": - _RoleType = RoleType.Administrator; + this._RoleType = RoleType.Administrator; break; case "registeredrole": - _RoleType = RoleType.RegisteredUser; + this._RoleType = RoleType.RegisteredUser; break; case "subscriberrole": - _RoleType = RoleType.Subscriber; + this._RoleType = RoleType.Subscriber; break; case "unverifiedrole": - _RoleType = RoleType.UnverifiedUser; + this._RoleType = RoleType.UnverifiedUser; break; default: - _RoleType = RoleType.None; + this._RoleType = RoleType.None; break; } - _RoleTypeSet = true; + + this._RoleTypeSet = true; break; case "securitymode": switch (reader.ReadElementContentAsString()) { case "securityrole": - SecurityMode = SecurityMode.SecurityRole; + this.SecurityMode = SecurityMode.SecurityRole; break; case "socialgroup": - SecurityMode = SecurityMode.SocialGroup; + this.SecurityMode = SecurityMode.SocialGroup; break; case "both": - SecurityMode = SecurityMode.Both; + this.SecurityMode = SecurityMode.Both; break; } + break; case "status": switch (reader.ReadElementContentAsString()) { case "pending": - Status = RoleStatus.Pending; + this.Status = RoleStatus.Pending; break; case "disabled": - Status = RoleStatus.Disabled; + this.Status = RoleStatus.Disabled; break; default: - Status = RoleStatus.Approved; + this.Status = RoleStatus.Approved; break; } + break; default: - if(reader.NodeType == XmlNodeType.Element && !String.IsNullOrEmpty(reader.Name)) + if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } + break; } } @@ -643,30 +633,30 @@ public void ReadXml(XmlReader reader) /// ----------------------------------------------------------------------------- /// - /// Writes a RoleInfo to an XmlWriter + /// Writes a RoleInfo to an XmlWriter. /// - /// The XmlWriter to use + /// The XmlWriter to use. /// ----------------------------------------------------------------------------- public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("role"); - //write out properties - writer.WriteElementString("rolename", RoleName); - writer.WriteElementString("description", Description); - writer.WriteElementString("billingfrequency", BillingFrequency); - writer.WriteElementString("billingperiod", BillingPeriod.ToString(CultureInfo.InvariantCulture)); - writer.WriteElementString("servicefee", ServiceFee.ToString(CultureInfo.InvariantCulture)); - writer.WriteElementString("trialfrequency", TrialFrequency); - writer.WriteElementString("trialperiod", TrialPeriod.ToString(CultureInfo.InvariantCulture)); - writer.WriteElementString("trialfee", TrialFee.ToString(CultureInfo.InvariantCulture)); - writer.WriteElementString("ispublic", IsPublic.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); - writer.WriteElementString("autoassignment", AutoAssignment.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); - writer.WriteElementString("rsvpcode", RSVPCode); - writer.WriteElementString("iconfile", IconFile); - writer.WriteElementString("issystemrole", IsSystemRole.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); - switch (RoleType) + // write out properties + writer.WriteElementString("rolename", this.RoleName); + writer.WriteElementString("description", this.Description); + writer.WriteElementString("billingfrequency", this.BillingFrequency); + writer.WriteElementString("billingperiod", this.BillingPeriod.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("servicefee", this.ServiceFee.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("trialfrequency", this.TrialFrequency); + writer.WriteElementString("trialperiod", this.TrialPeriod.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("trialfee", this.TrialFee.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("ispublic", this.IsPublic.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); + writer.WriteElementString("autoassignment", this.AutoAssignment.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); + writer.WriteElementString("rsvpcode", this.RSVPCode); + writer.WriteElementString("iconfile", this.IconFile); + writer.WriteElementString("issystemrole", this.IsSystemRole.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); + switch (this.RoleType) { case RoleType.Administrator: writer.WriteElementString("roletype", "adminrole"); @@ -685,7 +675,7 @@ public void WriteXml(XmlWriter writer) break; } - switch (SecurityMode) + switch (this.SecurityMode) { case SecurityMode.SecurityRole: writer.WriteElementString("securitymode", "securityrole"); @@ -697,7 +687,8 @@ public void WriteXml(XmlWriter writer) writer.WriteElementString("securitymode", "both"); break; } - switch (Status) + + switch (this.Status) { case RoleStatus.Pending: writer.WriteElementString("status", "pending"); @@ -710,21 +701,20 @@ public void WriteXml(XmlWriter writer) break; } - //Write end of main element + // Write end of main element writer.WriteEndElement(); - } - - #endregion - + } + private string GetString(string keyName, string defaultValue) { - if (Settings == null) + if (this.Settings == null) { return defaultValue; } - if (Settings.ContainsKey(keyName)) + + if (this.Settings.ContainsKey(keyName)) { - return Settings[keyName]; + return this.Settings[keyName]; } return defaultValue; @@ -732,11 +722,12 @@ private string GetString(string keyName, string defaultValue) private string FormatUrl(string url) { - if (url.StartsWith("/") && HttpContext.Current != null) + if (url.StartsWith("/") && HttpContext.Current != null) { - //server absolute path + // server absolute path return Globals.AddHTTP(HttpContext.Current.Request.Url.Host) + url; } + return url; } } diff --git a/DNN Platform/Library/Security/Roles/RoleProvider.cs b/DNN Platform/Library/Security/Roles/RoleProvider.cs index fad2162e114..00aa1d7ded3 100644 --- a/DNN Platform/Library/Security/Roles/RoleProvider.cs +++ b/DNN Platform/Library/Security/Roles/RoleProvider.cs @@ -1,36 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Security.Roles { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles.Internal; + public abstract class RoleProvider - { - #region Shared/Static Methods - - //return the provider + { + // return the provider public static RoleProvider Instance() { return ComponentFactory.GetComponent(); - } - - #endregion - - #region Role Methods - + } + public virtual bool CreateRole(RoleInfo role) { throw new NotImplementedException(); @@ -38,7 +27,7 @@ public virtual bool CreateRole(RoleInfo role) public virtual void DeleteRole(RoleInfo role) { - throw new NotImplementedException(); + throw new NotImplementedException(); } public abstract ArrayList GetRoles(int portalId); @@ -46,22 +35,17 @@ public virtual void DeleteRole(RoleInfo role) public abstract IList GetRolesBasicSearch(int portalID, int pageSize, string filterBy); public virtual IDictionary GetRoleSettings(int roleId) - { - return new Dictionary(); + { + return new Dictionary(); } public abstract void UpdateRole(RoleInfo role); public virtual void UpdateRoleSettings(RoleInfo role) { - - } - - #endregion - - #region RoleGroup Methods - - //Role Groups + } + + // Role Groups public abstract int CreateRoleGroup(RoleGroupInfo roleGroup); public abstract void DeleteRoleGroup(RoleGroupInfo roleGroup); @@ -70,12 +54,8 @@ public virtual void UpdateRoleSettings(RoleInfo role) public abstract ArrayList GetRoleGroups(int portalId); - public abstract void UpdateRoleGroup(RoleGroupInfo roleGroup); - - #endregion - - #region UserRole Methods - + public abstract void UpdateRoleGroup(RoleGroupInfo roleGroup); + public abstract bool AddUserToRole(int portalId, UserInfo user, UserRoleInfo userRole); public abstract UserRoleInfo GetUserRole(int PortalId, int UserId, int RoleId); @@ -86,10 +66,8 @@ public virtual void UpdateRoleSettings(RoleInfo role) public abstract void RemoveUserFromRole(int portalId, UserInfo user, UserRoleInfo userRole); - public abstract void UpdateUserRole(UserRoleInfo userRole); - - #endregion - + public abstract void UpdateUserRole(UserRoleInfo userRole); + public virtual RoleGroupInfo GetRoleGroupByName(int PortalID, string RoleGroupName) { return null; @@ -97,7 +75,7 @@ public virtual RoleGroupInfo GetRoleGroupByName(int PortalID, string RoleGroupNa public virtual IList GetUserRoles(UserInfo user, bool includePrivate) { - throw new NotImplementedException(); + throw new NotImplementedException(); } } } diff --git a/DNN Platform/Library/Security/Roles/RoleStatus.cs b/DNN Platform/Library/Security/Roles/RoleStatus.cs index f6535de021d..bb0afd89b44 100644 --- a/DNN Platform/Library/Security/Roles/RoleStatus.cs +++ b/DNN Platform/Library/Security/Roles/RoleStatus.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { + using System; + public enum RoleStatus { Pending = -1, Disabled = 0, - Approved = 1 + Approved = 1, } } diff --git a/DNN Platform/Library/Security/Roles/RoleType.cs b/DNN Platform/Library/Security/Roles/RoleType.cs index 658cd748fce..9b54f5f8f1e 100644 --- a/DNN Platform/Library/Security/Roles/RoleType.cs +++ b/DNN Platform/Library/Security/Roles/RoleType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { public enum RoleType @@ -10,6 +10,6 @@ public enum RoleType Subscriber, RegisteredUser, None, - UnverifiedUser + UnverifiedUser, } } diff --git a/DNN Platform/Library/Security/Roles/SecurityMode.cs b/DNN Platform/Library/Security/Roles/SecurityMode.cs index 50f97d7cfd1..4c2e7483ef3 100644 --- a/DNN Platform/Library/Security/Roles/SecurityMode.cs +++ b/DNN Platform/Library/Security/Roles/SecurityMode.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Roles { + using System; + public enum SecurityMode { SecurityRole = 0, SocialGroup = 1, - Both = 2 + Both = 2, } } diff --git a/DNN Platform/Library/Security/SecurityAccessLevel.cs b/DNN Platform/Library/Security/SecurityAccessLevel.cs index 00d9ae58676..0dffd4cc0fd 100644 --- a/DNN Platform/Library/Security/SecurityAccessLevel.cs +++ b/DNN Platform/Library/Security/SecurityAccessLevel.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security { - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// /// The SecurityAccessLevel enum is used to determine which level of access rights - /// to assign to a specific module or module action. + /// to assign to a specific module or module action. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public enum SecurityAccessLevel { ControlPanel = -3, @@ -19,6 +19,6 @@ public enum SecurityAccessLevel Edit = 1, Admin = 2, Host = 3, - ViewPermissions = 4 + ViewPermissions = 4, } } diff --git a/DNN Platform/Library/Services/Analytics/AnalyticsEngineBase.cs b/DNN Platform/Library/Services/Analytics/AnalyticsEngineBase.cs index 6c366727dbf..84d02ace9a2 100644 --- a/DNN Platform/Library/Services/Analytics/AnalyticsEngineBase.cs +++ b/DNN Platform/Library/Services/Analytics/AnalyticsEngineBase.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Analytics.Config; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics { + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Analytics.Config; + using DotNetNuke.Services.Tokens; + public abstract class AnalyticsEngineBase { public abstract string EngineName { get; } @@ -23,17 +18,17 @@ public string ReplaceTokens(string s) var tokenizer = new TokenReplace(); tokenizer.AccessingUser = UserController.Instance.GetCurrentUserInfo(); tokenizer.DebugMessages = false; - return (tokenizer.ReplaceEnvironmentTokens(s)); + return tokenizer.ReplaceEnvironmentTokens(s); } public AnalyticsConfiguration GetConfig() { - return AnalyticsConfiguration.GetConfig(EngineName); + return AnalyticsConfiguration.GetConfig(this.EngineName); } public virtual string RenderCustomScript(AnalyticsConfiguration config) { - return ""; + return string.Empty; } } } diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs index d08ca922c7b..daddd81785a 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs @@ -1,47 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Xml.Serialization; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics.Config { - [Serializable, XmlRoot("AnalyticsConfig")] + using System; + using System.Collections; + using System.IO; + using System.Xml.Serialization; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Log.EventLog; + + [Serializable] + [XmlRoot("AnalyticsConfig")] public class AnalyticsConfiguration { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (AnalyticsConfiguration)); - #region "Private Members" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AnalyticsConfiguration)); private AnalyticsRuleCollection _rules; - private AnalyticsSettingCollection _settings; - - #endregion - - #region "Public Properties" - + private AnalyticsSettingCollection _settings; + public AnalyticsSettingCollection Settings { get { - return _settings; + return this._settings; } + set { - _settings = value; + this._settings = value; } } @@ -49,18 +40,15 @@ public AnalyticsRuleCollection Rules { get { - return _rules; + return this._rules; } + set { - _rules = value; + this._rules = value; } - } - - #endregion - - #region "Shared Methods" - + } + public static AnalyticsConfiguration GetConfig(string analyticsEngineName) { string cacheKey = analyticsEngineName + "." + PortalSettings.Current.PortalId; @@ -70,11 +58,11 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) Config.Settings = new AnalyticsSettingCollection(); FileStream fileReader = null; - string filePath = ""; + string filePath = string.Empty; try { - Config = (AnalyticsConfiguration) DataCache.GetCache(cacheKey); - if ((Config == null)) + Config = (AnalyticsConfiguration)DataCache.GetCache(cacheKey); + if (Config == null) { filePath = PortalSettings.Current.HomeDirectoryMapPath + "\\" + analyticsEngineName + ".config"; @@ -82,8 +70,8 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) { return null; } - - //Create a FileStream for the Config file + + // Create a FileStream for the Config file fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); var doc = new XPathDocument(fileReader); @@ -99,6 +87,7 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) setting.SettingValue = nav.SelectSingleNode("SettingValue").Value; Config.Settings.Add(setting); } + foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsConfig/Rules/AnalyticsRule")) { var rule = new AnalyticsRule(); @@ -110,19 +99,21 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) { rule.Value = valueNode.Value; } + Config.Rules.Add(rule); } + if (File.Exists(filePath)) { - //Set back into Cache + // Set back into Cache DataCache.SetCache(cacheKey, Config, new DNNCacheDependency(filePath)); } } } catch (Exception ex) { - //log it - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString()}; + // log it + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() }; log.AddProperty("Analytics.AnalyticsConfiguration", "GetConfig Failed"); log.AddProperty("FilePath", filePath); log.AddProperty("ExceptionMessage", ex.Message); @@ -133,10 +124,11 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) { if (fileReader != null) { - //Close the Reader + // Close the Reader fileReader.Close(); } } + return Config; } @@ -145,30 +137,30 @@ public static void SaveConfig(string analyticsEngineName, AnalyticsConfiguration string cacheKey = analyticsEngineName + "." + PortalSettings.Current.PortalId; if (config.Settings != null) { - //Create a new Xml Serializer - var ser = new XmlSerializer(typeof (AnalyticsConfiguration)); - string filePath = ""; + // Create a new Xml Serializer + var ser = new XmlSerializer(typeof(AnalyticsConfiguration)); + string filePath = string.Empty; - //Create a FileStream for the Config file + // Create a FileStream for the Config file filePath = PortalSettings.Current.HomeDirectoryMapPath + "\\" + analyticsEngineName + ".config"; if (File.Exists(filePath)) { File.SetAttributes(filePath, FileAttributes.Normal); } + using (var fileWriter = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write)) using (var writer = new StreamWriter(fileWriter)) { - //Serialize the AnalyticsConfiguration + // Serialize the AnalyticsConfiguration ser.Serialize(writer, config); - //Close the Writers + // Close the Writers writer.Close(); fileWriter.Close(); } + DataCache.SetCache(cacheKey, config, new DNNCacheDependency(filePath)); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs index 346c32114fc..93f2b77a263 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics.Config { + using System; + [Serializable] public class AnalyticsRule { @@ -21,11 +16,12 @@ public int RoleId { get { - return _roleId; + return this._roleId; } + set { - _roleId = value; + this._roleId = value; } } @@ -33,11 +29,12 @@ public int TabId { get { - return _tabId; + return this._tabId; } + set { - _tabId = value; + this._tabId = value; } } @@ -45,11 +42,12 @@ public string Label { get { - return _label; + return this._label; } + set { - _label = value; + this._label = value; } } diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs index 8a572899dce..036bb95adba 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics.Config { + using System; + using System.Collections; + [Serializable] public class AnalyticsRuleCollection : CollectionBase { @@ -18,17 +13,18 @@ public virtual AnalyticsRule this[int index] { get { - return (AnalyticsRule) base.List[index]; + return (AnalyticsRule)this.List[index]; } + set { - base.List[index] = value; + this.List[index] = value; } } public void Add(AnalyticsRule r) { - InnerList.Add(r); + this.InnerList.Add(r); } } } diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs index 20ebf116eaa..80f466cded3 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics.Config { + using System; + [Serializable] public class AnalyticsSetting { @@ -20,11 +15,12 @@ public string SettingName { get { - return _settingName; + return this._settingName; } + set { - _settingName = value; + this._settingName = value; } } @@ -32,11 +28,12 @@ public string SettingValue { get { - return _settingValue; + return this._settingValue; } + set { - _settingValue = value; + this._settingValue = value; } } } diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs index e86d71e22f0..58f91d6506e 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics.Config { + using System; + using System.Collections; + [Serializable] public class AnalyticsSettingCollection : CollectionBase { @@ -18,17 +13,18 @@ public virtual AnalyticsSetting this[int index] { get { - return (AnalyticsSetting) base.List[index]; + return (AnalyticsSetting)this.List[index]; } + set { - base.List[index] = value; + this.List[index] = value; } } public void Add(AnalyticsSetting r) { - InnerList.Add(r); + this.InnerList.Add(r); } } } diff --git a/DNN Platform/Library/Services/Analytics/GenericAnalyticsEngine.cs b/DNN Platform/Library/Services/Analytics/GenericAnalyticsEngine.cs index cf220b3286e..b8bdf64b55d 100644 --- a/DNN Platform/Library/Services/Analytics/GenericAnalyticsEngine.cs +++ b/DNN Platform/Library/Services/Analytics/GenericAnalyticsEngine.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Analytics { public class GenericAnalyticsEngine : AnalyticsEngineBase @@ -16,7 +16,7 @@ public override string EngineName public override string RenderScript(string scriptTemplate) { - return ReplaceTokens(scriptTemplate); + return this.ReplaceTokens(scriptTemplate); } } } diff --git a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs index ed8319235a9..acf8c7b498f 100644 --- a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs +++ b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs @@ -1,37 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; - -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Log.EventLog; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Analytics /// Module: GoogleAnalytics /// ----------------------------------------------------------------------------- /// - /// Controller class definition for GoogleAnalytics which handles upgrades + /// Controller class definition for GoogleAnalytics which handles upgrades. /// /// /// /// ----------------------------------------------------------------------------- public class GoogleAnalyticsController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (GoogleAnalyticsController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(GoogleAnalyticsController)); + /// ----------------------------------------------------------------------------- /// /// Handles module upgrades includes a new Google Analytics Asychronous script. @@ -43,37 +39,38 @@ public class GoogleAnalyticsController public void UpgradeModule(string Version) { // MD5 Hash value of the old synchronous script config file (from previous module versions) - string[] TRADITIONAL_FILEHASHES = {"aRUf9NsElvrpiASJHHlmZg==", "+R2k5mvFvVhWsCm4WinyAA=="}; + string[] TRADITIONAL_FILEHASHES = { "aRUf9NsElvrpiASJHHlmZg==", "+R2k5mvFvVhWsCm4WinyAA==" }; switch (Version) { case "05.06.00": - //previous module versions - using (StreamReader fileReader = GetConfigFile()) + // previous module versions + using (StreamReader fileReader = this.GetConfigFile()) { if (fileReader != null) { var fileEncoding = new ASCIIEncoding(); using (var md5 = new MD5CryptoServiceProvider()) { - string currFileHashValue = ""; + string currFileHashValue = string.Empty; - //calculate md5 hash of existing file + // calculate md5 hash of existing file currFileHashValue = Convert.ToBase64String(md5.ComputeHash(fileEncoding.GetBytes(fileReader.ReadToEnd()))); fileReader.Close(); - IEnumerable result = (from h in TRADITIONAL_FILEHASHES where h == currFileHashValue select h); + IEnumerable result = from h in TRADITIONAL_FILEHASHES where h == currFileHashValue select h; - //compare md5 hash + // compare md5 hash if (result.Any()) { - //Copy new config file from \Config - //True causes .config to be overwritten + // Copy new config file from \Config + // True causes .config to be overwritten Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.SiteAnalytics, true); } } } } + break; } } @@ -89,7 +86,7 @@ public void UpgradeModule(string Version) private StreamReader GetConfigFile() { StreamReader fileReader = null; - string filePath = ""; + string filePath = string.Empty; try { filePath = Globals.ApplicationMapPath + "\\SiteAnalytics.config"; @@ -101,8 +98,8 @@ private StreamReader GetConfigFile() } catch (Exception ex) { - //log it - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + // log it + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("GoogleAnalytics.UpgradeModule", "GetConfigFile Failed"); log.AddProperty("FilePath", filePath); log.AddProperty("ExceptionMessage", ex.Message); @@ -111,8 +108,8 @@ private StreamReader GetConfigFile() { fileReader.Close(); } + Logger.Error(ex); - } return fileReader; diff --git a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs index 348d7716378..04d43895743 100644 --- a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs +++ b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Analytics.Config; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Analytics { + using System; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Analytics.Config; + public class GoogleAnalyticsEngine : AnalyticsEngineBase { public override string EngineName @@ -25,15 +21,15 @@ public override string EngineName public override string RenderScript(string scriptTemplate) { - AnalyticsConfiguration config = GetConfig(); + AnalyticsConfiguration config = this.GetConfig(); if (config == null) { - return ""; + return string.Empty; } - var trackingId = ""; - var urlParameter = ""; + var trackingId = string.Empty; + var urlParameter = string.Empty; var trackForAdmin = true; foreach (AnalyticsSetting setting in config.Settings) @@ -51,36 +47,37 @@ public override string RenderScript(string scriptTemplate) { trackForAdmin = true; } + break; } } - if (String.IsNullOrEmpty(trackingId)) + if (string.IsNullOrEmpty(trackingId)) { - return ""; + return string.Empty; } - //check whether setting to not track traffic if current user is host user or website administrator. + // check whether setting to not track traffic if current user is host user or website administrator. if (!trackForAdmin && (UserController.Instance.GetCurrentUserInfo().IsSuperUser || (PortalSettings.Current != null && UserController.Instance.GetCurrentUserInfo().IsInRole(PortalSettings.Current.AdministratorRoleName)))) { - return ""; + return string.Empty; } scriptTemplate = scriptTemplate.Replace("[TRACKING_ID]", trackingId); - if ((!String.IsNullOrEmpty(urlParameter))) + if (!string.IsNullOrEmpty(urlParameter)) { scriptTemplate = scriptTemplate.Replace("[PAGE_URL]", urlParameter); } else { - scriptTemplate = scriptTemplate.Replace("[PAGE_URL]", ""); + scriptTemplate = scriptTemplate.Replace("[PAGE_URL]", string.Empty); } - scriptTemplate = scriptTemplate.Replace("[CUSTOM_SCRIPT]", RenderCustomScript(config)); + scriptTemplate = scriptTemplate.Replace("[CUSTOM_SCRIPT]", this.RenderCustomScript(config)); return scriptTemplate; } @@ -96,20 +93,20 @@ public override string RenderCustomScript(AnalyticsConfiguration config) { switch (setting.SettingName.ToLowerInvariant()) { - case "anonymizeip": - { - bool.TryParse(setting.SettingValue, out anonymize); - break; - } - case "trackinguser": - { - bool.TryParse(setting.SettingValue, out trackingUserId); - break; - } + case "anonymizeip": + { + bool.TryParse(setting.SettingValue, out anonymize); + break; + } + + case "trackinguser": + { + bool.TryParse(setting.SettingValue, out trackingUserId); + break; + } } } - - + var customScripts = new System.Text.StringBuilder(); if (anonymize || PortalSettings.Current.DataConsentActive) @@ -131,6 +128,5 @@ public override string RenderCustomScript(AnalyticsConfiguration config) return string.Empty; } } - } } diff --git a/DNN Platform/Library/Services/Assets/AssetManager.cs b/DNN Platform/Library/Services/Assets/AssetManager.cs index aa8830e07ba..3ecb6251fbb 100644 --- a/DNN Platform/Library/Services/Assets/AssetManager.cs +++ b/DNN Platform/Library/Services/Assets/AssetManager.cs @@ -1,28 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Linq.Expressions; -using System.Text.RegularExpressions; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Assets { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Linq.Expressions; + using System.Text.RegularExpressions; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem; + + using Localization = DotNetNuke.Services.Localization.Localization; + public class AssetManager : ComponentBase, IAssetManager - { - #region Default exception messages - + { private const string UserHasNoPermissionToBrowseFolderDefaultMessage = "The user has no permission to browse this folder"; private const string FileNameInvalidDefaultMessage = "The specified name ({0}) is not valid"; private const string FolderFileNameIsReservedDefaultMessage = "The name is reserved. Try a different name"; @@ -33,19 +33,57 @@ public class AssetManager : ComponentBase, IAssetMa private const string InvalidMappedPathDefaultMessage = "The Mapped Path is invalid"; private const string FolderAlreadyExistsDefaultMessage = "Cannot create folder ({0}), folder already exists in this location"; private const string FolderFileNameHasInvalidcharactersDefaultMessage = "The name contains invalid character(s). Please specify a name without {0}"; - private const string DefaultMessageDefaultMessage = "The folder does not exist"; - - #endregion - + private const string DefaultMessageDefaultMessage = "The folder does not exist"; private static readonly Regex MappedPathRegex = new Regex(@"^(?!\s*[\\/]).*$", RegexOptions.Compiled); + public static IOrderedQueryable ApplyOrder(IQueryable source, string propertyName, bool asc) + { + var methodName = asc ? "OrderBy" : "OrderByDescending"; + var arg = Expression.Parameter(typeof(T), "x"); + + // Use reflection to mirror LINQ + var property = typeof(T).GetProperty(propertyName); + + // If property is undefined returns the original source + if (property == null) + { + return (IOrderedQueryable)source; + } + + Expression expr = Expression.Property(arg, property); + + var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), property.PropertyType); + var lambda = Expression.Lambda(delegateType, expr, arg); + + var result = typeof(Queryable).GetMethods().Single( + method => method.Name == methodName + && method.IsGenericMethodDefinition + && method.GetGenericArguments().Length == 2 + && method.GetParameters().Length == 2) + .MakeGenericMethod(typeof(T), property.PropertyType) + .Invoke(null, new object[] { source, lambda }); + return (IOrderedQueryable)result; + } + + public static bool HasPermission(IFolderInfo folder, string permissionKey) + { + var hasPermision = PortalSettings.Current.UserInfo.IsSuperUser; + + if (!hasPermision && folder != null) + { + hasPermision = FolderPermissionController.HasFolderPermission(folder.FolderPermissions, permissionKey); + } + + return hasPermision; + } + public ContentPage GetFolderContent(int folderId, int startIndex, int numItems, string sortExpression = null, SubfolderFilter subfolderFilter = SubfolderFilter.IncludeSubfoldersFolderStructure) { - var folder = GetFolderInfo(folderId); + var folder = this.GetFolderInfo(folderId); if (!FolderPermissionController.CanBrowseFolder((FolderInfo)folder)) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("UserHasNoPermissionToBrowseFolder", UserHasNoPermissionToBrowseFolderDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("UserHasNoPermissionToBrowseFolder", UserHasNoPermissionToBrowseFolderDefaultMessage)); } var sortProperties = SortProperties.Parse(sortExpression); @@ -58,11 +96,11 @@ public ContentPage GetFolderContent(int folderId, int startIndex, int numItems, } else { - folders = GetFolders(folder, sortProperties.Column == "ItemName" ? "FolderName" : sortProperties.Column, sortProperties.Ascending).ToList(); + folders = this.GetFolders(folder, sortProperties.Column == "ItemName" ? "FolderName" : sortProperties.Column, sortProperties.Ascending).ToList(); } var recursive = subfolderFilter == SubfolderFilter.IncludeSubfoldersFilesOnly; - var files = GetFiles(folder, sortProperties, startIndex, recursive).ToList(); + var files = this.GetFiles(folder, sortProperties, startIndex, recursive).ToList(); IEnumerable content; if (startIndex + numItems <= folders.Count()) @@ -84,14 +122,14 @@ public ContentPage GetFolderContent(int folderId, int startIndex, int numItems, { Folder = folder, Items = content.ToList(), - TotalCount = folders.Count() + files.Count() + TotalCount = folders.Count() + files.Count(), }; } public ContentPage SearchFolderContent(int folderId, string pattern, int startIndex, int numItems, string sortExpression = null, SubfolderFilter subfolderFilter = SubfolderFilter.IncludeSubfoldersFolderStructure) { var recursive = subfolderFilter != SubfolderFilter.ExcludeSubfolders; - var folder = GetFolderInfo(folderId); + var folder = this.GetFolderInfo(folderId); var files = FolderManager.Instance.SearchFiles(folder, pattern, recursive); var sortProperties = SortProperties.Parse(sortExpression); @@ -103,7 +141,7 @@ public ContentPage SearchFolderContent(int folderId, string pattern, int startIn { Folder = folder, Items = content.ToList(), - TotalCount = sortedFiles.Count() + TotalCount = sortedFiles.Count(), }; } @@ -119,73 +157,6 @@ public IEnumerable GetFolders(IFolderInfo parentFolder, string orde return ApplyOrder(folders.AsQueryable(), field, asc); } - private IEnumerable GetFiles(IFolderInfo folder, SortProperties sortProperties, int startIndex, bool recursive) - { - Requires.NotNull("folder", folder); - - if (Host.EnableFileAutoSync && startIndex == 0) - { - FolderManager.Instance.Synchronize(folder.PortalID, folder.FolderPath, false, true); - } - - return SortFiles(FolderManager.Instance.GetFiles(folder, recursive, true), sortProperties); - } - - private static IEnumerable SortFiles(IEnumerable files, SortProperties sortProperties) - { - switch (sortProperties.Column) - { - case "ItemName": - return OrderBy(files, f => f.FileName, sortProperties.Ascending); - case "LastModifiedOnDate": - return OrderBy(files, f => f.LastModifiedOnDate, sortProperties.Ascending); - case "Size": - return OrderBy(files, f => f.Size, sortProperties.Ascending); - case "ParentFolder": - return OrderBy(files, f => f.FolderId, new FolderPathComparer(), sortProperties.Ascending); - case "CreatedOnDate": - return OrderBy(files, f => f.CreatedOnDate, sortProperties.Ascending); - default: - return files; - } - } - - public static IOrderedQueryable ApplyOrder(IQueryable source, string propertyName, bool asc) - { - var methodName = asc ? "OrderBy" : "OrderByDescending"; - var arg = Expression.Parameter(typeof(T), "x"); - - // Use reflection to mirror LINQ - var property = typeof(T).GetProperty(propertyName); - - // If property is undefined returns the original source - if (property == null) return (IOrderedQueryable)source; - - Expression expr = Expression.Property(arg, property); - - var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), property.PropertyType); - var lambda = Expression.Lambda(delegateType, expr, arg); - - var result = typeof(Queryable).GetMethods().Single( - method => method.Name == methodName - && method.IsGenericMethodDefinition - && method.GetGenericArguments().Length == 2 - && method.GetParameters().Length == 2) - .MakeGenericMethod(typeof(T), property.PropertyType) - .Invoke(null, new object[] { source, lambda }); - return (IOrderedQueryable)result; - } - - private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, bool ascending) - { - return ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector); - } - - private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, IComparer comparer, bool ascending) - { - return ascending ? source.OrderBy(keySelector, comparer) : source.OrderByDescending(keySelector, comparer); - } - public IFileInfo RenameFile(int fileId, string newFileName) { Requires.NotNullOrEmpty("newFileName", newFileName); @@ -194,19 +165,19 @@ public IFileInfo RenameFile(int fileId, string newFileName) if (string.IsNullOrEmpty(filteredName)) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FileNameInvalid", FileNameInvalidDefaultMessage, newFileName)); + throw new AssetManagerException(Localization.GetExceptionMessage("FileNameInvalid", FileNameInvalidDefaultMessage, newFileName)); } // Chech if the new name has invalid chars - if (IsInvalidName(filteredName)) + if (this.IsInvalidName(filteredName)) { - throw new AssetManagerException(GetInvalidCharsErrorText()); + throw new AssetManagerException(this.GetInvalidCharsErrorText()); } // Check if the new name is a reserved name - if (IsReservedName(filteredName)) + if (this.IsReservedName(filteredName)) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FolderFileNameIsReserved", FolderFileNameIsReservedDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("FolderFileNameIsReserved", FolderFileNameIsReservedDefaultMessage)); } var file = FileManager.Instance.GetFile(fileId, true); @@ -221,7 +192,7 @@ public IFileInfo RenameFile(int fileId, string newFileName) var folder = FolderManager.Instance.GetFolder(file.FolderId); if (!HasPermission(folder, "MANAGE")) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("UserHasNoPermissionToEditFile", UserHasNoPermissionToEditFileDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("UserHasNoPermissionToEditFile", UserHasNoPermissionToEditFileDefaultMessage)); } return FileManager.Instance.RenameFile(file, newFileName); @@ -234,23 +205,23 @@ public IFolderInfo RenameFolder(int folderId, string newFolderName) newFolderName = CleanDotsAtTheEndOfTheName(newFolderName); // Check if the new name has invalid chars - if (IsInvalidName(newFolderName)) + if (this.IsInvalidName(newFolderName)) { - throw new AssetManagerException(GetInvalidCharsErrorText()); + throw new AssetManagerException(this.GetInvalidCharsErrorText()); } // Check if the name is reserved - if (IsReservedName(newFolderName)) + if (this.IsReservedName(newFolderName)) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FolderFileNameIsReserved", FolderFileNameIsReservedDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("FolderFileNameIsReserved", FolderFileNameIsReservedDefaultMessage)); } - var folder = GetFolderInfo(folderId); + var folder = this.GetFolderInfo(folderId); // Check if user has appropiate permissions if (!HasPermission(folder, "MANAGE")) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("UserHasNoPermissionToEditFolder", UserHasNoPermissionToEditFolderDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("UserHasNoPermissionToEditFolder", UserHasNoPermissionToEditFolderDefaultMessage)); } // check if the name has not changed @@ -258,45 +229,88 @@ public IFolderInfo RenameFolder(int folderId, string newFolderName) { return folder; } + if (folder.FolderName.Equals(newFolderName, StringComparison.InvariantCultureIgnoreCase)) { - folder.FolderPath = ReplaceFolderName(folder.FolderPath, folder.FolderName, newFolderName); + folder.FolderPath = this.ReplaceFolderName(folder.FolderPath, folder.FolderName, newFolderName); return FolderManager.Instance.UpdateFolder(folder); } - var newFolderPath = GetNewFolderPath(newFolderName, folder); + var newFolderPath = this.GetNewFolderPath(newFolderName, folder); + // Check if the new folder already exists if (FolderManager.Instance.FolderExists(folder.PortalID, newFolderPath)) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FolderAlreadyExists", FolderAlreadyExistsDefultMessage, newFolderName)); + throw new AssetManagerException(Localization.GetExceptionMessage("FolderAlreadyExists", FolderAlreadyExistsDefultMessage, newFolderName)); } FolderManager.Instance.RenameFolder(folder, newFolderName); return folder; } + private static IEnumerable SortFiles(IEnumerable files, SortProperties sortProperties) + { + switch (sortProperties.Column) + { + case "ItemName": + return OrderBy(files, f => f.FileName, sortProperties.Ascending); + case "LastModifiedOnDate": + return OrderBy(files, f => f.LastModifiedOnDate, sortProperties.Ascending); + case "Size": + return OrderBy(files, f => f.Size, sortProperties.Ascending); + case "ParentFolder": + return OrderBy(files, f => f.FolderId, new FolderPathComparer(), sortProperties.Ascending); + case "CreatedOnDate": + return OrderBy(files, f => f.CreatedOnDate, sortProperties.Ascending); + default: + return files; + } + } + + private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, bool ascending) + { + return ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector); + } + + private IEnumerable GetFiles(IFolderInfo folder, SortProperties sortProperties, int startIndex, bool recursive) + { + Requires.NotNull("folder", folder); + + if (Host.EnableFileAutoSync && startIndex == 0) + { + FolderManager.Instance.Synchronize(folder.PortalID, folder.FolderPath, false, true); + } + + return SortFiles(FolderManager.Instance.GetFiles(folder, recursive, true), sortProperties); + } + + private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, IComparer comparer, bool ascending) + { + return ascending ? source.OrderBy(keySelector, comparer) : source.OrderByDescending(keySelector, comparer); + } + public IFolderInfo CreateFolder(string folderName, int folderParentId, int folderMappingId, string mappedPath) { Requires.NotNullOrEmpty("folderName", folderName); var filterFolderName = CleanDotsAtTheEndOfTheName(folderName); - if (IsInvalidName(filterFolderName)) + if (this.IsInvalidName(filterFolderName)) { - throw new AssetManagerException(GetInvalidCharsErrorText()); + throw new AssetManagerException(this.GetInvalidCharsErrorText()); } // Check if the new name is a reserved name - if (IsReservedName(filterFolderName)) + if (this.IsReservedName(filterFolderName)) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FolderFileNameIsReserved", FolderFileNameIsReservedDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("FolderFileNameIsReserved", FolderFileNameIsReservedDefaultMessage)); } - var parentFolder = GetFolderInfo(folderParentId); + var parentFolder = this.GetFolderInfo(folderParentId); if (!HasPermission(parentFolder, "ADD")) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("UserHasNoPermissionToAdd", UserHasNoPermissionToAddDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("UserHasNoPermissionToAdd", UserHasNoPermissionToAddDefaultMessage)); } var folderPath = PathUtils.Instance.FormatFolderPath( @@ -307,7 +321,7 @@ public IFolderInfo CreateFolder(string folderName, int folderParentId, int folde if (!MappedPathRegex.IsMatch(mappedPath)) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("InvalidMappedPath", InvalidMappedPathDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("InvalidMappedPath", InvalidMappedPathDefaultMessage)); } try @@ -317,15 +331,18 @@ public IFolderInfo CreateFolder(string folderName, int folderParentId, int folde } catch (FolderAlreadyExistsException) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FolderAlreadyExists", FolderAlreadyExistsDefaultMessage, filterFolderName)); + throw new AssetManagerException(Localization.GetExceptionMessage("FolderAlreadyExists", FolderAlreadyExistsDefaultMessage, filterFolderName)); } } public bool DeleteFolder(int folderId, bool onlyUnlink, ICollection nonDeletedSubfolders) { var folder = FolderManager.Instance.GetFolder(folderId); - if (folder == null) return false; - + if (folder == null) + { + return false; + } + if (!HasPermission(folder, "DELETE")) { nonDeletedSubfolders.Add(folder); @@ -338,33 +355,21 @@ public bool DeleteFolder(int folderId, bool onlyUnlink, ICollection } else { - DeleteFolder(folder, nonDeletedSubfolders); + this.DeleteFolder(folder, nonDeletedSubfolders); } } return true; } - private void DeleteFolder(IFolderInfo folder, ICollection nonDeletedItems) - { - var nonDeletedSubfolders = new List(); - FolderManager.Instance.DeleteFolder(folder, nonDeletedSubfolders); - if (!nonDeletedSubfolders.Any()) - { - return; - } - - foreach (var nonDeletedSubfolder in nonDeletedSubfolders) - { - nonDeletedItems.Add(nonDeletedSubfolder); - } - } - public bool DeleteFile(int fileId) { var fileInfo = FileManager.Instance.GetFile(fileId, true); - if (fileInfo == null) return false; - + if (fileInfo == null) + { + return false; + } + var folder = FolderManager.Instance.GetFolder(fileInfo.FolderId); if (!HasPermission(folder, "DELETE")) @@ -381,9 +386,24 @@ private static string CleanDotsAtTheEndOfTheName(string name) return name.Trim().TrimEnd('.', ' '); } + private void DeleteFolder(IFolderInfo folder, ICollection nonDeletedItems) + { + var nonDeletedSubfolders = new List(); + FolderManager.Instance.DeleteFolder(folder, nonDeletedSubfolders); + if (!nonDeletedSubfolders.Any()) + { + return; + } + + foreach (var nonDeletedSubfolder in nonDeletedSubfolders) + { + nonDeletedItems.Add(nonDeletedSubfolder); + } + } + private bool IsInvalidName(string itemName) { - var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(GetInvalidChars()) + "]"); + var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(this.GetInvalidChars()) + "]"); return invalidFilenameChars.IsMatch(itemName); } @@ -411,29 +431,19 @@ private bool IsReservedName(string name) private string GetInvalidCharsErrorText() { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FolderFileNameHasInvalidcharacters", + throw new AssetManagerException(Localization.GetExceptionMessage( + "FolderFileNameHasInvalidcharacters", FolderFileNameHasInvalidcharactersDefaultMessage, "\\:/*?\"<>|")); } - public static bool HasPermission(IFolderInfo folder, string permissionKey) - { - var hasPermision = PortalSettings.Current.UserInfo.IsSuperUser; - - if (!hasPermision && folder != null) - { - hasPermision = FolderPermissionController.HasFolderPermission(folder.FolderPermissions, permissionKey); - } - - return hasPermision; - } - private IFolderInfo GetFolderInfo(int folderId) { var folder = FolderManager.Instance.GetFolder(folderId); if (folder == null) { - throw new AssetManagerException(Localization.Localization.GetExceptionMessage("FolderDoesNotExists", DefaultMessageDefaultMessage)); + throw new AssetManagerException(Localization.GetExceptionMessage("FolderDoesNotExists", DefaultMessageDefaultMessage)); } + return folder; } @@ -444,6 +454,7 @@ private string ReplaceFolderName(string path, string folderName, string newFolde { return path; } + var nameIndex = newPath.LastIndexOf(folderName, StringComparison.Ordinal); if (nameIndex == -1) { diff --git a/DNN Platform/Library/Services/Assets/AssetManagerException.cs b/DNN Platform/Library/Services/Assets/AssetManagerException.cs index fc6fc154b7e..b80a2f536ae 100644 --- a/DNN Platform/Library/Services/Assets/AssetManagerException.cs +++ b/DNN Platform/Library/Services/Assets/AssetManagerException.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Assets { + using System; + public class AssetManagerException : Exception { - public AssetManagerException(string message) : base(message) + public AssetManagerException(string message) + : base(message) { } } diff --git a/DNN Platform/Library/Services/Assets/ContentPage.cs b/DNN Platform/Library/Services/Assets/ContentPage.cs index 0ba42450379..7ccebdb90ae 100644 --- a/DNN Platform/Library/Services/Assets/ContentPage.cs +++ b/DNN Platform/Library/Services/Assets/ContentPage.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Assets { + using System.Collections.Generic; + + using DotNetNuke.Services.FileSystem; + public class ContentPage { public IFolderInfo Folder { get; set; } diff --git a/DNN Platform/Library/Services/Assets/FolderPathComparer.cs b/DNN Platform/Library/Services/Assets/FolderPathComparer.cs index b675d5c7269..57f184a44d0 100644 --- a/DNN Platform/Library/Services/Assets/FolderPathComparer.cs +++ b/DNN Platform/Library/Services/Assets/FolderPathComparer.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Assets { + using System.Collections.Generic; + + using DotNetNuke.Services.FileSystem; + public class FolderPathComparer : IComparer - { + { private readonly Dictionary cache; public FolderPathComparer() @@ -28,13 +29,13 @@ public int Compare(int folderIdA, int folderIdB) private string GetFolderPath(int folderId) { - if (!cache.ContainsKey(folderId)) + if (!this.cache.ContainsKey(folderId)) { var folder = FolderManager.Instance.GetFolder(folderId); - cache.Add(folderId, folder.FolderPath); + this.cache.Add(folderId, folder.FolderPath); } - return cache[folderId]; + return this.cache[folderId]; } } } diff --git a/DNN Platform/Library/Services/Assets/IAssetManager.cs b/DNN Platform/Library/Services/Assets/IAssetManager.cs index 979ceeebc5b..f25c6d6a622 100644 --- a/DNN Platform/Library/Services/Assets/IAssetManager.cs +++ b/DNN Platform/Library/Services/Assets/IAssetManager.cs @@ -1,85 +1,86 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Assets { + using System.Collections.Generic; + + using DotNetNuke.Services.FileSystem; + public interface IAssetManager { /// /// Gets the page of files and folders contained in the specified folder. /// - /// Folder Identifier - /// Start index to retrieve items - /// Max Number of items - /// The sort expression in a SQL format, e.g. FileName ASC + /// Folder Identifier. + /// Start index to retrieve items. + /// Max Number of items. + /// The sort expression in a SQL format, e.g. FileName ASC. /// - /// The list of files and folders contained in the specified folder paginated + /// The list of files and folders contained in the specified folder paginated. ContentPage GetFolderContent(int folderId, int startIndex, int numItems, string sortExpression = null, SubfolderFilter subfolderFilter = SubfolderFilter.IncludeSubfoldersFolderStructure); /// /// Searches the files and folders contained in the specified folder. /// - /// Folder Identifier - /// The pattern to search for - /// Start index to retrieve items - /// Max Number of items - /// The sort expression in a SQL format, e.g. FileName ASC - /// The list of files and folders contained in the specified folder paginated + /// Folder Identifier. + /// The pattern to search for. + /// Start index to retrieve items. + /// Max Number of items. + /// The sort expression in a SQL format, e.g. FileName ASC. + /// The list of files and folders contained in the specified folder paginated. ContentPage SearchFolderContent(int folderId, string pattern, int startIndex, int numItems, string sortExpression = null, SubfolderFilter subfolderFilter = SubfolderFilter.IncludeSubfoldersFolderStructure); /// /// Gets the list of subfolders for the specified folder. - /// + /// /// The folder from where to get the list of subfolders. - /// The field to order the list - /// True to order ascending, false to order descending + /// The field to order the list. + /// True to order ascending, false to order descending. /// The list of subfolders for the specified folder. IEnumerable GetFolders(IFolderInfo parentFolder, string orderingField, bool asc); /// /// Renames a existing file. /// - /// File reference to rename - /// The new name to set to the file - /// The final renamed file + /// File reference to rename. + /// The new name to set to the file. + /// The final renamed file. IFileInfo RenameFile(int fileId, string newFileName); /// /// Renames a existing folder. /// - /// Folder reference to rename - /// The new name to set to the folder - /// The final renamed folder + /// Folder reference to rename. + /// The new name to set to the folder. + /// The final renamed folder. IFolderInfo RenameFolder(int folderId, string newFolderName); /// /// Creates a new folder. /// - /// folderName is the name of the new folder - /// The reference to the parent folder where the new folder will be create - /// folderMappingID is the mapping related with the new folder - /// mappedPath used for the mapping to folder in remove provider - /// The newly folder created under the specified parent folder + /// folderName is the name of the new folder. + /// The reference to the parent folder where the new folder will be create. + /// folderMappingID is the mapping related with the new folder. + /// mappedPath used for the mapping to folder in remove provider. + /// The newly folder created under the specified parent folder. IFolderInfo CreateFolder(string folderName, int folderParentId, int folderMappingId, string mappedPath); /// - /// Deletes an existing folder + /// Deletes an existing folder. /// - /// The ide of the folder to delete - /// In case of a remote folder, specifies that the folder should be unlinked, not deleted - /// The list of subfolders that could not be deleted, for example due to permissions - /// True if the folder has been correctly deleted, false otherwise + /// The ide of the folder to delete. + /// In case of a remote folder, specifies that the folder should be unlinked, not deleted. + /// The list of subfolders that could not be deleted, for example due to permissions. + /// True if the folder has been correctly deleted, false otherwise. bool DeleteFolder(int folderId, bool onlyUnlink, ICollection nonDeletedSubfolders); /// - /// Deletes an existing file + /// Deletes an existing file. /// - /// The ide of the folder to delete - /// True if the file has been correctly deleted, false otherwise + /// The ide of the folder to delete. + /// True if the file has been correctly deleted, false otherwise. bool DeleteFile(int fileId); } } diff --git a/DNN Platform/Library/Services/Assets/SortProperties.cs b/DNN Platform/Library/Services/Assets/SortProperties.cs index 33b71c7cedd..20fb9d4c333 100644 --- a/DNN Platform/Library/Services/Assets/SortProperties.cs +++ b/DNN Platform/Library/Services/Assets/SortProperties.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Assets { public class SortProperties diff --git a/DNN Platform/Library/Services/Assets/SubfolderFilter.cs b/DNN Platform/Library/Services/Assets/SubfolderFilter.cs index bfc72f34a21..68650b20e2b 100644 --- a/DNN Platform/Library/Services/Assets/SubfolderFilter.cs +++ b/DNN Platform/Library/Services/Assets/SubfolderFilter.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Assets { public enum SubfolderFilter { ExcludeSubfolders, IncludeSubfoldersFilesOnly, - IncludeSubfoldersFolderStructure + IncludeSubfoldersFolderStructure, } } diff --git a/DNN Platform/Library/Services/Authentication/AuthMode.cs b/DNN Platform/Library/Services/Authentication/AuthMode.cs index 49c756f5196..942ead8f054 100644 --- a/DNN Platform/Library/Services/Authentication/AuthMode.cs +++ b/DNN Platform/Library/Services/Authentication/AuthMode.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication { public enum AuthMode { Login = 0, - Register = 1 + Register = 1, } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs b/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs index c100b109def..24a0316dd7d 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs @@ -1,52 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + /// ----------------------------------------------------------------------------- /// /// The AuthenticationConfig class providesa configuration class for the DNN - /// Authentication provider + /// Authentication provider. /// /// ----------------------------------------------------------------------------- [Serializable] public class AuthenticationConfig : AuthenticationConfigBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (AuthenticationConfig)); private const string CACHEKEY = "Authentication.DNN"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthenticationConfig)); - protected AuthenticationConfig(int portalID) : base(portalID) + protected AuthenticationConfig(int portalID) + : base(portalID) { - UseCaptcha = Null.NullBoolean; - Enabled = true; + this.UseCaptcha = Null.NullBoolean; + this.Enabled = true; try { string setting = Null.NullString; if (PortalController.Instance.GetPortalSettings(portalID).TryGetValue("DNN_Enabled", out setting)) { - Enabled = bool.Parse(setting); + this.Enabled = bool.Parse(setting); } + setting = Null.NullString; if (PortalController.Instance.GetPortalSettings(portalID).TryGetValue("DNN_UseCaptcha", out setting)) { - UseCaptcha = bool.Parse(setting); + this.UseCaptcha = bool.Parse(setting); } } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } } public bool Enabled { get; set; } @@ -62,12 +59,13 @@ public static void ClearConfig(int portalId) public static AuthenticationConfig GetConfig(int portalId) { string key = CACHEKEY + "_" + portalId; - var config = (AuthenticationConfig) DataCache.GetCache(key); + var config = (AuthenticationConfig)DataCache.GetCache(key); if (config == null) { config = new AuthenticationConfig(portalId); DataCache.SetCache(key, config); } + return config; } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs index 4b6be83f7a8..49afae67766 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs @@ -1,48 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + using System.ComponentModel; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationConfigBase class provides base configuration class for the - /// Authentication providers + /// The AuthenticationConfigBase class provides base configuration class for the + /// Authentication providers. /// /// ----------------------------------------------------------------------------- [Serializable] public abstract class AuthenticationConfigBase { - /// - /// Gets or sets the Dependency Provider to resolve registered - /// services with the container. - /// - /// - /// The Dependency Service. - /// - protected IServiceProvider DependencyProvider { get; } - public AuthenticationConfigBase() { - DependencyProvider = Globals.DependencyProvider; + this.DependencyProvider = Globals.DependencyProvider; } protected AuthenticationConfigBase(int portalID) : this() { - PortalID = portalID; + this.PortalID = portalID; } [Browsable(false)] public int PortalID { get; set; } + + /// + /// Gets the Dependency Provider to resolve registered + /// services with the container. + /// + /// + /// The Dependency Service. + /// + protected IServiceProvider DependencyProvider { get; } } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationController.cs b/DNN Platform/Library/Services/Authentication/AuthenticationController.cs index 39de86e1255..fcb0e4cde23 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationController.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationController.cs @@ -1,30 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + using System.Collections.Generic; using System.Linq; + using System.Web; using System.Web.UI; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Log.EventLog; using DotNetNuke.UI.Skins; /// ----------------------------------------------------------------------------- @@ -35,76 +29,70 @@ namespace DotNetNuke.Services.Authentication /// ----------------------------------------------------------------------------- public class AuthenticationController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (AuthenticationController)); - #region "Private Members" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthenticationController)); private static readonly DataProvider provider = DataProvider.Instance(); - #endregion - - #region "Private Shared Methods" - - private static object GetAuthenticationServicesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillCollection(provider.GetAuthenticationServices()); - } - - #endregion - - #region "Public Shared Methods" - /// ----------------------------------------------------------------------------- /// /// AddAuthentication adds a new Authentication System to the Data Store. /// - /// The new Authentication System to add + /// The new Authentication System to add. + /// /// ----------------------------------------------------------------------------- public static int AddAuthentication(AuthenticationInfo authSystem) { - EventLogController.Instance.AddLog(authSystem, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.AUTHENTICATION_CREATED); - return provider.AddAuthentication(authSystem.PackageID, - authSystem.AuthenticationType, - authSystem.IsEnabled, - authSystem.SettingsControlSrc, - authSystem.LoginControlSrc, - authSystem.LogoffControlSrc, - UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(authSystem, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.AUTHENTICATION_CREATED); + return provider.AddAuthentication( + authSystem.PackageID, + authSystem.AuthenticationType, + authSystem.IsEnabled, + authSystem.SettingsControlSrc, + authSystem.LoginControlSrc, + authSystem.LogoffControlSrc, + UserController.Instance.GetCurrentUserInfo().UserID); } /// ----------------------------------------------------------------------------- /// /// AddUserAuthentication adds a new UserAuthentication to the User. /// - /// The new Authentication System to add - /// The authentication type - /// The authentication token + /// The new Authentication System to add. + /// The authentication type. + /// The authentication token. + /// /// ----------------------------------------------------------------------------- public static int AddUserAuthentication(int userID, string authenticationType, string authenticationToken) { UserAuthenticationInfo userAuth = GetUserAuthentication(userID); - if (userAuth == null || String.IsNullOrEmpty(userAuth.AuthenticationType)) + if (userAuth == null || string.IsNullOrEmpty(userAuth.AuthenticationType)) { - EventLogController.Instance.AddLog("userID/authenticationType", - userID + "/" + authenticationType, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.AUTHENTICATION_USER_CREATED); + EventLogController.Instance.AddLog( + "userID/authenticationType", + userID + "/" + authenticationType, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.AUTHENTICATION_USER_CREATED); return provider.AddUserAuthentication(userID, authenticationType, authenticationToken, UserController.Instance.GetCurrentUserInfo().UserID); } else { - - EventLogController.Instance.AddLog("userID/authenticationType already exists", - userID + "/" + authenticationType, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.AUTHENTICATION_USER_UPDATED); + EventLogController.Instance.AddLog( + "userID/authenticationType already exists", + userID + "/" + authenticationType, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.AUTHENTICATION_USER_UPDATED); return userAuth.UserAuthenticationID; } } + private static object GetAuthenticationServicesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillCollection(provider.GetAuthenticationServices()); + } + /// /// Retrieves authentication information for an user. /// @@ -112,23 +100,22 @@ public static int AddUserAuthentication(int userID, string authenticationType, s /// public static UserAuthenticationInfo GetUserAuthentication(int userID) { - //Go to database + // Go to database return CBO.FillObject(provider.GetUserAuthentication(userID)); - } public static void DeleteAuthentication(AuthenticationInfo authSystem) { provider.DeleteAuthentication(authSystem.AuthenticationID); - EventLogController.Instance.AddLog(authSystem, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.AUTHENTICATION_DELETED); + EventLogController.Instance.AddLog(authSystem, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.AUTHENTICATION_DELETED); } /// ----------------------------------------------------------------------------- /// - /// GetAuthenticationService fetches a single Authentication Systems + /// GetAuthenticationService fetches a single Authentication Systems. /// - /// The ID of the Authentication System - /// An AuthenticationInfo object + /// The ID of the Authentication System. + /// An AuthenticationInfo object. /// ----------------------------------------------------------------------------- public static AuthenticationInfo GetAuthenticationService(int authenticationID) { @@ -141,20 +128,22 @@ public static AuthenticationInfo GetAuthenticationService(int authenticationID) break; } } + if (authInfo == null) { - //Go to database + // Go to database return CBO.FillObject(provider.GetAuthenticationService(authenticationID)); } + return authInfo; } /// ----------------------------------------------------------------------------- /// - /// GetAuthenticationServiceByPackageID fetches a single Authentication System + /// GetAuthenticationServiceByPackageID fetches a single Authentication System. /// - /// The id of the Package - /// An AuthenticationInfo object + /// The id of the Package. + /// An AuthenticationInfo object. /// ----------------------------------------------------------------------------- public static AuthenticationInfo GetAuthenticationServiceByPackageID(int packageID) { @@ -167,20 +156,22 @@ public static AuthenticationInfo GetAuthenticationServiceByPackageID(int package break; } } + if (authInfo == null) { - //Go to database + // Go to database return CBO.FillObject(provider.GetAuthenticationServiceByPackageID(packageID)); } + return authInfo; } /// ----------------------------------------------------------------------------- /// - /// GetAuthenticationServiceByType fetches a single Authentication Systems + /// GetAuthenticationServiceByType fetches a single Authentication Systems. /// - /// The type of the Authentication System - /// An AuthenticationInfo object + /// The type of the Authentication System. + /// An AuthenticationInfo object. /// ----------------------------------------------------------------------------- public static AuthenticationInfo GetAuthenticationServiceByType(string authenticationType) { @@ -193,20 +184,22 @@ public static AuthenticationInfo GetAuthenticationServiceByType(string authentic break; } } + if (authInfo == null) { - //Go to database + // Go to database return CBO.FillObject(provider.GetAuthenticationServiceByType(authenticationType)); } + return authInfo; } /// ----------------------------------------------------------------------------- /// /// GetAuthenticationServices fetches a list of all the Authentication Systems - /// installed in the system + /// installed in the system. /// - /// A List of AuthenticationInfo objects + /// A List of AuthenticationInfo objects. /// ----------------------------------------------------------------------------- public static List GetAuthenticationServices() { @@ -218,9 +211,9 @@ public static List GetAuthenticationServices() /// ----------------------------------------------------------------------------- /// - /// GetAuthenticationType fetches the authentication method used by the currently logged on user + /// GetAuthenticationType fetches the authentication method used by the currently logged on user. /// - /// An AuthenticationInfo object + /// An AuthenticationInfo object. /// ----------------------------------------------------------------------------- public static AuthenticationInfo GetAuthenticationType() { @@ -231,20 +224,21 @@ public static AuthenticationInfo GetAuthenticationType() { objAuthentication = GetAuthenticationServiceByType(HttpContext.Current.Request["authentication"]); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } } + return objAuthentication; } /// ----------------------------------------------------------------------------- /// /// GetEnabledAuthenticationServices fetches a list of all the Authentication Systems - /// installed in the system that have been enabled by the Host user + /// installed in the system that have been enabled by the Host user. /// - /// A List of AuthenticationInfo objects + /// A List of AuthenticationInfo objects. /// ----------------------------------------------------------------------------- public static List GetEnabledAuthenticationServices() { @@ -256,6 +250,7 @@ public static List GetEnabledAuthenticationServices() enabled.Add(authService); } } + return enabled; } @@ -285,59 +280,59 @@ public static bool HasSocialAuthenticationEnabled(UserControl control = null) /// true if OAuth Provider and it is enabled for the portal, Otherwise false. public static bool IsEnabledForPortal(AuthenticationInfo authentication, int portalId) { - return !string.IsNullOrEmpty(PortalController.GetPortalSetting(authentication.AuthenticationType + "_Enabled", portalId, "")) + return !string.IsNullOrEmpty(PortalController.GetPortalSetting(authentication.AuthenticationType + "_Enabled", portalId, string.Empty)) ? PortalController.GetPortalSettingAsBoolean(authentication.AuthenticationType + "_Enabled", portalId, false) : HostController.Instance.GetBoolean(authentication.AuthenticationType + "_Enabled", false); } /// ----------------------------------------------------------------------------- /// - /// GetLogoffRedirectURL fetches the url to redirect too after logoff + /// GetLogoffRedirectURL fetches the url to redirect too after logoff. /// - /// A PortalSettings object - /// The current Request - /// The Url + /// A PortalSettings object. + /// The current Request. + /// The Url. /// ----------------------------------------------------------------------------- public static string GetLogoffRedirectURL(PortalSettings settings, HttpRequest request) { - string _RedirectURL = ""; + string _RedirectURL = string.Empty; if (settings.Registration.RedirectAfterLogout == Null.NullInteger) { if (TabPermissionController.CanViewPage()) { - //redirect to current page (or home page if current page is a profile page to reduce redirects) - if (settings.ActiveTab.TabID == settings.UserTabId || settings.ActiveTab.ParentId == settings.UserTabId) - { + // redirect to current page (or home page if current page is a profile page to reduce redirects) + if (settings.ActiveTab.TabID == settings.UserTabId || settings.ActiveTab.ParentId == settings.UserTabId) + { _RedirectURL = TestableGlobals.Instance.NavigateURL(settings.HomeTabId); - } - else - { + } + else + { _RedirectURL = (request != null && request.UrlReferrer != null) ? request.UrlReferrer.PathAndQuery : TestableGlobals.Instance.NavigateURL(settings.ActiveTab.TabID); - } - + } } else if (settings.HomeTabId != -1) { - //redirect to portal home page specified + // redirect to portal home page specified _RedirectURL = TestableGlobals.Instance.NavigateURL(settings.HomeTabId); } - else //redirect to default portal root + else // redirect to default portal root { _RedirectURL = TestableGlobals.Instance.GetPortalDomainName(settings.PortalAlias.HTTPAlias, request, true) + "/" + Globals.glbDefaultPage; } } - else //redirect to after logout page + else // redirect to after logout page { - _RedirectURL = TestableGlobals.Instance.NavigateURL(settings.Registration.RedirectAfterLogout); + _RedirectURL = TestableGlobals.Instance.NavigateURL(settings.Registration.RedirectAfterLogout); } + return _RedirectURL; } /// ----------------------------------------------------------------------------- /// - /// SetAuthenticationType sets the authentication method used by the currently logged on user + /// SetAuthenticationType sets the authentication method used by the currently logged on user. /// - /// The Authentication type + /// The Authentication type. /// ----------------------------------------------------------------------------- public static void SetAuthenticationType(string value) { @@ -354,31 +349,33 @@ public static void SetAuthenticationType(string value, bool CreatePersistentCook { return; } - - //save the authenticationmethod as a cookie + + // save the authenticationmethod as a cookie HttpCookie cookie = null; cookie = Response.Cookies.Get("authentication"); - if ((cookie == null)) + if (cookie == null) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { - cookie = new HttpCookie("authentication", value) { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }; + cookie = new HttpCookie("authentication", value) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }; if (CreatePersistentCookie) { cookie.Expires = DateTime.Now.AddMinutes(PersistentCookieTimeout); } + Response.Cookies.Add(cookie); } } else { cookie.Value = value; - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { if (CreatePersistentCookie) { cookie.Expires = DateTime.Now.AddMinutes(PersistentCookieTimeout); } + Response.Cookies.Set(cookie); } else @@ -397,21 +394,20 @@ public static void SetAuthenticationType(string value, bool CreatePersistentCook /// /// UpdateAuthentication updates an existing Authentication System in the Data Store. /// - /// The new Authentication System to update + /// The new Authentication System to update. /// ----------------------------------------------------------------------------- public static void UpdateAuthentication(AuthenticationInfo authSystem) { - provider.UpdateAuthentication(authSystem.AuthenticationID, - authSystem.PackageID, - authSystem.AuthenticationType, - authSystem.IsEnabled, - authSystem.SettingsControlSrc, - authSystem.LoginControlSrc, - authSystem.LogoffControlSrc, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(authSystem, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.AUTHENTICATION_UPDATED); + provider.UpdateAuthentication( + authSystem.AuthenticationID, + authSystem.PackageID, + authSystem.AuthenticationType, + authSystem.IsEnabled, + authSystem.SettingsControlSrc, + authSystem.LoginControlSrc, + authSystem.LogoffControlSrc, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(authSystem, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.AUTHENTICATION_UPDATED); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs b/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs index 2b87ef8f6b4..0d6cdaf242d 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs @@ -1,135 +1,119 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationInfo class provides the Entity Layer for the + /// The AuthenticationInfo class provides the Entity Layer for the /// Authentication Systems. /// /// ----------------------------------------------------------------------------- [Serializable] public class AuthenticationInfo : BaseEntityInfo, IHydratable - { - #region Private Members - + { public AuthenticationInfo() { - LogoffControlSrc = Null.NullString; - LoginControlSrc = Null.NullString; - SettingsControlSrc = Null.NullString; - AuthenticationType = Null.NullString; - AuthenticationID = Null.NullInteger; - } - - #endregion - - #region Public Properties - + this.LogoffControlSrc = Null.NullString; + this.LoginControlSrc = Null.NullString; + this.SettingsControlSrc = Null.NullString; + this.AuthenticationType = Null.NullString; + this.AuthenticationID = Null.NullInteger; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the ID of the Authentication System + /// Gets or sets and Sets the ID of the Authentication System. /// /// ----------------------------------------------------------------------------- public int AuthenticationID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the PackageID for the Authentication System + /// Gets or sets and Sets the PackageID for the Authentication System. /// /// ----------------------------------------------------------------------------- public int PackageID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets a flag that determines whether the Authentication System is enabled + /// Gets or sets a value indicating whether gets and Sets a flag that determines whether the Authentication System is enabled. /// /// ----------------------------------------------------------------------------- public bool IsEnabled { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the type (name) of the Authentication System (eg DNN, OpenID, LiveID) + /// Gets or sets and Sets the type (name) of the Authentication System (eg DNN, OpenID, LiveID). /// /// ----------------------------------------------------------------------------- public string AuthenticationType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the url for the Settings Control + /// Gets or sets and Sets the url for the Settings Control. /// /// ----------------------------------------------------------------------------- public string SettingsControlSrc { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the url for the Login Control + /// Gets or sets and Sets the url for the Login Control. /// /// ----------------------------------------------------------------------------- public string LoginControlSrc { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the url for the Logoff Control + /// Gets or sets and Sets the url for the Logoff Control. /// /// ----------------------------------------------------------------------------- - public string LogoffControlSrc { get; set; } - - #endregion - - #region IHydratable Members + public string LogoffControlSrc { get; set; } /// ----------------------------------------------------------------------------- /// - /// Fills a RoleInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public virtual void Fill(IDataReader dr) - { - AuthenticationID = Null.SetNullInteger(dr["AuthenticationID"]); - PackageID = Null.SetNullInteger(dr["PackageID"]); - IsEnabled = Null.SetNullBoolean(dr["IsEnabled"]); - AuthenticationType = Null.SetNullString(dr["AuthenticationType"]); - SettingsControlSrc = Null.SetNullString(dr["SettingsControlSrc"]); - LoginControlSrc = Null.SetNullString(dr["LoginControlSrc"]); - LogoffControlSrc = Null.SetNullString(dr["LogoffControlSrc"]); - - //Fill base class fields - FillInternal(dr); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public virtual int KeyID { get { - return AuthenticationID; + return this.AuthenticationID; } + set { - AuthenticationID = value; + this.AuthenticationID = value; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a RoleInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public virtual void Fill(IDataReader dr) + { + this.AuthenticationID = Null.SetNullInteger(dr["AuthenticationID"]); + this.PackageID = Null.SetNullInteger(dr["PackageID"]); + this.IsEnabled = Null.SetNullBoolean(dr["IsEnabled"]); + this.AuthenticationType = Null.SetNullString(dr["AuthenticationType"]); + this.SettingsControlSrc = Null.SetNullString(dr["SettingsControlSrc"]); + this.LoginControlSrc = Null.SetNullString(dr["LoginControlSrc"]); + this.LogoffControlSrc = Null.SetNullString(dr["LogoffControlSrc"]); + + // Fill base class fields + this.FillInternal(dr); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs index a2dd885c46b..3a07044a872 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs @@ -1,56 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.UserRequest; -using System; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.UserRequest; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationLoginBase class provides a bas class for Authentiication - /// Login controls + /// The AuthenticationLoginBase class provides a bas class for Authentiication + /// Login controls. /// /// ----------------------------------------------------------------------------- public abstract class AuthenticationLoginBase : UserModuleBase - { - #region Delegates - - public delegate void UserAuthenticatedEventHandler(object sender, UserAuthenticatedEventArgs e); - - #endregion - + { protected AuthenticationLoginBase() { - RedirectURL = Null.NullString; - AuthenticationType = Null.NullString; - Mode = AuthMode.Login; + this.RedirectURL = Null.NullString; + this.AuthenticationType = Null.NullString; + this.Mode = AuthMode.Login; } + + public delegate void UserAuthenticatedEventHandler(object sender, UserAuthenticatedEventArgs e); + + public event UserAuthenticatedEventHandler UserAuthenticated; /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Type of Authentication associated with this control + /// Gets or sets and Sets the Type of Authentication associated with this control. /// /// ----------------------------------------------------------------------------- public string AuthenticationType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the control is Enabled + /// Gets a value indicating whether gets whether the control is Enabled. /// - /// This property must be overriden in the inherited class + /// This property must be overriden in the inherited class. /// ----------------------------------------------------------------------------- public abstract bool Enabled { get; } /// ----------------------------------------------------------------------------- /// - /// Gets the IP address associated with the request + /// Gets the IP address associated with the request. /// /// ----------------------------------------------------------------------------- public string IPAddress @@ -59,47 +55,48 @@ public string IPAddress { var controller = UserRequestIPAddressController.Instance; var request = new HttpRequestWrapper(HttpContext.Current.Request); - return controller.GetUserRequestIPAddress(request); ; + return controller.GetUserRequestIPAddress(request); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Authentication mode of the control (Login or Register) + /// Gets or sets the Authentication mode of the control (Login or Register). /// - /// This property may be overriden in the inherited class - /// ----------------------------------------------------------------------------- + /// This property may be overriden in the inherited class. + /// ----------------------------------------------------------------------------- public virtual AuthMode Mode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Redirect Url for this control + /// Gets or sets and Sets the Redirect Url for this control. /// /// ----------------------------------------------------------------------------- public string RedirectURL { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the control supports Registration + /// Gets a value indicating whether gets whether the control supports Registration. /// - /// This property may be overriden in the inherited class + /// This property may be overriden in the inherited class. /// ----------------------------------------------------------------------------- - public virtual bool SupportsRegistration { get { return false; } } + public virtual bool SupportsRegistration + { + get { return false; } + } - public event UserAuthenticatedEventHandler UserAuthenticated; + [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] + public static string GetIPAddress() + { + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); + } protected virtual void OnUserAuthenticated(UserAuthenticatedEventArgs ea) { - if (UserAuthenticated != null) + if (this.UserAuthenticated != null) { - UserAuthenticated(null, ea); + this.UserAuthenticated(null, ea); } } - - [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] - public static string GetIPAddress() - { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); - } } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs index 35cea06e45d..4aefc9dae38 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationLogoffBase class provides a base class for Authentiication - /// Logoff controls + /// The AuthenticationLogoffBase class provides a base class for Authentiication + /// Logoff controls. /// /// ----------------------------------------------------------------------------- public abstract class AuthenticationLogoffBase : UserModuleBase @@ -24,53 +20,55 @@ public abstract class AuthenticationLogoffBase : UserModuleBase private string _AuthenticationType = Null.NullString; private string _RedirectURL = Null.NullString; - /// - /// Gets or sets the Dependency Provider to resolve registered - /// services with the container. - /// - /// - /// The Dependency Service. - /// - protected IServiceProvider DependencyProvider { get; } - public AuthenticationLogoffBase() { - DependencyProvider = Globals.DependencyProvider; + this.DependencyProvider = Globals.DependencyProvider; } + public event EventHandler LogOff; + + public event EventHandler Redirect; + /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Type of Authentication associated with this control + /// Gets or sets and Sets the Type of Authentication associated with this control. /// /// ----------------------------------------------------------------------------- public string AuthenticationType { get { - return _AuthenticationType; + return this._AuthenticationType; } + set { - _AuthenticationType = value; + this._AuthenticationType = value; } } - public event EventHandler LogOff; - public event EventHandler Redirect; + /// + /// Gets the Dependency Provider to resolve registered + /// services with the container. + /// + /// + /// The Dependency Service. + /// + protected IServiceProvider DependencyProvider { get; } protected virtual void OnLogOff(EventArgs a) { - if (LogOff != null) + if (this.LogOff != null) { - LogOff(null, a); + this.LogOff(null, a); } } protected virtual void OnRedirect(EventArgs a) { - if (Redirect != null) + if (this.Redirect != null) { - Redirect(null, a); + this.Redirect(null, a); } } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs index dc2efe4b8fd..346108a23a7 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationSettingsBase class provides a base class for Authentiication - /// Settings controls + /// The AuthenticationSettingsBase class provides a base class for Authentiication + /// Settings controls. /// /// ----------------------------------------------------------------------------- public abstract class AuthenticationSettingsBase : PortalModuleBase @@ -23,26 +18,27 @@ public abstract class AuthenticationSettingsBase : PortalModuleBase /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Type of Authentication associated with this control + /// Gets or sets and Sets the Type of Authentication associated with this control. /// /// ----------------------------------------------------------------------------- public string AuthenticationType { get { - return _AuthenticationType; + return this._AuthenticationType; } + set { - _AuthenticationType = value; + this._AuthenticationType = value; } } /// ----------------------------------------------------------------------------- /// - /// UpdateSettings updates the settings in the Data Store + /// UpdateSettings updates the settings in the Data Store. /// - /// This method must be overriden in the inherited class + /// This method must be overriden in the inherited class. /// ----------------------------------------------------------------------------- public abstract void UpdateSettings(); } diff --git a/DNN Platform/Library/Services/Authentication/LogOffHandler.cs b/DNN Platform/Library/Services/Authentication/LogOffHandler.cs index 699d2991667..cd84c8baff2 100644 --- a/DNN Platform/Library/Services/Authentication/LogOffHandler.cs +++ b/DNN Platform/Library/Services/Authentication/LogOffHandler.cs @@ -1,25 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web; - -using DotNetNuke.Common.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System.Web; + + using DotNetNuke.Common.Internal; + /// ----------------------------------------------------------------------------- /// - /// The LogOffHandler class provides a replacement for the LogOff page + /// The LogOffHandler class provides a replacement for the LogOff page. /// public class LogOffHandler : IHttpHandler { - #region IHttpHandler Members - public bool IsReusable { get @@ -32,7 +25,5 @@ public void ProcessRequest(HttpContext context) { context.Response.Redirect(TestableGlobals.Instance.NavigateURL("LogOff")); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs b/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs index 484ec0bb70d..9231cc88e7e 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication.OAuth { + using System.Collections.Generic; + using System.Text; + internal static class AuthExtensions { public static string ToAuthorizationString(this IList parameters) diff --git a/DNN Platform/Library/Services/Authentication/OAuth/AuthorisationResult.cs b/DNN Platform/Library/Services/Authentication/OAuth/AuthorisationResult.cs index 2d951d5e865..cc40c531049 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/AuthorisationResult.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/AuthorisationResult.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication.OAuth { public enum AuthorisationResult { Denied, Authorized, - RequestingCode + RequestingCode, } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/HttpMethod.cs b/DNN Platform/Library/Services/Authentication/OAuth/HttpMethod.cs index 96b3ca50736..bb1b600fccf 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/HttpMethod.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/HttpMethod.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication.OAuth { public enum HttpMethod @@ -9,6 +9,6 @@ public enum HttpMethod GET, POST, PUT, - DELETE + DELETE, } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs index 422d93cae38..a84a04b8c37 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs @@ -1,48 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -//Based on the work of: - -// Base oAuth Class for Twitter and LinkedIn -// Author: Eran Sandler -// Code Url: http://oauth.net/code/ -// Author Url: http://eran.sandler.co.il/ -// -// Some modifications by Shannon Whitley -// Author Url: http://voiceoftech.com/ -// -// Additional modifications by Evan Smith (DNN-4143 & DNN-6265) -// Author Url: http://skydnn.com - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.IO; -using System.Net; -using System.Security.Cryptography; -using System.Text; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Membership; -using DotNetNuke.Instrumentation; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication.OAuth { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.IO; + using System.Net; + using System.Security.Cryptography; + using System.Text; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Localization; + public abstract class OAuthClientBase - { - #region Private Members - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OAuthClientBase)); + { + protected const string OAuthTokenKey = "oauth_token"; private const string HMACSHA1SignatureType = "HMAC-SHA1"; - //oAuth 1 + // oAuth 1 private const string OAuthParameterPrefix = "oauth_"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OAuthClientBase)); private const string OAuthConsumerKeyKey = "oauth_consumer_key"; private const string OAuthCallbackKey = "oauth_callback"; private const string OAuthVersionKey = "oauth_version"; @@ -54,91 +43,98 @@ public abstract class OAuthClientBase private const string OAuthVerifierKey = "oauth_verifier"; private const string OAuthCallbackConfirmedKey = "oauth_callback_confirmed"; - //oAuth 2 + // oAuth 2 private const string OAuthClientIdKey = "client_id"; private const string OAuthClientSecretKey = "client_secret"; private const string OAuthRedirectUriKey = "redirect_uri"; private const string OAuthGrantTyepKey = "grant_type"; private const string OAuthCodeKey = "code"; - private readonly Random random = new Random(); - private const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; - - //DNN-6265 - Support OAuth V2 optional parameter resource, which is required by Microsoft Azure Active - //Directory implementation of OAuth V2 - private const string OAuthResourceKey = "resource"; - #endregion + // DNN-6265 - Support OAuth V2 optional parameter resource, which is required by Microsoft Azure Active + // Directory implementation of OAuth V2 + private const string OAuthResourceKey = "resource"; + private readonly Random random = new Random(); + protected OAuthClientBase(int portalId, AuthMode mode, string service) { - //Set default Expiry to 14 days - //oAuth v1 tokens do not expire - //oAuth v2 tokens have an expiry - AuthTokenExpiry = new TimeSpan(14, 0, 0, 0); - Service = service; - - APIKey = OAuthConfigBase.GetConfig(Service, portalId).APIKey; - APISecret = OAuthConfigBase.GetConfig(Service, portalId).APISecret; - Mode = mode; - - CallbackUri = Mode == AuthMode.Login - ? new Uri(Globals.LoginURL(String.Empty, false)) - : new Uri(Globals.RegisterURL(String.Empty, String.Empty)); - } - - #region Protected Properties - - protected const string OAuthTokenKey = "oauth_token"; + // Set default Expiry to 14 days + // oAuth v1 tokens do not expire + // oAuth v2 tokens have an expiry + this.AuthTokenExpiry = new TimeSpan(14, 0, 0, 0); + this.Service = service; + + this.APIKey = OAuthConfigBase.GetConfig(this.Service, portalId).APIKey; + this.APISecret = OAuthConfigBase.GetConfig(this.Service, portalId).APISecret; + this.Mode = mode; + + this.CallbackUri = this.Mode == AuthMode.Login + ? new Uri(Globals.LoginURL(string.Empty, false)) + : new Uri(Globals.RegisterURL(string.Empty, string.Empty)); + } + + public Uri CallbackUri { get; set; } + + public string Service { get; set; } - protected virtual string UserGuidKey + protected virtual string UserGuidKey { - get { return String.Empty; } + get { return string.Empty; } } protected string APIKey { get; set; } + protected string APISecret { get; set; } + protected AuthMode Mode { get; set; } + protected string OAuthVersion { get; set; } + protected HttpMethod TokenMethod { get; set; } - //oAuth 1 + // oAuth 1 protected string OAuthVerifier { get { return HttpContext.Current.Request.Params[OAuthVerifierKey]; } } + protected Uri RequestTokenEndpoint { get; set; } + protected HttpMethod RequestTokenMethod { get; set; } + protected string TokenSecret { get; set; } + protected string UserGuid { get; set; } - //oAuth 1 and 2 + // oAuth 1 and 2 protected Uri AuthorizationEndpoint { get; set; } + protected string AuthToken { get; set; } + protected TimeSpan AuthTokenExpiry { get; set; } + protected Uri MeGraphEndpoint { get; set; } + protected Uri TokenEndpoint { get; set; } + protected string OAuthHeaderCode { get; set; } - //oAuth 2 - protected string AuthTokenName { get; set; } + // oAuth 2 + protected string AuthTokenName { get; set; } + protected string Scope { get; set; } - protected string AccessToken { get; set; } + + protected string AccessToken { get; set; } + protected string VerificationCode { get { return HttpContext.Current.Request.Params[OAuthCodeKey]; } } - - //DNN-6265 Support "Optional" Resource Parameter required by Azure AD Oauth V2 Solution - protected string APIResource { get; set; } - - #endregion - #region Public Properties - - public Uri CallbackUri { get; set; } - public string Service { get; set; } + // DNN-6265 Support "Optional" Resource Parameter required by Azure AD Oauth V2 Solution + protected string APIResource { get; set; } public virtual bool PrefixServiceToUserName { @@ -148,25 +144,186 @@ public virtual bool PrefixServiceToUserName public virtual bool AutoMatchExistingUsers { get { return false; } + } + + /// + /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case. + /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth. + /// + /// The value to Url encode. + /// Returns a Url encoded string. + public static string UrlEncode(string value) + { + var result = new StringBuilder(); + + foreach (char symbol in value) + { + if (UnreservedChars.IndexOf(symbol) != -1) + { + result.Append(symbol); + } + else + { + result.Append('%' + string.Format("{0:X2}", (int)symbol)); + } + } + + return result.ToString(); } + + public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action addCustomProperties, Action onAuthenticated) + { + var loginStatus = UserLoginStatus.LOGIN_FAILURE; + + string userName = this.PrefixServiceToUserName ? this.Service + "-" + user.Id : user.Id; + string token = this.Service + "-" + user.Id; - #endregion + UserInfo objUserInfo; - #region Private Methods + if (this.AutoMatchExistingUsers) + { + objUserInfo = MembershipProvider.Instance().GetUserByUserName(settings.PortalId, userName); + if (objUserInfo != null) + { + // user already exists... lets check for a token next... + var dnnAuthToken = MembershipProvider.Instance().GetUserByAuthToken(settings.PortalId, token, this.Service); + if (dnnAuthToken == null) + { + DataProvider.Instance().AddUserAuthentication(objUserInfo.UserID, this.Service, token, objUserInfo.UserID); + } + } + } + objUserInfo = UserController.ValidateUser(settings.PortalId, userName, string.Empty, + this.Service, token, + settings.PortalName, IPAddress, + ref loginStatus); + + // Raise UserAuthenticated Event + var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, token, loginStatus, this.Service) + { + AutoRegister = true, + UserName = userName, + }; + + var profileProperties = new NameValueCollection(); + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName))) + { + profileProperties.Add("FirstName", user.FirstName); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName))) + { + profileProperties.Add("LastName", user.LastName); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email))) + { + profileProperties.Add("Email", user.PreferredEmail); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.DisplayName))) + { + profileProperties.Add("DisplayName", user.DisplayName); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.ProfileImage))) + { + profileProperties.Add("ProfileImage", user.ProfileImage); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website))) + { + profileProperties.Add("Website", user.Website); + } + + if ((objUserInfo == null || string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale"))) && !string.IsNullOrEmpty(user.Locale)) + { + if (LocaleController.IsValidCultureName(user.Locale.Replace('_', '-'))) + { + profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-')); + } + else + { + profileProperties.Add("PreferredLocale", settings.CultureCode); + } + } + + if (objUserInfo == null || string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))) + { + if (string.IsNullOrEmpty(user.TimeZoneInfo)) + { + int timeZone; + if (int.TryParse(user.Timezone, out timeZone)) + { + var timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone); + + profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id); + } + } + else + { + profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo); + } + } + + addCustomProperties(profileProperties); + + eventArgs.Profile = profileProperties; + + if (this.Mode == AuthMode.Login) + { + this.SaveTokenCookie(string.Empty); + } + + onAuthenticated(eventArgs); + } + + public virtual AuthorisationResult Authorize() + { + if (this.OAuthVersion == "1.0") + { + return this.AuthorizeV1(); + } + + return this.AuthorizeV2(); + } + + /// + /// Generate the timestamp for the signature. + /// + /// + protected virtual string GenerateTimeStamp() + { + // Default implementation of UNIX time of the current UTC time + TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture); + } + + /// + /// Generate a nonce. + /// + /// + protected virtual string GenerateNonce() + { + // Just a simple implementation of a random number between 123400 and 9999999 + return this.random.Next(123400, 9999999).ToString(CultureInfo.InvariantCulture); + } + private AuthorisationResult AuthorizeV1() { - if (!IsCurrentUserAuthorized()) + if (!this.IsCurrentUserAuthorized()) { - if (!HaveVerificationCode()) + if (!this.HaveVerificationCode()) { string ret = null; - string response = RequestToken(); + string response = this.RequestToken(); if (!string.IsNullOrWhiteSpace(response)) { - //response contains token and token secret. We only need the token. + // response contains token and token secret. We only need the token. NameValueCollection qs = HttpUtility.ParseQueryString(response); if (qs[OAuthCallbackConfirmedKey] != null) @@ -179,11 +336,11 @@ private AuthorisationResult AuthorizeV1() if (qs[OAuthTokenKey] != null) { - ret = AuthorizationEndpoint + "?" + OAuthTokenKey + "=" + qs[OAuthTokenKey]; + ret = this.AuthorizationEndpoint + "?" + OAuthTokenKey + "=" + qs[OAuthTokenKey]; - AuthToken = qs[OAuthTokenKey]; - TokenSecret = qs[OAuthTokenSecretKey]; - SaveTokenCookie("_request"); + this.AuthToken = qs[OAuthTokenKey]; + this.TokenSecret = qs[OAuthTokenSecretKey]; + this.SaveTokenCookie("_request"); } } @@ -195,7 +352,7 @@ private AuthorisationResult AuthorizeV1() return AuthorisationResult.RequestingCode; } - ExchangeRequestTokenForToken(); + this.ExchangeRequestTokenForToken(); } return AuthorisationResult.Authorized; @@ -204,30 +361,30 @@ private AuthorisationResult AuthorizeV1() private AuthorisationResult AuthorizeV2() { string errorReason = HttpContext.Current.Request.Params["error_reason"]; - bool userDenied = (errorReason != null); + bool userDenied = errorReason != null; if (userDenied) { return AuthorisationResult.Denied; } - if (!HaveVerificationCode()) + if (!this.HaveVerificationCode()) { var parameters = new List { - new QueryParameter("scope", Scope), - new QueryParameter(OAuthClientIdKey, APIKey), - new QueryParameter(OAuthRedirectUriKey, HttpContext.Current.Server.UrlEncode(CallbackUri.ToString())), - new QueryParameter("state", Service), - new QueryParameter("response_type", "code") + new QueryParameter("scope", this.Scope), + new QueryParameter(OAuthClientIdKey, this.APIKey), + new QueryParameter(OAuthRedirectUriKey, HttpContext.Current.Server.UrlEncode(this.CallbackUri.ToString())), + new QueryParameter("state", this.Service), + new QueryParameter("response_type", "code"), }; - HttpContext.Current.Response.Redirect(AuthorizationEndpoint + "?" + parameters.ToNormalizedString(), false); + HttpContext.Current.Response.Redirect(this.AuthorizationEndpoint + "?" + parameters.ToNormalizedString(), false); return AuthorisationResult.RequestingCode; } - ExchangeCodeForToken(); + this.ExchangeCodeForToken(); - return String.IsNullOrEmpty(AuthToken) ? AuthorisationResult.Denied : AuthorisationResult.Authorized; + return string.IsNullOrEmpty(this.AuthToken) ? AuthorisationResult.Denied : AuthorisationResult.Authorized; } private string ComputeHash(HashAlgorithm hashAlgorithm, string data) @@ -251,46 +408,49 @@ private string ComputeHash(HashAlgorithm hashAlgorithm, string data) private void ExchangeCodeForToken() { IList parameters = new List(); - parameters.Add(new QueryParameter(OAuthClientIdKey, APIKey)); - parameters.Add(new QueryParameter(OAuthRedirectUriKey, HttpContext.Current.Server.UrlEncode(CallbackUri.ToString()))); - //DNN-6265 Support for OAuth V2 Secrets which are not URL Friendly - parameters.Add(new QueryParameter(OAuthClientSecretKey, HttpContext.Current.Server.UrlEncode(APISecret.ToString()))); + parameters.Add(new QueryParameter(OAuthClientIdKey, this.APIKey)); + parameters.Add(new QueryParameter(OAuthRedirectUriKey, HttpContext.Current.Server.UrlEncode(this.CallbackUri.ToString()))); + + // DNN-6265 Support for OAuth V2 Secrets which are not URL Friendly + parameters.Add(new QueryParameter(OAuthClientSecretKey, HttpContext.Current.Server.UrlEncode(this.APISecret.ToString()))); parameters.Add(new QueryParameter(OAuthGrantTyepKey, "authorization_code")); - parameters.Add(new QueryParameter(OAuthCodeKey, VerificationCode)); + parameters.Add(new QueryParameter(OAuthCodeKey, this.VerificationCode)); - //DNN-6265 Support for OAuth V2 optional parameter - if (!String.IsNullOrEmpty(APIResource)) + // DNN-6265 Support for OAuth V2 optional parameter + if (!string.IsNullOrEmpty(this.APIResource)) { - parameters.Add(new QueryParameter("resource", APIResource)); + parameters.Add(new QueryParameter("resource", this.APIResource)); } - string responseText = ExecuteWebRequest(TokenMethod, TokenEndpoint, parameters.ToNormalizedString(), String.Empty); + string responseText = this.ExecuteWebRequest(this.TokenMethod, this.TokenEndpoint, parameters.ToNormalizedString(), string.Empty); - AuthToken = GetToken(responseText); - AuthTokenExpiry = GetExpiry(responseText); + this.AuthToken = this.GetToken(responseText); + this.AuthTokenExpiry = this.GetExpiry(responseText); } private void ExchangeRequestTokenForToken() { - LoadTokenCookie("_request"); + this.LoadTokenCookie("_request"); - string response = ExecuteAuthorizedRequest(HttpMethod.POST, TokenEndpoint); + string response = this.ExecuteAuthorizedRequest(HttpMethod.POST, this.TokenEndpoint); if (response.Length > 0) { - //Store the Token and Token Secret + // Store the Token and Token Secret NameValueCollection qs = HttpUtility.ParseQueryString(response); if (qs[OAuthTokenKey] != null) { - AuthToken = qs[OAuthTokenKey]; + this.AuthToken = qs[OAuthTokenKey]; } + if (qs[OAuthTokenSecretKey] != null) { - TokenSecret = qs[OAuthTokenSecretKey]; + this.TokenSecret = qs[OAuthTokenSecretKey]; } - if (qs[UserGuidKey] != null) + + if (qs[this.UserGuidKey] != null) { - UserGuid = qs[UserGuidKey]; + this.UserGuid = qs[this.UserGuidKey]; } } } @@ -300,39 +460,40 @@ private string ExecuteAuthorizedRequest(HttpMethod method, Uri uri) string outUrl; List requestParameters; - string nonce = GenerateNonce(); - string timeStamp = GenerateTimeStamp(); - - string verifier = (uri == TokenEndpoint) ? OAuthVerifier: String.Empty; - //Generate Signature - string sig = GenerateSignature(uri, - AuthToken, - TokenSecret, - String.Empty, - verifier, - method.ToString(), - timeStamp, - nonce, - out outUrl, - out requestParameters); - - + string nonce = this.GenerateNonce(); + string timeStamp = this.GenerateTimeStamp(); + + string verifier = (uri == this.TokenEndpoint) ? this.OAuthVerifier : string.Empty; + + // Generate Signature + string sig = this.GenerateSignature( + uri, + this.AuthToken, + this.TokenSecret, + string.Empty, + verifier, + method.ToString(), + timeStamp, + nonce, + out outUrl, + out requestParameters); + var headerParameters = new List { - new QueryParameter(OAuthConsumerKeyKey, APIKey), + new QueryParameter(OAuthConsumerKeyKey, this.APIKey), new QueryParameter(OAuthNonceKey, nonce), new QueryParameter(OAuthSignatureKey, sig), new QueryParameter(OAuthSignatureMethodKey, HMACSHA1SignatureType), new QueryParameter(OAuthTimestampKey, timeStamp), - new QueryParameter(OAuthTokenKey, AuthToken), - new QueryParameter(OAuthVersionKey, OAuthVersion) + new QueryParameter(OAuthTokenKey, this.AuthToken), + new QueryParameter(OAuthVersionKey, this.OAuthVersion), }; - if (uri == TokenEndpoint) + if (uri == this.TokenEndpoint) { - headerParameters.Add(new QueryParameter(OAuthVerifierKey, OAuthVerifier)); + headerParameters.Add(new QueryParameter(OAuthVerifierKey, this.OAuthVerifier)); } - string ret = ExecuteWebRequest(method, uri, String.Empty, headerParameters.ToAuthorizationString()); + string ret = this.ExecuteWebRequest(method, uri, string.Empty, headerParameters.ToAuthorizationString()); return ret; } @@ -348,18 +509,20 @@ private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, request = WebRequest.CreateDefault(uri); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; - //request.ContentType = "text/xml"; + + // request.ContentType = "text/xml"; request.ContentLength = byteArray.Length; - - if (!String.IsNullOrEmpty(OAuthHeaderCode)) - { - byte[] API64 = Encoding.UTF8.GetBytes(APIKey + ":" + APISecret); - string Api64Encoded = System.Convert.ToBase64String(API64); - //Authentication providers needing an "Authorization: Basic/bearer base64(clientID:clientSecret)" header. OAuthHeaderCode might be: Basic/Bearer/empty. - request.Headers.Add("Authorization: " + OAuthHeaderCode + " " + Api64Encoded); - } - - if (!String.IsNullOrEmpty(parameters)) + + if (!string.IsNullOrEmpty(this.OAuthHeaderCode)) + { + byte[] API64 = Encoding.UTF8.GetBytes(this.APIKey + ":" + this.APISecret); + string Api64Encoded = System.Convert.ToBase64String(API64); + + // Authentication providers needing an "Authorization: Basic/bearer base64(clientID:clientSecret)" header. OAuthHeaderCode might be: Basic/Bearer/empty. + request.Headers.Add("Authorization: " + this.OAuthHeaderCode + " " + Api64Encoded); + } + + if (!string.IsNullOrEmpty(parameters)) { Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); @@ -368,11 +531,11 @@ private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, } else { - request = WebRequest.CreateDefault(GenerateRequestUri(uri.ToString(), parameters)); + request = WebRequest.CreateDefault(this.GenerateRequestUri(uri.ToString(), parameters)); } - //Add Headers - if (!String.IsNullOrEmpty(authHeader)) + // Add Headers + if (!string.IsNullOrEmpty(authHeader)) { request.Headers.Add(HttpRequestHeader.Authorization, authHeader); } @@ -406,6 +569,7 @@ private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, } } } + return null; } @@ -421,12 +585,12 @@ private string GenerateSignatureBase(Uri url, string token, string callbackurl, throw new ArgumentNullException("httpMethod"); } - requestParameters = GetQueryParameters(url.Query); - requestParameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion)); + requestParameters = this.GetQueryParameters(url.Query); + requestParameters.Add(new QueryParameter(OAuthVersionKey, this.OAuthVersion)); requestParameters.Add(new QueryParameter(OAuthNonceKey, nonce)); requestParameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp)); requestParameters.Add(new QueryParameter(OAuthSignatureMethodKey, HMACSHA1SignatureType)); - requestParameters.Add(new QueryParameter(OAuthConsumerKeyKey, APIKey)); + requestParameters.Add(new QueryParameter(OAuthConsumerKeyKey, this.APIKey)); if (!string.IsNullOrEmpty(callbackurl)) { @@ -450,6 +614,7 @@ private string GenerateSignatureBase(Uri url, string token, string callbackurl, { normalizedUrl += ":" + url.Port; } + normalizedUrl += url.AbsolutePath; string normalizedRequestParameters = requestParameters.ToNormalizedString(); @@ -463,7 +628,7 @@ private string GenerateSignatureBase(Uri url, string token, string callbackurl, private string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash) { - return ComputeHash(hash, signatureBase); + return this.ComputeHash(hash, signatureBase); } private List GetQueryParameters(string parameters) @@ -503,44 +668,45 @@ private string RequestToken() string outUrl; List requestParameters; - string nonce = GenerateNonce(); - string timeStamp = GenerateTimeStamp(); - - string sig = GenerateSignature(RequestTokenEndpoint, - String.Empty, - String.Empty, - CallbackUri.OriginalString, - String.Empty, - RequestTokenMethod.ToString(), - timeStamp, - nonce, - out outUrl, - out requestParameters); + string nonce = this.GenerateNonce(); + string timeStamp = this.GenerateTimeStamp(); + + string sig = this.GenerateSignature( + this.RequestTokenEndpoint, + string.Empty, + string.Empty, + this.CallbackUri.OriginalString, + string.Empty, + this.RequestTokenMethod.ToString(), + timeStamp, + nonce, + out outUrl, + out requestParameters); var headerParameters = new List { - new QueryParameter(OAuthCallbackKey, CallbackUri.OriginalString), - new QueryParameter(OAuthConsumerKeyKey, APIKey), + new QueryParameter(OAuthCallbackKey, this.CallbackUri.OriginalString), + new QueryParameter(OAuthConsumerKeyKey, this.APIKey), new QueryParameter(OAuthNonceKey, nonce), new QueryParameter(OAuthSignatureKey, sig), new QueryParameter(OAuthSignatureMethodKey, HMACSHA1SignatureType), new QueryParameter(OAuthTimestampKey, timeStamp), - new QueryParameter(OAuthVersionKey, OAuthVersion) + new QueryParameter(OAuthVersionKey, this.OAuthVersion), }; - string ret = ExecuteWebRequest(RequestTokenMethod, new Uri(outUrl), String.Empty, headerParameters.ToAuthorizationString()); + string ret = this.ExecuteWebRequest(this.RequestTokenMethod, new Uri(outUrl), string.Empty, headerParameters.ToAuthorizationString()); return ret; } private void SaveTokenCookie(string suffix) { - var authTokenCookie = new HttpCookie(AuthTokenName + suffix) { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }; - authTokenCookie.Values[OAuthTokenKey] = AuthToken; - authTokenCookie.Values[OAuthTokenSecretKey] = TokenSecret; - authTokenCookie.Values[UserGuidKey] = UserGuid; + var authTokenCookie = new HttpCookie(this.AuthTokenName + suffix) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }; + authTokenCookie.Values[OAuthTokenKey] = this.AuthToken; + authTokenCookie.Values[OAuthTokenSecretKey] = this.TokenSecret; + authTokenCookie.Values[this.UserGuidKey] = this.UserGuid; - authTokenCookie.Expires = DateTime.Now.Add(AuthTokenExpiry); + authTokenCookie.Expires = DateTime.Now.Add(this.AuthTokenExpiry); HttpContext.Current.Response.SetCookie(authTokenCookie); } @@ -552,32 +718,7 @@ private Uri GenerateRequestUri(string url, string parameters) } return new Uri(string.Format("{0}{1}{2}", url, url.Contains("?") ? "&" : "?", parameters)); - } - - #endregion - - #region Protected Methods - - /// - /// Generate the timestamp for the signature - /// - /// - protected virtual string GenerateTimeStamp() - { - // Default implementation of UNIX time of the current UTC time - TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); - return Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture); - } - - /// - /// Generate a nonce - /// - /// - protected virtual string GenerateNonce() - { - // Just a simple implementation of a random number between 123400 and 9999999 - return random.Next(123400, 9999999).ToString(CultureInfo.InvariantCulture); - } + } protected virtual TimeSpan GetExpiry(string responseText) { @@ -591,228 +732,89 @@ protected virtual string GetToken(string responseText) protected void LoadTokenCookie(string suffix) { - HttpCookie authTokenCookie = HttpContext.Current.Request.Cookies[AuthTokenName + suffix]; + HttpCookie authTokenCookie = HttpContext.Current.Request.Cookies[this.AuthTokenName + suffix]; if (authTokenCookie != null) { if (authTokenCookie.HasKeys) { - AuthToken = authTokenCookie.Values[OAuthTokenKey]; - TokenSecret = authTokenCookie.Values[OAuthTokenSecretKey]; - UserGuid = authTokenCookie.Values[UserGuidKey]; + this.AuthToken = authTokenCookie.Values[OAuthTokenKey]; + this.TokenSecret = authTokenCookie.Values[OAuthTokenSecretKey]; + this.UserGuid = authTokenCookie.Values[this.UserGuidKey]; } } - } - - #endregion - - public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action addCustomProperties, Action onAuthenticated) - { - var loginStatus = UserLoginStatus.LOGIN_FAILURE; - - string userName = PrefixServiceToUserName ? Service + "-" + user.Id : user.Id; - string token = Service + "-" + user.Id; - - UserInfo objUserInfo; - - if (AutoMatchExistingUsers) - { - objUserInfo = MembershipProvider.Instance().GetUserByUserName(settings.PortalId, userName); - if (objUserInfo != null) - { - //user already exists... lets check for a token next... - var dnnAuthToken = MembershipProvider.Instance().GetUserByAuthToken(settings.PortalId, token, Service); - if (dnnAuthToken == null) - { - DataProvider.Instance().AddUserAuthentication(objUserInfo.UserID, Service, token, objUserInfo.UserID); - } - } - } - - objUserInfo = UserController.ValidateUser(settings.PortalId, userName, "", - Service, token, - settings.PortalName, IPAddress, - ref loginStatus); - - - //Raise UserAuthenticated Event - var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, token, loginStatus, Service) - { - AutoRegister = true, - UserName = userName, - }; - - var profileProperties = new NameValueCollection(); - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName))) - { - profileProperties.Add("FirstName", user.FirstName); - } - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName))) - { - profileProperties.Add("LastName", user.LastName); - } - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email))) - { - profileProperties.Add("Email", user.PreferredEmail); - } - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.DisplayName))) - { - profileProperties.Add("DisplayName", user.DisplayName); - } - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.ProfileImage))) - { - profileProperties.Add("ProfileImage", user.ProfileImage); - } - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website))) - { - profileProperties.Add("Website", user.Website); - } - if ((objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale")))) && !string.IsNullOrEmpty(user.Locale)) - { - if (LocaleController.IsValidCultureName(user.Locale.Replace('_', '-'))) - { - profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-')); - } - else - { - profileProperties.Add("PreferredLocale", settings.CultureCode); - } - } - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone")))) - { - if (String.IsNullOrEmpty(user.TimeZoneInfo)) - { - int timeZone; - if (Int32.TryParse(user.Timezone, out timeZone)) - { - var timeZoneInfo = Localization.Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone); - - profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id); - } - } - else - { - profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo); - } - } - - addCustomProperties(profileProperties); - - eventArgs.Profile = profileProperties; - - if (Mode == AuthMode.Login) - { - SaveTokenCookie(String.Empty); - } - - onAuthenticated(eventArgs); - } - - public virtual AuthorisationResult Authorize() - { - if (OAuthVersion == "1.0") - { - return AuthorizeV1(); - } - return AuthorizeV2(); - } + } /// - /// Generates a signature using the HMAC-SHA1 algorithm + /// Generates a signature using the HMAC-SHA1 algorithm. /// - /// The full url that needs to be signed including its non OAuth url parameters - /// The token, if available. If not available pass null or an empty string - /// The token secret, if available. If not available pass null or an empty string + /// The full url that needs to be signed including its non OAuth url parameters. + /// The token, if available. If not available pass null or an empty string. + /// The token secret, if available. If not available pass null or an empty string. /// - /// This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string - /// The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc) + /// This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string. + /// The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc). /// /// /// /// - /// A base64 string of the hash value + /// A base64 string of the hash value. public string GenerateSignature(Uri url, string token, string tokenSecret, string callbackurl, string oauthVerifier, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out List requestParameters) { - string signatureBase = GenerateSignatureBase(url, token, callbackurl, oauthVerifier, httpMethod, timeStamp, nonce, out normalizedUrl, out requestParameters); + string signatureBase = this.GenerateSignatureBase(url, token, callbackurl, oauthVerifier, httpMethod, timeStamp, nonce, out normalizedUrl, out requestParameters); - var hmacsha1 = new HMACSHA1 - { - Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(APISecret), + var hmacsha1 = new HMACSHA1 + { + Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(this.APISecret), string.IsNullOrEmpty(tokenSecret) - ? "" - : UrlEncode(tokenSecret))) - }; + ? string.Empty + : UrlEncode(tokenSecret))), + }; - return GenerateSignatureUsingHash(signatureBase, hmacsha1); + return this.GenerateSignatureUsingHash(signatureBase, hmacsha1); } - public virtual TUserData GetCurrentUser() where TUserData : UserData + public virtual TUserData GetCurrentUser() + where TUserData : UserData { - LoadTokenCookie(String.Empty); + this.LoadTokenCookie(string.Empty); - if (!IsCurrentUserAuthorized()) + if (!this.IsCurrentUserAuthorized()) { return null; } - var accessToken = string.IsNullOrEmpty(AccessToken) ? "access_token=" + AuthToken : AccessToken + "=" + AuthToken; - string responseText = (OAuthVersion == "1.0") - ? ExecuteAuthorizedRequest(HttpMethod.GET, MeGraphEndpoint) - : ExecuteWebRequest(HttpMethod.GET, GenerateRequestUri(MeGraphEndpoint.ToString(), accessToken), null, String.Empty); + var accessToken = string.IsNullOrEmpty(this.AccessToken) ? "access_token=" + this.AuthToken : this.AccessToken + "=" + this.AuthToken; + string responseText = (this.OAuthVersion == "1.0") + ? this.ExecuteAuthorizedRequest(HttpMethod.GET, this.MeGraphEndpoint) + : this.ExecuteWebRequest(HttpMethod.GET, this.GenerateRequestUri(this.MeGraphEndpoint.ToString(), accessToken), null, string.Empty); var user = Json.Deserialize(responseText); return user; } public bool HaveVerificationCode() { - return (OAuthVersion == "1.0") ? (OAuthVerifier != null) : (VerificationCode != null); + return (this.OAuthVersion == "1.0") ? (this.OAuthVerifier != null) : (this.VerificationCode != null); } public bool IsCurrentService() { string service = HttpContext.Current.Request.Params["state"]; - return !String.IsNullOrEmpty(service) && service == Service; + return !string.IsNullOrEmpty(service) && service == this.Service; } - public Boolean IsCurrentUserAuthorized() + public bool IsCurrentUserAuthorized() { - return !String.IsNullOrEmpty(AuthToken); + return !string.IsNullOrEmpty(this.AuthToken); } public void RemoveToken() { - var authTokenCookie = new HttpCookie(AuthTokenName) + var authTokenCookie = new HttpCookie(this.AuthTokenName) { Expires = DateTime.Now.AddDays(-30), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; HttpContext.Current.Response.SetCookie(authTokenCookie); } - - /// - /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case. - /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth - /// - /// The value to Url encode - /// Returns a Url encoded string - public static string UrlEncode(string value) - { - var result = new StringBuilder(); - - foreach (char symbol in value) - { - if (UnreservedChars.IndexOf(symbol) != -1) - { - result.Append(symbol); - } - else - { - result.Append('%' + String.Format("{0:X2}", (int)symbol)); - } - } - - return result.ToString(); - } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs index bd012b06acd..4b651264932 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication.OAuth { - + using System; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + /// /// The Config class provides a central area for management of Module Configuration Settings. /// @@ -23,50 +22,45 @@ public class OAuthConfigBase : AuthenticationConfigBase protected OAuthConfigBase(string service, int portalId) : base(portalId) { - Service = service; - - var portalApiKey = PortalController.GetPortalSetting(this.Service + "_APIKey", portalId, ""); - var hostApiKey = ""; + this.Service = service; + + var portalApiKey = PortalController.GetPortalSetting(this.Service + "_APIKey", portalId, string.Empty); + var hostApiKey = string.Empty; if (string.IsNullOrEmpty(portalApiKey)) { - hostApiKey = HostController.Instance.GetString(this.Service + "_APIKey", ""); - HostConfig = !string.IsNullOrEmpty(hostApiKey); + hostApiKey = HostController.Instance.GetString(this.Service + "_APIKey", string.Empty); + this.HostConfig = !string.IsNullOrEmpty(hostApiKey); } else { - HostConfig = false; + this.HostConfig = false; } - if (HostConfig) + if (this.HostConfig) { - APIKey = hostApiKey; - APISecret = HostController.Instance.GetString(Service + "_APISecret", ""); - Enabled = HostController.Instance.GetBoolean(Service + "_Enabled", false); + this.APIKey = hostApiKey; + this.APISecret = HostController.Instance.GetString(this.Service + "_APISecret", string.Empty); + this.Enabled = HostController.Instance.GetBoolean(this.Service + "_Enabled", false); } else { - APIKey = portalApiKey; - APISecret = PortalController.GetPortalSetting(Service + "_APISecret", portalId, ""); - Enabled = PortalController.GetPortalSettingAsBoolean(Service + "_Enabled", portalId, false); + this.APIKey = portalApiKey; + this.APISecret = PortalController.GetPortalSetting(this.Service + "_APISecret", portalId, string.Empty); + this.Enabled = PortalController.GetPortalSettingAsBoolean(this.Service + "_Enabled", portalId, false); } } - protected string Service { get; set; } - public string APIKey { get; set; } public string APISecret { get; set; } + protected string Service { get; set; } + public bool Enabled { get; set; } public bool HostConfig { get; set; } - private static string GetCacheKey(string service, int portalId) - { - return _cacheKey + "." + service + "_" + portalId; - } - public static void ClearConfig(string service, int portalId) { DataCache.RemoveCache(GetCacheKey(service, portalId)); @@ -81,9 +75,15 @@ public static OAuthConfigBase GetConfig(string service, int portalId) config = new OAuthConfigBase(service, portalId); DataCache.SetCache(key, config); } + return config; } + private static string GetCacheKey(string service, int portalId) + { + return _cacheKey + "." + service + "_" + portalId; + } + public static void UpdateConfig(OAuthConfigBase config) { if (config.HostConfig) diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs index 763861f4b65..b026e4d8830 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Web; -using DotNetNuke.Common; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication.OAuth { + using System; + using System.Collections.Specialized; + using System.Web; + + using DotNetNuke.Common; + public abstract class OAuthLoginBase : AuthenticationLoginBase { + public override bool Enabled + { + get { return OAuthConfigBase.GetConfig(this.AuthSystemApplicationName, this.PortalId).Enabled; } + } + protected virtual string AuthSystemApplicationName { - get { return String.Empty; } + get { return string.Empty; } } protected OAuthClientBase OAuthClient { get; set; } @@ -26,45 +27,35 @@ protected virtual string AuthSystemApplicationName protected virtual void AddCustomProperties(NameValueCollection properties) { - } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (!IsPostBack) + if (!this.IsPostBack) { - //Save the return Url in the cookie - HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", RedirectURL) + // Save the return Url in the cookie + HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", this.RedirectURL) { Expires = DateTime.Now.AddMinutes(5), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }); } - bool shouldAuthorize = OAuthClient.IsCurrentService() && OAuthClient.HaveVerificationCode(); - if(Mode == AuthMode.Login) + bool shouldAuthorize = this.OAuthClient.IsCurrentService() && this.OAuthClient.HaveVerificationCode(); + if (this.Mode == AuthMode.Login) { - shouldAuthorize = shouldAuthorize || OAuthClient.IsCurrentUserAuthorized(); + shouldAuthorize = shouldAuthorize || this.OAuthClient.IsCurrentUserAuthorized(); } if (shouldAuthorize) { - if (OAuthClient.Authorize() == AuthorisationResult.Authorized) + if (this.OAuthClient.Authorize() == AuthorisationResult.Authorized) { - OAuthClient.AuthenticateUser(GetCurrentUser(), PortalSettings, IPAddress, AddCustomProperties, OnUserAuthenticated); + this.OAuthClient.AuthenticateUser(this.GetCurrentUser(), this.PortalSettings, this.IPAddress, this.AddCustomProperties, this.OnUserAuthenticated); } } - } - - #region Overrides of AuthenticationLoginBase - - public override bool Enabled - { - get { return OAuthConfigBase.GetConfig(AuthSystemApplicationName, PortalId).Enabled; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs index 5c4c84faafa..3ae16d4506f 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs @@ -1,24 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication.OAuth { + using System; + using System.Linq; + + using DotNetNuke.UI.WebControls; + public class OAuthSettingsBase : AuthenticationSettingsBase { protected PropertyEditorControl SettingsEditor; - protected virtual string AuthSystemApplicationName { get { return String.Empty; } } + protected virtual string AuthSystemApplicationName + { + get { return string.Empty; } + } public override void UpdateSettings() { - if (SettingsEditor.IsValid && SettingsEditor.IsDirty) + if (this.SettingsEditor.IsValid && this.SettingsEditor.IsDirty) { - var config = (OAuthConfigBase)SettingsEditor.DataSource; + var config = (OAuthConfigBase)this.SettingsEditor.DataSource; OAuthConfigBase.UpdateConfig(config); } } @@ -27,9 +31,9 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - OAuthConfigBase config = OAuthConfigBase.GetConfig(AuthSystemApplicationName, PortalId); - SettingsEditor.DataSource = config; - SettingsEditor.DataBind(); + OAuthConfigBase config = OAuthConfigBase.GetConfig(this.AuthSystemApplicationName, this.PortalId); + this.SettingsEditor.DataSource = config; + this.SettingsEditor.DataBind(); } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/QueryParameter.cs b/DNN Platform/Library/Services/Authentication/OAuth/QueryParameter.cs index 038fee5168c..62073bac12f 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/QueryParameter.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/QueryParameter.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Authentication.OAuth { /// - /// Provides an internal structure to sort the query parameter + /// Provides an internal structure to sort the query parameter. /// public class QueryParameter { @@ -15,8 +15,8 @@ public QueryParameter(string name, string value) this.Value = value; } - public string Name { get;private set; } + public string Name { get; private set; } - public string Value { get;private set; } + public string Value { get; private set; } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs b/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs index 9042391f0ce..8342504beff 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs @@ -1,32 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication.OAuth { + using System; + using System.Collections.Generic; + /// - /// Comparer class used to perform the sorting of the query parameters + /// Comparer class used to perform the sorting of the query parameters. /// internal class QueryParameterComparer : IComparer - { - #region IComparer Members - + { public int Compare(QueryParameter x, QueryParameter y) { if (x.Name == y.Name) { - return String.CompareOrdinal(x.Value, y.Value); + return string.CompareOrdinal(x.Value, y.Value); } - return String.CompareOrdinal(x.Name, y.Name); - } - - #endregion + + return string.CompareOrdinal(x.Name, y.Name); + } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs b/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs index a8d860f4792..9aabc792fab 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Runtime.Serialization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication.OAuth { + using System; + using System.Collections.Generic; + using System.Runtime.Serialization; + [DataContract] public class UserData { @@ -22,8 +17,9 @@ public virtual string DisplayName { get { - return Name; + return this.Name; } + set { } } @@ -37,9 +33,10 @@ public virtual string FirstName { get { - return (!String.IsNullOrEmpty(Name) && Name.IndexOf(" ", StringComparison.Ordinal) > 0) ? Name.Substring(0, Name.IndexOf(" ", StringComparison.Ordinal)) : String.Empty; + return (!string.IsNullOrEmpty(this.Name) && this.Name.IndexOf(" ", StringComparison.Ordinal) > 0) ? this.Name.Substring(0, this.Name.IndexOf(" ", StringComparison.Ordinal)) : string.Empty; } - set { Name = value + " " + LastName; } + + set { this.Name = value + " " + this.LastName; } } [DataMember(Name = "gender")] @@ -49,10 +46,10 @@ public virtual string LastName { get { - return (!String.IsNullOrEmpty(Name) && Name.IndexOf(" ", StringComparison.Ordinal) > 0) ? Name.Substring(Name.IndexOf(" ", StringComparison.Ordinal) + 1) : Name; + return (!string.IsNullOrEmpty(this.Name) && this.Name.IndexOf(" ", StringComparison.Ordinal) > 0) ? this.Name.Substring(this.Name.IndexOf(" ", StringComparison.Ordinal) + 1) : this.Name; } - set { Name = FirstName + " " + value; } - + + set { this.Name = this.FirstName + " " + value; } } [DataMember(Name = "locale")] @@ -61,15 +58,16 @@ public virtual string LastName [DataMember(Name = "name")] public virtual string Name { get; set; } - public string PreferredEmail - { + public string PreferredEmail + { get { - if (Emails == null) + if (this.Emails == null) { - return Email; + return this.Email; } - return Emails.PreferredEmail; + + return this.Emails.PreferredEmail; } } diff --git a/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs b/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs index a798b4b8c5a..091f6bee904 100644 --- a/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs +++ b/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs @@ -1,116 +1,112 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Membership; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + using System.Collections.Specialized; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + /// ----------------------------------------------------------------------------- /// /// The UserAuthenticatedEventArgs class provides a custom EventArgs object for the - /// UserAuthenticated event + /// UserAuthenticated event. /// /// ----------------------------------------------------------------------------- public class UserAuthenticatedEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// All properties Constructor. /// /// The user being authenticated. - /// The user token + /// The user token. /// The login status. - /// The type of Authentication + /// The type of Authentication. /// ----------------------------------------------------------------------------- public UserAuthenticatedEventArgs(UserInfo user, string token, UserLoginStatus status, string type) { - Profile = new NameValueCollection(); - Message = String.Empty; - AutoRegister = false; - Authenticated = true; - User = user; - LoginStatus = status; - UserToken = token; - AuthenticationType = type; - RememberMe = false; + this.Profile = new NameValueCollection(); + this.Message = string.Empty; + this.AutoRegister = false; + this.Authenticated = true; + this.User = user; + this.LoginStatus = status; + this.UserToken = token; + this.AuthenticationType = type; + this.RememberMe = false; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a flag that determines whether the User was authenticated + /// Gets or sets a value indicating whether gets and sets a flag that determines whether the User was authenticated. /// /// ----------------------------------------------------------------------------- public bool Authenticated { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Authentication Type + /// Gets or sets and sets the Authentication Type. /// /// ----------------------------------------------------------------------------- public string AuthenticationType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets a flag that determines whether the user should be automatically registered + /// Gets or sets a value indicating whether gets and sets a flag that determines whether the user should be automatically registered. /// /// ----------------------------------------------------------------------------- public bool AutoRegister { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Login Status + /// Gets or sets and sets the Login Status. /// /// ----------------------------------------------------------------------------- public UserLoginStatus LoginStatus { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Message + /// Gets or sets and sets the Message. /// /// ----------------------------------------------------------------------------- public string Message { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Profile + /// Gets or sets and sets the Profile. /// /// ----------------------------------------------------------------------------- public NameValueCollection Profile { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the RememberMe setting + /// Gets or sets a value indicating whether gets and sets the RememberMe setting. /// /// ----------------------------------------------------------------------------- public bool RememberMe { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the User + /// Gets or sets and sets the User. /// /// ----------------------------------------------------------------------------- public UserInfo User { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the UserToken (the userid or authenticated id) + /// Gets or sets and sets the UserToken (the userid or authenticated id). /// /// ----------------------------------------------------------------------------- public string UserToken { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Username + /// Gets or sets and sets the Username. /// /// ----------------------------------------------------------------------------- public string UserName { get; set; } diff --git a/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs b/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs index 90520227e6f..297602667a6 100644 --- a/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs +++ b/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs @@ -1,109 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Authentication { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// /// DNN-4016 - /// The UserAuthenticationInfo class provides the Entity Layer for the + /// The UserAuthenticationInfo class provides the Entity Layer for the /// user information in the Authentication Systems. /// [Serializable] public class UserAuthenticationInfo : BaseEntityInfo, IHydratable - { - - #region Private Members - + { public UserAuthenticationInfo() { - AuthenticationToken = Null.NullString; - AuthenticationType = Null.NullString; - UserAuthenticationID = Null.NullInteger; - } - - #endregion - - #region Public Properties - + this.AuthenticationToken = Null.NullString; + this.AuthenticationType = Null.NullString; + this.UserAuthenticationID = Null.NullInteger; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the ID of the User Record in the Authentication System + /// Gets or sets and Sets the ID of the User Record in the Authentication System. /// /// ----------------------------------------------------------------------------- public int UserAuthenticationID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the PackageID for the Authentication System + /// Gets or sets and Sets the PackageID for the Authentication System. /// /// ----------------------------------------------------------------------------- public int UserID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the type (name) of the Authentication System (eg DNN, OpenID, LiveID) + /// Gets or sets and Sets the type (name) of the Authentication System (eg DNN, OpenID, LiveID). /// /// ----------------------------------------------------------------------------- public string AuthenticationType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the url for the Logoff Control + /// Gets or sets and Sets the url for the Logoff Control. /// /// ----------------------------------------------------------------------------- - public string AuthenticationToken { get; set; } - - #endregion - - #region IHydratable Members + public string AuthenticationToken { get; set; } /// ----------------------------------------------------------------------------- /// - /// Fills a UserAuthenticationInfo from a Data Reader + /// Gets or sets and sets the Key ID. /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public virtual void Fill(IDataReader dr) - { - UserAuthenticationID = Null.SetNullInteger(dr["UserAuthenticationID"]); - UserID = Null.SetNullInteger(dr["UserID"]); - AuthenticationType = Null.SetNullString(dr["AuthenticationType"]); - AuthenticationToken = Null.SetNullString(dr["AuthenticationToken"]); - - //Fill base class fields - FillInternal(dr); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public virtual int KeyID { get { - return UserAuthenticationID; + return this.UserAuthenticationID; } + set { - UserAuthenticationID = value; + this.UserAuthenticationID = value; } - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a UserAuthenticationInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public virtual void Fill(IDataReader dr) + { + this.UserAuthenticationID = Null.SetNullInteger(dr["UserAuthenticationID"]); + this.UserID = Null.SetNullInteger(dr["UserID"]); + this.AuthenticationType = Null.SetNullString(dr["AuthenticationType"]); + this.AuthenticationToken = Null.SetNullString(dr["AuthenticationToken"]); - #endregion + // Fill base class fields + this.FillInternal(dr); + } } } diff --git a/DNN Platform/Library/Services/Cache/CachingProvider.cs b/DNN Platform/Library/Services/Cache/CachingProvider.cs index e3cde938474..621dd4fcb65 100644 --- a/DNN Platform/Library/Services/Cache/CachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/CachingProvider.cs @@ -1,65 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Caching; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Cache { - /// - /// CachingProvider provides basic component of cache system, by default it will use HttpRuntime.Cache. - /// - /// - /// Using cache will speed up the application to a great degree, we recommend to use cache for whole modules, - /// but sometimes cache also make confuse for user, if we didn't take care of how to make cache expired when needed, - /// such as if a data has already been deleted but the cache arn't clear, it will cause un expected errors. - /// so you should choose a correct performance setting type when you trying to cache some stuff, and always remember - /// update cache immediately after the data changed. - /// - /// - /// - /// public static void ClearCache(string cachePrefix) + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + + /// + /// CachingProvider provides basic component of cache system, by default it will use HttpRuntime.Cache. + /// + /// + /// Using cache will speed up the application to a great degree, we recommend to use cache for whole modules, + /// but sometimes cache also make confuse for user, if we didn't take care of how to make cache expired when needed, + /// such as if a data has already been deleted but the cache arn't clear, it will cause un expected errors. + /// so you should choose a correct performance setting type when you trying to cache some stuff, and always remember + /// update cache immediately after the data changed. + /// + /// + /// + /// public static void ClearCache(string cachePrefix) /// { /// CachingProvider.Instance().Clear("Prefix", GetDnnCacheKey(cachePrefix)); - /// } - /// - /// + /// } + /// + /// public abstract class CachingProvider - { - #region Private Members - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CachingProvider)); + { + private const string CachePrefix = "DNN_"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CachingProvider)); private static System.Web.Caching.Cache _cache; - private const string CachePrefix = "DNN_"; - - #endregion - - #region Protected Properties - - /// - /// Gets the default cache provider. - /// - /// HttpRuntime.Cache + + /// + /// Gets the default cache provider. + /// + /// HttpRuntime.Cache. protected static System.Web.Caching.Cache Cache { get @@ -68,83 +58,147 @@ protected static System.Web.Caching.Cache Cache } } - /// - /// Whether current caching provider disabled to expire cache. - /// - /// This setting shouldn't affect current server, cache should always expire in current server even this setting set to True. - protected static bool CacheExpirationDisable { get; private set; } - - #endregion - - #region Shared/Static Methods - - /// - /// Cleans the cache key by remove cache key prefix. - /// - /// The cache key. - /// cache key without prefix. - /// cache key is empty. + /// + /// Gets a value indicating whether whether current caching provider disabled to expire cache. + /// + /// This setting shouldn't affect current server, cache should always expire in current server even this setting set to True. + protected static bool CacheExpirationDisable { get; private set; } + + /// + /// Cleans the cache key by remove cache key prefix. + /// + /// The cache key. + /// cache key without prefix. + /// cache key is empty. public static string CleanCacheKey(string CacheKey) { - if (String.IsNullOrEmpty(CacheKey)) + if (string.IsNullOrEmpty(CacheKey)) { throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); } + return CacheKey.Substring(CachePrefix.Length); } - /// - /// Gets the cache key with key prefix. - /// - /// The cache key. - /// CachePrefix + CacheKey - /// Cache key is empty. + /// + /// Gets the cache key with key prefix. + /// + /// The cache key. + /// CachePrefix + CacheKey. + /// Cache key is empty. public static string GetCacheKey(string CacheKey) { if (string.IsNullOrEmpty(CacheKey)) { throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); } + return CachePrefix + CacheKey; } - /// - /// Instances of caching provider. - /// - /// The Implemments provider of cache system defind in web.config. + /// + /// Instances of caching provider. + /// + /// The Implemments provider of cache system defind in web.config. public static CachingProvider Instance() { return ComponentFactory.GetComponent(); } - /// - /// Disable Cache Expirataion. This control won't affect core caching provider, its behavior determined by extended caching provider. - /// This property designed for when process long time action, extended caching provider should not sync cache between web servers to improve performance. - /// - /// - internal static void DisableCacheExpiration() - { - CacheExpirationDisable = true; - Logger.Warn("Disable cache expiration."); - - } - - /// - /// Enable Cache Expirataion. This control won't affect core caching provider, its behavior determined by extended caching provider. - /// This property designed for when process long time action, extended caching provider should not sync cache between web servers to improve performance. - /// - /// - internal static void EnableCacheExpiration() - { - CacheExpirationDisable = false; - DataCache.ClearHostCache(true); - Logger.Warn("Enable cache expiration."); - } - - #endregion - - #region Private Methods - + /// + /// Clears the specified type. + /// + /// The type. + /// The data. + public virtual void Clear(string type, string data) + { + this.ClearCacheInternal(type, data, false); + } + + public virtual IDictionaryEnumerator GetEnumerator() + { + return Cache.GetEnumerator(); + } + + /// + /// Disable Cache Expirataion. This control won't affect core caching provider, its behavior determined by extended caching provider. + /// This property designed for when process long time action, extended caching provider should not sync cache between web servers to improve performance. + /// + /// + internal static void DisableCacheExpiration() + { + CacheExpirationDisable = true; + Logger.Warn("Disable cache expiration."); + } + + /// + /// Enable Cache Expirataion. This control won't affect core caching provider, its behavior determined by extended caching provider. + /// This property designed for when process long time action, extended caching provider should not sync cache between web servers to improve performance. + /// + /// + internal static void EnableCacheExpiration() + { + CacheExpirationDisable = false; + DataCache.ClearHostCache(true); + Logger.Warn("Enable cache expiration."); + } + + /// + /// Clears the cache internal. + /// + /// Type of the cache. + /// The data. + /// if set to true clear runtime cache. + protected void ClearCacheInternal(string cacheType, string data, bool clearRuntime) + { + switch (cacheType) + { + case "Prefix": + this.ClearCacheInternal(data, clearRuntime); + break; + case "Host": + this.ClearHostCacheInternal(clearRuntime); + break; + case "Folder": + this.ClearFolderCacheInternal(int.Parse(data), clearRuntime); + break; + case "Module": + this.ClearModuleCacheInternal(int.Parse(data), clearRuntime); + break; + case "ModulePermissionsByPortal": + this.ClearModulePermissionsCachesByPortalInternal(int.Parse(data), clearRuntime); + break; + case "Portal": + this.ClearPortalCacheInternal(int.Parse(data), false, clearRuntime); + break; + case "PortalCascade": + this.ClearPortalCacheInternal(int.Parse(data), true, clearRuntime); + break; + case "Tab": + this.ClearTabCacheInternal(int.Parse(data), clearRuntime); + break; + case "ServiceFrameworkRoutes": + this.ReloadServicesFrameworkRoutes(); + break; + } + } + + /// + /// Removes the internal. + /// + /// The cache key. + protected void RemoveInternal(string cacheKey) + { + // attempt remove from private dictionary + DataCache.RemoveFromPrivateDictionary(cacheKey); + + // remove item from memory + if (Cache[cacheKey] != null) + { + Cache.Remove(cacheKey); + } + } + private void ClearCacheInternal(string prefix, bool clearRuntime) { foreach (DictionaryEntry objDictionaryEntry in HttpRuntime.Cache) @@ -153,13 +207,13 @@ private void ClearCacheInternal(string prefix, bool clearRuntime) { if (clearRuntime) { - //remove item from runtime cache - RemoveInternal(Convert.ToString(objDictionaryEntry.Key)); + // remove item from runtime cache + this.RemoveInternal(Convert.ToString(objDictionaryEntry.Key)); } else { - //Call provider's remove method - Remove(Convert.ToString(objDictionaryEntry.Key)); + // Call provider's remove method + this.Remove(Convert.ToString(objDictionaryEntry.Key)); } } } @@ -167,60 +221,61 @@ private void ClearCacheInternal(string prefix, bool clearRuntime) private void ClearCacheKeysByPortalInternal(int portalId, bool clearRuntime) { - RemoveFormattedCacheKey(DataCache.PortalCacheKey, clearRuntime, Null.NullInteger, string.Empty); - RemoveFormattedCacheKey(DataCache.LocalesCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.ProfileDefinitionsCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.ListsCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.SkinsCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.PortalUserCountCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.PackagesCacheKey, clearRuntime, portalId); - - RemoveCacheKey(DataCache.AllPortalsCacheKey, clearRuntime); + this.RemoveFormattedCacheKey(DataCache.PortalCacheKey, clearRuntime, Null.NullInteger, string.Empty); + this.RemoveFormattedCacheKey(DataCache.LocalesCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.ProfileDefinitionsCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.ListsCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.SkinsCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.PortalUserCountCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.PackagesCacheKey, clearRuntime, portalId); + + this.RemoveCacheKey(DataCache.AllPortalsCacheKey, clearRuntime); } private void ClearDesktopModuleCacheInternal(int portalId, bool clearRuntime) { - RemoveFormattedCacheKey(DataCache.DesktopModuleCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.PortalDesktopModuleCacheKey, clearRuntime, portalId); - RemoveCacheKey(DataCache.ModuleDefinitionCacheKey, clearRuntime); - RemoveCacheKey(DataCache.ModuleControlsCacheKey, clearRuntime); + this.RemoveFormattedCacheKey(DataCache.DesktopModuleCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.PortalDesktopModuleCacheKey, clearRuntime, portalId); + this.RemoveCacheKey(DataCache.ModuleDefinitionCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.ModuleControlsCacheKey, clearRuntime); } private void ClearFolderCacheInternal(int portalId, bool clearRuntime) { - RemoveFormattedCacheKey(DataCache.FolderCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.FolderCacheKey, clearRuntime, portalId); // FolderUserCacheKey also includes permissions and userId but we don't have that information // here so we remove them using a prefix var folderUserCachePrefix = GetCacheKey(string.Format("Folders|{0}|", portalId)); - ClearCacheInternal(folderUserCachePrefix, clearRuntime); + this.ClearCacheInternal(folderUserCachePrefix, clearRuntime); - PermissionProvider.ResetCacheDependency(portalId, - () => RemoveFormattedCacheKey(DataCache.FolderPermissionCacheKey, clearRuntime, portalId)); + PermissionProvider.ResetCacheDependency( + portalId, + () => this.RemoveFormattedCacheKey(DataCache.FolderPermissionCacheKey, clearRuntime, portalId)); } private void ClearHostCacheInternal(bool clearRuntime) { - RemoveCacheKey(DataCache.HostSettingsCacheKey, clearRuntime); - RemoveCacheKey(DataCache.SecureHostSettingsCacheKey, clearRuntime); - RemoveCacheKey(DataCache.UnSecureHostSettingsCacheKey, clearRuntime); - RemoveCacheKey(DataCache.PortalAliasCacheKey, clearRuntime); - RemoveCacheKey("CSS", clearRuntime); - RemoveCacheKey("StyleSheets", clearRuntime); - RemoveCacheKey(DataCache.DesktopModulePermissionCacheKey, clearRuntime); - RemoveCacheKey("GetRoles", clearRuntime); - RemoveCacheKey("CompressionConfig", clearRuntime); - RemoveCacheKey(DataCache.SubscriptionTypesCacheKey, clearRuntime); - RemoveCacheKey(DataCache.PackageTypesCacheKey, clearRuntime); - RemoveCacheKey(DataCache.PermissionsCacheKey, clearRuntime); - RemoveCacheKey(DataCache.ContentTypesCacheKey, clearRuntime); - RemoveCacheKey(DataCache.JavaScriptLibrariesCacheKey, clearRuntime); - - //Clear "portal keys" for Host - ClearFolderCacheInternal(-1, clearRuntime); - ClearDesktopModuleCacheInternal(-1, clearRuntime); - ClearCacheKeysByPortalInternal(-1, clearRuntime); - ClearTabCacheInternal(-1, clearRuntime); + this.RemoveCacheKey(DataCache.HostSettingsCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.SecureHostSettingsCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.UnSecureHostSettingsCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.PortalAliasCacheKey, clearRuntime); + this.RemoveCacheKey("CSS", clearRuntime); + this.RemoveCacheKey("StyleSheets", clearRuntime); + this.RemoveCacheKey(DataCache.DesktopModulePermissionCacheKey, clearRuntime); + this.RemoveCacheKey("GetRoles", clearRuntime); + this.RemoveCacheKey("CompressionConfig", clearRuntime); + this.RemoveCacheKey(DataCache.SubscriptionTypesCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.PackageTypesCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.PermissionsCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.ContentTypesCacheKey, clearRuntime); + this.RemoveCacheKey(DataCache.JavaScriptLibrariesCacheKey, clearRuntime); + + // Clear "portal keys" for Host + this.ClearFolderCacheInternal(-1, clearRuntime); + this.ClearDesktopModuleCacheInternal(-1, clearRuntime); + this.ClearCacheKeysByPortalInternal(-1, clearRuntime); + this.ClearTabCacheInternal(-1, clearRuntime); } private void ClearModuleCacheInternal(int tabId, bool clearRuntime) @@ -232,109 +287,116 @@ private void ClearModuleCacheInternal(int tabId, bool clearRuntime) foreach (var moduleInfo in tabModules.Values) { cacheKey = string.Format(DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID); - if (clearRuntime) - RemoveInternal(cacheKey); - else - Remove(cacheKey); + if (clearRuntime) + { + this.RemoveInternal(cacheKey); + } + else + { + this.Remove(cacheKey); + } } } - RemoveFormattedCacheKey(DataCache.TabModuleCacheKey, clearRuntime, tabId); - RemoveFormattedCacheKey(DataCache.PublishedTabModuleCacheKey, clearRuntime, tabId); - RemoveFormattedCacheKey(DataCache.ModulePermissionCacheKey, clearRuntime, tabId); - RemoveFormattedCacheKey(DataCache.ModuleSettingsCacheKey, clearRuntime, tabId); + this.RemoveFormattedCacheKey(DataCache.TabModuleCacheKey, clearRuntime, tabId); + this.RemoveFormattedCacheKey(DataCache.PublishedTabModuleCacheKey, clearRuntime, tabId); + this.RemoveFormattedCacheKey(DataCache.ModulePermissionCacheKey, clearRuntime, tabId); + this.RemoveFormattedCacheKey(DataCache.ModuleSettingsCacheKey, clearRuntime, tabId); } private void ClearModulePermissionsCachesByPortalInternal(int portalId, bool clearRuntime) { foreach (var tabPair in TabController.Instance.GetTabsByPortal(portalId)) { - RemoveFormattedCacheKey(DataCache.ModulePermissionCacheKey, clearRuntime, tabPair.Value.TabID); + this.RemoveFormattedCacheKey(DataCache.ModulePermissionCacheKey, clearRuntime, tabPair.Value.TabID); } } private void ClearPortalCacheInternal(int portalId, bool cascade, bool clearRuntime) { - RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, string.Empty); + this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, string.Empty); var locales = LocaleController.Instance.GetLocales(portalId); if (locales == null || locales.Count == 0) { - //At least attempt to remove default locale + // At least attempt to remove default locale string defaultLocale = PortalController.GetPortalDefaultLanguage(portalId); - RemoveCacheKey(String.Format(DataCache.PortalCacheKey, portalId, defaultLocale), clearRuntime); - RemoveCacheKey(String.Format(DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); - RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, defaultLocale); + this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, defaultLocale), clearRuntime); + this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); + this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, defaultLocale); } else { foreach (Locale portalLocale in LocaleController.Instance.GetLocales(portalId).Values) { - RemoveCacheKey(String.Format(DataCache.PortalCacheKey, portalId, portalLocale.Code), clearRuntime); - RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, portalLocale.Code); + this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, portalLocale.Code), clearRuntime); + this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, portalLocale.Code); } - RemoveCacheKey(String.Format(DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); - RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, Null.NullString); + + this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); + this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, Null.NullString); } + if (cascade) { foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(portalId)) { - ClearModuleCacheInternal(tabPair.Value.TabID, clearRuntime); + this.ClearModuleCacheInternal(tabPair.Value.TabID, clearRuntime); } + foreach (ModuleInfo moduleInfo in ModuleController.Instance.GetModules(portalId)) { - RemoveCacheKey("GetModuleSettings" + moduleInfo.ModuleID, clearRuntime); + this.RemoveCacheKey("GetModuleSettings" + moduleInfo.ModuleID, clearRuntime); } } - - //Clear "portal keys" for Portal - ClearFolderCacheInternal(portalId, clearRuntime); - ClearCacheKeysByPortalInternal(portalId, clearRuntime); - ClearDesktopModuleCacheInternal(portalId, clearRuntime); - ClearTabCacheInternal(portalId, clearRuntime); - - RemoveCacheKey(String.Format(DataCache.RolesCacheKey, portalId), clearRuntime); - RemoveCacheKey(String.Format(DataCache.JournalTypesCacheKey, portalId), clearRuntime); + + // Clear "portal keys" for Portal + this.ClearFolderCacheInternal(portalId, clearRuntime); + this.ClearCacheKeysByPortalInternal(portalId, clearRuntime); + this.ClearDesktopModuleCacheInternal(portalId, clearRuntime); + this.ClearTabCacheInternal(portalId, clearRuntime); + + this.RemoveCacheKey(string.Format(DataCache.RolesCacheKey, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(DataCache.JournalTypesCacheKey, portalId), clearRuntime); } private void ClearTabCacheInternal(int portalId, bool clearRuntime) { - RemoveFormattedCacheKey(DataCache.TabCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.TabAliasSkinCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.TabCustomAliasCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.TabUrlCacheKey, clearRuntime, portalId); - RemoveFormattedCacheKey(DataCache.TabPermissionCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.TabCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.TabAliasSkinCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.TabCustomAliasCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.TabUrlCacheKey, clearRuntime, portalId); + this.RemoveFormattedCacheKey(DataCache.TabPermissionCacheKey, clearRuntime, portalId); Dictionary locales = LocaleController.Instance.GetLocales(portalId); if (locales == null || locales.Count == 0) { - //At least attempt to remove default locale + // At least attempt to remove default locale string defaultLocale = PortalController.GetPortalDefaultLanguage(portalId); - RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, defaultLocale, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, defaultLocale, portalId), clearRuntime); } else { foreach (Locale portalLocale in LocaleController.Instance.GetLocales(portalId).Values) { - RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, portalLocale.Code, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, portalLocale.Code, portalId), clearRuntime); } } - RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, Null.NullString, portalId), clearRuntime); - RemoveCacheKey(string.Format(DataCache.TabSettingsCacheKey, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, Null.NullString, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(DataCache.TabSettingsCacheKey, portalId), clearRuntime); } private void RemoveCacheKey(string CacheKey, bool clearRuntime) { if (clearRuntime) { - //remove item from runtime cache - RemoveInternal(GetCacheKey(CacheKey)); + // remove item from runtime cache + this.RemoveInternal(GetCacheKey(CacheKey)); } else { - //Call provider's remove method - Remove(GetCacheKey(CacheKey)); + // Call provider's remove method + this.Remove(GetCacheKey(CacheKey)); } } @@ -342,187 +404,111 @@ private void RemoveFormattedCacheKey(string CacheKeyBase, bool clearRuntime, par { if (clearRuntime) { - //remove item from runtime cache - RemoveInternal(string.Format(GetCacheKey(CacheKeyBase), parameters)); + // remove item from runtime cache + this.RemoveInternal(string.Format(GetCacheKey(CacheKeyBase), parameters)); } else { - //Call provider's remove method - Remove(string.Format(GetCacheKey(CacheKeyBase), parameters)); + // Call provider's remove method + this.Remove(string.Format(GetCacheKey(CacheKeyBase), parameters)); } - } - - #endregion + } - #region Protected Methods - - /// - /// Clears the cache internal. - /// - /// Type of the cache. - /// The data. - /// if set to true clear runtime cache. - protected void ClearCacheInternal(string cacheType, string data, bool clearRuntime) + private void ReloadServicesFrameworkRoutes() { - switch (cacheType) - { - case "Prefix": - ClearCacheInternal(data, clearRuntime); - break; - case "Host": - ClearHostCacheInternal(clearRuntime); - break; - case "Folder": - ClearFolderCacheInternal(int.Parse(data), clearRuntime); - break; - case "Module": - ClearModuleCacheInternal(int.Parse(data), clearRuntime); - break; - case "ModulePermissionsByPortal": - ClearModulePermissionsCachesByPortalInternal(int.Parse(data), clearRuntime); - break; - case "Portal": - ClearPortalCacheInternal(int.Parse(data), false, clearRuntime); - break; - case "PortalCascade": - ClearPortalCacheInternal(int.Parse(data), true, clearRuntime); - break; - case "Tab": - ClearTabCacheInternal(int.Parse(data), clearRuntime); - break; - case "ServiceFrameworkRoutes": - ReloadServicesFrameworkRoutes(); - break; - } - } - - private void ReloadServicesFrameworkRoutes() - { - //registration of routes when the servers is operating is done as part of the cache - //because the web request cahcing provider is the only inter-server communication channel - //that is reliable + // registration of routes when the servers is operating is done as part of the cache + // because the web request cahcing provider is the only inter-server communication channel + // that is reliable ServicesRoutingManager.RegisterServiceRoutes(); - } - - /// - /// Removes the internal. - /// - /// The cache key. - protected void RemoveInternal(string cacheKey) - { - //attempt remove from private dictionary - DataCache.RemoveFromPrivateDictionary(cacheKey); - //remove item from memory - if (Cache[cacheKey] != null) - { - Cache.Remove(cacheKey); - } } - /// - /// Clears the specified type. - /// - /// The type. - /// The data. - public virtual void Clear(string type, string data) - { - ClearCacheInternal(type, data, false); - } - - public virtual IDictionaryEnumerator GetEnumerator() - { - return Cache.GetEnumerator(); - } - - /// - /// Gets the item. - /// - /// The cache key. - /// cache content + /// + /// Gets the item. + /// + /// The cache key. + /// cache content. public virtual object GetItem(string cacheKey) { return Cache[cacheKey]; } - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The object. + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The object. public virtual void Insert(string cacheKey, object itemToCache) { - Insert(cacheKey, itemToCache, null as DNNCacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); + this.Insert(cacheKey, itemToCache, null as DNNCacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The object. - /// The dependency. + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The object. + /// The dependency. public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency) { - Insert(cacheKey, itemToCache, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); + this.Insert(cacheKey, itemToCache, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The object. - /// The dependency. - /// The absolute expiration. - /// The sliding expiration. + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The object. + /// The dependency. + /// The absolute expiration. + /// The sliding expiration. public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration) { - Insert(cacheKey, itemToCache, dependency, absoluteExpiration, slidingExpiration, CacheItemPriority.Default, null); + this.Insert(cacheKey, itemToCache, dependency, absoluteExpiration, slidingExpiration, CacheItemPriority.Default, null); } - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The value. - /// The dependency. - /// The absolute expiration. - /// The sliding expiration. - /// The priority. - /// The on remove callback. + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The value. + /// The dependency. + /// The absolute expiration. + /// The sliding expiration. + /// The priority. + /// The on remove callback. public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) - { - Cache.Insert(cacheKey, itemToCache, dependency == null ? null : dependency.SystemCacheDependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); - } - - /// - /// Determines whether is web farm. - /// - /// - /// true if is web farm; otherwise, false. - /// + { + Cache.Insert(cacheKey, itemToCache, dependency == null ? null : dependency.SystemCacheDependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); + } + + /// + /// Determines whether is web farm. + /// + /// + /// true if is web farm; otherwise, false. + /// public virtual bool IsWebFarm() { - return (ServerController.GetEnabledServers().Count > 1); + return ServerController.GetEnabledServers().Count > 1; } - /// - /// Purges the cache. - /// - /// + /// + /// Purges the cache. + /// + /// public virtual string PurgeCache() { - return Localization.Localization.GetString("PurgeCacheUnsupported.Text", Localization.Localization.GlobalResourceFile); + return Localization.GetString("PurgeCacheUnsupported.Text", Localization.GlobalResourceFile); } - /// - /// Removes the specified cache key. - /// - /// The cache key. + /// + /// Removes the specified cache key. + /// + /// The cache key. public virtual void Remove(string CacheKey) { - RemoveInternal(CacheKey); - } - - #endregion + this.RemoveInternal(CacheKey); + } } } diff --git a/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs b/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs index 362caac5328..4b440e0d94a 100644 --- a/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs +++ b/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs @@ -1,275 +1,256 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.Caching; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Cache { - /// - /// DNNCacheDependency provides dependency policies of cache system. - /// - /// - /// The CacheDependency class monitors the dependency relationships so that when any of them changes, the cached item will be automatically removed. - /// + using System; + using System.Web.Caching; + + /// + /// DNNCacheDependency provides dependency policies of cache system. + /// + /// + /// The CacheDependency class monitors the dependency relationships so that when any of them changes, the cached item will be automatically removed. + /// public class DNNCacheDependency : IDisposable - { - #region "Private Members" - + { private readonly DateTime _utcStart = DateTime.MaxValue; private DNNCacheDependency _cacheDependency; private string[] _cacheKeys; private string[] _fileNames; - private CacheDependency _systemCacheDependency; - - #endregion - - #region "Constructors" - - /// - /// Initializes a new instance of the class. - /// - /// The system cache dependency. + private CacheDependency _systemCacheDependency; + + /// + /// Initializes a new instance of the class. + /// + /// The system cache dependency. public DNNCacheDependency(CacheDependency systemCacheDependency) { - _systemCacheDependency = systemCacheDependency; + this._systemCacheDependency = systemCacheDependency; } - /// - /// Initializes a new instance of the class that monitors a file or directory for changes. - /// - /// + /// + /// Initializes a new instance of the class that monitors a file or directory for changes. + /// + /// public DNNCacheDependency(string filename) { - _fileNames = new[] {filename}; + this._fileNames = new[] { filename }; } - /// - /// Initializes a new instance of the class that monitors an array of paths (to files or directories) for changes. - /// - /// set the cache depend on muti files. + /// + /// Initializes a new instance of the class that monitors an array of paths (to files or directories) for changes. + /// + /// set the cache depend on muti files. public DNNCacheDependency(string[] filenames) { - _fileNames = filenames; + this._fileNames = filenames; } - /// - /// Initializes a new instance of the class that monitors an array of paths - /// (to files or directories) for changes and specifies a time when change monitoring begins. - /// - /// The filenames. - /// The start. + /// + /// Initializes a new instance of the class that monitors an array of paths + /// (to files or directories) for changes and specifies a time when change monitoring begins. + /// + /// The filenames. + /// The start. public DNNCacheDependency(string[] filenames, DateTime start) { - _utcStart = start.ToUniversalTime(); - _fileNames = filenames; + this._utcStart = start.ToUniversalTime(); + this._fileNames = filenames; } - /// - /// Initializes a new instance of the class that monitors an array of paths (to files or directories), - /// an array of cache keys, or both for changes. - /// - /// The filenames. - /// The cachekeys. + /// + /// Initializes a new instance of the class that monitors an array of paths (to files or directories), + /// an array of cache keys, or both for changes. + /// + /// The filenames. + /// The cachekeys. public DNNCacheDependency(string[] filenames, string[] cachekeys) { - _fileNames = filenames; - _cacheKeys = cachekeys; + this._fileNames = filenames; + this._cacheKeys = cachekeys; } - /// - /// Initializes a new instance of the class that monitors a file or directory for changes. - /// - /// The filename. - /// The start. + /// + /// Initializes a new instance of the class that monitors a file or directory for changes. + /// + /// The filename. + /// The start. public DNNCacheDependency(string filename, DateTime start) { - _utcStart = start.ToUniversalTime(); + this._utcStart = start.ToUniversalTime(); if (filename != null) { - _fileNames = new[] {filename}; + this._fileNames = new[] { filename }; } } - /// - /// Initializes a new instance of the class that monitors an array of paths (to files or directories), - /// an array of cache keys, or both for changes. - /// - /// The filenames. - /// The cachekeys. - /// The start. + /// + /// Initializes a new instance of the class that monitors an array of paths (to files or directories), + /// an array of cache keys, or both for changes. + /// + /// The filenames. + /// The cachekeys. + /// The start. public DNNCacheDependency(string[] filenames, string[] cachekeys, DateTime start) { - _utcStart = start.ToUniversalTime(); - _fileNames = filenames; - _cacheKeys = cachekeys; + this._utcStart = start.ToUniversalTime(); + this._fileNames = filenames; + this._cacheKeys = cachekeys; } - /// - /// Initializes a new instance of the classthat monitors an array of paths (to files or directories), - /// an array of cache keys, or both for changes. It also makes itself dependent upon a separate instance of the class. - /// - /// The filenames. - /// The cachekeys. - /// The dependency. + /// + /// Initializes a new instance of the classthat monitors an array of paths (to files or directories), + /// an array of cache keys, or both for changes. It also makes itself dependent upon a separate instance of the class. + /// + /// The filenames. + /// The cachekeys. + /// The dependency. public DNNCacheDependency(string[] filenames, string[] cachekeys, DNNCacheDependency dependency) { - _fileNames = filenames; - _cacheKeys = cachekeys; - _cacheDependency = dependency; + this._fileNames = filenames; + this._cacheKeys = cachekeys; + this._cacheDependency = dependency; } - /// - /// Initializes a new instance of the class that monitors an array of paths (to files or directories), - /// an array of cache keys, or both for changes. - /// It also makes itself dependent upon another instance of the class and a time when the change monitoring begins. - /// - /// The filenames. - /// The cachekeys. - /// The dependency. - /// The start. + /// + /// Initializes a new instance of the class that monitors an array of paths (to files or directories), + /// an array of cache keys, or both for changes. + /// It also makes itself dependent upon another instance of the class and a time when the change monitoring begins. + /// + /// The filenames. + /// The cachekeys. + /// The dependency. + /// The start. public DNNCacheDependency(string[] filenames, string[] cachekeys, DNNCacheDependency dependency, DateTime start) { - _utcStart = start.ToUniversalTime(); - _fileNames = filenames; - _cacheKeys = cachekeys; - _cacheDependency = dependency; - } - - #endregion - - #region "Public Properties" - - /// - /// Gets the cache keys. - /// + this._utcStart = start.ToUniversalTime(); + this._fileNames = filenames; + this._cacheKeys = cachekeys; + this._cacheDependency = dependency; + } + + /// + /// Gets the cache keys. + /// public string[] CacheKeys { get { - return _cacheKeys; + return this._cacheKeys; } } - /// - /// Gets the file names. - /// + /// + /// Gets the file names. + /// public string[] FileNames { get { - return _fileNames; + return this._fileNames; } } - /// - /// Gets a value indicating whether this instance has changed. - /// - /// - /// true if this instance has changed; otherwise, false. - /// + /// + /// Gets a value indicating whether this instance has changed. + /// + /// + /// true if this instance has changed; otherwise, false. + /// public bool HasChanged { get { - return SystemCacheDependency.HasChanged; + return this.SystemCacheDependency.HasChanged; } } - /// - /// Gets the cache dependency. - /// + /// + /// Gets the cache dependency. + /// public DNNCacheDependency CacheDependency { get { - return _cacheDependency; + return this._cacheDependency; } } - /// - /// Gets the start time. - /// + /// + /// Gets the start time. + /// public DateTime StartTime { get { - return _utcStart; + return this._utcStart; } } - /// - /// Gets the system cache dependency. - /// + /// + /// Gets the system cache dependency. + /// public CacheDependency SystemCacheDependency { get { - if (_systemCacheDependency == null) + if (this._systemCacheDependency == null) { - if (_cacheDependency == null) + if (this._cacheDependency == null) { - _systemCacheDependency = new CacheDependency(_fileNames, _cacheKeys, _utcStart); + this._systemCacheDependency = new CacheDependency(this._fileNames, this._cacheKeys, this._utcStart); } else { - _systemCacheDependency = new CacheDependency(_fileNames, _cacheKeys, _cacheDependency.SystemCacheDependency, _utcStart); + this._systemCacheDependency = new CacheDependency(this._fileNames, this._cacheKeys, this._cacheDependency.SystemCacheDependency, this._utcStart); } } - return _systemCacheDependency; + + return this._systemCacheDependency; } } - /// - /// Gets the UTC last modified. - /// + /// + /// Gets the UTC last modified. + /// public DateTime UtcLastModified { get { - return SystemCacheDependency.UtcLastModified; + return this.SystemCacheDependency.UtcLastModified; } - } - - #endregion - - #region IDisposable Members - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } - - - //Method that does the actual disposal of resources + + // Method that does the actual disposal of resources protected virtual void Dispose(bool disposing) { - if ((disposing)) + if (disposing) { - if (_cacheDependency != null) + if (this._cacheDependency != null) { - _cacheDependency.Dispose(disposing); + this._cacheDependency.Dispose(disposing); } - if (_systemCacheDependency != null) + + if (this._systemCacheDependency != null) { - _systemCacheDependency.Dispose(); + this._systemCacheDependency.Dispose(); } - _fileNames = null; - _cacheKeys = null; - _cacheDependency = null; - _systemCacheDependency = null; + + this._fileNames = null; + this._cacheKeys = null; + this._cacheDependency = null; + this._systemCacheDependency = null; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs index 68a3a1b1e39..252e42a862f 100644 --- a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs @@ -1,50 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using System.Web.Caching; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Cache { + using System; + using System.IO; + using System.Security.Cryptography; + using System.Text; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + public class FBCachingProvider : CachingProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FBCachingProvider)); internal const string CacheFileExtension = ".resources"; - internal static string CachingDirectory = "Cache\\"; - - #region Abstract Method Implementation - + internal static string CachingDirectory = "Cache\\"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FBCachingProvider)); + public override void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) { - //initialize cache dependency + // initialize cache dependency DNNCacheDependency d = dependency; - //if web farm is enabled - if (IsWebFarm()) + // if web farm is enabled + if (this.IsWebFarm()) { - //get hashed file name + // get hashed file name var f = new string[1]; f[0] = GetFileName(cacheKey); - //create a cache file for item + + // create a cache file for item CreateCacheFile(f[0], cacheKey); - //create a cache dependency on the cache file + + // create a cache dependency on the cache file d = new DNNCacheDependency(f, null, dependency); } - - //Call base class method to add obect to cache + + // Call base class method to add obect to cache base.Insert(cacheKey, itemToCache, d, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); } @@ -55,33 +50,31 @@ public override bool IsWebFarm() { _IsWebFarm = bool.Parse(Config.GetSetting("IsWebFarm")); } + return _IsWebFarm; } public override string PurgeCache() { - //called by scheduled job to remove cache files which are no longer active - return PurgeCacheFiles(Globals.HostMapPath + CachingDirectory); + // called by scheduled job to remove cache files which are no longer active + return this.PurgeCacheFiles(Globals.HostMapPath + CachingDirectory); } public override void Remove(string Key) { base.Remove(Key); - //if web farm is enabled in config file - if (IsWebFarm()) + // if web farm is enabled in config file + if (this.IsWebFarm()) { - //get hashed filename + // get hashed filename string f = GetFileName(Key); - //delete cache file - this synchronizes the cache across servers in the farm + + // delete cache file - this synchronizes the cache across servers in the farm DeleteCacheFile(f); } - } - - #endregion - - #region Private Methods - + } + private static string ByteArrayToString(byte[] arrInput) { int i; @@ -90,28 +83,31 @@ private static string ByteArrayToString(byte[] arrInput) { sOutput.Append(arrInput[i].ToString("X2")); } + return sOutput.ToString(); } private static void CreateCacheFile(string FileName, string CacheKey) { - //declare stream + // declare stream StreamWriter s = null; try { - //if the cache file does not already exist + // if the cache file does not already exist if (!File.Exists(FileName)) { - //create the cache file + // create the cache file s = File.CreateText(FileName); - //write the CacheKey to the file to provide a documented link between cache item and cache file + + // write the CacheKey to the file to provide a documented link between cache item and cache file s.Write(CacheKey); - //close the stream + + // close the stream } } catch (Exception ex) { - //permissions issue creating cache file or more than one thread may have been trying to write the cache file simultaneously + // permissions issue creating cache file or more than one thread may have been trying to write the cache file simultaneously Exceptions.Exceptions.LogException(ex); } finally @@ -134,14 +130,14 @@ private static void DeleteCacheFile(string FileName) } catch (Exception ex) { - //an error occurred when trying to delete the cache file - this is serious as it means that the cache will not be synchronized + // an error occurred when trying to delete the cache file - this is serious as it means that the cache will not be synchronized Exceptions.Exceptions.LogException(ex); } } private static string GetFileName(string CacheKey) { - //cache key may contain characters invalid for a filename - this method creates a valid filename + // cache key may contain characters invalid for a filename - this method creates a valid filename byte[] FileNameBytes = Encoding.ASCII.GetBytes(CacheKey); using (var sha256 = new SHA256CryptoServiceProvider()) { @@ -153,38 +149,40 @@ private static string GetFileName(string CacheKey) private string PurgeCacheFiles(string Folder) { - //declare counters + // declare counters int PurgedFiles = 0; int PurgeErrors = 0; int i; - - //get list of cache files + + // get list of cache files string[] f; f = Directory.GetFiles(Folder); - //loop through cache files + // loop through cache files for (i = 0; i <= f.Length - 1; i++) { - //get last write time for file + // get last write time for file DateTime dtLastWrite; dtLastWrite = File.GetLastWriteTime(f[i]); - //if the cache file is more than 2 hours old ( no point in checking most recent cache files ) + + // if the cache file is more than 2 hours old ( no point in checking most recent cache files ) if (dtLastWrite < DateTime.Now.Subtract(new TimeSpan(2, 0, 0))) { - //get cachekey + // get cachekey string strCacheKey = Path.GetFileNameWithoutExtension(f[i]); - //if the cache key does not exist in memory + + // if the cache key does not exist in memory if (DataCache.GetCache(strCacheKey) == null) { try { - //delete the file + // delete the file File.Delete(f[i]); PurgedFiles += 1; } catch (Exception exc) { - //an error occurred + // an error occurred Logger.Error(exc); PurgeErrors += 1; @@ -192,11 +190,9 @@ private string PurgeCacheFiles(string Folder) } } } - - //return a summary message for the job - return string.Format("Cache Synchronization Files Processed: " + f.Length + ", Purged: " + PurgedFiles + ", Errors: " + PurgeErrors); - } - #endregion - } + // return a summary message for the job + return string.Format("Cache Synchronization Files Processed: " + f.Length + ", Purged: " + PurgedFiles + ", Errors: " + PurgeErrors); + } + } } diff --git a/DNN Platform/Library/Services/Cache/PurgeCache.cs b/DNN Platform/Library/Services/Cache/PurgeCache.cs index 791ee63fbe0..eb1cbf12e70 100644 --- a/DNN Platform/Library/Services/Cache/PurgeCache.cs +++ b/DNN Platform/Library/Services/Cache/PurgeCache.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Cache { + using System; + + using DotNetNuke.Services.Scheduling; + public class PurgeCache : SchedulerClient { public PurgeCache(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; //REQUIRED + this.ScheduleHistoryItem = objScheduleHistoryItem; // REQUIRED } public override void DoWork() @@ -25,20 +20,20 @@ public override void DoWork() { string str = CachingProvider.Instance().PurgeCache(); - ScheduleHistoryItem.Succeeded = true; //REQUIRED - ScheduleHistoryItem.AddLogNote(str); + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED + this.ScheduleHistoryItem.AddLogNote(str); } - catch (Exception exc) //REQUIRED + catch (Exception exc) // REQUIRED { - ScheduleHistoryItem.Succeeded = false; //REQUIRED + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED + + this.ScheduleHistoryItem.AddLogNote(string.Format("Purging cache task failed: {0}.", exc.ToString())); - ScheduleHistoryItem.AddLogNote(string.Format("Purging cache task failed: {0}.", exc.ToString())); + // notification that we have errored + this.Errored(ref exc); // REQUIRED - //notification that we have errored - Errored(ref exc); //REQUIRED - - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } } diff --git a/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs b/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs index 12bbcf0a841..1c8584f09e6 100644 --- a/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs +++ b/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs @@ -1,112 +1,110 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -using DotNetNuke.Services.ClientCapability; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.ClientCapability { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Services.ClientCapability; + /// - /// Default Implementation of IClientCapability + /// Default Implementation of IClientCapability. /// public class ClientCapability : IClientCapability { - private IDictionary _capabilities; - /// + private IDictionary _capabilities; + + /// + /// Initializes a new instance of the class. /// Default Constructor. /// public ClientCapability() { - _capabilities = new Dictionary(); - } - - #region Implementation of IClientCapability - + this._capabilities = new Dictionary(); + } + /// - /// Unique ID of the client making request. + /// Gets or sets unique ID of the client making request. /// public string ID { get; set; } /// - /// User Agent of the client making request + /// Gets or sets user Agent of the client making request. /// public string UserAgent { get; set; } /// - /// Is request coming from a mobile device. + /// Gets or sets a value indicating whether is request coming from a mobile device. /// public bool IsMobile { get; set; } /// - /// Is request coming from a tablet device. + /// Gets or sets a value indicating whether is request coming from a tablet device. /// - public bool IsTablet { get; set; } + public bool IsTablet { get; set; } /// - /// Does the requesting device supports touch screen. + /// Gets or sets a value indicating whether does the requesting device supports touch screen. /// public bool IsTouchScreen { get; set; } /// - /// FacebookRequest property is filled when request is coming though Facebook iFrame (e.g. fan pages). + /// Gets or sets facebookRequest property is filled when request is coming though Facebook iFrame (e.g. fan pages). /// /// - /// FacebookRequest property is populated based on data in "signed_request" headers coming from Facebook. + /// FacebookRequest property is populated based on data in "signed_request" headers coming from Facebook. /// In order to ensure request is coming from Facebook, FacebookRequest.IsValidSignature method should be called with the secrety key provided by Facebook. - /// + /// public FacebookRequest FacebookRequest { get; set; } /// - /// ScreenResolution Width of the requester in Pixels. + /// Gets or sets screenResolution Width of the requester in Pixels. /// public int ScreenResolutionWidthInPixels { get; set; } /// - /// ScreenResolution Height of the requester in Pixels. + /// Gets or sets screenResolution Height of the requester in Pixels. /// public int ScreenResolutionHeightInPixels { get; set; } /// - /// Does requester support Flash. + /// Gets or sets a value indicating whether does requester support Flash. /// public bool SupportsFlash { get; set; } /// - /// A key-value collection containing all capabilities supported by requester + /// Gets or sets a key-value collection containing all capabilities supported by requester. /// [Obsolete("This method is not memory efficient and should be avoided as the Match class now exposes an accessor keyed on property name. Scheduled removal in v10.0.0.")] public IDictionary Capabilities { get { - return _capabilities; - + return this._capabilities; } + set { - _capabilities = value; - + this._capabilities = value; } } /// - /// Represents the name of the broweser in the request + /// Gets or sets represents the name of the broweser in the request. /// public string BrowserName { get; set; } /// - /// Returns the request prefered HTML DTD + /// Gets or sets the request prefered HTML DTD. /// public string HtmlPreferedDTD { get; set; } /// - /// Http server variable used for SSL offloading - if this value is empty offloading is not enabled + /// Gets or sets http server variable used for SSL offloading - if this value is empty offloading is not enabled. /// public string SSLOffload { get; set; } @@ -115,14 +113,12 @@ public IDictionary Capabilities /// /// /// - public virtual string this[string name] + public virtual string this[string name] { get { - throw new NotImplementedException(""); + throw new NotImplementedException(string.Empty); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs b/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs index 4d1acc9896e..5cb0c4d78a9 100644 --- a/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs +++ b/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; -using System.Web; - -using DotNetNuke.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.ClientCapability { + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.ComponentModel; + public abstract class ClientCapabilityProvider : IClientCapabilityProvider - { - #region Virtual Properties - + { + public static IClientCapability CurrentClientCapability + { + get + { + return Instance().GetClientCapability(HttpContext.Current.Request); + } + } + /// - /// Support detect the device whether is a tablet. + /// Gets a value indicating whether support detect the device whether is a tablet. /// public virtual bool SupportsTabletDetection { @@ -27,66 +28,52 @@ public virtual bool SupportsTabletDetection { return true; } + } + + public static ClientCapabilityProvider Instance() + { + return ComponentFactory.GetComponent(); } - - #endregion - - #region Abstract Methods + /// - /// Returns ClientCapability based on userAgent - /// + /// Returns ClientCapability based on userAgent. + /// + /// public abstract IClientCapability GetClientCapability(string userAgent); /// - /// Returns ClientCapability based on ClientCapabilityId - /// + /// Returns ClientCapability based on ClientCapabilityId. + /// + /// public abstract IClientCapability GetClientCapabilityById(string clientId); /// - /// Returns available Capability Values for every Capability Name + /// Returns available Capability Values for every Capability Name. /// /// - /// Dictionary of Capability Name along with List of possible values of the Capability + /// Dictionary of Capability Name along with List of possible values of the Capability. /// - /// Capability Name = mobile_browser, value = Safari, Andriod Webkit + /// Capability Name = mobile_browser, value = Safari, Andriod Webkit. public abstract IDictionary> GetAllClientCapabilityValues(); /// - /// Returns All available Client Capabilities present + /// Returns All available Client Capabilities present. /// /// - /// List of IClientCapability present - /// - public abstract IQueryable GetAllClientCapabilities(); - - #endregion - - #region Virtual Methods + /// List of IClientCapability present. + /// + public abstract IQueryable GetAllClientCapabilities(); + /// - /// Returns ClientCapability based on HttpRequest - /// + /// Returns ClientCapability based on HttpRequest. + /// + /// public virtual IClientCapability GetClientCapability(HttpRequest httpRequest) { - IClientCapability clientCapability = GetClientCapability(httpRequest.UserAgent); + IClientCapability clientCapability = this.GetClientCapability(httpRequest.UserAgent); clientCapability.FacebookRequest = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); return clientCapability; - } - #endregion - - #region static methods - public static ClientCapabilityProvider Instance() - { - return ComponentFactory.GetComponent(); - } - - public static IClientCapability CurrentClientCapability - { - get - { - return Instance().GetClientCapability(HttpContext.Current.Request); - } - } - #endregion + } } } diff --git a/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs b/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs index 1330c09c756..a8826faf5e2 100644 --- a/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs +++ b/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs @@ -1,115 +1,109 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Security.Cryptography; -using System.Web; - -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.ClientCapability { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Web; + + using DotNetNuke.Common.Utilities; + /// - /// Make modules that are aware of Facebook’s signed_request – a parameter that is POSTed to the web page being loaded in the iFrame, + /// Make modules that are aware of Facebook’s signed_request – a parameter that is POSTed to the web page being loaded in the iFrame, /// giving it variables such as if the Page has been Liked, and the age range of the user. - /// - /// For more details visit http://developers.facebook.com/docs/authentication/signed_request/ + /// + /// For more details visit http://developers.facebook.com/docs/authentication/signed_request/. /// public class FacebookRequest - { - #region Public Properties - + { /// - /// Mechanism used to sign the request + /// Gets or sets mechanism used to sign the request. /// public string Algorithm { get; set; } /// - /// Token you can pass to the Graph API or the Legacy REST API. + /// Gets or sets token you can pass to the Graph API or the Legacy REST API. /// - public string OauthToken{ get; set; } + public string OauthToken { get; set; } /// - /// DateTime when the oauth_token expires + /// Gets or sets dateTime when the oauth_token expires. /// public DateTime Expires { get; set; } /// - /// DateTime when the request was signed. + /// Gets or sets dateTime when the request was signed. /// public DateTime IssuedAt { get; set; } /// - /// Facebook user identifier (UID) of the current user. + /// Gets or sets facebook user identifier (UID) of the current user. /// public string UserID { get; set; } /// - /// User's locale. + /// Gets or sets user's locale. /// public string UserLocale { get; set; } /// - /// User's country. + /// Gets or sets user's country. /// public string UserCountry { get; set; } /// - /// User's minimum age range. + /// Gets or sets user's minimum age range. /// public long UserMinAge { get; set; } /// - /// User's maximum age range. + /// Gets or sets user's maximum age range. /// public long UserMaxAge { get; set; } /// - /// Page's Id. Only available if your app is an iframe loaded in a Page tab. + /// Gets or sets page's Id. Only available if your app is an iframe loaded in a Page tab. /// public string PageId { get; set; } /// - /// Has the user has liked the page. Only available if your app is an iframe loaded in a Page tab. + /// Gets or sets a value indicating whether has the user has liked the page. Only available if your app is an iframe loaded in a Page tab. /// public bool PageLiked { get; set; } /// - /// Is the page user Admin of the page. Only available if your app is an iframe loaded in a Page tab. + /// Gets or sets a value indicating whether is the page user Admin of the page. Only available if your app is an iframe loaded in a Page tab. /// - public bool PageUserAdmin { get; set; } + public bool PageUserAdmin { get; set; } /// - /// Page ID if your app is loaded within. Only available if your app is written in FBML and loaded in a Page tab. + /// Gets or sets page ID if your app is loaded within. Only available if your app is written in FBML and loaded in a Page tab. /// public long ProfileId { get; set; } /// - /// Content of a query string parameter also called app_data. Usually specified when the application built the link to pass some data to itself. Only available if your app is an iframe loaded in a Page tab. + /// Gets or sets content of a query string parameter also called app_data. Usually specified when the application built the link to pass some data to itself. Only available if your app is an iframe loaded in a Page tab. /// - public string AppData { get; set; } + public string AppData { get; set; } /// - /// Raw signed request coming from FaceBook in Post + /// Gets or sets raw signed request coming from FaceBook in Post. /// public string RawSignedRequest { get; set; } /// - /// Is this a valid FaceBook Request. Check this value prior to accessing any other property + /// Gets or sets a value indicating whether is this a valid FaceBook Request. Check this value prior to accessing any other property. /// - public bool IsValid { get; set; } - #endregion - - #region Public Methods - public bool IsValidSignature (string secretKey) + public bool IsValid { get; set; } + + public bool IsValidSignature(string secretKey) { - return FacebookRequestController.IsValidSignature(RawSignedRequest,secretKey); - } - #endregion + return FacebookRequestController.IsValidSignature(this.RawSignedRequest, secretKey); + } } - } diff --git a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs index e4576b3f2be..943f0c1de1f 100644 --- a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs +++ b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs @@ -1,73 +1,117 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Security.Cryptography; -using System.Web; - -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.ClientCapability { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Web; + + using DotNetNuke.Common.Utilities; + + internal struct Page + { + public string id { get; set; } + + public bool liked { get; set; } + + public bool admin { get; set; } + } + + internal struct Age + { + public long min { get; set; } + + public long max { get; set; } + } + + internal struct User + { + public string locale { get; set; } + + public string country { get; set; } + + public Age age { get; set; } + } + /// - /// Make modules that are aware of Facebook’s signed_request – a parameter that is POSTed to the web page being loaded in the iFrame, + /// Make modules that are aware of Facebook’s signed_request – a parameter that is POSTed to the web page being loaded in the iFrame, /// giving it variables such as if the Page has been Liked, and the age range of the user. - /// + /// /// public class FacebookRequestController { - public string AccessToken{ get; set; } + private const string SignedRequestParameter = "signed_request"; + + public static string API_SECRET { get; set; } + + public static string APP_ID { get; set; } + + public string AccessToken { get; set; } + public DateTime Expires { get; set; } + public long UserID { get; set; } + public long ProfileId { get; set; } - public static string API_SECRET { get; set; } - public static string APP_ID { get; set; } + public string RawSignedRequest { get; set; } - const string SignedRequestParameter = "signed_request"; + public bool IsValid { get; set; } - public static FacebookRequest GetFacebookDetailsFromRequest(HttpRequest Request) + public static FacebookRequest GetFacebookDetailsFromRequest(HttpRequest Request) { - if (Request == null) return null; - if (Request.RequestType != "POST") return null; + if (Request == null) + { + return null; + } + + if (Request.RequestType != "POST") + { + return null; + } + string rawSignedRequest = Request[SignedRequestParameter]; return GetFacebookDetailsFromRequest(rawSignedRequest); } public static FacebookRequest GetFacebookDetailsFromRequest(string rawSignedRequest) { - if (string.IsNullOrEmpty(rawSignedRequest)) return null; + if (string.IsNullOrEmpty(rawSignedRequest)) + { + return null; + } + + try + { + var facebookRequest = new FacebookRequest(); + facebookRequest.RawSignedRequest = rawSignedRequest; + facebookRequest.IsValid = false; - try - { - var facebookRequest = new FacebookRequest(); - facebookRequest.RawSignedRequest = rawSignedRequest; - facebookRequest.IsValid = false; + string[] signedRequestSplit = rawSignedRequest.Split('.'); + string expectedSignature = signedRequestSplit[0]; + string payload = signedRequestSplit[1]; - string[] signedRequestSplit = rawSignedRequest.Split('.'); - string expectedSignature = signedRequestSplit[0]; - string payload = signedRequestSplit[1]; + var decodedJson = ReplaceSpecialCharactersInSignedRequest(payload); + var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + ((4 - (decodedJson.Length % 4)) % 4), '=')); - var decodedJson = ReplaceSpecialCharactersInSignedRequest(payload); - var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length%4)%4, '=')); + var encoding = new UTF8Encoding(); + FaceBookData faceBookData = encoding.GetString(base64JsonArray).FromJson(); - var encoding = new UTF8Encoding(); - FaceBookData faceBookData = encoding.GetString(base64JsonArray).FromJson(); - if (faceBookData.algorithm == "HMAC-SHA256") { facebookRequest.IsValid = true; facebookRequest.Algorithm = faceBookData.algorithm; facebookRequest.ProfileId = faceBookData.profile_id; facebookRequest.AppData = faceBookData.app_data; - facebookRequest.OauthToken = !string.IsNullOrEmpty(faceBookData.oauth_token) ? faceBookData.oauth_token : ""; - facebookRequest.Expires = ConvertToTimestamp(faceBookData.expires); + facebookRequest.OauthToken = !string.IsNullOrEmpty(faceBookData.oauth_token) ? faceBookData.oauth_token : string.Empty; + facebookRequest.Expires = ConvertToTimestamp(faceBookData.expires); facebookRequest.IssuedAt = ConvertToTimestamp(faceBookData.issued_at); - facebookRequest.UserID = !string.IsNullOrEmpty(faceBookData.user_id) ? faceBookData.user_id : ""; + facebookRequest.UserID = !string.IsNullOrEmpty(faceBookData.user_id) ? faceBookData.user_id : string.Empty; facebookRequest.PageId = faceBookData.page.id; facebookRequest.PageLiked = faceBookData.page.liked; @@ -77,14 +121,14 @@ public static FacebookRequest GetFacebookDetailsFromRequest(string rawSignedRequ facebookRequest.UserCountry = faceBookData.user.country; facebookRequest.UserMinAge = faceBookData.user.age.min; facebookRequest.UserMaxAge = faceBookData.user.age.max; - } - - return facebookRequest; - } - catch(Exception) - { - return null; - } + } + + return facebookRequest; + } + catch (Exception) + { + return null; + } } public static bool IsValidSignature(string rawSignedRequest, string secretKey) @@ -101,8 +145,10 @@ public static bool IsValidSignature(string rawSignedRequest, string secretKey) var encoding = new UTF8Encoding(); var hmac = SignWithHmac(encoding.GetBytes(payload), encoding.GetBytes(secretKey)); var hmacBase64 = Base64UrlDecode(Convert.ToBase64String(hmac)); - if (hmacBase64 == expectedSignature) - return true; + if (hmacBase64 == expectedSignature) + { + return true; + } } } @@ -116,7 +162,11 @@ public static bool IsValidSignature(string rawSignedRequest, string secretKey) /// The base 64 string. private static string Base64UrlDecode(string encodedValue) { - if (String.IsNullOrEmpty(encodedValue)) return null; + if (string.IsNullOrEmpty(encodedValue)) + { + return null; + } + encodedValue = encodedValue.Replace('+', '-').Replace('/', '_').Replace("=", string.Empty).Trim(); return encodedValue; } @@ -134,50 +184,39 @@ private static byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody) return hmacAlgorithm.Hash; } } + /// - /// method for converting a System.DateTime value to a UNIX Timestamp + /// method for converting a System.DateTime value to a UNIX Timestamp. /// - /// date to convert + /// date to convert. /// private static DateTime ConvertToTimestamp(long value) { - //create Timespan by subtracting the value provided from - //the Unix Epoch + // create Timespan by subtracting the value provided from + // the Unix Epoch DateTime epoc = new DateTime(1970, 1, 1, 0, 0, 0, 0); return epoc.AddSeconds((double)value); } } - struct Page - { - public string id { get; set; } - public bool liked { get; set; } - public bool admin { get; set; } - } - - struct Age - { - public long min { get; set; } - public long max { get; set; } - } - - struct User - { - public string locale { get; set; } - public string country { get; set; } - public Age age { get; set; } - } - - struct FaceBookData + internal struct FaceBookData { public User user { get; set; } + public string algorithm { get; set; } + public long issued_at { get; set; } + public string user_id { get; set; } + public string oauth_token { get; set; } + public long expires { get; set; } + public string app_data { get; set; } + public Page page { get; set; } - public long profile_id { get; set; } + + public long profile_id { get; set; } } } diff --git a/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs b/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs index 9e5cc383614..ecd78486d44 100644 --- a/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs +++ b/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs @@ -1,92 +1,88 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.ClientCapability { + using System; + using System.Collections.Generic; + using System.Web; + /// - /// ClientCapability provides capabilities supported by the http requester (e.g. Mobile Device, TV, Desktop) + /// ClientCapability provides capabilities supported by the http requester (e.g. Mobile Device, TV, Desktop). /// /// - /// The capabilities are primarily derived based on UserAgent. - /// + /// The capabilities are primarily derived based on UserAgent. + /// public interface IClientCapability { /// - /// Unique ID of the client making request. + /// Gets or sets unique ID of the client making request. /// string ID { get; set; } /// - /// User Agent of the client making request + /// Gets or sets user Agent of the client making request. /// string UserAgent { get; set; } /// - /// Is request coming from a mobile device. + /// Gets or sets a value indicating whether is request coming from a mobile device. /// bool IsMobile { get; set; } /// - /// Is request coming from a tablet device. + /// Gets or sets a value indicating whether is request coming from a tablet device. /// bool IsTablet { get; set; } /// - /// Does the requesting device supports touch screen. + /// Gets or sets a value indicating whether does the requesting device supports touch screen. /// bool IsTouchScreen { get; set; } /// - /// FacebookRequest property is filled when request is coming though Facebook iFrame (e.g. fan pages). + /// Gets or sets facebookRequest property is filled when request is coming though Facebook iFrame (e.g. fan pages). /// /// - /// FacebookRequest property is populated based on data in "signed_request" headers coming from Facebook. + /// FacebookRequest property is populated based on data in "signed_request" headers coming from Facebook. /// In order to ensure request is coming from Facebook, FacebookRequest.IsValidSignature method should be called with the secrety key provided by Facebook. - /// Most of the properties in IClientCapability doesnot apply to Facebook - /// + /// Most of the properties in IClientCapability doesnot apply to Facebook. + /// FacebookRequest FacebookRequest { get; set; } /// - /// ScreenResolution Width of the requester in Pixels. + /// Gets or sets screenResolution Width of the requester in Pixels. /// int ScreenResolutionWidthInPixels { get; set; } /// - /// ScreenResolution Height of the requester in Pixels. + /// Gets or sets screenResolution Height of the requester in Pixels. /// int ScreenResolutionHeightInPixels { get; set; } /// - /// Represents the name of the broweser in the request - /// + /// Gets or sets represents the name of the broweser in the request. + /// string BrowserName { get; set; } /// - /// Does requester support Flash. + /// Gets or sets a value indicating whether does requester support Flash. /// bool SupportsFlash { get; set; } /// - /// A key-value collection containing all capabilities supported by requester - /// - [Obsolete("This method is not memory efficient and should be avoided as the Match class now exposes an accessor keyed on property name.. Scheduled removal in v10.0.0.")] + /// Gets or sets a key-value collection containing all capabilities supported by requester. + /// + [Obsolete("This method is not memory efficient and should be avoided as the Match class now exposes an accessor keyed on property name.. Scheduled removal in v10.0.0.")] IDictionary Capabilities { get; set; } /// - /// Returns the request prefered HTML DTD + /// Gets or sets the request prefered HTML DTD. /// string HtmlPreferedDTD { get; set; } /// - /// Http server variable used for SSL offloading - if this value is empty offloading is not enabled + /// Gets or sets http server variable used for SSL offloading - if this value is empty offloading is not enabled. /// string SSLOffload { get; set; } diff --git a/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs b/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs index 47227767385..53e758c2942 100644 --- a/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs +++ b/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs @@ -1,45 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.ClientCapability { + using System.Collections.Generic; + using System.Linq; + using System.Web; + public interface IClientCapabilityProvider { /// - /// Returns ClientCapability based on userAgent - /// + /// Returns ClientCapability based on userAgent. + /// + /// IClientCapability GetClientCapability(string userAgent); /// - /// Returns ClientCapability based on ClientCapabilityId - /// + /// Returns ClientCapability based on ClientCapabilityId. + /// + /// IClientCapability GetClientCapabilityById(string clientId); /// - /// Returns available Capability Values for every Capability Name + /// Returns available Capability Values for every Capability Name. /// /// - /// Dictionary of Capability Name along with List of possible values of the Capability + /// Dictionary of Capability Name along with List of possible values of the Capability. /// - /// Capability Name = mobile_browser, value = Safari, Andriod Webkit + /// Capability Name = mobile_browser, value = Safari, Andriod Webkit. IDictionary> GetAllClientCapabilityValues(); /// - /// Returns All available Client Capabilities present + /// Returns All available Client Capabilities present. /// /// - /// List of IClientCapability present - /// + /// List of IClientCapability present. + /// IQueryable GetAllClientCapabilities(); /// - /// Returns ClientCapability based on HttpRequest - /// + /// Returns ClientCapability based on HttpRequest. + /// + /// IClientCapability GetClientCapability(HttpRequest httpRequest); } } diff --git a/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs b/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs index f255f243a3d..1aed798e628 100644 --- a/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs +++ b/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.ClientDependency { - class PurgeClientDependencyFiles : SchedulerClient + using System; + using System.IO; + + using DotNetNuke.Services.Scheduling; + + internal class PurgeClientDependencyFiles : SchedulerClient { public PurgeClientDependencyFiles(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; //REQUIRED + this.ScheduleHistoryItem = objScheduleHistoryItem; // REQUIRED } public override void DoWork() @@ -28,20 +24,21 @@ public override void DoWork() { File.Delete(filePath); } - ScheduleHistoryItem.Succeeded = true; //REQUIRED - ScheduleHistoryItem.AddLogNote("Purging client dependency files task succeeded"); + + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("Purging client dependency files task succeeded"); } - catch (Exception exc) //REQUIRED + catch (Exception exc) // REQUIRED { - ScheduleHistoryItem.Succeeded = false; //REQUIRED + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED - ScheduleHistoryItem.AddLogNote(string.Format("Purging client dependency files task failed: {0}.", exc.ToString())); + this.ScheduleHistoryItem.AddLogNote(string.Format("Purging client dependency files task failed: {0}.", exc.ToString())); - //notification that we have errored - Errored(ref exc); //REQUIRED + // notification that we have errored + this.Errored(ref exc); // REQUIRED - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } } diff --git a/DNN Platform/Library/Services/Connections/ConnectionsController.cs b/DNN Platform/Library/Services/Connections/ConnectionsController.cs index d62822d06c3..223a088cb5c 100644 --- a/DNN Platform/Library/Services/Connections/ConnectionsController.cs +++ b/DNN Platform/Library/Services/Connections/ConnectionsController.cs @@ -1,27 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + public class ConnectionsController : ServiceLocator, IConnectionsController - { - #region Overrides of ServiceLocator - - protected override Func GetFactory() - { - return () => new ConnectionsController(); - } - - #endregion - + { public IList GetConnections(int portalId) { var connectors = ConnectionsManager.Instance.GetConnectors().Where(c => c.HasConfig(portalId)).ToList(); @@ -30,6 +22,7 @@ public IList GetConnections(int portalId) { allConnectors.AddRange(con.GetConnectors(portalId)); } + return allConnectors; } @@ -44,6 +37,10 @@ public IDictionary GetConnectionConfigs(int portalId, string nam return null; } - + + protected override Func GetFactory() + { + return () => new ConnectionsController(); + } } } diff --git a/DNN Platform/Library/Services/Connections/ConnectionsManager.cs b/DNN Platform/Library/Services/Connections/ConnectionsManager.cs index c55aa2522d0..40293627678 100644 --- a/DNN Platform/Library/Services/Connections/ConnectionsManager.cs +++ b/DNN Platform/Library/Services/Connections/ConnectionsManager.cs @@ -1,39 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Framework; -using DotNetNuke.Framework.Reflections; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Packages; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using DotNetNuke.Framework; + using DotNetNuke.Framework.Reflections; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Packages; + public sealed class ConnectionsManager : ServiceLocator, IConnectionsManager - { - #region Service Locator Implements - - protected override Func GetFactory() - { - return () => new ConnectionsManager(); - } - - #endregion - - #region Properties - + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ConnectionsManager)); private static readonly object LockerObject = new object(); - private static IDictionary _processors; - - #endregion - - #region Public Methods - + private static IDictionary _processors; + + protected override Func GetFactory() + { + return () => new ConnectionsManager(); + } + public void RegisterConnections() { if (_processors == null) @@ -42,7 +33,7 @@ public void RegisterConnections() { if (_processors == null) { - LoadProcessors(); + this.LoadProcessors(); } } } @@ -50,27 +41,23 @@ public void RegisterConnections() public IList GetConnectors() { - return _processors.Values.Where(x => IsPackageInstalled(x.GetType().Assembly)).ToList(); - } - - #endregion - - #region Private Methods - + return _processors.Values.Where(x => this.IsPackageInstalled(x.GetType().Assembly)).ToList(); + } + private void LoadProcessors() { _processors = new Dictionary(); var typeLocator = new TypeLocator(); - var types = typeLocator.GetAllMatchingTypes(IsValidFilter); + var types = typeLocator.GetAllMatchingTypes(this.IsValidFilter); foreach (var type in types) { try { var processor = Activator.CreateInstance(type) as IConnector; - if (processor != null - && !string.IsNullOrEmpty(processor.Name) + if (processor != null + && !string.IsNullOrEmpty(processor.Name) && !_processors.ContainsKey(processor.Name)) { _processors.Add(processor.Name, processor); @@ -90,10 +77,9 @@ private bool IsValidFilter(Type t) private bool IsPackageInstalled(Assembly assembly) { - return PackageController.Instance.GetExtensionPackages(-1, + return PackageController.Instance.GetExtensionPackages( + -1, info => info.Name == assembly.GetName().Name && info.IsValid).Count > 0; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs b/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs index b5f0e752050..547b9bba34a 100644 --- a/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs +++ b/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs @@ -1,26 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { + using System; + public class ConnectorArgumentException : ApplicationException { public ConnectorArgumentException() { - } - public ConnectorArgumentException(string message) : base(message) + public ConnectorArgumentException(string message) + : base(message) { - } - public ConnectorArgumentException(string message, Exception innerException) : base(message, innerException) + public ConnectorArgumentException(string message, Exception innerException) + : base(message, innerException) { - } } } diff --git a/DNN Platform/Library/Services/Connections/ConnectorCategories.cs b/DNN Platform/Library/Services/Connections/ConnectorCategories.cs index 77641331e77..cb971b6481b 100644 --- a/DNN Platform/Library/Services/Connections/ConnectorCategories.cs +++ b/DNN Platform/Library/Services/Connections/ConnectorCategories.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { public enum ConnectorCategories @@ -10,6 +10,6 @@ public enum ConnectorCategories FileSystem, Analytics, Marketting, - Other + Other, } } diff --git a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs index 6879feadf8b..a65ef91e137 100644 --- a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs +++ b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs @@ -1,25 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Dynamic; -using System.Linq; -using System.Text; -using System.Web.Script.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Dynamic; + using System.Linq; + using System.Text; + using System.Web.Script.Serialization; + public sealed class DynamicJsonConverter : JavaScriptConverter { + public override IEnumerable SupportedTypes + { + get { return new ReadOnlyCollection(new List(new[] { typeof(object) })); } + } + public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer) { - if (dictionary == null) - throw new ArgumentNullException("dictionary"); - + if (dictionary == null) + { + throw new ArgumentNullException("dictionary"); + } + return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; } @@ -27,36 +34,63 @@ public override IDictionary Serialize(object obj, JavaScriptSeri { throw new NotImplementedException(); } - - public override IEnumerable SupportedTypes - { - get { return new ReadOnlyCollection(new List(new[] { typeof(object) })); } - } - - #region Nested type: DynamicJsonObject - + private sealed class DynamicJsonObject : DynamicObject { private readonly IDictionary _dictionary; public DynamicJsonObject(IDictionary dictionary) { - if (dictionary == null) - throw new ArgumentNullException("dictionary"); - _dictionary = dictionary; + if (dictionary == null) + { + throw new ArgumentNullException("dictionary"); + } + + this._dictionary = dictionary; } public override string ToString() { var sb = new StringBuilder("{"); - ToString(sb); + this.ToString(sb); return sb.ToString(); } + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + if (!this._dictionary.TryGetValue(binder.Name, out result)) + { + // return null to avoid exception. caller can check for null this way... + result = null; + return true; + } + + result = WrapResultObject(result); + return true; + } + + public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) + { + if (indexes.Length == 1 && indexes[0] != null) + { + if (!this._dictionary.TryGetValue(indexes[0].ToString(), out result)) + { + // return null to avoid exception. caller can check for null this way... + result = null; + return true; + } + + result = WrapResultObject(result); + return true; + } + + return base.TryGetIndex(binder, indexes, out result); + } + private void ToString(StringBuilder sb) { var firstInDictionary = true; - foreach (var pair in _dictionary) + foreach (var pair in this._dictionary) { if (!firstInDictionary) { @@ -84,11 +118,12 @@ private void ToString(StringBuilder sb) { sb.Append(","); } + firstInArray = false; if (arrayValue is IDictionary) { - sb.Append(new DynamicJsonObject((IDictionary) arrayValue).ToString()); + sb.Append(new DynamicJsonObject((IDictionary)arrayValue).ToString()); } else if (arrayValue is string) { @@ -98,8 +133,8 @@ private void ToString(StringBuilder sb) { sb.AppendFormat("{0}", arrayValue); } - } + sb.Append("]"); } else @@ -107,46 +142,18 @@ private void ToString(StringBuilder sb) sb.AppendFormat("{0}:{1}", name, value); } } + sb.Append("}"); } - public override bool TryGetMember(GetMemberBinder binder, out object result) - { - if (!_dictionary.TryGetValue(binder.Name, out result)) - { - // return null to avoid exception. caller can check for null this way... - result = null; - return true; - } - - result = WrapResultObject(result); - return true; - } - - public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) - { - if (indexes.Length == 1 && indexes[0] != null) - { - if (!_dictionary.TryGetValue(indexes[0].ToString(), out result)) - { - // return null to avoid exception. caller can check for null this way... - result = null; - return true; - } - - result = WrapResultObject(result); - return true; - } - - return base.TryGetIndex(binder, indexes, out result); - } - private static object WrapResultObject(object result) { var dictionary = result as IDictionary; - if (dictionary != null) - return new DynamicJsonObject(dictionary); - + if (dictionary != null) + { + return new DynamicJsonObject(dictionary); + } + var arrayList = result as ArrayList; if (arrayList != null && arrayList.Count > 0) { @@ -157,8 +164,6 @@ private static object WrapResultObject(object result) return result; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Connections/IConnectionsController.cs b/DNN Platform/Library/Services/Connections/IConnectionsController.cs index 63327730019..ae0b04d75be 100644 --- a/DNN Platform/Library/Services/Connections/IConnectionsController.cs +++ b/DNN Platform/Library/Services/Connections/IConnectionsController.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { + using System.Collections; + using System.Collections.Generic; + public interface IConnectionsController { /// - /// Get Connection Settings for a Site - /// + /// Get Connection Settings for a Site. + /// + /// IList GetConnections(int portalId); /// diff --git a/DNN Platform/Library/Services/Connections/IConnectionsManager.cs b/DNN Platform/Library/Services/Connections/IConnectionsManager.cs index c742fd3942f..65ff1236bbb 100644 --- a/DNN Platform/Library/Services/Connections/IConnectionsManager.cs +++ b/DNN Platform/Library/Services/Connections/IConnectionsManager.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { + using System.Collections.Generic; + public interface IConnectionsManager { void RegisterConnections(); diff --git a/DNN Platform/Library/Services/Connections/IConnector.cs b/DNN Platform/Library/Services/Connections/IConnector.cs index 4bfe5337c5b..a412b69191b 100644 --- a/DNN Platform/Library/Services/Connections/IConnector.cs +++ b/DNN Platform/Library/Services/Connections/IConnector.cs @@ -1,50 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Connections { + using System.Collections.Generic; + public interface IConnector { /// - /// Id of the connector. It is required if SupportsMultiple is true. + /// Gets or sets id of the connector. It is required if SupportsMultiple is true. /// string Id { get; set; } /// - /// Unique name of the connector. It is used to distinguish between different types of connectors. + /// Gets unique name of the connector. It is used to distinguish between different types of connectors. /// string Name { get; } /// - /// Category of the connector. It can be used to sort similar type resources. + /// Gets category of the connector. It can be used to sort similar type resources. /// ConnectorCategories Type { get; } /// - /// Determines whether this connector supports multiple connections or not. + /// Gets a value indicating whether determines whether this connector supports multiple connections or not. /// bool SupportsMultiple { get; } /// - /// Display name of the connector. + /// Gets or sets display name of the connector. /// string DisplayName { get; set; } /// - /// Icon url of the connector. + /// Gets icon url of the connector. /// string IconUrl { get; } /// - /// Plugins folder for the connector. + /// Gets plugins folder for the connector. /// string PluginFolder { get; } /// - /// Determines if it is engage connector or not. + /// Gets a value indicating whether determines if it is engage connector or not. /// bool IsEngageConnector { get; } diff --git a/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs index 96dbdb4b2a4..e94d73241fe 100644 --- a/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs @@ -1,28 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Cryptography { + using System; + using System.IO; + using System.Security.Cryptography; + using System.Text; + internal class CoreCryptographyProvider : CryptographyProvider { /// - /// copy of legacy PortalSecurity.Encrypt method + /// copy of legacy PortalSecurity.Encrypt method. /// - /// string to be encrypted - /// key for encryption + /// string to be encrypted. + /// key for encryption. /// public override string EncryptParameter(string message, string passphrase) { string value; - if (!String.IsNullOrEmpty(passphrase)) + if (!string.IsNullOrEmpty(passphrase)) { - //convert key to 16 characters for simplicity + // convert key to 16 characters for simplicity if (passphrase.Length < 16) { passphrase = passphrase + "XXXXXXXXXXXXXXXX".Substring(0, 16 - passphrase.Length); @@ -32,14 +32,14 @@ public override string EncryptParameter(string message, string passphrase) passphrase = passphrase.Substring(0, 16); } - //create encryption keys + // create encryption keys byte[] byteKey = Encoding.UTF8.GetBytes(passphrase.Substring(0, 8)); byte[] byteVector = Encoding.UTF8.GetBytes(passphrase.Substring(passphrase.Length - 8, 8)); - //convert data to byte array + // convert data to byte array byte[] byteData = Encoding.UTF8.GetBytes(message); - //encrypt + // encrypt using (var objDes = new DESCryptoServiceProvider()) using (var objMemoryStream = new MemoryStream()) using (var objCryptoStream = new CryptoStream(objMemoryStream, objDes.CreateEncryptor(byteKey, byteVector), @@ -48,7 +48,7 @@ public override string EncryptParameter(string message, string passphrase) objCryptoStream.Write(byteData, 0, byteData.Length); objCryptoStream.FlushFinalBlock(); - //convert to string and Base64 encode + // convert to string and Base64 encode value = Convert.ToBase64String(objMemoryStream.ToArray()); } } @@ -56,23 +56,24 @@ public override string EncryptParameter(string message, string passphrase) { value = message; } + return value; } /// - /// copy of legacy PortalSecurity.Decrypt method + /// copy of legacy PortalSecurity.Decrypt method. /// - /// string to be decrypted - /// key for decryption + /// string to be decrypted. + /// key for decryption. /// public override string DecryptParameter(string message, string passphrase) { - string strValue = ""; + string strValue = string.Empty; if (!string.IsNullOrEmpty(passphrase) && !string.IsNullOrEmpty(message)) { try { - //convert key to 16 characters for simplicity + // convert key to 16 characters for simplicity if (passphrase.Length < 16) { passphrase = passphrase + "XXXXXXXXXXXXXXXX".Substring(0, 16 - passphrase.Length); @@ -82,45 +83,47 @@ public override string DecryptParameter(string message, string passphrase) passphrase = passphrase.Substring(0, 16); } - //create encryption keys + // create encryption keys byte[] byteKey = Encoding.UTF8.GetBytes(passphrase.Substring(0, 8)); byte[] byteVector = Encoding.UTF8.GetBytes(passphrase.Substring(passphrase.Length - 8, 8)); byte[] byteData = Convert.FromBase64String(message); - //decrypt + // decrypt using (var objDes = new DESCryptoServiceProvider()) using (var objMemoryStream = new MemoryStream()) - using (var objCryptoStream = new CryptoStream(objMemoryStream, + using (var objCryptoStream = new CryptoStream( + objMemoryStream, objDes.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write)) { objCryptoStream.Write(byteData, 0, byteData.Length); objCryptoStream.FlushFinalBlock(); - //convert to string + // convert to string Encoding objEncoding = Encoding.UTF8; strValue = objEncoding.GetString(objMemoryStream.ToArray()); } } - catch //decryption error + catch // decryption error { - strValue = ""; + strValue = string.Empty; } } + return strValue; } /// - /// copy of legacy PortalSecurity.EncryptString method + /// copy of legacy PortalSecurity.EncryptString method. /// - /// string to be encrypted - /// key for encryption + /// string to be encrypted. + /// key for encryption. /// public override string EncryptString(string message, string passphrase) { byte[] results; var utf8 = new UTF8Encoding(); - //hash the passphrase using MD5 to create 128bit byte array + // hash the passphrase using MD5 to create 128bit byte array using (var hashProvider = new MD5CryptoServiceProvider()) { byte[] tdesKey = hashProvider.ComputeHash(utf8.GetBytes(passphrase)); @@ -129,7 +132,7 @@ public override string EncryptString(string message, string passphrase) { Key = tdesKey, Mode = CipherMode.ECB, - Padding = PaddingMode.PKCS7 + Padding = PaddingMode.PKCS7, }; byte[] dataToEncrypt = utf8.GetBytes(message); @@ -141,28 +144,28 @@ public override string EncryptString(string message, string passphrase) } finally { - // Clear the TripleDes and Hashprovider services of any sensitive information + // Clear the TripleDes and Hashprovider services of any sensitive information tdesAlgorithm.Clear(); hashProvider.Clear(); } } - //Return the encrypted string as a base64 encoded string + // Return the encrypted string as a base64 encoded string return Convert.ToBase64String(results); } /// - /// copy of legacy PortalSecurity.DecryptString method + /// copy of legacy PortalSecurity.DecryptString method. /// - /// string to be decrypted - /// key for decryption + /// string to be decrypted. + /// key for decryption. /// public override string DecryptString(string message, string passphrase) { byte[] results; var utf8 = new UTF8Encoding(); - //hash the passphrase using MD5 to create 128bit byte array + // hash the passphrase using MD5 to create 128bit byte array using (var hashProvider = new MD5CryptoServiceProvider()) { byte[] tdesKey = hashProvider.ComputeHash(utf8.GetBytes(passphrase)); @@ -171,10 +174,9 @@ public override string DecryptString(string message, string passphrase) { Key = tdesKey, Mode = CipherMode.ECB, - Padding = PaddingMode.PKCS7 + Padding = PaddingMode.PKCS7, }; - - + byte[] dataToDecrypt = Convert.FromBase64String(message); try { @@ -183,7 +185,7 @@ public override string DecryptString(string message, string passphrase) } finally { - // Clear the TripleDes and Hashprovider services of any sensitive information + // Clear the TripleDes and Hashprovider services of any sensitive information tdesAlgorithm.Clear(); hashProvider.Clear(); } diff --git a/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs index 100b287a693..26911bbf067 100644 --- a/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs @@ -1,56 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Cryptography { + using DotNetNuke.ComponentModel; + public abstract class CryptographyProvider : ICryptographyProvider - { - #region Abstract Methods - + { + public static CryptographyProvider Instance() + { + return ComponentFactory.GetComponent(); + } + /// - /// simple method that uses basic encryption to safely encode parameters + /// simple method that uses basic encryption to safely encode parameters. /// - /// the text to be encrypted (encoded) - /// the key to perform the encryption - /// encrypted string + /// the text to be encrypted (encoded). + /// the key to perform the encryption. + /// encrypted string. public abstract string EncryptParameter(string message, string passphrase); /// - /// simple method that uses basic encryption to safely decode parameters + /// simple method that uses basic encryption to safely decode parameters. /// - /// the text to be decrypted (decoded) - /// the key to perform the decryption - /// decrypted string + /// the text to be decrypted (decoded). + /// the key to perform the decryption. + /// decrypted string. public abstract string DecryptParameter(string message, string passphrase); /// - /// safely encrypt sensitive data + /// safely encrypt sensitive data. /// - /// the text to be encrypted - /// the key to perform the encryption - /// encrypted string + /// the text to be encrypted. + /// the key to perform the encryption. + /// encrypted string. public abstract string EncryptString(string message, string passphrase); /// - /// safely decrypt sensitive data + /// safely decrypt sensitive data. /// - /// the text to be decrypted - /// the key to perform the decryption - /// decrypted string - public abstract string DecryptString(string message, string passphrase); - - #endregion - - #region static methods - - public static CryptographyProvider Instance() - { - return ComponentFactory.GetComponent(); - } - - #endregion + /// the text to be decrypted. + /// the key to perform the decryption. + /// decrypted string. + public abstract string DecryptString(string message, string passphrase); } } diff --git a/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs index 7f82b183b1f..aed4a069d55 100644 --- a/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs @@ -1,29 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Cryptography { + using System; + using System.IO; + using System.Security.Cryptography; + using System.Text; + + using DotNetNuke.Common.Utilities; + internal class FipsCompilanceCryptographyProvider : CryptographyProvider { /// - /// copy of legacy PortalSecurity.Encrypt method + /// copy of legacy PortalSecurity.Encrypt method. /// - /// string to be encrypted - /// key for encryption + /// string to be encrypted. + /// key for encryption. /// public override string EncryptParameter(string message, string passphrase) { string value; - if (!String.IsNullOrEmpty(passphrase)) + if (!string.IsNullOrEmpty(passphrase)) { - //convert key to 16 characters for simplicity + // convert key to 16 characters for simplicity if (passphrase.Length < 16) { passphrase = passphrase + "XXXXXXXXXXXXXXXX".Substring(0, 16 - passphrase.Length); @@ -33,14 +34,14 @@ public override string EncryptParameter(string message, string passphrase) passphrase = passphrase.Substring(0, 16); } - //create encryption keys + // create encryption keys byte[] byteKey = Encoding.UTF8.GetBytes(passphrase.Substring(0, 8)); byte[] byteVector = Encoding.UTF8.GetBytes(passphrase.Substring(passphrase.Length - 8, 8)); - //convert data to byte array + // convert data to byte array byte[] byteData = Encoding.UTF8.GetBytes(message); - //encrypt + // encrypt using (var objDes = new DESCryptoServiceProvider()) using (var objMemoryStream = new MemoryStream()) using (var objCryptoStream = new CryptoStream(objMemoryStream, objDes.CreateEncryptor(byteKey, byteVector), @@ -49,7 +50,7 @@ public override string EncryptParameter(string message, string passphrase) objCryptoStream.Write(byteData, 0, byteData.Length); objCryptoStream.FlushFinalBlock(); - //convert to string and Base64 encode + // convert to string and Base64 encode value = Convert.ToBase64String(objMemoryStream.ToArray()); } } @@ -57,24 +58,25 @@ public override string EncryptParameter(string message, string passphrase) { value = message; } + return value; } /// - /// copy of legacy PortalSecurity.Decrypt method + /// copy of legacy PortalSecurity.Decrypt method. /// - /// string to be decrypted - /// key for decryption + /// string to be decrypted. + /// key for decryption. /// public override string DecryptParameter(string message, string passphrase) { - string strValue = ""; + string strValue = string.Empty; if (!string.IsNullOrEmpty(passphrase) && !string.IsNullOrEmpty(message)) { - //convert data to byte array and Base64 decode + // convert data to byte array and Base64 decode try { - //convert key to 16 characters for simplicity + // convert key to 16 characters for simplicity if (passphrase.Length < 16) { passphrase = passphrase + "XXXXXXXXXXXXXXXX".Substring(0, 16 - passphrase.Length); @@ -84,38 +86,40 @@ public override string DecryptParameter(string message, string passphrase) passphrase = passphrase.Substring(0, 16); } - //create encryption keys + // create encryption keys byte[] byteKey = Encoding.UTF8.GetBytes(passphrase.Substring(0, 8)); byte[] byteVector = Encoding.UTF8.GetBytes(passphrase.Substring(passphrase.Length - 8, 8)); byte[] byteData = Convert.FromBase64String(message); - //decrypt + // decrypt using (var objDes = new DESCryptoServiceProvider()) using (var objMemoryStream = new MemoryStream()) - using (var objCryptoStream = new CryptoStream(objMemoryStream, + using (var objCryptoStream = new CryptoStream( + objMemoryStream, objDes.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write)) { objCryptoStream.Write(byteData, 0, byteData.Length); objCryptoStream.FlushFinalBlock(); - //convert to string + // convert to string Encoding objEncoding = Encoding.UTF8; strValue = objEncoding.GetString(objMemoryStream.ToArray()); } } - catch //decryption error + catch // decryption error { - strValue = ""; + strValue = string.Empty; } } + return strValue; } /// - /// copy of legacy PortalSecurity.EncryptString method + /// copy of legacy PortalSecurity.EncryptString method. /// - /// string to be encrypted - /// key for encryption + /// string to be encrypted. + /// key for encryption. /// public override string EncryptString(string message, string passphrase) { @@ -131,7 +135,7 @@ public override string EncryptString(string message, string passphrase) { Key = trimmedBytes, Mode = CipherMode.ECB, - Padding = PaddingMode.PKCS7 + Padding = PaddingMode.PKCS7, }; byte[] dataToEncrypt = utf8.GetBytes(message); @@ -143,21 +147,21 @@ public override string EncryptString(string message, string passphrase) } finally { - // Clear the TripleDes and Hashprovider services of any sensitive information + // Clear the TripleDes and Hashprovider services of any sensitive information tdesAlgorithm.Clear(); hashProvider.Clear(); } } - //Return the encrypted string as a base64 encoded string + // Return the encrypted string as a base64 encoded string return Convert.ToBase64String(results); } /// - /// copy of legacy PortalSecurity.DecryptString method + /// copy of legacy PortalSecurity.DecryptString method. /// - /// string to be decrypted - /// key for decryption + /// string to be decrypted. + /// key for decryption. /// public override string DecryptString(string message, string passphrase) { @@ -173,10 +177,9 @@ public override string DecryptString(string message, string passphrase) { Key = trimmedBytes, Mode = CipherMode.ECB, - Padding = PaddingMode.PKCS7 + Padding = PaddingMode.PKCS7, }; - - + byte[] dataToDecrypt = Convert.FromBase64String(message); try { @@ -185,7 +188,7 @@ public override string DecryptString(string message, string passphrase) } finally { - // Clear the TripleDes and Hashprovider services of any sensitive information + // Clear the TripleDes and Hashprovider services of any sensitive information tdesAlgorithm.Clear(); hashProvider.Clear(); } diff --git a/DNN Platform/Library/Services/Cryptography/ICryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/ICryptographyProvider.cs index 7d31074f0c1..1b9570e8704 100644 --- a/DNN Platform/Library/Services/Cryptography/ICryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/ICryptographyProvider.cs @@ -1,41 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Cryptography { public interface ICryptographyProvider { /// - /// simple method that uses basic encryption to safely encode parameters + /// simple method that uses basic encryption to safely encode parameters. /// - /// the text to be encrypted (encoded) - /// the key to perform the encryption - /// encrypted string + /// the text to be encrypted (encoded). + /// the key to perform the encryption. + /// encrypted string. string EncryptParameter(string message, string passphrase); /// - /// simple method that uses basic encryption to safely decode parameters + /// simple method that uses basic encryption to safely decode parameters. /// - /// the text to be decrypted (decoded) - /// the key to perform the decryption - /// decrypted string + /// the text to be decrypted (decoded). + /// the key to perform the decryption. + /// decrypted string. string DecryptParameter(string message, string passphrase); /// - /// safely encrypt sensitive data + /// safely encrypt sensitive data. /// - /// the text to be encrypted - /// the key to perform the encryption - /// encrypted string + /// the text to be encrypted. + /// the key to perform the encryption. + /// encrypted string. string EncryptString(string message, string passphrase); /// - /// safely decrypt sensitive data + /// safely decrypt sensitive data. /// - /// the text to be decrypted - /// the key to perform the decryption - /// decrypted string + /// the text to be decrypted. + /// the key to perform the decryption. + /// decrypted string. string DecryptString(string message, string passphrase); } } diff --git a/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs b/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs index d5b0606e58c..b00a14b37b6 100644 --- a/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs +++ b/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs @@ -1,11 +1,16 @@ -using DotNetNuke.Common.Extensions; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.DependencyInjection { + using System; + using System.Collections; + using System.Web; + + using DotNetNuke.Common.Extensions; + using Microsoft.Extensions.DependencyInjection; + public interface IScopeAccessor { IServiceScope GetScope(); @@ -19,17 +24,17 @@ public class ScopeAccessor : IScopeAccessor public ScopeAccessor() { - _getContextItems = fallbackGetContextItems; + this._getContextItems = fallbackGetContextItems; } public IServiceScope GetScope() { - return HttpContextDependencyInjectionExtensions.GetScope(_getContextItems()); + return HttpContextDependencyInjectionExtensions.GetScope(this._getContextItems()); } internal void SetContextItemsFunc(Func getContextItems) { - _getContextItems = getContextItems ?? fallbackGetContextItems; + this._getContextItems = getContextItems ?? fallbackGetContextItems; } } } diff --git a/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs b/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs index 3cfe4fc287f..0348de3d6e0 100644 --- a/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs +++ b/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs @@ -1,49 +1,88 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Cache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.EventQueue.Config { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Cache; + [Serializable] internal class EventQueueConfiguration - { - #region "Constructors" - + { internal EventQueueConfiguration() { - PublishedEvents = new Dictionary(); - EventQueueSubscribers = new Dictionary(); - } - - #endregion - - #region "Public Properties" - + this.PublishedEvents = new Dictionary(); + this.EventQueueSubscribers = new Dictionary(); + } + internal Dictionary EventQueueSubscribers { get; set; } - internal Dictionary PublishedEvents { get; set; } - - #endregion + internal Dictionary PublishedEvents { get; set; } - #region "Private Methods" + public static void RegisterEventSubscription(EventQueueConfiguration config, string eventname, SubscriberInfo subscriber) + { + var e = new PublishedEvent(); + e.EventName = eventname; + e.Subscribers = subscriber.ID; + config.PublishedEvents.Add(e.EventName, e); + if (!config.EventQueueSubscribers.ContainsKey(subscriber.ID)) + { + config.EventQueueSubscribers.Add(subscriber.ID, subscriber); + } + } + + internal static EventQueueConfiguration GetConfig() + { + var config = (EventQueueConfiguration)DataCache.GetCache("EventQueueConfig"); + if (config == null) + { + string filePath = Globals.HostMapPath + "EventQueue\\EventQueue.config"; + if (File.Exists(filePath)) + { + config = new EventQueueConfiguration(); + + // Deserialize into EventQueueConfiguration + config.Deserialize(FileSystemUtils.ReadFile(filePath)); + + // Set back into Cache + DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); + } + else + { + // make a default config file + config = new EventQueueConfiguration(); + config.PublishedEvents = new Dictionary(); + config.EventQueueSubscribers = new Dictionary(); + var subscriber = new SubscriberInfo("DNN Core"); + RegisterEventSubscription(config, "Application_Start", subscriber); + RegisterEventSubscription(config, "Application_Start_FirstRequest", subscriber); + SaveConfig(config, filePath); + } + } + + return config; + } + internal static void SaveConfig(EventQueueConfiguration config, string filePath) + { + StreamWriter oStream = File.CreateText(filePath); + oStream.WriteLine(config.Serialize()); + oStream.Close(); + + // Set back into Cache + DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); + } + private void Deserialize(string configXml) { - if (!String.IsNullOrEmpty(configXml)) + if (!string.IsNullOrEmpty(configXml)) { var xmlDoc = new XmlDocument { XmlResolver = null }; xmlDoc.LoadXml(configXml); @@ -52,8 +91,9 @@ private void Deserialize(string configXml) var oPublishedEvent = new PublishedEvent(); oPublishedEvent.EventName = xmlItem.SelectSingleNode("EventName").InnerText; oPublishedEvent.Subscribers = xmlItem.SelectSingleNode("Subscribers").InnerText; - PublishedEvents.Add(oPublishedEvent.EventName, oPublishedEvent); + this.PublishedEvents.Add(oPublishedEvent.EventName, oPublishedEvent); } + foreach (XmlElement xmlItem in xmlDoc.SelectNodes("/EventQueueConfig/EventQueueSubscribers/Subscriber")) { var oSubscriberInfo = new SubscriberInfo(); @@ -62,23 +102,11 @@ private void Deserialize(string configXml) oSubscriberInfo.Address = xmlItem.SelectSingleNode("Address").InnerText; oSubscriberInfo.Description = xmlItem.SelectSingleNode("Description").InnerText; oSubscriberInfo.PrivateKey = xmlItem.SelectSingleNode("PrivateKey").InnerText; - EventQueueSubscribers.Add(oSubscriberInfo.ID, oSubscriberInfo); + this.EventQueueSubscribers.Add(oSubscriberInfo.ID, oSubscriberInfo); } } } - public static void RegisterEventSubscription(EventQueueConfiguration config, string eventname, SubscriberInfo subscriber) - { - var e = new PublishedEvent(); - e.EventName = eventname; - e.Subscribers = subscriber.ID; - config.PublishedEvents.Add(e.EventName, e); - if (!config.EventQueueSubscribers.ContainsKey(subscriber.ID)) - { - config.EventQueueSubscribers.Add(subscriber.ID, subscriber); - } - } - private string Serialize() { var settings = new XmlWriterSettings(); @@ -94,75 +122,39 @@ private string Serialize() writer.WriteStartElement("EventQueueConfig"); writer.WriteStartElement("PublishedEvents"); - foreach (string key in PublishedEvents.Keys) + foreach (string key in this.PublishedEvents.Keys) { writer.WriteStartElement("Event"); - writer.WriteElementString("EventName", PublishedEvents[key].EventName); - writer.WriteElementString("Subscribers", PublishedEvents[key].Subscribers); + writer.WriteElementString("EventName", this.PublishedEvents[key].EventName); + writer.WriteElementString("Subscribers", this.PublishedEvents[key].Subscribers); writer.WriteEndElement(); } + writer.WriteEndElement(); writer.WriteStartElement("EventQueueSubscribers"); - foreach (string key in EventQueueSubscribers.Keys) + foreach (string key in this.EventQueueSubscribers.Keys) { writer.WriteStartElement("Subscriber"); - writer.WriteElementString("ID", EventQueueSubscribers[key].ID); - writer.WriteElementString("Name", EventQueueSubscribers[key].Name); - writer.WriteElementString("Address", EventQueueSubscribers[key].Address); - writer.WriteElementString("Description", EventQueueSubscribers[key].Description); - writer.WriteElementString("PrivateKey", EventQueueSubscribers[key].PrivateKey); + writer.WriteElementString("ID", this.EventQueueSubscribers[key].ID); + writer.WriteElementString("Name", this.EventQueueSubscribers[key].Name); + writer.WriteElementString("Address", this.EventQueueSubscribers[key].Address); + writer.WriteElementString("Description", this.EventQueueSubscribers[key].Description); + writer.WriteElementString("PrivateKey", this.EventQueueSubscribers[key].PrivateKey); writer.WriteEndElement(); } + writer.WriteEndElement(); - //Close EventQueueConfig + // Close EventQueueConfig writer.WriteEndElement(); writer.Close(); return sb.ToString(); } - } - #endregion - internal static EventQueueConfiguration GetConfig() - { - var config = (EventQueueConfiguration) DataCache.GetCache("EventQueueConfig"); - if ((config == null)) - { - string filePath = Globals.HostMapPath + "EventQueue\\EventQueue.config"; - if (File.Exists(filePath)) - { - config = new EventQueueConfiguration(); - //Deserialize into EventQueueConfiguration - config.Deserialize(FileSystemUtils.ReadFile(filePath)); - //Set back into Cache - DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); - } - else - { - //make a default config file - config = new EventQueueConfiguration(); - config.PublishedEvents = new Dictionary(); - config.EventQueueSubscribers = new Dictionary(); - var subscriber = new SubscriberInfo("DNN Core"); - RegisterEventSubscription(config, "Application_Start", subscriber); - RegisterEventSubscription(config, "Application_Start_FirstRequest", subscriber); - SaveConfig(config, filePath); - } - } - return config; - } - - internal static void SaveConfig(EventQueueConfiguration config, string filePath) - { - StreamWriter oStream = File.CreateText(filePath); - oStream.WriteLine(config.Serialize()); - oStream.Close(); - //Set back into Cache - DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); - } + } } } diff --git a/DNN Platform/Library/Services/EventQueue/Config/PublishedEvent.cs b/DNN Platform/Library/Services/EventQueue/Config/PublishedEvent.cs index 96afdc235b6..c4c39d2612f 100644 --- a/DNN Platform/Library/Services/EventQueue/Config/PublishedEvent.cs +++ b/DNN Platform/Library/Services/EventQueue/Config/PublishedEvent.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml.Serialization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.EventQueue.Config { + using System; + using System.Xml.Serialization; + [Serializable] public class PublishedEvent { diff --git a/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs b/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs index 5fb72e72d69..11e569ef1e8 100644 --- a/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs +++ b/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs @@ -1,33 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.EventQueue.Config { + using System; + + using DotNetNuke.Security; + [Serializable] public class SubscriberInfo { public SubscriberInfo() { - ID = Guid.NewGuid().ToString(); - Name = ""; - Description = ""; - Address = ""; + this.ID = Guid.NewGuid().ToString(); + this.Name = string.Empty; + this.Description = string.Empty; + this.Address = string.Empty; var oPortalSecurity = PortalSecurity.Instance; - PrivateKey = oPortalSecurity.CreateKey(16); + this.PrivateKey = oPortalSecurity.CreateKey(16); } - public SubscriberInfo(string subscriberName) : this() + public SubscriberInfo(string subscriberName) + : this() { - Name = subscriberName; + this.Name = subscriberName; } public string ID { get; set; } diff --git a/DNN Platform/Library/Services/EventQueue/EventMessage.cs b/DNN Platform/Library/Services/EventQueue/EventMessage.cs index 94c317124d1..838219cb443 100644 --- a/DNN Platform/Library/Services/EventQueue/EventMessage.cs +++ b/DNN Platform/Library/Services/EventQueue/EventMessage.cs @@ -1,33 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.IO; -using System.Text; -using System.Xml; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.EventQueue { + using System; + using System.Collections.Specialized; + using System.IO; + using System.Text; + using System.Xml; + + using DotNetNuke.Common.Utilities; + public enum MessagePriority { High, Medium, - Low + Low, } [Serializable] public class EventMessage - { - #region "Private Members" - + { private NameValueCollection _attributes; private string _authorizedRoles = Null.NullString; private string _body = Null.NullString; @@ -39,30 +32,23 @@ public class EventMessage private string _processorType = Null.NullString; private string _sender = Null.NullString; private DateTime _sentDate; - private string _subscribers = Null.NullString; - - #endregion - - #region "Constructors" - + private string _subscribers = Null.NullString; + public EventMessage() { - _attributes = new NameValueCollection(); - } - - #endregion - - #region "Public Properties" - + this._attributes = new NameValueCollection(); + } + public int EventMessageID { get { - return _eventMessageID; + return this._eventMessageID; } + set { - _eventMessageID = value; + this._eventMessageID = value; } } @@ -70,18 +56,19 @@ public string ProcessorType { get { - if (_processorType == null) + if (this._processorType == null) { return string.Empty; } else { - return _processorType; + return this._processorType; } } + set { - _processorType = value; + this._processorType = value; } } @@ -89,18 +76,19 @@ public string ProcessorCommand { get { - if (_processorCommand == null) + if (this._processorCommand == null) { return string.Empty; } else { - return _processorCommand; + return this._processorCommand; } } + set { - _processorCommand = value; + this._processorCommand = value; } } @@ -108,18 +96,19 @@ public string Body { get { - if (_body == null) + if (this._body == null) { return string.Empty; } else { - return _body; + return this._body; } } + set { - _body = value; + this._body = value; } } @@ -127,18 +116,19 @@ public string Sender { get { - if (_sender == null) + if (this._sender == null) { return string.Empty; } else { - return _sender; + return this._sender; } } + set { - _sender = value; + this._sender = value; } } @@ -146,18 +136,19 @@ public string Subscribers { get { - if (_subscribers == null) + if (this._subscribers == null) { return string.Empty; } else { - return _subscribers; + return this._subscribers; } } + set { - _subscribers = value; + this._subscribers = value; } } @@ -165,18 +156,19 @@ public string AuthorizedRoles { get { - if (_authorizedRoles == null) + if (this._authorizedRoles == null) { return string.Empty; } else { - return _authorizedRoles; + return this._authorizedRoles; } } + set { - _authorizedRoles = value; + this._authorizedRoles = value; } } @@ -184,11 +176,12 @@ public MessagePriority Priority { get { - return _priority; + return this._priority; } + set { - _priority = value; + this._priority = value; } } @@ -196,18 +189,19 @@ public string ExceptionMessage { get { - if (_exceptionMessage == null) + if (this._exceptionMessage == null) { return string.Empty; } else { - return _exceptionMessage; + return this._exceptionMessage; } } + set { - _exceptionMessage = value; + this._exceptionMessage = value; } } @@ -215,11 +209,12 @@ public DateTime SentDate { get { - return _sentDate.ToLocalTime(); + return this._sentDate.ToLocalTime(); } + set { - _sentDate = value.ToUniversalTime(); + this._sentDate = value.ToUniversalTime(); } } @@ -227,11 +222,12 @@ public DateTime ExpirationDate { get { - return _expirationDate.ToLocalTime(); + return this._expirationDate.ToLocalTime(); } + set { - _expirationDate = value.ToUniversalTime(); + this._expirationDate = value.ToUniversalTime(); } } @@ -239,18 +235,15 @@ public NameValueCollection Attributes { get { - return _attributes; + return this._attributes; } + set { - _attributes = value; + this._attributes = value; } - } - - #endregion - - #region "Public Methods" - + } + public void DeserializeAttributes(string configXml) { string attName = Null.NullString; @@ -261,12 +254,12 @@ public void DeserializeAttributes(string configXml) reader.ReadStartElement("Attributes"); if (!reader.IsEmptyElement) { - //Loop throug the Attributes + // Loop throug the Attributes do { reader.ReadStartElement("Attribute"); - //Load it from the Xml + // Load it from the Xml reader.ReadStartElement("Name"); attName = reader.ReadString(); reader.ReadEndElement(); @@ -280,10 +273,11 @@ public void DeserializeAttributes(string configXml) { reader.Read(); } - - //Add attribute to the collection - _attributes.Add(attName, attValue); - } while (reader.ReadToNextSibling("Attribute")); + + // Add attribute to the collection + this._attributes.Add(attName, attValue); + } + while (reader.ReadToNextSibling("Attribute")); } } @@ -299,40 +293,38 @@ public string SerializeAttributes() { writer.WriteStartElement("Attributes"); - foreach (string key in Attributes.Keys) + foreach (string key in this.Attributes.Keys) { writer.WriteStartElement("Attribute"); - //Write the Name element + // Write the Name element writer.WriteElementString("Name", key); - //Write the Value element - if (Attributes[key].IndexOfAny("<'>\"&".ToCharArray()) > -1) + // Write the Value element + if (this.Attributes[key].IndexOfAny("<'>\"&".ToCharArray()) > -1) { writer.WriteStartElement("Value"); - writer.WriteCData(Attributes[key]); + writer.WriteCData(this.Attributes[key]); writer.WriteEndElement(); } else { - //Write value - writer.WriteElementString("Value", Attributes[key]); + // Write value + writer.WriteElementString("Value", this.Attributes[key]); } - //Close the Attribute node + // Close the Attribute node writer.WriteEndElement(); } - //Close the Attributes node + // Close the Attributes node writer.WriteEndElement(); - //Close Writer + // Close Writer writer.Close(); return sb.ToString(); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs b/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs index 2219bb89f8c..67ebc52cbf8 100644 --- a/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs +++ b/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs @@ -1,32 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.EventQueue { + using System.Collections; + public class EventMessageCollection : CollectionBase { public virtual EventMessage this[int index] { get { - return (EventMessage) base.List[index]; + return (EventMessage)this.List[index]; } + set { - base.List[index] = value; + this.List[index] = value; } } public void Add(EventMessage message) { - InnerList.Add(message); + this.InnerList.Add(message); } } } diff --git a/DNN Platform/Library/Services/EventQueue/EventMessageProcessor.cs b/DNN Platform/Library/Services/EventQueue/EventMessageProcessor.cs index bb7c40ca5ad..264df124d6f 100644 --- a/DNN Platform/Library/Services/EventQueue/EventMessageProcessor.cs +++ b/DNN Platform/Library/Services/EventQueue/EventMessageProcessor.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.EventQueue { - /// - /// Basic class of EventMessageProcessor. - /// + /// + /// Basic class of EventMessageProcessor. + /// public abstract class EventMessageProcessorBase { public abstract bool ProcessMessage(EventMessage message); diff --git a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs index 5daa61073b7..af907dd412b 100644 --- a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs +++ b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Framework; -using DotNetNuke.Services.EventQueue.Config; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.EventQueue { - /// - /// EventQueueController provides business layer of event queue. - /// - /// - /// Sometimes when your module running in DotNetNuke,and contains some operats didn't want to execute immediately. - /// e.g: after your module installed into system, and some component you want to registed when the application restart, - /// you can send an 'Application_Start' message, so your specific operation will be executed when application has been restart. - /// - /// - /// - /// var oAppStartMessage = new EventMessage + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Framework; + using DotNetNuke.Services.EventQueue.Config; + using DotNetNuke.Services.Log.EventLog; + + /// + /// EventQueueController provides business layer of event queue. + /// + /// + /// Sometimes when your module running in DotNetNuke,and contains some operats didn't want to execute immediately. + /// e.g: after your module installed into system, and some component you want to registed when the application restart, + /// you can send an 'Application_Start' message, so your specific operation will be executed when application has been restart. + /// + /// + /// + /// var oAppStartMessage = new EventMessage /// { /// Sender = sender, /// Priority = MessagePriority.High, @@ -44,17 +39,36 @@ namespace DotNetNuke.Services.EventQueue /// { /// Config.Touch(); /// } - /// - /// + /// + /// public class EventQueueController - { - #region "Private Shared Methods" + { + /// + /// Gets the messages. + /// + /// Name of the event. + /// event message collection. + public static EventMessageCollection GetMessages(string eventName) + { + return FillMessageCollection(DataProvider.Instance().GetEventMessages(eventName)); + } + /// + /// Gets the messages. + /// + /// Name of the event. + /// The subscriber id. + /// + public static EventMessageCollection GetMessages(string eventName, string subscriberId) + { + return FillMessageCollection(DataProvider.Instance().GetEventMessagesBySubscriber(eventName, subscriberId)); + } + private static EventMessage FillMessage(IDataReader dr, bool CheckForOpenDataReader) { EventMessage message; - //read datareader + // read datareader bool canContinue = true; if (CheckForOpenDataReader) { @@ -64,11 +78,12 @@ private static EventMessage FillMessage(IDataReader dr, bool CheckForOpenDataRea canContinue = true; } } + if (canContinue) { message = new EventMessage(); message.EventMessageID = Convert.ToInt32(Null.SetNull(dr["EventMessageID"], message.EventMessageID)); - message.Priority = (MessagePriority) Enum.Parse(typeof (MessagePriority), Convert.ToString(Null.SetNull(dr["Priority"], message.Priority))); + message.Priority = (MessagePriority)Enum.Parse(typeof(MessagePriority), Convert.ToString(Null.SetNull(dr["Priority"], message.Priority))); message.ProcessorType = Convert.ToString(Null.SetNull(dr["ProcessorType"], message.ProcessorType)); message.ProcessorCommand = Convert.ToString(Null.SetNull(dr["ProcessorCommand"], message.ProcessorCommand)); message.Body = Convert.ToString(Null.SetNull(dr["Body"], message.Body)); @@ -79,7 +94,7 @@ private static EventMessage FillMessage(IDataReader dr, bool CheckForOpenDataRea message.SentDate = Convert.ToDateTime(Null.SetNull(dr["SentDate"], message.SentDate)); message.ExpirationDate = Convert.ToDateTime(Null.SetNull(dr["ExpirationDate"], message.ExpirationDate)); - //Deserialize Attributes + // Deserialize Attributes string xmlAttributes = Null.NullString; xmlAttributes = Convert.ToString(Null.SetNull(dr["Attributes"], xmlAttributes)); message.DeserializeAttributes(xmlAttributes); @@ -88,6 +103,7 @@ private static EventMessage FillMessage(IDataReader dr, bool CheckForOpenDataRea { message = null; } + return message; } @@ -99,9 +115,10 @@ private static EventMessageCollection FillMessageCollection(IDataReader dr) EventMessage obj; while (dr.Read()) { - //fill business object + // fill business object obj = FillMessage(dr, false); - //add to collection + + // add to collection arr.Add(obj); } } @@ -111,15 +128,16 @@ private static EventMessageCollection FillMessageCollection(IDataReader dr) } finally { - //close datareader + // close datareader CBO.CloseDataReader(dr, true); } + return arr; } private static string[] GetSubscribers(string eventName) { - //Get the subscribers to this event + // Get the subscribers to this event string[] subscribers = null; PublishedEvent publishedEvent = null; if (EventQueueConfiguration.GetConfig().PublishedEvents.TryGetValue(eventName, out publishedEvent)) @@ -128,62 +146,38 @@ private static string[] GetSubscribers(string eventName) } else { - subscribers = new string[] {}; + subscribers = new string[] { }; } + return subscribers; - } - - #endregion - - #region "Public Shared Methods" - - /// - /// Gets the messages. - /// - /// Name of the event. - /// event message collection. - public static EventMessageCollection GetMessages(string eventName) - { - return FillMessageCollection(DataProvider.Instance().GetEventMessages(eventName)); - } - - /// - /// Gets the messages. - /// - /// Name of the event. - /// The subscriber id. - /// - public static EventMessageCollection GetMessages(string eventName, string subscriberId) - { - return FillMessageCollection(DataProvider.Instance().GetEventMessagesBySubscriber(eventName, subscriberId)); - } + } - /// - /// Processes the messages. - /// - /// Name of the event. - /// + /// + /// Processes the messages. + /// + /// Name of the event. + /// public static bool ProcessMessages(string eventName) { return ProcessMessages(GetMessages(eventName)); } - /// - /// Processes the messages. - /// - /// Name of the event. - /// The subscriber id. - /// + /// + /// Processes the messages. + /// + /// Name of the event. + /// The subscriber id. + /// public static bool ProcessMessages(string eventName, string subscriberId) { return ProcessMessages(GetMessages(eventName, subscriberId)); } - /// - /// Processes the messages. - /// - /// The event messages. - /// + /// + /// Processes the messages. + /// + /// The event messages. + /// public static bool ProcessMessages(EventMessageCollection eventMessages) { bool success = Null.NullBoolean; @@ -194,20 +188,20 @@ public static bool ProcessMessages(EventMessageCollection eventMessages) try { object oMessageProcessor = Reflection.CreateObject(message.ProcessorType, message.ProcessorType); - if (!((EventMessageProcessorBase) oMessageProcessor).ProcessMessage(message)) + if (!((EventMessageProcessorBase)oMessageProcessor).ProcessMessage(message)) { throw new Exception(); } - - //Set Message comlete so it is not run a second time + + // Set Message comlete so it is not run a second time DataProvider.Instance().SetEventMessageComplete(message.EventMessageID); success = true; } catch { - //log if message could not be processed - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + // log if message could not be processed + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("EventQueue.ProcessMessage", "Message Processing Failed"); log.AddProperty("ProcessorType", message.ProcessorType); log.AddProperty("Body", message.Body); @@ -216,57 +210,61 @@ public static bool ProcessMessages(EventMessageCollection eventMessages) { log.AddProperty(key, message.Attributes[key]); } - if (!String.IsNullOrEmpty(message.ExceptionMessage)) + + if (!string.IsNullOrEmpty(message.ExceptionMessage)) { log.AddProperty("ExceptionMessage", message.ExceptionMessage); } + LogController.Instance.AddLog(log); if (message.ExpirationDate < DateTime.Now) { - //Set Message comlete so it is not run a second time + // Set Message comlete so it is not run a second time DataProvider.Instance().SetEventMessageComplete(message.EventMessageID); } } } + return success; } - /// - /// Sends the message. - /// - /// The message. - /// Name of the event. - /// + /// + /// Sends the message. + /// + /// The message. + /// Name of the event. + /// public static bool SendMessage(EventMessage message, string eventName) { - //set the sent date if it wasn't set by the sender + // set the sent date if it wasn't set by the sender if (message.SentDate != null) { message.SentDate = DateTime.Now; } - - //Get the subscribers to this event + + // Get the subscribers to this event string[] subscribers = GetSubscribers(eventName); - //send a message for each subscriber of the specified event + // send a message for each subscriber of the specified event int intMessageID = Null.NullInteger; bool success = true; try { for (int indx = 0; indx <= subscribers.Length - 1; indx++) { - intMessageID = DataProvider.Instance().AddEventMessage(eventName, - (int) message.Priority, - message.ProcessorType, - message.ProcessorCommand, - message.Body, - message.Sender, - subscribers[indx], - message.AuthorizedRoles, - message.ExceptionMessage, - message.SentDate, - message.ExpirationDate, - message.SerializeAttributes()); + intMessageID = DataProvider.Instance().AddEventMessage( + eventName, + (int)message.Priority, + message.ProcessorType, + message.ProcessorCommand, + message.Body, + message.Sender, + subscribers[indx], + message.AuthorizedRoles, + message.ExceptionMessage, + message.SentDate, + message.ExpirationDate, + message.SerializeAttributes()); } } catch (Exception ex) @@ -274,19 +272,14 @@ public static bool SendMessage(EventMessage message, string eventName) Exceptions.Exceptions.LogException(ex); success = Null.NullBoolean; } + return success; - } - - #endregion - - #region "Obsolete Methods" - + } + [Obsolete("This method is obsolete. Use Sendmessage(message, eventName) instead. Scheduled removal in v10.0.0.")] public bool SendMessage(EventMessage message, string eventName, bool encryptMessage) { return SendMessage(message, eventName); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Exceptions/BasePortalException.cs b/DNN Platform/Library/Services/Exceptions/BasePortalException.cs index bbd8b4ed781..5cb960f4342 100644 --- a/DNN Platform/Library/Services/Exceptions/BasePortalException.cs +++ b/DNN Platform/Library/Services/Exceptions/BasePortalException.cs @@ -1,115 +1,113 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Web; -using System.Xml.Serialization; - -using DotNetNuke.Application; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { - /// - /// Base Portal Exception. - /// + using System; + using System.Reflection; + using System.Runtime.Serialization; + using System.Security.Permissions; + using System.Web; + using System.Xml.Serialization; + + using DotNetNuke.Application; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + + /// + /// Base Portal Exception. + /// public class BasePortalException : Exception { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (BasePortalException)); - private string m_InnerExceptionString; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BasePortalException)); + private string m_InnerExceptionString; private string m_Message; - private string m_Source; + private string m_Source; private string m_StackTrace; - //default constructor - public BasePortalException() + // default constructor + public BasePortalException() { } - //constructor with exception message - public BasePortalException(string message) : base(message) + // constructor with exception message + public BasePortalException(string message) + : base(message) { - InitializePrivateVariables(); + this.InitializePrivateVariables(); } - //constructor with message and inner exception - public BasePortalException(string message, Exception inner) : base(message, inner) + // constructor with message and inner exception + public BasePortalException(string message, Exception inner) + : base(message, inner) { - InitializePrivateVariables(); + this.InitializePrivateVariables(); } - protected BasePortalException(SerializationInfo info, StreamingContext context) : base(info, context) + protected BasePortalException(SerializationInfo info, StreamingContext context) + : base(info, context) { - InitializePrivateVariables(); - AssemblyVersion = info.GetString("m_AssemblyVersion"); - PortalID = info.GetInt32("m_PortalID"); - PortalName = info.GetString("m_PortalName"); - UserID = info.GetInt32("m_UserID"); - UserName = info.GetString("m_Username"); - ActiveTabID = info.GetInt32("m_ActiveTabID"); - ActiveTabName = info.GetString("m_ActiveTabName"); - RawURL = info.GetString("m_RawURL"); - AbsoluteURL = info.GetString("m_AbsoluteURL"); - AbsoluteURLReferrer = info.GetString("m_AbsoluteURLReferrer"); - UserAgent = info.GetString("m_UserAgent"); - DefaultDataProvider = info.GetString("m_DefaultDataProvider"); - ExceptionGUID = info.GetString("m_ExceptionGUID"); - m_InnerExceptionString = info.GetString("m_InnerExceptionString"); - FileName = info.GetString("m_FileName"); - FileLineNumber = info.GetInt32("m_FileLineNumber"); - FileColumnNumber = info.GetInt32("m_FileColumnNumber"); - Method = info.GetString("m_Method"); - m_StackTrace = info.GetString("m_StackTrace"); - m_Message = info.GetString("m_Message"); - m_Source = info.GetString("m_Source"); + this.InitializePrivateVariables(); + this.AssemblyVersion = info.GetString("m_AssemblyVersion"); + this.PortalID = info.GetInt32("m_PortalID"); + this.PortalName = info.GetString("m_PortalName"); + this.UserID = info.GetInt32("m_UserID"); + this.UserName = info.GetString("m_Username"); + this.ActiveTabID = info.GetInt32("m_ActiveTabID"); + this.ActiveTabName = info.GetString("m_ActiveTabName"); + this.RawURL = info.GetString("m_RawURL"); + this.AbsoluteURL = info.GetString("m_AbsoluteURL"); + this.AbsoluteURLReferrer = info.GetString("m_AbsoluteURLReferrer"); + this.UserAgent = info.GetString("m_UserAgent"); + this.DefaultDataProvider = info.GetString("m_DefaultDataProvider"); + this.ExceptionGUID = info.GetString("m_ExceptionGUID"); + this.m_InnerExceptionString = info.GetString("m_InnerExceptionString"); + this.FileName = info.GetString("m_FileName"); + this.FileLineNumber = info.GetInt32("m_FileLineNumber"); + this.FileColumnNumber = info.GetInt32("m_FileColumnNumber"); + this.Method = info.GetString("m_Method"); + this.m_StackTrace = info.GetString("m_StackTrace"); + this.m_Message = info.GetString("m_Message"); + this.m_Source = info.GetString("m_Source"); } - public string AssemblyVersion { get; private set; } + public string AssemblyVersion { get; private set; } - public int PortalID { get; private set; } + public int PortalID { get; private set; } - public string PortalName { get; private set; } + public string PortalName { get; private set; } - public int UserID { get; private set; } + public int UserID { get; private set; } - public string UserName { get; private set; } + public string UserName { get; private set; } - public int ActiveTabID { get; private set; } + public int ActiveTabID { get; private set; } - public string ActiveTabName { get; private set; } + public string ActiveTabName { get; private set; } - public string RawURL { get; private set; } + public string RawURL { get; private set; } - public string AbsoluteURL { get; private set; } + public string AbsoluteURL { get; private set; } - public string AbsoluteURLReferrer { get; private set; } + public string AbsoluteURLReferrer { get; private set; } - public string UserAgent { get; private set; } + public string UserAgent { get; private set; } - public string DefaultDataProvider { get; private set; } + public string DefaultDataProvider { get; private set; } - public string ExceptionGUID { get; private set; } + public string ExceptionGUID { get; private set; } - public string FileName { get; private set; } + public string FileName { get; private set; } - public int FileLineNumber { get; private set; } + public int FileLineNumber { get; private set; } - public int FileColumnNumber { get; private set; } + public int FileColumnNumber { get; private set; } - public string Method { get; private set; } + public string Method { get; private set; } - [XmlIgnore] + [XmlIgnore] public new MethodBase TargetSite { get @@ -120,154 +118,157 @@ protected BasePortalException(SerializationInfo info, StreamingContext context) private void InitializePrivateVariables() { - //Try and get the Portal settings from context - //If an error occurs getting the context then set the variables to -1 + // Try and get the Portal settings from context + // If an error occurs getting the context then set the variables to -1 try { var context = HttpContext.Current; var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var innerException = new Exception(Message, this); + var innerException = new Exception(this.Message, this); while (innerException.InnerException != null) { innerException = innerException.InnerException; } + var exceptionInfo = Exceptions.GetExceptionInfo(innerException); - AssemblyVersion = DotNetNukeContext.Current.Application.Version.ToString(3); + this.AssemblyVersion = DotNetNukeContext.Current.Application.Version.ToString(3); if (portalSettings != null) { - PortalID = portalSettings.PortalId; - PortalName = portalSettings.PortalName; - ActiveTabID = portalSettings.ActiveTab.TabID; - ActiveTabName = portalSettings.ActiveTab.TabName; + this.PortalID = portalSettings.PortalId; + this.PortalName = portalSettings.PortalName; + this.ActiveTabID = portalSettings.ActiveTab.TabID; + this.ActiveTabName = portalSettings.ActiveTab.TabName; } else { - PortalID = -1; - PortalName = ""; - ActiveTabID = -1; - ActiveTabName = ""; + this.PortalID = -1; + this.PortalName = string.Empty; + this.ActiveTabID = -1; + this.ActiveTabName = string.Empty; } var currentUserInfo = UserController.Instance.GetCurrentUserInfo(); - UserID = (currentUserInfo != null) ? currentUserInfo.UserID : -1; + this.UserID = (currentUserInfo != null) ? currentUserInfo.UserID : -1; - if (UserID != -1) + if (this.UserID != -1) { - currentUserInfo = UserController.GetUserById(PortalID, UserID); - UserName = currentUserInfo != null ? currentUserInfo.Username : ""; + currentUserInfo = UserController.GetUserById(this.PortalID, this.UserID); + this.UserName = currentUserInfo != null ? currentUserInfo.Username : string.Empty; } else { - UserName = ""; + this.UserName = string.Empty; } if (context != null) { - RawURL = HttpUtility.HtmlEncode(context.Request.RawUrl); - AbsoluteURL = HttpUtility.HtmlEncode(context.Request.Url.AbsolutePath); + this.RawURL = HttpUtility.HtmlEncode(context.Request.RawUrl); + this.AbsoluteURL = HttpUtility.HtmlEncode(context.Request.Url.AbsolutePath); if (context.Request.UrlReferrer != null) { - AbsoluteURLReferrer = HttpUtility.HtmlEncode(context.Request.UrlReferrer.AbsoluteUri); + this.AbsoluteURLReferrer = HttpUtility.HtmlEncode(context.Request.UrlReferrer.AbsoluteUri); } - UserAgent = HttpUtility.HtmlEncode(context.Request.UserAgent ?? ""); + + this.UserAgent = HttpUtility.HtmlEncode(context.Request.UserAgent ?? string.Empty); } else { - RawURL = ""; - AbsoluteURL = ""; - AbsoluteURLReferrer = ""; - UserAgent = ""; + this.RawURL = string.Empty; + this.AbsoluteURL = string.Empty; + this.AbsoluteURLReferrer = string.Empty; + this.UserAgent = string.Empty; } + try { ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data"); string strTypeName = ((Provider)objProviderConfiguration.Providers[objProviderConfiguration.DefaultProvider]).Type; - DefaultDataProvider = strTypeName; - + this.DefaultDataProvider = strTypeName; } catch (Exception exc) { Logger.Error(exc); - DefaultDataProvider = ""; + this.DefaultDataProvider = string.Empty; } - ExceptionGUID = Guid.NewGuid().ToString(); + this.ExceptionGUID = Guid.NewGuid().ToString(); if (exceptionInfo != null) { - FileName = exceptionInfo.FileName; - FileLineNumber = exceptionInfo.FileLineNumber; - FileColumnNumber = exceptionInfo.FileColumnNumber; - Method = exceptionInfo.Method; + this.FileName = exceptionInfo.FileName; + this.FileLineNumber = exceptionInfo.FileLineNumber; + this.FileColumnNumber = exceptionInfo.FileColumnNumber; + this.Method = exceptionInfo.Method; } else { - FileName = ""; - FileLineNumber = -1; - FileColumnNumber = -1; - Method = ""; + this.FileName = string.Empty; + this.FileLineNumber = -1; + this.FileColumnNumber = -1; + this.Method = string.Empty; } try { - m_StackTrace = StackTrace; + this.m_StackTrace = this.StackTrace; } catch (Exception exc) { Logger.Error(exc); - m_StackTrace = ""; + this.m_StackTrace = string.Empty; } + try { - m_Message = Message; + this.m_Message = this.Message; } catch (Exception exc) { Logger.Error(exc); - m_Message = ""; + this.m_Message = string.Empty; } + try { - m_Source = Source; + this.m_Source = this.Source; } catch (Exception exc) { Logger.Error(exc); - m_Source = ""; + this.m_Source = string.Empty; } } catch (Exception exc) { - PortalID = -1; - UserID = -1; - AssemblyVersion = "-1"; - ActiveTabID = -1; - ActiveTabName = ""; - RawURL = ""; - AbsoluteURL = ""; - AbsoluteURLReferrer = ""; - UserAgent = ""; - DefaultDataProvider = ""; - ExceptionGUID = ""; - FileName = ""; - FileLineNumber = -1; - FileColumnNumber = -1; - Method = ""; - m_StackTrace = ""; - m_Message = ""; - m_Source = ""; + this.PortalID = -1; + this.UserID = -1; + this.AssemblyVersion = "-1"; + this.ActiveTabID = -1; + this.ActiveTabName = string.Empty; + this.RawURL = string.Empty; + this.AbsoluteURL = string.Empty; + this.AbsoluteURLReferrer = string.Empty; + this.UserAgent = string.Empty; + this.DefaultDataProvider = string.Empty; + this.ExceptionGUID = string.Empty; + this.FileName = string.Empty; + this.FileLineNumber = -1; + this.FileColumnNumber = -1; + this.Method = string.Empty; + this.m_StackTrace = string.Empty; + this.m_Message = string.Empty; + this.m_Source = string.Empty; Logger.Error(exc); - } } - //public override void GetObjectData(SerializationInfo info, StreamingContext context) - //{ + // public override void GetObjectData(SerializationInfo info, StreamingContext context) + // { // //Serialize this class' state and then call the base class GetObjectData // info.AddValue("m_AssemblyVersion", AssemblyVersion, typeof (string)); // info.AddValue("m_PortalID", PortalID, typeof (Int32)); @@ -290,6 +291,6 @@ private void InitializePrivateVariables() // info.AddValue("m_Message", m_Message, typeof (string)); // info.AddValue("m_Source", m_Source, typeof (string)); // base.GetObjectData(info, context); - //} + // } } } diff --git a/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs b/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs index 5ea070f2af6..7525066b789 100644 --- a/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs +++ b/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs @@ -1,31 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.UI; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { + using System; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.UI.Skins.Controls; + + using Localization = DotNetNuke.Services.Localization.Localization; + public class ErrorContainer : Control { public ErrorContainer(string strError) { - Container = FormatException(strError); + this.Container = this.FormatException(strError); } public ErrorContainer(string strError, Exception exc) { - Container = FormatException(strError, exc); + this.Container = this.FormatException(strError, exc); } public ErrorContainer(PortalSettings _PortalSettings, string strError, Exception exc) @@ -33,11 +30,11 @@ public ErrorContainer(PortalSettings _PortalSettings, string strError, Exception UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); if (objUserInfo.IsSuperUser) { - Container = FormatException(strError, exc); + this.Container = this.FormatException(strError, exc); } else { - Container = FormatException(strError); + this.Container = this.FormatException(strError); } } @@ -46,7 +43,7 @@ public ErrorContainer(PortalSettings _PortalSettings, string strError, Exception private ModuleMessage FormatException(string strError) { ModuleMessage m; - m = UI.Skins.Skin.GetModuleMessageControl(Localization.Localization.GetString("ErrorOccurred"), strError, ModuleMessage.ModuleMessageType.RedError); + m = UI.Skins.Skin.GetModuleMessageControl(Localization.GetString("ErrorOccurred"), strError, ModuleMessage.ModuleMessageType.RedError); return m; } @@ -59,8 +56,9 @@ private ModuleMessage FormatException(string strError, Exception exc) } else { - m = UI.Skins.Skin.GetModuleMessageControl(Localization.Localization.GetString("ErrorOccurred"), strError, ModuleMessage.ModuleMessageType.RedError); + m = UI.Skins.Skin.GetModuleMessageControl(Localization.GetString("ErrorOccurred"), strError, ModuleMessage.ModuleMessageType.RedError); } + return m; } } diff --git a/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs b/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs index 8550ac0939b..8fecf5615a6 100644 --- a/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs +++ b/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Security.Cryptography; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Exceptions { + using System; + using System.Security.Cryptography; + using System.Text; + public static class ExceptionExtensions { public static string Hash(this Exception exc) @@ -36,8 +36,15 @@ public static string Hash(this Exception exc) private static void AddException(StringBuilder sb, Exception ex) { - if (!string.IsNullOrEmpty(ex.Message)) sb.AppendLine(ex.Message); - if (!string.IsNullOrEmpty(ex.StackTrace)) sb.AppendLine(ex.StackTrace); + if (!string.IsNullOrEmpty(ex.Message)) + { + sb.AppendLine(ex.Message); + } + + if (!string.IsNullOrEmpty(ex.StackTrace)) + { + sb.AppendLine(ex.StackTrace); + } } } } diff --git a/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs b/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs index cea1699f281..d6abfedf59c 100644 --- a/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs +++ b/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs @@ -1,212 +1,205 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Exceptions +{ + using System; + using System.IO; + using System.Net; + using System.Text; + using System.Xml; + + [Serializable] + public class ExceptionInfo + { + public ExceptionInfo() + { + } + + public ExceptionInfo(Exception e) + { + this.Message = e.Message; + this.StackTrace = e.StackTrace; + this.Source = e.Source; + if (e.InnerException != null) + { + this.InnerMessage = e.InnerException.Message; + this.InnerStackTrace = e.InnerException.StackTrace; + } + + this.ExceptionHash = e.Hash(); + } + + public string AssemblyVersion { get; set; } -using System; -using System.IO; -using System.Net; -using System.Text; -using System.Xml; + public int PortalId { get; set; } -#endregion + public int UserId { get; set; } -namespace DotNetNuke.Services.Exceptions -{ - [Serializable] - public class ExceptionInfo - { - - #region Constructors - public ExceptionInfo() { } - - public ExceptionInfo(Exception e) - { - Message = e.Message; - StackTrace = e.StackTrace; - Source = e.Source; - if (e.InnerException != null) - { - InnerMessage = e.InnerException.Message; - InnerStackTrace = e.InnerException.StackTrace; - } - ExceptionHash = e.Hash(); - } - #endregion - - #region Properties - public string AssemblyVersion { get; set; } - - public int PortalId { get; set; } - - public int UserId { get; set; } - - public int TabId { get; set; } - - public string RawUrl { get; set; } - - public string Referrer { get; set; } - - public string UserAgent { get; set; } - - public string ExceptionHash { get; set; } - - public string Message { get; set; } - - public string StackTrace { get; set; } - - public string InnerMessage { get; set; } - - public string InnerStackTrace { get; set; } - - public string Source { get; set; } - - public string FileName { get; set; } - - public int FileLineNumber { get; set; } - - public int FileColumnNumber { get; set; } - - public string Method { get; set; } - #endregion - - #region Public Methods - public void Deserialize(string content) - { - using (XmlReader reader = XmlReader.Create(new StringReader(content))) - { - if (reader.Read()) - { - ReadXml(reader); - } - reader.Close(); - } - } - - public void ReadXml(XmlReader reader) - { - do - { - switch (reader.Name) - { - case "AssemblyVersion": - AssemblyVersion = reader.ReadContentAsString(); - break; - case "PortalId": - PortalId = reader.ReadContentAsInt(); - break; - case "UserId": - UserId = reader.ReadContentAsInt(); - break; - case "TabId": - TabId = reader.ReadContentAsInt(); - break; - case "RawUrl": - RawUrl = reader.ReadContentAsString(); - break; - case "Referrer": - Referrer = reader.ReadContentAsString(); - break; - case "UserAgent": - UserAgent = reader.ReadContentAsString(); - break; - case "ExceptionHash": - ExceptionHash = reader.ReadContentAsString(); - break; - case "Message": - Message = reader.ReadContentAsString(); - break; - case "StackTrace": - StackTrace = reader.ReadContentAsString(); - break; - case "InnerMessage": - InnerMessage = reader.ReadContentAsString(); - break; - case "InnerStackTrace": - InnerStackTrace = reader.ReadContentAsString(); - break; - case "Source": - Source = reader.ReadContentAsString(); - break; - case "FileName": - FileName = reader.ReadContentAsString(); - break; - case "FileLineNumber": - FileLineNumber = reader.ReadContentAsInt(); - break; - case "FileColumnNumber": - FileColumnNumber = reader.ReadContentAsInt(); - break; - case "Method": - Method = reader.ReadContentAsString(); - break; - } - reader.ReadEndElement(); - reader.Read(); - } while (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !String.IsNullOrEmpty(reader.LocalName)); - } - - public string Serialize() - { - var settings = new XmlWriterSettings(); - settings.ConformanceLevel = ConformanceLevel.Fragment; - settings.OmitXmlDeclaration = true; - var sb = new StringBuilder(); + public int TabId { get; set; } + + public string RawUrl { get; set; } + + public string Referrer { get; set; } + + public string UserAgent { get; set; } + + public string ExceptionHash { get; set; } + + public string Message { get; set; } + + public string StackTrace { get; set; } + + public string InnerMessage { get; set; } + + public string InnerStackTrace { get; set; } + + public string Source { get; set; } + + public string FileName { get; set; } + + public int FileLineNumber { get; set; } + + public int FileColumnNumber { get; set; } + + public string Method { get; set; } + + public void Deserialize(string content) + { + using (XmlReader reader = XmlReader.Create(new StringReader(content))) + { + if (reader.Read()) + { + this.ReadXml(reader); + } + + reader.Close(); + } + } + + public void ReadXml(XmlReader reader) + { + do + { + switch (reader.Name) + { + case "AssemblyVersion": + this.AssemblyVersion = reader.ReadContentAsString(); + break; + case "PortalId": + this.PortalId = reader.ReadContentAsInt(); + break; + case "UserId": + this.UserId = reader.ReadContentAsInt(); + break; + case "TabId": + this.TabId = reader.ReadContentAsInt(); + break; + case "RawUrl": + this.RawUrl = reader.ReadContentAsString(); + break; + case "Referrer": + this.Referrer = reader.ReadContentAsString(); + break; + case "UserAgent": + this.UserAgent = reader.ReadContentAsString(); + break; + case "ExceptionHash": + this.ExceptionHash = reader.ReadContentAsString(); + break; + case "Message": + this.Message = reader.ReadContentAsString(); + break; + case "StackTrace": + this.StackTrace = reader.ReadContentAsString(); + break; + case "InnerMessage": + this.InnerMessage = reader.ReadContentAsString(); + break; + case "InnerStackTrace": + this.InnerStackTrace = reader.ReadContentAsString(); + break; + case "Source": + this.Source = reader.ReadContentAsString(); + break; + case "FileName": + this.FileName = reader.ReadContentAsString(); + break; + case "FileLineNumber": + this.FileLineNumber = reader.ReadContentAsInt(); + break; + case "FileColumnNumber": + this.FileColumnNumber = reader.ReadContentAsInt(); + break; + case "Method": + this.Method = reader.ReadContentAsString(); + break; + } + + reader.ReadEndElement(); + reader.Read(); + } + while (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !string.IsNullOrEmpty(reader.LocalName)); + } + + public string Serialize() + { + var settings = new XmlWriterSettings(); + settings.ConformanceLevel = ConformanceLevel.Fragment; + settings.OmitXmlDeclaration = true; + var sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, settings)) { - WriteXml(writer); + this.WriteXml(writer); writer.Close(); return sb.ToString(); } - } - - public override string ToString() - { - var str = new StringBuilder(); - str.Append("

    AssemblyVersion:" + WebUtility.HtmlEncode(AssemblyVersion) + "

    "); - str.Append("

    PortalId:" + PortalId + "

    "); - str.Append("

    UserId:" + UserId + "

    "); - str.Append("

    TabId:" + TabId + "

    "); - str.Append("

    RawUrl:" + WebUtility.HtmlEncode(RawUrl) + "

    "); - str.Append("

    Referrer:" + WebUtility.HtmlEncode(Referrer) + "

    "); - str.Append("

    UserAgent:" + WebUtility.HtmlEncode(UserAgent) + "

    "); - str.Append("

    ExceptionHash:" + WebUtility.HtmlEncode(ExceptionHash) + "

    "); - str.Append("

    Message:" + WebUtility.HtmlEncode(Message) + "

    "); - str.Append("

    StackTrace:

    " + WebUtility.HtmlEncode(StackTrace)?.Replace(") at ", ")
    at ") + "

    "); - str.Append("

    InnerMessage:" + WebUtility.HtmlEncode(InnerMessage) + "

    "); - str.Append("

    InnerStackTrace:

    " + WebUtility.HtmlEncode(InnerStackTrace)?.Replace(") at ",")
    at ") + "

    "); - str.Append("

    Source:" + WebUtility.HtmlEncode(Source) + "

    "); - str.Append("

    FileName:" + WebUtility.HtmlEncode(FileName) + "

    "); - str.Append("

    FileLineNumber:" + FileLineNumber + "

    "); - str.Append("

    FileColumnNumber:" + FileColumnNumber + "

    "); - str.Append("

    Method:" + WebUtility.HtmlEncode(Method) + "

    "); - return str.ToString(); - } - - public void WriteXml(XmlWriter writer) - { - writer.WriteStartElement("Exception"); - writer.WriteElementString("AssemblyVersion", AssemblyVersion); - writer.WriteElementString("PortalId", PortalId.ToString()); - writer.WriteElementString("UserId", UserId.ToString()); - writer.WriteElementString("TabId", TabId.ToString()); - writer.WriteElementString("RawUrl", RawUrl); - writer.WriteElementString("Referrer", Referrer); - writer.WriteElementString("UserAgent", UserAgent); - writer.WriteElementString("ExceptionHash", ExceptionHash); - writer.WriteElementString("Message", Message); - writer.WriteElementString("StackTrace", StackTrace); - writer.WriteElementString("InnerMessage", InnerMessage); - writer.WriteElementString("InnerStackTrace", InnerStackTrace); - writer.WriteElementString("Source", Source); - writer.WriteElementString("FileName", FileName); - writer.WriteElementString("FileLineNumber", FileLineNumber.ToString()); - writer.WriteElementString("FileColumnNumber", FileColumnNumber.ToString()); - writer.WriteElementString("Method", Method); - writer.WriteEndElement(); - } - #endregion - - } + } + + public override string ToString() + { + var str = new StringBuilder(); + str.Append("

    AssemblyVersion:" + WebUtility.HtmlEncode(this.AssemblyVersion) + "

    "); + str.Append("

    PortalId:" + this.PortalId + "

    "); + str.Append("

    UserId:" + this.UserId + "

    "); + str.Append("

    TabId:" + this.TabId + "

    "); + str.Append("

    RawUrl:" + WebUtility.HtmlEncode(this.RawUrl) + "

    "); + str.Append("

    Referrer:" + WebUtility.HtmlEncode(this.Referrer) + "

    "); + str.Append("

    UserAgent:" + WebUtility.HtmlEncode(this.UserAgent) + "

    "); + str.Append("

    ExceptionHash:" + WebUtility.HtmlEncode(this.ExceptionHash) + "

    "); + str.Append("

    Message:" + WebUtility.HtmlEncode(this.Message) + "

    "); + str.Append("

    StackTrace:

    " + WebUtility.HtmlEncode(this.StackTrace)?.Replace(") at ", ")
    at ") + "

    "); + str.Append("

    InnerMessage:" + WebUtility.HtmlEncode(this.InnerMessage) + "

    "); + str.Append("

    InnerStackTrace:

    " + WebUtility.HtmlEncode(this.InnerStackTrace)?.Replace(") at ", ")
    at ") + "

    "); + str.Append("

    Source:" + WebUtility.HtmlEncode(this.Source) + "

    "); + str.Append("

    FileName:" + WebUtility.HtmlEncode(this.FileName) + "

    "); + str.Append("

    FileLineNumber:" + this.FileLineNumber + "

    "); + str.Append("

    FileColumnNumber:" + this.FileColumnNumber + "

    "); + str.Append("

    Method:" + WebUtility.HtmlEncode(this.Method) + "

    "); + return str.ToString(); + } + + public void WriteXml(XmlWriter writer) + { + writer.WriteStartElement("Exception"); + writer.WriteElementString("AssemblyVersion", this.AssemblyVersion); + writer.WriteElementString("PortalId", this.PortalId.ToString()); + writer.WriteElementString("UserId", this.UserId.ToString()); + writer.WriteElementString("TabId", this.TabId.ToString()); + writer.WriteElementString("RawUrl", this.RawUrl); + writer.WriteElementString("Referrer", this.Referrer); + writer.WriteElementString("UserAgent", this.UserAgent); + writer.WriteElementString("ExceptionHash", this.ExceptionHash); + writer.WriteElementString("Message", this.Message); + writer.WriteElementString("StackTrace", this.StackTrace); + writer.WriteElementString("InnerMessage", this.InnerMessage); + writer.WriteElementString("InnerStackTrace", this.InnerStackTrace); + writer.WriteElementString("Source", this.Source); + writer.WriteElementString("FileName", this.FileName); + writer.WriteElementString("FileLineNumber", this.FileLineNumber.ToString()); + writer.WriteElementString("FileColumnNumber", this.FileColumnNumber.ToString()); + writer.WriteElementString("Method", this.Method); + writer.WriteEndElement(); + } + } } diff --git a/DNN Platform/Library/Services/Exceptions/Exceptions.cs b/DNN Platform/Library/Services/Exceptions/Exceptions.cs index c29fd7f9869..d8b08813b21 100644 --- a/DNN Platform/Library/Services/Exceptions/Exceptions.cs +++ b/DNN Platform/Library/Services/Exceptions/Exceptions.cs @@ -1,66 +1,61 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Diagnostics; -using System.Reflection; -using System.Threading; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Modules; - -using Microsoft.VisualBasic.CompilerServices; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { - /// - /// Exceptions class provides operation to log most of the exceptions occured in system. - /// - /// - /// - /// For most developers, there is a hard problem need to face to is that our product will run on many and many servers with - /// much different environment, such as hardware, network, system version, framework version and so on, so there is many of reasons - /// will make our application throw lof of exceptions,even will stop our app to working. so when some error occured, we need a way - /// to find out the reason, we know we need to log all the exception, but the point is how to log useful information, you should log - /// the information what you need to location the code caught the error, but DONOT just log 'ERROR'. so we provide a full support of - /// exception log system. when error occured, we can found the detail information in event log and can locationt the error quickly. - /// - /// - /// Current we immplement lot of custom exception to use in different levels: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + using System; + using System.Diagnostics; + using System.Reflection; + using System.Threading; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.UI.Modules; + using Microsoft.VisualBasic.CompilerServices; + + /// + /// Exceptions class provides operation to log most of the exceptions occured in system. + /// + /// + /// + /// For most developers, there is a hard problem need to face to is that our product will run on many and many servers with + /// much different environment, such as hardware, network, system version, framework version and so on, so there is many of reasons + /// will make our application throw lof of exceptions,even will stop our app to working. so when some error occured, we need a way + /// to find out the reason, we know we need to log all the exception, but the point is how to log useful information, you should log + /// the information what you need to location the code caught the error, but DONOT just log 'ERROR'. so we provide a full support of + /// exception log system. when error occured, we can found the detail information in event log and can locationt the error quickly. + /// + /// + /// Current we immplement lot of custom exception to use in different levels: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// [StandardModule] public sealed class Exceptions { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Exceptions)); - /// - /// Gets the exception info. - /// - /// The exception. - /// Exception info. + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Exceptions)); + + /// + /// Gets the exception info. + /// + /// The exception. + /// Exception info. public static ExceptionInfo GetExceptionInfo(Exception e) { var objExceptionInfo = new ExceptionInfo(e); @@ -76,13 +71,16 @@ public static ExceptionInfo GetExceptionInfo(Exception e) { try { - //Get the corresponding method for that stack frame. + // Get the corresponding method for that stack frame. MemberInfo mi = sf.GetMethod(); - //Get the namespace where that method is defined. + + // Get the namespace where that method is defined. string res = mi.DeclaringType.Namespace + "."; - //Append the type name. + + // Append the type name. res += mi.DeclaringType.Name + "."; - //Append the name of the method. + + // Append the name of the method. res += mi.Name; objExceptionInfo.Method = res; } @@ -92,21 +90,37 @@ public static ExceptionInfo GetExceptionInfo(Exception e) objExceptionInfo.Method = "N/A - Reflection Permission required"; } - if (!String.IsNullOrEmpty(sf.GetFileName())) + + if (!string.IsNullOrEmpty(sf.GetFileName())) { objExceptionInfo.FileName = sf.GetFileName(); objExceptionInfo.FileColumnNumber = sf.GetFileColumnNumber(); objExceptionInfo.FileLineNumber = sf.GetFileLineNumber(); } } + return objExceptionInfo; } - /// - /// Threads the abort check if the exception is a ThreadAbortCheck. - /// - /// The exc. - /// + public static void ProcessHttpException() + { + var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); + var exc = new HttpException(404, notFoundErrorString); + ProcessHttpException(exc, HttpContext.Current.Request.RawUrl); + } + + public static void ProcessHttpException(string URL) + { + var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); + var exc = new HttpException(404, notFoundErrorString); + ProcessHttpException(exc, URL); + } + + /// + /// Threads the abort check if the exception is a ThreadAbortCheck. + /// + /// The exc. + /// private static bool ThreadAbortCheck(Exception exc) { if (exc is ThreadAbortException) @@ -120,41 +134,48 @@ private static bool ThreadAbortCheck(Exception exc) } } - public static void ProcessHttpException() + public static void ProcessHttpException(HttpException exc) { - var notFoundErrorString = Localization.Localization.GetString("ResourceNotFound", Localization.Localization.SharedResourceFile); - var exc = new HttpException(404, notFoundErrorString); ProcessHttpException(exc, HttpContext.Current.Request.RawUrl); } - public static void ProcessHttpException(string URL) + public static void ProcessHttpException(HttpRequest request) { - var notFoundErrorString = Localization.Localization.GetString("ResourceNotFound", Localization.Localization.SharedResourceFile); + var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); var exc = new HttpException(404, notFoundErrorString); - ProcessHttpException(exc, URL); + ProcessHttpException(exc, request.RawUrl); } - public static void ProcessHttpException(HttpException exc) + /// + /// Processes the module load exception. + /// + /// The portal module base. + /// The exc. + public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc) { - ProcessHttpException(exc, HttpContext.Current.Request.RawUrl); + ProcessModuleLoadException((Control)objPortalModuleBase, exc); } - public static void ProcessHttpException(HttpRequest request) + /// + /// Processes the module load exception. + /// + /// The portal module base. + /// The exc. + /// if set to true display error message. + public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc, bool DisplayErrorMessage) { - var notFoundErrorString = Localization.Localization.GetString("ResourceNotFound", Localization.Localization.SharedResourceFile); - var exc = new HttpException(404, notFoundErrorString); - ProcessHttpException(exc, request.RawUrl); + ProcessModuleLoadException((Control)objPortalModuleBase, exc, DisplayErrorMessage); } - private static void ProcessHttpException(HttpException exc, string URL) + private static void ProcessHttpException(HttpException exc, string URL) { - var notFoundErrorString = Localization.Localization.GetString("ResourceNotFound", Localization.Localization.SharedResourceFile); + var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); Logger.Error(notFoundErrorString + ": - " + URL, exc); var log = new LogInfo { BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() + LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), }; log.LogProperties.Add(new LogDetailInfo(notFoundErrorString, "URL")); var context = HttpContext.Current; @@ -162,123 +183,108 @@ private static void ProcessHttpException(HttpException exc, string URL) { log.LogProperties.Add(new LogDetailInfo("URL:", URL)); } + LogController.Instance.AddLog(log); - - + throw exc; } - /// - /// Processes the module load exception. - /// - /// The portal module base. - /// The exc. - public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc) - { - ProcessModuleLoadException((Control) objPortalModuleBase, exc); - } - - /// - /// Processes the module load exception. - /// - /// The portal module base. - /// The exc. - /// if set to true display error message. - public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc, bool DisplayErrorMessage) - { - ProcessModuleLoadException((Control) objPortalModuleBase, exc, DisplayErrorMessage); - } - - /// - /// Processes the module load exception. - /// - /// The friendly message. - /// The obj portal module base. - /// The exc. - /// if set to true display error message. + /// + /// Processes the module load exception. + /// + /// The friendly message. + /// The obj portal module base. + /// The exc. + /// if set to true display error message. public static void ProcessModuleLoadException(string FriendlyMessage, PortalModuleBase objPortalModuleBase, Exception exc, bool DisplayErrorMessage) { - ProcessModuleLoadException(FriendlyMessage, (Control) objPortalModuleBase, exc, DisplayErrorMessage); + ProcessModuleLoadException(FriendlyMessage, (Control)objPortalModuleBase, exc, DisplayErrorMessage); } - /// - /// Processes the module load exception. - /// - /// The CTRL. - /// The exc. + /// + /// Processes the module load exception. + /// + /// The CTRL. + /// The exc. public static void ProcessModuleLoadException(Control ctrl, Exception exc) { - //Exit Early if ThreadAbort Exception + // Exit Early if ThreadAbort Exception if (ThreadAbortCheck(exc)) { return; } + ProcessModuleLoadException(ctrl, exc, true); } - /// - /// Processes the module load exception. - /// - /// The CTRL. - /// The exc. - /// if set to true [display error message]. + /// + /// Processes the module load exception. + /// + /// The CTRL. + /// The exc. + /// if set to true [display error message]. public static void ProcessModuleLoadException(Control ctrl, Exception exc, bool DisplayErrorMessage) { - //Exit Early if ThreadAbort Exception + // Exit Early if ThreadAbort Exception if (ThreadAbortCheck(exc)) { return; } - string friendlyMessage = Localization.Localization.GetString("ErrorOccurred"); + + string friendlyMessage = Localization.GetString("ErrorOccurred"); var ctrlModule = ctrl as IModuleControl; if (ctrlModule == null) { - //Regular Control - friendlyMessage = Localization.Localization.GetString("ErrorOccurred"); + // Regular Control + friendlyMessage = Localization.GetString("ErrorOccurred"); } else { - //IModuleControl + // IModuleControl string moduleTitle = Null.NullString; if (ctrlModule != null && ctrlModule.ModuleContext.Configuration != null) { moduleTitle = ctrlModule.ModuleContext.Configuration.ModuleTitle; } - friendlyMessage = string.Format(Localization.Localization.GetString("ModuleUnavailable"), moduleTitle); + + friendlyMessage = string.Format(Localization.GetString("ModuleUnavailable"), moduleTitle); } + ProcessModuleLoadException(friendlyMessage, ctrl, exc, DisplayErrorMessage); } - /// - /// Processes the module load exception. - /// - /// The friendly message. - /// The CTRL. - /// The exc. + /// + /// Processes the module load exception. + /// + /// The friendly message. + /// The CTRL. + /// The exc. public static void ProcessModuleLoadException(string FriendlyMessage, Control ctrl, Exception exc) { - //Exit Early if ThreadAbort Exception + // Exit Early if ThreadAbort Exception if (ThreadAbortCheck(exc)) { return; } + ProcessModuleLoadException(FriendlyMessage, ctrl, exc, true); } - /// - /// Processes the module load exception. - /// - /// The friendly message. - /// The CTRL. - /// The exc. - /// if set to true display error message. + /// + /// Processes the module load exception. + /// + /// The friendly message. + /// The CTRL. + /// The exc. + /// if set to true display error message. public static void ProcessModuleLoadException(string FriendlyMessage, Control ctrl, Exception exc, bool DisplayErrorMessage) - { - //Exit Early if ThreadAbort Exception + { + // Exit Early if ThreadAbort Exception if (ThreadAbortCheck(exc)) { return; } + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); try { @@ -294,7 +300,7 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct if (Host.DebugMode && exc is HttpParseException) { - var httpParseError = ((HttpParseException)exc); + var httpParseError = (HttpParseException)exc; friendlyMessageOverride = string.Concat(exc.Message, " in ", httpParseError.VirtualPath, ":line ", httpParseError.Line); } @@ -307,28 +313,30 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct lex = new ModuleLoadException(friendlyMessageOverride, exc, ctrlModule.ModuleContext.Configuration); } - //publish the exception + // publish the exception var objExceptionLog = new ExceptionLogController(); objExceptionLog.AddLog(lex); - //Some modules may want to suppress an error message - //and just log the exception. + + // Some modules may want to suppress an error message + // and just log the exception. if (DisplayErrorMessage) { PlaceHolder ErrorPlaceholder = null; if (ctrl.Parent != null) { - ErrorPlaceholder = (PlaceHolder) ctrl.Parent.FindControl("MessagePlaceHolder"); + ErrorPlaceholder = (PlaceHolder)ctrl.Parent.FindControl("MessagePlaceHolder"); } + if (ErrorPlaceholder != null) { - //hide the module + // hide the module ctrl.Visible = false; ErrorPlaceholder.Visible = true; ErrorPlaceholder.Controls.Add(new ErrorContainer(_portalSettings, FriendlyMessage, lex).Container); } else { - //there's no ErrorPlaceholder, add it to the module's control collection + // there's no ErrorPlaceholder, add it to the module's control collection ctrl.Controls.Add(new ErrorContainer(_portalSettings, FriendlyMessage, lex).Container); } } @@ -339,14 +347,14 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct Logger.Fatal(exc2); ProcessPageLoadException(exc2); } + Logger.ErrorFormat("FriendlyMessage=\"{0}\" ctrl=\"{1}\" exc=\"{2}\"", FriendlyMessage, ctrl, exc); - } - /// - /// Processes the page load exception. - /// - /// The exc. + /// + /// Processes the page load exception. + /// + /// The exc. public static void ProcessPageLoadException(Exception exc) { PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -359,14 +367,15 @@ public static void ProcessPageLoadException(Exception exc) { appURL += "&def=ErrorMessage"; } + ProcessPageLoadException(exc, appURL); } - /// - /// Processes the page load exception. - /// - /// The exc. - /// The URL. + /// + /// Processes the page load exception. + /// + /// The exc. + /// The URL. public static void ProcessPageLoadException(Exception exc, string URL) { Logger.Error(URL, exc); @@ -374,23 +383,24 @@ public static void ProcessPageLoadException(Exception exc, string URL) { return; } + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (!Host.UseCustomErrorMessages) { - throw new PageLoadException((exc == null ? "" : exc.Message), exc); + throw new PageLoadException(exc == null ? string.Empty : exc.Message, exc); } else { - var lex = new PageLoadException((exc == null ? "" : exc.Message), exc); - //publish the exception + var lex = new PageLoadException(exc == null ? string.Empty : exc.Message, exc); + + // publish the exception var objExceptionLog = new ExceptionLogController(); objExceptionLog.AddLog(lex); - if (!String.IsNullOrEmpty(URL)) + if (!string.IsNullOrEmpty(URL)) { - //redirect + // redirect if (URL.IndexOf("error=terminate") != -1) { - HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); } @@ -402,10 +412,10 @@ public static void ProcessPageLoadException(Exception exc, string URL) } } - /// - /// Logs the ModuleLoadException. - /// - /// The exc. + /// + /// Logs the ModuleLoadException. + /// + /// The exc. public static void LogException(ModuleLoadException exc) { Logger.Error(exc); @@ -413,10 +423,10 @@ public static void LogException(ModuleLoadException exc) objExceptionLog.AddLog(exc, ExceptionLogController.ExceptionLogType.MODULE_LOAD_EXCEPTION); } - /// - /// Logs the PageLoadException. - /// - /// The exc. + /// + /// Logs the PageLoadException. + /// + /// The exc. public static void LogException(PageLoadException exc) { Logger.Error(exc); @@ -424,10 +434,10 @@ public static void LogException(PageLoadException exc) objExceptionLog.AddLog(exc, ExceptionLogController.ExceptionLogType.PAGE_LOAD_EXCEPTION); } - /// - /// Logs the SchedulerException. - /// - /// The exc. + /// + /// Logs the SchedulerException. + /// + /// The exc. public static void LogException(SchedulerException exc) { Logger.Error(exc); @@ -435,10 +445,10 @@ public static void LogException(SchedulerException exc) objExceptionLog.AddLog(exc, ExceptionLogController.ExceptionLogType.SCHEDULER_EXCEPTION); } - /// - /// Logs the SecurityException. - /// - /// The exc. + /// + /// Logs the SecurityException. + /// + /// The exc. public static void LogException(SecurityException exc) { Logger.Error(exc); @@ -446,10 +456,10 @@ public static void LogException(SecurityException exc) objExceptionLog.AddLog(exc, ExceptionLogController.ExceptionLogType.SECURITY_EXCEPTION); } - /// - /// Logs all the basic exception. - /// - /// The exc. + /// + /// Logs all the basic exception. + /// + /// The exc. public static void LogException(Exception exc) { Logger.Error(exc); @@ -457,10 +467,10 @@ public static void LogException(Exception exc) objExceptionLog.AddLog(exc, ExceptionLogController.ExceptionLogType.GENERAL_EXCEPTION); } - /// - /// Processes the scheduler exception. - /// - /// The exc. + /// + /// Processes the scheduler exception. + /// + /// The exc. public static void ProcessSchedulerException(Exception exc) { Logger.Error(exc); @@ -468,10 +478,10 @@ public static void ProcessSchedulerException(Exception exc) objExceptionLog.AddLog(exc, ExceptionLogController.ExceptionLogType.SCHEDULER_EXCEPTION); } - /// - /// Logs the search exception. - /// - /// The exc. + /// + /// Logs the search exception. + /// + /// The exc. public static void LogSearchException(SearchException exc) { Logger.Error(exc); diff --git a/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs b/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs index e6fa8290a59..af1e987f324 100644 --- a/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs +++ b/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Xml.Serialization; - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { + using System; + using System.Runtime.Serialization; + using System.Security.Permissions; + using System.Xml.Serialization; + + using DotNetNuke.Entities.Modules; + public class ModuleLoadException : BasePortalException { private readonly ModuleInfo m_ModuleConfiguration; @@ -23,36 +18,40 @@ public class ModuleLoadException : BasePortalException private int m_ModuleDefId; private int m_ModuleId; - //default constructor - public ModuleLoadException() + // default constructor + public ModuleLoadException() { } - //constructor with exception message - public ModuleLoadException(string message) : base(message) + // constructor with exception message + public ModuleLoadException(string message) + : base(message) { - InitilizePrivateVariables(); + this.InitilizePrivateVariables(); } - //constructor with exception message - public ModuleLoadException(string message, Exception inner, ModuleInfo ModuleConfiguration) : base(message, inner) + // constructor with exception message + public ModuleLoadException(string message, Exception inner, ModuleInfo ModuleConfiguration) + : base(message, inner) { - m_ModuleConfiguration = ModuleConfiguration; - InitilizePrivateVariables(); + this.m_ModuleConfiguration = ModuleConfiguration; + this.InitilizePrivateVariables(); } - //constructor with message and inner exception - public ModuleLoadException(string message, Exception inner) : base(message, inner) + // constructor with message and inner exception + public ModuleLoadException(string message, Exception inner) + : base(message, inner) { - InitilizePrivateVariables(); + this.InitilizePrivateVariables(); } - protected ModuleLoadException(SerializationInfo info, StreamingContext context) : base(info, context) + protected ModuleLoadException(SerializationInfo info, StreamingContext context) + : base(info, context) { - InitilizePrivateVariables(); - m_ModuleId = info.GetInt32("m_ModuleId"); - m_ModuleDefId = info.GetInt32("m_ModuleDefId"); - m_FriendlyName = info.GetString("m_FriendlyName"); + this.InitilizePrivateVariables(); + this.m_ModuleId = info.GetInt32("m_ModuleId"); + this.m_ModuleDefId = info.GetInt32("m_ModuleDefId"); + this.m_FriendlyName = info.GetString("m_FriendlyName"); } [XmlElement("ModuleID")] @@ -60,7 +59,7 @@ public int ModuleId { get { - return m_ModuleId; + return this.m_ModuleId; } } @@ -69,7 +68,7 @@ public int ModuleDefId { get { - return m_ModuleDefId; + return this.m_ModuleDefId; } } @@ -78,7 +77,7 @@ public string FriendlyName { get { - return m_FriendlyName; + return this.m_FriendlyName; } } @@ -87,36 +86,36 @@ public string ModuleControlSource { get { - return m_ModuleControlSource; + return this.m_ModuleControlSource; } } private void InitilizePrivateVariables() { - //Try and get the Portal settings from context - //If an error occurs getting the context then set the variables to -1 - if ((m_ModuleConfiguration != null)) + // Try and get the Portal settings from context + // If an error occurs getting the context then set the variables to -1 + if (this.m_ModuleConfiguration != null) { - m_ModuleId = m_ModuleConfiguration.ModuleID; - m_ModuleDefId = m_ModuleConfiguration.ModuleDefID; - m_FriendlyName = m_ModuleConfiguration.ModuleTitle; - m_ModuleControlSource = m_ModuleConfiguration.ModuleControl.ControlSrc; + this.m_ModuleId = this.m_ModuleConfiguration.ModuleID; + this.m_ModuleDefId = this.m_ModuleConfiguration.ModuleDefID; + this.m_FriendlyName = this.m_ModuleConfiguration.ModuleTitle; + this.m_ModuleControlSource = this.m_ModuleConfiguration.ModuleControl.ControlSrc; } else { - m_ModuleId = -1; - m_ModuleDefId = -1; + this.m_ModuleId = -1; + this.m_ModuleDefId = -1; } } - //public override void GetObjectData(SerializationInfo info, StreamingContext context) - //{ + // public override void GetObjectData(SerializationInfo info, StreamingContext context) + // { // //Serialize this class' state and then call the base class GetObjectData // info.AddValue("m_ModuleId", m_ModuleId, typeof (Int32)); // info.AddValue("m_ModuleDefId", m_ModuleDefId, typeof (Int32)); // info.AddValue("m_FriendlyName", m_FriendlyName, typeof (string)); // info.AddValue("m_ModuleControlSource", m_ModuleControlSource, typeof (string)); // base.GetObjectData(info, context); - //} + // } } } diff --git a/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs b/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs index b5facc24810..0355a66a286 100644 --- a/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs +++ b/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs @@ -1,39 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Runtime.Serialization; -using System.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { + using System; + using System.Collections.Generic; + using System.Data; + using System.Runtime.Serialization; + using System.Security.Permissions; + public class ObjectHydrationException : BasePortalException { private List _Columns; private Type _Type; - public ObjectHydrationException(string message, Exception innerException) : base(message, innerException) + public ObjectHydrationException(string message, Exception innerException) + : base(message, innerException) { } - public ObjectHydrationException(string message, Exception innerException, Type type, IDataReader dr) : base(message, innerException) + public ObjectHydrationException(string message, Exception innerException, Type type, IDataReader dr) + : base(message, innerException) { - _Type = type; - _Columns = new List(); + this._Type = type; + this._Columns = new List(); foreach (DataRow row in dr.GetSchemaTable().Rows) { - _Columns.Add(row["ColumnName"].ToString()); + this._Columns.Add(row["ColumnName"].ToString()); } } - protected ObjectHydrationException(SerializationInfo info, StreamingContext context) : base(info, context) + protected ObjectHydrationException(SerializationInfo info, StreamingContext context) + : base(info, context) { } @@ -41,11 +39,12 @@ public List Columns { get { - return _Columns; + return this._Columns; } + set { - _Columns = value; + this._Columns = value; } } @@ -53,11 +52,12 @@ public Type Type { get { - return _Type; + return this._Type; } + set { - _Type = value; + this._Type = value; } } @@ -66,12 +66,13 @@ public override string Message get { string _Message = base.Message; - _Message += " Expecting - " + Type + "."; + _Message += " Expecting - " + this.Type + "."; _Message += " Returned - "; - foreach (string columnName in Columns) + foreach (string columnName in this.Columns) { _Message += columnName + ", "; } + return _Message; } } diff --git a/DNN Platform/Library/Services/Exceptions/PageLoadException.cs b/DNN Platform/Library/Services/Exceptions/PageLoadException.cs index 3ae6f50fc55..01e9a5c7c5e 100644 --- a/DNN Platform/Library/Services/Exceptions/PageLoadException.cs +++ b/DNN Platform/Library/Services/Exceptions/PageLoadException.cs @@ -1,35 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Runtime.Serialization; -using System.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { + using System; + using System.Runtime.Serialization; + using System.Security.Permissions; + public class PageLoadException : BasePortalException { - //default constructor - public PageLoadException() + // default constructor + public PageLoadException() { } - //constructor with exception message - public PageLoadException(string message) : base(message) + // constructor with exception message + public PageLoadException(string message) + : base(message) { } - //constructor with message and inner exception - public PageLoadException(string message, Exception inner) : base(message, inner) + // constructor with message and inner exception + public PageLoadException(string message, Exception inner) + : base(message, inner) { } - protected PageLoadException(SerializationInfo info, StreamingContext context) : base(info, context) + protected PageLoadException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/DNN Platform/Library/Services/Exceptions/SchedulerException.cs b/DNN Platform/Library/Services/Exceptions/SchedulerException.cs index ac87d1fb7c4..61bab29931c 100644 --- a/DNN Platform/Library/Services/Exceptions/SchedulerException.cs +++ b/DNN Platform/Library/Services/Exceptions/SchedulerException.cs @@ -1,35 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Runtime.Serialization; -using System.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { + using System; + using System.Runtime.Serialization; + using System.Security.Permissions; + public class SchedulerException : BasePortalException { - //default constructor - public SchedulerException() + // default constructor + public SchedulerException() { } - //constructor with exception message - public SchedulerException(string message) : base(message) + // constructor with exception message + public SchedulerException(string message) + : base(message) { } - //constructor with message and inner exception - public SchedulerException(string message, Exception inner) : base(message, inner) + // constructor with message and inner exception + public SchedulerException(string message, Exception inner) + : base(message, inner) { } - protected SchedulerException(SerializationInfo info, StreamingContext context) : base(info, context) + protected SchedulerException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/DNN Platform/Library/Services/Exceptions/SearchException.cs b/DNN Platform/Library/Services/Exceptions/SearchException.cs index 4b610645814..6ea75bdf999 100644 --- a/DNN Platform/Library/Services/Exceptions/SearchException.cs +++ b/DNN Platform/Library/Services/Exceptions/SearchException.cs @@ -1,39 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { - #pragma warning disable 0618 + using System; + + using DotNetNuke.Services.Search; + +#pragma warning disable 0618 public class SearchException : BasePortalException { private readonly SearchItemInfo m_SearchItem; - //default constructor - public SearchException() + // default constructor + public SearchException() { } - public SearchException(string message, Exception inner, SearchItemInfo searchItem) : base(message, inner) + public SearchException(string message, Exception inner, SearchItemInfo searchItem) + : base(message, inner) { - m_SearchItem = searchItem; + this.m_SearchItem = searchItem; } public SearchItemInfo SearchItem { get { - return m_SearchItem; + return this.m_SearchItem; } } - } - #pragma warning restore 0618 + } +#pragma warning restore 0618 } diff --git a/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs b/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs index 45f089effd7..d67ac67e064 100644 --- a/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs +++ b/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Exceptions { + using System; + public class SearchIndexEmptyException : Exception { - public SearchIndexEmptyException(string message) : base(message) + public SearchIndexEmptyException(string message) + : base(message) { } } diff --git a/DNN Platform/Library/Services/Exceptions/SecurityException.cs b/DNN Platform/Library/Services/Exceptions/SecurityException.cs index 7e975486e6c..29c03632a1f 100644 --- a/DNN Platform/Library/Services/Exceptions/SecurityException.cs +++ b/DNN Platform/Library/Services/Exceptions/SecurityException.cs @@ -1,49 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Web; -using System.Xml.Serialization; - -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Exceptions { + using System; + using System.Runtime.Serialization; + using System.Security.Permissions; + using System.Web; + using System.Xml.Serialization; + + using DotNetNuke.Instrumentation; + public class SecurityException : BasePortalException { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SecurityException)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SecurityException)); private string m_IP; private string m_Querystring; - //default constructor + // default constructor public SecurityException() { } - //constructor with exception message - public SecurityException(string message) : base(message) + // constructor with exception message + public SecurityException(string message) + : base(message) { - InitilizePrivateVariables(); + this.InitilizePrivateVariables(); } - //constructor with message and inner exception - public SecurityException(string message, Exception inner) : base(message, inner) + // constructor with message and inner exception + public SecurityException(string message, Exception inner) + : base(message, inner) { - InitilizePrivateVariables(); + this.InitilizePrivateVariables(); } - protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context) + protected SecurityException(SerializationInfo info, StreamingContext context) + : base(info, context) { - InitilizePrivateVariables(); - m_IP = info.GetString("m_IP"); - m_Querystring = info.GetString("m_Querystring"); + this.InitilizePrivateVariables(); + this.m_IP = info.GetString("m_IP"); + this.m_Querystring = info.GetString("m_Querystring"); } [XmlElement("IP")] @@ -51,7 +49,7 @@ public string IP { get { - return m_IP; + return this.m_IP; } } @@ -60,36 +58,36 @@ public string Querystring { get { - return m_Querystring; + return this.m_Querystring; } } private void InitilizePrivateVariables() { - //Try and get the Portal settings from httpcontext + // Try and get the Portal settings from httpcontext try { if (HttpContext.Current.Request.UserHostAddress != null) { - m_IP = HttpContext.Current.Request.UserHostAddress; + this.m_IP = HttpContext.Current.Request.UserHostAddress; } - m_Querystring = HttpContext.Current.Request.MapPath(Querystring, HttpContext.Current.Request.ApplicationPath, false); + + this.m_Querystring = HttpContext.Current.Request.MapPath(this.Querystring, HttpContext.Current.Request.ApplicationPath, false); } catch (Exception exc) { - m_IP = ""; - m_Querystring = ""; + this.m_IP = string.Empty; + this.m_Querystring = string.Empty; Logger.Error(exc); - } } - //public override void GetObjectData(SerializationInfo info, StreamingContext context) - //{ + // public override void GetObjectData(SerializationInfo info, StreamingContext context) + // { // //Serialize this class' state and then call the base class GetObjectData // info.AddValue("m_IP", m_IP, typeof (string)); // info.AddValue("m_Querystring", m_Querystring, typeof (string)); // base.GetObjectData(info, context); - //} + // } } } diff --git a/DNN Platform/Library/Services/FileSystem/ContentDisposition.cs b/DNN Platform/Library/Services/FileSystem/ContentDisposition.cs index 1f214e99cef..5507064897f 100644 --- a/DNN Platform/Library/Services/FileSystem/ContentDisposition.cs +++ b/DNN Platform/Library/Services/FileSystem/ContentDisposition.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { /// @@ -13,9 +13,10 @@ public enum ContentDisposition /// The browser will display a dialog to allow the user to save or view the document. /// Attachment, + /// /// The document will be displayed automatically. /// - Inline + Inline, } } diff --git a/DNN Platform/Library/Services/FileSystem/DefaultMetadataNames.cs b/DNN Platform/Library/Services/FileSystem/DefaultMetadataNames.cs index e4b54bfa68e..cea59d59a92 100644 --- a/DNN Platform/Library/Services/FileSystem/DefaultMetadataNames.cs +++ b/DNN Platform/Library/Services/FileSystem/DefaultMetadataNames.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + public struct DefaultMetadataNames { public const string Created = "Created"; diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileAddedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileAddedEventArgs.cs index c828036b65e..920cf571607 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileAddedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileAddedEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FileAddedEventArgs : FileChangedEventArgs diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs index b2dce550524..b7f7a28da37 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FileChangedEventArgs : System.EventArgs { public IFileInfo FileInfo { get; set; } + public int UserId { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileDeletedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileDeletedEventArgs.cs index 94ee2110bfa..98c54611224 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileDeletedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileDeletedEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FileDeletedEventArgs : FileChangedEventArgs diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs index 2fdd7bac806..ee1837bc9a7 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FileDownloadedEventArgs : System.EventArgs { public IFileInfo FileInfo { get; set; } + public int UserId { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileMovedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileMovedEventArgs.cs index d2be8d74586..cc4bad7ca84 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileMovedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileMovedEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FileMovedEventArgs : FileChangedEventArgs diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileRenamedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileRenamedEventArgs.cs index ada2c7c5b69..d19de929a8b 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileRenamedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileRenamedEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FileRenamedEventArgs : FileChangedEventArgs diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs index 8b4ccf54a77..85e60f747a9 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FolderChangedEventArgs : System.EventArgs { public IFolderInfo FolderInfo { get; set; } + public int UserId { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderDeletedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderDeletedEventArgs.cs index b5efa20b0c6..acc9ca2d3fc 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderDeletedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderDeletedEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FolderDeletedEventArgs : FolderChangedEventArgs diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderMovedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderMovedEventArgs.cs index 29c2e25bcbe..f18add28e72 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderMovedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderMovedEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FolderMovedEventArgs : FolderChangedEventArgs diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderRenamedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderRenamedEventArgs.cs index 0c536d90c7b..0c1878089da 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderRenamedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderRenamedEventArgs.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.EventArgs { public class FolderRenamedEventArgs : FolderChangedEventArgs diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/FileAlreadyExistsException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/FileAlreadyExistsException.cs index 1a7e248ff2a..a88af00e3f5 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/FileAlreadyExistsException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/FileAlreadyExistsException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class FileAlreadyExistsException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/FileLockedException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/FileLockedException.cs index d774efd2c0e..6871e60b1fe 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/FileLockedException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/FileLockedException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + [Serializable] public class FileLockedException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/FolderAlreadyExistsException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/FolderAlreadyExistsException.cs index 7f9e259351e..d1f7e56fc42 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/FolderAlreadyExistsException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/FolderAlreadyExistsException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + [Serializable] public class FolderAlreadyExistsException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/FolderProviderException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/FolderProviderException.cs index ccf6d44300b..62e0ca30a68 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/FolderProviderException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/FolderProviderException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class FolderProviderException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileContentException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileContentException.cs index 25031953631..ac2584cbb93 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileContentException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileContentException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class InvalidFileContentException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileExtensionException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileExtensionException.cs index bf2170c6f78..c96a5c642e0 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileExtensionException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFileExtensionException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class InvalidFileExtensionException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFilenameException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFilenameException.cs index e8b2be65bc3..a78a5bfec3b 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFilenameException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFilenameException.cs @@ -1,15 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// Copyright (c) .NET Foundation. All rights reserved -// Licensed under the MIT License. See LICENSE file in the project root for full detail - -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + [Serializable] public class InvalidFilenameException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFolderPathException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFolderPathException.cs index 09b49ad3547..3cce7a805cb 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFolderPathException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidFolderPathException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + [Serializable] public class InvalidFolderPathException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidMetadataValuesException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidMetadataValuesException.cs index 4841ce8d0c9..c6af199121d 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidMetadataValuesException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/InvalidMetadataValuesException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + [Serializable] public class InvalidMetadataValuesException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/NoNetworkAvailableException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/NoNetworkAvailableException.cs index f99ec5bf68a..66aad3cd3fb 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/NoNetworkAvailableException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/NoNetworkAvailableException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + [Serializable] public class NoNetworkAvailableException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/NoSpaceAvailableException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/NoSpaceAvailableException.cs index 00f49dbac4f..43628f83f95 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/NoSpaceAvailableException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/NoSpaceAvailableException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class NoSpaceAvailableException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/Exceptions/PermissionsNotMetException.cs b/DNN Platform/Library/Services/FileSystem/Exceptions/PermissionsNotMetException.cs index d3d6bde8e2a..a0b88456155 100644 --- a/DNN Platform/Library/Services/FileSystem/Exceptions/PermissionsNotMetException.cs +++ b/DNN Platform/Library/Services/FileSystem/Exceptions/PermissionsNotMetException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class PermissionsNotMetException : Exception { diff --git a/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs b/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs index c6bafdfa4a2..b00259e6fae 100644 --- a/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs @@ -1,118 +1,108 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using DotNetNuke.Common.Lists; -using DotNetNuke.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { - public class FileContentTypeManager : ComponentBase, IFileContentTypeManager - { - #region Fields - - private IDictionary _contentTypes; - private static readonly object _threadLocker = new object(); - - #endregion - - #region Implement IFileContentTypeManager - - public virtual IDictionary ContentTypes - { - get - { - if (_contentTypes == null) - { - lock (_threadLocker) - { - if (_contentTypes == null) - { - var listController = new ListController(); - var listEntries = listController.GetListEntryInfoItems("ContentTypes"); - if (listEntries == null || !listEntries.Any()) - { - _contentTypes = GetDefaultContentTypes(); - } - else - { - _contentTypes = new Dictionary(); - if (listEntries != null) - { - foreach (var contentTypeEntry in listEntries) - { - _contentTypes.Add(contentTypeEntry.Value, contentTypeEntry.Text); - } - } - } - } - } - } - - return _contentTypes; - } - } - - public virtual string GetContentType(string extension) - { - - if (string.IsNullOrEmpty(extension)) return "application/octet-stream"; - - var key = extension.TrimStart('.').ToLowerInvariant(); - return ContentTypes.ContainsKey(key) ? ContentTypes[key] : "application/octet-stream"; - } - - #endregion - - #region Private Methods - - private Dictionary GetDefaultContentTypes() - { - var contentTypes = new Dictionary(); - contentTypes.Add("txt", "text/plain"); - contentTypes.Add("htm", "text/html"); - contentTypes.Add("html", "text/html"); - contentTypes.Add("rtf", "text/richtext"); - contentTypes.Add("jpg", "image/jpeg"); - contentTypes.Add("jpeg", "image/jpeg"); - contentTypes.Add("gif", "image/gif"); - contentTypes.Add("bmp", "image/bmp"); - contentTypes.Add("png", "image/png"); - contentTypes.Add("ico", "image/x-icon"); - contentTypes.Add("svg", "image/svg+xml"); - contentTypes.Add("ttf", "font/ttf"); - contentTypes.Add("eot", "application/vnd.ms-fontobject"); - contentTypes.Add("woff", "application/font-woff"); - contentTypes.Add("mp3", "audio/mpeg"); - contentTypes.Add("wma", "audio/x-ms-wma"); - contentTypes.Add("mpg", "video/mpeg"); - contentTypes.Add("mpeg", "video/mpeg"); - contentTypes.Add("avi", "video/avi"); - contentTypes.Add("mp4", "video/mp4"); - contentTypes.Add("wmv", "video/x-ms-wmv"); - contentTypes.Add("pdf", "application/pdf"); - contentTypes.Add("doc", "application/msword"); - contentTypes.Add("dot", "application/msword"); - contentTypes.Add("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); - contentTypes.Add("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"); - contentTypes.Add("csv", "text/csv"); - contentTypes.Add("xls", "application/x-msexcel"); - contentTypes.Add("xlt", "application/x-msexcel"); - contentTypes.Add("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - contentTypes.Add("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"); - contentTypes.Add("ppt", "application/vnd.ms-powerpoint"); - contentTypes.Add("pps", "application/vnd.ms-powerpoint"); - contentTypes.Add("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); - contentTypes.Add("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Common.Lists; + using DotNetNuke.ComponentModel; + + public class FileContentTypeManager : ComponentBase, IFileContentTypeManager + { + private static readonly object _threadLocker = new object(); + private IDictionary _contentTypes; + + public virtual IDictionary ContentTypes + { + get + { + if (this._contentTypes == null) + { + lock (_threadLocker) + { + if (this._contentTypes == null) + { + var listController = new ListController(); + var listEntries = listController.GetListEntryInfoItems("ContentTypes"); + if (listEntries == null || !listEntries.Any()) + { + this._contentTypes = this.GetDefaultContentTypes(); + } + else + { + this._contentTypes = new Dictionary(); + if (listEntries != null) + { + foreach (var contentTypeEntry in listEntries) + { + this._contentTypes.Add(contentTypeEntry.Value, contentTypeEntry.Text); + } + } + } + } + } + } - return contentTypes; - } + return this._contentTypes; + } + } - #endregion + public virtual string GetContentType(string extension) + { + if (string.IsNullOrEmpty(extension)) + { + return "application/octet-stream"; + } + + var key = extension.TrimStart('.').ToLowerInvariant(); + return this.ContentTypes.ContainsKey(key) ? this.ContentTypes[key] : "application/octet-stream"; + } + + private Dictionary GetDefaultContentTypes() + { + var contentTypes = new Dictionary(); + contentTypes.Add("txt", "text/plain"); + contentTypes.Add("htm", "text/html"); + contentTypes.Add("html", "text/html"); + contentTypes.Add("rtf", "text/richtext"); + contentTypes.Add("jpg", "image/jpeg"); + contentTypes.Add("jpeg", "image/jpeg"); + contentTypes.Add("gif", "image/gif"); + contentTypes.Add("bmp", "image/bmp"); + contentTypes.Add("png", "image/png"); + contentTypes.Add("ico", "image/x-icon"); + contentTypes.Add("svg", "image/svg+xml"); + contentTypes.Add("ttf", "font/ttf"); + contentTypes.Add("eot", "application/vnd.ms-fontobject"); + contentTypes.Add("woff", "application/font-woff"); + contentTypes.Add("mp3", "audio/mpeg"); + contentTypes.Add("wma", "audio/x-ms-wma"); + contentTypes.Add("mpg", "video/mpeg"); + contentTypes.Add("mpeg", "video/mpeg"); + contentTypes.Add("avi", "video/avi"); + contentTypes.Add("mp4", "video/mp4"); + contentTypes.Add("wmv", "video/x-ms-wmv"); + contentTypes.Add("pdf", "application/pdf"); + contentTypes.Add("doc", "application/msword"); + contentTypes.Add("dot", "application/msword"); + contentTypes.Add("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + contentTypes.Add("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"); + contentTypes.Add("csv", "text/csv"); + contentTypes.Add("xls", "application/x-msexcel"); + contentTypes.Add("xlt", "application/x-msexcel"); + contentTypes.Add("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + contentTypes.Add("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"); + contentTypes.Add("ppt", "application/vnd.ms-powerpoint"); + contentTypes.Add("pps", "application/vnd.ms-powerpoint"); + contentTypes.Add("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); + contentTypes.Add("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); - } + return contentTypes; + } + } } diff --git a/DNN Platform/Library/Services/FileSystem/FileInfo.cs b/DNN Platform/Library/Services/FileSystem/FileInfo.cs index da7fe3ebc06..b5ea750fa37 100644 --- a/DNN Platform/Library/Services/FileSystem/FileInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FileInfo.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Drawing; -using System.IO; -using System.Web; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem { + using System; + using System.Data; + using System.Drawing; + using System.IO; + using System.Web; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : FileInfo - /// + /// Project : DotNetNuke + /// Class : FileInfo + /// /// ----------------------------------------------------------------------------- /// - /// Represents the File object and holds the Properties of that object + /// Represents the File object and holds the Properties of that object. /// /// ----------------------------------------------------------------------------- [XmlRoot("file", IsNullable = false)] @@ -43,14 +38,12 @@ public class FileInfo : BaseEntityInfo, IHydratable, IFileInfo private int? _width = null; private int? _height = null; - private string _sha1Hash = null; - - #region Constructors - + private string _sha1Hash = null; + public FileInfo() { - UniqueId = Guid.NewGuid(); - VersionGuid = Guid.NewGuid(); + this.UniqueId = Guid.NewGuid(); + this.VersionGuid = Guid.NewGuid(); } public FileInfo(int portalId, string filename, string extension, int filesize, int width, int height, string contentType, string folder, int folderId, int storageLocation, bool cached) @@ -67,26 +60,22 @@ public FileInfo(int portalId, string filename, string extension, int filesize, i public FileInfo(Guid uniqueId, Guid versionGuid, int portalId, string filename, string extension, int filesize, int width, int height, string contentType, string folder, int folderId, int storageLocation, bool cached, string hash) { - UniqueId = uniqueId; - VersionGuid = versionGuid; - PortalId = portalId; - FileName = filename; - Extension = extension; - Size = filesize; - Width = width; - Height = height; - ContentType = contentType; - Folder = folder; - FolderId = folderId; - StorageLocation = storageLocation; - IsCached = cached; - SHA1Hash = hash; - } - - #endregion - - #region Properties - + this.UniqueId = uniqueId; + this.VersionGuid = versionGuid; + this.PortalId = portalId; + this.FileName = filename; + this.Extension = extension; + this.Size = filesize; + this.Width = width; + this.Height = height; + this.ContentType = contentType; + this.Folder = folder; + this.FolderId = folderId; + this.StorageLocation = storageLocation; + this.IsCached = cached; + this.SHA1Hash = hash; + } + [XmlElement("contenttype")] public string ContentType { get; set; } @@ -110,17 +99,18 @@ public string Folder { get { - return _folder; + return this._folder; } + set { - //Make sure folder name ends with / + // Make sure folder name ends with / if (!string.IsNullOrEmpty(value) && !value.EndsWith("/")) { value = value + "/"; } - _folder = value; + this._folder = value; } } @@ -132,16 +122,17 @@ public int Height { get { - if (FileId != 0 && (!_height.HasValue || _height.Value == Null.NullInteger)) + if (this.FileId != 0 && (!this._height.HasValue || this._height.Value == Null.NullInteger)) { - LoadImageProperties(); + this.LoadImageProperties(); } - return _height.Value; + return this._height.Value; } + set { - _height = value; + this._height = value; } } @@ -160,28 +151,28 @@ public string PhysicalPath portalSettings = PortalController.Instance.GetCurrentPortalSettings(); } - if (PortalId == Null.NullInteger) + if (this.PortalId == Null.NullInteger) { - physicalPath = Globals.HostMapPath + RelativePath; + physicalPath = Globals.HostMapPath + this.RelativePath; } else { - if (portalSettings == null || portalSettings.PortalId != PortalId) + if (portalSettings == null || portalSettings.PortalId != this.PortalId) { - //Get the PortalInfo based on the Portalid - var portal = PortalController.Instance.GetPortal(PortalId); - if ((portal != null)) + // Get the PortalInfo based on the Portalid + var portal = PortalController.Instance.GetPortal(this.PortalId); + if (portal != null) { - physicalPath = portal.HomeDirectoryMapPath + RelativePath; + physicalPath = portal.HomeDirectoryMapPath + this.RelativePath; } } else { - physicalPath = portalSettings.HomeDirectoryMapPath + RelativePath; + physicalPath = portalSettings.HomeDirectoryMapPath + this.RelativePath; } } - if ((!string.IsNullOrEmpty(physicalPath))) + if (!string.IsNullOrEmpty(physicalPath)) { physicalPath = physicalPath.Replace("/", "\\"); } @@ -197,7 +188,7 @@ public string RelativePath { get { - return Folder + FileName; + return this.Folder + this.FileName; } } @@ -212,16 +203,17 @@ public int Width { get { - if (FileId != 0 && (!_width.HasValue || _width.Value == Null.NullInteger)) + if (this.FileId != 0 && (!this._width.HasValue || this._width.Value == Null.NullInteger)) { - LoadImageProperties(); + this.LoadImageProperties(); } - return _width.Value; + return this._width.Value; } + set { - _width = value; + this._width = value; } } @@ -230,16 +222,17 @@ public string SHA1Hash { get { - if (FileId > 0 && string.IsNullOrEmpty(_sha1Hash)) + if (this.FileId > 0 && string.IsNullOrEmpty(this._sha1Hash)) { - LoadHashProperty(); + this.LoadHashProperty(); } - return _sha1Hash; + return this._sha1Hash; } + set { - _sha1Hash = value; + this._sha1Hash = value; } } @@ -249,9 +242,9 @@ public FileAttributes? FileAttributes { FileAttributes? _fileAttributes = null; - if (SupportsFileAttributes) + if (this.SupportsFileAttributes) { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(PortalId, FolderMappingID); + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalId, this.FolderMappingID); _fileAttributes = FolderProvider.Instance(folderMapping.FolderProviderType).GetFileAttributes(this); } @@ -263,21 +256,21 @@ public bool SupportsFileAttributes { get { - if (!_supportsFileAttributes.HasValue) + if (!this._supportsFileAttributes.HasValue) { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(PortalId, FolderMappingID); + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalId, this.FolderMappingID); try { - _supportsFileAttributes = FolderProvider.Instance(folderMapping.FolderProviderType).SupportsFileAttributes(); + this._supportsFileAttributes = FolderProvider.Instance(folderMapping.FolderProviderType).SupportsFileAttributes(); } catch { - _supportsFileAttributes = false; + this._supportsFileAttributes = false; } } - return _supportsFileAttributes.Value; + return this._supportsFileAttributes.Value; } } @@ -285,9 +278,9 @@ public DateTime LastModificationTime { get { - if(!_lastModificationTime.HasValue) + if (!this._lastModificationTime.HasValue) { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(PortalId, FolderMappingID); + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalId, this.FolderMappingID); try { @@ -299,11 +292,12 @@ public DateTime LastModificationTime } } - return _lastModificationTime.Value; + return this._lastModificationTime.Value; } + set { - _lastModificationTime = value; + this._lastModificationTime = value; } } @@ -311,129 +305,96 @@ public int FolderMappingID { get { - if (_folderMappingID == 0) + if (this._folderMappingID == 0) { - if (FolderId > 0) + if (this.FolderId > 0) { - var folder = FolderManager.Instance.GetFolder(FolderId); + var folder = FolderManager.Instance.GetFolder(this.FolderId); if (folder != null) { - _folderMappingID = folder.FolderMappingID; - return _folderMappingID; + this._folderMappingID = folder.FolderMappingID; + return this._folderMappingID; } } - switch (StorageLocation) + switch (this.StorageLocation) { case (int)FolderController.StorageLocationTypes.InsecureFileSystem: - _folderMappingID = FolderMappingController.Instance.GetFolderMapping(PortalId, "Standard").FolderMappingID; + this._folderMappingID = FolderMappingController.Instance.GetFolderMapping(this.PortalId, "Standard").FolderMappingID; break; case (int)FolderController.StorageLocationTypes.SecureFileSystem: - _folderMappingID = FolderMappingController.Instance.GetFolderMapping(PortalId, "Secure").FolderMappingID; + this._folderMappingID = FolderMappingController.Instance.GetFolderMapping(this.PortalId, "Secure").FolderMappingID; break; case (int)FolderController.StorageLocationTypes.DatabaseSecure: - _folderMappingID = FolderMappingController.Instance.GetFolderMapping(PortalId, "Database").FolderMappingID; + this._folderMappingID = FolderMappingController.Instance.GetFolderMapping(this.PortalId, "Database").FolderMappingID; break; default: - _folderMappingID = FolderMappingController.Instance.GetDefaultFolderMapping(PortalId).FolderMappingID; + this._folderMappingID = FolderMappingController.Instance.GetDefaultFolderMapping(this.PortalId).FolderMappingID; break; } } - return _folderMappingID; + return this._folderMappingID; } + set { - _folderMappingID = value; + this._folderMappingID = value; } } /// - /// Gets or sets a metadata field with an optional title associated to the file + /// Gets or sets a metadata field with an optional title associated to the file. /// public string Title { get; set; } public string Description { get; set; } /// - /// Gets or sets the date on which the file starts to be published + /// Gets or sets the date on which the file starts to be published. /// public DateTime StartDate { get; set; } /// - /// Gets or sets the date on which the file ends to be published + /// Gets or sets the date on which the file ends to be published. /// public DateTime EndDate { get; set; } /// - /// Gets or sets a value indicating whether publish period is enabled for the file + /// Gets or sets a value indicating whether publish period is enabled for the file. /// public bool EnablePublishPeriod { get; set; } /// - /// Gets or sets the published version number of the file + /// Gets or sets the published version number of the file. /// public int PublishedVersion { get; set; } /// - /// Gets a flag which says whether the file has ever been published + /// Gets a value indicating whether gets a flag which says whether the file has ever been published. /// [XmlIgnore] public bool HasBeenPublished { get; private set; } /// /// Gets a value indicating whether the file is enabled, - /// considering if the publish period is active and if the current date is within the publish period + /// considering if the publish period is active and if the current date is within the publish period. /// public bool IsEnabled { get { var today = DateTime.Today; - return !EnablePublishPeriod - || (StartDate.Date <= today && (EndDate == Null.NullDate || today <= EndDate.Date)); + return !this.EnablePublishPeriod + || (this.StartDate.Date <= today && (this.EndDate == Null.NullDate || today <= this.EndDate.Date)); } } /// - /// Gets or sets a reference to ContentItem, to use in Workflows + /// Gets or sets a reference to ContentItem, to use in Workflows. /// - public int ContentItemID { get; set; } - - #endregion - - #region IHydratable Implementation - - public void Fill(IDataReader dr) - { - ContentType = Null.SetNullString(dr["ContentType"]); - Extension = Null.SetNullString(dr["Extension"]); - FileId = Null.SetNullInteger(dr["FileId"]); - FileName = Null.SetNullString(dr["FileName"]); - Folder = Null.SetNullString(dr["Folder"]); - FolderId = Null.SetNullInteger(dr["FolderId"]); - Height = Null.SetNullInteger(dr["Height"]); - IsCached = Null.SetNullBoolean(dr["IsCached"]); - PortalId = Null.SetNullInteger(dr["PortalId"]); - SHA1Hash = Null.SetNullString(dr["SHA1Hash"]); - Size = Null.SetNullInteger(dr["Size"]); - StorageLocation = Null.SetNullInteger(dr["StorageLocation"]); - UniqueId = Null.SetNullGuid(dr["UniqueId"]); - VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); - Width = Null.SetNullInteger(dr["Width"]); - LastModificationTime = Null.SetNullDateTime(dr["LastModificationTime"]); - FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); - Title = Null.SetNullString(dr["Title"]); - Description = Null.SetNullString(dr["Description"]); - EnablePublishPeriod = Null.SetNullBoolean(dr["EnablePublishPeriod"]); - StartDate = Null.SetNullDateTime(dr["StartDate"]); - EndDate = Null.SetNullDateTime(dr["EndDate"]); - ContentItemID = Null.SetNullInteger(dr["ContentItemID"]); - PublishedVersion = Null.SetNullInteger(dr["PublishedVersion"]); - HasBeenPublished = Convert.ToBoolean(dr["HasBeenPublished"]); - FillBaseProperties(dr); - } + public int ContentItemID { get; set; } [XmlIgnore] public int KeyID @@ -442,29 +403,57 @@ public int KeyID { return this.FileId; } + set { - FileId = value; + this.FileId = value; } + } + + public void Fill(IDataReader dr) + { + this.ContentType = Null.SetNullString(dr["ContentType"]); + this.Extension = Null.SetNullString(dr["Extension"]); + this.FileId = Null.SetNullInteger(dr["FileId"]); + this.FileName = Null.SetNullString(dr["FileName"]); + this.Folder = Null.SetNullString(dr["Folder"]); + this.FolderId = Null.SetNullInteger(dr["FolderId"]); + this.Height = Null.SetNullInteger(dr["Height"]); + this.IsCached = Null.SetNullBoolean(dr["IsCached"]); + this.PortalId = Null.SetNullInteger(dr["PortalId"]); + this.SHA1Hash = Null.SetNullString(dr["SHA1Hash"]); + this.Size = Null.SetNullInteger(dr["Size"]); + this.StorageLocation = Null.SetNullInteger(dr["StorageLocation"]); + this.UniqueId = Null.SetNullGuid(dr["UniqueId"]); + this.VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); + this.Width = Null.SetNullInteger(dr["Width"]); + this.LastModificationTime = Null.SetNullDateTime(dr["LastModificationTime"]); + this.FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); + this.Title = Null.SetNullString(dr["Title"]); + this.Description = Null.SetNullString(dr["Description"]); + this.EnablePublishPeriod = Null.SetNullBoolean(dr["EnablePublishPeriod"]); + this.StartDate = Null.SetNullDateTime(dr["StartDate"]); + this.EndDate = Null.SetNullDateTime(dr["EndDate"]); + this.ContentItemID = Null.SetNullInteger(dr["ContentItemID"]); + this.PublishedVersion = Null.SetNullInteger(dr["PublishedVersion"]); + this.HasBeenPublished = Convert.ToBoolean(dr["HasBeenPublished"]); + this.FillBaseProperties(dr); } - - #endregion - - #region Private methods - + private void LoadImageProperties() - { + { var fileManager = (FileManager)FileManager.Instance; if (!fileManager.IsImageFile(this)) { - _width = _height = 0; + this._width = this._height = 0; return; } + var fileContent = fileManager.GetFileContent(this); if (fileContent == null) { - //If can't get file content then just exit the function, so it will load again next time. + // If can't get file content then just exit the function, so it will load again next time. return; } @@ -480,14 +469,14 @@ private void LoadImageProperties() { image = fileManager.GetImageFromStream(fileContent); - _width = image.Width; - _height = image.Height; + this._width = image.Width; + this._height = image.Height; } catch { - _width = 0; - _height = 0; - ContentType = "application/octet-stream"; + this._width = 0; + this._height = 0; + this.ContentType = "application/octet-stream"; } finally { @@ -495,23 +484,22 @@ private void LoadImageProperties() { image.Dispose(); } + fileContent.Position = 0; - } + } + fileContent.Close(); } private void LoadHashProperty() { var fileManager = (FileManager)FileManager.Instance; - var currentHashCode = FolderProvider.Instance( FolderMappingController.Instance.GetFolderMapping(FolderMappingID).FolderProviderType).GetHashCode(this); - if (currentHashCode != _sha1Hash) + var currentHashCode = FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(this.FolderMappingID).FolderProviderType).GetHashCode(this); + if (currentHashCode != this._sha1Hash) { - _sha1Hash = currentHashCode; + this._sha1Hash = currentHashCode; fileManager.UpdateFile(this); } - - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs index 5eb1ec5d43f..55ada41a337 100644 --- a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs @@ -1,36 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections.Specialized; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + public class FileLinkClickController : ServiceLocator, IFileLinkClickController { + public string GetFileLinkClick(IFileInfo file) + { + Requires.NotNull("file", file); + var portalId = file.PortalId; + var linkClickPortalSettigns = this.GetPortalSettingsForLinkClick(portalId); + + return TestableGlobals.Instance.LinkClick(string.Format("fileid={0}", file.FileId), Null.NullInteger, Null.NullInteger, true, false, portalId, linkClickPortalSettigns.EnableUrlLanguage, linkClickPortalSettigns.PortalGUID); + } + + public int GetFileIdFromLinkClick(NameValueCollection queryParams) + { + var linkClickPortalSettings = this.GetPortalSettingsForLinkClick(this.GetPortalIdFromLinkClick(queryParams)); + var strFileId = UrlUtils.DecryptParameter(queryParams["fileticket"], linkClickPortalSettings.PortalGUID); + int fileId; + return int.TryParse(strFileId, out fileId) ? fileId : -1; + } + private LinkClickPortalSettings GetPortalSettingsForLinkClick(int portalId) { if (portalId == Null.NullInteger) { - return new LinkClickPortalSettings - { - PortalGUID = Host.GUID, - EnableUrlLanguage = Host.EnableUrlLanguage - }; + return new LinkClickPortalSettings + { + PortalGUID = Host.GUID, + EnableUrlLanguage = Host.EnableUrlLanguage, + }; } + var portalSettings = new PortalSettings(portalId); - return new LinkClickPortalSettings - { - PortalGUID = portalSettings.GUID.ToString(), - EnableUrlLanguage = portalSettings.EnableUrlLanguage - }; + return new LinkClickPortalSettings + { + PortalGUID = portalSettings.GUID.ToString(), + EnableUrlLanguage = portalSettings.EnableUrlLanguage, + }; } private int GetPortalIdFromLinkClick(NameValueCollection queryParams) @@ -52,30 +71,13 @@ private int GetPortalIdFromLinkClick(NameValueCollection queryParams) return PortalSettings.Current.PortalId; } - public string GetFileLinkClick(IFileInfo file) - { - Requires.NotNull("file", file); - var portalId = file.PortalId; - var linkClickPortalSettigns = GetPortalSettingsForLinkClick(portalId); - - return TestableGlobals.Instance.LinkClick(String.Format("fileid={0}", file.FileId), Null.NullInteger, Null.NullInteger, true, false, portalId, linkClickPortalSettigns.EnableUrlLanguage, linkClickPortalSettigns.PortalGUID); - } - - public int GetFileIdFromLinkClick(NameValueCollection queryParams) - { - var linkClickPortalSettings = GetPortalSettingsForLinkClick(GetPortalIdFromLinkClick(queryParams)); - var strFileId = UrlUtils.DecryptParameter(queryParams["fileticket"], linkClickPortalSettings.PortalGUID); - int fileId; - return int.TryParse(strFileId, out fileId) ? fileId : -1; - } - protected override Func GetFactory() { return () => new FileLinkClickController(); } } - class LinkClickPortalSettings + internal class LinkClickPortalSettings { public string PortalGUID; public bool EnableUrlLanguage; diff --git a/DNN Platform/Library/Services/FileSystem/FileManager.cs b/DNN Platform/Library/Services/FileSystem/FileManager.cs index 7187797055b..8c0f807918e 100644 --- a/DNN Platform/Library/Services/FileSystem/FileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FileManager.cs @@ -1,74 +1,178 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text.RegularExpressions; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem.EventArgs; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Log.EventLog; -using ICSharpCode.SharpZipLib.Zip; -using System.Drawing.Imaging; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections.Generic; + using System.Drawing; + using System.Drawing.Imaging; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem.EventArgs; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Log.EventLog; + using ICSharpCode.SharpZipLib.Zip; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// /// Exposes methods to manage files. /// public class FileManager : ComponentBase, IFileManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileManager)); - - #region Properties - + private const int BufferSize = 4096; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileManager)); + public virtual IDictionary ContentTypes { get { return FileContentTypeManager.Instance.ContentTypes; } - } - - #endregion - - #region Constants - - private const int BufferSize = 4096; - - #endregion + } - #region Private Methods + private FileExtensionWhitelist WhiteList + { + get + { + var user = UserController.Instance.GetCurrentUserInfo(); + if (user != null) + { + if (user.IsSuperUser) + { + return Host.AllowedExtensionWhitelist; + } + + if (!user.IsAdmin) + { + var settings = PortalSettings.Current; + if (settings != null) + { + return settings.AllowedExtensionsWhitelist; + } + } + } + + return Host.AllowedExtensionWhitelist; + } + } + + /// + /// Adds a file to the specified folder. + /// + /// The folder where to add the file. + /// The name of the file. + /// The content of the file. + /// A IFileInfo as specified by the parameters. + public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent) + { + return this.AddFile(folder, fileName, fileContent, true, false, false, this.GetContentType(Path.GetExtension(fileName)), this.GetCurrentUserID()); + } + /// + /// Adds a file to the specified folder. + /// + /// The folder where to add the file. + /// The name of the file. + /// The content of the file. + /// Indicates if the file has to be over-written if it exits. + /// A IFileInfo as specified by the parameters. + public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite) + { + return this.AddFile(folder, fileName, fileContent, overwrite, false, false, this.GetContentType(Path.GetExtension(fileName)), this.GetCurrentUserID()); + } + + private static ImageFormat GetImageFormat(Image img) + { + if (img.RawFormat.Equals(ImageFormat.Jpeg)) + { + return ImageFormat.Jpeg; + } + + if (img.RawFormat.Equals(ImageFormat.Bmp)) + { + return ImageFormat.Bmp; + } + + if (img.RawFormat.Equals(ImageFormat.Png)) + { + return ImageFormat.Png; + } + + if (img.RawFormat.Equals(ImageFormat.Emf)) + { + return ImageFormat.Emf; + } + + if (img.RawFormat.Equals(ImageFormat.Exif)) + { + return ImageFormat.Exif; + } + + if (img.RawFormat.Equals(ImageFormat.Gif)) + { + return ImageFormat.Gif; + } + + if (img.RawFormat.Equals(ImageFormat.Icon)) + { + return ImageFormat.Icon; + } + + if (img.RawFormat.Equals(ImageFormat.MemoryBmp)) + { + return ImageFormat.Jpeg; + } + + if (img.RawFormat.Equals(ImageFormat.Tiff)) + { + return ImageFormat.Tiff; + } + else + { + return ImageFormat.Wmf; + } + } + + private static Stream ToStream(Image image, ImageFormat formaw) + { + var stream = new MemoryStream(); + image.Save(stream, formaw); + stream.Position = 0; + return stream; + } + private void AddFileToFolderProvider(Stream fileContent, string fileName, IFolderInfo destinationFolder, FolderProvider provider) { try { if (!fileContent.CanSeek) { - using (var seekableStream = GetSeekableStream(fileContent)) + using (var seekableStream = this.GetSeekableStream(fileContent)) { provider.AddFile(destinationFolder, fileName, seekableStream); } @@ -81,7 +185,7 @@ private void AddFileToFolderProvider(Stream fileContent, string fileName, IFolde catch (Exception ex) { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); } } @@ -95,18 +199,17 @@ private void DeleteFileFromFolderProvider(IFileInfo file, FolderProvider provide catch (Exception ex) { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); } - } - - #region On File Events + } + private void OnFileDeleted(IFileInfo fileInfo, int userId) { EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs { FileInfo = fileInfo, UserId = userId, - IsCascadeDeleting = false + IsCascadeDeleting = false, }); } @@ -116,7 +219,7 @@ private void OnFileRenamed(IFileInfo fileInfo, string oldFileName, int userId) { FileInfo = fileInfo, UserId = userId, - OldFileName = oldFileName + OldFileName = oldFileName, }); } @@ -126,7 +229,7 @@ private void OnFileMoved(IFileInfo fileInfo, string oldFilePath, int userId) { FileInfo = fileInfo, UserId = userId, - OldFilePath = oldFilePath + OldFilePath = oldFilePath, }); } @@ -135,7 +238,7 @@ private void OnFileOverwritten(IFileInfo fileInfo, int userId) EventManager.Instance.OnFileOverwritten(new FileChangedEventArgs { FileInfo = fileInfo, - UserId = userId + UserId = userId, }); } @@ -144,7 +247,7 @@ private void OnFileMetadataChanged(IFileInfo fileInfo, int userId) EventManager.Instance.OnFileMetadataChanged(new FileChangedEventArgs { FileInfo = fileInfo, - UserId = userId + UserId = userId, }); } @@ -154,11 +257,10 @@ private void OnFileAdded(IFileInfo fileInfo, IFolderInfo folderInfo, int userId) { FileInfo = fileInfo, UserId = userId, - FolderInfo = folderInfo + FolderInfo = folderInfo, }); - } - #endregion - + } + /// /// Rotate/Flip the image as per the metadata and reset the metadata. /// @@ -167,16 +269,25 @@ private void RotateFlipImage(ref Stream content) { try { - using (var image = GetImageFromStream(content)) + using (var image = this.GetImageFromStream(content)) { - if (!image.PropertyIdList.Any(x => x == 274)) return; - - var orientation = image.GetPropertyItem(274); //Find rotation/flip meta property - if (orientation == null) return; - + if (!image.PropertyIdList.Any(x => x == 274)) + { + return; + } + + var orientation = image.GetPropertyItem(274); // Find rotation/flip meta property + if (orientation == null) + { + return; + } + var flip = OrientationToFlipType(orientation.Value[0].ToString()); - if (flip == RotateFlipType.RotateNoneFlipNone) return;//No rotation or flip required - + if (flip == RotateFlipType.RotateNoneFlipNone) + { + return; // No rotation or flip required + } + image.RotateFlip(flip); var newOrientation = new byte[2]; newOrientation[0] = 1; // little Endian @@ -191,36 +302,6 @@ private void RotateFlipImage(ref Stream content) Logger.Error(ex); } } - private static ImageFormat GetImageFormat(Image img) - { - if (img.RawFormat.Equals(ImageFormat.Jpeg)) - return ImageFormat.Jpeg; - if (img.RawFormat.Equals(ImageFormat.Bmp)) - return ImageFormat.Bmp; - if (img.RawFormat.Equals(ImageFormat.Png)) - return ImageFormat.Png; - if (img.RawFormat.Equals(ImageFormat.Emf)) - return ImageFormat.Emf; - if (img.RawFormat.Equals(ImageFormat.Exif)) - return ImageFormat.Exif; - if (img.RawFormat.Equals(ImageFormat.Gif)) - return ImageFormat.Gif; - if (img.RawFormat.Equals(ImageFormat.Icon)) - return ImageFormat.Icon; - if (img.RawFormat.Equals(ImageFormat.MemoryBmp)) - return ImageFormat.Jpeg; - if (img.RawFormat.Equals(ImageFormat.Tiff)) - return ImageFormat.Tiff; - else - return ImageFormat.Wmf; - } - private static Stream ToStream(Image image, ImageFormat formaw) - { - var stream = new MemoryStream(); - image.Save(stream, formaw); - stream.Position = 0; - return stream; - } // Match the orientation code to the correct rotation: private static RotateFlipType OrientationToFlipType(string orientation) @@ -248,60 +329,6 @@ private static RotateFlipType OrientationToFlipType(string orientation) } } - private FileExtensionWhitelist WhiteList - { - get - { - var user = UserController.Instance.GetCurrentUserInfo(); - if (user != null) - { - if (user.IsSuperUser) - { - return Host.AllowedExtensionWhitelist; - } - if (!user.IsAdmin) - { - var settings = PortalSettings.Current; - if (settings != null) - { - return settings.AllowedExtensionsWhitelist; - } - } - } - return Host.AllowedExtensionWhitelist; - } - } - - #endregion - - #region Public Methods - - /// - /// Adds a file to the specified folder. - /// - /// The folder where to add the file. - /// The name of the file. - /// The content of the file. - /// A IFileInfo as specified by the parameters. - public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent) - { - - return AddFile(folder, fileName, fileContent, true, false, false, GetContentType(Path.GetExtension(fileName)), GetCurrentUserID()); - } - - /// - /// Adds a file to the specified folder. - /// - /// The folder where to add the file. - /// The name of the file. - /// The content of the file. - /// Indicates if the file has to be over-written if it exits. - /// A IFileInfo as specified by the parameters. - public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite) - { - return AddFile(folder, fileName, fileContent, overwrite, false, false, GetContentType(Path.GetExtension(fileName)), GetCurrentUserID()); - } - /// /// Adds a file to the specified folder. /// @@ -319,7 +346,7 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil /// A IFileInfo as specified by the parameters. public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite, bool checkPermissions, string contentType) { - return AddFile(folder, fileName, fileContent, overwrite, checkPermissions, false, contentType, GetCurrentUserID()); + return this.AddFile(folder, fileName, fileContent, overwrite, checkPermissions, false, contentType, this.GetCurrentUserID()); } /// @@ -331,7 +358,7 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil /// Indicates if the file has to be over-written if it exists. /// Indicates if permissions have to be met. /// The content type of the file. - /// ID of the user that creates the file + /// ID of the user that creates the file. /// Thrown when folder, fileName or fileContent are null. /// Thrown when the underlying system throw an exception. /// Thrown when the extension of the specified file is not allowed. @@ -340,7 +367,7 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil /// A IFileInfo as specified by the parameters. public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite, bool checkPermissions, string contentType, int createdByUserID) { - return AddFile(folder, fileName, fileContent, overwrite, checkPermissions, false, contentType, createdByUserID); + return this.AddFile(folder, fileName, fileContent, overwrite, checkPermissions, false, contentType, createdByUserID); } /// @@ -351,9 +378,9 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil /// The content of the file. /// Indicates if the file has to be over-written if it exists. /// Indicates if permissions have to be met. - /// Indicates whether the whitelist should be ignored + /// Indicates whether the whitelist should be ignored. /// The content type of the file. - /// ID of the user that creates the file + /// ID of the user that creates the file. /// Thrown when folder, fileName or fileContent are null. /// Thrown when the underlying system throw an exception. /// Thrown when the extension of the specified file is not allowed. @@ -365,10 +392,10 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("fileName", fileName); - CheckFileAddingRestrictions(folder, fileName, checkPermissions, ignoreWhiteList); + this.CheckFileAddingRestrictions(folder, fileName, checkPermissions, ignoreWhiteList); - //DNN-2949 If IgnoreWhiteList is set to true , then file should be copied and info logged into Event Viewer - if (!IsAllowedExtension(fileName) && ignoreWhiteList) + // DNN-2949 If IgnoreWhiteList is set to true , then file should be copied and info logged into Event Viewer + if (!this.IsAllowedExtension(fileName) && ignoreWhiteList) { var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.LogProperties.Add(new LogDetailInfo("Following file was imported/uploaded, but is not an authorized filetype: ", fileName)); @@ -378,16 +405,16 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); - bool fileExists = FileExists(folder, fileName, true); + bool fileExists = this.FileExists(folder, fileName, true); bool needToWriteFile = fileContent != null && (overwrite || !folderProvider.FileExists(folder, fileName)); bool usingSeekableStream = false; - if (fileContent != null && !needToWriteFile && FileExists(folder, fileName)) + if (fileContent != null && !needToWriteFile && this.FileExists(folder, fileName)) { - return GetFile(folder, fileName); + return this.GetFile(folder, fileName); } - var oldFile = fileExists ? GetFile(folder, fileName, true) : null; + var oldFile = fileExists ? this.GetFile(folder, fileName, true) : null; var now = DateTime.Now; var extension = Path.GetExtension(fileName); @@ -395,7 +422,7 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil { PortalId = folder.PortalID, FileName = fileName, - Extension = (!String.IsNullOrEmpty(extension)) ? extension.Replace(".", "") : String.Empty, + Extension = (!string.IsNullOrEmpty(extension)) ? extension.Replace(".", string.Empty) : string.Empty, Width = Null.NullInteger, Height = Null.NullInteger, ContentType = contentType, @@ -407,7 +434,7 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil EnablePublishPeriod = false, ContentItemID = oldFile != null ? oldFile.ContentItemID : Null.NullInteger, Title = oldFile != null ? oldFile.Title : Null.NullString, - SHA1Hash = oldFile != null ? oldFile.SHA1Hash : String.Empty + SHA1Hash = oldFile != null ? oldFile.SHA1Hash : string.Empty, }; try @@ -418,47 +445,50 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil { if (!fileContent.CanSeek) { - fileContent = GetSeekableStream(fileContent); + fileContent = this.GetSeekableStream(fileContent); usingSeekableStream = true; } - CheckFileWritingRestrictions(folder, fileName, fileContent, oldFile, createdByUserID); + this.CheckFileWritingRestrictions(folder, fileName, fileContent, oldFile, createdByUserID); // Retrieve Metadata - SetInitialFileMetadata(ref fileContent, file, folderProvider); + this.SetInitialFileMetadata(ref fileContent, file, folderProvider); // Workflow folderWorkflow = WorkflowManager.Instance.GetWorkflow(folder.WorkflowID); if (folderWorkflow != null) { - SetContentItem(file); + this.SetContentItem(file); file.FileId = oldFile != null ? oldFile.FileId : Null.NullInteger; if (folderWorkflow.WorkflowID == SystemWorkflowManager.Instance.GetDirectPublishWorkflow(folderWorkflow.PortalID).WorkflowID) { if (file.FileId == Null.NullInteger) { - AddFile(file, createdByUserID); + this.AddFile(file, createdByUserID); fileExists = true; } else { - //File Events for updating will be not fired. Only events for adding nust be fired - UpdateFile(file, true, false); + // File Events for updating will be not fired. Only events for adding nust be fired + this.UpdateFile(file, true, false); } - contentFileName = ProcessVersioning(folder, oldFile, file, createdByUserID); + + contentFileName = this.ProcessVersioning(folder, oldFile, file, createdByUserID); } else { - contentFileName = UpdateWhileApproving(folder, createdByUserID, file, oldFile, fileContent); - //This case will be to overwrite an existing file or initial file workflow - ManageFileAdding(createdByUserID, folderWorkflow, fileExists, file); + contentFileName = this.UpdateWhileApproving(folder, createdByUserID, file, oldFile, fileContent); + + // This case will be to overwrite an existing file or initial file workflow + this.ManageFileAdding(createdByUserID, folderWorkflow, fileExists, file); } } + // Versioning else { - contentFileName = ProcessVersioning(folder, oldFile, file, createdByUserID); + contentFileName = this.ProcessVersioning(folder, oldFile, file, createdByUserID); } } else @@ -471,13 +501,13 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil try { - //add file into database first if folder provider is default providers - //add file into database after file saved into folder provider for remote folder providers to avoid multiple thread issue. + // add file into database first if folder provider is default providers + // add file into database after file saved into folder provider for remote folder providers to avoid multiple thread issue. if (isDatabaseProvider) { if (folderWorkflow == null || !fileExists) { - ManageFileAdding(createdByUserID, folderWorkflow, fileExists, file); + this.ManageFileAdding(createdByUserID, folderWorkflow, fileExists, file); } if (needToWriteFile) @@ -494,7 +524,7 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil if (folderWorkflow == null || !fileExists) { - ManageFileAdding(createdByUserID, folderWorkflow, fileExists, file); + this.ManageFileAdding(createdByUserID, folderWorkflow, fileExists, file); } } @@ -526,16 +556,17 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil } throw new FolderProviderException( - Localization.Localization.GetExceptionMessage("AddFileUnderlyingSystemError", - "The underlying system threw an exception. The file has not been added."), - ex); + Localization.GetExceptionMessage( + "AddFileUnderlyingSystemError", + "The underlying system threw an exception. The file has not been added."), + ex); } DataCache.RemoveCache("GetFileById" + file.FileId); - ClearFolderCache(folder.PortalID); - var addedFile = GetFile(file.FileId, true); //The file could be pending to be approved, but it should be returned + this.ClearFolderCache(folder.PortalID); + var addedFile = this.GetFile(file.FileId, true); // The file could be pending to be approved, but it should be returned - NotifyFileAddingEvents(folder, createdByUserID, fileExists, folderWorkflow, addedFile); + this.NotifyFileAddingEvents(folder, createdByUserID, fileExists, folderWorkflow, addedFile); return addedFile; } @@ -548,28 +579,136 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil } } + /// + /// Copies the specified file into the specified folder. + /// + /// The file to copy. + /// The folder where to copy the file to. + /// Thrown when file or destinationFolder are null. + /// A IFileInfo with the information of the copied file. + public virtual IFileInfo CopyFile(IFileInfo file, IFolderInfo destinationFolder) + { + Requires.NotNull("file", file); + Requires.NotNull("destinationFolder", destinationFolder); + + if (file.FolderMappingID == destinationFolder.FolderMappingID) + { + if (!FolderPermissionController.Instance.CanAddFolder(destinationFolder)) + { + throw new PermissionsNotMetException(Localization.GetExceptionMessage("CopyFilePermissionsNotMet", "Permissions are not met. The file has not been copied.")); + } + + if (!PortalController.Instance.HasSpaceAvailable(destinationFolder.PortalID, file.Size)) + { + throw new NoSpaceAvailableException(Localization.GetExceptionMessage("CopyFileNoSpaceAvailable", "The portal has no space available to store the specified file. The file has not been copied.")); + } + + var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); + try + { + // check for existing file + var existingFile = this.GetFile(destinationFolder, file.FileName, true); + if (existingFile != null) + { + this.DeleteFile(existingFile); + } + + var folder = FolderManager.Instance.GetFolder(file.FolderId); + FolderProvider.Instance(folderMapping.FolderProviderType).CopyFile(folder.MappedPath, file.FileName, destinationFolder.MappedPath, folderMapping); + } + catch (Exception ex) + { + Logger.Error(ex); + throw new FolderProviderException(Localization.GetExceptionMessage("CopyFileUnderlyingSystemError", "The underlying system throw an exception. The file has not been copied."), ex); + } + + // copy Content Item + var contentItemID = this.CopyContentItem(file.ContentItemID); + + var fileId = DataProvider.Instance().AddFile( + file.PortalId, + Guid.NewGuid(), + Guid.NewGuid(), + file.FileName, + file.Extension, + file.Size, + file.Width, + file.Height, + file.ContentType, + destinationFolder.FolderPath, + destinationFolder.FolderID, + this.GetCurrentUserID(), + file.SHA1Hash, + DateTime.Now, + file.Title, + file.Description, + file.StartDate, + file.EndDate, + file.EnablePublishPeriod, + contentItemID); + + var copiedFile = this.GetFile(fileId, true); + + // Notify added file event + this.OnFileAdded(copiedFile, destinationFolder, this.GetCurrentUserID()); + + return copiedFile; + } + + using (var fileContent = this.GetFileContent(file)) + { + // check for existing file + var existingFile = this.GetFile(destinationFolder, file.FileName, true); + if (existingFile != null) + { + this.DeleteFile(existingFile); + } + + return this.AddFile(destinationFolder, file.FileName, fileContent, true, true, file.ContentType); + } + } + + /// + /// Deletes the specified file. + /// + /// The file to delete. + /// Thrown when file is null. + /// Thrown when the underlying system throw an exception. + public virtual void DeleteFile(IFileInfo file) + { + Requires.NotNull("file", file); + FileDeletionController.Instance.DeleteFile(file); + this.ClearFolderCache(file.PortalId); + + // Notify File Delete Event + this.OnFileDeleted(file, this.GetCurrentUserID()); + } + private void CheckFileAddingRestrictions(IFolderInfo folder, string fileName, bool checkPermissions, bool ignoreWhiteList) { if (checkPermissions && !FolderPermissionController.Instance.CanAddFolder(folder)) { - throw new PermissionsNotMetException(Localization.Localization.GetExceptionMessage("AddFilePermissionsNotMet", + throw new PermissionsNotMetException(Localization.GetExceptionMessage( + "AddFilePermissionsNotMet", "Permissions are not met. The file has not been added.")); } - if (!IsAllowedExtension(fileName) && !(UserController.Instance.GetCurrentUserInfo().IsSuperUser && ignoreWhiteList)) + if (!this.IsAllowedExtension(fileName) && !(UserController.Instance.GetCurrentUserInfo().IsSuperUser && ignoreWhiteList)) { throw new InvalidFileExtensionException( string.Format( - Localization.Localization.GetExceptionMessage("AddFileExtensionNotAllowed", + Localization.GetExceptionMessage( + "AddFileExtensionNotAllowed", "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(fileName))); } - if (!IsValidFilename(fileName)) + if (!this.IsValidFilename(fileName)) { throw new InvalidFilenameException( string.Format( - Localization.Localization.GetExceptionMessage("AddFilenameNotAllowed", + Localization.GetExceptionMessage( + "AddFilenameNotAllowed", "The file name '{0}' is not allowed. The file has not been added."), fileName)); } } @@ -580,12 +719,12 @@ private void NotifyFileAddingEvents(IFolderInfo folder, int createdByUserID, boo if (fileExists && (folderWorkflow == null || folderWorkflow.WorkflowID == SystemWorkflowManager.Instance.GetDirectPublishWorkflow(folderWorkflow.PortalID).WorkflowID)) { - OnFileOverwritten(file, createdByUserID); + this.OnFileOverwritten(file, createdByUserID); } if (!fileExists) { - OnFileAdded(file, folder, createdByUserID); + this.OnFileAdded(file, folder, createdByUserID); } } @@ -594,7 +733,7 @@ private void SetContentItem(IFileInfo file) // Create Content Item if does not exists if (file.ContentItemID == Null.NullInteger) { - file.ContentItemID = CreateFileContentItem().ContentItemId; + file.ContentItemID = this.CreateFileContentItem().ContentItemId; } } @@ -608,10 +747,10 @@ private void SetInitialFileMetadata(ref Stream fileContent, FileInfo file, Folde file.Width = 0; file.Height = 0; - if (IsImageFile(file)) + if (this.IsImageFile(file)) { - RotateFlipImage(ref fileContent); - SetImageProperties(file, fileContent); + this.RotateFlipImage(ref fileContent); + this.SetImageProperties(file, fileContent); } } @@ -619,7 +758,7 @@ private void SetImageProperties(IFileInfo file, Stream fileContent) { try { - using (var image = GetImageFromStream(fileContent)) + using (var image = this.GetImageFromStream(fileContent)) { file.Width = image.Width; file.Height = image.Height; @@ -640,22 +779,24 @@ private void CheckFileWritingRestrictions(IFolderInfo folder, string fileName, S if (!PortalController.Instance.HasSpaceAvailable(folder.PortalID, fileContent.Length)) { throw new NoSpaceAvailableException( - Localization.Localization.GetExceptionMessage("AddFileNoSpaceAvailable", - "The portal has no space available to store the specified file. The file has not been added.")); + Localization.GetExceptionMessage( + "AddFileNoSpaceAvailable", + "The portal has no space available to store the specified file. The file has not been added.")); } - //Publish Period + // Publish Period if (oldFile != null && FileLockingController.Instance.IsFileOutOfPublishPeriod(oldFile, folder.PortalID, createdByUserId)) { throw new FileLockedException( - Localization.Localization.GetExceptionMessage("FileLockedOutOfPublishPeriodError", - "File locked. The file cannot be updated because it is out of Publish Period")); + Localization.GetExceptionMessage( + "FileLockedOutOfPublishPeriodError", + "File locked. The file cannot be updated because it is out of Publish Period")); } if (!FileSecurityController.Instance.Validate(fileName, fileContent)) { var defaultMessage = "The content of '{0}' is not valid. The file has not been added."; - var errorMessage = Localization.Localization.GetExceptionMessage("AddFileInvalidContent", defaultMessage); + var errorMessage = Localization.GetExceptionMessage("AddFileInvalidContent", defaultMessage); throw new InvalidFileContentException(string.Format(errorMessage, fileName)); } } @@ -664,18 +805,19 @@ private void ManageFileAdding(int createdByUserID, Workflow folderWorkflow, bool { if (folderWorkflow == null || !fileExists) { - AddFile(file, createdByUserID); + this.AddFile(file, createdByUserID); } else { - //File Events for updating will not be fired. Only events for adding nust be fired - UpdateFile(file, true, false); + // File Events for updating will not be fired. Only events for adding nust be fired + this.UpdateFile(file, true, false); } - if (folderWorkflow != null && StartWorkflow(createdByUserID, folderWorkflow, fileExists, file.ContentItemID)) + + if (folderWorkflow != null && this.StartWorkflow(createdByUserID, folderWorkflow, fileExists, file.ContentItemID)) { - if (!fileExists) //if file exists it could have been published. So We don't have to update the field + if (!fileExists) // if file exists it could have been published. So We don't have to update the field { - //Maybe here we can set HasBeenPublished as 0 + // Maybe here we can set HasBeenPublished as 0 DataProvider.Instance().SetFileHasBeenPublished(file.FileId, false); } } @@ -683,26 +825,27 @@ private void ManageFileAdding(int createdByUserID, Workflow folderWorkflow, bool private void AddFile(IFileInfo file, int createdByUserID) { - file.FileId = DataProvider.Instance().AddFile(file.PortalId, - file.UniqueId, - file.VersionGuid, - file.FileName, - file.Extension, - file.Size, - file.Width, - file.Height, - file.ContentType, - file.Folder, - file.FolderId, - createdByUserID, - file.SHA1Hash, - file.LastModificationTime, - file.Title, - file.Description, - file.StartDate, - file.EndDate, - file.EnablePublishPeriod, - file.ContentItemID); + file.FileId = DataProvider.Instance().AddFile( + file.PortalId, + file.UniqueId, + file.VersionGuid, + file.FileName, + file.Extension, + file.Size, + file.Width, + file.Height, + file.ContentType, + file.Folder, + file.FolderId, + createdByUserID, + file.SHA1Hash, + file.LastModificationTime, + file.Title, + file.Description, + file.StartDate, + file.EndDate, + file.EnablePublishPeriod, + file.ContentItemID); } private string ProcessVersioning(IFolderInfo folder, IFileInfo oldFile, IFileInfo file, int createdByUserID) @@ -711,115 +854,10 @@ private string ProcessVersioning(IFolderInfo folder, IFileInfo oldFile, IFileInf { return FileVersionController.Instance.AddFileVersion(oldFile, createdByUserID); } + return file.FileName; } - /// - /// Copies the specified file into the specified folder. - /// - /// The file to copy. - /// The folder where to copy the file to. - /// Thrown when file or destinationFolder are null. - /// A IFileInfo with the information of the copied file. - public virtual IFileInfo CopyFile(IFileInfo file, IFolderInfo destinationFolder) - { - - Requires.NotNull("file", file); - Requires.NotNull("destinationFolder", destinationFolder); - - if (file.FolderMappingID == destinationFolder.FolderMappingID) - { - if (!FolderPermissionController.Instance.CanAddFolder(destinationFolder)) - { - throw new PermissionsNotMetException(Localization.Localization.GetExceptionMessage("CopyFilePermissionsNotMet", "Permissions are not met. The file has not been copied.")); - } - - if (!PortalController.Instance.HasSpaceAvailable(destinationFolder.PortalID, file.Size)) - { - throw new NoSpaceAvailableException(Localization.Localization.GetExceptionMessage("CopyFileNoSpaceAvailable", "The portal has no space available to store the specified file. The file has not been copied.")); - } - - var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - try - { - - //check for existing file - var existingFile = GetFile(destinationFolder, file.FileName, true); - if (existingFile != null) - { - DeleteFile(existingFile); - } - - var folder = FolderManager.Instance.GetFolder(file.FolderId); - FolderProvider.Instance(folderMapping.FolderProviderType).CopyFile(folder.MappedPath, file.FileName, destinationFolder.MappedPath, folderMapping); - } - catch (Exception ex) - { - Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("CopyFileUnderlyingSystemError", "The underlying system throw an exception. The file has not been copied."), ex); - } - - // copy Content Item - var contentItemID = CopyContentItem(file.ContentItemID); - - var fileId = DataProvider.Instance().AddFile( - file.PortalId, - Guid.NewGuid(), - Guid.NewGuid(), - file.FileName, - file.Extension, - file.Size, - file.Width, - file.Height, - file.ContentType, - destinationFolder.FolderPath, - destinationFolder.FolderID, - GetCurrentUserID(), - file.SHA1Hash, - DateTime.Now, - file.Title, - file.Description, - file.StartDate, - file.EndDate, - file.EnablePublishPeriod, - contentItemID); - - var copiedFile = GetFile(fileId, true); - - // Notify added file event - OnFileAdded(copiedFile, destinationFolder, GetCurrentUserID()); - - return copiedFile; - } - - using (var fileContent = GetFileContent(file)) - { - //check for existing file - var existingFile = GetFile(destinationFolder, file.FileName, true); - if (existingFile != null) - { - DeleteFile(existingFile); - } - - return AddFile(destinationFolder, file.FileName, fileContent, true, true, file.ContentType); - } - } - - /// - /// Deletes the specified file. - /// - /// The file to delete. - /// Thrown when file is null. - /// Thrown when the underlying system throw an exception. - public virtual void DeleteFile(IFileInfo file) - { - Requires.NotNull("file", file); - FileDeletionController.Instance.DeleteFile(file); - ClearFolderCache(file.PortalId); - // Notify File Delete Event - OnFileDeleted(file, GetCurrentUserID()); - } - /// /// Deletes the specified files. /// @@ -827,12 +865,11 @@ public virtual void DeleteFile(IFileInfo file) /// Thrown when files is null. public virtual void DeleteFiles(IEnumerable files) { - Requires.NotNull("files", files); foreach (var file in files) { - DeleteFile(file); + this.DeleteFile(file); } } @@ -847,7 +884,7 @@ public virtual void DeleteFiles(IEnumerable files) /// Thrown when the underlying system throw an exception. public virtual bool FileExists(IFolderInfo folder, string fileName) { - return FileExists(folder, fileName, false); + return this.FileExists(folder, fileName, false); } /// @@ -855,18 +892,17 @@ public virtual bool FileExists(IFolderInfo folder, string fileName) /// /// The folder where to check the existence of the file. /// The file name to check the existence of. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// A bool value indicating whether the file exists or not in the specified folder. /// Thrown when folder is null. /// Thrown when fileName is null or empty. /// Thrown when the underlying system throw an exception. public virtual bool FileExists(IFolderInfo folder, string fileName, bool retrieveUnpublishedFiles) { - Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("fileName", fileName); - var file = GetFile(folder, fileName, retrieveUnpublishedFiles); + var file = this.GetFile(folder, fileName, retrieveUnpublishedFiles); var existsFile = file != null; var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); @@ -878,7 +914,7 @@ public virtual bool FileExists(IFolderInfo folder, string fileName, bool retriev { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); } return existsFile; @@ -891,7 +927,6 @@ public virtual bool FileExists(IFolderInfo folder, string fileName, bool retriev /// The Content Type for the specified extension. public virtual string GetContentType(string extension) { - return FileContentTypeManager.Instance.GetContentType(extension); } @@ -902,14 +937,14 @@ public virtual string GetContentType(string extension) /// The IFileInfo object with the metadata of the specified file. public virtual IFileInfo GetFile(int fileID) { - return GetFile(fileID, false); + return this.GetFile(fileID, false); } /// /// Gets the file metadata for the specified file. /// /// The file identifier. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// The IFileInfo object with the metadata of the specified file. public virtual IFileInfo GetFile(int fileID, bool retrieveUnpublishedFiles) { @@ -925,10 +960,11 @@ public virtual IFileInfo GetFile(int fileID, bool retrieveUnpublishedFiles) file = CBO.Instance.FillObject(DataProvider.Instance().GetFileById(fileID, retrieveUnpublishedFiles)); if (file != null) { - var intCacheTimeout = 20 * Convert.ToInt32(GetPerformanceSetting()); + var intCacheTimeout = 20 * Convert.ToInt32(this.GetPerformanceSetting()); DataCache.SetCache(strCacheKey, file, TimeSpan.FromMinutes(intCacheTimeout)); } } + return (IFileInfo)file; } @@ -940,7 +976,7 @@ public virtual IFileInfo GetFile(int fileID, bool retrieveUnpublishedFiles) /// The IFileInfo object with the metadata of the specified file. public virtual IFileInfo GetFile(IFolderInfo folder, string fileName) { - return GetFile(folder, fileName, false); + return this.GetFile(folder, fileName, false); } /// @@ -948,11 +984,10 @@ public virtual IFileInfo GetFile(IFolderInfo folder, string fileName) /// /// The folder where the file is stored. /// The name of the file. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// The IFileInfo object with the metadata of the specified file. public virtual IFileInfo GetFile(IFolderInfo folder, string fileName, bool retrieveUnpublishedFiles) { - Requires.NotNullOrEmpty("fileName", fileName); Requires.NotNull("folder", folder); @@ -962,29 +997,28 @@ public virtual IFileInfo GetFile(IFolderInfo folder, string fileName, bool retri /// /// Gets the file metadata for the specified file. /// - /// The portal ID or Null.NullInteger for the Host + /// The portal ID or Null.NullInteger for the Host. /// Relative path to the file. /// Host and portal settings commonly return a relative path to a file. This method uses that relative path to fetch file metadata. /// The IFileInfo object with the metadata of the specified file. public virtual IFileInfo GetFile(int portalId, string relativePath) { - return GetFile(portalId, relativePath, false); + return this.GetFile(portalId, relativePath, false); } /// /// Gets the file metadata for the specified file. /// - /// The portal ID or Null.NullInteger for the Host + /// The portal ID or Null.NullInteger for the Host. /// Relative path to the file. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// Host and portal settings commonly return a relative path to a file. This method uses that relative path to fetch file metadata. /// The IFileInfo object with the metadata of the specified file. public virtual IFileInfo GetFile(int portalId, string relativePath, bool retrieveUnpublishedFiles) { - Requires.NotNullOrEmpty("relativePath", relativePath); - var folderPath = ""; + var folderPath = string.Empty; var seperatorIndex = relativePath.LastIndexOf('/'); if (seperatorIndex > 0) @@ -999,7 +1033,7 @@ public virtual IFileInfo GetFile(int portalId, string relativePath, bool retriev } var fileName = relativePath.Substring(folderPath.Length); - return GetFile(folderInfo, fileName, retrieveUnpublishedFiles); + return this.GetFile(folderInfo, fileName, retrieveUnpublishedFiles); } /// @@ -1027,7 +1061,7 @@ public virtual Stream GetFileContent(IFileInfo file) { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception"), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception"), ex); } } @@ -1041,20 +1075,23 @@ public virtual Stream GetFileContent(IFileInfo file) /// A seekable Stream. public virtual Stream GetSeekableStream(Stream stream) { - Requires.NotNull("stream", stream); - if (stream.CanSeek) return stream; - - var folderPath = GetHostMapPath(); + if (stream.CanSeek) + { + return stream; + } + + var folderPath = this.GetHostMapPath(); string filePath; do { filePath = Path.Combine(folderPath, Path.GetRandomFileName()) + ".resx"; - } while (File.Exists(filePath)); + } + while (File.Exists(filePath)); - var fileStream = GetAutoDeleteFileStream(filePath); + var fileStream = this.GetAutoDeleteFileStream(filePath); var array = new byte[BufferSize]; @@ -1078,7 +1115,6 @@ public virtual Stream GetSeekableStream(Stream stream) /// Thrown when the underlying system throw an exception. public string GetUrl(IFileInfo file) { - Requires.NotNull("file", file); var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); @@ -1091,18 +1127,18 @@ public string GetUrl(IFileInfo file) { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); } } /// - /// Gets a flag that dertermines if the file is an Image + /// Gets a flag that dertermines if the file is an Image. /// /// The file to test. /// The flag as a boolean value. public virtual bool IsImageFile(IFileInfo file) { - return (Globals.glbImageFileTypes + ",").IndexOf(file.Extension.ToLowerInvariant().Replace(".", "") + ",") > -1; + return (Globals.glbImageFileTypes + ",").IndexOf(file.Extension.ToLowerInvariant().Replace(".", string.Empty) + ",") > -1; } /// @@ -1121,23 +1157,23 @@ public virtual IFileInfo MoveFile(IFileInfo file, IFolderInfo destinationFolder) Requires.NotNull("file", file); Requires.NotNull("destinationFolder", destinationFolder); - //check whether the file is already in the dest folder. + // check whether the file is already in the dest folder. if (file.FolderId == destinationFolder.FolderID) { return file; } - var lockReason = ""; + var lockReason = string.Empty; if (FileLockingController.Instance.IsFileLocked(file, out lockReason)) { - throw new FileLockedException(Localization.Localization.GetExceptionMessage(lockReason, "File locked. The file cannot be updated. Reason: " + lockReason)); + throw new FileLockedException(Localization.GetExceptionMessage(lockReason, "File locked. The file cannot be updated. Reason: " + lockReason)); } - //check for existing file - var existingFile = GetFile(destinationFolder, file.FileName, true); + // check for existing file + var existingFile = this.GetFile(destinationFolder, file.FileName, true); if (existingFile != null) { - DeleteFile(existingFile); + this.DeleteFile(existingFile); } var destinationFolderMapping = FolderMappingController.Instance.GetFolderMapping(destinationFolder.PortalID, destinationFolder.FolderMappingID); @@ -1148,13 +1184,13 @@ public virtual IFileInfo MoveFile(IFileInfo file, IFolderInfo destinationFolder) if (destinationFolderMapping.FolderMappingID == sourceFolderMapping.FolderMappingID && destinationFolderProvider.SupportsMoveFile) { - //Implement Move + // Implement Move destinationFolderProvider.MoveFile(file, destinationFolder); } else { - //Implement Copy/Delete - using (var fileContent = GetFileContent(file)) + // Implement Copy/Delete + using (var fileContent = this.GetFileContent(file)) { if (destinationFolderMapping.MappingName == "Database") { @@ -1162,15 +1198,16 @@ public virtual IFileInfo MoveFile(IFileInfo file, IFolderInfo destinationFolder) } else { - AddFileToFolderProvider(fileContent, file.FileName, destinationFolder, destinationFolderProvider); + this.AddFileToFolderProvider(fileContent, file.FileName, destinationFolder, destinationFolderProvider); } } - DeleteFileFromFolderProvider(file, sourceFolderProvider); + + this.DeleteFileFromFolderProvider(file, sourceFolderProvider); } if (file.FolderMappingID == destinationFolder.FolderMappingID) { - MoveVersions(file, destinationFolder, sourceFolderProvider, destinationFolderProvider); + this.MoveVersions(file, destinationFolder, sourceFolderProvider, destinationFolderProvider); } else { @@ -1181,10 +1218,10 @@ public virtual IFileInfo MoveFile(IFileInfo file, IFolderInfo destinationFolder) file.FolderId = destinationFolder.FolderID; file.Folder = destinationFolder.FolderPath; file.FolderMappingID = destinationFolder.FolderMappingID; - file = UpdateFile(file); + file = this.UpdateFile(file); // Notify File Moved event - OnFileMoved(file, oldFilePath, GetCurrentUserID()); + this.OnFileMoved(file, oldFilePath, this.GetCurrentUserID()); return file; } @@ -1192,34 +1229,36 @@ public virtual IFileInfo MoveFile(IFileInfo file, IFolderInfo destinationFolder) /// /// Renames the specified file. /// - /// The file to rename + /// The file to rename. /// The new filename to assign to the file. /// Thrown when file is null. /// Thrown when the folder already contains a file with the same name. /// An IFileInfo with the information of the renamed file. public virtual IFileInfo RenameFile(IFileInfo file, string newFileName) { - Requires.NotNull("file", file); Requires.NotNullOrEmpty("newFileName", newFileName); - if (file.FileName == newFileName) return file; - - if (!IsAllowedExtension(newFileName)) + if (file.FileName == newFileName) + { + return file; + } + + if (!this.IsAllowedExtension(newFileName)) { - throw new InvalidFileExtensionException(string.Format(Localization.Localization.GetExceptionMessage("AddFileExtensionNotAllowed", "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(newFileName))); + throw new InvalidFileExtensionException(string.Format(Localization.GetExceptionMessage("AddFileExtensionNotAllowed", "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(newFileName))); } - if (!IsValidFilename(newFileName)) + if (!this.IsValidFilename(newFileName)) { - throw new InvalidFilenameException(string.Format(Localization.Localization.GetExceptionMessage("AddFilenameNotAllowed", "The file name '{0}' is not allowed. The file has not been added."), newFileName)); + throw new InvalidFilenameException(string.Format(Localization.GetExceptionMessage("AddFilenameNotAllowed", "The file name '{0}' is not allowed. The file has not been added."), newFileName)); } var folder = FolderManager.Instance.GetFolder(file.FolderId); - if (FileExists(folder, newFileName)) + if (this.FileExists(folder, newFileName)) { - throw new FileAlreadyExistsException(Localization.Localization.GetExceptionMessage("RenameFileAlreadyExists", "This folder already contains a file with the same name. The file has not been renamed.")); + throw new FileAlreadyExistsException(Localization.GetExceptionMessage("RenameFileAlreadyExists", "This folder already contains a file with the same name. The file has not been renamed.")); } var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); @@ -1232,19 +1271,20 @@ public virtual IFileInfo RenameFile(IFileInfo file, string newFileName) { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("RenameFileUnderlyingSystemError", "The underlying system threw an exception. The file has not been renamed."), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("RenameFileUnderlyingSystemError", "The underlying system threw an exception. The file has not been renamed."), ex); } var oldfileName = file.FileName; file.FileName = newFileName; if (Path.HasExtension(newFileName)) { - file.Extension = Path.GetExtension(newFileName).Replace(".", ""); + file.Extension = Path.GetExtension(newFileName).Replace(".", string.Empty); } - var renamedFile = UpdateFile(file); + + var renamedFile = this.UpdateFile(file); // Notify File Renamed event - OnFileRenamed(renamedFile, oldfileName, GetCurrentUserID()); + this.OnFileRenamed(renamedFile, oldfileName, this.GetCurrentUserID()); return renamedFile; } @@ -1256,7 +1296,6 @@ public virtual IFileInfo RenameFile(IFileInfo file, string newFileName) /// The file attributes to add. public void SetAttributes(IFileInfo file, FileAttributes fileAttributes) { - Requires.NotNull("file", file); var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); @@ -1268,7 +1307,7 @@ public void SetAttributes(IFileInfo file, FileAttributes fileAttributes) catch (Exception ex) { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); } } @@ -1276,17 +1315,15 @@ public void SetAttributes(IFileInfo file, FileAttributes fileAttributes) /// Extracts the files and folders contained in the specified zip file to the folder where the file belongs. /// /// The file to unzip. - /// Total files count in the zip file. /// Thrown when file is not a zip compressed file. /// Thrown when file or destination folder are null. public virtual void UnzipFile(IFileInfo file) { - Requires.NotNull("file", file); var destinationFolder = FolderManager.Instance.GetFolder(file.FolderId); - UnzipFile(file, destinationFolder); + this.UnzipFile(file, destinationFolder); } /// @@ -1294,12 +1331,11 @@ public virtual void UnzipFile(IFileInfo file) /// /// The file to unzip. /// The folder to unzip to. - /// Total files count in the zip file. /// Thrown when file is not a zip compressed file. /// Thrown when file or destination folder are null. public virtual void UnzipFile(IFileInfo file, IFolderInfo destinationFolder) { - UnzipFile(file, destinationFolder, null); + this.UnzipFile(file, destinationFolder, null); } /// @@ -1311,19 +1347,17 @@ public virtual void UnzipFile(IFileInfo file, IFolderInfo destinationFolder) /// Total files count in the zip file. /// Thrown when file is not a zip compressed file. /// Thrown when file or destination folder are null. - public virtual int UnzipFile(IFileInfo file, IFolderInfo destinationFolder, IList invalidFiles) { - Requires.NotNull("file", file); Requires.NotNull("destinationFolder", destinationFolder); if (file.Extension != "zip") { - throw new ArgumentException(Localization.Localization.GetExceptionMessage("InvalidZipFile", "The file specified is not a zip compressed file.")); + throw new ArgumentException(Localization.GetExceptionMessage("InvalidZipFile", "The file specified is not a zip compressed file.")); } - return ExtractFiles(file, destinationFolder, invalidFiles); + return this.ExtractFiles(file, destinationFolder, invalidFiles); } /// @@ -1342,7 +1376,7 @@ public virtual IFileInfo UpdateFile(IFileInfo file) throw new InvalidMetadataValuesException(message); } - return UpdateFile(file, true); + return this.UpdateFile(file, true); } /// @@ -1358,13 +1392,13 @@ public virtual IFileInfo UpdateFile(IFileInfo file, Stream fileContent) if (fileContent != null) { - if (IsImageFile(file)) + if (this.IsImageFile(file)) { Image image = null; try { - image = GetImageFromStream(fileContent); + image = this.GetImageFromStream(fileContent); file.Width = image.Width; file.Height = image.Height; @@ -1401,7 +1435,7 @@ public virtual IFileInfo UpdateFile(IFileInfo file, Stream fileContent) Logger.Error(ex); } - return UpdateFile(file); + return this.UpdateFile(file); } /// @@ -1412,11 +1446,10 @@ public virtual IFileInfo UpdateFile(IFileInfo file, Stream fileContent) /// Thrown when file or stream are null. public virtual void WriteFile(IFileInfo file, Stream stream) { - Requires.NotNull("file", file); Requires.NotNull("stream", stream); - using (var srcStream = GetFileContent(file)) + using (var srcStream = this.GetFileContent(file)) { const int bufferSize = 4096; var buffer = new byte[bufferSize]; @@ -1438,34 +1471,31 @@ public virtual void WriteFile(IFileInfo file, Stream stream) /// Thrown when permissions are not met. public virtual void WriteFileToResponse(IFileInfo file, ContentDisposition contentDisposition) { - Requires.NotNull("file", file); var folder = FolderManager.Instance.GetFolder(file.FolderId); if (!FolderPermissionController.Instance.CanViewFolder(folder)) { - throw new PermissionsNotMetException(Localization.Localization.GetExceptionMessage("WriteFileToResponsePermissionsNotMet", "Permissions are not met. The file cannot be downloaded.")); + throw new PermissionsNotMetException(Localization.GetExceptionMessage("WriteFileToResponsePermissionsNotMet", "Permissions are not met. The file cannot be downloaded.")); } - if (IsFileAutoSyncEnabled()) + if (this.IsFileAutoSyncEnabled()) { - AutoSyncFile(file); + this.AutoSyncFile(file); } - WriteFileToHttpContext(file, contentDisposition); - } - - #endregion - - #region Internal Methods - - #region ContentType Methods + this.WriteFileToHttpContext(file, contentDisposition); + } + internal virtual int CopyContentItem(int contentItemId) { - if (contentItemId == Null.NullInteger) return Null.NullInteger; - - var newContentItem = CreateFileContentItem(); + if (contentItemId == Null.NullInteger) + { + return Null.NullInteger; + } + + var newContentItem = this.CreateFileContentItem(); // Clone terms var termController = new TermController(); @@ -1497,18 +1527,17 @@ internal virtual ContentItem CreateFileContentItem() objContent.ContentItemId = Util.GetContentController().AddContentItem(objContent); return objContent; - } - - #endregion - - #region File Versions - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void MoveVersions(IFileInfo file, IFolderInfo destinationFolder, FolderProvider sourceFolderProvider, FolderProvider destinationFolderProvider) { var versions = FileVersionController.Instance.GetFileVersions(file).ToArray(); - if (!versions.Any()) return; - + if (!versions.Any()) + { + return; + } + var folder = FolderManager.Instance.GetFolder(file.FolderId); foreach (var version in versions) @@ -1517,9 +1546,12 @@ internal virtual void MoveVersions(IFileInfo file, IFolderInfo destinationFolder using (var fileContent = sourceFolderProvider.GetFileStream(folder, version.FileName)) { // This scenario is when the file is in the Database Folder Provider - if (fileContent == null) continue; - - AddFileToFolderProvider(fileContent, version.FileName, destinationFolder, destinationFolderProvider); + if (fileContent == null) + { + continue; + } + + this.AddFileToFolderProvider(fileContent, version.FileName, destinationFolder, destinationFolderProvider); } var fileVersion = new FileInfo @@ -1527,71 +1559,13 @@ internal virtual void MoveVersions(IFileInfo file, IFolderInfo destinationFolder FileName = version.FileName, Folder = file.Folder, FolderMappingID = file.FolderMappingID, - PortalId = folder.PortalID + PortalId = folder.PortalID, }; - DeleteFileFromFolderProvider(fileVersion, sourceFolderProvider); - } - } - - #endregion - - #region Workflow Methods - - private bool CanUpdateWhenApproving(IFolderInfo folder, ContentItem item, int createdByUserID) - { - if (WorkflowEngine.Instance.IsWorkflowOnDraft(item.ContentItemId)) - { - ////We assume User can add content to folder - return true; + this.DeleteFileFromFolderProvider(fileVersion, sourceFolderProvider); } - return WorkflowSecurity.Instance.HasStateReviewerPermission(folder.PortalID, createdByUserID, item.StateID); - } - - private bool StartWorkflow(int createdByUserID, Workflow folderWorkflow, bool fileExists, int contentItemID) - { - if (WorkflowEngine.Instance.IsWorkflowCompleted(contentItemID)) - { - WorkflowEngine.Instance.StartWorkflow(folderWorkflow.WorkflowID, contentItemID, createdByUserID); - return true; - } - return false; - } - private string UpdateWhileApproving(IFolderInfo folder, int createdByUserID, IFileInfo file, IFileInfo oldFile, Stream content) - { - var contentController = new ContentController(); - bool workflowCompleted = WorkflowEngine.Instance.IsWorkflowCompleted(file.ContentItemID); - - var isDatabaseMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID).MappingName == "Database"; - - //If the file does not exist, then the field would not has value. - //Currently, first upload has not version file - if (oldFile == null || !oldFile.HasBeenPublished) - { - return file.FileName; - } - if (workflowCompleted) //We assume User can add content to folder - { - return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); - } - - if (CanUpdateWhenApproving(folder, contentController.GetContentItem(file.ContentItemID), createdByUserID)) - { - //Update the Unpublished version - var versions = FileVersionController.Instance.GetFileVersions(file).ToArray(); - if (versions.Any()) - { - FileVersionController.Instance.DeleteFileVersion(file, versions.OrderByDescending(f => f.Version).FirstOrDefault().Version); - } - return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); - } - - throw new FileLockedException( - Localization.Localization.GetExceptionMessage("FileLockedRunningWorkflowError", - "File locked. The file cannot be updated because it has a running workflow")); - } - #endregion - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void AutoSyncFile(IFileInfo file) { @@ -1605,19 +1579,20 @@ internal virtual void AutoSyncFile(IFileInfo file) var newFileSize = folderProvider.GetFileSize(file); if (file.Size != newFileSize) { - using (var fileContent = GetFileContent(file)) + using (var fileContent = this.GetFileContent(file)) { - UpdateFile(file, fileContent); + this.UpdateFile(file, fileContent); } } } else { - DeleteFile(file); + this.DeleteFile(file); } - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, IList invalidFiles) { var folderManager = FolderManager.Instance; @@ -1628,11 +1603,12 @@ internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, { invalidFiles = new List(); } + var exactFilesCount = 0; try { - using (var fileContent = GetFileContent(file)) + using (var fileContent = this.GetFileContent(file)) { zipInputStream = new ZipInputStream(fileContent); @@ -1646,7 +1622,7 @@ internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, exactFilesCount++; var fileName = Path.GetFileName(zipEntry.Name); - EnsureZipFolder(zipEntry.Name, destinationFolder); + this.EnsureZipFolder(zipEntry.Name, destinationFolder); IFolderInfo parentFolder; if (zipEntry.Name.IndexOf("/") == -1) @@ -1661,7 +1637,7 @@ internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, try { - AddFile(parentFolder, fileName, zipInputStream, true); + this.AddFile(parentFolder, fileName, zipInputStream, true); } catch (PermissionsNotMetException exc) { @@ -1697,6 +1673,65 @@ internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, return exactFilesCount; } + + private bool CanUpdateWhenApproving(IFolderInfo folder, ContentItem item, int createdByUserID) + { + if (WorkflowEngine.Instance.IsWorkflowOnDraft(item.ContentItemId)) + { + ////We assume User can add content to folder + return true; + } + + return WorkflowSecurity.Instance.HasStateReviewerPermission(folder.PortalID, createdByUserID, item.StateID); + } + + private bool StartWorkflow(int createdByUserID, Workflow folderWorkflow, bool fileExists, int contentItemID) + { + if (WorkflowEngine.Instance.IsWorkflowCompleted(contentItemID)) + { + WorkflowEngine.Instance.StartWorkflow(folderWorkflow.WorkflowID, contentItemID, createdByUserID); + return true; + } + + return false; + } + + private string UpdateWhileApproving(IFolderInfo folder, int createdByUserID, IFileInfo file, IFileInfo oldFile, Stream content) + { + var contentController = new ContentController(); + bool workflowCompleted = WorkflowEngine.Instance.IsWorkflowCompleted(file.ContentItemID); + + var isDatabaseMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID).MappingName == "Database"; + + // If the file does not exist, then the field would not has value. + // Currently, first upload has not version file + if (oldFile == null || !oldFile.HasBeenPublished) + { + return file.FileName; + } + + if (workflowCompleted) // We assume User can add content to folder + { + return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); + } + + if (this.CanUpdateWhenApproving(folder, contentController.GetContentItem(file.ContentItemID), createdByUserID)) + { + // Update the Unpublished version + var versions = FileVersionController.Instance.GetFileVersions(file).ToArray(); + if (versions.Any()) + { + FileVersionController.Instance.DeleteFileVersion(file, versions.OrderByDescending(f => f.Version).FirstOrDefault().Version); + } + + return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); + } + + throw new FileLockedException( + Localization.GetExceptionMessage( + "FileLockedRunningWorkflowError", + "File locked. The file cannot be updated because it has a running workflow")); + } /// This member is reserved for internal use and is not intended to be used directly from your code. internal void EnsureZipFolder(string fileName, IFolderInfo destinationFolder) @@ -1740,22 +1775,24 @@ internal void EnsureZipFolder(string fileName, IFolderInfo destinationFolder) parentFolder = folderManager.GetFolder(destinationFolder.PortalID, newFolderPath); } } - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual Stream GetAutoDeleteFileStream(string filePath) { return new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, BufferSize, FileOptions.DeleteOnClose); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual int GetCurrentUserID() { return UserController.Instance.GetCurrentUserInfo().UserID; } /// This member is reserved for internal use and is not intended to be used directly from your code. - /// SHA1 hash of the file + /// SHA1 hash of the file. internal virtual string GetHash(Stream stream) { Requires.NotNull("stream", stream); @@ -1773,54 +1810,60 @@ internal virtual string GetHash(Stream stream) } /// - /// Gets the hash of a file + /// Gets the hash of a file. /// /// The file info. - /// SHA1 hash of the file + /// SHA1 hash of the file. internal virtual string GetHash(IFileInfo fileInfo) { return FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(fileInfo.FolderMappingID).FolderProviderType).GetHashCode(fileInfo); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual string GetHostMapPath() { return TestableGlobals.Instance.HostMapPath; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual Image GetImageFromStream(Stream stream) { return Image.FromStream(stream); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual Globals.PerformanceSettings GetPerformanceSetting() { return Host.PerformanceSetting; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool IsAllowedExtension(string fileName) { var extension = Path.GetExtension(fileName); - //regex matches a dot followed by 1 or more chars followed by a semi-colon - //regex is meant to block files like "foo.asp;.png" which can take advantage - //of a vulnerability in IIS6 which treasts such files as .asp, not .png + // regex matches a dot followed by 1 or more chars followed by a semi-colon + // regex is meant to block files like "foo.asp;.png" which can take advantage + // of a vulnerability in IIS6 which treasts such files as .asp, not .png return !string.IsNullOrEmpty(extension) - && WhiteList.IsAllowedExtension(extension) + && this.WhiteList.IsAllowedExtension(extension) && !Globals.FileExtensionRegex.IsMatch(fileName); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool IsValidFilename(string fileName) { - //regex ensures the file is a valid filename and doesn't include illegal characters + // regex ensures the file is a valid filename and doesn't include illegal characters return Globals.FileValidNameRegex.IsMatch(fileName); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool IsFileAutoSyncEnabled() { return Host.EnableFileAutoSync; @@ -1850,14 +1893,18 @@ internal virtual void WriteFileToHttpContext(IFileInfo file, ContentDisposition } // Do not send negative Content-Length (file.Size could be negative due to integer overflow for files > 2GB) - if (file.Size >= 0) objResponse.AppendHeader("Content-Length", file.Size.ToString(CultureInfo.InvariantCulture)); - objResponse.ContentType = GetContentType(file.Extension.Replace(".", "")); + if (file.Size >= 0) + { + objResponse.AppendHeader("Content-Length", file.Size.ToString(CultureInfo.InvariantCulture)); + } + + objResponse.ContentType = this.GetContentType(file.Extension.Replace(".", string.Empty)); try { - using (var fileContent = GetFileContent(file)) + using (var fileContent = this.GetFileContent(file)) { - WriteStream(objResponse, fileContent); + this.WriteStream(objResponse, fileContent); } } catch (Exception ex) @@ -1906,59 +1953,59 @@ internal virtual void WriteStream(HttpResponse objResponse, Stream objStream) } } } - - + /// /// Update file info to database. /// /// File info. - /// Whether to update the lazy load properties: Width, Height, Sha1Hash. - /// The file info + /// Whether to update the lazy load properties: Width, Height, Sha1Hash. + /// The file info. internal virtual IFileInfo UpdateFile(IFileInfo file, bool updateLazyload) { - //By default File Events will be fired - return UpdateFile(file, updateLazyload, true); + // By default File Events will be fired + return this.UpdateFile(file, updateLazyload, true); } - - + /// /// Update file info to database. /// /// File info. /// Whether to update the lazy load properties: Width, Height, Sha1Hash. - /// Whether to fire File events or not - /// The file info + /// Whether to fire File events or not. + /// The file info. internal virtual IFileInfo UpdateFile(IFileInfo file, bool updateLazyload, bool fireEvent) { Requires.NotNull("file", file); - DataProvider.Instance().UpdateFile(file.FileId, - file.VersionGuid, - file.FileName, - file.Extension, - file.Size, - updateLazyload ? file.Width : Null.NullInteger, - updateLazyload ? file.Height : Null.NullInteger, - file.ContentType, - file.FolderId, - GetCurrentUserID(), - updateLazyload ? file.SHA1Hash : Null.NullString, - file.LastModificationTime, - file.Title, - file.Description, - file.StartDate, - file.EndDate, - file.EnablePublishPeriod, - file.ContentItemID); + DataProvider.Instance().UpdateFile( + file.FileId, + file.VersionGuid, + file.FileName, + file.Extension, + file.Size, + updateLazyload ? file.Width : Null.NullInteger, + updateLazyload ? file.Height : Null.NullInteger, + file.ContentType, + file.FolderId, + this.GetCurrentUserID(), + updateLazyload ? file.SHA1Hash : Null.NullString, + file.LastModificationTime, + file.Title, + file.Description, + file.StartDate, + file.EndDate, + file.EnablePublishPeriod, + file.ContentItemID); DataCache.RemoveCache("GetFileById" + file.FileId); - ClearFolderCache(file.PortalId); - var updatedFile = GetFile(file.FileId); + this.ClearFolderCache(file.PortalId); + var updatedFile = this.GetFile(file.FileId); if (fireEvent) { - OnFileMetadataChanged(updatedFile ?? GetFile(file.FileId, true), GetCurrentUserID()); + this.OnFileMetadataChanged(updatedFile ?? this.GetFile(file.FileId, true), this.GetCurrentUserID()); } + return updatedFile; } @@ -1970,39 +2017,38 @@ internal virtual void ClearFolderCache(int portalId) private static bool ValidMetadata(IFileInfo file, out string exceptionMessage) { - exceptionMessage = ""; - //TODO check dynamically all required fields from MetadataInfo + exceptionMessage = string.Empty; + + // TODO check dynamically all required fields from MetadataInfo - //TODO check dynamically all max lengths from MetadataInfo - //TODO Use the MaxLength from MetadataInfo + // TODO check dynamically all max lengths from MetadataInfo + // TODO Use the MaxLength from MetadataInfo if (!string.IsNullOrEmpty(file.Title) && file.Title.Length > 256) { - exceptionMessage = Localization.Localization.GetExceptionMessage("MaxLengthExceeded", "The maximum length of the field {0} has been exceeded", DefaultMetadataNames.Title); + exceptionMessage = Localization.GetExceptionMessage("MaxLengthExceeded", "The maximum length of the field {0} has been exceeded", DefaultMetadataNames.Title); return false; } if (file.StartDate == null || file.StartDate == Null.NullDate) { - exceptionMessage = Localization.Localization.GetExceptionMessage("StartDateRequired", "The Start Date is required"); + exceptionMessage = Localization.GetExceptionMessage("StartDateRequired", "The Start Date is required"); return false; } var savedFile = FileManager.Instance.GetFile(file.FileId); if (file.StartDate < file.CreatedOnDate.Date && file.StartDate != savedFile.StartDate) { - exceptionMessage = Localization.Localization.GetExceptionMessage("StartDateMustNotBeInThePast", "The Start Date must not be in the past"); + exceptionMessage = Localization.GetExceptionMessage("StartDateMustNotBeInThePast", "The Start Date must not be in the past"); return false; } if (file.EndDate != Null.NullDate && file.StartDate > file.EndDate) { - exceptionMessage = Localization.Localization.GetExceptionMessage("InvalidPublishPeriod", "The End Date must be after the Start Date"); + exceptionMessage = Localization.GetExceptionMessage("InvalidPublishPeriod", "The End Date must be after the Start Date"); return false; } return true; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs index 68dc79f0ef2..8d1bf75c243 100644 --- a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs +++ b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs @@ -1,40 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; -using System.IO; -using System.Threading; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem.EventArgs; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem { + using System; + using System.Globalization; + using System.IO; + using System.Threading; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem.EventArgs; + using DotNetNuke.Services.Localization; + public class FileServerHandler : IHttpHandler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FileServerHandler)); - #region IHttpHandler Members + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileServerHandler)); + public bool IsReusable => true; + /// ----------------------------------------------------------------------------- /// /// This handler handles requests for LinkClick.aspx, but only those specifc - /// to file serving + /// to file serving. /// - /// System.Web.HttpContext) + /// System.Web.HttpContext). /// /// /// ----------------------------------------------------------------------------- @@ -45,25 +41,25 @@ public void ProcessRequest(HttpContext context) var ModuleId = -1; try { - //get TabId + // get TabId if (context.Request.QueryString["tabid"] != null) { - Int32.TryParse(context.Request.QueryString["tabid"], out TabId); + int.TryParse(context.Request.QueryString["tabid"], out TabId); } - //get ModuleId + // get ModuleId if (context.Request.QueryString["mid"] != null) { - Int32.TryParse(context.Request.QueryString["mid"], out ModuleId); + int.TryParse(context.Request.QueryString["mid"], out ModuleId); } } catch (Exception) { - //The TabId or ModuleId are incorrectly formatted (potential DOS) - Handle404Exception(context, context.Request.RawUrl); + // The TabId or ModuleId are incorrectly formatted (potential DOS) + this.Handle404Exception(context, context.Request.RawUrl); } - //get Language + // get Language string Language = _portalSettings.DefaultLanguage; if (context.Request.QueryString["language"] != null) { @@ -76,47 +72,51 @@ public void ProcessRequest(HttpContext context) Language = context.Request.Cookies["language"].Value; } } + if (LocaleController.Instance.IsEnabled(ref Language, _portalSettings.PortalId)) { - Localization.Localization.SetThreadCultures(new CultureInfo(Language), _portalSettings); - Localization.Localization.SetLanguage(Language); + Localization.SetThreadCultures(new CultureInfo(Language), _portalSettings); + Localization.SetLanguage(Language); } - //get the URL - string URL = ""; + // get the URL + string URL = string.Empty; if (context.Request.QueryString["fileticket"] != null) { - URL = "FileID=" + FileLinkClickController.Instance.GetFileIdFromLinkClick(context.Request.QueryString); } + if (context.Request.QueryString["userticket"] != null) { URL = "UserId=" + UrlUtils.DecryptParameter(context.Request.QueryString["userticket"]); } + if (context.Request.QueryString["link"] != null) { URL = context.Request.QueryString["link"]; if (URL.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) { - URL = ""; //restrict direct access by FileID + URL = string.Empty; // restrict direct access by FileID } } - if (!String.IsNullOrEmpty(URL)) + + if (!string.IsNullOrEmpty(URL)) { URL = URL.Replace(@"\", @"/"); - //update clicks, this must be done first, because the url tracker works with unmodified urls, like tabid, fileid etc + // update clicks, this must be done first, because the url tracker works with unmodified urls, like tabid, fileid etc var objUrls = new UrlController(); objUrls.UpdateUrlTracking(_portalSettings.PortalId, URL, ModuleId, -1); TabType UrlType = Globals.GetURLType(URL); - if(UrlType == TabType.Tab) + if (UrlType == TabType.Tab) { - //verify whether the tab is exist, otherwise throw out 404. + // verify whether the tab is exist, otherwise throw out 404. if (TabController.Instance.GetTab(int.Parse(URL), _portalSettings.PortalId, false) == null) { - Handle404Exception(context, context.Request.RawUrl); + this.Handle404Exception(context, context.Request.RawUrl); } } + if (UrlType != TabType.File) { URL = Globals.LinkClick(URL, TabId, ModuleId, false); @@ -124,7 +124,7 @@ public void ProcessRequest(HttpContext context) if (UrlType == TabType.File && URL.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false) { - //to handle legacy scenarios before the introduction of the FileServerHandler + // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(URL); var folderPath = URL.Substring(0, URL.LastIndexOf(fileName, StringComparison.InvariantCulture)); @@ -135,15 +135,16 @@ public void ProcessRequest(HttpContext context) URL = "FileID=" + file.FileId; } - //get optional parameters + // get optional parameters bool blnForceDownload = false; if ((context.Request.QueryString["forcedownload"] != null) || (context.Request.QueryString["contenttype"] != null)) - { - bool.TryParse(context.Request.QueryString["forcedownload"], out blnForceDownload); + { + bool.TryParse(context.Request.QueryString["forcedownload"], out blnForceDownload); } + var contentDisposition = blnForceDownload ? ContentDisposition.Attachment : ContentDisposition.Inline; - //clear the current response + // clear the current response context.Response.Clear(); var fileManager = FileManager.Instance; try @@ -155,11 +156,11 @@ public void ProcessRequest(HttpContext context) var file = fileManager.GetFile(int.Parse(UrlUtils.GetParameterValue(URL))); if (file != null) { - if (!file.IsEnabled || !HasAPublishedVersion(file)) + if (!file.IsEnabled || !this.HasAPublishedVersion(file)) { if (context.Request.IsAuthenticated) { - context.Response.Redirect(Globals.AccessDeniedURL(Localization.Localization.GetString("FileAccess.Error")), true); + context.Response.Redirect(Globals.AccessDeniedURL(Localization.GetString("FileAccess.Error")), true); } else { @@ -175,7 +176,7 @@ public void ProcessRequest(HttpContext context) EventManager.Instance.OnFileDownloaded(new FileDownloadedEventArgs() { FileInfo = file, - UserId = UserController.Instance.GetCurrentUserInfo().UserID + UserId = UserController.Instance.GetCurrentUserInfo().UserID, }); if (directUrl.Contains("LinkClick") || (blnForceDownload && folderMapping.FolderProviderType == "StandardFolderProvider")) @@ -192,16 +193,15 @@ public void ProcessRequest(HttpContext context) { if (context.Request.IsAuthenticated) { - context.Response.Redirect(Globals.AccessDeniedURL(Localization.Localization.GetString("FileAccess.Error")), true); + context.Response.Redirect(Globals.AccessDeniedURL(Localization.GetString("FileAccess.Error")), true); } else { context.Response.Redirect(Globals.AccessDeniedURL(), true); } } - catch (ThreadAbortException) //if call fileManager.WriteFileToResponse ThreadAbortException will shown, should catch it and do nothing. + catch (ThreadAbortException) // if call fileManager.WriteFileToResponse ThreadAbortException will shown, should catch it and do nothing. { - } catch (Exception ex) { @@ -211,18 +211,20 @@ public void ProcessRequest(HttpContext context) if (!download) { - Handle404Exception(context, URL); + this.Handle404Exception(context, URL); } + break; case TabType.Url: - //prevent phishing by verifying that URL exists in URLs table for Portal + // prevent phishing by verifying that URL exists in URLs table for Portal if (objUrls.GetUrl(_portalSettings.PortalId, URL) != null) { context.Response.Redirect(URL, true); } + break; default: - //redirect to URL + // redirect to URL context.Response.Redirect(URL, true); break; } @@ -232,12 +234,12 @@ public void ProcessRequest(HttpContext context) } catch (Exception) { - Handle404Exception(context, URL); + this.Handle404Exception(context, URL); } } else { - Handle404Exception(context, URL); + this.Handle404Exception(context, URL); } } @@ -247,7 +249,8 @@ private bool HasAPublishedVersion(IFileInfo file) { return true; } - //We should allow creator to see the file that is pending to be approved + + // We should allow creator to see the file that is pending to be approved var user = UserController.Instance.GetCurrentUserInfo(); return user != null && user.UserID == file.CreatedByUserID; } @@ -263,9 +266,5 @@ private void Handle404Exception(HttpContext context, string url) UrlUtils.Handle404Exception(context.Response, PortalController.Instance.GetCurrentPortalSettings()); } } - - public bool IsReusable => true; - - #endregion } } diff --git a/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs b/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs index 7b77752f212..93dd93ab73b 100644 --- a/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs @@ -1,11 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + + using Localization = DotNetNuke.Services.Localization.Localization; + public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter { private const string FileSizeFormat = "fs"; @@ -45,21 +47,21 @@ public string Format(string format, object arg, IFormatProvider formatProvider) if (size >= OneGigaByte) { size /= OneGigaByte; - suffix = Localization.Localization.GetString("SizeGb"); + suffix = Localization.GetString("SizeGb"); } else if (size >= OneMegaByte) { size /= OneMegaByte; - suffix = Localization.Localization.GetString("SizeMb"); + suffix = Localization.GetString("SizeMb"); } else if (size >= OneKiloByte) { size /= OneKiloByte; - suffix = Localization.Localization.GetString("SizeKb"); + suffix = Localization.GetString("SizeKb"); } else { - suffix = Localization.Localization.GetString("SizeB"); + suffix = Localization.GetString("SizeB"); } return string.Format("{0:N1} {1}", size, suffix); diff --git a/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs b/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs index 0fa15152221..e3070a89adf 100644 --- a/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs +++ b/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using System.Text.RegularExpressions; -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections.Specialized; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Utilities; + public class FileUrlHelper { private static readonly Regex RegexStandardFile = @@ -27,9 +28,11 @@ public static bool IsStandardFileURLFormat(string requestPath, out IFileInfo fil { portalId = int.Parse(portal); } + fileRequested = FileManager.Instance.GetFile(portalId, filePath); return true; } + fileRequested = null; return false; } @@ -42,6 +45,7 @@ public static bool IsLinkClickURLFormat(string requestPath, NameValueCollection fileRequested = FileManager.Instance.GetFile(fileId); return true; } + fileRequested = null; return false; } diff --git a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs index c44f2079b23..01c2bbd9821 100644 --- a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs @@ -1,32 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem.EventArgs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem.EventArgs; + public class FileVersionController : ComponentBase, IFileVersionController - { - - #region database methods + { public string AddFileVersion(IFileInfo file, int userId, bool published, bool removeOldestVersions, Stream content = null) { Requires.NotNull("file", file); - + byte[] fileContent = null; if (content != null) @@ -45,33 +43,34 @@ public string AddFileVersion(IFileInfo file, int userId, bool published, bool re } var newVersion = DataProvider.Instance() - .AddFileVersion(file.FileId, - file.UniqueId, - file.VersionGuid, - file.FileName, - file.Extension, - file.Size, - file.Width, - file.Height, - file.ContentType, - file.Folder, - file.FolderId, - userId, - file.SHA1Hash, - file.LastModificationTime, - file.Title, - file.EnablePublishPeriod, - file.StartDate, - file.EndDate, - file.ContentItemID, - published, - fileContent); - + .AddFileVersion( + file.FileId, + file.UniqueId, + file.VersionGuid, + file.FileName, + file.Extension, + file.Size, + file.Width, + file.Height, + file.ContentType, + file.Folder, + file.FolderId, + userId, + file.SHA1Hash, + file.LastModificationTime, + file.Title, + file.EnablePublishPeriod, + file.StartDate, + file.EndDate, + file.ContentItemID, + published, + fileContent); + DataCache.RemoveCache("GetFileById" + file.FileId); if (removeOldestVersions) { - RemoveOldestsVersions(file); + this.RemoveOldestsVersions(file); } if (published) @@ -82,25 +81,29 @@ public string AddFileVersion(IFileInfo file, int userId, bool published, bool re return GetVersionedFilename(file, newVersion); } - + public void SetPublishedVersion(IFileInfo file, int newPublishedVersion) { DataProvider.Instance().SetPublishedVersion(file.FileId, newPublishedVersion); DataCache.RemoveCache("GetFileById" + file.FileId); - // Rename the original file to the versioned name + // Rename the original file to the versioned name // Rename the new versioned name to the original file name var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) return; + if (folderMapping == null) + { + return; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); - folderProvider.RenameFile(file, GetVersionedFilename(file, file.PublishedVersion)); + folderProvider.RenameFile(file, GetVersionedFilename(file, file.PublishedVersion)); folderProvider.RenameFile( - new FileInfo { FileName = GetVersionedFilename(file, newPublishedVersion), Folder = file.Folder, FolderId = file.FolderId, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID }, + new FileInfo { FileName = GetVersionedFilename(file, newPublishedVersion), Folder = file.Folder, FolderId = file.FolderId, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID }, file.FileName); - + // Notify File Changed - OnFileChanged(file, UserController.Instance.GetCurrentUserInfo().UserID); + this.OnFileChanged(file, UserController.Instance.GetCurrentUserInfo().UserID); } public int DeleteFileVersion(IFileInfo file, int version) @@ -110,8 +113,11 @@ public int DeleteFileVersion(IFileInfo file, int version) int newVersion; var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) return Null.NullInteger; - + if (folderMapping == null) + { + return Null.NullInteger; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); if (file.PublishedVersion == version) @@ -120,10 +126,10 @@ public int DeleteFileVersion(IFileInfo file, int version) newVersion = DataProvider.Instance().DeleteFileVersion(file.FileId, version); folderProvider.RenameFile( - new FileInfo { FileId = file.FileId, FileName = GetVersionedFilename(file, newVersion), Folder = file.Folder, FolderId = file.FolderId, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID }, + new FileInfo { FileId = file.FileId, FileName = GetVersionedFilename(file, newVersion), Folder = file.Folder, FolderId = file.FolderId, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID }, file.FileName); - //Update the Last Modification Time + // Update the Last Modification Time var providerLastModificationTime = folderProvider.GetLastModificationTime(file); if (file.LastModificationTime != providerLastModificationTime) { @@ -131,12 +137,12 @@ public int DeleteFileVersion(IFileInfo file, int version) } // Notify File Changed - OnFileChanged(file, UserController.Instance.GetCurrentUserInfo().UserID); + this.OnFileChanged(file, UserController.Instance.GetCurrentUserInfo().UserID); } else { - newVersion = DataProvider.Instance().DeleteFileVersion(file.FileId, version); - folderProvider.DeleteFile(new FileInfo { FileName = GetVersionedFilename(file, version), Folder = file.Folder, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID, FolderId = file.FolderId }); + newVersion = DataProvider.Instance().DeleteFileVersion(file.FileId, version); + folderProvider.DeleteFile(new FileInfo { FileName = GetVersionedFilename(file, version), Folder = file.Folder, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID, FolderId = file.FolderId }); } DataCache.RemoveCache("GetFileById" + file.FileId); @@ -155,11 +161,14 @@ public void DeleteAllUnpublishedVersions(IFileInfo file, bool resetPublishedVers Requires.NotNull("file", file); var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) return; - + if (folderMapping == null) + { + return; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); - foreach (var version in GetFileVersions(file)) + foreach (var version in this.GetFileVersions(file)) { folderProvider.DeleteFile(new FileInfo { FileName = version.FileName, Folder = file.Folder, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID, FolderId = file.FolderId }); DataProvider.Instance().DeleteFileVersion(version.FileId, version.Version); @@ -181,12 +190,12 @@ public IEnumerable GetFileVersions(IFileInfo file) public bool IsFolderVersioned(int folderId) { - return IsFolderVersioned(FolderManager.Instance.GetFolder(folderId)); + return this.IsFolderVersioned(FolderManager.Instance.GetFolder(folderId)); } public bool IsFolderVersioned(IFolderInfo folder) { - return IsFileVersionEnabled(folder.PortalID) && folder.IsVersioned; + return this.IsFileVersionEnabled(folder.PortalID) && folder.IsVersioned; } public bool IsFileVersionEnabled(int portalId) @@ -209,27 +218,34 @@ public IEnumerable GetFileVersionsInFolder(int folderId) public Stream GetVersionContent(IFileInfo file, int version) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) return null; + if (folderMapping == null) + { + return null; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); var folder = FolderManager.Instance.GetFolder(file.FolderId); - return GetVersionContent(folderProvider, folder, file, version); + return this.GetVersionContent(folderProvider, folder, file, version); } public void RollbackFileVersion(IFileInfo file, int version, int userId) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) return; - + if (folderMapping == null) + { + return; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); var folder = FolderManager.Instance.GetFolder(file.FolderId); - using (var content = GetVersionContent(folderProvider, folder, file, version)) + using (var content = this.GetVersionContent(folderProvider, folder, file, version)) { FileManager.Instance.AddFile(folder, file.FileName, content, true, true, file.ContentType, userId); } // We need to refresh the file object file = FileManager.Instance.GetFile(file.FileId); - var fileVersion = GetFileVersion(file, version); + var fileVersion = this.GetFileVersion(file, version); file.Extension = fileVersion.Extension; file.Size = fileVersion.Size; file.SHA1Hash = fileVersion.SHA1Hash; @@ -237,20 +253,33 @@ public void RollbackFileVersion(IFileInfo file, int version, int userId) file.Height = fileVersion.Height; FileManager.Instance.UpdateFile(file); - RemoveOldestsVersions(file); + this.RemoveOldestsVersions(file); + } + + internal static string GetVersionedFilename(IFileInfo file, int version) + { + return string.Format("{0}_{1}.v.resources", file.FileId, version); } - - #endregion - #region helper methods + private static void RenameFile(IFileInfo file, string newFileName) + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); + if (folderMapping != null) + { + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); + folderProvider.RenameFile(file, newFileName); + } + DataCache.RemoveCache("GetFileById" + file.FileId); + } + private void OnFileChanged(IFileInfo fileInfo, int userId) { - EventManager.Instance.OnFileChanged(new FileChangedEventArgs - { - FileInfo = fileInfo, - UserId = userId - }); + EventManager.Instance.OnFileChanged(new FileChangedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + }); } private Stream GetVersionContent(FolderProvider provider, IFolderInfo folder, IFileInfo file, int version) @@ -261,34 +290,15 @@ private Stream GetVersionContent(FolderProvider provider, IFolderInfo folder, IF private void RemoveOldestsVersions(IFileInfo file) { var portalId = FolderManager.Instance.GetFolder(file.FolderId).PortalID; - var versions = GetFileVersions(file); - var maxVersions = MaxFileVersions(portalId) - 1; // The published version is not in the FileVersions collection + var versions = this.GetFileVersions(file); + var maxVersions = this.MaxFileVersions(portalId) - 1; // The published version is not in the FileVersions collection if (versions.Count() > maxVersions) { foreach (var v in versions.OrderBy(v => v.Version).Take(versions.Count() - maxVersions)) { - DeleteFileVersion(file, v.Version); + this.DeleteFileVersion(file, v.Version); } } } - - internal static string GetVersionedFilename(IFileInfo file, int version) - { - return string.Format("{0}_{1}.v.resources", file.FileId, version); - } - - private static void RenameFile(IFileInfo file, string newFileName) - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping != null) - { - var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); - folderProvider.RenameFile(file, newFileName); - } - - DataCache.RemoveCache("GetFileById" + file.FileId); - } - - #endregion } } diff --git a/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs b/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs index 86cf9c5e68f..68246edb7e6 100644 --- a/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs @@ -1,27 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Xml.Serialization; -using DotNetNuke.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Xml.Serialization; + + using DotNetNuke.Entities; + [Serializable] public class FileVersionInfo : BaseEntityInfo - { - #region "Constructors" - + { public FileVersionInfo() { - Version = 1; - } - - #endregion - - #region "Properties" - + this.Version = 1; + } + [XmlElement("fileid")] public int FileId { get; set; } @@ -36,7 +31,7 @@ public FileVersionInfo() [XmlElement("extension")] public string Extension { get; set; } - + [XmlElement("size")] public int Size { get; set; } @@ -47,8 +42,6 @@ public FileVersionInfo() public int Width { get; set; } [XmlElement("sha1hash")] - public string SHA1Hash { get; set; } - - #endregion + public string SHA1Hash { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderController.cs b/DNN Platform/Library/Services/FileSystem/FolderController.cs index 37077c3bd30..07100589034 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderController.cs @@ -1,45 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : FolderController + /// Project : DotNetNuke + /// Class : FolderController /// /// ----------------------------------------------------------------------------- /// /// Business Class that provides access to the Database for the functions within the calling classes - /// Instantiates the instance of the DataProvider and returns the object, if any + /// Instantiates the instance of the DataProvider and returns the object, if any. /// /// /// /// ----------------------------------------------------------------------------- public class FolderController - { - #region StorageLocationTypes enum - + { public enum StorageLocationTypes { InsecureFileSystem = 0, SecureFileSystem = 1, - DatabaseSecure = 2 - } - - #endregion + DatabaseSecure = 2, + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs index e682d57dc71..ebc5e85ef51 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Web; -using System.Xml.Serialization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Web; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + [XmlRoot("folder", IsNullable = false)] [Serializable] public class FolderInfo : BaseEntityInfo, IHydratable, IFolderInfo @@ -31,29 +26,47 @@ public class FolderInfo : BaseEntityInfo, IHydratable, IFolderInfo private string _displayName; private string _displayPath; private FolderPermissionCollection _folderPermissions; - private int _folderMappingId; - - #region Constructors - - public FolderInfo(): this(false) - { + private int _folderMappingId; + + public FolderInfo() + : this(false) + { } + + [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] + public FolderInfo(int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) + : this(Guid.NewGuid(), portalId, folderpath, storageLocation, isProtected, isCached, lastUpdated) + { + } + + [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] + public FolderInfo(Guid uniqueId, int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) + { + this.FolderID = Null.NullInteger; + this.UniqueId = uniqueId; + this.VersionGuid = Guid.NewGuid(); + this.WorkflowID = Null.NullInteger; + + this.PortalID = portalId; + this.FolderPath = folderpath; + this.StorageLocation = storageLocation; + this.IsProtected = isProtected; + this.IsCached = isCached; + this.LastUpdated = lastUpdated; + } internal FolderInfo(bool initialiseEmptyPermissions) { - FolderID = Null.NullInteger; - UniqueId = Guid.NewGuid(); - VersionGuid = Guid.NewGuid(); - WorkflowID = Null.NullInteger; + this.FolderID = Null.NullInteger; + this.UniqueId = Guid.NewGuid(); + this.VersionGuid = Guid.NewGuid(); + this.WorkflowID = Null.NullInteger; if (initialiseEmptyPermissions) { - _folderPermissions = new FolderPermissionCollection(); - } - } - #endregion - - #region Public Properties - + this._folderPermissions = new FolderPermissionCollection(); + } + } + [XmlElement("folderid")] public int FolderID { get; set; } @@ -68,17 +81,18 @@ public string FolderName { get { - string folderName = PathUtils.Instance.RemoveTrailingSlash(FolderPath); + string folderName = PathUtils.Instance.RemoveTrailingSlash(this.FolderPath); if (folderName.Length > 0 && folderName.LastIndexOf("/", StringComparison.Ordinal) > -1) { folderName = folderName.Substring(folderName.LastIndexOf("/", StringComparison.Ordinal) + 1); } + return folderName; } } /// - /// Gets a value indicating whether the folder has any child subfolder + /// Gets a value indicating whether the folder has any child subfolder. /// [XmlElement("haschildren")] public bool HasChildren @@ -94,15 +108,17 @@ public string DisplayName { get { - if (string.IsNullOrEmpty(_displayName)) + if (string.IsNullOrEmpty(this._displayName)) { - _displayName = FolderName; + this._displayName = this.FolderName; } - return _displayName; + + return this._displayName; } + set { - _displayName = value; + this._displayName = value; } } @@ -114,15 +130,17 @@ public string DisplayPath { get { - if (string.IsNullOrEmpty(_displayPath)) + if (string.IsNullOrEmpty(this._displayPath)) { - _displayPath = FolderPath; + this._displayPath = this.FolderPath; } - return _displayPath; + + return this._displayPath; } + set { - _displayPath = value; + this._displayPath = value; } } @@ -133,19 +151,19 @@ public string DisplayPath public bool IsProtected { get; set; } /// - /// Gets or sets a value indicating whether file versions are active for the folder + /// Gets or sets a value indicating whether file versions are active for the folder. /// [XmlElement("isversioned")] public bool IsVersioned { get; set; } /// - /// Gets or sets the path this folder is mapped on its provider file system + /// Gets or sets the path this folder is mapped on its provider file system. /// [XmlElement("mappedpath")] public string MappedPath { get; set; } /// - /// Gets or sets a reference to the active Workflow for the folder + /// Gets or sets a reference to the active Workflow for the folder. /// [XmlElement("workflowid")] public int WorkflowID { get; set; } @@ -154,7 +172,7 @@ public string DisplayPath public DateTime LastUpdated { get; set; } /// - /// Gets or sets a reference to the parent folder + /// Gets or sets a reference to the parent folder. /// [XmlElement("parentid")] public int ParentID { get; set; } @@ -171,22 +189,22 @@ public string PhysicalPath portalSettings = PortalController.Instance.GetCurrentPortalSettings(); } - if (PortalID == Null.NullInteger) + if (this.PortalID == Null.NullInteger) { - physicalPath = Globals.HostMapPath + FolderPath; + physicalPath = Globals.HostMapPath + this.FolderPath; } else { - if (portalSettings == null || portalSettings.PortalId != PortalID) + if (portalSettings == null || portalSettings.PortalId != this.PortalID) { - //Get the PortalInfo based on the Portalid - var portal = PortalController.Instance.GetPortal(PortalID); + // Get the PortalInfo based on the Portalid + var portal = PortalController.Instance.GetPortal(this.PortalID); - physicalPath = portal.HomeDirectoryMapPath + FolderPath; + physicalPath = portal.HomeDirectoryMapPath + this.FolderPath; } else { - physicalPath = portalSettings.HomeDirectoryMapPath + FolderPath; + physicalPath = portalSettings.HomeDirectoryMapPath + this.FolderPath; } } @@ -203,9 +221,9 @@ public string PhysicalPath [XmlElement("folderpermissions")] public FolderPermissionCollection FolderPermissions { - get + get { - return _folderPermissions ?? (_folderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(PortalID, FolderPath))); + return this._folderPermissions ?? (this._folderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(this.PortalID, this.FolderPath))); } } @@ -213,30 +231,31 @@ public int FolderMappingID { get { - if (_folderMappingId == 0) + if (this._folderMappingId == 0) { - switch (StorageLocation) + switch (this.StorageLocation) { case (int)FolderController.StorageLocationTypes.InsecureFileSystem: - _folderMappingId = FolderMappingController.Instance.GetFolderMapping(PortalID, "Standard").FolderMappingID; + this._folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Standard").FolderMappingID; break; case (int)FolderController.StorageLocationTypes.SecureFileSystem: - _folderMappingId = FolderMappingController.Instance.GetFolderMapping(PortalID, "Secure").FolderMappingID; + this._folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Secure").FolderMappingID; break; case (int)FolderController.StorageLocationTypes.DatabaseSecure: - _folderMappingId = FolderMappingController.Instance.GetFolderMapping(PortalID, "Database").FolderMappingID; + this._folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Database").FolderMappingID; break; default: - _folderMappingId = FolderMappingController.Instance.GetDefaultFolderMapping(PortalID).FolderMappingID; + this._folderMappingId = FolderMappingController.Instance.GetDefaultFolderMapping(this.PortalID).FolderMappingID; break; } } - return _folderMappingId; + return this._folderMappingId; } + set { - _folderMappingId = value; + this._folderMappingId = value; } } @@ -244,85 +263,54 @@ public bool IsStorageSecure { get { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(PortalID, FolderMappingID); + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalID, this.FolderMappingID); return FolderProvider.Instance(folderMapping.FolderProviderType).IsStorageSecure; - } - } - - #endregion - - #region IHydratable Implementation - - /// ----------------------------------------------------------------------------- - /// - /// Fills a FolderInfo from a Data Reader - /// - /// The Data Reader to use - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - FolderID = Null.SetNullInteger(dr["FolderID"]); - UniqueId = Null.SetNullGuid(dr["UniqueId"]); - VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); - PortalID = Null.SetNullInteger(dr["PortalID"]); - FolderPath = Null.SetNullString(dr["FolderPath"]); - MappedPath = Null.SetNullString(dr["MappedPath"]); - IsCached = Null.SetNullBoolean(dr["IsCached"]); - IsProtected = Null.SetNullBoolean(dr["IsProtected"]); - StorageLocation = Null.SetNullInteger(dr["StorageLocation"]); - LastUpdated = Null.SetNullDateTime(dr["LastUpdated"]); - FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); - IsVersioned = Null.SetNullBoolean(dr["IsVersioned"]); - WorkflowID = Null.SetNullInteger(dr["WorkflowID"]); - ParentID = Null.SetNullInteger(dr["ParentID"]); - FillBaseProperties(dr); - } + } + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Key ID + /// Gets or sets and sets the Key ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] public int KeyID { get { - return FolderID; + return this.FolderID; } + set { - FolderID = value; + this.FolderID = value; } - } - - #endregion - - #region Obsolete Methods - - [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] - public FolderInfo(int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) - : this(Guid.NewGuid(), portalId, folderpath, storageLocation, isProtected, isCached, lastUpdated) - { - } - - [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] - public FolderInfo(Guid uniqueId, int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) + } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a FolderInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) { - FolderID = Null.NullInteger; - UniqueId = uniqueId; - VersionGuid = Guid.NewGuid(); - WorkflowID = Null.NullInteger; - - PortalID = portalId; - FolderPath = folderpath; - StorageLocation = storageLocation; - IsProtected = isProtected; - IsCached = isCached; - LastUpdated = lastUpdated; + this.FolderID = Null.SetNullInteger(dr["FolderID"]); + this.UniqueId = Null.SetNullGuid(dr["UniqueId"]); + this.VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.FolderPath = Null.SetNullString(dr["FolderPath"]); + this.MappedPath = Null.SetNullString(dr["MappedPath"]); + this.IsCached = Null.SetNullBoolean(dr["IsCached"]); + this.IsProtected = Null.SetNullBoolean(dr["IsProtected"]); + this.StorageLocation = Null.SetNullInteger(dr["StorageLocation"]); + this.LastUpdated = Null.SetNullDateTime(dr["LastUpdated"]); + this.FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); + this.IsVersioned = Null.SetNullBoolean(dr["IsVersioned"]); + this.WorkflowID = Null.SetNullInteger(dr["WorkflowID"]); + this.ParentID = Null.SetNullInteger(dr["ParentID"]); + this.FillBaseProperties(dr); } - - #endregion } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderManager.cs b/DNN Platform/Library/Services/FileSystem/FolderManager.cs index 9adeaffcd31..6153368532d 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderManager.cs @@ -1,64 +1,170 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net.NetworkInformation; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem.EventArgs; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Log.EventLog; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net.NetworkInformation; + using System.Reflection; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem.EventArgs; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Log.EventLog; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// /// Exposes methods to manage folders. /// public class FolderManager : ComponentBase, IFolderManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FolderManager)); - private static readonly Dictionary SyncFoldersData = new Dictionary(); private const string DefaultUsersFoldersPath = "Users"; private const string DefaultMappedPathSetting = "DefaultMappedPath"; - private static readonly object _threadLocker = new object(); - - #region Public Properties - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FolderManager)); + private static readonly Dictionary SyncFoldersData = new Dictionary(); + private static readonly object _threadLocker = new object(); + public virtual string MyFolderName { get { - return Localization.Localization.GetString("MyFolderName"); + return Localization.GetString("MyFolderName"); + } + } + + /// + /// Creates a new folder using the provided folder path. + /// + /// The folder mapping to use. + /// The path of the new folder. + /// Thrown when folderPath or folderMapping are null. + /// Thrown when the underlying system throw an exception. + /// The added folder. + public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath) + { + return this.AddFolder(folderMapping, folderPath, folderPath); + } + + /// + /// Creates a new folder using the provided folder path and mapping. + /// + /// The folder mapping to use. + /// The path of the new folder. + /// The mapped path of the new folder. + /// Thrown when folderPath or folderMapping are null. + /// Thrown when the underlying system throw an exception. + /// The added folder. + public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath, string mappedPath) + { + Requires.PropertyNotNull("folderPath", folderPath); + Requires.NotNull("folderMapping", folderMapping); + + folderPath = folderPath.Trim(); + + if (this.FolderExists(folderMapping.PortalID, folderPath)) + { + throw new FolderAlreadyExistsException(Localization.GetExceptionMessage("AddFolderAlreadyExists", "The provided folder path already exists. The folder has not been added.")); + } + + if (!this.IsValidFolderPath(folderPath)) + { + throw new InvalidFolderPathException(Localization.GetExceptionMessage("AddFolderNotAllowed", "The folder path '{0}' is not allowed. The folder has not been added.", folderPath)); + } + + var parentFolder = this.GetParentFolder(folderMapping.PortalID, folderPath); + if (parentFolder != null) + { + var parentFolderMapping = FolderMappingController.Instance.GetFolderMapping( + parentFolder.PortalID, + parentFolder.FolderMappingID); + if (FolderProvider.Instance(parentFolderMapping.FolderProviderType).SupportsMappedPaths) + { + folderMapping = parentFolderMapping; + mappedPath = string.IsNullOrEmpty(parentFolder.FolderPath) ? PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath) + : PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath.Replace(parentFolder.FolderPath, string.Empty)); + } + else if (!FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) + { + mappedPath = folderPath; + } + else + { + // Parent foldermapping DOESN'T support mapped path + // abd current foldermapping YES support mapped path + mappedPath = PathUtils.Instance.FormatFolderPath(this.GetDefaultMappedPath(folderMapping) + mappedPath); + } + } + else if (FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) + { + mappedPath = PathUtils.Instance.FormatFolderPath(this.GetDefaultMappedPath(folderMapping) + mappedPath); + } + + try + { + FolderProvider.Instance(folderMapping.FolderProviderType).AddFolder(folderPath, folderMapping, mappedPath); + } + catch (Exception ex) + { + Logger.Error(ex); + + throw new FolderProviderException(Localization.GetExceptionMessage("AddFolderUnderlyingSystemError", "The underlying system threw an exception. The folder has not been added."), ex); } + + this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(folderMapping.PortalID, folderPath)); + var folderId = this.CreateFolderInDatabase(folderMapping.PortalID, folderPath, folderMapping.FolderMappingID, mappedPath); + + var folder = this.GetFolder(folderId); + + // Notify add folder event + this.OnFolderAdded(folder, this.GetCurrentUserId()); + + return folder; } - #endregion + private static Regex WildcardToRegex(string pattern) + { + if (!pattern.Contains("*") && !pattern.Contains("?")) + { + pattern = "^" + pattern + ".*$"; + } + else + { + pattern = "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$"; + } + + return RegexUtils.GetCachedRegex(pattern, RegexOptions.IgnoreCase); + } - #region Private Methods + private static bool IsStandardFolderProviderType(FolderMappingInfo folderMappingInfo) + { + var compatibleTypes = new[] { "StandardFolderProvider", "SecureFolderProvider", "DatabaseFolderProvider" }; + return compatibleTypes.Contains(folderMappingInfo.FolderProviderType); + } + private int AddFolderInternal(IFolderInfo folder) { - //Check this is not a duplicate - var tmpfolder = GetFolder(folder.PortalID, folder.FolderPath); + // Check this is not a duplicate + var tmpfolder = this.GetFolder(folder.PortalID, folder.FolderPath); if (tmpfolder != null && folder.FolderID == Null.NullInteger) { @@ -71,7 +177,7 @@ private int AddFolderInternal(IFolderInfo folder) var workflowId = folder.WorkflowID; // Inherit some configuration from its Parent Folder - var parentFolder = GetParentFolder(folder.PortalID, folder.FolderPath); + var parentFolder = this.GetParentFolder(folder.PortalID, folder.FolderPath); var parentId = Null.NullInteger; if (parentFolder != null) { @@ -81,48 +187,50 @@ private int AddFolderInternal(IFolderInfo folder) } folder.FolderPath = PathUtils.Instance.FormatFolderPath(folder.FolderPath); - folder.FolderID = DataProvider.Instance().AddFolder(folder.PortalID, - folder.UniqueId, - folder.VersionGuid, - folder.FolderPath, - folder.MappedPath, - folder.StorageLocation, - folder.IsProtected, - folder.IsCached, - folder.LastUpdated, - GetCurrentUserId(), - folder.FolderMappingID, - isVersioned, - workflowId, - parentId); - - //Refetch folder for logging - folder = GetFolder(folder.PortalID, folder.FolderPath); - - AddLogEntry(folder, EventLogController.EventLogType.FOLDER_CREATED); + folder.FolderID = DataProvider.Instance().AddFolder( + folder.PortalID, + folder.UniqueId, + folder.VersionGuid, + folder.FolderPath, + folder.MappedPath, + folder.StorageLocation, + folder.IsProtected, + folder.IsCached, + folder.LastUpdated, + this.GetCurrentUserId(), + folder.FolderMappingID, + isVersioned, + workflowId, + parentId); + + // Refetch folder for logging + folder = this.GetFolder(folder.PortalID, folder.FolderPath); + + this.AddLogEntry(folder, EventLogController.EventLogType.FOLDER_CREATED); if (parentFolder != null) { - UpdateFolderInternal(parentFolder, false); + this.UpdateFolderInternal(parentFolder, false); } else { - UpdateParentFolder(folder.PortalID, folder.FolderPath); + this.UpdateParentFolder(folder.PortalID, folder.FolderPath); } } else { - var parentFolder = GetParentFolder(folder.PortalID, folder.FolderPath); + var parentFolder = this.GetParentFolder(folder.PortalID, folder.FolderPath); if (parentFolder != null) { // Ensure that Parent Id is repaired folder.ParentID = parentFolder.FolderID; } - UpdateFolderInternal(folder, false); + + this.UpdateFolderInternal(folder, false); } - //Invalidate Cache - ClearFolderCache(folder.PortalID); + // Invalidate Cache + this.ClearFolderCache(folder.PortalID); return folder.FolderID; } @@ -133,8 +241,9 @@ private bool GetOnlyUnmap(IFolderInfo folder) { return true; } - return (FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(folder.FolderMappingID).FolderProviderType).SupportsMappedPaths && - GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID) ; + + return FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(folder.FolderMappingID).FolderProviderType).SupportsMappedPaths && + this.GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID; } private void UnmapFolderInternal(IFolderInfo folder, bool isCascadeDeleting) @@ -145,10 +254,11 @@ private void UnmapFolderInternal(IFolderInfo folder, bool isCascadeDeleting) { DirectoryWrapper.Instance.Delete(folder.PhysicalPath, true); } - DeleteFolder(folder.PortalID, folder.FolderPath); + + this.DeleteFolder(folder.PortalID, folder.FolderPath); // Notify folder deleted event - OnFolderDeleted(folder, GetCurrentUserId(), isCascadeDeleting); + this.OnFolderDeleted(folder, this.GetCurrentUserId(), isCascadeDeleting); } private void DeleteFolderInternal(IFolderInfo folder, bool isCascadeDeleting) @@ -166,8 +276,9 @@ private void DeleteFolderInternal(IFolderInfo folder, bool isCascadeDeleting) Logger.Error(ex); throw new FolderProviderException( - Localization.Localization.GetExceptionMessage("DeleteFolderUnderlyingSystemError", - "The underlying system threw an exception. The folder has not been deleted."), + Localization.GetExceptionMessage( + "DeleteFolderUnderlyingSystemError", + "The underlying system threw an exception. The folder has not been deleted."), ex); } @@ -175,18 +286,19 @@ private void DeleteFolderInternal(IFolderInfo folder, bool isCascadeDeleting) { DirectoryWrapper.Instance.Delete(folder.PhysicalPath, true); } - DeleteFolder(folder.PortalID, folder.FolderPath); + + this.DeleteFolder(folder.PortalID, folder.FolderPath); // Notify folder deleted event - OnFolderDeleted(folder, GetCurrentUserId(), isCascadeDeleting); + this.OnFolderDeleted(folder, this.GetCurrentUserId(), isCascadeDeleting); } private IFolderInfo GetParentFolder(int portalId, string folderPath) { - if (!String.IsNullOrEmpty(folderPath)) + if (!string.IsNullOrEmpty(folderPath)) { var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); - return GetFolder(portalId, parentFolderPath); + return this.GetFolder(portalId, parentFolderPath); } return null; @@ -201,11 +313,11 @@ private IEnumerable SearchFiles(IFolderInfo folder, Regex regex, bool if (recursive) { - foreach (var subFolder in GetFolders(folder)) + foreach (var subFolder in this.GetFolders(folder)) { if (FolderPermissionController.Instance.CanViewFolder(subFolder)) { - files.AddRange(SearchFiles(subFolder, regex, true)); + files.AddRange(this.SearchFiles(subFolder, regex, true)); } } } @@ -217,88 +329,69 @@ private IFolderInfo UpdateFolderInternal(IFolderInfo folder, bool clearCache) { Requires.NotNull("folder", folder); - DataProvider.Instance().UpdateFolder(folder.PortalID, - folder.VersionGuid, - folder.FolderID, - PathUtils.Instance.FormatFolderPath(folder.FolderPath), - folder.StorageLocation, - folder.MappedPath, - folder.IsProtected, - folder.IsCached, - folder.LastUpdated, - GetCurrentUserId(), - folder.FolderMappingID, - folder.IsVersioned, - folder.WorkflowID, - folder.ParentID); + DataProvider.Instance().UpdateFolder( + folder.PortalID, + folder.VersionGuid, + folder.FolderID, + PathUtils.Instance.FormatFolderPath(folder.FolderPath), + folder.StorageLocation, + folder.MappedPath, + folder.IsProtected, + folder.IsCached, + folder.LastUpdated, + this.GetCurrentUserId(), + folder.FolderMappingID, + folder.IsVersioned, + folder.WorkflowID, + folder.ParentID); if (clearCache) { - ClearFolderCache(folder.PortalID); + this.ClearFolderCache(folder.PortalID); } return folder; } - private static Regex WildcardToRegex(string pattern) + private int FindFolderMappingId(MergedTreeItem item, int portalId) { - if (!pattern.Contains("*") && !pattern.Contains("?")) + if (item.ExistsInFolderMapping) { - pattern = "^" + pattern + ".*$"; + return item.FolderMappingID; } - else + + if (item.FolderPath.IndexOf('/') != item.FolderPath.LastIndexOf('/')) { - pattern = "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$"; + var parentPath = item.FolderPath.Substring(0, item.FolderPath.TrimEnd('/').LastIndexOf('/') + 1); + var folder = this.GetFolder(portalId, parentPath); + if (folder != null) + { + return folder.FolderMappingID; + } } - return RegexUtils.GetCachedRegex(pattern, RegexOptions.IgnoreCase); - } - - private static bool IsStandardFolderProviderType(FolderMappingInfo folderMappingInfo) - { - var compatibleTypes = new[] { "StandardFolderProvider", "SecureFolderProvider", "DatabaseFolderProvider" }; - return compatibleTypes.Contains(folderMappingInfo.FolderProviderType); + return FolderMappingController.Instance.GetDefaultFolderMapping(portalId).FolderMappingID; } - private int FindFolderMappingId(MergedTreeItem item, int portalId) - { - if (item.ExistsInFolderMapping) - { - return item.FolderMappingID; - } - - if (item.FolderPath.IndexOf('/') != item.FolderPath.LastIndexOf('/')) - { - var parentPath = item.FolderPath.Substring(0, item.FolderPath.TrimEnd('/').LastIndexOf('/') + 1); - var folder = GetFolder(portalId, parentPath); - if (folder != null) - { - return folder.FolderMappingID; - } - } - - return FolderMappingController.Instance.GetDefaultFolderMapping(portalId).FolderMappingID; - } - private bool DeleteFolderRecursive(IFolderInfo folder, ICollection notDeletedSubfolders, bool isRecursiveDeletionFolder, bool unmap) { Requires.NotNull("folder", folder); if (UserSecurityController.Instance.HasFolderPermission(folder, "DELETE")) { - var subfolders = GetFolders(folder); + var subfolders = this.GetFolders(folder); var allSubFoldersHasBeenDeleted = true; foreach (var subfolder in subfolders) { - if (!DeleteFolderRecursive(subfolder, notDeletedSubfolders, false, unmap || GetOnlyUnmap(subfolder))) + if (!this.DeleteFolderRecursive(subfolder, notDeletedSubfolders, false, unmap || this.GetOnlyUnmap(subfolder))) { allSubFoldersHasBeenDeleted = false; } } - var files = GetFiles(folder, false, true); + var files = this.GetFiles(folder, false, true); foreach (var file in files) { if (unmap) @@ -307,21 +400,23 @@ private bool DeleteFolderRecursive(IFolderInfo folder, ICollection } else { - FileDeletionController.Instance.DeleteFile(file); + FileDeletionController.Instance.DeleteFile(file); } - OnFileDeleted(file, GetCurrentUserId(), true); - } - + + this.OnFileDeleted(file, this.GetCurrentUserId(), true); + } + if (allSubFoldersHasBeenDeleted) { if (unmap) { - UnmapFolderInternal(folder, !isRecursiveDeletionFolder); + this.UnmapFolderInternal(folder, !isRecursiveDeletionFolder); } else { - DeleteFolderInternal(folder, !isRecursiveDeletionFolder); + this.DeleteFolderInternal(folder, !isRecursiveDeletionFolder); } + return true; } } @@ -335,8 +430,9 @@ private string GetDefaultMappedPath(FolderMappingInfo folderMapping) var defaultMappedPath = folderMapping.FolderMappingSettings[DefaultMappedPathSetting]; if (defaultMappedPath == null) { - return String.Empty; + return string.Empty; } + return defaultMappedPath.ToString(); } @@ -347,167 +443,67 @@ private IEnumerable GetFolders(IFolderInfo parentFolder, bool allSu if (allSubFolders) { var subFolders = - GetFolders(parentFolder.PortalID) + this.GetFolders(parentFolder.PortalID) .Where( f => - f.FolderPath.StartsWith(parentFolder.FolderPath, + f.FolderPath.StartsWith( + parentFolder.FolderPath, StringComparison.InvariantCultureIgnoreCase)); return subFolders.Where(f => f.FolderID != parentFolder.FolderID); } - return GetFolders(parentFolder.PortalID).Where(f => f.ParentID == parentFolder.FolderID); - } - - #region On Folder Events + return this.GetFolders(parentFolder.PortalID).Where(f => f.ParentID == parentFolder.FolderID); + } + private void OnFolderMoved(IFolderInfo folderInfo, int userId, string oldFolderPath) { - EventManager.Instance.OnFolderMoved(new FolderMovedEventArgs - { - FolderInfo = folderInfo, - UserId = userId, - OldFolderPath = oldFolderPath - }); + EventManager.Instance.OnFolderMoved(new FolderMovedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + OldFolderPath = oldFolderPath, + }); } private void OnFolderRenamed(IFolderInfo folderInfo, int userId, string oldFolderName) { - EventManager.Instance.OnFolderRenamed(new FolderRenamedEventArgs - { - FolderInfo = folderInfo, - UserId = userId, - OldFolderName = oldFolderName - }); + EventManager.Instance.OnFolderRenamed(new FolderRenamedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + OldFolderName = oldFolderName, + }); } private void OnFolderDeleted(IFolderInfo folderInfo, int userId, bool isCascadeDeleting) { - EventManager.Instance.OnFolderDeleted(new FolderDeletedEventArgs - { - FolderInfo = folderInfo, - UserId = userId, - IsCascadeDeletng = isCascadeDeleting - }); + EventManager.Instance.OnFolderDeleted(new FolderDeletedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + IsCascadeDeletng = isCascadeDeleting, + }); } private void OnFolderAdded(IFolderInfo folderInfo, int userId) { - EventManager.Instance.OnFolderAdded(new FolderChangedEventArgs - { - FolderInfo = folderInfo, - UserId = userId - }); + EventManager.Instance.OnFolderAdded(new FolderChangedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + }); } private void OnFileDeleted(IFileInfo fileInfo, int userId, bool isCascadeDeleting) { - EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - IsCascadeDeleting = isCascadeDeleting - }); - } - - #endregion - - #endregion - - #region Public Methods - - /// - /// Creates a new folder using the provided folder path. - /// - /// The folder mapping to use. - /// The path of the new folder. - /// Thrown when folderPath or folderMapping are null. - /// Thrown when the underlying system throw an exception. - /// The added folder. - public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath) - { - return AddFolder(folderMapping, folderPath, folderPath); - } - - /// - /// Creates a new folder using the provided folder path and mapping. - /// - /// The folder mapping to use. - /// The path of the new folder. - /// The mapped path of the new folder. - /// Thrown when folderPath or folderMapping are null. - /// Thrown when the underlying system throw an exception. - /// The added folder. - public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath, string mappedPath) - { - Requires.PropertyNotNull("folderPath", folderPath); - Requires.NotNull("folderMapping", folderMapping); - - folderPath = folderPath.Trim(); - - if (FolderExists(folderMapping.PortalID, folderPath)) - { - throw new FolderAlreadyExistsException(Localization.Localization.GetExceptionMessage("AddFolderAlreadyExists", "The provided folder path already exists. The folder has not been added.")); - } - - if (!IsValidFolderPath(folderPath)) - { - throw new InvalidFolderPathException(Localization.Localization.GetExceptionMessage("AddFolderNotAllowed", "The folder path '{0}' is not allowed. The folder has not been added.", folderPath)); - } - - var parentFolder = GetParentFolder(folderMapping.PortalID, folderPath); - if (parentFolder != null) - { - var parentFolderMapping = FolderMappingController.Instance.GetFolderMapping(parentFolder.PortalID, - parentFolder.FolderMappingID); - if (FolderProvider.Instance(parentFolderMapping.FolderProviderType).SupportsMappedPaths) - { - folderMapping = parentFolderMapping; - mappedPath = String.IsNullOrEmpty(parentFolder.FolderPath) ? PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath) - : PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath.Replace(parentFolder.FolderPath, string.Empty)); - } - else if (!FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) - { - mappedPath = folderPath; - } - else - { - //Parent foldermapping DOESN'T support mapped path - // abd current foldermapping YES support mapped path - mappedPath = PathUtils.Instance.FormatFolderPath(GetDefaultMappedPath(folderMapping) + mappedPath); - } - } - else if (FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) - { - mappedPath = PathUtils.Instance.FormatFolderPath(GetDefaultMappedPath(folderMapping) + mappedPath); - } - - try - { - FolderProvider.Instance(folderMapping.FolderProviderType).AddFolder(folderPath, folderMapping, mappedPath); - } - catch (Exception ex) - { - Logger.Error(ex); - - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("AddFolderUnderlyingSystemError", "The underlying system threw an exception. The folder has not been added."), ex); - } - - CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(folderMapping.PortalID, folderPath)); - var folderId = CreateFolderInDatabase(folderMapping.PortalID, folderPath, folderMapping.FolderMappingID, mappedPath); - - var folder = GetFolder(folderId); - - // Notify add folder event - OnFolderAdded(folder, GetCurrentUserId()); - - return folder; - } - - internal virtual bool IsValidFolderPath(string folderPath) - { - var illegalInFolderPath = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))), RegexOptions.Compiled); - return !illegalInFolderPath.IsMatch(folderPath) && !folderPath.TrimEnd('/', '\\').EndsWith("."); - } + EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + IsCascadeDeleting = isCascadeDeleting, + }); + } /// /// Creates a new folder in the given portal using the provided folder path. @@ -524,11 +520,11 @@ public virtual IFolderInfo AddFolder(int portalId, string folderPath) folderPath = PathUtils.Instance.FormatFolderPath(folderPath); var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); - var parentFolder = GetFolder(portalId, parentFolderPath) ?? AddFolder(portalId, parentFolderPath); + var parentFolder = this.GetFolder(portalId, parentFolderPath) ?? this.AddFolder(portalId, parentFolderPath); var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, parentFolder.FolderMappingID); - return AddFolder(folderMapping, folderPath); + return this.AddFolder(folderMapping, folderPath); } /// @@ -538,13 +534,19 @@ public virtual IFolderInfo AddFolder(int portalId, string folderPath) /// Thrown when folder is null. /// Thrown when the underlying system throw an exception. public virtual void DeleteFolder(IFolderInfo folder) - { - DeleteFolderInternal(folder, false); + { + this.DeleteFolderInternal(folder, false); + } + + internal virtual bool IsValidFolderPath(string folderPath) + { + var illegalInFolderPath = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))), RegexOptions.Compiled); + return !illegalInFolderPath.IsMatch(folderPath) && !folderPath.TrimEnd('/', '\\').EndsWith("."); } public virtual void UnlinkFolder(IFolderInfo folder) { - DeleteFolderRecursive(folder, new Collection(), true, true); + this.DeleteFolderRecursive(folder, new Collection(), true, true); } /// @@ -553,23 +555,22 @@ public virtual void UnlinkFolder(IFolderInfo folder) /// The folder identifier. public virtual void DeleteFolder(int folderId) { - var folder = GetFolder(folderId); + var folder = this.GetFolder(folderId); - DeleteFolder(folder); + this.DeleteFolder(folder); } /// - /// Deletes the specified folder and all its content + /// Deletes the specified folder and all its content. /// - /// The folder to delete - /// A collection with all not deleted subfolders after processiong the action - /// + /// The folder to delete. + /// A collection with all not deleted subfolders after processiong the action. public void DeleteFolder(IFolderInfo folder, ICollection notDeletedSubfolders) { - DeleteFolderRecursive(folder, notDeletedSubfolders, true, GetOnlyUnmap(folder)); - } - - /// + this.DeleteFolderRecursive(folder, notDeletedSubfolders, true, this.GetOnlyUnmap(folder)); + } + + /// /// Checks the existence of the specified folder in the specified portal. /// /// The portal where to check the existence of the folder. @@ -579,7 +580,7 @@ public virtual bool FolderExists(int portalId, string folderPath) { Requires.PropertyNotNull("folderPath", folderPath); - return GetFolder(portalId, folderPath) != null; + return this.GetFolder(portalId, folderPath) != null; } /// @@ -589,26 +590,26 @@ public virtual bool FolderExists(int portalId, string folderPath) /// The list of files contained in the specified folder. public virtual IEnumerable GetFiles(IFolderInfo folder) { - return GetFiles(folder, false); + return this.GetFiles(folder, false); } /// /// Gets the files contained in the specified folder. /// /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders + /// Whether or not to include all the subfolders. /// The list of files contained in the specified folder. public virtual IEnumerable GetFiles(IFolderInfo folder, bool recursive) { - return GetFiles(folder, recursive, false); + return this.GetFiles(folder, recursive, false); } /// /// Gets the files contained in the specified folder. /// /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders - /// Indicates if the file is retrieved from All files or from Published files + /// Whether or not to include all the subfolders. + /// Indicates if the file is retrieved from All files or from Published files. /// The list of files contained in the specified folder. public virtual IEnumerable GetFiles(IFolderInfo folder, bool recursive, bool retrieveUnpublishedFiles) { @@ -620,7 +621,7 @@ public virtual IEnumerable GetFiles(IFolderInfo folder, bool recursiv /// /// Gets the list of Standard folders the specified user has the provided permissions. /// - /// The user info + /// The user info. /// The permissions the folders have to met. /// The list of Standard folders the specified user has the provided permissions. /// This method is used to support legacy behaviours and situations where we know the file/folder is in the file system. @@ -630,11 +631,11 @@ public virtual IEnumerable GetFileSystemFolders(UserInfo user, stri var portalId = user.PortalID; - var userFolder = GetUserFolder(user); + var userFolder = this.GetUserFolder(user); var defaultFolderMaping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - var folders = GetFolders(portalId, permissions, user.UserID).Where(f => f.FolderPath != null && f.FolderMappingID == defaultFolderMaping.FolderMappingID); + var folders = this.GetFolders(portalId, permissions, user.UserID).Where(f => f.FolderPath != null && f.FolderMappingID == defaultFolderMaping.FolderMappingID); foreach (var folder in folders) { @@ -642,10 +643,10 @@ public virtual IEnumerable GetFileSystemFolders(UserInfo user, stri { if (folder.FolderID == userFolder.FolderID) { - folder.DisplayPath = MyFolderName + "/"; - folder.DisplayName = MyFolderName; + folder.DisplayPath = this.MyFolderName + "/"; + folder.DisplayName = this.MyFolderName; } - else if (!folder.FolderPath.StartsWith(userFolder.FolderPath, StringComparison.InvariantCultureIgnoreCase)) //Allow UserFolder children + else if (!folder.FolderPath.StartsWith(userFolder.FolderPath, StringComparison.InvariantCultureIgnoreCase)) // Allow UserFolder children { continue; } @@ -664,16 +665,16 @@ public virtual IEnumerable GetFileSystemFolders(UserInfo user, stri /// The folder entity or null if the folder cannot be located. public virtual IFolderInfo GetFolder(int folderId) { - //Try and get the folder from the portal cache + // Try and get the folder from the portal cache IFolderInfo folder = null; var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (portalSettings != null) { - var folders = GetFolders(portalSettings.PortalId); + var folders = this.GetFolders(portalSettings.PortalId); folder = folders.SingleOrDefault(f => f.FolderID == folderId) ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(folderId)); } - return folder ?? (CBO.Instance.FillObject(DataProvider.Instance().GetFolder(folderId))); + return folder ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(folderId)); } /// @@ -688,7 +689,7 @@ public virtual IFolderInfo GetFolder(int portalId, string folderPath) folderPath = PathUtils.Instance.FormatFolderPath(folderPath); - var folders = GetFolders(portalId); + var folders = this.GetFolders(portalId); return folders.SingleOrDefault(f => f.FolderPath == folderPath) ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(portalId, folderPath)); } @@ -710,23 +711,23 @@ public virtual IFolderInfo GetFolder(Guid uniqueId) /// Thrown when parentFolder is null. public virtual IEnumerable GetFolders(IFolderInfo parentFolder) { - return GetFolders(parentFolder, false); + return this.GetFolders(parentFolder, false); } /// /// Gets the sorted list of folders of the provided portal. /// /// The portal identifier. - /// True = Read from Cache, False = Read from DB + /// True = Read from Cache, False = Read from DB. /// The sorted list of folders of the provided portal. public virtual IEnumerable GetFolders(int portalId, bool useCache) { if (!useCache) { - ClearFolderCache(portalId); + this.ClearFolderCache(portalId); } - return GetFolders(portalId); + return this.GetFolders(portalId); } /// @@ -739,7 +740,7 @@ public virtual IEnumerable GetFolders(int portalId) var folders = new List(); var cacheKey = string.Format(DataCache.FolderCacheKey, portalId); - CBO.Instance.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.FolderCacheTimeOut, DataCache.FolderCachePriority, portalId), GetFoldersSortedCallBack, false).ForEach(folders.Add); + CBO.Instance.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.FolderCacheTimeOut, DataCache.FolderCachePriority, portalId), this.GetFoldersSortedCallBack, false).ForEach(folders.Add); return folders; } @@ -757,25 +758,25 @@ public virtual IEnumerable GetFolders(int portalId, string permissi var cacheKey = string.Format(DataCache.FolderUserCacheKey, portalId, permissions, userId); var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.FolderUserCacheTimeOut, DataCache.FolderUserCachePriority, portalId, permissions, userId); - CBO.Instance.GetCachedObject>(cacheItemArgs, GetFoldersByPermissionSortedCallBack, false).ForEach(folders.Add); + CBO.Instance.GetCachedObject>(cacheItemArgs, this.GetFoldersByPermissionSortedCallBack, false).ForEach(folders.Add); return folders; } /// - /// Gets the list of folders the specified user has read permissions + /// Gets the list of folders the specified user has read permissions. /// - /// The user info + /// The user info. /// The list of folders the specified user has read permissions. public virtual IEnumerable GetFolders(UserInfo user) { - return GetFolders(user, "READ"); + return this.GetFolders(user, "READ"); } /// - /// Gets the list of folders the specified user has the provided permissions + /// Gets the list of folders the specified user has the provided permissions. /// - /// The user info + /// The user info. /// The permissions the folders have to met. /// The list of folders the specified user has the provided permissions. public virtual IEnumerable GetFolders(UserInfo user, string permissions) @@ -784,18 +785,18 @@ public virtual IEnumerable GetFolders(UserInfo user, string permiss var portalId = user.PortalID; - var userFolder = GetUserFolder(user); + var userFolder = this.GetUserFolder(user); - foreach (var folder in GetFolders(portalId, permissions, user.UserID).Where(folder => folder.FolderPath != null)) + foreach (var folder in this.GetFolders(portalId, permissions, user.UserID).Where(folder => folder.FolderPath != null)) { if (folder.FolderPath.StartsWith(DefaultUsersFoldersPath + "/", StringComparison.InvariantCultureIgnoreCase)) { if (folder.FolderID == userFolder.FolderID) { - folder.DisplayPath = Localization.Localization.GetString("MyFolderName") + "/"; - folder.DisplayName = Localization.Localization.GetString("MyFolderName"); + folder.DisplayPath = Localization.GetString("MyFolderName") + "/"; + folder.DisplayName = Localization.GetString("MyFolderName"); } - else if (!folder.FolderPath.StartsWith(userFolder.FolderPath, StringComparison.InvariantCultureIgnoreCase)) //Allow UserFolder children + else if (!folder.FolderPath.StartsWith(userFolder.FolderPath, StringComparison.InvariantCultureIgnoreCase)) // Allow UserFolder children { continue; } @@ -809,11 +810,11 @@ public virtual IEnumerable GetFolders(UserInfo user, string permiss public virtual IFolderInfo GetUserFolder(UserInfo userInfo) { - //always use _default portal for a super user + // always use _default portal for a super user int portalId = userInfo.IsSuperUser ? -1 : userInfo.PortalID; string userFolderPath = ((PathUtils)PathUtils.Instance).GetUserFolderPathInternal(userInfo); - return GetFolder(portalId, userFolderPath) ?? AddUserFolder(userInfo); + return this.GetFolder(portalId, userFolderPath) ?? this.AddUserFolder(userInfo); } public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) @@ -822,29 +823,34 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinatio Requires.NotNull("destinationFolder", destinationFolder); var newFolderPath = PathUtils.Instance.FormatFolderPath(destinationFolder.FolderPath + folder.FolderName + "/"); - - if (folder.FolderPath == destinationFolder.FolderPath) return folder; - if(FolderExists(folder.PortalID, newFolderPath)) + if (folder.FolderPath == destinationFolder.FolderPath) + { + return folder; + } + + if (this.FolderExists(folder.PortalID, newFolderPath)) { throw new InvalidOperationException(string.Format( - Localization.Localization.GetExceptionMessage("CannotMoveFolderAlreadyExists", - "The folder with name '{0}' cannot be moved. A folder with that name already exists under the folder '{1}'.", folder.FolderName, destinationFolder.FolderName))); + Localization.GetExceptionMessage( + "CannotMoveFolderAlreadyExists", + "The folder with name '{0}' cannot be moved. A folder with that name already exists under the folder '{1}'.", folder.FolderName, destinationFolder.FolderName))); } - + var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); var destinationFolderMapping = FolderMappingController.Instance.GetFolderMapping(destinationFolder.PortalID, destinationFolder.FolderMappingID); - if(!CanMoveBetweenFolderMappings(folderMapping, destinationFolderMapping)) + if (!this.CanMoveBetweenFolderMappings(folderMapping, destinationFolderMapping)) { throw new InvalidOperationException(string.Format( - Localization.Localization.GetExceptionMessage("CannotMoveFolderBetweenFolderType", - "The folder with name '{0}' cannot be moved. Move Folder operation between this two folder types is not allowed", folder.FolderName))); + Localization.GetExceptionMessage( + "CannotMoveFolderBetweenFolderType", + "The folder with name '{0}' cannot be moved. Move Folder operation between this two folder types is not allowed", folder.FolderName))); } - if (!IsMoveOperationValid(folder, destinationFolder, newFolderPath)) + if (!this.IsMoveOperationValid(folder, destinationFolder, newFolderPath)) { - throw new InvalidOperationException(Localization.Localization.GetExceptionMessage("MoveFolderCannotComplete", "The operation cannot be completed.")); + throw new InvalidOperationException(Localization.GetExceptionMessage("MoveFolderCannotComplete", "The operation cannot be completed.")); } var currentFolderPath = folder.FolderPath; @@ -852,14 +858,14 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinatio if ((folder.FolderMappingID == destinationFolder.FolderMappingID && FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMoveFolder) || (IsStandardFolderProviderType(folderMapping) && IsStandardFolderProviderType(destinationFolderMapping))) { - MoveFolderWithinProvider(folder, destinationFolder); + this.MoveFolderWithinProvider(folder, destinationFolder); } else { - MoveFolderBetweenProviders(folder, newFolderPath); + this.MoveFolderBetweenProviders(folder, newFolderPath); } - //log the folder moved event. + // log the folder moved event. var log = new LogInfo(); log.AddProperty("Old Folder Path", currentFolderPath); log.AddProperty("New Folder Path", newFolderPath); @@ -867,12 +873,12 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinatio log.LogTypeKey = EventLogController.EventLogType.FOLDER_MOVED.ToString(); LogController.Instance.AddLog(log); - //Files in cache are obsolete because their physical path is not correct after moving - DeleteFilesFromCache(folder.PortalID, newFolderPath); - var movedFolder = GetFolder(folder.FolderID); + // Files in cache are obsolete because their physical path is not correct after moving + this.DeleteFilesFromCache(folder.PortalID, newFolderPath); + var movedFolder = this.GetFolder(folder.FolderID); // Notify folder moved event - OnFolderMoved(folder, GetCurrentUserId(), currentFolderPath); + this.OnFolderMoved(folder, this.GetCurrentUserId(), currentFolderPath); return movedFolder; } @@ -890,40 +896,43 @@ public virtual void RenameFolder(IFolderInfo folder, string newFolderName) Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("newFolderName", newFolderName); - if (folder.FolderName.Equals(newFolderName)) return; - + if (folder.FolderName.Equals(newFolderName)) + { + return; + } + var currentFolderName = folder.FolderName; var newFolderPath = folder.FolderPath.Substring(0, folder.FolderPath.LastIndexOf(folder.FolderName, StringComparison.Ordinal)) + PathUtils.Instance.FormatFolderPath(newFolderName); - if (FolderExists(folder.PortalID, newFolderPath)) + if (this.FolderExists(folder.PortalID, newFolderPath)) { - throw new FolderAlreadyExistsException(Localization.Localization.GetExceptionMessage("RenameFolderAlreadyExists", "The destination folder already exists. The folder has not been renamed.")); + throw new FolderAlreadyExistsException(Localization.GetExceptionMessage("RenameFolderAlreadyExists", "The destination folder already exists. The folder has not been renamed.")); } var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); var provider = FolderProvider.Instance(folderMapping.FolderProviderType); - RenameFolderInFileSystem(folder, newFolderPath); + this.RenameFolderInFileSystem(folder, newFolderPath); - //Update Provider + // Update Provider provider.RenameFolder(folder, newFolderName); - //Update database - UpdateChildFolders(folder, newFolderPath); + // Update database + this.UpdateChildFolders(folder, newFolderPath); - //Files in cache are obsolete because their physical path is not correct after rename - DeleteFilesFromCache(folder.PortalID, newFolderPath); + // Files in cache are obsolete because their physical path is not correct after rename + this.DeleteFilesFromCache(folder.PortalID, newFolderPath); // Notify folder renamed event - OnFolderRenamed(folder, GetCurrentUserId(), currentFolderName); + this.OnFolderRenamed(folder, this.GetCurrentUserId(), currentFolderName); } /// - /// Search the files contained in the specified folder, for a matching pattern + /// Search the files contained in the specified folder, for a matching pattern. /// /// The folder from which to retrieve the files. - /// The patter to search for + /// The patter to search for. /// The list of files contained in the specified folder. public virtual IEnumerable SearchFiles(IFolderInfo folder, string pattern, bool recursive) { @@ -934,7 +943,7 @@ public virtual IEnumerable SearchFiles(IFolderInfo folder, string pat throw new FolderProviderException("No permission to view the folder"); } - return SearchFiles(folder, WildcardToRegex(pattern), recursive); + return this.SearchFiles(folder, WildcardToRegex(pattern), recursive); } /// @@ -944,7 +953,7 @@ public virtual IEnumerable SearchFiles(IFolderInfo folder, string pat /// The number of folder collisions. public virtual int Synchronize(int portalId) { - var folderCollisions = Synchronize(portalId, "", true, true); + var folderCollisions = this.Synchronize(portalId, string.Empty, true, true); DataCache.ClearFolderCache(portalId); @@ -959,7 +968,7 @@ public virtual int Synchronize(int portalId) /// The number of folder collisions. public virtual int Synchronize(int portalId, string relativePath) { - return Synchronize(portalId, relativePath, true, true); + return this.Synchronize(portalId, relativePath, true, true); } /// @@ -975,9 +984,9 @@ public virtual int Synchronize(int portalId, string relativePath, bool isRecursi { Requires.PropertyNotNull("relativePath", relativePath); - if (AreThereFolderMappingsRequiringNetworkConnectivity(portalId, relativePath, isRecursive) && !IsNetworkAvailable()) + if (this.AreThereFolderMappingsRequiringNetworkConnectivity(portalId, relativePath, isRecursive) && !this.IsNetworkAvailable()) { - throw new NoNetworkAvailableException(Localization.Localization.GetExceptionMessage("NoNetworkAvailableError", "Network connectivity is needed but there is no network available.")); + throw new NoNetworkAvailableException(Localization.GetExceptionMessage("NoNetworkAvailableError", "Network connectivity is needed but there is no network available.")); } int? scriptTimeOut = null; @@ -987,22 +996,23 @@ public virtual int Synchronize(int portalId, string relativePath, bool isRecursi { if (HttpContext.Current != null) { - scriptTimeOut = GetCurrentScriptTimeout(); + scriptTimeOut = this.GetCurrentScriptTimeout(); // Synchronization could be a time-consuming process. To not get a time-out, we need to modify the request time-out value - SetScriptTimeout(int.MaxValue); + this.SetScriptTimeout(int.MaxValue); } - var mergedTree = GetMergedTree(portalId, relativePath, isRecursive); + var mergedTree = this.GetMergedTree(portalId, relativePath, isRecursive); // Step 1: Add Folders - InitialiseSyncFoldersData(portalId, relativePath); + this.InitialiseSyncFoldersData(portalId, relativePath); for (var i = 0; i < mergedTree.Count; i++) { var item = mergedTree.Values[i]; - ProcessMergedTreeItemInAddMode(item, portalId); + this.ProcessMergedTreeItemInAddMode(item, portalId); } - RemoveSyncFoldersData(relativePath); + + this.RemoveSyncFoldersData(relativePath); // Step 2: Delete Files and Folders for (var i = mergedTree.Count - 1; i >= 0; i--) @@ -1011,10 +1021,10 @@ public virtual int Synchronize(int portalId, string relativePath, bool isRecursi if (syncFiles) { - SynchronizeFiles(item, portalId); + this.SynchronizeFiles(item, portalId); } - ProcessMergedTreeItemInDeleteMode(item, portalId); + this.ProcessMergedTreeItemInDeleteMode(item, portalId); } } finally @@ -1024,33 +1034,30 @@ public virtual int Synchronize(int portalId, string relativePath, bool isRecursi // Restore original time-out if (HttpContext.Current != null && scriptTimeOut != null) { - SetScriptTimeout(scriptTimeOut.Value); + this.SetScriptTimeout(scriptTimeOut.Value); } } return 0; } - + /// /// Updates metadata of the specified folder. /// /// The folder to update. - /// Thrown when folder is null. + /// Thrown when folder is null. + /// public virtual IFolderInfo UpdateFolder(IFolderInfo folder) { - var updatedFolder = UpdateFolderInternal(folder, true); + var updatedFolder = this.UpdateFolderInternal(folder, true); - AddLogEntry(updatedFolder, EventLogController.EventLogType.FOLDER_UPDATED); - - SaveFolderPermissions(updatedFolder); + this.AddLogEntry(updatedFolder, EventLogController.EventLogType.FOLDER_UPDATED); - return updatedFolder; - } - - #endregion - - #region Permission Methods + this.SaveFolderPermissions(updatedFolder); + return updatedFolder; + } + /// /// Adds read permissions for all users to the specified folder. /// @@ -1058,7 +1065,7 @@ public virtual IFolderInfo UpdateFolder(IFolderInfo folder) /// Used as base class for FolderPermissionInfo when there is no read permission already defined. public virtual void AddAllUserReadPermission(IFolderInfo folder, PermissionInfo permission) { - var roleId = Int32.Parse(Globals.glbRoleAllUsers); + var roleId = int.Parse(Globals.glbRoleAllUsers); var folderPermission = (from FolderPermissionInfo p in folder.FolderPermissions @@ -1076,7 +1083,7 @@ public virtual void AddAllUserReadPermission(IFolderInfo folder, PermissionInfo FolderID = folder.FolderID, UserID = Null.NullInteger, RoleID = roleId, - AllowAccess = true + AllowAccess = true, }; folder.FolderPermissions.Add(folderPermission); @@ -1086,24 +1093,27 @@ public virtual void AddAllUserReadPermission(IFolderInfo folder, PermissionInfo /// /// Sets folder permissions to the given folder by copying parent folder permissions. /// - /// The folder to copy permissions to + /// The folder to copy permissions to. public virtual void CopyParentFolderPermissions(IFolderInfo folder) { Requires.NotNull("folder", folder); - if (String.IsNullOrEmpty(folder.FolderPath)) return; - + if (string.IsNullOrEmpty(folder.FolderPath)) + { + return; + } + var parentFolderPath = folder.FolderPath.Substring(0, folder.FolderPath.Substring(0, folder.FolderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); foreach (FolderPermissionInfo objPermission in - GetFolderPermissionsFromSyncData(folder.PortalID, parentFolderPath)) + this.GetFolderPermissionsFromSyncData(folder.PortalID, parentFolderPath)) { var folderPermission = new FolderPermissionInfo(objPermission) { FolderID = folder.FolderID, RoleID = objPermission.RoleID, UserID = objPermission.UserID, - AllowAccess = objPermission.AllowAccess + AllowAccess = objPermission.AllowAccess, }; folder.FolderPermissions.Add(folderPermission, true); } @@ -1111,44 +1121,24 @@ public virtual void CopyParentFolderPermissions(IFolderInfo folder) FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } - private FolderPermissionCollection GetFolderPermissionsFromSyncData(int portalId, string relativePath) - { - var threadId = Thread.CurrentThread.ManagedThreadId; - FolderPermissionCollection permissions = null; - if (SyncFoldersData.ContainsKey(threadId)) - { - if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) - { - return SyncFoldersData[threadId].Permissions; - } - permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); - SyncFoldersData[threadId] = new SyncFolderData {PortalId = portalId, FolderPath = relativePath, Permissions = permissions}; - return permissions; - } - permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); - SyncFoldersData.Add(threadId, new SyncFolderData{ PortalId = portalId, FolderPath = relativePath, Permissions = permissions}); - - return permissions; - } - /// - /// Sets specific folder permissions for the given role to the given folder. + /// Sets specific folder permissions for the given role to the given folder. /// - /// The folder to set permission to - /// The id of the permission to assign - /// The role to assign the permission to + /// The folder to set permission to. + /// The id of the permission to assign. + /// The role to assign the permission to. public virtual void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId) { - SetFolderPermission(folder, permissionId, roleId, Null.NullInteger); + this.SetFolderPermission(folder, permissionId, roleId, Null.NullInteger); } /// /// Sets specific folder permissions for the given role/user to the given folder. /// - /// The folder to set permission to - /// The id of the permission to assign - /// The role to assign the permission to - /// The user to assign the permission to + /// The folder to set permission to. + /// The id of the permission to assign. + /// The role to assign the permission to. + /// The user to assign the permission to. public virtual void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId, int userId) { if (folder.FolderPermissions.Cast() @@ -1163,18 +1153,40 @@ public virtual void SetFolderPermission(IFolderInfo folder, int permissionId, in PermissionID = permissionId, RoleID = roleId, UserID = userId, - AllowAccess = true + AllowAccess = true, }; folder.FolderPermissions.Add(objFolderPermissionInfo, true); FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } + private FolderPermissionCollection GetFolderPermissionsFromSyncData(int portalId, string relativePath) + { + var threadId = Thread.CurrentThread.ManagedThreadId; + FolderPermissionCollection permissions = null; + if (SyncFoldersData.ContainsKey(threadId)) + { + if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) + { + return SyncFoldersData[threadId].Permissions; + } + + permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; + return permissions; + } + + permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); + + return permissions; + } + /// /// Sets folder permissions for administrator role to the given folder. /// - /// The folder to set permission to - /// The administrator role id to assign the permission to + /// The folder to set permission to. + /// The administrator role id to assign the permission to. public virtual void SetFolderPermissions(IFolderInfo folder, int administratorRoleId) { Requires.NotNull("folder", folder); @@ -1184,84 +1196,105 @@ public virtual void SetFolderPermissions(IFolderInfo folder, int administratorRo var folderPermission = new FolderPermissionInfo(objPermission) { FolderID = folder.FolderID, - RoleID = administratorRoleId + RoleID = administratorRoleId, }; folder.FolderPermissions.Add(folderPermission, true); } FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); - } - - #endregion + } + + /// + /// Moves the specified folder and its contents to a new location. + /// + /// The folder to move. + /// The new folder path. + /// The moved folder. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in DNN 7.1. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) . Scheduled removal in v10.0.0.")] + public virtual IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath) + { + Requires.NotNull("folder", folder); + Requires.NotNullOrEmpty("newFolderPath", newFolderPath); - #region Internal Methods + var nameCharIndex = newFolderPath.Substring(0, newFolderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1; + var parentFolder = this.GetFolder(folder.PortalID, newFolderPath.Substring(0, nameCharIndex)); + if (parentFolder.FolderID == folder.ParentID) + { + var newFolderName = newFolderPath.Substring(nameCharIndex, newFolderPath.Length - nameCharIndex - 1); + this.RenameFolder(folder, newFolderName); + return folder; + } + return this.MoveFolder(folder, parentFolder); + } + internal virtual void AddLogEntry(IFolderInfo folder, EventLogController.EventLogType eventLogType) { - EventLogController.Instance.AddLog(folder, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserId(), "", eventLogType); + EventLogController.Instance.AddLog(folder, PortalController.Instance.GetCurrentPortalSettings(), this.GetCurrentUserId(), string.Empty, eventLogType); } internal virtual void AddLogEntry(string propertyName, string propertyValue, EventLogController.EventLogType eventLogType) { - EventLogController.Instance.AddLog(propertyName, propertyValue, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserId(), eventLogType); + EventLogController.Instance.AddLog(propertyName, propertyValue, PortalController.Instance.GetCurrentPortalSettings(), this.GetCurrentUserId(), eventLogType); } /// This member is reserved for internal use and is not intended to be used directly from your code. internal void DeleteFilesFromCache(int portalId, string newFolderPath) { - var folders = GetFolders(portalId).Where(f => f.FolderPath.StartsWith(newFolderPath)); + var folders = this.GetFolders(portalId).Where(f => f.FolderPath.StartsWith(newFolderPath)); foreach (var folderInfo in folders) { - var fileIds = GetFiles(folderInfo).Select(f => f.FileId); + var fileIds = this.GetFiles(folderInfo).Select(f => f.FileId); foreach (var fileId in fileIds) { DataCache.RemoveCache("GetFileById" + fileId); - } - } - } - - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + } + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual IFolderInfo AddUserFolder(UserInfo user) { - //user _default portal for all super users + // user _default portal for all super users var portalId = user.IsSuperUser ? Null.NullInteger : user.PortalID; var folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, DefaultUsersFoldersPath) ?? FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - if (!FolderExists(portalId, DefaultUsersFoldersPath)) + if (!this.FolderExists(portalId, DefaultUsersFoldersPath)) { - AddFolder(folderMapping, DefaultUsersFoldersPath); + this.AddFolder(folderMapping, DefaultUsersFoldersPath); } #pragma warning disable 612,618 var rootFolder = PathUtils.Instance.GetUserFolderPathElement(user.UserID, PathUtils.UserFolderElement.Root); #pragma warning restore 612,618 - var folderPath = PathUtils.Instance.FormatFolderPath(String.Format(DefaultUsersFoldersPath + "/{0}", rootFolder)); + var folderPath = PathUtils.Instance.FormatFolderPath(string.Format(DefaultUsersFoldersPath + "/{0}", rootFolder)); - if (!FolderExists(portalId, folderPath)) + if (!this.FolderExists(portalId, folderPath)) { - AddFolder(folderMapping, folderPath); + this.AddFolder(folderMapping, folderPath); } #pragma warning disable 612,618 - folderPath = PathUtils.Instance.FormatFolderPath(String.Concat(folderPath, PathUtils.Instance.GetUserFolderPathElement(user.UserID, PathUtils.UserFolderElement.SubFolder))); + folderPath = PathUtils.Instance.FormatFolderPath(string.Concat(folderPath, PathUtils.Instance.GetUserFolderPathElement(user.UserID, PathUtils.UserFolderElement.SubFolder))); #pragma warning restore 612,618 - if (!FolderExists(portalId, folderPath)) + if (!this.FolderExists(portalId, folderPath)) { - AddFolder(folderMapping, folderPath); + this.AddFolder(folderMapping, folderPath); } - folderPath = PathUtils.Instance.FormatFolderPath(String.Concat(folderPath, user.UserID.ToString(CultureInfo.InvariantCulture))); + folderPath = PathUtils.Instance.FormatFolderPath(string.Concat(folderPath, user.UserID.ToString(CultureInfo.InvariantCulture))); - if (!FolderExists(portalId, folderPath)) + if (!this.FolderExists(portalId, folderPath)) { - AddFolder(folderMapping, folderPath); + this.AddFolder(folderMapping, folderPath); - var folder = GetFolder(portalId, folderPath); + var folder = this.GetFolder(portalId, folderPath); foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) { @@ -1271,15 +1304,15 @@ internal virtual IFolderInfo AddUserFolder(UserInfo user) { FolderID = folder.FolderID, UserID = user.UserID, - RoleID = Int32.Parse(Globals.glbRoleNothing), - AllowAccess = true + RoleID = int.Parse(Globals.glbRoleNothing), + AllowAccess = true, }; folder.FolderPermissions.Add(folderPermission); if (permission.PermissionKey.Equals("READ", StringComparison.InvariantCultureIgnoreCase)) { - AddAllUserReadPermission(folder, permission); + this.AddAllUserReadPermission(folder, permission); } } } @@ -1287,13 +1320,14 @@ internal virtual IFolderInfo AddUserFolder(UserInfo user) FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } - return GetFolder(portalId, folderPath); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + return this.GetFolder(portalId, folderPath); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool AreThereFolderMappingsRequiringNetworkConnectivity(int portalId, string relativePath, bool isRecursive) { - var folder = GetFolder(portalId, relativePath); + var folder = this.GetFolder(portalId, relativePath); if (folder != null) { @@ -1347,10 +1381,11 @@ internal virtual void ClearFolderCache(int portalId) internal virtual int CreateFolderInDatabase(int portalId, string folderPath, int folderMappingId) { - return CreateFolderInDatabase(portalId, folderPath, folderMappingId, folderPath); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + return this.CreateFolderInDatabase(portalId, folderPath, folderMappingId, folderPath); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual int CreateFolderInDatabase(int portalId, string folderPath, int folderMappingId, string mappedPath) { var isProtected = PathUtils.Instance.IsDefaultProtectedPath(folderPath); @@ -1371,24 +1406,25 @@ internal virtual int CreateFolderInDatabase(int portalId, string folderPath, int break; } } - var folder = new FolderInfo(true) - { - PortalID = portalId, - FolderPath = folderPath, - MappedPath = mappedPath, - StorageLocation = storageLocation, - IsProtected = isProtected, - IsCached = false, - FolderMappingID = folderMappingId, - LastUpdated = Null.NullDate - }; + + var folder = new FolderInfo(true) + { + PortalID = portalId, + FolderPath = folderPath, + MappedPath = mappedPath, + StorageLocation = storageLocation, + IsProtected = isProtected, + IsCached = false, + FolderMappingID = folderMappingId, + LastUpdated = Null.NullDate, + }; - folder.FolderID = AddFolderInternal(folder); + folder.FolderID = this.AddFolderInternal(folder); if (portalId != Null.NullInteger) { - //Set Folder Permissions to inherit from parent - CopyParentFolderPermissions(folder); + // Set Folder Permissions to inherit from parent + this.CopyParentFolderPermissions(folder); } return folder.FolderID; @@ -1409,8 +1445,8 @@ internal virtual void CreateFolderInFileSystem(string physicalPath) internal virtual void DeleteFolder(int portalId, string folderPath) { DataProvider.Instance().DeleteFolder(portalId, PathUtils.Instance.FormatFolderPath(folderPath)); - AddLogEntry("FolderPath", folderPath, EventLogController.EventLogType.FOLDER_DELETED); - UpdateParentFolder(portalId, folderPath); + this.AddLogEntry("FolderPath", folderPath, EventLogController.EventLogType.FOLDER_DELETED); + this.UpdateParentFolder(portalId, folderPath); DataCache.ClearFolderCache(portalId); } @@ -1420,7 +1456,7 @@ internal virtual void DeleteFoldersFromExternalStorageLocations(DictionaryThis member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual int GetCurrentScriptTimeout() { return HttpContext.Current.Server.ScriptTimeout; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual int GetCurrentUserId() { return UserController.Instance.GetCurrentUserInfo().UserID; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual SortedList GetDatabaseFolders(int portalId, string relativePath, bool isRecursive) { var databaseFolders = new SortedList(new IgnoreCaseStringComparer()); - var folder = GetFolder(portalId, relativePath); + var folder = this.GetFolder(portalId, relativePath); if (folder != null) { @@ -1469,21 +1508,22 @@ internal virtual SortedList GetDatabaseFolders(int porta FolderMappingID = folder.FolderMappingID, FolderPath = folder.FolderPath, ExistsInDatabase = true, - MappedPath = folder.MappedPath + MappedPath = folder.MappedPath, }; databaseFolders.Add(relativePath, item); } else { - databaseFolders = GetDatabaseFoldersRecursive(folder); + databaseFolders = this.GetDatabaseFoldersRecursive(folder); } } return databaseFolders; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual SortedList GetDatabaseFoldersRecursive(IFolderInfo folder) { var result = new SortedList(new IgnoreCaseStringComparer()); @@ -1495,30 +1535,31 @@ internal virtual SortedList GetDatabaseFoldersRecursive( { var folderInfo = stack.Pop(); - var item = new MergedTreeItem - { - FolderID = folderInfo.FolderID, - FolderMappingID = folderInfo.FolderMappingID, - FolderPath = folderInfo.FolderPath, - ExistsInDatabase = true, - MappedPath = folderInfo.MappedPath - }; + var item = new MergedTreeItem + { + FolderID = folderInfo.FolderID, + FolderMappingID = folderInfo.FolderMappingID, + FolderPath = folderInfo.FolderPath, + ExistsInDatabase = true, + MappedPath = folderInfo.MappedPath, + }; if (!result.ContainsKey(item.FolderPath)) { result.Add(item.FolderPath, item); } - foreach (var subfolder in GetFolders(folderInfo)) + foreach (var subfolder in this.GetFolders(folderInfo)) { stack.Push(subfolder); } } return result; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual SortedList GetFileSystemFolders(int portalId, string relativePath, bool isRecursive) { var fileSystemFolders = new SortedList(new IgnoreCaseStringComparer()); @@ -1541,21 +1582,22 @@ internal virtual SortedList GetFileSystemFolders(int por FolderMappingID = -1, FolderPath = relativePath, ExistsInFileSystem = true, - MappedPath = String.Empty + MappedPath = string.Empty, }; fileSystemFolders.Add(relativePath, item); } else { - fileSystemFolders = GetFileSystemFoldersRecursive(portalId, physicalPath); + fileSystemFolders = this.GetFileSystemFoldersRecursive(portalId, physicalPath); } } return fileSystemFolders; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual SortedList GetFileSystemFoldersRecursive(int portalId, string physicalPath) { var result = new SortedList(new IgnoreCaseStringComparer()); @@ -1577,7 +1619,7 @@ internal virtual SortedList GetFileSystemFoldersRecursiv FolderMappingID = -1, FolderPath = PathUtils.Instance.GetRelativePath(portalId, dir), ExistsInFileSystem = true, - MappedPath = String.Empty + MappedPath = string.Empty, }; result.Add(item.FolderPath, item); @@ -1599,9 +1641,10 @@ internal virtual SortedList GetFileSystemFoldersRecursiv } return result; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual FolderMappingInfo GetFolderMapping(Dictionary folderMappings, int folderMappingId) { if (!folderMappings.ContainsKey(folderMappingId)) @@ -1610,9 +1653,10 @@ internal virtual FolderMappingInfo GetFolderMapping(DictionaryThis member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual SortedList GetFolderMappingFoldersRecursive(FolderMappingInfo folderMapping, IFolderInfo folder) { var result = new SortedList(new IgnoreCaseStringComparer()); @@ -1627,9 +1671,9 @@ internal virtual SortedList GetFolderMappingFoldersRecur while (stack.Count > 0) { var mappedPath = stack.Pop(); - var relativePath = (String.IsNullOrEmpty(mappedPath)) - ? String.Empty - : (String.IsNullOrEmpty(baseMappedPath)) + var relativePath = string.IsNullOrEmpty(mappedPath) + ? string.Empty + : string.IsNullOrEmpty(baseMappedPath) ? mappedPath : RegexUtils.GetCachedRegex(Regex.Escape(baseMappedPath)).Replace(mappedPath, string.Empty, 1); @@ -1643,7 +1687,7 @@ internal virtual SortedList GetFolderMappingFoldersRecur FolderMappingID = folderMapping.FolderMappingID, FolderPath = folderPath, ExistsInFolderMapping = true, - MappedPath = mappedPath + MappedPath = mappedPath, }; if (!result.ContainsKey(item.FolderPath)) @@ -1662,43 +1706,49 @@ internal virtual SortedList GetFolderMappingFoldersRecur } return result; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual object GetFoldersByPermissionSortedCallBack(CacheItemArgs cacheItemArgs) { var portalId = (int)cacheItemArgs.ParamList[0]; var permissions = (string)cacheItemArgs.ParamList[1]; var userId = (int)cacheItemArgs.ParamList[2]; return CBO.Instance.FillCollection(DataProvider.Instance().GetFoldersByPortalAndPermissions(portalId, permissions, userId)); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual object GetFoldersSortedCallBack(CacheItemArgs cacheItemArgs) { var portalId = (int)cacheItemArgs.ParamList[0]; return CBO.Instance.FillCollection(DataProvider.Instance().GetFoldersByPortal(portalId)); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual SortedList GetMergedTree(int portalId, string relativePath, bool isRecursive) { - var fileSystemFolders = GetFileSystemFolders(portalId, relativePath, isRecursive); - var databaseFolders = GetDatabaseFolders(portalId, relativePath, isRecursive); + var fileSystemFolders = this.GetFileSystemFolders(portalId, relativePath, isRecursive); + var databaseFolders = this.GetDatabaseFolders(portalId, relativePath, isRecursive); - var mergedTree = MergeFolderLists(fileSystemFolders, databaseFolders); + var mergedTree = this.MergeFolderLists(fileSystemFolders, databaseFolders); var mappedFolders = new SortedList(); - //Some providers cache the list of objects for performance - ClearFolderProviderCachedLists(portalId); + // Some providers cache the list of objects for performance + this.ClearFolderProviderCachedLists(portalId); foreach (var mergedItem in mergedTree.Values) { - if (mergedItem.FolderMappingID == Null.NullInteger) continue; - + if (mergedItem.FolderMappingID == Null.NullInteger) + { + continue; + } + var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, mergedItem.FolderMappingID); - //Add any folders from non-core providers + // Add any folders from non-core providers if (folderMapping.MappingName != "Standard" && folderMapping.MappingName != "Secure" && folderMapping.MappingName != "Database") { if (!isRecursive) @@ -1707,8 +1757,8 @@ internal virtual SortedList GetMergedTree(int portalId, } else { - var folder = GetFolder(portalId, mergedItem.FolderPath); - mappedFolders = MergeFolderLists(mappedFolders, GetFolderMappingFoldersRecursive(folderMapping, folder)); + var folder = this.GetFolder(portalId, mergedItem.FolderPath); + mappedFolders = this.MergeFolderLists(mappedFolders, this.GetFolderMappingFoldersRecursive(folderMapping, folder)); } } else @@ -1717,48 +1767,52 @@ internal virtual SortedList GetMergedTree(int portalId, } } - mergedTree = MergeFolderLists(mergedTree, mappedFolders); + mergedTree = this.MergeFolderLists(mergedTree, mappedFolders); // Update ExistsInFolderMapping if the Parent Does Not ExistsInFolderMapping var margedTreeItems = mergedTree.Values; - foreach (var mergedItem in margedTreeItems.Where(m => m.ExistsInFolderMapping + foreach (var mergedItem in margedTreeItems.Where(m => m.ExistsInFolderMapping && margedTreeItems.Any(mt2 => !mt2.ExistsInFolderMapping && m.FolderPath.StartsWith(mt2.FolderPath)))) { mergedItem.ExistsInFolderMapping = false; } return mergedTree; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool IsFolderMappingEditable(FolderMappingInfo folderMapping) { return folderMapping.IsEditable; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, IFolderInfo destinationFolder, string newFolderPath) { - //FolderMapping cases + // FolderMapping cases var folderMapping = FolderMappingController.Instance.GetFolderMapping(folderToMove.PortalID, folderToMove.FolderMappingID); if (folderToMove.FolderMappingID == destinationFolder.FolderMappingID && FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) { - //Root mapped folder cannot be move, when folder mappings are equal + // Root mapped folder cannot be move, when folder mappings are equal if (folderToMove.MappedPath == string.Empty) { return false; } - //Destination folder cannot be a child mapped folder from the folder to move + // Destination folder cannot be a child mapped folder from the folder to move if (destinationFolder.MappedPath.StartsWith(folderToMove.MappedPath)) { return false; } } - return IsMoveOperationValid(folderToMove, newFolderPath); - } - /// This member is reserved for internal use and is not intended to be used directly from your code. + return this.IsMoveOperationValid(folderToMove, newFolderPath); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, string newFolderPath) { // Root folder cannot be moved @@ -1774,15 +1828,17 @@ internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, string newF } return true; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool IsNetworkAvailable() { return NetworkInterface.GetIsNetworkAvailable(); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual SortedList MergeFolderLists(SortedList list1, SortedList list2) { foreach (var item in list2.Values) @@ -1794,11 +1850,13 @@ internal virtual SortedList MergeFolderLists(SortedList< { existingItem.FolderID = item.FolderID; } + if (existingItem.FolderMappingID < 0) { existingItem.FolderMappingID = item.FolderMappingID; } - if (String.IsNullOrEmpty(existingItem.MappedPath)) + + if (string.IsNullOrEmpty(existingItem.MappedPath)) { existingItem.MappedPath = item.MappedPath; } @@ -1830,7 +1888,11 @@ internal virtual void MoveDirectory(string source, string target) foreach (var file in Directory.GetFiles(folders.Source, "*.*")) { var targetFile = Path.Combine(folders.Target, Path.GetFileName(file)); - if (File.Exists(targetFile)) File.Delete(targetFile); + if (File.Exists(targetFile)) + { + File.Delete(targetFile); + } + File.Move(file, targetFile); } @@ -1839,42 +1901,43 @@ internal virtual void MoveDirectory(string source, string target) stack.Push(new MoveFoldersInfo(folder, Path.Combine(folders.Target, Path.GetFileName(folder)))); } } + // ReSharper restore AssignNullToNotNullAttribute Directory.Delete(source, true); } /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void MoveFolderWithinProvider(IFolderInfo folder, IFolderInfo destinationFolder) - { + { var newFolderPath = destinationFolder.FolderPath + folder.FolderName + "/"; - RenameFolderInFileSystem(folder, newFolderPath); + this.RenameFolderInFileSystem(folder, newFolderPath); - //Update provider + // Update provider var newMappedPath = destinationFolder.MappedPath + folder.FolderName + "/"; var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); var provider = FolderProvider.Instance(folderMapping.FolderProviderType); provider.MoveFolder(folder.MappedPath, newMappedPath, folderMapping); - //Update database - UpdateChildFolders(folder, Path.Combine(destinationFolder.FolderPath, folder.FolderName)); + // Update database + this.UpdateChildFolders(folder, Path.Combine(destinationFolder.FolderPath, folder.FolderName)); } /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void MoveFolderBetweenProviders(IFolderInfo folder, string newFolderPath) { - RenameFolderInFileSystem(folder, newFolderPath); + this.RenameFolderInFileSystem(folder, newFolderPath); - var folderInfos = GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(folder.FolderPath)).ToArray(); + var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(folder.FolderPath)).ToArray(); var tmpFolderPath = folder.FolderPath; foreach (var folderInfo in folderInfos) { var folderPath = newFolderPath + folderInfo.FolderPath.Substring(tmpFolderPath.Length); - - var parentFolder = GetParentFolder(folder.PortalID, folderPath); + + var parentFolder = this.GetParentFolder(folder.PortalID, folderPath); folderInfo.ParentID = parentFolder.FolderID; folderInfo.FolderPath = folderPath; - UpdateFolderInternal(folderInfo, true); + this.UpdateFolderInternal(folderInfo, true); } } @@ -1882,7 +1945,7 @@ internal virtual void MoveFolderBetweenProviders(IFolderInfo folder, string newF internal virtual void OverwriteFolder(IFolderInfo sourceFolder, IFolderInfo destinationFolder, Dictionary folderMappings, SortedList foldersToDelete) { var fileManager = FileManager.Instance; - var files = GetFiles(sourceFolder, true); + var files = this.GetFiles(sourceFolder, true); foreach (var file in files) { @@ -1890,16 +1953,16 @@ internal virtual void OverwriteFolder(IFolderInfo sourceFolder, IFolderInfo dest } // Delete source folder in database - DeleteFolder(sourceFolder.PortalID, sourceFolder.FolderPath); + this.DeleteFolder(sourceFolder.PortalID, sourceFolder.FolderPath); - var folderMapping = GetFolderMapping(folderMappings, sourceFolder.FolderMappingID); + var folderMapping = this.GetFolderMapping(folderMappings, sourceFolder.FolderMappingID); - if (IsFolderMappingEditable(folderMapping)) + if (this.IsFolderMappingEditable(folderMapping)) { foldersToDelete.Add(sourceFolder.FolderPath, sourceFolder); } } - + /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void ProcessMergedTreeItemInAddMode(MergedTreeItem item, int portalId) { @@ -1909,8 +1972,8 @@ internal virtual void ProcessMergedTreeItemInAddMode(MergedTreeItem item, int po { if (!item.ExistsInDatabase) { - var folderMappingId = FindFolderMappingId(item, portalId); - CreateFolderInDatabase(portalId, item.FolderPath, folderMappingId); + var folderMappingId = this.FindFolderMappingId(item, portalId); + this.CreateFolderInDatabase(portalId, item.FolderPath, folderMappingId); } } else @@ -1919,13 +1982,13 @@ internal virtual void ProcessMergedTreeItemInAddMode(MergedTreeItem item, int po { if (item.ExistsInFolderMapping) { - CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); + this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); } } else // by exclusion it exists in the Folder Mapping { - CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); - CreateFolderInDatabase(portalId, item.FolderPath, item.FolderMappingID, item.MappedPath); + this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); + this.CreateFolderInDatabase(portalId, item.FolderPath, item.FolderMappingID, item.MappedPath); } } } @@ -1934,35 +1997,6 @@ internal virtual void ProcessMergedTreeItemInAddMode(MergedTreeItem item, int po Logger.Error(string.Format("Could not create folder {0}. EXCEPTION: {1}", item.FolderPath, ex.Message), ex); } } - private void InitialiseSyncFoldersData(int portalId, string relativePath) - { - var threadId = Thread.CurrentThread.ManagedThreadId; - var permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); - if (SyncFoldersData.ContainsKey(threadId)) - { - if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) - { - SyncFoldersData[threadId].Permissions = permissions; - } - else - { - SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; - } - } - else - { - SyncFoldersData.Add(threadId, new SyncFolderData{ PortalId = portalId, FolderPath = relativePath, Permissions = permissions}); - } - } - - private void RemoveSyncFoldersData(string relativePath) - { - var threadId = Thread.CurrentThread.ManagedThreadId; - if (SyncFoldersData.ContainsKey(threadId)) - { - SyncFoldersData.Remove(threadId); - } - } /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void ProcessMergedTreeItemInDeleteMode(MergedTreeItem item, int portalId) @@ -1971,8 +2005,11 @@ internal virtual void ProcessMergedTreeItemInDeleteMode(MergedTreeItem item, int { if (item.ExistsInDatabase) { - if (item.FolderPath == "") return; // Do not process root folder - + if (item.FolderPath == string.Empty) + { + return; // Do not process root folder + } + if (!item.ExistsInFolderMapping) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, item.FolderMappingID); @@ -1980,7 +2017,7 @@ internal virtual void ProcessMergedTreeItemInDeleteMode(MergedTreeItem item, int if (folderMapping.IsEditable) { DirectoryWrapper.Instance.Delete(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath), false); - DeleteFolder(portalId, item.FolderPath); + this.DeleteFolder(portalId, item.FolderPath); } } } @@ -1989,7 +2026,7 @@ internal virtual void ProcessMergedTreeItemInDeleteMode(MergedTreeItem item, int { if (item.ExistsInDatabase && !item.ExistsInFolderMapping) { - DeleteFolder(portalId, item.FolderPath); + this.DeleteFolder(portalId, item.FolderPath); } } } @@ -1997,7 +2034,7 @@ internal virtual void ProcessMergedTreeItemInDeleteMode(MergedTreeItem item, int /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void RemoveOrphanedFiles(IFolderInfo folder) { - var files = GetFiles(folder, false, true); + var files = this.GetFiles(folder, false, true); var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); @@ -2021,6 +2058,36 @@ internal virtual void RemoveOrphanedFiles(IFolderInfo folder) } } } + + private void InitialiseSyncFoldersData(int portalId, string relativePath) + { + var threadId = Thread.CurrentThread.ManagedThreadId; + var permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + if (SyncFoldersData.ContainsKey(threadId)) + { + if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) + { + SyncFoldersData[threadId].Permissions = permissions; + } + else + { + SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; + } + } + else + { + SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); + } + } + + private void RemoveSyncFoldersData(string relativePath) + { + var threadId = Thread.CurrentThread.ManagedThreadId; + if (SyncFoldersData.ContainsKey(threadId)) + { + SyncFoldersData.Remove(threadId); + } + } /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void RenameFolderInFileSystem(IFolderInfo folder, string newFolderPath) @@ -2028,10 +2095,13 @@ internal virtual void RenameFolderInFileSystem(IFolderInfo folder, string newFol var source = folder.PhysicalPath; var di = new DirectoryInfo(source); - if (!di.Exists) return; - + if (!di.Exists) + { + return; + } + var target = PathUtils.Instance.GetPhysicalPath(folder.PortalID, newFolderPath); - MoveDirectory(source, target); + this.MoveDirectory(source, target); } /// This member is reserved for internal use and is not intended to be used directly from your code. @@ -2049,7 +2119,7 @@ internal virtual void SetScriptTimeout(int timeout) /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void SynchronizeFiles(MergedTreeItem item, int portalId) { - var folder = GetFolder(portalId, item.FolderPath); + var folder = this.GetFolder(portalId, item.FolderPath); if (folder == null) { @@ -2100,7 +2170,7 @@ internal virtual void SynchronizeFiles(MergedTreeItem item, int portalId) } } - RemoveOrphanedFiles(folder); + this.RemoveOrphanedFiles(folder); } catch (Exception ex) { @@ -2111,14 +2181,14 @@ internal virtual void SynchronizeFiles(MergedTreeItem item, int portalId) /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void UpdateParentFolder(int portalId, string folderPath) { - if (!String.IsNullOrEmpty(folderPath)) + if (!string.IsNullOrEmpty(folderPath)) { var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); - var objFolder = GetFolder(portalId, parentFolderPath); + var objFolder = this.GetFolder(portalId, parentFolderPath); if (objFolder != null) { - //UpdateFolder(objFolder); - UpdateFolderInternal(objFolder, false); + // UpdateFolder(objFolder); + this.UpdateFolderInternal(objFolder, false); } } } @@ -2128,16 +2198,16 @@ internal virtual void UpdateChildFolders(IFolderInfo folder, string newFolderPat { var originalFolderPath = folder.FolderPath; - var folderInfos = GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(originalFolderPath)).ToArray(); - + var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(originalFolderPath)).ToArray(); + foreach (var folderInfo in folderInfos) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folderInfo.FolderMappingID); var provider = FolderProvider.Instance(folderMapping.FolderProviderType); - var folderPath = newFolderPath + (newFolderPath.EndsWith("/") ? "" : "/") + folderInfo.FolderPath.Substring(originalFolderPath.Length); + var folderPath = newFolderPath + (newFolderPath.EndsWith("/") ? string.Empty : "/") + folderInfo.FolderPath.Substring(originalFolderPath.Length); - var parentFolder = GetParentFolder(folder.PortalID, folderPath); + var parentFolder = this.GetParentFolder(folder.PortalID, folderPath); folderInfo.ParentID = parentFolder.FolderID; folderInfo.FolderPath = folderPath; @@ -2146,7 +2216,7 @@ internal virtual void UpdateChildFolders(IFolderInfo folder, string newFolderPat { if (provider.SupportsMappedPaths) { - var mappedPath = parentFolder.FolderPath == "" ? "" : folderPath.Replace(parentFolder.FolderPath, string.Empty); + var mappedPath = parentFolder.FolderPath == string.Empty ? string.Empty : folderPath.Replace(parentFolder.FolderPath, string.Empty); folderInfo.MappedPath = PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + mappedPath); } else @@ -2168,37 +2238,42 @@ internal virtual void UpdateChildFolders(IFolderInfo folder, string newFolderPat } } - UpdateFolderInternal(folderInfo, false); + this.UpdateFolderInternal(folderInfo, false); } - ClearFolderCache(folder.PortalID); - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + + this.ClearFolderCache(folder.PortalID); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + /// internal virtual bool CanMoveBetweenFolderMappings(FolderMappingInfo sourceFolderMapping, FolderMappingInfo destinationFolderMapping) { - //If Folder Mappings are exactly the same + // If Folder Mappings are exactly the same if (sourceFolderMapping.FolderMappingID == destinationFolderMapping.FolderMappingID) { return true; } return IsStandardFolderProviderType(sourceFolderMapping) && IsStandardFolderProviderType(destinationFolderMapping); - } - #endregion - - #region Internal Classes - + } + /// /// This class and its members are reserved for internal use and are not intended to be used in your code. /// internal class MergedTreeItem { public bool ExistsInFileSystem { get; set; } + public bool ExistsInDatabase { get; set; } + public bool ExistsInFolderMapping { get; set; } + public int FolderID { get; set; } + public int FolderMappingID { get; set; } + public string FolderPath { get; set; } + public string MappedPath { get; set; } } @@ -2209,7 +2284,7 @@ internal class IgnoreCaseStringComparer : IComparer { public int Compare(string x, string y) { - return String.Compare(x.ToLowerInvariant(), y.ToLowerInvariant(), StringComparison.Ordinal); + return string.Compare(x.ToLowerInvariant(), y.ToLowerInvariant(), StringComparison.Ordinal); } } @@ -2218,52 +2293,24 @@ public int Compare(string x, string y) /// internal class MoveFoldersInfo { - public string Source { get; private set; } - public string Target { get; private set; } - public MoveFoldersInfo(string source, string target) { - Source = source; - Target = target; + this.Source = source; + this.Target = target; } - } - - #endregion - - #region Obsolete Methods - - /// - /// Moves the specified folder and its contents to a new location. - /// - /// The folder to move. - /// The new folder path. - /// The moved folder. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.1. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) . Scheduled removal in v10.0.0.")] - public virtual IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath) - { - Requires.NotNull("folder", folder); - Requires.NotNullOrEmpty("newFolderPath", newFolderPath); - - var nameCharIndex = newFolderPath.Substring(0, newFolderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1; - var parentFolder = GetFolder(folder.PortalID, newFolderPath.Substring(0, nameCharIndex)); - if (parentFolder.FolderID == folder.ParentID) - { - var newFolderName = newFolderPath.Substring(nameCharIndex, newFolderPath.Length - nameCharIndex - 1); - RenameFolder(folder, newFolderName); - return folder; - } - - return MoveFolder(folder, parentFolder); - } - - #endregion + + public string Source { get; private set; } + + public string Target { get; private set; } + } } - class SyncFolderData + internal class SyncFolderData { public int PortalId { get; set; } + public string FolderPath { get; set; } + public FolderPermissionCollection Permissions { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs index 4e270d62ba2..64df51a8011 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs @@ -1,55 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem.Internal; + public class FolderMappingController : ComponentBase, IFolderMappingController - { - #region Constructor - + { + private const string CacheKeyPrefix = "GetFolderMappingSettings"; + private static readonly DataProvider dataProvider = DataProvider.Instance(); + internal FolderMappingController() { - } - - #endregion - - #region Private Variables - - private static readonly DataProvider dataProvider = DataProvider.Instance(); - private const string CacheKeyPrefix = "GetFolderMappingSettings"; - - #endregion - - #region Public Methods - + } + public FolderMappingInfo GetDefaultFolderMapping(int portalId) { var defaultFolderMapping = Config.GetSection("dotnetnuke/folder") != null ? - GetFolderMappings(portalId).Find(fm => fm.FolderProviderType == Config.GetDefaultProvider("folder").Name) : - GetFolderMapping(portalId, "Standard"); - return defaultFolderMapping ?? GetFolderMapping(portalId, "Standard"); + this.GetFolderMappings(portalId).Find(fm => fm.FolderProviderType == Config.GetDefaultProvider("folder").Name) : + this.GetFolderMapping(portalId, "Standard"); + return defaultFolderMapping ?? this.GetFolderMapping(portalId, "Standard"); } public int AddFolderMapping(FolderMappingInfo objFolderMapping) { - objFolderMapping.FolderMappingID = dataProvider.AddFolderMapping(objFolderMapping.PortalID, - objFolderMapping.MappingName, - objFolderMapping.FolderProviderType, - UserController.Instance.GetCurrentUserInfo().UserID); + objFolderMapping.FolderMappingID = dataProvider.AddFolderMapping( + objFolderMapping.PortalID, + objFolderMapping.MappingName, + objFolderMapping.FolderProviderType, + UserController.Instance.GetCurrentUserInfo().UserID); UpdateFolderMappingSettings(objFolderMapping); @@ -94,7 +85,7 @@ public void DeleteFolderMapping(int portalID, int folderMappingID) if (folderMappingFolders.Count() > 0) { - var defaultFolderMapping = GetDefaultFolderMapping(portalID); + var defaultFolderMapping = this.GetDefaultFolderMapping(portalID); foreach (var folderMappingFolder in folderMappingFolders) { @@ -111,10 +102,11 @@ public void DeleteFolderMapping(int portalID, int folderMappingID) public void UpdateFolderMapping(FolderMappingInfo objFolderMapping) { - dataProvider.UpdateFolderMapping(objFolderMapping.FolderMappingID, - objFolderMapping.MappingName, - objFolderMapping.Priority, - UserController.Instance.GetCurrentUserInfo().UserID); + dataProvider.UpdateFolderMapping( + objFolderMapping.FolderMappingID, + objFolderMapping.MappingName, + objFolderMapping.Priority, + UserController.Instance.GetCurrentUserInfo().UserID); ClearFolderMappingCache(objFolderMapping.PortalID); UpdateFolderMappingSettings(objFolderMapping); @@ -127,21 +119,23 @@ public FolderMappingInfo GetFolderMapping(int folderMappingID) public FolderMappingInfo GetFolderMapping(int portalId, int folderMappingID) { - return GetFolderMappings(portalId).SingleOrDefault(fm => fm.FolderMappingID == folderMappingID); + return this.GetFolderMappings(portalId).SingleOrDefault(fm => fm.FolderMappingID == folderMappingID); } public FolderMappingInfo GetFolderMapping(int portalId, string mappingName) { - return GetFolderMappings(portalId).SingleOrDefault(fm => fm.MappingName == mappingName); + return this.GetFolderMappings(portalId).SingleOrDefault(fm => fm.MappingName == mappingName); } public List GetFolderMappings(int portalId) { - var cacheKey = String.Format(DataCache.FolderMappingCacheKey, portalId); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - DataCache.FolderMappingCacheTimeOut, - DataCache.FolderMappingCachePriority), - (c) => CBO.FillCollection(dataProvider.GetFolderMappings(portalId))); + var cacheKey = string.Format(DataCache.FolderMappingCacheKey, portalId); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.FolderMappingCacheTimeOut, + DataCache.FolderMappingCachePriority), + (c) => CBO.FillCollection(dataProvider.GetFolderMappings(portalId))); } public void AddDefaultFolderTypes(int portalID) @@ -180,16 +174,14 @@ public Hashtable GetFolderMappingSettings(int folderMappingID) { CBO.CloseDataReader(dr, true); } + var intCacheTimeout = 20 * Convert.ToInt32(Host.PerformanceSetting); DataCache.SetCache(strCacheKey, objSettings, TimeSpan.FromMinutes(intCacheTimeout)); } + return objSettings; - } - - #endregion - - #region Private Methods - + } + private static void UpdateFolderMappingSettings(FolderMappingInfo objFolderMapping) { foreach (string sKey in objFolderMapping.FolderMappingSettings.Keys) @@ -228,15 +220,13 @@ private static void UpdateFolderMappingSetting(int folderMappingID, string setti private static void ClearFolderMappingCache(int portalId) { - var cacheKey = String.Format(DataCache.FolderMappingCacheKey, portalId); + var cacheKey = string.Format(DataCache.FolderMappingCacheKey, portalId); DataCache.RemoveCache(cacheKey); } private static void ClearFolderMappingSettingsCache(int folderMappingID) { DataCache.RemoveCache(CacheKeyPrefix + folderMappingID); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs index 4546fd9d484..9e7f1bd6338 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs @@ -1,63 +1,81 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.FileSystem.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.FileSystem.Internal; + /// - /// Represents the FolderMapping object and holds the Properties of that object + /// Represents the FolderMapping object and holds the Properties of that object. /// [Serializable] public class FolderMappingInfo : IHydratable { - private Hashtable _folderMappingSettings; + private Hashtable _folderMappingSettings; - #region "Public Properties" + private string _imageUrl; + + public FolderMappingInfo() + { + this.FolderMappingID = Null.NullInteger; + this.PortalID = Null.NullInteger; + } + public FolderMappingInfo(int portalID, string mappingName, string folderProviderType) + { + this.FolderMappingID = Null.NullInteger; + this.PortalID = portalID; + this.MappingName = mappingName; + this.FolderProviderType = folderProviderType; + } + public int FolderMappingID { get; set; } + public int PortalID { get; set; } + public string MappingName { get; set; } + public string FolderProviderType { get; set; } + public int Priority { get; set; } public Hashtable FolderMappingSettings { get { - if (_folderMappingSettings == null) + if (this._folderMappingSettings == null) { - if (FolderMappingID == Null.NullInteger) + if (this.FolderMappingID == Null.NullInteger) { - _folderMappingSettings = new Hashtable(); + this._folderMappingSettings = new Hashtable(); } else { - _folderMappingSettings = FolderMappingController.Instance.GetFolderMappingSettings(FolderMappingID); + this._folderMappingSettings = FolderMappingController.Instance.GetFolderMappingSettings(this.FolderMappingID); } } - return _folderMappingSettings; + + return this._folderMappingSettings; } } - - private string _imageUrl; + public string ImageUrl { get { - if (string.IsNullOrEmpty(_imageUrl)) + if (string.IsNullOrEmpty(this._imageUrl)) { - _imageUrl = FolderProvider.Instance(FolderProviderType).GetFolderProviderIconPath(); + this._imageUrl = FolderProvider.Instance(this.FolderProviderType).GetFolderProviderIconPath(); } - - return _imageUrl; + + return this._imageUrl; } } @@ -65,7 +83,7 @@ public bool IsEditable { get { - return !DefaultFolderProviders.GetDefaultProviders().Contains(FolderProviderType); + return !DefaultFolderProviders.GetDefaultProviders().Contains(this.FolderProviderType); } } @@ -73,69 +91,47 @@ public bool SyncAllSubFolders { get { - if(FolderMappingSettings.ContainsKey("SyncAllSubFolders")) + if (this.FolderMappingSettings.ContainsKey("SyncAllSubFolders")) { - return bool.Parse(FolderMappingSettings["SyncAllSubFolders"].ToString()); + return bool.Parse(this.FolderMappingSettings["SyncAllSubFolders"].ToString()); } return true; } + set { - FolderMappingSettings["SyncAllSubFolders"] = value; + this.FolderMappingSettings["SyncAllSubFolders"] = value; } - } - - #endregion - - #region "Constructors" - - public FolderMappingInfo() - { - FolderMappingID = Null.NullInteger; - PortalID = Null.NullInteger; - } - - public FolderMappingInfo(int portalID, string mappingName, string folderProviderType) - { - FolderMappingID = Null.NullInteger; - PortalID = portalID; - MappingName = mappingName; - FolderProviderType = folderProviderType; - } - - #endregion - - #region "IHydratable Implementation" + } /// - /// Fills a FolderInfo from a Data Reader - /// - /// The Data Reader to use - public void Fill(IDataReader dr) - { - FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); - PortalID = Null.SetNullInteger(dr["PortalID"]); - MappingName = Null.SetNullString(dr["MappingName"]); - FolderProviderType = Null.SetNullString(dr["FolderProviderType"]); - Priority = Null.SetNullInteger(dr["Priority"]); - } - - /// - /// Gets and sets the Key ID + /// Gets or sets and sets the Key ID. /// public int KeyID { get { - return FolderMappingID; + return this.FolderMappingID; } + set { - FolderMappingID = value; + this.FolderMappingID = value; } + } + + /// + /// Fills a FolderInfo from a Data Reader. + /// + /// The Data Reader to use. + public void Fill(IDataReader dr) + { + this.FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.MappingName = Null.SetNullString(dr["MappingName"]); + this.FolderProviderType = Null.SetNullString(dr["FolderProviderType"]); + this.Priority = Null.SetNullInteger(dr["Priority"]); } - - #endregion } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingSettingsControlBase.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingSettingsControlBase.cs index f35f6739ed3..bd5c6bde280 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingSettingsControlBase.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingSettingsControlBase.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; - -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System.Collections; + + using DotNetNuke.Entities.Modules; + public abstract class FolderMappingSettingsControlBase : PortalModuleBase { /// @@ -21,10 +21,10 @@ public abstract class FolderMappingSettingsControlBase : PortalModuleBase /// { /// tbSettingValue.Text = folderMappingSettings["SettingName"].ToString(); /// } - /// } + /// }. /// public abstract void LoadSettings(Hashtable folderMappingSettings); - + /// /// Use this method to update the provider's concrete settings for the specified folder mapping. /// @@ -51,7 +51,7 @@ public abstract class FolderMappingSettingsControlBase : PortalModuleBase /// { /// throw new Exception(); /// } - /// } + /// }. /// public abstract void UpdateSettings(int folderMappingID); } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs index bd0e54ba460..6ed64485396 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs @@ -1,59 +1,87 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem.FolderMappings; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { - public class FolderMappingsConfigController: ServiceLocator, IFolderMappingsConfigController + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem.FolderMappings; + + public class FolderMappingsConfigController : ServiceLocator, IFolderMappingsConfigController { + private const string configNode = "folderMappingsSettings"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FolderMappingsConfigController)); - private static readonly string defaultConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); - #region Constructor + private static readonly string defaultConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); + public FolderMappingsConfigController() { - FolderMappings = new Dictionary(); - FolderTypes = new List(); - LoadConfig(); - } - #endregion - - #region private methods + this.FolderMappings = new Dictionary(); + this.FolderTypes = new List(); + this.LoadConfig(); + } + + public IList FolderTypes { get; internal set; } + + public string ConfigNode + { + get { return configNode; } + } + private IDictionary FolderMappings { get; set; } + + public void LoadConfig() + { + try + { + if (File.Exists(defaultConfigFilePath)) + { + var configDocument = new XmlDocument { XmlResolver = null }; + configDocument.Load(defaultConfigFilePath); + this.FillFolderMappings(configDocument); + this.FillFolderTypes(configDocument); + } + } + catch (Exception ex) + { + Logger.Error(ex); + } + } private void FillFolderMappings(XmlDocument configDocument) { - var folderMappingsNode = configDocument.SelectSingleNode(ConfigNode+"/folderMappings"); + var folderMappingsNode = configDocument.SelectSingleNode(this.ConfigNode + "/folderMappings"); if (folderMappingsNode == null) { return; } - FolderMappings.Clear(); + + this.FolderMappings.Clear(); foreach (XmlNode folderMappingNode in folderMappingsNode) { - FolderMappings.Add(XmlUtils.GetNodeValue(folderMappingNode, "folderPath"), XmlUtils.GetNodeValue(folderMappingNode, "folderTypeName")); + this.FolderMappings.Add(XmlUtils.GetNodeValue(folderMappingNode, "folderPath"), XmlUtils.GetNodeValue(folderMappingNode, "folderTypeName")); } } private void FillFolderTypes(XmlDocument configDocument) { - var folderTypesNode = configDocument.SelectSingleNode(ConfigNode+"/folderTypes"); + var folderTypesNode = configDocument.SelectSingleNode(this.ConfigNode + "/folderTypes"); if (folderTypesNode == null) { return; } - FolderTypes.Clear(); + + this.FolderTypes.Clear(); foreach (XmlNode folderTypeNode in folderTypesNode) { - FolderTypes.Add(GetFolderMappingFromConfigNode(folderTypeNode)); + this.FolderTypes.Add(this.GetFolderMappingFromConfigNode(folderTypeNode)); } } @@ -63,7 +91,7 @@ private FolderTypeConfig GetFolderMappingFromConfigNode(XmlNode node) var folderType = new FolderTypeConfig() { Name = XmlUtils.GetAttributeValue(nodeNavigator, "name"), - Provider = XmlUtils.GetNodeValue(nodeNavigator, "provider"), + Provider = XmlUtils.GetNodeValue(nodeNavigator, "provider"), }; XmlNodeList settingsNode = node.SelectNodes("settings/setting"); if (settingsNode != null) @@ -76,68 +104,39 @@ private FolderTypeConfig GetFolderMappingFromConfigNode(XmlNode node) { Name = XmlUtils.GetAttributeValue(settingNode.CreateNavigator(), "name"), Value = settingNode.InnerText, - Encrypt = !String.IsNullOrEmpty(encryptValue) && Boolean.Parse(encryptValue) + Encrypt = !string.IsNullOrEmpty(encryptValue) && bool.Parse(encryptValue), }); } + folderType.Settings = settings; } return folderType; - } - #endregion - - #region public Properties - public IList FolderTypes { get; internal set; } - - private const string configNode = "folderMappingsSettings"; - public string ConfigNode - { - get { return configNode; } - } - #endregion - - #region public Methods - public void LoadConfig() - { - try - { - if (File.Exists(defaultConfigFilePath)) - { - var configDocument = new XmlDocument { XmlResolver = null }; - configDocument.Load(defaultConfigFilePath); - FillFolderMappings(configDocument); - FillFolderTypes(configDocument); - } - } - catch (Exception ex) - { - Logger.Error(ex); - } - } + } public void SaveConfig(string folderMappinsSettings) - { + { if (!File.Exists(defaultConfigFilePath)) { - var folderMappingsConfigContent = "<" + ConfigNode + ">" + folderMappinsSettings + ""; + var folderMappingsConfigContent = "<" + this.ConfigNode + ">" + folderMappinsSettings + ""; File.AppendAllText(defaultConfigFilePath, folderMappingsConfigContent); var configDocument = new XmlDocument { XmlResolver = null }; configDocument.LoadXml(folderMappingsConfigContent); - FillFolderMappings(configDocument); - FillFolderTypes(configDocument); + this.FillFolderMappings(configDocument); + this.FillFolderTypes(configDocument); } } public FolderMappingInfo GetFolderMapping(int portalId, string folderPath) { - if (!FolderMappings.ContainsKey(folderPath)) + if (!this.FolderMappings.ContainsKey(folderPath)) { return null; } - return FolderMappingController.Instance.GetFolderMapping(portalId, FolderMappings[folderPath]); - } - #endregion - + + return FolderMappingController.Instance.GetFolderMapping(portalId, this.FolderMappings[folderPath]); + } + protected override Func GetFactory() { return () => new FolderMappingsConfigController(); diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs index 28d772f98bf..3f18891e9b4 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs @@ -1,30 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem { + using System.Collections.Generic; + /// ----------------------------------------------------------------------------- /// - /// HostSettingConfig - A class that represents Install/DotNetNuke.Install.Config/Settings + /// HostSettingConfig - A class that represents Install/DotNetNuke.Install.Config/Settings. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class FolderTypeConfig { - public string Name { get; set; } - public string Provider { get; set; } - public IList Settings { get; set; } - public FolderTypeConfig() { - Settings = new List(); + this.Settings = new List(); } + + public string Name { get; set; } + + public string Provider { get; set; } + + public IList Settings { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs index c9c5b569610..4571ef3d9c4 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs @@ -1,25 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem { + using System; + /// ----------------------------------------------------------------------------- /// - /// HostSettingConfig - A class that represents Install/DotNetNuke.Install.Config/Settings + /// HostSettingConfig - A class that represents Install/DotNetNuke.Install.Config/Settings. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class FolderTypeSettingConfig { public string Name { get; set; } + public string Value { get; set; } + public bool Encrypt { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs index bb39e2a38ba..e0d800f567b 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs @@ -1,23 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System.Collections; + using System.Collections.Generic; + public interface IFolderMappingController { void AddDefaultFolderTypes(int portalId); + int AddFolderMapping(FolderMappingInfo objFolderMapping); + void DeleteFolderMapping(int portalId, int folderMappingId); + FolderMappingInfo GetDefaultFolderMapping(int portalId); + FolderMappingInfo GetFolderMapping(int folderMappingId); + FolderMappingInfo GetFolderMapping(int portalId, int folderMappingId); + FolderMappingInfo GetFolderMapping(int portalId, string mappingName); + List GetFolderMappings(int portalId); + Hashtable GetFolderMappingSettings(int folderMappingId); + void UpdateFolderMapping(FolderMappingInfo objFolderMapping); } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs index a324a93c197..f52bf25f616 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs @@ -1,42 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.FolderMappings { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + public interface IFolderMappingsConfigController { /// - /// All folder types read from folderMappings config file + /// Gets all folder types read from folderMappings config file. /// IList FolderTypes { get; } - + /// - /// Root node in folderMappings config file + /// Gets root node in folderMappings config file. /// string ConfigNode { get; } - + /// - /// Load data from folderMappings config file + /// Load data from folderMappings config file. /// void LoadConfig(); /// - /// Save data in folderMappings config file + /// Save data in folderMappings config file. /// /// void SaveConfig(string folderMappinsSettings); /// - /// Gets the folderMapping configured for a specific folder + /// Gets the folderMapping configured for a specific folder. /// - /// Portal Id where the folder is - /// Specific folder path + /// Portal Id where the folder is. + /// Specific folder path. + /// FolderMappingInfo GetFolderMapping(int portalId, string folderPath); } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs index 07a37cde5c4..b9476747ea1 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs @@ -1,74 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Host; -using DotNetNuke.Security; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Host; + using DotNetNuke.Security; + /// /// Base class that provides common functionallity to work with files and folders. /// public abstract class FolderProvider - { - #region Constants - - private const string SettingsControlId = "Settings.ascx"; - - #endregion - - #region Private Variables - - private string _providerName; - - #endregion - - #region Static Provider Methods - - /// - /// Get the list of all the folder providers. - /// - public static Dictionary GetProviderList() - { - var providerList = ComponentFactory.GetComponents(); - - foreach (var key in providerList.Keys) - { - providerList[key]._providerName = key; - } - - return providerList; - } - - /// - /// Gets an instance of a specific FolderProvider of a given name. - /// - public static FolderProvider Instance(string friendlyName) - { - var provider = ComponentFactory.GetComponent(friendlyName); - - provider._providerName = friendlyName; - - return provider; - } - - #endregion - - #region Properties - + { + private const string SettingsControlId = "Settings.ascx"; + private string _providerName; + /// - /// Gets a value indicating if the provider ensures the files/folders it manages are secure from outside access. + /// Gets a value indicating whether gets a value indicating if the provider ensures the files/folders it manages are secure from outside access. /// /// /// Some providers (e.g. Standard) store their files/folders in a way that allows for anonymous access that bypasses DotNetNuke. @@ -83,7 +42,7 @@ public virtual bool IsStorageSecure } /// - /// Gets a value indicating if the provider requires network connectivity to do its tasks. + /// Gets a value indicating whether gets a value indicating if the provider requires network connectivity to do its tasks. /// public virtual bool RequiresNetworkConnectivity { @@ -94,11 +53,11 @@ public virtual bool RequiresNetworkConnectivity } /// - /// Indicates if the folder provider supports mapped paths when creating new folders + /// Gets a value indicating whether indicates if the folder provider supports mapped paths when creating new folders. /// /// - /// If this method is not overrided it returns false - /// + /// If this method is not overrided it returns false. + /// public virtual bool SupportsMappedPaths { get @@ -106,6 +65,35 @@ public virtual bool SupportsMappedPaths return false; } } + + /// + /// Get the list of all the folder providers. + /// + /// + public static Dictionary GetProviderList() + { + var providerList = ComponentFactory.GetComponents(); + + foreach (var key in providerList.Keys) + { + providerList[key]._providerName = key; + } + + return providerList; + } + + /// + /// Gets an instance of a specific FolderProvider of a given name. + /// + /// + public static FolderProvider Instance(string friendlyName) + { + var provider = ComponentFactory.GetComponent(friendlyName); + + provider._providerName = friendlyName; + + return provider; + } /// /// Gets a value indicating whether the provider supports the MoveFile method. If a provider supports the MoveFile method, the @@ -123,12 +111,50 @@ public virtual bool SupportsMoveFile public virtual bool SupportsMoveFolder { get { return false; } + } + + public virtual void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) + { + this.AddFolder(folderPath, folderMapping); } - #endregion + /// + /// Copies the specified file to the destination folder. + /// + public virtual void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) + { + Requires.PropertyNotNull("folderPath", folderPath); + Requires.NotNullOrEmpty("fileName", fileName); + Requires.PropertyNotNull("newFolderPath", newFolderPath); + Requires.NotNull("folderMapping", folderMapping); + + if (folderPath == newFolderPath) + { + return; + } + + var sourceFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath); + var destinationFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, newFolderPath); - #region Private Methods + Requires.NotNull("sourceFolder", sourceFolder); + Requires.NotNull("destinationFolder", destinationFolder); + using (var fileContent = this.GetFileStream(sourceFolder, fileName)) + { + if (!fileContent.CanSeek) + { + using (var seekableStream = FileManager.Instance.GetSeekableStream(fileContent)) + { + this.AddFile(destinationFolder, fileName, seekableStream); + } + } + else + { + this.AddFile(destinationFolder, fileName, fileContent); + } + } + } + private static void AddFolderAndMoveFiles(string folderPath, string newFolderPath, FolderMappingInfo folderMapping) { var folderProvider = Instance(folderMapping.FolderProviderType); @@ -165,59 +191,18 @@ private static void MoveFiles(IFolderInfo folder, IFolderInfo newFolder, FolderM folderProvider.AddFile(newFolder, file, fileContent); } } + folderProvider.DeleteFile(new FileInfo { FileName = file, Folder = folder.FolderPath, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID }); } - } - - #endregion - - #region Virtual Methods - - public virtual void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) - { - AddFolder(folderPath, folderMapping); - } - - /// - /// Copies the specified file to the destination folder. - /// - public virtual void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) - { - Requires.PropertyNotNull("folderPath", folderPath); - Requires.NotNullOrEmpty("fileName", fileName); - Requires.PropertyNotNull("newFolderPath", newFolderPath); - Requires.NotNull("folderMapping", folderMapping); - - if (folderPath == newFolderPath) return; - - var sourceFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath); - var destinationFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, newFolderPath); - - Requires.NotNull("sourceFolder", sourceFolder); - Requires.NotNull("destinationFolder", destinationFolder); - - using (var fileContent = GetFileStream(sourceFolder, fileName)) - { - if (!fileContent.CanSeek) - { - using (var seekableStream = FileManager.Instance.GetSeekableStream(fileContent)) - { - AddFile(destinationFolder, fileName, seekableStream); - } - } - else - { - AddFile(destinationFolder, fileName, fileContent); - } - } - } + } /// /// Gets a file Stream of the specified file. - /// + /// + /// public virtual Stream GetFileStream(IFolderInfo folder, IFileInfo file, int version) { - return GetFileStream(folder, FileVersionController.GetVersionedFilename(file, version)); + return this.GetFileStream(folder, FileVersionController.GetVersionedFilename(file, version)); } /// @@ -231,7 +216,7 @@ public virtual Stream GetFileStream(IFolderInfo folder, IFileInfo file, int vers /// public virtual string GetSettingsControlVirtualPath() { - var provider = Config.GetProvider("folder", _providerName); + var provider = Config.GetProvider("folder", this._providerName); if (provider != null) { @@ -247,7 +232,7 @@ public virtual string GetSettingsControlVirtualPath() } /// - /// Moves a file to a new folder + /// Moves a file to a new folder. /// /// public virtual void MoveFile(IFileInfo file, IFolderInfo destinationFolder) @@ -283,18 +268,18 @@ public virtual void MoveFolder(string folderPath, string newFolderPath, FolderMa } /// - /// Gets the decrypted value of an encrypted folder mapping setting + /// Gets the decrypted value of an encrypted folder mapping setting. /// - /// If the value is not set the method returns null - /// Folder mapping settings - /// Setting name - /// the input parameters of the method cannot be null - /// decrypted value + /// If the value is not set the method returns null. + /// Folder mapping settings. + /// Setting name. + /// the input parameters of the method cannot be null. + /// decrypted value. public string GetEncryptedSetting(Hashtable folderMappingSettings, string settingName) { Requires.NotNull(nameof(folderMappingSettings), folderMappingSettings); Requires.NotNullOrEmpty(nameof(settingName), settingName); - + return PortalSecurity.Instance.Decrypt(Host.GUID, folderMappingSettings[settingName]?.ToString()); } @@ -305,11 +290,12 @@ public string EncryptValue(string settingValue) public virtual string GetHashCode(IFileInfo file) { - var currentHashCode = String.Empty; - using (var fileContent = GetFileStream(file)) + var currentHashCode = string.Empty; + using (var fileContent = this.GetFileStream(file)) { - currentHashCode = GetHashCode(file, fileContent); + currentHashCode = this.GetHashCode(file, fileContent); } + return currentHashCode; } @@ -335,12 +321,8 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) } return hashText.ToString(); - } - - #endregion - - #region Abstract Methods - + } + /// /// Adds a new file to the specified folder. /// @@ -366,12 +348,14 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// Checks the existence of the specified file in the underlying system. - /// + /// + /// public abstract bool FileExists(IFolderInfo folder, string fileName); /// /// Checks the existence of the specified folder in the underlying system. - /// + /// + /// public abstract bool FolderExists(string folderPath, FolderMappingInfo folderMapping); /// @@ -379,52 +363,62 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// /// Because some Providers don't support file attributes, this methods returns a nullable type to allow them to return null. - /// + /// + /// public abstract FileAttributes? GetFileAttributes(IFileInfo file); /// /// Gets the list of file names contained in the specified folder. - /// + /// + /// public abstract string[] GetFiles(IFolderInfo folder); /// /// Gets the file length. - /// + /// + /// public abstract long GetFileSize(IFileInfo file); /// /// Gets a file Stream of the specified file. - /// + /// + /// public abstract Stream GetFileStream(IFileInfo file); /// /// Gets a file Stream of the specified file. - /// + /// + /// public abstract Stream GetFileStream(IFolderInfo folder, string fileName); /// /// Gets the direct Url to the file. - /// + /// + /// public abstract string GetFileUrl(IFileInfo file); /// /// Gets the URL of the image to display in FileManager tree. - /// + /// + /// public abstract string GetFolderProviderIconPath(); /// /// Gets the time when the specified file was last modified. - /// + /// + /// public abstract DateTime GetLastModificationTime(IFileInfo file); /// /// Gets the list of subfolders for the specified folder. - /// + /// + /// public abstract IEnumerable GetSubFolders(string folderPath, FolderMappingInfo folderMapping); /// /// Indicates if the specified file is synchronized. - /// + /// + /// public abstract bool IsInSync(IFileInfo file); /// @@ -444,7 +438,8 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// Gets a value indicating if the underlying system supports file attributes. - /// + /// + /// public abstract bool SupportsFileAttributes(); /// @@ -461,8 +456,6 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// Do not close content Stream. /// - public abstract void UpdateFile(IFolderInfo folder, string fileName, Stream content); - - #endregion + public abstract void UpdateFile(IFolderInfo folder, string fileName, Stream content); } } diff --git a/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs b/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs index a9691d9a5d5..9b3d33e87ba 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { - public interface IFileContentTypeManager - { - /// - /// Gets the Content Type for the specified file extension. - /// - /// The file extension. - /// The Content Type for the specified extension. - string GetContentType(string extension); - - /// - /// Get all content types dictionary. - /// - IDictionary ContentTypes { get; } - } + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + public interface IFileContentTypeManager + { + /// + /// Gets get all content types dictionary. + /// + IDictionary ContentTypes { get; } + + /// + /// Gets the Content Type for the specified file extension. + /// + /// The file extension. + /// The Content Type for the specified extension. + string GetContentType(string extension); + } } diff --git a/DNN Platform/Library/Services/FileSystem/IFileEventHandlers.cs b/DNN Platform/Library/Services/FileSystem/IFileEventHandlers.cs index 9c885cf5b4d..775d6374f8e 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileEventHandlers.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileEventHandlers.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.FileSystem.EventArgs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using DotNetNuke.Services.FileSystem.EventArgs; + public interface IFileEventHandlers { void FileDeleted(object sender, FileDeletedEventArgs args); diff --git a/DNN Platform/Library/Services/FileSystem/IFileInfo.cs b/DNN Platform/Library/Services/FileSystem/IFileInfo.cs index b392716e850..ff55f8f9b09 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileInfo.cs @@ -1,83 +1,101 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; - -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.IO; + + using DotNetNuke.Entities.Users; + public interface IFileInfo { string ContentType { get; set; } + string Extension { get; set; } + int FileId { get; set; } + string FileName { get; set; } + string Folder { get; set; } + int FolderId { get; set; } + int Height { get; set; } + bool IsCached { get; set; } + string PhysicalPath { get; } + int PortalId { get; set; } + string RelativePath { get; } + string SHA1Hash { get; set; } + int Size { get; set; } + int StorageLocation { get; set; } + Guid UniqueId { get; set; } + Guid VersionGuid { get; set; } + int Width { get; set; } + FileAttributes? FileAttributes { get; } + bool SupportsFileAttributes { get; } + DateTime LastModificationTime { get; set; } + int FolderMappingID { get; set; } /// - /// Gets or sets a metadata field with an optional title associated to the file + /// Gets or sets a metadata field with an optional title associated to the file. /// string Title { get; set; } string Description { get; set; } /// - /// Gets or sets a value indicating whether publish period is enabled for the file + /// Gets or sets a value indicating whether publish period is enabled for the file. /// bool EnablePublishPeriod { get; set; } /// - /// Gets or sets the date on which the file starts to be published + /// Gets or sets the date on which the file starts to be published. /// DateTime StartDate { get; set; } /// - /// Gets or sets the date on which the file ends to be published - /// + /// Gets or sets the date on which the file ends to be published. + /// DateTime EndDate { get; set; } /// /// Gets a value indicating whether the file is enabled, - /// considering if the publish period is active and if the current date is within the publish period + /// considering if the publish period is active and if the current date is within the publish period. /// bool IsEnabled { get; } /// - /// Gets or sets a reference to ContentItem, to use in Workflows + /// Gets or sets a reference to ContentItem, to use in Workflows. /// int ContentItemID { get; set; } /// - /// Gets or sets the published version number of the file + /// Gets or sets the published version number of the file. /// int PublishedVersion { get; set; } - + /// - /// Gets a flag which says whether the file has ever been published + /// Gets a value indicating whether gets a flag which says whether the file has ever been published. /// - bool HasBeenPublished { get; } - - #region Supoort for BaseEntityInfo on inherited classes - + bool HasBeenPublished { get; } + int CreatedByUserID { get; } DateTime CreatedOnDate { get; } @@ -88,8 +106,6 @@ public interface IFileInfo UserInfo CreatedByUser(int portalId); - UserInfo LastModifiedByUser(int portalId); - - #endregion + UserInfo LastModifiedByUser(int portalId); } } diff --git a/DNN Platform/Library/Services/FileSystem/IFileLincClickController.cs b/DNN Platform/Library/Services/FileSystem/IFileLincClickController.cs index e5d5113e4e6..107683d0e65 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileLincClickController.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileLincClickController.cs @@ -1,25 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Specialized; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System.Collections.Specialized; + public interface IFileLinkClickController { /// - /// Get the Link Click Url from a file + /// Get the Link Click Url from a file. /// - /// The specified file - /// The Link Click Url + /// The specified file. + /// The Link Click Url. string GetFileLinkClick(IFileInfo file); /// - /// Get the File Id value contained in a Link Click Url + /// Get the File Id value contained in a Link Click Url. /// - /// Query string parameters collection from a Link Click url - /// A File Id (or -1 if no File Id could be extracted from the query string parameters) + /// Query string parameters collection from a Link Click url. + /// A File Id (or -1 if no File Id could be extracted from the query string parameters). int GetFileIdFromLinkClick(NameValueCollection queryParams); } } diff --git a/DNN Platform/Library/Services/FileSystem/IFileManager.cs b/DNN Platform/Library/Services/FileSystem/IFileManager.cs index 71ec6510374..bfb39dd8dea 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileManager.cs @@ -1,19 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections.Generic; + using System.IO; + /// /// Do not implement. This interface is meant for reference and unit test purposes only. /// There is no guarantee that this interface will not change. /// public interface IFileManager { + /// + /// Gets the system defined content types. + /// + [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.ContentTypes. Scheduled removal in v10.0.0.")] + IDictionary ContentTypes { get; } + /// /// Adds a file to the specified folder. /// @@ -54,8 +60,8 @@ public interface IFileManager /// Indicates if the file has to be over-written if it exists. /// Indicates if permissions have to be met. /// The content type of the file. - /// ID of the user that creates the file - /// A IFileInfo as specified by the parameters. + /// ID of the user that creates the file. + /// A IFileInfo as specified by the parameters. IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite, bool checkPermissions, string contentType, int createdByUserID); /// @@ -66,10 +72,10 @@ public interface IFileManager /// The content of the file. /// Indicates if the file has to be over-written if it exists. /// Indicates if permissions have to be met. - /// Indicates whether the whitelist should be ignored + /// Indicates whether the whitelist should be ignored. /// The content type of the file. - /// ID of the user that creates the file - /// A IFileInfo as specified by the parameters. + /// ID of the user that creates the file. + /// A IFileInfo as specified by the parameters. IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite, bool checkPermissions, bool ignoreWhiteList, string contentType, int createdByUserID); /// @@ -80,12 +86,6 @@ public interface IFileManager /// A IFileInfo with the information of the copied file. IFileInfo CopyFile(IFileInfo file, IFolderInfo destinationFolder); - /// - /// Gets the system defined content types - /// - [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.ContentTypes. Scheduled removal in v10.0.0.")] - IDictionary ContentTypes { get; } - /// /// Deletes the specified file. /// @@ -111,7 +111,7 @@ public interface IFileManager /// /// The folder where to check the existence of the file. /// The file name to check the existence of. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// A boolean value indicating whether the file exists or not in the specified folder. bool FileExists(IFolderInfo folder, string fileName, bool retrieveUnpublishedFiles); @@ -120,7 +120,7 @@ public interface IFileManager /// /// The file extension. /// The Content Type for the specified extension. - [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.GetContentType(string extension). Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.GetContentType(string extension). Scheduled removal in v10.0.0.")] string GetContentType(string extension); /// @@ -134,7 +134,7 @@ public interface IFileManager /// Gets the file metadata for the specified file. /// /// The file identifier. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// The IFileInfo object with the metadata of the specified file. IFileInfo GetFile(int fileID, bool retrieveUnpublishedFiles); @@ -151,14 +151,14 @@ public interface IFileManager /// /// The folder where the file is stored. /// The name of the file. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// The IFileInfo object with the metadata of the specified file. IFileInfo GetFile(IFolderInfo folder, string fileName, bool retrieveUnpublishedFiles); /// /// Gets the file metadata for the specified file. /// - /// The portal ID or Null.NullInteger for the Host + /// The portal ID or Null.NullInteger for the Host. /// Relative path to the file. /// Host and portal settings commonly return a relative path to a file. This method uses that relative path to fetch file metadata. /// The IFileInfo object with the metadata of the specified file. @@ -167,9 +167,9 @@ public interface IFileManager /// /// Gets the file metadata for the specified file. /// - /// The portal ID or Null.NullInteger for the Host + /// The portal ID or Null.NullInteger for the Host. /// Relative path to the file. - /// Indicates if the file is retrieved from All files or from Published files + /// Indicates if the file is retrieved from All files or from Published files. /// Host and portal settings commonly return a relative path to a file. This method uses that relative path to fetch file metadata. /// The IFileInfo object with the metadata of the specified file. IFileInfo GetFile(int portalId, string relativePath, bool retrieveUnpublishedFiles); @@ -196,7 +196,7 @@ public interface IFileManager string GetUrl(IFileInfo file); /// - /// Gets a flag that dertermines if the file is an Image + /// Gets a flag that dertermines if the file is an Image. /// /// The file to test. /// The flag as a boolean value. @@ -213,7 +213,7 @@ public interface IFileManager /// /// Renames the specified file. /// - /// The file to rename + /// The file to rename. /// The new filename to assign to the file. /// An IFileInfo with the information of the renamed file. IFileInfo RenameFile(IFileInfo file, string newFileName); @@ -229,7 +229,6 @@ public interface IFileManager /// Extracts the files and folders contained in the specified zip file to the folder where the file belongs. /// /// The file to unzip. - /// Total files count in the zip file. void UnzipFile(IFileInfo file); /// @@ -237,7 +236,6 @@ public interface IFileManager /// /// The file to unzip. /// The folder to unzip to. - /// Total files count in the zip file. void UnzipFile(IFileInfo file, IFolderInfo destinationFolder); /// diff --git a/DNN Platform/Library/Services/FileSystem/IFileVersionController.cs b/DNN Platform/Library/Services/FileSystem/IFileVersionController.cs index 9119a62a9c0..2c148770890 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileVersionController.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileVersionController.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System.Collections.Generic; + using System.IO; + /// /// Do not implement. This interface is meant for reference and unit test purposes only. /// There is no guarantee that this interface will not change. @@ -14,103 +14,103 @@ namespace DotNetNuke.Services.FileSystem public interface IFileVersionController { /// - /// Add a new version of the file + /// Add a new version of the file. /// - /// The file to add a version to - /// The user who is performing the operation - /// Indicates if the new version should be the published version - /// Remove the oldest versions if # > MaxVersions - /// Version content - /// The name of the file where the content should be stored + /// The file to add a version to. + /// The user who is performing the operation. + /// Indicates if the new version should be the published version. + /// Remove the oldest versions if # > MaxVersions. + /// Version content. + /// The name of the file where the content should be stored. string AddFileVersion(IFileInfo file, int userId, bool published = true, bool removeOldestVersions = true, Stream content = null); /// - /// Changes the published version of a file + /// Changes the published version of a file. /// - /// The file to change its published version - /// the version to change to + /// The file to change its published version. + /// the version to change to. void SetPublishedVersion(IFileInfo file, int version); /// /// Deletes a version of a file. - /// If the version to delete is the published version, the previous version gets published + /// If the version to delete is the published version, the previous version gets published. /// - /// The file to delete the version from - /// The number of the version to delete - /// The new published version + /// The file to delete the version from. + /// The number of the version to delete. + /// The new published version. int DeleteFileVersion(IFileInfo file, int version); /// - /// Gets the physical file with a specific version of a file + /// Gets the physical file with a specific version of a file. /// - /// The file to get the version from - /// The number of the version to retrieve - /// The version of the file + /// The file to get the version from. + /// The number of the version to retrieve. + /// The version of the file. FileVersionInfo GetFileVersion(IFileInfo file, int version); /// - /// Deletes all the unpublished versions of a file + /// Deletes all the unpublished versions of a file. /// - /// The file with versions - /// If True reset to 1 the PublishedVersion Property of the FileInfo + /// The file with versions. + /// If True reset to 1 the PublishedVersion Property of the FileInfo. void DeleteAllUnpublishedVersions(IFileInfo file, bool resetPublishedVersionNumber); /// - /// Returns all the versions of a file + /// Returns all the versions of a file. /// - /// The file with versions - /// Collection of file versions + /// The file with versions. + /// Collection of file versions. IEnumerable GetFileVersions(IFileInfo file); /// - /// This method returns true if FileVersion is enabled in the Folder, false otherwise + /// This method returns true if FileVersion is enabled in the Folder, false otherwise. /// - /// Folder Id - /// true if FileVersion is enabled in the Folder, false otherwise + /// Folder Id. + /// true if FileVersion is enabled in the Folder, false otherwise. bool IsFolderVersioned(int folderId); /// - /// This method returns true if FileVersion is enabled in the Folder, false otherwise + /// This method returns true if FileVersion is enabled in the Folder, false otherwise. /// - /// FolderInfo object - /// true if FileVersion is enabled in the Folder, false otherwise + /// FolderInfo object. + /// true if FileVersion is enabled in the Folder, false otherwise. bool IsFolderVersioned(IFolderInfo folder); /// - /// This method returns true if FileVersion is enabled in the portal, false otherwise + /// This method returns true if FileVersion is enabled in the portal, false otherwise. /// - /// Portal Id - /// true if FileVersion is enabled in the portal, false otherwise + /// Portal Id. + /// true if FileVersion is enabled in the portal, false otherwise. bool IsFileVersionEnabled(int portalId); /// - /// This method returns the max number of versions for a portal + /// This method returns the max number of versions for a portal. /// - /// Portal Id - /// Max file versions + /// Portal Id. + /// Max file versions. int MaxFileVersions(int portalId); /// - /// Rollbacks a file to the specified version + /// Rollbacks a file to the specified version. /// - /// The file to perform the rollback - /// The version to rollback to - /// The user who is performing the operation + /// The file to perform the rollback. + /// The version to rollback to. + /// The user who is performing the operation. void RollbackFileVersion(IFileInfo file, int version, int userId); /// - /// Get the content of a specific version file + /// Get the content of a specific version file. /// - /// The file to get the version - /// The version to obtain the content - /// The Stream with the file content + /// The file to get the version. + /// The version to obtain the content. + /// The Stream with the file content. Stream GetVersionContent(IFileInfo file, int version); /// - /// Get all the non-published versions in a Folder + /// Get all the non-published versions in a Folder. /// - /// Folder Id - /// Collection of file versions + /// Folder Id. + /// Collection of file versions. IEnumerable GetFileVersionsInFolder(int folderId); } } diff --git a/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs b/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs index e8a9d56c5dd..fd29c66643a 100644 --- a/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs @@ -1,60 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + public interface IFolderInfo { string DisplayName { get; set; } + string DisplayPath { get; set; } + int FolderID { get; set; } + string FolderName { get; } + string FolderPath { get; set; } + FolderPermissionCollection FolderPermissions { get; } + bool IsCached { get; set; } + bool IsProtected { get; set; } + DateTime LastUpdated { get; set; } + string PhysicalPath { get; } + int PortalID { get; set; } + int StorageLocation { get; set; } + Guid UniqueId { get; set; } + Guid VersionGuid { get; set; } + int FolderMappingID { get; set; } + bool IsStorageSecure { get; } /// - /// Gets or sets a value indicating whether file versions are active for the folder + /// Gets or sets a value indicating whether file versions are active for the folder. /// bool IsVersioned { get; set; } /// - /// Gets or sets a reference to the active Workflow for the folder + /// Gets or sets a reference to the active Workflow for the folder. /// int WorkflowID { get; set; } /// - /// Gets or sets a reference to the parent folder + /// Gets or sets a reference to the parent folder. /// int ParentID { get; set; } /// - /// Gets or sets the path this folder is mapped on its provider file system + /// Gets or sets the path this folder is mapped on its provider file system. /// string MappedPath { get; set; } /// - /// Gets a value indicating whether the folder has any child subfolder + /// Gets a value indicating whether the folder has any child subfolder. /// - bool HasChildren { get; } - - #region Supoort for BaseEntityInfo on inherited classes - + bool HasChildren { get; } + int CreatedByUserID { get; } DateTime CreatedOnDate { get; } @@ -65,8 +78,6 @@ public interface IFolderInfo UserInfo CreatedByUser(int portalId); - UserInfo LastModifiedByUser(int portalId); - - #endregion + UserInfo LastModifiedByUser(int portalId); } } diff --git a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs index db5748b1383..008b1ce6ed9 100644 --- a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs @@ -1,22 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + /// /// Do not implement. This interface is meant for reference and unit test purposes only. /// There is no guarantee that this interface will not change. /// public interface IFolderManager { + /// + /// Gets the alias name of the personal User Folder. + /// + string MyFolderName { get; } + /// /// Adds read permissions for all users to the specified folder. /// @@ -53,7 +58,7 @@ public interface IFolderManager /// /// Sets folder permissions to the given folder by copying parent folder permissions. /// - /// The folder to copy permissions to + /// The folder to copy permissions to. void CopyParentFolderPermissions(IFolderInfo folder); /// @@ -69,16 +74,16 @@ public interface IFolderManager void DeleteFolder(int folderId); /// - /// Unlink the specified folder + /// Unlink the specified folder. /// - /// The folder to unlink + /// The folder to unlink. void UnlinkFolder(IFolderInfo folder); /// - /// Delete the specified folder and all its content + /// Delete the specified folder and all its content. /// - /// The folder to delete> - /// A collection with all not deleted subfolders + /// The folder to delete>. + /// A collection with all not deleted subfolders. void DeleteFolder(IFolderInfo folder, ICollection notDeletedSubfolders); /// @@ -100,7 +105,7 @@ public interface IFolderManager /// Gets the files contained in the specified folder. /// /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders + /// Whether or not to include all the subfolders. /// The list of files contained in the specified folder. IEnumerable GetFiles(IFolderInfo folder, bool recursive); @@ -108,24 +113,24 @@ public interface IFolderManager /// Gets the files contained in the specified folder. /// /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders - /// Indicates if the file is retrieved from All files or from Published files + /// Whether or not to include all the subfolders. + /// Indicates if the file is retrieved from All files or from Published files. /// The list of files contained in the specified folder. IEnumerable GetFiles(IFolderInfo folder, bool recursive, bool retrieveUnpublishedFiles); /// - /// Search the files contained in the specified folder, for a matching pattern + /// Search the files contained in the specified folder, for a matching pattern. /// /// The folder from which to retrieve the files. - /// The patter to search for - /// Whether or not to include all the subfolders + /// The patter to search for. + /// Whether or not to include all the subfolders. /// The list of files contained in the specified folder. IEnumerable SearchFiles(IFolderInfo folder, string pattern, bool recursive = false); /// /// Gets the list of Standard folders the specified user has the provided permissions. /// - /// The user info + /// The user info. /// The permissions the folders have to met. /// The list of Standard folders the specified user has the provided permissions. /// This method is used to support legacy behaviours and situations where we know the file/folder is in the file system. @@ -154,10 +159,10 @@ public interface IFolderManager IFolderInfo GetFolder(Guid uniqueId); /// - /// Get the users folder + /// Get the users folder. /// - /// the user - /// FolderInfo for the users folder + /// the user. + /// FolderInfo for the users folder. IFolderInfo GetUserFolder(UserInfo userInfo); /// @@ -178,7 +183,7 @@ public interface IFolderManager /// Gets the sorted list of folders of the provided portal. /// /// The portal identifier. - /// True = Read from Cache, False = Read from DB + /// True = Read from Cache, False = Read from DB. /// The sorted list of folders of the provided portal. IEnumerable GetFolders(int portalId, bool useCache); @@ -194,23 +199,18 @@ public interface IFolderManager /// /// Gets the list of folders the specified user has read permissions. /// - /// The user info + /// The user info. /// The list of folders the specified user has read permissions. IEnumerable GetFolders(UserInfo user); /// /// Gets the list of folders the specified user has the provided permissions. /// - /// The user info + /// The user info. /// The permissions the folders have to met. /// The list of folders the specified user has the provided permissions. IEnumerable GetFolders(UserInfo user, string permissions); - /// - /// Gets the alias name of the personal User Folder - /// - string MyFolderName { get; } - /// /// Moves the specified folder and its contents to a new location. /// @@ -227,27 +227,27 @@ public interface IFolderManager void RenameFolder(IFolderInfo folder, string newFolderName); /// - /// Sets specific folder permissions for the given role to the given folder. + /// Sets specific folder permissions for the given role to the given folder. /// - /// The folder to set permission to - /// The id of the permission to assign - /// The role to assign the permission to + /// The folder to set permission to. + /// The id of the permission to assign. + /// The role to assign the permission to. void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId); /// /// Sets specific folder permissions for the given role/user to the given folder. /// - /// The folder to set permission to - /// The id of the permission to assign - /// The role to assign the permission to - /// The user to assign the permission to + /// The folder to set permission to. + /// The id of the permission to assign. + /// The role to assign the permission to. + /// The user to assign the permission to. void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId, int userId); /// /// Sets folder permissions for administrator role to the given folder. /// - /// The folder to set permission to - /// The administrator role id to assign the permission to + /// The folder to set permission to. + /// The administrator role id to assign the permission to. void SetFolderPermissions(IFolderInfo folder, int administratorRoleId); /// @@ -279,11 +279,9 @@ public interface IFolderManager /// Updates metadata of the specified folder. /// /// The folder to update. - /// The updated folder - IFolderInfo UpdateFolder(IFolderInfo folder); - - #region Obsolete Methods - + /// The updated folder. + IFolderInfo UpdateFolder(IFolderInfo folder); + /// /// Moves the specified folder and its contents to a new location. /// @@ -292,8 +290,6 @@ public interface IFolderManager /// The moved folder. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DNN 7.1. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) . Scheduled removal in v10.0.0.")] - IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath); - - #endregion + IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath); } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/DefaultFolderProviders.cs b/DNN Platform/Library/Services/FileSystem/Internal/DefaultFolderProviders.cs index 3d7f591cf71..07932e862cc 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/DefaultFolderProviders.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/DefaultFolderProviders.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using System; + using System.Collections.Generic; + using System.ComponentModel; + /// /// This class contains a method to return the list of names of the default folder providers. /// diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs index 3fb9c902b3f..e5e8a3fc595 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs @@ -1,25 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { - public class FileDeletionController : ServiceLocator< IFileDeletionController, FileDeletionController>, IFileDeletionController + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + + using Localization = DotNetNuke.Services.Localization.Localization; + + public class FileDeletionController : ServiceLocator, IFileDeletionController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileDeletionController)); + public void DeleteFile(IFileInfo file) { string lockReason; if (FileLockingController.Instance.IsFileLocked(file, out lockReason)) { - throw new FileLockedException(Localization.Localization.GetExceptionMessage(lockReason, "File locked. The file cannot be updated. Reason: " + lockReason)); + throw new FileLockedException(Localization.GetExceptionMessage(lockReason, "File locked. The file cannot be updated. Reason: " + lockReason)); } FileVersionController.Instance.DeleteAllUnpublishedVersions(file, false); @@ -31,10 +35,10 @@ public void DeleteFile(IFileInfo file) catch (Exception ex) { Logger.Error(ex); - throw new FolderProviderException(Localization.Localization.GetExceptionMessage("DeleteFileUnderlyingSystemError", "The underlying system threw an exception. The file has not been deleted."), ex); + throw new FolderProviderException(Localization.GetExceptionMessage("DeleteFileUnderlyingSystemError", "The underlying system threw an exception. The file has not been deleted."), ex); } - DeleteFileData(file); + this.DeleteFileData(file); DataCache.RemoveCache("GetFileById" + file.FileId); } @@ -44,31 +48,33 @@ public void UnlinkFile(IFileInfo file) string lockReason; if (FileLockingController.Instance.IsFileLocked(file, out lockReason)) { - throw new FileLockedException(Localization.Localization.GetExceptionMessage(lockReason, "File locked. The file cannot be updated. Reason: " + lockReason)); + throw new FileLockedException(Localization.GetExceptionMessage(lockReason, "File locked. The file cannot be updated. Reason: " + lockReason)); } FileVersionController.Instance.DeleteAllUnpublishedVersions(file, false); - - DeleteFileData(file); - } - + this.DeleteFileData(file); + } + public void DeleteFileData(IFileInfo file) { DataProvider.Instance().DeleteFile(file.PortalId, file.FileName, file.FolderId); - DeleteContentItem(file.ContentItemID); + this.DeleteContentItem(file.ContentItemID); } - private void DeleteContentItem(int contentItemId) + protected override Func GetFactory() { - if (contentItemId == Null.NullInteger) return; - - Util.GetContentController().DeleteContentItem(contentItemId); + return () => new FileDeletionController(); } - protected override Func GetFactory() + private void DeleteContentItem(int contentItemId) { - return () => new FileDeletionController(); + if (contentItemId == Null.NullInteger) + { + return; + } + + Util.GetContentController().DeleteContentItem(contentItemId); } } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs index 507c783d7a9..52f4e32b0ce 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem.Internal { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + public class FileLockingController : ServiceLocator, IFileLockingController { public bool IsFileLocked(IFileInfo file, out string lockReasonKey) { - lockReasonKey = ""; + lockReasonKey = string.Empty; var allowedUser = UserSecurityController.Instance.IsHostAdminUser(file.PortalId); if (allowedUser) @@ -32,7 +33,7 @@ public bool IsFileLocked(IFileInfo file, out string lockReasonKey) } } - var outOfPublishPeriod = IsFileOutOfPublishPeriod(file); + var outOfPublishPeriod = this.IsFileOutOfPublishPeriod(file); if (outOfPublishPeriod) { lockReasonKey = "FileLockedOutOfPublishPeriodError"; @@ -48,18 +49,19 @@ public bool IsFileOutOfPublishPeriod(IFileInfo file, int portalId, int userId) { return false; } - return IsFileOutOfPublishPeriod(file); - } - private bool IsFileOutOfPublishPeriod(IFileInfo file) - { - //Publish Period locks - return (file.EnablePublishPeriod && (file.StartDate > DateTime.Today || (file.EndDate < DateTime.Today && file.EndDate != Null.NullDate))); + return this.IsFileOutOfPublishPeriod(file); } protected override Func GetFactory() { return () => new FileLockingController(); } + + private bool IsFileOutOfPublishPeriod(IFileInfo file) + { + // Publish Period locks + return file.EnablePublishPeriod && (file.StartDate > DateTime.Today || (file.EndDate < DateTime.Today && file.EndDate != Null.NullDate)); + } } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs index 4286b219025..928ca3dc2b3 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs @@ -1,29 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using System; + using System.IO; + + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + /// /// Internal class to check file security. /// public class FileSecurityController : ServiceLocator, IFileSecurityController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSecurityController)); - private const int BufferSize = 4096; - - protected override Func GetFactory() - { - return () => new FileSecurityController(); - } + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSecurityController)); public bool Validate(string fileName, Stream fileContent) { @@ -31,21 +27,26 @@ public bool Validate(string fileName, Stream fileContent) Requires.NotNull("fileContent", fileContent); var extension = Path.GetExtension(fileName); - var checker = GetSecurityChecker(extension?.ToLowerInvariant().TrimStart('.')); + var checker = this.GetSecurityChecker(extension?.ToLowerInvariant().TrimStart('.')); - //when there is no specfic file check for the file type, then treat it as validated. + // when there is no specfic file check for the file type, then treat it as validated. if (checker == null) { return true; } - //use copy of the stream as we can't make sure how the check process the stream. - using (var copyStream = CopyStream(fileContent)) + // use copy of the stream as we can't make sure how the check process the stream. + using (var copyStream = this.CopyStream(fileContent)) { return checker.Validate(copyStream); } } + protected override Func GetFactory() + { + return () => new FileSecurityController(); + } + private IFileSecurityChecker GetSecurityChecker(string extension) { var listEntry = new ListController().GetListEntryInfo("FileSecurityChecker", extension); @@ -72,7 +73,8 @@ private Stream CopyStream(Stream stream) do { filePath = Path.Combine(folderPath, Path.GetRandomFileName()) + ".resx"; - } while (File.Exists(filePath)); + } + while (File.Exists(filePath)); var fileStream = ((FileManager)FileManager.Instance).GetAutoDeleteFileStream(filePath); diff --git a/DNN Platform/Library/Services/FileSystem/Internal/IFileDeletionController.cs b/DNN Platform/Library/Services/FileSystem/Internal/IFileDeletionController.cs index 939a7ec8bc2..92df30436d3 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/IFileDeletionController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/IFileDeletionController.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { public interface IFileDeletionController @@ -13,9 +13,9 @@ public interface IFileDeletionController void DeleteFile(IFileInfo file); /// - /// Unlinks the specified file + /// Unlinks the specified file. /// - /// The file to unlink + /// The file to unlink. void UnlinkFile(IFileInfo file); /// @@ -23,5 +23,5 @@ public interface IFileDeletionController /// /// The file to delete its metadata. void DeleteFileData(IFileInfo file); - } + } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/IFileLockingController.cs b/DNN Platform/Library/Services/FileSystem/Internal/IFileLockingController.cs index e209f6407e6..2f7ad5c130f 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/IFileLockingController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/IFileLockingController.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { public interface IFileLockingController { /// - /// Checks if a file is locked or not + /// Checks if a file is locked or not. /// - /// The file to be checked - /// The friendly reason why the file is locked - /// True if the file is locked, false in otherwise + /// The file to be checked. + /// The friendly reason why the file is locked. + /// True if the file is locked, false in otherwise. bool IsFileLocked(IFileInfo file, out string lockReasonKey); /// - /// Checks if the file is out of Publish Period + /// Checks if the file is out of Publish Period. /// - /// the file to be checked - /// The Portal Id where the file is contained - /// The user Id who is accessing to the file - /// True if the file is out of publish period, false in otherwise. In anycase, True for admin or host users + /// the file to be checked. + /// The Portal Id where the file is contained. + /// The user Id who is accessing to the file. + /// True if the file is out of publish period, false in otherwise. In anycase, True for admin or host users. bool IsFileOutOfPublishPeriod(IFileInfo file, int portalId, int userId); } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs index c63ada29877..7f43e92e2be 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using System.IO; + /// /// File Content Security Checker. /// @@ -14,7 +14,8 @@ public interface IFileSecurityChecker /// /// Checks if the file has valid content. /// - /// The File Content. + /// The File Content. + /// bool Validate(Stream fileContent); } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs index b3aeb2ea02c..4cb8ce1f055 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using System.IO; + /// /// Internal class to check file security. /// @@ -15,7 +15,8 @@ public interface IFileSecurityController /// Checks if the file has valid content. /// /// The File Name. - /// The File Content. + /// The File Content. + /// bool Validate(string fileName, Stream fileContent); } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/IUserSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/IUserSecurityController.cs index b72c9d5fb46..8d36716076b 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/IUserSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/IUserSecurityController.cs @@ -1,31 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { public interface IUserSecurityController { /// - /// Checks if the Current user is Host user or Admin user of the provided portal + /// Checks if the Current user is Host user or Admin user of the provided portal. /// - /// Portal Id to check Admin users - /// True if the Current user is Host user or Admin user. False otherwise + /// Portal Id to check Admin users. + /// True if the Current user is Host user or Admin user. False otherwise. bool IsHostAdminUser(int portalId); /// - /// Checks if the provided user is Host user or Admin user of the provided portal + /// Checks if the provided user is Host user or Admin user of the provided portal. /// - /// Portal Id to check Admin users - /// User Id to check - /// True if the user is Host user or Admin user. False otherwise + /// Portal Id to check Admin users. + /// User Id to check. + /// True if the user is Host user or Admin user. False otherwise. bool IsHostAdminUser(int portalId, int userId); /// - /// Checks if the provided permission is allowed for the current user in the provided folder + /// Checks if the provided permission is allowed for the current user in the provided folder. /// - /// Folder to check - /// Permission key to check + /// Folder to check. + /// Permission key to check. /// bool HasFolderPermission(IFolderInfo folder, string permissionKey); } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/SecurityCheckers/SvgFileChecker.cs b/DNN Platform/Library/Services/FileSystem/Internal/SecurityCheckers/SvgFileChecker.cs index d5caac13e82..bed129a7f85 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/SecurityCheckers/SvgFileChecker.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/SecurityCheckers/SvgFileChecker.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DotNetNuke.Security; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal.SecurityCheckers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + using DotNetNuke.Security; + public class SvgFileChecker : IFileSecurityChecker { public bool Validate(Stream fileContent) @@ -33,7 +34,7 @@ public bool Validate(Stream fileContent) } catch (Exception) { - //when there have exception occur, just return false as not validated, no need log the error. + // when there have exception occur, just return false as not validated, no need log the error. } return false; diff --git a/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs index 33268e5a73b..49c37c06061 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Permissions; + public class UserSecurityController : ServiceLocator, IUserSecurityController { public bool IsHostAdminUser(int portalId) { - return IsHostAdminUser(portalId, UserController.Instance.GetCurrentUserInfo().UserID); + return this.IsHostAdminUser(portalId, UserController.Instance.GetCurrentUserInfo().UserID); } public bool IsHostAdminUser(int portalId, int userId) @@ -23,8 +23,9 @@ public bool IsHostAdminUser(int portalId, int userId) { return false; } + var user = UserController.Instance.GetUserById(portalId, userId); - return user.IsSuperUser || portalId > Null.NullInteger && user.IsInRole(PortalController.Instance.GetPortal(portalId).AdministratorRoleName); + return user.IsSuperUser || (portalId > Null.NullInteger && user.IsInRole(PortalController.Instance.GetPortal(portalId).AdministratorRoleName)); } public bool HasFolderPermission(IFolderInfo folder, string permissionKey) diff --git a/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs index e9a3cbeb3e2..c69fb304093 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs @@ -1,26 +1,109 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Services.FileSystem + // ReSharper restore CheckNamespace { + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + public class DatabaseFolderProvider : SecureFolderProvider - { - #region Private Methods + { + /// + /// Clears the content of the file in the database. + /// + /// The file identifier. + public static void ClearFileContent(int fileId) + { + DataProvider.Instance().ClearFileContent(fileId); + DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); + } + + /// + /// Updates the content of the file in the database. + /// + /// The file identifier. + /// The new content. + public static void UpdateFileContent(int fileId, Stream content) + { + if (content != null) + { + byte[] fileContent; + var buffer = new byte[16 * 1024]; + using (var ms = new MemoryStream()) + { + int read; + while ((read = content.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, read); + } + + fileContent = ms.ToArray(); + } + + UpdateFileContent(fileId, fileContent); + } + else + { + ClearFileContent(fileId); + } + DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); + } + + public override void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) + { + Requires.PropertyNotNull("folderPath", folderPath); + Requires.NotNullOrEmpty("fileName", fileName); + Requires.PropertyNotNull("newFolderPath", newFolderPath); + Requires.NotNull("folderMapping", folderMapping); + + if (folderPath == newFolderPath) + { + return; + } + + var sourceFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath); + var destinationFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, newFolderPath); + + Requires.NotNull("sourceFolder", sourceFolder); + Requires.NotNull("destinationFolder", destinationFolder); + + using (var fileContent = this.GetFileStream(sourceFolder, fileName)) + { + if (!fileContent.CanSeek) + { + using (var seekableStream = FileManager.Instance.GetSeekableStream(fileContent)) + { + this.AddFile(destinationFolder, fileName, seekableStream); + } + } + else + { + this.AddFile(destinationFolder, fileName, fileContent); + } + } + } + + public override void AddFile(IFolderInfo folder, string fileName, Stream content) + { + Requires.NotNull("folder", folder); + Requires.NotNullOrEmpty("fileName", fileName); + + this.UpdateFile(folder, fileName, content); + } + private Stream GetFileStreamInternal(IDataReader dr) { byte[] bytes = null; @@ -75,50 +158,7 @@ private void UpdateFileInternal(int fileId, Stream content) } UpdateFileContent(fileId, fileContent); - } - - #endregion - - #region Abstract Methods - - public override void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) - { - Requires.PropertyNotNull("folderPath", folderPath); - Requires.NotNullOrEmpty("fileName", fileName); - Requires.PropertyNotNull("newFolderPath", newFolderPath); - Requires.NotNull("folderMapping", folderMapping); - - if (folderPath == newFolderPath) return; - - var sourceFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath); - var destinationFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, newFolderPath); - - Requires.NotNull("sourceFolder", sourceFolder); - Requires.NotNull("destinationFolder", destinationFolder); - - using (var fileContent = GetFileStream(sourceFolder, fileName)) - { - if (!fileContent.CanSeek) - { - using (var seekableStream = FileManager.Instance.GetSeekableStream(fileContent)) - { - AddFile(destinationFolder, fileName, seekableStream); - } - } - else - { - AddFile(destinationFolder, fileName, fileContent); - } - } - } - - public override void AddFile(IFolderInfo folder, string fileName, Stream content) - { - Requires.NotNull("folder", folder); - Requires.NotNullOrEmpty("fileName", fileName); - - UpdateFile(folder, fileName, content); - } + } public override void DeleteFile(IFileInfo file) { @@ -132,7 +172,7 @@ public override bool FileExists(IFolderInfo folder, string fileName) Requires.NotNull("folder", folder); Requires.PropertyNotNull("fileName", fileName); - return (FileManager.Instance.GetFile(folder, fileName, true) != null); + return FileManager.Instance.GetFile(folder, fileName, true) != null; } public override bool FolderExists(string folderPath, FolderMappingInfo folderMapping) @@ -140,7 +180,7 @@ public override bool FolderExists(string folderPath, FolderMappingInfo folderMap Requires.PropertyNotNull("folderPath", folderPath); Requires.NotNull("folderMapping", folderMapping); - return (FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath) != null); + return FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath) != null; } public override FileAttributes? GetFileAttributes(IFileInfo file) @@ -166,7 +206,7 @@ public override Stream GetFileStream(IFileInfo file) { Requires.NotNull("file", file); - return GetFileStreamInternal(DataProvider.Instance().GetFileContent(file.FileId)); + return this.GetFileStreamInternal(DataProvider.Instance().GetFileContent(file.FileId)); } public override Stream GetFileStream(IFolderInfo folder, string fileName) @@ -176,14 +216,14 @@ public override Stream GetFileStream(IFolderInfo folder, string fileName) var file = FileManager.Instance.GetFile(folder, fileName, true); - return file != null ? GetFileStreamInternal(DataProvider.Instance().GetFileContent(file.FileId)) : null; + return file != null ? this.GetFileStreamInternal(DataProvider.Instance().GetFileContent(file.FileId)) : null; } public override Stream GetFileStream(IFolderInfo folder, IFileInfo file, int version) { Requires.NotNull("file", file); - return file != null ? GetFileStreamInternal(DataProvider.Instance().GetFileVersionContent(file.FileId, version)) : null; + return file != null ? this.GetFileStreamInternal(DataProvider.Instance().GetFileVersionContent(file.FileId, version)) : null; } public override string GetFolderProviderIconPath() @@ -238,7 +278,7 @@ public override void UpdateFile(IFileInfo file, Stream content) { Requires.NotNull("file", file); - UpdateFileInternal(file.FileId, content); + this.UpdateFileInternal(file.FileId, content); } public override void UpdateFile(IFolderInfo folder, string fileName, Stream content) @@ -248,55 +288,13 @@ public override void UpdateFile(IFolderInfo folder, string fileName, Stream cont var file = FileManager.Instance.GetFile(folder, fileName, true); - if (file == null) return; - - UpdateFileInternal(file.FileId, content); - } - - #endregion - - #region Static Methods - - /// - /// Clears the content of the file in the database. - /// - /// The file identifier. - public static void ClearFileContent(int fileId) - { - DataProvider.Instance().ClearFileContent(fileId); - DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); - } - - /// - /// Updates the content of the file in the database. - /// - /// The file identifier. - /// The new content. - public static void UpdateFileContent(int fileId, Stream content) - { - if (content != null) - { - byte[] fileContent; - var buffer = new byte[16 * 1024]; - using (var ms = new MemoryStream()) - { - int read; - while ((read = content.Read(buffer, 0, buffer.Length)) > 0) - { - ms.Write(buffer, 0, read); - } - fileContent = ms.ToArray(); - } - - UpdateFileContent(fileId, fileContent); - } - else - { - ClearFileContent(fileId); - } - - DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); - } + if (file == null) + { + return; + } + + this.UpdateFileInternal(file.FileId, content); + } /// /// Updates the content of the file in the database. @@ -305,7 +303,7 @@ public static void UpdateFileContent(int fileId, Stream content) /// The new content. public static void UpdateFileContent(int fileId, byte[] content) { - if(content != null) + if (content != null) { DataProvider.Instance().UpdateFileContent(fileId, content); DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); @@ -314,8 +312,6 @@ public static void UpdateFileContent(int fileId, byte[] content) { ClearFileContent(fileId); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs index 9e66e9121a1..c68d704aa8b 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Services.FileSystem.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Services.FileSystem + // ReSharper restore CheckNamespace { + using System; + using System.IO; + + using DotNetNuke.Common; + using DotNetNuke.Services.FileSystem.Internal; + public class SecureFolderProvider : StandardFolderProvider - { - #region Public Properties - + { /// /// Gets the file extension to use for protected files. /// @@ -27,7 +27,7 @@ public string ProtectedExtension } /// - /// Gets a value indicating if the provider ensures the files/folders it manages are secure from outside access. + /// Gets a value indicating whether gets a value indicating if the provider ensures the files/folders it manages are secure from outside access. /// public override bool IsStorageSecure { @@ -35,12 +35,8 @@ public override bool IsStorageSecure { return true; } - } - - #endregion - - #region Abstract Methods - + } + public override string[] GetFiles(IFolderInfo folder) { Requires.NotNull("folder", folder); @@ -50,17 +46,20 @@ public override string[] GetFiles(IFolderInfo folder) for (var i = 0; i < fileNames.Length; i++) { var fileName = Path.GetFileName(fileNames[i]); - if (!fileName.EndsWith(ProtectedExtension, StringComparison.InvariantCultureIgnoreCase)) - { - var destFileName = fileNames[i] + ProtectedExtension; - if (FileWrapper.Instance.Exists(destFileName)) - FileWrapper.Instance.Delete(destFileName); - FileWrapper.Instance.Move(fileNames[i], destFileName); - } - else - { - fileName = fileName.Substring(0, fileName.LastIndexOf(ProtectedExtension, StringComparison.InvariantCultureIgnoreCase)); - } + if (!fileName.EndsWith(this.ProtectedExtension, StringComparison.InvariantCultureIgnoreCase)) + { + var destFileName = fileNames[i] + this.ProtectedExtension; + if (FileWrapper.Instance.Exists(destFileName)) + { + FileWrapper.Instance.Delete(destFileName); + } + + FileWrapper.Instance.Move(fileNames[i], destFileName); + } + else + { + fileName = fileName.Substring(0, fileName.LastIndexOf(this.ProtectedExtension, StringComparison.InvariantCultureIgnoreCase)); + } fileNames[i] = fileName; } @@ -76,26 +75,21 @@ public override string GetFileUrl(IFileInfo file) public override string GetFolderProviderIconPath() { return IconControllerWrapper.Instance.IconURL("FolderSecure", "32x32"); - } - - #endregion - - #region Protected Methods + } + protected override string GetActualPath(FolderMappingInfo folderMapping, string folderPath, string fileName) { - return base.GetActualPath(folderMapping, folderPath, fileName) + ProtectedExtension; + return base.GetActualPath(folderMapping, folderPath, fileName) + this.ProtectedExtension; } protected override string GetActualPath(IFileInfo file) { - return base.GetActualPath(file) + ProtectedExtension; + return base.GetActualPath(file) + this.ProtectedExtension; } protected override string GetActualPath(IFolderInfo folder, string fileName) { - return base.GetActualPath(folder, fileName) + ProtectedExtension; - } - - #endregion + return base.GetActualPath(folder, fileName) + this.ProtectedExtension; + } } } diff --git a/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs index ed35cf288c9..b603a8e1a24 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs @@ -1,32 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem.Internal; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable CheckNamespace namespace DotNetNuke.Services.FileSystem + // ReSharper restore CheckNamespace { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem.Internal; + public class StandardFolderProvider : FolderProvider { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardFolderProvider)); - private static readonly char[] InvalidFileUrlChars = new char[] { '%', ';', '?', ':', '@', '&', '=', '+', '$', ',' }; - - #region Public Properties - + private static readonly char[] InvalidFileUrlChars = new char[] { '%', ';', '?', ':', '@', '&', '=', '+', '$', ',' }; + /// - /// Gets a value indicating if the provider requires network connectivity to do its tasks. + /// Gets a value indicating whether gets a value indicating if the provider requires network connectivity to do its tasks. /// public override bool RequiresNetworkConnectivity { @@ -47,11 +47,8 @@ public override bool SupportsMoveFile public override bool SupportsMoveFolder { get { return true; } - } - - #endregion - - #region Abstract Methods + } + public override void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) { Requires.PropertyNotNull("folderPath", folderPath); @@ -59,10 +56,13 @@ public override void CopyFile(string folderPath, string fileName, string newFold Requires.PropertyNotNull("newFolderPath", newFolderPath); Requires.NotNull("folderMapping", folderMapping); - if (folderPath == newFolderPath) return; - - var filePath = GetActualPath(folderMapping, folderPath, fileName); - var newFilePath = GetActualPath(folderMapping, newFolderPath, fileName); + if (folderPath == newFolderPath) + { + return; + } + + var filePath = this.GetActualPath(folderMapping, folderPath, fileName); + var newFilePath = this.GetActualPath(folderMapping, newFolderPath, fileName); if (FileWrapper.Instance.Exists(filePath)) { @@ -76,7 +76,7 @@ public override void AddFile(IFolderInfo folder, string fileName, Stream content Requires.NotNullOrEmpty("fileName", fileName); Requires.NotNull("content", content); - UpdateFile(folder, fileName, content); + this.UpdateFile(folder, fileName, content); } public override void AddFolder(string folderPath, FolderMappingInfo folderMapping) @@ -87,7 +87,7 @@ public override void DeleteFile(IFileInfo file) { Requires.NotNull("file", file); - var path = GetActualPath(file); + var path = this.GetActualPath(file); if (FileWrapper.Instance.Exists(path)) { @@ -105,7 +105,7 @@ public override bool FileExists(IFolderInfo folder, string fileName) Requires.NotNull("folder", folder); Requires.PropertyNotNull("fileName", fileName); - return FileWrapper.Instance.Exists(GetActualPath(folder, fileName)); + return FileWrapper.Instance.Exists(this.GetActualPath(folder, fileName)); } public override bool FolderExists(string folderPath, FolderMappingInfo folderMapping) @@ -113,7 +113,7 @@ public override bool FolderExists(string folderPath, FolderMappingInfo folderMap Requires.PropertyNotNull("folderPath", folderPath); Requires.NotNull("folderMapping", folderMapping); - return DirectoryWrapper.Instance.Exists(GetActualPath(folderMapping, folderPath)); + return DirectoryWrapper.Instance.Exists(this.GetActualPath(folderMapping, folderPath)); } public override FileAttributes? GetFileAttributes(IFileInfo file) @@ -124,7 +124,7 @@ public override bool FolderExists(string folderPath, FolderMappingInfo folderMap try { - fileAttributes = FileWrapper.Instance.GetAttributes(GetActualPath(file)); + fileAttributes = FileWrapper.Instance.GetAttributes(this.GetActualPath(file)); } catch (Exception ex) { @@ -138,7 +138,7 @@ public override string[] GetFiles(IFolderInfo folder) { Requires.NotNull("folder", folder); - var fileNames = DirectoryWrapper.Instance.GetFiles(GetActualPath(folder)); + var fileNames = DirectoryWrapper.Instance.GetFiles(this.GetActualPath(folder)); for (var i = 0; i < fileNames.Length; i++) { @@ -152,7 +152,7 @@ public override long GetFileSize(IFileInfo file) { Requires.NotNull("file", file); - var physicalFile = new System.IO.FileInfo(GetActualPath(file)); + var physicalFile = new System.IO.FileInfo(this.GetActualPath(file)); return physicalFile.Length; } @@ -161,14 +161,14 @@ public override Stream GetFileStream(IFileInfo file) { Requires.NotNull("file", file); - return GetFileStreamInternal(GetActualPath(file)); + return this.GetFileStreamInternal(this.GetActualPath(file)); } public override Stream GetFileStream(IFolderInfo folder, string fileName) { Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("fileName", fileName); - return GetFileStreamInternal(GetActualPath(folder, fileName)); + return this.GetFileStreamInternal(this.GetActualPath(folder, fileName)); } public override string GetFileUrl(IFileInfo file) @@ -176,30 +176,33 @@ public override string GetFileUrl(IFileInfo file) Requires.NotNull("file", file); var portalSettings = file.PortalId == PortalSettings.Current?.PortalId ? - PortalSettings.Current : - GetPortalSettings(file.PortalId); + PortalSettings.Current : + this.GetPortalSettings(file.PortalId); var rootFolder = file.PortalId == Null.NullInteger ? Globals.HostPath : portalSettings.HomeDirectory; var fullPath = rootFolder + file.Folder + file.FileName; - //check if a filename has a character that is not valid for urls + // check if a filename has a character that is not valid for urls if (fullPath.IndexOfAny(InvalidFileUrlChars) >= 0) { - return Globals.LinkClick($"fileid={file.FileId}", - Null.NullInteger, - Null.NullInteger, - true, - false, - portalSettings.PortalId, - portalSettings.EnableUrlLanguage, + return Globals.LinkClick( + $"fileid={file.FileId}", + Null.NullInteger, + Null.NullInteger, + true, + false, + portalSettings.PortalId, + portalSettings.EnableUrlLanguage, portalSettings.GUID.ToString()); } // Does site management want the cachebuster parameter? if (portalSettings.AddCachebusterToResourceUris) { - var cachebusterToken = UrlUtils.EncryptParameter(file.LastModificationTime.GetHashCode().ToString()); + var cachebusterToken = UrlUtils.EncryptParameter( + file.LastModificationTime.GetHashCode().ToString(), + portalSettings.GUID.ToString()); return TestableGlobals.Instance.ResolveUrl(fullPath + "?ver=" + cachebusterToken); } @@ -220,7 +223,7 @@ public override DateTime GetLastModificationTime(IFileInfo file) try { - lastModificationTime = FileWrapper.Instance.GetLastWriteTime(GetActualPath(file)); + lastModificationTime = FileWrapper.Instance.GetLastWriteTime(this.GetActualPath(file)); } catch (Exception ex) { @@ -235,15 +238,15 @@ public override IEnumerable GetSubFolders(string folderPath, FolderMappi Requires.PropertyNotNull("folderPath", folderPath); Requires.NotNull("folderMapping", folderMapping); - return DirectoryWrapper.Instance.GetDirectories(GetActualPath(folderMapping, folderPath)) - .Select(directory => GetRelativePath(folderMapping, directory)); + return DirectoryWrapper.Instance.GetDirectories(this.GetActualPath(folderMapping, folderPath)) + .Select(directory => this.GetRelativePath(folderMapping, directory)); } public override bool IsInSync(IFileInfo file) { Requires.NotNull("file", file); - return Convert.ToInt32((file.LastModificationTime - GetLastModificationTime(file)).TotalSeconds) == 0; + return Convert.ToInt32((file.LastModificationTime - this.GetLastModificationTime(file)).TotalSeconds) == 0; } public override void MoveFile(IFileInfo file, IFolderInfo destinationFolder) @@ -253,8 +256,8 @@ public override void MoveFile(IFileInfo file, IFolderInfo destinationFolder) if (file.FolderId != destinationFolder.FolderID) { - string oldName = GetActualPath(file); - string newName = GetActualPath(destinationFolder, file.FileName); + string oldName = this.GetActualPath(file); + string newName = this.GetActualPath(destinationFolder, file.FileName); FileWrapper.Instance.Move(oldName, newName); } } @@ -272,8 +275,8 @@ public override void RenameFile(IFileInfo file, string newFileName) if (file.FileName != newFileName) { IFolderInfo folder = FolderManager.Instance.GetFolder(file.FolderId); - string oldName = GetActualPath(file); - string newName = GetActualPath(folder, newFileName); + string oldName = this.GetActualPath(file); + string newName = this.GetActualPath(folder, newFileName); FileWrapper.Instance.Move(oldName, newName); } } @@ -287,7 +290,7 @@ public override void SetFileAttributes(IFileInfo file, FileAttributes fileAttrib { Requires.NotNull("file", file); - FileWrapper.Instance.SetAttributes(GetActualPath(file), fileAttributes); + FileWrapper.Instance.SetAttributes(this.GetActualPath(file), fileAttributes); } public override bool SupportsFileAttributes() @@ -300,7 +303,7 @@ public override void UpdateFile(IFileInfo file, Stream content) Requires.NotNull("file", file); Requires.NotNull("content", content); - UpdateFile(FolderManager.Instance.GetFolder(file.FolderId), file.FileName, content); + this.UpdateFile(FolderManager.Instance.GetFolder(file.FolderId), file.FileName, content); } public override void UpdateFile(IFolderInfo folder, string fileName, Stream content) @@ -310,7 +313,7 @@ public override void UpdateFile(IFolderInfo folder, string fileName, Stream cont Requires.NotNull("content", content); var arrData = new byte[2048]; - var actualPath = GetActualPath(folder, fileName); + var actualPath = this.GetActualPath(folder, fileName); if (FileWrapper.Instance.Exists(actualPath)) { @@ -338,12 +341,8 @@ public override void UpdateFile(IFolderInfo folder, string fileName, Stream cont content.Position = originalPosition; } } - } - - #endregion - - #region Internal Methods - + } + internal virtual string GetHash(IFileInfo file) { var fileManager = new FileManager(); @@ -353,61 +352,58 @@ internal virtual string GetHash(IFileInfo file) internal virtual PortalSettings GetPortalSettings(int portalId) { return new PortalSettings(portalId); - } - - #endregion - - #region Protected Methods + } + /// - /// Get actual path to a file + /// Get actual path to a file. /// - /// Folder Mapping of the folder - /// Folder Path where the file is contained - /// Name of the file - /// A windows supported path to the file + /// Folder Mapping of the folder. + /// Folder Path where the file is contained. + /// Name of the file. + /// A windows supported path to the file. protected virtual string GetActualPath(FolderMappingInfo folderMapping, string folderPath, string fileName) { - var actualFolderPath = GetActualPath(folderMapping, folderPath); + var actualFolderPath = this.GetActualPath(folderMapping, folderPath); return Path.Combine(actualFolderPath, fileName); } /// - /// Get actual path to an IFileInfo + /// Get actual path to an IFileInfo. /// - /// The file - /// A windows supported path to the file + /// The file. + /// A windows supported path to the file. protected virtual string GetActualPath(IFileInfo file) { return file.PhysicalPath; } /// - /// Get actual path to a file in specified folder + /// Get actual path to a file in specified folder. /// - /// The folder that contains the file - /// The file name - /// A windows supported path to the file + /// The folder that contains the file. + /// The file name. + /// A windows supported path to the file. protected virtual string GetActualPath(IFolderInfo folder, string fileName) { return Path.Combine(folder.PhysicalPath, fileName); } /// - /// Get actual path to a folder in the specified folder mapping + /// Get actual path to a folder in the specified folder mapping. /// - /// The folder mapping - /// The folder path - /// A windows supported path to the folder + /// The folder mapping. + /// The folder path. + /// A windows supported path to the folder. protected virtual string GetActualPath(FolderMappingInfo folderMapping, string folderPath) { return PathUtils.Instance.GetPhysicalPath(folderMapping.PortalID, folderPath); } /// - /// Get actual path to a folder + /// Get actual path to a folder. /// - /// The folder - /// A windows supported path to the folder + /// The folder. + /// A windows supported path to the folder. protected virtual string GetActualPath(IFolderInfo folder) { return folder.PhysicalPath; @@ -434,17 +430,14 @@ protected Stream GetFileStreamInternal(string filePath) } /// - /// Get the path relative to the root of the FolderMapping + /// Get the path relative to the root of the FolderMapping. /// - /// Path is relative to this - /// The path - /// A relative path + /// Path is relative to this. + /// The path. + /// A relative path. protected virtual string GetRelativePath(FolderMappingInfo folderMapping, string path) { return PathUtils.Instance.GetRelativePath(folderMapping.PortalID, path); - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs b/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs index 5763b1ec83b..c7af66da24d 100644 --- a/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs +++ b/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs @@ -1,66 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem { + using System; + using System.Collections; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Scheduling; + public class SynchronizeFileSystem : SchedulerClient { public SynchronizeFileSystem(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } public override void DoWork() { try { - //notification that the event is progressing - Progressing(); //OPTIONAL + // notification that the event is progressing + this.Progressing(); // OPTIONAL - Synchronize(); + this.Synchronize(); - ScheduleHistoryItem.Succeeded = true; //REQUIRED + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED - ScheduleHistoryItem.AddLogNote("File System Synchronized."); //OPTIONAL + this.ScheduleHistoryItem.AddLogNote("File System Synchronized."); // OPTIONAL } catch (Exception exc) { - ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.Succeeded = false; + + this.ScheduleHistoryItem.AddLogNote("File System Synchronization failed. " + exc); - ScheduleHistoryItem.AddLogNote("File System Synchronization failed. " + exc); + // notification that we have errored + this.Errored(ref exc); - //notification that we have errored - Errored(ref exc); - - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } private void Synchronize() { var folderManager = FolderManager.Instance; - + folderManager.Synchronize(Null.NullInteger); var portals = PortalController.Instance.GetPortals(); - //Sync Portals - for (var intIndex = 0; intIndex <= portals.Count - 1; intIndex++) + + // Sync Portals + for (var intIndex = 0; intIndex <= portals.Count - 1; intIndex++) { - var portal = (PortalInfo) portals[intIndex]; + var portal = (PortalInfo)portals[intIndex]; folderManager.Synchronize(portal.PortalID); } } diff --git a/DNN Platform/Library/Services/FileSystem/UploadType.cs b/DNN Platform/Library/Services/FileSystem/UploadType.cs index cf8b929f74a..b9951b6ba81 100644 --- a/DNN Platform/Library/Services/FileSystem/UploadType.cs +++ b/DNN Platform/Library/Services/FileSystem/UploadType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { public enum UploadType @@ -10,6 +10,6 @@ public enum UploadType Container, Skin, Module, - LanguagePack + LanguagePack, } } diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/DirectoryWrapper.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/DirectoryWrapper.cs index fcb445e13ac..3e40dc07928 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/DirectoryWrapper.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/DirectoryWrapper.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; - -using DotNetNuke.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using System.IO; + + using DotNetNuke.ComponentModel; + public class DirectoryWrapper : ComponentBase, IDirectory { public void Delete(string path, bool recursive) { - if (Exists(path)) + if (this.Exists(path)) { Directory.Delete(path, recursive); } diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/FileWrapper.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/FileWrapper.cs index 23cffdd587d..2197d175659 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/FileWrapper.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/FileWrapper.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; - -using DotNetNuke.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using System; + using System.IO; + + using DotNetNuke.ComponentModel; + public class FileWrapper : ComponentBase, IFile { public Stream Create(string path) diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs index b20a4e609d0..76da3259450 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs @@ -1,16 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { public interface IDirectory { void Delete(string path, bool recursive); + bool Exists(string path); + string[] GetDirectories(string path); + string[] GetFiles(string path); + void Move(string sourceDirName, string destDirName); + void CreateDirectory(string path); } } diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs index 60bd1c1fe44..3e04778401b 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs @@ -1,23 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem.Internal { + using System; + using System.IO; + public interface IFile { Stream Create(string path); + void Delete(string path); + bool Exists(string path); + FileAttributes GetAttributes(string path); + DateTime GetLastWriteTime(string path); + void Move(string sourceFileName, string destFileName); + void Copy(string sourceFileName, string destinationFileName, bool overwrite); + Stream OpenRead(string path); + byte[] ReadAllBytes(string path); + void SetAttributes(string path, FileAttributes fileAttributes); } } diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/IIconController.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/IIconController.cs index 17cc3ecf332..d540c26c32e 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/IIconController.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/IIconController.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { internal interface IIconController diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs index f061c925123..dc45baf98b4 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs @@ -1,18 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Icons; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.FileSystem { + using System; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Icons; + internal class IconControllerWrapper : ComponentBase, IIconController - { - #region Implementation of IIconController - + { public string IconURL(string key) { return IconController.IconURL(key); @@ -21,8 +19,6 @@ public string IconURL(string key) public string IconURL(string key, string size) { return IconController.IconURL(key, size); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs b/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs index 35219bf1f3a..6c4c7db48b2 100644 --- a/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs +++ b/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -//#define INDIVIDUAL_LOCKS -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Web; -using System.Web.Hosting; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + #if INDIVIDUAL_LOCKS using System.Collections; #endif namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web; + using System.Web.Hosting; + internal interface IImageStore { void Add(string id, byte[] data); @@ -32,15 +32,32 @@ public class DiskImageStore : IImageStore private static DiskImageStore _diskImageStore; private static readonly object InstanceLock = new object(); private static string _cachePath; + private static TimeSpan _purgeInterval; private DateTime _lastPurge; private readonly object _purgeQueuedLock = new object(); private bool _purgeQueued; - private static TimeSpan _purgeInterval; #if INDIVIDUAL_LOCKS private Hashtable _fileLocks = new Hashtable(); -#else +#else private readonly object _fileLock = new object(); + static DiskImageStore() + { + EnableAutoPurge = true; + PurgeInterval = new TimeSpan(0, 5, 0); + CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); + } + + internal DiskImageStore() + { + if (CachePath != null && !Directory.Exists(CachePath)) + { + Directory.CreateDirectory(CachePath); + } + + this._lastPurge = DateTime.Now; + } + #endif public static string CachePath @@ -49,16 +66,19 @@ public static string CachePath { return _cachePath; } + set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(value)); } + _cachePath = value; } } - public static bool EnableAutoPurge { get; set; } //turn on/off purge feature + + public static bool EnableAutoPurge { get; set; } // turn on/off purge feature public static TimeSpan PurgeInterval { @@ -66,52 +86,23 @@ public static TimeSpan PurgeInterval { return _purgeInterval; } + set { if (value == null) { throw new ArgumentNullException(nameof(value)); } + if (value.Ticks < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } + _purgeInterval = value; } } - private DateTime LastPurge - { - get - { - if (_lastPurge < new DateTime(1990, 1, 1)) - { - _lastPurge = DateTime.Now.Subtract(PurgeInterval); - } - return _lastPurge; - } - set - { - _lastPurge = value; - } - } - - static DiskImageStore() - { - EnableAutoPurge = true; - PurgeInterval = new TimeSpan(0, 5, 0); - CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); - } - - internal DiskImageStore() - { - if (CachePath != null && !Directory.Exists(CachePath)) - { - Directory.CreateDirectory(CachePath); - } - _lastPurge = DateTime.Now; - } - internal static IImageStore Instance { get @@ -126,10 +117,29 @@ internal static IImageStore Instance } } } + return _diskImageStore; } } + private DateTime LastPurge + { + get + { + if (this._lastPurge < new DateTime(1990, 1, 1)) + { + this._lastPurge = DateTime.Now.Subtract(PurgeInterval); + } + + return this._lastPurge; + } + + set + { + this._lastPurge = value; + } + } + public void ForcePurgeFromServerCache(string cacheId) { var files = new DirectoryInfo(CachePath).GetFiles(); @@ -143,6 +153,35 @@ public void ForcePurgeFromServerCache(string cacheId) // do nothing at this point. } } + + void IImageStore.Add(string id, byte[] data) + { + this.Add(id, data); + } + + bool IImageStore.TryTransmitIfContains(string id, HttpResponseBase response) + { + return this.TryTransmitIfContains(id, response); + } + +#if INDIVIDUAL_LOCKS + private static string GetEntryId(FileInfo fileinfo) { + string id = fileinfo.Name.Substring(0, fileinfo.Name.Length - s_tempFileExtension.Length); + return id; + } + + private void DiscardFileLockObject(string id) { + // lock on hashtable to prevent other writers + lock (_fileLocks) { + _fileLocks.Remove(id); + } + } +#endif + + private static string BuildFilePath(string id) + { + return CachePath + id + TempFileExtension; + } private void PurgeCallback(object target) { @@ -185,6 +224,7 @@ private void PurgeCallback(object target) #endif } } + Thread.Sleep(0); foreach (var fileinfo in toTryDeleteAgain) { @@ -216,14 +256,14 @@ private void PurgeCallback(object target) #endif } - LastPurge = DateTime.Now; - _purgeQueued = false; + this.LastPurge = DateTime.Now; + this._purgeQueued = false; } private void Add(string id, byte[] data) { var path = BuildFilePath(id); - lock (GetFileLockObject(id)) + lock (this.GetFileLockObject(id)) { try { @@ -240,16 +280,18 @@ private bool TryTransmitIfContains(string id, HttpResponseBase response) { if (EnableAutoPurge) { - QueueAutoPurge(); + this.QueueAutoPurge(); } + string path = BuildFilePath(id); - lock (GetFileLockObject(id)) + lock (this.GetFileLockObject(id)) { if (File.Exists(path)) { response.TransmitFile(path); return true; } + return false; } } @@ -257,19 +299,19 @@ private bool TryTransmitIfContains(string id, HttpResponseBase response) private void QueueAutoPurge() { var now = DateTime.Now; - if (!_purgeQueued && now.Subtract(LastPurge) > PurgeInterval) + if (!this._purgeQueued && now.Subtract(this.LastPurge) > PurgeInterval) { - lock (_purgeQueuedLock) + lock (this._purgeQueuedLock) { - if (!_purgeQueued) + if (!this._purgeQueued) { - _purgeQueued = true; - ThreadPool.QueueUserWorkItem(PurgeCallback); + this._purgeQueued = true; + ThreadPool.QueueUserWorkItem(this.PurgeCallback); } } } } - + private object GetFileLockObject(string id) { #if INDIVIDUAL_LOCKS @@ -285,39 +327,8 @@ private object GetFileLockObject(string id) return lockObject; #else - return _fileLock; + return this._fileLock; #endif } - -#if INDIVIDUAL_LOCKS - private static string GetEntryId(FileInfo fileinfo) { - string id = fileinfo.Name.Substring(0, fileinfo.Name.Length - s_tempFileExtension.Length); - return id; - } - - private void DiscardFileLockObject(string id) { - // lock on hashtable to prevent other writers - lock (_fileLocks) { - _fileLocks.Remove(id); - } - } -#endif - - private static string BuildFilePath(string id) - { - return CachePath + id + TempFileExtension; - } - - #region IImageStore Members - void IImageStore.Add(string id, byte[] data) - { - Add(id, data); - } - - bool IImageStore.TryTransmitIfContains(string id, HttpResponseBase response) - { - return TryTransmitIfContains(id, response); - } - #endregion } } diff --git a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs index ca01182f7b3..46a417f85f5 100644 --- a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs @@ -1,65 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Configuration; -using System.Drawing; -using System.Drawing.Imaging; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.GeneratedImage.FilterTransform; -using DotNetNuke.Services.GeneratedImage.StartTransform; -using DotNetNuke.Services.Localization.Internal; -using Assembly = System.Reflection.Assembly; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Configuration; + using System.Drawing; + using System.Drawing.Imaging; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.GeneratedImage.FilterTransform; + using DotNetNuke.Services.GeneratedImage.StartTransform; + using DotNetNuke.Services.Localization.Internal; + + using Assembly = System.Reflection.Assembly; + public class DnnImageHandler : ImageHandler { /// - /// While list of server folders where the system allow the dnn image handler to - /// read to serve image files from it and its subfolders + /// While list of server folders where the system allow the dnn image handler to + /// read to serve image files from it and its subfolders. /// - private static readonly string[] WhiteListFolderPaths = { + private static readonly string[] WhiteListFolderPaths = + { Globals.DesktopModulePath, Globals.ImagePath, - Globals.ApplicationPath + "/Portals/" + Globals.ApplicationPath + "/Portals/", }; - private static bool IsAllowedFilePathImage(string filePath) - { - var normalizeFilePath = NormalizeFilePath(filePath.Trim()); - - // Resources file cannot be served - if (filePath.EndsWith(".resources")) - { - return false; - } - - // File outside the white list cannot be served - return WhiteListFolderPaths.Any(normalizeFilePath.StartsWith); - } + private string _defaultImageFile = string.Empty; - private static string NormalizeFilePath(string filePath) + public DnnImageHandler() { - var normalizeFilePath = filePath.Replace("\\", "/"); - if (!normalizeFilePath.StartsWith("/")) - { - normalizeFilePath = "/" + normalizeFilePath; - } - return normalizeFilePath; - } + // Set default settings here + this.EnableClientCache = true; + this.EnableServerCache = true; + this.AllowStandalone = true; + this.LogSecurity = false; + this.EnableIPCount = false; + this.ImageCompression = 95; + DiskImageStore.PurgeInterval = new TimeSpan(0, 3, 0); + this.IPCountPurgeInterval = new TimeSpan(0, 5, 0); + this.IPCountMaxCount = 500; + this.ClientCacheExpiration = new TimeSpan(0, 10, 0); + this.AllowedDomains = new[] { string.Empty }; - private string _defaultImageFile = string.Empty; + // read settings from web.config + this.ReadSettings(); + } private Image EmptyImage { @@ -67,24 +65,24 @@ private Image EmptyImage { var emptyBmp = new Bitmap(1, 1, PixelFormat.Format1bppIndexed); emptyBmp.MakeTransparent(); - ContentType = ImageFormat.Png; + this.ContentType = ImageFormat.Png; - if (string.IsNullOrEmpty(_defaultImageFile)) + if (string.IsNullOrEmpty(this._defaultImageFile)) { return emptyBmp; } try { - var fullFilePath = HttpContext.Current.Server.MapPath(_defaultImageFile); + var fullFilePath = HttpContext.Current.Server.MapPath(this._defaultImageFile); - if (!File.Exists(fullFilePath) || !IsAllowedFilePathImage(_defaultImageFile)) + if (!File.Exists(fullFilePath) || !IsAllowedFilePathImage(this._defaultImageFile)) { return emptyBmp; } - var fi = new System.IO.FileInfo(_defaultImageFile); - ContentType = GetImageFormat(fi.Extension); + var fi = new System.IO.FileInfo(this._defaultImageFile); + this.ContentType = GetImageFormat(fi.Extension); using (var stream = new FileStream(fullFilePath, FileMode.Open)) { @@ -99,34 +97,15 @@ private Image EmptyImage } } - public DnnImageHandler() - { - // Set default settings here - EnableClientCache = true; - EnableServerCache = true; - AllowStandalone = true; - LogSecurity = false; - EnableIPCount = false; - ImageCompression = 95; - DiskImageStore.PurgeInterval = new TimeSpan(0, 3, 0); - IPCountPurgeInterval = new TimeSpan(0, 5, 0); - IPCountMaxCount = 500; - ClientCacheExpiration = new TimeSpan(0, 10, 0); - AllowedDomains = new[] { string.Empty }; - - // read settings from web.config - ReadSettings(); - } - // Add image generation logic here and return an instance of ImageInfo public override ImageInfo GenerateImage(NameValueCollection parameters) { - SetupCulture(); + this.SetupCulture(); - //which type of image should be generated ? + // which type of image should be generated ? string mode = string.IsNullOrEmpty(parameters["mode"]) ? "profilepic" : parameters["mode"].ToLowerInvariant(); - // We need to determine the output format + // We need to determine the output format string format = string.IsNullOrEmpty(parameters["format"]) ? "jpg" : parameters["format"].ToLowerInvariant(); // Lets retrieve the color @@ -139,26 +118,26 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) // Do we have a resizemode defined ? var resizeMode = string.IsNullOrEmpty(parameters["resizemode"]) ? ImageResizeMode.Fit : (ImageResizeMode)Enum.Parse(typeof(ImageResizeMode), parameters["ResizeMode"], true); - // Maximum sizes + // Maximum sizes int maxWidth = string.IsNullOrEmpty(parameters["MaxWidth"]) ? 0 : Convert.ToInt32(parameters["MaxWidth"]); int maxHeight = string.IsNullOrEmpty(parameters["MaxHeight"]) ? 0 : Convert.ToInt32(parameters["MaxHeight"]); // Any text ? - string text = string.IsNullOrEmpty(parameters["text"]) ? "" : parameters["text"]; + string text = string.IsNullOrEmpty(parameters["text"]) ? string.Empty : parameters["text"]; // Default Image - _defaultImageFile = string.IsNullOrEmpty(parameters["NoImage"]) ? string.Empty : parameters["NoImage"]; + this._defaultImageFile = string.IsNullOrEmpty(parameters["NoImage"]) ? string.Empty : parameters["NoImage"]; // Do we override caching for this image ? if (!string.IsNullOrEmpty(parameters["NoCache"])) { - EnableClientCache = false; - EnableServerCache = false; + this.EnableClientCache = false; + this.EnableServerCache = false; } try { - ContentType = GetImageFormat(format); + this.ContentType = GetImageFormat(format); switch (mode) { @@ -168,34 +147,49 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) { uid = -1; } + var uppTrans = new UserProfilePicTransform { - UserID = uid + UserID = uid, }; IFileInfo photoFile; - ContentType = !uppTrans.TryGetPhotoFile(out photoFile) + this.ContentType = !uppTrans.TryGetPhotoFile(out photoFile) ? ImageFormat.Gif : GetImageFormat(photoFile?.Extension ?? "jpg"); - ImageTransforms.Add(uppTrans); + this.ImageTransforms.Add(uppTrans); break; case "placeholder": var placeHolderTrans = new PlaceholderTransform(); int width, height; - if (TryParseDimension(parameters["w"], out width)) - placeHolderTrans.Width = width; - if (TryParseDimension(parameters["h"], out height)) - placeHolderTrans.Height = height; - if (!string.IsNullOrEmpty(parameters["Color"])) - placeHolderTrans.Color = color; - if (!string.IsNullOrEmpty(parameters["Text"])) - placeHolderTrans.Text = text; - if (!string.IsNullOrEmpty(parameters["BackColor"])) - placeHolderTrans.BackColor = backColor; - - ImageTransforms.Add(placeHolderTrans); + if (TryParseDimension(parameters["w"], out width)) + { + placeHolderTrans.Width = width; + } + + if (TryParseDimension(parameters["h"], out height)) + { + placeHolderTrans.Height = height; + } + + if (!string.IsNullOrEmpty(parameters["Color"])) + { + placeHolderTrans.Color = color; + } + + if (!string.IsNullOrEmpty(parameters["Text"])) + { + placeHolderTrans.Text = text; + } + + if (!string.IsNullOrEmpty(parameters["BackColor"])) + { + placeHolderTrans.BackColor = backColor; + } + + this.ImageTransforms.Add(placeHolderTrans); break; case "securefile": @@ -206,25 +200,28 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) var file = FileManager.Instance.GetFile(fileId); if (file == null) { - return GetEmptyImageInfo(); + return this.GetEmptyImageInfo(); } + var folder = FolderManager.Instance.GetFolder(file.FolderId); if (!secureFileTrans.DoesHaveReadFolderPermission(folder)) { - return GetEmptyImageInfo(); + return this.GetEmptyImageInfo(); } - ContentType = GetImageFormat(file.Extension); + + this.ContentType = GetImageFormat(file.Extension); secureFileTrans.SecureFile = file; - secureFileTrans.EmptyImage = EmptyImage; - ImageTransforms.Add(secureFileTrans); + secureFileTrans.EmptyImage = this.EmptyImage; + this.ImageTransforms.Add(secureFileTrans); } + break; case "file": var imgFile = string.Empty; var imgUrl = string.Empty; - // Lets determine the 2 types of Image Source: Single file, file url + // Lets determine the 2 types of Image Source: Single file, file url var filePath = parameters["File"]; if (!string.IsNullOrEmpty(filePath)) { @@ -232,17 +229,19 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) var fullFilePath = HttpContext.Current.Server.MapPath(filePath); if (!File.Exists(fullFilePath) || !IsAllowedFilePathImage(filePath)) { - return GetEmptyImageInfo(); + return this.GetEmptyImageInfo(); } + imgFile = fullFilePath; } else if (!string.IsNullOrEmpty(parameters["Url"])) { var url = parameters["Url"]; + // allow only site resources when using the url parameter if (!url.StartsWith("http") || !UriBelongsToSite(new Uri(url))) { - return GetEmptyImageInfo(); + return this.GetEmptyImageInfo(); } imgUrl = url; @@ -261,10 +260,12 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) string[] parts = parameters["Url"].Split('.'); extension = parts[parts.Length - 1].ToLowerInvariant(); } - ContentType = GetImageFormat(extension); + + this.ContentType = GetImageFormat(extension); } - var imageFileTrans = new ImageFileTransform { ImageFilePath = imgFile, ImageUrl = imgUrl}; - ImageTransforms.Add(imageFileTrans); + + var imageFileTrans = new ImageFileTransform { ImageFilePath = imgFile, ImageUrl = imgUrl }; + this.ImageTransforms.Add(imageFileTrans); break; default: @@ -302,18 +303,20 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) pi.SetValue(imageTransform, parameters[key], null); break; } + break; } } } - ImageTransforms.Add(imageTransform); + + this.ImageTransforms.Add(imageTransform); break; } } catch (Exception ex) { Exceptions.Exceptions.LogException(ex); - return GetEmptyImageInfo(); + return this.GetEmptyImageInfo(); } // Resize-Transformation @@ -324,7 +327,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) TryParseDimension(parameters["w"], out width); TryParseDimension(parameters["h"], out height); - var size = string.IsNullOrEmpty(parameters["size"]) ? "" : parameters["size"]; + var size = string.IsNullOrEmpty(parameters["size"]) ? string.Empty : parameters["size"]; switch (size) { @@ -357,7 +360,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) if (mode == "profilepic") { resizeMode = ImageResizeMode.FitSquare; - if (width>0 && height>0 && width != height) + if (width > 0 && height > 0 && width != height) { resizeMode = ImageResizeMode.Fill; } @@ -373,9 +376,9 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) Height = height, MaxWidth = maxWidth, MaxHeight = maxHeight, - Border = border + Border = border, }; - ImageTransforms.Add(resizeTrans); + this.ImageTransforms.Add(resizeTrans); } } @@ -387,7 +390,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) if (double.TryParse(parameters["Gamma"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out gamma) && gamma >= 0.2 && gamma <= 5) { gammaTrans.Gamma = gamma; - ImageTransforms.Add(gammaTrans); + this.ImageTransforms.Add(gammaTrans); } } @@ -399,7 +402,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) if (int.TryParse(parameters["Brightness"], out brightness)) { brightnessTrans.Brightness = brightness; - ImageTransforms.Add(brightnessTrans); + this.ImageTransforms.Add(brightnessTrans); } } @@ -411,7 +414,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) if (double.TryParse(parameters["Contrast"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out contrast) && (contrast >= -100 && contrast <= 100)) { contrastTrans.Contrast = contrast; - ImageTransforms.Add(contrastTrans); + this.ImageTransforms.Add(contrastTrans); } } @@ -419,41 +422,57 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) if (!string.IsNullOrEmpty(parameters["Greyscale"])) { var greyscaleTrans = new ImageGreyScaleTransform(); - ImageTransforms.Add(greyscaleTrans); + this.ImageTransforms.Add(greyscaleTrans); } // Invert if (!string.IsNullOrEmpty(parameters["Invert"])) { var invertTrans = new ImageInvertTransform(); - ImageTransforms.Add(invertTrans); + this.ImageTransforms.Add(invertTrans); } - // Rotate / Flip + // Rotate / Flip if (!string.IsNullOrEmpty(parameters["RotateFlip"])) { var rotateFlipTrans = new ImageRotateFlipTransform(); var rotateFlipType = (RotateFlipType)Enum.Parse(typeof(RotateFlipType), parameters["RotateFlip"]); rotateFlipTrans.RotateFlip = rotateFlipType; - ImageTransforms.Add(rotateFlipTrans); - + this.ImageTransforms.Add(rotateFlipTrans); } // We start the chain with an empty image var dummy = new Bitmap(1, 1); using (var ms = new MemoryStream()) { - dummy.Save(ms, ContentType); + dummy.Save(ms, this.ContentType); return new ImageInfo(ms.ToArray()); } } - private ImageInfo GetEmptyImageInfo() + private static bool IsAllowedFilePathImage(string filePath) { - return new ImageInfo(EmptyImage) + var normalizeFilePath = NormalizeFilePath(filePath.Trim()); + + // Resources file cannot be served + if (filePath.EndsWith(".resources")) { - IsEmptyImage = true - }; + return false; + } + + // File outside the white list cannot be served + return WhiteListFolderPaths.Any(normalizeFilePath.StartsWith); + } + + private static string NormalizeFilePath(string filePath) + { + var normalizeFilePath = filePath.Replace("\\", "/"); + if (!normalizeFilePath.StartsWith("/")) + { + normalizeFilePath = "/" + normalizeFilePath; + } + + return normalizeFilePath; } private static bool TryParseDimension(string value, out int dimension) @@ -477,9 +496,53 @@ private static bool TryParseDimension(string value, out int dimension) dimension = 0; return false; } + return true; } + private static ImageFormat GetImageFormat(string extension) + { + switch (extension.ToLowerInvariant()) + { + case "jpg": + case "jpeg": + return ImageFormat.Jpeg; + case "bmp": + return ImageFormat.Bmp; + case "gif": + return ImageFormat.Gif; + case "png": + return ImageFormat.Png; + case "ico": + return ImageFormat.Icon; + default: + return ImageFormat.Png; + } + } + + // checks whether the uri belongs to any of the site-wide aliases + private static bool UriBelongsToSite(Uri uri) + { + IEnumerable hostAliases = + from PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliases().Values + select alias.HTTPAlias.ToLowerInvariant(); + + // if URI, for example, = "http(s)://myDomain:80/DNNDev/myPage?var=name" , then the two strings will be + // uriNoScheme1 = "mydomain/dnndev/mypage" -- lower case + // uriNoScheme2 = "mydomain:80/dnndev/mypage" -- lower case + var uriNoScheme1 = (uri.DnsSafeHost + uri.LocalPath).ToLowerInvariant(); + var uriNoScheme2 = (uri.Authority + uri.LocalPath).ToLowerInvariant(); + return hostAliases.Any(alias => uriNoScheme1.StartsWith(alias) || uriNoScheme2.StartsWith(alias)); + } + + private ImageInfo GetEmptyImageInfo() + { + return new ImageInfo(this.EmptyImage) + { + IsEmptyImage = true, + }; + } + private void ReadSettings() { var settings = ConfigurationManager.AppSettings["DnnImageHandler"]; @@ -496,37 +559,37 @@ private void ReadSettings() switch (name) { case "enableclientcache": - EnableClientCache = Convert.ToBoolean(setting[1]); + this.EnableClientCache = Convert.ToBoolean(setting[1]); break; case "clientcacheexpiration": - ClientCacheExpiration = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); + this.ClientCacheExpiration = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); break; case "enableservercache": - EnableServerCache = Convert.ToBoolean(setting[1]); + this.EnableServerCache = Convert.ToBoolean(setting[1]); break; case "servercacheexpiration": DiskImageStore.PurgeInterval = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); break; case "allowstandalone": - AllowStandalone = Convert.ToBoolean(setting[1]); + this.AllowStandalone = Convert.ToBoolean(setting[1]); break; case "logsecurity": - LogSecurity = Convert.ToBoolean(setting[1]); + this.LogSecurity = Convert.ToBoolean(setting[1]); break; case "imagecompression": - ImageCompression = Convert.ToInt32(setting[1]); + this.ImageCompression = Convert.ToInt32(setting[1]); break; case "alloweddomains": - AllowedDomains = setting[1].Split(','); + this.AllowedDomains = setting[1].Split(','); break; case "enableipcount": - EnableIPCount = Convert.ToBoolean(setting[1]); + this.EnableIPCount = Convert.ToBoolean(setting[1]); break; case "ipcountmax": - IPCountMaxCount = Convert.ToInt32(setting[1]); + this.IPCountMaxCount = Convert.ToInt32(setting[1]); break; case "ipcountpurgeinterval": - IPCountPurgeInterval = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); + this.IPCountPurgeInterval = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); break; } } @@ -535,48 +598,16 @@ private void ReadSettings() private void SetupCulture() { var settings = PortalController.Instance.GetCurrentPortalSettings(); - if (settings == null) return; - + if (settings == null) + { + return; + } + var pageLocale = TestableLocalization.Instance.GetPageLocale(settings); if (pageLocale != null) { TestableLocalization.Instance.SetThreadCultures(pageLocale, settings); } } - - private static ImageFormat GetImageFormat(string extension) - { - switch (extension.ToLowerInvariant()) - { - case "jpg": - case "jpeg": - return ImageFormat.Jpeg; - case "bmp": - return ImageFormat.Bmp; - case "gif": - return ImageFormat.Gif; - case "png": - return ImageFormat.Png; - case "ico": - return ImageFormat.Icon; - default: - return ImageFormat.Png; - } - } - - // checks whether the uri belongs to any of the site-wide aliases - private static bool UriBelongsToSite(Uri uri) - { - IEnumerable hostAliases = - from PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliases().Values - select alias.HTTPAlias.ToLowerInvariant(); - - // if URI, for example, = "http(s)://myDomain:80/DNNDev/myPage?var=name" , then the two strings will be - // uriNoScheme1 = "mydomain/dnndev/mypage" -- lower case - // uriNoScheme2 = "mydomain:80/dnndev/mypage" -- lower case - var uriNoScheme1 = (uri.DnsSafeHost + uri.LocalPath).ToLowerInvariant(); - var uriNoScheme2 = (uri.Authority + uri.LocalPath).ToLowerInvariant(); - return hostAliases.Any(alias => uriNoScheme1.StartsWith(alias) || uriNoScheme2.StartsWith(alias)); - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs index 95ddfd09147..804aac37bfb 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs @@ -1,70 +1,100 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Drawing.Drawing2D; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.FilterTransform { + using System.Drawing; + using System.Drawing.Drawing2D; + /// - /// Brightness ImageTransform class + /// Brightness ImageTransform class. /// - public class ImageBrightnessTransform : ImageTransform - { - /// - /// Sets the brightness value. Defaultvalue is 0. Range is -255 .. 255 - /// - public int Brightness { get; set; } - + public class ImageBrightnessTransform : ImageTransform + { + public ImageBrightnessTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Brightness = 0; + } + /// - /// Provides an Unique String for this class + /// Gets or sets the brightness value. Defaultvalue is 0. Range is -255 .. 255. /// - public override string UniqueString => base.UniqueString + "-" + Brightness; + public int Brightness { get; set; } - public ImageBrightnessTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - Brightness = 0; - } + /// + /// Gets provides an Unique String for this class. + /// + public override string UniqueString => base.UniqueString + "-" + this.Brightness; /// - /// Processes an input image applying a brightness image transformation + /// Processes an input image applying a brightness image transformation. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { - var temp = (Bitmap)image; - var bmap = (Bitmap)temp.Clone(); - if (Brightness < -255) Brightness = -255; - if (Brightness > 255) Brightness = 255; - Color c; - for (int i = 0; i < bmap.Width; i++) - { - for (int j = 0; j < bmap.Height; j++) - { - c = bmap.GetPixel(i, j); - int cR = c.R + Brightness; - int cG = c.G + Brightness; - int cB = c.B + Brightness; - - if (cR < 0) cR = 1; - if (cR > 255) cR = 255; - - if (cG < 0) cG = 1; - if (cG > 255) cG = 255; - - if (cB < 0) cB = 1; - if (cB > 255) cB = 255; + { + var temp = (Bitmap)image; + var bmap = (Bitmap)temp.Clone(); + if (this.Brightness < -255) + { + this.Brightness = -255; + } + + if (this.Brightness > 255) + { + this.Brightness = 255; + } + + Color c; + for (int i = 0; i < bmap.Width; i++) + { + for (int j = 0; j < bmap.Height; j++) + { + c = bmap.GetPixel(i, j); + int cR = c.R + this.Brightness; + int cG = c.G + this.Brightness; + int cB = c.B + this.Brightness; - bmap.SetPixel(i, j, Color.FromArgb((byte)cR, (byte)cG, (byte)cB)); - } - } - return (Bitmap)bmap.Clone(); - } - } + if (cR < 0) + { + cR = 1; + } + + if (cR > 255) + { + cR = 255; + } + + if (cG < 0) + { + cG = 1; + } + + if (cG > 255) + { + cG = 255; + } + + if (cB < 0) + { + cB = 1; + } + + if (cB > 255) + { + cB = 255; + } + + bmap.SetPixel(i, j, Color.FromArgb((byte)cR, (byte)cG, (byte)cB)); + } + } + + return (Bitmap)bmap.Clone(); + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs index ebfdf9f0041..f69e5cc12c1 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs @@ -1,83 +1,113 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Drawing.Drawing2D; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.FilterTransform { + using System.Drawing; + using System.Drawing.Drawing2D; + /// - /// Constrast ImageTransform class + /// Constrast ImageTransform class. /// - public class ImageContrastTransform : ImageTransform - { - /// - /// Sets the contrast value. Defaultvalue is 0. Range is -100 .. 100 - /// - public double Contrast { get; set; } - + public class ImageContrastTransform : ImageTransform + { + public ImageContrastTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Contrast = 0; + } + /// - /// Provides an Unique String for this class + /// Gets or sets the contrast value. Defaultvalue is 0. Range is -100 .. 100. /// - public override string UniqueString => base.UniqueString + "-" + Contrast; + public double Contrast { get; set; } - public ImageContrastTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - Contrast = 0; - } + /// + /// Gets provides an Unique String for this class. + /// + public override string UniqueString => base.UniqueString + "-" + this.Contrast; /// - /// Processes an input image applying a contrast image transformation + /// Processes an input image applying a contrast image transformation. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { - var temp = (Bitmap)image; - var bmap = (Bitmap)temp.Clone(); - if (Contrast < -100) Contrast = -100; - if (Contrast > 100) Contrast = 100; - Contrast = (100.0 + Contrast) / 100.0; - Contrast *= Contrast; - Color c; - for (int i = 0; i < bmap.Width; i++) - { - for (int j = 0; j < bmap.Height; j++) - { - c = bmap.GetPixel(i, j); - double pR = c.R / 255.0; - pR -= 0.5; - pR *= Contrast; - pR += 0.5; - pR *= 255; - if (pR < 0) pR = 0; - if (pR > 255) pR = 255; - - double pG = c.G / 255.0; - pG -= 0.5; - pG *= Contrast; - pG += 0.5; - pG *= 255; - if (pG < 0) pG = 0; - if (pG > 255) pG = 255; - - double pB = c.B / 255.0; - pB -= 0.5; - pB *= Contrast; - pB += 0.5; - pB *= 255; - if (pB < 0) pB = 0; - if (pB > 255) pB = 255; - - bmap.SetPixel(i, j, Color.FromArgb((byte)pR, (byte)pG, (byte)pB)); - } - } - return (Bitmap)bmap.Clone(); - } - } + { + var temp = (Bitmap)image; + var bmap = (Bitmap)temp.Clone(); + if (this.Contrast < -100) + { + this.Contrast = -100; + } + + if (this.Contrast > 100) + { + this.Contrast = 100; + } + + this.Contrast = (100.0 + this.Contrast) / 100.0; + this.Contrast *= this.Contrast; + Color c; + for (int i = 0; i < bmap.Width; i++) + { + for (int j = 0; j < bmap.Height; j++) + { + c = bmap.GetPixel(i, j); + double pR = c.R / 255.0; + pR -= 0.5; + pR *= this.Contrast; + pR += 0.5; + pR *= 255; + if (pR < 0) + { + pR = 0; + } + + if (pR > 255) + { + pR = 255; + } + + double pG = c.G / 255.0; + pG -= 0.5; + pG *= this.Contrast; + pG += 0.5; + pG *= 255; + if (pG < 0) + { + pG = 0; + } + + if (pG > 255) + { + pG = 255; + } + + double pB = c.B / 255.0; + pB -= 0.5; + pB *= this.Contrast; + pB += 0.5; + pB *= 255; + if (pB < 0) + { + pB = 0; + } + + if (pB > 255) + { + pB = 255; + } + + bmap.SetPixel(i, j, Color.FromArgb((byte)pR, (byte)pG, (byte)pB)); + } + } + + return (Bitmap)bmap.Clone(); + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs index e99eb0647ea..0078d94d812 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs @@ -1,63 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Drawing; -using System.Drawing.Drawing2D; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.FilterTransform { + using System; + using System.Drawing; + using System.Drawing.Drawing2D; + /// - /// Gamma ImageTransform class + /// Gamma ImageTransform class. /// public class ImageGammaTransform : ImageTransform - { - /// - /// Sets the gamma value. Defaultvalue is 0. Range is 0.2 .. 5 - /// - public double Gamma { get; set; } - + { + public ImageGammaTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Gamma = 1; + } + /// - /// Provides an Unique String for this class + /// Gets or sets the gamma value. Defaultvalue is 0. Range is 0.2 .. 5. /// - public override string UniqueString => base.UniqueString + "-" + Gamma; + public double Gamma { get; set; } - public ImageGammaTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - Gamma = 1; - } + /// + /// Gets provides an Unique String for this class. + /// + public override string UniqueString => base.UniqueString + "-" + this.Gamma; /// - /// Processes an input image applying a gamma image transformation + /// Processes an input image applying a gamma image transformation. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { - var temp = (Bitmap)image; - var bmap = (Bitmap)temp.Clone(); - Color c; - byte[] gammaArray = new byte[256]; - for (var i = 0; i < 256; ++i) - { - gammaArray[i] = (byte)Math.Min(255, (int)((255.0 * Math.Pow(i / 255.0, 1.0 / Gamma)) + 0.5)); - } - - for (var i = 0; i < bmap.Width; i++) - { - for (var j = 0; j < bmap.Height; j++) - { - c = bmap.GetPixel(i, j); - bmap.SetPixel(i, j, Color.FromArgb(gammaArray[c.R], - gammaArray[c.G], gammaArray[c.B])); - } - } - return (Image)bmap.Clone(); - } - } + { + var temp = (Bitmap)image; + var bmap = (Bitmap)temp.Clone(); + Color c; + byte[] gammaArray = new byte[256]; + for (var i = 0; i < 256; ++i) + { + gammaArray[i] = (byte)Math.Min(255, (int)((255.0 * Math.Pow(i / 255.0, 1.0 / this.Gamma)) + 0.5)); + } + + for (var i = 0; i < bmap.Width; i++) + { + for (var j = 0; j < bmap.Height; j++) + { + c = bmap.GetPixel(i, j); + bmap.SetPixel(i, j, Color.FromArgb( + gammaArray[c.R], + gammaArray[c.G], gammaArray[c.B])); + } + } + + return (Image)bmap.Clone(); + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs index 4f5d90d0e7a..e61e9904c8b 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs @@ -1,46 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Drawing.Drawing2D; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.FilterTransform { + using System.Drawing; + using System.Drawing.Drawing2D; + /// - /// Grey Scale ImageTransform class + /// Grey Scale ImageTransform class. /// - public class ImageGreyScaleTransform : ImageTransform - { - public ImageGreyScaleTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - } + public class ImageGreyScaleTransform : ImageTransform + { + public ImageGreyScaleTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } /// - /// Processes an input image applying a grey scale image transformation + /// Processes an input image applying a grey scale image transformation. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { - var temp = (Bitmap)image; - var bmap = (Bitmap)temp.Clone(); - Color c; - for (int i = 0; i < bmap.Width; i++) - { - for (int j = 0; j < bmap.Height; j++) - { - c = bmap.GetPixel(i, j); - byte gray = (byte)(.299 * c.R + .587 * c.G + .114 * c.B); + { + var temp = (Bitmap)image; + var bmap = (Bitmap)temp.Clone(); + Color c; + for (int i = 0; i < bmap.Width; i++) + { + for (int j = 0; j < bmap.Height; j++) + { + c = bmap.GetPixel(i, j); + byte gray = (byte)((.299 * c.R) + (.587 * c.G) + (.114 * c.B)); - bmap.SetPixel(i, j, Color.FromArgb(gray, gray, gray)); - } - } - return (Bitmap)bmap.Clone(); - } - } + bmap.SetPixel(i, j, Color.FromArgb(gray, gray, gray)); + } + } + + return (Bitmap)bmap.Clone(); + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs index 1ec4adefb5e..b93c81c8f2f 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs @@ -1,44 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Drawing.Drawing2D; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.FilterTransform { + using System.Drawing; + using System.Drawing.Drawing2D; + /// - /// Invert ImageTransform class + /// Invert ImageTransform class. /// - public class ImageInvertTransform : ImageTransform - { - public ImageInvertTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - } + public class ImageInvertTransform : ImageTransform + { + public ImageInvertTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } /// - /// Processes an input image applying an invert image transformation + /// Processes an input image applying an invert image transformation. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { - var temp = (Bitmap)image; - var bmap = (Bitmap)temp.Clone(); - Color c; - for (int i = 0; i < bmap.Width; i++) - { - for (int j = 0; j < bmap.Height; j++) - { - c = bmap.GetPixel(i, j); - bmap.SetPixel(i, j, Color.FromArgb(255 - c.R, 255 - c.G, 255 - c.B)); - } - } - return (Bitmap)bmap.Clone(); - } - } + { + var temp = (Bitmap)image; + var bmap = (Bitmap)temp.Clone(); + Color c; + for (int i = 0; i < bmap.Width; i++) + { + for (int j = 0; j < bmap.Height; j++) + { + c = bmap.GetPixel(i, j); + bmap.SetPixel(i, j, Color.FromArgb(255 - c.R, 255 - c.G, 255 - c.B)); + } + } + + return (Bitmap)bmap.Clone(); + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs index 35ff1df4799..70ee838dc0c 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs @@ -1,160 +1,189 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Drawing2D; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.FilterTransform { + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.Drawing; + using System.Drawing.Drawing2D; + /// - /// Resize ImageTransform class + /// Resize ImageTransform class. /// - public class ImageResizeTransform : ImageTransform - { - private int _width, _height, _border, _maxWidth, _maxHeight; + public class ImageResizeTransform : ImageTransform + { + private int _width; + private int _height; + private int _border; + private int _maxWidth; + private int _maxHeight; + + public ImageResizeTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Mode = ImageResizeMode.Fit; + } + + /// + /// Gets or sets the resize mode. The default value is Fit. + /// + public ImageResizeMode Mode { get; set; } /// - /// Sets the resize mode. The default value is Fit. - /// - public ImageResizeMode Mode { get; set; } - - /// - /// Sets the width of the resulting image - /// - public int Width { - get - { - return _width; - } - set - { - CheckValue(value); - _width = value; - } - } + /// Gets or sets the width of the resulting image. + /// + public int Width + { + get + { + return this._width; + } + + set + { + CheckValue(value); + this._width = value; + } + } /// - /// Sets the Max width of the resulting image + /// Gets or sets the Max width of the resulting image. /// public int MaxWidth { get { - return _maxWidth; + return this._maxWidth; } + set { CheckValue(value); - _maxWidth = value; + this._maxWidth = value; } } - /// - /// Sets the height of the resulting image - /// - public int Height { - get { - return _height; - } - set { - CheckValue(value); - _height = value; - } - } + /// + /// Gets or sets the height of the resulting image. + /// + public int Height + { + get + { + return this._height; + } + + set + { + CheckValue(value); + this._height = value; + } + } /// - /// Sets the max height of the resulting image + /// Gets or sets the max height of the resulting image. /// public int MaxHeight { get { - return _maxHeight; + return this._maxHeight; } + set { CheckValue(value); - _maxHeight = value; + this._maxHeight = value; } } - /// - /// Sets the border width of the resulting image - /// - public int Border - { - get - { - return _border; - } - set - { - CheckValue(value); - _border = value; - } - } - - /// - /// Sets the Backcolor - /// - public Color BackColor { get; set; } = Color.White; - - public ImageResizeTransform() { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - Mode = ImageResizeMode.Fit; - } + /// + /// Gets or sets the border width of the resulting image. + /// + public int Border + { + get + { + return this._border; + } + + set + { + CheckValue(value); + this._border = value; + } + } /// - /// Processes an input image applying a resize image transformation + /// Gets or sets the Backcolor. /// - /// Input image - /// Image result after image transformation + public Color BackColor { get; set; } = Color.White; + + /// + /// Gets provides an Unique String for this transformation. + /// + [Browsable(false)] + public override string UniqueString => base.UniqueString + this.Width + this.InterpolationMode + this.Height + this.Mode; + + /// + /// Processes an input image applying a resize image transformation. + /// + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) { - if (image == null) - return null; - - if (MaxWidth > 0) + if (image == null) + { + return null; + } + + if (this.MaxWidth > 0) { - Width = image.Width > MaxWidth ? MaxWidth : image.Width; + this.Width = image.Width > this.MaxWidth ? this.MaxWidth : image.Width; } - if (MaxHeight > 0) + if (this.MaxHeight > 0) { - Height = image.Height > MaxHeight ? MaxHeight : image.Height; + this.Height = image.Height > this.MaxHeight ? this.MaxHeight : image.Height; } - int scaledHeight = (int)(image.Height * ((float)Width / (float)image.Width)); - int scaledWidth = (int)(image.Width * ((float)Height / (float)image.Height)); - - Image procImage; - switch (Mode) { - case ImageResizeMode.Fit: - procImage = FitImage(image, scaledHeight, scaledWidth); - break; - case ImageResizeMode.Crop: - procImage = CropImage(image, scaledHeight, scaledWidth); - break; - case ImageResizeMode.FitSquare: - procImage = FitSquareImage(image); - break; - case ImageResizeMode.Fill: - procImage = FillImage(image); - break; + int scaledHeight = (int)(image.Height * ((float)this.Width / (float)image.Width)); + int scaledWidth = (int)(image.Width * ((float)this.Height / (float)image.Height)); + + Image procImage; + switch (this.Mode) + { + case ImageResizeMode.Fit: + procImage = this.FitImage(image, scaledHeight, scaledWidth); + break; + case ImageResizeMode.Crop: + procImage = this.CropImage(image, scaledHeight, scaledWidth); + break; + case ImageResizeMode.FitSquare: + procImage = this.FitSquareImage(image); + break; + case ImageResizeMode.Fill: + procImage = this.FillImage(image); + break; default: - Debug.Fail("Should not reach this"); - return null; - } - return procImage; - } - + Debug.Fail("Should not reach this"); + return null; + } + + return procImage; + } + + public override string ToString() + { + return "ImageResizeTransform"; + } + private static void CheckValue(int value) { if (value < 0) @@ -163,125 +192,123 @@ private static void CheckValue(int value) } } - private Image FitImage(Image img, int scaledHeight, int scaledWidth) { - int resizeWidth; - int resizeHeight; - if (Height == 0) { - resizeWidth = Width; - resizeHeight = scaledHeight; - } - else if (Width == 0) { - resizeWidth = scaledWidth; - resizeHeight = Height; - } - else { - if (((float)Width / (float)img.Width < Height / (float)img.Height)) { - resizeWidth = Width; - resizeHeight = scaledHeight; - } - else { - resizeWidth = scaledWidth; - resizeHeight = Height; - } - } - - var newimage = new Bitmap(resizeWidth + 2 * _border, resizeHeight + 2 * _border); - var graphics = Graphics.FromImage(newimage); - - graphics.CompositingMode = CompositingMode.SourceCopy; - graphics.CompositingQuality = CompositingQuality; - graphics.InterpolationMode = InterpolationMode; - graphics.SmoothingMode = SmoothingMode; - - graphics.FillRectangle(new SolidBrush(BackColor), new Rectangle(0, 0, resizeWidth + 2 * _border, resizeHeight + 2 * _border)); - graphics.DrawImage(img, _border, _border, resizeWidth, resizeHeight); - - return newimage; - } - - private Image FitSquareImage(Image img) - { - int resizeWidth; - int resizeHeight; - - int newDim = Width > 0 ? Width : Height; - - if (img.Height > img.Width) - { - resizeWidth = Convert.ToInt32((float)img.Width / (float)img.Height * newDim); - resizeHeight = newDim; - } - else - { - resizeWidth = newDim; - resizeHeight = Convert.ToInt32((float)img.Height / (float)img.Width * newDim); - } - - var newimage = new Bitmap(newDim + 2 * _border, newDim + 2 * _border); - var graphics = Graphics.FromImage(newimage); - - graphics.CompositingMode = CompositingMode.SourceCopy; - graphics.CompositingQuality = CompositingQuality; - graphics.InterpolationMode = InterpolationMode; - graphics.SmoothingMode = SmoothingMode; - - graphics.FillRectangle(new SolidBrush(BackColor),new Rectangle(0,0,newDim + 2*_border ,newDim + 2*_border)); - graphics.DrawImage(img, (newDim - resizeWidth) / 2 + _border, (newDim - resizeHeight) / 2 + _border, resizeWidth, resizeHeight); - return newimage; - } - - private Image CropImage(Image img, int scaledHeight, int scaledWidth) { - int resizeWidth; - int resizeHeight; - if ((float)Width / (float)img.Width > Height / (float)img.Height) { - resizeWidth = Width; - resizeHeight = scaledHeight; - } - else - { - resizeWidth = scaledWidth; - resizeHeight = Height; - } - - var newImage = new Bitmap(Width, Height); - var graphics = Graphics.FromImage(newImage); - - graphics.CompositingMode = CompositingMode.SourceCopy; - graphics.CompositingQuality = CompositingQuality; - graphics.InterpolationMode = InterpolationMode; - graphics.SmoothingMode = SmoothingMode; - graphics.PixelOffsetMode = PixelOffsetMode; - - graphics.DrawImage(img, (Width - resizeWidth) / 2, (Height - resizeHeight) / 2, resizeWidth, resizeHeight); - return newImage; - } + private Image FitImage(Image img, int scaledHeight, int scaledWidth) + { + int resizeWidth; + int resizeHeight; + if (this.Height == 0) + { + resizeWidth = this.Width; + resizeHeight = scaledHeight; + } + else if (this.Width == 0) + { + resizeWidth = scaledWidth; + resizeHeight = this.Height; + } + else + { + if ((float)this.Width / (float)img.Width < this.Height / (float)img.Height) + { + resizeWidth = this.Width; + resizeHeight = scaledHeight; + } + else + { + resizeWidth = scaledWidth; + resizeHeight = this.Height; + } + } - private Image FillImage(Image img) + var newimage = new Bitmap(resizeWidth + (2 * this._border), resizeHeight + (2 * this._border)); + var graphics = Graphics.FromImage(newimage); + + graphics.CompositingMode = CompositingMode.SourceCopy; + graphics.CompositingQuality = this.CompositingQuality; + graphics.InterpolationMode = this.InterpolationMode; + graphics.SmoothingMode = this.SmoothingMode; + + graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, resizeWidth + (2 * this._border), resizeHeight + (2 * this._border))); + graphics.DrawImage(img, this._border, this._border, resizeWidth, resizeHeight); + + return newimage; + } + + private Image FitSquareImage(Image img) + { + int resizeWidth; + int resizeHeight; + + int newDim = this.Width > 0 ? this.Width : this.Height; + + if (img.Height > img.Width) + { + resizeWidth = Convert.ToInt32((float)img.Width / (float)img.Height * newDim); + resizeHeight = newDim; + } + else + { + resizeWidth = newDim; + resizeHeight = Convert.ToInt32((float)img.Height / (float)img.Width * newDim); + } + + var newimage = new Bitmap(newDim + (2 * this._border), newDim + (2 * this._border)); + var graphics = Graphics.FromImage(newimage); + + graphics.CompositingMode = CompositingMode.SourceCopy; + graphics.CompositingQuality = this.CompositingQuality; + graphics.InterpolationMode = this.InterpolationMode; + graphics.SmoothingMode = this.SmoothingMode; + + graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, newDim + (2 * this._border), newDim + (2 * this._border))); + graphics.DrawImage(img, ((newDim - resizeWidth) / 2) + this._border, ((newDim - resizeHeight) / 2) + this._border, resizeWidth, resizeHeight); + return newimage; + } + + private Image CropImage(Image img, int scaledHeight, int scaledWidth) { - int resizeHeight = Height; - int resizeWidth = Width; - - var newImage = new Bitmap(Width, Height); + int resizeWidth; + int resizeHeight; + if ((float)this.Width / (float)img.Width > this.Height / (float)img.Height) + { + resizeWidth = this.Width; + resizeHeight = scaledHeight; + } + else + { + resizeWidth = scaledWidth; + resizeHeight = this.Height; + } + + var newImage = new Bitmap(this.Width, this.Height); var graphics = Graphics.FromImage(newImage); graphics.CompositingMode = CompositingMode.SourceCopy; - graphics.CompositingQuality = CompositingQuality; - graphics.InterpolationMode = InterpolationMode; - graphics.SmoothingMode = SmoothingMode; - graphics.PixelOffsetMode = PixelOffsetMode; + graphics.CompositingQuality = this.CompositingQuality; + graphics.InterpolationMode = this.InterpolationMode; + graphics.SmoothingMode = this.SmoothingMode; + graphics.PixelOffsetMode = this.PixelOffsetMode; - graphics.DrawImage(img, (Width - resizeWidth) / 2, (Height - resizeHeight) / 2, resizeWidth, resizeHeight); + graphics.DrawImage(img, (this.Width - resizeWidth) / 2, (this.Height - resizeHeight) / 2, resizeWidth, resizeHeight); return newImage; } - /// - /// Provides an Unique String for this transformation - /// - [Browsable(false)] - public override string UniqueString => base.UniqueString + Width + InterpolationMode + Height + Mode; + private Image FillImage(Image img) + { + int resizeHeight = this.Height; + int resizeWidth = this.Width; - public override string ToString() { - return "ImageResizeTransform"; - } - } + var newImage = new Bitmap(this.Width, this.Height); + var graphics = Graphics.FromImage(newImage); + + graphics.CompositingMode = CompositingMode.SourceCopy; + graphics.CompositingQuality = this.CompositingQuality; + graphics.InterpolationMode = this.InterpolationMode; + graphics.SmoothingMode = this.SmoothingMode; + graphics.PixelOffsetMode = this.PixelOffsetMode; + + graphics.DrawImage(img, (this.Width - resizeWidth) / 2, (this.Height - resizeHeight) / 2, resizeWidth, resizeHeight); + return newImage; + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs index 11dc3898a13..b35f5c7cb05 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs @@ -1,47 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Drawing.Drawing2D; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.FilterTransform { + using System.Drawing; + using System.Drawing.Drawing2D; + /// - /// Rotation ImageTransform class + /// Rotation ImageTransform class. /// - public class ImageRotateFlipTransform : ImageTransform - { - /// - /// Sets the type of rotation / flip . Defaultvalue is RotateNoneFlipNone - /// - public RotateFlipType RotateFlip { get; set; } + public class ImageRotateFlipTransform : ImageTransform + { + public ImageRotateFlipTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.RotateFlip = RotateFlipType.RotateNoneFlipNone; + } + + /// + /// Gets or sets the type of rotation / flip . Defaultvalue is RotateNoneFlipNone. + /// + public RotateFlipType RotateFlip { get; set; } /// - /// Provides an Unique String for this transformation + /// Gets provides an Unique String for this transformation. /// - public override string UniqueString => base.UniqueString + "-" + RotateFlip; + public override string UniqueString => base.UniqueString + "-" + this.RotateFlip; - public ImageRotateFlipTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - RotateFlip = RotateFlipType.RotateNoneFlipNone; - } - /// - /// Processes an input image applying a rotation image transformation + /// Processes an input image applying a rotation image transformation. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { - var temp = (Bitmap)image; - var bmap = (Bitmap)temp.Clone(); - bmap.RotateFlip(RotateFlip); - return (Bitmap)bmap.Clone(); - } - } + { + var temp = (Bitmap)image; + var bmap = (Bitmap)temp.Clone(); + bmap.RotateFlip(this.RotateFlip); + return (Bitmap)bmap.Clone(); + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs b/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs index ae640fb4066..c56e9f1ba7d 100644 --- a/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs +++ b/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Collections.Generic; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + public class GeneratedImage : Image { private const string TimestampField = "__timestamp"; @@ -19,15 +19,28 @@ public class GeneratedImage : Image private readonly HttpContextBase _context; private string _imageHandlerUrl; + public GeneratedImage() + { + this.Parameters = new List(); + } + + internal GeneratedImage(HttpContextBase context, Control bindingContainer) + : this() + { + this._context = context; + this._bindingContainer = bindingContainer; + } + public string ImageHandlerUrl { get { - return _imageHandlerUrl ?? string.Empty; + return this._imageHandlerUrl ?? string.Empty; } + set { - _imageHandlerUrl = value; + this._imageHandlerUrl = value; } } @@ -35,37 +48,27 @@ public string Timestamp { get { - return _timestamp ?? string.Empty; + return this._timestamp ?? string.Empty; } + set { - _timestamp = value; + this._timestamp = value; } } public List Parameters { get; } - private new HttpContextBase Context => _context ?? new HttpContextWrapper(HttpContext.Current); + private new HttpContextBase Context => this._context ?? new HttpContextWrapper(HttpContext.Current); - private new Control BindingContainer => _bindingContainer ?? base.BindingContainer; - - public GeneratedImage() - { - Parameters = new List(); - } - - internal GeneratedImage(HttpContextBase context, Control bindingContainer) : this() - { - _context = context; - _bindingContainer = bindingContainer; - } + private new Control BindingContainer => this._bindingContainer ?? base.BindingContainer; protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); - Control bindingContainer = BindingContainer; - foreach (var parameter in Parameters) + Control bindingContainer = this.BindingContainer; + foreach (var parameter in this.Parameters) { parameter.BindingContainer = bindingContainer; parameter.DataBind(); @@ -76,28 +79,36 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (DesignMode) + if (this.DesignMode) { return; } - ImageUrl = BuildImageUrl(); + this.ImageUrl = this.BuildImageUrl(); + } + + private static void AddQueryStringParameter(StringBuilder stringBuilder, bool paramAlreadyAdded, string name, string value) + { + stringBuilder.Append(paramAlreadyAdded ? '&' : '?'); + stringBuilder.Append(HttpUtility.UrlEncode(name)); + stringBuilder.Append('='); + stringBuilder.Append(HttpUtility.UrlEncode(value)); } private string BuildImageUrl() { var stringBuilder = new StringBuilder(); - stringBuilder.Append(ImageHandlerUrl); + stringBuilder.Append(this.ImageHandlerUrl); var paramAlreadyAdded = false; - foreach (var parameter in Parameters) + foreach (var parameter in this.Parameters) { AddQueryStringParameter(stringBuilder, paramAlreadyAdded, parameter.Name, parameter.Value); paramAlreadyAdded = true; } - string timeStamp = Timestamp?.Trim(); + string timeStamp = this.Timestamp?.Trim(); if (!string.IsNullOrEmpty(timeStamp)) { AddQueryStringParameter(stringBuilder, paramAlreadyAdded, TimestampField, timeStamp); @@ -105,13 +116,5 @@ private string BuildImageUrl() return stringBuilder.ToString(); } - - private static void AddQueryStringParameter(StringBuilder stringBuilder, bool paramAlreadyAdded, string name, string value) - { - stringBuilder.Append(paramAlreadyAdded ? '&' : '?'); - stringBuilder.Append(HttpUtility.UrlEncode(name)); - stringBuilder.Append('='); - stringBuilder.Append(HttpUtility.UrlEncode(value)); - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs index e3ab00b9ff5..efb376bdef9 100644 --- a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs +++ b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utils; -using DotNetNuke.Services.UserRequest; -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Threading; -using System.Web; -using System.Web.Hosting; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Threading; + using System.Web; + using System.Web.Hosting; + + using DotNetNuke.Common.Utils; + using DotNetNuke.Services.UserRequest; + public class IPCount { private const string TempFileExtension = ".tmp"; @@ -24,19 +25,29 @@ public class IPCount private static TimeSpan _purgeInterval; private static readonly object FileLock = new object(); + static IPCount() + { + PurgeInterval = new TimeSpan(0, 10, 0); + MaxCount = 500; + CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); + } + public static string CachePath { get { return _cachePath; } + set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(value)); } + if (!Directory.Exists(value)) { Directory.CreateDirectory(value); } + _cachePath = value; } } @@ -47,16 +58,19 @@ public static TimeSpan PurgeInterval { return _purgeInterval; } + set { if (value == null) { throw new ArgumentNullException(nameof(value)); } + if (value.Ticks < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } + _purgeInterval = value; } } @@ -75,23 +89,18 @@ private static DateTime LastPurge } else { - File.WriteAllText(CachePath + "_lastpurge", ""); + File.WriteAllText(CachePath + "_lastpurge", string.Empty); } + return lastPurge; } + set { - File.WriteAllText(CachePath + "_lastpurge", ""); + File.WriteAllText(CachePath + "_lastpurge", string.Empty); } } - static IPCount() - { - PurgeInterval = new TimeSpan(0, 10, 0); - MaxCount = 500; - CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); - } - public static bool CheckIp(string ipAddress) { var now = DateTime.Now; @@ -120,6 +129,7 @@ public static bool CheckIp(string ipAddress) } } } + Thread.Sleep(0); foreach (var fileinfo in toTryDeleteAgain) { @@ -132,13 +142,14 @@ public static bool CheckIp(string ipAddress) // do nothing at this point, try to delete file during next purge } } + LastPurge = DateTime.Now; _purgeQueued = false; } } } - + var path = BuildFilePath(ipAddress); var count = 1; lock (FileLock) @@ -148,32 +159,35 @@ public static bool CheckIp(string ipAddress) var strCount = File.ReadAllText(path); if (int.TryParse(strCount, out count)) { - if (count > MaxCount) - return false; - + if (count > MaxCount) + { + return false; + } + count++; } } + File.WriteAllText(path, count.ToString()); return true; } } - private static string BuildFilePath(string ipAddress) - { - // it takes only the IP address without PORT for the file name - var fileName = ipAddress.Split(':')[0]; - return CachePath + fileName + TempFileExtension; - } - /// - /// method to get Client ip address + /// method to get Client ip address. /// - /// IP Address of visitor + /// IP Address of visitor. [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] public static string GetVisitorIPAddress(HttpContextBase context) { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(context.Request); + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(context.Request); + } + + private static string BuildFilePath(string ipAddress) + { + // it takes only the IP address without PORT for the file name + var fileName = ipAddress.Split(':')[0]; + return CachePath + fileName + TempFileExtension; } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs b/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs index 36174075069..cfbebcb8013 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs @@ -1,155 +1,156 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Diagnostics; -using System.Drawing.Imaging; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Diagnostics; + using System.Drawing.Imaging; + using System.Web; + /// - /// Image Handler abstract class + /// Image Handler abstract class. /// public abstract class ImageHandler : IHttpHandler { - private ImageHandlerInternal Implementation { get; set; } + internal ImageHandler(IImageStore imageStore, DateTime now) + : this(new ImageHandlerInternal(imageStore, now)) + { + } + + protected ImageHandler() + : this(new ImageHandlerInternal()) + { + } + + private ImageHandler(ImageHandlerInternal implementation) + { + this.Implementation = implementation; + } /// - /// Enables server-side caching of the result + /// Gets or sets a value indicating whether enables server-side caching of the result. /// public bool EnableServerCache { - get { return Implementation.EnableServerCache; } - set { Implementation.EnableServerCache = value; } + get { return this.Implementation.EnableServerCache; } + set { this.Implementation.EnableServerCache = value; } } /// - /// Enables client-side caching of the result + /// Gets or sets a value indicating whether enables client-side caching of the result. /// public bool EnableClientCache { - get { return Implementation.EnableClientCache; } - set { Implementation.EnableClientCache = value; } + get { return this.Implementation.EnableClientCache; } + set { this.Implementation.EnableClientCache = value; } } + + private ImageHandlerInternal Implementation { get; set; } /// - /// Sets the client-side cache expiration time + /// Gets or sets the client-side cache expiration time. /// public TimeSpan ClientCacheExpiration { - get { return Implementation.ClientCacheExpiration; } - set { Implementation.ClientCacheExpiration = value; } + get { return this.Implementation.ClientCacheExpiration; } + set { this.Implementation.ClientCacheExpiration = value; } } /// - /// List of Domains who are allowed to use the imagehandler when security is enabled + /// Gets or sets list of Domains who are allowed to use the imagehandler when security is enabled. /// public string[] AllowedDomains { - get { return Implementation.AllowedDomains; } - set { Implementation.AllowedDomains = value; } + get { return this.Implementation.AllowedDomains; } + set { this.Implementation.AllowedDomains = value; } } public bool AllowStandalone { - get { return Implementation.AllowStandalone; } - set { Implementation.AllowStandalone = value; } + get { return this.Implementation.AllowStandalone; } + set { this.Implementation.AllowStandalone = value; } } public bool LogSecurity { - get { return Implementation.LogSecurity; } - set { Implementation.LogSecurity = value; } + get { return this.Implementation.LogSecurity; } + set { this.Implementation.LogSecurity = value; } } /// - /// Sets the type of the result image. The handler will return ouput with MIME type matching this content + /// Gets or sets the type of the result image. The handler will return ouput with MIME type matching this content. /// public ImageFormat ContentType { - get { return Implementation.ContentType; } - set { Implementation.ContentType = value; } + get { return this.Implementation.ContentType; } + set { this.Implementation.ContentType = value; } } /// - /// Sets the image compression encoding for the result image. Default is 50L + /// Gets or sets the image compression encoding for the result image. Default is 50L. /// public long ImageCompression { - get { return Implementation.ImageCompression; } - set { Implementation.ImageCompression = value; } + get { return this.Implementation.ImageCompression; } + set { this.Implementation.ImageCompression = value; } } /// - /// Enables block mechanism for DDOS by referring IP + /// Gets or sets a value indicating whether enables block mechanism for DDOS by referring IP. /// public bool EnableIPCount { - get { return Implementation.EnableIPCount; } - set { Implementation.EnableIPCount = value; } + get { return this.Implementation.EnableIPCount; } + set { this.Implementation.EnableIPCount = value; } } - + /// - /// Sets the maximum amount of images an IP address is allowed to generate - /// in the defined purge interval + /// Gets or sets the maximum amount of images an IP address is allowed to generate + /// in the defined purge interval. /// public int IPCountMaxCount { - get { return Implementation.IPCountMax; } - set { Implementation.IPCountMax = value; } + get { return this.Implementation.IPCountMax; } + set { this.Implementation.IPCountMax = value; } } /// - /// Timespan for resetting the blocking + /// Gets or sets timespan for resetting the blocking. /// public TimeSpan IPCountPurgeInterval { - get { return Implementation.IpCountPurgeInterval; } - set { Implementation.IpCountPurgeInterval = value; } + get { return this.Implementation.IpCountPurgeInterval; } + set { this.Implementation.IpCountPurgeInterval = value; } } + public virtual bool IsReusable => false; + /// - /// A list of image transforms that will be applied successively to the image + /// Gets a list of image transforms that will be applied successively to the image. /// - protected List ImageTransforms => Implementation.ImageTransforms; - - protected ImageHandler() - : this(new ImageHandlerInternal()) - { - } - - private ImageHandler(ImageHandlerInternal implementation) - { - Implementation = implementation; - } - - internal ImageHandler(IImageStore imageStore, DateTime now) - : this(new ImageHandlerInternal(imageStore, now)) - { - } + protected List ImageTransforms => this.Implementation.ImageTransforms; public abstract ImageInfo GenerateImage(NameValueCollection parameters); - public virtual bool IsReusable => false; - public void ProcessRequest(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } + HttpContextBase contextWrapper = new HttpContextWrapper(context); - ProcessRequest(contextWrapper); + this.ProcessRequest(contextWrapper); } internal void ProcessRequest(HttpContextBase context) { Debug.Assert(context != null); - Implementation.HandleImageRequest(context, GenerateImage, ToString()); + this.Implementation.HandleImageRequest(context, this.GenerateImage, this.ToString()); } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs index 8fe8919b5e4..94ffb31eafc 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs @@ -1,28 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.GeneratedImage.ImageQuantization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.UserRequest; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Diagnostics; + using System.Drawing; + using System.Drawing.Imaging; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.GeneratedImage.ImageQuantization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.UserRequest; + internal class ImageHandlerInternal { private static TimeSpan defaultClientCacheExpiration = new TimeSpan(0, 10, 0); @@ -31,20 +32,37 @@ internal class ImageHandlerInternal private IImageStore _imageStore; private DateTime? _now; + public ImageHandlerInternal() + { + this.ContentType = ImageFormat.Jpeg; + this.ImageCompression = 95; + this.ImageTransforms = new List(); + this.AllowStandalone = false; + } + + internal ImageHandlerInternal(IImageStore imageStore, DateTime now) + : this() + { + this._imageStore = imageStore; + this._now = now; + } + public TimeSpan ClientCacheExpiration { get { - return _clientCacheExpiration; + return this._clientCacheExpiration; } + set { if (value.Ticks < 0) { throw new ArgumentOutOfRangeException(nameof(value), "ClientCacheExpiration must be positive"); } - _clientCacheExpiration = value; - EnableClientCache = true; + + this._clientCacheExpiration = value; + this.EnableClientCache = true; } } @@ -52,11 +70,23 @@ public TimeSpan ClientCacheExpiration public long ImageCompression { get; set; } + public int IPCountMax + { + get { return IPCount.MaxCount; } + set { IPCount.MaxCount = value; } + } + + public TimeSpan IpCountPurgeInterval + { + get { return IPCount.PurgeInterval; } + set { IPCount.PurgeInterval = value; } + } + private DateTime DateTime_Now { get { - return _now ?? DateTime.Now; + return this._now ?? DateTime.Now; } } @@ -64,22 +94,10 @@ private IImageStore ImageStore { get { - return _imageStore ?? DiskImageStore.Instance; + return this._imageStore ?? DiskImageStore.Instance; } } - public int IPCountMax - { - set { IPCount.MaxCount = value; } - get { return IPCount.MaxCount; } - } - - public TimeSpan IpCountPurgeInterval - { - set { IPCount.PurgeInterval = value; } - get { return IPCount.PurgeInterval; } - } - public bool EnableClientCache { get; set; } public bool EnableServerCache { get; set; } @@ -98,53 +116,6 @@ public List ImageTransforms private set; } - public ImageHandlerInternal() - { - ContentType = ImageFormat.Jpeg; - ImageCompression = 95; - ImageTransforms = new List(); - AllowStandalone = false; - } - - internal ImageHandlerInternal(IImageStore imageStore, DateTime now) - : this() - { - _imageStore = imageStore; - _now = now; - } - - internal static string GetImageMimeType(ImageFormat format) - { - string mimeType = "image/x-unknown"; - - if (format.Equals(ImageFormat.Gif)) - { - mimeType = "image/gif"; - } - else if (format.Equals(ImageFormat.Jpeg)) - { - mimeType = "image/jpeg"; - } - else if (format.Equals(ImageFormat.Png)) - { - mimeType = "image/png"; - } - else if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp)) - { - mimeType = "image/bmp"; - } - else if (format.Equals(ImageFormat.Tiff)) - { - mimeType = "image/tiff"; - } - else if (format.Equals(ImageFormat.Icon)) - { - mimeType = "image/x-icon"; - } - - return mimeType; - } - public void HandleImageRequest(HttpContextBase context, Func imageGenCallback, string uniqueIdStringSeed) { context.Response.Clear(); @@ -152,22 +123,23 @@ public void HandleImageRequest(HttpContextBase context, Func DateTime_Now && etag == cacheId) + if (lastMod + this.ClientCacheExpiration > this.DateTime_Now && etag == cacheId) { context.Response.StatusCode = 304; context.Response.StatusDescription = "Not Modified"; @@ -264,49 +242,51 @@ public void HandleImageRequest(HttpContextBase context, Func k)) + string mimeType = "image/x-unknown"; + + if (format.Equals(ImageFormat.Gif)) { - builder.Append(key); - builder.Append(context.Request.QueryString.Get(key)); + mimeType = "image/gif"; + } + else if (format.Equals(ImageFormat.Jpeg)) + { + mimeType = "image/jpeg"; } - foreach (var tran in ImageTransforms) + else if (format.Equals(ImageFormat.Png)) { - builder.Append(tran.UniqueString); + mimeType = "image/png"; + } + else if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp)) + { + mimeType = "image/bmp"; + } + else if (format.Equals(ImageFormat.Tiff)) + { + mimeType = "image/tiff"; + } + else if (format.Equals(ImageFormat.Icon)) + { + mimeType = "image/x-icon"; } - return GetIDFromBytes(ASCIIEncoding.ASCII.GetBytes(builder.ToString())); + return mimeType; } private static string GetIDFromBytes(byte[] buffer) @@ -366,20 +361,52 @@ private static string GetIDFromBytes(byte[] buffer) { sb.Append(b.ToString("X2")); } + return sb.ToString(); } } + /// + /// Returns the encoder for the specified mime type. + /// + /// The mime type of the content. + /// ImageCodecInfo. + private static ImageCodecInfo GetEncoderInfo(string mimeType) + { + var encoders = ImageCodecInfo.GetImageEncoders(); + var e = encoders.FirstOrDefault(x => x.MimeType == mimeType); + return e; + } + + private string GetUniqueIDString(HttpContextBase context, string uniqueIdStringSeed) + { + var builder = new StringBuilder(); + builder.Append(uniqueIdStringSeed); + foreach (var key in context.Request.QueryString.AllKeys.OrderBy(k => k)) + { + builder.Append(key); + builder.Append(context.Request.QueryString.Get(key)); + } + + foreach (var tran in this.ImageTransforms) + { + builder.Append(tran.UniqueString); + } + + return GetIDFromBytes(ASCIIEncoding.ASCII.GetBytes(builder.ToString())); + } + private Image GetImageThroughTransforms(Image image) { try { Image temp = image; - foreach (var tran in ImageTransforms) + foreach (var tran in this.ImageTransforms) { temp = tran.ProcessImage(temp); } + return temp; } finally @@ -388,17 +415,26 @@ private Image GetImageThroughTransforms(Image image) } } - //Clear the user image disk cache if userid is found in clear list and is within ClientCacheExpiration time. + // Clear the user image disk cache if userid is found in clear list and is within ClientCacheExpiration time. private bool ClearDiskImageCacheIfNecessary(int userId, int portalId, string cacheId) { var cacheKey = string.Format(DataCache.UserIdListToClearDiskImageCacheKey, portalId); Dictionary userIds; - if ((userIds = DataCache.GetCache>(cacheKey)) == null || !userIds.ContainsKey(userId)) return false; - ImageStore.ForcePurgeFromServerCache(cacheId); + if ((userIds = DataCache.GetCache>(cacheKey)) == null || !userIds.ContainsKey(userId)) + { + return false; + } + + this.ImageStore.ForcePurgeFromServerCache(cacheId); DateTime expiry; - //The clear mechanism is performed for ClientCacheExpiration timespan so that all active clients clears the cache and don't see old data. - if (!userIds.TryGetValue(userId, out expiry) || DateTime.UtcNow <= expiry.Add(ClientCacheExpiration)) return true; - //Remove the userId from the clear list when timespan is > ClientCacheExpiration. + + // The clear mechanism is performed for ClientCacheExpiration timespan so that all active clients clears the cache and don't see old data. + if (!userIds.TryGetValue(userId, out expiry) || DateTime.UtcNow <= expiry.Add(this.ClientCacheExpiration)) + { + return true; + } + + // Remove the userId from the clear list when timespan is > ClientCacheExpiration. userIds.Remove(userId); DataCache.SetCache(cacheKey, userIds); return true; @@ -408,7 +444,7 @@ private Image GetImageThroughTransforms(byte[] buffer) { using (var memoryStream = new MemoryStream(buffer)) { - return GetImageThroughTransforms(Image.FromStream(memoryStream)); + return this.GetImageThroughTransforms(Image.FromStream(memoryStream)); } } @@ -416,7 +452,7 @@ private void RenderImage(Image image, Stream outStream) { try { - if (ContentType == ImageFormat.Gif) + if (this.ContentType == ImageFormat.Gif) { var quantizer = new OctreeQuantizer(255, 8); using (var quantized = quantizer.Quantize(image)) @@ -428,9 +464,9 @@ private void RenderImage(Image image, Stream outStream) { var eps = new EncoderParameters(1) { - Param = { [0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageCompression) } + Param = { [0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, this.ImageCompression) }, }; - var ici = GetEncoderInfo(GetImageMimeType(ContentType)); + var ici = GetEncoderInfo(GetImageMimeType(this.ContentType)); image?.Save(outStream, ici, eps); } } @@ -439,17 +475,5 @@ private void RenderImage(Image image, Stream outStream) image?.Dispose(); } } - - /// - /// Returns the encoder for the specified mime type - /// - /// The mime type of the content - /// ImageCodecInfo - private static ImageCodecInfo GetEncoderInfo(string mimeType) - { - var encoders = ImageCodecInfo.GetImageEncoders(); - var e = encoders.FirstOrDefault(x => x.MimeType == mimeType); - return e; - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs b/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs index 317b41ec362..09ff6e9de40 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs @@ -1,38 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Drawing; -using System.Net; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Drawing; + using System.Net; + /// - /// Image info class + /// Image info class. /// public class ImageInfo { - /// - /// Image - /// - public Image Image { get; private set; } - - /// - /// Image byte buffer - /// - public byte[] ImageByteBuffer { get; private set; } - - /// - /// Http status code - /// - public HttpStatusCode? HttpStatusCode { get; private set; } - - public bool IsEmptyImage { get; set; } = false; - public ImageInfo(HttpStatusCode statusCode) { - HttpStatusCode = statusCode; + this.HttpStatusCode = statusCode; } public ImageInfo(Image image) @@ -41,7 +24,8 @@ public ImageInfo(Image image) { throw new ArgumentNullException(nameof(image)); } - Image = image; + + this.Image = image; } public ImageInfo(byte[] imageBuffer) @@ -50,7 +34,25 @@ public ImageInfo(byte[] imageBuffer) { throw new ArgumentNullException(nameof(imageBuffer)); } - ImageByteBuffer = imageBuffer; + + this.ImageByteBuffer = imageBuffer; } + + /// + /// Gets image. + /// + public Image Image { get; private set; } + + /// + /// Gets image byte buffer. + /// + public byte[] ImageByteBuffer { get; private set; } + + /// + /// Gets http status code. + /// + public HttpStatusCode? HttpStatusCode { get; private set; } + + public bool IsEmptyImage { get; set; } = false; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs b/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs index 37375e4e82b..3315f1499f8 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs @@ -1,50 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel; -using System.Web.UI; -using System.Globalization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.ComponentModel; + using System.Globalization; + using System.Web.UI; + [Bindable(true)] public class ImageParameter : IDataBindingsAccessor { private readonly DataBindingCollection _dataBindings = new DataBindingCollection(); + public event EventHandler DataBinding; + public string Name { get; set; } public string Value { get; set; } - public event EventHandler DataBinding; + public Control BindingContainer { get; internal set; } + + DataBindingCollection IDataBindingsAccessor.DataBindings => this._dataBindings; - internal void DataBind() + bool IDataBindingsAccessor.HasDataBindings => this._dataBindings.Count != 0; + + public override string ToString() { - if (DataBinding != null) + if (string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.Value)) { - DataBinding(this, EventArgs.Empty); + return base.ToString(); } + + return string.Format(CultureInfo.InvariantCulture, "{0} = {1}", this.Name, this.Value); } - public override string ToString() + internal void DataBind() { - if (string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Value)) + if (this.DataBinding != null) { - return base.ToString(); + this.DataBinding(this, EventArgs.Empty); } - return string.Format(CultureInfo.InvariantCulture, "{0} = {1}", Name, Value); } - - public Control BindingContainer { get; internal set; } - - #region IDataBindingsAccessor Members - - DataBindingCollection IDataBindingsAccessor.DataBindings => _dataBindings; - - bool IDataBindingsAccessor.HasDataBindings => _dataBindings.Count != 0; - - #endregion } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs index a5bf6fbfe9e..a68a3e0b919 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs @@ -1,73 +1,75 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Drawing; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.ImageQuantization { + using System; + using System.Collections; + using System.Drawing; + /// /// Summary description for PaletteQuantizer. /// [CLSCompliant(false)] - public class GrayscaleQuantizer : PaletteQuantizer - { - /// - /// Construct the palette quantizer - /// - /// - /// Palette quantization only requires a single quantization step - /// - public GrayscaleQuantizer () : base( new ArrayList() ) - { - _colors = new Color[256]; + public class GrayscaleQuantizer : PaletteQuantizer + { + /// + /// Initializes a new instance of the class. + /// Construct the palette quantizer. + /// + /// + /// Palette quantization only requires a single quantization step. + /// + public GrayscaleQuantizer() + : base(new ArrayList()) + { + this._colors = new Color[256]; - int nColors = 256; + int nColors = 256; - // Initialize a new color table with entries that are determined - // by some optimal palette-finding algorithm; for demonstration - // purposes, use a grayscale. - for (uint i = 0; i < nColors; i++) - { - uint Alpha = 0xFF; // Colors are opaque. - uint intensity = Convert.ToUInt32(i*0xFF/(nColors-1)); // Even distribution. + // Initialize a new color table with entries that are determined + // by some optimal palette-finding algorithm; for demonstration + // purposes, use a grayscale. + for (uint i = 0; i < nColors; i++) + { + uint Alpha = 0xFF; // Colors are opaque. + uint intensity = Convert.ToUInt32(i * 0xFF / (nColors - 1)); // Even distribution. - // The GIF encoder makes the first entry in the palette - // that has a ZERO alpha the transparent color in the GIF. - // Pick the first one arbitrarily, for demonstration purposes. - - // Create a gray scale for demonstration purposes. - // Otherwise, use your favorite color reduction algorithm - // and an optimum palette for that algorithm generated here. - // For example, a color histogram, or a median cut palette. - _colors[i] = Color.FromArgb( (int)Alpha, - (int)intensity, - (int)intensity, - (int)intensity ); - } - } + // The GIF encoder makes the first entry in the palette + // that has a ZERO alpha the transparent color in the GIF. + // Pick the first one arbitrarily, for demonstration purposes. - /// - /// Override this to process the pixel in the second pass of the algorithm - /// - /// The pixel to quantize - /// The quantized value - protected override byte QuantizePixel ( Color32 pixel ) - { - double luminance = (pixel.Red *0.299) + (pixel.Green *0.587) + (pixel.Blue *0.114); + // Create a gray scale for demonstration purposes. + // Otherwise, use your favorite color reduction algorithm + // and an optimum palette for that algorithm generated here. + // For example, a color histogram, or a median cut palette. + this._colors[i] = Color.FromArgb( + (int)Alpha, + (int)intensity, + (int)intensity, + (int)intensity); + } + } - // Gray scale is an intensity map from black to white. - // Compute the index to the grayscale entry that - // approximates the luminance, and then round the index. - // Also, constrain the index choices by the number of - // colors to do, and then set that pixel's index to the - // byte value. - var colorIndex = (byte)(luminance +0.5); + /// + /// Override this to process the pixel in the second pass of the algorithm. + /// + /// The pixel to quantize. + /// The quantized value. + protected override byte QuantizePixel(Color32 pixel) + { + double luminance = (pixel.Red * 0.299) + (pixel.Green * 0.587) + (pixel.Blue * 0.114); - return colorIndex ; - } + // Gray scale is an intensity map from black to white. + // Compute the index to the grayscale entry that + // approximates the luminance, and then round the index. + // Also, constrain the index choices by the number of + // colors to do, and then set that pixel's index to the + // byte value. + var colorIndex = (byte)(luminance + 0.5); - } + return colorIndex; + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs index f921a6337e3..fffe4e09aeb 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs @@ -1,484 +1,505 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Drawing; -using System.Drawing.Imaging; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.ImageQuantization { - /// - /// Quantize using an Octree - /// - public class OctreeQuantizer : Quantizer - { - /// - /// Construct the octree quantizer - /// - /// - /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree, - /// the second pass quantizes a color based on the nodes in the tree - /// - /// The maximum number of colors to return - /// The number of significant bits - public OctreeQuantizer ( int maxColors , int maxColorBits ) : base ( false ) - { - if ( maxColors > 255 ) - throw new ArgumentOutOfRangeException ( nameof(maxColors) , maxColors , "The number of colors should be less than 256" ) ; - - if ( ( maxColorBits < 1 ) | ( maxColorBits > 8 ) ) - throw new ArgumentOutOfRangeException ( nameof(maxColorBits) , maxColorBits , "This should be between 1 and 8" ) ; - - // Construct the octree - _octree = new Octree ( maxColorBits ) ; - _maxColors = maxColors ; - } - - /// - /// Process the pixel in the first pass of the algorithm - /// - /// The pixel to quantize - /// - /// This function need only be overridden if your quantize algorithm needs two passes, - /// such as an Octree quantizer. - /// - protected override void InitialQuantizePixel ( Color32 pixel ) - { - // Add the color to the octree - _octree.AddColor ( pixel ) ; - } - - /// - /// Override this to process the pixel in the second pass of the algorithm - /// - /// The pixel to quantize - /// The quantized value - protected override byte QuantizePixel ( Color32 pixel ) - { - byte paletteIndex = (byte)_maxColors ; // The color at [_maxColors] is set to transparent - - - - // Get the palette index if this non-transparent - if ( pixel.Alpha > 0 ) - paletteIndex = (byte)_octree.GetPaletteIndex ( pixel ) ; - - return paletteIndex ; - } - - /// - /// Retrieve the palette for the quantized image - /// - /// Any old palette, this is overrwritten - /// The new color palette - protected override ColorPalette GetPalette ( ColorPalette original ) - { - // First off convert the octree to _maxColors colors - ArrayList palette = _octree.Palletize ( _maxColors - 1 ) ; - - // Then convert the palette based on those colors - for ( int index = 0 ; index < palette.Count ; index++ ) - original.Entries[index] = (Color)palette[index] ; - - // Add the transparent color - original.Entries[_maxColors] = Color.FromArgb ( 0 , 0 , 0 , 0 ) ; - - return original ; - } - - /// - /// Stores the tree - /// - private Octree _octree ; - - /// - /// Maximum allowed color depth - /// - private int _maxColors ; - - /// - /// Class which does the actual quantization - /// - private class Octree - { - /// - /// Construct the octree - /// - /// The maximum number of significant bits in the image - public Octree ( int maxColorBits ) - { - _maxColorBits = maxColorBits ; - _leafCount = 0 ; - _reducibleNodes = new OctreeNode[9] ; - _root = new OctreeNode ( 0 , _maxColorBits , this ) ; - _previousColor = 0 ; - _previousNode = null ; - } - - /// - /// Add a given color value to the octree - /// - /// - public void AddColor ( Color32 pixel ) - { - // Check if this request is for the same color as the last - if ( _previousColor == pixel.ARGB ) - { - // If so, check if I have a previous node setup. This will only ocurr if the first color in the image - // happens to be black, with an alpha component of zero. - if ( null == _previousNode ) - { - _previousColor = pixel.ARGB ; - _root.AddColor ( pixel , _maxColorBits , 0 , this ) ; - } - else - // Just update the previous node - _previousNode.Increment ( pixel ) ; - } - else - { - _previousColor = pixel.ARGB ; - _root.AddColor ( pixel , _maxColorBits , 0 , this ) ; - } - } + using System; + using System.Collections; + using System.Drawing; + using System.Drawing.Imaging; + + /// + /// Quantize using an Octree. + /// + public class OctreeQuantizer : Quantizer + { + /// + /// Stores the tree. + /// + private Octree _octree; + + /// + /// Maximum allowed color depth. + /// + private int _maxColors; + + /// + /// Initializes a new instance of the class. + /// Construct the octree quantizer. + /// + /// + /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree, + /// the second pass quantizes a color based on the nodes in the tree. + /// + /// The maximum number of colors to return. + /// The number of significant bits. + public OctreeQuantizer(int maxColors, int maxColorBits) + : base(false) + { + if (maxColors > 255) + { + throw new ArgumentOutOfRangeException(nameof(maxColors), maxColors, "The number of colors should be less than 256"); + } + + if ((maxColorBits < 1) | (maxColorBits > 8)) + { + throw new ArgumentOutOfRangeException(nameof(maxColorBits), maxColorBits, "This should be between 1 and 8"); + } + + // Construct the octree + this._octree = new Octree(maxColorBits); + this._maxColors = maxColors; + } + + /// + /// Process the pixel in the first pass of the algorithm. + /// + /// The pixel to quantize. + /// + /// This function need only be overridden if your quantize algorithm needs two passes, + /// such as an Octree quantizer. + /// + protected override void InitialQuantizePixel(Color32 pixel) + { + // Add the color to the octree + this._octree.AddColor(pixel); + } + + /// + /// Override this to process the pixel in the second pass of the algorithm. + /// + /// The pixel to quantize. + /// The quantized value. + protected override byte QuantizePixel(Color32 pixel) + { + byte paletteIndex = (byte)this._maxColors; // The color at [_maxColors] is set to transparent + + // Get the palette index if this non-transparent + if (pixel.Alpha > 0) + { + paletteIndex = (byte)this._octree.GetPaletteIndex(pixel); + } + + return paletteIndex; + } + + /// + /// Retrieve the palette for the quantized image. + /// + /// Any old palette, this is overrwritten. + /// The new color palette. + protected override ColorPalette GetPalette(ColorPalette original) + { + // First off convert the octree to _maxColors colors + ArrayList palette = this._octree.Palletize(this._maxColors - 1); + + // Then convert the palette based on those colors + for (int index = 0; index < palette.Count; index++) + { + original.Entries[index] = (Color)palette[index]; + } + + // Add the transparent color + original.Entries[this._maxColors] = Color.FromArgb(0, 0, 0, 0); + + return original; + } + + /// + /// Class which does the actual quantization. + /// + private class Octree + { + /// + /// Mask used when getting the appropriate pixels for a given node. + /// + private static readonly int[] mask = new int[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; + + /// + /// The root of the octree. + /// + private OctreeNode _root; + + /// + /// Number of leaves in the tree. + /// + private int _leafCount; + + /// + /// Initializes a new instance of the class. + /// Construct the octree. + /// + /// The maximum number of significant bits in the image. + public Octree(int maxColorBits) + { + this._maxColorBits = maxColorBits; + this._leafCount = 0; + this._reducibleNodes = new OctreeNode[9]; + this._root = new OctreeNode(0, this._maxColorBits, this); + this._previousColor = 0; + this._previousNode = null; + } + + /// + /// Gets or sets get/Set the number of leaves in the tree. + /// + public int Leaves + { + get { return this._leafCount; } + set { this._leafCount = value; } + } + + /// + /// Gets return the array of reducible nodes. + /// + protected OctreeNode[] ReducibleNodes + { + get { return this._reducibleNodes; } + } /// - /// Reduce the depth of the tree + /// Add a given color value to the octree. + /// + /// + public void AddColor(Color32 pixel) + { + // Check if this request is for the same color as the last + if (this._previousColor == pixel.ARGB) + { + // If so, check if I have a previous node setup. This will only ocurr if the first color in the image + // happens to be black, with an alpha component of zero. + if (this._previousNode == null) + { + this._previousColor = pixel.ARGB; + this._root.AddColor(pixel, this._maxColorBits, 0, this); + } + else + { + + // Just update the previous node + this._previousNode.Increment(pixel); + } + } + else + { + this._previousColor = pixel.ARGB; + this._root.AddColor(pixel, this._maxColorBits, 0, this); + } + } + + /// + /// Reduce the depth of the tree. /// public void Reduce() { int index; // Find the deepest level containing at least one reducible node - for (index = _maxColorBits - 1; (index > 0) && (null == _reducibleNodes[index]); index--) ; - + for (index = this._maxColorBits - 1; (index > 0) && (this._reducibleNodes[index] == null); index--) + { + } + // Reduce the node most recently added to the list at level 'index' - OctreeNode node = _reducibleNodes[index]; - _reducibleNodes[index] = node.NextReducible; + OctreeNode node = this._reducibleNodes[index]; + this._reducibleNodes[index] = node.NextReducible; // Decrement the leaf count after reducing the node - _leafCount -= node.Reduce(); - - + this._leafCount -= node.Reduce(); + // And just in case I've reduced the last color to be added, and the next color to // be added is the same, invalidate the previousNode... - _previousNode = null; + this._previousNode = null; } - /// - /// Get/Set the number of leaves in the tree - /// - public int Leaves - { - get { return _leafCount ; } - set { _leafCount = value ; } - } - - /// - /// Return the array of reducible nodes - /// - protected OctreeNode[] ReducibleNodes - { - get { return _reducibleNodes ; } - } - - /// - /// Keep track of the previous node that was quantized - /// - /// The node last quantized - protected void TrackPrevious ( OctreeNode node ) - { - _previousNode = node ; - } - - /// - /// Convert the nodes in the octree to a palette with a maximum of colorCount colors - /// - /// The maximum number of colors - /// An arraylist with the palettized colors - public ArrayList Palletize ( int colorCount ) - { - while ( Leaves > colorCount ) - Reduce ( ) ; - - // Now palettize the nodes - ArrayList palette = new ArrayList ( Leaves ) ; - int paletteIndex = 0 ; - _root.ConstructPalette ( palette , ref paletteIndex ) ; - - // And return the palette - return palette ; - } - - /// - /// Get the palette index for the passed color - /// - /// - /// - public int GetPaletteIndex ( Color32 pixel ) - { - return _root.GetPaletteIndex ( pixel , 0 ) ; - } - - /// - /// Mask used when getting the appropriate pixels for a given node - /// - private static readonly int[] mask = new int[8] { 0x80 , 0x40 , 0x20 , 0x10 , 0x08 , 0x04 , 0x02 , 0x01 } ; - - /// - /// The root of the octree - /// - private OctreeNode _root ; - - /// - /// Number of leaves in the tree - /// - private int _leafCount ; - - /// - /// Array of reducible nodes - /// - private OctreeNode[] _reducibleNodes ; - - /// - /// Maximum number of significant bits in the image - /// - private int _maxColorBits ; - - /// - /// Store the last node quantized - /// - private OctreeNode _previousNode ; - - /// - /// Cache the previous color quantized - /// - private int _previousColor ; - - /// - /// Class which encapsulates each node in the tree - /// - protected class OctreeNode - { - /// - /// Construct the node - /// - /// The level in the tree = 0 - 7 - /// The number of significant color bits in the image - /// The tree to which this node belongs - public OctreeNode ( int level , int colorBits , Octree octree ) - { - // Construct the new node - _leaf = ( level == colorBits ) ; - - _red = _green = _blue = 0 ; - _pixelCount = 0 ; - - // If a leaf, increment the leaf count - if ( _leaf ) - { - octree.Leaves++ ; - _nextReducible = null ; - _children = null ; - } - else - { - // Otherwise add this to the reducible nodes - _nextReducible = octree.ReducibleNodes[level] ; - octree.ReducibleNodes[level] = this ; - _children = new OctreeNode[8] ; - } - } - - /// - /// Add a color into the tree - /// - /// The color - /// The number of significant color bits - /// The level in the tree - /// The tree to which this node belongs - public void AddColor ( Color32 pixel , int colorBits , int level , Octree octree ) - { - // Update the color information if this is a leaf - if ( _leaf ) - { - Increment ( pixel ) ; - // Setup the previous node - octree.TrackPrevious ( this ) ; - } - else - { - // Go to the next level down in the tree - int shift = 7 - level ; - int index = ( ( pixel.Red & mask[level] ) >> ( shift - 2 ) ) | - ( ( pixel.Green & mask[level] ) >> ( shift - 1 ) ) | - ( ( pixel.Blue & mask[level] ) >> ( shift ) ) ; - - OctreeNode child = _children[index] ; - - if ( null == child ) - { - // Create a new child node & store in the array - child = new OctreeNode ( level + 1 , colorBits , octree ) ; - _children[index] = child ; - } - - // Add the color to the child node - child.AddColor ( pixel , colorBits , level + 1 , octree ) ; - } - - } - - /// - /// Get/Set the next reducible node - /// - public OctreeNode NextReducible - { - get { return _nextReducible ; } - set { _nextReducible = value ; } - } - - /// - /// Return the child nodes - /// - public OctreeNode[] Children - { - get { return _children ; } - } - - /// - /// Reduce this node by removing all of its children - /// - /// The number of leaves removed - public int Reduce ( ) - { - _red = _green = _blue = 0 ; - int children = 0 ; - - // Loop through all children and add their information to this node - for ( int index = 0 ; index < 8 ; index++ ) - { - if ( null != _children[index] ) - { - _red += _children[index]._red ; - _green += _children[index]._green ; - _blue += _children[index]._blue ; - _pixelCount += _children[index]._pixelCount ; - ++children ; - _children[index] = null ; - } - } - - // Now change this to a leaf node - _leaf = true ; - - // Return the number of nodes to decrement the leaf count by - return ( children - 1 ) ; - } - - /// - /// Traverse the tree, building up the color palette - /// - /// The palette - /// The current palette index - public void ConstructPalette ( ArrayList palette , ref int paletteIndex ) - { - if ( _leaf ) - { - // Consume the next palette index - _paletteIndex = paletteIndex++ ; - - // And set the color of the palette entry - palette.Add ( Color.FromArgb ( _red / _pixelCount , _green / _pixelCount , _blue / _pixelCount ) ) ; - } - else - { - // Loop through children looking for leaves - for ( int index = 0 ; index < 8 ; index++ ) - { - if ( null != _children[index] ) - _children[index].ConstructPalette ( palette , ref paletteIndex ) ; - } - } - } - - /// - /// Return the palette index for the passed color - /// - public int GetPaletteIndex ( Color32 pixel , int level ) - { - int paletteIndex = _paletteIndex ; - - if ( !_leaf ) - { - int shift = 7 - level ; - int index = ( ( pixel.Red & mask[level] ) >> ( shift - 2 ) ) | - ( ( pixel.Green & mask[level] ) >> ( shift - 1 ) ) | - ( ( pixel.Blue & mask[level] ) >> ( shift ) ) ; - - if ( null != _children[index] ) - paletteIndex = _children[index].GetPaletteIndex ( pixel , level + 1 ) ; - else - throw new Exception ( "Didn't expect this!" ) ; - } - - return paletteIndex ; - } - - /// - /// Increment the pixel count and add to the color information - /// - public void Increment ( Color32 pixel ) - { - _pixelCount++ ; - _red += pixel.Red ; - _green += pixel.Green ; - _blue += pixel.Blue ; - } - - /// - /// Flag indicating that this is a leaf node - /// - private bool _leaf ; - - /// - /// Number of pixels in this node - /// - private int _pixelCount ; - - /// - /// Red component - /// - private int _red ; - - /// - /// Green Component - /// - private int _green ; - - /// - /// Blue component - /// - private int _blue ; - - /// - /// Pointers to any child nodes - /// - private OctreeNode[] _children ; - - /// - /// Pointer to next reducible node - /// - private OctreeNode _nextReducible ; - - /// - /// The index of this node in the palette - /// - private int _paletteIndex ; - - } - } - } + /// + /// Convert the nodes in the octree to a palette with a maximum of colorCount colors. + /// + /// The maximum number of colors. + /// An arraylist with the palettized colors. + public ArrayList Palletize(int colorCount) + { + while (this.Leaves > colorCount) + { + this.Reduce(); + } + + // Now palettize the nodes + ArrayList palette = new ArrayList(this.Leaves); + int paletteIndex = 0; + this._root.ConstructPalette(palette, ref paletteIndex); + + // And return the palette + return palette; + } + + /// + /// Get the palette index for the passed color. + /// + /// + /// + public int GetPaletteIndex(Color32 pixel) + { + return this._root.GetPaletteIndex(pixel, 0); + } + + /// + /// Keep track of the previous node that was quantized. + /// + /// The node last quantized. + protected void TrackPrevious(OctreeNode node) + { + this._previousNode = node; + } + + /// + /// Array of reducible nodes. + /// + private OctreeNode[] _reducibleNodes; + + /// + /// Maximum number of significant bits in the image. + /// + private int _maxColorBits; + + /// + /// Store the last node quantized. + /// + private OctreeNode _previousNode; + + /// + /// Cache the previous color quantized. + /// + private int _previousColor; + + /// + /// Class which encapsulates each node in the tree. + /// + protected class OctreeNode + { + /// + /// Flag indicating that this is a leaf node. + /// + private bool _leaf; + + /// + /// Number of pixels in this node. + /// + private int _pixelCount; + + /// + /// Red component. + /// + private int _red; + + /// + /// Initializes a new instance of the class. + /// Construct the node. + /// + /// The level in the tree = 0 - 7. + /// The number of significant color bits in the image. + /// The tree to which this node belongs. + public OctreeNode(int level, int colorBits, Octree octree) + { + // Construct the new node + this._leaf = level == colorBits; + + this._red = this._green = this._blue = 0; + this._pixelCount = 0; + + // If a leaf, increment the leaf count + if (this._leaf) + { + octree.Leaves++; + this._nextReducible = null; + this._children = null; + } + else + { + // Otherwise add this to the reducible nodes + this._nextReducible = octree.ReducibleNodes[level]; + octree.ReducibleNodes[level] = this; + this._children = new OctreeNode[8]; + } + } + + /// + /// Gets or sets get/Set the next reducible node. + /// + public OctreeNode NextReducible + { + get { return this._nextReducible; } + set { this._nextReducible = value; } + } + + /// + /// Gets return the child nodes. + /// + public OctreeNode[] Children + { + get { return this._children; } + } + + /// + /// Add a color into the tree. + /// + /// The color. + /// The number of significant color bits. + /// The level in the tree. + /// The tree to which this node belongs. + public void AddColor(Color32 pixel, int colorBits, int level, Octree octree) + { + // Update the color information if this is a leaf + if (this._leaf) + { + this.Increment(pixel); + + // Setup the previous node + octree.TrackPrevious(this); + } + else + { + // Go to the next level down in the tree + int shift = 7 - level; + int index = ((pixel.Red & mask[level]) >> (shift - 2)) | + ((pixel.Green & mask[level]) >> (shift - 1)) | + ((pixel.Blue & mask[level]) >> shift); + + OctreeNode child = this._children[index]; + + if (child == null) + { + // Create a new child node & store in the array + child = new OctreeNode(level + 1, colorBits, octree); + this._children[index] = child; + } + + // Add the color to the child node + child.AddColor(pixel, colorBits, level + 1, octree); + } + } + + /// + /// Reduce this node by removing all of its children. + /// + /// The number of leaves removed. + public int Reduce() + { + this._red = this._green = this._blue = 0; + int children = 0; + + // Loop through all children and add their information to this node + for (int index = 0; index < 8; index++) + { + if (this._children[index] != null) + { + this._red += this._children[index]._red; + this._green += this._children[index]._green; + this._blue += this._children[index]._blue; + this._pixelCount += this._children[index]._pixelCount; + ++children; + this._children[index] = null; + } + } + + // Now change this to a leaf node + this._leaf = true; + + // Return the number of nodes to decrement the leaf count by + return children - 1; + } + + /// + /// Traverse the tree, building up the color palette. + /// + /// The palette. + /// The current palette index. + public void ConstructPalette(ArrayList palette, ref int paletteIndex) + { + if (this._leaf) + { + // Consume the next palette index + this._paletteIndex = paletteIndex++; + + // And set the color of the palette entry + palette.Add(Color.FromArgb(this._red / this._pixelCount, this._green / this._pixelCount, this._blue / this._pixelCount)); + } + else + { + // Loop through children looking for leaves + for (int index = 0; index < 8; index++) + { + if (this._children[index] != null) + { + this._children[index].ConstructPalette(palette, ref paletteIndex); + } + } + } + } + + /// + /// Return the palette index for the passed color. + /// + public int GetPaletteIndex(Color32 pixel, int level) + { + int paletteIndex = this._paletteIndex; + + if (!this._leaf) + { + int shift = 7 - level; + int index = ((pixel.Red & mask[level]) >> (shift - 2)) | + ((pixel.Green & mask[level]) >> (shift - 1)) | + ((pixel.Blue & mask[level]) >> shift); + + if (this._children[index] != null) + { + paletteIndex = this._children[index].GetPaletteIndex(pixel, level + 1); + } + else + { + throw new Exception("Didn't expect this!"); + } + } + + return paletteIndex; + } + + /// + /// Increment the pixel count and add to the color information. + /// + public void Increment(Color32 pixel) + { + this._pixelCount++; + this._red += pixel.Red; + this._green += pixel.Green; + this._blue += pixel.Blue; + } + + /// + /// Green Component. + /// + private int _green; + + /// + /// Blue component. + /// + private int _blue; + + /// + /// Pointers to any child nodes. + /// + private OctreeNode[] _children; + + /// + /// Pointer to next reducible node. + /// + private OctreeNode _nextReducible; + + /// + /// The index of this node in the palette. + /// + private int _paletteIndex; + } + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs index a9d4fb2a503..d409710242a 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs @@ -1,125 +1,133 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Drawing; -using System.Drawing.Imaging; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.ImageQuantization { + using System; + using System.Collections; + using System.Drawing; + using System.Drawing.Imaging; + /// /// Summary description for PaletteQuantizer. /// [CLSCompliant(false)] - public class PaletteQuantizer : Quantizer - { - /// - /// Construct the palette quantizer - /// - /// The color palette to quantize to - /// - /// Palette quantization only requires a single quantization step - /// - public PaletteQuantizer ( ArrayList palette ) : base ( true ) - { - _colorMap = new Hashtable ( ) ; - - _colors = new Color[palette.Count] ; - palette.CopyTo ( _colors ) ; - } - - /// - /// Override this to process the pixel in the second pass of the algorithm - /// - /// The pixel to quantize - /// The quantized value - protected override byte QuantizePixel ( Color32 pixel ) - { - byte colorIndex = 0 ; - int colorHash = pixel.ARGB ; + public class PaletteQuantizer : Quantizer + { + /// + /// List of all colors in the palette. + /// + protected Color[] _colors; + + /// + /// Lookup table for colors. + /// + private readonly Hashtable _colorMap; + + /// + /// Initializes a new instance of the class. + /// Construct the palette quantizer. + /// + /// The color palette to quantize to. + /// + /// Palette quantization only requires a single quantization step. + /// + public PaletteQuantizer(ArrayList palette) + : base(true) + { + this._colorMap = new Hashtable(); - // Check if the color is in the lookup table - if ( _colorMap.ContainsKey ( colorHash ) ) - colorIndex = (byte)_colorMap[colorHash] ; - else - { - // Not found - loop through the palette and find the nearest match. - // Firstly check the alpha value - if 0, lookup the transparent color - if ( 0 == pixel.Alpha ) - { - // Transparent. Lookup the first color with an alpha value of 0 - for ( int index = 0 ; index < _colors.Length ; index++ ) - { - if ( 0 == _colors[index].A ) - { - colorIndex = (byte)index ; - break ; - } - } - } - else - { - // Not transparent... - int leastDistance = int.MaxValue ; - int red = pixel.Red ; - int green = pixel.Green; - int blue = pixel.Blue; + this._colors = new Color[palette.Count]; + palette.CopyTo(this._colors); + } - // Loop through the entire palette, looking for the closest color match - for ( int index = 0 ; index < _colors.Length ; index++ ) - { - Color paletteColor = _colors[index]; - - int redDistance = paletteColor.R - red ; - int greenDistance = paletteColor.G - green ; - int blueDistance = paletteColor.B - blue ; + /// + /// Override this to process the pixel in the second pass of the algorithm. + /// + /// The pixel to quantize. + /// The quantized value. + protected override byte QuantizePixel(Color32 pixel) + { + byte colorIndex = 0; + int colorHash = pixel.ARGB; - int distance = ( redDistance * redDistance ) + - ( greenDistance * greenDistance ) + - ( blueDistance * blueDistance ) ; + // Check if the color is in the lookup table + if (this._colorMap.ContainsKey(colorHash)) + { + colorIndex = (byte)this._colorMap[colorHash]; + } + else + { + // Not found - loop through the palette and find the nearest match. + // Firstly check the alpha value - if 0, lookup the transparent color + if (pixel.Alpha == 0) + { + // Transparent. Lookup the first color with an alpha value of 0 + for (int index = 0; index < this._colors.Length; index++) + { + if (this._colors[index].A == 0) + { + colorIndex = (byte)index; + break; + } + } + } + else + { + // Not transparent... + int leastDistance = int.MaxValue; + int red = pixel.Red; + int green = pixel.Green; + int blue = pixel.Blue; - if ( distance < leastDistance ) - { - colorIndex = (byte)index ; - leastDistance = distance ; + // Loop through the entire palette, looking for the closest color match + for (int index = 0; index < this._colors.Length; index++) + { + Color paletteColor = this._colors[index]; - // And if it's an exact match, exit the loop - if ( 0 == distance ) - break ; - } - } - } + int redDistance = paletteColor.R - red; + int greenDistance = paletteColor.G - green; + int blueDistance = paletteColor.B - blue; - // Now I have the color, pop it into the hashtable for next time - _colorMap.Add ( colorHash , colorIndex ) ; - } + int distance = (redDistance * redDistance) + + (greenDistance * greenDistance) + + (blueDistance * blueDistance); - return colorIndex ; - } + if (distance < leastDistance) + { + colorIndex = (byte)index; + leastDistance = distance; - /// - /// Retrieve the palette for the quantized image - /// - /// Any old palette, this is overrwritten - /// The new color palette - protected override ColorPalette GetPalette ( ColorPalette palette ) - { - for ( int index = 0 ; index < _colors.Length ; index++ ) - palette.Entries[index] = _colors[index] ; + // And if it's an exact match, exit the loop + if (distance == 0) + { + break; + } + } + } + } - return palette ; - } + // Now I have the color, pop it into the hashtable for next time + this._colorMap.Add(colorHash, colorIndex); + } - /// - /// Lookup table for colors - /// - private readonly Hashtable _colorMap ; + return colorIndex; + } - /// - /// List of all colors in the palette - /// - protected Color[] _colors ; - } + /// + /// Retrieve the palette for the quantized image. + /// + /// Any old palette, this is overrwritten. + /// The new color palette. + protected override ColorPalette GetPalette(ColorPalette palette) + { + for (int index = 0; index < this._colors.Length; index++) + { + palette.Entries[index] = this._colors[index]; + } + + return palette; + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs index d9752c4d4d5..1ba2d5f5408 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs @@ -1,23 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.Runtime.InteropServices; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.ImageQuantization { + using System; + using System.Drawing; + using System.Drawing.Imaging; + using System.Runtime.InteropServices; + /// - /// Abstarct class for Quantizers + /// Abstarct class for Quantizers. /// public abstract class Quantizer - { + { /// - /// Construct the quantizer + /// Flag used to indicate whether a single pass or two passes are needed for quantization. /// - /// If true, the quantization only needs to loop through the source pixels once + private bool _singlePass; + private int _pixelSize; + + /// + /// Initializes a new instance of the class. + /// Construct the quantizer. + /// + /// If true, the quantization only needs to loop through the source pixels once. /// /// If you construct this class with a true value for singlePass, then the code will, when quantizing your image, /// only call the 'QuantizeImage' function. If two passes are required, the code will call 'InitialQuantizeImage' @@ -25,15 +32,15 @@ public abstract class Quantizer /// public Quantizer(bool singlePass) { - _singlePass = singlePass; - _pixelSize = Marshal.SizeOf(typeof (Color32)); + this._singlePass = singlePass; + this._pixelSize = Marshal.SizeOf(typeof(Color32)); } /// - /// Quantize an image and return the resulting output bitmap + /// Quantize an image and return the resulting output bitmap. /// - /// The image to quantize - /// A quantized version of the image + /// The image to quantize. + /// A quantized version of the image. public Bitmap Quantize(Image source) { // Get the size of the source image @@ -57,7 +64,6 @@ public Bitmap Quantize(Image source) // Draw the source image onto the copy bitmap, // which will effect a widening as appropriate. g.DrawImage(source, bounds); - } // Define a pointer to the bitmap data @@ -67,22 +73,21 @@ public Bitmap Quantize(Image source) { // Get the source image bits and lock into memory sourceData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - - - + // Call the FirstPass function if not a single pass algorithm. // For something like an octree quantizer, this will run through // all image pixels, build a data structure, and create a palette. - if (!_singlePass) - FirstPass(sourceData, width, height); - - // Then set the color palette on the output bitmap. I'm passing in the current palette - // as there's no way to construct a new, empty palette. - output.Palette = GetPalette(output.Palette); - - + if (!this._singlePass) + { + this.FirstPass(sourceData, width, height); + } + + // Then set the color palette on the output bitmap. I'm passing in the current palette + // as there's no way to construct a new, empty palette. + output.Palette = this.GetPalette(output.Palette); + // Then call the second pass which actually does the conversion - SecondPass(sourceData, output, width, height, bounds); + this.SecondPass(sourceData, output, width, height, bounds); } finally { @@ -95,15 +100,15 @@ public Bitmap Quantize(Image source) } /// - /// Execute the first pass through the pixels in the image + /// Execute the first pass through the pixels in the image. /// - /// The source data - /// The width in pixels of the image - /// The height in pixels of the image - protected virtual void FirstPass(BitmapData sourceData, int width, int height) + /// The source data. + /// The width in pixels of the image. + /// The height in pixels of the image. + protected virtual void FirstPass(BitmapData sourceData, int width, int height) { // Define the source data pointers. The source row is a byte to - // keep addition of the stride value easier (as this is in bytes) + // keep addition of the stride value easier (as this is in bytes) IntPtr pSourceRow = sourceData.Scan0; // Loop through each row @@ -114,10 +119,10 @@ protected virtual void FirstPass(BitmapData sourceData, int width, int height) // And loop through each column for (int col = 0; col < width; col++) - { - InitialQuantizePixel(new Color32(pSourcePixel)); - pSourcePixel = (IntPtr)((Int64)pSourcePixel + _pixelSize); - } // Now I have the pixel, call the FirstPassQuantize function... + { + this.InitialQuantizePixel(new Color32(pSourcePixel)); + pSourcePixel = (IntPtr)((long)pSourcePixel + this._pixelSize); + } // Now I have the pixel, call the FirstPassQuantize function... // Add the stride to the source row pSourceRow = (IntPtr)((long)pSourceRow + sourceData.Stride); @@ -125,13 +130,13 @@ protected virtual void FirstPass(BitmapData sourceData, int width, int height) } /// - /// Execute a second pass through the bitmap + /// Execute a second pass through the bitmap. /// - /// The source bitmap, locked into memory - /// The output bitmap - /// The width in pixels of the image - /// The height in pixels of the image - /// The bounding rectangle + /// The source bitmap, locked into memory. + /// The output bitmap. + /// The width in pixels of the image. + /// The height in pixels of the image. + /// The bounding rectangle. protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int width, int height, Rectangle bounds) { BitmapData outputData = null; @@ -152,8 +157,7 @@ protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int widt IntPtr pDestinationPixel = pDestinationRow; // And convert the first pixel, so that I have values going into the loop - - byte pixelValue = QuantizePixel(new Color32(pSourcePixel)); + byte pixelValue = this.QuantizePixel(new Color32(pSourcePixel)); // Assign the value of the first pixel Marshal.WriteByte(pDestinationPixel, pixelValue); @@ -175,7 +179,7 @@ protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int widt if (Marshal.ReadByte(pPreviousPixel) != Marshal.ReadByte(pSourcePixel)) { // Quantize the pixel - pixelValue = QuantizePixel(new Color32(pSourcePixel)); + pixelValue = this.QuantizePixel(new Color32(pSourcePixel)); // And setup the previous pointer pPreviousPixel = pSourcePixel; @@ -184,9 +188,8 @@ protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int widt // And set the pixel in the output Marshal.WriteByte(pDestinationPixel, pixelValue); - pSourcePixel = (IntPtr)((long)pSourcePixel + _pixelSize); + pSourcePixel = (IntPtr)((long)pSourcePixel + this._pixelSize); pDestinationPixel = (IntPtr)((long)pDestinationPixel + 1); - } // Add the stride to the source row @@ -204,9 +207,9 @@ protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int widt } /// - /// Override this to process the pixel in the first pass of the algorithm + /// Override this to process the pixel in the first pass of the algorithm. /// - /// The pixel to quantize + /// The pixel to quantize. /// /// This function need only be overridden if your quantize algorithm needs two passes, /// such as an Octree quantizer. @@ -216,76 +219,71 @@ protected virtual void InitialQuantizePixel(Color32 pixel) } /// - /// Override this to process the pixel in the second pass of the algorithm + /// Override this to process the pixel in the second pass of the algorithm. /// - /// The pixel to quantize - /// The quantized value + /// The pixel to quantize. + /// The quantized value. protected abstract byte QuantizePixel(Color32 pixel); /// - /// Retrieve the palette for the quantized image + /// Retrieve the palette for the quantized image. /// - /// Any old palette, this is overrwritten - /// The new color palette + /// Any old palette, this is overrwritten. + /// The new color palette. protected abstract ColorPalette GetPalette(ColorPalette original); /// - /// Flag used to indicate whether a single pass or two passes are needed for quantization. - /// - private bool _singlePass; - private int _pixelSize; - - /// - /// Struct that defines a 32 bpp colour + /// Struct that defines a 32 bpp colour. /// /// /// This struct is used to read data from a 32 bits per pixel image /// in memory, and is ordered in this manner as this is the way that - /// the data is layed out in memory + /// the data is layed out in memory. /// [StructLayout(LayoutKind.Explicit)] public struct Color32 { - - public Color32(IntPtr pSourcePixel) - { - this = (Color32) Marshal.PtrToStructure(pSourcePixel, typeof(Color32)); - - } - /// - /// Holds the blue component of the colour + /// Holds the blue component of the colour. /// [FieldOffset(0)] public byte Blue; + /// - /// Holds the green component of the colour + /// Holds the green component of the colour. /// [FieldOffset(1)] public byte Green; + /// - /// Holds the red component of the colour + /// Holds the red component of the colour. /// [FieldOffset(2)] public byte Red; + + public Color32(IntPtr pSourcePixel) + { + this = (Color32)Marshal.PtrToStructure(pSourcePixel, typeof(Color32)); + } + /// - /// Holds the alpha component of the colour + /// Holds the alpha component of the colour. /// [FieldOffset(3)] public byte Alpha; /// - /// Permits the color32 to be treated as an int32 + /// Permits the color32 to be treated as an int32. /// [FieldOffset(0)] public int ARGB; /// - /// Return the color for this Color32 object + /// Gets return the color for this Color32 object. /// public Color Color { - get { return Color.FromArgb(Alpha, Red, Green, Blue); } + get { return Color.FromArgb(this.Alpha, this.Red, this.Green, this.Blue); } } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageResizeMode.cs b/DNN Platform/Library/Services/GeneratedImage/ImageResizeMode.cs index 57fb8f755a6..f2de2182fbe 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageResizeMode.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageResizeMode.cs @@ -1,31 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { /// - /// Enumerator that represent the available resize modes + /// Enumerator that represent the available resize modes. /// - public enum ImageResizeMode { - /// - /// Resizes the image with the given width or height without maintaing the aspect ratio. + public enum ImageResizeMode + { + /// + /// Resizes the image with the given width or height without maintaing the aspect ratio. /// Fill, + + /// + /// Fit mode maintains the aspect ratio of the original image while ensuring that the dimensions of the result + /// do not exceed the maximum values for the resize transformation. + /// + Fit, + /// - /// Fit mode maintains the aspect ratio of the original image while ensuring that the dimensions of the result - /// do not exceed the maximum values for the resize transformation. - /// - Fit, - /// - /// Crop resizes the image and removes parts of it to ensure that the dimensions of the result are exactly - /// as specified by the transformation. - /// - Crop, - /// - /// Resizes the image with the given width or height and maintains the aspect ratio. The image will be centered in a - /// square area of the chosen background color - /// - FitSquare + /// Crop resizes the image and removes parts of it to ensure that the dimensions of the result are exactly + /// as specified by the transformation. + /// + Crop, + + /// + /// Resizes the image with the given width or height and maintains the aspect ratio. The image will be centered in a + /// square area of the chosen background color + /// + FitSquare, } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs b/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs index 4645b7e3438..79b2f42684e 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs @@ -1,57 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Imaging; + using System.IO; + /// - /// An abstract ImageTransform class + /// An abstract ImageTransform class. /// public abstract class ImageTransform { - /// - /// Sets the interpolation mode used for resizing images. The default is HighQualityBicubic. - /// - public InterpolationMode InterpolationMode { get; set; } - - /// - /// Sets the smoothing mode used for resizing images. The default is HighQuality. - /// - public SmoothingMode SmoothingMode { get; set; } + /// + /// Gets or sets the interpolation mode used for resizing images. The default is HighQualityBicubic. + /// + public InterpolationMode InterpolationMode { get; set; } - /// - /// Sets the pixel offset mode used for resizing images. The default is HighQuality. - /// - public PixelOffsetMode PixelOffsetMode { get; set; } + /// + /// Gets or sets the smoothing mode used for resizing images. The default is HighQuality. + /// + public SmoothingMode SmoothingMode { get; set; } - /// - /// Sets the compositing quality used for resizing images. The default is HighQuality. - /// - public CompositingQuality CompositingQuality { get; set; } + /// + /// Gets or sets the pixel offset mode used for resizing images. The default is HighQuality. + /// + public PixelOffsetMode PixelOffsetMode { get; set; } /// - /// Process an input image applying the image transformation + /// Gets or sets the compositing quality used for resizing images. The default is HighQuality. /// - /// Input image - /// Image processed - public abstract Image ProcessImage(Image image); + public CompositingQuality CompositingQuality { get; set; } // REVIEW: should this property be abstract? + + /// + /// Gets provides an Unique String for the image transformation. + /// + public virtual string UniqueString => this.GetType().FullName; + /// - /// Provides an Unique String for the image transformation + /// Process an input image applying the image transformation. /// - public virtual string UniqueString => GetType().FullName; + /// Input image. + /// Image processed. + public abstract Image ProcessImage(Image image); /// /// Creates a new image from stream. The created image is independent of the stream. /// /// - /// Image object + /// Image object. public virtual Bitmap CopyImage(Stream imgStream) { using (var srcImage = new Bitmap(imgStream)) @@ -60,11 +61,12 @@ public virtual Bitmap CopyImage(Stream imgStream) using (var graph = Graphics.FromImage(destImage)) { graph.CompositingMode = CompositingMode.SourceCopy; - graph.CompositingQuality = CompositingQuality; - graph.InterpolationMode = InterpolationMode; - graph.SmoothingMode = SmoothingMode; + graph.CompositingQuality = this.CompositingQuality; + graph.InterpolationMode = this.InterpolationMode; + graph.SmoothingMode = this.SmoothingMode; graph.DrawImage(srcImage, new Rectangle(0, 0, srcImage.Width, srcImage.Height)); } + return destImage; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs b/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs index 8892df36965..e5d3b2c2f84 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Entities.Profile; -using System.ComponentModel.Composition; -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel.Composition; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Profile; + /// - /// this class handles profile changes + /// this class handles profile changes. /// [Export(typeof(IProfileEventHandlers))] [ExportMetadata("MessageType", "ProfileEventHandler")] @@ -25,8 +26,12 @@ public class ProfileEventHandler : IProfileEventHandlers /// public void ProfileUpdated(object sender, ProfileEventArgs profileArgs) { - if (profileArgs?.User == null || profileArgs.OldProfile == null) return; - //extract old and new user profile from args and clear both client and server caching + if (profileArgs?.User == null || profileArgs.OldProfile == null) + { + return; + } + + // extract old and new user profile from args and clear both client and server caching var user = profileArgs.User; var newProfile = user.Profile; var oldProfile = profileArgs.OldProfile; @@ -36,10 +41,17 @@ public void ProfileUpdated(object sender, ProfileEventArgs profileArgs) { var cacheKey = string.Format(DataCache.UserIdListToClearDiskImageCacheKey, user.PortalID); Dictionary userIds; - if ((userIds = DataCache.GetCache>(cacheKey)) == null) - userIds = new Dictionary(); - //Add the userid to the clear cache list, if not already in the list. - if (userIds.ContainsKey(user.UserID)) userIds.Remove(user.UserID); + if ((userIds = DataCache.GetCache>(cacheKey)) == null) + { + userIds = new Dictionary(); + } + + // Add the userid to the clear cache list, if not already in the list. + if (userIds.ContainsKey(user.UserID)) + { + userIds.Remove(user.UserID); + } + userIds.Add(user.UserID, DateTime.UtcNow); DataCache.SetCache(cacheKey, userIds); } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs index 0142dc4c876..15124734152 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs @@ -1,96 +1,96 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.IO; -using System.Net; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.StartTransform { + using System; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.IO; + using System.Net; + /// - /// Image File ImageTransform class + /// Image File ImageTransform class. /// public class ImageFileTransform : ImageTransform - { - /// - /// File path of the image - /// - public string ImageFilePath { get; set; } + { + public ImageFileTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } + + /// + /// Gets or sets file path of the image. + /// + public string ImageFilePath { get; set; } /// - /// Url of the image + /// Gets or sets url of the image. /// public string ImageUrl { get; set; } /// - /// Sets the Image to return if no image or error + /// Gets or sets the Image to return if no image or error. /// public Image EmptyImage { get; set; } /// - /// Provides an Unique String for the image transformation + /// Gets provides an Unique String for the image transformation. /// - public override string UniqueString => base.UniqueString + "-" + ImageFilePath + ImageUrl; - - public ImageFileTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - } + public override string UniqueString => base.UniqueString + "-" + this.ImageFilePath + this.ImageUrl; /// /// Processes an input image applying a file image transformation. - /// This will return an image after read the stream from the File Path or Url + /// This will return an image after read the stream from the File Path or Url . /// - /// Input image - /// Image result after file image transformation + /// Input image. + /// Image result after file image transformation. public override Image ProcessImage(Image image) { - return !string.IsNullOrEmpty(ImageUrl) ? - ProcessImageFromUrl() : - ProcessImageFilePath(); + return !string.IsNullOrEmpty(this.ImageUrl) ? + this.ProcessImageFromUrl() : + this.ProcessImageFilePath(); } private Image ProcessImageFilePath() { try { - using (var stream = new FileStream(ImageFilePath, FileMode.Open)) + using (var stream = new FileStream(this.ImageFilePath, FileMode.Open)) { - return CopyImage(stream); + return this.CopyImage(stream); } } catch (Exception ex) { Exceptions.Exceptions.LogException(ex); - return EmptyImage; + return this.EmptyImage; } } private Image ProcessImageFromUrl() { - var httpWebRequest = (HttpWebRequest) WebRequest.Create(ImageUrl); + var httpWebRequest = (HttpWebRequest)WebRequest.Create(this.ImageUrl); try { - using (var httpWebReponse = (HttpWebResponse) httpWebRequest.GetResponse()) + using (var httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse()) { using (var stream = httpWebReponse.GetResponseStream()) { - return CopyImage(stream); + return this.CopyImage(stream); } } } catch (Exception ex) { Exceptions.Exceptions.LogException(ex); - return EmptyImage; + return this.EmptyImage; } } - } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs index ac4c5094451..7646776f675 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs @@ -1,123 +1,138 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.StartTransform { + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Text; + /// - /// Placeholder ImageTransform class + /// Placeholder ImageTransform class. /// - public class PlaceholderTransform : ImageTransform - { - /// - /// Sets the width of the placeholder image - /// - public int Width { get; set; } - - /// - /// Sets the Height of the placeholder image - /// - public int Height { get; set; } + public class PlaceholderTransform : ImageTransform + { + public PlaceholderTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.BackColor = Color.LightGray; + this.Color = Color.LightSlateGray; + this.Width = 0; + this.Height = 0; + this.Text = string.Empty; + } + + /// + /// Gets or sets the width of the placeholder image. + /// + public int Width { get; set; } - /// - /// Sets the Color of the border and text element - /// - public Color Color { get; set; } + /// + /// Gets or sets the Height of the placeholder image. + /// + public int Height { get; set; } - /// - /// Sets the backcolor of the placeholder element - /// - public Color BackColor { get; set; } + /// + /// Gets or sets the Color of the border and text element. + /// + public Color Color { get; set; } - /// - /// Sets the text of the placeholder image. if blank dimension will be used - /// - public string Text { get; set; } + /// + /// Gets or sets the backcolor of the placeholder element. + /// + public Color BackColor { get; set; } /// - /// Provides an Unique String for the image transformation + /// Gets or sets the text of the placeholder image. if blank dimension will be used. /// - public override string UniqueString => base.UniqueString + Width + "-" + Height + "-" + Color + "-" + BackColor + "-" + Text; + public string Text { get; set; } - public PlaceholderTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - BackColor = Color.LightGray; - Color = Color.LightSlateGray; - Width = 0; - Height = 0; - Text = ""; - } + /// + /// Gets provides an Unique String for the image transformation. + /// + public override string UniqueString => base.UniqueString + this.Width + "-" + this.Height + "-" + this.Color + "-" + this.BackColor + "-" + this.Text; /// - /// Processes an input image returning a placeholder image + /// Processes an input image returning a placeholder image. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { - // Check dimensions - if (Width == 0 && Height > 0) - Width = Height; - if (Width > 0 && Height == 0) - Height = Width; - - var bitmap = new Bitmap(Width, Height); - Brush backColorBrush = new SolidBrush(BackColor); - Brush colorBrush = new SolidBrush(Color); - var colorPen = new Pen(Color,2); - var text = string.IsNullOrEmpty(Text) ? $"{Width}x{Height}" : Text; + { + // Check dimensions + if (this.Width == 0 && this.Height > 0) + { + this.Width = this.Height; + } + + if (this.Width > 0 && this.Height == 0) + { + this.Height = this.Width; + } + + var bitmap = new Bitmap(this.Width, this.Height); + Brush backColorBrush = new SolidBrush(this.BackColor); + Brush colorBrush = new SolidBrush(this.Color); + var colorPen = new Pen(this.Color, 2); + var text = string.IsNullOrEmpty(this.Text) ? $"{this.Width}x{this.Height}" : this.Text; - using (var objGraphics = Graphics.FromImage(bitmap)) - { - // Initialize graphics - objGraphics.Clear(Color.White); - objGraphics.SmoothingMode = SmoothingMode.AntiAlias; - objGraphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; + using (var objGraphics = Graphics.FromImage(bitmap)) + { + // Initialize graphics + objGraphics.Clear(Color.White); + objGraphics.SmoothingMode = SmoothingMode.AntiAlias; + objGraphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; - // Fill bitmap with backcolor - - objGraphics.FillRectangle(backColorBrush,0,0, Width,Height); - - // Draw border - objGraphics.DrawRectangle(colorPen,1,1,Width-3,Height-3); + // Fill bitmap with backcolor + objGraphics.FillRectangle(backColorBrush, 0, 0, this.Width, this.Height); - // Determine fontsize - var fontSize = 13; - if (Width < 101) - fontSize = 8; - else if (Width < 151) - fontSize = 10; - else if (Width < 201) - fontSize = 12; - else if (Width < 301) - fontSize = 14; - else - fontSize = 24; + // Draw border + objGraphics.DrawRectangle(colorPen, 1, 1, this.Width - 3, this.Height - 3); - // Draw text on image - // Use rectangle for text and align text to center of rectangle - var font = new Font("Arial", fontSize, FontStyle.Bold); - var stringFormat = new StringFormat - { - Alignment = StringAlignment.Center, - LineAlignment = StringAlignment.Center - }; + // Determine fontsize + var fontSize = 13; + if (this.Width < 101) + { + fontSize = 8; + } + else if (this.Width < 151) + { + fontSize = 10; + } + else if (this.Width < 201) + { + fontSize = 12; + } + else if (this.Width < 301) + { + fontSize = 14; + } + else + { + fontSize = 24; + } + + // Draw text on image + // Use rectangle for text and align text to center of rectangle + var font = new Font("Arial", fontSize, FontStyle.Bold); + var stringFormat = new StringFormat + { + Alignment = StringAlignment.Center, + LineAlignment = StringAlignment.Center, + }; - var rectangle = new Rectangle(5, 5, Width - 10, Height - 10); - objGraphics.DrawString(text, font, colorBrush, rectangle, stringFormat); + var rectangle = new Rectangle(5, 5, this.Width - 10, this.Height - 10); + objGraphics.DrawString(text, font, colorBrush, rectangle, stringFormat); - // Save indicator to file - objGraphics.Flush(); - } - return bitmap; - } - } + // Save indicator to file + objGraphics.Flush(); + } + + return bitmap; + } + } } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs index 90b310605b1..cb98960fb1e 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs @@ -1,92 +1,74 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.StartTransform { + using System.Collections.Generic; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.IO; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem; + /// - /// Secure File ImageTransform class + /// Secure File ImageTransform class. /// - public class SecureFileTransform : ImageTransform - { - #region Properties + public class SecureFileTransform : ImageTransform + { + public SecureFileTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } + /// - /// Set IFileInfo object of given FileId + /// Gets or sets set IFileInfo object of given FileId. /// public IFileInfo SecureFile { get; set; } /// - /// Sets the Image to return if no image or error + /// Gets or sets the Image to return if no image or error. /// public Image EmptyImage { get; set; } /// - /// Provides an Unique String for the image transformation + /// Gets provides an Unique String for the image transformation. /// - public override string UniqueString => base.UniqueString + SecureFile.FileId; - #endregion - - public SecureFileTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - } + public override string UniqueString => base.UniqueString + this.SecureFile.FileId; /// - /// Processes an input image returing a secure file image + /// Processes an input image returing a secure file image. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. /// - /// If the secure file is not an image, it returns an image representing the file extension + /// If the secure file is not an image, it returns an image representing the file extension. /// public override Image ProcessImage(Image image) { // if SecureFile is no ImageFile return FileType-Image instead - if (!IsImageExtension(SecureFile.Extension)) - { - return GetSecureFileExtensionIconImage(); - } - - using (var content = FileManager.Instance.GetFileContent(SecureFile)) - { - return CopyImage(content); - } - } - - private Image GetSecureFileExtensionIconImage() - { - var extensionImageAbsolutePath = Globals.ApplicationMapPath + "\\" + - PortalSettings.Current.DefaultIconLocation.Replace("/", "\\") + "\\" + - "Ext" + SecureFile.Extension + "_32x32_Standard.png"; - - if (!File.Exists(extensionImageAbsolutePath)) + if (!IsImageExtension(this.SecureFile.Extension)) { - return EmptyImage; + return this.GetSecureFileExtensionIconImage(); } - using (var stream = new FileStream(extensionImageAbsolutePath, FileMode.Open)) + using (var content = FileManager.Instance.GetFileContent(this.SecureFile)) { - return CopyImage(stream); + return this.CopyImage(content); } } /// - /// Checks if the current user have READ permission on a given folder + /// Checks if the current user have READ permission on a given folder. /// - /// Folder info object - /// True if the user has READ permission, false otherwise + /// Folder info object. + /// True if the user has READ permission, false otherwise. public bool DoesHaveReadFolderPermission(IFolderInfo folder) { return FolderPermissionController.HasFolderPermission(folder.FolderPermissions, "Read"); @@ -102,5 +84,22 @@ private static bool IsImageExtension(string extension) var imageExtensions = new List { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG", ".ICO" }; return imageExtensions.Contains(extension.ToUpper()); } + + private Image GetSecureFileExtensionIconImage() + { + var extensionImageAbsolutePath = Globals.ApplicationMapPath + "\\" + + PortalSettings.Current.DefaultIconLocation.Replace("/", "\\") + "\\" + + "Ext" + this.SecureFile.Extension + "_32x32_Standard.png"; + + if (!File.Exists(extensionImageAbsolutePath)) + { + return this.EmptyImage; + } + + using (var stream = new FileStream(extensionImageAbsolutePath, FileMode.Open)) + { + return this.CopyImage(stream); + } + } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs index 9a9e7c48cc0..12d8237a7d0 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs @@ -1,75 +1,75 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.GeneratedImage.StartTransform { + using System.Collections.Generic; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Imaging; + using System.IO; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + /// - /// User Profile Picture ImageTransform class + /// User Profile Picture ImageTransform class. /// - public class UserProfilePicTransform : ImageTransform - { - #region Properties + public class UserProfilePicTransform : ImageTransform + { + public UserProfilePicTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } + /// - /// Sets the UserID of the profile pic - /// - public int UserID { get; set; } + /// Gets or sets the UserID of the profile pic. + /// + public int UserID { get; set; } /// - /// Provides an Unique String for the image transformation + /// Gets provides an Unique String for the image transformation. /// - public override string UniqueString => base.UniqueString + UserID; + public override string UniqueString => base.UniqueString + this.UserID; /// - /// Is reusable + /// Gets a value indicating whether is reusable. /// - public bool IsReusable => false; - #endregion - - public UserProfilePicTransform() - { - InterpolationMode = InterpolationMode.HighQualityBicubic; - SmoothingMode = SmoothingMode.HighQuality; - PixelOffsetMode = PixelOffsetMode.HighQuality; - CompositingQuality = CompositingQuality.HighQuality; - } + public bool IsReusable => false; /// - /// Processes an input image returning the user profile picture + /// Processes an input image returning the user profile picture. /// - /// Input image - /// Image result after image transformation + /// Input image. + /// Image result after image transformation. public override Image ProcessImage(Image image) - { + { IFileInfo photoFile; - if (TryGetPhotoFile(out photoFile)) - { - if (!IsImageExtension(photoFile.Extension)) - { - return GetNoAvatarImage(); - } + if (this.TryGetPhotoFile(out photoFile)) + { + if (!IsImageExtension(photoFile.Extension)) + { + return this.GetNoAvatarImage(); + } - using (var content = FileManager.Instance.GetFileContent(photoFile)) - { - return CopyImage(content); - } - } - return GetNoAvatarImage(); - } + using (var content = FileManager.Instance.GetFileContent(photoFile)) + { + return this.CopyImage(content); + } + } + + return this.GetNoAvatarImage(); + } /// - /// Get the Bitmap of the No Avatar Image + /// Get the Bitmap of the No Avatar Image. /// /// public Bitmap GetNoAvatarImage() @@ -77,7 +77,7 @@ public Bitmap GetNoAvatarImage() var avatarAbsolutePath = Globals.ApplicationMapPath + @"\images\no_avatar.gif"; using (var content = File.OpenRead(avatarAbsolutePath)) { - return CopyImage(content); + return this.CopyImage(content); } } @@ -91,7 +91,7 @@ public bool TryGetPhotoFile(out IFileInfo photoFile) photoFile = null; var settings = PortalController.Instance.GetCurrentPortalSettings(); - var targetUser = UserController.Instance.GetUser(settings.PortalId, UserID); + var targetUser = UserController.Instance.GetUser(settings.PortalId, this.UserID); if (targetUser == null) { return false; @@ -121,7 +121,7 @@ public bool TryGetPhotoFile(out IFileInfo photoFile) return isVisible; } - + private static bool IsImageExtension(string extension) { if (!extension.StartsWith(".")) diff --git a/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs b/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs index 8b6c433d0d9..6fa2ed401a5 100644 --- a/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs +++ b/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs @@ -1,42 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Web; -using DotNetNuke.Application; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.ImprovementsProgram { + using System; + using System.Collections.Generic; + using System.Configuration; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Web; + + using DotNetNuke.Application; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + public class BeaconService : ServiceLocator, IBeaconService { private static readonly bool IsAlphaMode = DotNetNukeContext.Current?.Application?.Status == ReleaseMode.Alpha; - protected override Func GetFactory() - { - return () => new BeaconService(); - } - private string _beaconEndpoint; public string GetBeaconEndpoint() { - if (string.IsNullOrEmpty(_beaconEndpoint)) + if (string.IsNullOrEmpty(this._beaconEndpoint)) { var ep = ConfigurationManager.AppSettings["ImprovementProgram.Endpoint"]; #if DEBUG - _beaconEndpoint = string.IsNullOrEmpty(ep) + this._beaconEndpoint = string.IsNullOrEmpty(ep) ? "https://dev.dnnapi.com/beacon" : ep; #else @@ -45,14 +41,15 @@ public string GetBeaconEndpoint() : ep; #endif } - return _beaconEndpoint; + + return this._beaconEndpoint; } public bool IsBeaconEnabledForControlBar(UserInfo user) { - //check for Update Service Opt-in - //check if a host or admin - //check if currently on a host/admin page + // check for Update Service Opt-in + // check if a host or admin + // check if currently on a host/admin page var enabled = false; if (Host.ParticipateInImprovementProg && !IsAlphaMode) @@ -66,6 +63,11 @@ public bool IsBeaconEnabledForControlBar(UserInfo user) return enabled; } + protected override Func GetFactory() + { + return () => new BeaconService(); + } + public bool IsBeaconEnabledForPersonaBar() { return Host.ParticipateInImprovementProg && !IsAlphaMode; @@ -76,11 +78,30 @@ public string GetBeaconQuery(UserInfo user, string filePath = null) var roles = 0; if (user.UserID >= 0) { - if (user.IsSuperUser) roles |= (int)RolesEnum.Host; - if (user.IsInRole("Administrators")) roles |= (int)RolesEnum.Admin; - if (user.IsInRole("Content Managers")) roles |= (int)RolesEnum.ContentManager; - if (user.IsInRole("Content Editors")) roles |= (int)RolesEnum.ContentEditor; - if (user.IsInRole("Community Manager")) roles |= (int)RolesEnum.CommunityManager; + if (user.IsSuperUser) + { + roles |= (int)RolesEnum.Host; + } + + if (user.IsInRole("Administrators")) + { + roles |= (int)RolesEnum.Admin; + } + + if (user.IsInRole("Content Managers")) + { + roles |= (int)RolesEnum.ContentManager; + } + + if (user.IsInRole("Content Editors")) + { + roles |= (int)RolesEnum.ContentEditor; + } + + if (user.IsInRole("Community Manager")) + { + roles |= (int)RolesEnum.CommunityManager; + } } // h: Host GUID - hashed @@ -91,59 +112,85 @@ public string GetBeaconQuery(UserInfo user, string filePath = null) // f: page name / tab path // n: Product Edition - hashed // v: Version - hashed - var uid = user.UserID.ToString("D") + user.CreatedOnDate.ToString("O"); var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var qparams = new Dictionary { // Remember to URL ENCODE values that can be ambigious - {"h", HttpUtility.UrlEncode(GetHash(Host.GUID))}, - {"p", HttpUtility.UrlEncode(GetHash(portalSettings.GUID.ToString()))}, - {"a", HttpUtility.UrlEncode(GetHash(portalSettings.PortalAlias.HTTPAlias))}, - {"u", HttpUtility.UrlEncode(GetHash(uid))}, - {"r", roles.ToString("D")}, + { "h", HttpUtility.UrlEncode(this.GetHash(Host.GUID)) }, + { "p", HttpUtility.UrlEncode(this.GetHash(portalSettings.GUID.ToString())) }, + { "a", HttpUtility.UrlEncode(this.GetHash(portalSettings.PortalAlias.HTTPAlias)) }, + { "u", HttpUtility.UrlEncode(this.GetHash(uid)) }, + { "r", roles.ToString("D") }, }; - if (!string.IsNullOrEmpty(filePath)) - qparams["f"] = HttpUtility.UrlEncode(filePath); - - //add package and version to context of request + if (!string.IsNullOrEmpty(filePath)) + { + qparams["f"] = HttpUtility.UrlEncode(filePath); + } + + // add package and version to context of request string packageName = DotNetNukeContext.Current.Application.Name; - string installVersion = Common.Globals.FormatVersion(DotNetNukeContext.Current.Application.Version, "00", 3, ""); - if (!string.IsNullOrEmpty(packageName)) - qparams["n"] = HttpUtility.UrlEncode(GetHash(packageName)); - if (!string.IsNullOrEmpty(installVersion)) - qparams["v"] = HttpUtility.UrlEncode(GetHash(installVersion)); - + string installVersion = Common.Globals.FormatVersion(DotNetNukeContext.Current.Application.Version, "00", 3, string.Empty); + if (!string.IsNullOrEmpty(packageName)) + { + qparams["n"] = HttpUtility.UrlEncode(this.GetHash(packageName)); + } + + if (!string.IsNullOrEmpty(installVersion)) + { + qparams["v"] = HttpUtility.UrlEncode(this.GetHash(installVersion)); + } + return "?" + string.Join("&", qparams.Select(kpv => kpv.Key + "=" + kpv.Value)); } public string GetBeaconUrl(UserInfo user, string filePath = null) { - return GetBeaconEndpoint() + GetBeaconQuery(user, filePath); + return this.GetBeaconEndpoint() + this.GetBeaconQuery(user, filePath); } - private string GetHash(string data) + private static RolesEnum GetUserRolesBitValues(UserInfo user) { - using (var sha256 = CryptographyUtils.CreateSHA256()) + var roles = RolesEnum.None; + if (user.UserID >= 0) { - var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(data)); - return Convert.ToBase64String(hash); + if (user.IsSuperUser) + { + roles |= RolesEnum.Host; + } + + if (user.IsInRole("Administrators")) + { + roles |= RolesEnum.Admin; + } + + if (user.IsInRole("Content Managers")) + { + roles |= RolesEnum.ContentManager; + } + + if (user.IsInRole("Content Editors")) + { + roles |= RolesEnum.ContentEditor; + } + + if (user.IsInRole("Community Manager")) + { + roles |= RolesEnum.CommunityManager; + } } + + return roles; } - private static RolesEnum GetUserRolesBitValues(UserInfo user) + private string GetHash(string data) { - var roles = RolesEnum.None; - if (user.UserID >= 0) + using (var sha256 = CryptographyUtils.CreateSHA256()) { - if (user.IsSuperUser) roles |= RolesEnum.Host; - if (user.IsInRole("Administrators")) roles |= RolesEnum.Admin; - if (user.IsInRole("Content Managers")) roles |= RolesEnum.ContentManager; - if (user.IsInRole("Content Editors")) roles |= RolesEnum.ContentEditor; - if (user.IsInRole("Community Manager")) roles |= RolesEnum.CommunityManager; + var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(data)); + return Convert.ToBase64String(hash); } - return roles; } } } diff --git a/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs b/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs index 77e84aa7c49..b811084252a 100644 --- a/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs +++ b/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs @@ -1,17 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.ImprovementsProgram { + using DotNetNuke.Entities.Users; + public interface IBeaconService { string GetBeaconEndpoint(); + string GetBeaconQuery(UserInfo user, string filePath = null); + string GetBeaconUrl(UserInfo user, string filePath = null); + bool IsBeaconEnabledForControlBar(UserInfo user); + bool IsBeaconEnabledForPersonaBar(); } } diff --git a/DNN Platform/Library/Services/ImprovementsProgram/RolesEnum.cs b/DNN Platform/Library/Services/ImprovementsProgram/RolesEnum.cs index 740314d263b..57a2d995d13 100644 --- a/DNN Platform/Library/Services/ImprovementsProgram/RolesEnum.cs +++ b/DNN Platform/Library/Services/ImprovementsProgram/RolesEnum.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.ImprovementsProgram { + using System; + [Flags] internal enum RolesEnum { @@ -14,6 +14,6 @@ internal enum RolesEnum Admin = 2, CommunityManager = 4, ContentManager = 8, - ContentEditor = 16 + ContentEditor = 16, } } diff --git a/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs b/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs index 723ecc6176c..6929f0dd092 100644 --- a/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs +++ b/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Blocker { /// @@ -10,7 +10,9 @@ namespace DotNetNuke.Services.Installer.Blocker public interface IInstallBlocker { void RegisterInstallBegining(); + void RegisterInstallEnd(); + bool IsInstallInProgress(); } } diff --git a/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs b/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs index bce48405056..e11e9e34d25 100644 --- a/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs +++ b/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs @@ -1,67 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities.Internal; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Blocker { + using System; + using System.IO; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities.Internal; + using DotNetNuke.Framework; + /// /// This class ... /// public class InstallBlocker : ServiceLocator, IInstallBlocker - { - #region Constants - - const string installBlockerFile = "\\installBlocker.lock"; - #endregion - - #region Members - private bool fileCreated = false; - #endregion - - #region Public Methods - + { + private const string installBlockerFile = "\\installBlocker.lock"; + private bool fileCreated = false; + public void RegisterInstallBegining() - { - if(!fileCreated) - File.Create(Globals.ApplicationMapPath + installBlockerFile); - fileCreated = true; + { + if (!this.fileCreated) + { + File.Create(Globals.ApplicationMapPath + installBlockerFile); + } + + this.fileCreated = true; } public bool IsInstallInProgress() { - return fileCreated || File.Exists(Globals.ApplicationMapPath + installBlockerFile); + return this.fileCreated || File.Exists(Globals.ApplicationMapPath + installBlockerFile); } public void RegisterInstallEnd() { - var retryable = new RetryableAction(() => + var retryable = new RetryableAction( + () => { - if (IsInstallInProgress() && fileCreated) + if (this.IsInstallInProgress() && this.fileCreated) { File.Delete(Globals.ApplicationMapPath + installBlockerFile); } }, "Deleting lock file", 60, TimeSpan.FromSeconds(1)); retryable.TryIt(); - fileCreated = false; - } - - #endregion - - #region Private Methods - #endregion - - #region Service Locator + this.fileCreated = false; + } + protected override Func GetFactory() { return () => new InstallBlocker(); - } - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs index 385d999e7b1..046eacdcb7e 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Reflection; -using System.Xml.XPath; - -using DotNetNuke.Application; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Dependencies { + using System; + using System.Reflection; + using System.Xml.XPath; + + using DotNetNuke.Application; + /// ----------------------------------------------------------------------------- /// - /// The CoreVersionDependency determines whether the CoreVersion is correct + /// The CoreVersionDependency determines whether the CoreVersion is correct. /// /// /// @@ -29,7 +24,7 @@ public override string ErrorMessage { get { - return string.Format(Util.INSTALL_Compatibility,minVersion); + return string.Format(Util.INSTALL_Compatibility, this.minVersion); } } @@ -38,17 +33,18 @@ public override bool IsValid get { bool _IsValid = true; - if (Assembly.GetExecutingAssembly().GetName().Version < minVersion) + if (Assembly.GetExecutingAssembly().GetName().Version < this.minVersion) { _IsValid = false; } + return _IsValid; } } public override void ReadManifest(XPathNavigator dependencyNav) { - minVersion = new Version(dependencyNav.Value); + this.minVersion = new Version(dependencyNav.Value); } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs b/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs index 76a95d59c47..dc4fa35d467 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs @@ -1,28 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Dependencies { + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// - /// The DependencyBase is a base class for Installer Dependencies + /// The DependencyBase is a base class for Installer Dependencies. /// /// /// /// ----------------------------------------------------------------------------- public abstract class DependencyBase : IDependency - { - #region IDependency Members - + { public virtual string ErrorMessage { get @@ -41,8 +34,6 @@ public virtual bool IsValid public virtual void ReadManifest(XPathNavigator dependencyNav) { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs b/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs index 26e72a282cf..5bb995718f5 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs @@ -1,35 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml.XPath; - -using DotNetNuke.Common.Lists; -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Dependencies { + using System.Xml.XPath; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Framework; + /// ----------------------------------------------------------------------------- /// /// The DependencyFactory is a factory class that is used to instantiate the - /// appropriate Dependency + /// appropriate Dependency. /// /// /// /// ----------------------------------------------------------------------------- public class DependencyFactory - { - #region Public Shared Methods - + { /// ----------------------------------------------------------------------------- /// - /// The GetDependency method instantiates (and returns) the relevant Dependency + /// The GetDependency method instantiates (and returns) the relevant Dependency. /// - /// The manifest (XPathNavigator) for the dependency + /// The manifest (XPathNavigator) for the dependency. + /// /// ----------------------------------------------------------------------------- public static IDependency GetDependency(XPathNavigator dependencyNav) { @@ -53,27 +47,28 @@ public static IDependency GetDependency(XPathNavigator dependencyNav) dependency = new TypeDependency(); break; default: - //Dependency type is defined in the List + // Dependency type is defined in the List var listController = new ListController(); ListEntryInfo entry = listController.GetListEntryInfo("Dependency", dependencyType); if (entry != null && !string.IsNullOrEmpty(entry.Text)) { - //The class for the Installer is specified in the Text property + // The class for the Installer is specified in the Text property dependency = (DependencyBase)Reflection.CreateObject(entry.Text, "Dependency_" + entry.Value); } + break; } + if (dependency == null) { - //Could not create dependency, show generic error message + // Could not create dependency, show generic error message dependency = new InvalidDependency(Util.INSTALL_Dependencies); } - //Read Manifest + + // Read Manifest dependency.ReadManifest(dependencyNav); return dependency; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs index cc7c7058961..31aaa8a2700 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml.XPath; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Dependencies { + using System.Xml.XPath; + /// ----------------------------------------------------------------------------- /// - /// The IDependency Interface defines the contract for a Package Dependency + /// The IDependency Interface defines the contract for a Package Dependency. /// /// /// @@ -20,6 +15,7 @@ namespace DotNetNuke.Services.Installer.Dependencies public interface IDependency { string ErrorMessage { get; } + bool IsValid { get; } void ReadManifest(XPathNavigator dependencyNav); diff --git a/DNN Platform/Library/Services/Installer/Dependencies/IManagedPackageDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/IManagedPackageDependency.cs index febc0f0dcb9..c97cd824525 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/IManagedPackageDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/IManagedPackageDependency.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Dependencies { + using DotNetNuke.Services.Installer.Packages; + public interface IManagedPackageDependency { PackageDependencyInfo PackageDependency { get; set; } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/InvalidDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/InvalidDependency.cs index 423268dba02..12d69140c2e 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/InvalidDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/InvalidDependency.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Dependencies { /// ----------------------------------------------------------------------------- /// /// The InvalidDependency signifies a dependency that is always invalid, - /// taking the place of dependencies that could not be created + /// taking the place of dependencies that could not be created. /// /// /// @@ -22,14 +22,14 @@ public class InvalidDependency : DependencyBase /// The error message to display. public InvalidDependency(string ErrorMessage) { - _ErrorMessage = ErrorMessage; + this._ErrorMessage = ErrorMessage; } public override string ErrorMessage { get { - return _ErrorMessage; + return this._ErrorMessage; } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs index b726ea3def0..76af91f2840 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs @@ -1,23 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Dependencies { + using System; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Packages; + public class ManagedPackageDependency : DependencyBase, IManagedPackageDependency { - public override string ErrorMessage { get { - return Util.INSTALL_Package + " - " + PackageDependency.PackageName; + return Util.INSTALL_Package + " - " + this.PackageDependency.PackageName; } } @@ -27,31 +26,29 @@ public override bool IsValid { bool _IsValid = true; - //Get Package from DataStore - PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, - (p) => p.Name.Equals(PackageDependency.PackageName, StringComparison.OrdinalIgnoreCase) - && p.Version >= PackageDependency.Version); + // Get Package from DataStore + PackageInfo package = PackageController.Instance.GetExtensionPackage( + Null.NullInteger, + (p) => p.Name.Equals(this.PackageDependency.PackageName, StringComparison.OrdinalIgnoreCase) + && p.Version >= this.PackageDependency.Version); if (package == null) { _IsValid = false; } + return _IsValid; } } + + public PackageDependencyInfo PackageDependency { get; set; } public override void ReadManifest(XPathNavigator dependencyNav) { - PackageDependency = new PackageDependencyInfo + this.PackageDependency = new PackageDependencyInfo { PackageName = dependencyNav.Value, - Version = new Version(Util.ReadAttribute(dependencyNav, "version")) + Version = new Version(Util.ReadAttribute(dependencyNav, "version")), }; - } - - #region IManagedPackageDependency Implementation - - public PackageDependencyInfo PackageDependency { get; set; } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs index 3049c8dceec..a27c71ac6ef 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs @@ -1,23 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Dependencies { using System; - + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The PackageDependency determines whether the dependent package is installed + /// The PackageDependency determines whether the dependent package is installed. /// /// /// @@ -30,7 +24,7 @@ public override string ErrorMessage { get { - return Util.INSTALL_Package + " - " + PackageName; + return Util.INSTALL_Package + " - " + this.PackageName; } } @@ -40,19 +34,20 @@ public override bool IsValid { bool _IsValid = true; - //Get Package from DataStore - PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, (p) => p.Name.Equals(PackageName, StringComparison.OrdinalIgnoreCase)); + // Get Package from DataStore + PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, (p) => p.Name.Equals(this.PackageName, StringComparison.OrdinalIgnoreCase)); if (package == null) { _IsValid = false; } + return _IsValid; } } public override void ReadManifest(XPathNavigator dependencyNav) { - PackageName = dependencyNav.Value; + this.PackageName = dependencyNav.Value; } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/PermissionsDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/PermissionsDependency.cs index 15e9b1c213a..c021099cc5c 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/PermissionsDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/PermissionsDependency.cs @@ -1,22 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Dependencies { + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// /// The PermissionsDependency determines whether the DotNetNuke site has the - /// corretc permissions + /// corretc permissions. /// /// /// @@ -30,7 +27,7 @@ public override string ErrorMessage { get { - return Util.INSTALL_Permissions + " - " + Localization.Localization.GetString(Permission, Localization.Localization.GlobalResourceFile); + return Util.INSTALL_Permissions + " - " + Localization.GetString(this.Permission, Localization.GlobalResourceFile); } } @@ -38,13 +35,13 @@ public override bool IsValid { get { - return SecurityPolicy.HasPermissions(Permissions, ref Permission); + return SecurityPolicy.HasPermissions(this.Permissions, ref this.Permission); } } public override void ReadManifest(XPathNavigator dependencyNav) { - Permissions = dependencyNav.Value; + this.Permissions = dependencyNav.Value; } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs index 9dd356b5982..5ef3360e38d 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml.XPath; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Dependencies { + using System; + using System.Xml.XPath; + + using DotNetNuke.Framework; + /// ----------------------------------------------------------------------------- /// - /// The TypeDependency determines whether the dependent type is installed + /// The TypeDependency determines whether the dependent type is installed. /// /// /// /// ----------------------------------------------------------------------------- public class TypeDependency : DependencyBase { - private string _missingDependentType = String.Empty; + private string _missingDependentType = string.Empty; private string _dependentTypes; public override string ErrorMessage { get { - return Util.INSTALL_Namespace + " - " + _missingDependentType; + return Util.INSTALL_Namespace + " - " + this._missingDependentType; } } @@ -38,28 +33,29 @@ public override bool IsValid get { bool isValid = true; - if (!String.IsNullOrEmpty(_dependentTypes)) + if (!string.IsNullOrEmpty(this._dependentTypes)) { - foreach (string dependentType in (_dependentTypes + ";").Split(';')) + foreach (string dependentType in (this._dependentTypes + ";").Split(';')) { - if (!String.IsNullOrEmpty(dependentType.Trim())) + if (!string.IsNullOrEmpty(dependentType.Trim())) { if (Reflection.CreateType(dependentType, true) == null) { - _missingDependentType = dependentType; + this._missingDependentType = dependentType; isValid = false; break; } } } } + return isValid; } } public override void ReadManifest(XPathNavigator dependencyNav) { - _dependentTypes = dependencyNav.Value; + this._dependentTypes = dependencyNav.Value; } } } diff --git a/DNN Platform/Library/Services/Installer/InstallFile.cs b/DNN Platform/Library/Services/Installer/InstallFile.cs index 97c39c4f26d..59fb30975bd 100644 --- a/DNN Platform/Library/Services/Installer/InstallFile.cs +++ b/DNN Platform/Library/Services/Installer/InstallFile.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.IO; -using System.Text.RegularExpressions; - -using ICSharpCode.SharpZipLib.Zip; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { + using System; + using System.ComponentModel; + using System.IO; + using System.Text.RegularExpressions; + + using ICSharpCode.SharpZipLib.Zip; + /// ----------------------------------------------------------------------------- /// - /// The InstallFile class represents a single file in an Installer Package + /// The InstallFile class represents a single file in an Installer Package. /// /// /// @@ -25,124 +20,119 @@ namespace DotNetNuke.Services.Installer [Serializable] public class InstallFile { - private static readonly Regex FileTypeMatchRegex = new Regex(Util.REGEX_Version + ".txt", RegexOptions.Compiled); - - #region Private Members - - #endregion - - #region Constructors - + private static readonly Regex FileTypeMatchRegex = new Regex(Util.REGEX_Version + ".txt", RegexOptions.Compiled); + /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallFile instance from a ZipInputStream and a ZipEntry + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallFile instance from a ZipInputStream and a ZipEntry. /// /// The ZipInputStream is read into a byte array (Buffer), and the ZipEntry is used to /// set up the properties of the InstallFile class. - /// The ZipInputStream - /// The ZipEntry - /// An INstallerInfo instance + /// The ZipInputStream. + /// The ZipEntry. + /// An INstallerInfo instance. /// ----------------------------------------------------------------------------- public InstallFile(ZipInputStream zip, ZipEntry entry, InstallerInfo info) { - Encoding = TextEncoding.UTF8; - InstallerInfo = info; - ReadZip(zip, entry); - } - - /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallFile instance + this.Encoding = TextEncoding.UTF8; + this.InstallerInfo = info; + this.ReadZip(zip, entry); + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallFile instance. /// - /// The fileName of the File + /// The fileName of the File. /// ----------------------------------------------------------------------------- public InstallFile(string fileName) { - Encoding = TextEncoding.UTF8; - ParseFileName(fileName); - } - - /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallFile instance + this.Encoding = TextEncoding.UTF8; + this.ParseFileName(fileName); + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallFile instance. /// - /// The fileName of the File - /// An INstallerInfo instance + /// The fileName of the File. + /// An INstallerInfo instance. /// ----------------------------------------------------------------------------- public InstallFile(string fileName, InstallerInfo info) { - Encoding = TextEncoding.UTF8; - ParseFileName(fileName); - InstallerInfo = info; - } - - /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallFile instance + this.Encoding = TextEncoding.UTF8; + this.ParseFileName(fileName); + this.InstallerInfo = info; + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallFile instance. /// - /// The fileName of the File + /// The fileName of the File. /// Source file name. - /// An INstallerInfo instance + /// An INstallerInfo instance. /// ----------------------------------------------------------------------------- public InstallFile(string fileName, string sourceFileName, InstallerInfo info) { - Encoding = TextEncoding.UTF8; - ParseFileName(fileName); - SourceFileName = sourceFileName; - InstallerInfo = info; - } - - /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallFile instance + this.Encoding = TextEncoding.UTF8; + this.ParseFileName(fileName); + this.SourceFileName = sourceFileName; + this.InstallerInfo = info; + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallFile instance. /// - /// The file name of the File - /// The file path of the file + /// The file name of the File. + /// The file path of the file. /// ----------------------------------------------------------------------------- public InstallFile(string fileName, string filePath) { - Encoding = TextEncoding.UTF8; - Name = fileName; - Path = filePath; - } - - #endregion - - #region Public Properties - + this.Encoding = TextEncoding.UTF8; + this.Name = fileName; + this.Path = filePath; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Action for this file + /// Gets or sets and sets the Action for this file. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string Action { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the location of the backup file + /// Gets the location of the backup file. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string BackupFileName { get { - return System.IO.Path.Combine(BackupPath, Name + ".config"); + return System.IO.Path.Combine(this.BackupPath, this.Name + ".config"); } } /// ----------------------------------------------------------------------------- /// - /// Gets the location of the backup folder + /// Gets the location of the backup folder. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public virtual string BackupPath { get { - return System.IO.Path.Combine(InstallerInfo.TempInstallFolder, System.IO.Path.Combine("Backup", Path)); + return System.IO.Path.Combine(this.InstallerInfo.TempInstallFolder, System.IO.Path.Combine("Backup", this.Path)); } } @@ -150,216 +140,211 @@ public virtual string BackupPath /// ----------------------------------------------------------------------------- /// - /// Gets the File Extension of the file + /// Gets the File Extension of the file. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string Extension { get { - string ext = System.IO.Path.GetExtension(Name); - if (String.IsNullOrEmpty(ext)) + string ext = System.IO.Path.GetExtension(this.Name); + if (string.IsNullOrEmpty(ext)) { - return ""; + return string.Empty; } + return ext.Substring(1); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Full Name of the file + /// Gets the Full Name of the file. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string FullName { get { - return System.IO.Path.Combine(Path, Name); + return System.IO.Path.Combine(this.Path, this.Name); } } /// ----------------------------------------------------------------------------- /// - /// Gets the associated InstallerInfo + /// Gets the associated InstallerInfo. /// - /// An InstallerInfo object + /// An InstallerInfo object. /// ----------------------------------------------------------------------------- [Browsable(false)] public InstallerInfo InstallerInfo { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Name of the file + /// Gets the Name of the file. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string Name { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Path of the file + /// Gets the Path of the file. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string Path { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the source file name + /// Gets the source file name. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string SourceFileName { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the location of the temporary file + /// Gets the location of the temporary file. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string TempFileName { get { - string fileName = SourceFileName; + string fileName = this.SourceFileName; if (string.IsNullOrEmpty(fileName)) { - fileName = FullName; + fileName = this.FullName; } - return System.IO.Path.Combine(InstallerInfo.TempInstallFolder, fileName); + + return System.IO.Path.Combine(this.InstallerInfo.TempInstallFolder, fileName); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Type of the file + /// Gets or sets and sets the Type of the file. /// - /// An InstallFileType Enumeration + /// An InstallFileType Enumeration. /// ----------------------------------------------------------------------------- public InstallFileType Type { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Version of the file + /// Gets the Version of the file. /// - /// A System.Version + /// A System.Version. /// ----------------------------------------------------------------------------- - public Version Version { get; private set; } - - #endregion - - #region Private Methods - + public Version Version { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// The SetVersion method sets the version of the file. + /// + /// The version of the file. + /// ----------------------------------------------------------------------------- + public void SetVersion(Version version) + { + this.Version = version; + } + /// ----------------------------------------------------------------------------- /// - /// The ParseFileName parses the ZipEntry metadata + /// The ParseFileName parses the ZipEntry metadata. /// - /// A String representing the file name + /// A String representing the file name. /// ----------------------------------------------------------------------------- private void ParseFileName(string fileName) { int i = fileName.Replace("\\", "/").LastIndexOf("/", StringComparison.Ordinal); if (i < 0) { - Name = fileName.Substring(0, fileName.Length); - Path = ""; + this.Name = fileName.Substring(0, fileName.Length); + this.Path = string.Empty; } else { - Name = fileName.Substring(i + 1, fileName.Length - (i + 1)); - Path = fileName.Substring(0, i); + this.Name = fileName.Substring(i + 1, fileName.Length - (i + 1)); + this.Path = fileName.Substring(0, i); } - if (string.IsNullOrEmpty(Path) && fileName.StartsWith("[app_code]")) + + if (string.IsNullOrEmpty(this.Path) && fileName.StartsWith("[app_code]")) { - Name = fileName.Substring(10, fileName.Length - 10); - Path = fileName.Substring(0, 10); + this.Name = fileName.Substring(10, fileName.Length - 10); + this.Path = fileName.Substring(0, 10); } - if (Name.Equals("manifest.xml", StringComparison.InvariantCultureIgnoreCase)) + + if (this.Name.Equals("manifest.xml", StringComparison.InvariantCultureIgnoreCase)) { - Type = InstallFileType.Manifest; + this.Type = InstallFileType.Manifest; } else { - switch (Extension.ToLowerInvariant()) + switch (this.Extension.ToLowerInvariant()) { case "ascx": - Type = InstallFileType.Ascx; + this.Type = InstallFileType.Ascx; break; case "dll": - Type = InstallFileType.Assembly; + this.Type = InstallFileType.Assembly; break; case "dnn": case "dnn5": case "dnn6": case "dnn7": - Type = InstallFileType.Manifest; + this.Type = InstallFileType.Manifest; break; case "resx": - Type = InstallFileType.Language; + this.Type = InstallFileType.Language; break; case "resources": case "zip": - Type = InstallFileType.Resources; + this.Type = InstallFileType.Resources; break; default: - if (Extension.EndsWith("dataprovider", StringComparison.InvariantCultureIgnoreCase) || Extension.Equals("sql", StringComparison.InvariantCultureIgnoreCase)) + if (this.Extension.EndsWith("dataprovider", StringComparison.InvariantCultureIgnoreCase) || this.Extension.Equals("sql", StringComparison.InvariantCultureIgnoreCase)) { - Type = InstallFileType.Script; + this.Type = InstallFileType.Script; } - else if (Path.StartsWith("[app_code]")) + else if (this.Path.StartsWith("[app_code]")) { - Type = InstallFileType.AppCode; + this.Type = InstallFileType.AppCode; } else { - Type = FileTypeMatchRegex.IsMatch(Name) ? InstallFileType.CleanUp : InstallFileType.Other; + this.Type = FileTypeMatchRegex.IsMatch(this.Name) ? InstallFileType.CleanUp : InstallFileType.Other; } + break; } } - - //remove [app_code] token - Path = Path.Replace("[app_code]", ""); - //remove starting "\" - if (Path.StartsWith("\\")) + // remove [app_code] token + this.Path = this.Path.Replace("[app_code]", string.Empty); + + // remove starting "\" + if (this.Path.StartsWith("\\")) { - Path = Path.Substring(1); + this.Path = this.Path.Substring(1); } } /// ----------------------------------------------------------------------------- /// - /// The ReadZip method reads the zip stream and parses the ZipEntry metadata + /// The ReadZip method reads the zip stream and parses the ZipEntry metadata. /// - /// A ZipStream containing the file content - /// A ZipEntry containing the file metadata + /// A ZipStream containing the file content. + /// A ZipEntry containing the file metadata. /// ----------------------------------------------------------------------------- private void ReadZip(ZipInputStream unzip, ZipEntry entry) { - ParseFileName(entry.Name); - Util.WriteStream(unzip, TempFileName); - File.SetLastWriteTime(TempFileName, entry.DateTime); - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// The SetVersion method sets the version of the file - /// - /// The version of the file - /// ----------------------------------------------------------------------------- - public void SetVersion(Version version) - { - Version = version; - } - - #endregion + this.ParseFileName(entry.Name); + Util.WriteStream(unzip, this.TempFileName); + File.SetLastWriteTime(this.TempFileName, entry.DateTime); + } } } diff --git a/DNN Platform/Library/Services/Installer/InstallFileType.cs b/DNN Platform/Library/Services/Installer/InstallFileType.cs index 121ed2d544b..869f2fe2b90 100644 --- a/DNN Platform/Library/Services/Installer/InstallFileType.cs +++ b/DNN Platform/Library/Services/Installer/InstallFileType.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { - [TypeConverter(typeof (EnumConverter))] + using System.ComponentModel; + + [TypeConverter(typeof(EnumConverter))] public enum InstallFileType { AppCode, @@ -21,6 +16,6 @@ public enum InstallFileType Manifest, Other, Resources, - Script + Script, } } diff --git a/DNN Platform/Library/Services/Installer/InstallMode.cs b/DNN Platform/Library/Services/Installer/InstallMode.cs index 065c10edab1..ef95d8f4ab7 100644 --- a/DNN Platform/Library/Services/Installer/InstallMode.cs +++ b/DNN Platform/Library/Services/Installer/InstallMode.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { - [TypeConverter(typeof (EnumConverter))] + using System.ComponentModel; + + [TypeConverter(typeof(EnumConverter))] public enum InstallMode { Install, ManifestOnly, - UnInstall + UnInstall, } } diff --git a/DNN Platform/Library/Services/Installer/Installer.cs b/DNN Platform/Library/Services/Installer/Installer.cs index 071ea0e2bae..99c5e85030f 100644 --- a/DNN Platform/Library/Services/Installer/Installer.cs +++ b/DNN Platform/Library/Services/Installer/Installer.cs @@ -1,200 +1,347 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Installers; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Installer.Writers; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { - using Entities.Controllers; - + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Installers; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Installer.Writers; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Web.Client.ClientResourceManagement; + /// ----------------------------------------------------------------------------- /// - /// The Installer class provides a single entrypoint for Package Installation + /// The Installer class provides a single entrypoint for Package Installation. /// /// ----------------------------------------------------------------------------- public class Installer { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Installer)); - #region Private Members - - private Stream _inputStream; - - #endregion - - #region Constructors - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Installer)); + private Stream _inputStream; + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// This Constructor creates a new Installer instance from a string representing - /// the physical path to the temporary install folder and a string representing - /// the physical path to the root of the site + /// the physical path to the temporary install folder and a string representing + /// the physical path to the root of the site. /// - /// The physical path to the zip file containg the package - /// The manifest filename - /// The physical path to the root of the site - /// Flag that determines whether the manifest will be loaded + /// The physical path to the zip file containg the package. + /// The manifest filename. + /// The physical path to the root of the site. + /// Flag that determines whether the manifest will be loaded. /// ----------------------------------------------------------------------------- public Installer(string tempFolder, string manifest, string physicalSitePath, bool loadManifest) { - Packages = new SortedList(); - //Called from Interactive installer - default IgnoreWhiteList to false - InstallerInfo = new InstallerInfo(tempFolder, manifest, physicalSitePath) { IgnoreWhiteList = false }; + this.Packages = new SortedList(); + + // Called from Interactive installer - default IgnoreWhiteList to false + this.InstallerInfo = new InstallerInfo(tempFolder, manifest, physicalSitePath) { IgnoreWhiteList = false }; if (loadManifest) { - ReadManifest(true); + this.ReadManifest(true); } - } - + } + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// This Constructor creates a new Installer instance from a Stream and a - /// string representing the physical path to the root of the site + /// string representing the physical path to the root of the site. /// - /// The Stream to use to create this InstallerInfo instance - /// The physical path to the root of the site - /// Flag that determines whether the manifest will be loaded + /// The Stream to use to create this InstallerInfo instance. + /// The physical path to the root of the site. + /// Flag that determines whether the manifest will be loaded. /// ----------------------------------------------------------------------------- - public Installer(Stream inputStream, string physicalSitePath, bool loadManifest) : this(inputStream, physicalSitePath, loadManifest, true) + public Installer(Stream inputStream, string physicalSitePath, bool loadManifest) + : this(inputStream, physicalSitePath, loadManifest, true) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// This Constructor creates a new Installer instance from a Stream and a - /// string representing the physical path to the root of the site + /// string representing the physical path to the root of the site. /// - /// The Stream to use to create this InstallerInfo instance - /// The physical path to the root of the site - /// Flag that determines whether the manifest will be loaded + /// The Stream to use to create this InstallerInfo instance. + /// The physical path to the root of the site. + /// Flag that determines whether the manifest will be loaded. /// Whether delete the temp folder. /// ----------------------------------------------------------------------------- public Installer(Stream inputStream, string physicalSitePath, bool loadManifest, bool deleteTemp) { - Packages = new SortedList(); + this.Packages = new SortedList(); - _inputStream = new MemoryStream(); - inputStream.CopyTo(_inputStream); - //Called from Batch installer - default IgnoreWhiteList to true - InstallerInfo = new InstallerInfo(inputStream, physicalSitePath) { IgnoreWhiteList = true }; + this._inputStream = new MemoryStream(); + inputStream.CopyTo(this._inputStream); + + // Called from Batch installer - default IgnoreWhiteList to true + this.InstallerInfo = new InstallerInfo(inputStream, physicalSitePath) { IgnoreWhiteList = true }; if (loadManifest) { - ReadManifest(deleteTemp); + this.ReadManifest(deleteTemp); } - } - + } + /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new Installer instance from a PackageInfo object + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new Installer instance from a PackageInfo object. /// - /// The PackageInfo instance - /// The physical path to the root of the site + /// The PackageInfo instance. + /// The physical path to the root of the site. /// ----------------------------------------------------------------------------- public Installer(PackageInfo package, string physicalSitePath) { - Packages = new SortedList(); - InstallerInfo = new InstallerInfo(package, physicalSitePath); + this.Packages = new SortedList(); + this.InstallerInfo = new InstallerInfo(package, physicalSitePath); - Packages.Add(Packages.Count, new PackageInstaller(package)); + this.Packages.Add(this.Packages.Count, new PackageInstaller(package)); } public Installer(string manifest, string physicalSitePath, bool loadManifest) { - Packages = new SortedList(); - InstallerInfo = new InstallerInfo(physicalSitePath, InstallMode.ManifestOnly); + this.Packages = new SortedList(); + this.InstallerInfo = new InstallerInfo(physicalSitePath, InstallMode.ManifestOnly); if (loadManifest) { - ReadManifest(new FileStream(manifest, FileMode.Open, FileAccess.Read)); + this.ReadManifest(new FileStream(manifest, FileMode.Open, FileAccess.Read)); } - } - - #endregion - - #region Public Properties - + } + /// ----------------------------------------------------------------------------- /// - /// Gets the associated InstallerInfo object + /// Gets the associated InstallerInfo object. /// - /// An InstallerInfo + /// An InstallerInfo. /// ----------------------------------------------------------------------------- public InstallerInfo InstallerInfo { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the associated InstallerInfo is valid + /// Gets a value indicating whether gets whether the associated InstallerInfo is valid. /// - /// True - if valid, False if not + /// True - if valid, False if not. /// ----------------------------------------------------------------------------- public bool IsValid { get { - return InstallerInfo.IsValid; + return this.InstallerInfo.IsValid; } } /// ----------------------------------------------------------------------------- /// - /// Gets a SortedList of Packages that are included in the Package Zip + /// Gets a SortedList of Packages that are included in the Package Zip. /// - /// A SortedList(Of Integer, PackageInstaller) + /// A SortedList(Of Integer, PackageInstaller). /// ----------------------------------------------------------------------------- public SortedList Packages { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets + /// Gets. /// - /// A Dictionary(Of String, PackageInstaller) + /// A Dictionary(Of String, PackageInstaller). /// ----------------------------------------------------------------------------- public string TempInstallFolder { get { - return InstallerInfo.TempInstallFolder; + return this.InstallerInfo.TempInstallFolder; + } + } + + public static XPathNavigator ConvertLegacyNavigator(XPathNavigator rootNav, InstallerInfo info) + { + XPathNavigator nav = null; + + var packageType = Null.NullString; + if (rootNav.Name == "dotnetnuke") + { + packageType = Util.ReadAttribute(rootNav, "type"); + } + else if (rootNav.Name.Equals("languagepack", StringComparison.InvariantCultureIgnoreCase)) + { + packageType = "LanguagePack"; + } + + XPathDocument legacyDoc; + string legacyManifest; + switch (packageType.ToLowerInvariant()) + { + case "module": + var sb = new StringBuilder(); + using (var writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + { + // Write manifest start element + PackageWriterBase.WriteManifestStartElement(writer); + + // Legacy Module - Process each folder + foreach (XPathNavigator folderNav in rootNav.Select("folders/folder")) + { + var modulewriter = new ModulePackageWriter(folderNav, info); + modulewriter.WriteManifest(writer, true); + } + + // Write manifest end element + PackageWriterBase.WriteManifestEndElement(writer); + + // Close XmlWriter + writer.Close(); + } + + // Load manifest into XPathDocument for processing + legacyDoc = new XPathDocument(new StringReader(sb.ToString())); + + // Parse the package nodes + nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); + break; + case "languagepack": + // Legacy Language Pack + var languageWriter = new LanguagePackWriter(rootNav, info); + info.LegacyError = languageWriter.LegacyError; + if (string.IsNullOrEmpty(info.LegacyError)) + { + legacyManifest = languageWriter.WriteManifest(false); + legacyDoc = new XPathDocument(new StringReader(legacyManifest)); + + // Parse the package nodes + nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); + } + + break; + case "skinobject": + // Legacy Skin Object + var skinControlwriter = new SkinControlPackageWriter(rootNav, info); + legacyManifest = skinControlwriter.WriteManifest(false); + legacyDoc = new XPathDocument(new StringReader(legacyManifest)); + + // Parse the package nodes + nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); + break; + } + + return nav; + } + + public void DeleteTempFolder() + { + try + { + if (!string.IsNullOrEmpty(this.TempInstallFolder)) + { + Directory.Delete(this.TempInstallFolder, true); + } + } + catch (Exception ex) + { + Logger.Error("Exception deleting folder " + this.TempInstallFolder + " while installing " + this.InstallerInfo.ManifestFile.Name, ex); + Exceptions.Exceptions.LogException(ex); } } - #endregion + /// ----------------------------------------------------------------------------- + /// + /// The Install method installs the feature. + /// + /// + /// ----------------------------------------------------------------------------- + public bool Install() + { + this.InstallerInfo.Log.StartJob(Util.INSTALL_Start); + bool bStatus = true; + try + { + bool clearClientCache = false; + this.InstallPackages(ref clearClientCache); + if (clearClientCache) + { + // Update the version of the client resources - so the cache is cleared + HostController.Instance.IncrementCrmVersion(true); + } + } + catch (Exception ex) + { + this.InstallerInfo.Log.AddFailure(ex); + bStatus = false; + } + finally + { + // Delete Temp Folder + if (!string.IsNullOrEmpty(this.TempInstallFolder)) + { + Globals.DeleteFolderRecursive(this.TempInstallFolder); + } + + this.InstallerInfo.Log.AddInfo(Util.FOLDER_DeletedBackup); + } + + if (this.InstallerInfo.Log.Valid) + { + this.InstallerInfo.Log.EndJob(Util.INSTALL_Success); + } + else + { + this.InstallerInfo.Log.EndJob(Util.INSTALL_Failed); + bStatus = false; + } + + // log installation event + this.LogInstallEvent("Package", "Install"); + + // when the installer initialized by file stream, we need save the file stream into backup folder. + if (this._inputStream != null && bStatus && this.Packages.Any()) + { + Task.Run(() => + { + this.BackupStreamIntoFile(this._inputStream, this.Packages[0].Package); + }); + } - #region Private Methods + // Clear Host Cache + DataCache.ClearHostCache(true); + if (Config.GetFcnMode() == Config.FcnMode.Disabled.ToString()) + { + // force application restart after the new changes only when FCN is disabled + Config.Touch(); + } + + return bStatus; + } + /// ----------------------------------------------------------------------------- /// - /// The InstallPackages method installs the packages + /// The InstallPackages method installs the packages. /// /// ----------------------------------------------------------------------------- private void InstallPackages(ref bool clearClientCache) { - //Iterate through all the Packages - for (int index = 0; index <= Packages.Count - 1; index++) + // Iterate through all the Packages + for (int index = 0; index <= this.Packages.Count - 1; index++) { - PackageInstaller installer = Packages.Values[index]; - //Check if package is valid + PackageInstaller installer = this.Packages.Values[index]; + + // Check if package is valid if (installer.Package.IsValid) { if (installer.Package.InstallerInfo.PackageID > Null.NullInteger || installer.Package.InstallerInfo.RepairInstall) @@ -202,73 +349,74 @@ private void InstallPackages(ref bool clearClientCache) clearClientCache = true; } - InstallerInfo.Log.AddInfo(Util.INSTALL_Start + " - " + installer.Package.Name); + this.InstallerInfo.Log.AddInfo(Util.INSTALL_Start + " - " + installer.Package.Name); installer.Install(); - if (InstallerInfo.Log.Valid) + if (this.InstallerInfo.Log.Valid) { - InstallerInfo.Log.AddInfo(Util.INSTALL_Success + " - " + installer.Package.Name); + this.InstallerInfo.Log.AddInfo(Util.INSTALL_Success + " - " + installer.Package.Name); } else { - InstallerInfo.Log.AddInfo(Util.INSTALL_Failed + " - " + installer.Package.Name); + this.InstallerInfo.Log.AddInfo(Util.INSTALL_Failed + " - " + installer.Package.Name); } } else { - InstallerInfo.Log.AddFailure(Util.INSTALL_Aborted + " - " + installer.Package.Name); + this.InstallerInfo.Log.AddFailure(Util.INSTALL_Aborted + " - " + installer.Package.Name); } } } /// ----------------------------------------------------------------------------- /// - /// Logs the Install event to the Event Log + /// Logs the Install event to the Event Log. /// - /// The name of the package + /// The name of the package. /// Event Type. /// ----------------------------------------------------------------------------- private void LogInstallEvent(string package, string eventType) { try { - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; - if (InstallerInfo.ManifestFile != null) - { - log.LogProperties.Add(new LogDetailInfo(eventType + " " + package + ":", InstallerInfo.ManifestFile.Name.Replace(".dnn", ""))); - } + if (this.InstallerInfo.ManifestFile != null) + { + log.LogProperties.Add(new LogDetailInfo(eventType + " " + package + ":", this.InstallerInfo.ManifestFile.Name.Replace(".dnn", string.Empty))); + } - foreach (LogEntry objLogEntry in InstallerInfo.Log.Logs) + foreach (LogEntry objLogEntry in this.InstallerInfo.Log.Logs) { log.LogProperties.Add(new LogDetailInfo("Info:", objLogEntry.Description)); } + LogController.Instance.AddLog(log); } catch (Exception exc) { Logger.Error(exc); - } } /// ----------------------------------------------------------------------------- /// - /// The ProcessPackages method processes the packages nodes in the manifest + /// The ProcessPackages method processes the packages nodes in the manifest. /// /// ----------------------------------------------------------------------------- private void ProcessPackages(XPathNavigator rootNav) { - //Parse the package nodes + // Parse the package nodes foreach (XPathNavigator nav in rootNav.Select("packages/package")) { - int order = Packages.Count; + int order = this.Packages.Count; string name = Util.ReadAttribute(nav, "name"); string installOrder = Util.ReadAttribute(nav, "installOrder"); if (!string.IsNullOrEmpty(installOrder)) { order = int.Parse(installOrder); } - Packages.Add(order, new PackageInstaller(nav.OuterXml, InstallerInfo)); + + this.Packages.Add(order, new PackageInstaller(nav.OuterXml, this.InstallerInfo)); } } @@ -276,7 +424,7 @@ private void ReadManifest(Stream stream) { var doc = new XPathDocument(stream); - //Read the root node to determine what version the manifest is + // Read the root node to determine what version the manifest is XPathNavigator rootNav = doc.CreateNavigator(); rootNav.MoveToFirstChild(); string packageType = Null.NullString; @@ -291,115 +439,45 @@ private void ReadManifest(Stream stream) } else { - InstallerInfo.Log.AddFailure(Util.PACKAGE_UnRecognizable); + this.InstallerInfo.Log.AddFailure(Util.PACKAGE_UnRecognizable); } + switch (packageType.ToLowerInvariant()) { case "package": - InstallerInfo.IsLegacyMode = false; - //Parse the package nodes - ProcessPackages(rootNav); + this.InstallerInfo.IsLegacyMode = false; + + // Parse the package nodes + this.ProcessPackages(rootNav); break; case "module": case "languagepack": case "skinobject": - InstallerInfo.IsLegacyMode = true; - ProcessPackages(ConvertLegacyNavigator(rootNav, InstallerInfo)); + this.InstallerInfo.IsLegacyMode = true; + this.ProcessPackages(ConvertLegacyNavigator(rootNav, this.InstallerInfo)); break; } } private void UnInstallPackages(bool deleteFiles) { - for (int index = 0; index <= Packages.Count - 1; index++) + for (int index = 0; index <= this.Packages.Count - 1; index++) { - PackageInstaller installer = Packages.Values[index]; - InstallerInfo.Log.AddInfo(Util.UNINSTALL_Start + " - " + installer.Package.Name); + PackageInstaller installer = this.Packages.Values[index]; + this.InstallerInfo.Log.AddInfo(Util.UNINSTALL_Start + " - " + installer.Package.Name); installer.DeleteFiles = deleteFiles; installer.UnInstall(); - if (InstallerInfo.Log.HasWarnings) + if (this.InstallerInfo.Log.HasWarnings) { - InstallerInfo.Log.AddWarning(Util.UNINSTALL_Warnings + " - " + installer.Package.Name); + this.InstallerInfo.Log.AddWarning(Util.UNINSTALL_Warnings + " - " + installer.Package.Name); } else { - InstallerInfo.Log.AddInfo(Util.UNINSTALL_Success + " - " + installer.Package.Name); + this.InstallerInfo.Log.AddInfo(Util.UNINSTALL_Success + " - " + installer.Package.Name); } } } - public static XPathNavigator ConvertLegacyNavigator(XPathNavigator rootNav, InstallerInfo info) - { - XPathNavigator nav = null; - - var packageType = Null.NullString; - if (rootNav.Name == "dotnetnuke") - { - packageType = Util.ReadAttribute(rootNav, "type"); - } - else if (rootNav.Name.Equals("languagepack", StringComparison.InvariantCultureIgnoreCase)) - { - packageType = "LanguagePack"; - } - - XPathDocument legacyDoc; - string legacyManifest; - switch (packageType.ToLowerInvariant()) - { - case "module": - var sb = new StringBuilder(); - using (var writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) - { - //Write manifest start element - PackageWriterBase.WriteManifestStartElement(writer); - - //Legacy Module - Process each folder - foreach (XPathNavigator folderNav in rootNav.Select("folders/folder")) - { - var modulewriter = new ModulePackageWriter(folderNav, info); - modulewriter.WriteManifest(writer, true); - } - - //Write manifest end element - PackageWriterBase.WriteManifestEndElement(writer); - - //Close XmlWriter - writer.Close(); - } - - //Load manifest into XPathDocument for processing - legacyDoc = new XPathDocument(new StringReader(sb.ToString())); - - //Parse the package nodes - nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); - break; - case "languagepack": - //Legacy Language Pack - var languageWriter = new LanguagePackWriter(rootNav, info); - info.LegacyError = languageWriter.LegacyError; - if (string.IsNullOrEmpty(info.LegacyError)) - { - legacyManifest = languageWriter.WriteManifest(false); - legacyDoc = new XPathDocument(new StringReader(legacyManifest)); - - //Parse the package nodes - nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); - } - break; - case "skinobject": - //Legacy Skin Object - var skinControlwriter = new SkinControlPackageWriter(rootNav, info); - legacyManifest = skinControlwriter.WriteManifest(false); - legacyDoc = new XPathDocument(new StringReader(legacyManifest)); - - //Parse the package nodes - nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); - break; - } - - return nav; - } - private void BackupStreamIntoFile(Stream stream, PackageInfo package) { try @@ -418,6 +496,7 @@ private void BackupStreamIntoFile(Stream stream, PackageInfo package) { stream.Seek(0, SeekOrigin.Begin); } + stream.CopyTo(fileStream); } } @@ -425,95 +504,7 @@ private void BackupStreamIntoFile(Stream stream, PackageInfo package) { Logger.Error(ex); } - } - - #endregion - - #region Public Methods - - public void DeleteTempFolder() - { - try - { - if (!string.IsNullOrEmpty(TempInstallFolder)) - { - Directory.Delete(TempInstallFolder, true); - } - } - catch (Exception ex) - { - Logger.Error("Exception deleting folder "+TempInstallFolder+" while installing "+InstallerInfo.ManifestFile.Name, ex); - Exceptions.Exceptions.LogException(ex); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The Install method installs the feature. - /// - /// ----------------------------------------------------------------------------- - public bool Install() - { - InstallerInfo.Log.StartJob(Util.INSTALL_Start); - bool bStatus = true; - try - { - bool clearClientCache = false; - InstallPackages(ref clearClientCache); - if (clearClientCache) - { - //Update the version of the client resources - so the cache is cleared - HostController.Instance.IncrementCrmVersion(true); - } - } - catch (Exception ex) - { - - InstallerInfo.Log.AddFailure(ex); - bStatus = false; - } - finally - { - //Delete Temp Folder - if (!string.IsNullOrEmpty(TempInstallFolder)) - { - Globals.DeleteFolderRecursive(TempInstallFolder); - } - InstallerInfo.Log.AddInfo(Util.FOLDER_DeletedBackup); - } - if (InstallerInfo.Log.Valid) - { - InstallerInfo.Log.EndJob(Util.INSTALL_Success); - } - else - { - InstallerInfo.Log.EndJob(Util.INSTALL_Failed); - bStatus = false; - } - - //log installation event - LogInstallEvent("Package", "Install"); - - //when the installer initialized by file stream, we need save the file stream into backup folder. - if (_inputStream != null && bStatus && Packages.Any()) - { - Task.Run(() => - { - BackupStreamIntoFile(_inputStream, Packages[0].Package); - }); - } - - //Clear Host Cache - DataCache.ClearHostCache(true); - - if (Config.GetFcnMode() == Config.FcnMode.Disabled.ToString()) - { - // force application restart after the new changes only when FCN is disabled - Config.Touch(); - } - - return bStatus; - } + } /// ----------------------------------------------------------------------------- /// @@ -522,55 +513,56 @@ public bool Install() /// ----------------------------------------------------------------------------- public void ReadManifest(bool deleteTemp) { - InstallerInfo.Log.StartJob(Util.DNN_Reading); - if (InstallerInfo.ManifestFile != null) + this.InstallerInfo.Log.StartJob(Util.DNN_Reading); + if (this.InstallerInfo.ManifestFile != null) { - ReadManifest(new FileStream(InstallerInfo.ManifestFile.TempFileName, FileMode.Open, FileAccess.Read)); + this.ReadManifest(new FileStream(this.InstallerInfo.ManifestFile.TempFileName, FileMode.Open, FileAccess.Read)); } - if (InstallerInfo.Log.Valid) + + if (this.InstallerInfo.Log.Valid) { - InstallerInfo.Log.EndJob(Util.DNN_Success); + this.InstallerInfo.Log.EndJob(Util.DNN_Success); } else if (deleteTemp) { - //Delete Temp Folder - DeleteTempFolder(); + // Delete Temp Folder + this.DeleteTempFolder(); } } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the feature + /// The UnInstall method uninstalls the feature. /// /// A flag that indicates whether the files should be - /// deleted + /// deleted. + /// /// ----------------------------------------------------------------------------- public bool UnInstall(bool deleteFiles) { - InstallerInfo.Log.StartJob(Util.UNINSTALL_Start); + this.InstallerInfo.Log.StartJob(Util.UNINSTALL_Start); try { - UnInstallPackages(deleteFiles); + this.UnInstallPackages(deleteFiles); } catch (Exception ex) { - - InstallerInfo.Log.AddFailure(ex); + this.InstallerInfo.Log.AddFailure(ex); return false; } - if (InstallerInfo.Log.HasWarnings) + + if (this.InstallerInfo.Log.HasWarnings) { - InstallerInfo.Log.EndJob(Util.UNINSTALL_Warnings); + this.InstallerInfo.Log.EndJob(Util.UNINSTALL_Warnings); } else { - InstallerInfo.Log.EndJob(Util.UNINSTALL_Success); + this.InstallerInfo.Log.EndJob(Util.UNINSTALL_Success); } - //log installation event - LogInstallEvent("Package", "UnInstall"); + + // log installation event + this.LogInstallEvent("Package", "UnInstall"); return true; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/InstallerInfo.cs b/DNN Platform/Library/Services/Installer/InstallerInfo.cs index b23eca5f74b..b4b27d97bbc 100644 --- a/DNN Platform/Library/Services/Installer/InstallerInfo.cs +++ b/DNN Platform/Library/Services/Installer/InstallerInfo.cs @@ -1,26 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; - -using ICSharpCode.SharpZipLib.Zip; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + using ICSharpCode.SharpZipLib.Zip; + /// ----------------------------------------------------------------------------- /// /// The InstallerInfo class holds all the information associated with a @@ -31,295 +25,288 @@ namespace DotNetNuke.Services.Installer /// ----------------------------------------------------------------------------- [Serializable] public class InstallerInfo - { - #region Private Members - - #endregion - - #region Constructors - + { /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallerInfo instance + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallerInfo instance. /// /// ----------------------------------------------------------------------------- public InstallerInfo() { - PhysicalSitePath = Null.NullString; - Initialize(); - } - - /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallerInfo instance from a - /// string representing the physical path to the root of the site + this.PhysicalSitePath = Null.NullString; + this.Initialize(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallerInfo instance from a + /// string representing the physical path to the root of the site. /// - /// The physical path to the root of the site + /// The physical path to the root of the site. /// Install Mode. /// ----------------------------------------------------------------------------- public InstallerInfo(string sitePath, InstallMode mode) { - Initialize(); - TempInstallFolder = Globals.InstallMapPath + "Temp\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); - PhysicalSitePath = sitePath; - InstallMode = mode; - } - - /// ----------------------------------------------------------------------------- - /// + this.Initialize(); + this.TempInstallFolder = Globals.InstallMapPath + "Temp\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); + this.PhysicalSitePath = sitePath; + this.InstallMode = mode; + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. /// This Constructor creates a new InstallerInfo instance from a Stream and a - /// string representing the physical path to the root of the site + /// string representing the physical path to the root of the site. /// - /// The Stream to use to create this InstallerInfo instance - /// The physical path to the root of the site + /// The Stream to use to create this InstallerInfo instance. + /// The physical path to the root of the site. /// ----------------------------------------------------------------------------- public InstallerInfo(Stream inputStream, string sitePath) { - Initialize(); - TempInstallFolder = Globals.InstallMapPath + "Temp\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); - PhysicalSitePath = sitePath; - - //Read the Zip file into its component entries - ReadZipStream(inputStream, false); - } + this.Initialize(); + this.TempInstallFolder = Globals.InstallMapPath + "Temp\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); + this.PhysicalSitePath = sitePath; + // Read the Zip file into its component entries + this.ReadZipStream(inputStream, false); + } + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// This Constructor creates a new InstallerInfo instance from a string representing - /// the physical path to the temporary install folder and a string representing - /// the physical path to the root of the site + /// the physical path to the temporary install folder and a string representing + /// the physical path to the root of the site. /// - /// The physical path to the zip file containg the package - /// The manifest filename - /// The physical path to the root of the site + /// The physical path to the zip file containg the package. + /// The manifest filename. + /// The physical path to the root of the site. /// ----------------------------------------------------------------------------- public InstallerInfo(string tempFolder, string manifest, string sitePath) { - Initialize(); - TempInstallFolder = tempFolder; - PhysicalSitePath = sitePath; + this.Initialize(); + this.TempInstallFolder = tempFolder; + this.PhysicalSitePath = sitePath; if (!string.IsNullOrEmpty(manifest)) { - ManifestFile = new InstallFile(manifest, this); + this.ManifestFile = new InstallFile(manifest, this); } - } - + } + /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new InstallerInfo instance from a PackageInfo object + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallerInfo instance from a PackageInfo object. /// - /// The PackageInfo instance - /// The physical path to the root of the site + /// The PackageInfo instance. + /// The physical path to the root of the site. /// ----------------------------------------------------------------------------- public InstallerInfo(PackageInfo package, string sitePath) { - Initialize(); - PhysicalSitePath = sitePath; - TempInstallFolder = Globals.InstallMapPath + "Temp\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); - InstallMode = InstallMode.UnInstall; - ManifestFile = new InstallFile(Path.Combine(TempInstallFolder, package.Name + ".dnn")); + this.Initialize(); + this.PhysicalSitePath = sitePath; + this.TempInstallFolder = Globals.InstallMapPath + "Temp\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); + this.InstallMode = InstallMode.UnInstall; + this.ManifestFile = new InstallFile(Path.Combine(this.TempInstallFolder, package.Name + ".dnn")); package.AttachInstallerInfo(this); - } - - #endregion - - #region Public Properties - + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets a list of allowable file extensions (in addition to the Host's List) + /// Gets or sets and sets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string AllowableFiles { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Files that are included in the Package + /// Gets a Dictionary of Files that are included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- public Dictionary Files { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the package contains Valid Files + /// Gets a value indicating whether gets whether the package contains Valid Files. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool HasValidFiles { get { bool _HasValidFiles = true; - if (Files.Values.Any(file => !Util.IsFileValid(file, AllowableFiles))) + if (this.Files.Values.Any(file => !Util.IsFileValid(file, this.AllowableFiles))) { _HasValidFiles = Null.NullBoolean; } + return _HasValidFiles; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the File Extension WhiteList is ignored + /// Gets or sets a value indicating whether gets and sets whether the File Extension WhiteList is ignored. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- public bool IgnoreWhiteList { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the Package is already installed with the same version + /// Gets or sets a value indicating whether gets whether the Package is already installed with the same version. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- public bool Installed { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the InstallMode + /// Gets the InstallMode. /// - /// A InstallMode value + /// A InstallMode value. /// ----------------------------------------------------------------------------- public InstallMode InstallMode { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Invalid File Extensions + /// Gets the Invalid File Extensions. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string InvalidFileExtensions { get { - string _InvalidFileExtensions = Files.Values.Where(file => !Util.IsFileValid(file, AllowableFiles)) + string _InvalidFileExtensions = this.Files.Values.Where(file => !Util.IsFileValid(file, this.AllowableFiles)) .Aggregate(Null.NullString, (current, file) => current + (", " + file.Extension)); if (!string.IsNullOrEmpty(_InvalidFileExtensions)) { _InvalidFileExtensions = _InvalidFileExtensions.Substring(2); } + return _InvalidFileExtensions; } } /// ----------------------------------------------------------------------------- /// - /// Gets whether the Installer is in legacy mode + /// Gets or sets a value indicating whether gets whether the Installer is in legacy mode. /// /// ----------------------------------------------------------------------------- public bool IsLegacyMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the InstallerInfo instance is Valid + /// Gets a value indicating whether gets whether the InstallerInfo instance is Valid. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- public bool IsValid { get { - return Log.Valid; + return this.Log.Valid; } } /// ----------------------------------------------------------------------------- /// - /// Gets the associated Logger + /// Gets or sets the associated Logger. /// - /// A Logger + /// A Logger. /// ----------------------------------------------------------------------------- public string LegacyError { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the associated Logger + /// Gets the associated Logger. /// - /// A Logger + /// A Logger. /// ----------------------------------------------------------------------------- public Logger Log { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Manifest File for the Package + /// Gets and Sets the Manifest File for the Package. /// - /// An InstallFile + /// An InstallFile. /// ----------------------------------------------------------------------------- public InstallFile ManifestFile { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Id of the package after installation (-1 if fail) + /// Gets or sets the Id of the package after installation (-1 if fail). /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int PackageID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Physical Path to the root of the Site (eg D:\Websites\DotNetNuke") + /// Gets the Physical Path to the root of the Site (eg D:\Websites\DotNetNuke"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string PhysicalSitePath { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Id of the current portal (-1 if Host) + /// Gets or sets the Id of the current portal (-1 if Host). /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int PortalID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Package Install is being repaird + /// Gets or sets a value indicating whether gets and sets whether the Package Install is being repaird. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- public bool RepairInstall { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the security Access Level of the user that is calling the INstaller + /// Gets or sets and sets the security Access Level of the user that is calling the INstaller. /// - /// A SecurityAccessLevel enumeration + /// A SecurityAccessLevel enumeration. /// ----------------------------------------------------------------------------- public SecurityAccessLevel SecurityAccessLevel { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Temporary Install Folder used to unzip the archive (and to place the - /// backups of existing files) during InstallMode + /// Gets the Temporary Install Folder used to unzip the archive (and to place the + /// backups of existing files) during InstallMode. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - public string TempInstallFolder { get; private set; } - - #endregion - - #region Private Methods - + public string TempInstallFolder { get; private set; } + private void Initialize() { - TempInstallFolder = Null.NullString; - SecurityAccessLevel = SecurityAccessLevel.Host; - RepairInstall = Null.NullBoolean; - PortalID = Null.NullInteger; - PackageID = Null.NullInteger; - Log = new Logger(); - IsLegacyMode = Null.NullBoolean; - IgnoreWhiteList = Null.NullBoolean; - InstallMode = InstallMode.Install; - Installed = Null.NullBoolean; - Files = new Dictionary(); + this.TempInstallFolder = Null.NullString; + this.SecurityAccessLevel = SecurityAccessLevel.Host; + this.RepairInstall = Null.NullBoolean; + this.PortalID = Null.NullInteger; + this.PackageID = Null.NullInteger; + this.Log = new Logger(); + this.IsLegacyMode = Null.NullBoolean; + this.IgnoreWhiteList = Null.NullBoolean; + this.InstallMode = InstallMode.Install; + this.Installed = Null.NullBoolean; + this.Files = new Dictionary(); } private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) { - Log.StartJob(Util.FILES_Reading); + this.Log.StartJob(Util.FILES_Reading); if (inputStream.CanSeek) { inputStream.Seek(0, SeekOrigin.Begin); @@ -332,82 +319,84 @@ private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) entry.CheckZipEntry(); if (!entry.IsDirectory) { - //Add file to list + // Add file to list var file = new InstallFile(unzip, entry, this); if (file.Type == InstallFileType.Resources && (file.Name.Equals("containers.zip", StringComparison.InvariantCultureIgnoreCase) || file.Name.Equals("skins.zip", StringComparison.InvariantCultureIgnoreCase))) { - //Temporarily save the TempInstallFolder - string tmpInstallFolder = TempInstallFolder; + // Temporarily save the TempInstallFolder + string tmpInstallFolder = this.TempInstallFolder; - //Create Zip Stream from File + // Create Zip Stream from File using (var zipStream = new FileStream(file.TempFileName, FileMode.Open, FileAccess.Read)) { - //Set TempInstallFolder - TempInstallFolder = Path.Combine(TempInstallFolder, Path.GetFileNameWithoutExtension(file.Name)); + // Set TempInstallFolder + this.TempInstallFolder = Path.Combine(this.TempInstallFolder, Path.GetFileNameWithoutExtension(file.Name)); - //Extract files from zip - ReadZipStream(zipStream, true); + // Extract files from zip + this.ReadZipStream(zipStream, true); } - //Restore TempInstallFolder - TempInstallFolder = tmpInstallFolder; + // Restore TempInstallFolder + this.TempInstallFolder = tmpInstallFolder; - //Delete zip file + // Delete zip file var zipFile = new FileInfo(file.TempFileName); zipFile.Delete(); } else { - Files[file.FullName.ToLowerInvariant()] = file; + this.Files[file.FullName.ToLowerInvariant()] = file; if (file.Type == InstallFileType.Manifest && !isEmbeddedZip) { - if (ManifestFile == null) + if (this.ManifestFile == null) { - ManifestFile = file; + this.ManifestFile = file; } else { - if (file.Extension == "dnn7" && (ManifestFile.Extension == "dnn" || ManifestFile.Extension == "dnn5" || ManifestFile.Extension == "dnn6")) + if (file.Extension == "dnn7" && (this.ManifestFile.Extension == "dnn" || this.ManifestFile.Extension == "dnn5" || this.ManifestFile.Extension == "dnn6")) { - ManifestFile = file; + this.ManifestFile = file; } - else if (file.Extension == "dnn6" && (ManifestFile.Extension == "dnn" || ManifestFile.Extension == "dnn5")) - { - ManifestFile = file; + else if (file.Extension == "dnn6" && (this.ManifestFile.Extension == "dnn" || this.ManifestFile.Extension == "dnn5")) + { + this.ManifestFile = file; } - else if (file.Extension == "dnn5" && ManifestFile.Extension == "dnn") + else if (file.Extension == "dnn5" && this.ManifestFile.Extension == "dnn") { - ManifestFile = file; + this.ManifestFile = file; } - else if (file.Extension == ManifestFile.Extension) + else if (file.Extension == this.ManifestFile.Extension) { - Log.AddFailure((Util.EXCEPTION_MultipleDnn + ManifestFile.Name + " and " + file.Name)); + this.Log.AddFailure(Util.EXCEPTION_MultipleDnn + this.ManifestFile.Name + " and " + file.Name); } } } } - Log.AddInfo(string.Format(Util.FILE_ReadSuccess, file.FullName)); + + this.Log.AddInfo(string.Format(Util.FILE_ReadSuccess, file.FullName)); } + entry = unzip.GetNextEntry(); } - if (ManifestFile == null) + + if (this.ManifestFile == null) { - Log.AddFailure(Util.EXCEPTION_MissingDnn); + this.Log.AddFailure(Util.EXCEPTION_MissingDnn); } - if (Log.Valid) + + if (this.Log.Valid) { - Log.EndJob(Util.FILES_ReadingEnd); + this.Log.EndJob(Util.FILES_ReadingEnd); } else { - Log.AddFailure(new Exception(Util.EXCEPTION_FileLoad)); - Log.EndJob(Util.FILES_ReadingEnd); + this.Log.AddFailure(new Exception(Util.EXCEPTION_FileLoad)); + this.Log.EndJob(Util.FILES_ReadingEnd); } - - //Close the Zip Input Stream as we have finished with it + + // Close the Zip Input Stream as we have finished with it inputStream.Close(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs index 0e3e1deda70..bb0c97b0368 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs @@ -1,27 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Reflection; -using System.Security; -using System.Text.RegularExpressions; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Data; -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.IO; + using System.Reflection; + using System.Security; + using System.Text.RegularExpressions; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Data; + using DotNetNuke.Framework; + /// ----------------------------------------------------------------------------- /// - /// The AssemblyInstaller installs Assembly Components to a DotNetNuke site + /// The AssemblyInstaller installs Assembly Components to a DotNetNuke site. /// /// /// @@ -31,169 +26,198 @@ public class AssemblyInstaller : FileInstaller private static readonly string OldVersion = "0.0.0.0-" + new Version(short.MaxValue, short.MaxValue, short.MaxValue, short.MaxValue); - #region "Protected Properties" - /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("assemblies") + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String - protected override string CollectionNodeName + /// A String. + public override string AllowableFiles { get { - return "assemblies"; + return "dll,pdb"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the default Path for the file - if not present in the manifest + /// Gets the name of the Collection Node ("assemblies"). /// - /// A String - protected override string DefaultPath + /// A String. + protected override string CollectionNodeName { get { - return "bin\\"; + return "assemblies"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("assembly") + /// Gets the default Path for the file - if not present in the manifest. /// - /// A String - protected override string ItemNodeName + /// A String. + protected override string DefaultPath { get { - return "assembly"; + return "bin\\"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the PhysicalBasePath for the assemblies + /// Gets the name of the Item Node ("assembly"). /// - /// A String - protected override string PhysicalBasePath + /// A String. + protected override string ItemNodeName { get { - return PhysicalSitePath + "\\"; + return "assembly"; } } - - #endregion - - #region "Public Properties" /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets the PhysicalBasePath for the assemblies. /// - /// A String - public override string AllowableFiles + /// A String. + protected override string PhysicalBasePath { get { - return "dll,pdb"; + return this.PhysicalSitePath + "\\"; } } - - - #endregion - - #region "Protected Methods" /// ----------------------------------------------------------------------------- /// /// The DeleteFile method deletes a single assembly. /// - /// The InstallFile to delete + /// The InstallFile to delete. protected override void DeleteFile(InstallFile file) { - //Attempt to unregister assembly this will return False if the assembly is used by another package and - //cannot be delete andtrue if it is not being used and can be deleted - if (DataProvider.Instance().UnRegisterAssembly(Package.PackageID, file.Name)) + // Attempt to unregister assembly this will return False if the assembly is used by another package and + // cannot be delete andtrue if it is not being used and can be deleted + if (DataProvider.Instance().UnRegisterAssembly(this.Package.PackageID, file.Name)) { - Log.AddInfo(Util.ASSEMBLY_UnRegistered + " - " + file.FullName); - - RemoveBindingRedirect(file); - - //Call base class version to deleteFile file from \bin + this.Log.AddInfo(Util.ASSEMBLY_UnRegistered + " - " + file.FullName); + + this.RemoveBindingRedirect(file); + + // Call base class version to deleteFile file from \bin base.DeleteFile(file); } else { - Log.AddInfo(Util.ASSEMBLY_InUse + " - " + file.FullName); + this.Log.AddInfo(Util.ASSEMBLY_InUse + " - " + file.FullName); } } /// ----------------------------------------------------------------------------- /// - /// Gets a flag that determines what type of file this installer supports + /// Gets a flag that determines what type of file this installer supports. /// - /// The type of file being processed + /// The type of file being processed. + /// protected override bool IsCorrectType(InstallFileType type) { - return (type == InstallFileType.Assembly); + return type == InstallFileType.Assembly; } /// ----------------------------------------------------------------------------- /// /// The InstallFile method installs a single assembly. /// - /// The InstallFile to install + /// The InstallFile to install. + /// protected override bool InstallFile(InstallFile file) { bool bSuccess = true; if (file.Action == "UnRegister") { - DeleteFile(file); + this.DeleteFile(file); } else { - //Attempt to register assembly this will return False if the assembly exists and true if it does not or is older - int returnCode = DataProvider.Instance().RegisterAssembly(Package.PackageID, file.Name, file.Version.ToString(3)); + // Attempt to register assembly this will return False if the assembly exists and true if it does not or is older + int returnCode = DataProvider.Instance().RegisterAssembly(this.Package.PackageID, file.Name, file.Version.ToString(3)); switch (returnCode) { case 0: - //Assembly Does Not Exist - Log.AddInfo(Util.ASSEMBLY_Added + " - " + file.FullName); + // Assembly Does Not Exist + this.Log.AddInfo(Util.ASSEMBLY_Added + " - " + file.FullName); break; case 1: - //Older version of Assembly Exists - Log.AddInfo(Util.ASSEMBLY_Updated + " - " + file.FullName); + // Older version of Assembly Exists + this.Log.AddInfo(Util.ASSEMBLY_Updated + " - " + file.FullName); break; case 2: case 3: - //Assembly already Registered - Log.AddInfo(Util.ASSEMBLY_Registered + " - " + file.FullName); + // Assembly already Registered + this.Log.AddInfo(Util.ASSEMBLY_Registered + " - " + file.FullName); break; } - - //If assembly not registered, is newer (or is the same version and we are in repair mode) + + // If assembly not registered, is newer (or is the same version and we are in repair mode) if (returnCode < 2 || (returnCode == 2 && file.InstallerInfo.RepairInstall)) { - //Call base class version to copy file to \bin + // Call base class version to copy file to \bin bSuccess = base.InstallFile(file); - AddOrUpdateBindingRedirect(file); + this.AddOrUpdateBindingRedirect(file); } } + return bSuccess; } - - #endregion - #region "Private Methods" + /// Reads the file's . + /// The path for the assembly whose is to be returned. + /// An or null. + private static AssemblyName ReadAssemblyName(string assemblyFile) + { + try + { + return AssemblyName.GetAssemblyName(assemblyFile); + } + catch (BadImageFormatException) + { + // assemblyFile is not a valid assembly. + return null; + } + catch (ArgumentException) + { + // assemblyFile is invalid, such as an assembly with an invalid culture. + return null; + } + catch (SecurityException) + { + // The caller does not have path discovery permission. + return null; + } + catch (FileLoadException) + { + // An assembly or module was loaded twice with two different sets of evidence. + return null; + } + } + + private static string ReadPublicKey(AssemblyName assemblyName) + { + if (assemblyName == null || !assemblyName.Flags.HasFlag(AssemblyNameFlags.PublicKey)) + { + return null; + } + + return PublicKeyTokenRegex.Match(assemblyName.FullName).Groups[1].Value; + } /// Adds or updates the binding redirect for the assembly file, if the assembly file it strong-named. /// The assembly file. private void AddOrUpdateBindingRedirect(InstallFile file) { - if (ApplyXmlMerge(file, "BindingRedirect.config")) + if (this.ApplyXmlMerge(file, "BindingRedirect.config")) { this.Log.AddInfo(Util.ASSEMBLY_AddedBindingRedirect + " - " + file.FullName); } @@ -203,9 +227,9 @@ private void AddOrUpdateBindingRedirect(InstallFile file) /// The assembly file. private void RemoveBindingRedirect(InstallFile file) { - if (ApplyXmlMerge(file, "RemoveBindingRedirect.config")) + if (this.ApplyXmlMerge(file, "RemoveBindingRedirect.config")) { - Log.AddInfo(Util.ASSEMBLY_RemovedBindingRedirect + " - " + file.FullName); + this.Log.AddInfo(Util.ASSEMBLY_RemovedBindingRedirect + " - " + file.FullName); } } @@ -230,49 +254,8 @@ private bool ApplyXmlMerge(InstallFile file, string xmlMergeFile) var xmlMergeDoc = GetXmlMergeDoc(xmlMergePath, name, publicKeyToken, OldVersion, newVersion); var xmlMerge = new XmlMerge(xmlMergeDoc, file.Version.ToString(), this.Package.Name); xmlMerge.UpdateConfigs(); - - return true; - } - /// Reads the file's . - /// The path for the assembly whose is to be returned. - /// An or null - private static AssemblyName ReadAssemblyName(string assemblyFile) - { - try - { - return AssemblyName.GetAssemblyName(assemblyFile); - } - catch (BadImageFormatException) - { - // assemblyFile is not a valid assembly. - return null; - } - catch (ArgumentException) - { - // assemblyFile is invalid, such as an assembly with an invalid culture. - return null; - } - catch (SecurityException) - { - // The caller does not have path discovery permission. - return null; - } - catch (FileLoadException) - { - // An assembly or module was loaded twice with two different sets of evidence. - return null; - } - } - - private static string ReadPublicKey(AssemblyName assemblyName) - { - if (assemblyName == null || !assemblyName.Flags.HasFlag(AssemblyNameFlags.PublicKey)) - { - return null; - } - - return PublicKeyTokenRegex.Match(assemblyName.FullName).Groups[1].Value; + return true; } /// Gets the XML merge document to create the binding redirect. @@ -325,7 +308,5 @@ private static void ReplaceInAttributeValue(XmlNode parentNode, XmlNamespaceMana var attribute = parentNode.SelectSingleNode(xpath, namespaceManager); attribute.Value = attribute.Value.Replace(oldValue, newValue); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs index 9ca7952c765..708c70f2c72 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs @@ -1,42 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Authentication; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Authentication; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationInstaller installs Authentication Service Components to a DotNetNuke site + /// The AuthenticationInstaller installs Authentication Service Components to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class AuthenticationInstaller : ComponentInstallerBase - { - #region "Private Properties" - + { private AuthenticationInfo AuthSystem; - private AuthenticationInfo TempAuthSystem; - - #endregion - - #region "Public Properties" - + private AuthenticationInfo TempAuthSystem; + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public override string AllowableFiles { @@ -44,46 +33,13 @@ public override string AllowableFiles { return "ashx, aspx, ascx, vb, cs, resx, css, js, resources, config, vbproj, csproj, sln, htm, html"; } - } - - #endregion - - #region "Private Methods" - - - /// ----------------------------------------------------------------------------- - /// - /// The DeleteAuthentiation method deletes the Authentication System - /// from the data Store. - /// - /// ----------------------------------------------------------------------------- - private void DeleteAuthentiation() - { - try - { - AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(Package.PackageID); - if (authSystem != null) - { - AuthenticationController.DeleteAuthentication(authSystem); - } - Log.AddInfo(string.Format(Util.AUTHENTICATION_UnRegistered, authSystem.AuthenticationType)); - } - catch (Exception ex) - { - Log.AddFailure(ex); - } - } - - #endregion - - #region "Public Methods" - - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. /// - /// In the case of Authentication systems this is not neccessary + /// In the case of Authentication systems this is not neccessary. /// ----------------------------------------------------------------------------- public override void Commit() { @@ -91,7 +47,7 @@ public override void Commit() /// ----------------------------------------------------------------------------- /// - /// The Install method installs the authentication component + /// The Install method installs the authentication component. /// /// ----------------------------------------------------------------------------- public override void Install() @@ -99,40 +55,65 @@ public override void Install() bool bAdd = Null.NullBoolean; try { - //Attempt to get the Authentication Service - TempAuthSystem = AuthenticationController.GetAuthenticationServiceByType(AuthSystem.AuthenticationType); + // Attempt to get the Authentication Service + this.TempAuthSystem = AuthenticationController.GetAuthenticationServiceByType(this.AuthSystem.AuthenticationType); - if (TempAuthSystem == null) + if (this.TempAuthSystem == null) { - //Enable by default - AuthSystem.IsEnabled = true; + // Enable by default + this.AuthSystem.IsEnabled = true; bAdd = true; } else { - AuthSystem.AuthenticationID = TempAuthSystem.AuthenticationID; - AuthSystem.IsEnabled = TempAuthSystem.IsEnabled; + this.AuthSystem.AuthenticationID = this.TempAuthSystem.AuthenticationID; + this.AuthSystem.IsEnabled = this.TempAuthSystem.IsEnabled; } - AuthSystem.PackageID = Package.PackageID; + + this.AuthSystem.PackageID = this.Package.PackageID; if (bAdd) { - //Add new service - AuthenticationController.AddAuthentication(AuthSystem); + // Add new service + AuthenticationController.AddAuthentication(this.AuthSystem); } else { - //Update service - AuthenticationController.UpdateAuthentication(AuthSystem); + // Update service + AuthenticationController.UpdateAuthentication(this.AuthSystem); } - Completed = true; - Log.AddInfo(string.Format(Util.AUTHENTICATION_Registered, AuthSystem.AuthenticationType)); + + this.Completed = true; + this.Log.AddInfo(string.Format(Util.AUTHENTICATION_Registered, this.AuthSystem.AuthenticationType)); } catch (Exception ex) { - - Log.AddFailure(ex); + this.Log.AddFailure(ex); } } + + /// ----------------------------------------------------------------------------- + /// + /// The DeleteAuthentiation method deletes the Authentication System + /// from the data Store. + /// + /// ----------------------------------------------------------------------------- + private void DeleteAuthentiation() + { + try + { + AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(this.Package.PackageID); + if (authSystem != null) + { + AuthenticationController.DeleteAuthentication(authSystem); + } + + this.Log.AddInfo(string.Format(Util.AUTHENTICATION_UnRegistered, authSystem.AuthenticationType)); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } /// ----------------------------------------------------------------------------- /// @@ -141,57 +122,55 @@ public override void Install() /// ----------------------------------------------------------------------------- public override void ReadManifest(XPathNavigator manifestNav) { - AuthSystem = new AuthenticationInfo(); + this.AuthSystem = new AuthenticationInfo(); - //Get the type - AuthSystem.AuthenticationType = Util.ReadElement(manifestNav, "authenticationService/type", Log, Util.AUTHENTICATION_TypeMissing); + // Get the type + this.AuthSystem.AuthenticationType = Util.ReadElement(manifestNav, "authenticationService/type", this.Log, Util.AUTHENTICATION_TypeMissing); - //Get the SettingsSrc - AuthSystem.SettingsControlSrc = Util.ReadElement(manifestNav, "authenticationService/settingsControlSrc", Log, Util.AUTHENTICATION_SettingsSrcMissing); + // Get the SettingsSrc + this.AuthSystem.SettingsControlSrc = Util.ReadElement(manifestNav, "authenticationService/settingsControlSrc", this.Log, Util.AUTHENTICATION_SettingsSrcMissing); - //Get the LoginSrc - AuthSystem.LoginControlSrc = Util.ReadElement(manifestNav, "authenticationService/loginControlSrc", Log, Util.AUTHENTICATION_LoginSrcMissing); + // Get the LoginSrc + this.AuthSystem.LoginControlSrc = Util.ReadElement(manifestNav, "authenticationService/loginControlSrc", this.Log, Util.AUTHENTICATION_LoginSrcMissing); - //Get the LogoffSrc - AuthSystem.LogoffControlSrc = Util.ReadElement(manifestNav, "authenticationService/logoffControlSrc"); + // Get the LogoffSrc + this.AuthSystem.LogoffControlSrc = Util.ReadElement(manifestNav, "authenticationService/logoffControlSrc"); - if (Log.Valid) + if (this.Log.Valid) { - Log.AddInfo(Util.AUTHENTICATION_ReadSuccess); + this.Log.AddInfo(Util.AUTHENTICATION_ReadSuccess); } } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() { - //If Temp Auth System exists then we need to update the DataStore with this - if (TempAuthSystem == null) + // If Temp Auth System exists then we need to update the DataStore with this + if (this.TempAuthSystem == null) { - //No Temp Auth System - Delete newly added system - DeleteAuthentiation(); + // No Temp Auth System - Delete newly added system + this.DeleteAuthentiation(); } else { - //Temp Auth System - Rollback to Temp - AuthenticationController.UpdateAuthentication(TempAuthSystem); + // Temp Auth System - Rollback to Temp + AuthenticationController.UpdateAuthentication(this.TempAuthSystem); } } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the authentication component + /// The UnInstall method uninstalls the authentication component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - DeleteAuthentiation(); - } - - #endregion + this.DeleteAuthentiation(); + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs index 49302b9975a..43ee5431468 100644 --- a/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs @@ -1,122 +1,109 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Xml.XPath; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using Microsoft.Extensions.FileSystemGlobbing; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using Microsoft.Extensions.FileSystemGlobbing; + /// ----------------------------------------------------------------------------- /// - /// The CleanupInstaller cleans up (removes) files from previous versions + /// The CleanupInstaller cleans up (removes) files from previous versions. /// /// /// /// ----------------------------------------------------------------------------- public class CleanupInstaller : FileInstaller { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (CleanupInstaller)); - #region "Private Members" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CleanupInstaller)); private string _fileName; - private string _glob; - - #endregion - - #region "Public Properties" - + private string _glob; + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - public override string AllowableFiles => "*"; - - #endregion - - #region "Private Methods" - - private bool ProcessCleanupFile() + public override string AllowableFiles => "*"; + + /// ----------------------------------------------------------------------------- + /// + /// The Commit method finalises the Install and commits any pending changes. + /// + /// In the case of Clenup this is not neccessary. + /// ----------------------------------------------------------------------------- + public override void Commit() { - Log.AddInfo(string.Format(Util.CLEANUP_Processing, Version.ToString(3))); - try - { - var strListFile = Path.Combine(Package.InstallerInfo.TempInstallFolder, _fileName); - if (File.Exists(strListFile)) - { - FileSystemUtils.DeleteFiles(File.ReadAllLines(strListFile)); - } - } - catch (Exception ex) - { - Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); - //DNN-9202: MUST NOT fail installation when cleanup files deletion fails - //return false; - } - Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, Version.ToString(3))); - return true; + // Do nothing + base.Commit(); } - private bool ProcessGlob() + /// ----------------------------------------------------------------------------- + /// + /// The Install method cleansup the files. + /// + /// ----------------------------------------------------------------------------- + public override void Install() { - Log.AddInfo(string.Format(Util.CLEANUP_Processing, Version.ToString(3))); try { - if (_glob.Contains("..")) + bool bSuccess = true; + if (string.IsNullOrEmpty(this._fileName) && string.IsNullOrEmpty(this._glob)) // No attribute: use the xml files definition. { - Log.AddWarning(Util.EXCEPTION + " - " + Util.EXCEPTION_GlobDotDotNotSupportedInCleanup); + foreach (InstallFile file in this.Files) + { + bSuccess = this.CleanupFile(file); + if (!bSuccess) + { + break; + } + } } - else + else if (!string.IsNullOrEmpty(this._fileName)) // Cleanup file provided: clean each file in the cleanup text file line one by one. { - var globs = new Matcher(StringComparison.InvariantCultureIgnoreCase); - globs.AddIncludePatterns(_glob.Split(';')); - var files = globs.GetResultsInFullPath(Globals.ApplicationMapPath).ToArray(); - FileSystemUtils.DeleteFiles(files); + bSuccess = this.ProcessCleanupFile(); } + else if (!string.IsNullOrEmpty(this._glob)) // A globbing pattern was provided, use it to find the files and delete what matches. + { + bSuccess = this.ProcessGlob(); + } + + this.Completed = bSuccess; } catch (Exception ex) { - Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } - Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, Version.ToString(3))); - return true; } - - #endregion - - #region "Protected Methods" - + /// ----------------------------------------------------------------------------- /// /// The CleanupFile method cleansup a single file. /// - /// The InstallFile to clean up + /// The InstallFile to clean up. + /// /// ----------------------------------------------------------------------------- protected bool CleanupFile(InstallFile insFile) { try { - //Backup File - if (File.Exists(PhysicalBasePath + insFile.FullName)) + // Backup File + if (File.Exists(this.PhysicalBasePath + insFile.FullName)) { - Util.BackupFile(insFile, PhysicalBasePath, Log); + Util.BackupFile(insFile, this.PhysicalBasePath, this.Log); } - - //Delete file - Util.DeleteFile(insFile, PhysicalBasePath, Log); + + // Delete file + Util.DeleteFile(insFile, this.PhysicalBasePath, this.Log); return true; } catch (Exception exc) @@ -129,109 +116,102 @@ protected bool CleanupFile(InstallFile insFile) /// ----------------------------------------------------------------------------- /// - /// The ProcessFile method determines what to do with parsed "file" node + /// The ProcessFile method determines what to do with parsed "file" node. /// - /// The file represented by the node - /// The XPathNavigator representing the node + /// The file represented by the node. + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected override void ProcessFile(InstallFile file, XPathNavigator nav) { if (file != null) { - Files.Add(file); + this.Files.Add(file); } } - - protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) - { - return base.ReadManifestItem(nav, false); - } - - /// ----------------------------------------------------------------------------- - /// - /// The RollbackFile method rolls back the cleanup of a single file. - /// - /// The InstallFile to commit - /// ----------------------------------------------------------------------------- - protected override void RollbackFile(InstallFile installFile) + + private bool ProcessCleanupFile() { - if (File.Exists(installFile.BackupFileName)) + this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); + try { - Util.RestoreFile(installFile, PhysicalBasePath, Log); + var strListFile = Path.Combine(this.Package.InstallerInfo.TempInstallFolder, this._fileName); + if (File.Exists(strListFile)) + { + FileSystemUtils.DeleteFiles(File.ReadAllLines(strListFile)); + } } - } - - #endregion - - #region "Public Methods" - - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Clenup this is not neccessary - /// ----------------------------------------------------------------------------- - public override void Commit() - { - //Do nothing - base.Commit(); + catch (Exception ex) + { + this.Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); + + // DNN-9202: MUST NOT fail installation when cleanup files deletion fails + // return false; + } + + this.Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); + return true; } - /// ----------------------------------------------------------------------------- - /// - /// The Install method cleansup the files - /// - /// ----------------------------------------------------------------------------- - public override void Install() + private bool ProcessGlob() { + this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); try { - bool bSuccess = true; - if (string.IsNullOrEmpty(_fileName) && string.IsNullOrEmpty(_glob)) // No attribute: use the xml files definition. + if (this._glob.Contains("..")) { - foreach (InstallFile file in Files) - { - bSuccess = CleanupFile(file); - if (!bSuccess) - { - break; - } - } + this.Log.AddWarning(Util.EXCEPTION + " - " + Util.EXCEPTION_GlobDotDotNotSupportedInCleanup); } - else if (!string.IsNullOrEmpty(_fileName)) // Cleanup file provided: clean each file in the cleanup text file line one by one. - { - bSuccess = ProcessCleanupFile(); - } - else if (!string.IsNullOrEmpty(_glob)) // A globbing pattern was provided, use it to find the files and delete what matches. + else { - bSuccess = ProcessGlob(); + var globs = new Matcher(StringComparison.InvariantCultureIgnoreCase); + globs.AddIncludePatterns(this._glob.Split(';')); + var files = globs.GetResultsInFullPath(Globals.ApplicationMapPath).ToArray(); + FileSystemUtils.DeleteFiles(files); } - Completed = bSuccess; } catch (Exception ex) { - Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); + this.Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); } + + this.Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); + return true; + } + + protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) + { + return base.ReadManifestItem(nav, false); } + /// ----------------------------------------------------------------------------- + /// + /// The RollbackFile method rolls back the cleanup of a single file. + /// + /// The InstallFile to commit. + /// ----------------------------------------------------------------------------- + protected override void RollbackFile(InstallFile installFile) + { + if (File.Exists(installFile.BackupFileName)) + { + Util.RestoreFile(installFile, this.PhysicalBasePath, this.Log); + } + } + public override void ReadManifest(XPathNavigator manifestNav) { - _fileName = Util.ReadAttribute(manifestNav, "fileName"); - _glob = Util.ReadAttribute(manifestNav, "glob"); + this._fileName = Util.ReadAttribute(manifestNav, "fileName"); + this._glob = Util.ReadAttribute(manifestNav, "glob"); base.ReadManifest(manifestNav); } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the file component + /// The UnInstall method uninstalls the file component. /// - /// There is no uninstall for this component + /// There is no uninstall for this component. /// ----------------------------------------------------------------------------- public override void UnInstall() { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs index e0250b75339..1ef0fe3746e 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs @@ -1,25 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Xml.XPath; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.EventQueue; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Collections.Generic; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.EventQueue; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The ComponentInstallerBase is a base class for all Component Installers + /// The ComponentInstallerBase is a base class for all Component Installers. /// /// /// @@ -28,14 +24,14 @@ public abstract class ComponentInstallerBase { protected ComponentInstallerBase() { - Completed = Null.NullBoolean; + this.Completed = Null.NullBoolean; } /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public virtual string AllowableFiles { @@ -47,76 +43,100 @@ public virtual string AllowableFiles /// ----------------------------------------------------------------------------- /// - /// Gets the Completed flag + /// Gets or sets a value indicating whether gets the Completed flag. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- public bool Completed { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the InstallMode + /// Gets the InstallMode. /// - /// An InstallMode value + /// An InstallMode value. /// ----------------------------------------------------------------------------- public InstallMode InstallMode { get { - return Package.InstallMode; + return this.Package.InstallMode; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Logger + /// Gets the Logger. /// - /// An Logger object + /// An Logger object. /// ----------------------------------------------------------------------------- public Logger Log { get { - return Package.Log; + return this.Package.Log; } } /// ----------------------------------------------------------------------------- /// - /// Gets the associated Package + /// Gets or sets the associated Package. /// - /// An PackageInfo object + /// An PackageInfo object. /// ----------------------------------------------------------------------------- public PackageInfo Package { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Files that are included in the Package + /// Gets a Dictionary of Files that are included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- public Dictionary PackageFiles { get { - return Package.Files; + return this.Package.Files; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Physical Path to the root of the Site (eg D:\Websites\DotNetNuke") + /// Gets the Physical Path to the root of the Site (eg D:\Websites\DotNetNuke"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string PhysicalSitePath { get { - return Package.InstallerInfo.PhysicalSitePath; + return this.Package.InstallerInfo.PhysicalSitePath; } } + public bool Skipped { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public virtual bool SupportsManifestOnlyInstall + { + get + { + return true; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Type of the component. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string Type { get; set; } + public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) { EventMessage eventMessage = null; @@ -124,40 +144,42 @@ public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) XPathNavigator eventMessageNav = manifestNav.SelectSingleNode("eventMessage"); if (eventMessageNav != null) { - eventMessage = new EventMessage - { - Priority = MessagePriority.High, - ExpirationDate = DateTime.Now.AddYears(-1), - SentDate = DateTime.Now, - Body = "", - ProcessorType = Util.ReadElement(eventMessageNav, "processorType", Log, Util.EVENTMESSAGE_TypeMissing), - ProcessorCommand = Util.ReadElement(eventMessageNav, "processorCommand", Log, Util.EVENTMESSAGE_CommandMissing) - }; + eventMessage = new EventMessage + { + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(-1), + SentDate = DateTime.Now, + Body = string.Empty, + ProcessorType = Util.ReadElement(eventMessageNav, "processorType", this.Log, Util.EVENTMESSAGE_TypeMissing), + ProcessorCommand = Util.ReadElement(eventMessageNav, "processorCommand", this.Log, Util.EVENTMESSAGE_CommandMissing), + }; foreach (XPathNavigator attributeNav in eventMessageNav.Select("attributes/*")) { var attribName = attributeNav.Name; var attribValue = attributeNav.Value; if (attribName == "upgradeVersionsList") { - if (!String.IsNullOrEmpty(attribValue)) + if (!string.IsNullOrEmpty(attribValue)) { string[] upgradeVersions = attribValue.Split(','); - attribValue = ""; + attribValue = string.Empty; foreach (string version in upgradeVersions) { switch (version.ToLowerInvariant()) { case "install": - if (Package.InstalledVersion == new Version(0, 0, 0)) + if (this.Package.InstalledVersion == new Version(0, 0, 0)) { attribValue += version + ","; } + break; case "upgrade": - if (Package.InstalledVersion > new Version(0, 0, 0)) + if (this.Package.InstalledVersion > new Version(0, 0, 0)) { attribValue += version + ","; } + break; default: Version upgradeVersion = null; @@ -167,59 +189,38 @@ public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) } catch (FormatException) { - Log.AddWarning(string.Format(Util.MODULE_InvalidVersion, version)); + this.Log.AddWarning(string.Format(Util.MODULE_InvalidVersion, version)); } - if (upgradeVersion != null && (Globals.Status == Globals.UpgradeStatus.Install)) //To allow when fresh installing or installresources + if (upgradeVersion != null && (Globals.Status == Globals.UpgradeStatus.Install)) // To allow when fresh installing or installresources { attribValue += version + ","; } - else if (upgradeVersion != null && upgradeVersion > Package.InstalledVersion) + else if (upgradeVersion != null && upgradeVersion > this.Package.InstalledVersion) { attribValue += version + ","; } + break; } - } + attribValue = attribValue.TrimEnd(','); } } + eventMessage.Attributes.Add(attribName, attribValue); } } + return eventMessage; } - public bool Skipped { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets whether the Installer supports Manifest only installs - /// - /// A Boolean - /// ----------------------------------------------------------------------------- - public virtual bool SupportsManifestOnlyInstall - { - get - { - return true; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Type of the component - /// - /// A String - /// ----------------------------------------------------------------------------- - public string Type { get; set; } - /// ----------------------------------------------------------------------------- /// - /// Gets the Version of the Component + /// Gets or sets the Version of the Component. /// - /// A System.Version + /// A System.Version. /// ----------------------------------------------------------------------------- public Version Version { get; set; } diff --git a/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs index 8bbc3081b86..12ab9759276 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs @@ -1,104 +1,88 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.IO; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// - /// The ConfigInstaller installs Config changes + /// The ConfigInstaller installs Config changes. /// /// /// /// ----------------------------------------------------------------------------- public class ConfigInstaller : ComponentInstallerBase - { - #region "Private Members" - + { private string _FileName = Null.NullString; private string _InstallConfig = Null.NullString; private XmlDocument _TargetConfig; private InstallFile _TargetFile; private string _UnInstallConfig = Null.NullString; private string _UninstallFileName = Null.NullString; - private XmlMerge _xmlMerge; - - #endregion - - #region "Protected Properties" - + private XmlMerge _xmlMerge; + /// ----------------------------------------------------------------------------- /// - /// Gets the Install config changes + /// Gets the Install config changes. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string InstallConfig { get { - return _InstallConfig; + return this._InstallConfig; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Target Config XmlDocument + /// Gets the Target Config XmlDocument. /// - /// An XmlDocument + /// An XmlDocument. /// ----------------------------------------------------------------------------- public XmlDocument TargetConfig { get { - return _TargetConfig; + return this._TargetConfig; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Target Config file to change + /// Gets the Target Config file to change. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public InstallFile TargetFile { get { - return _TargetFile; + return this._TargetFile; } } /// ----------------------------------------------------------------------------- /// - /// Gets the UnInstall config changes + /// Gets the UnInstall config changes. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string UnInstallConfig { get { - return _UnInstallConfig; + return this._UnInstallConfig; } - } - - #endregion - - #region "Public Methods" - - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -108,76 +92,76 @@ public override void Commit() { try { - if (string.IsNullOrEmpty(_FileName) && _xmlMerge.ConfigUpdateChangedNodes) + if (string.IsNullOrEmpty(this._FileName) && this._xmlMerge.ConfigUpdateChangedNodes) { - //Save the XmlDocument - Config.Save(TargetConfig, TargetFile.FullName); - Log.AddInfo(Util.CONFIG_Committed + " - " + TargetFile.Name); + // Save the XmlDocument + Config.Save(this.TargetConfig, this.TargetFile.FullName); + this.Log.AddInfo(Util.CONFIG_Committed + " - " + this.TargetFile.Name); } else { - _xmlMerge.SavePendingConfigs(); - foreach (var key in _xmlMerge.PendingDocuments.Keys) + this._xmlMerge.SavePendingConfigs(); + foreach (var key in this._xmlMerge.PendingDocuments.Keys) { - Log.AddInfo(Util.CONFIG_Committed + " - " + key); + this.Log.AddInfo(Util.CONFIG_Committed + " - " + key); } } } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } } /// ----------------------------------------------------------------------------- /// - /// The Install method installs the config component + /// The Install method installs the config component. /// /// ----------------------------------------------------------------------------- public override void Install() { try { - if (string.IsNullOrEmpty(_FileName)) + if (string.IsNullOrEmpty(this._FileName)) { - //First backup the config file - Util.BackupFile(TargetFile, PhysicalSitePath, Log); + // First backup the config file + Util.BackupFile(this.TargetFile, this.PhysicalSitePath, this.Log); - //Create an XmlDocument for the config file - _TargetConfig = new XmlDocument { XmlResolver = null }; - TargetConfig.Load(Path.Combine(PhysicalSitePath, TargetFile.FullName)); + // Create an XmlDocument for the config file + this._TargetConfig = new XmlDocument { XmlResolver = null }; + this.TargetConfig.Load(Path.Combine(this.PhysicalSitePath, this.TargetFile.FullName)); - //Create XmlMerge instance from InstallConfig source - _xmlMerge = new XmlMerge(new StringReader(InstallConfig), Package.Version.ToString(), Package.Name); + // Create XmlMerge instance from InstallConfig source + this._xmlMerge = new XmlMerge(new StringReader(this.InstallConfig), this.Package.Version.ToString(), this.Package.Name); - //Update the Config file - Note that this method does not save the file - we will save it in Commit - _xmlMerge.UpdateConfig(TargetConfig); - Completed = true; - Log.AddInfo(Util.CONFIG_Updated + " - " + TargetFile.Name); + // Update the Config file - Note that this method does not save the file - we will save it in Commit + this._xmlMerge.UpdateConfig(this.TargetConfig); + this.Completed = true; + this.Log.AddInfo(Util.CONFIG_Updated + " - " + this.TargetFile.Name); } else { - //Process external file - string strConfigFile = Path.Combine(Package.InstallerInfo.TempInstallFolder, _FileName); + // Process external file + string strConfigFile = Path.Combine(this.Package.InstallerInfo.TempInstallFolder, this._FileName); if (File.Exists(strConfigFile)) { - //Create XmlMerge instance from config file source + // Create XmlMerge instance from config file source using (var stream = File.OpenText(strConfigFile)) { - _xmlMerge = new XmlMerge(stream, Package.Version.ToString(3), Package.Name + " Install"); + this._xmlMerge = new XmlMerge(stream, this.Package.Version.ToString(3), this.Package.Name + " Install"); - //Process merge - _xmlMerge.UpdateConfigs(false); + // Process merge + this._xmlMerge.UpdateConfigs(false); } - Completed = true; - Log.AddInfo(Util.CONFIG_Updated); + this.Completed = true; + this.Log.AddInfo(Util.CONFIG_Updated); } } } catch (Exception ex) { - Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } @@ -188,83 +172,82 @@ public override void Install() /// ----------------------------------------------------------------------------- public override void ReadManifest(XPathNavigator manifestNav) { - _FileName = Util.ReadAttribute(manifestNav, "fileName"); - _UninstallFileName = Util.ReadAttribute(manifestNav, "unInstallFileName"); + this._FileName = Util.ReadAttribute(manifestNav, "fileName"); + this._UninstallFileName = Util.ReadAttribute(manifestNav, "unInstallFileName"); - if (string.IsNullOrEmpty(_FileName)) + if (string.IsNullOrEmpty(this._FileName)) { XPathNavigator nav = manifestNav.SelectSingleNode("config"); - //Get the name of the target config file to update + // Get the name of the target config file to update XPathNavigator nodeNav = nav.SelectSingleNode("configFile"); string targetFileName = nodeNav.Value; if (!string.IsNullOrEmpty(targetFileName)) { - _TargetFile = new InstallFile(targetFileName, "", Package.InstallerInfo); + this._TargetFile = new InstallFile(targetFileName, string.Empty, this.Package.InstallerInfo); } - //Get the Install config changes + + // Get the Install config changes nodeNav = nav.SelectSingleNode("install"); - _InstallConfig = nodeNav.InnerXml; + this._InstallConfig = nodeNav.InnerXml; - //Get the UnInstall config changes + // Get the UnInstall config changes nodeNav = nav.SelectSingleNode("uninstall"); - _UnInstallConfig = nodeNav.InnerXml; + this._UnInstallConfig = nodeNav.InnerXml; } } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the file component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the file component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() { - //Do nothing as the changes are all in memory - Log.AddInfo(Util.CONFIG_RolledBack + " - " + TargetFile.Name); + // Do nothing as the changes are all in memory + this.Log.AddInfo(Util.CONFIG_RolledBack + " - " + this.TargetFile.Name); } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the config component + /// The UnInstall method uninstalls the config component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - if (string.IsNullOrEmpty(_UninstallFileName)) + if (string.IsNullOrEmpty(this._UninstallFileName)) { - if (!string.IsNullOrEmpty(UnInstallConfig)) + if (!string.IsNullOrEmpty(this.UnInstallConfig)) { - //Create an XmlDocument for the config file - _TargetConfig = new XmlDocument { XmlResolver = null }; - TargetConfig.Load(Path.Combine(PhysicalSitePath, TargetFile.FullName)); + // Create an XmlDocument for the config file + this._TargetConfig = new XmlDocument { XmlResolver = null }; + this.TargetConfig.Load(Path.Combine(this.PhysicalSitePath, this.TargetFile.FullName)); - //Create XmlMerge instance from UnInstallConfig source - var merge = new XmlMerge(new StringReader(UnInstallConfig), Package.Version.ToString(), Package.Name); + // Create XmlMerge instance from UnInstallConfig source + var merge = new XmlMerge(new StringReader(this.UnInstallConfig), this.Package.Version.ToString(), this.Package.Name); - //Update the Config file - Note that this method does save the file - merge.UpdateConfig(TargetConfig, TargetFile.FullName); + // Update the Config file - Note that this method does save the file + merge.UpdateConfig(this.TargetConfig, this.TargetFile.FullName); } } else { - //Process external file - string strConfigFile = Path.Combine(Package.InstallerInfo.TempInstallFolder, _UninstallFileName); + // Process external file + string strConfigFile = Path.Combine(this.Package.InstallerInfo.TempInstallFolder, this._UninstallFileName); if (File.Exists(strConfigFile)) { - //Create XmlMerge instance from config file source + // Create XmlMerge instance from config file source StreamReader stream = File.OpenText(strConfigFile); - var merge = new XmlMerge(stream, Package.Version.ToString(3), Package.Name + " UnInstall"); + var merge = new XmlMerge(stream, this.Package.Version.ToString(3), this.Package.Name + " UnInstall"); - //Process merge + // Process merge merge.UpdateConfigs(); - //Close stream + // Close stream stream.Close(); } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ContainerInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ContainerInstaller.cs index 49e40d1bf6a..bc72e500e48 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ContainerInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ContainerInstaller.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using DotNetNuke.UI.Skins; + /// ----------------------------------------------------------------------------- /// - /// The ContainerInstaller installs Container Components to a DotNetNuke site + /// The ContainerInstaller installs Container Components to a DotNetNuke site. /// /// /// @@ -21,9 +16,9 @@ public class ContainerInstaller : SkinInstaller { /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("containerFiles") + /// Gets the name of the Collection Node ("containerFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -35,9 +30,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("containerFile") + /// Gets the name of the Item Node ("containerFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -49,9 +44,9 @@ protected override string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the SkinName Node ("containerName") + /// Gets the name of the SkinName Node ("containerName"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string SkinNameNodeName { @@ -63,9 +58,9 @@ protected override string SkinNameNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the RootName of the Skin + /// Gets the RootName of the Skin. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string SkinRoot { @@ -77,9 +72,9 @@ protected override string SkinRoot /// ----------------------------------------------------------------------------- /// - /// Gets the Type of the Skin + /// Gets the Type of the Skin. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string SkinType { diff --git a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs index f8c98844fcb..ea9479d9512 100644 --- a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs @@ -1,52 +1,75 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// - /// The FileInstaller installs File Components to a DotNetNuke site + /// The FileInstaller installs File Components to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class FileInstaller : ComponentInstallerBase - { - #region Private Members - + { private readonly List _Files = new List(); - private bool _DeleteFiles = Null.NullBoolean; - - #endregion - - #region Protected Properties + private bool _DeleteFiles = Null.NullBoolean; + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the Packages files are deleted when uninstalling the + /// package. + /// + /// A Boolean value. + /// ----------------------------------------------------------------------------- + public bool DeleteFiles + { + get + { + return this._DeleteFiles; + } + + set + { + this._DeleteFiles = value; + } + } /// ----------------------------------------------------------------------------- /// - /// Gets the BasePath for the files + /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public override bool SupportsManifestOnlyInstall + { + get + { + return Null.NullBoolean; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the BasePath for the files. /// - /// The Base Path is relative to the WebRoot - /// A String + /// The Base Path is relative to the WebRoot. + /// A String. /// ----------------------------------------------------------------------------- protected string BasePath { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("files") + /// Gets the name of the Collection Node ("files"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string CollectionNodeName { @@ -58,23 +81,23 @@ protected virtual string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Files that are included in this component + /// Gets a Dictionary of Files that are included in this component. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- protected List Files { get { - return _Files; + return this._Files; } } /// ----------------------------------------------------------------------------- /// - /// Gets the default Path for the file - if not present in the manifest + /// Gets the default Path for the file - if not present in the manifest. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string DefaultPath { @@ -86,9 +109,9 @@ protected virtual string DefaultPath /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("file") + /// Gets the name of the Item Node ("file"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string ItemNodeName { @@ -100,69 +123,79 @@ protected virtual string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the PhysicalBasePath for the files + /// Gets the PhysicalBasePath for the files. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string PhysicalBasePath { get { - string _PhysicalBasePath = PhysicalSitePath + "\\" + BasePath; + string _PhysicalBasePath = this.PhysicalSitePath + "\\" + this.BasePath; if (!_PhysicalBasePath.EndsWith("\\")) { _PhysicalBasePath += "\\"; } + return _PhysicalBasePath.Replace("/", "\\"); } - } - - #endregion - - #region Public Properties - + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Packages files are deleted when uninstalling the - /// package + /// The Commit method finalises the Install and commits any pending changes. /// - /// A Boolean value + /// In the case of Files this is not neccessary. /// ----------------------------------------------------------------------------- - public bool DeleteFiles + public override void Commit() { - get + try { - return _DeleteFiles; + foreach (InstallFile file in this.Files) + { + this.CommitFile(file); + } + + this.Completed = true; } - set + catch (Exception ex) { - _DeleteFiles = value; + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } /// ----------------------------------------------------------------------------- /// - /// Gets whether the Installer supports Manifest only installs + /// The Install method installs the file component. /// - /// A Boolean /// ----------------------------------------------------------------------------- - public override bool SupportsManifestOnlyInstall + public override void Install() { - get + try { - return Null.NullBoolean; + bool bSuccess = true; + foreach (InstallFile file in this.Files) + { + bSuccess = this.InstallFile(file); + if (!bSuccess) + { + break; + } + } + + this.Completed = bSuccess; + } + catch (Exception ex) + { + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } - - #endregion - - #region Protected Methods - + /// ----------------------------------------------------------------------------- /// /// The CommitFile method commits a single file. /// - /// The InstallFile to commit + /// The InstallFile to commit. /// ----------------------------------------------------------------------------- protected virtual void CommitFile(InstallFile insFile) { @@ -172,13 +205,13 @@ protected virtual void CommitFile(InstallFile insFile) /// /// The DeleteFile method deletes a single file. /// - /// The InstallFile to delete + /// The InstallFile to delete. /// ----------------------------------------------------------------------------- protected virtual void DeleteFile(InstallFile insFile) { - if (DeleteFiles) + if (this.DeleteFiles) { - Util.DeleteFile(insFile, PhysicalBasePath, Log); + Util.DeleteFile(insFile, this.PhysicalBasePath, this.Log); } } @@ -186,43 +219,45 @@ protected virtual void DeleteFile(InstallFile insFile) /// /// The InstallFile method installs a single file. /// - /// The InstallFile to install + /// The InstallFile to install. + /// /// ----------------------------------------------------------------------------- protected virtual bool InstallFile(InstallFile insFile) { try { - //Check the White Lists - if ((Package.InstallerInfo.IgnoreWhiteList || Util.IsFileValid(insFile, Package.InstallerInfo.AllowableFiles))) + // Check the White Lists + if (this.Package.InstallerInfo.IgnoreWhiteList || Util.IsFileValid(insFile, this.Package.InstallerInfo.AllowableFiles)) { - //Install File - if (File.Exists(PhysicalBasePath + insFile.FullName)) + // Install File + if (File.Exists(this.PhysicalBasePath + insFile.FullName)) { - Util.BackupFile(insFile, PhysicalBasePath, Log); + Util.BackupFile(insFile, this.PhysicalBasePath, this.Log); } - - //Copy file from temp location - Util.CopyFile(insFile, PhysicalBasePath, Log); + + // Copy file from temp location + Util.CopyFile(insFile, this.PhysicalBasePath, this.Log); return true; } else { - Log.AddFailure(string.Format(Util.FILE_NotAllowed, insFile.FullName)); + this.Log.AddFailure(string.Format(Util.FILE_NotAllowed, insFile.FullName)); return false; } } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); return false; } } /// ----------------------------------------------------------------------------- /// - /// Gets a flag that determines what type of file this installer supports + /// Gets a flag that determines what type of file this installer supports. /// - /// The type of file being processed + /// The type of file being processed. + /// /// ----------------------------------------------------------------------------- protected virtual bool IsCorrectType(InstallFileType type) { @@ -231,28 +266,28 @@ protected virtual bool IsCorrectType(InstallFileType type) /// ----------------------------------------------------------------------------- /// - /// The ProcessFile method determines what to do with parsed "file" node + /// The ProcessFile method determines what to do with parsed "file" node. /// - /// The file represented by the node - /// The XPathNavigator representing the node + /// The file represented by the node. + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected virtual void ProcessFile(InstallFile file, XPathNavigator nav) { - if (file != null && IsCorrectType(file.Type)) + if (file != null && this.IsCorrectType(file.Type)) { - Files.Add(file); + this.Files.Add(file); - //Add to the - Package.InstallerInfo.Files[file.FullName.ToLowerInvariant()] = file; + // Add to the + this.Package.InstallerInfo.Files[file.FullName.ToLowerInvariant()] = file; } } /// ----------------------------------------------------------------------------- /// /// The ReadCustomManifest method reads the custom manifest items (that subclasses - /// of FileInstaller may need) + /// of FileInstaller may need). /// - /// The XPathNavigator representing the node + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected virtual void ReadCustomManifest(XPathNavigator nav) { @@ -260,71 +295,75 @@ protected virtual void ReadCustomManifest(XPathNavigator nav) /// ----------------------------------------------------------------------------- /// - /// The ReadManifestItem method reads a single node + /// The ReadManifestItem method reads a single node. /// - /// The XPathNavigator representing the node - /// Flag that determines whether a check should be made + /// The XPathNavigator representing the node. + /// Flag that determines whether a check should be made. + /// /// ----------------------------------------------------------------------------- protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) { string fileName = Null.NullString; - //Get the path + // Get the path XPathNavigator pathNav = nav.SelectSingleNode("path"); if (pathNav == null) { - fileName = DefaultPath; + fileName = this.DefaultPath; } else { fileName = pathNav.Value + "\\"; } - - //Get the name + + // Get the name XPathNavigator nameNav = nav.SelectSingleNode("name"); if (nameNav != null) { fileName += nameNav.Value; } - - //Get the sourceFileName - string sourceFileName = Util.ReadElement(nav, "sourceFileName"); - var file = new InstallFile(fileName, sourceFileName, Package.InstallerInfo); - if ((!string.IsNullOrEmpty(BasePath)) && (BasePath.StartsWith("app_code", StringComparison.InvariantCultureIgnoreCase) && file.Type == InstallFileType.Other)) + + // Get the sourceFileName + string sourceFileName = Util.ReadElement(nav, "sourceFileName"); + var file = new InstallFile(fileName, sourceFileName, this.Package.InstallerInfo); + if ((!string.IsNullOrEmpty(this.BasePath)) && (this.BasePath.StartsWith("app_code", StringComparison.InvariantCultureIgnoreCase) && file.Type == InstallFileType.Other)) { file.Type = InstallFileType.AppCode; } + if (file != null) { - //Set the Version - string strVersion = XmlUtils.GetNodeValue(nav, "version"); + // Set the Version + string strVersion = XmlUtils.GetNodeValue(nav, "version"); if (!string.IsNullOrEmpty(strVersion)) { file.SetVersion(new Version(strVersion)); } else { - file.SetVersion(Package.Version); + file.SetVersion(this.Package.Version); } - - //Set the Action - string strAction = XmlUtils.GetAttributeValue(nav, "action"); + + // Set the Action + string strAction = XmlUtils.GetAttributeValue(nav, "action"); if (!string.IsNullOrEmpty(strAction)) { file.Action = strAction; } - if (InstallMode == InstallMode.Install && checkFileExists && file.Action != "UnRegister") + + if (this.InstallMode == InstallMode.Install && checkFileExists && file.Action != "UnRegister") { if (File.Exists(file.TempFileName)) { - Log.AddInfo(string.Format(Util.FILE_Found, file.Path, file.Name)); + this.Log.AddInfo(string.Format(Util.FILE_Found, file.Path, file.Name)); } else { - Log.AddFailure(Util.FILE_NotFound + " - " + file.TempFileName); + this.Log.AddFailure(Util.FILE_NotFound + " - " + file.TempFileName); } } } + return file; } @@ -333,18 +372,18 @@ protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFil /// The RollbackFile method rolls back the install of a single file. /// /// For new installs this removes the added file. For upgrades it restores the - /// backup file created during install - /// The InstallFile to commit + /// backup file created during install. + /// The InstallFile to commit. /// ----------------------------------------------------------------------------- protected virtual void RollbackFile(InstallFile installFile) { if (File.Exists(installFile.BackupFileName)) { - Util.RestoreFile(installFile, PhysicalBasePath, Log); + Util.RestoreFile(installFile, this.PhysicalBasePath, this.Log); } else { - DeleteFile(installFile); + this.DeleteFile(installFile); } } @@ -356,61 +395,8 @@ protected virtual void RollbackFile(InstallFile installFile) /// ----------------------------------------------------------------------------- protected virtual void UnInstallFile(InstallFile unInstallFile) { - DeleteFile(unInstallFile); - } - - #endregion - - #region Public Methods - - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Files this is not neccessary - /// ----------------------------------------------------------------------------- - public override void Commit() - { - try - { - foreach (InstallFile file in Files) - { - CommitFile(file); - } - Completed = true; - } - catch (Exception ex) - { - Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The Install method installs the file component - /// - /// ----------------------------------------------------------------------------- - public override void Install() - { - try - { - bool bSuccess = true; - foreach (InstallFile file in Files) - { - bSuccess = InstallFile(file); - if (!bSuccess) - { - break; - } - } - Completed = bSuccess; - } - catch (Exception ex) - { - Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); - } - } + this.DeleteFile(unInstallFile); + } /// ----------------------------------------------------------------------------- /// @@ -419,65 +405,66 @@ public override void Install() /// ----------------------------------------------------------------------------- public override void ReadManifest(XPathNavigator manifestNav) { - XPathNavigator rootNav = manifestNav.SelectSingleNode(CollectionNodeName); + XPathNavigator rootNav = manifestNav.SelectSingleNode(this.CollectionNodeName); if (rootNav != null) { XPathNavigator baseNav = rootNav.SelectSingleNode("basePath"); if (baseNav != null) { - BasePath = baseNav.Value; + this.BasePath = baseNav.Value; } - ReadCustomManifest(rootNav); - foreach (XPathNavigator nav in rootNav.Select(ItemNodeName)) + + this.ReadCustomManifest(rootNav); + foreach (XPathNavigator nav in rootNav.Select(this.ItemNodeName)) { - ProcessFile(ReadManifestItem(nav, true), nav); + this.ProcessFile(this.ReadManifestItem(nav, true), nav); } } } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the file component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the file component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() { try { - foreach (InstallFile file in Files) + foreach (InstallFile file in this.Files) { - RollbackFile(file); + this.RollbackFile(file); } - Completed = true; + + this.Completed = true; } catch (Exception ex) { - Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the file component + /// The UnInstall method uninstalls the file component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { try { - foreach (InstallFile file in Files) + foreach (InstallFile file in this.Files) { - UnInstallFile(file); + this.UnInstallFile(file); } - Completed = true; + + this.Completed = true; } catch (Exception ex) { - Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs b/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs index beeb715fd3d..86d7e6dc823 100644 --- a/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs +++ b/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs @@ -1,38 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml.XPath; - -using DotNetNuke.Common.Lists; -using DotNetNuke.Framework; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Xml.XPath; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Framework; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// /// The InstallerFactory is a factory class that is used to instantiate the - /// appropriate Component Installer + /// appropriate Component Installer. /// /// /// /// ----------------------------------------------------------------------------- public class InstallerFactory - { - #region Public Shared Methods - + { /// ----------------------------------------------------------------------------- /// - /// The GetInstaller method instantiates the relevant Component Installer + /// The GetInstaller method instantiates the relevant Component Installer. /// - /// The type of Installer + /// The type of Installer. + /// /// ----------------------------------------------------------------------------- public static ComponentInstallerBase GetInstaller(string installerType) { @@ -95,26 +89,29 @@ public static ComponentInstallerBase GetInstaller(string installerType) installer = new JavaScriptFileInstaller(); break; default: - //Installer type is defined in the List + // Installer type is defined in the List var listController = new ListController(); ListEntryInfo entry = listController.GetListEntryInfo("Installer", installerType); if (entry != null && !string.IsNullOrEmpty(entry.Text)) { - //The class for the Installer is specified in the Text property - installer = (ComponentInstallerBase) Reflection.CreateObject(entry.Text, "Installer_" + entry.Value); + // The class for the Installer is specified in the Text property + installer = (ComponentInstallerBase)Reflection.CreateObject(entry.Text, "Installer_" + entry.Value); } + break; } + return installer; } /// ----------------------------------------------------------------------------- /// - /// The GetInstaller method instantiates the relevant Component Installer + /// The GetInstaller method instantiates the relevant Component Installer. /// - /// The manifest (XPathNavigator) for the component - /// The associated PackageInfo instance + /// The manifest (XPathNavigator) for the component. + /// The associated PackageInfo instance. + /// /// ----------------------------------------------------------------------------- public static ComponentInstallerBase GetInstaller(XPathNavigator manifestNav, PackageInfo package) { @@ -124,10 +121,10 @@ public static ComponentInstallerBase GetInstaller(XPathNavigator manifestNav, Pa ComponentInstallerBase installer = GetInstaller(installerType); if (installer != null) { - //Set package + // Set package installer.Package = package; - //Set type + // Set type installer.Type = installerType; if (!string.IsNullOrEmpty(componentVersion)) @@ -138,16 +135,15 @@ public static ComponentInstallerBase GetInstaller(XPathNavigator manifestNav, Pa { installer.Version = package.Version; } - - //Read Manifest + + // Read Manifest if (package.InstallerInfo.InstallMode != InstallMode.ManifestOnly || installer.SupportsManifestOnlyInstall) { installer.ReadManifest(manifestNav); } } + return installer; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs index bee1dd95b93..acade88447f 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs @@ -1,87 +1,72 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Xml.XPath; - -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Xml.XPath; + + using DotNetNuke.Common; + public class JavaScriptFileInstaller : FileInstaller - { - #region Protected Properties - + { /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("jsfiles") + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - protected override string CollectionNodeName + public override string AllowableFiles { get { - return "jsfiles"; + return "js"; } - } - + } + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("jsfile") + /// Gets the name of the Collection Node ("jsfiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - protected override string ItemNodeName + protected override string CollectionNodeName { get { - return "jsfile"; + return "jsfiles"; } } - #endregion - - #region Public Properties - /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets the name of the Item Node ("jsfile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - public override string AllowableFiles + protected override string ItemNodeName { get { - return "js"; + return "jsfile"; } - } - - - #endregion - - #region Protected Methods - + } + /// ----------------------------------------------------------------------------- /// /// The ReadCustomManifest method reads the custom manifest items (that subclasses - /// of FileInstaller may need) + /// of FileInstaller may need). /// - /// The XPathNavigator representing the node + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected override void ReadCustomManifest(XPathNavigator nav) { XPathNavigator libraryNav = nav.SelectSingleNode("libraryFolderName"); if (libraryNav != null) { - BasePath = String.Format("Resources\\Libraries\\{0}\\{1}", libraryNav.Value, Globals.FormatVersion(Package.Version, "00", 3, "_")); + this.BasePath = string.Format("Resources\\Libraries\\{0}\\{1}", libraryNav.Value, Globals.FormatVersion(this.Package.Version, "00", 3, "_")); } - } - - - #endregion - + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs index d1e71e529c6..25682665a45 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs @@ -1,104 +1,100 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework.JavaScriptLibraries; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.IO; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.JavaScriptLibraries; + public class JavaScriptLibraryInstaller : ComponentInstallerBase { private JavaScriptLibrary _library; - private JavaScriptLibrary _installedLibrary; + private JavaScriptLibrary _installedLibrary; - #region Public Methods + public override void Commit() + { + } - private void DeleteLibrary() + public override void Install() { try { - //Attempt to get the Library - var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.PackageID == Package.PackageID); + // Attempt to get the JavaScript Library + this._installedLibrary = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == this._library.LibraryName && l.Version == this._library.Version); - if (library != null) + if (this._installedLibrary != null) { - JavaScriptLibraryController.Instance.DeleteLibrary(library); - - Log.AddInfo(string.Format(Util.LIBRARY_UnRegistered, library.LibraryName)); + this._library.JavaScriptLibraryID = this._installedLibrary.JavaScriptLibraryID; } + + // Save JavaScript Library to database + this._library.PackageID = this.Package.PackageID; + JavaScriptLibraryController.Instance.SaveLibrary(this._library); + + this.Completed = true; + this.Log.AddInfo(string.Format(Util.LIBRARY_Registered, this._library.LibraryName)); } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } } - - public override void Commit() - { - } - - public override void Install() + + private void DeleteLibrary() { try { - //Attempt to get the JavaScript Library - _installedLibrary = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == _library.LibraryName && l.Version == _library.Version); + // Attempt to get the Library + var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.PackageID == this.Package.PackageID); - if (_installedLibrary != null) + if (library != null) { - _library.JavaScriptLibraryID = _installedLibrary.JavaScriptLibraryID; - } - //Save JavaScript Library to database - _library.PackageID = Package.PackageID; - JavaScriptLibraryController.Instance.SaveLibrary(_library); + JavaScriptLibraryController.Instance.DeleteLibrary(library); - Completed = true; - Log.AddInfo(string.Format(Util.LIBRARY_Registered, _library.LibraryName)); + this.Log.AddInfo(string.Format(Util.LIBRARY_UnRegistered, library.LibraryName)); + } } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } } public override void ReadManifest(XPathNavigator manifestNav) { - //Load the JavaScript Library from the manifest - _library = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); - _library.Version = Package.Version; + // Load the JavaScript Library from the manifest + this._library = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); + this._library.Version = this.Package.Version; - if (Log.Valid) + if (this.Log.Valid) { - Log.AddInfo(Util.LIBRARY_ReadSuccess); + this.Log.AddInfo(Util.LIBRARY_ReadSuccess); } } public override void Rollback() { - //If Temp Library exists then we need to update the DataStore with this - if (_installedLibrary == null) + // If Temp Library exists then we need to update the DataStore with this + if (this._installedLibrary == null) { - //No Temp Library - Delete newly added library - DeleteLibrary(); + // No Temp Library - Delete newly added library + this.DeleteLibrary(); } else { - //Temp Library - Rollback to Temp - JavaScriptLibraryController.Instance.SaveLibrary(_installedLibrary); + // Temp Library - Rollback to Temp + JavaScriptLibraryController.Instance.SaveLibrary(this._installedLibrary); } } public override void UnInstall() { - DeleteLibrary(); - } - - #endregion - + this.DeleteLibrary(); + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs index b424180af59..e54515a707e 100644 --- a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs @@ -1,52 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// - /// The LanguageInstaller installs Language Packs to a DotNetNuke site + /// The LanguageInstaller installs Language Packs to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class LanguageInstaller : FileInstaller - { - #region Private Members - + { private readonly LanguagePackType LanguagePackType; private LanguagePackInfo InstalledLanguagePack; private Locale Language; private LanguagePackInfo LanguagePack; - private Locale TempLanguage; - - #endregion - + private Locale TempLanguage; + public LanguageInstaller(LanguagePackType type) { - LanguagePackType = type; - } - - #region Protected Properties + this.LanguagePackType = type; + } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("languageFiles") + /// Gets a list of allowable file extensions (in addition to the Host's List). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public override string AllowableFiles + { + get { return "resx, xml, tdf,template"; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the name of the Collection Node ("languageFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -58,9 +58,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("languageFile") + /// Gets the name of the Item Node ("languageFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -69,80 +69,100 @@ protected override string ItemNodeName return "languageFile"; } } - + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// The Commit method finalises the Install and commits any pending changes. /// - /// A String + /// In the case of Modules this is not neccessary. /// ----------------------------------------------------------------------------- - public override string AllowableFiles + public override void Commit() { - get { return "resx, xml, tdf,template"; } + if (this.LanguagePackType == LanguagePackType.Core || this.LanguagePack.DependentPackageID > 0) + { + base.Commit(); + } + else + { + this.Completed = true; + this.Skipped = true; + } } - - #endregion - - #region Private Methods /// ----------------------------------------------------------------------------- /// - /// The DeleteLanguage method deletes the Language - /// from the data Store. + /// The Install method installs the language component. /// /// ----------------------------------------------------------------------------- - private void DeleteLanguage() + public override void Install() { - try + if (this.LanguagePackType == LanguagePackType.Core || this.LanguagePack.DependentPackageID > 0) { - //Attempt to get the LanguagePack - LanguagePackInfo tempLanguagePack = LanguagePackController.GetLanguagePackByPackage(Package.PackageID); - - //Attempt to get the Locale - Locale language = LocaleController.Instance.GetLocale(tempLanguagePack.LanguageID); - if (tempLanguagePack != null) + try { - LanguagePackController.DeleteLanguagePack(tempLanguagePack); - } + // Attempt to get the LanguagePack + this.InstalledLanguagePack = LanguagePackController.GetLanguagePackByPackage(this.Package.PackageID); + if (this.InstalledLanguagePack != null) + { + this.LanguagePack.LanguagePackID = this.InstalledLanguagePack.LanguagePackID; + } - // fix DNN-26330 Removing a language pack extension removes the language - // we should not delete language when deleting language pack, as there is just a loose relationship - //if (language != null && tempLanguagePack.PackageType == LanguagePackType.Core) - //{ - // Localization.Localization.DeleteLanguage(language); - //} + // Attempt to get the Locale + this.TempLanguage = LocaleController.Instance.GetLocale(this.Language.Code); + if (this.TempLanguage != null) + { + this.Language.LanguageId = this.TempLanguage.LanguageId; + } + + if (this.LanguagePack.PackageType == LanguagePackType.Core) + { + // Update language + Localization.SaveLanguage(this.Language); + } + + // Set properties for Language Pack + this.LanguagePack.PackageID = this.Package.PackageID; + this.LanguagePack.LanguageID = this.Language.LanguageId; + + // Update LanguagePack + LanguagePackController.SaveLanguagePack(this.LanguagePack); + + this.Log.AddInfo(string.Format(Util.LANGUAGE_Registered, this.Language.Text)); - Log.AddInfo(string.Format(Util.LANGUAGE_UnRegistered, language.Text)); + // install (copy the files) by calling the base class + base.Install(); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } } - catch (Exception ex) + else { - Log.AddFailure(ex); + this.Completed = true; + this.Skipped = true; } } - - #endregion - - #region Protected Methods - + /// ----------------------------------------------------------------------------- /// - /// The ReadCustomManifest method reads the custom manifest items + /// The ReadCustomManifest method reads the custom manifest items. /// - /// The XPathNavigator representing the node + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected override void ReadCustomManifest(XPathNavigator nav) { - Language = new Locale(); - LanguagePack = new LanguagePackInfo(); + this.Language = new Locale(); + this.LanguagePack = new LanguagePackInfo(); - //Get the Skin name - Language.Code = Util.ReadElement(nav, "code"); - Language.Text = Util.ReadElement(nav, "displayName"); - Language.Fallback = Util.ReadElement(nav, "fallback"); + // Get the Skin name + this.Language.Code = Util.ReadElement(nav, "code"); + this.Language.Text = Util.ReadElement(nav, "displayName"); + this.Language.Fallback = Util.ReadElement(nav, "fallback"); - if (LanguagePackType == LanguagePackType.Core) + if (this.LanguagePackType == LanguagePackType.Core) { - LanguagePack.DependentPackageID = -2; + this.LanguagePack.DependentPackageID = -2; } else { @@ -150,128 +170,83 @@ protected override void ReadCustomManifest(XPathNavigator nav) PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals(packageName, StringComparison.OrdinalIgnoreCase)); if (package != null) { - LanguagePack.DependentPackageID = package.PackageID; + this.LanguagePack.DependentPackageID = package.PackageID; } } - - //Call base class - base.ReadCustomManifest(nav); - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Modules this is not neccessary - /// ----------------------------------------------------------------------------- - public override void Commit() - { - if (LanguagePackType == LanguagePackType.Core || LanguagePack.DependentPackageID > 0) - { - base.Commit(); - } - else - { - Completed = true; - Skipped = true; - } - } + // Call base class + base.ReadCustomManifest(nav); + } + /// ----------------------------------------------------------------------------- /// - /// The Install method installs the language component + /// The DeleteLanguage method deletes the Language + /// from the data Store. /// /// ----------------------------------------------------------------------------- - public override void Install() + private void DeleteLanguage() { - if (LanguagePackType == LanguagePackType.Core || LanguagePack.DependentPackageID > 0) + try { - try - { - //Attempt to get the LanguagePack - InstalledLanguagePack = LanguagePackController.GetLanguagePackByPackage(Package.PackageID); - if (InstalledLanguagePack != null) - { - LanguagePack.LanguagePackID = InstalledLanguagePack.LanguagePackID; - } + // Attempt to get the LanguagePack + LanguagePackInfo tempLanguagePack = LanguagePackController.GetLanguagePackByPackage(this.Package.PackageID); - //Attempt to get the Locale - TempLanguage = LocaleController.Instance.GetLocale(Language.Code); - if (TempLanguage != null) - { - Language.LanguageId = TempLanguage.LanguageId; - } - if (LanguagePack.PackageType == LanguagePackType.Core) - { - //Update language - Localization.Localization.SaveLanguage(Language); - } - - //Set properties for Language Pack - LanguagePack.PackageID = Package.PackageID; - LanguagePack.LanguageID = Language.LanguageId; - - //Update LanguagePack - LanguagePackController.SaveLanguagePack(LanguagePack); - - Log.AddInfo(string.Format(Util.LANGUAGE_Registered, Language.Text)); - - //install (copy the files) by calling the base class - base.Install(); - } - catch (Exception ex) + // Attempt to get the Locale + Locale language = LocaleController.Instance.GetLocale(tempLanguagePack.LanguageID); + if (tempLanguagePack != null) { - Log.AddFailure(ex); + LanguagePackController.DeleteLanguagePack(tempLanguagePack); } + + // fix DNN-26330 Removing a language pack extension removes the language + // we should not delete language when deleting language pack, as there is just a loose relationship + // if (language != null && tempLanguagePack.PackageType == LanguagePackType.Core) + // { + // Localization.DeleteLanguage(language); + // } + this.Log.AddInfo(string.Format(Util.LANGUAGE_UnRegistered, language.Text)); } - else + catch (Exception ex) { - Completed = true; - Skipped = true; + this.Log.AddFailure(ex); } - } + } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() { - //If Temp Language exists then we need to update the DataStore with this - if (TempLanguage == null) + // If Temp Language exists then we need to update the DataStore with this + if (this.TempLanguage == null) { - //No Temp Language - Delete newly added Language - DeleteLanguage(); + // No Temp Language - Delete newly added Language + this.DeleteLanguage(); } else { - //Temp Language - Rollback to Temp - Localization.Localization.SaveLanguage(TempLanguage); + // Temp Language - Rollback to Temp + Localization.SaveLanguage(this.TempLanguage); } - - //Call base class to prcoess files - base.Rollback(); + + // Call base class to prcoess files + base.Rollback(); } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the language component + /// The UnInstall method uninstalls the language component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - DeleteLanguage(); + this.DeleteLanguage(); - //Call base class to prcoess files + // Call base class to prcoess files base.UnInstall(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs index 3cf2a13a6d5..553d9fdde63 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs @@ -1,274 +1,259 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.EventQueue; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Tabs.TabVersions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.IO; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.EventQueue; + /// ----------------------------------------------------------------------------- /// - /// The ModuleInstaller installs Module Components to a DotNetNuke site + /// The ModuleInstaller installs Module Components to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class ModuleInstaller : ComponentInstallerBase - { - #region Private Properties - + { private DesktopModuleInfo _desktopModule; private EventMessage _eventMessage; - private DesktopModuleInfo _installedDesktopModule; - - #endregion - - #region Public Properties - + private DesktopModuleInfo _installedDesktopModule; + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public override string AllowableFiles { get { - return "cshtml, vbhtml, ashx, aspx, ascx, vb, cs, resx, css, js, resources, config, vbproj, csproj, sln, htm, html, xml, psd, svc, asmx, xsl, xslt"; + return "cshtml, vbhtml, ashx, aspx, ascx, vb, cs, resx, css, js, resources, config, vbproj, csproj, sln, htm, html, xml, psd, svc, asmx, xsl, xslt"; } - } - - #endregion - - #region Private Methods - - /// ----------------------------------------------------------------------------- - /// - /// The DeleteModule method deletes the Module from the data Store. - /// - /// ----------------------------------------------------------------------------- - private void DeleteModule() - { - try - { - //Attempt to get the Desktop Module - DesktopModuleInfo tempDesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(Package.PackageID); - if (tempDesktopModule != null) - { - var modules = ModuleController.Instance.GetModulesByDesktopModuleId(tempDesktopModule.DesktopModuleID); - //Remove CodeSubDirectory - if ((_desktopModule != null) && (!string.IsNullOrEmpty(_desktopModule.CodeSubDirectory))) - { - Config.RemoveCodeSubDirectory(_desktopModule.CodeSubDirectory); - } - var controller = new DesktopModuleController(); - - - Log.AddInfo(string.Format(Util.MODULE_UnRegistered, tempDesktopModule.ModuleName)); - //remove admin/host pages - if (!String.IsNullOrEmpty(tempDesktopModule.AdminPage)) - { - string tabPath = "//Admin//" + tempDesktopModule.AdminPage; - - var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) - { - var tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - - TabInfo temp = TabController.Instance.GetTab(tabID, portal.PortalID); - if ((temp != null)) - { - - var mods = TabModulesController.Instance.GetTabModules((temp)); - bool noOtherTabModule = true; - foreach (ModuleInfo mod in mods) - { - if (mod.DesktopModuleID != tempDesktopModule.DesktopModuleID) - { - noOtherTabModule = false; - - } - } - if (noOtherTabModule) - { - Log.AddInfo(string.Format(Util.MODULE_AdminPageRemoved, tempDesktopModule.AdminPage, portal.PortalID)); - TabController.Instance.DeleteTab(tabID, portal.PortalID); - } - Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleRemoved, tempDesktopModule.AdminPage, portal.PortalID)); - } - } - - } - if (!String.IsNullOrEmpty(tempDesktopModule.HostPage)) - { - Upgrade.Upgrade.RemoveHostPage(tempDesktopModule.HostPage); - Log.AddInfo(string.Format(Util.MODULE_HostPageRemoved, tempDesktopModule.HostPage)); - Log.AddInfo(string.Format(Util.MODULE_HostPagemoduleRemoved, tempDesktopModule.HostPage)); - } - - controller.DeleteDesktopModule(tempDesktopModule); - //Remove all the tab versions related with the module. - foreach (var module in modules) - { - var moduleInfo = module as ModuleInfo; - if (moduleInfo != null) - TabVersionController.Instance.DeleteTabVersionDetailByModule(moduleInfo.ModuleID); - } - } - - } - catch (Exception ex) - { - Log.AddFailure(ex); - } - } - - #endregion - - #region Public Methods - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. /// - /// In the case of Modules this is not neccessary + /// In the case of Modules this is not neccessary. /// ----------------------------------------------------------------------------- public override void Commit() { - //Add CodeSubDirectory - if (!string.IsNullOrEmpty(_desktopModule.CodeSubDirectory)) + // Add CodeSubDirectory + if (!string.IsNullOrEmpty(this._desktopModule.CodeSubDirectory)) { - Config.AddCodeSubDirectory(_desktopModule.CodeSubDirectory); + Config.AddCodeSubDirectory(this._desktopModule.CodeSubDirectory); } - if (_desktopModule.SupportedFeatures == Null.NullInteger) + + if (this._desktopModule.SupportedFeatures == Null.NullInteger) { - //Set an Event Message so the features are loaded by reflection on restart - var oAppStartMessage = new EventMessage - { - Priority = MessagePriority.High, - ExpirationDate = DateTime.Now.AddYears(-1), - SentDate = DateTime.Now, - Body = "", - ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", - ProcessorCommand = "UpdateSupportedFeatures" - }; - - //Add custom Attributes for this message - oAppStartMessage.Attributes.Add("BusinessControllerClass", _desktopModule.BusinessControllerClass); - oAppStartMessage.Attributes.Add("desktopModuleID", _desktopModule.DesktopModuleID.ToString()); - - //send it to occur on next App_Start Event + // Set an Event Message so the features are loaded by reflection on restart + var oAppStartMessage = new EventMessage + { + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(-1), + SentDate = DateTime.Now, + Body = string.Empty, + ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", + ProcessorCommand = "UpdateSupportedFeatures", + }; + + // Add custom Attributes for this message + oAppStartMessage.Attributes.Add("BusinessControllerClass", this._desktopModule.BusinessControllerClass); + oAppStartMessage.Attributes.Add("desktopModuleID", this._desktopModule.DesktopModuleID.ToString()); + + // send it to occur on next App_Start Event EventQueueController.SendMessage(oAppStartMessage, "Application_Start_FirstRequest"); } - - //Add Event Message - if (_eventMessage != null) + + // Add Event Message + if (this._eventMessage != null) { - if (!String.IsNullOrEmpty(_eventMessage.Attributes["UpgradeVersionsList"])) + if (!string.IsNullOrEmpty(this._eventMessage.Attributes["UpgradeVersionsList"])) { - _eventMessage.Attributes.Set("desktopModuleID", _desktopModule.DesktopModuleID.ToString()); - EventQueueController.SendMessage(_eventMessage, "Application_Start"); + this._eventMessage.Attributes.Set("desktopModuleID", this._desktopModule.DesktopModuleID.ToString()); + EventQueueController.SendMessage(this._eventMessage, "Application_Start"); } } - - //Add DesktopModule to all portals - if (!_desktopModule.IsPremium) + + // Add DesktopModule to all portals + if (!this._desktopModule.IsPremium) { - DesktopModuleController.AddDesktopModuleToPortals(_desktopModule.DesktopModuleID); + DesktopModuleController.AddDesktopModuleToPortals(this._desktopModule.DesktopModuleID); } - //Add DesktopModule to all portals - if (!String.IsNullOrEmpty(_desktopModule.AdminPage)) + // Add DesktopModule to all portals + if (!string.IsNullOrEmpty(this._desktopModule.AdminPage)) { foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - bool createdNewPage = false, addedNewModule = false; - DesktopModuleController.AddDesktopModulePageToPortal(_desktopModule, _desktopModule.AdminPage, portal.PortalID, ref createdNewPage, ref addedNewModule); + DesktopModuleController.AddDesktopModulePageToPortal(this._desktopModule, this._desktopModule.AdminPage, portal.PortalID, ref createdNewPage, ref addedNewModule); if (createdNewPage) { - Log.AddInfo(string.Format(Util.MODULE_AdminPageAdded, _desktopModule.AdminPage, portal.PortalID)); + this.Log.AddInfo(string.Format(Util.MODULE_AdminPageAdded, this._desktopModule.AdminPage, portal.PortalID)); } if (addedNewModule) { - Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleAdded, _desktopModule.AdminPage,portal.PortalID)); + this.Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleAdded, this._desktopModule.AdminPage, portal.PortalID)); } } - } - //Add host items - if (_desktopModule.Page != null && !String.IsNullOrEmpty(_desktopModule.HostPage)) + // Add host items + if (this._desktopModule.Page != null && !string.IsNullOrEmpty(this._desktopModule.HostPage)) { bool createdNewPage = false, addedNewModule = false; - DesktopModuleController.AddDesktopModulePageToPortal(_desktopModule, _desktopModule.HostPage, Null.NullInteger, ref createdNewPage, ref addedNewModule); + DesktopModuleController.AddDesktopModulePageToPortal(this._desktopModule, this._desktopModule.HostPage, Null.NullInteger, ref createdNewPage, ref addedNewModule); if (createdNewPage) { - Log.AddInfo(string.Format(Util.MODULE_HostPageAdded, _desktopModule.HostPage)); + this.Log.AddInfo(string.Format(Util.MODULE_HostPageAdded, this._desktopModule.HostPage)); } if (addedNewModule) { - Log.AddInfo(string.Format(Util.MODULE_HostPagemoduleAdded, _desktopModule.HostPage)); + this.Log.AddInfo(string.Format(Util.MODULE_HostPagemoduleAdded, this._desktopModule.HostPage)); } } } /// ----------------------------------------------------------------------------- /// - /// The Install method installs the Module component + /// The Install method installs the Module component. /// /// ----------------------------------------------------------------------------- public override void Install() { try { - //Attempt to get the Desktop Module - _installedDesktopModule = DesktopModuleController.GetDesktopModuleByModuleName(_desktopModule.ModuleName, Package.InstallerInfo.PortalID); + // Attempt to get the Desktop Module + this._installedDesktopModule = DesktopModuleController.GetDesktopModuleByModuleName(this._desktopModule.ModuleName, this.Package.InstallerInfo.PortalID); - if (_installedDesktopModule != null) + if (this._installedDesktopModule != null) { - _desktopModule.DesktopModuleID = _installedDesktopModule.DesktopModuleID; - //save the module's category - _desktopModule.Category = _installedDesktopModule.Category; + this._desktopModule.DesktopModuleID = this._installedDesktopModule.DesktopModuleID; + + // save the module's category + this._desktopModule.Category = this._installedDesktopModule.Category; } - - //Clear ModuleControls and Module Definitions caches in case script has modifed the contents + + // Clear ModuleControls and Module Definitions caches in case script has modifed the contents DataCache.RemoveCache(DataCache.ModuleDefinitionCacheKey); DataCache.RemoveCache(DataCache.ModuleControlsCacheKey); - //Save DesktopModule and child objects to database - _desktopModule.PackageID = Package.PackageID; - _desktopModule.DesktopModuleID = DesktopModuleController.SaveDesktopModule(_desktopModule, true, false); + // Save DesktopModule and child objects to database + this._desktopModule.PackageID = this.Package.PackageID; + this._desktopModule.DesktopModuleID = DesktopModuleController.SaveDesktopModule(this._desktopModule, true, false); - Completed = true; - Log.AddInfo(string.Format(Util.MODULE_Registered, _desktopModule.ModuleName)); + this.Completed = true; + this.Log.AddInfo(string.Format(Util.MODULE_Registered, this._desktopModule.ModuleName)); } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } } + + /// ----------------------------------------------------------------------------- + /// + /// The DeleteModule method deletes the Module from the data Store. + /// + /// ----------------------------------------------------------------------------- + private void DeleteModule() + { + try + { + // Attempt to get the Desktop Module + DesktopModuleInfo tempDesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(this.Package.PackageID); + if (tempDesktopModule != null) + { + var modules = ModuleController.Instance.GetModulesByDesktopModuleId(tempDesktopModule.DesktopModuleID); + + // Remove CodeSubDirectory + if ((this._desktopModule != null) && (!string.IsNullOrEmpty(this._desktopModule.CodeSubDirectory))) + { + Config.RemoveCodeSubDirectory(this._desktopModule.CodeSubDirectory); + } + + var controller = new DesktopModuleController(); + + this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, tempDesktopModule.ModuleName)); + + // remove admin/host pages + if (!string.IsNullOrEmpty(tempDesktopModule.AdminPage)) + { + string tabPath = "//Admin//" + tempDesktopModule.AdminPage; + + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) + { + var tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); + + TabInfo temp = TabController.Instance.GetTab(tabID, portal.PortalID); + if (temp != null) + { + var mods = TabModulesController.Instance.GetTabModules(temp); + bool noOtherTabModule = true; + foreach (ModuleInfo mod in mods) + { + if (mod.DesktopModuleID != tempDesktopModule.DesktopModuleID) + { + noOtherTabModule = false; + } + } + + if (noOtherTabModule) + { + this.Log.AddInfo(string.Format(Util.MODULE_AdminPageRemoved, tempDesktopModule.AdminPage, portal.PortalID)); + TabController.Instance.DeleteTab(tabID, portal.PortalID); + } + + this.Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleRemoved, tempDesktopModule.AdminPage, portal.PortalID)); + } + } + } + + if (!string.IsNullOrEmpty(tempDesktopModule.HostPage)) + { + Upgrade.Upgrade.RemoveHostPage(tempDesktopModule.HostPage); + this.Log.AddInfo(string.Format(Util.MODULE_HostPageRemoved, tempDesktopModule.HostPage)); + this.Log.AddInfo(string.Format(Util.MODULE_HostPagemoduleRemoved, tempDesktopModule.HostPage)); + } + + controller.DeleteDesktopModule(tempDesktopModule); + + // Remove all the tab versions related with the module. + foreach (var module in modules) + { + var moduleInfo = module as ModuleInfo; + if (moduleInfo != null) + { + TabVersionController.Instance.DeleteTabVersionDetailByModule(moduleInfo.ModuleID); + } + } + } + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } /// ----------------------------------------------------------------------------- /// @@ -277,23 +262,23 @@ public override void Install() /// ----------------------------------------------------------------------------- public override void ReadManifest(XPathNavigator manifestNav) { - //Load the Desktop Module from the manifest - _desktopModule = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); - - _desktopModule.FriendlyName = Package.FriendlyName; - _desktopModule.Description = Package.Description; - _desktopModule.Version = Globals.FormatVersion(Package.Version, "00", 4, "."); - _desktopModule.CompatibleVersions = Null.NullString; - _desktopModule.Dependencies = Null.NullString; - _desktopModule.Permissions = Null.NullString; - if (string.IsNullOrEmpty(_desktopModule.BusinessControllerClass)) + // Load the Desktop Module from the manifest + this._desktopModule = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); + + this._desktopModule.FriendlyName = this.Package.FriendlyName; + this._desktopModule.Description = this.Package.Description; + this._desktopModule.Version = Globals.FormatVersion(this.Package.Version, "00", 4, "."); + this._desktopModule.CompatibleVersions = Null.NullString; + this._desktopModule.Dependencies = Null.NullString; + this._desktopModule.Permissions = Null.NullString; + if (string.IsNullOrEmpty(this._desktopModule.BusinessControllerClass)) { - _desktopModule.SupportedFeatures = 0; + this._desktopModule.SupportedFeatures = 0; } - _eventMessage = ReadEventMessageNode(manifestNav); - - //Load permissions (to add) + this._eventMessage = this.ReadEventMessageNode(manifestNav); + + // Load permissions (to add) foreach (XPathNavigator moduleDefinitionNav in manifestNav.Select("desktopModule/moduleDefinitions/moduleDefinition")) { string friendlyName = Util.ReadElement(moduleDefinitionNav, "friendlyName"); @@ -303,50 +288,49 @@ public override void ReadManifest(XPathNavigator manifestNav) permission.PermissionCode = Util.ReadAttribute(permissionNav, "code"); permission.PermissionKey = Util.ReadAttribute(permissionNav, "key"); permission.PermissionName = Util.ReadAttribute(permissionNav, "name"); - ModuleDefinitionInfo moduleDefinition = _desktopModule.ModuleDefinitions[friendlyName]; + ModuleDefinitionInfo moduleDefinition = this._desktopModule.ModuleDefinitions[friendlyName]; if (moduleDefinition != null) { moduleDefinition.Permissions.Add(permission.PermissionKey, permission); } } } - if (Log.Valid) + + if (this.Log.Valid) { - Log.AddInfo(Util.MODULE_ReadSuccess); + this.Log.AddInfo(Util.MODULE_ReadSuccess); } } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() { - //If Temp Module exists then we need to update the DataStore with this - if (_installedDesktopModule == null) + // If Temp Module exists then we need to update the DataStore with this + if (this._installedDesktopModule == null) { - //No Temp Module - Delete newly added module - DeleteModule(); + // No Temp Module - Delete newly added module + this.DeleteModule(); } else { - //Temp Module - Rollback to Temp - DesktopModuleController.SaveDesktopModule(_installedDesktopModule, true, false); + // Temp Module - Rollback to Temp + DesktopModuleController.SaveDesktopModule(this._installedDesktopModule, true, false); } } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the Module component + /// The UnInstall method uninstalls the Module component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - DeleteModule(); - } - - #endregion + this.DeleteModule(); + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs index b0166ff4ee6..0a38230cec1 100644 --- a/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs @@ -1,246 +1,143 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.EventQueue; -using DotNetNuke.Services.Installer.Dependencies; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.EventQueue; + using DotNetNuke.Services.Installer.Dependencies; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The PackageInstaller class is an Installer for Packages + /// The PackageInstaller class is an Installer for Packages. /// /// ----------------------------------------------------------------------------- public class PackageInstaller : ComponentInstallerBase - { - #region Private Members - + { private readonly SortedList _componentInstallers = new SortedList(); private PackageInfo _installedPackage; - private EventMessage _eventMessage; - - #endregion - - #region Constructors - + private EventMessage _eventMessage; + /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new PackageInstaller instance + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new PackageInstaller instance. /// - /// A PackageInfo instance + /// A PackageInfo instance. /// ----------------------------------------------------------------------------- public PackageInstaller(PackageInfo package) { - IsValid = true; - DeleteFiles = Null.NullBoolean; - Package = package; + this.IsValid = true; + this.DeleteFiles = Null.NullBoolean; + this.Package = package; if (!string.IsNullOrEmpty(package.Manifest)) { - //Create an XPathDocument from the Xml + // Create an XPathDocument from the Xml var doc = new XPathDocument(new StringReader(package.Manifest)); XPathNavigator nav = doc.CreateNavigator().SelectSingleNode("package"); - ReadComponents(nav); + this.ReadComponents(nav); } else { ComponentInstallerBase installer = InstallerFactory.GetInstaller(package.PackageType); if (installer != null) { - //Set package + // Set package installer.Package = package; - //Set type + // Set type installer.Type = package.PackageType; - _componentInstallers.Add(0, installer); + this._componentInstallers.Add(0, installer); } } - } - + } + /// ----------------------------------------------------------------------------- - /// - /// This Constructor creates a new PackageInstaller instance + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new PackageInstaller instance. /// - /// An InstallerInfo instance - /// The manifest as a string + /// An InstallerInfo instance. + /// The manifest as a string. /// ----------------------------------------------------------------------------- public PackageInstaller(string packageManifest, InstallerInfo info) { - IsValid = true; - DeleteFiles = Null.NullBoolean; - Package = new PackageInfo(info); - Package.Manifest = packageManifest; + this.IsValid = true; + this.DeleteFiles = Null.NullBoolean; + this.Package = new PackageInfo(info); + this.Package.Manifest = packageManifest; if (!string.IsNullOrEmpty(packageManifest)) { - //Create an XPathDocument from the Xml + // Create an XPathDocument from the Xml var doc = new XPathDocument(new StringReader(packageManifest)); XPathNavigator nav = doc.CreateNavigator().SelectSingleNode("package"); - ReadManifest(nav); + this.ReadManifest(nav); } - } - - #endregion - - #region Public Properties - + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Packages files are deleted when uninstalling the - /// package + /// Gets or sets a value indicating whether gets and sets whether the Packages files are deleted when uninstalling the + /// package. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- public bool DeleteFiles { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the Package is Valid - /// - /// A Boolean value - /// ----------------------------------------------------------------------------- - public bool IsValid { get; private set; } - - #endregion - - #region Private Methods - - /// ----------------------------------------------------------------------------- - /// - /// The CheckSecurity method checks whether the user has the appropriate security + /// Gets a value indicating whether gets whether the Package is Valid. /// + /// A Boolean value. /// ----------------------------------------------------------------------------- - private void CheckSecurity() - { - PackageType type = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(Package.PackageType, StringComparison.OrdinalIgnoreCase)); - if (type == null) - { - //This package type not registered - Log.Logs.Clear(); - Log.AddFailure(Util.SECURITY_NotRegistered + " - " + Package.PackageType); - IsValid = false; - } - else - { - if (type.SecurityAccessLevel > Package.InstallerInfo.SecurityAccessLevel) - { - Log.Logs.Clear(); - Log.AddFailure(Util.SECURITY_Installer); - IsValid = false; - } - } - } - + public bool IsValid { get; private set; } + /// ----------------------------------------------------------------------------- /// - /// The ReadComponents method reads the components node of the manifest file. - /// - /// ----------------------------------------------------------------------------- - private void ReadComponents(XPathNavigator manifestNav) - { - foreach (XPathNavigator componentNav in manifestNav.CreateNavigator().Select("components/component")) - { - //Set default order to next value (ie the same as the size of the collection) - int order = _componentInstallers.Count; - - string type = componentNav.GetAttribute("type", ""); - if (InstallMode == InstallMode.Install) - { - string installOrder = componentNav.GetAttribute("installOrder", ""); - if (!string.IsNullOrEmpty(installOrder)) - { - order = int.Parse(installOrder); - } - } - else - { - string unInstallOrder = componentNav.GetAttribute("unInstallOrder", ""); - if (!string.IsNullOrEmpty(unInstallOrder)) - { - order = int.Parse(unInstallOrder); - } - } - if (Package.InstallerInfo != null) - { - Log.AddInfo(Util.DNN_ReadingComponent + " - " + type); - } - ComponentInstallerBase installer = InstallerFactory.GetInstaller(componentNav, Package); - if (installer == null) - { - Log.AddFailure(Util.EXCEPTION_InstallerCreate); - } - else - { - _componentInstallers.Add(order, installer); - Package.InstallerInfo.AllowableFiles += ", " + installer.AllowableFiles; - } - } - } - - private string ReadTextFromFile(string source) - { - string strText = Null.NullString; - if (Package.InstallerInfo.InstallMode != InstallMode.ManifestOnly) - { - //Load from file - strText = FileSystemUtils.ReadFile(Package.InstallerInfo.TempInstallFolder + "\\" + source); - } - return strText; - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method commits the package installation + /// The Commit method commits the package installation. /// /// ----------------------------------------------------------------------------- public override void Commit() { - for (int index = 0; index <= _componentInstallers.Count - 1; index++) + for (int index = 0; index <= this._componentInstallers.Count - 1; index++) { - ComponentInstallerBase compInstaller = _componentInstallers.Values[index]; - if (compInstaller.Version >= Package.InstalledVersion && compInstaller.Completed) + ComponentInstallerBase compInstaller = this._componentInstallers.Values[index]; + if (compInstaller.Version >= this.Package.InstalledVersion && compInstaller.Completed) { compInstaller.Commit(); } } - //Add Event Message - if (_eventMessage != null && !String.IsNullOrEmpty(_eventMessage.Attributes["UpgradeVersionsList"])) + // Add Event Message + if (this._eventMessage != null && !string.IsNullOrEmpty(this._eventMessage.Attributes["UpgradeVersionsList"])) { - _eventMessage.Attributes.Set("desktopModuleID", Null.NullInteger.ToString()); - EventQueueController.SendMessage(_eventMessage, "Application_Start"); + this._eventMessage.Attributes.Set("desktopModuleID", Null.NullInteger.ToString()); + EventQueueController.SendMessage(this._eventMessage, "Application_Start"); } - if (Log.Valid) + if (this.Log.Valid) { - Log.AddInfo(Util.INSTALL_Committed); + this.Log.AddInfo(Util.INSTALL_Committed); } else { - Log.AddFailure(Util.INSTALL_Aborted); + this.Log.AddFailure(Util.INSTALL_Aborted); } - Package.InstallerInfo.PackageID = Package.PackageID; + + this.Package.InstallerInfo.PackageID = this.Package.PackageID; } /// ----------------------------------------------------------------------------- /// - /// The Install method installs the components of the package + /// The Install method installs the components of the package. /// /// ----------------------------------------------------------------------------- public override void Install() @@ -248,37 +145,37 @@ public override void Install() bool isCompleted = true; try { - //Save the Package Information - if (_installedPackage != null) + // Save the Package Information + if (this._installedPackage != null) { - Package.PackageID = _installedPackage.PackageID; + this.Package.PackageID = this._installedPackage.PackageID; } - - //Save Package - PackageController.Instance.SaveExtensionPackage(Package); - //Iterate through all the Components - for (int index = 0; index <= _componentInstallers.Count - 1; index++) + // Save Package + PackageController.Instance.SaveExtensionPackage(this.Package); + + // Iterate through all the Components + for (int index = 0; index <= this._componentInstallers.Count - 1; index++) { - ComponentInstallerBase compInstaller = _componentInstallers.Values[index]; - if ((_installedPackage == null) || (compInstaller.Version > Package.InstalledVersion) || (Package.InstallerInfo.RepairInstall)) + ComponentInstallerBase compInstaller = this._componentInstallers.Values[index]; + if ((this._installedPackage == null) || (compInstaller.Version > this.Package.InstalledVersion) || this.Package.InstallerInfo.RepairInstall) { - Log.AddInfo(Util.INSTALL_Start + " - " + compInstaller.Type); + this.Log.AddInfo(Util.INSTALL_Start + " - " + compInstaller.Type); compInstaller.Install(); if (compInstaller.Completed) { if (compInstaller.Skipped) { - Log.AddInfo(Util.COMPONENT_Skipped + " - " + compInstaller.Type); + this.Log.AddInfo(Util.COMPONENT_Skipped + " - " + compInstaller.Type); } else { - Log.AddInfo(Util.COMPONENT_Installed + " - " + compInstaller.Type); + this.Log.AddInfo(Util.COMPONENT_Installed + " - " + compInstaller.Type); } } else { - Log.AddFailure(Util.INSTALL_Failed + " - " + compInstaller.Type); + this.Log.AddFailure(Util.INSTALL_Failed + " - " + compInstaller.Type); isCompleted = false; break; } @@ -287,20 +184,107 @@ public override void Install() } catch (Exception ex) { - Log.AddFailure(Util.INSTALL_Aborted + " - " + Package.Name + ":" + ex.Message); + this.Log.AddFailure(Util.INSTALL_Aborted + " - " + this.Package.Name + ":" + ex.Message); } + if (isCompleted) { - //All components successfully installed so Commit any pending changes - Commit(); + // All components successfully installed so Commit any pending changes + this.Commit(); + } + else + { + // There has been a failure so Rollback + this.Rollback(); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The CheckSecurity method checks whether the user has the appropriate security. + /// + /// ----------------------------------------------------------------------------- + private void CheckSecurity() + { + PackageType type = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(this.Package.PackageType, StringComparison.OrdinalIgnoreCase)); + if (type == null) + { + // This package type not registered + this.Log.Logs.Clear(); + this.Log.AddFailure(Util.SECURITY_NotRegistered + " - " + this.Package.PackageType); + this.IsValid = false; } else { - //There has been a failure so Rollback - Rollback(); + if (type.SecurityAccessLevel > this.Package.InstallerInfo.SecurityAccessLevel) + { + this.Log.Logs.Clear(); + this.Log.AddFailure(Util.SECURITY_Installer); + this.IsValid = false; + } } } + /// ----------------------------------------------------------------------------- + /// + /// The ReadComponents method reads the components node of the manifest file. + /// + /// ----------------------------------------------------------------------------- + private void ReadComponents(XPathNavigator manifestNav) + { + foreach (XPathNavigator componentNav in manifestNav.CreateNavigator().Select("components/component")) + { + // Set default order to next value (ie the same as the size of the collection) + int order = this._componentInstallers.Count; + + string type = componentNav.GetAttribute("type", string.Empty); + if (this.InstallMode == InstallMode.Install) + { + string installOrder = componentNav.GetAttribute("installOrder", string.Empty); + if (!string.IsNullOrEmpty(installOrder)) + { + order = int.Parse(installOrder); + } + } + else + { + string unInstallOrder = componentNav.GetAttribute("unInstallOrder", string.Empty); + if (!string.IsNullOrEmpty(unInstallOrder)) + { + order = int.Parse(unInstallOrder); + } + } + + if (this.Package.InstallerInfo != null) + { + this.Log.AddInfo(Util.DNN_ReadingComponent + " - " + type); + } + + ComponentInstallerBase installer = InstallerFactory.GetInstaller(componentNav, this.Package); + if (installer == null) + { + this.Log.AddFailure(Util.EXCEPTION_InstallerCreate); + } + else + { + this._componentInstallers.Add(order, installer); + this.Package.InstallerInfo.AllowableFiles += ", " + installer.AllowableFiles; + } + } + } + + private string ReadTextFromFile(string source) + { + string strText = Null.NullString; + if (this.Package.InstallerInfo.InstallMode != InstallMode.ManifestOnly) + { + // Load from file + strText = FileSystemUtils.ReadFile(this.Package.InstallerInfo.TempInstallFolder + "\\" + source); + } + + return strText; + } + /// ----------------------------------------------------------------------------- /// /// The ReadManifest method reads the manifest file and parses it into components. @@ -308,109 +292,131 @@ public override void Install() /// ----------------------------------------------------------------------------- public override void ReadManifest(XPathNavigator manifestNav) { - //Get Name Property - Package.Name = Util.ReadAttribute(manifestNav, "name", Log, Util.EXCEPTION_NameMissing); + // Get Name Property + this.Package.Name = Util.ReadAttribute(manifestNav, "name", this.Log, Util.EXCEPTION_NameMissing); - //Get Type - Package.PackageType = Util.ReadAttribute(manifestNav, "type", Log, Util.EXCEPTION_TypeMissing); + // Get Type + this.Package.PackageType = Util.ReadAttribute(manifestNav, "type", this.Log, Util.EXCEPTION_TypeMissing); - //If Skin or Container then set PortalID - if (Package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase) || Package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase)) + // If Skin or Container then set PortalID + if (this.Package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase) || this.Package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase)) { - Package.PortalID = Package.InstallerInfo.PortalID; + this.Package.PortalID = this.Package.InstallerInfo.PortalID; } - CheckSecurity(); - if (!IsValid) + + this.CheckSecurity(); + if (!this.IsValid) { return; } - //Get IsSystem - Package.IsSystemPackage = bool.Parse(Util.ReadAttribute(manifestNav, "isSystem", false, Log, "", bool.FalseString)); + // Get IsSystem + this.Package.IsSystemPackage = bool.Parse(Util.ReadAttribute(manifestNav, "isSystem", false, this.Log, string.Empty, bool.FalseString)); - //Get Version - string strVersion = Util.ReadAttribute(manifestNav, "version", Log, Util.EXCEPTION_VersionMissing); + // Get Version + string strVersion = Util.ReadAttribute(manifestNav, "version", this.Log, Util.EXCEPTION_VersionMissing); if (string.IsNullOrEmpty(strVersion)) { - IsValid = false; + this.IsValid = false; } - if (IsValid) + + if (this.IsValid) { - Package.Version = new Version(strVersion); + this.Package.Version = new Version(strVersion); } else { return; } - //Attempt to get the Package from the Data Store (see if its installed) - var packageType = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(Package.PackageType, StringComparison.OrdinalIgnoreCase)); + // Attempt to get the Package from the Data Store (see if its installed) + var packageType = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(this.Package.PackageType, StringComparison.OrdinalIgnoreCase)); if (packageType.SupportsSideBySideInstallation) { - _installedPackage = PackageController.Instance.GetExtensionPackage(Package.PortalID, p => p.Name.Equals(Package.Name, StringComparison.OrdinalIgnoreCase) - && p.PackageType.Equals(Package.PackageType, StringComparison.OrdinalIgnoreCase) - && p.Version == Package.Version); + this._installedPackage = PackageController.Instance.GetExtensionPackage(this.Package.PortalID, p => p.Name.Equals(this.Package.Name, StringComparison.OrdinalIgnoreCase) + && p.PackageType.Equals(this.Package.PackageType, StringComparison.OrdinalIgnoreCase) + && p.Version == this.Package.Version); } else { - _installedPackage = PackageController.Instance.GetExtensionPackage(Package.PortalID, p => p.Name.Equals(Package.Name, StringComparison.OrdinalIgnoreCase) - && p.PackageType.Equals(Package.PackageType, StringComparison.OrdinalIgnoreCase)); + this._installedPackage = PackageController.Instance.GetExtensionPackage(this.Package.PortalID, p => p.Name.Equals(this.Package.Name, StringComparison.OrdinalIgnoreCase) + && p.PackageType.Equals(this.Package.PackageType, StringComparison.OrdinalIgnoreCase)); } - if (_installedPackage != null) + if (this._installedPackage != null) { - Package.InstalledVersion = _installedPackage.Version; - Package.InstallerInfo.PackageID = _installedPackage.PackageID; + this.Package.InstalledVersion = this._installedPackage.Version; + this.Package.InstallerInfo.PackageID = this._installedPackage.PackageID; - if (Package.InstalledVersion > Package.Version) + if (this.Package.InstalledVersion > this.Package.Version) { - Log.AddFailure(Util.INSTALL_Version + " - " + Package.InstalledVersion.ToString(3)); - IsValid = false; + this.Log.AddFailure(Util.INSTALL_Version + " - " + this.Package.InstalledVersion.ToString(3)); + this.IsValid = false; } - else if (Package.InstalledVersion == Package.Version) + else if (this.Package.InstalledVersion == this.Package.Version) { - Package.InstallerInfo.Installed = true; - Package.InstallerInfo.PortalID = _installedPackage.PortalID; + this.Package.InstallerInfo.Installed = true; + this.Package.InstallerInfo.PortalID = this._installedPackage.PortalID; } } - Log.AddInfo(Util.DNN_ReadingPackage + " - " + Package.PackageType + " - " + Package.Name); - Package.FriendlyName = Util.ReadElement(manifestNav, "friendlyName", Package.Name); - Package.Description = Util.ReadElement(manifestNav, "description"); + this.Log.AddInfo(Util.DNN_ReadingPackage + " - " + this.Package.PackageType + " - " + this.Package.Name); + this.Package.FriendlyName = Util.ReadElement(manifestNav, "friendlyName", this.Package.Name); + this.Package.Description = Util.ReadElement(manifestNav, "description"); XPathNavigator foldernameNav = null; - Package.FolderName = String.Empty; - switch (Package.PackageType) + this.Package.FolderName = string.Empty; + switch (this.Package.PackageType) { case "Module": - //In Dynamics moduels, a component:type=File can have a basePath pointing to the App_Conde folder. This is not a correct FolderName - //To ensure that FolderName is DesktopModules... + // In Dynamics moduels, a component:type=File can have a basePath pointing to the App_Conde folder. This is not a correct FolderName + // To ensure that FolderName is DesktopModules... var folderNameValue = PackageController.GetSpecificFolderName(manifestNav, "components/component/files|components/component/resourceFiles", "basePath", "DesktopModules"); - if (!String.IsNullOrEmpty(folderNameValue)) Package.FolderName = folderNameValue.Replace('\\', '/'); + if (!string.IsNullOrEmpty(folderNameValue)) + { + this.Package.FolderName = folderNameValue.Replace('\\', '/'); + } + break; case "Auth_System": foldernameNav = manifestNav.SelectSingleNode("components/component/files"); - if (foldernameNav != null) Package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/'); + if (foldernameNav != null) + { + this.Package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/'); + } + break; case "Container": foldernameNav = manifestNav.SelectSingleNode("components/component/containerFiles"); - if (foldernameNav != null) Package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/'); + if (foldernameNav != null) + { + this.Package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/'); + } + break; case "Skin": foldernameNav = manifestNav.SelectSingleNode("components/component/skinFiles"); - if (foldernameNav != null) Package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/'); + if (foldernameNav != null) + { + this.Package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/'); + } + break; default: - //copied from "Module" without the extra OR condition + // copied from "Module" without the extra OR condition folderNameValue = PackageController.GetSpecificFolderName(manifestNav, "components/component/resourceFiles", "basePath", "DesktopModules"); - if (!String.IsNullOrEmpty(folderNameValue)) Package.FolderName = folderNameValue.Replace('\\', '/'); + if (!string.IsNullOrEmpty(folderNameValue)) + { + this.Package.FolderName = folderNameValue.Replace('\\', '/'); + } + break; } - _eventMessage = ReadEventMessageNode(manifestNav); + this._eventMessage = this.ReadEventMessageNode(manifestNav); - //Get Icon + // Get Icon XPathNavigator iconFileNav = manifestNav.SelectSingleNode("iconFile"); if (iconFileNav != null) { @@ -418,77 +424,80 @@ public override void ReadManifest(XPathNavigator manifestNav) { if (iconFileNav.Value.StartsWith("~/")) { - Package.IconFile = iconFileNav.Value; + this.Package.IconFile = iconFileNav.Value; } else if (iconFileNav.Value.StartsWith("DesktopModules", StringComparison.InvariantCultureIgnoreCase)) { - Package.IconFile = string.Format("~/{0}", iconFileNav.Value); + this.Package.IconFile = string.Format("~/{0}", iconFileNav.Value); } else { - Package.IconFile = (String.IsNullOrEmpty(Package.FolderName) ? "" : Package.FolderName + "/") + iconFileNav.Value; - Package.IconFile = (!Package.IconFile.StartsWith("~/")) ? "~/" + Package.IconFile : Package.IconFile; + this.Package.IconFile = (string.IsNullOrEmpty(this.Package.FolderName) ? string.Empty : this.Package.FolderName + "/") + iconFileNav.Value; + this.Package.IconFile = (!this.Package.IconFile.StartsWith("~/")) ? "~/" + this.Package.IconFile : this.Package.IconFile; } } } - //Get Author + + // Get Author XPathNavigator authorNav = manifestNav.SelectSingleNode("owner"); if (authorNav != null) { - Package.Owner = Util.ReadElement(authorNav, "name"); - Package.Organization = Util.ReadElement(authorNav, "organization"); - Package.Url = Util.ReadElement(authorNav, "url"); - Package.Email = Util.ReadElement(authorNav, "email"); + this.Package.Owner = Util.ReadElement(authorNav, "name"); + this.Package.Organization = Util.ReadElement(authorNav, "organization"); + this.Package.Url = Util.ReadElement(authorNav, "url"); + this.Package.Email = Util.ReadElement(authorNav, "email"); } - - //Get License + + // Get License XPathNavigator licenseNav = manifestNav.SelectSingleNode("license"); if (licenseNav != null) { string licenseSrc = Util.ReadAttribute(licenseNav, "src"); if (string.IsNullOrEmpty(licenseSrc)) { - //Load from element - Package.License = licenseNav.Value; + // Load from element + this.Package.License = licenseNav.Value; } else { - Package.License = ReadTextFromFile(licenseSrc); + this.Package.License = this.ReadTextFromFile(licenseSrc); } } - if (string.IsNullOrEmpty(Package.License)) + + if (string.IsNullOrEmpty(this.Package.License)) { - //Legacy Packages have no license - Package.License = Util.PACKAGE_NoLicense; + // Legacy Packages have no license + this.Package.License = Util.PACKAGE_NoLicense; } - - //Get Release Notes + + // Get Release Notes XPathNavigator relNotesNav = manifestNav.SelectSingleNode("releaseNotes"); if (relNotesNav != null) { string relNotesSrc = Util.ReadAttribute(relNotesNav, "src"); if (string.IsNullOrEmpty(relNotesSrc)) { - //Load from element - Package.ReleaseNotes = relNotesNav.Value; + // Load from element + this.Package.ReleaseNotes = relNotesNav.Value; } else { - Package.ReleaseNotes = ReadTextFromFile(relNotesSrc); + this.Package.ReleaseNotes = this.ReadTextFromFile(relNotesSrc); } } - if (string.IsNullOrEmpty(Package.ReleaseNotes)) + + if (string.IsNullOrEmpty(this.Package.ReleaseNotes)) { - //Legacy Packages have no Release Notes - Package.ReleaseNotes = Util.PACKAGE_NoReleaseNotes; + // Legacy Packages have no Release Notes + this.Package.ReleaseNotes = Util.PACKAGE_NoReleaseNotes; } - //Parse the Dependencies - var packageDependencies = Package.Dependencies; + // Parse the Dependencies + var packageDependencies = this.Package.Dependencies; foreach (XPathNavigator dependencyNav in manifestNav.CreateNavigator().Select("dependencies/dependency")) { - var dependency = DependencyFactory.GetDependency(dependencyNav); - var packageDependecy = dependency as IManagedPackageDependency; + var dependency = DependencyFactory.GetDependency(dependencyNav); + var packageDependecy = dependency as IManagedPackageDependency; if (packageDependecy != null) { @@ -497,80 +506,79 @@ public override void ReadManifest(XPathNavigator manifestNav) if (!dependency.IsValid) { - Log.AddFailure(dependency.ErrorMessage); + this.Log.AddFailure(dependency.ErrorMessage); return; } } - //Read Components - ReadComponents(manifestNav); + // Read Components + this.ReadComponents(manifestNav); } /// ----------------------------------------------------------------------------- /// - /// The Rollback method rolls back the package installation + /// The Rollback method rolls back the package installation. /// /// ----------------------------------------------------------------------------- public override void Rollback() { - for (int index = 0; index <= _componentInstallers.Count - 1; index++) + for (int index = 0; index <= this._componentInstallers.Count - 1; index++) { - ComponentInstallerBase compInstaller = _componentInstallers.Values[index]; - if (compInstaller.Version > Package.InstalledVersion && compInstaller.Completed) + ComponentInstallerBase compInstaller = this._componentInstallers.Values[index]; + if (compInstaller.Version > this.Package.InstalledVersion && compInstaller.Completed) { - Log.AddInfo(Util.COMPONENT_RollingBack + " - " + compInstaller.Type); + this.Log.AddInfo(Util.COMPONENT_RollingBack + " - " + compInstaller.Type); compInstaller.Rollback(); - Log.AddInfo(Util.COMPONENT_RolledBack + " - " + compInstaller.Type); + this.Log.AddInfo(Util.COMPONENT_RolledBack + " - " + compInstaller.Type); } } - - //If Previously Installed Package exists then we need to update the DataStore with this - if (_installedPackage == null) + + // If Previously Installed Package exists then we need to update the DataStore with this + if (this._installedPackage == null) { - //No Previously Installed Package - Delete newly added Package - PackageController.Instance.DeleteExtensionPackage(Package); + // No Previously Installed Package - Delete newly added Package + PackageController.Instance.DeleteExtensionPackage(this.Package); } else { - //Previously Installed Package - Rollback to Previously Installed - PackageController.Instance.SaveExtensionPackage(_installedPackage); + // Previously Installed Package - Rollback to Previously Installed + PackageController.Instance.SaveExtensionPackage(this._installedPackage); } } /// ----------------------------------------------------------------------------- /// - /// The Uninstall method uninstalls the components of the package + /// The Uninstall method uninstalls the components of the package. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - //Iterate through all the Components - for (int index = 0; index <= _componentInstallers.Count - 1; index++) + // Iterate through all the Components + for (int index = 0; index <= this._componentInstallers.Count - 1; index++) { - ComponentInstallerBase compInstaller = _componentInstallers.Values[index]; + ComponentInstallerBase compInstaller = this._componentInstallers.Values[index]; var fileInstaller = compInstaller as FileInstaller; if (fileInstaller != null) { - fileInstaller.DeleteFiles = DeleteFiles; + fileInstaller.DeleteFiles = this.DeleteFiles; } - Log.ResetFlags(); - Log.AddInfo(Util.UNINSTALL_StartComp + " - " + compInstaller.Type); + + this.Log.ResetFlags(); + this.Log.AddInfo(Util.UNINSTALL_StartComp + " - " + compInstaller.Type); compInstaller.UnInstall(); - Log.AddInfo(Util.COMPONENT_UnInstalled + " - " + compInstaller.Type); - if (Log.Valid) + this.Log.AddInfo(Util.COMPONENT_UnInstalled + " - " + compInstaller.Type); + if (this.Log.Valid) { - Log.AddInfo(Util.UNINSTALL_SuccessComp + " - " + compInstaller.Type); + this.Log.AddInfo(Util.UNINSTALL_SuccessComp + " - " + compInstaller.Type); } else { - Log.AddWarning(Util.UNINSTALL_WarningsComp + " - " + compInstaller.Type); + this.Log.AddWarning(Util.UNINSTALL_WarningsComp + " - " + compInstaller.Type); } } - - //Remove the Package information from the Data Store - PackageController.Instance.DeleteExtensionPackage(Package); - } - - #endregion + + // Remove the Package information from the Data Store + PackageController.Instance.DeleteExtensionPackage(this.Package); + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ProviderInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ProviderInstaller.cs index f2e9e6ae38b..837648d832e 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ProviderInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ProviderInstaller.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml.XPath; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System.Xml.XPath; + /// ----------------------------------------------------------------------------- /// - /// The ProviderInstaller installs Provider Components to a DotNetNuke site + /// The ProviderInstaller installs Provider Components to a DotNetNuke site. /// /// /// @@ -21,9 +16,9 @@ public class ProviderInstaller : ComponentInstallerBase { /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public override string AllowableFiles { @@ -35,12 +30,12 @@ public override string AllowableFiles public override void Commit() { - Completed = true; + this.Completed = true; } public override void Install() { - Completed = true; + this.Completed = true; } public override void ReadManifest(XPathNavigator manifestNav) @@ -49,12 +44,12 @@ public override void ReadManifest(XPathNavigator manifestNav) public override void Rollback() { - Completed = true; + this.Completed = true; } public override void UnInstall() { - Completed = true; + this.Completed = true; } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs index 6b3145f6978..106cd2e94b1 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs @@ -1,109 +1,86 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#region Usings - -using System; -using System.IO; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; - -using ICSharpCode.SharpZipLib.Zip; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.IO; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using ICSharpCode.SharpZipLib.Zip; + /// ----------------------------------------------------------------------------- /// - /// The ResourceFileInstaller installs Resource File Components (zips) to a DotNetNuke site + /// The ResourceFileInstaller installs Resource File Components (zips) to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class ResourceFileInstaller : FileInstaller { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ResourceFileInstaller)); - #region "Public Contants" public const string DEFAULT_MANIFESTEXT = ".manifest"; - private string _Manifest; - - #endregion - - #region "Protected Properties" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ResourceFileInstaller)); + private string _Manifest; + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("resourceFiles") + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - protected override string CollectionNodeName + public override string AllowableFiles { get { - return "resourceFiles"; + return "resources, zip"; } - } - + } + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("resourceFile") + /// Gets the name of the Collection Node ("resourceFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - protected override string ItemNodeName + protected override string CollectionNodeName { get { - return "resourceFile"; + return "resourceFiles"; } } /// ----------------------------------------------------------------------------- - protected string Manifest + /// + /// Gets the name of the Item Node ("resourceFile"). + /// + /// A String. + /// ----------------------------------------------------------------------------- + protected override string ItemNodeName { get { - return _Manifest; + return "resourceFile"; } } - #endregion - - #region "Public Properties" - - /// ----------------------------------------------------------------------------- - /// - /// Gets a list of allowable file extensions (in addition to the Host's List) - /// - /// A String - /// ----------------------------------------------------------------------------- - public override string AllowableFiles + // ----------------------------------------------------------------------------- + protected string Manifest { get { - return "resources, zip"; + return this._Manifest; } - } - - #endregion - - #region "Protected Methods" - + } + /// ----------------------------------------------------------------------------- /// /// The CommitFile method commits a single file. /// - /// The InstallFile to commit + /// The InstallFile to commit. /// ----------------------------------------------------------------------------- protected override void CommitFile(InstallFile insFile) { @@ -113,7 +90,7 @@ protected override void CommitFile(InstallFile insFile) /// /// The DeleteFile method deletes a single assembly. /// - /// The InstallFile to delete + /// The InstallFile to delete. /// ----------------------------------------------------------------------------- protected override void DeleteFile(InstallFile file) { @@ -123,21 +100,24 @@ protected override void DeleteFile(InstallFile file) /// /// The InstallFile method installs a single assembly. /// - /// The InstallFile to install + /// The InstallFile to install. + /// protected override bool InstallFile(InstallFile insFile) { bool retValue = true; try { - Log.AddInfo(Util.FILES_Expanding); - //Create the folder for destination - _Manifest = insFile.Name + ".manifest"; - if (!Directory.Exists(PhysicalBasePath)) + this.Log.AddInfo(Util.FILES_Expanding); + + // Create the folder for destination + this._Manifest = insFile.Name + ".manifest"; + if (!Directory.Exists(this.PhysicalBasePath)) { - Directory.CreateDirectory(PhysicalBasePath); + Directory.CreateDirectory(this.PhysicalBasePath); } + using (var unzip = new ZipInputStream(new FileStream(insFile.TempFileName, FileMode.Open))) - using (var manifestStream = new FileStream(Path.Combine(PhysicalBasePath, Manifest), FileMode.Create, FileAccess.Write)) + using (var manifestStream = new FileStream(Path.Combine(this.PhysicalBasePath, this.Manifest), FileMode.Create, FileAccess.Write)) { var settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Fragment; @@ -146,13 +126,12 @@ protected override bool InstallFile(InstallFile insFile) using (var writer = XmlWriter.Create(manifestStream, settings)) { - - //Start the new Root Element + // Start the new Root Element writer.WriteStartElement("dotnetnuke"); writer.WriteAttributeString("type", "ResourceFile"); writer.WriteAttributeString("version", "5.0"); - //Start files Element + // Start files Element writer.WriteStartElement("files"); ZipEntry entry = unzip.GetNextEntry(); @@ -163,42 +142,43 @@ protected override bool InstallFile(InstallFile insFile) { string fileName = Path.GetFileName(entry.Name); - //Start file Element + // Start file Element writer.WriteStartElement("file"); - //Write path - writer.WriteElementString("path", + // Write path + writer.WriteElementString( + "path", entry.Name.Substring(0, entry.Name.IndexOf(fileName))); - //Write name + // Write name writer.WriteElementString("name", fileName); - var physicalPath = Path.Combine(PhysicalBasePath, entry.Name); + var physicalPath = Path.Combine(this.PhysicalBasePath, entry.Name); if (File.Exists(physicalPath)) { - Util.BackupFile(new InstallFile(entry.Name, Package.InstallerInfo), - PhysicalBasePath, - Log); + Util.BackupFile( + new InstallFile(entry.Name, this.Package.InstallerInfo), + this.PhysicalBasePath, + this.Log); } Util.WriteStream(unzip, physicalPath); - //Close files Element + // Close files Element writer.WriteEndElement(); - Log.AddInfo(string.Format(Util.FILE_Created, entry.Name)); + this.Log.AddInfo(string.Format(Util.FILE_Created, entry.Name)); } entry = unzip.GetNextEntry(); } - //Close files Element + // Close files Element writer.WriteEndElement(); - Log.AddInfo(Util.FILES_CreatedResources); + this.Log.AddInfo(Util.FILES_CreatedResources); } } - } catch (Exception exc) { @@ -206,39 +186,42 @@ protected override bool InstallFile(InstallFile insFile) retValue = false; } + return retValue; } /// ----------------------------------------------------------------------------- /// - /// Gets a flag that determines what type of file this installer supports + /// Gets a flag that determines what type of file this installer supports. /// - /// The type of file being processed + /// The type of file being processed. + /// /// ----------------------------------------------------------------------------- protected override bool IsCorrectType(InstallFileType type) { - return (type == InstallFileType.Resources); + return type == InstallFileType.Resources; } /// ----------------------------------------------------------------------------- /// - /// The ReadManifestItem method reads a single node + /// The ReadManifestItem method reads a single node. /// - /// The XPathNavigator representing the node - /// Flag that determines whether a check should be made + /// The XPathNavigator representing the node. + /// Flag that determines whether a check should be made. + /// /// ----------------------------------------------------------------------------- protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) { InstallFile insFile = base.ReadManifestItem(nav, checkFileExists); - _Manifest = Util.ReadElement(nav, "manifest"); + this._Manifest = Util.ReadElement(nav, "manifest"); - if (string.IsNullOrEmpty(_Manifest)) + if (string.IsNullOrEmpty(this._Manifest)) { - _Manifest = insFile.FullName + DEFAULT_MANIFESTEXT; + this._Manifest = insFile.FullName + DEFAULT_MANIFESTEXT; } - //Call base method + // Call base method return base.ReadManifestItem(nav, checkFileExists); } @@ -247,8 +230,8 @@ protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFi /// The RollbackFile method rolls back the install of a single file. /// /// For new installs this removes the added file. For upgrades it restores the - /// backup file created during install - /// The InstallFile to commit + /// backup file created during install. + /// The InstallFile to commit. /// ----------------------------------------------------------------------------- protected override void RollbackFile(InstallFile insFile) { @@ -260,18 +243,19 @@ protected override void RollbackFile(InstallFile insFile) entry.CheckZipEntry(); if (!entry.IsDirectory) { - //Check for Backups + // Check for Backups if (File.Exists(insFile.BackupPath + entry.Name)) { - //Restore File - Util.RestoreFile(new InstallFile(unzip, entry, Package.InstallerInfo), PhysicalBasePath, Log); + // Restore File + Util.RestoreFile(new InstallFile(unzip, entry, this.Package.InstallerInfo), this.PhysicalBasePath, this.Log); } else { - //Delete File - Util.DeleteFile(entry.Name, PhysicalBasePath, Log); + // Delete File + Util.DeleteFile(entry.Name, this.PhysicalBasePath, this.Log); } } + entry = unzip.GetNextEntry(); } } @@ -279,8 +263,8 @@ protected override void RollbackFile(InstallFile insFile) protected override void UnInstallFile(InstallFile unInstallFile) { - _Manifest = unInstallFile.Name + ".manifest"; - var doc = new XPathDocument(Path.Combine(PhysicalBasePath, Manifest)); + this._Manifest = unInstallFile.Name + ".manifest"; + var doc = new XPathDocument(Path.Combine(this.PhysicalBasePath, this.Manifest)); foreach (XPathNavigator fileNavigator in doc.CreateNavigator().Select("dotnetnuke/files/file")) { @@ -289,22 +273,21 @@ protected override void UnInstallFile(InstallFile unInstallFile) string filePath = Path.Combine(path, fileName); try { - if (DeleteFiles) + if (this.DeleteFiles) { - Util.DeleteFile(filePath, PhysicalBasePath, Log); + Util.DeleteFile(filePath, this.PhysicalBasePath, this.Log); } } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } } - if (DeleteFiles) + + if (this.DeleteFiles) { - Util.DeleteFile(Manifest, PhysicalBasePath, Log); + Util.DeleteFile(this.Manifest, this.PhysicalBasePath, this.Log); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs index 8b2616e8bec..4bc8102d0ea 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs @@ -1,89 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Framework.Providers; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Framework.Providers; + /// ----------------------------------------------------------------------------- /// - /// The ScriptInstaller installs Script Components to a DotNetNuke site + /// The ScriptInstaller installs Script Components to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class ScriptInstaller : FileInstaller - { - #region Private Members - + { private readonly SortedList _installScripts = new SortedList(); private readonly SortedList _unInstallScripts = new SortedList(); private InstallFile _installScript; - private InstallFile _upgradeScript; - - #endregion - - #region Protected Properties - + private InstallFile _upgradeScript; + /// ----------------------------------------------------------------------------- /// - /// Gets the base Install Script (if present) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// An InstallFile + /// A String. + /// ----------------------------------------------------------------------------- + public override string AllowableFiles + { + get + { + return "*dataprovider, sql"; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the base Install Script (if present). + /// + /// An InstallFile. /// ----------------------------------------------------------------------------- protected InstallFile InstallScript { get { - return _installScript; + return this._installScript; } } /// ----------------------------------------------------------------------------- /// - /// Gets the collection of Install Scripts + /// Gets the collection of Install Scripts. /// - /// A List(Of InstallFile) + /// A List(Of InstallFile). /// ----------------------------------------------------------------------------- protected SortedList InstallScripts { get { - return _installScripts; + return this._installScripts; } } /// ----------------------------------------------------------------------------- /// - /// Gets the collection of UnInstall Scripts + /// Gets the collection of UnInstall Scripts. /// - /// A List(Of InstallFile) + /// A List(Of InstallFile). /// ----------------------------------------------------------------------------- protected SortedList UnInstallScripts { get { - return _unInstallScripts; + return this._unInstallScripts; } } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("scripts") + /// Gets the name of the Collection Node ("scripts"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -95,9 +98,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("script") + /// Gets the name of the Item Node ("script"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -117,253 +120,229 @@ protected ProviderConfiguration ProviderConfiguration /// ----------------------------------------------------------------------------- /// - /// Gets the Upgrade Script (if present) + /// Gets the Upgrade Script (if present). /// - /// An InstallFile + /// An InstallFile. /// ----------------------------------------------------------------------------- protected InstallFile UpgradeScript { get { - return _upgradeScript; + return this._upgradeScript; } - } - - #endregion - - #region Public Properties - + } + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// The Commit method finalises the Install and commits any pending changes. /// - /// A String + /// In the case of Files this is not neccessary. /// ----------------------------------------------------------------------------- - public override string AllowableFiles + public override void Commit() { - get - { - return "*dataprovider, sql"; - } + base.Commit(); } - - #endregion - #region Private Methods - - private bool ExecuteSql(InstallFile scriptFile) + /// ----------------------------------------------------------------------------- + /// + /// The Install method installs the script component. + /// + /// ----------------------------------------------------------------------------- + public override void Install() { - bool bSuccess = true; - - Log.AddInfo(string.Format(Util.SQL_BeginFile, scriptFile.Name)); - - //read script file for installation - string strScript = FileSystemUtils.ReadFile(PhysicalBasePath + scriptFile.FullName); - - //This check needs to be included because the unicode Byte Order mark results in an extra character at the start of the file - //The extra character - '?' - causes an error with the database. - if (strScript.StartsWith("?")) - { - strScript = strScript.Substring(1); - } - string strSQLExceptions = DataProvider.Instance().ExecuteScript(strScript); - if (!String.IsNullOrEmpty(strSQLExceptions)) + this.Log.AddInfo(Util.SQL_Begin); + try { - if (Package.InstallerInfo.IsLegacyMode) + bool bSuccess = true; + Version installedVersion = this.Package.InstalledVersion; + + // First process InstallScript + if (installedVersion == new Version(0, 0, 0)) { - Log.AddWarning(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); + if (this.InstallScript != null) + { + bSuccess = this.InstallScriptFile(this.InstallScript); + installedVersion = this.InstallScript.Version; + } } - else + + // Then process remain Install/Upgrade Scripts + if (bSuccess) { - Log.AddFailure(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); - bSuccess = false; + foreach (InstallFile file in this.InstallScripts.Values) + { + if (file.Version > installedVersion) + { + bSuccess = this.InstallScriptFile(file); + if (!bSuccess) + { + break; + } + } + } } - } - Log.AddInfo(string.Format(Util.SQL_EndFile, scriptFile.Name)); - return bSuccess; - } - private bool IsValidScript(string fileExtension) - { - return ProviderConfiguration.DefaultProvider.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase) || fileExtension.Equals("sql", StringComparison.InvariantCultureIgnoreCase); - } - - #endregion - - #region Protected Methods - - private bool InstallScriptFile(InstallFile scriptFile) - { - //Call base InstallFile method to copy file - bool bSuccess = InstallFile(scriptFile); + // Next process UpgradeScript - this script always runs if present + if (this.UpgradeScript != null) + { + bSuccess = this.InstallScriptFile(this.UpgradeScript); + installedVersion = this.UpgradeScript.Version; + } - //Process the file if it is an Install Script - var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); - if (extension != null) - { - string fileExtension = extension.Substring(1); - if (bSuccess && IsValidScript(fileExtension)) + // Then process uninstallScripts - these need to be copied but not executed + if (bSuccess) { - Log.AddInfo(Util.SQL_Executing + scriptFile.Name); - bSuccess = ExecuteSql(scriptFile); + foreach (InstallFile file in this.UnInstallScripts.Values) + { + bSuccess = this.InstallFile(file); + if (!bSuccess) + { + break; + } + } } + + this.Completed = bSuccess; } - return bSuccess; + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + + this.Log.AddInfo(Util.SQL_End); } /// ----------------------------------------------------------------------------- /// - /// Gets a flag that determines what type of file this installer supports + /// Gets a flag that determines what type of file this installer supports. /// - /// The type of file being processed + /// The type of file being processed. + /// /// ----------------------------------------------------------------------------- protected override bool IsCorrectType(InstallFileType type) { - return (type == InstallFileType.Script); + return type == InstallFileType.Script; } /// ----------------------------------------------------------------------------- /// - /// The ProcessFile method determines what to do with parsed "file" node + /// The ProcessFile method determines what to do with parsed "file" node. /// - /// The file represented by the node - /// The XPathNavigator representing the node + /// The file represented by the node. + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected override void ProcessFile(InstallFile file, XPathNavigator nav) { - string type = nav.GetAttribute("type", ""); - if (file != null && IsCorrectType(file.Type)) + string type = nav.GetAttribute("type", string.Empty); + if (file != null && this.IsCorrectType(file.Type)) { if (file.Name.StartsWith("install.", StringComparison.InvariantCultureIgnoreCase)) { - //This is the initial script when installing - _installScript = file; + // This is the initial script when installing + this._installScript = file; } else if (file.Name.StartsWith("upgrade.", StringComparison.InvariantCultureIgnoreCase)) { - _upgradeScript = file; + this._upgradeScript = file; } else if (type.Equals("install", StringComparison.InvariantCultureIgnoreCase)) { - //These are the Install/Upgrade scripts - InstallScripts[file.Version] = file; + // These are the Install/Upgrade scripts + this.InstallScripts[file.Version] = file; } else { - //These are the Uninstall scripts - UnInstallScripts[file.Version] = file; + // These are the Uninstall scripts + this.UnInstallScripts[file.Version] = file; } } - - //Call base method to set up for file processing + + // Call base method to set up for file processing base.ProcessFile(file, nav); } - - protected override void UnInstallFile(InstallFile scriptFile) + + private bool ExecuteSql(InstallFile scriptFile) { - //Process the file if it is an UnInstall Script - var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); - if (extension != null && (UnInstallScripts.ContainsValue(scriptFile) )) + bool bSuccess = true; + + this.Log.AddInfo(string.Format(Util.SQL_BeginFile, scriptFile.Name)); + + // read script file for installation + string strScript = FileSystemUtils.ReadFile(this.PhysicalBasePath + scriptFile.FullName); + + // This check needs to be included because the unicode Byte Order mark results in an extra character at the start of the file + // The extra character - '?' - causes an error with the database. + if (strScript.StartsWith("?")) { - string fileExtension = extension.Substring(1); - if (scriptFile.Name.StartsWith("uninstall.", StringComparison.InvariantCultureIgnoreCase) && IsValidScript(fileExtension)) + strScript = strScript.Substring(1); + } + + string strSQLExceptions = DataProvider.Instance().ExecuteScript(strScript); + if (!string.IsNullOrEmpty(strSQLExceptions)) + { + if (this.Package.InstallerInfo.IsLegacyMode) { - //Install Script - Log.AddInfo(Util.SQL_Executing + scriptFile.Name); - ExecuteSql(scriptFile); + this.Log.AddWarning(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); + } + else + { + this.Log.AddFailure(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); + bSuccess = false; } } - - //Call base method to delete file - base.UnInstallFile(scriptFile); + + this.Log.AddInfo(string.Format(Util.SQL_EndFile, scriptFile.Name)); + return bSuccess; } - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Files this is not neccessary - /// ----------------------------------------------------------------------------- - public override void Commit() + private bool IsValidScript(string fileExtension) { - base.Commit(); - } - - /// ----------------------------------------------------------------------------- - /// - /// The Install method installs the script component - /// - /// ----------------------------------------------------------------------------- - public override void Install() + return this.ProviderConfiguration.DefaultProvider.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase) || fileExtension.Equals("sql", StringComparison.InvariantCultureIgnoreCase); + } + + private bool InstallScriptFile(InstallFile scriptFile) { - Log.AddInfo(Util.SQL_Begin); - try - { - bool bSuccess = true; - Version installedVersion = Package.InstalledVersion; + // Call base InstallFile method to copy file + bool bSuccess = this.InstallFile(scriptFile); - //First process InstallScript - if (installedVersion == new Version(0, 0, 0)) - { - if (InstallScript != null) - { - bSuccess = InstallScriptFile(InstallScript); - installedVersion = InstallScript.Version; - } - } - - //Then process remain Install/Upgrade Scripts - if (bSuccess) - { - foreach (InstallFile file in InstallScripts.Values) - { - if (file.Version > installedVersion) - { - bSuccess = InstallScriptFile(file); - if (!bSuccess) - { - break; - } - } - } - } - - //Next process UpgradeScript - this script always runs if present - if (UpgradeScript != null) - { - bSuccess = InstallScriptFile(UpgradeScript); - installedVersion = UpgradeScript.Version; - } - - //Then process uninstallScripts - these need to be copied but not executed - if (bSuccess) + // Process the file if it is an Install Script + var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); + if (extension != null) + { + string fileExtension = extension.Substring(1); + if (bSuccess && this.IsValidScript(fileExtension)) { - foreach (InstallFile file in UnInstallScripts.Values) - { - bSuccess = InstallFile(file); - if (!bSuccess) - { - break; - } - } + this.Log.AddInfo(Util.SQL_Executing + scriptFile.Name); + bSuccess = this.ExecuteSql(scriptFile); } - Completed = bSuccess; } - catch (Exception ex) + + return bSuccess; + } + + protected override void UnInstallFile(InstallFile scriptFile) + { + // Process the file if it is an UnInstall Script + var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); + if (extension != null && this.UnInstallScripts.ContainsValue(scriptFile)) { - Log.AddFailure(ex); + string fileExtension = extension.Substring(1); + if (scriptFile.Name.StartsWith("uninstall.", StringComparison.InvariantCultureIgnoreCase) && this.IsValidScript(fileExtension)) + { + // Install Script + this.Log.AddInfo(Util.SQL_Executing + scriptFile.Name); + this.ExecuteSql(scriptFile); + } } - Log.AddInfo(Util.SQL_End); - } + + // Call base method to delete file + base.UnInstallFile(scriptFile); + } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the script component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the script component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() @@ -373,19 +352,17 @@ public override void Rollback() /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the script component + /// The UnInstall method uninstalls the script component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - Log.AddInfo(Util.SQL_BeginUnInstall); + this.Log.AddInfo(Util.SQL_BeginUnInstall); - //Call the base method + // Call the base method base.UnInstall(); - Log.AddInfo(Util.SQL_EndUnInstall); - } - - #endregion + this.Log.AddInfo(Util.SQL_EndUnInstall); + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs index 09d1e0df7f1..06e42d33362 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs @@ -1,44 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.IO; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// - /// The SkinControlInstaller installs SkinControl (SkinObject) Components to a DotNetNuke site + /// The SkinControlInstaller installs SkinControl (SkinObject) Components to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class SkinControlInstaller : ComponentInstallerBase - { - #region "Private Properties" - + { private SkinControlInfo InstalledSkinControl; - private SkinControlInfo SkinControl; - - #endregion - - #region "Public Properties" - - + private SkinControlInfo SkinControl; + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public override string AllowableFiles { @@ -46,78 +34,71 @@ public override string AllowableFiles { return "ascx, vb, cs, js, resx, xml, vbproj, csproj, sln"; } + } + + /// ----------------------------------------------------------------------------- + /// + /// The Commit method finalises the Install and commits any pending changes. + /// + /// In the case of Modules this is not neccessary. + /// ----------------------------------------------------------------------------- + public override void Commit() + { } - - #endregion - - #region "Private Methods" /// ----------------------------------------------------------------------------- /// - /// The DeleteSkinControl method deletes the SkinControl from the data Store. + /// The Install method installs the Module component. /// /// ----------------------------------------------------------------------------- - private void DeleteSkinControl() + public override void Install() { try { - //Attempt to get the SkinControl - SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(Package.PackageID); - if (skinControl != null) + // Attempt to get the SkinControl + this.InstalledSkinControl = SkinControlController.GetSkinControlByKey(this.SkinControl.ControlKey); + + if (this.InstalledSkinControl != null) { - SkinControlController.DeleteSkinControl(skinControl); + this.SkinControl.SkinControlID = this.InstalledSkinControl.SkinControlID; } - Log.AddInfo(string.Format(Util.MODULE_UnRegistered, skinControl.ControlKey)); + + // Save SkinControl + this.SkinControl.PackageID = this.Package.PackageID; + this.SkinControl.SkinControlID = SkinControlController.SaveSkinControl(this.SkinControl); + + this.Completed = true; + this.Log.AddInfo(string.Format(Util.MODULE_Registered, this.SkinControl.ControlKey)); } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } } - - #endregion - - #region "Public Methods" - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Modules this is not neccessary - /// ----------------------------------------------------------------------------- - public override void Commit() - { - } - + /// ----------------------------------------------------------------------------- /// - /// The Install method installs the Module component + /// The DeleteSkinControl method deletes the SkinControl from the data Store. /// /// ----------------------------------------------------------------------------- - public override void Install() + private void DeleteSkinControl() { try { - //Attempt to get the SkinControl - InstalledSkinControl = SkinControlController.GetSkinControlByKey(SkinControl.ControlKey); - - if (InstalledSkinControl != null) + // Attempt to get the SkinControl + SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(this.Package.PackageID); + if (skinControl != null) { - SkinControl.SkinControlID = InstalledSkinControl.SkinControlID; + SkinControlController.DeleteSkinControl(skinControl); } - - //Save SkinControl - SkinControl.PackageID = Package.PackageID; - SkinControl.SkinControlID = SkinControlController.SaveSkinControl(SkinControl); - - Completed = true; - Log.AddInfo(string.Format(Util.MODULE_Registered, SkinControl.ControlKey)); + + this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, skinControl.ControlKey)); } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } - } + } /// ----------------------------------------------------------------------------- /// @@ -126,46 +107,44 @@ public override void Install() /// ----------------------------------------------------------------------------- public override void ReadManifest(XPathNavigator manifestNav) { - //Load the SkinControl from the manifest - SkinControl = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); + // Load the SkinControl from the manifest + this.SkinControl = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); - if (Log.Valid) + if (this.Log.Valid) { - Log.AddInfo(Util.MODULE_ReadSuccess); + this.Log.AddInfo(Util.MODULE_ReadSuccess); } } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() { - //If Temp SkinControl exists then we need to update the DataStore with this - if (InstalledSkinControl == null) + // If Temp SkinControl exists then we need to update the DataStore with this + if (this.InstalledSkinControl == null) { - //No Temp SkinControl - Delete newly added SkinControl - DeleteSkinControl(); + // No Temp SkinControl - Delete newly added SkinControl + this.DeleteSkinControl(); } else { - //Temp SkinControl - Rollback to Temp - SkinControlController.SaveSkinControl(InstalledSkinControl); + // Temp SkinControl - Rollback to Temp + SkinControlController.SaveSkinControl(this.InstalledSkinControl); } } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the SkinControl component + /// The UnInstall method uninstalls the SkinControl component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - DeleteSkinControl(); - } - - #endregion + this.DeleteSkinControl(); + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs index 127fc5a23e8..a0fd91b89ab 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs @@ -1,49 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System; + using System.Collections; + using System.IO; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.UI.Skins; + /// ----------------------------------------------------------------------------- /// - /// The SkinInstaller installs Skin Components to a DotNetNuke site + /// The SkinInstaller installs Skin Components to a DotNetNuke site. /// /// /// /// ----------------------------------------------------------------------------- public class SkinInstaller : FileInstaller - { - #region "Private Members" - + { private readonly ArrayList _SkinFiles = new ArrayList(); private SkinPackageInfo SkinPackage; private SkinPackageInfo TempSkinPackage; - private string _SkinName = Null.NullString; - - #endregion - - #region "Protected Properties" - + private string _SkinName = Null.NullString; + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("skinFiles") + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. + /// ----------------------------------------------------------------------------- + public override string AllowableFiles + { + get + { + return "ascx, html, htm, css, xml, js, resx, jpg, jpeg, gif, png"; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the name of the Collection Node ("skinFiles"). + /// + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -55,9 +58,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("skinFile") + /// Gets the name of the Item Node ("skinFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -69,35 +72,36 @@ protected override string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the PhysicalBasePath for the skin files + /// Gets the PhysicalBasePath for the skin files. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string PhysicalBasePath { get { - string _PhysicalBasePath = RootPath + SkinRoot + "\\" + SkinPackage.SkinName; + string _PhysicalBasePath = this.RootPath + this.SkinRoot + "\\" + this.SkinPackage.SkinName; if (!_PhysicalBasePath.EndsWith("\\")) { _PhysicalBasePath += "\\"; } + return _PhysicalBasePath.Replace("/", "\\"); } } /// ----------------------------------------------------------------------------- /// - /// Gets the root folder for the Skin + /// Gets the root folder for the Skin. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected string RootPath { get { string _RootPath = Null.NullString; - if (Package.InstallerInfo.PortalID == Null.NullInteger && Package.PortalID == Null.NullInteger) + if (this.Package.InstallerInfo.PortalID == Null.NullInteger && this.Package.PortalID == Null.NullInteger) { _RootPath = Globals.HostMapPath; } @@ -105,29 +109,30 @@ protected string RootPath { _RootPath = PortalController.Instance.GetCurrentPortalSettings().HomeSystemDirectoryMapPath; } + return _RootPath; } } /// ----------------------------------------------------------------------------- /// - /// Gets the collection of Skin Files + /// Gets the collection of Skin Files. /// - /// A List(Of InstallFile) + /// A List(Of InstallFile). /// ----------------------------------------------------------------------------- protected ArrayList SkinFiles { get { - return _SkinFiles; + return this._SkinFiles; } } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the SkinName Node ("skinName") + /// Gets the name of the SkinName Node ("skinName"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string SkinNameNodeName { @@ -139,9 +144,9 @@ protected virtual string SkinNameNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the RootName of the Skin + /// Gets the RootName of the Skin. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string SkinRoot { @@ -153,9 +158,9 @@ protected virtual string SkinRoot /// ----------------------------------------------------------------------------- /// - /// Gets the Type of the Skin + /// Gets the Type of the Skin. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string SkinType { @@ -163,64 +168,127 @@ protected virtual string SkinType { return "Skin"; } - } - - #endregion - - #region "Public Properties" - + } + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// The Install method installs the skin component. /// - /// A String - /// ----------------------------------------------------------------------------- - public override string AllowableFiles + public override void Install() { - get + bool bAdd = Null.NullBoolean; + try { - return "ascx, html, htm, css, xml, js, resx, jpg, jpeg, gif, png"; + // Attempt to get the Skin Package + this.TempSkinPackage = SkinController.GetSkinPackage(this.SkinPackage.PortalID, this.SkinPackage.SkinName, this.SkinType); + if (this.TempSkinPackage == null) + { + bAdd = true; + this.SkinPackage.PackageID = this.Package.PackageID; + } + else + { + this.SkinPackage.SkinPackageID = this.TempSkinPackage.SkinPackageID; + if (this.TempSkinPackage.PackageID != this.Package.PackageID) + { + this.Completed = false; + this.Log.AddFailure(Util.SKIN_Installed); + return; + } + else + { + this.SkinPackage.PackageID = this.TempSkinPackage.PackageID; + } + } + + this.SkinPackage.SkinType = this.SkinType; + if (bAdd) + { + // Add new skin package + this.SkinPackage.SkinPackageID = SkinController.AddSkinPackage(this.SkinPackage); + } + else + { + // Update skin package + SkinController.UpdateSkinPackage(this.SkinPackage); + } + + this.Log.AddInfo(string.Format(Util.SKIN_Registered, this.SkinPackage.SkinName)); + + // install (copy the files) by calling the base class + base.Install(); + + // process the list of skin files + if (this.SkinFiles.Count > 0) + { + this.Log.StartJob(Util.SKIN_BeginProcessing); + string strMessage = Null.NullString; + var NewSkin = new SkinFileProcessor(this.RootPath, this.SkinRoot, this.SkinPackage.SkinName); + foreach (string skinFile in this.SkinFiles) + { + strMessage += NewSkin.ProcessFile(skinFile, SkinParser.Portable); + skinFile.Replace(Globals.HostMapPath + "\\", "[G]"); + switch (Path.GetExtension(skinFile)) + { + case ".htm": + SkinController.AddSkin(this.SkinPackage.SkinPackageID, skinFile.Replace("htm", "ascx")); + break; + case ".html": + SkinController.AddSkin(this.SkinPackage.SkinPackageID, skinFile.Replace("html", "ascx")); + break; + case ".ascx": + SkinController.AddSkin(this.SkinPackage.SkinPackageID, skinFile); + break; + } + } + + Array arrMessage = strMessage.Split(new[] { "
    " }, StringSplitOptions.None); + foreach (string strRow in arrMessage) + { + this.Log.AddInfo(HtmlUtils.StripTags(strRow, true)); + } + + this.Log.EndJob(Util.SKIN_EndProcessing); + } + + this.Completed = true; + } + catch (Exception ex) + { + this.Log.AddFailure(ex); } } - - #endregion - - #region "Private Methods" /// ----------------------------------------------------------------------------- /// - /// The DeleteSkinPackage method deletes the Skin Package - /// from the data Store. + /// The Rollback method undoes the installation of the component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- - private void DeleteSkinPackage() + public override void Rollback() { - try + // If Temp Skin exists then we need to update the DataStore with this + if (this.TempSkinPackage == null) { - //Attempt to get the Authentication Service - SkinPackageInfo skinPackage = SkinController.GetSkinByPackageID(Package.PackageID); - if (skinPackage != null) - { - SkinController.DeleteSkinPackage(skinPackage); - } - Log.AddInfo(string.Format(Util.SKIN_UnRegistered, skinPackage.SkinName)); + // No Temp Skin - Delete newly added Skin + this.DeleteSkinPackage(); } - catch (Exception ex) + else { - Log.AddFailure(ex); + // Temp Skin - Rollback to Temp + SkinController.UpdateSkinPackage(this.TempSkinPackage); } - } - - #endregion - - #region "Protected Methods" + // Call base class to prcoess files + base.Rollback(); + } + /// ----------------------------------------------------------------------------- /// - /// The ProcessFile method determines what to do with parsed "file" node + /// The ProcessFile method determines what to do with parsed "file" node. /// - /// The file represented by the node - /// The XPathNavigator representing the node + /// The file represented by the node. + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected override void ProcessFile(InstallFile file, XPathNavigator nav) { @@ -232,178 +300,90 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) case "css": if (file.Path.IndexOf(Globals.glbAboutPage, StringComparison.InvariantCultureIgnoreCase) < 0) { - SkinFiles.Add(PhysicalBasePath + file.FullName); + this.SkinFiles.Add(this.PhysicalBasePath + file.FullName); } + break; } - - //Call base method to set up for file processing - base.ProcessFile(file, nav); + + // Call base method to set up for file processing + base.ProcessFile(file, nav); } /// ----------------------------------------------------------------------------- /// - /// The ReadCustomManifest method reads the custom manifest items + /// The ReadCustomManifest method reads the custom manifest items. /// - /// The XPathNavigator representing the node + /// The XPathNavigator representing the node. /// ----------------------------------------------------------------------------- protected override void ReadCustomManifest(XPathNavigator nav) { - SkinPackage = new SkinPackageInfo(); - SkinPackage.PortalID = Package.PortalID; + this.SkinPackage = new SkinPackageInfo(); + this.SkinPackage.PortalID = this.Package.PortalID; - //Get the Skin name - SkinPackage.SkinName = Util.ReadElement(nav, SkinNameNodeName); + // Get the Skin name + this.SkinPackage.SkinName = Util.ReadElement(nav, this.SkinNameNodeName); - //Call base class + // Call base class base.ReadCustomManifest(nav); } - + /// ----------------------------------------------------------------------------- /// - /// The UnInstallFile method unInstalls a single file. + /// The DeleteSkinPackage method deletes the Skin Package + /// from the data Store. /// - /// The InstallFile to unInstall. /// ----------------------------------------------------------------------------- - protected override void UnInstallFile(InstallFile unInstallFile) - { - //Uninstall file - base.UnInstallFile(unInstallFile); - - if (unInstallFile.Extension == "htm" || unInstallFile.Extension == "html") - { - //Try to remove "processed file" - string fileName = unInstallFile.FullName; - fileName = fileName.Replace(Path.GetExtension(fileName), ".ascx"); - Util.DeleteFile(fileName, PhysicalBasePath, Log); - } - } - - #endregion - - #region "Public Methods" - - /// ----------------------------------------------------------------------------- - /// - /// The Install method installs the skin component - /// - public override void Install() + private void DeleteSkinPackage() { - bool bAdd = Null.NullBoolean; try { - //Attempt to get the Skin Package - TempSkinPackage = SkinController.GetSkinPackage(SkinPackage.PortalID, SkinPackage.SkinName, SkinType); - if (TempSkinPackage == null) - { - bAdd = true; - SkinPackage.PackageID = Package.PackageID; - } - else - { - SkinPackage.SkinPackageID = TempSkinPackage.SkinPackageID; - if (TempSkinPackage.PackageID != Package.PackageID) - { - Completed = false; - Log.AddFailure(Util.SKIN_Installed); - return; - } - else - { - SkinPackage.PackageID = TempSkinPackage.PackageID; - } - } - SkinPackage.SkinType = SkinType; - if (bAdd) - { - //Add new skin package - SkinPackage.SkinPackageID = SkinController.AddSkinPackage(SkinPackage); - } - else - { - //Update skin package - SkinController.UpdateSkinPackage(SkinPackage); - } - Log.AddInfo(string.Format(Util.SKIN_Registered, SkinPackage.SkinName)); - - //install (copy the files) by calling the base class - base.Install(); - - //process the list of skin files - if (SkinFiles.Count > 0) + // Attempt to get the Authentication Service + SkinPackageInfo skinPackage = SkinController.GetSkinByPackageID(this.Package.PackageID); + if (skinPackage != null) { - Log.StartJob(Util.SKIN_BeginProcessing); - string strMessage = Null.NullString; - var NewSkin = new SkinFileProcessor(RootPath, SkinRoot, SkinPackage.SkinName); - foreach (string skinFile in SkinFiles) - { - strMessage += NewSkin.ProcessFile(skinFile, SkinParser.Portable); - skinFile.Replace(Globals.HostMapPath + "\\", "[G]"); - switch (Path.GetExtension(skinFile)) - { - case ".htm": - SkinController.AddSkin(SkinPackage.SkinPackageID, skinFile.Replace("htm", "ascx")); - break; - case ".html": - SkinController.AddSkin(SkinPackage.SkinPackageID, skinFile.Replace("html", "ascx")); - break; - case ".ascx": - SkinController.AddSkin(SkinPackage.SkinPackageID, skinFile); - break; - } - } - Array arrMessage = strMessage.Split(new[] {"
    "}, StringSplitOptions.None); - foreach (string strRow in arrMessage) - { - Log.AddInfo(HtmlUtils.StripTags(strRow, true)); - } - Log.EndJob(Util.SKIN_EndProcessing); + SkinController.DeleteSkinPackage(skinPackage); } - Completed = true; + + this.Log.AddInfo(string.Format(Util.SKIN_UnRegistered, skinPackage.SkinName)); } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); } - } + } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the component in the event - /// that one of the other components fails + /// The UnInstallFile method unInstalls a single file. /// + /// The InstallFile to unInstall. /// ----------------------------------------------------------------------------- - public override void Rollback() + protected override void UnInstallFile(InstallFile unInstallFile) { - //If Temp Skin exists then we need to update the DataStore with this - if (TempSkinPackage == null) - { - //No Temp Skin - Delete newly added Skin - DeleteSkinPackage(); - } - else + // Uninstall file + base.UnInstallFile(unInstallFile); + + if (unInstallFile.Extension == "htm" || unInstallFile.Extension == "html") { - //Temp Skin - Rollback to Temp - SkinController.UpdateSkinPackage(TempSkinPackage); + // Try to remove "processed file" + string fileName = unInstallFile.FullName; + fileName = fileName.Replace(Path.GetExtension(fileName), ".ascx"); + Util.DeleteFile(fileName, this.PhysicalBasePath, this.Log); } - - //Call base class to prcoess files - base.Rollback(); - } + } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the skin component + /// The UnInstall method uninstalls the skin component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - DeleteSkinPackage(); + this.DeleteSkinPackage(); - //Call base class to prcoess files + // Call base class to prcoess files base.UnInstall(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs index f292f3018ad..835ca0d4442 100644 --- a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs @@ -1,30 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Urls; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { - class UrlProviderInstaller : ComponentInstallerBase + using System; + using System.Linq; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Urls; + + internal class UrlProviderInstaller : ComponentInstallerBase { private ExtensionUrlProviderInfo _extensionUrlProvider; private ExtensionUrlProviderInfo _installedExtensionUrlProvider; private string _desktopModuleName; - #region "Public Properties" - /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. public override string AllowableFiles { get @@ -33,29 +31,6 @@ public override string AllowableFiles } } - #endregion - - - private void DeleteProvider() - { - try - { - ExtensionUrlProviderInfo tempUrlProvider = ExtensionUrlProviderController.GetProviders(Null.NullInteger).Where(p => p.ProviderName == _extensionUrlProvider.ProviderName && p.ProviderType == _extensionUrlProvider.ProviderType).FirstOrDefault(); - if (tempUrlProvider != null) - { - ExtensionUrlProviderController.DeleteProvider(tempUrlProvider); - - Log.AddInfo(string.Format(Util.URLPROVIDER_UnRegistered, tempUrlProvider.ProviderName)); - } - } - catch (Exception ex) - { - Log.AddFailure(ex); - } - } - - #region Public Methods - /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -67,39 +42,57 @@ public override void Commit() /// ----------------------------------------------------------------------------- /// - /// The Install method installs the UrlProvider component + /// The Install method installs the UrlProvider component. /// /// ----------------------------------------------------------------------------- public override void Install() { try { - //Ensure DesktopModule Cache is cleared - DataCache.RemoveCache(String.Format(DataCache.DesktopModuleCacheKey, Null.NullInteger)); + // Ensure DesktopModule Cache is cleared + DataCache.RemoveCache(string.Format(DataCache.DesktopModuleCacheKey, Null.NullInteger)); - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(_desktopModuleName, Null.NullInteger); + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(this._desktopModuleName, Null.NullInteger); if (desktopModule != null) { - _extensionUrlProvider.DesktopModuleId = desktopModule.DesktopModuleID; + this._extensionUrlProvider.DesktopModuleId = desktopModule.DesktopModuleID; } - //Attempt to get the Desktop Module - _installedExtensionUrlProvider = ExtensionUrlProviderController.GetProviders(Null.NullInteger) - .SingleOrDefault(p => p.ProviderType == _extensionUrlProvider.ProviderType); + // Attempt to get the Desktop Module + this._installedExtensionUrlProvider = ExtensionUrlProviderController.GetProviders(Null.NullInteger) + .SingleOrDefault(p => p.ProviderType == this._extensionUrlProvider.ProviderType); - if (_installedExtensionUrlProvider != null) + if (this._installedExtensionUrlProvider != null) { - _extensionUrlProvider.ExtensionUrlProviderId = _installedExtensionUrlProvider.ExtensionUrlProviderId; + this._extensionUrlProvider.ExtensionUrlProviderId = this._installedExtensionUrlProvider.ExtensionUrlProviderId; } - ExtensionUrlProviderController.SaveProvider(_extensionUrlProvider); + ExtensionUrlProviderController.SaveProvider(this._extensionUrlProvider); - Completed = true; - Log.AddInfo(string.Format(Util.URLPROVIDER_Registered, _extensionUrlProvider.ProviderName)); + this.Completed = true; + this.Log.AddInfo(string.Format(Util.URLPROVIDER_Registered, this._extensionUrlProvider.ProviderName)); } catch (Exception ex) { - Log.AddFailure(ex); + this.Log.AddFailure(ex); + } + } + + private void DeleteProvider() + { + try + { + ExtensionUrlProviderInfo tempUrlProvider = ExtensionUrlProviderController.GetProviders(Null.NullInteger).Where(p => p.ProviderName == this._extensionUrlProvider.ProviderName && p.ProviderType == this._extensionUrlProvider.ProviderType).FirstOrDefault(); + if (tempUrlProvider != null) + { + ExtensionUrlProviderController.DeleteProvider(tempUrlProvider); + + this.Log.AddInfo(string.Format(Util.URLPROVIDER_UnRegistered, tempUrlProvider.ProviderName)); + } + } + catch (Exception ex) + { + this.Log.AddFailure(ex); } } @@ -110,55 +103,53 @@ public override void Install() /// ----------------------------------------------------------------------------- public override void ReadManifest(XPathNavigator manifestNav) { - _extensionUrlProvider = new ExtensionUrlProviderInfo - { - ProviderName = Util.ReadElement(manifestNav, "urlProvider/name", Log, Util.URLPROVIDER_NameMissing), - ProviderType = Util.ReadElement(manifestNav, "urlProvider/type", Log, Util.URLPROVIDER_TypeMissing), - SettingsControlSrc = Util.ReadElement(manifestNav, "urlProvider/settingsControlSrc"), - IsActive = true, - RedirectAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/redirectAllUrls", "false")), - ReplaceAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/replaceAllUrls", "false")), - RewriteAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/rewriteAllUrls", "false")) - }; - - _desktopModuleName = Util.ReadElement(manifestNav, "urlProvider/desktopModule"); - if (Log.Valid) + this._extensionUrlProvider = new ExtensionUrlProviderInfo { - Log.AddInfo(Util.URLPROVIDER_ReadSuccess); + ProviderName = Util.ReadElement(manifestNav, "urlProvider/name", this.Log, Util.URLPROVIDER_NameMissing), + ProviderType = Util.ReadElement(manifestNav, "urlProvider/type", this.Log, Util.URLPROVIDER_TypeMissing), + SettingsControlSrc = Util.ReadElement(manifestNav, "urlProvider/settingsControlSrc"), + IsActive = true, + RedirectAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/redirectAllUrls", "false")), + ReplaceAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/replaceAllUrls", "false")), + RewriteAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/rewriteAllUrls", "false")), + }; + + this._desktopModuleName = Util.ReadElement(manifestNav, "urlProvider/desktopModule"); + if (this.Log.Valid) + { + this.Log.AddInfo(Util.URLPROVIDER_ReadSuccess); } } /// ----------------------------------------------------------------------------- /// - /// The Rollback method undoes the installation of the component in the event - /// that one of the other components fails + /// The Rollback method undoes the installation of the component in the event + /// that one of the other components fails. /// /// ----------------------------------------------------------------------------- public override void Rollback() { - //If Temp Provider exists then we need to update the DataStore with this - if (_installedExtensionUrlProvider == null) + // If Temp Provider exists then we need to update the DataStore with this + if (this._installedExtensionUrlProvider == null) { - //No Temp Provider - Delete newly added module - DeleteProvider(); + // No Temp Provider - Delete newly added module + this.DeleteProvider(); } else { - //Temp Provider - Rollback to Temp - ExtensionUrlProviderController.SaveProvider(_installedExtensionUrlProvider); + // Temp Provider - Rollback to Temp + ExtensionUrlProviderController.SaveProvider(this._installedExtensionUrlProvider); } } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the component + /// The UnInstall method uninstalls the component. /// /// ----------------------------------------------------------------------------- public override void UnInstall() { - DeleteProvider(); + this.DeleteProvider(); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs index 459881c18e8..de509d94889 100644 --- a/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; - -using DotNetNuke.Common; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Installers { + using System.IO; + + using DotNetNuke.Common; + /// ----------------------------------------------------------------------------- /// - /// The WidgetInstaller installs Widget Components to a DotNetNuke site + /// The WidgetInstaller installs Widget Components to a DotNetNuke site. /// /// /// @@ -23,58 +18,58 @@ public class WidgetInstaller : FileInstaller { /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("widgetFiles") + /// Gets a list of allowable file extensions (in addition to the Host's List). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - protected override string CollectionNodeName + public override string AllowableFiles { get { - return "widgetFiles"; + return "js"; } } - + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("widgetFiles") + /// Gets the name of the Collection Node ("widgetFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - protected override string ItemNodeName + protected override string CollectionNodeName { get { - return "widgetFile"; + return "widgetFiles"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the PhysicalBasePath for the widget files + /// Gets the name of the Item Node ("widgetFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - protected override string PhysicalBasePath + protected override string ItemNodeName { get { - string widgetPath = Path.Combine("Resources\\Widgets\\User", BasePath); - return Path.Combine(Globals.ApplicationMapPath, widgetPath); + return "widgetFile"; } } /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List) + /// Gets the PhysicalBasePath for the widget files. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- - public override string AllowableFiles + protected override string PhysicalBasePath { get { - return "js"; + string widgetPath = Path.Combine("Resources\\Widgets\\User", this.BasePath); + return Path.Combine(Globals.ApplicationMapPath, widgetPath); } } } diff --git a/DNN Platform/Library/Services/Installer/LegacyUtil.cs b/DNN Platform/Library/Services/Installer/LegacyUtil.cs index 9233a91d14e..02e5d346115 100644 --- a/DNN Platform/Library/Services/Installer/LegacyUtil.cs +++ b/DNN Platform/Library/Services/Installer/LegacyUtil.cs @@ -1,41 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Installer.Writers; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { + using System; + using System.IO; + using System.Text; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Installer.Writers; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins; + /// ----------------------------------------------------------------------------- /// /// The LegacyUtil class is a Utility class that provides helper methods to transfer - /// legacy packages to Cambrian's Universal Installer based system + /// legacy packages to Cambrian's Universal Installer based system. /// /// /// /// ----------------------------------------------------------------------------- public class LegacyUtil { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (LegacyUtil)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LegacyUtil)); private static string AdminModules = "Adsense, MarketShare, Authentication, Banners, FeedExplorer, FileManager, HostSettings, Lists, LogViewer, Newsletters, PortalAliases, Portals, RecycleBin, Scheduler, SearchAdmin, SearchInput, SearchResults, Security, SiteLog, SiteWizard, SQL, Tabs, Vendors,"; @@ -47,114 +42,21 @@ public class LegacyUtil private static string KnownSkins = "DNN-Blue, DNN-Gray, MinimalExtropy,"; - private static PackageInfo CreateSkinPackage(SkinPackageInfo skin) - { - //Create a Package - var package = new PackageInfo(new InstallerInfo()); - package.Name = skin.SkinName; - package.FriendlyName = skin.SkinName; - package.Description = Null.NullString; - package.Version = new Version(1, 0, 0); - package.PackageType = skin.SkinType; - package.License = Util.PACKAGE_NoLicense; - - //See if the Skin is using a Namespace (or is a known skin) - ParsePackageName(package); - - return package; - } - - private static void CreateSkinManifest(XmlWriter writer, string skinFolder, string skinType, string tempInstallFolder, string subFolder) - { - string skinName = Path.GetFileNameWithoutExtension(skinFolder); - var skin = new SkinPackageInfo(); - skin.SkinName = skinName; - skin.SkinType = skinType; - - //Create a Package - PackageInfo package = CreateSkinPackage(skin); - - //Create a SkinPackageWriter - var skinWriter = new SkinPackageWriter(skin, package, tempInstallFolder, subFolder); - skinWriter.GetFiles(false); - - //We need to reset the BasePath so it using the correct basePath rather than the Temp InstallFolder - skinWriter.SetBasePath(); - - //Writer package manifest fragment to writer - skinWriter.WriteManifest(writer, true); - } - - private static void ProcessLegacySkin(string skinFolder, string skinType) - { - string skinName = Path.GetFileName(skinFolder); - if (skinName != "_default") - { - var skin = new SkinPackageInfo(); - skin.SkinName = skinName; - skin.SkinType = skinType; - - //Create a Package - PackageInfo package = CreateSkinPackage(skin); - - //Create a SkinPackageWriter - var skinWriter = new SkinPackageWriter(skin, package); - skinWriter.GetFiles(false); - - //Save the manifest - package.Manifest = skinWriter.WriteManifest(true); - - //Save Package - PackageController.Instance.SaveExtensionPackage(package); - - //Update Skin Package with new PackageID - skin.PackageID = package.PackageID; - - //Save Skin Package - skin.SkinPackageID = SkinController.AddSkinPackage(skin); - - foreach (InstallFile skinFile in skinWriter.Files.Values) - { - if (skinFile.Type == InstallFileType.Ascx) - { - if (skinType == "Skin") - { - SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootSkin, Path.Combine(skin.SkinName, skinFile.FullName))); - } - else - { - SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootContainer, Path.Combine(skin.SkinName, skinFile.FullName))); - } - } - } - } - } - - private static void ParsePackageName(PackageInfo package, string separator) - { - //See if the Module is using a "Namespace" for its name - int ownerIndex = package.Name.IndexOf(separator); - if (ownerIndex > 0) - { - package.Owner = package.Name.Substring(0, ownerIndex); - } - } - public static string CreateSkinManifest(string skinFolder, string skinType, string tempInstallFolder) { - //Test if there are Skins and Containers folders in TempInstallFolder (ie it is a legacy combi package) + // Test if there are Skins and Containers folders in TempInstallFolder (ie it is a legacy combi package) bool isCombi = false; var installFolder = new DirectoryInfo(tempInstallFolder); DirectoryInfo[] subFolders = installFolder.GetDirectories(); if (subFolders.Length > 0) { - if ((subFolders[0].Name.Equals("containers", StringComparison.InvariantCultureIgnoreCase) || subFolders[0].Name.Equals("skins", StringComparison.InvariantCultureIgnoreCase))) + if (subFolders[0].Name.Equals("containers", StringComparison.InvariantCultureIgnoreCase) || subFolders[0].Name.Equals("skins", StringComparison.InvariantCultureIgnoreCase)) { isCombi = true; } } - - //Create a writer to create the processed manifest + + // Create a writer to create the processed manifest var sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) { @@ -163,26 +65,28 @@ public static string CreateSkinManifest(string skinFolder, string skinType, stri { if (Directory.Exists(Path.Combine(tempInstallFolder, "Skins"))) { - //Add Skin Package Fragment - CreateSkinManifest(writer, skinFolder, "Skin", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", ""), "Skins"); + // Add Skin Package Fragment + CreateSkinManifest(writer, skinFolder, "Skin", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Skins"); } + if (Directory.Exists(Path.Combine(tempInstallFolder, "Containers"))) { - //Add Container PAckage Fragment - CreateSkinManifest(writer, skinFolder, "Container", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", ""), "Containers"); + // Add Container PAckage Fragment + CreateSkinManifest(writer, skinFolder, "Container", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Containers"); } } else { - //Add Package Fragment - CreateSkinManifest(writer, skinFolder, skinType, tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", ""), ""); + // Add Package Fragment + CreateSkinManifest(writer, skinFolder, skinType, tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), string.Empty); } + PackageWriterBase.WriteManifestEndElement(writer); - //Close XmlWriter + // Close XmlWriter writer.Close(); - //Return new manifest + // Return new manifest return sb.ToString(); } } @@ -194,11 +98,13 @@ public static void ParsePackageName(PackageInfo package) { ParsePackageName(package, "\\"); } + if (string.IsNullOrEmpty(package.Owner)) { ParsePackageName(package, "_"); } - if (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && AdminModules.Contains(package.Name + ",") || package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && CoreModules.Contains(package.Name + ",") || (package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase)) && KnownSkins.Contains(package.Name + ",") || package.PackageType.Equals("SkinObject", StringComparison.OrdinalIgnoreCase) && KnownSkinObjects.Contains(package.Name + ",")) + + if ((package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && AdminModules.Contains(package.Name + ",")) || (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && CoreModules.Contains(package.Name + ",")) || ((package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase)) && KnownSkins.Contains(package.Name + ",")) || (package.PackageType.Equals("SkinObject", StringComparison.OrdinalIgnoreCase) && KnownSkinObjects.Contains(package.Name + ","))) { if (string.IsNullOrEmpty(package.Owner)) { @@ -221,9 +127,10 @@ public static void ParsePackageName(PackageInfo package) } } } + if (package.Owner == "DotNetNuke" || package.Owner == "DNN") { - package.License = Localization.Localization.GetString("License", Localization.Localization.GlobalResourceFile); + package.License = Localization.GetString("License", Localization.GlobalResourceFile); package.Organization = ".NET Foundation"; package.Url = "https://dnncommunity.org"; package.Email = "info@dnncommunity.org"; @@ -235,29 +142,123 @@ public static void ParsePackageName(PackageInfo package) } } + private static PackageInfo CreateSkinPackage(SkinPackageInfo skin) + { + // Create a Package + var package = new PackageInfo(new InstallerInfo()); + package.Name = skin.SkinName; + package.FriendlyName = skin.SkinName; + package.Description = Null.NullString; + package.Version = new Version(1, 0, 0); + package.PackageType = skin.SkinType; + package.License = Util.PACKAGE_NoLicense; + + // See if the Skin is using a Namespace (or is a known skin) + ParsePackageName(package); + + return package; + } + + private static void CreateSkinManifest(XmlWriter writer, string skinFolder, string skinType, string tempInstallFolder, string subFolder) + { + string skinName = Path.GetFileNameWithoutExtension(skinFolder); + var skin = new SkinPackageInfo(); + skin.SkinName = skinName; + skin.SkinType = skinType; + + // Create a Package + PackageInfo package = CreateSkinPackage(skin); + + // Create a SkinPackageWriter + var skinWriter = new SkinPackageWriter(skin, package, tempInstallFolder, subFolder); + skinWriter.GetFiles(false); + + // We need to reset the BasePath so it using the correct basePath rather than the Temp InstallFolder + skinWriter.SetBasePath(); + + // Writer package manifest fragment to writer + skinWriter.WriteManifest(writer, true); + } + + private static void ProcessLegacySkin(string skinFolder, string skinType) + { + string skinName = Path.GetFileName(skinFolder); + if (skinName != "_default") + { + var skin = new SkinPackageInfo(); + skin.SkinName = skinName; + skin.SkinType = skinType; + + // Create a Package + PackageInfo package = CreateSkinPackage(skin); + + // Create a SkinPackageWriter + var skinWriter = new SkinPackageWriter(skin, package); + skinWriter.GetFiles(false); + + // Save the manifest + package.Manifest = skinWriter.WriteManifest(true); + + // Save Package + PackageController.Instance.SaveExtensionPackage(package); + + // Update Skin Package with new PackageID + skin.PackageID = package.PackageID; + + // Save Skin Package + skin.SkinPackageID = SkinController.AddSkinPackage(skin); + + foreach (InstallFile skinFile in skinWriter.Files.Values) + { + if (skinFile.Type == InstallFileType.Ascx) + { + if (skinType == "Skin") + { + SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootSkin, Path.Combine(skin.SkinName, skinFile.FullName))); + } + else + { + SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootContainer, Path.Combine(skin.SkinName, skinFile.FullName))); + } + } + } + } + } + + private static void ParsePackageName(PackageInfo package, string separator) + { + // See if the Module is using a "Namespace" for its name + int ownerIndex = package.Name.IndexOf(separator); + if (ownerIndex > 0) + { + package.Owner = package.Name.Substring(0, ownerIndex); + } + } + /// - /// Process legacy language package (that is based on manifest xml file) - /// + /// Process legacy language package (that is based on manifest xml file). + /// public static void ProcessLegacyLanguages() { - string filePath = Globals.ApplicationMapPath + Localization.Localization.SupportedLocalesFile.Substring(1).Replace("/", "\\"); + string filePath = Globals.ApplicationMapPath + Localization.SupportedLocalesFile.Substring(1).Replace("/", "\\"); if (File.Exists(filePath)) { var doc = new XPathDocument(filePath); - //Check for Browser and Url settings + // Check for Browser and Url settings XPathNavigator browserNav = doc.CreateNavigator().SelectSingleNode("root/browserDetection"); if (browserNav != null) { HostController.Instance.Update("EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); } + XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("root/languageInUrl"); if (urlNav != null) { HostController.Instance.Update("EnableUrlLanguage", Util.ReadAttribute(urlNav, "enabled", false, null, Null.NullString, "true")); } - - //Process each language + + // Process each language foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/language")) { if (nav.NodeType != XPathNodeType.Comment) @@ -266,69 +267,72 @@ public static void ProcessLegacyLanguages() language.Text = Util.ReadAttribute(nav, "name"); language.Code = Util.ReadAttribute(nav, "key"); language.Fallback = Util.ReadAttribute(nav, "fallback"); - //Save Language - Localization.Localization.SaveLanguage(language); - if (language.Code != Localization.Localization.SystemLocale) + + // Save Language + Localization.SaveLanguage(language); + if (language.Code != Localization.SystemLocale) { - //Create a Package - var package = new PackageInfo(new InstallerInfo()) - { - Name = language.Text, - FriendlyName = language.Text, - Description = Null.NullString, - Version = new Version(1, 0, 0), - PackageType = "CoreLanguagePack", - License = Util.PACKAGE_NoLicense - }; - - //Create a LanguagePackWriter + // Create a Package + var package = new PackageInfo(new InstallerInfo()) + { + Name = language.Text, + FriendlyName = language.Text, + Description = Null.NullString, + Version = new Version(1, 0, 0), + PackageType = "CoreLanguagePack", + License = Util.PACKAGE_NoLicense, + }; + + // Create a LanguagePackWriter var packageWriter = new LanguagePackWriter(language, package); - //Save the manifest + // Save the manifest package.Manifest = packageWriter.WriteManifest(true); - //Save Package + // Save Package PackageController.Instance.SaveExtensionPackage(package); - var languagePack = new LanguagePackInfo - { - LanguageID = language.LanguageId, - PackageID = package.PackageID, - DependentPackageID = -2 - }; + var languagePack = new LanguagePackInfo + { + LanguageID = language.LanguageId, + PackageID = package.PackageID, + DependentPackageID = -2, + }; LanguagePackController.SaveLanguagePack(languagePack); } } } } - - //Process Portal Locales files + + // Process Portal Locales files foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { int portalID = portal.PortalID; - filePath = string.Format(Globals.ApplicationMapPath + Localization.Localization.ApplicationResourceDirectory.Substring(1).Replace("/", "\\") + "\\Locales.Portal-{0}.xml", portalID); + filePath = string.Format(Globals.ApplicationMapPath + Localization.ApplicationResourceDirectory.Substring(1).Replace("/", "\\") + "\\Locales.Portal-{0}.xml", portalID); if (File.Exists(filePath)) { var doc = new XPathDocument(filePath); - //Check for Browser and Url settings + // Check for Browser and Url settings XPathNavigator browserNav = doc.CreateNavigator().SelectSingleNode("locales/browserDetection"); if (browserNav != null) { PortalController.UpdatePortalSetting(portalID, "EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); } + XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("locales/languageInUrl"); if (urlNav != null) { PortalController.UpdatePortalSetting(portalID, "EnableUrlLanguage", Util.ReadAttribute(urlNav, "enabled", false, null, Null.NullString, "true")); } + foreach (Locale installedLanguage in LocaleController.Instance.GetLocales(Null.NullInteger).Values) { string code = installedLanguage.Code; bool bFound = false; - //Check if this language is "inactive" + // Check if this language is "inactive" foreach (XPathNavigator inactiveNav in doc.CreateNavigator().Select("locales/inactive/locale")) { if (inactiveNav.Value == code) @@ -337,10 +341,11 @@ public static void ProcessLegacyLanguages() break; } } + if (!bFound) { - //Language is enabled - add to portal - Localization.Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); + // Language is enabled - add to portal + Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); } } } @@ -348,23 +353,23 @@ public static void ProcessLegacyLanguages() { foreach (Locale installedLanguage in LocaleController.Instance.GetLocales(Null.NullInteger).Values) { - //Language is enabled - add to portal - Localization.Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); + // Language is enabled - add to portal + Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); } } } } /// - /// Process legacy module version 3 .dnn install file + /// Process legacy module version 3 .dnn install file. /// - /// + /// public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) { - //Get the Module folder + // Get the Module folder string moduleFolder = Path.Combine(Globals.ApplicationMapPath, Path.Combine("DesktopModules", desktopModule.FolderName)); - //Find legacy manifest + // Find legacy manifest XPathNavigator rootNav = null; try { @@ -372,12 +377,12 @@ public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) string[] files = Directory.GetFiles(moduleFolder, "*.dnn.config"); if (files.Length > 0) { - //Create an XPathDocument from the Xml + // Create an XPathDocument from the Xml var doc = new XPathDocument(new FileStream(files[0], FileMode.Open, FileAccess.Read)); rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke"); } - //Module is not affiliated with a Package + // Module is not affiliated with a Package var package = new PackageInfo(new InstallerInfo()); package.Name = desktopModule.ModuleName; @@ -388,9 +393,10 @@ public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) { package.Version = new Version(desktopModule.Version); } + if (hostModules.Contains(desktopModule.ModuleName)) { - //Host Module so make this a system package + // Host Module so make this a system package package.IsSystemPackage = true; desktopModule.IsAdmin = true; } @@ -398,9 +404,10 @@ public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) { desktopModule.IsAdmin = false; } + package.PackageType = "Module"; - //See if the Module is using a "Namespace" for its name + // See if the Module is using a "Namespace" for its name ParsePackageName(package); if (files.Length > 0) @@ -410,23 +417,22 @@ public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) } else { - package.Manifest = ""; //module has no manifest + package.Manifest = string.Empty; // module has no manifest } - //Save Package + // Save Package PackageController.Instance.SaveExtensionPackage(package); - //Update Desktop Module with new PackageID + // Update Desktop Module with new PackageID desktopModule.PackageID = package.PackageID; - //Save DesktopModule + // Save DesktopModule DesktopModuleController.SaveDesktopModule(desktopModule, false, false); } catch (Exception exc) { Logger.Error(exc); - - } + } } public static void ProcessLegacyModules() @@ -441,8 +447,8 @@ public static void ProcessLegacyModules() } /// - /// Process legacy skinobject version 3 .dnn install package - /// + /// Process legacy skinobject version 3 .dnn install package. + ///
    public static void ProcessLegacySkinControls() { foreach (SkinControlInfo skinControl in SkinControlController.GetSkinControls().Values) @@ -451,7 +457,7 @@ public static void ProcessLegacySkinControls() { try { - //SkinControl is not affiliated with a Package + // SkinControl is not affiliated with a Package var package = new PackageInfo(new InstallerInfo()); package.Name = skinControl.ControlKey; @@ -460,25 +466,24 @@ public static void ProcessLegacySkinControls() package.Version = new Version(1, 0, 0); package.PackageType = "SkinObject"; - //See if the SkinControl is using a "Namespace" for its name + // See if the SkinControl is using a "Namespace" for its name ParsePackageName(package); var skinControlWriter = new SkinControlPackageWriter(skinControl, package); package.Manifest = skinControlWriter.WriteManifest(true); - //Save Package + // Save Package PackageController.Instance.SaveExtensionPackage(package); - //Update SkinControl with new PackageID + // Update SkinControl with new PackageID skinControl.PackageID = package.PackageID; - //Save SkinControl + // Save SkinControl SkinControlController.SaveSkinControl(skinControl); } catch (Exception exc) { Logger.Error(exc); - } } } @@ -486,14 +491,14 @@ public static void ProcessLegacySkinControls() public static void ProcessLegacySkins() { - //Process Legacy Skins + // Process Legacy Skins string skinRootPath = Path.Combine(Globals.HostMapPath, SkinController.RootSkin); foreach (string skinFolder in Directory.GetDirectories(skinRootPath)) { ProcessLegacySkin(skinFolder, "Skin"); } - - //Process Legacy Containers + + // Process Legacy Containers skinRootPath = Path.Combine(Globals.HostMapPath, SkinController.RootContainer); foreach (string skinFolder in Directory.GetDirectories(skinRootPath)) { diff --git a/DNN Platform/Library/Services/Installer/Log/LogEntry.cs b/DNN Platform/Library/Services/Installer/Log/LogEntry.cs index f4a0ba0145d..856cfbfc060 100644 --- a/DNN Platform/Library/Services/Installer/Log/LogEntry.cs +++ b/DNN Platform/Library/Services/Installer/Log/LogEntry.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Log { + using System; + /// ----------------------------------------------------------------------------- /// - /// The LogEntry class provides a single entry for the Installer Log + /// The LogEntry class provides a single entry for the Installer Log. /// /// /// @@ -20,53 +15,54 @@ namespace DotNetNuke.Services.Installer.Log [Serializable] public class LogEntry { - private readonly string _description; - + private readonly string _description; + /// ----------------------------------------------------------------------------- - /// - /// This Constructor builds a LogEntry from its type and description + /// + /// Initializes a new instance of the class. + /// This Constructor builds a LogEntry from its type and description. /// /// /// - /// The description (detail) of the entry - /// The type of LogEntry + /// The description (detail) of the entry. + /// The type of LogEntry. /// ----------------------------------------------------------------------------- public LogEntry(LogType type, string description) { - Type = type; - _description = description; + this.Type = type; + this._description = description; } /// ----------------------------------------------------------------------------- /// - /// Gets the type of LogEntry + /// Gets the type of LogEntry. /// - /// A LogType + /// A LogType. /// ----------------------------------------------------------------------------- public LogType Type { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the description of LogEntry + /// Gets the description of LogEntry. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Description { get { - if (_description == null) + if (this._description == null) { return "..."; } - - return _description; + + return this._description; } } public override string ToString() { - return string.Format("{0}: {1}", Type, Description); + return string.Format("{0}: {1}", this.Type, this.Description); } } } diff --git a/DNN Platform/Library/Services/Installer/Log/LogType.cs b/DNN Platform/Library/Services/Installer/Log/LogType.cs index ce18a93ced1..7fd4dbc827a 100644 --- a/DNN Platform/Library/Services/Installer/Log/LogType.cs +++ b/DNN Platform/Library/Services/Installer/Log/LogType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Log { public enum LogType @@ -10,6 +10,6 @@ public enum LogType Warning, Failure, StartJob, - EndJob + EndJob, } } diff --git a/DNN Platform/Library/Services/Installer/Log/Logger.cs b/DNN Platform/Library/Services/Installer/Log/Logger.cs index ff811f59a08..bce0591997c 100644 --- a/DNN Platform/Library/Services/Installer/Log/Logger.cs +++ b/DNN Platform/Library/Services/Installer/Log/Logger.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web.UI.HtmlControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Log { + using System; + using System.Collections.Generic; + using System.Web.UI.HtmlControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + /// ----------------------------------------------------------------------------- /// - /// The Logger class provides an Installer Log + /// The Logger class provides an Installer Log. /// /// /// /// ----------------------------------------------------------------------------- public class Logger { - private static readonly ILog DnnLogger = LoggerSource.Instance.GetLogger(typeof (Logger)); + private static readonly ILog DnnLogger = LoggerSource.Instance.GetLogger(typeof(Logger)); private readonly IList _logs; private string _errorClass; private bool _hasWarnings; @@ -34,31 +29,33 @@ public class Logger public Logger() { - _logs = new List(); - - _valid = true; - _hasWarnings = Null.NullBoolean; + this._logs = new List(); + + this._valid = true; + this._hasWarnings = Null.NullBoolean; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Css Class used for Error Log Entries + /// Gets or sets and sets the Css Class used for Error Log Entries. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ErrorClass { get { - if (String.IsNullOrEmpty(_errorClass)) + if (string.IsNullOrEmpty(this._errorClass)) { - _errorClass = "NormalRed"; + this._errorClass = "NormalRed"; } - return _errorClass; + + return this._errorClass; } + set { - _errorClass = value; + this._errorClass = value; } } @@ -66,148 +63,153 @@ public bool HasWarnings { get { - return _hasWarnings; + return this._hasWarnings; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Css Class used for Log Entries that should be highlighted + /// Gets or sets and sets the Css Class used for Log Entries that should be highlighted. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string HighlightClass { get { - if (String.IsNullOrEmpty(_highlightClass)) + if (string.IsNullOrEmpty(this._highlightClass)) { - _highlightClass = "NormalBold"; + this._highlightClass = "NormalBold"; } - return _highlightClass; + + return this._highlightClass; } + set { - _highlightClass = value; + this._highlightClass = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets a List of Log Entries + /// Gets a List of Log Entries. /// - /// A List of LogEntrys + /// A List of LogEntrys. /// ----------------------------------------------------------------------------- public IList Logs { get { - return _logs; + return this._logs; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Css Class used for normal Log Entries + /// Gets or sets and sets the Css Class used for normal Log Entries. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string NormalClass { get { - if (String.IsNullOrEmpty(_normalClass)) + if (string.IsNullOrEmpty(this._normalClass)) { - _normalClass = "Normal"; + this._normalClass = "Normal"; } - return _normalClass; + + return this._normalClass; } + set { - _normalClass = value; + this._normalClass = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets a Flag that indicates whether the Installation was Valid + /// Gets a value indicating whether gets a Flag that indicates whether the Installation was Valid. /// - /// A List of LogEntrys + /// A List of LogEntrys. /// ----------------------------------------------------------------------------- public bool Valid { get { - return _valid; + return this._valid; } } /// ----------------------------------------------------------------------------- /// - /// The AddFailure method adds a new LogEntry of type Failure to the Logs collection + /// The AddFailure method adds a new LogEntry of type Failure to the Logs collection. /// - /// This method also sets the Valid flag to false - /// The description of the LogEntry + /// This method also sets the Valid flag to false. + /// The description of the LogEntry. /// ----------------------------------------------------------------------------- public void AddFailure(string failure) { - _logs.Add(new LogEntry(LogType.Failure, failure)); + this._logs.Add(new LogEntry(LogType.Failure, failure)); DnnLogger.Error(failure); - _valid = false; + this._valid = false; } public void AddFailure(Exception ex) { - AddFailure((Util.EXCEPTION + ex)); + this.AddFailure(Util.EXCEPTION + ex); Exceptions.Exceptions.LogException(ex); } /// ----------------------------------------------------------------------------- /// - /// The AddInfo method adds a new LogEntry of type Info to the Logs collection + /// The AddInfo method adds a new LogEntry of type Info to the Logs collection. /// - /// The description of the LogEntry + /// The description of the LogEntry. /// ----------------------------------------------------------------------------- public void AddInfo(string info) - { - _logs.Add(new LogEntry(LogType.Info, info)); - DnnLogger.Info(info); + { + this._logs.Add(new LogEntry(LogType.Info, info)); + DnnLogger.Info(info); } /// ----------------------------------------------------------------------------- /// - /// The AddWarning method adds a new LogEntry of type Warning to the Logs collection + /// The AddWarning method adds a new LogEntry of type Warning to the Logs collection. /// - /// The description of the LogEntry + /// The description of the LogEntry. /// ----------------------------------------------------------------------------- public void AddWarning(string warning) { - _logs.Add(new LogEntry(LogType.Warning, warning)); - DnnLogger.Warn(warning); - _hasWarnings = true; + this._logs.Add(new LogEntry(LogType.Warning, warning)); + DnnLogger.Warn(warning); + this._hasWarnings = true; } /// ----------------------------------------------------------------------------- /// - /// The EndJob method adds a new LogEntry of type EndJob to the Logs collection + /// The EndJob method adds a new LogEntry of type EndJob to the Logs collection. /// - /// The description of the LogEntry + /// The description of the LogEntry. /// ----------------------------------------------------------------------------- public void EndJob(string job) { - _logs.Add(new LogEntry(LogType.EndJob, job)); + this._logs.Add(new LogEntry(LogType.EndJob, job)); DnnLogger.Info(job); } /// ----------------------------------------------------------------------------- /// - /// GetLogsTable formats log entries in an HtmlTable - /// + /// GetLogsTable formats log entries in an HtmlTable. + /// + /// /// ----------------------------------------------------------------------------- public HtmlTable GetLogsTable() { var arrayTable = new HtmlTable(); - foreach (LogEntry entry in Logs) + foreach (LogEntry entry in this.Logs) { var tr = new HtmlTableRow(); var tdType = new HtmlTableCell(); @@ -220,44 +222,46 @@ public HtmlTable GetLogsTable() { case LogType.Failure: case LogType.Warning: - tdType.Attributes.Add("class", ErrorClass); - tdDescription.Attributes.Add("class", ErrorClass); + tdType.Attributes.Add("class", this.ErrorClass); + tdDescription.Attributes.Add("class", this.ErrorClass); break; case LogType.StartJob: case LogType.EndJob: - tdType.Attributes.Add("class", HighlightClass); - tdDescription.Attributes.Add("class", HighlightClass); + tdType.Attributes.Add("class", this.HighlightClass); + tdDescription.Attributes.Add("class", this.HighlightClass); break; case LogType.Info: - tdType.Attributes.Add("class", NormalClass); - tdDescription.Attributes.Add("class", NormalClass); + tdType.Attributes.Add("class", this.NormalClass); + tdDescription.Attributes.Add("class", this.NormalClass); break; } + arrayTable.Rows.Add(tr); if (entry.Type == LogType.EndJob) { var spaceTR = new HtmlTableRow(); - spaceTR.Cells.Add(new HtmlTableCell {ColSpan = 2, InnerHtml = " "}); + spaceTR.Cells.Add(new HtmlTableCell { ColSpan = 2, InnerHtml = " " }); arrayTable.Rows.Add(spaceTR); } } + return arrayTable; } public void ResetFlags() { - _valid = true; + this._valid = true; } /// ----------------------------------------------------------------------------- /// - /// The StartJob method adds a new LogEntry of type StartJob to the Logs collection + /// The StartJob method adds a new LogEntry of type StartJob to the Logs collection. /// - /// The description of the LogEntry + /// The description of the LogEntry. /// ----------------------------------------------------------------------------- public void StartJob(string job) { - _logs.Add(new LogEntry(LogType.StartJob, job)); + this._logs.Add(new LogEntry(LogType.StartJob, job)); DnnLogger.Info(job); } } diff --git a/DNN Platform/Library/Services/Installer/NodeInsertType.cs b/DNN Platform/Library/Services/Installer/NodeInsertType.cs index 67cb186278c..6dfa192ea29 100644 --- a/DNN Platform/Library/Services/Installer/NodeInsertType.cs +++ b/DNN Platform/Library/Services/Installer/NodeInsertType.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer { public enum NodeInsertType { Before, - After + After, } } diff --git a/DNN Platform/Library/Services/Installer/Packages/IPackageController.cs b/DNN Platform/Library/Services/Installer/Packages/IPackageController.cs index 6fa7016c1a7..c2194e90153 100644 --- a/DNN Platform/Library/Services/Installer/Packages/IPackageController.cs +++ b/DNN Platform/Library/Services/Installer/Packages/IPackageController.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Packages { + using System; + using System.Collections.Generic; + public interface IPackageController { /// - /// DeleteExtensionPackage is used to remove an Extension Package for the System + /// DeleteExtensionPackage is used to remove an Extension Package for the System. /// - /// The Package you wish to delete + /// The Package you wish to delete. void DeleteExtensionPackage(PackageInfo package); /// @@ -23,8 +23,8 @@ public interface IPackageController /// The main situation where the portal Id will have a specific value is for skins which have /// been installed for a spcific portal/site. /// The "search criteria" to use to identify the extension package to - /// retrieve. In most cases this will be a simple lambda method e.g. p => p.Name == "Name" - /// The extension package + /// retrieve. In most cases this will be a simple lambda method e.g. p => p.Name == "Name". + /// The extension package. PackageInfo GetExtensionPackage(int portalId, Func predicate); /// @@ -35,9 +35,9 @@ public interface IPackageController /// The main situation where the portal Id will have a specific value is for skins which have /// been installed for a spcific portal/site. /// The "search criteria" to use to identify the extension package to - /// retrieve. In most cases this will be a simple lambda method e.g. p => p.Name == "Name" + /// retrieve. In most cases this will be a simple lambda method e.g. p => p.Name == "Name". /// Whether use a copy of the package info object. - /// The extension package + /// The extension package. PackageInfo GetExtensionPackage(int portalId, Func predicate, bool useCopy); /// @@ -47,7 +47,7 @@ public interface IPackageController /// a specific portal so in most situations developers will need to pass -1 to indicate this. /// The main situation where the portal Id will have a specific value is for skins which have /// been installed for a spcific portal/site. - /// A list of extension packages + /// A list of extension packages. IList GetExtensionPackages(int portalId); /// @@ -58,34 +58,34 @@ public interface IPackageController /// The main situation where the portal Id will have a specific value is for skins which have /// been installed for a spcific portal/site. /// The "search criteria" to use to identify the extension packages to - /// retrieve. In most cases this will be a simple lambda method e.g. p => p.PackageType == "Module" - /// A list of extension packages + /// retrieve. In most cases this will be a simple lambda method e.g. p => p.PackageType == "Module". + /// A list of extension packages. IList GetExtensionPackages(int portalId, Func predicate); /// /// SaveExtensionPackage is used to save an Extension Package. /// - /// The Package you wish to save + /// The Package you wish to save. void SaveExtensionPackage(PackageInfo package); /// /// GetExtensionPackage is used to retrieve a specific package type from the data store. /// /// The "search criteria" to use to identify the package type to - /// retrieve. In most cases this will be a simple lambda method e.g. t => t.PackageType == "Modules" - /// A package type + /// retrieve. In most cases this will be a simple lambda method e.g. t => t.PackageType == "Modules". + /// A package type. PackageType GetExtensionPackageType(Func predicate); /// /// GetExtensionPackageTypes is used to retrieve package types from the data store. /// - /// A list of package types + /// A list of package types. IList GetExtensionPackageTypes(); /// - /// Get the dependencies for a package + /// Get the dependencies for a package. /// - /// A List of PackageDependencyInfo objects + /// A List of PackageDependencyInfo objects. IList GetPackageDependencies(Func predicate); } } diff --git a/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs b/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs index f758bfd80c6..a2de0f78afd 100644 --- a/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs +++ b/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Packages { public interface IPackageEditor { int PackageID { get; set; } + bool IsWizard { get; set; } void Initialize(); diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs index 7abeadc4258..3382c575aff 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs @@ -1,90 +1,207 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Installer.Dependencies; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Skins; - -using ICSharpCode.SharpZipLib.Zip; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Packages { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Installer.Dependencies; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.UI.Skins; + using ICSharpCode.SharpZipLib.Zip; + /// ----------------------------------------------------------------------------- /// - /// The PackageController class provides the business class for the packages + /// The PackageController class provides the business class for the packages. /// /// ----------------------------------------------------------------------------- public class PackageController : ServiceLocator, IPackageController - { - #region Private Members + { + private static readonly DataProvider provider = DataProvider.Instance(); + + public static bool CanDeletePackage(PackageInfo package, PortalSettings portalSettings) + { + bool bCanDelete = true; - private static readonly DataProvider provider = DataProvider.Instance(); + var dependencies = Instance.GetPackageDependencies(d => d.PackageName.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && d.Version <= package.Version); + if (dependencies.Count > 0) + { + // There is at least one package dependent on this package. + foreach (var dependency in dependencies) + { + var dep = dependency; - #endregion + // Check if there is an alternative package + var packages = Instance.GetExtensionPackages( + package.PortalID, + p => p.Name.Equals(dep.PackageName, StringComparison.OrdinalIgnoreCase) + && p.Version >= dep.Version + && p.PackageID != package.PackageID); + if (packages.Count == 0) + { + bCanDelete = false; + } + } + } - protected override Func GetFactory() - { - return (() => new PackageController()); + if (bCanDelete) + { + switch (package.PackageType) + { + case "Skin": + case "Container": + // Need to get path of skin being deleted so we can call the public CanDeleteSkin function in the SkinController + string strRootSkin = package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase) ? SkinController.RootSkin : SkinController.RootContainer; + SkinPackageInfo _SkinPackageInfo = SkinController.GetSkinByPackageID(package.PackageID); + string strFolderPath = Path.Combine(_SkinPackageInfo.PortalID == Null.NullInteger ? Path.Combine(Globals.HostMapPath, strRootSkin) : Path.Combine(portalSettings.HomeSystemDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); + + bCanDelete = SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeSystemDirectoryMapPath); + if (_SkinPackageInfo.PortalID != Null.NullInteger) + { + // To be compliant with all versions + strFolderPath = Path.Combine(Path.Combine(portalSettings.HomeDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); + bCanDelete = bCanDelete && SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeDirectoryMapPath); + } + + break; + case "Provider": + // Check if the provider is the default provider + XmlDocument configDoc = Config.Load(); + string providerName = package.Name; + if (providerName.IndexOf(".", StringComparison.Ordinal) > Null.NullInteger) + { + providerName = providerName.Substring(providerName.IndexOf(".", StringComparison.Ordinal) + 1); + } + + switch (providerName) + { + case "SchedulingProvider": + providerName = "DNNScheduler"; + break; + case "SearchIndexProvider": + providerName = "ModuleIndexProvider"; + break; + case "SearchProvider": + providerName = "SearchDataStoreProvider"; + break; + } + + XPathNavigator providerNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/dotnetnuke/*[@defaultProvider='" + providerName + "']"); + bCanDelete = providerNavigator == null; + break; + } + } + + return bCanDelete; } - #region Private Methods + public static IDictionary GetModulePackagesInUse(int portalID, bool forHost) + { + return CBO.FillDictionary("PackageID", provider.GetModulePackagesInUse(portalID, forHost)); + } + + public void DeleteExtensionPackage(PackageInfo package) + { + switch (package.PackageType) + { + case "Auth_System": + AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); + if (authSystem != null) + { + AuthenticationController.DeleteAuthentication(authSystem); + } + + break; + case "CoreLanguagePack": + LanguagePackInfo languagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); + if (languagePack != null) + { + LanguagePackController.DeleteLanguagePack(languagePack); + } + + break; + case "Module": + var controller = new DesktopModuleController(); + DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); + if (desktopModule != null) + { + controller.DeleteDesktopModule(desktopModule); + } + + break; + case "SkinObject": + SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); + if (skinControl != null) + { + SkinControlController.DeleteSkinControl(skinControl); + } + + break; + } + + DeletePackageInternal(package); + } + public PackageInfo GetExtensionPackage(int portalId, Func predicate) + { + return this.GetExtensionPackage(portalId, predicate, false); + } + + protected override Func GetFactory() + { + return () => new PackageController(); + } + private static void AddLog(PackageInfo package, EventLogController.EventLogType logType) { - EventLogController.Instance.AddLog(package, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - "", - logType); - + EventLogController.Instance.AddLog( + package, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + logType); } private static void AddPackageInternal(PackageInfo package) { - package.PackageID = provider.AddPackage(package.PortalID, - package.Name, - package.FriendlyName, - package.Description, - package.PackageType, - package.Version.ToString(3), - package.License, - package.Manifest, - package.Owner, - package.Organization, - package.Url, - package.Email, - package.ReleaseNotes, - package.IsSystemPackage, - UserController.Instance.GetCurrentUserInfo().UserID, - package.FolderName, - package.IconFile); - - foreach (var dependency in package.Dependencies) - { - dependency.PackageId = package.PackageID; - SavePackageDependency(dependency); - } + package.PackageID = provider.AddPackage( + package.PortalID, + package.Name, + package.FriendlyName, + package.Description, + package.PackageType, + package.Version.ToString(3), + package.License, + package.Manifest, + package.Owner, + package.Organization, + package.Url, + package.Email, + package.ReleaseNotes, + package.IsSystemPackage, + UserController.Instance.GetCurrentUserInfo().UserID, + package.FolderName, + package.IconFile); + + foreach (var dependency in package.Dependencies) + { + dependency.PackageId = package.PackageID; + SavePackageDependency(dependency); + } AddLog(package, EventLogController.EventLogType.PACKAGE_CREATED); @@ -98,7 +215,7 @@ private static void ClearCache(int portalId) private static void ClearDependenciesCache() { - DataCache.RemoveCache(DataCache.PackageDependenciesCacheKey); + DataCache.RemoveCache(DataCache.PackageDependenciesCacheKey); } private static void DeletePackageInternal(PackageInfo package) @@ -110,106 +227,63 @@ private static void DeletePackageInternal(PackageInfo package) { ClearCache(PortalSettings.Current.PortalId); } + ClearCache(Null.NullInteger); - } private static IEnumerable GetPackageDependencies() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.PackageDependenciesCacheKey, - DataCache.PackagesCacheTimeout, - DataCache.PackagesCachePriority), - c => CBO.FillCollection(provider.GetPackageDependencies())); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PackageDependenciesCacheKey, + DataCache.PackagesCacheTimeout, + DataCache.PackagesCachePriority), + c => CBO.FillCollection(provider.GetPackageDependencies())); } private static void UpdatePackageInternal(PackageInfo package) { - provider.UpdatePackage(package.PackageID, - package.PortalID, - package.FriendlyName, - package.Description, - package.PackageType, - package.Version.ToString(3), - package.License, - package.Manifest, - package.Owner, - package.Organization, - package.Url, - package.Email, - package.ReleaseNotes, - package.IsSystemPackage, - UserController.Instance.GetCurrentUserInfo().UserID, - package.FolderName, - package.IconFile); - - foreach (var dependency in package.Dependencies) - { + provider.UpdatePackage( + package.PackageID, + package.PortalID, + package.FriendlyName, + package.Description, + package.PackageType, + package.Version.ToString(3), + package.License, + package.Manifest, + package.Owner, + package.Organization, + package.Url, + package.Email, + package.ReleaseNotes, + package.IsSystemPackage, + UserController.Instance.GetCurrentUserInfo().UserID, + package.FolderName, + package.IconFile); + + foreach (var dependency in package.Dependencies) + { dependency.PackageId = package.PackageID; SavePackageDependency(dependency); - } + } AddLog(package, EventLogController.EventLogType.PACKAGE_UPDATED); ClearCache(package.PortalID); } - private static void SavePackageDependency(PackageDependencyInfo dependency) - { - dependency.PackageDependencyId = provider.SavePackageDependency(dependency.PackageDependencyId, dependency.PackageId, dependency.PackageName, - dependency.Version.ToString()); - - ClearDependenciesCache(); - } - - #endregion - - #region IPackageController Implementation - - public void DeleteExtensionPackage(PackageInfo package) + private static void SavePackageDependency(PackageDependencyInfo dependency) { - switch (package.PackageType) - { - case "Auth_System": - AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); - if (authSystem != null) - { - AuthenticationController.DeleteAuthentication(authSystem); - } - break; - case "CoreLanguagePack": - LanguagePackInfo languagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); - if (languagePack != null) - { - LanguagePackController.DeleteLanguagePack(languagePack); - } - break; - case "Module": - var controller = new DesktopModuleController(); - DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); - if (desktopModule != null) - { - controller.DeleteDesktopModule(desktopModule); - } - break; - case "SkinObject": - SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); - if (skinControl != null) - { - SkinControlController.DeleteSkinControl(skinControl); - } - break; - } - DeletePackageInternal(package); - } + dependency.PackageDependencyId = provider.SavePackageDependency(dependency.PackageDependencyId, dependency.PackageId, dependency.PackageName, + dependency.Version.ToString()); - public PackageInfo GetExtensionPackage(int portalId, Func predicate) - { - return GetExtensionPackage(portalId, predicate, false); - } + ClearDependenciesCache(); + } public PackageInfo GetExtensionPackage(int portalId, Func predicate, bool useCopy) { - var package = GetExtensionPackages(portalId).FirstOrDefault(predicate); + var package = this.GetExtensionPackages(portalId).FirstOrDefault(predicate); if (package != null && useCopy) { @@ -223,19 +297,20 @@ public IList GetExtensionPackages(int portalId) { var cacheKey = string.Format(DataCache.PackagesCacheKey, portalId); var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.PackagesCacheTimeout, DataCache.PackagesCachePriority, portalId); - return CBO.GetCachedObject>(cacheItemArgs, - c => CBO.FillCollection(provider.GetPackages(portalId))); + return CBO.GetCachedObject>( + cacheItemArgs, + c => CBO.FillCollection(provider.GetPackages(portalId))); } public IList GetExtensionPackages(int portalId, Func predicate) { - return GetExtensionPackages(portalId).Where(predicate).ToList(); + return this.GetExtensionPackages(portalId).Where(predicate).ToList(); } /// - /// Save or update the package + /// Save or update the package. /// - /// + /// public void SaveExtensionPackage(PackageInfo package) { if (package.PackageID == Null.NullInteger) @@ -250,102 +325,23 @@ public void SaveExtensionPackage(PackageInfo package) public PackageType GetExtensionPackageType(Func predicate) { - return GetExtensionPackageTypes().SingleOrDefault(predicate); + return this.GetExtensionPackageTypes().SingleOrDefault(predicate); } public IList GetExtensionPackageTypes() { - return CBO.GetCachedObject>(new CacheItemArgs(DataCache.PackageTypesCacheKey, - DataCache.PackageTypesCacheTimeout, - DataCache.PackageTypesCachePriority), - c => CBO.FillCollection(provider.GetPackageTypes())); + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PackageTypesCacheKey, + DataCache.PackageTypesCacheTimeout, + DataCache.PackageTypesCachePriority), + c => CBO.FillCollection(provider.GetPackageTypes())); } public IList GetPackageDependencies(Func predicate) { return GetPackageDependencies().Where(predicate).ToList(); - } - - #endregion - - #region Static Helper Methods - - public static bool CanDeletePackage(PackageInfo package, PortalSettings portalSettings) - { - bool bCanDelete = true; - - var dependencies = Instance.GetPackageDependencies(d => d.PackageName.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && d.Version <= package.Version); - if (dependencies.Count > 0) - { - //There is at least one package dependent on this package. - foreach (var dependency in dependencies) - { - var dep = dependency; - - //Check if there is an alternative package - var packages = Instance.GetExtensionPackages(package.PortalID, - p => p.Name.Equals(dep.PackageName, StringComparison.OrdinalIgnoreCase) - && p.Version >= dep.Version - && p.PackageID != package.PackageID); - if (packages.Count == 0) - { - bCanDelete = false; - } - } - } - - if (bCanDelete) - { - switch (package.PackageType) - { - case "Skin": - case "Container": - //Need to get path of skin being deleted so we can call the public CanDeleteSkin function in the SkinController - string strRootSkin = package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase) ? SkinController.RootSkin : SkinController.RootContainer; - SkinPackageInfo _SkinPackageInfo = SkinController.GetSkinByPackageID(package.PackageID); - string strFolderPath = Path.Combine(_SkinPackageInfo.PortalID == Null.NullInteger ? Path.Combine(Globals.HostMapPath, strRootSkin) : Path.Combine(portalSettings.HomeSystemDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); - - bCanDelete = SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeSystemDirectoryMapPath); - if (_SkinPackageInfo.PortalID != Null.NullInteger) - { - //To be compliant with all versions - strFolderPath = Path.Combine(Path.Combine(portalSettings.HomeDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); - bCanDelete = bCanDelete && SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeDirectoryMapPath); - } - break; - case "Provider": - //Check if the provider is the default provider - XmlDocument configDoc = Config.Load(); - string providerName = package.Name; - if (providerName.IndexOf(".", StringComparison.Ordinal) > Null.NullInteger) - { - providerName = providerName.Substring(providerName.IndexOf(".", StringComparison.Ordinal) + 1); - } - switch (providerName) - { - case "SchedulingProvider": - providerName = "DNNScheduler"; - break; - case "SearchIndexProvider": - providerName = "ModuleIndexProvider"; - break; - case "SearchProvider": - providerName = "SearchDataStoreProvider"; - break; - } - XPathNavigator providerNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/dotnetnuke/*[@defaultProvider='" + providerName + "']"); - bCanDelete = (providerNavigator == null); - break; - } - } - - return bCanDelete; - } - - public static IDictionary GetModulePackagesInUse(int portalID, bool forHost) - { - return CBO.FillDictionary("PackageID", provider.GetModulePackagesInUse(portalID, forHost)); - } + } public static void ParsePackage(string file, string installPath, Dictionary packages, List invalidPackages) { @@ -363,7 +359,7 @@ public static void ParsePackage(string file, string installPath, Dictionary /// PackageCreatedEventArgs provides a custom EventArgs class for a /// Package Created Event. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class PackageCreatedEventArgs : EventArgs { - private readonly PackageInfo _Package; - - ///----------------------------------------------------------------------------- - /// - /// Builds a new PackageCreatedEventArgs + private readonly PackageInfo _Package; + + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Builds a new PackageCreatedEventArgs. /// - /// The package associated with this event + /// The package associated with this event. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public PackageCreatedEventArgs(PackageInfo package) { - _Package = package; + this._Package = package; } - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// Gets the Package associated with this event + /// Gets the Package associated with this event. /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public PackageInfo Package { get { - return _Package; + return this._Package; } } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventHandler.cs b/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventHandler.cs index d2b1a3e0be0..1e295c62933 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventHandler.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Packages { /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs b/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs index a926e975543..1c14dc9fe0d 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs @@ -1,17 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer.Packages { + using System; + [Serializable] public class PackageDependencyInfo { - public int PackageDependencyId { get; set; } - public int PackageId { get; set; } - public string PackageName { get; set; } - public Version Version { get; set; } + public int PackageDependencyId { get; set; } + + public int PackageId { get; set; } + + public string PackageName { get; set; } + + public Version Version { get; set; } } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs b/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs index 057b0d38f9e..ee5cbc9e5b6 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Packages { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.UI.Modules; + /// ----------------------------------------------------------------------------- /// - /// The PackageEditorBase class provides a Base Classs for Package Editors + /// The PackageEditorBase class provides a Base Classs for Package Editors. /// /// ----------------------------------------------------------------------------- public class PackageEditorBase : ModuleUserControlBase, IPackageEditor @@ -23,78 +18,79 @@ public class PackageEditorBase : ModuleUserControlBase, IPackageEditor private bool _IsWizard = Null.NullBoolean; private PackageInfo _Package; private int _PackageID = Null.NullInteger; - - protected string DisplayMode => (Request.QueryString["Display"] ?? "").ToLowerInvariant(); - - protected virtual string EditorID - { - get - { - return Null.NullString; - } - } - - protected bool IsSuperTab + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Package ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public int PackageID { get { - return ModuleContext.PortalSettings.ActiveTab.IsSuperTab; + return this._PackageID; } - } - - protected PackageInfo Package - { - get + + set { - if (_Package == null) - { - _Package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, (p) => p.PackageID == PackageID); ; - } - return _Package; + this._PackageID = value; } } - #region IPackageEditor Members - /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Package ID + /// Gets or sets a value indicating whether gets and sets whether the Editor is in the Wizard. /// - /// An Integer + /// An Boolean. /// ----------------------------------------------------------------------------- - public int PackageID + public bool IsWizard { get { - return _PackageID; + return this._IsWizard; } + set { - _PackageID = value; + this._IsWizard = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether the Editor is in the Wizard - /// - /// An Boolean - /// ----------------------------------------------------------------------------- - public bool IsWizard + protected string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); + + protected virtual string EditorID { get { - return _IsWizard; + return Null.NullString; } - set + } + + protected bool IsSuperTab + { + get { - _IsWizard = value; + return this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab; } } + protected PackageInfo Package + { + get + { + if (this._Package == null) + { + this._Package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, (p) => p.PackageID == this.PackageID); + } + + return this._Package; + } + } + /// ----------------------------------------------------------------------------- /// - /// Used to Initialize the Control + /// Used to Initialize the Control. /// /// ----------------------------------------------------------------------------- public virtual void Initialize() @@ -103,18 +99,16 @@ public virtual void Initialize() /// ----------------------------------------------------------------------------- /// - /// Used to Update the Package + /// Used to Update the Package. /// /// ----------------------------------------------------------------------------- public virtual void UpdatePackage() { - } - - #endregion - + } + protected override void OnInit(EventArgs e) { - ID = EditorID; + this.ID = this.EditorID; base.OnInit(e); } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs b/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs index 03c7b3b99a0..039477efce7 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Security.Cryptography; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Services.Installer.Log; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Packages { + using System; + using System.Collections.Generic; + using System.IO; + using System.Security.Cryptography; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Services.Installer.Log; + /// ----------------------------------------------------------------------------- /// - /// The PackageInfo class represents a single Installer Package + /// The PackageInfo class represents a single Installer Package. /// /// /// @@ -28,267 +23,270 @@ namespace DotNetNuke.Services.Installer.Packages [Serializable] public class PackageInfo : BaseEntityInfo { - private IList _dependencies; - + private IList _dependencies; + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// This Constructor creates a new InstallPackage instance as defined by the - /// Parameters + /// Parameters. /// /// ----------------------------------------------------------------------------- - public PackageInfo(InstallerInfo info) : this() + public PackageInfo(InstallerInfo info) + : this() { - AttachInstallerInfo(info); - } - - /// - /// This Constructor creates a new InstallPackage instance + this.AttachInstallerInfo(info); + } + + /// + /// Initializes a new instance of the class. + /// This Constructor creates a new InstallPackage instance. /// /// ----------------------------------------------------------------------------- public PackageInfo() { - PackageID = Null.NullInteger; - PortalID = Null.NullInteger; - Version = new Version(0, 0, 0); - IsValid = true; - InstalledVersion = new Version(0, 0, 0); + this.PackageID = Null.NullInteger; + this.PortalID = Null.NullInteger; + this.Version = new Version(0, 0, 0); + this.IsValid = true; + this.InstalledVersion = new Version(0, 0, 0); } /// Gets the direct dependencies of this package. [XmlIgnore] - public IList Dependencies - { + public IList Dependencies + { get { - return _dependencies ?? (_dependencies = (PackageID == -1) - ? new List() - : PackageController.Instance.GetPackageDependencies(p => p.PackageId == PackageID)); + return this._dependencies ?? (this._dependencies = (this.PackageID == -1) + ? new List() + : PackageController.Instance.GetPackageDependencies(p => p.PackageId == this.PackageID)); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Email for this package + /// Gets or sets the Email for this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Email { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Description of this package + /// Gets or sets the Description of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Description { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the FileName of this package + /// Gets or sets the FileName of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string FileName { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Files that are included in the Package + /// Gets a Dictionary of Files that are included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- [XmlIgnore] public Dictionary Files { get { - return InstallerInfo.Files; + return this.InstallerInfo.Files; } } /// ----------------------------------------------------------------------------- /// - /// Gets the name (path) of the folder where the package is installed + /// Gets or sets the name (path) of the folder where the package is installed. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string FolderName { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the FriendlyName of this package + /// Gets or sets and Sets the FriendlyName of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string FriendlyName { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the url for the icon for the package + /// Gets or sets the url for the icon for the package. /// - /// A string + /// A string. /// ----------------------------------------------------------------------------- public string IconFile { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Installed Version of the Package + /// Gets or sets and sets the Installed Version of the Package. /// - /// A System.Version + /// A System.Version. /// ----------------------------------------------------------------------------- public Version InstalledVersion { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the associated InstallerInfo + /// Gets the associated InstallerInfo. /// - /// An InstallerInfo object + /// An InstallerInfo object. /// ----------------------------------------------------------------------------- [XmlIgnore] public InstallerInfo InstallerInfo { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the InstallMode + /// Gets the InstallMode. /// - /// An InstallMode value + /// An InstallMode value. /// ----------------------------------------------------------------------------- public InstallMode InstallMode { get { - return InstallerInfo.InstallMode; + return this.InstallerInfo.InstallMode; } } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets whether this package is a "system" Package + /// Gets or sets a value indicating whether gets and Sets whether this package is a "system" Package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public bool IsSystemPackage { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the Package is Valid + /// Gets a value indicating whether gets whether the Package is Valid. /// - /// A Boolean value + /// A Boolean value. /// ----------------------------------------------------------------------------- [XmlIgnore] public bool IsValid { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the License of this package + /// Gets or sets and Sets the License of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string License { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Logger + /// Gets the Logger. /// - /// An Logger object + /// An Logger object. /// ----------------------------------------------------------------------------- [XmlIgnore] public Logger Log { get { - return InstallerInfo.Log; + return this.InstallerInfo.Log; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Manifest of this package + /// Gets or sets the Manifest of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Manifest { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Name of this package + /// Gets or sets the Name of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Name { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Organisation for this package + /// Gets or sets the Organisation for this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Organization { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Owner of this package + /// Gets or sets the Owner of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Owner { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the ID of this package + /// Gets or sets the ID of this package. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int PackageID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Type of this package + /// Gets or sets the Type of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string PackageType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the ID of this portal + /// Gets or sets the ID of this portal. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int PortalID { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the ReleaseNotes of this package + /// Gets or sets and Sets the ReleaseNotes of this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ReleaseNotes { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Url for this package + /// Gets or sets the Url for this package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Url { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Version of this package + /// Gets or sets the Version of this package. /// - /// A System.Version + /// A System.Version. /// ----------------------------------------------------------------------------- public Version Version { get; set; } /// ----------------------------------------------------------------------------- /// - /// The AttachInstallerInfo method attachs an InstallerInfo instance to the Package + /// The AttachInstallerInfo method attachs an InstallerInfo instance to the Package. /// - /// The InstallerInfo instance to attach + /// The InstallerInfo instance to attach. /// ----------------------------------------------------------------------------- public void AttachInstallerInfo(InstallerInfo installer) { - InstallerInfo = installer; + this.InstallerInfo = installer; } /// @@ -297,30 +295,30 @@ public void AttachInstallerInfo(InstallerInfo installer) /// public PackageInfo Clone() { - return new PackageInfo - { - PackageID = PackageID, - PortalID = PortalID, - PackageType = PackageType, - InstallerInfo = InstallerInfo, - Name = Name, - FriendlyName = FriendlyName, - Manifest = Manifest, - Email = Email, - Description = Description, - FolderName = FolderName, - FileName = FileName, - IconFile = IconFile, - IsSystemPackage = IsSystemPackage, - IsValid = IsValid, - Organization = Organization, - Owner = Owner, - License = License, - ReleaseNotes = ReleaseNotes, - Url = Url, - Version = Version, - InstalledVersion = InstalledVersion - }; + return new PackageInfo + { + PackageID = this.PackageID, + PortalID = this.PortalID, + PackageType = this.PackageType, + InstallerInfo = this.InstallerInfo, + Name = this.Name, + FriendlyName = this.FriendlyName, + Manifest = this.Manifest, + Email = this.Email, + Description = this.Description, + FolderName = this.FolderName, + FileName = this.FileName, + IconFile = this.IconFile, + IsSystemPackage = this.IsSystemPackage, + IsValid = this.IsValid, + Organization = this.Organization, + Owner = this.Owner, + License = this.License, + ReleaseNotes = this.ReleaseNotes, + Url = this.Url, + Version = this.Version, + InstalledVersion = this.InstalledVersion, + }; } } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageType.cs b/DNN Platform/Library/Services/Installer/Packages/PackageType.cs index 1b338dc928a..6ecc854c221 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageType.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageType.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Packages { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security; + /// /// This class allows PackageType to have a memeber named PackageType - /// to remain compatible with the original VB implementation + /// to remain compatible with the original VB implementation. /// [Serializable] public class PackageTypeMemberNameFixer { public PackageTypeMemberNameFixer() { - PackageType = string.Empty; + this.PackageType = string.Empty; } public string PackageType { get; set; } @@ -30,15 +25,18 @@ public PackageTypeMemberNameFixer() /// ----------------------------------------------------------------------------- /// - /// The PackageType class represents a single Installer Package Type + /// The PackageType class represents a single Installer Package Type. /// /// ----------------------------------------------------------------------------- [Serializable] public class PackageType : PackageTypeMemberNameFixer { public string Description { get; set; } + public string EditorControlSrc { get; set; } + public SecurityAccessLevel SecurityAccessLevel { get; set; } + public bool SupportsSideBySideInstallation { get; set; } } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs b/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs index 4192df0740d..db7c2dfd0af 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.UI.WebControls; - -using DNNLocalization = DotNetNuke.Services.Localization.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Packages.WebControls { + using System.Collections.Generic; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.UI.WebControls; + + using DNNLocalization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Services.Installer.Packages.WebControls @@ -28,12 +23,10 @@ namespace DotNetNuke.Services.Installer.Packages.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:PackageTypeEditControl runat=server>")] public class PackageTypeEditControl : TextEditControl - { - #region "Protected Methods" - + { /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- @@ -41,46 +34,44 @@ protected override void RenderEditMode(HtmlTextWriter writer) { IList packageTypes = PackageController.Instance.GetExtensionPackageTypes(); - //Render the Select Tag - ControlStyle.AddAttributesToRender(writer); + // Render the Select Tag + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.RenderBeginTag(HtmlTextWriterTag.Select); - //Add the Not Specified Option + // Add the Not Specified Option writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); - if (StringValue == Null.NullString) + if (this.StringValue == Null.NullString) { writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } - - //Render Option Tag + + // Render Option Tag writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write("<" + DNNLocalization.GetString("Not_Specified", DNNLocalization.SharedResourceFile) + ">"); writer.RenderEndTag(); foreach (PackageType type in packageTypes) { - //Add the Value Attribute + // Add the Value Attribute writer.AddAttribute(HtmlTextWriterAttribute.Value, type.PackageType); - if (type.PackageType == StringValue) + if (type.PackageType == this.StringValue) { - //Add the Selected Attribute + // Add the Selected Attribute writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } - - //Render Option Tag + + // Render Option Tag writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(type.PackageType); writer.RenderEndTag(); } - - //Close Select Tag + + // Close Select Tag writer.RenderEndTag(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/TextEncoding.cs b/DNN Platform/Library/Services/Installer/TextEncoding.cs index af89856cb04..542b71d792f 100644 --- a/DNN Platform/Library/Services/Installer/TextEncoding.cs +++ b/DNN Platform/Library/Services/Installer/TextEncoding.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Installer { public enum TextEncoding @@ -10,6 +10,6 @@ public enum TextEncoding UTF8, UTF16BigEndian, UTF16LittleEndian, - Unknown + Unknown, } } diff --git a/DNN Platform/Library/Services/Installer/Util.cs b/DNN Platform/Library/Services/Installer/Util.cs index 7df536feab9..94cae3642ae 100644 --- a/DNN Platform/Library/Services/Installer/Util.cs +++ b/DNN Platform/Library/Services/Installer/Util.cs @@ -1,42 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Diagnostics; -using System.IO; -using System.Net; -using System.Text; -using System.Xml.XPath; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Common.Utilities.Internal; -using DotNetNuke.Entities.Host; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.UI.Modules; -using System.Threading; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { + using System; + using System.Diagnostics; + using System.IO; + using System.Net; + using System.Text; + using System.Threading; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Common.Utilities.Internal; + using DotNetNuke.Entities.Host; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.UI.Modules; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// /// The InstallerBase class is a Base Class for all Installer - /// classes that need to use Localized Strings. It provides these strings - /// as localized Constants. + /// classes that need to use Localized Strings. It provides these strings + /// as localized Constants. /// /// /// public class Util { - #region Constants - // ReSharper disable InconsistentNaming public const string DEFAULT_MANIFESTEXT = ".manifest"; + public const string BackupInstallPackageFolder = "App_Data/ExtensionPackages/"; public static string ASSEMBLY_Added = GetLocalizedString("ASSEMBLY_Added"); public static string ASSEMBLY_AddedBindingRedirect = GetLocalizedString("ASSEMBLY_AddedBindingRedirect"); public static string ASSEMBLY_RemovedBindingRedirect = GetLocalizedString("ASSEMBLY_RemovedBindingRedirect"); @@ -174,30 +171,76 @@ public class Util public static string WRITER_SavedFile = GetLocalizedString("WRITER_SavedFile"); public static string WRITER_SaveFileError = GetLocalizedString("WRITER_SaveFileError"); public static string REGEX_Version = "\\d{2}.\\d{2}.\\d{2}"; - public const string BackupInstallPackageFolder = "App_Data/ExtensionPackages/"; - // ReSharper restore InconsistentNaming - #endregion - #region "Private Shared Methods" + /// ----------------------------------------------------------------------------- + /// + /// The BackupFile method backs up a file to the backup folder. + /// + /// The file to backup. + /// The basePath to the file. + /// A Logger to log the result. + public static void BackupFile(InstallFile installFile, string basePath, Logger log) + { + string fullFileName = Path.Combine(basePath, installFile.FullName); + string backupFileName = Path.Combine(installFile.BackupPath, installFile.Name + ".config"); + + // create the backup folder if neccessary + if (!Directory.Exists(installFile.BackupPath)) + { + Directory.CreateDirectory(installFile.BackupPath); + } + + // Copy file to backup location + RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(fullFileName, backupFileName), "Backup file " + fullFileName); + log.AddInfo(string.Format(FILE_CreateBackup, installFile.FullName)); + } + + /// ----------------------------------------------------------------------------- + /// + /// The CopyFile method copies a file from the temporary extract location. + /// + /// The file to copy. + /// The basePath to the file. + /// A Logger to log the result. + public static void CopyFile(InstallFile installFile, string basePath, Logger log) + { + string filePath = Path.Combine(basePath, installFile.Path); + string fullFileName = Path.Combine(basePath, installFile.FullName); + + // create the folder if neccessary + if (!Directory.Exists(filePath)) + { + log.AddInfo(string.Format(FOLDER_Created, filePath)); + Directory.CreateDirectory(filePath); + } + + // Copy file from temp location + RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(installFile.TempFileName, fullFileName), "Copy file to " + fullFileName); + + log.AddInfo(string.Format(FILE_Created, installFile.FullName)); + } + + // ReSharper restore InconsistentNaming /// ----------------------------------------------------------------------------- /// - /// The StreamToStream method reads a source stream and wrtites it to a destination stream + /// The StreamToStream method reads a source stream and wrtites it to a destination stream. /// - /// The Source Stream - /// The Destination Stream + /// The Source Stream. + /// The Destination Stream. private static void StreamToStream(Stream sourceStream, Stream destStream) { var buf = new byte[1024]; int count; do { - //Read the chunk from the source + // Read the chunk from the source count = sourceStream.Read(buf, 0, 1024); - //Write the chunk to the destination + // Write the chunk to the destination destStream.Write(buf, 0, count); - } while (count > 0); + } + while (count > 0); destStream.Flush(); } @@ -217,77 +260,26 @@ private static string ValidateNode(string propValue, bool isRequired, Logger log { if (isRequired) { - //Log Error + // Log Error log.AddFailure(logmessage); } else { - //Use Default + // Use Default propValue = defaultValue; } } - return propValue; - } - - #endregion - - #region Public Shared Methods - - /// ----------------------------------------------------------------------------- - /// - /// The BackupFile method backs up a file to the backup folder - /// - /// The file to backup - /// The basePath to the file - /// A Logger to log the result - public static void BackupFile(InstallFile installFile, string basePath, Logger log) - { - string fullFileName = Path.Combine(basePath, installFile.FullName); - string backupFileName = Path.Combine(installFile.BackupPath, installFile.Name + ".config"); - - //create the backup folder if neccessary - if (!Directory.Exists(installFile.BackupPath)) - { - Directory.CreateDirectory(installFile.BackupPath); - } - - //Copy file to backup location - RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(fullFileName, backupFileName), "Backup file " + fullFileName); - log.AddInfo(string.Format(FILE_CreateBackup, installFile.FullName)); - } - - /// ----------------------------------------------------------------------------- - /// - /// The CopyFile method copies a file from the temporary extract location. - /// - /// The file to copy - /// The basePath to the file - /// A Logger to log the result - public static void CopyFile(InstallFile installFile, string basePath, Logger log) - { - string filePath = Path.Combine(basePath, installFile.Path); - string fullFileName = Path.Combine(basePath, installFile.FullName); - - //create the folder if neccessary - if (!Directory.Exists(filePath)) - { - log.AddInfo(string.Format(FOLDER_Created, filePath)); - Directory.CreateDirectory(filePath); - } - - //Copy file from temp location - RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(installFile.TempFileName, fullFileName), "Copy file to " + fullFileName); - log.AddInfo(string.Format(FILE_Created, installFile.FullName)); + return propValue; } /// ----------------------------------------------------------------------------- /// /// The DeleteFile method deletes a file. /// - /// The file to delete - /// The basePath to the file - /// A Logger to log the result + /// The file to delete. + /// The basePath to the file. + /// A Logger to log the result. public static void DeleteFile(InstallFile installFile, string basePath, Logger log) { DeleteFile(installFile.FullName, basePath, log); @@ -297,9 +289,9 @@ public static void DeleteFile(InstallFile installFile, string basePath, Logger l /// /// The DeleteFile method deletes a file. /// - /// The file to delete - /// The basePath to the file - /// A Logger to log the result + /// The file to delete. + /// The basePath to the file. + /// A Logger to log the result. public static void DeleteFile(string fileName, string basePath, Logger log) { string fullFileName = Path.Combine(basePath, fileName); @@ -316,30 +308,29 @@ public static void DeleteFile(string fileName, string basePath, Logger log) } } - /// ----------------------------------------------------------------------------- /// /// The GetLocalizedString method provides a conveniencewrapper around the - /// Localization of Strings + /// Localization of Strings. /// - /// The localization key - /// The localized string + /// The localization key. + /// The localized string. public static string GetLocalizedString(string key) { - return Localization.Localization.GetString(key, Localization.Localization.SharedResourceFile); + return Localization.GetString(key, Localization.SharedResourceFile); } public static bool IsFileValid(InstallFile file, string packageWhiteList) { - //Check the White List + // Check the White List FileExtensionWhitelist whiteList = Host.AllowedExtensionWhitelist; - //Check the White Lists + // Check the White Lists string strExtension = file.Extension.ToLowerInvariant(); - if ((strExtension == "dnn" || whiteList.IsAllowedExtension(strExtension) || packageWhiteList.Contains(strExtension) || - (packageWhiteList.Contains("*dataprovider") && strExtension.EndsWith("dataprovider")))) + if (strExtension == "dnn" || whiteList.IsAllowedExtension(strExtension) || packageWhiteList.Contains(strExtension) || + (packageWhiteList.Contains("*dataprovider") && strExtension.EndsWith("dataprovider"))) { - //Install File is Valid + // Install File is Valid return true; } @@ -349,11 +340,11 @@ public static bool IsFileValid(InstallFile file, string packageWhiteList) /// ----------------------------------------------------------------------------- /// /// The InstallURL method provides a utility method to build the correct url - /// to install a package (and return to where you came from) + /// to install a package (and return to where you came from). /// - /// The id of the tab you are on - /// The type of package you are installing - /// The localized string + /// The id of the tab you are on. + /// The type of package you are installing. + /// The localized string. public static string InstallURL(int tabId, string type) { var parameters = new string[2]; @@ -362,6 +353,7 @@ public static string InstallURL(int tabId, string type) { parameters[1] = "ptype=" + type; } + var context = new ModuleInstanceContext(); return context.NavigateUrl(tabId, "Install", false, parameters); } @@ -374,10 +366,12 @@ public static string InstallURL(int tabId, string returnUrl, string type) { parameters[1] = "returnUrl=" + returnUrl; } + if (!string.IsNullOrEmpty(type)) { parameters[2] = "ptype=" + type; } + var context = new ModuleInstanceContext(); return context.NavigateUrl(tabId, "Install", false, parameters); } @@ -390,14 +384,17 @@ public static string InstallURL(int tabId, string returnUrl, string type, string { parameters[1] = "returnUrl=" + returnUrl; } + if (!string.IsNullOrEmpty(type)) { parameters[2] = "ptype=" + type; } + if (!string.IsNullOrEmpty(package)) { parameters[3] = "package=" + package; } + var context = new ModuleInstanceContext(); return context.NavigateUrl(tabId, "Install", false, parameters); } @@ -415,11 +412,11 @@ public static string UnInstallURL(int tabId, int packageId, string returnUrl) /// ----------------------------------------------------------------------------- /// /// The PackageWriterURL method provides a utility method to build the correct url - /// to create a package (and return to where you came from) + /// to create a package (and return to where you came from). /// - /// The ModuleContext of the module - /// The id of the package you are packaging - /// The localized string + /// The ModuleContext of the module. + /// The id of the package you are packaging. + /// The localized string. public static string PackageWriterURL(ModuleInstanceContext context, int packageId) { var parameters = new string[3]; @@ -437,6 +434,7 @@ public static string ParsePackageIconFileName(PackageInfo package) { filename = package.IconFile.StartsWith("~/" + package.FolderName) ? package.IconFile.Remove(0, ("~/" + package.FolderName).Length).TrimStart('/') : package.IconFile; } + return filename; } @@ -447,22 +445,23 @@ public static string ParsePackageIconFile(PackageInfo package) { iconFile = !package.IconFile.StartsWith("~/") ? "~/" + package.FolderName + "/" + package.IconFile : package.IconFile; } + return iconFile; } public static string ReadAttribute(XPathNavigator nav, string attributeName) { - return ValidateNode(nav.GetAttribute(attributeName, ""), false, null, "", ""); + return ValidateNode(nav.GetAttribute(attributeName, string.Empty), false, null, string.Empty, string.Empty); } public static string ReadAttribute(XPathNavigator nav, string attributeName, Logger log, string logmessage) { - return ValidateNode(nav.GetAttribute(attributeName, ""), true, log, logmessage, ""); + return ValidateNode(nav.GetAttribute(attributeName, string.Empty), true, log, logmessage, string.Empty); } public static string ReadAttribute(XPathNavigator nav, string attributeName, bool isRequired, Logger log, string logmessage, string defaultValue) { - return ValidateNode(nav.GetAttribute(attributeName, ""), isRequired, log, logmessage, defaultValue); + return ValidateNode(nav.GetAttribute(attributeName, string.Empty), isRequired, log, logmessage, defaultValue); } public static string GetPackageBackupName(PackageInfo package) @@ -493,23 +492,19 @@ public static string GetPackageBackupPath(PackageInfo package) return Path.Combine(folderPath, fileName); } - #endregion - - #region ReadElement - public static string ReadElement(XPathNavigator nav, string elementName) { - return ValidateNode(XmlUtils.GetNodeValue(nav, elementName), false, null, "", ""); + return ValidateNode(XmlUtils.GetNodeValue(nav, elementName), false, null, string.Empty, string.Empty); } public static string ReadElement(XPathNavigator nav, string elementName, string defaultValue) { - return ValidateNode(XmlUtils.GetNodeValue(nav, elementName), false, null, "", defaultValue); + return ValidateNode(XmlUtils.GetNodeValue(nav, elementName), false, null, string.Empty, defaultValue); } public static string ReadElement(XPathNavigator nav, string elementName, Logger log, string logmessage) { - return ValidateNode(XmlUtils.GetNodeValue(nav, elementName), true, log, logmessage, ""); + return ValidateNode(XmlUtils.GetNodeValue(nav, elementName), true, log, logmessage, string.Empty); } public static string ReadElement(XPathNavigator nav, string elementName, bool isRequired, Logger log, string logmessage, string defaultValue) @@ -519,17 +514,17 @@ public static string ReadElement(XPathNavigator nav, string elementName, bool is /// ----------------------------------------------------------------------------- /// - /// The RestoreFile method restores a file from the backup folder + /// The RestoreFile method restores a file from the backup folder. /// - /// The file to restore - /// The basePath to the file - /// A Logger to log the result + /// The file to restore. + /// The basePath to the file. + /// A Logger to log the result. public static void RestoreFile(InstallFile installFile, string basePath, Logger log) { string fullFileName = Path.Combine(basePath, installFile.FullName); string backupFileName = Path.Combine(installFile.BackupPath, installFile.Name + ".config"); - //Copy File back over install file + // Copy File back over install file FileSystemUtils.CopyFile(backupFileName, fullFileName); log.AddInfo(string.Format(FILE_RestoreBackup, installFile.FullName)); @@ -538,11 +533,11 @@ public static void RestoreFile(InstallFile installFile, string basePath, Logger /// ----------------------------------------------------------------------------- /// /// The UnInstallURL method provides a utility method to build the correct url - /// to uninstall a package (and return to where you came from) + /// to uninstall a package (and return to where you came from). /// - /// The id of the tab you are on - /// The id of the package you are uninstalling - /// The localized string + /// The id of the tab you are on. + /// The id of the package you are uninstalling. + /// The localized string. public static string UnInstallURL(int tabId, int packageId) { var parameters = new string[2]; @@ -554,38 +549,40 @@ public static string UnInstallURL(int tabId, int packageId) /// ----------------------------------------------------------------------------- /// - /// The WriteStream reads a source stream and writes it to a destination file + /// The WriteStream reads a source stream and writes it to a destination file. /// - /// The Source Stream - /// The Destination file + /// The Source Stream. + /// The Destination file. public static void WriteStream(Stream sourceStream, string destFileName) { var file = new FileInfo(destFileName); if (file.Directory != null && !file.Directory.Exists) + { file.Directory.Create(); + } - //HACK: Temporary fix, upping retry limit due to locking for existing filesystem access. This "fixes" azure, but isn't the most elegant + // HACK: Temporary fix, upping retry limit due to locking for existing filesystem access. This "fixes" azure, but isn't the most elegant TryToCreateAndExecute(destFileName, (f) => StreamToStream(sourceStream, f), 3500); } /// - /// Try to create file and perform an action on a file until a specific amount of time + /// Try to create file and perform an action on a file until a specific amount of time. /// - /// Path of the file - /// Action to execute on file - /// Maimum amount of time to try to do the action - /// true if action occur and false otherwise + /// Path of the file. + /// Action to execute on file. + /// Maimum amount of time to try to do the action. + /// true if action occur and false otherwise. public static bool TryToCreateAndExecute(string path, Action action, int milliSecondMax = Timeout.Infinite) { var result = false; var dateTimeStart = DateTime.Now; - Tuple < AutoResetEvent, FileSystemWatcher > tuple = null; + Tuple tuple = null; while (true) { try { - //Open for create, requesting read/write access, allow others to read/write as well + // Open for create, requesting read/write access, allow others to read/write as well using (var file = File.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { action(file); @@ -595,14 +592,14 @@ public static bool TryToCreateAndExecute(string path, Action action, } catch (IOException) { - // Init only once and only if needed. Prevent against many instantiation in case of multhreaded + // Init only once and only if needed. Prevent against many instantiation in case of multhreaded // file access concurrency (if file is frequently accessed by someone else). Better memory usage. if (tuple == null) { var autoResetEvent = new AutoResetEvent(true); var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(path)) { - EnableRaisingEvents = true + EnableRaisingEvents = true, }; fileSystemWatcher.Changed += @@ -620,7 +617,7 @@ public static bool TryToCreateAndExecute(string path, Action action, int milliSecond = Timeout.Infinite; if (milliSecondMax != Timeout.Infinite) { - milliSecond = (int) (DateTime.Now - dateTimeStart).TotalMilliseconds; + milliSecond = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds; if (milliSecond >= milliSecondMax) { result = false; @@ -644,95 +641,97 @@ public static bool TryToCreateAndExecute(string path, Action action, public static WebResponse GetExternalRequest(string URL, byte[] Data, string Username, string Password, string Domain, string ProxyAddress, int ProxyPort, bool DoPOST, string UserAgent, string Referer, out string Filename) { - return GetExternalRequest(URL, Data, Username, Password, Domain, ProxyAddress, ProxyPort, DoPOST, UserAgent, Referer, out Filename, Host.WebRequestTimeout); - } - - public static WebResponse GetExternalRequest(string URL, byte[] Data, string Username, string Password, string Domain, string ProxyAddress, int ProxyPort, bool DoPOST, string UserAgent, - string Referer, out string Filename, int requestTimeout) - { - return GetExternalRequest(URL, Data, Username, Password, Domain, ProxyAddress, ProxyPort, string.Empty, string.Empty, DoPOST, UserAgent, Referer, out Filename, requestTimeout); - } - - public static WebResponse GetExternalRequest(string URL, byte[] Data, string Username, string Password, string Domain, string ProxyAddress, int ProxyPort, - string ProxyUsername, string ProxyPassword, bool DoPOST, string UserAgent, string Referer, out string Filename) - { - return GetExternalRequest(URL, Data, Username, Password, Domain, ProxyAddress, ProxyPort, ProxyUsername, ProxyPassword, DoPOST, UserAgent, Referer, out Filename, Host.WebRequestTimeout); - } - - public static WebResponse GetExternalRequest(string URL, byte[] Data, string Username, string Password, string Domain, string ProxyAddress, int ProxyPort, - string ProxyUsername, string ProxyPassword, bool DoPOST, string UserAgent, string Referer, out string Filename, int requestTimeout) - { - if (!DoPOST && Data != null && Data.Length > 0) - { - string restoftheurl = Encoding.ASCII.GetString(Data); - if (URL != null && URL.IndexOf("?") <= 0) - { - URL = URL + "?"; - } - URL = URL + restoftheurl; - } - - var wreq = (HttpWebRequest)WebRequest.Create(URL); - wreq.UserAgent = UserAgent; - wreq.Referer = Referer; - wreq.Method = "GET"; - if (DoPOST) - { - wreq.Method = "POST"; - } - - wreq.Timeout = requestTimeout; - - if (!string.IsNullOrEmpty(ProxyAddress)) - { - var proxy = new WebProxy(ProxyAddress, ProxyPort); - if (!string.IsNullOrEmpty(ProxyUsername)) - { - var proxyCredentials = new NetworkCredential(ProxyUsername, ProxyPassword); - proxy.Credentials = proxyCredentials; - } - wreq.Proxy = proxy; - } - - if (Username != null && Password != null && Domain != null && Username.Trim() != "" && Password.Trim() != null && Domain.Trim() != null) - { - wreq.Credentials = new NetworkCredential(Username, Password, Domain); - } - else if (Username != null && Password != null && Username.Trim() != "" && Password.Trim() != null) - { - wreq.Credentials = new NetworkCredential(Username, Password); - } - - if (DoPOST && Data != null && Data.Length > 0) - { - wreq.ContentType = "application/x-www-form-urlencoded"; - Stream request = wreq.GetRequestStream(); - request.Write(Data, 0, Data.Length); - request.Close(); - } - - Filename = ""; - WebResponse wrsp = wreq.GetResponse(); - string cd = wrsp.Headers["Content-Disposition"]; - if (cd != null && cd.Trim() != string.Empty && cd.StartsWith("attachment")) - { - if (cd.IndexOf("filename") > -1 && cd.Substring(cd.IndexOf("filename")).IndexOf("=") > -1) - { - string filenameParam = cd.Substring(cd.IndexOf("filename")); - - if (filenameParam.IndexOf("\"") > -1) - { - Filename = filenameParam.Substring(filenameParam.IndexOf("\"") + 1).TrimEnd(Convert.ToChar("\"")).TrimEnd(Convert.ToChar("\\")); - } - else - { - Filename = filenameParam.Substring(filenameParam.IndexOf("=") + 1); - } - } - } - - return wrsp; - } + return GetExternalRequest(URL, Data, Username, Password, Domain, ProxyAddress, ProxyPort, DoPOST, UserAgent, Referer, out Filename, Host.WebRequestTimeout); + } + + public static WebResponse GetExternalRequest(string URL, byte[] Data, string Username, string Password, string Domain, string ProxyAddress, int ProxyPort, bool DoPOST, string UserAgent, + string Referer, out string Filename, int requestTimeout) + { + return GetExternalRequest(URL, Data, Username, Password, Domain, ProxyAddress, ProxyPort, string.Empty, string.Empty, DoPOST, UserAgent, Referer, out Filename, requestTimeout); + } + + public static WebResponse GetExternalRequest(string URL, byte[] Data, string Username, string Password, string Domain, string ProxyAddress, int ProxyPort, + string ProxyUsername, string ProxyPassword, bool DoPOST, string UserAgent, string Referer, out string Filename) + { + return GetExternalRequest(URL, Data, Username, Password, Domain, ProxyAddress, ProxyPort, ProxyUsername, ProxyPassword, DoPOST, UserAgent, Referer, out Filename, Host.WebRequestTimeout); + } + + public static WebResponse GetExternalRequest(string URL, byte[] Data, string Username, string Password, string Domain, string ProxyAddress, int ProxyPort, + string ProxyUsername, string ProxyPassword, bool DoPOST, string UserAgent, string Referer, out string Filename, int requestTimeout) + { + if (!DoPOST && Data != null && Data.Length > 0) + { + string restoftheurl = Encoding.ASCII.GetString(Data); + if (URL != null && URL.IndexOf("?") <= 0) + { + URL = URL + "?"; + } + + URL = URL + restoftheurl; + } + + var wreq = (HttpWebRequest)WebRequest.Create(URL); + wreq.UserAgent = UserAgent; + wreq.Referer = Referer; + wreq.Method = "GET"; + if (DoPOST) + { + wreq.Method = "POST"; + } + + wreq.Timeout = requestTimeout; + + if (!string.IsNullOrEmpty(ProxyAddress)) + { + var proxy = new WebProxy(ProxyAddress, ProxyPort); + if (!string.IsNullOrEmpty(ProxyUsername)) + { + var proxyCredentials = new NetworkCredential(ProxyUsername, ProxyPassword); + proxy.Credentials = proxyCredentials; + } + + wreq.Proxy = proxy; + } + + if (Username != null && Password != null && Domain != null && Username.Trim() != string.Empty && Password.Trim() != null && Domain.Trim() != null) + { + wreq.Credentials = new NetworkCredential(Username, Password, Domain); + } + else if (Username != null && Password != null && Username.Trim() != string.Empty && Password.Trim() != null) + { + wreq.Credentials = new NetworkCredential(Username, Password); + } + + if (DoPOST && Data != null && Data.Length > 0) + { + wreq.ContentType = "application/x-www-form-urlencoded"; + Stream request = wreq.GetRequestStream(); + request.Write(Data, 0, Data.Length); + request.Close(); + } + + Filename = string.Empty; + WebResponse wrsp = wreq.GetResponse(); + string cd = wrsp.Headers["Content-Disposition"]; + if (cd != null && cd.Trim() != string.Empty && cd.StartsWith("attachment")) + { + if (cd.IndexOf("filename") > -1 && cd.Substring(cd.IndexOf("filename")).IndexOf("=") > -1) + { + string filenameParam = cd.Substring(cd.IndexOf("filename")); + + if (filenameParam.IndexOf("\"") > -1) + { + Filename = filenameParam.Substring(filenameParam.IndexOf("\"") + 1).TrimEnd(Convert.ToChar("\"")).TrimEnd(Convert.ToChar("\\")); + } + else + { + Filename = filenameParam.Substring(filenameParam.IndexOf("=") + 1); + } + } + } + + return wrsp; + } public static void DeployExtension(WebResponse wr, string myfile, string installFolder) { @@ -761,24 +760,24 @@ public static void DeployExtension(WebResponse wr, string myfile, string install // Write the data to the local file localStream.Write(buffer, 0, bytesRead); - } while (bytesRead > 0); + } + while (bytesRead > 0); } finally { - // Close the response and streams objects here + // Close the response and streams objects here // to make sure they're closed even if an exception // is thrown at some point if (remoteStream != null) { remoteStream.Close(); } + if (localStream != null) { localStream.Close(); } } } - - #endregion } } diff --git a/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs index 1e128f2a3e8..6972685b0f0 100644 --- a/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs @@ -1,36 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// /// The AssemblyComponentWriter class handles creating the manifest for Assembly - /// Component(s) + /// Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class AssemblyComponentWriter : FileComponentWriter { - public AssemblyComponentWriter(string basePath, Dictionary assemblies, PackageInfo package) : base(basePath, assemblies, package) + public AssemblyComponentWriter(string basePath, Dictionary assemblies, PackageInfo package) + : base(basePath, assemblies, package) { } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("assemblies") + /// Gets the name of the Collection Node ("assemblies"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -42,9 +38,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("Assembly") + /// Gets the name of the Component Type ("Assembly"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ComponentType { @@ -56,9 +52,9 @@ protected override string ComponentType /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("assembly") + /// Gets the name of the Item Node ("assembly"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { diff --git a/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs index a821aea4c41..19de549d86d 100644 --- a/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs @@ -1,92 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.Xml; - -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.IO; + using System.Xml; + + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationPackageWriter class + /// The AuthenticationPackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class AuthenticationPackageWriter : PackageWriterBase - { - #region "Constructors" - - public AuthenticationPackageWriter(PackageInfo package) : base(package) + { + public AuthenticationPackageWriter(PackageInfo package) + : base(package) { - AuthSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); - Initialize(); + this.AuthSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); + this.Initialize(); } - public AuthenticationPackageWriter(AuthenticationInfo authSystem, PackageInfo package) : base(package) + public AuthenticationPackageWriter(AuthenticationInfo authSystem, PackageInfo package) + : base(package) { - AuthSystem = authSystem; - Initialize(); + this.AuthSystem = authSystem; + this.Initialize(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the associated Authentication System. + /// + /// An AuthenticationInfo object. + /// ----------------------------------------------------------------------------- + public AuthenticationInfo AuthSystem { get; set; } + + protected override void WriteManifestComponent(XmlWriter writer) + { + // Write Authentication Component + this.WriteAuthenticationComponent(writer); } - - #endregion - - #region "Public Properties" - - /// ----------------------------------------------------------------------------- - /// - /// Gets the associated Authentication System - /// - /// An AuthenticationInfo object - /// ----------------------------------------------------------------------------- - public AuthenticationInfo AuthSystem { get; set; } - - #endregion - - #region "Private Methods" - + private void Initialize() { - BasePath = Path.Combine("DesktopModules\\AuthenticationServices", AuthSystem.AuthenticationType); - AppCodePath = Path.Combine("App_Code\\AuthenticationServices", AuthSystem.AuthenticationType); - AssemblyPath = "bin"; + this.BasePath = Path.Combine("DesktopModules\\AuthenticationServices", this.AuthSystem.AuthenticationType); + this.AppCodePath = Path.Combine("App_Code\\AuthenticationServices", this.AuthSystem.AuthenticationType); + this.AssemblyPath = "bin"; } private void WriteAuthenticationComponent(XmlWriter writer) { - //Start component Element + // Start component Element writer.WriteStartElement("component"); writer.WriteAttributeString("type", "AuthenticationSystem"); - //Start authenticationService Element + // Start authenticationService Element writer.WriteStartElement("authenticationService"); - writer.WriteElementString("type", AuthSystem.AuthenticationType); - writer.WriteElementString("settingsControlSrc", AuthSystem.SettingsControlSrc); - writer.WriteElementString("loginControlSrc", AuthSystem.LoginControlSrc); - writer.WriteElementString("logoffControlSrc", AuthSystem.LogoffControlSrc); + writer.WriteElementString("type", this.AuthSystem.AuthenticationType); + writer.WriteElementString("settingsControlSrc", this.AuthSystem.SettingsControlSrc); + writer.WriteElementString("loginControlSrc", this.AuthSystem.LoginControlSrc); + writer.WriteElementString("logoffControlSrc", this.AuthSystem.LogoffControlSrc); - //End authenticationService Element + // End authenticationService Element writer.WriteEndElement(); - //End component Element + // End component Element writer.WriteEndElement(); - } - - #endregion - - protected override void WriteManifestComponent(XmlWriter writer) - { - //Write Authentication Component - WriteAuthenticationComponent(writer); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs index 409d7d70b87..bd1f3fd0418 100644 --- a/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs @@ -1,68 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.IO; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + using System.IO; + using System.Xml; + /// ----------------------------------------------------------------------------- /// /// The CleanupComponentWriter class handles creating the manifest for Cleanup - /// Component(s) + /// Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class CleanupComponentWriter - { - #region "Private Members" - + { private readonly SortedList _Files; - private string _BasePath; - - #endregion - - #region "Constructors" - + private string _BasePath; + /// ----------------------------------------------------------------------------- - /// - /// Constructs the ContainerComponentWriter + /// + /// Initializes a new instance of the class. + /// Constructs the ContainerComponentWriter. /// /// Base Path. - /// A Dictionary of files + /// A Dictionary of files. /// ----------------------------------------------------------------------------- public CleanupComponentWriter(string basePath, SortedList files) { - _Files = files; - _BasePath = basePath; - } - - #endregion - - #region "Public Methods" - + this._Files = files; + this._BasePath = basePath; + } + public virtual void WriteManifest(XmlWriter writer) { - foreach (KeyValuePair kvp in _Files) + foreach (KeyValuePair kvp in this._Files) { - //Start component Element + // Start component Element writer.WriteStartElement("component"); writer.WriteAttributeString("type", "Cleanup"); writer.WriteAttributeString("fileName", kvp.Value.Name); writer.WriteAttributeString("version", Path.GetFileNameWithoutExtension(kvp.Value.Name)); - //End component Element + // End component Element writer.WriteEndElement(); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs index e2f26544f25..6426401cde2 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs @@ -1,45 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// /// The ContainerComponentWriter class handles creating the manifest for Container - /// Component(s) + /// Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class ContainerComponentWriter : SkinComponentWriter - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs the ContainerComponentWriter + /// + /// Initializes a new instance of the class. + /// Constructs the ContainerComponentWriter. /// - /// The name of the Container - /// The Base Path for the files - /// A Dictionary of files + /// The name of the Container. + /// The Base Path for the files. + /// A Dictionary of files. /// /// ----------------------------------------------------------------------------- - public ContainerComponentWriter(string containerName, string basePath, Dictionary files, PackageInfo package) : base(containerName, basePath, files, package) + public ContainerComponentWriter(string containerName, string basePath, Dictionary files, PackageInfo package) + : base(containerName, basePath, files, package) { } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("containerFiles") + /// Gets the name of the Collection Node ("containerFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -51,9 +48,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("Skin") + /// Gets the name of the Component Type ("Skin"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ComponentType { @@ -65,9 +62,9 @@ protected override string ComponentType /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("containerFile") + /// Gets the name of the Item Node ("containerFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -79,9 +76,9 @@ protected override string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the SkinName Node ("containerName") + /// Gets the name of the SkinName Node ("containerName"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string SkinNameNodeName { diff --git a/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs index e444475f306..65e323df8fd 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs @@ -1,40 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml; - -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Xml; + + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.UI.Skins; + /// ----------------------------------------------------------------------------- /// - /// The ContainerPackageWriter class + /// The ContainerPackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class ContainerPackageWriter : SkinPackageWriter { - public ContainerPackageWriter(PackageInfo package) : base(package) + public ContainerPackageWriter(PackageInfo package) + : base(package) { - BasePath = "Portals\\_default\\Containers\\" + SkinPackage.SkinName; + this.BasePath = "Portals\\_default\\Containers\\" + this.SkinPackage.SkinName; } - public ContainerPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) : base(skinPackage, package) + public ContainerPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) + : base(skinPackage, package) { - BasePath = "Portals\\_default\\Containers\\" + skinPackage.SkinName; + this.BasePath = "Portals\\_default\\Containers\\" + skinPackage.SkinName; } protected override void WriteFilesToManifest(XmlWriter writer) { - var containerFileWriter = new ContainerComponentWriter(SkinPackage.SkinName, BasePath, Files, Package); + var containerFileWriter = new ContainerComponentWriter(this.SkinPackage.SkinName, this.BasePath, this.Files, this.Package); containerFileWriter.WriteManifest(writer); } } diff --git a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs index 2f476ed206b..8efe1c39906 100644 --- a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs @@ -1,65 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Xml; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The FileComponentWriter class handles creating the manifest for File Component(s) + /// The FileComponentWriter class handles creating the manifest for File Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class FileComponentWriter - { - #region "Private Members" - + { private readonly string _BasePath; private readonly Dictionary _Files; private readonly PackageInfo _Package; private int _InstallOrder = Null.NullInteger; - private int _UnInstallOrder = Null.NullInteger; - - #endregion - - #region "Constructors" - + private int _UnInstallOrder = Null.NullInteger; + /// ----------------------------------------------------------------------------- - /// - /// Constructs the FileComponentWriter + /// + /// Initializes a new instance of the class. + /// Constructs the FileComponentWriter. /// - /// The Base Path for the files - /// A Dictionary of files + /// The Base Path for the files. + /// A Dictionary of files. /// Package Info. /// ----------------------------------------------------------------------------- public FileComponentWriter(string basePath, Dictionary files, PackageInfo package) { - _Files = files; - _BasePath = basePath; - _Package = package; + this._Files = files; + this._BasePath = basePath; + this._Package = package; + } + + public int InstallOrder + { + get + { + return this._InstallOrder; + } + + set + { + this._InstallOrder = value; + } } - - #endregion - - #region "Protected Properties" + public int UnInstallOrder + { + get + { + return this._UnInstallOrder; + } + + set + { + this._UnInstallOrder = value; + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("files") + /// Gets the name of the Collection Node ("files"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string CollectionNodeName { @@ -71,9 +83,9 @@ protected virtual string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("File") + /// Gets the name of the Component Type ("File"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string ComponentType { @@ -85,9 +97,9 @@ protected virtual string ComponentType /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("file") + /// Gets the name of the Item Node ("file"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string ItemNodeName { @@ -99,71 +111,77 @@ protected virtual string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the Logger + /// Gets the Logger. /// - /// A Logger + /// A Logger. /// ----------------------------------------------------------------------------- protected virtual Logger Log { get { - return _Package.Log; + return this._Package.Log; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Package + /// Gets the Package. /// - /// A PackageInfo + /// A PackageInfo. /// ----------------------------------------------------------------------------- protected virtual PackageInfo Package { get { - return _Package; + return this._Package; } - } - - #endregion - - #region "Public Properties" - - public int InstallOrder + } + + public virtual void WriteManifest(XmlWriter writer) { - get + // Start component Element + writer.WriteStartElement("component"); + writer.WriteAttributeString("type", this.ComponentType); + if (this.InstallOrder > Null.NullInteger) { - return _InstallOrder; + writer.WriteAttributeString("installOrder", this.InstallOrder.ToString()); } - set + + if (this.UnInstallOrder > Null.NullInteger) { - _InstallOrder = value; + writer.WriteAttributeString("unInstallOrder", this.UnInstallOrder.ToString()); } - } - public int UnInstallOrder - { - get + // Start files element + writer.WriteStartElement(this.CollectionNodeName); + + // Write custom manifest items + this.WriteCustomManifest(writer); + + // Write basePath Element + if (!string.IsNullOrEmpty(this._BasePath)) { - return _UnInstallOrder; + writer.WriteElementString("basePath", this._BasePath); } - set + + foreach (InstallFile file in this._Files.Values) { - _UnInstallOrder = value; + this.WriteFileElement(writer, file); } - } - - #endregion - - #region "Protected Methods" + // End files Element + writer.WriteEndElement(); + // End component Element + writer.WriteEndElement(); + } + /// ----------------------------------------------------------------------------- /// /// The WriteCustomManifest method writes the custom manifest items (that subclasses - /// of FileComponentWriter may need) + /// of FileComponentWriter may need). /// - /// The Xmlwriter to use + /// The Xmlwriter to use. /// ----------------------------------------------------------------------------- protected virtual void WriteCustomManifest(XmlWriter writer) { @@ -171,79 +189,37 @@ protected virtual void WriteCustomManifest(XmlWriter writer) protected virtual void WriteFileElement(XmlWriter writer, InstallFile file) { - Log.AddInfo(string.Format(Util.WRITER_AddFileToManifest, file.Name)); + this.Log.AddInfo(string.Format(Util.WRITER_AddFileToManifest, file.Name)); - //Start file Element - writer.WriteStartElement(ItemNodeName); + // Start file Element + writer.WriteStartElement(this.ItemNodeName); - //Write path + // Write path if (!string.IsNullOrEmpty(file.Path)) { string path = file.Path; - if (!string.IsNullOrEmpty(_BasePath)) + if (!string.IsNullOrEmpty(this._BasePath)) { - if (file.Path.ToLowerInvariant().Contains(_BasePath.ToLowerInvariant())) + if (file.Path.ToLowerInvariant().Contains(this._BasePath.ToLowerInvariant())) { - path = file.Path.ToLowerInvariant().Replace(_BasePath.ToLowerInvariant() + "\\", ""); + path = file.Path.ToLowerInvariant().Replace(this._BasePath.ToLowerInvariant() + "\\", string.Empty); } } + writer.WriteElementString("path", path); } - - //Write name + + // Write name writer.WriteElementString("name", file.Name); - //Write sourceFileName + // Write sourceFileName if (!string.IsNullOrEmpty(file.SourceFileName)) { writer.WriteElementString("sourceFileName", file.SourceFileName); } - - //Close file Element - writer.WriteEndElement(); - } - - #endregion - - #region "Public Methods" - - public virtual void WriteManifest(XmlWriter writer) - { - //Start component Element - writer.WriteStartElement("component"); - writer.WriteAttributeString("type", ComponentType); - if (InstallOrder > Null.NullInteger) - { - writer.WriteAttributeString("installOrder", InstallOrder.ToString()); - } - if (UnInstallOrder > Null.NullInteger) - { - writer.WriteAttributeString("unInstallOrder", UnInstallOrder.ToString()); - } - - //Start files element - writer.WriteStartElement(CollectionNodeName); - //Write custom manifest items - WriteCustomManifest(writer); - - //Write basePath Element - if (!string.IsNullOrEmpty(_BasePath)) - { - writer.WriteElementString("basePath", _BasePath); - } - foreach (InstallFile file in _Files.Values) - { - WriteFileElement(writer, file); - } - - //End files Element - writer.WriteEndElement(); - - //End component Element + // Close file Element writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs index f14b0cc3e96..7db83412d1d 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs @@ -1,81 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Xml; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// /// The LanguageComponentWriter class handles creating the manifest for Language - /// Component(s) + /// Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class LanguageComponentWriter : FileComponentWriter - { - #region "Private Members" - + { private readonly int _DependentPackageID; private readonly Locale _Language; - private readonly LanguagePackType _PackageType; - - #endregion - - #region "Constructors" - + private readonly LanguagePackType _PackageType; + /// ----------------------------------------------------------------------------- - /// - /// Constructs the LanguageComponentWriter + /// + /// Initializes a new instance of the class. + /// Constructs the LanguageComponentWriter. /// /// Language Info. /// Base Path. - /// A Dictionary of files + /// A Dictionary of files. /// Package Info. /// ----------------------------------------------------------------------------- - public LanguageComponentWriter(Locale language, string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) + public LanguageComponentWriter(Locale language, string basePath, Dictionary files, PackageInfo package) + : base(basePath, files, package) { - _Language = language; - _PackageType = LanguagePackType.Core; - } - + this._Language = language; + this._PackageType = LanguagePackType.Core; + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs the LanguageComponentWriter + /// + /// Initializes a new instance of the class. + /// Constructs the LanguageComponentWriter. /// /// Language Package info. /// Base Path. - /// A Dictionary of files + /// A Dictionary of files. /// Package Info. /// ----------------------------------------------------------------------------- - public LanguageComponentWriter(LanguagePackInfo languagePack, string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) + public LanguageComponentWriter(LanguagePackInfo languagePack, string basePath, Dictionary files, PackageInfo package) + : base(basePath, files, package) { - _Language = LocaleController.Instance.GetLocale(languagePack.LanguageID); - _PackageType = languagePack.PackageType; - _DependentPackageID = languagePack.DependentPackageID; - } - - #endregion - - #region "Protected Properties" - - + this._Language = LocaleController.Instance.GetLocale(languagePack.LanguageID); + this._PackageType = languagePack.PackageType; + this._DependentPackageID = languagePack.DependentPackageID; + } + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("languageFiles") + /// Gets the name of the Collection Node ("languageFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -87,15 +75,15 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("CoreLanguage/ExtensionLanguage") + /// Gets the name of the Component Type ("CoreLanguage/ExtensionLanguage"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ComponentType { get { - if (_PackageType == LanguagePackType.Core) + if (this._PackageType == LanguagePackType.Core) { return "CoreLanguage"; } @@ -108,9 +96,9 @@ protected override string ComponentType /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("languageFile") + /// Gets the name of the Item Node ("languageFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -122,26 +110,24 @@ protected override string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// The WriteCustomManifest method writes the custom manifest items + /// The WriteCustomManifest method writes the custom manifest items. /// - /// The Xmlwriter to use + /// The Xmlwriter to use. /// ----------------------------------------------------------------------------- protected override void WriteCustomManifest(XmlWriter writer) { - //Write language Elements - writer.WriteElementString("code", _Language.Code); - if (_PackageType == LanguagePackType.Core) + // Write language Elements + writer.WriteElementString("code", this._Language.Code); + if (this._PackageType == LanguagePackType.Core) { - writer.WriteElementString("displayName", _Language.Text); - writer.WriteElementString("fallback", _Language.Fallback); + writer.WriteElementString("displayName", this._Language.Text); + writer.WriteElementString("fallback", this._Language.Fallback); } else { - PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == _DependentPackageID); + PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == this._DependentPackageID); writer.WriteElementString("package", package.Name); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs index 0f650263d93..db1aa2f09fa 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs @@ -1,108 +1,95 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// - /// The LanguagePackWriter class + /// The LanguagePackWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class LanguagePackWriter : PackageWriterBase - { - #region "Private Members" - + { private bool _IsCore = Null.NullBoolean; private Locale _Language; - private LanguagePackInfo _LanguagePack; - - #endregion - - #region "Constructors" - - - public LanguagePackWriter(PackageInfo package) : base(package) + private LanguagePackInfo _LanguagePack; + + public LanguagePackWriter(PackageInfo package) + : base(package) { - _LanguagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); - if (LanguagePack != null) + this._LanguagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); + if (this.LanguagePack != null) { - _Language = LocaleController.Instance.GetLocale(_LanguagePack.LanguageID); - if (LanguagePack.PackageType == LanguagePackType.Core) + this._Language = LocaleController.Instance.GetLocale(this._LanguagePack.LanguageID); + if (this.LanguagePack.PackageType == LanguagePackType.Core) { - BasePath = Null.NullString; + this.BasePath = Null.NullString; } else { - //Get the BasePath of the Dependent Package - PackageInfo dependendentPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == LanguagePack.DependentPackageID); + // Get the BasePath of the Dependent Package + PackageInfo dependendentPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == this.LanguagePack.DependentPackageID); PackageWriterBase dependentPackageWriter = PackageWriterFactory.GetWriter(dependendentPackage); - BasePath = dependentPackageWriter.BasePath; + this.BasePath = dependentPackageWriter.BasePath; } } else { - BasePath = Null.NullString; + this.BasePath = Null.NullString; } } public LanguagePackWriter(XPathNavigator manifestNav, InstallerInfo installer) { - _Language = new Locale(); + this._Language = new Locale(); XPathNavigator cultureNav = manifestNav.SelectSingleNode("Culture"); - _Language.Text = Util.ReadAttribute(cultureNav, "DisplayName"); - _Language.Code = Util.ReadAttribute(cultureNav, "Code"); - _Language.Fallback = Localization.Localization.SystemLocale; + this._Language.Text = Util.ReadAttribute(cultureNav, "DisplayName"); + this._Language.Code = Util.ReadAttribute(cultureNav, "Code"); + this._Language.Fallback = Localization.SystemLocale; - //Create a Package - Package = new PackageInfo(installer); - Package.Name = Language.Text; - Package.FriendlyName = Language.Text; - Package.Description = Null.NullString; - Package.Version = new Version(1, 0, 0); - Package.License = Util.PACKAGE_NoLicense; + // Create a Package + this.Package = new PackageInfo(installer); + this.Package.Name = this.Language.Text; + this.Package.FriendlyName = this.Language.Text; + this.Package.Description = Null.NullString; + this.Package.Version = new Version(1, 0, 0); + this.Package.License = Util.PACKAGE_NoLicense; - ReadLegacyManifest(manifestNav); + this.ReadLegacyManifest(manifestNav); - if (_IsCore) + if (this._IsCore) { - Package.PackageType = "CoreLanguagePack"; + this.Package.PackageType = "CoreLanguagePack"; } else { - Package.PackageType = "ExtensionLanguagePack"; + this.Package.PackageType = "ExtensionLanguagePack"; } - BasePath = Null.NullString; + + this.BasePath = Null.NullString; } - public LanguagePackWriter(Locale language, PackageInfo package) : base(package) + public LanguagePackWriter(Locale language, PackageInfo package) + : base(package) { - _Language = language; - BasePath = Null.NullString; - } - - #endregion - - #region "Public Properties" - + this._Language = language; + this.BasePath = Null.NullString; + } + public override bool IncludeAssemblies { get @@ -113,37 +100,80 @@ public override bool IncludeAssemblies /// ----------------------------------------------------------------------------- /// - /// Gets the associated Language + /// Gets or sets the associated Language. /// - /// An Locale object + /// An Locale object. /// ----------------------------------------------------------------------------- public Locale Language { get { - return _Language; + return this._Language; } + set { - _Language = value; + this._Language = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the associated Language Pack + /// Gets or sets the associated Language Pack. /// - /// An LanguagePackInfo object + /// An LanguagePackInfo object. /// ----------------------------------------------------------------------------- public LanguagePackInfo LanguagePack { get { - return _LanguagePack; + return this._LanguagePack; } + set { - _LanguagePack = value; + this._LanguagePack = value; + } + } + + protected override void GetFiles(bool includeSource, bool includeAppCode) + { + // Language file starts at the root + this.ParseFolder(Path.Combine(Globals.ApplicationMapPath, this.BasePath), Globals.ApplicationMapPath); + } + + protected override void ParseFiles(DirectoryInfo folder, string rootPath) + { + if (this.LanguagePack.PackageType == LanguagePackType.Core) + { + if ((folder.FullName.ToLowerInvariant().Contains("desktopmodules") && !folder.FullName.ToLowerInvariant().Contains("admin")) || folder.FullName.ToLowerInvariant().Contains("providers")) + { + return; + } + + if (folder.FullName.ToLowerInvariant().Contains("install") && folder.FullName.ToLowerInvariant().Contains("temp")) + { + return; + } + } + + if (folder.Name.ToLowerInvariant() == "app_localresources" || folder.Name.ToLowerInvariant() == "app_globalresources" || folder.Name.ToLowerInvariant() == "_default") + { + // Add the Files in the Folder + FileInfo[] files = folder.GetFiles(); + foreach (FileInfo file in files) + { + string filePath = folder.FullName.Replace(rootPath, string.Empty); + if (filePath.StartsWith("\\")) + { + filePath = filePath.Substring(1); + } + + if (file.Name.ToLowerInvariant().Contains(this.Language.Code.ToLowerInvariant()) || (this.Language.Code.ToLowerInvariant() == "en-us" && !file.Name.Contains("-"))) + { + this.AddFile(Path.Combine(filePath, file.Name)); + } + } } } @@ -160,18 +190,18 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) resourcetype = Util.ReadAttribute(fileNav, "FileType"); moduleName = Util.ReadAttribute(fileNav, "ModuleName").ToLowerInvariant(); sourceFileName = Path.Combine(resourcetype, Path.Combine(moduleName, fileName)); - string extendedExtension = "." + Language.Code.ToLowerInvariant() + ".resx"; + string extendedExtension = "." + this.Language.Code.ToLowerInvariant() + ".resx"; switch (resourcetype) { case "GlobalResource": filePath = "App_GlobalResources"; - _IsCore = true; + this._IsCore = true; break; case "ControlResource": filePath = "Controls\\App_LocalResources"; break; case "AdminResource": - _IsCore = true; + this._IsCore = true; switch (moduleName) { case "authentication": @@ -184,10 +214,10 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\FileManager\\App_LocalResources"; break; case "host": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "authentication.ascx": - filePath = ""; + filePath = string.Empty; break; case "friendlyurls.ascx": filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; @@ -199,12 +229,13 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; break; } + break; case "lists": filePath = "DesktopModules\\Admin\\Lists\\App_LocalResources"; break; case "localization": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "languageeditor.ascx": filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; @@ -219,15 +250,16 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; break; default: - filePath = ""; + filePath = string.Empty; break; } + break; case "logging": filePath = "DesktopModules\\Admin\\LogViewer\\App_LocalResources"; break; case "moduledefinitions": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "editmodulecontrol.ascx": filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; @@ -239,9 +271,10 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; break; default: - filePath = ""; + filePath = string.Empty; break; } + break; case "modules": filePath = "Admin\\Modules\\App_LocalResources"; @@ -250,7 +283,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Extensions\\App_LocalResources"; break; case "portal": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "editportalalias.ascx": filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; @@ -277,7 +310,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\SQL\\App_LocalResources"; break; case "systemmessages.ascx": - filePath = ""; + filePath = string.Empty; break; case "template.ascx": filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; @@ -286,12 +319,13 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "Admin\\Portal\\App_LocalResources"; break; } + break; case "scheduling": filePath = "DesktopModules\\Admin\\Scheduler\\App_LocalResources"; break; case "search": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "inputsettings.ascx": filePath = "DesktopModules\\Admin\\SearchInput\\App_LocalResources"; @@ -309,15 +343,16 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\SearchResults\\App_LocalResources"; break; } + break; case "security": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "accessdenied.ascx": filePath = "Admin\\Security\\App_LocalResources"; break; case "authenticationsettings.ascx": - filePath = ""; + filePath = string.Empty; break; case "editgroups.ascx": filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; @@ -326,7 +361,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; break; case "register.ascx": - filePath = ""; + filePath = string.Empty; break; case "roles.ascx": filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; @@ -338,9 +373,10 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "Admin\\Security\\App_LocalResources"; break; case "signin.ascx": - filePath = ""; + filePath = string.Empty; break; } + break; case "skins": filePath = "Admin\\Skins\\App_LocalResources"; @@ -349,7 +385,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\FeedExplorer\\App_LocalResources"; break; case "tabs": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "export.ascx": filePath = "Admin\\Tabs\\App_LocalResources"; @@ -367,9 +403,10 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Tabs\\App_LocalResources"; break; } + break; case "users": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "bulkemail.ascx": filePath = "DesktopModules\\Admin\\Newsletters\\App_LocalResources"; @@ -409,15 +446,16 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "Admin\\Users\\App_LocalResources"; break; } + break; case "vendors": - switch (fileName.Replace(extendedExtension, "")) + switch (fileName.Replace(extendedExtension, string.Empty)) { case "adsense.ascx": - filePath = ""; + filePath = string.Empty; break; case "editadsense.ascx": - filePath = ""; + filePath = string.Empty; break; case "affiliates.ascx": filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; @@ -444,46 +482,51 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; break; } + break; } + break; case "LocalResource": filePath = Path.Combine("DesktopModules", Path.Combine(moduleName, "App_LocalResources")); - //Two assumptions are made here - //1. Core files appear in the package before extension files - //2. Module packages only include one module - if (!_IsCore && _LanguagePack == null) + + // Two assumptions are made here + // 1. Core files appear in the package before extension files + // 2. Module packages only include one module + if (!this._IsCore && this._LanguagePack == null) { - //Check if language is installed - Locale locale = LocaleController.Instance.GetLocale(_Language.Code); + // Check if language is installed + Locale locale = LocaleController.Instance.GetLocale(this._Language.Code); if (locale == null) { - LegacyError = "CoreLanguageError"; + this.LegacyError = "CoreLanguageError"; } else { - //Attempt to figure out the Extension + // Attempt to figure out the Extension foreach (KeyValuePair kvp in DesktopModuleController.GetDesktopModules(Null.NullInteger)) { if (kvp.Value.FolderName.ToLowerInvariant() == moduleName) { - //Found Module - Get Package + // Found Module - Get Package var dependentPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == kvp.Value.PackageID); - Package.Name += "_" + dependentPackage.Name; - Package.FriendlyName += " " + dependentPackage.FriendlyName; - _LanguagePack = new LanguagePackInfo(); - _LanguagePack.DependentPackageID = dependentPackage.PackageID; - _LanguagePack.LanguageID = locale.LanguageId; + this.Package.Name += "_" + dependentPackage.Name; + this.Package.FriendlyName += " " + dependentPackage.FriendlyName; + this._LanguagePack = new LanguagePackInfo(); + this._LanguagePack.DependentPackageID = dependentPackage.PackageID; + this._LanguagePack.LanguageID = locale.LanguageId; break; } } - if (_LanguagePack == null) + + if (this._LanguagePack == null) { - LegacyError = "DependencyError"; + this.LegacyError = "DependencyError"; } } } + break; case "ProviderResource": filePath = Path.Combine("Providers", Path.Combine(moduleName, "App_LocalResources")); @@ -492,68 +535,27 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "Install\\App_LocalResources"; break; } + if (!string.IsNullOrEmpty(filePath)) { - AddFile(Path.Combine(filePath, fileName), sourceFileName); + this.AddFile(Path.Combine(filePath, fileName), sourceFileName); } } - } - - #endregion - - #region "Protected methods" - - protected override void GetFiles(bool includeSource, bool includeAppCode) - { - //Language file starts at the root - ParseFolder(Path.Combine(Globals.ApplicationMapPath, BasePath), Globals.ApplicationMapPath); - } - - protected override void ParseFiles(DirectoryInfo folder, string rootPath) - { - if (LanguagePack.PackageType == LanguagePackType.Core) - { - if (folder.FullName.ToLowerInvariant().Contains("desktopmodules") && !folder.FullName.ToLowerInvariant().Contains("admin") || folder.FullName.ToLowerInvariant().Contains("providers")) - { - return; - } - if (folder.FullName.ToLowerInvariant().Contains("install") && folder.FullName.ToLowerInvariant().Contains("temp")) - { - return; - } - } - if (folder.Name.ToLowerInvariant() == "app_localresources" || folder.Name.ToLowerInvariant() == "app_globalresources" || folder.Name.ToLowerInvariant() =="_default") - { - //Add the Files in the Folder - FileInfo[] files = folder.GetFiles(); - foreach (FileInfo file in files) - { - string filePath = folder.FullName.Replace(rootPath, ""); - if (filePath.StartsWith("\\")) - { - filePath = filePath.Substring(1); - } - if (file.Name.ToLowerInvariant().Contains(Language.Code.ToLowerInvariant()) || (Language.Code.ToLowerInvariant() == "en-us" && !file.Name.Contains("-"))) - { - AddFile(Path.Combine(filePath, file.Name)); - } - } - } - } + } protected override void WriteFilesToManifest(XmlWriter writer) { LanguageComponentWriter languageFileWriter; - if (LanguagePack == null) + if (this.LanguagePack == null) { - languageFileWriter = new LanguageComponentWriter(Language, BasePath, Files, Package); + languageFileWriter = new LanguageComponentWriter(this.Language, this.BasePath, this.Files, this.Package); } else { - languageFileWriter = new LanguageComponentWriter(LanguagePack, BasePath, Files, Package); + languageFileWriter = new LanguageComponentWriter(this.LanguagePack, this.BasePath, this.Files, this.Package); } + languageFileWriter.WriteManifest(writer); - } - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs index feddfebab53..dbd6b295b88 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs @@ -1,28 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The LibraryPackageWriter class + /// The LibraryPackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class LibraryPackageWriter : PackageWriterBase { - public LibraryPackageWriter(PackageInfo package) : base(package) + public LibraryPackageWriter(PackageInfo package) + : base(package) { - BasePath = "DesktopModules\\Libraries"; - AssemblyPath = "bin"; + this.BasePath = "DesktopModules\\Libraries"; + this.AssemblyPath = "bin"; } protected override void GetFiles(bool includeSource, bool includeAppCode) diff --git a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs index 3d07542addf..0cc9226e9d3 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs @@ -1,133 +1,119 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.IO; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The ModulePackageWriter class + /// The ModulePackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class ModulePackageWriter : PackageWriterBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ModulePackageWriter)); - #region "Constructors" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageWriter)); + public ModulePackageWriter(XPathNavigator manifestNav, InstallerInfo installer) { - DesktopModule = new DesktopModuleInfo(); + this.DesktopModule = new DesktopModuleInfo(); - //Create a Package - Package = new PackageInfo(installer); + // Create a Package + this.Package = new PackageInfo(installer); - ReadLegacyManifest(manifestNav, true); + this.ReadLegacyManifest(manifestNav, true); - Package.Name = DesktopModule.ModuleName; - Package.FriendlyName = DesktopModule.FriendlyName; - Package.Description = DesktopModule.Description; - if (!string.IsNullOrEmpty(DesktopModule.Version)) + this.Package.Name = this.DesktopModule.ModuleName; + this.Package.FriendlyName = this.DesktopModule.FriendlyName; + this.Package.Description = this.DesktopModule.Description; + if (!string.IsNullOrEmpty(this.DesktopModule.Version)) { - Package.Version = new Version(DesktopModule.Version); + this.Package.Version = new Version(this.DesktopModule.Version); } - Package.PackageType = "Module"; + this.Package.PackageType = "Module"; - LegacyUtil.ParsePackageName(Package); + LegacyUtil.ParsePackageName(this.Package); - Initialize(DesktopModule.FolderName); + this.Initialize(this.DesktopModule.FolderName); } - public ModulePackageWriter(DesktopModuleInfo desktopModule, XPathNavigator manifestNav, PackageInfo package) : base(package) + public ModulePackageWriter(DesktopModuleInfo desktopModule, XPathNavigator manifestNav, PackageInfo package) + : base(package) { - DesktopModule = desktopModule; + this.DesktopModule = desktopModule; - Initialize(desktopModule.FolderName); + this.Initialize(desktopModule.FolderName); if (manifestNav != null) { - ReadLegacyManifest(manifestNav.SelectSingleNode("folders/folder"), false); + this.ReadLegacyManifest(manifestNav.SelectSingleNode("folders/folder"), false); } - string physicalFolderPath = Path.Combine(Globals.ApplicationMapPath, BasePath); - ProcessModuleFolders(physicalFolderPath, physicalFolderPath); + + string physicalFolderPath = Path.Combine(Globals.ApplicationMapPath, this.BasePath); + this.ProcessModuleFolders(physicalFolderPath, physicalFolderPath); } - public ModulePackageWriter(PackageInfo package) : base(package) + public ModulePackageWriter(PackageInfo package) + : base(package) { - DesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); - Initialize(DesktopModule.FolderName); + this.DesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); + this.Initialize(this.DesktopModule.FolderName); } - public ModulePackageWriter(DesktopModuleInfo desktopModule, PackageInfo package) : base(package) + public ModulePackageWriter(DesktopModuleInfo desktopModule, PackageInfo package) + : base(package) { - DesktopModule = desktopModule; - Initialize(desktopModule.FolderName); - } - - #endregion - - #region "Protected Properties" - + this.DesktopModule = desktopModule; + this.Initialize(desktopModule.FolderName); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the associated Desktop Module. + /// + /// A DesktopModuleInfo object. + /// ----------------------------------------------------------------------------- + public DesktopModuleInfo DesktopModule { get; set; } + protected override Dictionary Dependencies { get { var dependencies = new Dictionary(); - if (!string.IsNullOrEmpty(DesktopModule.Dependencies)) + if (!string.IsNullOrEmpty(this.DesktopModule.Dependencies)) { - dependencies["type"] = DesktopModule.Dependencies; + dependencies["type"] = this.DesktopModule.Dependencies; } - if (!string.IsNullOrEmpty(DesktopModule.Permissions)) + + if (!string.IsNullOrEmpty(this.DesktopModule.Permissions)) { - dependencies["permission"] = DesktopModule.Permissions; + dependencies["permission"] = this.DesktopModule.Permissions; } + return dependencies; } - } - - #endregion - - #region "Public Properties" - - - /// ----------------------------------------------------------------------------- - /// - /// Gets the associated Desktop Module - /// - /// A DesktopModuleInfo object - /// ----------------------------------------------------------------------------- - public DesktopModuleInfo DesktopModule { get; set; } - - #endregion - - #region "Private Methods" - - private void Initialize(string folder) + } + + protected override void WriteManifestComponent(XmlWriter writer) { - BasePath = Path.Combine("DesktopModules", folder).Replace("/", "\\"); - AppCodePath = Path.Combine("App_Code", folder).Replace("/", "\\"); - AssemblyPath = "bin"; - } + // Write Module Component + this.WriteModuleComponent(writer); + } private static void ProcessControls(XPathNavigator controlNav, string moduleFolder, ModuleDefinitionInfo definition) { @@ -136,15 +122,15 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold moduleControl.ControlKey = Util.ReadElement(controlNav, "key"); moduleControl.ControlTitle = Util.ReadElement(controlNav, "title"); - //Write controlSrc + // Write controlSrc string controlSrc = Util.ReadElement(controlNav, "src"); if (!(controlSrc.StartsWith("desktopmodules", StringComparison.InvariantCultureIgnoreCase) || !controlSrc.EndsWith(".ascx", StringComparison.InvariantCultureIgnoreCase))) { - //this code allows a developer to reference an ASCX file in a different folder than the module folder ( good for ASCX files shared between modules where you want only a single copy ) - //or it allows the developer to use webcontrols rather than usercontrols - + // this code allows a developer to reference an ASCX file in a different folder than the module folder ( good for ASCX files shared between modules where you want only a single copy ) + // or it allows the developer to use webcontrols rather than usercontrols controlSrc = Path.Combine("DesktopModules", Path.Combine(moduleFolder, controlSrc)); } + controlSrc = controlSrc.Replace('\\', '/'); moduleControl.ControlSrc = controlSrc; @@ -155,7 +141,7 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold { try { - moduleControl.ControlType = (SecurityAccessLevel) TypeDescriptor.GetConverter(typeof (SecurityAccessLevel)).ConvertFromString(controlType); + moduleControl.ControlType = (SecurityAccessLevel)TypeDescriptor.GetConverter(typeof(SecurityAccessLevel)).ConvertFromString(controlType); } catch (Exception exc) { @@ -164,17 +150,20 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold throw new Exception(Util.EXCEPTION_Type); } } + string viewOrder = Util.ReadElement(controlNav, "vieworder"); if (!string.IsNullOrEmpty(viewOrder)) { moduleControl.ViewOrder = int.Parse(viewOrder); } + moduleControl.HelpURL = Util.ReadElement(controlNav, "helpurl"); string supportsPartialRendering = Util.ReadElement(controlNav, "supportspartialrendering"); if (!string.IsNullOrEmpty(supportsPartialRendering)) { moduleControl.SupportsPartialRendering = bool.Parse(supportsPartialRendering); } + string supportsPopUps = Util.ReadElement(controlNav, "supportspopups"); if (!string.IsNullOrEmpty(supportsPopUps)) { @@ -183,27 +172,34 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold definition.ModuleControls[moduleControl.ControlKey] = moduleControl; } + + private void Initialize(string folder) + { + this.BasePath = Path.Combine("DesktopModules", folder).Replace("/", "\\"); + this.AppCodePath = Path.Combine("App_Code", folder).Replace("/", "\\"); + this.AssemblyPath = "bin"; + } private void ProcessModuleFiles(string folder, string basePath) { - //we are going to drill down through the folders to add the files + // we are going to drill down through the folders to add the files foreach (string fileName in Directory.GetFiles(folder)) { - string name = fileName.Replace(basePath + "\\", ""); - AddFile(name, name); + string name = fileName.Replace(basePath + "\\", string.Empty); + this.AddFile(name, name); } } private void ProcessModuleFolders(string folder, string basePath) { - //Process Folders recursively + // Process Folders recursively foreach (string directoryName in Directory.GetDirectories(folder)) { - ProcessModuleFolders(directoryName, basePath); + this.ProcessModuleFolders(directoryName, basePath); } - - //process files - ProcessModuleFiles(folder, basePath); + + // process files + this.ProcessModuleFiles(folder, basePath); } private void ProcessModules(XPathNavigator moduleNav, string moduleFolder) @@ -216,185 +212,185 @@ private void ProcessModules(XPathNavigator moduleNav, string moduleFolder) { definition.DefaultCacheTime = int.Parse(cacheTime); } - - //Process legacy controls Node + + // Process legacy controls Node foreach (XPathNavigator controlNav in moduleNav.Select("controls/control")) { ProcessControls(controlNav, moduleFolder, definition); } - DesktopModule.ModuleDefinitions[definition.FriendlyName] = definition; + + this.DesktopModule.ModuleDefinitions[definition.FriendlyName] = definition; } private void ReadLegacyManifest(XPathNavigator folderNav, bool processModule) { if (processModule) { - //Version 2 of legacy manifest + // Version 2 of legacy manifest string name = Util.ReadElement(folderNav, "name"); - DesktopModule.FolderName = name; - DesktopModule.ModuleName = name; - DesktopModule.FriendlyName = name; + this.DesktopModule.FolderName = name; + this.DesktopModule.ModuleName = name; + this.DesktopModule.FriendlyName = name; string folderName = Util.ReadElement(folderNav, "foldername"); if (!string.IsNullOrEmpty(folderName)) { - DesktopModule.FolderName = folderName; + this.DesktopModule.FolderName = folderName; } - if (string.IsNullOrEmpty(DesktopModule.FolderName)) + + if (string.IsNullOrEmpty(this.DesktopModule.FolderName)) { - DesktopModule.FolderName = "MyModule"; + this.DesktopModule.FolderName = "MyModule"; } + string friendlyname = Util.ReadElement(folderNav, "friendlyname"); if (!string.IsNullOrEmpty(friendlyname)) { - DesktopModule.FriendlyName = friendlyname; - DesktopModule.ModuleName = friendlyname; + this.DesktopModule.FriendlyName = friendlyname; + this.DesktopModule.ModuleName = friendlyname; } + string iconFile = Util.ReadElement(folderNav, "iconfile"); if (!string.IsNullOrEmpty(iconFile)) { - Package.IconFile = iconFile; + this.Package.IconFile = iconFile; } + string modulename = Util.ReadElement(folderNav, "modulename"); if (!string.IsNullOrEmpty(modulename)) { - DesktopModule.ModuleName = modulename; + this.DesktopModule.ModuleName = modulename; } + string permissions = Util.ReadElement(folderNav, "permissions"); if (!string.IsNullOrEmpty(permissions)) { - DesktopModule.Permissions = permissions; + this.DesktopModule.Permissions = permissions; } + string dependencies = Util.ReadElement(folderNav, "dependencies"); if (!string.IsNullOrEmpty(dependencies)) { - DesktopModule.Dependencies = dependencies; + this.DesktopModule.Dependencies = dependencies; } - DesktopModule.Version = Util.ReadElement(folderNav, "version", "01.00.00"); - DesktopModule.Description = Util.ReadElement(folderNav, "description"); - DesktopModule.BusinessControllerClass = Util.ReadElement(folderNav, "businesscontrollerclass"); + + this.DesktopModule.Version = Util.ReadElement(folderNav, "version", "01.00.00"); + this.DesktopModule.Description = Util.ReadElement(folderNav, "description"); + this.DesktopModule.BusinessControllerClass = Util.ReadElement(folderNav, "businesscontrollerclass"); - //Process legacy modules Node + // Process legacy modules Node foreach (XPathNavigator moduleNav in folderNav.Select("modules/module")) { - ProcessModules(moduleNav, DesktopModule.FolderName); + this.ProcessModules(moduleNav, this.DesktopModule.FolderName); } } - - //Process legacy files Node + + // Process legacy files Node foreach (XPathNavigator fileNav in folderNav.Select("files/file")) { string fileName = Util.ReadElement(fileNav, "name"); string filePath = Util.ReadElement(fileNav, "path"); - //In Legacy Modules the file can be physically located in the Root of the zip folder - or in the path/file location - //First test the folder + // In Legacy Modules the file can be physically located in the Root of the zip folder - or in the path/file location + // First test the folder string sourceFileName; if (filePath.Contains("[app_code]")) { - //Special case for App_code - files can be in App_Code\ModuleName or root - sourceFileName = Path.Combine(filePath, fileName).Replace("[app_code]", "App_Code\\" + DesktopModule.FolderName); + // Special case for App_code - files can be in App_Code\ModuleName or root + sourceFileName = Path.Combine(filePath, fileName).Replace("[app_code]", "App_Code\\" + this.DesktopModule.FolderName); } else { sourceFileName = Path.Combine(filePath, fileName); } - string tempFolder = Package.InstallerInfo.TempInstallFolder; + + string tempFolder = this.Package.InstallerInfo.TempInstallFolder; if (!File.Exists(Path.Combine(tempFolder, sourceFileName))) { sourceFileName = fileName; } - - //In Legacy Modules the assembly is always in "bin" - ignore the path element + + // In Legacy Modules the assembly is always in "bin" - ignore the path element if (fileName.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase)) { - AddFile("bin/" + fileName, sourceFileName); + this.AddFile("bin/" + fileName, sourceFileName); } else { - AddFile(Path.Combine(filePath, fileName), sourceFileName); + this.AddFile(Path.Combine(filePath, fileName), sourceFileName); } } - - //Process resource file Node + + // Process resource file Node if (!string.IsNullOrEmpty(Util.ReadElement(folderNav, "resourcefile"))) { - AddResourceFile(new InstallFile(Util.ReadElement(folderNav, "resourcefile"), Package.InstallerInfo)); + this.AddResourceFile(new InstallFile(Util.ReadElement(folderNav, "resourcefile"), this.Package.InstallerInfo)); } } private void WriteEventMessage(XmlWriter writer) { - //Start Start eventMessage + // Start Start eventMessage writer.WriteStartElement("eventMessage"); - //Write Processor Type + // Write Processor Type writer.WriteElementString("processorType", "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke"); - //Write Processor Type + // Write Processor Type writer.WriteElementString("processorCommand", "UpgradeModule"); - //Write Event Message Attributes + // Write Event Message Attributes writer.WriteStartElement("attributes"); - //Write businessControllerClass Attribute - writer.WriteElementString("businessControllerClass", DesktopModule.BusinessControllerClass); + // Write businessControllerClass Attribute + writer.WriteElementString("businessControllerClass", this.DesktopModule.BusinessControllerClass); - //Write businessControllerClass Attribute + // Write businessControllerClass Attribute writer.WriteElementString("desktopModuleID", "[DESKTOPMODULEID]"); - //Write upgradeVersionsList Attribute + // Write upgradeVersionsList Attribute string upgradeVersions = Null.NullString; - Versions.Sort(); - foreach (string version in Versions) + this.Versions.Sort(); + foreach (string version in this.Versions) { upgradeVersions += version + ","; } + if (upgradeVersions.Length > 1) { upgradeVersions = upgradeVersions.Remove(upgradeVersions.Length - 1, 1); } + writer.WriteElementString("upgradeVersionsList", upgradeVersions); - //End end of Event Message Attribues + // End end of Event Message Attribues writer.WriteEndElement(); - //End component Element + // End component Element writer.WriteEndElement(); } private void WriteModuleComponent(XmlWriter writer) { - //Start component Element + // Start component Element writer.WriteStartElement("component"); writer.WriteAttributeString("type", "Module"); - //Write Module Manifest - if (AppCodeFiles.Count > 0) + // Write Module Manifest + if (this.AppCodeFiles.Count > 0) { - DesktopModule.CodeSubDirectory = DesktopModule.FolderName; + this.DesktopModule.CodeSubDirectory = this.DesktopModule.FolderName; } - CBO.SerializeObject(DesktopModule, writer); + + CBO.SerializeObject(this.DesktopModule, writer); - //Write EventMessage - if (!string.IsNullOrEmpty(DesktopModule.BusinessControllerClass)) + // Write EventMessage + if (!string.IsNullOrEmpty(this.DesktopModule.BusinessControllerClass)) { - WriteEventMessage(writer); + this.WriteEventMessage(writer); } - - //End component Element - writer.WriteEndElement(); - } - - #endregion - #region "Protected Methods" - - protected override void WriteManifestComponent(XmlWriter writer) - { - //Write Module Component - WriteModuleComponent(writer); - } - - #endregion + // End component Element + writer.WriteEndElement(); + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs index 1c00426a60c..ad70e28e35e 100644 --- a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs +++ b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs @@ -1,39 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; - -using ICSharpCode.SharpZipLib.Zip; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + using ICSharpCode.SharpZipLib.Zip; + /// ----------------------------------------------------------------------------- /// - /// The PackageWriter class + /// The PackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class PackageWriterBase - { -#region "Private Members" - + { + private static readonly Regex FileVersionMatchRegex = new Regex(Util.REGEX_Version, RegexOptions.Compiled); + private readonly Dictionary _AppCodeFiles = new Dictionary(); private readonly Dictionary _Assemblies = new Dictionary(); private readonly SortedList _CleanUpFiles = new SortedList(); @@ -44,142 +38,128 @@ public class PackageWriterBase private string _BasePath = Null.NullString; private PackageInfo _Package; - private static readonly Regex FileVersionMatchRegex = new Regex(Util.REGEX_Version, RegexOptions.Compiled); - - #endregion - - #region "Constructors" - - protected PackageWriterBase() - { - } - public PackageWriterBase(PackageInfo package) { - _Package = package; - _Package.AttachInstallerInfo(new InstallerInfo()); + this._Package = package; + this._Package.AttachInstallerInfo(new InstallerInfo()); + } + + protected PackageWriterBase() + { } - - #endregion - - #region "Protected Properties" - - protected virtual Dictionary Dependencies + + /// ----------------------------------------------------------------------------- + /// + /// Gets a Dictionary of AppCodeFiles that should be included in the Package. + /// + /// A Dictionary(Of String, InstallFile). + /// ----------------------------------------------------------------------------- + public Dictionary AppCodeFiles { get { - return new Dictionary(); + return this._AppCodeFiles; } - } - - #endregion - - #region "Public Properties" - - + } + /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of AppCodeFiles that should be included in the Package + /// Gets or sets and sets the Path for the Package's app code files. /// - /// A Dictionary(Of String, InstallFile) + /// A String. /// ----------------------------------------------------------------------------- - public Dictionary AppCodeFiles + public string AppCodePath { get; set; } + + protected virtual Dictionary Dependencies { get { - return _AppCodeFiles; + return new Dictionary(); } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Path for the Package's app code files - /// - /// A String - /// ----------------------------------------------------------------------------- - public string AppCodePath { get; set; } + } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Assemblies that should be included in the Package + /// Gets a Dictionary of Assemblies that should be included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- public Dictionary Assemblies { get { - return _Assemblies; + return this._Assemblies; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Path for the Package's assemblies - /// - /// A String - /// ----------------------------------------------------------------------------- - public string AssemblyPath { get; set; } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Path for the Package's assemblies. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string AssemblyPath { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Base Path for the Package + /// Gets or sets and sets the Base Path for the Package. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string BasePath { get { - return _BasePath; + return this._BasePath; } + set { - _BasePath = value; + this._BasePath = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of CleanUpFiles that should be included in the Package + /// Gets a Dictionary of CleanUpFiles that should be included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- public SortedList CleanUpFiles { get { - return _CleanUpFiles; + return this._CleanUpFiles; } } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Files that should be included in the Package + /// Gets a Dictionary of Files that should be included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- public Dictionary Files { get { - return _Files; + return this._Files; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether a project file is found in the folder - /// - /// A String - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether a project file is found in the folder. + /// + /// A String. + /// ----------------------------------------------------------------------------- public bool HasProjectFile { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether to include Assemblies + /// Gets a value indicating whether gets whether to include Assemblies. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public virtual bool IncludeAssemblies { @@ -187,94 +167,159 @@ public virtual bool IncludeAssemblies { return true; } - } - - /// - /// Gets and sets whether there are any errors in parsing legacy packages - /// - /// - /// - /// - public string LegacyError { get; set; } + } + + /// + /// Gets or sets and sets whether there are any errors in parsing legacy packages. + /// + /// + /// And sets whether there are any errors in parsing legacy packages + /// + /// + /// + public string LegacyError { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Logger + /// Gets the Logger. /// - /// An Logger object + /// An Logger object. /// ----------------------------------------------------------------------------- public Logger Log { get { - return Package.Log; + return this.Package.Log; } } /// ----------------------------------------------------------------------------- /// - /// Gets the associated Package + /// Gets or sets the associated Package. /// - /// An PackageInfo object + /// An PackageInfo object. /// ----------------------------------------------------------------------------- public PackageInfo Package { get { - return _Package; + return this._Package; } + set { - _Package = value; + this._Package = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Resources that should be included in the Package + /// Gets a Dictionary of Resources that should be included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- public Dictionary Resources { get { - return _Resources; + return this._Resources; } } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Scripts that should be included in the Package + /// Gets a Dictionary of Scripts that should be included in the Package. /// - /// A Dictionary(Of String, InstallFile) + /// A Dictionary(Of String, InstallFile). /// ----------------------------------------------------------------------------- public Dictionary Scripts { get { - return _Scripts; + return this._Scripts; } } /// ----------------------------------------------------------------------------- /// - /// Gets a List of Versions that should be included in the Package + /// Gets a List of Versions that should be included in the Package. /// - /// A List(Of String) + /// A List(Of String). /// ----------------------------------------------------------------------------- public List Versions { get { - return _Versions; + return this._Versions; + } + } + + public static void WriteManifestEndElement(XmlWriter writer) + { + // Close packages Element + writer.WriteEndElement(); + + // Close root Element + writer.WriteEndElement(); + } + + public static void WriteManifestStartElement(XmlWriter writer) + { + // Start the new Root Element + writer.WriteStartElement("dotnetnuke"); + writer.WriteAttributeString("type", "Package"); + writer.WriteAttributeString("version", "5.0"); + + // Start packages Element + writer.WriteStartElement("packages"); + } + + public virtual void AddFile(InstallFile file) + { + switch (file.Type) + { + case InstallFileType.AppCode: + this._AppCodeFiles[file.FullName.ToLowerInvariant()] = file; + break; + case InstallFileType.Assembly: + this._Assemblies[file.FullName.ToLowerInvariant()] = file; + break; + case InstallFileType.CleanUp: + this._CleanUpFiles[file.FullName.ToLowerInvariant()] = file; + break; + case InstallFileType.Script: + this._Scripts[file.FullName.ToLowerInvariant()] = file; + break; + default: + this._Files[file.FullName.ToLowerInvariant()] = file; + break; + } + + if ((file.Type == InstallFileType.CleanUp || file.Type == InstallFileType.Script) && FileVersionMatchRegex.IsMatch(file.Name)) + { + string version = Path.GetFileNameWithoutExtension(file.Name); + if (!this._Versions.Contains(version)) + { + this._Versions.Add(version); + } } } - - #endregion - #region "Private Methods" + public void AddResourceFile(InstallFile file) + { + this._Resources[file.FullName.ToLowerInvariant()] = file; + } + + protected virtual void AddFile(string fileName) + { + this.AddFile(new InstallFile(fileName, this.Package.InstallerInfo)); + } + protected virtual void AddFile(string fileName, string sourceFileName) + { + this.AddFile(new InstallFile(fileName, sourceFileName, this.Package.InstallerInfo)); + } + private void AddFilesToZip(ZipOutputStream stream, IDictionary files, string basePath) { foreach (InstallFile packageFile in files.Values) @@ -286,17 +331,19 @@ private void AddFilesToZip(ZipOutputStream stream, IDictionary 0) + // Write Dependencies + if (this.Dependencies.Count > 0) { writer.WriteStartElement("dependencies"); - foreach (KeyValuePair kvp in Dependencies) + foreach (KeyValuePair kvp in this.Dependencies) { writer.WriteStartElement("dependency"); writer.WriteAttributeString("type", kvp.Key); writer.WriteString(kvp.Value); writer.WriteEndElement(); } + writer.WriteEndElement(); } - - //Write components Element - writer.WriteStartElement("components"); - } - - #endregion - - #region "Protected Methods" - - protected virtual void AddFile(string fileName) - { - AddFile(new InstallFile(fileName, Package.InstallerInfo)); - } - protected virtual void AddFile(string fileName, string sourceFileName) - { - AddFile(new InstallFile(fileName, sourceFileName, Package.InstallerInfo)); - } + // Write components Element + writer.WriteStartElement("components"); + } protected virtual void ConvertLegacyManifest(XPathNavigator legacyManifest, XmlWriter writer) { @@ -436,35 +471,35 @@ protected virtual void ConvertLegacyManifest(XPathNavigator legacyManifest, XmlW protected virtual void GetFiles(bool includeSource, bool includeAppCode) { - string baseFolder = Path.Combine(Globals.ApplicationMapPath, BasePath); + string baseFolder = Path.Combine(Globals.ApplicationMapPath, this.BasePath); if (Directory.Exists(baseFolder)) { - //Create the DirectoryInfo object + // Create the DirectoryInfo object var folderInfo = new DirectoryInfo(baseFolder); - //Get the Project File in the folder + // Get the Project File in the folder FileInfo[] files = folderInfo.GetFiles("*.??proj"); - if (files.Length == 0) //Assume Dynamic (App_Code based) Module + if (files.Length == 0) // Assume Dynamic (App_Code based) Module { - //Add the files in the DesktopModules Folder - ParseFolder(baseFolder, baseFolder); + // Add the files in the DesktopModules Folder + this.ParseFolder(baseFolder, baseFolder); - //Add the files in the AppCode Folder + // Add the files in the AppCode Folder if (includeAppCode) { - string appCodeFolder = Path.Combine(Globals.ApplicationMapPath, AppCodePath); - ParseFolder(appCodeFolder, appCodeFolder); + string appCodeFolder = Path.Combine(Globals.ApplicationMapPath, this.AppCodePath); + this.ParseFolder(appCodeFolder, appCodeFolder); } } - else //WAP Project File is present + else // WAP Project File is present { - HasProjectFile = true; + this.HasProjectFile = true; - //Parse the Project files (probably only one) + // Parse the Project files (probably only one) foreach (FileInfo projFile in files) { - ParseProjectFile(projFile, includeSource); + this.ParseProjectFile(projFile, includeSource); } } } @@ -472,22 +507,24 @@ protected virtual void GetFiles(bool includeSource, bool includeAppCode) protected virtual void ParseFiles(DirectoryInfo folder, string rootPath) { - //Add the Files in the Folder + // Add the Files in the Folder FileInfo[] files = folder.GetFiles(); foreach (FileInfo file in files) { - string filePath = folder.FullName.Replace(rootPath, ""); + string filePath = folder.FullName.Replace(rootPath, string.Empty); if (filePath.StartsWith("\\")) { filePath = filePath.Substring(1); } + if (folder.FullName.ToLowerInvariant().Contains("app_code")) { filePath = "[app_code]" + filePath; } + if (!file.Extension.Equals(".dnn", StringComparison.InvariantCultureIgnoreCase) && (file.Attributes & FileAttributes.Hidden) == 0) { - AddFile(Path.Combine(filePath, file.Name)); + this.AddFile(Path.Combine(filePath, file.Name)); } } } @@ -498,26 +535,26 @@ protected virtual void ParseFolder(string folderName, string rootPath) { var folder = new DirectoryInfo(folderName); - //Recursively parse the subFolders + // Recursively parse the subFolders DirectoryInfo[] subFolders = folder.GetDirectories(); foreach (DirectoryInfo subFolder in subFolders) { if ((subFolder.Attributes & FileAttributes.Hidden) == 0) { - ParseFolder(subFolder.FullName, rootPath); + this.ParseFolder(subFolder.FullName, rootPath); } } - - //Add the Files in the Folder - ParseFiles(folder, rootPath); + + // Add the Files in the Folder + this.ParseFiles(folder, rootPath); } } protected void ParseProjectFile(FileInfo projFile, bool includeSource) { - string fileName = ""; + string fileName = string.Empty; - //Create an XPathDocument from the Xml + // Create an XPathDocument from the Xml var doc = new XPathDocument(new FileStream(projFile.FullName, FileMode.Open, FileAccess.Read)); XPathNavigator rootNav = doc.CreateNavigator(); var manager = new XmlNamespaceManager(rootNav.NameTable); @@ -527,11 +564,11 @@ protected void ParseProjectFile(FileInfo projFile, bool includeSource) XPathNavigator assemblyNav = rootNav.SelectSingleNode("proj:PropertyGroup/proj:AssemblyName", manager); fileName = assemblyNav.Value; XPathNavigator buildPathNav = rootNav.SelectSingleNode("proj:PropertyGroup/proj:OutputPath", manager); - string buildPath = buildPathNav.Value.Replace("..\\", ""); - buildPath = buildPath.Replace(AssemblyPath + "\\", ""); - AddFile(Path.Combine(buildPath, fileName + ".dll")); + string buildPath = buildPathNav.Value.Replace("..\\", string.Empty); + buildPath = buildPath.Replace(this.AssemblyPath + "\\", string.Empty); + this.AddFile(Path.Combine(buildPath, fileName + ".dll")); - //Check for referenced assemblies + // Check for referenced assemblies foreach (XPathNavigator itemNav in rootNav.Select("proj:ItemGroup/proj:Reference", manager)) { fileName = Util.ReadAttribute(itemNav, "Include"); @@ -539,247 +576,191 @@ protected void ParseProjectFile(FileInfo projFile, bool includeSource) { fileName = fileName.Substring(0, fileName.IndexOf(",")); } + if ( !(fileName.StartsWith("system", StringComparison.InvariantCultureIgnoreCase) || fileName.StartsWith("microsoft", StringComparison.InvariantCultureIgnoreCase) || fileName.Equals("dotnetnuke", StringComparison.InvariantCultureIgnoreCase) || fileName.Equals("dotnetnuke.webutility", StringComparison.InvariantCultureIgnoreCase) || fileName.Equals("dotnetnuke.webcontrols", StringComparison.InvariantCultureIgnoreCase))) { - AddFile(fileName + ".dll"); + this.AddFile(fileName + ".dll"); } } - - //Add all the files that are classified as None + + // Add all the files that are classified as None foreach (XPathNavigator itemNav in rootNav.Select("proj:ItemGroup/proj:None", manager)) { fileName = Util.ReadAttribute(itemNav, "Include"); - AddFile(fileName); + this.AddFile(fileName); } - - //Add all the files that are classified as Content + + // Add all the files that are classified as Content foreach (XPathNavigator itemNav in rootNav.Select("proj:ItemGroup/proj:Content", manager)) { fileName = Util.ReadAttribute(itemNav, "Include"); - AddFile(fileName); + this.AddFile(fileName); } - - //Add all the files that are classified as Compile + + // Add all the files that are classified as Compile if (includeSource) { foreach (XPathNavigator itemNav in rootNav.Select("proj:ItemGroup/proj:Compile", manager)) { fileName = Util.ReadAttribute(itemNav, "Include"); - AddFile(fileName); + this.AddFile(fileName); } } } protected virtual void WriteFilesToManifest(XmlWriter writer) { - var fileWriter = new FileComponentWriter(BasePath, Files, Package); + var fileWriter = new FileComponentWriter(this.BasePath, this.Files, this.Package); fileWriter.WriteManifest(writer); } protected virtual void WriteManifestComponent(XmlWriter writer) { - } - - #endregion - - #region "Public Methods" - - public virtual void AddFile(InstallFile file) - { - switch (file.Type) - { - case InstallFileType.AppCode: - _AppCodeFiles[file.FullName.ToLowerInvariant()] = file; - break; - case InstallFileType.Assembly: - _Assemblies[file.FullName.ToLowerInvariant()] = file; - break; - case InstallFileType.CleanUp: - _CleanUpFiles[file.FullName.ToLowerInvariant()] = file; - break; - case InstallFileType.Script: - _Scripts[file.FullName.ToLowerInvariant()] = file; - break; - default: - _Files[file.FullName.ToLowerInvariant()] = file; - break; - } - if ((file.Type == InstallFileType.CleanUp || file.Type == InstallFileType.Script) && FileVersionMatchRegex.IsMatch(file.Name)) - { - string version = Path.GetFileNameWithoutExtension(file.Name); - if (!_Versions.Contains(version)) - { - _Versions.Add(version); - } - } - } - - public void AddResourceFile(InstallFile file) - { - _Resources[file.FullName.ToLowerInvariant()] = file; - } + } public void CreatePackage(string archiveName, string manifestName, string manifest, bool createManifest) { if (createManifest) { - WriteManifest(manifestName, manifest); + this.WriteManifest(manifestName, manifest); } - AddFile(manifestName); - CreateZipFile(archiveName); + + this.AddFile(manifestName); + this.CreateZipFile(archiveName); } public void GetFiles(bool includeSource) { - //Call protected method that does the work - GetFiles(includeSource, true); + // Call protected method that does the work + this.GetFiles(includeSource, true); } - /// - /// WriteManifest writes an existing manifest - /// - /// The name of the manifest file - /// The manifest - /// This overload takes a package manifest and writes it to a file + /// + /// WriteManifest writes an existing manifest. + /// + /// The name of the manifest file. + /// The manifest. + /// This overload takes a package manifest and writes it to a file. public void WriteManifest(string manifestName, string manifest) { - using (XmlWriter writer = XmlWriter.Create(Path.Combine(Globals.ApplicationMapPath, Path.Combine(BasePath, manifestName)), XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + using (XmlWriter writer = XmlWriter.Create(Path.Combine(Globals.ApplicationMapPath, Path.Combine(this.BasePath, manifestName)), XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) { - Log.StartJob(Util.WRITER_CreatingManifest); - WriteManifest(writer, manifest); - Log.EndJob(Util.WRITER_CreatedManifest); + this.Log.StartJob(Util.WRITER_CreatingManifest); + this.WriteManifest(writer, manifest); + this.Log.EndJob(Util.WRITER_CreatedManifest); } } /// - /// WriteManifest writes a package manifest to an XmlWriter + /// WriteManifest writes a package manifest to an XmlWriter. /// - /// The XmlWriter - /// The manifest - /// This overload takes a package manifest and writes it to a Writer + /// The XmlWriter. + /// The manifest. + /// This overload takes a package manifest and writes it to a Writer. public void WriteManifest(XmlWriter writer, string manifest) { WriteManifestStartElement(writer); writer.WriteRaw(manifest); - //Close Dotnetnuke Element + // Close Dotnetnuke Element WriteManifestEndElement(writer); - //Close Writer + // Close Writer writer.Close(); } /// - /// WriteManifest writes the manifest assoicated with this PackageWriter to a string + /// WriteManifest writes the manifest assoicated with this PackageWriter to a string. /// /// A flag that indicates whether to return the package element - /// as a fragment (True) or whether to add the outer dotnetnuke and packages elements (False) - /// The manifest as a string + /// as a fragment (True) or whether to add the outer dotnetnuke and packages elements (False). + /// The manifest as a string. /// public string WriteManifest(bool packageFragment) { - //Create a writer to create the processed manifest + // Create a writer to create the processed manifest var sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) { - WriteManifest(writer, packageFragment); - //Close XmlWriter + this.WriteManifest(writer, packageFragment); + + // Close XmlWriter writer.Close(); - //Return new manifest + + // Return new manifest return sb.ToString(); } } public void WriteManifest(XmlWriter writer, bool packageFragment) { - Log.StartJob(Util.WRITER_CreatingManifest); + this.Log.StartJob(Util.WRITER_CreatingManifest); if (!packageFragment) { - //Start dotnetnuke element + // Start dotnetnuke element WriteManifestStartElement(writer); } - - //Start package Element - WritePackageStartElement(writer); - //write Script Component - if (Scripts.Count > 0) + // Start package Element + this.WritePackageStartElement(writer); + + // write Script Component + if (this.Scripts.Count > 0) { - var scriptWriter = new ScriptComponentWriter(BasePath, Scripts, Package); + var scriptWriter = new ScriptComponentWriter(this.BasePath, this.Scripts, this.Package); scriptWriter.WriteManifest(writer); } - - //write Clean Up Files Component - if (CleanUpFiles.Count > 0) + + // write Clean Up Files Component + if (this.CleanUpFiles.Count > 0) { - var cleanupFileWriter = new CleanupComponentWriter(BasePath, CleanUpFiles); + var cleanupFileWriter = new CleanupComponentWriter(this.BasePath, this.CleanUpFiles); cleanupFileWriter.WriteManifest(writer); } - - //Write the Custom Component - WriteManifestComponent(writer); - //Write Assemblies Component - if (Assemblies.Count > 0) + // Write the Custom Component + this.WriteManifestComponent(writer); + + // Write Assemblies Component + if (this.Assemblies.Count > 0) { - var assemblyWriter = new AssemblyComponentWriter(AssemblyPath, Assemblies, Package); + var assemblyWriter = new AssemblyComponentWriter(this.AssemblyPath, this.Assemblies, this.Package); assemblyWriter.WriteManifest(writer); } - - //Write AppCode Files Component - if (AppCodeFiles.Count > 0) + + // Write AppCode Files Component + if (this.AppCodeFiles.Count > 0) { - var fileWriter = new FileComponentWriter(AppCodePath, AppCodeFiles, Package); + var fileWriter = new FileComponentWriter(this.AppCodePath, this.AppCodeFiles, this.Package); fileWriter.WriteManifest(writer); } - - //write Files Component - if (Files.Count > 0) + + // write Files Component + if (this.Files.Count > 0) { - WriteFilesToManifest(writer); + this.WriteFilesToManifest(writer); } - - //write ResourceFiles Component - if (Resources.Count > 0) + + // write ResourceFiles Component + if (this.Resources.Count > 0) { - var fileWriter = new ResourceFileComponentWriter(BasePath, Resources, Package); + var fileWriter = new ResourceFileComponentWriter(this.BasePath, this.Resources, this.Package); fileWriter.WriteManifest(writer); } - - //Close Package - WritePackageEndElement(writer); + + // Close Package + this.WritePackageEndElement(writer); if (!packageFragment) { - //Close Dotnetnuke Element + // Close Dotnetnuke Element WriteManifestEndElement(writer); } - Log.EndJob(Util.WRITER_CreatedManifest); - } - - public static void WriteManifestEndElement(XmlWriter writer) - { - //Close packages Element - writer.WriteEndElement(); - - //Close root Element - writer.WriteEndElement(); - } - - public static void WriteManifestStartElement(XmlWriter writer) - { - //Start the new Root Element - writer.WriteStartElement("dotnetnuke"); - writer.WriteAttributeString("type", "Package"); - writer.WriteAttributeString("version", "5.0"); - - //Start packages Element - writer.WriteStartElement("packages"); + + this.Log.EndJob(Util.WRITER_CreatedManifest); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs b/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs index 691119a4c9e..41e1339fda3 100644 --- a/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs +++ b/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs @@ -1,34 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common.Lists; -using DotNetNuke.Framework; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using DotNetNuke.Common.Lists; + using DotNetNuke.Framework; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// /// The PackageWriterFactory is a factory class that is used to instantiate the - /// appropriate Package Writer + /// appropriate Package Writer. /// /// /// /// ----------------------------------------------------------------------------- public class PackageWriterFactory - { - #region "Public Shared Methods" - + { /// ----------------------------------------------------------------------------- /// - /// The GetWriter method instantiates the relevant PackageWriter Installer + /// The GetWriter method instantiates the relevant PackageWriter Installer. /// - /// The associated PackageInfo instance + /// The associated PackageInfo instance. + /// /// ----------------------------------------------------------------------------- public static PackageWriterBase GetWriter(PackageInfo package) { @@ -64,20 +58,20 @@ public static PackageWriterBase GetWriter(PackageInfo package) writer = new WidgetPackageWriter(package); break; default: - //PackageType is defined in the List + // PackageType is defined in the List var listController = new ListController(); ListEntryInfo entry = listController.GetListEntryInfo("PackageWriter", package.PackageType); if (entry != null && !string.IsNullOrEmpty(entry.Text)) { - //The class for the Installer is specified in the Text property - writer = (PackageWriterBase) Reflection.CreateObject(entry.Text, "PackageWriter_" + entry.Value); + // The class for the Installer is specified in the Text property + writer = (PackageWriterBase)Reflection.CreateObject(entry.Text, "PackageWriter_" + entry.Value); } + break; } + return writer; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs index e52e278d4f3..708d3809571 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs @@ -1,29 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The ProviderPackageWriter class + /// The ProviderPackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class ProviderPackageWriter : PackageWriterBase { - public ProviderPackageWriter(PackageInfo package) : base(package) + public ProviderPackageWriter(PackageInfo package) + : base(package) { XmlDocument configDoc = Config.Load(); XPathNavigator providerNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/dotnetnuke/*/providers/add[@name='" + package.Name + "']"); @@ -32,9 +28,10 @@ public ProviderPackageWriter(PackageInfo package) : base(package) { providerPath = Util.ReadAttribute(providerNavigator, "providerPath"); } + if (!string.IsNullOrEmpty(providerPath)) { - BasePath = providerPath.Replace("~/", "").Replace("/", "\\"); + this.BasePath = providerPath.Replace("~/", string.Empty).Replace("/", "\\"); } } diff --git a/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs index bd690754a99..96c173670f3 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs @@ -1,44 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// /// The ResourceFileComponentWriter class handles creating the manifest for Resource - /// File Component(s) + /// File Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class ResourceFileComponentWriter : FileComponentWriter - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs the ResourceFileComponentWriter + /// + /// Initializes a new instance of the class. + /// Constructs the ResourceFileComponentWriter. /// - /// The Base Path for the files - /// A Dictionary of files + /// The Base Path for the files. + /// A Dictionary of files. /// /// ----------------------------------------------------------------------------- - public ResourceFileComponentWriter(string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) + public ResourceFileComponentWriter(string basePath, Dictionary files, PackageInfo package) + : base(basePath, files, package) { } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("resourceFiles") + /// Gets the name of the Collection Node ("resourceFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -50,9 +47,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("ResourceFile") + /// Gets the name of the Component Type ("ResourceFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ComponentType { @@ -64,9 +61,9 @@ protected override string ComponentType /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("resourceFile") + /// Gets the name of the Item Node ("resourceFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { diff --git a/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs index a53aa9dd0aa..0153188e681 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs @@ -1,47 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// /// The ScriptComponentWriter class handles creating the manifest for Script - /// Component(s) + /// Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class ScriptComponentWriter : FileComponentWriter - { - #region "Constructors" - - public ScriptComponentWriter(string basePath, Dictionary scripts, PackageInfo package) : base(basePath, scripts, package) + { + public ScriptComponentWriter(string basePath, Dictionary scripts, PackageInfo package) + : base(basePath, scripts, package) { - } - - #endregion - - #region "Public Properties" - - + } + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("scripts") + /// Gets the name of the Collection Node ("scripts"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -53,9 +42,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("Script") + /// Gets the name of the Component Type ("Script"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ComponentType { @@ -67,9 +56,9 @@ protected override string ComponentType /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("script") + /// Gets the name of the Item Node ("script"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -81,57 +70,55 @@ protected override string ItemNodeName protected override void WriteFileElement(XmlWriter writer, InstallFile file) { - Log.AddInfo(string.Format(Util.WRITER_AddFileToManifest, file.Name)); + this.Log.AddInfo(string.Format(Util.WRITER_AddFileToManifest, file.Name)); string type = "Install"; string version = Null.NullString; string fileName = Path.GetFileNameWithoutExtension(file.Name); - if (fileName.Equals("uninstall", StringComparison.InvariantCultureIgnoreCase)) //UnInstall.SqlDataprovider + if (fileName.Equals("uninstall", StringComparison.InvariantCultureIgnoreCase)) // UnInstall.SqlDataprovider { type = "UnInstall"; - version = Package.Version.ToString(3); + version = this.Package.Version.ToString(3); } - else if (fileName.Equals("install", StringComparison.InvariantCultureIgnoreCase)) //Install.SqlDataprovider + else if (fileName.Equals("install", StringComparison.InvariantCultureIgnoreCase)) // Install.SqlDataprovider { type = "Install"; version = new Version(0, 0, 0).ToString(3); } - else if (fileName.StartsWith("Install")) //Install.xx.xx.xx.SqlDataprovider + else if (fileName.StartsWith("Install")) // Install.xx.xx.xx.SqlDataprovider { type = "Install"; - version = fileName.Replace("Install.", ""); + version = fileName.Replace("Install.", string.Empty); } - else //xx.xx.xx.SqlDataprovider + else // xx.xx.xx.SqlDataprovider { type = "Install"; version = fileName; } - - //Start file Element - writer.WriteStartElement(ItemNodeName); + + // Start file Element + writer.WriteStartElement(this.ItemNodeName); writer.WriteAttributeString("type", type); - //Write path + // Write path if (!string.IsNullOrEmpty(file.Path)) { writer.WriteElementString("path", file.Path); } - - //Write name + + // Write name writer.WriteElementString("name", file.Name); - //'Write sourceFileName + // 'Write sourceFileName if (!string.IsNullOrEmpty(file.SourceFileName)) { writer.WriteElementString("sourceFileName", file.SourceFileName); } - - //Write Version + + // Write Version writer.WriteElementString("version", version); - //Close file Element + // Close file Element writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs index ae3c811d8cb..c421bcdbda4 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs @@ -1,58 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Xml; - -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + using System.Xml; + + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The SkinComponentWriter class handles creating the manifest for Skin Component(s) + /// The SkinComponentWriter class handles creating the manifest for Skin Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class SkinComponentWriter : FileComponentWriter - { - #region "Private Members" - - private readonly string _SkinName; - - #endregion - - #region "Constructors" - + { + private readonly string _SkinName; + /// ----------------------------------------------------------------------------- - /// - /// Constructs the SkinComponentWriter + /// + /// Initializes a new instance of the class. + /// Constructs the SkinComponentWriter. /// - /// The name of the Skin - /// The Base Path for the files - /// A Dictionary of files + /// The name of the Skin. + /// The Base Path for the files. + /// A Dictionary of files. /// Package Info. /// ----------------------------------------------------------------------------- - public SkinComponentWriter(string skinName, string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) + public SkinComponentWriter(string skinName, string basePath, Dictionary files, PackageInfo package) + : base(basePath, files, package) { - _SkinName = skinName; - } - - #endregion - - #region "Protected Properties" - + this._SkinName = skinName; + } + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("skinFiles") + /// Gets the name of the Collection Node ("skinFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -64,9 +51,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("Skin") + /// Gets the name of the Component Type ("Skin"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ComponentType { @@ -78,9 +65,9 @@ protected override string ComponentType /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("skinFile") + /// Gets the name of the Item Node ("skinFile"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -92,9 +79,9 @@ protected override string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the SkinName Node ("skinName") + /// Gets the name of the SkinName Node ("skinName"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected virtual string SkinNameNodeName { @@ -102,24 +89,18 @@ protected virtual string SkinNameNodeName { return "skinName"; } - } - - #endregion - - #region "Protected Methods" - + } + /// ----------------------------------------------------------------------------- /// /// The WriteCustomManifest method writes the custom manifest items (that subclasses - /// of FileComponentWriter may need) + /// of FileComponentWriter may need). /// - /// The Xmlwriter to use + /// The Xmlwriter to use. /// ----------------------------------------------------------------------------- protected override void WriteCustomManifest(XmlWriter writer) { - writer.WriteElementString(SkinNameNodeName, _SkinName); - } - - #endregion + writer.WriteElementString(this.SkinNameNodeName, this._SkinName); + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs index 58ddb2b3637..5dc9ca51bea 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs @@ -1,132 +1,117 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System; + using System.IO; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The SkinControlPackageWriter class + /// The SkinControlPackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class SkinControlPackageWriter : PackageWriterBase - { - #region "Constructors" - - public SkinControlPackageWriter(PackageInfo package) : base(package) + { + public SkinControlPackageWriter(PackageInfo package) + : base(package) { - SkinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); - BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", "\\"); - AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.SkinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); + this.BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", "\\"); } - public SkinControlPackageWriter(SkinControlInfo skinControl, PackageInfo package) : base(package) + public SkinControlPackageWriter(SkinControlInfo skinControl, PackageInfo package) + : base(package) { - SkinControl = skinControl; - BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", "\\"); - AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.SkinControl = skinControl; + this.BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", "\\"); } public SkinControlPackageWriter(XPathNavigator manifestNav, InstallerInfo installer) { - SkinControl = new SkinControlInfo(); - - //Create a Package - Package = new PackageInfo(installer); - - ReadLegacyManifest(manifestNav, true); - - Package.Description = Null.NullString; - Package.Version = new Version(1, 0, 0); - Package.PackageType = "SkinObject"; - Package.License = Util.PACKAGE_NoLicense; - - BasePath = Path.Combine("DesktopModules", Package.Name.ToLowerInvariant()).Replace("/", "\\"); - AppCodePath = Path.Combine("App_Code", Package.Name.ToLowerInvariant()).Replace("/", "\\"); - } - - #endregion - - #region "Public Properties" + this.SkinControl = new SkinControlInfo(); + + // Create a Package + this.Package = new PackageInfo(installer); + + this.ReadLegacyManifest(manifestNav, true); + + this.Package.Description = Null.NullString; + this.Package.Version = new Version(1, 0, 0); + this.Package.PackageType = "SkinObject"; + this.Package.License = Util.PACKAGE_NoLicense; + + this.BasePath = Path.Combine("DesktopModules", this.Package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.AppCodePath = Path.Combine("App_Code", this.Package.Name.ToLowerInvariant()).Replace("/", "\\"); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the associated SkinControl. + /// + /// A SkinControlInfo object. + /// ----------------------------------------------------------------------------- + public SkinControlInfo SkinControl { get; set; } + + protected override void WriteManifestComponent(XmlWriter writer) + { + // Start component Element + writer.WriteStartElement("component"); + writer.WriteAttributeString("type", "SkinObject"); - /// ----------------------------------------------------------------------------- - /// - /// Gets the associated SkinControl - /// - /// A SkinControlInfo object - /// ----------------------------------------------------------------------------- - public SkinControlInfo SkinControl { get; set; } - - #endregion + // Write SkinControl Manifest + CBO.SerializeObject(this.SkinControl, writer); + // End component Element + writer.WriteEndElement(); + } + private void ReadLegacyManifest(XPathNavigator legacyManifest, bool processModule) { XPathNavigator folderNav = legacyManifest.SelectSingleNode("folders/folder"); if (processModule) { - Package.Name = Util.ReadElement(folderNav, "name"); - Package.FriendlyName = Package.Name; + this.Package.Name = Util.ReadElement(folderNav, "name"); + this.Package.FriendlyName = this.Package.Name; - //Process legacy controls Node + // Process legacy controls Node foreach (XPathNavigator controlNav in folderNav.Select("modules/module/controls/control")) { - SkinControl.ControlKey = Util.ReadElement(controlNav, "key"); - SkinControl.ControlSrc = Path.Combine(Path.Combine("DesktopModules", Package.Name.ToLowerInvariant()), Util.ReadElement(controlNav, "src")).Replace("\\", "/"); + this.SkinControl.ControlKey = Util.ReadElement(controlNav, "key"); + this.SkinControl.ControlSrc = Path.Combine(Path.Combine("DesktopModules", this.Package.Name.ToLowerInvariant()), Util.ReadElement(controlNav, "src")).Replace("\\", "/"); string supportsPartialRendering = Util.ReadElement(controlNav, "supportspartialrendering"); if (!string.IsNullOrEmpty(supportsPartialRendering)) { - SkinControl.SupportsPartialRendering = bool.Parse(supportsPartialRendering); + this.SkinControl.SupportsPartialRendering = bool.Parse(supportsPartialRendering); } } } - - //Process legacy files Node + + // Process legacy files Node foreach (XPathNavigator fileNav in folderNav.Select("files/file")) { string fileName = Util.ReadElement(fileNav, "name"); string filePath = Util.ReadElement(fileNav, "path"); - AddFile(Path.Combine(filePath, fileName), fileName); + this.AddFile(Path.Combine(filePath, fileName), fileName); } - - //Process resource file Node + + // Process resource file Node if (!string.IsNullOrEmpty(Util.ReadElement(folderNav, "resourcefile"))) { - AddFile(Util.ReadElement(folderNav, "resourcefile")); + this.AddFile(Util.ReadElement(folderNav, "resourcefile")); } - } - - #region "Protected Methods" - - protected override void WriteManifestComponent(XmlWriter writer) - { - //Start component Element - writer.WriteStartElement("component"); - writer.WriteAttributeString("type", "SkinObject"); - - //Write SkinControl Manifest - CBO.SerializeObject(SkinControl, writer); - - //End component Element - writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs index 9e397f19243..5b1bbd908d0 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs @@ -1,66 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml; - -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System; + using System.IO; + using System.Xml; + + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.UI.Skins; + /// ----------------------------------------------------------------------------- /// - /// The SkinPackageWriter class + /// The SkinPackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class SkinPackageWriter : PackageWriterBase - { - #region "Private Members" - + { private readonly SkinPackageInfo _SkinPackage; - private readonly string _SubFolder; - - #endregion - - #region "Constructors" - - public SkinPackageWriter(PackageInfo package) : base(package) + private readonly string _SubFolder; + + public SkinPackageWriter(PackageInfo package) + : base(package) { - _SkinPackage = SkinController.GetSkinByPackageID(package.PackageID); - SetBasePath(); + this._SkinPackage = SkinController.GetSkinByPackageID(package.PackageID); + this.SetBasePath(); } - public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) : base(package) + public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) + : base(package) { - _SkinPackage = skinPackage; - SetBasePath(); + this._SkinPackage = skinPackage; + this.SetBasePath(); } - public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath) : base(package) + public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath) + : base(package) { - _SkinPackage = skinPackage; - BasePath = basePath; + this._SkinPackage = skinPackage; + this.BasePath = basePath; } - public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath, string subFolder) : base(package) + public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath, string subFolder) + : base(package) { - _SkinPackage = skinPackage; - _SubFolder = subFolder; - BasePath = Path.Combine(basePath, subFolder); - } - - #endregion - - #region "Protected Properties" + this._SkinPackage = skinPackage; + this._SubFolder = subFolder; + this.BasePath = Path.Combine(basePath, subFolder); + } + public override bool IncludeAssemblies { get @@ -73,51 +63,50 @@ protected SkinPackageInfo SkinPackage { get { - return _SkinPackage; + return this._SkinPackage; } - } - - #endregion - + } + public void SetBasePath() { - if (_SkinPackage.SkinType == "Skin") + if (this._SkinPackage.SkinType == "Skin") { - BasePath = Path.Combine("Portals\\_default\\Skins", SkinPackage.SkinName); + this.BasePath = Path.Combine("Portals\\_default\\Skins", this.SkinPackage.SkinName); } else { - BasePath = Path.Combine("Portals\\_default\\Containers", SkinPackage.SkinName); + this.BasePath = Path.Combine("Portals\\_default\\Containers", this.SkinPackage.SkinName); } } protected override void GetFiles(bool includeSource, bool includeAppCode) { - //Call base class method with includeAppCode = false + // Call base class method with includeAppCode = false base.GetFiles(includeSource, false); } protected override void ParseFiles(DirectoryInfo folder, string rootPath) { - //Add the Files in the Folder + // Add the Files in the Folder FileInfo[] files = folder.GetFiles(); foreach (FileInfo file in files) { - string filePath = folder.FullName.Replace(rootPath, ""); + string filePath = folder.FullName.Replace(rootPath, string.Empty); if (filePath.StartsWith("\\")) { filePath = filePath.Substring(1); } + if (!file.Extension.Equals(".dnn", StringComparison.InvariantCultureIgnoreCase)) { - if (string.IsNullOrEmpty(_SubFolder)) + if (string.IsNullOrEmpty(this._SubFolder)) { - AddFile(Path.Combine(filePath, file.Name)); + this.AddFile(Path.Combine(filePath, file.Name)); } else { filePath = Path.Combine(filePath, file.Name); - AddFile(filePath, Path.Combine(_SubFolder, filePath)); + this.AddFile(filePath, Path.Combine(this._SubFolder, filePath)); } } } @@ -125,15 +114,16 @@ protected override void ParseFiles(DirectoryInfo folder, string rootPath) protected override void WriteFilesToManifest(XmlWriter writer) { - var skinFileWriter = new SkinComponentWriter(SkinPackage.SkinName, BasePath, Files, Package); - if (SkinPackage.SkinType == "Skin") + var skinFileWriter = new SkinComponentWriter(this.SkinPackage.SkinName, this.BasePath, this.Files, this.Package); + if (this.SkinPackage.SkinType == "Skin") { - skinFileWriter = new SkinComponentWriter(SkinPackage.SkinName, BasePath, Files, Package); + skinFileWriter = new SkinComponentWriter(this.SkinPackage.SkinName, this.BasePath, this.Files, this.Package); } else { - skinFileWriter = new ContainerComponentWriter(SkinPackage.SkinName, BasePath, Files, Package); + skinFileWriter = new ContainerComponentWriter(this.SkinPackage.SkinName, this.BasePath, this.Files, this.Package); } + skinFileWriter.WriteManifest(writer); } } diff --git a/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs index 24857e3e6de..ff1c3f84dc1 100644 --- a/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs @@ -1,35 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.Collections.Generic; + + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The WidgetComponentWriter class handles creating the manifest for Widget Component(s) + /// The WidgetComponentWriter class handles creating the manifest for Widget Component(s). /// /// /// /// ----------------------------------------------------------------------------- public class WidgetComponentWriter : FileComponentWriter { - public WidgetComponentWriter(string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) + public WidgetComponentWriter(string basePath, Dictionary files, PackageInfo package) + : base(basePath, files, package) { } /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("widgetFiles") + /// Gets the name of the Collection Node ("widgetFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string CollectionNodeName { @@ -41,9 +37,9 @@ protected override string CollectionNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("widgetFiles") + /// Gets the name of the Item Node ("widgetFiles"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ItemNodeName { @@ -55,9 +51,9 @@ protected override string ItemNodeName /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Component Type ("Widget") + /// Gets the name of the Component Type ("Widget"). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- protected override string ComponentType { diff --git a/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs index 936b80325ab..46479ad1d26 100644 --- a/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs @@ -1,64 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.Xml; - -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System.IO; + using System.Xml; + + using DotNetNuke.Services.Installer.Packages; + /// ----------------------------------------------------------------------------- /// - /// The WidgetPackageWriter class + /// The WidgetPackageWriter class. /// /// /// /// ----------------------------------------------------------------------------- public class WidgetPackageWriter : PackageWriterBase - { - #region "Constructors" - - public WidgetPackageWriter(PackageInfo package) : base(package) + { + public WidgetPackageWriter(PackageInfo package) + : base(package) { string company = package.Name; - if(company.Contains(".")) + if (company.Contains(".")) { company = company.Substring(0, company.IndexOf(".")); } - BasePath = Path.Combine("Resources\\Widgets\\User", company); - } - - #endregion - - #region "Public Properties" - + this.BasePath = Path.Combine("Resources\\Widgets\\User", company); + } + public override bool IncludeAssemblies { get { return false; } - } - - #endregion - + } + protected override void GetFiles(bool includeSource, bool includeAppCode) { - //Call base class method with includeAppCode = false + // Call base class method with includeAppCode = false base.GetFiles(includeSource, false); } protected override void WriteFilesToManifest(XmlWriter writer) { - string company = Package.Name.Substring(0, Package.Name.IndexOf(".")); - var widgetFileWriter = new WidgetComponentWriter(company, Files, Package); + string company = this.Package.Name.Substring(0, this.Package.Name.IndexOf(".")); + var widgetFileWriter = new WidgetComponentWriter(company, this.Files, this.Package); widgetFileWriter.WriteManifest(writer); } } diff --git a/DNN Platform/Library/Services/Installer/XmlMerge.cs b/DNN Platform/Library/Services/Installer/XmlMerge.cs index 41be56c6355..d7f2c19d249 100644 --- a/DNN Platform/Library/Services/Installer/XmlMerge.cs +++ b/DNN Platform/Library/Services/Installer/XmlMerge.cs @@ -1,43 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Xml; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Upgrade; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Xml; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Upgrade; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// The XmlMerge class is a utility class for XmlSplicing config files + /// The XmlMerge class is a utility class for XmlSplicing config files. /// /// ----------------------------------------------------------------------------- public class XmlMerge - { - #region Private Properties - - private IDictionary _pendingDocuments; - - #endregion - - #region "Constructors" - + { + private IDictionary _pendingDocuments; + /// ----------------------------------------------------------------------------- - /// - /// Initializes a new instance of the XmlMerge class. + /// + /// Initializes a new instance of the class. /// /// /// @@ -45,15 +36,15 @@ public class XmlMerge /// ----------------------------------------------------------------------------- public XmlMerge(string sourceFileName, string version, string sender) { - Version = version; - Sender = sender; - SourceConfig = new XmlDocument { XmlResolver = null }; - SourceConfig.Load(sourceFileName); - } - + this.Version = version; + this.Sender = sender; + this.SourceConfig = new XmlDocument { XmlResolver = null }; + this.SourceConfig.Load(sourceFileName); + } + /// ----------------------------------------------------------------------------- - /// - /// Initializes a new instance of the XmlMerge class. + /// + /// Initializes a new instance of the class. /// /// /// @@ -61,15 +52,15 @@ public XmlMerge(string sourceFileName, string version, string sender) /// ----------------------------------------------------------------------------- public XmlMerge(Stream sourceStream, string version, string sender) { - Version = version; - Sender = sender; - SourceConfig = new XmlDocument { XmlResolver = null }; - SourceConfig.Load(sourceStream); - } - + this.Version = version; + this.Sender = sender; + this.SourceConfig = new XmlDocument { XmlResolver = null }; + this.SourceConfig.Load(sourceStream); + } + /// ----------------------------------------------------------------------------- - /// - /// Initializes a new instance of the XmlMerge class. + /// + /// Initializes a new instance of the class. /// /// /// @@ -77,15 +68,15 @@ public XmlMerge(Stream sourceStream, string version, string sender) /// ----------------------------------------------------------------------------- public XmlMerge(TextReader sourceReader, string version, string sender) { - Version = version; - Sender = sender; - SourceConfig = new XmlDocument { XmlResolver = null }; - SourceConfig.Load(sourceReader); - } - + this.Version = version; + this.Sender = sender; + this.SourceConfig = new XmlDocument { XmlResolver = null }; + this.SourceConfig.Load(sourceReader); + } + /// ----------------------------------------------------------------------------- - /// - /// Initializes a new instance of the XmlMerge class. + /// + /// Initializes a new instance of the class. /// /// /// @@ -93,60 +84,56 @@ public XmlMerge(TextReader sourceReader, string version, string sender) /// ----------------------------------------------------------------------------- public XmlMerge(XmlDocument sourceDoc, string version, string sender) { - Version = version; - Sender = sender; - SourceConfig = sourceDoc; - } - - #endregion - - #region "Public Properties" - + this.Version = version; + this.Sender = sender; + this.SourceConfig = sourceDoc; + } + /// ----------------------------------------------------------------------------- /// - /// Gets the Source for the Config file + /// Gets the Source for the Config file. /// - /// An XmlDocument + /// An XmlDocument. /// ----------------------------------------------------------------------------- public XmlDocument SourceConfig { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Sender (source) of the changes to be merged + /// Gets the Sender (source) of the changes to be merged. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Sender { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Target Config file + /// Gets or sets the Target Config file. /// - /// An XmlDocument + /// An XmlDocument. /// ----------------------------------------------------------------------------- public XmlDocument TargetConfig { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the File Name of the Target Config file + /// Gets the File Name of the Target Config file. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string TargetFileName { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the Version of the changes to be merged + /// Gets the Version of the changes to be merged. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Version { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets a value indicating whether the last update performed by this instance resulted in any changes + /// Gets a value indicating whether the last update performed by this instance resulted in any changes. /// - /// true if there were changes, false if no changes were made to the target document + /// true if there were changes, false if no changes were made to the target document. /// ----------------------------------------------------------------------------- public bool ConfigUpdateChangedNodes { get; private set; } @@ -154,19 +141,55 @@ public IDictionary PendingDocuments { get { - if (_pendingDocuments == null) + if (this._pendingDocuments == null) { - _pendingDocuments = new Dictionary(); + this._pendingDocuments = new Dictionary(); } - return _pendingDocuments; + return this._pendingDocuments; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The UpdateConfig method processes the source file and updates the Target + /// Config Xml Document. + /// + /// An Xml Document represent the Target Xml File. + /// ----------------------------------------------------------------------------- + public void UpdateConfig(XmlDocument target) + { + var changedAnyNodes = false; + this.TargetConfig = target; + if (this.TargetConfig != null) + { + changedAnyNodes = this.ProcessNodes(this.SourceConfig.SelectNodes("/configuration/nodes/node"), false); } - } - #endregion + this.ConfigUpdateChangedNodes = changedAnyNodes; + } - #region "Private Methods" + /// ----------------------------------------------------------------------------- + /// + /// The UpdateConfig method processes the source file and updates the Target + /// Config file. + /// + /// An Xml Document represent the Target Xml File. + /// The fileName for the Target Xml File - relative to the webroot. + /// ----------------------------------------------------------------------------- + public void UpdateConfig(XmlDocument target, string fileName) + { + var changedAnyNodes = false; + this.TargetFileName = fileName; + this.TargetConfig = target; + if (this.TargetConfig != null) + { + changedAnyNodes = this.ProcessNodes(this.SourceConfig.SelectNodes("/configuration/nodes/node"), true); + } + this.ConfigUpdateChangedNodes = changedAnyNodes; + } + private bool AddNode(XmlNode rootNode, XmlNode actionNode) { var changedNode = false; @@ -174,8 +197,8 @@ private bool AddNode(XmlNode rootNode, XmlNode actionNode) { if (child.NodeType == XmlNodeType.Element || child.NodeType == XmlNodeType.Comment) { - rootNode.AppendChild(TargetConfig.ImportNode(child, true)); - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddNode:" + child.InnerXml.ToString()); + rootNode.AppendChild(this.TargetConfig.ImportNode(child, true)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddNode:" + child.InnerXml.ToString()); changedNode = true; } } @@ -190,8 +213,8 @@ private bool PrependNode(XmlNode rootNode, XmlNode actionNode) { if (child.NodeType == XmlNodeType.Element || child.NodeType == XmlNodeType.Comment) { - rootNode.PrependChild(TargetConfig.ImportNode(child, true)); - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "PrependNode:" + child.InnerXml.ToString()); + rootNode.PrependChild(this.TargetConfig.ImportNode(child, true)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "PrependNode:" + child.InnerXml.ToString()); changedNode = true; } } @@ -209,15 +232,15 @@ private bool InsertNode(XmlNode childRootNode, XmlNode actionNode, NodeInsertTyp { if (child.NodeType == XmlNodeType.Element || child.NodeType == XmlNodeType.Comment) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InsertNode:" + child.InnerXml.ToString()); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InsertNode:" + child.InnerXml.ToString()); switch (mode) { case NodeInsertType.Before: - rootNode.InsertBefore(TargetConfig.ImportNode(child, true), childRootNode); + rootNode.InsertBefore(this.TargetConfig.ImportNode(child, true), childRootNode); changedNode = true; break; case NodeInsertType.After: - rootNode.InsertAfter(TargetConfig.ImportNode(child, true), childRootNode); + rootNode.InsertAfter(this.TargetConfig.ImportNode(child, true), childRootNode); changedNode = true; break; } @@ -231,33 +254,33 @@ private bool ProcessNode(XmlNode node, XmlNode targetRoot) { Debug.Assert(node.Attributes != null, "node.Attributes != null"); - XmlNode rootNode = FindMatchingNode(targetRoot, node, "path"); - + XmlNode rootNode = this.FindMatchingNode(targetRoot, node, "path"); + string nodeAction = node.Attributes["action"].Value.ToLowerInvariant(); - if (rootNode == null) - { - return false; //not every TargetRoot will contain every target node - } - + if (rootNode == null) + { + return false; // not every TargetRoot will contain every target node + } + switch (nodeAction) { case "add": - return AddNode(rootNode, node); + return this.AddNode(rootNode, node); case "prepend": - return PrependNode(rootNode, node); + return this.PrependNode(rootNode, node); case "insertbefore": - return InsertNode(rootNode, node, NodeInsertType.Before); + return this.InsertNode(rootNode, node, NodeInsertType.Before); case "insertafter": - return InsertNode(rootNode, node, NodeInsertType.After); + return this.InsertNode(rootNode, node, NodeInsertType.After); case "remove": - return RemoveNode(rootNode); + return this.RemoveNode(rootNode); case "removeattribute": - return RemoveAttribute(rootNode, node); + return this.RemoveAttribute(rootNode, node); case "update": - return UpdateNode(rootNode, node); + return this.UpdateNode(rootNode, node); case "updateattribute": - return UpdateAttribute(rootNode, node); + return this.UpdateAttribute(rootNode, node); default: return false; } @@ -265,31 +288,31 @@ private bool ProcessNode(XmlNode node, XmlNode targetRoot) private XmlNode FindNode(XmlNode root, string rootNodePath, XmlNamespaceManager nsmgr) { - rootNodePath = AdjustRootNodePathRelativeToLocationElements(root, rootNodePath); + rootNodePath = this.AdjustRootNodePathRelativeToLocationElements(root, rootNodePath); return root.SelectSingleNode(rootNodePath, nsmgr); } private XmlNode FindNode(XmlNode root, string rootNodePath) { - rootNodePath = AdjustRootNodePathRelativeToLocationElements(root, rootNodePath); + rootNodePath = this.AdjustRootNodePathRelativeToLocationElements(root, rootNodePath); return root.SelectSingleNode(rootNodePath); } private string AdjustRootNodePathRelativeToLocationElements(XmlNode root, string rootNodePath) { - if(root.Name != "location") + if (root.Name != "location") { return rootNodePath; } var index = rootNodePath.IndexOf("configuration"); var adjustedPath = rootNodePath.Substring(index + "configuration".Length); - adjustedPath = adjustedPath.TrimStart(new[] {'/'}); - if(String.IsNullOrEmpty(adjustedPath)) + adjustedPath = adjustedPath.TrimStart(new[] { '/' }); + if (string.IsNullOrEmpty(adjustedPath)) { adjustedPath = "."; } - + return adjustedPath; } @@ -297,61 +320,61 @@ private bool ProcessNodes(XmlNodeList nodes, bool saveConfig) { var changedNodes = false; - //The nodes definition is not correct so skip changes - if (TargetConfig != null) + // The nodes definition is not correct so skip changes + if (this.TargetConfig != null) { - //in web.config it is possible to add nodes that contain nodes that would - //otherwise be in the root node, therefore some files can have multiple roots - //making it tricky to decide where to apply the xml merge operations - var targetRoots = GetTargetRoots().ToList(); + // in web.config it is possible to add nodes that contain nodes that would + // otherwise be in the root node, therefore some files can have multiple roots + // making it tricky to decide where to apply the xml merge operations + var targetRoots = this.GetTargetRoots().ToList(); - if(targetRoots.Count == 1) + if (targetRoots.Count == 1) { var root = targetRoots[0]; foreach (XmlNode node in nodes) { - changedNodes = ProcessNode(node, root) || changedNodes; + changedNodes = this.ProcessNode(node, root) || changedNodes; } } else { foreach (XmlNode node in nodes) { - var hits = FindMatchingNodes(node, targetRoots, "path").ToList(); + var hits = this.FindMatchingNodes(node, targetRoots, "path").ToList(); - if(hits.Count == 0) + if (hits.Count == 0) { continue; } - - if(hits.Count == 1) + + if (hits.Count == 1) { - changedNodes = ProcessNode(node, hits[0]) || changedNodes; + changedNodes = this.ProcessNode(node, hits[0]) || changedNodes; } - else if(hits.Count < targetRoots.Count) + else if (hits.Count < targetRoots.Count) { - changedNodes = ProcessNode(node, hits[0]) || changedNodes; + changedNodes = this.ProcessNode(node, hits[0]) || changedNodes; } else { - //hit on all roots - XmlNode hit = FindMatchingNodes(node, hits, "targetpath").FirstOrDefault(); + // hit on all roots + XmlNode hit = this.FindMatchingNodes(node, hits, "targetpath").FirstOrDefault(); if (hit != null) { - changedNodes = ProcessNode(node, hit) || changedNodes; + changedNodes = this.ProcessNode(node, hit) || changedNodes; } else { - //all paths match at root level but no targetpaths match below that so default to the initial root - changedNodes = ProcessNode(node, hits[0]) || changedNodes; + // all paths match at root level but no targetpaths match below that so default to the initial root + changedNodes = this.ProcessNode(node, hits[0]) || changedNodes; } } } } - + if (saveConfig && changedNodes) { - Config.Save(TargetConfig, TargetFileName); + Config.Save(this.TargetConfig, this.TargetFileName); } } @@ -362,9 +385,9 @@ private IEnumerable FindMatchingNodes(XmlNode mergeNode, IEnumerable GetTargetRoots() { - yield return TargetConfig.DocumentElement; - - var locations = TargetConfig.SelectNodes("/configuration/location"); + yield return this.TargetConfig.DocumentElement; + + var locations = this.TargetConfig.SelectNodes("/configuration/location"); if (locations != null) { foreach (XmlNode node in locations) @@ -424,7 +448,7 @@ private bool RemoveAttribute(XmlNode rootNode, XmlNode actionNode) if (rootNode.Attributes[attributeName] != null) { rootNode.Attributes.Remove(rootNode.Attributes[attributeName]); - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveAttribute:attributeName=" + attributeName.ToString()); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveAttribute:attributeName=" + attributeName.ToString()); changedNode = true; } } @@ -438,14 +462,14 @@ private bool RemoveNode(XmlNode node) var changedNode = false; if (node != null) { - //Get Parent + // Get Parent XmlNode parentNode = node.ParentNode; - //Remove current Node + // Remove current Node if (parentNode != null) { parentNode.RemoveChild(node); - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveNode:" + node.InnerXml.ToString()); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveNode:" + node.InnerXml.ToString()); changedNode = true; } } @@ -465,10 +489,10 @@ private bool UpdateAttribute(XmlNode rootNode, XmlNode actionNode) string attributeValue = actionNode.Attributes["value"].Value; if (!string.IsNullOrEmpty(attributeName)) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpdateAttribute:attributeName=" + attributeName.ToString()); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateAttribute:attributeName=" + attributeName.ToString()); if (rootNode.Attributes[attributeName] == null) { - rootNode.Attributes.Append(TargetConfig.CreateAttribute(attributeName)); + rootNode.Attributes.Append(this.TargetConfig.CreateAttribute(attributeName)); changedNode = true; } @@ -489,12 +513,13 @@ private bool UpdateNode(XmlNode rootNode, XmlNode actionNode) Debug.Assert(actionNode.Attributes != null, "actionNode.Attributes != null"); var changedNode = false; - string keyAttribute = ""; + string keyAttribute = string.Empty; if (actionNode.Attributes["key"] != null) { keyAttribute = actionNode.Attributes["key"].Value; - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpdateNode: keyAttribute=" + keyAttribute.ToString()); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateNode: keyAttribute=" + keyAttribute.ToString()); } + foreach (XmlNode child in actionNode.ChildNodes) { Debug.Assert(child.Attributes != null, "child.Attributes != null"); @@ -512,36 +537,38 @@ private bool UpdateNode(XmlNode rootNode, XmlNode actionNode) } else { - targetNode = FindMatchingNode(rootNode, actionNode, "targetpath"); + targetNode = this.FindMatchingNode(rootNode, actionNode, "targetpath"); } + if (targetNode == null) { - //Since there is no collision we can just add the node - rootNode.AppendChild(TargetConfig.ImportNode(child, true)); + // Since there is no collision we can just add the node + rootNode.AppendChild(this.TargetConfig.ImportNode(child, true)); changedNode = true; continue; } - //There is a collision so we need to determine what to do. + // There is a collision so we need to determine what to do. string collisionAction = actionNode.Attributes["collision"].Value; switch (collisionAction.ToLowerInvariant()) { case "overwrite": var oldContent = rootNode.InnerXml; - rootNode.ReplaceChild(TargetConfig.ImportNode(child, true), targetNode); + rootNode.ReplaceChild(this.TargetConfig.ImportNode(child, true), targetNode); var newContent = rootNode.InnerXml; changedNode = !string.Equals(oldContent, newContent, StringComparison.Ordinal); break; case "save": - string commentHeaderText = string.Format(Localization.Localization.GetString("XMLMERGE_Upgrade", Localization.Localization.SharedResourceFile), - Environment.NewLine, - Sender, - Version, - DateTime.Now); - XmlComment commentHeader = TargetConfig.CreateComment(commentHeaderText); - - var targetNodeContent = GetNodeContentWithoutComment(targetNode); - XmlComment commentNode = TargetConfig.CreateComment(targetNodeContent); + string commentHeaderText = string.Format( + Localization.GetString("XMLMERGE_Upgrade", Localization.SharedResourceFile), + Environment.NewLine, + this.Sender, + this.Version, + DateTime.Now); + XmlComment commentHeader = this.TargetConfig.CreateComment(commentHeaderText); + + var targetNodeContent = this.GetNodeContentWithoutComment(targetNode); + XmlComment commentNode = this.TargetConfig.CreateComment(targetNodeContent); var newChild = this.TargetConfig.ImportNode(child, true); rootNode.ReplaceChild(newChild, targetNode); rootNode.InsertBefore(commentHeader, newChild); @@ -557,119 +584,74 @@ private bool UpdateNode(XmlNode rootNode, XmlNode actionNode) return changedNode; } - private string GetNodeContentWithoutComment(XmlNode node) - { - var cloneNode = node.Clone(); - RemoveCommentNodes(cloneNode); - - return cloneNode.OuterXml; - } - - private void RemoveCommentNodes(XmlNode node) - { - var commentNodes = new List(); - foreach (XmlNode childNode in node.ChildNodes) - { - if (childNode.NodeType == XmlNodeType.Comment) - { - commentNodes.Add(childNode); - } - else if (childNode.HasChildNodes) - { - RemoveCommentNodes(childNode); - } - } - - if (commentNodes.Count > 0) - { - commentNodes.ForEach(n => { node.RemoveChild(n); }); - } - } - - #endregion - - #region "Public Methods" - - - /// ----------------------------------------------------------------------------- - /// - /// The UpdateConfig method processes the source file and updates the Target - /// Config Xml Document. - /// - /// An Xml Document represent the Target Xml File - /// ----------------------------------------------------------------------------- - public void UpdateConfig(XmlDocument target) + private string GetNodeContentWithoutComment(XmlNode node) { - var changedAnyNodes = false; - TargetConfig = target; - if (TargetConfig != null) - { - changedAnyNodes = ProcessNodes(SourceConfig.SelectNodes("/configuration/nodes/node"), false); - } + var cloneNode = node.Clone(); + this.RemoveCommentNodes(cloneNode); - ConfigUpdateChangedNodes = changedAnyNodes; + return cloneNode.OuterXml; } - /// ----------------------------------------------------------------------------- - /// - /// The UpdateConfig method processes the source file and updates the Target - /// Config file. - /// - /// An Xml Document represent the Target Xml File - /// The fileName for the Target Xml File - relative to the webroot - /// ----------------------------------------------------------------------------- - public void UpdateConfig(XmlDocument target, string fileName) + private void RemoveCommentNodes(XmlNode node) { - var changedAnyNodes = false; - TargetFileName = fileName; - TargetConfig = target; - if (TargetConfig != null) + var commentNodes = new List(); + foreach (XmlNode childNode in node.ChildNodes) { - changedAnyNodes = ProcessNodes(SourceConfig.SelectNodes("/configuration/nodes/node"), true); + if (childNode.NodeType == XmlNodeType.Comment) + { + commentNodes.Add(childNode); + } + else if (childNode.HasChildNodes) + { + this.RemoveCommentNodes(childNode); + } } - ConfigUpdateChangedNodes = changedAnyNodes; - } + if (commentNodes.Count > 0) + { + commentNodes.ForEach(n => { node.RemoveChild(n); }); + } + } /// ----------------------------------------------------------------------------- /// - /// The UpdateConfigs method processes the source file and updates the various config - /// files + /// The UpdateConfigs method processes the source file and updates the various config + /// files. /// /// ----------------------------------------------------------------------------- - public void UpdateConfigs() { - UpdateConfigs(true); + this.UpdateConfigs(true); } public void UpdateConfigs(bool autoSave) { var changedAnyNodes = false; - var nodes = SourceConfig.SelectNodes("/configuration/nodes"); + var nodes = this.SourceConfig.SelectNodes("/configuration/nodes"); if (nodes != null) { foreach (XmlNode configNode in nodes) { Debug.Assert(configNode.Attributes != null, "configNode.Attributes != null"); - //Attempt to load TargetFile property from configFile Atribute - TargetFileName = configNode.Attributes["configfile"].Value; - string targetProductName = ""; + // Attempt to load TargetFile property from configFile Atribute + this.TargetFileName = configNode.Attributes["configfile"].Value; + string targetProductName = string.Empty; if (configNode.Attributes["productName"] != null) { targetProductName = configNode.Attributes["productName"].Value; } + bool isAppliedToProduct; - if (!File.Exists(Globals.ApplicationMapPath + "\\" + TargetFileName)) + if (!File.Exists(Globals.ApplicationMapPath + "\\" + this.TargetFileName)) { - DnnInstallLogger.InstallLogInfo($"Target File {TargetFileName} doesn't exist, ignore the merge process"); + DnnInstallLogger.InstallLogInfo($"Target File {this.TargetFileName} doesn't exist, ignore the merge process"); return; } - TargetConfig = Config.Load(TargetFileName); - if (String.IsNullOrEmpty(targetProductName) || targetProductName == "All") + this.TargetConfig = Config.Load(this.TargetFileName); + if (string.IsNullOrEmpty(targetProductName) || targetProductName == "All") { isAppliedToProduct = true; } @@ -677,30 +659,29 @@ public void UpdateConfigs(bool autoSave) { isAppliedToProduct = DotNetNukeContext.Current.Application.ApplyToProduct(targetProductName); } - //The nodes definition is not correct so skip changes - if (TargetConfig != null && isAppliedToProduct) + + // The nodes definition is not correct so skip changes + if (this.TargetConfig != null && isAppliedToProduct) { - var changedNodes = ProcessNodes(configNode.SelectNodes("node"), autoSave); + var changedNodes = this.ProcessNodes(configNode.SelectNodes("node"), autoSave); changedAnyNodes = changedAnyNodes || changedNodes; if (!autoSave && changedNodes) { - PendingDocuments.Add(TargetFileName, TargetConfig); + this.PendingDocuments.Add(this.TargetFileName, this.TargetConfig); } } } } - ConfigUpdateChangedNodes = changedAnyNodes; + this.ConfigUpdateChangedNodes = changedAnyNodes; } public void SavePendingConfigs() { - foreach (var key in PendingDocuments.Keys) + foreach (var key in this.PendingDocuments.Keys) { - Config.Save(PendingDocuments[key], key); + Config.Save(this.PendingDocuments[key], key); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Journal/CommentInfo.cs b/DNN Platform/Library/Services/Journal/CommentInfo.cs index 313105d2e1b..97467a4660b 100644 --- a/DNN Platform/Library/Services/Journal/CommentInfo.cs +++ b/DNN Platform/Library/Services/Journal/CommentInfo.cs @@ -1,62 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - - -namespace DotNetNuke.Services.Journal { - public class CommentInfo : IHydratable, IPropertyAccess { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.Journal +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Tokens; + + public class CommentInfo : IHydratable, IPropertyAccess + { public int CommentId { get; set; } + public int JournalId { get; set; } + public string Comment { get; set; } + public DateTime DateCreated { get; set; } + public DateTime DateUpdated { get; set; } + public XmlDocument CommentXML { get; set; } + public int UserId { get; set; } + public string DisplayName { get; set; } - - - public int KeyID { - get { - return CommentId; + + public int KeyID + { + get + { + return this.CommentId; } - set { - CommentId = value; + + set + { + this.CommentId = value; } } - - public void Fill(System.Data.IDataReader dr) { - CommentId = Null.SetNullInteger(dr["CommentId"]); - JournalId = Null.SetNullInteger(dr["JournalId"]); - Comment = Null.SetNullString(dr["Comment"]); - DateCreated = Null.SetNullDateTime(dr["DateCreated"]); - DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); - if (!String.IsNullOrEmpty(Null.SetNullString(dr["CommentXML"]))) { - CommentXML = new XmlDocument { XmlResolver = null }; - CommentXML.LoadXml(dr["CommentXML"].ToString()); - } - UserId = Null.SetNullInteger(dr["UserId"]); - DisplayName = Null.SetNullString(dr["DisplayName"]); - + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } } - public CacheLevel Cacheability { - get { - return CacheLevel.fullyCacheable; + public void Fill(System.Data.IDataReader dr) + { + this.CommentId = Null.SetNullInteger(dr["CommentId"]); + this.JournalId = Null.SetNullInteger(dr["JournalId"]); + this.Comment = Null.SetNullString(dr["Comment"]); + this.DateCreated = Null.SetNullDateTime(dr["DateCreated"]); + this.DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); + if (!string.IsNullOrEmpty(Null.SetNullString(dr["CommentXML"]))) + { + this.CommentXML = new XmlDocument { XmlResolver = null }; + this.CommentXML.LoadXml(dr["CommentXML"].ToString()); } - + + this.UserId = Null.SetNullInteger(dr["UserId"]); + this.DisplayName = Null.SetNullString(dr["DisplayName"]); } - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { + public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { throw new NotImplementedException(); } } diff --git a/DNN Platform/Library/Services/Journal/Content.cs b/DNN Platform/Library/Services/Journal/Content.cs index 93d2b127f48..a01489a1900 100644 --- a/DNN Platform/Library/Services/Journal/Content.cs +++ b/DNN Platform/Library/Services/Journal/Content.cs @@ -1,63 +1,98 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content; -using DotNetNuke.Common.Utilities; - -namespace DotNetNuke.Services.Journal { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.Journal +{ + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + + public class Content + { + /// + /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. + /// + /// The primary key value (ContentTypeID) from the core API's Content Types table. + internal static int GetContentTypeID(string ContentTypeName) + { + var typeController = new ContentTypeController(); + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t; + int contentTypeId; - public class Content { + if (colContentTypes.Count() > 0) + { + var contentType = colContentTypes.Single(); + contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; + } + else + { + contentTypeId = CreateContentType(ContentTypeName); + } + return contentTypeId; + } + /// - /// This should only run after the Post exists in the data store. + /// This should only run after the Post exists in the data store. /// /// The newly created ContentItemID from the data store. /// This is for the first question in the thread. Not for replies or items with ParentID > 0. - internal ContentItem CreateContentItem(JournalItem objJournalItem, int tabId, int moduleId) { + internal ContentItem CreateContentItem(JournalItem objJournalItem, int tabId, int moduleId) + { var typeController = new ContentTypeController(); string contentTypeName = "DNNCorp_JournalProfile"; - if (objJournalItem.SocialGroupId > 0) { + if (objJournalItem.SocialGroupId > 0) + { contentTypeName = "DNNCorp_JournalGroup"; } - var colContentTypes = (from t in typeController.GetContentTypes() where t.ContentType == contentTypeName select t); + + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == contentTypeName select t; int contentTypeID; - if (colContentTypes.Count() > 0) { + if (colContentTypes.Count() > 0) + { var contentType = colContentTypes.Single(); contentTypeID = contentType == null ? CreateContentType(contentTypeName) : contentType.ContentTypeId; - } else { + } + else + { contentTypeID = CreateContentType(contentTypeName); } - - var objContent = new ContentItem { - Content = GetContentBody(objJournalItem), + + var objContent = new ContentItem + { + Content = GetContentBody(objJournalItem), ContentTypeId = contentTypeID, Indexed = false, ContentKey = "journalid=" + objJournalItem.JournalId, ModuleID = moduleId, - TabID = tabId + TabID = tabId, }; objContent.ContentItemId = Util.GetContentController().AddContentItem(objContent); // Add Terms - //var cntTerm = new Terms(); - //cntTerm.ManageQuestionTerms(objPost, objContent); - + // var cntTerm = new Terms(); + // cntTerm.ManageQuestionTerms(objPost, objContent); return objContent; } /// /// This is used to update the content in the ContentItems table. Should be called when a question is updated. /// - internal void UpdateContentItem(JournalItem objJournalItem, int tabId, int moduleId) { + internal void UpdateContentItem(JournalItem objJournalItem, int tabId, int moduleId) + { var objContent = Util.GetContentController().GetContentItem(objJournalItem.ContentItemId); - if (objContent == null) return; - //Only update content the contentitem if it was created by the journal + if (objContent == null) + { + return; + } + + // Only update content the contentitem if it was created by the journal if ((objContent.ContentTypeId == GetContentTypeID("DNNCorp_JournalProfile") && objJournalItem.ProfileId > 0) || (objContent.ContentTypeId == GetContentTypeID("DNNCorp_JournalGroup") && objJournalItem.SocialGroupId > 0)) { @@ -68,77 +103,70 @@ internal void UpdateContentItem(JournalItem objJournalItem, int tabId, int modul Util.GetContentController().UpdateContentItem(objContent); } - - + // Update Terms - //var cntTerm = new Terms(); - //cntTerm.ManageQuestionTerms(objPost, objContent); + // var cntTerm = new Terms(); + // cntTerm.ManageQuestionTerms(objPost, objContent); } /// /// This removes a content item associated with a question/thread from the data store. Should run every time an entire thread is deleted. /// /// - internal void DeleteContentItem(int contentItemID) { - if (contentItemID <= Null.NullInteger) return; + internal void DeleteContentItem(int contentItemID) + { + if (contentItemID <= Null.NullInteger) + { + return; + } + var objContent = Util.GetContentController().GetContentItem(contentItemID); - if (objContent == null) return; - - // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) - //var cntTerms = new Terms(); - //cntTerms.RemoveQuestionTerms(objContent); - + if (objContent == null) + { + return; + } + + // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) + // var cntTerms = new Terms(); + // cntTerms.RemoveQuestionTerms(objContent); Util.GetContentController().DeleteContentItem(objContent); } - - /// - /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. - /// - /// The primary key value (ContentTypeID) from the core API's Content Types table. - internal static int GetContentTypeID(string ContentTypeName) { - var typeController = new ContentTypeController(); - var colContentTypes = (from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t); - int contentTypeId; - - if (colContentTypes.Count() > 0) { - var contentType = colContentTypes.Single(); - contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; - } else { - contentTypeId = CreateContentType(ContentTypeName); - } - - return contentTypeId; - } - - #region Private Methods - + /// /// Creates a Content Type (for taxonomy) in the data store. /// /// The primary key value of the new ContentType. - private static int CreateContentType(string ContentTypeName) { + private static int CreateContentType(string ContentTypeName) + { var typeController = new ContentTypeController(); var objContentType = new ContentType { ContentType = ContentTypeName }; return typeController.AddContentType(objContentType); } + /// - /// Creates the content text + /// Creates the content text. /// /// /// - private static string GetContentBody(JournalItem objJournalItem) { - if (!string.IsNullOrEmpty(objJournalItem.Title)) { + private static string GetContentBody(JournalItem objJournalItem) + { + if (!string.IsNullOrEmpty(objJournalItem.Title)) + { return objJournalItem.Title; - } else if (!string.IsNullOrEmpty(objJournalItem.Summary)) { + } + else if (!string.IsNullOrEmpty(objJournalItem.Summary)) + { return objJournalItem.Summary; - } else if (!string.IsNullOrEmpty(objJournalItem.Body)) { + } + else if (!string.IsNullOrEmpty(objJournalItem.Body)) + { return objJournalItem.Body; - } else { + } + else + { return null; } - } - #endregion - + } } } diff --git a/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs b/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs index 59cca9f6c85..a03669707ac 100644 --- a/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs +++ b/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Journal { + using System; + using System.Data; + public interface IJournalDataService { IDataReader Journal_ListForSummary(int portalId, int moduleId, int currentUserId, int rowIndex, int maxRows); @@ -34,16 +29,22 @@ IDataReader Journal_ListForGroup(int portalId, int moduleId, int currentUserId, void Journal_SoftDeleteByGroupId(int portalId, int groupId); IDataReader Journal_Get(int portalId, int currentUserId, int journalId); + IDataReader Journal_Get(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck); + IDataReader Journal_GetByKey(int portalId, string objectKey); + IDataReader Journal_GetByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted); + int Journal_Save(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet); + int Journal_Save(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet, bool commentsHidden, bool commentsDisabled); int Journal_Update(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet); + int Journal_Update(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet, bool commentsHidden, bool commentsDisabled); @@ -66,7 +67,9 @@ int Journal_Update(int portalId, int currentUserId, int profileId, int groupId, void Journal_Comment_Like(int journalId, int commentId, int userId, string displayName); IDataReader Journal_Comment_LikeList(int portalId, int journalId, int commentId); + void Journal_Comments_ToggleDisable(int portalId, int journalId, bool disable); + void Journal_Comments_ToggleHidden(int portalId, int journalId, bool hidden); IDataReader Journal_Types_List(int portalId); diff --git a/DNN Platform/Library/Services/Journal/Data/JournalDataService.cs b/DNN Platform/Library/Services/Journal/Data/JournalDataService.cs index ffb7983c30b..c15ac573bb4 100644 --- a/DNN Platform/Library/Services/Journal/Data/JournalDataService.cs +++ b/DNN Platform/Library/Services/Journal/Data/JournalDataService.cs @@ -1,19 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Xml; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content; -using DotNetNuke.Framework; - -#endregion - -namespace DotNetNuke.Services.Journal { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Journal +{ + using System; + using System.IO; + using System.Xml; + + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Framework; + public class JournalDataService : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs b/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs index dc2a80c5490..6a8e059cf3c 100644 --- a/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs +++ b/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs @@ -1,198 +1,207 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Journal { + using System; + using System.Data; + + using DotNetNuke.Data; + internal class JournalDataServiceImpl : IJournalDataService { - private readonly DataProvider _provider = DataProvider.Instance(); - - #region IJournalDataService Members - + private readonly DataProvider _provider = DataProvider.Instance(); + public IDataReader Journal_ListForSummary(int portalId, int moduleId, int currentUserId, int rowIndex, int maxRows) { - return _provider.ExecuteReader("Journal_ListForSummary", portalId, moduleId, currentUserId, rowIndex, + return this._provider.ExecuteReader("Journal_ListForSummary", portalId, moduleId, currentUserId, rowIndex, maxRows); } public IDataReader Journal_ListForProfile(int portalId, int moduleId, int currentUserId, int profileId, int rowIndex, int maxRows) { - return _provider.ExecuteReader("Journal_ListForProfile", portalId, moduleId, currentUserId, profileId, + return this._provider.ExecuteReader("Journal_ListForProfile", portalId, moduleId, currentUserId, profileId, rowIndex, maxRows); } public IDataReader Journal_ListForGroup(int portalId, int moduleId, int currentUserId, int groupId, int rowIndex, int maxRows) { - return _provider.ExecuteReader("Journal_ListForGroup", portalId, moduleId, currentUserId, groupId, rowIndex, + return this._provider.ExecuteReader("Journal_ListForGroup", portalId, moduleId, currentUserId, groupId, rowIndex, maxRows); } public void Journal_Delete(int journalId) { - _provider.ExecuteNonQuery("Journal_Delete", journalId); + this._provider.ExecuteNonQuery("Journal_Delete", journalId); } public void Journal_DeleteByKey(int portalId, string objectKey) { - _provider.ExecuteNonQuery("Journal_DeleteByKey", portalId, objectKey); + this._provider.ExecuteNonQuery("Journal_DeleteByKey", portalId, objectKey); } public void Journal_DeleteByGroupId(int portalId, int groupId) { - _provider.ExecuteNonQuery("Journal_DeleteByGroupId", portalId, groupId); + this._provider.ExecuteNonQuery("Journal_DeleteByGroupId", portalId, groupId); } public void Journal_SoftDelete(int journalId) { - _provider.ExecuteNonQuery("Journal_Delete", journalId, true); + this._provider.ExecuteNonQuery("Journal_Delete", journalId, true); } - + public void Journal_SoftDeleteByKey(int portalId, string objectKey) { - _provider.ExecuteNonQuery("Journal_DeleteByKey", portalId, objectKey, true); + this._provider.ExecuteNonQuery("Journal_DeleteByKey", portalId, objectKey, true); } - + public void Journal_SoftDeleteByGroupId(int portalId, int groupId) { - _provider.ExecuteNonQuery("Journal_DeleteByGroupId", portalId, groupId, true); + this._provider.ExecuteNonQuery("Journal_DeleteByGroupId", portalId, groupId, true); } - + public void Journal_Like(int journalId, int userId, string displayName) { - _provider.ExecuteNonQuery("Journal_Like", journalId, userId, displayName); + this._provider.ExecuteNonQuery("Journal_Like", journalId, userId, displayName); } public IDataReader Journal_LikeList(int portalId, int journalId) { - return _provider.ExecuteReader("Journal_LikeList", portalId, journalId); + return this._provider.ExecuteReader("Journal_LikeList", portalId, journalId); } public void Journal_UpdateContentItemId(int journalId, int contentItemId) { - _provider.ExecuteNonQuery("Journal_UpdateContentItemId", journalId, contentItemId); + this._provider.ExecuteNonQuery("Journal_UpdateContentItemId", journalId, contentItemId); } - public IDataReader Journal_Get(int portalId, int currentUserId, int journalId) + + public IDataReader Journal_Get(int portalId, int currentUserId, int journalId) { - return Journal_Get(portalId, currentUserId, journalId, false, false, false); + return this.Journal_Get(portalId, currentUserId, journalId, false, false, false); } + public IDataReader Journal_Get(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck) { - return _provider.ExecuteReader("Journal_Get", portalId, currentUserId, journalId, includeAllItems, isDeleted, securityCheck); + return this._provider.ExecuteReader("Journal_Get", portalId, currentUserId, journalId, includeAllItems, isDeleted, securityCheck); } - public IDataReader Journal_GetByKey(int portalId, string objectKey) { - return Journal_GetByKey(portalId, objectKey, false, false); + + public IDataReader Journal_GetByKey(int portalId, string objectKey) + { + return this.Journal_GetByKey(portalId, objectKey, false, false); } + public IDataReader Journal_GetByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted) { - return _provider.ExecuteReader("Journal_GetByKey", portalId, objectKey, includeAllItems, isDeleted); + return this._provider.ExecuteReader("Journal_GetByKey", portalId, objectKey, includeAllItems, isDeleted); } + public int Journal_Save(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, - string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet) - { - journalId = _provider.ExecuteScalar("Journal_Save", portalId, journalId, journalTypeId, currentUserId, profileId, + string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet) + { + journalId = this._provider.ExecuteScalar("Journal_Save", portalId, journalId, journalTypeId, currentUserId, profileId, groupId, title, summary, itemData, xml, objectKey, accessKey, securitySet, false, false); - return journalId; - } + return journalId; + } + public int Journal_Save(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet, bool commentsDisabled, bool commentsHidden) { - journalId = _provider.ExecuteScalar("Journal_Save", portalId, journalId, journalTypeId, currentUserId, profileId, + journalId = this._provider.ExecuteScalar("Journal_Save", portalId, journalId, journalTypeId, currentUserId, profileId, groupId, title, summary, itemData, xml, objectKey, accessKey, securitySet, commentsDisabled, commentsHidden); return journalId; } + public int Journal_Update(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet) { - journalId = _provider.ExecuteScalar("Journal_Update", portalId, journalId, journalTypeId, currentUserId, profileId, + journalId = this._provider.ExecuteScalar("Journal_Update", portalId, journalId, journalTypeId, currentUserId, profileId, groupId, title, summary, itemData, xml, objectKey, accessKey, securitySet, false, false); return journalId; } + public int Journal_Update(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet, bool commentsDisabled, bool commentsHidden) { - journalId = _provider.ExecuteScalar("Journal_Update", portalId, journalId, journalTypeId, currentUserId, profileId, + journalId = this._provider.ExecuteScalar("Journal_Update", portalId, journalId, journalTypeId, currentUserId, profileId, groupId, title, summary, itemData, xml, objectKey, accessKey, securitySet, commentsDisabled, commentsHidden); return journalId; } - public void Journal_Comment_Delete(int journalId, int commentId) { - _provider.ExecuteNonQuery("Journal_Comment_Delete", journalId, commentId); + + public void Journal_Comment_Delete(int journalId, int commentId) + { + this._provider.ExecuteNonQuery("Journal_Comment_Delete", journalId, commentId); } public int Journal_Comment_Save(int journalId, int commentId, int userId, string comment, string xml, DateTime dateUpdated) { - commentId = _provider.ExecuteScalar("Journal_Comment_Save", journalId, commentId, userId, comment, xml, DataProvider.Instance().GetNull(dateUpdated)); + commentId = this._provider.ExecuteScalar("Journal_Comment_Save", journalId, commentId, userId, comment, xml, DataProvider.Instance().GetNull(dateUpdated)); return commentId; } - + public IDataReader Journal_Comment_List(int journalId) { - return _provider.ExecuteReader("Journal_Comment_List", journalId); + return this._provider.ExecuteReader("Journal_Comment_List", journalId); } public IDataReader Journal_Comment_Get(int commentId) { - return _provider.ExecuteReader("Journal_Comment_Get", commentId); + return this._provider.ExecuteReader("Journal_Comment_Get", commentId); } public IDataReader Journal_Comment_ListByJournalIds(string journalIds) { - return _provider.ExecuteReader("Journal_Comment_ListByJournalIds", journalIds); + return this._provider.ExecuteReader("Journal_Comment_ListByJournalIds", journalIds); } public void Journal_Comment_Like(int journalId, int commentId, int userId, string displayName) { - _provider.ExecuteNonQuery("Journal_Comment_Like", journalId, commentId, userId, displayName); + this._provider.ExecuteNonQuery("Journal_Comment_Like", journalId, commentId, userId, displayName); } - public IDataReader Journal_Comment_LikeList(int portalId, int journalId, int commentId) { - return _provider.ExecuteReader("Journal_Comment_LikeList", portalId, journalId, commentId); + + public IDataReader Journal_Comment_LikeList(int portalId, int journalId, int commentId) + { + return this._provider.ExecuteReader("Journal_Comment_LikeList", portalId, journalId, commentId); } + public void Journal_Comments_ToggleDisable(int portalId, int journalId, bool disable) { - _provider.ExecuteNonQuery("Journal_Comments_ToggleDisable", portalId, journalId, disable); + this._provider.ExecuteNonQuery("Journal_Comments_ToggleDisable", portalId, journalId, disable); } public void Journal_Comments_ToggleHidden(int portalId, int journalId, bool hidden) { - _provider.ExecuteNonQuery("Journal_Comments_ToggleHidden", portalId, journalId, hidden); + this._provider.ExecuteNonQuery("Journal_Comments_ToggleHidden", portalId, journalId, hidden); } - public IDataReader Journal_Types_List(int portalId) { - return _provider.ExecuteReader("Journal_Types_List", portalId); + + public IDataReader Journal_Types_List(int portalId) + { + return this._provider.ExecuteReader("Journal_Types_List", portalId); } public IDataReader Journal_Types_GetById(int journalTypeId) { - return _provider.ExecuteReader("Journal_Types_GetById", journalTypeId); + return this._provider.ExecuteReader("Journal_Types_GetById", journalTypeId); } public IDataReader Journal_Types_Get(string journalType) { - return _provider.ExecuteReader("Journal_Types_Get", journalType); + return this._provider.ExecuteReader("Journal_Types_Get", journalType); } public void Journal_Types_Delete(int journalTypeId, int portalId) { - _provider.ExecuteNonQuery("Journal_Types_Delete", journalTypeId, portalId); + this._provider.ExecuteNonQuery("Journal_Types_Delete", journalTypeId, portalId); } public int Journal_Types_Save(int journalTypeId, string journalType, string icon, int portalId, bool isEnabled, bool appliesToProfile, bool appliesToGroup, bool appliesToStream, string options, bool supportsNotify) { - journalTypeId = _provider.ExecuteScalar("Journal_Types_Save", journalTypeId, journalType, icon, + journalTypeId = this._provider.ExecuteScalar("Journal_Types_Save", journalTypeId, journalType, icon, portalId, isEnabled, appliesToProfile, appliesToGroup, appliesToStream, options, supportsNotify); return journalTypeId; @@ -200,24 +209,22 @@ public int Journal_Types_Save(int journalTypeId, string journalType, string icon public IDataReader Journal_GetStatsForGroup(int portalId, int groupId) { - return _provider.ExecuteReader("Journal_GetStatsForGroup", portalId, groupId); + return this._provider.ExecuteReader("Journal_GetStatsForGroup", portalId, groupId); } public IDataReader Journal_TypeFilters_List(int portalId, int moduleId) { - return _provider.ExecuteReader("Journal_TypeFilters_List", portalId, moduleId); + return this._provider.ExecuteReader("Journal_TypeFilters_List", portalId, moduleId); } public void Journal_TypeFilters_Delete(int portalId, int moduleId) { - _provider.ExecuteNonQuery("Journal_TypeFilters_Delete", portalId, moduleId); + this._provider.ExecuteNonQuery("Journal_TypeFilters_Delete", portalId, moduleId); } public void Journal_TypeFilters_Save(int portalId, int moduleId, int journalTypeId) { - _provider.ExecuteNonQuery("Journal_TypeFilters_Save", portalId, moduleId, journalTypeId); - } - - #endregion + this._provider.ExecuteNonQuery("Journal_TypeFilters_Save", portalId, moduleId, journalTypeId); + } } } diff --git a/DNN Platform/Library/Services/Journal/IJournalController.cs b/DNN Platform/Library/Services/Journal/IJournalController.cs index 8d3fcf216dc..5b9f447b638 100644 --- a/DNN Platform/Library/Services/Journal/IJournalController.cs +++ b/DNN Platform/Library/Services/Journal/IJournalController.cs @@ -1,25 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Journal { + using System; + using System.Collections.Generic; + using System.IO; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + public interface IJournalController { // Journal Items + /// /// Get journal type by name. /// /// type name. /// Journal type object. - /// + /// JournalTypeInfo GetJournalType(string journalType); /// @@ -27,7 +29,7 @@ public interface IJournalController /// /// Type id. /// Journal type object. - /// + /// JournalTypeInfo GetJournalTypeById(int journalTypeId); /// @@ -36,7 +38,7 @@ public interface IJournalController /// Id of portal. /// The object key. /// Journal object. - /// + /// JournalItem GetJournalItemByKey(int portalId, string objectKey); /// @@ -46,7 +48,7 @@ public interface IJournalController /// The object key. /// Whether include deleted items. /// - /// + /// JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems); /// @@ -57,7 +59,7 @@ public interface IJournalController /// Whether include deleted items. /// Whether get deleted item. /// - /// + /// JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted); /// @@ -67,7 +69,7 @@ public interface IJournalController /// Id of current user, if securityCheck set as True, will check whether this user has permission to view the journal. /// Id of Journal. /// Journal Object. - /// + /// JournalItem GetJournalItem(int portalId, int userId, int journalId); /// @@ -78,7 +80,7 @@ public interface IJournalController /// Id of Journal. /// Whether include deleted items. /// Journal Object. - /// + /// JournalItem GetJournalItem(int portalId, int userId, int journalId, bool includeAllItems); /// @@ -90,7 +92,7 @@ public interface IJournalController /// Whether include deleted items. /// Whether get deleted item. /// Journal Object. - /// + /// JournalItem GetJournalItem(int portalId, int userId, int journalId, bool includeAllItems, bool isDeleted); /// @@ -103,9 +105,9 @@ public interface IJournalController /// Whether get deleted item. /// Whether check current user has permission to get journal. /// Journal Object. - /// + /// JournalItem GetJournalItem(int portalId, int userId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck); - + /// /// Get all journal types in portal. /// @@ -114,22 +116,21 @@ public interface IJournalController IEnumerable GetJournalTypes(int portalId); /// - /// Save an uploaded file + /// Save an uploaded file. /// - /// Module where the file is uploaded - /// User who uploads the file - /// File Name - /// File content - /// A FileInfo object corresponding to the saved file + /// Module where the file is uploaded. + /// User who uploads the file. + /// File Name. + /// File content. + /// A FileInfo object corresponding to the saved file. IFileInfo SaveJourmalFile(ModuleInfo module, UserInfo userInfo, string fileName, Stream fileContent); - - + /// /// Save the journal object into database. /// /// Journal object. /// The module info of journal item context. - /// + /// void SaveJournalItem(JournalItem journalItem, ModuleInfo module); /// @@ -137,7 +138,7 @@ public interface IJournalController /// /// Journal object. /// The module info of journal item context. - /// + /// void UpdateJournalItem(JournalItem journalItem, ModuleInfo module); /// @@ -146,15 +147,15 @@ public interface IJournalController /// Id of portal. /// Id of current user. /// Id of the journal want to delete. - /// + /// void DeleteJournalItem(int portalId, int userId, int journalId); /// - /// Hard delete journal items based on group Id + /// Hard delete journal items based on group Id. /// /// Id of portal. /// Id of social group. - /// + /// void DeleteJournalItemByGroupId(int portalId, int groupId); /// @@ -162,7 +163,7 @@ public interface IJournalController /// /// Id of portal. /// Object key. - /// + /// void DeleteJournalItemByKey(int portalId, string objectKey); /// @@ -171,15 +172,15 @@ public interface IJournalController /// Id of portal. /// Id of current user. /// Id of the journal want to delete. - /// + /// void SoftDeleteJournalItem(int portalId, int userId, int journalId); /// - /// Soft delete journal items based on group Id + /// Soft delete journal items based on group Id. /// /// Id of portal. /// Id of social group. - /// + /// void SoftDeleteJournalItemByGroupId(int portalId, int groupId); /// @@ -187,15 +188,15 @@ public interface IJournalController /// /// Id of portal. /// Object key. - /// + /// void SoftDeleteJournalItemByKey(int portalId, string objectKey); - + /// /// Disable comment on a journal item. /// /// Id of portal. /// Id of the journal want to disable comment. - /// + /// void DisableComments(int portalId, int journalId); /// @@ -203,7 +204,7 @@ public interface IJournalController /// /// Id of portal. /// Id of the journal want to hide comments. - /// + /// void HideComments(int portalId, int journalId); /// @@ -211,7 +212,7 @@ public interface IJournalController /// /// Id of portal. /// Id of the journal want to enable comment. - /// + /// void EnableComments(int portalId, int journalId); /// @@ -219,7 +220,7 @@ public interface IJournalController /// /// Id of portal. /// Id of the journal want to show comment. - /// + /// void ShowComments(int portalId, int journalId); /// @@ -227,8 +228,8 @@ public interface IJournalController /// /// Id list of journal items. /// CommentInfo object list. - /// - IList GetCommentsByJournalIds(List journalIdList); + /// + IList GetCommentsByJournalIds(List journalIdList); /// /// Save a like on journal item. @@ -236,14 +237,14 @@ public interface IJournalController /// Id of journal item. /// Id of current user. /// User's display name. - /// + /// void LikeJournalItem(int journalId, int userId, string displayName); /// /// Save comment info object into database. /// /// Comment info object. - /// + /// void SaveComment(CommentInfo ci); /// @@ -251,7 +252,7 @@ public interface IJournalController /// /// Id of the comment. /// Comment info object. - /// + /// CommentInfo GetComment(int commentId); /// @@ -259,7 +260,7 @@ public interface IJournalController /// /// Id of journal. /// Id of comment. - /// + /// void DeleteComment(int journalId, int commentId); /// diff --git a/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs b/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs index 2c89a1a00b4..d60019bba0d 100644 --- a/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs +++ b/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs @@ -1,19 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Journal.Internal { + using System; + using System.Collections.Generic; + public interface IInternalJournalController { - IList GetJournalItemsByProfile (int portalId, int moduleId, int userID, int profileId, int currentIndex, int rows); + IList GetJournalItemsByProfile(int portalId, int moduleId, int userID, int profileId, int currentIndex, int rows); + IList GetJournalItemsByGroup(int portalId, int moduleId, int userID, int socialGroupId, int currentIndex, int rows); + IList GetJournalItems(int portalId, int moduleId, int userID, int currentIndex, int rows); void DeleteFilters(int portalId, int moduleId); + void SaveFilters(int portalId, int moduleId, int toInt32); } } diff --git a/DNN Platform/Library/Services/Journal/Internal/InternalJournalController.cs b/DNN Platform/Library/Services/Journal/Internal/InternalJournalController.cs index ebc2b829eab..c5a630faf84 100644 --- a/DNN Platform/Library/Services/Journal/Internal/InternalJournalController.cs +++ b/DNN Platform/Library/Services/Journal/Internal/InternalJournalController.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Journal.Internal { + using System; + + using DotNetNuke.Framework; + public class InternalJournalController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs index fb68e2cbee7..d843c3bc2ad 100644 --- a/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs @@ -1,38 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Journal.Internal { + using System; + using System.Collections.Generic; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security; + public class InternalJournalControllerImpl : IInternalJournalController { - private readonly IJournalDataService _dataService; - - #region Constructors - + private readonly IJournalDataService _dataService; + public InternalJournalControllerImpl() { - _dataService = JournalDataService.Instance; - } - - #endregion - + this._dataService = JournalDataService.Instance; + } + public IList GetJournalItemsByProfile(int portalId, int moduleId, int currentUserId, int profileId, int rowIndex, int maxRows) { return - CBO.FillCollection(_dataService.Journal_ListForProfile(portalId, moduleId, currentUserId, + CBO.FillCollection(this._dataService.Journal_ListForProfile(portalId, moduleId, currentUserId, profileId, rowIndex, maxRows)); } @@ -40,7 +31,7 @@ public IList GetJournalItemsByGroup(int portalId, int moduleId, int int rowIndex, int maxRows) { return - CBO.FillCollection(_dataService.Journal_ListForGroup(portalId, moduleId, currentUserId, + CBO.FillCollection(this._dataService.Journal_ListForGroup(portalId, moduleId, currentUserId, groupId, rowIndex, maxRows)); } @@ -48,18 +39,18 @@ public IList GetJournalItems(int portalId, int moduleId, int curren int maxRows) { return - CBO.FillCollection(_dataService.Journal_ListForSummary(portalId, moduleId, currentUserId, + CBO.FillCollection(this._dataService.Journal_ListForSummary(portalId, moduleId, currentUserId, rowIndex, maxRows)); } - + public void DeleteFilters(int portalId, int moduleId) { - _dataService.Journal_TypeFilters_Delete(portalId, moduleId); + this._dataService.Journal_TypeFilters_Delete(portalId, moduleId); } public void SaveFilters(int portalId, int moduleId, int journalTypeId) { - _dataService.Journal_TypeFilters_Save(portalId, moduleId, journalTypeId); + this._dataService.Journal_TypeFilters_Save(portalId, moduleId, journalTypeId); } } } diff --git a/DNN Platform/Library/Services/Journal/ItemData.cs b/DNN Platform/Library/Services/Journal/ItemData.cs index 925734179d3..3c85cd542ae 100644 --- a/DNN Platform/Library/Services/Journal/ItemData.cs +++ b/DNN Platform/Library/Services/Journal/ItemData.cs @@ -1,56 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using DotNetNuke.Services.Tokens; -namespace DotNetNuke.Services.Journal { - - public class ItemData : IPropertyAccess { - public string Url { get; set; } - public string Title { get; set; } - public string Description { get; set; } - public string ImageUrl { get; set; } - public CacheLevel Cacheability { - get { - return CacheLevel.fullyCacheable; - } - } - - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { - string OutputFormat = string.Empty; - if (format == string.Empty) { - OutputFormat = "g"; - } else { - OutputFormat = format; - } - propertyName = propertyName.ToLowerInvariant(); - switch (propertyName) { - case "url": - return PropertyAccess.FormatString(Url, format); - case "title": - return PropertyAccess.FormatString(Title, format); - case "description": - return PropertyAccess.FormatString(Description, format); - case "imageurl": - return PropertyAccess.FormatString(ImageUrl, format); - - - } - - propertyNotFound = true; - return string.Empty; - - } - } - - - - -} - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.Journal +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Xml; + + using DotNetNuke.Services.Tokens; + + public class ItemData : IPropertyAccess + { + public string Url { get; set; } + + public string Title { get; set; } + + public string Description { get; set; } + + public string ImageUrl { get; set; } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + + public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { + string OutputFormat = string.Empty; + if (format == string.Empty) + { + OutputFormat = "g"; + } + else + { + OutputFormat = format; + } + + propertyName = propertyName.ToLowerInvariant(); + switch (propertyName) + { + case "url": + return PropertyAccess.FormatString(this.Url, format); + case "title": + return PropertyAccess.FormatString(this.Title, format); + case "description": + return PropertyAccess.FormatString(this.Description, format); + case "imageurl": + return PropertyAccess.FormatString(this.ImageUrl, format); + } + + propertyNotFound = true; + return string.Empty; + } + } +} diff --git a/DNN Platform/Library/Services/Journal/JournalController.cs b/DNN Platform/Library/Services/Journal/JournalController.cs index 944c1f703c5..398f0ea4011 100644 --- a/DNN Platform/Library/Services/Journal/JournalController.cs +++ b/DNN Platform/Library/Services/Journal/JournalController.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Journal { + using System; + + using DotNetNuke.Framework; + public class JournalController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs index 2f88c44ebbc..27b953bf026 100644 --- a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs @@ -1,48 +1,174 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Drawing; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Web; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Journal { + using System; + using System.Collections.Generic; + using System.Data; + using System.Drawing; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + internal class JournalControllerImpl : IJournalController { - private readonly IJournalDataService _dataService; private const string AllowResizePhotosSetting = "Journal_AllowResizePhotos"; private const string AllowPhotosSetting = "Journal_AllowPhotos"; - private const string EditorEnabledSetting = "Journal_EditorEnabled"; - - #region Constructors + private readonly IJournalDataService _dataService; + private const string EditorEnabledSetting = "Journal_EditorEnabled"; + private static readonly string[] InvalidSecuritySetsWithoutId = new[] { "R", "U", "F", "P" }; + private static readonly char[] ValidSecurityDescriptors = new[] { 'E', 'C', 'R', 'U', 'F', 'P' }; + public JournalControllerImpl() { - _dataService = JournalDataService.Instance; - } + this._dataService = JournalDataService.Instance; + } + + // Journal Items + public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) + { + if (journalItem.UserId < 1) + { + throw new ArgumentException("journalItem.UserId must be for a real user"); + } + + UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); + if (currentUser == null) + { + throw new Exception("Unable to locate the current user"); + } + + string xml = null; + var portalSecurity = PortalSecurity.Instance; + if (!string.IsNullOrEmpty(journalItem.Title)) + { + journalItem.Title = portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.Summary)) + { + journalItem.Summary = portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.Body)) + { + journalItem.Body = portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); + } - #endregion + if (!string.IsNullOrEmpty(journalItem.Body)) + { + var xDoc = new XmlDocument { XmlResolver = null }; + XmlElement xnode = xDoc.CreateElement("items"); + XmlElement xnode2 = xDoc.CreateElement("item"); + xnode2.AppendChild(this.CreateElement(xDoc, "id", "-1")); + xnode2.AppendChild(this.CreateCDataElement(xDoc, "body", journalItem.Body)); + xnode.AppendChild(xnode2); + xDoc.AppendChild(xnode); + XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", null, null); + xDec.Encoding = "UTF-16"; + xDec.Standalone = "yes"; + XmlElement root = xDoc.DocumentElement; + xDoc.InsertBefore(xDec, root); + journalItem.JournalXML = xDoc; + xml = journalItem.JournalXML.OuterXml; + } + + if (journalItem.ItemData != null) + { + if (!string.IsNullOrEmpty(journalItem.ItemData.Title)) + { + journalItem.ItemData.Title = portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) + { + journalItem.ItemData.Description = portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) + { + journalItem.ItemData.Url = portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) + { + journalItem.ItemData.ImageUrl = portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); + } + } + + string journalData = journalItem.ItemData.ToJson(); + if (journalData == "null") + { + journalData = null; + } - #region Private Methods + this.PrepareSecuritySet(journalItem, currentUser); + + journalItem.JournalId = this._dataService.Journal_Save( + journalItem.PortalId, + journalItem.UserId, + journalItem.ProfileId, + journalItem.SocialGroupId, + journalItem.JournalId, + journalItem.JournalTypeId, + journalItem.Title, + journalItem.Summary, + journalItem.Body, + journalData, + xml, + journalItem.ObjectKey, + journalItem.AccessKey, + journalItem.SecuritySet, + journalItem.CommentsDisabled, + journalItem.CommentsHidden); + + var updatedJournalItem = this.GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); + journalItem.DateCreated = updatedJournalItem.DateCreated; + journalItem.DateUpdated = updatedJournalItem.DateUpdated; + var cnt = new Content(); + if (journalItem.ContentItemId > 0) + { + cnt.UpdateContentItem(journalItem, tabId, moduleId); + this._dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); + } + else + { + ContentItem ci = cnt.CreateContentItem(journalItem, tabId, moduleId); + this._dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); + journalItem.ContentItemId = ci.ContentItemId; + } + + if (journalItem.SocialGroupId > 0) + { + try + { + this.UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); + } + catch (Exception exc) + { + Exceptions.Exceptions.LogException(exc); + } + } + } + private XmlElement CreateElement(XmlDocument xDoc, string name, string value) { XmlElement xnode = xDoc.CreateElement(name); @@ -67,16 +193,16 @@ private void UpdateGroupStats(int portalId, int groupId) return; } - for (var i = 0; i < role.Settings.Keys.Count; i++ ) + for (var i = 0; i < role.Settings.Keys.Count; i++) { var key = role.Settings.Keys.ElementAt(i); - if(key.StartsWith("stat_")) + if (key.StartsWith("stat_")) { role.Settings[key] = "0"; } } - using (IDataReader dr = _dataService.Journal_GetStatsForGroup(portalId, groupId)) + using (IDataReader dr = this._dataService.Journal_GetStatsForGroup(portalId, groupId)) { while (dr.Read()) { @@ -90,14 +216,16 @@ private void UpdateGroupStats(int portalId, int groupId) role.Settings.Add(settingName, dr["JournalTypeCount"].ToString()); } } + dr.Close(); } + RoleController.Instance.UpdateRoleSettings(role, true); } private void DeleteJournalItem(int portalId, int currentUserId, int journalId, bool softDelete) { - var ji = GetJournalItem(portalId, currentUserId, journalId, !softDelete); + var ji = this.GetJournalItem(portalId, currentUserId, journalId, !softDelete); if (ji == null) { return; @@ -107,16 +235,16 @@ private void DeleteJournalItem(int portalId, int currentUserId, int journalId, b if (softDelete) { - _dataService.Journal_SoftDelete(journalId); + this._dataService.Journal_SoftDelete(journalId); } else { - _dataService.Journal_Delete(journalId); + this._dataService.Journal_Delete(journalId); } if (groupId > 0) { - UpdateGroupStats(portalId, groupId); + this.UpdateGroupStats(portalId, groupId); } // queue remove journal from search index @@ -125,23 +253,26 @@ private void DeleteJournalItem(int portalId, int currentUserId, int journalId, b PortalId = portalId, AuthorUserId = currentUserId, UniqueKey = ji.ContentItemId.ToString("D"), - //QueryString = "journalid=" + journalId, - SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId + + // QueryString = "journalid=" + journalId, + SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, }; - if (groupId > 0) - document.RoleId = groupId; - + if (groupId > 0) + { + document.RoleId = groupId; + } + DataProvider.Instance().AddSearchDeletedItems(document); } - + private Stream GetJournalImageContent(Stream fileContent) { Image image = new Bitmap(fileContent); int thumbnailWidth = 400; int thumbnailHeight = 400; - GetThumbnailSize(image.Width, image.Height, ref thumbnailWidth, ref thumbnailHeight); - var thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight, ThumbnailCallback, IntPtr.Zero); + this.GetThumbnailSize(image.Width, image.Height, ref thumbnailWidth, ref thumbnailHeight); + var thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight, this.ThumbnailCallback, IntPtr.Zero); var result = new MemoryStream(); thumbnail.Save(result, image.RawFormat); return result; @@ -152,12 +283,12 @@ private void GetThumbnailSize(int imageWidth, int imageHeight, ref int thumbnail if (imageWidth >= imageHeight) { thumbnailWidth = Math.Min(imageWidth, thumbnailWidth); - thumbnailHeight = GetMinorSize(imageHeight, imageWidth, thumbnailWidth); + thumbnailHeight = this.GetMinorSize(imageHeight, imageWidth, thumbnailWidth); } else { thumbnailHeight = Math.Min(imageHeight, thumbnailHeight); - thumbnailWidth = GetMinorSize(imageWidth, imageHeight, thumbnailHeight); + thumbnailWidth = this.GetMinorSize(imageWidth, imageHeight, thumbnailHeight); } } @@ -171,11 +302,10 @@ private int GetMinorSize(int imageMinorSize, int imageMajorSize, int thumbnailMa double calculated = (Convert.ToDouble(imageMinorSize) * Convert.ToDouble(thumbnailMajorSize)) / Convert.ToDouble(imageMajorSize); return Convert.ToInt32(Math.Round(calculated)); } - - + private bool IsImageFile(string fileName) { - return (Globals.glbImageFileTypes + ",").IndexOf(Path.GetExtension(fileName).Replace(".", "") + ",", StringComparison.InvariantCultureIgnoreCase) > -1; + return (Globals.glbImageFileTypes + ",").IndexOf(Path.GetExtension(fileName).Replace(".", string.Empty) + ",", StringComparison.InvariantCultureIgnoreCase) > -1; } private bool ThumbnailCallback() @@ -185,16 +315,18 @@ private bool ThumbnailCallback() private bool IsResizePhotosEnabled(ModuleInfo module) { - return GetBooleanSetting(AllowResizePhotosSetting, false, module) && - GetBooleanSetting(AllowPhotosSetting, true, module) && - GetBooleanSetting(EditorEnabledSetting, true, module); + return this.GetBooleanSetting(AllowResizePhotosSetting, false, module) && + this.GetBooleanSetting(AllowPhotosSetting, true, module) && + this.GetBooleanSetting(EditorEnabledSetting, true, module); } + private bool GetBooleanSetting(string settingName, bool defaultValue, ModuleInfo module) - { + { if (module.ModuleSettings.Contains(settingName)) { return Convert.ToBoolean(module.ModuleSettings[settingName].ToString()); } + return defaultValue; } @@ -202,9 +334,9 @@ private bool GetBooleanSetting(string settingName, bool defaultValue, ModuleInfo private void PrepareSecuritySet(JournalItem journalItem, UserInfo currentUser) { var originalSecuritySet = - journalItem.SecuritySet = (journalItem.SecuritySet ??string.Empty).ToUpperInvariant(); + journalItem.SecuritySet = (journalItem.SecuritySet ?? string.Empty).ToUpperInvariant(); - if (String.IsNullOrEmpty(journalItem.SecuritySet)) + if (string.IsNullOrEmpty(journalItem.SecuritySet)) { journalItem.SecuritySet = "E,"; } @@ -217,8 +349,10 @@ private void PrepareSecuritySet(JournalItem journalItem, UserInfo currentUser) if (journalItem.SecuritySet == "F,") { journalItem.SecuritySet = "F" + journalItem.UserId + ","; - if (journalItem.ProfileId > 0) - journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; + if (journalItem.ProfileId > 0) + { + journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; + } } else if (journalItem.SecuritySet == "U,") { @@ -226,8 +360,10 @@ private void PrepareSecuritySet(JournalItem journalItem, UserInfo currentUser) } else if (journalItem.SecuritySet == "R,") { - if (journalItem.SocialGroupId > 0) - journalItem.SecuritySet += "R" + journalItem.SocialGroupId + ","; + if (journalItem.SocialGroupId > 0) + { + journalItem.SecuritySet += "R" + journalItem.SocialGroupId + ","; + } } if (journalItem.ProfileId > 0 && journalItem.UserId != journalItem.ProfileId) @@ -248,190 +384,69 @@ private void PrepareSecuritySet(JournalItem journalItem, UserInfo currentUser) journalItem.SecuritySet += "U" + journalItem.UserId + ","; } - //if the post is marked as private, we shouldn't make it visible to the group. + // if the post is marked as private, we shouldn't make it visible to the group. if (journalItem.SocialGroupId > 0 && originalSecuritySet.Contains("U,")) { var item = journalItem; - var role = RoleController.Instance.GetRole(journalItem.PortalId, + var role = RoleController.Instance.GetRole( + journalItem.PortalId, r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == item.SocialGroupId); if (role != null && !role.IsPublic) { - journalItem.SecuritySet = journalItem.SecuritySet.Replace("E,", String.Empty).Replace("C,", String.Empty); + journalItem.SecuritySet = journalItem.SecuritySet.Replace("E,", string.Empty).Replace("C,", string.Empty); } } // clean up and remove duplicates var parts = journalItem.SecuritySet - .Replace(" ", "") + .Replace(" ", string.Empty) .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .Distinct() .Except(InvalidSecuritySetsWithoutId) .Where(p => p.IndexOfAny(ValidSecurityDescriptors) >= 0); - //TODO: validate existence and visibility/accessability of all Roles added to the set (if any) - + // TODO: validate existence and visibility/accessability of all Roles added to the set (if any) journalItem.SecuritySet = string.Join(",", parts); } - private static readonly string[] InvalidSecuritySetsWithoutId = new[] { "R", "U", "F", "P" }; - private static readonly char[] ValidSecurityDescriptors = new[] { 'E', 'C', 'R', 'U', 'F', 'P' }; - - #endregion - - #region Public Methods - - // Journal Items - public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) - { - if (journalItem.UserId < 1) - { - throw new ArgumentException("journalItem.UserId must be for a real user"); - } - - UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); - if (currentUser == null) - { - throw new Exception("Unable to locate the current user"); - } - - string xml = null; - var portalSecurity = PortalSecurity.Instance; - if (!String.IsNullOrEmpty(journalItem.Title)) - { - journalItem.Title = portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); - } - if (!String.IsNullOrEmpty(journalItem.Summary)) - { - journalItem.Summary = portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); - } - if (!String.IsNullOrEmpty(journalItem.Body)) - { - journalItem.Body = portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); - } - - if (!String.IsNullOrEmpty(journalItem.Body)) - { - var xDoc = new XmlDocument { XmlResolver = null }; - XmlElement xnode = xDoc.CreateElement("items"); - XmlElement xnode2 = xDoc.CreateElement("item"); - xnode2.AppendChild(CreateElement(xDoc, "id", "-1")); - xnode2.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body)); - xnode.AppendChild(xnode2); - xDoc.AppendChild(xnode); - XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", null, null); - xDec.Encoding = "UTF-16"; - xDec.Standalone = "yes"; - XmlElement root = xDoc.DocumentElement; - xDoc.InsertBefore(xDec, root); - journalItem.JournalXML = xDoc; - xml = journalItem.JournalXML.OuterXml; - } - if (journalItem.ItemData != null) - { - if (!String.IsNullOrEmpty(journalItem.ItemData.Title)) - { - journalItem.ItemData.Title = portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); - } - if (!String.IsNullOrEmpty(journalItem.ItemData.Description)) - { - journalItem.ItemData.Description = portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); - } - if (!String.IsNullOrEmpty(journalItem.ItemData.Url)) - { - journalItem.ItemData.Url = portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); - } - if (!String.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) - { - journalItem.ItemData.ImageUrl = portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); - } - } - string journalData = journalItem.ItemData.ToJson(); - if (journalData == "null") - { - journalData = null; - } - - PrepareSecuritySet(journalItem, currentUser); - - journalItem.JournalId = _dataService.Journal_Save(journalItem.PortalId, - journalItem.UserId, - journalItem.ProfileId, - journalItem.SocialGroupId, - journalItem.JournalId, - journalItem.JournalTypeId, - journalItem.Title, - journalItem.Summary, - journalItem.Body, - journalData, - xml, - journalItem.ObjectKey, - journalItem.AccessKey, - journalItem.SecuritySet, - journalItem.CommentsDisabled, - journalItem.CommentsHidden); - - var updatedJournalItem = GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); - journalItem.DateCreated = updatedJournalItem.DateCreated; - journalItem.DateUpdated = updatedJournalItem.DateUpdated; - var cnt = new Content(); - - if (journalItem.ContentItemId > 0) - { - cnt.UpdateContentItem(journalItem, tabId, moduleId); - _dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); - } - else - { - ContentItem ci = cnt.CreateContentItem(journalItem, tabId, moduleId); - _dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); - journalItem.ContentItemId = ci.ContentItemId; - } - if (journalItem.SocialGroupId > 0) - { - try - { - UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); - } - catch (Exception exc) - { - Exceptions.Exceptions.LogException(exc); - } - } - } - public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) { if (journalItem.UserId < 1) { throw new ArgumentException("journalItem.UserId must be for a real user"); } + UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); if (currentUser == null) { throw new Exception("Unable to locate the current user"); } + string xml = null; var portalSecurity = PortalSecurity.Instance; - if (!String.IsNullOrEmpty(journalItem.Title)) + if (!string.IsNullOrEmpty(journalItem.Title)) { journalItem.Title = portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); } - if (!String.IsNullOrEmpty(journalItem.Summary)) + + if (!string.IsNullOrEmpty(journalItem.Summary)) { journalItem.Summary = portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); } - if (!String.IsNullOrEmpty(journalItem.Body)) + + if (!string.IsNullOrEmpty(journalItem.Body)) { journalItem.Body = portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); } - if (!String.IsNullOrEmpty(journalItem.Body)) + + if (!string.IsNullOrEmpty(journalItem.Body)) { var xDoc = new XmlDocument { XmlResolver = null }; XmlElement xnode = xDoc.CreateElement("items"); XmlElement xnode2 = xDoc.CreateElement("item"); - xnode2.AppendChild(CreateElement(xDoc, "id", "-1")); - xnode2.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body)); + xnode2.AppendChild(this.CreateElement(xDoc, "id", "-1")); + xnode2.AppendChild(this.CreateCDataElement(xDoc, "body", journalItem.Body)); xnode.AppendChild(xnode2); xDoc.AppendChild(xnode); XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", null, null); @@ -442,52 +457,58 @@ public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) journalItem.JournalXML = xDoc; xml = journalItem.JournalXML.OuterXml; } + if (journalItem.ItemData != null) { - if (!String.IsNullOrEmpty(journalItem.ItemData.Title)) + if (!string.IsNullOrEmpty(journalItem.ItemData.Title)) { journalItem.ItemData.Title = portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); } - if (!String.IsNullOrEmpty(journalItem.ItemData.Description)) + + if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) { journalItem.ItemData.Description = portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); } - if (!String.IsNullOrEmpty(journalItem.ItemData.Url)) + + if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) { journalItem.ItemData.Url = portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); } - if (!String.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) + + if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) { journalItem.ItemData.ImageUrl = portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); } } + string journalData = journalItem.ItemData.ToJson(); if (journalData == "null") { journalData = null; } - PrepareSecuritySet(journalItem, currentUser); - - journalItem.JournalId = _dataService.Journal_Update(journalItem.PortalId, - journalItem.UserId, - journalItem.ProfileId, - journalItem.SocialGroupId, - journalItem.JournalId, - journalItem.JournalTypeId, - journalItem.Title, - journalItem.Summary, - journalItem.Body, - journalData, - xml, - journalItem.ObjectKey, - journalItem.AccessKey, - journalItem.SecuritySet, - journalItem.CommentsDisabled, - journalItem.CommentsHidden); - - var updatedJournalItem = GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); + this.PrepareSecuritySet(journalItem, currentUser); + + journalItem.JournalId = this._dataService.Journal_Update( + journalItem.PortalId, + journalItem.UserId, + journalItem.ProfileId, + journalItem.SocialGroupId, + journalItem.JournalId, + journalItem.JournalTypeId, + journalItem.Title, + journalItem.Summary, + journalItem.Body, + journalData, + xml, + journalItem.ObjectKey, + journalItem.AccessKey, + journalItem.SecuritySet, + journalItem.CommentsDisabled, + journalItem.CommentsHidden); + + var updatedJournalItem = this.GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); journalItem.DateCreated = updatedJournalItem.DateCreated; journalItem.DateUpdated = updatedJournalItem.DateUpdated; @@ -495,19 +516,20 @@ public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) if (journalItem.ContentItemId > 0) { cnt.UpdateContentItem(journalItem, tabId, moduleId); - _dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); + this._dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); } else { ContentItem ci = cnt.CreateContentItem(journalItem, tabId, moduleId); - _dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); + this._dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); journalItem.ContentItemId = ci.ContentItemId; } + if (journalItem.SocialGroupId > 0) { try { - UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); + this.UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); } catch (Exception exc) { @@ -515,35 +537,35 @@ public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) } } } - + public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId) { - return GetJournalItem(portalId, currentUserId, journalId, false, false); + return this.GetJournalItem(portalId, currentUserId, journalId, false, false); } public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems) { - return GetJournalItem(portalId, currentUserId, journalId, includeAllItems, false); + return this.GetJournalItem(portalId, currentUserId, journalId, includeAllItems, false); } public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted) { - return GetJournalItem(portalId, currentUserId, journalId, includeAllItems, isDeleted, false); + return this.GetJournalItem(portalId, currentUserId, journalId, includeAllItems, isDeleted, false); } public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck) { - return CBO.FillObject(_dataService.Journal_Get(portalId, currentUserId, journalId, includeAllItems, isDeleted, securityCheck)); + return CBO.FillObject(this._dataService.Journal_Get(portalId, currentUserId, journalId, includeAllItems, isDeleted, securityCheck)); } public JournalItem GetJournalItemByKey(int portalId, string objectKey) { - return GetJournalItemByKey(portalId, objectKey, false, false); + return this.GetJournalItemByKey(portalId, objectKey, false, false); } public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems) { - return GetJournalItemByKey(portalId, objectKey, includeAllItems, false); + return this.GetJournalItemByKey(portalId, objectKey, includeAllItems, false); } public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted) @@ -552,30 +574,32 @@ public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool incl { return null; } - return CBO.FillObject(_dataService.Journal_GetByKey(portalId, objectKey, includeAllItems, isDeleted)); + + return CBO.FillObject(this._dataService.Journal_GetByKey(portalId, objectKey, includeAllItems, isDeleted)); } public IFileInfo SaveJourmalFile(ModuleInfo module, UserInfo userInfo, string fileName, Stream fileContent) { var userFolder = FolderManager.Instance.GetUserFolder(userInfo); - if (IsImageFile(fileName) && IsResizePhotosEnabled(module)) + if (this.IsImageFile(fileName) && this.IsResizePhotosEnabled(module)) { - using (var stream = GetJournalImageContent(fileContent)) + using (var stream = this.GetJournalImageContent(fileContent)) { return FileManager.Instance.AddFile(userFolder, fileName, stream, true); } } - //todo: deal with the case where the exact file name already exists. - return FileManager.Instance.AddFile(userFolder, fileName, fileContent, true); + + // todo: deal with the case where the exact file name already exists. + return FileManager.Instance.AddFile(userFolder, fileName, fileContent, true); } - + public void SaveJournalItem(JournalItem journalItem, ModuleInfo module) { var tabId = module == null ? Null.NullInteger : module.TabID; var tabModuleId = module == null ? Null.NullInteger : module.TabModuleID; - SaveJournalItem(journalItem, tabId, tabModuleId); + this.SaveJournalItem(journalItem, tabId, tabModuleId); } public void UpdateJournalItem(JournalItem journalItem, ModuleInfo module) @@ -583,30 +607,31 @@ public void UpdateJournalItem(JournalItem journalItem, ModuleInfo module) var tabId = module == null ? Null.NullInteger : module.TabID; var tabModuleId = module == null ? Null.NullInteger : module.TabModuleID; - UpdateJournalItem(journalItem, tabId, tabModuleId); + this.UpdateJournalItem(journalItem, tabId, tabModuleId); } public void DisableComments(int portalId, int journalId) { - _dataService.Journal_Comments_ToggleDisable(portalId, journalId, true); + this._dataService.Journal_Comments_ToggleDisable(portalId, journalId, true); } public void EnableComments(int portalId, int journalId) { - _dataService.Journal_Comments_ToggleDisable(portalId, journalId, false); + this._dataService.Journal_Comments_ToggleDisable(portalId, journalId, false); } public void HideComments(int portalId, int journalId) { - _dataService.Journal_Comments_ToggleHidden(portalId, journalId, true); + this._dataService.Journal_Comments_ToggleHidden(portalId, journalId, true); } public void ShowComments(int portalId, int journalId) - { - _dataService.Journal_Comments_ToggleHidden(portalId, journalId, false); + { + this._dataService.Journal_Comments_ToggleHidden(portalId, journalId, false); } // Delete Journal Items + /// /// HARD deletes journal items. /// @@ -615,27 +640,27 @@ public void ShowComments(int portalId, int journalId) /// public void DeleteJournalItem(int portalId, int currentUserId, int journalId) { - DeleteJournalItem(portalId, currentUserId, journalId, false); + this.DeleteJournalItem(portalId, currentUserId, journalId, false); } /// - /// HARD deletes journal items based on item key + /// HARD deletes journal items based on item key. /// /// /// public void DeleteJournalItemByKey(int portalId, string objectKey) { - _dataService.Journal_DeleteByKey(portalId, objectKey); + this._dataService.Journal_DeleteByKey(portalId, objectKey); } /// - /// HARD deletes journal items based on group Id + /// HARD deletes journal items based on group Id. /// /// /// public void DeleteJournalItemByGroupId(int portalId, int groupId) { - _dataService.Journal_DeleteByGroupId(portalId, groupId); + this._dataService.Journal_DeleteByGroupId(portalId, groupId); } /// @@ -646,121 +671,113 @@ public void DeleteJournalItemByGroupId(int portalId, int groupId) /// public void SoftDeleteJournalItem(int portalId, int currentUserId, int journalId) { - DeleteJournalItem(portalId, currentUserId, journalId, true); + this.DeleteJournalItem(portalId, currentUserId, journalId, true); } /// - /// SOFT deletes journal items based on item key + /// SOFT deletes journal items based on item key. /// /// /// public void SoftDeleteJournalItemByKey(int portalId, string objectKey) { - _dataService.Journal_SoftDeleteByKey(portalId, objectKey); + this._dataService.Journal_SoftDeleteByKey(portalId, objectKey); } /// - /// SOFT deletes journal items based on group Id + /// SOFT deletes journal items based on group Id. /// /// /// public void SoftDeleteJournalItemByGroupId(int portalId, int groupId) { - _dataService.Journal_SoftDeleteByGroupId(portalId, groupId); + this._dataService.Journal_SoftDeleteByGroupId(portalId, groupId); } // Journal Comments - public IList GetCommentsByJournalIds(List journalIdList) + public IList GetCommentsByJournalIds(List journalIdList) { - var journalIds = journalIdList.Aggregate("", (current, journalId) => current + journalId + ";"); - return CBO.FillCollection(_dataService.Journal_Comment_ListByJournalIds(journalIds)); + var journalIds = journalIdList.Aggregate(string.Empty, (current, journalId) => current + journalId + ";"); + return CBO.FillCollection(this._dataService.Journal_Comment_ListByJournalIds(journalIds)); } public void LikeJournalItem(int journalId, int userId, string displayName) { - _dataService.Journal_Like(journalId, userId, displayName); + this._dataService.Journal_Like(journalId, userId, displayName); } public void SaveComment(CommentInfo comment) { var portalSecurity = PortalSecurity.Instance; - if (!String.IsNullOrEmpty(comment.Comment)) + if (!string.IsNullOrEmpty(comment.Comment)) { comment.Comment = portalSecurity.InputFilter(comment.Comment, PortalSecurity.FilterFlag.NoScripting); } - //TODO: enable once the profanity filter is working properly. - //objCommentInfo.Comment = portalSecurity.Remove(objCommentInfo.Comment, DotNetNuke.Security.PortalSecurity.ConfigType.ListController, "ProfanityFilter", DotNetNuke.Security.PortalSecurity.FilterScope.PortalList); - + + // TODO: enable once the profanity filter is working properly. + // objCommentInfo.Comment = portalSecurity.Remove(objCommentInfo.Comment, DotNetNuke.Security.PortalSecurity.ConfigType.ListController, "ProfanityFilter", DotNetNuke.Security.PortalSecurity.FilterScope.PortalList); string xml = null; if (comment.CommentXML != null) { xml = comment.CommentXML.OuterXml; } - - comment.CommentId = _dataService.Journal_Comment_Save(comment.JournalId, comment.CommentId, comment.UserId, comment.Comment, xml, Null.NullDate); - - var newComment = GetComment(comment.CommentId); + + comment.CommentId = this._dataService.Journal_Comment_Save(comment.JournalId, comment.CommentId, comment.UserId, comment.Comment, xml, Null.NullDate); + + var newComment = this.GetComment(comment.CommentId); comment.DateCreated = newComment.DateCreated; comment.DateUpdated = newComment.DateUpdated; } public CommentInfo GetComment(int commentId) { - return CBO.FillObject(_dataService.Journal_Comment_Get(commentId)); + return CBO.FillObject(this._dataService.Journal_Comment_Get(commentId)); } public void DeleteComment(int journalId, int commentId) { - _dataService.Journal_Comment_Delete(journalId, commentId); - //UNDONE: update the parent journal item and content item so this comment gets removed from search index + this._dataService.Journal_Comment_Delete(journalId, commentId); + + // UNDONE: update the parent journal item and content item so this comment gets removed from search index } public void LikeComment(int journalId, int commentId, int userId, string displayName) { - _dataService.Journal_Comment_Like(journalId, commentId, userId, displayName); - } - - #endregion - - #region Journal Types - + this._dataService.Journal_Comment_Like(journalId, commentId, userId, displayName); + } + public JournalTypeInfo GetJournalType(string journalType) { - return CBO.FillObject(_dataService.Journal_Types_Get(journalType)); + return CBO.FillObject(this._dataService.Journal_Types_Get(journalType)); } public JournalTypeInfo GetJournalTypeById(int journalTypeId) { - return CBO.FillObject(_dataService.Journal_Types_GetById(journalTypeId)); + return CBO.FillObject(this._dataService.Journal_Types_GetById(journalTypeId)); } public IEnumerable GetJournalTypes(int portalId) { return CBO.GetCachedObject>( - new CacheItemArgs(String.Format(DataCache.JournalTypesCacheKey, portalId), - DataCache.JournalTypesTimeOut, - DataCache.JournalTypesCachePriority, - portalId), - c => CBO.FillCollection(_dataService.Journal_Types_List(portalId))); - } - - #endregion - - #region Obsolete Methods - + new CacheItemArgs( + string.Format(DataCache.JournalTypesCacheKey, portalId), + DataCache.JournalTypesTimeOut, + DataCache.JournalTypesCachePriority, + portalId), + c => CBO.FillCollection(this._dataService.Journal_Types_List(portalId))); + } + [Obsolete("Deprecated in DNN 7.2.2. Use SaveJournalItem(JournalItem, ModuleInfo). Scheduled removal in v10.0.0.")] public void SaveJournalItem(JournalItem journalItem, int tabId) { - SaveJournalItem(journalItem, tabId, Null.NullInteger); + this.SaveJournalItem(journalItem, tabId, Null.NullInteger); } [Obsolete("Deprecated in DNN 7.2.2. Use UpdateJournalItem(JournalItem, ModuleInfo). Scheduled removal in v10.0.0.")] public void UpdateJournalItem(JournalItem journalItem, int tabId) { - UpdateJournalItem(journalItem, tabId, Null.NullInteger); - } - - #endregion + this.UpdateJournalItem(journalItem, tabId, Null.NullInteger); + } } } diff --git a/DNN Platform/Library/Services/Journal/JournalEntity.cs b/DNN Platform/Library/Services/Journal/JournalEntity.cs index 9dfe2ebd965..6193564a206 100644 --- a/DNN Platform/Library/Services/Journal/JournalEntity.cs +++ b/DNN Platform/Library/Services/Journal/JournalEntity.cs @@ -1,64 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using DotNetNuke.Services.Tokens; -namespace DotNetNuke.Services.Journal { - public class JournalEntity :IPropertyAccess { - public int Id {get;set;} - public string Name {get;set;} - public string Vanity {get; set;} - public string Avatar { get; set; } - public JournalEntity() { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.Journal +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Xml; + + using DotNetNuke.Services.Tokens; + + public class JournalEntity : IPropertyAccess + { + public JournalEntity() + { } - public JournalEntity(string entityXML) { - if (!string.IsNullOrEmpty(entityXML)) { + + public JournalEntity(string entityXML) + { + if (!string.IsNullOrEmpty(entityXML)) + { XmlDocument xDoc = new XmlDocument { XmlResolver = null }; xDoc.LoadXml(entityXML); - if ((xDoc != null)) { + if (xDoc != null) + { XmlNode xRoot = xDoc.DocumentElement; XmlNode xNode = null; xNode = xRoot.SelectSingleNode("//entity"); - if ((xNode != null)) { - Id = int.Parse(xNode["id"].InnerText); - Name = xNode["name"].InnerText.ToString(); - if ((xNode["vanity"] != null)) { - Vanity= xNode["vanity"].InnerText.ToString(); + if (xNode != null) + { + this.Id = int.Parse(xNode["id"].InnerText); + this.Name = xNode["name"].InnerText.ToString(); + if (xNode["vanity"] != null) + { + this.Vanity = xNode["vanity"].InnerText.ToString(); } - } } } } + + public int Id { get; set; } + + public string Name { get; set; } + + public string Vanity { get; set; } + + public string Avatar { get; set; } - public CacheLevel Cacheability { + public CacheLevel Cacheability + { get { return CacheLevel.fullyCacheable; } } - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { + public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { string OutputFormat = string.Empty; - if (format == string.Empty) { + if (format == string.Empty) + { OutputFormat = "g"; - } else { + } + else + { OutputFormat = format; } + propertyName = propertyName.ToLowerInvariant(); - switch (propertyName) { + switch (propertyName) + { case "id": - return PropertyAccess.FormatString(Id.ToString(), format); + return PropertyAccess.FormatString(this.Id.ToString(), format); case "name": - return PropertyAccess.FormatString(Name.ToString(), format); + return PropertyAccess.FormatString(this.Name.ToString(), format); case "vanity": - return PropertyAccess.FormatString(Vanity.ToString(), format); + return PropertyAccess.FormatString(this.Vanity.ToString(), format); case "avatar": - return PropertyAccess.FormatString(Avatar.ToString(), format); - - + return PropertyAccess.FormatString(this.Avatar.ToString(), format); } propertyNotFound = true; diff --git a/DNN Platform/Library/Services/Journal/JournalItem.cs b/DNN Platform/Library/Services/Journal/JournalItem.cs index 0cd774c0a9c..eae1339a26b 100644 --- a/DNN Platform/Library/Services/Journal/JournalItem.cs +++ b/DNN Platform/Library/Services/Journal/JournalItem.cs @@ -1,55 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; -using System.Xml; -using System.Xml.Serialization; -using DotNetNuke.Services.Tokens; -using System.IO; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Json; -using System.Web.Script.Serialization; - -#endregion - -namespace DotNetNuke.Services.Journal { - public class JournalItem : IHydratable, IPropertyAccess { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Journal +{ + using System; + using System.Data; + using System.IO; + using System.Runtime.Serialization; + using System.Runtime.Serialization.Json; + using System.Web.Script.Serialization; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + using DotNetNuke.Services.Tokens; + + public class JournalItem : IHydratable, IPropertyAccess + { public int JournalId { get; set; } + public int JournalTypeId { get; set; } + public int PortalId { get; set; } + public int UserId { get; set; } + public int ProfileId { get; set; } + public int SocialGroupId { get; set; } + public string Title { get; set; } + public string Summary { get; set; } + public string Body { get; set; } + public ItemData ItemData { get; set; } + public XmlDocument JournalXML { get; set; } + public DateTime DateCreated { get; set; } + public DateTime DateUpdated { get; set; } + public string ObjectKey { get; set; } + public Guid AccessKey { get; set; } + public string SecuritySet { get; set; } + public int ContentItemId { get; set; } + public JournalEntity JournalAuthor { get; set; } + public JournalEntity JournalOwner { get; set; } + public string TimeFrame { get; set; } + public bool CurrentUserLikes { get; set; } + public string JournalType { get; set; } + public bool IsDeleted { get; set; } + public bool CommentsDisabled { get; set; } + public bool CommentsHidden { get; set; } - public int SimilarCount { get; set; } - - /// + + public int SimilarCount { get; set; } + + /// /// Gets or sets the key ID. /// /// @@ -59,92 +81,110 @@ public class JournalItem : IHydratable, IPropertyAccess { /// If you derive class has its own key id, please override this property and set the value to your own key id. /// [XmlIgnore] - public virtual int KeyID { - get { - return JournalId; + public virtual int KeyID + { + get + { + return this.JournalId; + } + + set + { + this.JournalId = value; } - set { - JournalId = value; + } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; } } - public void Fill(IDataReader dr) { - JournalId = Null.SetNullInteger(dr["JournalId"]); - JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); - PortalId = Null.SetNullInteger(dr["PortalId"]); - UserId = Null.SetNullInteger(dr["UserId"]); - ProfileId = Null.SetNullInteger(dr["ProfileId"]); - SocialGroupId = Null.SetNullInteger(dr["GroupId"]); - if (!String.IsNullOrEmpty(Null.SetNullString(dr["JournalXML"]))) { - JournalXML = new XmlDocument { XmlResolver = null }; - JournalXML.LoadXml(dr["JournalXML"].ToString()); - XmlNode xRoot = JournalXML.DocumentElement; + public void Fill(IDataReader dr) + { + this.JournalId = Null.SetNullInteger(dr["JournalId"]); + this.JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); + this.PortalId = Null.SetNullInteger(dr["PortalId"]); + this.UserId = Null.SetNullInteger(dr["UserId"]); + this.ProfileId = Null.SetNullInteger(dr["ProfileId"]); + this.SocialGroupId = Null.SetNullInteger(dr["GroupId"]); + if (!string.IsNullOrEmpty(Null.SetNullString(dr["JournalXML"]))) + { + this.JournalXML = new XmlDocument { XmlResolver = null }; + this.JournalXML.LoadXml(dr["JournalXML"].ToString()); + XmlNode xRoot = this.JournalXML.DocumentElement; XmlNode xNode = xRoot.SelectSingleNode("//items/item/body"); - if (xNode != null) { - Body = xNode.InnerText; + if (xNode != null) + { + this.Body = xNode.InnerText; } } - DateCreated = Null.SetNullDateTime(dr["DateCreated"]); - DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); - ObjectKey = Null.SetNullString(dr["ObjectKey"]); - AccessKey = Null.SetNullGuid(dr["AccessKey"]); - Title = Null.SetNullString(dr["Title"]); - Summary = Null.SetNullString(dr["Summary"]); + + this.DateCreated = Null.SetNullDateTime(dr["DateCreated"]); + this.DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); + this.ObjectKey = Null.SetNullString(dr["ObjectKey"]); + this.AccessKey = Null.SetNullGuid(dr["AccessKey"]); + this.Title = Null.SetNullString(dr["Title"]); + this.Summary = Null.SetNullString(dr["Summary"]); string itemd = Null.SetNullString(dr["ItemData"]); - ItemData = new ItemData(); - if (!string.IsNullOrEmpty(itemd)) { - ItemData = itemd.FromJson(); + this.ItemData = new ItemData(); + if (!string.IsNullOrEmpty(itemd)) + { + this.ItemData = itemd.FromJson(); } - ContentItemId = Null.SetNullInteger(dr["ContentItemId"]); - JournalAuthor = new JournalEntity(dr["JournalAuthor"].ToString()); - JournalOwner = new JournalEntity(dr["JournalOwner"].ToString()); - JournalType = Null.SetNullString(dr["JournalType"]); + + this.ContentItemId = Null.SetNullInteger(dr["ContentItemId"]); + this.JournalAuthor = new JournalEntity(dr["JournalAuthor"].ToString()); + this.JournalOwner = new JournalEntity(dr["JournalOwner"].ToString()); + this.JournalType = Null.SetNullString(dr["JournalType"]); - IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); - CommentsDisabled = Null.SetNullBoolean(dr["CommentsDisabled"]); - CommentsHidden = Null.SetNullBoolean(dr["CommentsHidden"]); - SimilarCount = Null.SetNullInteger(dr["SimilarCount"]); - } - public CacheLevel Cacheability { - get { - return CacheLevel.fullyCacheable; - } + this.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); + this.CommentsDisabled = Null.SetNullBoolean(dr["CommentsDisabled"]); + this.CommentsHidden = Null.SetNullBoolean(dr["CommentsHidden"]); + this.SimilarCount = Null.SetNullInteger(dr["SimilarCount"]); } - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { + public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { string OutputFormat = string.Empty; - if (format == string.Empty) { + if (format == string.Empty) + { OutputFormat = "g"; - } else { + } + else + { OutputFormat = format; } + propertyName = propertyName.ToLowerInvariant(); - switch (propertyName) { + switch (propertyName) + { case "journalid": - return PropertyAccess.FormatString(JournalId.ToString(), format); + return PropertyAccess.FormatString(this.JournalId.ToString(), format); case "journaltypeid": - return PropertyAccess.FormatString(JournalTypeId.ToString(), format); + return PropertyAccess.FormatString(this.JournalTypeId.ToString(), format); case "profileid": - return PropertyAccess.FormatString(ProfileId.ToString(), format); + return PropertyAccess.FormatString(this.ProfileId.ToString(), format); case "socialgroupid": - return PropertyAccess.FormatString(SocialGroupId.ToString(), format); + return PropertyAccess.FormatString(this.SocialGroupId.ToString(), format); case "datecreated": - return PropertyAccess.FormatString(DateCreated.ToString(), format); + return PropertyAccess.FormatString(this.DateCreated.ToString(), format); case "title": - return PropertyAccess.FormatString(Title, format); + return PropertyAccess.FormatString(this.Title, format); case "summary": - return PropertyAccess.FormatString(Summary, format); + return PropertyAccess.FormatString(this.Summary, format); case "body": - return PropertyAccess.FormatString(Body, format); + return PropertyAccess.FormatString(this.Body, format); case "timeframe": - return PropertyAccess.FormatString(TimeFrame, format); + return PropertyAccess.FormatString(this.TimeFrame, format); case "isdeleted": - return IsDeleted.ToString(); + return this.IsDeleted.ToString(); } propertyNotFound = true; return string.Empty; - } } } diff --git a/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs b/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs index 754faaa7e55..24fa6967348 100644 --- a/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs +++ b/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs @@ -1,49 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Common.Utilities; - -namespace DotNetNuke.Services.Journal { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.Journal +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + [Serializable] - public class JournalTypeInfo : IHydratable { + public class JournalTypeInfo : IHydratable + { public int JournalTypeId { get; set; } + public int PortalId { get; set; } + public string JournalType { get; set; } + public string icon { get; set; } + public bool AppliesToProfile { get; set; } + public bool AppliesToGroup { get; set; } + public bool AppliesToStream { get; set; } + public bool SupportsNotify { get; set; } + public string Options { get; set; } + public bool IsEnabled { get; set; } + public bool EnableComments { get; set; } - public int KeyID { - get { - return JournalTypeId; + + public int KeyID + { + get + { + return this.JournalTypeId; } - set { - JournalTypeId = value; + + set + { + this.JournalTypeId = value; } } - public void Fill(System.Data.IDataReader dr) { - JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); - PortalId = Null.SetNullInteger(dr["PortalId"]); - JournalType = Null.SetNullString(dr["JournalType"]); - icon = Null.SetNullString(dr["icon"]); - AppliesToProfile = Null.SetNullBoolean(dr["AppliesToProfile"]); - AppliesToGroup = Null.SetNullBoolean(dr["AppliesToGroup"]); - AppliesToStream = Null.SetNullBoolean(dr["AppliesToStream"]); - SupportsNotify = Null.SetNullBoolean(dr["SupportsNotify"]); - Options = Null.SetNullString(dr["Options"]); - IsEnabled = Null.SetNullBoolean(dr["IsEnabled"]); - EnableComments = Null.SetNullBoolean(dr["EnableComments"]); + public void Fill(System.Data.IDataReader dr) + { + this.JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); + this.PortalId = Null.SetNullInteger(dr["PortalId"]); + this.JournalType = Null.SetNullString(dr["JournalType"]); + this.icon = Null.SetNullString(dr["icon"]); + this.AppliesToProfile = Null.SetNullBoolean(dr["AppliesToProfile"]); + this.AppliesToGroup = Null.SetNullBoolean(dr["AppliesToGroup"]); + this.AppliesToStream = Null.SetNullBoolean(dr["AppliesToStream"]); + this.SupportsNotify = Null.SetNullBoolean(dr["SupportsNotify"]); + this.Options = Null.SetNullString(dr["Options"]); + this.IsEnabled = Null.SetNullBoolean(dr["IsEnabled"]); + this.EnableComments = Null.SetNullBoolean(dr["EnableComments"]); } } } diff --git a/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs b/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs index 369e9aff343..6d6d1525673 100644 --- a/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs +++ b/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs @@ -1,40 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.Globalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System.Collections; + using System.Globalization; + public class CultureInfoComparer : IComparer { private readonly string _compare; public CultureInfoComparer(string compareBy) { - _compare = compareBy; - } - - #region IComparer Members - + this._compare = compareBy; + } + public int Compare(object x, object y) { - switch (_compare.ToUpperInvariant()) + switch (this._compare.ToUpperInvariant()) { case "ENGLISH": - return ((CultureInfo) x).EnglishName.CompareTo(((CultureInfo) y).EnglishName); + return ((CultureInfo)x).EnglishName.CompareTo(((CultureInfo)y).EnglishName); case "NATIVE": - return ((CultureInfo) x).NativeName.CompareTo(((CultureInfo) y).NativeName); + return ((CultureInfo)x).NativeName.CompareTo(((CultureInfo)y).NativeName); default: - return ((CultureInfo) x).Name.CompareTo(((CultureInfo) y).Name); + return ((CultureInfo)x).Name.CompareTo(((CultureInfo)y).Name); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Localization/ILocaleController.cs b/DNN Platform/Library/Services/Localization/ILocaleController.cs index cb8fcdb257b..0c1498a8672 100644 --- a/DNN Platform/Library/Services/Localization/ILocaleController.cs +++ b/DNN Platform/Library/Services/Localization/ILocaleController.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Globalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System.Collections.Generic; + using System.Globalization; + public interface ILocaleController { bool CanDeleteLanguage(int languageId); diff --git a/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs b/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs index 26c26a011ca..3faeb576cff 100644 --- a/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs +++ b/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization { + using System.Collections.Generic; + + using DotNetNuke.Entities.Portals; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. @@ -14,9 +15,13 @@ namespace DotNetNuke.Services.Localization public interface ILocalizationProvider { string GetString(string key, string resourceFileRoot); + string GetString(string key, string resourceFileRoot, string language); + string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings); + string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings, bool disableShowMissingKeys); + /// /// Saves a string to a resource file. /// @@ -29,11 +34,11 @@ public interface ILocalizationProvider /// if set to true a new file will be created if it is not found. /// if set to true a new key will be created if not found. /// If the value could be saved then true will be returned, otherwise false. - /// Any file io error or similar will lead to exceptions + /// Any file io error or similar will lead to exceptions. bool SaveString(string key, string value, string resourceFileRoot, string language, PortalSettings portalSettings, DotNetNuke.Services.Localization.LocalizationProvider.CustomizedLocale resourceType, bool addFile, bool addKey); /// - /// Gets a compiled resource file for a specific language and portal. This takes the original resource file + /// Gets a compiled resource file for a specific language and portal. This takes the original resource file /// and overwrites it with any keys found in localized and overridden resource files according to .net and DNN rules. /// /// The portal settings for the requesting portal. Only used to retrieve PortalId and DefaultLanguage. diff --git a/DNN Platform/Library/Services/Localization/Internal/ILocalization.cs b/DNN Platform/Library/Services/Localization/Internal/ILocalization.cs index 17fbdb4de31..97f325f799f 100644 --- a/DNN Platform/Library/Services/Localization/Internal/ILocalization.cs +++ b/DNN Platform/Library/Services/Localization/Internal/ILocalization.cs @@ -1,51 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization.Internal { + using System; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Entities.Portals; + public interface ILocalization { /// - /// Inspect the browser supplied language headers and find the best match from the supplied list + /// Inspect the browser supplied language headers and find the best match from the supplied list. /// - /// The codes to search for a match - /// The code to return if no good match is found - /// Best matching culture code, or fallback if no good match found + /// The codes to search for a match. + /// The code to return if no good match is found. + /// Best matching culture code, or fallback if no good match found. string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes, string fallback); /// - /// Inspect the browser supplied language headers and find the best match from the supplied list + /// Inspect the browser supplied language headers and find the best match from the supplied list. /// - /// The codes to search for a match - /// Best matching culture code, or SystemLocale if no good match found + /// The codes to search for a match. + /// Best matching culture code, or SystemLocale if no good match found. string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes); /// /// Detects the current language for the request. /// The order in which the language is being detect is: - /// 1. QueryString - /// 2. Cookie - /// 3. User profile (if request is authenticated) - /// 4. Browser preference (if portal has this option enabled) - /// 5. Portal default - /// 6. System default (en-US) - /// At any point, if a valid language is detected nothing else should be done + /// 1. QueryString + /// 2. Cookie + /// 3. User profile (if request is authenticated) + /// 4. Browser preference (if portal has this option enabled) + /// 5. Portal default + /// 6. System default (en-US) + /// At any point, if a valid language is detected nothing else should be done. /// - /// Current PortalSettings - /// A valid CultureInfo + /// Current PortalSettings. + /// A valid CultureInfo. CultureInfo GetPageLocale(PortalSettings portalSettings); /// - /// Sets the culture codes on the current Thread + /// Sets the culture codes on the current Thread. /// - /// Culture Info for the current page - /// The current portalSettings + /// Culture Info for the current page. + /// The current portalSettings. /// /// This method will configure the Thread culture codes. Any page which does not derive from PageBase should /// be sure to call this method in OnInit to ensure localiztion works correctly. See the TelerikDialogHandler for an example. diff --git a/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs b/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs index aaa061661ca..55901298efa 100644 --- a/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs +++ b/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization.Internal { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + internal class LocalizationImpl : ILocalization { public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes, string fallback) { - if(cultureCodes == null) + if (cultureCodes == null) { throw new ArgumentException("cultureCodes cannot be null"); } @@ -26,29 +27,30 @@ public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable culture } var values = cultureCodes.ToList(); - + foreach (string langHeader in HttpContextSource.Current.Request.UserLanguages ?? new string[0]) { string lang = langHeader; - //strip any ;q=xx + + // strip any ;q=xx lang = lang.Split(';')[0]; - //check for exact match e.g. de-DE == de-DE + // check for exact match e.g. de-DE == de-DE if (lang.Contains('-')) { var match = values.FirstOrDefault(x => x == lang); - if(match != null) + if (match != null) { return match; } } - //only keep the initial language value + // only keep the initial language value if (lang.Length > 1) { lang = lang.Substring(0, 2); - //check for language match e.g. en-GB == en-US because en == en + // check for language match e.g. en-GB == en-US because en == en var match = values.FirstOrDefault(x => x.StartsWith(lang)); if (match != null) { @@ -62,7 +64,7 @@ public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable culture public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes) { - return BestCultureCodeBasedOnBrowserLanguages(cultureCodes, Localization.SystemLocale); + return this.BestCultureCodeBasedOnBrowserLanguages(cultureCodes, Localization.SystemLocale); } public CultureInfo GetPageLocale(PortalSettings portalSettings) diff --git a/DNN Platform/Library/Services/Localization/Internal/TestableLocalization.cs b/DNN Platform/Library/Services/Localization/Internal/TestableLocalization.cs index c4e82d52054..cbe41bcd274 100644 --- a/DNN Platform/Library/Services/Localization/Internal/TestableLocalization.cs +++ b/DNN Platform/Library/Services/Localization/Internal/TestableLocalization.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization.Internal { + using System; + + using DotNetNuke.Framework; + public class TestableLocalization : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Localization/LanguagePackController.cs b/DNN Platform/Library/Services/Localization/LanguagePackController.cs index e95f91a2c31..d6eb26baa98 100644 --- a/DNN Platform/Library/Services/Localization/LanguagePackController.cs +++ b/DNN Platform/Library/Services/Localization/LanguagePackController.cs @@ -1,37 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Log.EventLog; + public class LanguagePackController { public static void DeleteLanguagePack(LanguagePackInfo languagePack) { - // fix DNN-26330 Removing a language pack extension removes the language + // fix DNN-26330 Removing a language pack extension removes the language // we should not delete language when deleting language pack, as there is just a loose relationship - //if (languagePack.PackageType == LanguagePackType.Core) - //{ + // if (languagePack.PackageType == LanguagePackType.Core) + // { // Locale language = LocaleController.Instance.GetLocale(languagePack.LanguageID); // if (language != null) // { // Localization.DeleteLanguage(language); // } - //} - + // } DataProvider.Instance().DeleteLanguagePack(languagePack.LanguagePackID); - EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGEPACK_DELETED); + EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGEPACK_DELETED); } public static LanguagePackInfo GetLanguagePackByPackage(int packageID) @@ -43,22 +37,24 @@ public static void SaveLanguagePack(LanguagePackInfo languagePack) { if (languagePack.LanguagePackID == Null.NullInteger) { - //Add Language Pack - languagePack.LanguagePackID = DataProvider.Instance().AddLanguagePack(languagePack.PackageID, - languagePack.LanguageID, - languagePack.DependentPackageID, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGEPACK_CREATED); + // Add Language Pack + languagePack.LanguagePackID = DataProvider.Instance().AddLanguagePack( + languagePack.PackageID, + languagePack.LanguageID, + languagePack.DependentPackageID, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGEPACK_CREATED); } else { - //Update LanguagePack - DataProvider.Instance().UpdateLanguagePack(languagePack.LanguagePackID, - languagePack.PackageID, - languagePack.LanguageID, - languagePack.DependentPackageID, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGEPACK_UPDATED); + // Update LanguagePack + DataProvider.Instance().UpdateLanguagePack( + languagePack.LanguagePackID, + languagePack.PackageID, + languagePack.LanguageID, + languagePack.DependentPackageID, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGEPACK_UPDATED); } } } diff --git a/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs b/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs index 7b526704997..646a434d9fe 100644 --- a/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs +++ b/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs @@ -1,43 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + [Serializable] public class LanguagePackInfo : BaseEntityInfo, IHydratable - { - #region "Private Members" - + { private int _DependentPackageID = Null.NullInteger; private int _LanguageID = Null.NullInteger; private int _LanguagePackID = Null.NullInteger; - private int _PackageID = Null.NullInteger; - - #endregion - - #region "Public Properties" - + private int _PackageID = Null.NullInteger; + public int LanguagePackID { get { - return _LanguagePackID; + return this._LanguagePackID; } + set { - _LanguagePackID = value; + this._LanguagePackID = value; } } @@ -45,11 +35,12 @@ public int LanguageID { get { - return _LanguageID; + return this._LanguageID; } + set { - _LanguageID = value; + this._LanguageID = value; } } @@ -57,11 +48,12 @@ public int PackageID { get { - return _PackageID; + return this._PackageID; } + set { - _PackageID = value; + this._PackageID = value; } } @@ -69,11 +61,12 @@ public int DependentPackageID { get { - return _DependentPackageID; + return this._DependentPackageID; } + set { - _DependentPackageID = value; + this._DependentPackageID = value; } } @@ -81,7 +74,7 @@ public LanguagePackType PackageType { get { - if (DependentPackageID == -2) + if (this.DependentPackageID == -2) { return LanguagePackType.Core; } @@ -90,34 +83,30 @@ public LanguagePackType PackageType return LanguagePackType.Extension; } } - } - - #endregion - - #region IHydratable Members - - public void Fill(IDataReader dr) - { - LanguagePackID = Null.SetNullInteger(dr["LanguagePackID"]); - LanguageID = Null.SetNullInteger(dr["LanguageID"]); - PackageID = Null.SetNullInteger(dr["PackageID"]); - DependentPackageID = Null.SetNullInteger(dr["DependentPackageID"]); - //Call the base classes fill method to populate base class proeprties - base.FillInternal(dr); - } + } public int KeyID { get { - return LanguagePackID; + return this.LanguagePackID; } + set { - LanguagePackID = value; + this.LanguagePackID = value; } + } + + public void Fill(IDataReader dr) + { + this.LanguagePackID = Null.SetNullInteger(dr["LanguagePackID"]); + this.LanguageID = Null.SetNullInteger(dr["LanguageID"]); + this.PackageID = Null.SetNullInteger(dr["PackageID"]); + this.DependentPackageID = Null.SetNullInteger(dr["DependentPackageID"]); + + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Localization/LanguagePackType.cs b/DNN Platform/Library/Services/Localization/LanguagePackType.cs index 9580e2caf3b..2df2137e3a2 100644 --- a/DNN Platform/Library/Services/Localization/LanguagePackType.cs +++ b/DNN Platform/Library/Services/Localization/LanguagePackType.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization { public enum LanguagePackType { Core, - Extension + Extension, } } diff --git a/DNN Platform/Library/Services/Localization/LanguagesListType.cs b/DNN Platform/Library/Services/Localization/LanguagesListType.cs index af4efe63623..4cfeb7a306e 100644 --- a/DNN Platform/Library/Services/Localization/LanguagesListType.cs +++ b/DNN Platform/Library/Services/Localization/LanguagesListType.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization { /// ----------------------------------------------------------------------------- /// - /// Enumeration that determines the type of Languages List + /// Enumeration that determines the type of Languages List. /// /// ----------------------------------------------------------------------------- public enum LanguagesListType { All, Supported, - Enabled + Enabled, } } diff --git a/DNN Platform/Library/Services/Localization/Locale.cs b/DNN Platform/Library/Services/Localization/Locale.cs index 6e7d7d95bf9..dc531d2925b 100644 --- a/DNN Platform/Library/Services/Localization/Locale.cs +++ b/DNN Platform/Library/Services/Localization/Locale.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Globalization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System; + using System.Data; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// /// The Locale class is a custom business object that represents a locale, which is the language and country combination. /// @@ -24,20 +19,18 @@ public class Locale : BaseEntityInfo, IHydratable { public Locale() { - PortalId = Null.NullInteger; - LanguageId = Null.NullInteger; - IsPublished = Null.NullBoolean; - } - - #region Public Properties - + this.PortalId = Null.NullInteger; + this.LanguageId = Null.NullInteger; + this.IsPublished = Null.NullBoolean; + } + public string Code { get; set; } public CultureInfo Culture { get { - return CultureInfo.GetCultureInfo(Code); + return CultureInfo.GetCultureInfo(this.Code); } } @@ -46,10 +39,11 @@ public string EnglishName get { string _Name = Null.NullString; - if (Culture != null) + if (this.Culture != null) { - _Name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Culture.EnglishName); + _Name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(this.Culture.EnglishName); } + return _Name; } } @@ -61,10 +55,11 @@ public Locale FallBackLocale get { Locale _FallbackLocale = null; - if (!string.IsNullOrEmpty(Fallback)) + if (!string.IsNullOrEmpty(this.Fallback)) { - _FallbackLocale = LocaleController.Instance.GetLocale(PortalId, Fallback); + _FallbackLocale = LocaleController.Instance.GetLocale(this.PortalId, this.Fallback); } + return _FallbackLocale; } } @@ -78,56 +73,51 @@ public string NativeName get { string _Name = Null.NullString; - if (Culture != null) + if (this.Culture != null) { - _Name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Culture.NativeName); + _Name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(this.Culture.NativeName); } + return _Name; } } public int PortalId { get; set; } - public string Text { get; set; } - - #endregion - - #region IHydratable Implementation - - public void Fill(IDataReader dr) - { - LanguageId = Null.SetNullInteger(dr["LanguageID"]); - Code = Null.SetNullString(dr["CultureCode"]); - Text = Null.SetNullString(dr["CultureName"]); - Fallback = Null.SetNullString(dr["FallbackCulture"]); - - //These fields may not be populated (for Host level locales) - DataTable schemaTable = dr.GetSchemaTable(); - bool hasColumns = schemaTable.Select("ColumnName = 'IsPublished' Or ColumnName = 'PortalID'").Length == 2; - - if(hasColumns) - { - IsPublished = Null.SetNullBoolean(dr["IsPublished"]); - PortalId = Null.SetNullInteger(dr["PortalID"]); - } - - //Call the base classes fill method to populate base class proeprties - base.FillInternal(dr); - } + public string Text { get; set; } public int KeyID { get { - return LanguageId; + return this.LanguageId; } + set { - LanguageId = value; + this.LanguageId = value; } - } + } + + public void Fill(IDataReader dr) + { + this.LanguageId = Null.SetNullInteger(dr["LanguageID"]); + this.Code = Null.SetNullString(dr["CultureCode"]); + this.Text = Null.SetNullString(dr["CultureName"]); + this.Fallback = Null.SetNullString(dr["FallbackCulture"]); - #endregion + // These fields may not be populated (for Host level locales) + DataTable schemaTable = dr.GetSchemaTable(); + bool hasColumns = schemaTable.Select("ColumnName = 'IsPublished' Or ColumnName = 'PortalID'").Length == 2; + + if (hasColumns) + { + this.IsPublished = Null.SetNullBoolean(dr["IsPublished"]); + this.PortalId = Null.SetNullInteger(dr["PortalID"]); + } - } + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); + } + } } diff --git a/DNN Platform/Library/Services/Localization/LocaleCollection.cs b/DNN Platform/Library/Services/Localization/LocaleCollection.cs index f4cdaf63719..f57afa35f0a 100644 --- a/DNN Platform/Library/Services/Localization/LocaleCollection.cs +++ b/DNN Platform/Library/Services/Localization/LocaleCollection.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Specialized; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System; + using System.Collections; + using System.Collections.Specialized; + /// /// The LocaleCollection class is a collection of Locale objects. It stores the supported locales. /// @@ -19,66 +14,67 @@ public class LocaleCollection : NameObjectCollectionBase { private DictionaryEntry _de; - public DictionaryEntry this[int index] + // Gets a String array that contains all the keys in the collection. + public string[] AllKeys { get { - _de.Key = BaseGetKey(index); - _de.Value = BaseGet(index); - return _de; + return this.BaseGetAllKeys(); } } - //Gets or sets the value associated with the specified key. - public Locale this[string key] + // Gets an Object array that contains all the values in the collection. + public Array AllValues { get { - return (Locale) BaseGet(key); - } - set - { - BaseSet(key, value); + return this.BaseGetAllValues(); } } - //Gets a String array that contains all the keys in the collection. - public string[] AllKeys + // Gets a value indicating if the collection contains keys that are not null. + public bool HasKeys { get { - return BaseGetAllKeys(); + return this.BaseHasKeys(); } } - //Gets an Object array that contains all the values in the collection. - public Array AllValues + public DictionaryEntry this[int index] { get { - return BaseGetAllValues(); + this._de.Key = this.BaseGetKey(index); + this._de.Value = this.BaseGet(index); + return this._de; } } - //Gets a value indicating if the collection contains keys that are not null. - public Boolean HasKeys + // Gets or sets the value associated with the specified key. + public Locale this[string key] { get { - return BaseHasKeys(); + return (Locale)this.BaseGet(key); + } + + set + { + this.BaseSet(key, value); } } - //Adds an entry to the collection. - public void Add(String key, Object value) + // Adds an entry to the collection. + public void Add(string key, object value) { - BaseAdd(key, value); + this.BaseAdd(key, value); } - //Removes an entry with the specified key from the collection. - public void Remove(String key) + // Removes an entry with the specified key from the collection. + public void Remove(string key) { - BaseRemove(key); + this.BaseRemove(key); } } } diff --git a/DNN Platform/Library/Services/Localization/LocaleController.cs b/DNN Platform/Library/Services/Localization/LocaleController.cs index a7a831178af..8e8c58de632 100644 --- a/DNN Platform/Library/Services/Localization/LocaleController.cs +++ b/DNN Platform/Library/Services/Localization/LocaleController.cs @@ -1,55 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Installer.Packages; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Installer.Packages; + /// /// LocaleContrller provides method to manage all pages with localization content. /// /// - /// Content localization in DotNetNuke will allow you to easily manage your web pages in a primary language - /// and then utilize translators to keep the content synchronized in multiple secondary languages. - /// Whether you are maintaining your site in a single language or dozens of languages, the content localization system - /// will help guide your content editors and translators through the process. Although content localization required + /// Content localization in DotNetNuke will allow you to easily manage your web pages in a primary language + /// and then utilize translators to keep the content synchronized in multiple secondary languages. + /// Whether you are maintaining your site in a single language or dozens of languages, the content localization system + /// will help guide your content editors and translators through the process. Although content localization required /// extensive changes to the core platform, we have been able to add this new feature while still improving overall system performance. /// public class LocaleController : ComponentBase, ILocaleController - { - #region Private Shared Methods - - private static object GetLocalesCallBack(CacheItemArgs cacheItemArgs) + { + public static bool IsValidCultureName(string name) { - var portalID = (int)cacheItemArgs.ParamList[0]; - Dictionary locales = CBO.FillDictionary("CultureCode", portalID > Null.NullInteger - ? DataProvider.Instance().GetLanguagesByPortal(portalID) - : DataProvider.Instance().GetLanguages(), new Dictionary(StringComparer.OrdinalIgnoreCase)); - return locales; - } - - #endregion - - #region Public Methods - + return + CultureInfo + .GetCultures(CultureTypes.SpecificCultures) + .Any(c => c.Name == name); + } + /// /// Determines whether the language can be delete. /// @@ -73,6 +61,15 @@ public List GetCultures(Dictionary locales) { return locales.Values.Select(locale => new CultureInfo(locale.Code)).ToList(); } + + private static object GetLocalesCallBack(CacheItemArgs cacheItemArgs) + { + var portalID = (int)cacheItemArgs.ParamList[0]; + Dictionary locales = CBO.FillDictionary("CultureCode", portalID > Null.NullInteger + ? DataProvider.Instance().GetLanguagesByPortal(portalID) + : DataProvider.Instance().GetLanguages(), new Dictionary(StringComparer.OrdinalIgnoreCase)); + return locales; + } /// /// Gets the current locale for current request to the portal. @@ -85,11 +82,12 @@ public Locale GetCurrentLocale(int PortalId) if (HttpContext.Current != null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["language"])) { - locale = GetLocale(HttpContext.Current.Request.QueryString["language"]); + locale = this.GetLocale(HttpContext.Current.Request.QueryString["language"]); } + return locale ?? ((PortalId == Null.NullInteger) - ? GetLocale(Localization.SystemLocale) - : GetDefaultLocale(PortalId)); + ? this.GetLocale(Localization.SystemLocale) + : this.GetDefaultLocale(PortalId)); } /// @@ -103,13 +101,14 @@ public Locale GetDefaultLocale(int portalId) Locale locale = null; if (portal != null) { - Dictionary locales = GetLocales(portal.PortalID); + Dictionary locales = this.GetLocales(portal.PortalID); if (locales != null && locales.ContainsKey(portal.DefaultLanguage)) { locale = locales[portal.DefaultLanguage]; } } - return locale ?? (GetLocale(Localization.SystemLocale)); + + return locale ?? this.GetLocale(Localization.SystemLocale); } /// @@ -119,7 +118,7 @@ public Locale GetDefaultLocale(int portalId) /// public Locale GetLocale(string code) { - return GetLocale(Null.NullInteger, code); + return this.GetLocale(Null.NullInteger, code); } /// @@ -130,7 +129,7 @@ public Locale GetLocale(string code) /// public Locale GetLocale(int portalID, string code) { - Dictionary dicLocales = GetLocales(portalID); + Dictionary dicLocales = this.GetLocales(portalID); Locale locale = null; if (dicLocales != null) @@ -161,7 +160,7 @@ public Locale GetLocaleOrCurrent(int portalID, string code) /// public Locale GetLocale(int languageID) { - Dictionary dicLocales = GetLocales(Null.NullInteger); + Dictionary dicLocales = this.GetLocales(Null.NullInteger); return (from kvp in dicLocales where kvp.Value.LanguageId == languageID select kvp.Value).FirstOrDefault(); } @@ -185,7 +184,8 @@ public Dictionary GetLocales(int portalID) { locales = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguages(), new Dictionary(StringComparer.OrdinalIgnoreCase)); } - return locales; + + return locales; } return null; @@ -198,7 +198,7 @@ public Dictionary GetLocales(int portalID) /// public Dictionary GetPublishedLocales(int portalID) { - return GetLocales(portalID).Where(kvp => kvp.Value.IsPublished).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + return this.GetLocales(portalID).Where(kvp => kvp.Value.IsPublished).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } /// @@ -214,20 +214,20 @@ public bool IsEnabled(ref string localeCode, int portalId) try { bool enabled = false; - Dictionary dicLocales = GetLocales(portalId); + Dictionary dicLocales = this.GetLocales(portalId); - //if ((!dicLocales.ContainsKey(localeCode))) + // if ((!dicLocales.ContainsKey(localeCode))) string locale = localeCode; if (dicLocales.FirstOrDefault(x => x.Key.ToLower() == locale.ToLower()).Key == null) { - //if localecode is neutral (en, es,...) try to find a locale that has the same language + // if localecode is neutral (en, es,...) try to find a locale that has the same language if (localeCode.IndexOf("-", StringComparison.Ordinal) == -1) { foreach (string strLocale in dicLocales.Keys) { if (strLocale.Split('-')[0].ToLower() == localeCode.ToLower()) { - //set the requested _localecode to the full locale + // set the requested _localecode to the full locale localeCode = strLocale; enabled = true; break; @@ -239,11 +239,12 @@ public bool IsEnabled(ref string localeCode, int portalId) { enabled = true; } + return enabled; } catch (Exception ex) { - //item could not be retrieved or error + // item could not be retrieved or error Exceptions.Exceptions.LogException(ex); return false; } @@ -311,15 +312,5 @@ public void PublishLanguage(int portalid, string cultureCode, bool publish) } } } - - public static bool IsValidCultureName(string name) - { - return - CultureInfo - .GetCultures(CultureTypes.SpecificCultures) - .Any(c => c.Name == name); - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Localization/Localization.cs b/DNN Platform/Library/Services/Localization/Localization.cs index f632ccc835b..cb9d342172f 100644 --- a/DNN Platform/Library/Services/Localization/Localization.cs +++ b/DNN Platform/Library/Services/Localization/Localization.cs @@ -1,44 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Localization.Internal; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Tokens; -using DotNetNuke.UI.Modules; -using System.Text.RegularExpressions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization.Internal; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Tokens; + using DotNetNuke.UI.Modules; + /// - /// CultureDropDownTypes allows the user to specify which culture name is displayed in the drop down list that is filled + /// CultureDropDownTypes allows the user to specify which culture name is displayed in the drop down list that is filled /// by using one of the helper methods. /// [Serializable] @@ -48,43 +44,49 @@ public enum CultureDropDownTypes /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in the .NET Framework language /// DisplayName, + /// /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in English /// EnglishName, + /// /// Displays the culture identifier /// Lcid, + /// /// Displays the culture name in the format "<languagecode2> (<country/regioncode2>) /// Name, + /// /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in the language that the culture is set to display /// NativeName, + /// /// Displays the IS0 639-1 two letter code /// TwoLetterIsoCode, + /// /// Displays the ISO 629-2 three letter code "<languagefull> (<country/regionfull>) /// - ThreeLetterIsoCode + ThreeLetterIsoCode, } /// /// Localization class support localization in system. /// /// - /// As DNN is used in more and more countries it is very important to provide modules with - /// good support for international users. Otherwise we are limiting our potential user base to + /// As DNN is used in more and more countries it is very important to provide modules with + /// good support for international users. Otherwise we are limiting our potential user base to /// that using English as their base language. /// /// You can store the muti language content in resource files and use the api below to get localization content. /// Resouces files named as: Control(Page)Name + Extension (.aspx/.ascx ) + Language + ".resx" - /// e.g: Installwizard.aspx.de-DE.resx + /// e.g: Installwizard.aspx.de-DE.resx. /// /// /// @@ -98,20 +100,15 @@ public enum CultureDropDownTypes /// public class Localization { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Localization)); - - #region Private Members - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Localization)); private static string _defaultKeyName = "resourcekey"; - //private static readonly ILocaleController LocaleController.Instance = LocaleController.Instance; - //private static readonly ILocalizationProvider _localizationProvider = LocalizationProvider.Instance; - private static bool? _showMissingKeys; - #endregion - - #region Public Shared Properties - + + // private static readonly ILocaleController LocaleController.Instance = LocaleController.Instance; + // private static readonly ILocalizationProvider _localizationProvider = LocalizationProvider.Instance; + private static bool? _showMissingKeys; + /// - /// Returns ~/App_GlobalResources + /// Gets ~/App_GlobalResources. /// public static string ApplicationResourceDirectory { @@ -122,7 +119,7 @@ public static string ApplicationResourceDirectory } /// - /// Returns ~/App_GlobalResources/Exceptions.resx + /// Gets ~/App_GlobalResources/Exceptions.resx. /// public static string ExceptionsResourceFile { @@ -133,7 +130,7 @@ public static string ExceptionsResourceFile } /// - /// Returns ~/App_GlobalResources/GlobalResources.resx + /// Gets ~/App_GlobalResources/GlobalResources.resx. /// public static string GlobalResourceFile { @@ -145,7 +142,7 @@ public static string GlobalResourceFile /// ----------------------------------------------------------------------------- /// - /// The KeyName property returns and caches the name of the key attribute used to lookup resources. + /// Gets or sets the KeyName property returns and caches the name of the key attribute used to lookup resources. /// This can be configured by setting ResourceManagerKey property in the web.config file. The default value for this property /// is 'key'. /// @@ -156,10 +153,11 @@ public static string KeyName { return _defaultKeyName; } + set { _defaultKeyName = value; - if (String.IsNullOrEmpty(_defaultKeyName)) + if (string.IsNullOrEmpty(_defaultKeyName)) { _defaultKeyName = "resourcekey"; } @@ -192,7 +190,7 @@ public static string SharedResourceFile /// ----------------------------------------------------------------------------- /// - /// The ShowMissingKeys property returns the web.config setting that determines + /// Gets a value indicating whether the ShowMissingKeys property returns the web.config setting that determines /// whether to render a visual indicator that a key is missing /// is 'key'. /// @@ -241,15 +239,11 @@ public static string SystemTimeZone { return "Pacific Standard Time"; } - } - - #endregion - - #region Public Properties - + } + /// ----------------------------------------------------------------------------- /// - /// The CurrentCulture returns the current Culture being used + /// Gets the CurrentCulture returns the current Culture being used /// is 'key'. /// /// ----------------------------------------------------------------------------- @@ -257,13 +251,13 @@ public string CurrentCulture { get { - //_CurrentCulture + // _CurrentCulture return Thread.CurrentThread.CurrentCulture.ToString(); } } /// - /// The CurrentUICulture for the Thread + /// Gets the CurrentUICulture for the Thread. /// public string CurrentUICulture { @@ -272,29 +266,95 @@ public string CurrentUICulture { return Thread.CurrentThread.CurrentUICulture.ToString(); } + } + + public static int ActiveLanguagesByPortalID(int portalID) + { + // Default to 1 (maybe called during portal creation before languages are enabled for portal) + int count = 1; + Dictionary locales = LocaleController.Instance.GetLocales(portalID); + if (locales != null) + { + count = locales.Count; + } + + return count; } - #endregion + public static void AddLanguageToPortal(int portalID, int languageID, bool clearCache) + { + // try to get valid locale reference + var newLocale = LocaleController.Instance.GetLocale(languageID); - #region Private Shared Methods + // we can only add a valid locale + if (newLocale != null) + { + // check if locale has not been added to portal already + var portalLocale = LocaleController.Instance.GetLocale(portalID, newLocale.Code); + // locale needs to be added + if (portalLocale == null) + { + // We need to add a translator role for the language + bool contentLocalizationEnabled = PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalID, false); + if (contentLocalizationEnabled) + { + // Create new Translator Role + AddTranslatorRole(portalID, newLocale); + } + + DataProvider.Instance().AddPortalLanguage(portalID, languageID, false, UserController.Instance.GetCurrentUserInfo().UserID); + string cacheKey = string.Format(DataCache.LocalesCacheKey, portalID); + DataCache.RemoveCache(cacheKey); + + EventLogController.Instance.AddLog( + "portalID/languageID", + portalID + "/" + languageID, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.LANGUAGETOPORTAL_CREATED); + + var portalInfo = PortalController.Instance.GetPortal(portalID); + if (portalInfo != null && newLocale.Code != portalInfo.DefaultLanguage) + { + // check to see if this is the first extra language being added to the portal + var portalLocales = LocaleController.Instance.GetLocales(portalID); + var firstExtraLanguage = (portalLocales != null) && portalLocales.Count == 2; + + if (firstExtraLanguage) + { + AddLanguageHttpAlias(portalID, LocaleController.Instance.GetLocale(portalID, portalInfo.DefaultLanguage)); + } + + AddLanguageHttpAlias(portalID, newLocale); + } + + if (clearCache) + { + DataCache.ClearPortalCache(portalID, false); + } + } + } + } + private static void LocalizeDataControlField(DataControlField controlField, string resourceFile) { string localizedText; - //Localize Header Text + // Localize Header Text if (!string.IsNullOrEmpty(controlField.HeaderText)) { - localizedText = GetString((controlField.HeaderText + ".Header"), resourceFile); + localizedText = GetString(controlField.HeaderText + ".Header", resourceFile); if (!string.IsNullOrEmpty(localizedText)) { controlField.HeaderText = localizedText; controlField.AccessibleHeaderText = controlField.HeaderText; } } + if (controlField is TemplateField) { - //do nothing + // do nothing } else if (controlField is ButtonField) { @@ -322,31 +382,37 @@ private static void LocalizeDataControlField(DataControlField controlField, stri { commands.CancelText = localizedText; } + localizedText = GetString(commands.DeleteText, resourceFile); if (!string.IsNullOrEmpty(localizedText)) { commands.DeleteText = localizedText; } + localizedText = GetString(commands.EditText, resourceFile); if (!string.IsNullOrEmpty(localizedText)) { commands.EditText = localizedText; } + localizedText = GetString(commands.InsertText, resourceFile); if (!string.IsNullOrEmpty(localizedText)) { commands.InsertText = localizedText; } + localizedText = GetString(commands.NewText, resourceFile); if (!string.IsNullOrEmpty(localizedText)) { commands.NewText = localizedText; } + localizedText = GetString(commands.SelectText, resourceFile); if (!string.IsNullOrEmpty(localizedText)) { commands.SelectText = localizedText; } + localizedText = GetString(commands.UpdateText, resourceFile); if (!string.IsNullOrEmpty(localizedText)) { @@ -371,81 +437,30 @@ private static void LocalizeDataControlField(DataControlField controlField, stri image.AlternateText = localizedText; } } - } - - #endregion - - #region Public Methods + } - public static int ActiveLanguagesByPortalID(int portalID) + public static void AddLanguagesToPortal(int portalID) { - //Default to 1 (maybe called during portal creation before languages are enabled for portal) - - int count = 1; - Dictionary locales = LocaleController.Instance.GetLocales(portalID); - if (locales != null) + foreach (Locale language in LocaleController.Instance.GetLocales(Null.NullInteger).Values) { - count = locales.Count; + // Add Portal/Language to PortalLanguages + AddLanguageToPortal(portalID, language.LanguageId, false); } - return count; + + DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portalID)); } - public static void AddLanguageToPortal(int portalID, int languageID, bool clearCache) + public static void AddLanguageToPortals(int languageID) { - - // try to get valid locale reference - var newLocale = LocaleController.Instance.GetLocale(languageID); - - // we can only add a valid locale - if (newLocale != null) + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - // check if locale has not been added to portal already - var portalLocale = LocaleController.Instance.GetLocale(portalID, newLocale.Code); - - // locale needs to be added - if (portalLocale == null) - { - //We need to add a translator role for the language - bool contentLocalizationEnabled = PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalID, false); - if (contentLocalizationEnabled) - { - //Create new Translator Role - AddTranslatorRole(portalID, newLocale); - } - - DataProvider.Instance().AddPortalLanguage(portalID, languageID, false, UserController.Instance.GetCurrentUserInfo().UserID); - string cacheKey = string.Format(DataCache.LocalesCacheKey, portalID); - DataCache.RemoveCache(cacheKey); - - EventLogController.Instance.AddLog("portalID/languageID", - portalID + "/" + languageID, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.LANGUAGETOPORTAL_CREATED); - - var portalInfo = PortalController.Instance.GetPortal(portalID); - if (portalInfo != null && newLocale.Code != portalInfo.DefaultLanguage) - { - // check to see if this is the first extra language being added to the portal - var portalLocales = LocaleController.Instance.GetLocales(portalID); - var firstExtraLanguage = (portalLocales != null) && portalLocales.Count == 2; - - if (firstExtraLanguage) - { - AddLanguageHttpAlias(portalID, LocaleController.Instance.GetLocale(portalID, portalInfo.DefaultLanguage)); - } - AddLanguageHttpAlias(portalID, newLocale); - } + // Add Portal/Language to PortalLanguages + AddLanguageToPortal(portal.PortalID, languageID, false); - if (clearCache) - { - DataCache.ClearPortalCache(portalID, false); - } - } + DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portal.PortalID)); } } - - + private static void AddLanguageHttpAlias(int portalId, Locale locale) { if (Config.GetFriendlyUrlProvider() == "advanced") @@ -471,7 +486,6 @@ private static void AddLanguageHttpAlias(int portalId, Locale locale) if (currentAlias != null && !string.IsNullOrEmpty(httpAlias) && portalInfo != null) { - if (!string.IsNullOrEmpty(currentAlias.CultureCode)) { // the portal alias is culture specific @@ -483,14 +497,14 @@ private static void AddLanguageHttpAlias(int portalId, Locale locale) } var alias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()); - if (!String.IsNullOrEmpty(alias)) + if (!string.IsNullOrEmpty(alias)) { - var newAlias = new PortalAliasInfo(currentAlias) - { - IsPrimary = true, - CultureCode = locale.Code, - HTTPAlias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()) - }; + var newAlias = new PortalAliasInfo(currentAlias) + { + IsPrimary = true, + CultureCode = locale.Code, + HTTPAlias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()), + }; PortalAliasController.Instance.AddPortalAlias(newAlias); } @@ -512,15 +526,15 @@ private static string GetValidLanguageURL(int portalId, string httpAlias, string modifiedLocale += counter.ToString(CultureInfo.InvariantCulture); } - alias = String.Format("{0}/{1}", httpAlias, modifiedLocale); + alias = string.Format("{0}/{1}", httpAlias, modifiedLocale); var tab = TabController.Instance.GetTabByName(modifiedLocale, portalId); - isValid = (tab == null); + isValid = tab == null; if (isValid) { var user = UserController.GetUserByVanityUrl(portalId, modifiedLocale); - isValid = (user == null); + isValid = user == null; } if (isValid) @@ -535,35 +549,15 @@ private static string GetValidLanguageURL(int portalId, string httpAlias, string } counter++; - } while (!isValid); + } + while (!isValid); return alias; } - public static void AddLanguagesToPortal(int portalID) - { - foreach (Locale language in LocaleController.Instance.GetLocales(Null.NullInteger).Values) - { - //Add Portal/Language to PortalLanguages - AddLanguageToPortal(portalID, language.LanguageId, false); - } - DataCache.RemoveCache(String.Format(DataCache.LocalesCacheKey, portalID)); - } - - public static void AddLanguageToPortals(int languageID) - { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - //Add Portal/Language to PortalLanguages - AddLanguageToPortal(portal.PortalID, languageID, false); - - DataCache.RemoveCache(String.Format(DataCache.LocalesCacheKey, portal.PortalID)); - } - } - public static void AddTranslatorRole(int portalID, Locale language) { - //Create new Translator Role + // Create new Translator Role string roleName = string.Format("Translator ({0})", language.Code); RoleInfo role = RoleController.Instance.GetRole(portalID, r => r.RoleName == roleName); @@ -585,9 +579,9 @@ public static void AddTranslatorRole(int portalID, Locale language) } /// - /// Converts old TimeZoneOffset to new TimeZoneInfo. + /// Converts old TimeZoneOffset to new TimeZoneInfo. /// - /// An offset in minutes, e.g. -480 (-8 times 60) for Pasicif Time Zone + /// An offset in minutes, e.g. -480 (-8 times 60) for Pasicif Time Zone. /// TimeZoneInfo is returned if timeZoneOffsetInMinutes is valid, otherwise TimeZoneInfo.Local is returned. /// Initial mapping is based on hard-coded rules. These rules are hard-coded from old standard TimeZones.xml data. /// When offset is not found hard-coded mapping, a lookup is performed in timezones defined in the system. The first found entry is returned. @@ -596,7 +590,7 @@ public static TimeZoneInfo ConvertLegacyTimeZoneOffsetToTimeZoneInfo(int timeZon { TimeZoneInfo timeZoneInfo = TimeZoneInfo.Local; - //lookup existing mapping + // lookup existing mapping switch (timeZoneOffsetInMinutes) { case -720: @@ -707,6 +701,7 @@ public static TimeZoneInfo ConvertLegacyTimeZoneOffsetToTimeZoneInfo(int timeZon break; } } + break; } @@ -720,15 +715,14 @@ public static void DeleteLanguage(Locale language) public static void DeleteLanguage(Locale language, bool isInstalling) { - //remove languages from all portals + // remove languages from all portals RemoveLanguageFromPortals(language.LanguageId, isInstalling); DataProvider.Instance().DeleteLanguage(language.LanguageId); - EventLogController.Instance.AddLog(language, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGE_DELETED); + EventLogController.Instance.AddLog(language, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGE_DELETED); DataCache.ClearHostCache(true); } - - + public static string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes, string fallback) { return TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(cultureCodes, fallback); @@ -737,16 +731,15 @@ public static string BestCultureCodeBasedOnBrowserLanguages(IEnumerable public static string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes) { return TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(cultureCodes); - } - - #region GetExceptionMessage - + } + public static string GetExceptionMessage(string key, string defaultValue) { if (HttpContext.Current == null) { return defaultValue; } + return GetString(key, ExceptionsResourceFile); } @@ -756,33 +749,10 @@ public static string GetExceptionMessage(string key, string defaultValue, params { return string.Format(defaultValue, @params); } + var content = GetString(key, ExceptionsResourceFile); - return string.Format(String.IsNullOrEmpty(content) ? defaultValue : GetString(key, ExceptionsResourceFile), @params); - } - - #endregion - - public string GetFixedCurrency(decimal expression, string culture, int numDigitsAfterDecimal) - { - string oldCurrentCulture = CurrentUICulture; - var newCulture = new CultureInfo(culture); - Thread.CurrentThread.CurrentUICulture = newCulture; - string currencyStr = expression.ToString(newCulture.NumberFormat.CurrencySymbol); - var oldCulture = new CultureInfo(oldCurrentCulture); - Thread.CurrentThread.CurrentUICulture = oldCulture; - return currencyStr; - } - - public string GetFixedDate(DateTime expression, string culture) - { - string oldCurrentCulture = CurrentUICulture; - var newCulture = new CultureInfo(culture); - Thread.CurrentThread.CurrentUICulture = newCulture; - string dateStr = expression.ToString(newCulture.DateTimeFormat.FullDateTimePattern); - var oldCulture = new CultureInfo(oldCurrentCulture); - Thread.CurrentThread.CurrentUICulture = oldCulture; - return dateStr; - } + return string.Format(string.IsNullOrEmpty(content) ? defaultValue : GetString(key, ExceptionsResourceFile), @params); + } public static string GetLanguageDisplayMode(int portalId) { @@ -792,6 +762,7 @@ public static string GetLanguageDisplayMode(int portalId) { viewType = "NATIVE"; } + return viewType; } @@ -829,126 +800,273 @@ public static string GetLocaleName(string code, CultureDropDownTypes displayType } return name; + } + + public string GetFixedCurrency(decimal expression, string culture, int numDigitsAfterDecimal) + { + string oldCurrentCulture = this.CurrentUICulture; + var newCulture = new CultureInfo(culture); + Thread.CurrentThread.CurrentUICulture = newCulture; + string currencyStr = expression.ToString(newCulture.NumberFormat.CurrencySymbol); + var oldCulture = new CultureInfo(oldCurrentCulture); + Thread.CurrentThread.CurrentUICulture = oldCulture; + return currencyStr; } - #region Language detection + public string GetFixedDate(DateTime expression, string culture) + { + string oldCurrentCulture = this.CurrentUICulture; + var newCulture = new CultureInfo(culture); + Thread.CurrentThread.CurrentUICulture = newCulture; + string dateStr = expression.ToString(newCulture.DateTimeFormat.FullDateTimePattern); + var oldCulture = new CultureInfo(oldCurrentCulture); + Thread.CurrentThread.CurrentUICulture = oldCulture; + return dateStr; + } + /// /// Detects the current language for the request. /// The order in which the language is being detect is: - /// 1. QueryString - /// 2. Cookie - /// 3. User profile (if request is authenticated) - /// 4. Browser preference (if portal has this option enabled) - /// 5. Portal default - /// 6. System default (en-US) - /// At any point, if a valid language is detected nothing else should be done + /// 1. QueryString + /// 2. Cookie + /// 3. User profile (if request is authenticated) + /// 4. Browser preference (if portal has this option enabled) + /// 5. Portal default + /// 6. System default (en-US) + /// At any point, if a valid language is detected nothing else should be done. /// - /// Current PortalSettings - /// A valid CultureInfo + /// Current PortalSettings. + /// A valid CultureInfo. public static CultureInfo GetPageLocale(PortalSettings portalSettings) { CultureInfo pageCulture = null; // 1. querystring - if (portalSettings != null) - pageCulture = GetCultureFromQs(portalSettings); - - // 2. cookie - if (portalSettings != null && pageCulture == null) - pageCulture = GetCultureFromCookie(portalSettings); - - // 3. user preference - if (portalSettings != null && pageCulture == null) - pageCulture = GetCultureFromProfile(portalSettings); + if (portalSettings != null) + { + pageCulture = GetCultureFromQs(portalSettings); + } + + // 2. cookie + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromCookie(portalSettings); + } + + // 3. user preference + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromProfile(portalSettings); + } + + // 4. browser + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromBrowser(portalSettings); + } + + // 5. portal default + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromPortal(portalSettings); + } + + // 6. system default + if (pageCulture == null) + { + pageCulture = new CultureInfo(SystemLocale); + } + + // finally set the cookie + SetLanguage(pageCulture.Name); + return pageCulture; + } - // 4. browser - if (portalSettings != null && pageCulture == null) - pageCulture = GetCultureFromBrowser(portalSettings); + /// + /// Tries to get a valid language from the browser preferences. + /// + /// Id of the current portal. + /// A valid CultureInfo if any is found. + public static CultureInfo GetBrowserCulture(int portalId) + { + if (HttpContext.Current == null || HttpContext.Current.Request == null || HttpContext.Current.Request.UserLanguages == null) + { + return null; + } + + CultureInfo culture = null; + foreach (string userLang in HttpContext.Current.Request.UserLanguages) + { + // split userlanguage by ";"... all but the first language will contain a preferrence index eg. ;q=.5 + string language = userLang.Split(';')[0]; + culture = GetCultureFromString(portalId, language); + if (culture != null) + { + break; + } + } + + return culture; + } + + public static string GetResourceFileName(string resourceFileName, string language, string mode, int portalId) + { + if (!resourceFileName.EndsWith(".resx")) + { + resourceFileName += ".resx"; + } + + if (language != SystemLocale) + { + if (resourceFileName.ToLowerInvariant().EndsWith(".en-us.resx")) + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 11) + "." + language + ".resx"; + } + else + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + language + ".resx"; + } + } + + if (mode == "Host") + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Host.resx"; + } + else if (mode == "Portal") + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Portal-" + portalId + ".resx"; + } + + return resourceFileName; + } - // 5. portal default - if (portalSettings != null && pageCulture == null) - pageCulture = GetCultureFromPortal(portalSettings); + public static string GetResourceFile(Control control, string fileName) + { + return control.TemplateSourceDirectory + "/" + LocalResourceDirectory + "/" + fileName; + } - // 6. system default - if (pageCulture == null) - pageCulture = new CultureInfo(SystemLocale); + /// + /// Parses the language parameter into a valid and enabled language in the current portal. + /// If an exact match is not found (language-region), it will try to find a match for the language only. + /// Ex: requested locale is "en-GB", requested language is "en", enabled locale is "en-US", so "en" is a match for "en-US". + /// + /// Id of current portal. + /// Language to be parsed. + /// A valid and enabled CultureInfo that matches the language passed if any. + internal static CultureInfo GetCultureFromString(int portalId, string language) + { + CultureInfo culture = null; + if (!string.IsNullOrEmpty(language)) + { + if (LocaleController.Instance.IsEnabled(ref language, portalId)) + { + culture = new CultureInfo(language); + } + else + { + string preferredLanguage = language.Split('-')[0]; - // finally set the cookie - SetLanguage(pageCulture.Name); - return pageCulture; - } + Dictionary enabledLocales = new Dictionary(); + if (portalId > Null.NullInteger) + { + enabledLocales = LocaleController.Instance.GetLocales(portalId); + } + + foreach (string localeCode in enabledLocales.Keys) + { + if (localeCode.Split('-')[0] == preferredLanguage.Split('-')[0]) + { + culture = new CultureInfo(localeCode); + break; + } + } + } + } + + return culture; + } /// - /// Tries to get a valid language from the querystring + /// Tries to get a valid language from the querystring. /// - /// Current PortalSettings - /// A valid CultureInfo if any is found + /// Current PortalSettings. + /// A valid CultureInfo if any is found. private static CultureInfo GetCultureFromQs(PortalSettings portalSettings) { - if (HttpContext.Current == null || HttpContext.Current.Request["language"] == null) - return null; - + if (HttpContext.Current == null || HttpContext.Current.Request["language"] == null) + { + return null; + } + string language = HttpContext.Current.Request["language"]; CultureInfo culture = GetCultureFromString(portalSettings.PortalId, language); return culture; } /// - /// Tries to get a valid language from the cookie + /// Tries to get a valid language from the cookie. /// - /// Current PortalSettings - /// A valid CultureInfo if any is found + /// Current PortalSettings. + /// A valid CultureInfo if any is found. private static CultureInfo GetCultureFromCookie(PortalSettings portalSettings) { CultureInfo culture; - if (HttpContext.Current == null || HttpContext.Current.Request.Cookies["language"] == null) - return null; - + if (HttpContext.Current == null || HttpContext.Current.Request.Cookies["language"] == null) + { + return null; + } + string language = HttpContext.Current.Request.Cookies["language"].Value; culture = GetCultureFromString(portalSettings.PortalId, language); return culture; } /// - /// Tries to get a valid language from the user profile + /// Tries to get a valid language from the user profile. /// - /// Current PortalSettings - /// A valid CultureInfo if any is found + /// Current PortalSettings. + /// A valid CultureInfo if any is found. private static CultureInfo GetCultureFromProfile(PortalSettings portalSettings) { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - - if (HttpContext.Current == null || !HttpContext.Current.Request.IsAuthenticated || objUserInfo.UserID == -1) - return null; + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + if (HttpContext.Current == null || !HttpContext.Current.Request.IsAuthenticated || objUserInfo.UserID == -1) + { + return null; + } + string language = objUserInfo.Profile.PreferredLocale; CultureInfo culture = GetCultureFromString(portalSettings.PortalId, language); return culture; } /// - /// Tries to get a valid language from the browser preferences if the portal has the setting + /// Tries to get a valid language from the browser preferences if the portal has the setting /// to use browser languages enabled. /// - /// Current PortalSettings - /// A valid CultureInfo if any is found + /// Current PortalSettings. + /// A valid CultureInfo if any is found. private static CultureInfo GetCultureFromBrowser(PortalSettings portalSettings) { - if (!portalSettings.EnableBrowserLanguage) - return null; - else - return GetBrowserCulture(portalSettings.PortalId); + if (!portalSettings.EnableBrowserLanguage) + { + return null; + } + else + { + return GetBrowserCulture(portalSettings.PortalId); + } } /// - /// Tries to get a valid language from the portal default preferences + /// Tries to get a valid language from the portal default preferences. /// - /// Current PortalSettings - /// A valid CultureInfo if any is found + /// Current PortalSettings. + /// A valid CultureInfo if any is found. private static CultureInfo GetCultureFromPortal(PortalSettings portalSettings) { CultureInfo culture = null; - if (!String.IsNullOrEmpty(portalSettings.DefaultLanguage)) + if (!string.IsNullOrEmpty(portalSettings.DefaultLanguage)) { // As the portal default language can never be disabled, we know this language is available and enabled culture = new CultureInfo(portalSettings.DefaultLanguage); @@ -957,9 +1075,11 @@ private static CultureInfo GetCultureFromPortal(PortalSettings portalSettings) { // Get the first enabled locale on the portal Dictionary enabledLocales = new Dictionary(); - if (portalSettings.PortalId > Null.NullInteger) - enabledLocales = LocaleController.Instance.GetLocales(portalSettings.PortalId); - + if (portalSettings.PortalId > Null.NullInteger) + { + enabledLocales = LocaleController.Instance.GetLocales(portalSettings.PortalId); + } + if (enabledLocales.Count > 0) { foreach (string localeCode in enabledLocales.Keys) @@ -969,106 +1089,13 @@ private static CultureInfo GetCultureFromPortal(PortalSettings portalSettings) } } } + return culture; } - - /// - /// Tries to get a valid language from the browser preferences - /// - /// Id of the current portal - /// A valid CultureInfo if any is found - public static CultureInfo GetBrowserCulture(int portalId) - { - if (HttpContext.Current == null || HttpContext.Current.Request == null || HttpContext.Current.Request.UserLanguages == null) - return null; - - CultureInfo culture = null; - foreach (string userLang in HttpContext.Current.Request.UserLanguages) - { - //split userlanguage by ";"... all but the first language will contain a preferrence index eg. ;q=.5 - string language = userLang.Split(';')[0]; - culture = GetCultureFromString(portalId, language); - if (culture != null) - break; - } - return culture; - } - - /// - /// Parses the language parameter into a valid and enabled language in the current portal. - /// If an exact match is not found (language-region), it will try to find a match for the language only. - /// Ex: requested locale is "en-GB", requested language is "en", enabled locale is "en-US", so "en" is a match for "en-US". - /// - /// Id of current portal - /// Language to be parsed - /// A valid and enabled CultureInfo that matches the language passed if any. - internal static CultureInfo GetCultureFromString(int portalId, string language) - { - CultureInfo culture = null; - if (!String.IsNullOrEmpty(language)) - { - if (LocaleController.Instance.IsEnabled(ref language, portalId)) - culture = new CultureInfo(language); - else - { - string preferredLanguage = language.Split('-')[0]; - - Dictionary enabledLocales = new Dictionary(); - if (portalId > Null.NullInteger) - enabledLocales = LocaleController.Instance.GetLocales(portalId); - - foreach (string localeCode in enabledLocales.Keys) - { - if (localeCode.Split('-')[0] == preferredLanguage.Split('-')[0]) - { - culture = new CultureInfo(localeCode); - break; - } - } - } - } - return culture; - } - #endregion - - public static string GetResourceFileName(string resourceFileName, string language, string mode, int portalId) - { - if (!resourceFileName.EndsWith(".resx")) - { - resourceFileName += ".resx"; - } - if (language != SystemLocale) - { - if (resourceFileName.ToLowerInvariant().EndsWith(".en-us.resx")) - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 11) + "." + language + ".resx"; - } - else - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + language + ".resx"; - } - } - if (mode == "Host") - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Host.resx"; - } - else if (mode == "Portal") - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Portal-" + portalId + ".resx"; - } - return resourceFileName; - } - - public static string GetResourceFile(Control control, string fileName) - { - return control.TemplateSourceDirectory + "/" + LocalResourceDirectory + "/" + fileName; - } - - #region GetString - + public static string GetString(string key, Control ctrl) { - //We need to find the parent module + // We need to find the parent module Control parentControl = ctrl.Parent; string localizedText; var moduleControl = parentControl as IModuleControl; @@ -1077,31 +1104,32 @@ public static string GetString(string key, Control ctrl) PropertyInfo pi = parentControl.GetType().GetProperty("LocalResourceFile"); if (pi != null) { - //If control has a LocalResourceFile property use this + // If control has a LocalResourceFile property use this localizedText = GetString(key, pi.GetValue(parentControl, null).ToString()); } else { - //Drill up to the next level + // Drill up to the next level localizedText = GetString(key, parentControl); } } else { - //We are at the Module Level so return key - //Get Resource File Root from Parents LocalResourceFile Property + // We are at the Module Level so return key + // Get Resource File Root from Parents LocalResourceFile Property localizedText = GetString(key, moduleControl.LocalResourceFile); } + return localizedText; } /// ----------------------------------------------------------------------------- - /// One of six overloads + /// One of six overloads. /// - /// GetString gets the localized string corresponding to the resource key + /// GetString gets the localized string corresponding to the resource key. /// - /// The resource key to find - /// The localized Text + /// The resource key to find. + /// The localized Text. /// ----------------------------------------------------------------------------- public static string GetString(string key) { @@ -1109,13 +1137,13 @@ public static string GetString(string key) } /// ----------------------------------------------------------------------------- - /// One of six overloads + /// One of six overloads. /// - /// GetString gets the localized string corresponding to the resourcekey + /// GetString gets the localized string corresponding to the resourcekey. /// - /// The resourcekey to find - /// The current portals Portal Settings - /// The localized Text + /// The resourcekey to find. + /// The current portals Portal Settings. + /// The localized Text. /// ----------------------------------------------------------------------------- public static string GetString(string key, PortalSettings portalSettings) { @@ -1123,14 +1151,14 @@ public static string GetString(string key, PortalSettings portalSettings) } /// ----------------------------------------------------------------------------- - /// One of six overloads + /// One of six overloads. /// - /// GetString gets the localized string corresponding to the resourcekey + /// GetString gets the localized string corresponding to the resourcekey. /// - /// The resourcekey to find - /// The Local Resource root + /// The resourcekey to find. + /// The Local Resource root. /// Disable to show missing key. - /// The localized Text + /// The localized Text. /// ----------------------------------------------------------------------------- public static string GetString(string key, string resourceFileRoot, bool disableShowMissingKeys) { @@ -1138,13 +1166,13 @@ public static string GetString(string key, string resourceFileRoot, bool disable } /// ----------------------------------------------------------------------------- - /// One of six overloads + /// One of six overloads. /// - /// GetString gets the localized string corresponding to the resourcekey + /// GetString gets the localized string corresponding to the resourcekey. /// - /// The resourcekey to find + /// The resourcekey to find. /// The Resource File Name. - /// The localized Text + /// The localized Text. /// ----------------------------------------------------------------------------- public static string GetString(string key, string resourceFileRoot) { @@ -1152,14 +1180,14 @@ public static string GetString(string key, string resourceFileRoot) } /// ----------------------------------------------------------------------------- - /// One of six overloads + /// One of six overloads. /// - /// GetString gets the localized string corresponding to the resourcekey + /// GetString gets the localized string corresponding to the resourcekey. /// - /// The resourcekey to find - /// The Local Resource root - /// A specific language to lookup the string - /// The localized Text + /// The resourcekey to find. + /// The Local Resource root. + /// A specific language to lookup the string. + /// The localized Text. /// ----------------------------------------------------------------------------- public static string GetString(string key, string resourceFileRoot, string language) { @@ -1167,15 +1195,15 @@ public static string GetString(string key, string resourceFileRoot, string langu } /// ----------------------------------------------------------------------------- - /// One of six overloads + /// One of six overloads. /// - /// GetString gets the localized string corresponding to the resourcekey + /// GetString gets the localized string corresponding to the resourcekey. /// - /// The resourcekey to find - /// The Local Resource root - /// The current portals Portal Settings - /// A specific language to lookup the string - /// The localized Text + /// The resourcekey to find. + /// The Local Resource root. + /// The current portals Portal Settings. + /// A specific language to lookup the string. + /// The localized Text. /// ----------------------------------------------------------------------------- public static string GetString(string key, string resourceFileRoot, PortalSettings portalSettings, string language) { @@ -1183,54 +1211,46 @@ public static string GetString(string key, string resourceFileRoot, PortalSettin } /// ----------------------------------------------------------------------------- - /// One of six overloads + /// One of six overloads. /// - /// GetString gets the localized string corresponding to the resourcekey + /// GetString gets the localized string corresponding to the resourcekey. /// - /// The resourcekey to find - /// The Local Resource root - /// The current portals Portal Settings - /// A specific language to lookup the string - /// Disables the show missing keys flag - /// The localized Text + /// The resourcekey to find. + /// The Local Resource root. + /// The current portals Portal Settings. + /// A specific language to lookup the string. + /// Disables the show missing keys flag. + /// The localized Text. /// ----------------------------------------------------------------------------- public static string GetString(string key, string resourceFileRoot, PortalSettings portalSettings, string language, bool disableShowMissingKeys) { return LocalizationProvider.Instance.GetString(key, resourceFileRoot, language, portalSettings, disableShowMissingKeys); - } - - #endregion - - #region GetStringUrl - + } + /// ----------------------------------------------------------------------------- /// - /// GetStringUrl gets the localized string corresponding to the resourcekey + /// GetStringUrl gets the localized string corresponding to the resourcekey. /// - /// The resourcekey to find - /// The Local Resource root - /// The localized Text + /// The resourcekey to find. + /// The Local Resource root. + /// The localized Text. /// /// This function should be used to retrieve strings to be used on URLs. /// It is the same as GetString(name,ResourceFileRoot) method /// but it disables the ShowMissingKey flag, so even it testing scenarios, the correct string - /// is returned + /// is returned. /// /// ----------------------------------------------------------------------------- public static string GetStringUrl(string key, string resourceFileRoot) { return GetString(key, resourceFileRoot, PortalController.Instance.GetCurrentPortalSettings(), null, true); - } - - #endregion - - #region GetSafeJSString - + } + /// - /// this function will escape reserved character fields to their "safe" javascript equivalents + /// this function will escape reserved character fields to their "safe" javascript equivalents. /// - /// The string to be parsed for unsafe characters - /// the string that is safe to use in a javascript function + /// The string to be parsed for unsafe characters. + /// the string that is safe to use in a javascript function. public static string GetSafeJSString(string unsafeString) { if (string.IsNullOrEmpty(unsafeString)) @@ -1242,21 +1262,17 @@ public static string GetSafeJSString(string unsafeString) } /// - /// this function will escape reserved character fields to their "safe" javascript equivalents + /// this function will escape reserved character fields to their "safe" javascript equivalents. /// - /// localization key - /// file for localization key - /// the string that is safe to use in a javascript function + /// localization key. + /// file for localization key. + /// the string that is safe to use in a javascript function. public static string GetSafeJSString(string key, string resourceFileRoot) { var unsafeString = GetString(key, resourceFileRoot); return GetSafeJSString(unsafeString); - } - - #endregion - - #region Get System Message - + } + /// ----------------------------------------------------------------------------- /// /// Gets a SystemMessage. @@ -1272,7 +1288,7 @@ public static string GetSafeJSString(string key, string resourceFileRoot) /// - All properties defined in in the form of: [User:property] /// - All values stored in the user profile in the form of: [Profile:key] /// - [User:VerificationCode]: User verification code for verified registrations - /// - [Date:Current]: Current date + /// - [Date:Current]: Current date. /// /// ----------------------------------------------------------------------------- public static string GetSystemMessage(PortalSettings portalSettings, string messageName) @@ -1296,7 +1312,7 @@ public static string GetSystemMessage(PortalSettings portalSettings, string mess /// - All properties defined in in the form of: [User:property] /// - All values stored in the user profile in the form of: [Profile:key] /// - [User:VerificationCode]: User verification code for verified registrations - /// - [Date:Current]: Current date + /// - [Date:Current]: Current date. /// /// ----------------------------------------------------------------------------- public static string GetSystemMessage(PortalSettings portalSettings, string messageName, UserInfo userInfo) @@ -1321,7 +1337,7 @@ public static string GetSystemMessage(PortalSettings portalSettings, string mess /// - All properties defined in in the form of: [User:property] /// - All values stored in the user profile in the form of: [Profile:key] /// - [User:VerificationCode]: User verification code for verified registrations - /// - [Date:Current]: Current date + /// - [Date:Current]: Current date. /// /// ----------------------------------------------------------------------------- public static string GetSystemMessage(string strLanguage, PortalSettings portalSettings, string messageName, UserInfo userInfo) @@ -1336,7 +1352,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS /// The portal settings for the portal to which the message will affect. /// The message tag which identifies the SystemMessage. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// The message body with all tags replaced. /// /// Supported tags: @@ -1346,7 +1362,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS /// - All properties defined in in the form of: [User:property] /// - All values stored in the user profile in the form of: [Profile:key] /// - [User:VerificationCode]: User verification code for verified registrations - /// - [Date:Current]: Current date + /// - [Date:Current]: Current date. /// /// ----------------------------------------------------------------------------- public static string GetSystemMessage(PortalSettings portalSettings, string messageName, string resourceFile) @@ -1362,7 +1378,7 @@ public static string GetSystemMessage(PortalSettings portalSettings, string mess /// The message tag which identifies the SystemMessage. /// Reference to the user used to personalize the message. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// The message body with all tags replaced. /// /// Supported tags: @@ -1372,7 +1388,7 @@ public static string GetSystemMessage(PortalSettings portalSettings, string mess /// - All properties defined in in the form of: [User:property] /// - All values stored in the user profile in the form of: [Profile:key] /// - [User:VerificationCode]: User verification code for verified registrations - /// - [Date:Current]: Current date + /// - [Date:Current]: Current date. /// /// ----------------------------------------------------------------------------- public static string GetSystemMessage(PortalSettings portalSettings, string messageName, UserInfo userInfo, string resourceFile) @@ -1387,11 +1403,11 @@ public static string GetSystemMessage(PortalSettings portalSettings, string mess /// The portal settings for the portal to which the message will affect. /// The message tag which identifies the SystemMessage. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// An ArrayList with replacements for custom tags. /// The message body with all tags replaced. /// - /// Custom tags are of the form [Custom:n], where n is the zero based index which + /// Custom tags are of the form [Custom:n], where n is the zero based index which /// will be used to find the replacement value in Custom parameter. /// /// ----------------------------------------------------------------------------- @@ -1408,11 +1424,11 @@ public static string GetSystemMessage(PortalSettings portalSettings, string mess /// The message tag which identifies the SystemMessage. /// Reference to the user used to personalize the message. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// An ArrayList with replacements for custom tags. /// The message body with all tags replaced. /// - /// Custom tags are of the form [Custom:n], where n is the zero based index which + /// Custom tags are of the form [Custom:n], where n is the zero based index which /// will be used to find the replacement value in Custom parameter. /// /// ----------------------------------------------------------------------------- @@ -1430,17 +1446,17 @@ public static string GetSystemMessage(PortalSettings portalSettings, string mess /// The message tag which identifies the SystemMessage. /// Reference to the user used to personalize the message. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// An ArrayList with replacements for custom tags. /// The message body with all tags replaced. /// - /// Custom tags are of the form [Custom:n], where n is the zero based index which + /// Custom tags are of the form [Custom:n], where n is the zero based index which /// will be used to find the replacement value in Custom parameter. /// /// ----------------------------------------------------------------------------- public static string GetSystemMessage(string strLanguage, PortalSettings portalSettings, string messageName, UserInfo userInfo, string resourceFile, ArrayList custom) { - return GetSystemMessage(strLanguage, portalSettings, messageName, userInfo, resourceFile, custom, null, "", -1); + return GetSystemMessage(strLanguage, portalSettings, messageName, userInfo, resourceFile, custom, null, string.Empty, -1); } /// ----------------------------------------------------------------------------- @@ -1452,13 +1468,13 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS /// The message tag which identifies the SystemMessage. /// Reference to the user used to personalize the message. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// An ArrayList with replacements for custom tags. - /// prefix for custom tags - /// UserID of the user accessing the system message + /// prefix for custom tags. + /// UserID of the user accessing the system message. /// The message body with all tags replaced. /// - /// Custom tags are of the form [Custom:n], where n is the zero based index which + /// Custom tags are of the form [Custom:n], where n is the zero based index which /// will be used to find the replacement value in Custom parameter. /// /// ----------------------------------------------------------------------------- @@ -1477,14 +1493,14 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS /// The message tag which identifies the SystemMessage. /// Reference to the user used to personalize the message. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// An ArrayList with replacements for custom tags. /// An IDictionary with replacements for custom tags. - /// prefix for custom tags - /// UserID of the user accessing the system message + /// prefix for custom tags. + /// UserID of the user accessing the system message. /// The message body with all tags replaced. /// - /// Custom tags are of the form [Custom:n], where n is the zero based index which + /// Custom tags are of the form [Custom:n], where n is the zero based index which /// will be used to find the replacement value in Custom parameter. /// /// ----------------------------------------------------------------------------- @@ -1494,12 +1510,13 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS try { string strMessageValue = GetString(messageName, resourceFile, portalSettings, strLanguage); - if (!String.IsNullOrEmpty(strMessageValue)) + if (!string.IsNullOrEmpty(strMessageValue)) { - if (String.IsNullOrEmpty(customCaption)) + if (string.IsNullOrEmpty(customCaption)) { customCaption = "Custom"; } + var objTokenReplace = new TokenReplace(Scope.SystemMessages, strLanguage, portalSettings, userInfo); if ((accessingUserID != -1) && (userInfo != null)) { @@ -1509,6 +1526,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS UserController.Instance.GetUser(portalSettings.PortalId, accessingUserID); } } + if (customArray != null) { strMessageValue = @@ -1520,6 +1538,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS objTokenReplace.ReplaceEnvironmentTokens(strMessageValue, customDictionary, customCaption); } } + return strMessageValue; } catch (NullReferenceException ex) @@ -1527,63 +1546,59 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS Logger.Error(ex); return messageName; } - } - - #endregion - - #region LoadCultureDropDownList - + } + /// /// LoadCultureDropDownList loads a DropDownList with the list of supported cultures - /// based on the languages defined in the supported locales file, for the current portal + /// based on the languages defined in the supported locales file, for the current portal. /// - /// DropDownList to load + /// DropDownList to load. /// Format of the culture to display. Must be one the CultureDropDownTypes values. - /// for list of allowable values - /// Name of the default culture to select + /// for list of allowable values. + /// Name of the default culture to select. public static void LoadCultureDropDownList(DropDownList list, CultureDropDownTypes displayType, string selectedValue) { - LoadCultureDropDownList(list, displayType, selectedValue, "", false); + LoadCultureDropDownList(list, displayType, selectedValue, string.Empty, false); } /// /// LoadCultureDropDownList loads a DropDownList with the list of supported cultures /// based on the languages defined in the supported locales file. - /// This overload allows us to display all installed languages. To do so, pass the value True to the Host parameter + /// This overload allows us to display all installed languages. To do so, pass the value True to the Host parameter. /// - /// DropDownList to load + /// DropDownList to load. /// Format of the culture to display. Must be one the CultureDropDownTypes values. - /// for list of allowable values - /// Name of the default culture to select - /// Boolean that defines wether or not to load host (ie. all available) locales + /// for list of allowable values. + /// Name of the default culture to select. + /// Boolean that defines wether or not to load host (ie. all available) locales. public static void LoadCultureDropDownList(DropDownList list, CultureDropDownTypes displayType, string selectedValue, bool loadHost) { - LoadCultureDropDownList(list, displayType, selectedValue, "", loadHost); + LoadCultureDropDownList(list, displayType, selectedValue, string.Empty, loadHost); } /// /// LoadCultureDropDownList loads a DropDownList with the list of supported cultures - /// based on the languages defined in the supported locales file - /// This overload allows us to filter a language from the dropdown. To do so pass a language code to the Filter parameter - /// This overload allows us to display all installed languages. To do so, pass the value True to the Host parameter + /// based on the languages defined in the supported locales file. + /// This overload allows us to filter a language from the dropdown. To do so pass a language code to the Filter parameter. + /// This overload allows us to display all installed languages. To do so, pass the value True to the Host parameter. /// - /// DropDownList to load + /// DropDownList to load. /// Format of the culture to display. Must be one the CultureDropDownTypes values. - /// for list of allowable values - /// Name of the default culture to select - /// String value that allows for filtering out a specific language - /// Boolean that defines wether or not to load host (ie. all available) locales + /// for list of allowable values. + /// Name of the default culture to select. + /// String value that allows for filtering out a specific language. + /// Boolean that defines wether or not to load host (ie. all available) locales. public static void LoadCultureDropDownList(DropDownList list, CultureDropDownTypes displayType, string selectedValue, string filter, bool host) { IEnumerable cultureListItems = LoadCultureInListItems(displayType, selectedValue, filter, host); - //add the items to the list + // add the items to the list foreach (var cultureItem in cultureListItems) { list.Items.Add(cultureItem); } - //select the default item + // select the default item if (selectedValue != null) { ListItem item = list.Items.FindByValue(selectedValue); @@ -1597,9 +1612,9 @@ public static void LoadCultureDropDownList(DropDownList list, CultureDropDownTyp /// /// LoadCultureDropDownList loads a DropDownList with the list of supported cultures - /// based on the languages defined in the supported locales file - /// This overload allows us to filter a language from the dropdown. To do so pass a language code to the Filter parameter - /// This overload allows us to display all installed languages. To do so, pass the value True to the Host parameter + /// based on the languages defined in the supported locales file. + /// This overload allows us to filter a language from the dropdown. To do so pass a language code to the Filter parameter. + /// This overload allows us to display all installed languages. To do so, pass the value True to the Host parameter. /// /// /// @@ -1629,23 +1644,21 @@ public static IEnumerable LoadCultureInListItems(CultureDropDownTypes } return cultureListItems; - } - - #endregion - + } + /// ----------------------------------------------------------------------------- /// - /// Localizes ModuleControl Titles + /// Localizes ModuleControl Titles. /// - /// ModuleControl + /// ModuleControl. /// - /// Localized control title if found + /// Localized control title if found. /// /// /// Resource keys are: ControlTitle_[key].Text /// Key MUST be lowercase in the resource file /// Key can also be "blank" for admin/edit controls. These will only be used - /// in admin pages + /// in admin pages. /// /// ----------------------------------------------------------------------------- public static string LocalizeControlTitle(IModuleControl moduleControl) @@ -1669,13 +1682,13 @@ public static string LocalizeControlTitle(IModuleControl moduleControl) else { bool isAdminPage = false; - //we should be checking that the tab path matches //Admin//pagename or //admin - //in this way we should avoid partial matches (ie //Administrators + + // we should be checking that the tab path matches //Admin//pagename or //admin + // in this way we should avoid partial matches (ie //Administrators if (PortalSettings.Current.ActiveTab.TabPath.StartsWith("//Admin//", StringComparison.CurrentCultureIgnoreCase) || - String.Compare(PortalSettings.Current.ActiveTab.TabPath, "//Admin", StringComparison.OrdinalIgnoreCase) == 0 || + string.Compare(PortalSettings.Current.ActiveTab.TabPath, "//Admin", StringComparison.OrdinalIgnoreCase) == 0 || PortalSettings.Current.ActiveTab.TabPath.StartsWith("//Host//", StringComparison.CurrentCultureIgnoreCase) || - String.Compare(PortalSettings.Current.ActiveTab.TabPath, "//Host", StringComparison.OrdinalIgnoreCase) == 0 - ) + string.Compare(PortalSettings.Current.ActiveTab.TabPath, "//Host", StringComparison.OrdinalIgnoreCase) == 0) { isAdminPage = true; } @@ -1687,59 +1700,61 @@ public static string LocalizeControlTitle(IModuleControl moduleControl) controlTitle = localizedvalue; } } + return controlTitle; } /// ----------------------------------------------------------------------------- /// - /// LocalizeDataGrid creates localized Headers for a DataGrid + /// LocalizeDataGrid creates localized Headers for a DataGrid. /// - /// Grid to localize + /// Grid to localize. /// The root name of the Resource File where the localized - /// text can be found + /// text can be found. /// ----------------------------------------------------------------------------- public static void LocalizeDataGrid(ref DataGrid grid, string resourceFile) { string localizedText; foreach (DataGridColumn col in grid.Columns) { - //Localize Header Text + // Localize Header Text if (!string.IsNullOrEmpty(col.HeaderText)) { localizedText = GetString(col.HeaderText + ".Header", resourceFile); - if (!String.IsNullOrEmpty(localizedText)) + if (!string.IsNullOrEmpty(localizedText)) { col.HeaderText = localizedText; } } + if (col is EditCommandColumn) { var editCol = (EditCommandColumn)col; - //Edit Text - maintained for backward compatibility + // Edit Text - maintained for backward compatibility localizedText = GetString(editCol.EditText + ".EditText", resourceFile); - if (!String.IsNullOrEmpty(localizedText)) + if (!string.IsNullOrEmpty(localizedText)) { editCol.EditText = localizedText; } - //Edit Text + // Edit Text localizedText = GetString(editCol.EditText, resourceFile); - if (!String.IsNullOrEmpty(localizedText)) + if (!string.IsNullOrEmpty(localizedText)) { editCol.EditText = localizedText; } - //Cancel Text + // Cancel Text localizedText = GetString(editCol.CancelText, resourceFile); - if (!String.IsNullOrEmpty(localizedText)) + if (!string.IsNullOrEmpty(localizedText)) { editCol.CancelText = localizedText; } - //Update Text + // Update Text localizedText = GetString(editCol.UpdateText, resourceFile); - if (!String.IsNullOrEmpty(localizedText)) + if (!string.IsNullOrEmpty(localizedText)) { editCol.UpdateText = localizedText; } @@ -1748,9 +1763,9 @@ public static void LocalizeDataGrid(ref DataGrid grid, string resourceFile) { var buttonCol = (ButtonColumn)col; - //Edit Text + // Edit Text localizedText = GetString(buttonCol.Text, resourceFile); - if (!String.IsNullOrEmpty(localizedText)) + if (!string.IsNullOrEmpty(localizedText)) { buttonCol.Text = localizedText; } @@ -1759,11 +1774,11 @@ public static void LocalizeDataGrid(ref DataGrid grid, string resourceFile) } /// - /// Localizes headers and fields on a DetailsView control + /// Localizes headers and fields on a DetailsView control. /// /// /// The root name of the resource file where the localized - /// texts can be found + /// texts can be found. /// public static void LocalizeDetailsView(ref DetailsView detailsView, string resourceFile) { @@ -1774,11 +1789,11 @@ public static void LocalizeDetailsView(ref DetailsView detailsView, string resou } /// - /// Localizes headers and fields on a GridView control + /// Localizes headers and fields on a GridView control. /// - /// Grid to localize + /// Grid to localize. /// The root name of the resource file where the localized - /// texts can be found + /// texts can be found. /// public static void LocalizeGridView(ref GridView gridView, string resourceFile) { @@ -1790,13 +1805,14 @@ public static void LocalizeGridView(ref GridView gridView, string resourceFile) /// ----------------------------------------------------------------------------- /// - /// Localizes the "Built In" Roles + /// Localizes the "Built In" Roles. /// /// /// Localizes: /// -DesktopTabs - /// -BreadCrumbs - /// + /// -BreadCrumbs. + /// + /// /// ----------------------------------------------------------------------------- public static string LocalizeRole(string role) { @@ -1806,21 +1822,17 @@ public static string LocalizeRole(string role) case Globals.glbRoleAllUsersName: case Globals.glbRoleSuperUserName: case Globals.glbRoleUnauthUserName: - string roleKey = role.Replace(" ", ""); + string roleKey = role.Replace(" ", string.Empty); localRole = GetString(roleKey); break; default: localRole = role; break; } + return localRole; } - private static IList GetPortalLocalizations(int portalID) - { - return CBO.FillCollection(DataProvider.Instance().GetPortalLocalizations(portalID)); - } - public static void RemoveLanguageFromPortal(int portalID, int languageID) { RemoveLanguageFromPortal(portalID, languageID, false); @@ -1843,7 +1855,6 @@ public static void RemoveLanguageFromPortal(int portalID, int languageID, bool i if (Config.GetFriendlyUrlProvider() == "advanced") { // only do this with Advanced URL Management - var portalInfo = PortalController.Instance.GetPortal(portalID); if (portalInfo != null) { @@ -1862,8 +1873,8 @@ public static void RemoveLanguageFromPortal(int portalID, int languageID, bool i { PortalAliasController.Instance.DeletePortalAlias(portalAliasInfo); - //Fix PortalSettings for the rest of this request - var newDefaultAlias = portalAliases.SingleOrDefault(a => a.IsPrimary && a.CultureCode == String.Empty); + // Fix PortalSettings for the rest of this request + var newDefaultAlias = portalAliases.SingleOrDefault(a => a.IsPrimary && a.CultureCode == string.Empty); if (newDefaultAlias != null) { var settings = PortalController.Instance.GetCurrentPortalSettings(); @@ -1877,27 +1888,33 @@ public static void RemoveLanguageFromPortal(int portalID, int languageID, bool i } } - //Get Translator Role + // Get Translator Role string roleName = string.Format("Translator ({0})", language.Code); RoleInfo role = RoleController.Instance.GetRole(portalID, r => r.RoleName == roleName); if (role != null) { - //Remove Translator Role from Portal + // Remove Translator Role from Portal RoleController.Instance.DeleteRole(role); } DataProvider.Instance().DeletePortalLanguages(portalID, languageID); - EventLogController.Instance.AddLog("portalID/languageID", - portalID + "/" + languageID, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.LANGUAGETOPORTAL_DELETED); + EventLogController.Instance.AddLog( + "portalID/languageID", + portalID + "/" + languageID, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.LANGUAGETOPORTAL_DELETED); DataCache.ClearPortalCache(portalID, false); } } + private static IList GetPortalLocalizations(int portalID) + { + return CBO.FillCollection(DataProvider.Instance().GetPortalLocalizations(portalID)); + } + public static void RemoveLanguageFromPortals(int languageId) { RemoveLanguageFromPortals(languageId, false); @@ -1923,22 +1940,24 @@ public static void SaveLanguage(Locale locale) { SaveLanguage(locale, true); } - - + public static void SaveLanguage(Locale locale, bool clearCache) { if (locale.LanguageId == Null.NullInteger) { locale.LanguageId = DataProvider.Instance().AddLanguage(locale.Code, locale.Text, locale.Fallback, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(locale, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGE_CREATED); + EventLogController.Instance.AddLog(locale, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGE_CREATED); } else { DataProvider.Instance().UpdateLanguage(locale.LanguageId, locale.Code, locale.Text, locale.Fallback, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(locale, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGE_UPDATED); + EventLogController.Instance.AddLog(locale, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGE_UPDATED); } - if (clearCache) - DataCache.ClearHostCache(true); + + if (clearCache) + { + DataCache.ClearHostCache(true); + } } public static void SetLanguage(string value) @@ -1951,20 +1970,20 @@ public static void SetLanguage(string value) return; } - //save the page culture as a cookie + // save the page culture as a cookie HttpCookie cookie = response.Cookies.Get("language"); - if ((cookie == null)) + if (cookie == null) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { - cookie = new HttpCookie("language", value) { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }; + cookie = new HttpCookie("language", value) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }; response.Cookies.Add(cookie); } } else { cookie.Value = value; - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { response.Cookies.Set(cookie); } @@ -1981,10 +2000,10 @@ public static void SetLanguage(string value) } /// - /// Sets the culture codes on the current Thread + /// Sets the culture codes on the current Thread. /// - /// Culture Info for the current page - /// The current portalSettings + /// Culture Info for the current page. + /// The current portalSettings. /// /// This method will configure the Thread culture codes. Any page which does not derive from PageBase should /// be sure to call this method in OnInit to ensure localiztion works correctly. See the TelerikDialogHandler for an example. @@ -1996,9 +2015,11 @@ public static void SetThreadCultures(CultureInfo cultureInfo, PortalSettings por throw new ArgumentNullException("cultureInfo"); } - if (cultureInfo.Name == "fa-IR") - cultureInfo = Persian.PersianController.GetPersianCultureInfo(); - + if (cultureInfo.Name == "fa-IR") + { + cultureInfo = Persian.PersianController.GetPersianCultureInfo(); + } + Thread.CurrentThread.CurrentCulture = cultureInfo; if (portalSettings != null && portalSettings.ContentLocalizationEnabled && @@ -2013,13 +2034,26 @@ public static void SetThreadCultures(CultureInfo cultureInfo, PortalSettings por } } + /// + /// Maps the culture code string into the corresponding language ID in the + /// database. In case there is no language defined in the systen with the + /// passed code, -1 () is returned. + /// + /// The culture to get the language ID for. + /// Language ID integer. + public static int GetCultureLanguageID(string cultureCode) + { + var locale = LocaleController.Instance.GetLocale(cultureCode); + return locale != null ? locale.LanguageId : Null.NullInteger; + } + /// /// When portal allows users to select their preferred UI language, this method /// will return the user ui preferred language if defined. Otherwise defaults - /// to the current culture + /// to the current culture. /// - /// Current culture - /// PortalSettings for the current request + /// Current culture. + /// PortalSettings for the current request. /// private static CultureInfo GetUserUICulture(CultureInfo currentCulture, PortalSettings portalSettings) { @@ -2030,8 +2064,10 @@ private static CultureInfo GetUserUICulture(CultureInfo currentCulture, PortalSe if (oCulture != null) { CultureInfo ci = GetCultureFromString(portalSettings.PortalId, oCulture.ToString()); - if (ci != null) - uiCulture = ci; + if (ci != null) + { + uiCulture = ci; + } } } catch @@ -2039,21 +2075,8 @@ private static CultureInfo GetUserUICulture(CultureInfo currentCulture, PortalSe // UserCulture seems not valid anymore, update to current culture Personalization.Personalization.SetProfile("Usability", "UICulture", currentCulture.Name); } + return uiCulture; } - - /// - /// Maps the culture code string into the corresponding language ID in the - /// database. In case there is no language defined in the systen with the - /// passed code, -1 () is returned. - /// - /// The culture to get the language ID for. - /// Language ID integer - public static int GetCultureLanguageID(string cultureCode) - { - var locale = LocaleController.Instance.GetLocale(cultureCode); - return locale != null ? locale.LanguageId : Null.NullInteger; - } - #endregion } } diff --git a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs index 0b39dc391ab..cdd3e6b6809 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs @@ -1,23 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.CodeDom; -using System.ComponentModel; -using System.IO; -using System.Web; -using System.Web.Compilation; -using System.Web.UI; -using System.Web.UI.Design; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { - [ExpressionPrefix("dnnLoc"), ExpressionEditor("DotNetNuke.Services.Localization.LocalizationExpressionBuilderEditor")] + using System; + using System.CodeDom; + using System.ComponentModel; + using System.IO; + using System.Web; + using System.Web.Compilation; + using System.Web.UI; + using System.Web.UI.Design; + + [ExpressionPrefix("dnnLoc")] + [ExpressionEditor("DotNetNuke.Services.Localization.LocalizationExpressionBuilderEditor")] public class LocalizationExpressionBuilder : ExpressionBuilder { public override bool SupportsEvaluate @@ -28,19 +24,6 @@ public override bool SupportsEvaluate } } - public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) - { - var inputParams = new CodeExpression[] - { - new CodePrimitiveExpression(entry.Expression.Trim()), - new CodeTypeOfExpression(entry.DeclaringType), - new CodePrimitiveExpression(entry.PropertyInfo.Name), - new CodePrimitiveExpression(context.VirtualPath) - }; - - return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(GetType()), "GetLocalizedResource", inputParams); - } - public static object GetLocalizedResource(string key, Type targetType, string propertyName, string virtualPath) { if (HttpContext.Current == null) @@ -48,7 +31,7 @@ public static object GetLocalizedResource(string key, Type targetType, string pr return null; } - string localResourceFile = ""; + string localResourceFile = string.Empty; if (!string.IsNullOrEmpty(virtualPath)) { string filename = Path.GetFileName(virtualPath); @@ -57,6 +40,7 @@ public static object GetLocalizedResource(string key, Type targetType, string pr localResourceFile = virtualPath.Replace(filename, Localization.LocalResourceDirectory + "/" + filename); } } + string value = Localization.GetString(key, localResourceFile); if (value == null) @@ -70,22 +54,36 @@ public static object GetLocalizedResource(string key, Type targetType, string pr PropertyDescriptor propDesc = TypeDescriptor.GetProperties(targetType)[propertyName]; if (propDesc != null && propDesc.PropertyType != value.GetType()) { - // Type mismatch - make sure that the value can be converted to the Web control property type + // Type mismatch - make sure that the value can be converted to the Web control property type if (propDesc.Converter != null) { if (propDesc.Converter.CanConvertFrom(value.GetType()) == false) { throw new InvalidOperationException(string.Format("Localized value '{0}' cannot be converted to type {1}.", key, propDesc.PropertyType)); } + return propDesc.Converter.ConvertFrom(value); } } } - // If we reach here, no type mismatch - return the value + // If we reach here, no type mismatch - return the value return value; } + public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) + { + var inputParams = new CodeExpression[] + { + new CodePrimitiveExpression(entry.Expression.Trim()), + new CodeTypeOfExpression(entry.DeclaringType), + new CodePrimitiveExpression(entry.PropertyInfo.Name), + new CodePrimitiveExpression(context.VirtualPath), + }; + + return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()), "GetLocalizedResource", inputParams); + } + public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { string key = entry.Expression.Trim(); diff --git a/DNN Platform/Library/Services/Localization/LocalizationExtensions.cs b/DNN Platform/Library/Services/Localization/LocalizationExtensions.cs index 92fa84a6cd4..1a88a705fa9 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationExtensions.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationExtensions.cs @@ -1,13 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System.Text.RegularExpressions; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System.Text.RegularExpressions; + public static class LocalizationExtensions { public const string ResxFileLocaleRegex = "(?i)(.*)\\.((\\w\\w-)?\\w{2,3}-\\w{2,3})(\\.resx)$(?-i)"; @@ -18,7 +15,7 @@ public static class LocalizationExtensions /// E.g. My file with.fancy-characters.fr-FR.resx should return "fr-FR". /// /// Name of the file. - /// Microsoft compatible locale code + /// Microsoft compatible locale code. public static string GetLocaleCodeFromFileName(this string fileName) { var m = FileNameMatchRegex.Match(fileName); @@ -30,12 +27,11 @@ public static string GetLocaleCodeFromFileName(this string fileName) /// E.g. My file with.fancy-characters.fr-FR.resx should return "My file with.fancy-characters". /// /// Name of the file. - /// File name stripped of culture code or extension + /// File name stripped of culture code or extension. public static string GetFileNameFromLocalizedResxFile(this string fileName) { var m = FileNameMatchRegex.Match(fileName); return m.Success ? m.Groups[1].Value : string.Empty; } - } } diff --git a/DNN Platform/Library/Services/Localization/LocalizationProvider.cs b/DNN Platform/Library/Services/Localization/LocalizationProvider.cs index fde8b615090..7cfeea6958e 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationProvider.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationProvider.cs @@ -1,599 +1,612 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Web.Hosting; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; - -namespace DotNetNuke.Services.Localization -{ - public class LocalizationProvider : ComponentBase, ILocalizationProvider - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LocalizationProvider)); - #region Nested type: CustomizedLocale - - public enum CustomizedLocale - { - None = 0, - Portal = 1, - Host = 2 - } - - #endregion - - #region Implementation of ILocalizationProvider - - public string GetString(string key, string resourceFileRoot) - { - return GetString(key, resourceFileRoot, null, PortalController.Instance.GetCurrentPortalSettings(), false); - } - - public string GetString(string key, string resourceFileRoot, string language) - { - return GetString(key, resourceFileRoot, language, PortalController.Instance.GetCurrentPortalSettings(), false); - } - - public string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings) - { - return GetString(key, resourceFileRoot, language, portalSettings, false); - } - - public string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings, bool disableShowMissingKeys) - { - //make the default translation property ".Text" - if (key.IndexOf(".", StringComparison.Ordinal) < 1) - { - key += ".Text"; - } - string resourceValue = Null.NullString; - bool keyFound = TryGetStringInternal(key, language, resourceFileRoot, portalSettings, ref resourceValue); - - //If the key can't be found then it doesn't exist in the Localization Resources - if (Localization.ShowMissingKeys && !disableShowMissingKeys) - { - if (keyFound) - { - resourceValue = "[L]" + resourceValue; - } - else - { - resourceValue = "RESX:" + key; - } - } - - if (!keyFound) - { - Logger.WarnFormat("Missing localization key. key:{0} resFileRoot:{1} threadCulture:{2} userlan:{3}", key, resourceFileRoot, Thread.CurrentThread.CurrentUICulture, language); - } - - return string.IsNullOrEmpty(resourceValue) ? string.Empty : RemoveHttpUrlsIfSiteisSSLEnabled(portalSettings, resourceValue); - } - - private string RemoveHttpUrlsIfSiteisSSLEnabled(PortalSettings portalSettings, string resourceValue) - { - - if (portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced)) - { - resourceValue = resourceValue.Replace(@"http:", @"https:"); - } - - return resourceValue; - } - - /// - /// Saves a string to a resource file. - /// - /// The key to save (e.g. "MyWidget.Text"). - /// The text value for the key. - /// Relative path for the resource file root (e.g. "DesktopModules/Admin/Lists/App_LocalResources/ListEditor.ascx.resx"). - /// The locale code in lang-region format (e.g. "fr-FR"). - /// The current portal settings. - /// Specifies whether to save as portal, host or system resource file. - /// if set to true a new file will be created if it is not found. - /// if set to true a new key will be created if not found. - /// If the value could be saved then true will be returned, otherwise false. - /// Any file io error or similar will lead to exceptions - public bool SaveString(string key, string value, string resourceFileRoot, string language, PortalSettings portalSettings, CustomizedLocale resourceType, bool createFile, bool createKey) - { - try - { - if (key.IndexOf(".", StringComparison.Ordinal) < 1) - { - key += ".Text"; - } - string resourceFileName = GetResourceFileName(resourceFileRoot, language); - resourceFileName = resourceFileName.Replace("." + language.ToLowerInvariant() + ".", "." + language + "."); - switch (resourceType) - { - case CustomizedLocale.Host: - resourceFileName = resourceFileName.Replace(".resx", ".Host.resx"); - break; - case CustomizedLocale.Portal: - resourceFileName = resourceFileName.Replace(".resx", ".Portal-" + portalSettings.PortalId + ".resx"); - break; - } - resourceFileName = resourceFileName.TrimStart('~', '/', '\\'); - string filePath = HostingEnvironment.MapPath("~/" + resourceFileName); - XmlDocument doc = null; - if (File.Exists(filePath)) - { - doc = new XmlDocument { XmlResolver = null }; - doc.Load(filePath); - } - else - { - if (createFile) - { - doc = new XmlDocument { XmlResolver = null }; - doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes")); - XmlNode root = doc.CreateElement("root"); - doc.AppendChild(root); - AddResourceFileNode(ref root, "resheader", "resmimetype", "text/microsoft-resx"); - AddResourceFileNode(ref root, "resheader", "version", "2.0"); - AddResourceFileNode(ref root, "resheader", "reader", "System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); - AddResourceFileNode(ref root, "resheader", "writer", "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); - } - } - if (doc == null) { return false; } - XmlNode reskeyNode = doc.SelectSingleNode("root/data[@name=\"" + key + "\"]"); - if (reskeyNode != null) - { - reskeyNode.SelectSingleNode("value").InnerText = value; - } - else - { - if (createKey) - { - XmlNode root = doc.SelectSingleNode("root"); - AddResourceFileNode(ref root, "data", key, value); - } - else - { - return false; - } - } - doc.Save(filePath); - DataCache.RemoveCache("/" + resourceFileName.ToLowerInvariant()); - return true; - } - catch (Exception ex) - { - throw new Exception(string.Format("Error while trying to create resource in {0}", resourceFileRoot), ex); - } - } - - public Dictionary GetCompiledResourceFile(PortalSettings portalSettings, string resourceFile, string locale) - { - return - CBO.GetCachedObject>(new CacheItemArgs("Compiled-" + resourceFile + "-" + locale + "-" + portalSettings.PortalId, - DataCache.ResourceFilesCacheTimeOut, DataCache.ResourceFilesCachePriority, resourceFile, locale, - portalSettings), GetCompiledResourceFileCallBack, true); - } - - #endregion - - private static object GetCompiledResourceFileCallBack(CacheItemArgs cacheItemArgs) - { - string resourceFile = (string)cacheItemArgs.Params[0]; - string locale = (string)cacheItemArgs.Params[1]; - PortalSettings portalSettings = (PortalSettings)cacheItemArgs.Params[2]; - string systemLanguage = Localization.SystemLocale; - string defaultLanguage = portalSettings.DefaultLanguage; - string fallbackLanguage = Localization.SystemLocale; - Locale targetLocale = LocaleController.Instance.GetLocale(locale); - if (!String.IsNullOrEmpty(targetLocale.Fallback)) - { - fallbackLanguage = targetLocale.Fallback; - } - - // get system default and merge the specific ones one by one - var res = GetResourceFile(resourceFile); - if (res == null) - { - return new Dictionary(); - } - - //clone the dictionart so that when merge values into dictionart, it won't - //affect the cache data. - res = res.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - res = MergeResourceFile(res, GetResourceFileName(resourceFile, systemLanguage, portalSettings.PortalId)); - if (defaultLanguage != systemLanguage) - { - res = MergeResourceFile(res, GetResourceFileName(resourceFile, defaultLanguage)); - res = MergeResourceFile(res, GetResourceFileName(resourceFile, defaultLanguage, portalSettings.PortalId)); - } - if (fallbackLanguage != defaultLanguage) - { - res = MergeResourceFile(res, GetResourceFileName(resourceFile, fallbackLanguage)); - res = MergeResourceFile(res, GetResourceFileName(resourceFile, fallbackLanguage, portalSettings.PortalId)); - } - if (locale != fallbackLanguage) - { - res = MergeResourceFile(res, GetResourceFileName(resourceFile, locale)); - res = MergeResourceFile(res, GetResourceFileName(resourceFile, locale, portalSettings.PortalId)); - } - return res; - } - - private static Dictionary MergeResourceFile(Dictionary current, string resourceFile) - { - var resFile = GetResourceFile(resourceFile); - if (resFile == null) - { - return current; - } - foreach (string key in current.Keys.ToList()) - { - if (resFile.ContainsKey(key)) - { - current[key] = resFile[key]; - } - } - return current; - } - - /// - /// Adds one of either a "resheader" or "data" element to resxRoot (which should be the root element of the resx file). - /// This function is used to construct new resource files and to add resource keys to an existing file. - /// - /// The RESX root. - /// Name of the element ("resheader" or "data"). - /// Name of the node (in case of "data" specify the localization key here, e.g. "MyWidget.Text"). - /// The node value (text value to use). - private static void AddResourceFileNode(ref XmlNode resxRoot, string elementName, string nodeName, string nodeValue) - { - XmlNode newNode = resxRoot.AddElement(elementName, "").AddAttribute("name", nodeName); - if (elementName == "data") - { - newNode = newNode.AddAttribute("xml:space", "preserve"); - } - newNode.AddElement("value", nodeValue); - } - - private static object GetResourceFileCallBack(CacheItemArgs cacheItemArgs) - { - string cacheKey = cacheItemArgs.CacheKey; - Dictionary resources = null; - - string filePath = null; - try - { - //Get resource file lookup to determine if the resource file even exists - SharedDictionary resourceFileExistsLookup = GetResourceFileLookupDictionary(); - - if (ResourceFileMayExist(resourceFileExistsLookup, cacheKey)) - { - //check if an absolute reference for the resource file was used - if (cacheKey.Contains(":\\") && Path.IsPathRooted(cacheKey)) - { - //if an absolute reference, check that the file exists - if (File.Exists(cacheKey)) - { - filePath = cacheKey; - } - } - - //no filepath found from an absolute reference, try and map the path to get the file path - if (filePath == null) - { - filePath = HostingEnvironment.MapPath(Globals.ApplicationPath + cacheKey); - } - - //The file is not in the lookup, or we know it exists as we have found it before - if (File.Exists(filePath)) - { - if (filePath != null) - { - var doc = new XPathDocument(filePath); - resources = new Dictionary(); - foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/data")) - { - if (nav.NodeType != XPathNodeType.Comment) - { - var selectSingleNode = nav.SelectSingleNode("value"); - if (selectSingleNode != null) - { - resources[nav.GetAttribute("name", String.Empty)] = selectSingleNode.Value; - } - } - } - } - cacheItemArgs.CacheDependency = new DNNCacheDependency(filePath); - - //File exists so add it to lookup with value true, so we are safe to try again - using (resourceFileExistsLookup.GetWriteLock()) - { - resourceFileExistsLookup[cacheKey] = true; - } - } - else - { - //File does not exist so add it to lookup with value false, so we don't try again - using (resourceFileExistsLookup.GetWriteLock()) - { - resourceFileExistsLookup[cacheKey] = false; - } - } - } - } - catch (Exception ex) - { - throw new Exception(string.Format("The following resource file caused an error while reading: {0}", filePath), ex); - } - return resources; - } - - private static SharedDictionary GetResourceFileLookupDictionary() - { - return - CBO.GetCachedObject>( - new CacheItemArgs(DataCache.ResourceFileLookupDictionaryCacheKey, DataCache.ResourceFileLookupDictionaryTimeOut, DataCache.ResourceFileLookupDictionaryCachePriority), - c => new SharedDictionary(), - true); - } - - private static Dictionary GetResourceFile(string resourceFile) - { - return CBO.GetCachedObject>(new CacheItemArgs(resourceFile, DataCache.ResourceFilesCacheTimeOut, DataCache.ResourceFilesCachePriority), - GetResourceFileCallBack, - true); - } - - private static string GetResourceFileName(string resourceFileRoot, string language, int portalId) - { - string resourceFile = GetResourceFileName(resourceFileRoot, language); - if (portalId != -1) - { - resourceFile = resourceFile.Replace(".resx", ".Portal-" + portalId + ".resx"); - } - return resourceFile; - } - - private static string GetResourceFileName(string resourceFileRoot, string language) - { - string resourceFile; - language = language.ToLowerInvariant(); - if (resourceFileRoot != null) - { - if (language == Localization.SystemLocale.ToLowerInvariant() || String.IsNullOrEmpty(language)) - { - switch (resourceFileRoot.Substring(resourceFileRoot.Length - 5, 5).ToLowerInvariant()) - { - case ".resx": - resourceFile = resourceFileRoot; - break; - case ".ascx": - resourceFile = resourceFileRoot + ".resx"; - break; - case ".aspx": - resourceFile = resourceFileRoot + ".resx"; - break; - default: - resourceFile = resourceFileRoot + ".ascx.resx"; //a portal module - break; - } - } - else - { - switch (resourceFileRoot.Substring(resourceFileRoot.Length - 5, 5).ToLowerInvariant()) - { - case ".resx": - resourceFile = resourceFileRoot.Replace(".resx", "." + language + ".resx"); - break; - case ".ascx": - resourceFile = resourceFileRoot.Replace(".ascx", ".ascx." + language + ".resx"); - break; - case ".aspx": - resourceFile = resourceFileRoot.Replace(".aspx", ".aspx." + language + ".resx"); - break; - default: - resourceFile = resourceFileRoot + ".ascx." + language + ".resx"; - break; - } - } - } - else - { - if (language == Localization.SystemLocale.ToLowerInvariant() || String.IsNullOrEmpty(language)) - { - resourceFile = Localization.SharedResourceFile; - } - else - { - resourceFile = Localization.SharedResourceFile.Replace(".resx", "." + language + ".resx"); - } - } - return resourceFile; - } - - private static bool ResourceFileMayExist(SharedDictionary resourceFileExistsLookup, string cacheKey) - { - bool mayExist; - using (resourceFileExistsLookup.GetReadLock()) - { - mayExist = !resourceFileExistsLookup.ContainsKey(cacheKey) || resourceFileExistsLookup[cacheKey]; - } - return mayExist; - } - - private static bool TryGetFromResourceFile(string key, string resourceFile, string userLanguage, string fallbackLanguage, string defaultLanguage, int portalID, ref string resourceValue) - { - //Try the user's language first - bool bFound = TryGetFromResourceFile(key, GetResourceFileName(resourceFile, userLanguage), portalID, ref resourceValue); - - if (!bFound && fallbackLanguage != userLanguage) - { - //Try fallback language next - bFound = TryGetFromResourceFile(key, GetResourceFileName(resourceFile, fallbackLanguage), portalID, ref resourceValue); - } - if (!bFound && !(defaultLanguage == userLanguage || defaultLanguage == fallbackLanguage)) - { - //Try default Language last - bFound = TryGetFromResourceFile(key, GetResourceFileName(resourceFile, defaultLanguage), portalID, ref resourceValue); - } - return bFound; - } - - private static bool TryGetFromResourceFile(string key, string resourceFile, int portalID, ref string resourceValue) - { - //Try Portal Resource File - bool bFound = TryGetFromResourceFile(key, resourceFile, portalID, CustomizedLocale.Portal, ref resourceValue); - if (!bFound) - { - //Try Host Resource File - bFound = TryGetFromResourceFile(key, resourceFile, portalID, CustomizedLocale.Host, ref resourceValue); - } - if (!bFound) - { - //Try Portal Resource File - bFound = TryGetFromResourceFile(key, resourceFile, portalID, CustomizedLocale.None, ref resourceValue); - } - return bFound; - } - - private static bool TryGetStringInternal(string key, string userLanguage, string resourceFile, PortalSettings portalSettings, ref string resourceValue) - { - string defaultLanguage = Null.NullString; - string fallbackLanguage = Localization.SystemLocale; - int portalId = Null.NullInteger; - - //Get the default language - if (portalSettings != null) - { - defaultLanguage = portalSettings.DefaultLanguage; - portalId = portalSettings.PortalId; - } - - //Set the userLanguage if not passed in - if (String.IsNullOrEmpty(userLanguage)) - { - userLanguage = Thread.CurrentThread.CurrentUICulture.ToString(); - } - - //Default the userLanguage to the defaultLanguage if not set - if (String.IsNullOrEmpty(userLanguage)) - { - userLanguage = defaultLanguage; - } - Locale userLocale = null; - try - { - if (Globals.Status != Globals.UpgradeStatus.Install) - { - //Get Fallback language, but not when we are installing (because we may not have a database yet) - userLocale = LocaleController.Instance.GetLocale(userLanguage); - } - } - catch (Exception ex) - { - Logger.Error(ex); - } - - if (userLocale != null && !String.IsNullOrEmpty(userLocale.Fallback)) - { - fallbackLanguage = userLocale.Fallback; - } - if (String.IsNullOrEmpty(resourceFile)) - { - resourceFile = Localization.SharedResourceFile; - } - - //Try the resource file for the key - bool bFound = TryGetFromResourceFile(key, resourceFile, userLanguage, fallbackLanguage, defaultLanguage, portalId, ref resourceValue); - if (!bFound) - { - if (Localization.SharedResourceFile.ToLowerInvariant() != resourceFile.ToLowerInvariant()) - { - //try to use a module specific shared resource file - string localSharedFile = resourceFile.Substring(0, resourceFile.LastIndexOf("/", StringComparison.Ordinal) + 1) + Localization.LocalSharedResourceFile; - - if (localSharedFile.ToLowerInvariant() != resourceFile.ToLowerInvariant()) - { - bFound = TryGetFromResourceFile(key, localSharedFile, userLanguage, fallbackLanguage, defaultLanguage, portalId, ref resourceValue); - } - } - } - if (!bFound) - { - if (Localization.SharedResourceFile.ToLowerInvariant() != resourceFile.ToLowerInvariant()) - { - bFound = TryGetFromResourceFile(key, Localization.SharedResourceFile, userLanguage, fallbackLanguage, defaultLanguage, portalId, ref resourceValue); - } - } - return bFound; - } - - private static bool TryGetFromResourceFile(string key, string resourceFile, int portalID, CustomizedLocale resourceType, ref string resourceValue) - { - bool bFound = Null.NullBoolean; - string resourceFileName = resourceFile; - switch (resourceType) - { - case CustomizedLocale.Host: - resourceFileName = resourceFile.Replace(".resx", ".Host.resx"); - break; - case CustomizedLocale.Portal: - resourceFileName = resourceFile.Replace(".resx", ".Portal-" + portalID + ".resx"); - break; - } - - if (resourceFileName.StartsWith("desktopmodules", StringComparison.InvariantCultureIgnoreCase) - || resourceFileName.StartsWith("admin", StringComparison.InvariantCultureIgnoreCase) - || resourceFileName.StartsWith("controls", StringComparison.InvariantCultureIgnoreCase)) - { - resourceFileName = "~/" + resourceFileName; - } - - //Local resource files are either named ~/... or /... - //The following logic creates a cachekey of /.... - string cacheKey = resourceFileName.Replace("~/", "/").ToLowerInvariant(); - if (!String.IsNullOrEmpty(Globals.ApplicationPath)) - { - if (Globals.ApplicationPath != "/portals") - { - if (cacheKey.StartsWith(Globals.ApplicationPath)) - { - cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length); - } - } - else - { - cacheKey = "~" + cacheKey; - if (cacheKey.StartsWith("~" + Globals.ApplicationPath)) - { - cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length + 1); - } - } - } - - //Get resource file lookup to determine if the resource file even exists - SharedDictionary resourceFileExistsLookup = GetResourceFileLookupDictionary(); - - if (ResourceFileMayExist(resourceFileExistsLookup, cacheKey)) - { - //File is not in lookup or its value is true so we know it exists - Dictionary dicResources = GetResourceFile(cacheKey); - if (dicResources != null) - { - bFound = dicResources.TryGetValue(key, out resourceValue); - } - } - - return bFound; - } - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.Localization +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web.Hosting; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + + public class LocalizationProvider : ComponentBase, ILocalizationProvider + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LocalizationProvider)); + + public enum CustomizedLocale + { + None = 0, + Portal = 1, + Host = 2, + } + + public string GetString(string key, string resourceFileRoot) + { + return this.GetString(key, resourceFileRoot, null, PortalController.Instance.GetCurrentPortalSettings(), false); + } + + public string GetString(string key, string resourceFileRoot, string language) + { + return this.GetString(key, resourceFileRoot, language, PortalController.Instance.GetCurrentPortalSettings(), false); + } + + public string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings) + { + return this.GetString(key, resourceFileRoot, language, portalSettings, false); + } + + public string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings, bool disableShowMissingKeys) + { + // make the default translation property ".Text" + if (key.IndexOf(".", StringComparison.Ordinal) < 1) + { + key += ".Text"; + } + + string resourceValue = Null.NullString; + bool keyFound = TryGetStringInternal(key, language, resourceFileRoot, portalSettings, ref resourceValue); + + // If the key can't be found then it doesn't exist in the Localization Resources + if (Localization.ShowMissingKeys && !disableShowMissingKeys) + { + if (keyFound) + { + resourceValue = "[L]" + resourceValue; + } + else + { + resourceValue = "RESX:" + key; + } + } + + if (!keyFound) + { + Logger.WarnFormat("Missing localization key. key:{0} resFileRoot:{1} threadCulture:{2} userlan:{3}", key, resourceFileRoot, Thread.CurrentThread.CurrentUICulture, language); + } + + return string.IsNullOrEmpty(resourceValue) ? string.Empty : resourceValue; + } + + /// + /// Saves a string to a resource file. + /// + /// The key to save (e.g. "MyWidget.Text"). + /// The text value for the key. + /// Relative path for the resource file root (e.g. "DesktopModules/Admin/Lists/App_LocalResources/ListEditor.ascx.resx"). + /// The locale code in lang-region format (e.g. "fr-FR"). + /// The current portal settings. + /// Specifies whether to save as portal, host or system resource file. + /// if set to true a new file will be created if it is not found. + /// if set to true a new key will be created if not found. + /// If the value could be saved then true will be returned, otherwise false. + /// Any file io error or similar will lead to exceptions. + public bool SaveString(string key, string value, string resourceFileRoot, string language, PortalSettings portalSettings, CustomizedLocale resourceType, bool createFile, bool createKey) + { + try + { + if (key.IndexOf(".", StringComparison.Ordinal) < 1) + { + key += ".Text"; + } + + string resourceFileName = GetResourceFileName(resourceFileRoot, language); + resourceFileName = resourceFileName.Replace("." + language.ToLowerInvariant() + ".", "." + language + "."); + switch (resourceType) + { + case CustomizedLocale.Host: + resourceFileName = resourceFileName.Replace(".resx", ".Host.resx"); + break; + case CustomizedLocale.Portal: + resourceFileName = resourceFileName.Replace(".resx", ".Portal-" + portalSettings.PortalId + ".resx"); + break; + } + + resourceFileName = resourceFileName.TrimStart('~', '/', '\\'); + string filePath = HostingEnvironment.MapPath("~/" + resourceFileName); + XmlDocument doc = null; + if (File.Exists(filePath)) + { + doc = new XmlDocument { XmlResolver = null }; + doc.Load(filePath); + } + else + { + if (createFile) + { + doc = new XmlDocument { XmlResolver = null }; + doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes")); + XmlNode root = doc.CreateElement("root"); + doc.AppendChild(root); + AddResourceFileNode(ref root, "resheader", "resmimetype", "text/microsoft-resx"); + AddResourceFileNode(ref root, "resheader", "version", "2.0"); + AddResourceFileNode(ref root, "resheader", "reader", "System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); + AddResourceFileNode(ref root, "resheader", "writer", "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); + } + } + + if (doc == null) + { + return false; + } + + XmlNode reskeyNode = doc.SelectSingleNode("root/data[@name=\"" + key + "\"]"); + if (reskeyNode != null) + { + reskeyNode.SelectSingleNode("value").InnerText = value; + } + else + { + if (createKey) + { + XmlNode root = doc.SelectSingleNode("root"); + AddResourceFileNode(ref root, "data", key, value); + } + else + { + return false; + } + } + + doc.Save(filePath); + DataCache.RemoveCache("/" + resourceFileName.ToLowerInvariant()); + return true; + } + catch (Exception ex) + { + throw new Exception(string.Format("Error while trying to create resource in {0}", resourceFileRoot), ex); + } + } + + public Dictionary GetCompiledResourceFile(PortalSettings portalSettings, string resourceFile, string locale) + { + return + CBO.GetCachedObject>( + new CacheItemArgs( + "Compiled-" + resourceFile + "-" + locale + "-" + portalSettings.PortalId, + DataCache.ResourceFilesCacheTimeOut, DataCache.ResourceFilesCachePriority, resourceFile, locale, + portalSettings), GetCompiledResourceFileCallBack, true); + } + + private static object GetCompiledResourceFileCallBack(CacheItemArgs cacheItemArgs) + { + string resourceFile = (string)cacheItemArgs.Params[0]; + string locale = (string)cacheItemArgs.Params[1]; + PortalSettings portalSettings = (PortalSettings)cacheItemArgs.Params[2]; + string systemLanguage = Localization.SystemLocale; + string defaultLanguage = portalSettings.DefaultLanguage; + string fallbackLanguage = Localization.SystemLocale; + Locale targetLocale = LocaleController.Instance.GetLocale(locale); + if (!string.IsNullOrEmpty(targetLocale.Fallback)) + { + fallbackLanguage = targetLocale.Fallback; + } + + // get system default and merge the specific ones one by one + var res = GetResourceFile(resourceFile); + if (res == null) + { + return new Dictionary(); + } + + // clone the dictionart so that when merge values into dictionart, it won't + // affect the cache data. + res = res.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + res = MergeResourceFile(res, GetResourceFileName(resourceFile, systemLanguage, portalSettings.PortalId)); + if (defaultLanguage != systemLanguage) + { + res = MergeResourceFile(res, GetResourceFileName(resourceFile, defaultLanguage)); + res = MergeResourceFile(res, GetResourceFileName(resourceFile, defaultLanguage, portalSettings.PortalId)); + } + + if (fallbackLanguage != defaultLanguage) + { + res = MergeResourceFile(res, GetResourceFileName(resourceFile, fallbackLanguage)); + res = MergeResourceFile(res, GetResourceFileName(resourceFile, fallbackLanguage, portalSettings.PortalId)); + } + + if (locale != fallbackLanguage) + { + res = MergeResourceFile(res, GetResourceFileName(resourceFile, locale)); + res = MergeResourceFile(res, GetResourceFileName(resourceFile, locale, portalSettings.PortalId)); + } + + return res; + } + + private static Dictionary MergeResourceFile(Dictionary current, string resourceFile) + { + var resFile = GetResourceFile(resourceFile); + if (resFile == null) + { + return current; + } + + foreach (string key in current.Keys.ToList()) + { + if (resFile.ContainsKey(key)) + { + current[key] = resFile[key]; + } + } + + return current; + } + + /// + /// Adds one of either a "resheader" or "data" element to resxRoot (which should be the root element of the resx file). + /// This function is used to construct new resource files and to add resource keys to an existing file. + /// + /// The RESX root. + /// Name of the element ("resheader" or "data"). + /// Name of the node (in case of "data" specify the localization key here, e.g. "MyWidget.Text"). + /// The node value (text value to use). + private static void AddResourceFileNode(ref XmlNode resxRoot, string elementName, string nodeName, string nodeValue) + { + XmlNode newNode = resxRoot.AddElement(elementName, string.Empty).AddAttribute("name", nodeName); + if (elementName == "data") + { + newNode = newNode.AddAttribute("xml:space", "preserve"); + } + + newNode.AddElement("value", nodeValue); + } + + private static object GetResourceFileCallBack(CacheItemArgs cacheItemArgs) + { + string cacheKey = cacheItemArgs.CacheKey; + Dictionary resources = null; + + string filePath = null; + try + { + // Get resource file lookup to determine if the resource file even exists + SharedDictionary resourceFileExistsLookup = GetResourceFileLookupDictionary(); + + if (ResourceFileMayExist(resourceFileExistsLookup, cacheKey)) + { + // check if an absolute reference for the resource file was used + if (cacheKey.Contains(":\\") && Path.IsPathRooted(cacheKey)) + { + // if an absolute reference, check that the file exists + if (File.Exists(cacheKey)) + { + filePath = cacheKey; + } + } + + // no filepath found from an absolute reference, try and map the path to get the file path + if (filePath == null) + { + filePath = HostingEnvironment.MapPath(Globals.ApplicationPath + cacheKey); + } + + // The file is not in the lookup, or we know it exists as we have found it before + if (File.Exists(filePath)) + { + if (filePath != null) + { + var doc = new XPathDocument(filePath); + resources = new Dictionary(); + foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/data")) + { + if (nav.NodeType != XPathNodeType.Comment) + { + var selectSingleNode = nav.SelectSingleNode("value"); + if (selectSingleNode != null) + { + resources[nav.GetAttribute("name", string.Empty)] = selectSingleNode.Value; + } + } + } + } + + cacheItemArgs.CacheDependency = new DNNCacheDependency(filePath); + + // File exists so add it to lookup with value true, so we are safe to try again + using (resourceFileExistsLookup.GetWriteLock()) + { + resourceFileExistsLookup[cacheKey] = true; + } + } + else + { + // File does not exist so add it to lookup with value false, so we don't try again + using (resourceFileExistsLookup.GetWriteLock()) + { + resourceFileExistsLookup[cacheKey] = false; + } + } + } + } + catch (Exception ex) + { + throw new Exception(string.Format("The following resource file caused an error while reading: {0}", filePath), ex); + } + + return resources; + } + + private static SharedDictionary GetResourceFileLookupDictionary() + { + return + CBO.GetCachedObject>( + new CacheItemArgs(DataCache.ResourceFileLookupDictionaryCacheKey, DataCache.ResourceFileLookupDictionaryTimeOut, DataCache.ResourceFileLookupDictionaryCachePriority), + c => new SharedDictionary(), + true); + } + + private static Dictionary GetResourceFile(string resourceFile) + { + return CBO.GetCachedObject>( + new CacheItemArgs(resourceFile, DataCache.ResourceFilesCacheTimeOut, DataCache.ResourceFilesCachePriority), + GetResourceFileCallBack, + true); + } + + private static string GetResourceFileName(string resourceFileRoot, string language, int portalId) + { + string resourceFile = GetResourceFileName(resourceFileRoot, language); + if (portalId != -1) + { + resourceFile = resourceFile.Replace(".resx", ".Portal-" + portalId + ".resx"); + } + + return resourceFile; + } + + private static string GetResourceFileName(string resourceFileRoot, string language) + { + string resourceFile; + language = language.ToLowerInvariant(); + if (resourceFileRoot != null) + { + if (language == Localization.SystemLocale.ToLowerInvariant() || string.IsNullOrEmpty(language)) + { + switch (resourceFileRoot.Substring(resourceFileRoot.Length - 5, 5).ToLowerInvariant()) + { + case ".resx": + resourceFile = resourceFileRoot; + break; + case ".ascx": + resourceFile = resourceFileRoot + ".resx"; + break; + case ".aspx": + resourceFile = resourceFileRoot + ".resx"; + break; + default: + resourceFile = resourceFileRoot + ".ascx.resx"; // a portal module + break; + } + } + else + { + switch (resourceFileRoot.Substring(resourceFileRoot.Length - 5, 5).ToLowerInvariant()) + { + case ".resx": + resourceFile = resourceFileRoot.Replace(".resx", "." + language + ".resx"); + break; + case ".ascx": + resourceFile = resourceFileRoot.Replace(".ascx", ".ascx." + language + ".resx"); + break; + case ".aspx": + resourceFile = resourceFileRoot.Replace(".aspx", ".aspx." + language + ".resx"); + break; + default: + resourceFile = resourceFileRoot + ".ascx." + language + ".resx"; + break; + } + } + } + else + { + if (language == Localization.SystemLocale.ToLowerInvariant() || string.IsNullOrEmpty(language)) + { + resourceFile = Localization.SharedResourceFile; + } + else + { + resourceFile = Localization.SharedResourceFile.Replace(".resx", "." + language + ".resx"); + } + } + + return resourceFile; + } + + private static bool ResourceFileMayExist(SharedDictionary resourceFileExistsLookup, string cacheKey) + { + bool mayExist; + using (resourceFileExistsLookup.GetReadLock()) + { + mayExist = !resourceFileExistsLookup.ContainsKey(cacheKey) || resourceFileExistsLookup[cacheKey]; + } + + return mayExist; + } + + private static bool TryGetFromResourceFile(string key, string resourceFile, string userLanguage, string fallbackLanguage, string defaultLanguage, int portalID, ref string resourceValue) + { + // Try the user's language first + bool bFound = TryGetFromResourceFile(key, GetResourceFileName(resourceFile, userLanguage), portalID, ref resourceValue); + + if (!bFound && fallbackLanguage != userLanguage) + { + // Try fallback language next + bFound = TryGetFromResourceFile(key, GetResourceFileName(resourceFile, fallbackLanguage), portalID, ref resourceValue); + } + + if (!bFound && !(defaultLanguage == userLanguage || defaultLanguage == fallbackLanguage)) + { + // Try default Language last + bFound = TryGetFromResourceFile(key, GetResourceFileName(resourceFile, defaultLanguage), portalID, ref resourceValue); + } + + return bFound; + } + + private static bool TryGetFromResourceFile(string key, string resourceFile, int portalID, ref string resourceValue) + { + // Try Portal Resource File + bool bFound = TryGetFromResourceFile(key, resourceFile, portalID, CustomizedLocale.Portal, ref resourceValue); + if (!bFound) + { + // Try Host Resource File + bFound = TryGetFromResourceFile(key, resourceFile, portalID, CustomizedLocale.Host, ref resourceValue); + } + + if (!bFound) + { + // Try Portal Resource File + bFound = TryGetFromResourceFile(key, resourceFile, portalID, CustomizedLocale.None, ref resourceValue); + } + + return bFound; + } + + private static bool TryGetStringInternal(string key, string userLanguage, string resourceFile, PortalSettings portalSettings, ref string resourceValue) + { + string defaultLanguage = Null.NullString; + string fallbackLanguage = Localization.SystemLocale; + int portalId = Null.NullInteger; + + // Get the default language + if (portalSettings != null) + { + defaultLanguage = portalSettings.DefaultLanguage; + portalId = portalSettings.PortalId; + } + + // Set the userLanguage if not passed in + if (string.IsNullOrEmpty(userLanguage)) + { + userLanguage = Thread.CurrentThread.CurrentUICulture.ToString(); + } + + // Default the userLanguage to the defaultLanguage if not set + if (string.IsNullOrEmpty(userLanguage)) + { + userLanguage = defaultLanguage; + } + + Locale userLocale = null; + try + { + if (Globals.Status != Globals.UpgradeStatus.Install) + { + // Get Fallback language, but not when we are installing (because we may not have a database yet) + userLocale = LocaleController.Instance.GetLocale(userLanguage); + } + } + catch (Exception ex) + { + Logger.Error(ex); + } + + if (userLocale != null && !string.IsNullOrEmpty(userLocale.Fallback)) + { + fallbackLanguage = userLocale.Fallback; + } + + if (string.IsNullOrEmpty(resourceFile)) + { + resourceFile = Localization.SharedResourceFile; + } + + // Try the resource file for the key + bool bFound = TryGetFromResourceFile(key, resourceFile, userLanguage, fallbackLanguage, defaultLanguage, portalId, ref resourceValue); + if (!bFound) + { + if (Localization.SharedResourceFile.ToLowerInvariant() != resourceFile.ToLowerInvariant()) + { + // try to use a module specific shared resource file + string localSharedFile = resourceFile.Substring(0, resourceFile.LastIndexOf("/", StringComparison.Ordinal) + 1) + Localization.LocalSharedResourceFile; + + if (localSharedFile.ToLowerInvariant() != resourceFile.ToLowerInvariant()) + { + bFound = TryGetFromResourceFile(key, localSharedFile, userLanguage, fallbackLanguage, defaultLanguage, portalId, ref resourceValue); + } + } + } + + if (!bFound) + { + if (Localization.SharedResourceFile.ToLowerInvariant() != resourceFile.ToLowerInvariant()) + { + bFound = TryGetFromResourceFile(key, Localization.SharedResourceFile, userLanguage, fallbackLanguage, defaultLanguage, portalId, ref resourceValue); + } + } + + return bFound; + } + + private static bool TryGetFromResourceFile(string key, string resourceFile, int portalID, CustomizedLocale resourceType, ref string resourceValue) + { + bool bFound = Null.NullBoolean; + string resourceFileName = resourceFile; + switch (resourceType) + { + case CustomizedLocale.Host: + resourceFileName = resourceFile.Replace(".resx", ".Host.resx"); + break; + case CustomizedLocale.Portal: + resourceFileName = resourceFile.Replace(".resx", ".Portal-" + portalID + ".resx"); + break; + } + + if (resourceFileName.StartsWith("desktopmodules", StringComparison.InvariantCultureIgnoreCase) + || resourceFileName.StartsWith("admin", StringComparison.InvariantCultureIgnoreCase) + || resourceFileName.StartsWith("controls", StringComparison.InvariantCultureIgnoreCase)) + { + resourceFileName = "~/" + resourceFileName; + } + + // Local resource files are either named ~/... or /... + // The following logic creates a cachekey of /.... + string cacheKey = resourceFileName.Replace("~/", "/").ToLowerInvariant(); + if (!string.IsNullOrEmpty(Globals.ApplicationPath)) + { + if (Globals.ApplicationPath != "/portals") + { + if (cacheKey.StartsWith(Globals.ApplicationPath)) + { + cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length); + } + } + else + { + cacheKey = "~" + cacheKey; + if (cacheKey.StartsWith("~" + Globals.ApplicationPath)) + { + cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length + 1); + } + } + } + + // Get resource file lookup to determine if the resource file even exists + SharedDictionary resourceFileExistsLookup = GetResourceFileLookupDictionary(); + + if (ResourceFileMayExist(resourceFileExistsLookup, cacheKey)) + { + // File is not in lookup or its value is true so we know it exists + Dictionary dicResources = GetResourceFile(cacheKey); + if (dicResources != null) + { + bFound = dicResources.TryGetValue(key, out resourceValue); + } + } + + return bFound; + } + } +} diff --git a/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs b/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs index 20a2fda106a..deb676528c8 100644 --- a/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs +++ b/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs @@ -1,60 +1,80 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization.Persian { + using System; + public class PersianCalendar : System.Globalization.PersianCalendar { public override int GetYear(DateTime time) { - try { return base.GetYear(time); } + try + { + return base.GetYear(time); + } catch { - //ignore + // ignore } + return time.Year; } public override int GetMonth(DateTime time) { - try { return base.GetMonth(time); } + try + { + return base.GetMonth(time); + } catch { - //ignore + // ignore } + return time.Month; } public override int GetDayOfMonth(DateTime time) { - try { return base.GetDayOfMonth(time); } + try + { + return base.GetDayOfMonth(time); + } catch { - //ignore + // ignore } + return time.Day; } public override int GetDayOfYear(DateTime time) { - try { return base.GetDayOfYear(time); } + try + { + return base.GetDayOfYear(time); + } catch { - //ignore + // ignore } + return time.DayOfYear; } public override DayOfWeek GetDayOfWeek(DateTime time) { - try { return base.GetDayOfWeek(time); } + try + { + return base.GetDayOfWeek(time); + } catch { - //ignore + // ignore } + return time.DayOfWeek; } } diff --git a/DNN Platform/Library/Services/Localization/Persian/PersianController.cs b/DNN Platform/Library/Services/Localization/Persian/PersianController.cs index cf19ebc7fab..4785b9b7a0a 100644 --- a/DNN Platform/Library/Services/Localization/Persian/PersianController.cs +++ b/DNN Platform/Library/Services/Localization/Persian/PersianController.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Localization.Persian { - class PersianController + using System; + using System.Globalization; + using System.Reflection; + + internal class PersianController { public static CultureInfo GetPersianCultureInfo() { @@ -20,19 +20,23 @@ public static CultureInfo GetPersianCultureInfo() var cal = new PersianCalendar(); FieldInfo fieldInfo = persianCultureInfo.GetType().GetField("calendar", BindingFlags.NonPublic | BindingFlags.Instance); - if (fieldInfo != null) - fieldInfo.SetValue(persianCultureInfo, cal); - + if (fieldInfo != null) + { + fieldInfo.SetValue(persianCultureInfo, cal); + } + FieldInfo info = persianCultureInfo.DateTimeFormat.GetType().GetField("calendar", BindingFlags.NonPublic | BindingFlags.Instance); - if (info != null) - info.SetValue(persianCultureInfo.DateTimeFormat, cal); - + if (info != null) + { + info.SetValue(persianCultureInfo.DateTimeFormat, cal); + } + return persianCultureInfo; } public static void SetPersianDateTimeFormatInfo(DateTimeFormatInfo persianDateTimeFormatInfo) { - persianDateTimeFormatInfo.MonthNames = new[] { "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند", "" }; + persianDateTimeFormatInfo.MonthNames = new[] { "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند", string.Empty }; persianDateTimeFormatInfo.MonthGenitiveNames = persianDateTimeFormatInfo.MonthNames; persianDateTimeFormatInfo.AbbreviatedMonthNames = persianDateTimeFormatInfo.MonthNames; persianDateTimeFormatInfo.AbbreviatedMonthGenitiveNames = persianDateTimeFormatInfo.MonthNames; diff --git a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs index a06d5dca76c..9430cd5887f 100644 --- a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs +++ b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs @@ -1,95 +1,94 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Threading; -using System.Web; -using System.Web.Caching; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Scheduling; - -#endregion - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + using System.Threading; + using System.Web; + using System.Web.Caching; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Scheduling; + public class DBLoggingProvider : LoggingProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DBLoggingProvider)); + public const string LogTypeCacheKey = "LogTypes"; + public const string LogTypeInfoCacheKey = "GetLogTypeConfigInfo"; + private const int ReaderLockTimeout = 10000; private const int WriterLockTimeout = 10000; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DBLoggingProvider)); private static readonly IList LogQueue = new List(); private static readonly ReaderWriterLockSlim LockNotif = new ReaderWriterLockSlim(); private static readonly ReaderWriterLockSlim LockQueueLog = new ReaderWriterLockSlim(); - - public const string LogTypeCacheKey = "LogTypes"; - public const string LogTypeInfoCacheKey = "GetLogTypeConfigInfo"; public const string LogTypeInfoByKeyCacheKey = "GetLogTypeConfigInfoByKey"; + public override void AddLog(LogInfo logInfo) + { + string configPortalID = logInfo.LogPortalID != Null.NullInteger + ? logInfo.LogPortalID.ToString() + : "*"; + var logTypeConfigInfo = this.GetLogTypeConfigInfoByKey(logInfo.LogTypeKey, configPortalID); + if (logTypeConfigInfo == null || logTypeConfigInfo.LoggingIsActive == false) + { + return; + } + + logInfo.LogConfigID = logTypeConfigInfo.ID; + var logQueueItem = new LogQueueItem { LogInfo = logInfo, LogTypeConfigInfo = logTypeConfigInfo }; + SchedulingProvider scheduler = SchedulingProvider.Instance(); + if (scheduler == null || logInfo.BypassBuffering || SchedulingProvider.Enabled == false + || scheduler.GetScheduleStatus() == ScheduleStatus.STOPPED || !Host.EventLogBuffer) + { + WriteLog(logQueueItem); + } + else + { + LogQueue.Add(logQueueItem); + } + } + + // ReSharper disable once InconsistentNaming + public override void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner) + { + DataProvider.Instance().AddLogType(logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeCSSClass, logTypeOwner); + DataCache.RemoveCache(LogTypeCacheKey); + } + private static Hashtable FillLogTypeConfigInfoByKey(ArrayList arr) { var ht = new Hashtable(); int i; for (i = 0; i <= arr.Count - 1; i++) { - var logTypeConfigInfo = (LogTypeConfigInfo) arr[i]; - if (String.IsNullOrEmpty(logTypeConfigInfo.LogTypeKey)) + var logTypeConfigInfo = (LogTypeConfigInfo)arr[i]; + if (string.IsNullOrEmpty(logTypeConfigInfo.LogTypeKey)) { logTypeConfigInfo.LogTypeKey = "*"; } - if (String.IsNullOrEmpty(logTypeConfigInfo.LogTypePortalID)) + + if (string.IsNullOrEmpty(logTypeConfigInfo.LogTypePortalID)) { logTypeConfigInfo.LogTypePortalID = "*"; } + ht.Add(logTypeConfigInfo.LogTypeKey + "|" + logTypeConfigInfo.LogTypePortalID, logTypeConfigInfo); } + DataCache.SetCache(LogTypeInfoByKeyCacheKey, ht); return ht; } - private LogTypeConfigInfo GetLogTypeConfigInfoByKey(string logTypeKey, string logTypePortalID) - { - var configInfoByKey = (Hashtable)DataCache.GetCache(LogTypeInfoByKeyCacheKey) ?? FillLogTypeConfigInfoByKey(GetLogTypeConfigInfo()); - var logTypeConfigInfo = (LogTypeConfigInfo) configInfoByKey[logTypeKey + "|" + logTypePortalID]; - if (logTypeConfigInfo == null) - { - logTypeConfigInfo = (LogTypeConfigInfo) configInfoByKey["*|" + logTypePortalID]; - if (logTypeConfigInfo == null) - { - logTypeConfigInfo = (LogTypeConfigInfo) configInfoByKey[logTypeKey + "|*"]; - if (logTypeConfigInfo == null) - { - logTypeConfigInfo = (LogTypeConfigInfo) configInfoByKey["*|*"]; - } - else - { - return logTypeConfigInfo; - } - } - else - { - return logTypeConfigInfo; - } - } - else - { - return logTypeConfigInfo; - } - return logTypeConfigInfo; - } - private static LogInfo FillLogInfo(IDataReader dr) { var obj = new LogInfo(); @@ -131,6 +130,7 @@ private static LogInfo FillLogInfo(IDataReader dr) { Logger.Error(exc); } + return obj; } @@ -143,6 +143,7 @@ private static void FillLogs(IDataReader dr, IList logs, ref int totalRecords) LogInfo logInfo = FillLogInfo(dr); logs.Add(logInfo); } + dr.NextResult(); while (dr.Read()) { @@ -155,6 +156,38 @@ private static void FillLogs(IDataReader dr, IList logs, ref int totalRecords) } } + private LogTypeConfigInfo GetLogTypeConfigInfoByKey(string logTypeKey, string logTypePortalID) + { + var configInfoByKey = (Hashtable)DataCache.GetCache(LogTypeInfoByKeyCacheKey) ?? FillLogTypeConfigInfoByKey(this.GetLogTypeConfigInfo()); + var logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey[logTypeKey + "|" + logTypePortalID]; + if (logTypeConfigInfo == null) + { + logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey["*|" + logTypePortalID]; + if (logTypeConfigInfo == null) + { + logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey[logTypeKey + "|*"]; + if (logTypeConfigInfo == null) + { + logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey["*|*"]; + } + else + { + return logTypeConfigInfo; + } + } + else + { + return logTypeConfigInfo; + } + } + else + { + return logTypeConfigInfo; + } + + return logTypeConfigInfo; + } + private static void WriteError(LogTypeConfigInfo logTypeConfigInfo, Exception exc, string header, string message) { if (HttpContext.Current != null) @@ -173,11 +206,11 @@ private static void WriteError(LogTypeConfigInfo logTypeConfigInfo, Exception ex { HtmlUtils.WriteError(response, logTypeConfigInfo.LogFileNameWithPath, message); } + HtmlUtils.WriteFooter(response); response.End(); } } - } private static void WriteLog(LogQueueItem logQueueItem) @@ -190,18 +223,19 @@ private static void WriteLog(LogQueueItem logQueueItem) { LogInfo objLogInfo = logQueueItem.LogInfo; string logProperties = objLogInfo.LogProperties.Serialize(); - DataProvider.Instance().AddLog(objLogInfo.LogGUID, - objLogInfo.LogTypeKey, - objLogInfo.LogUserID, - objLogInfo.LogUserName, - objLogInfo.LogPortalID, - objLogInfo.LogPortalName, - objLogInfo.LogCreateDate, - objLogInfo.LogServerName, - logProperties, - Convert.ToInt32(objLogInfo.LogConfigID), - objLogInfo.Exception, - logTypeConfigInfo.EmailNotificationIsActive); + DataProvider.Instance().AddLog( + objLogInfo.LogGUID, + objLogInfo.LogTypeKey, + objLogInfo.LogUserID, + objLogInfo.LogUserName, + objLogInfo.LogPortalID, + objLogInfo.LogPortalName, + objLogInfo.LogCreateDate, + objLogInfo.LogServerName, + logProperties, + Convert.ToInt32(objLogInfo.LogConfigID), + objLogInfo.Exception, + logTypeConfigInfo.EmailNotificationIsActive); if (logTypeConfigInfo.EmailNotificationIsActive) { if (LockNotif.TryEnterWriteLock(ReaderLockTimeout)) @@ -234,37 +268,6 @@ private static void WriteLog(LogQueueItem logQueueItem) } } - public override void AddLog(LogInfo logInfo) - { - string configPortalID = logInfo.LogPortalID != Null.NullInteger - ? logInfo.LogPortalID.ToString() - : "*"; - var logTypeConfigInfo = GetLogTypeConfigInfoByKey(logInfo.LogTypeKey, configPortalID); - if (logTypeConfigInfo == null || logTypeConfigInfo.LoggingIsActive == false) - { - return; - } - logInfo.LogConfigID = logTypeConfigInfo.ID; - var logQueueItem = new LogQueueItem {LogInfo = logInfo, LogTypeConfigInfo = logTypeConfigInfo}; - SchedulingProvider scheduler = SchedulingProvider.Instance(); - if (scheduler == null || logInfo.BypassBuffering || SchedulingProvider.Enabled == false - || scheduler.GetScheduleStatus() == ScheduleStatus.STOPPED || !Host.EventLogBuffer) - { - WriteLog(logQueueItem); - } - else - { - LogQueue.Add(logQueueItem); - } - } - - // ReSharper disable once InconsistentNaming - public override void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner) - { - DataProvider.Instance().AddLogType(logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeCSSClass, logTypeOwner); - DataCache.RemoveCache(LogTypeCacheKey); - } - public override void AddLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string thresholdTime, string thresholdTimeType, string mailFromAddress, string mailToAddress) { @@ -276,28 +279,33 @@ public override void AddLogTypeConfigInfo(string id, bool loggingIsActive, strin { intThreshold = Convert.ToInt32(threshold); } + if (Globals.NumberMatchRegex.IsMatch(thresholdTime)) { intThresholdTime = Convert.ToInt32(thresholdTime); } + if (Globals.NumberMatchRegex.IsMatch(thresholdTimeType)) { intThresholdTimeType = Convert.ToInt32(thresholdTimeType); } + if (Globals.NumberMatchRegex.IsMatch(keepMostRecent)) { intKeepMostRecent = Convert.ToInt32(keepMostRecent); } - DataProvider.Instance().AddLogTypeConfigInfo(loggingIsActive, - logTypeKey, - logTypePortalID, - intKeepMostRecent, - emailNotificationIsActive, - intThreshold, - intThresholdTime, - intThresholdTimeType, - mailFromAddress, - mailToAddress); + + DataProvider.Instance().AddLogTypeConfigInfo( + loggingIsActive, + logTypeKey, + logTypePortalID, + intKeepMostRecent, + emailNotificationIsActive, + intThreshold, + intThresholdTime, + intThresholdTimeType, + mailFromAddress, + mailToAddress); DataCache.RemoveCache(LogTypeInfoCacheKey); DataCache.RemoveCache(LogTypeInfoByKeyCacheKey); } @@ -341,7 +349,7 @@ public override ArrayList GetLogTypeConfigInfo() try { dr = DataProvider.Instance().GetLogTypeConfigInfo(); - list = CBO.FillCollection(dr, typeof (LogTypeConfigInfo)); + list = CBO.FillCollection(dr, typeof(LogTypeConfigInfo)); DataCache.SetCache(LogTypeInfoCacheKey, list); FillLogTypeConfigInfoByKey(list); } @@ -357,6 +365,7 @@ public override ArrayList GetLogTypeConfigInfo() } } } + return list; } @@ -367,8 +376,9 @@ public override LogTypeConfigInfo GetLogTypeConfigInfoByID(string id) public override ArrayList GetLogTypeInfo() { - return CBO.GetCachedObject(new CacheItemArgs(LogTypeCacheKey, 20, CacheItemPriority.Normal), - c => CBO.FillCollection(DataProvider.Instance().GetLogTypeInfo(), typeof (LogTypeInfo))); + return CBO.GetCachedObject( + new CacheItemArgs(LogTypeCacheKey, 20, CacheItemPriority.Normal), + c => CBO.FillCollection(DataProvider.Instance().GetLogTypeInfo(), typeof(LogTypeInfo))); } public override object GetSingleLog(LogInfo logInfo, ReturnType returnType) @@ -387,15 +397,18 @@ public override object GetSingleLog(LogInfo logInfo, ReturnType returnType) { CBO.CloseDataReader(dr, true); } + if (returnType == ReturnType.LogInfoObjects) { return log; } + var xmlDoc = new XmlDocument { XmlResolver = null }; if (log != null) { xmlDoc.LoadXml(log.Serialize()); } + return xmlDoc.DocumentElement; } @@ -406,24 +419,31 @@ public override bool LoggingIsEnabled(string logType, int portalID) { configPortalID = "*"; } - LogTypeConfigInfo configInfo = GetLogTypeConfigInfoByKey(logType, configPortalID); + + LogTypeConfigInfo configInfo = this.GetLogTypeConfigInfoByKey(logType, configPortalID); if (configInfo == null) { return false; } + return configInfo.LoggingIsActive; } public override void PurgeLogBuffer() { - if (!LockQueueLog.TryEnterWriteLock(WriterLockTimeout)) return; + if (!LockQueueLog.TryEnterWriteLock(WriterLockTimeout)) + { + return; + } + try { for (int i = LogQueue.Count - 1; i >= 0; i += -1) { LogQueueItem logQueueItem = LogQueue[i]; - //in case the log was removed - //by another thread simultaneously + + // in case the log was removed + // by another thread simultaneously if (logQueueItem != null) { WriteLog(logQueueItem); @@ -435,6 +455,7 @@ public override void PurgeLogBuffer() { LockQueueLog.ExitWriteLock(); } + DataProvider.Instance().PurgeLog(); } @@ -444,7 +465,7 @@ public override void SendLogNotifications() foreach (LogTypeConfigInfo typeConfigInfo in configInfos) { IDataReader dr = DataProvider.Instance().GetEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID)); - string log = ""; + string log = string.Empty; try { while (dr.Read()) @@ -457,6 +478,7 @@ public override void SendLogNotifications() { CBO.CloseDataReader(dr, true); } + Mail.Mail.SendEmail(typeConfigInfo.MailFromAddress, typeConfigInfo.MailToAddress, "Event Notification", string.Format("
    {0}
    ", HttpUtility.HtmlEncode(log))); DataProvider.Instance().UpdateEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID)); } @@ -499,29 +521,34 @@ public override void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, st { intThreshold = Convert.ToInt32(threshold); } + if (Globals.NumberMatchRegex.IsMatch(thresholdTime)) { intThresholdTime = Convert.ToInt32(thresholdTime); } + if (Globals.NumberMatchRegex.IsMatch(thresholdTimeType)) { intThresholdTimeType = Convert.ToInt32(thresholdTimeType); } + if (Globals.NumberMatchRegex.IsMatch(keepMostRecent)) { intKeepMostRecent = Convert.ToInt32(keepMostRecent); } - DataProvider.Instance().UpdateLogTypeConfigInfo(id, - loggingIsActive, - logTypeKey, - logTypePortalID, - intKeepMostRecent, - emailNotificationIsActive, - intThreshold, - intThresholdTime, - intThresholdTimeType, - mailFromAddress, - mailToAddress); + + DataProvider.Instance().UpdateLogTypeConfigInfo( + id, + loggingIsActive, + logTypeKey, + logTypePortalID, + intKeepMostRecent, + emailNotificationIsActive, + intThreshold, + intThresholdTime, + intThresholdTimeType, + mailFromAddress, + mailToAddress); DataCache.RemoveCache(LogTypeInfoCacheKey); DataCache.RemoveCache(LogTypeInfoByKeyCacheKey); } diff --git a/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs b/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs index 94865cfb87d..47a80fcb294 100644 --- a/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs @@ -1,32 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + public class EventLogController : ServiceLocator, IEventLogController - { - #region EventLogType enum - + { public enum EventLogType { USER_CREATED, @@ -182,62 +175,69 @@ public enum EventLogType WEBSERVER_DISABLED, WEBSERVER_ENABLED, WEBSERVER_PINGFAILED, - FOLDER_MOVED - } - - #endregion - - protected override Func GetFactory() + FOLDER_MOVED, + } + + public static void AddSettingLog(EventLogType logTypeKey, string idFieldName, int idValue, string settingName, string settingValue, int userId) { - return () => new EventLogController(); - } - - #region IEventLogController Members + var log = new LogInfo() { LogUserID = userId, LogTypeKey = logTypeKey.ToString() }; + log.LogProperties.Add(new LogDetailInfo(idFieldName, idValue.ToString())); + log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); + log.LogProperties.Add(new LogDetailInfo("SettingValue", settingValue)); + LogController.Instance.AddLog(log); + } + public void AddLog(string propertyName, string propertyValue, EventLogType logType) { - AddLog(propertyName, propertyValue, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, logType); + this.AddLog(propertyName, propertyValue, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, logType); } public void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, EventLogType logType) { - AddLog(propertyName, propertyValue, portalSettings, userID, logType.ToString()); + this.AddLog(propertyName, propertyValue, portalSettings, userID, logType.ToString()); } + + protected override Func GetFactory() + { + return () => new EventLogController(); + } public void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, string logType) { var properties = new LogProperties(); - var logDetailInfo = new LogDetailInfo {PropertyName = propertyName, PropertyValue = propertyValue}; + var logDetailInfo = new LogDetailInfo { PropertyName = propertyName, PropertyValue = propertyValue }; properties.Add(logDetailInfo); - AddLog(properties, portalSettings, userID, logType, false); + this.AddLog(properties, portalSettings, userID, logType, false); } public void AddLog(LogProperties properties, PortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering) { - //supports adding a custom string for LogType - var log = new LogInfo - { - LogUserID = userID, - LogTypeKey = logTypeKey, - LogProperties = properties, - BypassBuffering = bypassBuffering - }; + // supports adding a custom string for LogType + var log = new LogInfo + { + LogUserID = userID, + LogTypeKey = logTypeKey, + LogProperties = properties, + BypassBuffering = bypassBuffering, + }; if (portalSettings != null) { log.LogPortalID = portalSettings.PortalId; log.LogPortalName = portalSettings.PortalName; } + LogController.Instance.AddLog(log); } public void AddLog(PortalSettings portalSettings, int userID, EventLogType logType) { - AddLog(new LogProperties(), portalSettings, userID, logType.ToString(), false); + this.AddLog(new LogProperties(), portalSettings, userID, logType.ToString(), false); } public void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, EventLogType logType) { - AddLog(businessObject, portalSettings, userID, userName, logType.ToString()); + this.AddLog(businessObject, portalSettings, userID, userName, logType.ToString()); } public void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, string logType) @@ -339,17 +339,13 @@ public void AddLog(object businessObject, PortalSettings portalSettings, int use } else { - //Serialise using XmlSerializer + // Serialise using XmlSerializer log.LogProperties.Add(new LogDetailInfo("logdetail", XmlUtils.Serialize(businessObject))); } LogController.Instance.AddLog(log); - } - - #endregion - - #region ILogController Members - + } + public void AddLog(LogInfo logInfo) { LogController.Instance.AddLog(logInfo); @@ -428,24 +424,6 @@ public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) public virtual void UpdateLogType(LogTypeInfo logType) { LogController.Instance.UpdateLogType(logType); - } - - - #endregion - - #region Helper Methods - - public static void AddSettingLog(EventLogType logTypeKey, string idFieldName, int idValue, string settingName, string settingValue, int userId) - { - var log = new LogInfo() { LogUserID = userId, LogTypeKey = logTypeKey.ToString() }; - log.LogProperties.Add(new LogDetailInfo(idFieldName, idValue.ToString())); - log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); - log.LogProperties.Add(new LogDetailInfo("SettingValue", settingValue)); - - LogController.Instance.AddLog(log); - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs index 5b54a37c4f7..009d0e90b48 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs @@ -1,144 +1,136 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data.SqlClient; -using System.Diagnostics; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { - public class ExceptionLogController : LogController - { - #region ExceptionLogType enum - - public enum ExceptionLogType - { - GENERAL_EXCEPTION, - MODULE_LOAD_EXCEPTION, - PAGE_LOAD_EXCEPTION, - SCHEDULER_EXCEPTION, - SECURITY_EXCEPTION, - SEARCH_INDEXER_EXCEPTION, - DATA_EXCEPTION - } + using System; + using System.Data.SqlClient; + using System.Diagnostics; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Exceptions; + + public class ExceptionLogController : LogController + { + public enum ExceptionLogType + { + GENERAL_EXCEPTION, + MODULE_LOAD_EXCEPTION, + PAGE_LOAD_EXCEPTION, + SCHEDULER_EXCEPTION, + SECURITY_EXCEPTION, + SEARCH_INDEXER_EXCEPTION, + DATA_EXCEPTION, + } + + public void AddLog(Exception objException) + { + this.AddLog(objException, ExceptionLogType.GENERAL_EXCEPTION); + } - #endregion - - public void AddLog(Exception objException) - { - AddLog(objException, ExceptionLogType.GENERAL_EXCEPTION); - } - - public void AddLog(BasePortalException objBasePortalException) - { - var log = new LogInfo - { - Exception = Exceptions.Exceptions.GetExceptionInfo(objBasePortalException), - }; - log.Exception.AssemblyVersion = objBasePortalException.AssemblyVersion; - log.Exception.PortalId = objBasePortalException.PortalID; - log.Exception.UserId = objBasePortalException.UserID; - log.Exception.TabId = objBasePortalException.ActiveTabID; - log.Exception.RawUrl = objBasePortalException.RawURL; - log.Exception.Referrer = objBasePortalException.AbsoluteURLReferrer; - log.Exception.UserAgent = objBasePortalException.UserAgent; - if (objBasePortalException.GetType().Name == "ModuleLoadException") - { - AddLog(objBasePortalException, log, ExceptionLogType.MODULE_LOAD_EXCEPTION); - } - else if (objBasePortalException.GetType().Name == "PageLoadException") - { - AddLog(objBasePortalException, log, ExceptionLogType.PAGE_LOAD_EXCEPTION); - } - else if (objBasePortalException.GetType().Name == "SchedulerException") - { - AddLog(objBasePortalException, log, ExceptionLogType.SCHEDULER_EXCEPTION); - } - else if (objBasePortalException.GetType().Name == "SecurityException") - { - AddLog(objBasePortalException, log, ExceptionLogType.SECURITY_EXCEPTION); - } - else if (objBasePortalException.GetType().Name == "SearchException") - { - AddLog(objBasePortalException, log, ExceptionLogType.SEARCH_INDEXER_EXCEPTION); - } - else - { - AddLog(objBasePortalException, log, ExceptionLogType.GENERAL_EXCEPTION); - } - } + public void AddLog(BasePortalException objBasePortalException) + { + var log = new LogInfo + { + Exception = Exceptions.GetExceptionInfo(objBasePortalException), + }; + log.Exception.AssemblyVersion = objBasePortalException.AssemblyVersion; + log.Exception.PortalId = objBasePortalException.PortalID; + log.Exception.UserId = objBasePortalException.UserID; + log.Exception.TabId = objBasePortalException.ActiveTabID; + log.Exception.RawUrl = objBasePortalException.RawURL; + log.Exception.Referrer = objBasePortalException.AbsoluteURLReferrer; + log.Exception.UserAgent = objBasePortalException.UserAgent; + if (objBasePortalException.GetType().Name == "ModuleLoadException") + { + this.AddLog(objBasePortalException, log, ExceptionLogType.MODULE_LOAD_EXCEPTION); + } + else if (objBasePortalException.GetType().Name == "PageLoadException") + { + this.AddLog(objBasePortalException, log, ExceptionLogType.PAGE_LOAD_EXCEPTION); + } + else if (objBasePortalException.GetType().Name == "SchedulerException") + { + this.AddLog(objBasePortalException, log, ExceptionLogType.SCHEDULER_EXCEPTION); + } + else if (objBasePortalException.GetType().Name == "SecurityException") + { + this.AddLog(objBasePortalException, log, ExceptionLogType.SECURITY_EXCEPTION); + } + else if (objBasePortalException.GetType().Name == "SearchException") + { + this.AddLog(objBasePortalException, log, ExceptionLogType.SEARCH_INDEXER_EXCEPTION); + } + else + { + this.AddLog(objBasePortalException, log, ExceptionLogType.GENERAL_EXCEPTION); + } + } - public void AddLog(Exception objException, ExceptionLogType logType) - { - var log = new LogInfo { Exception = new ExceptionInfo(objException) }; - AddLog(objException, log, logType); - } + public void AddLog(Exception objException, ExceptionLogType logType) + { + var log = new LogInfo { Exception = new ExceptionInfo(objException) }; + this.AddLog(objException, log, logType); + } - public void AddLog(Exception objException, LogInfo log, ExceptionLogType logType) - { - log.LogTypeKey = logType.ToString(); - if (logType == ExceptionLogType.SEARCH_INDEXER_EXCEPTION) - { - //Add SearchException Properties - var objSearchException = (SearchException)objException; - log.LogProperties.Add(new LogDetailInfo("ModuleId", objSearchException.SearchItem.ModuleId.ToString())); - log.LogProperties.Add(new LogDetailInfo("SearchItemId", objSearchException.SearchItem.SearchItemId.ToString())); - log.LogProperties.Add(new LogDetailInfo("Title", objSearchException.SearchItem.Title)); - log.LogProperties.Add(new LogDetailInfo("SearchKey", objSearchException.SearchItem.SearchKey)); - log.LogProperties.Add(new LogDetailInfo("GUID", objSearchException.SearchItem.GUID)); - } - else if (logType == ExceptionLogType.MODULE_LOAD_EXCEPTION) - { - //Add ModuleLoadException Properties - var objModuleLoadException = (ModuleLoadException)objException; - log.LogProperties.Add(new LogDetailInfo("ModuleId", objModuleLoadException.ModuleId.ToString())); - log.LogProperties.Add(new LogDetailInfo("ModuleDefId", objModuleLoadException.ModuleDefId.ToString())); - log.LogProperties.Add(new LogDetailInfo("FriendlyName", objModuleLoadException.FriendlyName)); - log.LogProperties.Add(new LogDetailInfo("ModuleControlSource", objModuleLoadException.ModuleControlSource)); - } - else if (logType == ExceptionLogType.SECURITY_EXCEPTION) - { - //Add SecurityException Properties - var objSecurityException = (SecurityException)objException; - log.LogProperties.Add(new LogDetailInfo("Querystring", objSecurityException.Querystring)); - log.LogProperties.Add(new LogDetailInfo("IP", objSecurityException.IP)); - } + public void AddLog(Exception objException, LogInfo log, ExceptionLogType logType) + { + log.LogTypeKey = logType.ToString(); + if (logType == ExceptionLogType.SEARCH_INDEXER_EXCEPTION) + { + // Add SearchException Properties + var objSearchException = (SearchException)objException; + log.LogProperties.Add(new LogDetailInfo("ModuleId", objSearchException.SearchItem.ModuleId.ToString())); + log.LogProperties.Add(new LogDetailInfo("SearchItemId", objSearchException.SearchItem.SearchItemId.ToString())); + log.LogProperties.Add(new LogDetailInfo("Title", objSearchException.SearchItem.Title)); + log.LogProperties.Add(new LogDetailInfo("SearchKey", objSearchException.SearchItem.SearchKey)); + log.LogProperties.Add(new LogDetailInfo("GUID", objSearchException.SearchItem.GUID)); + } + else if (logType == ExceptionLogType.MODULE_LOAD_EXCEPTION) + { + // Add ModuleLoadException Properties + var objModuleLoadException = (ModuleLoadException)objException; + log.LogProperties.Add(new LogDetailInfo("ModuleId", objModuleLoadException.ModuleId.ToString())); + log.LogProperties.Add(new LogDetailInfo("ModuleDefId", objModuleLoadException.ModuleDefId.ToString())); + log.LogProperties.Add(new LogDetailInfo("FriendlyName", objModuleLoadException.FriendlyName)); + log.LogProperties.Add(new LogDetailInfo("ModuleControlSource", objModuleLoadException.ModuleControlSource)); + } + else if (logType == ExceptionLogType.SECURITY_EXCEPTION) + { + // Add SecurityException Properties + var objSecurityException = (SecurityException)objException; + log.LogProperties.Add(new LogDetailInfo("Querystring", objSecurityException.Querystring)); + log.LogProperties.Add(new LogDetailInfo("IP", objSecurityException.IP)); + } - //Add BasePortalException Properties - var objBasePortalException = new BasePortalException(objException.ToString(), objException); - log.LogProperties.Add(new LogDetailInfo("AbsoluteURL", objBasePortalException.AbsoluteURL)); - log.LogProperties.Add(new LogDetailInfo("DefaultDataProvider", objBasePortalException.DefaultDataProvider)); - log.LogProperties.Add(new LogDetailInfo("ExceptionGUID", objBasePortalException.ExceptionGUID)); - log.LogPortalID = objBasePortalException.PortalID; + // Add BasePortalException Properties + var objBasePortalException = new BasePortalException(objException.ToString(), objException); + log.LogProperties.Add(new LogDetailInfo("AbsoluteURL", objBasePortalException.AbsoluteURL)); + log.LogProperties.Add(new LogDetailInfo("DefaultDataProvider", objBasePortalException.DefaultDataProvider)); + log.LogProperties.Add(new LogDetailInfo("ExceptionGUID", objBasePortalException.ExceptionGUID)); + log.LogPortalID = objBasePortalException.PortalID; - var sqlException = objException as SqlException; + var sqlException = objException as SqlException; if (sqlException != null && (uint)sqlException.ErrorCode == 0x80131904 && sqlException.Number == 4060) - { - // This is to avoid stack-overflow exception when a database connection exception occurs - // bercause the logger will try to write to the database and goes in a loop of failures. - Trace.TraceError(log.Serialize()); + { + // This is to avoid stack-overflow exception when a database connection exception occurs + // bercause the logger will try to write to the database and goes in a loop of failures. + Trace.TraceError(log.Serialize()); } else { Instance.AddLog(log); } - //when current user is host user and exception is PageLoadException, try to log the log guid into cookies. - //so that this log can be picked and do more action on it later. - if (logType == ExceptionLogType.PAGE_LOAD_EXCEPTION && HttpContext.Current != null && UserController.Instance.GetCurrentUserInfo().IsSuperUser) - { + // when current user is host user and exception is PageLoadException, try to log the log guid into cookies. + // so that this log can be picked and do more action on it later. + if (logType == ExceptionLogType.PAGE_LOAD_EXCEPTION && HttpContext.Current != null && UserController.Instance.GetCurrentUserInfo().IsSuperUser) + { HttpContext.Current.Response.Cookies.Add( - new HttpCookie("LogGUID", log.LogGUID) { HttpOnly = false, Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }); - } - } - } + new HttpCookie("LogGUID", log.LogGUID) { HttpOnly = false, Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); + } + } + } } diff --git a/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs b/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs index 907016e99ba..6197cae7efb 100644 --- a/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Log.EventLog { + using DotNetNuke.Entities.Portals; + /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. diff --git a/DNN Platform/Library/Services/Log/EventLog/ILogController.cs b/DNN Platform/Library/Services/Log/EventLog/ILogController.cs index a1c6027a7ab..bd1cef58e02 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ILogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ILogController.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Log.EventLog { + using System.Collections; + using System.Collections.Generic; + public interface ILogController { void AddLog(LogInfo logInfo); diff --git a/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs b/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs index 6d5d7fd16cd..b81f07fba02 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Log.EventLog { + using System; + public interface ILogViewer { - void BindData(); - string EventFilter { get; set; } + + void BindData(); } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogController.cs b/DNN Platform/Library/Services/Log/EventLog/LogController.cs index ef9165a074f..d77df9efb0c 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogController.cs @@ -1,44 +1,185 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Web; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data.SqlClient; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + public partial class LogController : ServiceLocator, ILogController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (LogController)); - private const int WriterLockTimeout = 10000; //milliseconds + private const int WriterLockTimeout = 10000; // milliseconds + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LogController)); private static readonly ReaderWriterLockSlim LockLog = new ReaderWriterLockSlim(); - - protected override Func GetFactory() + + public void AddLog(LogInfo logInfo) { - return () => new LogController(); + if (Globals.Status == Globals.UpgradeStatus.Install) + { + Logger.Info(logInfo); + } + else + { + try + { + logInfo.LogCreateDate = DateTime.Now; + logInfo.LogServerName = Globals.ServerName; + if (string.IsNullOrEmpty(logInfo.LogServerName)) + { + logInfo.LogServerName = "NA"; + } + + if (string.IsNullOrEmpty(logInfo.LogUserName)) + { + if (HttpContext.Current != null) + { + if (HttpContext.Current.Request.IsAuthenticated) + { + logInfo.LogUserName = UserController.Instance.GetCurrentUserInfo().Username; + } + } + } + + // Get portal name if name isn't set + if (logInfo.LogPortalID != Null.NullInteger && string.IsNullOrEmpty(logInfo.LogPortalName)) + { + logInfo.LogPortalName = PortalController.Instance.GetPortal(logInfo.LogPortalID).PortalName; + } + + // Check if Log Type exists + if (!this.GetLogTypeInfoDictionary().ContainsKey(logInfo.LogTypeKey)) + { + // Add new Log Type + var logType = new LogTypeInfo() + { + LogTypeKey = logInfo.LogTypeKey, + LogTypeFriendlyName = logInfo.LogTypeKey, + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + LogTypeCSSClass = "GeneralAdminOperation", + LogTypeDescription = string.Empty, + }; + this.AddLogType(logType); + + var logTypeConfigInfo = new LogTypeConfigInfo() + { + LogTypeKey = logInfo.LogTypeKey, + LogTypePortalID = "*", + LoggingIsActive = false, + KeepMostRecent = "-1", + EmailNotificationIsActive = false, + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = string.Empty, + MailToAddress = string.Empty, + }; + this.AddLogTypeConfigInfo(logTypeConfigInfo); + } + + if (LoggingProvider.Instance() != null) + { + try + { + LoggingProvider.Instance().AddLog(logInfo); + } + catch (Exception) + { + if (Globals.Status != Globals.UpgradeStatus.Upgrade) // this may caught exception during upgrade because old logging provider has problem in it. + { + throw; + } + } + } + } + catch (Exception exc) + { + Logger.Error(exc); + + AddLogToFile(logInfo); + } + } } - #region Private Methods + public void AddLogType(string configFile, string fallbackConfigFile) + { + var xmlDoc = new XmlDocument { XmlResolver = null }; + try + { + xmlDoc.Load(configFile); + } + catch (FileNotFoundException exc) + { + Logger.Debug(exc); + xmlDoc.Load(fallbackConfigFile); + } + + var logType = xmlDoc.SelectNodes("/LogConfig/LogTypes/LogType"); + if (logType != null) + { + foreach (XmlNode typeInfo in logType) + { + if (typeInfo.Attributes != null) + { + var objLogTypeInfo = new LogTypeInfo + { + LogTypeKey = typeInfo.Attributes["LogTypeKey"].Value, + LogTypeFriendlyName = typeInfo.Attributes["LogTypeFriendlyName"].Value, + LogTypeDescription = typeInfo.Attributes["LogTypeDescription"].Value, + LogTypeCSSClass = typeInfo.Attributes["LogTypeCSSClass"].Value, + LogTypeOwner = typeInfo.Attributes["LogTypeOwner"].Value, + }; + this.AddLogType(objLogTypeInfo); + } + } + } + + var logTypeConfig = xmlDoc.SelectNodes("/LogConfig/LogTypeConfig"); + if (logTypeConfig != null) + { + foreach (XmlNode typeConfigInfo in logTypeConfig) + { + if (typeConfigInfo.Attributes != null) + { + var logTypeConfigInfo = new LogTypeConfigInfo + { + EmailNotificationIsActive = typeConfigInfo.Attributes["EmailNotificationStatus"].Value == "On", + KeepMostRecent = typeConfigInfo.Attributes["KeepMostRecent"].Value, + LoggingIsActive = typeConfigInfo.Attributes["LoggingStatus"].Value == "On", + LogTypeKey = typeConfigInfo.Attributes["LogTypeKey"].Value, + LogTypePortalID = typeConfigInfo.Attributes["LogTypePortalID"].Value, + MailFromAddress = typeConfigInfo.Attributes["MailFromAddress"].Value, + MailToAddress = typeConfigInfo.Attributes["MailToAddress"].Value, + NotificationThreshold = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThreshold"].Value), + NotificationThresholdTime = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThresholdTime"].Value), + NotificationThresholdTimeType = + (LogTypeConfigInfo.NotificationThresholdTimeTypes)Enum.Parse(typeof(LogTypeConfigInfo.NotificationThresholdTimeTypes), typeConfigInfo.Attributes["NotificationThresholdTimeType"].Value), + }; + this.AddLogTypeConfigInfo(logTypeConfigInfo); + } + } + } + } + protected override Func GetFactory() + { + return () => new LogController(); + } + private static void AddLogToFile(LogInfo logInfo) { try @@ -46,11 +187,11 @@ private static void AddLogToFile(LogInfo logInfo) var f = Globals.HostMapPath + "\\Logs\\LogFailures.xml.resources"; WriteLog(f, logInfo.Serialize()); } + // ReSharper disable EmptyGeneralCatchClause catch (Exception exc) // ReSharper restore EmptyGeneralCatchClause { Logger.Error(exc); - } } @@ -81,6 +222,7 @@ private static void WriteToStreamWriter(FileStream fs, string message) { message = "" + message; } + sw.WriteLine(message + ""); sw.Flush(); } @@ -89,7 +231,11 @@ private static void WriteToStreamWriter(FileStream fs, string message) private static void WriteLog(string filePath, string message) { FileStream fs = null; - if (!LockLog.TryEnterWriteLock(WriterLockTimeout)) return; + if (!LockLog.TryEnterWriteLock(WriterLockTimeout)) + { + return; + } + try { var intAttempts = 0; @@ -106,6 +252,7 @@ private static void WriteLog(string filePath, string message) Thread.Sleep(1); } } + if (fs == null) { if (HttpContext.Current != null) @@ -149,162 +296,10 @@ private static void WriteLog(string filePath, string message) { fs.Close(); } + LockLog.ExitWriteLock(); } - } - - #endregion - - #region Public Methods - - public void AddLog(LogInfo logInfo) - { - if (Globals.Status == Globals.UpgradeStatus.Install) - { - Logger.Info(logInfo); - } - else - { - try - { - logInfo.LogCreateDate = DateTime.Now; - logInfo.LogServerName = Globals.ServerName; - if (string.IsNullOrEmpty(logInfo.LogServerName)) - { - logInfo.LogServerName = "NA"; - } - if (String.IsNullOrEmpty(logInfo.LogUserName)) - { - if (HttpContext.Current != null) - { - if (HttpContext.Current.Request.IsAuthenticated) - { - logInfo.LogUserName = UserController.Instance.GetCurrentUserInfo().Username; - } - } - } - - //Get portal name if name isn't set - if (logInfo.LogPortalID != Null.NullInteger && String.IsNullOrEmpty(logInfo.LogPortalName)) - { - logInfo.LogPortalName = PortalController.Instance.GetPortal(logInfo.LogPortalID).PortalName; - } - - //Check if Log Type exists - if (!GetLogTypeInfoDictionary().ContainsKey(logInfo.LogTypeKey)) - { - //Add new Log Type - var logType = new LogTypeInfo() - { - LogTypeKey = logInfo.LogTypeKey, - LogTypeFriendlyName = logInfo.LogTypeKey, - LogTypeOwner = "DotNetNuke.Logging.EventLogType", - LogTypeCSSClass = "GeneralAdminOperation", - LogTypeDescription = string.Empty - }; - AddLogType(logType); - - var logTypeConfigInfo = new LogTypeConfigInfo() - { - LogTypeKey = logInfo.LogTypeKey, - LogTypePortalID = "*", - LoggingIsActive = false, - KeepMostRecent = "-1", - EmailNotificationIsActive = false, - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = String.Empty, - MailToAddress = String.Empty - }; - AddLogTypeConfigInfo(logTypeConfigInfo); - } - - if (LoggingProvider.Instance() != null) - { - try - { - LoggingProvider.Instance().AddLog(logInfo); - } - catch (Exception) - { - if (Globals.Status != Globals.UpgradeStatus.Upgrade) //this may caught exception during upgrade because old logging provider has problem in it. - { - throw; - } - } - - } - } - catch (Exception exc) - { - Logger.Error(exc); - - AddLogToFile(logInfo); - } - } - } - - public void AddLogType(string configFile, string fallbackConfigFile) - { - var xmlDoc = new XmlDocument { XmlResolver = null }; - try - { - xmlDoc.Load(configFile); - } - catch (FileNotFoundException exc) - { - Logger.Debug(exc); - xmlDoc.Load(fallbackConfigFile); - } - - var logType = xmlDoc.SelectNodes("/LogConfig/LogTypes/LogType"); - if (logType != null) - { - foreach (XmlNode typeInfo in logType) - { - if (typeInfo.Attributes != null) - { - var objLogTypeInfo = new LogTypeInfo - { - LogTypeKey = typeInfo.Attributes["LogTypeKey"].Value, - LogTypeFriendlyName = typeInfo.Attributes["LogTypeFriendlyName"].Value, - LogTypeDescription = typeInfo.Attributes["LogTypeDescription"].Value, - LogTypeCSSClass = typeInfo.Attributes["LogTypeCSSClass"].Value, - LogTypeOwner = typeInfo.Attributes["LogTypeOwner"].Value - }; - AddLogType(objLogTypeInfo); - } - } - } - - var logTypeConfig = xmlDoc.SelectNodes("/LogConfig/LogTypeConfig"); - if (logTypeConfig != null) - { - foreach (XmlNode typeConfigInfo in logTypeConfig) - { - if (typeConfigInfo.Attributes != null) - { - var logTypeConfigInfo = new LogTypeConfigInfo - { - EmailNotificationIsActive = typeConfigInfo.Attributes["EmailNotificationStatus"].Value == "On", - KeepMostRecent = typeConfigInfo.Attributes["KeepMostRecent"].Value, - LoggingIsActive = typeConfigInfo.Attributes["LoggingStatus"].Value == "On", - LogTypeKey = typeConfigInfo.Attributes["LogTypeKey"].Value, - LogTypePortalID = typeConfigInfo.Attributes["LogTypePortalID"].Value, - MailFromAddress = typeConfigInfo.Attributes["MailFromAddress"].Value, - MailToAddress = typeConfigInfo.Attributes["MailToAddress"].Value, - NotificationThreshold = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThreshold"].Value), - NotificationThresholdTime = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThresholdTime"].Value), - NotificationThresholdTimeType = - (LogTypeConfigInfo.NotificationThresholdTimeTypes) - Enum.Parse(typeof(LogTypeConfigInfo.NotificationThresholdTimeTypes), typeConfigInfo.Attributes["NotificationThresholdTimeType"].Value) - }; - AddLogTypeConfigInfo(logTypeConfigInfo); - } - } - } - } + } public void AddLogType(LogTypeInfo logType) { @@ -313,18 +308,19 @@ public void AddLogType(LogTypeInfo logType) public void AddLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) { - LoggingProvider.Instance().AddLogTypeConfigInfo(logTypeConfig.ID, - logTypeConfig.LoggingIsActive, - logTypeConfig.LogTypeKey, - logTypeConfig.LogTypePortalID, - logTypeConfig.KeepMostRecent, - logTypeConfig.LogFileName, - logTypeConfig.EmailNotificationIsActive, - Convert.ToString(logTypeConfig.NotificationThreshold), - Convert.ToString(logTypeConfig.NotificationThresholdTime), - Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), - logTypeConfig.MailFromAddress, - logTypeConfig.MailToAddress); + LoggingProvider.Instance().AddLogTypeConfigInfo( + logTypeConfig.ID, + logTypeConfig.LoggingIsActive, + logTypeConfig.LogTypeKey, + logTypeConfig.LogTypePortalID, + logTypeConfig.KeepMostRecent, + logTypeConfig.LogFileName, + logTypeConfig.EmailNotificationIsActive, + Convert.ToString(logTypeConfig.NotificationThreshold), + Convert.ToString(logTypeConfig.NotificationThresholdTime), + Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), + logTypeConfig.MailFromAddress, + logTypeConfig.MailToAddress); } public void ClearLog() @@ -379,25 +375,24 @@ public void PurgeLogBuffer() public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) { - LoggingProvider.Instance().UpdateLogTypeConfigInfo(logTypeConfig.ID, - logTypeConfig.LoggingIsActive, - logTypeConfig.LogTypeKey, - logTypeConfig.LogTypePortalID, - logTypeConfig.KeepMostRecent, - logTypeConfig.LogFileName, - logTypeConfig.EmailNotificationIsActive, - Convert.ToString(logTypeConfig.NotificationThreshold), - Convert.ToString(logTypeConfig.NotificationThresholdTime), - Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), - logTypeConfig.MailFromAddress, - logTypeConfig.MailToAddress); + LoggingProvider.Instance().UpdateLogTypeConfigInfo( + logTypeConfig.ID, + logTypeConfig.LoggingIsActive, + logTypeConfig.LogTypeKey, + logTypeConfig.LogTypePortalID, + logTypeConfig.KeepMostRecent, + logTypeConfig.LogFileName, + logTypeConfig.EmailNotificationIsActive, + Convert.ToString(logTypeConfig.NotificationThreshold), + Convert.ToString(logTypeConfig.NotificationThresholdTime), + Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), + logTypeConfig.MailFromAddress, + logTypeConfig.MailToAddress); } public virtual void UpdateLogType(LogTypeInfo logType) { LoggingProvider.Instance().UpdateLogType(logType.LogTypeKey, logType.LogTypeFriendlyName, logType.LogTypeDescription, logType.LogTypeCSSClass, logType.LogTypeOwner); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs index 9c73e996bff..35c2d347a7f 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs @@ -1,42 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.Text; + using System.Xml; + [Serializable] public class LogDetailInfo { private string _PropertyName; private string _PropertyValue; - public LogDetailInfo() : this("", "") + public LogDetailInfo() + : this(string.Empty, string.Empty) { } public LogDetailInfo(string name, string value) { - _PropertyName = name; - _PropertyValue = value; + this._PropertyName = name; + this._PropertyValue = value; } public string PropertyName { get { - return _PropertyName; + return this._PropertyName; } + set { - _PropertyName = value; + this._PropertyName = value; } } @@ -44,23 +41,24 @@ public string PropertyValue { get { - return _PropertyValue; + return this._PropertyValue; } + set { - _PropertyValue = value; + this._PropertyValue = value; } } public void ReadXml(XmlReader reader) { reader.ReadStartElement("PropertyName"); - PropertyName = reader.ReadString(); + this.PropertyName = reader.ReadString(); reader.ReadEndElement(); if (!reader.IsEmptyElement) { reader.ReadStartElement("PropertyValue"); - PropertyValue = reader.ReadString(); + this.PropertyValue = reader.ReadString(); reader.ReadEndElement(); } else @@ -73,9 +71,9 @@ public override string ToString() { var sb = new StringBuilder(); sb.Append("

    "); - sb.Append(PropertyName); + sb.Append(this.PropertyName); sb.Append(": "); - sb.Append(PropertyValue); + sb.Append(this.PropertyValue); sb.Append("

    "); return sb.ToString(); } @@ -83,8 +81,8 @@ public override string ToString() public void WriteXml(XmlWriter writer) { writer.WriteStartElement("LogProperty"); - writer.WriteElementString("PropertyName", PropertyName); - writer.WriteElementString("PropertyValue", PropertyValue); + writer.WriteElementString("PropertyName", this.PropertyName); + writer.WriteElementString("PropertyValue", this.PropertyValue); writer.WriteEndElement(); } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs index d205509caf7..8e7a814232f 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs @@ -1,46 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text; -using System.Xml; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.IO; + using System.Text; + using System.Xml; + + using DotNetNuke.Services.Exceptions; + [Serializable] public class LogInfo - { - #region Constructors - + { public LogInfo() { - LogGUID = Guid.NewGuid().ToString(); - BypassBuffering = false; - LogProperties = new LogProperties(); - LogPortalID = -1; - LogPortalName = ""; - LogUserID = -1; - LogEventID = -1; - LogUserName = ""; - Exception = new ExceptionInfo(); + this.LogGUID = Guid.NewGuid().ToString(); + this.BypassBuffering = false; + this.LogProperties = new LogProperties(); + this.LogPortalID = -1; + this.LogPortalName = string.Empty; + this.LogUserID = -1; + this.LogEventID = -1; + this.LogUserName = string.Empty; + this.Exception = new ExceptionInfo(); } - public LogInfo(string content) : this() + public LogInfo(string content) + : this() { - Deserialize(content); - } - - #endregion - - #region "Properties" - + this.Deserialize(content); + } + public string LogGUID { get; set; } public string LogFileID { get; set; } @@ -69,12 +60,29 @@ public LogInfo(string content) : this() public string LogConfigID { get; set; } - public ExceptionInfo Exception { get; set; } - - #endregion - - #region Public Methods + public ExceptionInfo Exception { get; set; } + public static bool IsSystemType(string PropName) + { + switch (PropName) + { + case "LogGUID": + case "LogFileID": + case "LogTypeKey": + case "LogCreateDate": + case "LogCreateDateNum": + case "LogPortalID": + case "LogPortalName": + case "LogUserID": + case "LogUserName": + case "BypassBuffering": + case "LogServerName": + return true; + } + + return false; + } + public void AddProperty(string PropertyName, string PropertyValue) { try @@ -83,22 +91,25 @@ public void AddProperty(string PropertyName, string PropertyValue) { PropertyValue = string.Empty; } + if (PropertyName.Length > 50) { PropertyName = PropertyName.Substring(0, 50); } + if (PropertyValue.Length > 500) { PropertyValue = "(TRUNCATED TO 500 CHARS): " + PropertyValue.Substring(0, 500); } + var objLogDetailInfo = new LogDetailInfo(); objLogDetailInfo.PropertyName = PropertyName; objLogDetailInfo.PropertyValue = PropertyValue; - LogProperties.Add(objLogDetailInfo); + this.LogProperties.Add(objLogDetailInfo); } catch (Exception exc) { - Exceptions.Exceptions.LogException(exc); + Exceptions.LogException(exc); } } @@ -108,8 +119,9 @@ public void Deserialize(string content) { if (reader.Read()) { - ReadXml(reader); + this.ReadXml(reader); } + reader.Close(); } } @@ -123,83 +135,64 @@ public void ReadXml(XmlReader reader) switch (reader.Name) { case "LogGUID": - LogGUID = reader.ReadContentAsString(); + this.LogGUID = reader.ReadContentAsString(); break; case "LogFileID": - LogFileID = reader.ReadContentAsString(); + this.LogFileID = reader.ReadContentAsString(); break; case "LogTypeKey": - LogTypeKey = reader.ReadContentAsString(); + this.LogTypeKey = reader.ReadContentAsString(); break; case "LogUserID": - LogUserID = reader.ReadContentAsInt(); + this.LogUserID = reader.ReadContentAsInt(); break; case "LogEventID": - LogEventID = reader.ReadContentAsInt(); + this.LogEventID = reader.ReadContentAsInt(); break; case "LogUserName": - LogUserName = reader.ReadContentAsString(); + this.LogUserName = reader.ReadContentAsString(); break; case "LogPortalID": - LogPortalID = reader.ReadContentAsInt(); + this.LogPortalID = reader.ReadContentAsInt(); break; case "LogPortalName": - LogPortalName = reader.ReadContentAsString(); + this.LogPortalName = reader.ReadContentAsString(); break; case "LogCreateDate": - LogCreateDate = DateTime.Parse(reader.ReadContentAsString()); + this.LogCreateDate = DateTime.Parse(reader.ReadContentAsString()); break; case "LogCreateDateNum": - LogCreateDateNum = reader.ReadContentAsLong(); + this.LogCreateDateNum = reader.ReadContentAsLong(); break; case "BypassBuffering": - BypassBuffering = bool.Parse(reader.ReadContentAsString()); + this.BypassBuffering = bool.Parse(reader.ReadContentAsString()); break; case "LogServerName": - LogServerName = reader.ReadContentAsString(); + this.LogServerName = reader.ReadContentAsString(); + break; + case "LogConfigID": + this.LogConfigID = reader.ReadContentAsString(); break; - case "LogConfigID": - LogConfigID = reader.ReadContentAsString(); - break; - } + } } } - - //Check for LogProperties child node + + // Check for LogProperties child node reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "LogProperties") { reader.ReadStartElement("LogProperties"); - if (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !String.IsNullOrEmpty(reader.LocalName)) + if (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !string.IsNullOrEmpty(reader.LocalName)) { - LogProperties.ReadXml(reader); + this.LogProperties.ReadXml(reader); } - } - //Check for Exception child node - if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Exception") - { - Exception.ReadXml(reader); - } - } - - public static bool IsSystemType(string PropName) - { - switch (PropName) + } + + // Check for Exception child node + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Exception") { - case "LogGUID": - case "LogFileID": - case "LogTypeKey": - case "LogCreateDate": - case "LogCreateDateNum": - case "LogPortalID": - case "LogPortalName": - case "LogUserID": - case "LogUserName": - case "BypassBuffering": - case "LogServerName": - return true; + this.Exception.ReadXml(reader); } - return false; } public string Serialize() @@ -210,7 +203,7 @@ public string Serialize() var sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, settings)) { - WriteXml(writer); + this.WriteXml(writer); writer.Close(); return sb.ToString(); } @@ -219,47 +212,47 @@ public string Serialize() public override string ToString() { var str = new StringBuilder(); - str.Append("

    LogGUID:" + LogGUID + "

    "); - str.Append("

    LogType:" + LogTypeKey + "

    "); - str.Append("

    UserID:" + LogUserID + "

    "); - str.Append("

    EventID:" + LogEventID + "

    "); - str.Append("

    Username:" + LogUserName + "

    "); - str.Append("

    PortalID:" + LogPortalID + "

    "); - str.Append("

    PortalName:" + LogPortalName + "

    "); - str.Append("

    CreateDate:" + LogCreateDate + "

    "); - str.Append("

    ServerName:" + LogServerName + "

    "); - str.Append(LogProperties.ToString()); - if (!string.IsNullOrEmpty(Exception.ExceptionHash)) - { - str.Append(Exception.ToString()); - } + str.Append("

    LogGUID:" + this.LogGUID + "

    "); + str.Append("

    LogType:" + this.LogTypeKey + "

    "); + str.Append("

    UserID:" + this.LogUserID + "

    "); + str.Append("

    EventID:" + this.LogEventID + "

    "); + str.Append("

    Username:" + this.LogUserName + "

    "); + str.Append("

    PortalID:" + this.LogPortalID + "

    "); + str.Append("

    PortalName:" + this.LogPortalName + "

    "); + str.Append("

    CreateDate:" + this.LogCreateDate + "

    "); + str.Append("

    ServerName:" + this.LogServerName + "

    "); + str.Append(this.LogProperties.ToString()); + if (!string.IsNullOrEmpty(this.Exception.ExceptionHash)) + { + str.Append(this.Exception.ToString()); + } + return str.ToString(); } public void WriteXml(XmlWriter writer) { writer.WriteStartElement("log"); - writer.WriteAttributeString("LogGUID", LogGUID); - writer.WriteAttributeString("LogFileID", LogFileID); - writer.WriteAttributeString("LogTypeKey", LogTypeKey); - writer.WriteAttributeString("LogUserID", LogUserID.ToString()); - writer.WriteAttributeString("LogEventID", LogEventID.ToString()); - writer.WriteAttributeString("LogUserName", LogUserName); - writer.WriteAttributeString("LogPortalID", LogPortalID.ToString()); - writer.WriteAttributeString("LogPortalName", LogPortalName); - writer.WriteAttributeString("LogCreateDate", LogCreateDate.ToString()); - writer.WriteAttributeString("LogCreateDateNum", LogCreateDateNum.ToString()); - writer.WriteAttributeString("BypassBuffering", BypassBuffering.ToString()); - writer.WriteAttributeString("LogServerName", LogServerName); - writer.WriteAttributeString("LogConfigID", LogConfigID); - LogProperties.WriteXml(writer); - if (!string.IsNullOrEmpty(Exception.ExceptionHash)) - { - Exception.WriteXml(writer); - } + writer.WriteAttributeString("LogGUID", this.LogGUID); + writer.WriteAttributeString("LogFileID", this.LogFileID); + writer.WriteAttributeString("LogTypeKey", this.LogTypeKey); + writer.WriteAttributeString("LogUserID", this.LogUserID.ToString()); + writer.WriteAttributeString("LogEventID", this.LogEventID.ToString()); + writer.WriteAttributeString("LogUserName", this.LogUserName); + writer.WriteAttributeString("LogPortalID", this.LogPortalID.ToString()); + writer.WriteAttributeString("LogPortalName", this.LogPortalName); + writer.WriteAttributeString("LogCreateDate", this.LogCreateDate.ToString()); + writer.WriteAttributeString("LogCreateDateNum", this.LogCreateDateNum.ToString()); + writer.WriteAttributeString("BypassBuffering", this.BypassBuffering.ToString()); + writer.WriteAttributeString("LogServerName", this.LogServerName); + writer.WriteAttributeString("LogConfigID", this.LogConfigID); + this.LogProperties.WriteXml(writer); + if (!string.IsNullOrEmpty(this.Exception.ExceptionHash)) + { + this.Exception.WriteXml(writer); + } + writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs b/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs index bb7477cfd0a..b5fdf567ba2 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs @@ -1,51 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Text; -using System.Xml; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.Collections; + using System.IO; + using System.Text; + using System.Xml; + + using DotNetNuke.Common.Utilities; + public class LogProperties : ArrayList - { - #region "Public Properties" - + { public string Summary { get { - string summary = HtmlUtils.Clean(ToString(), true); + string summary = HtmlUtils.Clean(this.ToString(), true); if (summary.Length > 75) { summary = summary.Substring(0, 75); } + return summary; } - } - - #endregion - - #region "Public Methods" - + } + public void Deserialize(string content) { using (XmlReader reader = XmlReader.Create(new StringReader(content))) { reader.ReadStartElement("LogProperties"); - if (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !String.IsNullOrEmpty(reader.LocalName)) + if (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !string.IsNullOrEmpty(reader.LocalName)) { - ReadXml(reader); + this.ReadXml(reader); } + reader.Close(); } } @@ -56,16 +47,16 @@ public void ReadXml(XmlReader reader) { reader.ReadStartElement("LogProperty"); - //Create new LogDetailInfo object + // Create new LogDetailInfo object var logDetail = new LogDetailInfo(); - //Load it from the Xml + // Load it from the Xml logDetail.ReadXml(reader); - //Add to the collection - Add(logDetail); - - } while (reader.ReadToNextSibling("LogProperty")); + // Add to the collection + this.Add(logDetail); + } + while (reader.ReadToNextSibling("LogProperty")); } public string Serialize() @@ -76,7 +67,7 @@ public string Serialize() var sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, settings)) { - WriteXml(writer); + this.WriteXml(writer); writer.Close(); return sb.ToString(); } @@ -89,6 +80,7 @@ public override string ToString() { sb.Append(logDetail.ToString()); } + return sb.ToString(); } @@ -99,9 +91,8 @@ public void WriteXml(XmlWriter writer) { logDetail.WriteXml(writer); } + writer.WriteEndElement(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogQueueItem.cs b/DNN Platform/Library/Services/Log/EventLog/LogQueueItem.cs index 2a69a57cae2..ba88dff409f 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogQueueItem.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogQueueItem.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Log.EventLog { public class LogQueueItem diff --git a/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs index 9e420738879..0ef91402ed4 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs @@ -1,50 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Common; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + [Serializable] public class LogTypeConfigInfo : LogTypeInfo - { - #region NotificationThresholdTimeTypes enum - + { + private string _mailFromAddress; + public enum NotificationThresholdTimeTypes { None = 0, Seconds = 1, Minutes = 2, Hours = 3, - Days = 4 - } - - #endregion - - private string _mailFromAddress; + Days = 4, + } public DateTime StartDateTime { get { - switch (NotificationThresholdTimeType) + switch (this.NotificationThresholdTimeType) { case NotificationThresholdTimeTypes.Seconds: - return DateTime.Now.AddSeconds(NotificationThresholdTime*-1); + return DateTime.Now.AddSeconds(this.NotificationThresholdTime * -1); case NotificationThresholdTimeTypes.Minutes: - return DateTime.Now.AddMinutes(NotificationThresholdTime*-1); + return DateTime.Now.AddMinutes(this.NotificationThresholdTime * -1); case NotificationThresholdTimeTypes.Hours: - return DateTime.Now.AddHours(NotificationThresholdTime*-1); + return DateTime.Now.AddHours(this.NotificationThresholdTime * -1); case NotificationThresholdTimeTypes.Days: - return DateTime.Now.AddDays(NotificationThresholdTime*-1); + return DateTime.Now.AddDays(this.NotificationThresholdTime * -1); default: return Null.NullDate; } @@ -55,16 +46,18 @@ public DateTime StartDateTime public string MailFromAddress { - get { + get + { var portalSettings = Globals.GetPortalSettings(); - return - string.IsNullOrWhiteSpace(_mailFromAddress) - ? (portalSettings == null ? string.Empty : portalSettings.Email) - : _mailFromAddress; } - set { _mailFromAddress = value; } + return + string.IsNullOrWhiteSpace(this._mailFromAddress) + ? (portalSettings == null ? string.Empty : portalSettings.Email) + : this._mailFromAddress; + } + + set { this._mailFromAddress = value; } } - - + public string MailToAddress { get; set; } public int NotificationThreshold { get; set; } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogTypeInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogTypeInfo.cs index e60ba8324c7..5fb1102ab07 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogTypeInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogTypeInfo.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + [Serializable] public class LogTypeInfo { diff --git a/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs b/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs index 4fdbc6ab7da..23fbcff4952 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs @@ -1,45 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; - -using DotNetNuke.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + + using DotNetNuke.ComponentModel; + public abstract class LoggingProvider - { - #region ReturnType enum - + { public enum ReturnType { LogInfoObjects, - XML - } - - #endregion - - #region "Shared/Static Methods" - - //return the provider - public static LoggingProvider Instance() + XML, + } + + // return the provider + public static LoggingProvider Instance() { return ComponentFactory.GetComponent(); - } - - #endregion - - #region "Abstract Methods" - + } + public abstract void AddLog(LogInfo logInfo); public abstract void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); @@ -83,8 +68,6 @@ public virtual List GetLogs(int portalID, string logType, int pageSize, public abstract void UpdateLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); - public abstract void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); - - #endregion + public abstract void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); } } diff --git a/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs b/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs index bd0902456c9..aafc9dea15a 100644 --- a/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs +++ b/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs @@ -1,41 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + + using DotNetNuke.Services.Scheduling; + public class PurgeLogBuffer : SchedulerClient { public PurgeLogBuffer(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } public override void DoWork() { try { - //notification that the event is progressing - Progressing(); //OPTIONAL + // notification that the event is progressing + this.Progressing(); // OPTIONAL LoggingProvider.Instance().PurgeLogBuffer(); - ScheduleHistoryItem.Succeeded = true; //REQUIRED - ScheduleHistoryItem.AddLogNote("Purged log entries successfully"); //OPTIONAL + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("Purged log entries successfully"); // OPTIONAL } - catch (Exception exc) //REQUIRED + catch (Exception exc) // REQUIRED { - ScheduleHistoryItem.Succeeded = false; //REQUIRED - ScheduleHistoryItem.AddLogNote("EXCEPTION: " + exc); //OPTIONAL - Errored(ref exc); //REQUIRED - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("EXCEPTION: " + exc); // OPTIONAL + this.Errored(ref exc); // REQUIRED + + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs b/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs index cff836e01e8..8af03e24945 100644 --- a/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs +++ b/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs @@ -1,41 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System; + + using DotNetNuke.Services.Scheduling; + public class SendLogNotifications : SchedulerClient { public SendLogNotifications(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } public override void DoWork() { try { - //notification that the event is progressing - Progressing(); //OPTIONAL + // notification that the event is progressing + this.Progressing(); // OPTIONAL LoggingProvider.Instance().SendLogNotifications(); - ScheduleHistoryItem.Succeeded = true; //REQUIRED - ScheduleHistoryItem.AddLogNote("Sent log notifications successfully"); //OPTIONAL + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("Sent log notifications successfully"); // OPTIONAL } - catch (Exception exc) //REQUIRED + catch (Exception exc) // REQUIRED { - ScheduleHistoryItem.Succeeded = false; //REQUIRED - ScheduleHistoryItem.AddLogNote("EXCEPTION: " + exc); //OPTIONAL - Errored(ref exc); //REQUIRED - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("EXCEPTION: " + exc); // OPTIONAL + this.Errored(ref exc); // REQUIRED + + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } } diff --git a/DNN Platform/Library/Services/Mail/Mail.cs b/DNN Platform/Library/Services/Mail/Mail.cs index f722c695825..be93f07def0 100644 --- a/DNN Platform/Library/Services/Mail/Mail.cs +++ b/DNN Platform/Library/Services/Mail/Mail.cs @@ -1,37 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Mail; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Tokens; - -using Localize = DotNetNuke.Services.Localization.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mail { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Mail; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Tokens; + + using Localize = DotNetNuke.Services.Localization.Localization; + public class Mail - { - #region Private Methods - + { private static readonly Regex SmtpServerRegex = new Regex("^[^:]+(:[0-9]{1,5})?$", RegexOptions.Compiled); + + public static string ConvertToText(string sHTML) + { + var formattedHtml = HtmlUtils.FormatText(sHTML, true); + var styleLessHtml = HtmlUtils.RemoveInlineStyle(formattedHtml); + return HtmlUtils.StripTags(styleLessHtml, true); + } + + public static bool IsValidEmailAddress(string Email, int portalid) + { + string pattern = Null.NullString; + + // During install Wizard we may not have a valid PortalID + if (portalid != Null.NullInteger) + { + pattern = Convert.ToString(UserController.GetUserSettings(portalid)["Security_EmailValidation"]); + } + + pattern = string.IsNullOrEmpty(pattern) ? Globals.glbEmailRegEx : pattern; + return Regex.Match(Email, pattern).Success; + } private static string SendMailInternal(MailMessage mailMessage, string subject, string body, MailPriority priority, MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable attachments, @@ -40,15 +54,14 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, string retValue = string.Empty; mailMessage.Priority = (System.Net.Mail.MailPriority)priority; - mailMessage.IsBodyHtml = (bodyFormat == MailFormat.Html); - - + mailMessage.IsBodyHtml = bodyFormat == MailFormat.Html; + // Only modify senderAdress if smtpAuthentication is enabled - // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM. + // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM. if (smtpAuthentication == "1" || smtpAuthentication == "2") { - //if the senderAddress is the email address of the Host then switch it smtpUsername if different - //if display name of senderAddress is empty, then use Host.HostTitle for it + // if the senderAddress is the email address of the Host then switch it smtpUsername if different + // if display name of senderAddress is empty, then use Host.HostTitle for it if (mailMessage.Sender != null) { var senderAddress = mailMessage.Sender.Address; @@ -60,11 +73,13 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, senderAddress = smtpUsername; needUpdateSender = true; } + if (string.IsNullOrEmpty(senderDisplayName)) { senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle; needUpdateSender = true; } + if (needUpdateSender) { mailMessage.Sender = new MailAddress(senderAddress, senderDisplayName); @@ -76,19 +91,19 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, } } - //attachments + // attachments foreach (var attachment in attachments) { mailMessage.Attachments.Add(attachment); } - //message + // message mailMessage.SubjectEncoding = bodyEncoding; mailMessage.Subject = HtmlUtils.StripWhiteSpace(subject, true); mailMessage.BodyEncoding = bodyEncoding; - //added support for multipart html messages - //add text part as alternate view + // added support for multipart html messages + // add text part as alternate view var PlainView = AlternateView.CreateAlternateViewFromString(ConvertToText(body), null, "text/plain"); mailMessage.AlternateViews.Add(PlainView); if (mailMessage.IsBodyHtml) @@ -102,7 +117,7 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, { try { - //to workaround problem in 4.0 need to specify host name + // to workaround problem in 4.0 need to specify host name using (var smtpClient = new SmtpClient()) { var smtpHostParts = smtpServer.Split(':'); @@ -118,27 +133,29 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, smtpClient.Port = port; } + // else the port defaults to 25 by .NET when not set - smtpClient.ServicePoint.MaxIdleTime = Host.SMTPMaxIdleTime; smtpClient.ServicePoint.ConnectionLimit = Host.SMTPConnectionLimit; switch (smtpAuthentication) { case "": - case "0": //anonymous + case "0": // anonymous break; - case "1": //basic - if (!String.IsNullOrEmpty(smtpUsername) && !String.IsNullOrEmpty(smtpPassword)) + case "1": // basic + if (!string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(smtpPassword)) { smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new NetworkCredential(smtpUsername, smtpPassword); } + break; - case "2": //NTLM + case "2": // NTLM smtpClient.UseDefaultCredentials = true; break; } + smtpClient.EnableSsl = smtpEnableSSL; smtpClient.Send(mailMessage); smtpClient.Dispose(); @@ -156,7 +173,7 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, retValue = Localize.GetString("SMTPConfigurationProblem") + " "; } - //mail configuration problem + // mail configuration problem if (exc.InnerException != null) { retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message); @@ -179,30 +196,7 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, } return retValue; - } - - #endregion - - #region Public Methods - - public static string ConvertToText(string sHTML) - { - var formattedHtml = HtmlUtils.FormatText(sHTML, true); - var styleLessHtml = HtmlUtils.RemoveInlineStyle(formattedHtml); - return HtmlUtils.StripTags(styleLessHtml, true); - } - - public static bool IsValidEmailAddress(string Email, int portalid) - { - string pattern = Null.NullString; - //During install Wizard we may not have a valid PortalID - if (portalid != Null.NullInteger) - { - pattern = Convert.ToString(UserController.GetUserSettings(portalid)["Security_EmailValidation"]); - } - pattern = string.IsNullOrEmpty(pattern) ? Globals.glbEmailRegEx : pattern; - return Regex.Match(Email, pattern).Success; - } + } public static void SendEmail(string fromAddress, string toAddress, string subject, string body) { @@ -228,7 +222,7 @@ public static void SendEmail(string fromAddress, string senderAddress, string to public static string SendEmail(string fromAddress, string senderAddress, string toAddress, string subject, string body, List attachments) { - if ((string.IsNullOrWhiteSpace(Host.SMTPServer))) + if (string.IsNullOrWhiteSpace(Host.SMTPServer)) { return "SMTP Server not configured"; } @@ -247,9 +241,9 @@ public static string SendEmail(string fromAddress, string senderAddress, string /// /// Send an email notification /// - /// The user to whom the message is being sent - /// The type of message being sent - /// Portal Settings + /// The user to whom the message is being sent. + /// The type of message being sent. + /// Portal Settings. /// /// /// ----------------------------------------------------------------------------- @@ -262,16 +256,16 @@ public static string SendMail(UserInfo user, MessageType msgType, PortalSettings /// /// Send an email notification /// - /// The PortalId of the user to whom the message is being sent - /// The UserId of the user to whom the message is being sent - /// The type of message being sent - /// Portal Settings + /// The PortalId of the user to whom the message is being sent. + /// The UserId of the user to whom the message is being sent. + /// The type of message being sent. + /// Portal Settings. /// /// /// ----------------------------------------------------------------------------- public static string SendMail(int portalId, int userId, MessageType msgType, PortalSettings settings) { - //Send Notification to User + // Send Notification to User var user = UserController.Instance.GetUserById(portalId, userId); int toUser = user.UserID; string locale = user.Profile.PreferredLocale; @@ -308,10 +302,11 @@ public static string SendMail(int portalId, int userId, MessageType msgType, Por custom = new ArrayList { HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Server.UrlEncode(user.Username)), - HttpContext.Current.Server.UrlEncode(user.GetProperty("verificationcode", String.Empty, null, - user, Scope.SystemMessages, ref propertyNotFound)) + HttpContext.Current.Server.UrlEncode(user.GetProperty("verificationcode", string.Empty, null, + user, Scope.SystemMessages, ref propertyNotFound)), }; } + break; case MessageType.PasswordReminder: subject = "EMAIL_PASSWORD_REMINDER_SUBJECT"; @@ -343,11 +338,11 @@ public static string SendMail(int portalId, int userId, MessageType msgType, Por break; } - subject = Localize.GetSystemMessage(locale, settings, subject, user, Localize.GlobalResourceFile, custom, "", settings.AdministratorId); - body = Localize.GetSystemMessage(locale, settings, body, user, Localize.GlobalResourceFile, custom, "", settings.AdministratorId); + subject = Localize.GetSystemMessage(locale, settings, subject, user, Localize.GlobalResourceFile, custom, string.Empty, settings.AdministratorId); + body = Localize.GetSystemMessage(locale, settings, body, user, Localize.GlobalResourceFile, custom, string.Empty, settings.AdministratorId); var fromUser = (UserController.GetUserByEmail(settings.PortalId, settings.Email) != null) ? - String.Format("{0} < {1} >", UserController.GetUserByEmail(settings.PortalId, settings.Email).DisplayName, settings.Email) : settings.Email; + string.Format("{0} < {1} >", UserController.GetUserByEmail(settings.PortalId, settings.Email).DisplayName, settings.Email) : settings.Email; SendEmail(fromUser, UserController.GetUserById(settings.PortalId, toUser).Email, subject, body); return Null.NullString; @@ -375,7 +370,7 @@ public static string SendMail(string mailFrom, string mailTo, string bcc, string string smtpUsername, string smtpPassword) { MailFormat bodyFormat = MailFormat.Text; - if (!String.IsNullOrEmpty(bodyType)) + if (!string.IsNullOrEmpty(bodyType)) { switch (bodyType.ToLowerInvariant()) { @@ -387,7 +382,8 @@ public static string SendMail(string mailFrom, string mailTo, string bcc, string break; } } - return SendMail(mailFrom, mailTo, "", bcc, MailPriority.Normal, subject, bodyFormat, Encoding.UTF8, body, attachment, smtpServer, smtpAuthentication, smtpUsername, smtpPassword); + + return SendMail(mailFrom, mailTo, string.Empty, bcc, MailPriority.Normal, subject, bodyFormat, Encoding.UTF8, body, attachment, smtpServer, smtpAuthentication, smtpUsername, smtpPassword); } /// ----------------------------------------------------------------------------- @@ -418,146 +414,153 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string attachment, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { - return SendMail(mailFrom, - mailTo, - cc, - bcc, - mailFrom, - priority, - subject, - bodyFormat, - bodyEncoding, - body, - attachment.Split('|'), - smtpServer, - smtpAuthentication, - smtpUsername, - smtpPassword, - smtpEnableSSL); + return SendMail( + mailFrom, + mailTo, + cc, + bcc, + mailFrom, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachment.Split('|'), + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL); } public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { - return SendMail(mailFrom, - mailTo, - cc, - bcc, - mailFrom, - priority, - subject, - bodyFormat, - bodyEncoding, - body, - attachments, - smtpServer, - smtpAuthentication, - smtpUsername, - smtpPassword, - smtpEnableSSL); + return SendMail( + mailFrom, + mailTo, + cc, + bcc, + mailFrom, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachments, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL); } /// /// Sends an email based on params. /// - /// Email sender - /// Recipients, can be more then one separated by semi-colons - /// CC-recipients, can be more then one separated by semi-colons - /// BCC-recipients, can be more then one separated by semi-colons - /// Reply-to email to be displayed for recipients - /// - /// Subject of email - /// - /// Email Encoding from System.Text.Encoding - /// Body of email - /// List of filenames to attach to email - /// IP or ServerName of the SMTP server. When empty or null, then it takes from the HostSettings + /// Email sender. + /// Recipients, can be more then one separated by semi-colons. + /// CC-recipients, can be more then one separated by semi-colons. + /// BCC-recipients, can be more then one separated by semi-colons. + /// Reply-to email to be displayed for recipients. + /// . + /// Subject of email. + /// . + /// Email Encoding from System.Text.Encoding. + /// Body of email. + /// List of filenames to attach to email. + /// IP or ServerName of the SMTP server. When empty or null, then it takes from the HostSettings. /// SMTP authentication method. Can be "0" - anonymous, "1" - basic, "2" - NTLM. When empty or null, then it takes from the HostSettings. /// SMTP authentication UserName. When empty or null, then it takes from the HostSettings. /// SMTP authentication Password. When empty or null, then it takes from the HostSettings. /// Enable or disable SSL. /// Returns an empty string on success mail sending. Otherwise returns an error description. - /// SendMail( "admin@email.com", - /// "user@email.com", - /// "user1@email.com;user2@email.com", - /// "user3@email.com", - /// "no-reply@email.com", - /// MailPriority.Low, - /// "This is test email", - /// MailFormat.Text, - /// Encoding.UTF8, - /// "Test body. Test body. Test body.", - /// new string[] {"d:\documents\doc1.doc","d:\documents\doc2.doc"}, - /// "mail.email.com", - /// "1", - /// "admin@email.com", - /// "AdminPassword", - /// false); - /// + /// SendMail( "admin@email.com", + /// "user@email.com", + /// "user1@email.com;user2@email.com", + /// "user3@email.com", + /// "no-reply@email.com", + /// MailPriority.Low, + /// "This is test email", + /// MailFormat.Text, + /// Encoding.UTF8, + /// "Test body. Test body. Test body.", + /// new string[] {"d:\documents\doc1.doc","d:\documents\doc2.doc"}, + /// "mail.email.com", + /// "1", + /// "admin@email.com", + /// "AdminPassword", + /// false). + /// public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { var attachmentList = (from attachment in attachments - where !String.IsNullOrEmpty(attachment) + where !string.IsNullOrEmpty(attachment) select new Attachment(attachment)) .ToList(); - return SendMail(mailFrom, - mailTo, - cc, - bcc, - replyTo, - priority, - subject, - bodyFormat, - bodyEncoding, - body, - attachmentList, - smtpServer, - smtpAuthentication, - smtpUsername, - smtpPassword, - smtpEnableSSL); + return SendMail( + mailFrom, + mailTo, + cc, + bcc, + replyTo, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachmentList, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL); } public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { - return SendMail(mailFrom, - string.Empty, - mailTo, - cc, - bcc, - replyTo, - priority, - subject, - bodyFormat, - bodyEncoding, - body, - attachments, - smtpServer, - smtpAuthentication, - smtpUsername, - smtpPassword, - smtpEnableSSL); + return SendMail( + mailFrom, + string.Empty, + mailTo, + cc, + bcc, + replyTo, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachments, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL); } public static string SendMail(string mailFrom, string mailSender, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { - //SMTP server configuration + // SMTP server configuration if (string.IsNullOrWhiteSpace(smtpServer) && !string.IsNullOrWhiteSpace(Host.SMTPServer)) { smtpServer = Host.SMTPServer; } + if (string.IsNullOrEmpty(smtpAuthentication) && !string.IsNullOrEmpty(Host.SMTPAuthentication)) { smtpAuthentication = Host.SMTPAuthentication; } + if (string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(Host.SMTPUsername)) { smtpUsername = Host.SMTPUsername; } + if (string.IsNullOrEmpty(smtpPassword) && !string.IsNullOrEmpty(Host.SMTPPassword)) { smtpPassword = Host.SMTPPassword; @@ -570,8 +573,9 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, ? new MailMessage { From = - new MailAddress(mailFrom, - UserController.GetUserByEmail(PortalSettings.Current.PortalId, mailFrom).DisplayName) + new MailAddress( + mailFrom, + UserController.GetUserByEmail(PortalSettings.Current.PortalId, mailFrom).DisplayName), } : new MailMessage { From = new MailAddress(mailFrom) }; } @@ -585,24 +589,27 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, mailMessage.Sender = new MailAddress(mailSender); } - if (!String.IsNullOrEmpty(mailTo)) + if (!string.IsNullOrEmpty(mailTo)) { - //translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons + // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons mailTo = mailTo.Replace(";", ","); mailMessage.To.Add(mailTo); } - if (!String.IsNullOrEmpty(cc)) + + if (!string.IsNullOrEmpty(cc)) { - //translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons + // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons cc = cc.Replace(";", ","); mailMessage.CC.Add(cc); } - if (!String.IsNullOrEmpty(bcc)) + + if (!string.IsNullOrEmpty(bcc)) { - //translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons + // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons bcc = bcc.Replace(";", ","); mailMessage.Bcc.Add(bcc); } + if (replyTo != string.Empty) { mailMessage.ReplyToList.Add(new MailAddress(replyTo)); @@ -613,8 +620,6 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, return SendMailInternal(mailMessage, subject, body, priority, bodyFormat, bodyEncoding, attachments, smtpServer, smtpAuthentication, smtpUsername, smtpPassword, smtpEnableSSL); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Mail/MailFormat.cs b/DNN Platform/Library/Services/Mail/MailFormat.cs index b7522a3be98..e60f1e53f5b 100644 --- a/DNN Platform/Library/Services/Mail/MailFormat.cs +++ b/DNN Platform/Library/Services/Mail/MailFormat.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Mail { - /// - /// Enum MailFormat, possible values: Text and Html - /// - public enum MailFormat - { - Text, - Html - } + /// + /// Enum MailFormat, possible values: Text and Html. + /// + public enum MailFormat + { + Text, + Html, + } } diff --git a/DNN Platform/Library/Services/Mail/MailPriority.cs b/DNN Platform/Library/Services/Mail/MailPriority.cs index e4aaf0e873b..afd094ac297 100644 --- a/DNN Platform/Library/Services/Mail/MailPriority.cs +++ b/DNN Platform/Library/Services/Mail/MailPriority.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Mail { - /// - /// Enum MailPriority, there are 3 levels of priorities: Normal, Low or High - /// + /// + /// Enum MailPriority, there are 3 levels of priorities: Normal, Low or High. + /// public enum MailPriority { Normal, Low, - High + High, } } diff --git a/DNN Platform/Library/Services/Mail/MessageType.cs b/DNN Platform/Library/Services/Mail/MessageType.cs index ba41fc0a648..f901a671d6a 100644 --- a/DNN Platform/Library/Services/Mail/MessageType.cs +++ b/DNN Platform/Library/Services/Mail/MessageType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Mail { public enum MessageType @@ -17,6 +17,6 @@ public enum MessageType PasswordUpdated, PasswordReminderUserIsNotApproved, UserAuthorized, - UserUnAuthorized + UserUnAuthorized, } } diff --git a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs index 284ddbb516d..829b1428f84 100644 --- a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs +++ b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs @@ -1,315 +1,333 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net.Mail; -using System.Net.Mime; -using System.Text; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Messaging.Data; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mail { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net.Mail; + using System.Net.Mime; + using System.Text; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Messaging.Data; + using DotNetNuke.Services.Tokens; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// /// SendTokenizedBulkEmail Class is a class to manage the sending of bulk mails - /// that contains tokens, which might be replaced with individual user properties + /// that contains tokens, which might be replaced with individual user properties. /// /// /// /// ----------------------------------------------------------------------------- public class SendTokenizedBulkEmail : IDisposable { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SendTokenizedBulkEmail)); - #region AddressMethods enum - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SendTokenizedBulkEmail)); + + // ReSharper restore InconsistentNaming + private readonly List _addressedRoles = new List(); + private readonly List _addressedUsers = new List(); + private readonly List _attachments = new List(); + /// - /// Addressing Methods (personalized or hidden) + /// Addressing Methods (personalized or hidden). /// - // ReSharper disable InconsistentNaming - // Existing public API + // ReSharper disable InconsistentNaming + // Existing public API public enum AddressMethods { - Send_TO = 1, Send_BCC = 2, - Send_Relay = 3 - } - // ReSharper restore InconsistentNaming - - #endregion - - #region "Private Members" - - private readonly List _addressedRoles = new List(); - private readonly List _addressedUsers = new List(); - private readonly List _attachments = new List(); + Send_Relay = 3, + } private UserInfo _replyToUser; private bool _smtpEnableSSL; private TokenReplace _tokenReplace; private PortalSettings _portalSettings; private UserInfo _sendingUser; - private string _body = ""; + private string _body = string.Empty; private string _confirmBodyHTML; private string _confirmBodyText; private string _confirmSubject; private string _noError; private string _relayEmail; - private string _smtpAuthenticationMethod = ""; - private string _smtpPassword = ""; - private string _smtpServer = ""; - private string _smtpUsername = ""; + private string _smtpAuthenticationMethod = string.Empty; + private string _smtpPassword = string.Empty; + private string _smtpServer = string.Empty; + private string _smtpUsername = string.Empty; private string _strSenderLanguage; - private bool _isDisposed; - - #endregion - - #region "Constructs" - + private bool _isDisposed; + public SendTokenizedBulkEmail() { - ReportRecipients = true; - AddressMethod = AddressMethods.Send_TO; - BodyFormat = MailFormat.Text; - Subject = ""; - Priority = MailPriority.Normal; - Initialize(); + this.ReportRecipients = true; + this.AddressMethod = AddressMethods.Send_TO; + this.BodyFormat = MailFormat.Text; + this.Subject = string.Empty; + this.Priority = MailPriority.Normal; + this.Initialize(); } public SendTokenizedBulkEmail(List addressedRoles, List addressedUsers, bool removeDuplicates, string subject, string body) { - ReportRecipients = true; - AddressMethod = AddressMethods.Send_TO; - BodyFormat = MailFormat.Text; - Priority = MailPriority.Normal; - _addressedRoles = addressedRoles; - _addressedUsers = addressedUsers; - RemoveDuplicates = removeDuplicates; - Subject = subject; - Body = body; - SuppressTokenReplace = SuppressTokenReplace; - Initialize(); + this.ReportRecipients = true; + this.AddressMethod = AddressMethods.Send_TO; + this.BodyFormat = MailFormat.Text; + this.Priority = MailPriority.Normal; + this._addressedRoles = addressedRoles; + this._addressedUsers = addressedUsers; + this.RemoveDuplicates = removeDuplicates; + this.Subject = subject; + this.Body = body; + this.SuppressTokenReplace = this.SuppressTokenReplace; + this.Initialize(); + } + + ~SendTokenizedBulkEmail() + { + this.Dispose(false); } - - #endregion - - #region "Public Properties" - - /// - /// Priority of emails to be sent - /// + + /// + /// Gets or sets priority of emails to be sent. + /// public MailPriority Priority { get; set; } - /// - /// Subject of the emails to be sent - /// - /// may contain tokens + /// + /// Gets or sets subject of the emails to be sent. + /// + /// may contain tokens. public string Subject { get; set; } - /// - /// body text of the email to be sent - /// - /// may contain HTML tags and tokens. Side effect: sets BodyFormat autmatically + /// + /// Gets or sets body text of the email to be sent. + /// + /// may contain HTML tags and tokens. Side effect: sets BodyFormat autmatically. public string Body { get { - return _body; + return this._body; } + set { - _body = value; - BodyFormat = HtmlUtils.IsHtml(_body) ? MailFormat.Html : MailFormat.Text; + this._body = value; + this.BodyFormat = HtmlUtils.IsHtml(this._body) ? MailFormat.Html : MailFormat.Text; } } - /// format of body text for the email to be sent. - /// by default activated, if tokens are found in Body and subject. + /// Gets or sets format of body text for the email to be sent. + /// by default activated, if tokens are found in Body and subject. public MailFormat BodyFormat { get; set; } - /// address method for the email to be sent (TO or BCC) - /// TO is default value + /// Gets or sets address method for the email to be sent (TO or BCC). + /// TO is default value. public AddressMethods AddressMethod { get; set; } - /// portal alias http path to be used for links to images, ... + /// Gets or sets portal alias http path to be used for links to images, ... public string PortalAlias { get; set; } - /// UserInfo of the user sending the mail - /// if not set explicitely, currentuser will be used + /// Gets or sets userInfo of the user sending the mail. + /// if not set explicitely, currentuser will be used. public UserInfo SendingUser { get { - return _sendingUser; + return this._sendingUser; } + set { - _sendingUser = value; - if (_sendingUser.Profile.PreferredLocale != null) + this._sendingUser = value; + if (this._sendingUser.Profile.PreferredLocale != null) { - _strSenderLanguage = _sendingUser.Profile.PreferredLocale; + this._strSenderLanguage = this._sendingUser.Profile.PreferredLocale; } else { PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - _strSenderLanguage = portalSettings.DefaultLanguage; + this._strSenderLanguage = portalSettings.DefaultLanguage; } } } - /// email of the user to be shown in the mail as replyTo address - /// if not set explicitely, sendingUser will be used + /// Gets or sets email of the user to be shown in the mail as replyTo address. + /// if not set explicitely, sendingUser will be used. public UserInfo ReplyTo { get { - return _replyToUser ?? SendingUser; + return this._replyToUser ?? this.SendingUser; } + set { - _replyToUser = value; + this._replyToUser = value; } - } - - /// shall duplicate email addresses be ignored? (default value: false) - /// Duplicate Users (e.g. from multiple role selections) will always be ignored. - public bool RemoveDuplicates { get; set; } - - /// Shall automatic TokenReplace be prohibited? - /// default value: false - public bool SuppressTokenReplace { get; set; } - - /// Shall List of recipients appended to confirmation report? - /// enabled by default. + } + + /// Gets or sets a value indicating whether shall duplicate email addresses be ignored? (default value: false). + /// Duplicate Users (e.g. from multiple role selections) will always be ignored. + public bool RemoveDuplicates { get; set; } + + /// Gets or sets a value indicating whether shall automatic TokenReplace be prohibited?. + /// default value: false. + public bool SuppressTokenReplace { get; set; } + + /// Gets or sets a value indicating whether shall List of recipients appended to confirmation report?. + /// enabled by default. public bool ReportRecipients { get; set; } public string RelayEmailAddress { get { - return AddressMethod == AddressMethods.Send_Relay ? _relayEmail : string.Empty; + return this.AddressMethod == AddressMethods.Send_Relay ? this._relayEmail : string.Empty; } + set { - _relayEmail = value; + this._relayEmail = value; } } - public string[] LanguageFilter { get; set; } - - #endregion - - #region "Private Methods" + public string[] LanguageFilter { get; set; } + + /// Specify SMTP server to be used. + /// name of the SMTP server. + /// authentication string (0: anonymous, 1: basic, 2: NTLM). + /// username to log in SMTP server. + /// password to log in SMTP server. + /// SSL used to connect tp SMTP server. + /// always true. + /// if not called, values will be taken from host settings. + public bool SetSMTPServer(string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + { + this.EnsureNotDisposed(); + + this._smtpServer = smtpServer; + this._smtpAuthenticationMethod = smtpAuthentication; + this._smtpUsername = smtpUsername; + this._smtpPassword = smtpPassword; + this._smtpEnableSSL = smtpEnableSSL; + return true; + } - /// internal method to initialize used objects, depending on parameters of construct method + /// Add a single attachment file to the email. + /// path to file to attach. + /// only local stored files can be added with a path. + public void AddAttachment(string localPath) + { + this.EnsureNotDisposed(); + this._attachments.Add(new Attachment(localPath)); + } + + /// internal method to initialize used objects, depending on parameters of construct method. private void Initialize() { - _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - PortalAlias = _portalSettings.PortalAlias.HTTPAlias; - SendingUser = (UserInfo) HttpContext.Current.Items["UserInfo"]; - _tokenReplace = new TokenReplace(); - _confirmBodyHTML = Localization.Localization.GetString("EMAIL_BulkMailConf_Html_Body", Localization.Localization.GlobalResourceFile, _strSenderLanguage); - _confirmBodyText = Localization.Localization.GetString("EMAIL_BulkMailConf_Text_Body", Localization.Localization.GlobalResourceFile, _strSenderLanguage); - _confirmSubject = Localization.Localization.GetString("EMAIL_BulkMailConf_Subject", Localization.Localization.GlobalResourceFile, _strSenderLanguage); - _noError = Localization.Localization.GetString("NoErrorsSending", Localization.Localization.GlobalResourceFile, _strSenderLanguage); - _smtpEnableSSL = Host.EnableSMTPSSL; + this._portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + this.PortalAlias = this._portalSettings.PortalAlias.HTTPAlias; + this.SendingUser = (UserInfo)HttpContext.Current.Items["UserInfo"]; + this._tokenReplace = new TokenReplace(); + this._confirmBodyHTML = Localization.GetString("EMAIL_BulkMailConf_Html_Body", Localization.GlobalResourceFile, this._strSenderLanguage); + this._confirmBodyText = Localization.GetString("EMAIL_BulkMailConf_Text_Body", Localization.GlobalResourceFile, this._strSenderLanguage); + this._confirmSubject = Localization.GetString("EMAIL_BulkMailConf_Subject", Localization.GlobalResourceFile, this._strSenderLanguage); + this._noError = Localization.GetString("NoErrorsSending", Localization.GlobalResourceFile, this._strSenderLanguage); + this._smtpEnableSSL = Host.EnableSMTPSSL; } - /// Send bulkmail confirmation to admin - /// number of email recipients - /// number of messages sent, -1 if not determinable - /// number of emails not sent - /// Subject of BulkMail sent (to be used as reference) - /// date/time, sendout started - /// mail error texts - /// List of recipients as formatted string + /// Send bulkmail confirmation to admin. + /// number of email recipients. + /// number of messages sent, -1 if not determinable. + /// number of emails not sent. + /// Subject of BulkMail sent (to be used as reference). + /// date/time, sendout started. + /// mail error texts. + /// List of recipients as formatted string. /// private void SendConfirmationMail(int numRecipients, int numMessages, int numErrors, string subject, string startedAt, string mailErrors, string recipientList) - { - //send confirmation, use resource string like: - //Operation started at: [Custom:0]
    - //EmailRecipients: [Custom:1] - //Operation Completed: [Custom:3]
    - //Number of Errors: [Custom:4]
    - //Error Report:
    - //[Custom:5] + { + // send confirmation, use resource string like: + // Operation started at: [Custom:0]
    + // EmailRecipients: [Custom:1] + // Operation Completed: [Custom:3]
    + // Number of Errors: [Custom:4]
    + // Error Report:
    + // [Custom:5] //-------------------------------------- - //Recipients: - //[custom:6] + // Recipients: + // [custom:6] var parameters = new ArrayList { startedAt, numRecipients.ToString(CultureInfo.InvariantCulture), numMessages >= 0 ? numMessages.ToString(CultureInfo.InvariantCulture) : "***", DateTime.Now.ToString(CultureInfo.InvariantCulture), - numErrors > 0 ? numErrors.ToString(CultureInfo.InvariantCulture) : "", - mailErrors != string.Empty ? mailErrors : _noError, - ReportRecipients ? recipientList : "" + numErrors > 0 ? numErrors.ToString(CultureInfo.InvariantCulture) : string.Empty, + mailErrors != string.Empty ? mailErrors : this._noError, + this.ReportRecipients ? recipientList : string.Empty, }; - _tokenReplace.User = _sendingUser; - string body = _tokenReplace.ReplaceEnvironmentTokens(BodyFormat == MailFormat.Html ? _confirmBodyHTML : _confirmBodyText, parameters, "Custom"); - string strSubject = string.Format(_confirmSubject, subject); - if (!SuppressTokenReplace) + this._tokenReplace.User = this._sendingUser; + string body = this._tokenReplace.ReplaceEnvironmentTokens(this.BodyFormat == MailFormat.Html ? this._confirmBodyHTML : this._confirmBodyText, parameters, "Custom"); + string strSubject = string.Format(this._confirmSubject, subject); + if (!this.SuppressTokenReplace) { - strSubject = _tokenReplace.ReplaceEnvironmentTokens(strSubject); + strSubject = this._tokenReplace.ReplaceEnvironmentTokens(strSubject); } - var message = new Message {FromUserID = _sendingUser.UserID, ToUserID = _sendingUser.UserID, Subject = strSubject, Body = body, Status = MessageStatusType.Unread}; + + var message = new Message { FromUserID = this._sendingUser.UserID, ToUserID = this._sendingUser.UserID, Subject = strSubject, Body = body, Status = MessageStatusType.Unread }; - Mail.SendEmail(_sendingUser.Email, _sendingUser.Email, message.Subject, message.Body); + Mail.SendEmail(this._sendingUser.Email, this._sendingUser.Email, message.Subject, message.Body); } - /// check, if the user's language matches the current language filter - /// Language of the user - /// userlanguage matches current languageFilter - /// if filter not set, true is returned + /// check, if the user's language matches the current language filter. + /// Language of the user. + /// userlanguage matches current languageFilter. + /// if filter not set, true is returned. private bool MatchLanguageFilter(string userLanguage) { - if (LanguageFilter == null || LanguageFilter.Length == 0) + if (this.LanguageFilter == null || this.LanguageFilter.Length == 0) { return true; } - if(string.IsNullOrEmpty(userLanguage)) + if (string.IsNullOrEmpty(userLanguage)) { - userLanguage = _portalSettings.DefaultLanguage; + userLanguage = this._portalSettings.DefaultLanguage; } - return LanguageFilter.Any(s => userLanguage.StartsWith(s, StringComparison.InvariantCultureIgnoreCase)); + return this.LanguageFilter.Any(s => userLanguage.StartsWith(s, StringComparison.InvariantCultureIgnoreCase)); } - /// add a user to the userlist, if it is not already in there - /// user to add - /// list of key (either email addresses or userid's) - /// List of users - /// for use by Recipients method only + /// add a user to the userlist, if it is not already in there. + /// user to add. + /// list of key (either email addresses or userid's). + /// List of users. + /// for use by Recipients method only. private void ConditionallyAddUser(UserInfo user, ref List keyList, ref List userList) { - if (((user.UserID <= 0 || user.Membership.Approved) && user.Email != string.Empty) && MatchLanguageFilter(user.Profile.PreferredLocale)) + if (((user.UserID <= 0 || user.Membership.Approved) && user.Email != string.Empty) && this.MatchLanguageFilter(user.Profile.PreferredLocale)) { string key; - if (RemoveDuplicates || user.UserID == Null.NullInteger) + if (this.RemoveDuplicates || user.UserID == Null.NullInteger) { key = user.Email; } @@ -317,6 +335,7 @@ private void ConditionallyAddUser(UserInfo user, ref List keyList, ref L { key = user.UserID.ToString(CultureInfo.InvariantCulture); } + if (key != string.Empty && !keyList.Contains(key)) { userList.Add(user); @@ -325,14 +344,14 @@ private void ConditionallyAddUser(UserInfo user, ref List keyList, ref L } } - private List LoadAttachments() - { - var attachments = new List(); - foreach (var attachment in _attachments) - { + private List LoadAttachments() + { + var attachments = new List(); + foreach (var attachment in this._attachments) + { Attachment newAttachment; MemoryStream memoryStream = null; - var buffer = new byte[4096]; + var buffer = new byte[4096]; try { memoryStream = new MemoryStream(); @@ -343,12 +362,15 @@ private List LoadAttachments() { break; } + memoryStream.Write(buffer, 0, read); } + newAttachment = new Attachment(memoryStream, attachment.ContentType); newAttachment.ContentStream.Position = 0; attachments.Add(newAttachment); - //reset original position + + // reset original position attachment.ContentStream.Position = 0; memoryStream = null; } @@ -356,185 +378,160 @@ private List LoadAttachments() { memoryStream?.Dispose(); } - } - return attachments; - } - - #endregion - - #region "Public Methods" - - /// Specify SMTP server to be used - /// name of the SMTP server - /// authentication string (0: anonymous, 1: basic, 2: NTLM) - /// username to log in SMTP server - /// password to log in SMTP server - /// SSL used to connect tp SMTP server - /// always true - /// if not called, values will be taken from host settings - public bool SetSMTPServer(string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) - { - EnsureNotDisposed(); - - _smtpServer = smtpServer; - _smtpAuthenticationMethod = smtpAuthentication; - _smtpUsername = smtpUsername; - _smtpPassword = smtpPassword; - _smtpEnableSSL = smtpEnableSSL; - return true; - } - - /// Add a single attachment file to the email - /// path to file to attach - /// only local stored files can be added with a path - public void AddAttachment(string localPath) - { - EnsureNotDisposed(); - _attachments.Add(new Attachment(localPath)); - } + } + + return attachments; + } public void AddAttachment(Stream contentStream, ContentType contentType) { - EnsureNotDisposed(); - _attachments.Add(new Attachment(contentStream, contentType)); + this.EnsureNotDisposed(); + this._attachments.Add(new Attachment(contentStream, contentType)); } - /// Add a single recipient - /// userinfo of user to add - /// emaiol will be used for addressing, other properties might be used for TokenReplace + /// Add a single recipient. + /// userinfo of user to add. + /// emaiol will be used for addressing, other properties might be used for TokenReplace. public void AddAddressedUser(UserInfo recipient) { - EnsureNotDisposed(); - _addressedUsers.Add(recipient); + this.EnsureNotDisposed(); + this._addressedUsers.Add(recipient); } - /// Add all members of a role to recipient list - /// name of a role, whose members shall be added to recipients - /// emaiol will be used for addressing, other properties might be used for TokenReplace + /// Add all members of a role to recipient list. + /// name of a role, whose members shall be added to recipients. + /// emaiol will be used for addressing, other properties might be used for TokenReplace. public void AddAddressedRole(string roleName) { - EnsureNotDisposed(); - _addressedRoles.Add(roleName); + this.EnsureNotDisposed(); + this._addressedRoles.Add(roleName); } - /// All bulk mail recipients, derived from role names and individual adressees - /// List of userInfo objects, who receive the bulk mail - /// user.Email used for sending, other properties might be used for TokenReplace + /// All bulk mail recipients, derived from role names and individual adressees. + /// List of userInfo objects, who receive the bulk mail. + /// user.Email used for sending, other properties might be used for TokenReplace. public List Recipients() { - EnsureNotDisposed(); + this.EnsureNotDisposed(); var userList = new List(); var keyList = new List(); - - foreach (string roleName in _addressedRoles) + + foreach (string roleName in this._addressedRoles) { string role = roleName; - var roleInfo = RoleController.Instance.GetRole(_portalSettings.PortalId, r => r.RoleName == role); + var roleInfo = RoleController.Instance.GetRole(this._portalSettings.PortalId, r => r.RoleName == role); - foreach (UserInfo objUser in RoleController.Instance.GetUsersByRole(_portalSettings.PortalId, roleName)) + foreach (UserInfo objUser in RoleController.Instance.GetUsersByRole(this._portalSettings.PortalId, roleName)) { UserInfo user = objUser; ProfileController.GetUserProfile(ref user); - var userRole = RoleController.Instance.GetUserRole(_portalSettings.PortalId, objUser.UserID, roleInfo.RoleID); - //only add if user role has not expired and effectivedate has been passed + var userRole = RoleController.Instance.GetUserRole(this._portalSettings.PortalId, objUser.UserID, roleInfo.RoleID); + + // only add if user role has not expired and effectivedate has been passed if ((userRole.EffectiveDate <= DateTime.Now || Null.IsNull(userRole.EffectiveDate)) && (userRole.ExpiryDate >= DateTime.Now || Null.IsNull(userRole.ExpiryDate))) { - ConditionallyAddUser(objUser, ref keyList, ref userList); + this.ConditionallyAddUser(objUser, ref keyList, ref userList); } } } - - foreach (UserInfo objUser in _addressedUsers) + + foreach (UserInfo objUser in this._addressedUsers) { - ConditionallyAddUser(objUser, ref keyList, ref userList); + this.ConditionallyAddUser(objUser, ref keyList, ref userList); } - + return userList; } - /// Send bulkmail to all recipients according to settings - /// Number of emails sent, null.integer if not determinable - /// Detailed status report is sent by email to sending user + /// Send bulkmail to all recipients according to settings. + /// Number of emails sent, null.integer if not determinable. + /// Detailed status report is sent by email to sending user. public int SendMails() { - EnsureNotDisposed(); - + this.EnsureNotDisposed(); + int recipients = 0; int messagesSent = 0; int errors = 0; - + try { - //send to recipients - string body = _body; - if (BodyFormat == MailFormat.Html) //Add Base Href for any images inserted in to the email. + // send to recipients + string body = this._body; + if (this.BodyFormat == MailFormat.Html) // Add Base Href for any images inserted in to the email. { - var host = PortalAlias.Contains("/") ? PortalAlias.Substring(0, PortalAlias.IndexOf('/')) : PortalAlias; - body = "" + Subject + "" + body + ""; + var host = this.PortalAlias.Contains("/") ? this.PortalAlias.Substring(0, this.PortalAlias.IndexOf('/')) : this.PortalAlias; + body = "" + this.Subject + "" + body + ""; } - string subject = Subject; + + string subject = this.Subject; string startedAt = DateTime.Now.ToString(CultureInfo.InvariantCulture); - bool replaceTokens = !SuppressTokenReplace && (_tokenReplace.ContainsTokens(Subject) || _tokenReplace.ContainsTokens(_body)); + bool replaceTokens = !this.SuppressTokenReplace && (this._tokenReplace.ContainsTokens(this.Subject) || this._tokenReplace.ContainsTokens(this._body)); bool individualSubj = false; bool individualBody = false; var mailErrors = new StringBuilder(); var mailRecipients = new StringBuilder(); - - switch (AddressMethod) + + switch (this.AddressMethod) { case AddressMethods.Send_TO: case AddressMethods.Send_Relay: - //optimization: + // optimization: if (replaceTokens) { - individualBody = (_tokenReplace.Cacheability(_body) == CacheLevel.notCacheable); - individualSubj = (_tokenReplace.Cacheability(Subject) == CacheLevel.notCacheable); + individualBody = this._tokenReplace.Cacheability(this._body) == CacheLevel.notCacheable; + individualSubj = this._tokenReplace.Cacheability(this.Subject) == CacheLevel.notCacheable; if (!individualBody) { - body = _tokenReplace.ReplaceEnvironmentTokens(body); + body = this._tokenReplace.ReplaceEnvironmentTokens(body); } + if (!individualSubj) { - subject = _tokenReplace.ReplaceEnvironmentTokens(subject); + subject = this._tokenReplace.ReplaceEnvironmentTokens(subject); } } - foreach (UserInfo user in Recipients()) + + foreach (UserInfo user in this.Recipients()) { recipients += 1; if (individualBody || individualSubj) { - _tokenReplace.User = user; - _tokenReplace.AccessingUser = user; + this._tokenReplace.User = user; + this._tokenReplace.AccessingUser = user; if (individualBody) { - body = _tokenReplace.ReplaceEnvironmentTokens(_body); + body = this._tokenReplace.ReplaceEnvironmentTokens(this._body); } + if (individualSubj) { - subject = _tokenReplace.ReplaceEnvironmentTokens(Subject); + subject = this._tokenReplace.ReplaceEnvironmentTokens(this.Subject); } } - string recipient = AddressMethod == AddressMethods.Send_TO ? user.Email : RelayEmailAddress; - - string mailError = Mail.SendMail(_sendingUser.Email, - recipient, - "", - "", - ReplyTo.Email, - Priority, - subject, - BodyFormat, - Encoding.UTF8, - body, - LoadAttachments(), - _smtpServer, - _smtpAuthenticationMethod, - _smtpUsername, - _smtpPassword, - _smtpEnableSSL); + + string recipient = this.AddressMethod == AddressMethods.Send_TO ? user.Email : this.RelayEmailAddress; + + string mailError = Mail.SendMail( + this._sendingUser.Email, + recipient, + string.Empty, + string.Empty, + this.ReplyTo.Email, + this.Priority, + subject, + this.BodyFormat, + Encoding.UTF8, + body, + this.LoadAttachments(), + this._smtpServer, + this._smtpAuthenticationMethod, + this._smtpUsername, + this._smtpPassword, + this._smtpEnableSSL); if (!string.IsNullOrEmpty(mailError)) { mailErrors.Append(mailError); @@ -544,7 +541,7 @@ public int SendMails() else { mailRecipients.Append(user.Email); - mailRecipients.Append(BodyFormat == MailFormat.Html ? "
    " : Environment.NewLine); + mailRecipients.Append(this.BodyFormat == MailFormat.Html ? "
    " : Environment.NewLine); messagesSent += 1; } } @@ -553,44 +550,46 @@ public int SendMails() case AddressMethods.Send_BCC: var distributionList = new StringBuilder(); messagesSent = Null.NullInteger; - foreach (UserInfo user in Recipients()) + foreach (UserInfo user in this.Recipients()) { recipients += 1; distributionList.Append(user.Email + "; "); mailRecipients.Append(user.Email); - mailRecipients.Append(BodyFormat == MailFormat.Html ? "
    " : Environment.NewLine); + mailRecipients.Append(this.BodyFormat == MailFormat.Html ? "
    " : Environment.NewLine); } if (distributionList.Length > 2) { if (replaceTokens) { - //no access to User properties possible! + // no access to User properties possible! var tr = new TokenReplace(Scope.Configuration); - body = tr.ReplaceEnvironmentTokens(_body); - subject = tr.ReplaceEnvironmentTokens(Subject); + body = tr.ReplaceEnvironmentTokens(this._body); + subject = tr.ReplaceEnvironmentTokens(this.Subject); } else { - body = _body; - subject = Subject; + body = this._body; + subject = this.Subject; } - string mailError = Mail.SendMail(_sendingUser.Email, - _sendingUser.Email, - "", - distributionList.ToString(0, distributionList.Length - 2), - ReplyTo.Email, - Priority, - subject, - BodyFormat, - Encoding.UTF8, - body, - LoadAttachments(), - _smtpServer, - _smtpAuthenticationMethod, - _smtpUsername, - _smtpPassword, - _smtpEnableSSL); + + string mailError = Mail.SendMail( + this._sendingUser.Email, + this._sendingUser.Email, + string.Empty, + distributionList.ToString(0, distributionList.Length - 2), + this.ReplyTo.Email, + this.Priority, + subject, + this.BodyFormat, + Encoding.UTF8, + body, + this.LoadAttachments(), + this._smtpServer, + this._smtpAuthenticationMethod, + this._smtpUsername, + this._smtpPassword, + this._smtpEnableSSL); if (mailError == string.Empty) { messagesSent = 1; @@ -601,15 +600,18 @@ public int SendMails() errors += 1; } } + break; } + if (mailErrors.Length > 0) { mailRecipients = new StringBuilder(); } - SendConfirmationMail(recipients, messagesSent, errors, subject, startedAt, mailErrors.ToString(), mailRecipients.ToString()); + + this.SendConfirmationMail(recipients, messagesSent, errors, subject, startedAt, mailErrors.ToString(), mailRecipients.ToString()); } - catch (Exception exc) //send mail failure + catch (Exception exc) // send mail failure { Logger.Error(exc); @@ -617,57 +619,52 @@ public int SendMails() } finally { - foreach (var attachment in _attachments) - { - attachment.Dispose(); - } + foreach (var attachment in this._attachments) + { + attachment.Dispose(); + } } + return messagesSent; } - /// Wrapper for Function SendMails + /// Wrapper for Function SendMails. public void Send() { - EnsureNotDisposed(); - SendMails(); - } - - #endregion - - private void EnsureNotDisposed() - { - if (_isDisposed) - { - throw new ObjectDisposedException("SharedDictionary"); - } - } + this.EnsureNotDisposed(); + this.SendMails(); + } public void Dispose() { - Dispose(true); + this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { - if (!_isDisposed) + if (!this._isDisposed) { if (disposing) { - //get rid of managed resources - foreach (Attachment attachment in _attachments) + // get rid of managed resources + foreach (Attachment attachment in this._attachments) { attachment.Dispose(); - _isDisposed = true; + this._isDisposed = true; } } + // get rid of unmanaged resources } } - - ~SendTokenizedBulkEmail() + + private void EnsureNotDisposed() { - Dispose(false); + if (this._isDisposed) + { + throw new ObjectDisposedException("SharedDictionary"); + } } } } diff --git a/DNN Platform/Library/Services/Messaging/Data/IMessagingDataService.cs b/DNN Platform/Library/Services/Messaging/Data/IMessagingDataService.cs index a8f700ee7a0..a397cbec213 100644 --- a/DNN Platform/Library/Services/Messaging/Data/IMessagingDataService.cs +++ b/DNN Platform/Library/Services/Messaging/Data/IMessagingDataService.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Messaging.Data { + using System; + using System.Data; + public interface IMessagingDataService { IDataReader GetMessageByID(int MessageID); diff --git a/DNN Platform/Library/Services/Messaging/Data/Message.cs b/DNN Platform/Library/Services/Messaging/Data/Message.cs index d74b23bb662..8141202eea8 100644 --- a/DNN Platform/Library/Services/Messaging/Data/Message.cs +++ b/DNN Platform/Library/Services/Messaging/Data/Message.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Messaging.Data { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + /// ----------------------------------------------------------------------------- /// - /// The Info class for Messaging + /// The Info class for Messaging. /// /// /// @@ -40,85 +35,80 @@ public class Message : IHydratable private string _ToUserName; private bool _allowReply; - private bool _skipInbox; - - #region "Constructors" - - public Message() - { - Conversation = Guid.Empty; - Status = MessageStatusType.Draft; - MessageDate = DateTime.Now; - } - - #endregion - - #region "Public Properties" - + private bool _skipInbox; + private Guid _EmailSchedulerInstance; private DateTime _EmailSentDate; + + public Message() + { + this.Conversation = Guid.Empty; + this.Status = MessageStatusType.Draft; + this.MessageDate = DateTime.Now; + } public string FromUserName { get { - return _FromUserName; + return this._FromUserName; } + private set { - _FromUserName = value; + this._FromUserName = value; } } - - + public int FromUserID { get { - return _FromUserID; + return this._FromUserID; } + set { - _FromUserID = value; + this._FromUserID = value; } } - - + public int ToRoleID { get { - return _ToRoleId; + return this._ToRoleId; } + set { - _ToRoleId = value; + this._ToRoleId = value; } } - - + public bool AllowReply { get { - return _allowReply; + return this._allowReply; } + set { - _allowReply = value; + this._allowReply = value; } } - - + public bool SkipInbox { get { - return _skipInbox; + return this._skipInbox; } + set { - _skipInbox = value; + this._skipInbox = value; } } @@ -126,24 +116,25 @@ public bool EmailSent { get { - return _EmailSent; + return this._EmailSent; } + set { - _EmailSent = value; + this._EmailSent = value; } } - - + public string Body { get { - return _Body; + return this._Body; } + set { - _Body = value; + this._Body = value; } } @@ -151,11 +142,12 @@ public DateTime MessageDate { get { - return _MessageDate; + return this._MessageDate; } + set { - _MessageDate = value; + this._MessageDate = value; } } @@ -163,11 +155,12 @@ public Guid Conversation { get { - return _Conversation; + return this._Conversation; } + set { - _Conversation = value; + this._Conversation = value; } } @@ -175,24 +168,25 @@ public int MessageID { get { - return _MessageID; + return this._MessageID; } + private set { - _MessageID = value; + this._MessageID = value; } } - - + public int PortalID { get { - return _PortalID; + return this._PortalID; } + set { - _PortalID = value; + this._PortalID = value; } } @@ -200,11 +194,12 @@ public int ReplyTo { get { - return _ReplyTo; + return this._ReplyTo; } + private set { - _ReplyTo = value; + this._ReplyTo = value; } } @@ -212,11 +207,12 @@ public MessageStatusType Status { get { - return _Status; + return this._Status; } + set { - _Status = value; + this._Status = value; } } @@ -225,26 +221,27 @@ public string Subject get { var ps = PortalSecurity.Instance; - return ps.InputFilter(_Subject, PortalSecurity.FilterFlag.NoMarkup); + return ps.InputFilter(this._Subject, PortalSecurity.FilterFlag.NoMarkup); } + set { var ps = PortalSecurity.Instance; ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); - _Subject = ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + this._Subject = ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } - - + public int ToUserID { get { - return _ToUserID; + return this._ToUserID; } + set { - _ToUserID = value; + this._ToUserID = value; } } @@ -252,104 +249,96 @@ public string ToUserName { get { - return _ToUserName; + return this._ToUserName; } + private set { - _ToUserName = value; + this._ToUserName = value; } } - - + public DateTime EmailSentDate { get { - return _EmailSentDate; + return this._EmailSentDate; } + private set { - _EmailSentDate = value; + this._EmailSentDate = value; } } - - + public Guid EmailSchedulerInstance { get { - return _EmailSchedulerInstance; + return this._EmailSchedulerInstance; } + private set { - _EmailSchedulerInstance = value; + this._EmailSchedulerInstance = value; } - } - - #endregion - - #region "Public Methods" - - public Message GetReplyMessage() - { - var message = new Message(); - message.AllowReply = AllowReply; - message.Body = string.Format("


    On {0} {1} wrote ", MessageDate, FromUserName) + Body; - message.Conversation = Conversation; - message.FromUserID = ToUserID; - message.ToUserID = FromUserID; - message.ToUserName = FromUserName; - message.PortalID = PortalID; - message.ReplyTo = MessageID; - message.SkipInbox = SkipInbox; - message.Subject = "RE:" + Subject; - - return message; - } - - #endregion - - #region "IHydratable Implementation" - - public void Fill(IDataReader dr) - { - MessageID = Null.SetNullInteger(dr["MessageID"]); - PortalID = Null.SetNullInteger(dr["PortalID"]); - FromUserID = Null.SetNullInteger(dr["FromUserID"]); - FromUserName = Null.SetNullString(dr["FromUserName"]); - ToUserID = Null.SetNullInteger(dr["ToUserID"]); - //'_ToUserName = Null.SetNullString(dr.Item("ToUserName")) - ReplyTo = Null.SetNullInteger(dr["ReplyTo"]); - Status = (MessageStatusType) Enum.Parse(typeof (MessageStatusType), Null.SetNullString(dr["Status"])); - Body = Null.SetNullString(dr["Body"]); - Subject = Null.SetNullString(dr["Subject"]); - MessageDate = Null.SetNullDateTime(dr["Date"]); - ToRoleID = Null.SetNullInteger(dr["ToRoleID"]); - AllowReply = Null.SetNullBoolean(dr["AllowReply"]); - SkipInbox = Null.SetNullBoolean(dr["SkipPortal"]); - EmailSent = Null.SetNullBoolean(dr["EmailSent"]); - ToUserName = Null.SetNullString(dr["ToUserName"]); - string g = Null.SetNullString(dr["Conversation"]); - EmailSentDate = Null.SetNullDateTime(dr["EmailSentDate"]); - EmailSchedulerInstance = Null.SetNullGuid(dr["EmailSchedulerInstance"]); - Conversation = Null.SetNullGuid(dr["Conversation"]); - - - //'Conversation = New Guid(g) - } + } public int KeyID { get { - return MessageID; + return this.MessageID; } + set { - MessageID = value; + this.MessageID = value; } - } + } + + public Message GetReplyMessage() + { + var message = new Message(); + message.AllowReply = this.AllowReply; + message.Body = string.Format("


    On {0} {1} wrote ", this.MessageDate, this.FromUserName) + this.Body; + message.Conversation = this.Conversation; + message.FromUserID = this.ToUserID; + message.ToUserID = this.FromUserID; + message.ToUserName = this.FromUserName; + message.PortalID = this.PortalID; + message.ReplyTo = this.MessageID; + message.SkipInbox = this.SkipInbox; + message.Subject = "RE:" + this.Subject; - #endregion + return message; + } + + public void Fill(IDataReader dr) + { + this.MessageID = Null.SetNullInteger(dr["MessageID"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.FromUserID = Null.SetNullInteger(dr["FromUserID"]); + this.FromUserName = Null.SetNullString(dr["FromUserName"]); + this.ToUserID = Null.SetNullInteger(dr["ToUserID"]); + + // '_ToUserName = Null.SetNullString(dr.Item("ToUserName")) + this.ReplyTo = Null.SetNullInteger(dr["ReplyTo"]); + this.Status = (MessageStatusType)Enum.Parse(typeof(MessageStatusType), Null.SetNullString(dr["Status"])); + this.Body = Null.SetNullString(dr["Body"]); + this.Subject = Null.SetNullString(dr["Subject"]); + this.MessageDate = Null.SetNullDateTime(dr["Date"]); + this.ToRoleID = Null.SetNullInteger(dr["ToRoleID"]); + this.AllowReply = Null.SetNullBoolean(dr["AllowReply"]); + this.SkipInbox = Null.SetNullBoolean(dr["SkipPortal"]); + this.EmailSent = Null.SetNullBoolean(dr["EmailSent"]); + this.ToUserName = Null.SetNullString(dr["ToUserName"]); + string g = Null.SetNullString(dr["Conversation"]); + this.EmailSentDate = Null.SetNullDateTime(dr["EmailSentDate"]); + this.EmailSchedulerInstance = Null.SetNullGuid(dr["EmailSchedulerInstance"]); + this.Conversation = Null.SetNullGuid(dr["Conversation"]); + + // 'Conversation = New Guid(g) + } } } diff --git a/DNN Platform/Library/Services/Messaging/Data/MessageStatusType.cs b/DNN Platform/Library/Services/Messaging/Data/MessageStatusType.cs index 2b589e608d8..21b811cd98a 100644 --- a/DNN Platform/Library/Services/Messaging/Data/MessageStatusType.cs +++ b/DNN Platform/Library/Services/Messaging/Data/MessageStatusType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Messaging.Data { public enum MessageStatusType @@ -9,6 +9,6 @@ public enum MessageStatusType Draft = 0, Unread = 1, Read = 2, - Deleted = 3 + Deleted = 3, } } diff --git a/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs b/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs index 284f34e0ad3..d10078a5329 100644 --- a/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs +++ b/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs @@ -1,86 +1,79 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; - -using DotNetNuke.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Messaging.Data { + using System; + using System.Data; + + using DotNetNuke.Data; + public class MessagingDataService : IMessagingDataService { - private readonly DataProvider provider = DataProvider.Instance(); - - #region IMessagingDataService Members - + private readonly DataProvider provider = DataProvider.Instance(); + public IDataReader GetMessageByID(int messageId) { - return provider.ExecuteReader("Messaging_GetMessage", messageId); + return this.provider.ExecuteReader("Messaging_GetMessage", messageId); } public IDataReader GetUserInbox(int PortalID, int UserID, int PageNumber, int PageSize) { - return provider.ExecuteReader("Messaging_GetInbox", PortalID, UserID, PageNumber, PageSize); + return this.provider.ExecuteReader("Messaging_GetInbox", PortalID, UserID, PageNumber, PageSize); } public int GetInboxCount(int PortalID, int UserID) { - return provider.ExecuteScalar("Messaging_GetInboxCount", PortalID, UserID); + return this.provider.ExecuteScalar("Messaging_GetInboxCount", PortalID, UserID); } public long SaveMessage(Message objMessaging) { - return provider.ExecuteScalar("Messaging_Save_Message", - objMessaging.PortalID, - objMessaging.FromUserID, - objMessaging.ToUserID, - objMessaging.ToRoleID, - (int) objMessaging.Status, - objMessaging.Subject, - objMessaging.Body, - objMessaging.MessageDate, - objMessaging.Conversation, - objMessaging.ReplyTo, - objMessaging.AllowReply, - objMessaging.SkipInbox); + return this.provider.ExecuteScalar( + "Messaging_Save_Message", + objMessaging.PortalID, + objMessaging.FromUserID, + objMessaging.ToUserID, + objMessaging.ToRoleID, + (int)objMessaging.Status, + objMessaging.Subject, + objMessaging.Body, + objMessaging.MessageDate, + objMessaging.Conversation, + objMessaging.ReplyTo, + objMessaging.AllowReply, + objMessaging.SkipInbox); } public int GetNewMessageCount(int PortalID, int UserID) { - return provider.ExecuteScalar("Messaging_GetNewMessageCount", PortalID, UserID); + return this.provider.ExecuteScalar("Messaging_GetNewMessageCount", PortalID, UserID); } public IDataReader GetNextMessageForDispatch(Guid SchedulerInstance) { - return provider.ExecuteReader("Messaging_GetNextMessageForDispatch", SchedulerInstance); + return this.provider.ExecuteReader("Messaging_GetNextMessageForDispatch", SchedulerInstance); } public void MarkMessageAsDispatched(int MessageID) { - provider.ExecuteNonQuery("Messaging_MarkMessageAsDispatched", MessageID); + this.provider.ExecuteNonQuery("Messaging_MarkMessageAsDispatched", MessageID); } public void UpdateMessage(Message message) { - provider.ExecuteNonQuery("Messaging_UpdateMessage", - message.MessageID, - message.ToUserID, - message.ToRoleID, - (int) message.Status, - message.Subject, - message.Body, - message.MessageDate, - message.ReplyTo, - message.AllowReply, - message.SkipInbox); - } - - #endregion + this.provider.ExecuteNonQuery( + "Messaging_UpdateMessage", + message.MessageID, + message.ToUserID, + message.ToRoleID, + (int)message.Status, + message.Subject, + message.Body, + message.MessageDate, + message.ReplyTo, + message.AllowReply, + message.SkipInbox); + } } } diff --git a/DNN Platform/Library/Services/Messaging/IMessagingController.cs b/DNN Platform/Library/Services/Messaging/IMessagingController.cs index b37accbeb47..7541cded17d 100644 --- a/DNN Platform/Library/Services/Messaging/IMessagingController.cs +++ b/DNN Platform/Library/Services/Messaging/IMessagingController.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Services.Messaging.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Messaging { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Messaging.Data; + public interface IMessagingController { Message GetMessageByID(int PortalID, int UserID, int MessageID); diff --git a/DNN Platform/Library/Services/Mobile/IMatchRule.cs b/DNN Platform/Library/Services/Mobile/IMatchRule.cs index 52620d44e22..99a2ecac627 100644 --- a/DNN Platform/Library/Services/Mobile/IMatchRule.cs +++ b/DNN Platform/Library/Services/Mobile/IMatchRule.cs @@ -1,29 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public interface IMatchRule - { - /// - /// Primary Id. - /// - int Id { get; } - /// - /// capbility name. - /// - string Capability { get; set; } + using System; + + public interface IMatchRule + { + /// + /// Gets primary Id. + /// + int Id { get; } + + /// + /// Gets or sets capbility name. + /// + string Capability { get; set; } - /// - /// reg expression to match the request - /// - string Expression { get; set; } - } + /// + /// Gets or sets reg expression to match the request. + /// + string Expression { get; set; } + } } diff --git a/DNN Platform/Library/Services/Mobile/IPreviewProfile.cs b/DNN Platform/Library/Services/Mobile/IPreviewProfile.cs index 797479c640a..4d0d9cff1ef 100644 --- a/DNN Platform/Library/Services/Mobile/IPreviewProfile.cs +++ b/DNN Platform/Library/Services/Mobile/IPreviewProfile.cs @@ -1,32 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public interface IPreviewProfile - { - int Id { get; set; } + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + + public interface IPreviewProfile + { + int Id { get; set; } - int PortalId { get; set; } + int PortalId { get; set; } - string Name { get; set; } + string Name { get; set; } - int Width { get; set; } + int Width { get; set; } - string UserAgent { get; set; } + string UserAgent { get; set; } - int Height { get; set; } + int Height { get; set; } - int SortOrder { get; set; } - } + int SortOrder { get; set; } + } } diff --git a/DNN Platform/Library/Services/Mobile/IPreviewProfileController.cs b/DNN Platform/Library/Services/Mobile/IPreviewProfileController.cs index bfb6b7f8ce1..774730b2bd5 100644 --- a/DNN Platform/Library/Services/Mobile/IPreviewProfileController.cs +++ b/DNN Platform/Library/Services/Mobile/IPreviewProfileController.cs @@ -1,25 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public interface IPreviewProfileController - { - void Save(IPreviewProfile profile); + using System; + using System.Collections.Generic; + + public interface IPreviewProfileController + { + void Save(IPreviewProfile profile); - void Delete(int portalId, int id); + void Delete(int portalId, int id); - IList GetProfilesByPortal(int portalId); + IList GetProfilesByPortal(int portalId); - IPreviewProfile GetProfileById(int portalId, int id); - } + IPreviewProfile GetProfileById(int portalId, int id); + } } diff --git a/DNN Platform/Library/Services/Mobile/IRedirection.cs b/DNN Platform/Library/Services/Mobile/IRedirection.cs index dde5efd462a..24c928a8fb5 100644 --- a/DNN Platform/Library/Services/Mobile/IRedirection.cs +++ b/DNN Platform/Library/Services/Mobile/IRedirection.cs @@ -1,72 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public interface IRedirection - { - /// - /// Primary ID. - /// - int Id { get; } - /// - /// Portal Id. - /// - int PortalId { get; set; } - /// - /// Redirection name. - /// - string Name { get; set; } + using System; + using System.Collections.Generic; + + public interface IRedirection + { + /// + /// Gets primary ID. + /// + int Id { get; } + + /// + /// Gets or sets portal Id. + /// + int PortalId { get; set; } + + /// + /// Gets or sets redirection name. + /// + string Name { get; set; } - /// - /// if redirect by visit the whole portal, this value should be -1; - /// otherwise should be the exactly page id for redirection. - /// - int SourceTabId { get; set; } + /// + /// Gets or sets if redirect by visit the whole portal, this value should be -1; + /// otherwise should be the exactly page id for redirection. + /// + int SourceTabId { get; set; } - /// - /// This value will be available when SourceTabId have a specific value, in that way when this value is true, page will rediect - /// to target when request source tab and all child tabs under source tab. - /// - bool IncludeChildTabs { get; set; } + /// + /// Gets or sets a value indicating whether this value will be available when SourceTabId have a specific value, in that way when this value is true, page will rediect + /// to target when request source tab and all child tabs under source tab. + /// + bool IncludeChildTabs { get; set; } - /// - /// The redirection type: should be Mobile, Tablet, Both of mobile and tablet, and all other unknown devices. - /// if this value is Other, should use MatchRules to match the special request need to redirect. - /// - RedirectionType Type { get; set; } + /// + /// Gets or sets the redirection type: should be Mobile, Tablet, Both of mobile and tablet, and all other unknown devices. + /// if this value is Other, should use MatchRules to match the special request need to redirect. + /// + RedirectionType Type { get; set; } - /// - /// request match rules. - /// + /// + /// Gets or sets request match rules. + /// IList MatchRules { get; set; } - /// - /// Redirection target type. - /// - TargetType TargetType { get; set; } + /// + /// Gets or sets redirection target type. + /// + TargetType TargetType { get; set; } - /// - /// Redirection target value, can a portal id, tab id or a specific url. - /// - object TargetValue { get; set; } + /// + /// Gets or sets redirection target value, can a portal id, tab id or a specific url. + /// + object TargetValue { get; set; } - /// - /// Enabled the Redirection. - /// - bool Enabled { get; set; } + /// + /// Gets or sets a value indicating whether enabled the Redirection. + /// + bool Enabled { get; set; } - /// - /// Redirection's Order - /// - int SortOrder { get; set; } - } + /// + /// Gets or sets redirection's Order. + /// + int SortOrder { get; set; } + } } diff --git a/DNN Platform/Library/Services/Mobile/IRedirectionController.cs b/DNN Platform/Library/Services/Mobile/IRedirectionController.cs index 811a568d687..36411441401 100644 --- a/DNN Platform/Library/Services/Mobile/IRedirectionController.cs +++ b/DNN Platform/Library/Services/Mobile/IRedirectionController.cs @@ -1,45 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public interface IRedirectionController - { - void Save(IRedirection redirection); + using System; + using System.Collections.Generic; + using System.Web; + + public interface IRedirectionController + { + void Save(IRedirection redirection); - void PurgeInvalidRedirections(int portalId); + void PurgeInvalidRedirections(int portalId); - void Delete(int portalId, int id); + void Delete(int portalId, int id); - void DeleteRule(int portalId, int redirectionId, int ruleId); + void DeleteRule(int portalId, int redirectionId, int ruleId); IList GetAllRedirections(); - IList GetRedirectionsByPortal(int portalId); + IList GetRedirectionsByPortal(int portalId); - IRedirection GetRedirectionById(int portalId, int id); + IRedirection GetRedirectionById(int portalId, int id); - string GetRedirectUrl(string userAgent, int portalId, int currentTabId); + string GetRedirectUrl(string userAgent, int portalId, int currentTabId); string GetRedirectUrl(string userAgent); - string GetFullSiteUrl(); + string GetFullSiteUrl(); - string GetFullSiteUrl(int portalId, int currentTabId); + string GetFullSiteUrl(int portalId, int currentTabId); string GetMobileSiteUrl(); string GetMobileSiteUrl(int portalId, int currentTabId); bool IsRedirectAllowedForTheSession(HttpApplication app); - } + } } diff --git a/DNN Platform/Library/Services/Mobile/MatchRule.cs b/DNN Platform/Library/Services/Mobile/MatchRule.cs index e39bb4a6c65..c9669a8b16a 100644 --- a/DNN Platform/Library/Services/Mobile/MatchRule.cs +++ b/DNN Platform/Library/Services/Mobile/MatchRule.cs @@ -1,87 +1,84 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + [Serializable] - public class MatchRule : IMatchRule, IHydratable - { - private int _id = -1; + public class MatchRule : IMatchRule, IHydratable + { + private int _id = -1; - /// - /// Match rule's primary key. - /// + /// + /// Gets or sets match rule's primary key. + /// [XmlAttribute] - public int Id - { - get - { - return _id; - } - set - { - _id = value; - } - } + public int Id + { + get + { + return this._id; + } + + set + { + this._id = value; + } + } - /// - /// Capability's name. - /// + /// + /// Gets or sets capability's name. + /// [XmlAttribute] public string Capability - { - get; - set; - } + { + get; + set; + } - /// - /// The value to match the capability from request. - /// + /// + /// Gets or sets the value to match the capability from request. + /// [XmlAttribute] public string Expression - { - get; - set; - } + { + get; + set; + } - /// - /// IHydratable.KeyID. - /// + /// + /// Gets or sets iHydratable.KeyID. + /// [XmlAttribute] public int KeyID - { - get - { - return this.Id; - } - set - { - this.Id = value; - } - } + { + get + { + return this.Id; + } + + set + { + this.Id = value; + } + } - /// - /// Fill the object with data from database. - /// - /// the data reader. - public void Fill(System.Data.IDataReader dr) - { - this.Id = Convert.ToInt32(dr["Id"]); - this.Capability = dr["Capability"].ToString(); - this.Expression = dr["Expression"].ToString(); - } - } + /// + /// Fill the object with data from database. + /// + /// the data reader. + public void Fill(System.Data.IDataReader dr) + { + this.Id = Convert.ToInt32(dr["Id"]); + this.Capability = dr["Capability"].ToString(); + this.Expression = dr["Expression"].ToString(); + } + } } diff --git a/DNN Platform/Library/Services/Mobile/PreviewProfile.cs b/DNN Platform/Library/Services/Mobile/PreviewProfile.cs index f7be40c0106..b404f6cbe04 100644 --- a/DNN Platform/Library/Services/Mobile/PreviewProfile.cs +++ b/DNN Platform/Library/Services/Mobile/PreviewProfile.cs @@ -1,114 +1,111 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - [Serializable] - public class PreviewProfile : IPreviewProfile, IHydratable - { - private int _id = -1; + using System; + using System.Collections.Generic; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Entities.Modules; + + [Serializable] + public class PreviewProfile : IPreviewProfile, IHydratable + { + private int _id = -1; - /// - /// Primary key. - /// - [XmlAttribute] - public int Id - { - get - { - return _id; - } - set - { - _id = value; - } - } + /// + /// Gets or sets primary key. + /// + [XmlAttribute] + public int Id + { + get + { + return this._id; + } + + set + { + this._id = value; + } + } - /// - /// the profiles' effected portal. - /// - [XmlAttribute] - public int PortalId - { - get; - set; - } + /// + /// Gets or sets the profiles' effected portal. + /// + [XmlAttribute] + public int PortalId + { + get; + set; + } - /// - /// profile's name. - /// - [XmlAttribute] - public string Name - { - get; - set; - } + /// + /// Gets or sets profile's name. + /// + [XmlAttribute] + public string Name + { + get; + set; + } - /// - /// the preview device's width. - /// - [XmlAttribute] - public int Width { get; set; } + /// + /// Gets or sets the preview device's width. + /// + [XmlAttribute] + public int Width { get; set; } - /// - /// the preview device's height. - /// - [XmlAttribute] - public int Height { get; set; } + /// + /// Gets or sets the preview device's height. + /// + [XmlAttribute] + public int Height { get; set; } - /// - /// the preview device's user agent. - /// - [XmlAttribute] - public string UserAgent { get; set; } + /// + /// Gets or sets the preview device's user agent. + /// + [XmlAttribute] + public string UserAgent { get; set; } - /// - /// Profile's sort order. - /// - [XmlAttribute] - public int SortOrder { get; set; } + /// + /// Gets or sets profile's sort order. + /// + [XmlAttribute] + public int SortOrder { get; set; } - /// - /// IHydratable.KeyID. - /// - [XmlIgnore] - public int KeyID - { - get - { - return this.Id; - } - set - { - this.Id = value; - } - } + /// + /// Gets or sets iHydratable.KeyID. + /// + [XmlIgnore] + public int KeyID + { + get + { + return this.Id; + } + + set + { + this.Id = value; + } + } - /// - /// Fill the object with data from database. - /// - /// the data reader. - public void Fill(IDataReader dr) - { - this.Id = Convert.ToInt32(dr["Id"]); - this.PortalId = Convert.ToInt32(dr["PortalId"]); - this.Name = dr["Name"].ToString(); - this.Width = Convert.ToInt32(dr["Width"]); - this.Height = Convert.ToInt32(dr["Height"]); - this.UserAgent = dr["UserAgent"].ToString(); - this.SortOrder = Convert.ToInt32(dr["SortOrder"]); - } - } + /// + /// Fill the object with data from database. + /// + /// the data reader. + public void Fill(IDataReader dr) + { + this.Id = Convert.ToInt32(dr["Id"]); + this.PortalId = Convert.ToInt32(dr["PortalId"]); + this.Name = dr["Name"].ToString(); + this.Width = Convert.ToInt32(dr["Width"]); + this.Height = Convert.ToInt32(dr["Height"]); + this.UserAgent = dr["UserAgent"].ToString(); + this.SortOrder = Convert.ToInt32(dr["SortOrder"]); + } + } } diff --git a/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs b/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs index 78bf31c5b3d..012f6d413d4 100644 --- a/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs +++ b/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs @@ -1,165 +1,155 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml.Serialization; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - /// - /// The business of mobile preview profiles. - /// - public class PreviewProfileController : IPreviewProfileController - { - #region "Public Methods" - /// - /// save a preview profile. If profile.Id equals Null.NullInteger(-1), that means need to add a new profile; - /// otherwise will update the profile by profile.Id. - /// - /// profile object. - public void Save(IPreviewProfile profile) - { - Requires.NotNull("The profile can't be null", profile); - - if (profile.Id == Null.NullInteger || profile.SortOrder == 0) - { - profile.SortOrder = GetProfilesByPortal(profile.PortalId, false).Count + 1; - } - - int id = DataProvider.Instance().SavePreviewProfile(profile.Id, - profile.PortalId, - profile.Name, - profile.Width, - profile.Height, - profile.UserAgent, - profile.SortOrder, - UserController.Instance.GetCurrentUserInfo().UserID); - - profile.Id = id; - - var logContent = string.Format("{0} Mobile Preview Profile '{1}'", profile.Id == Null.NullInteger ? "Add" : "Update", profile.Name); - AddLog(logContent); - - ClearCache(profile.PortalId); - } - - /// - /// delete a preview profile. - /// - /// Portal's id. - /// the profile's id. - public void Delete(int portalId, int id) - { - var delProfile = GetProfileById(portalId, id); - if (delProfile != null) - { - //update the list order - GetProfilesByPortal(portalId).Where(p => p.SortOrder > delProfile.SortOrder).ToList().ForEach(p => - { - p.SortOrder--; - Save(p); - }); - DataProvider.Instance().DeletePreviewProfile(id); - - var logContent = string.Format("Delete Mobile Preview Profile '{0}'", id); - AddLog(logContent); - - ClearCache(portalId); - } - } - - /// - /// get a preview profiles list for portal. - /// - /// portal id. - /// List of preview profile. - public IList GetProfilesByPortal(int portalId) - { - return GetProfilesByPortal(portalId, true); - } - - /// - /// get a specific preview profile by id. - /// - /// the profile belong's portal. - /// profile's id. - /// profile object. - public IPreviewProfile GetProfileById(int portalId, int id) - { - return GetProfilesByPortal(portalId).Where(r => r.Id == id).FirstOrDefault(); - } - - #endregion - - #region "Private Methods" - - private IList GetProfilesByPortal(int portalId, bool addDefault) - { - string cacheKey = string.Format(DataCache.PreviewProfilesCacheKey, portalId); - var cacheArg = new CacheItemArgs(cacheKey, DataCache.PreviewProfilesCacheTimeOut, DataCache.PreviewProfilesCachePriority, portalId, addDefault); - return CBO.GetCachedObject>(cacheArg, GetProfilesByPortalIdCallBack); - } - - private IList GetProfilesByPortalIdCallBack(CacheItemArgs cacheItemArgs) - { - int portalId = (int)cacheItemArgs.ParamList[0]; - bool addDefault = (bool)cacheItemArgs.ParamList[1]; - - var profiles = CBO.FillCollection(DataProvider.Instance().GetPreviewProfiles(portalId)); - if (profiles.Count == 0 && addDefault) - { - profiles = CreateDefaultDevices(portalId); - } - - return profiles.Cast().ToList(); - } - - private void ClearCache(int portalId) - { - DataCache.RemoveCache(string.Format(DataCache.PreviewProfilesCacheKey, portalId)); - } - - private void AddLog(string logContent) - { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Xml.Serialization; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Log.EventLog; + + /// + /// The business of mobile preview profiles. + /// + public class PreviewProfileController : IPreviewProfileController + { + /// + /// save a preview profile. If profile.Id equals Null.NullInteger(-1), that means need to add a new profile; + /// otherwise will update the profile by profile.Id. + /// + /// profile object. + public void Save(IPreviewProfile profile) + { + Requires.NotNull("The profile can't be null", profile); + + if (profile.Id == Null.NullInteger || profile.SortOrder == 0) + { + profile.SortOrder = this.GetProfilesByPortal(profile.PortalId, false).Count + 1; + } + + int id = DataProvider.Instance().SavePreviewProfile( + profile.Id, + profile.PortalId, + profile.Name, + profile.Width, + profile.Height, + profile.UserAgent, + profile.SortOrder, + UserController.Instance.GetCurrentUserInfo().UserID); + + profile.Id = id; + + var logContent = string.Format("{0} Mobile Preview Profile '{1}'", profile.Id == Null.NullInteger ? "Add" : "Update", profile.Name); + this.AddLog(logContent); + + this.ClearCache(profile.PortalId); + } + + /// + /// delete a preview profile. + /// + /// Portal's id. + /// the profile's id. + public void Delete(int portalId, int id) + { + var delProfile = this.GetProfileById(portalId, id); + if (delProfile != null) + { + // update the list order + this.GetProfilesByPortal(portalId).Where(p => p.SortOrder > delProfile.SortOrder).ToList().ForEach(p => + { + p.SortOrder--; + this.Save(p); + }); + DataProvider.Instance().DeletePreviewProfile(id); + + var logContent = string.Format("Delete Mobile Preview Profile '{0}'", id); + this.AddLog(logContent); + + this.ClearCache(portalId); + } + } + + /// + /// get a preview profiles list for portal. + /// + /// portal id. + /// List of preview profile. + public IList GetProfilesByPortal(int portalId) + { + return this.GetProfilesByPortal(portalId, true); + } + + /// + /// get a specific preview profile by id. + /// + /// the profile belong's portal. + /// profile's id. + /// profile object. + public IPreviewProfile GetProfileById(int portalId, int id) + { + return this.GetProfilesByPortal(portalId).Where(r => r.Id == id).FirstOrDefault(); + } + + private IList GetProfilesByPortal(int portalId, bool addDefault) + { + string cacheKey = string.Format(DataCache.PreviewProfilesCacheKey, portalId); + var cacheArg = new CacheItemArgs(cacheKey, DataCache.PreviewProfilesCacheTimeOut, DataCache.PreviewProfilesCachePriority, portalId, addDefault); + return CBO.GetCachedObject>(cacheArg, this.GetProfilesByPortalIdCallBack); + } + + private IList GetProfilesByPortalIdCallBack(CacheItemArgs cacheItemArgs) + { + int portalId = (int)cacheItemArgs.ParamList[0]; + bool addDefault = (bool)cacheItemArgs.ParamList[1]; + + var profiles = CBO.FillCollection(DataProvider.Instance().GetPreviewProfiles(portalId)); + if (profiles.Count == 0 && addDefault) + { + profiles = this.CreateDefaultDevices(portalId); + } + + return profiles.Cast().ToList(); + } + + private void ClearCache(int portalId) + { + DataCache.RemoveCache(string.Format(DataCache.PreviewProfilesCacheKey, portalId)); + } + + private void AddLog(string logContent) + { EventLogController.Instance.AddLog("Message", logContent, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.ADMIN_ALERT); - } - - - private List CreateDefaultDevices(int portalId) - { - string defaultPreviewProfiles; + } + + private List CreateDefaultDevices(int portalId) + { + string defaultPreviewProfiles; var settings = PortalController.Instance.GetPortalSettings(portalId); - List profiles = new List(); + List profiles = new List(); - if (!settings.TryGetValue("DefPreviewProfiles_Created", out defaultPreviewProfiles) || defaultPreviewProfiles != DotNetNukeContext.Current.Application.Name) - { - try - { - var defaultDeviceDBPath = Config.GetSetting("DefaultDevicesDatabase"); + if (!settings.TryGetValue("DefPreviewProfiles_Created", out defaultPreviewProfiles) || defaultPreviewProfiles != DotNetNukeContext.Current.Application.Name) + { + try + { + var defaultDeviceDBPath = Config.GetSetting("DefaultDevicesDatabase"); if (!string.IsNullOrEmpty(defaultDeviceDBPath)) { var dataPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, defaultDeviceDBPath); if (!string.IsNullOrEmpty(dataPath) && File.Exists(dataPath)) { - var serializer = new XmlSerializer(typeof (List)); - profiles = (List) serializer.Deserialize(File.OpenRead(dataPath)); + var serializer = new XmlSerializer(typeof(List)); + profiles = (List)serializer.Deserialize(File.OpenRead(dataPath)); if (profiles != null) { @@ -167,22 +157,21 @@ private List CreateDefaultDevices(int portalId) { p.PortalId = portalId; - Save(p); + this.Save(p); }); } } } - PortalController.UpdatePortalSetting(portalId, "DefPreviewProfiles_Created", DotNetNukeContext.Current.Application.Name); - } - catch (Exception ex) - { - Exceptions.Exceptions.LogException(ex); - } - } - - return profiles; - } - #endregion - } + PortalController.UpdatePortalSetting(portalId, "DefPreviewProfiles_Created", DotNetNukeContext.Current.Application.Name); + } + catch (Exception ex) + { + Exceptions.Exceptions.LogException(ex); + } + } + + return profiles; + } + } } diff --git a/DNN Platform/Library/Services/Mobile/Redirection.cs b/DNN Platform/Library/Services/Mobile/Redirection.cs index f0f052685fb..2b999f40065 100644 --- a/DNN Platform/Library/Services/Mobile/Redirection.cs +++ b/DNN Platform/Library/Services/Mobile/Redirection.cs @@ -1,169 +1,167 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.ComponentModel; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + [Serializable] - public class Redirection : IRedirection, IHydratable - { - private int _id = -1; + public class Redirection : IRedirection, IHydratable + { + private int _id = -1; - /// - /// Redirection's primary key. - /// - public int Id - { - get - { - return _id; - } - set - { - _id = value; - _matchRules = null; - } - } + [XmlIgnore] + private IList _matchRules; + + /// + /// Gets or sets redirection's primary key. + /// + public int Id + { + get + { + return this._id; + } + + set + { + this._id = value; + this._matchRules = null; + } + } /// - /// The portal Redirection is belong to. - /// + /// Gets or sets the portal Redirection is belong to. + ///
    [XmlAttribute] public int PortalId { get; set; } - + /// - /// Redirection name. - /// + /// Gets or sets redirection name. + /// [XmlAttribute] public string Name { get; set; } - - /// - /// The redirection's match source tab. if this value is Null.NullInteger(-1) means should redirect when request the whole current portal; - /// otherwise means this redirection will be available for the specific tab. - /// + + /// + /// Gets or sets the redirection's match source tab. if this value is Null.NullInteger(-1) means should redirect when request the whole current portal; + /// otherwise means this redirection will be available for the specific tab. + /// + [XmlAttribute] + public int SourceTabId { get; set; } + + /// + /// Gets or sets a value indicating whether this value will be available when SourceTabId have a specific value, in that way when this value is true, page will rediect + /// to target when request source tab and all child tabs under source tab. + /// [XmlAttribute] - public int SourceTabId { get; set; } + public bool IncludeChildTabs { get; set; } - /// - /// This value will be available when SourceTabId have a specific value, in that way when this value is true, page will rediect - /// to target when request source tab and all child tabs under source tab. - /// - [XmlAttribute] - public bool IncludeChildTabs { get; set; } - - /// - /// Redirection Type: Mobile, Tablet, Both or Other. - /// + /// + /// Gets or sets redirection Type: Mobile, Tablet, Both or Other. + /// [XmlAttribute] public RedirectionType Type { get; set; } - - [XmlIgnore] - private IList _matchRules; - /// - /// When redirection type is RedirectionType.Other, should use this collection to match the request by capability info. - /// + /// + /// Gets or sets when redirection type is RedirectionType.Other, should use this collection to match the request by capability info. + /// [XmlIgnore] - public IList MatchRules - { - get - { - if (_matchRules == null) - { - if (_id == Null.NullInteger) - { - _matchRules = new List(); - } - else - { - //get from database - _matchRules = CBO.FillCollection(DataProvider.Instance().GetRedirectionRules(this.Id)).Cast().ToList(); - } - } + public IList MatchRules + { + get + { + if (this._matchRules == null) + { + if (this._id == Null.NullInteger) + { + this._matchRules = new List(); + } + else + { + // get from database + this._matchRules = CBO.FillCollection(DataProvider.Instance().GetRedirectionRules(this.Id)).Cast().ToList(); + } + } - return _matchRules; - } - set - { - _matchRules = value; - } - } + return this._matchRules; + } + + set + { + this._matchRules = value; + } + } - /// - /// Redirection's target type, should be: Portal, Tab, Url - /// + /// + /// Gets or sets redirection's target type, should be: Portal, Tab, Url. + /// [XmlAttribute] - public TargetType TargetType { get; set; } - - /// - /// the redirection's target value, this value will determine by TargetType as: - /// - /// TargetType.Portal: this value should be a portal id. - /// TargetType.Tab: this value should be a tab id. - /// TargetType.Url: this value should be a valid url. - /// - /// + public TargetType TargetType { get; set; } + + /// + /// Gets or sets the redirection's target value, this value will determine by TargetType as: + /// + /// TargetType.Portal: this value should be a portal id. + /// TargetType.Tab: this value should be a tab id. + /// TargetType.Url: this value should be a valid url. + /// + /// [XmlAttribute] public object TargetValue { get; set; } - - /// - /// Whether this redirection is available. - /// + + /// + /// Gets or sets a value indicating whether whether this redirection is available. + /// [XmlAttribute] - public bool Enabled { get; set; } - - /// - /// Redirection's piority. - /// + public bool Enabled { get; set; } + + /// + /// Gets or sets redirection's piority. + /// [XmlAttribute] - public int SortOrder { get; set; } - - /// - /// IHydratable.KeyID. - /// + public int SortOrder { get; set; } + + /// + /// Gets or sets iHydratable.KeyID. + /// [XmlIgnore] - public int KeyID - { - get - { - return this.Id; - } - set - { - this.Id = value; - } - } + public int KeyID + { + get + { + return this.Id; + } + + set + { + this.Id = value; + } + } - /// - /// Fill the object with data from database. - /// - /// the data reader. - public void Fill(System.Data.IDataReader dr) - { - this.Id = Convert.ToInt32(dr["Id"]); - this.PortalId = Convert.ToInt32(dr["PortalId"]); - this.Name = dr["Name"].ToString(); - this.Type = (RedirectionType)Convert.ToInt32(dr["Type"]); - this.SourceTabId = Convert.ToInt32(dr["SourceTabId"]); - this.IncludeChildTabs = Convert.ToBoolean(dr["IncludeChildTabs"]); - this.SortOrder = Convert.ToInt32(dr["SortOrder"]); - this.TargetType = (TargetType)Convert.ToInt32(dr["TargetType"]); - this.TargetValue = dr["TargetValue"]; - this.Enabled = Convert.ToBoolean(dr["Enabled"]); - } - } + /// + /// Fill the object with data from database. + /// + /// the data reader. + public void Fill(System.Data.IDataReader dr) + { + this.Id = Convert.ToInt32(dr["Id"]); + this.PortalId = Convert.ToInt32(dr["PortalId"]); + this.Name = dr["Name"].ToString(); + this.Type = (RedirectionType)Convert.ToInt32(dr["Type"]); + this.SourceTabId = Convert.ToInt32(dr["SourceTabId"]); + this.IncludeChildTabs = Convert.ToBoolean(dr["IncludeChildTabs"]); + this.SortOrder = Convert.ToInt32(dr["SortOrder"]); + this.TargetType = (TargetType)Convert.ToInt32(dr["TargetType"]); + this.TargetValue = dr["TargetValue"]; + this.Enabled = Convert.ToBoolean(dr["Enabled"]); + } + } } diff --git a/DNN Platform/Library/Services/Mobile/RedirectionController.cs b/DNN Platform/Library/Services/Mobile/RedirectionController.cs index f3a734bb09b..e565d1aef44 100644 --- a/DNN Platform/Library/Services/Mobile/RedirectionController.cs +++ b/DNN Platform/Library/Services/Mobile/RedirectionController.cs @@ -1,131 +1,126 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.ClientCapability; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public class RedirectionController : IRedirectionController + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.ClientCapability; + using DotNetNuke.Services.Log.EventLog; + + public class RedirectionController : IRedirectionController { - #region Constants private const string DisableMobileRedirectCookieName = "disablemobileredirect"; - private const string DisableRedirectPresistCookieName = "disableredirectpresist"; - private const string DisableMobileRedirectQueryStringName = "nomo"; //google uses the same name nomo=1 means do not redirect to mobile - #endregion - - #region Private Properties + private const string DisableRedirectPresistCookieName = "disableredirectpresist"; + private const string DisableMobileRedirectQueryStringName = "nomo"; // google uses the same name nomo=1 means do not redirect to mobile private const string UrlsCacheKey = "MobileRedirectAllUrls"; - private const string RedirectionUrlCacheKey = "RedirectionUrl_{0}_{1}_{2}"; - private const string FullSiteUrlCacheKey = "FullSiteUrl_{0}_{1}"; - private const string MobileSiteUrlCacheKey = "MobileSiteUrl_{0}_{1}"; - private const int UrlsCacheTimeout = 60; - - #endregion + private const string RedirectionUrlCacheKey = "RedirectionUrl_{0}_{1}_{2}"; + private const string FullSiteUrlCacheKey = "FullSiteUrl_{0}_{1}"; + private const string MobileSiteUrlCacheKey = "MobileSiteUrl_{0}_{1}"; + private const int UrlsCacheTimeout = 60; - #region Public Methods + private string AllRedirectionsCacheKey + { + get + { + return string.Format(DataCache.RedirectionsCacheKey, "All"); + } + } /// /// Is Redirection Allowed for the session. Method analyzes the query string for special parameters to enable / disable redirects. /// Cookie is created to temporarily store those parameters so that they remain available till the interactions are active. /// - /// boolean - True if redirection - /// app - HttpApplication. Request and Response properties are used + /// boolean - True if redirection. + /// app - HttpApplication. Request and Response properties are used. public bool IsRedirectAllowedForTheSession(HttpApplication app) { bool allowed = true; - //Check for the existence of special query string to force enable / disable of redirect + // Check for the existence of special query string to force enable / disable of redirect if (app.Request.QueryString[DisableMobileRedirectQueryStringName] != null) { int val; if (int.TryParse(app.Request.QueryString[DisableMobileRedirectQueryStringName], out val)) { - if (val == 0) //forced enable. clear any cookie previously set + if (val == 0) // forced enable. clear any cookie previously set { if (app.Response.Cookies[DisableMobileRedirectCookieName] != null) { var cookie = new HttpCookie(DisableMobileRedirectCookieName) { Expires = DateTime.Now.AddMinutes(-1), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; - app.Response.Cookies.Add(cookie); + app.Response.Cookies.Add(cookie); } - if (app.Response.Cookies[DisableRedirectPresistCookieName] != null) - { - var cookie = new HttpCookie(DisableRedirectPresistCookieName) - { - Expires = DateTime.Now.AddMinutes(-1), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") - }; - app.Response.Cookies.Add(cookie); - } + if (app.Response.Cookies[DisableRedirectPresistCookieName] != null) + { + var cookie = new HttpCookie(DisableRedirectPresistCookieName) + { + Expires = DateTime.Now.AddMinutes(-1), + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }; + app.Response.Cookies.Add(cookie); + } } - else if (val == 1) //forced disable. need to setup cookie + else if (val == 1) // forced disable. need to setup cookie { allowed = false; - } - } + } + } } - else if (app.Request.Cookies[DisableMobileRedirectCookieName] != null && app.Request.Cookies[DisableRedirectPresistCookieName] != null) //check for cookie + else if (app.Request.Cookies[DisableMobileRedirectCookieName] != null && app.Request.Cookies[DisableRedirectPresistCookieName] != null) // check for cookie { allowed = false; } - - if (!allowed) //redirect is not setup to be allowed, keep the cookie alive + if (!allowed) // redirect is not setup to be allowed, keep the cookie alive { - //this cookie is set to re-enable redirect after 20 minutes - var presistCookie = new HttpCookie(DisableRedirectPresistCookieName) - { - Expires = DateTime.Now.AddMinutes(20), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") - }; + // this cookie is set to re-enable redirect after 20 minutes + var presistCookie = new HttpCookie(DisableRedirectPresistCookieName) + { + Expires = DateTime.Now.AddMinutes(20), + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }; app.Response.Cookies.Add(presistCookie); - //this cookie is set to re-enable redirect after close browser. + // this cookie is set to re-enable redirect after close browser. var cookie = new HttpCookie(DisableMobileRedirectCookieName) { - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; - app.Response.Cookies.Add(cookie); + app.Response.Cookies.Add(cookie); } return allowed; } - - /// - /// Get Redirection Url based on UserAgent. + + /// + /// Get Redirection Url based on UserAgent. /// - /// string - Empty if redirection rules are not defined or no match found + /// string - Empty if redirection rules are not defined or no match found. /// User Agent - used for client capability detection. public string GetRedirectUrl(string userAgent) - { + { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (portalSettings != null && portalSettings.ActiveTab != null) { - string redirectUrl = GetRedirectUrl(userAgent, portalSettings.PortalId, portalSettings.ActiveTab.TabID); + string redirectUrl = this.GetRedirectUrl(userAgent, portalSettings.PortalId, portalSettings.ActiveTab.TabID); if (!string.IsNullOrEmpty(redirectUrl) && string.Compare(redirectUrl, portalSettings.ActiveTab.FullUrl, true, CultureInfo.InvariantCulture) != 0) { return redirectUrl; @@ -136,200 +131,209 @@ public string GetRedirectUrl(string userAgent) } /// - /// Get Redirection Url based on Http Context and Portal Id. + /// Get Redirection Url based on Http Context and Portal Id. /// - /// string - Empty if redirection rules are not defined or no match found + /// string - Empty if redirection rules are not defined or no match found. /// User Agent - used for client capability detection. /// Portal Id from which Redirection Rules should be applied. - /// Current Tab Id that needs to be evaluated. + /// Current Tab Id that needs to be evaluated. public string GetRedirectUrl(string userAgent, int portalId, int currentTabId) { Requires.NotNullOrEmpty("userAgent", userAgent); - string redirectUrl = string.Empty; + string redirectUrl = string.Empty; - IList redirections = GetRedirectionsByPortal(portalId); - //check for redirect only when redirect rules are defined - if (redirections == null || redirections.Count == 0) - { + IList redirections = this.GetRedirectionsByPortal(portalId); + + // check for redirect only when redirect rules are defined + if (redirections == null || redirections.Count == 0) + { return redirectUrl; - } + } - //try to get content from cache - var cacheKey = string.Format(RedirectionUrlCacheKey, userAgent, portalId, currentTabId); - redirectUrl = GetUrlFromCache(cacheKey); - if (!string.IsNullOrEmpty(redirectUrl)) + // try to get content from cache + var cacheKey = string.Format(RedirectionUrlCacheKey, userAgent, portalId, currentTabId); + redirectUrl = this.GetUrlFromCache(cacheKey); + if (!string.IsNullOrEmpty(redirectUrl)) { return redirectUrl; } IClientCapability clientCapability = null; - - foreach (var redirection in redirections) - { - if (redirection.Enabled) - { - bool checkFurther = false; - //redirection is based on source tab - if (redirection.SourceTabId != Null.NullInteger) - { - //source tab matches current tab - if (currentTabId == redirection.SourceTabId) - { - checkFurther = true; - } - //is child tabs to be included as well - else if (redirection.IncludeChildTabs) - { - //Get all the descendents of the source tab and find out if current tab is in source tab's hierarchy or not. + + foreach (var redirection in redirections) + { + if (redirection.Enabled) + { + bool checkFurther = false; + + // redirection is based on source tab + if (redirection.SourceTabId != Null.NullInteger) + { + // source tab matches current tab + if (currentTabId == redirection.SourceTabId) + { + checkFurther = true; + } + + // is child tabs to be included as well + else if (redirection.IncludeChildTabs) + { + // Get all the descendents of the source tab and find out if current tab is in source tab's hierarchy or not. foreach (var childTab in TabController.Instance.GetTabsByPortal(portalId).DescendentsOf(redirection.SourceTabId)) - { - if (childTab.TabID == currentTabId) - { - checkFurther = true; - break; - } - } - } - } - //redirection is based on portal - else if (redirection.SourceTabId == Null.NullInteger) - { - checkFurther = true; - } - - if (checkFurther) - { - if (clientCapability == null) - { + { + if (childTab.TabID == currentTabId) + { + checkFurther = true; + break; + } + } + } + } + + // redirection is based on portal + else if (redirection.SourceTabId == Null.NullInteger) + { + checkFurther = true; + } + + if (checkFurther) + { + if (clientCapability == null) + { clientCapability = ClientCapabilityProvider.Instance().GetClientCapability(userAgent); - } - //check if client capability matches with this rule - if (DoesCapabilityMatchWithRule(clientCapability, redirection)) - { - //find the redirect url - redirectUrl = GetRedirectUrlFromRule(redirection, portalId, currentTabId); - - //update cache content - SetUrlInCache(cacheKey, redirectUrl); - break; - } - } - } - } - - return redirectUrl; + } + + // check if client capability matches with this rule + if (this.DoesCapabilityMatchWithRule(clientCapability, redirection)) + { + // find the redirect url + redirectUrl = this.GetRedirectUrlFromRule(redirection, portalId, currentTabId); + + // update cache content + this.SetUrlInCache(cacheKey, redirectUrl); + break; + } + } + } + } + + return redirectUrl; } /// - /// Get Url for the equivalent full site based on the current page of the mobile site + /// Get Url for the equivalent full site based on the current page of the mobile site. /// - /// string - Empty if redirection rules are not defined or no match found + /// string - Empty if redirection rules are not defined or no match found. public string GetFullSiteUrl() { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (portalSettings != null && portalSettings.ActiveTab != null) { - string fullSiteUrl = GetFullSiteUrl(portalSettings.PortalId, portalSettings.ActiveTab.TabID); + string fullSiteUrl = this.GetFullSiteUrl(portalSettings.PortalId, portalSettings.ActiveTab.TabID); if (!string.IsNullOrEmpty(fullSiteUrl) && string.Compare(fullSiteUrl, portalSettings.ActiveTab.FullUrl, true, CultureInfo.InvariantCulture) != 0) - { + { return fullSiteUrl; } } - return string.Empty; + return string.Empty; } /// - /// Get Url for the equivalent full site based on the current page of the mobile site + /// Get Url for the equivalent full site based on the current page of the mobile site. /// - /// string - Empty if redirection rules are not defined or no match found + /// string - Empty if redirection rules are not defined or no match found. /// Portal Id from which Redirection Rules should be applied. - /// Current Tab Id that needs to be evaluated. + /// Current Tab Id that needs to be evaluated. public string GetFullSiteUrl(int portalId, int currentTabId) { string fullSiteUrl = string.Empty; - IList redirections = GetAllRedirections(); - //check for redirect only when redirect rules are defined + IList redirections = this.GetAllRedirections(); + + // check for redirect only when redirect rules are defined if (redirections == null || redirections.Count == 0) { return fullSiteUrl; } - //try to get content from cache - var cacheKey = string.Format(FullSiteUrlCacheKey, portalId, currentTabId); - fullSiteUrl = GetUrlFromCache(cacheKey); + // try to get content from cache + var cacheKey = string.Format(FullSiteUrlCacheKey, portalId, currentTabId); + fullSiteUrl = this.GetUrlFromCache(cacheKey); if (!string.IsNullOrEmpty(fullSiteUrl)) { return fullSiteUrl; - } - - bool foundRule = false; - foreach (var redirection in redirections) - { - if (redirection.Enabled) - { - if (redirection.TargetType == TargetType.Tab) //page within same site - { - int targetTabId = int.Parse(redirection.TargetValue.ToString()); - if (targetTabId == currentTabId) //target tab is same as current tab - { - foundRule = true; - } - } - else if (redirection.TargetType == TargetType.Portal) //home page of another portal - { - int targetPortalId = int.Parse(redirection.TargetValue.ToString()); - if (targetPortalId == portalId) //target portal is same as current portal - { - foundRule = true; - } - } - - //found the rule, let's find the url now - if (foundRule) - { - ////redirection is based on tab - //Following are being commented as NavigateURL method does not return correct url for a tab in a different portal - //always point to the home page of the other portal - //if (redirection.SourceTabId != Null.NullInteger) - //{ - // fullSiteUrl = Globals.NavigateURL(redirection.SourceTabId); - //} - //else //redirection is based on portal - { - var portalSettings = new PortalSettings(redirection.PortalId); - if (portalSettings.HomeTabId != Null.NullInteger && portalSettings.HomeTabId != currentTabId) //ensure it's not redirecting to itself - { - fullSiteUrl = GetPortalHomePageUrl(portalSettings); - } - } - break; - } - } - } - - //append special query string + } + + bool foundRule = false; + foreach (var redirection in redirections) + { + if (redirection.Enabled) + { + if (redirection.TargetType == TargetType.Tab) // page within same site + { + int targetTabId = int.Parse(redirection.TargetValue.ToString()); + if (targetTabId == currentTabId) // target tab is same as current tab + { + foundRule = true; + } + } + else if (redirection.TargetType == TargetType.Portal) // home page of another portal + { + int targetPortalId = int.Parse(redirection.TargetValue.ToString()); + if (targetPortalId == portalId) // target portal is same as current portal + { + foundRule = true; + } + } + + // found the rule, let's find the url now + if (foundRule) + { + ////redirection is based on tab + // Following are being commented as NavigateURL method does not return correct url for a tab in a different portal + // always point to the home page of the other portal + // if (redirection.SourceTabId != Null.NullInteger) + // { + // fullSiteUrl = Globals.NavigateURL(redirection.SourceTabId); + // } + // else //redirection is based on portal + { + var portalSettings = new PortalSettings(redirection.PortalId); + if (portalSettings.HomeTabId != Null.NullInteger && portalSettings.HomeTabId != currentTabId) // ensure it's not redirecting to itself + { + fullSiteUrl = this.GetPortalHomePageUrl(portalSettings); + } + } + + break; + } + } + } + + // append special query string if (!string.IsNullOrEmpty(fullSiteUrl)) + { fullSiteUrl += string.Format("{0}{1}=1", fullSiteUrl.Contains("?") ? "&" : "?", DisableMobileRedirectQueryStringName); + } - //update cache content - SetUrlInCache(cacheKey, fullSiteUrl); + // update cache content + this.SetUrlInCache(cacheKey, fullSiteUrl); - return fullSiteUrl; + return fullSiteUrl; } /// - /// Get Url for the equivalent mobile site based on the current page of the full site + /// Get Url for the equivalent mobile site based on the current page of the full site. /// - /// string - Empty if redirection rules are not defined or no match found + /// string - Empty if redirection rules are not defined or no match found. public string GetMobileSiteUrl() { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (portalSettings != null && portalSettings.ActiveTab != null) { - string fullSiteUrl = GetMobileSiteUrl(portalSettings.PortalId, portalSettings.ActiveTab.TabID); + string fullSiteUrl = this.GetMobileSiteUrl(portalSettings.PortalId, portalSettings.ActiveTab.TabID); if (!string.IsNullOrEmpty(fullSiteUrl) && string.Compare(fullSiteUrl, portalSettings.ActiveTab.FullUrl, true, CultureInfo.InvariantCulture) != 0) { return fullSiteUrl; @@ -340,96 +344,100 @@ public string GetMobileSiteUrl() } /// - /// Get Url for the equivalent mobile site based on the current page of the full site + /// Get Url for the equivalent mobile site based on the current page of the full site. /// - /// string - Empty if redirection rules are not defined or no match found + /// string - Empty if redirection rules are not defined or no match found. /// Portal Id from which Redirection Rules should be applied. - /// Current Tab Id that needs to be evaluated. + /// Current Tab Id that needs to be evaluated. public string GetMobileSiteUrl(int portalId, int currentTabId) { string mobileSiteUrl = string.Empty; - IList redirections = GetRedirectionsByPortal(portalId); - //check for redirect only when redirect rules are defined + IList redirections = this.GetRedirectionsByPortal(portalId); + + // check for redirect only when redirect rules are defined if (redirections == null || redirections.Count == 0) { return mobileSiteUrl; } - //try to get content from cache - var cacheKey = string.Format(MobileSiteUrlCacheKey, portalId, currentTabId); - mobileSiteUrl = GetUrlFromCache(cacheKey); + // try to get content from cache + var cacheKey = string.Format(MobileSiteUrlCacheKey, portalId, currentTabId); + mobileSiteUrl = this.GetUrlFromCache(cacheKey); if (!string.IsNullOrEmpty(mobileSiteUrl)) { return mobileSiteUrl; } - //let's try to find if this tab has any specifc rules - foreach (var redirection in redirections) - { - if (redirection.Enabled) - { - if (redirection.SourceTabId != Null.NullInteger && currentTabId == redirection.SourceTabId) - { - mobileSiteUrl = GetRedirectUrlFromRule(redirection, portalId, currentTabId); - break; - } - } - } - - //tab has no specific rule, we can select the first rule - if (string.IsNullOrEmpty(mobileSiteUrl)) - { - var firstRedirection = redirections.FirstOrDefault(r => r.Enabled); - if (firstRedirection != null) - { - mobileSiteUrl = GetRedirectUrlFromRule(firstRedirection, portalId, currentTabId); - } - } - - //append special query string + // let's try to find if this tab has any specifc rules + foreach (var redirection in redirections) + { + if (redirection.Enabled) + { + if (redirection.SourceTabId != Null.NullInteger && currentTabId == redirection.SourceTabId) + { + mobileSiteUrl = this.GetRedirectUrlFromRule(redirection, portalId, currentTabId); + break; + } + } + } + + // tab has no specific rule, we can select the first rule + if (string.IsNullOrEmpty(mobileSiteUrl)) + { + var firstRedirection = redirections.FirstOrDefault(r => r.Enabled); + if (firstRedirection != null) + { + mobileSiteUrl = this.GetRedirectUrlFromRule(firstRedirection, portalId, currentTabId); + } + } + + // append special query string if (!string.IsNullOrEmpty(mobileSiteUrl)) - mobileSiteUrl += string.Format("{0}{1}=0", mobileSiteUrl.Contains("?") ? "&" : "?", DisableMobileRedirectQueryStringName); + { + mobileSiteUrl += string.Format("{0}{1}=0", mobileSiteUrl.Contains("?") ? "&" : "?", DisableMobileRedirectQueryStringName); + } - //update cache content - SetUrlInCache(cacheKey, mobileSiteUrl); + // update cache content + this.SetUrlInCache(cacheKey, mobileSiteUrl); - return mobileSiteUrl; + return mobileSiteUrl; } - /// - /// save a redirection. If redirection.Id equals Null.NullInteger(-1), that means need to add a new redirection; - /// otherwise will update the redirection by redirection.Id. - /// - /// redirection object. - public void Save(IRedirection redirection) - { - if(redirection.Id == Null.NullInteger || redirection.SortOrder == 0) - { - redirection.SortOrder = GetRedirectionsByPortal(redirection.PortalId).Count + 1; - } - - int id = DataProvider.Instance().SaveRedirection(redirection.Id, - redirection.PortalId, - redirection.Name, - (int) redirection.Type, - redirection.SortOrder, - redirection.SourceTabId, - redirection.IncludeChildTabs, - (int) redirection.TargetType, - redirection.TargetValue, - redirection.Enabled, - UserController.Instance.GetCurrentUserInfo().UserID); - - foreach (IMatchRule rule in redirection.MatchRules) - { - DataProvider.Instance().SaveRedirectionRule(rule.Id, id, rule.Capability, rule.Expression); - } + /// + /// save a redirection. If redirection.Id equals Null.NullInteger(-1), that means need to add a new redirection; + /// otherwise will update the redirection by redirection.Id. + /// + /// redirection object. + public void Save(IRedirection redirection) + { + if (redirection.Id == Null.NullInteger || redirection.SortOrder == 0) + { + redirection.SortOrder = this.GetRedirectionsByPortal(redirection.PortalId).Count + 1; + } + + int id = DataProvider.Instance().SaveRedirection( + redirection.Id, + redirection.PortalId, + redirection.Name, + (int)redirection.Type, + redirection.SortOrder, + redirection.SourceTabId, + redirection.IncludeChildTabs, + (int)redirection.TargetType, + redirection.TargetValue, + redirection.Enabled, + UserController.Instance.GetCurrentUserInfo().UserID); + + foreach (IMatchRule rule in redirection.MatchRules) + { + DataProvider.Instance().SaveRedirectionRule(rule.Id, id, rule.Capability, rule.Expression); + } var logContent = string.Format("'{0}' {1}", redirection.Name, redirection.Id == Null.NullInteger ? "Added" : "Updated"); - AddLog(logContent); + this.AddLog(logContent); - ClearCache(redirection.PortalId); - } + this.ClearCache(redirection.PortalId); + } /// /// Deletes all redirection rules that were set for pages that have been soft or hard deleted. @@ -438,24 +446,24 @@ public void Save(IRedirection redirection) public void PurgeInvalidRedirections(int portalId) { var allTabs = TabController.Instance.GetTabsByPortal(portalId); - var redirects = GetRedirectionsByPortal(portalId); + var redirects = this.GetRedirectionsByPortal(portalId); - //remove rules for deleted source tabs + // remove rules for deleted source tabs foreach (var r in redirects.Where(r => r.SourceTabId != Null.NullInteger && allTabs.Where(t => t.Key == r.SourceTabId).Count() < 1)) { - Delete(portalId, r.Id); + this.Delete(portalId, r.Id); } - - //remove rules for deleted target tabs - redirects = GetRedirectionsByPortal(portalId); //fresh get of rules in case some were deleted above + + // remove rules for deleted target tabs + redirects = this.GetRedirectionsByPortal(portalId); // fresh get of rules in case some were deleted above foreach (var r in redirects.Where(r => r.TargetType == TargetType.Tab && allTabs.Where(t => t.Key == int.Parse(r.TargetValue.ToString())).Count() < 1)) { - Delete(portalId, r.Id); + this.Delete(portalId, r.Id); } - //remove rules for deleted target portals - redirects = GetRedirectionsByPortal(portalId); //fresh get of rules in case some were deleted above - var allPortals = PortalController.Instance.GetPortals(); + // remove rules for deleted target portals + redirects = this.GetRedirectionsByPortal(portalId); // fresh get of rules in case some were deleted above + var allPortals = PortalController.Instance.GetPortals(); foreach (var r in redirects.Where(r => r.TargetType == TargetType.Portal)) { bool found = false; @@ -467,87 +475,90 @@ public void PurgeInvalidRedirections(int portalId) break; } } - if (!found) - Delete(portalId, r.Id); + + if (!found) + { + this.Delete(portalId, r.Id); + } } } - /// - /// delete a redirection. - /// - /// Portal's id. - /// the redirection's id. - public void Delete(int portalId, int id) - { - var delRedirection = GetRedirectionById(portalId, id); - if (delRedirection != null) - { - //update the list order - GetRedirectionsByPortal(portalId).Where(p => p.SortOrder > delRedirection.SortOrder).ToList().ForEach(p => - { - p.SortOrder--; - Save(p); - }); - DataProvider.Instance().DeleteRedirection(id); - - var logContent = string.Format("Id '{0}' Deleted", id); - AddLog(logContent); - - ClearCache(portalId); - } - } - - /// - /// delete a redirection's match rule. - /// - /// Portal's id. - /// the redirection's id. - /// the rule's id. - public void DeleteRule(int portalId, int redirectionId, int ruleId) - { - DataProvider.Instance().DeleteRedirectionRule(ruleId); + /// + /// delete a redirection. + /// + /// Portal's id. + /// the redirection's id. + public void Delete(int portalId, int id) + { + var delRedirection = this.GetRedirectionById(portalId, id); + if (delRedirection != null) + { + // update the list order + this.GetRedirectionsByPortal(portalId).Where(p => p.SortOrder > delRedirection.SortOrder).ToList().ForEach(p => + { + p.SortOrder--; + this.Save(p); + }); + DataProvider.Instance().DeleteRedirection(id); + + var logContent = string.Format("Id '{0}' Deleted", id); + this.AddLog(logContent); + + this.ClearCache(portalId); + } + } + + /// + /// delete a redirection's match rule. + /// + /// Portal's id. + /// the redirection's id. + /// the rule's id. + public void DeleteRule(int portalId, int redirectionId, int ruleId) + { + DataProvider.Instance().DeleteRedirectionRule(ruleId); var logContent = string.Format("Id '{0}' Removed from Redirection Id '{1}'", ruleId, redirectionId); - AddLog(logContent); + this.AddLog(logContent); - ClearCache(portalId); - } + this.ClearCache(portalId); + } /// /// get all redirections defined in system. - /// + /// /// List of redirection. public IList GetAllRedirections() - { - var cacheArg = new CacheItemArgs(AllRedirectionsCacheKey, DataCache.RedirectionsCacheTimeOut, DataCache.RedirectionsCachePriority, ""); - return CBO.GetCachedObject>(cacheArg, GetAllRedirectionsCallBack); + { + var cacheArg = new CacheItemArgs(this.AllRedirectionsCacheKey, DataCache.RedirectionsCacheTimeOut, DataCache.RedirectionsCachePriority, string.Empty); + return CBO.GetCachedObject>(cacheArg, this.GetAllRedirectionsCallBack); } - /// - /// get a redirection list for portal. - /// - /// redirection id. - /// List of redirection. - public IList GetRedirectionsByPortal(int portalId) - { - string cacheKey = string.Format(DataCache.RedirectionsCacheKey, portalId); - var cacheArg = new CacheItemArgs(cacheKey, DataCache.RedirectionsCacheTimeOut, DataCache.RedirectionsCachePriority, portalId); - return CBO.GetCachedObject>(cacheArg, GetRedirectionsByPortalCallBack); - } - - /// - /// get a specific redirection by id. - /// - /// the redirection belong's portal. - /// redirection's id. - /// redirection object. - public IRedirection GetRedirectionById(int portalId, int id) - { - return GetRedirectionsByPortal(portalId).Where(r => r.Id == id).FirstOrDefault(); - } + /// + /// get a redirection list for portal. + /// + /// redirection id. + /// List of redirection. + public IList GetRedirectionsByPortal(int portalId) + { + string cacheKey = string.Format(DataCache.RedirectionsCacheKey, portalId); + var cacheArg = new CacheItemArgs(cacheKey, DataCache.RedirectionsCacheTimeOut, DataCache.RedirectionsCachePriority, portalId); + return CBO.GetCachedObject>(cacheArg, this.GetRedirectionsByPortalCallBack); + } + + /// + /// get a specific redirection by id. + /// + /// the redirection belong's portal. + /// redirection's id. + /// redirection object. + public IRedirection GetRedirectionById(int portalId, int id) + { + return this.GetRedirectionsByPortal(portalId).Where(r => r.Id == id).FirstOrDefault(); + } /// - /// returns a target URL for the specific redirection + /// returns a target URL for the specific redirection. /// /// /// @@ -557,14 +568,14 @@ public string GetRedirectUrlFromRule(IRedirection redirection, int portalId, int { string redirectUrl = string.Empty; - if (redirection.TargetType == TargetType.Url) //independent url base + if (redirection.TargetType == TargetType.Url) // independent url base { redirectUrl = redirection.TargetValue.ToString(); } - else if (redirection.TargetType == TargetType.Tab) //page within same site + else if (redirection.TargetType == TargetType.Tab) // page within same site { int targetTabId = int.Parse(redirection.TargetValue.ToString()); - if (targetTabId != currentTabId) //ensure it's not redirecting to itself + if (targetTabId != currentTabId) // ensure it's not redirecting to itself { var tab = TabController.Instance.GetTab(targetTabId, portalId, false); if (tab != null && !tab.IsDeleted) @@ -573,18 +584,18 @@ public string GetRedirectUrlFromRule(IRedirection redirection, int portalId, int } } } - else if (redirection.TargetType == TargetType.Portal) //home page of another portal + else if (redirection.TargetType == TargetType.Portal) // home page of another portal { int targetPortalId = int.Parse(redirection.TargetValue.ToString()); - if (targetPortalId != portalId) //ensure it's not redirecting to itself + if (targetPortalId != portalId) // ensure it's not redirecting to itself { - //check whethter the target portal still exists + // check whethter the target portal still exists if (PortalController.Instance.GetPortals().Cast().Any(p => p.PortalID == targetPortalId)) { var portalSettings = new PortalSettings(targetPortalId); - if (portalSettings.HomeTabId != Null.NullInteger && portalSettings.HomeTabId != currentTabId) //ensure it's not redirecting to itself + if (portalSettings.HomeTabId != Null.NullInteger && portalSettings.HomeTabId != currentTabId) // ensure it's not redirecting to itself { - redirectUrl = GetPortalHomePageUrl(portalSettings); + redirectUrl = this.GetPortalHomePageUrl(portalSettings); } } } @@ -593,19 +604,15 @@ public string GetRedirectUrlFromRule(IRedirection redirection, int portalId, int return redirectUrl; } - #endregion - - #region "Private Methods" - private string GetPortalHomePageUrl(PortalSettings portalSettings) { - return Globals.AddHTTP(portalSettings.DefaultPortalAlias); + return Globals.AddHTTP(portalSettings.DefaultPortalAlias); } - private IList GetAllRedirectionsCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillCollection(DataProvider.Instance().GetAllRedirections()).Cast().ToList(); - } + private IList GetAllRedirectionsCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillCollection(DataProvider.Instance().GetAllRedirections()).Cast().ToList(); + } private IList GetRedirectionsByPortalCallBack(CacheItemArgs cacheItemArgs) { @@ -613,12 +620,12 @@ private IList GetRedirectionsByPortalCallBack(CacheItemArgs cacheI return CBO.FillCollection(DataProvider.Instance().GetRedirections(portalId)).Cast().ToList(); } - private void ClearCache(int portalId) - { - DataCache.RemoveCache(string.Format(DataCache.RedirectionsCacheKey, portalId)); - DataCache.RemoveCache(AllRedirectionsCacheKey); - DataCache.RemoveCache(UrlsCacheKey); - } + private void ClearCache(int portalId) + { + DataCache.RemoveCache(string.Format(DataCache.RedirectionsCacheKey, portalId)); + DataCache.RemoveCache(this.AllRedirectionsCacheKey); + DataCache.RemoveCache(UrlsCacheKey); + } private string GetUrlFromCache(string cacheKey) { @@ -627,13 +634,13 @@ private string GetUrlFromCache(string cacheKey) if (cachedUrls != null) { using (cachedUrls.GetReadLock()) - { + { if (cachedUrls.ContainsKey(cacheKey)) { - return cachedUrls[cacheKey]; - } + return cachedUrls[cacheKey]; + } } - } + } return string.Empty; } @@ -651,6 +658,7 @@ private void SetUrlInCache(string cacheKey, string url) { cachedUrls = new SharedDictionary(); } + using (cachedUrls.GetWriteLock()) { cachedUrls[cacheKey] = url; @@ -659,14 +667,14 @@ private void SetUrlInCache(string cacheKey, string url) DataCache.SetCache(UrlsCacheKey, cachedUrls, TimeSpan.FromMinutes(UrlsCacheTimeout)); } - private void AddLog(string logContent) - { + private void AddLog(string logContent) + { EventLogController.Instance.AddLog("Site Redirection Rule", logContent, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.ADMIN_ALERT); - } + } private bool DoesCapabilityMatchWithRule(IClientCapability clientCapability, IRedirection redirection) { - bool match = false; + bool match = false; if (redirection.Type == RedirectionType.Tablet && clientCapability.IsTablet) { match = true; @@ -681,7 +689,7 @@ private bool DoesCapabilityMatchWithRule(IClientCapability clientCapability, IRe } else if (redirection.Type == RedirectionType.Other) { - //match all the capabilities defined in the rule + // match all the capabilities defined in the rule int matchCount = 0; foreach (IMatchRule rule in redirection.MatchRules) { @@ -693,25 +701,14 @@ private bool DoesCapabilityMatchWithRule(IClientCapability clientCapability, IRe } } } - if(matchCount > 0 && matchCount == redirection.MatchRules.Count) + + if (matchCount > 0 && matchCount == redirection.MatchRules.Count) { match = true; } } - + return match; } - - #endregion - - #region Private Properties - private string AllRedirectionsCacheKey - { - get - { - return string.Format(DataCache.RedirectionsCacheKey, "All"); - } - } - #endregion } } diff --git a/DNN Platform/Library/Services/Mobile/RedirectionType.cs b/DNN Platform/Library/Services/Mobile/RedirectionType.cs index ace340cea8e..794dab71b50 100644 --- a/DNN Platform/Library/Services/Mobile/RedirectionType.cs +++ b/DNN Platform/Library/Services/Mobile/RedirectionType.cs @@ -1,40 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public enum RedirectionType - { - /// - /// Redirect when request from a mobile phone - /// - MobilePhone = 1, + using System; + + public enum RedirectionType + { + /// + /// Redirect when request from a mobile phone + /// + MobilePhone = 1, - /// - /// Redirect when request from a tablet - /// - Tablet = 2, + /// + /// Redirect when request from a tablet + /// + Tablet = 2, /// /// Redirect when request from either a mobile phone or a tablet /// AllMobile = 3, - /// - /// Redirect when request from some unknown device, should be determine by match rules; - /// - Other = 4, + /// + /// Redirect when request from some unknown device, should be determine by match rules; + /// + Other = 4, - /// - /// Redirect when request from a smart phone - /// - SmartPhone = 5 - } + /// + /// Redirect when request from a smart phone + /// + SmartPhone = 5, + } } diff --git a/DNN Platform/Library/Services/Mobile/TargetType.cs b/DNN Platform/Library/Services/Mobile/TargetType.cs index 0dba1018371..73c3ac2a87a 100644 --- a/DNN Platform/Library/Services/Mobile/TargetType.cs +++ b/DNN Platform/Library/Services/Mobile/TargetType.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Mobile { - public enum TargetType - { - /// - /// Redirect when request from a mobile - /// - Portal = 1, + using System; + + public enum TargetType + { + /// + /// Redirect when request from a mobile + /// + Portal = 1, - /// - /// Redirect when request from a tablet - /// - Tab = 2, + /// + /// Redirect when request from a tablet + /// + Tab = 2, - /// - /// Redirect when request from some unknown device, should be determine by match rules; - /// - Url = 3 - } + /// + /// Redirect when request from some unknown device, should be determine by match rules; + /// + Url = 3, + } } diff --git a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs index e3a4610f277..d5eda6af7d7 100644 --- a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs @@ -1,50 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.ModuleCache { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Security.Cryptography; + using System.Text; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + public class FileProvider : ModuleCachingProvider - { - #region Private Members - + { private const string DataFileExtension = ".data.resources"; private const string AttribFileExtension = ".attrib.resources"; - private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); - - #endregion - - #region Private Methods - - private string GenerateCacheKeyHash(int tabModuleId, string cacheKey) + private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); + + public override string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy) { - byte[] hash = Encoding.ASCII.GetBytes(cacheKey); - using (var sha256 = new SHA256CryptoServiceProvider()) + var cacheKey = new StringBuilder(); + if (varyBy != null) { - hash = sha256.ComputeHash(hash); - return tabModuleId + "_" + ByteArrayToString(hash); + SortedDictionary.Enumerator varyByParms = varyBy.GetEnumerator(); + while (varyByParms.MoveNext()) + { + string key = varyByParms.Current.Key.ToLowerInvariant(); + cacheKey.Append(string.Concat(key, "=", varyByParms.Current.Value, "|")); + } } + + return this.GenerateCacheKeyHash(tabModuleId, cacheKey.ToString()); } - - + public override int GetItemCount(int tabModuleId) + { + return GetCachedItemCount(tabModuleId); + } + private static string GetAttribFileName(int tabModuleId, string cacheKey) { return string.Concat(GetCacheFolder(), cacheKey, AttribFileExtension); @@ -52,7 +50,17 @@ private static string GetAttribFileName(int tabModuleId, string cacheKey) private static int GetCachedItemCount(int tabModuleId) { - return Directory.GetFiles(GetCacheFolder(), String.Format("*{0}", DataFileExtension)).Length; + return Directory.GetFiles(GetCacheFolder(), string.Format("*{0}", DataFileExtension)).Length; + } + + private string GenerateCacheKeyHash(int tabModuleId, string cacheKey) + { + byte[] hash = Encoding.ASCII.GetBytes(cacheKey); + using (var sha256 = new SHA256CryptoServiceProvider()) + { + hash = sha256.ComputeHash(hash); + return tabModuleId + "_" + this.ByteArrayToString(hash); + } } private static string GetCachedOutputFileName(int tabModuleId, string cacheKey) @@ -61,7 +69,7 @@ private static string GetCachedOutputFileName(int tabModuleId, string cacheKey) } /// - /// [jmarino] 2011-06-16 Check for ContainsKey for a write added + /// [jmarino] 2011-06-16 Check for ContainsKey for a write added. /// /// /// @@ -80,12 +88,11 @@ private static string GetCacheFolder(int portalId) var portalInfo = PortalController.Instance.GetPortal(portalId); string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; - - - if (!(string.IsNullOrEmpty(homeDirectoryMapPath))) + + if (!string.IsNullOrEmpty(homeDirectoryMapPath)) { cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); - if (!(Directory.Exists(cacheFolder))) + if (!Directory.Exists(cacheFolder)) { Directory.CreateDirectory(cacheFolder); } @@ -93,8 +100,10 @@ private static string GetCacheFolder(int portalId) using (var writerLock = CacheFolderPath.GetWriteLock()) { - if (!CacheFolderPath.ContainsKey(portalId)) - CacheFolderPath.Add(portalId, cacheFolder); + if (!CacheFolderPath.ContainsKey(portalId)) + { + CacheFolderPath.Add(portalId, cacheFolder); + } } return cacheFolder; @@ -106,6 +115,11 @@ private static string GetCacheFolder() return GetCacheFolder(portalId); } + private static bool IsPathInApplication(string cacheFolder) + { + return cacheFolder.Contains(Globals.ApplicationMapPath); + } + private bool IsFileExpired(string file) { StreamReader oRead = null; @@ -122,11 +136,11 @@ private bool IsFileExpired(string file) return false; } } - catch - { - //if check expire time failed, then force to expire the cache. - return true; - } + catch + { + // if check expire time failed, then force to expire the cache. + return true; + } finally { if (oRead != null) @@ -144,48 +158,20 @@ private void PurgeCache(string folder) { if (!FileSystemUtils.DeleteFileWithWait(File, 100, 200)) { - filesNotDeleted.Append(String.Format("{0};", File)); + filesNotDeleted.Append(string.Format("{0};", File)); } else { i += 1; } } + if (filesNotDeleted.Length > 0) { - throw new IOException(String.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); + throw new IOException(string.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); } } - private static bool IsPathInApplication(string cacheFolder) - { - return cacheFolder.Contains(Globals.ApplicationMapPath); - } - - #endregion - - #region Abstract Method Implementation - - public override string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy) - { - var cacheKey = new StringBuilder(); - if (varyBy != null) - { - SortedDictionary.Enumerator varyByParms = varyBy.GetEnumerator(); - while ((varyByParms.MoveNext())) - { - string key = varyByParms.Current.Key.ToLowerInvariant(); - cacheKey.Append(string.Concat(key, "=", varyByParms.Current.Value, "|")); - } - } - return GenerateCacheKeyHash(tabModuleId, cacheKey.ToString()); - } - - public override int GetItemCount(int tabModuleId) - { - return GetCachedItemCount(tabModuleId); - } - public override byte[] GetModule(int tabModuleId, string cacheKey) { string cachedModule = GetCachedOutputFileName(tabModuleId, cacheKey); @@ -193,6 +179,7 @@ public override byte[] GetModule(int tabModuleId, string cacheKey) { return null; } + var fInfo = new FileInfo(cachedModule); long numBytes = fInfo.Length; using (var fStream = new FileStream(cachedModule, FileMode.Open, FileAccess.Read)) @@ -204,7 +191,7 @@ public override byte[] GetModule(int tabModuleId, string cacheKey) public override void PurgeCache(int portalId) { - PurgeCache(GetCacheFolder(portalId)); + this.PurgeCache(GetCacheFolder(portalId)); } public override void PurgeExpiredItems(int portalId) @@ -216,14 +203,14 @@ public override void PurgeExpiredItems(int portalId) string cacheFolder = GetCacheFolder(portalId); if (Directory.Exists(cacheFolder) && IsPathInApplication(cacheFolder)) { - foreach (string File in Directory.GetFiles(cacheFolder, String.Format("*{0}", AttribFileExtension))) + foreach (string File in Directory.GetFiles(cacheFolder, string.Format("*{0}", AttribFileExtension))) { - if (IsFileExpired(File)) + if (this.IsFileExpired(File)) { string fileToDelete = File.Replace(AttribFileExtension, DataFileExtension); if (!FileSystemUtils.DeleteFileWithWait(fileToDelete, 100, 200)) { - filesNotDeleted.Append(String.Format("{0};", fileToDelete)); + filesNotDeleted.Append(string.Format("{0};", fileToDelete)); } else { @@ -232,9 +219,10 @@ public override void PurgeExpiredItems(int portalId) } } } + if (filesNotDeleted.Length > 0) { - throw new IOException(String.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); + throw new IOException(string.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); } } catch (Exception ex) @@ -247,9 +235,8 @@ public override void SetModule(int tabModuleId, string cacheKey, TimeSpan durati { try { - string cachedOutputFile = GetCachedOutputFileName(tabModuleId, cacheKey); - + if (File.Exists(cachedOutputFile)) { FileSystemUtils.DeleteFileWithWait(cachedOutputFile, 100, 200); @@ -292,6 +279,7 @@ public override void Remove(int tabModuleId) i += 1; } } + if (filesNotDeleted.Length > 0) { throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted); @@ -301,8 +289,6 @@ public override void Remove(int tabModuleId) { Exceptions.Exceptions.LogException(ex); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs index 9be33dce49e..e0ebd4e6157 100644 --- a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs @@ -1,40 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using System.Web.Caching; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Cache; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.ModuleCache { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Text; + using System.Web.Caching; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Cache; + public class MemoryProvider : ModuleCachingProvider { private const string cachePrefix = "ModuleCache:"; - private List GetCacheKeys(int tabModuleId) - { - var keys = new List(); - IDictionaryEnumerator CacheEnum = CachingProvider.Instance().GetEnumerator(); - while ((CacheEnum.MoveNext())) - { - if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix, "|", tabModuleId.ToString(), "|"))) - { - keys.Add(CacheEnum.Key.ToString()); - } - } - return keys; - } - public override string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy) { var cacheKey = new StringBuilder(); @@ -45,12 +26,28 @@ public override string GenerateCacheKey(int tabModuleId, SortedDictionary GetCacheKeys(int tabModuleId) + { + var keys = new List(); + IDictionaryEnumerator CacheEnum = CachingProvider.Instance().GetEnumerator(); + while (CacheEnum.MoveNext()) + { + if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix, "|", tabModuleId.ToString(), "|"))) + { + keys.Add(CacheEnum.Key.ToString()); + } + } + + return keys; } public override byte[] GetModule(int tabModuleId, string cacheKey) @@ -76,7 +73,7 @@ public override void SetModule(int tabModuleId, string cacheKey, TimeSpan durati public override void PurgeExpiredItems(int portalId) { - //throw new NotSupportedException(); + // throw new NotSupportedException(); } } } diff --git a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs index 359f8d1d81c..56a0fba715f 100644 --- a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Text; - -using DotNetNuke.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.ModuleCache { + using System; + using System.Collections.Generic; + using System.Text; + + using DotNetNuke.ComponentModel; + public abstract class ModuleCachingProvider { public static Dictionary GetProviderList() @@ -33,6 +28,10 @@ public static void RemoveItemFromAllProviders(int tabModuleId) kvp.Value.Remove(tabModuleId); } } + + public abstract string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy); + + public abstract int GetItemCount(int tabModuleId); protected string ByteArrayToString(byte[] arrInput) { @@ -42,33 +41,22 @@ protected string ByteArrayToString(byte[] arrInput) { sOutput.Append(arrInput[i].ToString("X2")); } + return sOutput.ToString(); - } - - #region Abstract methods - - public abstract string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy); - - public abstract int GetItemCount(int tabModuleId); + } public abstract byte[] GetModule(int tabModuleId, string cacheKey); public abstract void Remove(int tabModuleId); - public abstract void SetModule(int tabModuleId, string cacheKey, TimeSpan duration, byte[] moduleOutput); - - #endregion - - #region Virtual Methods - + public abstract void SetModule(int tabModuleId, string cacheKey, TimeSpan duration, byte[] moduleOutput); + public virtual void PurgeCache(int portalId) { } public virtual void PurgeExpiredItems(int portalId) { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs b/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs index 7200c1b61af..3bc65f4588d 100644 --- a/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs +++ b/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs @@ -1,27 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.ModuleCache { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Scheduling; + public class PurgeModuleCache : SchedulerClient { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (PurgeModuleCache)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PurgeModuleCache)); + public PurgeModuleCache(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; //REQUIRED + this.ScheduleHistoryItem = objScheduleHistoryItem; // REQUIRED } public override void DoWork() @@ -36,29 +32,29 @@ public override void DoWork() foreach (PortalInfo portal in portals) { kvp.Value.PurgeExpiredItems(portal.PortalID); - ScheduleHistoryItem.AddLogNote(string.Format("Purged Module cache for {0}. ", kvp.Key)); + this.ScheduleHistoryItem.AddLogNote(string.Format("Purged Module cache for {0}. ", kvp.Key)); } } catch (NotSupportedException exc) { - //some Module caching providers don't use this feature + // some Module caching providers don't use this feature Logger.Debug(exc); - } } - ScheduleHistoryItem.Succeeded = true; //REQUIRED + + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED } - catch (Exception exc) //REQUIRED + catch (Exception exc) // REQUIRED { - ScheduleHistoryItem.Succeeded = false; //REQUIRED + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED + + this.ScheduleHistoryItem.AddLogNote(string.Format("Purging Module cache task failed: {0}.", exc.ToString())); - ScheduleHistoryItem.AddLogNote(string.Format("Purging Module cache task failed: {0}.", exc.ToString())); + // notification that we have errored + this.Errored(ref exc); // REQUIRED - //notification that we have errored - Errored(ref exc); //REQUIRED - - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } } diff --git a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs index 3cdb8bc9021..6a6029ee462 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs @@ -1,37 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.OutputCache { + using System; + using System.IO; + using System.Text; + // helper class to capture the response into a file public abstract class OutputCacheResponseFilter : Stream { - private Stream _captureStream; - - #region "Constructors" - + private Stream _captureStream; + public OutputCacheResponseFilter(Stream filterChain, string cacheKey, TimeSpan cacheDuration, int maxVaryByCount) { - ChainedStream = filterChain; - CacheKey = cacheKey; - CacheDuration = cacheDuration; - MaxVaryByCount = maxVaryByCount; - _captureStream = CaptureStream; - } - - #endregion - - #region "Public Properties" - + this.ChainedStream = filterChain; + this.CacheKey = cacheKey; + this.CacheDuration = cacheDuration; + this.MaxVaryByCount = maxVaryByCount; + this._captureStream = this.CaptureStream; + } + public TimeSpan CacheDuration { get; set; } public virtual string CacheKey { get; set; } @@ -40,11 +29,12 @@ public Stream CaptureStream { get { - return _captureStream; + return this._captureStream; } + set { - _captureStream = value; + this._captureStream = value; } } @@ -92,39 +82,38 @@ public override long Position { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } - } - - #endregion - - #region "Public Methods" - + } + public override void Flush() { - ChainedStream.Flush(); - if (HasErrored) + this.ChainedStream.Flush(); + if (this.HasErrored) { return; } - if ((((_captureStream) != null))) + + if (this._captureStream != null) { - _captureStream.Flush(); + this._captureStream.Flush(); } } public override void Write(byte[] buffer, int offset, int count) { - ChainedStream.Write(buffer, offset, count); - if (HasErrored) + this.ChainedStream.Write(buffer, offset, count); + if (this.HasErrored) { return; } - if ((((_captureStream) != null))) + + if (this._captureStream != null) { - _captureStream.Write(buffer, offset, count); + this._captureStream.Write(buffer, offset, count); } } @@ -141,41 +130,42 @@ public override long Seek(long offset, SeekOrigin origin) public override void SetLength(long value) { throw new NotSupportedException(); - } - - #endregion - - protected virtual void AddItemToCache(int itemId, string output) - { - } - - protected virtual void RemoveItemFromCache(int itemId) - { - } + } public virtual byte[] StopFiltering(int itemId, bool deleteData) { - if (HasErrored) + if (this.HasErrored) { return null; } - if ((((CaptureStream) != null))) + if (this.CaptureStream != null) { - CaptureStream.Position = 0; - using (var reader = new StreamReader(CaptureStream, Encoding.Default)) + this.CaptureStream.Position = 0; + using (var reader = new StreamReader(this.CaptureStream, Encoding.Default)) { string output = reader.ReadToEnd(); - AddItemToCache(itemId, output); + this.AddItemToCache(itemId, output); } - CaptureStream.Close(); - CaptureStream = null; + + this.CaptureStream.Close(); + this.CaptureStream = null; } + if (deleteData) { - RemoveItemFromCache(itemId); + this.RemoveItemFromCache(itemId); } + return null; } + + protected virtual void AddItemToCache(int itemId, string output) + { + } + + protected virtual void RemoveItemFromCache(int itemId) + { + } } } diff --git a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs index a5488224572..50a4b907126 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs @@ -1,27 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using System.Web; - -using DotNetNuke.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.OutputCache { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.IO; + using System.Security.Cryptography; + using System.Text; + using System.Web; + + using DotNetNuke.ComponentModel; + public abstract class OutputCachingProvider - { - #region "Protected Methods" + { + public static Dictionary GetProviderList() + { + return ComponentFactory.GetComponents(); + } + public static OutputCachingProvider Instance(string FriendlyName) + { + return ComponentFactory.GetComponent(FriendlyName); + } + protected string ByteArrayToString(byte[] arrInput) { int i = 0; @@ -30,6 +33,7 @@ protected string ByteArrayToString(byte[] arrInput) { sOutput.Append(arrInput[i].ToString("X2")); } + return sOutput.ToString(); } @@ -39,44 +43,31 @@ protected string GenerateCacheKeyHash(int tabId, string cacheKey) using (var sha256 = new SHA256CryptoServiceProvider()) { hash = sha256.ComputeHash(hash); - return string.Concat(tabId.ToString(), "_", ByteArrayToString(hash)); + return string.Concat(tabId.ToString(), "_", this.ByteArrayToString(hash)); } } protected void WriteStreamAsText(HttpContext context, Stream stream, long offset, long length) { - if ((length < 0)) + if (length < 0) { - length = (stream.Length - offset); + length = stream.Length - offset; } - if ((length > 0)) + if (length > 0) { - if ((offset > 0)) + if (offset > 0) { stream.Seek(offset, SeekOrigin.Begin); } + var buffer = new byte[Convert.ToInt32(length)]; int count = stream.Read(buffer, 0, Convert.ToInt32(length)); char[] output = Encoding.UTF8.GetChars(buffer, 0, count); context.Response.ContentEncoding = Encoding.UTF8; context.Response.Output.Write(output); } - } - - #endregion - - #region "Shared/Static Methods" - - public static Dictionary GetProviderList() - { - return ComponentFactory.GetComponents(); - } - - public static OutputCachingProvider Instance(string FriendlyName) - { - return ComponentFactory.GetComponent(FriendlyName); - } + } public static void RemoveItemFromAllProviders(int tabId) { @@ -84,12 +75,8 @@ public static void RemoveItemFromAllProviders(int tabId) { kvp.Value.Remove(tabId); } - } - - #endregion - - #region "Abstract Methods" - + } + public abstract int GetItemCount(int tabId); public abstract byte[] GetOutput(int tabId, string cacheKey); @@ -100,19 +87,15 @@ public static void RemoveItemFromAllProviders(int tabId) public abstract void SetOutput(int tabId, string cacheKey, TimeSpan duration, byte[] output); - public abstract bool StreamOutput(int tabId, string cacheKey, HttpContext context); - - #endregion - - #region "Virtual Methods" - + public abstract bool StreamOutput(int tabId, string cacheKey, HttpContext context); + public virtual string GenerateCacheKey(int tabId, StringCollection includeVaryByKeys, StringCollection excludeVaryByKeys, SortedDictionary varyBy) { var cacheKey = new StringBuilder(); if (varyBy != null) { SortedDictionary.Enumerator varyByParms = varyBy.GetEnumerator(); - while ((varyByParms.MoveNext())) + while (varyByParms.MoveNext()) { string key = varyByParms.Current.Key.ToLowerInvariant(); if (includeVaryByKeys.Contains(key) && !excludeVaryByKeys.Contains(key)) @@ -121,7 +104,8 @@ public virtual string GenerateCacheKey(int tabId, StringCollection includeVaryBy } } } - return GenerateCacheKeyHash(tabId, cacheKey.ToString()); + + return this.GenerateCacheKeyHash(tabId, cacheKey.ToString()); } public virtual void PurgeCache(int portalId) @@ -130,8 +114,6 @@ public virtual void PurgeCache(int portalId) public virtual void PurgeExpiredItems(int portalId) { - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs index 3de95939ebe..6a2fcfaba16 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs @@ -1,23 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.IO; -using System.Text; -using System.Web; -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.OutputCache.Providers { + using System; + using System.Data; + using System.IO; + using System.Text; + using System.Web; + + using DotNetNuke.Data; + /// /// DatabaseProvider implements the OutputCachingProvider for database storage. /// public class DatabaseProvider : OutputCachingProvider - { - #region Abstract Method Implementation - + { public override int GetItemCount(int tabId) { return DataProvider.Instance().GetOutputCacheItemCount(tabId); @@ -35,7 +34,7 @@ public override byte[] GetOutput(int tabId, string cacheKey) } else { - if (! (dr.Read())) + if (!dr.Read()) { return null; } @@ -90,20 +89,20 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex } else { - if (! (dr.Read())) + if (!dr.Read()) { return false; } - var expireTime = Convert.ToDateTime(dr["Expiration"]); - if(expireTime < DateTime.UtcNow) - { - DataProvider.Instance().RemoveOutputCacheItem(tabId); - return false; - } + var expireTime = Convert.ToDateTime(dr["Expiration"]); + if (expireTime < DateTime.UtcNow) + { + DataProvider.Instance().RemoveOutputCacheItem(tabId); + return false; + } - context.Response.BinaryWrite(Encoding.Default.GetBytes(dr["Data"].ToString())); - return true; + context.Response.BinaryWrite(Encoding.Default.GetBytes(dr["Data"].ToString())); + return true; } } finally @@ -113,8 +112,6 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex dr.Close(); } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs index 752dd65b182..848d1420415 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs @@ -1,32 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.OutputCache.Providers { + using System; + using System.IO; + + using DotNetNuke.Data; + /// /// FileResponseFilter implements the OutputCacheRepsonseFilter to capture the response into database. /// public class DatabaseResponseFilter : OutputCacheResponseFilter { - internal DatabaseResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) + internal DatabaseResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) + : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) { if (maxVaryByCount > -1 && DataProvider.Instance().GetOutputCacheItemCount(itemId) >= maxVaryByCount) { - HasErrored = true; + this.HasErrored = true; return; } - CaptureStream = new MemoryStream(); + this.CaptureStream = new MemoryStream(); } protected override void AddItemToCache(int itemId, string output) { - DataProvider.Instance().AddOutputCacheItem(itemId, CacheKey, output, DateTime.UtcNow.Add(CacheDuration)); + DataProvider.Instance().AddOutputCacheItem(itemId, this.CacheKey, output, DateTime.UtcNow.Add(this.CacheDuration)); } protected override void RemoveItemFromCache(int itemId) diff --git a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs index 53f8deb06bf..6c620f5e368 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Web; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Log.EventLog; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.OutputCache.Providers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Web; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Log.EventLog; + /// /// FileProvider implements the OutputCachingProvider for file storage. /// @@ -23,10 +24,40 @@ public class FileProvider : OutputCachingProvider public const string AttribFileExtension = ".attrib.resources"; public const string TempFileExtension = ".temp.resources"; - private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); + private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); + + public override int GetItemCount(int tabId) + { + return GetCachedItemCount(tabId); + } - #region Private Methods + public override byte[] GetOutput(int tabId, string cacheKey) + { + string cachedOutput = GetCachedOutputFileName(tabId, cacheKey); + if (!File.Exists(cachedOutput)) + { + return null; + } + + var fInfo = new FileInfo(cachedOutput); + long numBytes = fInfo.Length; + using (var fStream = new FileStream(cachedOutput, FileMode.Open, FileAccess.Read)) + using (var br = new BinaryReader(fStream)) + { + return br.ReadBytes(Convert.ToInt32(numBytes)); + } + } + + internal static string GetAttribFileName(int tabId, string cacheKey) + { + return string.Concat(GetCacheFolder(), cacheKey, AttribFileExtension); + } + internal static int GetCachedItemCount(int tabId) + { + return Directory.GetFiles(GetCacheFolder(), $"{tabId}_*{DataFileExtension}").Length; + } + private static string GetCacheFolder() { int portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId; @@ -48,12 +79,11 @@ private static string GetCacheFolder(int portalId) var portalInfo = PortalController.Instance.GetPortal(portalId); string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; - - - if (!(string.IsNullOrEmpty(homeDirectoryMapPath))) + + if (!string.IsNullOrEmpty(homeDirectoryMapPath)) { cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); - if (!(Directory.Exists(cacheFolder))) + if (!Directory.Exists(cacheFolder)) { Directory.CreateDirectory(cacheFolder); } @@ -62,7 +92,6 @@ private static string GetCacheFolder(int portalId) using (var writerLock = CacheFolderPath.GetWriteLock()) { CacheFolderPath.Add(portalId, cacheFolder); - } return cacheFolder; @@ -101,7 +130,7 @@ private void PurgeCache(string folder) int i = 0; foreach (string file in Directory.GetFiles(folder, "*.resources")) { - if (!(FileSystemUtils.DeleteFileWithWait(file, 100, 200))) + if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200)) { filesNotDeleted.Append(file + ";"); } @@ -110,6 +139,7 @@ private void PurgeCache(string folder) i += 1; } } + if (filesNotDeleted.Length > 0) { throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted); @@ -119,21 +149,7 @@ private void PurgeCache(string folder) { Exceptions.Exceptions.LogException(ex); } - } - - #endregion - - #region Friend Methods - - internal static string GetAttribFileName(int tabId, string cacheKey) - { - return string.Concat(GetCacheFolder(), cacheKey, AttribFileExtension); - } - - internal static int GetCachedItemCount(int tabId) - { - return Directory.GetFiles(GetCacheFolder(), $"{tabId}_*{DataFileExtension}").Length; - } + } internal static string GetCachedOutputFileName(int tabId, string cacheKey) { @@ -143,32 +159,7 @@ internal static string GetCachedOutputFileName(int tabId, string cacheKey) internal static string GetTempFileName(int tabId, string cacheKey) { return string.Concat(GetCacheFolder(), cacheKey, TempFileExtension); - } - - #endregion - - #region Abstract Method Implementation - - public override int GetItemCount(int tabId) - { - return GetCachedItemCount(tabId); - } - - public override byte[] GetOutput(int tabId, string cacheKey) - { - string cachedOutput = GetCachedOutputFileName(tabId, cacheKey); - if (!(File.Exists(cachedOutput))) - { - return null; - } - var fInfo = new FileInfo(cachedOutput); - long numBytes = fInfo.Length; - using (var fStream = new FileStream(cachedOutput, FileMode.Open, FileAccess.Read)) - using (var br = new BinaryReader(fStream)) - { - return br.ReadBytes(Convert.ToInt32(numBytes)); - } - } + } public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVaryByCount, Stream responseFilter, string cacheKey, TimeSpan cacheDuration) { @@ -178,9 +169,9 @@ public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVa public override void PurgeCache(int portalId) { string cacheFolder = GetCacheFolder(portalId); - if (!(string.IsNullOrEmpty(cacheFolder))) + if (!string.IsNullOrEmpty(cacheFolder)) { - PurgeCache(cacheFolder); + this.PurgeCache(cacheFolder); } } @@ -190,14 +181,14 @@ public override void PurgeExpiredItems(int portalId) int i = 0; string cacheFolder = GetCacheFolder(portalId); - if (!(string.IsNullOrEmpty(cacheFolder))) + if (!string.IsNullOrEmpty(cacheFolder)) { foreach (string file in Directory.GetFiles(cacheFolder, "*" + AttribFileExtension)) { - if (IsFileExpired(file)) + if (this.IsFileExpired(file)) { string fileToDelete = file.Replace(AttribFileExtension, DataFileExtension); - if (!(FileSystemUtils.DeleteFileWithWait(fileToDelete, 100, 200))) + if (!FileSystemUtils.DeleteFileWithWait(fileToDelete, 100, 200)) { filesNotDeleted.Append(fileToDelete + ";"); } @@ -207,6 +198,7 @@ public override void PurgeExpiredItems(int portalId) } } } + if (filesNotDeleted.Length > 0) { throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted); @@ -225,11 +217,11 @@ public override void Remove(int tabId) int i = 0; string cacheFolder = GetCacheFolder(portals[tabId]); - if (!(string.IsNullOrEmpty(cacheFolder))) + if (!string.IsNullOrEmpty(cacheFolder)) { foreach (string file in Directory.GetFiles(cacheFolder, string.Concat(tabId, "_*.*"))) { - if (!(FileSystemUtils.DeleteFileWithWait(file, 100, 200))) + if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200)) { filesNotDeleted.Append(string.Concat(file, ";")); } @@ -238,6 +230,7 @@ public override void Remove(int tabId) i += 1; } } + if (filesNotDeleted.Length > 0) { var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; @@ -248,7 +241,7 @@ public override void Remove(int tabId) PropertyValue = string.Format( "Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", - i, filesNotDeleted) + i, filesNotDeleted), }; var properties = new LogProperties { logDetail }; log.LogProperties = properties; @@ -290,10 +283,10 @@ public override void SetOutput(int tabId, string cacheKey, TimeSpan duration, by } catch (Exception ex) { - // TODO: Need to implement multi-threading. + // TODO: Need to implement multi-threading. // The current code is not thread safe and threw error if two threads tried creating cache file // A thread could create a file between the time another thread deleted it and tried to create new cache file. - // This would result in a system.IO.IOException. Also, there was no error handling in place so the + // This would result in a system.IO.IOException. Also, there was no error handling in place so the // Error would bubble up to the user and provide details on the file structure of the site. Exceptions.Exceptions.LogException(ex); } @@ -324,9 +317,8 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex { Exceptions.Exceptions.LogException(ex); } + return foundFile; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs index e39f51945d1..61c60e140d6 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs @@ -1,54 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.OutputCache.Providers { + using System; + using System.IO; + + using DotNetNuke.Common.Utilities; + /// /// FileResponseFilter implements the OutputCacheRepsonseFilter to capture the response into files. /// public class FileResponseFilter : OutputCacheResponseFilter { - //Private _content As StringBuilder + // Private _content As StringBuilder private DateTime _cacheExpiration; - internal FileResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) + internal FileResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) + : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) { if (maxVaryByCount > -1 && Services.OutputCache.Providers.FileProvider.GetCachedItemCount(itemId) >= maxVaryByCount) { - HasErrored = true; + this.HasErrored = true; return; } - CachedOutputTempFileName = Services.OutputCache.Providers.FileProvider.GetTempFileName(itemId, cacheKey); - CachedOutputFileName = Services.OutputCache.Providers.FileProvider.GetCachedOutputFileName(itemId, cacheKey); - CachedOutputAttribFileName = Services.OutputCache.Providers.FileProvider.GetAttribFileName(itemId, cacheKey); - if (File.Exists(CachedOutputTempFileName)) + this.CachedOutputTempFileName = Services.OutputCache.Providers.FileProvider.GetTempFileName(itemId, cacheKey); + this.CachedOutputFileName = Services.OutputCache.Providers.FileProvider.GetCachedOutputFileName(itemId, cacheKey); + this.CachedOutputAttribFileName = Services.OutputCache.Providers.FileProvider.GetAttribFileName(itemId, cacheKey); + if (File.Exists(this.CachedOutputTempFileName)) { - bool fileDeleted = FileSystemUtils.DeleteFileWithWait(CachedOutputTempFileName, 100, 200); + bool fileDeleted = FileSystemUtils.DeleteFileWithWait(this.CachedOutputTempFileName, 100, 200); if (fileDeleted == false) { - HasErrored = true; + this.HasErrored = true; } } - if (HasErrored == false) + + if (this.HasErrored == false) { try { - CaptureStream = new FileStream(CachedOutputTempFileName, FileMode.CreateNew, FileAccess.Write); + this.CaptureStream = new FileStream(this.CachedOutputTempFileName, FileMode.CreateNew, FileAccess.Write); } catch (Exception) { - HasErrored = true; + this.HasErrored = true; throw; } - _cacheExpiration = DateTime.UtcNow.Add(cacheDuration); - HasErrored = false; + this._cacheExpiration = DateTime.UtcNow.Add(cacheDuration); + this.HasErrored = false; } } @@ -62,40 +65,42 @@ public DateTime CacheExpiration { get { - return _cacheExpiration; + return this._cacheExpiration; } + set { - _cacheExpiration = value; + this._cacheExpiration = value; } } public override byte[] StopFiltering(int itemId, bool deleteData) { - if (HasErrored) + if (this.HasErrored) { return null; } - if ((CaptureStream) != null) + if (this.CaptureStream != null) { - CaptureStream.Close(); + this.CaptureStream.Close(); - if (File.Exists(CachedOutputFileName)) + if (File.Exists(this.CachedOutputFileName)) { - FileSystemUtils.DeleteFileWithWait(CachedOutputFileName, 100, 200); + FileSystemUtils.DeleteFileWithWait(this.CachedOutputFileName, 100, 200); } - File.Move(CachedOutputTempFileName, CachedOutputFileName); + File.Move(this.CachedOutputTempFileName, this.CachedOutputFileName); - StreamWriter oWrite = File.CreateText(CachedOutputAttribFileName); - oWrite.WriteLine(_cacheExpiration.ToString()); + StreamWriter oWrite = File.CreateText(this.CachedOutputAttribFileName); + oWrite.WriteLine(this._cacheExpiration.ToString()); oWrite.Close(); } + if (deleteData) { - FileSystemUtils.DeleteFileWithWait(CachedOutputFileName, 100, 200); - FileSystemUtils.DeleteFileWithWait(CachedOutputAttribFileName, 100, 200); + FileSystemUtils.DeleteFileWithWait(this.CachedOutputFileName, 100, 200); + FileSystemUtils.DeleteFileWithWait(this.CachedOutputAttribFileName, 100, 200); } return null; diff --git a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs index 1aed975eae2..272b68e872c 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs @@ -1,66 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; -using System.Web.Caching; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.OutputCache.Providers { + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.Caching; + /// /// MemoryResponseFilter implements the OutputCachingProvider for memory storage. /// public class MemoryProvider : OutputCachingProvider { protected const string cachePrefix = "DNN_OUTPUT:"; - private static System.Web.Caching.Cache runtimeCache; - - #region Friend Properties - + private static System.Web.Caching.Cache runtimeCache; + internal static System.Web.Caching.Cache Cache { get { - //create singleton of the cache object + // create singleton of the cache object if (runtimeCache == null) { runtimeCache = HttpRuntime.Cache; } + return runtimeCache; } } - internal static string CachePrefix - { - get - { - return cachePrefix; - } - } - - #endregion - - #region Private Methods - - private string GetCacheKey(string CacheKey) + internal static string CachePrefix { - if (string.IsNullOrEmpty(CacheKey)) + get { - throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); + return cachePrefix; } - return string.Concat(cachePrefix, CacheKey); + } + + public override string GenerateCacheKey(int tabId, System.Collections.Specialized.StringCollection includeVaryByKeys, System.Collections.Specialized.StringCollection excludeVaryByKeys, SortedDictionary varyBy) + { + return this.GetCacheKey(base.GenerateCacheKey(tabId, includeVaryByKeys, excludeVaryByKeys, varyBy)); } - #endregion - - #region Friend Methods - + public override int GetItemCount(int tabId) + { + return GetCacheKeys(tabId).Count(); + } + internal static List GetCacheKeys() { var keys = new List(); @@ -72,6 +64,7 @@ internal static List GetCacheKeys() keys.Add(CacheEnum.Key.ToString()); } } + return keys; } @@ -86,29 +79,26 @@ internal static List GetCacheKeys(int tabId) keys.Add(CacheEnum.Key.ToString()); } } + return keys; - } - - #endregion - - #region Abstract Method Implementation - - public override string GenerateCacheKey(int tabId, System.Collections.Specialized.StringCollection includeVaryByKeys, System.Collections.Specialized.StringCollection excludeVaryByKeys, SortedDictionary varyBy) - { - return GetCacheKey(base.GenerateCacheKey(tabId, includeVaryByKeys, excludeVaryByKeys, varyBy)); - } - - public override int GetItemCount(int tabId) + } + + private string GetCacheKey(string CacheKey) { - return GetCacheKeys(tabId).Count(); - } + if (string.IsNullOrEmpty(CacheKey)) + { + throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); + } + + return string.Concat(cachePrefix, CacheKey); + } public override byte[] GetOutput(int tabId, string cacheKey) { object output = Cache[cacheKey]; if (output != null) { - return (byte[]) output; + return (byte[])output; } else { @@ -154,10 +144,8 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex return false; } - context.Response.BinaryWrite(Encoding.Default.GetBytes(Cache[cacheKey].ToString())); - return true; - } - - #endregion + context.Response.BinaryWrite(Encoding.Default.GetBytes(Cache[cacheKey].ToString())); + return true; + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs index d80ce0a9a14..a5f61383daa 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs @@ -1,53 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web; -using System.Web.Caching; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.OutputCache.Providers { + using System; + using System.IO; + using System.Web; + using System.Web.Caching; + /// /// FileResponseFilter implements the OutputCacheRepsonseFilter to capture the response into memory. /// public class MemoryResponseFilter : OutputCacheResponseFilter { - //Private _content As StringBuilder + // Private _content As StringBuilder private static System.Web.Caching.Cache runtimeCache; - internal MemoryResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) + internal MemoryResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) + : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) { if (maxVaryByCount > -1 && Services.OutputCache.Providers.MemoryProvider.GetCacheKeys(itemId).Count >= maxVaryByCount) { - HasErrored = true; + this.HasErrored = true; return; } - CaptureStream = new MemoryStream(); + + this.CaptureStream = new MemoryStream(); } protected static System.Web.Caching.Cache Cache { get { - //create singleton of the cache object + // create singleton of the cache object if (runtimeCache == null) { runtimeCache = HttpRuntime.Cache; } + return runtimeCache; } } protected override void AddItemToCache(int itemId, string output) { - Cache.Insert(CacheKey, output, null, DateTime.UtcNow.Add(CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); + Cache.Insert(this.CacheKey, output, null, DateTime.UtcNow.Add(this.CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } protected override void RemoveItemFromCache(int itemId) { - Cache.Remove(CacheKey); + Cache.Remove(this.CacheKey); } } } diff --git a/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs b/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs index bd600bb32d3..ac19fe59fb6 100644 --- a/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs +++ b/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Scheduling; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.OutputCache { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Scheduling; + public class PurgeOutputCache : SchedulerClient { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (PurgeOutputCache)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PurgeOutputCache)); public PurgeOutputCache(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; //REQUIRED + this.ScheduleHistoryItem = objScheduleHistoryItem; // REQUIRED } public override void DoWork() @@ -37,28 +32,29 @@ public override void DoWork() foreach (PortalInfo portal in portals) { kvp.Value.PurgeExpiredItems(portal.PortalID); - ScheduleHistoryItem.AddLogNote(string.Format("Purged output cache for {0}. ", kvp.Key)); + this.ScheduleHistoryItem.AddLogNote(string.Format("Purged output cache for {0}. ", kvp.Key)); } } catch (NotSupportedException exc) { - //some output caching providers don't use this feature + // some output caching providers don't use this feature Logger.Debug(exc); } } - ScheduleHistoryItem.Succeeded = true; //REQUIRED + + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED } - catch (Exception exc) //REQUIRED + catch (Exception exc) // REQUIRED { - ScheduleHistoryItem.Succeeded = false; //REQUIRED + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED + + this.ScheduleHistoryItem.AddLogNote(string.Format("Purging output cache task failed: {0}.", exc.ToString())); // OPTIONAL - ScheduleHistoryItem.AddLogNote(string.Format("Purging output cache task failed: {0}.", exc.ToString())); //OPTIONAL + // notification that we have errored + this.Errored(ref exc); - //notification that we have errored - Errored(ref exc); - - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } } diff --git a/DNN Platform/Library/Services/Personalization/Personalization.cs b/DNN Platform/Library/Services/Personalization/Personalization.cs index 2fb94278687..c13203b9a87 100644 --- a/DNN Platform/Library/Services/Personalization/Personalization.cs +++ b/DNN Platform/Library/Services/Personalization/Personalization.cs @@ -1,81 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Personalization { + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + public class Personalization - { - #region Private Methods + { + /// + /// load users profile and extract value base on naming container and key. + /// + /// Container for related set of values. + /// Individual profile key. + /// + public static object GetProfile(string namingContainer, string key) + { + return GetProfile(LoadProfile(), namingContainer, key); + } + /// + /// extract value base on naming container and key from PersonalizationInfo object. + /// + /// Object containing user personalization info. + /// Container for related set of values. + /// Individual profile key. + /// + public static object GetProfile(PersonalizationInfo personalization, string namingContainer, string key) + { + return personalization != null ? personalization.Profile[namingContainer + ":" + key] : string.Empty; + } + private static PersonalizationInfo LoadProfile() { HttpContext context = HttpContext.Current; - //First try and load Personalization object from the Context - var personalization = (PersonalizationInfo) context.Items["Personalization"]; + // First try and load Personalization object from the Context + var personalization = (PersonalizationInfo)context.Items["Personalization"]; - //If the Personalization object is nothing load it and store it in the context for future calls + // If the Personalization object is nothing load it and store it in the context for future calls if (personalization == null) { - var _portalSettings = (PortalSettings) context.Items["PortalSettings"]; + var _portalSettings = (PortalSettings)context.Items["PortalSettings"]; - //load the user info object + // load the user info object UserInfo UserInfo = UserController.Instance.GetCurrentUserInfo(); - //get the personalization object + // get the personalization object var personalizationController = new PersonalizationController(); personalization = personalizationController.LoadProfile(UserInfo.UserID, _portalSettings.PortalId); - //store it in the context + // store it in the context context.Items.Add("Personalization", personalization); } + return personalization; - } - - #endregion - - #region Public Shared Methods - - /// - /// load users profile and extract value base on naming container and key - /// - /// Container for related set of values - /// Individual profile key - /// - public static object GetProfile(string namingContainer, string key) - { - return GetProfile(LoadProfile(), namingContainer, key); - } + } /// - /// extract value base on naming container and key from PersonalizationInfo object + /// load users profile and extract secure value base on naming container and key. /// - /// Object containing user personalization info - /// Container for related set of values - /// Individual profile key - /// - public static object GetProfile(PersonalizationInfo personalization, string namingContainer, string key) - { - return personalization != null ? personalization.Profile[namingContainer + ":" + key] : ""; - } - - /// - /// load users profile and extract secure value base on naming container and key - /// - /// Container for related set of values - /// Individual profile key + /// Container for related set of values. + /// Individual profile key. /// public static object GetSecureProfile(string namingContainer, string key) { @@ -84,11 +74,11 @@ public static object GetSecureProfile(string namingContainer, string key) /// /// extract value base on naming container and key from PersonalizationInfo object - /// function will automatically decrypt value to plaintext + /// function will automatically decrypt value to plaintext. /// - /// Object containing user personalization info - /// Container for related set of values - /// Individual profile key + /// Object containing user personalization info. + /// Container for related set of values. + /// Individual profile key. /// public static object GetSecureProfile(PersonalizationInfo personalization, string namingContainer, string key) { @@ -97,15 +87,16 @@ public static object GetSecureProfile(PersonalizationInfo personalization, strin var ps = PortalSecurity.Instance; return ps.DecryptString(personalization.Profile[namingContainer + ":" + key].ToString(), Config.GetDecryptionkey()); } - return ""; + + return string.Empty; } /// /// remove value from profile - /// uses namingcontainer and key to locate approriate value + /// uses namingcontainer and key to locate approriate value. /// - /// Container for related set of values - /// Individual profile key + /// Container for related set of values. + /// Individual profile key. public static void RemoveProfile(string namingContainer, string key) { RemoveProfile(LoadProfile(), namingContainer, key); @@ -113,38 +104,38 @@ public static void RemoveProfile(string namingContainer, string key) /// /// remove value from users PersonalizationInfo object (if it exists) - /// uses namingcontainer and key to locate approriate value + /// uses namingcontainer and key to locate approriate value. /// - /// Object containing user personalization info - /// Container for related set of values - /// Individual profile key + /// Object containing user personalization info. + /// Container for related set of values. + /// Individual profile key. public static void RemoveProfile(PersonalizationInfo personalization, string namingContainer, string key) { if (personalization != null) { - (personalization.Profile).Remove(namingContainer + ":" + key); + personalization.Profile.Remove(namingContainer + ":" + key); personalization.IsModified = true; } } /// - /// persist profile value -use naming container and key to orgainize + /// persist profile value -use naming container and key to orgainize. /// - /// Container for related set of values - /// Individual profile key - /// Individual profile value + /// Container for related set of values. + /// Individual profile key. + /// Individual profile value. public static void SetProfile(string namingContainer, string key, object value) { SetProfile(LoadProfile(), namingContainer, key, value); } /// - /// persist value stored in PersonalizationInfo obhect - use naming container and key to organize + /// persist value stored in PersonalizationInfo obhect - use naming container and key to organize. /// - /// Object containing user personalization info - /// Container for related set of values - /// Individual profile key - /// Individual profile value + /// Object containing user personalization info. + /// Container for related set of values. + /// Individual profile key. + /// Individual profile value. public static void SetProfile(PersonalizationInfo personalization, string namingContainer, string key, object value) { if (personalization != null) @@ -156,24 +147,24 @@ public static void SetProfile(PersonalizationInfo personalization, string naming /// /// persist profile value -use naming container and key to orgainize - /// function calls an overload which automatically encrypts the value + /// function calls an overload which automatically encrypts the value. /// - /// Object containing user personalization info - /// Individual profile key - /// Individual profile value + /// Object containing user personalization info. + /// Individual profile key. + /// Individual profile value. public static void SetSecureProfile(string namingContainer, string key, object value) { SetSecureProfile(LoadProfile(), namingContainer, key, value); } /// - /// persist profile value from PersonalizationInfo object, using naming container and key to organise - /// function will automatically encrypt the value to plaintext + /// persist profile value from PersonalizationInfo object, using naming container and key to organise + /// function will automatically encrypt the value to plaintext. /// - /// Object containing user personalization info - /// Container for related set of values - /// Individual profile key - /// Individual profile value + /// Object containing user personalization info. + /// Container for related set of values. + /// Individual profile key. + /// Individual profile value. public static void SetSecureProfile(PersonalizationInfo personalization, string namingContainer, string key, object value) { if (personalization != null) @@ -182,7 +173,6 @@ public static void SetSecureProfile(PersonalizationInfo personalization, string personalization.Profile[namingContainer + ":" + key] = ps.EncryptString(value.ToString(), Config.GetDecryptionkey()); personalization.IsModified = true; } - } - #endregion + } } } diff --git a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs index 005a096ca73..cf43f8cba2d 100644 --- a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs +++ b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs @@ -1,54 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Data; -using System.Text; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Personalization { + using System; + using System.Collections; + using System.Data; + using System.Text; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Security; + public class PersonalizationController { - //default implementation relies on HTTPContext + // default implementation relies on HTTPContext public void LoadProfile(HttpContext httpContext, int userId, int portalId) { - LoadProfile(new HttpContextWrapper(httpContext), userId, portalId); + this.LoadProfile(new HttpContextWrapper(httpContext), userId, portalId); } public void LoadProfile(HttpContextBase httpContext, int userId, int portalId) { if (HttpContext.Current.Items["Personalization"] == null) { - httpContext.Items.Add("Personalization", LoadProfile(userId, portalId)); + httpContext.Items.Add("Personalization", this.LoadProfile(userId, portalId)); } } - //override allows for manipulation of PersonalizationInfo outside of HTTPContext + // override allows for manipulation of PersonalizationInfo outside of HTTPContext public PersonalizationInfo LoadProfile(int userId, int portalId) { - var personalization = new PersonalizationInfo {UserId = userId, PortalId = portalId, IsModified = false}; + var personalization = new PersonalizationInfo { UserId = userId, PortalId = portalId, IsModified = false }; string profileData = Null.NullString; if (userId > Null.NullInteger) - { - var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); - profileData = CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.UserPersonalizationCacheTimeout, - DataCache.UserPersonalizationCachePriority, portalId, userId), GetCachedUserPersonalizationCallback); + { + var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); + profileData = CBO.GetCachedObject( + new CacheItemArgs(cacheKey, DataCache.UserPersonalizationCacheTimeout, + DataCache.UserPersonalizationCachePriority, portalId, userId), GetCachedUserPersonalizationCallback); } else { - //Anon User - so try and use cookie. + // Anon User - so try and use cookie. HttpContext context = HttpContext.Current; if (context != null && context.Request.Cookies["DNNPersonalization"] != null) { @@ -59,22 +56,35 @@ public PersonalizationInfo LoadProfile(int userId, int portalId) var personalizationCookie = new HttpCookie("DNNPersonalization", string.Empty) { Expires = DateTime.Now.AddDays(-1), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; context.Response.Cookies.Add(personalizationCookie); } } } + personalization.Profile = string.IsNullOrEmpty(profileData) ? new Hashtable() : Globals.DeserializeHashTableXml(profileData); return personalization; } + public void SaveProfile(PersonalizationInfo personalization) + { + this.SaveProfile(personalization, personalization.UserId, personalization.PortalId); + } + + // default implementation relies on HTTPContext + public void SaveProfile(HttpContext httpContext, int userId, int portalId) + { + var objPersonalization = (PersonalizationInfo)httpContext.Items["Personalization"]; + this.SaveProfile(objPersonalization, userId, portalId); + } + private static object GetCachedUserPersonalizationCallback(CacheItemArgs cacheItemArgs) { var portalId = (int)cacheItemArgs.ParamList[0]; var userId = (int)cacheItemArgs.ParamList[1]; - var returnValue = Null.NullString; //Default is no profile + var returnValue = Null.NullString; // Default is no profile IDataReader dr = null; try { @@ -83,7 +93,7 @@ private static object GetCachedUserPersonalizationCallback(CacheItemArgs cacheIt { returnValue = dr["ProfileData"].ToString(); } - else //does not exist + else // does not exist { DataProvider.Instance().AddProfile(userId, portalId); } @@ -100,19 +110,7 @@ private static object GetCachedUserPersonalizationCallback(CacheItemArgs cacheIt return returnValue; } - public void SaveProfile(PersonalizationInfo personalization) - { - SaveProfile(personalization, personalization.UserId, personalization.PortalId); - } - - //default implementation relies on HTTPContext - public void SaveProfile(HttpContext httpContext, int userId, int portalId) - { - var objPersonalization = (PersonalizationInfo) httpContext.Items["Personalization"]; - SaveProfile(objPersonalization, userId, portalId); - } - - //override allows for manipulation of PersonalizationInfo outside of HTTPContext + // override allows for manipulation of PersonalizationInfo outside of HTTPContext public void SaveProfile(PersonalizationInfo personalization, int userId, int portalId) { if (personalization != null && personalization.IsModified) @@ -125,19 +123,21 @@ public void SaveProfile(PersonalizationInfo personalization, int userId, int por // remove then re-add the updated one var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); DataCache.RemoveCache(cacheKey); - CBO.GetCachedObject(new CacheItemArgs(cacheKey, + CBO.GetCachedObject( + new CacheItemArgs( + cacheKey, DataCache.UserPersonalizationCacheTimeout, DataCache.UserPersonalizationCachePriority), _ => profileData); } else { - //Anon User - so try and use cookie. + // Anon User - so try and use cookie. var context = HttpContext.Current; if (context != null) { var personalizationCookie = new HttpCookie("DNNPersonalization", EncryptData(profileData)) { Expires = DateTime.Now.AddDays(30), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; context.Response.Cookies.Add(personalizationCookie); } diff --git a/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs b/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs index 5a797837c1f..a5ed3315ec2 100644 --- a/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs +++ b/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs @@ -1,33 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Personalization { + using System; + using System.Collections; + [Serializable] public class PersonalizationInfo - { - #region Private Members - - #endregion - - #region Public Properties - + { public int UserId { get; set; } public int PortalId { get; set; } public bool IsModified { get; set; } - public Hashtable Profile { get; set; } - - #endregion + public Hashtable Profile { get; set; } } } diff --git a/DNN Platform/Library/Services/Registration/IRegistrationProfileController.cs b/DNN Platform/Library/Services/Registration/IRegistrationProfileController.cs index a97ab3c71bf..8043ce5c14a 100644 --- a/DNN Platform/Library/Services/Registration/IRegistrationProfileController.cs +++ b/DNN Platform/Library/Services/Registration/IRegistrationProfileController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Registration { + using System.Collections.Generic; + public interface IRegistrationProfileController { IEnumerable Search(int portalId, string searchValue); diff --git a/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs b/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs index 212842c9c5e..ca6fbb84911 100644 --- a/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs +++ b/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Framework; -using DotNetNuke.Common.Lists; -using DotNetNuke.Entities.Profile; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Registration { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Framework; + public class RegistrationProfileController : ServiceLocator, IRegistrationProfileController { public IEnumerable Search(int portalId, string searchTerm) @@ -24,31 +25,31 @@ public IEnumerable Search(int portalId, string searchTerm) .Cast() .Where(definition => definition.DataType != imageType.EntryID)) { - AddProperty(results, definition.PropertyName, searchTerm); + this.AddProperty(results, definition.PropertyName, searchTerm); } - AddProperty(results, "Email", searchTerm); - AddProperty(results, "DisplayName", searchTerm); - AddProperty(results, "Username", searchTerm); - AddProperty(results, "Password", searchTerm); - AddProperty(results, "PasswordConfirm", searchTerm); - AddProperty(results, "PasswordQuestion", searchTerm); - AddProperty(results, "PasswordAnswer", searchTerm); + this.AddProperty(results, "Email", searchTerm); + this.AddProperty(results, "DisplayName", searchTerm); + this.AddProperty(results, "Username", searchTerm); + this.AddProperty(results, "Password", searchTerm); + this.AddProperty(results, "PasswordConfirm", searchTerm); + this.AddProperty(results, "PasswordQuestion", searchTerm); + this.AddProperty(results, "PasswordAnswer", searchTerm); + + return results; + } - return results; + protected override Func GetFactory() + { + return () => new RegistrationProfileController(); } private void AddProperty(List results, string field, string searchTerm) - { + { if (field.ToLowerInvariant().Contains(searchTerm.ToLowerInvariant().Trim())) { results.Add(field); } } - - protected override Func GetFactory() - { - return () => new RegistrationProfileController(); - } } } diff --git a/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs b/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs index df74307e246..e1374c25990 100644 --- a/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs +++ b/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs @@ -1,65 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Collections; -using System.Collections.Generic; -using System.Threading; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; - -using Microsoft.VisualBasic; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using Microsoft.VisualBasic; + + using Globals = DotNetNuke.Common.Globals; + public class DNNScheduler : SchedulingProvider - { - - #region Public Properties - + { public override Dictionary Settings { get { return ComponentFactory.GetComponentSettings() as Dictionary; } - } - - #endregion - - #region Public Methods - + } + public override int AddSchedule(ScheduleItem scheduleItem) { - //Remove item from queue + // Remove item from queue Scheduler.CoreScheduler.RemoveFromScheduleQueue(scheduleItem); - //save item - scheduleItem.ScheduleID = SchedulingController.AddSchedule(scheduleItem.TypeFullName, - scheduleItem.TimeLapse, - scheduleItem.TimeLapseMeasurement, - scheduleItem.RetryTimeLapse, - scheduleItem.RetryTimeLapseMeasurement, - scheduleItem.RetainHistoryNum, - scheduleItem.AttachToEvent, - scheduleItem.CatchUpEnabled, - scheduleItem.Enabled, - scheduleItem.ObjectDependencies, - scheduleItem.Servers, - scheduleItem.FriendlyName, - scheduleItem.ScheduleStartDate); - //Add schedule to queue - RunScheduleItemNow(scheduleItem); - - //Return Id + + // save item + scheduleItem.ScheduleID = SchedulingController.AddSchedule( + scheduleItem.TypeFullName, + scheduleItem.TimeLapse, + scheduleItem.TimeLapseMeasurement, + scheduleItem.RetryTimeLapse, + scheduleItem.RetryTimeLapseMeasurement, + scheduleItem.RetainHistoryNum, + scheduleItem.AttachToEvent, + scheduleItem.CatchUpEnabled, + scheduleItem.Enabled, + scheduleItem.ObjectDependencies, + scheduleItem.Servers, + scheduleItem.FriendlyName, + scheduleItem.ScheduleStartDate); + + // Add schedule to queue + this.RunScheduleItemNow(scheduleItem); + + // Return Id return scheduleItem.ScheduleID; } @@ -166,8 +156,8 @@ public override void PurgeScheduleHistory() public override void ReStart(string sourceOfRestart) { - Halt(sourceOfRestart); - StartAndWaitForResponse(); + this.Halt(sourceOfRestart); + this.StartAndWaitForResponse(); } public override void RunEventSchedule(EventName eventName) @@ -181,7 +171,7 @@ public override void RunEventSchedule(EventName eventName) public override void RunScheduleItemNow(ScheduleItem scheduleItem, bool runNow) { - //Remove item from queue + // Remove item from queue Scheduler.CoreScheduler.RemoveFromScheduleQueue(scheduleItem); var scheduleHistoryItem = new ScheduleHistoryItem(scheduleItem) { NextStart = runNow ? DateTime.Now : (scheduleItem.ScheduleStartDate != Null.NullDate ? scheduleItem.ScheduleStartDate : DateTime.Now) }; @@ -199,7 +189,7 @@ public override void RunScheduleItemNow(ScheduleItem scheduleItem, bool runNow) public override void RunScheduleItemNow(ScheduleItem scheduleItem) { - RunScheduleItemNow(scheduleItem, false); + this.RunScheduleItemNow(scheduleItem, false); } public override void Start() @@ -217,17 +207,18 @@ public override void StartAndWaitForResponse() { if (Enabled) { - var newThread = new Thread(Start) {IsBackground = true}; + var newThread = new Thread(this.Start) { IsBackground = true }; newThread.Start(); - //wait for up to 30 seconds for thread - //to start up + // wait for up to 30 seconds for thread + // to start up for (int i = 0; i <= 30; i++) { - if (GetScheduleStatus() != ScheduleStatus.STOPPED) + if (this.GetScheduleStatus() != ScheduleStatus.STOPPED) { return; } + Thread.Sleep(1000); } } @@ -240,12 +231,14 @@ public override void UpdateScheduleWithoutExecution(ScheduleItem scheduleItem) public override void UpdateSchedule(ScheduleItem scheduleItem) { - //Remove item from queue + // Remove item from queue Scheduler.CoreScheduler.RemoveFromScheduleQueue(scheduleItem); - //save item + + // save item SchedulingController.UpdateSchedule(scheduleItem); - //Update items that are already scheduled - var futureHistory = GetScheduleHistory(scheduleItem.ScheduleID).Cast().Where(h => h.NextStart > DateTime.Now); + + // Update items that are already scheduled + var futureHistory = this.GetScheduleHistory(scheduleItem.ScheduleID).Cast().Where(h => h.NextStart > DateTime.Now); var scheduleItemStart = scheduleItem.ScheduleStartDate > DateTime.Now ? scheduleItem.ScheduleStartDate @@ -255,20 +248,17 @@ public override void UpdateSchedule(ScheduleItem scheduleItem) scheduleHistoryItem.NextStart = scheduleItemStart; SchedulingController.UpdateScheduleHistory(scheduleHistoryItem); } - - - //Add schedule to queue - RunScheduleItemNow(scheduleItem); + + // Add schedule to queue + this.RunScheduleItemNow(scheduleItem); } - //DNN-5001 Possibility to stop already running tasks + // DNN-5001 Possibility to stop already running tasks public override void RemoveFromScheduleInProgress(ScheduleItem scheduleItem) { - //get ScheduleHistoryItem of the running task - var runningscheduleHistoryItem = GetScheduleHistory(scheduleItem.ScheduleID).Cast().ElementAtOrDefault(0); + // get ScheduleHistoryItem of the running task + var runningscheduleHistoryItem = this.GetScheduleHistory(scheduleItem.ScheduleID).Cast().ElementAtOrDefault(0); Scheduler.CoreScheduler.StopScheduleInProgress(scheduleItem, runningscheduleHistoryItem); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs index ed24b08e792..d64380637d8 100644 --- a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs +++ b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs @@ -1,39 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Reflection; -using System.Threading; -using System.Web.Compilation; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using Microsoft.Extensions.DependencyInjection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System; + using System.Reflection; + using System.Threading; + using System.Web.Compilation; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + using Microsoft.Extensions.DependencyInjection; + public class ProcessGroup { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ProcessGroup)); - //'''''''''''''''''''''''''''''''''''''''''''''''''' - //This class represents a process group for - //our threads to run in. - //'''''''''''''''''''''''''''''''''''''''''''''''''' - #region Delegates - - public delegate void CompletedEventHandler(); - - #endregion - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProcessGroup)); + private static int numberOfProcessesInQueue; private static int numberOfProcesses; private static int processesCompleted; + + // '''''''''''''''''''''''''''''''''''''''''''''''''' + // This class represents a process group for + // our threads to run in. + // '''''''''''''''''''''''''''''''''''''''''''''''''' + public delegate void CompletedEventHandler(); private static int ticksElapsed; + public event CompletedEventHandler Completed; + private static int GetTicksElapsed { get @@ -58,29 +53,27 @@ private static int GetProcessesInQueue } } - public event CompletedEventHandler Completed; - public void Run(ScheduleHistoryItem objScheduleHistoryItem) { IServiceScope serviceScope = null; SchedulerClient Process = null; try { - //This is called from RunPooledThread() + // This is called from RunPooledThread() ticksElapsed = Environment.TickCount - ticksElapsed; serviceScope = Globals.DependencyProvider.CreateScope(); - Process = GetSchedulerClient(serviceScope.ServiceProvider, objScheduleHistoryItem.TypeFullName, objScheduleHistoryItem); + Process = this.GetSchedulerClient(serviceScope.ServiceProvider, objScheduleHistoryItem.TypeFullName, objScheduleHistoryItem); Process.ScheduleHistoryItem = objScheduleHistoryItem; - - //Set up the handlers for the CoreScheduler + + // Set up the handlers for the CoreScheduler Process.ProcessStarted += Scheduler.CoreScheduler.WorkStarted; Process.ProcessProgressing += Scheduler.CoreScheduler.WorkProgressing; Process.ProcessCompleted += Scheduler.CoreScheduler.WorkCompleted; Process.ProcessErrored += Scheduler.CoreScheduler.WorkErrored; - //This kicks off the DoWork method of the class - //type specified in the configuration. - - Process.Started(); + + // This kicks off the DoWork method of the class + // type specified in the configuration. + Process.Started(); try { Process.ScheduleHistoryItem.Succeeded = false; @@ -88,9 +81,9 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) } catch (Exception exc) { - //in case the scheduler client - //didn't have proper exception handling - //make sure we fire the Errored event + // in case the scheduler client + // didn't have proper exception handling + // make sure we fire the Errored event Logger.Error(exc); if (Process != null) @@ -99,50 +92,52 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) { Process.ScheduleHistoryItem.Succeeded = false; } + Process.Errored(ref exc); } } + if (Process.ScheduleHistoryItem.Succeeded) { Process.Completed(); } - - //If all processes in this ProcessGroup have - //completed, set the ticksElapsed and raise - //the Completed event. - //I don't think this is necessary with the - //other events. I'll leave it for now and - //will probably take it out later. - if (processesCompleted == numberOfProcesses) + // If all processes in this ProcessGroup have + // completed, set the ticksElapsed and raise + // the Completed event. + // I don't think this is necessary with the + // other events. I'll leave it for now and + // will probably take it out later. + if (processesCompleted == numberOfProcesses) { if (processesCompleted == numberOfProcesses) { ticksElapsed = Environment.TickCount - ticksElapsed; - if (Completed != null) + if (this.Completed != null) { - Completed(); + this.Completed(); } } } } catch (Exception exc) { - //in case the scheduler client - //didn't have proper exception handling - //make sure we fire the Errored event + // in case the scheduler client + // didn't have proper exception handling + // make sure we fire the Errored event if (Process != null) { if (Process.ScheduleHistoryItem != null) { Process.ScheduleHistoryItem.Succeeded = false; } + Process.Errored(ref exc); } else { - //when the schedule has invalid config and can't initialize the Process, - //we need also trigger work errored event so that the schedule can remove from inprogress and inqueue list to prevent endless loop. + // when the schedule has invalid config and can't initialize the Process, + // we need also trigger work errored event so that the schedule can remove from inprogress and inqueue list to prevent endless loop. Scheduler.CoreScheduler.WorkStarted(objScheduleHistoryItem); objScheduleHistoryItem.Succeeded = false; Scheduler.CoreScheduler.WorkErrored(objScheduleHistoryItem, exc); @@ -152,31 +147,15 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) { serviceScope?.Dispose(); - //Track how many processes have completed for - //this instanciation of the ProcessGroup + // Track how many processes have completed for + // this instanciation of the ProcessGroup numberOfProcessesInQueue -= 1; processesCompleted += 1; } } - private SchedulerClient GetSchedulerClient(IServiceProvider services, string strProcess, ScheduleHistoryItem objScheduleHistoryItem) - { - //This is a method to encapsulate returning - //an object whose class inherits SchedulerClient. - Type t = BuildManager.GetType(strProcess, true, true); - return (SchedulerClient)ActivatorUtilities.CreateInstance(services, t, objScheduleHistoryItem); - } - - //This subroutine is callback for Threadpool.QueueWorkItem. This is the necessary - //subroutine signature for QueueWorkItem, and Run() is proper for creating a Thread - //so the two subroutines cannot be combined, so instead just call Run from here. - private void RunPooledThread(object objScheduleHistoryItem) - { - Run((ScheduleHistoryItem) objScheduleHistoryItem); - } - - //Add a queue request to Threadpool with a - //callback to RunPooledThread which calls Run() + // Add a queue request to Threadpool with a + // callback to RunPooledThread which calls Run() public void AddQueueUserWorkItem(ScheduleItem s) { numberOfProcessesInQueue += 1; @@ -184,9 +163,10 @@ public void AddQueueUserWorkItem(ScheduleItem s) var obj = new ScheduleHistoryItem(s); try { - //Create a callback to subroutine RunPooledThread - WaitCallback callback = RunPooledThread; - //And put in a request to ThreadPool to run the process. + // Create a callback to subroutine RunPooledThread + WaitCallback callback = this.RunPooledThread; + + // And put in a request to ThreadPool to run the process. ThreadPool.QueueUserWorkItem(callback, obj); } catch (Exception exc) @@ -194,5 +174,21 @@ public void AddQueueUserWorkItem(ScheduleItem s) Exceptions.Exceptions.ProcessSchedulerException(exc); } } + + private SchedulerClient GetSchedulerClient(IServiceProvider services, string strProcess, ScheduleHistoryItem objScheduleHistoryItem) + { + // This is a method to encapsulate returning + // an object whose class inherits SchedulerClient. + Type t = BuildManager.GetType(strProcess, true, true); + return (SchedulerClient)ActivatorUtilities.CreateInstance(services, t, objScheduleHistoryItem); + } + + // This subroutine is callback for Threadpool.QueueWorkItem. This is the necessary + // subroutine signature for QueueWorkItem, and Run() is proper for creating a Thread + // so the two subroutines cannot be combined, so instead just call Run from here. + private void RunPooledThread(object objScheduleHistoryItem) + { + this.Run((ScheduleHistoryItem)objScheduleHistoryItem); + } } } diff --git a/DNN Platform/Library/Services/Scheduling/PurgeScheduleHistory.cs b/DNN Platform/Library/Services/Scheduling/PurgeScheduleHistory.cs index 1b41d14f3de..b8dc13483ee 100644 --- a/DNN Platform/Library/Services/Scheduling/PurgeScheduleHistory.cs +++ b/DNN Platform/Library/Services/Scheduling/PurgeScheduleHistory.cs @@ -1,45 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System; + public class PurgeScheduleHistory : SchedulerClient { public PurgeScheduleHistory(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } public override void DoWork() { try { - //notification that the event is progressing - Progressing(); + // notification that the event is progressing + this.Progressing(); SchedulingProvider.Instance().PurgeScheduleHistory(); - //update the result to success since no exception was thrown - ScheduleHistoryItem.Succeeded = true; - ScheduleHistoryItem.AddLogNote("Schedule history purged."); + // update the result to success since no exception was thrown + this.ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.AddLogNote("Schedule history purged."); } catch (Exception exc) { - ScheduleHistoryItem.Succeeded = false; - ScheduleHistoryItem.AddLogNote("Schedule history purge failed." + exc); - ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.AddLogNote("Schedule history purge failed." + exc); + this.ScheduleHistoryItem.Succeeded = false; + + // notification that we have errored + this.Errored(ref exc); - //notification that we have errored - Errored(ref exc); - - //log the exception + // log the exception Exceptions.Exceptions.LogException(exc); } } diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs b/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs index 9133a21af46..30e69483f74 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Text; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System; + using System.Data; + using System.Text; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + [Serializable] public class ScheduleHistoryItem : ScheduleItem { @@ -28,40 +23,40 @@ public class ScheduleHistoryItem : ScheduleItem public ScheduleHistoryItem() { - _ScheduleHistoryID = Null.NullInteger; - _StartDate = Null.NullDate; - EndDate = Null.NullDate; - _Succeeded = Null.NullBoolean; - _LogNotes = new StringBuilder(); - _Server = Null.NullString; + this._ScheduleHistoryID = Null.NullInteger; + this._StartDate = Null.NullDate; + this.EndDate = Null.NullDate; + this._Succeeded = Null.NullBoolean; + this._LogNotes = new StringBuilder(); + this._Server = Null.NullString; } public ScheduleHistoryItem(ScheduleItem objScheduleItem) { - AttachToEvent = objScheduleItem.AttachToEvent; - CatchUpEnabled = objScheduleItem.CatchUpEnabled; - Enabled = objScheduleItem.Enabled; - NextStart = objScheduleItem.NextStart; - ObjectDependencies = objScheduleItem.ObjectDependencies; - ProcessGroup = objScheduleItem.ProcessGroup; - RetainHistoryNum = objScheduleItem.RetainHistoryNum; - RetryTimeLapse = objScheduleItem.RetryTimeLapse; - RetryTimeLapseMeasurement = objScheduleItem.RetryTimeLapseMeasurement; - ScheduleID = objScheduleItem.ScheduleID; - ScheduleSource = objScheduleItem.ScheduleSource; - ThreadID = objScheduleItem.ThreadID; - TimeLapse = objScheduleItem.TimeLapse; - TimeLapseMeasurement = objScheduleItem.TimeLapseMeasurement; - TypeFullName = objScheduleItem.TypeFullName; - Servers = objScheduleItem.Servers; - FriendlyName = objScheduleItem.FriendlyName; - _ScheduleHistoryID = Null.NullInteger; - _StartDate = Null.NullDate; - EndDate = Null.NullDate; - _Succeeded = Null.NullBoolean; - _LogNotes = new StringBuilder(); - _Server = Null.NullString; - ScheduleStartDate = objScheduleItem.ScheduleStartDate != Null.NullDate + this.AttachToEvent = objScheduleItem.AttachToEvent; + this.CatchUpEnabled = objScheduleItem.CatchUpEnabled; + this.Enabled = objScheduleItem.Enabled; + this.NextStart = objScheduleItem.NextStart; + this.ObjectDependencies = objScheduleItem.ObjectDependencies; + this.ProcessGroup = objScheduleItem.ProcessGroup; + this.RetainHistoryNum = objScheduleItem.RetainHistoryNum; + this.RetryTimeLapse = objScheduleItem.RetryTimeLapse; + this.RetryTimeLapseMeasurement = objScheduleItem.RetryTimeLapseMeasurement; + this.ScheduleID = objScheduleItem.ScheduleID; + this.ScheduleSource = objScheduleItem.ScheduleSource; + this.ThreadID = objScheduleItem.ThreadID; + this.TimeLapse = objScheduleItem.TimeLapse; + this.TimeLapseMeasurement = objScheduleItem.TimeLapseMeasurement; + this.TypeFullName = objScheduleItem.TypeFullName; + this.Servers = objScheduleItem.Servers; + this.FriendlyName = objScheduleItem.FriendlyName; + this._ScheduleHistoryID = Null.NullInteger; + this._StartDate = Null.NullDate; + this.EndDate = Null.NullDate; + this._Succeeded = Null.NullBoolean; + this._LogNotes = new StringBuilder(); + this._Server = Null.NullString; + this.ScheduleStartDate = objScheduleItem.ScheduleStartDate != Null.NullDate ? objScheduleItem.ScheduleStartDate : Null.NullDate; } @@ -74,13 +69,13 @@ public double ElapsedTime { try { - if (EndDate == Null.NullDate && _StartDate != Null.NullDate) + if (this.EndDate == Null.NullDate && this._StartDate != Null.NullDate) { - return DateTime.Now.Subtract(_StartDate).TotalSeconds; + return DateTime.Now.Subtract(this._StartDate).TotalSeconds; } - else if (_StartDate != Null.NullDate) + else if (this._StartDate != Null.NullDate) { - return EndDate.Subtract(_StartDate).TotalSeconds; + return this.EndDate.Subtract(this._StartDate).TotalSeconds; } else { @@ -100,11 +95,12 @@ public string LogNotes { get { - return _LogNotes.ToString(); + return this._LogNotes.ToString(); } + set { - _LogNotes = new StringBuilder(value); + this._LogNotes = new StringBuilder(value); } } @@ -112,7 +108,7 @@ public bool Overdue { get { - if (NextStart < DateTime.Now && EndDate == Null.NullDate) + if (this.NextStart < DateTime.Now && this.EndDate == Null.NullDate) { return true; } @@ -129,9 +125,9 @@ public double OverdueBy { try { - if (NextStart <= DateTime.Now && EndDate == Null.NullDate) + if (this.NextStart <= DateTime.Now && this.EndDate == Null.NullDate) { - return Math.Round(DateTime.Now.Subtract(NextStart).TotalSeconds); + return Math.Round(DateTime.Now.Subtract(this.NextStart).TotalSeconds); } else { @@ -151,9 +147,9 @@ public double RemainingTime { try { - if (NextStart > DateTime.Now && EndDate == Null.NullDate) + if (this.NextStart > DateTime.Now && this.EndDate == Null.NullDate) { - return Math.Round(NextStart.Subtract(DateTime.Now).TotalSeconds); + return Math.Round(this.NextStart.Subtract(DateTime.Now).TotalSeconds); } else { @@ -171,11 +167,12 @@ public int ScheduleHistoryID { get { - return _ScheduleHistoryID; + return this._ScheduleHistoryID; } + set { - _ScheduleHistoryID = value; + this._ScheduleHistoryID = value; } } @@ -183,11 +180,12 @@ public string Server { get { - return _Server; + return this._Server; } + set { - _Server = value; + this._Server = value; } } @@ -195,11 +193,12 @@ public DateTime StartDate { get { - return _StartDate; + return this._StartDate; } + set { - _StartDate = value; + this._StartDate = value; } } @@ -207,32 +206,37 @@ public bool Succeeded { get { - return _Succeeded; + return this._Succeeded; } + set { - _Succeeded = value; - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"ScheduleHistoryItem.Succeeded Info (ScheduledTask {(value == false ? "Start" : "End")}): {FriendlyName}"); + this._Succeeded = value; + if (_tracelLogger.IsDebugEnabled) + { + _tracelLogger.Debug($"ScheduleHistoryItem.Succeeded Info (ScheduledTask {(value == false ? "Start" : "End")}): {this.FriendlyName}"); + } } } public virtual void AddLogNote(string notes) { - _LogNotes.Append(notes); - if (_tracelLogger.IsTraceEnabled) - _tracelLogger.Trace(notes.Replace(@"
    ", Environment.NewLine)); + this._LogNotes.Append(notes); + if (_tracelLogger.IsTraceEnabled) + { + _tracelLogger.Trace(notes.Replace(@"
    ", Environment.NewLine)); + } } public override void Fill(IDataReader dr) { - ScheduleHistoryID = Null.SetNullInteger(dr["ScheduleHistoryID"]); - StartDate = Null.SetNullDateTime(dr["StartDate"]); - EndDate = Null.SetNullDateTime(dr["EndDate"]); - Succeeded = Null.SetNullBoolean(dr["Succeeded"]); - LogNotes = Null.SetNullString(dr["LogNotes"]); - Server = Null.SetNullString(dr["Server"]); - FillInternal(dr); + this.ScheduleHistoryID = Null.SetNullInteger(dr["ScheduleHistoryID"]); + this.StartDate = Null.SetNullDateTime(dr["StartDate"]); + this.EndDate = Null.SetNullDateTime(dr["EndDate"]); + this.Succeeded = Null.SetNullBoolean(dr["Succeeded"]); + this.LogNotes = Null.SetNullString(dr["LogNotes"]); + this.Server = Null.SetNullString(dr["Server"]); + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs b/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs index 8dc65373c1d..e57dc82735d 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs @@ -1,32 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System.Collections; + /// ----------------------------------------------------------------------------- /// /// The ScheduleHistorySortStartDate Class is a custom IComparer Implementation - /// used to sort the Schedule Items + /// used to sort the Schedule Items. /// /// /// /// ----------------------------------------------------------------------------- public class ScheduleHistorySortStartDate : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { - return ((ScheduleHistoryItem) y).StartDate.CompareTo(((ScheduleHistoryItem) x).StartDate); - } - - #endregion + return ((ScheduleHistoryItem)y).StartDate.CompareTo(((ScheduleHistoryItem)x).StartDate); + } } } diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs b/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs index 057a50c4695..af52c88f0a2 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs @@ -1,57 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System; + using System.Collections; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + [Serializable] public class ScheduleItem : BaseEntityInfo, IHydratable - { - #region Private Members - - private static readonly DateTime MinNextTime = DateTime.Now; + { + private static readonly DateTime MinNextTime = DateTime.Now; private DateTime? _NextStart; - private Hashtable _ScheduleItemSettings; - - #endregion - - #region Constructors - + private Hashtable _ScheduleItemSettings; + public ScheduleItem() { - ScheduleID = Null.NullInteger; - TypeFullName = Null.NullString; - TimeLapse = Null.NullInteger; - TimeLapseMeasurement = Null.NullString; - RetryTimeLapse = Null.NullInteger; - RetryTimeLapseMeasurement = Null.NullString; - ObjectDependencies = Null.NullString; - RetainHistoryNum = Null.NullInteger; - CatchUpEnabled = Null.NullBoolean; - Enabled = Null.NullBoolean; - AttachToEvent = Null.NullString; - ThreadID = Null.NullInteger; - ProcessGroup = Null.NullInteger; - Servers = Null.NullString; - ScheduleStartDate = Null.NullDate; - } - - #endregion - - #region Persisted Properties - + this.ScheduleID = Null.NullInteger; + this.TypeFullName = Null.NullString; + this.TimeLapse = Null.NullInteger; + this.TimeLapseMeasurement = Null.NullString; + this.RetryTimeLapse = Null.NullInteger; + this.RetryTimeLapseMeasurement = Null.NullString; + this.ObjectDependencies = Null.NullString; + this.RetainHistoryNum = Null.NullInteger; + this.CatchUpEnabled = Null.NullBoolean; + this.Enabled = Null.NullBoolean; + this.AttachToEvent = Null.NullString; + this.ThreadID = Null.NullInteger; + this.ProcessGroup = Null.NullInteger; + this.Servers = Null.NullString; + this.ScheduleStartDate = Null.NullDate; + } + public string AttachToEvent { get; set; } public bool CatchUpEnabled { get; set; } @@ -66,15 +51,17 @@ public virtual DateTime NextStart { get { - if (!_NextStart.HasValue) + if (!this._NextStart.HasValue) { - _NextStart = MinNextTime; + this._NextStart = MinNextTime; } - return _NextStart.Value > MinNextTime ? _NextStart.Value : MinNextTime; + + return this._NextStart.Value > MinNextTime ? this._NextStart.Value : MinNextTime; } + set { - _NextStart = value; + this._NextStart = value; } } @@ -100,31 +87,26 @@ public virtual DateTime NextStart public ScheduleSource ScheduleSource { get; set; } - public int ThreadID { get; set; } - - #endregion - - #region IHydratable Members - + public int ThreadID { get; set; } + public int KeyID { get { - return ScheduleID; + return this.ScheduleID; } + set { - ScheduleID = value; + this.ScheduleID = value; } } public virtual void Fill(IDataReader dr) { - FillInternal(dr); - } - - #endregion - + this.FillInternal(dr); + } + public bool HasObjectDependencies(string strObjectDependencies) { if (strObjectDependencies.IndexOf(",") > -1) @@ -134,80 +116,80 @@ public bool HasObjectDependencies(string strObjectDependencies) int i; for (i = 0; i <= a.Length - 1; i++) { - if (ObjectDependencies.IndexOf(a[i].Trim(), StringComparison.InvariantCultureIgnoreCase) > -1) + if (this.ObjectDependencies.IndexOf(a[i].Trim(), StringComparison.InvariantCultureIgnoreCase) > -1) { return true; } } } - else if (ObjectDependencies.IndexOf(strObjectDependencies, StringComparison.InvariantCultureIgnoreCase) > -1) + else if (this.ObjectDependencies.IndexOf(strObjectDependencies, StringComparison.InvariantCultureIgnoreCase) > -1) { return true; } + return false; - } - - #region "Public Methods" - + } + public void AddSetting(string Key, string Value) { - _ScheduleItemSettings.Add(Key, Value); + this._ScheduleItemSettings.Add(Key, Value); } public virtual string GetSetting(string Key) { - if (_ScheduleItemSettings == null) + if (this._ScheduleItemSettings == null) { - GetSettings(); + this.GetSettings(); } - if (_ScheduleItemSettings != null && _ScheduleItemSettings.ContainsKey(Key)) + + if (this._ScheduleItemSettings != null && this._ScheduleItemSettings.ContainsKey(Key)) { - return Convert.ToString(_ScheduleItemSettings[Key]); + return Convert.ToString(this._ScheduleItemSettings[Key]); } else { - return ""; + return string.Empty; } } public virtual Hashtable GetSettings() { - _ScheduleItemSettings = SchedulingProvider.Instance().GetScheduleItemSettings(ScheduleID); - return _ScheduleItemSettings; + this._ScheduleItemSettings = SchedulingProvider.Instance().GetScheduleItemSettings(this.ScheduleID); + return this._ScheduleItemSettings; } protected override void FillInternal(IDataReader dr) { - ScheduleID = Null.SetNullInteger(dr["ScheduleID"]); - FriendlyName = Null.SetNullString(dr["FriendlyName"]); - TypeFullName = Null.SetNullString(dr["TypeFullName"]); - TimeLapse = Null.SetNullInteger(dr["TimeLapse"]); - TimeLapseMeasurement = Null.SetNullString(dr["TimeLapseMeasurement"]); - RetryTimeLapse = Null.SetNullInteger(dr["RetryTimeLapse"]); - RetryTimeLapseMeasurement = Null.SetNullString(dr["RetryTimeLapseMeasurement"]); - ObjectDependencies = Null.SetNullString(dr["ObjectDependencies"]); - AttachToEvent = Null.SetNullString(dr["AttachToEvent"]); - RetainHistoryNum = Null.SetNullInteger(dr["RetainHistoryNum"]); - CatchUpEnabled = Null.SetNullBoolean(dr["CatchUpEnabled"]); - Enabled = Null.SetNullBoolean(dr["Enabled"]); - Servers = Null.SetNullString(dr["Servers"]); + this.ScheduleID = Null.SetNullInteger(dr["ScheduleID"]); + this.FriendlyName = Null.SetNullString(dr["FriendlyName"]); + this.TypeFullName = Null.SetNullString(dr["TypeFullName"]); + this.TimeLapse = Null.SetNullInteger(dr["TimeLapse"]); + this.TimeLapseMeasurement = Null.SetNullString(dr["TimeLapseMeasurement"]); + this.RetryTimeLapse = Null.SetNullInteger(dr["RetryTimeLapse"]); + this.RetryTimeLapseMeasurement = Null.SetNullString(dr["RetryTimeLapseMeasurement"]); + this.ObjectDependencies = Null.SetNullString(dr["ObjectDependencies"]); + this.AttachToEvent = Null.SetNullString(dr["AttachToEvent"]); + this.RetainHistoryNum = Null.SetNullInteger(dr["RetainHistoryNum"]); + this.CatchUpEnabled = Null.SetNullBoolean(dr["CatchUpEnabled"]); + this.Enabled = Null.SetNullBoolean(dr["Enabled"]); + this.Servers = Null.SetNullString(dr["Servers"]); var schema = dr.GetSchemaTable(); if (schema != null) { if (schema.Select("ColumnName = 'NextStart'").Length > 0) { - NextStart = Null.SetNullDateTime(dr["NextStart"]); + this.NextStart = Null.SetNullDateTime(dr["NextStart"]); } + if (schema.Select("ColumnName = 'ScheduleStartDate'").Length > 0) { - ScheduleStartDate = Null.SetNullDateTime(dr["ScheduleStartDate"]); + this.ScheduleStartDate = Null.SetNullDateTime(dr["ScheduleStartDate"]); } } - //Fill BaseEntityInfo + + // Fill BaseEntityInfo base.FillInternal(dr); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs b/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs index ec089eee269..8e77f0c3476 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs @@ -1,32 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System.Collections; + /// ----------------------------------------------------------------------------- /// /// The ScheduleStatusSortRemainingTimeDescending Class is a custom IComparer Implementation - /// used to sort the Schedule Items + /// used to sort the Schedule Items. /// /// /// /// ----------------------------------------------------------------------------- public class ScheduleStatusSortRemainingTimeDescending : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { - return ((ScheduleHistoryItem) x).RemainingTime.CompareTo(((ScheduleHistoryItem) y).RemainingTime); - } - - #endregion + return ((ScheduleHistoryItem)x).RemainingTime.CompareTo(((ScheduleHistoryItem)y).RemainingTime); + } } } diff --git a/DNN Platform/Library/Services/Scheduling/Scheduler.cs b/DNN Platform/Library/Services/Scheduling/Scheduler.cs index 6aeedce1fcc..2102667baa0 100644 --- a/DNN Platform/Library/Services/Scheduling/Scheduler.cs +++ b/DNN Platform/Library/Services/Scheduling/Scheduler.cs @@ -1,43 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Principal; -using System.Text; -using System.Threading; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Log.EventLog; -using Microsoft.VisualBasic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Scheduling { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Security.Principal; + using System.Text; + using System.Threading; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Log.EventLog; + using Microsoft.VisualBasic; + internal static class Scheduler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Scheduler)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Scheduler)); + internal static class CoreScheduler { - //This is the heart of the scheduler mechanism. - //This class manages running new events according - //to the schedule. + // If KeepRunning gets switched to false, + // the scheduler stops running. + public static bool KeepThreadAlive = true; + public static bool KeepRunning = true; + + // This is the heart of the scheduler mechanism. + // This class manages running new events according + // to the schedule. // - //This class can also react to the three - //scheduler events (Started, Progressing and Completed) + // This class can also react to the three + // scheduler events (Started, Progressing and Completed) private static bool _threadPoolInitialized; - //The MaxThreadCount establishes the maximum - //threads you want running simultaneously - //for spawning SchedulerClient processes + // The MaxThreadCount establishes the maximum + // threads you want running simultaneously + // for spawning SchedulerClient processes private static int _maxThreadCount; private static int _activeThreadCount; - //If KeepRunning gets switched to false, - //the scheduler stops running. + // If KeepRunning gets switched to false, + // the scheduler stops running. private static bool _forceReloadSchedule; private static bool _debug; @@ -46,26 +53,21 @@ internal static class CoreScheduler private static readonly SharedList ScheduleQueue; private static readonly SharedList ScheduleInProgress; - //This is our array that holds the process group - //where our threads will be kicked off. + // This is our array that holds the process group + // where our threads will be kicked off. private static ProcessGroup[] _processGroup; - //A ReaderWriterLockSlim will protect our objects - //in memory from being corrupted by simultaneous - //thread operations. This block of code below - //establishes variables to help keep track - //of the ReaderWriter locks. + // A ReaderWriterLockSlim will protect our objects + // in memory from being corrupted by simultaneous + // thread operations. This block of code below + // establishes variables to help keep track + // of the ReaderWriter locks. private static int _readerTimeouts; private static int _writerTimeouts; private static readonly TimeSpan LockTimeout = TimeSpan.FromSeconds(45); private static readonly ReaderWriterLockSlim StatusLock = new ReaderWriterLockSlim(); private static ScheduleStatus _status = ScheduleStatus.STOPPED; - //If KeepRunning gets switched to false, - //the scheduler stops running. - public static bool KeepThreadAlive = true; - public static bool KeepRunning = true; - static CoreScheduler() { var lockStrategy = new ReaderWriterLockStrategy(LockRecursionPolicy.SupportsRecursion); @@ -74,8 +76,10 @@ static CoreScheduler() ScheduleInProgress = new SharedList(lockStrategy); } + private delegate void AddToScheduleInProgressDelegate(ScheduleHistoryItem item); + /// - /// tracks how many threads we have free to work with at any given time. + /// Gets tracks how many threads we have free to work with at any given time. /// public static int FreeThreads { @@ -85,20 +89,99 @@ public static int FreeThreads } } + public static ScheduleHistoryItem AddScheduleHistory(ScheduleHistoryItem scheduleHistoryItem) + { + try + { + int scheduleHistoryID = SchedulingController.AddScheduleHistory(scheduleHistoryItem); + scheduleHistoryItem.ScheduleHistoryID = scheduleHistoryID; + } + catch (Exception exc) + { + Exceptions.Exceptions.ProcessSchedulerException(exc); + } + + return scheduleHistoryItem; + } + + /// + /// Adds an item to the collection of schedule items in queue. + /// + /// + /// Thread Safe. + public static void AddToScheduleQueue(ScheduleHistoryItem scheduleHistoryItem) + { + if (!ScheduleQueueContains(scheduleHistoryItem)) + { + try + { + // objQueueReadWriteLock.EnterWriteLock(WriteTimeout) + using (ScheduleQueue.GetWriteLock(LockTimeout)) + { + // Do a second check just in case + if (!ScheduleQueueContains(scheduleHistoryItem) && + !IsInProgress(scheduleHistoryItem)) + { + // It is safe for this thread to read or write + // from the shared resource. + ScheduleQueue.Add(scheduleHistoryItem); + } + } + } + catch (ApplicationException ex) + { + // The writer lock request timed out. + Interlocked.Increment(ref _writerTimeouts); + Exceptions.Exceptions.LogException(ex); + } + } + } + + internal static bool IsInQueue(ScheduleItem scheduleItem) + { + try + { + using (ScheduleQueue.GetReadLock(LockTimeout)) + { + return ScheduleQueue.Any(si => si.ScheduleID == scheduleItem.ScheduleID); + } + } + catch (ApplicationException) + { + // The reader lock request timed out. + Interlocked.Increment(ref _readerTimeouts); + return false; + } + } + + internal static ServerInfo GetServer(string executingServer) + { + try + { + return ServerController.GetServers().FirstOrDefault( + s => ServerController.GetServerName(s).Equals(executingServer, StringComparison.OrdinalIgnoreCase) && s.Enabled); + } + catch (Exception) + { + // catches edge-case where schedule runs before webserver registration + return null; + } + } + /// /// adds an item to the collection of schedule items in progress. /// - /// Item to add - /// Thread Safe + /// Item to add. + /// Thread Safe. private static void AddToScheduleInProgress(ScheduleHistoryItem scheduleHistoryItem) { - if (!(ScheduleInProgressContains(scheduleHistoryItem))) + if (!ScheduleInProgressContains(scheduleHistoryItem)) { try { using (ScheduleInProgress.GetWriteLock(LockTimeout)) { - if (!(ScheduleInProgressContains(scheduleHistoryItem))) + if (!ScheduleInProgressContains(scheduleHistoryItem)) { ScheduleInProgress.Add(scheduleHistoryItem); } @@ -115,7 +198,7 @@ private static void AddToScheduleInProgress(ScheduleHistoryItem scheduleHistoryI private static int GetProcessGroup() { - //return a random process group + // return a random process group var r = new Random(); return r.Next(0, _numberOfProcessGroups - 1); } @@ -133,8 +216,11 @@ private static bool IsInProgress(ScheduleItem scheduleItem) { // The reader lock request timed out. Interlocked.Increment(ref _readerTimeouts); - if (Logger.IsDebugEnabled) - Logger.Debug(ex); + if (Logger.IsDebugEnabled) + { + Logger.Debug(ex); + } + return false; } } @@ -143,7 +229,7 @@ private static bool IsInProgress(ScheduleItem scheduleItem) /// Removes an item from the collection of schedule items in progress. ///
    /// - /// Thread Safe + /// Thread Safe. private static void RemoveFromScheduleInProgress(ScheduleItem scheduleItem) { try @@ -169,7 +255,7 @@ private static void RemoveFromScheduleInProgress(ScheduleItem scheduleItem) /// Gets a schedulehistory item from the collection of schedule items in progress. /// /// - /// Thread Safe + /// Thread Safe. private static ScheduleHistoryItem GetScheduleItemFromScheduleInProgress(ScheduleItem scheduleItem) { try @@ -179,7 +265,6 @@ private static ScheduleHistoryItem GetScheduleItemFromScheduleInProgress(Schedul var item = ScheduleInProgress.FirstOrDefault(si => si.ScheduleID == scheduleItem.ScheduleID); return item; } - } catch (ApplicationException ex) { @@ -187,10 +272,10 @@ private static ScheduleHistoryItem GetScheduleItemFromScheduleInProgress(Schedul Interlocked.Increment(ref _writerTimeouts); Exceptions.Exceptions.LogException(ex); } + return null; } - - + private static bool ScheduleInProgressContains(ScheduleHistoryItem scheduleHistoryItem) { try @@ -224,159 +309,88 @@ private static bool ScheduleQueueContains(ScheduleItem objScheduleItem) return false; } } - - internal static bool IsInQueue(ScheduleItem scheduleItem) + + public static void FireEvents() { - try + // This method uses a thread pool to + // call the SchedulerClient methods that need + // to be called. + + // For each item in the queue that there + // is an open thread for, set the object + // in the array to a new ProcessGroup object. + // Pass in the ScheduleItem to the ProcessGroup + // so the ProcessGroup can pass it around for + // logging and notifications. + lock (ScheduleQueue) { + var scheduleList = new List(); using (ScheduleQueue.GetReadLock(LockTimeout)) { - return ScheduleQueue.Any(si => si.ScheduleID == scheduleItem.ScheduleID); + foreach (ScheduleItem scheduleItem in ScheduleQueue) + { + scheduleList.Add(scheduleItem); + } } - } - catch (ApplicationException) - { - // The reader lock request timed out. - Interlocked.Increment(ref _readerTimeouts); - return false; - } - } - internal static ServerInfo GetServer(string executingServer) - { - try - { - return ServerController.GetServers().FirstOrDefault( - s => ServerController.GetServerName(s).Equals(executingServer, StringComparison.OrdinalIgnoreCase) && s.Enabled); - } - catch (Exception) - { - //catches edge-case where schedule runs before webserver registration - return null; - } - - } + int numToRun = scheduleList.Count; + int numRun = 0; - public static ScheduleHistoryItem AddScheduleHistory(ScheduleHistoryItem scheduleHistoryItem) - { - try - { - int scheduleHistoryID = SchedulingController.AddScheduleHistory(scheduleHistoryItem); - scheduleHistoryItem.ScheduleHistoryID = scheduleHistoryID; - } - catch (Exception exc) - { - Exceptions.Exceptions.ProcessSchedulerException(exc); - } + foreach (ScheduleItem scheduleItem in scheduleList) + { + if (!KeepRunning) + { + return; + } - return scheduleHistoryItem; - } + int processGroup = GetProcessGroup(); - /// - /// Adds an item to the collection of schedule items in queue. - /// - /// - /// Thread Safe - public static void AddToScheduleQueue(ScheduleHistoryItem scheduleHistoryItem) - { - if (!ScheduleQueueContains(scheduleHistoryItem)) - { - try - { - //objQueueReadWriteLock.EnterWriteLock(WriteTimeout) - using (ScheduleQueue.GetWriteLock(LockTimeout)) + if (scheduleItem.NextStart <= DateTime.Now && + scheduleItem.Enabled && + !IsInProgress(scheduleItem) && + !HasDependenciesConflict(scheduleItem) && + numRun < numToRun) { - //Do a second check just in case - if (!ScheduleQueueContains(scheduleHistoryItem) && - !IsInProgress(scheduleHistoryItem)) + scheduleItem.ProcessGroup = processGroup; + if (scheduleItem.ScheduleSource == ScheduleSource.NOT_SET) { - // It is safe for this thread to read or write - // from the shared resource. - ScheduleQueue.Add(scheduleHistoryItem); + if (SchedulingProvider.SchedulerMode == SchedulerMode.TIMER_METHOD) + { + scheduleItem.ScheduleSource = ScheduleSource.STARTED_FROM_TIMER; + } + else if (SchedulingProvider.SchedulerMode == SchedulerMode.REQUEST_METHOD) + { + scheduleItem.ScheduleSource = ScheduleSource.STARTED_FROM_BEGIN_REQUEST; + } } + + var delegateFunc = new AddToScheduleInProgressDelegate(AddToScheduleInProgress); + var scheduleHistoryItem = new ScheduleHistoryItem(scheduleItem); + scheduleHistoryItem.StartDate = DateTime.Now; + delegateFunc.BeginInvoke(scheduleHistoryItem, null, null); + Thread.Sleep(1000); + + _processGroup[processGroup].AddQueueUserWorkItem(scheduleItem); + + LogEventAddedToProcessGroup(scheduleItem); + numRun += 1; + } + else + { + LogWhyTaskNotRun(scheduleItem); } - } - catch (ApplicationException ex) - { - // The writer lock request timed out. - Interlocked.Increment(ref _writerTimeouts); - Exceptions.Exceptions.LogException(ex); } } } - private delegate void AddToScheduleInProgressDelegate(ScheduleHistoryItem item); - public static void FireEvents() + public static int GetActiveThreadCount() { - //This method uses a thread pool to - //call the SchedulerClient methods that need - //to be called. - - //For each item in the queue that there - //is an open thread for, set the object - //in the array to a new ProcessGroup object. - //Pass in the ScheduleItem to the ProcessGroup - //so the ProcessGroup can pass it around for - //logging and notifications. - lock (ScheduleQueue) - { - var scheduleList = new List(); - using (ScheduleQueue.GetReadLock(LockTimeout)) - { - foreach (ScheduleItem scheduleItem in ScheduleQueue) - { - scheduleList.Add(scheduleItem); - } - } - - int numToRun = scheduleList.Count; - int numRun = 0; - - foreach (ScheduleItem scheduleItem in scheduleList) - { - if (!KeepRunning) - { - return; - } - - int processGroup = GetProcessGroup(); - - if (scheduleItem.NextStart <= DateTime.Now && - scheduleItem.Enabled && - !IsInProgress(scheduleItem) && - !HasDependenciesConflict(scheduleItem) && - numRun < numToRun) - { - scheduleItem.ProcessGroup = processGroup; - if (scheduleItem.ScheduleSource == ScheduleSource.NOT_SET) - { - if (SchedulingProvider.SchedulerMode == SchedulerMode.TIMER_METHOD) - { - scheduleItem.ScheduleSource = ScheduleSource.STARTED_FROM_TIMER; - } - else if (SchedulingProvider.SchedulerMode == SchedulerMode.REQUEST_METHOD) - { - scheduleItem.ScheduleSource = ScheduleSource.STARTED_FROM_BEGIN_REQUEST; - } - } - - var delegateFunc = new AddToScheduleInProgressDelegate(AddToScheduleInProgress); - var scheduleHistoryItem = new ScheduleHistoryItem(scheduleItem); - scheduleHistoryItem.StartDate = DateTime.Now; - delegateFunc.BeginInvoke(scheduleHistoryItem, null, null); - Thread.Sleep(1000); + return _activeThreadCount; + } - _processGroup[processGroup].AddQueueUserWorkItem(scheduleItem); - - LogEventAddedToProcessGroup(scheduleItem); - numRun += 1; - } - else - { - LogWhyTaskNotRun(scheduleItem); - } - } - } + public static int GetFreeThreadCount() + { + return FreeThreads; } private static void LogWhyTaskNotRun(ScheduleItem scheduleItem) @@ -390,34 +404,39 @@ private static void LogWhyTaskNotRun(ScheduleItem scheduleItem) strDebug.Append(" task is scheduled for " + scheduleItem.NextStart); appended = true; } - - + if (!scheduleItem.Enabled) { if (appended) { strDebug.Append(" and"); } + strDebug.Append(" task is not enabled"); appended = true; } + if (IsInProgress(scheduleItem)) { if (appended) { strDebug.Append(" and"); } + strDebug.Append(" task is already in progress"); appended = true; } + if (HasDependenciesConflict(scheduleItem)) { if (appended) { strDebug.Append(" and"); } + strDebug.Append(" task has conflicting dependency"); } + var log = new LogInfo(); log.AddProperty("EVENT NOT RUN REASON", strDebug.ToString()); log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString()); @@ -439,16 +458,6 @@ private static void LogEventAddedToProcessGroup(ScheduleItem scheduleItem) } } - public static int GetActiveThreadCount() - { - return _activeThreadCount; - } - - public static int GetFreeThreadCount() - { - return FreeThreads; - } - public static int GetMaxThreadCount() { return _maxThreadCount; @@ -457,8 +466,8 @@ public static int GetMaxThreadCount() /// /// Gets a copy of the collection of schedule items in progress. /// - /// Copy of the schedule items currently in progress - /// This is a snapshot of the collection scheduled items could start or complete at any time + /// Copy of the schedule items currently in progress. + /// This is a snapshot of the collection scheduled items could start or complete at any time. public static Collection GetScheduleInProgress() { var c = new Collection(); @@ -478,15 +487,16 @@ public static Collection GetScheduleInProgress() Interlocked.Increment(ref _readerTimeouts); Exceptions.Exceptions.LogException(ex); } + return c; } /// /// Gets the number of items in the collection of schedule items in progress. /// - /// Number of items in progress + /// Number of items in progress. /// Thread Safe - /// This count is a snapshot and may change at any time + /// This count is a snapshot and may change at any time. /// public static int GetScheduleInProgressCount() { @@ -501,8 +511,11 @@ public static int GetScheduleInProgressCount() { // The reader lock request timed out. Interlocked.Increment(ref _readerTimeouts); - if (Logger.IsDebugEnabled) - Logger.Debug(ex); + if (Logger.IsDebugEnabled) + { + Logger.Debug(ex); + } + return 0; } } @@ -510,7 +523,7 @@ public static int GetScheduleInProgressCount() /// /// Gets a copy of collection of all schedule items in queue. /// - /// A copy of the ScheduleQueue + /// A copy of the ScheduleQueue. /// Thread Safe /// The returned collection is a snapshot in time the real ScheduleQueue may change at any time. /// @@ -526,6 +539,7 @@ public static Collection GetScheduleQueue() c.Add(item, item.ScheduleID.ToString(), null, null); } } + return c; } catch (ApplicationException ex) @@ -533,15 +547,16 @@ public static Collection GetScheduleQueue() Interlocked.Increment(ref _readerTimeouts); Exceptions.Exceptions.LogException(ex); } + return c; } /// /// Gets the number of items in the collection of schedule items in progress. /// - /// Number of items in progress + /// Number of items in progress. /// Thread Safe - /// This count is a snapshot and may change at any time + /// This count is a snapshot and may change at any time. /// public static int GetScheduleQueueCount() { @@ -568,54 +583,56 @@ public static ScheduleStatus GetScheduleStatus() { try { - //ScheduleStatus is a value type a copy is returned (enumeration) + // ScheduleStatus is a value type a copy is returned (enumeration) return _status; } finally { StatusLock.ExitReadLock(); } - } } catch (ApplicationException) { - //The reader lock request timed out. + // The reader lock request timed out. Interlocked.Increment(ref _readerTimeouts); } + return ScheduleStatus.NOT_SET; } /// - /// Halt the Scheduler + /// Halt the Scheduler. /// - /// Initiator of Halt + /// Initiator of Halt. public static void Halt(string sourceOfHalt) { - //should do nothing if the scheduler havn't start yet. - var currentStatus = GetScheduleStatus(); - if(currentStatus == ScheduleStatus.NOT_SET || currentStatus == ScheduleStatus.STOPPED) - { - return; - } + // should do nothing if the scheduler havn't start yet. + var currentStatus = GetScheduleStatus(); + if (currentStatus == ScheduleStatus.NOT_SET || currentStatus == ScheduleStatus.STOPPED) + { + return; + } + SetScheduleStatus(ScheduleStatus.SHUTTING_DOWN); - var log = new LogInfo {LogTypeKey = "SCHEDULER_SHUTTING_DOWN"}; + var log = new LogInfo { LogTypeKey = "SCHEDULER_SHUTTING_DOWN" }; log.AddProperty("Initiator", sourceOfHalt); LogController.Instance.AddLog(log); KeepRunning = false; - //wait for up to 120 seconds for thread - //to shut down + // wait for up to 120 seconds for thread + // to shut down for (int i = 0; i <= 120; i++) { if (GetScheduleStatus() == ScheduleStatus.STOPPED) { return; } + Thread.Sleep(1000); } - + _activeThreadCount = 0; } @@ -643,8 +660,11 @@ public static bool HasDependenciesConflict(ScheduleItem scheduleItem) { // The reader lock request timed out. Interlocked.Increment(ref _readerTimeouts); - if (Logger.IsDebugEnabled) - Logger.Debug(ex); + if (Logger.IsDebugEnabled) + { + Logger.Debug(ex); + } + return false; } } @@ -653,24 +673,28 @@ public static void LoadQueueFromEvent(EventName eventName) { var executingServer = ServerController.GetExecutingServerName(); List schedule = SchedulingController.GetScheduleByEvent(eventName.ToString(), executingServer); - if (Logger.IsDebugEnabled) - Logger.Debug("loadqueue executingServer:" + executingServer); + if (Logger.IsDebugEnabled) + { + Logger.Debug("loadqueue executingServer:" + executingServer); + } + var thisServer = GetServer(executingServer); if (thisServer == null) { return; } - bool runningInAGroup = !String.IsNullOrEmpty(thisServer.ServerGroup); + bool runningInAGroup = !string.IsNullOrEmpty(thisServer.ServerGroup); var serverGroupServers = ServerGroupServers(thisServer); foreach (ScheduleItem scheduleItem in schedule) { - if (runningInAGroup && String.IsNullOrEmpty(scheduleItem.Servers)) + if (runningInAGroup && string.IsNullOrEmpty(scheduleItem.Servers)) { scheduleItem.Servers = serverGroupServers; } + var historyItem = new ScheduleHistoryItem(scheduleItem); if (!IsInQueue(historyItem) && @@ -689,22 +713,24 @@ public static void LoadQueueFromTimer() _forceReloadSchedule = false; var executingServer = ServerController.GetExecutingServerName(); List schedule = SchedulingController.GetSchedule(executingServer); - if (Logger.IsDebugEnabled) - Logger.Debug("LoadQueueFromTimer executingServer:" + executingServer); + if (Logger.IsDebugEnabled) + { + Logger.Debug("LoadQueueFromTimer executingServer:" + executingServer); + } + var thisServer = GetServer(executingServer); if (thisServer == null) { return; } - bool runningInAGroup = !String.IsNullOrEmpty(thisServer.ServerGroup); - - var serverGroupServers = ServerGroupServers(thisServer); - + bool runningInAGroup = !string.IsNullOrEmpty(thisServer.ServerGroup); + var serverGroupServers = ServerGroupServers(thisServer); + foreach (ScheduleItem scheduleItem in schedule) { - if (runningInAGroup && String.IsNullOrEmpty(scheduleItem.Servers)) + if (runningInAGroup && string.IsNullOrEmpty(scheduleItem.Servers)) { scheduleItem.Servers = serverGroupServers; } @@ -724,18 +750,12 @@ public static void LoadQueueFromTimer() { historyItem.ScheduleSource = ScheduleSource.STARTED_FROM_BEGIN_REQUEST; } + AddToScheduleQueue(historyItem); } } } - private static string ServerGroupServers(ServerInfo thisServer) - { - //Get the servers - var servers = ServerController.GetEnabledServers().Where(s => s.ServerGroup == thisServer.ServerGroup); - return servers.Aggregate(string.Empty, (current, serverInfo) => current + ServerController.GetServerName(serverInfo) + ","); - } - public static void PurgeScheduleHistory() { SchedulingController.PurgeScheduleHistory(); @@ -746,17 +766,24 @@ public static void ReloadSchedule() _forceReloadSchedule = true; } + private static string ServerGroupServers(ServerInfo thisServer) + { + // Get the servers + var servers = ServerController.GetEnabledServers().Where(s => s.ServerGroup == thisServer.ServerGroup); + return servers.Aggregate(string.Empty, (current, serverInfo) => current + ServerController.GetServerName(serverInfo) + ","); + } + /// /// Removes an item from the collection of schedule items in queue. /// - /// Item to remove + /// Item to remove. public static void RemoveFromScheduleQueue(ScheduleItem scheduleItem) { try { using (ScheduleQueue.GetWriteLock(LockTimeout)) { - //the scheduleitem instances may not be equal even though the scheduleids are equal + // the scheduleitem instances may not be equal even though the scheduleids are equal var item = ScheduleQueue.FirstOrDefault(si => si.ScheduleID == scheduleItem.ScheduleID); if (item != null) { @@ -776,36 +803,35 @@ public static void RunEventSchedule(EventName eventName) { try { - var log = new LogInfo {LogTypeKey = "SCHEDULE_FIRED_FROM_EVENT"}; + var log = new LogInfo { LogTypeKey = "SCHEDULE_FIRED_FROM_EVENT" }; log.AddProperty("EVENT", eventName.ToString()); LogController.Instance.AddLog(log); - //We allow for three threads to run simultaneously. - //As long as we have an open thread, continue. + // We allow for three threads to run simultaneously. + // As long as we have an open thread, continue. - //Load the queue to determine which schedule - //items need to be run. + // Load the queue to determine which schedule + // items need to be run. LoadQueueFromEvent(eventName); while (GetScheduleQueueCount() > 0) { SetScheduleStatus(ScheduleStatus.RUNNING_EVENT_SCHEDULE); - //Fire off the events that need running. + // Fire off the events that need running. if (GetScheduleQueueCount() > 0) { FireEvents(); } - - + if (_writerTimeouts > 20 || _readerTimeouts > 20) { - //Wait for 10 minutes so we don't fill up the logs + // Wait for 10 minutes so we don't fill up the logs Thread.Sleep(TimeSpan.FromMinutes(10)); } else { - //Wait for 10 seconds to avoid cpu overutilization + // Wait for 10 seconds to avoid cpu overutilization Thread.Sleep(TimeSpan.FromSeconds(10)); } @@ -825,10 +851,10 @@ public static void SetScheduleStatus(ScheduleStatus newStatus) { try { - //note:locking inside this method is highly misleading - //as there is no lock in place between when the caller - //decides to call this method and when the lock is acquired - //the value could easily change in that time + // note:locking inside this method is highly misleading + // as there is no lock in place between when the caller + // decides to call this method and when the lock is acquired + // the value could easily change in that time if (StatusLock.TryEnterWriteLock(LockTimeout)) { try @@ -840,7 +866,7 @@ public static void SetScheduleStatus(ScheduleStatus newStatus) finally { // Ensure that the lock is released. - StatusLock.ExitWriteLock();; + StatusLock.ExitWriteLock(); } } } @@ -860,8 +886,8 @@ public static void Start() _activeThreadCount = 0; - //This is where the action begins. - //Loop until KeepRunning = false + // This is where the action begins. + // Loop until KeepRunning = false if (SchedulingProvider.SchedulerMode != SchedulerMode.REQUEST_METHOD || _debug) { var log = new LogInfo(); @@ -873,11 +899,13 @@ public static void Start() { try { - if (Common.Globals.ElapsedSinceAppStart.TotalSeconds < SchedulingProvider.DelayAtAppStart) + if (Common.Globals.ElapsedSinceAppStart.TotalSeconds < SchedulingProvider.DelayAtAppStart) { - if (!KeepThreadAlive) - return; - + if (!KeepThreadAlive) + { + return; + } + Thread.Sleep(1000); continue; } @@ -890,27 +918,28 @@ public static void Start() { SetScheduleStatus(ScheduleStatus.RUNNING_REQUEST_SCHEDULE); } - //Load the queue to determine which schedule - //items need to be run. - + + // Load the queue to determine which schedule + // items need to be run. LoadQueueFromTimer(); - //Keep track of when the queue was last refreshed - //so we can perform a refresh periodically + // Keep track of when the queue was last refreshed + // so we can perform a refresh periodically DateTime lastQueueRefresh = DateTime.Now; bool refreshQueueSchedule = false; - //We allow for [MaxThreadCount] threads to run - //simultaneously. As long as we have an open thread - //and we don't have to refresh the queue, continue - //to loop. - //refreshQueueSchedule can get set to true near bottom of loop - //not sure why R# thinks it is always false + // We allow for [MaxThreadCount] threads to run + // simultaneously. As long as we have an open thread + // and we don't have to refresh the queue, continue + // to loop. + // refreshQueueSchedule can get set to true near bottom of loop + // not sure why R# thinks it is always false // ReSharper disable ConditionIsAlwaysTrueOrFalse while (FreeThreads > 0 && !refreshQueueSchedule && KeepRunning && !_forceReloadSchedule) + // ReSharper restore ConditionIsAlwaysTrueOrFalse { - //Fire off the events that need running. + // Fire off the events that need running. if (SchedulingProvider.SchedulerMode == SchedulerMode.TIMER_METHOD) { SetScheduleStatus(ScheduleStatus.RUNNING_TIMER_SCHEDULE); @@ -926,16 +955,16 @@ public static void Start() { FireEvents(); } + if (KeepThreadAlive == false) { return; } - - + if (_writerTimeouts > 20 || _readerTimeouts > 20) { - //Some kind of deadlock on a resource. - //Wait for 10 minutes so we don't fill up the logs + // Some kind of deadlock on a resource. + // Wait for 10 minutes so we don't fill up the logs if (KeepRunning) { Thread.Sleep(TimeSpan.FromMinutes(10)); @@ -947,7 +976,7 @@ public static void Start() } else { - //Wait for 10 seconds to avoid cpu overutilization + // Wait for 10 seconds to avoid cpu overutilization if (KeepRunning) { Thread.Sleep(TimeSpan.FromSeconds(10)); @@ -957,8 +986,8 @@ public static void Start() return; } - //Refresh queue from database every 10 minutes - //if there are no items currently in progress + // Refresh queue from database every 10 minutes + // if there are no items currently in progress if ((lastQueueRefresh.AddMinutes(10) <= DateTime.Now || _forceReloadSchedule) && FreeThreads == _maxThreadCount) { refreshQueueSchedule = true; @@ -967,14 +996,14 @@ public static void Start() } } - //There are no available threads, all threads are being - //used. Wait 10 seconds until one is available + // There are no available threads, all threads are being + // used. Wait 10 seconds until one is available if (KeepRunning) { if (refreshQueueSchedule == false) { SetScheduleStatus(ScheduleStatus.WAITING_FOR_OPEN_THREAD); - Thread.Sleep(10000); //sleep for 10 seconds + Thread.Sleep(10000); // sleep for 10 seconds } } else @@ -985,7 +1014,8 @@ public static void Start() catch (Exception exc) { Exceptions.Exceptions.ProcessSchedulerException(exc); - //sleep for 10 minutes + + // sleep for 10 minutes Thread.Sleep(600000); } } @@ -1000,6 +1030,7 @@ public static void Start() { SetScheduleStatus(ScheduleStatus.WAITING_FOR_REQUEST); } + if (SchedulingProvider.SchedulerMode != SchedulerMode.REQUEST_METHOD || _debug) { var log = new LogInfo { LogTypeKey = "SCHEDULER_STOPPED" }; @@ -1026,15 +1057,15 @@ public static void WorkCompleted(SchedulerClient schedulerClient) { ScheduleHistoryItem scheduleHistoryItem = schedulerClient.ScheduleHistoryItem; - //Remove the object in the ScheduleInProgress collection + // Remove the object in the ScheduleInProgress collection RemoveFromScheduleInProgress(scheduleHistoryItem); - //A SchedulerClient is notifying us that their - //process has completed. Decrease our ActiveThreadCount + // A SchedulerClient is notifying us that their + // process has completed. Decrease our ActiveThreadCount Interlocked.Decrement(ref _activeThreadCount); - //Update the schedule item object property - //to note the end time and next start + // Update the schedule item object property + // to note the end time and next start scheduleHistoryItem.EndDate = DateTime.Now; if (scheduleHistoryItem.ScheduleSource == ScheduleSource.STARTED_FROM_EVENT) @@ -1099,24 +1130,23 @@ public static void WorkCompleted(SchedulerClient schedulerClient) } } - //Update the ScheduleHistory in the database + // Update the ScheduleHistory in the database UpdateScheduleHistory(scheduleHistoryItem); if (scheduleHistoryItem.NextStart != Null.NullDate) { - //Put the object back into the ScheduleQueue - //collection with the new NextStart date. + // Put the object back into the ScheduleQueue + // collection with the new NextStart date. scheduleHistoryItem.StartDate = Null.NullDate; scheduleHistoryItem.EndDate = Null.NullDate; - scheduleHistoryItem.LogNotes = ""; + scheduleHistoryItem.LogNotes = string.Empty; scheduleHistoryItem.ProcessGroup = -1; AddToScheduleQueue(scheduleHistoryItem); } - - + if (schedulerClient.ScheduleHistoryItem.RetainHistoryNum > 0) { - var log = new LogInfo {LogTypeKey = "SCHEDULER_EVENT_COMPLETED"}; + var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_COMPLETED" }; log.AddProperty("TYPE", schedulerClient.GetType().FullName); log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); log.AddProperty("NEXT START", Convert.ToString(scheduleHistoryItem.NextStart)); @@ -1145,18 +1175,17 @@ public static void WorkErrored(ScheduleHistoryItem scheduleHistoryItem, Exceptio { try { - //Remove the object in the ScheduleInProgress collection + // Remove the object in the ScheduleInProgress collection RemoveFromScheduleInProgress(scheduleHistoryItem); - //A SchedulerClient is notifying us that their - //process has errored. Decrease our ActiveThreadCount + // A SchedulerClient is notifying us that their + // process has errored. Decrease our ActiveThreadCount Interlocked.Decrement(ref _activeThreadCount); - - + Exceptions.Exceptions.ProcessSchedulerException(exception); - //Update the schedule item object property - //to note the end time and next start + // Update the schedule item object property + // to note the end time and next start scheduleHistoryItem.EndDate = DateTime.Now; if (scheduleHistoryItem.ScheduleSource == ScheduleSource.STARTED_FROM_EVENT) { @@ -1189,30 +1218,32 @@ public static void WorkErrored(ScheduleHistoryItem scheduleHistoryItem, Exceptio break; } } - //Update the ScheduleHistory in the database + + // Update the ScheduleHistory in the database UpdateScheduleHistory(scheduleHistoryItem); if (scheduleHistoryItem.NextStart != Null.NullDate && scheduleHistoryItem.RetryTimeLapse != Null.NullInteger) { - //Put the object back into the ScheduleQueue - //collection with the new NextStart date. + // Put the object back into the ScheduleQueue + // collection with the new NextStart date. scheduleHistoryItem.StartDate = Null.NullDate; scheduleHistoryItem.EndDate = Null.NullDate; - scheduleHistoryItem.LogNotes = ""; + scheduleHistoryItem.LogNotes = string.Empty; scheduleHistoryItem.ProcessGroup = -1; AddToScheduleQueue(scheduleHistoryItem); } if (scheduleHistoryItem.RetainHistoryNum > 0) { - //Write out the log entry for this event - var log = new LogInfo {LogTypeKey = "SCHEDULER_EVENT_FAILURE"}; + // Write out the log entry for this event + var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_FAILURE" }; log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); log.AddProperty("TYPE", scheduleHistoryItem.TypeFullName); if (exception != null) { log.AddProperty("EXCEPTION", exception.Message); } + log.AddProperty("RESCHEDULED FOR", Convert.ToString(scheduleHistoryItem.NextStart)); log.AddProperty("SOURCE", scheduleHistoryItem.ScheduleSource.ToString()); log.AddProperty("ACTIVE THREADS", _activeThreadCount.ToString()); @@ -1234,12 +1265,12 @@ public static void WorkProgressing(SchedulerClient schedulerClient) { try { - //A SchedulerClient is notifying us that their - //process is in progress. Informational only. + // A SchedulerClient is notifying us that their + // process is in progress. Informational only. if (schedulerClient.ScheduleHistoryItem.RetainHistoryNum > 0) { - //Write out the log entry for this event - var log = new LogInfo {LogTypeKey = "SCHEDULER_EVENT_PROGRESSING"}; + // Write out the log entry for this event + var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_PROGRESSING" }; log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); log.AddProperty("TYPE", schedulerClient.GetType().FullName); log.AddProperty("SOURCE", schedulerClient.ScheduleHistoryItem.ScheduleSource.ToString()); @@ -1270,25 +1301,25 @@ public static void WorkStarted(ScheduleHistoryItem scheduleHistoryItem) { scheduleHistoryItem.ThreadID = Thread.CurrentThread.GetHashCode(); - //Put the object in the ScheduleInProgress collection - //and remove it from the ScheduleQueue + // Put the object in the ScheduleInProgress collection + // and remove it from the ScheduleQueue RemoveFromScheduleQueue(scheduleHistoryItem); AddToScheduleInProgress(scheduleHistoryItem); - //A SchedulerClient is notifying us that their - //process has started. Increase our ActiveThreadCount + // A SchedulerClient is notifying us that their + // process has started. Increase our ActiveThreadCount Interlocked.Increment(ref _activeThreadCount); activeThreadCountIncremented = true; - //Update the schedule item - //object property to note the start time. + // Update the schedule item + // object property to note the start time. scheduleHistoryItem.StartDate = DateTime.Now; AddScheduleHistory(scheduleHistoryItem); - + if (scheduleHistoryItem.RetainHistoryNum > 0) { - //Write out the log entry for this event - var log = new LogInfo {LogTypeKey = "SCHEDULER_EVENT_STARTED"}; + // Write out the log entry for this event + var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_STARTED" }; log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); log.AddProperty("TYPE", scheduleHistoryItem.TypeFullName); log.AddProperty("SOURCE", scheduleHistoryItem.ScheduleSource.ToString()); @@ -1303,61 +1334,40 @@ public static void WorkStarted(ScheduleHistoryItem scheduleHistoryItem) } catch (Exception exc) { - //Decrement the ActiveThreadCount because - //otherwise the number of active threads - //will appear to be climbing when in fact - //no tasks are being executed. + // Decrement the ActiveThreadCount because + // otherwise the number of active threads + // will appear to be climbing when in fact + // no tasks are being executed. if (activeThreadCountIncremented) { Interlocked.Decrement(ref _activeThreadCount); } + Exceptions.Exceptions.ProcessSchedulerException(exc); } } - internal static void InitializeThreadPool(bool boolDebug, int maxThreads) - { - _debug = boolDebug; - lock (typeof (CoreScheduler)) - { - if (!_threadPoolInitialized) - { - _threadPoolInitialized = true; - if (maxThreads == -1) - { - maxThreads = 1; - } - _numberOfProcessGroups = maxThreads; - _maxThreadCount = maxThreads; - for (int i = 0; i < _numberOfProcessGroups; i++) - { - Array.Resize(ref _processGroup, i + 1); - _processGroup[i] = new ProcessGroup(); - } - } - } - } - - //DNN-5001 + // DNN-5001 public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHistoryItem runningscheduleHistoryItem) { try { - //attempt to stop task only if it is still in progress + // attempt to stop task only if it is still in progress if (GetScheduleItemFromScheduleInProgress(scheduleItem) != null) { var scheduleHistoryItem = GetScheduleItemFromScheduleInProgress(scheduleItem); scheduleHistoryItem.ScheduleHistoryID = runningscheduleHistoryItem.ScheduleHistoryID; scheduleHistoryItem.StartDate = runningscheduleHistoryItem.StartDate; - //Remove the object in the ScheduleInProgress collection + + // Remove the object in the ScheduleInProgress collection RemoveFromScheduleInProgress(scheduleHistoryItem); - //A SchedulerClient is notifying us that their - //process has completed. Decrease our ActiveThreadCount + // A SchedulerClient is notifying us that their + // process has completed. Decrease our ActiveThreadCount Interlocked.Decrement(ref _activeThreadCount); - //Update the schedule item object property - //to note the end time and next start + // Update the schedule item object property + // to note the end time and next start scheduleHistoryItem.EndDate = DateTime.Now; if (scheduleHistoryItem.ScheduleSource == ScheduleSource.STARTED_FROM_EVENT) @@ -1388,7 +1398,7 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis break; case "w": scheduleHistoryItem.NextStart = - scheduleHistoryItem.StartDate.AddDays(scheduleHistoryItem.TimeLapse*7); + scheduleHistoryItem.StartDate.AddDays(scheduleHistoryItem.TimeLapse * 7); break; case "mo": scheduleHistoryItem.NextStart = @@ -1422,7 +1432,7 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis break; case "w": scheduleHistoryItem.NextStart = - scheduleHistoryItem.StartDate.AddDays(scheduleHistoryItem.TimeLapse*7); + scheduleHistoryItem.StartDate.AddDays(scheduleHistoryItem.TimeLapse * 7); break; case "mo": scheduleHistoryItem.NextStart = @@ -1435,36 +1445,59 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis } } } - //Update the ScheduleHistory in the database + + // Update the ScheduleHistory in the database UpdateScheduleHistory(scheduleHistoryItem); - - + if (scheduleHistoryItem.NextStart != Null.NullDate) { - //Put the object back into the ScheduleQueue - //collection with the new NextStart date. + // Put the object back into the ScheduleQueue + // collection with the new NextStart date. scheduleHistoryItem.StartDate = Null.NullDate; scheduleHistoryItem.EndDate = Null.NullDate; - scheduleHistoryItem.LogNotes = ""; + scheduleHistoryItem.LogNotes = string.Empty; scheduleHistoryItem.ProcessGroup = -1; AddToScheduleQueue(scheduleHistoryItem); } - //Write out the log entry for this event - var log = new LogInfo {LogTypeKey = "SCHEDULER_EVENT_COMPLETED"}; + // Write out the log entry for this event + var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_COMPLETED" }; log.AddProperty("REASON", "Scheduler task has been stopped manually"); log.AddProperty("TYPE", scheduleHistoryItem.TypeFullName); log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); log.AddProperty("NEXT START", Convert.ToString(scheduleHistoryItem.NextStart)); LogController.Instance.AddLog(log); } - } catch (Exception exc) { Exceptions.Exceptions.ProcessSchedulerException(exc); } } + + internal static void InitializeThreadPool(bool boolDebug, int maxThreads) + { + _debug = boolDebug; + lock (typeof(CoreScheduler)) + { + if (!_threadPoolInitialized) + { + _threadPoolInitialized = true; + if (maxThreads == -1) + { + maxThreads = 1; + } + + _numberOfProcessGroups = maxThreads; + _maxThreadCount = maxThreads; + for (int i = 0; i < _numberOfProcessGroups; i++) + { + Array.Resize(ref _processGroup, i + 1); + _processGroup[i] = new ProcessGroup(); + } + } + } + } } } } diff --git a/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs b/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs index 696665c5a61..e8fc213f58c 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs @@ -1,32 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Threading; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { - /// - /// This class is inherited by any class that wants to run tasks in the scheduler. - /// + using System; + using System.Threading; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + + /// + /// This class is inherited by any class that wants to run tasks in the scheduler. + /// public abstract class SchedulerClient { public SchedulerClient() { - SchedulerEventGUID = Null.NullString; - aProcessMethod = Null.NullString; - Status = Null.NullString; - ScheduleHistoryItem = new ScheduleHistoryItem(); + this.SchedulerEventGUID = Null.NullString; + this.aProcessMethod = Null.NullString; + this.Status = Null.NullString; + this.ScheduleHistoryItem = new ScheduleHistoryItem(); } + public event WorkStarted ProcessStarted; + + public event WorkProgressing ProcessProgressing; + + public event WorkCompleted ProcessCompleted; + public ScheduleHistoryItem ScheduleHistoryItem { get; set; } public string SchedulerEventGUID { get; set; } @@ -42,50 +43,47 @@ public int ThreadID return Thread.CurrentThread.ManagedThreadId; } } - - public event WorkStarted ProcessStarted; - public event WorkProgressing ProcessProgressing; - public event WorkCompleted ProcessCompleted; + public event WorkErrored ProcessErrored; public void Started() { - if (ProcessStarted != null) + if (this.ProcessStarted != null) { - ProcessStarted(this); + this.ProcessStarted(this); } } public void Progressing() { - if (ProcessProgressing != null) + if (this.ProcessProgressing != null) { - ProcessProgressing(this); + this.ProcessProgressing(this); } } public void Completed() { - if (ProcessCompleted != null) + if (this.ProcessCompleted != null) { - ProcessCompleted(this); + this.ProcessCompleted(this); } } public void Errored(ref Exception objException) { - if (ProcessErrored != null) + if (this.ProcessErrored != null) { - ProcessErrored(this, objException); + this.ProcessErrored(this, objException); } } /// ''''''''''''''''''''''''''''''''''''''''''''''''''' - /// + /// /// This is the sub that kicks off the actual - /// work within the SchedulerClient's subclass - /// - /// ''''''''''''''''''''''''''''''''''''''''''''''''''' - public abstract void DoWork(); + /// work within the SchedulerClient's subclass. + /// + /// ''''''''''''''''''''''''''''''''''''''''''''''''''' + public abstract void DoWork(); } } diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs index 536df0ea62a..48285323b48 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs @@ -1,66 +1,64 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Log.EventLog; - -using Microsoft.VisualBasic; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Log.EventLog; + using Microsoft.VisualBasic; + + using Globals = DotNetNuke.Common.Globals; + public class SchedulingController { [Obsolete("Obsoleted in 7.3.0 - use alternate overload. Scheduled removal in v10.0.0.")] public static int AddSchedule(string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName) { - return AddSchedule(TypeFullName, - TimeLapse, - TimeLapseMeasurement, - RetryTimeLapse, - RetryTimeLapseMeasurement, - RetainHistoryNum, - AttachToEvent, - CatchUpEnabled, - Enabled, - ObjectDependencies, - Servers, - FriendlyName, - DateTime.Now); + return AddSchedule( + TypeFullName, + TimeLapse, + TimeLapseMeasurement, + RetryTimeLapse, + RetryTimeLapseMeasurement, + RetainHistoryNum, + AttachToEvent, + CatchUpEnabled, + Enabled, + ObjectDependencies, + Servers, + FriendlyName, + DateTime.Now); } + public static int AddSchedule(string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName, DateTime ScheduleStartDate) { EventLogController.Instance.AddLog("TypeFullName", TypeFullName, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.SCHEDULE_CREATED); - return DataProvider.Instance().AddSchedule(TypeFullName, - TimeLapse, - TimeLapseMeasurement, - RetryTimeLapse, - RetryTimeLapseMeasurement, - RetainHistoryNum, - AttachToEvent, - CatchUpEnabled, - Enabled, - ObjectDependencies, - Servers, - UserController.Instance.GetCurrentUserInfo().UserID, - FriendlyName, - ScheduleStartDate); + return DataProvider.Instance().AddSchedule( + TypeFullName, + TimeLapse, + TimeLapseMeasurement, + RetryTimeLapse, + RetryTimeLapseMeasurement, + RetainHistoryNum, + AttachToEvent, + CatchUpEnabled, + Enabled, + ObjectDependencies, + Servers, + UserController.Instance.GetCurrentUserInfo().UserID, + FriendlyName, + ScheduleStartDate); } public static int AddScheduleHistory(ScheduleHistoryItem objScheduleHistoryItem) @@ -76,11 +74,12 @@ public static void AddScheduleItemSetting(int ScheduleID, string Name, string Va public static void DeleteSchedule(int ScheduleID) { DataProvider.Instance().DeleteSchedule(ScheduleID); - EventLogController.Instance.AddLog("ScheduleID", - ScheduleID.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.SCHEDULE_DELETED); + EventLogController.Instance.AddLog( + "ScheduleID", + ScheduleID.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.SCHEDULE_DELETED); } public static int GetActiveThreadCount() @@ -136,13 +135,14 @@ public static List GetScheduleHistory(int ScheduleID) public static Hashtable GetScheduleItemSettings(int ScheduleID) { var h = new Hashtable(); - using(var r = DataProvider.Instance().GetScheduleItemSettings(ScheduleID)) + using (var r = DataProvider.Instance().GetScheduleItemSettings(ScheduleID)) { while (r.Read()) { h.Add(r["SettingName"], r["SettingValue"]); } } + return h; } @@ -171,92 +171,96 @@ public static void ReloadSchedule() Scheduler.CoreScheduler.ReloadSchedule(); } - public static void UpdateSchedule(ScheduleItem scheduleItem) - { + public static void UpdateSchedule(ScheduleItem scheduleItem) + { #pragma warning disable 618 - UpdateSchedule(scheduleItem.ScheduleID, - scheduleItem.TypeFullName, - scheduleItem.TimeLapse, - scheduleItem.TimeLapseMeasurement, - scheduleItem.RetryTimeLapse, - scheduleItem.RetryTimeLapseMeasurement, - scheduleItem.RetainHistoryNum, - scheduleItem.AttachToEvent, - scheduleItem.CatchUpEnabled, - scheduleItem.Enabled, - scheduleItem.ObjectDependencies, - scheduleItem.Servers, - scheduleItem.FriendlyName, - scheduleItem.ScheduleStartDate); + UpdateSchedule( + scheduleItem.ScheduleID, + scheduleItem.TypeFullName, + scheduleItem.TimeLapse, + scheduleItem.TimeLapseMeasurement, + scheduleItem.RetryTimeLapse, + scheduleItem.RetryTimeLapseMeasurement, + scheduleItem.RetainHistoryNum, + scheduleItem.AttachToEvent, + scheduleItem.CatchUpEnabled, + scheduleItem.Enabled, + scheduleItem.ObjectDependencies, + scheduleItem.Servers, + scheduleItem.FriendlyName, + scheduleItem.ScheduleStartDate); #pragma warning restore 618 - } + } public static void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName) { #pragma warning disable 618 - UpdateSchedule(ScheduleID, - TypeFullName, - TimeLapse, - TimeLapseMeasurement, - RetryTimeLapse, - RetryTimeLapseMeasurement, - RetainHistoryNum, - AttachToEvent, - CatchUpEnabled, - Enabled, - ObjectDependencies, - Servers, - FriendlyName, - DateTime.Now); + UpdateSchedule( + ScheduleID, + TypeFullName, + TimeLapse, + TimeLapseMeasurement, + RetryTimeLapse, + RetryTimeLapseMeasurement, + RetainHistoryNum, + AttachToEvent, + CatchUpEnabled, + Enabled, + ObjectDependencies, + Servers, + FriendlyName, + DateTime.Now); #pragma warning restore 618 - } + } [Obsolete("Obsoleted in 7.3.0 - use alternate overload. Scheduled removal in v10.0.0.")] public static void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName, DateTime ScheduleStartDate) { - DataProvider.Instance().UpdateSchedule(ScheduleID, - TypeFullName, - TimeLapse, - TimeLapseMeasurement, - RetryTimeLapse, - RetryTimeLapseMeasurement, - RetainHistoryNum, - AttachToEvent, - CatchUpEnabled, - Enabled, - ObjectDependencies, - Servers, - UserController.Instance.GetCurrentUserInfo().UserID, - FriendlyName, - ScheduleStartDate); + DataProvider.Instance().UpdateSchedule( + ScheduleID, + TypeFullName, + TimeLapse, + TimeLapseMeasurement, + RetryTimeLapse, + RetryTimeLapseMeasurement, + RetainHistoryNum, + AttachToEvent, + CatchUpEnabled, + Enabled, + ObjectDependencies, + Servers, + UserController.Instance.GetCurrentUserInfo().UserID, + FriendlyName, + ScheduleStartDate); EventLogController.Instance.AddLog("TypeFullName", TypeFullName, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.SCHEDULE_UPDATED); } public static void UpdateScheduleHistory(ScheduleHistoryItem objScheduleHistoryItem) { - DataProvider.Instance().UpdateScheduleHistory(objScheduleHistoryItem.ScheduleHistoryID, - objScheduleHistoryItem.EndDate, - objScheduleHistoryItem.Succeeded, - objScheduleHistoryItem.LogNotes, - objScheduleHistoryItem.NextStart); + DataProvider.Instance().UpdateScheduleHistory( + objScheduleHistoryItem.ScheduleHistoryID, + objScheduleHistoryItem.EndDate, + objScheduleHistoryItem.Succeeded, + objScheduleHistoryItem.LogNotes, + objScheduleHistoryItem.NextStart); } public static bool CanRunOnThisServer(string servers) { - string lwrServers = ""; + string lwrServers = string.Empty; if (servers != null) { lwrServers = servers.ToLowerInvariant(); } - if (String.IsNullOrEmpty(lwrServers) || lwrServers.Contains(Globals.ServerName.ToLowerInvariant())) + + if (string.IsNullOrEmpty(lwrServers) || lwrServers.Contains(Globals.ServerName.ToLowerInvariant())) { return true; } return false; } - } } diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs index 726e0f67c12..b0fd2d1cc2a 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs @@ -1,29 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using Microsoft.VisualBasic; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Scheduling { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using Microsoft.VisualBasic; + + using Globals = DotNetNuke.Common.Globals; + + // ReSharper restore InconsistentNaming + + // set up our delegates so we can track and react to events of the scheduler clients + public delegate void WorkStarted(SchedulerClient objSchedulerClient); + + public delegate void WorkProgressing(SchedulerClient objSchedulerClient); + + public delegate void WorkCompleted(SchedulerClient objSchedulerClient); + // ReSharper disable InconsistentNaming public enum EventName { - //do not add APPLICATION_END - //it will not reliably complete - APPLICATION_START + // do not add APPLICATION_END + // it will not reliably complete + APPLICATION_START, } public enum ScheduleSource @@ -32,7 +38,7 @@ public enum ScheduleSource STARTED_FROM_SCHEDULE_CHANGE, STARTED_FROM_EVENT, STARTED_FROM_TIMER, - STARTED_FROM_BEGIN_REQUEST + STARTED_FROM_BEGIN_REQUEST, } public enum ScheduleStatus @@ -44,23 +50,15 @@ public enum ScheduleStatus RUNNING_REQUEST_SCHEDULE, WAITING_FOR_REQUEST, SHUTTING_DOWN, - STOPPED + STOPPED, } public enum SchedulerMode { DISABLED = 0, TIMER_METHOD = 1, - REQUEST_METHOD = 2 + REQUEST_METHOD = 2, } - // ReSharper restore InconsistentNaming - - //set up our delegates so we can track and react to events of the scheduler clients - public delegate void WorkStarted(SchedulerClient objSchedulerClient); - - public delegate void WorkProgressing(SchedulerClient objSchedulerClient); - - public delegate void WorkCompleted(SchedulerClient objSchedulerClient); public delegate void WorkErrored(SchedulerClient objSchedulerClient, Exception objException); @@ -70,14 +68,14 @@ public abstract class SchedulingProvider protected SchedulingProvider() { - var settings = Settings; + var settings = this.Settings; if (settings != null) { - ProviderPath = settings["providerPath"]; + this.ProviderPath = settings["providerPath"]; string str; bool dbg; - + if (settings.TryGetValue("debug", out str) && bool.TryParse(str, out dbg)) { Debug = dbg; @@ -88,15 +86,16 @@ protected SchedulingProvider() { value = 1; } + MaxThreads = value; - //if (!settings.TryGetValue("delayAtAppStart", out str) || !int.TryParse(str, out value)) - //{ + // if (!settings.TryGetValue("delayAtAppStart", out str) || !int.TryParse(str, out value)) + // { // value = 60; - //} + // } if (DotNetNuke.Common.Globals.Status != Globals.UpgradeStatus.Install) { - DelayAtAppStart = HostController.Instance.GetInteger("SchedulerdelayAtAppStart", 1)*60; + DelayAtAppStart = HostController.Instance.GetInteger("SchedulerdelayAtAppStart", 1) * 60; } else { @@ -118,7 +117,7 @@ protected SchedulingProvider() } /// - /// The number of seconds since application start where no timer-initiated + /// Gets the number of seconds since application start where no timer-initiated /// schedulers are allowed to run before. This safeguards against ovelapped /// application re-starts. See "Disable Ovelapped Recycling" under Recycling /// of IIS Manager Application Pool's Advanced Settings. @@ -137,8 +136,6 @@ public static bool Enabled public static int MaxThreads { get; private set; } - public string ProviderPath { get; private set; } - public static bool ReadyForPoll { get @@ -154,6 +151,7 @@ public static DateTime ScheduleLastPolled return DataCache.GetCache("ScheduleLastPolled") != null ? (DateTime)DataCache.GetCache("ScheduleLastPolled") : DateTime.MinValue; } + set { var nextScheduledTask = Instance().GetNextScheduledTask(ServerController.GetExecutingServerName()); @@ -163,6 +161,8 @@ public static DateTime ScheduleLastPolled } } + public string ProviderPath { get; private set; } + public static SchedulerMode SchedulerMode { get @@ -183,8 +183,7 @@ public static SchedulingProvider Instance() { return ComponentFactory.GetComponent(); } - - + public abstract void Start(); public abstract void ExecuteTasks(); @@ -231,19 +230,20 @@ public static SchedulingProvider Instance() public abstract void UpdateSchedule(ScheduleItem scheduleItem); - public abstract void UpdateScheduleWithoutExecution (ScheduleItem scheduleItem); + public abstract void UpdateScheduleWithoutExecution(ScheduleItem scheduleItem); public abstract void DeleteSchedule(ScheduleItem scheduleItem); public virtual void RunScheduleItemNow(ScheduleItem scheduleItem) { - //Do Nothing + // Do Nothing } + public virtual void RunScheduleItemNow(ScheduleItem scheduleItem, bool runNow) { - //Do Nothing + // Do Nothing } + public abstract void RemoveFromScheduleInProgress(ScheduleItem scheduleItem); - } } diff --git a/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs b/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs index 16aa14fb6b3..b7da74f764d 100644 --- a/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs @@ -1,46 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Entities; + /// - /// BaseResult to be implemented by the different Crawlers to provide Permission and Url Services + /// BaseResult to be implemented by the different Crawlers to provide Permission and Url Services. /// /// The abstract methods in this Class will be called by Search Result engine for every Hit found in Search Index. [Serializable] public abstract class BaseResultController - { - #region Abstract - + { /// - /// Does the user in the Context have View Permission on the Document + /// Gets the localized search type name. /// - /// Search Result - /// True or False + public virtual string LocalizedSearchTypeName => string.Empty; + + /// + /// Does the user in the Context have View Permission on the Document. + /// + /// Search Result. + /// True or False. public abstract bool HasViewPermission(SearchResult searchResult); /// /// Return a Url that can be shown in search results. /// - /// Search Result - /// Url - /// The Query Strings in the Document (if present) should be appended while returning the Url + /// Search Result. + /// Url. + /// The Query Strings in the Document (if present) should be appended while returning the Url. public abstract string GetDocUrl(SearchResult searchResult); - - /// - /// Gets the localized search type name. - /// - public virtual string LocalizedSearchTypeName => ""; - - #endregion } } diff --git a/DNN Platform/Library/Services/Search/Controllers/IModuleSearchResultController.cs b/DNN Platform/Library/Services/Search/Controllers/IModuleSearchResultController.cs index dfff62e7a83..02600c80c96 100644 --- a/DNN Platform/Library/Services/Search/Controllers/IModuleSearchResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/IModuleSearchResultController.cs @@ -1,34 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using DotNetNuke.Services.Search.Entities; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Services.Search.Entities; + /// - /// Module can optionally specify custom behavior to provide Permission and Url Services. + /// Module can optionally specify custom behavior to provide Permission and Url Services. /// /// This is needed only when Module wants additional capabilities on top of what Core already performs. public interface IModuleSearchResultController { /// - /// Does the user in the Context have View Permission on the Document + /// Does the user in the Context have View Permission on the Document. /// - /// Search Result - /// True or False + /// Search Result. + /// True or False. bool HasViewPermission(SearchResult searchResult); /// /// Return a Url that can be shown in search results. /// - /// Search Result - /// Url - /// The Query Strings in the Document (if present) should be appended while returning the Url + /// Search Result. + /// Url. + /// The Query Strings in the Document (if present) should be appended while returning the Url. string GetDocUrl(SearchResult searchResult); } } diff --git a/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs b/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs index 5df8080ba1b..e4be421b391 100644 --- a/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs @@ -1,36 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { + using System; + + using DotNetNuke.Services.Search.Entities; + public interface ISearchController - { - #region Core Search APIs - + { /// - /// Get Search Result for the searchQuery at the Site Level + /// Get Search Result for the searchQuery at the Site Level. /// - /// SearchQuery object with various search criteria - /// SearchResults + /// SearchQuery object with various search criteria. + /// SearchResults. SearchResults SiteSearch(SearchQuery searchQuery); /// - /// Get Search Result for the searchQuery at the Module Level + /// Get Search Result for the searchQuery at the Module Level. /// - /// SearchQuery object with various search criteria - /// SearchResults - /// SearchTypeIds provided in the searchQuery will be ignored - SearchResults ModuleSearch(SearchQuery searchQuery); - - #endregion + /// SearchQuery object with various search criteria. + /// SearchResults. + /// SearchTypeIds provided in the searchQuery will be ignored. + SearchResults ModuleSearch(SearchQuery searchQuery); } } diff --git a/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs b/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs index 01082a8deb0..acf8cc316f9 100644 --- a/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs @@ -1,53 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Web.Caching; - -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Web.Caching; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Search.Entities; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// - /// Search Result Controller for Module Crawler + /// Search Result Controller for Module Crawler. /// /// [Serializable] public class ModuleResultController : BaseResultController { + private const string ModuleByIdCacheKey = "ModuleById{0}"; + private const CacheItemPriority ModuleByIdCachePriority = CacheItemPriority.Normal; + private const int ModuleByIdCacheTimeOut = 20; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleResultController)); private static Hashtable _moduleSearchControllers = new Hashtable(); private static object _threadLock = new object(); - #region Abstract Class Implmentation - public override bool HasViewPermission(SearchResult searchResult) { var viewable = false; if (searchResult.ModuleId > 0) { - //Get All related tabIds from moduleId (while minimizing DB access; using caching) + // Get All related tabIds from moduleId (while minimizing DB access; using caching) var moduleId = searchResult.ModuleId; + // The next call has over 30% performance enhancement over the above one var tabModules = TabController.Instance.GetTabsByPortal(searchResult.PortalId).Values .SelectMany(tabinfo => tabinfo.ChildModules.Where(kv => kv.Key == moduleId)).Select(m => m.Value); @@ -55,24 +55,25 @@ public override bool HasViewPermission(SearchResult searchResult) foreach (ModuleInfo module in tabModules) { var tab = TabController.Instance.GetTab(module.TabID, searchResult.PortalId, false); - if (ModuleIsAvailable(tab, module) && !tab.IsDeleted && !tab.DisableLink && TabPermissionController.CanViewPage(tab)) + if (this.ModuleIsAvailable(tab, module) && !tab.IsDeleted && !tab.DisableLink && TabPermissionController.CanViewPage(tab)) { - //Check If authorised to View Module - if (ModulePermissionController.CanViewModule(module) && HasModuleSearchPermission(module, searchResult)) + // Check If authorised to View Module + if (ModulePermissionController.CanViewModule(module) && this.HasModuleSearchPermission(module, searchResult)) { - //Verify against search document permissions + // Verify against search document permissions if (string.IsNullOrEmpty(searchResult.Permissions) || PortalSecurity.IsInRoles(searchResult.Permissions)) { viewable = true; if (string.IsNullOrEmpty(searchResult.Url)) { - searchResult.Url = GetModuleSearchUrl(module, searchResult); + searchResult.Url = this.GetModuleSearchUrl(module, searchResult); if (string.IsNullOrEmpty(searchResult.Url)) { searchResult.Url = TestableGlobals.Instance.NavigateURL(module.TabID, string.Empty, searchResult.QueryString); } } + break; } } @@ -91,10 +92,13 @@ public override bool HasViewPermission(SearchResult searchResult) public override string GetDocUrl(SearchResult searchResult) { if (!string.IsNullOrEmpty(searchResult.Url)) + { return searchResult.Url; + } + + var url = Localization.GetString("SEARCH_NoLink"); - var url = Localization.Localization.GetString("SEARCH_NoLink"); - //Get All related tabIds from moduleId + // Get All related tabIds from moduleId var tabModules = GetModuleTabs(searchResult.ModuleId); foreach (ModuleInfo module in tabModules) @@ -104,7 +108,7 @@ public override string GetDocUrl(SearchResult searchResult) { try { - url = GetModuleSearchUrl(module, searchResult); + url = this.GetModuleSearchUrl(module, searchResult); if (string.IsNullOrEmpty(url)) { @@ -127,10 +131,6 @@ public override string GetDocUrl(SearchResult searchResult) return url; } - private const string ModuleByIdCacheKey = "ModuleById{0}"; - private const CacheItemPriority ModuleByIdCachePriority = CacheItemPriority.Normal; - private const int ModuleByIdCacheTimeOut = 20; - private static ArrayList GetModuleTabs(int moduleID) { // no manual clearing of the cache exists; let is just expire @@ -144,7 +144,7 @@ private bool HasModuleSearchPermission(ModuleInfo module, SearchResult searchRes { var canView = true; - var moduleSearchController = GetModuleSearchController(module); + var moduleSearchController = this.GetModuleSearchController(module); if (moduleSearchController != null) { canView = moduleSearchController.HasViewPermission(searchResult); @@ -152,11 +152,11 @@ private bool HasModuleSearchPermission(ModuleInfo module, SearchResult searchRes return canView; } - + private string GetModuleSearchUrl(ModuleInfo module, SearchResult searchResult) { var url = string.Empty; - var moduleSearchController = GetModuleSearchController(module); + var moduleSearchController = this.GetModuleSearchController(module); if (moduleSearchController != null) { url = moduleSearchController.GetDocUrl(searchResult); @@ -189,7 +189,7 @@ private IModuleSearchResultController GetModuleSearchController(ModuleInfo modul private bool ModuleIsAvailable(TabInfo tab, ModuleInfo module) { - return GetModules(tab).Any(m => m.ModuleID == module.ModuleID && !m.IsDeleted); + return this.GetModules(tab).Any(m => m.ModuleID == module.ModuleID && !m.IsDeleted); } private IEnumerable GetModules(TabInfo tab) @@ -202,7 +202,5 @@ private IEnumerable GetModules(TabInfo tab) return TabVersionBuilder.Instance.GetCurrentModules(tab.TabID); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Search/Controllers/SearchController.cs b/DNN Platform/Library/Services/Search/Controllers/SearchController.cs index 34c73215639..3b116fec597 100644 --- a/DNN Platform/Library/Services/Search/Controllers/SearchController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/SearchController.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { - /// - /// Business Layer to manage Search. - /// + using System; + + using DotNetNuke.Framework; + + /// + /// Business Layer to manage Search. + /// public class SearchController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs index 73d09d994f8..3ac5f12c07d 100644 --- a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs @@ -1,87 +1,238 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Web.Caching; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -using Lucene.Net.Documents; -using Lucene.Net.Index; -using Lucene.Net.QueryParsers; -using Lucene.Net.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using Lucene.Net.Documents; + using Lucene.Net.Index; + using Lucene.Net.QueryParsers; + using Lucene.Net.Search; + /// ----------------------------------------------------------------------------- /// - /// The Impl Controller class for Search + /// The Impl Controller class for Search. /// /// ----------------------------------------------------------------------------- internal class SearchControllerImpl : ISearchController - { - #region Private Properties - + { private const string SeacrchContollersCacheKey = "SearchControllers"; - - private readonly int _moduleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - - #endregion - - #region Core Search APIs + private readonly int _moduleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; + public SearchResults SiteSearch(SearchQuery searchQuery) { - var results = GetResults(searchQuery); - return new SearchResults{TotalHits = results.Item1, Results = results.Item2}; + var results = this.GetResults(searchQuery); + return new SearchResults { TotalHits = results.Item1, Results = results.Item2 }; } public SearchResults ModuleSearch(SearchQuery searchQuery) { - searchQuery.SearchTypeIds = new List { _moduleSearchTypeId }; - var results = GetResults(searchQuery); + searchQuery.SearchTypeIds = new List { this._moduleSearchTypeId }; + var results = this.GetResults(searchQuery); return new SearchResults { TotalHits = results.Item1, Results = results.Item2 }; - } + } - #endregion + private static void FillTagsValues(Document doc, SearchResult result) + { + foreach (var field in doc.GetFields()) + { + if (field.StringValue == null) + { + continue; + } + + int intField; + switch (field.Name) + { + case Constants.UniqueKeyTag: + result.UniqueKey = field.StringValue; + break; + case Constants.TitleTag: + var title = field.StringValue; + result.Title = title; + break; + case Constants.BodyTag: + result.Body = field.StringValue; + break; + case Constants.DescriptionTag: + result.Description = field.StringValue; + break; + case Constants.Tag: + result.Tags = result.Tags.Concat(new[] { field.StringValue }); + break; + case Constants.PermissionsTag: + result.Permissions = field.StringValue; + break; + case Constants.QueryStringTag: + result.QueryString = field.StringValue; + break; + case Constants.UrlTag: + result.Url = field.StringValue; + break; + case Constants.SearchTypeTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.SearchTypeId = intField; + } + + break; + case Constants.ModuleIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.ModuleId = intField; + } + + break; + case Constants.ModuleDefIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.ModuleDefId = intField; + } + + break; + case Constants.PortalIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.PortalId = intField; + } + + break; + case Constants.AuthorIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.AuthorUserId = intField; + } + + break; + case Constants.RoleIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.RoleId = intField; + } + + break; + case Constants.AuthorNameTag: + result.AuthorName = field.StringValue; + break; + case Constants.TabIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.TabId = intField; + } + + break; + case Constants.ModifiedTimeTag: + DateTime modifiedTimeUtc; + DateTime.TryParseExact(field.StringValue, Constants.DateTimeFormat, null, DateTimeStyles.None, out modifiedTimeUtc); + result.ModifiedTimeUtc = modifiedTimeUtc; + break; + default: + if (field.Name.StartsWith(Constants.NumericKeyPrefixTag)) + { + var key = field.Name.Substring(Constants.NumericKeyPrefixTag.Length); + if (int.TryParse(field.StringValue, out intField)) + { + if (!result.NumericKeys.ContainsKey(key)) + { + result.NumericKeys.Add(key, intField); + } + } + } + else if (field.Name.StartsWith(Constants.KeywordsPrefixTag)) + { + var key = field.Name.Substring(Constants.KeywordsPrefixTag.Length); + if (!result.Keywords.ContainsKey(key)) + { + result.Keywords.Add(key, field.StringValue); + } + } + + break; + } + } + } - #region Private Methods + private static string GetSnippet(SearchResult searchResult, LuceneResult luceneResult) + { + var sb = new StringBuilder(); + if (!string.IsNullOrEmpty(luceneResult.TitleSnippet)) + { + sb.Append(luceneResult.TitleSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.DescriptionSnippet)) + { + sb.Append(luceneResult.DescriptionSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.TagSnippet)) + { + sb.Append(luceneResult.TagSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.BodySnippet)) + { + sb.Append(luceneResult.BodySnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.AuthorSnippet)) + { + sb.Append(luceneResult.AuthorSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.ContentSnippet)) + { + sb.Append(luceneResult.ContentSnippet + "..."); + } + + var snippet = sb.ToString(); + if (string.IsNullOrEmpty(snippet)) + { + snippet = searchResult.Title; + } + + return snippet; + } + private Tuple> GetResults(SearchQuery searchQuery) { Requires.NotNull("Query", searchQuery); Requires.PropertyNotEqualTo("searchQuery", "SearchTypeIds", searchQuery.SearchTypeIds.Count(), 0); - if((searchQuery.ModuleId > 0) && (searchQuery.SearchTypeIds.Count() > 1 || !searchQuery.SearchTypeIds.Contains(_moduleSearchTypeId))) - throw new ArgumentException(Localization.Localization.GetExceptionMessage("ModuleIdMustHaveSearchTypeIdForModule", "ModuleId based search must have SearchTypeId for a module only")); - - if(searchQuery.SortField == SortFields.CustomStringField || searchQuery.SortField == SortFields.CustomNumericField - || searchQuery.SortField == SortFields.NumericKey || searchQuery.SortField == SortFields.Keyword) - Requires.NotNullOrEmpty("CustomSortField", searchQuery.CustomSortField); - + if ((searchQuery.ModuleId > 0) && (searchQuery.SearchTypeIds.Count() > 1 || !searchQuery.SearchTypeIds.Contains(this._moduleSearchTypeId))) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdMustHaveSearchTypeIdForModule", "ModuleId based search must have SearchTypeId for a module only")); + } + + if (searchQuery.SortField == SortFields.CustomStringField || searchQuery.SortField == SortFields.CustomNumericField + || searchQuery.SortField == SortFields.NumericKey || searchQuery.SortField == SortFields.Keyword) + { + Requires.NotNullOrEmpty("CustomSortField", searchQuery.CustomSortField); + } var query = new BooleanQuery(); if (!string.IsNullOrEmpty(searchQuery.KeyWords)) { try { - var allowLeadingWildcard = HostController.Instance.GetString("Search_AllowLeadingWildcard", "N") == "Y" || searchQuery.AllowLeadingWildcard; - var keywords = SearchHelper.Instance.RephraseSearchText(searchQuery.KeyWords, searchQuery.WildCardSearch, allowLeadingWildcard); + var allowLeadingWildcard = HostController.Instance.GetString("Search_AllowLeadingWildcard", "N") == "Y" || searchQuery.AllowLeadingWildcard; + var keywords = SearchHelper.Instance.RephraseSearchText(searchQuery.KeyWords, searchQuery.WildCardSearch, allowLeadingWildcard); + // don't use stemming analyzer for exact matches or non-analyzed fields (e.g. Tags) var analyzer = LuceneController.Instance.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); var nonStemmerAnalyzer = new SearchQueryAnalyzer(false); @@ -90,10 +241,11 @@ private Tuple> GetResults(SearchQuery searchQuery) { var parserContent = new QueryParser(Constants.LuceneVersion, fieldToSearch, fieldToSearch == Constants.Tag ? nonStemmerAnalyzer : analyzer); - parserContent.AllowLeadingWildcard = allowLeadingWildcard; + parserContent.AllowLeadingWildcard = allowLeadingWildcard; var parsedQueryContent = parserContent.Parse(keywords); keywordQuery.Add(parsedQueryContent, Occur.SHOULD); } + query.Add(keywordQuery, Occur.MUST); } catch (Exception) @@ -108,20 +260,26 @@ private Tuple> GetResults(SearchQuery searchQuery) var portalIdQuery = new BooleanQuery(); foreach (var portalId in searchQuery.PortalIds) { - portalIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.PortalIdTag, portalId, portalId, true, true), Occur.SHOULD); + portalIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.PortalIdTag, portalId, portalId, true, true), Occur.SHOULD); } - if (searchQuery.PortalIds.Any()) query.Add(portalIdQuery, Occur.MUST); - - ApplySearchTypeIdFilter(query, searchQuery); + + if (searchQuery.PortalIds.Any()) + { + query.Add(portalIdQuery, Occur.MUST); + } + + this.ApplySearchTypeIdFilter(query, searchQuery); if (searchQuery.BeginModifiedTimeUtc > DateTime.MinValue && searchQuery.EndModifiedTimeUtc >= searchQuery.BeginModifiedTimeUtc) { query.Add(NumericRangeQuery.NewLongRange(Constants.ModifiedTimeTag, long.Parse(searchQuery.BeginModifiedTimeUtc.ToString(Constants.DateTimeFormat)), long.Parse(searchQuery.EndModifiedTimeUtc.ToString(Constants.DateTimeFormat)), true, true), Occur.MUST); } - if(searchQuery.RoleId > 0) - query.Add(NumericRangeQuery.NewIntRange(Constants.RoleIdTag, searchQuery.RoleId, searchQuery.RoleId, true, true), Occur.MUST); - + if (searchQuery.RoleId > 0) + { + query.Add(NumericRangeQuery.NewIntRange(Constants.RoleIdTag, searchQuery.RoleId, searchQuery.RoleId, true, true), Occur.MUST); + } + foreach (var tag in searchQuery.Tags) { var text = tag.ToLowerInvariant(); @@ -129,25 +287,27 @@ private Tuple> GetResults(SearchQuery searchQuery) { text = System.Net.WebUtility.HtmlDecode(text); } + query.Add(new TermQuery(new Term(Constants.Tag, text)), Occur.MUST); } foreach (var kvp in searchQuery.CustomKeywords) { - query.Add(new TermQuery(new Term( + query.Add( + new TermQuery(new Term( SearchHelper.Instance.StripTagsNoAttributes(Constants.KeywordsPrefixTag + kvp.Key, true), kvp.Value)), Occur.MUST); } foreach (var kvp in searchQuery.NumericKeys) { - query.Add(NumericRangeQuery.NewIntRange(Constants.NumericKeyPrefixTag + kvp.Key, kvp.Value, kvp.Value, true, true), Occur.MUST); + query.Add(NumericRangeQuery.NewIntRange(Constants.NumericKeyPrefixTag + kvp.Key, kvp.Value, kvp.Value, true, true), Occur.MUST); } if (!string.IsNullOrEmpty(searchQuery.CultureCode)) { var localeQuery = new BooleanQuery(); - var languageId = Localization.Localization.GetCultureLanguageID(searchQuery.CultureCode); + var languageId = Localization.GetCultureLanguageID(searchQuery.CultureCode); localeQuery.Add(NumericRangeQuery.NewIntRange(Constants.LocaleTag, languageId, languageId, true, true), Occur.SHOULD); localeQuery.Add(NumericRangeQuery.NewIntRange(Constants.LocaleTag, Null.NullInteger, Null.NullInteger, true, true), Occur.SHOULD); query.Add(localeQuery, Occur.MUST); @@ -156,19 +316,19 @@ private Tuple> GetResults(SearchQuery searchQuery) var luceneQuery = new LuceneQuery { Query = query, - Sort = GetSort(searchQuery), + Sort = this.GetSort(searchQuery), PageIndex = searchQuery.PageIndex, PageSize = searchQuery.PageSize, TitleSnippetLength = searchQuery.TitleSnippetLength, - BodySnippetLength = searchQuery.BodySnippetLength + BodySnippetLength = searchQuery.BodySnippetLength, }; - return GetSecurityTrimmedResults(searchQuery, luceneQuery); + return this.GetSecurityTrimmedResults(searchQuery, luceneQuery); } private Sort GetSort(SearchQuery query) { - var sort = Sort.RELEVANCE; //default sorting - relevance is always descending. + var sort = Sort.RELEVANCE; // default sorting - relevance is always descending. if (query.SortField != SortFields.Relevance) { var reverse = query.SortDirection != SortDirections.Ascending; @@ -207,13 +367,13 @@ private Sort GetSort(SearchQuery query) private void ApplySearchTypeIdFilter(BooleanQuery query, SearchQuery searchQuery) { - //Special handling for Module Search - if (searchQuery.SearchTypeIds.Count() == 1 && searchQuery.SearchTypeIds.Contains(_moduleSearchTypeId)) + // Special handling for Module Search + if (searchQuery.SearchTypeIds.Count() == 1 && searchQuery.SearchTypeIds.Contains(this._moduleSearchTypeId)) { - //When moduleid is specified, we ignore other searchtypeid or moduledefinitionid. Major security check + // When moduleid is specified, we ignore other searchtypeid or moduledefinitionid. Major security check if (searchQuery.ModuleId > 0) { - //this is the main hook for module based search. Occur.MUST is a requirement for this condition or else results from other modules will be found + // this is the main hook for module based search. Occur.MUST is a requirement for this condition or else results from other modules will be found query.Add(NumericRangeQuery.NewIntRange(Constants.ModuleIdTag, searchQuery.ModuleId, searchQuery.ModuleId, true, true), Occur.MUST); } else @@ -223,31 +383,38 @@ private void ApplySearchTypeIdFilter(BooleanQuery query, SearchQuery searchQuery { modDefQuery.Add(NumericRangeQuery.NewIntRange(Constants.ModuleDefIdTag, moduleDefId, moduleDefId, true, true), Occur.SHOULD); } - if (searchQuery.ModuleDefIds.Any()) - query.Add(modDefQuery, Occur.MUST); //Note the MUST + + if (searchQuery.ModuleDefIds.Any()) + { + query.Add(modDefQuery, Occur.MUST); // Note the MUST + } } - query.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, _moduleSearchTypeId, _moduleSearchTypeId, true, true), Occur.MUST); + query.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, this._moduleSearchTypeId, this._moduleSearchTypeId, true, true), Occur.MUST); } else { var searchTypeIdQuery = new BooleanQuery(); foreach (var searchTypeId in searchQuery.SearchTypeIds) { - if (searchTypeId == _moduleSearchTypeId) - { - foreach (var moduleDefId in searchQuery.ModuleDefIds.OrderBy(id => id)) + if (searchTypeId == this._moduleSearchTypeId) + { + foreach (var moduleDefId in searchQuery.ModuleDefIds.OrderBy(id => id)) { searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.ModuleDefIdTag, moduleDefId, moduleDefId, true, true), Occur.SHOULD); - } - if (!searchQuery.ModuleDefIds.Any()) - searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); + } + + if (!searchQuery.ModuleDefIds.Any()) + { + searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); + } } else { - searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); + searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); } } + query.Add(searchTypeIdQuery, Occur.MUST); } } @@ -258,7 +425,7 @@ private SearchResult GetSearchResultFromLuceneResult(LuceneResult luceneResult) var doc = luceneResult.Document; result.DisplayScore = luceneResult.DisplayScore; result.Score = luceneResult.Score; - + // set culture code of result result.CultureCode = string.Empty; var localeField = luceneResult.Document.GetField(Constants.LocaleTag); @@ -280,110 +447,26 @@ private SearchResult GetSearchResultFromLuceneResult(LuceneResult luceneResult) return result; } - private static void FillTagsValues(Document doc, SearchResult result) + private static SearchResult GetPartialSearchResult(Document doc, SearchQuery searchQuery) { - foreach (var field in doc.GetFields()) + var result = new SearchResult { SearchContext = searchQuery.SearchContext }; + var localeField = doc.GetField(Constants.LocaleTag); + + if (localeField != null) { - if (field.StringValue == null) continue; - int intField; - switch (field.Name) - { - case Constants.UniqueKeyTag: - result.UniqueKey = field.StringValue; - break; - case Constants.TitleTag: - var title = field.StringValue; - result.Title = title; - break; - case Constants.BodyTag: - result.Body = field.StringValue; - break; - case Constants.DescriptionTag: - result.Description = field.StringValue; - break; - case Constants.Tag: - result.Tags = result.Tags.Concat(new[] { field.StringValue }); - break; - case Constants.PermissionsTag: - result.Permissions = field.StringValue; - break; - case Constants.QueryStringTag: - result.QueryString = field.StringValue; - break; - case Constants.UrlTag: - result.Url = field.StringValue; - break; - case Constants.SearchTypeTag: - if(int.TryParse(field.StringValue, out intField)) result.SearchTypeId = intField; - break; - case Constants.ModuleIdTag: - if (int.TryParse(field.StringValue, out intField)) result.ModuleId = intField; - break; - case Constants.ModuleDefIdTag: - if (int.TryParse(field.StringValue, out intField)) result.ModuleDefId = intField; - break; - case Constants.PortalIdTag: - if (int.TryParse(field.StringValue, out intField)) result.PortalId = intField; - break; - case Constants.AuthorIdTag: - if (int.TryParse(field.StringValue, out intField)) result.AuthorUserId = intField; - break; - case Constants.RoleIdTag: - if (int.TryParse(field.StringValue, out intField)) result.RoleId = intField; - break; - case Constants.AuthorNameTag: - result.AuthorName = field.StringValue; - break; - case Constants.TabIdTag: - if (int.TryParse(field.StringValue, out intField)) result.TabId = intField; - break; - case Constants.ModifiedTimeTag: - DateTime modifiedTimeUtc; - DateTime.TryParseExact(field.StringValue, Constants.DateTimeFormat, null, DateTimeStyles.None, out modifiedTimeUtc); - result.ModifiedTimeUtc = modifiedTimeUtc; - break; - default: - if (field.Name.StartsWith(Constants.NumericKeyPrefixTag)) - { - var key = field.Name.Substring(Constants.NumericKeyPrefixTag.Length); - if (int.TryParse(field.StringValue, out intField)) - { - if (!result.NumericKeys.ContainsKey(key)) - result.NumericKeys.Add(key, intField); - } - } - else if (field.Name.StartsWith(Constants.KeywordsPrefixTag)) - { - var key = field.Name.Substring(Constants.KeywordsPrefixTag.Length); - if (!result.Keywords.ContainsKey(key)) - result.Keywords.Add(key, field.StringValue); - } - break; - } + int id; + result.CultureCode = int.TryParse(localeField.StringValue, out id) && id >= 0 + ? LocaleController.Instance.GetLocale(id).Code : Null.NullString; } - } - - private static string GetSnippet(SearchResult searchResult, LuceneResult luceneResult) - { - var sb = new StringBuilder(); - - if (!string.IsNullOrEmpty(luceneResult.TitleSnippet)) sb.Append(luceneResult.TitleSnippet + "..."); - if (!string.IsNullOrEmpty(luceneResult.DescriptionSnippet)) sb.Append(luceneResult.DescriptionSnippet + "..."); - if (!string.IsNullOrEmpty(luceneResult.TagSnippet)) sb.Append(luceneResult.TagSnippet + "..."); - if (!string.IsNullOrEmpty(luceneResult.BodySnippet)) sb.Append(luceneResult.BodySnippet + "..."); - if (!string.IsNullOrEmpty(luceneResult.AuthorSnippet)) sb.Append(luceneResult.AuthorSnippet + "..."); - if (!string.IsNullOrEmpty(luceneResult.ContentSnippet)) sb.Append(luceneResult.ContentSnippet + "..."); - - var snippet = sb.ToString(); - if (string.IsNullOrEmpty(snippet)) snippet = searchResult.Title; - return snippet; - } + FillTagsValues(doc, result); + return result; + } private Dictionary GetSearchResultControllers() { var cachArg = new CacheItemArgs(SeacrchContollersCacheKey, 120, CacheItemPriority.Default); - return CBO.GetCachedObject>(cachArg, GetSearchResultsControllersCallBack); + return CBO.GetCachedObject>(cachArg, this.GetSearchResultsControllersCallBack); } private Dictionary GetSearchResultsControllersCallBack(CacheItemArgs cacheItem) @@ -408,34 +491,34 @@ private Dictionary GetSearchResultsControllersCallBac return resultControllers; } - + private Tuple> GetSecurityTrimmedResults(SearchQuery searchQuery, LuceneQuery luceneQuery) { var results = new List(); var totalHits = 0; - //**************************************************************************** + // **************************************************************************** // First Fetch and determine starting item of current page - //**************************************************************************** + // **************************************************************************** if (searchQuery.PageSize > 0) { - var luceneResults = LuceneController.Instance.Search(new LuceneSearchContext - { - LuceneQuery = luceneQuery, - SearchQuery = searchQuery, - SecurityCheckerDelegate = HasPermissionToViewDoc - }); - results = luceneResults.Results.Select(GetSearchResultFromLuceneResult).ToList(); + var luceneResults = LuceneController.Instance.Search(new LuceneSearchContext + { + LuceneQuery = luceneQuery, + SearchQuery = searchQuery, + SecurityCheckerDelegate = this.HasPermissionToViewDoc, + }); + results = luceneResults.Results.Select(this.GetSearchResultFromLuceneResult).ToList(); totalHits = luceneResults.TotalHits; - //**************************************************************************** - //Adding URL Links to final trimmed results - //**************************************************************************** + // **************************************************************************** + // Adding URL Links to final trimmed results + // **************************************************************************** foreach (var result in results) { if (string.IsNullOrEmpty(result.Url)) { - var resultController = GetSearchResultControllers().Single(sc => sc.Key == result.SearchTypeId).Value; + var resultController = this.GetSearchResultControllers().Single(sc => sc.Key == result.SearchTypeId).Value; result.Url = resultController.GetDocUrl(result); } } @@ -443,32 +526,13 @@ private Tuple> GetSecurityTrimmedResults(SearchQuery se return new Tuple>(totalHits, results); } - + private bool HasPermissionToViewDoc(Document document, SearchQuery searchQuery) { // others LuceneResult fields are not impotrant at this moment var result = GetPartialSearchResult(document, searchQuery); - var resultController = GetSearchResultControllers().SingleOrDefault(sc => sc.Key == result.SearchTypeId).Value; + var resultController = this.GetSearchResultControllers().SingleOrDefault(sc => sc.Key == result.SearchTypeId).Value; return resultController != null && resultController.HasViewPermission(result); } - - private static SearchResult GetPartialSearchResult(Document doc, SearchQuery searchQuery) - { - var result = new SearchResult {SearchContext = searchQuery.SearchContext}; - var localeField = doc.GetField(Constants.LocaleTag); - - if (localeField != null) - { - int id; - result.CultureCode = int.TryParse(localeField.StringValue, out id) && id >= 0 - ? LocaleController.Instance.GetLocale(id).Code : Null.NullString; - } - - FillTagsValues(doc, result); - return result; - } - - - #endregion } } diff --git a/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs b/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs index 90a30a7f11a..2d644ad3cbb 100644 --- a/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs @@ -1,32 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { + using System; + using System.Linq; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Search.Entities; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// - /// Search Result Controller for Tab Indexer + /// Search Result Controller for Tab Indexer. /// /// [Serializable] public class TabResultController : BaseResultController { - private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; - - #region Abstract Class Implmentation + private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + public override string LocalizedSearchTypeName => Localization.GetString("Crawler_tab", LocalizedResxFile); + public override bool HasViewPermission(SearchResult searchResult) { var viewable = true; @@ -39,10 +37,10 @@ public override bool HasViewPermission(SearchResult searchResult) return viewable; } - + public override string GetDocUrl(SearchResult searchResult) { - var url = Localization.Localization.GetString("SEARCH_NoLink"); + var url = Localization.GetString("SEARCH_NoLink"); var tab = TabController.Instance.GetTab(searchResult.TabId, searchResult.PortalId, false); if (TabPermissionController.CanViewPage(tab)) @@ -64,12 +62,8 @@ public override string GetDocUrl(SearchResult searchResult) url = TestableGlobals.Instance.NavigateURL(searchResult.TabId, string.Empty, searchResult.QueryString); } } - + return url; } - - public override string LocalizedSearchTypeName => Localization.Localization.GetString("Crawler_tab", LocalizedResxFile); - - #endregion } } diff --git a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs index 09d36442adc..0ebb532542d 100644 --- a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs @@ -1,46 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Text.RegularExpressions; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Controllers { + using System; + using System.Linq; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Services.Search.Entities; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// - /// Search Result Controller for Tab Indexer + /// Search Result Controller for Tab Indexer. /// /// [Serializable] public class UserResultController : BaseResultController { + private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + private static readonly Regex SearchResultMatchRegex = new Regex(@"^(\d+)_", RegexOptions.Compiled); - private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; - - #region Private Properties - + public override string LocalizedSearchTypeName => Localization.GetString("Crawler_user", LocalizedResxFile); + private PortalSettings PortalSettings { get { return PortalController.Instance.GetCurrentPortalSettings(); } - } - - #endregion - - #region Abstract Class Implmentation - + } + public override bool HasViewPermission(SearchResult searchResult) { var userId = GetUserId(searchResult); @@ -49,7 +43,7 @@ public override bool HasViewPermission(SearchResult searchResult) return false; } - var userInSearchResult = UserController.GetUserById(PortalSettings.PortalId, userId); + var userInSearchResult = UserController.GetUserById(this.PortalSettings.PortalId, userId); if (userInSearchResult == null || userInSearchResult.IsDeleted) { return false; @@ -58,17 +52,17 @@ public override bool HasViewPermission(SearchResult searchResult) if (searchResult.UniqueKey.Contains("adminonly")) { var currentUser = UserController.Instance.GetCurrentUserInfo(); - return currentUser.IsSuperUser + return currentUser.IsSuperUser || currentUser.IsInRole("Administrators") || currentUser.UserID == userId; } - + if (searchResult.UniqueKey.Contains("friendsandgroups")) { var extendedVisibility = searchResult.UniqueKey.IndexOf("_") != searchResult.UniqueKey.LastIndexOf("_") ? searchResult.UniqueKey.Split('_')[2] : string.Empty; - return HasSocialReplationship(userInSearchResult, UserController.Instance.GetCurrentUserInfo(), extendedVisibility); + return this.HasSocialReplationship(userInSearchResult, UserController.Instance.GetCurrentUserInfo(), extendedVisibility); } if (searchResult.UniqueKey.Contains("membersonly")) @@ -100,16 +94,16 @@ public override bool HasViewPermission(SearchResult searchResult) public override string GetDocUrl(SearchResult searchResult) { - var url = TestableGlobals.Instance.NavigateURL(PortalSettings.UserTabId, string.Empty, "userid=" + GetUserId(searchResult)); + var url = TestableGlobals.Instance.NavigateURL(this.PortalSettings.UserTabId, string.Empty, "userid=" + GetUserId(searchResult)); return url; } - public override string LocalizedSearchTypeName => Localization.Localization.GetString("Crawler_user", LocalizedResxFile); - - #endregion - - #region Private Methods - + private static int GetUserId(SearchDocumentToDelete searchResult) + { + var match = SearchResultMatchRegex.Match(searchResult.UniqueKey); + return match.Success ? Convert.ToInt32(match.Groups[1].Value) : Null.NullInteger; + } + private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, string extendedVisibility) { if (string.IsNullOrEmpty(extendedVisibility)) @@ -117,12 +111,12 @@ private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, return false; } - var profileVisibility = new ProfileVisibility(PortalSettings.PortalId, extendedVisibility); + var profileVisibility = new ProfileVisibility(this.PortalSettings.PortalId, extendedVisibility); var isVisible = accessingUser.UserID == targetUser.UserID; if (!isVisible) { - //Relationships + // Relationships foreach (var relationship in profileVisibility.RelationshipVisibilities) { switch (relationship.RelationshipTypeId) @@ -137,8 +131,7 @@ private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, isVisible = targetUser.Social.UserRelationships.Any(userRelationship => (userRelationship.RelationshipId == relationship.RelationshipId && accessingUser.UserID == userRelationship.RelatedUserId - && userRelationship.Status == RelationshipStatus.Accepted) - ); + && userRelationship.Status == RelationshipStatus.Accepted)); break; } @@ -147,7 +140,8 @@ private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, break; } } - //Groups/Roles + + // Groups/Roles if (profileVisibility.RoleVisibilities.Any(role => accessingUser.IsInRole(role.RoleName))) { isVisible = true; @@ -156,12 +150,5 @@ private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, return isVisible; } - - private static int GetUserId(SearchDocumentToDelete searchResult) - { - var match = SearchResultMatchRegex.Match(searchResult.UniqueKey); - return match.Success ? Convert.ToInt32(match.Groups[1].Value) : Null.NullInteger; - } - #endregion } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs b/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs index 526d6011f3a..46bdccfd6d3 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Entities { + using System; + using System.Collections.Generic; + /// - /// The document that will be stored in Search Index + /// The document that will be stored in Search Index. /// - /// Each document is one discrete unit of content to be indexed and is independent from other Documents + /// Each document is one discrete unit of content to be indexed and is independent from other Documents. [Serializable] public class SearchDocument : SearchDocumentToDelete { + public SearchDocument() + { + this.Tags = new string[0]; + this.IsActive = true; + } + /// - /// Content's Title + /// Gets or sets content's Title. /// /// /// HTML tags are stripped from this property, but certain HTML attribute values will be retain, ie. alt and title attribute values. @@ -27,7 +28,7 @@ public class SearchDocument : SearchDocumentToDelete public string Title { get; set; } /// - /// Content's Description + /// Gets or sets content's Description. /// /// /// Description should generally be no more than two sentences. This property is used by RSS Syndication. It is also used in search result when highlighted text is not found during searching. @@ -36,7 +37,7 @@ public class SearchDocument : SearchDocumentToDelete public string Description { get; set; } /// - ///Content's Body + /// Gets or sets content's Body. /// /// /// HTML tags are stripped from this property, but certain HTML attribute values will be retain, ie. alt and title attribute values. @@ -44,60 +45,50 @@ public class SearchDocument : SearchDocumentToDelete public string Body { get; set; } /// - /// Url for the indexed item. + /// Gets or sets url for the indexed item. /// - /// Usually TabId or ModuleId is enough to generate Document Url in Search Result. However, Url field is used if present in SearchResult + /// Usually TabId or ModuleId is enough to generate Document Url in Search Result. However, Url field is used if present in SearchResult. public string Url { get; set; } /// - /// Time when Content was last modified (in Utc) + /// Gets or sets time when Content was last modified (in Utc). /// public DateTime ModifiedTimeUtc { get; set; } /// - /// Flag to indicate if Content is Active or Not. Content will be deleted from Index when IsActive = false. Default is True. + /// Gets or sets a value indicating whether flag to indicate if Content is Active or Not. Content will be deleted from Index when IsActive = false. Default is True. /// public bool IsActive { get; set; } /// - /// A string representation of roles and users who have view (or denied view) permissions + /// Gets or sets a string representation of roles and users who have view (or denied view) permissions. /// - /// The Permission property is same as how it�s implement internally in the Platform. Allow or Deny permission can be specified for RoleNamess and / or UserIds. + /// The Permission property is same as how it�s implement internally in the Platform. Allow or Deny permission can be specified for RoleNamess and / or UserIds. /// A semicolon must be specified to separate two RoleName or UserId. /// "!Translator (en-US);![3];[5];Administrators; ContentEditorRole" /// ! -- identifies denied permission /// [n] -- identifies UserId - ///Above example denies permission to Role �Translator (en-Us)� and UserId 3, but allows permission to Roles �Administrators� and �ContentEditorRole� and UserId + /// Above example denies permission to Role �Translator (en-Us)� and UserId 3, but allows permission to Roles �Administrators� and �ContentEditorRole� and UserId. public string Permissions { get; set; } /// - /// Tags can be specified as additional information + /// Gets or sets tags can be specified as additional information. /// - public IEnumerable Tags { get; set; } - - #region constructor - - public SearchDocument() - { - Tags = new string[0]; - IsActive = true; - } - - #endregion - + public IEnumerable Tags { get; set; } + public override string ToString() { return string.Join(", ", new[] { - "Portal ID: " + PortalId, - "Tab ID: " + TabId, - "Module ID: " + ModuleId, - "Mod. Def.ID: " + ModuleDefId, - "Url: " + Url, - "Unique Key: " + UniqueKey, - "Last Modified: " + ModifiedTimeUtc.ToString("O"), - "Culture: " + CultureCode, - "Search Type: " + SearchTypeId + "Portal ID: " + this.PortalId, + "Tab ID: " + this.TabId, + "Module ID: " + this.ModuleId, + "Mod. Def.ID: " + this.ModuleDefId, + "Url: " + this.Url, + "Unique Key: " + this.UniqueKey, + "Last Modified: " + this.ModifiedTimeUtc.ToString("O"), + "Culture: " + this.CultureCode, + "Search Type: " + this.SearchTypeId, }); } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs b/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs index 73befe1033f..6e1f650d079 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs @@ -1,65 +1,75 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Entities { + using System; + using System.Collections.Generic; + + using Newtonsoft.Json; + /// - /// The document that will be deleted from search Index + /// The document that will be deleted from search Index. /// - /// This is the base for all search documents (have ccommon properties) that can be used for deleting from the search index) + /// This is the base for all search documents (have ccommon properties) that can be used for deleting from the search index). [Serializable] public class SearchDocumentToDelete { + public SearchDocumentToDelete() + { + this.Keywords = new Dictionary(); + this.NumericKeys = new Dictionary(); + this.CultureCode = string.Empty; + this.SearchTypeId = + this.PortalId = + this.RoleId = -1; + this.ModuleDefId = + this.ModuleId = + this.TabId = + this.AuthorUserId = 0; + } + /// - /// A key to uniquely identify a document in the Index + /// Gets or sets a key to uniquely identify a document in the Index. /// /// A value of -1 means this is property is not used. public string UniqueKey { get; set; } /// - /// RoleId (GroupId) for additional filtering [Optional] + /// Gets or sets roleId (GroupId) for additional filtering [Optional]. /// /// This property can be used while under Social Groups. /// A value of -1 means this is property is not used. public int RoleId { get; set; } /// - /// Portal Id + /// Gets or sets portal Id. /// /// A value of -1 means this is property is not used. public int PortalId { get; set; } /// - /// Tab Id of the Content [Optional] + /// Gets or sets tab Id of the Content [Optional]. /// /// A value of -1 means this is property is not used. public int TabId { get; set; } /// - /// Module Definition Id of the Content. + /// Gets or sets module Definition Id of the Content. /// - /// This is needed when SearchTypeId is for a Module + /// This is needed when SearchTypeId is for a Module. /// A value of -1 means this is property is not used. public int ModuleDefId { get; set; } /// - /// Module Id of the Content + /// Gets or sets module Id of the Content. /// - /// This is needed when SearchTypeId is for a Module + /// This is needed when SearchTypeId is for a Module. /// A value of -1 means this is property is not used. public int ModuleId { get; set; } /// - /// User Id of the Author + /// Gets or sets user Id of the Author. /// /// Author's display name is automatically found and stored. AuthorName can be found in SearchResult. /// However, this may get out of date if Display Name is changed after Index. @@ -67,54 +77,40 @@ public class SearchDocumentToDelete public int AuthorUserId { get; set; } /// - /// Search Type Id, e.g. module, file or url + /// Gets or sets search Type Id, e.g. module, file or url. /// /// A value of -1 means this is property is not used. public int SearchTypeId { get; set; } /// - /// QueryString that may be associated with a Search Document. + /// Gets or sets queryString that may be associated with a Search Document. /// - /// This information will be used to creare Url for the document + /// This information will be used to creare Url for the document. /// A value of NULL/EMPTY means this is property is not used. public string QueryString { get; set; } /// - /// Additional keywords can be specified for Indexing + /// Gets or sets additional keywords can be specified for Indexing. /// - /// This is key-value pair, e.g. "AliasName","something" + /// This is key-value pair, e.g. "AliasName","something". /// An empty dictionary means this is property is not used. public IDictionary Keywords { get; set; } /// - /// Additional numeric fields can be specified for Indexing + /// Gets or sets additional numeric fields can be specified for Indexing. /// - /// This is key-value pair, e.g. "ItemId","888" + /// This is key-value pair, e.g. "ItemId","888". /// An empty dictionary means this is property is not used. public IDictionary NumericKeys { get; set; } /// - /// Culture Code associated with the content. + /// Gets or sets culture Code associated with the content. /// /// A value of NULL/EMPTY means this is property is not used. public string CultureCode { get; set; } - public SearchDocumentToDelete() - { - Keywords = new Dictionary(); - NumericKeys = new Dictionary(); - CultureCode = string.Empty; - SearchTypeId = - PortalId = - RoleId = -1; - ModuleDefId = - ModuleId = - TabId = - AuthorUserId = 0; - } - /// - /// This is to allow saving current instance into DB as JSON entity + /// This is to allow saving current instance into DB as JSON entity. /// /// public string ToJsonString() @@ -123,7 +119,7 @@ public string ToJsonString() } /// - /// This is overriden to present current instance as JSON string + /// This is overriden to present current instance as JSON string. /// /// public override string ToString() diff --git a/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs b/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs index 2291cde427b..0f1853fbc06 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs @@ -1,134 +1,144 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Entities { + using System; + using System.Collections; + using System.Collections.Generic; + /// /// Criteria to search for. /// - /// This object should be passed to SearchController to search for Content. KeyWords and PortalId must be specified + /// This object should be passed to SearchController to search for Content. KeyWords and PortalId must be specified. [Serializable] public class SearchQuery { - /// - /// A key to uniquely identify a document in the Index + public SearchQuery() + { + this.Tags = new string[0]; + this.PortalIds = new int[0]; + this.SearchTypeIds = new int[0]; + this.ModuleDefIds = new int[0]; + this.TitleSnippetLength = 60; + this.BodySnippetLength = 100; + this.PageSize = 10; + this.PageIndex = 1; + this.SearchContext = new Dictionary(); + this.CustomKeywords = new Dictionary(); + this.NumericKeys = new Dictionary(); + } + + /// + /// Gets or sets a key to uniquely identify a document in the Index. /// public string UniqueKey { get; set; } /// - /// Keywords to search for. + /// Gets or sets keywords to search for. /// public string KeyWords { get; set; } /// - /// A collection of Portal Ids of the Site to perform Search upon. This field must be specified or else Portal 0 will be searched by default. + /// Gets or sets a collection of Portal Ids of the Site to perform Search upon. This field must be specified or else Portal 0 will be searched by default. /// - /// Search cannot be executed across Sites + /// Search cannot be executed across Sites. public IEnumerable PortalIds { get; set; } /// - /// A collection of Search Type Ids that should be searched upon [Optional] + /// Gets or sets a collection of Search Type Ids that should be searched upon [Optional]. /// public IEnumerable SearchTypeIds { get; set; } /// - /// A collection of Module Def Ids that should be searched upon [Optional]. Match is performed only when a SearchTypeId for Module Search Crawler Id + /// Gets or sets a collection of Module Def Ids that should be searched upon [Optional]. Match is performed only when a SearchTypeId for Module Search Crawler Id. /// public IEnumerable ModuleDefIds { get; set; } /// - /// Module Id to restrict Search. Value > 0 is used only. + /// Gets or sets module Id to restrict Search. Value > 0 is used only. /// public int ModuleId { get; set; } /// - /// Role Id to restrict Search. Value > 0 is used only. + /// Gets or sets role Id to restrict Search. Value > 0 is used only. /// public int RoleId { get; set; } /// - /// Tab Id to restrict Search. Value > 0 is used only. + /// Gets or sets tab Id to restrict Search. Value > 0 is used only. /// public int TabId { get; set; } /// - /// Locale to restrict Search to. This field can be left empty for single language site + /// Gets or sets locale to restrict Search to. This field can be left empty for single language site. /// - /// E.g. A value en-US or nl-NL can specified to restrict search to a single locale . + /// E.g. A value en-US or nl-NL can specified to restrict search to a single locale . public string Locale { get; set; } - + /// - /// Begin Date of the time when Content was last modified (in Utc). This field is optional. + /// Gets or sets begin Date of the time when Content was last modified (in Utc). This field is optional. /// public DateTime BeginModifiedTimeUtc { get; set; } /// - /// End Date of the time when Content was last modified (in Utc). This field is optional. + /// Gets or sets end Date of the time when Content was last modified (in Utc). This field is optional. /// public DateTime EndModifiedTimeUtc { get; set; } /// - /// Restrict search to specific tags. This field is optional. + /// Gets or sets restrict search to specific tags. This field is optional. /// public IEnumerable Tags { get; set; } /// - /// Page Index for the result, e.g. pageIndex=1 and pageSize=10 indicates first 10 hits. Default value is 1 + /// Gets or sets page Index for the result, e.g. pageIndex=1 and pageSize=10 indicates first 10 hits. Default value is 1. /// public int PageIndex { get; set; } /// - /// Page size of the search result. Default value is 10. + /// Gets or sets page size of the search result. Default value is 10. /// public int PageSize { get; set; } /// - /// Maximum length of highlighted title field in the results + /// Gets or sets maximum length of highlighted title field in the results. /// public int TitleSnippetLength { get; set; } /// - /// Maximum length of highlighted title field in the results + /// Gets or sets maximum length of highlighted title field in the results. /// public int BodySnippetLength { get; set; } /// - /// Culture Code associated with the content. + /// Gets or sets culture Code associated with the content. /// - /// Culture-Neutral content is always returned even though this value is specfied + /// Culture-Neutral content is always returned even though this value is specfied. public string CultureCode { get; set; } /// - /// Sort option of the search result. This field is optional. + /// Gets or sets sort option of the search result. This field is optional. /// public SortFields SortField { get; set; } /// - /// Sort option of the search result. This field is optional. + /// Gets or sets sort option of the search result. This field is optional. /// public SortDirections SortDirection { get; set; } /// - /// Name of the custom sort field, works with SortFields.CustomNumericField or SortFields.CustomStringField option. + /// Gets or sets name of the custom sort field, works with SortFields.CustomNumericField or SortFields.CustomStringField option. /// /// Enum SortFields can be used to sort on Relevance, LastModified and Title. Additional fields such as one provided under /// SearchDocument.Keywords, SearchDocument.NumericKeys or Tags can be specified. /// can be specified by using CustomSortField property. One needs to ensure that the field name is a valid one. /// - /// authorid or authorname + /// authorid or authorname. public string CustomSortField { get; set; } /// - /// Set this to true to perform perform WildCard Search. + /// Gets or sets a value indicating whether set this to true to perform perform WildCard Search. /// /// This property is not respected when Keywords contain special boolean phrases "~", "*", "\"", "\'", "and", "or", "+", "-". /// When this is enabled, an additional OR is performed, e.g. (keyword OR keyword*). It adds asterisk at then end to find any words starting with the keyword. @@ -136,48 +146,29 @@ public class SearchQuery public bool WildCardSearch { get; set; } /// - /// Context information such as the type of module that initiated the search can be stored here. + /// Gets or sets context information such as the type of module that initiated the search can be stored here. /// This is key-value pair, e.g. "SearchSource","SiteSearch" /// public IDictionary SearchContext { get; set; } /// - /// Restrict search to specific Keywords. This field is optional. Lookup is done in the SearchDocument.Keywords collection. + /// Gets or sets restrict search to specific Keywords. This field is optional. Lookup is done in the SearchDocument.Keywords collection. /// - /// This is key-value pair, e.g. "AliasName","something" + /// This is key-value pair, e.g. "AliasName","something". /// An empty dictionary means this is property is not used. public IDictionary CustomKeywords { get; set; } /// - /// Restrict search to specific NumericKeys. This field is optional. + /// Gets or sets restrict search to specific NumericKeys. This field is optional. /// - /// This is key-value pair, e.g. "ItemId","888" + /// This is key-value pair, e.g. "ItemId","888". /// An empty dictionary means this is property is not used. public IDictionary NumericKeys { get; set; } - /// - /// Set this to true to allow search in word. - /// - /// When host setting "Search_AllowLeadingWildcard" set to true, it will always allow search in word but ignore this value. - public bool AllowLeadingWildcard { get; set; } - - #region constructor - - public SearchQuery() - { - Tags = new string[0]; - PortalIds = new int[0]; - SearchTypeIds = new int[0]; - ModuleDefIds = new int[0]; - TitleSnippetLength = 60; - BodySnippetLength = 100; - PageSize = 10; - PageIndex = 1; - SearchContext = new Dictionary(); - CustomKeywords = new Dictionary(); - NumericKeys = new Dictionary(); - } - - #endregion + /// + /// Gets or sets a value indicating whether set this to true to allow search in word. + /// + /// When host setting "Search_AllowLeadingWildcard" set to true, it will always allow search in word but ignore this value. + public bool AllowLeadingWildcard { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchResult.cs b/DNN Platform/Library/Services/Search/Entities/SearchResult.cs index d8be68b1c19..5f345cd2d0f 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchResult.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchResult.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Entities { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Search.Internals; + /// /// Search Result to be displayed to end user /// @@ -22,49 +17,53 @@ namespace DotNetNuke.Services.Search.Entities [Serializable] public class SearchResult : SearchDocument { + /// + /// Initializes a new instance of the class. + /// Empty Constructor. + /// + public SearchResult() + { + this.Tags = new string[0]; + this.NumericKeys = new Dictionary(); + this.Keywords = new Dictionary(); + this.SearchContext = new Dictionary(); + } + /// - /// Time when Content was last modified (in friendly format) + /// Gets time when Content was last modified (in friendly format). /// - public string DisplayModifiedTime { get { return DateUtils.CalculateDateForDisplay(ModifiedTimeUtc); } } + public string DisplayModifiedTime + { + get { return DateUtils.CalculateDateForDisplay(this.ModifiedTimeUtc); } + } /// - /// Highlighted snippet from document + /// Gets or sets highlighted snippet from document. /// public string Snippet { get; set; } /// - /// Optional: Display Name of the Author + /// Gets or sets optional: Display Name of the Author. /// /// This may be different form current Display Name when Index was run prior to change in Display Name. public string AuthorName { get; set; } /// - /// Lucene's original Score. The score of this document for the query. + /// Gets or sets lucene's original Score. The score of this document for the query. /// - /// This field may not be reliable as most of the time it contains Nan. Use DisplayScore instead + /// This field may not be reliable as most of the time it contains Nan. Use DisplayScore instead. public float Score { get; set; } /// - /// Lucene's original Score in String format, e.g. 1.45678 or 0.87642. The score of this document for the query. + /// Gets or sets lucene's original Score in String format, e.g. 1.45678 or 0.87642. The score of this document for the query. /// /// This field is more reliable than the float version of Score. public string DisplayScore { get; set; } /// - /// Context information such as the type of module that initiated the search can be stored here. + /// Gets or sets context information such as the type of module that initiated the search can be stored here. /// This is key-value pair, e.g. "SearchSource","SiteSearch" /// - public IDictionary SearchContext { get; set; } - - /// - /// Empty Constructor - /// - public SearchResult() - { - Tags = new string[0]; - NumericKeys = new Dictionary(); - Keywords = new Dictionary(); - SearchContext = new Dictionary(); - } + public IDictionary SearchContext { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchResults.cs b/DNN Platform/Library/Services/Search/Entities/SearchResults.cs index 76e6cc40abc..c1a48fe5e0d 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchResults.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchResults.cs @@ -1,38 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Entities { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + /// - /// Collection storing Search Results + /// Collection storing Search Results. /// [Serializable] public class SearchResults { + public SearchResults() + { + this.Results = new List(); + } + /// - /// Total Hits found in Lucene + /// Gets or sets total Hits found in Lucene. /// /// This number will generally be larger than count of Results object as Results usually holds 10 items, whereas TotalHits indicates TOTAL hits in entire Lucene for the query supplied. public int TotalHits { get; set; } /// - /// Collection of Results + /// Gets or sets collection of Results. /// public IList Results { get; set; } - - public SearchResults() - { - Results = new List(); - } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs b/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs index ee52e2846c3..18fa95bf5e3 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs @@ -1,21 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Entities { + using System; + [Serializable] public class SearchStopWords { public int StopWordsId { get; set; } + public string StopWords { get; set; } + public int CreatedByUserId { get; set; } + public int LastModifiedByUserId { get; set; } + public DateTime CreatedOnDate { get; set; } + public DateTime LastModifiedOnDate { get; set; } + public int PortalId { get; set; } + public string CultureCode { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchType.cs b/DNN Platform/Library/Services/Search/Entities/SearchType.cs index f32df7d8c30..82b01070f9a 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchType.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchType.cs @@ -1,31 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Entities { + using System; + [Serializable] public class SearchType { /// - /// Search Type Id + /// Gets or sets search Type Id. /// public int SearchTypeId { get; set; } - + /// - /// Search Type Name + /// Gets or sets search Type Name. /// public string SearchTypeName { get; set; } /// - /// A class implementing BaseResultController. This class will be invoked by reflection. + /// Gets or sets a class implementing BaseResultController. This class will be invoked by reflection. /// public string SearchResultClass { get; set; } /// - /// Content from this SearchType will normally be not searched while performing site or module search + /// Gets or sets a value indicating whether content from this SearchType will normally be not searched while performing site or module search. /// public bool IsPrivate { get; set; } } diff --git a/DNN Platform/Library/Services/Search/Entities/SortDirections.cs b/DNN Platform/Library/Services/Search/Entities/SortDirections.cs index a37f6744a15..b5bfe5e04ab 100644 --- a/DNN Platform/Library/Services/Search/Entities/SortDirections.cs +++ b/DNN Platform/Library/Services/Search/Entities/SortDirections.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Entities { /// - /// Sorting direction to be used for Querying + /// Sorting direction to be used for Querying. /// - /// Does not apply when SortFields.Relevance is specified in SearchQuery.SortField + /// Does not apply when SortFields.Relevance is specified in SearchQuery.SortField. public enum SortDirections { /// @@ -18,6 +18,6 @@ public enum SortDirections /// /// Sort by ascending order /// - Ascending = 1 + Ascending = 1, } } diff --git a/DNN Platform/Library/Services/Search/Entities/SortFields.cs b/DNN Platform/Library/Services/Search/Entities/SortFields.cs index 6b2e896df5d..a3eb3bc3424 100644 --- a/DNN Platform/Library/Services/Search/Entities/SortFields.cs +++ b/DNN Platform/Library/Services/Search/Entities/SortFields.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Entities { /// - /// Sorting criteria to be used for Querying + /// Sorting criteria to be used for Querying. /// public enum SortFields { @@ -18,7 +18,7 @@ public enum SortFields /// Sort by DateTime Modified. Latest come first /// LastModified = 1, - + /// /// Sort by Title. /// @@ -49,6 +49,6 @@ public enum SortFields /// Specify custom string filed for sorting. Field name should be specified in SearchQuery.CustomSortField /// /// This option should be used when you can't any of the previous options, e.g. authorname or UniqueKey (key) - CustomStringField = 7 + CustomStringField = 7, } } diff --git a/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs b/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs index 2decee65d12..6dcec0c897f 100644 --- a/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs +++ b/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs @@ -1,20 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Entities { + using System; + [Serializable] public class SynonymsGroup { public int SynonymsGroupId { get; set; } + public string SynonymsTags { get; set; } + public int CreatedByUserId { get; set; } + public int LastModifiedByUserId { get; set; } + public DateTime CreatedOnDate { get; set; } + public DateTime LastModifiedOnDate { get; set; } + public int PortalId { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/IndexingProvider.cs b/DNN Platform/Library/Services/Search/IndexingProvider.cs index 9a5c46739ac..9f54a30f30b 100644 --- a/DNN Platform/Library/Services/Search/IndexingProvider.cs +++ b/DNN Platform/Library/Services/Search/IndexingProvider.cs @@ -1,30 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { - /// A base class for search indexers + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + + /// A base class for search indexers. + [Obsolete("Legacy Indexing base class -- Deprecated in DNN 7.1. Use 'IndexingProviderBase' instead.. Scheduled removal in v10.0.0.")] public abstract class IndexingProvider { + private const string TimePostfix = "UtcTime"; + private const string DataPostfix = "Data"; + /// This method must save search documents in batches to minimize memory usage instead of returning all documents at once. - /// ID of the portal for which to index items - /// Minimum modification date of items that need to be indexed - /// A delegate function to send the collection of documents to for saving/indexing - /// The number of documents indexed - public virtual int IndexSearchDocuments(int portalId, + /// ID of the portal for which to index items. + /// Minimum modification date of items that need to be indexed. + /// A delegate function to send the collection of documents to for saving/indexing. + /// The number of documents indexed. + public virtual int IndexSearchDocuments( + int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer) { throw new NotImplementedException(); @@ -39,18 +40,15 @@ public virtual IEnumerable GetSearchDocuments(int portalId, Date [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] public abstract SearchItemInfoCollection GetSearchIndexItems(int portalId); - private const string TimePostfix = "UtcTime"; - private const string DataPostfix = "Data"; - - /// Retrieves the date/time of the last item to be indexed + /// Retrieves the date/time of the last item to be indexed. /// The portal ID. /// The schedule ID. /// The local time passed to . - /// Either or the stored index time, whichever is earlier + /// Either or the stored index time, whichever is earlier. protected DateTime GetLocalTimeOfLastIndexedItem(int portalId, int scheduleId, DateTime localTime) { var lastTime = SearchHelper.Instance.GetIndexerCheckpointUtcTime( - scheduleId, ScheduleItemSettingKey(portalId, TimePostfix)).ToLocalTime(); + scheduleId, this.ScheduleItemSettingKey(portalId, TimePostfix)).ToLocalTime(); return lastTime < localTime ? lastTime : localTime; } @@ -61,38 +59,38 @@ protected DateTime GetLocalTimeOfLastIndexedItem(int portalId, int scheduleId, D protected void SetLocalTimeOfLastIndexedItem(int portalId, int scheduleId, DateTime localTime) { SearchHelper.Instance.SetIndexerCheckpointUtcTime( - scheduleId, ScheduleItemSettingKey(portalId, TimePostfix), localTime.ToUniversalTime()); + scheduleId, this.ScheduleItemSettingKey(portalId, TimePostfix), localTime.ToUniversalTime()); } - /// Retrieves free format data to help the indexer to perform its job + /// Retrieves free format data to help the indexer to perform its job. /// The portal ID. /// The schedule ID. - /// The checkpoint data + /// The checkpoint data. protected string GetLastCheckpointData(int portalId, int scheduleId) { - return SearchHelper.Instance.GetIndexerCheckpointData(scheduleId, ScheduleItemSettingKey(portalId, DataPostfix)); + return SearchHelper.Instance.GetIndexerCheckpointData(scheduleId, this.ScheduleItemSettingKey(portalId, DataPostfix)); } - /// Stores free format data to help the indexer to perform its job + /// Stores free format data to help the indexer to perform its job. /// The portal ID. /// The schedule ID. /// The data to store. protected void SetLastCheckpointData(int portalId, int scheduleId, string data) { - SearchHelper.Instance.SetIndexerCheckpointData(scheduleId, ScheduleItemSettingKey(portalId, DataPostfix), data); + SearchHelper.Instance.SetIndexerCheckpointData(scheduleId, this.ScheduleItemSettingKey(portalId, DataPostfix), data); } /// /// Creates a unique name for the IndexingProvider implementation that can be used /// to save/retrieve scheduler item {key,name} setting pairs per portal and feature. /// - /// The ID of the portal - /// The name of the property + /// The ID of the portal. + /// The name of the property. /// /// Note that changing the class name in derived classes will cause this key to differ /// from the names stored in the database; therefore, don't change the derived class /// [full] names once these are deployed to market in an actual release version. - /// The format of the key is as follows: + /// The format of the key is as follows:. ///
      ///
    1. "Search" literal
    2. ///
    3. Name of the indexer class
    4. @@ -102,11 +100,11 @@ protected void SetLastCheckpointData(int portalId, int scheduleId, string data) ///
    ///
    ///
    - /// The setting key + /// The setting key. private string ScheduleItemSettingKey(int portalId, string propertyId) { Requires.NotNullOrEmpty("propertyId", propertyId); - var t = GetType(); + var t = this.GetType(); return string.Join("_", "Search", t.Name, t.FullName.GetHashCode().ToString("x8"), portalId.ToString(), propertyId); } } diff --git a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs new file mode 100644 index 00000000000..a97022931fc --- /dev/null +++ b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs @@ -0,0 +1,110 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Search +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + + /// A base class for search indexers. + public abstract class IndexingProviderBase + { + private const string TimePostfix = "UtcTime"; + private const string DataPostfix = "Data"; + + /// This method must save search documents in batches to minimize memory usage instead of returning all documents at once. + /// ID of the portal for which to index items. + /// Minimum modification date of items that need to be indexed. + /// A delegate function to send the collection of documents to for saving/indexing. + /// The number of documents indexed. + public abstract int IndexSearchDocuments( + int portalId, + ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer); + + [Obsolete("Deprecated in DNN 7.4.2 Use 'IndexSearchDocuments' instead for lower memory footprint during search.. Scheduled removal in v10.0.0.")] + public virtual IEnumerable GetSearchDocuments(int portalId, DateTime startDateLocal) + { + return Enumerable.Empty(); + } + + [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] + public virtual SearchItemInfoCollection GetSearchIndexItems(int portalId) + { + return new SearchItemInfoCollection(); + } + + /// Retrieves the date/time of the last item to be indexed. + /// The portal ID. + /// The schedule ID. + /// The local time passed to . + /// Either or the stored index time, whichever is earlier. + protected DateTime GetLocalTimeOfLastIndexedItem(int portalId, int scheduleId, DateTime localTime) + { + var lastTime = SearchHelper.Instance.GetIndexerCheckpointUtcTime( + scheduleId, this.ScheduleItemSettingKey(portalId, TimePostfix)).ToLocalTime(); + return lastTime < localTime ? lastTime : localTime; + } + + /// Stores the date/time of the last item to be indexed. + /// The portal ID. + /// The schedule ID. + /// The local time to store. + protected void SetLocalTimeOfLastIndexedItem(int portalId, int scheduleId, DateTime localTime) + { + SearchHelper.Instance.SetIndexerCheckpointUtcTime( + scheduleId, this.ScheduleItemSettingKey(portalId, TimePostfix), localTime.ToUniversalTime()); + } + + /// Retrieves free format data to help the indexer to perform its job. + /// The portal ID. + /// The schedule ID. + /// The checkpoint data. + protected string GetLastCheckpointData(int portalId, int scheduleId) + { + return SearchHelper.Instance.GetIndexerCheckpointData(scheduleId, this.ScheduleItemSettingKey(portalId, DataPostfix)); + } + + /// Stores free format data to help the indexer to perform its job. + /// The portal ID. + /// The schedule ID. + /// The data to store. + protected void SetLastCheckpointData(int portalId, int scheduleId, string data) + { + SearchHelper.Instance.SetIndexerCheckpointData(scheduleId, this.ScheduleItemSettingKey(portalId, DataPostfix), data); + } + + /// + /// Creates a unique name for the IndexingProvider implementation that can be used + /// to save/retrieve scheduler item {key,name} setting pairs per portal and feature. + /// + /// The ID of the portal. + /// The name of the property. + /// + /// Note that changing the class name in derived classes will cause this key to differ + /// from the names stored in the database; therefore, don't change the derived class + /// [full] names once these are deployed to market in an actual release version. + /// The format of the key is as follows:. + ///
      + ///
    1. "Search" literal
    2. + ///
    3. Name of the indexer class
    4. + ///
    5. Hash of the full class name of the indexer class (this and the previous will keep the key short and unique)
    6. + ///
    7. Portal ID the setting is related to
    8. + ///
    9. An additional property identifier set by the caller (this allows more items to be saved per indexer per portal)
    10. + ///
    + ///
    + ///
    + /// The setting key. + private string ScheduleItemSettingKey(int portalId, string propertyId) + { + Requires.NotNullOrEmpty("propertyId", propertyId); + var t = this.GetType(); + return string.Join("_", "Search", t.Name, t.FullName.GetHashCode().ToString("x8"), portalId.ToString(), propertyId); + } + } +} diff --git a/DNN Platform/Library/Services/Search/Internals/Constants.cs b/DNN Platform/Library/Services/Search/Internals/Constants.cs index efae035bbf7..81642b88dd1 100644 --- a/DNN Platform/Library/Services/Search/Internals/Constants.cs +++ b/DNN Platform/Library/Services/Search/Internals/Constants.cs @@ -1,17 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using Version = Lucene.Net.Util.Version; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + + using Version = Lucene.Net.Util.Version; + /// - /// Constants + /// Constants. /// internal static class Constants { @@ -45,49 +42,51 @@ internal static class Constants internal const string StatusTag = "status"; internal const string RoleIdTag = "role"; - //internal const string FolderIdTag = "folderid"; - //internal const string FileIdTag = "fileid"; - //internal const string FolderNameTag = "foldername"; - //internal const string FileNameTag = "filename"; - + // internal const string FolderIdTag = "folderid"; + // internal const string FileIdTag = "fileid"; + // internal const string FolderNameTag = "foldername"; + // internal const string FileNameTag = "filename"; internal const string DateTimeFormat = "yyyyMMddHHmmssfff"; internal const string ReindexDateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; - internal static Version LuceneVersion = Version.LUCENE_30; - - //Field Boost Settings - they are scaled down by 10. + // Field Boost Settings - they are scaled down by 10. internal const int DefaultSearchTitleBoost = 50; internal const int DefaultSearchTagBoost = 40; + + internal static Version LuceneVersion = Version.LUCENE_30; internal const int DefaultSearchKeywordBoost = 35; internal const int DefaultSearchDescriptionBoost = 20; internal const int DefaultSearchAuthorBoost = 15; - internal const int StandardLuceneBoost = 10; //Lucene's default boost is 1.0f + internal const int StandardLuceneBoost = 10; // Lucene's default boost is 1.0f - //Field Bosst Setting Names + // Field Bosst Setting Names internal const string SearchTitleBoostSetting = "Search_Title_Boost"; internal const string SearchTagBoostSetting = "Search_Tag_Boost"; internal const string SearchContentBoostSetting = "Search_Content_Boost"; internal const string SearchDescriptionBoostSetting = "Search_Description_Boost"; internal const string SearchAuthorBoostSetting = "Search_Author_Boost"; - //If weighted sum of Likes, Comment and Weight is the number below, Document gets a boost of 1.0 + // If weighted sum of Likes, Comment and Weight is the number below, Document gets a boost of 1.0 internal const int DefaultDocumentBoostScale = 1000; - internal readonly static string[] FieldsNeedAnalysis = { TitleTag, SubjectTag, CommentsTag, AuthorNameTag, StatusTag, CategoryTag }; + // search index tokenizers word lengths + internal const int MinimumMinLen = 1; + internal const int DefaultMinLen = 3; + + internal static readonly string[] FieldsNeedAnalysis = { TitleTag, SubjectTag, CommentsTag, AuthorNameTag, StatusTag, CategoryTag }; - internal readonly static string[] KeyWordSearchFields = { TitleTag, - Tag, - DescriptionTag, - BodyTag, - ContentTag, + internal static readonly string[] KeyWordSearchFields = + { + TitleTag, + Tag, + DescriptionTag, + BodyTag, + ContentTag, KeywordsPrefixTag + TitleTag, KeywordsPrefixTag + SubjectTag, KeywordsPrefixTag + CommentsTag, - KeywordsPrefixTag + AuthorNameTag}; - - // search index tokenizers word lengths - internal const int MinimumMinLen = 1; - internal const int DefaultMinLen = 3; + KeywordsPrefixTag + AuthorNameTag, + }; internal const int MaximumMinLen = 10; internal const int MinimumMaxLen = 10; diff --git a/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs b/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs index 3d15c79d5be..13e5f397bf8 100644 --- a/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs +++ b/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs @@ -1,56 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Entities; + /// /// Internal Search Controller Interface. /// This is an Internal interface and should not be used outside of Core. /// - public interface IInternalSearchController + public interface IInternalSearchController { /// - /// Get a List of Search Content Source that participate in Search - /// + /// Get a List of Search Content Source that participate in Search. + ///
    + /// IEnumerable GetSearchContentSourceList(int portalId); /// - /// Returns current search indexs general information + /// Returns current search indexs general information. /// /// SearchStatistics GetSearchStatistics(); /// - /// Get Friendly Display Name for the Search Result + /// Get Friendly Display Name for the Search Result. /// - /// SearchTypeId is used primarily to obtain this value. Multiple SearchTypeId can map to same Display Name, + /// SearchTypeId is used primarily to obtain this value. Multiple SearchTypeId can map to same Display Name, /// e.g. Tab, Module, Html/Module all map to Pages. - /// For SearchTypeId=module, ModuleDefitionId is also used. Module's display name is used unless an entry is found in - /// ~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx for the Module_[MODULENAME].txt is found. - string GetSearchDocumentTypeDisplayName(SearchResult searchResult); - - #region Core Search Indexing APIs - + /// For SearchTypeId=module, ModuleDefitionId is also used. Module's display name is used unless an entry is found in + /// ~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx for the Module_[MODULENAME].txt is found. + /// + string GetSearchDocumentTypeDisplayName(SearchResult searchResult); + /// - /// Add a Search Document to Search Index + /// Add a Search Document to Search Index. /// void AddSearchDocument(SearchDocument searchDocument); /// - /// Adds the collection of search documents to the search index + /// Adds the collection of search documents to the search index. /// /// - /// The controller auto-commits at the end of this method + /// The controller auto-commits at the end of this method. /// /// void AddSearchDocuments(IEnumerable searchDocumentList); @@ -63,7 +58,7 @@ public interface IInternalSearchController void DeleteSearchDocument(SearchDocument searchDocument); /// - /// Delete all search documents related to a particula module + /// Delete all search documents related to a particula module. /// /// /// @@ -71,14 +66,14 @@ public interface IInternalSearchController void DeleteSearchDocumentsByModule(int portalId, int moduleId, int moduleDefId); /// - /// Deletes all documents of a specified portal and search type (used for re-index operation) + /// Deletes all documents of a specified portal and search type (used for re-index operation). /// /// /// void DeleteAllDocuments(int portalId, int searchTypeId); /// - /// Commits individually added/deleted documents to the search index + /// Commits individually added/deleted documents to the search index. /// void Commit(); @@ -88,13 +83,11 @@ public interface IInternalSearchController ///
    /// /// This is a costly operation which consumes substantial CPU and I/O resources, therefore use it - /// judiciously. If your site has a a single server that performs both indexing and searching, then + /// judiciously. If your site has a a single server that performs both indexing and searching, then /// you should consider running the optimize operation after hours or over the weekend so that it /// does not interfere with ongoing search activities. /// /// True is optimization was scheduled to run in the background, false otherwise. - bool OptimizeSearchIndex(); - - #endregion + bool OptimizeSearchIndex(); } } diff --git a/DNN Platform/Library/Services/Search/Internals/ILuceneController.cs b/DNN Platform/Library/Services/Search/Internals/ILuceneController.cs index 43c2f6bb160..5fe0da329d1 100644 --- a/DNN Platform/Library/Services/Search/Internals/ILuceneController.cs +++ b/DNN Platform/Library/Services/Search/Internals/ILuceneController.cs @@ -1,41 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using DotNetNuke.Services.Search.Entities; -using Lucene.Net.Analysis; -using Lucene.Net.Documents; -using Lucene.Net.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Analysis; + using Lucene.Net.Documents; + using Lucene.Net.Search; + internal interface ILuceneController { /// - /// Execute Search + /// Execute Search. /// - /// Search Context - /// List of matching Documents + /// Search Context. + /// List of matching Documents. LuceneResults Search(LuceneSearchContext luceneSearchContext); /// - /// Adds Lucene Document in Lucene Index + /// Adds Lucene Document in Lucene Index. /// void Add(Document doc); /// - /// Delete a Search Document from the Search Index + /// Delete a Search Document from the Search Index. /// void Delete(Query query); /// - /// Commits the added search documents into the search database + /// Commits the added search documents into the search database. /// void Commit(); @@ -44,7 +40,7 @@ internal interface ILuceneController /// /// /// This is a costly operation which consumes substantial CPU and I/O resources, therefore use it - /// judiciously. If your site has a a single server that performs both indexing and searching, then + /// judiciously. If your site has a a single server that performs both indexing and searching, then /// you should consider running the optimize operation after hours or over the weekend so that it /// does not interfere with ongoing search activities. /// This means you should expect the size of your index to roughly triple (temporarily) @@ -69,13 +65,13 @@ internal interface ILuceneController int SearchbleDocsCount(); /// - /// Returns if the current search index has deletions + /// Returns if the current search index has deletions. /// - /// Whther the search index has deletions or not + /// Whther the search index has deletions or not. bool HasDeletions(); /// - /// Returns current search indexs general information + /// Returns current search indexs general information. /// /// object or null if the information can not be retrieved. SearchStatistics GetSearchStatistics(); diff --git a/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs b/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs index cbddcbefe7f..d9338e6bc2c 100644 --- a/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs +++ b/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs @@ -1,34 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Entities; + /// /// Internal Search Controller Helper Interface. /// This is an Internal interface and should not be used outside of Core. /// public interface ISearchHelper - { - - #region SearchType APIs - - // /// - // /// Commits the added search documents into the search database - // /// - // void Commit(); - + { + // /// + // /// Commits the added search documents into the search database + // /// + // void Commit(); + /// - /// Returns a list of SearchTypes defined in the system + /// Returns a list of SearchTypes defined in the system. /// /// IEnumerable GetSearchTypes(); @@ -37,60 +29,53 @@ public interface ISearchHelper /// Gets a SearchType Item for the given name. /// /// - SearchType GetSearchTypeByName(string searchTypeName); - - #endregion - - #region Synonym Management APIs + SearchType GetSearchTypeByName(string searchTypeName); + /// - /// Returns a list of Synonyms for a given word. E.g. leap, hop for jump + /// Returns a list of Synonyms for a given word. E.g. leap, hop for jump. /// - /// word for which to obtain synonyms - /// portal id - /// culture code - /// List of synonyms - /// Synonyms must be defined in system first + /// word for which to obtain synonyms. + /// portal id. + /// culture code. + /// List of synonyms. + /// Synonyms must be defined in system first. IEnumerable GetSynonyms(int portalId, string cultureCode, string term); /// - /// Returns a list of SynonymsGroup defined in the system + /// Returns a list of SynonymsGroup defined in the system. /// /// IEnumerable GetSynonymsGroups(int portalId, string cultureCode); /// - /// Adds a synonymsgroup to system + /// Adds a synonymsgroup to system. /// - /// synonyms tags seperated by comma, like this: dnn,dotnetnuke + /// synonyms tags seperated by comma, like this: dnn,dotnetnuke. /// - /// culture code + /// culture code. /// int AddSynonymsGroup(string synonymsTags, int portalId, string cultureCode, out string duplicateWord); /// - /// Updates a sysnonymsGroup + /// Updates a sysnonymsGroup. /// /// - /// synonyms tags seperated by comma, like this: dnn,dotnetnuke + /// synonyms tags seperated by comma, like this: dnn,dotnetnuke. /// - /// culture code + /// culture code. /// int UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int portalId, string cultureCode, out string duplicateWord); /// - /// Deletes a synonyms group + /// Deletes a synonyms group. /// /// /// - /// culture code - void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultureCode); - - #endregion - - #region Stop Word Management APIs - + /// culture code. + void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultureCode); + /// - /// Gets a search stop words + /// Gets a search stop words. /// /// /// @@ -98,7 +83,7 @@ public interface ISearchHelper SearchStopWords GetSearchStopWords(int portalId, string cultureCode); /// - /// Adds a search stop words + /// Adds a search stop words. /// /// /// @@ -107,7 +92,7 @@ public interface ISearchHelper int AddSearchStopWords(string stopWords, int portalId, string cultureCode); /// - /// Updates a search stop words + /// Updates a search stop words. /// /// /// @@ -117,38 +102,41 @@ public interface ISearchHelper int UpdateSearchStopWords(int stopWordsId, string stopWords, int portalId, string cultureCode); /// - /// Deletes a search stop words + /// Deletes a search stop words. /// /// /// /// - void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureCode); - - #endregion - - #region Reindex and Compact settings - + void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureCode); + DateTime GetSearchReindexRequestTime(int portalId); + DateTime SetSearchReindexRequestTime(int portalId); + bool GetSearchCompactFlag(); + void SetSearchReindexRequestTime(bool turnOn); + bool IsReindexRequested(int portalId, DateTime startDate); + IEnumerable GetPortalsToReindex(DateTime startDate); + DateTime GetLastSuccessfulIndexingDateTime(int scheduleId); + void SetLastSuccessfulIndexingDateTime(int scheduleId, DateTime startDateLocal); DateTime GetIndexerCheckpointUtcTime(int scheduleId, string indexerKey); + void SetIndexerCheckpointUtcTime(int scheduleId, string indexerKey, DateTime lastUtcTime); string GetIndexerCheckpointData(int scheduleId, string indexerKey); - void SetIndexerCheckpointData(int scheduleId, string indexerKey, string checkPointData); - - #endregion - - #region Other Search Helper methods + + void SetIndexerCheckpointData(int scheduleId, string indexerKey, string checkPointData); + Tuple GetSearchMinMaxLength(); - string RephraseSearchText(string searchPhrase, bool useWildCard, bool allowLeadingWildcard = false); - string StripTagsNoAttributes(string html, bool retainSpace); - #endregion + + string RephraseSearchText(string searchPhrase, bool useWildCard, bool allowLeadingWildcard = false); + + string StripTagsNoAttributes(string html, bool retainSpace); } } diff --git a/DNN Platform/Library/Services/Search/Internals/ISearchQueryStringParser.cs b/DNN Platform/Library/Services/Search/Internals/ISearchQueryStringParser.cs index 9f3378ee287..fb63202c229 100644 --- a/DNN Platform/Library/Services/Search/Internals/ISearchQueryStringParser.cs +++ b/DNN Platform/Library/Services/Search/Internals/ISearchQueryStringParser.cs @@ -1,36 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + public interface ISearchQueryStringParser { /// - /// Gets the list of tags parsing the search keywords + /// Gets the list of tags parsing the search keywords. /// - /// search keywords - /// output keywords removing the tags - /// List of tags + /// search keywords. + /// output keywords removing the tags. + /// List of tags. IList GetTags(string keywords, out string outputKeywords); /// - /// Gets the Last Modified Date parsing the search keywords + /// Gets the Last Modified Date parsing the search keywords. /// - /// search keywords - /// output keywords removing the last modified date - /// Last Modified Date + /// search keywords. + /// output keywords removing the last modified date. + /// Last Modified Date. DateTime GetLastModifiedDate(string keywords, out string outputKeywords); /// - /// Gets the list of Search Types parsing the search keywords + /// Gets the list of Search Types parsing the search keywords. /// - /// search keywords - /// output keywords removing the Search Type - /// List of Search Types + /// search keywords. + /// output keywords removing the Search Type. + /// List of Search Types. IList GetSearchTypeList(string keywords, out string outputKeywords); } } diff --git a/DNN Platform/Library/Services/Search/Internals/InternalSearchController.cs b/DNN Platform/Library/Services/Search/Internals/InternalSearchController.cs index 1be9663c060..998bd784933 100644 --- a/DNN Platform/Library/Services/Search/Internals/InternalSearchController.cs +++ b/DNN Platform/Library/Services/Search/Internals/InternalSearchController.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { - /// - /// Internal Search Controller. This is an Internal class and should not be used outside of Core - /// + using System; + + using DotNetNuke.Framework; + + /// + /// Internal Search Controller. This is an Internal class and should not be used outside of Core. + /// public class InternalSearchController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs index a8ec7412d93..fc820ea17a1 100644 --- a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs @@ -1,77 +1,104 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using System.Web.Caching; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Search.Controllers; -using DotNetNuke.Services.Search.Entities; - -using Lucene.Net.Documents; -using Lucene.Net.Index; -using Lucene.Net.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Documents; + using Lucene.Net.Index; + using Lucene.Net.Search; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// The Impl Controller class for Lucene + /// The Impl Controller class for Lucene. /// /// ----------------------------------------------------------------------------- internal class InternalSearchControllerImpl : IInternalSearchController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InternalSearchControllerImpl)); private const string SearchableModuleDefsKey = "{0}-{1}"; private const string SearchableModuleDefsCacheKey = "SearchableModuleDefs"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InternalSearchControllerImpl)); private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + private const string HtmlTagsWithAttrs = "<[a-z_:][\\w:.-]*(\\s+(?\\w+\\s*?=\\s*?[\"'].*?[\"']))+\\s*/?>"; + + private const string AttrText = "[\"'](?.*?)[\"']"; + private static readonly string[] HtmlAttributesToRetain = { "alt", "title" }; + private static readonly DataProvider DataProvider = DataProvider.Instance(); + + private static readonly Regex StripOpeningTagsRegex = new Regex(@"<\w*\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly int _titleBoost; private readonly int _tagBoost; private readonly int _contentBoost; private readonly int _descriptionBoost; private readonly int _authorBoost; private readonly int _moduleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - - private static readonly DataProvider DataProvider = DataProvider.Instance(); - - private static readonly Regex StripOpeningTagsRegex = new Regex(@"<\w*\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex StripClosingTagsRegex = new Regex(@"", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - #region constructor + private static readonly Regex StripClosingTagsRegex = new Regex(@"", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex HtmlTagsRegex = new Regex(HtmlTagsWithAttrs, RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex AttrTextRegex = new Regex(AttrText, RegexOptions.Compiled); + public InternalSearchControllerImpl() { var hostController = HostController.Instance; - _titleBoost = hostController.GetInteger(Constants.SearchTitleBoostSetting, Constants.DefaultSearchTitleBoost); - _tagBoost = hostController.GetInteger(Constants.SearchTagBoostSetting, Constants.DefaultSearchTagBoost); - _contentBoost = hostController.GetInteger(Constants.SearchContentBoostSetting, Constants.DefaultSearchKeywordBoost); - _descriptionBoost = hostController.GetInteger(Constants.SearchDescriptionBoostSetting, Constants.DefaultSearchDescriptionBoost); - _authorBoost = hostController.GetInteger(Constants.SearchAuthorBoostSetting, Constants.DefaultSearchAuthorBoost); + this._titleBoost = hostController.GetInteger(Constants.SearchTitleBoostSetting, Constants.DefaultSearchTitleBoost); + this._tagBoost = hostController.GetInteger(Constants.SearchTagBoostSetting, Constants.DefaultSearchTagBoost); + this._contentBoost = hostController.GetInteger(Constants.SearchContentBoostSetting, Constants.DefaultSearchKeywordBoost); + this._descriptionBoost = hostController.GetInteger(Constants.SearchDescriptionBoostSetting, Constants.DefaultSearchDescriptionBoost); + this._authorBoost = hostController.GetInteger(Constants.SearchAuthorBoostSetting, Constants.DefaultSearchAuthorBoost); + } + + public IEnumerable GetSearchContentSourceList(int portalId) + { + var searchableModuleDefsCacheArgs = new CacheItemArgs( + string.Format(SearchableModuleDefsKey, SearchableModuleDefsCacheKey, portalId), + 120, CacheItemPriority.Default); + + var list = CBO.GetCachedObject>( + searchableModuleDefsCacheArgs, this.SearchContentSourceCallback); + + return list; } - #endregion + public string GetSearchDocumentTypeDisplayName(SearchResult searchResult) + { + // ModuleDefId will be zero for non-module + var key = string.Format("{0}-{1}", searchResult.SearchTypeId, searchResult.ModuleDefId); + var keys = CBO.Instance.GetCachedObject>( + new CacheItemArgs(key, 120, CacheItemPriority.Default), this.SearchDocumentTypeDisplayNameCallBack, false); + + return keys.ContainsKey(key) ? keys[key] : string.Empty; + } + + public void AddSearchDocument(SearchDocument searchDocument) + { + this.AddSearchDocumentInternal(searchDocument, false); + } + internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) { var searchTypes = CBO.FillCollection(DataProvider.GetAllSearchTypes()); @@ -91,25 +118,29 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) foreach (ModuleInfo module in modules) { - if (!modDefIds.Contains(module.ModuleDefID)) modDefIds.Add(module.ModuleDefID); + if (!modDefIds.Contains(module.ModuleDefID)) + { + modDefIds.Add(module.ModuleDefID); + } } - + var list = modDefIds.Select(ModuleDefinitionController.GetModuleDefinitionByID).ToList(); foreach (var def in list) { - var text = Localization.Localization.GetSafeJSString("Module_" + def.DefinitionName, LocalizedResxFile); + var text = Localization.GetSafeJSString("Module_" + def.DefinitionName, LocalizedResxFile); if (string.IsNullOrEmpty(text)) { text = def.FriendlyName; } + var result = new SearchContentSource { SearchTypeId = crawler.SearchTypeId, SearchTypeName = crawler.SearchTypeName, IsPrivate = crawler.IsPrivate, - ModuleDefinitionId = def.ModuleDefID, - LocalizedName = text + ModuleDefinitionId = def.ModuleDefID, + LocalizedName = text, }; results.Add(result); @@ -120,8 +151,8 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) default: var resultControllerType = Reflection.CreateType(crawler.SearchResultClass); - var resultController = (BaseResultController)Reflection.CreateObject(resultControllerType); - var localizedName = Localization.Localization.GetSafeJSString(resultController.LocalizedSearchTypeName); + var resultController = (BaseResultController)Reflection.CreateObject(resultControllerType); + var localizedName = Localization.GetSafeJSString(resultController.LocalizedSearchTypeName); results.Add(new SearchContentSource { @@ -129,26 +160,13 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) SearchTypeName = crawler.SearchTypeName, IsPrivate = crawler.IsPrivate, ModuleDefinitionId = 0, - LocalizedName = localizedName + LocalizedName = localizedName, }); break; } } return results; - - } - - public IEnumerable GetSearchContentSourceList(int portalId) - { - var searchableModuleDefsCacheArgs = new CacheItemArgs( - string.Format(SearchableModuleDefsKey, SearchableModuleDefsCacheKey, portalId), - 120, CacheItemPriority.Default); - - var list = CBO.GetCachedObject>( - searchableModuleDefsCacheArgs, SearchContentSourceCallback); - - return list; } private object SearchDocumentTypeDisplayNameCallBack(CacheItemArgs cacheItem) @@ -156,33 +174,55 @@ private object SearchDocumentTypeDisplayNameCallBack(CacheItemArgs cacheItem) var data = new Dictionary(); foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - var searchContentSources = GetSearchContentSourceList(portal.PortalID); + var searchContentSources = this.GetSearchContentSourceList(portal.PortalID); foreach (var searchContentSource in searchContentSources) { var key = string.Format("{0}-{1}", searchContentSource.SearchTypeId, searchContentSource.ModuleDefinitionId); - if(!data.ContainsKey(key)) - data.Add(key, searchContentSource.LocalizedName); + if (!data.ContainsKey(key)) + { + data.Add(key, searchContentSource.LocalizedName); + } } } return data; } - public string GetSearchDocumentTypeDisplayName(SearchResult searchResult) + public void AddSearchDocuments(IEnumerable searchDocuments) { - //ModuleDefId will be zero for non-module - var key = string.Format("{0}-{1}", searchResult.SearchTypeId, searchResult.ModuleDefId); - var keys = CBO.Instance.GetCachedObject>( - new CacheItemArgs(key, 120, CacheItemPriority.Default), SearchDocumentTypeDisplayNameCallBack, false); + var searchDocs = searchDocuments as IList ?? searchDocuments.ToList(); + if (searchDocs.Any()) + { + const int commitBatchSize = 1024 * 16; + var idx = 0; + + // var added = false; + foreach (var searchDoc in searchDocs) + { + try + { + this.AddSearchDocumentInternal(searchDoc, (++idx % commitBatchSize) == 0); + + // added = true; + } + catch (Exception ex) + { + Logger.ErrorFormat("Search Document error: {0}{1}{2}", searchDoc, Environment.NewLine, ex); + } + } - return keys.ContainsKey(key) ? keys[key] : string.Empty; + // Note: modified to do commit only once at the end of scheduler job + // check so we don't commit again + // if (added && (idx % commitBatchSize) != 0) + // { + // Commit(); + // } + } } - #region Core Search APIs - - public void AddSearchDocument(SearchDocument searchDocument) + public void DeleteSearchDocument(SearchDocument searchDocument) { - AddSearchDocumentInternal(searchDocument, false); + this.DeleteSearchDocumentInternal(searchDocument, false); } private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) @@ -192,47 +232,54 @@ private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoC Requires.NotNegative("SearchTypeId", searchDocument.SearchTypeId); Requires.PropertyNotEqualTo("searchDocument", "SearchTypeId", searchDocument.SearchTypeId, 0); Requires.PropertyNotEqualTo("searchDocument", "ModifiedTimeUtc", searchDocument.ModifiedTimeUtc.ToString(CultureInfo.InvariantCulture), DateTime.MinValue.ToString(CultureInfo.InvariantCulture)); - - if (searchDocument.SearchTypeId == _moduleSearchTypeId) - { - if(searchDocument.ModuleDefId <= 0) - throw new ArgumentException( Localization.Localization.GetExceptionMessage("ModuleDefIdMustBeGreaterThanZero","ModuleDefId must be greater than zero when SearchTypeId is for a module")); - if (searchDocument.ModuleId <= 0) - throw new ArgumentException(Localization.Localization.GetExceptionMessage("ModuleIdMustBeGreaterThanZero","ModuleId must be greater than zero when SearchTypeId is for a module")); + if (searchDocument.SearchTypeId == this._moduleSearchTypeId) + { + if (searchDocument.ModuleDefId <= 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleDefIdMustBeGreaterThanZero", "ModuleDefId must be greater than zero when SearchTypeId is for a module")); + } + + if (searchDocument.ModuleId <= 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdMustBeGreaterThanZero", "ModuleId must be greater than zero when SearchTypeId is for a module")); + } } else { - if (searchDocument.ModuleDefId > 0) - throw new ArgumentException(Localization.Localization.GetExceptionMessage("ModuleDefIdWhenSearchTypeForModule","ModuleDefId is needed only when SearchTypeId is for a module")); - - if (searchDocument.ModuleId > 0) - throw new ArgumentException(Localization.Localization.GetExceptionMessage("ModuleIdWhenSearchTypeForModule","ModuleId is needed only when SearchTypeId is for a module")); + if (searchDocument.ModuleDefId > 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleDefIdWhenSearchTypeForModule", "ModuleDefId is needed only when SearchTypeId is for a module")); + } + + if (searchDocument.ModuleId > 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdWhenSearchTypeForModule", "ModuleId is needed only when SearchTypeId is for a module")); + } } var doc = new Document(); var sb = new StringBuilder(); - //TODO - Set setOmitTermFreqAndPositions - //TODO - Check if Numeric fields need to have Store.YES or Store.NO - //TODO - Should ModifiedTime be mandatory - //TODO - Is Locale needed for a single-language site - //TODO - Sorting + // TODO - Set setOmitTermFreqAndPositions + // TODO - Check if Numeric fields need to have Store.YES or Store.NO + // TODO - Should ModifiedTime be mandatory + // TODO - Is Locale needed for a single-language site + // TODO - Sorting - //Field.Store.YES | Stores the value. When the value is stored, the original String in its entirety is recorded in the index - //Field.Store.NO | Doesn’t store the value. This option is often used along with Index.ANALYZED to index a large text field that doesn’t need to be retrieved + // Field.Store.YES | Stores the value. When the value is stored, the original String in its entirety is recorded in the index + // Field.Store.NO | Doesn’t store the value. This option is often used along with Index.ANALYZED to index a large text field that doesn’t need to be retrieved // | in its original form, such as bodies of web pages, or any other type of text document. - //Index.ANALYZED | Use the analyzer to break the field’s value into a stream of separate tokens and make each token searchable - //Index.NOT_ANALYZED | Do index the field, but don’t analyze the String value.Instead, treat the Field’s entire value as a single token and make that token searchable. + // Index.ANALYZED | Use the analyzer to break the field’s value into a stream of separate tokens and make each token searchable + // Index.NOT_ANALYZED | Do index the field, but don’t analyze the String value.Instead, treat the Field’s entire value as a single token and make that token searchable. // Generic and Additional SearchDocument Params - AddSearchDocumentParamters(doc, searchDocument, sb); - - - //Remove the existing document from Lucene - DeleteSearchDocumentInternal(searchDocument, false); + this.AddSearchDocumentParamters(doc, searchDocument, sb); + + // Remove the existing document from Lucene + this.DeleteSearchDocumentInternal(searchDocument, false); - //Add only when Document is active. The previous call would have otherwise deleted the document if it existed earlier + // Add only when Document is active. The previous call would have otherwise deleted the document if it existed earlier if (searchDocument.IsActive) { Thread.SetData(Thread.GetNamedDataSlot(Constants.TlsSearchInfo), searchDocument); @@ -248,103 +295,20 @@ private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoC if (autoCommit) { - Commit(); + this.Commit(); } } - public void AddSearchDocuments(IEnumerable searchDocuments) - { - var searchDocs = searchDocuments as IList ?? searchDocuments.ToList(); - if (searchDocs.Any()) - { - const int commitBatchSize = 1024 * 16; - var idx = 0; - //var added = false; - - foreach (var searchDoc in searchDocs) - { - try - { - AddSearchDocumentInternal(searchDoc, (++idx%commitBatchSize) == 0); - //added = true; - } - catch (Exception ex) - { - Logger.ErrorFormat("Search Document error: {0}{1}{2}", searchDoc, Environment.NewLine, ex); - } - } - - //Note: modified to do commit only once at the end of scheduler job - // check so we don't commit again - //if (added && (idx % commitBatchSize) != 0) - //{ - // Commit(); - //} - } - } - - public void DeleteSearchDocument(SearchDocument searchDocument) - { - DeleteSearchDocumentInternal(searchDocument, false); - } - - private void DeleteSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) - { - var query = new BooleanQuery(); - - if (searchDocument.SearchTypeId > -1) - query.Add(NumericValueQuery(Constants.SearchTypeTag, searchDocument.SearchTypeId), Occur.MUST); - - if (searchDocument.PortalId > -1) - query.Add(NumericValueQuery(Constants.PortalIdTag, searchDocument.PortalId), Occur.MUST); - - if (searchDocument.RoleId > -1) - query.Add(NumericValueQuery(Constants.RoleIdTag, searchDocument.RoleId), Occur.MUST); - - if (searchDocument.ModuleDefId > 0) - query.Add(NumericValueQuery(Constants.ModuleDefIdTag, searchDocument.ModuleDefId), Occur.MUST); - - if (searchDocument.ModuleId > 0) - query.Add(NumericValueQuery(Constants.ModuleIdTag, searchDocument.ModuleId), Occur.MUST); - - if (searchDocument.TabId > 0) - query.Add(NumericValueQuery(Constants.TabIdTag, searchDocument.TabId), Occur.MUST); - - if (searchDocument.AuthorUserId > 0) - query.Add(NumericValueQuery(Constants.AuthorIdTag, searchDocument.AuthorUserId), Occur.MUST); - - if (!string.IsNullOrEmpty(searchDocument.UniqueKey)) - query.Add(new TermQuery(new Term(Constants.UniqueKeyTag, searchDocument.UniqueKey)), Occur.MUST); - - if (!string.IsNullOrEmpty(searchDocument.QueryString)) - query.Add(new TermQuery(new Term(Constants.QueryStringTag, searchDocument.QueryString)), Occur.MUST); - - if (!string.IsNullOrEmpty(searchDocument.CultureCode)) - query.Add(NumericValueQuery(Constants.LocaleTag, Localization.Localization.GetCultureLanguageID(searchDocument.CultureCode)), Occur.MUST); - - LuceneController.Instance.Delete(query); - - if (autoCommit) - { - Commit(); - } - } - - private static Query NumericValueQuery(string numericName, int numericVal) - { - return NumericRangeQuery.NewIntRange(numericName, numericVal, numericVal, true, true); - } - public void DeleteSearchDocumentsByModule(int portalId, int moduleId, int moduleDefId) { Requires.NotNegative("PortalId", portalId); - DeleteSearchDocument(new SearchDocument + this.DeleteSearchDocument(new SearchDocument { PortalId = portalId, ModuleId = moduleId, ModuleDefId = moduleDefId, - SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId + SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, }); } @@ -352,13 +316,80 @@ public void DeleteAllDocuments(int portalId, int searchTypeId) { Requires.NotNegative("SearchTypeId", searchTypeId); - DeleteSearchDocument(new SearchDocument + this.DeleteSearchDocument(new SearchDocument { PortalId = portalId, - SearchTypeId = searchTypeId + SearchTypeId = searchTypeId, }); } + private static Query NumericValueQuery(string numericName, int numericVal) + { + return NumericRangeQuery.NewIntRange(numericName, numericVal, numericVal, true, true); + } + + private void DeleteSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) + { + var query = new BooleanQuery(); + + if (searchDocument.SearchTypeId > -1) + { + query.Add(NumericValueQuery(Constants.SearchTypeTag, searchDocument.SearchTypeId), Occur.MUST); + } + + if (searchDocument.PortalId > -1) + { + query.Add(NumericValueQuery(Constants.PortalIdTag, searchDocument.PortalId), Occur.MUST); + } + + if (searchDocument.RoleId > -1) + { + query.Add(NumericValueQuery(Constants.RoleIdTag, searchDocument.RoleId), Occur.MUST); + } + + if (searchDocument.ModuleDefId > 0) + { + query.Add(NumericValueQuery(Constants.ModuleDefIdTag, searchDocument.ModuleDefId), Occur.MUST); + } + + if (searchDocument.ModuleId > 0) + { + query.Add(NumericValueQuery(Constants.ModuleIdTag, searchDocument.ModuleId), Occur.MUST); + } + + if (searchDocument.TabId > 0) + { + query.Add(NumericValueQuery(Constants.TabIdTag, searchDocument.TabId), Occur.MUST); + } + + if (searchDocument.AuthorUserId > 0) + { + query.Add(NumericValueQuery(Constants.AuthorIdTag, searchDocument.AuthorUserId), Occur.MUST); + } + + if (!string.IsNullOrEmpty(searchDocument.UniqueKey)) + { + query.Add(new TermQuery(new Term(Constants.UniqueKeyTag, searchDocument.UniqueKey)), Occur.MUST); + } + + if (!string.IsNullOrEmpty(searchDocument.QueryString)) + { + query.Add(new TermQuery(new Term(Constants.QueryStringTag, searchDocument.QueryString)), Occur.MUST); + } + + if (!string.IsNullOrEmpty(searchDocument.CultureCode)) + { + query.Add(NumericValueQuery(Constants.LocaleTag, Localization.GetCultureLanguageID(searchDocument.CultureCode)), Occur.MUST); + } + + LuceneController.Instance.Delete(query); + + if (autoCommit) + { + this.Commit(); + } + } + public void Commit() { LuceneController.Instance.Commit(); @@ -373,33 +404,48 @@ public bool OptimizeSearchIndex() public SearchStatistics GetSearchStatistics() { return LuceneController.Instance.GetSearchStatistics(); - } - - #endregion - - #region Private methods + } + /// + /// Add Field to Doc when supplied fieldValue > 0. + /// + private static void AddIntField(Document doc, int fieldValue, string fieldTag) + { + if (fieldValue > 0) + { + doc.Add(new NumericField(fieldTag, Field.Store.YES, true).SetIntValue(fieldValue)); + } + } + private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocument, StringBuilder sb) { - //mandatory fields + // mandatory fields doc.Add(new Field(Constants.UniqueKeyTag, SearchHelper.Instance.StripTagsNoAttributes(searchDocument.UniqueKey, true), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new NumericField(Constants.PortalIdTag, Field.Store.YES, true).SetIntValue(searchDocument.PortalId)); doc.Add(new NumericField(Constants.SearchTypeTag, Field.Store.YES, true).SetIntValue(searchDocument.SearchTypeId)); doc.Add(!string.IsNullOrEmpty(searchDocument.CultureCode) - ? new NumericField(Constants.LocaleTag, Field.Store.YES, true).SetIntValue(Localization.Localization.GetCultureLanguageID(searchDocument.CultureCode)) + ? new NumericField(Constants.LocaleTag, Field.Store.YES, true).SetIntValue(Localization.GetCultureLanguageID(searchDocument.CultureCode)) : new NumericField(Constants.LocaleTag, Field.Store.YES, true).SetIntValue(-1)); if (!string.IsNullOrEmpty(searchDocument.Title)) { var field = new Field(Constants.TitleTag, StripTagsRetainAttributes(searchDocument.Title, HtmlAttributesToRetain, false, true), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - if (_titleBoost >0 && _titleBoost != Constants.StandardLuceneBoost) field.Boost = _titleBoost / 10f; + if (this._titleBoost > 0 && this._titleBoost != Constants.StandardLuceneBoost) + { + field.Boost = this._titleBoost / 10f; + } + doc.Add(field); } if (!string.IsNullOrEmpty(searchDocument.Description)) { var field = new Field(Constants.DescriptionTag, StripTagsRetainAttributes(searchDocument.Description, HtmlAttributesToRetain, false, true), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - if (_descriptionBoost > 0 && _descriptionBoost != Constants.StandardLuceneBoost) field.Boost = _descriptionBoost / 10f; + if (this._descriptionBoost > 0 && this._descriptionBoost != Constants.StandardLuceneBoost) + { + field.Boost = this._descriptionBoost / 10f; + } + doc.Add(field); } @@ -426,28 +472,32 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum switch (key) { case Constants.TitleTag: - if (_titleBoost > 0 && _titleBoost != Constants.StandardLuceneBoost) + if (this._titleBoost > 0 && this._titleBoost != Constants.StandardLuceneBoost) { - field.Boost = _titleBoost / 10f; + field.Boost = this._titleBoost / 10f; } + break; case Constants.SubjectTag: - if (_contentBoost > 0 && _contentBoost != Constants.StandardLuceneBoost) + if (this._contentBoost > 0 && this._contentBoost != Constants.StandardLuceneBoost) { - field.Boost = _contentBoost / 10f; + field.Boost = this._contentBoost / 10f; } + break; case Constants.CommentsTag: - if (_descriptionBoost > 0 && _descriptionBoost != Constants.StandardLuceneBoost) + if (this._descriptionBoost > 0 && this._descriptionBoost != Constants.StandardLuceneBoost) { - field.Boost = _descriptionBoost / 10f; + field.Boost = this._descriptionBoost / 10f; } + break; case Constants.AuthorNameTag: - if (_authorBoost > 0 && _authorBoost != Constants.StandardLuceneBoost) + if (this._authorBoost > 0 && this._authorBoost != Constants.StandardLuceneBoost) { - field.Boost = _authorBoost / 10f; + field.Boost = this._authorBoost / 10f; } + break; } @@ -466,12 +516,13 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum var field = new Field(Constants.Tag, SearchHelper.Instance.StripTagsNoAttributes(tag.ToLowerInvariant(), true), Field.Store.YES, Field.Index.NOT_ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); if (!tagBoostApplied) { - if (_tagBoost > 0 && _tagBoost != Constants.StandardLuceneBoost) + if (this._tagBoost > 0 && this._tagBoost != Constants.StandardLuceneBoost) { - field.Boost = _tagBoost / 10f; + field.Boost = this._tagBoost / 10f; tagBoostApplied = true; } } + doc.Add(field); } @@ -487,7 +538,11 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum if (user != null && !string.IsNullOrEmpty(user.DisplayName)) { var field = new Field(Constants.AuthorNameTag, user.DisplayName, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - if (_authorBoost > 0 && _authorBoost != Constants.StandardLuceneBoost) field.Boost = _authorBoost / 10f; + if (this._authorBoost > 0 && this._authorBoost != Constants.StandardLuceneBoost) + { + field.Boost = this._authorBoost / 10f; + } + doc.Add(field); } } @@ -503,41 +558,29 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum { var field = new Field(Constants.ContentTag, SearchHelper.Instance.StripTagsNoAttributes(sb.ToString(), true), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); doc.Add(field); - if (_contentBoost > 0 && _contentBoost != Constants.StandardLuceneBoost) field.Boost = _contentBoost/10f; + if (this._contentBoost > 0 && this._contentBoost != Constants.StandardLuceneBoost) + { + field.Boost = this._contentBoost / 10f; + } } - } - /// - /// Add Field to Doc when supplied fieldValue > 0 - /// - private static void AddIntField(Document doc, int fieldValue, string fieldTag) - { - if (fieldValue > 0) - doc.Add(new NumericField(fieldTag, Field.Store.YES, true).SetIntValue(fieldValue)); - } - - private const string HtmlTagsWithAttrs = "<[a-z_:][\\w:.-]*(\\s+(?\\w+\\s*?=\\s*?[\"'].*?[\"']))+\\s*/?>"; - private static readonly Regex HtmlTagsRegex = new Regex(HtmlTagsWithAttrs, RegexOptions.IgnoreCase | RegexOptions.Compiled); - - private const string AttrText = "[\"'](?.*?)[\"']"; - private static readonly Regex AttrTextRegex = new Regex(AttrText, RegexOptions.Compiled); - private static string StripTagsRetainAttributes(string html, IEnumerable attributes, bool decoded, bool retainSpace) { var attributesList = attributes as IList ?? attributes.ToList(); var strippedString = html; - var emptySpace = retainSpace ? " " : ""; + var emptySpace = retainSpace ? " " : string.Empty; - if (!String.IsNullOrEmpty(strippedString)) + if (!string.IsNullOrEmpty(strippedString)) { // Remove all opening HTML Tags with no attributes strippedString = StripOpeningTagsRegex.Replace(strippedString, emptySpace); + // Remove all closing HTML Tags strippedString = StripClosingTagsRegex.Replace(strippedString, emptySpace); } - if (!String.IsNullOrEmpty(strippedString)) + if (!string.IsNullOrEmpty(strippedString)) { var list = new List(); @@ -571,11 +614,12 @@ private static string StripTagsRetainAttributes(string html, IEnumerable } // If not decoded, decode and strip again. Becareful with recursive - if (!decoded) strippedString = StripTagsRetainAttributes(HttpUtility.HtmlDecode(strippedString), attributesList, true, retainSpace); - + if (!decoded) + { + strippedString = StripTagsRetainAttributes(HttpUtility.HtmlDecode(strippedString), attributesList, true, retainSpace); + } + return strippedString; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneController.cs b/DNN Platform/Library/Services/Search/Internals/LuceneController.cs index 512207b084b..bbdec08d790 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneController.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneController.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { - /// - /// Low-level APIs to manage Lucene Layer. This is an Internal class and should not be used outside of Core - /// + using System; + + using DotNetNuke.Framework; + + /// + /// Low-level APIs to manage Lucene Layer. This is an Internal class and should not be used outside of Core. + /// internal class LuceneController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs index d7f40d0c21d..39e82eccba2 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs @@ -1,104 +1,95 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Search.Entities; -using Lucene.Net.Analysis; -using Lucene.Net.Documents; -using Lucene.Net.Index; -using Lucene.Net.Search; -using Lucene.Net.Search.Vectorhighlight; -using Lucene.Net.Store; -using DotNetNuke.Instrumentation; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Analysis; + using Lucene.Net.Documents; + using Lucene.Net.Index; + using Lucene.Net.Search; + using Lucene.Net.Search.Vectorhighlight; + using Lucene.Net.Store; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// The Impl Controller class for Lucene + /// The Impl Controller class for Lucene. /// /// ----------------------------------------------------------------------------- internal class LuceneControllerImpl : ILuceneController, IDisposable - { - #region Constants + { + internal const int DefaultRereadTimeSpan = 30; // in seconds private const string DefaultSearchFolder = @"App_Data\Search"; private const string WriteLockFile = "write.lock"; - internal const int DefaultRereadTimeSpan = 30; // in seconds private const int DefaultSearchRetryTimes = 5; private const int DISPOSED = 1; - private const int UNDISPOSED = 0; - #endregion - - #region Private Properties - + private const int UNDISPOSED = 0; + private const string HighlightPreTag = "[b]"; + private const string HighlightPostTag = "[/b]"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LuceneControllerImpl)); - internal string IndexFolder { get; private set; } - private IndexWriter _writer; private IndexReader _idxReader; private CachedReader _reader; + + internal string IndexFolder { get; private set; } private FastVectorHighlighter _fastHighlighter; private readonly object _writerLock = new object(); private readonly double _readerTimeSpan; // in seconds - private readonly int _searchRetryTimes; //search retry times if exception thrown during search process + private readonly int _searchRetryTimes; // search retry times if exception thrown during search process private readonly List _oldReaders = new List(); private int _isDisposed = UNDISPOSED; - private const string HighlightPreTag = "[b]"; - private const string HighlightPostTag = "[/b]"; - private const string HtmlPreTag = ""; - private const string HtmlPostTag = ""; + private const string HtmlPostTag = "
    "; - #region constructor + private DateTime _lastReadTimeUtc; + private DateTime _lastDirModifyTimeUtc; + public LuceneControllerImpl() { var hostController = HostController.Instance; var folder = hostController.GetString(Constants.SearchIndexFolderKey, DefaultSearchFolder); - if (string.IsNullOrEmpty(folder)) folder = DefaultSearchFolder; - IndexFolder = Path.Combine(Globals.ApplicationMapPath, folder); - _readerTimeSpan = hostController.GetDouble(Constants.SearchReaderRefreshTimeKey, DefaultRereadTimeSpan); - _searchRetryTimes = hostController.GetInteger(Constants.SearchRetryTimesKey, DefaultSearchRetryTimes); - } - - private void CheckDisposed() - { - if (Thread.VolatileRead(ref _isDisposed) == DISPOSED) - throw new ObjectDisposedException(Localization.Localization.GetExceptionMessage("LuceneControlerIsDisposed","LuceneController is disposed and cannot be used anymore")); + if (string.IsNullOrEmpty(folder)) + { + folder = DefaultSearchFolder; + } + + this.IndexFolder = Path.Combine(Globals.ApplicationMapPath, folder); + this._readerTimeSpan = hostController.GetDouble(Constants.SearchReaderRefreshTimeKey, DefaultRereadTimeSpan); + this._searchRetryTimes = hostController.GetInteger(Constants.SearchRetryTimesKey, DefaultSearchRetryTimes); } - #endregion - + private IndexWriter Writer { get { - if (_writer == null) + if (this._writer == null) { - lock (_writerLock) + lock (this._writerLock) { - if (_writer == null) + if (this._writer == null) { - var lockFile = Path.Combine(IndexFolder, WriteLockFile); + var lockFile = Path.Combine(this.IndexFolder, WriteLockFile); if (File.Exists(lockFile)) { try @@ -111,134 +102,107 @@ private IndexWriter Writer { #pragma warning disable 0618 throw new SearchException( - Localization.Localization.GetExceptionMessage("UnableToCreateLuceneWriter","Unable to create Lucene writer (lock file is in use). Please recycle AppPool in IIS to release lock."), + Localization.GetExceptionMessage("UnableToCreateLuceneWriter", "Unable to create Lucene writer (lock file is in use). Please recycle AppPool in IIS to release lock."), e, new SearchItemInfo()); #pragma warning restore 0618 } } - CheckDisposed(); - var writer = new IndexWriter(FSDirectory.Open(IndexFolder), - GetCustomAnalyzer() ?? new SynonymAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); - _idxReader = writer.GetReader(); + this.CheckDisposed(); + var writer = new IndexWriter( + FSDirectory.Open(this.IndexFolder), + this.GetCustomAnalyzer() ?? new SynonymAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); + this._idxReader = writer.GetReader(); Thread.MemoryBarrier(); - _writer = writer; + this._writer = writer; } } } - return _writer; + + return this._writer; + } + } + + private bool MustRereadIndex + { + get + { + return (DateTime.UtcNow - this._lastReadTimeUtc).TotalSeconds >= this._readerTimeSpan && + System.IO.Directory.Exists(this.IndexFolder) && + System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder) != this._lastDirModifyTimeUtc; } } // made internal to be used in unit tests only; otherwise could be made private internal IndexSearcher GetSearcher() { - if (_reader == null || MustRereadIndex) + if (this._reader == null || this.MustRereadIndex) { - CheckValidIndexFolder(); - UpdateLastAccessTimes(); - InstantiateReader(); + this.CheckValidIndexFolder(); + this.UpdateLastAccessTimes(); + this.InstantiateReader(); } - return _reader.GetSearcher(); + return this._reader.GetSearcher(); } + private void CheckDisposed() + { + if (Thread.VolatileRead(ref this._isDisposed) == DISPOSED) + { + throw new ObjectDisposedException(Localization.GetExceptionMessage("LuceneControlerIsDisposed", "LuceneController is disposed and cannot be used anymore")); + } + } + private void InstantiateReader() { IndexSearcher searcher; - if (_idxReader != null) + if (this._idxReader != null) { - //use the Reopen() method for better near-realtime when the _writer ins't null - var newReader = _idxReader.Reopen(); - if (_idxReader != newReader) + // use the Reopen() method for better near-realtime when the _writer ins't null + var newReader = this._idxReader.Reopen(); + if (this._idxReader != newReader) { - //_idxReader.Dispose(); -- will get disposed upon disposing the searcher - Interlocked.Exchange(ref _idxReader, newReader); + // _idxReader.Dispose(); -- will get disposed upon disposing the searcher + Interlocked.Exchange(ref this._idxReader, newReader); } - searcher = new IndexSearcher(_idxReader); + searcher = new IndexSearcher(this._idxReader); } else { // Note: disposing the IndexSearcher instance obtained from the next // statement will not close the underlying reader on dispose. - searcher = new IndexSearcher(FSDirectory.Open(IndexFolder)); + searcher = new IndexSearcher(FSDirectory.Open(this.IndexFolder)); } var reader = new CachedReader(searcher); - var cutoffTime = DateTime.Now - TimeSpan.FromSeconds(_readerTimeSpan*10); - lock (((ICollection) _oldReaders).SyncRoot) + var cutoffTime = DateTime.Now - TimeSpan.FromSeconds(this._readerTimeSpan * 10); + lock (((ICollection)this._oldReaders).SyncRoot) { - CheckDisposed(); - _oldReaders.RemoveAll(r => r.LastUsed <= cutoffTime); - _oldReaders.Add(reader); - Interlocked.Exchange(ref _reader, reader); + this.CheckDisposed(); + this._oldReaders.RemoveAll(r => r.LastUsed <= cutoffTime); + this._oldReaders.Add(reader); + Interlocked.Exchange(ref this._reader, reader); } } - private DateTime _lastReadTimeUtc; - private DateTime _lastDirModifyTimeUtc; - - private bool MustRereadIndex - { - get - { - return (DateTime.UtcNow - _lastReadTimeUtc).TotalSeconds >= _readerTimeSpan && - System.IO.Directory.Exists(IndexFolder) && - System.IO.Directory.GetLastWriteTimeUtc(IndexFolder) != _lastDirModifyTimeUtc; - } - } - - private void UpdateLastAccessTimes() - { - _lastReadTimeUtc = DateTime.UtcNow; - if (System.IO.Directory.Exists(IndexFolder)) - { - _lastDirModifyTimeUtc = System.IO.Directory.GetLastWriteTimeUtc(IndexFolder); - } - } - - private void RescheduleAccessTimes() - { - // forces re-opening the reader within 30 seconds from now (used mainly by commit) - var now = DateTime.UtcNow; - if (_readerTimeSpan > DefaultRereadTimeSpan && (now - _lastReadTimeUtc).TotalSeconds > DefaultRereadTimeSpan) - { - _lastReadTimeUtc = now - TimeSpan.FromSeconds(_readerTimeSpan - DefaultRereadTimeSpan); - } - } - - private void CheckValidIndexFolder() - { - if (!ValidateIndexFolder()) - { - throw new SearchIndexEmptyException(Localization.Localization.GetExceptionMessage("SearchIndexingDirectoryNoValid","Search indexing directory is either empty or does not exist")); - } - } - - private bool ValidateIndexFolder() - { - return System.IO.Directory.Exists(IndexFolder) && - System.IO.Directory.GetFiles(IndexFolder, "*.*").Length > 0; - } - private FastVectorHighlighter FastHighlighter { get { - if (_fastHighlighter == null) + if (this._fastHighlighter == null) { FragListBuilder fragListBuilder = new SimpleFragListBuilder(); FragmentsBuilder fragmentBuilder = new ScoreOrderFragmentsBuilder( new[] { HighlightPreTag }, new[] { HighlightPostTag }); - _fastHighlighter = new FastVectorHighlighter(true, true, fragListBuilder, fragmentBuilder); + this._fastHighlighter = new FastVectorHighlighter(true, true, fragListBuilder, fragmentBuilder); } - return _fastHighlighter; + + return this._fastHighlighter; } - } - - #endregion - + } + public LuceneResults Search(LuceneSearchContext searchContext) { Requires.NotNull("LuceneQuery", searchContext.LuceneQuery); @@ -248,29 +212,29 @@ public LuceneResults Search(LuceneSearchContext searchContext) var luceneResults = new LuceneResults(); - //validate whether index folder is exist and contains index files, otherwise return null. - if (!ValidateIndexFolder()) + // validate whether index folder is exist and contains index files, otherwise return null. + if (!this.ValidateIndexFolder()) { return luceneResults; } - - var highlighter = FastHighlighter; + + var highlighter = this.FastHighlighter; var fieldQuery = highlighter.GetFieldQuery(searchContext.LuceneQuery.Query); var maxResults = searchContext.LuceneQuery.PageIndex * searchContext.LuceneQuery.PageSize; var minResults = maxResults - searchContext.LuceneQuery.PageSize + 1; - for (var i = 0; i < _searchRetryTimes; i++) + for (var i = 0; i < this._searchRetryTimes; i++) { try { - var searcher = GetSearcher(); + var searcher = this.GetSearcher(); var searchSecurityTrimmer = new SearchSecurityTrimmer(new SearchSecurityTrimmerContext { Searcher = searcher, SecurityChecker = searchContext.SecurityCheckerDelegate, LuceneQuery = searchContext.LuceneQuery, - SearchQuery = searchContext.SearchQuery + SearchQuery = searchContext.SearchQuery, }); searcher.Search(searchContext.LuceneQuery.Query, null, searchSecurityTrimmer); luceneResults.TotalHits = searchSecurityTrimmer.TotalHits; @@ -281,31 +245,33 @@ public LuceneResults Search(LuceneSearchContext searchContext) Logger.Trace(sb); } - //Page doesn't exist - if (luceneResults.TotalHits < minResults) - break; - + // Page doesn't exist + if (luceneResults.TotalHits < minResults) + { + break; + } + luceneResults.Results = searchSecurityTrimmer.ScoreDocs.Select(match => new LuceneResult { Document = searcher.Doc(match.Doc), Score = match.Score, - DisplayScore = GetDisplayScoreFromMatch(match.ToString()), - TitleSnippet = GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.TitleTag, searchContext.LuceneQuery.TitleSnippetLength), - BodySnippet = GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.BodyTag, searchContext.LuceneQuery.BodySnippetLength), - DescriptionSnippet = GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.DescriptionTag, searchContext.LuceneQuery.TitleSnippetLength), - TagSnippet = GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.Tag, searchContext.LuceneQuery.TitleSnippetLength), - AuthorSnippet = GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.AuthorNameTag, searchContext.LuceneQuery.TitleSnippetLength), - ContentSnippet = GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.ContentTag, searchContext.LuceneQuery.TitleSnippetLength) + DisplayScore = this.GetDisplayScoreFromMatch(match.ToString()), + TitleSnippet = this.GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.TitleTag, searchContext.LuceneQuery.TitleSnippetLength), + BodySnippet = this.GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.BodyTag, searchContext.LuceneQuery.BodySnippetLength), + DescriptionSnippet = this.GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.DescriptionTag, searchContext.LuceneQuery.TitleSnippetLength), + TagSnippet = this.GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.Tag, searchContext.LuceneQuery.TitleSnippetLength), + AuthorSnippet = this.GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.AuthorNameTag, searchContext.LuceneQuery.TitleSnippetLength), + ContentSnippet = this.GetHighlightedText(highlighter, fieldQuery, searcher, match, Constants.ContentTag, searchContext.LuceneQuery.TitleSnippetLength), }).ToList(); break; } catch (Exception ex) when (ex is IOException || ex is AlreadyClosedException) { - DisposeReaders(); - DisposeWriter(false); + this.DisposeReaders(); + this.DisposeWriter(false); - if (i == _searchRetryTimes - 1) + if (i == this._searchRetryTimes - 1) { throw; } @@ -319,14 +285,31 @@ public LuceneResults Search(LuceneSearchContext searchContext) return luceneResults; } - private string GetHighlightedText(FastVectorHighlighter highlighter, FieldQuery fieldQuery, IndexSearcher searcher, ScoreDoc match, string tag, int length) + public void Add(Document doc) { - var s = highlighter.GetBestFragment(fieldQuery, searcher.IndexReader, match.Doc, tag, length); - if (!string.IsNullOrEmpty(s)) + Requires.NotNull("searchDocument", doc); + if (doc.GetFields().Count > 0) { - s = HttpUtility.HtmlEncode(s).Replace(HighlightPreTag, HtmlPreTag).Replace(HighlightPostTag, HtmlPostTag); + try + { + this.Writer.AddDocument(doc); + } + catch (OutOfMemoryException) + { + lock (this._writerLock) + { + // as suggested by Lucene's doc + this.DisposeWriter(); + this.Writer.AddDocument(doc); + } + } } - return s; + } + + public void Delete(Query query) + { + Requires.NotNull("luceneQuery", query); + this.Writer.DeleteDocuments(query); } private static StringBuilder GetSearcResultExplanation(LuceneQuery luceneQuery, IEnumerable scoreDocs, IndexSearcher searcher) @@ -341,63 +324,84 @@ private static StringBuilder GetSearcResultExplanation(LuceneQuery luceneQuery, sb.AppendLine(doc.Get(Constants.TitleTag)); sb.AppendLine(explanation.ToString()); } + return sb; } - /// - /// Extract the Score portion of the match.ToString() - /// - private string GetDisplayScoreFromMatch(string match) + private void UpdateLastAccessTimes() { - var displayScore = string.Empty; - if (!string.IsNullOrEmpty(match)) + this._lastReadTimeUtc = DateTime.UtcNow; + if (System.IO.Directory.Exists(this.IndexFolder)) { - var beginPos = match.IndexOf('['); - var endPos = match.LastIndexOf(']'); - if (beginPos > 0 && endPos > 0 && endPos > beginPos) displayScore = match.Substring(beginPos + 1, endPos - beginPos - 1); + this._lastDirModifyTimeUtc = System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder); } + } - return displayScore; + private void RescheduleAccessTimes() + { + // forces re-opening the reader within 30 seconds from now (used mainly by commit) + var now = DateTime.UtcNow; + if (this._readerTimeSpan > DefaultRereadTimeSpan && (now - this._lastReadTimeUtc).TotalSeconds > DefaultRereadTimeSpan) + { + this._lastReadTimeUtc = now - TimeSpan.FromSeconds(this._readerTimeSpan - DefaultRereadTimeSpan); + } } - public void Add(Document doc) + private void CheckValidIndexFolder() { - Requires.NotNull("searchDocument", doc); - if (doc.GetFields().Count > 0) + if (!this.ValidateIndexFolder()) { - try - { - Writer.AddDocument(doc); - } - catch (OutOfMemoryException) - { - lock (_writerLock) - { - // as suggested by Lucene's doc - DisposeWriter(); - Writer.AddDocument(doc); - } - } + throw new SearchIndexEmptyException(Localization.GetExceptionMessage("SearchIndexingDirectoryNoValid", "Search indexing directory is either empty or does not exist")); } } - public void Delete(Query query) + private bool ValidateIndexFolder() { - Requires.NotNull("luceneQuery", query); - Writer.DeleteDocuments(query); + return System.IO.Directory.Exists(this.IndexFolder) && + System.IO.Directory.GetFiles(this.IndexFolder, "*.*").Length > 0; + } + + private string GetHighlightedText(FastVectorHighlighter highlighter, FieldQuery fieldQuery, IndexSearcher searcher, ScoreDoc match, string tag, int length) + { + var s = highlighter.GetBestFragment(fieldQuery, searcher.IndexReader, match.Doc, tag, length); + if (!string.IsNullOrEmpty(s)) + { + s = HttpUtility.HtmlEncode(s).Replace(HighlightPreTag, HtmlPreTag).Replace(HighlightPostTag, HtmlPostTag); + } + + return s; + } + + /// + /// Extract the Score portion of the match.ToString(). + /// + private string GetDisplayScoreFromMatch(string match) + { + var displayScore = string.Empty; + if (!string.IsNullOrEmpty(match)) + { + var beginPos = match.IndexOf('['); + var endPos = match.LastIndexOf(']'); + if (beginPos > 0 && endPos > 0 && endPos > beginPos) + { + displayScore = match.Substring(beginPos + 1, endPos - beginPos - 1); + } + } + + return displayScore; } public void Commit() { - if (_writer != null) + if (this._writer != null) { - lock (_writerLock) + lock (this._writerLock) { - if (_writer != null) + if (this._writer != null) { - CheckDisposed(); - _writer.Commit(); - RescheduleAccessTimes(); + this.CheckDisposed(); + this._writer.Commit(); + this.RescheduleAccessTimes(); } } } @@ -405,7 +409,7 @@ public void Commit() public bool OptimizeSearchIndex(bool doWait) { - var writer = _writer; + var writer = this._writer; if (writer != null && writer.HasDeletions()) { if (doWait) @@ -413,13 +417,14 @@ public bool OptimizeSearchIndex(bool doWait) Logger.Debug("Compacting Search Index - started"); } - CheckDisposed(); - //optimize down to "> 1 segments" for better performance than down to 1 - _writer.Optimize(4, doWait); - + this.CheckDisposed(); + + // optimize down to "> 1 segments" for better performance than down to 1 + this._writer.Optimize(4, doWait); + if (doWait) { - Commit(); + this.Commit(); Logger.Debug("Compacting Search Index - finished"); } @@ -431,52 +436,52 @@ public bool OptimizeSearchIndex(bool doWait) public bool HasDeletions() { - CheckDisposed(); - var searcher = GetSearcher(); + this.CheckDisposed(); + var searcher = this.GetSearcher(); return searcher.IndexReader.HasDeletions; } public int MaxDocsCount() { - CheckDisposed(); - var searcher = GetSearcher(); + this.CheckDisposed(); + var searcher = this.GetSearcher(); return searcher.IndexReader.MaxDoc; } public int SearchbleDocsCount() { - CheckDisposed(); - var searcher = GetSearcher(); + this.CheckDisposed(); + var searcher = this.GetSearcher(); return searcher.IndexReader.NumDocs(); } // works on the computer (in a web-farm) that runs under the scheduler public SearchStatistics GetSearchStatistics() { - CheckDisposed(); - var searcher = GetSearcher(); + this.CheckDisposed(); + var searcher = this.GetSearcher(); - var files = System.IO.Directory.GetFiles(IndexFolder, "*.*"); + var files = System.IO.Directory.GetFiles(this.IndexFolder, "*.*"); var size = files.Select(name => new FileInfo(name)).Select(fInfo => fInfo.Length).Sum(); - return new SearchStatistics - { - //Hack: seems that NumDocs/MaxDoc are buggy and return incorrect/swapped values - TotalActiveDocuments = searcher.IndexReader.NumDocs(), - TotalDeletedDocuments = searcher.IndexReader.NumDeletedDocs, - IndexLocation = IndexFolder, - LastModifiedOn = System.IO.Directory.GetLastWriteTimeUtc(IndexFolder), - IndexDbSize = size - }; + return new SearchStatistics + { + // Hack: seems that NumDocs/MaxDoc are buggy and return incorrect/swapped values + TotalActiveDocuments = searcher.IndexReader.NumDocs(), + TotalDeletedDocuments = searcher.IndexReader.NumDeletedDocs, + IndexLocation = this.IndexFolder, + LastModifiedOn = System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder), + IndexDbSize = size, + }; } public void Dispose() { - var status = Interlocked.CompareExchange(ref _isDisposed, DISPOSED, UNDISPOSED); + var status = Interlocked.CompareExchange(ref this._isDisposed, DISPOSED, UNDISPOSED); if (status == UNDISPOSED) { - DisposeWriter(); - DisposeReaders(); + this.DisposeWriter(); + this.DisposeReaders(); } } @@ -486,7 +491,7 @@ public Analyzer GetCustomAnalyzer() if (analyzer == null) { var customAnalyzerType = HostController.Instance.GetString("Search_CustomAnalyzer", string.Empty); - + if (!string.IsNullOrEmpty(customAnalyzerType)) { try @@ -495,8 +500,8 @@ public Analyzer GetCustomAnalyzer() analyzer = Reflection.CreateInstance(analyzerType) as Analyzer; if (analyzer == null) { - throw new ArgumentException(String.Format( - Localization.Localization.GetExceptionMessage("InvalidAnalyzerClass", "The class '{0}' cannot be created because it's invalid or is not an analyzer, will use default analyzer."), + throw new ArgumentException(string.Format( + Localization.GetExceptionMessage("InvalidAnalyzerClass", "The class '{0}' cannot be created because it's invalid or is not an analyzer, will use default analyzer."), customAnalyzerType)); } @@ -515,22 +520,22 @@ public Analyzer GetCustomAnalyzer() private void DisposeWriter(bool commit = true) { - if (_writer != null) + if (this._writer != null) { - lock (_writerLock) + lock (this._writerLock) { - if (_writer != null) + if (this._writer != null) { - _idxReader.Dispose(); - _idxReader = null; + this._idxReader.Dispose(); + this._idxReader = null; if (commit) { - _writer.Commit(); + this._writer.Commit(); } - _writer.Dispose(); - _writer = null; + this._writer.Dispose(); + this._writer = null; } } } @@ -538,43 +543,45 @@ private void DisposeWriter(bool commit = true) private void DisposeReaders() { - lock (((ICollection)_oldReaders).SyncRoot) + lock (((ICollection)this._oldReaders).SyncRoot) { - foreach (var rdr in _oldReaders) + foreach (var rdr in this._oldReaders) { rdr.Dispose(); } - _oldReaders.Clear(); - _reader = null; + + this._oldReaders.Clear(); + this._reader = null; } } - class CachedReader : IDisposable + private class CachedReader : IDisposable { - public DateTime LastUsed { get; private set; } private readonly IndexSearcher _searcher; public CachedReader(IndexSearcher searcher) { - _searcher = searcher; - UpdateLastUsed(); + this._searcher = searcher; + this.UpdateLastUsed(); } + + public DateTime LastUsed { get; private set; } public IndexSearcher GetSearcher() { - UpdateLastUsed(); - return _searcher; + this.UpdateLastUsed(); + return this._searcher; } - private void UpdateLastUsed() + public void Dispose() { - LastUsed = DateTime.Now; + this._searcher.Dispose(); + this._searcher.IndexReader.Dispose(); } - public void Dispose() + private void UpdateLastUsed() { - _searcher.Dispose(); - _searcher.IndexReader.Dispose(); + this.LastUsed = DateTime.Now; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs b/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs index 5e4f982474f..fc0fbc1964d 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs @@ -1,66 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Services.Search.Entities; - -using Lucene.Net.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Search; + /// - /// Lucene Specific Query Object to be passed into Lucene for Search + /// Lucene Specific Query Object to be passed into Lucene for Search. /// internal class LuceneQuery { + public LuceneQuery() + { + this.PageIndex = 1; + this.TitleSnippetLength = 60; + this.BodySnippetLength = 100; + this.PageSize = 10; + this.Sort = Sort.RELEVANCE; + } + /// - /// Lucene's original Query Object + /// Gets or sets lucene's original Query Object. /// public Query Query { get; set; } /// - /// Lucene's original Sort Object. Default is by Relevance + /// Gets or sets lucene's original Sort Object. Default is by Relevance. /// public Sort Sort { get; set; } /// - /// Page Index for the result, e.g. pageIndex=1 and pageSize=10 indicates first 10 hits. Default value is 1 + /// Gets or sets page Index for the result, e.g. pageIndex=1 and pageSize=10 indicates first 10 hits. Default value is 1. /// public int PageIndex { get; set; } /// - /// Page size of the search result. Default value is 10. + /// Gets or sets page size of the search result. Default value is 10. /// public int PageSize { get; set; } /// - /// Maximum length of highlighted title field in the results + /// Gets or sets maximum length of highlighted title field in the results. /// public int TitleSnippetLength { get; set; } /// - /// Maximum length of highlighted title field in the results + /// Gets or sets maximum length of highlighted title field in the results. /// - public int BodySnippetLength { get; set; } - - #region constructor - - public LuceneQuery() - { - PageIndex = 1; - TitleSnippetLength = 60; - BodySnippetLength = 100; - PageSize = 10; - Sort = Sort.RELEVANCE; - } - - #endregion + public int BodySnippetLength { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneResult.cs b/DNN Platform/Library/Services/Search/Internals/LuceneResult.cs index 03d1b5b170c..90ee36dd004 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneResult.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneResult.cs @@ -1,70 +1,64 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Services.Search.Entities; - -using Lucene.Net.Documents; -using Lucene.Net.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Documents; + using Lucene.Net.Search; + /// - /// Lucene Specific Query Result + /// Lucene Specific Query Result. /// internal class LuceneResult { /// - /// Lucene's original Document Object + /// Gets or sets lucene's original Document Object. /// public Document Document { get; set; } /// - /// Lucene's original Score. The score of this document for the query. + /// Gets or sets lucene's original Score. The score of this document for the query. /// - /// This field may not be reliable as most of the time it contains Nan. Use DisplayScore instead + /// This field may not be reliable as most of the time it contains Nan. Use DisplayScore instead. public float Score { get; set; } /// - /// Lucene's original Score in String format, e.g. 1.45678 or 0.87642. The score of this document for the query. + /// Gets or sets lucene's original Score in String format, e.g. 1.45678 or 0.87642. The score of this document for the query. /// /// This field is more reliable than the float version of Score. public string DisplayScore { get; set; } /// - /// Highlighted Title Snippet. This may be empty for synonym based search + /// Gets or sets highlighted Title Snippet. This may be empty for synonym based search. /// public string TitleSnippet { get; set; } /// - /// Highlighted Body Snippet. This may be empty for synonym based search + /// Gets or sets highlighted Body Snippet. This may be empty for synonym based search. /// public string BodySnippet { get; set; } /// - /// Highlighted Description Snippet. This may be empty for synonym based search + /// Gets or sets highlighted Description Snippet. This may be empty for synonym based search. /// public string DescriptionSnippet { get; set; } /// - /// Highlighted Tag Snippet. This may be empty for synonym based search + /// Gets or sets highlighted Tag Snippet. This may be empty for synonym based search. /// public string TagSnippet { get; set; } /// - /// Highlighted Author Snippet. This may be empty for synonym based search + /// Gets or sets highlighted Author Snippet. This may be empty for synonym based search. /// public string AuthorSnippet { get; set; } /// - /// Highlighted Content Snippet. This may be empty for synonym based search + /// Gets or sets highlighted Content Snippet. This may be empty for synonym based search. /// public string ContentSnippet { get; set; } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs b/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs index f0faeadc441..d9498b88c17 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System.Collections.Generic; + internal class LuceneResults { - public IEnumerable Results { get; set; } - public int TotalHits { get; set; } - public LuceneResults() { - Results = new List(); + this.Results = new List(); } + + public IEnumerable Results { get; set; } + + public int TotalHits { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneSearchContext.cs b/DNN Platform/Library/Services/Search/Internals/LuceneSearchContext.cs index 53f945949a2..33d6a9834c9 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneSearchContext.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneSearchContext.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Search.Entities; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using DotNetNuke.Services.Search.Entities; + internal class LuceneSearchContext { public LuceneQuery LuceneQuery { get; set; } + public SearchQuery SearchQuery { get; set; } + public SecurityCheckerDelegate SecurityCheckerDelegate { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchContentSource.cs b/DNN Platform/Library/Services/Search/Internals/SearchContentSource.cs index 17b3560824e..b21f440ac6d 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchContentSource.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchContentSource.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Services.Search.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Internals { + using System; + + using DotNetNuke.Services.Search.Entities; + [Serializable] - public class SearchContentSource: SearchType + public class SearchContentSource : SearchType { public string LocalizedName { get; set; } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchHelper.cs b/DNN Platform/Library/Services/Search/Internals/SearchHelper.cs index c723a8aa7e0..bd5869a1174 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchHelper.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchHelper.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + + using DotNetNuke.Framework; + /// - /// Internal Search Controller. This is an Internal class and should not be used outside of Core - /// + /// Internal Search Controller. This is an Internal class and should not be used outside of Core. + /// public class SearchHelper : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs index b4a587b8733..11e3c31b1a3 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs @@ -1,35 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Collections.Generic; -using System.Data.SqlTypes; -using System.Globalization; -using System.Text; -using System.Web; -using System.Web.Caching; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Entities.Controllers; -using System.IO; -using Lucene.Net.Analysis; -using Lucene.Net.Analysis.Standard; -using Lucene.Net.Util; -using Lucene.Net.Analysis.Tokenattributes; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + using System.Data.SqlTypes; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Analysis; + using Lucene.Net.Analysis.Standard; + using Lucene.Net.Analysis.Tokenattributes; + using Lucene.Net.Util; + internal class SearchHelperImpl : ISearchHelper { private const string SearchTypesCacheKey = "SearchTypes"; @@ -39,15 +35,14 @@ internal class SearchHelperImpl : ISearchHelper private const string LastIndexKeyFormat = "{0}_{1}"; private const string SearchStopWordsCacheKey = "SearchStopWords"; private const string ResourceFileRelativePathWithoutExt = "/App_GlobalResources/GlobalResources"; - private readonly IList _emptySynonums = new List(0); - - #region SearchType APIs - + private readonly IList _emptySynonums = new List(0); + public IEnumerable GetSearchTypes() { var cachArg = new CacheItemArgs(SearchTypesCacheKey, 120, CacheItemPriority.Default); - return CBO.GetCachedObject>(cachArg, - delegate + return CBO.GetCachedObject>( + cachArg, + dataArgs => { return CBO.FillCollection(DataProvider.Instance().GetAllSearchTypes()); }); @@ -55,28 +50,18 @@ public IEnumerable GetSearchTypes() public SearchType GetSearchTypeByName(string searchTypeName) { - return GetSearchTypes().Single(t => t.SearchTypeName == searchTypeName); - } - - #endregion - - #region Synonym Management APIs - - private IDictionary> GetSynonymTerms(int portalId, string cultureCode) - { - var cacheKey = string.Format("{0}_{1}_{2}", SynonymTermsCacheKey, portalId, cultureCode); - var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); - return CBO.GetCachedObject>>(cachArg, SynonymTermsCallBack); - } + return this.GetSearchTypes().Single(t => t.SearchTypeName == searchTypeName); + } public IEnumerable GetSynonyms(int portalId, string cultureCode, string term) { - var terms = GetSynonymTerms(portalId, cultureCode); + var terms = this.GetSynonymTerms(portalId, cultureCode); IList synonyms; if (terms == null || !terms.TryGetValue((term ?? string.Empty).ToLowerInvariant(), out synonyms)) { - synonyms = _emptySynonums; + synonyms = this._emptySynonums; } + return synonyms; } @@ -84,26 +69,46 @@ public IEnumerable GetSynonymsGroups(int portalId, string culture { var cacheKey = string.Format(CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); - return CBO.GetCachedObject>(cachArg, GetSynonymsGroupsCallBack); + return CBO.GetCachedObject>(cachArg, this.GetSynonymsGroupsCallBack); + } + + private IDictionary> GetSynonymTerms(int portalId, string cultureCode) + { + var cacheKey = string.Format("{0}_{1}_{2}", SynonymTermsCacheKey, portalId, cultureCode); + var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); + return CBO.GetCachedObject>>(cachArg, this.SynonymTermsCallBack); } public int AddSynonymsGroup(string synonymsTags, int portalId, string cultureCode, out string duplicateWord) { duplicateWord = null; - if (string.IsNullOrEmpty(synonymsTags)) return 0; - if (portalId < 0) return 0; - + if (string.IsNullOrEmpty(synonymsTags)) + { + return 0; + } + + if (portalId < 0) + { + return 0; + } + var userId = PortalSettings.Current.UserId; - var list = GetSynonymsGroups(portalId, cultureCode); + var list = this.GetSynonymsGroups(portalId, cultureCode); var tags = synonymsTags.ToLowerInvariant().Split(','); - if (!tags.Any()) return 0; - + if (!tags.Any()) + { + return 0; + } + foreach (var group in list) { var groupTags = group.SynonymsTags.ToLowerInvariant().Split(','); duplicateWord = tags.FirstOrDefault(groupTags.Contains); - if (!string.IsNullOrEmpty(duplicateWord)) return 0; + if (!string.IsNullOrEmpty(duplicateWord)) + { + return 0; + } } var newId = DataProvider.Instance().AddSynonymsGroup(synonymsTags, userId, portalId, cultureCode); @@ -119,22 +124,35 @@ public int AddSynonymsGroup(string synonymsTags, int portalId, string cultureCod public int UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int portalId, string cultureCode, out string duplicateWord) { duplicateWord = null; - if (synonymsGroupId <= 0) return 0; - if (string.IsNullOrEmpty(synonymsTags)) return 0; - + if (synonymsGroupId <= 0) + { + return 0; + } + + if (string.IsNullOrEmpty(synonymsTags)) + { + return 0; + } + var userId = PortalSettings.Current.UserId; - var list = GetSynonymsGroups(portalId, cultureCode); + var list = this.GetSynonymsGroups(portalId, cultureCode); var tags = synonymsTags.ToLowerInvariant().Split(','); - if (!tags.Any()) return 0; - + if (!tags.Any()) + { + return 0; + } + foreach (var group in list) { if (group.SynonymsGroupId != synonymsGroupId) { var groupTags = group.SynonymsTags.ToLowerInvariant().Split(','); duplicateWord = tags.FirstOrDefault(groupTags.Contains); - if (!string.IsNullOrEmpty(duplicateWord)) return 0; + if (!string.IsNullOrEmpty(duplicateWord)) + { + return 0; + } } } @@ -149,8 +167,11 @@ public int UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int por public void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultureCode) { - if (synonymsGroupId <= 0) return; - + if (synonymsGroupId <= 0) + { + return; + } + DataProvider.Instance().DeleteSynonymsGroup(synonymsGroupId); var cacheKey = string.Format(CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); @@ -163,19 +184,33 @@ public SearchStopWords GetSearchStopWords(int portalId, string cultureCode) { var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); - var list = CBO.GetCachedObject>(cachArg, GetSearchStopWordsCallBack); + var list = CBO.GetCachedObject>(cachArg, this.GetSearchStopWordsCallBack); return list == null ? null : list.FirstOrDefault(); } public int AddSearchStopWords(string stopWords, int portalId, string cultureCode) { - if (string.IsNullOrEmpty(stopWords)) return 0; - if (portalId < 0) return 0; - if (string.IsNullOrEmpty(cultureCode)) return 0; - + if (string.IsNullOrEmpty(stopWords)) + { + return 0; + } + + if (portalId < 0) + { + return 0; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + return 0; + } + var tags = stopWords.ToLowerInvariant().Split(','); - if (!tags.Any()) return 0; - + if (!tags.Any()) + { + return 0; + } + var userId = PortalSettings.Current.UserId; var newId = DataProvider.Instance().AddSearchStopWords(stopWords, userId, portalId, cultureCode); var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); @@ -185,14 +220,32 @@ public int AddSearchStopWords(string stopWords, int portalId, string cultureCode public int UpdateSearchStopWords(int stopWordsId, string stopWords, int portalId, string cultureCode) { - if (string.IsNullOrEmpty(stopWords)) return 0; - if (portalId < 0) return 0; - if (stopWordsId <= 0) return 0; - if (string.IsNullOrEmpty(cultureCode)) return 0; - + if (string.IsNullOrEmpty(stopWords)) + { + return 0; + } + + if (portalId < 0) + { + return 0; + } + + if (stopWordsId <= 0) + { + return 0; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + return 0; + } + var tags = stopWords.ToLowerInvariant().Split(','); - if (!tags.Any()) return 0; - + if (!tags.Any()) + { + return 0; + } + var userId = PortalSettings.Current.UserId; DataProvider.Instance().UpdateSearchStopWords(stopWordsId, stopWords, userId); var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); @@ -202,17 +255,16 @@ public int UpdateSearchStopWords(int stopWordsId, string stopWords, int portalId public void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureCode) { - if (stopWordsId <= 0) return; - + if (stopWordsId <= 0) + { + return; + } + DataProvider.Instance().DeleteSearchStopWords(stopWordsId); var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); - } - - #endregion - - #region Reindex and Compact settings management API - + } + public DateTime GetSearchReindexRequestTime(int portalId) { var requestedOn = SqlDateTime.MinValue.Value; @@ -250,7 +302,7 @@ public DateTime SetSearchReindexRequestTime(int portalId) public bool GetSearchCompactFlag() { - return "1" == HostController.Instance.GetString(Constants.SearchOptimizeFlagName, Null.NullString); + return HostController.Instance.GetString(Constants.SearchOptimizeFlagName, Null.NullString) == "1"; } public void SetSearchReindexRequestTime(bool turnOn) @@ -259,26 +311,27 @@ public void SetSearchReindexRequestTime(bool turnOn) } /// - /// Determines whether there was a request to re-index the site since a specific date/time - /// + /// Determines whether there was a request to re-index the site since a specific date/time. + /// + /// public bool IsReindexRequested(int portalId, DateTime startDate) { - var reindexDateTime = GetSearchReindexRequestTime(portalId); + var reindexDateTime = this.GetSearchReindexRequestTime(portalId); return reindexDateTime > startDate; } /// - /// Returns a collection of portal ID's to reindex if it was requested since last indexing + /// Returns a collection of portal ID's to reindex if it was requested since last indexing. /// /// /// public IEnumerable GetPortalsToReindex(DateTime startDate) { var portals2Reindex = PortalController.Instance.GetPortals().Cast() - .Where(portal => IsReindexRequested(portal.PortalID, startDate)) + .Where(portal => this.IsReindexRequested(portal.PortalID, startDate)) .Select(portal => portal.PortalID); - if (IsReindexRequested(-1, startDate)) + if (this.IsReindexRequested(-1, startDate)) { // Include Host Level portals2Reindex = portals2Reindex.Concat(new[] { -1 }); @@ -291,7 +344,8 @@ public IEnumerable GetPortalsToReindex(DateTime startDate) /// Returns the last time search indexing was completed successfully. /// The returned value in local server time (not UTC). /// Beware that the value stored in teh database is converted to UTC time. - /// + /// + /// public DateTime GetLastSuccessfulIndexingDateTime(int scheduleId) { var settings = SchedulingProvider.Instance().GetScheduleItemSettings(scheduleId); @@ -310,7 +364,10 @@ public DateTime GetLastSuccessfulIndexingDateTime(int scheduleId) { // retrieves the date as UTC but returns to caller as local lastTime = FixSqlDateTime(lastTime).ToLocalTime().ToLocalTime(); - if (lastTime > DateTime.Now) lastTime = DateTime.Now; + if (lastTime > DateTime.Now) + { + lastTime = DateTime.Now; + } } else { @@ -327,7 +384,8 @@ public DateTime GetLastSuccessfulIndexingDateTime(int scheduleId) /// public void SetLastSuccessfulIndexingDateTime(int scheduleId, DateTime startDateLocal) { - SchedulingProvider.Instance().AddScheduleItemSetting(scheduleId, + SchedulingProvider.Instance().AddScheduleItemSetting( + scheduleId, Constants.SearchLastSuccessIndexName, startDateLocal.ToUniversalTime().ToString(Constants.ReindexDateTimeFormat)); } @@ -364,27 +422,37 @@ public string GetIndexerCheckpointData(int scheduleId, string indexerKey) public void SetIndexerCheckpointData(int scheduleId, string indexerKey, string checkPointData) { SchedulingProvider.Instance().AddScheduleItemSetting(scheduleId, indexerKey, checkPointData); - } - - #endregion - - #region Other Search Helper methods - + } + public Tuple GetSearchMinMaxLength() { var hostController = HostController.Instance; var minWordLength = hostController.GetInteger(Constants.SearchMinLengthKey, Constants.DefaultMinLen); var maxWordLength = hostController.GetInteger(Constants.SearchMaxLengthKey, Constants.DefaultMaxLen); - if (minWordLength < Constants.MinimumMinLen) minWordLength = Constants.MinimumMinLen; - if (maxWordLength < Constants.MinimumMaxLen) maxWordLength = Constants.MinimumMaxLen; - - if (minWordLength > Constants.MaximumMinLen) minWordLength = Constants.MaximumMinLen; - if (maxWordLength > Constants.MaximumMaxLen) maxWordLength = Constants.MaximumMaxLen; - + if (minWordLength < Constants.MinimumMinLen) + { + minWordLength = Constants.MinimumMinLen; + } + + if (maxWordLength < Constants.MinimumMaxLen) + { + maxWordLength = Constants.MinimumMaxLen; + } + + if (minWordLength > Constants.MaximumMinLen) + { + minWordLength = Constants.MaximumMinLen; + } + + if (maxWordLength > Constants.MaximumMaxLen) + { + maxWordLength = Constants.MaximumMaxLen; + } + if (minWordLength > maxWordLength) { - var exceptionMessage = Localization.Localization.GetExceptionMessage("SearchAnalyzerMinWordLength", "Search Analyzer: min word length ({0}) is greater than max word length ({1}) value"); + var exceptionMessage = Localization.GetExceptionMessage("SearchAnalyzerMinWordLength", "Search Analyzer: min word length ({0}) is greater than max word length ({1}) value"); throw new InvalidDataException( string.Format(exceptionMessage, minWordLength, maxWordLength)); } @@ -393,23 +461,23 @@ public Tuple GetSearchMinMaxLength() } /// - /// Processes and re-phrases the search text by looking into exact-match and wildcard option + /// Processes and re-phrases the search text by looking into exact-match and wildcard option. /// /// /// - /// - /// cleaned and pre-processed search phrase - public string RephraseSearchText(string searchPhrase, bool useWildCard, bool allowLeadingWildcard = false) + /// + /// cleaned and pre-processed search phrase. + public string RephraseSearchText(string searchPhrase, bool useWildCard, bool allowLeadingWildcard = false) { - searchPhrase = CleanSearchPhrase(HttpUtility.HtmlDecode(searchPhrase)); + searchPhrase = this.CleanSearchPhrase(HttpUtility.HtmlDecode(searchPhrase)); if (!useWildCard && !searchPhrase.Contains("\"")) { return searchPhrase; } - + // we have a quotation marks and/or wildcard search, adjust accordingly - var chars = FoldToASCII(searchPhrase).ToCharArray(); + var chars = this.FoldToASCII(searchPhrase).ToCharArray(); var insideQuote = false; var newPhraseBulder = new StringBuilder(); var currentWord = new StringBuilder(); @@ -426,14 +494,16 @@ public string RephraseSearchText(string searchPhrase, bool useWildCard, bool all newPhraseBulder.Append(currentWord + " "); currentWord.Clear(); } + break; case ' ': if (!insideQuote && useWildCard) { // end of a word; we need to append a wild card to search when needed - newPhraseBulder.Append(FixLastWord(currentWord.ToString().Trim(), allowLeadingWildcard) + " "); + newPhraseBulder.Append(this.FixLastWord(currentWord.ToString().Trim(), allowLeadingWildcard) + " "); currentWord.Clear(); } + break; } } @@ -446,7 +516,7 @@ public string RephraseSearchText(string searchPhrase, bool useWildCard, bool all } else if (useWildCard) { - newPhraseBulder.Append(FixLastWord(currentWord.ToString().Trim(), allowLeadingWildcard)); + newPhraseBulder.Append(this.FixLastWord(currentWord.ToString().Trim(), allowLeadingWildcard)); } else { @@ -458,33 +528,36 @@ public string RephraseSearchText(string searchPhrase, bool useWildCard, bool all public string StripTagsNoAttributes(string html, bool retainSpace) { - var strippedString = !String.IsNullOrEmpty(html) ? HtmlUtils.StripTags(html, retainSpace) : html; + var strippedString = !string.IsNullOrEmpty(html) ? HtmlUtils.StripTags(html, retainSpace) : html; // Encode and Strip again - strippedString = !String.IsNullOrEmpty(strippedString) ? HtmlUtils.StripTags(html, retainSpace) : html; + strippedString = !string.IsNullOrEmpty(strippedString) ? HtmlUtils.StripTags(html, retainSpace) : html; return strippedString; - } - - #endregion - - #region private methods - + } + private static DateTime FixSqlDateTime(DateTime datim) { - if (datim <= SqlDateTime.MinValue.Value) - datim = SqlDateTime.MinValue.Value.AddDays(1); - else if (datim >= SqlDateTime.MaxValue.Value) - datim = SqlDateTime.MaxValue.Value.AddDays(-1); + if (datim <= SqlDateTime.MinValue.Value) + { + datim = SqlDateTime.MinValue.Value.AddDays(1); + } + else if (datim >= SqlDateTime.MaxValue.Value) + { + datim = SqlDateTime.MaxValue.Value.AddDays(-1); + } + return datim; } - private string FixLastWord(string lastWord, bool allowLeadingWildcard) + private string FixLastWord(string lastWord, bool allowLeadingWildcard) { - if (string.IsNullOrEmpty(lastWord)) - return string.Empty; - - if (lastWord.IndexOfAny(new[] {'~', '*'}) < 0) + if (string.IsNullOrEmpty(lastWord)) + { + return string.Empty; + } + + if (lastWord.IndexOfAny(new[] { '~', '*' }) < 0) { var beginIsGroup = false; var endIsGroup = false; @@ -514,13 +587,21 @@ private string FixLastWord(string lastWord, bool allowLeadingWildcard) if (lastWord.Length > 0 && lastWord != "AND" && lastWord != "OR") { lastWord = (beginIsGroup && endIsGroup) - ? string.Format("{0} OR {1}{0}*", lastWord, allowLeadingWildcard ? "*" : string.Empty) - : string.Format("({0} OR {1}{0}*)", lastWord, allowLeadingWildcard ? "*" : string.Empty); + ? string.Format("{0} OR {1}{0}*", lastWord, allowLeadingWildcard ? "*" : string.Empty) + : string.Format("({0} OR {1}{0}*)", lastWord, allowLeadingWildcard ? "*" : string.Empty); } - if (beginIsGroup) lastWord = c1 + lastWord; - if (endIsGroup) lastWord += c2; + if (beginIsGroup) + { + lastWord = c1 + lastWord; + } + + if (endIsGroup) + { + lastWord += c2; + } } + return lastWord; } @@ -570,7 +651,7 @@ private string CleanSearchPhrase(string searchPhrase) if (hasExactMatch) { // remove empty double quotes - cleaned = cleaned.Replace("\"\"", "").Replace("\" \"", ""); + cleaned = cleaned.Replace("\"\"", string.Empty).Replace("\" \"", string.Empty); } return cleaned; @@ -582,27 +663,35 @@ private object SynonymTermsCallBack(CacheItemArgs cacheItem) var allTerms = new Dictionary>(); var portalId = int.Parse(parts[1]); var cultureCode = parts[2]; - var groups = GetSynonymsGroups(portalId, cultureCode); - if (groups == null) return allTerms; - + var groups = this.GetSynonymsGroups(portalId, cultureCode); + if (groups == null) + { + return allTerms; + } + foreach (var synonymsGroup in groups) { var terms = new Dictionary>(); var groupTags = synonymsGroup.SynonymsTags.ToLowerInvariant().Split(','); - //add the first key first + + // add the first key first foreach (var tag in groupTags) { - if (!terms.ContainsKey(tag)) - terms.Add(tag, new List()); + if (!terms.ContainsKey(tag)) + { + terms.Add(tag, new List()); + } } - //add synonyms + // add synonyms foreach (var term in terms) { foreach (var syn in terms) { - if (term.Key != syn.Key) - term.Value.Add(syn.Key); + if (term.Key != syn.Key) + { + term.Value.Add(syn.Key); + } } } @@ -621,8 +710,8 @@ private object GetSearchStopWordsCallBack(CacheItemArgs cacheItem) var portalId = int.Parse(splittedKeys[1]); var cultureCode = splittedKeys[2]; - EnsurePortalDefaultsAreSet(portalId); - + this.EnsurePortalDefaultsAreSet(portalId); + return CBO.FillCollection(DataProvider.Instance().GetSearchStopWords(portalId, cultureCode)); } @@ -630,33 +719,46 @@ private void EnsurePortalDefaultsAreSet(int portalId) { const string setting = "SearchAdminInitialization"; - //check portal settings first - if (PortalController.GetPortalSetting(setting, portalId, "false") != "false") return; - - //Portal may not be present, especially during installation - if (PortalController.Instance.GetPortal(portalId) == null) return; - + // check portal settings first + if (PortalController.GetPortalSetting(setting, portalId, "false") != "false") + { + return; + } + + // Portal may not be present, especially during installation + if (PortalController.Instance.GetPortal(portalId) == null) + { + return; + } + foreach (var locale in LocaleController.Instance.GetLocales(portalId).Values) { - var resourceFile = GetResourceFile(locale.Code); + var resourceFile = this.GetResourceFile(locale.Code); - var currentStopWords = CBO.FillCollection(DataProvider.Instance().GetSearchStopWords(portalId, locale.Code)); + var currentStopWords = CBO.FillCollection(DataProvider.Instance().GetSearchStopWords(portalId, locale.Code)); if (currentStopWords == null || currentStopWords.Count == 0) { - //Add Default StopWord - var defaultStopWords = Localization.Localization.GetString("DefaultStopwordGroup", resourceFile); - if (!string.IsNullOrEmpty(defaultStopWords)) DataProvider.Instance().AddSearchStopWords(defaultStopWords, 1, portalId, locale.Code); + // Add Default StopWord + var defaultStopWords = Localization.GetString("DefaultStopwordGroup", resourceFile); + if (!string.IsNullOrEmpty(defaultStopWords)) + { + DataProvider.Instance().AddSearchStopWords(defaultStopWords, 1, portalId, locale.Code); + } } var currentSynonymGroups = CBO.FillCollection(DataProvider.Instance().GetAllSynonymsGroups(portalId, locale.Code)); if (currentSynonymGroups == null || currentSynonymGroups.Count == 0) { - //Add Default Synonym - var defaultSynonymsGroup = Localization.Localization.GetString("DefaultSynonymGroup", resourceFile); - if (!string.IsNullOrEmpty(defaultSynonymsGroup)) DataProvider.Instance().AddSynonymsGroup(defaultSynonymsGroup, 1, portalId, locale.Code); + // Add Default Synonym + var defaultSynonymsGroup = Localization.GetString("DefaultSynonymGroup", resourceFile); + if (!string.IsNullOrEmpty(defaultSynonymsGroup)) + { + DataProvider.Instance().AddSynonymsGroup(defaultSynonymsGroup, 1, portalId, locale.Code); + } } } - //Update Portal Settings + + // Update Portal Settings PortalController.UpdatePortalSetting(portalId, setting, "true", true); } @@ -672,32 +774,30 @@ private object GetSynonymsGroupsCallBack(CacheItemArgs cacheItem) var portalId = int.Parse(cacheItem.CacheKey.Split('_')[1]); var cultureCode = cacheItem.CacheKey.Split('_')[2]; - EnsurePortalDefaultsAreSet(portalId); + this.EnsurePortalDefaultsAreSet(portalId); return CBO.FillCollection(DataProvider.Instance().GetAllSynonymsGroups(portalId, cultureCode)); } - + private string FoldToASCII(string searchPhrase) { var sb = new StringBuilder(); var cleanedPhrase = searchPhrase.Trim('\0'); - + var asciiFilter = new ASCIIFoldingFilter(new WhitespaceTokenizer((TextReader)new StringReader(cleanedPhrase))); string space = string.Empty; - while(asciiFilter.IncrementToken()) + while (asciiFilter.IncrementToken()) { - sb.AppendFormat("{0}{1}", space ?? "", asciiFilter.GetAttribute().Term); + sb.AppendFormat("{0}{1}", space ?? string.Empty, asciiFilter.GetAttribute().Term); if (string.IsNullOrEmpty(space)) { space = " "; } } + return sb.ToString(); - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs b/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs index bf92f3b9e73..c6460c379b2 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs @@ -1,23 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; - -using DotNetNuke.Entities.Controllers; - -using Lucene.Net.Analysis; -using Lucene.Net.Analysis.Standard; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.IO; + + using DotNetNuke.Entities.Controllers; + using Lucene.Net.Analysis; + using Lucene.Net.Analysis.Standard; + /// - /// This is responsible for the filters chain that analyzes search documents/queries + /// This is responsible for the filters chain that analyzes search documents/queries. /// internal class SearchQueryAnalyzer : Analyzer { @@ -25,29 +19,28 @@ internal class SearchQueryAnalyzer : Analyzer public SearchQueryAnalyzer(bool useStemmingFilter) { - _useStemmingFilter = useStemmingFilter; + this._useStemmingFilter = useStemmingFilter; } public override TokenStream TokenStream(string fieldName, TextReader reader) { var wordLengthMinMax = SearchHelper.Instance.GetSearchMinMaxLength(); - //Note: the order of filtering is important for both operation and performane, so we try to make it work faster + // Note: the order of filtering is important for both operation and performane, so we try to make it work faster // Also, note that filters are applied from the innermost outwards. var filter = - new ASCIIFoldingFilter( // accents filter + new ASCIIFoldingFilter(// accents filter new LowerCaseFilter( new LengthFilter( new StandardFilter( - new StandardTokenizer(Constants.LuceneVersion, reader) - ) - , wordLengthMinMax.Item1, wordLengthMinMax.Item2) - ) - ); - - if (!_useStemmingFilter) - return filter; - + new StandardTokenizer(Constants.LuceneVersion, reader)), + wordLengthMinMax.Item1, wordLengthMinMax.Item2))); + + if (!this._useStemmingFilter) + { + return filter; + } + return new PorterStemFilter(filter); } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs b/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs index c7f589cec70..acbb5225a7d 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs @@ -1,40 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Framework; + /// - /// Class responsible to parse the Search Query String parameter + /// Class responsible to parse the Search Query String parameter. /// public class SearchQueryStringParser - : ServiceLocator - , ISearchQueryStringParser + : ServiceLocator, + ISearchQueryStringParser { - protected override Func GetFactory() - { - return () => new SearchQueryStringParser(); - } - private static readonly Regex TagRegex = new Regex(@"\[(.*?)\]", RegexOptions.Compiled); private static readonly Regex DateRegex = new Regex(@"after:(\w+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex TypeRegex = new Regex(@"type:([^,]+(,[^,]+)*)", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + protected override Func GetFactory() + { + return () => new SearchQueryStringParser(); + } /// - /// Gets the list of tags parsing the search keywords + /// Gets the list of tags parsing the search keywords. /// - /// search keywords - /// output keywords removing the tags - /// List of tags + /// search keywords. + /// output keywords removing the tags. + /// List of tags. public IList GetTags(string keywords, out string outputKeywords) { var tags = new List(); @@ -52,24 +53,26 @@ public IList GetTags(string keywords, out string outputKeywords) { tags.Add(HttpUtility.HtmlEncode(tag.Trim())); } + m = m.NextMatch(); } outputKeywords = TagRegex.Replace(keywords, string.Empty).Trim(); } + return tags; } /// - /// Gets the Last Modified Date parsing the search keywords + /// Gets the Last Modified Date parsing the search keywords. /// - /// search keywords - /// output keywords removing the last modified date - /// Last Modified Date + /// search keywords. + /// output keywords removing the last modified date. + /// Last Modified Date. public DateTime GetLastModifiedDate(string keywords, out string outputKeywords) { var m = DateRegex.Match(keywords); - var date = ""; + var date = string.Empty; while (m.Success && string.IsNullOrEmpty(date)) { date = m.Groups[1].ToString(); @@ -103,15 +106,15 @@ public DateTime GetLastModifiedDate(string keywords, out string outputKeywords) } /// - /// Gets the list of Search Types parsing the search keywords + /// Gets the list of Search Types parsing the search keywords. /// - /// search keywords - /// output keywords removing the Search Type - /// List of Search Types + /// search keywords. + /// output keywords removing the Search Type. + /// List of Search Types. public IList GetSearchTypeList(string keywords, out string outputKeywords) { var m = TypeRegex.Match(keywords); - var types = ""; + var types = string.Empty; while (m.Success && string.IsNullOrEmpty(types)) { types = m.Groups[1].ToString().Trim(); diff --git a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs index fbebadfc81d..d832daa15c3 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using DotNetNuke.Services.Search.Entities; -using Lucene.Net.Documents; -using Lucene.Net.Index; -using Lucene.Net.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Documents; + using Lucene.Net.Index; + using Lucene.Net.Search; + internal delegate bool SecurityCheckerDelegate(Document luceneResult, SearchQuery searchQuery); internal class SearchSecurityTrimmer : Collector @@ -25,7 +21,8 @@ internal class SearchSecurityTrimmer : Collector private readonly IndexSearcher _searcher; private Scorer _scorer; - private int _docBase, _totalHits; + private int _docBase; + private int _totalHits; private readonly LuceneQuery _luceneQuery; private readonly SearchQuery _searchQuery; private readonly List _hitDocs; @@ -33,62 +30,79 @@ internal class SearchSecurityTrimmer : Collector public SearchSecurityTrimmer(SearchSecurityTrimmerContext searchContext) { - _securityChecker = searchContext.SecurityChecker; - _searcher = searchContext.Searcher; - _luceneQuery = searchContext.LuceneQuery; - _searchQuery = searchContext.SearchQuery; - _hitDocs = new List(16); + this._securityChecker = searchContext.SecurityChecker; + this._searcher = searchContext.Searcher; + this._luceneQuery = searchContext.LuceneQuery; + this._searchQuery = searchContext.SearchQuery; + this._hitDocs = new List(16); } - public override bool AcceptsDocsOutOfOrder { get { return false; } } + public override bool AcceptsDocsOutOfOrder + { + get { return false; } + } - public override void SetNextReader(IndexReader reader, int docBase) + public int TotalHits { - _docBase = docBase; + get + { + if (this._scoreDocs == null) + { + this.PrepareScoreDocs(); + } + + return this._totalHits; + } } - public override void SetScorer(Scorer scorer) + public List ScoreDocs { - _scorer = scorer; + get + { + if (this._scoreDocs == null) + { + this.PrepareScoreDocs(); + } + + return this._scoreDocs; + } } - public override void Collect(int doc) + public override void SetNextReader(IndexReader reader, int docBase) { - _hitDocs.Add(new ScoreDoc(doc + _docBase, _scorer.Score())); + this._docBase = docBase; } - public int TotalHits + public override void SetScorer(Scorer scorer) { - get - { - if (_scoreDocs == null) PrepareScoreDocs(); - return _totalHits; - } + this._scorer = scorer; } - public List ScoreDocs + public override void Collect(int doc) { - get - { - if (_scoreDocs == null) PrepareScoreDocs(); - return _scoreDocs; - } + this._hitDocs.Add(new ScoreDoc(doc + this._docBase, this._scorer.Score())); } private string GetStringFromField(Document doc, SortField sortField) { var field = doc.GetField(sortField.Field); - return field == null ? "" : field.StringValue; + return field == null ? string.Empty : field.StringValue; } private long GetLongFromField(Document doc, SortField sortField) { var field = doc.GetField(sortField.Field); - if (field == null) return 0; - + if (field == null) + { + return 0; + } + long data; - if (long.TryParse(field.StringValue, out data) && data >= 0) return data; - + if (long.TryParse(field.StringValue, out data) && data >= 0) + { + return data; + } + return 0; } @@ -96,20 +110,20 @@ private void PrepareScoreDocs() { int skippedSoFar; var collectedSoFar = skippedSoFar = 0; - var pageSize = _luceneQuery.PageSize; - var toSkip = _luceneQuery.PageIndex <= 1 ? 0 : ((_luceneQuery.PageIndex - 1) * pageSize); + var pageSize = this._luceneQuery.PageSize; + var toSkip = this._luceneQuery.PageIndex <= 1 ? 0 : ((this._luceneQuery.PageIndex - 1) * pageSize); IEnumerable tempDocs = new List(); - _totalHits = _hitDocs.Count; + this._totalHits = this._hitDocs.Count; var useRelevance = false; - if (ReferenceEquals(Sort.RELEVANCE, _luceneQuery.Sort)) + if (ReferenceEquals(Sort.RELEVANCE, this._luceneQuery.Sort)) { useRelevance = true; } else { - var fields = _luceneQuery.Sort.GetSort(); + var fields = this._luceneQuery.Sort.GetSort(); if (fields == null || fields.Count() != 1) { useRelevance = true; @@ -119,42 +133,52 @@ private void PrepareScoreDocs() var field = fields[0]; if (field.Type == SortField.INT || field.Type == SortField.LONG) { - if(field.Reverse) - tempDocs = _hitDocs.Select(d => new { SDoc = d, Document = _searcher.Doc(d.Doc) }) - .OrderByDescending(rec => GetLongFromField(rec.Document, field)) + if (field.Reverse) + { + tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) + .OrderByDescending(rec => this.GetLongFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); - else - tempDocs = _hitDocs.Select(d => new { SDoc = d, Document = _searcher.Doc(d.Doc) }) - .OrderBy(rec => GetLongFromField(rec.Document, field)) + .Select(rec => rec.SDoc); + } + else + { + tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) + .OrderBy(rec => this.GetLongFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); + .Select(rec => rec.SDoc); + } } else { - if (field.Reverse) - tempDocs = _hitDocs.Select(d => new {SDoc = d, Document = _searcher.Doc(d.Doc)}) - .OrderByDescending(rec => GetStringFromField(rec.Document, field)) + if (field.Reverse) + { + tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) + .OrderByDescending(rec => this.GetStringFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); - else - tempDocs = _hitDocs.Select(d => new { SDoc = d, Document = _searcher.Doc(d.Doc) }) - .OrderBy(rec => GetStringFromField(rec.Document, field)) + .Select(rec => rec.SDoc); + } + else + { + tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) + .OrderBy(rec => this.GetStringFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); + .Select(rec => rec.SDoc); + } } } } - if (useRelevance) - tempDocs = _hitDocs.OrderByDescending(d => d.Score).ThenBy(d => d.Doc); - + if (useRelevance) + { + tempDocs = this._hitDocs.OrderByDescending(d => d.Score).ThenBy(d => d.Doc); + } + var scoreDocSize = Math.Min(tempDocs.Count(), pageSize); - _scoreDocs = new List(scoreDocSize); + this._scoreDocs = new List(scoreDocSize); - foreach (var scoreDoc in tempDocs) + foreach (var scoreDoc in tempDocs) { - if (_securityChecker == null || _securityChecker(_searcher.Doc(scoreDoc.Doc), _searchQuery)) + if (this._securityChecker == null || this._securityChecker(this._searcher.Doc(scoreDoc.Doc), this._searchQuery)) { if (skippedSoFar < toSkip) { @@ -167,12 +191,12 @@ private void PrepareScoreDocs() continue; } - _scoreDocs.Add(scoreDoc); + this._scoreDocs.Add(scoreDoc); ++collectedSoFar; } else { - _totalHits--; + this._totalHits--; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmerContext.cs b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmerContext.cs index 8fa977d3818..8eeeeda8b66 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmerContext.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmerContext.cs @@ -1,17 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Search.Entities; -using Lucene.Net.Search; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Search; + internal class SearchSecurityTrimmerContext { public IndexSearcher Searcher { get; set; } + public SecurityCheckerDelegate SecurityChecker { get; set; } + public LuceneQuery LuceneQuery { get; set; } + public SearchQuery SearchQuery { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs b/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs index ff2711f5392..5fcb5f47ac2 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs @@ -1,20 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search.Internals { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + public class SearchStatistics { public int TotalActiveDocuments { get; set; } + public int TotalDeletedDocuments { get; set; } + public string IndexLocation { get; set; } + public DateTime LastModifiedOn { get; set; } + public long IndexDbSize { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs b/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs index 3aae4da2ac3..4c76d45eb5c 100644 --- a/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs +++ b/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs @@ -1,25 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Search.Entities; -using Lucene.Net.Analysis; -using Lucene.Net.Analysis.Standard; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Threading; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Analysis; + using Lucene.Net.Analysis.Standard; + /// - /// This is responsible for the filters chain that analyzes search documents/queries + /// This is responsible for the filters chain that analyzes search documents/queries. /// internal class SynonymAnalyzer : Analyzer { @@ -28,26 +24,22 @@ public override TokenStream TokenStream(string fieldName, TextReader reader) var stops = GetStopWords(); var wordLengthMinMax = SearchHelper.Instance.GetSearchMinMaxLength(); - //Note: the order of filtering is important for both operation and performane, so we try to make it work faster + // Note: the order of filtering is important for both operation and performane, so we try to make it work faster // Also, note that filters are applied from the innermost outwards. // According to Lucene's documentaiton the StopFilter performs a case-sensitive lookup of each token in a set of stop // words. It relies on being fed already lowercased tokens. Therefore, DO NOT reverse the order of these filters. return - new PorterStemFilter( // stemming filter - new ASCIIFoldingFilter( // accents filter + new PorterStemFilter(// stemming filter + new ASCIIFoldingFilter(// accents filter new SynonymFilter( - new StopFilter(true, + new StopFilter( + true, new LowerCaseFilter( new LengthFilter( new StandardFilter( - new StandardTokenizer(Constants.LuceneVersion, reader) - ) - , wordLengthMinMax.Item1, wordLengthMinMax.Item2) - ) - , stops) - ) - ) - ) + new StandardTokenizer(Constants.LuceneVersion, reader)), + wordLengthMinMax.Item1, wordLengthMinMax.Item2)), + stops)))) ; } @@ -69,8 +61,10 @@ private static ISet GetStopWords() if (string.IsNullOrEmpty(cultureCode)) { var portalInfo = PortalController.Instance.GetPortal(portalId); - if (portalInfo != null) - cultureCode = portalInfo.DefaultLanguage; + if (portalInfo != null) + { + cultureCode = portalInfo.DefaultLanguage; + } } } @@ -79,7 +73,7 @@ private static ISet GetStopWords() if (searchStopWords != null && !string.IsNullOrEmpty(searchStopWords.StopWords)) { - //TODO Use cache from InternalSearchController + // TODO Use cache from InternalSearchController var cultureInfo = new CultureInfo(cultureCode ?? "en-US"); var strArray = searchStopWords.StopWords.Split(',').Select(s => s.ToLower(cultureInfo)).ToArray(); var set = new CharArraySet(strArray.Length, false); diff --git a/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs b/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs index 6d1339b5e67..bd64fd2b398 100644 --- a/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs +++ b/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs @@ -1,27 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Search.Entities; - -using Lucene.Net.Analysis; -using Lucene.Net.Analysis.Tokenattributes; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search.Internals { + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Threading; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Search.Entities; + using Lucene.Net.Analysis; + using Lucene.Net.Analysis.Tokenattributes; + /// - /// SynonymFilter + /// SynonymFilter. /// - /// Implementation is inspired by sample code in Manning Lucene In Action 2nd Edition, pg. 133 + /// Implementation is inspired by sample code in Manning Lucene In Action 2nd Edition, pg. 133. internal sealed class SynonymFilter : TokenFilter { private readonly Stack _synonymStack = new Stack(); @@ -29,34 +24,37 @@ internal sealed class SynonymFilter : TokenFilter private readonly TermAttribute _termAtt; private readonly PositionIncrementAttribute _posIncrAtt; - public SynonymFilter(TokenStream input) : base(input) + public SynonymFilter(TokenStream input) + : base(input) { - _termAtt = (TermAttribute) AddAttribute(); - _posIncrAtt = (PositionIncrementAttribute)AddAttribute(); + this._termAtt = (TermAttribute)this.AddAttribute(); + this._posIncrAtt = (PositionIncrementAttribute)this.AddAttribute(); } public override bool IncrementToken() { - //Pop buffered synonyms - if (_synonymStack.Count > 0) + // Pop buffered synonyms + if (this._synonymStack.Count > 0) { - var syn = _synonymStack.Pop(); - RestoreState(_current); - _termAtt.SetTermBuffer(syn); + var syn = this._synonymStack.Pop(); + this.RestoreState(this._current); + this._termAtt.SetTermBuffer(syn); - //set position increment to 0 - _posIncrAtt.PositionIncrement = 0; + // set position increment to 0 + this._posIncrAtt.PositionIncrement = 0; return true; } - //read next token - if (!input.IncrementToken()) - return false; - - //push synonyms onto stack - if (AddAliasesToStack()) + // read next token + if (!this.input.IncrementToken()) + { + return false; + } + + // push synonyms onto stack + if (this.AddAliasesToStack()) { - _current = CaptureState(); //save current token + this._current = this.CaptureState(); // save current token } return true; @@ -64,7 +62,7 @@ public override bool IncrementToken() private bool AddAliasesToStack() { - var portalId = 0; //default + var portalId = 0; // default string cultureCode; var searchDoc = Thread.GetData(Thread.GetNamedDataSlot(Constants.TlsSearchInfo)) as SearchDocument; if (searchDoc != null) @@ -74,22 +72,29 @@ private bool AddAliasesToStack() if (string.IsNullOrEmpty(cultureCode)) { var portalInfo = PortalController.Instance.GetPortal(portalId); - if (portalInfo != null) - cultureCode = portalInfo.DefaultLanguage; + if (portalInfo != null) + { + cultureCode = portalInfo.DefaultLanguage; + } } } else { cultureCode = Thread.CurrentThread.CurrentCulture.Name; } - var synonyms = SearchHelper.Instance.GetSynonyms(portalId, cultureCode, _termAtt.Term).ToArray(); - if (!synonyms.Any()) return false; - + + var synonyms = SearchHelper.Instance.GetSynonyms(portalId, cultureCode, this._termAtt.Term).ToArray(); + if (!synonyms.Any()) + { + return false; + } + var cultureInfo = new CultureInfo(cultureCode); foreach (var synonym in synonyms) { - _synonymStack.Push(synonym.ToLower(cultureInfo)); + this._synonymStack.Push(synonym.ToLower(cultureInfo)); } + return true; } } diff --git a/DNN Platform/Library/Services/Search/ModuleIndexInfo.cs b/DNN Platform/Library/Services/Search/ModuleIndexInfo.cs index 6fd2ea35630..f573d53a513 100644 --- a/DNN Platform/Library/Services/Search/ModuleIndexInfo.cs +++ b/DNN Platform/Library/Services/Search/ModuleIndexInfo.cs @@ -1,23 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { - internal class ModuleIndexInfo - { - public ModuleInfo ModuleInfo { get; set; } + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Entities.Modules; + + internal class ModuleIndexInfo + { + public ModuleInfo ModuleInfo { get; set; } - public bool SupportSearch { get; set; } - } + public bool SupportSearch { get; set; } + } } diff --git a/DNN Platform/Library/Services/Search/ModuleIndexer.cs b/DNN Platform/Library/Services/Search/ModuleIndexer.cs index e3b3b88d3d3..0fff6a693bb 100644 --- a/DNN Platform/Library/Services/Search/ModuleIndexer.cs +++ b/DNN Platform/Library/Services/Search/ModuleIndexer.cs @@ -1,29 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data.SqlTypes; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data.SqlTypes; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.Index @@ -31,72 +29,64 @@ namespace DotNetNuke.Services.Search /// ----------------------------------------------------------------------------- /// /// The ModuleIndexer is an implementation of the abstract IndexingProvider - /// class + /// class. /// /// /// /// ----------------------------------------------------------------------------- - public class ModuleIndexer : IndexingProvider - { - #region Private Fields - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ModuleIndexer)); + public class ModuleIndexer : IndexingProviderBase + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleIndexer)); private static readonly int ModuleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - private readonly IDictionary> _searchModules; - - #endregion - - #region Constructors - - public ModuleIndexer() : this(false) - { - } - - public ModuleIndexer(bool needSearchModules) - { - _searchModules = new Dictionary>(); - - if (needSearchModules) - { - var portals = PortalController.Instance.GetPortals(); - foreach (var portal in portals.Cast()) - { - _searchModules.Add(portal.PortalID, GetModulesForIndex(portal.PortalID)); - } - - _searchModules.Add(Null.NullInteger, GetModulesForIndex(Null.NullInteger)); - } - } + private readonly IDictionary> _searchModules; + + public ModuleIndexer() + : this(false) + { + } - #endregion + public ModuleIndexer(bool needSearchModules) + { + this._searchModules = new Dictionary>(); - #region Public Methods + if (needSearchModules) + { + var portals = PortalController.Instance.GetPortals(); + foreach (var portal in portals.Cast()) + { + this._searchModules.Add(portal.PortalID, this.GetModulesForIndex(portal.PortalID)); + } - /// ----------------------------------------------------------------------------- + this._searchModules.Add(Null.NullInteger, this.GetModulesForIndex(Null.NullInteger)); + } + } + + /// ----------------------------------------------------------------------------- /// /// Returns the number of indexed SearchDocuments for the portal. /// /// This replaces "GetSearchIndexItems" as a newer implementation of search. /// /// ----------------------------------------------------------------------------- - public override int IndexSearchDocuments(int portalId, + public override int IndexSearchDocuments( + int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer) { Requires.NotNull("indexer", indexer); const int saveThreshold = 1024 * 2; var totalIndexed = 0; - startDateLocal = GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal); + startDateLocal = this.GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal); var searchDocuments = new List(); - var searchModuleCollection = _searchModules.ContainsKey(portalId) - ? _searchModules[portalId].Where(m => m.SupportSearch).Select(m => m.ModuleInfo) - : GetSearchModules(portalId); + var searchModuleCollection = this._searchModules.ContainsKey(portalId) + ? this._searchModules[portalId].Where(m => m.SupportSearch).Select(m => m.ModuleInfo) + : this.GetSearchModules(portalId); - //Some modules update LastContentModifiedOnDate (e.g. Html module) when their content changes. - //We won't be calling into such modules if LastContentModifiedOnDate is prior to startDate. - //LastContentModifiedOnDate remains MinValue for modules that don't update this property + // Some modules update LastContentModifiedOnDate (e.g. Html module) when their content changes. + // We won't be calling into such modules if LastContentModifiedOnDate is prior to startDate. + // LastContentModifiedOnDate remains MinValue for modules that don't update this property var modulesInDateRange = searchModuleCollection.Where(module => - !((SqlDateTime.MinValue.Value < module.LastContentModifiedOnDate && module.LastContentModifiedOnDate < startDateLocal))) + !(SqlDateTime.MinValue.Value < module.LastContentModifiedOnDate && module.LastContentModifiedOnDate < startDateLocal)) .OrderBy(m => m.LastContentModifiedOnDate).ThenBy(m => m.ModuleID).ToArray(); if (modulesInDateRange.Any()) @@ -106,7 +96,7 @@ public override int IndexSearchDocuments(int portalId, try { var controller = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); - var contentInfo = new SearchContentModuleInfo {ModSearchBaseControllerType= (ModuleSearchBase) controller, ModInfo = module}; + var contentInfo = new SearchContentModuleInfo { ModSearchBaseControllerType = (ModuleSearchBase)controller, ModInfo = module }; var searchItems = contentInfo.ModSearchBaseControllerType.GetModifiedSearchDocuments(module, startDateLocal.ToUniversalTime()); if (searchItems != null && searchItems.Count > 0) @@ -116,13 +106,14 @@ public override int IndexSearchDocuments(int portalId, if (Logger.IsTraceEnabled) { - Logger.TraceFormat("ModuleIndexer: {0} search documents found for module [{1} mid:{2}]", + Logger.TraceFormat( + "ModuleIndexer: {0} search documents found for module [{1} mid:{2}]", searchItems.Count, module.DesktopModule.ModuleName, module.ModuleID); } if (searchDocuments.Count >= saveThreshold) { - totalIndexed += IndexCollectedDocs(indexer, searchDocuments, portalId, schedule); + totalIndexed += this.IndexCollectedDocs(indexer, searchDocuments, portalId, schedule); searchDocuments.Clear(); } } @@ -135,40 +126,13 @@ public override int IndexSearchDocuments(int portalId, if (searchDocuments.Count > 0) { - totalIndexed += IndexCollectedDocs(indexer, searchDocuments, portalId, schedule); + totalIndexed += this.IndexCollectedDocs(indexer, searchDocuments, portalId, schedule); } } return totalIndexed; } - private static void AddModuleMetaData(IEnumerable searchItems, ModuleInfo module) - { - foreach (var searchItem in searchItems) - { - searchItem.ModuleDefId = module.ModuleDefID; - searchItem.ModuleId = module.ModuleID; - if (string.IsNullOrEmpty(searchItem.CultureCode)) - { - searchItem.CultureCode = module.CultureCode; - } - - if (Null.IsNull(searchItem.ModifiedTimeUtc)) - { - searchItem.ModifiedTimeUtc = module.LastContentModifiedOnDate.ToUniversalTime(); - } - } - } - - private int IndexCollectedDocs( - Action> indexer, ICollection searchDocuments, int portalId, ScheduleHistoryItem schedule) - { - indexer.Invoke(searchDocuments); - var total = searchDocuments.Count; - SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, schedule.StartDate); - return total; - } - /// ----------------------------------------------------------------------------- /// /// Returns a collection of SearchDocuments containing module metadata (title, header, footer...) of Searchable Modules. @@ -180,8 +144,8 @@ private int IndexCollectedDocs( public List GetModuleMetaData(int portalId, DateTime startDate) { var searchDocuments = new List(); - var searchModuleCollection = _searchModules.ContainsKey(portalId) ? - _searchModules[portalId].Select(m => m.ModuleInfo) : GetSearchModules(portalId, true); + var searchModuleCollection = this._searchModules.ContainsKey(portalId) ? + this._searchModules[portalId].Select(m => m.ModuleInfo) : this.GetSearchModules(portalId, true); foreach (ModuleInfo module in searchModuleCollection) { try @@ -198,7 +162,7 @@ public List GetModuleMetaData(int portalId, DateTime startDate) PortalId = portalId, CultureCode = module.CultureCode, ModifiedTimeUtc = module.LastModifiedOnDate.ToUniversalTime(), - Body = module.Header + " " + module.Footer + Body = module.Header + " " + module.Footer, }; if (module.Terms != null && module.Terms.Count > 0) @@ -218,18 +182,18 @@ public List GetModuleMetaData(int portalId, DateTime startDate) } return searchDocuments; - } - + } + /// ----------------------------------------------------------------------------- /// /// Converts a SearchItemInfo into a SearchDocument. - /// + /// /// SearchItemInfo object was used in the old version of search. /// /// /// /// ----------------------------------------------------------------------------- - #pragma warning disable 0618 +#pragma warning disable 0618 public SearchDocument ConvertSearchItemInfoToSearchDocument(SearchItemInfo searchItem) { var module = ModuleController.Instance.GetModule(searchItem.ModuleId, Null.NullInteger, true); @@ -248,153 +212,70 @@ public SearchDocument ConvertSearchItemInfoToSearchDocument(SearchItemInfo searc PortalId = module.PortalID, SearchTypeId = ModuleSearchTypeId, CultureCode = module.CultureCode, - //Add Module MetaData + + // Add Module MetaData ModuleDefId = module.ModuleDefID, - ModuleId = module.ModuleID + ModuleId = module.ModuleID, }; return searchDoc; - } - #pragma warning restore 0618 - - #endregion - - #region Protected Methods - - /// ----------------------------------------------------------------------------- - /// - /// Gets a list of modules that are listed as "Searchable" from the module definition and check if they - /// implement ModuleSearchBase -- which is a newer implementation of search that replaces ISearchable - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected IEnumerable GetSearchModules(int portalId) - { - return GetSearchModules(portalId, false); - } - - protected IEnumerable GetSearchModules(int portalId, bool allModules) - { - return from mii in GetModulesForIndex(portalId) - where allModules || mii.SupportSearch - select mii.ModuleInfo; - } + } - - #endregion - - #region Obsolete Methods - - /// ----------------------------------------------------------------------------- - /// - /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. - /// Used for Legacy Search (ISearchable) - /// - /// GetSearchIndexItems gets the SearchInfo Items for the Portal - /// - /// - /// - /// The Id of the Portal - /// ----------------------------------------------------------------------------- - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - public override SearchItemInfoCollection GetSearchIndexItems(int portalId) + private static void AddModuleMetaData(IEnumerable searchItems, ModuleInfo module) { - var searchItems = new SearchItemInfoCollection(); - var searchCollection = GetModuleList(portalId); - foreach (SearchContentModuleInfo scModInfo in searchCollection) + foreach (var searchItem in searchItems) { - try + searchItem.ModuleDefId = module.ModuleDefID; + searchItem.ModuleId = module.ModuleID; + if (string.IsNullOrEmpty(searchItem.CultureCode)) { - var myCollection = scModInfo.ModControllerType.GetSearchItems(scModInfo.ModInfo); - if (myCollection != null) - { - foreach (SearchItemInfo searchItem in myCollection) - { - searchItem.TabId = scModInfo.ModInfo.TabID; - } - - Logger.Trace("ModuleIndexer: " + myCollection.Count + " search documents found for module [" + scModInfo.ModInfo.DesktopModule.ModuleName + " mid:" + scModInfo.ModInfo.ModuleID + "]"); - - searchItems.AddRange(myCollection); - } + searchItem.CultureCode = module.CultureCode; } - catch (Exception ex) + + if (Null.IsNull(searchItem.ModifiedTimeUtc)) { - Exceptions.Exceptions.LogException(ex); + searchItem.ModifiedTimeUtc = module.LastContentModifiedOnDate.ToUniversalTime(); } } - return searchItems; } + private int IndexCollectedDocs( + Action> indexer, ICollection searchDocuments, int portalId, ScheduleHistoryItem schedule) + { + indexer.Invoke(searchDocuments); + var total = searchDocuments.Count; + this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, schedule.StartDate); + return total; + } +#pragma warning restore 0618 + /// ----------------------------------------------------------------------------- /// - /// LEGACY: Deprecated in DNN 7.1. Use 'GetSearchModules' instead. - /// Used for Legacy Search (ISearchable) - /// - /// GetModuleList gets a collection of SearchContentModuleInfo Items for the Portal + /// Gets a list of modules that are listed as "Searchable" from the module definition and check if they + /// implement ModuleSearchBase -- which is a newer implementation of search that replaces ISearchable. /// - /// - /// Parses the Modules of the Portal, determining whetehr they are searchable. - /// - /// The Id of the Portal + /// + /// /// ----------------------------------------------------------------------------- - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'GetSearchModules' instead.. Scheduled removal in v10.0.0.")] - protected SearchContentModuleInfoCollection GetModuleList(int portalId) + protected IEnumerable GetSearchModules(int portalId) { - var results = new SearchContentModuleInfoCollection(); - var arrModules = ModuleController.Instance.GetSearchModules(portalId); - var businessControllers = new Hashtable(); - var htModules = new Hashtable(); - - foreach (var module in arrModules.Cast().Where(module => !htModules.ContainsKey(module.ModuleID))) - { - try - { - //Check if the business controller is in the Hashtable - var controller = businessControllers[module.DesktopModule.BusinessControllerClass]; - if (!String.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass)) - { - //If nothing create a new instance - if (controller == null) - { - //Add to hashtable - controller = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); - businessControllers.Add(module.DesktopModule.BusinessControllerClass, controller); - } - //Double-Check that module supports ISearchable - - //Check if module inherits from ModuleSearchBase - if (controller is ISearchable && !(controller is ModuleSearchBase)) - { - var contentInfo = new SearchContentModuleInfo {ModControllerType = (ISearchable) controller, ModInfo = module}; - results.Add(contentInfo); - } - } - } - catch (Exception ex) - { - Logger.Error(ex); - ThrowLogError(module, ex); - } - finally - { - htModules.Add(module.ModuleID, module.ModuleID); - } - } - return results; + return this.GetSearchModules(portalId, false); } - #endregion - - #region Private Methods - + protected IEnumerable GetSearchModules(int portalId, bool allModules) + { + return from mii in this.GetModulesForIndex(portalId) + where allModules || mii.SupportSearch + select mii.ModuleInfo; + } + private static void ThrowLogError(ModuleInfo module, Exception ex) { try { var message = string.Format( - Localization.Localization.GetExceptionMessage("ErrorCreatingBusinessControllerClass", + Localization.GetExceptionMessage( + "ErrorCreatingBusinessControllerClass", "Error Creating BusinessControllerClass '{0}' of module({1}) id=({2}) in tab({3}) and portal({4})"), module.DesktopModule.BusinessControllerClass, module.DesktopModule.ModuleName, @@ -413,8 +294,9 @@ private IEnumerable GetModulesForIndex(int portalId) { var businessControllers = new Hashtable(); var searchModuleIds = new HashSet(); - var searchModules = new List(); - //Only get modules that are set to be Indexed. + var searchModules = new List(); + + // Only get modules that are set to be Indexed. var modules = ModuleController.Instance.GetSearchModules(portalId).Cast().Where(m => m.TabModuleSettings["AllowIndex"] == null || bool.Parse(m.TabModuleSettings["AllowIndex"].ToString())); foreach (var module in modules.Where(module => !searchModuleIds.Contains(module.ModuleID))) @@ -422,23 +304,24 @@ private IEnumerable GetModulesForIndex(int portalId) try { var tab = TabController.Instance.GetTab(module.TabID, portalId, false); - //Only index modules on tabs that are set to be Indexed. + + // Only index modules on tabs that are set to be Indexed. if (tab.TabSettings["AllowIndex"] == null || (tab.TabSettings["AllowIndex"] != null && bool.Parse(tab.TabSettings["AllowIndex"].ToString()))) { - //Check if the business controller is in the Hashtable + // Check if the business controller is in the Hashtable var controller = businessControllers[module.DesktopModule.BusinessControllerClass]; - if (!String.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass)) + if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass)) { - //If nothing create a new instance + // If nothing create a new instance if (controller == null) { - //Add to hashtable + // Add to hashtable controller = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); businessControllers.Add(module.DesktopModule.BusinessControllerClass, controller); } } - searchModules.Add(new ModuleIndexInfo{ModuleInfo = module, SupportSearch = controller is ModuleSearchBase}); + searchModules.Add(new ModuleIndexInfo { ModuleInfo = module, SupportSearch = controller is ModuleSearchBase }); } } catch (Exception ex) @@ -451,10 +334,8 @@ private IEnumerable GetModulesForIndex(int portalId) searchModuleIds.Add(module.ModuleID); } } + return searchModules; - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Services/Search/SearchConfig.cs b/DNN Platform/Library/Services/Search/SearchConfig.cs index f440454393f..5cf8aa29a79 100644 --- a/DNN Platform/Library/Services/Search/SearchConfig.cs +++ b/DNN Platform/Library/Services/Search/SearchConfig.cs @@ -1,42 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + /// ----------------------------------------------------------------------------- /// - /// The SearchConfig class provides a configuration class for Search + /// The SearchConfig class provides a configuration class for Search. /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] [Serializable] public class SearchConfig { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SearchConfig)); - #region "Private Members" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SearchConfig)); private readonly bool _SearchIncludeCommon; private readonly bool _SearchIncludeNumeric; private readonly int _SearchMaxWordlLength; - private readonly int _SearchMinWordlLength; - - #endregion - - #region "Constructor(s)" - + private readonly int _SearchMinWordlLength; + public SearchConfig(int portalID) : this(PortalController.Instance.GetPortalSettings(portalID)) { @@ -44,77 +33,68 @@ public SearchConfig(int portalID) public SearchConfig(Dictionary settings) { - _SearchIncludeCommon = GetSettingAsBoolean("SearchIncludeCommon", settings, Host.SearchIncludeCommon); - _SearchIncludeNumeric = GetSettingAsBoolean("SearchIncludeNumeric", settings, Host.SearchIncludeNumeric); - _SearchMaxWordlLength = GetSettingAsInteger("MaxSearchWordLength", settings, Host.SearchMaxWordlLength); - _SearchMinWordlLength = GetSettingAsInteger("MinSearchWordLength", settings, Host.SearchMinWordlLength); - } - - #endregion - - #region "Public Properties" - + this._SearchIncludeCommon = this.GetSettingAsBoolean("SearchIncludeCommon", settings, Host.SearchIncludeCommon); + this._SearchIncludeNumeric = this.GetSettingAsBoolean("SearchIncludeNumeric", settings, Host.SearchIncludeNumeric); + this._SearchMaxWordlLength = this.GetSettingAsInteger("MaxSearchWordLength", settings, Host.SearchMaxWordlLength); + this._SearchMinWordlLength = this.GetSettingAsInteger("MinSearchWordLength", settings, Host.SearchMinWordlLength); + } + /// ----------------------------------------------------------------------------- /// - /// Gets whether to inlcude Common Words in the Search Index + /// Gets a value indicating whether gets whether to inlcude Common Words in the Search Index. /// - /// Defaults to False + /// Defaults to False. /// ----------------------------------------------------------------------------- public bool SearchIncludeCommon { get { - return _SearchIncludeCommon; + return this._SearchIncludeCommon; } } /// ----------------------------------------------------------------------------- /// - /// Gets whether to inlcude Numbers in the Search Index + /// Gets a value indicating whether gets whether to inlcude Numbers in the Search Index. /// - /// Defaults to False + /// Defaults to False. /// ----------------------------------------------------------------------------- public bool SearchIncludeNumeric { get { - return _SearchIncludeNumeric; + return this._SearchIncludeNumeric; } } /// ----------------------------------------------------------------------------- /// - /// Gets the maximum Search Word length to index + /// Gets the maximum Search Word length to index. /// - /// Defaults to 25 + /// Defaults to 25. /// ----------------------------------------------------------------------------- public int SearchMaxWordlLength { get { - return _SearchMaxWordlLength; + return this._SearchMaxWordlLength; } } /// ----------------------------------------------------------------------------- /// - /// Gets the maximum Search Word length to index + /// Gets the maximum Search Word length to index. /// - /// Defaults to 3 + /// Defaults to 3. /// ----------------------------------------------------------------------------- public int SearchMinWordlLength { get { - return _SearchMinWordlLength; + return this._SearchMinWordlLength; } - } - - #endregion - - #region "Private Methods" - - + } + private bool GetSettingAsBoolean(string key, Dictionary settings, bool defaultValue) { bool retValue = Null.NullBoolean; @@ -128,15 +108,15 @@ private bool GetSettingAsBoolean(string key, Dictionary settings } else { - retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); } } catch (Exception exc) { - //we just want to trap the error as we may not be installed so there will be no Settings + // we just want to trap the error as we may not be installed so there will be no Settings Logger.Error(exc); - } + return retValue; } @@ -158,13 +138,11 @@ private int GetSettingAsInteger(string key, Dictionary settings, } catch (Exception exc) { - //we just want to trap the error as we may not be installed so there will be no Settings + // we just want to trap the error as we may not be installed so there will be no Settings Logger.Error(exc); - } + return retValue; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs b/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs index a156de783ad..292ffa874fe 100644 --- a/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.Index @@ -19,7 +14,7 @@ namespace DotNetNuke.Services.Search /// ----------------------------------------------------------------------------- /// /// The SearchContentModuleInfo class represents an extendension (by containment) - /// of ModuleInfo to add a parametere that determines whether a module is Searchable + /// of ModuleInfo to add a parametere that determines whether a module is Searchable. /// /// /// @@ -37,11 +32,12 @@ public ISearchable ModControllerType { get { - return MModControllerType; + return this.MModControllerType; } + set { - MModControllerType = value; + this.MModControllerType = value; } } #pragma warning restore 0618 @@ -50,11 +46,12 @@ public ModuleSearchBase ModSearchBaseControllerType { get { - return SearchBaseControllerType; + return this.SearchBaseControllerType; } + set { - SearchBaseControllerType = value; + this.SearchBaseControllerType = value; } } @@ -62,11 +59,12 @@ public ModuleInfo ModInfo { get { - return MModInfo; + return this.MModInfo; } + set { - MModInfo = value; + this.MModInfo = value; } } } diff --git a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs index 49ade48eccc..207ebef731f 100644 --- a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System.Collections; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.Index @@ -21,40 +16,37 @@ namespace DotNetNuke.Services.Search /// /// /// ----------------------------------------------------------------------------- - #pragma warning disable 0618 +#pragma warning disable 0618 public class SearchContentModuleInfoCollection : CollectionBase - { - #region "Constructors" - - /// + { + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchContentModuleInfoCollection class. /// public SearchContentModuleInfoCollection() { - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchContentModuleInfoCollection class containing the elements of the specified source collection. /// /// A SearchContentModuleInfoCollection with which to initialize the collection. public SearchContentModuleInfoCollection(SearchContentModuleInfoCollection value) { - AddRange(value); - } - - /// + this.AddRange(value); + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchContentModuleInfoCollection class containing the specified array of SearchContentModuleInfo objects. /// /// An array of SearchContentModuleInfo objects with which to initialize the collection. public SearchContentModuleInfoCollection(SearchContentModuleInfo[] value) { - AddRange(value); - } - - #endregion - - #region "Properties" - + this.AddRange(value); + } + /// /// Gets the SearchContentModuleInfoCollection at the specified index in the collection. /// @@ -65,25 +57,23 @@ public SearchContentModuleInfo this[int index] { get { - return (SearchContentModuleInfo) List[index]; + return (SearchContentModuleInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } - } - - #endregion - - #region "Public Methods" - + } + /// /// Add an element of the specified SearchContentModuleInfo to the end of the collection. /// - /// An object of type SearchContentModuleInfo to add to the collection. + /// An object of type SearchContentModuleInfo to add to the collection. + /// public int Add(SearchContentModuleInfo value) { - return List.Add(value); + return this.List.Add(value); } /// @@ -93,17 +83,17 @@ public int Add(SearchContentModuleInfo value) /// The index in the collection of the specified object, if found; otherwise, -1. public int IndexOf(SearchContentModuleInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } /// /// Add an element of the specified SearchContentModuleInfo to the collection at the designated index. /// - /// An Integer to indicate the location to add the object to the collection. + /// An Integer to indicate the location to add the object to the collection. /// An object of type SearchContentModuleInfo to add to the collection. public void Insert(int index, SearchContentModuleInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } /// @@ -112,7 +102,7 @@ public void Insert(int index, SearchContentModuleInfo value) /// An object of type SearchContentModuleInfo to remove to the collection. public void Remove(SearchContentModuleInfo value) { - List.Remove(value); + this.List.Remove(value); } /// @@ -122,8 +112,8 @@ public void Remove(SearchContentModuleInfo value) /// true if the collection contains the specified object; otherwise, false. public bool Contains(SearchContentModuleInfo value) { - //If value is not of type SearchContentModuleInfo, this will return false. - return List.Contains(value); + // If value is not of type SearchContentModuleInfo, this will return false. + return this.List.Contains(value); } /// @@ -134,7 +124,7 @@ public void AddRange(SearchContentModuleInfo[] value) { for (int i = 0; i <= value.Length - 1; i++) { - Add(value[i]); + this.Add(value[i]); } } @@ -146,7 +136,7 @@ public void AddRange(SearchContentModuleInfoCollection value) { for (int i = 0; i <= value.Count - 1; i++) { - Add((SearchContentModuleInfo) value.List[i]); + this.Add((SearchContentModuleInfo)value.List[i]); } } @@ -157,21 +147,19 @@ public void AddRange(SearchContentModuleInfoCollection value) /// The index of the array at which to begin inserting. public void CopyTo(SearchContentModuleInfo[] array, int index) { - List.CopyTo(array, index); + this.List.CopyTo(array, index); } /// /// Creates a one-dimensional Array instance containing the collection items. /// - /// Array of type SearchContentModuleInfo + /// Array of type SearchContentModuleInfo. public SearchContentModuleInfo[] ToArray() { - var arr = new SearchContentModuleInfo[Count]; - CopyTo(arr, 0); + var arr = new SearchContentModuleInfo[this.Count]; + this.CopyTo(arr, 0); return arr; - } - - #endregion - } - #pragma warning restore 0618 + } + } +#pragma warning restore 0618 } diff --git a/DNN Platform/Library/Services/Search/SearchCriteria.cs b/DNN Platform/Library/Services/Search/SearchCriteria.cs index 0798c8846df..3a820d42d5b 100644 --- a/DNN Platform/Library/Services/Search/SearchCriteria.cs +++ b/DNN Platform/Library/Services/Search/SearchCriteria.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Search { + using System; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.DataStore /// Class: SearchCriteria /// ----------------------------------------------------------------------------- /// - /// The SearchCriteria represents a search criterion + /// The SearchCriteria represents a search criterion. /// /// /// diff --git a/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs b/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs index 1ac4974c321..3c75149b3cc 100644 --- a/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.DataStore @@ -24,44 +19,46 @@ namespace DotNetNuke.Services.Search /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] public class SearchCriteriaCollection : CollectionBase - { - #region Constructors - - /// + { + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class. /// - public SearchCriteriaCollection() { - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class containing the elements of the specified source collection. /// /// A SearchCriteriaCollection with which to initialize the collection. public SearchCriteriaCollection(SearchCriteriaCollection value) { - AddRange(value); - } - - /// + this.AddRange(value); + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class containing the specified array of SearchCriteria objects. /// /// An array of SearchCriteria objects with which to initialize the collection. public SearchCriteriaCollection(SearchCriteria[] value) { - AddRange(value); - } - - /// + this.AddRange(value); + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class containing the elements of the specified source collection. /// - /// A criteria string with which to initialize the collection + /// A criteria string with which to initialize the collection. public SearchCriteriaCollection(string value) { - //split search criteria into words + // split search criteria into words string[] words = value.Split(' '); - //Add all criteria without modifiers + + // Add all criteria without modifiers foreach (string word in words) { var criterion = new SearchCriteria(); @@ -70,10 +67,11 @@ public SearchCriteriaCollection(string value) criterion.MustInclude = false; criterion.MustExclude = false; criterion.Criteria = word; - Add(criterion); + this.Add(criterion); } } - //Add all mandatory criteria + + // Add all mandatory criteria foreach (string word in words) { var criterion = new SearchCriteria(); @@ -82,10 +80,11 @@ public SearchCriteriaCollection(string value) criterion.MustInclude = true; criterion.MustExclude = false; criterion.Criteria = word.Remove(0, 1); - Add(criterion); + this.Add(criterion); } } - //Add all excluded criteria + + // Add all excluded criteria foreach (string word in words) { var criterion = new SearchCriteria(); @@ -94,15 +93,11 @@ public SearchCriteriaCollection(string value) criterion.MustInclude = false; criterion.MustExclude = true; criterion.Criteria = word.Remove(0, 1); - Add(criterion); + this.Add(criterion); } } - } - - #endregion - - #region Properties - + } + /// /// Gets the SearchCriteriaCollection at the specified index in the collection. /// @@ -113,25 +108,23 @@ public SearchCriteria this[int index] { get { - return (SearchCriteria) List[index]; + return (SearchCriteria)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } - } - - #endregion - - #region Public Methods - + } + /// /// Add an element of the specified SearchCriteria to the end of the collection. /// - /// An object of type SearchCriteria to add to the collection. + /// An object of type SearchCriteria to add to the collection. + /// public int Add(SearchCriteria value) { - return List.Add(value); + return this.List.Add(value); } /// @@ -141,17 +134,17 @@ public int Add(SearchCriteria value) /// The index in the collection of the specified object, if found; otherwise, -1. public int IndexOf(SearchCriteria value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } /// /// Add an element of the specified SearchCriteria to the collection at the designated index. /// - /// An Integer to indicate the location to add the object to the collection. + /// An Integer to indicate the location to add the object to the collection. /// An object of type SearchCriteria to add to the collection. public void Insert(int index, SearchCriteria value) { - List.Insert(index, value); + this.List.Insert(index, value); } /// @@ -160,7 +153,7 @@ public void Insert(int index, SearchCriteria value) /// An object of type SearchCriteria to remove to the collection. public void Remove(SearchCriteria value) { - List.Remove(value); + this.List.Remove(value); } /// @@ -170,7 +163,7 @@ public void Remove(SearchCriteria value) /// true if the collection contains the specified object; otherwise, false. public bool Contains(SearchCriteria value) { - return List.Contains(value); + return this.List.Contains(value); } /// @@ -181,7 +174,7 @@ public void AddRange(SearchCriteria[] value) { for (int i = 0; i <= value.Length - 1; i++) { - Add(value[i]); + this.Add(value[i]); } } @@ -193,7 +186,7 @@ public void AddRange(SearchCriteriaCollection value) { for (int i = 0; i <= value.Count - 1; i++) { - Add((SearchCriteria) value.List[i]); + this.Add((SearchCriteria)value.List[i]); } } @@ -204,20 +197,18 @@ public void AddRange(SearchCriteriaCollection value) /// The index of the array at which to begin inserting. public void CopyTo(SearchCriteria[] array, int index) { - List.CopyTo(array, index); + this.List.CopyTo(array, index); } /// /// Creates a one-dimensional Array instance containing the collection items. /// - /// Array of type SearchCriteria + /// Array of type SearchCriteria. public SearchCriteria[] ToArray() { - var arr = new SearchCriteria[Count]; - CopyTo(arr, 0); + var arr = new SearchCriteria[this.Count]; + this.CopyTo(arr, 0); return arr; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Search/SearchDataStore.cs b/DNN Platform/Library/Services/Search/SearchDataStore.cs index 1b010b98d4a..9132a15485f 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStore.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStore.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Search.Internals; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.DataStore @@ -32,63 +27,24 @@ namespace DotNetNuke.Services.Search /// ----------------------------------------------------------------------------- /// /// The SearchDataStore is an implementation of the abstract SearchDataStoreProvider - /// class + /// class. /// /// /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] public class SearchDataStore : SearchDataStoreProvider - { - #region Private Methods - + { /// ----------------------------------------------------------------------------- /// - /// GetCommonWords gets a list of the Common Words for the locale + /// GetSearchItems gets a collection of Search Items for a Module/Tab/Portal. /// /// /// - /// The locale string - /// A hashtable of common words - /// ----------------------------------------------------------------------------- - private Hashtable GetCommonWords(string locale) - { - string strCacheKey = "CommonWords" + locale; - var objWords = (Hashtable) DataCache.GetCache(strCacheKey); - if (objWords == null) - { - objWords = new Hashtable(); - IDataReader drWords = DataProvider.Instance().GetSearchCommonWordsByLocale(locale); - try - { - while (drWords.Read()) - { - objWords.Add(drWords["CommonWord"].ToString(), drWords["CommonWord"].ToString()); - } - } - finally - { - drWords.Close(); - drWords.Dispose(); - } - DataCache.SetCache(strCacheKey, objWords); - } - return objWords; - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// GetSearchItems gets a collection of Search Items for a Module/Tab/Portal - /// - /// - /// - /// A Id of the Portal - /// A Id of the Tab - /// A Id of the Module + /// A Id of the Portal. + /// A Id of the Tab. + /// A Id of the Module. + /// /// ----------------------------------------------------------------------------- public override SearchResultsInfoCollection GetSearchItems(int portalId, int tabId, int moduleId) { @@ -97,12 +53,13 @@ public override SearchResultsInfoCollection GetSearchItems(int portalId, int tab /// ----------------------------------------------------------------------------- /// - /// GetSearchResults gets the search results for a passed in criteria string + /// GetSearchResults gets the search results for a passed in criteria string. /// /// /// - /// A Id of the Portal - /// The criteria string + /// A Id of the Portal. + /// The criteria string. + /// /// ----------------------------------------------------------------------------- public override SearchResultsInfoCollection GetSearchResults(int portalId, string criteria) { @@ -111,24 +68,24 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin var portal = PortalController.Instance.GetPortal(portalId); - //Get the Settings for this Portal + // Get the Settings for this Portal var portalSettings = new PortalSettings(portal); - //We will assume that the content is in the locale of the Portal - Hashtable commonWords = GetCommonWords(portalSettings.DefaultLanguage); + // We will assume that the content is in the locale of the Portal + Hashtable commonWords = this.GetCommonWords(portalSettings.DefaultLanguage); - //clean criteria + // clean criteria criteria = criteria.ToLowerInvariant(); - //split search criteria into words + // split search criteria into words var searchWords = new SearchCriteriaCollection(criteria); var searchResults = new Dictionary(); - //dicResults is a Dictionary(Of SearchItemID, Dictionary(Of TabID, SearchResultsInfo) + // dicResults is a Dictionary(Of SearchItemID, Dictionary(Of TabID, SearchResultsInfo) var dicResults = new Dictionary>(); - //iterate through search criteria words + // iterate through search criteria words foreach (SearchCriteria criterion in searchWords) { if (commonWords.ContainsKey(criterion.Criteria) == false || portalSettings.SearchIncludeCommon) @@ -137,36 +94,37 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin { searchResults.Add(criterion.Criteria, SearchDataStoreController.GetSearchResults(portalId, criterion.Criteria)); } + if (searchResults.ContainsKey(criterion.Criteria)) { foreach (SearchResultsInfo result in searchResults[criterion.Criteria]) { - //Add results to dicResults + // Add results to dicResults if (!criterion.MustExclude) { if (dicResults.ContainsKey(result.SearchItemID)) { - //The Dictionary exists for this SearchItemID already so look in the TabId keyed Sub-Dictionary + // The Dictionary exists for this SearchItemID already so look in the TabId keyed Sub-Dictionary Dictionary dic = dicResults[result.SearchItemID]; if (dic.ContainsKey(result.TabId)) { - //The sub-Dictionary contains the item already so update the relevance + // The sub-Dictionary contains the item already so update the relevance SearchResultsInfo searchResult = dic[result.TabId]; searchResult.Relevance += result.Relevance; } else { - //Add Entry to Sub-Dictionary + // Add Entry to Sub-Dictionary dic.Add(result.TabId, result); } } else { - //Create new TabId keyed Dictionary + // Create new TabId keyed Dictionary var dic = new Dictionary(); dic.Add(result.TabId, result); - //Add new Dictionary to SearchResults + // Add new Dictionary to SearchResults dicResults.Add(result.SearchItemID, dic); } } @@ -174,6 +132,7 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin } } } + foreach (SearchCriteria criterion in searchWords) { var mandatoryResults = new Dictionary(); @@ -184,32 +143,33 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin { if (criterion.MustInclude) { - //Add to mandatory results lookup + // Add to mandatory results lookup mandatoryResults[result.SearchItemID] = true; hasMandatory = true; } else if (criterion.MustExclude) { - //Add to exclude results lookup + // Add to exclude results lookup excludedResults[result.SearchItemID] = true; hasExcluded = true; } } } + foreach (KeyValuePair> kvpResults in dicResults) { - //The key of this collection is the SearchItemID, Check if the value of this collection should be processed + // The key of this collection is the SearchItemID, Check if the value of this collection should be processed if (hasMandatory && (!mandatoryResults.ContainsKey(kvpResults.Key))) { - //1. If mandatoryResults exist then only process if in mandatoryResults Collection + // 1. If mandatoryResults exist then only process if in mandatoryResults Collection foreach (SearchResultsInfo result in kvpResults.Value.Values) { result.Delete = true; } } - else if (hasExcluded && (excludedResults.ContainsKey(kvpResults.Key))) + else if (hasExcluded && excludedResults.ContainsKey(kvpResults.Key)) { - //2. Do not process results in the excludedResults Collection + // 2. Do not process results in the excludedResults Collection foreach (SearchResultsInfo result in kvpResults.Value.Values) { result.Delete = true; @@ -217,8 +177,8 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin } } } - - //Process results against permissions and mandatory and excluded results + + // Process results against permissions and mandatory and excluded results var results = new SearchResultsInfoCollection(); foreach (KeyValuePair> kvpResults in dicResults) { @@ -226,11 +186,11 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin { if (!result.Delete) { - //Check If authorised to View Tab + // Check If authorised to View Tab TabInfo objTab = TabController.Instance.GetTab(result.TabId, portalId, false); if (TabPermissionController.CanViewPage(objTab)) { - //Check If authorised to View Module + // Check If authorised to View Module ModuleInfo objModule = ModuleController.Instance.GetModule(result.ModuleId, result.TabId, false); if (ModulePermissionController.CanViewModule(objModule)) { @@ -240,50 +200,83 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin } } } - - //Return Search Results Collection + + // Return Search Results Collection return results; } + + /// ----------------------------------------------------------------------------- + /// + /// GetCommonWords gets a list of the Common Words for the locale. + /// + /// + /// + /// The locale string. + /// A hashtable of common words. + /// ----------------------------------------------------------------------------- + private Hashtable GetCommonWords(string locale) + { + string strCacheKey = "CommonWords" + locale; + var objWords = (Hashtable)DataCache.GetCache(strCacheKey); + if (objWords == null) + { + objWords = new Hashtable(); + IDataReader drWords = DataProvider.Instance().GetSearchCommonWordsByLocale(locale); + try + { + while (drWords.Read()) + { + objWords.Add(drWords["CommonWord"].ToString(), drWords["CommonWord"].ToString()); + } + } + finally + { + drWords.Close(); + drWords.Dispose(); + } + + DataCache.SetCache(strCacheKey, objWords); + } + + return objWords; + } /// ----------------------------------------------------------------------------- /// - /// StoreSearchItems adds the Search Item to the Data Store + /// StoreSearchItems adds the Search Item to the Data Store. /// /// /// - /// A Collection of SearchItems + /// A Collection of SearchItems. public override void StoreSearchItems(SearchItemInfoCollection searchItems) { var indexer = new ModuleIndexer(); - + var modulesDic = new Dictionary(); foreach (SearchItemInfo item in searchItems) - { + { if (!modulesDic.ContainsKey(item.ModuleId)) { var module = ModuleController.Instance.GetModule(item.ModuleId, Null.NullInteger, true); modulesDic.Add(item.ModuleId, module.CultureCode); - - //Remove all indexed items for this module + + // Remove all indexed items for this module InternalSearchController.Instance.DeleteSearchDocumentsByModule(module.PortalID, module.ModuleID, module.ModuleDefID); } } - - //Process the SearchItems by Module to reduce Database hits + + // Process the SearchItems by Module to reduce Database hits foreach (var kvp in modulesDic) { - //Get the Module's SearchItems + // Get the Module's SearchItems var moduleSearchItems = searchItems.ModuleItems(kvp.Key); - - //Convert SearchItemInfo objects to SearchDocument objects - var searchDocuments = (from SearchItemInfo item in moduleSearchItems select indexer.ConvertSearchItemInfoToSearchDocument(item)).ToList(); - - //Index - InternalSearchController.Instance.AddSearchDocuments(searchDocuments); - } - } - #endregion + // Convert SearchItemInfo objects to SearchDocument objects + var searchDocuments = (from SearchItemInfo item in moduleSearchItems select indexer.ConvertSearchItemInfoToSearchDocument(item)).ToList(); + // Index + InternalSearchController.Instance.AddSearchDocuments(searchDocuments); + } + } } } diff --git a/DNN Platform/Library/Services/Search/SearchDataStoreController.cs b/DNN Platform/Library/Services/Search/SearchDataStoreController.cs index 9a247ce4ea6..715a2c3f7c6 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStoreController.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStoreController.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.DataStore /// Class: SearchDataStoreController /// ----------------------------------------------------------------------------- /// - /// The SearchDataStoreController is the Business Controller class for SearchDataStore + /// The SearchDataStoreController is the Business Controller class for SearchDataStore. /// /// /// @@ -38,18 +33,18 @@ public static int AddSearchItem(SearchItemInfo item) [Obsolete("Deprecated in DNN 7.2.2 Implementation changed to do nothing. Scheduled removal in v10.0.0.")] public static void DeleteSearchItem(int SearchItemId) - { + { } [Obsolete("Deprecated in DNN 7.2.2 Implementation changed to do nothing. Scheduled removal in v10.0.0.")] public static void DeleteSearchItemWords(int SearchItemId) - { + { } [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] public static SearchItemInfo GetSearchItem(int ModuleId, string SearchKey) { - var empty=new SearchItemInfo(); + var empty = new SearchItemInfo(); return empty; } @@ -69,12 +64,13 @@ public static ArrayList GetSearchItems(int PortalId, int TabId, int ModuleId) /// ----------------------------------------------------------------------------- /// - /// GetSearchResults gets the search results for a single word + /// GetSearchResults gets the search results for a single word. /// /// /// - /// A Id of the Portal - /// The word + /// A Id of the Portal. + /// The word. + /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] public static SearchResultsInfoCollection GetSearchResults(int PortalID, string Word) @@ -92,11 +88,12 @@ public static SearchResultsInfoCollection GetSearchResults(int PortalId, int Tab /// ----------------------------------------------------------------------------- /// - /// GetSearchSettings gets the search settings for a single module + /// GetSearchSettings gets the search settings for a single module. /// /// /// - /// The Id of the Module + /// The Id of the Module. + /// /// ----------------------------------------------------------------------------- public static Dictionary GetSearchSettings(int ModuleId) { @@ -113,7 +110,7 @@ public static Dictionary GetSearchSettings(int ModuleId) } else { - dicSearchSettings[dr.GetString(0)] = ""; + dicSearchSettings[dr.GetString(0)] = string.Empty; } } } @@ -125,12 +122,13 @@ public static Dictionary GetSearchSettings(int ModuleId) { CBO.CloseDataReader(dr, true); } + return dicSearchSettings; } [Obsolete("Deprecated in DNN 7.2.2 Implementation changed to do nothing. Scheduled removal in v10.0.0.")] public static void UpdateSearchItem(SearchItemInfo item) - { + { } } } diff --git a/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs b/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs index e53b9673e60..10fa642f713 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs @@ -1,42 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] public abstract class SearchDataStoreProvider - { - #region "Shared/Static Methods" - - //return the provider + { + // return the provider public static SearchDataStoreProvider Instance() { return ComponentFactory.GetComponent(); - } - - #endregion - - #region "Abstract Methods" - + } + public abstract void StoreSearchItems(SearchItemInfoCollection searchItems); public abstract SearchResultsInfoCollection GetSearchResults(int portalId, string criteria); - public abstract SearchResultsInfoCollection GetSearchItems(int portalId, int tabId, int moduleId); - - #endregion + public abstract SearchResultsInfoCollection GetSearchItems(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/Services/Search/SearchEngine.cs b/DNN Platform/Library/Services/Search/SearchEngine.cs index 1c018751b43..0d1aa87637c 100644 --- a/DNN Platform/Library/Services/Search/SearchEngine.cs +++ b/DNN Platform/Library/Services/Search/SearchEngine.cs @@ -1,33 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data.SqlTypes; -using System.Linq; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Services.Scheduling; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections.Generic; + using System.Data.SqlTypes; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using Newtonsoft.Json; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke /// Class: SearchEngine /// ----------------------------------------------------------------------------- /// - /// The SearchEngine manages the Indexing of the Portal content + /// The SearchEngine manages the Indexing of the Portal content. /// /// /// @@ -36,68 +32,58 @@ internal class SearchEngine { internal SearchEngine(ScheduleHistoryItem scheduler, DateTime startTime) { - SchedulerItem = scheduler; - IndexingStartTime = startTime; - } - - #region Properties - + this.SchedulerItem = scheduler; + this.IndexingStartTime = startTime; + } + public ScheduleHistoryItem SchedulerItem { get; private set; } // the time from where to start indexing items - public DateTime IndexingStartTime { get; private set; } - - #endregion - - #region internal + public DateTime IndexingStartTime { get; private set; } + /// ----------------------------------------------------------------------------- /// - /// Indexes content within the given time farame + /// Indexes content within the given time farame. /// /// ----------------------------------------------------------------------------- internal void IndexContent() { - //Index TAB META-DATA + // Index TAB META-DATA var tabIndexer = new TabIndexer(); - var searchDocsCount = GetAndStoreSearchDocuments(tabIndexer); + var searchDocsCount = this.GetAndStoreSearchDocuments(tabIndexer); var indexedSearchDocumentCount = searchDocsCount; - AddIdexingResults("Tabs Indexed", searchDocsCount); + this.AddIdexingResults("Tabs Indexed", searchDocsCount); - //Index MODULE META-DATA from modules that inherit from ModuleSearchBase + // Index MODULE META-DATA from modules that inherit from ModuleSearchBase var moduleIndexer = new ModuleIndexer(true); - searchDocsCount = GetAndStoreModuleMetaData(moduleIndexer); + searchDocsCount = this.GetAndStoreModuleMetaData(moduleIndexer); indexedSearchDocumentCount += searchDocsCount; - AddIdexingResults("Modules (Metadata) Indexed", searchDocsCount); + this.AddIdexingResults("Modules (Metadata) Indexed", searchDocsCount); - //Index MODULE CONTENT from modules that inherit from ModuleSearchBase - searchDocsCount = GetAndStoreSearchDocuments(moduleIndexer); + // Index MODULE CONTENT from modules that inherit from ModuleSearchBase + searchDocsCount = this.GetAndStoreSearchDocuments(moduleIndexer); indexedSearchDocumentCount += searchDocsCount; - //Index all Defunct ISearchable module content + // Index all Defunct ISearchable module content #pragma warning disable 0618 - var searchItems = GetContent(moduleIndexer); + var searchItems = this.GetContent(moduleIndexer); SearchDataStoreProvider.Instance().StoreSearchItems(searchItems); #pragma warning restore 0618 indexedSearchDocumentCount += searchItems.Count; - //Both ModuleSearchBase and ISearchable module content count - AddIdexingResults("Modules (Content) Indexed", searchDocsCount + searchItems.Count); + // Both ModuleSearchBase and ISearchable module content count + this.AddIdexingResults("Modules (Content) Indexed", searchDocsCount + searchItems.Count); if (!HostController.Instance.GetBoolean("DisableUserCrawling", false)) { - //Index User data + // Index User data var userIndexer = new UserIndexer(); - var userIndexed = GetAndStoreSearchDocuments(userIndexer); + var userIndexed = this.GetAndStoreSearchDocuments(userIndexer); indexedSearchDocumentCount += userIndexed; - AddIdexingResults("Users", userIndexed); + this.AddIdexingResults("Users", userIndexed); } - SchedulerItem.AddLogNote("
    Total Items Indexed: " + indexedSearchDocumentCount + ""); - } - - private void AddIdexingResults(string description, int count) - { - SchedulerItem.AddLogNote(string.Format("
      {0}: {1}", description, count)); + this.SchedulerItem.AddLogNote("
    Total Items Indexed: " + indexedSearchDocumentCount + ""); } internal bool CompactSearchIndexIfNeeded(ScheduleHistoryItem scheduleItem) @@ -113,6 +99,7 @@ internal bool CompactSearchIndexIfNeeded(ScheduleHistoryItem scheduleItem) scheduleItem.AddLogNote(string.Format("
    Compacted Index, total time {0}", stopWatch.Elapsed)); } } + return false; } @@ -121,7 +108,7 @@ internal bool CompactSearchIndexIfNeeded(ScheduleHistoryItem scheduleItem) ///
    internal void DeleteOldDocsBeforeReindex() { - var portal2Reindex = SearchHelper.Instance.GetPortalsToReindex(IndexingStartTime); + var portal2Reindex = SearchHelper.Instance.GetPortalsToReindex(this.IndexingStartTime); var controller = InternalSearchController.Instance; foreach (var portalId in portal2Reindex) @@ -131,13 +118,18 @@ internal void DeleteOldDocsBeforeReindex() } } + private void AddIdexingResults(string description, int count) + { + this.SchedulerItem.AddLogNote(string.Format("
      {0}: {1}", description, count)); + } + /// /// Deletes all deleted items from the system that are added to deletions table. /// internal void DeleteRemovedObjects() { var deletedCount = 0; - var cutoffTime = SchedulerItem.StartDate.ToUniversalTime(); + var cutoffTime = this.SchedulerItem.StartDate.ToUniversalTime(); var searchController = InternalSearchController.Instance; var dataProvider = DataProvider.Instance(); using (var reader = dataProvider.GetSearchDeletedItems(cutoffTime)) @@ -149,30 +141,95 @@ internal void DeleteRemovedObjects() searchController.DeleteSearchDocument(document); deletedCount += 1; } + reader.Close(); } - AddIdexingResults("Deleted Objects", deletedCount); + + this.AddIdexingResults("Deleted Objects", deletedCount); dataProvider.DeleteProcessedSearchDeletedItems(cutoffTime); } /// - /// Commits (flushes) all added and deleted content to search engine's disk file + /// Commits (flushes) all added and deleted content to search engine's disk file. /// internal void Commit() { InternalSearchController.Instance.Commit(); + } + + /// ----------------------------------------------------------------------------- + /// + /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. + /// Used for Legacy Search (ISearchable) + /// + /// GetContent gets all the content and passes it to the Indexer. + /// + /// + /// + /// The Index Provider that will index the content of the portal. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] + protected SearchItemInfoCollection GetContent(IndexingProviderBase indexer) + { + var searchItems = new SearchItemInfoCollection(); + var portals = PortalController.Instance.GetPortals(); + for (var index = 0; index <= portals.Count - 1; index++) + { + var portal = (PortalInfo)portals[index]; + searchItems.AddRange(indexer.GetSearchIndexItems(portal.PortalID)); + } + + return searchItems; } - #endregion - #region Private + /// ----------------------------------------------------------------------------- + /// + /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. + /// Used for Legacy Search (ISearchable) + /// + /// GetContent gets the Portal's content and passes it to the Indexer. + /// + /// + /// + /// The Id of the Portal. + /// The Index Provider that will index the content of the portal. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] + protected SearchItemInfoCollection GetContent(int portalId, IndexingProvider indexer) + { + var searchItems = new SearchItemInfoCollection(); + searchItems.AddRange(indexer.GetSearchIndexItems(portalId)); + return searchItems; + } + /// ----------------------------------------------------------------------------- + /// + /// Ensures all SearchDocuments have a SearchTypeId. + /// + /// + /// ----------------------------------------------------------------------------- + private static void StoreSearchDocuments(IEnumerable searchDocs) + { + var defaultSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; + + var searchDocumentList = searchDocs as IList ?? searchDocs.ToList(); + foreach (var searchDocument in searchDocumentList.Where(searchDocument => searchDocument.SearchTypeId <= 0)) + { + searchDocument.SearchTypeId = defaultSearchTypeId; + } + + InternalSearchController.Instance.AddSearchDocuments(searchDocumentList); + } + /// ----------------------------------------------------------------------------- /// /// Gets all the Search Documents for the given timeframe. /// /// /// ----------------------------------------------------------------------------- - private int GetAndStoreSearchDocuments(IndexingProvider indexer) + private int GetAndStoreSearchDocuments(IndexingProviderBase indexer) { IList searchDocs; var portals = PortalController.Instance.GetPortals(); @@ -181,11 +238,11 @@ private int GetAndStoreSearchDocuments(IndexingProvider indexer) foreach (var portal in portals.Cast()) { - indexSince = FixedIndexingStartDate(portal.PortalID); + indexSince = this.FixedIndexingStartDate(portal.PortalID); try { indexedCount += indexer.IndexSearchDocuments( - portal.PortalID, SchedulerItem, indexSince, StoreSearchDocuments); + portal.PortalID, this.SchedulerItem, indexSince, StoreSearchDocuments); } catch (NotImplementedException) { @@ -198,11 +255,11 @@ private int GetAndStoreSearchDocuments(IndexingProvider indexer) } // Include Host Level Items - indexSince = FixedIndexingStartDate(-1); + indexSince = this.FixedIndexingStartDate(-1); try { indexedCount += indexer.IndexSearchDocuments( - Null.NullInteger, SchedulerItem, indexSince, StoreSearchDocuments); + Null.NullInteger, this.SchedulerItem, indexSince, StoreSearchDocuments); } catch (NotImplementedException) { @@ -212,12 +269,13 @@ private int GetAndStoreSearchDocuments(IndexingProvider indexer) StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); } + return indexedCount; } /// ----------------------------------------------------------------------------- /// - /// Gets all the Searchable Module MetaData SearchDocuments within the timeframe for all portals + /// Gets all the Searchable Module MetaData SearchDocuments within the timeframe for all portals. /// /// ----------------------------------------------------------------------------- private int GetAndStoreModuleMetaData(ModuleIndexer indexer) @@ -226,18 +284,18 @@ private int GetAndStoreModuleMetaData(ModuleIndexer indexer) var portals = PortalController.Instance.GetPortals(); DateTime indexSince; var indexedCount = 0; - //DateTime startDate - + + // DateTime startDate foreach (var portal in portals.Cast()) { - indexSince = FixedIndexingStartDate(portal.PortalID); + indexSince = this.FixedIndexingStartDate(portal.PortalID); searchDocs = indexer.GetModuleMetaData(portal.PortalID, indexSince); StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); } // Include Host Level Items - indexSince = FixedIndexingStartDate(Null.NullInteger); + indexSince = this.FixedIndexingStartDate(Null.NullInteger); searchDocs = indexer.GetModuleMetaData(Null.NullInteger, indexSince); StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); @@ -247,88 +305,19 @@ private int GetAndStoreModuleMetaData(ModuleIndexer indexer) /// ----------------------------------------------------------------------------- /// - /// Ensures all SearchDocuments have a SearchTypeId - /// - /// - /// ----------------------------------------------------------------------------- - private static void StoreSearchDocuments(IEnumerable searchDocs) - { - var defaultSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - - var searchDocumentList = searchDocs as IList ?? searchDocs.ToList(); - foreach (var searchDocument in searchDocumentList.Where(searchDocument => searchDocument.SearchTypeId <= 0)) - { - searchDocument.SearchTypeId = defaultSearchTypeId; - } - - InternalSearchController.Instance.AddSearchDocuments(searchDocumentList); - } - - /// ----------------------------------------------------------------------------- - /// - /// Adjusts the re-index date/time to account for the portal reindex value + /// Adjusts the re-index date/time to account for the portal reindex value. /// /// ----------------------------------------------------------------------------- private DateTime FixedIndexingStartDate(int portalId) { - var startDate = IndexingStartTime; + var startDate = this.IndexingStartTime; if (startDate < SqlDateTime.MinValue.Value || SearchHelper.Instance.IsReindexRequested(portalId, startDate)) { return SqlDateTime.MinValue.Value.AddDays(1); } + return startDate; - } - - #endregion - - #region Obsoleted Methods - - /// ----------------------------------------------------------------------------- - /// - /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. - /// Used for Legacy Search (ISearchable) - /// - /// GetContent gets all the content and passes it to the Indexer - /// - /// - /// - /// The Index Provider that will index the content of the portal - /// ----------------------------------------------------------------------------- - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - protected SearchItemInfoCollection GetContent(IndexingProvider indexer) - { - var searchItems = new SearchItemInfoCollection(); - var portals = PortalController.Instance.GetPortals(); - for (var index = 0; index <= portals.Count - 1; index++) - { - var portal = (PortalInfo)portals[index]; - searchItems.AddRange(indexer.GetSearchIndexItems(portal.PortalID)); - } - return searchItems; - } - - /// ----------------------------------------------------------------------------- - /// - /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. - /// Used for Legacy Search (ISearchable) - /// - /// GetContent gets the Portal's content and passes it to the Indexer - /// - /// - /// - /// The Id of the Portal - /// The Index Provider that will index the content of the portal - /// ----------------------------------------------------------------------------- - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - protected SearchItemInfoCollection GetContent(int portalId, IndexingProvider indexer) - { - var searchItems = new SearchItemInfoCollection(); - searchItems.AddRange(indexer.GetSearchIndexItems(portalId)); - return searchItems; - } - - #endregion - + } } } diff --git a/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs b/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs index f664a875409..7603d770db9 100644 --- a/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs +++ b/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs @@ -1,19 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Internals; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke @@ -32,12 +28,12 @@ public class SearchEngineScheduler : SchedulerClient public SearchEngineScheduler(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } /// ----------------------------------------------------------------------------- /// - /// DoWork runs the scheduled item + /// DoWork runs the scheduled item. /// /// /// @@ -46,35 +42,35 @@ public override void DoWork() { try { - var lastSuccessFulDateTime = SearchHelper.Instance.GetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID); + var lastSuccessFulDateTime = SearchHelper.Instance.GetLastSuccessfulIndexingDateTime(this.ScheduleHistoryItem.ScheduleID); Logger.Trace("Search: Site Crawler - Starting. Content change start time " + lastSuccessFulDateTime.ToString("g")); - ScheduleHistoryItem.AddLogNote(string.Format("Starting. Content change start time {0:g}", lastSuccessFulDateTime)); + this.ScheduleHistoryItem.AddLogNote(string.Format("Starting. Content change start time {0:g}", lastSuccessFulDateTime)); - var searchEngine = new SearchEngine(ScheduleHistoryItem, lastSuccessFulDateTime); + var searchEngine = new SearchEngine(this.ScheduleHistoryItem, lastSuccessFulDateTime); try { searchEngine.DeleteOldDocsBeforeReindex(); searchEngine.DeleteRemovedObjects(); searchEngine.IndexContent(); - searchEngine.CompactSearchIndexIfNeeded(ScheduleHistoryItem); + searchEngine.CompactSearchIndexIfNeeded(this.ScheduleHistoryItem); } finally { searchEngine.Commit(); } - ScheduleHistoryItem.Succeeded = true; - ScheduleHistoryItem.AddLogNote("
    Indexing Successful"); - SearchHelper.Instance.SetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID, ScheduleHistoryItem.StartDate); + this.ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.AddLogNote("
    Indexing Successful"); + SearchHelper.Instance.SetLastSuccessfulIndexingDateTime(this.ScheduleHistoryItem.ScheduleID, this.ScheduleHistoryItem.StartDate); Logger.Trace("Search: Site Crawler - Indexing Successful"); } catch (Exception ex) { - ScheduleHistoryItem.Succeeded = false; - ScheduleHistoryItem.AddLogNote("
    EXCEPTION: " + ex.Message); - Errored(ref ex); - if (ScheduleHistoryItem.ScheduleSource != ScheduleSource.STARTED_FROM_BEGIN_REQUEST) + this.ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.AddLogNote("
    EXCEPTION: " + ex.Message); + this.Errored(ref ex); + if (this.ScheduleHistoryItem.ScheduleSource != ScheduleSource.STARTED_FROM_BEGIN_REQUEST) { Exceptions.Exceptions.LogException(ex); } diff --git a/DNN Platform/Library/Services/Search/SearchItemInfo.cs b/DNN Platform/Library/Services/Search/SearchItemInfo.cs index daf739c3356..ff3b046f3e2 100644 --- a/DNN Platform/Library/Services/Search/SearchItemInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchItemInfo.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke /// Class: SearchItemInfo /// ----------------------------------------------------------------------------- /// - /// The SearchItemInfo represents a Search Item + /// The SearchItemInfo represents a Search Item. /// /// /// @@ -45,7 +40,7 @@ public SearchItemInfo() } public SearchItemInfo(string Title, string Description, int Author, DateTime PubDate, int ModuleID, string SearchKey, string Content) - : this(Title, Description, Author, PubDate, ModuleID, SearchKey, Content, "", Null.NullInteger) + : this(Title, Description, Author, PubDate, ModuleID, SearchKey, Content, string.Empty, Null.NullInteger) { } @@ -55,49 +50,49 @@ public SearchItemInfo(string Title, string Description, int Author, DateTime Pub } public SearchItemInfo(string Title, string Description, int Author, DateTime PubDate, int ModuleID, string SearchKey, string Content, int Image) - : this(Title, Description, Author, PubDate, ModuleID, SearchKey, Content, "", Image) + : this(Title, Description, Author, PubDate, ModuleID, SearchKey, Content, string.Empty, Image) { } public SearchItemInfo(string Title, string Description, int Author, DateTime PubDate, int ModuleID, string SearchKey, string Content, string Guid, int Image) { - _Title = Title; - _Description = Description; - _Author = Author; - _PubDate = PubDate; - _ModuleId = ModuleID; - _SearchKey = SearchKey; - _Content = Content; - _GUID = Guid; - _ImageFileId = Image; - _HitCount = 0; + this._Title = Title; + this._Description = Description; + this._Author = Author; + this._PubDate = PubDate; + this._ModuleId = ModuleID; + this._SearchKey = SearchKey; + this._Content = Content; + this._GUID = Guid; + this._ImageFileId = Image; + this._HitCount = 0; } public SearchItemInfo(string Title, string Description, int Author, DateTime PubDate, int ModuleID, string SearchKey, string Content, string Guid, int Image, int TabID) { - _Title = Title; - _Description = Description; - _Author = Author; - _PubDate = PubDate; - _ModuleId = ModuleID; - _SearchKey = SearchKey; - _Content = Content; - _GUID = Guid; - _ImageFileId = Image; - _HitCount = 0; - _TabId = TabID; - } - - + this._Title = Title; + this._Description = Description; + this._Author = Author; + this._PubDate = PubDate; + this._ModuleId = ModuleID; + this._SearchKey = SearchKey; + this._Content = Content; + this._GUID = Guid; + this._ImageFileId = Image; + this._HitCount = 0; + this._TabId = TabID; + } + public int SearchItemId { get { - return _SearchItemId; + return this._SearchItemId; } + set { - _SearchItemId = value; + this._SearchItemId = value; } } @@ -105,11 +100,12 @@ public string Title { get { - return _Title; + return this._Title; } + set { - _Title = value; + this._Title = value; } } @@ -117,11 +113,12 @@ public string Description { get { - return _Description; + return this._Description; } + set { - _Description = value; + this._Description = value; } } @@ -129,11 +126,12 @@ public int Author { get { - return _Author; + return this._Author; } + set { - _Author = value; + this._Author = value; } } @@ -141,11 +139,12 @@ public DateTime PubDate { get { - return _PubDate; + return this._PubDate; } + set { - _PubDate = value; + this._PubDate = value; } } @@ -153,11 +152,12 @@ public int ModuleId { get { - return _ModuleId; + return this._ModuleId; } + set { - _ModuleId = value; + this._ModuleId = value; } } @@ -165,11 +165,12 @@ public string SearchKey { get { - return _SearchKey; + return this._SearchKey; } + set { - _SearchKey = value; + this._SearchKey = value; } } @@ -177,11 +178,12 @@ public string Content { get { - return _Content; + return this._Content; } + set { - _Content = value; + this._Content = value; } } @@ -189,11 +191,12 @@ public string GUID { get { - return _GUID; + return this._GUID; } + set { - _GUID = value; + this._GUID = value; } } @@ -201,11 +204,12 @@ public int ImageFileId { get { - return _ImageFileId; + return this._ImageFileId; } + set { - _ImageFileId = value; + this._ImageFileId = value; } } @@ -213,11 +217,12 @@ public int HitCount { get { - return _HitCount; + return this._HitCount; } + set { - _HitCount = value; + this._HitCount = value; } } @@ -225,11 +230,12 @@ public int TabId { get { - return _TabId; + return this._TabId; } + set { - _TabId = value; + this._TabId = value; } } } diff --git a/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs index 0335363b58d..d43169bf4ba 100644 --- a/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke @@ -25,47 +20,45 @@ namespace DotNetNuke.Services.Search [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] [Serializable] public class SearchItemInfoCollection : CollectionBase - { - #region "Constructors" - - /// + { + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollection class. /// public SearchItemInfoCollection() { - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollection class containing the elements of the specified source collection. /// /// A SearchItemInfoCollection with which to initialize the collection. public SearchItemInfoCollection(SearchItemInfoCollection value) { - AddRange(value); - } - - /// + this.AddRange(value); + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollection class containing the specified array of SearchItemInfo objects. /// /// An array of SearchItemInfo objects with which to initialize the collection. public SearchItemInfoCollection(SearchItemInfo[] value) { - AddRange(value); - } - - /// + this.AddRange(value); + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollectionSearchItemInfoCollection class containing the specified array of SearchItemInfo objects. /// /// An arraylist of SearchItemInfo objects with which to initialize the collection. public SearchItemInfoCollection(ArrayList value) { - AddRange(value); - } - - #endregion - - #region "Properties" - + this.AddRange(value); + } + /// /// Gets the SearchItemInfoCollection at the specified index in the collection. /// @@ -76,25 +69,23 @@ public SearchItemInfo this[int index] { get { - return (SearchItemInfo) List[index]; + return (SearchItemInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } - } - - #endregion - - #region "Public Methods" - + } + /// /// Add an element of the specified SearchItemInfo to the end of the collection. /// - /// An object of type SearchItemInfo to add to the collection. + /// An object of type SearchItemInfo to add to the collection. + /// public int Add(SearchItemInfo value) { - return List.Add(value); + return this.List.Add(value); } /// @@ -104,17 +95,17 @@ public int Add(SearchItemInfo value) /// The index in the collection of the specified object, if found; otherwise, -1. public int IndexOf(SearchItemInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } /// /// Add an element of the specified SearchItemInfo to the collection at the designated index. /// - /// An Integer to indicate the location to add the object to the collection. + /// An Integer to indicate the location to add the object to the collection. /// An object of type SearchItemInfo to add to the collection. public void Insert(int index, SearchItemInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } /// @@ -123,7 +114,7 @@ public void Insert(int index, SearchItemInfo value) /// An object of type SearchItemInfo to remove to the collection. public void Remove(SearchItemInfo value) { - List.Remove(value); + this.List.Remove(value); } /// @@ -133,7 +124,7 @@ public void Remove(SearchItemInfo value) /// true if the collection contains the specified object; otherwise, false. public bool Contains(SearchItemInfo value) { - return List.Contains(value); + return this.List.Contains(value); } /// @@ -144,7 +135,7 @@ public void AddRange(SearchItemInfo[] value) { for (int i = 0; i <= value.Length - 1; i++) { - Add(value[i]); + this.Add(value[i]); } } @@ -158,7 +149,7 @@ public void AddRange(ArrayList value) { if (obj is SearchItemInfo) { - Add((SearchItemInfo) obj); + this.Add((SearchItemInfo)obj); } } } @@ -171,7 +162,7 @@ public void AddRange(SearchItemInfoCollection value) { for (int i = 0; i <= value.Count - 1; i++) { - Add((SearchItemInfo) value.List[i]); + this.Add((SearchItemInfo)value.List[i]); } } @@ -182,17 +173,17 @@ public void AddRange(SearchItemInfoCollection value) /// The index of the array at which to begin inserting. public void CopyTo(SearchItemInfo[] array, int index) { - List.CopyTo(array, index); + this.List.CopyTo(array, index); } /// /// Creates a one-dimensional Array instance containing the collection items. /// - /// Array of type SearchItemInfo + /// Array of type SearchItemInfo. public SearchItemInfo[] ToArray() { - var arr = new SearchItemInfo[Count]; - CopyTo(arr, 0); + var arr = new SearchItemInfo[this.Count]; + this.CopyTo(arr, 0); return arr; } @@ -207,9 +198,8 @@ public SearchItemInfoCollection ModuleItems(int ModuleId) retValue.Add(info); } } + return retValue; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Search/SearchResultsInfo.cs b/DNN Platform/Library/Services/Search/SearchResultsInfo.cs index 57c41be7c4a..2b6026dbe5c 100644 --- a/DNN Platform/Library/Services/Search/SearchResultsInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchResultsInfo.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke /// Class: SearchResultsInfo /// ----------------------------------------------------------------------------- /// - /// The SearchResultsInfo represents a Search Result Item + /// The SearchResultsInfo represents a Search Result Item. /// /// /// @@ -45,11 +40,12 @@ public int SearchItemID { get { - return m_SearchItemID; + return this.m_SearchItemID; } + set { - m_SearchItemID = value; + this.m_SearchItemID = value; } } @@ -57,11 +53,12 @@ public string Title { get { - return m_Title; + return this.m_Title; } + set { - m_Title = value; + this.m_Title = value; } } @@ -69,11 +66,12 @@ public string Description { get { - return m_Description; + return this.m_Description; } + set { - m_Description = value; + this.m_Description = value; } } @@ -81,11 +79,12 @@ public string Author { get { - return m_Author; + return this.m_Author; } + set { - m_Author = value; + this.m_Author = value; } } @@ -93,11 +92,12 @@ public DateTime PubDate { get { - return m_PubDate; + return this.m_PubDate; } + set { - m_PubDate = value; + this.m_PubDate = value; } } @@ -105,11 +105,12 @@ public string Guid { get { - return m_Guid; + return this.m_Guid; } + set { - m_Guid = value; + this.m_Guid = value; } } @@ -117,11 +118,12 @@ public int Image { get { - return m_Image; + return this.m_Image; } + set { - m_Image = value; + this.m_Image = value; } } @@ -129,11 +131,12 @@ public int TabId { get { - return m_TabId; + return this.m_TabId; } + set { - m_TabId = value; + this.m_TabId = value; } } @@ -141,11 +144,12 @@ public string SearchKey { get { - return m_SearchKey; + return this.m_SearchKey; } + set { - m_SearchKey = value; + this.m_SearchKey = value; } } @@ -153,11 +157,12 @@ public int Occurrences { get { - return m_Occurrences; + return this.m_Occurrences; } + set { - m_Occurrences = value; + this.m_Occurrences = value; } } @@ -165,11 +170,12 @@ public int Relevance { get { - return m_Relevance; + return this.m_Relevance; } + set { - m_Relevance = value; + this.m_Relevance = value; } } @@ -177,11 +183,12 @@ public int ModuleId { get { - return m_ModuleId; + return this.m_ModuleId; } + set { - m_ModuleId = value; + this.m_ModuleId = value; } } @@ -189,11 +196,12 @@ public bool Delete { get { - return m_Delete; + return this.m_Delete; } + set { - m_Delete = value; + this.m_Delete = value; } } @@ -201,11 +209,12 @@ public string AuthorName { get { - return m_AuthorName; + return this.m_AuthorName; } + set { - m_AuthorName = value; + this.m_AuthorName = value; } } @@ -213,11 +222,12 @@ public int PortalId { get { - return m_PortalId; + return this.m_PortalId; } + set { - m_PortalId = value; + this.m_PortalId = value; } } } diff --git a/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs index b1c30c7bc04..eca03620cd9 100644 --- a/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke @@ -25,47 +20,45 @@ namespace DotNetNuke.Services.Search [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] [Serializable] public class SearchResultsInfoCollection : CollectionBase - { - #region "Constructors" - - /// + { + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class. /// public SearchResultsInfoCollection() { - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class containing the elements of the specified source collection. /// /// A SearchResultsInfoCollection with which to initialize the collection. public SearchResultsInfoCollection(SearchResultsInfoCollection value) { - AddRange(value); - } - - /// + this.AddRange(value); + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class containing the specified array of SearchResultsInfo objects. /// /// An array of SearchResultsInfo objects with which to initialize the collection. public SearchResultsInfoCollection(SearchResultsInfo[] value) { - AddRange(value); - } - - /// + this.AddRange(value); + } + + /// + /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class containing the specified array of SearchResultsInfo objects. /// /// An array of SearchResultsInfo objects with which to initialize the collection. public SearchResultsInfoCollection(ArrayList value) { - AddRange(value); - } - - #endregion - - #region "Properties" - + this.AddRange(value); + } + /// /// Gets the SearchResultsInfoCollection at the specified index in the collection. /// @@ -76,25 +69,23 @@ public SearchResultsInfo this[int index] { get { - return (SearchResultsInfo) List[index]; + return (SearchResultsInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } - } - - #endregion - - #region "Public Methods" - + } + /// /// Add an element of the specified SearchResultsInfo to the end of the collection. /// - /// An object of type SearchResultsInfo to add to the collection. + /// An object of type SearchResultsInfo to add to the collection. + /// public int Add(SearchResultsInfo value) { - return List.Add(value); + return this.List.Add(value); } /// @@ -104,17 +95,17 @@ public int Add(SearchResultsInfo value) /// The index in the collection of the specified object, if found; otherwise, -1. public int IndexOf(SearchResultsInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } /// /// Add an element of the specified SearchResultsInfo to the collection at the designated index. /// - /// An Integer to indicate the location to add the object to the collection. + /// An Integer to indicate the location to add the object to the collection. /// An object of type SearchResultsInfo to add to the collection. public void Insert(int index, SearchResultsInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } /// @@ -123,7 +114,7 @@ public void Insert(int index, SearchResultsInfo value) /// An object of type SearchResultsInfo to remove to the collection. public void Remove(SearchResultsInfo value) { - List.Remove(value); + this.List.Remove(value); } /// @@ -133,7 +124,7 @@ public void Remove(SearchResultsInfo value) /// true if the collection contains the specified object; otherwise, false. public bool Contains(SearchResultsInfo value) { - return List.Contains(value); + return this.List.Contains(value); } /// @@ -144,7 +135,7 @@ public void AddRange(SearchResultsInfo[] value) { for (int i = 0; i <= value.Length - 1; i++) { - Add(value[i]); + this.Add(value[i]); } } @@ -158,7 +149,7 @@ public void AddRange(ArrayList value) { if (obj is SearchResultsInfo) { - Add((SearchResultsInfo) obj); + this.Add((SearchResultsInfo)obj); } } } @@ -171,7 +162,7 @@ public void AddRange(SearchResultsInfoCollection value) { for (int i = 0; i <= value.Count - 1; i++) { - Add((SearchResultsInfo) value.List[i]); + this.Add((SearchResultsInfo)value.List[i]); } } @@ -182,20 +173,18 @@ public void AddRange(SearchResultsInfoCollection value) /// The index of the array at which to begin inserting. public void CopyTo(SearchResultsInfo[] array, int index) { - List.CopyTo(array, index); + this.List.CopyTo(array, index); } /// /// Creates a one-dimensional Array instance containing the collection items. /// - /// Array of type SearchResultsInfo + /// Array of type SearchResultsInfo. public SearchResultsInfo[] ToArray() { - var arr = new SearchResultsInfo[Count]; - CopyTo(arr, 0); + var arr = new SearchResultsInfo[this.Count]; + this.CopyTo(arr, 0); return arr; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Search/TabIndexer.cs b/DNN Platform/Library/Services/Search/TabIndexer.cs index b14d7ffa19f..034e12196fe 100644 --- a/DNN Platform/Library/Services/Search/TabIndexer.cs +++ b/DNN Platform/Library/Services/Search/TabIndexer.cs @@ -1,23 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Collections.Generic; -using DotNetNuke.Common; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.Index @@ -25,12 +21,12 @@ namespace DotNetNuke.Services.Search /// ----------------------------------------------------------------------------- /// /// The TabIndexer is an implementation of the abstract IndexingProvider - /// class + /// class. /// /// /// /// ----------------------------------------------------------------------------- - public class TabIndexer : IndexingProvider + public class TabIndexer : IndexingProviderBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabIndexer)); private static readonly int TabSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("tab").SearchTypeId; @@ -40,19 +36,22 @@ public class TabIndexer : IndexingProvider /// Returns the number of SearchDocuments indexed with Tab MetaData for the given portal. /// /// This replaces "GetSearchIndexItems" as a newer implementation of search. + /// /// ----------------------------------------------------------------------------- - public override int IndexSearchDocuments(int portalId, + public override int IndexSearchDocuments( + int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer) { Requires.NotNull("indexer", indexer); const int saveThreshold = 1024; var totalIndexed = 0; - startDateLocal = GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal); + startDateLocal = this.GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal); var searchDocuments = new List(); var tabs = ( from t in TabController.Instance.GetTabsByPortal(portalId).AsList() where t.LastModifiedOnDate > startDateLocal && (t.TabSettings["AllowIndex"] == null || - "true".Equals(t.TabSettings["AllowIndex"].ToString(), + "true".Equals( + t.TabSettings["AllowIndex"].ToString(), StringComparison.CurrentCultureIgnoreCase)) select t).OrderBy(t => t.LastModifiedOnDate).ThenBy(t => t.TabID).ToArray(); @@ -67,7 +66,7 @@ from t in TabController.Instance.GetTabsByPortal(portalId).AsList() if (searchDocuments.Count >= saveThreshold) { - totalIndexed += IndexCollectedDocs(indexer, searchDocuments, portalId, schedule.ScheduleID); + totalIndexed += this.IndexCollectedDocs(indexer, searchDocuments, portalId, schedule.ScheduleID); } } catch (Exception ex) @@ -78,7 +77,7 @@ from t in TabController.Instance.GetTabsByPortal(portalId).AsList() if (searchDocuments.Count > 0) { - totalIndexed += IndexCollectedDocs(indexer, searchDocuments, portalId, schedule.ScheduleID); + totalIndexed += this.IndexCollectedDocs(indexer, searchDocuments, portalId, schedule.ScheduleID); } } @@ -96,12 +95,12 @@ private static SearchDocument GetTabSearchDocument(TabInfo tab) CultureCode = tab.CultureCode, ModifiedTimeUtc = tab.LastModifiedOnDate.ToUniversalTime(), Body = string.Empty, - Description = tab.Description + Description = tab.Description, }; searchDoc.Keywords.Add("keywords", tab.KeyWords); - //Using TabName for searchDoc.Title due to higher prevalence and relavency || TabTitle will be stored as a keyword + // Using TabName for searchDoc.Title due to higher prevalence and relavency || TabTitle will be stored as a keyword searchDoc.Title = tab.TabName; searchDoc.Keywords.Add("title", tab.Title); @@ -118,20 +117,15 @@ private static SearchDocument GetTabSearchDocument(TabInfo tab) return searchDoc; } - private int IndexCollectedDocs(Action> indexer, + private int IndexCollectedDocs( + Action> indexer, ICollection searchDocuments, int portalId, int scheduleId) { indexer.Invoke(searchDocuments); var total = searchDocuments.Count; - SetLocalTimeOfLastIndexedItem(portalId, scheduleId, searchDocuments.Last().ModifiedTimeUtc); + this.SetLocalTimeOfLastIndexedItem(portalId, scheduleId, searchDocuments.Last().ModifiedTimeUtc); searchDocuments.Clear(); return total; } - - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - public override SearchItemInfoCollection GetSearchIndexItems(int portalId) - { - return null; - } } } diff --git a/DNN Platform/Library/Services/Search/UserIndexer.cs b/DNN Platform/Library/Services/Search/UserIndexer.cs index a76062de30d..395fecfc272 100644 --- a/DNN Platform/Library/Services/Search/UserIndexer.cs +++ b/DNN Platform/Library/Services/Search/UserIndexer.cs @@ -1,33 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Data.SqlTypes; -using System.Linq; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; -using Lucene.Net.QueryParsers; -using Lucene.Net.Search; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { + using System; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlTypes; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using Lucene.Net.QueryParsers; + using Lucene.Net.Search; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke.Search.Index @@ -35,43 +31,37 @@ namespace DotNetNuke.Services.Search /// ----------------------------------------------------------------------------- /// /// The TabIndexer is an implementation of the abstract IndexingProvider - /// class + /// class. /// /// /// /// ----------------------------------------------------------------------------- - public class UserIndexer : IndexingProvider + public class UserIndexer : IndexingProviderBase { internal const string UserIndexResetFlag = "UserIndexer_ReIndex"; internal const string ValueSplitFlag = "$$$"; - internal static readonly Regex UsrFirstNameSplitRx = new Regex(Regex.Escape(ValueSplitFlag), RegexOptions.Compiled); - - #region Private Properties - + internal static readonly Regex UsrFirstNameSplitRx = new Regex(Regex.Escape(ValueSplitFlag), RegexOptions.Compiled); private const int BatchSize = 250; private const int ClauseMaxCount = 1024; - private static readonly int UserSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; - - #endregion - - #region Override Methods - + private static readonly int UserSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; + /// ----------------------------------------------------------------------------- /// /// Searches for and indexes modified users for the given portal. /// - /// Count of indexed records + /// Count of indexed records. /// ----------------------------------------------------------------------------- - public override int IndexSearchDocuments(int portalId, + public override int IndexSearchDocuments( + int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer) { Requires.NotNull("indexer", indexer); const int saveThreshold = BatchSize; var totalIndexed = 0; var checkpointModified = false; - startDateLocal = GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal); + startDateLocal = this.GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal); var searchDocuments = new Dictionary(); var needReindex = PortalController.GetPortalSettingAsBoolean(UserIndexResetFlag, portalId, false); @@ -93,7 +83,7 @@ public override int IndexSearchDocuments(int portalId, try { int startUserId; - var checkpointData = GetLastCheckpointData(portalId, schedule.ScheduleID); + var checkpointData = this.GetLastCheckpointData(portalId, schedule.ScheduleID); if (string.IsNullOrEmpty(checkpointData) || !int.TryParse(checkpointData, out startUserId)) { startUserId = Null.NullInteger; @@ -108,23 +98,24 @@ public override int IndexSearchDocuments(int portalId, if (rowsAffected > 0 && searchDocuments.Count >= saveThreshold) { - //remove existing indexes + // remove existing indexes DeleteDocuments(portalId, indexedUsers); var values = searchDocuments.Values; - totalIndexed += IndexCollectedDocs(indexer, values); - SetLastCheckpointData(portalId, schedule.ScheduleID, startUserId.ToString()); - SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, values.Last().ModifiedTimeUtc.ToLocalTime()); + totalIndexed += this.IndexCollectedDocs(indexer, values); + this.SetLastCheckpointData(portalId, schedule.ScheduleID, startUserId.ToString()); + this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, values.Last().ModifiedTimeUtc.ToLocalTime()); searchDocuments.Clear(); checkpointModified = true; } - } while (rowsAffected > 0); + } + while (rowsAffected > 0); if (searchDocuments.Count > 0) { - //remove existing indexes + // remove existing indexes DeleteDocuments(portalId, indexedUsers); var values = searchDocuments.Values; - totalIndexed += IndexCollectedDocs(indexer, values); + totalIndexed += this.IndexCollectedDocs(indexer, values); checkpointModified = true; } @@ -142,19 +133,13 @@ public override int IndexSearchDocuments(int portalId, if (checkpointModified) { // at last reset start user pointer - SetLastCheckpointData(portalId, schedule.ScheduleID, Null.NullInteger.ToString()); - SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, DateTime.Now); + this.SetLastCheckpointData(portalId, schedule.ScheduleID, Null.NullInteger.ToString()); + this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, DateTime.Now); } + return totalIndexed; } - private int IndexCollectedDocs(Action> indexer, ICollection searchDocuments) - { - indexer.Invoke(searchDocuments); - var total = searchDocuments.Select(d => d.UniqueKey.Substring(0, d.UniqueKey.IndexOf("_", StringComparison.Ordinal))).Distinct().Count(); - return total; - } - private static int FindModifiedUsers(int portalId, DateTime startDateLocal, IDictionary searchDocuments, IList profileDefinitions, out IList indexedUsers, ref int startUserId) @@ -166,11 +151,14 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, while (reader.Read()) { var userSearch = GetUserSearch(reader); - if (userSearch == null) continue; - + if (userSearch == null) + { + continue; + } + AddBasicInformation(searchDocuments, indexedUsers, userSearch, portalId); - //log the userid so that it can get the correct user collection next time. + // log the userid so that it can get the correct user collection next time. if (userSearch.UserId > startUserId) { startUserId = userSearch.UserId; @@ -195,7 +183,7 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, var splitValues = Regex.Split(propertyValue, Regex.Escape(ValueSplitFlag)); propertyValue = splitValues[0]; - var visibilityMode = ((UserVisibilityMode)Convert.ToInt32(splitValues[1])); + var visibilityMode = (UserVisibilityMode)Convert.ToInt32(splitValues[1]); var extendedVisibility = splitValues[2]; var modifiedTime = Convert.ToDateTime(splitValues[3]).ToUniversalTime(); @@ -204,7 +192,7 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, continue; } - //DNN-5740 / DNN-9040: replace split flag if it included in property value. + // DNN-5740 / DNN-9040: replace split flag if it included in property value. propertyValue = propertyValue.Replace("[$]", "$"); var uniqueKey = string.Format("{0}_{1}", userSearch.UserId, visibilityMode).ToLowerInvariant(); if (visibilityMode == UserVisibilityMode.FriendsAndGroups) @@ -224,7 +212,7 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, } else { - //Need remove use exists index for all visibilities. + // Need remove use exists index for all visibilities. if (!indexedUsers.Contains(userSearch.UserId)) { indexedUsers.Add(userSearch.UserId); @@ -239,7 +227,7 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, PortalId = portalId, ModifiedTimeUtc = modifiedTime, Description = userSearch.FirstName, - Title = userSearch.DisplayName + Title = userSearch.DisplayName, }; searchDoc.Keywords.Add(propertyName, propertyValue); searchDoc.NumericKeys.Add("superuser", Convert.ToInt32(userSearch.SuperUser)); @@ -251,6 +239,7 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, rowsAffected++; } } + return rowsAffected; } @@ -264,8 +253,9 @@ private static void AddBasicInformation(IDictionary sear { indexedUsers.Add(userSearch.UserId); } - //if the user doesn't exist in search collection, we need add it with ALLUsers mode, - //so that can make sure DisplayName will be indexed + + // if the user doesn't exist in search collection, we need add it with ALLUsers mode, + // so that can make sure DisplayName will be indexed var searchDoc = new SearchDocument { SearchTypeId = UserSearchTypeId, @@ -276,7 +266,7 @@ private static void AddBasicInformation(IDictionary sear ModifiedTimeUtc = userSearch.LastModifiedOnDate, Body = string.Empty, Description = userSearch.FirstName, - Title = userSearch.DisplayName + Title = userSearch.DisplayName, }; searchDoc.NumericKeys.Add("superuser", Convert.ToInt32(userSearch.SuperUser)); searchDocuments.Add(searchDoc.UniqueKey, searchDoc); @@ -290,8 +280,9 @@ private static void AddBasicInformation(IDictionary sear { indexedUsers.Add(userSearch.UserId); } - //if the user doesn't exist in search collection, we need add it with ALLUsers mode, - //so that can make sure DisplayName will be indexed + + // if the user doesn't exist in search collection, we need add it with ALLUsers mode, + // so that can make sure DisplayName will be indexed var searchDoc = new SearchDocument { SearchTypeId = UserSearchTypeId, @@ -302,7 +293,7 @@ private static void AddBasicInformation(IDictionary sear ModifiedTimeUtc = userSearch.LastModifiedOnDate, Body = string.Empty, Description = userSearch.FirstName, - Title = userSearch.DisplayName + Title = userSearch.DisplayName, }; searchDoc.NumericKeys.Add("superuser", Convert.ToInt32(userSearch.SuperUser)); @@ -313,6 +304,13 @@ private static void AddBasicInformation(IDictionary sear } } + private int IndexCollectedDocs(Action> indexer, ICollection searchDocuments) + { + indexer.Invoke(searchDocuments); + var total = searchDocuments.Select(d => d.UniqueKey.Substring(0, d.UniqueKey.IndexOf("_", StringComparison.Ordinal))).Distinct().Count(); + return total; + } + private static UserSearch GetUserSearch(IDataRecord reader) { try @@ -327,7 +325,7 @@ private static UserSearch GetUserSearch(IDataRecord reader) UserName = reader["Username"].ToString(), SuperUser = Convert.ToBoolean(reader["IsSuperUser"]), LastModifiedOnDate = Convert.ToDateTime(modifiedOn).ToUniversalTime(), - CreatedOnDate = Convert.ToDateTime(createdOn).ToUniversalTime() + CreatedOnDate = Convert.ToDateTime(createdOn).ToUniversalTime(), }; if (!string.IsNullOrEmpty(userSearch.FirstName) && userSearch.FirstName.Contains(ValueSplitFlag)) @@ -342,12 +340,8 @@ private static UserSearch GetUserSearch(IDataRecord reader) Exceptions.Exceptions.LogException(ex); return null; } - } - - #endregion - - #region Private Methods - + } + private static void DeleteDocuments(int portalId, ICollection usersList) { if (usersList == null || usersList.Count == 0) @@ -355,7 +349,7 @@ private static void DeleteDocuments(int portalId, ICollection usersList) return; } - var values = Enum.GetValues(typeof (UserVisibilityMode)); + var values = Enum.GetValues(typeof(UserVisibilityMode)); var clauseCount = 0; foreach (var item in values) @@ -363,12 +357,13 @@ private static void DeleteDocuments(int portalId, ICollection usersList) var keyword = new StringBuilder("("); foreach (var userId in usersList) { - var mode = Enum.GetName(typeof (UserVisibilityMode), item); + var mode = Enum.GetName(typeof(UserVisibilityMode), item); keyword.AppendFormat("{2} {0}_{1} OR {0}_{1}* ", userId, mode, keyword.Length > 1 ? "OR " : string.Empty); clauseCount += 2; - if (clauseCount >= ClauseMaxCount) - //max cluaseCount is 1024, if reach the max value, perform a delete action. + if (clauseCount >= ClauseMaxCount) + + // max cluaseCount is 1024, if reach the max value, perform a delete action. { keyword.Append(")"); PerformDelete(portalId, keyword.ToString().ToLowerInvariant()); @@ -389,11 +384,11 @@ private static void PerformDelete(int portalId, string keyword) { var query = new BooleanQuery { - {NumericRangeQuery.NewIntRange(Constants.PortalIdTag, portalId, portalId, true, true), Occur.MUST}, + { NumericRangeQuery.NewIntRange(Constants.PortalIdTag, portalId, portalId, true, true), Occur.MUST }, { NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, UserSearchTypeId, UserSearchTypeId, true, true), Occur.MUST - } + }, }; var parserContent = new QueryParser(Constants.LuceneVersion, Constants.UniqueKeyTag, @@ -408,31 +403,25 @@ private static bool ContainsColumn(string col, IDataReader reader) { var schema = reader.GetSchemaTable(); return schema != null && schema.Select("ColumnName = '" + col + "'").Length > 0; - } - - #endregion - - #region Obsoleted Methods - - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - public override SearchItemInfoCollection GetSearchIndexItems(int portalId) - { - return null; - } - - #endregion - + } } internal class UserSearch { public int UserId { get; set; } + public string DisplayName { get; set; } + public string FirstName { get; set; } + public string Email { get; set; } + public string UserName { get; set; } + public bool SuperUser { get; set; } + public DateTime LastModifiedOnDate { get; set; } + public DateTime CreatedOnDate { get; set; } } } diff --git a/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs b/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs index 3b8221411c7..cc3365021c8 100644 --- a/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs +++ b/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs @@ -1,116 +1,187 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Sitemap { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + public class CoreSitemapProvider : SitemapProvider { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CoreSitemapProvider)); private bool includeHiddenPages; private float minPagePriority; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CoreSitemapProvider)); private bool useLevelBasedPagePriority; /// - /// Includes page urls on the sitemap + /// Includes page urls on the sitemap. /// /// /// Pages that are included: /// - are not deleted /// - are not disabled /// - are normal pages (not links,...) - /// - are visible (based on date and permissions) + /// - are visible (based on date and permissions). /// + /// public override List GetUrls(int portalId, PortalSettings ps, string version) { SitemapUrl pageUrl = null; var urls = new List(); - useLevelBasedPagePriority = bool.Parse(PortalController.GetPortalSetting("SitemapLevelMode", portalId, "False")); - minPagePriority = float.Parse(PortalController.GetPortalSetting("SitemapMinPriority", portalId, "0.1"), CultureInfo.InvariantCulture); - includeHiddenPages = bool.Parse(PortalController.GetPortalSetting("SitemapIncludeHidden", portalId, "True")); + this.useLevelBasedPagePriority = bool.Parse(PortalController.GetPortalSetting("SitemapLevelMode", portalId, "False")); + this.minPagePriority = float.Parse(PortalController.GetPortalSetting("SitemapMinPriority", portalId, "0.1"), CultureInfo.InvariantCulture); + this.includeHiddenPages = bool.Parse(PortalController.GetPortalSetting("SitemapIncludeHidden", portalId, "True")); var currentLanguage = ps.CultureCode; if (string.IsNullOrEmpty(currentLanguage)) { - currentLanguage = Localization.Localization.GetPageLocale(ps).Name; + currentLanguage = Localization.GetPageLocale(ps).Name; } + var languagePublished = LocaleController.Instance.GetLocale(ps.PortalId, currentLanguage).IsPublished; - var tabs = TabController.Instance.GetTabsByPortal(portalId).Values - .Where(t => !t.IsSystem - && !ps.ContentLocalizationEnabled || (languagePublished && t.CultureCode.Equals(currentLanguage, StringComparison.InvariantCultureIgnoreCase))); - foreach (TabInfo tab in tabs) - { - try - { - if (!tab.IsDeleted && !tab.DisableLink && tab.TabType == TabType.Normal && - (Null.IsNull(tab.StartDate) || tab.StartDate < DateTime.Now) && - (Null.IsNull(tab.EndDate) || tab.EndDate > DateTime.Now) && IsTabPublic(tab.TabPermissions)) - { - if ((includeHiddenPages || tab.IsVisible) && tab.HasBeenPublished) - { - try - { - pageUrl = GetPageUrl(tab, currentLanguage, ps); - urls.Add(pageUrl); - } - catch (Exception) - { - Logger.ErrorFormat("Error has occurred getting PageUrl for {0}", tab.TabName); - } - } - } - } - catch (Exception ex) - { - Services.Exceptions.Exceptions.LogException(new Exception(Localization.Localization.GetExceptionMessage("SitemapUrlGenerationError", - "URL sitemap generation for page '{0} - {1}' caused an exception: {2}", - tab.TabID, tab.TabName, ex.Message))); - } - } + var tabs = TabController.Instance.GetTabsByPortal(portalId).Values + .Where(t => (!t.IsSystem + && !ps.ContentLocalizationEnabled) || (languagePublished && t.CultureCode.Equals(currentLanguage, StringComparison.InvariantCultureIgnoreCase))); + foreach (TabInfo tab in tabs) + { + try + { + if (!tab.IsDeleted && !tab.DisableLink && tab.TabType == TabType.Normal && + (Null.IsNull(tab.StartDate) || tab.StartDate < DateTime.Now) && + (Null.IsNull(tab.EndDate) || tab.EndDate > DateTime.Now) && this.IsTabPublic(tab.TabPermissions)) + { + if ((this.includeHiddenPages || tab.IsVisible) && tab.HasBeenPublished) + { + try + { + pageUrl = this.GetPageUrl(tab, currentLanguage, ps); + urls.Add(pageUrl); + } + catch (Exception) + { + Logger.ErrorFormat("Error has occurred getting PageUrl for {0}", tab.TabName); + } + } + } + } + catch (Exception ex) + { + Services.Exceptions.Exceptions.LogException(new Exception(Localization.GetExceptionMessage( + "SitemapUrlGenerationError", + "URL sitemap generation for page '{0} - {1}' caused an exception: {2}", + tab.TabID, tab.TabName, ex.Message))); + } + } return urls; } + public virtual bool IsTabPublic(TabPermissionCollection objTabPermissions) + { + string roles = objTabPermissions.ToString("VIEW"); + bool hasPublicRole = false; + + if (roles != null) + { + // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance + foreach (string role in roles.Split(new[] { ';' })) + { + if (!string.IsNullOrEmpty(role)) + { + // Deny permission + if (role.StartsWith("!")) + { + string denyRole = role.Replace("!", string.Empty); + if (denyRole == Globals.glbRoleUnauthUserName || denyRole == Globals.glbRoleAllUsersName) + { + hasPublicRole = false; + break; + } + + // Grant permission + } + else + { + if (role == Globals.glbRoleUnauthUserName || role == Globals.glbRoleAllUsersName) + { + hasPublicRole = true; + break; + } + } + } + } + } + + return hasPublicRole; + } + /// - /// Return the sitemap url node for the page + /// When page level priority is used, the priority for each page will be computed from + /// the hierarchy level of the page. + /// Top level pages will have a value of 1, second level 0.9, third level 0.8, ... /// - /// The page being indexed - /// Culture code to use in the URL - /// A SitemapUrl object for the current page + /// The page being indexed. + /// The priority assigned to the page. + /// + /// + protected float GetPriority(TabInfo objTab) + { + float priority = objTab.SiteMapPriority; + + if (this.useLevelBasedPagePriority) + { + if (objTab.Level >= 9) + { + priority = 0.1F; + } + else + { + priority = Convert.ToSingle(1 - (objTab.Level * 0.1)); + } + + if (priority < this.minPagePriority) + { + priority = this.minPagePriority; + } + } + + return priority; + } + + /// + /// Return the sitemap url node for the page. + /// + /// The page being indexed. + /// Culture code to use in the URL. + /// A SitemapUrl object for the current page. /// /// private SitemapUrl GetPageUrl(TabInfo objTab, string language, PortalSettings ps) { var pageUrl = new SitemapUrl(); - var url = TestableGlobals.Instance.NavigateURL(objTab.TabID, objTab.IsSuperTab, ps, "", language); + var url = TestableGlobals.Instance.NavigateURL(objTab.TabID, objTab.IsSuperTab, ps, string.Empty, language); if ((ps.SSLEnforced || (objTab.IsSecure && ps.SSLEnabled)) && url.StartsWith("http://")) { url = "https://" + url.Substring("http://".Length); } + pageUrl.Url = url; - pageUrl.Priority = GetPriority(objTab); + pageUrl.Priority = this.GetPriority(objTab); pageUrl.LastModified = objTab.LastModifiedOnDate; foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(objTab.TabID).Values) { @@ -119,6 +190,7 @@ private SitemapUrl GetPageUrl(TabInfo objTab, string language, PortalSettings ps pageUrl.LastModified = m.LastModifiedOnDate; } } + pageUrl.ChangeFrequency = SitemapChangeFrequency.Daily; // support for alternate pages: https://support.google.com/webmasters/answer/2620865?hl=en @@ -128,21 +200,23 @@ private SitemapUrl GetPageUrl(TabInfo objTab, string language, PortalSettings ps TabInfo currentTab = objTab; if (!objTab.IsDefaultLanguage) + { currentTab = objTab.DefaultLanguageTab; + } foreach (TabInfo localized in currentTab.LocalizedTabs.Values) { if ((!localized.IsDeleted && !localized.DisableLink && localized.TabType == TabType.Normal) && (Null.IsNull(localized.StartDate) || localized.StartDate < DateTime.Now) && (Null.IsNull(localized.EndDate) || localized.EndDate > DateTime.Now) && - (IsTabPublic(localized.TabPermissions)) && - (includeHiddenPages || localized.IsVisible) && localized.HasBeenPublished) + this.IsTabPublic(localized.TabPermissions) && + (this.includeHiddenPages || localized.IsVisible) && localized.HasBeenPublished) { - string alternateUrl = TestableGlobals.Instance.NavigateURL(localized.TabID, localized.IsSuperTab, ps, "", localized.CultureCode); + string alternateUrl = TestableGlobals.Instance.NavigateURL(localized.TabID, localized.IsSuperTab, ps, string.Empty, localized.CultureCode); alternates.Add(new AlternateUrl() { Url = alternateUrl, - Language = localized.CultureCode + Language = localized.CultureCode, }); } } @@ -150,11 +224,11 @@ private SitemapUrl GetPageUrl(TabInfo objTab, string language, PortalSettings ps if (alternates.Count > 0) { // add default language to the list - string alternateUrl = TestableGlobals.Instance.NavigateURL(currentTab.TabID, currentTab.IsSuperTab, ps, "", currentTab.CultureCode); + string alternateUrl = TestableGlobals.Instance.NavigateURL(currentTab.TabID, currentTab.IsSuperTab, ps, string.Empty, currentTab.CultureCode); alternates.Add(new AlternateUrl() { Url = alternateUrl, - Language = currentTab.CultureCode + Language = currentTab.CultureCode, }); pageUrl.AlternateUrls = alternates; @@ -163,81 +237,5 @@ private SitemapUrl GetPageUrl(TabInfo objTab, string language, PortalSettings ps return pageUrl; } - - /// - /// When page level priority is used, the priority for each page will be computed from - /// the hierarchy level of the page. - /// Top level pages will have a value of 1, second level 0.9, third level 0.8, ... - /// - /// The page being indexed - /// The priority assigned to the page - /// - /// - protected float GetPriority(TabInfo objTab) - { - float priority = objTab.SiteMapPriority; - - if (useLevelBasedPagePriority) - { - if (objTab.Level >= 9) - { - priority = 0.1F; - } - else - { - priority = Convert.ToSingle(1 - (objTab.Level * 0.1)); - } - - if (priority < minPagePriority) - { - priority = minPagePriority; - } - } - - return priority; - } - - #region "Security Check" - - public virtual bool IsTabPublic(TabPermissionCollection objTabPermissions) - { - string roles = objTabPermissions.ToString("VIEW"); - bool hasPublicRole = false; - - - if ((roles != null)) - { - // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance - foreach (string role in roles.Split(new[] { ';' })) - { - if (!string.IsNullOrEmpty(role)) - { - // Deny permission - if (role.StartsWith("!")) - { - string denyRole = role.Replace("!", ""); - if ((denyRole == Globals.glbRoleUnauthUserName || denyRole == Globals.glbRoleAllUsersName)) - { - hasPublicRole = false; - break; - } - // Grant permission - } - else - { - if ((role == Globals.glbRoleUnauthUserName || role == Globals.glbRoleAllUsersName)) - { - hasPublicRole = true; - break; - } - } - } - } - } - - return hasPublicRole; - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs index 407f30656c6..7bdfa9ed702 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs @@ -1,140 +1,141 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Sitemap { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + + using Localization = DotNetNuke.Services.Localization.Localization; + public class SitemapBuilder { -#region Fields private const int SITEMAP_MAXURLS = 50000; private const string SITEMAP_VERSION = "0.9"; + private static readonly object _lock = new object(); + + private static List _providers; + private readonly PortalSettings PortalSettings; - private string _cacheFileName; - private string _cacheIndexFileNameFormat; - - #endregion - - #region Properties + private string _cacheFileName; + private string _cacheIndexFileNameFormat; + + /// + /// Initializes a new instance of the class. + /// Creates an instance of the sitemap builder class. + /// + /// Current PortalSettings for the portal being processed. + /// + /// + public SitemapBuilder(PortalSettings ps) + { + this.PortalSettings = ps; - public string CacheFileName - { - get - { - if (string.IsNullOrEmpty(_cacheFileName)) - { - var currentCulture = PortalSettings.CultureCode?.ToLowerInvariant(); + LoadProviders(); + } + + public string CacheFileName + { + get + { + if (string.IsNullOrEmpty(this._cacheFileName)) + { + var currentCulture = this.PortalSettings.CultureCode?.ToLowerInvariant(); if (string.IsNullOrEmpty(currentCulture)) { - currentCulture = Localization.Localization.GetPageLocale(PortalSettings).Name.ToLowerInvariant(); + currentCulture = Localization.GetPageLocale(this.PortalSettings).Name.ToLowerInvariant(); } - _cacheFileName = string.Format("sitemap" + ".{0}.xml", currentCulture); - } - - return _cacheFileName; - } - } + this._cacheFileName = string.Format("sitemap" + ".{0}.xml", currentCulture); + } - public string CacheIndexFileNameFormat - { - get - { - if (string.IsNullOrEmpty(_cacheIndexFileNameFormat)) - { - var currentCulture = Localization.Localization.GetPageLocale(PortalSettings).Name.ToLowerInvariant(); - _cacheIndexFileNameFormat = string.Format("sitemap_{{0}}" + ".{0}.xml", currentCulture); - } + return this._cacheFileName; + } + } - return _cacheIndexFileNameFormat; - } - } + public string CacheIndexFileNameFormat + { + get + { + if (string.IsNullOrEmpty(this._cacheIndexFileNameFormat)) + { + var currentCulture = Localization.GetPageLocale(this.PortalSettings).Name.ToLowerInvariant(); + this._cacheIndexFileNameFormat = string.Format("sitemap_{{0}}" + ".{0}.xml", currentCulture); + } - #endregion + return this._cacheIndexFileNameFormat; + } + } - /// - /// Creates an instance of the sitemap builder class - /// - /// Current PortalSettings for the portal being processed - /// - /// - public SitemapBuilder(PortalSettings ps) + public List Providers { - PortalSettings = ps; - - LoadProviders(); + get + { + return _providers; + } } - - #region "Sitemap Building" - + /// - /// Builds the complete portal sitemap + /// Builds the complete portal sitemap. /// /// /// public void BuildSiteMap(TextWriter output) { - int cacheDays = Int32.Parse(PortalController.GetPortalSetting("SitemapCacheDays", PortalSettings.PortalId, "1")); + int cacheDays = int.Parse(PortalController.GetPortalSetting("SitemapCacheDays", this.PortalSettings.PortalId, "1")); bool cached = cacheDays > 0; - - if (cached && CacheIsValid()) + + if (cached && this.CacheIsValid()) { - WriteSitemapFileToOutput(CacheFileName, output); + this.WriteSitemapFileToOutput(this.CacheFileName, output); return; } var allUrls = new List(); - - + // excluded urls by priority float excludePriority = 0; - excludePriority = float.Parse(PortalController.GetPortalSetting("SitemapExcludePriority", PortalSettings.PortalId, "0"), NumberFormatInfo.InvariantInfo); + excludePriority = float.Parse(PortalController.GetPortalSetting("SitemapExcludePriority", this.PortalSettings.PortalId, "0"), NumberFormatInfo.InvariantInfo); // get all urls bool isProviderEnabled = false; bool isProviderPriorityOverrided = false; float providerPriorityValue = 0; - - - foreach (SitemapProvider _provider in Providers) + + foreach (SitemapProvider _provider in this.Providers) { - isProviderEnabled = bool.Parse(PortalController.GetPortalSetting(_provider.Name + "Enabled", PortalSettings.PortalId, "True")); + isProviderEnabled = bool.Parse(PortalController.GetPortalSetting(_provider.Name + "Enabled", this.PortalSettings.PortalId, "True")); if (isProviderEnabled) { // check if we should override the priorities - isProviderPriorityOverrided = bool.Parse(PortalController.GetPortalSetting(_provider.Name + "Override", PortalSettings.PortalId, "False")); + isProviderPriorityOverrided = bool.Parse(PortalController.GetPortalSetting(_provider.Name + "Override", this.PortalSettings.PortalId, "False")); + // stored as an integer (pr * 100) to prevent from translating errors with the decimal point - providerPriorityValue = float.Parse(PortalController.GetPortalSetting(_provider.Name + "Value", PortalSettings.PortalId, "50")) / 100; + providerPriorityValue = float.Parse(PortalController.GetPortalSetting(_provider.Name + "Value", this.PortalSettings.PortalId, "50")) / 100; // Get all urls from provider List urls = new List(); try { - urls = _provider.GetUrls(PortalSettings.PortalId, PortalSettings, SITEMAP_VERSION); + urls = _provider.GetUrls(this.PortalSettings.PortalId, this.PortalSettings, SITEMAP_VERSION); } catch (Exception ex) { - Services.Exceptions.Exceptions.LogException(new Exception(Localization.Localization.GetExceptionMessage("SitemapProviderError", + Services.Exceptions.Exceptions.LogException(new Exception(Localization.GetExceptionMessage( + "SitemapProviderError", "URL sitemap provider '{0}' failed with error: {1}", _provider.Name, ex.Message))); } @@ -145,7 +146,8 @@ public void BuildSiteMap(TextWriter output) { url.Priority = providerPriorityValue; } - if (url.Priority > 0 && url.Priority >= excludePriority) //#RS# a valid sitemap needs priorities larger then 0, otherwise the sitemap will be rejected by google as invalid + + if (url.Priority > 0 && url.Priority >= excludePriority) // #RS# a valid sitemap needs priorities larger then 0, otherwise the sitemap will be rejected by google as invalid { allUrls.Add(url); } @@ -161,7 +163,7 @@ public void BuildSiteMap(TextWriter output) if (!cached) { cached = true; - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "SitemapCacheDays", "1"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "SitemapCacheDays", "1"); } // create all the files @@ -183,50 +185,49 @@ public void BuildSiteMap(TextWriter output) elements = elementsInFile; } - WriteSitemap(cached, output, index, allUrls.GetRange(lowerIndex, elements)); + this.WriteSitemap(cached, output, index, allUrls.GetRange(lowerIndex, elements)); } // create the sitemap index - WriteSitemapIndex(output, index - 1); + this.WriteSitemapIndex(output, index - 1); } else { // create a regular sitemap file - WriteSitemap(cached, output, 0, allUrls); + this.WriteSitemap(cached, output, 0, allUrls); } - - + if (cached) { - WriteSitemapFileToOutput(CacheFileName, output); + this.WriteSitemapFileToOutput(this.CacheFileName, output); } } /// /// Returns the sitemap file that is part of a sitemapindex. /// - /// Index of the sitemap to return - /// The output stream + /// Index of the sitemap to return. + /// The output stream. /// - /// The file should already exist since when using sitemapindexes the files are all cached to disk + /// The file should already exist since when using sitemapindexes the files are all cached to disk. /// public void GetSitemapIndexFile(string index, TextWriter output) { - var currentCulture = Localization.Localization.GetPageLocale(PortalSettings).Name.ToLowerInvariant(); - WriteSitemapFileToOutput(string.Format("sitemap_{0}.{1}.xml", index, currentCulture), output); + var currentCulture = Localization.GetPageLocale(this.PortalSettings).Name.ToLowerInvariant(); + this.WriteSitemapFileToOutput(string.Format("sitemap_{0}.{1}.xml", index, currentCulture), output); } /// - /// Generates a sitemap file + /// Generates a sitemap file. /// - /// Wheter the generated file should be cached or not - /// The output stream - /// For sitemapindex files the number of the file being generated, 0 otherwise - /// The list of urls to be included in the file + /// Wheter the generated file should be cached or not. + /// The output stream. + /// For sitemapindex files the number of the file being generated, 0 otherwise. + /// The list of urls to be included in the file. /// - /// If the output should be cached it will generate a file under the portal directory (portals\[portalid]\sitemaps\) with + /// If the output should be cached it will generate a file under the portal directory (portals\[portalid]\sitemaps\) with /// the result of the generation. If the file is part of a sitemap, index will be appended to the - /// filename cached on disk ("sitemap_1.xml") + /// filename cached on disk ("sitemap_1.xml"). /// private void WriteSitemap(bool cached, TextWriter output, int index, List allUrls) { @@ -236,12 +237,13 @@ private void WriteSitemap(bool cached, TextWriter output, int index, List 0) ? string.Format(CacheIndexFileNameFormat, index) : CacheFileName; - sitemapOutput = new StreamWriter(PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + cachedFile, false, Encoding.UTF8); + + var cachedFile = (index > 0) ? string.Format(this.CacheIndexFileNameFormat, index) : this.CacheFileName; + sitemapOutput = new StreamWriter(this.PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + cachedFile, false, Encoding.UTF8); } // Initialize writer @@ -262,7 +264,7 @@ private void WriteSitemap(bool cached, TextWriter output, int index, List - /// Generates a sitemapindex file + /// Generates a sitemapindex file. /// - /// The output stream - /// Number of files that are included in the sitemap index + /// The output stream. + /// Number of files that are included in the sitemap index. private void WriteSitemapIndex(TextWriter output, int totalFiles) { TextWriter sitemapOutput; - using (sitemapOutput = new StreamWriter(PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + CacheFileName, false, Encoding.UTF8)) + using (sitemapOutput = new StreamWriter(this.PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + this.CacheFileName, false, Encoding.UTF8)) { // Initialize writer var settings = new XmlWriterSettings(); @@ -309,9 +313,9 @@ private void WriteSitemapIndex(TextWriter output, int totalFiles) string url = null; url = "~/Sitemap.aspx?i=" + index; - if (IsChildPortal(PortalSettings, HttpContext.Current)) + if (this.IsChildPortal(this.PortalSettings, HttpContext.Current)) { - url += "&portalid=" + PortalSettings.PortalId; + url += "&portalid=" + this.PortalSettings.PortalId; } writer.WriteStartElement("sitemap"); @@ -319,6 +323,7 @@ private void WriteSitemapIndex(TextWriter output, int totalFiles) writer.WriteElementString("lastmod", DateTime.Now.ToString("yyyy-MM-dd")); writer.WriteEndElement(); } + writer.WriteEndElement(); writer.Close(); } @@ -326,16 +331,12 @@ private void WriteSitemapIndex(TextWriter output, int totalFiles) sitemapOutput.Flush(); sitemapOutput.Close(); } - } - - #endregion - - #region "Helper methods" - + } + /// - /// Adds a new url to the sitemap + /// Adds a new url to the sitemap. /// - /// The url to be included in the sitemap + /// The url to be included in the sitemap. /// /// private void AddURL(SitemapUrl sitemapUrl, XmlWriter writer) @@ -346,8 +347,8 @@ private void AddURL(SitemapUrl sitemapUrl, XmlWriter writer) writer.WriteElementString("changefreq", sitemapUrl.ChangeFrequency.ToString().ToLowerInvariant()); writer.WriteElementString("priority", sitemapUrl.Priority.ToString("F01", CultureInfo.InvariantCulture)); - //if (sitemapUrl.AlternateUrls != null) - //{ + // if (sitemapUrl.AlternateUrls != null) + // { // foreach (AlternateUrl alternate in sitemapUrl.AlternateUrls) // { // writer.WriteStartElement("link", "http://www.w3.org/1999/xhtml"); @@ -356,24 +357,25 @@ private void AddURL(SitemapUrl sitemapUrl, XmlWriter writer) // writer.WriteAttributeString("href", alternate.Url); // writer.WriteEndElement(); // } - //} + // } writer.WriteEndElement(); } /// - /// Is sitemap is cached, verifies is the cached file exists and is still valid + /// Is sitemap is cached, verifies is the cached file exists and is still valid. /// - /// True is the cached file exists and is still valid, false otherwise + /// True is the cached file exists and is still valid, false otherwise. private bool CacheIsValid() { - int cacheDays = int.Parse(PortalController.GetPortalSetting("SitemapCacheDays", PortalSettings.PortalId, "1")); - var isValid = File.Exists(PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + CacheFileName); + int cacheDays = int.Parse(PortalController.GetPortalSetting("SitemapCacheDays", this.PortalSettings.PortalId, "1")); + var isValid = File.Exists(this.PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + this.CacheFileName); if (!isValid) { return isValid; } - DateTime lastmod = File.GetLastWriteTime(PortalSettings.HomeSystemDirectoryMapPath + "/Sitemap/" + CacheFileName); + + DateTime lastmod = File.GetLastWriteTime(this.PortalSettings.HomeSystemDirectoryMapPath + "/Sitemap/" + this.CacheFileName); if (lastmod.AddDays(cacheDays) < DateTime.Now) { isValid = false; @@ -383,26 +385,26 @@ private bool CacheIsValid() } /// - /// When the sitemap is cached, reads the sitemap file and writes to the output stream + /// When the sitemap is cached, reads the sitemap file and writes to the output stream. /// - /// File name - /// The output stream + /// File name. + /// The output stream. private void WriteSitemapFileToOutput(string file, TextWriter output) { - if (!File.Exists(PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + file)) + if (!File.Exists(this.PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + file)) { return; } + // write the cached file to output - using (var reader = new StreamReader(PortalSettings.HomeSystemDirectoryMapPath + "/Sitemap/" + file, Encoding.UTF8)) + using (var reader = new StreamReader(this.PortalSettings.HomeSystemDirectoryMapPath + "/Sitemap/" + file, Encoding.UTF8)) { output.Write(reader.ReadToEnd()); reader.Close(); } } - - + private bool IsChildPortal(PortalSettings ps, HttpContext context) { bool isChild = false; @@ -418,31 +420,16 @@ private bool IsChildPortal(PortalSettings ps, HttpContext context) { portalName = PortalController.GetPortalFolder(portalAlias.HTTPAlias); } + if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) { isChild = true; } } + return isChild; - } - - #endregion - - #region "Provider configuration and setup" - - private static List _providers; - - private static readonly object _lock = new object(); - - public List Providers - { - get - { - return _providers; - } - } - - + } + private static void LoadProviders() { // Avoid claiming lock if providers are already loaded @@ -451,21 +438,17 @@ private static void LoadProviders() lock (_lock) { _providers = new List(); - - + foreach (KeyValuePair comp in ComponentFactory.GetComponents()) { comp.Value.Name = comp.Key; comp.Value.Description = comp.Value.Description; _providers.Add(comp.Value); } - - - //'ProvidersHelper.InstantiateProviders(section.Providers, _providers, GetType(SiteMapProvider)) + + // 'ProvidersHelper.InstantiateProviders(section.Providers, _providers, GetType(SiteMapProvider)) } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapChangeFrequency.cs b/DNN Platform/Library/Services/Sitemap/SitemapChangeFrequency.cs index 8af16c813bb..01bf09ef481 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapChangeFrequency.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapChangeFrequency.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Sitemap { public enum SitemapChangeFrequency @@ -12,6 +12,6 @@ public enum SitemapChangeFrequency Weekly, Monthly, Yearly, - Never + Never, } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs b/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs index 1746a96120d..b8bf5947c2c 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs @@ -1,23 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text; -using System.Web; - -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Sitemap { + using System; + using System.Text; + using System.Web; + + using DotNetNuke.Entities.Portals; + public class SitemapHandler : IHttpHandler - { - #region IHttpHandler Members - + { public bool IsReusable { get @@ -38,7 +31,7 @@ public void ProcessRequest(HttpContext context) var builder = new SitemapBuilder(ps); - if ((context.Request.QueryString["i"] != null)) + if (context.Request.QueryString["i"] != null) { // This is a request for one of the files that build the sitemapindex builder.GetSitemapIndexFile(context.Request.QueryString["i"], Response.Output); @@ -52,8 +45,6 @@ public void ProcessRequest(HttpContext context) { Exceptions.Exceptions.LogException(exc); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs b/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs index 15024648421..f224c023101 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs @@ -1,47 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Globalization; - -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Sitemap { + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Entities.Portals; + public abstract class SitemapProvider { public string Name { get; set; } public string Description { get; set; } - - + public bool Enabled { get { - return bool.Parse(PortalController.GetPortalSetting(Name + "Enabled", PortalController.Instance.GetCurrentPortalSettings().PortalId, "True")); + return bool.Parse(PortalController.GetPortalSetting(this.Name + "Enabled", PortalController.Instance.GetCurrentPortalSettings().PortalId, "True")); } + set { - PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, Name + "Enabled", value.ToString()); + PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, this.Name + "Enabled", value.ToString()); } } - - + public bool OverridePriority { get { - return bool.Parse(PortalController.GetPortalSetting(Name + "Override", PortalController.Instance.GetCurrentPortalSettings().PortalId, "False")); + return bool.Parse(PortalController.GetPortalSetting(this.Name + "Override", PortalController.Instance.GetCurrentPortalSettings().PortalId, "False")); } + set { - PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, Name + "Override", value.ToString()); + PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, this.Name + "Override", value.ToString()); } } @@ -50,21 +45,21 @@ public float Priority get { float value = 0; - if ((OverridePriority)) + if (this.OverridePriority) { // stored as an integer (pr * 100) to prevent from translating errors with the decimal point - value = float.Parse(PortalController.GetPortalSetting(Name + "Value", PortalController.Instance.GetCurrentPortalSettings().PortalId, "0.5"), NumberFormatInfo.InvariantInfo); + value = float.Parse(PortalController.GetPortalSetting(this.Name + "Value", PortalController.Instance.GetCurrentPortalSettings().PortalId, "0.5"), NumberFormatInfo.InvariantInfo); } + return value; } set { - PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, Name + "Value", value.ToString(NumberFormatInfo.InvariantInfo)); + PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, this.Name + "Value", value.ToString(NumberFormatInfo.InvariantInfo)); } } - - + public abstract List GetUrls(int portalId, PortalSettings ps, string version); } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs b/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs index e247881b58c..9f9b9a60e35 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs @@ -1,27 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Sitemap { + using System; + using System.Collections.Generic; + public class SitemapUrl { public string Url { get; set; } - - + public DateTime LastModified { get; set; } - - + public SitemapChangeFrequency ChangeFrequency { get; set; } - - + public float Priority { get; set; } public List AlternateUrls { get; set; } diff --git a/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs b/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs index eaadf6a1d9e..9a661f66d32 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs @@ -1,74 +1,67 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Social.Messaging.Internal.Views; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging.Data { - /// Data Service component for core messaging functions + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Social.Messaging.Internal.Views; + + /// Data Service component for core messaging functions. internal class DataService : ComponentBase, IDataService { - /// The provider instance + /// The provider instance. private readonly DataProvider _provider = DataProvider.Instance(); - #region Messages CRUD - /// Saves the message. /// The message. /// The portal identifier. /// The create update user identifier. - /// The id of the newly created message + /// The id of the newly created message. public int SaveMessage(Message message, int portalId, int createUpdateUserId) { - //need to fix groupmail - return _provider.ExecuteScalar("CoreMessaging_SaveMessage", message.MessageID, portalId ,message.To, message.From, message.Subject, message.Body, message.ConversationId, message.ReplyAllAllowed, message.SenderUserID, createUpdateUserId); + // need to fix groupmail + return this._provider.ExecuteScalar("CoreMessaging_SaveMessage", message.MessageID, portalId, message.To, message.From, message.Subject, message.Body, message.ConversationId, message.ReplyAllAllowed, message.SenderUserID, createUpdateUserId); } - /// Gets the message. - /// The message identifier. - /// A containing the message data + /// Gets the message. + /// The message identifier. + /// A containing the message data. public IDataReader GetMessage(int messageId) { - return _provider.ExecuteReader("CoreMessaging_GetMessage", messageId); + return this._provider.ExecuteReader("CoreMessaging_GetMessage", messageId); } /// Gets the last sent message. /// The user identifier. /// The portal identifier. - /// A containing the last sent message data + /// A containing the last sent message data. public IDataReader GetLastSentMessage(int userId, int portalId) { - return _provider.ExecuteReader("CoreMessaging_GetLastSentMessage", userId, portalId); + return this._provider.ExecuteReader("CoreMessaging_GetLastSentMessage", userId, portalId); } /// Gets the messages by sender. /// The message identifier. /// The portal identifier. - /// A containing the messages for a given portal Id + /// A containing the messages for a given portal Id. public IDataReader GetMessagesBySender(int messageId, int portalId) { - return _provider.ExecuteReader("CoreMessaging_GetMessagesBySender", messageId, portalId); + return this._provider.ExecuteReader("CoreMessaging_GetMessagesBySender", messageId, portalId); } /// Deletes the message. /// The message identifier. public void DeleteMessage(int messageId) { - _provider.ExecuteNonQuery("CoreMessaging_DeleteMessage", messageId); + this._provider.ExecuteNonQuery("CoreMessaging_DeleteMessage", messageId); } /// Deletes the user from conversation. @@ -76,7 +69,7 @@ public void DeleteMessage(int messageId) /// The user identifier. public void DeleteUserFromConversation(int conversationId, int userId) { - _provider.ExecuteNonQuery("CoreMessaging_DeleteUserFromConversation", conversationId, userId); + this._provider.ExecuteNonQuery("CoreMessaging_DeleteUserFromConversation", conversationId, userId); } /// Creates a message reply. @@ -86,21 +79,21 @@ public void DeleteUserFromConversation(int conversationId, int userId) /// The sender user identifier. /// From name. /// The create update user identifier. - /// The id of the reply created + /// The id of the reply created. public int CreateMessageReply(int conversationId, int portalId, string body, int senderUserId, string fromName, int createUpdateUserId) { - return _provider.ExecuteScalar("CoreMessaging_CreateMessageReply", conversationId, portalId, body, senderUserId, fromName, createUpdateUserId); + return this._provider.ExecuteScalar("CoreMessaging_CreateMessageReply", conversationId, portalId, body, senderUserId, fromName, createUpdateUserId); } /// - /// check if an attempt to reply to an existing mail has valid users + /// check if an attempt to reply to an existing mail has valid users. /// - /// the particular reply within the message - /// the user sending the message - as they are a recipient they must be excluded from the count - /// The count of recipients + /// the particular reply within the message. + /// the user sending the message - as they are a recipient they must be excluded from the count. + /// The count of recipients. public int CheckReplyHasRecipients(int conversationId, int userId) { - return _provider.ExecuteScalar("CoreMessaging_CheckReplyHasRecipients", conversationId, userId); + return this._provider.ExecuteScalar("CoreMessaging_CheckReplyHasRecipients", conversationId, userId); } /// Gets the in box view. @@ -113,7 +106,7 @@ public int CheckReplyHasRecipients(int conversationId, int userId) /// The read status. /// The archived status. /// The sent status. - /// A containing the inbox data + /// A containing the inbox data. public IDataReader GetInBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus, MessageSentStatus sentStatus) { object read = null; @@ -150,7 +143,7 @@ public IDataReader GetInBoxView(int userId, int portalId, int afterMessageId, in break; } - return _provider.ExecuteReader("CoreMessaging_GetMessageConversations", userId, portalId , afterMessageId, numberOfRecords, sortColumn, sortAscending, read, archived, sent); + return this._provider.ExecuteReader("CoreMessaging_GetMessageConversations", userId, portalId, afterMessageId, numberOfRecords, sortColumn, sortAscending, read, archived, sent); } /// Gets the sent box view. @@ -160,10 +153,10 @@ public IDataReader GetInBoxView(int userId, int portalId, int afterMessageId, in /// The number of records. /// The sort column. /// if set to true [sort ascending]. - /// A containing the sent message box data + /// A containing the sent message box data. public IDataReader GetSentBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending) { - return _provider.ExecuteReader("CoreMessaging_GetSentBox", userId, portalId, afterMessageId, numberOfRecords, sortColumn, sortAscending); + return this._provider.ExecuteReader("CoreMessaging_GetSentBox", userId, portalId, afterMessageId, numberOfRecords, sortColumn, sortAscending); } /// Gets the archive box view. @@ -173,10 +166,10 @@ public IDataReader GetSentBoxView(int userId, int portalId, int afterMessageId, /// The number of records. /// The sort column. /// if set to true [sort ascending]. - /// A containing the archived messages data + /// A containing the archived messages data. public IDataReader GetArchiveBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending) { - return _provider.ExecuteReader("CoreMessaging_GetArchiveBox", userId, portalId, afterMessageId, numberOfRecords, sortColumn, sortAscending); + return this._provider.ExecuteReader("CoreMessaging_GetArchiveBox", userId, portalId, afterMessageId, numberOfRecords, sortColumn, sortAscending); } /// Gets the message thread. @@ -187,10 +180,10 @@ public IDataReader GetArchiveBoxView(int userId, int portalId, int afterMessageI /// The sort column. /// if set to true [sort ascending]. /// The total records. - /// A containing the message thread data + /// A containing the message thread data. public IDataReader GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool @sortAscending, ref int totalRecords) - { - return _provider.ExecuteReader("CoreMessaging_GetMessageThread", conversationId, userId, afterMessageId, numberOfRecords, sortColumn, sortAscending); + { + return this._provider.ExecuteReader("CoreMessaging_GetMessageThread", conversationId, userId, afterMessageId, numberOfRecords, sortColumn, sortAscending); } /// Updates the message read status for a given conversation. @@ -199,7 +192,7 @@ public IDataReader GetMessageThread(int conversationId, int userId, int afterMes /// if read is set to true otherwise false. public void UpdateMessageReadStatus(int conversationId, int userId, bool read) { - _provider.ExecuteNonQuery("CoreMessaging_UpdateMessageReadStatus", conversationId, userId, read); + this._provider.ExecuteNonQuery("CoreMessaging_UpdateMessageReadStatus", conversationId, userId, read); } /// Updates the message archived status. @@ -208,90 +201,86 @@ public void UpdateMessageReadStatus(int conversationId, int userId, bool read) /// if set to true archived. public void UpdateMessageArchivedStatus(int conversationId, int userId, bool archived) { - _provider.ExecuteNonQuery("CoreMessaging_UpdateMessageArchivedStatus", conversationId, userId, archived); + this._provider.ExecuteNonQuery("CoreMessaging_UpdateMessageArchivedStatus", conversationId, userId, archived); } /// Counts the new threads. /// The user identifier. /// The portal identifier. - /// The count of new threads for a given user + /// The count of new threads for a given user. public int CountNewThreads(int userId, int portalId) { - return _provider.ExecuteScalar("CoreMessaging_CountNewThreads", userId, portalId); + return this._provider.ExecuteScalar("CoreMessaging_CountNewThreads", userId, portalId); } /// Counts the total conversations. /// The user identifier. /// The portal identifier. - /// The count of new conversations for a given user + /// The count of new conversations for a given user. public int CountTotalConversations(int userId, int portalId) { - return _provider.ExecuteScalar("CoreMessaging_CountTotalConversations", userId, portalId); + return this._provider.ExecuteScalar("CoreMessaging_CountTotalConversations", userId, portalId); } /// Counts the messages by conversation. /// The conversation identifier. - /// The count of new messages for a given conversation + /// The count of new messages for a given conversation. public int CountMessagesByConversation(int conversationId) { - return _provider.ExecuteScalar("CoreMessaging_CountMessagesByConversation", conversationId); + return this._provider.ExecuteScalar("CoreMessaging_CountMessagesByConversation", conversationId); } /// Counts the archived messages by conversation. /// The conversation identifier. - /// The count of archived messages for a given conversation + /// The count of archived messages for a given conversation. public int CountArchivedMessagesByConversation(int conversationId) { - return _provider.ExecuteScalar("CoreMessaging_CountArchivedMessagesByConversation", conversationId); + return this._provider.ExecuteScalar("CoreMessaging_CountArchivedMessagesByConversation", conversationId); } /// Counts the sent messages. /// The user identifier. /// The portal identifier. - /// The count of messages sent for a given user + /// The count of messages sent for a given user. public int CountSentMessages(int userId, int portalId) { - return _provider.ExecuteScalar("CoreMessaging_CountSentMessages", userId, portalId); + return this._provider.ExecuteScalar("CoreMessaging_CountSentMessages", userId, portalId); } /// Counts the archived messages. /// The user identifier. /// The portal identifier. - /// The count of archived messages for a given user + /// The count of archived messages for a given user. public int CountArchivedMessages(int userId, int portalId) { - return _provider.ExecuteScalar("CoreMessaging_CountArchivedMessages", userId, portalId); + return this._provider.ExecuteScalar("CoreMessaging_CountArchivedMessages", userId, portalId); } /// Counts the sent conversations. /// The user identifier. /// The portal identifier. - /// The count of sent conversations for a given user + /// The count of sent conversations for a given user. public int CountSentConversations(int userId, int portalId) { - return _provider.ExecuteScalar("CoreMessaging_CountSentConversations", userId, portalId); + return this._provider.ExecuteScalar("CoreMessaging_CountSentConversations", userId, portalId); } /// Counts the archived conversations. /// The user identifier. /// The portal identifier. - /// The count of archived conversations for a given user + /// The count of archived conversations for a given user. public int CountArchivedConversations(int userId, int portalId) { - return _provider.ExecuteScalar("CoreMessaging_CountArchivedConversations", userId, portalId); + return this._provider.ExecuteScalar("CoreMessaging_CountArchivedConversations", userId, portalId); } - #endregion - - #region Message_Recipients CRUD - /// Saves the message recipient. /// The message recipient. /// The create update user identifier. /// The new message recipient Id. public int SaveMessageRecipient(MessageRecipient messageRecipient, int createUpdateUserId) { - return _provider.ExecuteScalar("CoreMessaging_SaveMessageRecipient", messageRecipient.RecipientID, messageRecipient.MessageID, messageRecipient.UserID, messageRecipient.Read, messageRecipient.Archived, createUpdateUserId); + return this._provider.ExecuteScalar("CoreMessaging_SaveMessageRecipient", messageRecipient.RecipientID, messageRecipient.MessageID, messageRecipient.UserID, messageRecipient.Read, messageRecipient.Archived, createUpdateUserId); } /// Creates the message recipients for role. @@ -300,47 +289,47 @@ public int SaveMessageRecipient(MessageRecipient messageRecipient, int createUpd /// The create update user identifier. public void CreateMessageRecipientsForRole(int messageId, string roleIds, int createUpdateUserId) { - _provider.ExecuteNonQuery("CoreMessaging_CreateMessageRecipientsForRole", messageId, roleIds, createUpdateUserId); + this._provider.ExecuteNonQuery("CoreMessaging_CreateMessageRecipientsForRole", messageId, roleIds, createUpdateUserId); } /// Gets the message recipient. /// The message recipient identifier. - /// A containing the message recipient data + /// A containing the message recipient data. public IDataReader GetMessageRecipient(int messageRecipientId) { - return _provider.ExecuteReader("CoreMessaging_GetMessageRecipient", messageRecipientId); + return this._provider.ExecuteReader("CoreMessaging_GetMessageRecipient", messageRecipientId); } /// Gets the message recipients by user. /// The user identifier. - /// A containing the message recipient data + /// A containing the message recipient data. public IDataReader GetMessageRecipientsByUser(int userId) { - return _provider.ExecuteReader("CoreMessaging_GetMessageRecipientsByUser", userId); + return this._provider.ExecuteReader("CoreMessaging_GetMessageRecipientsByUser", userId); } /// Gets the message recipients by message. /// The message identifier. - /// A containing the message recipient data + /// A containing the message recipient data. public IDataReader GetMessageRecipientsByMessage(int messageId) { - return _provider.ExecuteReader("CoreMessaging_GetMessageRecipientsByMessage", messageId); + return this._provider.ExecuteReader("CoreMessaging_GetMessageRecipientsByMessage", messageId); } /// Gets the message recipient by message and user. /// The message identifier. /// The user identifier. - /// A containing the message recipient data + /// A containing the message recipient data. public IDataReader GetMessageRecipientByMessageAndUser(int messageId, int userId) { - return _provider.ExecuteReader("CoreMessaging_GetMessageRecipientsByMessageAndUser", messageId, userId); + return this._provider.ExecuteReader("CoreMessaging_GetMessageRecipientsByMessageAndUser", messageId, userId); } /// Deletes the message recipient. /// The message recipient identifier. public void DeleteMessageRecipient(int messageRecipientId) { - _provider.ExecuteNonQuery("CoreMessaging_DeleteMessageRecipient", messageRecipientId); + this._provider.ExecuteNonQuery("CoreMessaging_DeleteMessageRecipient", messageRecipientId); } /// Deletes the message recipient by message and user. @@ -348,37 +337,33 @@ public void DeleteMessageRecipient(int messageRecipientId) /// The user identifier. public void DeleteMessageRecipientByMessageAndUser(int messageId, int userId) { - _provider.ExecuteNonQuery("CoreMessaging_DeleteMessageRecipientByMessageAndUser", messageId, userId); + this._provider.ExecuteNonQuery("CoreMessaging_DeleteMessageRecipientByMessageAndUser", messageId, userId); } - #endregion - - #region Message_Attachments CRUD - /// Saves the message attachment. /// The message attachment. /// The create update user identifier. - /// The message attachment Id + /// The message attachment Id. public int SaveMessageAttachment(MessageAttachment messageAttachment, int createUpdateUserId) { - return _provider.ExecuteScalar("CoreMessaging_SaveMessageAttachment", messageAttachment.MessageAttachmentID, messageAttachment.MessageID, messageAttachment.FileID, createUpdateUserId); + return this._provider.ExecuteScalar("CoreMessaging_SaveMessageAttachment", messageAttachment.MessageAttachmentID, messageAttachment.MessageID, messageAttachment.FileID, createUpdateUserId); } /// Gets the message attachment. /// The message attachment identifier. - /// A containing the message attachment data + /// A containing the message attachment data. public IDataReader GetMessageAttachment(int messageAttachmentId) { - return _provider.ExecuteReader("CoreMessaging_GetMessageAttachment", messageAttachmentId); + return this._provider.ExecuteReader("CoreMessaging_GetMessageAttachment", messageAttachmentId); } /// Gets the message attachments by message id. /// The message identifier. - /// A list of + /// A list of . public IList GetMessageAttachmentsByMessage(int messageId) { var attachments = new List(); - var dr = _provider.ExecuteReader("CoreMessaging_GetMessageAttachmentsByMessage", messageId); + var dr = this._provider.ExecuteReader("CoreMessaging_GetMessageAttachmentsByMessage", messageId); try { @@ -387,15 +372,18 @@ public IList GetMessageAttachmentsByMessage(int messageId) var fileId = Convert.ToInt32(dr["FileID"]); var file = FileManager.Instance.GetFile(fileId); - if (file == null) continue; + if (file == null) + { + continue; + } var attachment = new MessageFileView - { - Name = file.FileName, - Size = file.Size.ToString(CultureInfo.InvariantCulture), - Url = FileManager.Instance.GetUrl(file), - FileId = fileId - }; + { + Name = file.FileName, + Size = file.Size.ToString(CultureInfo.InvariantCulture), + Url = FileManager.Instance.GetUrl(file), + FileId = fileId, + }; attachments.Add(attachment); } @@ -412,49 +400,41 @@ public IList GetMessageAttachmentsByMessage(int messageId) /// The message attachment identifier. public void DeleteMessageAttachment(int messageAttachmentId) { - _provider.ExecuteNonQuery("CoreMessaging_DeleteMessageAttachment", messageAttachmentId); + this._provider.ExecuteNonQuery("CoreMessaging_DeleteMessageAttachment", messageAttachmentId); } - #endregion - - #region Upgrade APIs - /// Converts the legacy messages. /// Index of the page. /// Size of the page. public void ConvertLegacyMessages(int pageIndex, int pageSize) { - _provider.ExecuteNonQuery("CoreMessaging_ConvertLegacyMessages", pageIndex, pageSize); + this._provider.ExecuteNonQuery("CoreMessaging_ConvertLegacyMessages", pageIndex, pageSize); } /// Counts the legacy messages. - /// A containing the messages data + /// A containing the messages data. public IDataReader CountLegacyMessages() { - return _provider.ExecuteReader("CoreMessaging_CountLegacyMessages"); + return this._provider.ExecuteReader("CoreMessaging_CountLegacyMessages"); } - #endregion - - #region Queued email API's - /// Gets the next messages for instant dispatch. /// The scheduler instance. /// Size of the batch. - /// A containing the messages data + /// A containing the messages data. public IDataReader GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize) { - return _provider.ExecuteReader("CoreMessaging_GetNextMessagesForInstantDispatch", schedulerInstance,batchSize); + return this._provider.ExecuteReader("CoreMessaging_GetNextMessagesForInstantDispatch", schedulerInstance, batchSize); } /// Gets the next messages for digest dispatch. /// The frequency. /// The scheduler instance. /// Size of the batch. - /// A containing the messages data + /// A containing the messages data. public IDataReader GetNextMessagesForDigestDispatch(int frequecy, Guid schedulerInstance, int batchSize) { - return _provider.ExecuteReader("CoreMessaging_GetNextMessagesForDigestDispatch", frequecy, schedulerInstance, batchSize); + return this._provider.ExecuteReader("CoreMessaging_GetNextMessagesForDigestDispatch", frequecy, schedulerInstance, batchSize); } /// Marks the message as dispatched. @@ -462,7 +442,7 @@ public IDataReader GetNextMessagesForDigestDispatch(int frequecy, Guid scheduler /// The recipient identifier. public void MarkMessageAsDispatched(int messageId, int recipientId) { - _provider.ExecuteNonQuery("CoreMessaging_MarkMessageAsDispatched", messageId, recipientId); + this._provider.ExecuteNonQuery("CoreMessaging_MarkMessageAsDispatched", messageId, recipientId); } /// Marks the message as sent. @@ -470,20 +450,16 @@ public void MarkMessageAsDispatched(int messageId, int recipientId) /// The recipient identifier. public void MarkMessageAsSent(int messageId, int recipientId) { - _provider.ExecuteNonQuery("CoreMessaging_MarkMessageAsSent", messageId, recipientId); + this._provider.ExecuteNonQuery("CoreMessaging_MarkMessageAsSent", messageId, recipientId); } - #endregion - - #region User Preferences - /// Gets the user preference. /// The portal identifier. /// The user identifier. - /// A containing the user data + /// A containing the user data. public IDataReader GetUserPreference(int portalId, int userId) { - return _provider.ExecuteReader("CoreMessaging_GetUserPreference", portalId, userId); + return this._provider.ExecuteReader("CoreMessaging_GetUserPreference", portalId, userId); } /// Sets the user preference. @@ -493,9 +469,7 @@ public IDataReader GetUserPreference(int portalId, int userId) /// The notifications email frequency. public void SetUserPreference(int portalId, int userId, int messagesEmailFrequency, int notificationsEmailFrequency) { - _provider.ExecuteNonQuery("CoreMessaging_SetUserPreference", portalId, userId, messagesEmailFrequency, notificationsEmailFrequency); + this._provider.ExecuteNonQuery("CoreMessaging_SetUserPreference", portalId, userId, messagesEmailFrequency, notificationsEmailFrequency); } - - #endregion } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs b/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs index 6758de4ee98..f9507f3f202 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs @@ -1,93 +1,98 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Services.Social.Messaging.Internal.Views; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging.Data { + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Services.Social.Messaging.Internal.Views; + public interface IDataService - { - #region Messages CRUD - + { int SaveMessage(Message message, int portalId, int createUpdateUserId); + IDataReader GetMessage(int messageId); + IDataReader GetMessagesBySender(int messageId, int portalId); + IDataReader GetLastSentMessage(int userId, int portalId); + void DeleteMessage(int messageId); + void DeleteUserFromConversation(int conversationId, int userId); IDataReader GetInBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus, MessageSentStatus sentStatus); + IDataReader GetSentBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); + IDataReader GetArchiveBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); - IDataReader GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, ref int totalRecords); + + IDataReader GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, ref int totalRecords); + void UpdateMessageReadStatus(int conversationId, int userId, bool read); + void UpdateMessageArchivedStatus(int conversationId, int userId, bool archived); - int CreateMessageReply(int conversationId, int portalId,string body, int senderUserId, string from, int createUpdateUserId); + + int CreateMessageReply(int conversationId, int portalId, string body, int senderUserId, string from, int createUpdateUserId); + int CountNewThreads(int userId, int portalId); + int CountTotalConversations(int userId, int portalId); + int CountMessagesByConversation(int conversationId); + int CountArchivedMessagesByConversation(int conversationId); + int CountSentMessages(int userId, int portalId); + int CountArchivedMessages(int userId, int portalId); + int CountSentConversations(int userId, int portalId); + int CountArchivedConversations(int userId, int portalId); - int CheckReplyHasRecipients(int conversationId, int userId); - - #endregion - - #region Message_Recipients CRUD - + + int CheckReplyHasRecipients(int conversationId, int userId); + int SaveMessageRecipient(MessageRecipient messageRecipient, int createUpdateUserId); + void CreateMessageRecipientsForRole(int messageId, string roleIds, int createUpdateUserId); + IDataReader GetMessageRecipient(int messageRecipientId); + IDataReader GetMessageRecipientsByUser(int userId); + IDataReader GetMessageRecipientsByMessage(int messageId); + IDataReader GetMessageRecipientByMessageAndUser(int messageId, int userId); + void DeleteMessageRecipient(int messageRecipientId); - void DeleteMessageRecipientByMessageAndUser(int messageId, int userId); - - #endregion - - #region Message_Attachments CRUD - + + void DeleteMessageRecipientByMessageAndUser(int messageId, int userId); + int SaveMessageAttachment(MessageAttachment messageAttachment, int createUpdateUserId); + IDataReader GetMessageAttachment(int messageAttachmentId); + IList GetMessageAttachmentsByMessage(int messageId); - void DeleteMessageAttachment(int messageAttachmentId); - - #endregion - - #region Upgrade APIs - + + void DeleteMessageAttachment(int messageAttachmentId); + void ConvertLegacyMessages(int pageIndex, int pageSize); - IDataReader CountLegacyMessages(); - - #endregion - - #region Queued email API's - + IDataReader CountLegacyMessages(); + IDataReader GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize); + IDataReader GetNextMessagesForDigestDispatch(int frequecy, Guid schedulerInstance, int batchSize); - void MarkMessageAsDispatched(int messageId,int recipientId); - void MarkMessageAsSent(int messageId, int recipientId); - - #endregion - - #region User Preferences - + + void MarkMessageAsDispatched(int messageId, int recipientId); + + void MarkMessageAsSent(int messageId, int recipientId); + IDataReader GetUserPreference(int portalId, int userId); - void SetUserPreference(int portalId, int userId, int messagesEmailFrequency, int notificationsEmailFrequency); - - #endregion + + void SetUserPreference(int portalId, int userId, int messagesEmailFrequency, int notificationsEmailFrequency); } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowedException.cs b/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowedException.cs index e6f5bb0b6f4..8d4dedabbdf 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowedException.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowedException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging.Exceptions { + using System; + using System.Runtime.Serialization; + [Serializable] public class AttachmentsNotAllowed : Exception { diff --git a/DNN Platform/Library/Services/Social/Messaging/Exceptions/MessageOrRecipientNotFoundException.cs b/DNN Platform/Library/Services/Social/Messaging/Exceptions/MessageOrRecipientNotFoundException.cs index fe34a6ac8c1..412115debec 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Exceptions/MessageOrRecipientNotFoundException.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Exceptions/MessageOrRecipientNotFoundException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging.Exceptions { + using System; + using System.Runtime.Serialization; + [Serializable] public class MessageOrRecipientNotFoundException : Exception { diff --git a/DNN Platform/Library/Services/Social/Messaging/Exceptions/RecipientLimitExceededException.cs b/DNN Platform/Library/Services/Social/Messaging/Exceptions/RecipientLimitExceededException.cs index 17983835bbe..7a0e98a7924 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Exceptions/RecipientLimitExceededException.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Exceptions/RecipientLimitExceededException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging.Exceptions { + using System; + using System.Runtime.Serialization; + [Serializable] public class RecipientLimitExceededException : Exception { diff --git a/DNN Platform/Library/Services/Social/Messaging/Exceptions/ThrottlingIntervalNotMetException.cs b/DNN Platform/Library/Services/Social/Messaging/Exceptions/ThrottlingIntervalNotMetException.cs index 57f111d1995..22cfd7ec9dc 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Exceptions/ThrottlingIntervalNotMetException.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Exceptions/ThrottlingIntervalNotMetException.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging.Exceptions { + using System; + using System.Runtime.Serialization; + [Serializable] public class ThrottlingIntervalNotMetException : Exception { diff --git a/DNN Platform/Library/Services/Social/Messaging/Frequency.cs b/DNN Platform/Library/Services/Social/Messaging/Frequency.cs index 97648efcd36..f790641dbd8 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Frequency.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Frequency.cs @@ -1,20 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Runtime.Serialization; + [DataContract] public enum Frequency { - [EnumMember] Never = -1, - [EnumMember] Instant = 0, - [EnumMember] Daily = 1, - [EnumMember] Hourly = 2, - [EnumMember] Weekly = 3, - [EnumMember] Monthly = 4 + [EnumMember] + Never = -1, + [EnumMember] + Instant = 0, + [EnumMember] + Daily = 1, + [EnumMember] + Hourly = 2, + [EnumMember] + Weekly = 3, + [EnumMember] + Monthly = 4, } } diff --git a/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs index 23aa585de78..235714e5bc1 100644 --- a/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs @@ -1,22 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + public interface IMessagingController - { - #region Public APIs - + { void SendMessage(Message message, IList roles, IList users, IList fileIDs); - void SendMessage(Message message, IList roles, IList users, IList fileIDs, UserInfo sender); - - #endregion + void SendMessage(Message message, IList roles, IList users, IList fileIDs, UserInfo sender); } } diff --git a/DNN Platform/Library/Services/Social/Messaging/IUserPreferencesController.cs b/DNN Platform/Library/Services/Social/Messaging/IUserPreferencesController.cs index 800d0a0d455..849265c09e6 100644 --- a/DNN Platform/Library/Services/Social/Messaging/IUserPreferencesController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/IUserPreferencesController.cs @@ -1,27 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging { + using DotNetNuke.Entities.Users; + /// - /// This class is responsible to manage the Messaging User Preference + /// This class is responsible to manage the Messaging User Preference. /// public interface IUserPreferencesController { /// - /// Set the User Messaging Preference + /// Set the User Messaging Preference. /// - /// User Preference + /// User Preference. void SetUserPreference(UserPreference userPreference); /// - /// Get the User Messaging Preference + /// Get the User Messaging Preference. /// - /// User info - /// User Messaging Preference + /// User info. + /// User Messaging Preference. UserPreference GetUserPreference(UserInfo userinfo); } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs index 95ba81cde66..bd71deb7d8e 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging.Internal { using System; @@ -10,52 +10,49 @@ namespace DotNetNuke.Services.Social.Messaging.Internal using DotNetNuke.Entities.Users; using DotNetNuke.Services.Social.Messaging.Internal.Views; - /// Interface used for Message Controller behaviors + /// Interface used for Message Controller behaviors. public interface IInternalMessagingController - { - #region Reply APIs - + { int ReplyMessage(int conversationId, string body, IList fileIDs); - int ReplyMessage(int conversationId, string body, IList fileIDs, UserInfo sender); - - #endregion - - #region CRUD APIs - + int ReplyMessage(int conversationId, string body, IList fileIDs, UserInfo sender); + Message GetMessage(int messageId); + MessageRecipient GetMessageRecipient(int messageId, int userId); + IList GetMessageRecipients(int messageId); + void DeleteMessageRecipient(int messageId, int userId); + void DeleteUserFromConversation(int conversationId, int userId); void MarkRead(int conversationId, int userId); + void MarkUnRead(int conversationId, int userId); + void MarkArchived(int conversationId, int userId); - void MarkUnArchived(int conversationId, int userId); - - #endregion - - #region Admin Settings APIs - - ///How long a user needs to wait before user is allowed sending the next message - ///Time in seconds. Returns zero if user has never sent a message - /// Sender's UserInfo + + void MarkUnArchived(int conversationId, int userId); + + /// How long a user needs to wait before user is allowed sending the next message. + /// Time in seconds. Returns zero if user has never sent a message. + /// Sender's UserInfo. int WaitTimeForNextMessage(UserInfo sender); - ///Last message sent by the User - ///Message. Null when no message was sent - /// Sender's UserInfo + /// Last message sent by the User. + /// Message. Null when no message was sent. + /// Sender's UserInfo. Message GetLastSentMessage(UserInfo sender); - ///Maximum number of Recipients allowed - ///Count. Message to a Role is considered a single Recipient. Each User in the To list is counted as one User each. - /// Portal Id + /// Maximum number of Recipients allowed. + /// Count. Message to a Role is considered a single Recipient. Each User in the To list is counted as one User each. + /// Portal Id. int RecipientLimit(int portalId); - ///Are attachments allowed - ///True or False - /// Portal Id + /// Are attachments allowed. + /// True or False. + /// Portal Id. bool AttachmentsAllowed(int portalId); /// Whether or not to includes the attachment in the email message. @@ -63,27 +60,20 @@ public interface IInternalMessagingController /// bool IncludeAttachments(int portalId); - ///Whether disable regular users to send message to user/group, default is false. - /// Portal Id - bool DisablePrivateMessage(int portalId); - - #endregion - - #region Upgrade APIs - + /// Whether disable regular users to send message to user/group, default is false. + /// Portal Id. + /// + bool DisablePrivateMessage(int portalId); + /// Converts the legacy messages. /// Index of the page. /// Size of the page. void ConvertLegacyMessages(int pageIndex, int pageSize); /// Counts the legacy messages. - /// A count of messages - int CountLegacyMessages(); - - #endregion - - #region Get View APIs - + /// A count of messages. + int CountLegacyMessages(); + /// Gets the inbox. /// The user identifier. /// The after message identifier. @@ -92,7 +82,7 @@ public interface IInternalMessagingController /// if set to true [ascending]. /// The read status. /// The archived status. - /// A + /// A . MessageBoxView GetInbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool @ascending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus); /// Gets the inbox. @@ -101,19 +91,19 @@ public interface IInternalMessagingController /// The number of records. /// The sort column. /// if set to true [sort ascending]. - /// A + /// A . MessageBoxView GetInbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); /// Gets the recent inbox. /// The user identifier. - /// A + /// A . MessageBoxView GetRecentInbox(int userId); /// Gets the recent inbox. /// The user identifier. /// The after message identifier. /// The number of records. - /// A + /// A . MessageBoxView GetRecentInbox(int userId, int afterMessageId, int numberOfRecords); /// Gets the sent box. @@ -124,7 +114,7 @@ public interface IInternalMessagingController /// if set to true [ascending]. /// The read status. /// The archived status. - /// A + /// A . MessageBoxView GetSentbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool ascending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus); /// Gets the sent box. @@ -133,26 +123,26 @@ public interface IInternalMessagingController /// The number of records. /// The sort column. /// if set to true [sort ascending]. - /// A + /// A . MessageBoxView GetSentbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); /// Gets the recent sent box. /// The user identifier. - /// A + /// A . MessageBoxView GetRecentSentbox(int userId); /// Gets the recent sent box. /// The user identifier. /// The after message identifier. /// The number of records. - /// A + /// A . MessageBoxView GetRecentSentbox(int userId, int afterMessageId, int numberOfRecords); /// Gets the archived messages. /// The user identifier. /// The after message identifier. /// The number of records. - /// A + /// A . MessageBoxView GetArchivedMessages(int userId, int afterMessageId, int numberOfRecords); /// Gets the message thread. @@ -163,7 +153,7 @@ public interface IInternalMessagingController /// The sort column. /// if set to true [ascending]. /// The total records. - /// A + /// A . MessageThreadsView GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool ascending, ref int totalRecords); /// Gets the message thread. @@ -172,28 +162,23 @@ public interface IInternalMessagingController /// The after message identifier. /// The number of records. /// The total records. - /// A + /// A . MessageThreadsView GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, ref int totalRecords); /// Gets the attachments for the specified message. /// The message identifier. - /// A list of - IEnumerable GetAttachments(int messageId); - - #endregion - - #region Queued email API's - - IList GetNextMessagesForInstantDispatch(Guid schedulerInstance,int batchSize); + /// A list of . + IEnumerable GetAttachments(int messageId); + + IList GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize); + IList GetNextMessagesForDigestDispatch(Frequency frequency, Guid schedulerInstance, int batchSize); + void MarkMessageAsDispatched(int messageId, int recipientId); - void MarkMessageAsSent(int messageId, int recipientId); - - #endregion - - #region Counter APIs - - int CheckReplyHasRecipients(int conversationId , int userId); + + void MarkMessageAsSent(int messageId, int recipientId); + + int CheckReplyHasRecipients(int conversationId, int userId); int CountUnreadMessages(int userId, int portalId); @@ -209,8 +194,6 @@ public interface IInternalMessagingController int CountSentConversations(int userId, int portalId); - int CountArchivedConversations(int userId, int portalId); - - #endregion + int CountArchivedConversations(int userId, int portalId); } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingController.cs index b3814a4feea..f0b5b64b562 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingController.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging.Internal { - /// - /// Business Layer to manage Messaging. Also contains CRUD methods. - /// + using System; + + using DotNetNuke.Framework; + + /// + /// Business Layer to manage Messaging. Also contains CRUD methods. + /// public class InternalMessagingController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs index 5b7d045b9f6..d3e72276cd4 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs @@ -1,31 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Social.Messaging.Data; -using DotNetNuke.Services.Social.Messaging.Exceptions; -using DotNetNuke.Services.Social.Messaging.Internal.Views; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging.Internal { - /// The Controller class for social Messaging + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Messaging.Data; + using DotNetNuke.Services.Social.Messaging.Exceptions; + using DotNetNuke.Services.Social.Messaging.Internal.Views; + + using Localization = DotNetNuke.Services.Localization.Localization; + + /// The Controller class for social Messaging. internal class InternalMessagingControllerImpl : IInternalMessagingController - { - #region Constants - + { internal const int ConstMaxTo = 2000; internal const int ConstMaxSubject = 400; internal const int ConstDefaultPageIndex = 0; @@ -34,18 +30,10 @@ internal class InternalMessagingControllerImpl : IInternalMessagingController internal const string ConstSortColumnFrom = "From"; internal const string ConstSortColumnSubject = "Subject"; internal const bool ConstAscending = true; - internal const double DefaultMessagingThrottlingInterval = 0.5; //default MessagingThrottlingInterval set to 30 seconds. - - #endregion - - #region Private Variables - - private readonly IDataService _dataService; - - #endregion - - #region Constructors - + internal const double DefaultMessagingThrottlingInterval = 0.5; // default MessagingThrottlingInterval set to 30 seconds. + + private readonly IDataService _dataService; + public InternalMessagingControllerImpl() : this(DataService.Instance) { @@ -53,218 +41,203 @@ public InternalMessagingControllerImpl() public InternalMessagingControllerImpl(IDataService dataService) { - //Argument Contract + // Argument Contract Requires.NotNull("dataService", dataService); - _dataService = dataService; - } - - #endregion - - #region CRUD APIs - + this._dataService = dataService; + } + public virtual void DeleteMessageRecipient(int messageId, int userId) { - _dataService.DeleteMessageRecipientByMessageAndUser(messageId, userId); + this._dataService.DeleteMessageRecipientByMessageAndUser(messageId, userId); } public virtual void DeleteUserFromConversation(int conversationId, int userId) { - _dataService.DeleteUserFromConversation(conversationId, userId); + this._dataService.DeleteUserFromConversation(conversationId, userId); } public virtual Message GetMessage(int messageId) { - return CBO.FillObject(_dataService.GetMessage(messageId)); + return CBO.FillObject(this._dataService.GetMessage(messageId)); } public virtual MessageRecipient GetMessageRecipient(int messageId, int userId) { - return CBO.FillObject(_dataService.GetMessageRecipientByMessageAndUser(messageId, userId)); + return CBO.FillObject(this._dataService.GetMessageRecipientByMessageAndUser(messageId, userId)); } public virtual IList GetMessageRecipients(int messageId) { - return CBO.FillCollection(_dataService.GetMessageRecipientsByMessage(messageId)); + return CBO.FillCollection(this._dataService.GetMessageRecipientsByMessage(messageId)); } public virtual void MarkArchived(int conversationId, int userId) { - _dataService.UpdateMessageArchivedStatus(conversationId, userId, true); + this._dataService.UpdateMessageArchivedStatus(conversationId, userId, true); } public virtual void MarkRead(int conversationId, int userId) { - _dataService.UpdateMessageReadStatus(conversationId, userId, true); + this._dataService.UpdateMessageReadStatus(conversationId, userId, true); } public virtual void MarkUnArchived(int conversationId, int userId) { - _dataService.UpdateMessageArchivedStatus(conversationId, userId, false); + this._dataService.UpdateMessageArchivedStatus(conversationId, userId, false); } public virtual void MarkUnRead(int conversationId, int userId) { - _dataService.UpdateMessageReadStatus(conversationId, userId, false); - } - - #endregion - - #region Reply APIs - + this._dataService.UpdateMessageReadStatus(conversationId, userId, false); + } + public virtual int ReplyMessage(int conversationId, string body, IList fileIDs) { - return ReplyMessage(conversationId, body, fileIDs, UserController.Instance.GetCurrentUserInfo()); + return this.ReplyMessage(conversationId, body, fileIDs, UserController.Instance.GetCurrentUserInfo()); } public virtual int ReplyMessage(int conversationId, string body, IList fileIDs, UserInfo sender) { if (sender == null || sender.UserID <= 0) { - throw new ArgumentException(Localization.Localization.GetString("MsgSenderRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgSenderRequiredError", Localization.ExceptionsResourceFile)); } if (string.IsNullOrEmpty(body)) { - throw new ArgumentException(Localization.Localization.GetString("MsgBodyRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgBodyRequiredError", Localization.ExceptionsResourceFile)); } - //Cannot have attachments if it's not enabled + // Cannot have attachments if it's not enabled if (fileIDs != null && !InternalMessagingController.Instance.AttachmentsAllowed(sender.PortalID)) { - throw new AttachmentsNotAllowed(Localization.Localization.GetString("MsgAttachmentsNotAllowed", Localization.Localization.ExceptionsResourceFile)); + throw new AttachmentsNotAllowed(Localization.GetString("MsgAttachmentsNotAllowed", Localization.ExceptionsResourceFile)); } - - - //Profanity Filter - var profanityFilterSetting = GetPortalSetting("MessagingProfanityFilters", sender.PortalID, "NO"); + + // Profanity Filter + var profanityFilterSetting = this.GetPortalSetting("MessagingProfanityFilters", sender.PortalID, "NO"); if (profanityFilterSetting.Equals("YES", StringComparison.InvariantCultureIgnoreCase)) { - body = InputFilter(body); + body = this.InputFilter(body); } - //call ReplyMessage - var messageId = _dataService.CreateMessageReply(conversationId, PortalController.GetEffectivePortalId(sender.PortalID), body, sender.UserID, sender.DisplayName, GetCurrentUserInfo().UserID); - if (messageId == -1) //Parent message was not found or Recipient was not found in the message + // call ReplyMessage + var messageId = this._dataService.CreateMessageReply(conversationId, PortalController.GetEffectivePortalId(sender.PortalID), body, sender.UserID, sender.DisplayName, this.GetCurrentUserInfo().UserID); + if (messageId == -1) // Parent message was not found or Recipient was not found in the message { - throw new MessageOrRecipientNotFoundException(Localization.Localization.GetString("MsgMessageOrRecipientNotFound", Localization.Localization.ExceptionsResourceFile)); + throw new MessageOrRecipientNotFoundException(Localization.GetString("MsgMessageOrRecipientNotFound", Localization.ExceptionsResourceFile)); } - //associate attachments + // associate attachments if (fileIDs != null) { foreach (var attachment in fileIDs.Select(fileId => new MessageAttachment { MessageAttachmentID = Null.NullInteger, FileID = fileId, MessageID = messageId })) { - _dataService.SaveMessageAttachment(attachment, UserController.Instance.GetCurrentUserInfo().UserID); + this._dataService.SaveMessageAttachment(attachment, UserController.Instance.GetCurrentUserInfo().UserID); } } // Mark reply as read and dispatched by the sender - var recipient = GetMessageRecipient(messageId, sender.UserID); - - MarkMessageAsDispatched(messageId, recipient.RecipientID); - MarkRead(conversationId, sender.UserID); - - return messageId; - } - + var recipient = this.GetMessageRecipient(messageId, sender.UserID); - #endregion - - #region Admin Settings APIs + this.MarkMessageAsDispatched(messageId, recipient.RecipientID); + this.MarkRead(conversationId, sender.UserID); + return messageId; + } + /// How long a user needs to wait before sending the next message. /// Time in seconds. Returns zero if user is Host, Admin or has never sent a message. - /// Sender's UserInfo + /// Sender's UserInfo. /// public virtual int WaitTimeForNextMessage(UserInfo sender) { Requires.NotNull("sender", sender); var waitTime = 0; + // MessagingThrottlingInterval contains the number of MINUTES to wait before sending the next message - var interval = GetPortalSettingAsDouble("MessagingThrottlingInterval", sender.PortalID, DefaultMessagingThrottlingInterval) * 60; - if (interval > 0 && !IsAdminOrHost(sender)) + var interval = this.GetPortalSettingAsDouble("MessagingThrottlingInterval", sender.PortalID, DefaultMessagingThrottlingInterval) * 60; + if (interval > 0 && !this.IsAdminOrHost(sender)) { - var lastSentMessage = GetLastSentMessage(sender); + var lastSentMessage = this.GetLastSentMessage(sender); if (lastSentMessage != null) { - waitTime = (int)(interval - GetDateTimeNow().Subtract(lastSentMessage.CreatedOnDate).TotalSeconds); + waitTime = (int)(interval - this.GetDateTimeNow().Subtract(lastSentMessage.CreatedOnDate).TotalSeconds); } } + return waitTime < 0 ? 0 : waitTime; } - ///Last message sent by the User - ///Message. Null when no message was sent - /// Sender's UserInfo + /// Last message sent by the User. + /// Message. Null when no message was sent. + /// Sender's UserInfo. public virtual Message GetLastSentMessage(UserInfo sender) { - return CBO.FillObject(_dataService.GetLastSentMessage(sender.UserID, PortalController.GetEffectivePortalId(sender.PortalID))); + return CBO.FillObject(this._dataService.GetLastSentMessage(sender.UserID, PortalController.GetEffectivePortalId(sender.PortalID))); } /// Whether or not attachments are included with outgoing email. - /// Portal Id - /// True or False + /// Portal Id. + /// True or False. public virtual bool IncludeAttachments(int portalId) { return this.GetPortalSetting("MessagingIncludeAttachments", portalId, "YES") == "YES"; } - /// Are attachments allowed - /// Portal Id - /// True or False + /// Are attachments allowed. + /// Portal Id. + /// True or False. public virtual bool AttachmentsAllowed(int portalId) { return this.GetPortalSetting("MessagingAllowAttachments", portalId, "YES") == "YES"; } - ///Maximum number of Recipients allowed - ///Count. Message to a Role is considered a single Recipient. Each User in the To list is counted as one User each. - /// Portal Id + /// Maximum number of Recipients allowed. + /// Count. Message to a Role is considered a single Recipient. Each User in the To list is counted as one User each. + /// Portal Id. public virtual int RecipientLimit(int portalId) { - return GetPortalSettingAsInteger("MessagingRecipientLimit", portalId, 5); + return this.GetPortalSettingAsInteger("MessagingRecipientLimit", portalId, 5); } - ///Whether disable regular users to send message to user/group, default is false. - /// Portal Id - public virtual bool DisablePrivateMessage(int portalId) - { - return GetPortalSetting("DisablePrivateMessage", portalId, "N") == "Y"; - } - - #endregion - - #region Get View APIs - + /// Whether disable regular users to send message to user/group, default is false. + /// Portal Id. + /// + public virtual bool DisablePrivateMessage(int portalId) + { + return this.GetPortalSetting("DisablePrivateMessage", portalId, "N") == "Y"; + } + public virtual MessageBoxView GetArchivedMessages(int userId, int afterMessageId, int numberOfRecords) { - var reader = _dataService.GetArchiveBoxView(userId, PortalController.GetEffectivePortalId(GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending); + var reader = this._dataService.GetArchiveBoxView(userId, PortalController.GetEffectivePortalId(this.GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending); return new MessageBoxView { Conversations = CBO.FillCollection(reader) }; } public virtual MessageBoxView GetInbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending) { - return GetInbox(userId, afterMessageId, numberOfRecords, sortColumn, sortAscending, MessageReadStatus.Any, MessageArchivedStatus.UnArchived); + return this.GetInbox(userId, afterMessageId, numberOfRecords, sortColumn, sortAscending, MessageReadStatus.Any, MessageArchivedStatus.UnArchived); } public virtual MessageBoxView GetInbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus) { - var reader = _dataService.GetInBoxView(userId, PortalController.GetEffectivePortalId(GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, sortColumn, sortAscending, readStatus, archivedStatus, MessageSentStatus.Received); - return new MessageBoxView { Conversations = CBO.FillCollection(reader) }; + var reader = this._dataService.GetInBoxView(userId, PortalController.GetEffectivePortalId(this.GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, sortColumn, sortAscending, readStatus, archivedStatus, MessageSentStatus.Received); + return new MessageBoxView { Conversations = CBO.FillCollection(reader) }; } public virtual MessageThreadsView GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, ref int totalRecords) { - return GetMessageThread(conversationId, userId, afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending, ref totalRecords); + return this.GetMessageThread(conversationId, userId, afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending, ref totalRecords); } public virtual MessageThreadsView GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, ref int totalRecords) { var messageThreadsView = new MessageThreadsView(); - var dr = _dataService.GetMessageThread(conversationId, userId, afterMessageId, numberOfRecords, sortColumn, sortAscending, ref totalRecords); + var dr = this._dataService.GetMessageThread(conversationId, userId, afterMessageId, numberOfRecords, sortColumn, sortAscending, ref totalRecords); try { @@ -275,11 +248,14 @@ public virtual MessageThreadsView GetMessageThread(int conversationId, int userI if (messageThreadView.Conversation.AttachmentCount > 0) { - messageThreadView.Attachments = _dataService.GetMessageAttachmentsByMessage(messageThreadView.Conversation.MessageID); + messageThreadView.Attachments = this._dataService.GetMessageAttachmentsByMessage(messageThreadView.Conversation.MessageID); } - if (messageThreadsView.Conversations == null) messageThreadsView.Conversations = new List(); - + if (messageThreadsView.Conversations == null) + { + messageThreadsView.Conversations = new List(); + } + messageThreadsView.Conversations.Add(messageThreadView); } } @@ -288,64 +264,63 @@ public virtual MessageThreadsView GetMessageThread(int conversationId, int userI CBO.CloseDataReader(dr, true); } - return messageThreadsView; + return messageThreadsView; } public virtual MessageBoxView GetRecentInbox(int userId) { - return GetRecentInbox(userId, ConstDefaultPageIndex, ConstDefaultPageSize); + return this.GetRecentInbox(userId, ConstDefaultPageIndex, ConstDefaultPageSize); } public virtual MessageBoxView GetRecentInbox(int userId, int afterMessageId, int numberOfRecords) { - return GetInbox(userId, afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending); + return this.GetInbox(userId, afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending); } public virtual MessageBoxView GetRecentSentbox(int userId) { - return GetRecentSentbox(userId, ConstDefaultPageIndex, ConstDefaultPageSize); + return this.GetRecentSentbox(userId, ConstDefaultPageIndex, ConstDefaultPageSize); } public virtual MessageBoxView GetRecentSentbox(int userId, int afterMessageId, int numberOfRecords) { - return GetSentbox(userId, afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending); + return this.GetSentbox(userId, afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending); } public virtual MessageBoxView GetSentbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending) { - return GetSentbox(userId, afterMessageId, numberOfRecords, sortColumn, sortAscending, MessageReadStatus.Any, MessageArchivedStatus.UnArchived); + return this.GetSentbox(userId, afterMessageId, numberOfRecords, sortColumn, sortAscending, MessageReadStatus.Any, MessageArchivedStatus.UnArchived); } public virtual MessageBoxView GetSentbox(int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus) { - var reader = _dataService.GetSentBoxView(userId, PortalController.GetEffectivePortalId(GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, sortColumn, sortAscending); + var reader = this._dataService.GetSentBoxView(userId, PortalController.GetEffectivePortalId(this.GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, sortColumn, sortAscending); return new MessageBoxView { Conversations = CBO.FillCollection(reader) }; - } - - #endregion - - #region Counter APIs - + } + public virtual int CheckReplyHasRecipients(int conversationId, int userId) { return userId <= 0 ? 0 : - conversationId <= 0 ? 0 : _dataService.CheckReplyHasRecipients(conversationId, userId); + conversationId <= 0 ? 0 : this._dataService.CheckReplyHasRecipients(conversationId, userId); } public virtual int CountArchivedMessagesByConversation(int conversationId) { - return conversationId <= 0 ? 0 : _dataService.CountArchivedMessagesByConversation(conversationId); + return conversationId <= 0 ? 0 : this._dataService.CountArchivedMessagesByConversation(conversationId); } public virtual int CountMessagesByConversation(int conversationId) { - return conversationId <= 0 ? 0 : _dataService.CountMessagesByConversation(conversationId); + return conversationId <= 0 ? 0 : this._dataService.CountMessagesByConversation(conversationId); } public virtual int CountConversations(int userId, int portalId) { - if (userId <= 0) return 0; - + if (userId <= 0) + { + return 0; + } + var cacheKey = string.Format(DataCache.UserNotificationsConversationCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); @@ -354,7 +329,7 @@ public virtual int CountConversations(int userId, int portalId) return (int)cacheObject; } - var count = _dataService.CountTotalConversations(userId, portalId); + var count = this._dataService.CountTotalConversations(userId, portalId); cache.Insert(cacheKey, count, (DNNCacheDependency)null, DateTime.Now.AddSeconds(DataCache.NotificationsCacheTimeInSec), System.Web.Caching.Cache.NoSlidingExpiration); return count; @@ -362,8 +337,11 @@ public virtual int CountConversations(int userId, int portalId) public virtual int CountUnreadMessages(int userId, int portalId) { - if (userId <= 0) return 0; - + if (userId <= 0) + { + return 0; + } + var cacheKey = string.Format(DataCache.UserNewThreadsCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); @@ -372,7 +350,7 @@ public virtual int CountUnreadMessages(int userId, int portalId) return (int)cacheObject; } - var count = _dataService.CountNewThreads(userId, portalId); + var count = this._dataService.CountNewThreads(userId, portalId); cache.Insert(cacheKey, count, (DNNCacheDependency)null, DateTime.Now.AddSeconds(DataCache.NotificationsCacheTimeInSec), System.Web.Caching.Cache.NoSlidingExpiration); return count; @@ -380,36 +358,57 @@ public virtual int CountUnreadMessages(int userId, int portalId) public virtual int CountSentMessages(int userId, int portalId) { - return userId <= 0 ? 0 : _dataService.CountSentMessages(userId, portalId); + return userId <= 0 ? 0 : this._dataService.CountSentMessages(userId, portalId); } public virtual int CountArchivedMessages(int userId, int portalId) { - return userId <= 0 ? 0 : _dataService.CountArchivedMessages(userId, portalId); + return userId <= 0 ? 0 : this._dataService.CountArchivedMessages(userId, portalId); } public virtual int CountSentConversations(int userId, int portalId) { - return userId <= 0 ? 0 : _dataService.CountSentConversations(userId, portalId); + return userId <= 0 ? 0 : this._dataService.CountSentConversations(userId, portalId); } public virtual int CountArchivedConversations(int userId, int portalId) { - return userId <= 0 ? 0 : _dataService.CountArchivedConversations(userId, portalId); + return userId <= 0 ? 0 : this._dataService.CountArchivedConversations(userId, portalId); } /// Gets the attachments. /// The message identifier. - /// A list of message attachments for the given message + /// A list of message attachments for the given message. public IEnumerable GetAttachments(int messageId) + { + return this._dataService.GetMessageAttachmentsByMessage(messageId); + } + + public void ConvertLegacyMessages(int pageIndex, int pageSize) { - return _dataService.GetMessageAttachmentsByMessage(messageId); + this._dataService.ConvertLegacyMessages(pageIndex, pageSize); } - #endregion + public int CountLegacyMessages() + { + var totalRecords = 0; + var dr = this._dataService.CountLegacyMessages(); - #region Internal Methods + try + { + while (dr.Read()) + { + totalRecords = Convert.ToInt32(dr["TotalRecords"]); + } + } + finally + { + CBO.CloseDataReader(dr, true); + } + return totalRecords; + } + internal virtual DateTime GetDateTimeNow() { return DateTime.UtcNow; @@ -444,62 +443,26 @@ internal virtual string InputFilter(string input) { var ps = PortalSecurity.Instance; return ps.InputFilter(input, PortalSecurity.FilterFlag.NoProfanity); - } - - #endregion - - #region Upgrade APIs - - public void ConvertLegacyMessages(int pageIndex, int pageSize) - { - _dataService.ConvertLegacyMessages(pageIndex, pageSize); - } - - public int CountLegacyMessages() - { - var totalRecords = 0; - var dr = _dataService.CountLegacyMessages(); - - try - { - while (dr.Read()) - { - totalRecords = Convert.ToInt32(dr["TotalRecords"]); - } - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return totalRecords; - } - - #endregion - - #region Queued email API's - + } + public IList GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize) { - return CBO.FillCollection(_dataService.GetNextMessagesForInstantDispatch(schedulerInstance, batchSize)); + return CBO.FillCollection(this._dataService.GetNextMessagesForInstantDispatch(schedulerInstance, batchSize)); } public IList GetNextMessagesForDigestDispatch(Frequency frequency, Guid schedulerInstance, int batchSize) { - return CBO.FillCollection(_dataService.GetNextMessagesForDigestDispatch(Convert.ToInt32(frequency), schedulerInstance, batchSize)); + return CBO.FillCollection(this._dataService.GetNextMessagesForDigestDispatch(Convert.ToInt32(frequency), schedulerInstance, batchSize)); } - - + public virtual void MarkMessageAsDispatched(int messageId, int recipientId) { - _dataService.MarkMessageAsDispatched(messageId, recipientId); + this._dataService.MarkMessageAsDispatched(messageId, recipientId); } public virtual void MarkMessageAsSent(int messageId, int recipientId) { - _dataService.MarkMessageAsSent(messageId, recipientId); - } - - #endregion + this._dataService.MarkMessageAsSent(messageId, recipientId); + } } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageBoxView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageBoxView.cs index d2b5f5533a9..5279ed18d70 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageBoxView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageBoxView.cs @@ -1,39 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging.Internal.Views { + using System; + using System.Collections.Generic; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging.Views /// Class: MessageBoxView /// ----------------------------------------------------------------------------- /// - /// The MessageBoxView contains the View of Inbox, Sent or Archived messages + /// The MessageBoxView contains the View of Inbox, Sent or Archived messages. /// /// ----------------------------------------------------------------------------- - public class MessageBoxView + public class MessageBoxView { /// - /// Total Number of Coversations + /// Gets or sets total Number of Coversations. /// public int TotalConversations { get; set; } /// - /// Total Number of New (Unread) Threads + /// Gets or sets total Number of New (Unread) Threads. /// public int TotalNewThreads { get; set; } /// - /// List of Conversations + /// Gets or sets list of Conversations. /// public List Conversations { get; set; } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs index 26ba39a3e62..c172a10e8b6 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging.Internal.Views { + using System; + using System.Data; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging.Views @@ -27,119 +27,121 @@ public class MessageConversationView : IHydratable private DateTime _createdOnDate; /// - /// MessageID - The primary key + /// Gets or sets messageID - The primary key. /// public int MessageID { get { - return _messageID; + return this._messageID; } + set { - _messageID = value; + this._messageID = value; } } /// - /// portalID for the message + /// Gets or sets portalID for the message. /// public int PortalID { get; set; } /// - /// To list for the message. This information is saved for faster display of To list in the message + /// Gets or sets to list for the message. This information is saved for faster display of To list in the message. /// public string To { get; set; } /// - /// Message From + /// Gets or sets message From. /// public string From { get; set; } /// - /// Message Subject + /// Gets or sets message Subject. /// public string Subject { get; set; } /// - /// Message body + /// Gets or sets message body. /// public string Body { get; set; } /// - /// Conversation ID of the Message. Each message has at least one ConversationId. Subsequent Replies to a Message get same ConversationId + /// Gets or sets conversation ID of the Message. Each message has at least one ConversationId. Subsequent Replies to a Message get same ConversationId. /// public int ConversationId { get; set; } /// - /// ReplyAllAllowed is a bit value to indicate if the reply to the message can be sent to all the recipients or just the sender + /// Gets or sets a value indicating whether replyAllAllowed is a bit value to indicate if the reply to the message can be sent to all the recipients or just the sender. /// - public bool ReplyAllAllowed { get; set; } /// - /// The UserID of the sender of the message + /// Gets or sets the UserID of the sender of the message. /// public int SenderUserID { get; set; } /// - /// A pretty printed string with the time since the message was created + /// Gets a pretty printed string with the time since the message was created. /// public string DisplayDate { get { - if (string.IsNullOrEmpty(_displayDate)) + if (string.IsNullOrEmpty(this._displayDate)) { - _displayDate = DateUtils.CalculateDateForDisplay(_createdOnDate); + this._displayDate = DateUtils.CalculateDateForDisplay(this._createdOnDate); } - return _displayDate; + + return this._displayDate; } } /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// public int KeyID { get { - return MessageID; + return this.MessageID; } + set { - MessageID = value; + this.MessageID = value; } } /// - /// RowNumber of the message in a set + /// Gets or sets rowNumber of the message in a set. /// public int RowNumber { get; set; } /// - /// Count of Total Attachments in a Conversation. It is calculated by adding attachments in all the threads for a given conversation. + /// Gets or sets count of Total Attachments in a Conversation. It is calculated by adding attachments in all the threads for a given conversation. /// public int AttachmentCount { get; set; } /// - /// Count of Total New (Unread) Threads in a Conversation. It is calculated by inspecting all the threads in a conversation and counting the ones that are not read yet. + /// Gets or sets count of Total New (Unread) Threads in a Conversation. It is calculated by inspecting all the threads in a conversation and counting the ones that are not read yet. /// public int NewThreadCount { get; set; } /// - /// Count of Total Threads in a Conversation. + /// Gets or sets count of Total Threads in a Conversation. /// public int ThreadCount { get; set; } /// - /// The Sender User Profile URL + /// Gets the Sender User Profile URL. /// public string SenderProfileUrl { get { - return Globals.UserProfileURL(SenderUserID); + return Globals.UserProfileURL(this.SenderUserID); } } @@ -149,19 +151,19 @@ public string SenderProfileUrl /// the data reader. public void Fill(IDataReader dr) { - MessageID = Convert.ToInt32(dr["MessageID"]); - To = Null.SetNullString(dr["To"]); - From = Null.SetNullString(dr["From"]); - Subject = Null.SetNullString(dr["Subject"]); - Body = Null.SetNullString(dr["Body"]); - ConversationId = Null.SetNullInteger(dr["ConversationID"]); - ReplyAllAllowed = Null.SetNullBoolean(dr["ReplyAllAllowed"]); - SenderUserID = Convert.ToInt32(dr["SenderUserID"]); - RowNumber = Convert.ToInt32(dr["RowNumber"]); - AttachmentCount = Convert.ToInt32(dr["AttachmentCount"]); - NewThreadCount = Convert.ToInt32(dr["NewThreadCount"]); - ThreadCount = Convert.ToInt32(dr["ThreadCount"]); - _createdOnDate = Null.SetNullDateTime(dr["CreatedOnDate"]); + this.MessageID = Convert.ToInt32(dr["MessageID"]); + this.To = Null.SetNullString(dr["To"]); + this.From = Null.SetNullString(dr["From"]); + this.Subject = Null.SetNullString(dr["Subject"]); + this.Body = Null.SetNullString(dr["Body"]); + this.ConversationId = Null.SetNullInteger(dr["ConversationID"]); + this.ReplyAllAllowed = Null.SetNullBoolean(dr["ReplyAllAllowed"]); + this.SenderUserID = Convert.ToInt32(dr["SenderUserID"]); + this.RowNumber = Convert.ToInt32(dr["RowNumber"]); + this.AttachmentCount = Convert.ToInt32(dr["AttachmentCount"]); + this.NewThreadCount = Convert.ToInt32(dr["NewThreadCount"]); + this.ThreadCount = Convert.ToInt32(dr["ThreadCount"]); + this._createdOnDate = Null.SetNullDateTime(dr["CreatedOnDate"]); } } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs index 1e5afdf9a01..bc1f55c1a13 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging.Internal.Views { - /// The MessageFileView class contains details about the attachment + using System; + + /// The MessageFileView class contains details about the attachment. /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging.Views @@ -15,14 +15,14 @@ namespace DotNetNuke.Services.Social.Messaging.Internal.Views /// ----------------------------------------------------------------------------- public class MessageFileView { - /// The _size + /// The _size. private string _size; /// Gets or sets the file identifier. /// The file identifier. public int FileId { get; set; } - /// Gets or sets the name of the file with extension + /// Gets or sets the name of the file with extension. /// The name. public string Name { get; set; } @@ -30,11 +30,16 @@ public class MessageFileView /// The size. public string Size { - get { return _size; } + get { return this._size; } + set { long bytes; - if (!long.TryParse(value, out bytes)) return; + if (!long.TryParse(value, out bytes)) + { + return; + } + const int scale = 1024; var orders = new[] { "GB", "MB", "KB", "B" }; var max = (long)Math.Pow(scale, orders.Length - 1); @@ -43,18 +48,19 @@ public string Size { if (bytes > max) { - _size = string.Format("{0:##.##} {1}", decimal.Divide(bytes, max), order); + this._size = string.Format("{0:##.##} {1}", decimal.Divide(bytes, max), order); return; } max /= scale; } - _size = "0 B"; + + this._size = "0 B"; } } /// - /// Gets or sets the url of the file to download + /// Gets or sets the url of the file to download. /// public string Url { get; set; } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadView.cs index 8bb42b1bd61..3530ac28ed8 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadView.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging.Internal.Views { + using System; + using System.Collections.Generic; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging /// Class: MessageThreadView /// ----------------------------------------------------------------------------- /// - /// The MessageThreadView class contains MessageConversationView and collection of MessageAttachmentView + /// The MessageThreadView class contains MessageConversationView and collection of MessageAttachmentView. /// /// ----------------------------------------------------------------------------- public class MessageThreadView { /// - /// MessageItemView containing consolidated information about the message + /// Gets or sets messageItemView containing consolidated information about the message. /// public MessageConversationView Conversation { get; set; } /// - /// List of attachments + /// Gets or sets list of attachments. /// public IList Attachments { get; set; } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadsView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadsView.cs index ba488039b1e..6dc8a04493e 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadsView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageThreadsView.cs @@ -1,45 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Xml.Serialization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging.Internal.Views { + using System; + using System.Collections.Generic; + using System.Xml.Serialization; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging /// Class: MessageThreadsView /// ----------------------------------------------------------------------------- /// - /// The MessageThreadsView class contains collection of MessageThreadView and other meta data + /// The MessageThreadsView class contains collection of MessageThreadView and other meta data. /// /// ----------------------------------------------------------------------------- public class MessageThreadsView { /// - /// Total Number of Threads + /// Gets or sets total Number of Threads. /// public int TotalThreads { get; set; } /// - /// Total Number of New (Unread) Threads + /// Gets or sets total Number of New (Unread) Threads. /// public int TotalNewThreads { get; set; } /// - /// Total Number of Archived Threads + /// Gets or sets total Number of Archived Threads. /// public int TotalArchivedThreads { get; set; } /// - /// List of Conversations + /// Gets or sets list of Conversations. /// public List Conversations { get; set; } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Message.cs b/DNN Platform/Library/Services/Social/Messaging/Message.cs index d418a3ab4d8..59043428aea 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Message.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Message.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging @@ -23,7 +18,7 @@ namespace DotNetNuke.Services.Social.Messaging /// ----------------------------------------------------------------------------- /// /// The Message class describes the content of messages sent via the system - /// As messaging is system wide process and there may be no portalID context (e.g. a host messaging "all users") the object does not tie to portalID + /// As messaging is system wide process and there may be no portalID context (e.g. a host messaging "all users") the object does not tie to portalID. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -33,104 +28,107 @@ public class Message : BaseEntityInfo, IHydratable private string _displayDate; /// - /// MessageID - The primary key + /// Gets or sets messageID - The primary key. /// [XmlAttribute] public int MessageID { get { - return _messageID; + return this._messageID; } + set { - _messageID = value; + this._messageID = value; } } /// - /// portalID for the message + /// Gets or sets portalID for the message. /// [XmlAttribute] public int PortalID { get; set; } /// - /// To list for the message. This information is saved for faster display of To list in the message + /// Gets or sets to list for the message. This information is saved for faster display of To list in the message. /// [XmlAttribute] public string To { get; set; } /// - /// Message From + /// Gets or sets message From. /// [XmlAttribute] public string From { get; set; } /// - /// Message Subject + /// Gets or sets message Subject. /// [XmlAttribute] public string Subject { get; set; } /// - /// Message body + /// Gets or sets message body. /// [XmlAttribute] public string Body { get; set; } /// - /// Conversation ID of the Message. Each message has at least one ConversationId. Subsequent Replies to a Message get same ConversationId + /// Gets or sets conversation ID of the Message. Each message has at least one ConversationId. Subsequent Replies to a Message get same ConversationId. /// [XmlAttribute] public int ConversationId { get; set; } /// - /// NotificationType ID of the Message. Each message is associated with a notification type. + /// Gets or sets notificationType ID of the Message. Each message is associated with a notification type. /// [XmlAttribute] public int NotificationTypeID { get; set; } /// - /// ReplyAllAllowed is a bit value to indicate if the reply to the message can be sent to all the recipients or just the sender + /// Gets or sets a value indicating whether replyAllAllowed is a bit value to indicate if the reply to the message can be sent to all the recipients or just the sender. /// [XmlAttribute] public bool ReplyAllAllowed { get; set; } /// - /// The UserID of the sender of the message + /// Gets or sets the UserID of the sender of the message. /// [XmlAttribute] public int SenderUserID { get; set; } /// - /// A pretty printed string with the time since the message was created + /// Gets a pretty printed string with the time since the message was created. /// [XmlAttribute] public string DisplayDate { get { - if (string.IsNullOrEmpty(_displayDate)) + if (string.IsNullOrEmpty(this._displayDate)) { - _displayDate = DateUtils.CalculateDateForDisplay(CreatedOnDate); + this._displayDate = DateUtils.CalculateDateForDisplay(this.CreatedOnDate); } - return _displayDate; + + return this._displayDate; } } /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID { get { - return MessageID; + return this.MessageID; } + set { - MessageID = value; + this.MessageID = value; } } @@ -140,18 +138,19 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - MessageID = Convert.ToInt32(dr["MessageID"]); - PortalID = Null.SetNullInteger(dr["PortalId"]); - To = Null.SetNullString(dr["To"]); - From = Null.SetNullString(dr["From"]); - Subject = Null.SetNullString(dr["Subject"]); - Body = Null.SetNullString(dr["Body"]); - ConversationId = Null.SetNullInteger(dr["ConversationID"]); - ReplyAllAllowed = Null.SetNullBoolean(dr["ReplyAllAllowed"]); - SenderUserID = Convert.ToInt32(dr["SenderUserID"]); - NotificationTypeID = Null.SetNullInteger(dr["NotificationTypeID"]); - //add audit column data - FillInternal(dr); + this.MessageID = Convert.ToInt32(dr["MessageID"]); + this.PortalID = Null.SetNullInteger(dr["PortalId"]); + this.To = Null.SetNullString(dr["To"]); + this.From = Null.SetNullString(dr["From"]); + this.Subject = Null.SetNullString(dr["Subject"]); + this.Body = Null.SetNullString(dr["Body"]); + this.ConversationId = Null.SetNullInteger(dr["ConversationID"]); + this.ReplyAllAllowed = Null.SetNullBoolean(dr["ReplyAllAllowed"]); + this.SenderUserID = Convert.ToInt32(dr["SenderUserID"]); + this.NotificationTypeID = Null.SetNullInteger(dr["NotificationTypeID"]); + + // add audit column data + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageArchivedStatus.cs b/DNN Platform/Library/Services/Social/Messaging/MessageArchivedStatus.cs index 656a15aebae..3450236369e 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageArchivedStatus.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageArchivedStatus.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// - /// Archived Status of a Message + /// Archived Status of a Message. /// public enum MessageArchivedStatus { @@ -34,6 +29,6 @@ public enum MessageArchivedStatus /// /// Any Message Status - Both Archived and UnArchived /// - Any = -1 + Any = -1, } } diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs b/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs index 69e1700753d..95dd2cc7516 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging /// Class: MessageAttachment /// ----------------------------------------------------------------------------- /// - /// The MessageAttachment class describes the content attachments associated with a message + /// The MessageAttachment class describes the content attachments associated with a message. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -31,36 +26,36 @@ public class MessageAttachment : BaseEntityInfo, IHydratable private int _messageattachmentID = -1; /// - /// MessageAttachmentID - The primary key + /// Gets or sets messageAttachmentID - The primary key. /// [XmlAttribute] public int MessageAttachmentID { get { - return _messageattachmentID; + return this._messageattachmentID; } + set { - _messageattachmentID = value; + this._messageattachmentID = value; } } /// - /// MessageID of the message that contains this attachment + /// Gets or sets messageID of the message that contains this attachment. /// [XmlAttribute] public int MessageID { get; set; } /// - /// The FileID of the attachment (what will be used against the Files table to provide the attachment) + /// Gets or sets the FileID of the attachment (what will be used against the Files table to provide the attachment). /// [XmlAttribute] public int FileID { get; set; } - - + /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID @@ -69,6 +64,7 @@ public int KeyID { return this.MessageAttachmentID; } + set { this.MessageAttachmentID = value; @@ -84,10 +80,9 @@ public void Fill(IDataReader dr) this.MessageAttachmentID = Convert.ToInt32(dr["MessageAttachmentID"]); this.MessageID = Convert.ToInt32(dr["MessageID"]); this.FileID = Convert.ToInt32(dr["FileID"]); - - //add audit column data - FillInternal(dr); - + + // add audit column data + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageReadStatus.cs b/DNN Platform/Library/Services/Social/Messaging/MessageReadStatus.cs index c861463d120..7b6898de09d 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageReadStatus.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageReadStatus.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// - /// Read Status of a Message + /// Read Status of a Message. /// public enum MessageReadStatus { @@ -34,6 +29,6 @@ public enum MessageReadStatus /// /// Any Message Status - Both Read and UnRead /// - Any = -1 + Any = -1, } } diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs b/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs index ed1e57ef269..91da96f149f 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Messaging /// Class: MessageRecipient /// ----------------------------------------------------------------------------- /// - /// The MessageRecipient class is used to store the details of all recipients of a particular message + /// The MessageRecipient class is used to store the details of all recipients of a particular message. /// /// ----------------------------------------------------------------------------- [Serializable] @@ -31,48 +26,48 @@ public class MessageRecipient : BaseEntityInfo, IHydratable private int _recipientID = -1; /// - /// RecipientID - The primary key + /// Gets or sets recipientID - The primary key. /// [XmlAttribute] public int RecipientID { get { - return _recipientID; + return this._recipientID; } + set { - _recipientID = value; + this._recipientID = value; } } /// - /// The messageID of who sent the message to this recipient + /// Gets or sets the messageID of who sent the message to this recipient. /// [XmlAttribute] public int MessageID { get; set; } /// - /// The UserID of the user receiving the message + /// Gets or sets the UserID of the user receiving the message. /// [XmlAttribute] public int UserID { get; set; } /// - /// Is Message read. True: Yes, False: No. + /// Gets or sets a value indicating whether is Message read. True: Yes, False: No. /// [XmlAttribute] public bool Read { get; set; } - - + /// - /// Is Message archived. True: Yes, False: No. + /// Gets or sets a value indicating whether is Message archived. True: Yes, False: No. /// [XmlAttribute] public bool Archived { get; set; } - + /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID @@ -81,6 +76,7 @@ public int KeyID { return this.RecipientID; } + set { this.RecipientID = value; @@ -98,10 +94,9 @@ public void Fill(IDataReader dr) this.UserID = Convert.ToInt32(dr["UserID"]); this.Archived = Null.SetNullBoolean(dr["Archived"]); this.Read = Null.SetNullBoolean(dr["Read"]); - - //add audit column data - FillInternal(dr); - + + // add audit column data + this.FillInternal(dr); } } } diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageSentStatus.cs b/DNN Platform/Library/Services/Social/Messaging/MessageSentStatus.cs index 649cdf90ede..54de40e5bc4 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageSentStatus.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageSentStatus.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// - /// Sent Status of a Message - Is this a Sent Message or a Received Message + /// Sent Status of a Message - Is this a Sent Message or a Received Message. /// public enum MessageSentStatus { @@ -34,6 +29,6 @@ public enum MessageSentStatus /// /// Any Message Status - Both Sent and Received /// - Any = -1 + Any = -1, } } diff --git a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs index e9f748bc500..58c930106d3 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs @@ -1,127 +1,111 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Portals.Internal; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Social.Messaging.Data; -using DotNetNuke.Services.Social.Messaging.Exceptions; -using DotNetNuke.Services.Social.Messaging.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Messaging { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Portals.Internal; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Social.Messaging.Data; + using DotNetNuke.Services.Social.Messaging.Exceptions; + using DotNetNuke.Services.Social.Messaging.Internal; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// The Controller class for social Messaging + /// The Controller class for social Messaging. /// /// /// - public class MessagingController - : ServiceLocator - , IMessagingController + public class MessagingController + : ServiceLocator, + IMessagingController { - protected override Func GetFactory() - { - return () => new MessagingController(); - } - - #region Constants - internal const int ConstMaxTo = 2000; internal const int ConstMaxSubject = 400; internal const int ConstDefaultPageIndex = 0; + + protected override Func GetFactory() + { + return () => new MessagingController(); + } internal const int ConstDefaultPageSize = 10; internal const string ConstSortColumnDate = "CreatedOnDate"; internal const string ConstSortColumnFrom = "From"; internal const string ConstSortColumnSubject = "Subject"; internal const bool ConstAscending = true; - internal const double DefaultMessagingThrottlingInterval = 0.5; //default MessagingThrottlingInterval set to 30 seconds. - - #endregion - - #region Private Variables - - private readonly IDataService _dataService; - - #endregion - - #region Constructors - - public MessagingController() : this(DataService.Instance) + internal const double DefaultMessagingThrottlingInterval = 0.5; // default MessagingThrottlingInterval set to 30 seconds. + + private readonly IDataService _dataService; + + public MessagingController() + : this(DataService.Instance) { } public MessagingController(IDataService dataService) { - //Argument Contract + // Argument Contract Requires.NotNull("dataService", dataService); - _dataService = dataService; - } - - #endregion - - #region Public APIs - + this._dataService = dataService; + } + public virtual void SendMessage(Message message, IList roles, IList users, IList fileIDs) { - SendMessage(message, roles, users, fileIDs, UserController.Instance.GetCurrentUserInfo()); + this.SendMessage(message, roles, users, fileIDs, UserController.Instance.GetCurrentUserInfo()); } public virtual void SendMessage(Message message, IList roles, IList users, IList fileIDs, UserInfo sender) { if (sender == null || sender.UserID <= 0) { - throw new ArgumentException(Localization.Localization.GetString("MsgSenderRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgSenderRequiredError", Localization.ExceptionsResourceFile)); } if (message == null) { - throw new ArgumentException(Localization.Localization.GetString("MsgMessageRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgMessageRequiredError", Localization.ExceptionsResourceFile)); } if (string.IsNullOrEmpty(message.Subject) && string.IsNullOrEmpty(message.Body)) { - throw new ArgumentException(Localization.Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.ExceptionsResourceFile)); } if (roles == null && users == null) { - throw new ArgumentException(Localization.Localization.GetString("MsgRolesOrUsersRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgRolesOrUsersRequiredError", Localization.ExceptionsResourceFile)); } - if (InternalMessagingController.Instance.DisablePrivateMessage(sender.PortalID) && !IsAdminOrHost(sender)) - { - throw new ArgumentException(Localization.Localization.GetString("PrivateMessageDisabledError", Localization.Localization.ExceptionsResourceFile)); - } + if (InternalMessagingController.Instance.DisablePrivateMessage(sender.PortalID) && !this.IsAdminOrHost(sender)) + { + throw new ArgumentException(Localization.GetString("PrivateMessageDisabledError", Localization.ExceptionsResourceFile)); + } if (!string.IsNullOrEmpty(message.Subject) && message.Subject.Length > ConstMaxSubject) { - throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgSubjectTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxSubject, message.Subject.Length)); + throw new ArgumentException(string.Format(Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), ConstMaxSubject, message.Subject.Length)); } - if (roles != null && roles.Count > 0 && !IsAdminOrHost(sender)) + if (roles != null && roles.Count > 0 && !this.IsAdminOrHost(sender)) { if (!roles.All(role => sender.Social.Roles.Any(userRoleInfo => role.RoleID == userRoleInfo.RoleID && userRoleInfo.IsOwner))) { - throw new ArgumentException(Localization.Localization.GetString("MsgOnlyHostOrAdminOrUserInGroupCanSendToRoleError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgOnlyHostOrAdminOrUserInGroupCanSendToRoleError", Localization.ExceptionsResourceFile)); } } @@ -138,48 +122,59 @@ public virtual void SendMessage(Message message, IList roles, IList !string.IsNullOrEmpty(user.DisplayName))) sbTo.Append(user.DisplayName + ","); + foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) + { + sbTo.Append(user.DisplayName + ","); + } } if (sbTo.Length == 0) { - throw new ArgumentException(Localization.Localization.GetString("MsgEmptyToListFoundError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgEmptyToListFoundError", Localization.ExceptionsResourceFile)); } - + if (sbTo.Length > ConstMaxTo) { - throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgToListTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); + throw new ArgumentException(string.Format(Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); } - //Cannot send message if within ThrottlingInterval + // Cannot send message if within ThrottlingInterval var waitTime = InternalMessagingController.Instance.WaitTimeForNextMessage(sender); if (waitTime > 0) { - var interval = GetPortalSettingAsDouble("MessagingThrottlingInterval", sender.PortalID, DefaultMessagingThrottlingInterval); - throw new ThrottlingIntervalNotMetException(string.Format(Localization.Localization.GetString("MsgThrottlingIntervalNotMet", Localization.Localization.ExceptionsResourceFile), interval)); + var interval = this.GetPortalSettingAsDouble("MessagingThrottlingInterval", sender.PortalID, DefaultMessagingThrottlingInterval); + throw new ThrottlingIntervalNotMetException(string.Format(Localization.GetString("MsgThrottlingIntervalNotMet", Localization.ExceptionsResourceFile), interval)); } - //Cannot have attachments if it's not enabled + // Cannot have attachments if it's not enabled if (fileIDs != null && fileIDs.Count > 0 && !InternalMessagingController.Instance.AttachmentsAllowed(sender.PortalID)) { - throw new AttachmentsNotAllowed(Localization.Localization.GetString("MsgAttachmentsNotAllowed", Localization.Localization.ExceptionsResourceFile)); + throw new AttachmentsNotAllowed(Localization.GetString("MsgAttachmentsNotAllowed", Localization.ExceptionsResourceFile)); } - //Cannot exceed RecipientLimit + // Cannot exceed RecipientLimit var recipientCount = 0; - if (users != null) recipientCount += users.Count; - if (roles != null) recipientCount += roles.Count; + if (users != null) + { + recipientCount += users.Count; + } + + if (roles != null) + { + recipientCount += roles.Count; + } + if (recipientCount > InternalMessagingController.Instance.RecipientLimit(sender.PortalID)) { - throw new RecipientLimitExceededException(Localization.Localization.GetString("MsgRecipientLimitExceeded", Localization.Localization.ExceptionsResourceFile)); + throw new RecipientLimitExceededException(Localization.GetString("MsgRecipientLimitExceeded", Localization.ExceptionsResourceFile)); } - //Profanity Filter - var profanityFilterSetting = GetPortalSetting("MessagingProfanityFilters", sender.PortalID, "NO"); + // Profanity Filter + var profanityFilterSetting = this.GetPortalSetting("MessagingProfanityFilters", sender.PortalID, "NO"); if (profanityFilterSetting.Equals("YES", StringComparison.InvariantCultureIgnoreCase)) { - message.Subject = InputFilter(message.Subject); - message.Body = InputFilter(message.Body); + message.Subject = this.InputFilter(message.Subject); + message.Body = this.InputFilter(message.Body); } message.To = sbTo.ToString().Trim(','); @@ -188,21 +183,21 @@ public virtual void SendMessage(Message message, IList roles, IList new MessageAttachment { MessageAttachmentID = Null.NullInteger, FileID = fileId, MessageID = message.MessageID })) { - if (CanViewFile(attachment.FileID)) + if (this.CanViewFile(attachment.FileID)) { - _dataService.SaveMessageAttachment(attachment, UserController.Instance.GetCurrentUserInfo().UserID); + this._dataService.SaveMessageAttachment(attachment, UserController.Instance.GetCurrentUserInfo().UserID); } } } - //send message to Roles + // send message to Roles if (roles != null) { var roleIds = string.Empty; @@ -211,10 +206,10 @@ public virtual void SendMessage(Message message, IList roles, IList current + (roleId + ",")) .Trim(','); - _dataService.CreateMessageRecipientsForRole(message.MessageID, roleIds, UserController.Instance.GetCurrentUserInfo().UserID); + this._dataService.CreateMessageRecipientsForRole(message.MessageID, roleIds, UserController.Instance.GetCurrentUserInfo().UserID); } - //send message to each User - this should be called after CreateMessageRecipientsForRole. + // send message to each User - this should be called after CreateMessageRecipientsForRole. if (users == null) { users = new List(); @@ -222,18 +217,18 @@ public virtual void SendMessage(Message message, IList roles, IList u.UserID != sender.UserID)) { var recipient = InternalMessagingController.Instance.GetMessageRecipient(message.MessageID, sender.UserID); - if(recipient == null) - { - //add sender as a recipient of the message + if (recipient == null) + { + // add sender as a recipient of the message recipient = new MessageRecipient { MessageID = message.MessageID, UserID = sender.UserID, Read = false, RecipientID = Null.NullInteger }; - recipient.RecipientID = _dataService.SaveMessageRecipient(recipient, UserController.Instance.GetCurrentUserInfo().UserID); + recipient.RecipientID = this._dataService.SaveMessageRecipient(recipient, UserController.Instance.GetCurrentUserInfo().UserID); } InternalMessagingController.Instance.MarkMessageAsDispatched(message.MessageID, recipient.RecipientID); @@ -241,12 +236,8 @@ public virtual void SendMessage(Message message, IList roles, IList - /// A SchedulerClient instance that handles all the offline messaging actions + /// A SchedulerClient instance that handles all the offline messaging actions. /// public class CoreMessagingScheduler : SchedulerClient { - /// The setting name for number hours since last hourly digest run + /// The setting name for number hours since last hourly digest run. private const string SettingLastHourlyRun = "CoreMessagingLastHourlyDigestRun"; - /// The setting name for number hours since last daily digest run + /// The setting name for number hours since last daily digest run. private const string SettingLastDailyRun = "CoreMessagingLastDailyDigestRun"; - /// The setting name for number hours since last weekly digest run + /// The setting name for number hours since last weekly digest run. private const string SettingLastWeeklyRun = "CoreMessagingLastWeeklyDigestRun"; - /// The setting name for number hours since last monthly digest run + /// The setting name for number hours since last monthly digest run. private const string SettingLastMonthlyRun = "CoreMessagingLastMonthlyDigestRun"; /// Initializes a new instance of the class. @@ -48,23 +49,23 @@ public CoreMessagingScheduler(ScheduleHistoryItem objScheduleHistoryItem) this.ScheduleHistoryItem = objScheduleHistoryItem; } - /// This is the method that kicks off the actual work within the SchedulerClient's subclass + /// This is the method that kicks off the actual work within the SchedulerClient's subclass. public override void DoWork() { try { var schedulerInstance = Guid.NewGuid(); - ScheduleHistoryItem.AddLogNote("Messaging Scheduler DoWork Starting " + schedulerInstance); + this.ScheduleHistoryItem.AddLogNote("Messaging Scheduler DoWork Starting " + schedulerInstance); if (string.IsNullOrEmpty(Host.SMTPServer)) { - ScheduleHistoryItem.AddLogNote("
    No SMTP Servers have been configured for this host. Terminating task."); - ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.AddLogNote("
    No SMTP Servers have been configured for this host. Terminating task."); + this.ScheduleHistoryItem.Succeeded = true; } else { this.Progressing(); - + var instantMessages = this.HandleInstantMessages(schedulerInstance); var remainingMessages = Host.MessageSchedulerBatchSize - instantMessages; if (remainingMessages > 0) @@ -72,20 +73,20 @@ public override void DoWork() this.HandleFrequentDigests(schedulerInstance, remainingMessages); } - ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.Succeeded = true; } } catch (Exception ex) { - ScheduleHistoryItem.Succeeded = false; - ScheduleHistoryItem.AddLogNote("
    Messaging Scheduler Failed: " + ex); + this.ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.AddLogNote("
    Messaging Scheduler Failed: " + ex); this.Errored(ref ex); } } /// Determines whether [is send email enable] [the specified portal identifier]. /// The portal identifier. - /// True if mail is enabled in PortalSettings + /// True if mail is enabled in PortalSettings. private static bool IsSendEmailEnable(int portalId) { return PortalController.GetPortalSetting("MessagingSendEmail", portalId, "YES") == "YES"; @@ -93,7 +94,7 @@ private static bool IsSendEmailEnable(int portalId) /// Determines whether [is user able to receive an email] [the specified recipient user]. /// The recipient user. - /// True if the user can receive email, otherwise false + /// True if the user can receive email, otherwise false. private static bool IsUserAbleToReceiveAnEmail(UserInfo recipientUser) { return recipientUser != null && !recipientUser.IsDeleted && recipientUser.Membership.Approved; @@ -102,7 +103,7 @@ private static bool IsUserAbleToReceiveAnEmail(UserInfo recipientUser) /// Gets the sender address. /// The sender. /// From address. - /// The formatted sender address + /// The formatted sender address. private static string GetSenderAddress(string sender, string fromAddress) { return string.Format("{0} < {1} >", sender, fromAddress); @@ -113,13 +114,13 @@ private static string GetSenderAddress(string sender, string fromAddress) /// The message body. /// The portal settings. /// The recipient user. - /// A string containing the email body with any tokens replaced + /// A string containing the email body with any tokens replaced. private static string GetEmailBody(string template, string messageBody, PortalSettings portalSettings, UserInfo recipientUser) { template = template.Replace("[MESSAGEBODY]", messageBody); // moved to top since that we we can replace tokens in there too... template = template.Replace("[RECIPIENTUSERID]", recipientUser.UserID.ToString(CultureInfo.InvariantCulture)); template = template.Replace("[RECIPIENTDISPLAYNAME]", recipientUser.DisplayName); - template = template.Replace("[RECIPIENTEMAIL]", recipientUser.Email); + template = template.Replace("[RECIPIENTEMAIL]", recipientUser.Email); template = template.Replace("[SITEURL]", GetPortalHomeUrl(portalSettings)); template = template.Replace("[NOTIFICATIONURL]", GetNotificationUrl(portalSettings, recipientUser.UserID)); template = template.Replace("[PORTALNAME]", portalSettings.PortalName); @@ -155,8 +156,8 @@ private static string GetEmailItemContent(PortalSettings portalSettings, Message var acceptUrl = GetRelationshipAcceptRequestUrl(portalSettings, authorId, "AcceptFriend"); var profileUrl = GetProfileUrl(portalSettings, authorId); - var linkContent = GetFriendRequestActionsTemplate(defaultLanguage); - emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl)); + var linkContent = GetFriendRequestActionsTemplate(portalSettings, defaultLanguage); + emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl)); } if (messageDetails.NotificationTypeID == 3) @@ -166,14 +167,14 @@ private static string GetEmailItemContent(PortalSettings portalSettings, Message var acceptUrl = GetRelationshipAcceptRequestUrl(portalSettings, authorId, "FollowBack"); var profileUrl = GetProfileUrl(portalSettings, authorId); - var linkContent = GetFollowRequestActionsTemplate(defaultLanguage); - emailItemContent = emailItemContent.Replace("[FOLLOWREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl)); + var linkContent = GetFollowRequestActionsTemplate(portalSettings, defaultLanguage); + emailItemContent = emailItemContent.Replace("[FOLLOWREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl)); } // No social actions for the rest of notifications types emailItemContent = emailItemContent.Replace("[FOLLOWREQUESTACTIONS]", string.Empty); - emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Empty); - + emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Empty); + return emailItemContent; } @@ -189,48 +190,48 @@ private static void MarkMessagesAsDispatched(IEnumerable messa /// Gets the email body item template. /// The language. - /// The email body template item from the Global Resource File: EMAIL_MESSAGING_DISPATCH_ITEM - private static string GetEmailBodyItemTemplate(string language) + /// The email body template item from the Global Resource File: EMAIL_MESSAGING_DISPATCH_ITEM. + private static string GetEmailBodyItemTemplate(PortalSettings portalSettings, string language) { - return Localization.Localization.GetString("EMAIL_MESSAGING_DISPATCH_ITEM", Localization.Localization.GlobalResourceFile, language); + return Localization.GetString("EMAIL_MESSAGING_DISPATCH_ITEM", Localization.GlobalResourceFile, portalSettings, language); } /// Gets the email body template. /// The language. - /// The email body template from the Global Resource File: EMAIL_MESSAGING_DISPATCH_BODY - private static string GetEmailBodyTemplate(string language) + /// The email body template from the Global Resource File: EMAIL_MESSAGING_DISPATCH_BODY. + private static string GetEmailBodyTemplate(PortalSettings portalSettings, string language) { - return Localization.Localization.GetString("EMAIL_MESSAGING_DISPATCH_BODY", Localization.Localization.GlobalResourceFile, language); + return Localization.GetString("EMAIL_MESSAGING_DISPATCH_BODY", Localization.GlobalResourceFile, portalSettings, language); } /// Gets the email subject template. /// The language. - /// The email subject template from the Global Resource File: EMAIL_SUBJECT_FORMAT - private static string GetEmailSubjectTemplate(string language) + /// The email subject template from the Global Resource File: EMAIL_SUBJECT_FORMAT. + private static string GetEmailSubjectTemplate(PortalSettings portalSettings, string language) { - return Localization.Localization.GetString("EMAIL_SUBJECT_FORMAT", Localization.Localization.GlobalResourceFile, language); + return Localization.GetString("EMAIL_SUBJECT_FORMAT", Localization.GlobalResourceFile, language); } /// Gets the friend request actions template. /// The language. - /// The friend request actions defined in the Global Resource File: EMAIL_SOCIAL_FRIENDREQUESTACTIONS - private static string GetFriendRequestActionsTemplate(string language) + /// The friend request actions defined in the Global Resource File: EMAIL_SOCIAL_FRIENDREQUESTACTIONS. + private static string GetFriendRequestActionsTemplate(PortalSettings portalSettings, string language) { - return Localization.Localization.GetString("EMAIL_SOCIAL_FRIENDREQUESTACTIONS", Localization.Localization.GlobalResourceFile, language); + return Localization.GetString("EMAIL_SOCIAL_FRIENDREQUESTACTIONS", Localization.GlobalResourceFile, portalSettings, language); } /// Gets the follow request actions template. /// The language. - /// The follow request actions defined in the Global Resource File: EMAIL_SOCIAL_FOLLOWREQUESTACTIONS - private static string GetFollowRequestActionsTemplate(string language) + /// The follow request actions defined in the Global Resource File: EMAIL_SOCIAL_FOLLOWREQUESTACTIONS. + private static string GetFollowRequestActionsTemplate(PortalSettings portalSettings, string language) { - return Localization.Localization.GetString("EMAIL_SOCIAL_FOLLOWREQUESTACTIONS", Localization.Localization.GlobalResourceFile, language); + return Localization.GetString("EMAIL_SOCIAL_FOLLOWREQUESTACTIONS", Localization.GlobalResourceFile, portalSettings, language); } /// Gets the name of the sender. /// The display name. /// Name of the portal. - /// Either the display name for the sender or the portal name + /// Either the display name for the sender or the portal name. private static string GetSenderName(string displayName, string portalName) { return string.IsNullOrEmpty(displayName) ? portalName : displayName; @@ -239,7 +240,7 @@ private static string GetSenderName(string displayName, string portalName) /// Gets the profile pic URL. /// The portal settings. /// The user identifier. - /// The handler url to fetch the picture for the specified userId + /// The handler url to fetch the picture for the specified userId. private static string GetProfilePicUrl(PortalSettings portalSettings, int userId) { return string.Format( @@ -254,22 +255,22 @@ private static string GetProfilePicUrl(PortalSettings portalSettings, int userId /// The portal settings. /// The user identifier. /// The action. - /// The handler url to fetch the relationship picture for the specified userId + /// The handler url to fetch the relationship picture for the specified userId. private static string GetRelationshipAcceptRequestUrl(PortalSettings portalSettings, int userId, string action) { return string.Format( "http://{0}/tabid/{1}/userId/{2}/action/{3}/{4}", portalSettings.DefaultPortalAlias, portalSettings.UserTabId, - userId.ToString(CultureInfo.InvariantCulture), - action, - Globals.glbDefaultPage); + userId.ToString(CultureInfo.InvariantCulture), + action, + Globals.glbDefaultPage); } /// Gets the profile URL. /// The portal settings. /// The user identifier. - /// The handler url to fetch the profile picture for the specified userId + /// The handler url to fetch the profile picture for the specified userId. private static string GetProfileUrl(PortalSettings portalSettings, int userId) { return string.Format( @@ -283,7 +284,7 @@ private static string GetProfileUrl(PortalSettings portalSettings, int userId) /// Gets the display name. /// The portal settings. /// The user identifier. - /// The display name for the given user + /// The display name for the given user. private static string GetDisplayName(PortalSettings portalSettings, int userId) { return (UserController.GetUserById(portalSettings.PortalId, userId) != null) @@ -294,7 +295,7 @@ private static string GetDisplayName(PortalSettings portalSettings, int userId) /// Gets the notification URL. /// The portal settings. /// The user identifier. - /// The handler url to fetch a notification for the specified userId + /// The handler url to fetch a notification for the specified userId. private static string GetNotificationUrl(PortalSettings portalSettings, int userId) { var cacheKey = string.Format("MessageCenterTab:{0}:{1}", portalSettings.PortalId, portalSettings.CultureCode); @@ -333,7 +334,7 @@ private static string GetNotificationUrl(PortalSettings portalSettings, int user /// Gets the portal logo URL. /// The portal settings. - /// A Url to the portal logo + /// A Url to the portal logo. private static string GetPortalLogoUrl(PortalSettings portalSettings) { return string.Format( @@ -345,7 +346,7 @@ private static string GetPortalLogoUrl(PortalSettings portalSettings) /// Gets the name of the domain. /// The portal settings. - /// Resolves the domain name (portal alias) for the specified portal + /// Resolves the domain name (portal alias) for the specified portal. private static string GetDomainName(PortalSettings portalSettings) { var portalAlias = portalSettings.DefaultPortalAlias; @@ -356,7 +357,7 @@ private static string GetDomainName(PortalSettings portalSettings) /// Gets the portal home URL. /// The portal settings. - /// The default portal alias url + /// The default portal alias url. private static string GetPortalHomeUrl(PortalSettings portalSettings) { return string.Format("http://{0}", portalSettings.DefaultPortalAlias); @@ -365,23 +366,23 @@ private static string GetPortalHomeUrl(PortalSettings portalSettings) /// Gets the subscriptions URL. /// The portal settings. /// The user identifier. - /// The url for viewing subscriptions + /// The url for viewing subscriptions. private static string GetSubscriptionsUrl(PortalSettings portalSettings, int userId) { return string.Format( "http://{0}/tabid/{1}/ctl/Profile/userId/{2}/pageno/3", portalSettings.DefaultPortalAlias, GetMessageTab(portalSettings), - userId); + userId); } /// Gets the message tab. /// The sending portal. - /// The tabId for where the Message Center is installed + /// The tabId for where the Message Center is installed. private static int GetMessageTab(PortalSettings sendingPortal) { var cacheKey = string.Format("MessageTab:{0}", sendingPortal.PortalId); - + var cacheItemArgs = new CacheItemArgs(cacheKey, 30, CacheItemPriority.Default, sendingPortal); return CBO.GetCachedObject(cacheItemArgs, GetMessageTabCallback); @@ -415,6 +416,43 @@ private static object GetMessageTabCallback(CacheItemArgs cacheItemArgs) return portalSettings.UserTabId; } + private static string RemoveHttpUrlsIfSiteisSSLEnabled(string stringContainingHttp, PortalSettings portalSettings) + { + if (stringContainingHttp.IndexOf("http") > -1 && portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced)) + { + var urlToReplace = GetPortalHomeUrl(portalSettings); + var urlReplaceWith = $"https://{portalSettings.DefaultPortalAlias}"; + stringContainingHttp = stringContainingHttp.Replace(urlToReplace, urlReplaceWith); + } + + return stringContainingHttp; + } + + private static string ResolveUrl(PortalSettings portalSettings, string template) + { + const string linkRegex = "(href|src)=\"(/[^\"]*?)\""; + var matches = Regex.Matches(template, linkRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); + foreach (Match match in matches) + { + var link = match.Groups[2].Value; + var defaultAlias = portalSettings.DefaultPortalAlias; + var domain = Globals.AddHTTP(defaultAlias); + if (defaultAlias.Contains("/")) + { + var subDomain = + defaultAlias.Substring(defaultAlias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase)); + if (link.StartsWith(subDomain, StringComparison.InvariantCultureIgnoreCase)) + { + link = link.Substring(subDomain.Length); + } + } + + template = template.Replace(match.Value, $"{match.Groups[1].Value}=\"{domain}{link}\""); + } + + return template; + } + /// Handles the frequent digests. /// The scheduler instance. /// The remaining messages. @@ -422,14 +460,14 @@ private void HandleFrequentDigests(Guid schedulerInstance, int remainingMessages { var handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddHours(-1), SettingLastHourlyRun, Frequency.Hourly, schedulerInstance, remainingMessages); remainingMessages = remainingMessages - handledMessages; - - handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddDays(-1), SettingLastDailyRun, Frequency.Daily, schedulerInstance, remainingMessages); + + handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddDays(-1), SettingLastDailyRun, Frequency.Daily, schedulerInstance, remainingMessages); + remainingMessages = remainingMessages - handledMessages; + + handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddDays(-7), SettingLastWeeklyRun, Frequency.Weekly, schedulerInstance, remainingMessages); remainingMessages = remainingMessages - handledMessages; - - handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddDays(-7), SettingLastWeeklyRun, Frequency.Weekly, schedulerInstance, remainingMessages); - remainingMessages = remainingMessages - handledMessages; - this.HandleFrequencyDigest(DateTime.Now.AddDays(-30), SettingLastMonthlyRun, Frequency.Monthly, schedulerInstance, remainingMessages); + this.HandleFrequencyDigest(DateTime.Now.AddDays(-30), SettingLastMonthlyRun, Frequency.Monthly, schedulerInstance, remainingMessages); } /// Handles the frequency digest. @@ -438,7 +476,7 @@ private void HandleFrequentDigests(Guid schedulerInstance, int remainingMessages /// The frequency. /// The scheduler instance. /// The remaining messages. - /// The count of messages processed + /// The count of messages processed. private int HandleFrequencyDigest(DateTime dateToCompare, string settingKeyLastRunDate, Frequency frequency, Guid schedulerInstance, int remainingMessages) { int handledMessages = 0; @@ -447,14 +485,14 @@ private int HandleFrequencyDigest(DateTime dateToCompare, string settingKeyLastR return handledMessages; } - var lastRunDate = this.GetScheduleItemDateSetting(settingKeyLastRunDate); + var lastRunDate = this.GetScheduleItemDateSetting(settingKeyLastRunDate); if (dateToCompare >= lastRunDate) { handledMessages = this.HandleDigest(schedulerInstance, frequency, remainingMessages); if (handledMessages < remainingMessages) { SchedulingProvider.Instance().AddScheduleItemSetting( - ScheduleHistoryItem.ScheduleID, settingKeyLastRunDate, DateTime.Now.ToString(CultureInfo.InvariantCulture)); + this.ScheduleHistoryItem.ScheduleID, settingKeyLastRunDate, DateTime.Now.ToString(CultureInfo.InvariantCulture)); } } @@ -465,14 +503,14 @@ private int HandleFrequencyDigest(DateTime dateToCompare, string settingKeyLastR /// The scheduler instance. /// The frequency. /// The remaining messages. - /// The count of messages processed + /// The count of messages processed. private int HandleDigest(Guid schedulerInstance, Frequency frequency, int remainingMessages) { var messagesSent = 0; // get subscribers based on frequency, utilize remaining batch size as part of count of users to return (note, if multiple subscriptions have the same frequency they will be combined into 1 email) - ScheduleHistoryItem.AddLogNote("
    Messaging Scheduler Starting Digest '" + schedulerInstance + "'. "); - + this.ScheduleHistoryItem.AddLogNote("
    Messaging Scheduler Starting Digest '" + schedulerInstance + "'. "); + var messageLeft = true; while (messageLeft) @@ -504,7 +542,7 @@ private int HandleDigest(Guid schedulerInstance, Frequency frequency, int remain } // at this point we have sent all digest notifications for this batch - ScheduleHistoryItem.AddLogNote("Sent " + messagesSent + " digest subscription emails for this batch. "); + this.ScheduleHistoryItem.AddLogNote("Sent " + messagesSent + " digest subscription emails for this batch. "); return messagesSent; } catch (Exception e) @@ -518,8 +556,8 @@ private int HandleDigest(Guid schedulerInstance, Frequency frequency, int remain } } - ScheduleHistoryItem.AddLogNote("Sent " + messagesSent + " " + frequency + " digest subscription emails. "); - + this.ScheduleHistoryItem.AddLogNote("Sent " + messagesSent + " " + frequency + " digest subscription emails. "); + return messagesSent; } @@ -546,9 +584,9 @@ private void SendDigest(IEnumerable messages, PortalSettings p var defaultLanguage = recipientUser.Profile.PreferredLocale; - var emailSubjectTemplate = GetEmailSubjectTemplate(defaultLanguage); - var emailBodyTemplate = GetEmailBodyTemplate(defaultLanguage); - var emailBodyItemTemplate = GetEmailBodyItemTemplate(defaultLanguage); + var emailSubjectTemplate = GetEmailSubjectTemplate(portalSettings, defaultLanguage); + var emailBodyTemplate = GetEmailBodyTemplate(portalSettings, defaultLanguage); + var emailBodyItemTemplate = GetEmailBodyItemTemplate(portalSettings, defaultLanguage); var emailBodyItemContent = messageRecipients.Aggregate( string.Empty, @@ -569,23 +607,12 @@ private void SendDigest(IEnumerable messages, PortalSettings p MarkMessagesAsDispatched(messageRecipients); } - private static string RemoveHttpUrlsIfSiteisSSLEnabled(string stringContainingHttp, PortalSettings portalSettings) - { - if (stringContainingHttp.IndexOf("http") > -1 && portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced)) - { - var urlToReplace = GetPortalHomeUrl(portalSettings); - var urlReplaceWith = $"https://{portalSettings.DefaultPortalAlias}"; - stringContainingHttp = stringContainingHttp.Replace(urlToReplace, urlReplaceWith); - } - return stringContainingHttp; - } - /// Gets the schedule item date setting. /// The setting key. - /// The date the schedule was ran + /// The date the schedule was ran. private DateTime GetScheduleItemDateSetting(string settingKey) { - var colScheduleItemSettings = SchedulingProvider.Instance().GetScheduleItemSettings(ScheduleHistoryItem.ScheduleID); + var colScheduleItemSettings = SchedulingProvider.Instance().GetScheduleItemSettings(this.ScheduleHistoryItem.ScheduleID); var dateValue = DateTime.Now; if (colScheduleItemSettings.Count > 0) @@ -598,13 +625,13 @@ private DateTime GetScheduleItemDateSetting(string settingKey) else { SchedulingProvider.Instance().AddScheduleItemSetting( - ScheduleHistoryItem.ScheduleID, SettingLastHourlyRun, dateValue.ToString(CultureInfo.InvariantCulture)); + this.ScheduleHistoryItem.ScheduleID, SettingLastHourlyRun, dateValue.ToString(CultureInfo.InvariantCulture)); SchedulingProvider.Instance().AddScheduleItemSetting( - ScheduleHistoryItem.ScheduleID, SettingLastDailyRun, dateValue.ToString(CultureInfo.InvariantCulture)); + this.ScheduleHistoryItem.ScheduleID, SettingLastDailyRun, dateValue.ToString(CultureInfo.InvariantCulture)); SchedulingProvider.Instance().AddScheduleItemSetting( - ScheduleHistoryItem.ScheduleID, SettingLastWeeklyRun, dateValue.ToString(CultureInfo.InvariantCulture)); + this.ScheduleHistoryItem.ScheduleID, SettingLastWeeklyRun, dateValue.ToString(CultureInfo.InvariantCulture)); SchedulingProvider.Instance().AddScheduleItemSetting( - ScheduleHistoryItem.ScheduleID, SettingLastMonthlyRun, dateValue.ToString(CultureInfo.InvariantCulture)); + this.ScheduleHistoryItem.ScheduleID, SettingLastMonthlyRun, dateValue.ToString(CultureInfo.InvariantCulture)); } return dateValue; @@ -612,7 +639,7 @@ private DateTime GetScheduleItemDateSetting(string settingKey) /// Handles the sending of messages. /// The scheduler instance. - /// The count of messages sent + /// The count of messages sent. private int HandleInstantMessages(Guid schedulerInstance) { var messageLeft = true; @@ -643,7 +670,7 @@ private int HandleInstantMessages(Guid schedulerInstance) } } - ScheduleHistoryItem.AddLogNote(string.Format("
    Messaging Scheduler '{0}' sent a total of {1} message(s)", schedulerInstance, messagesSent)); + this.ScheduleHistoryItem.AddLogNote(string.Format("
    Messaging Scheduler '{0}' sent a total of {1} message(s)", schedulerInstance, messagesSent)); return messagesSent; } @@ -651,7 +678,7 @@ private int HandleInstantMessages(Guid schedulerInstance) /// The message recipient. private void SendMessage(MessageRecipient messageRecipient) { - var message = InternalMessagingController.Instance.GetMessage(messageRecipient.MessageID); + var message = InternalMessagingController.Instance.GetMessage(messageRecipient.MessageID); var toUser = UserController.Instance.GetUser(message.PortalID, messageRecipient.UserID); if (!IsUserAbleToReceiveAnEmail(toUser)) @@ -667,15 +694,15 @@ private void SendMessage(MessageRecipient messageRecipient) } var defaultLanguage = toUser.Profile.PreferredLocale; + var portalSettings = new PortalSettings(message.PortalID); - var emailSubjectTemplate = GetEmailSubjectTemplate(defaultLanguage); - var emailBodyTemplate = GetEmailBodyTemplate(defaultLanguage); - var emailBodyItemTemplate = GetEmailBodyItemTemplate(defaultLanguage); + var emailSubjectTemplate = GetEmailSubjectTemplate(portalSettings, defaultLanguage); + var emailBodyTemplate = GetEmailBodyTemplate(portalSettings, defaultLanguage); + var emailBodyItemTemplate = GetEmailBodyItemTemplate(portalSettings, defaultLanguage); var author = UserController.Instance.GetUser(message.PortalID, message.SenderUserID); - var portalSettings = new PortalSettings(message.PortalID); var fromAddress = (UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email) != null) ? - String.Format("{0} < {1} >", UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email).DisplayName, portalSettings.Email) : portalSettings.Email; + string.Format("{0} < {1} >", UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email).DisplayName, portalSettings.Email) : portalSettings.Email; var toAddress = toUser.Email; if (Mail.Mail.IsValidEmailAddress(toUser.Email, toUser.PortalID)) @@ -690,7 +717,7 @@ private void SendMessage(MessageRecipient messageRecipient) // Include the attachment in the email message if configured to do so if (InternalMessagingController.Instance.AttachmentsAllowed(message.PortalID)) { - Mail.Mail.SendEmail(fromAddress, senderAddress, toAddress, subject, body, CreateAttachments(message.MessageID).ToList()); + Mail.Mail.SendEmail(fromAddress, senderAddress, toAddress, subject, body, this.CreateAttachments(message.MessageID).ToList()); } else { @@ -703,7 +730,7 @@ private void SendMessage(MessageRecipient messageRecipient) /// Creates list of attachments for the specified message. /// The message identifier. - /// A list of attachments + /// A list of attachments. private IEnumerable CreateAttachments(int messageId) { foreach (var fileView in InternalMessagingController.Instance.GetAttachments(messageId)) @@ -716,31 +743,5 @@ private IEnumerable CreateAttachments(int messageId) } } } - - private static string ResolveUrl(PortalSettings portalSettings, string template) - { - const string linkRegex = "(href|src)=\"(/[^\"]*?)\""; - var matches = Regex.Matches(template, linkRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); - foreach (Match match in matches) - { - var link = match.Groups[2].Value; - var defaultAlias = portalSettings.DefaultPortalAlias; - var domain = Globals.AddHTTP(defaultAlias); - if (defaultAlias.Contains("/")) - { - var subDomain = - defaultAlias.Substring(defaultAlias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase)); - if (link.StartsWith(subDomain, StringComparison.InvariantCultureIgnoreCase)) - { - link = link.Substring(subDomain.Length); - } - } - - template = template.Replace(match.Value, $"{match.Groups[1].Value}=\"{domain}{link}\""); - } - - return template; - } - } } diff --git a/DNN Platform/Library/Services/Social/Messaging/UserPreference.cs b/DNN Platform/Library/Services/Social/Messaging/UserPreference.cs index a6cf33e945c..92a07027936 100644 --- a/DNN Platform/Library/Services/Social/Messaging/UserPreference.cs +++ b/DNN Platform/Library/Services/Social/Messaging/UserPreference.cs @@ -1,34 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging { + using System; + /// - /// Represents the Messaging User Preference + /// Represents the Messaging User Preference. /// [Serializable] public class UserPreference { /// - /// Portal where the preference are applied + /// Gets or sets portal where the preference are applied. /// public int PortalId { get; set; } /// - /// User Identifier + /// Gets or sets user Identifier. /// public int UserId { get; set; } /// - /// The Email Delivery Frequency used for Messages + /// Gets or sets the Email Delivery Frequency used for Messages. /// public Frequency MessagesEmailFrequency { get; set; } /// - /// The Email Delivery Frequency used for Notifications + /// Gets or sets the Email Delivery Frequency used for Notifications. /// public Frequency NotificationsEmailFrequency { get; set; } } diff --git a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs index d93000af455..fb2769ab73d 100644 --- a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs @@ -1,53 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Social.Messaging.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Messaging { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Social.Messaging.Data; + public class UserPreferencesController : ServiceLocator, IUserPreferencesController - { - #region Private Memebers - private readonly IDataService dataService; - #endregion - - protected override Func GetFactory() - { - return () => new UserPreferencesController(); - } - - #region Constructor - public UserPreferencesController() : this(DataService.Instance) + { + private readonly IDataService dataService; + + public UserPreferencesController() + : this(DataService.Instance) { } public UserPreferencesController(IDataService dataService) { - //Argument Contract + // Argument Contract Requires.NotNull("dataService", dataService); this.dataService = dataService; - } - #endregion - - #region Public API + } + public void SetUserPreference(UserPreference userPreference) { - dataService.SetUserPreference(userPreference.PortalId, userPreference.UserId, Convert.ToInt32(userPreference.MessagesEmailFrequency), Convert.ToInt32(userPreference.NotificationsEmailFrequency)); + this.dataService.SetUserPreference(userPreference.PortalId, userPreference.UserId, Convert.ToInt32(userPreference.MessagesEmailFrequency), Convert.ToInt32(userPreference.NotificationsEmailFrequency)); } + + protected override Func GetFactory() + { + return () => new UserPreferencesController(); + } public UserPreference GetUserPreference(UserInfo userinfo) { - return CBO.FillObject(dataService.GetUserPreference(userinfo.PortalID, userinfo.UserID)); - } - - #endregion - + return CBO.FillObject(this.dataService.GetUserPreference(userinfo.PortalID, userinfo.UserID)); + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs b/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs index 23b37af1b91..76a787d8b9e 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs @@ -1,168 +1,149 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Notifications.Data { + using System; + using System.Data; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + internal class DataService : ComponentBase, IDataService { + private const string Prefix = "CoreMessaging_"; private readonly DataProvider _provider = DataProvider.Instance(); - private const string Prefix = "CoreMessaging_"; - - #region Private Methods - - private static string GetFullyQualifiedName(string procedureName) - { - return Prefix + procedureName; - } - - #endregion - - #region NotificationTypes CRUD - + public int CreateNotificationType(string name, string description, int timeToLive, int desktopModuleId, int createUpdateUserId, bool isTask) { - return _provider.ExecuteScalar(GetFullyQualifiedName("CreateNotificationType"), name, _provider.GetNull(description), _provider.GetNull(timeToLive), _provider.GetNull(desktopModuleId), createUpdateUserId, isTask); + return this._provider.ExecuteScalar(GetFullyQualifiedName("CreateNotificationType"), name, this._provider.GetNull(description), this._provider.GetNull(timeToLive), this._provider.GetNull(desktopModuleId), createUpdateUserId, isTask); } public void DeleteNotificationType(int notificationTypeId) { - _provider.ExecuteNonQuery(GetFullyQualifiedName("DeleteNotificationType"), notificationTypeId); + this._provider.ExecuteNonQuery(GetFullyQualifiedName("DeleteNotificationType"), notificationTypeId); } + + private static string GetFullyQualifiedName(string procedureName) + { + return Prefix + procedureName; + } public IDataReader GetNotificationType(int notificationTypeId) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotificationType"), notificationTypeId); + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationType"), notificationTypeId); } public IDataReader GetNotificationTypeByName(string name) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeByName"), name); - } - - #endregion - - #region NotificationTypeActions CRUD - + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeByName"), name); + } + public int AddNotificationTypeAction(int notificationTypeId, string nameResourceKey, string descriptionResourceKey, string confirmResourceKey, string apiCall, int createdByUserId) { - return _provider.ExecuteScalar(GetFullyQualifiedName("AddNotificationTypeAction"), notificationTypeId, nameResourceKey, _provider.GetNull(descriptionResourceKey), _provider.GetNull(confirmResourceKey), apiCall, createdByUserId); + return this._provider.ExecuteScalar(GetFullyQualifiedName("AddNotificationTypeAction"), notificationTypeId, nameResourceKey, this._provider.GetNull(descriptionResourceKey), this._provider.GetNull(confirmResourceKey), apiCall, createdByUserId); } public void DeleteNotificationTypeAction(int notificationTypeActionId) { - _provider.ExecuteNonQuery(GetFullyQualifiedName("DeleteNotificationTypeAction"), notificationTypeActionId); + this._provider.ExecuteNonQuery(GetFullyQualifiedName("DeleteNotificationTypeAction"), notificationTypeActionId); } public IDataReader GetNotificationTypeAction(int notificationTypeActionId) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeAction"), notificationTypeActionId); + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeAction"), notificationTypeActionId); } public IDataReader GetNotificationTypeActionByName(int notificationTypeId, string name) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeActionByName"), notificationTypeId, name); + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeActionByName"), notificationTypeId, name); } public IDataReader GetNotificationTypeActions(int notificationTypeId) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeActions"), notificationTypeId); - } - - #endregion - - #region Notifications Public Methods - + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeActions"), notificationTypeId); + } + public int SendNotification(Notification notification, int portalId) { var createdByUserId = UserController.Instance.GetCurrentUserInfo().UserID; - return _provider.ExecuteScalar(GetFullyQualifiedName("SendNotification"), - notification.NotificationTypeID, - portalId, - notification.To, - notification.From, - notification.Subject, - notification.Body, - notification.SenderUserID, - createdByUserId, - _provider.GetNull(notification.ExpirationDate), - notification.IncludeDismissAction, - notification.Context); + return this._provider.ExecuteScalar( + GetFullyQualifiedName("SendNotification"), + notification.NotificationTypeID, + portalId, + notification.To, + notification.From, + notification.Subject, + notification.Body, + notification.SenderUserID, + createdByUserId, + this._provider.GetNull(notification.ExpirationDate), + notification.IncludeDismissAction, + notification.Context); } public void DeleteNotification(int notificationId) { - _provider.ExecuteNonQuery(GetFullyQualifiedName("DeleteNotification"), notificationId); + this._provider.ExecuteNonQuery(GetFullyQualifiedName("DeleteNotification"), notificationId); } public int DeleteUserNotifications(int userId, int portalId) { - return userId <= 0 ? 0 : _provider.ExecuteScalar(GetFullyQualifiedName("DeleteUserNotifications"), userId, portalId); + return userId <= 0 ? 0 : this._provider.ExecuteScalar(GetFullyQualifiedName("DeleteUserNotifications"), userId, portalId); } public int CountNotifications(int userId, int portalId) { - return userId <= 0 ? 0 : _provider.ExecuteScalar(GetFullyQualifiedName("CountNotifications"), userId, portalId); + return userId <= 0 ? 0 : this._provider.ExecuteScalar(GetFullyQualifiedName("CountNotifications"), userId, portalId); } public IDataReader GetNotifications(int userId, int portalId, int afterNotificationId, int numberOfRecords) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotifications"), userId, portalId, afterNotificationId, numberOfRecords); + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotifications"), userId, portalId, afterNotificationId, numberOfRecords); } public IDataReader GetNotification(int notificationId) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotification"), notificationId); + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotification"), notificationId); } public IDataReader GetNotificationByContext(int notificationTypeId, string context) { - return _provider.ExecuteReader(GetFullyQualifiedName("GetNotificationByContext"), notificationTypeId, context); + return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationByContext"), notificationTypeId, context); + } + + public bool IsToastPending(int notificationId) + { + return this._provider.ExecuteScalar( + GetFullyQualifiedName("IsToastPending"), + notificationId); } - #endregion - - #region Toast - - public bool IsToastPending(int notificationId) - { - return _provider.ExecuteScalar(GetFullyQualifiedName("IsToastPending"), - notificationId); - } - - /// - /// Mark a Toast ready for sending - /// - /// The notification Id - /// The Recipient User Id - public void MarkReadyForToast(int notificationId, int userId) - { - _provider.ExecuteNonQuery(GetFullyQualifiedName("MarkReadyForToast"), notificationId, userId); - } - - /// - /// Mark Toast being already sent - /// - /// The notification Id - /// The Recipient User Id - public void MarkToastSent(int notificationId, int userId) - { - _provider.ExecuteNonQuery(GetFullyQualifiedName("MarkToastSent"), notificationId, userId); - } - - public IDataReader GetToasts(int userId, int portalId) - { - return _provider.ExecuteReader(GetFullyQualifiedName("GetToasts"), userId, portalId); - } + /// + /// Mark a Toast ready for sending. + /// + /// The notification Id. + /// The Recipient User Id. + public void MarkReadyForToast(int notificationId, int userId) + { + this._provider.ExecuteNonQuery(GetFullyQualifiedName("MarkReadyForToast"), notificationId, userId); + } - #endregion + /// + /// Mark Toast being already sent. + /// + /// The notification Id. + /// The Recipient User Id. + public void MarkToastSent(int notificationId, int userId) + { + this._provider.ExecuteNonQuery(GetFullyQualifiedName("MarkToastSent"), notificationId, userId); + } + public IDataReader GetToasts(int userId, int portalId) + { + return this._provider.ExecuteReader(GetFullyQualifiedName("GetToasts"), userId, portalId); + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/Data/IDataService.cs b/DNN Platform/Library/Services/Social/Notifications/Data/IDataService.cs index c5d2a356666..b00af56ea5c 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Data/IDataService.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Data/IDataService.cs @@ -1,184 +1,168 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Social.Notifications.Data { + using System; + using System.Data; + public interface IDataService { - #region NotificationTypes CRUD - /// - /// Creates a new Notification Type + /// Creates a new Notification Type. /// - /// Name of the Notification Type - /// Description of the Notification Type - /// Time to live of the Notification Type - /// Id of the desktop module to which the Notification Type is associated - /// Id of the user that creates and updates the Notification Type - /// Whether this Notification Type is task or not - /// Id of the created Notification Type + /// Name of the Notification Type. + /// Description of the Notification Type. + /// Time to live of the Notification Type. + /// Id of the desktop module to which the Notification Type is associated. + /// Id of the user that creates and updates the Notification Type. + /// Whether this Notification Type is task or not. + /// Id of the created Notification Type. int CreateNotificationType(string name, string description, int timeToLive, int desktopModuleId, int createUpdateUserId, bool isTask); /// - /// Deletes an existing Notification Type + /// Deletes an existing Notification Type. /// - /// Id of the Notification Type to delete + /// Id of the Notification Type to delete. void DeleteNotificationType(int notificationTypeId); /// - /// Gets a Notification Type + /// Gets a Notification Type. /// - /// If of the Notification Type to get - /// IDataReader with the retrieved data + /// If of the Notification Type to get. + /// IDataReader with the retrieved data. IDataReader GetNotificationType(int notificationTypeId); /// - /// Gets a Notification Type + /// Gets a Notification Type. /// - /// Name of the Notification Type to get - /// IDataReader with the retrieved data + /// Name of the Notification Type to get. + /// IDataReader with the retrieved data. IDataReader GetNotificationTypeByName(string name); - #endregion - - #region NotificationTypeActions CRUD - /// - /// Creates a new Notification Type Action + /// Creates a new Notification Type Action. /// - /// Id of the Notification Type to which the Notification Type Action is associated - /// Resource key used to get the localized name of the Notification Type Action - /// Resource key used to get the localized description of the Notification Type Action - /// Resource key used to get the localized confirm text of the Notification Type Action - /// Relative url to the api that has to be call when selection the Notification Type Action - /// Id of the user that created the Notification Type Action - /// The created Notification Type Action + /// Id of the Notification Type to which the Notification Type Action is associated. + /// Resource key used to get the localized name of the Notification Type Action. + /// Resource key used to get the localized description of the Notification Type Action. + /// Resource key used to get the localized confirm text of the Notification Type Action. + /// Relative url to the api that has to be call when selection the Notification Type Action. + /// Id of the user that created the Notification Type Action. + /// The created Notification Type Action. int AddNotificationTypeAction(int notificationTypeId, string nameResourceKey, string descriptionResourceKey, string confirmResourceKey, string apiCall, int createdByUserId); /// - /// Deletes a Notification Type Action + /// Deletes a Notification Type Action. /// - /// Id of the Notification Type Action to deleted + /// Id of the Notification Type Action to deleted. void DeleteNotificationTypeAction(int notificationTypeActionId); /// - /// Gets a Notification Type Action + /// Gets a Notification Type Action. /// - /// Id of the Notification Type Action to get - /// DataReader with the retrieved data + /// Id of the Notification Type Action to get. + /// DataReader with the retrieved data. IDataReader GetNotificationTypeAction(int notificationTypeActionId); /// - /// Gets a Notification Type Action + /// Gets a Notification Type Action. /// - /// Id of the Notification Type to which the Notification Type Action is associated - /// Name of the Notification Type Action - /// DataReader with the retrieved data + /// Id of the Notification Type to which the Notification Type Action is associated. + /// Name of the Notification Type Action. + /// DataReader with the retrieved data. IDataReader GetNotificationTypeActionByName(int notificationTypeId, string name); /// - /// Gets all the Notification Type Action of a Notification Type + /// Gets all the Notification Type Action of a Notification Type. /// - /// Id of the Notification Type from which we want to get the associated Notification Type Actions - /// DataReader with the retrieved data + /// Id of the Notification Type from which we want to get the associated Notification Type Actions. + /// DataReader with the retrieved data. IDataReader GetNotificationTypeActions(int notificationTypeId); - #endregion - - #region Notifications - /// - /// Send a notification to its receivers + /// Send a notification to its receivers. /// - /// Notification to send - /// Portal id of the Notification - /// Id of the new message + /// Notification to send. + /// Portal id of the Notification. + /// Id of the new message. int SendNotification(Notification notification, int portalId); /// - /// Delete a Notification + /// Delete a Notification. /// - /// Id of the Notification to delete + /// Id of the Notification to delete. void DeleteNotification(int notificationId); /// - /// Deletes all the Notifications of a user + /// Deletes all the Notifications of a user. /// - /// Portal Id of the user - /// User from who delete all the Notifications - /// Amount of deleted Notifications + /// Portal Id of the user. + /// User from who delete all the Notifications. + /// Amount of deleted Notifications. int DeleteUserNotifications(int portalID, int userID); /// - /// Gets the amount of Notifications of a user + /// Gets the amount of Notifications of a user. /// - /// Id of the user from who count the Notifications - /// Portal Id of the user - /// The amount of Notifications of a user + /// Id of the user from who count the Notifications. + /// Portal Id of the user. + /// The amount of Notifications of a user. int CountNotifications(int userId, int portalId); /// - /// Gets a paginated list of Notifications + /// Gets a paginated list of Notifications. /// - /// Id of the user from get the Notifications - /// Portal Id of the user - /// Id of the Notification after which get the list of Notificationss - /// Maximum amount of retrieved Notifications - /// DataReader with the retrieved data + /// Id of the user from get the Notifications. + /// Portal Id of the user. + /// Id of the Notification after which get the list of Notificationss. + /// Maximum amount of retrieved Notifications. + /// DataReader with the retrieved data. IDataReader GetNotifications(int userId, int portalId, int afterNotificationId, int numberOfRecords); /// - /// Gets a Notification + /// Gets a Notification. /// - /// Id of the Notification to get - /// DataReader with the retrieved data + /// Id of the Notification to get. + /// DataReader with the retrieved data. IDataReader GetNotification(int notificationId); /// - /// Gets a Notification + /// Gets a Notification. /// - /// Id of the Noticationb type of the Notification - /// Context of the Notification to get - /// DataReader with the retrieved data + /// Id of the Noticationb type of the Notification. + /// Context of the Notification to get. + /// DataReader with the retrieved data. IDataReader GetNotificationByContext(int notificationTypeId, string context); - #endregion - - #region Toast - /// - /// Whether a Toast Notification is pending or not + /// Whether a Toast Notification is pending or not. /// - /// Id of the Notification to check - /// True if the Toast Notification is pending, False if it is not + /// Id of the Notification to check. + /// True if the Toast Notification is pending, False if it is not. bool IsToastPending(int notificationId); - /// - /// Mark a Toast ready for sending - /// - /// The notification Id - /// The Recipient User Id - void MarkReadyForToast(int notificationId, int userId); + /// + /// Mark a Toast ready for sending. + /// + /// The notification Id. + /// The Recipient User Id. + void MarkReadyForToast(int notificationId, int userId); - /// - /// Mark Toast being already sent - /// - /// The notification Id - /// The Recipient User Id - void MarkToastSent(int notificationId, int userId); + /// + /// Mark Toast being already sent. + /// + /// The notification Id. + /// The Recipient User Id. + void MarkToastSent(int notificationId, int userId); /// /// Get a list of Toast Notifications that have not been delivered yet. /// /// Id of the user from who we want to know which Toast Notifications have not been delivered yet. - /// Portal Id of the user - /// DataReader with the retrieved data + /// Portal Id of the user. + /// DataReader with the retrieved data. IDataReader GetToasts(int userId, int portalId); - - #endregion } } diff --git a/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs b/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs index 59030949dab..b3e49ed42b3 100644 --- a/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs +++ b/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs @@ -1,65 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Notifications { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + /// /// Defines the methods to work with Notifications, NotificationTypes, NotificationTypeActions and NotificationActions. /// public interface INotificationsController - { - #region NotificationTypes Methods - + { /// /// Creates a new notification type. /// /// void CreateNotificationType(NotificationType notificationType); - + /// /// Deletes an existing notification type. /// /// The notification type identifier. void DeleteNotificationType(int notificationTypeId); - + /// /// Gets a notification type by identifier. /// /// The notification type identifier. /// The notification type with the provided identifier. NotificationType GetNotificationType(int notificationTypeId); - + /// /// Gets a notification type by name. /// /// The notification type name. /// The notification type with the provided name. - NotificationType GetNotificationType(string name); - - #endregion - - #region NotificationTypeActions Methods - + NotificationType GetNotificationType(string name); + /// /// Deletes an existing notification type action. /// /// The notification type action identifier. void DeleteNotificationTypeAction(int notificationTypeActionId); - + /// /// Gets a notification type action by identifier. /// /// The notification type action identifier. /// The notification type action with the provided identifier. NotificationTypeAction GetNotificationTypeAction(int notificationTypeActionId); - + /// /// Gets a notification type action by notification type and name. /// @@ -67,7 +61,7 @@ public interface INotificationsController /// The notification type action name. /// The notification type action with the provided notification type and name. NotificationTypeAction GetNotificationTypeAction(int notificationTypeId, string name); - + /// /// Gets the list of notification type actions for the provided notification type. /// @@ -76,26 +70,21 @@ public interface INotificationsController IList GetNotificationTypeActions(int notificationTypeId); /// - /// Set the actions for a NotificationType + /// Set the actions for a NotificationType. /// - /// The actions - /// Id of the notification type - void SetNotificationTypeActions(IList actions, int notificationTypeId); - - #endregion - - #region Notifications Methods - + /// The actions. + /// Id of the notification type. + void SetNotificationTypeActions(IList actions, int notificationTypeId); + /// /// Creates a new notification and sets is sender as the portal administrator. /// - /// The notification - /// The portalId + /// The notification. + /// The portalId. /// The list of roles to send the notification to. Leave it as null to send only to individual users. /// The list of users to send the notification to. Leave it as null to send only to roles. - /// The new notification. void SendNotification(Notification notification, int portalId, IList roles, IList users); - + /// /// Counts the notifications sent to the provided user in the specified portal. /// @@ -103,7 +92,7 @@ public interface INotificationsController /// The portal identifier. /// The number of notifications sent to the provided user in the specified portal. int CountNotifications(int userId, int portalId); - + /// /// Gets a list of notifications sent to the provided user in the specified portal. /// @@ -126,7 +115,7 @@ public interface INotificationsController /// Deletes all user notifications in a specific portal. ///
    /// The user to delete notifications for. - /// Number of deleted notifications + /// Number of deleted notifications. int DeleteUserNotifications(UserInfo user); /// @@ -141,65 +130,59 @@ public interface INotificationsController /// Deletes all NotificationRecipient for the NotificationId. /// /// It also deletes the notification. - /// The notification identifier. + /// The notification identifier. void DeleteAllNotificationRecipients(int notificationId); /// /// Deletes an individual notification recipient based on NotificationTypeId, Context and UserId. /// /// It also deletes the notification if there are no more recipients. - /// Id of the notification type + /// Id of the notification type. /// Context set by creator of the notification. /// The user identifier. void DeleteNotificationRecipient(int notificationTypeId, string context, int userId); /// - /// Get a Notification + /// Get a Notification. /// - /// The notificationId - /// A notification + /// The notificationId. + /// A notification. Notification GetNotification(int notificationId); /// - /// Get a Notification by NotificationTypeId and Context + /// Get a Notification by NotificationTypeId and Context. /// - /// Id of the notification type + /// Id of the notification type. /// Context set by creator of the notification. /// The filtered list of notifications sent to the provided user in the specified portal. - IList GetNotificationByContext(int notificationTypeId, string context); - - #endregion - - #region Toast APIS - - /// - /// Is there a Toast that needs to be sent for a Notification - /// - /// The Notification Id - /// True if Toast needs to be sent. False otherwise. - bool IsToastPending(int notificationId); - - /// - /// Mark a Toast ready for sending - /// - /// The notification Object - /// The Recipient User Info Object - void MarkReadyForToast(Notification notification, UserInfo userInfo); - - /// - /// Mark Toast being already sent - /// - /// The notification Id - /// The Recipient User Id - void MarkToastSent(int notificationId, int userId); - - /// - /// Get a list of Toasts that have not been delivered yet. - /// - /// UserInfo object - /// List of Undelivered Toasts for the user specific to the portal - IList GetToasts(UserInfo userInfo); - - #endregion + IList GetNotificationByContext(int notificationTypeId, string context); + + /// + /// Is there a Toast that needs to be sent for a Notification. + /// + /// The Notification Id. + /// True if Toast needs to be sent. False otherwise. + bool IsToastPending(int notificationId); + + /// + /// Mark a Toast ready for sending. + /// + /// The notification Object. + /// The Recipient User Info Object. + void MarkReadyForToast(Notification notification, UserInfo userInfo); + + /// + /// Mark Toast being already sent. + /// + /// The notification Id. + /// The Recipient User Id. + void MarkToastSent(int notificationId, int userId); + + /// + /// Get a list of Toasts that have not been delivered yet. + /// + /// UserInfo object. + /// List of Undelivered Toasts for the user specific to the portal. + IList GetToasts(UserInfo userInfo); } } diff --git a/DNN Platform/Library/Services/Social/Notifications/Notification.cs b/DNN Platform/Library/Services/Social/Notifications/Notification.cs index 151025f9e10..1a8b4598059 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Notification.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Notification.cs @@ -1,196 +1,184 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Notifications { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Notifications /// Class: Notification /// ----------------------------------------------------------------------------- /// - /// The Notification class describes the a notification received by a user as a consecuence of an action + /// The Notification class describes the a notification received by a user as a consecuence of an action. /// /// ----------------------------------------------------------------------------- [Serializable] public class Notification : BaseEntityInfo, IHydratable - { - #region Private Properties - + { private int _notificationID = -1; - private string _displayDate; - - #endregion - - #region Public Properties - + private string _displayDate; + + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public Notification() + { + this.SendToast = true; + } + /// - /// NotificationID - The primary key + /// Gets or sets notificationID - The primary key. /// [XmlAttribute] public int NotificationID { get { - return _notificationID; + return this._notificationID; } + set { - _notificationID = value; + this._notificationID = value; } } /// - /// The message type identifier. + /// Gets or sets the message type identifier. /// [XmlAttribute] public int NotificationTypeID { get; set; } /// - /// To list for the message. This information is saved for faster display of To list in the message + /// Gets or sets to list for the message. This information is saved for faster display of To list in the message. /// [XmlAttribute] public string To { get; set; } /// - /// Message From + /// Gets or sets message From. /// [XmlAttribute] public string From { get; set; } /// - /// Message Subject + /// Gets or sets message Subject. /// [XmlAttribute] public string Subject { get; set; } /// - /// Message body + /// Gets or sets message body. /// [XmlAttribute] public string Body { get; set; } /// - /// Context set by creator of the notification + /// Gets or sets context set by creator of the notification. /// [XmlAttribute] public string Context { get; set; } /// - /// The UserID of the sender of the message + /// Gets or sets the UserID of the sender of the message. /// [XmlAttribute] public int SenderUserID { get; set; } /// - /// A pretty printed string with the time since the message was created + /// Gets a pretty printed string with the time since the message was created. /// [XmlAttribute] public string DisplayDate { get { - if (string.IsNullOrEmpty(_displayDate)) + if (string.IsNullOrEmpty(this._displayDate)) { - _displayDate = DateUtils.CalculateDateForDisplay(CreatedOnDate); + this._displayDate = DateUtils.CalculateDateForDisplay(this.CreatedOnDate); } - return _displayDate; + + return this._displayDate; } } /// - /// For notifications, this field indicates when it has to be removed (or not displayed) + /// Gets or sets for notifications, this field indicates when it has to be removed (or not displayed). /// [XmlAttribute] public DateTime ExpirationDate { get; set; } /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID { get { - return NotificationID; + return this.NotificationID; } + set { - NotificationID = value; + this.NotificationID = value; } } /// - /// Should this notification support a dismiss action + /// Gets or sets a value indicating whether should this notification support a dismiss action. /// [XmlAttribute] public bool IncludeDismissAction { get; set; } /// - /// The notification is displayed on the UI as a toast notification + /// Gets or sets a value indicating whether the notification is displayed on the UI as a toast notification. /// - [XmlAttribute] - public bool SendToast { get; set; } - - #endregion - - #region Constructors - - /// - /// Default constructor - /// - public Notification() - { - SendToast = true; - } - - #endregion - - #region Public Methods - + [XmlAttribute] + public bool SendToast { get; set; } + /// /// Fill the object with data from database. /// /// the data reader. public void Fill(IDataReader dr) { - NotificationID = Convert.ToInt32(dr["MessageID"]); - NotificationTypeID = Convert.ToInt32(dr["NotificationTypeID"]); - To = Null.SetNullString(dr["To"]); - From = Null.SetNullString(dr["From"]); - Subject = Null.SetNullString(dr["Subject"]); - Body = Null.SetNullString(dr["Body"]); - Context = Null.SetNullString(dr["Context"]); - SenderUserID = Convert.ToInt32(dr["SenderUserID"]); - ExpirationDate = Null.SetNullDateTime(dr["ExpirationDate"]); - IncludeDismissAction = Null.SetNullBoolean(dr["IncludeDismissAction"]); - - var schema = dr.GetSchemaTable(); - if (schema != null) - { - if (schema.Select("ColumnName = 'SendToast'").Length > 0) - { - SendToast = Null.SetNullBoolean(dr["SendToast"]); - } - else - { - SendToast = false; - } - } - - //add audit column data - FillInternal(dr); - } + this.NotificationID = Convert.ToInt32(dr["MessageID"]); + this.NotificationTypeID = Convert.ToInt32(dr["NotificationTypeID"]); + this.To = Null.SetNullString(dr["To"]); + this.From = Null.SetNullString(dr["From"]); + this.Subject = Null.SetNullString(dr["Subject"]); + this.Body = Null.SetNullString(dr["Body"]); + this.Context = Null.SetNullString(dr["Context"]); + this.SenderUserID = Convert.ToInt32(dr["SenderUserID"]); + this.ExpirationDate = Null.SetNullDateTime(dr["ExpirationDate"]); + this.IncludeDismissAction = Null.SetNullBoolean(dr["IncludeDismissAction"]); + + var schema = dr.GetSchemaTable(); + if (schema != null) + { + if (schema.Select("ColumnName = 'SendToast'").Length > 0) + { + this.SendToast = Null.SetNullBoolean(dr["SendToast"]); + } + else + { + this.SendToast = false; + } + } - #endregion + // add audit column data + this.FillInternal(dr); + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs index 5f824243f46..92868be7ccf 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Notifications { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Services.Social.Notifications @@ -29,35 +29,36 @@ public class NotificationType : BaseEntityInfo, IHydratable private int _desktopModuleId = -1; /// - /// The notification type identifier. + /// Gets or sets the notification type identifier. /// [XmlAttribute] public int NotificationTypeId { get { - return _notificationTypeId; + return this._notificationTypeId; } + set { - _notificationTypeId = value; + this._notificationTypeId = value; } } /// - /// The notification type name. + /// Gets or sets the notification type name. /// [XmlAttribute] public string Name { get; set; } /// - /// The notification type description. + /// Gets or sets the notification type description. /// [XmlAttribute] public string Description { get; set; } /// - /// The amount of time to add to the creation date of the message to calculate the expiration date. + /// Gets or sets the amount of time to add to the creation date of the message to calculate the expiration date. /// /// /// Minutes precision. Seconds won't be considered. @@ -66,7 +67,7 @@ public int NotificationTypeId public TimeSpan TimeToLive { get; set; } /// - /// If the message type is related to a specific module, this field is used to localize actions by getting the resource file from the module folder. + /// Gets or sets if the message type is related to a specific module, this field is used to localize actions by getting the resource file from the module folder. /// /// /// The resource file used will be SharedResources by convention. @@ -76,33 +77,32 @@ public int DesktopModuleId { get { - return _desktopModuleId; + return this._desktopModuleId; } + set { - _desktopModuleId = value; + this._desktopModuleId = value; } } /// - /// Is this of a Task type. Default is false. + /// Gets or sets a value indicating whether is this of a Task type. Default is false. /// /// /// Tasks are primarily notifications where an action must be taken. Dismiss is usually not enough. /// [XmlAttribute] - public bool IsTask { get; set; } - - #region Implementation of IHydratable - + public bool IsTask { get; set; } + /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID { - get { return NotificationTypeId; } - set { NotificationTypeId = value; } + get { return this.NotificationTypeId; } + set { this.NotificationTypeId = value; } } /// @@ -111,21 +111,20 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"]); - Name = dr["Name"].ToString(); - Description = Null.SetNullString(dr["Description"]); + this.NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"]); + this.Name = dr["Name"].ToString(); + this.Description = Null.SetNullString(dr["Description"]); var timeToLive = Null.SetNullInteger(dr["TTL"]); if (timeToLive != Null.NullInteger) { - TimeToLive = new TimeSpan(0, timeToLive, 0); + this.TimeToLive = new TimeSpan(0, timeToLive, 0); } - DesktopModuleId = Null.SetNullInteger(dr["DesktopModuleID"]); - IsTask = Null.SetNullBoolean(dr["IsTask"]); - - //add audit column data - FillInternal(dr); - } + + this.DesktopModuleId = Null.SetNullInteger(dr["DesktopModuleID"]); + this.IsTask = Null.SetNullBoolean(dr["IsTask"]); - #endregion + // add audit column data + this.FillInternal(dr); + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs index 0b5415412da..7f156add21b 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Notifications { + using System; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Services.Social.Notifications @@ -27,67 +27,66 @@ public class NotificationTypeAction : BaseEntityInfo, IHydratable private int _notificationTypeActionId = -1; /// - /// The notification type action identifier. + /// Gets or sets the notification type action identifier. /// [XmlAttribute] public int NotificationTypeActionId { get { - return _notificationTypeActionId; + return this._notificationTypeActionId; } + set { - _notificationTypeActionId = value; + this._notificationTypeActionId = value; } } /// - /// The notification type identifier. + /// Gets or sets the notification type identifier. /// [XmlAttribute] public int NotificationTypeId { get; set; } /// - /// The notification type action name resource key. + /// Gets or sets the notification type action name resource key. /// [XmlAttribute] public string NameResourceKey { get; set; } /// - /// The notification type action description resource key. + /// Gets or sets the notification type action description resource key. /// [XmlAttribute] public string DescriptionResourceKey { get; set; } /// - /// The notification type action confirmation resource key. + /// Gets or sets the notification type action confirmation resource key. /// [XmlAttribute] public string ConfirmResourceKey { get; set; } /// - /// The notification type action order to be used while displaying the list of available actions. + /// Gets or sets the notification type action order to be used while displaying the list of available actions. /// [XmlAttribute] public int Order { get; set; } /// - /// The Service Framework URL to be called when the action is performed. + /// Gets or sets the Service Framework URL to be called when the action is performed. /// [XmlAttribute] - public string APICall { get; set; } - - #region Implementation of IHydratable - + public string APICall { get; set; } + /// - /// IHydratable.KeyID. + /// Gets or sets iHydratable.KeyID. /// [XmlIgnore] public int KeyID { - get { return NotificationTypeActionId; } - set { NotificationTypeActionId = value; } + get { return this.NotificationTypeActionId; } + set { this.NotificationTypeActionId = value; } } /// @@ -96,18 +95,16 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - NotificationTypeActionId = Convert.ToInt32(dr["NotificationTypeActionID"]); - NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"]); - NameResourceKey = dr["NameResourceKey"].ToString(); - DescriptionResourceKey = Null.SetNullString(dr["DescriptionResourceKey"]); - ConfirmResourceKey = Null.SetNullString(dr["ConfirmResourceKey"]); - Order = Convert.ToInt32(dr["Order"]); - APICall = dr["APICall"].ToString(); - - //add audit column data - FillInternal(dr); - } + this.NotificationTypeActionId = Convert.ToInt32(dr["NotificationTypeActionID"]); + this.NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"]); + this.NameResourceKey = dr["NameResourceKey"].ToString(); + this.DescriptionResourceKey = Null.SetNullString(dr["DescriptionResourceKey"]); + this.ConfirmResourceKey = Null.SetNullString(dr["ConfirmResourceKey"]); + this.Order = Convert.ToInt32(dr["Order"]); + this.APICall = dr["APICall"].ToString(); - #endregion + // add audit column data + this.FillInternal(dr); + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs index 34020bb6b71..b0e6660182e 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs @@ -1,81 +1,70 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Services.Social.Notifications.Data; -using DotNetNuke.Services.Cache; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Notifications { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications.Data; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// /// Provides the methods to work with Notifications, NotificationTypes, NotificationTypeActions and NotificationActions. /// - public class NotificationsController - : ServiceLocator - , INotificationsController + public class NotificationsController + : ServiceLocator, + INotificationsController { + internal const int ConstMaxSubject = 400; + internal const int ConstMaxTo = 2000; + private const string ToastsCacheKey = "GetToasts_{0}"; + protected override Func GetFactory() { return () => new NotificationsController(); - } - - #region Constants - - internal const int ConstMaxSubject = 400; - internal const int ConstMaxTo = 2000; - private const string ToastsCacheKey = "GetToasts_{0}"; - - #endregion - - #region Private Variables - + } private readonly IDataService _dataService; - private readonly Messaging.Data.IDataService _messagingDataService; - - #endregion - - #region Constructors - - /// - /// Default constructor + private readonly Messaging.Data.IDataService _messagingDataService; + + /// + /// Initializes a new instance of the class. + /// Default constructor. /// public NotificationsController() : this(DataService.Instance, Messaging.Data.DataService.Instance) { - } - - /// - /// Constructor from specifict data service + } + + /// + /// Initializes a new instance of the class. + /// Constructor from specifict data service. /// - /// Class with methods to do CRUD in database for the entities of types , and - /// Class with methods to do CRUD in database for the entities of types , and and to interact with the stored procedures regarding messaging + /// Class with methods to do CRUD in database for the entities of types , and . + /// Class with methods to do CRUD in database for the entities of types , and and to interact with the stored procedures regarding messaging. public NotificationsController(IDataService dataService, Messaging.Data.IDataService messagingDataService) { Requires.NotNull("dataService", dataService); Requires.NotNull("messagingDataService", messagingDataService); - _dataService = dataService; - _messagingDataService = messagingDataService; - } - - #endregion - - #region Public API - + this._dataService = dataService; + this._messagingDataService = messagingDataService; + } + public void SetNotificationTypeActions(IList actions, int notificationTypeId) { Requires.NotNull("actions", actions); @@ -97,20 +86,24 @@ public void SetNotificationTypeActions(IList actions, in foreach (var action in actions) { - action.NotificationTypeActionId = _dataService.AddNotificationTypeAction(notificationTypeId, - action.NameResourceKey, - action.DescriptionResourceKey, - action.ConfirmResourceKey, - action.APICall, - GetCurrentUserId()); + action.NotificationTypeActionId = this._dataService.AddNotificationTypeAction( + notificationTypeId, + action.NameResourceKey, + action.DescriptionResourceKey, + action.ConfirmResourceKey, + action.APICall, + this.GetCurrentUserId()); action.NotificationTypeId = notificationTypeId; } } public virtual int CountNotifications(int userId, int portalId) { - if (userId <= 0) return 0; - + if (userId <= 0) + { + return 0; + } + var cacheKey = string.Format(DataCache.UserNotificationsCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); @@ -119,7 +112,7 @@ public virtual int CountNotifications(int userId, int portalId) return (int)cacheObject; } - var count = _dataService.CountNotifications(userId, portalId); + var count = this._dataService.CountNotifications(userId, portalId); cache.Insert(cacheKey, count, (DNNCacheDependency)null, DateTime.Now.AddSeconds(DataCache.NotificationsCacheTimeInSec), System.Web.Caching.Cache.NoSlidingExpiration); return count; @@ -137,22 +130,22 @@ public virtual void SendNotification(Notification notification, int portalId, IL if (notification.SenderUserID < 1) { - notification.SenderUserID = GetAdminUser().UserID; + notification.SenderUserID = this.GetAdminUser().UserID; } if (string.IsNullOrEmpty(notification.Subject) && string.IsNullOrEmpty(notification.Body)) { - throw new ArgumentException(Localization.Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.ExceptionsResourceFile)); } if (roles == null && users == null) { - throw new ArgumentException(Localization.Localization.GetString("MsgRolesOrUsersRequiredError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgRolesOrUsersRequiredError", Localization.ExceptionsResourceFile)); } if (!string.IsNullOrEmpty(notification.Subject) && notification.Subject.Length > ConstMaxSubject) { - throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgSubjectTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxSubject, notification.Subject.Length)); + throw new ArgumentException(string.Format(Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), ConstMaxSubject, notification.Subject.Length)); } var sbTo = new StringBuilder(); @@ -166,28 +159,31 @@ public virtual void SendNotification(Notification notification, int portalId, IL if (users != null) { - foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) sbTo.Append(user.DisplayName + ","); + foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) + { + sbTo.Append(user.DisplayName + ","); + } } if (sbTo.Length == 0) { - throw new ArgumentException(Localization.Localization.GetString("MsgEmptyToListFoundError", Localization.Localization.ExceptionsResourceFile)); + throw new ArgumentException(Localization.GetString("MsgEmptyToListFoundError", Localization.ExceptionsResourceFile)); } if (sbTo.Length > ConstMaxTo) { - throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgToListTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); + throw new ArgumentException(string.Format(Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); } notification.To = sbTo.ToString().Trim(','); - if (notification.ExpirationDate != new DateTime()) + if (notification.ExpirationDate != default(DateTime)) { - notification.ExpirationDate = GetExpirationDate(notification.NotificationTypeID); + notification.ExpirationDate = this.GetExpirationDate(notification.NotificationTypeID); } - notification.NotificationID = _dataService.SendNotification(notification, pid); + notification.NotificationID = this._dataService.SendNotification(notification, pid); - //send message to Roles + // send message to Roles if (roles != null) { var roleIds = string.Empty; @@ -196,13 +192,13 @@ public virtual void SendNotification(Notification notification, int portalId, IL .Aggregate(roleIds, (current, roleId) => current + (roleId + ",")) .Trim(','); - _messagingDataService.CreateMessageRecipientsForRole( + this._messagingDataService.CreateMessageRecipientsForRole( notification.NotificationID, roleIds, UserController.Instance.GetCurrentUserInfo().UserID); } - //send message to each User - this should be called after CreateMessageRecipientsForRole. + // send message to each User - this should be called after CreateMessageRecipientsForRole. if (users == null) { users = new List(); @@ -210,27 +206,27 @@ public virtual void SendNotification(Notification notification, int portalId, IL var recipients = from user in users where InternalMessagingController.Instance.GetMessageRecipient(notification.NotificationID, user.UserID) == null - select new MessageRecipient - { - MessageID = notification.NotificationID, - UserID = user.UserID, - Read = false, - RecipientID = Null.NullInteger - }; + select new MessageRecipient + { + MessageID = notification.NotificationID, + UserID = user.UserID, + Read = false, + RecipientID = Null.NullInteger, + }; foreach (var recipient in recipients) { - _messagingDataService.SaveMessageRecipient( + this._messagingDataService.SaveMessageRecipient( recipient, UserController.Instance.GetCurrentUserInfo().UserID); } - //if sendToast is true, then mark all recipients' as ready for toast. + // if sendToast is true, then mark all recipients' as ready for toast. if (notification.SendToast) { foreach (var messageRecipient in InternalMessagingController.Instance.GetMessageRecipients(notification.NotificationID)) { - MarkReadyForToast(notification, messageRecipient.UserID); + this.MarkReadyForToast(notification, messageRecipient.UserID); } } } @@ -245,12 +241,13 @@ public void CreateNotificationType(NotificationType notificationType) notificationType.DesktopModuleId = Null.NullInteger; } - notificationType.NotificationTypeId = _dataService.CreateNotificationType(notificationType.Name, - notificationType.Description, - (int)notificationType.TimeToLive.TotalMinutes == 0 ? Null.NullInteger : (int)notificationType.TimeToLive.TotalMinutes, - notificationType.DesktopModuleId, - GetCurrentUserId(), - notificationType.IsTask); + notificationType.NotificationTypeId = this._dataService.CreateNotificationType( + notificationType.Name, + notificationType.Description, + (int)notificationType.TimeToLive.TotalMinutes == 0 ? Null.NullInteger : (int)notificationType.TimeToLive.TotalMinutes, + notificationType.DesktopModuleId, + this.GetCurrentUserId(), + notificationType.IsTask); } public virtual void DeleteNotification(int notificationId) @@ -260,13 +257,14 @@ public virtual void DeleteNotification(int notificationId) { DataCache.RemoveCache(string.Format(ToastsCacheKey, recipient.UserID)); } - _dataService.DeleteNotification(notificationId); + + this._dataService.DeleteNotification(notificationId); } public int DeleteUserNotifications(UserInfo user) { DataCache.RemoveCache(string.Format(ToastsCacheKey, user.UserID)); - return _dataService.DeleteUserNotifications(user.UserID, user.PortalID); + return this._dataService.DeleteUserNotifications(user.UserID, user.PortalID); } public virtual void DeleteNotificationRecipient(int notificationId, int userId) @@ -276,7 +274,7 @@ public virtual void DeleteNotificationRecipient(int notificationId, int userId) var recipients = InternalMessagingController.Instance.GetMessageRecipients(notificationId); if (recipients.Count == 0) { - DeleteNotification(notificationId); + this.DeleteNotification(notificationId); } } @@ -284,40 +282,40 @@ public virtual void DeleteAllNotificationRecipients(int notificationId) { foreach (var recipient in InternalMessagingController.Instance.GetMessageRecipients(notificationId)) { - DeleteNotificationRecipient(notificationId, recipient.UserID); + this.DeleteNotificationRecipient(notificationId, recipient.UserID); } } public virtual void DeleteNotificationRecipient(int notificationTypeId, string context, int userId) { - foreach (var notification in GetNotificationByContext(notificationTypeId, context)) + foreach (var notification in this.GetNotificationByContext(notificationTypeId, context)) { - DeleteNotificationRecipient(notification.NotificationID, userId); + this.DeleteNotificationRecipient(notification.NotificationID, userId); } } public Notification GetNotification(int notificationId) { - return CBO.FillObject(_dataService.GetNotification(notificationId)); + return CBO.FillObject(this._dataService.GetNotification(notificationId)); } public virtual IList GetNotificationByContext(int notificationTypeId, string context) { - return CBO.FillCollection(_dataService.GetNotificationByContext(notificationTypeId, context)); + return CBO.FillCollection(this._dataService.GetNotificationByContext(notificationTypeId, context)); } public virtual void DeleteNotificationType(int notificationTypeId) { - _dataService.DeleteNotificationType(notificationTypeId); + this._dataService.DeleteNotificationType(notificationTypeId); - RemoveNotificationTypeCache(); + this.RemoveNotificationTypeCache(); } public virtual void DeleteNotificationTypeAction(int notificationTypeActionId) { - _dataService.DeleteNotificationTypeAction(notificationTypeActionId); + this._dataService.DeleteNotificationTypeAction(notificationTypeActionId); - RemoveNotificationTypeActionCache(); + this.RemoveNotificationTypeActionCache(); } public virtual IList GetNotifications(int userId, int portalId, int afterNotificationId, int numberOfRecords) @@ -327,16 +325,17 @@ public virtual IList GetNotifications(int userId, int portalId, in { pid = PortalController.GetEffectivePortalId(portalId); } + return userId <= 0 ? new List(0) - : CBO.FillCollection(_dataService.GetNotifications(userId, pid, afterNotificationId, numberOfRecords)); + : CBO.FillCollection(this._dataService.GetNotifications(userId, pid, afterNotificationId, numberOfRecords)); } public virtual NotificationType GetNotificationType(int notificationTypeId) { var notificationTypeCacheKey = string.Format(DataCache.NotificationTypesCacheKey, notificationTypeId); var cacheItemArgs = new CacheItemArgs(notificationTypeCacheKey, DataCache.NotificationTypesTimeOut, DataCache.NotificationTypesCachePriority, notificationTypeId); - return CBO.GetCachedObject(cacheItemArgs, GetNotificationTypeCallBack); + return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeCallBack); } public virtual NotificationType GetNotificationType(string name) @@ -345,14 +344,14 @@ public virtual NotificationType GetNotificationType(string name) var notificationTypeCacheKey = string.Format(DataCache.NotificationTypesCacheKey, name); var cacheItemArgs = new CacheItemArgs(notificationTypeCacheKey, DataCache.NotificationTypesTimeOut, DataCache.NotificationTypesCachePriority, name); - return CBO.GetCachedObject(cacheItemArgs, GetNotificationTypeByNameCallBack); + return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeByNameCallBack); } public virtual NotificationTypeAction GetNotificationTypeAction(int notificationTypeActionId) { var notificationTypeActionCacheKey = string.Format(DataCache.NotificationTypeActionsCacheKey, notificationTypeActionId); var cacheItemArgs = new CacheItemArgs(notificationTypeActionCacheKey, DataCache.NotificationTypeActionsTimeOut, DataCache.NotificationTypeActionsPriority, notificationTypeActionId); - return CBO.GetCachedObject(cacheItemArgs, GetNotificationTypeActionCallBack); + return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeActionCallBack); } public virtual NotificationTypeAction GetNotificationTypeAction(int notificationTypeId, string name) @@ -361,38 +360,34 @@ public virtual NotificationTypeAction GetNotificationTypeAction(int notification var notificationTypeActionCacheKey = string.Format(DataCache.NotificationTypeActionsByNameCacheKey, notificationTypeId, name); var cacheItemArgs = new CacheItemArgs(notificationTypeActionCacheKey, DataCache.NotificationTypeActionsTimeOut, DataCache.NotificationTypeActionsPriority, notificationTypeId, name); - return CBO.GetCachedObject(cacheItemArgs, GetNotificationTypeActionByNameCallBack); + return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeActionByNameCallBack); } public virtual IList GetNotificationTypeActions(int notificationTypeId) { - return CBO.FillCollection(_dataService.GetNotificationTypeActions(notificationTypeId)); + return CBO.FillCollection(this._dataService.GetNotificationTypeActions(notificationTypeId)); + } + + public bool IsToastPending(int notificationId) + { + return this._dataService.IsToastPending(notificationId); } - #endregion - - #region Toast APIS - - public bool IsToastPending(int notificationId) - { - return _dataService.IsToastPending(notificationId); - } - - public void MarkReadyForToast(Notification notification, UserInfo userInfo) - { - MarkReadyForToast(notification, userInfo.UserID); - } + public void MarkReadyForToast(Notification notification, UserInfo userInfo) + { + this.MarkReadyForToast(notification, userInfo.UserID); + } public void MarkReadyForToast(Notification notification, int userId) { DataCache.RemoveCache(string.Format(ToastsCacheKey, userId)); - _dataService.MarkReadyForToast(notification.NotificationID, userId); + this._dataService.MarkReadyForToast(notification.NotificationID, userId); } - public void MarkToastSent(int notificationId, int userId) - { - _dataService.MarkToastSent(notificationId, userId); - } + public void MarkToastSent(int notificationId, int userId) + { + this._dataService.MarkToastSent(notificationId, userId); + } public IList GetToasts(UserInfo userInfo) { @@ -401,24 +396,20 @@ public IList GetToasts(UserInfo userInfo) if (toasts == null) { - toasts = CBO.FillCollection(_dataService.GetToasts(userInfo.UserID, userInfo.PortalID)); + toasts = CBO.FillCollection(this._dataService.GetToasts(userInfo.UserID, userInfo.PortalID)); foreach (var message in toasts) { - _dataService.MarkToastSent(message.NotificationID, userInfo.UserID); + this._dataService.MarkToastSent(message.NotificationID, userInfo.UserID); } - //Set the cache to empty toasts object because we don't want to make calls to database everytime for empty objects. - //This empty object cache would be cleared by MarkReadyForToast emthod when a new notification arrives for the user. + + // Set the cache to empty toasts object because we don't want to make calls to database everytime for empty objects. + // This empty object cache would be cleared by MarkReadyForToast emthod when a new notification arrives for the user. DataCache.SetCache(cacheKey, new List()); } return toasts; - } - - - #endregion - - #region Internal Methods - + } + internal virtual UserInfo GetAdminUser() { var current = PortalSettings.Current; @@ -434,7 +425,7 @@ internal virtual int GetCurrentUserId() internal virtual DateTime GetExpirationDate(int notificationTypeId) { - var notificationType = GetNotificationType(notificationTypeId); + var notificationType = this.GetNotificationType(notificationTypeId); return notificationType.TimeToLive.TotalMinutes > 0 ? DateTime.UtcNow.AddMinutes(notificationType.TimeToLive.TotalMinutes) @@ -444,26 +435,26 @@ internal virtual DateTime GetExpirationDate(int notificationTypeId) internal virtual object GetNotificationTypeActionCallBack(CacheItemArgs cacheItemArgs) { var notificationTypeActionId = (int)cacheItemArgs.ParamList[0]; - return CBO.FillObject(_dataService.GetNotificationTypeAction(notificationTypeActionId)); + return CBO.FillObject(this._dataService.GetNotificationTypeAction(notificationTypeActionId)); } internal virtual object GetNotificationTypeActionByNameCallBack(CacheItemArgs cacheItemArgs) { var notificationTypeId = (int)cacheItemArgs.ParamList[0]; var name = cacheItemArgs.ParamList[1].ToString(); - return CBO.FillObject(_dataService.GetNotificationTypeActionByName(notificationTypeId, name)); + return CBO.FillObject(this._dataService.GetNotificationTypeActionByName(notificationTypeId, name)); } internal virtual object GetNotificationTypeByNameCallBack(CacheItemArgs cacheItemArgs) { var notificationName = cacheItemArgs.ParamList[0].ToString(); - return CBO.FillObject(_dataService.GetNotificationTypeByName(notificationName)); + return CBO.FillObject(this._dataService.GetNotificationTypeByName(notificationName)); } internal virtual object GetNotificationTypeCallBack(CacheItemArgs cacheItemArgs) { var notificationTypeId = (int)cacheItemArgs.ParamList[0]; - return CBO.FillObject(_dataService.GetNotificationType(notificationTypeId)); + return CBO.FillObject(this._dataService.GetNotificationType(notificationTypeId)); } internal virtual string GetPortalSetting(string settingName, int portalId, string defaultValue) @@ -485,8 +476,6 @@ internal virtual void RemoveNotificationTypeActionCache() internal virtual void RemoveNotificationTypeCache() { DataCache.ClearCache("NotificationTypes:"); - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs b/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs index bba415dc017..48337777654 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs @@ -1,91 +1,89 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using DotNetNuke.Data; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions.Data { + using System; + using System.Data; + + using DotNetNuke.Data; + using DotNetNuke.Framework; + public class DataService : ServiceLocator, IDataService - { - #region Private Members - private readonly DataProvider provider; - #endregion - + { + private readonly DataProvider provider; + public DataService() { - provider = DataProvider.Instance(); - } - - protected override Func GetFactory() - { - return () => new DataService(); + this.provider = DataProvider.Instance(); } - - #region Subscription Types + public int AddSubscriptionType(string subscriptionName, string friendlyName, int desktopModuleId) { - return provider.ExecuteScalar("CoreMessaging_AddSubscriptionType", subscriptionName, friendlyName, desktopModuleId); + return this.provider.ExecuteScalar("CoreMessaging_AddSubscriptionType", subscriptionName, friendlyName, desktopModuleId); } public IDataReader GetSubscriptionTypes() { - return provider.ExecuteReader("CoreMessaging_GetSubscriptionTypes"); + return this.provider.ExecuteReader("CoreMessaging_GetSubscriptionTypes"); } - public bool DeleteSubscriptionType(int subscriptionTypeId) + protected override Func GetFactory() { - return provider.ExecuteScalar("CoreMessaging_DeleteSubscriptionType", subscriptionTypeId) == 0; - } - #endregion - + return () => new DataService(); + } - #region Subscriptions + public bool DeleteSubscriptionType(int subscriptionTypeId) + { + return this.provider.ExecuteScalar("CoreMessaging_DeleteSubscriptionType", subscriptionTypeId) == 0; + } + public int AddSubscription(int userId, int portalId, int subscriptionTypeId, string objectKey, string description, int moduleId, int tabId, string objectData) { - return provider.ExecuteScalar("CoreMessaging_AddSubscription", - userId, - provider.GetNull(portalId), - subscriptionTypeId, - objectKey, + return this.provider.ExecuteScalar( + "CoreMessaging_AddSubscription", + userId, + this.provider.GetNull(portalId), + subscriptionTypeId, + objectKey, description, - provider.GetNull(moduleId), - provider.GetNull(tabId), + this.provider.GetNull(moduleId), + this.provider.GetNull(tabId), objectData); } public IDataReader GetSubscriptionsByUser(int portalId, int userId, int subscriptionTypeId) { - return provider.ExecuteReader("CoreMessaging_GetSubscriptionsByUser", provider.GetNull(portalId), userId, provider.GetNull(subscriptionTypeId)); + return this.provider.ExecuteReader("CoreMessaging_GetSubscriptionsByUser", this.provider.GetNull(portalId), userId, this.provider.GetNull(subscriptionTypeId)); } public IDataReader GetSubscriptionsByContent(int portalId, int subscriptionTypeId, string objectKey) { - return provider.ExecuteReader("CoreMessaging_GetSubscriptionsByContent", provider.GetNull(portalId), subscriptionTypeId, objectKey); + return this.provider.ExecuteReader("CoreMessaging_GetSubscriptionsByContent", this.provider.GetNull(portalId), subscriptionTypeId, objectKey); } public IDataReader IsSubscribed(int portalId, int userId, int subscriptionTypeId, string objectKey, int moduleId, int tabId) { - return provider.ExecuteReader("CoreMessaging_IsSubscribed", - provider.GetNull(portalId), - userId, - subscriptionTypeId, - objectKey, - provider.GetNull(moduleId), - provider.GetNull(tabId)); + return this.provider.ExecuteReader( + "CoreMessaging_IsSubscribed", + this.provider.GetNull(portalId), + userId, + subscriptionTypeId, + objectKey, + this.provider.GetNull(moduleId), + this.provider.GetNull(tabId)); } public bool DeleteSubscription(int subscriptionId) { - return provider.ExecuteScalar("CoreMessaging_DeleteSubscription", subscriptionId) == 0; + return this.provider.ExecuteScalar("CoreMessaging_DeleteSubscription", subscriptionId) == 0; } public int UpdateSubscriptionDescription(string objectKey, int portalId, string newDescription) { - return provider.ExecuteScalar("CoreMessaging_UpdateSubscriptionDescription", + return this.provider.ExecuteScalar( + "CoreMessaging_UpdateSubscriptionDescription", objectKey, portalId, newDescription); @@ -93,9 +91,7 @@ public int UpdateSubscriptionDescription(string objectKey, int portalId, string public void DeleteSubscriptionsByObjectKey(int portalId, string objectKey) { - provider.ExecuteNonQuery("CoreMessaging_DeleteSubscriptionsByObjectKey", portalId, objectKey); - } - - #endregion + this.provider.ExecuteNonQuery("CoreMessaging_DeleteSubscriptionsByObjectKey", portalId, objectKey); + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/Data/IDataService.cs b/DNN Platform/Library/Services/Social/Subscriptions/Data/IDataService.cs index 6147a50eb7d..f2de98c31f5 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/Data/IDataService.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/Data/IDataService.cs @@ -1,100 +1,100 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions.Data { + using System.Data; + public interface IDataService { /// - /// Adds a Subscription Type + /// Adds a Subscription Type. /// - /// Subscription Type Name - /// Subscription Type FriendlyName - /// DesktopModule Id - /// Subscription Type Id + /// Subscription Type Name. + /// Subscription Type FriendlyName. + /// DesktopModule Id. + /// Subscription Type Id. int AddSubscriptionType(string subscriptionName, string friendlyName, int desktopModuleId); /// - /// Returns all the Subscription Types + /// Returns all the Subscription Types. /// - /// Subscription types + /// Subscription types. IDataReader GetSubscriptionTypes(); - + /// - /// Deletes a Subscription Type + /// Deletes a Subscription Type. /// - /// Subscription Type Id - /// True if the subscription type has been deleted, false otherwise + /// Subscription Type Id. + /// True if the subscription type has been deleted, false otherwise. bool DeleteSubscriptionType(int subscriptionTypeId); - + /// - /// Adds a Subscription + /// Adds a Subscription. /// - /// User Id - /// Portal id - /// Subscription Type Id - /// Object Key - /// Description - /// Module Id - /// Tab Id - /// Object Data - /// Suscription Id + /// User Id. + /// Portal id. + /// Subscription Type Id. + /// Object Key. + /// Description. + /// Module Id. + /// Tab Id. + /// Object Data. + /// Suscription Id. int AddSubscription(int userId, int portalId, int subscriptionTypeId, string objectKey, string description, int moduleId, int tabId, string objectData); /// - /// Returns the User Subscriptions + /// Returns the User Subscriptions. /// - /// Portal Id - /// User Id - /// Subscription Type Id - /// Collection of Subscriptions + /// Portal Id. + /// User Id. + /// Subscription Type Id. + /// Collection of Subscriptions. IDataReader GetSubscriptionsByUser(int portalId, int userId, int subscriptionTypeId); /// - /// Returns the Content Subscriptions + /// Returns the Content Subscriptions. /// - /// Portal Id - /// Subscription Type Id - /// Object Key - /// Collection of Subscriptions + /// Portal Id. + /// Subscription Type Id. + /// Object Key. + /// Collection of Subscriptions. IDataReader GetSubscriptionsByContent(int portalId, int subscriptionTypeId, string objectKey); - + /// - /// Checks if the user is subscribed to an ObjectKey + /// Checks if the user is subscribed to an ObjectKey. /// - /// Portal Id - /// User Id - /// Subscription Type - /// Object Key - /// Module Id - /// Tab Id - /// Subscription + /// Portal Id. + /// User Id. + /// Subscription Type. + /// Object Key. + /// Module Id. + /// Tab Id. + /// Subscription. IDataReader IsSubscribed(int portalId, int userId, int subscriptionTypeId, string objectKey, int moduleId, int tabId); - + /// - /// Deletes a Subscription + /// Deletes a Subscription. /// - /// Subscription Id - /// True if the subscription has been deleted, false otherwise + /// Subscription Id. + /// True if the subscription has been deleted, false otherwise. bool DeleteSubscription(int subscriptionId); /// - /// Updates a Subscription Description + /// Updates a Subscription Description. /// - /// Subscription Object Key - /// Subscription Portal Id - /// New Subscription Description - /// The number of subscription descriptions that have been updated + /// Subscription Object Key. + /// Subscription Portal Id. + /// New Subscription Description. + /// The number of subscription descriptions that have been updated. int UpdateSubscriptionDescription(string objectKey, int portalId, string newDescription); /// - /// Deletes all subscriptions matching the specified object key + /// Deletes all subscriptions matching the specified object key. /// - /// Portal Id - /// Object Key + /// Portal Id. + /// Object Key. void DeleteSubscriptionsByObjectKey(int portalId, string objectKey); } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/Entities/Subscription.cs b/DNN Platform/Library/Services/Social/Subscriptions/Entities/Subscription.cs index e8727d177b4..696eda28b56 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/Entities/Subscription.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/Entities/Subscription.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions.Entities { + using System; + /// /// This class represents a Subscription instance. /// @@ -13,57 +13,57 @@ namespace DotNetNuke.Services.Social.Subscriptions.Entities public class Subscription { /// - /// The subscription identifier. + /// Gets or sets the subscription identifier. /// public int SubscriptionId { get; set; } /// - /// The user the subscription is associated with. + /// Gets or sets the user the subscription is associated with. /// public int UserId { get; set; } /// - /// The site the subscription is associated with. + /// Gets or sets the site the subscription is associated with. /// public int PortalId { get; set; } /// - /// The type of subscription. + /// Gets or sets the type of subscription. /// public int SubscriptionTypeId { get; set; } - + /// - /// Object key that represent the content which user is subscribed to. + /// Gets or sets object key that represent the content which user is subscribed to. /// The format of the ObjectKey is up to the consumer. (i.e.: blog:12, where 12 represents the post identifier). /// public string ObjectKey { get; set; } /// - /// Object Data that represents metadata to manage the subscription. + /// Gets or sets object Data that represents metadata to manage the subscription. /// The format of the ObjectData is up to the consumer. (i.e.: destinationModule:486, where 486 represents a extra property called Destination Module). /// public string ObjectData { get; set; } /// - /// Description of the content which user is subscribed to. + /// Gets or sets description of the content which user is subscribed to. /// public string Description { get; set; } /// - /// The date the user subscribed. + /// Gets or sets the date the user subscribed. /// public DateTime CreatedOnDate { get; set; } - + /// - /// Associates the subscription with an instance of a module. - /// If set it uses to apply to Security Trimming. + /// Gets or sets associates the subscription with an instance of a module. + /// If set it uses to apply to Security Trimming. /// If the user does not have view permission on that module the Subscription won't be retrieved by the SubscriptionController. /// public int ModuleId { get; set; } /// - /// Associates the subscription with a tab. - /// If set it uses to apply to Security Trimming. + /// Gets or sets associates the subscription with a tab. + /// If set it uses to apply to Security Trimming. /// If the user does not have view permission on that tab the Subscription won't be retrieved by the SubscriptionController. /// public int TabId { get; set; } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/Entities/SubscriptionType.cs b/DNN Platform/Library/Services/Social/Subscriptions/Entities/SubscriptionType.cs index aab12ed58f6..c492c3909cf 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/Entities/SubscriptionType.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/Entities/SubscriptionType.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions.Entities { + using System; + /// /// This class represents a Subscription Type. /// @@ -13,22 +13,22 @@ namespace DotNetNuke.Services.Social.Subscriptions.Entities public class SubscriptionType { /// - /// The Subscription Type identifier. + /// Gets or sets the Subscription Type identifier. /// public int SubscriptionTypeId { get; set; } /// - /// The Subscription Name. + /// Gets or sets the Subscription Name. /// public string SubscriptionName { get; set; } /// - /// The Subscription Friendly Name. + /// Gets or sets the Subscription Friendly Name. /// public string FriendlyName { get; set; } /// - /// The Desktop Module Id associated with the subscription type. + /// Gets or sets the Desktop Module Id associated with the subscription type. /// This is an optional field but it should be set if the Subscription Type belongs to a specific module. /// public int DesktopModuleId { get; set; } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs index 514f4383c62..ac3e51ee774 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs @@ -1,69 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions { + using System.Collections.Generic; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Social.Subscriptions.Entities; + /// - /// This controller is responsible to manage the user subscriptions + /// This controller is responsible to manage the user subscriptions. /// public interface ISubscriptionController { /// /// Returns the User Subscriptions. /// - /// User Info - /// Portal Id - /// Subscription Type Id - /// Collection of subscriptions + /// User Info. + /// Portal Id. + /// Subscription Type Id. + /// Collection of subscriptions. IEnumerable GetUserSubscriptions(UserInfo user, int portalId, int subscriptionTypeId = -1); - + /// /// Returns the Content Subscriptions. /// - /// Portal Id - /// Subscription Type Id - /// Object Key - /// Collection of subscriptions + /// Portal Id. + /// Subscription Type Id. + /// Object Key. + /// Collection of subscriptions. IEnumerable GetContentSubscriptions(int portalId, int subscriptionTypeId, string objectKey); /// /// Returns true if a user is subscribed to a Content. /// - /// Subscription - /// True if the user is subscribed to the content, false otherwise + /// Subscription. + /// True if the user is subscribed to the content, false otherwise. bool IsSubscribed(Subscription subscription); - + /// /// Adds a new Subscription. /// If the operation succeed the SubscriptionId property of the Subscription entity will be filled up. /// - /// Subscription + /// Subscription. void AddSubscription(Subscription subscription); /// /// Deletes a Subscription. /// - /// Subscription + /// Subscription. void DeleteSubscription(Subscription subscription); /// /// Updates a Subscription Description. /// - /// Subscription Object Key - /// Portal Id - /// New Subscription Description + /// Subscription Object Key. + /// Portal Id. + /// New Subscription Description. + /// int UpdateSubscriptionDescription(string objectKey, int portalId, string newDescription); /// - /// Deletes all subscriptions matching the specified object key + /// Deletes all subscriptions matching the specified object key. /// - /// Portal Id - /// Object Key + /// Portal Id. + /// Object Key. void DeleteSubscriptionsByObjectKey(int portalId, string objectKey); } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionSecurityController.cs b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionSecurityController.cs index 80be8000e57..b91f5c69fbf 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionSecurityController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionSecurityController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions { + using DotNetNuke.Services.Social.Subscriptions.Entities; + /// /// This controller provides permission info about the User Subscription. /// @@ -14,8 +14,8 @@ public interface ISubscriptionSecurityController /// /// Check if the User has permission on the Subscription based on the Subscription ModuleId and TabId. /// - /// Subscription - /// True if user has permission, false otherwise + /// Subscription. + /// True if user has permission, false otherwise. bool HasPermission(Subscription subscription); } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionTypeController.cs b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionTypeController.cs index 1e345e513ed..098259b0aa6 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionTypeController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionTypeController.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Social.Subscriptions.Entities; + /// /// This controller is responsible to manage the subscription types. /// @@ -17,33 +18,33 @@ public interface ISubscriptionTypeController /// Creates a new Subscription Type. /// If the operation succeed the SubscriptionTypeId property of the Subscription entity will be filled up. /// - /// Subscription Type + /// Subscription Type. void AddSubscriptionType(SubscriptionType subscriptionType); /// /// Retrieves a Single Subscription Type that match the where predicate. /// - /// Where Predicate - /// Subscription Type + /// Where Predicate. + /// Subscription Type. SubscriptionType GetSubscriptionType(Func predicate); /// /// Retrieves all the Subscription Type. /// - /// Subscription Types collection + /// Subscription Types collection. IEnumerable GetSubscriptionTypes(); /// /// Retrieves a set of Subscription Types specifying a where predicate. /// - /// Where predicate - /// Subscription Type collection + /// Where predicate. + /// Subscription Type collection. IEnumerable GetSubscriptionTypes(Func predicate); - + /// /// Deletes a Subscription Type from the system. /// - /// Subscription Type + /// Subscription Type. void DeleteSubscriptionType(SubscriptionType subscriptionType); } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs index 0d10fefe3ec..d78797d957b 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Social.Subscriptions.Data; -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Social.Subscriptions.Data; + using DotNetNuke.Services.Social.Subscriptions.Entities; + /// /// This controller is responsible to manage the user subscriptions. /// @@ -24,39 +25,38 @@ public class SubscriptionController : ServiceLocator GetFactory() - { - return () => new SubscriptionController(); + this.dataService = DataService.Instance; + this.subscriptionSecurityController = SubscriptionSecurityController.Instance; } - - #region Implemented Methods + public IEnumerable GetUserSubscriptions(UserInfo user, int portalId, int subscriptionTypeId = -1) { - var subscriptions = CBO.FillCollection(dataService.GetSubscriptionsByUser( + var subscriptions = CBO.FillCollection(this.dataService.GetSubscriptionsByUser( portalId, user.UserID, subscriptionTypeId)); - return subscriptions.Where(s => subscriptionSecurityController.HasPermission(s)); + return subscriptions.Where(s => this.subscriptionSecurityController.HasPermission(s)); } public IEnumerable GetContentSubscriptions(int portalId, int subscriptionTypeId, string objectKey) { - var subscriptions = CBO.FillCollection(dataService.GetSubscriptionsByContent( + var subscriptions = CBO.FillCollection(this.dataService.GetSubscriptionsByContent( portalId, subscriptionTypeId, objectKey)); - return subscriptions.Where(s => subscriptionSecurityController.HasPermission(s)); + return subscriptions.Where(s => this.subscriptionSecurityController.HasPermission(s)); } + protected override Func GetFactory() + { + return () => new SubscriptionController(); + } + public bool IsSubscribed(Subscription subscription) { - var fetchedSubscription = CBO.FillObject(dataService.IsSubscribed( + var fetchedSubscription = CBO.FillObject(this.dataService.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, @@ -64,7 +64,7 @@ public bool IsSubscribed(Subscription subscription) subscription.ModuleId, subscription.TabId)); - return fetchedSubscription != null && subscriptionSecurityController.HasPermission(fetchedSubscription); + return fetchedSubscription != null && this.subscriptionSecurityController.HasPermission(fetchedSubscription); } public void AddSubscription(Subscription subscription) @@ -74,21 +74,22 @@ public void AddSubscription(Subscription subscription) Requires.NotNegative("subscription.SubscriptionTypeId", subscription.SubscriptionTypeId); Requires.PropertyNotNull("subscription.ObjectKey", subscription.ObjectKey); - subscription.SubscriptionId = dataService.AddSubscription(subscription.UserId, - subscription.PortalId, - subscription.SubscriptionTypeId, - subscription.ObjectKey, - subscription.Description, - subscription.ModuleId, - subscription.TabId, - subscription.ObjectData); + subscription.SubscriptionId = this.dataService.AddSubscription( + subscription.UserId, + subscription.PortalId, + subscription.SubscriptionTypeId, + subscription.ObjectKey, + subscription.Description, + subscription.ModuleId, + subscription.TabId, + subscription.ObjectData); } public void DeleteSubscription(Subscription subscription) { Requires.NotNull("subscription", subscription); - var subscriptionToDelete = CBO.FillObject(dataService.IsSubscribed( + var subscriptionToDelete = CBO.FillObject(this.dataService.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, @@ -96,9 +97,12 @@ public void DeleteSubscription(Subscription subscription) subscription.ModuleId, subscription.TabId)); - if (subscriptionToDelete == null) return; - - dataService.DeleteSubscription(subscriptionToDelete.SubscriptionId); + if (subscriptionToDelete == null) + { + return; + } + + this.dataService.DeleteSubscription(subscriptionToDelete.SubscriptionId); } public int UpdateSubscriptionDescription(string objectKey, int portalId, string newDescription) @@ -106,14 +110,12 @@ public int UpdateSubscriptionDescription(string objectKey, int portalId, string Requires.PropertyNotNull("objectKey", objectKey); Requires.NotNull("portalId", portalId); Requires.PropertyNotNull("newDescription", newDescription); - return dataService.UpdateSubscriptionDescription(objectKey, portalId, newDescription); + return this.dataService.UpdateSubscriptionDescription(objectKey, portalId, newDescription); } public void DeleteSubscriptionsByObjectKey(int portalId, string objectKey) { - dataService.DeleteSubscriptionsByObjectKey(portalId, objectKey); - } - - #endregion + this.dataService.DeleteSubscriptionsByObjectKey(portalId, objectKey); + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs index 0b01adb3d2f..12ccfa470ad 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Services.Social.Subscriptions.Entities; + /// /// This controller provides permission info about the User Subscription. /// public class SubscriptionSecurityController : ServiceLocator, ISubscriptionSecurityController { - protected override Func GetFactory() - { - return () => new SubscriptionSecurityController(); - } - public bool HasPermission(Subscription subscription) { var userInfo = GetUserFromSubscription(subscription); @@ -42,9 +37,13 @@ public bool HasPermission(Subscription subscription) } return true; + } + + protected override Func GetFactory() + { + return () => new SubscriptionSecurityController(); } - - #region Private Static Methods + private static bool HasUserModuleViewPermission(UserInfo userInfo, ModuleInfo moduleInfo) { var portalSettings = new PortalSettings(moduleInfo.PortalID); @@ -70,7 +69,6 @@ private static ModuleInfo GetModuleFromSubscription(Subscription subscription) private static UserInfo GetUserFromSubscription(Subscription subscription) { return UserController.Instance.GetUser(subscription.PortalId, subscription.UserId); - } - #endregion + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs index 00b23d716da..f17a76f7c3e 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Services.Social.Subscriptions.Data; -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Social.Subscriptions { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Services.Social.Subscriptions.Data; + using DotNetNuke.Services.Social.Subscriptions.Entities; + /// /// This controller is responsible to manage the subscription types. /// @@ -22,20 +23,14 @@ public class SubscriptionTypeController : ServiceLocator GetFactory() - { - return () => new SubscriptionTypeController(); - } - - #region Implemented Methods + public void AddSubscriptionType(SubscriptionType subscriptionType) { Requires.NotNull("subscriptionType", subscriptionType); - subscriptionType.SubscriptionTypeId = dataService.AddSubscriptionType( + subscriptionType.SubscriptionTypeId = this.dataService.AddSubscriptionType( subscriptionType.SubscriptionName, subscriptionType.FriendlyName, subscriptionType.DesktopModuleId); @@ -47,24 +42,31 @@ public SubscriptionType GetSubscriptionType(Func predica { Requires.NotNull("predicate", predicate); - return GetSubscriptionTypes().SingleOrDefault(predicate); + return this.GetSubscriptionTypes().SingleOrDefault(predicate); } + protected override Func GetFactory() + { + return () => new SubscriptionTypeController(); + } + public IEnumerable GetSubscriptionTypes() { - var cacheArgs = new CacheItemArgs(DataCache.SubscriptionTypesCacheKey, - DataCache.SubscriptionTypesTimeOut, - DataCache.SubscriptionTypesCachePriority); + var cacheArgs = new CacheItemArgs( + DataCache.SubscriptionTypesCacheKey, + DataCache.SubscriptionTypesTimeOut, + DataCache.SubscriptionTypesCachePriority); - return CBO.GetCachedObject>(cacheArgs, - c => CBO.FillCollection(dataService.GetSubscriptionTypes())); + return CBO.GetCachedObject>( + cacheArgs, + c => CBO.FillCollection(this.dataService.GetSubscriptionTypes())); } public IEnumerable GetSubscriptionTypes(Func predicate) { Requires.NotNull("predicate", predicate); - return GetSubscriptionTypes().Where(predicate); + return this.GetSubscriptionTypes().Where(predicate); } public void DeleteSubscriptionType(SubscriptionType subscriptionType) @@ -72,11 +74,10 @@ public void DeleteSubscriptionType(SubscriptionType subscriptionType) Requires.NotNull("subscriptionType", subscriptionType); Requires.NotNegative("subscriptionType.SubscriptionTypeId", subscriptionType.SubscriptionTypeId); - dataService.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId); + this.dataService.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId); CleanCache(); - } - #endregion - + } + private static void CleanCache() { DataCache.RemoveCache(DataCache.SubscriptionTypesCacheKey); diff --git a/DNN Platform/Library/Services/Syndication/RssHandler.cs b/DNN Platform/Library/Services/Syndication/RssHandler.cs index 76a5aa2f864..620acece9dd 100644 --- a/DNN Platform/Library/Services/Syndication/RssHandler.cs +++ b/DNN Platform/Library/Services/Syndication/RssHandler.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Search.Controllers; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + public class RssHandler : SyndicationHandlerBase { /// - /// This method + /// This method. /// /// /// @@ -32,29 +27,31 @@ public class RssHandler : SyndicationHandlerBase protected override void PopulateChannel(string channelName, string userName) { ModuleInfo objModule; - if (Request == null || Settings == null || Settings.ActiveTab == null || ModuleId == Null.NullInteger) + if (this.Request == null || this.Settings == null || this.Settings.ActiveTab == null || this.ModuleId == Null.NullInteger) { return; } - Channel["title"] = Settings.PortalName; - Channel["link"] = Globals.AddHTTP(Globals.GetDomainName(Request)); - if (!String.IsNullOrEmpty(Settings.Description)) + + this.Channel["title"] = this.Settings.PortalName; + this.Channel["link"] = Globals.AddHTTP(Globals.GetDomainName(this.Request)); + if (!string.IsNullOrEmpty(this.Settings.Description)) { - Channel["description"] = Settings.Description; + this.Channel["description"] = this.Settings.Description; } else { - Channel["description"] = Settings.PortalName; + this.Channel["description"] = this.Settings.PortalName; } - Channel["language"] = Settings.DefaultLanguage; - Channel["copyright"] = !string.IsNullOrEmpty(Settings.FooterText) ? Settings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()) : string.Empty; - Channel["webMaster"] = Settings.Email; - + + this.Channel["language"] = this.Settings.DefaultLanguage; + this.Channel["copyright"] = !string.IsNullOrEmpty(this.Settings.FooterText) ? this.Settings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()) : string.Empty; + this.Channel["webMaster"] = this.Settings.Email; + IList searchResults = null; var query = new SearchQuery(); - query.PortalIds = new[] { Settings.PortalId }; - query.TabId = TabId; - query.ModuleId = ModuleId; + query.PortalIds = new[] { this.Settings.PortalId }; + query.TabId = this.TabId; + query.ModuleId = this.ModuleId; query.SearchTypeIds = new[] { SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId }; try @@ -65,13 +62,14 @@ protected override void PopulateChannel(string channelName, string userName) { Exceptions.Exceptions.LogException(ex); } + if (searchResults != null) { foreach (var result in searchResults) { if (!result.UniqueKey.StartsWith(Constants.ModuleMetaDataPrefixTag) && TabPermissionController.CanViewPage()) { - if (Settings.ActiveTab.StartDate < DateTime.Now && Settings.ActiveTab.EndDate > DateTime.Now) + if (this.Settings.ActiveTab.StartDate < DateTime.Now && this.Settings.ActiveTab.EndDate > DateTime.Now) { objModule = ModuleController.Instance.GetModule(result.ModuleId, query.TabId, false); if (objModule != null && objModule.DisplaySyndicate && objModule.IsDeleted == false) @@ -81,7 +79,7 @@ protected override void PopulateChannel(string channelName, string userName) if (Convert.ToDateTime(objModule.StartDate == Null.NullDate ? DateTime.MinValue : objModule.StartDate) < DateTime.Now && Convert.ToDateTime(objModule.EndDate == Null.NullDate ? DateTime.MaxValue : objModule.EndDate) > DateTime.Now) { - Channel.Items.Add(GetRssItem(result)); + this.Channel.Items.Add(this.GetRssItem(result)); } } } @@ -92,7 +90,22 @@ protected override void PopulateChannel(string channelName, string userName) } /// - /// Creates an RSS Item + /// The PreRender event is used to set the Caching Policy for the Feed. This mimics the behavior from the + /// OutputCache directive in the old Rss.aspx file. @OutputCache Duration="60" VaryByParam="moduleid". + /// + /// Event Args. + /// + protected override void OnPreRender(EventArgs ea) + { + base.OnPreRender(ea); + + this.Context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); + this.Context.Response.Cache.SetCacheability(HttpCacheability.Public); + this.Context.Response.Cache.VaryByParams["moduleid"] = true; + } + + /// + /// Creates an RSS Item. /// /// /// @@ -101,7 +114,7 @@ private GenericRssElement GetRssItem(SearchResult searchResult) { var item = new GenericRssElement(); var url = searchResult.Url; - if (url.Trim() == "") + if (url.Trim() == string.Empty) { url = TestableGlobals.Instance.NavigateURL(searchResult.TabId); if (url.IndexOf(HttpContext.Current.Request.Url.Host, StringComparison.InvariantCultureIgnoreCase) == -1) @@ -111,27 +124,12 @@ private GenericRssElement GetRssItem(SearchResult searchResult) } item["title"] = searchResult.Title; - item["description"] = searchResult.Description; + item["description"] = searchResult.Description; item["pubDate"] = searchResult.ModifiedTimeUtc.ToUniversalTime().ToString("r"); item["link"] = url; item["guid"] = url; return item; } - - /// - /// The PreRender event is used to set the Caching Policy for the Feed. This mimics the behavior from the - /// OutputCache directive in the old Rss.aspx file. @OutputCache Duration="60" VaryByParam="moduleid" - /// - /// Event Args. - /// - protected override void OnPreRender(EventArgs ea) - { - base.OnPreRender(ea); - - Context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); - Context.Response.Cache.SetCacheability(HttpCacheability.Public); - Context.Response.Cache.VaryByParams["moduleid"] = true; - } } } diff --git a/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs b/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs index b8064a7b0e5..0dfc2f5c966 100644 --- a/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs +++ b/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + public class SyndicationHandlerBase : GenericRssHttpHandlerBase { private int _moduleId = Null.NullInteger; @@ -33,14 +28,15 @@ public int TabId { get { - if (_tabId == Null.NullInteger && Request.QueryString["tabid"] != null) + if (this._tabId == Null.NullInteger && this.Request.QueryString["tabid"] != null) { - if (! Int32.TryParse(Request.QueryString["tabid"], out _tabId)) + if (!int.TryParse(this.Request.QueryString["tabid"], out this._tabId)) { - _tabId = Null.NullInteger; + this._tabId = Null.NullInteger; } } - return _tabId; + + return this._tabId; } } @@ -48,14 +44,15 @@ public int ModuleId { get { - if (_moduleId == Null.NullInteger && Request.QueryString["moduleid"] != null) + if (this._moduleId == Null.NullInteger && this.Request.QueryString["moduleid"] != null) { - if (! Int32.TryParse(Request.QueryString["moduleid"], out _moduleId)) + if (!int.TryParse(this.Request.QueryString["moduleid"], out this._moduleId)) { - _moduleId = Null.NullInteger; + this._moduleId = Null.NullInteger; } } - return _moduleId; + + return this._moduleId; } } diff --git a/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs b/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs index 565fe1c81b5..0c7e0399494 100644 --- a/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs +++ b/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs @@ -1,44 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Web; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.SystemDateTime { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + /// /// The SystemDateTime provides static method to obtain System's Time. /// /// /// DateTime information is collected from Database. The methods are created to find one unified timestamp from database - /// as opposed to depending on web server's timestamp. This method becomes more relevant in a web farm configuration + /// as opposed to depending on web server's timestamp. This method becomes more relevant in a web farm configuration. /// public class SystemDateTime { @@ -52,15 +47,14 @@ public static DateTime GetCurrentTimeUtc() /// ----------------------------------------------------------------------------- /// - /// GetCurrentTime get current time from database + /// GetCurrentTime get current time from database. /// - /// DateTime + /// DateTime. /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in DNN 9.1.0. Replaced by DateUtils.GetDatabaseLocalTime, which includes caching. Scheduled removal in v11.0.0.")] public static DateTime GetCurrentTime() { return Provider.GetDatabaseTime(); } - } } diff --git a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs index 1d112212f20..ada00e37b88 100644 --- a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs @@ -1,17 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Tokens { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + + using DotNetNuke.Entities.Users; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// - /// BaseCustomTokenReplace allows to add multiple sources implementing IPropertyAccess + /// BaseCustomTokenReplace allows to add multiple sources implementing IPropertyAccess. /// /// public abstract class BaseCustomTokenReplace : BaseTokenReplace @@ -19,95 +22,56 @@ public abstract class BaseCustomTokenReplace : BaseTokenReplace protected Dictionary PropertySource = new Dictionary(); /// - /// Gets/sets the user object representing the currently accessing user (permission) + /// Gets or sets /sets the user object representing the currently accessing user (permission). /// - /// UserInfo oject + /// UserInfo oject. public UserInfo AccessingUser { get; set; } /// - /// Gets/sets the current Access Level controlling access to critical user settings - /// - /// A TokenAccessLevel as defined above - protected Scope CurrentAccessLevel { get; set; } - - /// - /// If DebugMessages are enabled, unknown Tokens are replaced with Error Messages + /// Gets or sets a value indicating whether if DebugMessages are enabled, unknown Tokens are replaced with Error Messages. /// - /// + /// + /// If DebugMessages are enabled, unknown Tokens are replaced with Error Messages + /// /// /// public bool DebugMessages { get; set; } - protected override string replacedTokenValue(string objectName, string propertyName, string format) - { - string result = string.Empty; - bool propertyNotFound = false; - if (PropertySource.ContainsKey(objectName.ToLowerInvariant())) - { - result = PropertySource[objectName.ToLowerInvariant()].GetProperty(propertyName, format, FormatProvider, AccessingUser, CurrentAccessLevel, ref propertyNotFound); - } - else - { - if (DebugMessages) - { - string message = Localization.Localization.GetString("TokenReplaceUnknownObject", Localization.Localization.SharedResourceFile, FormatProvider.ToString()); - if (message == string.Empty) - { - message = "Error accessing [{0}:{1}], {0} is an unknown datasource"; - } - result = string.Format(message, objectName, propertyName); - } - } - if (DebugMessages && propertyNotFound) - { - string message; - if (result == PropertyAccess.ContentLocked) - { - message = Localization.Localization.GetString("TokenReplaceRestrictedProperty", Localization.Localization.GlobalResourceFile, FormatProvider.ToString()); - } - else - { - message = Localization.Localization.GetString("TokenReplaceUnknownProperty", Localization.Localization.GlobalResourceFile, FormatProvider.ToString()); - } - if (message == string.Empty) - { - message = "Error accessing [{0}:{1}], {1} is unknown for datasource {0}"; - } - result = string.Format(message, objectName, propertyName); - } - - return result; - } + /// + /// Gets or sets /sets the current Access Level controlling access to critical user settings. + /// + /// A TokenAccessLevel as defined above. + protected Scope CurrentAccessLevel { get; set; } /// - /// returns cacheability of the passed text regarding all contained tokens + /// returns cacheability of the passed text regarding all contained tokens. /// - /// the text to parse for tokens to replace - /// cacheability level (not - safe - fully) - /// always check cacheability before caching a module! + /// the text to parse for tokens to replace. + /// cacheability level (not - safe - fully). + /// always check cacheability before caching a module!. public CacheLevel Cacheability(string sourceText) { CacheLevel isSafe = CacheLevel.fullyCacheable; if (sourceText != null && !string.IsNullOrEmpty(sourceText)) { - //initialize PropertyAccess classes - string DummyResult = ReplaceTokens(sourceText); + // initialize PropertyAccess classes + string DummyResult = this.ReplaceTokens(sourceText); - foreach (Match currentMatch in TokenizerRegex.Matches(sourceText)) + foreach (Match currentMatch in this.TokenizerRegex.Matches(sourceText)) { string strObjectName = currentMatch.Result("${object}"); - if (!String.IsNullOrEmpty(strObjectName)) + if (!string.IsNullOrEmpty(strObjectName)) { if (strObjectName == "[") { - //nothing + // nothing } - else if (!PropertySource.ContainsKey(strObjectName.ToLowerInvariant())) + else if (!this.PropertySource.ContainsKey(strObjectName.ToLowerInvariant())) { } else { - CacheLevel c = PropertySource[strObjectName.ToLowerInvariant()].Cacheability; + CacheLevel c = this.PropertySource[strObjectName.ToLowerInvariant()].Cacheability; if (c < isSafe) { isSafe = c; @@ -116,21 +80,68 @@ public CacheLevel Cacheability(string sourceText) } } } + return isSafe; } /// - /// Checks for present [Object:Property] tokens + /// Checks for present [Object:Property] tokens. /// - /// String with [Object:Property] tokens + /// String with [Object:Property] tokens. /// public bool ContainsTokens(string strSourceText) { if (!string.IsNullOrEmpty(strSourceText)) { - return TokenizerRegex.Matches(strSourceText).Cast().Any(currentMatch => currentMatch.Result("${object}").Length > 0); + return this.TokenizerRegex.Matches(strSourceText).Cast().Any(currentMatch => currentMatch.Result("${object}").Length > 0); } + return false; } + + protected override string replacedTokenValue(string objectName, string propertyName, string format) + { + string result = string.Empty; + bool propertyNotFound = false; + if (this.PropertySource.ContainsKey(objectName.ToLowerInvariant())) + { + result = this.PropertySource[objectName.ToLowerInvariant()].GetProperty(propertyName, format, this.FormatProvider, this.AccessingUser, this.CurrentAccessLevel, ref propertyNotFound); + } + else + { + if (this.DebugMessages) + { + string message = Localization.GetString("TokenReplaceUnknownObject", Localization.SharedResourceFile, this.FormatProvider.ToString()); + if (message == string.Empty) + { + message = "Error accessing [{0}:{1}], {0} is an unknown datasource"; + } + + result = string.Format(message, objectName, propertyName); + } + } + + if (this.DebugMessages && propertyNotFound) + { + string message; + if (result == PropertyAccess.ContentLocked) + { + message = Localization.GetString("TokenReplaceRestrictedProperty", Localization.GlobalResourceFile, this.FormatProvider.ToString()); + } + else + { + message = Localization.GetString("TokenReplaceUnknownProperty", Localization.GlobalResourceFile, this.FormatProvider.ToString()); + } + + if (message == string.Empty) + { + message = "Error accessing [{0}:{1}], {1} is unknown for datasource {0}"; + } + + result = string.Format(message, objectName, propertyName); + } + + return result; + } } } diff --git a/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs b/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs index 31fb3d4bf42..b811555bcb1 100644 --- a/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs @@ -1,25 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; - -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Tokens { + using System; + using System.Globalization; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + + using DotNetNuke.Common.Utilities; + /// - /// The BaseTokenReplace class provides the tokenization of tokens formatted + /// The BaseTokenReplace class provides the tokenization of tokens formatted /// [object:property] or [object:property|format|ifEmpty] or [custom:no] within a string /// with the appropriate current property/custom values. /// /// public abstract class BaseTokenReplace { + protected const string ObjectLessToken = "no_object"; + private const string ExpressionDefault = "(?:(?\\[\\])|\\[(?:(?[^{}\\]\\[:]+):(?[^\\]\\[\\|]+))(?:\\|(?:(?[^\\]\\[]+)\\|(?[^\\]\\[]+))|\\|(?:(?[^\\|\\]\\[]+)))?\\])|(?\\[[^\\]\\[]+\\])|(?[^\\]\\[]+)"; @@ -30,56 +32,55 @@ public abstract class BaseTokenReplace private const string TokenReplaceCacheKeyDefault = "TokenReplaceRegEx_Default"; private const string TokenReplaceCacheKeyObjectless = "TokenReplaceRegEx_Objectless"; - - + private CultureInfo _formatProvider; private string _language; - protected const string ObjectLessToken = "no_object"; - - protected bool UseObjectLessExpression { get; set; } - /// - /// Gets the Format provider as Culture info from stored language or current culture + /// Gets or sets /sets the language to be used, e.g. for date format. /// - /// An CultureInfo - protected CultureInfo FormatProvider - { - get { return _formatProvider ?? (_formatProvider = Thread.CurrentThread.CurrentUICulture); } - } - - /// - /// Gets/sets the language to be used, e.g. for date format - /// - /// A string, representing the locale + /// A string, representing the locale. public string Language { get { - return _language; + return this._language; } + set { - _language = value; - _formatProvider = new CultureInfo(_language); + this._language = value; + this._formatProvider = new CultureInfo(this._language); } } + protected bool UseObjectLessExpression { get; set; } + + /// + /// Gets the Format provider as Culture info from stored language or current culture. + /// + /// An CultureInfo. + protected CultureInfo FormatProvider + { + get { return this._formatProvider ?? (this._formatProvider = Thread.CurrentThread.CurrentUICulture); } + } + /// - /// Gets the Regular expression for the token to be replaced + /// Gets the Regular expression for the token to be replaced. /// - /// A regular Expression + /// A regular Expression. protected Regex TokenizerRegex { get { - var cacheKey = (UseObjectLessExpression) ? TokenReplaceCacheKeyObjectless : TokenReplaceCacheKeyDefault; + var cacheKey = this.UseObjectLessExpression ? TokenReplaceCacheKeyObjectless : TokenReplaceCacheKeyDefault; var tokenizer = DataCache.GetCache(cacheKey) as Regex; if (tokenizer == null) { - tokenizer = RegexUtils.GetCachedRegex(UseObjectLessExpression ? ExpressionObjectLess : ExpressionDefault); + tokenizer = RegexUtils.GetCachedRegex(this.UseObjectLessExpression ? ExpressionObjectLess : ExpressionDefault); DataCache.SetCache(cacheKey, tokenizer); } + return tokenizer; } } @@ -93,24 +94,27 @@ protected virtual string ReplaceTokens(string sourceText) { return string.Empty; } + var result = new StringBuilder(); - foreach (Match currentMatch in TokenizerRegex.Matches(sourceText)) + foreach (Match currentMatch in this.TokenizerRegex.Matches(sourceText)) { string objectName = currentMatch.Result("${object}"); - if (!String.IsNullOrEmpty(objectName)) + if (!string.IsNullOrEmpty(objectName)) { if (objectName == "[") { objectName = ObjectLessToken; } + string propertyName = currentMatch.Result("${property}"); string format = currentMatch.Result("${format}"); string ifEmptyReplacment = currentMatch.Result("${ifEmpty}"); - string conversion = replacedTokenValue(objectName, propertyName, format); - if (!String.IsNullOrEmpty(ifEmptyReplacment) && String.IsNullOrEmpty(conversion)) + string conversion = this.replacedTokenValue(objectName, propertyName, format); + if (!string.IsNullOrEmpty(ifEmptyReplacment) && string.IsNullOrEmpty(conversion)) { conversion = ifEmptyReplacment; } + result.Append(conversion); } else @@ -118,6 +122,7 @@ protected virtual string ReplaceTokens(string sourceText) result.Append(currentMatch.Result("${text}")); } } + return result.ToString(); } } diff --git a/DNN Platform/Library/Services/Tokens/CacheLevel.cs b/DNN Platform/Library/Services/Tokens/CacheLevel.cs index 8ccd7e0a461..a5c613ea573 100644 --- a/DNN Platform/Library/Services/Tokens/CacheLevel.cs +++ b/DNN Platform/Library/Services/Tokens/CacheLevel.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Tokens { /// - /// CacheLevel is used to specify the cachability of a string, determined as minimum of the used token cachability + /// CacheLevel is used to specify the cachability of a string, determined as minimum of the used token cachability. /// /// - /// CacheLevel is determined as minimum of the used tokens' cachability + /// CacheLevel is determined as minimum of the used tokens' cachability. /// public enum CacheLevel : byte { @@ -16,13 +16,15 @@ public enum CacheLevel : byte /// Caching of the text is not suitable and might expose security risks /// notCacheable = 0, + /// /// Caching of the text might result in inaccurate display (e.g. time), but does not expose a security risk /// secureforCaching = 5, + /// /// Caching of the text can be done without limitations or any risk /// - fullyCacheable = 10 + fullyCacheable = 10, } } diff --git a/DNN Platform/Library/Services/Tokens/HtmlTokenReplace.cs b/DNN Platform/Library/Services/Tokens/HtmlTokenReplace.cs index bef8bd5d3e0..521a6dc050b 100644 --- a/DNN Platform/Library/Services/Tokens/HtmlTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/HtmlTokenReplace.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Tokens { + using System.Web.UI; + public class HtmlTokenReplace : TokenReplace { public HtmlTokenReplace(Page page) : base(Scope.DefaultSettings) { - PropertySource["css"] = new CssPropertyAccess(page); - PropertySource["js"] = new JavaScriptPropertyAccess(page); - PropertySource["javascript"] = new JavaScriptPropertyAccess(page); - PropertySource["antiforgerytoken"] = new AntiForgeryTokenPropertyAccess(); + this.PropertySource["css"] = new CssPropertyAccess(page); + this.PropertySource["js"] = new JavaScriptPropertyAccess(page); + this.PropertySource["javascript"] = new JavaScriptPropertyAccess(page); + this.PropertySource["antiforgerytoken"] = new AntiForgeryTokenPropertyAccess(); } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/AntiForgeryTokenPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/AntiForgeryTokenPropertyAccess.cs index ca04733baf8..94024e8a968 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/AntiForgeryTokenPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/AntiForgeryTokenPropertyAccess.cs @@ -1,16 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable CheckNamespace - -using System; -using System.Globalization; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Tokens { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + public class AntiForgeryTokenPropertyAccess : IPropertyAccess { public CacheLevel Cacheability @@ -22,7 +21,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - return String.Empty; + return string.Empty; } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs index 92f514a813e..e97ebf69ee9 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs @@ -1,61 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Globalization; - -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System; + using System.Collections; + using System.Globalization; + + using DotNetNuke.Entities.Users; + public class ArrayListPropertyAccess : IPropertyAccess { private readonly ArrayList custom; public ArrayListPropertyAccess(ArrayList list) { - custom = list; - } - - #region IPropertyAccess Members + this.custom = list; + } + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { - if (custom == null) + if (this.custom == null) { return string.Empty; } + object valueObject = null; string OutputFormat = format; if (string.IsNullOrEmpty(format)) { OutputFormat = "g"; } + int intIndex = int.Parse(propertyName); - if ((custom != null) && custom.Count > intIndex) + if ((this.custom != null) && this.custom.Count > intIndex) { - valueObject = custom[intIndex].ToString(); + valueObject = this.custom[intIndex].ToString(); } - if ((valueObject != null)) + + if (valueObject != null) { switch (valueObject.GetType().Name) { case "String": - return PropertyAccess.FormatString((string) valueObject, format); + return PropertyAccess.FormatString((string)valueObject, format); case "Boolean": - return (PropertyAccess.Boolean2LocalizedYesNo((bool) valueObject, formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo((bool)valueObject, formatProvider); case "DateTime": case "Double": case "Single": case "Int32": case "Int64": - return (((IFormattable) valueObject).ToString(OutputFormat, formatProvider)); + return ((IFormattable)valueObject).ToString(OutputFormat, formatProvider); default: return PropertyAccess.FormatString(valueObject.ToString(), format); } @@ -66,15 +70,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs index bef0a2af61a..a3df44f539c 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable once CheckNamespace -using System; -using System.Web.UI; -using DotNetNuke.Entities.Users; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable once CheckNamespace namespace DotNetNuke.Services.Tokens { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Newtonsoft.Json; + public class StylesheetDto { [JsonProperty("path")] @@ -31,29 +31,31 @@ public class CssPropertyAccess : JsonPropertyAccess public CssPropertyAccess(Page page) { - _page = page; + this._page = page; } protected override string ProcessToken(StylesheetDto model, UserInfo accessingUser, Scope accessLevel) { - if (String.IsNullOrEmpty(model.Path)) + if (string.IsNullOrEmpty(model.Path)) { throw new ArgumentException("The Css token must specify a path or property."); } + if (model.Priority == 0) { model.Priority = (int)FileOrder.Css.DefaultPriority; } - if (String.IsNullOrEmpty(model.Provider)) + + if (string.IsNullOrEmpty(model.Provider)) { - ClientResourceManager.RegisterStyleSheet(_page, model.Path, model.Priority); + ClientResourceManager.RegisterStyleSheet(this._page, model.Path, model.Priority); } else { - ClientResourceManager.RegisterStyleSheet(_page, model.Path, model.Priority, model.Provider); + ClientResourceManager.RegisterStyleSheet(this._page, model.Path, model.Priority, model.Provider); } - return String.Empty; + return string.Empty; } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs index 461b9156f4f..3a53aa65809 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + public class CulturePropertyAccess : IPropertyAccess - { - #region IPropertyAccess Members - + { + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { CultureInfo ci = formatProvider; @@ -25,33 +26,40 @@ public string GetProperty(string propertyName, string format, CultureInfo format { return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.EnglishName), format); } + if (propertyName.Equals(CultureDropDownTypes.Lcid.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return ci.LCID.ToString(); } + if (propertyName.Equals(CultureDropDownTypes.Name.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.Name, format); } + if (propertyName.Equals(CultureDropDownTypes.NativeName.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.NativeName), format); } + if (propertyName.Equals(CultureDropDownTypes.TwoLetterIsoCode.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.TwoLetterISOLanguageName, format); } + if (propertyName.Equals(CultureDropDownTypes.ThreeLetterIsoCode.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.ThreeLetterISOLanguageName, format); } + if (propertyName.Equals(CultureDropDownTypes.DisplayName.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.DisplayName, format); } + if (propertyName.Equals("languagename", StringComparison.InvariantCultureIgnoreCase)) { - if(ci.IsNeutralCulture) + if (ci.IsNeutralCulture) { return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.EnglishName), format); } @@ -60,9 +68,10 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.Parent.EnglishName), format); } } + if (propertyName.Equals("languagenativename", StringComparison.InvariantCultureIgnoreCase)) { - if(ci.IsNeutralCulture) + if (ci.IsNeutralCulture) { return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.NativeName), format); } @@ -71,12 +80,13 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.Parent.NativeName), format); } } + if (propertyName.Equals("countryname", StringComparison.InvariantCultureIgnoreCase)) { - if(ci.IsNeutralCulture) + if (ci.IsNeutralCulture) { - //Neutral culture do not include region information - return ""; + // Neutral culture do not include region information + return string.Empty; } else { @@ -84,33 +94,23 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.EnglishName), format); } } + if (propertyName.Equals("countrynativename", StringComparison.InvariantCultureIgnoreCase)) { - if(ci.IsNeutralCulture) + if (ci.IsNeutralCulture) { - //Neutral culture do not include region information - return ""; + // Neutral culture do not include region information + return string.Empty; } else { RegionInfo country = new RegionInfo(new CultureInfo(ci.Name, false).LCID); return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.NativeName), format); } - - } + PropertyNotFound = true; return string.Empty; } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs index 1d3f1556e7b..93dbfb2d065 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs @@ -1,42 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Data; -using System.Globalization; - -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System; + using System.Data; + using System.Globalization; + + using DotNetNuke.Entities.Users; + public class DataRowPropertyAccess : IPropertyAccess { private readonly DataRow dr; public DataRowPropertyAccess(DataRow row) { - dr = row; - } - - #region IPropertyAccess Members + this.dr = row; + } + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { - if (dr == null) + if (this.dr == null) { return string.Empty; } - object valueObject = dr[propertyName]; + + object valueObject = this.dr[propertyName]; string OutputFormat = format; if (string.IsNullOrEmpty(format)) { OutputFormat = "g"; } + if (valueObject != null) { switch (valueObject.GetType().Name) @@ -44,13 +47,13 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "String": return PropertyAccess.FormatString(Convert.ToString(valueObject), format); case "Boolean": - return (PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject), formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject), formatProvider); case "DateTime": case "Double": case "Single": case "Int32": case "Int64": - return (((IFormattable) valueObject).ToString(OutputFormat, formatProvider)); + return ((IFormattable)valueObject).ToString(OutputFormat, formatProvider); default: return PropertyAccess.FormatString(valueObject.ToString(), format); } @@ -61,15 +64,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs index 2ee43f44c40..33c70ff51f3 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Users; + public class DateTimePropertyAccess : IPropertyAccess - { - #region IPropertyAccess Members - + { + public CacheLevel Cacheability + { + get + { + return CacheLevel.secureforCaching; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { TimeZoneInfo userTimeZone = AccessingUser.Profile.PreferredTimeZone; @@ -27,39 +28,33 @@ public string GetProperty(string propertyName, string format, CultureInfo format { format = "D"; } + return TimeZoneInfo.ConvertTime(DateTime.Now, userTimeZone).ToString(format, formatProvider); case "now": if (format == string.Empty) { format = "g"; } + return TimeZoneInfo.ConvertTime(DateTime.Now, userTimeZone).ToString(format, formatProvider); case "system": - if (format == String.Empty) + if (format == string.Empty) { format = "g"; } + return DateTime.Now.ToString(format, formatProvider); case "utc": - if (format == String.Empty) + if (format == string.Empty) { format = "g"; } + return DateTime.Now.ToUniversalTime().ToString(format, formatProvider); default: PropertyNotFound = true; return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.secureforCaching; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs index 683655d331a..aefa16d06a5 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs @@ -1,42 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Globalization; - -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System; + using System.Collections; + using System.Globalization; + + using DotNetNuke.Entities.Users; + public class DictionaryPropertyAccess : IPropertyAccess { private readonly IDictionary NameValueCollection; public DictionaryPropertyAccess(IDictionary list) { - NameValueCollection = list; - } - - #region IPropertyAccess Members + this.NameValueCollection = list; + } + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } + public virtual string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { - if (NameValueCollection == null) + if (this.NameValueCollection == null) { return string.Empty; } - object valueObject = NameValueCollection[propertyName]; + + object valueObject = this.NameValueCollection[propertyName]; string OutputFormat = format; if (string.IsNullOrEmpty(format)) { OutputFormat = "g"; } + if (valueObject != null) { switch (valueObject.GetType().Name) @@ -44,13 +47,13 @@ public virtual string GetProperty(string propertyName, string format, CultureInf case "String": return PropertyAccess.FormatString(Convert.ToString(valueObject), format); case "Boolean": - return (PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject), formatProvider)); + return PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject), formatProvider); case "DateTime": case "Double": case "Single": case "Int32": case "Int64": - return (((IFormattable) valueObject).ToString(OutputFormat, formatProvider)); + return ((IFormattable)valueObject).ToString(OutputFormat, formatProvider); default: return PropertyAccess.FormatString(valueObject.ToString(), format); } @@ -61,15 +64,5 @@ public virtual string GetProperty(string propertyName, string format, CultureInf return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs index 00d5762ad08..bf9ca9e1d52 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs @@ -1,38 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Globalization; - -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System.Globalization; + + using DotNetNuke.Entities.Users; + /// - /// Returns an Empty String for all Properties + /// Returns an Empty String for all Properties. /// /// public class EmptyPropertyAccess : IPropertyAccess - { - #region IPropertyAccess Members - - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) - { - return string.Empty; - } - + { public CacheLevel Cacheability { get { return CacheLevel.notCacheable; } + } + + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) + { + return string.Empty; } - - #endregion } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/IPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/IPropertyAccess.cs index 8d200a0186c..7f6d3bac169 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/IPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/IPropertyAccess.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Globalization; - -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System.Globalization; + + using DotNetNuke.Entities.Users; + public interface IPropertyAccess { CacheLevel Cacheability { get; } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs index 6033b6bbedc..ded946edfb2 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable once CheckNamespace namespace DotNetNuke.Services.Tokens { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Newtonsoft.Json; + public class JavaScriptDto { [JsonProperty("jsname")] @@ -40,54 +41,57 @@ public class JavaScriptPropertyAccess : JsonPropertyAccess public JavaScriptPropertyAccess(Page page) { - _page = page; + this._page = page; } protected override string ProcessToken(JavaScriptDto model, UserInfo accessingUser, Scope accessLevel) { - if (String.IsNullOrEmpty(model.JsName)) + if (string.IsNullOrEmpty(model.JsName)) { - if (String.IsNullOrEmpty(model.Path)) + if (string.IsNullOrEmpty(model.Path)) { throw new ArgumentException("If the jsname property is not specified then the JavaScript token must specify a path or property."); } + if (model.Priority == 0) { model.Priority = (int)FileOrder.Js.DefaultPriority; } - if (String.IsNullOrEmpty(model.Provider)) + + if (string.IsNullOrEmpty(model.Provider)) { - ClientResourceManager.RegisterScript(_page, model.Path, model.Priority); + ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority); } else { - ClientResourceManager.RegisterScript(_page, model.Path, model.Priority, model.Provider); + ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority, model.Provider); } } - else if (!String.IsNullOrEmpty(model.Path)) + else if (!string.IsNullOrEmpty(model.Path)) { if (model.Priority == 0) { model.Priority = (int)FileOrder.Js.DefaultPriority; } - if (String.IsNullOrEmpty(model.Provider)) + + if (string.IsNullOrEmpty(model.Provider)) { - ClientResourceManager.RegisterScript(_page, model.Path, model.Priority, "", model.JsName, model.Version); + ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority, string.Empty, model.JsName, model.Version); } else { - ClientResourceManager.RegisterScript(_page, model.Path, model.Priority, model.Provider, model.JsName, model.Version); + ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority, model.Provider, model.JsName, model.Version); } } else { Version version = null; SpecificVersion specific = SpecificVersion.Latest; - if (!String.IsNullOrEmpty(model.Version)) + if (!string.IsNullOrEmpty(model.Version)) { version = new Version(model.Version); - if (!String.IsNullOrEmpty(model.Specific)) + if (!string.IsNullOrEmpty(model.Specific)) { switch (model.Specific) { @@ -106,10 +110,11 @@ protected override string ProcessToken(JavaScriptDto model, UserInfo accessingUs } } } + JavaScript.RequestRegistration(model.JsName, version, specific); } - return String.Empty; + return string.Empty; } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs index 93b8b9aaa7c..d26b422217b 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using DotNetNuke.Entities.Users; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable once CheckNamespace namespace DotNetNuke.Services.Tokens { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Users; + using Newtonsoft.Json; + public abstract class JsonPropertyAccess : IPropertyAccess { public virtual CacheLevel Cacheability @@ -27,7 +28,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format var deserializedObject = JsonConvert.DeserializeObject(json); - return ProcessToken(deserializedObject, accessingUser, accessLevel); + return this.ProcessToken(deserializedObject, accessingUser, accessLevel); } protected abstract string ProcessToken(TModel model, UserInfo accessingUser, Scope accessLevel); diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs index 76b57fa0799..a334d3622f3 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs @@ -1,22 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; -using System.Reflection; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Tokens { + using System; + using System.Globalization; + using System.Reflection; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// - /// Property Access to Objects using Relection + /// Property Access to Objects using Relection. /// /// public class PropertyAccess : IPropertyAccess @@ -25,7 +22,7 @@ public class PropertyAccess : IPropertyAccess public PropertyAccess(object TokenSource) { - obj = TokenSource; + this.obj = TokenSource; } public static string ContentLocked @@ -34,18 +31,7 @@ public static string ContentLocked { return "*******"; } - } - - #region IPropertyAccess Members - - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) - { - if (obj == null) - { - return string.Empty; - } - return GetObjectProperty(obj, propertyName, format, formatProvider, ref PropertyNotFound); - } + } public CacheLevel Cacheability { @@ -53,10 +39,8 @@ public CacheLevel Cacheability { return CacheLevel.notCacheable; } - } - - #endregion - + } + /// /// Boolean2LocalizedYesNo returns the translated string for "yes" or "no" against a given boolean value. /// @@ -67,15 +51,15 @@ public CacheLevel Cacheability public static string Boolean2LocalizedYesNo(bool value, CultureInfo formatProvider) { string strValue = Convert.ToString(value ? "Yes" : "No"); - return Localization.Localization.GetString(strValue, null, formatProvider.ToString()); + return Localization.GetString(strValue, null, formatProvider.ToString()); } /// /// Returns a formatted String if a format is given, otherwise it returns the unchanged value. /// - /// string to be formatted - /// format specification - /// formatted string + /// string to be formatted. + /// format specification. + /// formatted string. /// public static string FormatString(string value, string format) { @@ -92,16 +76,26 @@ public static string FormatString(string value, string format) return string.Empty; } } + + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) + { + if (this.obj == null) + { + return string.Empty; + } + + return GetObjectProperty(this.obj, propertyName, format, formatProvider, ref PropertyNotFound); + } /// - /// Returns the localized property of any object as string using reflection + /// Returns the localized property of any object as string using reflection. /// - /// Object to access - /// Name of property - /// Format String - /// specify formatting - /// out: specifies, whether property was found - /// Localized Property + /// Object to access. + /// Name of property. + /// Format String. + /// specify formatting. + /// out: specifies, whether property was found. + /// Localized Property. /// public static string GetObjectProperty(object objObject, string strPropertyName, string strFormat, CultureInfo formatProvider, ref bool PropertyNotFound) { @@ -110,7 +104,7 @@ public static string GetObjectProperty(object objObject, string strPropertyName, if (CBO.GetProperties(objObject.GetType()).TryGetValue(strPropertyName, out objProperty)) { object propValue = objProperty.GetValue(objObject, null); - Type t = typeof (string); + Type t = typeof(string); if (propValue != null) { switch (objProperty.PropertyType.Name) @@ -118,7 +112,7 @@ public static string GetObjectProperty(object objObject, string strPropertyName, case "String": return FormatString(Convert.ToString(propValue), strFormat); case "Boolean": - return (Boolean2LocalizedYesNo(Convert.ToBoolean(propValue), formatProvider)); + return Boolean2LocalizedYesNo(Convert.ToBoolean(propValue), formatProvider); case "DateTime": case "Double": case "Single": @@ -128,14 +122,16 @@ public static string GetObjectProperty(object objObject, string strPropertyName, { strFormat = "g"; } - return (((IFormattable) propValue).ToString(strFormat, formatProvider)); + + return ((IFormattable)propValue).ToString(strFormat, formatProvider); } } else { - return ""; + return string.Empty; } } + PropertyNotFound = true; return string.Empty; } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs index cc189444464..5b0ee6de526 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs @@ -1,24 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Entities.Users; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.Services.Tokens + // ReSharper restore CheckNamespace { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Users; + public class TicksPropertyAccess : IPropertyAccess - { - #region IPropertyAccess Members - + { + public CacheLevel Cacheability + { + get + { + return CacheLevel.secureforCaching; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { switch (propertyName.ToLowerInvariant()) @@ -30,18 +32,9 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "ticksperday": return TimeSpan.TicksPerDay.ToString(formatProvider); } + PropertyNotFound = true; return string.Empty; } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.secureforCaching; - } - } - - #endregion } } diff --git a/DNN Platform/Library/Services/Tokens/Scope.cs b/DNN Platform/Library/Services/Tokens/Scope.cs index a3453f24172..779db2a7d7e 100644 --- a/DNN Platform/Library/Services/Tokens/Scope.cs +++ b/DNN Platform/Library/Services/Tokens/Scope.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Tokens { /// - /// Scope informs the property access classes about the planned usage of the token + /// Scope informs the property access classes about the planned usage of the token. /// /// /// The result of a token replace operation depends on the current context, privacy settings @@ -18,21 +18,25 @@ public enum Scope /// Only access to Date and Time /// NoSettings = 0, + /// /// Tokens for Host, Portal, Tab (, Module), user name /// Configuration = 1, + /// /// Configuration, Current User data and user data allowed for registered members /// DefaultSettings = 2, + /// /// System notifications to users and adminstrators /// SystemMessages = 3, + /// /// internal debugging, error messages, logs /// - Debug = 4 + Debug = 4, } } diff --git a/DNN Platform/Library/Services/Tokens/TokenReplace.cs b/DNN Platform/Library/Services/Tokens/TokenReplace.cs index f05f586df58..0bfa86c1681 100644 --- a/DNN Platform/Library/Services/Tokens/TokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/TokenReplace.cs @@ -1,310 +1,331 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Data; -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Tokens { + using System.Collections; + using System.Data; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + /// /// The TokenReplace class provides the option to replace tokens formatted /// [object:property] or [object:property|format] or [custom:no] within a string /// with the appropriate current property/custom values. /// Example for Newsletter: 'Dear [user:Displayname],' ==> 'Dear Superuser Account,' /// Supported Token Sources: User, Host, Portal, Tab, Module, Membership, Profile, - /// Row, Date, Ticks, ArrayList (Custom), IDictionary + /// Row, Date, Ticks, ArrayList (Custom), IDictionary. /// /// public class TokenReplace : BaseCustomTokenReplace { - private ModuleInfo _moduleInfo; - - /// - /// creates a new TokenReplace object for default context + private ModuleInfo _moduleInfo; + + /// + /// Initializes a new instance of the class. + /// creates a new TokenReplace object for default context. /// - public TokenReplace() : this(Scope.DefaultSettings, null, null, null, Null.NullInteger) + public TokenReplace() + : this(Scope.DefaultSettings, null, null, null, Null.NullInteger) { - } - - /// - /// creates a new TokenReplace object for default context and the current module + } + + /// + /// Initializes a new instance of the class. + /// creates a new TokenReplace object for default context and the current module. /// - /// ID of the current module - public TokenReplace(int moduleID) : this(Scope.DefaultSettings, null, null, null, moduleID) + /// ID of the current module. + public TokenReplace(int moduleID) + : this(Scope.DefaultSettings, null, null, null, moduleID) { - } - - /// - /// creates a new TokenReplace object for custom context + } + + /// + /// Initializes a new instance of the class. + /// creates a new TokenReplace object for custom context. /// - /// Security level granted by the calling object - public TokenReplace(Scope accessLevel) : this(accessLevel, null, null, null, Null.NullInteger) + /// Security level granted by the calling object. + public TokenReplace(Scope accessLevel) + : this(accessLevel, null, null, null, Null.NullInteger) { - } - - /// - /// creates a new TokenReplace object for custom context + } + + /// + /// Initializes a new instance of the class. + /// creates a new TokenReplace object for custom context. /// - /// Security level granted by the calling object - /// ID of the current module - public TokenReplace(Scope accessLevel, int moduleID) : this(accessLevel, null, null, null, moduleID) + /// Security level granted by the calling object. + /// ID of the current module. + public TokenReplace(Scope accessLevel, int moduleID) + : this(accessLevel, null, null, null, moduleID) { - } - - /// - /// creates a new TokenReplace object for custom context + } + + /// + /// Initializes a new instance of the class. + /// creates a new TokenReplace object for custom context. /// - /// Security level granted by the calling object + /// Security level granted by the calling object. /// Locale to be used for formatting etc. - /// PortalSettings to be used - /// user, for which the properties shall be returned - public TokenReplace(Scope accessLevel, string language, PortalSettings portalSettings, UserInfo user) : this(accessLevel, language, portalSettings, user, Null.NullInteger) + /// PortalSettings to be used. + /// user, for which the properties shall be returned. + public TokenReplace(Scope accessLevel, string language, PortalSettings portalSettings, UserInfo user) + : this(accessLevel, language, portalSettings, user, Null.NullInteger) { - } - - /// - /// creates a new TokenReplace object for custom context + } + + /// + /// Initializes a new instance of the class. + /// creates a new TokenReplace object for custom context. /// - /// Security level granted by the calling object + /// Security level granted by the calling object. /// Locale to be used for formatting etc. - /// PortalSettings to be used - /// user, for which the properties shall be returned - /// ID of the current module + /// PortalSettings to be used. + /// user, for which the properties shall be returned. + /// ID of the current module. public TokenReplace(Scope accessLevel, string language, PortalSettings portalSettings, UserInfo user, int moduleID) { - ModuleId = int.MinValue; - CurrentAccessLevel = accessLevel; + this.ModuleId = int.MinValue; + this.CurrentAccessLevel = accessLevel; if (accessLevel != Scope.NoSettings) { if (portalSettings == null) { if (HttpContext.Current != null) { - PortalSettings = PortalController.Instance.GetCurrentPortalSettings(); + this.PortalSettings = PortalController.Instance.GetCurrentPortalSettings(); } } else { - PortalSettings = portalSettings; + this.PortalSettings = portalSettings; } + if (user == null) { if (HttpContext.Current != null) { - User = (UserInfo) HttpContext.Current.Items["UserInfo"]; + this.User = (UserInfo)HttpContext.Current.Items["UserInfo"]; } else { - User = new UserInfo(); + this.User = new UserInfo(); } - AccessingUser = User; + + this.AccessingUser = this.User; } else { - User = user; + this.User = user; if (HttpContext.Current != null) { - AccessingUser = (UserInfo) HttpContext.Current.Items["UserInfo"]; + this.AccessingUser = (UserInfo)HttpContext.Current.Items["UserInfo"]; } else { - AccessingUser = new UserInfo(); + this.AccessingUser = new UserInfo(); } } - Language = string.IsNullOrEmpty(language) ? new Localization.Localization().CurrentUICulture : language; + + this.Language = string.IsNullOrEmpty(language) ? new Localization.Localization().CurrentUICulture : language; if (moduleID != Null.NullInteger) { - ModuleId = moduleID; + this.ModuleId = moduleID; } } - PropertySource["date"] = new DateTimePropertyAccess(); - PropertySource["datetime"] = new DateTimePropertyAccess(); - PropertySource["ticks"] = new TicksPropertyAccess(); - PropertySource["culture"] = new CulturePropertyAccess(); + + this.PropertySource["date"] = new DateTimePropertyAccess(); + this.PropertySource["datetime"] = new DateTimePropertyAccess(); + this.PropertySource["ticks"] = new TicksPropertyAccess(); + this.PropertySource["culture"] = new CulturePropertyAccess(); } - + /// - /// Gets/sets the current ModuleID to be used for 'User:' token replacement + /// Gets or sets /sets the current ModuleID to be used for 'User:' token replacement. /// - /// ModuleID (Integer) + /// ModuleID (Integer). public int ModuleId { get; set; } /// - /// Gets/sets the module settings object to use for 'Module:' token replacement + /// Gets or sets /sets the module settings object to use for 'Module:' token replacement. /// public ModuleInfo ModuleInfo { get { - if (ModuleId > int.MinValue && (_moduleInfo == null || _moduleInfo.ModuleID != ModuleId)) + if (this.ModuleId > int.MinValue && (this._moduleInfo == null || this._moduleInfo.ModuleID != this.ModuleId)) { - if (PortalSettings != null && PortalSettings.ActiveTab != null) + if (this.PortalSettings != null && this.PortalSettings.ActiveTab != null) { - _moduleInfo = ModuleController.Instance.GetModule(ModuleId, PortalSettings.ActiveTab.TabID, false); + this._moduleInfo = ModuleController.Instance.GetModule(this.ModuleId, this.PortalSettings.ActiveTab.TabID, false); } else { - _moduleInfo = ModuleController.Instance.GetModule(ModuleId, Null.NullInteger, true); + this._moduleInfo = ModuleController.Instance.GetModule(this.ModuleId, Null.NullInteger, true); } } - return _moduleInfo; + + return this._moduleInfo; } + set { - _moduleInfo = value; + this._moduleInfo = value; } } /// - /// Gets/sets the portal settings object to use for 'Portal:' token replacement + /// Gets or sets /sets the portal settings object to use for 'Portal:' token replacement. /// - /// PortalSettings oject + /// PortalSettings oject. public PortalSettings PortalSettings { get; set; } /// - /// Gets/sets the user object to use for 'User:' token replacement + /// Gets or sets /sets the user object to use for 'User:' token replacement. /// - /// UserInfo oject + /// UserInfo oject. public UserInfo User { get; set; } /// - /// setup context by creating appropriate objects + /// Replaces tokens in sourceText parameter with the property values. + /// + /// String with [Object:Property] tokens. + /// string containing replaced values. + public string ReplaceEnvironmentTokens(string sourceText) + { + return this.ReplaceTokens(sourceText); + } + + /// + /// Replaces tokens in sourceText parameter with the property values. + /// + /// String with [Object:Property] tokens. + /// + /// string containing replaced values. + public string ReplaceEnvironmentTokens(string sourceText, DataRow row) + { + var rowProperties = new DataRowPropertyAccess(row); + this.PropertySource["field"] = rowProperties; + this.PropertySource["row"] = rowProperties; + return this.ReplaceTokens(sourceText); + } + + /// + /// setup context by creating appropriate objects. /// /// - /// security is not the purpose of the initialization, this is in the responsibility of each property access class + /// security is not the purpose of the initialization, this is in the responsibility of each property access class. /// private void InitializePropertySources() { - //Cleanup, by default "" is returned for these objects and any property + // Cleanup, by default "" is returned for these objects and any property IPropertyAccess defaultPropertyAccess = new EmptyPropertyAccess(); - PropertySource["portal"] = defaultPropertyAccess; - PropertySource["tab"] = defaultPropertyAccess; - PropertySource["host"] = defaultPropertyAccess; - PropertySource["module"] = defaultPropertyAccess; - PropertySource["user"] = defaultPropertyAccess; - PropertySource["membership"] = defaultPropertyAccess; - PropertySource["profile"] = defaultPropertyAccess; + this.PropertySource["portal"] = defaultPropertyAccess; + this.PropertySource["tab"] = defaultPropertyAccess; + this.PropertySource["host"] = defaultPropertyAccess; + this.PropertySource["module"] = defaultPropertyAccess; + this.PropertySource["user"] = defaultPropertyAccess; + this.PropertySource["membership"] = defaultPropertyAccess; + this.PropertySource["profile"] = defaultPropertyAccess; - //initialization - if (CurrentAccessLevel >= Scope.Configuration) + // initialization + if (this.CurrentAccessLevel >= Scope.Configuration) { - if (PortalSettings != null) + if (this.PortalSettings != null) { - PropertySource["portal"] = PortalSettings; - PropertySource["tab"] = PortalSettings.ActiveTab; + this.PropertySource["portal"] = this.PortalSettings; + this.PropertySource["tab"] = this.PortalSettings.ActiveTab; } - PropertySource["host"] = new HostPropertyAccess(); - if (ModuleInfo != null) + + this.PropertySource["host"] = new HostPropertyAccess(); + if (this.ModuleInfo != null) { - PropertySource["module"] = ModuleInfo; + this.PropertySource["module"] = this.ModuleInfo; } } - if (CurrentAccessLevel >= Scope.DefaultSettings && !(User == null || User.UserID == -1)) + + if (this.CurrentAccessLevel >= Scope.DefaultSettings && !(this.User == null || this.User.UserID == -1)) { - PropertySource["user"] = User; - PropertySource["membership"] = new MembershipPropertyAccess(User); - PropertySource["profile"] = new ProfilePropertyAccess(User); + this.PropertySource["user"] = this.User; + this.PropertySource["membership"] = new MembershipPropertyAccess(this.User); + this.PropertySource["profile"] = new ProfilePropertyAccess(this.User); } } - /// - /// Replaces tokens in sourceText parameter with the property values - /// - /// String with [Object:Property] tokens - /// string containing replaced values - public string ReplaceEnvironmentTokens(string sourceText) - { - return ReplaceTokens(sourceText); - } - /// - /// Replaces tokens in sourceText parameter with the property values + /// Replaces tokens in sourceText parameter with the property values. /// - /// String with [Object:Property] tokens - /// - /// string containing replaced values - public string ReplaceEnvironmentTokens(string sourceText, DataRow row) - { - var rowProperties = new DataRowPropertyAccess(row); - PropertySource["field"] = rowProperties; - PropertySource["row"] = rowProperties; - return ReplaceTokens(sourceText); - } - - /// - /// Replaces tokens in sourceText parameter with the property values - /// - /// String with [Object:Property] tokens + /// String with [Object:Property] tokens. /// /// - /// string containing replaced values + /// string containing replaced values. public string ReplaceEnvironmentTokens(string sourceText, ArrayList custom, string customCaption) { - PropertySource[customCaption.ToLowerInvariant()] = new ArrayListPropertyAccess(custom); - return ReplaceTokens(sourceText); + this.PropertySource[customCaption.ToLowerInvariant()] = new ArrayListPropertyAccess(custom); + return this.ReplaceTokens(sourceText); } /// - /// Replaces tokens in sourceText parameter with the property values + /// Replaces tokens in sourceText parameter with the property values. /// - /// String with [Object:Property] tokens - /// NameValueList for replacing [custom:name] tokens, where 'custom' is specified in next param and name is either thekey or the index number in the string - /// Token name to be used inside token [custom:name] - /// string containing replaced values + /// String with [Object:Property] tokens. + /// NameValueList for replacing [custom:name] tokens, where 'custom' is specified in next param and name is either thekey or the index number in the string. + /// Token name to be used inside token [custom:name]. + /// string containing replaced values. public string ReplaceEnvironmentTokens(string sourceText, IDictionary custom, string customCaption) { - PropertySource[customCaption.ToLowerInvariant()] = new DictionaryPropertyAccess(custom); - return ReplaceTokens(sourceText); + this.PropertySource[customCaption.ToLowerInvariant()] = new DictionaryPropertyAccess(custom); + return this.ReplaceTokens(sourceText); } - /// - /// Replaces tokens in sourceText parameter with the property values - /// - /// String with [Object:Property] tokens - /// NameValueList for replacing [custom:name] tokens, where 'custom' is specified in next param and name is either thekey or the index number in the string - /// Token names to be used inside token [custom:name], where 'custom' is one of the values in the string array - /// string containing replaced values + /// + /// Replaces tokens in sourceText parameter with the property values. + /// + /// String with [Object:Property] tokens. + /// NameValueList for replacing [custom:name] tokens, where 'custom' is specified in next param and name is either thekey or the index number in the string. + /// Token names to be used inside token [custom:name], where 'custom' is one of the values in the string array. + /// string containing replaced values. public string ReplaceEnvironmentTokens(string sourceText, IDictionary custom, string[] customCaptions) { foreach (var customCaption in customCaptions) { - PropertySource[customCaption.ToLowerInvariant()] = new DictionaryPropertyAccess(custom); - } - return ReplaceTokens(sourceText); + this.PropertySource[customCaption.ToLowerInvariant()] = new DictionaryPropertyAccess(custom); + } + + return this.ReplaceTokens(sourceText); } - + /// - /// Replaces tokens in sourceText parameter with the property values + /// Replaces tokens in sourceText parameter with the property values. /// - /// String with [Object:Property] tokens - /// NameValueList for replacing [custom:name] tokens, where 'custom' is specified in next param and name is either thekey or the index number in the string - /// Token name to be used inside token [custom:name] - /// DataRow, from which field values shall be used for replacement - /// string containing replaced values + /// String with [Object:Property] tokens. + /// NameValueList for replacing [custom:name] tokens, where 'custom' is specified in next param and name is either thekey or the index number in the string. + /// Token name to be used inside token [custom:name]. + /// DataRow, from which field values shall be used for replacement. + /// string containing replaced values. public string ReplaceEnvironmentTokens(string sourceText, ArrayList custom, string customCaption, DataRow row) { var rowProperties = new DataRowPropertyAccess(row); - PropertySource["field"] = rowProperties; - PropertySource["row"] = rowProperties; - PropertySource[customCaption.ToLowerInvariant()] = new ArrayListPropertyAccess(custom); - return ReplaceTokens(sourceText); + this.PropertySource["field"] = rowProperties; + this.PropertySource["row"] = rowProperties; + this.PropertySource[customCaption.ToLowerInvariant()] = new ArrayListPropertyAccess(custom); + return this.ReplaceTokens(sourceText); } /// - /// Replaces tokens in sourceText parameter with the property values, skipping environment objects + /// Replaces tokens in sourceText parameter with the property values, skipping environment objects. /// - /// String with [Object:Property] tokens - /// string containing replaced values + /// String with [Object:Property] tokens. + /// string containing replaced values. protected override string ReplaceTokens(string sourceText) { - InitializePropertySources(); + this.InitializePropertySources(); return base.ReplaceTokens(sourceText); } } diff --git a/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs b/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs index 14bac45e476..892c04a5b40 100644 --- a/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs +++ b/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs @@ -1,79 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Web.Compilation; -using DotNetNuke.Services.Upgrade.Internals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Upgrade { - /// - /// This class is used to write log into separate installer log file. - /// - internal class DnnInstallLogger - { - private static StackFrame CallingFrame - { - get - { - StackFrame frame = null; - StackFrame[] stack = new StackTrace().GetFrames(); - - int frameDepth = 0; - if (stack != null) - { - Type reflectedType = stack[frameDepth].GetMethod().ReflectedType; - while (reflectedType == BuildManager.GetType("DotNetNuke.Services.Exceptions.Exceptions", false) || reflectedType == typeof(DnnInstallLogger)) - { - frameDepth++; - reflectedType = stack[frameDepth].GetMethod().ReflectedType; - } - frame = stack[frameDepth]; - } - return frame; - } - } - - private static Type CallingType - { - get - { - return CallingFrame.GetMethod().DeclaringType; - } - } - - #region InstallLog - - public static void InstallLogError(object message) - { - LogInstaller("[ERROR]", message.ToString()); - } - - public static void InstallLogError(string message, Exception exception) - { - LogInstaller("[ERROR]", message.ToString(CultureInfo.InvariantCulture) + " : " + exception); - } + using System; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.Web.Compilation; + + using DotNetNuke.Services.Upgrade.Internals; + + /// + /// This class is used to write log into separate installer log file. + /// + internal class DnnInstallLogger + { + private static StackFrame CallingFrame + { + get + { + StackFrame frame = null; + StackFrame[] stack = new StackTrace().GetFrames(); - public static void InstallLogInfo(object message) - { - LogInstaller("[INFO]", message.ToString()); - } + int frameDepth = 0; + if (stack != null) + { + Type reflectedType = stack[frameDepth].GetMethod().ReflectedType; + while (reflectedType == BuildManager.GetType("DotNetNuke.Services.Exceptions.Exceptions", false) || reflectedType == typeof(DnnInstallLogger)) + { + frameDepth++; + reflectedType = stack[frameDepth].GetMethod().ReflectedType; + } + + frame = stack[frameDepth]; + } + + return frame; + } + } - #endregion + private static Type CallingType + { + get + { + return CallingFrame.GetMethod().DeclaringType; + } + } + + public static void InstallLogError(object message) + { + LogInstaller("[ERROR]", message.ToString()); + } - private static void LogInstaller(string logType, string message) - { - var logFile = InstallController.Instance.InstallerLogName; - var logfilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Portals\_default\Logs\" + logFile); - using (var writer = new StreamWriter(logfilePath, true)) - { - writer.WriteLine(DateTime.UtcNow.ToString(CultureInfo.InvariantCulture) + " " + logType + " " + CallingType + " " + message); - } + public static void InstallLogError(string message, Exception exception) + { + LogInstaller("[ERROR]", message.ToString(CultureInfo.InvariantCulture) + " : " + exception); + } - } - } + public static void InstallLogInfo(object message) + { + LogInstaller("[INFO]", message.ToString()); + } + + private static void LogInstaller(string logType, string message) + { + var logFile = InstallController.Instance.InstallerLogName; + var logfilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Portals\_default\Logs\" + logFile); + using (var writer = new StreamWriter(logfilePath, true)) + { + writer.WriteLine(DateTime.UtcNow.ToString(CultureInfo.InvariantCulture) + " " + logType + " " + CallingType + " " + message); + } + } + } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs b/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs index 14f57d31434..b2078103a3a 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs @@ -1,24 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Upgrade.Internals { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; + /// ----------------------------------------------------------------------------- /// - /// Interface for InstallController. This Interface is meant for Internal use only + /// Interface for InstallController. This Interface is meant for Internal use only. /// /// /// public interface IInstallController { + string InstallerLogName { get; } + bool IsValidSqlServerVersion(string connectionString); bool IsAbleToPerformDatabaseActions(string connectionString); @@ -30,26 +32,26 @@ public interface IInstallController bool IsAvailableLanguagePack(string cultureCode); /// - /// GetInstallConfig - Returns configuration stored in DotNetNuke.Install.Config + /// GetInstallConfig - Returns configuration stored in DotNetNuke.Install.Config. /// - /// ConnectionConfig object. Null if information is not present in the config file + /// ConnectionConfig object. Null if information is not present in the config file. InstallConfig GetInstallConfig(); /// - /// SetInstallConfig - Saves configuration n DotNetNuke.Install.Config - /// + /// SetInstallConfig - Saves configuration n DotNetNuke.Install.Config. + /// void SetInstallConfig(InstallConfig installConfig); /// - /// RemoveFromInstallConfig - Removes the specified XML Node from the InstallConfig + /// RemoveFromInstallConfig - Removes the specified XML Node from the InstallConfig. /// /// void RemoveFromInstallConfig(string xmlNodePath); /// - /// GetConnectionFromWebConfig - Returns Connection Configuration in web.config file + /// GetConnectionFromWebConfig - Returns Connection Configuration in web.config file. /// - /// ConnectionConfig object. Null if information is not present in the config file + /// ConnectionConfig object. Null if information is not present in the config file. ConnectionConfig GetConnectionFromWebConfig(); CultureInfo GetCurrentLanguage(); @@ -57,7 +59,5 @@ public interface IInstallController string TestDatabaseConnection(ConnectionConfig connectionConfig); CultureInfo GetCultureFromCookie(); - - string InstallerLogName { get; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs index 0714b35f93d..b20518e8575 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs @@ -1,31 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration { + using System; + /// ----------------------------------------------------------------------------- /// - /// ConnectionConfig - A class that represents Install/DotNetNuke.Install.Config/Connection + /// ConnectionConfig - A class that represents Install/DotNetNuke.Install.Config/Connection. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class ConnectionConfig { public string Server { get; set; } + public string Database { get; set; } + public string File { get; set; } + public bool Integrated { get; set; } + public string User { get; set; } + public string Password { get; set; } + public bool RunAsDbowner { get; set; } + public string Qualifier { get; set; } + public string UpgradeConnectionString { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs index 37769e0ef1c..27703882087 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs @@ -1,25 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration { + using System; + /// ----------------------------------------------------------------------------- /// - /// HostSettingConfig - A class that represents Install/DotNetNuke.Install.Config/Settings + /// HostSettingConfig - A class that represents Install/DotNetNuke.Install.Config/Settings. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class HostSettingConfig { public string Name { get; set; } + public string Value { get; set; } + public bool IsSecure { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs index 736ef3b7de2..8fb242f7e06 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs @@ -1,45 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration { + using System; + using System.Collections.Generic; + /// ----------------------------------------------------------------------------- /// /// InstallConfig - A class that represents DotNetNuke.Install.Config XML configuration file - /// TODO This class may not capture all the details from the config file + /// TODO This class may not capture all the details from the config file. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class InstallConfig { + public InstallConfig() + { + this.Portals = new List(); + this.Scripts = new List(); + this.Settings = new List(); + } + public IList Scripts { get; set; } + public string Version { get; set; } + public string InstallCulture { get; set; } + public SuperUserConfig SuperUser { get; set; } + public ConnectionConfig Connection { get; set; } + public LicenseConfig License { get; set; } + public IList Portals { get; set; } + public IList Settings { get; set; } - public string FolderMappingsSettings { get; set; } + public string FolderMappingsSettings { get; set; } public bool SupportLocalization { get; set; } - - public InstallConfig() - { - Portals = new List(); - Scripts = new List(); - Settings = new List(); - } } - - } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs index 6ae89edf3c3..8500b1752f4 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs @@ -1,27 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration { + using System; + /// ----------------------------------------------------------------------------- /// - /// LicenseConfig - A class that represents Install/DotNetNuke.Install.Config/LicenseActivation + /// LicenseConfig - A class that represents Install/DotNetNuke.Install.Config/LicenseActivation. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class LicenseConfig { public string AccountEmail { get; set; } + public string InvoiceNumber { get; set; } + public string WebServer { get; set; } + public string LicenseType { get; set; } + public bool TrialRequest { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs index 56919a7a29c..4d48566fa4d 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs @@ -1,40 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration { + using System; + using System.Collections.Generic; + /// ----------------------------------------------------------------------------- /// - /// PortalConfig - A class that represents Install/DotNetNuke.Install.Config/Portals/Portal + /// PortalConfig - A class that represents Install/DotNetNuke.Install.Config/Portals/Portal. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class PortalConfig { + public PortalConfig() + { + this.PortAliases = new List(); + } + public string PortalName { get; set; } + public string AdminFirstName { get; set; } + public string AdminLastName { get; set; } + public string AdminUserName { get; set; } + public string AdminPassword { get; set; } + public string AdminEmail { get; set; } + public string Description { get; set; } + public string Keywords { get; set; } + public string TemplateFileName { get; set; } + public bool IsChild { get; set; } + public string HomeDirectory { get; set; } - public IList PortAliases { get; set; } - - public PortalConfig() - { - PortAliases = new List(); - } + + public IList PortAliases { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs index d58fb736d63..c22727a1f69 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs @@ -1,29 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration { + using System; + /// ----------------------------------------------------------------------------- /// - /// SuperUserConfig - A class that represents Install/DotNetNuke.Install.Config/SuperUser + /// SuperUserConfig - A class that represents Install/DotNetNuke.Install.Config/SuperUser. /// - /// ----------------------------------------------------------------------------- - + /// ----------------------------------------------------------------------------- public class SuperUserConfig { public string FirstName { get; set; } + public string LastName { get; set; } + public string UserName { get; set; } + public string Password { get; set; } + public string Email { get; set; } + public string Locale { get; set; } + public bool UpdatePassword { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallController.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallController.cs index 243ec431ef5..d873aee8ac4 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallController.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallController.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Framework; -using DotNetNuke.Services.Upgrade.InternalController; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals { - /// - /// Business Layer to manage Messaging. Also contains CRUD methods. - /// + using System; + + using DotNetNuke.Framework; + using DotNetNuke.Services.Upgrade.InternalController; + + /// + /// Business Layer to manage Messaging. Also contains CRUD methods. + /// public class InstallController : ServiceLocator { protected override Func GetFactory() diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs index 39fc44d8450..cdf223bc279 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs @@ -1,45 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data.Common; -using System.Data.SqlClient; -using System.Globalization; -using System.Net; -using System.Threading; -using System.Web; -using System.Xml; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Installer; -using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals { + using System; + using System.Collections.Generic; + using System.Data.Common; + using System.Data.SqlClient; + using System.Globalization; + using System.Net; + using System.Threading; + using System.Web; + using System.Xml; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Installer; + using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// The Controller class for Installer + /// The Controller class for Installer. /// /// /// internal class InstallControllerImpl : IInstallController - { - #region IInstallController Members - + { + public string InstallerLogName + { + get { return "InstallerLog" + DateTime.Now.ToString("yyyyMMdd") + ".resources"; } + } + /// - /// GetConnectionFromWebConfig - Returns Connection Configuration in web.config file + /// GetConnectionFromWebConfig - Returns Connection Configuration in web.config file. /// - /// ConnectionConfig object. Null if information is not present in the config file + /// ConnectionConfig object. Null if information is not present in the config file. public ConnectionConfig GetConnectionFromWebConfig() { var connectionConfig = new ConnectionConfig(); @@ -75,10 +75,10 @@ public ConnectionConfig GetConnectionFromWebConfig() connectionConfig.Password = value; break; case "integrated security": - connectionConfig.Integrated = (value.ToLowerInvariant() == "true"); + connectionConfig.Integrated = value.ToLowerInvariant() == "true"; break; case "attachdbfilename": - connectionConfig.File = value.Replace("|DataDirectory|", ""); + connectionConfig.File = value.Replace("|DataDirectory|", string.Empty); break; } } @@ -92,8 +92,8 @@ public ConnectionConfig GetConnectionFromWebConfig() } /// - /// SetInstallConfig - Saves configuration n DotNetNuke.Install.Config - /// + /// SetInstallConfig - Saves configuration n DotNetNuke.Install.Config. + /// public void SetInstallConfig(InstallConfig installConfig) { if (installConfig == null) @@ -101,12 +101,12 @@ public void SetInstallConfig(InstallConfig installConfig) return; } - //Load Template + // Load Template var installTemplate = new XmlDocument { XmlResolver = null }; Upgrade.GetInstallTemplate(installTemplate); XmlNode dotnetnukeNode = installTemplate.SelectSingleNode("//dotnetnuke"); - //Set Version + // Set Version if (!string.IsNullOrEmpty(installConfig.Version)) { XmlNode versionNode = installTemplate.SelectSingleNode("//dotnetnuke/version"); @@ -119,7 +119,7 @@ public void SetInstallConfig(InstallConfig installConfig) versionNode.InnerText = installConfig.Version; } - //Set installer culture + // Set installer culture if (!string.IsNullOrEmpty(installConfig.InstallCulture)) { XmlNode versionNode = installTemplate.SelectSingleNode("//dotnetnuke/installCulture"); @@ -132,7 +132,7 @@ public void SetInstallConfig(InstallConfig installConfig) versionNode.InnerText = installConfig.InstallCulture; } - //Set SuperUser + // Set SuperUser if (installConfig.SuperUser != null) { XmlNode superUserNode = installTemplate.SelectSingleNode("//dotnetnuke/superuser"); @@ -153,10 +153,10 @@ public void SetInstallConfig(InstallConfig installConfig) AppendNewXmlNode(ref installTemplate, ref superUserNode, "updatepassword", "false"); } - //Set Folder Mappings Settings + // Set Folder Mappings Settings if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) { - XmlNode folderMappingsNode = installTemplate.SelectSingleNode("//dotnetnuke/"+FolderMappingsConfigController.Instance.ConfigNode); + XmlNode folderMappingsNode = installTemplate.SelectSingleNode("//dotnetnuke/" + FolderMappingsConfigController.Instance.ConfigNode); if (folderMappingsNode == null) { @@ -166,7 +166,7 @@ public void SetInstallConfig(InstallConfig installConfig) folderMappingsNode.InnerText = installConfig.FolderMappingsSettings; } - //Set Portals + // Set Portals if (installConfig.Portals != null && installConfig.Portals.Count > 0) { XmlNode portalsNode = installTemplate.SelectSingleNode("//dotnetnuke/portals"); @@ -178,8 +178,7 @@ public void SetInstallConfig(InstallConfig installConfig) { portalsNode.RemoveAll(); } - - + foreach (PortalConfig portalConfig in installConfig.Portals) { XmlNode portalNode = AppendNewXmlNode(ref installTemplate, ref portalsNode, "portal", null); @@ -204,7 +203,7 @@ public void SetInstallConfig(InstallConfig installConfig) } } - //Set the settings + // Set the settings if (installConfig.Settings != null && installConfig.Settings.Count > 0) { XmlNode settingsNode = installTemplate.SelectSingleNode("//dotnetnuke/settings"); @@ -212,12 +211,12 @@ public void SetInstallConfig(InstallConfig installConfig) { settingsNode = AppendNewXmlNode(ref installTemplate, ref dotnetnukeNode, "settings", null); } + // DNN-8833: for this node specifically we should append/overwrite existing but not clear all - //else - //{ + // else + // { // settingsNode.RemoveAll(); - //} - + // } foreach (HostSettingConfig setting in installConfig.Settings) { XmlNode settingNode = AppendNewXmlNode(ref installTemplate, ref settingsNode, setting.Name, setting.Value); @@ -230,7 +229,7 @@ public void SetInstallConfig(InstallConfig installConfig) } } - //Set Connection + // Set Connection if (installConfig.Connection != null) { XmlNode connectionNode = installTemplate.SelectSingleNode("//dotnetnuke/connection"); @@ -259,11 +258,12 @@ public void SetInstallConfig(InstallConfig installConfig) public void RemoveFromInstallConfig(string xmlNodePath) { - InstallConfig config = GetInstallConfig(); + InstallConfig config = this.GetInstallConfig(); if (config == null) { return; } + var installTemplate = new XmlDocument { XmlResolver = null }; Upgrade.GetInstallTemplate(installTemplate); XmlNodeList nodes = installTemplate.SelectNodes(xmlNodePath); @@ -271,31 +271,32 @@ public void RemoveFromInstallConfig(string xmlNodePath) { nodes[0].ParentNode.RemoveChild(nodes[0]); } + Upgrade.SetInstallTemplate(installTemplate); } /// - /// GetInstallConfig - Returns configuration stored in DotNetNuke.Install.Config + /// GetInstallConfig - Returns configuration stored in DotNetNuke.Install.Config. /// - /// ConnectionConfig object. Null if information is not present in the config file + /// ConnectionConfig object. Null if information is not present in the config file. public InstallConfig GetInstallConfig() { var installConfig = new InstallConfig(); - //Load Template + // Load Template var installTemplate = new XmlDocument { XmlResolver = null }; Upgrade.GetInstallTemplate(installTemplate); - //Parse the root node + // Parse the root node XmlNode rootNode = installTemplate.SelectSingleNode("//dotnetnuke"); if (rootNode != null) { installConfig.Version = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "version"); installConfig.SupportLocalization = XmlUtils.GetNodeValueBoolean(rootNode.CreateNavigator(), "supportLocalization"); - installConfig.InstallCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture") ?? Localization.Localization.SystemLocale; + installConfig.InstallCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture") ?? Localization.SystemLocale; } - //Parse the scripts node + // Parse the scripts node XmlNode scriptsNode = installTemplate.SelectSingleNode("//dotnetnuke/scripts"); if (scriptsNode != null) { @@ -308,13 +309,13 @@ public InstallConfig GetInstallConfig() } } - //Parse the connection node + // Parse the connection node XmlNode connectionNode = installTemplate.SelectSingleNode("//dotnetnuke/connection"); if (connectionNode != null) { var connectionConfig = new ConnectionConfig(); - //Build connection string from the file + // Build connection string from the file connectionConfig.Server = XmlUtils.GetNodeValue(connectionNode.CreateNavigator(), "server"); connectionConfig.Database = XmlUtils.GetNodeValue(connectionNode.CreateNavigator(), "database"); connectionConfig.File = XmlUtils.GetNodeValue(connectionNode.CreateNavigator(), "file"); @@ -328,7 +329,7 @@ public InstallConfig GetInstallConfig() installConfig.Connection = connectionConfig; } - //Parse the superuser node + // Parse the superuser node XmlNode superUserNode = installTemplate.SelectSingleNode("//dotnetnuke/superuser"); if (superUserNode != null) { @@ -345,7 +346,7 @@ public InstallConfig GetInstallConfig() installConfig.SuperUser = superUserConfig; } - //Parse the license node + // Parse the license node XmlNode licenseNode = installTemplate.SelectSingleNode("//dotnetnuke/license"); if (licenseNode != null) { @@ -356,7 +357,7 @@ public InstallConfig GetInstallConfig() licenseConfig.WebServer = XmlUtils.GetNodeValue(licenseNode.CreateNavigator(), "webServer"); licenseConfig.LicenseType = XmlUtils.GetNodeValue(licenseNode.CreateNavigator(), "licenseType"); - if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(licenseNode.CreateNavigator(), "trial"))) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(licenseNode.CreateNavigator(), "trial"))) { licenseConfig.TrialRequest = bool.Parse(XmlUtils.GetNodeValue(licenseNode.CreateNavigator(), "trial")); } @@ -364,7 +365,7 @@ public InstallConfig GetInstallConfig() installConfig.License = licenseConfig; } - //Parse the settings node + // Parse the settings node XmlNode settingsNode = installTemplate.SelectSingleNode("//dotnetnuke/settings"); if (settingsNode != null) { @@ -376,7 +377,7 @@ public InstallConfig GetInstallConfig() if (settingNode.Attributes != null) { XmlAttribute secureAttrib = settingNode.Attributes["Secure"]; - if ((secureAttrib != null)) + if (secureAttrib != null) { if (secureAttrib.Value.ToLowerInvariant() == "true") { @@ -384,14 +385,16 @@ public InstallConfig GetInstallConfig() } } } - installConfig.Settings.Add(new HostSettingConfig {Name = settingNode.Name, Value = settingNode.InnerText, IsSecure = settingIsSecure}); + + installConfig.Settings.Add(new HostSettingConfig { Name = settingNode.Name, Value = settingNode.InnerText, IsSecure = settingIsSecure }); } } } - var folderMappingsNode = installTemplate.SelectSingleNode("//dotnetnuke/"+FolderMappingsConfigController.Instance.ConfigNode); - installConfig.FolderMappingsSettings = (folderMappingsNode != null)? folderMappingsNode.InnerXml : String.Empty; + + var folderMappingsNode = installTemplate.SelectSingleNode("//dotnetnuke/" + FolderMappingsConfigController.Instance.ConfigNode); + installConfig.FolderMappingsSettings = (folderMappingsNode != null) ? folderMappingsNode.InnerXml : string.Empty; - //Parse the portals node + // Parse the portals node XmlNodeList portalsNode = installTemplate.SelectNodes("//dotnetnuke/portals/portal"); if (portalsNode != null) { @@ -411,14 +414,14 @@ public InstallConfig GetInstallConfig() portalConfig.AdminPassword = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "password"); portalConfig.AdminEmail = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "email"); } + portalConfig.Description = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "description"); portalConfig.Keywords = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "keywords"); portalConfig.TemplateFileName = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "templatefile"); portalConfig.IsChild = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "ischild").ToLowerInvariant() == "true"; - ; portalConfig.HomeDirectory = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "homedirectory"); - //Get the Portal Alias + // Get the Portal Alias XmlNodeList portalAliases = portalNode.SelectNodes("portalaliases/portalalias"); if (portalAliases != null) { @@ -430,6 +433,7 @@ public InstallConfig GetInstallConfig() } } } + installConfig.Portals.Add(portalConfig); } } @@ -440,8 +444,7 @@ public InstallConfig GetInstallConfig() public bool IsValidSqlServerVersion(string connectionString) { - //todo: check if we can use globals.DatabaseEngineVersion instead - + // todo: check if we can use globals.DatabaseEngineVersion instead bool isValidVersion = false; var sqlConnection = new SqlConnection(connectionString); try @@ -451,28 +454,28 @@ public bool IsValidSqlServerVersion(string connectionString) string serverVersion = sqlConnection.ServerVersion; if (serverVersion != null) { - string[] serverVersionDetails = serverVersion.Split(new[] {"."}, StringSplitOptions.None); + string[] serverVersionDetails = serverVersion.Split(new[] { "." }, StringSplitOptions.None); int versionNumber = int.Parse(serverVersionDetails[0]); switch (versionNumber) { - case 8: - //sql 2000 + case 8: + // sql 2000 case 9: - //sql 2005 + // sql 2005 isValidVersion = false; break; - case 10: - //sql 2008 - case 11: - //sql 2010 + case 10: + // sql 2008 + case 11: + // sql 2010 case 12: - //sql 2012 + // sql 2012 isValidVersion = true; break; default: - //covers unknown versions and later releases + // covers unknown versions and later releases isValidVersion = true; break; } @@ -480,13 +483,14 @@ public bool IsValidSqlServerVersion(string connectionString) } catch (Exception) { - //cannot connect with the details + // cannot connect with the details isValidVersion = false; } finally { sqlConnection.Close(); } + return isValidVersion; } @@ -495,13 +499,14 @@ public bool IsAbleToPerformDatabaseActions(string connectionString) var fakeName = "{databaseOwner}[{objectQualifier}FakeTable_" + DateTime.Now.Ticks.ToString("x16") + "]"; var databaseActions = string.Format(@"CREATE TABLE {0}([fakeColumn] [int] NULL); SELECT * FROM {0}; DROP TABLE {0};", fakeName); var strExceptions = DataProvider.Instance().ExecuteScript(connectionString, databaseActions); - //if no exceptions we have necessary drop etc permissions + + // if no exceptions we have necessary drop etc permissions return string.IsNullOrEmpty(strExceptions); } public bool IsValidDotNetVersion() { - //todo: check that this works for 4.5 etc. + // todo: check that this works for 4.5 etc. return Upgrade.IsNETFrameworkCurrent("4.0"); } @@ -525,14 +530,16 @@ public bool IsAvailableLanguagePack(string cultureCode) string downloadUrl = UpdateService.GetLanguageDownloadUrl(cultureCode); string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); - //no need to download english, always there - if (cultureCode != "en-us" && String.IsNullOrEmpty(downloadUrl) != true) + + // no need to download english, always there + if (cultureCode != "en-us" && string.IsNullOrEmpty(downloadUrl) != true) { var newCulture = new CultureInfo(cultureCode); Thread.CurrentThread.CurrentCulture = newCulture; - GetLanguagePack(downloadUrl, installFolder); + this.GetLanguagePack(downloadUrl, installFolder); return true; } + return false; } catch (Exception) @@ -544,25 +551,25 @@ public bool IsAvailableLanguagePack(string cultureCode) public CultureInfo GetCurrentLanguage() { CultureInfo pageCulture = null; - - + // 1. querystring - pageCulture = GetCultureFromQs(); + pageCulture = this.GetCultureFromQs(); // 2. cookie - pageCulture = GetCultureFromCookie(); + pageCulture = this.GetCultureFromCookie(); // 3. browser - pageCulture = GetCultureFromBrowser(); + pageCulture = this.GetCultureFromBrowser(); return pageCulture; } /// - /// Tests the Database Connection using the database connection config + /// Tests the Database Connection using the database connection config. /// /// - /// + /// + /// public string TestDatabaseConnection(ConnectionConfig config) { DbConnectionStringBuilder builder = DataProvider.Instance().GetConnectionStringBuilder(); @@ -599,26 +606,32 @@ public CultureInfo GetCultureFromCookie() var culture = new CultureInfo(language); return culture; } - - public string InstallerLogName - { - get { return "InstallerLog" + DateTime.Now.ToString("yyyyMMdd") + ".resources"; } - } - - #endregion - + public CultureInfo GetCultureFromBrowser() { CultureInfo culture = null; foreach (string userLang in HttpContext.Current.Request.UserLanguages) { - //split userlanguage by ";"... all but the first language will contain a preferrence index eg. ;q=.5 + // split userlanguage by ";"... all but the first language will contain a preferrence index eg. ;q=.5 string language = userLang.Split(';')[0]; culture = new CultureInfo(language); } + return culture; } - + + private static XmlNode AppendNewXmlNode(ref XmlDocument document, ref XmlNode parentNode, string elementName, string elementValue) + { + XmlNode newNode = document.CreateNode(XmlNodeType.Element, elementName, null); + if (!string.IsNullOrEmpty(elementValue)) + { + newNode.InnerText = elementValue; + } + + parentNode.AppendChild(newNode); + return newNode; + } + private CultureInfo GetCultureFromQs() { if (HttpContext.Current == null || HttpContext.Current.Request["language"] == null) @@ -633,35 +646,26 @@ private CultureInfo GetCultureFromQs() private void GetLanguagePack(string downloadUrl, string installFolder) { - string myfile = ""; - WebResponse wr = Util.GetExternalRequest(downloadUrl, - null, - null, - null, - null, - null, - -1, - null, - null, - false, - "DotNetNuke-Appgallery/1.0.0.0(Microsoft Windows NT 6.1.7600.0", - "wpi://2.1.0.0/Microsoft Windows NT 6.1.7600.0", - out myfile, - 10000); - //use fixed name for later installation + string myfile = string.Empty; + WebResponse wr = Util.GetExternalRequest( + downloadUrl, + null, + null, + null, + null, + null, + -1, + null, + null, + false, + "DotNetNuke-Appgallery/1.0.0.0(Microsoft Windows NT 6.1.7600.0", + "wpi://2.1.0.0/Microsoft Windows NT 6.1.7600.0", + out myfile, + 10000); + + // use fixed name for later installation myfile = "installlanguage.resources"; Util.DeployExtension(wr, myfile, installFolder); } - - private static XmlNode AppendNewXmlNode(ref XmlDocument document, ref XmlNode parentNode, string elementName, string elementValue) - { - XmlNode newNode = document.CreateNode(XmlNodeType.Element, elementName, null); - if (!string.IsNullOrEmpty(elementValue)) - { - newNode.InnerText = elementValue; - } - parentNode.AppendChild(newNode); - return newNode; - } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/ActivateLicenseStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/ActivateLicenseStep.cs index af0e7e8395f..a145fdc8f4d 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/ActivateLicenseStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/ActivateLicenseStep.cs @@ -1,52 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System; + + using DotNetNuke.Instrumentation; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ------------------------------------------------------------------------------------------------ /// - /// DatabaseVerificationStep - Step that performs database verification checks prior to installation + /// DatabaseVerificationStep - Step that performs database verification checks prior to installation. /// - /// ------------------------------------------------------------------------------------------------ + /// ------------------------------------------------------------------------------------------------ public class ActivateLicenseStep : BaseInstallationStep { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ActivateLicenseStep)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ActivateLicenseStep)); public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; - Details = Localization.Localization.GetString("LicenseActivation", LocalInstallResourceFile); + this.Details = Localization.GetString("LicenseActivation", this.LocalInstallResourceFile); var installConfig = InstallController.Instance.GetInstallConfig(); - var licenseConfig = (installConfig != null) ? installConfig.License : null; + var licenseConfig = (installConfig != null) ? installConfig.License : null; if (licenseConfig != null && (!string.IsNullOrEmpty(licenseConfig.AccountEmail) && !string.IsNullOrEmpty(licenseConfig.InvoiceNumber) && !string.IsNullOrEmpty(licenseConfig.LicenseType) && !string.IsNullOrEmpty(licenseConfig.WebServer))) { try { - var activationResult = ""; + var activationResult = string.Empty; activationResult = Upgrade.ActivateLicense(); if (!activationResult.ToLowerInvariant().Contains("success")) { - Errors.Add(Localization.Localization.GetString("LicenseActivation", LocalInstallResourceFile) + ": " + activationResult); + this.Errors.Add(Localization.GetString("LicenseActivation", this.LocalInstallResourceFile) + ": " + activationResult); Logger.TraceFormat("ActivateLicense Status - {0}", activationResult); } } catch (Exception ex) { - Errors.Add(Localization.Localization.GetString("LicenseActivation", LocalInstallResourceFile) + ": " + ex.Message); + this.Errors.Add(Localization.GetString("LicenseActivation", this.LocalInstallResourceFile) + ": " + ex.Message); Logger.TraceFormat("ActivateLicense Status - {0}", ex.Message); } } - Status = Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs index c1599cce93e..07a8ebb260c 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs @@ -1,36 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Instrumentation; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ------------------------------------------------------------------------------------------------ /// - /// AddFcnModeVerificationStep - Step that performs FcnMode verification checks prior to installation + /// AddFcnModeVerificationStep - Step that performs FcnMode verification checks prior to installation. /// - /// ------------------------------------------------------------------------------------------------ + /// ------------------------------------------------------------------------------------------------ public class AddFcnModeStep : BaseInstallationStep { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AddFcnModeStep)); public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; string strError = Config.AddFCNMode(Config.FcnMode.Single); if (!string.IsNullOrEmpty(strError)) { - Errors.Add(Localization.Localization.GetString("FcnMode", LocalInstallResourceFile) + ": " + strError); + this.Errors.Add(Localization.GetString("FcnMode", this.LocalInstallResourceFile) + ": " + strError); Logger.TraceFormat("Adding FcnMode : {0}", strError); } - Status = Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs index 61b376ae47f..a23b5d31c12 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs @@ -1,87 +1,72 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System; + using System.Collections.Generic; + /// ----------------------------------------------------------------------------- /// - /// BaseInstallationStep - Abstract class to perform common tasks for the various installation steps + /// BaseInstallationStep - Abstract class to perform common tasks for the various installation steps. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public abstract class BaseInstallationStep : IInstallationStep - { - #region Protected - + { protected string LocalInstallResourceFile = "~/Install/App_LocalResources/InstallWizard.aspx.resx"; - protected string LocalUpgradeResourceFile = "~/Install/App_LocalResources/UpgradeWizard.aspx.resx"; - - #endregion - - #region Private - - private string _details = string.Empty; - - #endregion - + protected string LocalUpgradeResourceFile = "~/Install/App_LocalResources/UpgradeWizard.aspx.resx"; + private string _details = string.Empty; + protected BaseInstallationStep() { - Percentage = 0; - Errors = new List(); - } - - #region Implementation of IInstallationStep + this.Percentage = 0; + this.Errors = new List(); + } /// - /// Any details of the task while it's executing - /// + /// This event gets fired when any activity gets recorded + /// + public event ActivityEventHandler Activity; + + /// + /// Gets or sets any details of the task while it's executing. + /// public string Details { get { - return _details; + return this._details; } + set { - _details = value; - DnnInstallLogger.InstallLogInfo(_details); - if (Activity != null) - Activity(_details); + this._details = value; + DnnInstallLogger.InstallLogInfo(this._details); + if (this.Activity != null) + { + this.Activity(this._details); + } } } /// - /// Percentage done - /// + /// Gets or sets percentage done. + /// public int Percentage { get; set; } /// - /// Step Status - /// + /// Gets or sets step Status. + /// public StepStatus Status { get; set; } /// - /// List of Errors - /// + /// Gets or sets list of Errors. + /// public IList Errors { get; set; } /// - /// Main method to execute the step - /// - public abstract void Execute(); - - /// - /// This event gets fired when any activity gets recorded + /// Main method to execute the step. /// - public event ActivityEventHandler Activity; - - #endregion + public abstract void Execute(); } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs index aa2b8c5e674..6959aa1ce05 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs @@ -1,60 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Upgrade.Internals.Steps; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// FilePermissionCheck - Step that performs file permission checks prior to installation + /// FilePermissionCheck - Step that performs file permission checks prior to installation. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class FilePermissionCheckStep : BaseInstallationStep { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FilePermissionCheckStep)); - #region Implementation of IInstallationStep - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FilePermissionCheckStep)); + /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; var verifiers = new List { new FileSystemPermissionVerifier(HttpContext.Current.Server.MapPath("~")), - new FileSystemPermissionVerifier(HttpContext.Current.Server.MapPath("~/App_Data")) + new FileSystemPermissionVerifier(HttpContext.Current.Server.MapPath("~/App_Data")), }; - Details = Localization.Localization.GetString("FolderCreateCheck", LocalInstallResourceFile) - + Localization.Localization.GetString("FileCreateCheck", LocalInstallResourceFile) - + Localization.Localization.GetString("FileDeleteCheck", LocalInstallResourceFile) - + Localization.Localization.GetString("FolderDeleteCheck", LocalInstallResourceFile); - Logger.TraceFormat("FilePermissionCheck - {0}", Details); - - if (!verifiers.All(v => v.VerifyAll())) - Errors.Add(string.Format(Localization.Localization.GetString("StepFailed", LocalInstallResourceFile), Details)); - Percentage = 100; - - Status = Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - Logger.TraceFormat("FilePermissionCheck Status - {0}", Status); - } - - #endregion + this.Details = Localization.GetString("FolderCreateCheck", this.LocalInstallResourceFile) + + Localization.GetString("FileCreateCheck", this.LocalInstallResourceFile) + + Localization.GetString("FileDeleteCheck", this.LocalInstallResourceFile) + + Localization.GetString("FolderDeleteCheck", this.LocalInstallResourceFile); + Logger.TraceFormat("FilePermissionCheck - {0}", this.Details); + + if (!verifiers.All(v => v.VerifyAll())) + { + this.Errors.Add(string.Format(Localization.GetString("StepFailed", this.LocalInstallResourceFile), this.Details)); + } + + this.Percentage = 100; + + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + Logger.TraceFormat("FilePermissionCheck Status - {0}", this.Status); + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs index 7c59b2b5265..d49c47da736 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs @@ -1,13 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Microsoft.Win32; -using System; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System; + using System.Web; + + using Microsoft.Win32; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// /// Performs verifications about the IIS environment. /// @@ -18,27 +21,27 @@ public class IISVerificationStep : BaseInstallationStep /// public override void Execute() { - Status = StepStatus.Running; + this.Status = StepStatus.Running; - Details = Localization.Localization.GetString("CheckingIIS", LocalInstallResourceFile); + this.Details = Localization.GetString("CheckingIIS", this.LocalInstallResourceFile); // Checks for integrated pipeline mode. if (!HttpRuntime.UsingIntegratedPipeline) { - Errors.Add(Localization.Localization.GetString("IISVerificationFail", LocalInstallResourceFile)); - Status = StepStatus.Abort; + this.Errors.Add(Localization.GetString("IISVerificationFail", this.LocalInstallResourceFile)); + this.Status = StepStatus.Abort; return; } // Check for .Net Framework 4.7.2 if (!IsDotNetVersionAtLeast(461808)) { - Errors.Add(Localization.Localization.GetString("DotNetVersion472Required", LocalInstallResourceFile)); - Status = StepStatus.Abort; + this.Errors.Add(Localization.GetString("DotNetVersion472Required", this.LocalInstallResourceFile)); + this.Status = StepStatus.Abort; return; } - Status = StepStatus.Done; + this.Status = StepStatus.Done; } private static bool IsDotNetVersionAtLeast(int version) diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs index f45fa5212a0..ba644bbd198 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs @@ -1,69 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.Steps { - + using System; + using System.Collections.Generic; + /// - /// This event gets fired when any activity gets recorded + /// This event gets fired when any activity gets recorded. /// public delegate void ActivityEventHandler(string status); /// - /// Interface for an Installation Step + /// Interface for an Installation Step. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public interface IInstallationStep - { - #region Properties - + { /// - /// Any details of the task while it's executing - /// + /// This event gets fired when any activity gets recorded + /// + event ActivityEventHandler Activity; + + /// + /// Gets any details of the task while it's executing. + /// string Details { get; } /// - /// Percentage done - /// + /// Gets percentage done. + /// int Percentage { get; } /// - /// Step Status - /// + /// Gets step Status. + /// StepStatus Status { get; } /// - /// List of Errors - /// - IList Errors { get; } - - #endregion - - #region Methods - - /// - /// Main method to execute the step - /// - void Execute(); - - #endregion - - #region Events - + /// Gets list of Errors. + /// + IList Errors { get; } + /// - /// This event gets fired when any activity gets recorded + /// Main method to execute the step. /// - event ActivityEventHandler Activity; - - #endregion - + void Execute(); } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs index cffd8e4de8d..e2518f0bb4e 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs @@ -1,54 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.Steps; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// InstallSuperUserStep - Step that installs SuperUser Account + /// InstallSuperUserStep - Step that installs SuperUser Account. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class InitializeHostSettingsStep : BaseInstallationStep - { - #region Implementation of IInstallationStep - + { /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; - Details = Localization.Localization.GetString("InitHostSetting", LocalInstallResourceFile); + this.Details = Localization.GetString("InitHostSetting", this.LocalInstallResourceFile); var installConfig = InstallController.Instance.GetInstallConfig(); - //if any super user (even deleted) is found - exit + // if any super user (even deleted) is found - exit var superUsers = UserController.GetUsers(true, true, Null.NullInteger); if (superUsers != null && superUsers.Count > 0) { - Details = "..."; - Status = StepStatus.Done; + this.Details = "..."; + this.Status = StepStatus.Done; return; } - //Need to clear the cache to pick up new HostSettings from the SQLDataProvider script + // Need to clear the cache to pick up new HostSettings from the SQLDataProvider script DataCache.RemoveCache(DataCache.HostSettingsCacheKey); string domainName = Globals.GetDomainName(HttpContext.Current.Request); @@ -64,6 +59,7 @@ public override void Execute() { settingValue = domainName; } + break; case "HostEmail": if (string.IsNullOrEmpty(settingValue)) @@ -73,15 +69,14 @@ public override void Execute() break; } + HostController.Instance.Update(settingName, settingValue, setting.IsSecure); } - //Synchronise Host Folder - FolderManager.Instance.Synchronize(Null.NullInteger, "", true, true); - - Status = StepStatus.Done; - } + // Synchronise Host Folder + FolderManager.Instance.Synchronize(Null.NullInteger, string.Empty, true, true); - #endregion + this.Status = StepStatus.Done; + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs index a24f882293b..995a35e940f 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs @@ -1,38 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.Steps; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// InstallDatabaseStep - Step that installs Database + /// InstallDatabaseStep - Step that installs Database. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class InstallDatabaseStep : BaseInstallationStep - { - #region Implementation of IInstallationStep - + { /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; var counter = 0; const int totalSteps = 6; @@ -42,7 +38,7 @@ public override void Execute() var installConfig = InstallController.Instance.GetInstallConfig(); var providerPath = DataProvider.Instance().GetProviderPath(); - //Step 1 - Install Base Database. Only when it's not already installed. Globals.DataBaseVersion is null when SPs are not present + // Step 1 - Install Base Database. Only when it's not already installed. Globals.DataBaseVersion is null when SPs are not present if (Globals.DataBaseVersion == null) { var defaultProvider = Config.GetDefaultProvider("data").Name; @@ -51,128 +47,134 @@ public override void Execute() foreach (var script in installConfig.Scripts) { var scriptFile = providerPath + script + "." + defaultProvider; - var description = Localization.Localization.GetString("InstallingDataBaseScriptStep", LocalInstallResourceFile); - Details = description + Upgrade.GetFileNameWithoutExtension(scriptFile); + var description = Localization.GetString("InstallingDataBaseScriptStep", this.LocalInstallResourceFile); + this.Details = description + Upgrade.GetFileNameWithoutExtension(scriptFile); var exception = Upgrade.ExecuteScript(scriptFile, false); if (!string.IsNullOrEmpty(exception)) { - Errors.Add(exception); - Status = StepStatus.Retry; - return; + this.Errors.Add(exception); + this.Status = StepStatus.Retry; + return; } - Percentage += percentForMiniStep; + + this.Percentage += percentForMiniStep; } // update the version Globals.UpdateDataBaseVersion(new Version(installConfig.Version)); - Details = Localization.Localization.GetString("InstallingMembershipDatabaseScriptStep", LocalInstallResourceFile); - //Optionally Install the memberRoleProvider + this.Details = Localization.GetString("InstallingMembershipDatabaseScriptStep", this.LocalInstallResourceFile); + + // Optionally Install the memberRoleProvider var exceptions = Upgrade.InstallMemberRoleProvider(providerPath, false); - if (!string.IsNullOrEmpty(exceptions)) - { - Errors.Add(exceptions); - Status = StepStatus.Retry; - return; - } + if (!string.IsNullOrEmpty(exceptions)) + { + this.Errors.Add(exceptions); + this.Status = StepStatus.Retry; + return; + } } - Percentage = percentForEachStep * counter++; + + this.Percentage = percentForEachStep * counter++; - //Step 2 - Process the Upgrade Script files + // Step 2 - Process the Upgrade Script files var versions = new List(); var scripts = Upgrade.GetUpgradeScripts(providerPath, DataProvider.Instance().GetVersion()); if (scripts.Count > 0) { - percentForMiniStep = percentForEachStep/(scripts.Count); + percentForMiniStep = percentForEachStep / scripts.Count; foreach (string scriptFile in scripts) { var fileName = Upgrade.GetFileNameWithoutExtension(scriptFile); var version = new Version(fileName); - string description = Localization.Localization.GetString("ProcessingUpgradeScript", LocalInstallResourceFile); - Details = description + fileName; + string description = Localization.GetString("ProcessingUpgradeScript", this.LocalInstallResourceFile); + this.Details = description + fileName; bool scriptExecuted; - var exceptions = Upgrade.UpgradeVersion(scriptFile, false, out scriptExecuted); - if (!string.IsNullOrEmpty(exceptions)) - { - Errors.Add(exceptions); - Status = StepStatus.Retry; - return; - } + var exceptions = Upgrade.UpgradeVersion(scriptFile, false, out scriptExecuted); + if (!string.IsNullOrEmpty(exceptions)) + { + this.Errors.Add(exceptions); + this.Status = StepStatus.Retry; + return; + } if (scriptExecuted) { versions.Add(version); } - Percentage += percentForMiniStep; + this.Percentage += percentForMiniStep; } } - Percentage = percentForEachStep * counter++; + + this.Percentage = percentForEachStep * counter++; - //Step 3 - Perform version specific application upgrades + // Step 3 - Perform version specific application upgrades foreach (Version ver in versions) { - string description = Localization.Localization.GetString("UpgradingVersionApplication", LocalInstallResourceFile); - Details = description + ver; + string description = Localization.GetString("UpgradingVersionApplication", this.LocalInstallResourceFile); + this.Details = description + ver; var exceptions = Upgrade.UpgradeApplication(providerPath, ver, false); - if (!string.IsNullOrEmpty(exceptions)) - { - Errors.Add(exceptions); - Status = StepStatus.Retry; - return; - } - Percentage += percentForMiniStep; + if (!string.IsNullOrEmpty(exceptions)) + { + this.Errors.Add(exceptions); + this.Status = StepStatus.Retry; + return; + } + + this.Percentage += percentForMiniStep; } - Percentage = percentForEachStep * counter++; - - - //Step 4 - Execute config file updates - foreach (Version ver in versions) - { - string description = Localization.Localization.GetString("UpdatingConfigFile", LocalInstallResourceFile); - Details = description + ver; - var exceptions = Upgrade.UpdateConfig(providerPath, ver, false); - if (!string.IsNullOrEmpty(exceptions)) - { - Errors.Add(exceptions); - Status = StepStatus.Retry; - return; - } - Percentage += percentForMiniStep; - } - Percentage = percentForEachStep * counter++; - - //Step 5 - Delete files which are no longer used + + this.Percentage = percentForEachStep * counter++; + + // Step 4 - Execute config file updates foreach (Version ver in versions) { - string description = Localization.Localization.GetString("DeletingOldFiles", LocalInstallResourceFile); - Details = description + ver; + string description = Localization.GetString("UpdatingConfigFile", this.LocalInstallResourceFile); + this.Details = description + ver; + var exceptions = Upgrade.UpdateConfig(providerPath, ver, false); + if (!string.IsNullOrEmpty(exceptions)) + { + this.Errors.Add(exceptions); + this.Status = StepStatus.Retry; + return; + } + + this.Percentage += percentForMiniStep; + } + + this.Percentage = percentForEachStep * counter++; + + // Step 5 - Delete files which are no longer used + foreach (Version ver in versions) + { + string description = Localization.GetString("DeletingOldFiles", this.LocalInstallResourceFile); + this.Details = description + ver; var exceptions = Upgrade.DeleteFiles(providerPath, ver, false); - if (!string.IsNullOrEmpty(exceptions)) - { - Errors.Add(exceptions); - Status = StepStatus.Retry; - return; - } - Percentage += percentForMiniStep; + if (!string.IsNullOrEmpty(exceptions)) + { + this.Errors.Add(exceptions); + this.Status = StepStatus.Retry; + return; + } + + this.Percentage += percentForMiniStep; } - Percentage = percentForEachStep * counter++; + + this.Percentage = percentForEachStep * counter++; - //Step 6 - Perform general application upgrades - Details = Localization.Localization.GetString("UpgradingNormalApplication", LocalInstallResourceFile); + // Step 6 - Perform general application upgrades + this.Details = Localization.GetString("UpgradingNormalApplication", this.LocalInstallResourceFile); Upgrade.UpgradeApplication(); - //Step 7 - Save Accept DNN Terms flag + // Step 7 - Save Accept DNN Terms flag HostController.Instance.Update("AcceptDnnTerms", "Y"); DataCache.ClearHostCache(true); - Percentage = percentForEachStep * counter++; - - Status = Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - } - - #endregion + this.Percentage = percentForEachStep * counter++; + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs index 9196404c265..b717c209c6e 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs @@ -1,44 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + using System.IO; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Upgrade.Internals.Steps; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// InstallExtensionsStep - Step that installs all the Extensions + /// InstallExtensionsStep - Step that installs all the Extensions. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class InstallExtensionsStep : BaseInstallationStep { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (InstallExtensionsStep)); - #region Implementation of IInstallationStep - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InstallExtensionsStep)); + /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { var packages = Upgrade.GetInstallPackages(); if (packages.Count == 0) { - Percentage = 100; - Status = StepStatus.Done; + this.Percentage = 100; + this.Status = StepStatus.Done; return; } - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; var percentForEachStep = 100 / packages.Count; var counter = 0; @@ -46,20 +43,20 @@ public override void Execute() { var file = package.Key; var packageType = package.Value.PackageType; - var message = string.Format(Localization.Localization.GetString("InstallingExtension", LocalInstallResourceFile), packageType, Path.GetFileName(file)); - Details = message; - Logger.Trace(Details); + var message = string.Format(Localization.GetString("InstallingExtension", this.LocalInstallResourceFile), packageType, Path.GetFileName(file)); + this.Details = message; + Logger.Trace(this.Details); var success = Upgrade.InstallPackage(file, packageType, false); if (!success) { - Errors.Add(message); + this.Errors.Add(message); break; } - Percentage = percentForEachStep * counter++; + + this.Percentage = percentForEachStep * counter++; } - Status = Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - } - - #endregion + + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs index e51dcd94a88..5a6c92759f7 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs @@ -1,107 +1,97 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + using System.IO; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; + using DotNetNuke.Services.Upgrade.Internals.Steps; + /// ----------------------------------------------------------------------------- /// - /// InstallSiteStep - Step that installs Website + /// InstallSiteStep - Step that installs Website. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class InstallSiteStep : BaseInstallationStep - { - #region Implementation of IInstallationStep - + { /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; - - - //Set Status to None + this.Percentage = 0; + this.Status = StepStatus.Running; + + // Set Status to None Globals.SetStatus(Globals.UpgradeStatus.None); - - + var installConfig = InstallController.Instance.GetInstallConfig(); var percentForEachStep = 100 / installConfig.Portals.Count; var counter = 0; foreach (var portal in installConfig.Portals) { - string description = Localization.Localization.GetString("CreatingSite", LocalInstallResourceFile); - Details = string.Format(description, portal.PortalName); - CreateSite(portal, installConfig); + string description = Localization.GetString("CreatingSite", this.LocalInstallResourceFile); + this.Details = string.Format(description, portal.PortalName); + this.CreateSite(portal, installConfig); counter++; - Percentage = percentForEachStep * counter++; + this.Percentage = percentForEachStep * counter++; } Globals.ResetAppStartElapseTime(); - Status = StepStatus.Done; - } - - #endregion - - #region Private Methods - + this.Status = StepStatus.Done; + } + private void CreateSite(PortalConfig portal, InstallConfig installConfig) { - - var domain = ""; - if ((HttpContext.Current != null)) + var domain = string.Empty; + if (HttpContext.Current != null) { - domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install/launchautoinstall", "").Replace("/install", "").Replace("/runinstall", ""); + domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install/launchautoinstall", string.Empty).Replace("/install", string.Empty).Replace("/runinstall", string.Empty); } var serverPath = Globals.ApplicationMapPath + "\\"; - //Get the Portal Alias + // Get the Portal Alias var portalAlias = domain; - if (portal.PortAliases.Count > 0) portalAlias = portal.PortAliases[0]; - - //Verify that portal alias is not present + if (portal.PortAliases.Count > 0) + { + portalAlias = portal.PortAliases[0]; + } + + // Verify that portal alias is not present if (PortalAliasController.Instance.GetPortalAlias(portalAlias.ToLowerInvariant()) != null) { - string description = Localization.Localization.GetString("SkipCreatingSite", LocalInstallResourceFile); - Details = string.Format(description, portalAlias); + string description = Localization.GetString("SkipCreatingSite", this.LocalInstallResourceFile); + this.Details = string.Format(description, portalAlias); return; } - //Create default email + // Create default email var email = portal.AdminEmail; if (string.IsNullOrEmpty(email)) { - email = "admin@" + domain.Replace("www.", ""); - //Remove any domain subfolder information ( if it exists ) + email = "admin@" + domain.Replace("www.", string.Empty); + + // Remove any domain subfolder information ( if it exists ) if (email.IndexOf("/") != -1) { email = email.Substring(0, email.IndexOf("/")); } } - //install LP if installing in a different language + // install LP if installing in a different language string culture = installConfig.InstallCulture; if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { @@ -112,49 +102,57 @@ private void CreateSite(PortalConfig portal, InstallConfig installConfig) { if (!Upgrade.InstallPackage(lpFilePath, "Language", false)) { - culture = Localization.Localization.SystemLocale; + culture = Localization.SystemLocale; } } else { - culture = Localization.Localization.SystemLocale; + culture = Localization.SystemLocale; } } var template = Upgrade.FindBestTemplate(portal.TemplateFileName, culture); UserInfo userInfo; - if (!String.IsNullOrEmpty(portal.AdminUserName)) - userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); - else - userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); - + if (!string.IsNullOrEmpty(portal.AdminUserName)) + { + userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); + } + else + { + userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); + } + var childPath = string.Empty; - if (portal.IsChild) - childPath = portalAlias.Substring(portalAlias.LastIndexOf("/") + 1); - - //Create Folder Mappings config - if (!String.IsNullOrEmpty(installConfig.FolderMappingsSettings)) + if (portal.IsChild) + { + childPath = portalAlias.Substring(portalAlias.LastIndexOf("/") + 1); + } + + // Create Folder Mappings config + if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) { FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); } - //add item to identity install from install wizard. + + // add item to identity install from install wizard. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("InstallFromWizard", true); } - //Create Portal - var portalId = PortalController.Instance.CreatePortal(portal.PortalName, - userInfo, - portal.Description, - portal.Keywords, - template, - portal.HomeDirectory, - portalAlias, - serverPath, - serverPath + childPath, - portal.IsChild); + // Create Portal + var portalId = PortalController.Instance.CreatePortal( + portal.PortalName, + userInfo, + portal.Description, + portal.Keywords, + template, + portal.HomeDirectory, + portalAlias, + serverPath, + serverPath + childPath, + portal.IsChild); if (portalId > -1) { @@ -164,30 +162,27 @@ private void CreateSite(PortalConfig portal, InstallConfig installConfig) } } - //remove en-US from portal if installing in a different language + // remove en-US from portal if installing in a different language if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { var locale = LocaleController.Instance.GetLocale("en-US"); - Localization.Localization.RemoveLanguageFromPortal(portalId, locale.LanguageId, true); + Localization.RemoveLanguageFromPortal(portalId, locale.LanguageId, true); } - //Log user in to site + // Log user in to site var loginStatus = UserLoginStatus.LOGIN_FAILURE; - UserController.UserLogin(portalId, userInfo.Username, installConfig.SuperUser.Password, "", "", "", ref loginStatus, false); + UserController.UserLogin(portalId, userInfo.Username, installConfig.SuperUser.Password, string.Empty, string.Empty, string.Empty, ref loginStatus, false); InstallController.Instance.RemoveFromInstallConfig("//dotnetnuke/superuser/password"); - } - - //private void CreateFolderMappingConfig(string folderMappinsSettings) - //{ - // string folderMappingsConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); - // if (!File.Exists(folderMappingsConfigPath)) - // { - // File.AppendAllText(folderMappingsConfigPath, "" + folderMappinsSettings + ""); - // } - //} - - #endregion - + } + + // private void CreateFolderMappingConfig(string folderMappinsSettings) + // { + // string folderMappingsConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); + // if (!File.Exists(folderMappingsConfigPath)) + // { + // File.AppendAllText(folderMappingsConfigPath, "" + folderMappinsSettings + ""); + // } + // } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs index ff36424839c..d87486ba9f3 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs @@ -1,75 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.Steps; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// - /// InstallSuperUserStep - Step that installs SuperUser Account + /// InstallSuperUserStep - Step that installs SuperUser Account. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class InstallSuperUserStep : BaseInstallationStep - { - #region Implementation of IInstallationStep - + { /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; - Details = Localization.Localization.GetString("CreateSuperUser", LocalInstallResourceFile); + this.Details = Localization.GetString("CreateSuperUser", this.LocalInstallResourceFile); var installConfig = InstallController.Instance.GetInstallConfig(); - //if any super user (even deleted) is found - exit + // if any super user (even deleted) is found - exit var superUsers = UserController.GetUsers(true, true, Null.NullInteger); if (superUsers != null && superUsers.Count > 0) { - Details = "..."; - Status = StepStatus.Done; + this.Details = "..."; + this.Status = StepStatus.Done; return; } - //Set admin user to be a superuser + // Set admin user to be a superuser var adminSuperUser = UserController.GetUserByName(0, installConfig.SuperUser.UserName); if (adminSuperUser != null) { adminSuperUser.IsSuperUser = true; adminSuperUser.Membership.UpdatePassword = false; - //refresh the profile to get definitions for super user. - adminSuperUser.Profile = null; - adminSuperUser.Profile.PreferredLocale = installConfig.SuperUser.Locale; - adminSuperUser.Profile.PreferredTimeZone = TimeZoneInfo.Local; + + // refresh the profile to get definitions for super user. + adminSuperUser.Profile = null; + adminSuperUser.Profile.PreferredLocale = installConfig.SuperUser.Locale; + adminSuperUser.Profile.PreferredTimeZone = TimeZoneInfo.Local; UserController.UpdateUser(0, adminSuperUser); } else { - //Construct UserInfo object - var superUser = new UserInfo - { - PortalID = -1, - FirstName = installConfig.SuperUser.FirstName, - LastName = installConfig.SuperUser.LastName, - Username = installConfig.SuperUser.UserName, - DisplayName = installConfig.SuperUser.FirstName + " " + installConfig.SuperUser.LastName, - Membership = {Password = installConfig.SuperUser.Password}, - Email = installConfig.SuperUser.Email, - IsSuperUser = true - }; + // Construct UserInfo object + var superUser = new UserInfo + { + PortalID = -1, + FirstName = installConfig.SuperUser.FirstName, + LastName = installConfig.SuperUser.LastName, + Username = installConfig.SuperUser.UserName, + DisplayName = installConfig.SuperUser.FirstName + " " + installConfig.SuperUser.LastName, + Membership = { Password = installConfig.SuperUser.Password }, + Email = installConfig.SuperUser.Email, + IsSuperUser = true, + }; superUser.Membership.Approved = true; superUser.Profile.FirstName = installConfig.SuperUser.FirstName; @@ -77,17 +73,17 @@ public override void Execute() superUser.Profile.PreferredLocale = installConfig.SuperUser.Locale; superUser.Profile.PreferredTimeZone = TimeZoneInfo.Local; superUser.Membership.UpdatePassword = false; - - //Create SuperUser if not present - if (UserController.GetUserByName(superUser.PortalID, superUser.Username) == null) - UserController.CreateUser(ref superUser); - } - Details = Localization.Localization.GetString("CreatingSuperUser", LocalInstallResourceFile) + installConfig.SuperUser.UserName; + // Create SuperUser if not present + if (UserController.GetUserByName(superUser.PortalID, superUser.Username) == null) + { + UserController.CreateUser(ref superUser); + } + } - Status = StepStatus.Done; - } + this.Details = Localization.GetString("CreatingSuperUser", this.LocalInstallResourceFile) + installConfig.SuperUser.UserName; - #endregion + this.Status = StepStatus.Done; + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs index 67d09e502a2..8b5bb30308b 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs @@ -1,28 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Instrumentation; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ------------------------------------------------------------------------------------------------ /// - /// DatabaseVerificationStep - Step that performs database verification checks prior to installation + /// DatabaseVerificationStep - Step that performs database verification checks prior to installation. /// - /// ------------------------------------------------------------------------------------------------ + /// ------------------------------------------------------------------------------------------------ public class InstallVersionStep : BaseInstallationStep { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InstallVersionStep)); public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; var databaseVersion = DataProvider.Instance().GetInstallVersion(); @@ -30,11 +32,11 @@ public override void Execute() if (!string.IsNullOrEmpty(strError)) { - Errors.Add(Localization.Localization.GetString("InstallVersion", LocalInstallResourceFile) + ": " + strError); + this.Errors.Add(Localization.GetString("InstallVersion", this.LocalInstallResourceFile) + ": " + strError); Logger.TraceFormat("Adding InstallVersion : {0}", strError); } - Status = Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/StepStatus.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/StepStatus.cs index 95ee23db2b1..a506aa06a2d 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/StepStatus.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/StepStatus.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System; + /// - /// Status of an Installation Step + /// Status of an Installation Step. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public enum StepStatus { /// @@ -27,7 +22,7 @@ public enum StepStatus Running = 1, /// - /// Step is done and was successful. + /// Step is done and was successful. /// Done = 2, @@ -44,6 +39,6 @@ public enum StepStatus /// /// Step resulted in Application Restart. You should redirect to the same page. /// - AppRestart = 5 + AppRestart = 5, } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs index 54c853412e9..3690dab6314 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs @@ -1,81 +1,87 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.Steps; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- /// /// SynchConnectionStringStep - Step that synchs connection string between DotNetNuke.Install.Config and Web.Config /// The connection information stored in DotNetNuke.Install.Config takes precendence (if present) - /// Synchornization only happens when settings are different + /// Synchornization only happens when settings are different. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class SynchConnectionStringStep : BaseInstallationStep - { - #region Implementation of IInstallationStep - + { /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; var installConfig = InstallController.Instance.GetInstallConfig(); - if(installConfig == null) + if (installConfig == null) { - Status = StepStatus.Done; + this.Status = StepStatus.Done; return; } var connectionConfig = installConfig.Connection; if (connectionConfig == null) { - Status = StepStatus.Done; + this.Status = StepStatus.Done; return; } if (string.IsNullOrEmpty(connectionConfig.File) && string.IsNullOrEmpty(connectionConfig.Database)) - { - Errors.Add(Localization.Localization.GetString("RequiresFileOrDatabase", LocalInstallResourceFile)); - Status = StepStatus.Abort; + { + this.Errors.Add(Localization.GetString("RequiresFileOrDatabase", this.LocalInstallResourceFile)); + this.Status = StepStatus.Abort; return; } var builder = DataProvider.Instance().GetConnectionStringBuilder(); - - if (!string.IsNullOrEmpty(connectionConfig.Server)) - builder["Data Source"] = connectionConfig.Server; - if (!string.IsNullOrEmpty(connectionConfig.Database)) - builder["Initial Catalog"] = connectionConfig.Database; + if (!string.IsNullOrEmpty(connectionConfig.Server)) + { + builder["Data Source"] = connectionConfig.Server; + } + + if (!string.IsNullOrEmpty(connectionConfig.Database)) + { + builder["Initial Catalog"] = connectionConfig.Database; + } else if (!string.IsNullOrEmpty(connectionConfig.File)) { builder["attachdbfilename"] = "|DataDirectory|" + connectionConfig.File; builder["user instance"] = "true"; } - if (connectionConfig.Integrated) - builder["integrated security"] = "true"; - - if (!string.IsNullOrEmpty(connectionConfig.User)) - builder["uid"] = connectionConfig.User; - - if (!string.IsNullOrEmpty(connectionConfig.Password)) - builder["pwd"] = connectionConfig.Password; - + if (connectionConfig.Integrated) + { + builder["integrated security"] = "true"; + } + + if (!string.IsNullOrEmpty(connectionConfig.User)) + { + builder["uid"] = connectionConfig.User; + } + + if (!string.IsNullOrEmpty(connectionConfig.Password)) + { + builder["pwd"] = connectionConfig.Password; + } + string dbowner; if (connectionConfig.RunAsDbowner) { @@ -83,25 +89,26 @@ public override void Execute() } else { - dbowner = (string.IsNullOrEmpty(GetUpgradeConnectionStringUserID())) + dbowner = string.IsNullOrEmpty(this.GetUpgradeConnectionStringUserID()) ? connectionConfig.User + "." - : GetUpgradeConnectionStringUserID(); + : this.GetUpgradeConnectionStringUserID(); } - + var connectionString = builder.ToString(); - //load web.config connection string for comparison + // load web.config connection string for comparison var appConnectionString = Config.GetConnectionString(); var modified = false; - //save to web.config if different - if(appConnectionString.ToLower() != connectionString.ToLower()) + + // save to web.config if different + if (appConnectionString.ToLower() != connectionString.ToLower()) { Config.UpdateConnectionString(connectionString); modified = true; } - //Compare (and overwrite) Owner and Qualifier in Data Provider + // Compare (and overwrite) Owner and Qualifier in Data Provider if (Config.GetDataBaseOwner().ToLower() != dbowner.ToLower() || (Config.GetObjectQualifer().ToLower() != connectionConfig.Qualifier.ToLower())) { @@ -109,26 +116,22 @@ public override void Execute() modified = true; } - //Compare (and overwrite) Owner and Qualifier in Data Provider + // Compare (and overwrite) Owner and Qualifier in Data Provider if (!string.IsNullOrEmpty(connectionConfig.UpgradeConnectionString) && Config.GetUpgradeConnectionString().ToLower() != connectionConfig.UpgradeConnectionString.ToLower()) { Config.UpdateUpgradeConnectionString("SqlDataProvider", connectionConfig.UpgradeConnectionString); modified = true; } - Status = modified ? StepStatus.AppRestart : StepStatus.Done; - } - - #endregion - - #region Private Methods - + this.Status = modified ? StepStatus.AppRestart : StepStatus.Done; + } + private string GetUpgradeConnectionStringUserID() { - string dbUser = ""; + string dbUser = string.Empty; string connection = Config.GetUpgradeConnectionString(); - //If connection string does not use integrated security, then get user id. + // If connection string does not use integrated security, then get user id. if (connection.ToLowerInvariant().Contains("user id") || connection.ToLowerInvariant().Contains("uid") || connection.ToLowerInvariant().Contains("user")) { string[] connectionParams = connection.Split(';'); @@ -147,9 +150,8 @@ private string GetUpgradeConnectionStringUserID() } } } + return dbUser; - } - - #endregion + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs index 22804190c4c..df952e0c1ba 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs @@ -1,71 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.Configuration; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.Steps; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + using System.Web; + using System.Web.Configuration; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.Steps; + /// ----------------------------------------------------------------------------- /// - /// UpdateLanguagePackStep - Step that downloads and installs language pack + /// UpdateLanguagePackStep - Step that downloads and installs language pack. /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class UpdateLanguagePackStep : BaseInstallationStep { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UpdateLanguagePackStep)); - #region Implementation of IInstallationStep - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UpdateLanguagePackStep)); + /// - /// Main method to execute the step - /// + /// Main method to execute the step. + /// public override void Execute() { - Percentage = 0; - Status = StepStatus.Running; + this.Percentage = 0; + this.Status = StepStatus.Running; var installConfig = InstallController.Instance.GetInstallConfig(); string culture = installConfig.InstallCulture; - + if (culture.ToLowerInvariant() != "en-us") { - try - { - //need apply the Licensing module after packages installed, so that we can know whats the edition of install instance. CE/PE/EE - var document = Config.Load(); - var licensingNode = document.SelectSingleNode("/configuration/system.webServer/modules/add[@name='Licensing']"); - if (licensingNode != null) - { - var type = licensingNode.Attributes["type"].Value; - var module = Reflection.CreateObject(type, null, false) as IHttpModule; - module.Init(HttpContext.Current.ApplicationInstance); - } - - InstallController.Instance.IsAvailableLanguagePack(culture); - } - catch (Exception ex) - { - //we shouldn't break the install process when LP download failed, for admin user can install the LP after website created. - //so we logged what's wrong here, and user can check it later. - Logger.Error(ex); - } - + try + { + // need apply the Licensing module after packages installed, so that we can know whats the edition of install instance. CE/PE/EE + var document = Config.Load(); + var licensingNode = document.SelectSingleNode("/configuration/system.webServer/modules/add[@name='Licensing']"); + if (licensingNode != null) + { + var type = licensingNode.Attributes["type"].Value; + var module = Reflection.CreateObject(type, null, false) as IHttpModule; + module.Init(HttpContext.Current.ApplicationInstance); + } + + InstallController.Instance.IsAvailableLanguagePack(culture); + } + catch (Exception ex) + { + // we shouldn't break the install process when LP download failed, for admin user can install the LP after website created. + // so we logged what's wrong here, and user can check it later. + Logger.Error(ex); + } } - Status = StepStatus.Done; - } - - #endregion + + this.Status = StepStatus.Done; + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs b/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs index 337f7340d46..039bac46d3d 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs @@ -1,39 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Net; - -using DotNetNuke.Application; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Upgrade.Internals { + using System; + using System.IO; + using System.Net; + + using DotNetNuke.Application; + using DotNetNuke.Common; + public class UpdateService { - private static String ApplicationVersion + private static string ApplicationVersion { get { var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; - return Globals.FormatVersion(version, "00", 3, ""); + return Globals.FormatVersion(version, "00", 3, string.Empty); } } - private static String ApplicationName + private static string ApplicationName { get { return DotNetNukeContext.Current.Application.Name; } } - - + public static StreamReader GetLanguageList() { - String url = DotNetNukeContext.Current.Application.UpgradeUrl + "/languages.aspx"; + string url = DotNetNukeContext.Current.Application.UpgradeUrl + "/languages.aspx"; url += "?core=" + ApplicationVersion; url += "&type=Framework"; url += "&name=" + ApplicationName; @@ -42,9 +41,9 @@ public static StreamReader GetLanguageList() return myResponseReader; } - public static String GetLanguageDownloadUrl(String cultureCode) + public static string GetLanguageDownloadUrl(string cultureCode) { - String url = DotNetNukeContext.Current.Application.UpgradeUrl + "/languages.aspx"; + string url = DotNetNukeContext.Current.Application.UpgradeUrl + "/languages.aspx"; url += "?core=" + ApplicationVersion; url += "&type=Framework"; url += "&name=" + ApplicationName; @@ -57,22 +56,22 @@ public static String GetLanguageDownloadUrl(String cultureCode) private static StreamReader GetResponseAsStream(string url) { - //creating the proxy for the service call using the HttpWebRequest class - var webReq = (HttpWebRequest) WebRequest.Create(url); + // creating the proxy for the service call using the HttpWebRequest class + var webReq = (HttpWebRequest)WebRequest.Create(url); - //Set the method/action type + // Set the method/action type webReq.Method = "GET"; - //We use form contentType + // We use form contentType webReq.ContentType = "text/xml; charset=utf-8"; - //Get the response handle, we have no true response yet! - var webResp = (HttpWebResponse) webReq.GetResponse(); + // Get the response handle, we have no true response yet! + var webResp = (HttpWebResponse)webReq.GetResponse(); - //Now, we read the response (the string), and output it. + // Now, we read the response (the string), and output it. Stream myResponse = webResp.GetResponseStream(); - //read the stream into streamreader + // read the stream into streamreader var myResponseReader = new StreamReader(myResponse); return myResponseReader; } diff --git a/DNN Platform/Library/Services/Upgrade/Upgrade.cs b/DNN Platform/Library/Services/Upgrade/Upgrade.cs index c76fae41d6f..ded5cc3b4a4 100644 --- a/DNN Platform/Library/Services/Upgrade/Upgrade.cs +++ b/DNN Platform/Library/Services/Upgrade/Upgrade.cs @@ -1,104 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Data.SqlClient; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using System.Web.Configuration; -using System.Xml; -using System.Xml.XPath; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Analytics; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.EventQueue.Config; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Installer; -using DotNetNuke.Services.Installer.Dependencies; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Localization.Internal; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Search; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Services.Upgrade.InternalController.Steps; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.Steps; -using DotNetNuke.UI.Internals; - -using ICSharpCode.SharpZipLib.Zip; - -using Assembly = System.Reflection.Assembly; -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; -using ModuleInfo = DotNetNuke.Entities.Modules.ModuleInfo; -using Util = DotNetNuke.Entities.Content.Common.Util; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade { - ///----------------------------------------------------------------------------- - /// + using System; + using System.Collections; + using System.Collections.Generic; + using System.Configuration; + using System.Data; + using System.Data.SqlClient; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Security.Cryptography; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Web.Configuration; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Analytics; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.EventQueue.Config; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Installer; + using DotNetNuke.Services.Installer.Dependencies; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Localization.Internal; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Search; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Services.Upgrade.InternalController.Steps; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.Steps; + using DotNetNuke.UI.Internals; + using ICSharpCode.SharpZipLib.Zip; + + using Assembly = System.Reflection.Assembly; + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + using Localization = DotNetNuke.Services.Localization.Localization; + using ModuleInfo = DotNetNuke.Entities.Modules.ModuleInfo; + using Util = DotNetNuke.Entities.Content.Common.Util; + + /// ----------------------------------------------------------------------------- + /// /// The Upgrade class provides Shared/Static methods to Upgrade/Install - /// a DotNetNuke Application - /// - /// - /// - ///----------------------------------------------------------------------------- + /// a DotNetNuke Application. + /// + /// + /// + /// ----------------------------------------------------------------------------- public class Upgrade { + private const string FipsCompilanceAssembliesCheckedKey = "FipsCompilanceAssembliesChecked"; + private const string FipsCompilanceAssembliesFolder = "App_Data\\FipsCompilanceAssemblies"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Upgrade)); private static readonly object _threadLocker = new object(); - - #region Private Shared Field - private static DateTime _startTime; - private const string FipsCompilanceAssembliesCheckedKey = "FipsCompilanceAssembliesChecked"; - private const string FipsCompilanceAssembliesFolder = "App_Data\\FipsCompilanceAssemblies"; - - #endregion - - #region Public Properties public static string DefaultProvider { @@ -117,10 +105,6 @@ public static TimeSpan RunTime } } - #endregion - - #region Private Methods - private static Version ApplicationVersion { get @@ -129,39 +113,261 @@ private static Version ApplicationVersion } } + public static int RemoveModule(string desktopModuleName, string tabName, int parentId, bool removeTab) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModule:" + desktopModuleName); + TabInfo tab = TabController.Instance.GetTabByName(tabName, Null.NullInteger, parentId); + int moduleDefId = 0; + int count = 0; + + // Get the Modules on the Tab + if (tab != null) + { + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(tab.TabID)) + { + var module = kvp.Value; + if (module.DesktopModule.FriendlyName == desktopModuleName) + { + // Delete the Module from the Modules list + ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); + moduleDefId = module.ModuleDefID; + } + else + { + count += 1; + } + } + + // If Tab has no modules optionally remove tab + if (count == 0 && removeTab) + { + TabController.Instance.DeleteTab(tab.TabID, tab.PortalID); + } + } + + return moduleDefId; + } + + public static void MakeModulePremium(string moduleName) + { + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, -1); + if (desktopModule != null) + { + desktopModule.IsAdmin = true; + desktopModule.IsPremium = true; + DesktopModuleController.SaveDesktopModule(desktopModule, false, true); + + // Remove Portal/Module to PortalDesktopModules + DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals. + /// + /// The Name to give this new Tab. + /// + /// The Icon for this new Tab. + /// + /// A flag indicating whether the tab is visible. + /// The Module Deinition Id for the module to be aded to this tab. + /// The Module's title. + /// The Module's icon. + /// Modules Inherit the Pages View Permisions. + /// ----------------------------------------------------------------------------- + public static void AddAdminPages(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) + { + ArrayList portals = PortalController.Instance.GetPortals(); + + // Add Page to Admin Menu of all configured Portals + for (var index = 0; index <= portals.Count - 1; index++) + { + var portal = (PortalInfo)portals[index]; + + // Create New Admin Page (or get existing one) + var newPage = AddAdminPage(portal, tabName, description, tabIconFile, tabIconFileLarge, isVisible); + + // Add Module To Page + AddModuleToPage(newPage, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// AddAdminPage adds an Admin Tab Page. + /// + /// The Portal. + /// The Name to give this new Tab. + /// + /// The Icon for this new Tab. + /// + /// A flag indicating whether the tab is visible. + /// + /// ----------------------------------------------------------------------------- + public static TabInfo AddAdminPage(PortalInfo portal, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminPage:" + tabName); + TabInfo adminPage = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, false); + + if (adminPage != null) + { + var tabPermissionCollection = new TabPermissionCollection(); + AddPagePermission(tabPermissionCollection, "View", Convert.ToInt32(portal.AdministratorRoleId)); + AddPagePermission(tabPermissionCollection, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); + return AddPage(adminPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible, tabPermissionCollection, true); + } + + return null; + } + + /// ----------------------------------------------------------------------------- + /// + /// ExecuteScript executes a SQl script file. + /// + /// + /// + /// The script to Execute. + /// Need to output feedback message. + /// + /// ----------------------------------------------------------------------------- + internal static string ExecuteScript(string scriptFile, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ExecutingScript", Localization.GlobalResourceFile) + ":" + Path.GetFileName(scriptFile)); + } + + // read script file for installation + string script = FileSystemUtils.ReadFile(scriptFile); + + // execute SQL installation script + string exceptions = DataProvider.Instance().ExecuteScript(script); + + // add installer logging + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); + } + + // log the results + try + { + using (var streamWriter = File.CreateText(scriptFile.Replace("." + DefaultProvider, string.Empty) + ".log.resources")) + { + streamWriter.WriteLine(exceptions); + streamWriter.Close(); + } + } + catch (Exception exc) + { + // does not have permission to create the log file + Logger.Error(exc); + } + + if (writeFeedback) + { + string resourcesFile = Path.GetFileName(scriptFile); + if (!string.IsNullOrEmpty(resourcesFile)) + { + HtmlUtils.WriteScriptSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions), resourcesFile.Replace("." + DefaultProvider, ".log.resources")); + } + } + + return exceptions; + } + /// ----------------------------------------------------------------------------- /// - /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals + /// InstallMemberRoleProvider - Installs the MemberRole Provider Db objects. /// - /// The Name to give this new Tab + /// + /// + /// The Path to the Provider Directory. + /// Whether need to output feedback message. + /// + /// ----------------------------------------------------------------------------- + internal static string InstallMemberRoleProvider(string providerPath, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); + + string exceptions = string.Empty; + + bool installMemberRole = true; + if (Config.GetSetting("InstallMemberRole") != null) + { + installMemberRole = bool.Parse(Config.GetSetting("InstallMemberRole")); + } + + if (installMemberRole) + { + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing MemberRole Provider:
    "); + } + + // Install Common + exceptions += InstallMemberRoleProviderScript(providerPath, "InstallCommon", writeFeedback); + + // Install Membership + exceptions += InstallMemberRoleProviderScript(providerPath, "InstallMembership", writeFeedback); + + // Install Profile + // exceptions += InstallMemberRoleProviderScript(providerPath, "InstallProfile", writeFeedback); + // Install Roles + // exceptions += InstallMemberRoleProviderScript(providerPath, "InstallRoles", writeFeedback); + } + + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); + } + + return exceptions; + } + + /// ----------------------------------------------------------------------------- + /// + /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals. + /// + /// The Name to give this new Tab. /// Description. - /// The Icon for this new Tab - /// The large Icon for this new Tab - /// A flag indicating whether the tab is visible - /// The Module Deinition Id for the module to be aded to this tab - /// The Module's title - /// The Module's icon + /// The Icon for this new Tab. + /// The large Icon for this new Tab. + /// A flag indicating whether the tab is visible. + /// The Module Deinition Id for the module to be aded to this tab. + /// The Module's title. + /// The Module's icon. /// ----------------------------------------------------------------------------- private static void AddAdminPages(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, int moduleDefId, string moduleTitle, string moduleIconFile) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddAdminPages:" + tabName); - //Call overload with InheritPermisions=True - AddAdminPages(tabName, description, tabIconFile, tabIconFileLarge, isVisible, moduleDefId, moduleTitle, moduleIconFile, true); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminPages:" + tabName); + // Call overload with InheritPermisions=True + AddAdminPages(tabName, description, tabIconFile, tabIconFileLarge, isVisible, moduleDefId, moduleTitle, moduleIconFile, true); } private static void AddAdminRoleToPage(string tabPath) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddAdminRoleToPage:" + tabPath); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminRoleToPage:" + tabPath); foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { int tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - if ((tabID != Null.NullInteger)) + if (tabID != Null.NullInteger) { TabInfo tab = TabController.Instance.GetTab(tabID, portal.PortalID, true); - if ((tab.TabPermissions.Count == 0)) + if (tab.TabPermissions.Count == 0) { AddPagePermission(tab.TabPermissions, "View", Convert.ToInt32(portal.AdministratorRoleId)); AddPagePermission(tab.TabPermissions, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); @@ -173,7 +379,7 @@ private static void AddAdminRoleToPage(string tabPath) private static void AddConsoleModuleSettings(int moduleID) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddConsoleModuleSettings:" + moduleID); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddConsoleModuleSettings:" + moduleID); ModuleController.Instance.UpdateModuleSetting(moduleID, "DefaultSize", "IconFileLarge"); ModuleController.Instance.UpdateModuleSetting(moduleID, "AllowSizeChange", "False"); @@ -184,7 +390,7 @@ private static void AddConsoleModuleSettings(int moduleID) private static void AddEventQueueApplicationStartFirstRequest() { - //Add new EventQueue Event + // Add new EventQueue Event var config = EventQueueConfiguration.GetConfig(); if (config != null) { @@ -202,18 +408,18 @@ private static void AddEventQueueApplicationStartFirstRequest() /// ----------------------------------------------------------------------------- /// - /// AddModuleControl adds a new Module Control to the system + /// AddModuleControl adds a new Module Control to the system. /// /// /// - /// The Module Definition Id - /// The key for this control in the Definition - /// The title of this control - /// Te source of ths control - /// The icon file - /// The type of control - /// The vieworder for this module - /// The Help Url + /// The Module Definition Id. + /// The key for this control in the Definition. + /// The title of this control. + /// Te source of ths control. + /// The icon file. + /// The type of control. + /// The vieworder for this module. + /// The Help Url. /// ----------------------------------------------------------------------------- private static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder, string helpURL) { @@ -222,7 +428,8 @@ private static void AddModuleControl(int moduleDefId, string controlKey, string private static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder, string helpURL, bool supportsPartialRendering) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddModuleControl:" + moduleDefId); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleControl:" + moduleDefId); + // check if module control exists var moduleControl = ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefId); if (moduleControl == null) @@ -238,7 +445,7 @@ private static void AddModuleControl(int moduleDefId, string controlKey, string ViewOrder = viewOrder, IconFile = iconFile, HelpURL = helpURL, - SupportsPartialRendering = supportsPartialRendering + SupportsPartialRendering = supportsPartialRendering, }; ModuleControlController.AddModuleControl(moduleControl); @@ -247,44 +454,45 @@ private static void AddModuleControl(int moduleDefId, string controlKey, string /// ----------------------------------------------------------------------------- /// - /// AddModuleDefinition adds a new Core Module Definition to the system + /// AddModuleDefinition adds a new Core Module Definition to the system. /// /// - /// This overload allows the caller to determine whether the module has a controller - /// class + /// This overload allows the caller to determine whether the module has a controller + /// class. /// - /// The Friendly Name of the Module to Add - /// Description of the Module - /// The Module Definition Name - /// A flag representing whether the module is a Premium module - /// A flag representing whether the module is an Admin module - /// The Module Definition Id of the new Module + /// The Friendly Name of the Module to Add. + /// Description of the Module. + /// The Module Definition Name. + /// A flag representing whether the module is a Premium module. + /// A flag representing whether the module is an Admin module. + /// The Module Definition Id of the new Module. /// ----------------------------------------------------------------------------- private static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName, bool premium, bool admin) { - return AddModuleDefinition(desktopModuleName, description, moduleDefinitionName, "", false, premium, admin); + return AddModuleDefinition(desktopModuleName, description, moduleDefinitionName, string.Empty, false, premium, admin); } /// ----------------------------------------------------------------------------- /// - /// AddModuleDefinition adds a new Core Module Definition to the system + /// AddModuleDefinition adds a new Core Module Definition to the system. /// /// - /// This overload allows the caller to determine whether the module has a controller - /// class + /// This overload allows the caller to determine whether the module has a controller + /// class. /// - /// The Friendly Name of the Module to Add - /// Description of the Module - /// The Module Definition Name + /// The Friendly Name of the Module to Add. + /// Description of the Module. + /// The Module Definition Name. /// Business Control Class. /// Whether the module is enable for portals. - /// A flag representing whether the module is a Premium module - /// A flag representing whether the module is an Admin module - /// The Module Definition Id of the new Module + /// A flag representing whether the module is a Premium module. + /// A flag representing whether the module is an Admin module. + /// The Module Definition Id of the new Module. /// ----------------------------------------------------------------------------- private static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName, string businessControllerClass, bool isPortable, bool premium, bool admin) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddModuleDefinition:" + desktopModuleName); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleDefinition:" + desktopModuleName); + // check if desktop module exists var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); if (desktopModule == null) @@ -298,17 +506,18 @@ private static int AddModuleDefinition(string desktopModuleName, string descript Owner = "DNN", Organization = ".NET Foundation", Url = "https://dnncommunity.org", - Email = "info@dnncommunity.org" + Email = "info@dnncommunity.org", }; if (desktopModuleName == "Extensions" || desktopModuleName == "Skin Designer") { package.IsSystemPackage = true; } + package.Version = new Version(1, 0, 0); PackageController.Instance.SaveExtensionPackage(package); - string moduleName = desktopModuleName.Replace(" ", ""); + string moduleName = desktopModuleName.Replace(" ", string.Empty); desktopModule = new DesktopModuleInfo { DesktopModuleID = Null.NullInteger, @@ -320,12 +529,13 @@ private static int AddModuleDefinition(string desktopModuleName, string descript Version = "01.00.00", BusinessControllerClass = businessControllerClass, IsPortable = isPortable, - SupportedFeatures = 0 + SupportedFeatures = 0, }; - if ((isPortable)) + if (isPortable) { desktopModule.SupportedFeatures = 1; } + desktopModule.IsPremium = premium; desktopModule.IsAdmin = admin; @@ -345,75 +555,75 @@ private static int AddModuleDefinition(string desktopModuleName, string descript moduleDefinition.ModuleDefID = ModuleDefinitionController.SaveModuleDefinition(moduleDefinition, false, false); } + return moduleDefinition.ModuleDefID; } /// ----------------------------------------------------------------------------- /// - /// AddModuleToPage adds a module to a Page + /// AddModuleToPage adds a module to a Page. /// /// - /// This overload assumes ModulePermissions will be inherited + /// This overload assumes ModulePermissions will be inherited. /// - /// The Page to add the Module to - /// The Module Deinition Id for the module to be aded to this tab - /// The Module's title - /// The Module's icon + /// The Page to add the Module to. + /// The Module Deinition Id for the module to be aded to this tab. + /// The Module's title. + /// The Module's icon. /// ----------------------------------------------------------------------------- private static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile) { - //Call overload with InheritPermisions=True + // Call overload with InheritPermisions=True return AddModuleToPage(page, moduleDefId, moduleTitle, moduleIconFile, true); } /// ----------------------------------------------------------------------------- /// - /// AddPage adds a Tab Page + /// AddPage adds a Tab Page. /// /// - /// Adds a Tab to a parentTab + /// Adds a Tab to a parentTab. /// - /// The Parent Tab - /// The Name to give this new Tab + /// The Parent Tab. + /// The Name to give this new Tab. /// Description. - /// The Icon for this new Tab - /// The Large Icon for this new Tab - /// A flag indicating whether the tab is visible - /// Page Permissions Collection for this page - /// Is an admin page + /// The Icon for this new Tab. + /// The Large Icon for this new Tab. + /// A flag indicating whether the tab is visible. + /// Page Permissions Collection for this page. + /// Is an admin page. /// ----------------------------------------------------------------------------- private static TabInfo AddPage(TabInfo parentTab, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions, bool isAdmin) { int parentId = Null.NullInteger; int portalId = Null.NullInteger; - if ((parentTab != null)) + if (parentTab != null) { parentId = parentTab.TabID; portalId = parentTab.PortalID; } - return AddPage(portalId, parentId, tabName, description, tabIconFile, tabIconFileLarge, isVisible, permissions, isAdmin); } /// ----------------------------------------------------------------------------- /// - /// AddPage adds a Tab Page + /// AddPage adds a Tab Page. /// - /// The Id of the Portal - /// The Id of the Parent Tab - /// The Name to give this new Tab + /// The Id of the Portal. + /// The Id of the Parent Tab. + /// The Name to give this new Tab. /// Description. - /// The Icon for this new Tab - /// The large Icon for this new Tab - /// A flag indicating whether the tab is visible - /// Page Permissions Collection for this page - /// Is and admin page + /// The Icon for this new Tab. + /// The large Icon for this new Tab. + /// A flag indicating whether the tab is visible. + /// Page Permissions Collection for this page. + /// Is and admin page. /// ----------------------------------------------------------------------------- private static TabInfo AddPage(int portalId, int parentId, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions, bool isAdmin) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddPage:" + tabName); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPage:" + tabName); TabInfo tab = TabController.Instance.GetTabByName(tabName, portalId, parentId); @@ -424,41 +634,43 @@ private static TabInfo AddPage(int portalId, int parentId, string tabName, strin TabID = Null.NullInteger, PortalID = portalId, TabName = tabName, - Title = "", + Title = string.Empty, Description = description, - KeyWords = "", + KeyWords = string.Empty, IsVisible = isVisible, DisableLink = false, ParentId = parentId, IconFile = tabIconFile, IconFileLarge = tabIconFileLarge, - IsDeleted = false + IsDeleted = false, }; tab.TabID = TabController.Instance.AddTab(tab, !isAdmin); - if (((permissions != null))) + if (permissions != null) { foreach (TabPermissionInfo tabPermission in permissions) { tab.TabPermissions.Add(tabPermission, true); } + TabPermissionController.SaveTabPermissions(tab); } } + return tab; } /// ----------------------------------------------------------------------------- /// - /// AddPagePermission adds a TabPermission to a TabPermission Collection + /// AddPagePermission adds a TabPermission to a TabPermission Collection. /// - /// Page Permissions Collection for this page - /// The Permission key - /// The role given the permission + /// Page Permissions Collection for this page. + /// The Permission key. + /// The role given the permission. /// ----------------------------------------------------------------------------- private static void AddPagePermission(TabPermissionCollection permissions, string key, int roleId) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddPagePermission:" + key); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPagePermission:" + key); var permissionController = new PermissionController(); var permission = (PermissionInfo)permissionController.GetPermissionByCodeAndKey("SYSTEM_TAB", key)[0]; @@ -467,20 +679,19 @@ private static void AddPagePermission(TabPermissionCollection permissions, strin permissions.Add(tabPermission); } - /// ----------------------------------------------------------------------------- /// - /// AddSearchResults adds a top level Hidden Search Results Page + /// AddSearchResults adds a top level Hidden Search Results Page. /// - /// The Module Deinition Id for the Search Results Module + /// The Module Deinition Id for the Search Results Module. /// ----------------------------------------------------------------------------- private static void AddSearchResults(int moduleDefId) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddSearchResults:" + moduleDefId); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddSearchResults:" + moduleDefId); var portals = PortalController.Instance.GetPortals(); int intPortal; - //Add Page to Admin Menu of all configured Portals + // Add Page to Admin Menu of all configured Portals for (intPortal = 0; intPortal <= portals.Count - 1; intPortal++) { var tabPermissions = new TabPermissionCollection(); @@ -491,27 +702,28 @@ private static void AddSearchResults(int moduleDefId) AddPagePermission(tabPermissions, "View", Convert.ToInt32(portal.AdministratorRoleId)); AddPagePermission(tabPermissions, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); - //Create New Page (or get existing one) - var tab = AddPage(portal.PortalID, Null.NullInteger, "Search Results", "", "", "", false, tabPermissions, false); + // Create New Page (or get existing one) + var tab = AddPage(portal.PortalID, Null.NullInteger, "Search Results", string.Empty, string.Empty, string.Empty, false, tabPermissions, false); - //Add Module To Page - AddModuleToPage(tab, moduleDefId, "Search Results", ""); + // Add Module To Page + AddModuleToPage(tab, moduleDefId, "Search Results", string.Empty); } } /// ----------------------------------------------------------------------------- /// - /// AddSkinControl adds a new Module Control to the system + /// AddSkinControl adds a new Module Control to the system. /// /// /// - /// The key for this control in the Definition + /// The key for this control in the Definition. /// Package Name. - /// Te source of ths control + /// Te source of ths control. /// ----------------------------------------------------------------------------- private static void AddSkinControl(string controlKey, string packageName, string controlSrc) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddSkinControl:" + controlKey); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddSkinControl:" + controlKey); + // check if skin control exists SkinControlInfo skinControl = SkinControlController.GetSkinControlByKey(controlKey); if (skinControl == null) @@ -529,7 +741,7 @@ private static void AddSkinControl(string controlKey, string packageName, string private static void AddDefaultModuleIcons() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddDefaultModuleIcons"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddDefaultModuleIcons"); var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Google Analytics"); if (pkg != null) { @@ -629,12 +841,11 @@ private static void AddDefaultModuleIcons() private static void AddModuleCategories() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddModuleCategories"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleCategories"); DesktopModuleController.AddModuleCategory("< None >"); DesktopModuleController.AddModuleCategory("Admin"); DesktopModuleController.AddModuleCategory("Common"); - foreach (var desktopModuleInfo in DesktopModuleController.GetDesktopModules(Null.NullInteger)) { bool update = false; @@ -673,12 +884,14 @@ private static void AddModuleCategories() default: break; } + if (update) { if (desktopModuleInfo.Value.PackageID == Null.NullInteger) { LegacyUtil.ProcessLegacyModule(desktopModuleInfo.Value); } + DesktopModuleController.SaveDesktopModule(desktopModuleInfo.Value, false, false); } } @@ -686,23 +899,23 @@ private static void AddModuleCategories() /// ----------------------------------------------------------------------------- /// - /// CoreModuleExists determines whether a Core Module exists on the system + /// CoreModuleExists determines whether a Core Module exists on the system. /// /// /// - /// The Friendly Name of the Module - /// True if the Module exists, otherwise False + /// The Friendly Name of the Module. + /// True if the Module exists, otherwise False. /// ----------------------------------------------------------------------------- private static bool CoreModuleExists(string desktopModuleName) { var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); - return ((desktopModule != null)); + return desktopModule != null; } private static void EnableModalPopUps() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "EnableModalPopUps"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "EnableModalPopUps"); foreach (var desktopModuleInfo in DesktopModuleController.GetDesktopModules(Null.NullInteger)) { switch (desktopModuleInfo.Value.ModuleName) @@ -738,13 +951,14 @@ private static void EnableModalPopUps() { foreach (ModuleControlInfo control in definition.ModuleControls.Values) { - if (!String.IsNullOrEmpty(control.ControlKey)) + if (!string.IsNullOrEmpty(control.ControlKey)) { control.SupportsPopUps = true; ModuleControlController.SaveModuleControl(control, false); } } } + break; default: break; @@ -760,71 +974,11 @@ private static void EnableModalPopUps() /// ----------------------------------------------------------------------------- /// - /// ExecuteScript executes a SQl script file - /// - /// - /// - /// The script to Execute - /// Need to output feedback message. - /// ----------------------------------------------------------------------------- - internal static string ExecuteScript(string scriptFile, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.Localization.GetString("ExecutingScript", Localization.Localization.GlobalResourceFile) + ":" + Path.GetFileName(scriptFile)); - } - - // read script file for installation - string script = FileSystemUtils.ReadFile(scriptFile); - - // execute SQL installation script - string exceptions = DataProvider.Instance().ExecuteScript(script); - - //add installer logging - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogEnd", Localization.Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); - } - - // log the results - try - { - using (var streamWriter = File.CreateText(scriptFile.Replace("." + DefaultProvider, "") + ".log.resources")) - { - streamWriter.WriteLine(exceptions); - streamWriter.Close(); - } - } - catch (Exception exc) - { - //does not have permission to create the log file - Logger.Error(exc); - } - - if (writeFeedback) - { - string resourcesFile = Path.GetFileName(scriptFile); - if (!String.IsNullOrEmpty(resourcesFile)) - { - HtmlUtils.WriteScriptSuccessError(HttpContext.Current.Response, (string.IsNullOrEmpty(exceptions)), resourcesFile.Replace("." + DefaultProvider, ".log.resources")); - } - } - - return exceptions; - } - - /// ----------------------------------------------------------------------------- - /// - /// GetModuleDefinition gets the Module Definition Id of a module + /// GetModuleDefinition gets the Module Definition Id of a module. /// - /// The Friendly Name of the Module to Add - /// The Module Definition Name - /// The Module Definition Id of the Module (-1 if no module definition) + /// The Friendly Name of the Module to Add. + /// The Module Definition Name. + /// The Module Definition Id of the Module (-1 if no module definition). /// ----------------------------------------------------------------------------- private static int GetModuleDefinition(string desktopModuleName, string moduleDefinitionName) { @@ -842,18 +996,17 @@ private static int GetModuleDefinition(string desktopModuleName, string moduleDe return -1; } - return objModuleDefinition.ModuleDefID; } /// ----------------------------------------------------------------------------- /// - /// HostTabExists determines whether a tab of a given name exists under the Host tab + /// HostTabExists determines whether a tab of a given name exists under the Host tab. /// /// /// - /// The Name of the Tab - /// True if the Tab exists, otherwise False + /// The Name of the Tab. + /// True if the Tab exists, otherwise False. /// ----------------------------------------------------------------------------- private static bool HostTabExists(string tabName) { @@ -861,74 +1014,23 @@ private static bool HostTabExists(string tabName) var hostTab = TabController.Instance.GetTabByName("Host", Null.NullInteger); var tab = TabController.Instance.GetTabByName(tabName, Null.NullInteger, hostTab.TabID); - if ((tab != null)) + if (tab != null) { tabExists = true; } - return tabExists; } /// ----------------------------------------------------------------------------- /// - /// InstallMemberRoleProvider - Installs the MemberRole Provider Db objects - /// - /// - /// - /// The Path to the Provider Directory - /// Whether need to output feedback message. - /// ----------------------------------------------------------------------------- - internal static string InstallMemberRoleProvider(string providerPath, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); - - string exceptions = ""; - - bool installMemberRole = true; - if ((Config.GetSetting("InstallMemberRole") != null)) - { - installMemberRole = bool.Parse(Config.GetSetting("InstallMemberRole")); - } - - if (installMemberRole) - { - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing MemberRole Provider:
    "); - } - - //Install Common - exceptions += InstallMemberRoleProviderScript(providerPath, "InstallCommon", writeFeedback); - //Install Membership - exceptions += InstallMemberRoleProviderScript(providerPath, "InstallMembership", writeFeedback); - //Install Profile - //exceptions += InstallMemberRoleProviderScript(providerPath, "InstallProfile", writeFeedback); - //Install Roles - //exceptions += InstallMemberRoleProviderScript(providerPath, "InstallRoles", writeFeedback); - } - - if (String.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogEnd", Localization.Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); - } - - return exceptions; - } - - /// ----------------------------------------------------------------------------- - /// - /// InstallMemberRoleProviderScript - Installs a specific MemberRole Provider script + /// InstallMemberRoleProviderScript - Installs a specific MemberRole Provider script. /// /// /// - /// The Path to the Provider Directory - /// The Name of the Script File - /// Whether or not to echo results + /// The Path to the Provider Directory. + /// The Name of the Script File. + /// Whether or not to echo results. private static string InstallMemberRoleProviderScript(string providerPath, string scriptFile, bool writeFeedback) { if (writeFeedback) @@ -949,7 +1051,7 @@ private static string InstallMemberRoleProviderScript(string providerPath, strin } catch (Exception exc) { - //does not have permission to create the log file + // does not have permission to create the log file Logger.Error(exc); } @@ -958,16 +1060,16 @@ private static string InstallMemberRoleProviderScript(string providerPath, strin /// ----------------------------------------------------------------------------- /// - /// ParseFiles parses the Host Template's Files node + /// ParseFiles parses the Host Template's Files node. /// /// /// - /// The Files node - /// The PortalId (-1 for Host Files) + /// The Files node. + /// The PortalId (-1 for Host Files). /// ----------------------------------------------------------------------------- private static void ParseFiles(XmlNode node, int portalId) { - //Parse the File nodes + // Parse the File nodes if (node != null) { XmlNodeList nodes = node.SelectNodes("file"); @@ -1007,24 +1109,24 @@ private static void ParseFiles(XmlNode node, int portalId) /// ----------------------------------------------------------------------------- /// - /// RemoveCoreModule removes a Core Module from the system + /// RemoveCoreModule removes a Core Module from the system. /// /// /// - /// The Friendly Name of the Module to Remove - /// The Name of the parent Tab/Page for this module - /// The Name to tab that contains the Module - /// A flag to determine whether to remove the Tab if it has no - /// other modules + /// The Friendly Name of the Module to Remove. + /// The Name of the parent Tab/Page for this module. + /// The Name to tab that contains the Module. + /// A flag to determine whether to remove the Tab if it has no + /// other modules. /// ----------------------------------------------------------------------------- private static void RemoveCoreModule(string desktopModuleName, string parentTabName, string tabName, bool removeTab) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveCoreModule:" + desktopModuleName); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveCoreModule:" + desktopModuleName); int moduleDefId = Null.NullInteger; int desktopModuleId = 0; - //Find and remove the Module from the Tab + // Find and remove the Module from the Tab switch (parentTabName) { case "Host": @@ -1034,16 +1136,18 @@ private static void RemoveCoreModule(string desktopModuleName, string parentTabN { moduleDefId = RemoveModule(desktopModuleName, tabName, tab.TabID, removeTab); } + break; case "Admin": var portals = PortalController.Instance.GetPortals(); - //Iterate through the Portals to remove the Module from the Tab + // Iterate through the Portals to remove the Module from the Tab for (int intPortal = 0; intPortal <= portals.Count - 1; intPortal++) { var portal = (PortalInfo)portals[intPortal]; moduleDefId = RemoveModule(desktopModuleName, tabName, portal.AdminTabId, removeTab); } + break; } @@ -1055,7 +1159,7 @@ private static void RemoveCoreModule(string desktopModuleName, string parentTabN } else { - //Get the Module Definition + // Get the Module Definition ModuleDefinitionInfo moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId); if (moduleDefinition != null) { @@ -1066,53 +1170,19 @@ private static void RemoveCoreModule(string desktopModuleName, string parentTabN if (desktopModule != null) { - //Delete the Desktop Module + // Delete the Desktop Module var desktopModuleController = new DesktopModuleController(); desktopModuleController.DeleteDesktopModule(desktopModuleId); - //Delete the Package + // Delete the Package PackageController.Instance.DeleteExtensionPackage(PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == desktopModule.PackageID)); } } - public static int RemoveModule(string desktopModuleName, string tabName, int parentId, bool removeTab) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveModule:" + desktopModuleName); - TabInfo tab = TabController.Instance.GetTabByName(tabName, Null.NullInteger, parentId); - int moduleDefId = 0; - int count = 0; - - //Get the Modules on the Tab - if (tab != null) - { - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(tab.TabID)) - { - var module = kvp.Value; - if (module.DesktopModule.FriendlyName == desktopModuleName) - { - //Delete the Module from the Modules list - ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); - moduleDefId = module.ModuleDefID; - } - else - { - count += 1; - } - } - - //If Tab has no modules optionally remove tab - if (count == 0 && removeTab) - { - TabController.Instance.DeleteTab(tab.TabID, tab.PortalID); - } - } - - return moduleDefId; - } - private static void RemoveModuleControl(int moduleDefId, string controlKey) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveModuleControl:" + moduleDefId); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModuleControl:" + moduleDefId); + // get Module Control var moduleControl = ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefId); if (moduleControl != null) @@ -1123,18 +1193,18 @@ private static void RemoveModuleControl(int moduleDefId, string controlKey) private static void RemoveModuleFromPortals(string friendlyName) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveModuleFromPortals:" + friendlyName); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModuleFromPortals:" + friendlyName); DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); if (desktopModule != null) { - //Module was incorrectly assigned as "IsPremium=False" + // Module was incorrectly assigned as "IsPremium=False" if (desktopModule.PackageID > Null.NullInteger) { desktopModule.IsPremium = true; DesktopModuleController.SaveDesktopModule(desktopModule, false, true); } - //Remove the module from Portals + // Remove the module from Portals DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); } } @@ -1146,7 +1216,7 @@ private static bool TabPermissionExists(TabPermissionInfo tabPermission, int por private static void FavIconsToPortalSettings() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "FavIconsToPortalSettings"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "FavIconsToPortalSettings"); const string fileName = "favicon.ico"; var portals = PortalController.Instance.GetPortals().Cast(); @@ -1159,7 +1229,7 @@ private static void FavIconsToPortalSettings() try { int fileId; - var folder = FolderManager.Instance.GetFolder(portalInfo.PortalID, ""); + var folder = FolderManager.Instance.GetFolder(portalInfo.PortalID, string.Empty); if (!FileManager.Instance.FileExists(folder, fileName)) { using (var stream = File.OpenRead(localPath)) @@ -1167,6 +1237,7 @@ private static void FavIconsToPortalSettings() FileManager.Instance.AddFile(folder, fileName, stream, /*overwrite*/ false); } } + fileId = FileManager.Instance.GetFile(folder, fileName).FileId; new FavIcon(portalInfo.PortalID).Update(fileId); @@ -1188,14 +1259,14 @@ private static void FavIconsToPortalSettings() private static void AddIconToAllowedFiles() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddIconToAllowedFiles"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddIconToAllowedFiles"); var toAdd = new List { ".ico" }; HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); } private static void UpgradeToVersion323() { - //add new SecurityException + // add new SecurityException string configFile = Globals.HostMapPath + "Logs\\LogConfig\\SecurityExceptionTemplate.xml.resources"; LogController.Instance.AddLogType(configFile, Null.NullString); } @@ -1229,15 +1300,16 @@ private static void UpgradeToVersion470() if (!Directory.Exists(portalTemplateFolder)) { - //Create Portal Templates folder + // Create Portal Templates folder Directory.CreateDirectory(portalTemplateFolder); } + string portalTemplateFile = portalTemplateFolder + "Default.page.template"; if (!File.Exists(portalTemplateFile)) { File.Copy(hostTemplateFile, portalTemplateFile); - //Synchronize the Templates folder to ensure the templates are accessible + // Synchronize the Templates folder to ensure the templates are accessible FolderManager.Instance.Synchronize(portal.PortalID, "Templates/", false, true); } } @@ -1246,8 +1318,8 @@ private static void UpgradeToVersion470() private static void UpgradeToVersion482() { - //checks for the very rare case where the default validationkey prior to 4.08.02 - //is still being used and updates it + // checks for the very rare case where the default validationkey prior to 4.08.02 + // is still being used and updates it Config.UpdateValidationKey(); } @@ -1255,7 +1327,7 @@ private static void UpgradeToVersion500() { ArrayList portals = PortalController.Instance.GetPortals(); - //Add Edit Permissions for Admin Tabs to legacy portals + // Add Edit Permissions for Admin Tabs to legacy portals var permissionController = new PermissionController(); ArrayList permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_TAB", "EDIT"); int permissionId = -1; @@ -1278,7 +1350,7 @@ private static void UpgradeToVersion500() adminTab.TabPermissions.Add(tabPermission); } - //Save Tab Permissions to Data Base + // Save Tab Permissions to Data Base TabPermissionController.SaveTabPermissions(adminTab); foreach (var childTab in TabController.GetTabsByParent(portal.AdminTabId, portal.PortalID)) @@ -1288,20 +1360,21 @@ private static void UpgradeToVersion500() { childTab.TabPermissions.Add(tabPermission); } - //Save Tab Permissions to Data Base + + // Save Tab Permissions to Data Base TabPermissionController.SaveTabPermissions(childTab); } } } } - //Update Host/Admin modules Visibility setting + // Update Host/Admin modules Visibility setting bool superTabProcessed = Null.NullBoolean; foreach (PortalInfo portal in portals) { if (!superTabProcessed) { - //Process Host Tabs + // Process Host Tabs foreach (TabInfo childTab in TabController.GetTabsByParent(portal.SuperTabId, Null.NullInteger)) { foreach (ModuleInfo tabModule in ModuleController.Instance.GetTabModules(childTab.TabID).Values) @@ -1312,7 +1385,7 @@ private static void UpgradeToVersion500() } } - //Process Portal Tabs + // Process Portal Tabs foreach (TabInfo childTab in TabController.GetTabsByParent(portal.AdminTabId, portal.PortalID)) { foreach (ModuleInfo tabModule in ModuleController.Instance.GetTabModules(childTab.TabID).Values) @@ -1323,7 +1396,7 @@ private static void UpgradeToVersion500() } } - //Upgrade PortalDesktopModules to support new "model" + // Upgrade PortalDesktopModules to support new "model" permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_DESKTOPMODULE", "DEPLOY"); if (permissions.Count == 1) { @@ -1332,13 +1405,14 @@ private static void UpgradeToVersion500() { permissionId = permission.PermissionID; } + foreach (PortalInfo portal in portals) { foreach (DesktopModuleInfo desktopModule in DesktopModuleController.GetDesktopModules(Null.NullInteger).Values) { if (!desktopModule.IsPremium) { - //Parse the permissions + // Parse the permissions var deployPermissions = new DesktopModulePermissionCollection(); DesktopModulePermissionInfo deployPermission; @@ -1357,7 +1431,7 @@ private static void UpgradeToVersion500() deployPermissions.Add(deployPermission); } - //Add Portal/Module to PortalDesktopModules + // Add Portal/Module to PortalDesktopModules DesktopModuleController.AddDesktopModuleToPortal(portal.PortalID, desktopModule, deployPermissions, false); } } @@ -1374,7 +1448,7 @@ private static void UpgradeToVersion500() private static void UpgradeToVersion501() { - //add new Cache Error Event Type + // add new Cache Error Event Type string configFile = string.Format("{0}Logs\\LogConfig\\CacheErrorTemplate.xml.resources", Globals.HostMapPath); LogController.Instance.AddLogType(configFile, Null.NullString); } @@ -1383,42 +1457,43 @@ private static void UpgradeToVersion510() { int moduleDefId; - //add Dashboard module and tab + // add Dashboard module and tab if (HostTabExists("Dashboard") == false) { moduleDefId = AddModuleDefinition("Dashboard", "Provides a snapshot of your DotNetNuke Application.", "Dashboard", true, true); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Dashboard/Dashboard.ascx", "icon_dashboard_32px.gif", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "Export", "", "DesktopModules/Admin/Dashboard/Export.ascx", "", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "DashboardControls", "", "DesktopModules/Admin/Dashboard/DashboardControls.ascx", "", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Dashboard/Dashboard.ascx", "icon_dashboard_32px.gif", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "Export", string.Empty, "DesktopModules/Admin/Dashboard/Export.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "DashboardControls", string.Empty, "DesktopModules/Admin/Dashboard/DashboardControls.ascx", string.Empty, SecurityAccessLevel.Host, 0); - //Create New Host Page (or get existing one) + // Create New Host Page (or get existing one) TabInfo dashboardPage = AddHostPage("Dashboard", "Summary view of application and site settings.", "~/images/icon_dashboard_16px.gif", "~/images/icon_dashboard_32px.gif", true); - //Add Module To Page + // Add Module To Page AddModuleToPage(dashboardPage, moduleDefId, "Dashboard", "~/images/icon_dashboard_32px.gif"); } else { - //Module was incorrectly assigned as "IsPremium=False" + // Module was incorrectly assigned as "IsPremium=False" RemoveModuleFromPortals("Dashboard"); - //fix path for dashboarcontrols + + // fix path for dashboarcontrols moduleDefId = GetModuleDefinition("Dashboard", "Dashboard"); RemoveModuleControl(moduleDefId, "DashboardControls"); - AddModuleControl(moduleDefId, "DashboardControls", "", "DesktopModules/Admin/Dashboard/DashboardControls.ascx", "", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "DashboardControls", string.Empty, "DesktopModules/Admin/Dashboard/DashboardControls.ascx", string.Empty, SecurityAccessLevel.Host, 0); } - //Add the Extensions Module + // Add the Extensions Module if (CoreModuleExists("Extensions") == false) { - moduleDefId = AddModuleDefinition("Extensions", "", "Extensions"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Extensions/Extensions.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.View, 0); + moduleDefId = AddModuleDefinition("Extensions", string.Empty, "Extensions"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Extensions/Extensions.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.View, 0); AddModuleControl(moduleDefId, "Edit", "Edit Feature", "DesktopModules/Admin/Extensions/EditExtension.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Edit, 0); AddModuleControl(moduleDefId, "PackageWriter", "Package Writer", "DesktopModules/Admin/Extensions/PackageWriter.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); AddModuleControl(moduleDefId, "EditControl", "Edit Control", "DesktopModules/Admin/Extensions/Editors/EditModuleControl.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); AddModuleControl(moduleDefId, "ImportModuleDefinition", "Import Module Definition", "DesktopModules/Admin/Extensions/Editors/ImportModuleDefinition.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); AddModuleControl(moduleDefId, "BatchInstall", "Batch Install", "DesktopModules/Admin/Extensions/BatchInstall.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); AddModuleControl(moduleDefId, "NewExtension", "New Extension Wizard", "DesktopModules/Admin/Extensions/ExtensionWizard.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, "", true); + AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, string.Empty, true); } else { @@ -1429,151 +1504,151 @@ private static void UpgradeToVersion510() RemoveModuleControl(moduleDefId, "LanguageSettings"); RemoveModuleControl(moduleDefId, "EditResourceKey"); RemoveModuleControl(moduleDefId, "EditSkins"); - AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, "", true); + AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, string.Empty, true); - //Module was incorrectly assigned as "IsPremium=False" + // Module was incorrectly assigned as "IsPremium=False" RemoveModuleFromPortals("Extensions"); } - //Remove Module Definitions Module from Host Page (if present) + // Remove Module Definitions Module from Host Page (if present) RemoveCoreModule("Module Definitions", "Host", "Module Definitions", false); - //Remove old Module Definition DynamicContentValidator module + // Remove old Module Definition DynamicContentValidator module DesktopModuleController.DeleteDesktopModule("Module Definition DynamicContentValidator"); - //Get Module Definitions + // Get Module Definitions TabInfo definitionsPage = TabController.Instance.GetTabByName("Module Definitions", Null.NullInteger); - //Add Module To Page if not present + // Add Module To Page if not present int moduleId = AddModuleToPage(definitionsPage, moduleDefId, "Module Definitions", "~/images/icon_moduledefinitions_32px.gif"); ModuleController.Instance.UpdateModuleSetting(moduleId, "Extensions_Mode", "Module"); - //Add Extensions Host Page + // Add Extensions Host Page TabInfo extensionsPage = AddHostPage("Extensions", "Install, add, modify and delete extensions, such as modules, skins and language packs.", "~/images/icon_extensions_16px.gif", "~/images/icon_extensions_32px.png", true); moduleId = AddModuleToPage(extensionsPage, moduleDefId, "Extensions", "~/images/icon_extensions_32px.png"); ModuleController.Instance.UpdateModuleSetting(moduleId, "Extensions_Mode", "All"); - //Add Extensions Module to Admin Page for all Portals + // Add Extensions Module to Admin Page for all Portals AddAdminPages("Extensions", "Install, add, modify and delete extensions, such as modules, skins and language packs.", "~/images/icon_extensions_16px.gif", "~/images/icon_extensions_32px.png", true, moduleDefId, "Extensions", "~/images/icon_extensions_32px.png"); - //Remove Host Languages Page + // Remove Host Languages Page RemoveHostPage("Languages"); - //Remove Admin > Authentication Pages + // Remove Admin > Authentication Pages RemoveAdminPages("//Admin//Authentication"); - //Remove old Languages module + // Remove old Languages module DesktopModuleController.DeleteDesktopModule("Languages"); - //Add new Languages module - moduleDefId = AddModuleDefinition("Languages", "", "Languages", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); + // Add new Languages module + moduleDefId = AddModuleDefinition("Languages", string.Empty, "Languages", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); AddModuleControl(moduleDefId, "Edit", "Edit Language", "DesktopModules/Admin/Languages/EditLanguage.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); AddModuleControl(moduleDefId, "EditResourceKey", "Full Language Editor", "DesktopModules/Admin/Languages/languageeditorext.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); - AddModuleControl(moduleDefId, "LanguageSettings", "Language Settings", "DesktopModules/Admin/Languages/LanguageSettings.ascx", "", SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, "LanguageSettings", "Language Settings", "DesktopModules/Admin/Languages/LanguageSettings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); AddModuleControl(moduleDefId, "TimeZone", "TimeZone Editor", "DesktopModules/Admin/Languages/timezoneeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "Verify", "Resource File Verifier", "DesktopModules/Admin/Languages/resourceverifier.ascx", "", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "PackageWriter", "Language Pack Writer", "DesktopModules/Admin/Languages/LanguagePackWriter.ascx", "", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "Verify", "Resource File Verifier", "DesktopModules/Admin/Languages/resourceverifier.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "PackageWriter", "Language Pack Writer", "DesktopModules/Admin/Languages/LanguagePackWriter.ascx", string.Empty, SecurityAccessLevel.Host, 0); - //Add Module to Admin Page for all Portals + // Add Module to Admin Page for all Portals AddAdminPages("Languages", "Manage Language Resources.", "~/images/icon_language_16px.gif", "~/images/icon_language_32px.gif", true, moduleDefId, "Language Editor", "~/images/icon_language_32px.gif"); - //Remove Host Skins Page + // Remove Host Skins Page RemoveHostPage("Skins"); - //Remove old Skins module + // Remove old Skins module DesktopModuleController.DeleteDesktopModule("Skins"); - //Add new Skins module - moduleDefId = AddModuleDefinition("Skins", "", "Skins", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Skins/editskins.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.View, 0); + // Add new Skins module + moduleDefId = AddModuleDefinition("Skins", string.Empty, "Skins", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Skins/editskins.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.View, 0); - //Add Module to Admin Page for all Portals + // Add Module to Admin Page for all Portals AddAdminPages("Skins", "Manage Skin Resources.", "~/images/icon_skins_16px.gif", "~/images/icon_skins_32px.gif", true, moduleDefId, "Skin Editor", "~/images/icon_skins_32px.gif"); - //Remove old Skin Designer module + // Remove old Skin Designer module DesktopModuleController.DeleteDesktopModule("Skin Designer"); DesktopModuleController.DeleteDesktopModule("SkinDesigner"); - //Add new Skin Designer module + // Add new Skin Designer module moduleDefId = AddModuleDefinition("Skin Designer", "Allows you to modify skin attributes.", "Skin Designer", true, true); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/SkinDesigner/Attributes.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SkinDesigner/Attributes.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.Host, 0); - //Add new Skin Designer to every Admin Skins Tab + // Add new Skin Designer to every Admin Skins Tab AddModuleToPages("//Admin//Skins", moduleDefId, "Skin Designer", "~/images/icon_skins_32px.gif", true); - //Remove Admin Whats New Page + // Remove Admin Whats New Page RemoveAdminPages("//Admin//WhatsNew"); - //WhatsNew needs to be set to IsPremium and removed from all portals + // WhatsNew needs to be set to IsPremium and removed from all portals RemoveModuleFromPortals("WhatsNew"); - //Create New WhatsNew Host Page (or get existing one) + // Create New WhatsNew Host Page (or get existing one) TabInfo newPage = AddHostPage("What's New", "Provides a summary of the major features for each release.", "~/images/icon_whatsnew_16px.gif", "~/images/icon_whatsnew_32px.gif", true); - //Add WhatsNew Module To Page + // Add WhatsNew Module To Page moduleDefId = GetModuleDefinition("WhatsNew", "WhatsNew"); AddModuleToPage(newPage, moduleDefId, "What's New", "~/images/icon_whatsnew_32px.gif"); - //add console module + // add console module moduleDefId = AddModuleDefinition("Console", "Display children pages as icon links for navigation.", "Console", "DotNetNuke.Modules.Console.Components.ConsoleController", true, false, false); - AddModuleControl(moduleDefId, "", "Console", "DesktopModules/Admin/Console/ViewConsole.ascx", "", SecurityAccessLevel.Anonymous, 0); - AddModuleControl(moduleDefId, "Settings", "Console Settings", "DesktopModules/Admin/Console/Settings.ascx", "", SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, string.Empty, "Console", "DesktopModules/Admin/Console/ViewConsole.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); + AddModuleControl(moduleDefId, "Settings", "Console Settings", "DesktopModules/Admin/Console/Settings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - //add console module to host page - moduleId = AddModuleToPage("//Host", Null.NullInteger, moduleDefId, "Basic Features", "", true); + // add console module to host page + moduleId = AddModuleToPage("//Host", Null.NullInteger, moduleDefId, "Basic Features", string.Empty, true); int tabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host", Null.NullString); TabInfo tab; - //add console settings for host page - if ((tabId != Null.NullInteger)) + // add console settings for host page + if (tabId != Null.NullInteger) { tab = TabController.Instance.GetTab(tabId, Null.NullInteger, true); - if (((tab != null))) + if (tab != null) { AddConsoleModuleSettings(moduleId); } } - //add module to all admin pages + // add module to all admin pages foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { tabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin", Null.NullString); - if ((tabId != Null.NullInteger)) + if (tabId != Null.NullInteger) { tab = TabController.Instance.GetTab(tabId, portal.PortalID, true); - if (((tab != null))) + if (tab != null) { - moduleId = AddModuleToPage(tab, moduleDefId, "Basic Features", "", true); + moduleId = AddModuleToPage(tab, moduleDefId, "Basic Features", string.Empty, true); AddConsoleModuleSettings(moduleId); } } } - //Add Google Analytics module + // Add Google Analytics module moduleDefId = AddModuleDefinition("Google Analytics", "Configure Site Google Analytics settings.", "GoogleAnalytics", false, false); - AddModuleControl(moduleDefId, "", "Google Analytics", "DesktopModules/Admin/Analytics/GoogleAnalyticsSettings.ascx", "", SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, string.Empty, "Google Analytics", "DesktopModules/Admin/Analytics/GoogleAnalyticsSettings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); AddAdminPages("Google Analytics", "Configure Site Google Analytics settings.", "~/images/icon_analytics_16px.gif", "~/images/icon_analytics_32px.gif", true, moduleDefId, "Google Analytics", "~/images/icon_analytics_32px.gif"); } private static void UpgradeToVersion511() { - //New Admin pages may not have administrator permission - //Add Admin role if it does not exist for google analytics or extensions + // New Admin pages may not have administrator permission + // Add Admin role if it does not exist for google analytics or extensions AddAdminRoleToPage("//Admin//Extensions"); AddAdminRoleToPage("//Admin//GoogleAnalytics"); } private static void UpgradeToVersion513() { - //Ensure that default language is present (not neccessarily enabled) + // Ensure that default language is present (not neccessarily enabled) var defaultLanguage = LocaleController.Instance.GetLocale("en-US") ?? new Locale(); defaultLanguage.Code = "en-US"; defaultLanguage.Text = "English (United States)"; - Localization.Localization.SaveLanguage(defaultLanguage); + Localization.SaveLanguage(defaultLanguage); - //Ensure that there is a Default Authorization System + // Ensure that there is a Default Authorization System var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DefaultAuthentication"); if (package == null) { @@ -1585,16 +1660,16 @@ private static void UpgradeToVersion513() PackageType = "Auth_System", Version = new Version(1, 0, 0), Owner = "DNN", - License = Localization.Localization.GetString("License", Localization.Localization.GlobalResourceFile), + License = Localization.GetString("License", Localization.GlobalResourceFile), Organization = ".NET Foundation", Url = "https://dnncommunity.org", Email = "info@dnncommunity.org", ReleaseNotes = "There are no release notes for this version.", - IsSystemPackage = true + IsSystemPackage = true, }; PackageController.Instance.SaveExtensionPackage(package); - //Add Authentication System + // Add Authentication System var authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN") ?? new AuthenticationInfo(); authSystem.PackageID = package.PackageID; authSystem.AuthenticationType = "DNN"; @@ -1615,14 +1690,14 @@ private static void UpgradeToVersion513() private static void UpgradeToVersion520() { - //Add new ViewSource control - AddModuleControl(Null.NullInteger, "ViewSource", "View Module Source", "Admin/Modules/ViewSource.ascx", "~/images/icon_source_32px.gif", SecurityAccessLevel.Host, 0, "", true); + // Add new ViewSource control + AddModuleControl(Null.NullInteger, "ViewSource", "View Module Source", "Admin/Modules/ViewSource.ascx", "~/images/icon_source_32px.gif", SecurityAccessLevel.Host, 0, string.Empty, true); - //Add Marketplace module definition + // Add Marketplace module definition int moduleDefId = AddModuleDefinition("Marketplace", "Search for DotNetNuke modules, extension and skins.", "Marketplace"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Marketplace/Marketplace.ascx", "~/images/icon_marketplace_32px.gif", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Marketplace/Marketplace.ascx", "~/images/icon_marketplace_32px.gif", SecurityAccessLevel.Host, 0); - //Add marketplace Module To Page + // Add marketplace Module To Page TabInfo newPage = AddHostPage("Marketplace", "Search for DotNetNuke modules, extension and skins.", "~/images/icon_marketplace_16px.gif", "~/images/icon_marketplace_32px.gif", true); moduleDefId = GetModuleDefinition("Marketplace", "Marketplace"); AddModuleToPage(newPage, moduleDefId, "Marketplace", "~/images/icon_marketplace_32px.gif"); @@ -1643,29 +1718,28 @@ private static void UpgradeToVersion521() private static void UpgradeToVersion530() { - //update languages module + // update languages module int moduleDefId = GetModuleDefinition("Languages", "Languages"); - RemoveModuleControl(moduleDefId, ""); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Languages/languageEnabler.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0, "", true); - AddModuleControl(moduleDefId, "Editor", "", "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); + RemoveModuleControl(moduleDefId, string.Empty); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Languages/languageEnabler.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0, string.Empty, true); + AddModuleControl(moduleDefId, "Editor", string.Empty, "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); - //Add new View Profile module - moduleDefId = AddModuleDefinition("ViewProfile", "", "ViewProfile", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/ViewProfile/ViewProfile.ascx", "~/images/icon_profile_32px.gif", SecurityAccessLevel.View, 0); + // Add new View Profile module + moduleDefId = AddModuleDefinition("ViewProfile", string.Empty, "ViewProfile", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ViewProfile/ViewProfile.ascx", "~/images/icon_profile_32px.gif", SecurityAccessLevel.View, 0); AddModuleControl(moduleDefId, "Settings", "Settings", "DesktopModules/Admin/ViewProfile/Settings.ascx", "~/images/icon_profile_32px.gif", SecurityAccessLevel.Edit, 0); - //Add new Sitemap settings module - moduleDefId = AddModuleDefinition("Sitemap", "", "Sitemap", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Sitemap/SitemapSettings.ascx", "~/images/icon_analytics_32px.gif", SecurityAccessLevel.View, 0); + // Add new Sitemap settings module + moduleDefId = AddModuleDefinition("Sitemap", string.Empty, "Sitemap", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Sitemap/SitemapSettings.ascx", "~/images/icon_analytics_32px.gif", SecurityAccessLevel.View, 0); AddAdminPages("Search Engine Sitemap", "Configure the sitemap for submission to common search engines.", "~/images/icon_analytics_16px.gif", "~/images/icon_analytics_32px.gif", true, moduleDefId, "Search Engine Sitemap", "~/images/icon_analytics_32px.gif"); - - //Add new Photo Profile field to Host + // Add new Photo Profile field to Host var listController = new ListController(); Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); var properties = ProfileController.GetPropertyDefinitionsByPortal(Null.NullInteger); - ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, properties.Count * 2 + 2, UserVisibilityMode.AllUsers, dataTypes); + ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); string installTemplateFile = string.Format("{0}Template\\UserProfile.page.template", Globals.InstallMapPath); string hostTemplateFile = string.Format("{0}Templates\\UserProfile.page.template", Globals.HostMapPath); @@ -1676,6 +1750,7 @@ private static void UpgradeToVersion530() File.Copy(installTemplateFile, hostTemplateFile); } } + if (File.Exists(hostTemplateFile)) { ArrayList portals = PortalController.Instance.GetPortals(); @@ -1683,23 +1758,23 @@ private static void UpgradeToVersion530() { properties = ProfileController.GetPropertyDefinitionsByPortal(portal.PortalID); - //Add new Photo Profile field to Portal - ProfileController.AddDefaultDefinition(portal.PortalID, "Preferences", "Photo", "Image", 0, properties.Count * 2 + 2, UserVisibilityMode.AllUsers, dataTypes); + // Add new Photo Profile field to Portal + ProfileController.AddDefaultDefinition(portal.PortalID, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); - //Rename old Default Page template + // Rename old Default Page template string defaultPageTemplatePath = string.Format("{0}Templates\\Default.page.template", portal.HomeDirectoryMapPath); if (File.Exists(defaultPageTemplatePath)) { - File.Move(defaultPageTemplatePath, String.Format("{0}Templates\\Default_old.page.template", portal.HomeDirectoryMapPath)); + File.Move(defaultPageTemplatePath, string.Format("{0}Templates\\Default_old.page.template", portal.HomeDirectoryMapPath)); } - //Update Default profile template in every portal + // Update Default profile template in every portal PortalController.Instance.CopyPageTemplate("Default.page.template", portal.HomeDirectoryMapPath); - //Add User profile template to every portal + // Add User profile template to every portal PortalController.Instance.CopyPageTemplate("UserProfile.page.template", portal.HomeDirectoryMapPath); - //Synchronize the Templates folder to ensure the templates are accessible + // Synchronize the Templates folder to ensure the templates are accessible FolderManager.Instance.Synchronize(portal.PortalID, "Templates/", false, true); var xmlDoc = new XmlDocument { XmlResolver = null }; @@ -1720,7 +1795,7 @@ private static void UpgradeToVersion530() var userTab = TabController.Instance.GetTabByName(tabName, portal.PortalID) ?? TabController.DeserializeTab(userTabNode, null, portal.PortalID, PortalTemplateModuleAction.Merge); - //Update SiteSettings to point to the new page + // Update SiteSettings to point to the new page if (portal.UserTabId > Null.NullInteger) { portal.RegisterTabId = portal.UserTabId; @@ -1730,29 +1805,31 @@ private static void UpgradeToVersion530() portal.UserTabId = userTab.TabID; } } + PortalController.Instance.UpdatePortalInfo(portal); - //Add Users folder to every portal + // Add Users folder to every portal string usersFolder = string.Format("{0}Users\\", portal.HomeDirectoryMapPath); if (!Directory.Exists(usersFolder)) { - //Create Users folder + // Create Users folder Directory.CreateDirectory(usersFolder); - //Synchronize the Users folder to ensure the user folder is accessible + // Synchronize the Users folder to ensure the user folder is accessible FolderManager.Instance.Synchronize(portal.PortalID, "Users/", false, true); } } } + AddEventQueueApplicationStartFirstRequest(); - //Change Key for Module Defintions; + // Change Key for Module Defintions; moduleDefId = GetModuleDefinition("Extensions", "Extensions"); RemoveModuleControl(moduleDefId, "ImportModuleDefinition"); AddModuleControl(moduleDefId, "EditModuleDefinition", "Edit Module Definition", "DesktopModules/Admin/Extensions/Editors/EditModuleDefinition.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - //Module was incorrectly assigned as "IsPremium=False" + // Module was incorrectly assigned as "IsPremium=False" RemoveModuleFromPortals("Users And Roles"); } @@ -1762,36 +1839,37 @@ private static void UpgradeToVersion540() var configNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/system.web.extensions"); if (configNavigator == null) { - //attempt to remove "System.Web.Extensions" configuration section + // attempt to remove "System.Web.Extensions" configuration section string upgradeFile = string.Format("{0}\\Config\\SystemWebExtensions.config", Globals.InstallMapPath); string message = UpdateConfig(upgradeFile, ApplicationVersion, "Remove System.Web.Extensions"); - EventLogController.Instance.AddLog("UpgradeConfig", - string.IsNullOrEmpty(message) + EventLogController.Instance.AddLog( + "UpgradeConfig", + string.IsNullOrEmpty(message) ? "Remove System Web Extensions" : string.Format("Remove System Web Extensions failed. Error reported during attempt to update:{0}", message), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.HOST_ALERT); + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.HOST_ALERT); } - //Add Styles Skin Object + // Add Styles Skin Object AddSkinControl("TAGS", "DotNetNuke.TagsSkinObject", "Admin/Skins/Tags.ascx"); - //Add Content List module definition + // Add Content List module definition int moduleDefId = AddModuleDefinition("ContentList", "This module displays a list of content by tag.", "Content List"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/ContentList/ContentList.ascx", "", SecurityAccessLevel.View, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ContentList/ContentList.ascx", string.Empty, SecurityAccessLevel.View, 0); - //Update registration page + // Update registration page ArrayList portals = PortalController.Instance.GetPortals(); foreach (PortalInfo portal in portals) { - //objPortal.RegisterTabId = objPortal.UserTabId; + // objPortal.RegisterTabId = objPortal.UserTabId; PortalController.Instance.UpdatePortalInfo(portal); - //Add ContentList to Search Results Page + // Add ContentList to Search Results Page int tabId = TabController.GetTabByTabPath(portal.PortalID, "//SearchResults", Null.NullString); TabInfo searchPage = TabController.Instance.GetTab(tabId, portal.PortalID, false); - AddModuleToPage(searchPage, moduleDefId, "Results", ""); + AddModuleToPage(searchPage, moduleDefId, "Results", string.Empty); } } @@ -1801,14 +1879,15 @@ private static void UpgradeToVersion543() string logFilePath = DataProvider.Instance().GetProviderPath(); if (Directory.Exists(logFilePath)) { - //get log files + // get log files foreach (string fileName in Directory.GetFiles(logFilePath, "*.log")) { if (File.Exists(fileName + ".resources")) { File.Delete(fileName + ".resources"); } - //copy requires use of move + + // copy requires use of move File.Move(fileName, fileName + ".resources"); } } @@ -1816,11 +1895,11 @@ private static void UpgradeToVersion543() private static void UpgradeToVersion550() { - //update languages module + // update languages module int moduleDefId = GetModuleDefinition("Languages", "Languages"); - AddModuleControl(moduleDefId, "TranslationStatus", "", "DesktopModules/Admin/Languages/TranslationStatus.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, "TranslationStatus", string.Empty, "DesktopModules/Admin/Languages/TranslationStatus.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); - //due to an error in 5.3.0 we need to recheck and readd Application_Start_FirstRequest + // due to an error in 5.3.0 we need to recheck and readd Application_Start_FirstRequest AddEventQueueApplicationStartFirstRequest(); // check if UserProfile page template exists in Host folder and if not, copy it from Install folder @@ -1834,7 +1913,7 @@ private static void UpgradeToVersion550() } } - //Fix the permission for User Folders + // Fix the permission for User Folders foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { foreach (FolderInfo folder in FolderManager.Instance.GetFolders(portal.PortalID)) @@ -1845,8 +1924,8 @@ private static void UpgradeToVersion550() { if (permission.PermissionKey.Equals("READ", StringComparison.InvariantCultureIgnoreCase)) { - //Add All Users Read Access to the folder - int roleId = Int32.Parse(Globals.glbRoleAllUsers); + // Add All Users Read Access to the folder + int roleId = int.Parse(Globals.glbRoleAllUsers); if (!folder.FolderPermissions.Contains(permission.PermissionKey, folder.FolderID, roleId, Null.NullInteger)) { var folderPermission = new FolderPermissionInfo(permission) { FolderID = folder.FolderID, UserID = Null.NullInteger, RoleID = roleId, AllowAccess = true }; @@ -1859,14 +1938,15 @@ private static void UpgradeToVersion550() FolderPermissionController.SaveFolderPermissions(folder); } } - //Remove user page template from portal if it exists (from 5.3) + + // Remove user page template from portal if it exists (from 5.3) if (File.Exists(string.Format("{0}Templates\\UserProfile.page.template", portal.HomeDirectoryMapPath))) { File.Delete(string.Format("{0}Templates\\UserProfile.page.template", portal.HomeDirectoryMapPath)); } } - //DNN-12894 - Country Code for "United Kingdom" is incorrect + // DNN-12894 - Country Code for "United Kingdom" is incorrect var listController = new ListController(); var listItem = listController.GetListEntryInfo("Country", "UK"); if (listItem != null) @@ -1875,17 +1955,17 @@ private static void UpgradeToVersion550() listController.UpdateListEntry(listItem); } - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - //fix issue where portal default language may be disabled + // fix issue where portal default language may be disabled string defaultLanguage = portal.DefaultLanguage; if (!IsLanguageEnabled(portal.PortalID, defaultLanguage)) { Locale language = LocaleController.Instance.GetLocale(defaultLanguage); - Localization.Localization.AddLanguageToPortal(portal.PortalID, language.LanguageId, true); + Localization.AddLanguageToPortal(portal.PortalID, language.LanguageId, true); } - //preemptively create any missing localization records rather than relying on dynamic creation + + // preemptively create any missing localization records rather than relying on dynamic creation foreach (Locale locale in LocaleController.Instance.GetLocales(portal.PortalID).Values) { DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, locale.Code); @@ -1895,23 +1975,23 @@ private static void UpgradeToVersion550() private static void UpgradeToVersion560() { - //Add .htmtemplate file extension + // Add .htmtemplate file extension var toAdd = new List { ".htmtemplate" }; HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); - //Add new Xml Merge module - int moduleDefId = AddModuleDefinition("Configuration Manager", "", "Configuration Manager", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/XmlMerge/XmlMerge.ascx", "~/images/icon_configuration_32px.png", SecurityAccessLevel.Host, 0); + // Add new Xml Merge module + int moduleDefId = AddModuleDefinition("Configuration Manager", string.Empty, "Configuration Manager", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/XmlMerge/XmlMerge.ascx", "~/images/icon_configuration_32px.png", SecurityAccessLevel.Host, 0); - //Add Module To Page + // Add Module To Page TabInfo hostPage = AddHostPage("Configuration Manager", "Modify configuration settings for your site", "~/images/icon_configuration_16px.png", "~/images/icon_configuration_32px.png", true); AddModuleToPage(hostPage, moduleDefId, "Configuration Manager", "~/images/icon_configuration_32px.png"); - //Update Google Analytics Script in SiteAnalysis.config + // Update Google Analytics Script in SiteAnalysis.config var googleAnalyticsController = new GoogleAnalyticsController(); googleAnalyticsController.UpgradeModule("05.06.00"); - //Updated LanguageSettings.ascx control to be a Settings control + // Updated LanguageSettings.ascx control to be a Settings control ModuleDefinitionInfo languageModule = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Languages"); ModuleControlInfo moduleControl = ModuleControlController.GetModuleControlsByModuleDefinitionID(languageModule.ModuleDefID)["LanguageSettings"]; moduleControl.ControlKey = "Settings"; @@ -1920,12 +2000,12 @@ private static void UpgradeToVersion560() private static void UpgradeToVersion562() { - //Add new Photo Profile field to Host + // Add new Photo Profile field to Host var listController = new ListController(); Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); var properties = ProfileController.GetPropertyDefinitionsByPortal(Null.NullInteger); - ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, properties.Count * 2 + 2, UserVisibilityMode.AllUsers, dataTypes); + ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); HostController.Instance.Update("AutoAddPortalAlias", Globals.Status == Globals.UpgradeStatus.Install ? "Y" : "N"); @@ -1947,10 +2027,10 @@ private static void UpgradeToVersion562() if (CoreModuleExists("LogViewer") == false) { moduleDefId = AddModuleDefinition("LogViewer", "Allows you to view log entries for site events.", "Log Viewer"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/LogViewer/LogViewer.ascx", "", SecurityAccessLevel.Admin, 0); - AddModuleControl(moduleDefId, "Edit", "Edit Log Settings", "DesktopModules/Admin/LogViewer/EditLogTypes.ascx", "", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/LogViewer/LogViewer.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, "Edit", "Edit Log Settings", "DesktopModules/Admin/LogViewer/EditLogTypes.ascx", string.Empty, SecurityAccessLevel.Host, 0); - //Add the Module/Page to all configured portals + // Add the Module/Page to all configured portals AddAdminPages("Log Viewer", "View a historical log of database events such as event schedules, exceptions, account logins, module and page changes, user account activities, security role activities, etc.", "icon_viewstats_16px.gif", "icon_viewstats_32px.gif", true, moduleDefId, "Log Viewer", "icon_viewstats_16px.gif"); } @@ -1959,15 +2039,15 @@ private static void UpgradeToVersion562() if (CoreModuleExists("Scheduler") == false) { moduleDefId = AddModuleDefinition("Scheduler", "Allows you to schedule tasks to be run at specified intervals.", "Scheduler"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Scheduler/ViewSchedule.ascx", "", SecurityAccessLevel.Admin, 0); - AddModuleControl(moduleDefId, "Edit", "Edit Schedule", "DesktopModules/Admin/Scheduler/EditSchedule.ascx", "", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "History", "Schedule History", "DesktopModules/Admin/Scheduler/ViewScheduleHistory.ascx", "", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "Status", "Schedule Status", "DesktopModules/Admin/Scheduler/ViewScheduleStatus.ascx", "", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Scheduler/ViewSchedule.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, "Edit", "Edit Schedule", "DesktopModules/Admin/Scheduler/EditSchedule.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "History", "Schedule History", "DesktopModules/Admin/Scheduler/ViewScheduleHistory.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "Status", "Schedule Status", "DesktopModules/Admin/Scheduler/ViewScheduleStatus.ascx", string.Empty, SecurityAccessLevel.Host, 0); - //Create New Host Page (or get existing one) + // Create New Host Page (or get existing one) newPage = AddHostPage("Schedule", "Add, modify and delete scheduled tasks to be run at specified intervals.", "icon_scheduler_16px.gif", "icon_scheduler_32px.gif", true); - //Add Module To Page + // Add Module To Page AddModuleToPage(newPage, moduleDefId, "Schedule", "icon_scheduler_16px.gif"); } @@ -1975,12 +2055,12 @@ private static void UpgradeToVersion562() if (CoreModuleExists("SearchAdmin") == false) { moduleDefId = AddModuleDefinition("SearchAdmin", "The Search Admininstrator provides the ability to manage search settings.", "Search Admin"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/SearchAdmin/SearchAdmin.ascx", "", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchAdmin/SearchAdmin.ascx", string.Empty, SecurityAccessLevel.Host, 0); - //Create New Host Page (or get existing one) + // Create New Host Page (or get existing one) newPage = AddHostPage("Search Admin", "Manage search settings associated with DotNetNuke's search capability.", "icon_search_16px.gif", "icon_search_32px.gif", true); - //Add Module To Page + // Add Module To Page AddModuleToPage(newPage, moduleDefId, "Search Admin", "icon_search_16px.gif"); } @@ -1988,18 +2068,18 @@ private static void UpgradeToVersion562() if (CoreModuleExists("SearchInput") == false) { moduleDefId = AddModuleDefinition("SearchInput", "The Search Input module provides the ability to submit a search to a given search results module.", "Search Input", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/SearchInput/SearchInput.ascx", "", SecurityAccessLevel.Anonymous, 0); - AddModuleControl(moduleDefId, "Settings", "Search Input Settings", "DesktopModules/Admin/SearchInput/Settings.ascx", "", SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchInput/SearchInput.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); + AddModuleControl(moduleDefId, "Settings", "Search Input Settings", "DesktopModules/Admin/SearchInput/Settings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); } // add the Search Results module if (CoreModuleExists("SearchResults") == false) { moduleDefId = AddModuleDefinition("SearchResults", "The Search Reasults module provides the ability to display search results.", "Search Results", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/SearchResults/SearchResults.ascx", "", SecurityAccessLevel.Anonymous, 0); - AddModuleControl(moduleDefId, "Settings", "Search Results Settings", "DesktopModules/Admin/SearchResults/Settings.ascx", "", SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchResults/SearchResults.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); + AddModuleControl(moduleDefId, "Settings", "Search Results Settings", "DesktopModules/Admin/SearchResults/Settings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); - //Add the Search Module/Page to all configured portals + // Add the Search Module/Page to all configured portals AddSearchResults(moduleDefId); } @@ -2007,73 +2087,71 @@ private static void UpgradeToVersion562() if (CoreModuleExists("SiteWizard") == false) { moduleDefId = AddModuleDefinition("SiteWizard", "The Administrator can use this user-friendly wizard to set up the common Extensions of the Portal/Site.", "Site Wizard"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/SiteWizard/Sitewizard.ascx", "", SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SiteWizard/Sitewizard.ascx", string.Empty, SecurityAccessLevel.Admin, 0); AddAdminPages("Site Wizard", "Configure portal settings, page design and apply a site template using a step-by-step wizard.", "icon_wizard_16px.gif", "icon_wizard_32px.gif", true, moduleDefId, "Site Wizard", "icon_wizard_16px.gif"); } - //add Lists module and tab + // add Lists module and tab if (HostTabExists("Lists") == false) { moduleDefId = AddModuleDefinition("Lists", "Allows you to edit common lists.", "Lists"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Lists/ListEditor.ascx", "", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Lists/ListEditor.ascx", string.Empty, SecurityAccessLevel.Host, 0); - //Create New Host Page (or get existing one) + // Create New Host Page (or get existing one) newPage = AddHostPage("Lists", "Manage common lists.", "icon_lists_16px.gif", "icon_lists_32px.gif", true); - //Add Module To Page + // Add Module To Page AddModuleToPage(newPage, moduleDefId, "Lists", "icon_lists_16px.gif"); } if (HostTabExists("Superuser Accounts") == false) { - //add SuperUser Accounts module and tab + // add SuperUser Accounts module and tab DesktopModuleInfo objDesktopModuleInfo = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); moduleDefId = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Accounts", objDesktopModuleInfo.DesktopModuleID).ModuleDefID; - //Create New Host Page (or get existing one) + // Create New Host Page (or get existing one) newPage = AddHostPage("Superuser Accounts", "Manage host user accounts.", "icon_users_16px.gif", "icon_users_32px.gif", true); - //Add Module To Page + // Add Module To Page AddModuleToPage(newPage, moduleDefId, "SuperUser Accounts", "icon_users_32px.gif"); } - //Add Edit Role Groups + // Add Edit Role Groups moduleDefId = GetModuleDefinition("Security", "Security Roles"); AddModuleControl(moduleDefId, "EditGroup", "Edit Role Groups", "DesktopModules/Admin/Security/EditGroups.ascx", "icon_securityroles_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); AddModuleControl(moduleDefId, "UserSettings", "Manage User Settings", "DesktopModules/Admin/Security/UserSettings.ascx", "~/images/settings.gif", SecurityAccessLevel.Edit, Null.NullInteger); - //Add User Accounts Controls + // Add User Accounts Controls moduleDefId = GetModuleDefinition("Security", "User Accounts"); AddModuleControl(moduleDefId, "ManageProfile", "Manage Profile Definition", "DesktopModules/Admin/Security/ProfileDefinitions.ascx", "icon_users_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); AddModuleControl(moduleDefId, "EditProfileProperty", "Edit Profile Property Definition", "DesktopModules/Admin/Security/EditProfileDefinition.ascx", "icon_users_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); AddModuleControl(moduleDefId, "UserSettings", "Manage User Settings", "DesktopModules/Admin/Security/UserSettings.ascx", "~/images/settings.gif", SecurityAccessLevel.Edit, Null.NullInteger); AddModuleControl(Null.NullInteger, "Profile", "Profile", "DesktopModules/Admin/Security/ManageUsers.ascx", "icon_users_32px.gif", SecurityAccessLevel.Anonymous, Null.NullInteger); - AddModuleControl(Null.NullInteger, "SendPassword", "Send Password", "DesktopModules/Admin/Security/SendPassword.ascx", "", SecurityAccessLevel.Anonymous, Null.NullInteger); + AddModuleControl(Null.NullInteger, "SendPassword", "Send Password", "DesktopModules/Admin/Security/SendPassword.ascx", string.Empty, SecurityAccessLevel.Anonymous, Null.NullInteger); AddModuleControl(Null.NullInteger, "ViewProfile", "View Profile", "DesktopModules/Admin/Security/ViewProfile.ascx", "icon_users_32px.gif", SecurityAccessLevel.Anonymous, Null.NullInteger); - //Update Child Portal subHost.aspx + // Update Child Portal subHost.aspx UpdateChildPortalsDefaultPage(); // add the solutions explorer module to the admin tab if (CoreModuleExists("Solutions") == false) { moduleDefId = AddModuleDefinition("Solutions", "Browse additional solutions for your application.", "Solutions", false, false); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/Solutions/Solutions.ascx", "", SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Solutions/Solutions.ascx", string.Empty, SecurityAccessLevel.Admin, 0); AddAdminPages("Solutions", "DotNetNuke Solutions Explorer page provides easy access to locate free and commercial DotNetNuke modules, skin and more.", "icon_solutions_16px.gif", "icon_solutions_32px.gif", true, moduleDefId, "Solutions Explorer", "icon_solutions_32px.gif"); } - - //Add Search Skin Object + // Add Search Skin Object AddSkinControl("SEARCH", "DotNetNuke.SearchSkinObject", "Admin/Skins/Search.ascx"); - //Add TreeView Skin Object + // Add TreeView Skin Object AddSkinControl("TREEVIEW", "DotNetNuke.TreeViewSkinObject", "Admin/Skins/TreeViewMenu.ascx"); - //Add Text Skin Object + // Add Text Skin Object AddSkinControl("TEXT", "DotNetNuke.TextSkinObject", "Admin/Skins/Text.ascx"); - //Add Styles Skin Object - + // Add Styles Skin Object AddSkinControl("STYLES", "DotNetNuke.StylesSkinObject", "Admin/Skins/Styles.ascx"); } @@ -2081,8 +2159,8 @@ private static void UpgradeToVersion600() { var hostPages = TabController.Instance.GetTabsByPortal(Null.NullInteger); - //This ensures that all host pages have a tab path. - //so they can be found later. (DNNPRO-17129) + // This ensures that all host pages have a tab path. + // so they can be found later. (DNNPRO-17129) foreach (var hostPage in hostPages.Values) { hostPage.TabPath = Globals.GenerateTabPath(hostPage.ParentId, hostPage.TabName); @@ -2102,11 +2180,11 @@ private static void UpgradeToVersion600() } } - //remove timezone editor + // remove timezone editor int moduleDefId = GetModuleDefinition("Languages", "Languages"); RemoveModuleControl(moduleDefId, "TimeZone"); - //6.0 requires the old TimeZone property to be marked as Deleted - Delete for Host + // 6.0 requires the old TimeZone property to be marked as Deleted - Delete for Host ProfilePropertyDefinition ppdHostTimeZone = ProfileController.GetPropertyDefinitionByName(Null.NullInteger, "TimeZone"); if (ppdHostTimeZone != null) { @@ -2115,13 +2193,13 @@ private static void UpgradeToVersion600() foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - //update timezoneinfo + // update timezoneinfo #pragma warning disable 612,618 - TimeZoneInfo timeZoneInfo = Localization.Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(portal.TimeZoneOffset); + TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(portal.TimeZoneOffset); #pragma warning restore 612,618 PortalController.UpdatePortalSetting(portal.PortalID, "TimeZone", timeZoneInfo.Id, false); - //6.0 requires the old TimeZone property to be marked as Deleted - Delete for Portals + // 6.0 requires the old TimeZone property to be marked as Deleted - Delete for Portals ProfilePropertyDefinition ppdTimeZone = ProfileController.GetPropertyDefinitionByName(portal.PortalID, "TimeZone"); if (ppdTimeZone != null) { @@ -2139,12 +2217,12 @@ private static void UpgradeToVersion600() } } - //Ensure that Display Beta Notice setting is present + // Ensure that Display Beta Notice setting is present var displayBetaNotice = Host.DisplayBetaNotice; HostController.Instance.Update("DisplayBetaNotice", displayBetaNotice ? "Y" : "N"); moduleDefId = GetModuleDefinition("Languages", "Languages"); - AddModuleControl(moduleDefId, "EnableContent", "Enable Localized Content", "DesktopModules/Admin/Languages/EnableLocalizedContent.ascx", "", SecurityAccessLevel.Host, 0, null, false); + AddModuleControl(moduleDefId, "EnableContent", "Enable Localized Content", "DesktopModules/Admin/Languages/EnableLocalizedContent.ascx", string.Empty, SecurityAccessLevel.Host, 0, null, false); AddDefaultModuleIcons(); @@ -2163,15 +2241,15 @@ private static void UpgradeToVersion600() private static void UpgradeToVersion601() { - //List module needs to be available to Portals also + // List module needs to be available to Portals also var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Lists"); if (pkg != null) { - //List package is no longer a system package + // List package is no longer a system package pkg.IsSystemPackage = false; PackageController.Instance.SaveExtensionPackage(pkg); - //List desktop module is no longer premium or admin module + // List desktop module is no longer premium or admin module var desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(pkg.PackageID); desktopModule.IsAdmin = false; desktopModule.IsPremium = false; @@ -2186,16 +2264,16 @@ private static void UpgradeToVersion601() { foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - //ensure desktop module is not present in the portal + // ensure desktop module is not present in the portal var pdmi = DesktopModuleController.GetPortalDesktopModule(portal.PortalID, desktopModule.DesktopModuleID); if (pdmi == null) { - //Parse the permissions + // Parse the permissions var deployPermissions = new DesktopModulePermissionCollection(); var deployPermission = new DesktopModulePermissionInfo { PermissionID = permission.PermissionID, AllowAccess = true, RoleID = portal.AdministratorRoleId }; deployPermissions.Add(deployPermission); - //Add Portal/Module to PortalDesktopModules + // Add Portal/Module to PortalDesktopModules DesktopModuleController.AddDesktopModuleToPortal(portal.PortalID, desktopModule, deployPermissions, true); } } @@ -2206,11 +2284,11 @@ private static void UpgradeToVersion601() private static void UpgradeToVersion602() { - //Add avi,mpg,mpeg,mp3,wmv,mov,wav extensions + // Add avi,mpg,mpeg,mp3,wmv,mov,wav extensions var exts = new List { ".avi", ".mpg", ".mpeg", ".mp3", ".wmv", ".mov", ".wav" }; HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(exts)); - //Fix the icons for SiteMap page + // Fix the icons for SiteMap page foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { var siteMap = TabController.Instance.GetTabByName("Search Engine SiteMap", portal.PortalID); @@ -2228,12 +2306,12 @@ private static void UpgradeToVersion610() { AddModuleCategories(); - //update languages module + // update languages module int moduleDefId = GetModuleDefinition("Languages", "Languages"); AddModuleControl(moduleDefId, "LocalizePages", "Localize Pages", "DesktopModules/Admin/Languages/LocalizePages.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0, Null.NullString, true); - //add store control - moduleDefId = AddModuleDefinition("Extensions", "", "Extensions"); + // add store control + moduleDefId = AddModuleDefinition("Extensions", string.Empty, "Extensions"); AddModuleControl(moduleDefId, "Store", "Store Details", "DesktopModules/Admin/Extensions/Store.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); EnableModalPopUps(); @@ -2251,22 +2329,23 @@ private static void UpgradeToVersion610() } } - //Add List module to Admin page of every portal + // Add List module to Admin page of every portal ModuleDefinitionInfo mDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Lists"); if (mDef != null) { - AddAdminPages("Lists", - "Manage common lists", - "~/Icons/Sigma/Lists_16X16_Standard.png", - "~/Icons/Sigma/Lists_32X32_Standard.png", - true, - mDef.ModuleDefID, - "Lists", - "~/Icons/Sigma/Lists_16X16_Standard.png", - true); + AddAdminPages( + "Lists", + "Manage common lists", + "~/Icons/Sigma/Lists_16X16_Standard.png", + "~/Icons/Sigma/Lists_32X32_Standard.png", + true, + mDef.ModuleDefID, + "Lists", + "~/Icons/Sigma/Lists_16X16_Standard.png", + true); } - //update DotNetNuke.Portals' friend name to 'Sites'. + // update DotNetNuke.Portals' friend name to 'Sites'. var portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Portals"); if (portalPackage != null) { @@ -2274,13 +2353,13 @@ private static void UpgradeToVersion610() PackageController.Instance.SaveExtensionPackage(portalPackage); } - //add mobile preview control + // add mobile preview control AddModuleControl(Null.NullInteger, "MobilePreview", "Mobile Preview", "DesktopModules/Admin/MobilePreview/Preview.ascx", string.Empty, SecurityAccessLevel.Admin, Null.NullInteger); } private static void UpgradeToVersion612() { - //update DotNetNuke.Portals' friend name to 'Sites'. + // update DotNetNuke.Portals' friend name to 'Sites'. var portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Portals"); if (portalPackage != null) { @@ -2290,7 +2369,7 @@ private static void UpgradeToVersion612() PackageController.Instance.SaveExtensionPackage(portalPackage); } - //update 'Portal' to 'Sites' in package description. + // update 'Portal' to 'Sites' in package description. portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Tabs"); if (portalPackage != null) { @@ -2350,7 +2429,7 @@ private static void UpgradeToVersion612() private static void UpgradeToVersion613() { - //Rename admin pages page's title to 'Page Management'. + // Rename admin pages page's title to 'Page Management'. foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { var pagesTabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin//Pages", Null.NullString); @@ -2369,7 +2448,7 @@ private static void UpgradeToVersion613() private static void UpgradeToVersion620() { - //add host (system) profanityfilter list + // add host (system) profanityfilter list const string listName = "ProfanityFilter"; var listController = new ListController(); var entry = new ListEntryInfo(); @@ -2381,9 +2460,10 @@ private static void UpgradeToVersion620() entry.Text = "FindThisText"; entry.SystemList = true; } + listController.AddListEntry(entry); - //add same list to each portal + // add same list to each portal foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { entry.PortalID = portal.PortalID; @@ -2391,38 +2471,38 @@ private static void UpgradeToVersion620() entry.ListName = listName + "-" + portal.PortalID; listController.AddListEntry(entry); - //also create default social relationship entries for the portal + // also create default social relationship entries for the portal RelationshipController.Instance.CreateDefaultRelationshipsForPortal(portal.PortalID); } - //Convert old Messages to new schema + // Convert old Messages to new schema ConvertOldMessages(); - //Replace old Messaging module on User Profile with new + // Replace old Messaging module on User Profile with new ReplaceMessagingModule(); - //Move Photo Property to the end of the propert list. + // Move Photo Property to the end of the propert list. MovePhotoProperty(); - //Update Child Portal's Default Page + // Update Child Portal's Default Page UpdateChildPortalsDefaultPage(); - //Add core notification types + // Add core notification types AddCoreNotificationTypesFor620(); - //Console module should not be IPortable + // Console module should not be IPortable var consoleModule = DesktopModuleController.GetDesktopModuleByModuleName("Console", Null.NullInteger); consoleModule.SupportedFeatures = 0; - consoleModule.BusinessControllerClass = ""; + consoleModule.BusinessControllerClass = string.Empty; DesktopModuleController.SaveDesktopModule(consoleModule, false, false); } private static void UpgradeToVersion621() { - //update administrators' role description. + // update administrators' role description. foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - //update about me's template + // update about me's template var myProfileTabId = TabController.GetTabByTabPath(portal.PortalID, "//ActivityFeed//MyProfile", string.Empty); if (myProfileTabId != Null.NullInteger) { @@ -2489,34 +2569,35 @@ private static void UpgradeToVersion700() // add the site Advanced Settings module to the admin tab if (CoreModuleExists("AdvancedSettings") == false) { - var moduleDefId = AddModuleDefinition("AdvancedSettings", "", "Advanced Settings"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/AdvancedSettings/AdvancedSettings.ascx", "", SecurityAccessLevel.Admin, 0); - AddAdminPages("Advanced Settings", - "", - "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png", - "~/Icons/Sigma/AdvancedSettings_32X32_Standard.png", - true, - moduleDefId, - "Advanced Settings", - "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png"); + var moduleDefId = AddModuleDefinition("AdvancedSettings", string.Empty, "Advanced Settings"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/AdvancedSettings/AdvancedSettings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddAdminPages( + "Advanced Settings", + string.Empty, + "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png", + "~/Icons/Sigma/AdvancedSettings_32X32_Standard.png", + true, + moduleDefId, + "Advanced Settings", + "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png"); } ConvertCoreNotificationTypeActionsFor700(); - //Remove Feed Explorer module + // Remove Feed Explorer module DesktopModuleController.DeleteDesktopModule("FeedExplorer"); DesktopModuleController.DeleteDesktopModule("Solutions"); - //Register Newtonsoft assembly + // Register Newtonsoft assembly DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Newtonsoft.Json.dll", "4.5.6"); - //subhost.aspx was updated + // subhost.aspx was updated UpdateChildPortalsDefaultPage(); } private static void UpgradeToVersion710() { - //create a placeholder entry - uses the most common 5 character password (seed list is 6 characters and above) + // create a placeholder entry - uses the most common 5 character password (seed list is 6 characters and above) const string listName = "BannedPasswords"; var listController = new ListController(); var entry = new ListEntryInfo(); @@ -2529,7 +2610,7 @@ private static void UpgradeToVersion710() entry.SystemList = false; } - //add list to each portal and update primary alias + // add list to each portal and update primary alias foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { entry.PortalID = portal.PortalID; @@ -2537,8 +2618,8 @@ private static void UpgradeToVersion710() entry.ListName = listName + "-" + portal.PortalID; listController.AddListEntry(entry); - var defaultAlias = PortalController.GetPortalSetting("DefaultPortalAlias", portal.PortalID, String.Empty); - if (!String.IsNullOrEmpty(defaultAlias)) + var defaultAlias = PortalController.GetPortalSetting("DefaultPortalAlias", portal.PortalID, string.Empty); + if (!string.IsNullOrEmpty(defaultAlias)) { foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).Where(alias => alias.HTTPAlias == defaultAlias)) { @@ -2559,8 +2640,7 @@ private static void UpgradeToVersion710() var fileContentType = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); - - //only perform following for an existing installation upgrading + // only perform following for an existing installation upgrading if (Globals.Status == Globals.UpgradeStatus.Upgrade) { UpdateFoldersForParentId(); @@ -2568,18 +2648,18 @@ private static void UpgradeToVersion710() ImportDocumentLibraryCategoryAssoc(fileContentType); } - //Add 404 Log + // Add 404 Log var logTypeInfo = new LogTypeInfo { LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), LogTypeFriendlyName = "HTTP Error Code 404 Page Not Found", - LogTypeDescription = "", + LogTypeDescription = string.Empty, LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" + LogTypeOwner = "DotNetNuke.Logging.EventLogType", }; LogController.Instance.AddLogType(logTypeInfo); - //Add LogType + // Add LogType var logTypeConf = new LogTypeConfigInfo { LoggingIsActive = true, @@ -2590,27 +2670,27 @@ private static void UpgradeToVersion710() NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, MailFromAddress = Null.NullString, MailToAddress = Null.NullString, - LogTypePortalID = "*" + LogTypePortalID = "*", }; LogController.Instance.AddLogTypeConfigInfo(logTypeConf); UninstallPackage("DotNetNuke.SearchInput", "Module"); - //enable password strength meter for new installs only + // enable password strength meter for new installs only HostController.Instance.Update("EnableStrengthMeter", Globals.Status == Globals.UpgradeStatus.Install ? "Y" : "N"); - //Add IP filter log type + // Add IP filter log type var logTypeFilterInfo = new LogTypeInfo { LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), LogTypeFriendlyName = "HTTP Error Code 403.6 forbidden ip address rejected", - LogTypeDescription = "", + LogTypeDescription = string.Empty, LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" + LogTypeOwner = "DotNetNuke.Logging.EventLogType", }; LogController.Instance.AddLogType(logTypeFilterInfo); - //Add LogType + // Add LogType var logTypeFilterConf = new LogTypeConfigInfo { LoggingIsActive = true, @@ -2621,7 +2701,7 @@ private static void UpgradeToVersion710() NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, MailFromAddress = Null.NullString, MailToAddress = Null.NullString, - LogTypePortalID = "*" + LogTypePortalID = "*", }; LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); @@ -2634,7 +2714,9 @@ private static void UpgradeToVersion710() var modDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Search Admin"); if (modDef != null) - AddAdminPages("Search Admin", "Manage search settings associated with DotNetNuke's search capability.", "~/Icons/Sigma/Search_16x16_Standard.png", "~/Icons/Sigma/Search_32x32_Standard.png", true, modDef.ModuleDefID, "Search Admin", ""); + { + AddAdminPages("Search Admin", "Manage search settings associated with DotNetNuke's search capability.", "~/Icons/Sigma/Search_16x16_Standard.png", "~/Icons/Sigma/Search_32x32_Standard.png", true, modDef.ModuleDefID, "Search Admin", string.Empty); + } CopyGettingStartedStyles(); } @@ -2643,14 +2725,14 @@ private static void UpgradeToVersion711() { DesktopModuleController.DeleteDesktopModule("FileManager"); - //Add TabUrl Logtypes + // Add TabUrl Logtypes var logTypeInfo = new LogTypeInfo { LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), LogTypeFriendlyName = "TabURL created", - LogTypeDescription = "", + LogTypeDescription = string.Empty, LogTypeCSSClass = "OperationSuccess", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" + LogTypeOwner = "DotNetNuke.Logging.EventLogType", }; LogController.Instance.AddLogType(logTypeInfo); @@ -2661,12 +2743,11 @@ private static void UpgradeToVersion711() logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; LogController.Instance.AddLogType(logTypeInfo); - } private static void UpgradeToVersion712() { - //update console module in Admin/Host page to set OrderTabsByHierarchy setting to true. + // update console module in Admin/Host page to set OrderTabsByHierarchy setting to true. foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { var tabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin", Null.NullString); @@ -2703,13 +2784,13 @@ private static void UpgradeToVersion720() DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); } - //ensure old codeplex module is uninstalled - need to check for both variants of package name + // ensure old codeplex module is uninstalled - need to check for both variants of package name UninstallPackage("DotNetNuke.Module Creator", "Module"); UninstallPackage("DNNCorp.ModuleCreator", "Module"); DesktopModuleController.AddModuleCategory("Developer"); var moduleDefId = AddModuleDefinition("Module Creator", "Development of modules.", "Module Creator"); - AddModuleControl(moduleDefId, "", "", "DesktopModules/Admin/ModuleCreator/CreateModule.ascx", "~/DesktopModules/Admin/ModuleCreator/icon.png", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ModuleCreator/CreateModule.ascx", "~/DesktopModules/Admin/ModuleCreator/icon.png", SecurityAccessLevel.Host, 0); if (ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId) != null) { var desktopModuleId = ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId).DesktopModuleID; @@ -2725,17 +2806,17 @@ private static void UpgradeToVersion720() var typeController = new ContentTypeController(); var fileContentType = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); - //only perform following for an existing installation upgrading + // only perform following for an existing installation upgrading if (Globals.Status == Globals.UpgradeStatus.Upgrade) { ImportDocumentLibraryCategories(); ImportDocumentLibraryCategoryAssoc(fileContentType); } - //fixes issue introduced by eventlog's being defined in upgrade.cs + // fixes issue introduced by eventlog's being defined in upgrade.cs PortalController.EnsureRequiredEventLogTypesExist(); - //Remove Professional Features pages from CE + // Remove Professional Features pages from CE int advancedFeaturesTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host//ProfessionalFeatures", Null.NullString); if (DotNetNukeContext.Current.Application.Name == "DNNCORP.CE") { @@ -2743,17 +2824,18 @@ private static void UpgradeToVersion720() { TabController.Instance.DeleteTab(tab.TabID, Null.NullInteger); } + TabController.Instance.DeleteTab(advancedFeaturesTabId, Null.NullInteger); } - //Remove Whats New + // Remove Whats New int whatsNewTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host//WhatsNew", Null.NullString); TabController.Instance.DeleteTab(whatsNewTabId, Null.NullInteger); - //Remove WhatsNew module + // Remove WhatsNew module DesktopModuleController.DeleteDesktopModule("WhatsNew"); - //read plaintext password via old API and encrypt + // read plaintext password via old API and encrypt var current = HostController.Instance.GetString("SMTPPassword"); if (!string.IsNullOrEmpty(current)) { @@ -2765,7 +2847,7 @@ private static void UpgradeToVersion721() { try { - //the username maybe html encode when register in 7.1.2, it will caught unicode charactors changed, need use InputFilter to correct the value. + // the username maybe html encode when register in 7.1.2, it will caught unicode charactors changed, need use InputFilter to correct the value. var portalSecurity = PortalSecurity.Instance; using (var reader = DataProvider.Instance().ExecuteSQL("SELECT UserID, Username FROM {databaseOwner}[{objectQualifier}Users] WHERE Username LIKE '%&%'")) { @@ -2776,8 +2858,9 @@ private static void UpgradeToVersion721() if (userName != HttpUtility.HtmlDecode(userName)) { - userName = portalSecurity.InputFilter(HttpUtility.HtmlDecode(userName), - PortalSecurity.FilterFlag.NoScripting | + userName = portalSecurity.InputFilter( + HttpUtility.HtmlDecode(userName), + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); @@ -2798,7 +2881,7 @@ private static void UpgradeToVersion722() { UninstallPackage("DotNetNuke.Messaging", "Module"); - //add event log type:POTENTIAL_PAYPAL_PAYMENT_FRAUD + // add event log type:POTENTIAL_PAYPAL_PAYMENT_FRAUD if (!DoesLogTypeExists(EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString())) { var logTypeInfo = new LogTypeInfo @@ -2806,14 +2889,14 @@ private static void UpgradeToVersion722() LogTypeKey = EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString(), LogTypeFriendlyName = "Potential Paypal Payment Fraud", - LogTypeDescription = "", + LogTypeDescription = string.Empty, LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType" + LogTypeOwner = "DotNetNuke.Logging.EventLogType", }; LogController.Instance.AddLogType(logTypeInfo); } - //AdvancedSettings module needs to be made a system package + // AdvancedSettings module needs to be made a system package var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.AdvancedSettings"); if (pkg != null) { @@ -2821,7 +2904,7 @@ private static void UpgradeToVersion722() PackageController.Instance.SaveExtensionPackage(pkg); } - //Site Wizard module needs to be made a system package + // Site Wizard module needs to be made a system package pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteWizard"); if (pkg != null) { @@ -2829,7 +2912,7 @@ private static void UpgradeToVersion722() PackageController.Instance.SaveExtensionPackage(pkg); } - //Site Log module needs to be made a system package + // Site Log module needs to be made a system package pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteLog"); if (pkg != null) { @@ -2837,7 +2920,7 @@ private static void UpgradeToVersion722() PackageController.Instance.SaveExtensionPackage(pkg); } - //Module Creator module needs to be made a system package + // Module Creator module needs to be made a system package pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Module Creator"); if (pkg != null) { @@ -2845,7 +2928,7 @@ private static void UpgradeToVersion722() PackageController.Instance.SaveExtensionPackage(pkg); } - //Telerik.Web module needs to be made a system package + // Telerik.Web module needs to be made a system package pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Telerik.Web"); if (pkg != null) { @@ -2853,7 +2936,7 @@ private static void UpgradeToVersion722() PackageController.Instance.SaveExtensionPackage(pkg); } - //jQuery needs to be made a system package + // jQuery needs to be made a system package pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "jQuery"); if (pkg != null) { @@ -2861,7 +2944,7 @@ private static void UpgradeToVersion722() PackageController.Instance.SaveExtensionPackage(pkg); } - //jQuery-Migrate needs to be made a system package + // jQuery-Migrate needs to be made a system package pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "jQuery-Migrate"); if (pkg != null) { @@ -2869,13 +2952,13 @@ private static void UpgradeToVersion722() PackageController.Instance.SaveExtensionPackage(pkg); } - //Make ConfigurationManager Premium + // Make ConfigurationManager Premium MakeModulePremium(@"ConfigurationManager"); - //Make ConfigurationManager Premium + // Make ConfigurationManager Premium MakeModulePremium(@"Dashboard"); - //Make ProfessionalPreview Premium + // Make ProfessionalPreview Premium MakeModulePremium(@"ProfessionalPreview"); } @@ -2903,7 +2986,7 @@ private static void UpgradeToVersion730() private static void UpgradeToVersion732() { - //Register System referenced 3rd party assemblies. + // Register System referenced 3rd party assemblies. DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.dll", "3.0.3"); DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.Contrib.FastVectorHighlighter.dll", "3.0.3"); DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.Contrib.Analyzers.dll", "3.0.3"); @@ -2927,7 +3010,7 @@ private static void UpgradeToVersion732() DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebMatrix.Data.dll", "2.0.20126"); DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebMatrix.WebData.dll", "2.0.20126"); - //update help url + // update help url HostController.Instance.Update("HelpURL", "https://dnndocs.com", false); } @@ -2942,14 +3025,14 @@ private static void UpgradeToVersion733() { NameResourceKey = "AuthorizeUser", DescriptionResourceKey = "AuthorizeUserDescription", - APICall = "API/InternalServices/NewUserNotificationService/Authorize" + APICall = "API/InternalServices/NewUserNotificationService/Authorize", }, new NotificationTypeAction { NameResourceKey = "RejectUser", DescriptionResourceKey = "RejectUserDescription", APICall = "API/InternalServices/NewUserNotificationService/Reject" - } + }, }; NotificationsController.Instance.SetNotificationTypeActions(actions, notificationType.NotificationTypeId); @@ -2980,12 +3063,12 @@ private static void UpgradeToVersion742() var skinFolder = string.Format("{0}Skins\\DarkKnightMobile", Globals.HostMapPath); if (!Directory.Exists(skinFolder)) { - UninstallPackage("DarkKnightMobile", "Skin"); //Skin + UninstallPackage("DarkKnightMobile", "Skin"); // Skin } if (!Directory.Exists(containerFolder)) { - UninstallPackage("DarkKnightMobile", "Container"); //Container + UninstallPackage("DarkKnightMobile", "Container"); // Container } } @@ -3008,7 +3091,7 @@ private static void RemoveContentListModuleFromSearchResultsPage() var module = kvp.Value; if (module.DesktopModule.FriendlyName == "ContentList") { - //Delete the Module from the Modules list + // Delete the Module from the Modules list ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); break; } @@ -3020,7 +3103,8 @@ private static void AddManageUsersModulePermissions() { var permCtl = new PermissionController(); var desktopInfo = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); - //add new user dialog + + // add new user dialog var md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Account", desktopInfo.DesktopModuleID); try { @@ -3029,16 +3113,16 @@ private static void AddManageUsersModulePermissions() ModuleDefID = md.ModuleDefID, PermissionCode = "SECURITY_MODULE", PermissionKey = "MANAGEUSER", - PermissionName = "Manage User" + PermissionName = "Manage User", }; permCtl.AddPermission(pi); - } catch { - //suppress + // suppress } + md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Accounts", desktopInfo.DesktopModuleID); try { @@ -3047,16 +3131,16 @@ private static void AddManageUsersModulePermissions() ModuleDefID = md.ModuleDefID, PermissionCode = "SECURITY_MODULE", PermissionKey = "MANAGEUSERS", - PermissionName = "Manage Users" + PermissionName = "Manage Users", }; permCtl.AddPermission(pi); - } catch { - //suppress + // suppress } + md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Security Roles", desktopInfo.DesktopModuleID); try { @@ -3065,17 +3149,15 @@ private static void AddManageUsersModulePermissions() ModuleDefID = md.ModuleDefID, PermissionCode = "SECURITY_MODULE", PermissionKey = "MANAGEROLES", - PermissionName = "Manage Roles" + PermissionName = "Manage Roles", }; permCtl.AddPermission(pi); - } catch { - //suppress + // suppress } - } private static ContentItem CreateFileContentItem() @@ -3132,6 +3214,7 @@ private static void ImportDocumentLibraryCategoryAssoc(ContentType fileContentTy term = new Term(dr["CategoryName"].ToString(), null, vocabulary.VocabularyId); termController.AddTerm(term); } + termController.AddTermToContent(term, attachContentItem); } } @@ -3153,14 +3236,15 @@ private static void ImportDocumentLibraryCategories() private static void UpdateFoldersForParentId() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpgradeFolders"); - //Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeFolders"); + + // Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out var foldersToConvert = DataProvider.Instance().GetLegacyFolderCount(); var foldersRemaining = foldersToConvert; if (foldersRemaining > 0) { - //Create an empty line + // Create an empty line HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "
    ", false); } @@ -3187,10 +3271,9 @@ private static void UpdateFoldersForParentId() } } - private static void UninstallPackage(string packageName, string packageType, bool deleteFiles = true, string version = "") { - DnnInstallLogger.InstallLogInfo(string.Concat(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile), "Uninstallation of Package:", packageName, " Type:", packageType, " Version:", version)); + DnnInstallLogger.InstallLogInfo(string.Concat(Localization.GetString("LogStart", Localization.GlobalResourceFile), "Uninstallation of Package:", packageName, " Type:", packageType, " Version:", version)); var searchInput = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals(packageName, StringComparison.OrdinalIgnoreCase) @@ -3198,7 +3281,7 @@ private static void UninstallPackage(string packageName, string packageType, boo && (string.IsNullOrEmpty(version) || p.Version.ToString() == version)); if (searchInput != null) { - var searchInputInstaller = new Installer.Installer(searchInput, Globals.ApplicationMapPath); + var searchInputInstaller = new Installer(searchInput, Globals.ApplicationMapPath); searchInputInstaller.UnInstall(deleteFiles); } } @@ -3217,10 +3300,9 @@ private static void ConvertCoreNotificationTypeActionsFor700() if (actions.Any()) { - foreach (var action in actions) { - action.APICall = action.APICall.Replace(".ashx", ""); + action.APICall = action.APICall.Replace(".ashx", string.Empty); NotificationsController.Instance.DeleteNotificationTypeAction( action.NotificationTypeActionId); } @@ -3246,7 +3328,7 @@ private static void AddMissingNotificationTypes(string notificationTypeName) { NameResourceKey = "Accept", DescriptionResourceKey = "AcceptFriend", - APICall = "API/InternalServices/RelationshipService/AcceptFriend" + APICall = "API/InternalServices/RelationshipService/AcceptFriend", }); NotificationsController.Instance.CreateNotificationType(friendRequestType); NotificationsController.Instance.SetNotificationTypeActions(friendRequestTypeActions, friendRequestType.NotificationTypeId); @@ -3262,8 +3344,8 @@ private static void AddMissingNotificationTypes(string notificationTypeName) { NameResourceKey = "FollowBack", DescriptionResourceKey = "FollowBack", - ConfirmResourceKey = "", - APICall = "API/InternalServices/RelationshipService/FollowBack" + ConfirmResourceKey = string.Empty, + APICall = "API/InternalServices/RelationshipService/FollowBack", }); NotificationsController.Instance.CreateNotificationType(followBackRequestType); NotificationsController.Instance.SetNotificationTypeActions(followBackRequestTypeActions, followBackRequestType.NotificationTypeId); @@ -3279,53 +3361,54 @@ private static void AddMissingNotificationTypes(string notificationTypeName) private static void AddCoreNotificationTypesFor620() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddCoreNotificationTypesFor620"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddCoreNotificationTypesFor620"); var actions = new List(); - //Friend request + // Friend request var type = new NotificationType { Name = "FriendRequest", Description = "Friend Request" }; actions.Add(new NotificationTypeAction { NameResourceKey = "Accept", DescriptionResourceKey = "AcceptFriend", - APICall = "API/InternalServices/RelationshipService/AcceptFriend" + APICall = "API/InternalServices/RelationshipService/AcceptFriend", }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); - //Follower + // Follower type = new NotificationType { Name = "FollowerRequest", Description = "Follower Request" }; NotificationsController.Instance.CreateNotificationType(type); - //Follow Back + // Follow Back type = new NotificationType { Name = "FollowBackRequest", Description = "Follow Back Request" }; actions.Clear(); actions.Add(new NotificationTypeAction { NameResourceKey = "FollowBack", DescriptionResourceKey = "FollowBack", - ConfirmResourceKey = "", - APICall = "API/InternalServices/RelationshipService/FollowBack" + ConfirmResourceKey = string.Empty, + APICall = "API/InternalServices/RelationshipService/FollowBack", }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); - //Translation submitted + // Translation submitted type = new NotificationType { Name = "TranslationSubmitted", Description = "Translation Submitted" }; NotificationsController.Instance.CreateNotificationType(type); } private static void ConvertOldMessages() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "ConvertOldMessages"); - //Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ConvertOldMessages"); + + // Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out var messagesToConvert = InternalMessagingController.Instance.CountLegacyMessages(); var messagesRemaining = messagesToConvert; const int batchSize = 500; if (messagesRemaining > 0) { - //Create an empty line + // Create an empty line HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "
    ", false); } @@ -3352,21 +3435,24 @@ private static void ConvertOldMessages() private static void ReplaceMessagingModule() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "ReplaceMessagingModule"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ReplaceMessagingModule"); var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Message Center"); - if (moduleDefinition == null) return; + if (moduleDefinition == null) + { + return; + } var portals = PortalController.Instance.GetPortals(); foreach (PortalInfo portal in portals) { if (portal.UserTabId > Null.NullInteger) { - //Find TabInfo + // Find TabInfo TabInfo tab = TabController.Instance.GetTab(portal.UserTabId, portal.PortalID, true); if (tab != null) { - //Add new module to the page - AddModuleToPage(tab, moduleDefinition.ModuleDefID, "Message Center", "", true); + // Add new module to the page + AddModuleToPage(tab, moduleDefinition.ModuleDefID, "Message Center", string.Empty, true); } foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(portal.UserTabId)) @@ -3374,7 +3460,7 @@ private static void ReplaceMessagingModule() var module = kvp.Value; if (module.DesktopModule.FriendlyName == "Messaging") { - //Delete the Module from the Modules list + // Delete the Module from the Modules list ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); break; } @@ -3383,24 +3469,9 @@ private static void ReplaceMessagingModule() } } - public static void MakeModulePremium(string moduleName) - { - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, -1); - if (desktopModule != null) - { - desktopModule.IsAdmin = true; - desktopModule.IsPremium = true; - DesktopModuleController.SaveDesktopModule(desktopModule, false, true); - - //Remove Portal/Module to PortalDesktopModules - DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); - } - } - - private static void MovePhotoProperty() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "MovePhotoProperty"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "MovePhotoProperty"); foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { var properties = ProfileController.GetPropertyDefinitionsByPortal(portal.PortalID).Cast(); @@ -3424,11 +3495,12 @@ private static void MovePhotoProperty() private static void UpdateChildPortalsDefaultPage() { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpdateChildPortalsDefaultPage"); - //Update Child Portal subHost.aspx + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateChildPortalsDefaultPage"); + + // Update Child Portal subHost.aspx foreach (PortalAliasInfo aliasInfo in PortalAliasController.Instance.GetPortalAliases().Values) { - //For the alias to be for a child it must be of the form ...../child + // For the alias to be for a child it must be of the form ...../child int intChild = aliasInfo.HTTPAlias.IndexOf("/"); if (intChild != -1 && intChild != (aliasInfo.HTTPAlias.Length - 1)) { @@ -3436,35 +3508,39 @@ private static void UpdateChildPortalsDefaultPage() if (!string.IsNullOrEmpty(Globals.ApplicationPath)) { childPath = childPath.Replace("\\", "/"); - childPath = childPath.Replace(Globals.ApplicationPath, ""); + childPath = childPath.Replace(Globals.ApplicationPath, string.Empty); } + childPath = childPath.Replace("/", "\\"); + // check if File exists and make sure it's not the site's main default.aspx page string childDefaultPage = childPath + "\\" + Globals.glbDefaultPage; if (childPath != Globals.ApplicationMapPath && File.Exists(childDefaultPage)) { var objDefault = new System.IO.FileInfo(childDefaultPage); var objSubHost = new System.IO.FileInfo(Globals.HostMapPath + "subhost.aspx"); + // check if upgrade is necessary if (objDefault.Length != objSubHost.Length) { - //check file is readonly + // check file is readonly bool wasReadonly = false; FileAttributes attributes = File.GetAttributes(childDefaultPage); if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { wasReadonly = true; - //remove readonly attribute + + // remove readonly attribute File.SetAttributes(childDefaultPage, FileAttributes.Normal); } - //Rename existing file + // Rename existing file File.Copy(childDefaultPage, childPath + "\\old_" + Globals.glbDefaultPage, true); - //copy file + // copy file File.Copy(Globals.HostMapPath + "subhost.aspx", childDefaultPage, true); - //set back the readonly attribute + // set back the readonly attribute if (wasReadonly) { File.SetAttributes(childDefaultPage, FileAttributes.ReadOnly); @@ -3477,11 +3553,10 @@ private static void UpdateChildPortalsDefaultPage() private static void CopyGettingStartedStyles() { - //copy getting started css to portals folder. + // copy getting started css to portals folder. var hostGettingStartedFile = string.Format("{0}GettingStarted.css", Globals.HostMapPath); foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - if (File.Exists(hostGettingStartedFile)) { var portalFile = portal.HomeDirectoryMapPath + "GettingStarted.css"; @@ -3491,7 +3566,7 @@ private static void CopyGettingStartedStyles() } } - //update the getting started page to have this custom style sheet. + // update the getting started page to have this custom style sheet. var gettingStartedTabId = PortalController.GetPortalSettingAsInteger("GettingStartedTabId", portal.PortalID, Null.NullInteger); if (gettingStartedTabId > Null.NullInteger) { @@ -3524,6 +3599,7 @@ private static void RemoveGettingStartedPages() { TabController.Instance.DeleteTab(gettingStartedTabId, portal.PortalID); } + PortalController.DeletePortalSetting(portal.PortalID, "GettingStartedTabId"); } } @@ -3543,154 +3619,97 @@ private static bool DoesLogTypeExists(string logTypeKey) { return false; } - return true; - } - - #endregion - - #region Public Methods - - ///----------------------------------------------------------------------------- - /// - /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals - /// - ///The Name to give this new Tab - /// - ///The Icon for this new Tab - /// - ///A flag indicating whether the tab is visible - ///The Module Deinition Id for the module to be aded to this tab - ///The Module's title - ///The Module's icon - ///Modules Inherit the Pages View Permisions - ///----------------------------------------------------------------------------- - public static void AddAdminPages(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) - { - ArrayList portals = PortalController.Instance.GetPortals(); - - //Add Page to Admin Menu of all configured Portals - for (var index = 0; index <= portals.Count - 1; index++) - { - var portal = (PortalInfo)portals[index]; - - //Create New Admin Page (or get existing one) - var newPage = AddAdminPage(portal, tabName, description, tabIconFile, tabIconFileLarge, isVisible); - - //Add Module To Page - AddModuleToPage(newPage, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); - } - } - - ///----------------------------------------------------------------------------- - /// - /// AddAdminPage adds an Admin Tab Page - /// - ///The Portal - ///The Name to give this new Tab - /// - ///The Icon for this new Tab - /// - ///A flag indicating whether the tab is visible - ///----------------------------------------------------------------------------- - public static TabInfo AddAdminPage(PortalInfo portal, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddAdminPage:" + tabName); - TabInfo adminPage = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, false); - if ((adminPage != null)) - { - var tabPermissionCollection = new TabPermissionCollection(); - AddPagePermission(tabPermissionCollection, "View", Convert.ToInt32(portal.AdministratorRoleId)); - AddPagePermission(tabPermissionCollection, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); - return AddPage(adminPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible, tabPermissionCollection, true); - } - return null; + return true; } - ///----------------------------------------------------------------------------- - /// - /// AddHostPage adds a Host Tab Page - /// - ///The Name to give this new Tab - /// - ///The Icon for this new Tab - /// - ///A flag indicating whether the tab is visible - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// AddHostPage adds a Host Tab Page. + /// + /// The Name to give this new Tab. + /// + /// The Icon for this new Tab. + /// + /// A flag indicating whether the tab is visible. + /// + /// ----------------------------------------------------------------------------- public static TabInfo AddHostPage(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddHostPage:" + tabName); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddHostPage:" + tabName); TabInfo hostPage = TabController.Instance.GetTabByName("Host", Null.NullInteger); - if ((hostPage != null)) + if (hostPage != null) { return AddPage(hostPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible, new TabPermissionCollection(), true); } + return null; } - ///----------------------------------------------------------------------------- - /// - /// AddModuleControl adds a new Module Control to the system - /// - /// - /// - ///The Module Definition Id - ///The key for this control in the Definition - ///The title of this control - ///Te source of ths control - ///The icon file - ///The type of control - ///The vieworder for this module - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// AddModuleControl adds a new Module Control to the system. + /// + /// + /// + /// The Module Definition Id. + /// The key for this control in the Definition. + /// The title of this control. + /// Te source of ths control. + /// The icon file. + /// The type of control. + /// The vieworder for this module. + /// ----------------------------------------------------------------------------- public static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder) { - //Call Overload with HelpUrl = Null.NullString + // Call Overload with HelpUrl = Null.NullString AddModuleControl(moduleDefId, controlKey, controlTitle, controlSrc, iconFile, controlType, viewOrder, Null.NullString); } - ///----------------------------------------------------------------------------- - /// - /// AddModuleDefinition adds a new Core Module Definition to the system - /// - /// - /// This overload asumes the module is an Admin module and not a Premium Module - /// - ///The Friendly Name of the Module to Add - ///Description of the Module - ///The Module Definition Name - ///The Module Definition Id of the new Module - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// AddModuleDefinition adds a new Core Module Definition to the system. + /// + /// + /// This overload asumes the module is an Admin module and not a Premium Module. + /// + /// The Friendly Name of the Module to Add. + /// Description of the Module. + /// The Module Definition Name. + /// The Module Definition Id of the new Module. + /// ----------------------------------------------------------------------------- public static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName) { - //Call overload with Premium=False and Admin=True + // Call overload with Premium=False and Admin=True return AddModuleDefinition(desktopModuleName, description, moduleDefinitionName, false, true); } - ///----------------------------------------------------------------------------- - /// - /// AddModuleToPage adds a module to a Page - /// - /// - /// - ///The Page to add the Module to - ///The Module Deinition Id for the module to be aded to this tab - ///The Module's title - ///The Module's icon - ///Inherit the Pages View Permisions - ///----------------------------------------------------------------------------- - public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) + /// ----------------------------------------------------------------------------- + /// + /// AddModuleToPage adds a module to a Page. + /// + /// + /// + /// The Page to add the Module to. + /// The Module Deinition Id for the module to be aded to this tab. + /// The Module's title. + /// The Module's icon. + /// Inherit the Pages View Permisions. + /// + /// ----------------------------------------------------------------------------- + public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) { return AddModuleToPage(page, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions, true, Globals.glbDefaultPane); } public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions, bool displayTitle, string paneName) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); ModuleInfo moduleInfo; int moduleId = Null.NullInteger; - if ((page != null)) + if (page != null) { bool isDuplicate = false; foreach (var kvp in ModuleController.Instance.GetTabModules(page.TabID)) @@ -3719,7 +3738,7 @@ public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTi AllTabs = false, Visibility = VisibilityState.None, InheritViewPermissions = inheritPermissions, - DisplayTitle = displayTitle + DisplayTitle = displayTitle, }; ModuleController.Instance.InitialModulePermission(moduleInfo, moduleInfo.TabID, inheritPermissions ? 0 : 1); @@ -3729,7 +3748,6 @@ public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTi try { moduleId = ModuleController.Instance.AddModule(moduleInfo); - } catch (Exception exc) { @@ -3738,24 +3756,25 @@ public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTi } } } - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogEnd", Localization.Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); + + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); return moduleId; } - public static int AddModuleToPage(string tabPath, int portalId, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) { int moduleId = Null.NullInteger; int tabID = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString); - if ((tabID != Null.NullInteger)) + if (tabID != Null.NullInteger) { TabInfo tab = TabController.Instance.GetTab(tabID, portalId, true); - if ((tab != null)) + if (tab != null) { moduleId = AddModuleToPage(tab, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); } } + return moduleId; } @@ -3765,10 +3784,10 @@ public static void AddModuleToPages(string tabPath, int moduleDefId, string modu foreach (PortalInfo portal in portals) { int tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - if ((tabID != Null.NullInteger)) + if (tabID != Null.NullInteger) { var tab = TabController.Instance.GetTab(tabID, portal.PortalID, true); - if ((tab != null)) + if (tab != null) { AddModuleToPage(tab, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); } @@ -3778,26 +3797,27 @@ public static void AddModuleToPages(string tabPath, int moduleDefId, string modu /// ----------------------------------------------------------------------------- /// - /// AddPortal manages the Installation of a new DotNetNuke Portal + /// AddPortal manages the Installation of a new DotNetNuke Portal. /// /// /// + /// /// ----------------------------------------------------------------------------- public static int AddPortal(XmlNode node, bool status, int indent, UserInfo superUser = null) { - int portalId = -1; try { string hostMapPath = Globals.HostMapPath; - string childPath = ""; - string domain = ""; + string childPath = string.Empty; + string domain = string.Empty; - if ((HttpContext.Current != null)) + if (HttpContext.Current != null) { - domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install", ""); + domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install", string.Empty); } - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "AddPortal:" + domain); + + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPortal:" + domain); string portalName = XmlUtils.GetNodeValue(node.CreateNavigator(), "portalname"); if (status) { @@ -3822,7 +3842,7 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe bool isChild = bool.Parse(XmlUtils.GetNodeValue(node.CreateNavigator(), "ischild")); string homeDirectory = XmlUtils.GetNodeValue(node.CreateNavigator(), "homedirectory"); - //Get the Portal Alias + // Get the Portal Alias XmlNodeList portalAliases = node.SelectNodes("portalaliases/portalalias"); string strPortalAlias = domain; if (portalAliases != null) @@ -3836,11 +3856,12 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe } } - //Create default email + // Create default email if (string.IsNullOrEmpty(email)) { - email = "admin@" + domain.Replace("www.", ""); - //Remove any domain subfolder information ( if it exists ) + email = "admin@" + domain.Replace("www.", string.Empty); + + // Remove any domain subfolder information ( if it exists ) if (email.IndexOf("/") != -1) { email = email.Substring(0, email.IndexOf("/")); @@ -3855,22 +3876,22 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe var template = FindBestTemplate(templateFileName); var userInfo = superUser ?? CreateUserInfo(firstName, lastName, username, password, email); - - //Create Portal - portalId = PortalController.Instance.CreatePortal(portalName, - userInfo, - description, - keyWords, - template, - homeDirectory, - strPortalAlias, - serverPath, - serverPath + childPath, - isChild); + // Create Portal + portalId = PortalController.Instance.CreatePortal( + portalName, + userInfo, + description, + keyWords, + template, + homeDirectory, + strPortalAlias, + serverPath, + serverPath + childPath, + isChild); if (portalId > -1) { - //Add Extra Aliases + // Add Extra Aliases if (portalAliases != null) { foreach (XmlNode portalAlias in portalAliases) @@ -3884,19 +3905,19 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Creating Site Alias: " + portalAlias.InnerText + "
    "); } } + PortalController.Instance.AddPortalAlias(portalId, portalAlias.InnerText); } } } - //Force Administrator to Update Password on first log in + // Force Administrator to Update Password on first log in PortalInfo portal = PortalController.Instance.GetPortal(portalId); UserInfo adminUser = UserController.GetUserById(portalId, portal.AdministratorId); adminUser.Membership.UpdatePassword = true; UserController.UpdateUser(portalId, adminUser); } - return portalId; } } @@ -3909,18 +3930,21 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Error! " + ex.Message + ex.StackTrace + "
    "); DnnInstallLogger.InstallLogError(ex); } + // failure portalId = -1; } + return portalId; } /// ----------------------------------------------------------------------------- /// - /// Obsolete, AddPortal manages the Installation of a new DotNetNuke Portal + /// Obsolete, AddPortal manages the Installation of a new DotNetNuke Portal. /// /// /// + /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in DNN 9.3.0, will be removed in 11.0.0. Use the overloaded method with the 'superUser' parameter instead. Scheduled removal in v11.0.0.")] public static int AddPortal(XmlNode node, bool status, int indent) @@ -3928,76 +3952,6 @@ public static int AddPortal(XmlNode node, bool status, int indent) return AddPortal(node, status, indent, null); } - internal static UserInfo CreateUserInfo(string firstName, string lastName, string userName, string password, string email) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "CreateUserInfo:" + userName); - var adminUser = new UserInfo - { - FirstName = firstName, - LastName = lastName, - Username = userName, - DisplayName = firstName + " " + lastName, - Membership = { Password = password }, - Email = email, - IsSuperUser = false - }; - adminUser.Membership.Approved = true; - adminUser.Profile.FirstName = firstName; - adminUser.Profile.LastName = lastName; - adminUser.Membership.UpdatePassword = true; - return adminUser; - } - - internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName, string currentCulture) - { - if (string.IsNullOrEmpty(currentCulture)) - currentCulture = Localization.Localization.SystemLocale; - - var templates = PortalController.Instance.GetAvailablePortalTemplates(); - - var defaultTemplates = - templates.Where(x => Path.GetFileName(x.TemplateFilePath) == templateFileName).ToList(); - - var match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant() == currentCulture); - if (match == null) - { - match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant().StartsWith(currentCulture.Substring(0, 2))); - } - if (match == null) - { - match = defaultTemplates.FirstOrDefault(x => string.IsNullOrEmpty(x.CultureCode)); - } - - if (match == null) - { - throw new Exception("Unable to locate specified portal template: " + templateFileName); - } - - return match; - } - - internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName) - { - //Load Template - var installTemplate = new XmlDocument { XmlResolver = null }; - Upgrade.GetInstallTemplate(installTemplate); - //Parse the root node - XmlNode rootNode = installTemplate.SelectSingleNode("//dotnetnuke"); - String currentCulture = ""; - if (rootNode != null) - { - currentCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture"); - } - - if (String.IsNullOrEmpty(currentCulture)) - { - currentCulture = Localization.Localization.SystemLocale; - } - currentCulture = currentCulture.ToLowerInvariant(); - - return FindBestTemplate(templateFileName, currentCulture); - } - public static string BuildUserTable(IDataReader dr, string header, string message) { string warnings = Null.NullString; @@ -4033,14 +3987,14 @@ public static string BuildUserTable(IDataReader dr, string header, string messag warnings = stringBuilder.ToString(); } - return warnings; } /// ----------------------------------------------------------------------------- /// - /// CheckUpgrade checks whether there are any possible upgrade issues + /// CheckUpgrade checks whether there are any possible upgrade issues. /// + /// /// ----------------------------------------------------------------------------- public static string CheckUpgrade() { @@ -4071,37 +4025,113 @@ public static string CheckUpgrade() warnings += ex.Message; } - try + try + { + using (dr = dataProvider.ExecuteReader("GetUserCount")) + { + dr.Read(); + int userCount = dr.GetInt32(0); + + // ReSharper disable PossibleLossOfFraction + double time = userCount / 10834; + + // ReSharper restore PossibleLossOfFraction + if (userCount > 1000) + { + warnings += "

    More than 1000 Users

    This DotNetNuke Database has " + userCount + + " users. As the users and their profiles are transferred to a new format, it is estimated that the script will take ~" + time.ToString("F2") + + " minutes to execute.

    "; + } + } + } + catch (Exception ex) + { + Logger.Error(ex); + warnings += Environment.NewLine + Environment.NewLine + ex.Message; + } + + return warnings; + } + + internal static UserInfo CreateUserInfo(string firstName, string lastName, string userName, string password, string email) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "CreateUserInfo:" + userName); + var adminUser = new UserInfo + { + FirstName = firstName, + LastName = lastName, + Username = userName, + DisplayName = firstName + " " + lastName, + Membership = { Password = password }, + Email = email, + IsSuperUser = false, + }; + adminUser.Membership.Approved = true; + adminUser.Profile.FirstName = firstName; + adminUser.Profile.LastName = lastName; + adminUser.Membership.UpdatePassword = true; + return adminUser; + } + + internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName, string currentCulture) + { + if (string.IsNullOrEmpty(currentCulture)) + { + currentCulture = Localization.SystemLocale; + } + + var templates = PortalController.Instance.GetAvailablePortalTemplates(); + + var defaultTemplates = + templates.Where(x => Path.GetFileName(x.TemplateFilePath) == templateFileName).ToList(); + + var match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant() == currentCulture); + if (match == null) + { + match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant().StartsWith(currentCulture.Substring(0, 2))); + } + + if (match == null) + { + match = defaultTemplates.FirstOrDefault(x => string.IsNullOrEmpty(x.CultureCode)); + } + + if (match == null) + { + throw new Exception("Unable to locate specified portal template: " + templateFileName); + } + + return match; + } + + internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName) + { + // Load Template + var installTemplate = new XmlDocument { XmlResolver = null }; + Upgrade.GetInstallTemplate(installTemplate); + + // Parse the root node + XmlNode rootNode = installTemplate.SelectSingleNode("//dotnetnuke"); + string currentCulture = string.Empty; + if (rootNode != null) { - using (dr = dataProvider.ExecuteReader("GetUserCount")) - { - dr.Read(); - int userCount = dr.GetInt32(0); - // ReSharper disable PossibleLossOfFraction - double time = userCount / 10834; - // ReSharper restore PossibleLossOfFraction - if (userCount > 1000) - { - warnings += "

    More than 1000 Users

    This DotNetNuke Database has " + userCount + - " users. As the users and their profiles are transferred to a new format, it is estimated that the script will take ~" + time.ToString("F2") + - " minutes to execute.

    "; - } - } + currentCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture"); } - catch (Exception ex) + + if (string.IsNullOrEmpty(currentCulture)) { - Logger.Error(ex); - warnings += Environment.NewLine + Environment.NewLine + ex.Message; + currentCulture = Localization.SystemLocale; } + currentCulture = currentCulture.ToLowerInvariant(); - return warnings; + return FindBestTemplate(templateFileName, currentCulture); } /// ----------------------------------------------------------------------------- /// /// DeleteInstallerFiles - clean up install config and installwizard files - /// If installwizard is ran again this will be recreated via the dotnetnuke.install.config.resources file + /// If installwizard is ran again this will be recreated via the dotnetnuke.install.config.resources file. /// /// /// uses FileSystemUtils.DeleteFile as it checks for readonly attribute status @@ -4140,20 +4170,21 @@ public static void DeleteInstallerFiles() /// ----------------------------------------------------------------------------- /// - /// DeleteFiles - clean up deprecated files and folders + /// DeleteFiles - clean up deprecated files and folders. /// /// /// - /// Path to provider - /// The Version being Upgraded - /// Display status in UI? + /// Path to provider. + /// The Version being Upgraded. + /// Display status in UI?. + /// /// ----------------------------------------------------------------------------- public static string DeleteFiles(string providerPath, Version version, bool writeFeedback) { var stringVersion = GetStringVersionWithRevision(version); - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "DeleteFiles:" + stringVersion); - string exceptions = ""; + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "DeleteFiles:" + stringVersion); + string exceptions = string.Empty; if (writeFeedback) { HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Cleaning Up Files: " + stringVersion); @@ -4172,6 +4203,7 @@ public static string DeleteFiles(string providerPath, Version version, bool writ Logger.Error("Error cleanup file " + listFile, ex); exceptions += $"Error: {ex.Message + ex.StackTrace}{Environment.NewLine}"; + // log the results DnnInstallLogger.InstallLogError(exceptions); try @@ -4190,44 +4222,35 @@ public static string DeleteFiles(string providerPath, Version version, bool writ if (writeFeedback) { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, (string.IsNullOrEmpty(exceptions))); + HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions)); } return exceptions; } - private static string GetStringVersionWithRevision(Version version) - { - var stringVersion = GetStringVersion(version); - if (version.Revision > 0) - { - stringVersion += "." + version.Revision.ToString("D2"); - } - return stringVersion; - } - - ///----------------------------------------------------------------------------- - /// + /// ----------------------------------------------------------------------------- + /// /// ExecuteScripts manages the Execution of Scripts from the Install/Scripts folder. - /// It is also triggered by InstallDNN and UpgradeDNN - /// - /// - /// - ///The path to the Data Provider - ///----------------------------------------------------------------------------- + /// It is also triggered by InstallDNN and UpgradeDNN. + /// + /// + /// + /// The path to the Data Provider. + /// ----------------------------------------------------------------------------- public static void ExecuteScripts(string strProviderPath) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "ExecuteScripts:" + strProviderPath); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ExecuteScripts:" + strProviderPath); string scriptPath = Globals.ApplicationMapPath + "\\Install\\Scripts\\"; if (Directory.Exists(scriptPath)) { string[] files = Directory.GetFiles(scriptPath); foreach (string file in files) { - //Execute if script is a provider script + // Execute if script is a provider script if (file.IndexOf("." + DefaultProvider) != -1) { ExecuteScript(file, true); + // delete the file try { @@ -4243,32 +4266,43 @@ public static void ExecuteScripts(string strProviderPath) } } - ///----------------------------------------------------------------------------- - /// - /// ExecuteScript executes a special script - /// - /// - /// - ///The script file to execute - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// ExecuteScript executes a special script. + /// + /// + /// + /// The script file to execute. + /// ----------------------------------------------------------------------------- public static void ExecuteScript(string file) { - //Execute if script is a provider script + // Execute if script is a provider script if (file.IndexOf("." + DefaultProvider) != -1) { ExecuteScript(file, true); } } - ///----------------------------------------------------------------------------- - /// - /// GetInstallTemplate retrieves the Installation Template as specifeid in web.config - /// - /// - /// - ///The Xml Document to load - ///A string which contains the error message - if appropriate - ///----------------------------------------------------------------------------- + private static string GetStringVersionWithRevision(Version version) + { + var stringVersion = GetStringVersion(version); + if (version.Revision > 0) + { + stringVersion += "." + version.Revision.ToString("D2"); + } + + return stringVersion; + } + + /// ----------------------------------------------------------------------------- + /// + /// GetInstallTemplate retrieves the Installation Template as specifeid in web.config. + /// + /// + /// + /// The Xml Document to load. + /// A string which contains the error message - if appropriate. + /// ----------------------------------------------------------------------------- public static string GetInstallTemplate(XmlDocument xmlDoc) { string errorMessage = Null.NullString; @@ -4287,10 +4321,10 @@ public static string GetInstallTemplate(XmlDocument xmlDoc) } /// - /// SetInstalltemplate saves the XmlDocument back to Installation Template specified in web.config + /// SetInstalltemplate saves the XmlDocument back to Installation Template specified in web.config. /// - /// The Xml Document to save - /// A string which contains the error massage - if appropriate + /// The Xml Document to save. + /// A string which contains the error massage - if appropriate. public static string SetInstallTemplate(XmlDocument xmlDoc) { string errorMessage = Null.NullString; @@ -4298,7 +4332,7 @@ public static string SetInstallTemplate(XmlDocument xmlDoc) string filePath = Globals.ApplicationMapPath + "\\Install\\" + installTemplate; try { - //ensure the file is not read-only + // ensure the file is not read-only var attributes = File.GetAttributes(filePath); if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { @@ -4318,22 +4352,23 @@ public static string SetInstallTemplate(XmlDocument xmlDoc) return errorMessage; } - ///----------------------------------------------------------------------------- - /// + /// ----------------------------------------------------------------------------- + /// /// GetInstallVersion retrieves the Base Instal Version as specifeid in the install - /// template - /// - /// - /// - ///The Install Template - ///----------------------------------------------------------------------------- + /// template. + /// + /// + /// + /// The Install Template. + /// + /// ----------------------------------------------------------------------------- public static Version GetInstallVersion(XmlDocument xmlDoc) { string version = Null.NullString; - //get base version + // get base version XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke"); - if ((node != null)) + if (node != null) { version = XmlUtils.GetNodeValue(node.CreateNavigator(), "version"); } @@ -4341,42 +4376,45 @@ public static Version GetInstallVersion(XmlDocument xmlDoc) return new Version(version); } - ///----------------------------------------------------------------------------- - /// - /// GetLogFile gets the filename for the version's log file - /// - /// - /// - ///The path to the Data Provider - ///The Version - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// GetLogFile gets the filename for the version's log file. + /// + /// + /// + /// The path to the Data Provider. + /// The Version. + /// + /// ----------------------------------------------------------------------------- public static string GetLogFile(string providerPath, Version version) { return providerPath + GetStringVersion(version) + ".log.resources"; } - ///----------------------------------------------------------------------------- - /// - /// GetScriptFile gets the filename for the version - /// - /// - /// - ///The path to the Data Provider - ///The Version - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// GetScriptFile gets the filename for the version. + /// + /// + /// + /// The path to the Data Provider. + /// The Version. + /// + /// ----------------------------------------------------------------------------- public static string GetScriptFile(string providerPath, Version version) { return providerPath + GetStringVersion(version) + "." + DefaultProvider; } - ///----------------------------------------------------------------------------- - /// - /// GetStringVersion gets the Version String (xx.xx.xx) from the Version - /// - /// - /// - ///The Version - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// GetStringVersion gets the Version String (xx.xx.xx) from the Version. + /// + /// + /// + /// The Version. + /// + /// ----------------------------------------------------------------------------- public static string GetStringVersion(Version version) { var versionArray = new int[3]; @@ -4398,36 +4436,39 @@ public static string GetStringVersion(Version version) { stringVersion += versionArray[i].ToString(); } + if (i < 2) { stringVersion += "."; } } + return stringVersion; } - ///----------------------------------------------------------------------------- - /// - /// GetSuperUser gets the superuser from the Install Template - /// - /// - /// - ///The install Templae - ///a flag to determine whether to output feedback - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// GetSuperUser gets the superuser from the Install Template. + /// + /// + /// + /// The install Templae. + /// a flag to determine whether to output feedback. + /// + /// ----------------------------------------------------------------------------- public static UserInfo GetSuperUser(XmlDocument xmlTemplate, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "GetSuperUser"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "GetSuperUser"); XmlNode node = xmlTemplate.SelectSingleNode("//dotnetnuke/superuser"); UserInfo superUser = null; - if ((node != null)) + if (node != null) { if (writeFeedback) { HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Configuring SuperUser:
    "); } - //Parse the SuperUsers nodes + // Parse the SuperUsers nodes string firstName = XmlUtils.GetNodeValue(node.CreateNavigator(), "firstname"); string lastName = XmlUtils.GetNodeValue(node.CreateNavigator(), "lastname"); string username = XmlUtils.GetNodeValue(node.CreateNavigator(), "username"); @@ -4445,7 +4486,7 @@ public static UserInfo GetSuperUser(XmlDocument xmlTemplate, bool writeFeedback) DisplayName = firstName + " " + lastName, Membership = { Password = password }, Email = email, - IsSuperUser = true + IsSuperUser = true, }; superUser.Membership.Approved = true; @@ -4459,19 +4500,21 @@ public static UserInfo GetSuperUser(XmlDocument xmlTemplate, bool writeFeedback) superUser.Membership.UpdatePassword = true; } } + return superUser; } - ///----------------------------------------------------------------------------- - /// + /// ----------------------------------------------------------------------------- + /// /// GetUpgradeScripts gets an ArrayList of the Scripts required to Upgrade to the - /// current Assembly Version - /// - /// - /// - ///The path to the Data Provider - ///The current Database Version - ///----------------------------------------------------------------------------- + /// current Assembly Version. + /// + /// + /// + /// The path to the Data Provider. + /// The current Database Version. + /// + /// ----------------------------------------------------------------------------- public static ArrayList GetUpgradeScripts(string providerPath, Version databaseVersion) { var scriptFiles = new ArrayList(); @@ -4482,17 +4525,19 @@ public static ArrayList GetUpgradeScripts(string providerPath, Version databaseV foreach (string file in files) { - // script file name must conform to ##.##.##.DefaultProviderName + // script file name must conform to ##.##.##.DefaultProviderName if (file != null) { if (GetFileName(file).Length == 9 + DefaultProvider.Length) { var version = new Version(GetFileNameWithoutExtension(file)); + // check if script file is relevant for upgrade if (version > databaseVersion && version <= ApplicationVersion && GetFileName(file).Length == 9 + DefaultProvider.Length) { scriptFiles.Add(file); - //check if any incrementals exist + + // check if any incrementals exist var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); if (incrementalfiles != null) { @@ -4504,7 +4549,6 @@ public static ArrayList GetUpgradeScripts(string providerPath, Version databaseV if (version == databaseVersion && version <= ApplicationVersion && GetFileName(file).Length == 9 + DefaultProvider.Length) { - var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); if (incrementalfiles != null) { @@ -4514,62 +4558,41 @@ public static ArrayList GetUpgradeScripts(string providerPath, Version databaseV Logger.TraceFormat("GetUpgradedScripts including {0}", file); } - //else - //{ + // else + // { // Logger.TraceFormat("GetUpgradedScripts excluding {0}", file); - //} + // } } } } - return scriptFiles; } - private static string[] AddAvailableIncrementalFiles(string providerPath, Version version) - { - if (version.Major < 8) - { - return null; - } - - var files = Directory.GetFiles(providerPath, GetStringVersion(version) + ".*." + DefaultProvider); - Array.Sort(files); // The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required. - - return files; - - - } - - private static string GetFileName(string file) - { - return Path.GetFileName(file); - } - - ///----------------------------------------------------------------------------- - /// - /// InitialiseHostSettings gets the Host Settings from the Install Template - /// - /// - /// - ///The install Templae - ///a flag to determine whether to output feedback - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// InitialiseHostSettings gets the Host Settings from the Install Template. + /// + /// + /// + /// The install Templae. + /// a flag to determine whether to output feedback. + /// ----------------------------------------------------------------------------- public static void InitialiseHostSettings(XmlDocument xmlTemplate, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InitialiseHostSettings"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InitialiseHostSettings"); XmlNode node = xmlTemplate.SelectSingleNode("//dotnetnuke/settings"); - if ((node != null)) + if (node != null) { if (writeFeedback) { HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Settings:
    "); } - //Need to clear the cache to pick up new HostSettings from the SQLDataProvider script + // Need to clear the cache to pick up new HostSettings from the SQLDataProvider script DataCache.RemoveCache(DataCache.HostSettingsCacheKey); - //Parse the Settings nodes + // Parse the Settings nodes foreach (XmlNode settingNode in node.ChildNodes) { string settingName = settingNode.Name; @@ -4578,7 +4601,7 @@ public static void InitialiseHostSettings(XmlDocument xmlTemplate, bool writeFee { XmlAttribute secureAttrib = settingNode.Attributes["Secure"]; bool settingIsSecure = false; - if ((secureAttrib != null)) + if (secureAttrib != null) { if (secureAttrib.Value.ToLowerInvariant() == "true") { @@ -4595,16 +4618,17 @@ public static void InitialiseHostSettings(XmlDocument xmlTemplate, bool writeFee { settingValue = domainName; } + break; case "HostEmail": if (string.IsNullOrEmpty(settingValue)) { settingValue = "support@" + domainName; - //Remove any folders + // Remove any folders settingValue = settingValue.Substring(0, settingValue.IndexOf("/")); - //Remove port number + // Remove port number if (settingValue.IndexOf(":") != -1) { settingValue = settingValue.Substring(0, settingValue.IndexOf(":")); @@ -4614,41 +4638,40 @@ public static void InitialiseHostSettings(XmlDocument xmlTemplate, bool writeFee break; } - HostController.Instance.Update(settingName, settingValue, settingIsSecure); } } } } - ///----------------------------------------------------------------------------- - /// + /// ----------------------------------------------------------------------------- + /// /// InstallDatabase runs all the "scripts" identifed in the Install Template to - /// install the base version - /// - /// - /// - /// - ///The Xml Document to load - ///A flag that determines whether to output feedback to the Response Stream - /// - ///A string which contains the error message - if appropriate - ///----------------------------------------------------------------------------- + /// install the base version. + /// + /// + /// + /// + /// The Xml Document to load. + /// A flag that determines whether to output feedback to the Response Stream. + /// + /// A string which contains the error message - if appropriate. + /// ----------------------------------------------------------------------------- public static string InstallDatabase(Version version, string providerPath, XmlDocument xmlDoc, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InstallDatabase:" + Globals.FormatVersion(version)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallDatabase:" + Globals.FormatVersion(version)); string defaultProvider = Config.GetDefaultProvider("data").Name; string message = Null.NullString; - //Output feedback line + // Output feedback line if (writeFeedback) { HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Version: " + Globals.FormatVersion(version) + "
    "); } - //Parse the script nodes + // Parse the script nodes XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke/scripts"); - if ((node != null)) + if (node != null) { // Loop through the available scripts message = (from XmlNode scriptNode in node.SelectNodes("script") select scriptNode.InnerText + "." + defaultProvider).Aggregate(message, (current, script) => current + ExecuteScript(providerPath + script, writeFeedback)); @@ -4657,23 +4680,41 @@ public static string InstallDatabase(Version version, string providerPath, XmlDo // update the version Globals.UpdateDataBaseVersion(version); - //Optionally Install the memberRoleProvider + // Optionally Install the memberRoleProvider message += InstallMemberRoleProvider(providerPath, writeFeedback); return message; } - ///----------------------------------------------------------------------------- - /// - /// InstallDNN manages the Installation of a new DotNetNuke Application - /// - /// - /// - ///The path to the Data Provider - ///----------------------------------------------------------------------------- + private static string[] AddAvailableIncrementalFiles(string providerPath, Version version) + { + if (version.Major < 8) + { + return null; + } + + var files = Directory.GetFiles(providerPath, GetStringVersion(version) + ".*." + DefaultProvider); + Array.Sort(files); // The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required. + + return files; + } + + private static string GetFileName(string file) + { + return Path.GetFileName(file); + } + + /// ----------------------------------------------------------------------------- + /// + /// InstallDNN manages the Installation of a new DotNetNuke Application. + /// + /// + /// + /// The path to the Data Provider. + /// ----------------------------------------------------------------------------- public static void InstallDNN(string strProviderPath) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InstallDNN:" + strProviderPath); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallDNN:" + strProviderPath); var xmlDoc = new XmlDocument { XmlResolver = null }; // open the Install Template XML file @@ -4681,19 +4722,19 @@ public static void InstallDNN(string strProviderPath) if (string.IsNullOrEmpty(errorMessage)) { - //get base version + // get base version Version baseVersion = GetInstallVersion(xmlDoc); - //Install Base Version + // Install Base Version InstallDatabase(baseVersion, strProviderPath, xmlDoc, true); - //Call Upgrade with the current DB Version to carry out any incremental upgrades + // Call Upgrade with the current DB Version to carry out any incremental upgrades UpgradeDNN(strProviderPath, baseVersion); // parse Host Settings if available InitialiseHostSettings(xmlDoc, true); - //Create SuperUser only when it's not there (even soft deleted) + // Create SuperUser only when it's not there (even soft deleted) var superUsers = UserController.GetUsers(true, true, Null.NullInteger); if (superUsers == null || superUsers.Count == 0) { @@ -4706,25 +4747,25 @@ public static void InstallDNN(string strProviderPath) // parse File List if available InstallFiles(xmlDoc, true); - //Run any addition scripts in the Scripts folder + // Run any addition scripts in the Scripts folder HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing Additional Scripts:
    "); ExecuteScripts(strProviderPath); - //Install optional resources if present + // Install optional resources if present var packages = GetInstallPackages(); foreach (var package in packages) { InstallPackage(package.Key, package.Value.PackageType, true); } - //Set Status to None + // Set Status to None Globals.SetStatus(Globals.UpgradeStatus.None); - //download LP (and templates) if not using en-us + // download LP (and templates) if not using en-us IInstallationStep ensureLpAndTemplate = new UpdateLanguagePackStep(); ensureLpAndTemplate.Execute(); - //install LP that contains templates if installing in a different language + // install LP that contains templates if installing in a different language var installConfig = InstallController.Instance.GetInstallConfig(); string culture = installConfig.InstallCulture; if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) @@ -4738,17 +4779,15 @@ public static void InstallDNN(string strProviderPath) } } - - // parse portal(s) if available XmlNodeList nodes = xmlDoc.SelectNodes("//dotnetnuke/portals/portal"); if (nodes != null) { foreach (XmlNode node in nodes) { - if ((node != null)) + if (node != null) { - //add item to identity install from install wizard. + // add item to identity install from install wizard. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("InstallFromWizard", true); @@ -4770,8 +4809,8 @@ public static void InstallDNN(string strProviderPath) } else { - //500 Error - Redirect to ErrorPage - if ((HttpContext.Current != null)) + // 500 Error - Redirect to ErrorPage + if (HttpContext.Current != null) { string url = "~/ErrorPage.aspx?status=500&error=" + errorMessage; HttpContext.Current.Response.Clear(); @@ -4780,41 +4819,43 @@ public static void InstallDNN(string strProviderPath) } } - ///----------------------------------------------------------------------------- - /// - /// InstallFiles intsalls any files listed in the Host Install Configuration file - /// - /// - /// - ///The Xml Document to load - ///A flag that determines whether to output feedback to the Response Stream - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// InstallFiles intsalls any files listed in the Host Install Configuration file. + /// + /// + /// + /// The Xml Document to load. + /// A flag that determines whether to output feedback to the Response Stream. + /// ----------------------------------------------------------------------------- public static void InstallFiles(XmlDocument xmlDoc, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InstallFiles"); - //Parse the file nodes + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallFiles"); + + // Parse the file nodes XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke/files"); - if ((node != null)) + if (node != null) { if (writeFeedback) { HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Files:
    "); } + ParseFiles(node, Null.NullInteger); } - //Synchronise Host Folder + // Synchronise Host Folder if (writeFeedback) { HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Synchronizing Host Files:
    "); } - FolderManager.Instance.Synchronize(Null.NullInteger, "", true, true); + FolderManager.Instance.Synchronize(Null.NullInteger, string.Empty, true, true); } public static bool InstallPackage(string file, string packageType, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InstallPackage:" + file); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackage:" + file); bool success = Null.NullBoolean; if (writeFeedback) { @@ -4827,9 +4868,9 @@ public static bool InstallPackage(string file, string packageType, bool writeFee deleteTempFolder = Null.NullBoolean; } - var installer = new Installer.Installer(new FileStream(file, FileMode.Open, FileAccess.Read), Globals.ApplicationMapPath, true, deleteTempFolder); + var installer = new Installer(new FileStream(file, FileMode.Open, FileAccess.Read), Globals.ApplicationMapPath, true, deleteTempFolder); - //Check if manifest is valid + // Check if manifest is valid if (installer.IsValid) { installer.InstallerInfo.RepairInstall = true; @@ -4839,10 +4880,10 @@ public static bool InstallPackage(string file, string packageType, bool writeFee { if (installer.InstallerInfo.ManifestFile == null) { - //Missing manifest + // Missing manifest if (packageType == "Skin" || packageType == "Container") { - //Legacy Skin/Container + // Legacy Skin/Container string tempInstallFolder = installer.TempInstallFolder; string manifestFile = Path.Combine(tempInstallFolder, Path.GetFileNameWithoutExtension(file) + ".dnn"); using (var manifestWriter = new StreamWriter(manifestFile)) @@ -4850,22 +4891,22 @@ public static bool InstallPackage(string file, string packageType, bool writeFee manifestWriter.Write(LegacyUtil.CreateSkinManifest(file, packageType, tempInstallFolder)); } - installer = new Installer.Installer(tempInstallFolder, manifestFile, HttpContext.Current.Request.MapPath("."), true); + installer = new Installer(tempInstallFolder, manifestFile, HttpContext.Current.Request.MapPath("."), true); - //Set the Repair flag to true for Batch Install + // Set the Repair flag to true for Batch Install installer.InstallerInfo.RepairInstall = true; success = installer.Install(); } else if (Globals.Status != Globals.UpgradeStatus.None) { - var message = string.Format(Localization.Localization.GetString("InstallPackageError", Localization.Localization.ExceptionsResourceFile), file, "Manifest file missing"); + var message = string.Format(Localization.GetString("InstallPackageError", Localization.ExceptionsResourceFile), file, "Manifest file missing"); DnnInstallLogger.InstallLogError(message); } } else { - //log the failure log when installer is invalid and not caught by mainfest file missing. + // log the failure log when installer is invalid and not caught by mainfest file missing. foreach (var log in installer.InstallerInfo.Log.Logs .Where(l => l.Type == LogType.Failure)) { @@ -4881,6 +4922,7 @@ public static bool InstallPackage(string file, string packageType, bool writeFee { HtmlUtils.WriteSuccessError(HttpContext.Current.Response, success); } + if (success) { // delete file @@ -4894,11 +4936,12 @@ public static bool InstallPackage(string file, string packageType, bool writeFee Logger.Error(exc); } } + return success; } /// - /// Gets a ist of installable extensions sorted to ensure dependencies are installed first + /// Gets a ist of installable extensions sorted to ensure dependencies are installed first. /// /// public static IDictionary GetInstallPackages() @@ -4910,7 +4953,7 @@ public static IDictionary GetInstallPackages() ParsePackagesFromApplicationPath(packageTypes, packages, invalidPackages); - //Add packages with no dependency requirements + // Add packages with no dependency requirements var sortedPackages = packages.Where(p => p.Value.Dependencies.Count == 0).ToDictionary(p => p.Key, p => p.Value); var prevDependentCount = -1; @@ -4930,20 +4973,79 @@ public static IDictionary GetInstallPackages() addedPackages.Add(package.Key); } } + foreach (var packageKey in addedPackages) { dependentPackages.Remove(packageKey); } + dependentCount = dependentPackages.Count; } - //Add any packages whose dependency cannot be resolved - foreach (var package in dependentPackages) - { - sortedPackages.Add(package.Key, package.Value); + // Add any packages whose dependency cannot be resolved + foreach (var package in dependentPackages) + { + sortedPackages.Add(package.Key, package.Value); + } + + return sortedPackages; + } + + public static void InstallPackages(string packageType, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackages:" + packageType); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Optional " + packageType + "s:
    "); + } + + string installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; + if (Directory.Exists(installPackagePath)) + { + foreach (string file in Directory.GetFiles(installPackagePath)) + { + if (Path.GetExtension(file.ToLowerInvariant()) == ".zip" /*|| installLanguage */) + { + InstallPackage(file, packageType, writeFeedback); + } + } + } + } + + public static bool IsNETFrameworkCurrent(string version) + { + bool isCurrent = Null.NullBoolean; + switch (version) + { + case "3.5": + // Try and instantiate a 3.5 Class + if (Reflection.CreateType("System.Data.Linq.DataContext", true) != null) + { + isCurrent = true; + } + + break; + case "4.0": + // Look for requestValidationMode attribute + XmlDocument configFile = Config.Load(); + XPathNavigator configNavigator = configFile.CreateNavigator().SelectSingleNode("//configuration/system.web/httpRuntime|//configuration/location/system.web/httpRuntime"); + if (configNavigator != null && !string.IsNullOrEmpty(configNavigator.GetAttribute("requestValidationMode", string.Empty))) + { + isCurrent = true; + } + + break; + case "4.5": + // Try and instantiate a 4.5 Class + if (Reflection.CreateType("System.Reflection.ReflectionContext", true) != null) + { + isCurrent = true; + } + + break; } - return sortedPackages; + return isCurrent; } private static void ParsePackagesFromApplicationPath(IEnumerable packageTypes, Dictionary packages, List invalidPackages) @@ -4951,10 +5053,17 @@ private static void ParsePackagesFromApplicationPath(IEnumerable package foreach (var packageType in packageTypes) { var installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; - if (!Directory.Exists(installPackagePath)) { continue; } + if (!Directory.Exists(installPackagePath)) + { + continue; + } var files = Directory.GetFiles(installPackagePath); - if (files.Length <= 0) { continue; } + if (files.Length <= 0) + { + continue; + } + Array.Sort(files); // The order of the returned file names is not guaranteed on certain NAS systems; use the Sort method if a specific sort order is required. var optionalPackages = new List(); @@ -4969,10 +5078,11 @@ private static void ParsePackagesFromApplicationPath(IEnumerable package PackageController.ParsePackage(file, installPackagePath, packages, invalidPackages); if (packages.ContainsKey(file)) { - //check whether have version conflict and remove old version. + // check whether have version conflict and remove old version. var package = packages[file]; - var installedPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, + var installedPackage = PackageController.Instance.GetExtensionPackage( + Null.NullInteger, p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.PackageType.Equals(package.PackageType, StringComparison.OrdinalIgnoreCase)); @@ -4982,7 +5092,7 @@ private static void ParsePackagesFromApplicationPath(IEnumerable package var oldPackages = packages.Where(kvp => kvp.Value.FriendlyName.Equals(package.FriendlyName, StringComparison.OrdinalIgnoreCase) && kvp.Value.Version < package.Version).ToList(); - //if there already have higher version installed, remove current one from list. + // if there already have higher version installed, remove current one from list. if (installedPackage != null && package.Version <= installedPackage.Version) { oldPackages.Add(new KeyValuePair(file, package)); @@ -4999,7 +5109,7 @@ private static void ParsePackagesFromApplicationPath(IEnumerable package } catch (Exception) { - //do nothing here. + // do nothing here. } } } @@ -5012,7 +5122,7 @@ private static void ParsePackagesFromApplicationPath(IEnumerable package } } - //remove optional + // remove optional optionalPackages.ForEach(f => { if (packages.ContainsKey(f)) @@ -5023,69 +5133,15 @@ private static void ParsePackagesFromApplicationPath(IEnumerable package } } - public static void InstallPackages(string packageType, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "InstallPackages:" + packageType); - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Optional " + packageType + "s:
    "); - } - string installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; - if (Directory.Exists(installPackagePath)) - { - foreach (string file in Directory.GetFiles(installPackagePath)) - { - - if (Path.GetExtension(file.ToLowerInvariant()) == ".zip" /*|| installLanguage */) - { - - InstallPackage(file, packageType, writeFeedback); - } - } - } - } - - public static bool IsNETFrameworkCurrent(string version) - { - bool isCurrent = Null.NullBoolean; - switch (version) - { - case "3.5": - //Try and instantiate a 3.5 Class - if (Reflection.CreateType("System.Data.Linq.DataContext", true) != null) - { - isCurrent = true; - } - break; - case "4.0": - //Look for requestValidationMode attribute - XmlDocument configFile = Config.Load(); - XPathNavigator configNavigator = configFile.CreateNavigator().SelectSingleNode("//configuration/system.web/httpRuntime|//configuration/location/system.web/httpRuntime"); - if (configNavigator != null && !string.IsNullOrEmpty(configNavigator.GetAttribute("requestValidationMode", ""))) - { - isCurrent = true; - } - break; - case "4.5": - //Try and instantiate a 4.5 Class - if (Reflection.CreateType("System.Reflection.ReflectionContext", true) != null) - { - isCurrent = true; - } - break; - } - return isCurrent; - } - public static void RemoveAdminPages(string tabPath) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveAdminPages:" + tabPath); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveAdminPages:" + tabPath); var portals = PortalController.Instance.GetPortals(); foreach (PortalInfo portal in portals) { var tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - if ((tabID != Null.NullInteger)) + if (tabID != Null.NullInteger) { TabController.Instance.DeleteTab(tabID, portal.PortalID); } @@ -5094,7 +5150,7 @@ public static void RemoveAdminPages(string tabPath) public static void RemoveHostPage(string pageName) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "RemoveHostPage:" + pageName); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveHostPage:" + pageName); TabInfo skinsTab = TabController.Instance.GetTabByName(pageName, Null.NullInteger); if (skinsTab != null) { @@ -5104,8 +5160,7 @@ public static void RemoveHostPage(string pageName) public static void StartTimer() { - //Start Upgrade Timer - + // Start Upgrade Timer _startTime = DateTime.Now; } @@ -5116,66 +5171,68 @@ public static void TryUpgradeNETFramework() case "3.5": if (!IsNETFrameworkCurrent("3.5")) { - //Upgrade to .NET 3.5 + // Upgrade to .NET 3.5 string upgradeFile = string.Format("{0}\\Config\\Net35.config", Globals.InstallMapPath); string message = UpdateConfig(upgradeFile, ApplicationVersion, ".NET 3.5 Upgrade"); if (string.IsNullOrEmpty(message)) { - //Remove old AJAX file + // Remove old AJAX file FileSystemUtils.DeleteFile(Path.Combine(Globals.ApplicationMapPath, "bin\\System.Web.Extensions.dll")); - //Log Upgrade - + // Log Upgrade EventLogController.Instance.AddLog("UpgradeNet", "Upgraded Site to .NET 3.5", PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_ALERT); } else { - //Log Failed Upgrade + // Log Failed Upgrade EventLogController.Instance.AddLog("UpgradeNet", string.Format("Upgrade to .NET 3.5 failed. Error reported during attempt to update:{0}", message), PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_ALERT); } } + break; case "4.0": if (!IsNETFrameworkCurrent("4.0")) { - //Upgrade to .NET 4.0 + // Upgrade to .NET 4.0 string upgradeFile = string.Format("{0}\\Config\\Net40.config", Globals.InstallMapPath); string strMessage = UpdateConfig(upgradeFile, ApplicationVersion, ".NET 4.0 Upgrade"); - EventLogController.Instance.AddLog("UpgradeNet", - string.IsNullOrEmpty(strMessage) + EventLogController.Instance.AddLog( + "UpgradeNet", + string.IsNullOrEmpty(strMessage) ? "Upgraded Site to .NET 4.0" : string.Format("Upgrade to .NET 4.0 failed. Error reported during attempt to update:{0}", strMessage), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.HOST_ALERT); + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.HOST_ALERT); } + break; } } - ///----------------------------------------------------------------------------- - /// + /// ----------------------------------------------------------------------------- + /// /// UpgradeApplication - This overload is used for general application upgrade operations. - /// - /// + /// + /// /// Since it is not version specific and is invoked whenever the application is /// restarted, the operations must be re-executable. - /// - ///----------------------------------------------------------------------------- + ///
    + /// ----------------------------------------------------------------------------- public static void UpgradeApplication() { try { - //Remove UpdatePanel from Login Control - not neccessary in popup. + // Remove UpdatePanel from Login Control - not neccessary in popup. var loginControl = ModuleControlController.GetModuleControlByControlKey("Login", -1); loginControl.SupportsPartialRendering = false; ModuleControlController.SaveModuleControl(loginControl, true); - //Upgrade to .NET 3.5/4.0 + // Upgrade to .NET 3.5/4.0 TryUpgradeNETFramework(); - //Update the version of the client resources - so the cache is cleared + // Update the version of the client resources - so the cache is cleared DataCache.ClearHostCache(false); HostController.Instance.IncrementCrmVersion(true); } @@ -5185,7 +5242,7 @@ public static void UpgradeApplication() var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), - BypassBuffering = true + BypassBuffering = true, }; log.AddProperty("Upgraded DotNetNuke", "General"); log.AddProperty("Warnings", "Error: " + ex.Message + Environment.NewLine); @@ -5198,15 +5255,15 @@ public static void UpgradeApplication() { Logger.Error(exc); } - } - //Remove any .txt and .config files that may exist in the Install folder + // Remove any .txt and .config files that may exist in the Install folder foreach (string file in Directory.GetFiles(Globals.InstallMapPath + "Cleanup\\", "??.??.??.txt") .Concat(Directory.GetFiles(Globals.InstallMapPath + "Cleanup\\", "??.??.??.??.txt"))) { FileSystemUtils.DeleteFile(file); } + foreach (string file in Directory.GetFiles(Globals.InstallMapPath + "Config\\", "??.??.??.config") .Concat(Directory.GetFiles(Globals.InstallMapPath + "Config\\", "??.??.??.??.config"))) { @@ -5214,24 +5271,26 @@ public static void UpgradeApplication() } } - ///----------------------------------------------------------------------------- - /// + /// ----------------------------------------------------------------------------- + /// /// UpgradeApplication - This overload is used for version specific application upgrade operations. - /// - /// + /// + /// /// This should be used for file system modifications or upgrade operations which /// should only happen once. Database references are not recommended because future /// versions of the application may result in code incompatibilties. - /// - ///----------------------------------------------------------------------------- + ///
    + /// + /// ----------------------------------------------------------------------------- public static string UpgradeApplication(string providerPath, Version version, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + Localization.Localization.GetString("ApplicationUpgrades", Localization.Localization.GlobalResourceFile) + ": " + version.ToString(3)); - string exceptions = ""; + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + ": " + version.ToString(3)); + string exceptions = string.Empty; if (writeFeedback) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.Localization.GetString("ApplicationUpgrades", Localization.Localization.GlobalResourceFile) + " : " + GetStringVersionWithRevision(version)); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + " : " + GetStringVersionWithRevision(version)); } + try { if (version.Revision == -1) @@ -5377,7 +5436,7 @@ public static string UpgradeApplication(string providerPath, Version version, bo } else { - //Incremental + // Incremental switch (version.ToString(4)) { case "8.0.0.6": @@ -5405,10 +5464,11 @@ public static string UpgradeApplication(string providerPath, Version version, bo { Logger.Error(ex); exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + // log the results if (string.IsNullOrEmpty(exceptions)) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogEnd", Localization.Localization.GlobalResourceFile) + Localization.Localization.GetString("ApplicationUpgrades", Localization.Localization.GlobalResourceFile) + ": " + version.ToString(3)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + ": " + version.ToString(3)); } else { @@ -5431,7 +5491,74 @@ public static string UpgradeApplication(string providerPath, Version version, bo if (writeFeedback) { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, (string.IsNullOrEmpty(exceptions))); + HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions)); + } + + return exceptions; + } + + public static string UpdateConfig(string providerPath, Version version, bool writeFeedback) + { + var stringVersion = GetStringVersionWithRevision(version); + + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, $"Updating Config Files: {stringVersion}"); + } + + string strExceptions = UpdateConfig(providerPath, Globals.InstallMapPath + "Config\\" + stringVersion + ".config", version, "Core Upgrade"); + if (string.IsNullOrEmpty(strExceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); + } + else + { + DnnInstallLogger.InstallLogError(strExceptions); + } + + if (writeFeedback) + { + HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(strExceptions)); + } + + return strExceptions; + } + + public static string UpdateConfig(string configFile, Version version, string reason) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); + string exceptions = string.Empty; + if (File.Exists(configFile)) + { + // Create XmlMerge instance from config file source + StreamReader stream = File.OpenText(configFile); + try + { + var merge = new XmlMerge(stream, version.ToString(3), reason); + + // Process merge + merge.UpdateConfigs(); + } + catch (Exception ex) + { + exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + Exceptions.Exceptions.LogException(ex); + } + finally + { + // Close stream + stream.Close(); + } + } + + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); } return exceptions; @@ -5579,18 +5706,18 @@ private static void UpgradeToVersion920() if (!HostTabExists("Superuser Accounts")) { - //add SuperUser Accounts module and tab + // add SuperUser Accounts module and tab var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); if (desktopModule != null) { var moduleDefId = ModuleDefinitionController .GetModuleDefinitionByFriendlyName("User Accounts", desktopModule.DesktopModuleID).ModuleDefID; - //Create New Host Page (or get existing one) + // Create New Host Page (or get existing one) var newPage = AddHostPage("Superuser Accounts", "Manage host user accounts.", "~/Icons/Sigma/Users_16X16_Standard.png", "~/Icons/Sigma/Users_32X32_Standard.png", false); - //Add Module To Page + // Add Module To Page AddModuleToPage(newPage, moduleDefId, "SuperUser Accounts", "~/Icons/Sigma/Users_32X32_Standard.png"); } } @@ -5620,6 +5747,7 @@ private static void UpgradeToVersion930() Logger.Warn("Unable to run orphaned user check. Application name is missing or not defined."); return; } + using (var reader = DataProvider.Instance().ExecuteReader("DeleteOrphanedAspNetUsers", applicationName)) { while (reader.Read()) @@ -5714,90 +5842,26 @@ private static void UpgradeToVersion960() HostController.Instance.Update("DefaultEndUserExtensionWhitelist", exts.ToStorageString()); } - public static string UpdateConfig(string providerPath, Version version, bool writeFeedback) - { - var stringVersion = GetStringVersionWithRevision(version); - - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, $"Updating Config Files: {stringVersion}"); - } - string strExceptions = UpdateConfig(providerPath, Globals.InstallMapPath + "Config\\" + stringVersion + ".config", version, "Core Upgrade"); - if (string.IsNullOrEmpty(strExceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogEnd", Localization.Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); - } - else - { - DnnInstallLogger.InstallLogError(strExceptions); - } - - if (writeFeedback) - { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, (string.IsNullOrEmpty(strExceptions))); - } - - return strExceptions; - } - - public static string UpdateConfig(string configFile, Version version, string reason) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - string exceptions = ""; - if (File.Exists(configFile)) - { - //Create XmlMerge instance from config file source - StreamReader stream = File.OpenText(configFile); - try - { - var merge = new XmlMerge(stream, version.ToString(3), reason); - - //Process merge - merge.UpdateConfigs(); - } - catch (Exception ex) - { - exceptions += String.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); - Exceptions.Exceptions.LogException(ex); - } - finally - { - //Close stream - stream.Close(); - } - } - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogEnd", Localization.Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); - } - return exceptions; - } - - public static string UpdateConfig(string providerPath, string configFile, Version version, string reason) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - string exceptions = ""; + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); + string exceptions = string.Empty; if (File.Exists(configFile)) { - //Create XmlMerge instance from config file source + // Create XmlMerge instance from config file source StreamReader stream = File.OpenText(configFile); try { var merge = new XmlMerge(stream, version.ToString(3), reason); - //Process merge + // Process merge merge.UpdateConfigs(); } catch (Exception ex) { Logger.Error(ex); exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + // log the results try { @@ -5814,37 +5878,38 @@ public static string UpdateConfig(string providerPath, string configFile, Versio } finally { - //Close stream + // Close stream stream.Close(); } } + if (string.IsNullOrEmpty(exceptions)) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogEnd", Localization.Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); } else { DnnInstallLogger.InstallLogError(exceptions); } + return exceptions; } - - ///----------------------------------------------------------------------------- - /// - /// UpgradeDNN manages the Upgrade of an exisiting DotNetNuke Application - /// - /// - /// - ///The path to the Data Provider - ///The current Database Version - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// UpgradeDNN manages the Upgrade of an exisiting DotNetNuke Application. + /// + /// + /// + /// The path to the Data Provider. + /// The current Database Version. + /// ----------------------------------------------------------------------------- public static void UpgradeDNN(string providerPath, Version dataBaseVersion) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpgradeDNN:" + Globals.FormatVersion(ApplicationVersion)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeDNN:" + Globals.FormatVersion(ApplicationVersion)); HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Upgrading to Version: " + Globals.FormatVersion(ApplicationVersion) + "
    "); - //Process the Upgrade Script files + // Process the Upgrade Script files var versions = new List(); foreach (string scriptFile in GetUpgradeScripts(providerPath, dataBaseVersion)) { @@ -5859,7 +5924,7 @@ public static void UpgradeDNN(string providerPath, Version dataBaseVersion) foreach (Version ver in versions) { - //' perform version specific application upgrades + // ' perform version specific application upgrades UpgradeApplication(providerPath, ver, true); } @@ -5868,41 +5933,39 @@ public static void UpgradeDNN(string providerPath, Version dataBaseVersion) // delete files which are no longer used DeleteFiles(providerPath, ver, true); } + foreach (Version ver in versions) { - //execute config file updates + // execute config file updates UpdateConfig(providerPath, ver, true); } + DataProvider.Instance().SetCorePackageVersions(); // perform general application upgrades HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Performing General Upgrades
    "); - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("GeneralUpgrades", Localization.Localization.GlobalResourceFile)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("GeneralUpgrades", Localization.GlobalResourceFile)); UpgradeApplication(); DataCache.ClearHostCache(true); } - internal static string GetFileNameWithoutExtension(string scriptFile) - { - return Path.GetFileNameWithoutExtension(scriptFile); - } - public static string UpgradeIndicator(Version version, bool isLocal, bool isSecureConnection) { - return UpgradeIndicator(version, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, "", isLocal, isSecureConnection); + return UpgradeIndicator(version, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, string.Empty, isLocal, isSecureConnection); } public static string UpgradeIndicator(Version version, string packageType, string packageName, string culture, bool isLocal, bool isSecureConnection) { - string url = ""; + string url = string.Empty; if (Host.CheckUpgrade && version != new Version(0, 0, 0)) { url = DotNetNukeContext.Current.Application.UpgradeUrl + "/update.aspx"; - //use network path reference so it works in ssl-offload scenarios + + // use network path reference so it works in ssl-offload scenarios url = url.Replace("http://", "//"); - url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, ""); - url += "&version=" + Globals.FormatVersion(version, "00", 3, ""); + url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, string.Empty); + url += "&version=" + Globals.FormatVersion(version, "00", 3, string.Empty); url += "&type=" + packageType; url += "&name=" + packageName; if (packageType.ToLowerInvariant() == "module") @@ -5913,36 +5976,44 @@ public static string UpgradeIndicator(Version version, string packageType, strin url += "&no=" + moduleType.Instances; } } + url += "&id=" + Host.GUID; if (packageType.Equals(DotNetNukeContext.Current.Application.Type, StringComparison.OrdinalIgnoreCase)) { - if (!String.IsNullOrEmpty(HostController.Instance.GetString("NewsletterSubscribeEmail"))) + if (!string.IsNullOrEmpty(HostController.Instance.GetString("NewsletterSubscribeEmail"))) { url += "&email=" + HttpUtility.UrlEncode(HostController.Instance.GetString("NewsletterSubscribeEmail")); } var portals = PortalController.Instance.GetPortals(); url += "&no=" + portals.Count; - url += "&os=" + Globals.FormatVersion(Globals.OperatingSystemVersion, "00", 2, ""); - url += "&net=" + Globals.FormatVersion(Globals.NETFrameworkVersion, "00", 2, ""); - url += "&db=" + Globals.FormatVersion(Globals.DatabaseEngineVersion, "00", 2, ""); + url += "&os=" + Globals.FormatVersion(Globals.OperatingSystemVersion, "00", 2, string.Empty); + url += "&net=" + Globals.FormatVersion(Globals.NETFrameworkVersion, "00", 2, string.Empty); + url += "&db=" + Globals.FormatVersion(Globals.DatabaseEngineVersion, "00", 2, string.Empty); var source = Config.GetSetting("Source"); if (!string.IsNullOrEmpty(source)) { url += "&src=" + source; } } + if (!string.IsNullOrEmpty(culture)) { url += "&culture=" + culture; } } + return url; } + internal static string GetFileNameWithoutExtension(string scriptFile) + { + return Path.GetFileNameWithoutExtension(scriptFile); + } + public static string UpgradeRedirect() { - return UpgradeRedirect(ApplicationVersion, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, ""); + return UpgradeRedirect(ApplicationVersion, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, string.Empty); } public static string UpgradeRedirect(Version version, string packageType, string packageName, string culture) @@ -5955,8 +6026,8 @@ public static string UpgradeRedirect(Version version, string packageType, string else { url = DotNetNukeContext.Current.Application.UpgradeUrl + "/redirect.aspx"; - url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, ""); - url += "&version=" + Globals.FormatVersion(version, "00", 3, ""); + url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, string.Empty); + url += "&version=" + Globals.FormatVersion(version, "00", 3, string.Empty); url += "&type=" + packageType; url += "&name=" + packageName; if (!string.IsNullOrEmpty(culture)) @@ -5964,37 +6035,40 @@ public static string UpgradeRedirect(Version version, string packageType, string url += "&culture=" + culture; } } + return url; } - ///----------------------------------------------------------------------------- - /// - /// UpgradeVersion upgrades a single version - /// - /// - /// - ///The upgrade script file - ///Write status to Response Stream? - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// UpgradeVersion upgrades a single version. + /// + /// + /// + /// The upgrade script file. + /// Write status to Response Stream?. + /// + /// ----------------------------------------------------------------------------- public static string UpgradeVersion(string scriptFile, bool writeFeedback) { bool scriptExecuted; return UpgradeVersion(scriptFile, writeFeedback, out scriptExecuted); } - ///----------------------------------------------------------------------------- - /// - /// UpgradeVersion upgrades a single version - /// - /// - /// - ///The upgrade script file - ///Write status to Response Stream? + /// ----------------------------------------------------------------------------- + /// + /// UpgradeVersion upgrades a single version. + /// + /// + /// + /// The upgrade script file. + /// Write status to Response Stream?. /// Identity whether the script file executed. - ///----------------------------------------------------------------------------- + /// + /// ----------------------------------------------------------------------------- public static string UpgradeVersion(string scriptFile, bool writeFeedback, out bool scriptExecuted) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); var version = new Version(GetFileNameWithoutExtension(scriptFile)); string exceptions = Null.NullString; scriptExecuted = false; @@ -6012,7 +6086,7 @@ public static string UpgradeVersion(string scriptFile, bool writeFeedback, out b var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), - BypassBuffering = true + BypassBuffering = true, }; log.AddProperty("Upgraded DotNetNuke", "Version: " + Globals.FormatVersion(version)); if (exceptions.Length > 0) @@ -6021,8 +6095,9 @@ public static string UpgradeVersion(string scriptFile, bool writeFeedback, out b } else { - log.AddProperty("No Warnings", ""); + log.AddProperty("No Warnings", string.Empty); } + LogController.Instance.AddLog(log); } @@ -6039,7 +6114,7 @@ public static string UpgradeVersion(string scriptFile, bool writeFeedback, out b var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), - BypassBuffering = true + BypassBuffering = true, }; log.AddProperty("Upgraded DotNetNuke", "Version: " + Globals.FormatVersion(version) + ", Iteration:" + version.Revision); if (exceptions.Length > 0) @@ -6048,33 +6123,29 @@ public static string UpgradeVersion(string scriptFile, bool writeFeedback, out b } else { - log.AddProperty("No Warnings", ""); + log.AddProperty("No Warnings", string.Empty); } + LogController.Instance.AddLog(log); } if (string.IsNullOrEmpty(exceptions)) { - DnnInstallLogger.InstallLogInfo(Localization.Localization.GetString("LogStart", Localization.Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); } else { DnnInstallLogger.InstallLogError(exceptions); } - return exceptions; - } - protected static bool IsLanguageEnabled(int portalid, string code) - { - Locale enabledLanguage; - return LocaleController.Instance.GetLocales(portalid).TryGetValue(code, out enabledLanguage); + return exceptions; } public static bool UpdateNewtonsoftVersion() { try { - //check whether current binding already specific to correct version. + // check whether current binding already specific to correct version. if (NewtonsoftNeedUpdate()) { lock (_threadLocker) @@ -6100,13 +6171,13 @@ public static bool UpdateNewtonsoftVersion() public static string ActivateLicense() { - var isLicensable = (File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Professional.dll")) || File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll"))); - var activationResult = ""; + var isLicensable = File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Professional.dll")) || File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")); + var activationResult = string.Empty; if (isLicensable) { var sku = File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")) ? "DNNENT" : "DNNPRO"; - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.Localization.GetString("ActivatingLicense", Localization.Localization.GlobalResourceFile)); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ActivatingLicense", Localization.GlobalResourceFile)); var installConfig = InstallController.Instance.GetInstallConfig(); var licenseConfig = (installConfig != null) ? installConfig.License : null; @@ -6117,19 +6188,26 @@ public static string ActivateLicense() licenseActivation.AutoActivation(licenseConfig.AccountEmail, licenseConfig.InvoiceNumber, licenseConfig.WebServer, licenseConfig.LicenseType, sku); activationResult = licenseActivation.LicenseResult; - //Log Event to Event Log - EventLogController.Instance.AddLog("License Activation", - "License Activated during install for: " + licenseConfig.AccountEmail + " | invoice: " + licenseConfig.InvoiceNumber, - EventLogController.EventLogType.HOST_ALERT); + // Log Event to Event Log + EventLogController.Instance.AddLog( + "License Activation", + "License Activated during install for: " + licenseConfig.AccountEmail + " | invoice: " + licenseConfig.InvoiceNumber, + EventLogController.EventLogType.HOST_ALERT); } } return activationResult; } + protected static bool IsLanguageEnabled(int portalid, string code) + { + Locale enabledLanguage; + return LocaleController.Instance.GetLocales(portalid).TryGetValue(code, out enabledLanguage); + } + public static bool RemoveInvalidAntiForgeryCookie() { - //DNN-9394: when upgrade from old version which use MVC version below than 5, it may saved antiforgery cookie + // DNN-9394: when upgrade from old version which use MVC version below than 5, it may saved antiforgery cookie // with a different cookie name which join the root path even equals to "/", then it will cause API request failed. // we need remove the cookie during upgrade process. var appPath = HttpRuntime.AppDomainAppVirtualPath; @@ -6263,7 +6341,7 @@ private static XmlDocument FindLanguageXmlDocument(string cultureCode, ref IDict { if (string.IsNullOrEmpty(cultureCode)) { - cultureCode = Localization.Localization.SystemLocale; + cultureCode = Localization.SystemLocale; } if (resourcesDict.ContainsKey(cultureCode)) @@ -6273,12 +6351,14 @@ private static XmlDocument FindLanguageXmlDocument(string cultureCode, ref IDict try { - var languageFilePath = Path.Combine(Globals.HostMapPath, + var languageFilePath = Path.Combine( + Globals.HostMapPath, string.Format("Default Website.template.{0}.resx", cultureCode)); if (!File.Exists(languageFilePath)) { - languageFilePath = Path.Combine(Globals.HostMapPath, - string.Format("Default Website.template.{0}.resx", Localization.Localization.SystemLocale)); + languageFilePath = Path.Combine( + Globals.HostMapPath, + string.Format("Default Website.template.{0}.resx", Localization.SystemLocale)); } var xmlDocument = new XmlDocument { XmlResolver = null }; @@ -6312,7 +6392,5 @@ private static bool NewtonsoftNeedUpdate() return true; } - - #endregion } } diff --git a/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs b/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs index 859c646d8c1..e30ce3fa263 100644 --- a/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs +++ b/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs @@ -1,34 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Url.FriendlyUrl { + using System; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + public abstract class FriendlyUrlProvider - { - #region "Shared/Static Methods" - - //return the provider + { + // return the provider public static FriendlyUrlProvider Instance() { return ComponentFactory.GetComponent(); - } - - #endregion - - #region "Abstract Methods" - + } + public abstract string FriendlyUrl(TabInfo tab, string path); public abstract string FriendlyUrl(TabInfo tab, string path, string pageName); @@ -38,11 +27,9 @@ public virtual string FriendlyUrl(TabInfo tab, string path, string pageName, Por { return this.FriendlyUrl(tab, path, pageName, (IPortalSettings)settings); } - + public abstract string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings); - public abstract string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias); - - #endregion + public abstract string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias); } } diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs index 89003e167e7..97ec3cb659d 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs @@ -1,33 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.UserProfile { + using System; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + public class UserProfilePageHandler : IHttpHandler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (UserProfilePageHandler)); - #region IHttpHandler Members + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserProfilePageHandler)); + public bool IsReusable + { + get + { + return true; + } + } + /// ----------------------------------------------------------------------------- /// /// This handler handles requests for LinkClick.aspx, but only those specifc - /// to file serving + /// to file serving. /// - /// System.Web.HttpContext) + /// System.Web.HttpContext). /// /// /// ----------------------------------------------------------------------------- @@ -39,21 +41,20 @@ public void ProcessRequest(HttpContext context) try { - //try UserId + // try UserId if (!string.IsNullOrEmpty(context.Request.QueryString["UserId"])) { - UserId = Int32.Parse(context.Request.QueryString["UserId"]); + UserId = int.Parse(context.Request.QueryString["UserId"]); if (UserController.GetUserById(PortalId, UserId) == null) { - //The user cannot be found (potential DOS) + // The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); - } } if (UserId == Null.NullInteger) { - //try userName + // try userName if (!string.IsNullOrEmpty(context.Request.QueryString["UserName"])) { UserId = GetUserId(context.Request.QueryString["UserName"], PortalId); @@ -62,22 +63,21 @@ public void ProcessRequest(HttpContext context) if (UserId == Null.NullInteger) { - //try user + // try user string user = context.Request.QueryString["User"]; if (!string.IsNullOrEmpty(user)) { - if (!Int32.TryParse(user, out UserId)) + if (!int.TryParse(user, out UserId)) { - //User is not an integer, so try it as a name + // User is not an integer, so try it as a name UserId = GetUserId(user, PortalId); } else { if (UserController.GetUserById(PortalId, UserId) == null) { - //The user cannot be found (potential DOS) + // The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); - } } } @@ -85,31 +85,22 @@ public void ProcessRequest(HttpContext context) if (UserId == Null.NullInteger) { - //The user cannot be found (potential DOS) + // The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } } catch (Exception exc) { Logger.Debug(exc); - //The user cannot be found (potential DOS) + + // The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } - //Redirect to Userprofile Page + // Redirect to Userprofile Page context.Response.Redirect(Globals.UserProfileURL(UserId), true); } - - public bool IsReusable - { - get - { - return true; - } - } - - #endregion - + private static int GetUserId(string username, int PortalId) { int _UserId = Null.NullInteger; @@ -120,9 +111,10 @@ private static int GetUserId(string username, int PortalId) } else { - //The user cannot be found (potential DOS) + // The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(); } + return _UserId; } } diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs index c7b30858608..206c6a023b6 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs @@ -1,96 +1,97 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.IO; -using System.Threading; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.UserProfile { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization.Internal; + public class UserProfilePicHandler : IHttpHandler - { - #region Private Fields - - private static object _locker = new object(); - - #endregion - - #region IHttpHandler Members + { + private static object _locker = new object(); + public bool IsReusable + { + get + { + return false; + } + } + public void ProcessRequest(HttpContext context) { - SetupCulture(); + this.SetupCulture(); var userId = -1; var width = 55; var height = 55; - var size = ""; + var size = string.Empty; try { - if (!String.IsNullOrEmpty(context.Request.QueryString["userid"])) + if (!string.IsNullOrEmpty(context.Request.QueryString["userid"])) { userId = Convert.ToInt32(context.Request.QueryString["userid"]); } - if (!String.IsNullOrEmpty(context.Request.QueryString["w"])) + if (!string.IsNullOrEmpty(context.Request.QueryString["w"])) { width = Convert.ToInt32(context.Request.QueryString["w"]); } - if (!String.IsNullOrEmpty(context.Request.QueryString["h"])) + if (!string.IsNullOrEmpty(context.Request.QueryString["h"])) { height = Convert.ToInt32(context.Request.QueryString["h"]); } - if (!String.IsNullOrEmpty(context.Request.QueryString["size"])) + + if (!string.IsNullOrEmpty(context.Request.QueryString["size"])) { size = context.Request.QueryString["size"]; } - } catch (Exception) { Exceptions.Exceptions.ProcessHttpException(context.Request); } - if (height > 128) { height = 128; } - if (width > 128) { width = 128; } - - - CalculateSize(ref height, ref width, ref size); + if (height > 128) + { + height = 128; + } + + if (width > 128) + { + width = 128; + } + + this.CalculateSize(ref height, ref width, ref size); PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); var user = UserController.Instance.GetUser(settings.PortalId, userId); IFileInfo photoFile = null; var photoLoaded = false; - if (user != null && TryGetPhotoFile(user, out photoFile)) + if (user != null && this.TryGetPhotoFile(user, out photoFile)) { - if (!IsImageExtension(photoFile.Extension)) + if (!this.IsImageExtension(photoFile.Extension)) { - try - { - context.Response.End(); - } - catch (ThreadAbortException)//if ThreadAbortException will shown, should catch it and do nothing. - { - - } - + try + { + context.Response.End(); + } + catch (ThreadAbortException) // if ThreadAbortException will shown, should catch it and do nothing. + { + } } var folder = FolderManager.Instance.GetFolder(photoFile.FolderId); @@ -125,7 +126,6 @@ public void ProcessRequest(HttpContext context) case "gif": context.Response.ContentType = "image/gif"; break; - } using (var memoryStream = new MemoryStream()) @@ -151,7 +151,7 @@ public void ProcessRequest(HttpContext context) context.ApplicationInstance.CompleteRequest(); } - //whether current user has permission to view target user's photo. + // whether current user has permission to view target user's photo. private bool TryGetPhotoFile(UserInfo targetUser, out IFileInfo photoFile) { bool isVisible = false; @@ -162,7 +162,7 @@ private bool TryGetPhotoFile(UserInfo targetUser, out IFileInfo photoFile) var photoProperty = targetUser.Profile.GetProperty("Photo"); if (photoProperty != null) { - isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, targetUser); + isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, targetUser); if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) { @@ -207,8 +207,9 @@ private void CalculateSize(ref int height, ref int width, ref string size) width = 128; size = "xl"; } - //set a default if unprocessed - if (String.IsNullOrEmpty(size)) + + // set a default if unprocessed + if (string.IsNullOrEmpty(size)) { height = 32; width = 32; @@ -230,24 +231,16 @@ private bool IsImageExtension(string extension) private void SetupCulture() { PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - if (settings == null) return; - + if (settings == null) + { + return; + } + CultureInfo pageLocale = TestableLocalization.Instance.GetPageLocale(settings); if (pageLocale != null) { TestableLocalization.Instance.SetThreadCultures(pageLocale, settings); } } - - public bool IsReusable - { - get - { - return false; - } - } - - #endregion - } } diff --git a/DNN Platform/Library/Services/UserRequest/IPAddressFamily.cs b/DNN Platform/Library/Services/UserRequest/IPAddressFamily.cs index 7fa007ff2b9..68867e79c37 100644 --- a/DNN Platform/Library/Services/UserRequest/IPAddressFamily.cs +++ b/DNN Platform/Library/Services/UserRequest/IPAddressFamily.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.UserRequest { + using System; + /// - /// IP address family + /// IP address family. /// public enum IPAddressFamily { IPv4, - IPv6 + IPv6, } } diff --git a/DNN Platform/Library/Services/UserRequest/IUserRequestIPAddressController.cs b/DNN Platform/Library/Services/UserRequest/IUserRequestIPAddressController.cs index 150d19eadce..7727c5f946a 100644 --- a/DNN Platform/Library/Services/UserRequest/IUserRequestIPAddressController.cs +++ b/DNN Platform/Library/Services/UserRequest/IUserRequestIPAddressController.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.UserRequest { + using System.Web; + public interface IUserRequestIPAddressController { /// /// To retrieve IPv4 of user making request to application. /// /// - /// IP address + /// IP address. string GetUserRequestIPAddress(HttpRequestBase request); /// - /// To retrieve IPv4/IPv6 of user making request to application + /// To retrieve IPv4/IPv6 of user making request to application. /// /// /// - /// IP address + /// IP address. string GetUserRequestIPAddress(HttpRequestBase request, IPAddressFamily ipFamily); } } diff --git a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs index 53fe4a957c7..bcd881e1381 100644 --- a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs +++ b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Controllers; -using System; -using System.Web; -using System.Linq; -using DotNetNuke.Framework; -using System.Net; -using System.Net.Sockets; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.UserRequest { - public class UserRequestIPAddressController : ServiceLocator, IUserRequestIPAddressController + using System; + using System.Linq; + using System.Net; + using System.Net.Sockets; + using System.Web; + + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Framework; + + public class UserRequestIPAddressController : ServiceLocator, IUserRequestIPAddressController { public string GetUserRequestIPAddress(HttpRequestBase request) { - return GetUserRequestIPAddress(request, IPAddressFamily.IPv4); + return this.GetUserRequestIPAddress(request, IPAddressFamily.IPv4); } public string GetUserRequestIPAddress(HttpRequestBase request, IPAddressFamily ipFamily) @@ -27,8 +28,8 @@ public string GetUserRequestIPAddress(HttpRequestBase request, IPAddressFamily i if (request.Headers.AllKeys.Contains(userRequestIPHeader)) { userIPAddress = request.Headers[userRequestIPHeader]; - userIPAddress = userIPAddress.Split(',')[0]; - } + userIPAddress = userIPAddress.Split(',')[0]; + } if (string.IsNullOrEmpty(userIPAddress)) { @@ -48,14 +49,19 @@ public string GetUserRequestIPAddress(HttpRequestBase request, IPAddressFamily i { userIPAddress = string.Empty; } - - if (!string.IsNullOrEmpty(userIPAddress) && !ValidateIP(userIPAddress, ipFamily)) + + if (!string.IsNullOrEmpty(userIPAddress) && !this.ValidateIP(userIPAddress, ipFamily)) { userIPAddress = string.Empty; } return userIPAddress; } + + protected override Func GetFactory() + { + return () => new UserRequestIPAddressController(); + } private bool ValidateIP(string ipString, IPAddressFamily ipFamily) { @@ -63,25 +69,20 @@ private bool ValidateIP(string ipString, IPAddressFamily ipFamily) if (IPAddress.TryParse(ipString, out address)) { if (ipFamily == IPAddressFamily.IPv4 && - address.AddressFamily == AddressFamily.InterNetwork && + address.AddressFamily == AddressFamily.InterNetwork && ipString.Split('.').Length == 4) { return true; } - if (ipFamily == IPAddressFamily.IPv6 && + if (ipFamily == IPAddressFamily.IPv6 && address.AddressFamily == AddressFamily.InterNetworkV6) { return true; } } + return false; } - - - protected override Func GetFactory() - { - return () => new UserRequestIPAddressController(); - } } } diff --git a/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs b/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs index f1912ddfa93..6ee82b41a23 100644 --- a/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs +++ b/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs @@ -1,25 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Scheduling; -using System; - -#endregion - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Users { + using System; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Scheduling; + public class PurgeDeletedUsers : SchedulerClient { - public PurgeDeletedUsers(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } public override void DoWork() @@ -46,32 +40,34 @@ public override void DoWork() thresholdDate = DateTime.Now.AddDays(-7 * settings.DataConsentDelay); break; } + var deletedUsers = UserController.GetDeletedUsers(portal.PortalID); foreach (UserInfo user in deletedUsers) { if (user.LastModifiedOnDate < thresholdDate && user.RequestsRemoval) { UserController.RemoveUser(user); - ScheduleHistoryItem.AddLogNote(string.Format("Removed user {0}{1}", user.Username, Environment.NewLine)); + this.ScheduleHistoryItem.AddLogNote(string.Format("Removed user {0}{1}", user.Username, Environment.NewLine)); } } } } } - ScheduleHistoryItem.Succeeded = true; //REQUIRED - ScheduleHistoryItem.AddLogNote("Purging deleted users task completed"); + + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED + this.ScheduleHistoryItem.AddLogNote("Purging deleted users task completed"); } - catch (Exception exc) //REQUIRED + catch (Exception exc) // REQUIRED { - ScheduleHistoryItem.Succeeded = false; //REQUIRED + this.ScheduleHistoryItem.Succeeded = false; // REQUIRED - ScheduleHistoryItem.AddLogNote(string.Format("Purging deleted users task failed: {0}.", exc.ToString())); + this.ScheduleHistoryItem.AddLogNote(string.Format("Purging deleted users task failed: {0}.", exc.ToString())); - //notification that we have errored - Errored(ref exc); //REQUIRED + // notification that we have errored + this.Errored(ref exc); // REQUIRED - //log the exception - Exceptions.Exceptions.LogException(exc); //OPTIONAL + // log the exception + Exceptions.Exceptions.LogException(exc); // OPTIONAL } } } diff --git a/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs b/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs index 5965bcb732d..4ba5d8afaa4 100644 --- a/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs +++ b/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Zip { + using System; + using System.Linq; + using System.Reflection; + /// /// This class contains a fix for a breaking upgrade in DNN 9.2 regarding the ZIP. /// It is in charge of fixing an assembly rename which was necessary when DNN - /// upgraded from an older SharpZipLib with a different DLL name. + /// upgraded from an older SharpZipLib with a different DLL name. /// /// /// The class in this folder will be used by.net when an assembly is missing. @@ -19,20 +19,20 @@ namespace DotNetNuke.Services.Zip /// redirect it to the correct (new) assembly. /// /// Once this remapping has been completed, this code will not be used again until the next - /// restart of the DNN application. - /// - /// final solution taken from https://raw.githubusercontent.com/2sic/2sxc/master/2sxc%20Dnn/Dnn920/SharpZipLibRedirect.cs + /// restart of the DNN application. + /// + /// final solution taken from https://raw.githubusercontent.com/2sic/2sxc/master/2sxc%20Dnn/Dnn920/SharpZipLibRedirect.cs. /// internal class SharpZipLibRedirect { - internal static bool AlreadyRun { get; private set; } - private const string OldName = "SharpZipLib"; private const string NewName = "ICSharpCode.SharpZipLib"; + + internal static bool AlreadyRun { get; private set; } /// /// Registration call - should only be called once - /// Has extra security to prevent it from running multiple times + /// Has extra security to prevent it from running multiple times. /// internal static void RegisterSharpZipLibRedirect() { @@ -40,6 +40,7 @@ internal static void RegisterSharpZipLibRedirect() { return; } + // stop any further attempts to access this AlreadyRun = true; diff --git a/DNN Platform/Library/Startup.cs b/DNN Platform/Library/Startup.cs index 925541afd62..e458f14da66 100644 --- a/DNN Platform/Library/Startup.cs +++ b/DNN Platform/Library/Startup.cs @@ -1,18 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.DependencyInjection; -using DotNetNuke.Entities.Portals; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Modules.Html5; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke { + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.DependencyInjection; + using DotNetNuke.Entities.Portals; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Modules.Html5; + using Microsoft.Extensions.DependencyInjection; + public class Startup : IDnnStartup { public void ConfigureServices(IServiceCollection services) diff --git a/DNN Platform/Library/UI/Containers/ActionBase.cs b/DNN Platform/Library/UI/Containers/ActionBase.cs index 5078900bced..d07c7a51fe5 100644 --- a/DNN Platform/Library/UI/Containers/ActionBase.cs +++ b/DNN Platform/Library/UI/Containers/ActionBase.cs @@ -1,193 +1,173 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers - /// Class : ActionBase + /// Class : ActionBase /// ----------------------------------------------------------------------------- /// /// ActionBase is an abstract base control for Action objects that inherit from UserControl. /// /// - /// ActionBase inherits from UserControl, and implements the IActionControl Interface + /// ActionBase inherits from UserControl, and implements the IActionControl Interface. /// public abstract class ActionBase : UserControl, IActionControl { - #region "Private Members" - + protected bool m_supportsIcons = true; private ActionManager _ActionManager; private ModuleAction _ActionRoot; - protected bool m_supportsIcons = true; - - #endregion - #region Protected Properties + public event ActionEventHandler Action; - /// ----------------------------------------------------------------------------- - /// - /// Gets the Actions Collection - /// - /// A ModuleActionCollection - protected ModuleActionCollection Actions + public bool EditMode { get { - return ModuleContext.Actions; + return this.ModuleContext.PortalSettings.UserMode != PortalSettings.Mode.View; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets the ActionRoot - /// - /// A ModuleActionCollection - protected ModuleAction ActionRoot + public bool SupportsIcons { get { - if (_ActionRoot == null) - { - _ActionRoot = new ModuleAction(ModuleContext.GetNextActionID(), Localization.GetString("Manage.Text", Localization.GlobalResourceFile), string.Empty, string.Empty, "manage-icn.png"); - } - return _ActionRoot; + return this.m_supportsIcons; } } /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleContext + /// Gets the Actions Collection. /// - /// A ModuleInstanceContext - protected ModuleInstanceContext ModuleContext + /// A ModuleActionCollection. + protected ModuleActionCollection Actions { get { - return ModuleControl.ModuleContext; + return this.ModuleContext.Actions; } } /// ----------------------------------------------------------------------------- /// - /// Gets the PortalSettings + /// Gets the ActionRoot. /// - /// A PortalSettings object - protected PortalSettings PortalSettings + /// A ModuleActionCollection. + protected ModuleAction ActionRoot { get { - return ModuleControl.ModuleContext.PortalSettings; + if (this._ActionRoot == null) + { + this._ActionRoot = new ModuleAction(this.ModuleContext.GetNextActionID(), Localization.GetString("Manage.Text", Localization.GlobalResourceFile), string.Empty, string.Empty, "manage-icn.png"); + } + + return this._ActionRoot; } } - - #endregion - #region Public Properties - - public bool EditMode + /// ----------------------------------------------------------------------------- + /// + /// Gets the ModuleContext. + /// + /// A ModuleInstanceContext. + protected ModuleInstanceContext ModuleContext { get { - return ModuleContext.PortalSettings.UserMode != PortalSettings.Mode.View; + return this.ModuleControl.ModuleContext; } } - public bool SupportsIcons + /// ----------------------------------------------------------------------------- + /// + /// Gets the PortalSettings. + /// + /// A PortalSettings object. + protected PortalSettings PortalSettings { get { - return m_supportsIcons; + return this.ModuleControl.ModuleContext.PortalSettings; } } - - #endregion - - #region IActionControl Members - - public event ActionEventHandler Action; /// ----------------------------------------------------------------------------- /// - /// Gets the ActionManager instance for this Action control + /// Gets the ActionManager instance for this Action control. /// - /// An ActionManager object + /// An ActionManager object. public ActionManager ActionManager { get { - if (_ActionManager == null) + if (this._ActionManager == null) { - _ActionManager = new ActionManager(this); + this._ActionManager = new ActionManager(this); } - return _ActionManager; + + return this._ActionManager; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleControl instance for this Action control + /// Gets or sets and sets the ModuleControl instance for this Action control. /// - /// An IModuleControl object + /// An IModuleControl object. public IModuleControl ModuleControl { get; set; } - #endregion - - #region Protected Methods - /// ----------------------------------------------------------------------------- /// - /// DisplayControl determines whether the control should be displayed + /// DisplayControl determines whether the control should be displayed. /// + /// protected bool DisplayControl(DNNNodeCollection objNodes) { - return ActionManager.DisplayControl(objNodes); + return this.ActionManager.DisplayControl(objNodes); } /// ----------------------------------------------------------------------------- /// - /// OnAction raises the Action Event for this control + /// OnAction raises the Action Event for this control. /// protected virtual void OnAction(ActionEventArgs e) { - if (Action != null) + if (this.Action != null) { - Action(this, e); + this.Action(this, e); } } /// ----------------------------------------------------------------------------- /// - /// ProcessAction processes the action event + /// ProcessAction processes the action event. /// protected void ProcessAction(string ActionID) { int output; - if (Int32.TryParse(ActionID, out output)) + if (int.TryParse(ActionID, out output)) { - ModuleAction action = Actions.GetActionByID(output); + ModuleAction action = this.Actions.GetActionByID(output); if (action != null) { - if (!ActionManager.ProcessAction(action)) + if (!this.ActionManager.ProcessAction(action)) { - OnAction(new ActionEventArgs(action, ModuleContext.Configuration)); + this.OnAction(new ActionEventArgs(action, this.ModuleContext.Configuration)); } } } @@ -195,7 +175,7 @@ protected void ProcessAction(string ActionID) /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the class is loaded + /// Page_Load runs when the class is loaded. /// /// /// @@ -208,17 +188,14 @@ protected override void OnLoad(EventArgs e) return; } - ActionRoot.Actions.AddRange(Actions); + this.ActionRoot.Actions.AddRange(this.Actions); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } - base.OnLoad(e); + base.OnLoad(e); } - - - #endregion } } diff --git a/DNN Platform/Library/UI/Containers/ActionButton.cs b/DNN Platform/Library/UI/Containers/ActionButton.cs index 63e9763470c..d6da3b1f1be 100644 --- a/DNN Platform/Library/UI/Containers/ActionButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionButton.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Modules.Actions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System; + + using DotNetNuke.Entities.Modules.Actions; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers - /// Class : ActionButton + /// Class : ActionButton /// ----------------------------------------------------------------------------- /// /// ActionButton provides a button (or group of buttons) for action(s). @@ -27,181 +22,175 @@ namespace DotNetNuke.UI.Containers [Obsolete("This class has been deprecated in favour of the new ActionCommandButton and ActionButtonList.. Scheduled removal in v11.0.0.")] public class ActionButton : ActionBase { - private ActionButtonList _ButtonList; - - #region "Public Properties" - + private ActionButtonList _ButtonList; + /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Command Name + /// Gets or sets the Command Name. /// /// - /// Maps to ModuleActionType in DotNetNuke.Entities.Modules.Actions + /// Maps to ModuleActionType in DotNetNuke.Entities.Modules.Actions. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string CommandName { get { - EnsureChildControls(); - return _ButtonList.CommandName; + this.EnsureChildControls(); + return this._ButtonList.CommandName; } + set { - EnsureChildControls(); - _ButtonList.CommandName = value; + this.EnsureChildControls(); + this._ButtonList.CommandName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the CSS Class + /// Gets or sets the CSS Class. /// /// - /// Defaults to 'CommandButton' + /// Defaults to 'CommandButton'. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string CssClass { get { - EnsureChildControls(); - return _ButtonList.CssClass; + this.EnsureChildControls(); + return this._ButtonList.CssClass; } + set { - EnsureChildControls(); - _ButtonList.CssClass = value; + this.EnsureChildControls(); + this._ButtonList.CssClass = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the link is displayed + /// Gets or sets a value indicating whether gets or sets whether the link is displayed. /// /// - /// Defaults to True + /// Defaults to True. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool DisplayLink { get { - EnsureChildControls(); - return _ButtonList.DisplayLink; + this.EnsureChildControls(); + return this._ButtonList.DisplayLink; } + set { - EnsureChildControls(); - _ButtonList.DisplayLink = value; + this.EnsureChildControls(); + this._ButtonList.DisplayLink = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the icon is displayed + /// Gets or sets a value indicating whether gets or sets whether the icon is displayed. /// /// - /// Defaults to False + /// Defaults to False. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool DisplayIcon { get { - EnsureChildControls(); - return _ButtonList.DisplayIcon; + this.EnsureChildControls(); + return this._ButtonList.DisplayIcon; } + set { - EnsureChildControls(); - _ButtonList.DisplayIcon = value; + this.EnsureChildControls(); + this._ButtonList.DisplayIcon = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Icon used + /// Gets or sets the Icon used. /// /// - /// Defaults to the icon defined in Action + /// Defaults to the icon defined in Action. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconFile { get { - EnsureChildControls(); - return _ButtonList.ImageURL; + this.EnsureChildControls(); + return this._ButtonList.ImageURL; } + set { - EnsureChildControls(); - _ButtonList.ImageURL = value; + this.EnsureChildControls(); + this._ButtonList.ImageURL = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Separator between Buttons + /// Gets or sets the Separator between Buttons. /// /// - /// Defaults to 2 non-breaking spaces + /// Defaults to 2 non-breaking spaces. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ButtonSeparator { get { - EnsureChildControls(); - return _ButtonList.ButtonSeparator; + this.EnsureChildControls(); + return this._ButtonList.ButtonSeparator; } + set { - EnsureChildControls(); - _ButtonList.ButtonSeparator = value; + this.EnsureChildControls(); + this._ButtonList.ButtonSeparator = value; } - } - - #endregion - - #region "Private Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// Action_Click responds to an Action Event in the contained actionButtonList + /// CreateChildControls builds the control tree. /// /// ----------------------------------------------------------------------------- - private void Action_Click(object sender, ActionEventArgs e) + protected override void CreateChildControls() { - ProcessAction(e.Action.ID.ToString()); - } - - #endregion + base.CreateChildControls(); - #region "Protected Methods" + this._ButtonList = new ActionButtonList(); + this._ButtonList.Action += this.Action_Click; + this.Controls.Add(this._ButtonList); + } + /// ----------------------------------------------------------------------------- /// - /// CreateChildControls builds the control tree + /// Action_Click responds to an Action Event in the contained actionButtonList. /// /// ----------------------------------------------------------------------------- - protected override void CreateChildControls() + private void Action_Click(object sender, ActionEventArgs e) { - base.CreateChildControls(); - - _ButtonList = new ActionButtonList(); - _ButtonList.Action += Action_Click; - - Controls.Add(_ButtonList); - } - - #endregion + this.ProcessAction(e.Action.ID.ToString()); + } } } diff --git a/DNN Platform/Library/UI/Containers/ActionButtonList.cs b/DNN Platform/Library/UI/Containers/ActionButtonList.cs index aa0d2580783..3fec63ab692 100644 --- a/DNN Platform/Library/UI/Containers/ActionButtonList.cs +++ b/DNN Platform/Library/UI/Containers/ActionButtonList.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.UI.Modules; + /// /// ActionButtonList provides a list of buttons for a group of actions of the same type. /// @@ -24,159 +19,145 @@ namespace DotNetNuke.UI.Containers /// public class ActionButtonList : CompositeControl, IActionControl { - #region "Private Members" - private ActionManager _ActionManager; private ModuleActionCollection _ModuleActions; private string _buttonSeparator = "  "; - private string _commandName = ""; + private string _commandName = string.Empty; private bool _displayLink = true; - - #endregion - - #region "Protected Members" + public event ActionEventHandler Action; /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleActionCollection to bind to the list + /// Gets or sets the Separator between Buttons. /// - /// A ModuleActionCollection - protected ModuleActionCollection ModuleActions + /// Defaults to 2 non-breaking spaces. + /// A String. + public string ButtonSeparator { get { - if (_ModuleActions == null) - { - _ModuleActions = ModuleControl.ModuleContext.Actions.GetActionsByCommandName(CommandName); - } - return _ModuleActions; + return this._buttonSeparator; } - } - - #endregion - #region "Public Properties" + set + { + this._buttonSeparator = value; + } + } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Separator between Buttons + /// Gets or sets the Command Name. /// - /// Defaults to 2 non-breaking spaces - /// A String - public string ButtonSeparator + /// Maps to ModuleActionType in DotNetNuke.Entities.Modules.Actions. + /// A String. + public string CommandName { get { - return _buttonSeparator; + return this._commandName; } + set { - _buttonSeparator = value; + this._commandName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Command Name + /// Gets the ModuleActionCollection to bind to the list. /// - /// Maps to ModuleActionType in DotNetNuke.Entities.Modules.Actions - /// A String - public string CommandName + /// A ModuleActionCollection. + protected ModuleActionCollection ModuleActions { get { - return _commandName; - } - set - { - _commandName = value; + if (this._ModuleActions == null) + { + this._ModuleActions = this.ModuleControl.ModuleContext.Actions.GetActionsByCommandName(this.CommandName); + } + + return this._ModuleActions; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the icon is displayed + /// Gets or sets a value indicating whether gets or sets whether the icon is displayed. /// - /// Defaults to False - /// A Boolean + /// Defaults to False. + /// A Boolean. public bool DisplayIcon { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the link is displayed + /// Gets or sets a value indicating whether gets or sets whether the link is displayed. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. public bool DisplayLink { get { - return _displayLink; + return this._displayLink; } + set { - _displayLink = value; + this._displayLink = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Icon used + /// Gets or sets the Icon used. /// - /// Defaults to the icon defined in Action - /// A String + /// Defaults to the icon defined in Action. + /// A String. public string ImageURL { get; set; } - #region IActionControl Members - - public event ActionEventHandler Action; - /// ----------------------------------------------------------------------------- /// - /// Gets the ActionManager instance for this Action control + /// Gets the ActionManager instance for this Action control. /// - /// An ActionManager object + /// An ActionManager object. public ActionManager ActionManager { get { - if (_ActionManager == null) + if (this._ActionManager == null) { - _ActionManager = new ActionManager(this); + this._ActionManager = new ActionManager(this); } - return _ActionManager; + + return this._ActionManager; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleControl instance for this Action control + /// Gets or sets and sets the ModuleControl instance for this Action control. /// - /// An IModuleControl object + /// An IModuleControl object. public IModuleControl ModuleControl { get; set; } - #endregion - - #endregion - - #region "Protected Methods" - /// ----------------------------------------------------------------------------- /// - /// OnAction raises the Action Event + /// OnAction raises the Action Event. /// protected virtual void OnAction(ActionEventArgs e) { - if (Action != null) + if (this.Action != null) { - Action(this, e); + this.Action(this, e); } } /// ----------------------------------------------------------------------------- /// - /// OnLoad runs when the control is loaded into the Control Tree + /// OnLoad runs when the control is loaded into the Control Tree. /// protected override void OnLoad(EventArgs e) { @@ -186,46 +167,41 @@ protected override void OnLoad(EventArgs e) return; } - foreach (ModuleAction action in ModuleActions) + foreach (ModuleAction action in this.ModuleActions) { - if (action != null && ActionManager.IsVisible(action)) + if (action != null && this.ActionManager.IsVisible(action)) { - //Create a new ActionCommandButton + // Create a new ActionCommandButton var actionButton = new ActionCommandButton(); - //Set all the properties + // Set all the properties actionButton.ModuleAction = action; - actionButton.ModuleControl = ModuleControl; - actionButton.CommandName = CommandName; - actionButton.CssClass = CssClass; - actionButton.DisplayLink = DisplayLink; - actionButton.DisplayIcon = DisplayIcon; - actionButton.ImageUrl = ImageURL; + actionButton.ModuleControl = this.ModuleControl; + actionButton.CommandName = this.CommandName; + actionButton.CssClass = this.CssClass; + actionButton.DisplayLink = this.DisplayLink; + actionButton.DisplayIcon = this.DisplayIcon; + actionButton.ImageUrl = this.ImageURL; - //Add a handler for the Action Event - actionButton.Action += ActionButtonClick; + // Add a handler for the Action Event + actionButton.Action += this.ActionButtonClick; - Controls.Add(actionButton); + this.Controls.Add(actionButton); - Controls.Add(new LiteralControl(ButtonSeparator)); + this.Controls.Add(new LiteralControl(this.ButtonSeparator)); } } - Visible = (Controls.Count > 0); - } - - #endregion - #region "Event Handlers" + this.Visible = this.Controls.Count > 0; + } /// ----------------------------------------------------------------------------- /// - /// ActionButtonClick handles the Action event of the contained ActionCommandButton(s) + /// ActionButtonClick handles the Action event of the contained ActionCommandButton(s). /// private void ActionButtonClick(object sender, ActionEventArgs e) { - OnAction(e); + this.OnAction(e); } - - #endregion } } diff --git a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs index fcd31d84b1c..a5395382530 100644 --- a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers - /// Class : ActionCommandButton + /// Class : ActionCommandButton /// ----------------------------------------------------------------------------- /// /// ActionCommandButton provides a button for a single action. @@ -28,156 +23,144 @@ namespace DotNetNuke.UI.Containers /// /// ----------------------------------------------------------------------------- public class ActionCommandButton : CommandButton, IActionControl - { - #region "Private Members" - + { private ActionManager _ActionManager; - private ModuleAction _ModuleAction; - - #endregion - - #region "Public Properties" - + private ModuleAction _ModuleAction; + + public event ActionEventHandler Action; + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleAction for this Action control + /// Gets or sets and sets the ModuleAction for this Action control. /// - /// A ModuleAction object + /// A ModuleAction object. /// ----------------------------------------------------------------------------- public ModuleAction ModuleAction { get { - if (_ModuleAction == null) + if (this._ModuleAction == null) { - _ModuleAction = ModuleControl.ModuleContext.Actions.GetActionByCommandName(CommandName); + this._ModuleAction = this.ModuleControl.ModuleContext.Actions.GetActionByCommandName(this.CommandName); } - return _ModuleAction; + + return this._ModuleAction; } + set { - _ModuleAction = value; + this._ModuleAction = value; } - } - - #region IActionControl Members - - public event ActionEventHandler Action; + } /// ----------------------------------------------------------------------------- /// - /// Gets the ActionManager instance for this Action control + /// Gets the ActionManager instance for this Action control. /// - /// An ActionManager object + /// An ActionManager object. /// ----------------------------------------------------------------------------- public ActionManager ActionManager { get { - if (_ActionManager == null) + if (this._ActionManager == null) { - _ActionManager = new ActionManager(this); + this._ActionManager = new ActionManager(this); } - return _ActionManager; + + return this._ActionManager; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleControl instance for this Action control + /// Gets or sets and sets the ModuleControl instance for this Action control. /// - /// An IModuleControl object + /// An IModuleControl object. /// ----------------------------------------------------------------------------- - public IModuleControl ModuleControl { get; set; } - - #endregion - - #endregion - - #region "Protected Methods" - + public IModuleControl ModuleControl { get; set; } + /// ----------------------------------------------------------------------------- /// - /// CreateChildControls builds the control tree + /// CreateChildControls builds the control tree. /// /// ----------------------------------------------------------------------------- protected override void CreateChildControls() { - //Call base class method to ensure Control Tree is built + // Call base class method to ensure Control Tree is built base.CreateChildControls(); - //Set Causes Validation and Enables ViewState to false - CausesValidation = false; - EnableViewState = false; + // Set Causes Validation and Enables ViewState to false + this.CausesValidation = false; + this.EnableViewState = false; } /// ----------------------------------------------------------------------------- /// - /// OnAction raises the Action Event + /// OnAction raises the Action Event. /// /// ----------------------------------------------------------------------------- protected virtual void OnAction(ActionEventArgs e) { - if (Action != null) + if (this.Action != null) { - Action(this, e); + this.Action(this, e); } } /// ----------------------------------------------------------------------------- /// - /// OnButtonClick runs when the underlying CommandButton is clicked + /// OnButtonClick runs when the underlying CommandButton is clicked. /// /// ----------------------------------------------------------------------------- protected override void OnButtonClick(EventArgs e) { base.OnButtonClick(e); - if (!ActionManager.ProcessAction(ModuleAction)) + if (!this.ActionManager.ProcessAction(this.ModuleAction)) { - OnAction(new ActionEventArgs(ModuleAction, ModuleControl.ModuleContext.Configuration)); + this.OnAction(new ActionEventArgs(this.ModuleAction, this.ModuleControl.ModuleContext.Configuration)); } } /// ----------------------------------------------------------------------------- /// - /// OnPreRender runs when just before the Render phase of the Page Lifecycle + /// OnPreRender runs when just before the Render phase of the Page Lifecycle. /// /// ----------------------------------------------------------------------------- protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (ModuleAction != null && ActionManager.IsVisible(ModuleAction)) + if (this.ModuleAction != null && this.ActionManager.IsVisible(this.ModuleAction)) { - Text = ModuleAction.Title; - CommandArgument = ModuleAction.ID.ToString(); + this.Text = this.ModuleAction.Title; + this.CommandArgument = this.ModuleAction.ID.ToString(); - if (DisplayIcon && (!string.IsNullOrEmpty(ModuleAction.Icon) || !string.IsNullOrEmpty(ImageUrl))) + if (this.DisplayIcon && (!string.IsNullOrEmpty(this.ModuleAction.Icon) || !string.IsNullOrEmpty(this.ImageUrl))) { - if (!string.IsNullOrEmpty(ImageUrl)) + if (!string.IsNullOrEmpty(this.ImageUrl)) { - ImageUrl = ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1) + ImageUrl; + this.ImageUrl = this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1) + this.ImageUrl; } else { - if (ModuleAction.Icon.IndexOf("/") > Null.NullInteger) + if (this.ModuleAction.Icon.IndexOf("/") > Null.NullInteger) { - ImageUrl = ModuleAction.Icon; + this.ImageUrl = this.ModuleAction.Icon; } else { - ImageUrl = "~/images/" + ModuleAction.Icon; + this.ImageUrl = "~/images/" + this.ModuleAction.Icon; } } } - ActionManager.GetClientScriptURL(ModuleAction, this); + + this.ActionManager.GetClientScriptURL(this.ModuleAction, this); } else { - Visible = false; + this.Visible = false; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Containers/ActionManager.cs b/DNN Platform/Library/UI/Containers/ActionManager.cs index d287ecebe70..c1272643670 100644 --- a/DNN Platform/Library/UI/Containers/ActionManager.cs +++ b/DNN Platform/Library/UI/Containers/ActionManager.cs @@ -1,149 +1,177 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Web; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System; + using System.Linq; + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers - /// Class : ActionManager + /// Class : ActionManager /// ----------------------------------------------------------------------------- /// /// ActionManager is a helper class that provides common Action Behaviours that can - /// be used by any IActionControl implementation + /// be used by any IActionControl implementation. /// /// ----------------------------------------------------------------------------- public class ActionManager - { - #region Private Members - + { private readonly PortalSettings PortalSettings = PortalController.Instance.GetCurrentPortalSettings(); private readonly HttpRequest Request = HttpContext.Current.Request; - private readonly HttpResponse Response = HttpContext.Current.Response; - - #endregion - - #region Constructors - + private readonly HttpResponse Response = HttpContext.Current.Response; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new ActionManager + /// + /// Initializes a new instance of the class. + /// Constructs a new ActionManager. /// /// ----------------------------------------------------------------------------- public ActionManager(IActionControl actionControl) { - ActionControl = actionControl; - } - - #endregion - - #region Public Properties - + this.ActionControl = actionControl; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Action Control that is connected to this ActionManager instance + /// Gets or sets and sets the Action Control that is connected to this ActionManager instance. /// - /// An IActionControl object + /// An IActionControl object. /// ----------------------------------------------------------------------------- public IActionControl ActionControl { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleInstanceContext instance that is connected to this ActionManager - /// instance + /// Gets the ModuleInstanceContext instance that is connected to this ActionManager + /// instance. /// - /// A ModuleInstanceContext object + /// A ModuleInstanceContext object. /// ----------------------------------------------------------------------------- protected ModuleInstanceContext ModuleContext { get { - return ActionControl.ModuleControl.ModuleContext; + return this.ActionControl.ModuleControl.ModuleContext; } + } + + /// ----------------------------------------------------------------------------- + /// + /// DisplayControl determines whether the associated Action control should be + /// displayed. + /// + /// + /// ----------------------------------------------------------------------------- + public bool DisplayControl(DNNNodeCollection objNodes) + { + if (objNodes != null && objNodes.Count > 0 && this.PortalSettings.UserMode != PortalSettings.Mode.View) + { + DNNNode objRootNode = objNodes[0]; + if (objRootNode.HasNodes && objRootNode.DNNNodes.Count == 0) + { + // if has pending node then display control + return true; + } + else if (objRootNode.DNNNodes.Count > 0) + { + // verify that at least one child is not a break + foreach (DNNNode childNode in objRootNode.DNNNodes) + { + if (!childNode.IsBreak) + { + // Found a child so make Visible + return true; + } + } + } + } + + return false; } - #endregion - - #region Private Methods - + /// ----------------------------------------------------------------------------- + /// + /// GetAction gets the action associated with the commandName. + /// + /// The command name. + /// + /// ----------------------------------------------------------------------------- + public ModuleAction GetAction(string commandName) + { + return this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByCommandName(commandName); + } + private void ClearCache(ModuleAction Command) { - //synchronize cache - ModuleController.SynchronizeModule(ModuleContext.ModuleId); + // synchronize cache + ModuleController.SynchronizeModule(this.ModuleContext.ModuleId); - //Redirect to the same page to pick up changes - Response.Redirect(Request.RawUrl, true); + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); } private void Delete(ModuleAction Command) { - var module = ModuleController.Instance.GetModule(int.Parse(Command.CommandArgument), ModuleContext.TabId, true); + var module = ModuleController.Instance.GetModule(int.Parse(Command.CommandArgument), this.ModuleContext.TabId, true); - //Check if this is the owner instance of a shared module. + // Check if this is the owner instance of a shared module. var user = UserController.Instance.GetCurrentUserInfo(); if (!module.IsShared) { foreach (ModuleInfo instance in ModuleController.Instance.GetTabModulesByModule(module.ModuleID)) { - if(instance.IsShared) + if (instance.IsShared) { - //HARD Delete Shared Instance + // HARD Delete Shared Instance ModuleController.Instance.DeleteTabModule(instance.TabID, instance.ModuleID, false); - EventLogController.Instance.AddLog(instance, PortalSettings, user.UserID, "", EventLogController.EventLogType.MODULE_DELETED); + EventLogController.Instance.AddLog(instance, this.PortalSettings, user.UserID, string.Empty, EventLogController.EventLogType.MODULE_DELETED); } } } - ModuleController.Instance.DeleteTabModule(ModuleContext.TabId, int.Parse(Command.CommandArgument), true); - EventLogController.Instance.AddLog(module, PortalSettings, user.UserID, "", EventLogController.EventLogType.MODULE_SENT_TO_RECYCLE_BIN); + ModuleController.Instance.DeleteTabModule(this.ModuleContext.TabId, int.Parse(Command.CommandArgument), true); + EventLogController.Instance.AddLog(module, this.PortalSettings, user.UserID, string.Empty, EventLogController.EventLogType.MODULE_SENT_TO_RECYCLE_BIN); - //Redirect to the same page to pick up changes - Response.Redirect(Request.RawUrl, true); + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); } private void DoAction(ModuleAction Command) { if (Command.NewWindow) { - UrlUtils.OpenNewWindow(ActionControl.ModuleControl.Control.Page, GetType(), Command.Url); + UrlUtils.OpenNewWindow(this.ActionControl.ModuleControl.Control.Page, this.GetType(), Command.Url); } else { - Response.Redirect(Command.Url, true); + this.Response.Redirect(Command.Url, true); } } private void Localize(ModuleAction Command) { - ModuleInfo sourceModule = ModuleController.Instance.GetModule(ModuleContext.ModuleId, ModuleContext.TabId, false); + ModuleInfo sourceModule = ModuleController.Instance.GetModule(this.ModuleContext.ModuleId, this.ModuleContext.TabId, false); switch (Command.CommandName) { case ModuleActionType.LocalizeModule: - ModuleController.Instance.LocalizeModule(sourceModule, LocaleController.Instance.GetCurrentLocale(ModuleContext.PortalId)); + ModuleController.Instance.LocalizeModule(sourceModule, LocaleController.Instance.GetCurrentLocale(this.ModuleContext.PortalId)); break; case ModuleActionType.DeLocalizeModule: ModuleController.Instance.DeLocalizeModule(sourceModule); @@ -151,12 +179,12 @@ private void Localize(ModuleAction Command) } // Redirect to the same page to pick up changes - Response.Redirect(Request.RawUrl, true); + this.Response.Redirect(this.Request.RawUrl, true); } private void Translate(ModuleAction Command) { - ModuleInfo sourceModule = ModuleController.Instance.GetModule(ModuleContext.ModuleId, ModuleContext.TabId, false); + ModuleInfo sourceModule = ModuleController.Instance.GetModule(this.ModuleContext.ModuleId, this.ModuleContext.TabId, false); switch (Command.CommandName) { case ModuleActionType.TranslateModule: @@ -168,16 +196,16 @@ private void Translate(ModuleAction Command) } // Redirect to the same page to pick up changes - Response.Redirect(Request.RawUrl, true); + this.Response.Redirect(this.Request.RawUrl, true); } private void MoveToPane(ModuleAction Command) { - ModuleController.Instance.UpdateModuleOrder(ModuleContext.TabId, ModuleContext.ModuleId, -1, Command.CommandArgument); - ModuleController.Instance.UpdateTabModuleOrder(ModuleContext.TabId); + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, -1, Command.CommandArgument); + ModuleController.Instance.UpdateTabModuleOrder(this.ModuleContext.TabId); - //Redirect to the same page to pick up changes - Response.Redirect(Request.RawUrl, true); + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); } private void MoveUpDown(ModuleAction Command) @@ -185,93 +213,48 @@ private void MoveUpDown(ModuleAction Command) switch (Command.CommandName) { case ModuleActionType.MoveTop: - ModuleController.Instance.UpdateModuleOrder(ModuleContext.TabId, ModuleContext.ModuleId, 0, Command.CommandArgument); + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, 0, Command.CommandArgument); break; case ModuleActionType.MoveUp: - ModuleController.Instance.UpdateModuleOrder(ModuleContext.TabId, ModuleContext.ModuleId, ModuleContext.Configuration.ModuleOrder - 3, Command.CommandArgument); + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, this.ModuleContext.Configuration.ModuleOrder - 3, Command.CommandArgument); break; case ModuleActionType.MoveDown: - ModuleController.Instance.UpdateModuleOrder(ModuleContext.TabId, ModuleContext.ModuleId, ModuleContext.Configuration.ModuleOrder + 3, Command.CommandArgument); + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, this.ModuleContext.Configuration.ModuleOrder + 3, Command.CommandArgument); break; case ModuleActionType.MoveBottom: - ModuleController.Instance.UpdateModuleOrder(ModuleContext.TabId, ModuleContext.ModuleId, (ModuleContext.Configuration.PaneModuleCount * 2) + 1, Command.CommandArgument); + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, (this.ModuleContext.Configuration.PaneModuleCount * 2) + 1, Command.CommandArgument); break; } - ModuleController.Instance.UpdateTabModuleOrder(ModuleContext.TabId); - - //Redirect to the same page to pick up changes - Response.Redirect(Request.RawUrl, true); - } + + ModuleController.Instance.UpdateTabModuleOrder(this.ModuleContext.TabId); - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// DisplayControl determines whether the associated Action control should be - /// displayed - /// - /// ----------------------------------------------------------------------------- - public bool DisplayControl(DNNNodeCollection objNodes) - { - if (objNodes != null && objNodes.Count > 0 && PortalSettings.UserMode != PortalSettings.Mode.View) - { - DNNNode objRootNode = objNodes[0]; - if (objRootNode.HasNodes && objRootNode.DNNNodes.Count == 0) - { - //if has pending node then display control - return true; - } - else if (objRootNode.DNNNodes.Count > 0) - { - //verify that at least one child is not a break - foreach (DNNNode childNode in objRootNode.DNNNodes) - { - if (!childNode.IsBreak) - { - //Found a child so make Visible - return true; - } - } - } - } - return false; - } - - /// ----------------------------------------------------------------------------- - /// - /// GetAction gets the action associated with the commandName - /// - /// The command name - /// ----------------------------------------------------------------------------- - public ModuleAction GetAction(string commandName) - { - return ActionControl.ModuleControl.ModuleContext.Actions.GetActionByCommandName(commandName); - } + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); + } /// ----------------------------------------------------------------------------- /// - /// GetAction gets the action associated with the id + /// GetAction gets the action associated with the id. /// - /// The Id + /// The Id. + /// /// ----------------------------------------------------------------------------- public ModuleAction GetAction(int id) { - return ActionControl.ModuleControl.ModuleContext.Actions.GetActionByID(id); + return this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByID(id); } /// ----------------------------------------------------------------------------- /// - /// GetClientScriptURL gets the client script to attach to the control's client - /// side onclick event + /// GetClientScriptURL gets the client script to attach to the control's client + /// side onclick event. /// - /// The Action - /// The Control + /// The Action. + /// The Control. /// ----------------------------------------------------------------------------- public void GetClientScriptURL(ModuleAction action, WebControl control) { - if (!String.IsNullOrEmpty(action.ClientScript)) + if (!string.IsNullOrEmpty(action.ClientScript)) { string Script = action.ClientScript; int JSPos = Script.IndexOf("javascript:", StringComparison.InvariantCultureIgnoreCase); @@ -279,6 +262,7 @@ public void GetClientScriptURL(ModuleAction action, WebControl control) { Script = Script.Substring(JSPos + 11); } + string FormatScript = "javascript: return {0};"; control.Attributes.Add("onClick", string.Format(FormatScript, Script)); } @@ -286,16 +270,17 @@ public void GetClientScriptURL(ModuleAction action, WebControl control) /// ----------------------------------------------------------------------------- /// - /// IsVisible determines whether the action control is Visible + /// IsVisible determines whether the action control is Visible. /// - /// The Action + /// The Action. + /// /// ----------------------------------------------------------------------------- public bool IsVisible(ModuleAction action) { bool _IsVisible = false; - if (action.Visible && ModulePermissionController.HasModuleAccess(action.Secure, Null.NullString, ModuleContext.Configuration)) + if (action.Visible && ModulePermissionController.HasModuleAccess(action.Secure, Null.NullString, this.ModuleContext.Configuration)) { - if ((ModuleContext.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (action.Secure == SecurityAccessLevel.Anonymous || action.Secure == SecurityAccessLevel.View)) + if ((this.ModuleContext.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (action.Secure == SecurityAccessLevel.Anonymous || action.Secure == SecurityAccessLevel.View)) { _IsVisible = true; } @@ -308,31 +293,35 @@ public bool IsVisible(ModuleAction action) { _IsVisible = false; } + return _IsVisible; } /// ----------------------------------------------------------------------------- /// - /// ProcessAction processes the action + /// ProcessAction processes the action. /// - /// The Id of the Action + /// The Id of the Action. + /// /// ----------------------------------------------------------------------------- public bool ProcessAction(string id) { bool bProcessed = true; int nid = 0; - if (Int32.TryParse(id, out nid)) + if (int.TryParse(id, out nid)) { - bProcessed = ProcessAction(ActionControl.ModuleControl.ModuleContext.Actions.GetActionByID(nid)); + bProcessed = this.ProcessAction(this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByID(nid)); } + return bProcessed; } /// ----------------------------------------------------------------------------- /// - /// ProcessAction processes the action + /// ProcessAction processes the action. /// - /// The Action + /// The Action. + /// /// ----------------------------------------------------------------------------- public bool ProcessAction(ModuleAction action) { @@ -340,59 +329,59 @@ public bool ProcessAction(ModuleAction action) switch (action.CommandName) { case ModuleActionType.ModuleHelp: - DoAction(action); + this.DoAction(action); break; case ModuleActionType.OnlineHelp: - DoAction(action); + this.DoAction(action); break; case ModuleActionType.ModuleSettings: - DoAction(action); + this.DoAction(action); break; case ModuleActionType.DeleteModule: - Delete(action); + this.Delete(action); break; case ModuleActionType.PrintModule: case ModuleActionType.SyndicateModule: - DoAction(action); + this.DoAction(action); break; case ModuleActionType.ClearCache: - ClearCache(action); + this.ClearCache(action); break; case ModuleActionType.MovePane: - MoveToPane(action); + this.MoveToPane(action); break; case ModuleActionType.MoveTop: case ModuleActionType.MoveUp: case ModuleActionType.MoveDown: case ModuleActionType.MoveBottom: - MoveUpDown(action); + this.MoveUpDown(action); break; case ModuleActionType.LocalizeModule: - Localize(action); + this.Localize(action); break; case ModuleActionType.DeLocalizeModule: - Localize(action); + this.Localize(action); break; case ModuleActionType.TranslateModule: - Translate(action); + this.Translate(action); break; case ModuleActionType.UnTranslateModule: - Translate(action); + this.Translate(action); break; - default: //custom action - if (!String.IsNullOrEmpty(action.Url) && action.UseActionEvent == false) + default: // custom action + if (!string.IsNullOrEmpty(action.Url) && action.UseActionEvent == false) { - DoAction(action); + this.DoAction(action); } else { bProcessed = false; } + break; } + return bProcessed; - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Containers/ActionsMenu.cs b/DNN Platform/Library/UI/Containers/ActionsMenu.cs index 7ab6701d2f9..cbfa0303de7 100644 --- a/DNN Platform/Library/UI/Containers/ActionsMenu.cs +++ b/DNN Platform/Library/UI/Containers/ActionsMenu.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text.RegularExpressions; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System; + using System.Text.RegularExpressions; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers - /// Class : ActionsMenu + /// Class : ActionsMenu /// ----------------------------------------------------------------------------- /// /// ActionsMenu provides a menu for a collection of actions. @@ -33,339 +28,319 @@ namespace DotNetNuke.UI.Containers /// /// ----------------------------------------------------------------------------- public class ActionsMenu : Control, IActionControl - { - #region "Private Members" - + { private ActionManager _ActionManager; private ModuleAction _ActionRoot; private int _ExpandDepth = -1; private NavigationProvider _ProviderControl; - private string _ProviderName = "DNNMenuNavigationProvider"; - - #endregion - - #region "Protected Properties" - + private string _ProviderName = "DNNMenuNavigationProvider"; + + public event ActionEventHandler Action; + /// ----------------------------------------------------------------------------- /// - /// Gets the ActionRoot + /// Gets or sets and Sets the Expansion Depth for the Control. /// - /// A ModuleActionCollection + /// An Integer. /// ----------------------------------------------------------------------------- - protected ModuleAction ActionRoot + public int ExpandDepth { get { - if (_ActionRoot == null) + if (this.PopulateNodesFromClient == false || this.ProviderControl.SupportsPopulateOnDemand == false) { - _ActionRoot = new ModuleAction(ModuleControl.ModuleContext.GetNextActionID(), " ", "", "", "action.gif"); + return -1; } - return _ActionRoot; + + return this._ExpandDepth; + } + + set + { + this._ExpandDepth = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Provider Control + /// Gets or sets and Sets the Path to the Script Library for the provider. /// - /// A NavigationProvider + /// A String. /// ----------------------------------------------------------------------------- - protected NavigationProvider ProviderControl + public string PathSystemScript { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the ActionRoot. + /// + /// A ModuleActionCollection. + /// ----------------------------------------------------------------------------- + protected ModuleAction ActionRoot { get { - return _ProviderControl; + if (this._ActionRoot == null) + { + this._ActionRoot = new ModuleAction(this.ModuleControl.ModuleContext.GetNextActionID(), " ", string.Empty, string.Empty, "action.gif"); + } + + return this._ActionRoot; } } - - #endregion - - #region "Public Properties" /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Expansion Depth for the Control + /// Gets the Provider Control. /// - /// An Integer + /// A NavigationProvider. /// ----------------------------------------------------------------------------- - public int ExpandDepth + protected NavigationProvider ProviderControl { get { - if (PopulateNodesFromClient == false || ProviderControl.SupportsPopulateOnDemand == false) - { - return -1; - } - return _ExpandDepth; - } - set - { - _ExpandDepth = value; + return this._ProviderControl; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and Sets the Path to the Script Library for the provider - /// - /// A String - /// ----------------------------------------------------------------------------- - public string PathSystemScript { get; set; } + } - /// ----------------------------------------------------------------------------- - /// - /// Gets and Sets whether the Menu should be populated from the client - /// - /// A Boolean - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and Sets whether the Menu should be populated from the client. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool PopulateNodesFromClient { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and Sets the Name of the provider to use + /// Gets or sets and Sets the Name of the provider to use. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ProviderName { get { - return _ProviderName; + return this._ProviderName; } + set { - _ProviderName = value; + this._ProviderName = value; } - } - - #region IActionControl Members - - public event ActionEventHandler Action; + } /// ----------------------------------------------------------------------------- /// - /// Gets the ActionManager instance for this Action control + /// Gets the ActionManager instance for this Action control. /// - /// An ActionManager object + /// An ActionManager object. /// ----------------------------------------------------------------------------- public ActionManager ActionManager { get { - if (_ActionManager == null) + if (this._ActionManager == null) { - _ActionManager = new ActionManager(this); + this._ActionManager = new ActionManager(this); } - return _ActionManager; + + return this._ActionManager; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleControl instance for this Action control + /// Gets or sets and sets the ModuleControl instance for this Action control. /// - /// An IModuleControl object + /// An IModuleControl object. /// ----------------------------------------------------------------------------- - public IModuleControl ModuleControl { get; set; } - - #endregion - - #endregion - - #region "Private Methods" - + public IModuleControl ModuleControl { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// BindMenu binds the Navigation Provider to the Node Collection. + /// + /// ----------------------------------------------------------------------------- + protected void BindMenu() + { + this.BindMenu(Navigation.GetActionNodes(this.ActionRoot, this, this.ExpandDepth)); + } /// ----------------------------------------------------------------------------- /// - /// BindMenu binds the Navigation Provider to the Node Collection + /// OnAction raises the Action Event. /// - /// The Nodes collection to bind + /// ----------------------------------------------------------------------------- + protected virtual void OnAction(ActionEventArgs e) + { + if (this.Action != null) + { + this.Action(this, e); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// BindMenu binds the Navigation Provider to the Node Collection. + /// + /// The Nodes collection to bind. /// ----------------------------------------------------------------------------- private void BindMenu(DNNNodeCollection objNodes) { - Visible = ActionManager.DisplayControl(objNodes); - if (Visible) + this.Visible = this.ActionManager.DisplayControl(objNodes); + if (this.Visible) { - //since we always bind we need to clear the nodes for providers that maintain their state - ProviderControl.ClearNodes(); + // since we always bind we need to clear the nodes for providers that maintain their state + this.ProviderControl.ClearNodes(); foreach (DNNNode objNode in objNodes) { - ProcessNodes(objNode); + this.ProcessNodes(objNode); } - ProviderControl.Bind(objNodes); + + this.ProviderControl.Bind(objNodes); } } - /// ----------------------------------------------------------------------------- - /// - /// ProcessNodes proceses a single node and its children - /// - /// The Node to process - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// ProcessNodes proceses a single node and its children. + /// + /// The Node to process. + /// ----------------------------------------------------------------------------- private void ProcessNodes(DNNNode objParent) { - if (!String.IsNullOrEmpty(objParent.JSFunction)) + if (!string.IsNullOrEmpty(objParent.JSFunction)) { - objParent.JSFunction = string.Format("if({0}){{{1}}};", objParent.JSFunction, Page.ClientScript.GetPostBackEventReference(ProviderControl.NavigationControl, objParent.ID)); + objParent.JSFunction = string.Format("if({0}){{{1}}};", objParent.JSFunction, this.Page.ClientScript.GetPostBackEventReference(this.ProviderControl.NavigationControl, objParent.ID)); } + foreach (DNNNode objNode in objParent.DNNNodes) { - ProcessNodes(objNode); + this.ProcessNodes(objNode); } } /// ----------------------------------------------------------------------------- /// - /// SetMenuDefaults sets up the default values + /// SetMenuDefaults sets up the default values. /// /// ----------------------------------------------------------------------------- private void SetMenuDefaults() { try { - //--- original page set attributes --- - ProviderControl.StyleIconWidth = 15; - ProviderControl.MouseOutHideDelay = 500; - ProviderControl.MouseOverAction = NavigationProvider.HoverAction.Expand; - ProviderControl.MouseOverDisplay = NavigationProvider.HoverDisplay.None; - - //style sheet settings - ProviderControl.CSSControl = "ModuleTitle_MenuBar"; - ProviderControl.CSSContainerRoot = "ModuleTitle_MenuContainer"; - ProviderControl.CSSNode = "ModuleTitle_MenuItem"; - ProviderControl.CSSIcon = "ModuleTitle_MenuIcon"; - ProviderControl.CSSContainerSub = "ModuleTitle_SubMenu"; - ProviderControl.CSSBreak = "ModuleTitle_MenuBreak"; - ProviderControl.CSSNodeHover = "ModuleTitle_MenuItemSel"; - ProviderControl.CSSIndicateChildSub = "ModuleTitle_MenuArrow"; - ProviderControl.CSSIndicateChildRoot = "ModuleTitle_RootMenuArrow"; - - ProviderControl.PathImage = Globals.ApplicationPath + "/Images/"; - ProviderControl.PathSystemImage = Globals.ApplicationPath + "/Images/"; - ProviderControl.IndicateChildImageSub = "action_right.gif"; - ProviderControl.IndicateChildren = true; - ProviderControl.StyleRoot = "background-color: Transparent; font-size: 1pt;"; - ProviderControl.NodeClick += MenuItem_Click; + //--- original page set attributes --- + this.ProviderControl.StyleIconWidth = 15; + this.ProviderControl.MouseOutHideDelay = 500; + this.ProviderControl.MouseOverAction = NavigationProvider.HoverAction.Expand; + this.ProviderControl.MouseOverDisplay = NavigationProvider.HoverDisplay.None; + + // style sheet settings + this.ProviderControl.CSSControl = "ModuleTitle_MenuBar"; + this.ProviderControl.CSSContainerRoot = "ModuleTitle_MenuContainer"; + this.ProviderControl.CSSNode = "ModuleTitle_MenuItem"; + this.ProviderControl.CSSIcon = "ModuleTitle_MenuIcon"; + this.ProviderControl.CSSContainerSub = "ModuleTitle_SubMenu"; + this.ProviderControl.CSSBreak = "ModuleTitle_MenuBreak"; + this.ProviderControl.CSSNodeHover = "ModuleTitle_MenuItemSel"; + this.ProviderControl.CSSIndicateChildSub = "ModuleTitle_MenuArrow"; + this.ProviderControl.CSSIndicateChildRoot = "ModuleTitle_RootMenuArrow"; + + this.ProviderControl.PathImage = Globals.ApplicationPath + "/Images/"; + this.ProviderControl.PathSystemImage = Globals.ApplicationPath + "/Images/"; + this.ProviderControl.IndicateChildImageSub = "action_right.gif"; + this.ProviderControl.IndicateChildren = true; + this.ProviderControl.StyleRoot = "background-color: Transparent; font-size: 1pt;"; + this.ProviderControl.NodeClick += this.MenuItem_Click; } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - - #region "Protected Methods" - - /// ----------------------------------------------------------------------------- - /// - /// BindMenu binds the Navigation Provider to the Node Collection - /// - /// ----------------------------------------------------------------------------- - protected void BindMenu() - { - BindMenu(Navigation.GetActionNodes(ActionRoot, this, ExpandDepth)); - } - - /// ----------------------------------------------------------------------------- - /// - /// OnAction raises the Action Event - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnAction(ActionEventArgs e) - { - if (Action != null) - { - Action(this, e); - } - } + } /// ----------------------------------------------------------------------------- /// - /// OnInit runs during the controls initialisation phase + /// OnInit runs during the controls initialisation phase. /// /// ----------------------------------------------------------------------------- protected override void OnInit(EventArgs e) { - _ProviderControl = NavigationProvider.Instance(ProviderName); - ProviderControl.PopulateOnDemand += ProviderControl_PopulateOnDemand; + this._ProviderControl = NavigationProvider.Instance(this.ProviderName); + this.ProviderControl.PopulateOnDemand += this.ProviderControl_PopulateOnDemand; base.OnInit(e); - ProviderControl.ControlID = "ctl" + ID; - ProviderControl.Initialize(); - Controls.Add(ProviderControl.NavigationControl); + this.ProviderControl.ControlID = "ctl" + this.ID; + this.ProviderControl.Initialize(); + this.Controls.Add(this.ProviderControl.NavigationControl); } /// ----------------------------------------------------------------------------- /// - /// OnLoad runs during the controls load phase + /// OnLoad runs during the controls load phase. /// /// ----------------------------------------------------------------------------- protected override void OnLoad(EventArgs e) { base.OnLoad(e); - //Add the Actions to the Action Root - ActionRoot.Actions.AddRange(ModuleControl.ModuleContext.Actions); + // Add the Actions to the Action Root + this.ActionRoot.Actions.AddRange(this.ModuleControl.ModuleContext.Actions); - //Set Menu Defaults - SetMenuDefaults(); + // Set Menu Defaults + this.SetMenuDefaults(); } /// ----------------------------------------------------------------------------- /// - /// OnPreRender runs during the controls pre-render phase + /// OnPreRender runs during the controls pre-render phase. /// /// ----------------------------------------------------------------------------- protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - BindMenu(); - } - - #endregion - - #region "Event Handlers" - + this.BindMenu(); + } + /// ----------------------------------------------------------------------------- /// - /// MenuItem_Click handles the Menu Click event + /// MenuItem_Click handles the Menu Click event. /// /// ----------------------------------------------------------------------------- private void MenuItem_Click(NavigationEventArgs args) { if (Globals.NumberMatchRegex.IsMatch(args.ID)) { - ModuleAction action = ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID)); - if (!ActionManager.ProcessAction(action)) + ModuleAction action = this.ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID)); + if (!this.ActionManager.ProcessAction(action)) { - OnAction(new ActionEventArgs(action, ModuleControl.ModuleContext.Configuration)); + this.OnAction(new ActionEventArgs(action, this.ModuleControl.ModuleContext.Configuration)); } } } /// ----------------------------------------------------------------------------- /// - /// ProviderControl_PopulateOnDemand handles the Populate On Demand Event + /// ProviderControl_PopulateOnDemand handles the Populate On Demand Event. /// /// ----------------------------------------------------------------------------- private void ProviderControl_PopulateOnDemand(NavigationEventArgs args) { - SetMenuDefaults(); - ActionRoot.Actions.AddRange(ModuleControl.ModuleContext.Actions); //Modules how add custom actions in control lifecycle will not have those actions populated... + this.SetMenuDefaults(); + this.ActionRoot.Actions.AddRange(this.ModuleControl.ModuleContext.Actions); // Modules how add custom actions in control lifecycle will not have those actions populated... - ModuleAction objAction = ActionRoot; - if (ActionRoot.ID != Convert.ToInt32(args.ID)) + ModuleAction objAction = this.ActionRoot; + if (this.ActionRoot.ID != Convert.ToInt32(args.ID)) { - objAction = ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID)); + objAction = this.ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID)); } + if (args.Node == null) { - args.Node = Navigation.GetActionNode(args.ID, ProviderControl.ID, objAction, this); + args.Node = Navigation.GetActionNode(args.ID, this.ProviderControl.ID, objAction, this); } - ProviderControl.ClearNodes(); //since we always bind we need to clear the nodes for providers that maintain their state - BindMenu(Navigation.GetActionNodes(objAction, args.Node, this, ExpandDepth)); - } - - #endregion + + this.ProviderControl.ClearNodes(); // since we always bind we need to clear the nodes for providers that maintain their state + this.BindMenu(Navigation.GetActionNodes(objAction, args.Node, this, this.ExpandDepth)); + } } } diff --git a/DNN Platform/Library/UI/Containers/Container.cs b/DNN Platform/Library/UI/Containers/Container.cs index d36a2464f4c..7ecdd5bf0dc 100644 --- a/DNN Platform/Library/UI/Containers/Container.cs +++ b/DNN Platform/Library/UI/Containers/Container.cs @@ -1,178 +1,186 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Linq; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Application; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Containers.EventListeners; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.WebControls; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { - using Web.Client; + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Application; + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Containers.EventListeners; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; /// - /// Container is the base for the Containers + /// Container is the base for the Containers. /// /// /// public class Container : UserControl { - #region Private Members - private readonly ILog _tracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); private HtmlContainerControl _contentPane; private ModuleInfo _moduleConfiguration; private ModuleHost _moduleHost; - #endregion - - #region Protected Properties - + /// ----------------------------------------------------------------------------- /// - /// Gets the Content Pane Control (Id="ContentPane") + /// Gets the ModuleControl object that this container is displaying. /// - /// An HtmlContainerControl - protected HtmlContainerControl ContentPane + /// A ModuleHost object. + public IModuleControl ModuleControl { get { - return _contentPane ?? (_contentPane = FindControl(Globals.glbDefaultPane) as HtmlContainerControl); + IModuleControl moduleControl = null; + if (this.ModuleHost != null) + { + moduleControl = this.ModuleHost.ModuleControl; + } + + return moduleControl; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Portal Settings for the current Portal + /// Gets and sets the ModuleInfo object that this container is displaying. /// - /// A PortalSettings object - protected PortalSettings PortalSettings + /// A ModuleInfo object. + public ModuleInfo ModuleConfiguration { get { - return PortalController.Instance.GetCurrentPortalSettings(); + return this._moduleConfiguration; } } - - #endregion - #region Public Properties - - /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleControl object that this container is displaying + /// Gets the Content Pane Control (Id="ContentPane"). /// - /// A ModuleHost object - public IModuleControl ModuleControl + /// An HtmlContainerControl. + protected HtmlContainerControl ContentPane { get { - IModuleControl moduleControl = null; - if (ModuleHost != null) - { - moduleControl = ModuleHost.ModuleControl; - } - return moduleControl; + return this._contentPane ?? (this._contentPane = this.FindControl(Globals.glbDefaultPane) as HtmlContainerControl); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleInfo object that this container is displaying + /// Gets the Portal Settings for the current Portal. /// - /// A ModuleInfo object - public ModuleInfo ModuleConfiguration + /// A PortalSettings object. + protected PortalSettings PortalSettings { get { - return _moduleConfiguration; + return PortalController.Instance.GetCurrentPortalSettings(); } } /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleHost object that this container is displaying + /// Gets the ModuleHost object that this container is displaying. /// - /// A ModuleHost object + /// A ModuleHost object. public ModuleHost ModuleHost { get { - return _moduleHost; + return this._moduleHost; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Parent Container for this container + /// Gets the Parent Container for this container. /// - /// A String + /// A String. public Skins.Skin ParentSkin { get { - //This finds a reference to the containing skin + // This finds a reference to the containing skin return Skins.Skin.GetParentSkin(this); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Path for this container + /// Gets the Path for this container. /// - /// A String + /// A String. public string ContainerPath { get { - return TemplateSourceDirectory + "/"; + return this.TemplateSourceDirectory + "/"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Source for this container + /// Gets or sets the Source for this container. /// - /// A String + /// A String. public string ContainerSrc { get; set; } internal bool InjectActionMenu { get; set; } - - #endregion - #region Private Helper Methods + public void SetModuleConfiguration(ModuleInfo configuration) + { + this._moduleConfiguration = configuration; + this.ProcessModule(); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnInit runs when the Container is initialised. + /// + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.InvokeContainerEvents(ContainerEventType.OnContainerInit); + } + + /// + /// OnLoad runs when the Container is loaded. + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.InvokeContainerEvents(ContainerEventType.OnContainerLoad); + } private void AddAdministratorOnlyHighlighting(string message) { - ContentPane.Controls.Add(new LiteralControl(string.Format("
    {0}
    ", message))); + this.ContentPane.Controls.Add(new LiteralControl(string.Format("
    {0}
    ", message))); } /// ----------------------------------------------------------------------------- @@ -188,31 +196,32 @@ private void ProcessChildControls(Control control) ISkinControl skinControl; foreach (Control childControl in control.Controls) { - //check if control is an action control + // check if control is an action control actions = childControl as IActionControl; if (actions != null) { - actions.ModuleControl = ModuleControl; - actions.Action += ModuleActionClick; + actions.ModuleControl = this.ModuleControl; + actions.Action += this.ModuleActionClick; } - //check if control is an actionLink control + // check if control is an actionLink control var actionLink = childControl as ActionLink; if (actionLink != null) { - actionLink.ModuleControl = ModuleControl; + actionLink.ModuleControl = this.ModuleControl; } - //check if control is a skin control + // check if control is a skin control skinControl = childControl as ISkinControl; if (skinControl != null) { - skinControl.ModuleControl = ModuleControl; + skinControl.ModuleControl = this.ModuleControl; } + if (childControl.HasControls()) { - //recursive call for child controls - ProcessChildControls(childControl); + // recursive call for child controls + this.ProcessChildControls(childControl); } } } @@ -224,19 +233,19 @@ private void ProcessChildControls(Control control) ///
    private void ProcessContentPane() { - SetAlignment(); + this.SetAlignment(); - SetBackground(); + this.SetBackground(); - SetBorder(); + this.SetBorder(); - //display visual indicator if module is only visible to administrators - string viewRoles = ModuleConfiguration.InheritViewPermissions - ? TabPermissionController.GetTabPermissions(ModuleConfiguration.TabID, ModuleConfiguration.PortalID).ToString("VIEW") - : ModuleConfiguration.ModulePermissions.ToString("VIEW"); + // display visual indicator if module is only visible to administrators + string viewRoles = this.ModuleConfiguration.InheritViewPermissions + ? TabPermissionController.GetTabPermissions(this.ModuleConfiguration.TabID, this.ModuleConfiguration.PortalID).ToString("VIEW") + : this.ModuleConfiguration.ModulePermissions.ToString("VIEW"); - string pageEditRoles = TabPermissionController.GetTabPermissions(ModuleConfiguration.TabID, ModuleConfiguration.PortalID).ToString("EDIT"); - string moduleEditRoles = ModuleConfiguration.ModulePermissions.ToString("EDIT"); + string pageEditRoles = TabPermissionController.GetTabPermissions(this.ModuleConfiguration.TabID, this.ModuleConfiguration.PortalID).ToString("EDIT"); + string moduleEditRoles = this.ModuleConfiguration.ModulePermissions.ToString("EDIT"); viewRoles = viewRoles.Replace(";", string.Empty).Trim().ToLowerInvariant(); pageEditRoles = pageEditRoles.Replace(";", string.Empty).Trim().ToLowerInvariant(); @@ -244,27 +253,30 @@ private void ProcessContentPane() var showMessage = false; var adminMessage = Null.NullString; - if (viewRoles.Equals(PortalSettings.AdministratorRoleName, StringComparison.InvariantCultureIgnoreCase) - && (moduleEditRoles.Equals(PortalSettings.AdministratorRoleName, StringComparison.InvariantCultureIgnoreCase) - || String.IsNullOrEmpty(moduleEditRoles)) - && pageEditRoles.Equals(PortalSettings.AdministratorRoleName, StringComparison.InvariantCultureIgnoreCase)) + if (viewRoles.Equals(this.PortalSettings.AdministratorRoleName, StringComparison.InvariantCultureIgnoreCase) + && (moduleEditRoles.Equals(this.PortalSettings.AdministratorRoleName, StringComparison.InvariantCultureIgnoreCase) + || string.IsNullOrEmpty(moduleEditRoles)) + && pageEditRoles.Equals(this.PortalSettings.AdministratorRoleName, StringComparison.InvariantCultureIgnoreCase)) { adminMessage = Localization.GetString("ModuleVisibleAdministrator.Text"); - showMessage = !ModuleConfiguration.HideAdminBorder && !Globals.IsAdminControl(); + showMessage = !this.ModuleConfiguration.HideAdminBorder && !Globals.IsAdminControl(); } - if (ModuleConfiguration.StartDate >= DateTime.Now) + + if (this.ModuleConfiguration.StartDate >= DateTime.Now) { - adminMessage = string.Format(Localization.GetString("ModuleEffective.Text"), ModuleConfiguration.StartDate); + adminMessage = string.Format(Localization.GetString("ModuleEffective.Text"), this.ModuleConfiguration.StartDate); showMessage = !Globals.IsAdminControl(); } - if (ModuleConfiguration.EndDate <= DateTime.Now) + + if (this.ModuleConfiguration.EndDate <= DateTime.Now) { - adminMessage = string.Format(Localization.GetString("ModuleExpired.Text"), ModuleConfiguration.EndDate); + adminMessage = string.Format(Localization.GetString("ModuleExpired.Text"), this.ModuleConfiguration.EndDate); showMessage = !Globals.IsAdminControl(); } + if (showMessage) { - AddAdministratorOnlyHighlighting(adminMessage); + this.AddAdministratorOnlyHighlighting(adminMessage); } } @@ -274,17 +286,17 @@ private void ProcessContentPane() ///
    private void ProcessFooter() { - //inject the footer - if (!String.IsNullOrEmpty(ModuleConfiguration.Footer)) + // inject the footer + if (!string.IsNullOrEmpty(this.ModuleConfiguration.Footer)) { - var footer = new Literal {Text = ModuleConfiguration.Footer}; - ContentPane.Controls.Add(footer); + var footer = new Literal { Text = this.ModuleConfiguration.Footer }; + this.ContentPane.Controls.Add(footer); } - - //inject an end comment around the module content + + // inject an end comment around the module content if (!Globals.IsAdminControl()) { - ContentPane.Controls.Add(new LiteralControl("")); + this.ContentPane.Controls.Add(new LiteralControl("")); } } @@ -296,86 +308,93 @@ private void ProcessHeader() { if (!Globals.IsAdminControl()) { - //inject a start comment around the module content - ContentPane.Controls.Add(new LiteralControl("")); + // inject a start comment around the module content + this.ContentPane.Controls.Add(new LiteralControl("")); } - - //inject the header - if (!String.IsNullOrEmpty(ModuleConfiguration.Header)) + + // inject the header + if (!string.IsNullOrEmpty(this.ModuleConfiguration.Header)) { - var header = new Literal {Text = ModuleConfiguration.Header}; - ContentPane.Controls.Add(header); + var header = new Literal { Text = this.ModuleConfiguration.Header }; + this.ContentPane.Controls.Add(header); } } /// ----------------------------------------------------------------------------- /// - /// ProcessModule processes the module which is attached to this container + /// ProcessModule processes the module which is attached to this container. /// private void ProcessModule() { - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"Container.ProcessModule Start (TabId:{PortalSettings.ActiveTab.TabID},ModuleID: {ModuleConfiguration.ModuleDefinition.DesktopModuleID}): Module FriendlyName: '{ModuleConfiguration.ModuleDefinition.FriendlyName}')"); + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"Container.ProcessModule Start (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleID: {this.ModuleConfiguration.ModuleDefinition.DesktopModuleID}): Module FriendlyName: '{this.ModuleConfiguration.ModuleDefinition.FriendlyName}')"); + } - if (ContentPane != null) + if (this.ContentPane != null) { - //Process Content Pane Attributes - ProcessContentPane(); + // Process Content Pane Attributes + this.ProcessContentPane(); // always add the actions menu as the first item in the content pane. - if (InjectActionMenu && !ModuleHost.IsViewMode(ModuleConfiguration, PortalSettings) && Request.QueryString["dnnprintmode"] != "true") + if (this.InjectActionMenu && !ModuleHost.IsViewMode(this.ModuleConfiguration, this.PortalSettings) && this.Request.QueryString["dnnprintmode"] != "true") { JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ContentPane.Controls.Add(LoadControl(PortalSettings.DefaultModuleActionMenu)); + this.ContentPane.Controls.Add(this.LoadControl(this.PortalSettings.DefaultModuleActionMenu)); - //register admin.css - ClientResourceManager.RegisterAdminStylesheet(Page, Globals.HostPath + "admin.css"); + // register admin.css + ClientResourceManager.RegisterAdminStylesheet(this.Page, Globals.HostPath + "admin.css"); } - //Process Module Header - ProcessHeader(); + // Process Module Header + this.ProcessHeader(); + + // Try to load the module control + this._moduleHost = new ModuleHost(this.ModuleConfiguration, this.ParentSkin, this); + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"Container.ProcessModule Info (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleID: {this.ModuleConfiguration.ModuleDefinition.DesktopModuleID}): ControlPane.Controls.Add(ModuleHost:{this._moduleHost.ID})"); + } - //Try to load the module control - _moduleHost = new ModuleHost(ModuleConfiguration, ParentSkin, this); - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"Container.ProcessModule Info (TabId:{PortalSettings.ActiveTab.TabID},ModuleID: {ModuleConfiguration.ModuleDefinition.DesktopModuleID}): ControlPane.Controls.Add(ModuleHost:{_moduleHost.ID})"); + this.ContentPane.Controls.Add(this.ModuleHost); - ContentPane.Controls.Add(ModuleHost); + // Process Module Footer + this.ProcessFooter(); - //Process Module Footer - ProcessFooter(); - - //Process the Action Controls - if (ModuleHost != null && ModuleControl != null) + // Process the Action Controls + if (this.ModuleHost != null && this.ModuleControl != null) { - ProcessChildControls(this); + this.ProcessChildControls(this); } - - //Add Module Stylesheets - ProcessStylesheets(ModuleHost != null); + + // Add Module Stylesheets + this.ProcessStylesheets(this.ModuleHost != null); + } + + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"Container.ProcessModule End (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleID: {this.ModuleConfiguration.ModuleDefinition.DesktopModuleID}): Module FriendlyName: '{this.ModuleConfiguration.ModuleDefinition.FriendlyName}')"); } - if (_tracelLogger.IsDebugEnabled) - _tracelLogger.Debug($"Container.ProcessModule End (TabId:{PortalSettings.ActiveTab.TabID},ModuleID: {ModuleConfiguration.ModuleDefinition.DesktopModuleID}): Module FriendlyName: '{ModuleConfiguration.ModuleDefinition.FriendlyName}')"); } - /// ----------------------------------------------------------------------------- - /// - /// ProcessStylesheets processes the Module and Container stylesheets and adds - /// them to the Page. - /// + /// ----------------------------------------------------------------------------- + /// + /// ProcessStylesheets processes the Module and Container stylesheets and adds + /// them to the Page. + /// private void ProcessStylesheets(bool includeModuleCss) { - ClientResourceManager.RegisterStyleSheet(Page, ContainerPath + "container.css", FileOrder.Css.ContainerCss); - ClientResourceManager.RegisterStyleSheet(Page, ContainerSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificContainerCss); + ClientResourceManager.RegisterStyleSheet(this.Page, this.ContainerPath + "container.css", FileOrder.Css.ContainerCss); + ClientResourceManager.RegisterStyleSheet(this.Page, this.ContainerSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificContainerCss); - //process the base class module properties + // process the base class module properties if (includeModuleCss) { - string controlSrc = ModuleConfiguration.ModuleControl.ControlSrc; - string folderName = ModuleConfiguration.DesktopModule.FolderName; + string controlSrc = this.ModuleConfiguration.ModuleControl.ControlSrc; + string folderName = this.ModuleConfiguration.DesktopModule.FolderName; - string stylesheet = ""; - if (String.IsNullOrEmpty(folderName)==false) + string stylesheet = string.Empty; + if (string.IsNullOrEmpty(folderName) == false) { if (controlSrc.EndsWith(".mvc")) { @@ -385,76 +404,52 @@ private void ProcessStylesheets(bool includeModuleCss) { stylesheet = Globals.ApplicationPath + "/DesktopModules/" + folderName.Replace("\\", "/") + "/module.css"; } - ClientResourceManager.RegisterStyleSheet(Page, stylesheet, FileOrder.Css.ModuleCss); + + ClientResourceManager.RegisterStyleSheet(this.Page, stylesheet, FileOrder.Css.ModuleCss); } + var ix = controlSrc.LastIndexOf("/", StringComparison.Ordinal); if (ix >= 0) { stylesheet = Globals.ApplicationPath + "/" + controlSrc.Substring(0, ix + 1) + "module.css"; - ClientResourceManager.RegisterStyleSheet(Page, stylesheet, FileOrder.Css.ModuleCss); + ClientResourceManager.RegisterStyleSheet(this.Page, stylesheet, FileOrder.Css.ModuleCss); } } } private void SetAlignment() { - if (!String.IsNullOrEmpty(ModuleConfiguration.Alignment)) + if (!string.IsNullOrEmpty(this.ModuleConfiguration.Alignment)) { - if (ContentPane.Attributes["class"] != null) + if (this.ContentPane.Attributes["class"] != null) { - ContentPane.Attributes["class"] = ContentPane.Attributes["class"] + " DNNAlign" + ModuleConfiguration.Alignment.ToLowerInvariant(); + this.ContentPane.Attributes["class"] = this.ContentPane.Attributes["class"] + " DNNAlign" + this.ModuleConfiguration.Alignment.ToLowerInvariant(); } else { - ContentPane.Attributes["class"] = "DNNAlign" + ModuleConfiguration.Alignment.ToLowerInvariant(); + this.ContentPane.Attributes["class"] = "DNNAlign" + this.ModuleConfiguration.Alignment.ToLowerInvariant(); } } } private void SetBackground() { - if (!String.IsNullOrEmpty(ModuleConfiguration.Color)) + if (!string.IsNullOrEmpty(this.ModuleConfiguration.Color)) { - ContentPane.Style["background-color"] = ModuleConfiguration.Color; + this.ContentPane.Style["background-color"] = this.ModuleConfiguration.Color; } } private void SetBorder() { - if (!String.IsNullOrEmpty(ModuleConfiguration.Border)) + if (!string.IsNullOrEmpty(this.ModuleConfiguration.Border)) { - ContentPane.Style["border-top"] = String.Format("{0}px #000000 solid", ModuleConfiguration.Border); - ContentPane.Style["border-bottom"] = String.Format("{0}px #000000 solid", ModuleConfiguration.Border); - ContentPane.Style["border-right"] = String.Format("{0}px #000000 solid", ModuleConfiguration.Border); - ContentPane.Style["border-left"] = String.Format("{0}px #000000 solid", ModuleConfiguration.Border); + this.ContentPane.Style["border-top"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); + this.ContentPane.Style["border-bottom"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); + this.ContentPane.Style["border-right"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); + this.ContentPane.Style["border-left"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); } } - - #endregion - - #region Protected Methods - - /// ----------------------------------------------------------------------------- - /// - /// OnInit runs when the Container is initialised. - /// - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - InvokeContainerEvents(ContainerEventType.OnContainerInit); - } - - /// - /// OnLoad runs when the Container is loaded. - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - - InvokeContainerEvents(ContainerEventType.OnContainerLoad); - } /// ----------------------------------------------------------------------------- /// @@ -464,7 +459,7 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - InvokeContainerEvents(ContainerEventType.OnContainerPreRender); + this.InvokeContainerEvents(ContainerEventType.OnContainerPreRender); } /// ----------------------------------------------------------------------------- @@ -475,7 +470,7 @@ protected override void OnUnload(EventArgs e) { base.OnUnload(e); - InvokeContainerEvents(ContainerEventType.OnContainerUnLoad); + this.InvokeContainerEvents(ContainerEventType.OnContainerUnLoad); } private void InvokeContainerEvents(ContainerEventType containerEventType) @@ -490,46 +485,30 @@ private void InvokeContainerEvents(ContainerEventType containerEventType) } } } - - #endregion - - #region Public Methods - - public void SetModuleConfiguration(ModuleInfo configuration) - { - _moduleConfiguration = configuration; - ProcessModule(); - } - - #endregion - - #region Event Handlers /// ----------------------------------------------------------------------------- /// /// ModuleAction_Click runs when a ModuleAction is clicked. /// - /// The Module Action must be configured to fire an event (it may be configured + /// The Module Action must be configured to fire an event (it may be configured /// to redirect to a new url). The event handler finds the Parent Container and invokes each /// registered ModuleActionEventListener delegate. - /// + /// /// Note: with the refactoring of this to the Container, this could be handled at the container level. /// However, for legacy purposes this is left this way, as many modules would have registered their /// listeners on the Container directly, rather than through the helper method in PortalModuleBase. private void ModuleActionClick(object sender, ActionEventArgs e) { - //Search through the listeners - foreach (ModuleActionEventListener listener in ParentSkin.ActionEventListeners) - { - //If the associated module has registered a listener + // Search through the listeners + foreach (ModuleActionEventListener listener in this.ParentSkin.ActionEventListeners) + { + // If the associated module has registered a listener if (e.ModuleConfiguration.ModuleID == listener.ModuleID) { - //Invoke the listener to handle the ModuleAction_Click event + // Invoke the listener to handle the ModuleAction_Click event listener.ActionEvent.Invoke(sender, e); } } } - - #endregion } } diff --git a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventArgs.cs b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventArgs.cs index bbb366c3089..2583304acb7 100644 --- a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventArgs.cs +++ b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventArgs.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers.EventListeners { - ///----------------------------------------------------------------------------- + using System; + + /// ----------------------------------------------------------------------------- /// - /// ContainerEventArgs provides a custom EventARgs class for Container Events + /// ContainerEventArgs provides a custom EventARgs class for Container Events. /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class ContainerEventArgs : EventArgs { private readonly Container _Container; public ContainerEventArgs(Container container) { - _Container = container; + this._Container = container; } public Container Container { get { - return _Container; + return this._Container; } } } diff --git a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs index e75e7e78497..0b55e87a934 100644 --- a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs +++ b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Containers.EventListeners { /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventListener.cs b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventListener.cs index 7165b4d8be2..1a1f31b0f13 100644 --- a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventListener.cs +++ b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventListener.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Containers.EventListeners { public class ContainerEventListener @@ -11,15 +11,15 @@ public class ContainerEventListener public ContainerEventListener(ContainerEventType type, ContainerEventHandler e) { - _Type = type; - _ContainerEvent = e; + this._Type = type; + this._ContainerEvent = e; } public ContainerEventType EventType { get { - return _Type; + return this._Type; } } @@ -27,7 +27,7 @@ public ContainerEventHandler ContainerEvent { get { - return _ContainerEvent; + return this._ContainerEvent; } } } diff --git a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventType.cs b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventType.cs index 5909cac5073..dceadadef34 100644 --- a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventType.cs +++ b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventType.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Containers.EventListeners { - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// ContainerEventType provides a custom enum for Container event types + /// ContainerEventType provides a custom enum for Container event types. /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public enum ContainerEventType { OnContainerInit, OnContainerLoad, OnContainerPreRender, - OnContainerUnLoad + OnContainerUnLoad, } } diff --git a/DNN Platform/Library/UI/Containers/IActionControl.cs b/DNN Platform/Library/UI/Containers/IActionControl.cs index 9eaf2a03134..e5428c256e7 100644 --- a/DNN Platform/Library/UI/Containers/IActionControl.cs +++ b/DNN Platform/Library/UI/Containers/IActionControl.cs @@ -1,29 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.UI.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers - /// Class : IActionControl + /// Class : IActionControl /// ----------------------------------------------------------------------------- /// - /// IActionControl provides a common INterface for Action Controls + /// IActionControl provides a common INterface for Action Controls. /// /// ----------------------------------------------------------------------------- public interface IActionControl { + event ActionEventHandler Action; + ActionManager ActionManager { get; } + IModuleControl ModuleControl { get; set; } - event ActionEventHandler Action; } } diff --git a/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs b/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs index 9c518b913c7..bad4b26280f 100644 --- a/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs +++ b/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs @@ -1,32 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Personalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.ControlPanels { + using System; + using System.Collections; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Personalization; + /// ----------------------------------------------------------------------------- /// /// The ControlPanel class defines a custom base class inherited by all @@ -37,102 +32,93 @@ namespace DotNetNuke.UI.ControlPanels /// ----------------------------------------------------------------------------- public class ControlPanelBase : UserControl { - #region Private Members - private string _localResourceFile; - - #endregion - #region Protected Properties + protected enum ViewPermissionType + { + View = 0, + Edit = 1, + } /// ----------------------------------------------------------------------------- /// - /// Gets whether the ControlPanel is Visible + /// Gets or sets and sets the Local ResourceFile for the Control Panel. /// - /// A Boolean + /// A String. /// ----------------------------------------------------------------------------- - protected bool IsVisible + public string LocalResourceFile { get { - return PortalSettings.ControlPanelVisible; + string fileRoot; + if (string.IsNullOrEmpty(this._localResourceFile)) + { + fileRoot = this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + this.ID; + } + else + { + fileRoot = this._localResourceFile; + } + + return fileRoot; } + + set + { + this._localResourceFile = value; + } + } + + public virtual bool IncludeInControlHierarchy + { + get { return true; } } /// ----------------------------------------------------------------------------- /// - /// Gets the current Portal Settings + /// Gets a value indicating whether gets whether the ControlPanel is Visible. /// + /// A Boolean. /// ----------------------------------------------------------------------------- - protected PortalSettings PortalSettings + protected bool IsVisible { get { - return PortalController.Instance.GetCurrentPortalSettings(); + return this.PortalSettings.ControlPanelVisible; } } /// ----------------------------------------------------------------------------- /// - /// Gets the User mode of the Control Panel + /// Gets the current Portal Settings. /// - /// A Boolean /// ----------------------------------------------------------------------------- - protected PortalSettings.Mode UserMode + protected PortalSettings PortalSettings { get { - return PortalSettings.UserMode; + return PortalController.Instance.GetCurrentPortalSettings(); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Local ResourceFile for the Control Panel + /// Gets the User mode of the Control Panel. /// - /// A String + /// A Boolean. /// ----------------------------------------------------------------------------- - public string LocalResourceFile + protected PortalSettings.Mode UserMode { get { - string fileRoot; - if (String.IsNullOrEmpty(_localResourceFile)) - { - fileRoot = TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + ID; - } - else - { - fileRoot = _localResourceFile; - } - return fileRoot; + return this.PortalSettings.UserMode; } - set - { - _localResourceFile = value; - } - } - - - public virtual bool IncludeInControlHierarchy - { - get { return true; } } public virtual bool IsDockable { - get { return false; } - set { } - } - - protected bool IsModuleAdmin() - { - return IsModuleAdminInternal(); - } - - protected bool IsPageAdmin() - { - return IsPageAdminInternal(); + get { return false; } + set { } } internal static bool IsModuleAdminInternal() @@ -150,6 +136,7 @@ internal static bool IsModuleAdminInternal() } } } + return PortalController.Instance.GetCurrentPortalSettings().ControlPanelSecurity == PortalSettings.ControlPanelPermission.ModuleEditor && _IsModuleAdmin; } @@ -161,98 +148,74 @@ internal static bool IsPageAdminInternal() { _IsPageAdmin = true; } + return _IsPageAdmin; } - #endregion - - #region Private Methods - - /// ----------------------------------------------------------------------------- - /// - /// Adds a Module Permission - /// - /// Module Info - /// The permission to add - /// The Id of the role to add the permission for. - /// Operator - /// Whether allow to access the module - /// ----------------------------------------------------------------------------- - private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) + protected bool IsModuleAdmin() { - var objModulePermission = new ModulePermissionInfo(); - objModulePermission.ModuleID = objModule.ModuleID; - objModulePermission.PermissionID = permission.PermissionID; - objModulePermission.RoleID = roleId; - objModulePermission.UserID = userId; - objModulePermission.PermissionKey = permission.PermissionKey; - objModulePermission.AllowAccess = allowAccess; + return IsModuleAdminInternal(); + } - //add the permission to the collection - if (!objModule.ModulePermissions.Contains(objModulePermission)) - { - objModule.ModulePermissions.Add(objModulePermission); - } - return objModulePermission; + protected bool IsPageAdmin() + { + return IsPageAdminInternal(); } - - #endregion - #region Protected Methods - /// ----------------------------------------------------------------------------- /// - /// Adds an Existing Module to a Pane + /// Adds an Existing Module to a Pane. /// - /// The alignment for the Modue - /// The Id of the existing module - /// The id of the tab - /// The pane to add the module to - /// The relative position within the pane for the module + /// The alignment for the Modue. + /// The Id of the existing module. + /// The id of the tab. + /// The pane to add the module to. + /// The relative position within the pane for the module. /// ----------------------------------------------------------------------------- protected void AddExistingModule(int moduleId, int tabId, string paneName, int position, string align) { ModuleInfo objModule; int UserId = -1; - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); UserId = objUserInfo.UserID; } + objModule = ModuleController.Instance.GetModule(moduleId, tabId, false); if (objModule != null) { - //clone the module object ( to avoid creating an object reference to the data cache ) + // clone the module object ( to avoid creating an object reference to the data cache ) ModuleInfo objClone = objModule.Clone(); - objClone.TabID = PortalSettings.ActiveTab.TabID; + objClone.TabID = this.PortalSettings.ActiveTab.TabID; objClone.ModuleOrder = position; objClone.PaneName = paneName; objClone.Alignment = align; ModuleController.Instance.AddModule(objClone); - EventLogController.Instance.AddLog(objClone, PortalSettings, UserId, "", EventLogController.EventLogType.MODULE_CREATED); + EventLogController.Instance.AddLog(objClone, this.PortalSettings, UserId, string.Empty, EventLogController.EventLogType.MODULE_CREATED); } } /// ----------------------------------------------------------------------------- /// - /// Adds a New Module to a Pane + /// Adds a New Module to a Pane. /// - /// The alignment for the Modue - /// The Id of the DesktopModule - /// The View Permission Type for the Module - /// The Title for the resulting module - /// The pane to add the module to - /// The relative position within the pane for the module + /// The alignment for the Modue. + /// The Id of the DesktopModule. + /// The View Permission Type for the Module. + /// The Title for the resulting module. + /// The pane to add the module to. + /// The relative position within the pane for the module. /// ----------------------------------------------------------------------------- protected void AddNewModule(string title, int desktopModuleId, string paneName, int position, ViewPermissionType permissionType, string align) { - TabPermissionCollection objTabPermissions = PortalSettings.ActiveTab.TabPermissions; + TabPermissionCollection objTabPermissions = this.PortalSettings.ActiveTab.TabPermissions; var objPermissionController = new PermissionController(); try { DesktopModuleInfo desktopModule; - if (!DesktopModuleController.GetDesktopModules(PortalSettings.PortalId).TryGetValue(desktopModuleId, out desktopModule)) + if (!DesktopModuleController.GetDesktopModules(this.PortalSettings.PortalId).TryGetValue(desktopModuleId, out desktopModule)) { throw new ArgumentException("desktopModuleId"); } @@ -261,21 +224,23 @@ protected void AddNewModule(string title, int desktopModuleId, string paneName, { Exceptions.LogException(ex); } + int UserId = -1; - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); UserId = objUserInfo.UserID; } + foreach (ModuleDefinitionInfo objModuleDefinition in ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values) { var objModule = new ModuleInfo(); - objModule.Initialize(PortalSettings.PortalId); - objModule.PortalID = PortalSettings.PortalId; - objModule.TabID = PortalSettings.ActiveTab.TabID; + objModule.Initialize(this.PortalSettings.PortalId); + objModule.PortalID = this.PortalSettings.PortalId; + objModule.TabID = this.PortalSettings.ActiveTab.TabID; objModule.ModuleOrder = position; - if (String.IsNullOrEmpty(title)) + if (string.IsNullOrEmpty(title)) { objModule.ModuleTitle = objModuleDefinition.FriendlyName; } @@ -283,6 +248,7 @@ protected void AddNewModule(string title, int desktopModuleId, string paneName, { objModule.ModuleTitle = title; } + objModule.PaneName = paneName; objModule.ModuleDefID = objModuleDefinition.ModuleDefID; if (objModuleDefinition.DefaultCacheTime > 0) @@ -297,6 +263,7 @@ protected void AddNewModule(string title, int desktopModuleId, string paneName, } } } + switch (permissionType) { case ViewPermissionType.View: @@ -306,62 +273,66 @@ protected void AddNewModule(string title, int desktopModuleId, string paneName, objModule.InheritViewPermissions = false; break; } - - //get the default module view permissions + + // get the default module view permissions ArrayList arrSystemModuleViewPermissions = objPermissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); - //get the permissions from the page + // get the permissions from the page foreach (TabPermissionInfo objTabPermission in objTabPermissions) { if (objTabPermission.PermissionKey == "VIEW" && permissionType == ViewPermissionType.View) { - //Don't need to explicitly add View permisisons if "Same As Page" + // Don't need to explicitly add View permisisons if "Same As Page" continue; } - - //get the system module permissions for the permissionkey + + // get the system module permissions for the permissionkey ArrayList arrSystemModulePermissions = objPermissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", objTabPermission.PermissionKey); - //loop through the system module permissions + + // loop through the system module permissions int j; for (j = 0; j <= arrSystemModulePermissions.Count - 1; j++) { PermissionInfo objSystemModulePermission; - objSystemModulePermission = (PermissionInfo) arrSystemModulePermissions[j]; + objSystemModulePermission = (PermissionInfo)arrSystemModulePermissions[j]; if (objSystemModulePermission.PermissionKey == "VIEW" && permissionType == ViewPermissionType.Edit && objTabPermission.PermissionKey != "EDIT") { - //Only Page Editors get View permissions if "Page Editors Only" + // Only Page Editors get View permissions if "Page Editors Only" continue; } - ModulePermissionInfo objModulePermission = AddModulePermission(objModule, - objSystemModulePermission, - objTabPermission.RoleID, - objTabPermission.UserID, - objTabPermission.AllowAccess); - //ensure that every EDIT permission which allows access also provides VIEW permission + ModulePermissionInfo objModulePermission = this.AddModulePermission( + objModule, + objSystemModulePermission, + objTabPermission.RoleID, + objTabPermission.UserID, + objTabPermission.AllowAccess); + + // ensure that every EDIT permission which allows access also provides VIEW permission if (objModulePermission.PermissionKey == "EDIT" && objModulePermission.AllowAccess) { - ModulePermissionInfo objModuleViewperm = AddModulePermission(objModule, - (PermissionInfo) arrSystemModuleViewPermissions[0], - objModulePermission.RoleID, - objModulePermission.UserID, - true); + ModulePermissionInfo objModuleViewperm = this.AddModulePermission( + objModule, + (PermissionInfo)arrSystemModuleViewPermissions[0], + objModulePermission.RoleID, + objModulePermission.UserID, + true); } } - - //Get the custom Module Permissions, Assume that roles with Edit Tab Permissions - //are automatically assigned to the Custom Module Permissions + + // Get the custom Module Permissions, Assume that roles with Edit Tab Permissions + // are automatically assigned to the Custom Module Permissions if (objTabPermission.PermissionKey == "EDIT") { ArrayList arrCustomModulePermissions = objPermissionController.GetPermissionsByModuleDefID(objModule.ModuleDefID); - //loop through the custom module permissions + // loop through the custom module permissions for (j = 0; j <= arrCustomModulePermissions.Count - 1; j++) { - //create the module permission + // create the module permission PermissionInfo objCustomModulePermission; - objCustomModulePermission = (PermissionInfo) arrCustomModulePermissions[j]; - AddModulePermission(objModule, objCustomModulePermission, objTabPermission.RoleID, objTabPermission.UserID, objTabPermission.AllowAccess); + objCustomModulePermission = (PermissionInfo)arrCustomModulePermissions[j]; + this.AddModulePermission(objModule, objCustomModulePermission, objTabPermission.RoleID, objTabPermission.UserID, objTabPermission.AllowAccess); } } } @@ -369,7 +340,8 @@ protected void AddNewModule(string title, int desktopModuleId, string paneName, if (PortalSettings.Current.ContentLocalizationEnabled) { Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId); - //set the culture of the module to that of the tab + + // set the culture of the module to that of the tab var tabInfo = TabController.Instance.GetTab(objModule.TabID, PortalSettings.Current.PortalId, false); objModule.CultureCode = tabInfo != null ? tabInfo.CultureCode : defaultLocale.Code; } @@ -386,10 +358,40 @@ protected void AddNewModule(string title, int desktopModuleId, string paneName, /// ----------------------------------------------------------------------------- /// - /// Builds a URL + /// Adds a Module Permission. /// - /// The friendly name of the Module - /// The ID of the portal + /// Module Info. + /// The permission to add. + /// The Id of the role to add the permission for. + /// Operator. + /// Whether allow to access the module. + /// ----------------------------------------------------------------------------- + private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) + { + var objModulePermission = new ModulePermissionInfo(); + objModulePermission.ModuleID = objModule.ModuleID; + objModulePermission.PermissionID = permission.PermissionID; + objModulePermission.RoleID = roleId; + objModulePermission.UserID = userId; + objModulePermission.PermissionKey = permission.PermissionKey; + objModulePermission.AllowAccess = allowAccess; + + // add the permission to the collection + if (!objModule.ModulePermissions.Contains(objModulePermission)) + { + objModule.ModulePermissions.Add(objModulePermission); + } + + return objModulePermission; + } + + /// ----------------------------------------------------------------------------- + /// + /// Builds a URL. + /// + /// The friendly name of the Module. + /// The ID of the portal. + /// /// ----------------------------------------------------------------------------- protected string BuildURL(int PortalID, string FriendlyName) { @@ -406,6 +408,7 @@ protected string BuildURL(int PortalID, string FriendlyName) strURL = TestableGlobals.Instance.NavigateURL(objModule.TabID); } } + return strURL; } @@ -417,54 +420,43 @@ protected bool GetModulePermission(int PortalID, string FriendlyName) { AllowAccess = ModulePermissionController.CanViewModule(objModule); } + return AllowAccess; } /// ----------------------------------------------------------------------------- /// - /// Sets the UserMode + /// Sets the UserMode. /// - /// The userMode to set + /// The userMode to set. /// ----------------------------------------------------------------------------- protected void SetUserMode(string userMode) { - Personalization.SetProfile("Usability", "UserMode" + PortalSettings.PortalId, userMode.ToUpper()); + Personalization.SetProfile("Usability", "UserMode" + this.PortalSettings.PortalId, userMode.ToUpper()); } /// ----------------------------------------------------------------------------- /// - /// Sets the current Visible Mode + /// Sets the current Visible Mode. /// - /// A flag indicating whether the Control Panel should be visible + /// A flag indicating whether the Control Panel should be visible. /// ----------------------------------------------------------------------------- protected void SetVisibleMode(bool isVisible) { - Personalization.SetProfile("Usability", "ControlPanelVisible" + PortalSettings.PortalId, isVisible.ToString()); + Personalization.SetProfile("Usability", "ControlPanelVisible" + this.PortalSettings.PortalId, isVisible.ToString()); } - protected override void OnInit(EventArgs e) - { - if (this.Page.Items.Contains(typeof(ControlPanelBase)) && this.Page.Items[typeof(ControlPanelBase)] is ControlPanelBase) - { - this.Parent.Controls.Remove(this); - } - else - { - this.Page.Items[typeof(ControlPanelBase)] = this; - base.OnInit(e); - } - } - - #endregion - - #region Nested type: ViewPermissionType - - protected enum ViewPermissionType + protected override void OnInit(EventArgs e) { - View = 0, - Edit = 1 + if (this.Page.Items.Contains(typeof(ControlPanelBase)) && this.Page.Items[typeof(ControlPanelBase)] is ControlPanelBase) + { + this.Parent.Controls.Remove(this); + } + else + { + this.Page.Items[typeof(ControlPanelBase)] = this; + base.OnInit(e); + } } - - #endregion } } diff --git a/DNN Platform/Library/UI/ControlUtilities.cs b/DNN Platform/Library/UI/ControlUtilities.cs index d77e53e2a9a..3099949d7cd 100644 --- a/DNN Platform/Library/UI/ControlUtilities.cs +++ b/DNN Platform/Library/UI/ControlUtilities.cs @@ -1,21 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -using DotNetNuke.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI { + using System; + using System.Web.UI; + + using DotNetNuke.Framework; + public class ControlUtilities { - public static T FindParentControl(Control control) where T : Control + public static T FindParentControl(Control control) + where T : Control { T parent = default(T); if (control.Parent == null) @@ -34,13 +30,15 @@ public static T FindParentControl(Control control) where T : Control parent = FindParentControl(control.Parent); } } + return parent; } - public static T FindControl(Control control, string id, bool recursive) where T : Control + public static T FindControl(Control control, string id, bool recursive) + where T : Control { T target = null; - if(control.Parent != null) + if (control.Parent != null) { target = control.Parent.FindControl(id) as T; @@ -49,55 +47,64 @@ public static T FindControl(Control control, string id, bool recursive) where target = FindControl(control.Parent, id, true); } } - + return target; } - public static T FindFirstDescendent(Control control) where T : Control - { - return FindFirstDescendent(control, idx => idx is T); + public static T FindFirstDescendent(Control control) + where T : Control + { + return FindFirstDescendent(control, idx => idx is T); } - public static T FindFirstDescendent(Control control, Predicate predicate) where T : Control - { - if (predicate(control)) return control as T; - - foreach (Control childControl in control.Controls) - { - T descendent = FindFirstDescendent(childControl, predicate); - if (descendent != null) - return descendent; - } - - return null; + public static T FindFirstDescendent(Control control, Predicate predicate) + where T : Control + { + if (predicate(control)) + { + return control as T; + } + + foreach (Control childControl in control.Controls) + { + T descendent = FindFirstDescendent(childControl, predicate); + if (descendent != null) + { + return descendent; + } + } + + return null; } /// ----------------------------------------------------------------------------- /// - /// LoadControl loads a control and returns a reference to the control + /// LoadControl loads a control and returns a reference to the control. /// - /// The type of control to Load - /// The parent Container Control + /// The type of control to Load. + /// The parent Container Control. /// The source for the control. This can either be a User Control (.ascx) or a compiled /// control. - /// A Control of type T + /// A Control of type T. /// ----------------------------------------------------------------------------- - public static T LoadControl(TemplateControl containerControl, string ControlSrc) where T : Control + public static T LoadControl(TemplateControl containerControl, string ControlSrc) + where T : Control { T ctrl; - //load the control dynamically + // load the control dynamically if (ControlSrc.EndsWith(".ascx", StringComparison.InvariantCultureIgnoreCase)) { - //load from a user control on the file system - ctrl = (T) containerControl.LoadControl("~/" + ControlSrc); + // load from a user control on the file system + ctrl = (T)containerControl.LoadControl("~/" + ControlSrc); } else { - //load from a typename in an assembly ( ie. server control ) + // load from a typename in an assembly ( ie. server control ) Type objType = Reflection.CreateType(ControlSrc); - ctrl = (T) containerControl.LoadControl(objType, null); + ctrl = (T)containerControl.LoadControl(objType, null); } + return ctrl; } } diff --git a/DNN Platform/Library/UI/FavIcon.cs b/DNN Platform/Library/UI/FavIcon.cs index 87b70e9e68f..96b6723baa8 100644 --- a/DNN Platform/Library/UI/FavIcon.cs +++ b/DNN Platform/Library/UI/FavIcon.cs @@ -1,61 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Internals { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.FileSystem; + /// - /// Manages the FavIcon of a portal + /// Manages the FavIcon of a portal. /// public class FavIcon { private const string SettingName = "FavIconPath"; - private readonly int _portalId; - - /// - /// Initializes a FavIcon instance + private readonly int _portalId; + + /// + /// Initializes a new instance of the class. + /// Initializes a FavIcon instance. /// - /// The id of the portal + /// The id of the portal. public FavIcon(int portalId) { - _portalId = portalId; + this._portalId = portalId; } /// - /// Get the path of the favicon file relative to the portal root + /// Get the HTML for a favicon link. /// - /// This relative path is only relevant to use with Host/Portal Settings the path is not guaranteed any - /// physical relevance in the local file system - /// Path to the favicon file relative to portal root, or empty string when there is no favicon set - public string GetSettingPath() - { - return PortalController.GetPortalSetting(SettingName, _portalId, ""); - } - - /// - /// Update the file to use for a favIcon - /// - /// The file id or Null.NullInteger for none - public void Update(int fileId) - { - PortalController.UpdatePortalSetting(_portalId, SettingName, fileId != Null.NullInteger ? string.Format("FileID={0}", fileId) : "", /*clearCache*/ true); - DataCache.ClearCache(GetCacheKey(_portalId)); - } - - /// - /// Get the HTML for a favicon link - /// - /// The portal id - /// The HTML for the favicon link for the portal, or an empty string if there is no favicon + /// The portal id. + /// The HTML for the favicon link for the portal, or an empty string if there is no favicon. public static string GetHeaderLink(int portalId) { string headerLink; @@ -63,7 +43,7 @@ public static string GetHeaderLink(int portalId) if (fromCache == null) { - //only create an instance of FavIcon when there is a cache miss + // only create an instance of FavIcon when there is a cache miss string favIconPath = new FavIcon(portalId).GetRelativeUrl(); if (!string.IsNullOrEmpty(favIconPath)) { @@ -71,11 +51,11 @@ public static string GetHeaderLink(int portalId) } else { - headerLink = ""; + headerLink = string.Empty; } - //cache link or empty string to ensure we don't always have a - //cache miss when no favicon is in use + // cache link or empty string to ensure we don't always have a + // cache miss when no favicon is in use UpdateCachedHeaderLink(portalId, headerLink); } else @@ -86,21 +66,25 @@ public static string GetHeaderLink(int portalId) return headerLink; } - private string GetRelativeUrl() + /// + /// Get the path of the favicon file relative to the portal root. + /// + /// This relative path is only relevant to use with Host/Portal Settings the path is not guaranteed any + /// physical relevance in the local file system. + /// Path to the favicon file relative to portal root, or empty string when there is no favicon set. + public string GetSettingPath() { - var fileInfo = GetFileInfo(); - return fileInfo == null ? string.Empty : FileManager.Instance.GetUrl(fileInfo); + return PortalController.GetPortalSetting(SettingName, this._portalId, string.Empty); } - private IFileInfo GetFileInfo() + /// + /// Update the file to use for a favIcon. + /// + /// The file id or Null.NullInteger for none. + public void Update(int fileId) { - var path = GetSettingPath(); - if( ! String.IsNullOrEmpty(path) ) - { - return FileManager.Instance.GetFile(_portalId, path); - } - - return null; + PortalController.UpdatePortalSetting(this._portalId, SettingName, fileId != Null.NullInteger ? string.Format("FileID={0}", fileId) : string.Empty, /*clearCache*/ true); + DataCache.ClearCache(GetCacheKey(this._portalId)); } private static void UpdateCachedHeaderLink(int portalId, string headerLink) @@ -115,5 +99,22 @@ private static string GetCacheKey(int portalId) { return "FAVICON" + portalId; } + + private string GetRelativeUrl() + { + var fileInfo = this.GetFileInfo(); + return fileInfo == null ? string.Empty : FileManager.Instance.GetUrl(fileInfo); + } + + private IFileInfo GetFileInfo() + { + var path = this.GetSettingPath(); + if (!string.IsNullOrEmpty(path)) + { + return FileManager.Instance.GetFile(this._portalId, path); + } + + return null; + } } } diff --git a/DNN Platform/Library/UI/Modules/BaseModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/BaseModuleControlFactory.cs index 72f0a756945..c7b6ff7524b 100644 --- a/DNN Platform/Library/UI/Modules/BaseModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/BaseModuleControlFactory.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Localization; -using System.IO; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { + using System.IO; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Localization; + public abstract class BaseModuleControlFactory : IModuleControlFactory { public abstract Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc); @@ -20,7 +21,7 @@ public virtual ModuleControlBase CreateModuleControl(ModuleInfo moduleConfigurat var moduleControl = new ModuleControlBase(); moduleControl.ModuleContext.Configuration = moduleConfiguration; - moduleControl.LocalResourceFile = moduleConfiguration.ModuleControl.ControlSrc.Replace(Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc), "") + + moduleControl.LocalResourceFile = moduleConfiguration.ModuleControl.ControlSrc.Replace(Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc), string.Empty) + Localization.LocalResourceDirectory + "/" + Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc); diff --git a/DNN Platform/Library/UI/Modules/CachedModuleControl.cs b/DNN Platform/Library/UI/Modules/CachedModuleControl.cs index a4cd1cca10c..5c92862b2dd 100644 --- a/DNN Platform/Library/UI/Modules/CachedModuleControl.cs +++ b/DNN Platform/Library/UI/Modules/CachedModuleControl.cs @@ -1,51 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Modules - /// Class : CachedModuleControl + /// Class : CachedModuleControl /// ----------------------------------------------------------------------------- /// /// CachedModuleControl represents a cached "ModuleControl". It inherits from - /// Literal and implements the IModuleControl interface + /// Literal and implements the IModuleControl interface. /// /// ----------------------------------------------------------------------------- public class CachedModuleControl : Literal, IModuleControl { private string _localResourceFile; - private ModuleInstanceContext _moduleContext; - + private ModuleInstanceContext _moduleContext; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new CachedModuleControl + /// + /// Initializes a new instance of the class. + /// Constructs a new CachedModuleControl. /// - /// The cached Content for this control + /// The cached Content for this control. /// ----------------------------------------------------------------------------- public CachedModuleControl(string cachedContent) { - Text = cachedContent; - } - - #region IModuleControl Members - + this.Text = cachedContent; + } + /// ----------------------------------------------------------------------------- /// - /// Gets the underlying base control for this ModuleControl + /// Gets the underlying base control for this ModuleControl. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public Control Control { @@ -57,37 +51,37 @@ public Control Control /// ----------------------------------------------------------------------------- /// - /// Gets the Path for this control (used primarily for UserControls) + /// Gets the Path for this control (used primarily for UserControls). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlPath { get { - return TemplateSourceDirectory + "/"; + return this.TemplateSourceDirectory + "/"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Name for this control + /// Gets the Name for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlName { get { - return GetType().Name.Replace("_", "."); + return this.GetType().Name.Replace("_", "."); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the local resource file for this control + /// Gets or sets and sets the local resource file for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string LocalResourceFile { @@ -95,40 +89,41 @@ public string LocalResourceFile { string fileRoot; - if (string.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = ControlPath + "/" + Localization.LocalResourceDirectory + "/" + ID; + fileRoot = this.ControlPath + "/" + Localization.LocalResourceDirectory + "/" + this.ID; } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Module Context for this control + /// Gets the Module Context for this control. /// - /// A ModuleInstanceContext + /// A ModuleInstanceContext. /// ----------------------------------------------------------------------------- public ModuleInstanceContext ModuleContext { get { - if (_moduleContext == null) + if (this._moduleContext == null) { - _moduleContext = new ModuleInstanceContext(this); + this._moduleContext = new ModuleInstanceContext(this); } - return _moduleContext; + + return this._moduleContext; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs index 752581dbe87..ad72fade265 100644 --- a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs +++ b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web; -using System.Web.UI; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Framework; -using DotNetNuke.Services.Cache; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules.Html5 { + using System; + using System.IO; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Framework; + using DotNetNuke.Services.Cache; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + public class Html5HostControl : ModuleControlBase, IActionable { private readonly string _html5File; @@ -23,7 +24,7 @@ public class Html5HostControl : ModuleControlBase, IActionable public Html5HostControl(string html5File) { - _html5File = html5File; + this._html5File = html5File; } public ModuleActionCollection ModuleActions { get; private set; } @@ -32,52 +33,41 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - if (!(string.IsNullOrEmpty(_html5File))) + if (!string.IsNullOrEmpty(this._html5File)) { - //Check if css file exists - var cssFile = Path.ChangeExtension(_html5File, ".css"); - if (FileExists(cssFile)) + // Check if css file exists + var cssFile = Path.ChangeExtension(this._html5File, ".css"); + if (this.FileExists(cssFile)) { - ClientResourceManager.RegisterStyleSheet(Page, cssFile, FileOrder.Css.DefaultPriority); + ClientResourceManager.RegisterStyleSheet(this.Page, cssFile, FileOrder.Css.DefaultPriority); } - //Check if js file exists - var jsFile = Path.ChangeExtension(_html5File, ".js"); - if (FileExists(jsFile)) + // Check if js file exists + var jsFile = Path.ChangeExtension(this._html5File, ".js"); + if (this.FileExists(jsFile)) { - ClientResourceManager.RegisterScript(Page, jsFile, FileOrder.Js.DefaultPriority); + ClientResourceManager.RegisterScript(this.Page, jsFile, FileOrder.Js.DefaultPriority); } - _fileContent = GetFileContent(_html5File); + this._fileContent = this.GetFileContent(this._html5File); - ModuleActions = new ModuleActionCollection(); - var tokenReplace = new Html5ModuleTokenReplace(Page, _html5File, ModuleContext, ModuleActions); - _fileContent = tokenReplace.ReplaceEnvironmentTokens(_fileContent); + this.ModuleActions = new ModuleActionCollection(); + var tokenReplace = new Html5ModuleTokenReplace(this.Page, this._html5File, this.ModuleContext, this.ModuleActions); + this._fileContent = tokenReplace.ReplaceEnvironmentTokens(this._fileContent); } - //Register for Services Framework + // Register for Services Framework ServicesFramework.Instance.RequestAjaxScriptSupport(); } - private string GetFileContent(string filepath) + protected override void OnPreRender(EventArgs e) { - var cacheKey = string.Format(DataCache.SpaModulesContentHtmlFileCacheKey, filepath); - var absoluteFilePath = Page.Server.MapPath(filepath); - var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.SpaModulesHtmlFileTimeOut, - DataCache.SpaModulesHtmlFileCachePriority) - { - CacheDependency = new DNNCacheDependency(absoluteFilePath) - }; - return CBO.GetCachedObject(cacheItemArgs, c => GetFileContentInternal(absoluteFilePath)); - } + base.OnPreRender(e); - private bool FileExists(string filepath) - { - var cacheKey = string.Format(DataCache.SpaModulesFileExistsCacheKey, filepath); - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, - DataCache.SpaModulesHtmlFileTimeOut, - DataCache.SpaModulesHtmlFileCachePriority), - c => File.Exists(Page.Server.MapPath(filepath))); + if (!string.IsNullOrEmpty(this._html5File)) + { + this.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(this._fileContent))); + } } private static string GetFileContentInternal(string filepath) @@ -88,14 +78,27 @@ private static string GetFileContentInternal(string filepath) } } - protected override void OnPreRender(EventArgs e) + private string GetFileContent(string filepath) { - base.OnPreRender(e); - - if (!(string.IsNullOrEmpty(_html5File))) + var cacheKey = string.Format(DataCache.SpaModulesContentHtmlFileCacheKey, filepath); + var absoluteFilePath = this.Page.Server.MapPath(filepath); + var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.SpaModulesHtmlFileTimeOut, + DataCache.SpaModulesHtmlFileCachePriority) { - Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(_fileContent))); - } + CacheDependency = new DNNCacheDependency(absoluteFilePath), + }; + return CBO.GetCachedObject(cacheItemArgs, c => GetFileContentInternal(absoluteFilePath)); + } + + private bool FileExists(string filepath) + { + var cacheKey = string.Format(DataCache.SpaModulesFileExistsCacheKey, filepath); + return CBO.GetCachedObject( + new CacheItemArgs( + cacheKey, + DataCache.SpaModulesHtmlFileTimeOut, + DataCache.SpaModulesHtmlFileCachePriority), + c => File.Exists(this.Page.Server.MapPath(filepath))); } } } diff --git a/DNN Platform/Library/UI/Modules/Html5/Html5ModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/Html5/Html5ModuleControlFactory.cs index d0bd33320d9..9c56a61fcfd 100644 --- a/DNN Platform/Library/UI/Modules/Html5/Html5ModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/Html5/Html5ModuleControlFactory.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules.Html5 { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + public class Html5ModuleControlFactory : BaseModuleControlFactory { public override Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc) @@ -17,12 +18,12 @@ public override Control CreateControl(TemplateControl containerControl, string c public override Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { - return CreateControl(containerControl, String.Empty, moduleConfiguration.ModuleControl.ControlSrc); + return this.CreateControl(containerControl, string.Empty, moduleConfiguration.ModuleControl.ControlSrc); } public override Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) { - return CreateControl(containerControl, String.Empty, controlSrc); + return this.CreateControl(containerControl, string.Empty, controlSrc); } } } diff --git a/DNN Platform/Library/UI/Modules/Html5/Html5ModuleTokenReplace.cs b/DNN Platform/Library/UI/Modules/Html5/Html5ModuleTokenReplace.cs index b387f5e3683..63f861e7032 100644 --- a/DNN Platform/Library/UI/Modules/Html5/Html5ModuleTokenReplace.cs +++ b/DNN Platform/Library/UI/Modules/Html5/Html5ModuleTokenReplace.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Web.UI; -using DotNetNuke.Framework; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Instrumentation; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules.Html5 { + using System; + using System.Collections; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Tokens; + public class Html5ModuleTokenReplace : HtmlTokenReplace { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Html5ModuleTokenReplace)); @@ -22,26 +23,26 @@ public class Html5ModuleTokenReplace : HtmlTokenReplace public Html5ModuleTokenReplace(Page page, string html5File, ModuleInstanceContext moduleContext, ModuleActionCollection moduleActions) : base(page) { - AccessingUser = moduleContext.PortalSettings.UserInfo; - DebugMessages = moduleContext.PortalSettings.UserMode != Entities.Portals.PortalSettings.Mode.View; - ModuleId = moduleContext.ModuleId; - PortalSettings = moduleContext.PortalSettings; + this.AccessingUser = moduleContext.PortalSettings.UserInfo; + this.DebugMessages = moduleContext.PortalSettings.UserMode != Entities.Portals.PortalSettings.Mode.View; + this.ModuleId = moduleContext.ModuleId; + this.PortalSettings = moduleContext.PortalSettings; - PropertySource["moduleaction"] = new ModuleActionsPropertyAccess(moduleContext, moduleActions); - PropertySource["resx"] = new ModuleLocalizationPropertyAccess(moduleContext, html5File); - PropertySource["modulecontext"] = new ModuleContextPropertyAccess(moduleContext); - PropertySource["request"] = new RequestPropertyAccess(page.Request); + this.PropertySource["moduleaction"] = new ModuleActionsPropertyAccess(moduleContext, moduleActions); + this.PropertySource["resx"] = new ModuleLocalizationPropertyAccess(moduleContext, html5File); + this.PropertySource["modulecontext"] = new ModuleContextPropertyAccess(moduleContext); + this.PropertySource["request"] = new RequestPropertyAccess(page.Request); // DNN-7750 var bizClass = moduleContext.Configuration.DesktopModule.BusinessControllerClass; - - var businessController = GetBusinessController(bizClass); + + var businessController = this.GetBusinessController(bizClass); if (businessController != null) { var tokens = businessController.GetTokens(page, moduleContext); foreach (var token in tokens) { - PropertySource.Add(token.Key, token.Value); + this.PropertySource.Add(token.Key, token.Value); } } } @@ -69,7 +70,7 @@ private ICustomTokenProvider GetBusinessController(string bizClass) { Logger.Error(exc); } - + return null; } } diff --git a/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs index bbfe8bae41f..1652cb7e342 100644 --- a/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Tokens; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules.Html5 { + using System; + + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Tokens; + using Newtonsoft.Json; + public class ModuleActionDto { [JsonProperty("controlkey")] @@ -43,19 +44,19 @@ public class ModuleActionsPropertyAccess : JsonPropertyAccess public ModuleActionsPropertyAccess(ModuleInstanceContext moduleContext, ModuleActionCollection moduleActions) { - _moduleContext = moduleContext; - _moduleActions = moduleActions; + this._moduleContext = moduleContext; + this._moduleActions = moduleActions; } protected override string ProcessToken(ModuleActionDto model, UserInfo accessingUser, Scope accessLevel) { - var title = (!String.IsNullOrEmpty(model.TitleKey) && !String.IsNullOrEmpty(model.LocalResourceFile)) + var title = (!string.IsNullOrEmpty(model.TitleKey) && !string.IsNullOrEmpty(model.LocalResourceFile)) ? Localization.GetString(model.TitleKey, model.LocalResourceFile) : model.Title; SecurityAccessLevel securityAccessLevel = SecurityAccessLevel.View; - if (!String.IsNullOrEmpty(model.SecurityAccessLevel)) + if (!string.IsNullOrEmpty(model.SecurityAccessLevel)) { switch (model.SecurityAccessLevel) { @@ -74,27 +75,27 @@ protected override string ProcessToken(ModuleActionDto model, UserInfo accessing } } - var moduleAction = new ModuleAction(_moduleContext.GetNextActionID()) + var moduleAction = new ModuleAction(this._moduleContext.GetNextActionID()) { Title = title, Icon = model.Icon, - Secure = securityAccessLevel + Secure = securityAccessLevel, }; if (string.IsNullOrEmpty(model.Script)) { - moduleAction.Url = _moduleContext.EditUrl(model.ControlKey); + moduleAction.Url = this._moduleContext.EditUrl(model.ControlKey); } else { - moduleAction.Url = model.Script.StartsWith("javascript:", StringComparison.InvariantCultureIgnoreCase) ? - model.Script : + moduleAction.Url = model.Script.StartsWith("javascript:", StringComparison.InvariantCultureIgnoreCase) ? + model.Script : string.Format("javascript:{0}", model.Script); } - _moduleActions.Add(moduleAction); + this._moduleActions.Add(moduleAction); - return String.Empty; + return string.Empty; } } } diff --git a/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs index 9f662c41ed0..a69c0bf5e18 100644 --- a/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Globalization; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Tokens; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ConvertPropertyToExpressionBody - namespace DotNetNuke.UI.Modules.Html5 { + using System.Globalization; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Tokens; + public class ModuleContextPropertyAccess : IPropertyAccess { private readonly ModuleInstanceContext _moduleContext; public ModuleContextPropertyAccess(ModuleInstanceContext moduleContext) { - _moduleContext = moduleContext; + this._moduleContext = moduleContext; } public virtual CacheLevel Cacheability @@ -29,22 +29,23 @@ public string GetProperty(string propertyName, string format, CultureInfo format switch (propertyName.ToLowerInvariant()) { case "moduleid": - return _moduleContext.ModuleId.ToString(); + return this._moduleContext.ModuleId.ToString(); case "tabmoduleid": - return _moduleContext.TabModuleId.ToString(); + return this._moduleContext.TabModuleId.ToString(); case "tabid": - return _moduleContext.TabId.ToString(); + return this._moduleContext.TabId.ToString(); case "portalid": - return _moduleContext.Configuration.OwnerPortalID.ToString(); + return this._moduleContext.Configuration.OwnerPortalID.ToString(); case "issuperuser": - return _moduleContext.PortalSettings.UserInfo.IsSuperUser.ToString(); + return this._moduleContext.PortalSettings.UserInfo.IsSuperUser.ToString(); case "editmode": - return _moduleContext.EditMode.ToString(); + return this._moduleContext.EditMode.ToString(); default: - if (_moduleContext.Settings.ContainsKey(propertyName)) + if (this._moduleContext.Settings.ContainsKey(propertyName)) { - return (string)_moduleContext.Settings[propertyName]; + return (string)this._moduleContext.Settings[propertyName]; } + break; } diff --git a/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs index 4bffee8b233..9b8a69e0be2 100644 --- a/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Tokens; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules.Html5 { + using System; + using System.IO; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Tokens; + using Newtonsoft.Json; + public class ModuleLocalizationDto { [JsonProperty("key")] @@ -27,8 +28,8 @@ public class ModuleLocalizationPropertyAccess : JsonPropertyAccess - /// IModuleControl provides a common Interface for Module Controls + /// IModuleControl provides a common Interface for Module Controls. /// /// ----------------------------------------------------------------------------- public interface IModuleControl { Control Control { get; } + string ControlPath { get; } + string ControlName { get; } + string LocalResourceFile { get; set; } + ModuleInstanceContext ModuleContext { get; } } } diff --git a/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs index 69c437b20b0..93a7bb0ab82 100644 --- a/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs @@ -1,18 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; - -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + public interface IModuleControlFactory { Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc); + Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration); + ModuleControlBase CreateModuleControl(ModuleInfo moduleConfiguration); + Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc); } } diff --git a/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs b/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs index 00e5431617c..85826533093 100644 --- a/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs +++ b/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs @@ -1,19 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules; -using System; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + public interface IModuleControlPipeline { Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc); + Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration); + Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc); + Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfiguration); + Control CreateModuleControl(ModuleInfo moduleConfiguration); } } diff --git a/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs b/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs index fb270b2084f..652c931a483 100644 --- a/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs +++ b/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + public interface IModuleInjectionFilter { bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings); diff --git a/DNN Platform/Library/UI/Modules/IProfileModule.cs b/DNN Platform/Library/UI/Modules/IProfileModule.cs index d973be60fdd..8c2648c8446 100644 --- a/DNN Platform/Library/UI/Modules/IProfileModule.cs +++ b/DNN Platform/Library/UI/Modules/IProfileModule.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { public interface IProfileModule diff --git a/DNN Platform/Library/UI/Modules/ISettingsControl.cs b/DNN Platform/Library/UI/Modules/ISettingsControl.cs index 706fe4d4c6f..e68866400d5 100644 --- a/DNN Platform/Library/UI/Modules/ISettingsControl.cs +++ b/DNN Platform/Library/UI/Modules/ISettingsControl.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Modules - /// Class : ISettingsControl + /// Class : ISettingsControl /// ----------------------------------------------------------------------------- /// - /// ISettingsControl provides a common Interface for Module Settings Controls + /// ISettingsControl provides a common Interface for Module Settings Controls. /// /// ----------------------------------------------------------------------------- public interface ISettingsControl : IModuleControl diff --git a/DNN Platform/Library/UI/Modules/ModuleCachingType.cs b/DNN Platform/Library/UI/Modules/ModuleCachingType.cs index 932a6ca2af5..96a558035ed 100644 --- a/DNN Platform/Library/UI/Modules/ModuleCachingType.cs +++ b/DNN Platform/Library/UI/Modules/ModuleCachingType.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Modules - /// Class : ModuleCachingType + /// Class : ModuleCachingType /// ----------------------------------------------------------------------------- /// - /// ModuleCachingType is an enum that provides the caching types for Module Content + /// ModuleCachingType is an enum that provides the caching types for Module Content. /// /// ----------------------------------------------------------------------------- public enum ModuleCachingType { Memory, Disk, - Database + Database, } } diff --git a/DNN Platform/Library/UI/Modules/ModuleControlBase.cs b/DNN Platform/Library/UI/Modules/ModuleControlBase.cs index a9e7e1f8f8c..dbb705f5cc5 100644 --- a/DNN Platform/Library/UI/Modules/ModuleControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ModuleControlBase.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System.Web.UI; + + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Modules - /// Class : ModuleControlBase + /// Class : ModuleControlBase /// ----------------------------------------------------------------------------- /// /// ModuleControlBase is a base class for Module Controls that inherits from the @@ -26,15 +21,13 @@ namespace DotNetNuke.UI.Modules public class ModuleControlBase : Control, IModuleControl { private string _localResourceFile; - private ModuleInstanceContext _moduleContext; - - #region IModuleControl Members - + private ModuleInstanceContext _moduleContext; + /// ----------------------------------------------------------------------------- /// - /// Gets the underlying base control for this ModuleControl + /// Gets the underlying base control for this ModuleControl. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public Control Control { @@ -46,77 +39,78 @@ public Control Control /// ----------------------------------------------------------------------------- /// - /// Gets the Path for this control (used primarily for UserControls) + /// Gets the Path for this control (used primarily for UserControls). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlPath { get { - return TemplateSourceDirectory + "/"; + return this.TemplateSourceDirectory + "/"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Name for this control + /// Gets the Name for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlName { get { - return GetType().Name.Replace("_", "."); + return this.GetType().Name.Replace("_", "."); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the local resource file for this control + /// Gets or sets and sets the local resource file for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string LocalResourceFile { get { string fileRoot; - if (string.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = ControlPath + "/" + Localization.LocalResourceDirectory + "/" + ID; + fileRoot = this.ControlPath + "/" + Localization.LocalResourceDirectory + "/" + this.ID; } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Module Context for this control + /// Gets the Module Context for this control. /// - /// A ModuleInstanceContext + /// A ModuleInstanceContext. /// ----------------------------------------------------------------------------- public ModuleInstanceContext ModuleContext { get { - if (_moduleContext == null) + if (this._moduleContext == null) { - _moduleContext = new ModuleInstanceContext(this); + this._moduleContext = new ModuleInstanceContext(this); } - return _moduleContext; + + return this._moduleContext; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs index 6b72e36aa41..f78fee1d849 100644 --- a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs @@ -1,69 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web.UI; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules.Html5; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { + using System; + using System.IO; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules.Html5; + [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] public class ModuleControlFactory { private static readonly ILog TracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - private static IModuleControlFactory GetModuleControlFactory(string controlSrc) - { - string extension = Path.GetExtension(controlSrc.ToLowerInvariant()); - - IModuleControlFactory controlFactory = null; - Type factoryType; - switch (extension) - { - case ".ascx": - controlFactory = new WebFormsModuleControlFactory(); - break; - case ".html": - case ".htm": - controlFactory = new Html5ModuleControlFactory(); - break; - case ".cshtml": - case ".vbhtml": - factoryType = Reflection.CreateType("DotNetNuke.Web.Razor.RazorModuleControlFactory"); - if (factoryType != null) - { - controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; - } - break; - case ".mvc": - factoryType = Reflection.CreateType("DotNetNuke.Web.Mvc.MvcModuleControlFactory"); - if (factoryType != null) - { - controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; - } - break; - default: - controlFactory = new ReflectedModuleControlFactory(); - break; - } - - return controlFactory; - } - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] public static Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc) { - if (TracelLogger.IsDebugEnabled) - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); @@ -86,16 +49,22 @@ public static Control LoadModuleControl(TemplateControl containerControl, Module } } - if (TracelLogger.IsDebugEnabled) - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] public static Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { - if (TracelLogger.IsDebugEnabled) - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; IModuleControlFactory controlFactory = GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); @@ -118,17 +87,63 @@ public static Control LoadModuleControl(TemplateControl containerControl, Module } } - if (TracelLogger.IsDebugEnabled) - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - public static Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) + private static IModuleControlFactory GetModuleControlFactory(string controlSrc) { - if (TracelLogger.IsDebugEnabled) - TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + string extension = Path.GetExtension(controlSrc.ToLowerInvariant()); + + IModuleControlFactory controlFactory = null; + Type factoryType; + switch (extension) + { + case ".ascx": + controlFactory = new WebFormsModuleControlFactory(); + break; + case ".html": + case ".htm": + controlFactory = new Html5ModuleControlFactory(); + break; + case ".cshtml": + case ".vbhtml": + factoryType = Reflection.CreateType("DotNetNuke.Web.Razor.RazorModuleControlFactory"); + if (factoryType != null) + { + controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; + } + + break; + case ".mvc": + factoryType = Reflection.CreateType("DotNetNuke.Web.Mvc.MvcModuleControlFactory"); + if (factoryType != null) + { + controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; + } + + break; + default: + controlFactory = new ReflectedModuleControlFactory(); + break; + } + + return controlFactory; + } + [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] + public static Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) + { + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); @@ -155,8 +170,11 @@ public static Control LoadSettingsControl(TemplateControl containerControl, Modu } } - if (TracelLogger.IsDebugEnabled) - TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } @@ -178,19 +196,21 @@ public static Control CreateModuleControl(ModuleInfo moduleConfiguration) switch (extension) { case ".mvc": - var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", "").Split('/'); + var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); - moduleControl.LocalResourceFile = String.Format("~/DesktopModules/MVC/{0}/{1}/{2}.resx", - moduleConfiguration.DesktopModule.FolderName, - Localization.LocalResourceDirectory, - segments[0]); + moduleControl.LocalResourceFile = string.Format( + "~/DesktopModules/MVC/{0}/{1}/{2}.resx", + moduleConfiguration.DesktopModule.FolderName, + Localization.LocalResourceDirectory, + segments[0]); break; default: - moduleControl.LocalResourceFile = moduleConfiguration.ModuleControl.ControlSrc.Replace(Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc), "") + + moduleControl.LocalResourceFile = moduleConfiguration.ModuleControl.ControlSrc.Replace(Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc), string.Empty) + Localization.LocalResourceDirectory + "/" + Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc); break; } + return moduleControl; } } diff --git a/DNN Platform/Library/UI/Modules/ModuleHost.cs b/DNN Platform/Library/UI/Modules/ModuleHost.cs index 1e3efabb052..8612a41aaba 100644 --- a/DNN Platform/Library/UI/Modules/ModuleHost.cs +++ b/DNN Platform/Library/UI/Modules/ModuleHost.cs @@ -1,109 +1,98 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.ModuleCache; -using DotNetNuke.UI.Utilities; -using DotNetNuke.UI.WebControls; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Microsoft.Extensions.DependencyInjection; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.ModuleCache; + using DotNetNuke.UI.Utilities; + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Modules - /// Class : ModuleHost + /// Class : ModuleHost /// ----------------------------------------------------------------------------- /// /// ModuleHost hosts a Module Control (or its cached Content). /// public sealed class ModuleHost : Panel { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ModuleHost)); - - private static readonly Regex CdfMatchRegex = new Regex(@"<\!--CDF\((?JAVASCRIPT|CSS|JS-LIBRARY)\|(?.+?)(\|(?.+?)\|(?\d+?))?\)-->", - RegexOptions.IgnoreCase | RegexOptions.Compiled); private const string DefaultCssProvider = "DnnPageHeaderProvider"; private const string DefaultJsProvider = "DnnBodyProvider"; - #region Private Members + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleHost)); + private static readonly Regex CdfMatchRegex = new Regex( + @"<\!--CDF\((?JAVASCRIPT|CSS|JS-LIBRARY)\|(?.+?)(\|(?.+?)\|(?\d+?))?\)-->", + RegexOptions.IgnoreCase | RegexOptions.Compiled); private readonly ModuleInfo _moduleConfiguration; private Control _control; private bool _isCached; private readonly IModuleControlPipeline _moduleControlPipeline = Globals.DependencyProvider.GetRequiredService(); - #endregion - - #region Constructors - /// ----------------------------------------------------------------------------- /// - /// Creates a Module Host control using the ModuleConfiguration for the Module + /// Initializes a new instance of the class. + /// Creates a Module Host control using the ModuleConfiguration for the Module. /// /// /// public ModuleHost(ModuleInfo moduleConfiguration, Skins.Skin skin, Containers.Container container) { - ID = "ModuleContent"; - Container = container; - _moduleConfiguration = moduleConfiguration; - Skin = skin; + this.ID = "ModuleContent"; + this.Container = container; + this._moduleConfiguration = moduleConfiguration; + this.Skin = skin; } - #endregion - - #region Public Properties - public Containers.Container Container { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the attached ModuleControl + /// Gets the attached ModuleControl. /// - /// An IModuleControl + /// An IModuleControl. public IModuleControl ModuleControl { get { - //Make sure the Control tree has been created - EnsureChildControls(); - return _control as IModuleControl; + // Make sure the Control tree has been created + this.EnsureChildControls(); + return this._control as IModuleControl; } } /// ----------------------------------------------------------------------------- /// - /// Gets the current POrtal Settings + /// Gets the current POrtal Settings. /// public PortalSettings PortalSettings { @@ -115,9 +104,83 @@ public PortalSettings PortalSettings public Skins.Skin Skin { get; private set; } - #endregion + /// ----------------------------------------------------------------------------- + /// + /// Gets a flag that indicates whether the Module is in View Mode. + /// + /// A Boolean. + internal static bool IsViewMode(ModuleInfo moduleInfo, PortalSettings settings) + { + bool viewMode; + + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.ViewPermissions, Null.NullString, + moduleInfo)) + { + viewMode = false; + } + else + { + viewMode = !ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, Null.NullString, + moduleInfo); + } + + return viewMode || settings.UserMode == PortalSettings.Mode.View; + } + + /// ----------------------------------------------------------------------------- + /// + /// CreateChildControls builds the control tree. + /// + protected override void CreateChildControls() + { + this.Controls.Clear(); + + // Load Module Control (or cached control) + this.LoadModuleControl(); + + // Optionally Inject AJAX Update Panel + if (this.ModuleControl != null) + { + // if module is dynamically loaded and AJAX is installed and the control supports partial rendering (defined in ModuleControls table ) + if (!this._isCached && this._moduleConfiguration.ModuleControl.SupportsPartialRendering && AJAX.IsInstalled()) + { + this.LoadUpdatePanel(); + } + else + { + // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage + InjectMessageControl(this); + + this.InjectVersionToTheModuleIfSupported(); + + // inject the module into the panel + this.InjectModuleContent(this._control); + } + } + } - #region Private Methods + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (Host.EnableCustomModuleCssClass) + { + string moduleName = this.ModuleControl.ModuleContext.Configuration.DesktopModule.ModuleName; + if (moduleName != null) + { + moduleName = Globals.CleanName(moduleName); + } + + this.Attributes.Add("class", string.Format("DNNModuleContent Mod{0}C", moduleName)); + } + } + + private static void InjectMessageControl(Control container) + { + // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage + var messagePlaceholder = new PlaceHolder { ID = "MessagePlaceHolder", Visible = false }; + container.Controls.Add(messagePlaceholder); + } private bool IsVersionRequest() { @@ -127,77 +190,80 @@ private bool IsVersionRequest() private void InjectVersionToTheModuleIfSupported() { - if (!(_control is IVersionableControl)) return; + if (!(this._control is IVersionableControl)) + { + return; + } - var versionableControl = _control as IVersionableControl; - if (_moduleConfiguration.ModuleVersion != Null.NullInteger) + var versionableControl = this._control as IVersionableControl; + if (this._moduleConfiguration.ModuleVersion != Null.NullInteger) { - versionableControl.SetModuleVersion(_moduleConfiguration.ModuleVersion); + versionableControl.SetModuleVersion(this._moduleConfiguration.ModuleVersion); } } private void InjectModuleContent(Control content) { - if (_moduleConfiguration.IsWebSlice && !Globals.IsAdminControl()) + if (this._moduleConfiguration.IsWebSlice && !Globals.IsAdminControl()) { - //Assign the class - hslice to the Drag-N-Drop Panel - CssClass = "hslice"; + // Assign the class - hslice to the Drag-N-Drop Panel + this.CssClass = "hslice"; var titleLabel = new Label - { - CssClass = "entry-title Hidden", - Text = !string.IsNullOrEmpty(_moduleConfiguration.WebSliceTitle) ? _moduleConfiguration.WebSliceTitle : _moduleConfiguration.ModuleTitle - }; - Controls.Add(titleLabel); + { + CssClass = "entry-title Hidden", + Text = !string.IsNullOrEmpty(this._moduleConfiguration.WebSliceTitle) ? this._moduleConfiguration.WebSliceTitle : this._moduleConfiguration.ModuleTitle, + }; + this.Controls.Add(titleLabel); - var websliceContainer = new Panel {CssClass = "entry-content"}; + var websliceContainer = new Panel { CssClass = "entry-content" }; websliceContainer.Controls.Add(content); - var expiry = new HtmlGenericControl {TagName = "abbr"}; + var expiry = new HtmlGenericControl { TagName = "abbr" }; expiry.Attributes["class"] = "endtime"; - if (!Null.IsNull(_moduleConfiguration.WebSliceExpiryDate)) + if (!Null.IsNull(this._moduleConfiguration.WebSliceExpiryDate)) { - expiry.Attributes["title"] = _moduleConfiguration.WebSliceExpiryDate.ToString("o"); + expiry.Attributes["title"] = this._moduleConfiguration.WebSliceExpiryDate.ToString("o"); websliceContainer.Controls.Add(expiry); } - else if (_moduleConfiguration.EndDate < DateTime.MaxValue) + else if (this._moduleConfiguration.EndDate < DateTime.MaxValue) { - expiry.Attributes["title"] = _moduleConfiguration.EndDate.ToString("o"); + expiry.Attributes["title"] = this._moduleConfiguration.EndDate.ToString("o"); websliceContainer.Controls.Add(expiry); } - var ttl = new HtmlGenericControl {TagName = "abbr"}; + var ttl = new HtmlGenericControl { TagName = "abbr" }; ttl.Attributes["class"] = "ttl"; - if (_moduleConfiguration.WebSliceTTL > 0) + if (this._moduleConfiguration.WebSliceTTL > 0) { - ttl.Attributes["title"] = _moduleConfiguration.WebSliceTTL.ToString(); + ttl.Attributes["title"] = this._moduleConfiguration.WebSliceTTL.ToString(); websliceContainer.Controls.Add(ttl); } - else if (_moduleConfiguration.CacheTime > 0) + else if (this._moduleConfiguration.CacheTime > 0) { - ttl.Attributes["title"] = (_moduleConfiguration.CacheTime/60).ToString(); + ttl.Attributes["title"] = (this._moduleConfiguration.CacheTime / 60).ToString(); websliceContainer.Controls.Add(ttl); } - Controls.Add(websliceContainer); + this.Controls.Add(websliceContainer); } else { - Controls.Add(content); + this.Controls.Add(content); } } /// ---------------------------------------------------------------------------- /// - /// Gets a flag that indicates whether the Module Content should be displayed + /// Gets a flag that indicates whether the Module Content should be displayed. /// - /// A Boolean + /// A Boolean. private bool DisplayContent() { - //module content visibility options - var content = PortalSettings.UserMode != PortalSettings.Mode.Layout; - if (Page.Request.QueryString["content"] != null) + // module content visibility options + var content = this.PortalSettings.UserMode != PortalSettings.Mode.Layout; + if (this.Page.Request.QueryString["content"] != null) { - switch (Page.Request.QueryString["Content"].ToLowerInvariant()) + switch (this.Page.Request.QueryString["Content"].ToLowerInvariant()) { case "1": case "true": @@ -209,78 +275,51 @@ private bool DisplayContent() break; } } + if (Globals.IsAdminControl()) { content = true; } - return content; - } - - private static void InjectMessageControl(Control container) - { - //inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage - var messagePlaceholder = new PlaceHolder {ID = "MessagePlaceHolder", Visible = false}; - container.Controls.Add(messagePlaceholder); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets a flag that indicates whether the Module is in View Mode - /// - /// A Boolean - internal static bool IsViewMode(ModuleInfo moduleInfo, PortalSettings settings) - { - bool viewMode; - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.ViewPermissions, Null.NullString, - moduleInfo)) - { - viewMode = false; - } - else - { - viewMode = !(ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, Null.NullString, - moduleInfo)); - } - - return viewMode || settings.UserMode == PortalSettings.Mode.View; + return content; } /// ----------------------------------------------------------------------------- /// - /// LoadModuleControl loads the ModuleControl (PortalModuelBase) + /// LoadModuleControl loads the ModuleControl (PortalModuelBase). /// private void LoadModuleControl() { try { - if (DisplayContent()) + if (this.DisplayContent()) { - //if the module supports caching and caching is enabled for the instance and the user does not have Edit rights or is currently in View mode - if (SupportsCaching() && IsViewMode(_moduleConfiguration, PortalSettings) && !IsVersionRequest()) + // if the module supports caching and caching is enabled for the instance and the user does not have Edit rights or is currently in View mode + if (this.SupportsCaching() && IsViewMode(this._moduleConfiguration, this.PortalSettings) && !this.IsVersionRequest()) { - //attempt to load the cached content - _isCached = TryLoadCached(); + // attempt to load the cached content + this._isCached = this.TryLoadCached(); } - if (!_isCached) + + if (!this._isCached) { - // load the control dynamically - _control = _moduleControlPipeline.LoadModuleControl(Page, _moduleConfiguration); + // load the control dynamically + this._control = this._moduleControlPipeline.LoadModuleControl(this.Page, this._moduleConfiguration); } } - else //content placeholder + else // content placeholder { - _control = _moduleControlPipeline.CreateModuleControl(_moduleConfiguration); + this._control = this._moduleControlPipeline.CreateModuleControl(this._moduleConfiguration); } - if (Skin != null) + + if (this.Skin != null) { - - //check for IMC - Skin.Communicator.LoadCommunicator(_control); + // check for IMC + this.Skin.Communicator.LoadCommunicator(this._control); } - - //add module settings - ModuleControl.ModuleContext.Configuration = _moduleConfiguration; + + // add module settings + this.ModuleControl.ModuleContext.Configuration = this._moduleConfiguration; } catch (ThreadAbortException exc) { @@ -291,14 +330,14 @@ private void LoadModuleControl() catch (Exception exc) { Logger.Error(exc); - - //add module settings - _control = _moduleControlPipeline.CreateModuleControl(_moduleConfiguration); - ModuleControl.ModuleContext.Configuration = _moduleConfiguration; + + // add module settings + this._control = this._moduleControlPipeline.CreateModuleControl(this._moduleConfiguration); + this.ModuleControl.ModuleContext.Configuration = this._moduleConfiguration; if (TabPermissionController.CanAdminPage()) { - //only display the error to page administrators - Exceptions.ProcessModuleLoadException(_control, exc); + // only display the error to page administrators + Exceptions.ProcessModuleLoadException(this._control, exc); } else { @@ -306,85 +345,85 @@ private void LoadModuleControl() new ExceptionLogController().AddLog(exc); } } - - //Enable ViewState - _control.ViewStateMode = ViewStateMode.Enabled; + + // Enable ViewState + this._control.ViewStateMode = ViewStateMode.Enabled; } /// - /// LoadUpdatePanel optionally loads an AJAX Update Panel + /// LoadUpdatePanel optionally loads an AJAX Update Panel. /// private void LoadUpdatePanel() { - //register AJAX + // register AJAX AJAX.RegisterScriptManager(); - //enable Partial Rendering - var scriptManager = AJAX.GetScriptManager(Page); + // enable Partial Rendering + var scriptManager = AJAX.GetScriptManager(this.Page); if (scriptManager != null) { scriptManager.EnablePartialRendering = true; } - - //create update panel + + // create update panel var updatePanel = new UpdatePanel - { - UpdateMode = UpdatePanelUpdateMode.Conditional, - ID = _control.ID + "_UP" - }; + { + UpdateMode = UpdatePanelUpdateMode.Conditional, + ID = this._control.ID + "_UP", + }; - //get update panel content template + // get update panel content template var templateContainer = updatePanel.ContentTemplateContainer; - //inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage + // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage InjectMessageControl(templateContainer); - //inject module into update panel content template - templateContainer.Controls.Add(_control); + // inject module into update panel content template + templateContainer.Controls.Add(this._control); - //inject the update panel into the panel - InjectModuleContent(updatePanel); + // inject the update panel into the panel + this.InjectModuleContent(updatePanel); - //create image for update progress control + // create image for update progress control var progressTemplate = "
    "; - //inject updateprogress into the panel + // inject updateprogress into the panel var updateProgress = new UpdateProgress - { - AssociatedUpdatePanelID = updatePanel.ID, - ID = updatePanel.ID + "_Prog", + { + AssociatedUpdatePanelID = updatePanel.ID, + ID = updatePanel.ID + "_Prog", - ProgressTemplate = new LiteralTemplate(progressTemplate) - }; - Controls.Add(updateProgress); + ProgressTemplate = new LiteralTemplate(progressTemplate), + }; + this.Controls.Add(updateProgress); } /// ----------------------------------------------------------------------------- /// - /// Gets a flag that indicates whether the Module Instance supports Caching + /// Gets a flag that indicates whether the Module Instance supports Caching. /// - /// A Boolean + /// A Boolean. private bool SupportsCaching() { - return _moduleConfiguration.CacheTime > 0; + return this._moduleConfiguration.CacheTime > 0; } /// ----------------------------------------------------------------------------- /// - /// Trys to load previously cached Module Content + /// Trys to load previously cached Module Content. /// - /// A Boolean that indicates whether the cahed content was loaded + /// A Boolean that indicates whether the cahed content was loaded. private bool TryLoadCached() { bool success = false; string cachedContent = string.Empty; try { - var cache = ModuleCachingProvider.Instance(_moduleConfiguration.GetEffectiveCacheMethod()); - var varyBy = new SortedDictionary {{"locale", Thread.CurrentThread.CurrentUICulture.ToString()}}; + var cache = ModuleCachingProvider.Instance(this._moduleConfiguration.GetEffectiveCacheMethod()); + var varyBy = new SortedDictionary { { "locale", Thread.CurrentThread.CurrentUICulture.ToString() } }; - string cacheKey = cache.GenerateCacheKey(_moduleConfiguration.TabModuleID, varyBy); - byte[] cachedBytes = ModuleCachingProvider.Instance(_moduleConfiguration.GetEffectiveCacheMethod()).GetModule(_moduleConfiguration.TabModuleID, cacheKey); + string cacheKey = cache.GenerateCacheKey(this._moduleConfiguration.TabModuleID, varyBy); + byte[] cachedBytes = ModuleCachingProvider.Instance(this._moduleConfiguration.GetEffectiveCacheMethod()).GetModule(this._moduleConfiguration.TabModuleID, cacheKey); if (cachedBytes != null && cachedBytes.Length > 0) { @@ -398,12 +437,14 @@ private bool TryLoadCached() Exceptions.LogException(ex); success = false; } + if (success) { this.RestoreCachedClientResourceRegistrations(cachedContent); - _control = _moduleControlPipeline.CreateCachedControl(cachedContent, _moduleConfiguration); - Controls.Add(_control); + this._control = this._moduleControlPipeline.CreateCachedControl(cachedContent, this._moduleConfiguration); + this.Controls.Add(this._control); } + return success; } @@ -452,7 +493,7 @@ private void RestoreCachedClientResourceRegistrations(string cachedContent) priority = (int)FileOrder.Js.DefaultPriority; } - ClientResourceManager.RegisterScript(Page, filePath, priority, forceProvider); + ClientResourceManager.RegisterScript(this.Page, filePath, priority, forceProvider); break; case "CSS": if (string.IsNullOrEmpty(forceProvider)) @@ -465,7 +506,7 @@ private void RestoreCachedClientResourceRegistrations(string cachedContent) priority = (int)FileOrder.Css.DefaultPriority; } - ClientResourceManager.RegisterStyleSheet(Page, filePath, priority, forceProvider); + ClientResourceManager.RegisterStyleSheet(this.Page, filePath, priority, forceProvider); break; case "JS-LIBRARY": var args = filePath.Split(new[] { ',', }, StringSplitOptions.None); @@ -487,102 +528,48 @@ private void RestoreCachedClientResourceRegistrations(string cachedContent) } } - #endregion - - #region Protected Methods - /// ----------------------------------------------------------------------------- /// - /// CreateChildControls builds the control tree - /// - protected override void CreateChildControls() - { - Controls.Clear(); - - //Load Module Control (or cached control) - LoadModuleControl(); - - //Optionally Inject AJAX Update Panel - if (ModuleControl != null) - { - //if module is dynamically loaded and AJAX is installed and the control supports partial rendering (defined in ModuleControls table ) - if (!_isCached && _moduleConfiguration.ModuleControl.SupportsPartialRendering && AJAX.IsInstalled()) - { - LoadUpdatePanel(); - } - else - { - //inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage - InjectMessageControl(this); - - InjectVersionToTheModuleIfSupported(); - - //inject the module into the panel - InjectModuleContent(_control); - } - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (Host.EnableCustomModuleCssClass) - { - string moduleName = ModuleControl.ModuleContext.Configuration.DesktopModule.ModuleName; - if (moduleName != null) - { - moduleName = Globals.CleanName(moduleName); - } - Attributes.Add("class", string.Format("DNNModuleContent Mod{0}C", moduleName)); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// RenderContents renders the contents of the control to the output stream + /// RenderContents renders the contents of the control to the output stream. /// protected override void RenderContents(HtmlTextWriter writer) { - if (_isCached) + if (this._isCached) { - //Render the cached control to the output stream + // Render the cached control to the output stream base.RenderContents(writer); } else { - if (SupportsCaching() && IsViewMode(_moduleConfiguration, PortalSettings) && !Globals.IsAdminControl() && !IsVersionRequest()) + if (this.SupportsCaching() && IsViewMode(this._moduleConfiguration, this.PortalSettings) && !Globals.IsAdminControl() && !this.IsVersionRequest()) { - //Render to cache + // Render to cache var tempWriter = new StringWriter(); - _control.RenderControl(new HtmlTextWriter(tempWriter)); + this._control.RenderControl(new HtmlTextWriter(tempWriter)); string cachedOutput = tempWriter.ToString(); if (!string.IsNullOrEmpty(cachedOutput) && (!HttpContext.Current.Request.Browser.Crawler)) { - //Save content to cache + // Save content to cache var moduleContent = Encoding.UTF8.GetBytes(cachedOutput); - var cache = ModuleCachingProvider.Instance(_moduleConfiguration.GetEffectiveCacheMethod()); + var cache = ModuleCachingProvider.Instance(this._moduleConfiguration.GetEffectiveCacheMethod()); - var varyBy = new SortedDictionary {{"locale", Thread.CurrentThread.CurrentUICulture.ToString()}}; + var varyBy = new SortedDictionary { { "locale", Thread.CurrentThread.CurrentUICulture.ToString() } }; - var cacheKey = cache.GenerateCacheKey(_moduleConfiguration.TabModuleID, varyBy); - cache.SetModule(_moduleConfiguration.TabModuleID, cacheKey, new TimeSpan(0, 0, _moduleConfiguration.CacheTime), moduleContent); + var cacheKey = cache.GenerateCacheKey(this._moduleConfiguration.TabModuleID, varyBy); + cache.SetModule(this._moduleConfiguration.TabModuleID, cacheKey, new TimeSpan(0, 0, this._moduleConfiguration.CacheTime), moduleContent); } - - //Render the cached content to Response + + // Render the cached content to Response writer.Write(cachedOutput); } else { - //Render the control to Response + // Render the control to Response base.RenderContents(writer); } } } - - #endregion - } } diff --git a/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs b/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs index db479de8e0a..899ca5628f6 100644 --- a/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs +++ b/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Collections.Internal; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework.Reflections; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Collections.Internal; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework.Reflections; + using DotNetNuke.Instrumentation; + internal class ModuleInjectionManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ModuleInjectionManager)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleInjectionManager)); private static NaiveLockingList _filters; public static void RegisterInjectionFilters() @@ -29,7 +29,17 @@ public static void RegisterInjectionFilters() } } - private static IEnumerable GetFilters() + public static bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings) + { + return _filters.All(filter => filter.CanInjectModule(module, portalSettings)); + } + + internal static bool IsValidModuleInjectionFilter(Type t) + { + return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IModuleInjectionFilter).IsAssignableFrom(t); + } + + private static IEnumerable GetFilters() { var typeLocator = new TypeLocator(); IEnumerable types = typeLocator.GetAllMatchingTypes(IsValidModuleInjectionFilter); @@ -54,15 +64,5 @@ private static IEnumerable GetFilters() } } } - - internal static bool IsValidModuleInjectionFilter(Type t) - { - return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IModuleInjectionFilter).IsAssignableFrom(t); - } - - public static bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings) - { - return _filters.All(filter => filter.CanInjectModule(module, portalSettings)); - } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs index a70fcf1d69f..be2a6f48656 100644 --- a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs +++ b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs @@ -1,41 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Linq; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.Utilities; - -using Globals = DotNetNuke.Common.Globals; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System; + using System.Collections; + using System.Linq; + using System.Web; + using System.Web.UI; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.Utilities; + + using Globals = DotNetNuke.Common.Globals; /// - /// Provides context data for a particular instance of a module + /// Provides context data for a particular instance of a module. /// public class ModuleInstanceContext { - #region Private Members - private readonly IModuleControl _moduleControl; private ModuleActionCollection _actions; private ModuleAction _moduleSpecificActions; @@ -46,65 +38,60 @@ public class ModuleInstanceContext private int _nextActionId = -1; private Hashtable _settings; - #endregion - - #region Constructors - public ModuleInstanceContext() { } public ModuleInstanceContext(IModuleControl moduleControl) { - _moduleControl = moduleControl; + this._moduleControl = moduleControl; } - #endregion - - #region Public Properties - /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Actions for this module context + /// Gets or sets and sets the Actions for this module context. /// /// ----------------------------------------------------------------------------- public ModuleActionCollection Actions { get { - if (_actions == null) + if (this._actions == null) { - LoadActions(HttpContext.Current.Request); + this.LoadActions(HttpContext.Current.Request); } - return _actions; + + return this._actions; } + set { - _actions = value; + this._actions = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Module Configuration (ModuleInfo) for this context + /// Gets or sets and sets the Module Configuration (ModuleInfo) for this context. /// /// ----------------------------------------------------------------------------- public ModuleInfo Configuration { get { - return _configuration; + return this._configuration; } + set { - _configuration = value; + this._configuration = value; } } /// ----------------------------------------------------------------------------- /// - /// The EditMode property is used to determine whether the user is in the - /// Administrator role + /// Gets a value indicating whether the EditMode property is used to determine whether the user is in the + /// Administrator role. /// /// ----------------------------------------------------------------------------- public bool EditMode @@ -117,44 +104,47 @@ public bool EditMode /// ----------------------------------------------------------------------------- /// - /// Gets and sets the HelpUrl for this context + /// Gets or sets and sets the HelpUrl for this context. /// /// ----------------------------------------------------------------------------- public string HelpURL { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the module is Editable (in Admin mode) + /// Gets a value indicating whether gets whether the module is Editable (in Admin mode). /// /// ----------------------------------------------------------------------------- public bool IsEditable { get { - //Perform tri-state switch check to avoid having to perform a security - //role lookup on every property access (instead caching the result) - if (!_isEditable.HasValue) + // Perform tri-state switch check to avoid having to perform a security + // role lookup on every property access (instead caching the result) + if (!this._isEditable.HasValue) { - bool blnPreview = (PortalSettings.UserMode == PortalSettings.Mode.View) || PortalSettings.IsLocked; - if (Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) + bool blnPreview = (this.PortalSettings.UserMode == PortalSettings.Mode.View) || this.PortalSettings.IsLocked; + if (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) { blnPreview = false; } + bool blnHasModuleEditPermissions = false; - if (_configuration != null) + if (this._configuration != null) { - blnHasModuleEditPermissions = ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "CONTENT", Configuration); + blnHasModuleEditPermissions = ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "CONTENT", this.Configuration); } + if (blnPreview == false && blnHasModuleEditPermissions) { - _isEditable = true; + this._isEditable = true; } else { - _isEditable = false; + this._isEditable = false; } } - return _isEditable.Value; + + return this._isEditable.Value; } } @@ -162,31 +152,32 @@ public bool IsHostMenu { get { - return Globals.IsHostTab(PortalSettings.ActiveTab.TabID); + return Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the module ID for this context + /// Gets or sets and sets the module ID for this context. /// /// ----------------------------------------------------------------------------- public int ModuleId { get { - if (_configuration != null) + if (this._configuration != null) { - return _configuration.ModuleID; + return this._configuration.ModuleID; } return Null.NullInteger; } + set { - if (_configuration != null) + if (this._configuration != null) { - _configuration.ModuleID = value; + this._configuration.ModuleID = value; } } } @@ -195,7 +186,7 @@ public PortalAliasInfo PortalAlias { get { - return PortalSettings.PortalAlias; + return this.PortalSettings.PortalAlias; } } @@ -203,7 +194,7 @@ public int PortalId { get { - return PortalSettings.PortalId; + return this.PortalSettings.PortalId; } } @@ -217,40 +208,41 @@ public PortalSettings PortalSettings /// ----------------------------------------------------------------------------- /// - /// Gets the settings for this context + /// Gets the settings for this context. /// /// ----------------------------------------------------------------------------- public Hashtable Settings { get { - if (_settings == null) + if (this._settings == null) { - _settings = new ModuleController().GetModuleSettings(ModuleId, TabId); + this._settings = new ModuleController().GetModuleSettings(this.ModuleId, this.TabId); - //add the TabModuleSettings to the ModuleSettings - Hashtable tabModuleSettings = new ModuleController().GetTabModuleSettings(TabModuleId, TabId); + // add the TabModuleSettings to the ModuleSettings + Hashtable tabModuleSettings = new ModuleController().GetTabModuleSettings(this.TabModuleId, this.TabId); foreach (string strKey in tabModuleSettings.Keys) { - _settings[strKey] = tabModuleSettings[strKey]; + this._settings[strKey] = tabModuleSettings[strKey]; } } - return _settings; + + return this._settings; } } /// ----------------------------------------------------------------------------- /// - /// Gets the tab ID for this context + /// Gets the tab ID for this context. /// /// ----------------------------------------------------------------------------- public int TabId { get { - if (_configuration != null) + if (this._configuration != null) { - return Convert.ToInt32(_configuration.TabID); + return Convert.ToInt32(this._configuration.TabID); } return Null.NullInteger; @@ -259,36 +251,71 @@ public int TabId /// ----------------------------------------------------------------------------- /// - /// Gets the tabnmodule ID for this context + /// Gets or sets the tabnmodule ID for this context. /// /// ----------------------------------------------------------------------------- public int TabModuleId { get { - if (_configuration != null) + if (this._configuration != null) { - return Convert.ToInt32(_configuration.TabModuleID); + return Convert.ToInt32(this._configuration.TabModuleID); } return Null.NullInteger; } + set { - if (_configuration != null) + if (this._configuration != null) { - _configuration.TabModuleID = value; + this._configuration.TabModuleID = value; } } } - #endregion + public string EditUrl() + { + return this.EditUrl(string.Empty, string.Empty, "Edit"); + } + + public string EditUrl(string controlKey) + { + return this.EditUrl(string.Empty, string.Empty, controlKey); + } + + private static string FilterUrl(HttpRequest request) + { + return request.RawUrl.Replace("\"", string.Empty); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetActionsCount gets the current number of actions. + /// + /// The actions collection to count. + /// The current count. + /// ----------------------------------------------------------------------------- + private static int GetActionsCount(int count, ModuleActionCollection actions) + { + foreach (ModuleAction action in actions) + { + if (action.HasChildren()) + { + count += action.Actions.Count; + + // Recursively call to see if this collection has any child actions that would affect the count + count = GetActionsCount(count, action.Actions); + } + } - #region Private Methods + return count; + } /// ----------------------------------------------------------------------------- /// - /// AddHelpActions Adds the Help actions to the Action Menu + /// AddHelpActions Adds the Help actions to the Action Menu. /// /// /// @@ -297,424 +324,415 @@ private void AddHelpActions() { var url = string.Empty; var showInNewWindow = false; - if (!string.IsNullOrEmpty(Configuration.ModuleControl.HelpURL) && Host.EnableModuleOnLineHelp && PortalSettings.EnablePopUps) + if (!string.IsNullOrEmpty(this.Configuration.ModuleControl.HelpURL) && Host.EnableModuleOnLineHelp && this.PortalSettings.EnablePopUps) { - var supportInPopup = SupportShowInPopup(Configuration.ModuleControl.HelpURL); + var supportInPopup = this.SupportShowInPopup(this.Configuration.ModuleControl.HelpURL); if (supportInPopup) { - url = UrlUtils.PopUpUrl(Configuration.ModuleControl.HelpURL, PortalSettings, false, false, 550, 950); + url = UrlUtils.PopUpUrl(this.Configuration.ModuleControl.HelpURL, this.PortalSettings, false, false, 550, 950); } else { - url = Configuration.ModuleControl.HelpURL; + url = this.Configuration.ModuleControl.HelpURL; showInNewWindow = true; } } else { - url = NavigateUrl(TabId, "Help", false, "ctlid=" + Configuration.ModuleControlId, "moduleid=" + ModuleId); - } - - var helpAction = new ModuleAction(GetNextActionID()) - { - Title = Localization.GetString(ModuleActionType.ModuleHelp, Localization.GlobalResourceFile), - CommandName = ModuleActionType.ModuleHelp, - CommandArgument = "", - Icon = "action_help.gif", - Url = url, - Secure = SecurityAccessLevel.Edit, - Visible = true, - NewWindow = showInNewWindow, - UseActionEvent = true - }; - _moduleGenericActions.Actions.Add(helpAction); + url = this.NavigateUrl(this.TabId, "Help", false, "ctlid=" + this.Configuration.ModuleControlId, "moduleid=" + this.ModuleId); + } + + var helpAction = new ModuleAction(this.GetNextActionID()) + { + Title = Localization.GetString(ModuleActionType.ModuleHelp, Localization.GlobalResourceFile), + CommandName = ModuleActionType.ModuleHelp, + CommandArgument = string.Empty, + Icon = "action_help.gif", + Url = url, + Secure = SecurityAccessLevel.Edit, + Visible = true, + NewWindow = showInNewWindow, + UseActionEvent = true, + }; + this._moduleGenericActions.Actions.Add(helpAction); } private void AddPrintAction() { - var action = new ModuleAction(GetNextActionID()) - { - Title = Localization.GetString(ModuleActionType.PrintModule, Localization.GlobalResourceFile), - CommandName = ModuleActionType.PrintModule, - CommandArgument = "", - Icon = "action_print.gif", - Url = NavigateUrl(TabId, - "", - false, - "mid=" + ModuleId, - "SkinSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootSkin + "/" + Globals.glbHostSkinFolder + "/" + "No Skin"), - "ContainerSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootContainer + "/" + Globals.glbHostSkinFolder + "/" + "No Container"), - "dnnprintmode=true"), - Secure = SecurityAccessLevel.Anonymous, - UseActionEvent = true, - Visible = true, - NewWindow = true - }; - _moduleGenericActions.Actions.Add(action); + var action = new ModuleAction(this.GetNextActionID()) + { + Title = Localization.GetString(ModuleActionType.PrintModule, Localization.GlobalResourceFile), + CommandName = ModuleActionType.PrintModule, + CommandArgument = string.Empty, + Icon = "action_print.gif", + Url = this.NavigateUrl( + this.TabId, + string.Empty, + false, + "mid=" + this.ModuleId, + "SkinSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootSkin + "/" + Globals.glbHostSkinFolder + "/" + "No Skin"), + "ContainerSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootContainer + "/" + Globals.glbHostSkinFolder + "/" + "No Container"), + "dnnprintmode=true"), + Secure = SecurityAccessLevel.Anonymous, + UseActionEvent = true, + Visible = true, + NewWindow = true, + }; + this._moduleGenericActions.Actions.Add(action); } private void AddSyndicateAction() { - var action = new ModuleAction(GetNextActionID()) - { - Title = Localization.GetString(ModuleActionType.SyndicateModule, Localization.GlobalResourceFile), - CommandName = ModuleActionType.SyndicateModule, - CommandArgument = "", - Icon = "action_rss.gif", - Url = NavigateUrl(PortalSettings.ActiveTab.TabID, "", "RSS.aspx", false, "moduleid=" + ModuleId), - Secure = SecurityAccessLevel.Anonymous, - UseActionEvent = true, - Visible = true, - NewWindow = true - }; - _moduleGenericActions.Actions.Add(action); + var action = new ModuleAction(this.GetNextActionID()) + { + Title = Localization.GetString(ModuleActionType.SyndicateModule, Localization.GlobalResourceFile), + CommandName = ModuleActionType.SyndicateModule, + CommandArgument = string.Empty, + Icon = "action_rss.gif", + Url = this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, string.Empty, "RSS.aspx", false, "moduleid=" + this.ModuleId), + Secure = SecurityAccessLevel.Anonymous, + UseActionEvent = true, + Visible = true, + NewWindow = true, + }; + this._moduleGenericActions.Actions.Add(action); } /// ----------------------------------------------------------------------------- /// - /// AddMenuMoveActions Adds the Move actions to the Action Menu + /// AddMenuMoveActions Adds the Move actions to the Action Menu. /// /// /// /// ----------------------------------------------------------------------------- private void AddMenuMoveActions() { - //module movement - _moduleMoveActions = new ModuleAction(GetNextActionID(), Localization.GetString(ModuleActionType.MoveRoot, Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, false); + // module movement + this._moduleMoveActions = new ModuleAction(this.GetNextActionID(), Localization.GetString(ModuleActionType.MoveRoot, Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, false); - //move module up/down - if (Configuration != null) + // move module up/down + if (this.Configuration != null) { - if ((Configuration.ModuleOrder != 0) && (Configuration.PaneModuleIndex > 0)) + if ((this.Configuration.ModuleOrder != 0) && (this.Configuration.PaneModuleIndex > 0)) { - _moduleMoveActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.MoveTop, Localization.GlobalResourceFile), - ModuleActionType.MoveTop, - Configuration.PaneName, - "action_top.gif", - "", - false, - SecurityAccessLevel.View, - true, - false); - _moduleMoveActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.MoveUp, Localization.GlobalResourceFile), - ModuleActionType.MoveUp, - Configuration.PaneName, - "action_up.gif", - "", - false, - SecurityAccessLevel.View, - true, - false); + this._moduleMoveActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.MoveTop, Localization.GlobalResourceFile), + ModuleActionType.MoveTop, + this.Configuration.PaneName, + "action_top.gif", + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); + this._moduleMoveActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.MoveUp, Localization.GlobalResourceFile), + ModuleActionType.MoveUp, + this.Configuration.PaneName, + "action_up.gif", + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); } - if ((Configuration.ModuleOrder != 0) && (Configuration.PaneModuleIndex < (Configuration.PaneModuleCount - 1))) - { - _moduleMoveActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.MoveDown, Localization.GlobalResourceFile), - ModuleActionType.MoveDown, - Configuration.PaneName, - "action_down.gif", - "", - false, - SecurityAccessLevel.View, - true, - false); - _moduleMoveActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.MoveBottom, Localization.GlobalResourceFile), - ModuleActionType.MoveBottom, - Configuration.PaneName, - "action_bottom.gif", - "", - false, - SecurityAccessLevel.View, - true, - false); - } - } - //move module to pane - foreach (object obj in PortalSettings.ActiveTab.Panes) - { - var pane = obj as string; - if (!string.IsNullOrEmpty(pane) && Configuration != null && !Configuration.PaneName.Equals(pane, StringComparison.InvariantCultureIgnoreCase)) + if ((this.Configuration.ModuleOrder != 0) && (this.Configuration.PaneModuleIndex < (this.Configuration.PaneModuleCount - 1))) { - _moduleMoveActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.MovePane, Localization.GlobalResourceFile) + " " + pane, - ModuleActionType.MovePane, - pane, - "action_move.gif", - "", - false, - SecurityAccessLevel.View, - true, - false); + this._moduleMoveActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.MoveDown, Localization.GlobalResourceFile), + ModuleActionType.MoveDown, + this.Configuration.PaneName, + "action_down.gif", + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); + this._moduleMoveActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.MoveBottom, Localization.GlobalResourceFile), + ModuleActionType.MoveBottom, + this.Configuration.PaneName, + "action_bottom.gif", + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); } } - } - - private static string FilterUrl(HttpRequest request) - { - return request.RawUrl.Replace("\"", ""); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetActionsCount gets the current number of actions - /// - /// The actions collection to count. - /// The current count - /// ----------------------------------------------------------------------------- - private static int GetActionsCount(int count, ModuleActionCollection actions) - { - foreach (ModuleAction action in actions) + // move module to pane + foreach (object obj in this.PortalSettings.ActiveTab.Panes) { - if (action.HasChildren()) + var pane = obj as string; + if (!string.IsNullOrEmpty(pane) && this.Configuration != null && !this.Configuration.PaneName.Equals(pane, StringComparison.InvariantCultureIgnoreCase)) { - count += action.Actions.Count; - - //Recursively call to see if this collection has any child actions that would affect the count - count = GetActionsCount(count, action.Actions); + this._moduleMoveActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.MovePane, Localization.GlobalResourceFile) + " " + pane, + ModuleActionType.MovePane, + pane, + "action_move.gif", + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); } } - return count; } /// ----------------------------------------------------------------------------- /// - /// LoadActions loads the Actions collections + /// LoadActions loads the Actions collections. /// /// /// /// ----------------------------------------------------------------------------- private void LoadActions(HttpRequest request) { - _actions = new ModuleActionCollection(); - if (PortalSettings.IsLocked) + this._actions = new ModuleActionCollection(); + if (this.PortalSettings.IsLocked) { return; } - _moduleGenericActions = new ModuleAction(GetNextActionID(), Localization.GetString("ModuleGenericActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty); + this._moduleGenericActions = new ModuleAction(this.GetNextActionID(), Localization.GetString("ModuleGenericActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty); int maxActionId = Null.NullInteger; - //check if module Implements Entities.Modules.IActionable interface - var actionable = _moduleControl as IActionable; + // check if module Implements Entities.Modules.IActionable interface + var actionable = this._moduleControl as IActionable; if (actionable != null) { - _moduleSpecificActions = new ModuleAction(GetNextActionID(), Localization.GetString("ModuleSpecificActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty); + this._moduleSpecificActions = new ModuleAction(this.GetNextActionID(), Localization.GetString("ModuleSpecificActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty); ModuleActionCollection moduleActions = actionable.ModuleActions; foreach (ModuleAction action in moduleActions) { - if (ModulePermissionController.HasModuleAccess(action.Secure, "CONTENT", Configuration)) + if (ModulePermissionController.HasModuleAccess(action.Secure, "CONTENT", this.Configuration)) { - if (String.IsNullOrEmpty(action.Icon)) + if (string.IsNullOrEmpty(action.Icon)) { action.Icon = "edit.gif"; } + if (action.ID > maxActionId) { maxActionId = action.ID; } - _moduleSpecificActions.Actions.Add(action); - if (!UIUtilities.IsLegacyUI(ModuleId, action.ControlKey, PortalId) && action.Url.Contains("ctl")) + this._moduleSpecificActions.Actions.Add(action); + + if (!UIUtilities.IsLegacyUI(this.ModuleId, action.ControlKey, this.PortalId) && action.Url.Contains("ctl")) { - action.ClientScript = UrlUtils.PopUpUrl(action.Url, _moduleControl as Control, PortalSettings, true, false); + action.ClientScript = UrlUtils.PopUpUrl(action.Url, this._moduleControl as Control, this.PortalSettings, true, false); } } } - if (_moduleSpecificActions.Actions.Count > 0) + + if (this._moduleSpecificActions.Actions.Count > 0) { - _actions.Add(_moduleSpecificActions); + this._actions.Add(this._moduleSpecificActions); } } - //Make sure the Next Action Id counter is correct - int actionCount = GetActionsCount(_actions.Count, _actions); - if (_nextActionId < maxActionId) + // Make sure the Next Action Id counter is correct + int actionCount = GetActionsCount(this._actions.Count, this._actions); + if (this._nextActionId < maxActionId) { - _nextActionId = maxActionId; + this._nextActionId = maxActionId; } - if (_nextActionId < actionCount) + + if (this._nextActionId < actionCount) { - _nextActionId = actionCount; + this._nextActionId = actionCount; } - //Custom injection of Module Settings when shared as ViewOnly - if (Configuration != null && (Configuration.IsShared && Configuration.IsShareableViewOnly) + // Custom injection of Module Settings when shared as ViewOnly + if (this.Configuration != null && (this.Configuration.IsShared && this.Configuration.IsShareableViewOnly) && TabPermissionController.CanAddContentToPage()) { - _moduleGenericActions.Actions.Add(GetNextActionID(), - Localization.GetString("ModulePermissions.Action", Localization.GlobalResourceFile), - "ModulePermissions", - "", - "action_settings.gif", - NavigateUrl(TabId, "ModulePermissions", false, "ModuleId=" + ModuleId, "ReturnURL=" + FilterUrl(request)), - false, - SecurityAccessLevel.ViewPermissions, - true, - false); + this._moduleGenericActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString("ModulePermissions.Action", Localization.GlobalResourceFile), + "ModulePermissions", + string.Empty, + "action_settings.gif", + this.NavigateUrl(this.TabId, "ModulePermissions", false, "ModuleId=" + this.ModuleId, "ReturnURL=" + FilterUrl(request)), + false, + SecurityAccessLevel.ViewPermissions, + true, + false); } else { - if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", Configuration)) + if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", this.Configuration)) { - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration)) + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", this.Configuration)) { - _moduleGenericActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.ModuleSettings, Localization.GlobalResourceFile), - ModuleActionType.ModuleSettings, - "", - "action_settings.gif", - NavigateUrl(TabId, "Module", false, "ModuleId=" + ModuleId, "ReturnURL=" + FilterUrl(request)), - false, - SecurityAccessLevel.Edit, - true, - false); + this._moduleGenericActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.ModuleSettings, Localization.GlobalResourceFile), + ModuleActionType.ModuleSettings, + string.Empty, + "action_settings.gif", + this.NavigateUrl(this.TabId, "Module", false, "ModuleId=" + this.ModuleId, "ReturnURL=" + FilterUrl(request)), + false, + SecurityAccessLevel.Edit, + true, + false); } } } - if (!string.IsNullOrEmpty(Configuration.DesktopModule.BusinessControllerClass)) + if (!string.IsNullOrEmpty(this.Configuration.DesktopModule.BusinessControllerClass)) { - //check if module implements IPortable interface, and user has Admin permissions - if (Configuration.DesktopModule.IsPortable) + // check if module implements IPortable interface, and user has Admin permissions + if (this.Configuration.DesktopModule.IsPortable) { - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "EXPORT", Configuration)) + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "EXPORT", this.Configuration)) { - _moduleGenericActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.ExportModule, Localization.GlobalResourceFile), - ModuleActionType.ExportModule, - "", - "action_export.gif", - NavigateUrl(PortalSettings.ActiveTab.TabID, "ExportModule", false, "moduleid=" + ModuleId, "ReturnURL=" + FilterUrl(request)), - - "", - false, - SecurityAccessLevel.View, - true, - false); + this._moduleGenericActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.ExportModule, Localization.GlobalResourceFile), + ModuleActionType.ExportModule, + string.Empty, + "action_export.gif", + this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, "ExportModule", false, "moduleid=" + this.ModuleId, "ReturnURL=" + FilterUrl(request)), + + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); } - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "IMPORT", Configuration)) + + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "IMPORT", this.Configuration)) { - _moduleGenericActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.ImportModule, Localization.GlobalResourceFile), - ModuleActionType.ImportModule, - "", - "action_import.gif", - NavigateUrl(PortalSettings.ActiveTab.TabID, "ImportModule", false, "moduleid=" + ModuleId, "ReturnURL=" + FilterUrl(request)), - "", - false, - SecurityAccessLevel.View, - true, - false); + this._moduleGenericActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.ImportModule, Localization.GlobalResourceFile), + ModuleActionType.ImportModule, + string.Empty, + "action_import.gif", + this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, "ImportModule", false, "moduleid=" + this.ModuleId, "ReturnURL=" + FilterUrl(request)), + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); } } - if (Configuration.DesktopModule.IsSearchable && Configuration.DisplaySyndicate) + + if (this.Configuration.DesktopModule.IsSearchable && this.Configuration.DisplaySyndicate) { - AddSyndicateAction(); + this.AddSyndicateAction(); } } - //help module actions available to content editors and administrators + // help module actions available to content editors and administrators const string permisisonList = "CONTENT,DELETE,EDIT,EXPORT,IMPORT,MANAGE"; - if (ModulePermissionController.HasModulePermission(Configuration.ModulePermissions, permisisonList) + if (ModulePermissionController.HasModulePermission(this.Configuration.ModulePermissions, permisisonList) && request.QueryString["ctl"] != "Help" && !Globals.IsAdminControl()) { - AddHelpActions(); + this.AddHelpActions(); } - //Add Print Action - if (Configuration.DisplayPrint) + // Add Print Action + if (this.Configuration.DisplayPrint) { - //print module action available to everyone - AddPrintAction(); + // print module action available to everyone + this.AddPrintAction(); } - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Host, "MANAGE", Configuration) && !Globals.IsAdminControl()) + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Host, "MANAGE", this.Configuration) && !Globals.IsAdminControl()) { - _moduleGenericActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.ViewSource, Localization.GlobalResourceFile), - ModuleActionType.ViewSource, - "", - "action_source.gif", - NavigateUrl(TabId, "ViewSource", false, "ModuleId=" + ModuleId, "ctlid=" + Configuration.ModuleControlId, "ReturnURL=" + FilterUrl(request)), - false, - SecurityAccessLevel.Host, - true, - false); + this._moduleGenericActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.ViewSource, Localization.GlobalResourceFile), + ModuleActionType.ViewSource, + string.Empty, + "action_source.gif", + this.NavigateUrl(this.TabId, "ViewSource", false, "ModuleId=" + this.ModuleId, "ctlid=" + this.Configuration.ModuleControlId, "ReturnURL=" + FilterUrl(request)), + false, + SecurityAccessLevel.Host, + true, + false); } - - - if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", Configuration)) + if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", this.Configuration)) { - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE", Configuration)) + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE", this.Configuration)) { - //Check if this is the owner instance of a shared module. + // Check if this is the owner instance of a shared module. string confirmText = "confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteModule.Confirm")) + "')"; - if (!Configuration.IsShared) + if (!this.Configuration.IsShared) { - var portal = PortalController.Instance.GetPortal(PortalSettings.PortalId); - if (PortalGroupController.Instance.IsModuleShared(Configuration.ModuleID, portal)) + var portal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); + if (PortalGroupController.Instance.IsModuleShared(this.Configuration.ModuleID, portal)) { confirmText = "confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteSharedModule.Confirm")) + "')"; } } - _moduleGenericActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.DeleteModule, Localization.GlobalResourceFile), - ModuleActionType.DeleteModule, - Configuration.ModuleID.ToString(), - "action_delete.gif", - "", - confirmText, - false, - SecurityAccessLevel.View, - true, - false); + this._moduleGenericActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.DeleteModule, Localization.GlobalResourceFile), + ModuleActionType.DeleteModule, + this.Configuration.ModuleID.ToString(), + "action_delete.gif", + string.Empty, + confirmText, + false, + SecurityAccessLevel.View, + true, + false); } - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration)) + + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", this.Configuration)) { - _moduleGenericActions.Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.ClearCache, Localization.GlobalResourceFile), - ModuleActionType.ClearCache, - Configuration.ModuleID.ToString(), - "action_refresh.gif", - "", - false, - SecurityAccessLevel.View, - true, - false); + this._moduleGenericActions.Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.ClearCache, Localization.GlobalResourceFile), + ModuleActionType.ClearCache, + this.Configuration.ModuleID.ToString(), + "action_refresh.gif", + string.Empty, + false, + SecurityAccessLevel.View, + true, + false); } - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration)) + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", this.Configuration)) { - //module movement - AddMenuMoveActions(); + // module movement + this.AddMenuMoveActions(); } } - if (_moduleGenericActions.Actions.Count > 0) + if (this._moduleGenericActions.Actions.Count > 0) { - _actions.Add(_moduleGenericActions); + this._actions.Add(this._moduleGenericActions); } - if (_moduleMoveActions != null && _moduleMoveActions.Actions.Count > 0) + if (this._moduleMoveActions != null && this._moduleMoveActions.Actions.Count > 0) { - _actions.Add(_moduleMoveActions); + this._actions.Add(this._moduleMoveActions); } - foreach (ModuleAction action in _moduleGenericActions.Actions) + foreach (ModuleAction action in this._moduleGenericActions.Actions) { - if (!UIUtilities.IsLegacyUI(ModuleId, action.ControlKey, PortalId) && action.Url.Contains("ctl")) + if (!UIUtilities.IsLegacyUI(this.ModuleId, action.ControlKey, this.PortalId) && action.Url.Contains("ctl")) { - action.ClientScript = UrlUtils.PopUpUrl(action.Url, _moduleControl as Control, PortalSettings, true, false); + action.ClientScript = UrlUtils.PopUpUrl(action.Url, this._moduleControl as Control, this.PortalSettings, true, false); } } } @@ -731,29 +749,15 @@ private bool SupportShowInPopup(string url) || (!isSecureConnection && url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)); } - #endregion - - #region Public Methods - - public string EditUrl() - { - return EditUrl("", "", "Edit"); - } - - public string EditUrl(string controlKey) - { - return EditUrl("", "", controlKey); - } - public string EditUrl(string keyName, string keyValue) { - return EditUrl(keyName, keyValue, "Edit"); + return this.EditUrl(keyName, keyValue, "Edit"); } public string EditUrl(string keyName, string keyValue, string controlKey) { var parameters = new string[] { }; - return EditUrl(keyName, keyValue, controlKey, parameters); + return this.EditUrl(keyName, keyValue, controlKey, parameters); } public string EditUrl(string keyName, string keyValue, string controlKey, params string[] additionalParameters) @@ -763,10 +767,11 @@ public string EditUrl(string keyName, string keyValue, string controlKey, params { key = "Edit"; } + string moduleIdParam = string.Empty; - if (Configuration != null) + if (this.Configuration != null) { - moduleIdParam = string.Format("mid={0}", Configuration.ModuleID); + moduleIdParam = string.Format("mid={0}", this.Configuration.ModuleID); } string[] parameters; @@ -784,12 +789,12 @@ public string EditUrl(string keyName, string keyValue, string controlKey, params Array.Copy(additionalParameters, 0, parameters, 1, additionalParameters.Length); } - return NavigateUrl(PortalSettings.ActiveTab.TabID, key, false, parameters); + return this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, key, false, parameters); } public string NavigateUrl(int tabID, string controlKey, bool pageRedirect, params string[] additionalParameters) { - return NavigateUrl(tabID, controlKey, Globals.glbDefaultPage, pageRedirect, additionalParameters); + return this.NavigateUrl(tabID, controlKey, Globals.glbDefaultPage, pageRedirect, additionalParameters); } public string NavigateUrl(int tabID, string controlKey, string pageName, bool pageRedirect, params string[] additionalParameters) @@ -800,22 +805,21 @@ public string NavigateUrl(int tabID, string controlKey, string pageName, bool pa var url = TestableGlobals.Instance.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); // Making URLs call popups - if (PortalSettings != null && PortalSettings.EnablePopUps) + if (this.PortalSettings != null && this.PortalSettings.EnablePopUps) { - if (!UIUtilities.IsLegacyUI(ModuleId, controlKey, PortalId) && (url.Contains("ctl"))) + if (!UIUtilities.IsLegacyUI(this.ModuleId, controlKey, this.PortalId) && url.Contains("ctl")) { - url = UrlUtils.PopUpUrl(url, null, PortalSettings, false, pageRedirect); + url = UrlUtils.PopUpUrl(url, null, this.PortalSettings, false, pageRedirect); } } + return url; } public int GetNextActionID() { - _nextActionId += 1; - return _nextActionId; + this._nextActionId += 1; + return this._nextActionId; } - - #endregion } } diff --git a/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs b/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs index 73b06f8f556..6bb4821d45d 100644 --- a/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.IO; -using System.Web.UI; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System.IO; + using System.Web.UI; + + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Modules - /// Class : ModuleUserControlBase + /// Class : ModuleUserControlBase /// ----------------------------------------------------------------------------- /// /// ModuleUserControlBase is a base class for Module Controls that inherits from the @@ -28,24 +23,12 @@ public class ModuleUserControlBase : UserControl, IModuleControl { private string _localResourceFile; private ModuleInstanceContext _moduleContext; - - protected string LocalizeString(string key) - { - return Localization.GetString(key, LocalResourceFile); - } - - protected string LocalizeSafeJsString(string key) - { - return Localization.GetSafeJSString(key, LocalResourceFile); - } - - #region IModuleControl Members - + /// ----------------------------------------------------------------------------- /// - /// Gets the underlying base control for this ModuleControl + /// Gets the underlying base control for this ModuleControl. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public Control Control { @@ -57,77 +40,88 @@ public Control Control /// ----------------------------------------------------------------------------- /// - /// Gets the Path for this control (used primarily for UserControls) + /// Gets the Path for this control (used primarily for UserControls). /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlPath { get { - return TemplateSourceDirectory + "/"; + return this.TemplateSourceDirectory + "/"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Name for this control + /// Gets the Name for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ControlName { get { - return GetType().Name.Replace("_", "."); + return this.GetType().Name.Replace("_", "."); } } + protected string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + + protected string LocalizeSafeJsString(string key) + { + return Localization.GetSafeJSString(key, this.LocalResourceFile); + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the local resource file for this control + /// Gets or sets and sets the local resource file for this control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string LocalResourceFile { get { string fileRoot; - if (string.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = Path.Combine(ControlPath, Localization.LocalResourceDirectory + "/" + ID); + fileRoot = Path.Combine(this.ControlPath, Localization.LocalResourceDirectory + "/" + this.ID); } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Module Context for this control + /// Gets the Module Context for this control. /// - /// A ModuleInstanceContext + /// A ModuleInstanceContext. /// ----------------------------------------------------------------------------- public ModuleInstanceContext ModuleContext { get { - if (_moduleContext == null) + if (this._moduleContext == null) { - _moduleContext = new ModuleInstanceContext(this); + this._moduleContext = new ModuleInstanceContext(this); } - return _moduleContext; + + return this._moduleContext; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs index 4f238e374e2..572f4ae279f 100644 --- a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs @@ -1,72 +1,81 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; -using System.Threading; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System; + using System.Globalization; + using System.Threading; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using Microsoft.Extensions.DependencyInjection; + public abstract class ProfileModuleUserControlBase : ModuleUserControlBase, IProfileModule { - protected INavigationManager NavigationManager { get; } public ProfileModuleUserControlBase() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - #region IProfileModule Members - + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + } + public abstract bool DisplayModule { get; } public int ProfileUserId { get { - if (!string.IsNullOrEmpty(Request.Params["UserId"])) + if (!string.IsNullOrEmpty(this.Request.Params["UserId"])) { - return Int32.Parse(Request.Params["UserId"]); + return int.Parse(this.Request.Params["UserId"]); } return UserController.Instance.GetCurrentUserInfo().UserID; } - } - - #endregion - - #region Protected Properties - + } + + protected INavigationManager NavigationManager { get; } + protected bool IsUser { - get { return ProfileUserId == ModuleContext.PortalSettings.UserId; } + get { return this.ProfileUserId == this.ModuleContext.PortalSettings.UserId; } } protected UserInfo ProfileUser { - get { return UserController.GetUserById(ModuleContext.PortalId, ProfileUserId); } - } - - #endregion - - #region Private Methods + get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } + } + + protected override void OnInit(EventArgs e) + { + if (string.IsNullOrEmpty(this.Request.Params["UserId"]) && + (this.ModuleContext.PortalSettings.ActiveTab.TabID == this.ModuleContext.PortalSettings.UserTabId + || this.ModuleContext.PortalSettings.ActiveTab.ParentId == this.ModuleContext.PortalSettings.UserTabId)) + { + try + { + // Clicked on breadcrumb - don't know which user + this.Response.Redirect( + this.Request.IsAuthenticated + ? this.NavigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, string.Empty, "UserId=" + this.ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) + : this.GetRedirectUrl(), true); + } + catch (ThreadAbortException) + { + Thread.ResetAbort(); + } + } + base.OnInit(e); + } + private string GetRedirectUrl() { - //redirect user to default page if not specific the home tab, do this action to prevent loop redirect. - var homeTabId = ModuleContext.PortalSettings.HomeTabId; + // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. + var homeTabId = this.ModuleContext.PortalSettings.HomeTabId; string redirectUrl; if (homeTabId > Null.NullInteger) @@ -75,39 +84,11 @@ private string GetRedirectUrl() } else { - redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, Request, true) + + redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, this.Request, true) + "/" + Globals.glbDefaultPage; } return redirectUrl; - } - - #endregion - - #region Protected Methods - - protected override void OnInit(EventArgs e) - { - if (string.IsNullOrEmpty(Request.Params["UserId"]) && - (ModuleContext.PortalSettings.ActiveTab.TabID == ModuleContext.PortalSettings.UserTabId - || ModuleContext.PortalSettings.ActiveTab.ParentId == ModuleContext.PortalSettings.UserTabId)) - { - try - { - //Clicked on breadcrumb - don't know which user - Response.Redirect(Request.IsAuthenticated - ? NavigationManager.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "", "UserId=" + ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) - : GetRedirectUrl(), true); - } - catch (ThreadAbortException) - { - Thread.ResetAbort(); - } - } - - base.OnInit(e); - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Modules/ReflectedModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/ReflectedModuleControlFactory.cs index 772b894cc9f..28cadee578e 100644 --- a/DNN Platform/Library/UI/Modules/ReflectedModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/ReflectedModuleControlFactory.cs @@ -1,31 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + public class ReflectedModuleControlFactory : BaseModuleControlFactory { public override Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc) { // load from a typename in an assembly ( ie. server control) var objType = Reflection.CreateType(controlSrc); - return (containerControl.LoadControl(objType, null)); + return containerControl.LoadControl(objType, null); } public override Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { - return CreateControl(containerControl, String.Empty, moduleConfiguration.ModuleControl.ControlSrc); + return this.CreateControl(containerControl, string.Empty, moduleConfiguration.ModuleControl.ControlSrc); } public override Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) { - return CreateControl(containerControl, String.Empty, controlSrc); + return this.CreateControl(containerControl, string.Empty, controlSrc); } } } diff --git a/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs b/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs index e549c37ee06..ac946737dfa 100644 --- a/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs +++ b/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs @@ -1,34 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + public class StandardModuleInjectionFilter : IModuleInjectionFilter - { - #region Implementation of IModuleInjectionFilter - + { public bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings) { - return ModulePermissionController.CanViewModule(module) - && module.IsDeleted == false - && ((module.StartDate < DateTime.Now && module.EndDate > DateTime.Now) - || Globals.IsLayoutMode() - || Globals.IsEditMode() - ); - } - - #endregion + return ModulePermissionController.CanViewModule(module) + && module.IsDeleted == false + && ((module.StartDate < DateTime.Now && module.EndDate > DateTime.Now) + || Globals.IsLayoutMode() + || Globals.IsEditMode()); + } } } diff --git a/DNN Platform/Library/UI/Modules/WebFormsModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/WebFormsModuleControlFactory.cs index 5cdd72662fd..4e26537603d 100644 --- a/DNN Platform/Library/UI/Modules/WebFormsModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/WebFormsModuleControlFactory.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; - -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Modules { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + public class WebFormsModuleControlFactory : BaseModuleControlFactory { public override Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc) @@ -18,12 +18,12 @@ public override Control CreateControl(TemplateControl containerControl, string c public override Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { - return CreateControl(containerControl, String.Empty, moduleConfiguration.ModuleControl.ControlSrc); + return this.CreateControl(containerControl, string.Empty, moduleConfiguration.ModuleControl.ControlSrc); } public override Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) { - return CreateControl(containerControl, String.Empty, controlSrc); + return this.CreateControl(containerControl, string.Empty, controlSrc); } } } diff --git a/DNN Platform/Library/UI/Navigation.cs b/DNN Platform/Library/UI/Navigation.cs index bed04605136..f6f4ee449c8 100644 --- a/DNN Platform/Library/UI/Navigation.cs +++ b/DNN Platform/Library/UI/Navigation.cs @@ -1,73 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Containers; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Containers; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.WebControls; + public class Navigation - { - #region NavNodeOptions enum - + { public enum NavNodeOptions { IncludeSelf = 1, IncludeParent = 2, IncludeSiblings = 4, MarkPendingNodes = 8, - IncludeHiddenNodes = 16 - } - - #endregion - - #region ToolTipSource enum - + IncludeHiddenNodes = 16, + } + public enum ToolTipSource { TabName, Title, Description, - None + None, + } + + public static bool CanShowTab(TabInfo objTab, bool isAdminMode, bool showDisabled) + { + return CanShowTab(objTab, isAdminMode, showDisabled, false); } - #endregion - - #region Private Shared Methods - + public static bool CanShowTab(TabInfo tab, bool isAdminMode, bool showDisabled, bool showHidden) + { + // if tab is visible, not deleted, not expired (or admin), and user has permission to see it... + return (tab.IsVisible || showHidden) && tab.HasAVisibleVersion && !tab.IsDeleted && + (!tab.DisableLink || showDisabled) && + (((tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate) && + (tab.EndDate > DateTime.Now || tab.EndDate == Null.NullDate)) || isAdminMode) && + TabPermissionController.CanNavigateToPage(tab); + } + /// ----------------------------------------------------------------------------- /// - /// Recursive function to add module's actions to the DNNNodeCollection based off of passed in ModuleActions + /// Recursive function to add module's actions to the DNNNodeCollection based off of passed in ModuleActions. /// - /// Parent action - /// Parent node + /// Parent action. + /// Parent node. /// Root Node. - /// ActionControl to base actions off of - /// How many levels deep should be populated + /// ActionControl to base actions off of. + /// How many levels deep should be populated. /// /// /// ----------------------------------------------------------------------------- private static void AddChildActions(ModuleAction parentAction, DNNNode parentNode, DNNNode rootNode, IActionControl actionControl, int intDepth) { - //Add Menu Items + // Add Menu Items foreach (ModuleAction action in parentAction.Actions) { bool isActionPending = IsActionPending(parentNode, rootNode, intDepth); @@ -75,17 +75,17 @@ private static void AddChildActions(ModuleAction parentAction, DNNNode parentNod { if (isActionPending == false) { - //A title (text) of ~ denotes a break + // A title (text) of ~ denotes a break parentNode.DNNNodes.AddBreak(); } } else { - //if action is visible and user has permission + // if action is visible and user has permission if (action.Visible && (action.Secure != SecurityAccessLevel.Anonymous || - (!ModuleHost.IsViewMode(actionControl.ModuleControl.ModuleContext.Configuration, PortalSettings.Current)) - && ModulePermissionController.HasModuleAccess(action.Secure, Null.NullString, actionControl.ModuleControl.ModuleContext.Configuration))) + ((!ModuleHost.IsViewMode(actionControl.ModuleControl.ModuleContext.Configuration, PortalSettings.Current)) + && ModulePermissionController.HasModuleAccess(action.Secure, Null.NullString, actionControl.ModuleControl.ModuleContext.Configuration)))) { if (isActionPending) { @@ -97,7 +97,7 @@ private static void AddChildActions(ModuleAction parentAction, DNNNode parentNod DNNNode node = parentNode.DNNNodes[i]; node.ID = action.ID.ToString(); node.Key = action.ID.ToString(); - node.Text = action.Title; //no longer including SPACE in generic node collection, each control must handle how they want to display + node.Text = action.Title; // no longer including SPACE in generic node collection, each control must handle how they want to display if (string.IsNullOrEmpty(action.ClientScript) && string.IsNullOrEmpty(action.Url) && string.IsNullOrEmpty(action.CommandArgument)) { node.Enabled = false; @@ -110,7 +110,7 @@ private static void AddChildActions(ModuleAction parentAction, DNNNode parentNod else { node.NavigateURL = action.Url; - if (action.UseActionEvent == false && !String.IsNullOrEmpty(node.NavigateURL)) + if (action.UseActionEvent == false && !string.IsNullOrEmpty(node.NavigateURL)) { node.ClickAction = eClickAction.Navigate; if (action.NewWindow) @@ -123,8 +123,9 @@ private static void AddChildActions(ModuleAction parentAction, DNNNode parentNod node.ClickAction = eClickAction.PostBack; } } + node.Image = action.Icon; - if (action.HasChildren()) //if action has children then call function recursively + if (action.HasChildren()) // if action has children then call function recursively { AddChildActions(action, node, rootNode, actionControl, intDepth); } @@ -136,28 +137,28 @@ private static void AddChildActions(ModuleAction parentAction, DNNNode parentNod /// ----------------------------------------------------------------------------- /// - /// Assigns common properties from passed in tab to newly created DNNNode that is added to the passed in DNNNodeCollection + /// Assigns common properties from passed in tab to newly created DNNNode that is added to the passed in DNNNodeCollection. /// - /// Tab to base DNNNode off of - /// Node collection to append new node to - /// Hashtable of breadcrumb IDs to efficiently determine node's BreadCrumb property - /// Portal settings object to determine if node is selected + /// Tab to base DNNNode off of. + /// Node collection to append new node to. + /// Hashtable of breadcrumb IDs to efficiently determine node's BreadCrumb property. + /// Portal settings object to determine if node is selected. /// /// - /// Logic moved to separate sub to make GetNavigationNodes cleaner + /// Logic moved to separate sub to make GetNavigationNodes cleaner. /// /// ----------------------------------------------------------------------------- private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtable objBreadCrumbs, PortalSettings objPortalSettings, ToolTipSource eToolTips, IDictionary nodesLookup) { var objNode = new DNNNode(); - if (objTab.Title == "~") //NEW! + if (objTab.Title == "~") // NEW! { - //A title (text) of ~ denotes a break + // A title (text) of ~ denotes a break objNodes.AddBreak(); } else { - //assign breadcrumb and selected properties + // assign breadcrumb and selected properties if (objBreadCrumbs.Contains(objTab.TabID)) { objNode.BreadCrumb = true; @@ -166,10 +167,12 @@ private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtabl objNode.Selected = true; } } + if (objTab.DisableLink) { objNode.Enabled = false; } + objNode.ID = objTab.TabID.ToString(); objNode.Key = objNode.ID; objNode.Text = objTab.LocalizedTabName; @@ -189,8 +192,9 @@ private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtabl objNode.ToolTip = objTab.Description; break; } + bool newWindow = false; - if (objTab.TabSettings["LinkNewWindow"] != null && Boolean.TryParse((string)objTab.TabSettings["LinkNewWindow"], out newWindow) && newWindow) + if (objTab.TabSettings["LinkNewWindow"] != null && bool.TryParse((string)objTab.TabSettings["LinkNewWindow"], out newWindow) && newWindow) { objNode.Target = "_blank"; } @@ -205,40 +209,40 @@ private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtabl private static bool IsActionPending(DNNNode objParentNode, DNNNode objRootNode, int intDepth) { - //if we aren't restricting depth then its never pending + // if we aren't restricting depth then its never pending if (intDepth == -1) { return false; } - //parents level + 1 = current node level - //if current node level - (roots node level) <= the desired depth then not pending + // parents level + 1 = current node level + // if current node level - (roots node level) <= the desired depth then not pending if (objParentNode.Level + 1 - objRootNode.Level <= intDepth) { return false; } + return true; } private static bool IsTabPending(TabInfo objTab, DNNNode objParentNode, DNNNode objRootNode, int intDepth, Hashtable objBreadCrumbs, int intLastBreadCrumbId, bool blnPOD) { - // - //A - //| + // A + // | //--B - //| | - //| --B-1 - //| | | - //| | --B-1-1 - //| | | - //| | --B-1-2 - //| | - //| --B-2 - //| | - //| --B-2-1 - //| | - //| --B-2-2 - //| + // | | + // | --B-1 + // | | | + // | | --B-1-1 + // | | | + // | | --B-1-2 + // | | + // | --B-2 + // | | + // | --B-2-1 + // | | + // | --B-2-2 + // | //--C // | // --C-1 @@ -253,42 +257,42 @@ private static bool IsTabPending(TabInfo objTab, DNNNode objParentNode, DNNNode // | // --C-2-2 - //if we aren't restricting depth then its never pending + // if we aren't restricting depth then its never pending if (intDepth == -1) { return false; } - //parents level + 1 = current node level - //if current node level - (roots node level) <= the desired depth then not pending + // parents level + 1 = current node level + // if current node level - (roots node level) <= the desired depth then not pending if (objParentNode.Level + 1 - objRootNode.Level <= intDepth) { return false; } - - + //--- These checks below are here so tree becomes expands to selected node --- if (blnPOD) { - //really only applies to controls with POD enabled, since the root passed in may be some node buried down in the chain - //and the depth something like 1. We need to include the appropriate parent's and parent siblings - //Why is the check for POD required? Well to allow for functionality like RootOnly requests. We do not want any children - //regardless if they are a breadcrumb + // really only applies to controls with POD enabled, since the root passed in may be some node buried down in the chain + // and the depth something like 1. We need to include the appropriate parent's and parent siblings + // Why is the check for POD required? Well to allow for functionality like RootOnly requests. We do not want any children + // regardless if they are a breadcrumb - //if tab is in the breadcrumbs then obviously not pending + // if tab is in the breadcrumbs then obviously not pending if (objBreadCrumbs.Contains(objTab.TabID)) { return false; } - //if parent is in the breadcrumb and it is not the last breadcrumb then not pending - //in tree above say we our breadcrumb is (A, B, B-2) we want our tree containing A, B, B-2 AND B-1 AND C since A and B are expanded - //we do NOT want B-2-1 and B-2-2, thus the check for Last Bread Crumb + // if parent is in the breadcrumb and it is not the last breadcrumb then not pending + // in tree above say we our breadcrumb is (A, B, B-2) we want our tree containing A, B, B-2 AND B-1 AND C since A and B are expanded + // we do NOT want B-2-1 and B-2-2, thus the check for Last Bread Crumb if (objBreadCrumbs.Contains(objTab.ParentId) && intLastBreadCrumbId != objTab.ParentId) { return false; } } + return true; } @@ -299,7 +303,7 @@ private static bool IsTabSibling(TabInfo objTab, int intStartTabId, Hashtable ob return objTab.ParentId == -1; } - return objTab.ParentId == ((TabInfo) objTabLookup[intStartTabId]).ParentId; + return objTab.ParentId == ((TabInfo)objTabLookup[intStartTabId]).ParentId; } private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable objTabLookup, Hashtable objBreadCrumbs, int intLastBreadCrumbId, ToolTipSource eToolTips, int intStartTabId, @@ -308,7 +312,7 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob PortalSettings objPortalSettings = PortalController.Instance.GetCurrentPortalSettings(); bool showHidden = (intNavNodeOptions & (int)NavNodeOptions.IncludeHiddenNodes) == (int)NavNodeOptions.IncludeHiddenNodes; - if (CanShowTab(objTab, TabPermissionController.CanAdminPage(), true, showHidden)) //based off of tab properties, is it shown + if (CanShowTab(objTab, TabPermissionController.CanAdminPage(), true, showHidden)) // based off of tab properties, is it shown { DNNNodeCollection objParentNodes; DNNNode objParentNode; @@ -317,47 +321,49 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob { objParentNode = objRootNode; } + objParentNodes = objParentNode.DNNNodes; if (objTab.TabID == intStartTabId) { - //is this the starting tab - if ((intNavNodeOptions & (int) NavNodeOptions.IncludeParent) != 0) + // is this the starting tab + if ((intNavNodeOptions & (int)NavNodeOptions.IncludeParent) != 0) { - //if we are including parent, make sure there is one, then add + // if we are including parent, make sure there is one, then add if (objTabLookup[objTab.ParentId] != null) { - AddNode((TabInfo) objTabLookup[objTab.ParentId], objParentNodes, objBreadCrumbs, objPortalSettings, eToolTips, nodesLookup); + AddNode((TabInfo)objTabLookup[objTab.ParentId], objParentNodes, objBreadCrumbs, objPortalSettings, eToolTips, nodesLookup); if (nodesLookup.TryGetValue(objTab.ParentId.ToString(), out objParentNode)) { objParentNodes = objParentNode.DNNNodes; } } } - if ((intNavNodeOptions & (int) NavNodeOptions.IncludeSelf) != 0) + + if ((intNavNodeOptions & (int)NavNodeOptions.IncludeSelf) != 0) { - //if we are including our self (starting tab) then add + // if we are including our self (starting tab) then add AddNode(objTab, objParentNodes, objBreadCrumbs, objPortalSettings, eToolTips, nodesLookup); } } - else if (((intNavNodeOptions & (int) NavNodeOptions.IncludeSiblings) != 0) && IsTabSibling(objTab, intStartTabId, objTabLookup)) + else if (((intNavNodeOptions & (int)NavNodeOptions.IncludeSiblings) != 0) && IsTabSibling(objTab, intStartTabId, objTabLookup)) { - //is this a sibling of the starting node, and we are including siblings, then add it + // is this a sibling of the starting node, and we are including siblings, then add it AddNode(objTab, objParentNodes, objBreadCrumbs, objPortalSettings, eToolTips, nodesLookup); } else { - if (blnParentFound) //if tabs parent already in hierarchy (as is the case when we are sending down more than 1 level) + if (blnParentFound) // if tabs parent already in hierarchy (as is the case when we are sending down more than 1 level) { - //parent will be found for siblings. Check to see if we want them, if we don't make sure tab is not a sibling - if (((intNavNodeOptions & (int) NavNodeOptions.IncludeSiblings) != 0) || IsTabSibling(objTab, intStartTabId, objTabLookup) == false) + // parent will be found for siblings. Check to see if we want them, if we don't make sure tab is not a sibling + if (((intNavNodeOptions & (int)NavNodeOptions.IncludeSiblings) != 0) || IsTabSibling(objTab, intStartTabId, objTabLookup) == false) { - //determine if tab should be included or marked as pending - bool blnPOD = (intNavNodeOptions & (int) NavNodeOptions.MarkPendingNodes) != 0; + // determine if tab should be included or marked as pending + bool blnPOD = (intNavNodeOptions & (int)NavNodeOptions.MarkPendingNodes) != 0; if (IsTabPending(objTab, objParentNode, objRootNode, intDepth, objBreadCrumbs, intLastBreadCrumbId, blnPOD)) { if (blnPOD) { - objParentNode.HasNodes = true; //mark it as a pending node + objParentNode.HasNodes = true; // mark it as a pending node } } else @@ -366,45 +372,26 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob } } } - else if ((intNavNodeOptions & (int) NavNodeOptions.IncludeSelf) == 0 && objTab.ParentId == intStartTabId) + else if ((intNavNodeOptions & (int)NavNodeOptions.IncludeSelf) == 0 && objTab.ParentId == intStartTabId) { - //if not including self and parent is the start id then add + // if not including self and parent is the start id then add AddNode(objTab, objParentNodes, objBreadCrumbs, objPortalSettings, eToolTips, nodesLookup); } } } - } - - #endregion - - #region Public Shared Methods - - public static bool CanShowTab(TabInfo objTab, bool isAdminMode, bool showDisabled) - { - return CanShowTab(objTab, isAdminMode, showDisabled, false); - } - - public static bool CanShowTab(TabInfo tab, bool isAdminMode, bool showDisabled, bool showHidden) - { - //if tab is visible, not deleted, not expired (or admin), and user has permission to see it... - return ((tab.IsVisible || showHidden) && tab.HasAVisibleVersion && !tab.IsDeleted && - (!tab.DisableLink || showDisabled) && - (((tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate) && - (tab.EndDate > DateTime.Now || tab.EndDate == Null.NullDate)) || isAdminMode) && - TabPermissionController.CanNavigateToPage(tab)); - } + } /// ----------------------------------------------------------------------------- /// - /// Allows for DNNNode object to be easily obtained based off of passed in ID + /// Allows for DNNNode object to be easily obtained based off of passed in ID. /// - /// NodeID to retrieve - /// Namespace for node collection (usually control's ClientID) - /// Root Action object used in searching - /// ActionControl to base actions off of - /// DNNNode + /// NodeID to retrieve. + /// Namespace for node collection (usually control's ClientID). + /// Root Action object used in searching. + /// ActionControl to base actions off of. + /// DNNNode. /// - /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider + /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider. /// /// ----------------------------------------------------------------------------- public static DNNNode GetActionNode(string strID, string strNamespace, ModuleAction objActionRoot, Control objControl) @@ -420,10 +407,10 @@ public static DNNNode GetActionNode(string strID, string strNamespace, ModuleAct /// ----------------------------------------------------------------------------- /// /// This function provides a central location to obtain a generic node collection of the actions associated - /// to a module based off of the current user's context + /// to a module based off of the current user's context. /// - /// Root module action - /// ActionControl to base actions off of + /// Root module action. + /// ActionControl to base actions off of. /// /// /// @@ -435,12 +422,12 @@ public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, Contr /// ----------------------------------------------------------------------------- /// - /// This function provides a central location to obtain a generic node collection of the actions associated - /// to a module based off of the current user's context + /// This function provides a central location to obtain a generic node collection of the actions associated + /// to a module based off of the current user's context. /// - /// Root module action - /// ActionControl to base actions off of - /// How many levels deep should be populated + /// Root module action. + /// ActionControl to base actions off of. + /// How many levels deep should be populated. /// /// /// @@ -465,18 +452,19 @@ public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, Contr AddChildActions(objActionRoot, objRoot, objRoot.ParentNode, objActionControl, intDepth); } } + return objCol; } /// ----------------------------------------------------------------------------- /// - /// This function provides a central location to obtain a generic node collection of the actions associated - /// to a module based off of the current user's context + /// This function provides a central location to obtain a generic node collection of the actions associated + /// to a module based off of the current user's context. /// - /// Root module action - /// Root node on which to populate children - /// ActionControl to base actions off of - /// How many levels deep should be populated + /// Root module action. + /// Root node on which to populate children. + /// ActionControl to base actions off of. + /// How many levels deep should be populated. /// /// /// @@ -489,18 +477,19 @@ public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, DNNNo { AddChildActions(objActionRoot, objRootNode, objRootNode, objActionControl, intDepth); } + return objCol; } /// ----------------------------------------------------------------------------- /// - /// Allows for DNNNode object to be easily obtained based off of passed in ID + /// Allows for DNNNode object to be easily obtained based off of passed in ID. /// - /// NodeID to retrieve - /// Namespace for node collection (usually control's ClientID) - /// DNNNode + /// NodeID to retrieve. + /// Namespace for node collection (usually control's ClientID). + /// DNNNode. /// - /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider + /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider. /// /// ----------------------------------------------------------------------------- public static DNNNode GetNavigationNode(string strID, string strNamespace) @@ -516,12 +505,12 @@ public static DNNNode GetNavigationNode(string strID, string strNamespace) /// ----------------------------------------------------------------------------- /// /// This function provides a central location to obtain a generic node collection of the pages/tabs included in - /// the current context's (user) navigation hierarchy + /// the current context's (user) navigation hierarchy. /// - /// Namespace (typically control's ClientID) of node collection to create - /// Collection of DNNNodes + /// Namespace (typically control's ClientID) of node collection to create. + /// Collection of DNNNodes. /// - /// Returns all navigation nodes for a given user + /// Returns all navigation nodes for a given user. /// /// ----------------------------------------------------------------------------- public static DNNNodeCollection GetNavigationNodes(string strNamespace) @@ -532,16 +521,16 @@ public static DNNNodeCollection GetNavigationNodes(string strNamespace) /// ----------------------------------------------------------------------------- /// /// This function provides a central location to obtain a generic node collection of the pages/tabs included in - /// the current context's (user) navigation hierarchy + /// the current context's (user) navigation hierarchy. /// - /// Namespace (typically control's ClientID) of node collection to create - /// Enumerator to determine what text to display in the tooltips - /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD) - /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD) - /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent) - /// Collection of DNNNodes + /// Namespace (typically control's ClientID) of node collection to create. + /// Enumerator to determine what text to display in the tooltips. + /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD). + /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD). + /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent). + /// Collection of DNNNodes. /// - /// Returns a subset of navigation nodes based off of passed in starting node id and depth + /// Returns a subset of navigation nodes based off of passed in starting node id and depth. /// /// ----------------------------------------------------------------------------- public static DNNNodeCollection GetNavigationNodes(string strNamespace, ToolTipSource eToolTips, int intStartTabId, int intDepth, int intNavNodeOptions) @@ -553,16 +542,16 @@ public static DNNNodeCollection GetNavigationNodes(string strNamespace, ToolTipS /// ----------------------------------------------------------------------------- /// /// This function provides a central location to obtain a generic node collection of the pages/tabs included in - /// the current context's (user) navigation hierarchy + /// the current context's (user) navigation hierarchy. /// - /// Node in which to add children to - /// Enumerator to determine what text to display in the tooltips - /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD) - /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD) - /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent) - /// Collection of DNNNodes + /// Node in which to add children to. + /// Enumerator to determine what text to display in the tooltips. + /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD). + /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD). + /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent). + /// Collection of DNNNodes. /// - /// Returns a subset of navigation nodes based off of passed in starting node id and depth + /// Returns a subset of navigation nodes based off of passed in starting node id and depth. /// /// ----------------------------------------------------------------------------- public static DNNNodeCollection GetNavigationNodes(DNNNode objRootNode, ToolTipSource eToolTips, int intStartTabId, int intDepth, int intNavNodeOptions) @@ -579,6 +568,7 @@ public static DNNNodeCollection GetNavigationNodes(DNNNode objRootNode, ToolTipS objBreadCrumbs.Add(tabInfo.TabID, 1); intLastBreadCrumbId = tabInfo.TabID; } + var portalTabs = TabController.GetTabsBySortOrder(objPortalSettings.PortalId, objPortalSettings.CultureCode, true); var hostTabs = TabController.GetTabsBySortOrder(Null.NullInteger, Localization.SystemLocale, true); @@ -594,7 +584,7 @@ public static DNNNodeCollection GetNavigationNodes(DNNNode objRootNode, ToolTipS objTabLookup.Add(objTab.TabID, objTab); } - //convert dnn nodes to dictionary. + // convert dnn nodes to dictionary. var nodesDict = new Dictionary(); SaveDnnNodesToDictionary(nodesDict, objRootNodes); @@ -625,8 +615,6 @@ private static void SaveDnnNodesToDictionary(IDictionary nodesD SaveDnnNodesToDictionary(nodesDict, node.DNNNodes); } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs b/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs index 6fed05e5ba5..81262dac75d 100644 --- a/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs +++ b/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs @@ -1,37 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI.HtmlControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.UI.ControlPanels; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins.Controls { - public class ControlPanel : SkinObjectBase - { - public bool IsDockable { get; set; } + using System; + using System.Web.UI.HtmlControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.UI.ControlPanels; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + + public class ControlPanel : SkinObjectBase + { + public bool IsDockable { get; set; } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); + protected override void OnInit(EventArgs e) + { + base.OnInit(e); - if (Request.QueryString["dnnprintmode"] != "true" && !UrlUtils.InPopUp()) - { - var objControlPanel = ControlUtilities.LoadControl(this, Host.ControlPanel); - var objForm = (HtmlForm)Page.FindControl("Form"); + if (this.Request.QueryString["dnnprintmode"] != "true" && !UrlUtils.InPopUp()) + { + var objControlPanel = ControlUtilities.LoadControl(this, Host.ControlPanel); + var objForm = (HtmlForm)this.Page.FindControl("Form"); - if(objControlPanel.IncludeInControlHierarchy) + if (objControlPanel.IncludeInControlHierarchy) { - objControlPanel.IsDockable = IsDockable; - if (!Host.ControlPanel.EndsWith("controlbar.ascx", StringComparison.InvariantCultureIgnoreCase)) - Controls.Add(objControlPanel); + objControlPanel.IsDockable = this.IsDockable; + if (!Host.ControlPanel.EndsWith("controlbar.ascx", StringComparison.InvariantCultureIgnoreCase)) + { + this.Controls.Add(objControlPanel); + } else { if (objForm != null) @@ -40,14 +42,14 @@ protected override void OnInit(EventArgs e) } else { - Page.Controls.AddAt(0, objControlPanel); + this.Page.Controls.AddAt(0, objControlPanel); } } - //register admin.css - ClientResourceManager.RegisterAdminStylesheet(Page, Globals.HostPath + "admin.css"); + // register admin.css + ClientResourceManager.RegisterAdminStylesheet(this.Page, Globals.HostPath + "admin.css"); } - } - } - } + } + } + } } diff --git a/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs b/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs index 14e13f6a69e..d2087f7a31d 100644 --- a/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs +++ b/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs @@ -1,39 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Globalization; -using System.IO; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Collections.Specialized; + using System.Globalization; + using System.IO; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Tokens; + public class LanguageTokenReplace : TokenReplace { - //see http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=6505 + // see http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=6505 public LanguageTokenReplace() : base(Scope.NoSettings) { - UseObjectLessExpression = true; - PropertySource[ObjectLessToken] = new LanguagePropertyAccess(this, Globals.GetPortalSettings()); + this.UseObjectLessExpression = true; + this.PropertySource[ObjectLessToken] = new LanguagePropertyAccess(this, Globals.GetPortalSettings()); } public string resourceFile { get; set; } @@ -41,38 +36,44 @@ public LanguageTokenReplace() public class LanguagePropertyAccess : IPropertyAccess { + public LanguageTokenReplace objParent; private const string FlagIconPhysicalLocation = @"~\images\Flags"; private const string NonExistingFlagIconFileName = "none.gif"; private readonly PortalSettings objPortal; - public LanguageTokenReplace objParent; public LanguagePropertyAccess(LanguageTokenReplace parent, PortalSettings settings) { - objPortal = settings; - objParent = parent; + this.objPortal = settings; + this.objParent = parent; } - #region IPropertyAccess Members + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope CurrentScope, ref bool PropertyNotFound) { switch (propertyName.ToLowerInvariant()) { case "url": - return NewUrl(objParent.Language); + return this.NewUrl(this.objParent.Language); case "flagsrc": - var mappedGifFile = PathUtils.Instance.MapPath($@"{FlagIconPhysicalLocation}\{objParent.Language}.gif"); - return File.Exists(mappedGifFile) ? $"/{objParent.Language}.gif" : $@"/{NonExistingFlagIconFileName}"; + var mappedGifFile = PathUtils.Instance.MapPath($@"{FlagIconPhysicalLocation}\{this.objParent.Language}.gif"); + return File.Exists(mappedGifFile) ? $"/{this.objParent.Language}.gif" : $@"/{NonExistingFlagIconFileName}"; case "selected": - return (objParent.Language == CultureInfo.CurrentCulture.Name).ToString(); + return (this.objParent.Language == CultureInfo.CurrentCulture.Name).ToString(); case "label": - return Localization.GetString("Label", objParent.resourceFile); + return Localization.GetString("Label", this.objParent.resourceFile); case "i": return Globals.ResolveUrl("~/images/Flags"); case "p": - return Globals.ResolveUrl(PathUtils.Instance.RemoveTrailingSlash(objPortal.HomeDirectory)); + return Globals.ResolveUrl(PathUtils.Instance.RemoveTrailingSlash(this.objPortal.HomeDirectory)); case "s": - return Globals.ResolveUrl(PathUtils.Instance.RemoveTrailingSlash(objPortal.ActiveTab.SkinPath)); + return Globals.ResolveUrl(PathUtils.Instance.RemoveTrailingSlash(this.objPortal.ActiveTab.SkinPath)); case "g": return Globals.ResolveUrl("~/portals/" + Globals.glbHostSkinFolder); default: @@ -81,32 +82,19 @@ public string GetProperty(string propertyName, string format, CultureInfo format } } - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - - #endregion - - #region Private Methods - - /// /// getQSParams builds up a new querystring. This is necessary /// in order to prep for navigateUrl. /// we don't ever want a tabid, a ctl and a language parameter in the qs /// also, the portalid param is not allowed when the tab is a supertab - /// (because NavigateUrl adds the portalId param to the qs) + /// (because NavigateUrl adds the portalId param to the qs). /// - /// Language to switch into + /// Language to switch into. /// /// private string[] GetQsParams(string newLanguage, bool isLocalized) { - string returnValue = ""; + string returnValue = string.Empty; NameValueCollection queryStringCollection = HttpContext.Current.Request.QueryString; var rawQueryStringCollection = HttpUtility.ParseQueryString(new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl).Query); @@ -122,10 +110,10 @@ private string[] GetQsParams(string newLanguage, bool isLocalized) { case "tabid": case "ctl": - case "language": //skip parameter + case "language": // skip parameter break; case "mid": - case "moduleid": //start of patch (Manzoni Fausto) gemini 14205 + case "moduleid": // start of patch (Manzoni Fausto) gemini 14205 if (isLocalized) { string ModuleIdKey = arrKeys[i].ToLowerInvariant(); @@ -141,56 +129,59 @@ private string[] GetQsParams(string newLanguage, bool isLocalized) { returnValue += "&"; } + returnValue += ModuleIdKey + "=" + localizedModule.ModuleID; } } + break; default: - if ((arrKeys[i].ToLowerInvariant() == "portalid") && objPortal.ActiveTab.IsSuperTab) + if ((arrKeys[i].ToLowerInvariant() == "portalid") && this.objPortal.ActiveTab.IsSuperTab) { - //skip parameter - //navigateURL adds portalid to querystring if tab is superTab + // skip parameter + // navigateURL adds portalid to querystring if tab is superTab } else { if (!string.IsNullOrEmpty(rawQueryStringCollection.Get(arrKeys[i]))) { - //skip parameter as it is part of a querystring param that has the following form + // skip parameter as it is part of a querystring param that has the following form // [friendlyURL]/?param=value // gemini 25516 - if (!DotNetNuke.Entities.Host.Host.UseFriendlyUrls) { - if (!String.IsNullOrEmpty(returnValue)) + if (!string.IsNullOrEmpty(returnValue)) { returnValue += "&"; } + returnValue += arrKeys[i] + "=" + HttpUtility.UrlEncode(rawQueryStringCollection.Get(arrKeys[i])); } - - } + // on localised pages most of the module parameters have no sense and generate duplicate urls for the same content // because we are on a other tab with other modules (example : /en-US/news/articleid/1) - else //if (!isLocalized) -- this applies only when a portal "Localized Content" is enabled. + else // if (!isLocalized) -- this applies only when a portal "Localized Content" is enabled. { string[] arrValues = queryStringCollection.GetValues(i); if (arrValues != null) { for (int j = 0; j <= arrValues.GetUpperBound(0); j++) { - if (!String.IsNullOrEmpty(returnValue)) + if (!string.IsNullOrEmpty(returnValue)) { returnValue += "&"; } + var qsv = arrKeys[i]; - qsv = qsv.Replace("\"", ""); - qsv = qsv.Replace("'", ""); + qsv = qsv.Replace("\"", string.Empty); + qsv = qsv.Replace("'", string.Empty); returnValue += qsv + "=" + HttpUtility.UrlEncode(arrValues[j]); } } } } + break; } } @@ -198,38 +189,39 @@ private string[] GetQsParams(string newLanguage, bool isLocalized) if (!settings.ContentLocalizationEnabled && LocaleController.Instance.GetLocales(settings.PortalId).Count > 1 && !settings.EnableUrlLanguage) { - //because useLanguageInUrl is false, navigateUrl won't add a language param, so we need to do that ourselves - if (returnValue != "") + // because useLanguageInUrl is false, navigateUrl won't add a language param, so we need to do that ourselves + if (returnValue != string.Empty) { returnValue += "&"; } + returnValue += "language=" + newLanguage.ToLowerInvariant(); } - //return the new querystring as a string array + // return the new querystring as a string array return returnValue.Split('&'); } /// /// newUrl returns the new URL based on the new language. - /// Basically it is just a call to NavigateUrl, with stripped qs parameters + /// Basically it is just a call to NavigateUrl, with stripped qs parameters. /// /// private string NewUrl(string newLanguage) { var newLocale = LocaleController.Instance.GetLocale(newLanguage); - //Ensure that the current ActiveTab is the culture of the new language - var tabId = objPortal.ActiveTab.TabID; + // Ensure that the current ActiveTab is the culture of the new language + var tabId = this.objPortal.ActiveTab.TabID; var islocalized = false; - var localizedTab = TabController.Instance.GetTabByCulture(tabId, objPortal.PortalId, newLocale); + var localizedTab = TabController.Instance.GetTabByCulture(tabId, this.objPortal.PortalId, newLocale); if (localizedTab != null) { islocalized = true; if (localizedTab.IsDeleted || !TabPermissionController.CanViewPage(localizedTab)) { - var localizedPortal = PortalController.Instance.GetPortal(objPortal.PortalId, newLocale.Code); + var localizedPortal = PortalController.Instance.GetPortal(this.objPortal.PortalId, newLocale.Code); tabId = localizedPortal.HomeTabId; } else @@ -238,25 +230,26 @@ private string NewUrl(string newLanguage) switch (localizedTab.TabType) { case TabType.Normal: - //normal tab + // normal tab tabId = localizedTab.TabID; break; case TabType.Tab: - //alternate tab url + // alternate tab url fullurl = TestableGlobals.Instance.NavigateURL(Convert.ToInt32(localizedTab.Url)); break; case TabType.File: - //file url + // file url fullurl = TestableGlobals.Instance.LinkClick(localizedTab.Url, localizedTab.TabID, Null.NullInteger); break; case TabType.Url: - //external url + // external url fullurl = localizedTab.Url; break; } + if (!string.IsNullOrEmpty(fullurl)) { - return GetCleanUrl(fullurl); + return this.GetCleanUrl(fullurl); } } } @@ -271,15 +264,18 @@ private string NewUrl(string newLanguage) var queryParams = HttpUtility.ParseQueryString(new Uri(string.Concat(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority), HttpContext.Current.Request.RawUrl)).Query); queryParams.Remove("returnurl"); var queryString = queryParams.ToString(); - if (queryString.Length > 0) rawQueryString = string.Concat("?", queryString); + if (queryString.Length > 0) + { + rawQueryString = string.Concat("?", queryString); + } } var controlKey = HttpContext.Current.Request.QueryString["ctl"]; - var queryStrings = GetQsParams(newLocale.Code, islocalized); - var isSuperTab = objPortal.ActiveTab.IsSuperTab; - var url = $"{TestableGlobals.Instance.NavigateURL(tabId, isSuperTab, objPortal, controlKey, newLanguage, queryStrings)}{rawQueryString}"; + var queryStrings = this.GetQsParams(newLocale.Code, islocalized); + var isSuperTab = this.objPortal.ActiveTab.IsSuperTab; + var url = $"{TestableGlobals.Instance.NavigateURL(tabId, isSuperTab, this.objPortal, controlKey, newLanguage, queryStrings)}{rawQueryString}"; - return GetCleanUrl(url); + return this.GetCleanUrl(url); } private string GetCleanUrl(string url) @@ -292,8 +288,5 @@ private string GetCleanUrl(string url) return url; } - - #endregion - } } diff --git a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs index 23bb0964a99..763d6372de9 100644 --- a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs +++ b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs @@ -1,48 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { - + using System; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + /// /// public class ModuleMessage : SkinObjectBase - { - #region ModuleMessageType enum - + { + protected Panel dnnSkinMessage; + protected Label lblHeading; + protected Label lblMessage; + public enum ModuleMessageType { GreenSuccess, YellowWarning, RedError, - BlueInfo - } - - #endregion - #region "Private Members" - - protected Panel dnnSkinMessage; - protected Label lblHeading; - protected Label lblMessage; - protected Control scrollScript; - - #endregion - - #region "Public Members" - + BlueInfo, + } + protected Control scrollScript; + public string Text { get; set; } public string Heading { get; set; } @@ -51,84 +36,79 @@ public enum ModuleMessageType public string IconImage { get; set; } - /// - /// Check this message is shown as page message or module message. - /// - public bool IsModuleMessage - { - get - { - return this.Parent.ID == "MessagePlaceHolder"; - } - } - - #endregion - - #region "Protected Methods" - - /// - /// The Page_Load server event handler on this page is used - /// to populate the role information for the page - /// - protected override void OnLoad(EventArgs e) + /// + /// Gets a value indicating whether check this message is shown as page message or module message. + /// + public bool IsModuleMessage + { + get + { + return this.Parent.ID == "MessagePlaceHolder"; + } + } + + /// + /// The Page_Load server event handler on this page is used + /// to populate the role information for the page. + /// + protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { - var strMessage = ""; - - //check to see if a url - //was passed in for an icon - if (!String.IsNullOrEmpty(IconImage)) + var strMessage = string.Empty; + + // check to see if a url + // was passed in for an icon + if (!string.IsNullOrEmpty(this.IconImage)) { - strMessage += Text; - dnnSkinMessage.CssClass = "dnnFormMessage dnnFormWarning"; + strMessage += this.Text; + this.dnnSkinMessage.CssClass = "dnnFormMessage dnnFormWarning"; } else { - switch (IconType) + switch (this.IconType) { case ModuleMessageType.GreenSuccess: - strMessage += Text; - dnnSkinMessage.CssClass = "dnnFormMessage dnnFormSuccess"; + strMessage += this.Text; + this.dnnSkinMessage.CssClass = "dnnFormMessage dnnFormSuccess"; break; case ModuleMessageType.YellowWarning: - strMessage += Text; - dnnSkinMessage.CssClass = "dnnFormMessage dnnFormWarning"; + strMessage += this.Text; + this.dnnSkinMessage.CssClass = "dnnFormMessage dnnFormWarning"; break; case ModuleMessageType.BlueInfo: - strMessage += Text; - dnnSkinMessage.CssClass = "dnnFormMessage dnnFormInfo"; + strMessage += this.Text; + this.dnnSkinMessage.CssClass = "dnnFormMessage dnnFormInfo"; break; case ModuleMessageType.RedError: - strMessage += Text; - dnnSkinMessage.CssClass = "dnnFormMessage dnnFormValidationSummary"; + strMessage += this.Text; + this.dnnSkinMessage.CssClass = "dnnFormMessage dnnFormValidationSummary"; break; } } - lblMessage.Text = strMessage; + + this.lblMessage.Text = strMessage; - if (!String.IsNullOrEmpty(Heading)) + if (!string.IsNullOrEmpty(this.Heading)) { - lblHeading.Visible = true; - lblHeading.Text = Heading; + this.lblHeading.Visible = true; + this.lblHeading.Text = this.Heading; } } - catch (Exception exc) //Control failed to load + catch (Exception exc) // Control failed to load { Exceptions.ProcessModuleLoadException(this, exc, false); } } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); - //set the scroll js only shown for module message and in postback mode. - scrollScript.Visible = IsPostBack && IsModuleMessage; - } - - #endregion + // set the scroll js only shown for module message and in postback mode. + this.scrollScript.Visible = this.IsPostBack && this.IsModuleMessage; + } } } diff --git a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs index 3d517762f3c..7d654302961 100644 --- a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs +++ b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.Skins.Controls @@ -34,115 +29,116 @@ namespace DotNetNuke.UI.Skins.Controls [ToolboxData("<{0}:SkinsEditControl runat=server>")] public class SkinsEditControl : EditControl, IPostBackEventHandler { - private string _AddedItem = Null.NullString; - - #region "Constructors" - + private string _AddedItem = Null.NullString; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a SkinsEditControl + /// + /// Initializes a new instance of the class. + /// Constructs a SkinsEditControl. /// /// ----------------------------------------------------------------------------- public SkinsEditControl() { - } - + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a SkinsEditControl + /// + /// Initializes a new instance of the class. + /// Constructs a SkinsEditControl. /// - /// The type of the property + /// The type of the property. /// ----------------------------------------------------------------------------- public SkinsEditControl(string type) { - SystemType = type; - } - - #endregion - - #region "Protected Properties" - + this.SystemType = type; + } + /// ----------------------------------------------------------------------------- /// - /// DictionaryValue returns the Dictionary(Of Integer, String) representation of the Value + /// Gets or sets dictionaryValue returns the Dictionary(Of Integer, String) representation of the Value. /// - /// A Dictionary(Of Integer, String) representing the Value + /// A Dictionary(Of Integer, String) representing the Value. /// ----------------------------------------------------------------------------- protected Dictionary DictionaryValue { get { - return Value as Dictionary; + return this.Value as Dictionary; } + set { - Value = value; + this.Value = value; } } /// ----------------------------------------------------------------------------- /// - /// OldDictionaryValue returns the Dictionary(Of Integer, String) representation of the OldValue + /// Gets or sets oldDictionaryValue returns the Dictionary(Of Integer, String) representation of the OldValue. /// - /// A Dictionary(Of Integer, String) representing the OldValue + /// A Dictionary(Of Integer, String) representing the OldValue. /// ----------------------------------------------------------------------------- protected Dictionary OldDictionaryValue { get { - return OldValue as Dictionary; + return this.OldValue as Dictionary; } + set { - OldValue = value; + this.OldValue = value; } } /// ----------------------------------------------------------------------------- /// - /// OldStringValue returns the String representation of the OldValue + /// Gets oldStringValue returns the String representation of the OldValue. /// - /// A String representing the OldValue + /// A String representing the OldValue. /// ----------------------------------------------------------------------------- protected string OldStringValue { get { string strValue = Null.NullString; - if (OldDictionaryValue != null) + if (this.OldDictionaryValue != null) { - foreach (string Skin in OldDictionaryValue.Values) + foreach (string Skin in this.OldDictionaryValue.Values) { strValue += Skin + ","; } } + return strValue; } } /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets stringValue is the value of the control expressed as a String. /// - /// A string representing the Value + /// A string representing the Value. /// ----------------------------------------------------------------------------- protected override string StringValue { get { string strValue = Null.NullString; - if (DictionaryValue != null) + if (this.DictionaryValue != null) { - foreach (string Skin in DictionaryValue.Values) + foreach (string Skin in this.DictionaryValue.Values) { strValue += Skin + ","; } } + return strValue; } + set { - Value = value; + this.Value = value; } } @@ -150,156 +146,182 @@ protected string AddedItem { get { - return _AddedItem; + return this._AddedItem; } + set { - _AddedItem = value; + this._AddedItem = value; } - } - - #region IPostBackEventHandler Members - + } + public void RaisePostBackEvent(string eventArgument) { PropertyEditorEventArgs args; switch (eventArgument.Substring(0, 3)) { case "Del": - args = new PropertyEditorEventArgs(Name); - args.Value = DictionaryValue; - args.OldValue = OldDictionaryValue; + args = new PropertyEditorEventArgs(this.Name); + args.Value = this.DictionaryValue; + args.OldValue = this.OldDictionaryValue; args.Key = int.Parse(eventArgument.Substring(7)); args.Changed = true; - base.OnItemDeleted(args); + this.OnItemDeleted(args); break; case "Add": - args = new PropertyEditorEventArgs(Name); - args.Value = AddedItem; - args.StringValue = AddedItem; + args = new PropertyEditorEventArgs(this.Name); + args.Value = this.AddedItem; + args.StringValue = this.AddedItem; args.Changed = true; - base.OnItemAdded(args); + this.OnItemAdded(args); break; } + } + + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + bool dataChanged = false; + string postedValue; + var newDictionaryValue = new Dictionary(); + foreach (KeyValuePair kvp in this.DictionaryValue) + { + postedValue = postCollection[this.UniqueID + "_skin" + kvp.Key]; + if (kvp.Value.Equals(postedValue)) + { + newDictionaryValue[kvp.Key] = kvp.Value; + } + else + { + newDictionaryValue[kvp.Key] = postedValue; + dataChanged = true; + } + } + + postedValue = postCollection[this.UniqueID + "_skinnew"]; + if (!string.IsNullOrEmpty(postedValue)) + { + this.AddedItem = postedValue; + } + + this.DictionaryValue = newDictionaryValue; + return dataChanged; } - - #endregion - - #endregion - - #region "Protected Methods" - + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = DictionaryValue; - args.OldValue = OldDictionaryValue; - args.StringValue = ""; + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.DictionaryValue; + args.OldValue = this.OldDictionaryValue; + args.StringValue = string.Empty; args.Changed = true; - base.OnValueChanged(args); + this.OnValueChanged(args); } /// ----------------------------------------------------------------------------- /// - /// OnPreRender runs just before the control is due to be rendered + /// OnPreRender runs just before the control is due to be rendered. /// /// ----------------------------------------------------------------------------- protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - //Register control for PostBack - Page.RegisterRequiresPostBack(this); + // Register control for PostBack + this.Page.RegisterRequiresPostBack(this); } /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { int length = Null.NullInteger; - if ((CustomAttributes != null)) + if (this.CustomAttributes != null) { - foreach (Attribute attribute in CustomAttributes) + foreach (Attribute attribute in this.CustomAttributes) { if (attribute is MaxLengthAttribute) { - var lengthAtt = (MaxLengthAttribute) attribute; + var lengthAtt = (MaxLengthAttribute)attribute; length = lengthAtt.Length; break; } } } - if (DictionaryValue != null) + + if (this.DictionaryValue != null) { - foreach (KeyValuePair kvp in DictionaryValue) + foreach (KeyValuePair kvp in this.DictionaryValue) { - //Render Hyperlink - writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, "Delete_" + kvp.Key, false)); + // Render Hyperlink + writer.AddAttribute(HtmlTextWriterAttribute.Href, this.Page.ClientScript.GetPostBackClientHyperlink(this, "Delete_" + kvp.Key, false)); writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "javascript:return confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteItem")) + "');"); - writer.AddAttribute(HtmlTextWriterAttribute.Title, Localization.GetString("cmdDelete", LocalResourceFile)); + writer.AddAttribute(HtmlTextWriterAttribute.Title, Localization.GetString("cmdDelete", this.LocalResourceFile)); writer.RenderBeginTag(HtmlTextWriterTag.A); - //Render Image + // Render Image writer.AddAttribute(HtmlTextWriterAttribute.Src, IconController.IconURL("Delete")); writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); writer.RenderBeginTag(HtmlTextWriterTag.Img); - //Render end of Image + // Render end of Image writer.RenderEndTag(); - //Render end of Hyperlink + // Render end of Hyperlink writer.RenderEndTag(); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Value, kvp.Value); if (length > Null.NullInteger) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID + "_skin" + kvp.Key); + + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_skin" + kvp.Key); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); writer.WriteBreak(); } + writer.WriteBreak(); - //Create Add Row - //Render Hyperlink - writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, "Add", false)); - writer.AddAttribute(HtmlTextWriterAttribute.Title, Localization.GetString("cmdAdd", LocalResourceFile)); + // Create Add Row + // Render Hyperlink + writer.AddAttribute(HtmlTextWriterAttribute.Href, this.Page.ClientScript.GetPostBackClientHyperlink(this, "Add", false)); + writer.AddAttribute(HtmlTextWriterAttribute.Title, Localization.GetString("cmdAdd", this.LocalResourceFile)); writer.RenderBeginTag(HtmlTextWriterTag.A); - //Render Image + // Render Image writer.AddAttribute(HtmlTextWriterAttribute.Src, IconController.IconURL("Add")); writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); writer.RenderBeginTag(HtmlTextWriterTag.Img); - //Render end of Image + // Render end of Image writer.RenderEndTag(); - //Render end of Hyperlink + // Render end of Hyperlink writer.RenderEndTag(); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); if (length > Null.NullInteger) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID + "_skinnew"); + + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_skinnew"); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); writer.WriteBreak(); @@ -308,52 +330,23 @@ protected override void RenderEditMode(HtmlTextWriter writer) /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderViewMode(HtmlTextWriter writer) { - if (DictionaryValue != null) + if (this.DictionaryValue != null) { - foreach (KeyValuePair kvp in DictionaryValue) + foreach (KeyValuePair kvp in this.DictionaryValue) { - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(kvp.Value); writer.RenderEndTag(); writer.WriteBreak(); } } - } - - #endregion - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - bool dataChanged = false; - string postedValue; - var newDictionaryValue = new Dictionary(); - foreach (KeyValuePair kvp in DictionaryValue) - { - postedValue = postCollection[UniqueID + "_skin" + kvp.Key]; - if (kvp.Value.Equals(postedValue)) - { - newDictionaryValue[kvp.Key] = kvp.Value; - } - else - { - newDictionaryValue[kvp.Key] = postedValue; - dataChanged = true; - } - } - postedValue = postCollection[UniqueID + "_skinnew"]; - if (!string.IsNullOrEmpty(postedValue)) - { - AddedItem = postedValue; - } - DictionaryValue = newDictionaryValue; - return dataChanged; - } + } } } diff --git a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventArgs.cs b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventArgs.cs index c6c8d2953c0..e2b0fa6a1ac 100644 --- a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventArgs.cs +++ b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventArgs.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.EventListeners { - ///----------------------------------------------------------------------------- + using System; + + /// ----------------------------------------------------------------------------- /// - /// SkinEventArgs provides a custom EventARgs class for Skin Events + /// SkinEventArgs provides a custom EventARgs class for Skin Events. /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public class SkinEventArgs : EventArgs { private readonly Skin _Skin; public SkinEventArgs(Skin skin) { - _Skin = skin; + this._Skin = skin; } public Skin Skin { get { - return _Skin; + return this._Skin; } } } diff --git a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs index 71361be7d5c..9fb2fa648ae 100644 --- a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs +++ b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins.EventListeners { /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs index 76a1da058fe..4e4f10cc2c8 100644 --- a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs +++ b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins.EventListeners { public class SkinEventListener { public SkinEventListener(SkinEventType type, SkinEventHandler e) { - EventType = type; - SkinEvent = e; + this.EventType = type; + this.SkinEvent = e; } public SkinEventType EventType { get; private set; } + public SkinEventHandler SkinEvent { get; private set; } } } diff --git a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventType.cs b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventType.cs index 664d55b26d3..d643d449173 100644 --- a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventType.cs +++ b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventType.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins.EventListeners { - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// SkinEventType provides a custom enum for skin event types + /// SkinEventType provides a custom enum for skin event types. /// /// - ///----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public enum SkinEventType { OnSkinInit, OnSkinLoad, OnSkinPreRender, - OnSkinUnLoad + OnSkinUnLoad, } } diff --git a/DNN Platform/Library/UI/Skins/ISkinControl.cs b/DNN Platform/Library/UI/Skins/ISkinControl.cs index e096d2b1948..1c5ac112767 100644 --- a/DNN Platform/Library/UI/Skins/ISkinControl.cs +++ b/DNN Platform/Library/UI/Skins/ISkinControl.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using DotNetNuke.UI.Modules; + public interface ISkinControl { IModuleControl ModuleControl { get; set; } diff --git a/DNN Platform/Library/UI/Skins/InstalledSkinInfo.cs b/DNN Platform/Library/UI/Skins/InstalledSkinInfo.cs index 360a4b47862..5753bc0f18e 100644 --- a/DNN Platform/Library/UI/Skins/InstalledSkinInfo.cs +++ b/DNN Platform/Library/UI/Skins/InstalledSkinInfo.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System.Xml; + public class InstalledSkinInfo { public bool InUse { get; set; } @@ -20,13 +15,13 @@ public class InstalledSkinInfo public void WriteXml(XmlWriter writer) { - //Write start of main elemenst + // Write start of main elemenst writer.WriteStartElement("skin"); - writer.WriteElementString("skinName", SkinName); - writer.WriteElementString("inUse", InUse.ToString()); + writer.WriteElementString("skinName", this.SkinName); + writer.WriteElementString("inUse", this.InUse.ToString()); - //Write end of Host Info + // Write end of Host Info writer.WriteEndElement(); } } diff --git a/DNN Platform/Library/UI/Skins/NavObjectBase.cs b/DNN Platform/Library/UI/Skins/NavObjectBase.cs index e39f404f0b4..1572bd43272 100644 --- a/DNN Platform/Library/UI/Skins/NavObjectBase.cs +++ b/DNN Platform/Library/UI/Skins/NavObjectBase.cs @@ -1,26 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.UI.WebControls; + public class NavObjectBase : SkinObjectBase - { - #region "Private Members" - + { private readonly List m_objCustomAttributes = new List(); private bool m_blnPopulateNodesFromClient = true; private int m_intExpandDepth = -1; @@ -65,7 +58,7 @@ public class NavObjectBase : SkinObjectBase private string m_strIndicateChildImageRoot; private string m_strIndicateChildImageSub; private string m_strIndicateChildren; - private string m_strLevel = ""; + private string m_strLevel = string.Empty; private string m_strMouseOutHideDelay; private string m_strMouseOverAction; private string m_strMouseOverDisplay; @@ -80,7 +73,7 @@ public class NavObjectBase : SkinObjectBase private string m_strPathImage; private string m_strPathSystemImage; private string m_strPathSystemScript; - private string m_strProviderName = ""; + private string m_strProviderName = string.Empty; private string m_strSeparatorHTML; private string m_strSeparatorLeftHTML; private string m_strSeparatorLeftHTMLActive; @@ -102,65 +95,66 @@ public class NavObjectBase : SkinObjectBase private string m_strStyleSelectionBorderColor; private string m_strStyleSelectionColor; private string m_strStyleSelectionForeColor; - private string m_strToolTip = ""; - private string m_strWorkImage; - - #endregion - - #region "Public Properties" - //JH - 2/5/07 - support for custom attributes - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty)] + private string m_strToolTip = string.Empty; + private string m_strWorkImage; + + // JH - 2/5/07 - support for custom attributes + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] public List CustomAttributes { get { - return m_objCustomAttributes; + return this.m_objCustomAttributes; } } public bool ShowHiddenTabs { get; set; } - + public string ProviderName { get { - return m_strProviderName; + return this.m_strProviderName; } + set { - m_strProviderName = value; + this.m_strProviderName = value; } } - protected NavigationProvider Control + public string Level { get { - return m_objControl; + return this.m_strLevel; + } + + set + { + this.m_strLevel = value; } } - public string Level + public string ToolTip { get { - return m_strLevel; + return this.m_strToolTip; } + set { - m_strLevel = value; + this.m_strToolTip = value; } } - public string ToolTip + protected NavigationProvider Control { get { - return m_strToolTip; - } - set - { - m_strToolTip = value; + return this.m_objControl; } } @@ -168,11 +162,12 @@ public bool PopulateNodesFromClient { get { - return m_blnPopulateNodesFromClient; + return this.m_blnPopulateNodesFromClient; } + set { - m_blnPopulateNodesFromClient = value; + this.m_blnPopulateNodesFromClient = value; } } @@ -180,11 +175,12 @@ public int ExpandDepth { get { - return m_intExpandDepth; + return this.m_intExpandDepth; } + set { - m_intExpandDepth = value; + this.m_intExpandDepth = value; } } @@ -192,11 +188,12 @@ public int StartTabId { get { - return m_intStartTabId; + return this.m_intStartTabId; } + set { - m_intStartTabId = value; + this.m_intStartTabId = value; } } @@ -204,25 +201,26 @@ public string PathSystemImage { get { - if (Control == null) + if (this.Control == null) { - return m_strPathSystemImage; + return this.m_strPathSystemImage; } else { - return Control.PathSystemImage; + return this.Control.PathSystemImage; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strPathSystemImage = value; + this.m_strPathSystemImage = value; } else { - Control.PathSystemImage = value; + this.Control.PathSystemImage = value; } } } @@ -231,25 +229,26 @@ public string PathImage { get { - if (Control == null) + if (this.Control == null) { - return m_strPathImage; + return this.m_strPathImage; } else { - return Control.PathImage; + return this.Control.PathImage; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strPathImage = value; + this.m_strPathImage = value; } else { - Control.PathImage = value; + this.Control.PathImage = value; } } } @@ -258,24 +257,25 @@ public string WorkImage { get { - if (Control == null) + if (this.Control == null) { - return m_strWorkImage; + return this.m_strWorkImage; } else { - return Control.WorkImage; + return this.Control.WorkImage; } } + set { - if (Control == null) + if (this.Control == null) { - m_strWorkImage = value; + this.m_strWorkImage = value; } else { - Control.WorkImage = value; + this.Control.WorkImage = value; } } } @@ -284,24 +284,25 @@ public string PathSystemScript { get { - if (Control == null) + if (this.Control == null) { - return m_strPathSystemScript; + return this.m_strPathSystemScript; } else { - return Control.PathSystemScript; + return this.Control.PathSystemScript; } } + set { - if (Control == null) + if (this.Control == null) { - m_strPathSystemScript = value; + this.m_strPathSystemScript = value; } else { - Control.PathSystemScript = value; + this.Control.PathSystemScript = value; } } } @@ -310,14 +311,14 @@ public string ControlOrientation { get { - string retValue = ""; - if (Control == null) + string retValue = string.Empty; + if (this.Control == null) { - retValue = m_strControlOrientation; + retValue = this.m_strControlOrientation; } else { - switch (Control.ControlOrientation) + switch (this.Control.ControlOrientation) { case NavigationProvider.Orientation.Horizontal: retValue = "Horizontal"; @@ -327,23 +328,25 @@ public string ControlOrientation break; } } + return retValue; } + set { - if (Control == null) + if (this.Control == null) { - m_strControlOrientation = value; + this.m_strControlOrientation = value; } else { switch (value.ToLowerInvariant()) { case "horizontal": - Control.ControlOrientation = NavigationProvider.Orientation.Horizontal; + this.Control.ControlOrientation = NavigationProvider.Orientation.Horizontal; break; case "vertical": - Control.ControlOrientation = NavigationProvider.Orientation.Vertical; + this.Control.ControlOrientation = NavigationProvider.Orientation.Vertical; break; } } @@ -354,14 +357,14 @@ public string ControlAlignment { get { - string retValue = ""; - if (Control == null) + string retValue = string.Empty; + if (this.Control == null) { - retValue = m_strControlAlignment; + retValue = this.m_strControlAlignment; } else { - switch (Control.ControlAlignment) + switch (this.Control.ControlAlignment) { case NavigationProvider.Alignment.Left: retValue = "Left"; @@ -377,29 +380,31 @@ public string ControlAlignment break; } } + return retValue; } + set { - if (Control == null) + if (this.Control == null) { - m_strControlAlignment = value; + this.m_strControlAlignment = value; } else { switch (value.ToLowerInvariant()) { case "left": - Control.ControlAlignment = NavigationProvider.Alignment.Left; + this.Control.ControlAlignment = NavigationProvider.Alignment.Left; break; case "right": - Control.ControlAlignment = NavigationProvider.Alignment.Right; + this.Control.ControlAlignment = NavigationProvider.Alignment.Right; break; case "center": - Control.ControlAlignment = NavigationProvider.Alignment.Center; + this.Control.ControlAlignment = NavigationProvider.Alignment.Center; break; case "justify": - Control.ControlAlignment = NavigationProvider.Alignment.Justify; + this.Control.ControlAlignment = NavigationProvider.Alignment.Justify; break; } } @@ -410,24 +415,25 @@ public string ForceCrawlerDisplay { get { - if (Control == null) + if (this.Control == null) { - return m_strForceCrawlerDisplay; + return this.m_strForceCrawlerDisplay; } else { - return Control.ForceCrawlerDisplay; + return this.Control.ForceCrawlerDisplay; } } + set { - if (Control == null) + if (this.Control == null) { - m_strForceCrawlerDisplay = value; + this.m_strForceCrawlerDisplay = value; } else { - Control.ForceCrawlerDisplay = value; + this.Control.ForceCrawlerDisplay = value; } } } @@ -436,24 +442,25 @@ public string ForceDownLevel { get { - if (Control == null) + if (this.Control == null) { - return m_strForceDownLevel; + return this.m_strForceDownLevel; } else { - return Control.ForceDownLevel; + return this.Control.ForceDownLevel; } } + set { - if (Control == null) + if (this.Control == null) { - m_strForceDownLevel = value; + this.m_strForceDownLevel = value; } else { - Control.ForceDownLevel = value; + this.Control.ForceDownLevel = value; } } } @@ -462,24 +469,25 @@ public string MouseOutHideDelay { get { - if (Control == null) + if (this.Control == null) { - return m_strMouseOutHideDelay; + return this.m_strMouseOutHideDelay; } else { - return Control.MouseOutHideDelay.ToString(); + return this.Control.MouseOutHideDelay.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strMouseOutHideDelay = value; + this.m_strMouseOutHideDelay = value; } else { - Control.MouseOutHideDelay = Convert.ToDecimal(value); + this.Control.MouseOutHideDelay = Convert.ToDecimal(value); } } } @@ -488,14 +496,14 @@ public string MouseOverDisplay { get { - string retValue = ""; - if (Control == null) + string retValue = string.Empty; + if (this.Control == null) { - retValue = m_strMouseOverDisplay; + retValue = this.m_strMouseOverDisplay; } else { - switch (Control.MouseOverDisplay) + switch (this.Control.MouseOverDisplay) { case NavigationProvider.HoverDisplay.Highlight: retValue = "Highlight"; @@ -508,26 +516,28 @@ public string MouseOverDisplay break; } } + return retValue; } + set { - if (Control == null) + if (this.Control == null) { - m_strMouseOverDisplay = value; + this.m_strMouseOverDisplay = value; } else { switch (value.ToLowerInvariant()) { case "highlight": - Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Highlight; + this.Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Highlight; break; case "outset": - Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Outset; + this.Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Outset; break; case "none": - Control.MouseOverDisplay = NavigationProvider.HoverDisplay.None; + this.Control.MouseOverDisplay = NavigationProvider.HoverDisplay.None; break; } } @@ -538,14 +548,14 @@ public string MouseOverAction { get { - string retValue = ""; - if (Control == null) + string retValue = string.Empty; + if (this.Control == null) { - retValue = m_strMouseOverAction; + retValue = this.m_strMouseOverAction; } else { - switch (Control.MouseOverAction) + switch (this.Control.MouseOverAction) { case NavigationProvider.HoverAction.Expand: retValue = "True"; @@ -555,23 +565,25 @@ public string MouseOverAction break; } } + return retValue; } + set { - if (Control == null) + if (this.Control == null) { - m_strMouseOverAction = value; + this.m_strMouseOverAction = value; } else { - if (Convert.ToBoolean(GetValue(value, "True"))) + if (Convert.ToBoolean(this.GetValue(value, "True"))) { - Control.MouseOverAction = NavigationProvider.HoverAction.Expand; + this.Control.MouseOverAction = NavigationProvider.HoverAction.Expand; } else { - Control.MouseOverAction = NavigationProvider.HoverAction.None; + this.Control.MouseOverAction = NavigationProvider.HoverAction.None; } } } @@ -581,24 +593,25 @@ public string IndicateChildren { get { - if (Control == null) + if (this.Control == null) { - return m_strIndicateChildren; + return this.m_strIndicateChildren; } else { - return Control.IndicateChildren.ToString(); + return this.Control.IndicateChildren.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strIndicateChildren = value; + this.m_strIndicateChildren = value; } else { - Control.IndicateChildren = Convert.ToBoolean(value); + this.Control.IndicateChildren = Convert.ToBoolean(value); } } } @@ -607,25 +620,26 @@ public string IndicateChildImageRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strIndicateChildImageRoot; + return this.m_strIndicateChildImageRoot; } else { - return Control.IndicateChildImageRoot; + return this.Control.IndicateChildImageRoot; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strIndicateChildImageRoot = value; + this.m_strIndicateChildImageRoot = value; } else { - Control.IndicateChildImageRoot = value; + this.Control.IndicateChildImageRoot = value; } } } @@ -634,25 +648,26 @@ public string IndicateChildImageSub { get { - if (Control == null) + if (this.Control == null) { - return m_strIndicateChildImageSub; + return this.m_strIndicateChildImageSub; } else { - return Control.IndicateChildImageSub; + return this.Control.IndicateChildImageSub; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strIndicateChildImageSub = value; + this.m_strIndicateChildImageSub = value; } else { - Control.IndicateChildImageSub = value; + this.Control.IndicateChildImageSub = value; } } } @@ -661,25 +676,26 @@ public string IndicateChildImageExpandedRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strIndicateChildImageExpandedRoot; + return this.m_strIndicateChildImageExpandedRoot; } else { - return Control.IndicateChildImageExpandedRoot; + return this.Control.IndicateChildImageExpandedRoot; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strIndicateChildImageExpandedRoot = value; + this.m_strIndicateChildImageExpandedRoot = value; } else { - Control.IndicateChildImageExpandedRoot = value; + this.Control.IndicateChildImageExpandedRoot = value; } } } @@ -688,25 +704,26 @@ public string IndicateChildImageExpandedSub { get { - if (Control == null) + if (this.Control == null) { - return m_strIndicateChildImageExpandedSub; + return this.m_strIndicateChildImageExpandedSub; } else { - return Control.IndicateChildImageExpandedSub; + return this.Control.IndicateChildImageExpandedSub; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strIndicateChildImageExpandedSub = value; + this.m_strIndicateChildImageExpandedSub = value; } else { - Control.IndicateChildImageExpandedSub = value; + this.Control.IndicateChildImageExpandedSub = value; } } } @@ -715,25 +732,26 @@ public string NodeLeftHTMLRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeLeftHTMLRoot; + return this.m_strNodeLeftHTMLRoot; } else { - return Control.NodeLeftHTMLRoot; + return this.Control.NodeLeftHTMLRoot; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeLeftHTMLRoot = value; + this.m_strNodeLeftHTMLRoot = value; } else { - Control.NodeLeftHTMLRoot = value; + this.Control.NodeLeftHTMLRoot = value; } } } @@ -742,25 +760,26 @@ public string NodeRightHTMLRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeRightHTMLRoot; + return this.m_strNodeRightHTMLRoot; } else { - return Control.NodeRightHTMLRoot; + return this.Control.NodeRightHTMLRoot; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeRightHTMLRoot = value; + this.m_strNodeRightHTMLRoot = value; } else { - Control.NodeRightHTMLRoot = value; + this.Control.NodeRightHTMLRoot = value; } } } @@ -769,25 +788,26 @@ public string NodeLeftHTMLSub { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeLeftHTMLSub; + return this.m_strNodeLeftHTMLSub; } else { - return Control.NodeLeftHTMLSub; + return this.Control.NodeLeftHTMLSub; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeLeftHTMLSub = value; + this.m_strNodeLeftHTMLSub = value; } else { - Control.NodeLeftHTMLSub = value; + this.Control.NodeLeftHTMLSub = value; } } } @@ -796,25 +816,26 @@ public string NodeRightHTMLSub { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeRightHTMLSub; + return this.m_strNodeRightHTMLSub; } else { - return Control.NodeRightHTMLSub; + return this.Control.NodeRightHTMLSub; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeRightHTMLSub = value; + this.m_strNodeRightHTMLSub = value; } else { - Control.NodeRightHTMLSub = value; + this.Control.NodeRightHTMLSub = value; } } } @@ -823,25 +844,26 @@ public string NodeLeftHTMLBreadCrumbRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeLeftHTMLBreadCrumbRoot; + return this.m_strNodeLeftHTMLBreadCrumbRoot; } else { - return Control.NodeLeftHTMLBreadCrumbRoot; + return this.Control.NodeLeftHTMLBreadCrumbRoot; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeLeftHTMLBreadCrumbRoot = value; + this.m_strNodeLeftHTMLBreadCrumbRoot = value; } else { - Control.NodeLeftHTMLBreadCrumbRoot = value; + this.Control.NodeLeftHTMLBreadCrumbRoot = value; } } } @@ -850,25 +872,26 @@ public string NodeLeftHTMLBreadCrumbSub { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeLeftHTMLBreadCrumbSub; + return this.m_strNodeLeftHTMLBreadCrumbSub; } else { - return Control.NodeLeftHTMLBreadCrumbSub; + return this.Control.NodeLeftHTMLBreadCrumbSub; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeLeftHTMLBreadCrumbSub = value; + this.m_strNodeLeftHTMLBreadCrumbSub = value; } else { - Control.NodeLeftHTMLBreadCrumbSub = value; + this.Control.NodeLeftHTMLBreadCrumbSub = value; } } } @@ -877,25 +900,26 @@ public string NodeRightHTMLBreadCrumbRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeRightHTMLBreadCrumbRoot; + return this.m_strNodeRightHTMLBreadCrumbRoot; } else { - return Control.NodeRightHTMLBreadCrumbRoot; + return this.Control.NodeRightHTMLBreadCrumbRoot; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeRightHTMLBreadCrumbRoot = value; + this.m_strNodeRightHTMLBreadCrumbRoot = value; } else { - Control.NodeRightHTMLBreadCrumbRoot = value; + this.Control.NodeRightHTMLBreadCrumbRoot = value; } } } @@ -904,25 +928,26 @@ public string NodeRightHTMLBreadCrumbSub { get { - if (Control == null) + if (this.Control == null) { - return m_strNodeRightHTMLBreadCrumbSub; + return this.m_strNodeRightHTMLBreadCrumbSub; } else { - return Control.NodeRightHTMLBreadCrumbSub; + return this.Control.NodeRightHTMLBreadCrumbSub; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strNodeRightHTMLBreadCrumbSub = value; + this.m_strNodeRightHTMLBreadCrumbSub = value; } else { - Control.NodeRightHTMLBreadCrumbSub = value; + this.Control.NodeRightHTMLBreadCrumbSub = value; } } } @@ -931,25 +956,26 @@ public string SeparatorHTML { get { - if (Control == null) + if (this.Control == null) { - return m_strSeparatorHTML; + return this.m_strSeparatorHTML; } else { - return Control.SeparatorHTML; + return this.Control.SeparatorHTML; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strSeparatorHTML = value; + this.m_strSeparatorHTML = value; } else { - Control.SeparatorHTML = value; + this.Control.SeparatorHTML = value; } } } @@ -958,25 +984,26 @@ public string SeparatorLeftHTML { get { - if (Control == null) + if (this.Control == null) { - return m_strSeparatorLeftHTML; + return this.m_strSeparatorLeftHTML; } else { - return Control.SeparatorLeftHTML; + return this.Control.SeparatorLeftHTML; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strSeparatorLeftHTML = value; + this.m_strSeparatorLeftHTML = value; } else { - Control.SeparatorLeftHTML = value; + this.Control.SeparatorLeftHTML = value; } } } @@ -985,25 +1012,26 @@ public string SeparatorRightHTML { get { - if (Control == null) + if (this.Control == null) { - return m_strSeparatorRightHTML; + return this.m_strSeparatorRightHTML; } else { - return Control.SeparatorRightHTML; + return this.Control.SeparatorRightHTML; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strSeparatorRightHTML = value; + this.m_strSeparatorRightHTML = value; } else { - Control.SeparatorRightHTML = value; + this.Control.SeparatorRightHTML = value; } } } @@ -1012,25 +1040,26 @@ public string SeparatorLeftHTMLActive { get { - if (Control == null) + if (this.Control == null) { - return m_strSeparatorLeftHTMLActive; + return this.m_strSeparatorLeftHTMLActive; } else { - return Control.SeparatorLeftHTMLActive; + return this.Control.SeparatorLeftHTMLActive; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strSeparatorLeftHTMLActive = value; + this.m_strSeparatorLeftHTMLActive = value; } else { - Control.SeparatorLeftHTMLActive = value; + this.Control.SeparatorLeftHTMLActive = value; } } } @@ -1039,25 +1068,26 @@ public string SeparatorRightHTMLActive { get { - if (Control == null) + if (this.Control == null) { - return m_strSeparatorRightHTMLActive; + return this.m_strSeparatorRightHTMLActive; } else { - return Control.SeparatorRightHTMLActive; + return this.Control.SeparatorRightHTMLActive; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strSeparatorRightHTMLActive = value; + this.m_strSeparatorRightHTMLActive = value; } else { - Control.SeparatorRightHTMLActive = value; + this.Control.SeparatorRightHTMLActive = value; } } } @@ -1066,25 +1096,26 @@ public string SeparatorLeftHTMLBreadCrumb { get { - if (Control == null) + if (this.Control == null) { - return m_strSeparatorLeftHTMLBreadCrumb; + return this.m_strSeparatorLeftHTMLBreadCrumb; } else { - return Control.SeparatorLeftHTMLBreadCrumb; + return this.Control.SeparatorLeftHTMLBreadCrumb; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strSeparatorLeftHTMLBreadCrumb = value; + this.m_strSeparatorLeftHTMLBreadCrumb = value; } else { - Control.SeparatorLeftHTMLBreadCrumb = value; + this.Control.SeparatorLeftHTMLBreadCrumb = value; } } } @@ -1093,25 +1124,26 @@ public string SeparatorRightHTMLBreadCrumb { get { - if (Control == null) + if (this.Control == null) { - return m_strSeparatorRightHTMLBreadCrumb; + return this.m_strSeparatorRightHTMLBreadCrumb; } else { - return Control.SeparatorRightHTMLBreadCrumb; + return this.Control.SeparatorRightHTMLBreadCrumb; } } + set { - value = GetPath(value); - if (Control == null) + value = this.GetPath(value); + if (this.Control == null) { - m_strSeparatorRightHTMLBreadCrumb = value; + this.m_strSeparatorRightHTMLBreadCrumb = value; } else { - Control.SeparatorRightHTMLBreadCrumb = value; + this.Control.SeparatorRightHTMLBreadCrumb = value; } } } @@ -1120,24 +1152,25 @@ public string CSSControl { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSControl; + return this.m_strCSSControl; } else { - return Control.CSSControl; + return this.Control.CSSControl; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSControl = value; + this.m_strCSSControl = value; } else { - Control.CSSControl = value; + this.Control.CSSControl = value; } } } @@ -1146,24 +1179,25 @@ public string CSSContainerRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSContainerRoot; + return this.m_strCSSContainerRoot; } else { - return Control.CSSContainerRoot; + return this.Control.CSSContainerRoot; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSContainerRoot = value; + this.m_strCSSContainerRoot = value; } else { - Control.CSSContainerRoot = value; + this.Control.CSSContainerRoot = value; } } } @@ -1172,24 +1206,25 @@ public string CSSNode { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSNode; + return this.m_strCSSNode; } else { - return Control.CSSNode; + return this.Control.CSSNode; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSNode = value; + this.m_strCSSNode = value; } else { - Control.CSSNode = value; + this.Control.CSSNode = value; } } } @@ -1198,24 +1233,25 @@ public string CSSIcon { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSIcon; + return this.m_strCSSIcon; } else { - return Control.CSSIcon; + return this.Control.CSSIcon; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSIcon = value; + this.m_strCSSIcon = value; } else { - Control.CSSIcon = value; + this.Control.CSSIcon = value; } } } @@ -1224,24 +1260,25 @@ public string CSSContainerSub { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSContainerSub; + return this.m_strCSSContainerSub; } else { - return Control.CSSContainerSub; + return this.Control.CSSContainerSub; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSContainerSub = value; + this.m_strCSSContainerSub = value; } else { - Control.CSSContainerSub = value; + this.Control.CSSContainerSub = value; } } } @@ -1250,24 +1287,25 @@ public string CSSNodeHover { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSNodeHover; + return this.m_strCSSNodeHover; } else { - return Control.CSSNodeHover; + return this.Control.CSSNodeHover; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSNodeHover = value; + this.m_strCSSNodeHover = value; } else { - Control.CSSNodeHover = value; + this.Control.CSSNodeHover = value; } } } @@ -1276,24 +1314,25 @@ public string CSSBreak { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSBreak; + return this.m_strCSSBreak; } else { - return Control.CSSBreak; + return this.Control.CSSBreak; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSBreak = value; + this.m_strCSSBreak = value; } else { - Control.CSSBreak = value; + this.Control.CSSBreak = value; } } } @@ -1302,24 +1341,25 @@ public string CSSIndicateChildSub { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSIndicateChildSub; + return this.m_strCSSIndicateChildSub; } else { - return Control.CSSIndicateChildSub; + return this.Control.CSSIndicateChildSub; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSIndicateChildSub = value; + this.m_strCSSIndicateChildSub = value; } else { - Control.CSSIndicateChildSub = value; + this.Control.CSSIndicateChildSub = value; } } } @@ -1328,24 +1368,25 @@ public string CSSIndicateChildRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSIndicateChildRoot; + return this.m_strCSSIndicateChildRoot; } else { - return Control.CSSIndicateChildRoot; + return this.Control.CSSIndicateChildRoot; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSIndicateChildRoot = value; + this.m_strCSSIndicateChildRoot = value; } else { - Control.CSSIndicateChildRoot = value; + this.Control.CSSIndicateChildRoot = value; } } } @@ -1354,24 +1395,25 @@ public string CSSBreadCrumbRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSBreadCrumbRoot; + return this.m_strCSSBreadCrumbRoot; } else { - return Control.CSSBreadCrumbRoot; + return this.Control.CSSBreadCrumbRoot; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSBreadCrumbRoot = value; + this.m_strCSSBreadCrumbRoot = value; } else { - Control.CSSBreadCrumbRoot = value; + this.Control.CSSBreadCrumbRoot = value; } } } @@ -1380,24 +1422,25 @@ public string CSSBreadCrumbSub { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSBreadCrumbSub; + return this.m_strCSSBreadCrumbSub; } else { - return Control.CSSBreadCrumbSub; + return this.Control.CSSBreadCrumbSub; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSBreadCrumbSub = value; + this.m_strCSSBreadCrumbSub = value; } else { - Control.CSSBreadCrumbSub = value; + this.Control.CSSBreadCrumbSub = value; } } } @@ -1406,24 +1449,25 @@ public string CSSNodeRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSNodeRoot; + return this.m_strCSSNodeRoot; } else { - return Control.CSSNodeRoot; + return this.Control.CSSNodeRoot; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSNodeRoot = value; + this.m_strCSSNodeRoot = value; } else { - Control.CSSNodeRoot = value; + this.Control.CSSNodeRoot = value; } } } @@ -1432,24 +1476,25 @@ public string CSSNodeSelectedRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSNodeSelectedRoot; + return this.m_strCSSNodeSelectedRoot; } else { - return Control.CSSNodeSelectedRoot; + return this.Control.CSSNodeSelectedRoot; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSNodeSelectedRoot = value; + this.m_strCSSNodeSelectedRoot = value; } else { - Control.CSSNodeSelectedRoot = value; + this.Control.CSSNodeSelectedRoot = value; } } } @@ -1458,24 +1503,25 @@ public string CSSNodeSelectedSub { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSNodeSelectedSub; + return this.m_strCSSNodeSelectedSub; } else { - return Control.CSSNodeSelectedSub; + return this.Control.CSSNodeSelectedSub; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSNodeSelectedSub = value; + this.m_strCSSNodeSelectedSub = value; } else { - Control.CSSNodeSelectedSub = value; + this.Control.CSSNodeSelectedSub = value; } } } @@ -1484,24 +1530,25 @@ public string CSSNodeHoverRoot { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSNodeHoverRoot; + return this.m_strCSSNodeHoverRoot; } else { - return Control.CSSNodeHoverRoot; + return this.Control.CSSNodeHoverRoot; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSNodeHoverRoot = value; + this.m_strCSSNodeHoverRoot = value; } else { - Control.CSSNodeHoverRoot = value; + this.Control.CSSNodeHoverRoot = value; } } } @@ -1510,24 +1557,25 @@ public string CSSNodeHoverSub { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSNodeHoverSub; + return this.m_strCSSNodeHoverSub; } else { - return Control.CSSNodeHoverSub; + return this.Control.CSSNodeHoverSub; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSNodeHoverSub = value; + this.m_strCSSNodeHoverSub = value; } else { - Control.CSSNodeHoverSub = value; + this.Control.CSSNodeHoverSub = value; } } } @@ -1536,24 +1584,25 @@ public string CSSSeparator { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSSeparator; + return this.m_strCSSSeparator; } else { - return Control.CSSSeparator; + return this.Control.CSSSeparator; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSSeparator = value; + this.m_strCSSSeparator = value; } else { - Control.CSSSeparator = value; + this.Control.CSSSeparator = value; } } } @@ -1562,24 +1611,25 @@ public string CSSLeftSeparator { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSLeftSeparator; + return this.m_strCSSLeftSeparator; } else { - return Control.CSSLeftSeparator; + return this.Control.CSSLeftSeparator; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSLeftSeparator = value; + this.m_strCSSLeftSeparator = value; } else { - Control.CSSLeftSeparator = value; + this.Control.CSSLeftSeparator = value; } } } @@ -1588,24 +1638,25 @@ public string CSSRightSeparator { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSRightSeparator; + return this.m_strCSSRightSeparator; } else { - return Control.CSSRightSeparator; + return this.Control.CSSRightSeparator; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSRightSeparator = value; + this.m_strCSSRightSeparator = value; } else { - Control.CSSRightSeparator = value; + this.Control.CSSRightSeparator = value; } } } @@ -1614,24 +1665,25 @@ public string CSSLeftSeparatorSelection { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSLeftSeparatorSelection; + return this.m_strCSSLeftSeparatorSelection; } else { - return Control.CSSLeftSeparatorSelection; + return this.Control.CSSLeftSeparatorSelection; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSLeftSeparatorSelection = value; + this.m_strCSSLeftSeparatorSelection = value; } else { - Control.CSSLeftSeparatorSelection = value; + this.Control.CSSLeftSeparatorSelection = value; } } } @@ -1640,24 +1692,25 @@ public string CSSRightSeparatorSelection { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSRightSeparatorSelection; + return this.m_strCSSRightSeparatorSelection; } else { - return Control.CSSRightSeparatorSelection; + return this.Control.CSSRightSeparatorSelection; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSRightSeparatorSelection = value; + this.m_strCSSRightSeparatorSelection = value; } else { - Control.CSSRightSeparatorSelection = value; + this.Control.CSSRightSeparatorSelection = value; } } } @@ -1666,24 +1719,25 @@ public string CSSLeftSeparatorBreadCrumb { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSLeftSeparatorBreadCrumb; + return this.m_strCSSLeftSeparatorBreadCrumb; } else { - return Control.CSSLeftSeparatorBreadCrumb; + return this.Control.CSSLeftSeparatorBreadCrumb; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSLeftSeparatorBreadCrumb = value; + this.m_strCSSLeftSeparatorBreadCrumb = value; } else { - Control.CSSLeftSeparatorBreadCrumb = value; + this.Control.CSSLeftSeparatorBreadCrumb = value; } } } @@ -1692,24 +1746,25 @@ public string CSSRightSeparatorBreadCrumb { get { - if (Control == null) + if (this.Control == null) { - return m_strCSSRightSeparatorBreadCrumb; + return this.m_strCSSRightSeparatorBreadCrumb; } else { - return Control.CSSRightSeparatorBreadCrumb; + return this.Control.CSSRightSeparatorBreadCrumb; } } + set { - if (Control == null) + if (this.Control == null) { - m_strCSSRightSeparatorBreadCrumb = value; + this.m_strCSSRightSeparatorBreadCrumb = value; } else { - Control.CSSRightSeparatorBreadCrumb = value; + this.Control.CSSRightSeparatorBreadCrumb = value; } } } @@ -1718,24 +1773,25 @@ public string StyleBackColor { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleBackColor; + return this.m_strStyleBackColor; } else { - return Control.StyleBackColor; + return this.Control.StyleBackColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleBackColor = value; + this.m_strStyleBackColor = value; } else { - Control.StyleBackColor = value; + this.Control.StyleBackColor = value; } } } @@ -1744,24 +1800,25 @@ public string StyleForeColor { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleForeColor; + return this.m_strStyleForeColor; } else { - return Control.StyleForeColor; + return this.Control.StyleForeColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleForeColor = value; + this.m_strStyleForeColor = value; } else { - Control.StyleForeColor = value; + this.Control.StyleForeColor = value; } } } @@ -1770,24 +1827,25 @@ public string StyleHighlightColor { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleHighlightColor; + return this.m_strStyleHighlightColor; } else { - return Control.StyleHighlightColor; + return this.Control.StyleHighlightColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleHighlightColor = value; + this.m_strStyleHighlightColor = value; } else { - Control.StyleHighlightColor = value; + this.Control.StyleHighlightColor = value; } } } @@ -1796,24 +1854,25 @@ public string StyleIconBackColor { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleIconBackColor; + return this.m_strStyleIconBackColor; } else { - return Control.StyleIconBackColor; + return this.Control.StyleIconBackColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleIconBackColor = value; + this.m_strStyleIconBackColor = value; } else { - Control.StyleIconBackColor = value; + this.Control.StyleIconBackColor = value; } } } @@ -1822,24 +1881,25 @@ public string StyleSelectionBorderColor { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleSelectionBorderColor; + return this.m_strStyleSelectionBorderColor; } else { - return Control.StyleSelectionBorderColor; + return this.Control.StyleSelectionBorderColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleSelectionBorderColor = value; + this.m_strStyleSelectionBorderColor = value; } else { - Control.StyleSelectionBorderColor = value; + this.Control.StyleSelectionBorderColor = value; } } } @@ -1848,24 +1908,25 @@ public string StyleSelectionColor { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleSelectionColor; + return this.m_strStyleSelectionColor; } else { - return Control.StyleSelectionColor; + return this.Control.StyleSelectionColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleSelectionColor = value; + this.m_strStyleSelectionColor = value; } else { - Control.StyleSelectionColor = value; + this.Control.StyleSelectionColor = value; } } } @@ -1874,24 +1935,25 @@ public string StyleSelectionForeColor { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleSelectionForeColor; + return this.m_strStyleSelectionForeColor; } else { - return Control.StyleSelectionForeColor; + return this.Control.StyleSelectionForeColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleSelectionForeColor = value; + this.m_strStyleSelectionForeColor = value; } else { - Control.StyleSelectionForeColor = value; + this.Control.StyleSelectionForeColor = value; } } } @@ -1900,24 +1962,25 @@ public string StyleControlHeight { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleControlHeight; + return this.m_strStyleControlHeight; } else { - return Control.StyleControlHeight.ToString(); + return this.Control.StyleControlHeight.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleControlHeight = value; + this.m_strStyleControlHeight = value; } else { - Control.StyleControlHeight = Convert.ToDecimal(value); + this.Control.StyleControlHeight = Convert.ToDecimal(value); } } } @@ -1926,24 +1989,25 @@ public string StyleBorderWidth { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleBorderWidth; + return this.m_strStyleBorderWidth; } else { - return Control.StyleBorderWidth.ToString(); + return this.Control.StyleBorderWidth.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleBorderWidth = value; + this.m_strStyleBorderWidth = value; } else { - Control.StyleBorderWidth = Convert.ToDecimal(value); + this.Control.StyleBorderWidth = Convert.ToDecimal(value); } } } @@ -1952,24 +2016,25 @@ public string StyleNodeHeight { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleNodeHeight; + return this.m_strStyleNodeHeight; } else { - return Control.StyleNodeHeight.ToString(); + return this.Control.StyleNodeHeight.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleNodeHeight = value; + this.m_strStyleNodeHeight = value; } else { - Control.StyleNodeHeight = Convert.ToDecimal(value); + this.Control.StyleNodeHeight = Convert.ToDecimal(value); } } } @@ -1978,24 +2043,25 @@ public string StyleIconWidth { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleIconWidth; + return this.m_strStyleIconWidth; } else { - return Control.StyleIconWidth.ToString(); + return this.Control.StyleIconWidth.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleIconWidth = value; + this.m_strStyleIconWidth = value; } else { - Control.StyleIconWidth = Convert.ToDecimal(value); + this.Control.StyleIconWidth = Convert.ToDecimal(value); } } } @@ -2004,24 +2070,25 @@ public string StyleFontNames { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleFontNames; + return this.m_strStyleFontNames; } else { - return Control.StyleFontNames; + return this.Control.StyleFontNames; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleFontNames = value; + this.m_strStyleFontNames = value; } else { - Control.StyleFontNames = value; + this.Control.StyleFontNames = value; } } } @@ -2030,24 +2097,25 @@ public string StyleFontSize { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleFontSize; + return this.m_strStyleFontSize; } else { - return Control.StyleFontSize.ToString(); + return this.Control.StyleFontSize.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleFontSize = value; + this.m_strStyleFontSize = value; } else { - Control.StyleFontSize = Convert.ToDecimal(value); + this.Control.StyleFontSize = Convert.ToDecimal(value); } } } @@ -2056,24 +2124,25 @@ public string StyleFontBold { get { - if (Control == null) + if (this.Control == null) { - return m_strStyleFontBold; + return this.m_strStyleFontBold; } else { - return Control.StyleFontBold; + return this.Control.StyleFontBold; } } + set { - if (Control == null) + if (this.Control == null) { - m_strStyleFontBold = value; + this.m_strStyleFontBold = value; } else { - Control.StyleFontBold = value; + this.Control.StyleFontBold = value; } } } @@ -2082,24 +2151,25 @@ public string EffectsShadowColor { get { - if (Control == null) + if (this.Control == null) { - return m_strEffectsShadowColor; + return this.m_strEffectsShadowColor; } else { - return Control.EffectsShadowColor; + return this.Control.EffectsShadowColor; } } + set { - if (Control == null) + if (this.Control == null) { - m_strEffectsShadowColor = value; + this.m_strEffectsShadowColor = value; } else { - Control.EffectsShadowColor = value; + this.Control.EffectsShadowColor = value; } } } @@ -2108,24 +2178,25 @@ public string EffectsStyle { get { - if (Control == null) + if (this.Control == null) { - return m_strEffectsStyle; + return this.m_strEffectsStyle; } else { - return Control.EffectsStyle; + return this.Control.EffectsStyle; } } + set { - if (Control == null) + if (this.Control == null) { - m_strEffectsStyle = value; + this.m_strEffectsStyle = value; } else { - Control.EffectsStyle = value; + this.Control.EffectsStyle = value; } } } @@ -2134,24 +2205,25 @@ public string EffectsShadowStrength { get { - if (Control == null) + if (this.Control == null) { - return m_strEffectsShadowStrength; + return this.m_strEffectsShadowStrength; } else { - return Control.EffectsShadowStrength.ToString(); + return this.Control.EffectsShadowStrength.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strEffectsShadowStrength = value; + this.m_strEffectsShadowStrength = value; } else { - Control.EffectsShadowStrength = Convert.ToInt32(value); + this.Control.EffectsShadowStrength = Convert.ToInt32(value); } } } @@ -2160,24 +2232,25 @@ public string EffectsTransition { get { - if (Control == null) + if (this.Control == null) { - return m_strEffectsTransition; + return this.m_strEffectsTransition; } else { - return Control.EffectsTransition; + return this.Control.EffectsTransition; } } + set { - if (Control == null) + if (this.Control == null) { - m_strEffectsTransition = value; + this.m_strEffectsTransition = value; } else { - Control.EffectsTransition = value; + this.Control.EffectsTransition = value; } } } @@ -2186,24 +2259,25 @@ public string EffectsDuration { get { - if (Control == null) + if (this.Control == null) { - return m_strEffectsDuration; + return this.m_strEffectsDuration; } else { - return Control.EffectsDuration.ToString(); + return this.Control.EffectsDuration.ToString(); } } + set { - if (Control == null) + if (this.Control == null) { - m_strEffectsDuration = value; + this.m_strEffectsDuration = value; } else { - Control.EffectsDuration = Convert.ToDouble(value); + this.Control.EffectsDuration = Convert.ToDouble(value); } } } @@ -2212,58 +2286,58 @@ public string EffectsShadowDirection { get { - if (Control == null) + if (this.Control == null) { - return m_strEffectsShadowDirection; + return this.m_strEffectsShadowDirection; } else { - return Control.EffectsShadowDirection; + return this.Control.EffectsShadowDirection; } } + set { - if (Control == null) + if (this.Control == null) { - m_strEffectsShadowDirection = value; + this.m_strEffectsShadowDirection = value; } else { - Control.EffectsShadowDirection = value; + this.Control.EffectsShadowDirection = value; } } - } - - #endregion - - #region "Public Methods" - - public DNNNodeCollection GetNavigationNodes(DNNNode objNode) + } + + public DNNNodeCollection GetNavigationNodes(DNNNode objNode) { - int intRootParent = PortalSettings.ActiveTab.TabID; + int intRootParent = this.PortalSettings.ActiveTab.TabID; DNNNodeCollection objNodes = null; Navigation.ToolTipSource eToolTips; int intNavNodeOptions = 0; - int intDepth = ExpandDepth; - switch (Level.ToLowerInvariant()) + int intDepth = this.ExpandDepth; + switch (this.Level.ToLowerInvariant()) { case "child": break; case "parent": - intNavNodeOptions = (int) Navigation.NavNodeOptions.IncludeParent + (int) Navigation.NavNodeOptions.IncludeSelf; + intNavNodeOptions = (int)Navigation.NavNodeOptions.IncludeParent + (int)Navigation.NavNodeOptions.IncludeSelf; break; case "same": - intNavNodeOptions = (int) Navigation.NavNodeOptions.IncludeSiblings + (int) Navigation.NavNodeOptions.IncludeSelf; + intNavNodeOptions = (int)Navigation.NavNodeOptions.IncludeSiblings + (int)Navigation.NavNodeOptions.IncludeSelf; break; default: intRootParent = -1; - intNavNodeOptions = (int) Navigation.NavNodeOptions.IncludeSiblings + (int) Navigation.NavNodeOptions.IncludeSelf; + intNavNodeOptions = (int)Navigation.NavNodeOptions.IncludeSiblings + (int)Navigation.NavNodeOptions.IncludeSelf; break; } - if (ShowHiddenTabs) intNavNodeOptions += (int) Navigation.NavNodeOptions.IncludeHiddenNodes; - - switch (ToolTip.ToLowerInvariant()) + if (this.ShowHiddenTabs) + { + intNavNodeOptions += (int)Navigation.NavNodeOptions.IncludeHiddenNodes; + } + + switch (this.ToolTip.ToLowerInvariant()) { case "name": eToolTips = Navigation.ToolTipSource.TabName; @@ -2278,38 +2352,39 @@ public DNNNodeCollection GetNavigationNodes(DNNNode objNode) eToolTips = Navigation.ToolTipSource.None; break; } - if (PopulateNodesFromClient && Control.SupportsPopulateOnDemand) + + if (this.PopulateNodesFromClient && this.Control.SupportsPopulateOnDemand) { - intNavNodeOptions += (int) Navigation.NavNodeOptions.MarkPendingNodes; + intNavNodeOptions += (int)Navigation.NavNodeOptions.MarkPendingNodes; } - if (PopulateNodesFromClient && Control.SupportsPopulateOnDemand == false) + + if (this.PopulateNodesFromClient && this.Control.SupportsPopulateOnDemand == false) { - ExpandDepth = -1; + this.ExpandDepth = -1; } - if (StartTabId != -1) + + if (this.StartTabId != -1) { - intRootParent = StartTabId; + intRootParent = this.StartTabId; } + if (objNode != null) { intRootParent = Convert.ToInt32(objNode.ID); - intNavNodeOptions = (int) Navigation.NavNodeOptions.MarkPendingNodes; + intNavNodeOptions = (int)Navigation.NavNodeOptions.MarkPendingNodes; objNodes = Navigation.GetNavigationNodes(objNode, eToolTips, intRootParent, intDepth, intNavNodeOptions); } else { - objNodes = Navigation.GetNavigationNodes(Control.ClientID, eToolTips, intRootParent, intDepth, intNavNodeOptions); + objNodes = Navigation.GetNavigationNodes(this.Control.ClientID, eToolTips, intRootParent, intDepth, intNavNodeOptions); } + return objNodes; - } - - #endregion - - #region "Protected Methods" - - protected string GetValue(string strVal, string strDefault) + } + + protected string GetValue(string strVal, string strDefault) { - if (String.IsNullOrEmpty(strVal)) + if (string.IsNullOrEmpty(strVal)) { return strDefault; } @@ -2321,360 +2396,428 @@ protected string GetValue(string strVal, string strDefault) protected void InitializeNavControl(Control objParent, string strDefaultProvider) { - if (String.IsNullOrEmpty(ProviderName)) + if (string.IsNullOrEmpty(this.ProviderName)) { - ProviderName = strDefaultProvider; + this.ProviderName = strDefaultProvider; } - m_objControl = NavigationProvider.Instance(ProviderName); - Control.ControlID = "ctl" + ID; - Control.Initialize(); - AssignControlProperties(); - objParent.Controls.Add(Control.NavigationControl); - } - - #endregion + + this.m_objControl = NavigationProvider.Instance(this.ProviderName); + this.Control.ControlID = "ctl" + this.ID; + this.Control.Initialize(); + this.AssignControlProperties(); + objParent.Controls.Add(this.Control.NavigationControl); + } - #region "Private Methods" - - private void AssignControlProperties() + protected void Bind(DNNNodeCollection objNodes) { - if (!String.IsNullOrEmpty(m_strPathSystemImage)) + this.Control.Bind(objNodes); + } + + private void AssignControlProperties() + { + if (!string.IsNullOrEmpty(this.m_strPathSystemImage)) { - Control.PathSystemImage = m_strPathSystemImage; + this.Control.PathSystemImage = this.m_strPathSystemImage; } - if (!String.IsNullOrEmpty(m_strPathImage)) + + if (!string.IsNullOrEmpty(this.m_strPathImage)) { - Control.PathImage = m_strPathImage; + this.Control.PathImage = this.m_strPathImage; } - if (!String.IsNullOrEmpty(m_strPathSystemScript)) + + if (!string.IsNullOrEmpty(this.m_strPathSystemScript)) { - Control.PathSystemScript = m_strPathSystemScript; + this.Control.PathSystemScript = this.m_strPathSystemScript; } - if (!String.IsNullOrEmpty(m_strWorkImage)) + + if (!string.IsNullOrEmpty(this.m_strWorkImage)) { - Control.WorkImage = m_strWorkImage; + this.Control.WorkImage = this.m_strWorkImage; } - if (!String.IsNullOrEmpty(m_strControlOrientation)) + + if (!string.IsNullOrEmpty(this.m_strControlOrientation)) { - switch (m_strControlOrientation.ToLowerInvariant()) + switch (this.m_strControlOrientation.ToLowerInvariant()) { case "horizontal": - Control.ControlOrientation = NavigationProvider.Orientation.Horizontal; + this.Control.ControlOrientation = NavigationProvider.Orientation.Horizontal; break; case "vertical": - Control.ControlOrientation = NavigationProvider.Orientation.Vertical; + this.Control.ControlOrientation = NavigationProvider.Orientation.Vertical; break; } } - if (!String.IsNullOrEmpty(m_strControlAlignment)) + + if (!string.IsNullOrEmpty(this.m_strControlAlignment)) { - switch (m_strControlAlignment.ToLowerInvariant()) + switch (this.m_strControlAlignment.ToLowerInvariant()) { case "left": - Control.ControlAlignment = NavigationProvider.Alignment.Left; + this.Control.ControlAlignment = NavigationProvider.Alignment.Left; break; case "right": - Control.ControlAlignment = NavigationProvider.Alignment.Right; + this.Control.ControlAlignment = NavigationProvider.Alignment.Right; break; case "center": - Control.ControlAlignment = NavigationProvider.Alignment.Center; + this.Control.ControlAlignment = NavigationProvider.Alignment.Center; break; case "justify": - Control.ControlAlignment = NavigationProvider.Alignment.Justify; + this.Control.ControlAlignment = NavigationProvider.Alignment.Justify; break; } } - Control.ForceCrawlerDisplay = GetValue(m_strForceCrawlerDisplay, "False"); - Control.ForceDownLevel = GetValue(m_strForceDownLevel, "False"); - if (!String.IsNullOrEmpty(m_strMouseOutHideDelay)) + + this.Control.ForceCrawlerDisplay = this.GetValue(this.m_strForceCrawlerDisplay, "False"); + this.Control.ForceDownLevel = this.GetValue(this.m_strForceDownLevel, "False"); + if (!string.IsNullOrEmpty(this.m_strMouseOutHideDelay)) { - Control.MouseOutHideDelay = Convert.ToDecimal(m_strMouseOutHideDelay); + this.Control.MouseOutHideDelay = Convert.ToDecimal(this.m_strMouseOutHideDelay); } - if (!String.IsNullOrEmpty(m_strMouseOverDisplay)) + + if (!string.IsNullOrEmpty(this.m_strMouseOverDisplay)) { - switch (m_strMouseOverDisplay.ToLowerInvariant()) + switch (this.m_strMouseOverDisplay.ToLowerInvariant()) { case "highlight": - Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Highlight; + this.Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Highlight; break; case "outset": - Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Outset; + this.Control.MouseOverDisplay = NavigationProvider.HoverDisplay.Outset; break; case "none": - Control.MouseOverDisplay = NavigationProvider.HoverDisplay.None; + this.Control.MouseOverDisplay = NavigationProvider.HoverDisplay.None; break; } } - if (Convert.ToBoolean(GetValue(m_strMouseOverAction, "True"))) + + if (Convert.ToBoolean(this.GetValue(this.m_strMouseOverAction, "True"))) { - Control.MouseOverAction = NavigationProvider.HoverAction.Expand; + this.Control.MouseOverAction = NavigationProvider.HoverAction.Expand; } else { - Control.MouseOverAction = NavigationProvider.HoverAction.None; + this.Control.MouseOverAction = NavigationProvider.HoverAction.None; } - Control.IndicateChildren = Convert.ToBoolean(GetValue(m_strIndicateChildren, "True")); - if (!String.IsNullOrEmpty(m_strIndicateChildImageRoot)) + + this.Control.IndicateChildren = Convert.ToBoolean(this.GetValue(this.m_strIndicateChildren, "True")); + if (!string.IsNullOrEmpty(this.m_strIndicateChildImageRoot)) { - Control.IndicateChildImageRoot = m_strIndicateChildImageRoot; + this.Control.IndicateChildImageRoot = this.m_strIndicateChildImageRoot; } - if (!String.IsNullOrEmpty(m_strIndicateChildImageSub)) + + if (!string.IsNullOrEmpty(this.m_strIndicateChildImageSub)) { - Control.IndicateChildImageSub = m_strIndicateChildImageSub; + this.Control.IndicateChildImageSub = this.m_strIndicateChildImageSub; } - if (!String.IsNullOrEmpty(m_strIndicateChildImageExpandedRoot)) + + if (!string.IsNullOrEmpty(this.m_strIndicateChildImageExpandedRoot)) { - Control.IndicateChildImageExpandedRoot = m_strIndicateChildImageExpandedRoot; + this.Control.IndicateChildImageExpandedRoot = this.m_strIndicateChildImageExpandedRoot; } - if (!String.IsNullOrEmpty(m_strIndicateChildImageExpandedSub)) + + if (!string.IsNullOrEmpty(this.m_strIndicateChildImageExpandedSub)) { - Control.IndicateChildImageExpandedSub = m_strIndicateChildImageExpandedSub; + this.Control.IndicateChildImageExpandedSub = this.m_strIndicateChildImageExpandedSub; } - if (!String.IsNullOrEmpty(m_strNodeLeftHTMLRoot)) + + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLRoot)) { - Control.NodeLeftHTMLRoot = m_strNodeLeftHTMLRoot; + this.Control.NodeLeftHTMLRoot = this.m_strNodeLeftHTMLRoot; } - if (!String.IsNullOrEmpty(m_strNodeRightHTMLRoot)) + + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLRoot)) { - Control.NodeRightHTMLRoot = m_strNodeRightHTMLRoot; + this.Control.NodeRightHTMLRoot = this.m_strNodeRightHTMLRoot; } - if (!String.IsNullOrEmpty(m_strNodeLeftHTMLSub)) + + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLSub)) { - Control.NodeLeftHTMLSub = m_strNodeLeftHTMLSub; + this.Control.NodeLeftHTMLSub = this.m_strNodeLeftHTMLSub; } - if (!String.IsNullOrEmpty(m_strNodeRightHTMLSub)) + + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLSub)) { - Control.NodeRightHTMLSub = m_strNodeRightHTMLSub; + this.Control.NodeRightHTMLSub = this.m_strNodeRightHTMLSub; } - if (!String.IsNullOrEmpty(m_strNodeLeftHTMLBreadCrumbRoot)) + + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLBreadCrumbRoot)) { - Control.NodeLeftHTMLBreadCrumbRoot = m_strNodeLeftHTMLBreadCrumbRoot; + this.Control.NodeLeftHTMLBreadCrumbRoot = this.m_strNodeLeftHTMLBreadCrumbRoot; } - if (!String.IsNullOrEmpty(m_strNodeLeftHTMLBreadCrumbSub)) + + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLBreadCrumbSub)) { - Control.NodeLeftHTMLBreadCrumbSub = m_strNodeLeftHTMLBreadCrumbSub; + this.Control.NodeLeftHTMLBreadCrumbSub = this.m_strNodeLeftHTMLBreadCrumbSub; } - if (!String.IsNullOrEmpty(m_strNodeRightHTMLBreadCrumbRoot)) + + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLBreadCrumbRoot)) { - Control.NodeRightHTMLBreadCrumbRoot = m_strNodeRightHTMLBreadCrumbRoot; + this.Control.NodeRightHTMLBreadCrumbRoot = this.m_strNodeRightHTMLBreadCrumbRoot; } - if (!String.IsNullOrEmpty(m_strNodeRightHTMLBreadCrumbSub)) + + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLBreadCrumbSub)) { - Control.NodeRightHTMLBreadCrumbSub = m_strNodeRightHTMLBreadCrumbSub; + this.Control.NodeRightHTMLBreadCrumbSub = this.m_strNodeRightHTMLBreadCrumbSub; } - if (!String.IsNullOrEmpty(m_strSeparatorHTML)) + + if (!string.IsNullOrEmpty(this.m_strSeparatorHTML)) { - Control.SeparatorHTML = m_strSeparatorHTML; + this.Control.SeparatorHTML = this.m_strSeparatorHTML; } - if (!String.IsNullOrEmpty(m_strSeparatorLeftHTML)) + + if (!string.IsNullOrEmpty(this.m_strSeparatorLeftHTML)) { - Control.SeparatorLeftHTML = m_strSeparatorLeftHTML; + this.Control.SeparatorLeftHTML = this.m_strSeparatorLeftHTML; } - if (!String.IsNullOrEmpty(m_strSeparatorRightHTML)) + + if (!string.IsNullOrEmpty(this.m_strSeparatorRightHTML)) { - Control.SeparatorRightHTML = m_strSeparatorRightHTML; + this.Control.SeparatorRightHTML = this.m_strSeparatorRightHTML; } - if (!String.IsNullOrEmpty(m_strSeparatorLeftHTMLActive)) + + if (!string.IsNullOrEmpty(this.m_strSeparatorLeftHTMLActive)) { - Control.SeparatorLeftHTMLActive = m_strSeparatorLeftHTMLActive; + this.Control.SeparatorLeftHTMLActive = this.m_strSeparatorLeftHTMLActive; } - if (!String.IsNullOrEmpty(m_strSeparatorRightHTMLActive)) + + if (!string.IsNullOrEmpty(this.m_strSeparatorRightHTMLActive)) { - Control.SeparatorRightHTMLActive = m_strSeparatorRightHTMLActive; + this.Control.SeparatorRightHTMLActive = this.m_strSeparatorRightHTMLActive; } - if (!String.IsNullOrEmpty(m_strSeparatorLeftHTMLBreadCrumb)) + + if (!string.IsNullOrEmpty(this.m_strSeparatorLeftHTMLBreadCrumb)) { - Control.SeparatorLeftHTMLBreadCrumb = m_strSeparatorLeftHTMLBreadCrumb; + this.Control.SeparatorLeftHTMLBreadCrumb = this.m_strSeparatorLeftHTMLBreadCrumb; } - if (!String.IsNullOrEmpty(m_strSeparatorRightHTMLBreadCrumb)) + + if (!string.IsNullOrEmpty(this.m_strSeparatorRightHTMLBreadCrumb)) { - Control.SeparatorRightHTMLBreadCrumb = m_strSeparatorRightHTMLBreadCrumb; + this.Control.SeparatorRightHTMLBreadCrumb = this.m_strSeparatorRightHTMLBreadCrumb; } - if (!String.IsNullOrEmpty(m_strCSSControl)) + + if (!string.IsNullOrEmpty(this.m_strCSSControl)) { - Control.CSSControl = m_strCSSControl; + this.Control.CSSControl = this.m_strCSSControl; } - if (!String.IsNullOrEmpty(m_strCSSContainerRoot)) + + if (!string.IsNullOrEmpty(this.m_strCSSContainerRoot)) { - Control.CSSContainerRoot = m_strCSSContainerRoot; + this.Control.CSSContainerRoot = this.m_strCSSContainerRoot; } - if (!String.IsNullOrEmpty(m_strCSSNode)) + + if (!string.IsNullOrEmpty(this.m_strCSSNode)) { - Control.CSSNode = m_strCSSNode; + this.Control.CSSNode = this.m_strCSSNode; } - if (!String.IsNullOrEmpty(m_strCSSIcon)) + + if (!string.IsNullOrEmpty(this.m_strCSSIcon)) { - Control.CSSIcon = m_strCSSIcon; + this.Control.CSSIcon = this.m_strCSSIcon; } - if (!String.IsNullOrEmpty(m_strCSSContainerSub)) + + if (!string.IsNullOrEmpty(this.m_strCSSContainerSub)) { - Control.CSSContainerSub = m_strCSSContainerSub; + this.Control.CSSContainerSub = this.m_strCSSContainerSub; } - if (!String.IsNullOrEmpty(m_strCSSNodeHover)) + + if (!string.IsNullOrEmpty(this.m_strCSSNodeHover)) { - Control.CSSNodeHover = m_strCSSNodeHover; + this.Control.CSSNodeHover = this.m_strCSSNodeHover; } - if (!String.IsNullOrEmpty(m_strCSSBreak)) + + if (!string.IsNullOrEmpty(this.m_strCSSBreak)) { - Control.CSSBreak = m_strCSSBreak; + this.Control.CSSBreak = this.m_strCSSBreak; } - if (!String.IsNullOrEmpty(m_strCSSIndicateChildSub)) + + if (!string.IsNullOrEmpty(this.m_strCSSIndicateChildSub)) { - Control.CSSIndicateChildSub = m_strCSSIndicateChildSub; + this.Control.CSSIndicateChildSub = this.m_strCSSIndicateChildSub; } - if (!String.IsNullOrEmpty(m_strCSSIndicateChildRoot)) + + if (!string.IsNullOrEmpty(this.m_strCSSIndicateChildRoot)) { - Control.CSSIndicateChildRoot = m_strCSSIndicateChildRoot; + this.Control.CSSIndicateChildRoot = this.m_strCSSIndicateChildRoot; } - if (!String.IsNullOrEmpty(m_strCSSBreadCrumbRoot)) + + if (!string.IsNullOrEmpty(this.m_strCSSBreadCrumbRoot)) { - Control.CSSBreadCrumbRoot = m_strCSSBreadCrumbRoot; + this.Control.CSSBreadCrumbRoot = this.m_strCSSBreadCrumbRoot; } - if (!String.IsNullOrEmpty(m_strCSSBreadCrumbSub)) + + if (!string.IsNullOrEmpty(this.m_strCSSBreadCrumbSub)) { - Control.CSSBreadCrumbSub = m_strCSSBreadCrumbSub; + this.Control.CSSBreadCrumbSub = this.m_strCSSBreadCrumbSub; } - if (!String.IsNullOrEmpty(m_strCSSNodeRoot)) + + if (!string.IsNullOrEmpty(this.m_strCSSNodeRoot)) { - Control.CSSNodeRoot = m_strCSSNodeRoot; + this.Control.CSSNodeRoot = this.m_strCSSNodeRoot; } - if (!String.IsNullOrEmpty(m_strCSSNodeSelectedRoot)) + + if (!string.IsNullOrEmpty(this.m_strCSSNodeSelectedRoot)) { - Control.CSSNodeSelectedRoot = m_strCSSNodeSelectedRoot; + this.Control.CSSNodeSelectedRoot = this.m_strCSSNodeSelectedRoot; } - if (!String.IsNullOrEmpty(m_strCSSNodeSelectedSub)) + + if (!string.IsNullOrEmpty(this.m_strCSSNodeSelectedSub)) { - Control.CSSNodeSelectedSub = m_strCSSNodeSelectedSub; + this.Control.CSSNodeSelectedSub = this.m_strCSSNodeSelectedSub; } - if (!String.IsNullOrEmpty(m_strCSSNodeHoverRoot)) + + if (!string.IsNullOrEmpty(this.m_strCSSNodeHoverRoot)) { - Control.CSSNodeHoverRoot = m_strCSSNodeHoverRoot; + this.Control.CSSNodeHoverRoot = this.m_strCSSNodeHoverRoot; } - if (!String.IsNullOrEmpty(m_strCSSNodeHoverSub)) + + if (!string.IsNullOrEmpty(this.m_strCSSNodeHoverSub)) { - Control.CSSNodeHoverSub = m_strCSSNodeHoverSub; + this.Control.CSSNodeHoverSub = this.m_strCSSNodeHoverSub; } - if (!String.IsNullOrEmpty(m_strCSSSeparator)) + + if (!string.IsNullOrEmpty(this.m_strCSSSeparator)) { - Control.CSSSeparator = m_strCSSSeparator; + this.Control.CSSSeparator = this.m_strCSSSeparator; } - if (!String.IsNullOrEmpty(m_strCSSLeftSeparator)) + + if (!string.IsNullOrEmpty(this.m_strCSSLeftSeparator)) { - Control.CSSLeftSeparator = m_strCSSLeftSeparator; + this.Control.CSSLeftSeparator = this.m_strCSSLeftSeparator; } - if (!String.IsNullOrEmpty(m_strCSSRightSeparator)) + + if (!string.IsNullOrEmpty(this.m_strCSSRightSeparator)) { - Control.CSSRightSeparator = m_strCSSRightSeparator; + this.Control.CSSRightSeparator = this.m_strCSSRightSeparator; } - if (!String.IsNullOrEmpty(m_strCSSLeftSeparatorSelection)) + + if (!string.IsNullOrEmpty(this.m_strCSSLeftSeparatorSelection)) { - Control.CSSLeftSeparatorSelection = m_strCSSLeftSeparatorSelection; + this.Control.CSSLeftSeparatorSelection = this.m_strCSSLeftSeparatorSelection; } - if (!String.IsNullOrEmpty(m_strCSSRightSeparatorSelection)) + + if (!string.IsNullOrEmpty(this.m_strCSSRightSeparatorSelection)) { - Control.CSSRightSeparatorSelection = m_strCSSRightSeparatorSelection; + this.Control.CSSRightSeparatorSelection = this.m_strCSSRightSeparatorSelection; } - if (!String.IsNullOrEmpty(m_strCSSLeftSeparatorBreadCrumb)) + + if (!string.IsNullOrEmpty(this.m_strCSSLeftSeparatorBreadCrumb)) { - Control.CSSLeftSeparatorBreadCrumb = m_strCSSLeftSeparatorBreadCrumb; + this.Control.CSSLeftSeparatorBreadCrumb = this.m_strCSSLeftSeparatorBreadCrumb; } - if (!String.IsNullOrEmpty(m_strCSSRightSeparatorBreadCrumb)) + + if (!string.IsNullOrEmpty(this.m_strCSSRightSeparatorBreadCrumb)) { - Control.CSSRightSeparatorBreadCrumb = m_strCSSRightSeparatorBreadCrumb; + this.Control.CSSRightSeparatorBreadCrumb = this.m_strCSSRightSeparatorBreadCrumb; } - if (!String.IsNullOrEmpty(m_strStyleBackColor)) + + if (!string.IsNullOrEmpty(this.m_strStyleBackColor)) { - Control.StyleBackColor = m_strStyleBackColor; + this.Control.StyleBackColor = this.m_strStyleBackColor; } - if (!String.IsNullOrEmpty(m_strStyleForeColor)) + + if (!string.IsNullOrEmpty(this.m_strStyleForeColor)) { - Control.StyleForeColor = m_strStyleForeColor; + this.Control.StyleForeColor = this.m_strStyleForeColor; } - if (!String.IsNullOrEmpty(m_strStyleHighlightColor)) + + if (!string.IsNullOrEmpty(this.m_strStyleHighlightColor)) { - Control.StyleHighlightColor = m_strStyleHighlightColor; + this.Control.StyleHighlightColor = this.m_strStyleHighlightColor; } - if (!String.IsNullOrEmpty(m_strStyleIconBackColor)) + + if (!string.IsNullOrEmpty(this.m_strStyleIconBackColor)) { - Control.StyleIconBackColor = m_strStyleIconBackColor; + this.Control.StyleIconBackColor = this.m_strStyleIconBackColor; } - if (!String.IsNullOrEmpty(m_strStyleSelectionBorderColor)) + + if (!string.IsNullOrEmpty(this.m_strStyleSelectionBorderColor)) { - Control.StyleSelectionBorderColor = m_strStyleSelectionBorderColor; + this.Control.StyleSelectionBorderColor = this.m_strStyleSelectionBorderColor; } - if (!String.IsNullOrEmpty(m_strStyleSelectionColor)) + + if (!string.IsNullOrEmpty(this.m_strStyleSelectionColor)) { - Control.StyleSelectionColor = m_strStyleSelectionColor; + this.Control.StyleSelectionColor = this.m_strStyleSelectionColor; } - if (!String.IsNullOrEmpty(m_strStyleSelectionForeColor)) + + if (!string.IsNullOrEmpty(this.m_strStyleSelectionForeColor)) { - Control.StyleSelectionForeColor = m_strStyleSelectionForeColor; + this.Control.StyleSelectionForeColor = this.m_strStyleSelectionForeColor; } - if (!String.IsNullOrEmpty(m_strStyleControlHeight)) + + if (!string.IsNullOrEmpty(this.m_strStyleControlHeight)) { - Control.StyleControlHeight = Convert.ToDecimal(m_strStyleControlHeight); + this.Control.StyleControlHeight = Convert.ToDecimal(this.m_strStyleControlHeight); } - if (!String.IsNullOrEmpty(m_strStyleBorderWidth)) + + if (!string.IsNullOrEmpty(this.m_strStyleBorderWidth)) { - Control.StyleBorderWidth = Convert.ToDecimal(m_strStyleBorderWidth); + this.Control.StyleBorderWidth = Convert.ToDecimal(this.m_strStyleBorderWidth); } - if (!String.IsNullOrEmpty(m_strStyleNodeHeight)) + + if (!string.IsNullOrEmpty(this.m_strStyleNodeHeight)) { - Control.StyleNodeHeight = Convert.ToDecimal(m_strStyleNodeHeight); + this.Control.StyleNodeHeight = Convert.ToDecimal(this.m_strStyleNodeHeight); } - if (!String.IsNullOrEmpty(m_strStyleIconWidth)) + + if (!string.IsNullOrEmpty(this.m_strStyleIconWidth)) { - Control.StyleIconWidth = Convert.ToDecimal(m_strStyleIconWidth); + this.Control.StyleIconWidth = Convert.ToDecimal(this.m_strStyleIconWidth); } - if (!String.IsNullOrEmpty(m_strStyleFontNames)) + + if (!string.IsNullOrEmpty(this.m_strStyleFontNames)) { - Control.StyleFontNames = m_strStyleFontNames; + this.Control.StyleFontNames = this.m_strStyleFontNames; } - if (!String.IsNullOrEmpty(m_strStyleFontSize)) + + if (!string.IsNullOrEmpty(this.m_strStyleFontSize)) { - Control.StyleFontSize = Convert.ToDecimal(m_strStyleFontSize); + this.Control.StyleFontSize = Convert.ToDecimal(this.m_strStyleFontSize); } - if (!String.IsNullOrEmpty(m_strStyleFontBold)) + + if (!string.IsNullOrEmpty(this.m_strStyleFontBold)) { - Control.StyleFontBold = m_strStyleFontBold; + this.Control.StyleFontBold = this.m_strStyleFontBold; } - if (!String.IsNullOrEmpty(m_strEffectsShadowColor)) + + if (!string.IsNullOrEmpty(this.m_strEffectsShadowColor)) { - Control.EffectsShadowColor = m_strEffectsShadowColor; + this.Control.EffectsShadowColor = this.m_strEffectsShadowColor; } - if (!String.IsNullOrEmpty(m_strEffectsStyle)) + + if (!string.IsNullOrEmpty(this.m_strEffectsStyle)) { - Control.EffectsStyle = m_strEffectsStyle; + this.Control.EffectsStyle = this.m_strEffectsStyle; } - if (!String.IsNullOrEmpty(m_strEffectsShadowStrength)) + + if (!string.IsNullOrEmpty(this.m_strEffectsShadowStrength)) { - Control.EffectsShadowStrength = Convert.ToInt32(m_strEffectsShadowStrength); + this.Control.EffectsShadowStrength = Convert.ToInt32(this.m_strEffectsShadowStrength); } - if (!String.IsNullOrEmpty(m_strEffectsTransition)) + + if (!string.IsNullOrEmpty(this.m_strEffectsTransition)) { - Control.EffectsTransition = m_strEffectsTransition; + this.Control.EffectsTransition = this.m_strEffectsTransition; } - if (!String.IsNullOrEmpty(m_strEffectsDuration)) + + if (!string.IsNullOrEmpty(this.m_strEffectsDuration)) { - Control.EffectsDuration = Convert.ToDouble(m_strEffectsDuration); + this.Control.EffectsDuration = Convert.ToDouble(this.m_strEffectsDuration); } - if (!String.IsNullOrEmpty(m_strEffectsShadowDirection)) + + if (!string.IsNullOrEmpty(this.m_strEffectsShadowDirection)) { - Control.EffectsShadowDirection = m_strEffectsShadowDirection; + this.Control.EffectsShadowDirection = this.m_strEffectsShadowDirection; } - Control.CustomAttributes = CustomAttributes; - } - - protected void Bind(DNNNodeCollection objNodes) - { - Control.Bind(objNodes); + + this.Control.CustomAttributes = this.CustomAttributes; } private string GetPath(string strPath) { if (strPath.IndexOf("[SKINPATH]") > -1) { - return strPath.Replace("[SKINPATH]", PortalSettings.ActiveTab.SkinPath); + return strPath.Replace("[SKINPATH]", this.PortalSettings.ActiveTab.SkinPath); } else if (strPath.IndexOf("[APPIMAGEPATH]") > -1) { @@ -2682,20 +2825,19 @@ private string GetPath(string strPath) } else if (strPath.IndexOf("[HOMEDIRECTORY]") > -1) { - return strPath.Replace("[HOMEDIRECTORY]", PortalSettings.HomeDirectory); + return strPath.Replace("[HOMEDIRECTORY]", this.PortalSettings.HomeDirectory); } else { if (strPath.StartsWith("~")) { - return ResolveUrl(strPath); + return this.ResolveUrl(strPath); } } + return strPath; - } - - #endregion - } + } + } public class CustomAttribute { diff --git a/DNN Platform/Library/UI/Skins/Pane.cs b/DNN Platform/Library/UI/Skins/Pane.cs index 31261dbe1c3..3cf8eac8836 100644 --- a/DNN Platform/Library/UI/Skins/Pane.cs +++ b/DNN Platform/Library/UI/Skins/Pane.cs @@ -1,89 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI.Containers; -using DotNetNuke.UI.Utilities; -using DotNetNuke.UI.WebControls; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Threading; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.Containers; + using DotNetNuke.UI.Utilities; + using DotNetNuke.UI.WebControls; + + using Globals = DotNetNuke.Common.Globals; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Skins - /// Class : Pane + /// Class : Pane /// ----------------------------------------------------------------------------- /// - /// The Pane class represents a Pane within the Skin + /// The Pane class represents a Pane within the Skin. /// /// /// /// ----------------------------------------------------------------------------- public class Pane - { - #region Private Members - + { private const string CPaneOutline = "paneOutline"; private HtmlGenericControl _containerWrapperControl; - private Dictionary _containers; - - #endregion - - #region Constructors - + private Dictionary _containers; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new Pane object from the Control in the Skin + /// + /// Initializes a new instance of the class. + /// Constructs a new Pane object from the Control in the Skin. /// /// The HtmlContainerControl in the Skin. /// ----------------------------------------------------------------------------- public Pane(HtmlContainerControl pane) { - PaneControl = pane; - //Disable ViewState (we enable it later in the process) - PaneControl.ViewStateMode = ViewStateMode.Disabled; - Name = pane.ID; - } - + this.PaneControl = pane; + + // Disable ViewState (we enable it later in the process) + this.PaneControl.ViewStateMode = ViewStateMode.Disabled; + this.Name = pane.ID; + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new Pane object from the Control in the Skin + /// + /// Initializes a new instance of the class. + /// Constructs a new Pane object from the Control in the Skin. /// - /// The name (ID) of the HtmlContainerControl + /// The name (ID) of the HtmlContainerControl. /// The HtmlContainerControl in the Skin. /// ----------------------------------------------------------------------------- public Pane(string name, HtmlContainerControl pane) { - PaneControl = pane; - Name = name; - } - - #endregion - - #region Protected Properties - + this.PaneControl = pane; + this.Name = name; + } + /// ----------------------------------------------------------------------------- /// /// Gets a Dictionary of Containers. @@ -93,27 +81,27 @@ public Pane(string name, HtmlContainerControl pane) { get { - return _containers ?? (_containers = new Dictionary()); + return this._containers ?? (this._containers = new Dictionary()); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the name (ID) of the Pane + /// Gets or sets and sets the name (ID) of the Pane. /// /// ----------------------------------------------------------------------------- protected string Name { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the HtmlContainerControl + /// Gets or sets and sets the HtmlContainerControl. /// /// ----------------------------------------------------------------------------- protected HtmlContainerControl PaneControl { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the PortalSettings of the Portal + /// Gets the PortalSettings of the Portal. /// /// ----------------------------------------------------------------------------- protected PortalSettings PortalSettings @@ -123,50 +111,244 @@ protected PortalSettings PortalSettings return PortalController.Instance.GetCurrentPortalSettings(); } } + + /// ----------------------------------------------------------------------------- + /// + /// InjectModule injects a Module (and its container) into the Pane. + /// + /// The Module. + /// ----------------------------------------------------------------------------- + public void InjectModule(ModuleInfo module) + { + this._containerWrapperControl = new HtmlGenericControl("div"); + this.PaneControl.Controls.Add(this._containerWrapperControl); + + // inject module classes + string classFormatString = "DnnModule DnnModule-{0} DnnModule-{1}"; + string sanitizedModuleName = Null.NullString; + + if (!string.IsNullOrEmpty(module.DesktopModule.ModuleName)) + { + sanitizedModuleName = Globals.CreateValidClass(module.DesktopModule.ModuleName, false); + } + + if (this.IsVesionableModule(module)) + { + classFormatString += " DnnVersionableControl"; + } + + this._containerWrapperControl.Attributes["class"] = string.Format(classFormatString, sanitizedModuleName, module.ModuleID); + + try + { + if (!Globals.IsAdminControl() && (this.PortalSettings.InjectModuleHyperLink || this.PortalSettings.UserMode != PortalSettings.Mode.View)) + { + this._containerWrapperControl.Controls.Add(new LiteralControl("")); + } + + // Load container control + Containers.Container container = this.LoadModuleContainer(module); + + // Add Container to Dictionary + this.Containers.Add(container.ID, container); + + // hide anything of type ActionsMenu - as we're injecting our own menu now. + container.InjectActionMenu = container.Controls.OfType().Count() == 0; + if (!container.InjectActionMenu) + { + foreach (var actionControl in container.Controls.OfType()) + { + if (actionControl is ActionsMenu) + { + Control control = actionControl as Control; + if (control != null) + { + control.Visible = false; + container.InjectActionMenu = true; + } + } + } + } + + if (Globals.IsLayoutMode() && Globals.IsAdminControl() == false) + { + // provide Drag-N-Drop capabilities + var dragDropContainer = new Panel(); + Control title = container.FindControl("dnnTitle"); + + // Assume that the title control is named dnnTitle. If this becomes an issue we could loop through the controls looking for the title type of skin object + dragDropContainer.ID = container.ID + "_DD"; + this._containerWrapperControl.Controls.Add(dragDropContainer); + + // inject the container into the page pane - this triggers the Pre_Init() event for the user control + dragDropContainer.Controls.Add(container); + + if (title != null) + { + if (title.Controls.Count > 0) + { + title = title.Controls[0]; + } + } + + // enable drag and drop + if (title != null) + { + // The title ID is actually the first child so we need to make sure at least one child exists + DNNClientAPI.EnableContainerDragAndDrop(title, dragDropContainer, module.ModuleID); + ClientAPI.RegisterPostBackEventHandler(this.PaneControl, "MoveToPane", this.ModuleMoveToPanePostBack, false); + } + } + else + { + this._containerWrapperControl.Controls.Add(container); + if (Globals.IsAdminControl()) + { + this._containerWrapperControl.Attributes["class"] += " DnnModule-Admin"; + } + } + + // Attach Module to Container + container.SetModuleConfiguration(module); + + // display collapsible page panes + if (this.PaneControl.Visible == false) + { + this.PaneControl.Visible = true; + } + } + catch (ThreadAbortException) + { + // Response.Redirect may called in module control's OnInit method, so it will cause ThreadAbortException, no need any action here. + } + catch (Exception exc) + { + var lex = new ModuleLoadException(string.Format(Skin.MODULEADD_ERROR, this.PaneControl.ID), exc); + if (TabPermissionController.CanAdminPage()) + { + // only display the error to administrators + this._containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, Skin.MODULELOAD_ERROR, lex).Container); + } + + Exceptions.LogException(exc); + throw lex; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// ProcessPane processes the Attributes for the PaneControl. + /// + /// ----------------------------------------------------------------------------- + public void ProcessPane() + { + if (this.PaneControl != null) + { + // remove excess skin non-validating attributes + this.PaneControl.Attributes.Remove("ContainerType"); + this.PaneControl.Attributes.Remove("ContainerName"); + this.PaneControl.Attributes.Remove("ContainerSrc"); + + if (Globals.IsLayoutMode()) + { + this.PaneControl.Visible = true; + + // display pane border + string cssclass = this.PaneControl.Attributes["class"]; + if (string.IsNullOrEmpty(cssclass)) + { + this.PaneControl.Attributes["class"] = CPaneOutline; + } + else + { + this.PaneControl.Attributes["class"] = cssclass.Replace(CPaneOutline, string.Empty).Trim().Replace(" ", " ") + " " + CPaneOutline; + } + + // display pane name + var ctlLabel = new Label { Text = "
    " + this.Name + "

    ", CssClass = "SubHead" }; + this.PaneControl.Controls.AddAt(0, ctlLabel); + } + else + { + if (this.PaneControl.Visible == false && TabPermissionController.CanAddContentToPage()) + { + this.PaneControl.Visible = true; + } + + if (this.CanCollapsePane()) + { + // This pane has no controls so set the width to 0 + if (this.PaneControl.Attributes["style"] != null) + { + this.PaneControl.Attributes.Remove("style"); + } + + if (this.PaneControl.Attributes["class"] != null) + { + this.PaneControl.Attributes["class"] = this.PaneControl.Attributes["class"] + " DNNEmptyPane"; + } + else + { + this.PaneControl.Attributes["class"] = "DNNEmptyPane"; + } + } + + // Add support for drag and drop + if (Globals.IsEditMode()) // this call also checks for permission + { + if (this.PaneControl.Attributes["class"] != null) + { + this.PaneControl.Attributes["class"] = this.PaneControl.Attributes["class"] + " dnnSortable"; + } + else + { + this.PaneControl.Attributes["class"] = "dnnSortable"; + } + } + } + } + } private bool CanCollapsePane() { - //This section sets the width to "0" on panes that have no modules. - //This preserves the integrity of the HTML syntax so we don't have to set - //the visiblity of a pane to false. Setting the visibility of a pane to - //false where there are colspans and rowspans can render the skin incorrectly. + // This section sets the width to "0" on panes that have no modules. + // This preserves the integrity of the HTML syntax so we don't have to set + // the visiblity of a pane to false. Setting the visibility of a pane to + // false where there are colspans and rowspans can render the skin incorrectly. bool canCollapsePane = true; - if (Containers.Count > 0) + if (this.Containers.Count > 0) { canCollapsePane = false; } - else if (PaneControl.Controls.Count == 1) + else if (this.PaneControl.Controls.Count == 1) { - //Pane contains 1 control + // Pane contains 1 control canCollapsePane = false; - var literal = PaneControl.Controls[0] as LiteralControl; + var literal = this.PaneControl.Controls[0] as LiteralControl; if (literal != null) { - //Check if the literal control is just whitespace - if so we can collapse panes - if (String.IsNullOrEmpty(HtmlUtils.StripWhiteSpace(literal.Text, false))) + // Check if the literal control is just whitespace - if so we can collapse panes + if (string.IsNullOrEmpty(HtmlUtils.StripWhiteSpace(literal.Text, false))) { canCollapsePane = true; } } } - else if (PaneControl.Controls.Count > 1) + else if (this.PaneControl.Controls.Count > 1) { - //Pane contains more than 1 control + // Pane contains more than 1 control canCollapsePane = false; } + return canCollapsePane; - } - - #endregion - - #region Private Methods - + } + /// ----------------------------------------------------------------------------- /// - /// LoadContainerByPath gets the Container from its Url(Path) + /// LoadContainerByPath gets the Container from its Url(Path). /// - /// The Url to the Container control - /// A Container + /// The Url to the Container control. + /// A Container. /// ----------------------------------------------------------------------------- private Containers.Container LoadContainerByPath(string containerPath) { @@ -185,43 +367,48 @@ private Containers.Container LoadContainerByPath(string containerPath) { containerPath = containerPath.Remove(0, Globals.ApplicationPath.Length); } - container = ControlUtilities.LoadControl(PaneControl.Page, containerPath); + + container = ControlUtilities.LoadControl(this.PaneControl.Page, containerPath); container.ContainerSrc = containerSrc; - //call databind so that any server logic in the container is executed + + // call databind so that any server logic in the container is executed container.DataBind(); } catch (Exception exc) { - //could not load user control + // could not load user control var lex = new ModuleLoadException(Skin.MODULELOAD_ERROR, exc); if (TabPermissionController.CanAdminPage()) { - //only display the error to administrators - _containerWrapperControl.Controls.Add(new ErrorContainer(PortalSettings, string.Format(Skin.CONTAINERLOAD_ERROR, containerPath), lex).Container); + // only display the error to administrators + this._containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, string.Format(Skin.CONTAINERLOAD_ERROR, containerPath), lex).Container); } + Exceptions.LogException(lex); } + return container; } /// ----------------------------------------------------------------------------- /// - /// LoadModuleContainer gets the Container for cookie + /// LoadModuleContainer gets the Container for cookie. /// /// Current Http Request. - /// A Container + /// A Container. /// ----------------------------------------------------------------------------- private Containers.Container LoadContainerFromCookie(HttpRequest request) { Containers.Container container = null; - HttpCookie cookie = request.Cookies["_ContainerSrc" + PortalSettings.PortalId]; + HttpCookie cookie = request.Cookies["_ContainerSrc" + this.PortalSettings.PortalId]; if (cookie != null) { - if (!String.IsNullOrEmpty(cookie.Value)) + if (!string.IsNullOrEmpty(cookie.Value)) { - container = LoadContainerByPath(SkinController.FormatSkinSrc(cookie.Value + ".ascx", PortalSettings)); + container = this.LoadContainerByPath(SkinController.FormatSkinSrc(cookie.Value + ".ascx", this.PortalSettings)); } } + return container; } @@ -231,27 +418,28 @@ private Containers.Container LoadContainerFromPane() string containerSrc; var validSrc = false; - if ((PaneControl.Attributes["ContainerType"] != null) && (PaneControl.Attributes["ContainerName"] != null)) + if ((this.PaneControl.Attributes["ContainerType"] != null) && (this.PaneControl.Attributes["ContainerName"] != null)) { - containerSrc = "[" + PaneControl.Attributes["ContainerType"] + "]" + SkinController.RootContainer + "/" + PaneControl.Attributes["ContainerName"] + "/" + - PaneControl.Attributes["ContainerSrc"]; + containerSrc = "[" + this.PaneControl.Attributes["ContainerType"] + "]" + SkinController.RootContainer + "/" + this.PaneControl.Attributes["ContainerName"] + "/" + + this.PaneControl.Attributes["ContainerSrc"]; validSrc = true; } else { - containerSrc = PaneControl.Attributes["ContainerSrc"]; + containerSrc = this.PaneControl.Attributes["ContainerSrc"]; if (containerSrc.Contains("/") && !(containerSrc.StartsWith("[g]", StringComparison.InvariantCultureIgnoreCase) || containerSrc.StartsWith("[l]", StringComparison.InvariantCultureIgnoreCase))) { - containerSrc = string.Format(SkinController.IsGlobalSkin(PortalSettings.ActiveTab.SkinSrc) ? "[G]containers/{0}" : "[L]containers/{0}", containerSrc.TrimStart('/')); + containerSrc = string.Format(SkinController.IsGlobalSkin(this.PortalSettings.ActiveTab.SkinSrc) ? "[G]containers/{0}" : "[L]containers/{0}", containerSrc.TrimStart('/')); validSrc = true; } } if (validSrc) { - containerSrc = SkinController.FormatSkinSrc(containerSrc, PortalSettings); - container = LoadContainerByPath(containerSrc); + containerSrc = SkinController.FormatSkinSrc(containerSrc, this.PortalSettings); + container = this.LoadContainerByPath(containerSrc); } + return container; } @@ -261,15 +449,16 @@ private Containers.Container LoadContainerFromQueryString(ModuleInfo module, Htt int previewModuleId = -1; if (request.QueryString["ModuleId"] != null) { - Int32.TryParse(request.QueryString["ModuleId"], out previewModuleId); + int.TryParse(request.QueryString["ModuleId"], out previewModuleId); } - //load user container ( based on cookie ) + // load user container ( based on cookie ) if ((request.QueryString["ContainerSrc"] != null) && (module.ModuleID == previewModuleId || previewModuleId == -1)) { - string containerSrc = SkinController.FormatSkinSrc(Globals.QueryStringDecode(request.QueryString["ContainerSrc"]) + ".ascx", PortalSettings); - container = LoadContainerByPath(containerSrc); + string containerSrc = SkinController.FormatSkinSrc(Globals.QueryStringDecode(request.QueryString["ContainerSrc"]) + ".ascx", this.PortalSettings); + container = this.LoadContainerByPath(containerSrc); } + return container; } @@ -278,118 +467,123 @@ private Containers.Container LoadNoContainer(ModuleInfo module) string noContainerSrc = "[G]" + SkinController.RootContainer + "/_default/No Container.ascx"; Containers.Container container = null; - //if the module specifies that no container should be used + // if the module specifies that no container should be used if (module.DisplayTitle == false) { - //always display container if the current user is the administrator or the module is being used in an admin case + // always display container if the current user is the administrator or the module is being used in an admin case bool displayTitle = ModulePermissionController.CanEditModuleContent(module) || Globals.IsAdminSkin(); - //unless the administrator is in view mode + + // unless the administrator is in view mode if (displayTitle) { - displayTitle = (PortalSettings.UserMode != PortalSettings.Mode.View); + displayTitle = this.PortalSettings.UserMode != PortalSettings.Mode.View; } if (displayTitle == false) { - container = LoadContainerByPath(SkinController.FormatSkinSrc(noContainerSrc, PortalSettings)); + container = this.LoadContainerByPath(SkinController.FormatSkinSrc(noContainerSrc, this.PortalSettings)); } } + return container; } - + private Containers.Container LoadModuleContainer(ModuleInfo module) { var containerSrc = Null.NullString; - var request = PaneControl.Page.Request; + var request = this.PaneControl.Page.Request; Containers.Container container = null; - if (PortalSettings.EnablePopUps && UrlUtils.InPopUp()) + if (this.PortalSettings.EnablePopUps && UrlUtils.InPopUp()) { containerSrc = module.ContainerPath + "popUpContainer.ascx"; - //Check Skin for a popup Container - if (module.ContainerSrc == PortalSettings.ActiveTab.ContainerSrc) + + // Check Skin for a popup Container + if (module.ContainerSrc == this.PortalSettings.ActiveTab.ContainerSrc) { if (File.Exists(HttpContext.Current.Server.MapPath(containerSrc))) { - container = LoadContainerByPath(containerSrc); + container = this.LoadContainerByPath(containerSrc); } } - //error loading container - load default popup container + // error loading container - load default popup container if (container == null) { containerSrc = Globals.HostPath + "Containers/_default/popUpContainer.ascx"; - container = LoadContainerByPath(containerSrc); + container = this.LoadContainerByPath(containerSrc); } } else { - container = (LoadContainerFromQueryString(module, request) ?? LoadContainerFromCookie(request)) ?? LoadNoContainer(module); + container = (this.LoadContainerFromQueryString(module, request) ?? this.LoadContainerFromCookie(request)) ?? this.LoadNoContainer(module); if (container == null) { - //Check Skin for Container - var masterModules = PortalSettings.ActiveTab.ChildModules; + // Check Skin for Container + var masterModules = this.PortalSettings.ActiveTab.ChildModules; if (masterModules.ContainsKey(module.ModuleID) && string.IsNullOrEmpty(masterModules[module.ModuleID].ContainerSrc)) { - //look for a container specification in the skin pane - if (PaneControl != null) + // look for a container specification in the skin pane + if (this.PaneControl != null) { - if ((PaneControl.Attributes["ContainerSrc"] != null)) + if (this.PaneControl.Attributes["ContainerSrc"] != null) { - container = LoadContainerFromPane(); + container = this.LoadContainerFromPane(); } } } } - //else load assigned container + // else load assigned container if (container == null) { containerSrc = module.ContainerSrc; - if (!String.IsNullOrEmpty(containerSrc)) + if (!string.IsNullOrEmpty(containerSrc)) { - containerSrc = SkinController.FormatSkinSrc(containerSrc, PortalSettings); - container = LoadContainerByPath(containerSrc); + containerSrc = SkinController.FormatSkinSrc(containerSrc, this.PortalSettings); + container = this.LoadContainerByPath(containerSrc); } } - //error loading container - load from tab + // error loading container - load from tab if (container == null) { - containerSrc = PortalSettings.ActiveTab.ContainerSrc; - if (!String.IsNullOrEmpty(containerSrc)) + containerSrc = this.PortalSettings.ActiveTab.ContainerSrc; + if (!string.IsNullOrEmpty(containerSrc)) { - containerSrc = SkinController.FormatSkinSrc(containerSrc, PortalSettings); - container = LoadContainerByPath(containerSrc); + containerSrc = SkinController.FormatSkinSrc(containerSrc, this.PortalSettings); + container = this.LoadContainerByPath(containerSrc); } } - //error loading container - load default + // error loading container - load default if (container == null) { - containerSrc = SkinController.FormatSkinSrc(SkinController.GetDefaultPortalContainer(), PortalSettings); - container = LoadContainerByPath(containerSrc); + containerSrc = SkinController.FormatSkinSrc(SkinController.GetDefaultPortalContainer(), this.PortalSettings); + container = this.LoadContainerByPath(containerSrc); } } - //Set container path + // Set container path module.ContainerPath = SkinController.FormatSkinPath(containerSrc); - //set container id to an explicit short name to reduce page payload + // set container id to an explicit short name to reduce page payload container.ID = "ctr"; - //make the container id unique for the page + + // make the container id unique for the page if (module.ModuleID > -1) { container.ID += module.ModuleID.ToString(); } + return container; } /// ----------------------------------------------------------------------------- /// - /// ModuleMoveToPanePostBack excutes when a module is moved by Drag-and-Drop + /// ModuleMoveToPanePostBack excutes when a module is moved by Drag-and-Drop. /// - /// A ClientAPIPostBackEventArgs object + /// A ClientAPIPostBackEventArgs object. /// ----------------------------------------------------------------------------- private void ModuleMoveToPanePostBack(ClientAPIPostBackEventArgs args) { @@ -403,220 +597,20 @@ private void ModuleMoveToPanePostBack(ClientAPIPostBackEventArgs args) ModuleController.Instance.UpdateModuleOrder(portalSettings.ActiveTab.TabID, moduleId, moduleOrder, paneName); ModuleController.Instance.UpdateTabModuleOrder(portalSettings.ActiveTab.TabID); - //Redirect to the same page to pick up changes - PaneControl.Page.Response.Redirect(PaneControl.Page.Request.RawUrl, true); + // Redirect to the same page to pick up changes + this.PaneControl.Page.Response.Redirect(this.PaneControl.Page.Request.RawUrl, true); } } - - + private bool IsVesionableModule(ModuleInfo moduleInfo) - { - if (String.IsNullOrEmpty(moduleInfo.DesktopModule.BusinessControllerClass)) + { + if (string.IsNullOrEmpty(moduleInfo.DesktopModule.BusinessControllerClass)) { return false; - } - - object controller = Framework.Reflection.CreateObject(moduleInfo.DesktopModule.BusinessControllerClass, ""); + } + + object controller = Framework.Reflection.CreateObject(moduleInfo.DesktopModule.BusinessControllerClass, string.Empty); return controller is IVersionable; - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// InjectModule injects a Module (and its container) into the Pane - /// - /// The Module - /// ----------------------------------------------------------------------------- - public void InjectModule(ModuleInfo module) - { - _containerWrapperControl = new HtmlGenericControl("div"); - PaneControl.Controls.Add(_containerWrapperControl); - - //inject module classes - string classFormatString = "DnnModule DnnModule-{0} DnnModule-{1}"; - string sanitizedModuleName = Null.NullString; - - if (!String.IsNullOrEmpty(module.DesktopModule.ModuleName)) - { - sanitizedModuleName = Globals.CreateValidClass(module.DesktopModule.ModuleName, false); - } - - if (IsVesionableModule(module)) - { - classFormatString += " DnnVersionableControl"; - } - - _containerWrapperControl.Attributes["class"] = String.Format(classFormatString, sanitizedModuleName, module.ModuleID); - - try - { - if (!Globals.IsAdminControl() && (PortalSettings.InjectModuleHyperLink || PortalSettings.UserMode != PortalSettings.Mode.View)) - { - _containerWrapperControl.Controls.Add(new LiteralControl("")); - } - - //Load container control - Containers.Container container = LoadModuleContainer(module); - - //Add Container to Dictionary - Containers.Add(container.ID, container); - - // hide anything of type ActionsMenu - as we're injecting our own menu now. - container.InjectActionMenu = (container.Controls.OfType().Count() == 0); - if (!container.InjectActionMenu) - { - foreach (var actionControl in container.Controls.OfType()) - { - if (actionControl is ActionsMenu) - { - Control control = actionControl as Control; - if (control != null) - { - control.Visible = false; - container.InjectActionMenu = true; - } - } - } - } - - if (Globals.IsLayoutMode() && Globals.IsAdminControl() == false) - { - //provide Drag-N-Drop capabilities - var dragDropContainer = new Panel(); - Control title = container.FindControl("dnnTitle"); - //Assume that the title control is named dnnTitle. If this becomes an issue we could loop through the controls looking for the title type of skin object - dragDropContainer.ID = container.ID + "_DD"; - _containerWrapperControl.Controls.Add(dragDropContainer); - - //inject the container into the page pane - this triggers the Pre_Init() event for the user control - dragDropContainer.Controls.Add(container); - - if (title != null) - { - if (title.Controls.Count > 0) - { - title = title.Controls[0]; - } - } - - //enable drag and drop - if (title != null) - { - //The title ID is actually the first child so we need to make sure at least one child exists - DNNClientAPI.EnableContainerDragAndDrop(title, dragDropContainer, module.ModuleID); - ClientAPI.RegisterPostBackEventHandler(PaneControl, "MoveToPane", ModuleMoveToPanePostBack, false); - } - } - else - { - _containerWrapperControl.Controls.Add(container); - if (Globals.IsAdminControl()) - { - _containerWrapperControl.Attributes["class"] += " DnnModule-Admin"; - } - } - - //Attach Module to Container - container.SetModuleConfiguration(module); - - //display collapsible page panes - if (PaneControl.Visible == false) - { - PaneControl.Visible = true; - } - } - catch (ThreadAbortException) - { - //Response.Redirect may called in module control's OnInit method, so it will cause ThreadAbortException, no need any action here. - } - catch (Exception exc) - { - var lex = new ModuleLoadException(string.Format(Skin.MODULEADD_ERROR, PaneControl.ID), exc); - if (TabPermissionController.CanAdminPage()) - { - //only display the error to administrators - _containerWrapperControl.Controls.Add(new ErrorContainer(PortalSettings, Skin.MODULELOAD_ERROR, lex).Container); - } - Exceptions.LogException(exc); - throw lex; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// ProcessPane processes the Attributes for the PaneControl - /// - /// ----------------------------------------------------------------------------- - public void ProcessPane() - { - if (PaneControl != null) - { - //remove excess skin non-validating attributes - PaneControl.Attributes.Remove("ContainerType"); - PaneControl.Attributes.Remove("ContainerName"); - PaneControl.Attributes.Remove("ContainerSrc"); - - if (Globals.IsLayoutMode()) - { - PaneControl.Visible = true; - - //display pane border - string cssclass = PaneControl.Attributes["class"]; - if (string.IsNullOrEmpty(cssclass)) - { - PaneControl.Attributes["class"] = CPaneOutline; - } - else - { - PaneControl.Attributes["class"] = cssclass.Replace(CPaneOutline, "").Trim().Replace(" ", " ") + " " + CPaneOutline; - } - //display pane name - var ctlLabel = new Label { Text = "
    " + Name + "

    ", CssClass = "SubHead" }; - PaneControl.Controls.AddAt(0, ctlLabel); - } - else - { - if (PaneControl.Visible == false && TabPermissionController.CanAddContentToPage()) - { - PaneControl.Visible = true; - } - - if (CanCollapsePane()) - { - //This pane has no controls so set the width to 0 - if (PaneControl.Attributes["style"] != null) - { - PaneControl.Attributes.Remove("style"); - } - if (PaneControl.Attributes["class"] != null) - { - PaneControl.Attributes["class"] = PaneControl.Attributes["class"] + " DNNEmptyPane"; - } - else - { - PaneControl.Attributes["class"] = "DNNEmptyPane"; - } - } - - //Add support for drag and drop - if (Globals.IsEditMode()) // this call also checks for permission - { - if (PaneControl.Attributes["class"] != null) - { - PaneControl.Attributes["class"] = PaneControl.Attributes["class"] + " dnnSortable"; - } - else - { - PaneControl.Attributes["class"] = "dnnSortable"; - } - } - } - } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Skins/Skin.cs b/DNN Platform/Library/UI/Skins/Skin.cs index 88978f1c1d3..c6c70050034 100644 --- a/DNN Platform/Library/UI/Skins/Skin.cs +++ b/DNN Platform/Library/UI/Skins/Skin.cs @@ -1,199 +1,259 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Application; -using DotNetNuke.Collections.Internal; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Modules.Communications; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.ControlPanels; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.Skins.EventListeners; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.VisualBasic; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Application; + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Modules.Communications; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.ControlPanels; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.Skins.EventListeners; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.VisualBasic; + + using Globals = DotNetNuke.Common.Globals; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Skins - /// Class : Skin + /// Class : Skin /// ----------------------------------------------------------------------------- /// - /// Skin is the base for the Skins + /// Skin is the base for the Skins. /// /// /// /// ----------------------------------------------------------------------------- public class Skin : UserControlBase - { - #region Public Constants - - // ReSharper disable InconsistentNaming + { + public const string OnInitMessage = "Skin_InitMessage"; + public const string OnInitMessageType = "Skin_InitMessageType"; + + // ReSharper disable InconsistentNaming public static string MODULELOAD_ERROR = Localization.GetString("ModuleLoad.Error"); public static string CONTAINERLOAD_ERROR = Localization.GetString("ContainerLoad.Error"); public static string MODULEADD_ERROR = Localization.GetString("ModuleAdd.Error"); - public const string OnInitMessage = "Skin_InitMessage"; - public const string OnInitMessageType = "Skin_InitMessageType"; - - private readonly ModuleCommunicate _communicator = new ModuleCommunicate(); - // ReSharper restore InconsistentNaming - - #endregion - - #region Private Members - + private readonly ModuleCommunicate _communicator = new ModuleCommunicate(); + + // ReSharper restore InconsistentNaming private ArrayList _actionEventListeners; private Control _controlPanel; - private Dictionary _panes; - - #endregion - + private Dictionary _panes; + public Skin() { - ModuleControlPipeline = Globals.DependencyProvider.GetRequiredService(); - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - #region Protected Properties - + this.ModuleControlPipeline = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + } + /// ----------------------------------------------------------------------------- /// - /// Gets the ControlPanel container. + /// Gets a Dictionary of Panes. /// /// /// /// ----------------------------------------------------------------------------- - internal Control ControlPanel + public Dictionary Panes { get { - return _controlPanel ?? (_controlPanel = FindControl("ControlPanel")); + return this._panes ?? (this._panes = new Dictionary()); } } - protected IModuleControlPipeline ModuleControlPipeline { get; } - protected INavigationManager NavigationManager { get; } - #endregion - - #region Friend Properties - /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleCommunicate instance for the skin + /// Gets or sets an ArrayList of ActionEventListeners. /// - /// The ModuleCommunicate instance for the Skin - internal ModuleCommunicate Communicator + /// ----------------------------------------------------------------------------- + public ArrayList ActionEventListeners { get { - return _communicator; + return this._actionEventListeners ?? (this._actionEventListeners = new ArrayList()); + } + + set + { + this._actionEventListeners = value; } } - #endregion - - #region Public Properties + /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Panes. + /// Gets the ControlPanel container. /// /// /// /// ----------------------------------------------------------------------------- - public Dictionary Panes + internal Control ControlPanel { get { - return _panes ?? (_panes = new Dictionary()); + return this._controlPanel ?? (this._controlPanel = this.FindControl("ControlPanel")); } } - + /// ----------------------------------------------------------------------------- /// - /// Gets an ArrayList of ActionEventListeners + /// Gets the ModuleCommunicate instance for the skin. /// - /// ----------------------------------------------------------------------------- - public ArrayList ActionEventListeners + /// The ModuleCommunicate instance for the Skin. + internal ModuleCommunicate Communicator { get { - return _actionEventListeners ?? (_actionEventListeners = new ArrayList()); - } - set - { - _actionEventListeners = value; + return this._communicator; } - } + } + + protected IModuleControlPipeline ModuleControlPipeline { get; } + + protected INavigationManager NavigationManager { get; } /// ----------------------------------------------------------------------------- /// - /// Gets the Path for this skin + /// Gets the Path for this skin. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string SkinPath { get { - return TemplateSourceDirectory + "/"; + return this.TemplateSourceDirectory + "/"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Source for this skin + /// Gets or sets the Source for this skin. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string SkinSrc { get; set; } + + public static void AddModuleMessage(PortalModuleBase control, string message, ModuleMessage.ModuleMessageType moduleMessageType) + { + AddModuleMessage(control, string.Empty, message, moduleMessageType, Null.NullString); + } + + public static void AddModuleMessage(PortalModuleBase control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) + { + AddModuleMessage(control, heading, message, moduleMessageType, Null.NullString); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnInit runs when the Skin is initialised. /// - /// A String /// ----------------------------------------------------------------------------- - public string SkinSrc { get; set; } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + // Load the Panes + this.LoadPanes(); + + // Load the Module Control(s) + bool success = Globals.IsAdminControl() ? this.ProcessSlaveModule() : this.ProcessMasterModules(); + + // Load the Control Panel + this.InjectControlPanel(); + + // Register any error messages on the Skin + if (this.Request.QueryString["error"] != null && Host.ShowCriticalErrors) + { + AddPageMessage(this, Localization.GetString("CriticalError.Error"), " ", ModuleMessage.ModuleMessageType.RedError); + + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) + { + ServicesFramework.Instance.RequestAjaxScriptSupport(); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + + JavaScript.RequestRegistration(CommonJs.jQueryUI); + JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn_dom); + ClientResourceManager.RegisterScript(this.Page, "~/resources/shared/scripts/dnn.logViewer.js"); + } + } + + if (!TabPermissionController.CanAdminPage() && !success) + { + // only display the warning to non-administrators (administrators will see the errors) + AddPageMessage(this, Localization.GetString("ModuleLoadWarning.Error"), string.Format(Localization.GetString("ModuleLoadWarning.Text"), this.PortalSettings.Email), ModuleMessage.ModuleMessageType.YellowWarning); + } + + this.InvokeSkinEvents(SkinEventType.OnSkinInit); + + if (HttpContext.Current != null && HttpContext.Current.Items.Contains(OnInitMessage)) + { + var messageType = ModuleMessage.ModuleMessageType.YellowWarning; + if (HttpContext.Current.Items.Contains(OnInitMessageType)) + { + messageType = (ModuleMessage.ModuleMessageType)Enum.Parse(typeof(ModuleMessage.ModuleMessageType), HttpContext.Current.Items[OnInitMessageType].ToString(), true); + } + + AddPageMessage(this, string.Empty, HttpContext.Current.Items[OnInitMessage].ToString(), messageType); + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + } - #endregion + // Process the Panes attributes + this.ProcessPanes(); + } - #region Private Methods + /// ----------------------------------------------------------------------------- + /// + /// OnLoad runs when the Skin is loaded. + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.InvokeSkinEvents(SkinEventType.OnSkinLoad); + } + private static void AddModuleMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconSrc) { if (control != null) { - if (!String.IsNullOrEmpty(message)) + if (!string.IsNullOrEmpty(message)) { var messagePlaceHolder = ControlUtilities.FindControl(control, "MessagePlaceHolder", true); if (messagePlaceHolder != null) @@ -208,7 +268,7 @@ private static void AddModuleMessage(Control control, string heading, string mes private static void AddPageMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconSrc) { - if (!String.IsNullOrEmpty(message)) + if (!string.IsNullOrEmpty(message)) { Control contentPane = FindControlRecursive(control, Globals.glbDefaultPane); @@ -222,38 +282,80 @@ private static void AddPageMessage(Control control, string heading, string messa private static Control FindControlRecursive(Control rootControl, string controlId) { - if (rootControl.ID == controlId) return rootControl; - + if (rootControl.ID == controlId) + { + return rootControl; + } + foreach (Control controlToSearch in rootControl.Controls) { Control controlToReturn = FindControlRecursive(controlToSearch, controlId); - if (controlToReturn != null) return controlToReturn; + if (controlToReturn != null) + { + return controlToReturn; + } } + return null; } - + private static Skin LoadSkin(PageBase page, string skinPath) + { + Skin ctlSkin = null; + try + { + string skinSrc = skinPath; + if (skinPath.IndexOf(Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase) != -1) + { + skinPath = skinPath.Remove(0, Globals.ApplicationPath.Length); + } + + ctlSkin = ControlUtilities.LoadControl(page, skinPath); + ctlSkin.SkinSrc = skinSrc; + + // call databind so that any server logic in the skin is executed + ctlSkin.DataBind(); + } + catch (Exception exc) + { + // could not load user control + var lex = new PageLoadException("Unhandled error loading page.", exc); + if (TabPermissionController.CanAdminPage()) + { + // only display the error to administrators + var skinError = (Label)page.FindControl("SkinError"); + skinError.Text = string.Format(Localization.GetString("SkinLoadError", Localization.GlobalResourceFile), skinPath, page.Server.HtmlEncode(exc.Message)); + skinError.Visible = true; + } + + Exceptions.LogException(lex); + } + + return ctlSkin; + } + private bool CheckExpired() { bool blnExpired = false; - if (PortalSettings.ExpiryDate != Null.NullDate) + if (this.PortalSettings.ExpiryDate != Null.NullDate) { - if (Convert.ToDateTime(PortalSettings.ExpiryDate) < DateTime.Now && !Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) + if (Convert.ToDateTime(this.PortalSettings.ExpiryDate) < DateTime.Now && !Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) { blnExpired = true; } } + return blnExpired; } private Pane GetPane(ModuleInfo module) { Pane pane; - bool found = Panes.TryGetValue(module.PaneName.ToLowerInvariant(), out pane); + bool found = this.Panes.TryGetValue(module.PaneName.ToLowerInvariant(), out pane); if (!found) { - Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); + this.Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); } return pane; @@ -261,19 +363,19 @@ private Pane GetPane(ModuleInfo module) private void InjectControlPanel() { - //if querystring dnnprintmode=true, controlpanel will not be shown - if (Request.QueryString["dnnprintmode"] != "true" && !UrlUtils.InPopUp() && Request.QueryString["hidecommandbar"] != "true") + // if querystring dnnprintmode=true, controlpanel will not be shown + if (this.Request.QueryString["dnnprintmode"] != "true" && !UrlUtils.InPopUp() && this.Request.QueryString["hidecommandbar"] != "true") { - if (Host.AllowControlPanelToDetermineVisibility || (ControlPanelBase.IsPageAdminInternal() || ControlPanelBase.IsModuleAdminInternal())) + if (Host.AllowControlPanelToDetermineVisibility || (ControlPanelBase.IsPageAdminInternal() || ControlPanelBase.IsModuleAdminInternal())) { - //ControlPanel processing + // ControlPanel processing var controlPanel = ControlUtilities.LoadControl(this, Host.ControlPanel); - var form = (HtmlForm)Parent.FindControl("Form"); + var form = (HtmlForm)this.Parent.FindControl("Form"); if (controlPanel.IncludeInControlHierarchy) { - //inject ControlPanel control into skin - if (ControlPanel == null || HostController.Instance.GetBoolean("IgnoreControlPanelWrapper", false)) + // inject ControlPanel control into skin + if (this.ControlPanel == null || HostController.Instance.GetBoolean("IgnoreControlPanelWrapper", false)) { if (form != null) { @@ -281,16 +383,16 @@ private void InjectControlPanel() } else { - Page.Controls.AddAt(0, controlPanel); + this.Page.Controls.AddAt(0, controlPanel); } } else { - ControlPanel.Controls.Add(controlPanel); + this.ControlPanel.Controls.Add(controlPanel); } - //register admin.css - ClientResourceManager.RegisterAdminStylesheet(Page, Globals.HostPath + "admin.css"); + // register admin.css + ClientResourceManager.RegisterAdminStylesheet(this.Page, Globals.HostPath + "admin.css"); } } } @@ -311,15 +413,15 @@ private void InvokeSkinEvents(SkinEventType skinEventType) private void LoadPanes() { - //iterate page controls - foreach (Control ctlControl in Controls) + // iterate page controls + foreach (Control ctlControl in this.Controls) { var objPaneControl = ctlControl as HtmlContainerControl; - //Panes must be runat=server controls so they have to have an ID + // Panes must be runat=server controls so they have to have an ID if (objPaneControl != null && !string.IsNullOrEmpty(objPaneControl.ID)) { - //load the skin panes + // load the skin panes switch (objPaneControl.TagName.ToLowerInvariant()) { case "td": @@ -332,84 +434,55 @@ private void LoadPanes() case "main": case "article": case "aside": - //content pane + // content pane if (!objPaneControl.ID.Equals("controlpanel", StringComparison.InvariantCultureIgnoreCase)) { - //Add to the PortalSettings (for use in the Control Panel) - PortalSettings.ActiveTab.Panes.Add(objPaneControl.ID); + // Add to the PortalSettings (for use in the Control Panel) + this.PortalSettings.ActiveTab.Panes.Add(objPaneControl.ID); - //Add to the Panes collection - Panes.Add(objPaneControl.ID.ToLowerInvariant(), new Pane(objPaneControl)); + // Add to the Panes collection + this.Panes.Add(objPaneControl.ID.ToLowerInvariant(), new Pane(objPaneControl)); } else { - //Control Panel pane - _controlPanel = objPaneControl; + // Control Panel pane + this._controlPanel = objPaneControl; } + break; } } } } - private static Skin LoadSkin(PageBase page, string skinPath) - { - Skin ctlSkin = null; - try - { - string skinSrc = skinPath; - if (skinPath.IndexOf(Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase) != -1) - { - skinPath = skinPath.Remove(0, Globals.ApplicationPath.Length); - } - ctlSkin = ControlUtilities.LoadControl(page, skinPath); - ctlSkin.SkinSrc = skinSrc; - //call databind so that any server logic in the skin is executed - ctlSkin.DataBind(); - } - catch (Exception exc) - { - //could not load user control - var lex = new PageLoadException("Unhandled error loading page.", exc); - if (TabPermissionController.CanAdminPage()) - { - //only display the error to administrators - var skinError = (Label)page.FindControl("SkinError"); - skinError.Text = string.Format(Localization.GetString("SkinLoadError", Localization.GlobalResourceFile), skinPath, page.Server.HtmlEncode(exc.Message)); - skinError.Visible = true; - } - Exceptions.LogException(lex); - } - return ctlSkin; - } - private bool ProcessModule(ModuleInfo module) { var success = true; - if (ModuleInjectionManager.CanInjectModule(module, PortalSettings)) + if (ModuleInjectionManager.CanInjectModule(module, this.PortalSettings)) { - //We need to ensure that Content Item exists since in old versions Content Items are not needed for modules - EnsureContentItemForModule(module); + // We need to ensure that Content Item exists since in old versions Content Items are not needed for modules + this.EnsureContentItemForModule(module); - Pane pane = GetPane(module); + Pane pane = this.GetPane(module); if (pane != null) { - success = InjectModule(pane, module); + success = this.InjectModule(pane, module); } else { var lex = new ModuleLoadException(Localization.GetString("PaneNotFound.Error")); - Controls.Add(new ErrorContainer(PortalSettings, MODULELOAD_ERROR, lex).Container); + this.Controls.Add(new ErrorContainer(this.PortalSettings, MODULELOAD_ERROR, lex).Container); Exceptions.LogException(lex); } } + return success; } /// - /// Handle access denied errors by displaying an error message - /// or by performing a redirect to a predefined "access denied URL" + /// Handle access denied errors by displaying an error message + /// or by performing a redirect to a predefined "access denied URL". /// /// private void HandleAccesDenied(bool redirect = false) @@ -418,11 +491,11 @@ private void HandleAccesDenied(bool redirect = false) if (redirect) { var redirectUrl = Globals.AccessDeniedURL(message); - Response.Redirect(redirectUrl, true); + this.Response.Redirect(redirectUrl, true); } else { - AddPageMessage(this, "", message, ModuleMessage.ModuleMessageType.YellowWarning); + AddPageMessage(this, string.Empty, message, ModuleMessage.ModuleMessageType.YellowWarning); } } @@ -431,13 +504,13 @@ private bool ProcessMasterModules() bool success = true; if (TabPermissionController.CanViewPage()) { - //We need to ensure that Content Item exists since in old versions Content Items are not needed for tabs - EnsureContentItemForTab(PortalSettings.ActiveTab); + // We need to ensure that Content Item exists since in old versions Content Items are not needed for tabs + this.EnsureContentItemForTab(this.PortalSettings.ActiveTab); // Versioning checks. if (!TabController.CurrentPage.HasAVisibleVersion) { - HandleAccesDenied(true); + this.HandleAccesDenied(true); } int urlVersion; @@ -445,70 +518,72 @@ private bool ProcessMasterModules() { if (!TabVersionUtils.CanSeeVersionedPages()) { - HandleAccesDenied(false); + this.HandleAccesDenied(false); return true; } if (TabVersionController.Instance.GetTabVersions(TabController.CurrentPage.TabID).All(tabVersion => tabVersion.Version != urlVersion)) { - Response.Redirect(NavigationManager.NavigateURL(PortalSettings.ErrorPage404, string.Empty, "status=404")); + this.Response.Redirect(this.NavigationManager.NavigateURL(this.PortalSettings.ErrorPage404, string.Empty, "status=404")); } } - //check portal expiry date - if (!CheckExpired()) + // check portal expiry date + if (!this.CheckExpired()) { - if ((PortalSettings.ActiveTab.StartDate < DateAndTime.Now && PortalSettings.ActiveTab.EndDate > DateAndTime.Now) || TabPermissionController.CanAdminPage() || Globals.IsLayoutMode()) + if ((this.PortalSettings.ActiveTab.StartDate < DateAndTime.Now && this.PortalSettings.ActiveTab.EndDate > DateAndTime.Now) || TabPermissionController.CanAdminPage() || Globals.IsLayoutMode()) { - foreach (var objModule in PortalSettingsController.Instance().GetTabModules(PortalSettings)) + foreach (var objModule in PortalSettingsController.Instance().GetTabModules(this.PortalSettings)) { - success = ProcessModule(objModule); + success = this.ProcessModule(objModule); } } else { - HandleAccesDenied(false); + this.HandleAccesDenied(false); } } else { - AddPageMessage(this, - "", - string.Format(Localization.GetString("ContractExpired.Error"), PortalSettings.PortalName, Globals.GetMediumDate(PortalSettings.ExpiryDate.ToString(CultureInfo.InvariantCulture)), PortalSettings.Email), - ModuleMessage.ModuleMessageType.RedError); + AddPageMessage( + this, + string.Empty, + string.Format(Localization.GetString("ContractExpired.Error"), this.PortalSettings.PortalName, Globals.GetMediumDate(this.PortalSettings.ExpiryDate.ToString(CultureInfo.InvariantCulture)), this.PortalSettings.Email), + ModuleMessage.ModuleMessageType.RedError); } } else { - //If request localized page which haven't complete translate yet, redirect to default language version. - var redirectUrl = Globals.AccessDeniedURL(Localization.GetString("TabAccess.Error")); - + // If request localized page which haven't complete translate yet, redirect to default language version. + var redirectUrl = Globals.AccessDeniedURL(Localization.GetString("TabAccess.Error")); + // Current locale will use default if did'nt find any - Locale currentLocale = LocaleController.Instance.GetCurrentLocale(PortalSettings.PortalId); - if (PortalSettings.ContentLocalizationEnabled && - TabController.CurrentPage.CultureCode != currentLocale.Code) - { - redirectUrl = new LanguageTokenReplace {Language = currentLocale.Code}.ReplaceEnvironmentTokens("[URL]"); - } - - Response.Redirect(redirectUrl, true); + Locale currentLocale = LocaleController.Instance.GetCurrentLocale(this.PortalSettings.PortalId); + if (this.PortalSettings.ContentLocalizationEnabled && + TabController.CurrentPage.CultureCode != currentLocale.Code) + { + redirectUrl = new LanguageTokenReplace { Language = currentLocale.Code }.ReplaceEnvironmentTokens("[URL]"); + } + + this.Response.Redirect(redirectUrl, true); } + return success; } private void EnsureContentItemForTab(Entities.Tabs.TabInfo tabInfo) { - //If tab exists but ContentItem not, then we create it + // If tab exists but ContentItem not, then we create it if (tabInfo.ContentItemId == Null.NullInteger && tabInfo.TabID != Null.NullInteger) { TabController.Instance.CreateContentItem(tabInfo); - TabController.Instance.UpdateTab(tabInfo); + TabController.Instance.UpdateTab(tabInfo); } } private void EnsureContentItemForModule(ModuleInfo module) { - //If module exists but ContentItem not, then we create it + // If module exists but ContentItem not, then we create it if (module.ContentItemId == Null.NullInteger && module.ModuleID != Null.NullInteger) { ModuleController.Instance.CreateContentItem(module); @@ -518,7 +593,7 @@ private void EnsureContentItemForModule(ModuleInfo module) private void ProcessPanes() { - foreach (KeyValuePair kvp in Panes) + foreach (KeyValuePair kvp in this.Panes) { kvp.Value.ProcessPane(); } @@ -529,17 +604,18 @@ private bool ProcessSlaveModule() var success = true; var key = UIUtilities.GetControlKey(); var moduleId = UIUtilities.GetModuleId(key); - var slaveModule = UIUtilities.GetSlaveModule(moduleId, key, PortalSettings.ActiveTab.TabID); + var slaveModule = UIUtilities.GetSlaveModule(moduleId, key, this.PortalSettings.ActiveTab.TabID); Pane pane; - Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); + this.Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); slaveModule.PaneName = Globals.glbDefaultPane; - slaveModule.ContainerSrc = PortalSettings.ActiveTab.ContainerSrc; - if (String.IsNullOrEmpty(slaveModule.ContainerSrc)) + slaveModule.ContainerSrc = this.PortalSettings.ActiveTab.ContainerSrc; + if (string.IsNullOrEmpty(slaveModule.ContainerSrc)) { - slaveModule.ContainerSrc = PortalSettings.DefaultPortalContainer; + slaveModule.ContainerSrc = this.PortalSettings.DefaultPortalContainer; } - slaveModule.ContainerSrc = SkinController.FormatSkinSrc(slaveModule.ContainerSrc, PortalSettings); + + slaveModule.ContainerSrc = SkinController.FormatSkinSrc(slaveModule.ContainerSrc, this.PortalSettings); slaveModule.ContainerPath = SkinController.FormatSkinPath(slaveModule.ContainerSrc); var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID); @@ -547,7 +623,7 @@ private bool ProcessSlaveModule() { slaveModule.ModuleControlId = moduleControl.ModuleControlID; slaveModule.IconFile = moduleControl.IconFile; - + string permissionKey; switch (slaveModule.ModuleControl.ControlSrc) { @@ -567,91 +643,16 @@ private bool ProcessSlaveModule() if (ModulePermissionController.HasModuleAccess(slaveModule.ModuleControl.ControlType, permissionKey, slaveModule)) { - success = InjectModule(pane, slaveModule); + success = this.InjectModule(pane, slaveModule); } else { - Response.Redirect(Globals.AccessDeniedURL(Localization.GetString("ModuleAccess.Error")), true); + this.Response.Redirect(Globals.AccessDeniedURL(Localization.GetString("ModuleAccess.Error")), true); } } return success; - } - - #endregion - - #region Protected Methods - - /// ----------------------------------------------------------------------------- - /// - /// OnInit runs when the Skin is initialised. - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - //Load the Panes - LoadPanes(); - - //Load the Module Control(s) - bool success = Globals.IsAdminControl() ? ProcessSlaveModule() : ProcessMasterModules(); - - //Load the Control Panel - InjectControlPanel(); - - //Register any error messages on the Skin - if (Request.QueryString["error"] != null && Host.ShowCriticalErrors) - { - AddPageMessage(this, Localization.GetString("CriticalError.Error"), " ", ModuleMessage.ModuleMessageType.RedError); - - if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) - { - ServicesFramework.Instance.RequestAjaxScriptSupport(); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - - JavaScript.RequestRegistration(CommonJs.jQueryUI); - JavaScript.RegisterClientReference(Page, ClientAPI.ClientNamespaceReferences.dnn_dom); - ClientResourceManager.RegisterScript(Page, "~/resources/shared/scripts/dnn.logViewer.js"); - } - } - - if (!TabPermissionController.CanAdminPage() && !success) - { - //only display the warning to non-administrators (administrators will see the errors) - AddPageMessage(this, Localization.GetString("ModuleLoadWarning.Error"), string.Format(Localization.GetString("ModuleLoadWarning.Text"), PortalSettings.Email), ModuleMessage.ModuleMessageType.YellowWarning); - } - - InvokeSkinEvents(SkinEventType.OnSkinInit); - - if (HttpContext.Current != null && HttpContext.Current.Items.Contains(OnInitMessage)) - { - var messageType = ModuleMessage.ModuleMessageType.YellowWarning; - if (HttpContext.Current.Items.Contains(OnInitMessageType)) - { - messageType = (ModuleMessage.ModuleMessageType)Enum.Parse(typeof (ModuleMessage.ModuleMessageType), HttpContext.Current.Items[OnInitMessageType].ToString(), true); - } - AddPageMessage(this, string.Empty, HttpContext.Current.Items[OnInitMessage].ToString(), messageType); - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - } - - //Process the Panes attributes - ProcessPanes(); - } - - /// ----------------------------------------------------------------------------- - /// - /// OnLoad runs when the Skin is loaded. - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - InvokeSkinEvents(SkinEventType.OnSkinLoad); - } + } /// ----------------------------------------------------------------------------- /// @@ -662,21 +663,21 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - InvokeSkinEvents(SkinEventType.OnSkinPreRender); - var isSpecialPageMode = UrlUtils.InPopUp() || Request.QueryString["dnnprintmode"] == "true"; + this.InvokeSkinEvents(SkinEventType.OnSkinPreRender); + var isSpecialPageMode = UrlUtils.InPopUp() || this.Request.QueryString["dnnprintmode"] == "true"; if (TabPermissionController.CanAddContentToPage() && Globals.IsEditMode() && !isSpecialPageMode) { - //Register Drag and Drop plugin + // Register Drag and Drop plugin JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ClientResourceManager.RegisterStyleSheet(Page, "~/resources/shared/stylesheets/dnn.dragDrop.css", FileOrder.Css.FeatureCss); - ClientResourceManager.RegisterScript(Page, "~/resources/shared/scripts/dnn.dragDrop.js"); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/resources/shared/stylesheets/dnn.dragDrop.css", FileOrder.Css.FeatureCss); + ClientResourceManager.RegisterScript(this.Page, "~/resources/shared/scripts/dnn.dragDrop.js"); - //Register Client Script + // Register Client Script var sb = new StringBuilder(); sb.AppendLine(" (function ($) {"); sb.AppendLine(" $(document).ready(function () {"); sb.AppendLine(" $('.dnnSortable').dnnModuleDragDrop({"); - sb.AppendLine(" tabId: " + PortalSettings.ActiveTab.TabID + ","); + sb.AppendLine(" tabId: " + this.PortalSettings.ActiveTab.TabID + ","); sb.AppendLine(" draggingHintText: '" + Localization.GetSafeJSString("DraggingHintText", Localization.GlobalResourceFile) + "',"); sb.AppendLine(" dragHintText: '" + Localization.GetSafeJSString("DragModuleHint", Localization.GlobalResourceFile) + "',"); sb.AppendLine(" dropHintText: '" + Localization.GetSafeJSString("DropModuleHint", Localization.GlobalResourceFile) + "',"); @@ -686,17 +687,16 @@ protected override void OnPreRender(EventArgs e) sb.AppendLine(" } (jQuery));"); var script = sb.ToString(); - if (ScriptManager.GetCurrent(Page) != null) + if (ScriptManager.GetCurrent(this.Page) != null) { // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "DragAndDrop", script, true); + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "DragAndDrop", script, true); } else { - Page.ClientScript.RegisterStartupScript(GetType(), "DragAndDrop", script, true); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "DragAndDrop", script, true); } } - } /// ----------------------------------------------------------------------------- @@ -708,44 +708,30 @@ protected override void OnUnload(EventArgs e) { base.OnUnload(e); - InvokeSkinEvents(SkinEventType.OnSkinUnLoad); - } - - #endregion - - #region Public Methods - - public static void AddModuleMessage(PortalModuleBase control, string message, ModuleMessage.ModuleMessageType moduleMessageType) - { - AddModuleMessage(control, "", message, moduleMessageType, Null.NullString); - } - - public static void AddModuleMessage(PortalModuleBase control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) - { - AddModuleMessage(control, heading, message, moduleMessageType, Null.NullString); - } + this.InvokeSkinEvents(SkinEventType.OnSkinUnLoad); + } /// ----------------------------------------------------------------------------- /// - /// AddModuleMessage adds a Moduel Message control to the Skin + /// AddModuleMessage adds a Moduel Message control to the Skin. /// - /// The Message Text - /// The current control - /// The type of the message + /// The Message Text. + /// The current control. + /// The type of the message. /// ----------------------------------------------------------------------------- public static void AddModuleMessage(Control control, string message, ModuleMessage.ModuleMessageType moduleMessageType) { - AddModuleMessage(control, "", message, moduleMessageType, Null.NullString); + AddModuleMessage(control, string.Empty, message, moduleMessageType, Null.NullString); } /// ----------------------------------------------------------------------------- /// - /// AddModuleMessage adds a Moduel Message control to the Skin + /// AddModuleMessage adds a Moduel Message control to the Skin. /// - /// The Message Heading - /// The Message Text - /// The current control - /// The type of the message + /// The Message Heading. + /// The Message Text. + /// The current control. + /// The type of the message. /// ----------------------------------------------------------------------------- public static void AddModuleMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { @@ -754,12 +740,12 @@ public static void AddModuleMessage(Control control, string heading, string mess /// ----------------------------------------------------------------------------- /// - /// AddPageMessage adds a Page Message control to the Skin + /// AddPageMessage adds a Page Message control to the Skin. /// - /// The Message Heading - /// The Icon to diplay - /// The Message Text - /// The Page + /// The Message Heading. + /// The Icon to diplay. + /// The Message Text. + /// The Page. /// ----------------------------------------------------------------------------- public static void AddPageMessage(Page page, string heading, string message, string iconSrc) { @@ -768,12 +754,12 @@ public static void AddPageMessage(Page page, string heading, string message, str /// ----------------------------------------------------------------------------- /// - /// AddPageMessage adds a Page Message control to the Skin + /// AddPageMessage adds a Page Message control to the Skin. /// - /// The Message Heading - /// The Icon to diplay - /// The Message Text - /// The skin + /// The Message Heading. + /// The Icon to diplay. + /// The Message Text. + /// The skin. /// ----------------------------------------------------------------------------- public static void AddPageMessage(Skin skin, string heading, string message, string iconSrc) { @@ -782,12 +768,12 @@ public static void AddPageMessage(Skin skin, string heading, string message, str /// ----------------------------------------------------------------------------- /// - /// AddPageMessage adds a Page Message control to the Skin + /// AddPageMessage adds a Page Message control to the Skin. /// - /// The Message Heading - /// The Message Text - /// The skin - /// The type of the message + /// The Message Heading. + /// The Message Text. + /// The skin. + /// The type of the message. /// ----------------------------------------------------------------------------- public static void AddPageMessage(Skin skin, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { @@ -796,12 +782,12 @@ public static void AddPageMessage(Skin skin, string heading, string message, Mod /// ----------------------------------------------------------------------------- /// - /// AddPageMessage adds a Page Message control to the Skin + /// AddPageMessage adds a Page Message control to the Skin. /// - /// The Message Heading - /// The Message Text - /// The Page - /// The type of the message + /// The Message Heading. + /// The Message Text. + /// The Page. + /// The type of the message. /// ----------------------------------------------------------------------------- public static void AddPageMessage(Page page, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { @@ -810,11 +796,12 @@ public static void AddPageMessage(Page page, string heading, string message, Mod /// ----------------------------------------------------------------------------- /// - /// GetModuleMessageControl gets an existing Message Control and sets its properties + /// GetModuleMessageControl gets an existing Message Control and sets its properties. /// - /// The Message Heading - /// The Message Text - /// The Message Icon + /// The Message Heading. + /// The Message Text. + /// The Message Icon. + /// /// ----------------------------------------------------------------------------- public static ModuleMessage GetModuleMessageControl(string heading, string message, string iconImage) { @@ -823,11 +810,12 @@ public static ModuleMessage GetModuleMessageControl(string heading, string messa /// ----------------------------------------------------------------------------- /// - /// GetModuleMessageControl gets an existing Message Control and sets its properties + /// GetModuleMessageControl gets an existing Message Control and sets its properties. /// - /// The Message Heading - /// The Message Text - /// The type of message + /// The Message Heading. + /// The Message Text. + /// The type of message. + /// /// ----------------------------------------------------------------------------- public static ModuleMessage GetModuleMessageControl(string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { @@ -836,18 +824,18 @@ public static ModuleMessage GetModuleMessageControl(string heading, string messa /// ----------------------------------------------------------------------------- /// - /// GetModuleMessageControl gets an existing Message Control and sets its properties + /// GetModuleMessageControl gets an existing Message Control and sets its properties. /// - /// The Message Heading - /// The Message Text - /// The Message Icon - /// The type of message + /// The Message Heading. + /// The Message Text. + /// The Message Icon. + /// The type of message. + /// /// ----------------------------------------------------------------------------- public static ModuleMessage GetModuleMessageControl(string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconImage) { - - //Use this to get a module message control - //with a standard DotNetNuke icon + // Use this to get a module message control + // with a standard DotNetNuke icon var s = new Skin(); var moduleMessage = (ModuleMessage)s.LoadControl("~/admin/skins/ModuleMessage.ascx"); moduleMessage.Heading = heading; @@ -859,9 +847,10 @@ public static ModuleMessage GetModuleMessageControl(string heading, string messa /// ----------------------------------------------------------------------------- /// - /// GetParentSkin gets the Parent Skin for a control + /// GetParentSkin gets the Parent Skin for a control. /// - /// The control whose Parent Skin is requested + /// The control whose Parent Skin is requested. + /// /// ----------------------------------------------------------------------------- public static Skin GetParentSkin(PortalModuleBase module) { @@ -870,9 +859,10 @@ public static Skin GetParentSkin(PortalModuleBase module) /// ----------------------------------------------------------------------------- /// - /// GetParentSkin gets the Parent Skin for a control + /// GetParentSkin gets the Parent Skin for a control. /// - /// The control whose Parent Skin is requested + /// The control whose Parent Skin is requested. + /// /// ----------------------------------------------------------------------------- public static Skin GetParentSkin(Control control) { @@ -883,15 +873,16 @@ public static Skin GetParentSkin(Control control) /// /// GetPopUpSkin gets the Skin that is used in modal popup. /// - /// The Page + /// The Page. + /// /// ----------------------------------------------------------------------------- public static Skin GetPopUpSkin(PageBase page) { Skin skin = null; - //attempt to find and load a popup skin from the assigned skinned source + // attempt to find and load a popup skin from the assigned skinned source string skinSource = Globals.IsAdminSkin() ? SkinController.FormatSkinSrc(page.PortalSettings.DefaultAdminSkin, page.PortalSettings) : page.PortalSettings.ActiveTab.SkinSrc; - if (!String.IsNullOrEmpty(skinSource)) + if (!string.IsNullOrEmpty(skinSource)) { skinSource = SkinController.FormatSkinSrc(SkinController.FormatSkinPath(skinSource) + "popUpSkin.ascx", page.PortalSettings); @@ -901,17 +892,17 @@ public static Skin GetPopUpSkin(PageBase page) } } - //error loading popup skin - load default popup skin + // error loading popup skin - load default popup skin if (skin == null) { skinSource = Globals.HostPath + "Skins/_default/popUpSkin.ascx"; skin = LoadSkin(page, skinSource); } - //set skin path + // set skin path page.PortalSettings.ActiveTab.SkinPath = SkinController.FormatSkinPath(skinSource); - //set skin id to an explicit short name to reduce page payload and make it standards compliant + // set skin id to an explicit short name to reduce page payload and make it standards compliant skin.ID = "dnn"; return skin; @@ -919,29 +910,30 @@ public static Skin GetPopUpSkin(PageBase page) /// ----------------------------------------------------------------------------- /// - /// GetSkin gets the Skin + /// GetSkin gets the Skin. /// - /// The Page + /// The Page. + /// /// ----------------------------------------------------------------------------- public static Skin GetSkin(PageBase page) { Skin skin = null; string skinSource = Null.NullString; - //skin preview - if ((page.Request.QueryString["SkinSrc"] != null)) + // skin preview + if (page.Request.QueryString["SkinSrc"] != null) { skinSource = SkinController.FormatSkinSrc(Globals.QueryStringDecode(page.Request.QueryString["SkinSrc"]) + ".ascx", page.PortalSettings); skin = LoadSkin(page, skinSource); } - //load user skin ( based on cookie ) + // load user skin ( based on cookie ) if (skin == null) { HttpCookie skinCookie = page.Request.Cookies["_SkinSrc" + page.PortalSettings.PortalId]; if (skinCookie != null) { - if (!String.IsNullOrEmpty(skinCookie.Value)) + if (!string.IsNullOrEmpty(skinCookie.Value)) { skinSource = SkinController.FormatSkinSrc(skinCookie.Value + ".ascx", page.PortalSettings); skin = LoadSkin(page, skinSource); @@ -949,86 +941,104 @@ public static Skin GetSkin(PageBase page) } } - //load assigned skin + // load assigned skin if (skin == null) { - //DNN-6170 ensure skin value is culture specific - //skinSource = Globals.IsAdminSkin() ? SkinController.FormatSkinSrc(page.PortalSettings.DefaultAdminSkin, page.PortalSettings) : page.PortalSettings.ActiveTab.SkinSrc; + // DNN-6170 ensure skin value is culture specific + // skinSource = Globals.IsAdminSkin() ? SkinController.FormatSkinSrc(page.PortalSettings.DefaultAdminSkin, page.PortalSettings) : page.PortalSettings.ActiveTab.SkinSrc; skinSource = Globals.IsAdminSkin() ? PortalController.GetPortalSetting("DefaultAdminSkin", page.PortalSettings.PortalId, Host.DefaultPortalSkin, page.PortalSettings.CultureCode) : page.PortalSettings.ActiveTab.SkinSrc; - if (!String.IsNullOrEmpty(skinSource)) + if (!string.IsNullOrEmpty(skinSource)) { skinSource = SkinController.FormatSkinSrc(skinSource, page.PortalSettings); skin = LoadSkin(page, skinSource); } } - //error loading skin - load default + // error loading skin - load default if (skin == null) { skinSource = SkinController.FormatSkinSrc(SkinController.GetDefaultPortalSkin(), page.PortalSettings); skin = LoadSkin(page, skinSource); } - //set skin path + // set skin path page.PortalSettings.ActiveTab.SkinPath = SkinController.FormatSkinPath(skinSource); - //set skin id to an explicit short name to reduce page payload and make it standards compliant + // set skin id to an explicit short name to reduce page payload and make it standards compliant skin.ID = "dnn"; return skin; } + public static List GetInstalledSkins() + { + var list = new List(); + foreach (string folder in Directory.GetDirectories(Path.Combine(Globals.HostMapPath, "Skins"))) + { + if (!folder.EndsWith(Globals.glbHostSkinFolder)) + { + var skin = new InstalledSkinInfo(); + skin.SkinName = folder.Substring(folder.LastIndexOf("\\") + 1); + skin.InUse = isFallbackSkin(folder) || !SkinController.CanDeleteSkin(folder, string.Empty); + list.Add(skin); + } + } + + return list; + } + /// ----------------------------------------------------------------------------- /// - /// InjectModule injects the module into the Pane + /// InjectModule injects the module into the Pane. /// - /// The module to inject - /// The pane + /// The module to inject. + /// The pane. + /// /// ----------------------------------------------------------------------------- public bool InjectModule(Pane pane, ModuleInfo module) { bool bSuccess = true; - //try to inject the module into the pane + // try to inject the module into the pane try { - if(PortalSettings.ActiveTab.TabID == PortalSettings.UserTabId || PortalSettings.ActiveTab.ParentId == PortalSettings.UserTabId) + if (this.PortalSettings.ActiveTab.TabID == this.PortalSettings.UserTabId || this.PortalSettings.ActiveTab.ParentId == this.PortalSettings.UserTabId) { - var profileModule = ModuleControlPipeline.LoadModuleControl(Page, module) as IProfileModule; + var profileModule = this.ModuleControlPipeline.LoadModuleControl(this.Page, module) as IProfileModule; if (profileModule == null || profileModule.DisplayModule) { pane.InjectModule(module); - } + } } else { - pane.InjectModule(module); + pane.InjectModule(module); } - } catch (ThreadAbortException) { - //Response.Redirect may called in module control's OnInit method, so it will cause ThreadAbortException, no need any action here. + // Response.Redirect may called in module control's OnInit method, so it will cause ThreadAbortException, no need any action here. } catch (Exception ex) { Exceptions.LogException(ex); bSuccess = false; } + return bSuccess; } /// ----------------------------------------------------------------------------- /// - /// RegisterModuleActionEvent registers a Module Action Event + /// RegisterModuleActionEvent registers a Module Action Event. /// - /// The ID of the module - /// An Action Event Handler + /// The ID of the module. + /// An Action Event Handler. /// ----------------------------------------------------------------------------- public void RegisterModuleActionEvent(int moduleId, ActionEventHandler e) { - ActionEventListeners.Add(new ModuleActionEventListener(moduleId, e)); + this.ActionEventListeners.Add(new ModuleActionEventListener(moduleId, e)); } private static bool isFallbackSkin(string skinPath) @@ -1039,25 +1049,8 @@ private static bool isFallbackSkin(string skinPath) { defaultSkinPath = defaultSkinPath.Substring(0, defaultSkinPath.Length - 1); } + return skinPath.IndexOf(defaultSkinPath, StringComparison.CurrentCultureIgnoreCase) != -1; } - - public static List GetInstalledSkins() - { - var list = new List(); - foreach (string folder in Directory.GetDirectories(Path.Combine(Globals.HostMapPath, "Skins"))) - { - if (!folder.EndsWith(Globals.glbHostSkinFolder)) - { - var skin = new InstalledSkinInfo(); - skin.SkinName = folder.Substring(folder.LastIndexOf("\\") + 1); - skin.InUse = isFallbackSkin(folder) || !SkinController.CanDeleteSkin(folder, ""); - list.Add(skin); - } - } - return list; - } - - #endregion } } diff --git a/DNN Platform/Library/UI/Skins/SkinControl.cs b/DNN Platform/Library/UI/Skins/SkinControl.cs index a6949e345a4..e007bf65ee9 100644 --- a/DNN Platform/Library/UI/Skins/SkinControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinControl.cs @@ -1,54 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Collections.Generic; + using System.IO; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.WebControls; + public class SkinControl : UserControlBase - { - #region "Private Members" - + { + protected DropDownList cboSkin; + protected CommandButton cmdPreview; private string _DefaultKey = "System"; private string _SkinRoot; private string _SkinSrc; - private string _Width = ""; + private string _Width = string.Empty; private string _localResourceFile; private PortalInfo _objPortal; - protected DropDownList cboSkin; - protected CommandButton cmdPreview; protected RadioButton optHost; - protected RadioButton optSite; - - #endregion - - #region "Public Properties" - + protected RadioButton optSite; + public string DefaultKey { get { - return _DefaultKey; + return this._DefaultKey; } + set { - _DefaultKey = value; + this._DefaultKey = value; } } @@ -56,11 +46,12 @@ public string Width { get { - return Convert.ToString(ViewState["SkinControlWidth"]); + return Convert.ToString(this.ViewState["SkinControlWidth"]); } + set { - _Width = value; + this._Width = value; } } @@ -68,11 +59,12 @@ public string SkinRoot { get { - return Convert.ToString(ViewState["SkinRoot"]); + return Convert.ToString(this.ViewState["SkinRoot"]); } + set { - _SkinRoot = value; + this._SkinRoot = value; } } @@ -80,18 +72,19 @@ public string SkinSrc { get { - if (cboSkin.SelectedItem != null) + if (this.cboSkin.SelectedItem != null) { - return cboSkin.SelectedItem.Value; + return this.cboSkin.SelectedItem.Value; } else { - return ""; + return string.Empty; } } + set { - _SkinSrc = value; + this._SkinSrc = value; } } @@ -100,134 +93,88 @@ public string LocalResourceFile get { string fileRoot; - if (String.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/SkinControl.ascx"; + fileRoot = this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/SkinControl.ascx"; } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; - } - } - - #endregion - - #region "Private Methods" - - private void LoadSkins() - { - cboSkin.Items.Clear(); - - if (optHost.Checked) - { - // load host skins - foreach (KeyValuePair Skin in SkinController.GetSkins(_objPortal, SkinRoot, SkinScope.Host)) - { - cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); - } + this._localResourceFile = value; } - - if (optSite.Checked) - { - // load portal skins - foreach (KeyValuePair Skin in SkinController.GetSkins(_objPortal, SkinRoot, SkinScope.Site)) - { - cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); - } - } - - cboSkin.Items.Insert(0, new ListItem("<" + Localization.GetString(DefaultKey, LocalResourceFile) + ">", "")); - - - // select current skin - for (int intIndex = 0; intIndex < cboSkin.Items.Count; intIndex++) - { - if (cboSkin.Items[intIndex].Value.Equals(Convert.ToString(ViewState["SkinSrc"]), StringComparison.InvariantCultureIgnoreCase)) - { - cboSkin.Items[intIndex].Selected = true; - break; - } - } - } - - #endregion - - #region "Event Handlers" - + } + /// - /// The Page_Load server event handler on this page is used - /// to populate the role information for the page - /// - protected override void OnLoad(EventArgs e) + /// The Page_Load server event handler on this page is used + /// to populate the role information for the page. + /// + protected override void OnLoad(EventArgs e) { - base.OnLoad(e); - - #region Bind Handles - - optHost.CheckedChanged += optHost_CheckedChanged; - optSite.CheckedChanged += optSite_CheckedChanged; - cmdPreview.Click += cmdPreview_Click; - - #endregion - + base.OnLoad(e); + this.optHost.CheckedChanged += this.optHost_CheckedChanged; + this.optSite.CheckedChanged += this.optSite_CheckedChanged; + this.cmdPreview.Click += this.cmdPreview_Click; try { - if (Request.QueryString["pid"] != null && (Globals.IsHostTab(PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + if (this.Request.QueryString["pid"] != null && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) { - _objPortal = PortalController.Instance.GetPortal(Int32.Parse(Request.QueryString["pid"])); + this._objPortal = PortalController.Instance.GetPortal(int.Parse(this.Request.QueryString["pid"])); } else { - _objPortal = PortalController.Instance.GetPortal(PortalSettings.PortalId); + this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); } - if (!Page.IsPostBack) + + if (!this.Page.IsPostBack) { - //save persistent values - ViewState["SkinControlWidth"] = _Width; - ViewState["SkinRoot"] = _SkinRoot; - ViewState["SkinSrc"] = _SkinSrc; - - //set width of control - if (!String.IsNullOrEmpty(_Width)) + // save persistent values + this.ViewState["SkinControlWidth"] = this._Width; + this.ViewState["SkinRoot"] = this._SkinRoot; + this.ViewState["SkinSrc"] = this._SkinSrc; + + // set width of control + if (!string.IsNullOrEmpty(this._Width)) { - cboSkin.Width = Unit.Parse(_Width); + this.cboSkin.Width = Unit.Parse(this._Width); } - - //set selected skin - if (!String.IsNullOrEmpty(_SkinSrc)) + + // set selected skin + if (!string.IsNullOrEmpty(this._SkinSrc)) { - switch (_SkinSrc.Substring(0, 3)) + switch (this._SkinSrc.Substring(0, 3)) { case "[L]": - optHost.Checked = false; - optSite.Checked = true; + this.optHost.Checked = false; + this.optSite.Checked = true; break; case "[G]": - optSite.Checked = false; - optHost.Checked = true; + this.optSite.Checked = false; + this.optHost.Checked = true; break; } } else { - //no skin selected, initialized to site skin if any exists - string strRoot = _objPortal.HomeDirectoryMapPath + SkinRoot; + // no skin selected, initialized to site skin if any exists + string strRoot = this._objPortal.HomeDirectoryMapPath + this.SkinRoot; if (Directory.Exists(strRoot) && Directory.GetDirectories(strRoot).Length > 0) { - optHost.Checked = false; - optSite.Checked = true; + this.optHost.Checked = false; + this.optSite.Checked = true; } } - LoadSkins(); + + this.LoadSkins(); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -235,33 +182,67 @@ protected override void OnLoad(EventArgs e) protected void optHost_CheckedChanged(object sender, EventArgs e) { - LoadSkins(); + this.LoadSkins(); } + + private void LoadSkins() + { + this.cboSkin.Items.Clear(); + + if (this.optHost.Checked) + { + // load host skins + foreach (KeyValuePair Skin in SkinController.GetSkins(this._objPortal, this.SkinRoot, SkinScope.Host)) + { + this.cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); + } + } + + if (this.optSite.Checked) + { + // load portal skins + foreach (KeyValuePair Skin in SkinController.GetSkins(this._objPortal, this.SkinRoot, SkinScope.Site)) + { + this.cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); + } + } + + this.cboSkin.Items.Insert(0, new ListItem("<" + Localization.GetString(this.DefaultKey, this.LocalResourceFile) + ">", string.Empty)); + + // select current skin + for (int intIndex = 0; intIndex < this.cboSkin.Items.Count; intIndex++) + { + if (this.cboSkin.Items[intIndex].Value.Equals(Convert.ToString(this.ViewState["SkinSrc"]), StringComparison.InvariantCultureIgnoreCase)) + { + this.cboSkin.Items[intIndex].Selected = true; + break; + } + } + } protected void optSite_CheckedChanged(object sender, EventArgs e) { - LoadSkins(); + this.LoadSkins(); } protected void cmdPreview_Click(object sender, EventArgs e) { - if (!String.IsNullOrEmpty(SkinSrc)) + if (!string.IsNullOrEmpty(this.SkinSrc)) { - string strType = SkinRoot.Substring(0, SkinRoot.Length - 1); + string strType = this.SkinRoot.Substring(0, this.SkinRoot.Length - 1); - string strURL = Globals.ApplicationURL() + "&" + strType + "Src=" + Globals.QueryStringEncode(SkinSrc.Replace(".ascx", "")); + string strURL = Globals.ApplicationURL() + "&" + strType + "Src=" + Globals.QueryStringEncode(this.SkinSrc.Replace(".ascx", string.Empty)); - if (SkinRoot == SkinController.RootContainer) + if (this.SkinRoot == SkinController.RootContainer) { - if (Request.QueryString["ModuleId"] != null) + if (this.Request.QueryString["ModuleId"] != null) { - strURL += "&ModuleId=" + Request.QueryString["ModuleId"]; + strURL += "&ModuleId=" + this.Request.QueryString["ModuleId"]; } } - Response.Redirect(strURL, true); + + this.Response.Redirect(strURL, true); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinController.cs b/DNN Platform/Library/UI/Skins/SkinController.cs index 1f5a5ce1f1c..70fb637fcd1 100644 --- a/DNN Platform/Library/UI/Skins/SkinController.cs +++ b/DNN Platform/Library/UI/Skins/SkinController.cs @@ -1,56 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text.RegularExpressions; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -using ICSharpCode.SharpZipLib.Zip; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Text.RegularExpressions; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using ICSharpCode.SharpZipLib.Zip; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : SkinController + /// Project : DotNetNuke + /// Class : SkinController /// /// ----------------------------------------------------------------------------- /// - /// Handles the Business Control Layer for Skins + /// Handles the Business Control Layer for Skins. /// /// /// /// ----------------------------------------------------------------------------- public class SkinController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SkinController)); private const string GlobalSkinPrefix = "[G]"; private const string PortalSystemSkinPrefix = "[S]"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinController)); private const string PortalSkinPrefix = "[L]"; private static readonly Regex GdirRegex = new Regex("\\[g]", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex SdirRegex = new Regex("\\[s]", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex LdirRegex = new Regex("\\[l]", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - #region Public Shared Properties - + private static readonly Regex LdirRegex = new Regex("\\[l]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + public static string RootSkin { get @@ -65,22 +57,29 @@ public static string RootContainer { return "Containers"; } + } + + public static int AddSkin(int skinPackageID, string skinSrc) + { + return DataProvider.Instance().AddSkin(skinPackageID, skinSrc); } - - #endregion - - #region Public Shared Methods + public static int AddSkinPackage(SkinPackageInfo skinPackage) + { + EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINPACKAGE_CREATED); + return DataProvider.Instance().AddSkinPackage(skinPackage.PackageID, skinPackage.PortalID, skinPackage.SkinName, skinPackage.SkinType, UserController.Instance.GetCurrentUserInfo().UserID); + } + private static void AddSkinFiles(List> skins, string skinRoot, string skinFolder, string skinPrefix) { foreach (string skinFile in Directory.GetFiles(skinFolder, "*.ascx")) { string folder = skinFolder.Substring(skinFolder.LastIndexOf("\\") + 1); - string key = (skinPrefix == PortalSystemSkinPrefix || skinPrefix == PortalSkinPrefix ? "Site: " : "Host: ") - + FormatSkinName(folder, Path.GetFileNameWithoutExtension(skinFile)); - string value = skinPrefix + skinRoot + "/" + folder + "/" + Path.GetFileName(skinFile); - skins.Add(new KeyValuePair(key, value)); + string key = (skinPrefix == PortalSystemSkinPrefix || skinPrefix == PortalSkinPrefix ? "Site: " : "Host: ") + + FormatSkinName(folder, Path.GetFileNameWithoutExtension(skinFile)); + string value = skinPrefix + skinRoot + "/" + folder + "/" + Path.GetFileName(skinFile); + skins.Add(new KeyValuePair(key, value)); } } @@ -99,6 +98,7 @@ private static List> GetHostSkins(string skinRoot) } } } + return skins; } @@ -107,36 +107,25 @@ private static List> GetPortalSkins(PortalInfo port var skins = new List>(); if (portalInfo != null) - { + { ProcessSkinsFolder(skins, portalInfo.HomeSystemDirectoryMapPath + skinRoot, skinRoot, PortalSystemSkinPrefix); - ProcessSkinsFolder(skins, portalInfo.HomeDirectoryMapPath + skinRoot, skinRoot, PortalSkinPrefix); //to be compliant with all versions + ProcessSkinsFolder(skins, portalInfo.HomeDirectoryMapPath + skinRoot, skinRoot, PortalSkinPrefix); // to be compliant with all versions } + return skins; } private static void ProcessSkinsFolder(List> skins, string skinsFolder, string skinRoot, string skinPrefix) - { + { if (Directory.Exists(skinsFolder)) { foreach (string skinFolder in Directory.GetDirectories(skinsFolder)) { - AddSkinFiles(skins, skinRoot, skinFolder, skinPrefix); + AddSkinFiles(skins, skinRoot, skinFolder, skinPrefix); } } } - - public static int AddSkin(int skinPackageID, string skinSrc) - { - return DataProvider.Instance().AddSkin(skinPackageID, skinSrc); - } - - public static int AddSkinPackage(SkinPackageInfo skinPackage) - { - EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.SKINPACKAGE_CREATED); - return DataProvider.Instance().AddSkinPackage(skinPackage.PackageID, skinPackage.PortalID, skinPackage.SkinName, skinPackage.SkinType, UserController.Instance.GetCurrentUserInfo().UserID); - } - public static bool CanDeleteSkin(string folderPath, string portalHomeDirMapPath) { string skinType; @@ -145,18 +134,19 @@ public static bool CanDeleteSkin(string folderPath, string portalHomeDirMapPath) if (folderPath.IndexOf(Globals.HostMapPath, StringComparison.InvariantCultureIgnoreCase) != -1) { skinType = "G"; - skinFolder = folderPath.ToLowerInvariant().Replace(Globals.HostMapPath.ToLowerInvariant(), "").Replace("\\", "/"); + skinFolder = folderPath.ToLowerInvariant().Replace(Globals.HostMapPath.ToLowerInvariant(), string.Empty).Replace("\\", "/"); } else if (folderPath.IndexOf(PortalSettings.Current.HomeSystemDirectoryMapPath, StringComparison.InvariantCultureIgnoreCase) != -1) { skinType = "S"; - skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), "").Replace("\\", "/"); + skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), string.Empty).Replace("\\", "/"); } - else //to be compliant with all versions + else // to be compliant with all versions { skinType = "L"; - skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), "").Replace("\\", "/"); + skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), string.Empty).Replace("\\", "/"); } + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); string skin = "[" + skinType.ToLowerInvariant() + "]" + skinFolder.ToLowerInvariant(); @@ -176,11 +166,13 @@ public static bool CanDeleteSkin(string folderPath, string portalHomeDirMapPath) canDelete = false; } } + if (canDelete) { - //Check if used for Tabs or Modules + // Check if used for Tabs or Modules canDelete = DataProvider.Instance().CanDeleteSkin(skinType, skinFolder); } + return canDelete; } @@ -192,7 +184,7 @@ public static void DeleteSkin(int skinID) public static void DeleteSkinPackage(SkinPackageInfo skinPackage) { DataProvider.Instance().DeleteSkinPackage(skinPackage.SkinPackageID); - EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.SKINPACKAGE_DELETED); + EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINPACKAGE_DELETED); } public static string FormatMessage(string title, string body, int level, bool isError) @@ -200,40 +192,43 @@ public static string FormatMessage(string title, string body, int level, bool is string message = title; if (isError) { - message = "" + title + ""; + message = "" + title + ""; } + switch (level) { case -1: - message = "

    " + message + ""; + message = "

    " + message + ""; break; case 0: - message = "

    " + message + ""; + message = "

    " + message + ""; break; case 1: - message = "
    " + message + ""; + message = "
    " + message + ""; break; default: message = "
  • " + message + "
  • "; break; } + return message + ": " + body + Environment.NewLine; } public static string FormatSkinPath(string skinSrc) { string strSkinSrc = skinSrc; - if (!String.IsNullOrEmpty(strSkinSrc)) + if (!string.IsNullOrEmpty(strSkinSrc)) { strSkinSrc = strSkinSrc.Substring(0, strSkinSrc.LastIndexOf("/") + 1); } + return strSkinSrc; } public static string FormatSkinSrc(string skinSrc, PortalSettings portalSettings) { string strSkinSrc = skinSrc; - if (!String.IsNullOrEmpty(strSkinSrc)) + if (!string.IsNullOrEmpty(strSkinSrc)) { switch (strSkinSrc.Substring(0, 3).ToLowerInvariant()) { @@ -243,11 +238,12 @@ public static string FormatSkinSrc(string skinSrc, PortalSettings portalSettings case "[s]": strSkinSrc = SdirRegex.Replace(strSkinSrc, portalSettings.HomeSystemDirectory); break; - case "[l]": //to be compliant with all versions + case "[l]": // to be compliant with all versions strSkinSrc = LdirRegex.Replace(strSkinSrc, portalSettings.HomeDirectory); break; } } + return strSkinSrc; } @@ -290,10 +286,10 @@ public static List> GetSkins(PortalInfo portalInfo, var skins = new List>(); switch (scope) { - case SkinScope.Host: //load host skins + case SkinScope.Host: // load host skins skins = GetHostSkins(skinRoot); break; - case SkinScope.Site: //load portal skins + case SkinScope.Site: // load portal skins skins = GetPortalSkins(portalInfo, skinRoot); break; case SkinScope.All: @@ -301,40 +297,12 @@ public static List> GetSkins(PortalInfo portalInfo, skins.AddRange(GetPortalSkins(portalInfo, skinRoot)); break; } + return skins; } - /// ----------------------------------------------------------------------------- - /// - /// format skin name - /// - /// - /// - /// The Folder Name - /// The File Name without extension - private static string FormatSkinName(string skinFolder, string skinFile) - { - if (skinFolder.Equals("_default", StringComparison.InvariantCultureIgnoreCase)) - { - // host folder - return skinFile; - - } - - //portal folder - switch (skinFile.ToLowerInvariant()) - { - case "skin": - case "container": - case "default": - return skinFolder; - default: - return skinFolder + " - " + skinFile; - } - } - /// - /// Determines if a given skin is defined as a global skin + /// Determines if a given skin is defined as a global skin. /// /// This is the app relative path and filename of the skin to be checked. /// True if the skin is located in the HostPath child directories. @@ -346,8 +314,7 @@ public static bool IsGlobalSkin(string skinSrc) { return skinSrc.Contains(Globals.HostPath); } - - + public static void SetSkin(string skinRoot, int portalId, SkinType skinType, string skinSrc) { var selectedCultureCode = LocaleController.Instance.GetCurrentLocale(portalId).Code; @@ -376,6 +343,7 @@ public static void SetSkin(string skinRoot, int portalId, SkinType skinType, str PortalController.UpdatePortalSetting(portalId, "DefaultPortalSkin", skinSrc, true, selectedCultureCode); } } + break; case "Containers": if (skinType == SkinType.Admin) @@ -400,10 +368,39 @@ public static void SetSkin(string skinRoot, int portalId, SkinType skinType, str PortalController.UpdatePortalSetting(portalId, "DefaultPortalContainer", skinSrc, true, selectedCultureCode); } } + break; } } + /// ----------------------------------------------------------------------------- + /// + /// format skin name. + /// + /// + /// + /// The Folder Name. + /// The File Name without extension. + private static string FormatSkinName(string skinFolder, string skinFile) + { + if (skinFolder.Equals("_default", StringComparison.InvariantCultureIgnoreCase)) + { + // host folder + return skinFile; + } + + // portal folder + switch (skinFile.ToLowerInvariant()) + { + case "skin": + case "container": + case "default": + return skinFolder; + default: + return skinFolder + " - " + skinFile; + } + } + public static void UpdateSkin(int skinID, string skinSrc) { DataProvider.Instance().UpdateSkin(skinID, skinSrc); @@ -411,13 +408,14 @@ public static void UpdateSkin(int skinID, string skinSrc) public static void UpdateSkinPackage(SkinPackageInfo skinPackage) { - DataProvider.Instance().UpdateSkinPackage(skinPackage.SkinPackageID, - skinPackage.PackageID, - skinPackage.PortalID, - skinPackage.SkinName, - skinPackage.SkinType, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.SKINPACKAGE_UPDATED); + DataProvider.Instance().UpdateSkinPackage( + skinPackage.SkinPackageID, + skinPackage.PackageID, + skinPackage.PortalID, + skinPackage.SkinName, + skinPackage.SkinType, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINPACKAGE_UPDATED); foreach (KeyValuePair kvp in skinPackage.Skins) { UpdateSkin(kvp.Key, kvp.Value); @@ -434,10 +432,10 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s FileStream objFileStream; int intSize = 2048; var arrData = new byte[2048]; - string strMessage = ""; + string strMessage = string.Empty; var arrSkinFiles = new ArrayList(); - //Localized Strings + // Localized Strings PortalSettings ResourcePortalSettings = Globals.GetPortalSettings(); string BEGIN_MESSAGE = Localization.GetString("BeginZip", ResourcePortalSettings); string CREATE_DIR = Localization.GetString("CreateDir", ResourcePortalSettings); @@ -454,13 +452,13 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s objZipEntry.CheckZipEntry(); if (!objZipEntry.IsDirectory) { - //validate file extension + // validate file extension strExtension = objZipEntry.Name.Substring(objZipEntry.Name.LastIndexOf(".") + 1); - var extraExtensions = new List {".ASCX", ".HTM", ".HTML", ".CSS", ".SWF", ".RESX", ".XAML", ".JS"}; - if(Host.AllowedExtensionWhitelist.IsAllowedExtension(strExtension, extraExtensions)) + var extraExtensions = new List { ".ASCX", ".HTM", ".HTML", ".CSS", ".SWF", ".RESX", ".XAML", ".JS" }; + if (Host.AllowedExtensionWhitelist.IsAllowedExtension(strExtension, extraExtensions)) { - //process embedded zip files - if (objZipEntry.Name.Equals(RootSkin.ToLowerInvariant() + ".zip", StringComparison.InvariantCultureIgnoreCase)) + // process embedded zip files + if (objZipEntry.Name.Equals(RootSkin.ToLowerInvariant() + ".zip", StringComparison.InvariantCultureIgnoreCase)) { using (var objMemoryStream = new MemoryStream()) { @@ -470,13 +468,14 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s objMemoryStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } + objMemoryStream.Seek(0, SeekOrigin.Begin); strMessage += UploadLegacySkin(rootPath, RootSkin, skinName, objMemoryStream); } } else if (objZipEntry.Name.Equals(RootContainer.ToLowerInvariant() + ".zip", StringComparison.InvariantCultureIgnoreCase)) { - using(var objMemoryStream = new MemoryStream()) + using (var objMemoryStream = new MemoryStream()) { intSize = objZipInputStream.Read(arrData, 0, arrData.Length); while (intSize > 0) @@ -484,6 +483,7 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s objMemoryStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } + objMemoryStream.Seek(0, SeekOrigin.Begin); strMessage += UploadLegacySkin(rootPath, RootContainer, skinName, objMemoryStream); } @@ -492,24 +492,24 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s { strFileName = rootPath + skinRoot + "\\" + skinName + "\\" + objZipEntry.Name; - //create the directory if it does not exist + // create the directory if it does not exist if (!Directory.Exists(Path.GetDirectoryName(strFileName))) { strMessage += FormatMessage(CREATE_DIR, Path.GetDirectoryName(strFileName), 2, false); Directory.CreateDirectory(Path.GetDirectoryName(strFileName)); } - - //remove the old file + + // remove the old file if (File.Exists(strFileName)) { File.SetAttributes(strFileName, FileAttributes.Normal); File.Delete(strFileName); } - - //create the new file + + // create the new file objFileStream = File.Create(strFileName); - - //unzip the file + + // unzip the file strMessage += FormatMessage(WRITE_FILE, Path.GetFileName(strFileName), 2, false); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); while (intSize > 0) @@ -517,9 +517,10 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s objFileStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } + objFileStream.Close(); - //save the skin file + // save the skin file switch (Path.GetExtension(strFileName)) { case ".htm": @@ -530,8 +531,10 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s { arrSkinFiles.Add(strFileName); } + break; } + break; } } @@ -540,35 +543,36 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s strMessage += string.Format(FILE_RESTICTED, objZipEntry.Name, Host.AllowedExtensionWhitelist.ToStorageString(), ",", ", *.").Replace("2", "true"); } } + objZipEntry = objZipInputStream.GetNextEntry(); } + strMessage += FormatMessage(END_MESSAGE, skinName + ".zip", 1, false); objZipInputStream.Close(); - //process the list of skin files + // process the list of skin files var NewSkin = new SkinFileProcessor(rootPath, skinRoot, skinName); strMessage += NewSkin.ProcessList(arrSkinFiles, SkinParser.Portable); - - //log installation event + + // log installation event try { - var log = new LogInfo {LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()}; + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.LogProperties.Add(new LogDetailInfo("Install Skin:", skinName)); - Array arrMessage = strMessage.Split(new[] {"
    "}, StringSplitOptions.None); + Array arrMessage = strMessage.Split(new[] { "
    " }, StringSplitOptions.None); foreach (string strRow in arrMessage) { log.LogProperties.Add(new LogDetailInfo("Info:", HtmlUtils.StripTags(strRow, true))); } + LogController.Instance.AddLog(log); } catch (Exception exc) { Logger.Error(exc); - } + return strMessage; - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinDefaults.cs b/DNN Platform/Library/UI/Skins/SkinDefaults.cs index 1a461228538..1661610fe44 100644 --- a/DNN Platform/Library/UI/Skins/SkinDefaults.cs +++ b/DNN Platform/Library/UI/Skins/SkinDefaults.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Xml; + + using DotNetNuke.Common.Utilities; + public enum SkinDefaultType { SkinInfo, - ContainerInfo + ContainerInfo, } [Serializable] @@ -33,20 +28,21 @@ private SkinDefaults(SkinDefaultType DefaultType) var dnndoc = new XmlDocument { XmlResolver = null }; dnndoc.Load(filePath); XmlNode defaultElement = dnndoc.SelectSingleNode("/configuration/skinningdefaults/" + nodename); - _folder = defaultElement.Attributes["folder"].Value; - _defaultName = defaultElement.Attributes["default"].Value; - _adminDefaultName = defaultElement.Attributes["admindefault"].Value; + this._folder = defaultElement.Attributes["folder"].Value; + this._defaultName = defaultElement.Attributes["default"].Value; + this._adminDefaultName = defaultElement.Attributes["admindefault"].Value; } public string AdminDefaultName { get { - return _adminDefaultName; + return this._adminDefaultName; } + set { - _adminDefaultName = value; + this._adminDefaultName = value; } } @@ -54,11 +50,12 @@ public string DefaultName { get { - return _defaultName; + return this._defaultName; } + set { - _defaultName = value; + this._defaultName = value; } } @@ -66,20 +63,15 @@ public string Folder { get { - return _folder; + return this._folder; } + set { - _folder = value; + this._folder = value; } } - private static object GetSkinDefaultsCallback(CacheItemArgs cacheItemArgs) - { - var defaultType = (SkinDefaultType) cacheItemArgs.ParamList[0]; - return new SkinDefaults(defaultType); - } - public static SkinDefaults GetSkinDefaults(SkinDefaultType DefaultType) { return @@ -87,5 +79,11 @@ public static SkinDefaults GetSkinDefaults(SkinDefaultType DefaultType) new CacheItemArgs(string.Format(DataCache.SkinDefaultsCacheKey, DefaultType), DataCache.SkinDefaultsCacheTimeOut, DataCache.SkinDefaultsCachePriority, DefaultType), GetSkinDefaultsCallback); } + + private static object GetSkinDefaultsCallback(CacheItemArgs cacheItemArgs) + { + var defaultType = (SkinDefaultType)cacheItemArgs.ParamList[0]; + return new SkinDefaults(defaultType); + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs index 5dbfc0e737b..3b69d0630b8 100644 --- a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs +++ b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using System.Xml; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer; + public enum SkinParser { Localized, - Portable + Portable, } /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : SkinFileProcessor + /// Project : DotNetNuke + /// Class : SkinFileProcessor /// /// ----------------------------------------------------------------------------- /// @@ -40,9 +35,7 @@ public enum SkinParser /// ----------------------------------------------------------------------------- public class SkinFileProcessor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SkinFileProcessor)); - #region "Private Members" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinFileProcessor)); private readonly string DUPLICATE_DETAIL = Util.GetLocalizedString("DuplicateSkinObject.Detail"); private readonly string DUPLICATE_ERROR = Util.GetLocalizedString("DuplicateSkinObject.Error"); private readonly string FILES_END = Util.GetLocalizedString("EndSkinFiles"); @@ -60,38 +53,36 @@ public class SkinFileProcessor private readonly string m_SkinName; private readonly string m_SkinPath; private readonly string m_SkinRoot; - private string m_Message = ""; - - #endregion - - #region "Constructors" - + private string m_Message = string.Empty; + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// SkinFileProcessor class constructor. /// /// - /// This constructor parses a memory based skin + /// This constructor parses a memory based skin. /// /// ----------------------------------------------------------------------------- public SkinFileProcessor(string ControlKey, string ControlSrc) { - m_ControlList.Add(ControlKey, ControlSrc); + this.m_ControlList.Add(ControlKey, ControlSrc); - //Instantiate the control parser with the list of skin objects - m_ControlFactory = new ControlParser(m_ControlList); - - //Instantiate the object parser with the list of skin objects - m_ObjectFactory = new ObjectParser(m_ControlList); - } + // Instantiate the control parser with the list of skin objects + this.m_ControlFactory = new ControlParser(this.m_ControlList); + // Instantiate the object parser with the list of skin objects + this.m_ObjectFactory = new ObjectParser(this.m_ControlList); + } + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// SkinFileProcessor class constructor. /// /// File path to the portals upload directory. - /// Specifies type of skin (Skins or Containers) - /// Name of folder in which skin will reside (Zip file name) + /// Specifies type of skin (Skins or Containers). + /// Name of folder in which skin will reside (Zip file name). /// /// The constructor primes the file processor with path information and /// control data that should only be retrieved once. It checks for the @@ -105,161 +96,152 @@ public SkinFileProcessor(string ControlKey, string ControlSrc) /// ----------------------------------------------------------------------------- public SkinFileProcessor(string SkinPath, string SkinRoot, string SkinName) { - Message += SkinController.FormatMessage(INITIALIZE_PROCESSOR, SkinRoot + " :: " + SkinName, 0, false); + this.Message += SkinController.FormatMessage(this.INITIALIZE_PROCESSOR, SkinRoot + " :: " + SkinName, 0, false); - //Save path information for future use - m_SkinRoot = SkinRoot; - m_SkinPath = SkinPath; - m_SkinName = SkinName; + // Save path information for future use + this.m_SkinRoot = SkinRoot; + this.m_SkinPath = SkinPath; + this.m_SkinName = SkinName; - //Check for and read skin package level attribute information file + // Check for and read skin package level attribute information file string FileName = this.SkinPath + this.SkinRoot + "\\" + this.SkinName + "\\" + SkinRoot.Substring(0, SkinRoot.Length - 1) + ".xml"; if (File.Exists(FileName)) { try { - SkinAttributes.Load(FileName); - Message += SkinController.FormatMessage(PACKAGE_LOAD, Path.GetFileName(FileName), 2, false); + this.SkinAttributes.Load(FileName); + this.Message += SkinController.FormatMessage(this.PACKAGE_LOAD, Path.GetFileName(FileName), 2, false); } catch (Exception ex) { - //could not load XML file + // could not load XML file Logger.Error(ex); - Message += SkinController.FormatMessage(string.Format(PACKAGE_LOAD_ERROR, ex.Message), Path.GetFileName(FileName), 2, true); + this.Message += SkinController.FormatMessage(string.Format(this.PACKAGE_LOAD_ERROR, ex.Message), Path.GetFileName(FileName), 2, true); } } - //Look at every control + // Look at every control string Token; foreach (SkinControlInfo objSkinControl in SkinControlController.GetSkinControls().Values) { Token = objSkinControl.ControlKey.ToUpper(); - //If the control is already in the hash table - if (m_ControlList.ContainsKey(Token)) + // If the control is already in the hash table + if (this.m_ControlList.ContainsKey(Token)) { - Message += SkinController.FormatMessage(string.Format(DUPLICATE_ERROR, Token), - string.Format(DUPLICATE_DETAIL, m_ControlList[Token], objSkinControl.ControlSrc), - 2, - true); + this.Message += SkinController.FormatMessage( + string.Format(this.DUPLICATE_ERROR, Token), + string.Format(this.DUPLICATE_DETAIL, this.m_ControlList[Token], objSkinControl.ControlSrc), + 2, + true); } else { - //Add it - Message += SkinController.FormatMessage(string.Format(LOAD_SKIN_TOKEN, Token), objSkinControl.ControlSrc, 2, false); - m_ControlList.Add(Token, objSkinControl.ControlSrc); + // Add it + this.Message += SkinController.FormatMessage(string.Format(this.LOAD_SKIN_TOKEN, Token), objSkinControl.ControlSrc, 2, false); + this.m_ControlList.Add(Token, objSkinControl.ControlSrc); } } - //Instantiate the control parser with the list of skin objects - m_ControlFactory = new ControlParser(m_ControlList); - - //Instantiate the object parser with the list of skin objects - m_ObjectFactory = new ObjectParser(m_ControlList); - } - - #endregion + // Instantiate the control parser with the list of skin objects + this.m_ControlFactory = new ControlParser(this.m_ControlList); - #region "Private Properties" - - private PathParser PathFactory + // Instantiate the object parser with the list of skin objects + this.m_ObjectFactory = new ObjectParser(this.m_ControlList); + } + + public string SkinRoot { get { - return m_PathFactory; + return this.m_SkinRoot; } } - private ControlParser ControlFactory + public string SkinPath { get { - return m_ControlFactory; + return this.m_SkinPath; } } - - private ObjectParser ObjectFactory + + private PathParser PathFactory { get { - return m_ObjectFactory; + return this.m_PathFactory; } } - private XmlDocument SkinAttributes + private ControlParser ControlFactory { get { - return m_SkinAttributes; + return this.m_ControlFactory; } } - private string Message + private ObjectParser ObjectFactory { get { - return m_Message; - } - set - { - m_Message = value; + return this.m_ObjectFactory; } } - #endregion - - #region "Public Properties" - - public string SkinRoot + private XmlDocument SkinAttributes { get { - return m_SkinRoot; + return this.m_SkinAttributes; } } - public string SkinPath + private string Message { get { - return m_SkinPath; + return this.m_Message; } - } + + set + { + this.m_Message = value; + } + } public string SkinName { get { - return m_SkinName; + return this.m_SkinName; } - } - - #endregion - - #region "Public Methods" - + } + public string ProcessFile(string FileName, SkinParser ParseOption) { - string strMessage = SkinController.FormatMessage(FILE_BEGIN, Path.GetFileName(FileName), 0, false); - var objSkinFile = new SkinFile(SkinRoot, FileName, SkinAttributes); + string strMessage = SkinController.FormatMessage(this.FILE_BEGIN, Path.GetFileName(FileName), 0, false); + var objSkinFile = new SkinFile(this.SkinRoot, FileName, this.SkinAttributes); switch (objSkinFile.FileExtension) { case ".htm": case ".html": string contents = objSkinFile.Contents; - strMessage += ObjectFactory.Parse(ref contents); - strMessage += PathFactory.Parse(ref contents, PathFactory.HTMLList, objSkinFile.SkinRootPath, ParseOption); - strMessage += ControlFactory.Parse(ref contents, objSkinFile.Attributes); + strMessage += this.ObjectFactory.Parse(ref contents); + strMessage += this.PathFactory.Parse(ref contents, this.PathFactory.HTMLList, objSkinFile.SkinRootPath, ParseOption); + strMessage += this.ControlFactory.Parse(ref contents, objSkinFile.Attributes); objSkinFile.Contents = contents; var Registrations = new ArrayList(); - Registrations.AddRange(ControlFactory.Registrations); - Registrations.AddRange(ObjectFactory.Registrations); + Registrations.AddRange(this.ControlFactory.Registrations); + Registrations.AddRange(this.ObjectFactory.Registrations); strMessage += objSkinFile.PrependASCXDirectives(Registrations); break; } + objSkinFile.Write(); strMessage += objSkinFile.Messages; - strMessage += SkinController.FormatMessage(FILE_END, Path.GetFileName(FileName), 1, false); + strMessage += SkinController.FormatMessage(this.FILE_END, Path.GetFileName(FileName), 1, false); return strMessage; } @@ -274,36 +256,33 @@ public string ProcessFile(string FileName, SkinParser ParseOption) /// ----------------------------------------------------------------------------- public string ProcessList(ArrayList FileList) { - return ProcessList(FileList, SkinParser.Localized); + return this.ProcessList(FileList, SkinParser.Localized); } public string ProcessList(ArrayList FileList, SkinParser ParseOption) { foreach (string FileName in FileList) { - Message += ProcessFile(FileName, ParseOption); + this.Message += this.ProcessFile(FileName, ParseOption); } - Message += SkinController.FormatMessage(FILES_END, SkinRoot + " :: " + SkinName, 0, false); - return Message; + + this.Message += SkinController.FormatMessage(this.FILES_END, this.SkinRoot + " :: " + this.SkinName, 0, false); + return this.Message; } public string ProcessSkin(string SkinSource, XmlDocument SkinAttributes, SkinParser ParseOption) { var objSkinFile = new SkinFile(SkinSource, SkinAttributes); string contents = objSkinFile.Contents; - Message += ControlFactory.Parse(ref contents, objSkinFile.Attributes); - Message += objSkinFile.PrependASCXDirectives(ControlFactory.Registrations); + this.Message += this.ControlFactory.Parse(ref contents, objSkinFile.Attributes); + this.Message += objSkinFile.PrependASCXDirectives(this.ControlFactory.Registrations); return contents; - } - - #endregion - - #region Nested type: ControlParser - + } + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : SkinFileProcessor.ControlParser - /// + /// Project : DotNetNuke + /// Class : SkinFileProcessor.ControlParser + /// /// ----------------------------------------------------------------------------- /// /// Parsing functionality for token replacement in new skin files. @@ -321,16 +300,17 @@ public string ProcessSkin(string SkinSource, XmlDocument SkinAttributes, SkinPar /// ----------------------------------------------------------------------------- private class ControlParser { + private static readonly Regex FindTokenInstance = + new Regex("\\[\\s*(?\\w*)\\s*:?\\s*(?\\w*)\\s*]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly Hashtable m_ControlList; private XmlDocument m_Attributes = new XmlDocument { XmlResolver = null }; - private string m_ParseMessages = ""; + private string m_ParseMessages = string.Empty; private ArrayList m_RegisterList = new ArrayList(); - - private static readonly Regex FindTokenInstance = - new Regex("\\[\\s*(?\\w*)\\s*:?\\s*(?\\w*)\\s*]", RegexOptions.IgnoreCase | RegexOptions.Compiled); - + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// ControlParser class constructor. /// /// @@ -339,12 +319,12 @@ private class ControlParser /// ----------------------------------------------------------------------------- public ControlParser(Hashtable ControlList) { - m_ControlList = (Hashtable)ControlList.Clone(); + this.m_ControlList = (Hashtable)ControlList.Clone(); } /// ----------------------------------------------------------------------------- /// - /// Registration directives generated as a result of the Parse method. + /// Gets registration directives generated as a result of the Parse method. /// /// ArrayList of formatted registration directives. /// @@ -361,7 +341,7 @@ internal ArrayList Registrations { get { - return m_RegisterList; + return this.m_RegisterList; } } @@ -369,7 +349,7 @@ private MatchEvaluator Handler { get { - return TokenMatchHandler; + return this.TokenMatchHandler; } } @@ -377,11 +357,12 @@ private ArrayList RegisterList { get { - return m_RegisterList; + return this.m_RegisterList; } + set { - m_RegisterList = value; + this.m_RegisterList = value; } } @@ -389,7 +370,7 @@ private Hashtable ControlList { get { - return m_ControlList; + return this.m_ControlList; } } @@ -397,11 +378,12 @@ private XmlDocument Attributes { get { - return m_Attributes; + return this.m_Attributes; } + set { - m_Attributes = value; + this.m_Attributes = value; } } @@ -409,11 +391,12 @@ private string Messages { get { - return m_ParseMessages; + return this.m_ParseMessages; } + set { - m_ParseMessages = value; + this.m_ParseMessages = value; } } @@ -431,17 +414,19 @@ private string Messages /// ----------------------------------------------------------------------------- public string Parse(ref string Source, XmlDocument Attributes) { - Messages = string.Empty; - //set the token attributes + this.Messages = string.Empty; + + // set the token attributes this.Attributes = Attributes; - //clear register list - RegisterList.Clear(); + + // clear register list + this.RegisterList.Clear(); - //define the regular expression to match tokens + // define the regular expression to match tokens - //parse the file - Source = FindTokenInstance.Replace(Source, Handler); - return Messages; + // parse the file + Source = FindTokenInstance.Replace(Source, this.Handler); + return this.Messages; } /// ----------------------------------------------------------------------------- @@ -473,44 +458,47 @@ private string TokenMatchHandler(Match m) string Token = m.Groups["token"].Value.ToUpper(); string ControlName = Token + m.Groups["instance"].Value; - //if the token has an instance name, use it to look for the corresponding attributes - string AttributeNode = Token + (String.IsNullOrEmpty(m.Groups["instance"].Value) ? "" : ":" + m.Groups["instance"].Value); + // if the token has an instance name, use it to look for the corresponding attributes + string AttributeNode = Token + (string.IsNullOrEmpty(m.Groups["instance"].Value) ? string.Empty : ":" + m.Groups["instance"].Value); - Messages += SkinController.FormatMessage(TOKEN_PROC, "[" + AttributeNode + "]", 2, false); + this.Messages += SkinController.FormatMessage(TOKEN_PROC, "[" + AttributeNode + "]", 2, false); - //if the token is a recognized skin control - if (ControlList.ContainsKey(Token) || Token.IndexOf("CONTENTPANE") != -1) + // if the token is a recognized skin control + if (this.ControlList.ContainsKey(Token) || Token.IndexOf("CONTENTPANE") != -1) { - string SkinControl = ""; + string SkinControl = string.Empty; - if (ControlList.ContainsKey(Token)) + if (this.ControlList.ContainsKey(Token)) { - Messages += SkinController.FormatMessage(TOKEN_SKIN, (string)ControlList[Token], 2, false); + this.Messages += SkinController.FormatMessage(TOKEN_SKIN, (string)this.ControlList[Token], 2, false); } else { - Messages += SkinController.FormatMessage(TOKEN_PANE, Token, 2, false); + this.Messages += SkinController.FormatMessage(TOKEN_PANE, Token, 2, false); } - //f there is an attribute file - if (Attributes.DocumentElement != null) + // f there is an attribute file + if (this.Attributes.DocumentElement != null) { - //look for the the node of this instance of the token - XmlNode xmlSkinAttributeRoot = Attributes.DocumentElement.SelectSingleNode("descendant::Object[Token='[" + AttributeNode + "]']"); - //if the token is found + // look for the the node of this instance of the token + XmlNode xmlSkinAttributeRoot = this.Attributes.DocumentElement.SelectSingleNode("descendant::Object[Token='[" + AttributeNode + "]']"); + + // if the token is found if (xmlSkinAttributeRoot != null) { - Messages += SkinController.FormatMessage(TOKEN_FOUND, "[" + AttributeNode + "]", 2, false); - //process each token attribute + this.Messages += SkinController.FormatMessage(TOKEN_FOUND, "[" + AttributeNode + "]", 2, false); + + // process each token attribute foreach (XmlNode xmlSkinAttribute in xmlSkinAttributeRoot.SelectNodes(".//Settings/Setting")) { - if (!String.IsNullOrEmpty(xmlSkinAttribute.SelectSingleNode("Value").InnerText)) + if (!string.IsNullOrEmpty(xmlSkinAttribute.SelectSingleNode("Value").InnerText)) { - //append the formatted attribute to the inner contents of the control statement - Messages += SkinController.FormatMessage(TOKEN_FORMAT, - xmlSkinAttribute.SelectSingleNode("Name").InnerText + "=\"" + xmlSkinAttribute.SelectSingleNode("Value").InnerText + "\"", - 2, - false); + // append the formatted attribute to the inner contents of the control statement + this.Messages += SkinController.FormatMessage( + TOKEN_FORMAT, + xmlSkinAttribute.SelectSingleNode("Name").InnerText + "=\"" + xmlSkinAttribute.SelectSingleNode("Value").InnerText + "\"", + 2, + false); SkinControl += " " + xmlSkinAttribute.SelectSingleNode("Name").InnerText + "=\"" + xmlSkinAttribute.SelectSingleNode("Value").InnerText.Replace("\"", """) + "\""; } @@ -518,23 +506,24 @@ private string TokenMatchHandler(Match m) } else { - Messages += SkinController.FormatMessage(TOKEN_NOTFOUND_INFILE, "[" + AttributeNode + "]", 2, false); + this.Messages += SkinController.FormatMessage(TOKEN_NOTFOUND_INFILE, "[" + AttributeNode + "]", 2, false); } } - if (ControlList.ContainsKey(Token)) + + if (this.ControlList.ContainsKey(Token)) { - //create the skin object user control tag + // create the skin object user control tag SkinControl = "dnn:" + Token + " runat=\"server\" id=\"dnn" + ControlName + "\"" + SkinControl; - //save control registration statement - string ControlRegistration = "<%@ Register TagPrefix=\"dnn\" TagName=\"" + Token + "\" Src=\"~/" + (string)ControlList[Token] + "\" %>" + Environment.NewLine; - if (RegisterList.Contains(ControlRegistration) == false) + // save control registration statement + string ControlRegistration = "<%@ Register TagPrefix=\"dnn\" TagName=\"" + Token + "\" Src=\"~/" + (string)this.ControlList[Token] + "\" %>" + Environment.NewLine; + if (this.RegisterList.Contains(ControlRegistration) == false) { - RegisterList.Add(ControlRegistration); + this.RegisterList.Add(ControlRegistration); } - //return the control statement - Messages += SkinController.FormatMessage(CONTROL_FORMAT, "<" + SkinControl + " />", 2, false); + // return the control statement + this.Messages += SkinController.FormatMessage(CONTROL_FORMAT, "<" + SkinControl + " />", 2, false); SkinControl = "<" + SkinControl + " />"; } @@ -544,34 +533,32 @@ private string TokenMatchHandler(Match m) { SkinControl = " id=\"ContentPane\""; } + SkinControl = "div runat=\"server\"" + SkinControl + ">"; } + return SkinControl; } else { - //return the unmodified token - //note that this is currently protecting array syntax in embedded javascript - //should be fixed in the regular expressions but is not, currently. - Messages += SkinController.FormatMessage(TOKEN_NOTFOUND, "[" + m.Groups["token"].Value + "]", 2, false); + // return the unmodified token + // note that this is currently protecting array syntax in embedded javascript + // should be fixed in the regular expressions but is not, currently. + this.Messages += SkinController.FormatMessage(TOKEN_NOTFOUND, "[" + m.Groups["token"].Value + "]", 2, false); return "[" + m.Groups["token"].Value + "]"; } } - } - - #endregion - - #region Nested type: ObjectParser - + } + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : SkinFileProcessor.ObjectParser - /// + /// Project : DotNetNuke + /// Class : SkinFileProcessor.ObjectParser + /// /// ----------------------------------------------------------------------------- /// /// Parsing functionality for token replacement in new skin files. @@ -589,18 +576,19 @@ private string TokenMatchHandler(Match m) /// ----------------------------------------------------------------------------- private class ObjectParser { - private readonly Hashtable m_ControlList; - private string m_ParseMessages = ""; - private ArrayList m_RegisterList = new ArrayList(); - - //define the regular expression to match objects + // define the regular expression to match objects private static readonly Regex FindObjectInstance = new Regex("\\.*?)
    ", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex MultiSpaceRegex = new Regex("\\s+", RegexOptions.Compiled); - + private static readonly Regex MultiSpaceRegex = new Regex("\\s+", RegexOptions.Compiled); + + private readonly Hashtable m_ControlList; + private string m_ParseMessages = string.Empty; + private ArrayList m_RegisterList = new ArrayList(); + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// ControlParser class constructor. /// /// @@ -609,12 +597,12 @@ private class ObjectParser /// ----------------------------------------------------------------------------- public ObjectParser(Hashtable ControlList) { - m_ControlList = (Hashtable)ControlList.Clone(); + this.m_ControlList = (Hashtable)ControlList.Clone(); } /// ----------------------------------------------------------------------------- /// - /// Registration directives generated as a result of the Parse method. + /// Gets registration directives generated as a result of the Parse method. /// /// ArrayList of formatted registration directives. /// @@ -631,7 +619,7 @@ internal ArrayList Registrations { get { - return m_RegisterList; + return this.m_RegisterList; } } @@ -639,7 +627,7 @@ private MatchEvaluator Handler { get { - return ObjectMatchHandler; + return this.ObjectMatchHandler; } } @@ -647,11 +635,12 @@ private ArrayList RegisterList { get { - return m_RegisterList; + return this.m_RegisterList; } + set { - m_RegisterList = value; + this.m_RegisterList = value; } } @@ -659,7 +648,7 @@ private Hashtable ControlList { get { - return m_ControlList; + return this.m_ControlList; } } @@ -667,11 +656,12 @@ private string Messages { get { - return m_ParseMessages; + return this.m_ParseMessages; } + set { - m_ParseMessages = value; + this.m_ParseMessages = value; } } @@ -686,15 +676,15 @@ private string Messages /// ----------------------------------------------------------------------------- public string Parse(ref string Source) { - Messages = string.Empty; + this.Messages = string.Empty; - //clear register list - RegisterList.Clear(); + // clear register list + this.RegisterList.Clear(); - //parse the file - Source = FindObjectInstance.Replace(Source, Handler); + // parse the file + Source = FindObjectInstance.Replace(Source, this.Handler); - return Messages; + return this.Messages; } /// ----------------------------------------------------------------------------- @@ -708,7 +698,7 @@ public string Parse(ref string Source) /// it encounters. The returned value of the handler is substituted for the /// original match. So the handler properly formats the replacement for the /// object and returns it instead. If an unknown object is encountered, the object - /// is unmodified. This can happen if an object is a client-side object or + /// is unmodified. This can happen if an object is a client-side object or /// has not yet been installed. /// /// ----------------------------------------------------------------------------- @@ -720,21 +710,21 @@ private string ObjectMatchHandler(Match m) string CONTROL_FORMAT = Util.GetLocalizedString("ControlFormat"); string OBJECT_NOTFOUND = Util.GetLocalizedString("ObjectNotFound"); - //"token" string matches will be in the form of (" id=".." codetype=".." codebase=".." etc...>") - //we need to assume properly formatted HTML - attributes will be enclosed in double quotes and there will no spaces between assignments ( ie. attribute="value" ) + // "token" string matches will be in the form of (" id=".." codetype=".." codebase=".." etc...>") + // we need to assume properly formatted HTML - attributes will be enclosed in double quotes and there will no spaces between assignments ( ie. attribute="value" ) - //extract the embedded object attributes (" id=".." codetype=".." codebase=".." etc...") + // extract the embedded object attributes (" id=".." codetype=".." codebase=".." etc...") string EmbeddedObjectAttributes = m.Groups["token"].Value.Substring(0, m.Groups["token"].Value.IndexOf(">")); - //split into array + // split into array string[] Attributes = EmbeddedObjectAttributes.Split(' '); - //declare skin object elements - string AttributeNode = ""; - string Token = ""; - string ControlName = ""; + // declare skin object elements + string AttributeNode = string.Empty; + string Token = string.Empty; + string ControlName = string.Empty; - //iterate and process valid attributes + // iterate and process valid attributes string[] Attribute; string AttributeName; string AttributeValue; @@ -744,7 +734,7 @@ private string ObjectMatchHandler(Match m) { Attribute = strAttribute.Split('='); AttributeName = Attribute[0].Trim(); - AttributeValue = Attribute[1].Trim().Replace("\"", ""); + AttributeValue = Attribute[1].Trim().Replace("\"", string.Empty); switch (AttributeName.ToLowerInvariant()) { case "id": @@ -760,60 +750,61 @@ private string ObjectMatchHandler(Match m) } } - //process skin object + // process skin object if (AttributeNode.Equals("dotnetnuke/server", StringComparison.InvariantCultureIgnoreCase)) { - //we have a valid skin object specification - Messages += SkinController.FormatMessage(OBJECT_PROC, Token, 2, false); + // we have a valid skin object specification + this.Messages += SkinController.FormatMessage(OBJECT_PROC, Token, 2, false); - //if the embedded object is a recognized skin object - if (ControlList.ContainsKey(Token) || Token == "CONTENTPANE") + // if the embedded object is a recognized skin object + if (this.ControlList.ContainsKey(Token) || Token == "CONTENTPANE") { - string SkinControl = ""; + string SkinControl = string.Empty; - if (ControlList.ContainsKey(Token)) + if (this.ControlList.ContainsKey(Token)) { - Messages += SkinController.FormatMessage(OBJECT_SKIN, (string)ControlList[Token], 2, false); + this.Messages += SkinController.FormatMessage(OBJECT_SKIN, (string)this.ControlList[Token], 2, false); } else { - Messages += SkinController.FormatMessage(OBJECT_PANE, Token, 2, false); + this.Messages += SkinController.FormatMessage(OBJECT_PANE, Token, 2, false); } - //process embedded object params + // process embedded object params string Parameters = m.Groups["token"].Value.Substring(m.Groups["token"].Value.IndexOf(">") + 1); - Parameters = Parameters.Replace("", ""); + Parameters = Parameters.Replace("", string.Empty); - //convert multiple spaces and carriage returns into single spaces + // convert multiple spaces and carriage returns into single spaces Parameters = MultiSpaceRegex.Replace(Parameters, " "); - if (ControlList.ContainsKey(Token)) + if (this.ControlList.ContainsKey(Token)) { - //create the skin object user control tag + // create the skin object user control tag SkinControl = "dnn:" + Token + " runat=\"server\" "; - if (!String.IsNullOrEmpty(ControlName)) + if (!string.IsNullOrEmpty(ControlName)) { SkinControl += "id=\"" + ControlName + "\" "; } + SkinControl += Parameters; - //save control registration statement - string ControlRegistration = "<%@ Register TagPrefix=\"dnn\" TagName=\"" + Token + "\" Src=\"~/" + (string)ControlList[Token] + "\" %>" + Environment.NewLine; - if (RegisterList.Contains(ControlRegistration) == false) + // save control registration statement + string ControlRegistration = "<%@ Register TagPrefix=\"dnn\" TagName=\"" + Token + "\" Src=\"~/" + (string)this.ControlList[Token] + "\" %>" + Environment.NewLine; + if (this.RegisterList.Contains(ControlRegistration) == false) { - RegisterList.Add(ControlRegistration); + this.RegisterList.Add(ControlRegistration); } - //return the control statement - Messages += SkinController.FormatMessage(CONTROL_FORMAT, "<" + SkinControl + " />", 2, false); + // return the control statement + this.Messages += SkinController.FormatMessage(CONTROL_FORMAT, "<" + SkinControl + " />", 2, false); SkinControl = "<" + SkinControl + "/>"; } else { SkinControl = "div runat=\"server\" "; - if (!String.IsNullOrEmpty(ControlName)) + if (!string.IsNullOrEmpty(ControlName)) { SkinControl += "id=\"" + ControlName + "\" "; } @@ -821,37 +812,35 @@ private string ObjectMatchHandler(Match m) { SkinControl += "id=\"ContentPane\" "; } + SkinControl += Parameters + ">"; } + return SkinControl; } else { - //return the unmodified embedded object - Messages += SkinController.FormatMessage(OBJECT_NOTFOUND, Token, 2, false); + // return the unmodified embedded object + this.Messages += SkinController.FormatMessage(OBJECT_NOTFOUND, Token, 2, false); return ""; } } else { - //return unmodified embedded object + // return unmodified embedded object return ""; } } - } - - #endregion - - #region Nested type: PathParser - + } + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : SkinFileProcessor.PathParser - /// + /// Project : DotNetNuke + /// Class : SkinFileProcessor.PathParser + /// /// ----------------------------------------------------------------------------- /// /// Parsing functionality for path replacement in new skin files. @@ -859,21 +848,14 @@ private string ObjectMatchHandler(Match m) /// /// This class encapsulates the data and methods necessary to appropriately /// handle all the path replacement parsing needs for new skin files. Parsing - /// supported for CSS syntax and HTML syntax (which covers ASCX files also). + /// supported for CSS syntax and HTML syntax (which covers ASCX files also). /// /// ----------------------------------------------------------------------------- private class PathParser { - private readonly string SUBST = Util.GetLocalizedString("Substituting"); - private readonly string SUBST_DETAIL = Util.GetLocalizedString("Substituting.Detail"); - private readonly ArrayList m_CSSPatterns = new ArrayList(); - private readonly ArrayList m_HTMLPatterns = new ArrayList(); - private string m_Messages = ""; - private string m_SkinPath = ""; - private const RegexOptions PatternOptions = RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled; - //retrieve the patterns + // retrieve the patterns private static readonly Regex[] HtmlArrayPattern = { new Regex("(?]*?\\sprofile\\s*=\\s*\")(?!https://|http://|\\\\|[~/])(?[^\"]*)(?\"[^>]*>)", PatternOptions), @@ -886,19 +868,25 @@ private class PathParser new Regex("(?<(?:base|link|a|area)[^>]*?\\shref\\s*=\\s*\")(?!https://|http://|\\\\|[~/]|javascript:|mailto:)(?[^\"]*)(?\"[^>]*>)", PatternOptions), new Regex("(?<(?:blockquote|ins|del|q)[^>]*?\\scite\\s*=\\s*\")(?!https://|http://|\\\\|[~/])(?[^\"]*)(?\"[^>]*>)", PatternOptions), new Regex("(?<(?:param\\s+name\\s*=\\s*\"(?:movie|src|base)\")[^>]*?\\svalue\\s*=\\s*\")(?!https://|http://|\\\\|[~/])(?[^\"]*)(?\"[^>]*>)", PatternOptions), - new Regex("(?]*?\\s(?:src)\\s*=\\s*\")(?!https://|http://|\\\\|[~/])(?[^\"]*)(?\"[^>]*>)", PatternOptions) + new Regex("(?]*?\\s(?:src)\\s*=\\s*\")(?!https://|http://|\\\\|[~/])(?[^\"]*)(?\"[^>]*>)", PatternOptions), }; + + private readonly string SUBST = Util.GetLocalizedString("Substituting"); + private readonly string SUBST_DETAIL = Util.GetLocalizedString("Substituting.Detail"); + private readonly ArrayList m_CSSPatterns = new ArrayList(); + private readonly ArrayList m_HTMLPatterns = new ArrayList(); + private string m_Messages = string.Empty; + private string m_SkinPath = string.Empty; - //retrieve the patterns + // retrieve the patterns private static readonly Regex[] CssArrayPattern = { - new Regex("(?\\surl\\u0028)(?[^\\u0029]*)(?\\u0029.*;)", PatternOptions) + new Regex("(?\\surl\\u0028)(?[^\\u0029]*)(?\\u0029.*;)", PatternOptions), }; - - + /// ----------------------------------------------------------------------------- /// - /// List of regular expressions for processing HTML syntax. + /// Gets list of regular expressions for processing HTML syntax. /// /// ArrayList of Regex objects formatted for the Parser method. /// @@ -912,22 +900,23 @@ public ArrayList HTMLList { get { - //if the arraylist in uninitialized - if (m_HTMLPatterns.Count == 0) + // if the arraylist in uninitialized + if (this.m_HTMLPatterns.Count == 0) { - //for each pattern, create a regex object - m_HTMLPatterns.AddRange(HtmlArrayPattern); + // for each pattern, create a regex object + this.m_HTMLPatterns.AddRange(HtmlArrayPattern); - //optimize the arraylist size since it will not change - m_HTMLPatterns.TrimToSize(); + // optimize the arraylist size since it will not change + this.m_HTMLPatterns.TrimToSize(); } - return m_HTMLPatterns; + + return this.m_HTMLPatterns; } } /// ----------------------------------------------------------------------------- /// - /// List of regular expressions for processing CSS syntax. + /// Gets list of regular expressions for processing CSS syntax. /// /// ArrayList of Regex objects formatted for the Parser method. /// @@ -941,16 +930,17 @@ public ArrayList CSSList { get { - //if the arraylist in uninitialized - if (m_CSSPatterns.Count == 0) + // if the arraylist in uninitialized + if (this.m_CSSPatterns.Count == 0) { - //for each pattern, create a regex object - m_CSSPatterns.AddRange(CssArrayPattern); + // for each pattern, create a regex object + this.m_CSSPatterns.AddRange(CssArrayPattern); - //optimize the arraylist size since it will not change - m_CSSPatterns.TrimToSize(); + // optimize the arraylist size since it will not change + this.m_CSSPatterns.TrimToSize(); } - return m_CSSPatterns; + + return this.m_CSSPatterns; } } @@ -958,7 +948,7 @@ private MatchEvaluator Handler { get { - return MatchHandler; + return this.MatchHandler; } } @@ -966,11 +956,12 @@ private string SkinPath { get { - return m_SkinPath; + return this.m_SkinPath; } + set { - m_SkinPath = value; + this.m_SkinPath = value; } } @@ -991,19 +982,21 @@ private string SkinPath /// ----------------------------------------------------------------------------- public string Parse(ref string Source, ArrayList RegexList, string SkinPath, SkinParser ParseOption) { - m_Messages = ""; + this.m_Messages = string.Empty; - //set path propery which is file specific + // set path propery which is file specific this.SkinPath = SkinPath; - //set parse option + + // set parse option this.ParseOption = ParseOption; - //process each regular expression + // process each regular expression for (int i = 0; i <= RegexList.Count - 1; i++) { - Source = ((Regex)RegexList[i]).Replace(Source, Handler); + Source = ((Regex)RegexList[i]).Replace(Source, this.Handler); } - return m_Messages; + + return this.m_Messages; } /// ----------------------------------------------------------------------------- @@ -1024,45 +1017,44 @@ private string MatchHandler(Match m) string strOldTag = m.Groups["tag"].Value + m.Groups["content"].Value + m.Groups["endtag"].Value; string strNewTag = strOldTag; - //we do not want to process object tags to DotNetNuke widgets + // we do not want to process object tags to DotNetNuke widgets if (!m.Groups[0].Value.ToLowerInvariant().Contains("codetype=\"dotnetnuke/client\"")) { - switch (ParseOption) + switch (this.ParseOption) { case SkinParser.Localized: - //if the tag does not contain the localized path - if (strNewTag.IndexOf(SkinPath) == -1) + // if the tag does not contain the localized path + if (strNewTag.IndexOf(this.SkinPath) == -1) { - //insert the localized path - strNewTag = m.Groups["tag"].Value + SkinPath + m.Groups["content"].Value + m.Groups["endtag"].Value; + // insert the localized path + strNewTag = m.Groups["tag"].Value + this.SkinPath + m.Groups["content"].Value + m.Groups["endtag"].Value; } + break; case SkinParser.Portable: - //if the tag does not contain a reference to the skinpath + // if the tag does not contain a reference to the skinpath if (strNewTag.IndexOf("<%= skinpath %>", StringComparison.InvariantCultureIgnoreCase) == -1) { - //insert the skinpath + // insert the skinpath strNewTag = m.Groups["tag"].Value + "<%= SkinPath %>" + m.Groups["content"].Value + m.Groups["endtag"].Value; } - //if the tag contains the localized path - if (strNewTag.IndexOf(SkinPath) != -1) + // if the tag contains the localized path + if (strNewTag.IndexOf(this.SkinPath) != -1) { - //remove the localized path - strNewTag = strNewTag.Replace(SkinPath, ""); + // remove the localized path + strNewTag = strNewTag.Replace(this.SkinPath, string.Empty); } + break; } } - m_Messages += SkinController.FormatMessage(SUBST, string.Format(SUBST_DETAIL, HttpUtility.HtmlEncode(strOldTag), HttpUtility.HtmlEncode(strNewTag)), 2, false); + + this.m_Messages += SkinController.FormatMessage(this.SUBST, string.Format(this.SUBST_DETAIL, HttpUtility.HtmlEncode(strOldTag), HttpUtility.HtmlEncode(strNewTag)), 2, false); return strNewTag; } - } - - #endregion - - #region Nested type: SkinFile - + } + /// ----------------------------------------------------------------------------- /// /// Utility class for processing of skin files. @@ -1072,6 +1064,11 @@ private string MatchHandler(Match m) /// ----------------------------------------------------------------------------- private class SkinFile { + private const string StrPattern = "<\\s*body[^>]*>(?.*)<\\s*/\\s*body\\s*>"; + + private static readonly Regex PaneCheck1Regex = new Regex("\\s*id\\s*=\\s*\"" + Globals.glbDefaultPane + "\"", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex PaneCheck2Regex = new Regex("\\s*[" + Globals.glbDefaultPane + "]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly string CONTROL_DIR = Util.GetLocalizedString("ControlDirective"); private readonly string CONTROL_REG = Util.GetLocalizedString("ControlRegister"); private readonly string FILE_FORMAT_ERROR = Util.GetLocalizedString("FileFormat.Error"); @@ -1085,16 +1082,12 @@ private class SkinFile private readonly string m_SkinRootPath; private readonly string m_WriteFileName; private string FILE_FORMAT_DETAIL = Util.GetLocalizedString("FileFormat.Detail"); - private string m_Messages = ""; - - private static readonly Regex PaneCheck1Regex = new Regex("\\s*id\\s*=\\s*\"" + Globals.glbDefaultPane + "\"", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex PaneCheck2Regex = new Regex("\\s*[" + Globals.glbDefaultPane + "]", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - const string StrPattern = "<\\s*body[^>]*>(?.*)<\\s*/\\s*body\\s*>"; - private static readonly Regex BodyExtractionRegex = new Regex(StrPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); - + private string m_Messages = string.Empty; + private static readonly Regex BodyExtractionRegex = new Regex(StrPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// SkinFile class constructor. /// /// @@ -1102,17 +1095,18 @@ private class SkinFile /// /// The constructor primes the utility class with basic file information. /// It also checks for the existentce of a skinfile level attribute file - /// and read it in, if found. + /// and read it in, if found. /// /// ----------------------------------------------------------------------------- public SkinFile(string SkinContents, XmlDocument SkinAttributes) { - m_FileAttributes = SkinAttributes; - Contents = SkinContents; - } - + this.m_FileAttributes = SkinAttributes; + this.Contents = SkinContents; + } + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// SkinFile class constructor. /// /// @@ -1121,58 +1115,59 @@ public SkinFile(string SkinContents, XmlDocument SkinAttributes) /// /// The constructor primes the utility class with basic file information. /// It also checks for the existentce of a skinfile level attribute file - /// and read it in, if found. + /// and read it in, if found. /// /// ----------------------------------------------------------------------------- public SkinFile(string SkinRoot, string FileName, XmlDocument SkinAttributes) { - //capture file information - m_FileName = FileName; - m_FileExtension = Path.GetExtension(FileName); - m_SkinRoot = SkinRoot; - m_FileAttributes = SkinAttributes; - - //determine and store path to portals skin root folder - string strTemp = FileName.Replace(Path.GetFileName(FileName), ""); + // capture file information + this.m_FileName = FileName; + this.m_FileExtension = Path.GetExtension(FileName); + this.m_SkinRoot = SkinRoot; + this.m_FileAttributes = SkinAttributes; + + // determine and store path to portals skin root folder + string strTemp = FileName.Replace(Path.GetFileName(FileName), string.Empty); strTemp = strTemp.Replace("\\", "/"); - m_SkinRootPath = Globals.ApplicationPath + strTemp.Substring(strTemp.ToUpper().IndexOf("/PORTALS")); + this.m_SkinRootPath = Globals.ApplicationPath + strTemp.Substring(strTemp.ToUpper().IndexOf("/PORTALS")); - //read file contents - Contents = Read(FileName); + // read file contents + this.Contents = this.Read(FileName); - //setup some attributes based on file extension - switch (FileExtension) + // setup some attributes based on file extension + switch (this.FileExtension) { case ".htm": case ".html": - //set output file name to .ASCX - m_WriteFileName = FileName.Replace(Path.GetExtension(FileName), ".ascx"); + // set output file name to .ASCX + this.m_WriteFileName = FileName.Replace(Path.GetExtension(FileName), ".ascx"); - //capture warning if file does not contain a id="ContentPane" or [CONTENTPANE] - if (!PaneCheck1Regex.IsMatch(Contents) && !PaneCheck2Regex.IsMatch(Contents)) + // capture warning if file does not contain a id="ContentPane" or [CONTENTPANE] + if (!PaneCheck1Regex.IsMatch(this.Contents) && !PaneCheck2Regex.IsMatch(this.Contents)) { - m_Messages += SkinController.FormatMessage(FILE_FORMAT_ERROR, string.Format(FILE_FORMAT_ERROR, FileName), 2, true); + this.m_Messages += SkinController.FormatMessage(this.FILE_FORMAT_ERROR, string.Format(this.FILE_FORMAT_ERROR, FileName), 2, true); } - //Check for existence of and load skin file level attribute information - if (File.Exists(FileName.Replace(FileExtension, ".xml"))) + // Check for existence of and load skin file level attribute information + if (File.Exists(FileName.Replace(this.FileExtension, ".xml"))) { try { - m_FileAttributes.Load(FileName.Replace(FileExtension, ".xml")); - m_Messages += SkinController.FormatMessage(FILE_LOAD, FileName, 2, false); + this.m_FileAttributes.Load(FileName.Replace(this.FileExtension, ".xml")); + this.m_Messages += SkinController.FormatMessage(this.FILE_LOAD, FileName, 2, false); } - catch (Exception exc) //could not load XML file + catch (Exception exc) // could not load XML file { Logger.Error(exc); - m_FileAttributes = SkinAttributes; - m_Messages += SkinController.FormatMessage(FILE_LOAD_ERROR, FileName, 2, true); + this.m_FileAttributes = SkinAttributes; + this.m_Messages += SkinController.FormatMessage(this.FILE_LOAD_ERROR, FileName, 2, true); } } + break; default: - //output file name is same as input file name - m_WriteFileName = FileName; + // output file name is same as input file name + this.m_WriteFileName = FileName; break; } } @@ -1181,7 +1176,7 @@ public string SkinRoot { get { - return m_SkinRoot; + return this.m_SkinRoot; } } @@ -1189,7 +1184,7 @@ public XmlDocument Attributes { get { - return m_FileAttributes; + return this.m_FileAttributes; } } @@ -1197,7 +1192,7 @@ public string Messages { get { - return m_Messages; + return this.m_Messages; } } @@ -1205,7 +1200,7 @@ public string FileName { get { - return m_FileName; + return this.m_FileName; } } @@ -1213,7 +1208,7 @@ public string WriteFileName { get { - return m_WriteFileName; + return this.m_WriteFileName; } } @@ -1221,7 +1216,7 @@ public string FileExtension { get { - return m_FileExtension; + return this.m_FileExtension; } } @@ -1229,33 +1224,24 @@ public string SkinRootPath { get { - return m_SkinRootPath; + return this.m_SkinRootPath; } } public string Contents { get; set; } - private string Read(string FileName) - { - using (var objStreamReader = new StreamReader(FileName)) - { - string strFileContents = objStreamReader.ReadToEnd(); - objStreamReader.Close(); - return strFileContents; - } - } - public void Write() { - //delete the file before attempting to write - if (File.Exists(WriteFileName)) + // delete the file before attempting to write + if (File.Exists(this.WriteFileName)) { - File.Delete(WriteFileName); + File.Delete(this.WriteFileName); } - m_Messages += SkinController.FormatMessage(FILE_WRITE, Path.GetFileName(WriteFileName), 2, false); - using (var objStreamWriter = new StreamWriter(WriteFileName)) + + this.m_Messages += SkinController.FormatMessage(this.FILE_WRITE, Path.GetFileName(this.WriteFileName), 2, false); + using (var objStreamWriter = new StreamWriter(this.WriteFileName)) { - objStreamWriter.WriteLine(Contents); + objStreamWriter.WriteLine(this.Contents); objStreamWriter.Flush(); objStreamWriter.Close(); } @@ -1273,39 +1259,49 @@ public void Write() /// ----------------------------------------------------------------------------- public string PrependASCXDirectives(ArrayList Registrations) { - string Messages = ""; - string Prefix = ""; + string Messages = string.Empty; + string Prefix = string.Empty; - //format and save @Control directive - Match objMatch = BodyExtractionRegex.Match(Contents); + // format and save @Control directive + Match objMatch = BodyExtractionRegex.Match(this.Contents); if (objMatch.Success && !string.IsNullOrEmpty(objMatch.Groups[1].Value)) { - //if the skin source is an HTML document, extract the content within the tags - Contents = objMatch.Groups[1].Value; + // if the skin source is an HTML document, extract the content within the tags + this.Contents = objMatch.Groups[1].Value; } - if (SkinRoot == SkinController.RootSkin) + + if (this.SkinRoot == SkinController.RootSkin) { Prefix += "<%@ Control language=\"vb\" AutoEventWireup=\"false\" Explicit=\"True\" Inherits=\"DotNetNuke.UI.Skins.Skin\" %>" + Environment.NewLine; } - else if (SkinRoot == SkinController.RootContainer) + else if (this.SkinRoot == SkinController.RootContainer) { Prefix += "<%@ Control language=\"vb\" AutoEventWireup=\"false\" Explicit=\"True\" Inherits=\"DotNetNuke.UI.Containers.Container\" %>" + Environment.NewLine; } - Messages += SkinController.FormatMessage(CONTROL_DIR, HttpUtility.HtmlEncode(Prefix), 2, false); + + Messages += SkinController.FormatMessage(this.CONTROL_DIR, HttpUtility.HtmlEncode(Prefix), 2, false); - //add preformatted Control Registrations + // add preformatted Control Registrations foreach (string Item in Registrations) { - Messages += SkinController.FormatMessage(CONTROL_REG, HttpUtility.HtmlEncode(Item), 2, false); + Messages += SkinController.FormatMessage(this.CONTROL_REG, HttpUtility.HtmlEncode(Item), 2, false); Prefix += Item; } - //update file contents to include ascx header information - Contents = Prefix + Contents; + // update file contents to include ascx header information + this.Contents = Prefix + this.Contents; return Messages; } - } - #endregion + private string Read(string FileName) + { + using (var objStreamReader = new StreamReader(FileName)) + { + string strFileContents = objStreamReader.ReadToEnd(); + objStreamReader.Close(); + return strFileContents; + } + } + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinInfo.cs b/DNN Platform/Library/UI/Skins/SkinInfo.cs index 1da64b32312..65091e6dc8e 100644 --- a/DNN Platform/Library/UI/Skins/SkinInfo.cs +++ b/DNN Platform/Library/UI/Skins/SkinInfo.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : SkinInfo - /// + /// Project : DotNetNuke + /// Class : SkinInfo + /// /// ----------------------------------------------------------------------------- /// - /// Handles the Business Object for Skins + /// Handles the Business Object for Skins. /// /// /// @@ -34,11 +29,12 @@ public int SkinId { get { - return _SkinId; + return this._SkinId; } + set { - _SkinId = value; + this._SkinId = value; } } @@ -46,11 +42,12 @@ public int PortalId { get { - return _PortalId; + return this._PortalId; } + set { - _PortalId = value; + this._PortalId = value; } } @@ -58,11 +55,12 @@ public string SkinRoot { get { - return _SkinRoot; + return this._SkinRoot; } + set { - _SkinRoot = value; + this._SkinRoot = value; } } @@ -70,11 +68,12 @@ public SkinType SkinType { get { - return _SkinType; + return this._SkinType; } + set { - _SkinType = value; + this._SkinType = value; } } @@ -82,11 +81,12 @@ public string SkinSrc { get { - return _SkinSrc; + return this._SkinSrc; } + set { - _SkinSrc = value; + this._SkinSrc = value; } } } diff --git a/DNN Platform/Library/UI/Skins/SkinObjectBase.cs b/DNN Platform/Library/UI/Skins/SkinObjectBase.cs index 9162d4b0848..b2a3ee85e04 100644 --- a/DNN Platform/Library/UI/Skins/SkinObjectBase.cs +++ b/DNN Platform/Library/UI/Skins/SkinObjectBase.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; -using System.Web.UI; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System.ComponentModel; + using System.Web.UI; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using DotNetNuke.UI.Modules; + /// ----------------------------------------------------------------------------- /// /// The SkinObject class defines a custom base class inherited by all @@ -25,10 +20,11 @@ public class SkinObjectBase : UserControl, ISkinControl { /// ----------------------------------------------------------------------------- /// - /// Gets the portal Settings for this Skin Control + /// Gets the portal Settings for this Skin Control. /// /// ----------------------------------------------------------------------------- - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { get @@ -39,7 +35,7 @@ public PortalSettings PortalSettings /// ----------------------------------------------------------------------------- /// - /// Gets whether we are in Admin Mode + /// Gets a value indicating whether gets whether we are in Admin Mode. /// /// ----------------------------------------------------------------------------- public bool AdminMode @@ -48,17 +44,13 @@ public bool AdminMode { return TabPermissionController.CanAdminPage(); } - } - - #region ISkinControl Members - + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the associated ModuleControl for this SkinControl + /// Gets or sets and sets the associated ModuleControl for this SkinControl. /// /// ----------------------------------------------------------------------------- - public IModuleControl ModuleControl { get; set; } - - #endregion + public IModuleControl ModuleControl { get; set; } } } diff --git a/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs b/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs index dc469854a77..9d096cf05c8 100644 --- a/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs +++ b/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs @@ -1,58 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Xml.Serialization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.Collections.Generic; + using System.Data; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : SkinPackageInfo - /// + /// Project : DotNetNuke + /// Class : SkinPackageInfo + /// /// ----------------------------------------------------------------------------- /// - /// Handles the Business Object for Skins + /// Handles the Business Object for Skins. /// /// /// /// ----------------------------------------------------------------------------- [Serializable] public class SkinPackageInfo : BaseEntityInfo, IHydratable - { - #region "Private Members" - + { private int _PackageID = Null.NullInteger; private int _PortalID = Null.NullInteger; private string _SkinName; private int _SkinPackageID = Null.NullInteger; private string _SkinType; - private Dictionary _Skins = new Dictionary(); - - #endregion - - #region "Public Properties" - + private Dictionary _Skins = new Dictionary(); + public int PackageID { get { - return _PackageID; + return this._PackageID; } + set { - _PackageID = value; + this._PackageID = value; } } @@ -60,11 +50,12 @@ public int SkinPackageID { get { - return _SkinPackageID; + return this._SkinPackageID; } + set { - _SkinPackageID = value; + this._SkinPackageID = value; } } @@ -72,11 +63,12 @@ public int PortalID { get { - return _PortalID; + return this._PortalID; } + set { - _PortalID = value; + this._PortalID = value; } } @@ -84,11 +76,12 @@ public string SkinName { get { - return _SkinName; + return this._SkinName; } + set { - _SkinName = value; + this._SkinName = value; } } @@ -97,11 +90,12 @@ public Dictionary Skins { get { - return _Skins; + return this._Skins; } + set { - _Skins = value; + this._Skins = value; } } @@ -109,26 +103,37 @@ public string SkinType { get { - return _SkinType; + return this._SkinType; } + set { - _SkinType = value; + this._SkinType = value; } - } - - #endregion - - #region IHydratable Members + } + public int KeyID + { + get + { + return this.SkinPackageID; + } + + set + { + this.SkinPackageID = value; + } + } + public void Fill(IDataReader dr) { - SkinPackageID = Null.SetNullInteger(dr["SkinPackageID"]); - PackageID = Null.SetNullInteger(dr["PackageID"]); - SkinName = Null.SetNullString(dr["SkinName"]); - SkinType = Null.SetNullString(dr["SkinType"]); - //Call the base classes fill method to populate base class proeprties - base.FillInternal(dr); + this.SkinPackageID = Null.SetNullInteger(dr["SkinPackageID"]); + this.PackageID = Null.SetNullInteger(dr["PackageID"]); + this.SkinName = Null.SetNullString(dr["SkinName"]); + this.SkinType = Null.SetNullString(dr["SkinType"]); + + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); if (dr.NextResult()) { @@ -137,24 +142,10 @@ public void Fill(IDataReader dr) int skinID = Null.SetNullInteger(dr["SkinID"]); if (skinID > Null.NullInteger) { - _Skins[skinID] = Null.SetNullString(dr["SkinSrc"]); + this._Skins[skinID] = Null.SetNullString(dr["SkinSrc"]); } } } } - - public int KeyID - { - get - { - return SkinPackageID; - } - set - { - SkinPackageID = value; - } - } - - #endregion } } diff --git a/DNN Platform/Library/UI/Skins/SkinScope.cs b/DNN Platform/Library/UI/Skins/SkinScope.cs index ae21134a0d6..745128b1116 100644 --- a/DNN Platform/Library/UI/Skins/SkinScope.cs +++ b/DNN Platform/Library/UI/Skins/SkinScope.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins { public enum SkinScope { All = 0, Host = 1, - Site = 2 + Site = 2, } } diff --git a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs index 184f3b23992..21fb4c7b69d 100644 --- a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs @@ -1,60 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; - -using Image = System.Drawing.Image; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins { + using System; + using System.IO; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + + using Image = System.Drawing.Image; + /// ----------------------------------------------------------------------------- /// /// SkinThumbNailControl is a user control that provides that displays the skins - /// as a Radio ButtonList with Thumbnail Images where available + /// as a Radio ButtonList with Thumbnail Images where available. /// /// /// /// ----------------------------------------------------------------------------- public abstract class SkinThumbNailControl : UserControlBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SkinThumbNailControl)); - #region "Private Members" - protected HtmlGenericControl ControlContainer; - protected RadioButtonList OptSkin; - - #endregion - - #region "Properties" - + protected RadioButtonList OptSkin; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinThumbNailControl)); + public string Border { get { - return Convert.ToString(ViewState["SkinControlBorder"]); + return Convert.ToString(this.ViewState["SkinControlBorder"]); } + set { - ViewState["SkinControlBorder"] = value; - if (!String.IsNullOrEmpty(value)) + this.ViewState["SkinControlBorder"] = value; + if (!string.IsNullOrEmpty(value)) { - ControlContainer.Style.Add("border-top", value); - ControlContainer.Style.Add("border-bottom", value); - ControlContainer.Style.Add("border-left", value); - ControlContainer.Style.Add("border-right", value); + this.ControlContainer.Style.Add("border-top", value); + this.ControlContainer.Style.Add("border-bottom", value); + this.ControlContainer.Style.Add("border-left", value); + this.ControlContainer.Style.Add("border-right", value); } } } @@ -63,14 +53,15 @@ public int Columns { get { - return Convert.ToInt32(ViewState["SkinControlColumns"]); + return Convert.ToInt32(this.ViewState["SkinControlColumns"]); } + set { - ViewState["SkinControlColumns"] = value; + this.ViewState["SkinControlColumns"] = value; if (value > 0) { - OptSkin.RepeatColumns = value; + this.OptSkin.RepeatColumns = value; } } } @@ -79,14 +70,15 @@ public string Height { get { - return Convert.ToString(ViewState["SkinControlHeight"]); + return Convert.ToString(this.ViewState["SkinControlHeight"]); } + set { - ViewState["SkinControlHeight"] = value; - if (!String.IsNullOrEmpty(value)) + this.ViewState["SkinControlHeight"] = value; + if (!string.IsNullOrEmpty(value)) { - ControlContainer.Style.Add("height", value); + this.ControlContainer.Style.Add("height", value); } } } @@ -95,11 +87,12 @@ public string SkinRoot { get { - return Convert.ToString(ViewState["SkinRoot"]); + return Convert.ToString(this.ViewState["SkinRoot"]); } + set { - ViewState["SkinRoot"] = value; + this.ViewState["SkinRoot"] = value; } } @@ -107,17 +100,18 @@ public string SkinSrc { get { - return OptSkin.SelectedItem != null ? OptSkin.SelectedItem.Value : ""; + return this.OptSkin.SelectedItem != null ? this.OptSkin.SelectedItem.Value : string.Empty; } + set { - //select current skin + // select current skin int intIndex; - for (intIndex = 0; intIndex <= OptSkin.Items.Count - 1; intIndex++) + for (intIndex = 0; intIndex <= this.OptSkin.Items.Count - 1; intIndex++) { - if (OptSkin.Items[intIndex].Value == value) + if (this.OptSkin.Items[intIndex].Value == value) { - OptSkin.Items[intIndex].Selected = true; + this.OptSkin.Items[intIndex].Selected = true; break; } } @@ -128,77 +122,70 @@ public string Width { get { - return Convert.ToString(ViewState["SkinControlWidth"]); + return Convert.ToString(this.ViewState["SkinControlWidth"]); } + set { - ViewState["SkinControlWidth"] = value; - if (!String.IsNullOrEmpty(value)) + this.ViewState["SkinControlWidth"] = value; + if (!string.IsNullOrEmpty(value)) { - ControlContainer.Style.Add("width", value); + this.ControlContainer.Style.Add("width", value); } } - } - - #endregion - - #region "Private Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// AddDefaultSkin adds the not-specified skin to the radio button list + /// Clear clears the radio button list. /// /// /// /// ----------------------------------------------------------------------------- - private void AddDefaultSkin() + public void Clear() { - var strDefault = Localization.GetString("Not_Specified") + "
    "; - strDefault += ""; - OptSkin.Items.Insert(0, new ListItem(strDefault, "")); + this.OptSkin.Items.Clear(); } /// ----------------------------------------------------------------------------- /// - /// AddSkin adds the skin to the radio button list + /// LoadAllSkins loads all the available skins (Host and Site) to the radio button list. /// /// /// - /// Root Path. - /// The Skin Folder - /// The Skin File + /// Optionally include the "Not Specified" option. /// ----------------------------------------------------------------------------- - private void AddSkin(string root, string strFolder, string strFile) + public void LoadAllSkins(bool includeNotSpecified) { - var strImage = ""; - if (File.Exists(strFile.Replace(".ascx", ".jpg"))) - { - strImage += ""; - } - else + // default value + if (includeNotSpecified) { - strImage += ""; + this.AddDefaultSkin(); } - OptSkin.Items.Add(new ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)) + "
    " + strImage, root + "/" + strFolder + "/" + Path.GetFileName(strFile))); + + // load host skins (includeNotSpecified = false as we have already added it) + this.LoadHostSkins(false); + + // load portal skins (includeNotSpecified = false as we have already added it) + this.LoadPortalSkins(false); } /// ----------------------------------------------------------------------------- /// - /// format skin name + /// format skin name. /// /// /// - /// The Folder Name - /// The File Name without extension + /// The Folder Name. + /// The File Name without extension. private static string FormatSkinName(string strSkinFolder, string strSkinFile) { - if (strSkinFolder.Equals("_default", StringComparison.InvariantCultureIgnoreCase)) //host folder + if (strSkinFolder.Equals("_default", StringComparison.InvariantCultureIgnoreCase)) // host folder { return strSkinFile; } - - //portal folder + + // portal folder switch (strSkinFile.ToLowerInvariant()) { case "skin": @@ -212,11 +199,11 @@ private static string FormatSkinName(string strSkinFolder, string strSkinFile) /// ----------------------------------------------------------------------------- /// - /// CreateThumbnail creates a thumbnail of the Preview Image + /// CreateThumbnail creates a thumbnail of the Preview Image. /// /// /// - /// The Image File Name + /// The Image File Name. /// ----------------------------------------------------------------------------- private static string CreateThumbnail(string strImage) { @@ -224,130 +211,132 @@ private static string CreateThumbnail(string strImage) var strThumbnail = strImage.Replace(Path.GetFileName(strImage), "thumbnail_" + Path.GetFileName(strImage)); - //check if image has changed + // check if image has changed if (File.Exists(strThumbnail)) { - //var d1 = File.GetLastWriteTime(strThumbnail); - //var d2 = File.GetLastWriteTime(strImage); + // var d1 = File.GetLastWriteTime(strThumbnail); + // var d2 = File.GetLastWriteTime(strImage); if (File.GetLastWriteTime(strThumbnail) == File.GetLastWriteTime(strImage)) { blnCreate = false; } } + if (blnCreate) { - const int intSize = 140; //size of the thumbnail + const int intSize = 140; // size of the thumbnail Image objImage; try { objImage = Image.FromFile(strImage); - - //scale the image to prevent distortion + + // scale the image to prevent distortion int intWidth; int intHeight; double dblScale; if (objImage.Height > objImage.Width) { - //The height was larger, so scale the width + // The height was larger, so scale the width dblScale = (double)intSize / objImage.Height; intHeight = intSize; - intWidth = Convert.ToInt32(objImage.Width*dblScale); + intWidth = Convert.ToInt32(objImage.Width * dblScale); } else { - //The width was larger, so scale the height + // The width was larger, so scale the height dblScale = (double)intSize / objImage.Width; intWidth = intSize; - intHeight = Convert.ToInt32(objImage.Height*dblScale); + intHeight = Convert.ToInt32(objImage.Height * dblScale); } - - //create the thumbnail image - var objThumbnail = objImage.GetThumbnailImage(intWidth, intHeight, null, IntPtr.Zero); - - //delete the old file ( if it exists ) - if (File.Exists(strThumbnail)) + + // create the thumbnail image + var objThumbnail = objImage.GetThumbnailImage(intWidth, intHeight, null, IntPtr.Zero); + + // delete the old file ( if it exists ) + if (File.Exists(strThumbnail)) { File.Delete(strThumbnail); } - - //save the thumbnail image - objThumbnail.Save(strThumbnail, objImage.RawFormat); - - //set the file attributes - File.SetAttributes(strThumbnail, FileAttributes.Normal); + + // save the thumbnail image + objThumbnail.Save(strThumbnail, objImage.RawFormat); + + // set the file attributes + File.SetAttributes(strThumbnail, FileAttributes.Normal); File.SetLastWriteTime(strThumbnail, File.GetLastWriteTime(strImage)); - //tidy up + // tidy up objImage.Dispose(); objThumbnail.Dispose(); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } } + strThumbnail = Globals.ApplicationPath + "\\" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\", StringComparison.InvariantCultureIgnoreCase)); return strThumbnail; - } - - #endregion - - #region "Public Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// Clear clears the radio button list + /// AddDefaultSkin adds the not-specified skin to the radio button list. /// /// /// /// ----------------------------------------------------------------------------- - public void Clear() + private void AddDefaultSkin() { - OptSkin.Items.Clear(); + var strDefault = Localization.GetString("Not_Specified") + "
    "; + strDefault += ""; + this.OptSkin.Items.Insert(0, new ListItem(strDefault, string.Empty)); } /// ----------------------------------------------------------------------------- /// - /// LoadAllSkins loads all the available skins (Host and Site) to the radio button list + /// AddSkin adds the skin to the radio button list. /// /// /// - /// Optionally include the "Not Specified" option + /// Root Path. + /// The Skin Folder. + /// The Skin File. /// ----------------------------------------------------------------------------- - public void LoadAllSkins(bool includeNotSpecified) + private void AddSkin(string root, string strFolder, string strFile) { - //default value - if (includeNotSpecified) + var strImage = string.Empty; + if (File.Exists(strFile.Replace(".ascx", ".jpg"))) { - AddDefaultSkin(); + strImage += ""; } - - //load host skins (includeNotSpecified = false as we have already added it) - LoadHostSkins(false); - - //load portal skins (includeNotSpecified = false as we have already added it) - LoadPortalSkins(false); + else + { + strImage += ""; + } + + this.OptSkin.Items.Add(new ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)) + "
    " + strImage, root + "/" + strFolder + "/" + Path.GetFileName(strFile))); } /// ----------------------------------------------------------------------------- /// - /// LoadHostSkins loads all the available Host skins to the radio button list + /// LoadHostSkins loads all the available Host skins to the radio button list. /// /// /// - /// Optionally include the "Not Specified" option + /// Optionally include the "Not Specified" option. /// ----------------------------------------------------------------------------- public void LoadHostSkins(bool includeNotSpecified) { - - //default value + // default value if (includeNotSpecified) { - AddDefaultSkin(); + this.AddDefaultSkin(); } - - //load host skins - var strRoot = Globals.HostMapPath + SkinRoot; + + // load host skins + var strRoot = Globals.HostMapPath + this.SkinRoot; if (Directory.Exists(strRoot)) { var arrFolders = Directory.GetDirectories(strRoot); @@ -355,7 +344,7 @@ public void LoadHostSkins(bool includeNotSpecified) { if (!strFolder.EndsWith(Globals.glbHostSkinFolder)) { - LoadSkins(strFolder, "[G]", false); + this.LoadSkins(strFolder, "[G]", false); } } } @@ -363,49 +352,50 @@ public void LoadHostSkins(bool includeNotSpecified) /// ----------------------------------------------------------------------------- /// - /// LoadHostSkins loads all the available Site/Portal skins to the radio button list + /// LoadHostSkins loads all the available Site/Portal skins to the radio button list. /// /// /// - /// Optionally include the "Not Specified" option + /// Optionally include the "Not Specified" option. /// ----------------------------------------------------------------------------- public void LoadPortalSkins(bool includeNotSpecified) { - //default value + // default value if (includeNotSpecified) { - AddDefaultSkin(); + this.AddDefaultSkin(); } - - //load portal skins - var strRoot = PortalSettings.HomeDirectoryMapPath + SkinRoot; + + // load portal skins + var strRoot = this.PortalSettings.HomeDirectoryMapPath + this.SkinRoot; if (Directory.Exists(strRoot)) { var arrFolders = Directory.GetDirectories(strRoot); foreach (var strFolder in arrFolders) { - LoadSkins(strFolder, "[L]", false); + this.LoadSkins(strFolder, "[L]", false); } } } /// ----------------------------------------------------------------------------- /// - /// LoadSkins loads all the available skins in a specific folder to the radio button list + /// LoadSkins loads all the available skins in a specific folder to the radio button list. /// /// /// - /// The folder to search for skins - /// A string that identifies whether the skin is Host "[G]" or Site "[L]" - /// Optionally include the "Not Specified" option + /// The folder to search for skins. + /// A string that identifies whether the skin is Host "[G]" or Site "[L]". + /// Optionally include the "Not Specified" option. /// ----------------------------------------------------------------------------- public void LoadSkins(string strFolder, string skinType, bool includeNotSpecified) { - //default value + // default value if (includeNotSpecified) { - AddDefaultSkin(); + this.AddDefaultSkin(); } + if (Directory.Exists(strFolder)) { var arrFiles = Directory.GetFiles(strFolder, "*.ascx"); @@ -413,12 +403,9 @@ public void LoadSkins(string strFolder, string skinType, bool includeNotSpecifie foreach (var strFile in arrFiles) { - AddSkin(skinType + SkinRoot, strFolder, strFile); + this.AddSkin(skinType + this.SkinRoot, strFolder, strFile); } } - } - - #endregion - + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinType.cs b/DNN Platform/Library/UI/Skins/SkinType.cs index 78de4613776..4e0b4b6a524 100644 --- a/DNN Platform/Library/UI/Skins/SkinType.cs +++ b/DNN Platform/Library/UI/Skins/SkinType.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins { public enum SkinType { Portal = 0, - Admin = 1 + Admin = 1, } } diff --git a/DNN Platform/Library/UI/UIUtilities.cs b/DNN Platform/Library/UI/UIUtilities.cs index bdf7ba88fd0..26e38c7ce95 100644 --- a/DNN Platform/Library/UI/UIUtilities.cs +++ b/DNN Platform/Library/UI/UIUtilities.cs @@ -1,34 +1,81 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.ControlPanels; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI { + using System; + using System.IO; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.ControlPanels; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins; + public class UIUtilities { + public static ModuleInfo GetSlaveModule(int tabId) + { + var key = GetControlKey(); + var moduleId = GetModuleId(key); + + ModuleInfo slaveModule = GetSlaveModule(moduleId, key, tabId); + if (slaveModule != null) + { + var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? + ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); + if (moduleControl != null) + { + slaveModule.ModuleControlId = moduleControl.ModuleControlID; + } + } + + return slaveModule; + } + + public static bool IsLegacyUI(int moduleId, string key, int portalId) + { + var request = HttpContext.Current.Request; + var isLegacyUi = true; + var settings = PortalController.Instance.GetCurrentPortalSettings(); + if (settings != null) + { + isLegacyUi = !(settings.EnablePopUps && !request.Browser.Crawler && request.Browser.EcmaScriptVersion >= new Version(1, 0)); + + if (!isLegacyUi && !string.IsNullOrEmpty(key)) + { + var slaveModule = GetSlaveModule(moduleId, key, settings.ActiveTab.TabID); + if (slaveModule != null) + { + var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? + ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); + if (moduleControl != null) + { + isLegacyUi = !moduleControl.SupportsPopUps; + } + } + } + } + + return isLegacyUi; + } + internal static string GetControlKey() { HttpRequest request = HttpContext.Current.Request; - string key = ""; + string key = string.Empty; if (request.QueryString["ctl"] != null) { key = request.QueryString["ctl"]; } + return key; } @@ -39,11 +86,12 @@ internal static int GetModuleId(string key) int moduleId = -1; if (request.QueryString["mid"] != null) { - Int32.TryParse(request.QueryString["mid"], out moduleId); + int.TryParse(request.QueryString["mid"], out moduleId); } + if (request.QueryString["moduleid"] != null && (key.Equals("module", StringComparison.InvariantCultureIgnoreCase) || key.Equals("help", StringComparison.InvariantCultureIgnoreCase))) { - Int32.TryParse(request.QueryString["moduleid"], out moduleId); + int.TryParse(request.QueryString["moduleid"], out moduleId); } return moduleId; @@ -53,11 +101,12 @@ internal static string GetRenderMode() { HttpRequest request = HttpContext.Current.Request; - var renderMode = ""; + var renderMode = string.Empty; if (request.QueryString["render"] != null) { renderMode = request.QueryString["render"]; } + return renderMode; } @@ -77,7 +126,7 @@ internal static ModuleInfo GetSlaveModule(int moduleId, string key, int tabId) if (slaveModule == null) { - slaveModule = (new ModuleInfo {ModuleID = moduleId, ModuleDefID = -1, TabID = tabId, InheritViewPermissions = true}); + slaveModule = new ModuleInfo { ModuleID = moduleId, ModuleDefID = -1, TabID = tabId, InheritViewPermissions = true }; } if (request.QueryString["moduleid"] != null && (key.ToLowerInvariant() == "module" || key.ToLowerInvariant() == "help")) @@ -87,16 +136,16 @@ internal static ModuleInfo GetSlaveModule(int moduleId, string key, int tabId) if (request.QueryString["dnnprintmode"] != "true") { - slaveModule.ModuleTitle = ""; + slaveModule.ModuleTitle = string.Empty; } - slaveModule.Header = ""; - slaveModule.Footer = ""; + slaveModule.Header = string.Empty; + slaveModule.Footer = string.Empty; slaveModule.StartDate = DateTime.MinValue; slaveModule.EndDate = DateTime.MaxValue; slaveModule.Visibility = VisibilityState.None; - slaveModule.Color = ""; - slaveModule.Border = ""; + slaveModule.Color = string.Empty; + slaveModule.Border = string.Empty; slaveModule.DisplayTitle = true; slaveModule.DisplayPrint = false; slaveModule.DisplaySyndicate = false; @@ -104,52 +153,6 @@ internal static ModuleInfo GetSlaveModule(int moduleId, string key, int tabId) return slaveModule; } - public static ModuleInfo GetSlaveModule(int tabId) - { - var key = GetControlKey(); - var moduleId = GetModuleId(key); - - ModuleInfo slaveModule = GetSlaveModule(moduleId, key, tabId); - if (slaveModule != null) - { - var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? - ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); - if (moduleControl != null) - { - slaveModule.ModuleControlId = moduleControl.ModuleControlID; - } - } - - return slaveModule; - } - - public static bool IsLegacyUI(int moduleId, string key, int portalId) - { - var request = HttpContext.Current.Request; - var isLegacyUi = true; - var settings = PortalController.Instance.GetCurrentPortalSettings(); - if (settings != null) - { - isLegacyUi = !(settings.EnablePopUps && !request.Browser.Crawler && request.Browser.EcmaScriptVersion >= new Version(1, 0)); - - if (!isLegacyUi && !String.IsNullOrEmpty(key)) - { - var slaveModule = GetSlaveModule(moduleId, key, settings.ActiveTab.TabID); - if (slaveModule != null) - { - var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? - ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); - if (moduleControl != null) - { - isLegacyUi = !moduleControl.SupportsPopUps; - } - } - } - } - - return isLegacyUi; - } - public static bool IsLegacyUI(int portalId) { var key = GetControlKey(); @@ -167,7 +170,7 @@ internal static string GetLocalResourceFile(Control ctrl) if (ctrl is UserControl) { resourceFileName = string.Format("{0}/{1}/{2}.ascx.resx", ctrl.TemplateSourceDirectory, Localization.LocalResourceDirectory, ctrl.GetType().BaseType.Name); - if ((File.Exists(ctrl.Page.Server.MapPath(resourceFileName)))) + if (File.Exists(ctrl.Page.Server.MapPath(resourceFileName))) { break; } diff --git a/DNN Platform/Library/UI/UserControls/Address.cs b/DNN Platform/Library/UI/UserControls/Address.cs index 80a2c0e4bea..a154c898837 100644 --- a/DNN Platform/Library/UI/UserControls/Address.cs +++ b/DNN Platform/Library/UI/UserControls/Address.cs @@ -1,876 +1,881 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Lists; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { - - /// - /// The Address UserControl is used to manage User Addresses - /// - /// - /// - public abstract class Address : UserControlBase - { - - #region Private Members - - private const string MyFileName = "Address.ascx"; - private string _cell; - private string _city; - private string _controlColumnWidth = ""; - private string _country; - private string _countryData = "Text"; - private string _fax; - private string _labelColumnWidth = ""; - private int _moduleId; - private string _postal; - private string _region; - private string _regionData = "Text"; - private bool _showCell = true; - private bool _showCity = true; - private bool _showCountry = true; - private bool _showFax = true; - private bool _showPostal = true; - private bool _showRegion = true; - private bool _showStreet = true; - private bool _showTelephone = true; - private bool _showUnit = true; - private string _street; - private string _telephone; - private string _unit; - protected CountryListBox cboCountry; - protected DropDownList cboRegion; - protected CheckBox chkCell; - protected CheckBox chkCity; - protected CheckBox chkCountry; - protected CheckBox chkFax; - protected CheckBox chkPostal; - protected CheckBox chkRegion; - protected CheckBox chkStreet; - protected CheckBox chkTelephone; - protected LabelControl plCell; - protected LabelControl plCity; - protected LabelControl plCountry; - protected LabelControl plFax; - protected LabelControl plPostal; - protected LabelControl plRegion; - protected LabelControl plStreet; - protected LabelControl plTelephone; - protected LabelControl plUnit; - protected HtmlGenericControl divCell; - protected HtmlGenericControl divCity; - protected HtmlGenericControl divCountry; - protected HtmlGenericControl divFax; - protected HtmlGenericControl divPostal; - protected HtmlGenericControl divRegion; - protected HtmlGenericControl divStreet; - protected HtmlGenericControl divTelephone; - protected HtmlGenericControl divUnit; - protected TextBox txtCell; - protected TextBox txtCity; - protected TextBox txtFax; - protected TextBox txtPostal; - protected TextBox txtRegion; - protected TextBox txtStreet; - protected TextBox txtTelephone; - protected TextBox txtUnit; - protected RequiredFieldValidator valCell; - protected RequiredFieldValidator valCity; - protected RequiredFieldValidator valCountry; - protected RequiredFieldValidator valFax; - protected RequiredFieldValidator valPostal; - protected RequiredFieldValidator valRegion1; - protected RequiredFieldValidator valRegion2; - protected RequiredFieldValidator valStreet; - protected RequiredFieldValidator valTelephone; - - #endregion - - #region Constructors - - protected Address() - { - StartTabIndex = 1; - } - - #endregion - - #region Properties - - public int ModuleId - { - get - { - return Convert.ToInt32(ViewState["ModuleId"]); - } - set - { - _moduleId = value; - } - } - - public string LabelColumnWidth - { - get - { - return Convert.ToString(ViewState["LabelColumnWidth"]); - } - set - { - _labelColumnWidth = value; - } - } - - public string ControlColumnWidth - { - get - { - return Convert.ToString(ViewState["ControlColumnWidth"]); - } - set - { - _controlColumnWidth = value; - } - } - - public int StartTabIndex { private get; set; } - - public string Street - { - get - { - return txtStreet.Text; - } - set - { - _street = value; - } - } - - public string Unit - { - get - { - return txtUnit.Text; - } - set - { - _unit = value; - } - } - - public string City - { - get - { - return txtCity.Text; - } - set - { - _city = value; - } - } - - public string Country - { - get - { - var retValue = ""; - if (cboCountry.SelectedItem != null) - { - switch (_countryData.ToLowerInvariant()) - { - case "text": - retValue = cboCountry.SelectedIndex == 0 ? "" : cboCountry.SelectedItem.Text; - break; - case "value": - retValue = cboCountry.SelectedItem.Value; - break; - } - } - return retValue; - } - set - { - _country = value; - } - } - - public string Region - { - get - { - var retValue = ""; - if (cboRegion.Visible) - { - if (cboRegion.SelectedItem != null) - { - switch (_regionData.ToLowerInvariant()) - { - case "text": - if (cboRegion.SelectedIndex > 0) - { - retValue = cboRegion.SelectedItem.Text; - } - break; - case "value": - retValue = cboRegion.SelectedItem.Value; - break; - } - } - } - else - { - retValue = txtRegion.Text; - } - return retValue; - } - set - { - _region = value; - } - } - - public string Postal - { - get - { - return txtPostal.Text; - } - set - { - _postal = value; - } - } - - public string Telephone - { - get - { - return txtTelephone.Text; - } - set - { - _telephone = value; - } - } - - public string Cell - { - get - { - return txtCell.Text; - } - set - { - _cell = value; - } - } - - public string Fax - { - get - { - return txtFax.Text; - } - set - { - _fax = value; - } - } - - public bool ShowStreet - { - set - { - _showStreet = value; - } - } - - public bool ShowUnit - { - set - { - _showUnit = value; - } - } - - public bool ShowCity - { - set - { - _showCity = value; - } - } - - public bool ShowCountry - { - set - { - _showCountry = value; - } - } - - public bool ShowRegion - { - set - { - _showRegion = value; - } - } - - public bool ShowPostal - { - set - { - _showPostal = value; - } - } - - public bool ShowTelephone - { - set - { - _showTelephone = value; - } - } - - public bool ShowCell - { - set - { - _showCell = value; - } - } - - public bool ShowFax - { - set - { - _showFax = value; - } - } - - public string CountryData - { - set - { - _countryData = value; - } - } - - public string RegionData - { - set - { - _regionData = value; - } - } - - public string LocalResourceFile - { - get - { - return Localization.GetResourceFile(this, MyFileName); - } - } - - #endregion - - #region Private Methods - - /// - /// Localize correctly sets up the control for US/Canada/Other Countries - /// - /// - /// - private void Localize() - { - var countryCode = cboCountry.SelectedItem.Value; - var ctlEntry = new ListController(); - //listKey in format "Country.US:Region" - var listKey = "Country." + countryCode; - var entryCollection = ctlEntry.GetListEntryInfoItems("Region", listKey); - - if (entryCollection.Any()) - { - cboRegion.Visible = true; - txtRegion.Visible = false; - { - cboRegion.Items.Clear(); - cboRegion.DataSource = entryCollection; - cboRegion.DataBind(); - cboRegion.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", "")); - } - if (countryCode.Equals("us", StringComparison.InvariantCultureIgnoreCase)) - { - valRegion1.Enabled = true; - valRegion2.Enabled = false; - valRegion1.ErrorMessage = Localization.GetString("StateRequired", Localization.GetResourceFile(this, MyFileName)); - plRegion.Text = Localization.GetString("plState", Localization.GetResourceFile(this, MyFileName)); - plRegion.HelpText = Localization.GetString("plState.Help", Localization.GetResourceFile(this, MyFileName)); - plPostal.Text = Localization.GetString("plZip", Localization.GetResourceFile(this, MyFileName)); - plPostal.HelpText = Localization.GetString("plZip.Help", Localization.GetResourceFile(this, MyFileName)); - } - else - { - valRegion1.ErrorMessage = Localization.GetString("ProvinceRequired", Localization.GetResourceFile(this, MyFileName)); - plRegion.Text = Localization.GetString("plProvince", Localization.GetResourceFile(this, MyFileName)); - plRegion.HelpText = Localization.GetString("plProvince.Help", Localization.GetResourceFile(this, MyFileName)); - plPostal.Text = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName)); - plPostal.HelpText = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName)); - } - valRegion1.Enabled = true; - valRegion2.Enabled = false; - } - else - { - cboRegion.ClearSelection(); - cboRegion.Visible = false; - txtRegion.Visible = true; - valRegion1.Enabled = false; - valRegion2.Enabled = true; - valRegion2.ErrorMessage = Localization.GetString("RegionRequired", Localization.GetResourceFile(this, MyFileName)); - plRegion.Text = Localization.GetString("plRegion", Localization.GetResourceFile(this, MyFileName)); - plRegion.HelpText = Localization.GetString("plRegion.Help", Localization.GetResourceFile(this, MyFileName)); - plPostal.Text = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName)); - plPostal.HelpText = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName)); - } - - var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", PortalSettings.PortalId, true); - if (reqRegion) - { - valRegion1.Enabled = false; - valRegion2.Enabled = false; - } - } - - /// - /// ShowRequiredFields sets up displaying which fields are required - /// - /// - /// - private void ShowRequiredFields() - { - var reqStreet = PortalController.GetPortalSettingAsBoolean("addressstreet", PortalSettings.PortalId, true); - var reqCity = PortalController.GetPortalSettingAsBoolean("addresscity", PortalSettings.PortalId, true); - var reqCountry = PortalController.GetPortalSettingAsBoolean("addresscountry", PortalSettings.PortalId, true); - var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", PortalSettings.PortalId, true); - var reqPostal = PortalController.GetPortalSettingAsBoolean("addresspostal", PortalSettings.PortalId, true); - var reqTelephone = PortalController.GetPortalSettingAsBoolean("addresstelephone", PortalSettings.PortalId, true); - var reqCell = PortalController.GetPortalSettingAsBoolean("addresscell", PortalSettings.PortalId, true); - var reqFax = PortalController.GetPortalSettingAsBoolean("addressfax", PortalSettings.PortalId, true); - - if (TabPermissionController.CanAdminPage()) - { - if (reqCountry) - { - chkCountry.Checked = true; - valCountry.Enabled = true; - cboCountry.CssClass = "dnnFormRequired"; - } - else - { - valCountry.Enabled = false; - cboCountry.CssClass = ""; - } - if (reqRegion) - { - chkRegion.Checked = true; - txtRegion.CssClass = "dnnFormRequired"; - cboRegion.CssClass = "dnnFormRequired"; - - if (cboRegion.Visible) - { - valRegion1.Enabled = true; - valRegion2.Enabled = false; - } - else - { - valRegion1.Enabled = false; - valRegion2.Enabled = true; - } - } - else - { - valRegion1.Enabled = false; - valRegion2.Enabled = false; - txtRegion.CssClass = ""; - cboRegion.CssClass = ""; - } - if (reqCity) - { - chkCity.Checked = true; - valCity.Enabled = true; - txtCity.CssClass = "dnnFormRequired"; - } - else - { - valCity.Enabled = false; - txtCity.CssClass = ""; - } - if (reqStreet) - { - chkStreet.Checked = true; - valStreet.Enabled = true; - txtStreet.CssClass = "dnnFormRequired"; - } - else - { - valStreet.Enabled = false; - txtStreet.CssClass = ""; - } - if (reqPostal) - { - chkPostal.Checked = true; - valPostal.Enabled = true; - txtPostal.CssClass = "dnnFormRequired"; - } - else - { - valPostal.Enabled = false; - txtPostal.CssClass = ""; - } - if (reqTelephone) - { - chkTelephone.Checked = true; - valTelephone.Enabled = true; - txtTelephone.CssClass = "dnnFormRequired"; - } - else - { - valTelephone.Enabled = false; - txtTelephone.CssClass = ""; - } - if (reqCell) - { - chkCell.Checked = true; - valCell.Enabled = true; - txtCell.CssClass = "dnnFormRequired"; - } - else - { - valCell.Enabled = false; - txtCell.CssClass = ""; - } - if (reqFax) - { - chkFax.Checked = true; - valFax.Enabled = true; - txtFax.CssClass = "dnnFormRequired"; - } - else - { - valFax.Enabled = false; - txtFax.CssClass = ""; - } - } - } - - /// - /// UpdateRequiredFields updates which fields are required - /// - /// - /// - private void UpdateRequiredFields() - { - if (chkCountry.Checked == false) - { - chkRegion.Checked = false; - } - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addressstreet", chkStreet.Checked ? "" : "N"); - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addresscity", chkCity.Checked ? "" : "N"); - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addresscountry", chkCountry.Checked ? "" : "N"); - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addressregion", chkRegion.Checked ? "" : "N"); - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addresspostal", chkPostal.Checked ? "" : "N"); - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addresstelephone", chkTelephone.Checked ? "" : "N"); - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addresscell", chkCell.Checked ? "" : "N"); - PortalController.UpdatePortalSetting(PortalSettings.PortalId, "addressfax", chkFax.Checked ? "" : "N"); - - ShowRequiredFields(); - } - - #endregion - - #region Event Handlers - - /// - /// Page_Load runs when the control is loaded - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cboCountry.SelectedIndexChanged += OnCountryIndexChanged; - chkCell.CheckedChanged += OnCellCheckChanged; - chkCity.CheckedChanged += OnCityCheckChanged; - chkCountry.CheckedChanged += OnCountryCheckChanged; - chkFax.CheckedChanged += OnFaxCheckChanged; - chkPostal.CheckedChanged += OnPostalCheckChanged; - chkRegion.CheckedChanged += OnRegionCheckChanged; - chkStreet.CheckedChanged += OnStreetCheckChanged; - chkTelephone.CheckedChanged += OnTelephoneCheckChanged; - - try - { - valStreet.ErrorMessage = Localization.GetString("StreetRequired", Localization.GetResourceFile(this, MyFileName)); - valCity.ErrorMessage = Localization.GetString("CityRequired", Localization.GetResourceFile(this, MyFileName)); - valCountry.ErrorMessage = Localization.GetString("CountryRequired", Localization.GetResourceFile(this, MyFileName)); - valPostal.ErrorMessage = Localization.GetString("PostalRequired", Localization.GetResourceFile(this, MyFileName)); - valTelephone.ErrorMessage = Localization.GetString("TelephoneRequired", Localization.GetResourceFile(this, MyFileName)); - valCell.ErrorMessage = Localization.GetString("CellRequired", Localization.GetResourceFile(this, MyFileName)); - valFax.ErrorMessage = Localization.GetString("FaxRequired", Localization.GetResourceFile(this, MyFileName)); - - if (!Page.IsPostBack) - { - txtStreet.TabIndex = Convert.ToInt16(StartTabIndex); - txtUnit.TabIndex = Convert.ToInt16(StartTabIndex + 1); - txtCity.TabIndex = Convert.ToInt16(StartTabIndex + 2); - cboCountry.TabIndex = Convert.ToInt16(StartTabIndex + 3); - cboRegion.TabIndex = Convert.ToInt16(StartTabIndex + 4); - txtRegion.TabIndex = Convert.ToInt16(StartTabIndex + 5); - txtPostal.TabIndex = Convert.ToInt16(StartTabIndex + 6); - txtTelephone.TabIndex = Convert.ToInt16(StartTabIndex + 7); - txtCell.TabIndex = Convert.ToInt16(StartTabIndex + 8); - txtFax.TabIndex = Convert.ToInt16(StartTabIndex + 9); - - //", "")); - - switch (_countryData.ToLowerInvariant()) - { - case "text": - if (String.IsNullOrEmpty(_country)) - { - cboCountry.SelectedIndex = 0; - } - else - { - if (cboCountry.Items.FindByText(_country) != null) - { - cboCountry.ClearSelection(); - cboCountry.Items.FindByText(_country).Selected = true; - } - } - break; - case "value": - if (cboCountry.Items.FindByValue(_country) != null) - { - cboCountry.ClearSelection(); - cboCountry.Items.FindByValue(_country).Selected = true; - } - break; - } - Localize(); - - if (cboRegion.Visible) - { - switch (_regionData.ToLowerInvariant()) - { - case "text": - if (String.IsNullOrEmpty(_region)) - { - cboRegion.SelectedIndex = 0; - } - else - { - if (cboRegion.Items.FindByText(_region) != null) - { - cboRegion.Items.FindByText(_region).Selected = true; - } - } - break; - case "value": - if (cboRegion.Items.FindByValue(_region) != null) - { - cboRegion.Items.FindByValue(_region).Selected = true; - } - break; - } - } - else - { - txtRegion.Text = _region; - } - txtStreet.Text = _street; - txtUnit.Text = _unit; - txtCity.Text = _city; - txtPostal.Text = _postal; - txtTelephone.Text = _telephone; - txtCell.Text = _cell; - txtFax.Text = _fax; - - divStreet.Visible = _showStreet; - divUnit.Visible = _showUnit; - divCity.Visible = _showCity; - divCountry.Visible = _showCountry; - divRegion.Visible = _showRegion; - divPostal.Visible = _showPostal; - divTelephone.Visible = _showTelephone; - divCell.Visible = _showCell; - divFax.Visible = _showFax; - - if (TabPermissionController.CanAdminPage()) - { - chkStreet.Visible = true; - chkCity.Visible = true; - chkCountry.Visible = true; - chkRegion.Visible = true; - chkPostal.Visible = true; - chkTelephone.Visible = true; - chkCell.Visible = true; - chkFax.Visible = true; - } - ViewState["ModuleId"] = Convert.ToString(_moduleId); - ViewState["LabelColumnWidth"] = _labelColumnWidth; - ViewState["ControlColumnWidth"] = _controlColumnWidth; - - ShowRequiredFields(); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnCountryIndexChanged(object sender, EventArgs e) - { - try - { - Localize(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnCityCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) //Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnCountryCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnPostalCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnRegionCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnStreetCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnTelephoneCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnCellCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnFaxCheckChanged(object sender, EventArgs e) - { - try - { - UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - #endregion - - } + using System; + using System.Linq; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.WebControls; + + /// + /// The Address UserControl is used to manage User Addresses. + /// + /// + /// + public abstract class Address : UserControlBase + { + protected CountryListBox cboCountry; + protected DropDownList cboRegion; + private const string MyFileName = "Address.ascx"; + private string _cell; + private string _city; + private string _controlColumnWidth = string.Empty; + private string _country; + private string _countryData = "Text"; + private string _fax; + private string _labelColumnWidth = string.Empty; + private int _moduleId; + private string _postal; + private string _region; + private string _regionData = "Text"; + private bool _showCell = true; + private bool _showCity = true; + private bool _showCountry = true; + private bool _showFax = true; + private bool _showPostal = true; + private bool _showRegion = true; + private bool _showStreet = true; + private bool _showTelephone = true; + private bool _showUnit = true; + private string _street; + private string _telephone; + private string _unit; + protected CheckBox chkCell; + protected CheckBox chkCity; + protected CheckBox chkCountry; + protected CheckBox chkFax; + protected CheckBox chkPostal; + protected CheckBox chkRegion; + protected CheckBox chkStreet; + protected CheckBox chkTelephone; + protected LabelControl plCell; + protected LabelControl plCity; + protected LabelControl plCountry; + protected LabelControl plFax; + protected LabelControl plPostal; + protected LabelControl plRegion; + protected LabelControl plStreet; + protected LabelControl plTelephone; + protected LabelControl plUnit; + protected HtmlGenericControl divCell; + protected HtmlGenericControl divCity; + protected HtmlGenericControl divCountry; + protected HtmlGenericControl divFax; + protected HtmlGenericControl divPostal; + protected HtmlGenericControl divRegion; + protected HtmlGenericControl divStreet; + protected HtmlGenericControl divTelephone; + protected HtmlGenericControl divUnit; + protected TextBox txtCell; + protected TextBox txtCity; + protected TextBox txtFax; + protected TextBox txtPostal; + protected TextBox txtRegion; + protected TextBox txtStreet; + protected TextBox txtTelephone; + protected TextBox txtUnit; + protected RequiredFieldValidator valCell; + protected RequiredFieldValidator valCity; + protected RequiredFieldValidator valCountry; + protected RequiredFieldValidator valFax; + protected RequiredFieldValidator valPostal; + protected RequiredFieldValidator valRegion1; + protected RequiredFieldValidator valRegion2; + protected RequiredFieldValidator valStreet; + protected RequiredFieldValidator valTelephone; + + protected Address() + { + this.StartTabIndex = 1; + } + + public int ModuleId + { + get + { + return Convert.ToInt32(this.ViewState["ModuleId"]); + } + + set + { + this._moduleId = value; + } + } + + public string LabelColumnWidth + { + get + { + return Convert.ToString(this.ViewState["LabelColumnWidth"]); + } + + set + { + this._labelColumnWidth = value; + } + } + + public string ControlColumnWidth + { + get + { + return Convert.ToString(this.ViewState["ControlColumnWidth"]); + } + + set + { + this._controlColumnWidth = value; + } + } + + public int StartTabIndex { private get; set; } + + public string Street + { + get + { + return this.txtStreet.Text; + } + + set + { + this._street = value; + } + } + + public string Unit + { + get + { + return this.txtUnit.Text; + } + + set + { + this._unit = value; + } + } + + public string City + { + get + { + return this.txtCity.Text; + } + + set + { + this._city = value; + } + } + + public string Country + { + get + { + var retValue = string.Empty; + if (this.cboCountry.SelectedItem != null) + { + switch (this._countryData.ToLowerInvariant()) + { + case "text": + retValue = this.cboCountry.SelectedIndex == 0 ? string.Empty : this.cboCountry.SelectedItem.Text; + break; + case "value": + retValue = this.cboCountry.SelectedItem.Value; + break; + } + } + + return retValue; + } + + set + { + this._country = value; + } + } + + public string Region + { + get + { + var retValue = string.Empty; + if (this.cboRegion.Visible) + { + if (this.cboRegion.SelectedItem != null) + { + switch (this._regionData.ToLowerInvariant()) + { + case "text": + if (this.cboRegion.SelectedIndex > 0) + { + retValue = this.cboRegion.SelectedItem.Text; + } + + break; + case "value": + retValue = this.cboRegion.SelectedItem.Value; + break; + } + } + } + else + { + retValue = this.txtRegion.Text; + } + + return retValue; + } + + set + { + this._region = value; + } + } + + public string Postal + { + get + { + return this.txtPostal.Text; + } + + set + { + this._postal = value; + } + } + + public string Telephone + { + get + { + return this.txtTelephone.Text; + } + + set + { + this._telephone = value; + } + } + + public string Cell + { + get + { + return this.txtCell.Text; + } + + set + { + this._cell = value; + } + } + + public string Fax + { + get + { + return this.txtFax.Text; + } + + set + { + this._fax = value; + } + } + + public bool ShowStreet + { + set + { + this._showStreet = value; + } + } + + public bool ShowUnit + { + set + { + this._showUnit = value; + } + } + + public bool ShowCity + { + set + { + this._showCity = value; + } + } + + public bool ShowCountry + { + set + { + this._showCountry = value; + } + } + + public bool ShowRegion + { + set + { + this._showRegion = value; + } + } + + public bool ShowPostal + { + set + { + this._showPostal = value; + } + } + + public bool ShowTelephone + { + set + { + this._showTelephone = value; + } + } + + public bool ShowCell + { + set + { + this._showCell = value; + } + } + + public bool ShowFax + { + set + { + this._showFax = value; + } + } + + public string CountryData + { + set + { + this._countryData = value; + } + } + + public string RegionData + { + set + { + this._regionData = value; + } + } + + public string LocalResourceFile + { + get + { + return Localization.GetResourceFile(this, MyFileName); + } + } + + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboCountry.SelectedIndexChanged += this.OnCountryIndexChanged; + this.chkCell.CheckedChanged += this.OnCellCheckChanged; + this.chkCity.CheckedChanged += this.OnCityCheckChanged; + this.chkCountry.CheckedChanged += this.OnCountryCheckChanged; + this.chkFax.CheckedChanged += this.OnFaxCheckChanged; + this.chkPostal.CheckedChanged += this.OnPostalCheckChanged; + this.chkRegion.CheckedChanged += this.OnRegionCheckChanged; + this.chkStreet.CheckedChanged += this.OnStreetCheckChanged; + this.chkTelephone.CheckedChanged += this.OnTelephoneCheckChanged; + + try + { + this.valStreet.ErrorMessage = Localization.GetString("StreetRequired", Localization.GetResourceFile(this, MyFileName)); + this.valCity.ErrorMessage = Localization.GetString("CityRequired", Localization.GetResourceFile(this, MyFileName)); + this.valCountry.ErrorMessage = Localization.GetString("CountryRequired", Localization.GetResourceFile(this, MyFileName)); + this.valPostal.ErrorMessage = Localization.GetString("PostalRequired", Localization.GetResourceFile(this, MyFileName)); + this.valTelephone.ErrorMessage = Localization.GetString("TelephoneRequired", Localization.GetResourceFile(this, MyFileName)); + this.valCell.ErrorMessage = Localization.GetString("CellRequired", Localization.GetResourceFile(this, MyFileName)); + this.valFax.ErrorMessage = Localization.GetString("FaxRequired", Localization.GetResourceFile(this, MyFileName)); + + if (!this.Page.IsPostBack) + { + this.txtStreet.TabIndex = Convert.ToInt16(this.StartTabIndex); + this.txtUnit.TabIndex = Convert.ToInt16(this.StartTabIndex + 1); + this.txtCity.TabIndex = Convert.ToInt16(this.StartTabIndex + 2); + this.cboCountry.TabIndex = Convert.ToInt16(this.StartTabIndex + 3); + this.cboRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 4); + this.txtRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 5); + this.txtPostal.TabIndex = Convert.ToInt16(this.StartTabIndex + 6); + this.txtTelephone.TabIndex = Convert.ToInt16(this.StartTabIndex + 7); + this.txtCell.TabIndex = Convert.ToInt16(this.StartTabIndex + 8); + this.txtFax.TabIndex = Convert.ToInt16(this.StartTabIndex + 9); + + // ", string.Empty)); + + switch (this._countryData.ToLowerInvariant()) + { + case "text": + if (string.IsNullOrEmpty(this._country)) + { + this.cboCountry.SelectedIndex = 0; + } + else + { + if (this.cboCountry.Items.FindByText(this._country) != null) + { + this.cboCountry.ClearSelection(); + this.cboCountry.Items.FindByText(this._country).Selected = true; + } + } + + break; + case "value": + if (this.cboCountry.Items.FindByValue(this._country) != null) + { + this.cboCountry.ClearSelection(); + this.cboCountry.Items.FindByValue(this._country).Selected = true; + } + + break; + } + + this.Localize(); + + if (this.cboRegion.Visible) + { + switch (this._regionData.ToLowerInvariant()) + { + case "text": + if (string.IsNullOrEmpty(this._region)) + { + this.cboRegion.SelectedIndex = 0; + } + else + { + if (this.cboRegion.Items.FindByText(this._region) != null) + { + this.cboRegion.Items.FindByText(this._region).Selected = true; + } + } + + break; + case "value": + if (this.cboRegion.Items.FindByValue(this._region) != null) + { + this.cboRegion.Items.FindByValue(this._region).Selected = true; + } + + break; + } + } + else + { + this.txtRegion.Text = this._region; + } + + this.txtStreet.Text = this._street; + this.txtUnit.Text = this._unit; + this.txtCity.Text = this._city; + this.txtPostal.Text = this._postal; + this.txtTelephone.Text = this._telephone; + this.txtCell.Text = this._cell; + this.txtFax.Text = this._fax; + + this.divStreet.Visible = this._showStreet; + this.divUnit.Visible = this._showUnit; + this.divCity.Visible = this._showCity; + this.divCountry.Visible = this._showCountry; + this.divRegion.Visible = this._showRegion; + this.divPostal.Visible = this._showPostal; + this.divTelephone.Visible = this._showTelephone; + this.divCell.Visible = this._showCell; + this.divFax.Visible = this._showFax; + + if (TabPermissionController.CanAdminPage()) + { + this.chkStreet.Visible = true; + this.chkCity.Visible = true; + this.chkCountry.Visible = true; + this.chkRegion.Visible = true; + this.chkPostal.Visible = true; + this.chkTelephone.Visible = true; + this.chkCell.Visible = true; + this.chkFax.Visible = true; + } + + this.ViewState["ModuleId"] = Convert.ToString(this._moduleId); + this.ViewState["LabelColumnWidth"] = this._labelColumnWidth; + this.ViewState["ControlColumnWidth"] = this._controlColumnWidth; + + this.ShowRequiredFields(); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnCountryIndexChanged(object sender, EventArgs e) + { + try + { + this.Localize(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + /// + /// Localize correctly sets up the control for US/Canada/Other Countries. + /// + /// + /// + private void Localize() + { + var countryCode = this.cboCountry.SelectedItem.Value; + var ctlEntry = new ListController(); + + // listKey in format "Country.US:Region" + var listKey = "Country." + countryCode; + var entryCollection = ctlEntry.GetListEntryInfoItems("Region", listKey); + + if (entryCollection.Any()) + { + this.cboRegion.Visible = true; + this.txtRegion.Visible = false; + { + this.cboRegion.Items.Clear(); + this.cboRegion.DataSource = entryCollection; + this.cboRegion.DataBind(); + this.cboRegion.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", string.Empty)); + } + + if (countryCode.Equals("us", StringComparison.InvariantCultureIgnoreCase)) + { + this.valRegion1.Enabled = true; + this.valRegion2.Enabled = false; + this.valRegion1.ErrorMessage = Localization.GetString("StateRequired", Localization.GetResourceFile(this, MyFileName)); + this.plRegion.Text = Localization.GetString("plState", Localization.GetResourceFile(this, MyFileName)); + this.plRegion.HelpText = Localization.GetString("plState.Help", Localization.GetResourceFile(this, MyFileName)); + this.plPostal.Text = Localization.GetString("plZip", Localization.GetResourceFile(this, MyFileName)); + this.plPostal.HelpText = Localization.GetString("plZip.Help", Localization.GetResourceFile(this, MyFileName)); + } + else + { + this.valRegion1.ErrorMessage = Localization.GetString("ProvinceRequired", Localization.GetResourceFile(this, MyFileName)); + this.plRegion.Text = Localization.GetString("plProvince", Localization.GetResourceFile(this, MyFileName)); + this.plRegion.HelpText = Localization.GetString("plProvince.Help", Localization.GetResourceFile(this, MyFileName)); + this.plPostal.Text = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName)); + this.plPostal.HelpText = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName)); + } + + this.valRegion1.Enabled = true; + this.valRegion2.Enabled = false; + } + else + { + this.cboRegion.ClearSelection(); + this.cboRegion.Visible = false; + this.txtRegion.Visible = true; + this.valRegion1.Enabled = false; + this.valRegion2.Enabled = true; + this.valRegion2.ErrorMessage = Localization.GetString("RegionRequired", Localization.GetResourceFile(this, MyFileName)); + this.plRegion.Text = Localization.GetString("plRegion", Localization.GetResourceFile(this, MyFileName)); + this.plRegion.HelpText = Localization.GetString("plRegion.Help", Localization.GetResourceFile(this, MyFileName)); + this.plPostal.Text = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName)); + this.plPostal.HelpText = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName)); + } + + var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", this.PortalSettings.PortalId, true); + if (reqRegion) + { + this.valRegion1.Enabled = false; + this.valRegion2.Enabled = false; + } + } + + /// + /// ShowRequiredFields sets up displaying which fields are required. + /// + /// + /// + private void ShowRequiredFields() + { + var reqStreet = PortalController.GetPortalSettingAsBoolean("addressstreet", this.PortalSettings.PortalId, true); + var reqCity = PortalController.GetPortalSettingAsBoolean("addresscity", this.PortalSettings.PortalId, true); + var reqCountry = PortalController.GetPortalSettingAsBoolean("addresscountry", this.PortalSettings.PortalId, true); + var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", this.PortalSettings.PortalId, true); + var reqPostal = PortalController.GetPortalSettingAsBoolean("addresspostal", this.PortalSettings.PortalId, true); + var reqTelephone = PortalController.GetPortalSettingAsBoolean("addresstelephone", this.PortalSettings.PortalId, true); + var reqCell = PortalController.GetPortalSettingAsBoolean("addresscell", this.PortalSettings.PortalId, true); + var reqFax = PortalController.GetPortalSettingAsBoolean("addressfax", this.PortalSettings.PortalId, true); + + if (TabPermissionController.CanAdminPage()) + { + if (reqCountry) + { + this.chkCountry.Checked = true; + this.valCountry.Enabled = true; + this.cboCountry.CssClass = "dnnFormRequired"; + } + else + { + this.valCountry.Enabled = false; + this.cboCountry.CssClass = string.Empty; + } + + if (reqRegion) + { + this.chkRegion.Checked = true; + this.txtRegion.CssClass = "dnnFormRequired"; + this.cboRegion.CssClass = "dnnFormRequired"; + + if (this.cboRegion.Visible) + { + this.valRegion1.Enabled = true; + this.valRegion2.Enabled = false; + } + else + { + this.valRegion1.Enabled = false; + this.valRegion2.Enabled = true; + } + } + else + { + this.valRegion1.Enabled = false; + this.valRegion2.Enabled = false; + this.txtRegion.CssClass = string.Empty; + this.cboRegion.CssClass = string.Empty; + } + + if (reqCity) + { + this.chkCity.Checked = true; + this.valCity.Enabled = true; + this.txtCity.CssClass = "dnnFormRequired"; + } + else + { + this.valCity.Enabled = false; + this.txtCity.CssClass = string.Empty; + } + + if (reqStreet) + { + this.chkStreet.Checked = true; + this.valStreet.Enabled = true; + this.txtStreet.CssClass = "dnnFormRequired"; + } + else + { + this.valStreet.Enabled = false; + this.txtStreet.CssClass = string.Empty; + } + + if (reqPostal) + { + this.chkPostal.Checked = true; + this.valPostal.Enabled = true; + this.txtPostal.CssClass = "dnnFormRequired"; + } + else + { + this.valPostal.Enabled = false; + this.txtPostal.CssClass = string.Empty; + } + + if (reqTelephone) + { + this.chkTelephone.Checked = true; + this.valTelephone.Enabled = true; + this.txtTelephone.CssClass = "dnnFormRequired"; + } + else + { + this.valTelephone.Enabled = false; + this.txtTelephone.CssClass = string.Empty; + } + + if (reqCell) + { + this.chkCell.Checked = true; + this.valCell.Enabled = true; + this.txtCell.CssClass = "dnnFormRequired"; + } + else + { + this.valCell.Enabled = false; + this.txtCell.CssClass = string.Empty; + } + + if (reqFax) + { + this.chkFax.Checked = true; + this.valFax.Enabled = true; + this.txtFax.CssClass = "dnnFormRequired"; + } + else + { + this.valFax.Enabled = false; + this.txtFax.CssClass = string.Empty; + } + } + } + + /// + /// UpdateRequiredFields updates which fields are required. + /// + /// + /// + private void UpdateRequiredFields() + { + if (this.chkCountry.Checked == false) + { + this.chkRegion.Checked = false; + } + + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressstreet", this.chkStreet.Checked ? string.Empty : "N"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscity", this.chkCity.Checked ? string.Empty : "N"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscountry", this.chkCountry.Checked ? string.Empty : "N"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressregion", this.chkRegion.Checked ? string.Empty : "N"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresspostal", this.chkPostal.Checked ? string.Empty : "N"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresstelephone", this.chkTelephone.Checked ? string.Empty : "N"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscell", this.chkCell.Checked ? string.Empty : "N"); + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressfax", this.chkFax.Checked ? string.Empty : "N"); + + this.ShowRequiredFields(); + } + + protected void OnCityCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnCountryCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnPostalCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnRegionCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnStreetCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnTelephoneCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnCellCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnFaxCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } } diff --git a/DNN Platform/Library/UI/UserControls/DualListControl.cs b/DNN Platform/Library/UI/UserControls/DualListControl.cs index c72ef574624..c6d436d0fdc 100644 --- a/DNN Platform/Library/UI/UserControls/DualListControl.cs +++ b/DNN Platform/Library/UI/UserControls/DualListControl.cs @@ -1,54 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Web.UI.WebControls; - -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Collections; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + public abstract class DualListControl : UserControlBase - { - #region "Private Members" + { protected Label Label1; protected Label Label2; + protected LinkButton cmdAdd; + protected LinkButton cmdAddAll; private string MyFileName = "DualListControl.ascx"; private ArrayList _Assigned; private ArrayList _Available; - private string _DataTextField = ""; - private string _DataValueField = ""; + private string _DataTextField = string.Empty; + private string _DataValueField = string.Empty; private bool _Enabled = true; - private string _ListBoxHeight = ""; - private string _ListBoxWidth = ""; - protected LinkButton cmdAdd; - protected LinkButton cmdAddAll; + private string _ListBoxHeight = string.Empty; + private string _ListBoxWidth = string.Empty; protected LinkButton cmdRemove; protected LinkButton cmdRemoveAll; protected ListBox lstAssigned; - protected ListBox lstAvailable; - - #endregion - - #region "Public Properties" - + protected ListBox lstAvailable; + public string ListBoxWidth { get { - return Convert.ToString(ViewState[ClientID + "_ListBoxWidth"]); + return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxWidth"]); } + set { - _ListBoxWidth = value; + this._ListBoxWidth = value; } } @@ -56,11 +47,12 @@ public string ListBoxHeight { get { - return Convert.ToString(ViewState[ClientID + "_ListBoxHeight"]); + return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxHeight"]); } + set { - _ListBoxHeight = value; + this._ListBoxHeight = value; } } @@ -69,15 +61,17 @@ public ArrayList Available get { var objList = new ArrayList(); - foreach (ListItem objListItem in lstAvailable.Items) + foreach (ListItem objListItem in this.lstAvailable.Items) { objList.Add(objListItem); } + return objList; } + set { - _Available = value; + this._Available = value; } } @@ -86,15 +80,17 @@ public ArrayList Assigned get { var objList = new ArrayList(); - foreach (ListItem objListItem in lstAssigned.Items) + foreach (ListItem objListItem in this.lstAssigned.Items) { objList.Add(objListItem); } + return objList; } + set { - _Assigned = value; + this._Assigned = value; } } @@ -102,7 +98,7 @@ public string DataTextField { set { - _DataTextField = value; + this._DataTextField = value; } } @@ -110,7 +106,7 @@ public string DataValueField { set { - _DataValueField = value; + this._DataValueField = value; } } @@ -118,72 +114,69 @@ public bool Enabled { set { - _Enabled = value; + this._Enabled = value; } - } - - #endregion - - #region "Protected Event Handlers" - - /// The Page_Load server event handler on this page is used to populate the role information for the page - protected override void OnLoad(EventArgs e) + } + + /// The Page_Load server event handler on this page is used to populate the role information for the page. + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdAdd.Click += cmdAdd_Click; - cmdAddAll.Click += cmdAddAll_Click; - cmdRemove.Click += cmdRemove_Click; - cmdRemoveAll.Click += cmdRemoveAll_Click; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdAddAll.Click += this.cmdAddAll_Click; + this.cmdRemove.Click += this.cmdRemove_Click; + this.cmdRemoveAll.Click += this.cmdRemoveAll_Click; try { - //Localization - Label1.Text = Localization.GetString("Available", Localization.GetResourceFile(this, MyFileName)); - Label2.Text = Localization.GetString("Assigned", Localization.GetResourceFile(this, MyFileName)); - cmdAdd.ToolTip = Localization.GetString("Add", Localization.GetResourceFile(this, MyFileName)); - cmdAddAll.ToolTip = Localization.GetString("AddAll", Localization.GetResourceFile(this, MyFileName)); - cmdRemove.ToolTip = Localization.GetString("Remove", Localization.GetResourceFile(this, MyFileName)); - cmdRemoveAll.ToolTip = Localization.GetString("RemoveAll", Localization.GetResourceFile(this, MyFileName)); + // Localization + this.Label1.Text = Localization.GetString("Available", Localization.GetResourceFile(this, this.MyFileName)); + this.Label2.Text = Localization.GetString("Assigned", Localization.GetResourceFile(this, this.MyFileName)); + this.cmdAdd.ToolTip = Localization.GetString("Add", Localization.GetResourceFile(this, this.MyFileName)); + this.cmdAddAll.ToolTip = Localization.GetString("AddAll", Localization.GetResourceFile(this, this.MyFileName)); + this.cmdRemove.ToolTip = Localization.GetString("Remove", Localization.GetResourceFile(this, this.MyFileName)); + this.cmdRemoveAll.ToolTip = Localization.GetString("RemoveAll", Localization.GetResourceFile(this, this.MyFileName)); - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - //set dimensions of control - if (!String.IsNullOrEmpty(_ListBoxWidth)) + // set dimensions of control + if (!string.IsNullOrEmpty(this._ListBoxWidth)) { - lstAvailable.Width = Unit.Parse(_ListBoxWidth); - lstAssigned.Width = Unit.Parse(_ListBoxWidth); + this.lstAvailable.Width = Unit.Parse(this._ListBoxWidth); + this.lstAssigned.Width = Unit.Parse(this._ListBoxWidth); } - if (!String.IsNullOrEmpty(_ListBoxHeight)) + + if (!string.IsNullOrEmpty(this._ListBoxHeight)) { - lstAvailable.Height = Unit.Parse(_ListBoxHeight); - lstAssigned.Height = Unit.Parse(_ListBoxHeight); + this.lstAvailable.Height = Unit.Parse(this._ListBoxHeight); + this.lstAssigned.Height = Unit.Parse(this._ListBoxHeight); } - - //load available - lstAvailable.DataTextField = _DataTextField; - lstAvailable.DataValueField = _DataValueField; - lstAvailable.DataSource = _Available; - lstAvailable.DataBind(); - Sort(lstAvailable); - //load selected - lstAssigned.DataTextField = _DataTextField; - lstAssigned.DataValueField = _DataValueField; - lstAssigned.DataSource = _Assigned; - lstAssigned.DataBind(); - Sort(lstAssigned); + // load available + this.lstAvailable.DataTextField = this._DataTextField; + this.lstAvailable.DataValueField = this._DataValueField; + this.lstAvailable.DataSource = this._Available; + this.lstAvailable.DataBind(); + this.Sort(this.lstAvailable); + + // load selected + this.lstAssigned.DataTextField = this._DataTextField; + this.lstAssigned.DataValueField = this._DataValueField; + this.lstAssigned.DataSource = this._Assigned; + this.lstAssigned.DataBind(); + this.Sort(this.lstAssigned); - //set enabled - lstAvailable.Enabled = _Enabled; - lstAssigned.Enabled = _Enabled; + // set enabled + this.lstAvailable.Enabled = this._Enabled; + this.lstAssigned.Enabled = this._Enabled; - //save persistent values - ViewState[ClientID + "_ListBoxWidth"] = _ListBoxWidth; - ViewState[ClientID + "_ListBoxHeight"] = _ListBoxHeight; + // save persistent values + this.ViewState[this.ClientID + "_ListBoxWidth"] = this._ListBoxWidth; + this.ViewState[this.ClientID + "_ListBoxHeight"] = this._ListBoxHeight; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -192,71 +185,73 @@ protected override void OnLoad(EventArgs e) private void cmdAdd_Click(object sender, EventArgs e) { var objList = new ArrayList(); - foreach (ListItem objListItem in lstAvailable.Items) + foreach (ListItem objListItem in this.lstAvailable.Items) { objList.Add(objListItem); } + foreach (ListItem objListItem in objList) { if (objListItem.Selected) { - lstAvailable.Items.Remove(objListItem); - lstAssigned.Items.Add(objListItem); + this.lstAvailable.Items.Remove(objListItem); + this.lstAssigned.Items.Add(objListItem); } } - lstAvailable.ClearSelection(); - lstAssigned.ClearSelection(); - Sort(lstAssigned); + + this.lstAvailable.ClearSelection(); + this.lstAssigned.ClearSelection(); + this.Sort(this.lstAssigned); } private void cmdRemove_Click(object sender, EventArgs e) { var objList = new ArrayList(); - foreach (ListItem objListItem in lstAssigned.Items) + foreach (ListItem objListItem in this.lstAssigned.Items) { objList.Add(objListItem); } + foreach (ListItem objListItem in objList) { if (objListItem.Selected) { - lstAssigned.Items.Remove(objListItem); - lstAvailable.Items.Add(objListItem); + this.lstAssigned.Items.Remove(objListItem); + this.lstAvailable.Items.Add(objListItem); } } - lstAvailable.ClearSelection(); - lstAssigned.ClearSelection(); - Sort(lstAvailable); + + this.lstAvailable.ClearSelection(); + this.lstAssigned.ClearSelection(); + this.Sort(this.lstAvailable); } private void cmdAddAll_Click(object sender, EventArgs e) { - foreach (ListItem objListItem in lstAvailable.Items) + foreach (ListItem objListItem in this.lstAvailable.Items) { - lstAssigned.Items.Add(objListItem); + this.lstAssigned.Items.Add(objListItem); } - lstAvailable.Items.Clear(); - lstAvailable.ClearSelection(); - lstAssigned.ClearSelection(); - Sort(lstAssigned); + + this.lstAvailable.Items.Clear(); + this.lstAvailable.ClearSelection(); + this.lstAssigned.ClearSelection(); + this.Sort(this.lstAssigned); } private void cmdRemoveAll_Click(object sender, EventArgs e) { - foreach (ListItem objListItem in lstAssigned.Items) + foreach (ListItem objListItem in this.lstAssigned.Items) { - lstAvailable.Items.Add(objListItem); + this.lstAvailable.Items.Add(objListItem); } - lstAssigned.Items.Clear(); - lstAvailable.ClearSelection(); - lstAssigned.ClearSelection(); - Sort(lstAvailable); - } - - #endregion - - #region "Private Methods" - + + this.lstAssigned.Items.Clear(); + this.lstAvailable.ClearSelection(); + this.lstAssigned.ClearSelection(); + this.Sort(this.lstAvailable); + } + private void Sort(ListBox ctlListBox) { var arrListItems = new ArrayList(); @@ -264,29 +259,24 @@ private void Sort(ListBox ctlListBox) { arrListItems.Add(objListItem); } + arrListItems.Sort(new ListItemComparer()); ctlListBox.Items.Clear(); foreach (ListItem objListItem in arrListItems) { ctlListBox.Items.Add(objListItem); } - } - - #endregion + } } public class ListItemComparer : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { - var a = (ListItem) x; - var b = (ListItem) y; + var a = (ListItem)x; + var b = (ListItem)y; var c = new CaseInsensitiveComparer(); return c.Compare(a.Text, b.Text); - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/UserControls/Help.cs b/DNN Platform/Library/UI/UserControls/Help.cs index 7d5353fe7c4..b064e5f783a 100644 --- a/DNN Platform/Library/UI/UserControls/Help.cs +++ b/DNN Platform/Library/UI/UserControls/Help.cs @@ -1,37 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web.UI.WebControls; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.IO; + using System.Web.UI.WebControls; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + public abstract class Help : PortalModuleBase { - private string MyFileName = "Help.ascx"; - private string _key; protected LinkButton cmdCancel; protected HyperLink cmdHelp; + private string MyFileName = "Help.ascx"; + private string _key; protected Literal helpFrame; protected Label lblHelp; protected Label lblInfo; + /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -41,16 +37,16 @@ public abstract class Help : PortalModuleBase protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdCancel.Click += cmdCancel_Click; + this.cmdCancel.Click += this.cmdCancel_Click; int moduleControlId = Null.NullInteger; - if (Request.QueryString["ctlid"] != null) + if (this.Request.QueryString["ctlid"] != null) { - moduleControlId = Int32.Parse(Request.QueryString["ctlid"]); + moduleControlId = int.Parse(this.Request.QueryString["ctlid"]); } else if (Host.EnableModuleOnLineHelp) { - helpFrame.Text = string.Format("", Host.HelpURL); + this.helpFrame.Text = string.Format("", Host.HelpURL); } ModuleControlInfo objModuleControl = ModuleControlController.GetModuleControl(moduleControlId); @@ -58,34 +54,35 @@ protected override void OnLoad(EventArgs e) { if (!string.IsNullOrEmpty(objModuleControl.HelpURL) && Host.EnableModuleOnLineHelp) { - helpFrame.Text = string.Format("", objModuleControl.HelpURL); ; + this.helpFrame.Text = string.Format("", objModuleControl.HelpURL); } else { string fileName = Path.GetFileName(objModuleControl.ControlSrc); string localResourceFile = objModuleControl.ControlSrc.Replace(fileName, Localization.LocalResourceDirectory + "/" + fileName); - if (!String.IsNullOrEmpty(Localization.GetString(ModuleActionType.HelpText, localResourceFile))) + if (!string.IsNullOrEmpty(Localization.GetString(ModuleActionType.HelpText, localResourceFile))) { - lblHelp.Text = Localization.GetString(ModuleActionType.HelpText, localResourceFile); + this.lblHelp.Text = Localization.GetString(ModuleActionType.HelpText, localResourceFile); } else { - lblHelp.Text = Localization.GetString("lblHelp.Text", Localization.GetResourceFile(this, MyFileName)); + this.lblHelp.Text = Localization.GetString("lblHelp.Text", Localization.GetResourceFile(this, this.MyFileName)); } } - _key = objModuleControl.ControlKey; - //display module info to Host users - if (UserInfo.IsSuperUser) + this._key = objModuleControl.ControlKey; + + // display module info to Host users + if (this.UserInfo.IsSuperUser) { - string strInfo = Localization.GetString("lblInfo.Text", Localization.GetResourceFile(this, MyFileName)); + string strInfo = Localization.GetString("lblInfo.Text", Localization.GetResourceFile(this, this.MyFileName)); strInfo = strInfo.Replace("[CONTROL]", objModuleControl.ControlKey); strInfo = strInfo.Replace("[SRC]", objModuleControl.ControlSrc); ModuleDefinitionInfo objModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(objModuleControl.ModuleDefID); if (objModuleDefinition != null) { strInfo = strInfo.Replace("[DEFINITION]", objModuleDefinition.FriendlyName); - DesktopModuleInfo objDesktopModule = DesktopModuleController.GetDesktopModule(objModuleDefinition.DesktopModuleID, PortalId); + DesktopModuleInfo objDesktopModule = DesktopModuleController.GetDesktopModule(objModuleDefinition.DesktopModuleID, this.PortalId); if (objDesktopModule != null) { PackageInfo objPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == objDesktopModule.PackageID); @@ -100,37 +97,39 @@ protected override void OnLoad(EventArgs e) } } } - lblInfo.Text = Server.HtmlDecode(strInfo); + + this.lblInfo.Text = this.Server.HtmlDecode(strInfo); } - cmdHelp.Visible = !string.IsNullOrEmpty(objModuleControl.HelpURL); + this.cmdHelp.Visible = !string.IsNullOrEmpty(objModuleControl.HelpURL); } - if (Page.IsPostBack == false) + + if (this.Page.IsPostBack == false) { - if (Request.UrlReferrer != null) + if (this.Request.UrlReferrer != null) { - ViewState["UrlReferrer"] = Convert.ToString(Request.UrlReferrer); + this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); } else { - ViewState["UrlReferrer"] = ""; + this.ViewState["UrlReferrer"] = string.Empty; } } } /// ----------------------------------------------------------------------------- /// - /// cmdCancel_Click runs when the cancel Button is clicked + /// cmdCancel_Click runs when the cancel Button is clicked. /// /// /// - protected void cmdCancel_Click(Object sender, EventArgs e) + protected void cmdCancel_Click(object sender, EventArgs e) { try { - Response.Redirect(Convert.ToString(ViewState["UrlReferrer"]), true); + this.Response.Redirect(Convert.ToString(this.ViewState["UrlReferrer"]), true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } diff --git a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs index 3a966a8a556..742b14685c0 100644 --- a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs +++ b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + /// ----------------------------------------------------------------------------- /// /// HelpButtonControl is a user control that provides all the server code to display @@ -24,39 +19,33 @@ namespace DotNetNuke.UI.UserControls /// /// /// To implement help, the control uses the ClientAPI interface. In particular - /// the javascript function __dnn_Help_OnClick() + /// the javascript function __dnn_Help_OnClick(). /// /// ----------------------------------------------------------------------------- public abstract class HelpButtonControl : UserControl - { - #region "Private Members" - - private string _HelpKey; - private string _ResourceKey; + { protected LinkButton cmdHelp; protected Image imgHelp; + private string _HelpKey; + private string _ResourceKey; protected Label lblHelp; - protected Panel pnlHelp; - - #endregion - - #region "Public Properties" - + protected Panel pnlHelp; + /// ----------------------------------------------------------------------------- /// - /// ControlName is the Id of the control that is associated with the label + /// Gets or sets controlName is the Id of the control that is associated with the label. /// - /// A string representing the id of the associated control + /// A string representing the id of the associated control. /// /// /// ----------------------------------------------------------------------------- - public string ControlName { get; set; } //Associated Edit Control for this Label + public string ControlName { get; set; } // Associated Edit Control for this Label /// ----------------------------------------------------------------------------- /// - /// HelpKey is the Resource Key for the Help Text + /// Gets or sets helpKey is the Resource Key for the Help Text. /// - /// A string representing the Resource Key for the Help Text + /// A string representing the Resource Key for the Help Text. /// /// /// ----------------------------------------------------------------------------- @@ -64,19 +53,20 @@ public string HelpKey { get { - return _HelpKey; + return this._HelpKey; } + set { - _HelpKey = value; + this._HelpKey = value; } } /// ----------------------------------------------------------------------------- /// - /// HelpText is value of the Help Text if no ResourceKey is provided + /// Gets or sets helpText is value of the Help Text if no ResourceKey is provided. /// - /// A string representing the Text + /// A string representing the Text. /// /// /// ----------------------------------------------------------------------------- @@ -84,26 +74,27 @@ public string HelpText { get { - return lblHelp.Text; + return this.lblHelp.Text; } + set { - lblHelp.Text = value; - imgHelp.AlternateText = HtmlUtils.Clean(value, false); - - //hide the help icon if the help text is "" - if (String.IsNullOrEmpty(value)) + this.lblHelp.Text = value; + this.imgHelp.AlternateText = HtmlUtils.Clean(value, false); + + // hide the help icon if the help text is "" + if (string.IsNullOrEmpty(value)) { - imgHelp.Visible = false; + this.imgHelp.Visible = false; } } } /// ----------------------------------------------------------------------------- /// - /// ResourceKey is the Resource Key for the Help Text + /// Gets or sets resourceKey is the Resource Key for the Help Text. /// - /// A string representing the Resource Key for the Label Text + /// A string representing the Resource Key for the Label Text. /// /// /// ----------------------------------------------------------------------------- @@ -111,21 +102,18 @@ public string ResourceKey { get { - return _ResourceKey; + return this._ResourceKey; } + set { - _ResourceKey = value; + this._ResourceKey = value; } - } - - #endregion - - #region "Event Handlers" - + } + /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -134,23 +122,24 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdHelp.Click += cmdHelp_Click; + this.cmdHelp.Click += this.cmdHelp_Click; try { - DNNClientAPI.EnableMinMax(cmdHelp, pnlHelp, true, DNNClientAPI.MinMaxPersistanceType.None); - if (String.IsNullOrEmpty(_HelpKey)) + DNNClientAPI.EnableMinMax(this.cmdHelp, this.pnlHelp, true, DNNClientAPI.MinMaxPersistanceType.None); + if (string.IsNullOrEmpty(this._HelpKey)) { - //Set Help Key to the Resource Key plus ".Help" - _HelpKey = _ResourceKey + ".Help"; + // Set Help Key to the Resource Key plus ".Help" + this._HelpKey = this._ResourceKey + ".Help"; } - string helpText = Localization.GetString(_HelpKey, this); - if (!String.IsNullOrEmpty(helpText)) + + string helpText = Localization.GetString(this._HelpKey, this); + if (!string.IsNullOrEmpty(helpText)) { - HelpText = helpText; + this.HelpText = helpText; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -158,9 +147,7 @@ protected override void OnLoad(EventArgs e) protected void cmdHelp_Click(object sender, EventArgs e) { - pnlHelp.Visible = true; - } - - #endregion + this.pnlHelp.Visible = true; + } } } diff --git a/DNN Platform/Library/UI/UserControls/IFilePickerUploader.cs b/DNN Platform/Library/UI/UserControls/IFilePickerUploader.cs index c9c07974a71..8a411df7327 100644 --- a/DNN Platform/Library/UI/UserControls/IFilePickerUploader.cs +++ b/DNN Platform/Library/UI/UserControls/IFilePickerUploader.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.UserControls { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + public interface IFilePickerUploader { int FileID { get; set; } diff --git a/DNN Platform/Library/UI/UserControls/LabelControl.cs b/DNN Platform/Library/UI/UserControls/LabelControl.cs index 5ae1b480a4f..b369e4c25b8 100644 --- a/DNN Platform/Library/UI/UserControls/LabelControl.cs +++ b/DNN Platform/Library/UI/UserControls/LabelControl.cs @@ -1,259 +1,250 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + + /// + /// LabelControl is a user control that provides all the server code to manage a + /// label, including localization, 508 support and help. + /// + /// + /// To implement help, the control uses the ClientAPI interface. In particular + /// the javascript function __dnn_Help_OnClick(). + /// + public abstract class LabelControl : UserControl + { + protected LinkButton cmdHelp; + protected HtmlGenericControl label; + protected Label lblHelp; + protected Label lblLabel; + protected Panel pnlHelp; + protected Label lblNoHelpLabel; + + /// + /// Gets or sets controlName is the Id of the control that is associated with the label. + /// + /// A string representing the id of the associated control. + /// + /// + public string ControlName { get; set; } + + /// + /// Gets or sets set the associate control id format, combined used with ControlName for controls + /// which have child edit control and want that child control focus when click label. + /// + public string AssociateFormat { get; set; } + + /// + /// Gets or sets css style applied to the asp:label control. + /// + /// A string representing css class name. + /// + /// + public string CssClass { get; set; } + + /// + /// Gets or sets helpKey is the Resource Key for the Help Text. + /// + /// A string representing the Resource Key for the Help Text. + /// + /// + public string HelpKey { get; set; } + + /// + /// Gets or sets helpText is value of the Help Text if no ResourceKey is provided. + /// + /// A string representing the Text. + /// + /// + public string HelpText + { + get + { + return this.lblHelp.Text; + } + + set + { + this.lblHelp.Text = value; + } + } - /// - /// LabelControl is a user control that provides all the server code to manage a - /// label, including localization, 508 support and help. - /// - /// - /// To implement help, the control uses the ClientAPI interface. In particular - /// the javascript function __dnn_Help_OnClick() - /// - public abstract class LabelControl : UserControl - { - - #region Private Memebers - - protected LinkButton cmdHelp; - protected HtmlGenericControl label; - protected Label lblHelp; - protected Label lblLabel; - protected Panel pnlHelp; - protected Label lblNoHelpLabel; - - #endregion - - #region Properties - - /// - /// ControlName is the Id of the control that is associated with the label - /// - /// A string representing the id of the associated control - /// - /// - public string ControlName { get; set; } - - /// - /// Set the associate control id format, combined used with ControlName for controls - /// which have child edit control and want that child control focus when click label. - /// - public string AssociateFormat { get; set; } - - /// - /// Css style applied to the asp:label control - /// - /// A string representing css class name - /// - /// - public string CssClass { get; set; } - - /// - /// HelpKey is the Resource Key for the Help Text - /// - /// A string representing the Resource Key for the Help Text - /// - /// - public string HelpKey { get; set; } - - /// - /// HelpText is value of the Help Text if no ResourceKey is provided - /// - /// A string representing the Text - /// - /// - public string HelpText - { - get - { - return lblHelp.Text; - } - set - { - lblHelp.Text = value; - } - } - - public string NoHelpLabelText - { - get - { - return lblNoHelpLabel.Text; - } - set - { - lblNoHelpLabel.Text = value; - } - } - - /// - /// ResourceKey is the Resource Key for the Label Text - /// - /// A string representing the Resource Key for the Label Text - /// - /// - public string ResourceKey { get; set; } - - /// - /// Suffix is Optional Text that appears after the Localized Label Text - /// - /// A string representing the Optional Text - /// - /// - public string Suffix { get; set; } - - /// - /// Text is value of the Label Text if no ResourceKey is provided - /// - /// A string representing the Text - /// - /// - public string Text - { - get - { - return lblLabel.Text; - } - set - { - lblLabel.Text = value; - } - } - - /// - /// Width is value of the Label Width - /// - /// A string representing the Text - /// - /// - public Unit Width - { - get - { - return lblLabel.Width; - } - set - { - lblLabel.Width = value; - } - } - - #endregion - - #region Event Handlers - - /// - /// Page_Load runs when the control is loaded - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - try - { - RegisterClientDependencies(); - } - catch (Exception exc) //Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } + public string NoHelpLabelText + { + get + { + return this.lblNoHelpLabel.Text; + } + + set + { + this.lblNoHelpLabel.Text = value; + } + } + + /// + /// Gets or sets resourceKey is the Resource Key for the Label Text. + /// + /// A string representing the Resource Key for the Label Text. + /// + /// + public string ResourceKey { get; set; } + + /// + /// Gets or sets suffix is Optional Text that appears after the Localized Label Text. + /// + /// A string representing the Optional Text. + /// + /// + public string Suffix { get; set; } + + /// + /// Gets or sets text is value of the Label Text if no ResourceKey is provided. + /// + /// A string representing the Text. + /// + /// + public string Text + { + get + { + return this.lblLabel.Text; + } + + set + { + this.lblLabel.Text = value; + } + } + + /// + /// Gets or sets width is value of the Label Width. + /// + /// A string representing the Text. + /// + /// + public Unit Width + { + get + { + return this.lblLabel.Width; + } + + set + { + this.lblLabel.Width = value; + } + } + + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + try + { + this.RegisterClientDependencies(); + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); - //get the localised text - if (String.IsNullOrEmpty(ResourceKey)) - { - //Set Resource Key to the ID of the control - ResourceKey = ID; - } - if ((!string.IsNullOrEmpty(ResourceKey))) - { - var localText = Localization.GetString(ResourceKey, this); - if (!string.IsNullOrEmpty(localText)) - { - Text = localText + Suffix; - //NoHelpLabelText = Text; - } - else - { - Text += Suffix; - //NoHelpLabelText = Text; - } - } + // get the localised text + if (string.IsNullOrEmpty(this.ResourceKey)) + { + // Set Resource Key to the ID of the control + this.ResourceKey = this.ID; + } + + if (!string.IsNullOrEmpty(this.ResourceKey)) + { + var localText = Localization.GetString(this.ResourceKey, this); + if (!string.IsNullOrEmpty(localText)) + { + this.Text = localText + this.Suffix; + + // NoHelpLabelText = Text; + } + else + { + this.Text += this.Suffix; + + // NoHelpLabelText = Text; + } + } - //Set Help Key to the Resource Key plus ".Help" - if (String.IsNullOrEmpty(HelpKey)) - { - HelpKey = ResourceKey + ".Help"; - } + // Set Help Key to the Resource Key plus ".Help" + if (string.IsNullOrEmpty(this.HelpKey)) + { + this.HelpKey = this.ResourceKey + ".Help"; + } - var helpText = Localization.GetString(HelpKey, this); - if ((!string.IsNullOrEmpty(helpText)) || (string.IsNullOrEmpty(HelpText))) - { - HelpText = helpText; - } + var helpText = Localization.GetString(this.HelpKey, this); + if ((!string.IsNullOrEmpty(helpText)) || string.IsNullOrEmpty(this.HelpText)) + { + this.HelpText = helpText; + } - if (string.IsNullOrEmpty(HelpText)) - { - pnlHelp.Visible = cmdHelp.Visible = false; - //lblHelp.Visible = false; - //lblNoHelpLabel.Visible = true; - } + if (string.IsNullOrEmpty(this.HelpText)) + { + this.pnlHelp.Visible = this.cmdHelp.Visible = false; + + // lblHelp.Visible = false; + // lblNoHelpLabel.Visible = true; + } - if (!string.IsNullOrEmpty(CssClass)) - { - lblLabel.CssClass = CssClass; - } + if (!string.IsNullOrEmpty(this.CssClass)) + { + this.lblLabel.CssClass = this.CssClass; + } - //find the reference control in the parents Controls collection - if (!String.IsNullOrEmpty(ControlName)) - { - var c = Parent.FindControl(ControlName); - var clientId = ControlName; - if (c != null) - { - clientId = c.ClientID; - } + // find the reference control in the parents Controls collection + if (!string.IsNullOrEmpty(this.ControlName)) + { + var c = this.Parent.FindControl(this.ControlName); + var clientId = this.ControlName; + if (c != null) + { + clientId = c.ClientID; + } - if (!string.IsNullOrEmpty(AssociateFormat)) + if (!string.IsNullOrEmpty(this.AssociateFormat)) { - clientId = string.Format(AssociateFormat, clientId); + clientId = string.Format(this.AssociateFormat, clientId); } - label.Attributes["for"] = clientId; + + this.label.Attributes["for"] = clientId; } - } + } - private void RegisterClientDependencies() - { + private void RegisterClientDependencies() + { JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - //ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); - } - - #endregion - - } + + // ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); + } + } } diff --git a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs index 0f4ab81bf56..674370275f5 100644 --- a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs +++ b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs @@ -1,44 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + /// ----------------------------------------------------------------------------- /// /// LocaleSelectorControl is a user control that provides all the server code to manage - /// localisation selection + /// localisation selection. /// /// ----------------------------------------------------------------------------- public abstract class LocaleSelectorControl : UserControlBase - { - #region "Controls" - + { protected DropDownList ddlPortalDefaultLanguage; protected Literal litStatus; - protected RadioButtonList rbViewType; - - #endregion - + protected RadioButtonList rbViewType; private string MyFileName = "LocaleSelectorControl.ascx"; - private string _ViewType = ""; + private string _ViewType = string.Empty; + + public string CultureCode + { + get + { + return this.ddlPortalDefaultLanguage.SelectedValue; + } + } private CultureDropDownTypes DisplayType { get { - switch (ViewType) + switch (this.ViewType) { case "NATIVE": return CultureDropDownTypes.NativeName; @@ -54,63 +52,48 @@ private string ViewType { get { - if (string.IsNullOrEmpty(_ViewType)) + if (string.IsNullOrEmpty(this._ViewType)) { - _ViewType = Convert.ToString(Personalization.GetProfile("LanguageEnabler", string.Format("ViewType{0}", PortalSettings.PortalId))); + this._ViewType = Convert.ToString(Personalization.GetProfile("LanguageEnabler", string.Format("ViewType{0}", this.PortalSettings.PortalId))); } - if (string.IsNullOrEmpty(_ViewType)) + + if (string.IsNullOrEmpty(this._ViewType)) { - _ViewType = "NATIVE"; + this._ViewType = "NATIVE"; } - return _ViewType; + + return this._ViewType; } - } - - #region "Public Methods" - + } + public void BindDefaultLanguageSelector() { - if (Page.IsPostBack == false) + if (this.Page.IsPostBack == false) { - Localization.LoadCultureDropDownList(ddlPortalDefaultLanguage, DisplayType, PortalSettings.DefaultLanguage, true); + Localization.LoadCultureDropDownList(this.ddlPortalDefaultLanguage, this.DisplayType, this.PortalSettings.DefaultLanguage, true); } - } - - #endregion - - #region "Public properties" - - public string CultureCode - { - get - { - return ddlPortalDefaultLanguage.SelectedValue; - } - } - - #endregion - - #region "Event Handlers" - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - rbViewType.SelectedIndexChanged += rbViewType_SelectedIndexChanged; + this.rbViewType.SelectedIndexChanged += this.rbViewType_SelectedIndexChanged; - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { ListItem item = default(ListItem); - item = new ListItem(Localization.GetString("NativeName.Text", Localization.GetResourceFile(this, MyFileName)), "NATIVE"); - rbViewType.Items.Add(item); - if (ViewType == "NATIVE") + item = new ListItem(Localization.GetString("NativeName.Text", Localization.GetResourceFile(this, this.MyFileName)), "NATIVE"); + this.rbViewType.Items.Add(item); + if (this.ViewType == "NATIVE") { item.Selected = true; } - item = new ListItem(Localization.GetString("EnglishName.Text", Localization.GetResourceFile(this, MyFileName)), "ENGLISH"); - rbViewType.Items.Add(item); - if (ViewType == "ENGLISH") + + item = new ListItem(Localization.GetString("EnglishName.Text", Localization.GetResourceFile(this, this.MyFileName)), "ENGLISH"); + this.rbViewType.Items.Add(item); + if (this.ViewType == "ENGLISH") { item.Selected = true; } @@ -121,17 +104,15 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (Visible) + if (this.Visible) { - BindDefaultLanguageSelector(); + this.BindDefaultLanguageSelector(); } } private void rbViewType_SelectedIndexChanged(object sender, EventArgs e) { - _ViewType = rbViewType.SelectedValue; - } - - #endregion + this._ViewType = this.rbViewType.SelectedValue; + } } } diff --git a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs index 69da823ce6d..43d5e4f2808 100644 --- a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs +++ b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs @@ -1,86 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text.RegularExpressions; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Text.RegularExpressions; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + public abstract class ModuleAuditControl : UserControl { - private const string MyFileName = "ModuleAuditControl.ascx"; - private string _systemUser; protected Label lblCreatedBy; protected Label lblUpdatedBy; + private const string MyFileName = "ModuleAuditControl.ascx"; + private string _systemUser; private static readonly Regex CheckDateColumnRegex = new Regex(@"^-?\d+$", RegexOptions.Compiled); - private string DisplayMode => (Request.QueryString["Display"] ?? "").ToLowerInvariant(); - - [Serializable] - private class EntityInfo - { - public int CreatedByUserID { get; set; } - public DateTime CreatedOnDate { get; set; } - public int LastModifiedByUserID { get; set; } - public DateTime LastModifiedOnDate { get; set; } - } - public ModuleAuditControl() { - LastModifiedDate = String.Empty; - LastModifiedByUser = String.Empty; - CreatedByUser = String.Empty; - CreatedDate = String.Empty; + this.LastModifiedDate = string.Empty; + this.LastModifiedByUser = string.Empty; + this.CreatedByUser = string.Empty; + this.CreatedDate = string.Empty; } public string CreatedDate { private get; set; } public string CreatedByUser { private get; set; } + private string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); + + [Serializable] + private class EntityInfo + { + public int CreatedByUserID { get; set; } + + public DateTime CreatedOnDate { get; set; } + + public int LastModifiedByUserID { get; set; } + + public DateTime LastModifiedOnDate { get; set; } + } + public string LastModifiedByUser { private get; set; } public string LastModifiedDate { private get; set; } - public BaseEntityInfo Entity - { - set - { - if (value != null) - { - var entity = new EntityInfo(); - entity.CreatedByUserID = value.CreatedByUserID; - entity.CreatedOnDate = value.CreatedOnDate; - entity.LastModifiedByUserID = value.LastModifiedByUserID; - entity.LastModifiedOnDate = value.LastModifiedOnDate; - - ViewState["Entity"] = entity; - } - else - { - ViewState["Entity"] = null; - } - } - } - - private EntityInfo Model - { - get { return ViewState["Entity"] as EntityInfo; } - } + public BaseEntityInfo Entity + { + set + { + if (value != null) + { + var entity = new EntityInfo(); + entity.CreatedByUserID = value.CreatedByUserID; + entity.CreatedOnDate = value.CreatedOnDate; + entity.LastModifiedByUserID = value.LastModifiedByUserID; + entity.LastModifiedOnDate = value.LastModifiedOnDate; + + this.ViewState["Entity"] = entity; + } + else + { + this.ViewState["Entity"] = null; + } + } + } + + private EntityInfo Model + { + get { return this.ViewState["Entity"] as EntityInfo; } + } protected override void OnLoad(EventArgs e) { @@ -88,27 +87,27 @@ protected override void OnLoad(EventArgs e) try { - if (Model != null) + if (this.Model != null) { - CreatedByUser = Model.CreatedByUserID.ToString(); - CreatedDate = Model.CreatedOnDate.ToString(); - LastModifiedByUser = Model.LastModifiedByUserID.ToString(); - LastModifiedDate = Model.LastModifiedOnDate.ToString(); + this.CreatedByUser = this.Model.CreatedByUserID.ToString(); + this.CreatedDate = this.Model.CreatedOnDate.ToString(); + this.LastModifiedByUser = this.Model.LastModifiedByUserID.ToString(); + this.LastModifiedDate = this.Model.LastModifiedOnDate.ToString(); } - //check to see if updated check is redundant - var isCreatorAndUpdater = CreatedByUser == LastModifiedByUser && - Globals.NumberMatchRegex.IsMatch(CreatedByUser) && Globals.NumberMatchRegex.IsMatch(LastModifiedByUser); + // check to see if updated check is redundant + var isCreatorAndUpdater = this.CreatedByUser == this.LastModifiedByUser && + Globals.NumberMatchRegex.IsMatch(this.CreatedByUser) && Globals.NumberMatchRegex.IsMatch(this.LastModifiedByUser); - _systemUser = Localization.GetString("SystemUser", Localization.GetResourceFile(this, MyFileName)); - var displayMode = DisplayMode; + this._systemUser = Localization.GetString("SystemUser", Localization.GetResourceFile(this, MyFileName)); + var displayMode = this.DisplayMode; if (displayMode != "editor" && displayMode != "settings") { - ShowCreatedString(); - ShowUpdatedString(isCreatorAndUpdater); + this.ShowCreatedString(); + this.ShowUpdatedString(isCreatorAndUpdater); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -116,58 +115,58 @@ protected override void OnLoad(EventArgs e) private void ShowCreatedString() { - if (CheckDateColumnRegex.IsMatch(CreatedByUser)) + if (CheckDateColumnRegex.IsMatch(this.CreatedByUser)) { - if (int.Parse(CreatedByUser) == Null.NullInteger) + if (int.Parse(this.CreatedByUser) == Null.NullInteger) { - CreatedByUser = _systemUser; + this.CreatedByUser = this._systemUser; } else { - //contains a UserID - UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(CreatedByUser)); + // contains a UserID + UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(this.CreatedByUser)); if (userInfo != null) { - CreatedByUser = userInfo.DisplayName; + this.CreatedByUser = userInfo.DisplayName; } } } + string createdString = Localization.GetString("CreatedBy", Localization.GetResourceFile(this, MyFileName)); - lblCreatedBy.Text = string.Format(createdString, CreatedByUser, CreatedDate); - + this.lblCreatedBy.Text = string.Format(createdString, this.CreatedByUser, this.CreatedDate); } private void ShowUpdatedString(bool isCreatorAndUpdater) { - //check to see if audit contains update information - if (string.IsNullOrEmpty(LastModifiedDate)) + // check to see if audit contains update information + if (string.IsNullOrEmpty(this.LastModifiedDate)) { return; } - if (CheckDateColumnRegex.IsMatch(LastModifiedByUser)) + if (CheckDateColumnRegex.IsMatch(this.LastModifiedByUser)) { if (isCreatorAndUpdater) { - LastModifiedByUser = CreatedByUser; + this.LastModifiedByUser = this.CreatedByUser; } - else if (int.Parse(LastModifiedByUser) == Null.NullInteger) + else if (int.Parse(this.LastModifiedByUser) == Null.NullInteger) { - LastModifiedByUser = _systemUser; + this.LastModifiedByUser = this._systemUser; } else { - //contains a UserID - UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(LastModifiedByUser)); + // contains a UserID + UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(this.LastModifiedByUser)); if (userInfo != null) { - LastModifiedByUser = userInfo.DisplayName; + this.LastModifiedByUser = userInfo.DisplayName; } } } string updatedByString = Localization.GetString("UpdatedBy", Localization.GetResourceFile(this, MyFileName)); - lblUpdatedBy.Text = string.Format(updatedByString, LastModifiedByUser, LastModifiedDate); + this.lblUpdatedBy.Text = string.Format(updatedByString, this.LastModifiedByUser, this.LastModifiedDate); } } } diff --git a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs index a79a78e8b40..6f9c27f9c85 100644 --- a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs +++ b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.Utilities; + /// ----------------------------------------------------------------------------- /// /// SectionHeadControl is a user control that provides all the server code to allow a @@ -27,28 +22,21 @@ namespace DotNetNuke.UI.UserControls /// /// ----------------------------------------------------------------------------- public class SectionHeadControl : UserControl - { - #region "Private Members" - + { + protected ImageButton imgIcon; + protected Label lblTitle; private bool _includeRule; private bool _isExpanded = true; private string _javaScript = "__dnn_SectionMaxMin"; private string _maxImageUrl = "images/plus.gif"; private string _minImageUrl = "images/minus.gif"; - protected ImageButton imgIcon; - protected Label lblTitle; - protected Panel pnlRule; - - #endregion - - #region "Public Properties" - - + protected Panel pnlRule; + /// ----------------------------------------------------------------------------- /// - /// CssClass determines the Css Class used for the Title Text + /// Gets or sets cssClass determines the Css Class used for the Title Text. /// - /// A string representing the name of the css class + /// A string representing the name of the css class. /// /// /// ----------------------------------------------------------------------------- @@ -56,20 +44,21 @@ public string CssClass { get { - return lblTitle.CssClass; + return this.lblTitle.CssClass; } + set { - lblTitle.CssClass = value; + this.lblTitle.CssClass = value; } } /// ----------------------------------------------------------------------------- /// - /// IncludeRule determines whether there is a horizontal rule displayed under the - /// header text + /// Gets or sets a value indicating whether includeRule determines whether there is a horizontal rule displayed under the + /// header text. /// - /// A string representing true or false + /// A string representing true or false. /// /// /// ----------------------------------------------------------------------------- @@ -77,17 +66,18 @@ public bool IncludeRule { get { - return _includeRule; + return this._includeRule; } + set { - _includeRule = value; + this._includeRule = value; } } /// ----------------------------------------------------------------------------- /// - /// IsExpanded determines whether the section is expanded or collapsed. + /// Gets or sets a value indicating whether isExpanded determines whether the section is expanded or collapsed. /// /// Boolean value that determines whether the panel is expanded (true) /// or collapsed (false). The default is true. @@ -98,20 +88,21 @@ public bool IsExpanded { get { - return DNNClientAPI.MinMaxContentVisibile(imgIcon, -1, !_isExpanded, DNNClientAPI.MinMaxPersistanceType.Page); + return DNNClientAPI.MinMaxContentVisibile(this.imgIcon, -1, !this._isExpanded, DNNClientAPI.MinMaxPersistanceType.Page); } + set { - _isExpanded = value; - DNNClientAPI.MinMaxContentVisibile(imgIcon, -1, !_isExpanded, DNNClientAPI.MinMaxPersistanceType.Page, value); + this._isExpanded = value; + DNNClientAPI.MinMaxContentVisibile(this.imgIcon, -1, !this._isExpanded, DNNClientAPI.MinMaxPersistanceType.Page, value); } } /// ----------------------------------------------------------------------------- /// - /// JavaScript is the name of the javascript function implementation. + /// Gets or sets javaScript is the name of the javascript function implementation. /// - /// A string representing the name of the javascript function implementation + /// A string representing the name of the javascript function implementation. /// /// /// ----------------------------------------------------------------------------- @@ -119,20 +110,21 @@ public string JavaScript { get { - return _javaScript; + return this._javaScript; } + set { - _javaScript = value; + this._javaScript = value; } } /// ----------------------------------------------------------------------------- /// - /// The MaxImageUrl is the url of the image displayed when the contained panel is + /// Gets or sets the MaxImageUrl is the url of the image displayed when the contained panel is /// collapsed. /// - /// A string representing the url of the Max Image + /// A string representing the url of the Max Image. /// /// /// ----------------------------------------------------------------------------- @@ -140,20 +132,21 @@ public string MaxImageUrl { get { - return _maxImageUrl; + return this._maxImageUrl; } + set { - _maxImageUrl = value; + this._maxImageUrl = value; } } /// ----------------------------------------------------------------------------- /// - /// The MinImageUrl is the url of the image displayed when the contained panel is + /// Gets or sets the MinImageUrl is the url of the image displayed when the contained panel is /// expanded. /// - /// A string representing the url of the Min Image + /// A string representing the url of the Min Image. /// /// /// ----------------------------------------------------------------------------- @@ -161,39 +154,40 @@ public string MinImageUrl { get { - return _minImageUrl; + return this._minImageUrl; } + set { - _minImageUrl = value; + this._minImageUrl = value; } - } - - /// ----------------------------------------------------------------------------- - /// - /// The ResourceKey is the key used to identify the Localization Resource for the - /// title text. - /// - /// A string representing the ResourceKey. - /// - /// - /// ----------------------------------------------------------------------------- - public string ResourceKey { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// The Section is the Id of the DHTML object that contains the xection content - /// title text. - /// - /// A string representing the Section. - /// - /// - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the ResourceKey is the key used to identify the Localization Resource for the + /// title text. + /// + /// A string representing the ResourceKey. + /// + /// + /// ----------------------------------------------------------------------------- + public string ResourceKey { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Section is the Id of the DHTML object that contains the xection content + /// title text. + /// + /// A string representing the Section. + /// + /// + /// ----------------------------------------------------------------------------- public string Section { get; set; } /// ----------------------------------------------------------------------------- /// - /// The Text is the name or title of the section + /// Gets or sets the Text is the name or title of the section. /// /// A string representing the Title Text. /// @@ -203,21 +197,18 @@ public string Text { get { - return lblTitle.Text; + return this.lblTitle.Text; } + set { - lblTitle.Text = value; + this.lblTitle.Text = value; } - } - - #endregion - - #region "Event Handlers" - + } + /// ----------------------------------------------------------------------------- /// - /// Assign resource key to label for localization + /// Assign resource key to label for localization. /// /// /// @@ -229,13 +220,13 @@ protected override void OnLoad(EventArgs e) try { - //set the resourcekey attribute to the label - if (!String.IsNullOrEmpty(ResourceKey)) + // set the resourcekey attribute to the label + if (!string.IsNullOrEmpty(this.ResourceKey)) { - lblTitle.Attributes["resourcekey"] = ResourceKey; + this.lblTitle.Attributes["resourcekey"] = this.ResourceKey; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -243,7 +234,7 @@ protected override void OnLoad(EventArgs e) /// ----------------------------------------------------------------------------- /// - /// Renders the SectionHeadControl + /// Renders the SectionHeadControl. /// /// /// @@ -255,18 +246,18 @@ protected override void OnPreRender(EventArgs e) try { - var ctl = (HtmlControl) Parent.FindControl(Section); + var ctl = (HtmlControl)this.Parent.FindControl(this.Section); if (ctl != null) { - lblTitle.Attributes.Add("onclick", imgIcon.ClientID + ".click();"); - lblTitle.Attributes.Add("style", "cursor: pointer"); - DNNClientAPI.EnableMinMax(imgIcon, ctl, !IsExpanded, Page.ResolveUrl(MinImageUrl), Page.ResolveUrl(MaxImageUrl), DNNClientAPI.MinMaxPersistanceType.Page); + this.lblTitle.Attributes.Add("onclick", this.imgIcon.ClientID + ".click();"); + this.lblTitle.Attributes.Add("style", "cursor: pointer"); + DNNClientAPI.EnableMinMax(this.imgIcon, ctl, !this.IsExpanded, this.Page.ResolveUrl(this.MinImageUrl), this.Page.ResolveUrl(this.MaxImageUrl), DNNClientAPI.MinMaxPersistanceType.Page); } - - //optionlly show hr - pnlRule.Visible = _includeRule; + + // optionlly show hr + this.pnlRule.Visible = this._includeRule; } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -274,13 +265,11 @@ protected override void OnPreRender(EventArgs e) protected void imgIcon_Click(object sender, ImageClickEventArgs e) { - var ctl = (HtmlControl) Parent.FindControl(Section); + var ctl = (HtmlControl)this.Parent.FindControl(this.Section); if (ctl != null) { - IsExpanded = !IsExpanded; + this.IsExpanded = !this.IsExpanded; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/UserControls/TextEditor.cs b/DNN Platform/Library/UI/UserControls/TextEditor.cs index 429f1eaf885..2feafb07e49 100644 --- a/DNN Platform/Library/UI/UserControls/TextEditor.cs +++ b/DNN Platform/Library/UI/UserControls/TextEditor.cs @@ -1,46 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text.RegularExpressions; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Modules.HTMLEditorProvider; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Text.RegularExpressions; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.HTMLEditorProvider; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + /// ----------------------------------------------------------------------------- /// Class: TextEditor /// Project: DotNetNuke /// ----------------------------------------------------------------------------- /// - /// TextEditor is a user control that provides a wrapper for the HtmlEditor providers + /// TextEditor is a user control that provides a wrapper for the HtmlEditor providers. /// /// /// /// ----------------------------------------------------------------------------- [ValidationPropertyAttribute("Text")] public class TextEditor : UserControl - { - #region Private Members - - private const string MyFileName = "TextEditor.ascx"; - private HtmlEditorProvider _richTextEditor; + { protected Panel PanelTextEditor; protected RadioButtonList OptRender; + private const string MyFileName = "TextEditor.ascx"; + private HtmlEditorProvider _richTextEditor; protected RadioButtonList OptView; protected PlaceHolder PlcEditor; protected HtmlGenericControl DivBasicTextBox; @@ -51,56 +45,53 @@ public class TextEditor : UserControl public TextEditor() { - HtmlEncode = true; - ChooseRender = true; - ChooseMode = true; - } - - #endregion - - #region Properties - - ///Enables/Disables the option to allow the user to select between Rich/Basic Mode, Default is true. + this.HtmlEncode = true; + this.ChooseRender = true; + this.ChooseMode = true; + } + + /// Gets or sets a value indicating whether enables/Disables the option to allow the user to select between Rich/Basic Mode, Default is true. public bool ChooseMode { get; set; } - ///Determines wether or not the Text/Html button is rendered for Basic mode, Default is True + /// Gets or sets a value indicating whether determines wether or not the Text/Html button is rendered for Basic mode, Default is True. public bool ChooseRender { get; set; } - ///Gets/Sets the Default mode of the control, either "RICH" or "BASIC", Defaults to Rich - public string DefaultMode + /// Gets or sets /Sets the Default mode of the control, either "RICH" or "BASIC", Defaults to Rich. + public string DefaultMode { get { - return ViewState["DefaultMode"] == null || String.IsNullOrEmpty(ViewState["DefaultMode"].ToString()) ? "RICH" : ViewState["DefaultMode"].ToString(); + return this.ViewState["DefaultMode"] == null || string.IsNullOrEmpty(this.ViewState["DefaultMode"].ToString()) ? "RICH" : this.ViewState["DefaultMode"].ToString(); } + set { if (!value.Equals("BASIC", StringComparison.OrdinalIgnoreCase)) { - ViewState["DefaultMode"] = "RICH"; + this.ViewState["DefaultMode"] = "RICH"; } else { - ViewState["DefaultMode"] = "BASIC"; + this.ViewState["DefaultMode"] = "BASIC"; } } } - ///Gets/Sets the Height of the control - public Unit Height { get; set; } + /// Gets or sets /Sets the Height of the control. + public Unit Height { get; set; } - ///Turns on HtmlEncoding of text. If this option is on the control will assume, it is being passed encoded text and will decode. + /// Gets or sets a value indicating whether turns on HtmlEncoding of text. If this option is on the control will assume, it is being passed encoded text and will decode. public bool HtmlEncode { get; set; } - ///The current mode of the control "RICH", "BASIC" - public string Mode + /// Gets or sets the current mode of the control "RICH", "BASIC". + public string Mode { get { - string strMode = ""; + string strMode = string.Empty; UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - //Check if Personal Preference is set + // Check if Personal Preference is set if (objUserInfo.UserID >= 0) { if (Personalization.GetProfile("DotNetNuke.TextEditor", "PreferredTextEditor") != null) @@ -108,35 +99,37 @@ public string Mode strMode = Convert.ToString(Personalization.GetProfile("DotNetNuke.TextEditor", "PreferredTextEditor")); } } - - //If no Preference Check if Viewstate has been saved - if (String.IsNullOrEmpty(strMode)) + + // If no Preference Check if Viewstate has been saved + if (string.IsNullOrEmpty(strMode)) { - if (ViewState["DesktopMode"] != null && !String.IsNullOrEmpty(ViewState["DesktopMode"].ToString())) + if (this.ViewState["DesktopMode"] != null && !string.IsNullOrEmpty(this.ViewState["DesktopMode"].ToString())) { - strMode = Convert.ToString(ViewState["DesktopMode"]); + strMode = Convert.ToString(this.ViewState["DesktopMode"]); } } - - //Finally if still no value Use default - if (String.IsNullOrEmpty(strMode)) + + // Finally if still no value Use default + if (string.IsNullOrEmpty(strMode)) { - strMode = DefaultMode; + strMode = this.DefaultMode; } - if (strMode == "RICH" && !IsRichEditorAvailable) + if (strMode == "RICH" && !this.IsRichEditorAvailable) { strMode = "BASIC"; } + return strMode; } + set { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); if (!value.Equals("BASIC", StringComparison.OrdinalIgnoreCase)) { - ViewState["DesktopMode"] = "RICH"; + this.ViewState["DesktopMode"] = "RICH"; if (objUserInfo.UserID >= 0) { @@ -145,7 +138,7 @@ public string Mode } else { - ViewState["DesktopMode"] = "BASIC"; + this.ViewState["DesktopMode"] = "BASIC"; if (objUserInfo.UserID >= 0) { @@ -155,47 +148,53 @@ public string Mode } } - ///Gets/Sets the Text of the control - public string Text + /// Gets or sets /Sets the Text of the control. + public string Text { get { - switch (OptView.SelectedItem.Value) + switch (this.OptView.SelectedItem.Value) { case "BASIC": - switch (OptRender.SelectedItem.Value) + switch (this.OptRender.SelectedItem.Value) { case "T": - return Encode(HtmlUtils.ConvertToHtml(RemoveBaseTags(TxtDesktopHTML.Text))); - //break; + return this.Encode(HtmlUtils.ConvertToHtml(RemoveBaseTags(this.TxtDesktopHTML.Text))); + + // break; case "R": - return RemoveBaseTags(TxtDesktopHTML.Text); - //break; + return RemoveBaseTags(this.TxtDesktopHTML.Text); + + // break; default: - return Encode(RemoveBaseTags(TxtDesktopHTML.Text)); - //break; + return this.Encode(RemoveBaseTags(this.TxtDesktopHTML.Text)); + + // break; } + default: - return IsRichEditorAvailable ? Encode(RemoveBaseTags(_richTextEditor.Text)) : Encode(RemoveBaseTags(TxtDesktopHTML.Text)); + return this.IsRichEditorAvailable ? this.Encode(RemoveBaseTags(this._richTextEditor.Text)) : this.Encode(RemoveBaseTags(this.TxtDesktopHTML.Text)); } } + set { - TxtDesktopHTML.Text = HtmlUtils.ConvertToText(Decode(value)); - if (IsRichEditorAvailable) + this.TxtDesktopHTML.Text = HtmlUtils.ConvertToText(this.Decode(value)); + if (this.IsRichEditorAvailable) { - _richTextEditor.Text = Decode(value); + this._richTextEditor.Text = this.Decode(value); } } } - ///Sets the render mode for Basic mode. {Raw | HTML | Text} - public string TextRenderMode + /// Gets or sets the render mode for Basic mode. {Raw | HTML | Text}. + public string TextRenderMode { get { - return Convert.ToString(ViewState["textrender"]); + return Convert.ToString(this.ViewState["textrender"]); } + set { var strMode = value.ToUpper().Substring(0, 1); @@ -203,36 +202,37 @@ public string TextRenderMode { strMode = "H"; } - ViewState["textrender"] = strMode; + + this.ViewState["textrender"] = strMode; } } - ///Gets/Sets the Width of the control - public Unit Width { get; set; } + /// Gets or sets /Sets the Width of the control. + public Unit Width { get; set; } public bool IsRichEditorAvailable { get { - return _richTextEditor != null; + return this._richTextEditor != null; } } - ///Allows public access ot the HtmlEditorProvider - public HtmlEditorProvider RichText + /// Gets allows public access ot the HtmlEditorProvider. + public HtmlEditorProvider RichText { get { - return _richTextEditor; + return this._richTextEditor; } } - /// Allows public access of the BasicTextEditor + /// Gets allows public access of the BasicTextEditor. public TextBox BasicTextEditor { get { - return TxtDesktopHTML; + return this.TxtDesktopHTML; } } @@ -243,159 +243,154 @@ public string OptViewClientId return this.OptView.ClientID; } } + public string LocalResourceFile { get { - return TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + MyFileName; + return this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + MyFileName; } + } + + public void ChangeMode(string mode) + { + this.OptView.SelectedItem.Value = mode; + this.OptViewSelectedIndexChanged(this.OptView, EventArgs.Empty); } - - #endregion - - #region Private Methods + + public void ChangeTextRenderMode(string textRenderMode) + { + this.OptRender.SelectedItem.Value = textRenderMode; + this.OptRenderSelectedIndexChanged(this.OptRender, EventArgs.Empty); + } + private static string RemoveBaseTags(string strInput) + { + return Globals.BaseTagRegex.Replace(strInput, " "); + } + /// ----------------------------------------------------------------------------- /// - /// Decodes the html + /// Decodes the html. /// /// /// - /// Html to decode - /// The decoded html + /// Html to decode. + /// The decoded html. /// ----------------------------------------------------------------------------- private string Decode(string strHtml) { - return HtmlEncode ? Server.HtmlDecode(strHtml) : strHtml; + return this.HtmlEncode ? this.Server.HtmlDecode(strHtml) : strHtml; } /// ----------------------------------------------------------------------------- /// - /// Encodes the html + /// Encodes the html. /// /// /// - /// Html to encode - /// The encoded html + /// Html to encode. + /// The encoded html. /// ----------------------------------------------------------------------------- private string Encode(string strHtml) { - return HtmlEncode ? Server.HtmlEncode(strHtml) : strHtml; + return this.HtmlEncode ? this.Server.HtmlEncode(strHtml) : strHtml; } /// ----------------------------------------------------------------------------- /// - /// Builds the radio button lists + /// Builds the radio button lists. /// /// /// /// ----------------------------------------------------------------------------- private void PopulateLists() { - if (OptRender.Items.Count == 0) + if (this.OptRender.Items.Count == 0) { - OptRender.Items.Add(new ListItem(Localization.GetString("Text", Localization.GetResourceFile(this, MyFileName)), "T")); - OptRender.Items.Add(new ListItem(Localization.GetString("Html", Localization.GetResourceFile(this, MyFileName)), "H")); - OptRender.Items.Add(new ListItem(Localization.GetString("Raw", Localization.GetResourceFile(this, MyFileName)), "R")); + this.OptRender.Items.Add(new ListItem(Localization.GetString("Text", Localization.GetResourceFile(this, MyFileName)), "T")); + this.OptRender.Items.Add(new ListItem(Localization.GetString("Html", Localization.GetResourceFile(this, MyFileName)), "H")); + this.OptRender.Items.Add(new ListItem(Localization.GetString("Raw", Localization.GetResourceFile(this, MyFileName)), "R")); } - if (OptView.Items.Count == 0) + + if (this.OptView.Items.Count == 0) { - OptView.Items.Add(new ListItem(Localization.GetString("BasicTextBox", Localization.GetResourceFile(this, MyFileName)), "BASIC")); - if (IsRichEditorAvailable) + this.OptView.Items.Add(new ListItem(Localization.GetString("BasicTextBox", Localization.GetResourceFile(this, MyFileName)), "BASIC")); + if (this.IsRichEditorAvailable) { - OptView.Items.Add(new ListItem(Localization.GetString("RichTextBox", Localization.GetResourceFile(this, MyFileName)), "RICH")); + this.OptView.Items.Add(new ListItem(Localization.GetString("RichTextBox", Localization.GetResourceFile(this, MyFileName)), "RICH")); } } } /// ----------------------------------------------------------------------------- /// - /// Sets the Mode displayed + /// Sets the Mode displayed. /// /// /// /// ----------------------------------------------------------------------------- private void SetPanels() { - if (OptView.SelectedIndex != -1) + if (this.OptView.SelectedIndex != -1) { - Mode = OptView.SelectedItem.Value; + this.Mode = this.OptView.SelectedItem.Value; } - if (!String.IsNullOrEmpty(Mode)) + + if (!string.IsNullOrEmpty(this.Mode)) { - OptView.Items.FindByValue(Mode).Selected = true; + this.OptView.Items.FindByValue(this.Mode).Selected = true; } else { - OptView.SelectedIndex = 0; + this.OptView.SelectedIndex = 0; } - - //Set the text render mode for basic mode - if (OptRender.SelectedIndex != -1) + + // Set the text render mode for basic mode + if (this.OptRender.SelectedIndex != -1) { - TextRenderMode = OptRender.SelectedItem.Value; + this.TextRenderMode = this.OptRender.SelectedItem.Value; } - if (!String.IsNullOrEmpty(TextRenderMode)) + + if (!string.IsNullOrEmpty(this.TextRenderMode)) { - OptRender.Items.FindByValue(TextRenderMode).Selected = true; + this.OptRender.Items.FindByValue(this.TextRenderMode).Selected = true; } else { - OptRender.SelectedIndex = 0; + this.OptRender.SelectedIndex = 0; } - if (OptView.SelectedItem.Value == "BASIC") + + if (this.OptView.SelectedItem.Value == "BASIC") { - DivBasicTextBox.Visible = true; - DivRichTextBox.Visible = false; - PanelView.CssClass = "dnnTextPanelView dnnTextPanelView-basic"; + this.DivBasicTextBox.Visible = true; + this.DivRichTextBox.Visible = false; + this.PanelView.CssClass = "dnnTextPanelView dnnTextPanelView-basic"; } else { - DivBasicTextBox.Visible = false; - DivRichTextBox.Visible = true; - PanelView.CssClass = "dnnTextPanelView"; + this.DivBasicTextBox.Visible = false; + this.DivRichTextBox.Visible = true; + this.PanelView.CssClass = "dnnTextPanelView"; } } - - private static string RemoveBaseTags(String strInput) - { - return Globals.BaseTagRegex.Replace(strInput, " "); - } - #endregion - - #region Public Methods - - public void ChangeMode(string mode) - { - OptView.SelectedItem.Value = mode; - OptViewSelectedIndexChanged(OptView, EventArgs.Empty); - } - public void ChangeTextRenderMode(string textRenderMode) - { - OptRender.SelectedItem.Value = textRenderMode; - OptRenderSelectedIndexChanged(OptRender, EventArgs.Empty); - } - - #endregion - - #region Event Handlers - + protected override void OnInit(EventArgs e) { base.OnInit(e); - _richTextEditor = HtmlEditorProvider.Instance(); + this._richTextEditor = HtmlEditorProvider.Instance(); - if (IsRichEditorAvailable) + if (this.IsRichEditorAvailable) { - _richTextEditor.ControlID = ID; - _richTextEditor.Initialize(); + this._richTextEditor.ControlID = this.ID; + this._richTextEditor.Initialize(); } } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -404,48 +399,49 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - OptRender.SelectedIndexChanged += OptRenderSelectedIndexChanged; - OptView.SelectedIndexChanged += OptViewSelectedIndexChanged; - + this.OptRender.SelectedIndexChanged += this.OptRenderSelectedIndexChanged; + this.OptView.SelectedIndexChanged += this.OptViewSelectedIndexChanged; + try { - //Populate Radio Button Lists - PopulateLists(); + // Populate Radio Button Lists + this.PopulateLists(); - //Get the current user - //UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + // Get the current user + // UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - //Set the width and height of the controls - if (IsRichEditorAvailable) + // Set the width and height of the controls + if (this.IsRichEditorAvailable) { - _richTextEditor.Width = Width; - _richTextEditor.Height = Height; + this._richTextEditor.Width = this.Width; + this._richTextEditor.Height = this.Height; } - TxtDesktopHTML.Height = Height; - TxtDesktopHTML.Width = Width; - PanelView.Width = Width; - PanelTextEditor.Width = Width; + this.TxtDesktopHTML.Height = this.Height; + this.TxtDesktopHTML.Width = this.Width; + this.PanelView.Width = this.Width; + this.PanelTextEditor.Width = this.Width; - //Optionally display the radio button lists - if (!ChooseMode) + // Optionally display the radio button lists + if (!this.ChooseMode) { - PanelView.Visible = false; + this.PanelView.Visible = false; } - if (!ChooseRender) + + if (!this.ChooseRender) { - DivBasicRender.Visible = false; + this.DivBasicRender.Visible = false; } - //Load the editor - if (IsRichEditorAvailable) + // Load the editor + if (this.IsRichEditorAvailable) { - PlcEditor.Controls.Add(_richTextEditor.HtmlEditorControl); + this.PlcEditor.Controls.Add(this._richTextEditor.HtmlEditorControl); } - SetPanels(); + this.SetPanels(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -453,65 +449,66 @@ protected override void OnLoad(EventArgs e) /// ----------------------------------------------------------------------------- /// - /// optRender_SelectedIndexChanged runs when Basic Text Box mode is changed + /// optRender_SelectedIndexChanged runs when Basic Text Box mode is changed. /// /// /// /// ----------------------------------------------------------------------------- - protected void OptRenderSelectedIndexChanged(Object sender, EventArgs e) + protected void OptRenderSelectedIndexChanged(object sender, EventArgs e) { - if (OptRender.SelectedIndex != -1) + if (this.OptRender.SelectedIndex != -1) { - TextRenderMode = OptRender.SelectedItem.Value; + this.TextRenderMode = this.OptRender.SelectedItem.Value; } - if (Mode == "BASIC") + + if (this.Mode == "BASIC") { - TxtDesktopHTML.Text = TextRenderMode == "H" ? HtmlUtils.ConvertToHtml(TxtDesktopHTML.Text) : HtmlUtils.ConvertToText(TxtDesktopHTML.Text); + this.TxtDesktopHTML.Text = this.TextRenderMode == "H" ? HtmlUtils.ConvertToHtml(this.TxtDesktopHTML.Text) : HtmlUtils.ConvertToText(this.TxtDesktopHTML.Text); } - SetPanels(); + + this.SetPanels(); } /// ----------------------------------------------------------------------------- /// - /// optView_SelectedIndexChanged runs when Editor Mode is changed + /// optView_SelectedIndexChanged runs when Editor Mode is changed. /// /// /// /// ----------------------------------------------------------------------------- - protected void OptViewSelectedIndexChanged(Object sender, EventArgs e) + protected void OptViewSelectedIndexChanged(object sender, EventArgs e) { - if (OptView.SelectedIndex != -1) + if (this.OptView.SelectedIndex != -1) { - Mode = OptView.SelectedItem.Value; + this.Mode = this.OptView.SelectedItem.Value; } - if (Mode == "BASIC") + + if (this.Mode == "BASIC") { - switch (TextRenderMode) + switch (this.TextRenderMode) { case "T": - TxtDesktopHTML.Text = HtmlUtils.ConvertToText(_richTextEditor.Text); + this.TxtDesktopHTML.Text = HtmlUtils.ConvertToText(this._richTextEditor.Text); break; default: - TxtDesktopHTML.Text = _richTextEditor.Text; + this.TxtDesktopHTML.Text = this._richTextEditor.Text; break; } } else { - switch (TextRenderMode) + switch (this.TextRenderMode) { case "T": - _richTextEditor.Text = HtmlUtils.ConvertToHtml(TxtDesktopHTML.Text); + this._richTextEditor.Text = HtmlUtils.ConvertToHtml(this.TxtDesktopHTML.Text); break; default: - _richTextEditor.Text = TxtDesktopHTML.Text; + this._richTextEditor.Text = this.TxtDesktopHTML.Text; break; } } - SetPanels(); - } - - #endregion - + + this.SetPanels(); + } } } diff --git a/DNN Platform/Library/UI/UserControls/URLControl.cs b/DNN Platform/Library/UI/UserControls/URLControl.cs index 3ddd1bbd7d3..d7b7194f64d 100644 --- a/DNN Platform/Library/UI/UserControls/URLControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLControl.cs @@ -1,41 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Text.RegularExpressions; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Collections; + using System.IO; + using System.Text.RegularExpressions; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + using Globals = DotNetNuke.Common.Globals; + public abstract class UrlControl : UserControlBase { - #region "Private Members" - protected Panel ErrorRow; protected Panel FileRow; protected Panel ImagesRow; @@ -43,6 +36,8 @@ public abstract class UrlControl : UserControlBase protected Panel TypeRow; protected Panel URLRow; protected Panel UserRow; + protected DropDownList cboFiles; + protected DropDownList cboFolders; private bool _doChangeURL; private bool _doReloadFiles; private bool _doReloadFolders; @@ -50,8 +45,6 @@ public abstract class UrlControl : UserControlBase private bool _doRenderTypes; private string _localResourceFile; private PortalInfo _objPortal; - protected DropDownList cboFiles; - protected DropDownList cboFolders; protected DropDownList cboImages; protected DropDownList cboTabs; protected DropDownList cboUrls; @@ -78,29 +71,26 @@ public abstract class UrlControl : UserControlBase protected TextBox txtUrl; protected TextBox txtUser; - #endregion - - #region "Public Properties" - public string FileFilter { get { - if (ViewState["FileFilter"] != null) + if (this.ViewState["FileFilter"] != null) { - return Convert.ToString(ViewState["FileFilter"]); + return Convert.ToString(this.ViewState["FileFilter"]); } else { - return ""; + return string.Empty; } } + set { - ViewState["FileFilter"] = value; - if (IsTrackingViewState) + this.ViewState["FileFilter"] = value; + if (this.IsTrackingViewState) { - _doReloadFiles = true; + this._doReloadFiles = true; } } } @@ -109,21 +99,22 @@ public bool IncludeActiveTab { get { - if (ViewState["IncludeActiveTab"] != null) + if (this.ViewState["IncludeActiveTab"] != null) { - return Convert.ToBoolean(ViewState["IncludeActiveTab"]); + return Convert.ToBoolean(this.ViewState["IncludeActiveTab"]); } else { - return false; //Set as default + return false; // Set as default } } + set { - ViewState["IncludeActiveTab"] = value; - if (IsTrackingViewState) + this.ViewState["IncludeActiveTab"] = value; + if (this.IsTrackingViewState) { - _doRenderTypeControls = true; + this._doRenderTypeControls = true; } } } @@ -133,19 +124,21 @@ public string LocalResourceFile get { string fileRoot; - if (String.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/URLControl.ascx"; + fileRoot = this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/URLControl.ascx"; } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } } @@ -153,9 +146,9 @@ public bool Log { get { - if (chkLog.Visible) + if (this.chkLog.Visible) { - return chkLog.Checked; + return this.chkLog.Checked; } else { @@ -169,19 +162,21 @@ public int ModuleID get { int myMid = -2; - if (ViewState["ModuleId"] != null) + if (this.ViewState["ModuleId"] != null) { - myMid = Convert.ToInt32(ViewState["ModuleId"]); + myMid = Convert.ToInt32(this.ViewState["ModuleId"]); } - else if (Request.QueryString["mid"] != null) + else if (this.Request.QueryString["mid"] != null) { - Int32.TryParse(Request.QueryString["mid"], out myMid); + int.TryParse(this.Request.QueryString["mid"], out myMid); } + return myMid; } + set { - ViewState["ModuleId"] = value; + this.ViewState["ModuleId"] = value; } } @@ -189,11 +184,12 @@ public bool NewWindow { get { - return chkNewWindow.Visible && chkNewWindow.Checked; + return this.chkNewWindow.Visible && this.chkNewWindow.Checked; } + set { - chkNewWindow.Checked = chkNewWindow.Visible && value; + this.chkNewWindow.Checked = this.chkNewWindow.Visible && value; } } @@ -201,21 +197,22 @@ public bool Required { get { - if (ViewState["Required"] != null) + if (this.ViewState["Required"] != null) { - return Convert.ToBoolean(ViewState["Required"]); + return Convert.ToBoolean(this.ViewState["Required"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["Required"] = value; - if (IsTrackingViewState) + this.ViewState["Required"] = value; + if (this.IsTrackingViewState) { - _doRenderTypeControls = true; + this._doRenderTypeControls = true; } } } @@ -224,21 +221,22 @@ public bool ShowFiles { get { - if (ViewState["ShowFiles"] != null) + if (this.ViewState["ShowFiles"] != null) { - return Convert.ToBoolean(ViewState["ShowFiles"]); + return Convert.ToBoolean(this.ViewState["ShowFiles"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowFiles"] = value; - if (IsTrackingViewState) + this.ViewState["ShowFiles"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -247,21 +245,22 @@ public bool ShowImages { get { - if (ViewState["ShowImages"] != null) + if (this.ViewState["ShowImages"] != null) { - return Convert.ToBoolean(ViewState["ShowImages"]); + return Convert.ToBoolean(this.ViewState["ShowImages"]); } else { return false; } } + set { - ViewState["ShowImages"] = value; - if (IsTrackingViewState) + this.ViewState["ShowImages"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -270,11 +269,12 @@ public bool ShowLog { get { - return chkLog.Visible; + return this.chkLog.Visible; } + set { - chkLog.Visible = value; + this.chkLog.Visible = value; } } @@ -282,11 +282,12 @@ public bool ShowNewWindow { get { - return chkNewWindow.Visible; + return this.chkNewWindow.Visible; } + set { - chkNewWindow.Visible = value; + this.chkNewWindow.Visible = value; } } @@ -294,21 +295,22 @@ public bool ShowNone { get { - if (ViewState["ShowNone"] != null) + if (this.ViewState["ShowNone"] != null) { - return Convert.ToBoolean(ViewState["ShowNone"]); + return Convert.ToBoolean(this.ViewState["ShowNone"]); } else { - return false; //Set as default in the old variable + return false; // Set as default in the old variable } } + set { - ViewState["ShowNone"] = value; - if (IsTrackingViewState) + this.ViewState["ShowNone"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -317,21 +319,22 @@ public bool ShowTabs { get { - if (ViewState["ShowTabs"] != null) + if (this.ViewState["ShowTabs"] != null) { - return Convert.ToBoolean(ViewState["ShowTabs"]); + return Convert.ToBoolean(this.ViewState["ShowTabs"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowTabs"] = value; - if (IsTrackingViewState) + this.ViewState["ShowTabs"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -340,11 +343,12 @@ public bool ShowTrack { get { - return chkTrack.Visible; + return this.chkTrack.Visible; } + set { - chkTrack.Visible = value; + this.chkTrack.Visible = value; } } @@ -352,21 +356,22 @@ public bool ShowUpLoad { get { - if (ViewState["ShowUpLoad"] != null) + if (this.ViewState["ShowUpLoad"] != null) { - return Convert.ToBoolean(ViewState["ShowUpLoad"]); + return Convert.ToBoolean(this.ViewState["ShowUpLoad"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowUpLoad"] = value; - if (IsTrackingViewState) + this.ViewState["ShowUpLoad"] = value; + if (this.IsTrackingViewState) { - _doRenderTypeControls = true; + this._doRenderTypeControls = true; } } } @@ -375,21 +380,22 @@ public bool ShowUrls { get { - if (ViewState["ShowUrls"] != null) + if (this.ViewState["ShowUrls"] != null) { - return Convert.ToBoolean(ViewState["ShowUrls"]); + return Convert.ToBoolean(this.ViewState["ShowUrls"]); } else { - return true; //Set as default in the old variable + return true; // Set as default in the old variable } } + set { - ViewState["ShowUrls"] = value; - if (IsTrackingViewState) + this.ViewState["ShowUrls"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -398,21 +404,22 @@ public bool ShowUsers { get { - if (ViewState["ShowUsers"] != null) + if (this.ViewState["ShowUsers"] != null) { - return Convert.ToBoolean(ViewState["ShowUsers"]); + return Convert.ToBoolean(this.ViewState["ShowUsers"]); } else { - return false; //Set as default in the old variable + return false; // Set as default in the old variable } } + set { - ViewState["ShowUsers"] = value; - if (IsTrackingViewState) + this.ViewState["ShowUsers"] = value; + if (this.IsTrackingViewState) { - _doRenderTypes = true; + this._doRenderTypes = true; } } } @@ -421,9 +428,9 @@ public bool Track { get { - if (chkTrack.Visible) + if (this.chkTrack.Visible) { - return chkTrack.Checked; + return this.chkTrack.Checked; } else { @@ -436,94 +443,102 @@ public string Url { get { - string r = ""; - string strCurrentType = ""; - if (optType.Items.Count > 0 && optType.SelectedIndex >= 0) + string r = string.Empty; + string strCurrentType = string.Empty; + if (this.optType.Items.Count > 0 && this.optType.SelectedIndex >= 0) { - strCurrentType = optType.SelectedItem.Value; + strCurrentType = this.optType.SelectedItem.Value; } + switch (strCurrentType) { case "I": - if (cboImages.SelectedItem != null) + if (this.cboImages.SelectedItem != null) { - r = cboImages.SelectedItem.Value; + r = this.cboImages.SelectedItem.Value; } + break; case "U": - if (cboUrls.Visible) + if (this.cboUrls.Visible) { - if (cboUrls.SelectedItem != null) + if (this.cboUrls.SelectedItem != null) { - r = cboUrls.SelectedItem.Value; - txtUrl.Text = r; + r = this.cboUrls.SelectedItem.Value; + this.txtUrl.Text = r; } } else { - string mCustomUrl = txtUrl.Text; + string mCustomUrl = this.txtUrl.Text; if (mCustomUrl.Equals("http://", StringComparison.InvariantCultureIgnoreCase)) { - r = ""; + r = string.Empty; } else { r = Globals.AddHTTP(mCustomUrl); } } + break; case "T": - string strTab = ""; - if (cboTabs.SelectedItem != null) + string strTab = string.Empty; + if (this.cboTabs.SelectedItem != null) { - strTab = cboTabs.SelectedItem.Value; + strTab = this.cboTabs.SelectedItem.Value; if (Globals.NumberMatchRegex.IsMatch(strTab) && (Convert.ToInt32(strTab) >= 0)) { r = strTab; } } + break; case "F": - if (cboFiles.SelectedItem != null) + if (this.cboFiles.SelectedItem != null) { - if (!String.IsNullOrEmpty(cboFiles.SelectedItem.Value)) + if (!string.IsNullOrEmpty(this.cboFiles.SelectedItem.Value)) { - r = "FileID=" + cboFiles.SelectedItem.Value; + r = "FileID=" + this.cboFiles.SelectedItem.Value; } else { - r = ""; + r = string.Empty; } } + break; case "M": - if (!String.IsNullOrEmpty(txtUser.Text)) + if (!string.IsNullOrEmpty(this.txtUser.Text)) { - UserInfo objUser = UserController.GetCachedUser(_objPortal.PortalID, txtUser.Text); + UserInfo objUser = UserController.GetCachedUser(this._objPortal.PortalID, this.txtUser.Text); if (objUser != null) { r = "UserID=" + objUser.UserID; } else { - lblMessage.Text = Localization.GetString("NoUser", LocalResourceFile); - ErrorRow.Visible = true; - txtUser.Text = ""; + this.lblMessage.Text = Localization.GetString("NoUser", this.LocalResourceFile); + this.ErrorRow.Visible = true; + this.txtUser.Text = string.Empty; } } + break; } + return r; } + set { - ViewState["Url"] = value; - txtUrl.Text = string.Empty; + this.ViewState["Url"] = value; + this.txtUrl.Text = string.Empty; - if (IsTrackingViewState) + if (this.IsTrackingViewState) { - _doChangeURL = true; - _doReloadFiles = true; + this._doChangeURL = true; + this._doReloadFiles = true; } } } @@ -532,16 +547,17 @@ public string UrlType { get { - return Convert.ToString(ViewState["UrlType"]); + return Convert.ToString(this.ViewState["UrlType"]); } + set { - if (value != null && !String.IsNullOrEmpty(value.Trim())) + if (value != null && !string.IsNullOrEmpty(value.Trim())) { - ViewState["UrlType"] = value; - if (IsTrackingViewState) + this.ViewState["UrlType"] = value; + if (this.IsTrackingViewState) { - _doChangeURL = true; + this._doChangeURL = true; } } } @@ -551,113 +567,174 @@ public string Width { get { - return Convert.ToString(ViewState["SkinControlWidth"]); + return Convert.ToString(this.ViewState["SkinControlWidth"]); } + set { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { - cboUrls.Width = Unit.Parse(value); - txtUrl.Width = Unit.Parse(value); - cboImages.Width = Unit.Parse(value); - cboTabs.Width = Unit.Parse(value); - cboFolders.Width = Unit.Parse(value); - cboFiles.Width = Unit.Parse(value); - txtUser.Width = Unit.Parse(value); - ViewState["SkinControlWidth"] = value; + this.cboUrls.Width = Unit.Parse(value); + this.txtUrl.Width = Unit.Parse(value); + this.cboImages.Width = Unit.Parse(value); + this.cboTabs.Width = Unit.Parse(value); + this.cboFolders.Width = Unit.Parse(value); + this.cboFiles.Width = Unit.Parse(value); + this.txtUser.Width = Unit.Parse(value); + this.ViewState["SkinControlWidth"] = value; } } } - #endregion + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + AJAX.RegisterPostBackControl(this.FindControl("cmdSave")); + + // prevent unauthorized access + if (this.Request.IsAuthenticated == false) + { + this.Visible = false; + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboFolders.SelectedIndexChanged += this.cboFolders_SelectedIndexChanged; + this.optType.SelectedIndexChanged += this.optType_SelectedIndexChanged; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdSave.Click += this.cmdSave_Click; + this.cmdSelect.Click += this.cmdSelect_Click; + this.cmdUpload.Click += this.cmdUpload_Click; + + this.ErrorRow.Visible = false; + + try + { + if ((this.Request.QueryString["pid"] != null) && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + { + this._objPortal = PortalController.Instance.GetPortal(int.Parse(this.Request.QueryString["pid"])); + } + else + { + this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); + } + + if (this.ViewState["IsUrlControlLoaded"] == null) + { + // If Not Page.IsPostBack Then + // let's make at least an initialization + // The type radio button must be initialized + // The url must be initialized no matter its value + this._doRenderTypes = true; + this._doChangeURL = true; + ClientAPI.AddButtonConfirm(this.cmdDelete, Localization.GetString("DeleteItem")); - #region "Private Methods" + // The following line was mover to the pre-render event to ensure render for the first time + // ViewState("IsUrlControlLoaded") = "Loaded" + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } private ArrayList GetFileList(bool NoneSpecified) { int PortalId = Null.NullInteger; - if ((!IsHostMenu) || (Request.QueryString["pid"] != null)) + if ((!this.IsHostMenu) || (this.Request.QueryString["pid"] != null)) { - PortalId = _objPortal.PortalID; + PortalId = this._objPortal.PortalID; } - return Globals.GetFileList(PortalId, FileFilter, NoneSpecified, cboFolders.SelectedItem.Value, false); + + return Globals.GetFileList(PortalId, this.FileFilter, NoneSpecified, this.cboFolders.SelectedItem.Value, false); } private void LoadFolders(string Permissions) { int PortalId = Null.NullInteger; - cboFolders.Items.Clear(); + this.cboFolders.Items.Clear(); - if ((!IsHostMenu) || (Request.QueryString["pid"] != null)) + if ((!this.IsHostMenu) || (this.Request.QueryString["pid"] != null)) { - PortalId = _objPortal.PortalID; + PortalId = this._objPortal.PortalID; } + var folders = FolderManager.Instance.GetFolders(UserController.Instance.GetCurrentUserInfo(), Permissions); foreach (FolderInfo folder in folders) { var FolderItem = new ListItem(); if (folder.FolderPath == Null.NullString) { - FolderItem.Text = Localization.GetString("Root", LocalResourceFile); + FolderItem.Text = Localization.GetString("Root", this.LocalResourceFile); } else { FolderItem.Text = folder.DisplayPath; } + FolderItem.Value = folder.FolderPath; - cboFolders.Items.Add(FolderItem); + this.cboFolders.Items.Add(FolderItem); } } private void LoadUrls() { var objUrls = new UrlController(); - cboUrls.Items.Clear(); - cboUrls.DataSource = objUrls.GetUrls(_objPortal.PortalID); - cboUrls.DataBind(); + this.cboUrls.Items.Clear(); + this.cboUrls.DataSource = objUrls.GetUrls(this._objPortal.PortalID); + this.cboUrls.DataBind(); } private void SetStorageLocationType() { - string FolderName = cboFolders.SelectedValue; + string FolderName = this.cboFolders.SelectedValue; - //Check to see if this is the 'Root' folder, if so we cannot rely on its text value because it is something and not an empty string that we need to lookup the 'root' folder - if (cboFolders.SelectedValue == string.Empty) + // Check to see if this is the 'Root' folder, if so we cannot rely on its text value because it is something and not an empty string that we need to lookup the 'root' folder + if (this.cboFolders.SelectedValue == string.Empty) { - FolderName = ""; + FolderName = string.Empty; } - var objFolderInfo = FolderManager.Instance.GetFolder(PortalSettings.PortalId, FolderName); + + var objFolderInfo = FolderManager.Instance.GetFolder(this.PortalSettings.PortalId, FolderName); if (objFolderInfo != null) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(objFolderInfo.PortalID, objFolderInfo.FolderMappingID); if (folderMapping.MappingName == "Standard") { - imgStorageLocationType.Visible = false; + this.imgStorageLocationType.Visible = false; } else { - imgStorageLocationType.Visible = true; - imgStorageLocationType.ImageUrl = FolderProvider.Instance(folderMapping.FolderProviderType).GetFolderProviderIconPath(); + this.imgStorageLocationType.Visible = true; + this.imgStorageLocationType.ImageUrl = FolderProvider.Instance(folderMapping.FolderProviderType).GetFolderProviderIconPath(); } } } private void DoChangeURL() { - string _Url = Convert.ToString(ViewState["Url"]); - string _Urltype = Convert.ToString(ViewState["UrlType"]); - if (!String.IsNullOrEmpty(_Url)) + string _Url = Convert.ToString(this.ViewState["Url"]); + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); + if (!string.IsNullOrEmpty(_Url)) { var objUrls = new UrlController(); string TrackingUrl = _Url; _Urltype = Globals.GetURLType(_Url).ToString("g").Substring(0, 1); - if (_Urltype == "U" && (_Url.StartsWith("~/" + PortalSettings.DefaultIconLocation, StringComparison.InvariantCultureIgnoreCase))) + if (_Urltype == "U" && _Url.StartsWith("~/" + this.PortalSettings.DefaultIconLocation, StringComparison.InvariantCultureIgnoreCase)) { _Urltype = "I"; } - ViewState["UrlType"] = _Urltype; + + this.ViewState["UrlType"] = _Urltype; if (_Urltype == "F") { if (_Url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) @@ -671,10 +748,10 @@ private void DoChangeURL() } else { - //to handle legacy scenarios before the introduction of the FileServerHandler + // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(_Url); var folderPath = _Url.Substring(0, _Url.LastIndexOf(fileName)); - var folder = FolderManager.Instance.GetFolder(_objPortal.PortalID, folderPath); + var folder = FolderManager.Instance.GetFolder(this._objPortal.PortalID, folderPath); var fileId = -1; if (folder != null) { @@ -684,498 +761,465 @@ private void DoChangeURL() fileId = file.FileId; } } + TrackingUrl = "FileID=" + fileId.ToString(); } } + if (_Urltype == "M") { if (_Url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) { - UserInfo objUser = UserController.GetUserById(_objPortal.PortalID, int.Parse(_Url.Substring(7))); + UserInfo objUser = UserController.GetUserById(this._objPortal.PortalID, int.Parse(_Url.Substring(7))); if (objUser != null) { _Url = objUser.Username; } } } - UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(_objPortal.PortalID, TrackingUrl, ModuleID); + + UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this._objPortal.PortalID, TrackingUrl, this.ModuleID); if (objUrlTracking != null) { - chkNewWindow.Checked = objUrlTracking.NewWindow; - chkTrack.Checked = objUrlTracking.TrackClicks; - chkLog.Checked = objUrlTracking.LogActivity; + this.chkNewWindow.Checked = objUrlTracking.NewWindow; + this.chkTrack.Checked = objUrlTracking.TrackClicks; + this.chkLog.Checked = objUrlTracking.LogActivity; } - else //the url does not exist in the tracking table + else // the url does not exist in the tracking table { - chkTrack.Checked = false; - chkLog.Checked = false; + this.chkTrack.Checked = false; + this.chkLog.Checked = false; } - ViewState["Url"] = _Url; + + this.ViewState["Url"] = _Url; } else { - if (!String.IsNullOrEmpty(_Urltype)) + if (!string.IsNullOrEmpty(_Urltype)) { - optType.ClearSelection(); - if (optType.Items.FindByValue(_Urltype) != null) + this.optType.ClearSelection(); + if (this.optType.Items.FindByValue(_Urltype) != null) { - optType.Items.FindByValue(_Urltype).Selected = true; + this.optType.Items.FindByValue(_Urltype).Selected = true; } else { - optType.Items[0].Selected = true; + this.optType.Items[0].Selected = true; } } else { - if (optType.Items.Count > 0) + if (this.optType.Items.Count > 0) { - optType.ClearSelection(); - optType.Items[0].Selected = true; + this.optType.ClearSelection(); + this.optType.Items[0].Selected = true; } } - chkNewWindow.Checked = false; //Need check - chkTrack.Checked = false; //Need check - chkLog.Checked = false; //Need check + + this.chkNewWindow.Checked = false; // Need check + this.chkTrack.Checked = false; // Need check + this.chkLog.Checked = false; // Need check } - //Url type changed, then we must draw the controlos for that type - _doRenderTypeControls = true; + // Url type changed, then we must draw the controlos for that type + this._doRenderTypeControls = true; } private void DoRenderTypes() { - //We must clear the list to keep the same item order - string strCurrent = ""; - if (optType.SelectedIndex >= 0) + // We must clear the list to keep the same item order + string strCurrent = string.Empty; + if (this.optType.SelectedIndex >= 0) { - strCurrent = optType.SelectedItem.Value; //Save current selected value + strCurrent = this.optType.SelectedItem.Value; // Save current selected value } - optType.Items.Clear(); - if (ShowNone) + + this.optType.Items.Clear(); + if (this.ShowNone) { - if (optType.Items.FindByValue("N") == null) + if (this.optType.Items.FindByValue("N") == null) { - optType.Items.Add(new ListItem(Localization.GetString("NoneType", LocalResourceFile), "N")); + this.optType.Items.Add(new ListItem(Localization.GetString("NoneType", this.LocalResourceFile), "N")); } } else { - if (optType.Items.FindByValue("N") != null) + if (this.optType.Items.FindByValue("N") != null) { - optType.Items.Remove(optType.Items.FindByValue("N")); + this.optType.Items.Remove(this.optType.Items.FindByValue("N")); } } - if (ShowUrls) + + if (this.ShowUrls) { - if (optType.Items.FindByValue("U") == null) + if (this.optType.Items.FindByValue("U") == null) { - optType.Items.Add(new ListItem(Localization.GetString("URLType", LocalResourceFile), "U")); + this.optType.Items.Add(new ListItem(Localization.GetString("URLType", this.LocalResourceFile), "U")); } } else { - if (optType.Items.FindByValue("U") != null) + if (this.optType.Items.FindByValue("U") != null) { - optType.Items.Remove(optType.Items.FindByValue("U")); + this.optType.Items.Remove(this.optType.Items.FindByValue("U")); } } - if (ShowTabs) + + if (this.ShowTabs) { - if (optType.Items.FindByValue("T") == null) + if (this.optType.Items.FindByValue("T") == null) { - optType.Items.Add(new ListItem(Localization.GetString("TabType", LocalResourceFile), "T")); + this.optType.Items.Add(new ListItem(Localization.GetString("TabType", this.LocalResourceFile), "T")); } } else { - if (optType.Items.FindByValue("T") != null) + if (this.optType.Items.FindByValue("T") != null) { - optType.Items.Remove(optType.Items.FindByValue("T")); + this.optType.Items.Remove(this.optType.Items.FindByValue("T")); } } - if (ShowFiles) + + if (this.ShowFiles) { - if (optType.Items.FindByValue("F") == null) + if (this.optType.Items.FindByValue("F") == null) { - optType.Items.Add(new ListItem(Localization.GetString("FileType", LocalResourceFile), "F")); + this.optType.Items.Add(new ListItem(Localization.GetString("FileType", this.LocalResourceFile), "F")); } } else { - if (optType.Items.FindByValue("F") != null) + if (this.optType.Items.FindByValue("F") != null) { - optType.Items.Remove(optType.Items.FindByValue("F")); + this.optType.Items.Remove(this.optType.Items.FindByValue("F")); } } - if (ShowImages) + + if (this.ShowImages) { - if (optType.Items.FindByValue("I") == null) + if (this.optType.Items.FindByValue("I") == null) { - optType.Items.Add(new ListItem(Localization.GetString("ImageType", LocalResourceFile), "I")); + this.optType.Items.Add(new ListItem(Localization.GetString("ImageType", this.LocalResourceFile), "I")); } } else { - if (optType.Items.FindByValue("I") != null) + if (this.optType.Items.FindByValue("I") != null) { - optType.Items.Remove(optType.Items.FindByValue("I")); + this.optType.Items.Remove(this.optType.Items.FindByValue("I")); } } - if (ShowUsers) + + if (this.ShowUsers) { - if (optType.Items.FindByValue("M") == null) + if (this.optType.Items.FindByValue("M") == null) { - optType.Items.Add(new ListItem(Localization.GetString("UserType", LocalResourceFile), "M")); + this.optType.Items.Add(new ListItem(Localization.GetString("UserType", this.LocalResourceFile), "M")); } } else { - if (optType.Items.FindByValue("M") != null) + if (this.optType.Items.FindByValue("M") != null) { - optType.Items.Remove(optType.Items.FindByValue("M")); + this.optType.Items.Remove(this.optType.Items.FindByValue("M")); } } - if (optType.Items.Count > 0) + + if (this.optType.Items.Count > 0) { - if (!String.IsNullOrEmpty(strCurrent)) + if (!string.IsNullOrEmpty(strCurrent)) { - if (optType.Items.FindByValue(strCurrent) != null) + if (this.optType.Items.FindByValue(strCurrent) != null) { - optType.Items.FindByValue(strCurrent).Selected = true; + this.optType.Items.FindByValue(strCurrent).Selected = true; } else { - optType.Items[0].Selected = true; - _doRenderTypeControls = true; //Type changed, re-draw + this.optType.Items[0].Selected = true; + this._doRenderTypeControls = true; // Type changed, re-draw } } else { - optType.Items[0].Selected = true; - _doRenderTypeControls = true; //Type changed, re-draw + this.optType.Items[0].Selected = true; + this._doRenderTypeControls = true; // Type changed, re-draw } - TypeRow.Visible = optType.Items.Count > 1; + + this.TypeRow.Visible = this.optType.Items.Count > 1; } else { - TypeRow.Visible = false; + this.TypeRow.Visible = false; } } private void DoCorrectRadioButtonList() { - string _Urltype = Convert.ToString(ViewState["UrlType"]); + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); - if (optType.Items.Count > 0) + if (this.optType.Items.Count > 0) { - optType.ClearSelection(); - if (!String.IsNullOrEmpty(_Urltype)) + this.optType.ClearSelection(); + if (!string.IsNullOrEmpty(_Urltype)) { - if (optType.Items.FindByValue(_Urltype) != null) + if (this.optType.Items.FindByValue(_Urltype) != null) { - optType.Items.FindByValue(_Urltype).Selected = true; + this.optType.Items.FindByValue(_Urltype).Selected = true; } else { - optType.Items[0].Selected = true; - _Urltype = optType.Items[0].Value; - ViewState["UrlType"] = _Urltype; + this.optType.Items[0].Selected = true; + _Urltype = this.optType.Items[0].Value; + this.ViewState["UrlType"] = _Urltype; } } else { - optType.Items[0].Selected = true; - _Urltype = optType.Items[0].Value; - ViewState["UrlType"] = _Urltype; + this.optType.Items[0].Selected = true; + _Urltype = this.optType.Items[0].Value; + this.ViewState["UrlType"] = _Urltype; } } } private void DoRenderTypeControls() { - string _Url = Convert.ToString(ViewState["Url"]); - string _Urltype = Convert.ToString(ViewState["UrlType"]); + string _Url = Convert.ToString(this.ViewState["Url"]); + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); var objUrls = new UrlController(); - if (!String.IsNullOrEmpty(_Urltype)) + if (!string.IsNullOrEmpty(_Urltype)) { - //load listitems - switch (optType.SelectedItem.Value) + // load listitems + switch (this.optType.SelectedItem.Value) { - case "N": //None - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = false; + case "N": // None + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; break; - case "I": //System Image - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = true; + case "I": // System Image + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = true; - cboImages.Items.Clear(); + this.cboImages.Items.Clear(); - string strImagesFolder = Path.Combine(Globals.ApplicationMapPath, PortalSettings.DefaultIconLocation.Replace('/', '\\')); + string strImagesFolder = Path.Combine(Globals.ApplicationMapPath, this.PortalSettings.DefaultIconLocation.Replace('/', '\\')); foreach (string strImage in Directory.GetFiles(strImagesFolder)) { - string img = strImage.Replace(strImagesFolder, "").Trim('/').Trim('\\'); - cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", PortalSettings.DefaultIconLocation, img).ToLowerInvariant())); + string img = strImage.Replace(strImagesFolder, string.Empty).Trim('/').Trim('\\'); + this.cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", this.PortalSettings.DefaultIconLocation, img).ToLowerInvariant())); } - ListItem selecteItem = cboImages.Items.FindByValue(_Url.ToLowerInvariant()); + ListItem selecteItem = this.cboImages.Items.FindByValue(_Url.ToLowerInvariant()); if (selecteItem != null) { selecteItem.Selected = true; } + break; - case "U": //Url - URLRow.Visible = true; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = false; - if (String.IsNullOrEmpty(txtUrl.Text)) + case "U": // Url + this.URLRow.Visible = true; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + if (string.IsNullOrEmpty(this.txtUrl.Text)) { - txtUrl.Text = _Url; + this.txtUrl.Text = _Url; } - if (String.IsNullOrEmpty(txtUrl.Text)) + + if (string.IsNullOrEmpty(this.txtUrl.Text)) { - txtUrl.Text = "http://"; + this.txtUrl.Text = "http://"; } - txtUrl.Visible = true; - cmdSelect.Visible = true; + this.txtUrl.Visible = true; - cboUrls.Visible = false; - cmdAdd.Visible = false; - cmdDelete.Visible = false; + this.cmdSelect.Visible = true; + + this.cboUrls.Visible = false; + this.cmdAdd.Visible = false; + this.cmdDelete.Visible = false; break; - case "T": //tab - URLRow.Visible = false; - TabRow.Visible = true; - FileRow.Visible = false; - UserRow.Visible = false; - ImagesRow.Visible = false; + case "T": // tab + this.URLRow.Visible = false; + this.TabRow.Visible = true; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; - cboTabs.Items.Clear(); + this.cboTabs.Items.Clear(); PortalSettings _settings = PortalController.Instance.GetCurrentPortalSettings(); - cboTabs.DataSource = TabController.GetPortalTabs(_settings.PortalId, Null.NullInteger, !Required, "none available", true, false, false, true, false); - cboTabs.DataBind(); - if (cboTabs.Items.FindByValue(_Url) != null) + this.cboTabs.DataSource = TabController.GetPortalTabs(_settings.PortalId, Null.NullInteger, !this.Required, "none available", true, false, false, true, false); + this.cboTabs.DataBind(); + if (this.cboTabs.Items.FindByValue(_Url) != null) { - cboTabs.Items.FindByValue(_Url).Selected = true; + this.cboTabs.Items.FindByValue(_Url).Selected = true; } - if (!IncludeActiveTab && cboTabs.Items.FindByValue(_settings.ActiveTab.TabID.ToString()) != null) + if (!this.IncludeActiveTab && this.cboTabs.Items.FindByValue(_settings.ActiveTab.TabID.ToString()) != null) { - cboTabs.Items.FindByValue(_settings.ActiveTab.TabID.ToString()).Attributes.Add("disabled", "disabled"); + this.cboTabs.Items.FindByValue(_settings.ActiveTab.TabID.ToString()).Attributes.Add("disabled", "disabled"); } + break; - case "F": //file - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = true; - UserRow.Visible = false; - ImagesRow.Visible = false; - - if (ViewState["FoldersLoaded"] == null || _doReloadFolders) + case "F": // file + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = true; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + + if (this.ViewState["FoldersLoaded"] == null || this._doReloadFolders) { - LoadFolders("BROWSE,ADD"); - ViewState["FoldersLoaded"] = "Y"; + this.LoadFolders("BROWSE,ADD"); + this.ViewState["FoldersLoaded"] = "Y"; } - if (cboFolders.Items.Count == 0) + + if (this.cboFolders.Items.Count == 0) { - lblMessage.Text = Localization.GetString("NoPermission", LocalResourceFile); - ErrorRow.Visible = true; - FileRow.Visible = false; + this.lblMessage.Text = Localization.GetString("NoPermission", this.LocalResourceFile); + this.ErrorRow.Visible = true; + this.FileRow.Visible = false; return; } - //select folder - //We Must check if selected folder has changed because of a property change (Secure, Database) + // select folder + // We Must check if selected folder has changed because of a property change (Secure, Database) string FileName = string.Empty; string FolderPath = string.Empty; string LastFileName = string.Empty; string LastFolderPath = string.Empty; bool _MustRedrawFiles = false; - //Let's try to remember last selection - if (ViewState["LastFolderPath"] != null) + + // Let's try to remember last selection + if (this.ViewState["LastFolderPath"] != null) { - LastFolderPath = Convert.ToString(ViewState["LastFolderPath"]); + LastFolderPath = Convert.ToString(this.ViewState["LastFolderPath"]); } - if (ViewState["LastFileName"] != null) + + if (this.ViewState["LastFileName"] != null) { - LastFileName = Convert.ToString(ViewState["LastFileName"]); + LastFileName = Convert.ToString(this.ViewState["LastFileName"]); } + if (_Url != string.Empty) { - //Let's use the new URL + // Let's use the new URL FileName = _Url.Substring(_Url.LastIndexOf("/") + 1); - FolderPath = _Url.Replace(FileName, ""); + FolderPath = _Url.Replace(FileName, string.Empty); } else { - //Use last settings + // Use last settings FileName = LastFileName; FolderPath = LastFolderPath; } - if (cboFolders.Items.FindByValue(FolderPath) != null) + + if (this.cboFolders.Items.FindByValue(FolderPath) != null) { - cboFolders.ClearSelection(); - cboFolders.Items.FindByValue(FolderPath).Selected = true; + this.cboFolders.ClearSelection(); + this.cboFolders.Items.FindByValue(FolderPath).Selected = true; } - else if (cboFolders.Items.Count > 0) + else if (this.cboFolders.Items.Count > 0) { - cboFolders.ClearSelection(); - cboFolders.Items[0].Selected = true; - FolderPath = cboFolders.Items[0].Value; + this.cboFolders.ClearSelection(); + this.cboFolders.Items[0].Selected = true; + FolderPath = this.cboFolders.Items[0].Value; } - if (ViewState["FilesLoaded"] == null || FolderPath != LastFolderPath || _doReloadFiles) + + if (this.ViewState["FilesLoaded"] == null || FolderPath != LastFolderPath || this._doReloadFiles) { - //Reload files only if property change or not same folder + // Reload files only if property change or not same folder _MustRedrawFiles = true; - ViewState["FilesLoaded"] = "Y"; + this.ViewState["FilesLoaded"] = "Y"; } else { - if (cboFiles.Items.Count > 0) + if (this.cboFiles.Items.Count > 0) { - if ((Required && String.IsNullOrEmpty(cboFiles.Items[0].Value)) || (!Required && !String.IsNullOrEmpty(cboFiles.Items[0].Value))) + if ((this.Required && string.IsNullOrEmpty(this.cboFiles.Items[0].Value)) || (!this.Required && !string.IsNullOrEmpty(this.cboFiles.Items[0].Value))) { - //Required state has changed, so we need to reload files + // Required state has changed, so we need to reload files _MustRedrawFiles = true; } } - else if (!Required) + else if (!this.Required) { - //Required state has changed, so we need to reload files + // Required state has changed, so we need to reload files _MustRedrawFiles = true; } } + if (_MustRedrawFiles) { - cboFiles.DataSource = GetFileList(!Required); - cboFiles.DataBind(); - if (cboFiles.Items.FindByText(FileName) != null) + this.cboFiles.DataSource = this.GetFileList(!this.Required); + this.cboFiles.DataBind(); + if (this.cboFiles.Items.FindByText(FileName) != null) { - cboFiles.ClearSelection(); - cboFiles.Items.FindByText(FileName).Selected = true; + this.cboFiles.ClearSelection(); + this.cboFiles.Items.FindByText(FileName).Selected = true; } } - cboFiles.Visible = true; - txtFile.Visible = false; - FolderInfo objFolder = (FolderInfo)FolderManager.Instance.GetFolder(_objPortal.PortalID, FolderPath); - cmdUpload.Visible = ShowUpLoad && FolderPermissionController.CanAddFolder(objFolder); + this.cboFiles.Visible = true; + this.txtFile.Visible = false; - SetStorageLocationType(); - txtUrl.Visible = false; - cmdSave.Visible = false; - cmdCancel.Visible = false; + FolderInfo objFolder = (FolderInfo)FolderManager.Instance.GetFolder(this._objPortal.PortalID, FolderPath); + this.cmdUpload.Visible = this.ShowUpLoad && FolderPermissionController.CanAddFolder(objFolder); - if (cboFolders.SelectedIndex >= 0) + this.SetStorageLocationType(); + this.txtUrl.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + + if (this.cboFolders.SelectedIndex >= 0) { - ViewState["LastFolderPath"] = cboFolders.SelectedValue; + this.ViewState["LastFolderPath"] = this.cboFolders.SelectedValue; } else { - ViewState["LastFolderPath"] = ""; + this.ViewState["LastFolderPath"] = string.Empty; } - if (cboFiles.SelectedIndex >= 0) + + if (this.cboFiles.SelectedIndex >= 0) { - ViewState["LastFileName"] = cboFiles.SelectedValue; + this.ViewState["LastFileName"] = this.cboFiles.SelectedValue; } else { - ViewState["LastFileName"] = ""; + this.ViewState["LastFileName"] = string.Empty; } + break; - case "M": //membership users - URLRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = true; - ImagesRow.Visible = false; - if (String.IsNullOrEmpty(txtUser.Text)) + case "M": // membership users + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = true; + this.ImagesRow.Visible = false; + if (string.IsNullOrEmpty(this.txtUser.Text)) { - txtUser.Text = _Url; + this.txtUser.Text = _Url; } + break; } } else { - URLRow.Visible = false; - ImagesRow.Visible = false; - TabRow.Visible = false; - FileRow.Visible = false; - UserRow.Visible = false; - } - } - - #endregion - - #region "Event Handlers" - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - AJAX.RegisterPostBackControl(FindControl("cmdSave")); - - //prevent unauthorized access - if (Request.IsAuthenticated == false) - { - Visible = false; - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cboFolders.SelectedIndexChanged += cboFolders_SelectedIndexChanged; - optType.SelectedIndexChanged += optType_SelectedIndexChanged; - cmdAdd.Click += cmdAdd_Click; - cmdCancel.Click += cmdCancel_Click; - cmdDelete.Click += cmdDelete_Click; - cmdSave.Click += cmdSave_Click; - cmdSelect.Click += cmdSelect_Click; - cmdUpload.Click += cmdUpload_Click; - - ErrorRow.Visible = false; - - try - { - if ((Request.QueryString["pid"] != null) && (Globals.IsHostTab(PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) - { - _objPortal = PortalController.Instance.GetPortal(Int32.Parse(Request.QueryString["pid"])); - } - else - { - _objPortal = PortalController.Instance.GetPortal(PortalSettings.PortalId); - } - if (ViewState["IsUrlControlLoaded"] == null) - { - //If Not Page.IsPostBack Then - //let's make at least an initialization - //The type radio button must be initialized - //The url must be initialized no matter its value - _doRenderTypes = true; - _doChangeURL = true; - ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem")); - //The following line was mover to the pre-render event to ensure render for the first time - //ViewState("IsUrlControlLoaded") = "Loaded" - } - } - catch (Exception exc) //Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); + this.URLRow.Visible = false; + this.ImagesRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; } } @@ -1185,160 +1229,173 @@ protected override void OnPreRender(EventArgs e) try { - if (_doRenderTypes) + if (this._doRenderTypes) { - DoRenderTypes(); + this.DoRenderTypes(); } - if (_doChangeURL) + + if (this._doChangeURL) { - DoChangeURL(); + this.DoChangeURL(); } - if (_doReloadFolders || _doReloadFiles) + + if (this._doReloadFolders || this._doReloadFiles) { - DoCorrectRadioButtonList(); - _doRenderTypeControls = true; + this.DoCorrectRadioButtonList(); + this._doRenderTypeControls = true; } - if (_doRenderTypeControls) + + if (this._doRenderTypeControls) { - if (!(_doReloadFolders || _doReloadFiles)) + if (!(this._doReloadFolders || this._doReloadFiles)) { - DoCorrectRadioButtonList(); + this.DoCorrectRadioButtonList(); } - DoRenderTypeControls(); + + this.DoRenderTypeControls(); } - ViewState["Url"] = null; - ViewState["IsUrlControlLoaded"] = "Loaded"; + + this.ViewState["Url"] = null; + this.ViewState["IsUrlControlLoaded"] = "Loaded"; } catch (Exception exc) { - //Let's detect possible problems + // Let's detect possible problems Exceptions.LogException(new Exception("Error rendering URLControl subcontrols.", exc)); } } - protected void cboFolders_SelectedIndexChanged(Object sender, EventArgs e) + protected void cboFolders_SelectedIndexChanged(object sender, EventArgs e) { int PortalId = Null.NullInteger; - if (!IsHostMenu || Request.QueryString["pid"] != null) + if (!this.IsHostMenu || this.Request.QueryString["pid"] != null) { - PortalId = _objPortal.PortalID; + PortalId = this._objPortal.PortalID; } - var objFolder = FolderManager.Instance.GetFolder(PortalId, cboFolders.SelectedValue); + + var objFolder = FolderManager.Instance.GetFolder(PortalId, this.cboFolders.SelectedValue); if (FolderPermissionController.CanAddFolder((FolderInfo)objFolder)) { - if (!txtFile.Visible) + if (!this.txtFile.Visible) { - cmdSave.Visible = false; - //only show if not already in upload mode and not disabled - cmdUpload.Visible = ShowUpLoad; + this.cmdSave.Visible = false; + + // only show if not already in upload mode and not disabled + this.cmdUpload.Visible = this.ShowUpLoad; } } else { - //reset controls - cboFiles.Visible = true; - cmdUpload.Visible = false; - txtFile.Visible = false; - cmdSave.Visible = false; - cmdCancel.Visible = false; + // reset controls + this.cboFiles.Visible = true; + this.cmdUpload.Visible = false; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; } - cboFiles.Items.Clear(); - cboFiles.DataSource = GetFileList(!Required); - cboFiles.DataBind(); - SetStorageLocationType(); - if (cboFolders.SelectedIndex >= 0) + + this.cboFiles.Items.Clear(); + this.cboFiles.DataSource = this.GetFileList(!this.Required); + this.cboFiles.DataBind(); + this.SetStorageLocationType(); + if (this.cboFolders.SelectedIndex >= 0) { - ViewState["LastFolderPath"] = cboFolders.SelectedValue; + this.ViewState["LastFolderPath"] = this.cboFolders.SelectedValue; } else { - ViewState["LastFolderPath"] = ""; + this.ViewState["LastFolderPath"] = string.Empty; } - if (cboFiles.SelectedIndex >= 0) + + if (this.cboFiles.SelectedIndex >= 0) { - ViewState["LastFileName"] = cboFiles.SelectedValue; + this.ViewState["LastFileName"] = this.cboFiles.SelectedValue; } else { - ViewState["LastFileName"] = ""; + this.ViewState["LastFileName"] = string.Empty; } - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; - _doReloadFolders = false; - _doReloadFiles = false; + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } protected void cmdAdd_Click(object sender, EventArgs e) { - cboUrls.Visible = false; - cmdSelect.Visible = true; - txtUrl.Visible = true; - cmdAdd.Visible = false; - cmdDelete.Visible = false; - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; - _doReloadFolders = false; - _doReloadFiles = false; + this.cboUrls.Visible = false; + this.cmdSelect.Visible = true; + this.txtUrl.Visible = true; + this.cmdAdd.Visible = false; + this.cmdDelete.Visible = false; + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } - protected void cmdCancel_Click(Object sender, EventArgs e) + protected void cmdCancel_Click(object sender, EventArgs e) { - cboFiles.Visible = true; - cmdUpload.Visible = true; - txtFile.Visible = false; - cmdSave.Visible = false; - cmdCancel.Visible = false; - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; - _doReloadFolders = false; - _doReloadFiles = false; + this.cboFiles.Visible = true; + this.cmdUpload.Visible = true; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } protected void cmdDelete_Click(object sender, EventArgs e) { - if (cboUrls.SelectedItem != null) + if (this.cboUrls.SelectedItem != null) { var objUrls = new UrlController(); - objUrls.DeleteUrl(_objPortal.PortalID, cboUrls.SelectedItem.Value); - LoadUrls(); //we must reload the url list - } - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; - _doReloadFolders = false; - _doReloadFiles = false; + objUrls.DeleteUrl(this._objPortal.PortalID, this.cboUrls.SelectedItem.Value); + this.LoadUrls(); // we must reload the url list + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } - protected void cmdSave_Click(Object sender, EventArgs e) + protected void cmdSave_Click(object sender, EventArgs e) { - cmdUpload.Visible = false; + this.cmdUpload.Visible = false; - //if no file is selected exit - if (String.IsNullOrEmpty(txtFile.PostedFile.FileName)) + // if no file is selected exit + if (string.IsNullOrEmpty(this.txtFile.PostedFile.FileName)) { return; } + string ParentFolderName; - if (Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) + if (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) { ParentFolderName = Globals.HostMapPath; } else { - ParentFolderName = PortalSettings.HomeDirectoryMapPath; + ParentFolderName = this.PortalSettings.HomeDirectoryMapPath; } - ParentFolderName += cboFolders.SelectedItem.Value; - string strExtension = Path.GetExtension(txtFile.PostedFile.FileName).Replace(".", ""); - if (!String.IsNullOrEmpty(FileFilter) && ("," + FileFilter.ToLowerInvariant()).IndexOf("," + strExtension.ToLowerInvariant()) == -1) + ParentFolderName += this.cboFolders.SelectedItem.Value; + + string strExtension = Path.GetExtension(this.txtFile.PostedFile.FileName).Replace(".", string.Empty); + if (!string.IsNullOrEmpty(this.FileFilter) && ("," + this.FileFilter.ToLowerInvariant()).IndexOf("," + strExtension.ToLowerInvariant()) == -1) { - //trying to upload a file not allowed for current filter - lblMessage.Text = string.Format(Localization.GetString("UploadError", LocalResourceFile), FileFilter, strExtension); - ErrorRow.Visible = true; + // trying to upload a file not allowed for current filter + this.lblMessage.Text = string.Format(Localization.GetString("UploadError", this.LocalResourceFile), this.FileFilter, strExtension); + this.ErrorRow.Visible = true; } else { @@ -1348,144 +1405,147 @@ protected void cmdSave_Click(Object sender, EventArgs e) var settings = PortalController.Instance.GetCurrentPortalSettings(); var portalID = (settings.ActiveTab.ParentId == settings.SuperTabId) ? Null.NullInteger : settings.PortalId; - var fileName = Path.GetFileName(txtFile.PostedFile.FileName); + var fileName = Path.GetFileName(this.txtFile.PostedFile.FileName); var folderPath = Globals.GetSubFolderPath(ParentFolderName.Replace("/", "\\") + fileName, portalID); var folder = folderManager.GetFolder(portalID, folderPath); - ErrorRow.Visible = false; + this.ErrorRow.Visible = false; try { - fileManager.AddFile(folder, fileName, txtFile.PostedFile.InputStream, true, true, ((FileManager)fileManager).GetContentType(Path.GetExtension(fileName))); + fileManager.AddFile(folder, fileName, this.txtFile.PostedFile.InputStream, true, true, ((FileManager)fileManager).GetContentType(Path.GetExtension(fileName))); } catch (Services.FileSystem.PermissionsNotMetException) { - lblMessage.Text += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); - ErrorRow.Visible = true; + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); + this.ErrorRow.Visible = true; } catch (NoSpaceAvailableException) { - lblMessage.Text += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); - ErrorRow.Visible = true; + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); + this.ErrorRow.Visible = true; } catch (InvalidFileExtensionException) { - lblMessage.Text += "
    " + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); - ErrorRow.Visible = true; + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); + this.ErrorRow.Visible = true; } catch (Exception) { - lblMessage.Text += "
    " + string.Format(Localization.GetString("SaveFileError"), fileName); - ErrorRow.Visible = true; + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("SaveFileError"), fileName); + this.ErrorRow.Visible = true; } } - if (lblMessage.Text == string.Empty) + + if (this.lblMessage.Text == string.Empty) { - cboFiles.Visible = true; - cmdUpload.Visible = ShowUpLoad; - txtFile.Visible = false; - cmdSave.Visible = false; - cmdCancel.Visible = false; - ErrorRow.Visible = false; + this.cboFiles.Visible = true; + this.cmdUpload.Visible = this.ShowUpLoad; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + this.ErrorRow.Visible = false; var Root = new DirectoryInfo(ParentFolderName); - cboFiles.Items.Clear(); - cboFiles.DataSource = GetFileList(false); - cboFiles.DataBind(); + this.cboFiles.Items.Clear(); + this.cboFiles.DataSource = this.GetFileList(false); + this.cboFiles.DataBind(); - string FileName = txtFile.PostedFile.FileName.Substring(txtFile.PostedFile.FileName.LastIndexOf("\\") + 1); - if (cboFiles.Items.FindByText(FileName) != null) + string FileName = this.txtFile.PostedFile.FileName.Substring(this.txtFile.PostedFile.FileName.LastIndexOf("\\") + 1); + if (this.cboFiles.Items.FindByText(FileName) != null) { - cboFiles.Items.FindByText(FileName).Selected = true; + this.cboFiles.Items.FindByText(FileName).Selected = true; } - if (cboFiles.SelectedIndex >= 0) + + if (this.cboFiles.SelectedIndex >= 0) { - ViewState["LastFileName"] = cboFiles.SelectedValue; + this.ViewState["LastFileName"] = this.cboFiles.SelectedValue; } else { - ViewState["LastFileName"] = ""; + this.ViewState["LastFileName"] = string.Empty; } } - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; - _doReloadFolders = false; - _doReloadFiles = false; + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } protected void cmdSelect_Click(object sender, EventArgs e) { - cboUrls.Visible = true; - cmdSelect.Visible = false; - txtUrl.Visible = false; - cmdAdd.Visible = true; - cmdDelete.Visible = PortalSecurity.IsInRole(_objPortal.AdministratorRoleName); - LoadUrls(); - if (cboUrls.Items.FindByValue(txtUrl.Text) != null) - { - cboUrls.ClearSelection(); - cboUrls.Items.FindByValue(txtUrl.Text).Selected = true; - } - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; - _doReloadFolders = false; - _doReloadFiles = false; + this.cboUrls.Visible = true; + this.cmdSelect.Visible = false; + this.txtUrl.Visible = false; + this.cmdAdd.Visible = true; + this.cmdDelete.Visible = PortalSecurity.IsInRole(this._objPortal.AdministratorRoleName); + this.LoadUrls(); + if (this.cboUrls.Items.FindByValue(this.txtUrl.Text) != null) + { + this.cboUrls.ClearSelection(); + this.cboUrls.Items.FindByValue(this.txtUrl.Text).Selected = true; + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } protected void cmdUpload_Click(object sender, EventArgs e) { - string strSaveFolder = cboFolders.SelectedValue; - LoadFolders("ADD"); - if (cboFolders.Items.FindByValue(strSaveFolder) != null) + string strSaveFolder = this.cboFolders.SelectedValue; + this.LoadFolders("ADD"); + if (this.cboFolders.Items.FindByValue(strSaveFolder) != null) { - cboFolders.Items.FindByValue(strSaveFolder).Selected = true; - cboFiles.Visible = false; - cmdUpload.Visible = false; - txtFile.Visible = true; - cmdSave.Visible = true; - cmdCancel.Visible = true; + this.cboFolders.Items.FindByValue(strSaveFolder).Selected = true; + this.cboFiles.Visible = false; + this.cmdUpload.Visible = false; + this.txtFile.Visible = true; + this.cmdSave.Visible = true; + this.cmdCancel.Visible = true; } else { - if (cboFolders.Items.Count > 0) + if (this.cboFolders.Items.Count > 0) { - cboFolders.Items[0].Selected = true; - cboFiles.Visible = false; - cmdUpload.Visible = false; - txtFile.Visible = true; - cmdSave.Visible = true; - cmdCancel.Visible = true; + this.cboFolders.Items[0].Selected = true; + this.cboFiles.Visible = false; + this.cmdUpload.Visible = false; + this.txtFile.Visible = true; + this.cmdSave.Visible = true; + this.cmdCancel.Visible = true; } else { - //reset controls - LoadFolders("BROWSE,ADD"); - cboFolders.Items.FindByValue(strSaveFolder).Selected = true; - cboFiles.Visible = true; - cmdUpload.Visible = false; - txtFile.Visible = false; - cmdSave.Visible = false; - cmdCancel.Visible = false; - lblMessage.Text = Localization.GetString("NoWritePermission", LocalResourceFile); - ErrorRow.Visible = true; - } - } - _doRenderTypeControls = false; //Must not render on this postback - _doRenderTypes = false; - _doChangeURL = false; - _doReloadFolders = false; - _doReloadFiles = false; + // reset controls + this.LoadFolders("BROWSE,ADD"); + this.cboFolders.Items.FindByValue(strSaveFolder).Selected = true; + this.cboFiles.Visible = true; + this.cmdUpload.Visible = false; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + this.lblMessage.Text = Localization.GetString("NoWritePermission", this.LocalResourceFile); + this.ErrorRow.Visible = true; + } + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } - protected void optType_SelectedIndexChanged(Object sender, EventArgs e) + protected void optType_SelectedIndexChanged(object sender, EventArgs e) { - //Type changed, render the correct control set - ViewState["UrlType"] = optType.SelectedItem.Value; - _doRenderTypeControls = true; + // Type changed, render the correct control set + this.ViewState["UrlType"] = this.optType.SelectedItem.Value; + this._doRenderTypeControls = true; } - - #endregion } } diff --git a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs index 189aee170df..eef23c59cfe 100644 --- a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs @@ -1,31 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; - -using Calendar = DotNetNuke.Common.Utilities.Calendar; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.IO; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + + using Calendar = DotNetNuke.Common.Utilities.Calendar; + public abstract class URLTrackingControl : UserControlBase - { - #region "Private Members" - + { protected Label Label1; protected Label Label2; protected Label Label3; @@ -33,13 +26,13 @@ public abstract class URLTrackingControl : UserControlBase protected Label Label5; protected Label Label6; protected Label Label7; - private string _FormattedURL = ""; - private int _ModuleID = -2; - private string _TrackingURL = ""; - private string _URL = ""; - private string _localResourceFile; protected LinkButton cmdDisplay; protected HyperLink cmdEndCalendar; + private string _FormattedURL = string.Empty; + private int _ModuleID = -2; + private string _TrackingURL = string.Empty; + private string _URL = string.Empty; + private string _localResourceFile; protected HyperLink cmdStartCalendar; protected DataGrid grdLog; protected Label lblClicks; @@ -53,21 +46,18 @@ public abstract class URLTrackingControl : UserControlBase protected TextBox txtEndDate; protected TextBox txtStartDate; protected CompareValidator valEndDate; - protected CompareValidator valStartDate; - - #endregion - - #region "Public Properties" - + protected CompareValidator valStartDate; + public string FormattedURL { get { - return _FormattedURL; + return this._FormattedURL; } + set { - _FormattedURL = value; + this._FormattedURL = value; } } @@ -75,11 +65,12 @@ public string TrackingURL { get { - return _TrackingURL; + return this._TrackingURL; } + set { - _TrackingURL = value; + this._TrackingURL = value; } } @@ -87,11 +78,12 @@ public string URL { get { - return _URL; + return this._URL; } + set { - _URL = value; + this._URL = value; } } @@ -99,19 +91,21 @@ public int ModuleID { get { - int moduleID = _ModuleID; + int moduleID = this._ModuleID; if (moduleID == -2) { - if (Request.QueryString["mid"] != null) + if (this.Request.QueryString["mid"] != null) { - Int32.TryParse(Request.QueryString["mid"], out moduleID); + int.TryParse(this.Request.QueryString["mid"], out moduleID); } } + return moduleID; } + set { - _ModuleID = value; + this._ModuleID = value; } } @@ -120,110 +114,113 @@ public string LocalResourceFile get { string fileRoot; - if (String.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - fileRoot = TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/URLTrackingControl.ascx"; + fileRoot = this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/URLTrackingControl.ascx"; } else { - fileRoot = _localResourceFile; + fileRoot = this._localResourceFile; } + return fileRoot; } + set { - _localResourceFile = value; + this._localResourceFile = value; } - } - - #endregion - - #region "Event Handlers" - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdDisplay.Click += cmdDisplay_Click; + this.cmdDisplay.Click += this.cmdDisplay_Click; try { - //this needs to execute always to the client script code is registred in InvokePopupCal - cmdStartCalendar.NavigateUrl = Calendar.InvokePopupCal(txtStartDate); - cmdEndCalendar.NavigateUrl = Calendar.InvokePopupCal(txtEndDate); - if (!Page.IsPostBack) + // this needs to execute always to the client script code is registred in InvokePopupCal + this.cmdStartCalendar.NavigateUrl = Calendar.InvokePopupCal(this.txtStartDate); + this.cmdEndCalendar.NavigateUrl = Calendar.InvokePopupCal(this.txtEndDate); + if (!this.Page.IsPostBack) { - if (!String.IsNullOrEmpty(_URL)) + if (!string.IsNullOrEmpty(this._URL)) { - lblLogURL.Text = URL; //saved for loading Log grid - TabType URLType = Globals.GetURLType(_URL); - if (URLType == TabType.File && _URL.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false) + this.lblLogURL.Text = this.URL; // saved for loading Log grid + TabType URLType = Globals.GetURLType(this._URL); + if (URLType == TabType.File && this._URL.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false) { - //to handle legacy scenarios before the introduction of the FileServerHandler - var fileName = Path.GetFileName(_URL); + // to handle legacy scenarios before the introduction of the FileServerHandler + var fileName = Path.GetFileName(this._URL); - var folderPath = _URL.Substring(0, _URL.LastIndexOf(fileName)); - var folder = FolderManager.Instance.GetFolder(PortalSettings.PortalId, folderPath); + var folderPath = this._URL.Substring(0, this._URL.LastIndexOf(fileName)); + var folder = FolderManager.Instance.GetFolder(this.PortalSettings.PortalId, folderPath); var file = FileManager.Instance.GetFile(folder, fileName); - lblLogURL.Text = "FileID=" + file.FileId; + this.lblLogURL.Text = "FileID=" + file.FileId; } + var objUrls = new UrlController(); - UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(PortalSettings.PortalId, lblLogURL.Text, ModuleID); + UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this.PortalSettings.PortalId, this.lblLogURL.Text, this.ModuleID); if (objUrlTracking != null) { - if (String.IsNullOrEmpty(_FormattedURL)) + if (string.IsNullOrEmpty(this._FormattedURL)) { - lblURL.Text = Globals.LinkClick(URL, PortalSettings.ActiveTab.TabID, ModuleID, false); - if (!lblURL.Text.StartsWith("http") && !lblURL.Text.StartsWith("mailto")) + this.lblURL.Text = Globals.LinkClick(this.URL, this.PortalSettings.ActiveTab.TabID, this.ModuleID, false); + if (!this.lblURL.Text.StartsWith("http") && !this.lblURL.Text.StartsWith("mailto")) { - lblURL.Text = Globals.AddHTTP(Request.Url.Host) + lblURL.Text; + this.lblURL.Text = Globals.AddHTTP(this.Request.Url.Host) + this.lblURL.Text; } } else { - lblURL.Text = _FormattedURL; + this.lblURL.Text = this._FormattedURL; } - lblCreatedDate.Text = objUrlTracking.CreatedDate.ToString(); + + this.lblCreatedDate.Text = objUrlTracking.CreatedDate.ToString(); if (objUrlTracking.TrackClicks) { - pnlTrack.Visible = true; - if (String.IsNullOrEmpty(_TrackingURL)) + this.pnlTrack.Visible = true; + if (string.IsNullOrEmpty(this._TrackingURL)) { - if (!URL.StartsWith("http")) + if (!this.URL.StartsWith("http")) { - lblTrackingURL.Text = Globals.AddHTTP(Request.Url.Host); + this.lblTrackingURL.Text = Globals.AddHTTP(this.Request.Url.Host); } - lblTrackingURL.Text += Globals.LinkClick(URL, PortalSettings.ActiveTab.TabID, ModuleID, objUrlTracking.TrackClicks); + + this.lblTrackingURL.Text += Globals.LinkClick(this.URL, this.PortalSettings.ActiveTab.TabID, this.ModuleID, objUrlTracking.TrackClicks); } else { - lblTrackingURL.Text = _TrackingURL; + this.lblTrackingURL.Text = this._TrackingURL; } - lblClicks.Text = objUrlTracking.Clicks.ToString(); + + this.lblClicks.Text = objUrlTracking.Clicks.ToString(); if (!Null.IsNull(objUrlTracking.LastClick)) { - lblLastClick.Text = objUrlTracking.LastClick.ToString(); + this.lblLastClick.Text = objUrlTracking.LastClick.ToString(); } } + if (objUrlTracking.LogActivity) { - pnlLog.Visible = true; + this.pnlLog.Visible = true; - txtStartDate.Text = DateTime.Today.AddDays(-6).ToShortDateString(); - txtEndDate.Text = DateTime.Today.AddDays(1).ToShortDateString(); + this.txtStartDate.Text = DateTime.Today.AddDays(-6).ToShortDateString(); + this.txtEndDate.Text = DateTime.Today.AddDays(1).ToShortDateString(); } } } else { - Visible = false; + this.Visible = false; } } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -233,28 +230,29 @@ private void cmdDisplay_Click(object sender, EventArgs e) { try { - string strStartDate = txtStartDate.Text; - if (!String.IsNullOrEmpty(strStartDate)) + string strStartDate = this.txtStartDate.Text; + if (!string.IsNullOrEmpty(strStartDate)) { strStartDate = strStartDate + " 00:00"; } - string strEndDate = txtEndDate.Text; - if (!String.IsNullOrEmpty(strEndDate)) + + string strEndDate = this.txtEndDate.Text; + if (!string.IsNullOrEmpty(strEndDate)) { strEndDate = strEndDate + " 23:59"; } + var objUrls = new UrlController(); - //localize datagrid - Localization.LocalizeDataGrid(ref grdLog, LocalResourceFile); - grdLog.DataSource = objUrls.GetUrlLog(PortalSettings.PortalId, lblLogURL.Text, ModuleID, Convert.ToDateTime(strStartDate), Convert.ToDateTime(strEndDate)); - grdLog.DataBind(); + + // localize datagrid + Localization.LocalizeDataGrid(ref this.grdLog, this.LocalResourceFile); + this.grdLog.DataSource = objUrls.GetUrlLog(this.PortalSettings.PortalId, this.lblLogURL.Text, this.ModuleID, Convert.ToDateTime(strStartDate), Convert.ToDateTime(strEndDate)); + this.grdLog.DataBind(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/UserControls/User.cs b/DNN Platform/Library/UI/UserControls/User.cs index 26520773e5a..66889046f13 100644 --- a/DNN Platform/Library/UI/UserControls/User.cs +++ b/DNN Platform/Library/UI/UserControls/User.cs @@ -1,41 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Framework; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.UserControls { + using System; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// - /// The User UserControl is used to manage User Details + /// The User UserControl is used to manage User Details. /// /// /// /// ----------------------------------------------------------------------------- public abstract class User : UserControlBase - { - #region "Private Members" - + { protected HtmlTableRow ConfirmPasswordRow; - private string MyFileName = "User.ascx"; protected HtmlTableRow PasswordRow; + protected Label lblUsername; + protected Label lblUsernameAsterisk; + private string MyFileName = "User.ascx"; private string _Confirm; - private string _ControlColumnWidth = ""; + private string _ControlColumnWidth = string.Empty; private string _Email; private string _FirstName; private string _IM; - private string _LabelColumnWidth = ""; + private string _LabelColumnWidth = string.Empty; private string _LastName; private int _ModuleId; private string _Password; @@ -43,13 +38,6 @@ public abstract class User : UserControlBase private int _StartTabIndex = 1; private string _UserName; private string _Website; - protected Label lblUsername; - - #endregion - - #region "Protected Members" - - protected Label lblUsernameAsterisk; protected LabelControl plConfirm; protected LabelControl plEmail; protected LabelControl plFirstName; @@ -73,21 +61,18 @@ public abstract class User : UserControlBase protected RequiredFieldValidator valFirstName; protected RequiredFieldValidator valLastName; protected RequiredFieldValidator valPassword; - protected RequiredFieldValidator valUsername; - - #endregion - - #region "Public Properties" - - public int ModuleId + protected RequiredFieldValidator valUsername; + + public int ModuleId { get { - return Convert.ToInt32(ViewState["ModuleId"]); + return Convert.ToInt32(this.ViewState["ModuleId"]); } + set { - _ModuleId = value; + this._ModuleId = value; } } @@ -95,11 +80,12 @@ public string LabelColumnWidth { get { - return Convert.ToString(ViewState["LabelColumnWidth"]); + return Convert.ToString(this.ViewState["LabelColumnWidth"]); } + set { - _LabelColumnWidth = value; + this._LabelColumnWidth = value; } } @@ -107,11 +93,12 @@ public string ControlColumnWidth { get { - return Convert.ToString(ViewState["ControlColumnWidth"]); + return Convert.ToString(this.ViewState["ControlColumnWidth"]); } + set { - _ControlColumnWidth = value; + this._ControlColumnWidth = value; } } @@ -119,11 +106,12 @@ public string FirstName { get { - return txtFirstName.Text; + return this.txtFirstName.Text; } + set { - _FirstName = value; + this._FirstName = value; } } @@ -131,11 +119,12 @@ public string LastName { get { - return txtLastName.Text; + return this.txtLastName.Text; } + set { - _LastName = value; + this._LastName = value; } } @@ -143,11 +132,12 @@ public string UserName { get { - return txtUsername.Text; + return this.txtUsername.Text; } + set { - _UserName = value; + this._UserName = value; } } @@ -155,11 +145,12 @@ public string Password { get { - return txtPassword.Text; + return this.txtPassword.Text; } + set { - _Password = value; + this._Password = value; } } @@ -167,11 +158,12 @@ public string Confirm { get { - return txtConfirm.Text; + return this.txtConfirm.Text; } + set { - _Confirm = value; + this._Confirm = value; } } @@ -179,11 +171,12 @@ public string Email { get { - return txtEmail.Text; + return this.txtEmail.Text; } + set { - _Email = value; + this._Email = value; } } @@ -191,11 +184,12 @@ public string Website { get { - return txtWebsite.Text; + return this.txtWebsite.Text; } + set { - _Website = value; + this._Website = value; } } @@ -203,11 +197,12 @@ public string IM { get { - return txtIM.Text; + return this.txtIM.Text; } + set { - _IM = value; + this._IM = value; } } @@ -215,7 +210,7 @@ public int StartTabIndex { set { - _StartTabIndex = value; + this._StartTabIndex = value; } } @@ -223,7 +218,7 @@ public bool ShowPassword { set { - _ShowPassword = value; + this._ShowPassword = value; } } @@ -231,17 +226,13 @@ public string LocalResourceFile { get { - return Localization.GetResourceFile(this, MyFileName); + return Localization.GetResourceFile(this, this.MyFileName); } - } - - #endregion - - #region "Event Handlers" - - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -251,73 +242,74 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - if (Page.IsPostBack == false) + if (this.Page.IsPostBack == false) { - txtFirstName.TabIndex = Convert.ToInt16(_StartTabIndex); - txtLastName.TabIndex = Convert.ToInt16(_StartTabIndex + 1); - txtUsername.TabIndex = Convert.ToInt16(_StartTabIndex + 2); - txtPassword.TabIndex = Convert.ToInt16(_StartTabIndex + 3); - txtConfirm.TabIndex = Convert.ToInt16(_StartTabIndex + 4); - txtEmail.TabIndex = Convert.ToInt16(_StartTabIndex + 5); - txtWebsite.TabIndex = Convert.ToInt16(_StartTabIndex + 6); - txtIM.TabIndex = Convert.ToInt16(_StartTabIndex + 7); - txtFirstName.Text = _FirstName; - txtLastName.Text = _LastName; - txtEmail.Text = _Email; - txtUsername.Text = _UserName; - lblUsername.Text = _UserName; - txtPassword.Text = _Password; - txtConfirm.Text = _Confirm; - txtWebsite.Text = _Website; - txtIM.Text = _IM; - if (!String.IsNullOrEmpty(_ControlColumnWidth)) + this.txtFirstName.TabIndex = Convert.ToInt16(this._StartTabIndex); + this.txtLastName.TabIndex = Convert.ToInt16(this._StartTabIndex + 1); + this.txtUsername.TabIndex = Convert.ToInt16(this._StartTabIndex + 2); + this.txtPassword.TabIndex = Convert.ToInt16(this._StartTabIndex + 3); + this.txtConfirm.TabIndex = Convert.ToInt16(this._StartTabIndex + 4); + this.txtEmail.TabIndex = Convert.ToInt16(this._StartTabIndex + 5); + this.txtWebsite.TabIndex = Convert.ToInt16(this._StartTabIndex + 6); + this.txtIM.TabIndex = Convert.ToInt16(this._StartTabIndex + 7); + this.txtFirstName.Text = this._FirstName; + this.txtLastName.Text = this._LastName; + this.txtEmail.Text = this._Email; + this.txtUsername.Text = this._UserName; + this.lblUsername.Text = this._UserName; + this.txtPassword.Text = this._Password; + this.txtConfirm.Text = this._Confirm; + this.txtWebsite.Text = this._Website; + this.txtIM.Text = this._IM; + if (!string.IsNullOrEmpty(this._ControlColumnWidth)) { - txtFirstName.Width = Unit.Parse(_ControlColumnWidth); - txtLastName.Width = Unit.Parse(_ControlColumnWidth); - txtEmail.Width = Unit.Parse(_ControlColumnWidth); - txtUsername.Width = Unit.Parse(_ControlColumnWidth); - txtPassword.Width = Unit.Parse(_ControlColumnWidth); - txtConfirm.Width = Unit.Parse(_ControlColumnWidth); - txtWebsite.Width = Unit.Parse(_ControlColumnWidth); - txtIM.Width = Unit.Parse(_ControlColumnWidth); + this.txtFirstName.Width = Unit.Parse(this._ControlColumnWidth); + this.txtLastName.Width = Unit.Parse(this._ControlColumnWidth); + this.txtEmail.Width = Unit.Parse(this._ControlColumnWidth); + this.txtUsername.Width = Unit.Parse(this._ControlColumnWidth); + this.txtPassword.Width = Unit.Parse(this._ControlColumnWidth); + this.txtConfirm.Width = Unit.Parse(this._ControlColumnWidth); + this.txtWebsite.Width = Unit.Parse(this._ControlColumnWidth); + this.txtIM.Width = Unit.Parse(this._ControlColumnWidth); } - if (!_ShowPassword) + + if (!this._ShowPassword) { - valPassword.Enabled = false; - valConfirm1.Enabled = false; - valConfirm2.Enabled = false; - PasswordRow.Visible = false; - ConfirmPasswordRow.Visible = false; - txtUsername.Visible = false; - valUsername.Enabled = false; - lblUsername.Visible = true; - lblUsernameAsterisk.Visible = false; + this.valPassword.Enabled = false; + this.valConfirm1.Enabled = false; + this.valConfirm2.Enabled = false; + this.PasswordRow.Visible = false; + this.ConfirmPasswordRow.Visible = false; + this.txtUsername.Visible = false; + this.valUsername.Enabled = false; + this.lblUsername.Visible = true; + this.lblUsernameAsterisk.Visible = false; } else { - txtUsername.Visible = true; - valUsername.Enabled = true; - lblUsername.Visible = false; - lblUsernameAsterisk.Visible = true; - valPassword.Enabled = true; - valConfirm1.Enabled = true; - valConfirm2.Enabled = true; - PasswordRow.Visible = true; - ConfirmPasswordRow.Visible = true; + this.txtUsername.Visible = true; + this.valUsername.Enabled = true; + this.lblUsername.Visible = false; + this.lblUsernameAsterisk.Visible = true; + this.valPassword.Enabled = true; + this.valConfirm1.Enabled = true; + this.valConfirm2.Enabled = true; + this.PasswordRow.Visible = true; + this.ConfirmPasswordRow.Visible = true; } - ViewState["ModuleId"] = Convert.ToString(_ModuleId); - ViewState["LabelColumnWidth"] = _LabelColumnWidth; - ViewState["ControlColumnWidth"] = _ControlColumnWidth; + + this.ViewState["ModuleId"] = Convert.ToString(this._ModuleId); + this.ViewState["LabelColumnWidth"] = this._LabelColumnWidth; + this.ViewState["ControlColumnWidth"] = this._ControlColumnWidth; } - txtPassword.Attributes.Add("value", txtPassword.Text); - txtConfirm.Attributes.Add("value", txtConfirm.Text); + + this.txtPassword.Attributes.Add("value", this.txtPassword.Text); + this.txtConfirm.Attributes.Add("value", this.txtConfirm.Text); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - } + } + } } diff --git a/DNN Platform/Library/UI/Utilities/ClientAPI.cs b/DNN Platform/Library/UI/Utilities/ClientAPI.cs index bb39f27c047..6b6a9022de3 100644 --- a/DNN Platform/Library/UI/Utilities/ClientAPI.cs +++ b/DNN Platform/Library/UI/Utilities/ClientAPI.cs @@ -1,28 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Utilities { + using System; + using System.Collections; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : ClientAPI + /// Project : DotNetNuke + /// Class : ClientAPI /// /// ----------------------------------------------------------------------------- /// @@ -32,42 +28,34 @@ namespace DotNetNuke.UI.Utilities /// public class DNNClientAPI { - #region MinMaxPersistanceType enum + private static readonly Hashtable m_objEnabledClientPersonalizationKeys = new Hashtable(); public enum MinMaxPersistanceType { None, Page, Cookie, - Personalization + Personalization, } - #endregion - - #region PageCallBackType enum - public enum PageCallBackType { GetPersonalization = 0, - SetPersonalization = 1 + SetPersonalization = 1, } - #endregion - - private static readonly Hashtable m_objEnabledClientPersonalizationKeys = new Hashtable(); - /// ----------------------------------------------------------------------------- /// - /// Adds client side body.onload event handler + /// Adds client side body.onload event handler. /// - /// Current page rendering content - /// Javascript function name to execute + /// Current page rendering content. + /// Javascript function name to execute. /// /// [Obsolete("This method has been deprecated and its code replaced in the 7.1.0 release. Scheduled removal in v10.0.0.")] public static void AddBodyOnloadEventHandler(Page objPage, string strJSFunction) { - //legacy implementation replaced + // legacy implementation replaced AddBodyOnLoad(objPage, strJSFunction, strJSFunction); } @@ -96,19 +84,13 @@ public static void InitFileManager(Page objPage) AddBodyOnLoad(objPage, "initFileManager", "initFileManager();"); } - private static void AddBodyOnLoad(Page objPage, string scriptKey, string strJSFunction) - { - JavaScript.RegisterClientReference(objPage, ClientAPI.ClientNamespaceReferences.dnn); - objPage.ClientScript.RegisterStartupScript(objPage.GetType(), scriptKey, strJSFunction, true); - } - /// ----------------------------------------------------------------------------- /// - /// Allows any module to have drag and drop functionality enabled + /// Allows any module to have drag and drop functionality enabled. /// - /// Title element that responds to the click and dragged - /// Container - /// Module ID + /// Title element that responds to the click and dragged. + /// Container. + /// Module ID. /// /// This sub also will send down information to notify the client of the panes that have been defined in the current skin. /// @@ -120,9 +102,9 @@ public static void EnableContainerDragAndDrop(Control objTitle, Control objConta JavaScript.RegisterClientReference(objTitle.Page, ClientAPI.ClientNamespaceReferences.dnn_dom_positioning); ClientAPI.RegisterClientVariable(objTitle.Page, "__dnn_dragDrop", objContainer.ClientID + " " + objTitle.ClientID + " " + ModuleID + ";", false); - string strPanes = ""; - string strPaneNames = ""; - var objPortalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"]; + string strPanes = string.Empty; + string strPaneNames = string.Empty; + var objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; Control objCtl; foreach (string strPane in objPortalSettings.ActiveTab.Panes) @@ -132,8 +114,10 @@ public static void EnableContainerDragAndDrop(Control objTitle, Control objConta { strPanes += objCtl.ClientID + ";"; } + strPaneNames += strPane + ";"; } + ClientAPI.RegisterClientVariable(objTitle.Page, "__dnn_Panes", strPanes, true); ClientAPI.RegisterClientVariable(objTitle.Page, "__dnn_PaneNames", strPaneNames, true); } @@ -141,23 +125,29 @@ public static void EnableContainerDragAndDrop(Control objTitle, Control objConta /// ----------------------------------------------------------------------------- /// - /// Allows a button and a content area to support client side min/max functionality + /// Allows a button and a content area to support client side min/max functionality. /// - /// Control that when clicked causes content area to be hidden/shown - /// Content area that is hidden/shown - /// If content area is to be defaulted to minimized pass in true - /// How to store current state of min/max. Cookie, Page, None + /// Control that when clicked causes content area to be hidden/shown. + /// Content area that is hidden/shown. + /// If content area is to be defaulted to minimized pass in true. + /// How to store current state of min/max. Cookie, Page, None. /// /// This method's purpose is to provide a higher level of abstraction between the ClientAPI and the module developer. /// public static void EnableMinMax(Control objButton, Control objContent, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) { - EnableMinMax(objButton, objContent, -1, blnDefaultMin, "", "", ePersistanceType); + EnableMinMax(objButton, objContent, -1, blnDefaultMin, string.Empty, string.Empty, ePersistanceType); + } + + private static void AddBodyOnLoad(Page objPage, string scriptKey, string strJSFunction) + { + JavaScript.RegisterClientReference(objPage, ClientAPI.ClientNamespaceReferences.dnn); + objPage.ClientScript.RegisterStartupScript(objPage.GetType(), scriptKey, strJSFunction, true); } public static void EnableMinMax(Control objButton, Control objContent, int intModuleId, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) { - EnableMinMax(objButton, objContent, intModuleId, blnDefaultMin, "", "", ePersistanceType); + EnableMinMax(objButton, objContent, intModuleId, blnDefaultMin, string.Empty, string.Empty, ePersistanceType); } public static void EnableMinMax(Control objButton, Control objContent, bool blnDefaultMin, string strMinIconLoc, string strMaxIconLoc, MinMaxPersistanceType ePersistanceType) @@ -167,15 +157,15 @@ public static void EnableMinMax(Control objButton, Control objContent, bool blnD /// ----------------------------------------------------------------------------- /// - /// Allows a button and a content area to support client side min/max functionality + /// Allows a button and a content area to support client side min/max functionality. /// - /// Control that when clicked causes content area to be hidden/shown - /// Content area that is hidden/shown - /// Module id of button/content, used only for persistance type of Cookie - /// If content area is to be defaulted to minimized pass in true - /// Location of minimized icon - /// Location of maximized icon - /// How to store current state of min/max. Cookie, Page, None + /// Control that when clicked causes content area to be hidden/shown. + /// Content area that is hidden/shown. + /// Module id of button/content, used only for persistance type of Cookie. + /// If content area is to be defaulted to minimized pass in true. + /// Location of minimized icon. + /// Location of maximized icon. + /// How to store current state of min/max. Cookie, Page, None. /// /// This method's purpose is to provide a higher level of abstraction between the ClientAPI and the module developer. /// @@ -206,19 +196,21 @@ public static void EnableMinMax(Control objButton, Control objContent, int intMo { case MinMaxPersistanceType.None: AddAttribute(objButton, "onclick", "if (__dnn_SectionMaxMin(this, '" + objContent.ClientID + "')) return false;"); - if (!String.IsNullOrEmpty(strMinIconLoc)) + if (!string.IsNullOrEmpty(strMinIconLoc)) { AddAttribute(objButton, "max_icon", strMaxIconLoc); AddAttribute(objButton, "min_icon", strMinIconLoc); } + break; case MinMaxPersistanceType.Page: AddAttribute(objButton, "onclick", "if (__dnn_SectionMaxMin(this, '" + objContent.ClientID + "')) return false;"); - if (!String.IsNullOrEmpty(strMinIconLoc)) + if (!string.IsNullOrEmpty(strMinIconLoc)) { AddAttribute(objButton, "max_icon", strMaxIconLoc); AddAttribute(objButton, "min_icon", strMinIconLoc); } + break; case MinMaxPersistanceType.Cookie: if (intModuleId != -1) @@ -238,35 +230,39 @@ public static void EnableMinMax(Control objButton, Control objContent, int intMo ClientAPI.RegisterClientVariable(objButton.Page, "__dnn_" + intModuleId + ":defminimized", "true", true); } } + break; case MinMaxPersistanceType.Personalization: - //Regardless if we determine whether or not the browser supports client-side personalization - //we need to store these keys to properly display or hide the content (They are needed in MinMaxContentVisible) + // Regardless if we determine whether or not the browser supports client-side personalization + // we need to store these keys to properly display or hide the content (They are needed in MinMaxContentVisible) AddAttribute(objButton, "userctr", strPersonalizationNamingCtr); AddAttribute(objButton, "userkey", strPersonalizationKey); if (EnableClientPersonalization(strPersonalizationNamingCtr, strPersonalizationKey, objButton.Page)) { AddAttribute(objButton, "onclick", "if (__dnn_SectionMaxMin(this, '" + objContent.ClientID + "')) return false;"); - if (!String.IsNullOrEmpty(strMinIconLoc)) + if (!string.IsNullOrEmpty(strMinIconLoc)) { AddAttribute(objButton, "max_icon", strMaxIconLoc); AddAttribute(objButton, "min_icon", strMinIconLoc); } } + break; } } + if (MinMaxContentVisibile(objButton, intModuleId, blnDefaultMin, ePersistanceType)) { if (ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.DHTML)) { - AddStyleAttribute(objContent, "display", ""); + AddStyleAttribute(objContent, "display", string.Empty); } else { objContent.Visible = true; } - if (!String.IsNullOrEmpty(strMinIconLoc)) + + if (!string.IsNullOrEmpty(strMinIconLoc)) { SetMinMaxProperties(objButton, strMinIconLoc, Localization.GetString("Minimize"), Localization.GetString("Minimize")); } @@ -281,22 +277,34 @@ public static void EnableMinMax(Control objButton, Control objContent, int intMo { objContent.Visible = false; } - if (!String.IsNullOrEmpty(strMaxIconLoc)) + + if (!string.IsNullOrEmpty(strMaxIconLoc)) { SetMinMaxProperties(objButton, strMaxIconLoc, Localization.GetString("Maximize"), Localization.GetString("Maximize")); } } + if (intAnimationFrames != 5) { ClientAPI.RegisterClientVariable(objButton.Page, "animf_" + objContent.ClientID, intAnimationFrames.ToString(), true); } } + public static bool MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) + { + return MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType); + } + + public static void MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType, bool value) + { + MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType, value); + } + private static void SetMinMaxProperties(Control objButton, string strImage, string strToolTip, string strAltText) { if (objButton is LinkButton) { - var objLB = (LinkButton) objButton; + var objLB = (LinkButton)objButton; objLB.ToolTip = strToolTip; if (objLB.Controls.Count > 0) { @@ -317,36 +325,26 @@ private static void SetImageProperties(Control objControl, string strImage, stri { if (objControl is Image) { - var objImage = (Image) objControl; + var objImage = (Image)objControl; objImage.ImageUrl = strImage; objImage.AlternateText = strAltText; objImage.ToolTip = strToolTip; } else if (objControl is ImageButton) { - var objImage = (ImageButton) objControl; + var objImage = (ImageButton)objControl; objImage.ImageUrl = strImage; objImage.AlternateText = strAltText; objImage.ToolTip = strToolTip; } else if (objControl is HtmlImage) { - var objImage = (HtmlImage) objControl; + var objImage = (HtmlImage)objControl; objImage.Src = strImage; objImage.Alt = strAltText; } } - public static bool MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) - { - return MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType); - } - - public static void MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType, bool value) - { - MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType, value); - } - public static bool MinMaxContentVisibile(Control objButton, int intModuleId, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) { if (HttpContext.Current != null) @@ -355,7 +353,7 @@ public static bool MinMaxContentVisibile(Control objButton, int intModuleId, boo { case MinMaxPersistanceType.Page: string sExpanded = ClientAPI.GetClientVariable(objButton.Page, objButton.ClientID + ":exp"); - if (!String.IsNullOrEmpty(sExpanded)) + if (!string.IsNullOrEmpty(sExpanded)) { return sExpanded == "1" ? true : false; } @@ -363,6 +361,7 @@ public static bool MinMaxContentVisibile(Control objButton, int intModuleId, boo { return !blnDefaultMin; } + case MinMaxPersistanceType.Cookie: if (intModuleId != -1) { @@ -380,6 +379,7 @@ public static bool MinMaxContentVisibile(Control objButton, int intModuleId, boo { return true; } + case MinMaxPersistanceType.Personalization: string strVisible = Convert.ToString(Personalization.GetProfile(Globals.GetAttribute(objButton, "userctr"), Globals.GetAttribute(objButton, "userkey"))); if (string.IsNullOrEmpty(strVisible)) @@ -390,10 +390,12 @@ public static bool MinMaxContentVisibile(Control objButton, int intModuleId, boo { return Convert.ToBoolean(strVisible); } + default: return !blnDefaultMin; } } + return Null.NullBoolean; } @@ -410,7 +412,7 @@ public static void MinMaxContentVisibile(Control objButton, int intModuleId, boo var objModuleVisible = new HttpCookie("_Module" + intModuleId + "_Visible", value.ToString().ToLowerInvariant()) { Expires = DateTime.MaxValue, - Path = (!string.IsNullOrEmpty(Common.Globals.ApplicationPath) ? Common.Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Common.Globals.ApplicationPath) ? Common.Globals.ApplicationPath : "/", }; HttpContext.Current.Response.AppendCookie(objModuleVisible); break; @@ -421,15 +423,48 @@ public static void MinMaxContentVisibile(Control objButton, int intModuleId, boo } } + // enables callbacks for request, and registers personalization key to be accessible from client + // returns true when browser is capable of callbacks + public static bool EnableClientPersonalization(string strNamingContainer, string strKey, Page objPage) + { + if (ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.XMLHTTP)) + { + // Instead of sending the callback js function down to the client, we are hardcoding + // it on the client. DNN owns the interface, so there is no worry about an outside + // entity changing it on us. We are simply calling this here to register all the appropriate + // js libraries + ClientAPI.GetCallbackEventReference(objPage, string.Empty, string.Empty, string.Empty, string.Empty); + + // in order to limit the keys that can be accessed and written we are storing the enabled keys + // in this shared hash table + lock (m_objEnabledClientPersonalizationKeys.SyncRoot) + { + if (IsPersonalizationKeyRegistered(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey) == false) + { + m_objEnabledClientPersonalizationKeys.Add(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey, string.Empty); + } + } + + return true; + } + + return false; + } + + public static bool IsPersonalizationKeyRegistered(string strKey) + { + return m_objEnabledClientPersonalizationKeys.ContainsKey(strKey); + } + private static void AddAttribute(Control objControl, string strName, string strValue) { if (objControl is HtmlControl) { - ((HtmlControl) objControl).Attributes.Add(strName, strValue); + ((HtmlControl)objControl).Attributes.Add(strName, strValue); } else if (objControl is WebControl) { - ((WebControl) objControl).Attributes.Add(strName, strValue); + ((WebControl)objControl).Attributes.Add(strName, strValue); } } @@ -437,57 +472,26 @@ private static void AddStyleAttribute(Control objControl, string strName, string { if (objControl is HtmlControl) { - if (!String.IsNullOrEmpty(strValue)) + if (!string.IsNullOrEmpty(strValue)) { - ((HtmlControl) objControl).Style.Add(strName, strValue); + ((HtmlControl)objControl).Style.Add(strName, strValue); } else { - ((HtmlControl) objControl).Style.Remove(strName); + ((HtmlControl)objControl).Style.Remove(strName); } } else if (objControl is WebControl) { - if (!String.IsNullOrEmpty(strValue)) + if (!string.IsNullOrEmpty(strValue)) { - ((WebControl) objControl).Style.Add(strName, strValue); + ((WebControl)objControl).Style.Add(strName, strValue); } else { - ((WebControl) objControl).Style.Remove(strName); - } - } - } - - //enables callbacks for request, and registers personalization key to be accessible from client - //returns true when browser is capable of callbacks - public static bool EnableClientPersonalization(string strNamingContainer, string strKey, Page objPage) - { - if (ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.XMLHTTP)) - { - //Instead of sending the callback js function down to the client, we are hardcoding - //it on the client. DNN owns the interface, so there is no worry about an outside - //entity changing it on us. We are simply calling this here to register all the appropriate - //js libraries - ClientAPI.GetCallbackEventReference(objPage, "", "", "", ""); - - //in order to limit the keys that can be accessed and written we are storing the enabled keys - //in this shared hash table - lock (m_objEnabledClientPersonalizationKeys.SyncRoot) - { - if (IsPersonalizationKeyRegistered(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey) == false) - { - m_objEnabledClientPersonalizationKeys.Add(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey, ""); - } + ((WebControl)objControl).Style.Remove(strName); } - return true; } - return false; - } - - public static bool IsPersonalizationKeyRegistered(string strKey) - { - return m_objEnabledClientPersonalizationKeys.ContainsKey(strKey); } } } diff --git a/DNN Platform/Library/UI/WebControls/ActionLink.cs b/DNN Platform/Library/UI/WebControls/ActionLink.cs index bf96a9363d6..b1827743eda 100644 --- a/DNN Platform/Library/UI/WebControls/ActionLink.cs +++ b/DNN Platform/Library/UI/WebControls/ActionLink.cs @@ -1,50 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.UI.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.UI.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.WebControls - /// Class : ActionLink + /// Class : ActionLink /// ----------------------------------------------------------------------------- /// /// ActionLink provides a button for a single action. /// /// - /// ActionBase inherits from HyperLink + /// ActionBase inherits from HyperLink. /// /// ----------------------------------------------------------------------------- public class ActionLink : HyperLink - { - #region Private Members - + { public ActionLink() { - RequireEditMode = false; - Security = "Edit"; - ControlKey = ""; - Title = ""; - } - - #endregion - - #region Public Properties - + this.RequireEditMode = false; + this.Security = "Edit"; + this.ControlKey = string.Empty; + this.Title = string.Empty; + } + public string Title { get; set; } public string ControlKey { get; set; } @@ -57,72 +46,61 @@ public ActionLink() public bool RequireEditMode { get; set; } - public IModuleControl ModuleControl { get; set; } - - #endregion - - #region Private Methods - - private bool IsVisible(SecurityAccessLevel security) - { - bool isVisible = false; - if (ModulePermissionController.HasModuleAccess(security, Null.NullString, ModuleControl.ModuleContext.Configuration)) - { - if ((RequireEditMode != true || ModuleControl.ModuleContext.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (security == SecurityAccessLevel.Anonymous || security == SecurityAccessLevel.View)) - { - isVisible = true; - } - } - - return isVisible; - } - - #endregion - - #region Protected Methods - + public IModuleControl ModuleControl { get; set; } + /// ----------------------------------------------------------------------------- /// - /// CreateChildControls builds the control tree + /// CreateChildControls builds the control tree. /// /// ----------------------------------------------------------------------------- protected override void CreateChildControls() { - //Call base class method to ensure Control Tree is built + // Call base class method to ensure Control Tree is built base.CreateChildControls(); - //Set Causes Validation and Enables ViewState to false - EnableViewState = false; + // Set Causes Validation and Enables ViewState to false + this.EnableViewState = false; } - - + /// ----------------------------------------------------------------------------- /// - /// OnPreRender runs when just before the Render phase of the Page Lifecycle + /// OnPreRender runs when just before the Render phase of the Page Lifecycle. /// /// ----------------------------------------------------------------------------- protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (Visible && IsVisible((SecurityAccessLevel)Enum.Parse(typeof(SecurityAccessLevel), Security))) + if (this.Visible && this.IsVisible((SecurityAccessLevel)Enum.Parse(typeof(SecurityAccessLevel), this.Security))) { - Text = Title; - NavigateUrl = ControlKey != "" - ? ModuleControl.ModuleContext.EditUrl(KeyName, KeyValue, ControlKey) - : ModuleControl.ModuleContext.EditUrl(Title); + this.Text = this.Title; + this.NavigateUrl = this.ControlKey != string.Empty + ? this.ModuleControl.ModuleContext.EditUrl(this.KeyName, this.KeyValue, this.ControlKey) + : this.ModuleControl.ModuleContext.EditUrl(this.Title); - if (CssClass == "") + if (this.CssClass == string.Empty) { - CssClass = "dnnPrimaryAction"; + this.CssClass = "dnnPrimaryAction"; } } else { - Visible = false; + this.Visible = false; + } + } + + private bool IsVisible(SecurityAccessLevel security) + { + bool isVisible = false; + if (ModulePermissionController.HasModuleAccess(security, Null.NullString, this.ModuleControl.ModuleContext.Configuration)) + { + if ((this.RequireEditMode != true || this.ModuleControl.ModuleContext.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (security == SecurityAccessLevel.Anonymous || security == SecurityAccessLevel.View)) + { + isVisible = true; + } } - } - #endregion + return isVisible; + } } } diff --git a/DNN Platform/Library/UI/WebControls/CaptchaControl.cs b/DNN Platform/Library/UI/WebControls/CaptchaControl.cs index 0996d0d9616..e3cc6b5bca2 100644 --- a/DNN Platform/Library/UI/WebControls/CaptchaControl.cs +++ b/DNN Platform/Library/UI/WebControls/CaptchaControl.cs @@ -1,544 +1,375 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Globalization; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Caching; -using System.Web.Security; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -using Image = System.Web.UI.WebControls.Image; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.ComponentModel; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Globalization; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Caching; + using System.Web.Security; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + + using Image = System.Web.UI.WebControls.Image; + + /// + /// The CaptchaControl control provides a Captcha Challenge control. + /// + /// + /// + [ToolboxData("<{0}:CaptchaControl Runat=\"server\" CaptchaHeight=\"100px\" CaptchaWidth=\"300px\" />")] + public class CaptchaControl : WebControl, INamingContainer, IPostBackDataHandler + { + internal const string KEY = "captcha"; + private const int EXPIRATION_DEFAULT = 120; + private const int LENGTH_DEFAULT = 6; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CaptchaControl)); + private const string RENDERURL_DEFAULT = "ImageChallenge.captcha.aspx"; + private const string CHARS_DEFAULT = "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + private static readonly string[] _FontFamilies = { "Arial", "Comic Sans MS", "Courier New", "Georgia", "Lucida Console", "MS Sans Serif", "Tahoma", "Times New Roman", "Trebuchet MS", "Verdana" }; + + private static readonly Random _Rand = new Random(); + private static string _Separator = ":-:"; + private readonly Style _ErrorStyle = new Style(); + private readonly Style _TextBoxStyle = new Style(); + private Color _BackGroundColor = Color.Transparent; + private string _BackGroundImage = string.Empty; + private string _CaptchaChars = CHARS_DEFAULT; + private Unit _CaptchaHeight = Unit.Pixel(100); + private int _CaptchaLength = LENGTH_DEFAULT; + private string _CaptchaText; + private Unit _CaptchaWidth = Unit.Pixel(300); + private int _Expiration; + private bool _IsValid; + private string _RenderUrl = RENDERURL_DEFAULT; + private string _UserText = string.Empty; + private Image _image; + + public CaptchaControl() + { + this.ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile); + this.Text = Localization.GetString("CaptchaText.Text", Localization.SharedResourceFile); + this._Expiration = HostController.Instance.GetInteger("EXPIRATION_DEFAULT", EXPIRATION_DEFAULT); + } + + public event ServerValidateEventHandler UserValidated; + + /// + /// Gets or sets and sets the BackGroundColor. + /// + [Category("Appearance")] + [Description("The Background Color to use for the Captcha Image.")] + public Color BackGroundColor + { + get + { + return this._BackGroundColor; + } + + set + { + this._BackGroundColor = value; + } + } + + /// + /// Gets or sets and sets the BackGround Image. + /// + [Category("Appearance")] + [Description("A Background Image to use for the Captcha Image.")] + public string BackGroundImage + { + get + { + return this._BackGroundImage; + } + + set + { + this._BackGroundImage = value; + } + } + + private bool IsDesignMode + { + get + { + return HttpContext.Current == null; + } + } + + /// + /// Gets or sets and sets the list of characters. + /// + [Category("Behavior")] + [DefaultValue(CHARS_DEFAULT)] + [Description("Characters used to render CAPTCHA text. A character will be picked randomly from the string.")] + public string CaptchaChars + { + get + { + return this._CaptchaChars; + } + + set + { + this._CaptchaChars = value; + } + } + + /// + /// Gets or sets and sets the height of the Captcha image. + /// + [Category("Appearance")] + [Description("Height of Captcha Image.")] + public Unit CaptchaHeight + { + get + { + return this._CaptchaHeight; + } + + set + { + this._CaptchaHeight = value; + } + } + + /// + /// Gets or sets and sets the length of the Captcha string. + /// + [Category("Behavior")] + [DefaultValue(LENGTH_DEFAULT)] + [Description("Number of CaptchaChars used in the CAPTCHA text")] + public int CaptchaLength + { + get + { + return this._CaptchaLength; + } + + set + { + this._CaptchaLength = value; + } + } + + /// + /// Gets or sets and sets the width of the Captcha image. + /// + [Category("Appearance")] + [Description("Width of Captcha Image.")] + public Unit CaptchaWidth + { + get + { + return this._CaptchaWidth; + } + + set + { + this._CaptchaWidth = value; + } + } + + /// + /// Gets or sets a value indicating whether gets and sets whether the Viewstate is enabled. + /// + [Browsable(false)] + public override bool EnableViewState + { + get + { + return base.EnableViewState; + } + + set + { + base.EnableViewState = value; + } + } + + /// + /// Gets or sets and sets the ErrorMessage to display if the control is invalid. + /// + [Category("Behavior")] + [Description("The Error Message to display if invalid.")] + [DefaultValue("")] + public string ErrorMessage { get; set; } + + /// + /// Gets and sets the BackGroundColor. + /// + [Browsable(true)] + [Category("Appearance")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Error Message Control.")] + public Style ErrorStyle + { + get + { + return this._ErrorStyle; + } + } + + /// + /// Gets or sets and sets the Expiration time in seconds. + /// + [Category("Behavior")] + [Description("The duration of time (seconds) a user has before the challenge expires.")] + [DefaultValue(EXPIRATION_DEFAULT)] + public int Expiration + { + get + { + return this._Expiration; + } + + set + { + this._Expiration = value; + } + } + + /// + /// Gets a value indicating whether gets whether the control is valid. + /// + [Category("Validation")] + [Description("Returns True if the user was CAPTCHA validated after a postback.")] + public bool IsValid + { + get + { + return this._IsValid; + } + } + + /// + /// Gets or sets and sets the Url to use to render the control. + /// + [Category("Behavior")] + [Description("The URL used to render the image to the client.")] + [DefaultValue(RENDERURL_DEFAULT)] + public string RenderUrl + { + get + { + return this._RenderUrl; + } + + set + { + this._RenderUrl = value; + } + } + + /// + /// Gets or sets and sets the Help Text to use. + /// + [Category("Captcha")] + [DefaultValue("Enter the code shown above:")] + [Description("Instructional text displayed next to CAPTCHA image.")] + public string Text { get; set; } + + /// + /// Gets the Style to use for the Text Box. + /// + [Browsable(true)] + [Category("Appearance")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Text Box Control.")] + public Style TextBoxStyle + { + get + { + return this._TextBoxStyle; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// LoadPostData loads the Post Back Data and determines whether the value has change. + /// + /// A key to the PostBack Data to load. + /// A name value collection of postback data. + /// + /// ----------------------------------------------------------------------------- + public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + this._UserText = postCollection[postDataKey]; + this.Validate(this._UserText); + if (!this._IsValid && !string.IsNullOrEmpty(this._UserText)) + { + this._CaptchaText = this.GetNextCaptcha(); + } + + return false; + } + + /// ----------------------------------------------------------------------------- + /// + /// RaisePostDataChangedEvent runs when the PostBackData has changed. + /// + /// ----------------------------------------------------------------------------- + public void RaisePostDataChangedEvent() + { + } + + /// + /// Validates the posted back data. + /// + /// The user entered data. + /// + public bool Validate(string userData) + { + var cacheKey = string.Format(DataCache.CaptchaCacheKey, userData); + var cacheObj = DataCache.GetCache(cacheKey); + + if (cacheObj == null) + { + this._IsValid = false; + } + else + { + this._IsValid = true; + DataCache.RemoveCache(cacheKey); + } - /// - /// The CaptchaControl control provides a Captcha Challenge control - /// - /// - /// - [ToolboxData("<{0}:CaptchaControl Runat=\"server\" CaptchaHeight=\"100px\" CaptchaWidth=\"300px\" />")] - public class CaptchaControl : WebControl, INamingContainer, IPostBackDataHandler - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (CaptchaControl)); - - #region Private Constants - - private const int EXPIRATION_DEFAULT = 120; - private const int LENGTH_DEFAULT = 6; - private const string RENDERURL_DEFAULT = "ImageChallenge.captcha.aspx"; - private const string CHARS_DEFAULT = "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; - - #endregion - - #region Friend Constants - - internal const string KEY = "captcha"; - - #endregion - - #region Private Members - - private static readonly string[] _FontFamilies = {"Arial", "Comic Sans MS", "Courier New", "Georgia", "Lucida Console", "MS Sans Serif", "Tahoma", "Times New Roman", "Trebuchet MS", "Verdana"}; - - private static readonly Random _Rand = new Random(); - private static string _Separator = ":-:"; - private readonly Style _ErrorStyle = new Style(); - private readonly Style _TextBoxStyle = new Style(); - private Color _BackGroundColor = Color.Transparent; - private string _BackGroundImage = ""; - private string _CaptchaChars = CHARS_DEFAULT; - private Unit _CaptchaHeight = Unit.Pixel(100); - private int _CaptchaLength = LENGTH_DEFAULT; - private string _CaptchaText; - private Unit _CaptchaWidth = Unit.Pixel(300); - private int _Expiration; - private bool _IsValid; - private string _RenderUrl = RENDERURL_DEFAULT; - private string _UserText = ""; - private Image _image; - - #endregion - - #region Constructors - - public CaptchaControl() - { - ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile); - Text = Localization.GetString("CaptchaText.Text", Localization.SharedResourceFile); - _Expiration = HostController.Instance.GetInteger("EXPIRATION_DEFAULT", EXPIRATION_DEFAULT); - } - - #endregion - - #region Private Properties - - private bool IsDesignMode - { - get - { - return HttpContext.Current == null; - } - } - - #endregion - - #region Public Properties - - /// - /// Gets and sets the BackGroundColor - /// - [Category("Appearance"), Description("The Background Color to use for the Captcha Image.")] - public Color BackGroundColor - { - get - { - return _BackGroundColor; - } - set - { - _BackGroundColor = value; - } - } - - /// - /// Gets and sets the BackGround Image - /// - [Category("Appearance"), Description("A Background Image to use for the Captcha Image.")] - public string BackGroundImage - { - get - { - return _BackGroundImage; - } - set - { - _BackGroundImage = value; - } - } - - /// - /// Gets and sets the list of characters - /// - [Category("Behavior"), DefaultValue(CHARS_DEFAULT), Description("Characters used to render CAPTCHA text. A character will be picked randomly from the string.")] - public string CaptchaChars - { - get - { - return _CaptchaChars; - } - set - { - _CaptchaChars = value; - } - } - - /// - /// Gets and sets the height of the Captcha image - /// - [Category("Appearance"), Description("Height of Captcha Image.")] - public Unit CaptchaHeight - { - get - { - return _CaptchaHeight; - } - set - { - _CaptchaHeight = value; - } - } - - /// - /// Gets and sets the length of the Captcha string - /// - [Category("Behavior"), DefaultValue(LENGTH_DEFAULT), Description("Number of CaptchaChars used in the CAPTCHA text")] - public int CaptchaLength - { - get - { - return _CaptchaLength; - } - set - { - _CaptchaLength = value; - } - } - - /// - /// Gets and sets the width of the Captcha image - /// - [Category("Appearance"), Description("Width of Captcha Image.")] - public Unit CaptchaWidth - { - get - { - return _CaptchaWidth; - } - set - { - _CaptchaWidth = value; - } - } - - /// - /// Gets and sets whether the Viewstate is enabled - /// - [Browsable(false)] - public override bool EnableViewState - { - get - { - return base.EnableViewState; - } - set - { - base.EnableViewState = value; - } - } - - /// - /// Gets and sets the ErrorMessage to display if the control is invalid - /// - [Category("Behavior"), Description("The Error Message to display if invalid."), DefaultValue("")] - public string ErrorMessage { get; set; } - - /// - /// Gets and sets the BackGroundColor - /// - [Browsable(true), Category("Appearance"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), - Description("Set the Style for the Error Message Control.")] - public Style ErrorStyle - { - get - { - return _ErrorStyle; - } - } - - /// - /// Gets and sets the Expiration time in seconds - /// - [Category("Behavior"), Description("The duration of time (seconds) a user has before the challenge expires."), DefaultValue(EXPIRATION_DEFAULT)] - public int Expiration - { - get - { - return _Expiration; - } - set - { - _Expiration = value; - } - } - - /// - /// Gets whether the control is valid - /// - [Category("Validation"), Description("Returns True if the user was CAPTCHA validated after a postback.")] - public bool IsValid - { - get - { - return _IsValid; - } - } - - /// - /// Gets and sets the Url to use to render the control - /// - [Category("Behavior"), Description("The URL used to render the image to the client."), DefaultValue(RENDERURL_DEFAULT)] - public string RenderUrl - { - get - { - return _RenderUrl; - } - set - { - _RenderUrl = value; - } - } - - /// - /// Gets and sets the Help Text to use - /// - [Category("Captcha"), DefaultValue("Enter the code shown above:"), Description("Instructional text displayed next to CAPTCHA image.")] - public string Text { get; set; } - - /// - /// Gets the Style to use for the Text Box - /// - [Browsable(true), Category("Appearance"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), - Description("Set the Style for the Text Box Control.")] - public Style TextBoxStyle - { - get - { - return _TextBoxStyle; - } - } - - #region IPostBackDataHandler Members - - /// ----------------------------------------------------------------------------- - /// - /// LoadPostData loads the Post Back Data and determines whether the value has change - /// - /// A key to the PostBack Data to load - /// A name value collection of postback data - /// ----------------------------------------------------------------------------- - public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - _UserText = postCollection[postDataKey]; - Validate(_UserText); - if (!_IsValid && !string.IsNullOrEmpty(_UserText)) - { - _CaptchaText = GetNextCaptcha(); - } - return false; - } - - /// ----------------------------------------------------------------------------- - /// - /// RaisePostDataChangedEvent runs when the PostBackData has changed. - /// - /// ----------------------------------------------------------------------------- - public void RaisePostDataChangedEvent() - { - } - - #endregion - - #endregion - - #region Public Events - - - public event ServerValidateEventHandler UserValidated; - - #endregion - - #region Private Methods - - /// - /// Builds the url for the Handler - /// - private string GetUrl() - { - var url = ResolveUrl(RenderUrl); - url += "?" + KEY + "=" + Encrypt(EncodeTicket(), DateTime.Now.AddSeconds(Expiration)); - - //Append the Alias to the url so that it doesn't lose track of the alias it's currently on - var _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - url += "&alias=" + _portalSettings.PortalAlias.HTTPAlias; - return url; - } - - /// - /// Encodes the querystring to pass to the Handler - /// - private string EncodeTicket() - { - var sb = new StringBuilder(); - - sb.Append(CaptchaWidth.Value.ToString()); - sb.Append(_Separator + CaptchaHeight.Value); - sb.Append(_Separator + _CaptchaText); - sb.Append(_Separator + BackGroundImage); - - return sb.ToString(); - } - - #endregion - - #region Shared/Static Methods - - /// - /// Creates the Image - /// - /// The width of the image - /// The height of the image - private static Bitmap CreateImage(int width, int height) - { - var bmp = new Bitmap(width, height); - Graphics g; - var rect = new Rectangle(0, 0, width, height); - var rectF = new RectangleF(0, 0, width, height); - - g = Graphics.FromImage(bmp); - - Brush b = new LinearGradientBrush(rect, - Color.FromArgb(_Rand.Next(224), _Rand.Next(224), _Rand.Next(224)), - Color.FromArgb(_Rand.Next(224), _Rand.Next(224), _Rand.Next(224)), - Convert.ToSingle(_Rand.NextDouble())*360, - false); - g.FillRectangle(b, rectF); - - if (_Rand.Next(2) == 1) - { - DistortImage(ref bmp, _Rand.Next(5, 20)); - } - else - { - DistortImage(ref bmp, -_Rand.Next(5, 20)); - } - return bmp; - } - - /// - /// Creates the Text - /// - /// The text to display - /// The width of the image - /// The height of the image - /// Graphic draw context. - private static GraphicsPath CreateText(string text, int width, int height, Graphics g) - { - var textPath = new GraphicsPath(); - var ff = GetFont(); - var emSize = Convert.ToInt32(width*2/text.Length); - Font f = null; - try - { - var measured = new SizeF(0, 0); - var workingSize = new SizeF(width, height); - while ((emSize > 2)) - { - f = new Font(ff, emSize); - measured = g.MeasureString(text, f); - if (!(measured.Width > workingSize.Width || measured.Height > workingSize.Height)) - { - break; - } - f.Dispose(); - emSize -= 2; - } - emSize += 8; - f = new Font(ff, emSize); - - var fmt = new StringFormat(); - fmt.Alignment = StringAlignment.Center; - fmt.LineAlignment = StringAlignment.Center; - - textPath.AddString(text, f.FontFamily, Convert.ToInt32(f.Style), f.Size, new RectangleF(0, 0, width, height), fmt); - WarpText(ref textPath, new Rectangle(0, 0, width, height)); - } - catch (Exception exc) - { - Logger.Error(exc); - - } - finally - { - f.Dispose(); - } - return textPath; - } - - /// ----------------------------------------------------------------------------- - /// - /// Decrypts the CAPTCHA Text - /// - /// The encrypted text - /// ----------------------------------------------------------------------------- - private static string Decrypt(string encryptedContent) - { - string decryptedText = string.Empty; - try - { - FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedContent); - if ((!ticket.Expired)) - { - decryptedText = ticket.UserData; - } - } - catch (ArgumentException exc) - { - Logger.Debug(exc); - - } - return decryptedText; - } - - /// ----------------------------------------------------------------------------- - /// - /// DistortImage distorts the captcha image - /// - /// The Image to distort - /// Distortion. - /// ----------------------------------------------------------------------------- - private static void DistortImage(ref Bitmap b, double distortion) - { - int width = b.Width; - int height = b.Height; - - var copy = (Bitmap) b.Clone(); - for (int y = 0; y <= height - 1; y++) - { - for (int x = 0; x <= width - 1; x++) - { - int newX = Convert.ToInt32(x + (distortion*Math.Sin(Math.PI*y/64.0))); - int newY = Convert.ToInt32(y + (distortion*Math.Cos(Math.PI*x/64.0))); - if ((newX < 0 || newX >= width)) - { - newX = 0; - } - if ((newY < 0 || newY >= height)) - { - newY = 0; - } - b.SetPixel(x, y, copy.GetPixel(newX, newY)); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Encrypts the CAPTCHA Text - /// - /// The text to encrypt - /// The time the ticket expires - /// ----------------------------------------------------------------------------- - private static string Encrypt(string content, DateTime expiration) - { - var ticket = new FormsAuthenticationTicket(1, HttpContext.Current.Request.UserHostAddress, DateTime.Now, expiration, false, content); - return FormsAuthentication.Encrypt(ticket); - } - - /// ----------------------------------------------------------------------------- - /// - /// GenerateImage generates the Captch Image - /// - /// The Encrypted Text to display - /// ----------------------------------------------------------------------------- - internal static Bitmap GenerateImage(string encryptedText) - { - string encodedText = Decrypt(encryptedText); - Bitmap bmp = null; - string[] Settings = Regex.Split(encodedText, _Separator); - try - { + this.OnUserValidated(new ServerValidateEventArgs(this._CaptchaText, this._IsValid)); + return this._IsValid; + } + + /// ----------------------------------------------------------------------------- + /// + /// GenerateImage generates the Captch Image. + /// + /// The Encrypted Text to display. + /// + /// ----------------------------------------------------------------------------- + internal static Bitmap GenerateImage(string encryptedText) + { + string encodedText = Decrypt(encryptedText); + Bitmap bmp = null; + string[] Settings = Regex.Split(encodedText, _Separator); + try + { int width; int height; if (int.TryParse(Settings[0], out width) && int.TryParse(Settings[1], out height)) @@ -549,7 +380,7 @@ internal static Bitmap GenerateImage(string encryptedText) Graphics g; Brush b = new SolidBrush(Color.LightGray); Brush b1 = new SolidBrush(Color.Black); - if (String.IsNullOrEmpty(backgroundImage)) + if (string.IsNullOrEmpty(backgroundImage)) { bmp = CreateImage(width, height); } @@ -557,11 +388,12 @@ internal static Bitmap GenerateImage(string encryptedText) { bmp = (Bitmap)System.Drawing.Image.FromFile(HttpContext.Current.Request.MapPath(backgroundImage)); } + g = Graphics.FromImage(bmp); - //Create Text + // Create Text GraphicsPath textPath = CreateText(text, width, height, g); - if (String.IsNullOrEmpty(backgroundImage)) + if (string.IsNullOrEmpty(backgroundImage)) { g.FillPath(b, textPath); } @@ -569,300 +401,464 @@ internal static Bitmap GenerateImage(string encryptedText) { g.FillPath(b1, textPath); } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - return bmp; - } - - /// ----------------------------------------------------------------------------- - /// - /// GetFont gets a random font to use for the Captcha Text - /// - /// ----------------------------------------------------------------------------- - private static FontFamily GetFont() - { - FontFamily _font = null; - while (_font == null) - { - try - { - _font = new FontFamily(_FontFamilies[_Rand.Next(_FontFamilies.Length)]); - } - catch (Exception exc) - { - Logger.Error(exc); - - _font = null; - } - } - return _font; - } - - /// ----------------------------------------------------------------------------- - /// - /// Generates a random point - /// - /// The minimum x value - /// The maximum x value - /// The minimum y value - /// The maximum y value - /// ----------------------------------------------------------------------------- - private static PointF RandomPoint(int xmin, int xmax, int ymin, int ymax) - { - return new PointF(_Rand.Next(xmin, xmax), _Rand.Next(ymin, ymax)); - } - - /// ----------------------------------------------------------------------------- - /// - /// Warps the Text - /// - /// The Graphics Path for the text - /// a rectangle which defines the image - /// ----------------------------------------------------------------------------- - private static void WarpText(ref GraphicsPath textPath, Rectangle rect) - { - int intWarpDivisor; - var rectF = new RectangleF(0, 0, rect.Width, rect.Height); - - intWarpDivisor = _Rand.Next(4, 8); - - int intHrange = Convert.ToInt32(rect.Height/intWarpDivisor); - int intWrange = Convert.ToInt32(rect.Width/intWarpDivisor); - - PointF p1 = RandomPoint(0, intWrange, 0, intHrange); - PointF p2 = RandomPoint(rect.Width - (intWrange - Convert.ToInt32(p1.X)), rect.Width, 0, intHrange); - PointF p3 = RandomPoint(0, intWrange, rect.Height - (intHrange - Convert.ToInt32(p1.Y)), rect.Height); - PointF p4 = RandomPoint(rect.Width - (intWrange - Convert.ToInt32(p3.X)), rect.Width, rect.Height - (intHrange - Convert.ToInt32(p2.Y)), rect.Height); - - var points = new[] {p1, p2, p3, p4}; - var m = new Matrix(); - m.Translate(0, 0); - textPath.Warp(points, rectF, m, WarpMode.Perspective, 0); - } - - #endregion - - #region "Protected Methods" - - /// - /// Creates the child controls - /// - protected override void CreateChildControls() - { - base.CreateChildControls(); - - if ((CaptchaWidth.IsEmpty || CaptchaWidth.Type != UnitType.Pixel || CaptchaHeight.IsEmpty || CaptchaHeight.Type != UnitType.Pixel)) - { - throw new InvalidOperationException("Must specify size of control in pixels."); - } - _image = new Image {BorderColor = BorderColor, BorderStyle = BorderStyle, BorderWidth = BorderWidth, ToolTip = ToolTip, EnableViewState = false}; - Controls.Add(_image); - } - - /// - /// Gets the next Captcha - /// - protected virtual string GetNextCaptcha() - { - - var sb = new StringBuilder(); - var rand = new Random(); - int n; - var intMaxLength = CaptchaChars.Length; - - for (n = 0; n <= CaptchaLength - 1; n++) - { - sb.Append(CaptchaChars.Substring(rand.Next(intMaxLength), 1)); - } - var challenge = sb.ToString(); - - //NOTE: this could be a problem in a web farm using in-memory caching where + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + + return bmp; + } + + /// + /// Creates the child controls. + /// + protected override void CreateChildControls() + { + base.CreateChildControls(); + + if (this.CaptchaWidth.IsEmpty || this.CaptchaWidth.Type != UnitType.Pixel || this.CaptchaHeight.IsEmpty || this.CaptchaHeight.Type != UnitType.Pixel) + { + throw new InvalidOperationException("Must specify size of control in pixels."); + } + + this._image = new Image { BorderColor = this.BorderColor, BorderStyle = this.BorderStyle, BorderWidth = this.BorderWidth, ToolTip = this.ToolTip, EnableViewState = false }; + this.Controls.Add(this._image); + } + + /// + /// Gets the next Captcha. + /// + /// + protected virtual string GetNextCaptcha() + { + var sb = new StringBuilder(); + var rand = new Random(); + int n; + var intMaxLength = this.CaptchaChars.Length; + + for (n = 0; n <= this.CaptchaLength - 1; n++) + { + sb.Append(this.CaptchaChars.Substring(rand.Next(intMaxLength), 1)); + } + + var challenge = sb.ToString(); + + // NOTE: this could be a problem in a web farm using in-memory caching where // the request might go to another server in the farm. Also, in a system // with a single server or web-farm, the cache might be cleared // which will cause a problem in such case unless sticky sessions are used. var cacheKey = string.Format(DataCache.CaptchaCacheKey, challenge); - DataCache.SetCache(cacheKey, challenge, (DNNCacheDependency)null, DateTime.Now.AddSeconds(_Expiration + 1), + DataCache.SetCache(cacheKey, challenge, (DNNCacheDependency)null, DateTime.Now.AddSeconds(this._Expiration + 1), Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null); - return challenge; - } - - /// - /// Loads the previously saved Viewstate - /// - /// The saved state - protected override void LoadViewState(object savedState) - { + return challenge; + } + + /// + /// Creates the Image. + /// + /// The width of the image. + /// The height of the image. + private static Bitmap CreateImage(int width, int height) + { + var bmp = new Bitmap(width, height); + Graphics g; + var rect = new Rectangle(0, 0, width, height); + var rectF = new RectangleF(0, 0, width, height); + + g = Graphics.FromImage(bmp); + + Brush b = new LinearGradientBrush( + rect, + Color.FromArgb(_Rand.Next(224), _Rand.Next(224), _Rand.Next(224)), + Color.FromArgb(_Rand.Next(224), _Rand.Next(224), _Rand.Next(224)), + Convert.ToSingle(_Rand.NextDouble()) * 360, + false); + g.FillRectangle(b, rectF); + + if (_Rand.Next(2) == 1) + { + DistortImage(ref bmp, _Rand.Next(5, 20)); + } + else + { + DistortImage(ref bmp, -_Rand.Next(5, 20)); + } + + return bmp; + } + + /// + /// Creates the Text. + /// + /// The text to display. + /// The width of the image. + /// The height of the image. + /// Graphic draw context. + private static GraphicsPath CreateText(string text, int width, int height, Graphics g) + { + var textPath = new GraphicsPath(); + var ff = GetFont(); + var emSize = Convert.ToInt32(width * 2 / text.Length); + Font f = null; + try + { + var measured = new SizeF(0, 0); + var workingSize = new SizeF(width, height); + while (emSize > 2) + { + f = new Font(ff, emSize); + measured = g.MeasureString(text, f); + if (!(measured.Width > workingSize.Width || measured.Height > workingSize.Height)) + { + break; + } + + f.Dispose(); + emSize -= 2; + } + + emSize += 8; + f = new Font(ff, emSize); + + var fmt = new StringFormat(); + fmt.Alignment = StringAlignment.Center; + fmt.LineAlignment = StringAlignment.Center; + + textPath.AddString(text, f.FontFamily, Convert.ToInt32(f.Style), f.Size, new RectangleF(0, 0, width, height), fmt); + WarpText(ref textPath, new Rectangle(0, 0, width, height)); + } + catch (Exception exc) + { + Logger.Error(exc); + } + finally + { + f.Dispose(); + } + + return textPath; + } + + /// + /// Builds the url for the Handler. + /// + private string GetUrl() + { + var url = this.ResolveUrl(this.RenderUrl); + url += "?" + KEY + "=" + Encrypt(this.EncodeTicket(), DateTime.Now.AddSeconds(this.Expiration)); + + // Append the Alias to the url so that it doesn't lose track of the alias it's currently on + var _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + url += "&alias=" + _portalSettings.PortalAlias.HTTPAlias; + return url; + } + + /// + /// Encodes the querystring to pass to the Handler. + /// + private string EncodeTicket() + { + var sb = new StringBuilder(); + + sb.Append(this.CaptchaWidth.Value.ToString()); + sb.Append(_Separator + this.CaptchaHeight.Value); + sb.Append(_Separator + this._CaptchaText); + sb.Append(_Separator + this.BackGroundImage); + + return sb.ToString(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Decrypts the CAPTCHA Text. + /// + /// The encrypted text. + /// ----------------------------------------------------------------------------- + private static string Decrypt(string encryptedContent) + { + string decryptedText = string.Empty; + try + { + FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedContent); + if (!ticket.Expired) + { + decryptedText = ticket.UserData; + } + } + catch (ArgumentException exc) + { + Logger.Debug(exc); + } + + return decryptedText; + } + + /// ----------------------------------------------------------------------------- + /// + /// DistortImage distorts the captcha image. + /// + /// The Image to distort. + /// Distortion. + /// ----------------------------------------------------------------------------- + private static void DistortImage(ref Bitmap b, double distortion) + { + int width = b.Width; + int height = b.Height; + + var copy = (Bitmap)b.Clone(); + for (int y = 0; y <= height - 1; y++) + { + for (int x = 0; x <= width - 1; x++) + { + int newX = Convert.ToInt32(x + (distortion * Math.Sin(Math.PI * y / 64.0))); + int newY = Convert.ToInt32(y + (distortion * Math.Cos(Math.PI * x / 64.0))); + if (newX < 0 || newX >= width) + { + newX = 0; + } + + if (newY < 0 || newY >= height) + { + newY = 0; + } + + b.SetPixel(x, y, copy.GetPixel(newX, newY)); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Encrypts the CAPTCHA Text. + /// + /// The text to encrypt. + /// The time the ticket expires. + /// ----------------------------------------------------------------------------- + private static string Encrypt(string content, DateTime expiration) + { + var ticket = new FormsAuthenticationTicket(1, HttpContext.Current.Request.UserHostAddress, DateTime.Now, expiration, false, content); + return FormsAuthentication.Encrypt(ticket); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetFont gets a random font to use for the Captcha Text. + /// + /// ----------------------------------------------------------------------------- + private static FontFamily GetFont() + { + FontFamily _font = null; + while (_font == null) + { + try + { + _font = new FontFamily(_FontFamilies[_Rand.Next(_FontFamilies.Length)]); + } + catch (Exception exc) + { + Logger.Error(exc); + + _font = null; + } + } + + return _font; + } + + /// ----------------------------------------------------------------------------- + /// + /// Generates a random point. + /// + /// The minimum x value. + /// The maximum x value. + /// The minimum y value. + /// The maximum y value. + /// ----------------------------------------------------------------------------- + private static PointF RandomPoint(int xmin, int xmax, int ymin, int ymax) + { + return new PointF(_Rand.Next(xmin, xmax), _Rand.Next(ymin, ymax)); + } + + /// ----------------------------------------------------------------------------- + /// + /// Warps the Text. + /// + /// The Graphics Path for the text. + /// a rectangle which defines the image. + /// ----------------------------------------------------------------------------- + private static void WarpText(ref GraphicsPath textPath, Rectangle rect) + { + int intWarpDivisor; + var rectF = new RectangleF(0, 0, rect.Width, rect.Height); + + intWarpDivisor = _Rand.Next(4, 8); + + int intHrange = Convert.ToInt32(rect.Height / intWarpDivisor); + int intWrange = Convert.ToInt32(rect.Width / intWarpDivisor); + + PointF p1 = RandomPoint(0, intWrange, 0, intHrange); + PointF p2 = RandomPoint(rect.Width - (intWrange - Convert.ToInt32(p1.X)), rect.Width, 0, intHrange); + PointF p3 = RandomPoint(0, intWrange, rect.Height - (intHrange - Convert.ToInt32(p1.Y)), rect.Height); + PointF p4 = RandomPoint(rect.Width - (intWrange - Convert.ToInt32(p3.X)), rect.Width, rect.Height - (intHrange - Convert.ToInt32(p2.Y)), rect.Height); + + var points = new[] { p1, p2, p3, p4 }; + var m = new Matrix(); + m.Translate(0, 0); + textPath.Warp(points, rectF, m, WarpMode.Perspective, 0); + } + + /// + /// Loads the previously saved Viewstate. + /// + /// The saved state. + protected override void LoadViewState(object savedState) + { if (savedState != null) { - //Load State from the array of objects that was saved at SaveViewState. + // Load State from the array of objects that was saved at SaveViewState. var myState = (object[])savedState; - //Load the ViewState of the Base Control + // Load the ViewState of the Base Control if (myState[0] != null) { base.LoadViewState(myState[0]); } - //Load the CAPTCHA Text from the ViewState + // Load the CAPTCHA Text from the ViewState if (myState[1] != null) { - _CaptchaText = Convert.ToString(myState[1]); + this._CaptchaText = Convert.ToString(myState[1]); } } - //var cacheKey = string.Format(DataCache.CaptchaCacheKey, masterPortalId); - //_CaptchaText - - } + + // var cacheKey = string.Format(DataCache.CaptchaCacheKey, masterPortalId); + // _CaptchaText + } - /// - /// Runs just before the control is to be rendered - /// - protected override void OnPreRender(EventArgs e) - { - //Generate Random Challenge Text - _CaptchaText = GetNextCaptcha(); + /// + /// Runs just before the control is to be rendered. + /// + protected override void OnPreRender(EventArgs e) + { + // Generate Random Challenge Text + this._CaptchaText = this.GetNextCaptcha(); - //Enable Viewstate Encryption - Page.RegisterRequiresViewStateEncryption(); + // Enable Viewstate Encryption + this.Page.RegisterRequiresViewStateEncryption(); - //Call Base Class method - base.OnPreRender(e); - } + // Call Base Class method + base.OnPreRender(e); + } protected virtual void OnUserValidated(ServerValidateEventArgs e) { - ServerValidateEventHandler handler = UserValidated; + ServerValidateEventHandler handler = this.UserValidated; if (handler != null) { handler(this, e); } } - /// - /// Render the control - /// - /// An Html Text Writer - protected override void Render(HtmlTextWriter writer) - { - ControlStyle.AddAttributesToRender(writer); - - //Render outer
    Tag - writer.AddAttribute("class", "dnnLeft"); - writer.RenderBeginTag(HtmlTextWriterTag.Div); - - //Render image Tag - writer.AddAttribute(HtmlTextWriterAttribute.Src, GetUrl()); - writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); - if (!String.IsNullOrEmpty(ToolTip)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Alt, ToolTip); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Alt, Localization.GetString("CaptchaAlt.Text", Localization.SharedResourceFile)); - } - writer.RenderBeginTag(HtmlTextWriterTag.Img); - writer.RenderEndTag(); - - //Render Help Text - if (!String.IsNullOrEmpty(Text)) - { - writer.RenderBeginTag(HtmlTextWriterTag.Div); - writer.Write(Text); - writer.RenderEndTag(); - } - - //Render text box Tag - TextBoxStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Style, "width:" + Width); - writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, _CaptchaText.Length.ToString()); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - if (!String.IsNullOrEmpty(AccessKey)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, AccessKey); - } - if (!Enabled) - { - writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); - } - if (TabIndex > 0) - { - writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, TabIndex.ToString()); - } - if (_UserText == _CaptchaText) - { - writer.AddAttribute(HtmlTextWriterAttribute.Value, _UserText); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Value, ""); - } - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.RenderEndTag(); - - //Render error message - if (!IsValid && Page.IsPostBack && !string.IsNullOrEmpty(_UserText)) - { - ErrorStyle.AddAttributesToRender(writer); - writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(ErrorMessage); - writer.RenderEndTag(); - } - - //Render
    - writer.RenderEndTag(); - } - - /// - /// Save the controls Voewstate - /// - protected override object SaveViewState() - { - var baseState = base.SaveViewState(); - var allStates = new object[2]; - allStates[0] = baseState; - if (string.IsNullOrEmpty(_CaptchaText)) - { - _CaptchaText = GetNextCaptcha(); - } - allStates[1] = _CaptchaText; - - return allStates; - } - - #endregion - - #region Public Methods - - /// - /// Validates the posted back data - /// - /// The user entered data - public bool Validate(string userData) - { - var cacheKey = string.Format(DataCache.CaptchaCacheKey, userData); - var cacheObj = DataCache.GetCache(cacheKey); + /// + /// Render the control. + /// + /// An Html Text Writer. + protected override void Render(HtmlTextWriter writer) + { + this.ControlStyle.AddAttributesToRender(writer); - if (cacheObj == null) - { - _IsValid = false; - } - else - { - _IsValid = true; - DataCache.RemoveCache(cacheKey); - } - - OnUserValidated(new ServerValidateEventArgs(_CaptchaText, _IsValid)); - return _IsValid; - } - - #endregion - - } + // Render outer
    Tag + writer.AddAttribute("class", "dnnLeft"); + writer.RenderBeginTag(HtmlTextWriterTag.Div); + + // Render image Tag + writer.AddAttribute(HtmlTextWriterAttribute.Src, this.GetUrl()); + writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); + if (!string.IsNullOrEmpty(this.ToolTip)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Alt, this.ToolTip); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Alt, Localization.GetString("CaptchaAlt.Text", Localization.SharedResourceFile)); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Img); + writer.RenderEndTag(); + + // Render Help Text + if (!string.IsNullOrEmpty(this.Text)) + { + writer.RenderBeginTag(HtmlTextWriterTag.Div); + writer.Write(this.Text); + writer.RenderEndTag(); + } + + // Render text box Tag + this.TextBoxStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); + writer.AddAttribute(HtmlTextWriterAttribute.Style, "width:" + this.Width); + writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this._CaptchaText.Length.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + if (!string.IsNullOrEmpty(this.AccessKey)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, this.AccessKey); + } + + if (!this.Enabled) + { + writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); + } + + if (this.TabIndex > 0) + { + writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, this.TabIndex.ToString()); + } + + if (this._UserText == this._CaptchaText) + { + writer.AddAttribute(HtmlTextWriterAttribute.Value, this._UserText); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Value, string.Empty); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.RenderEndTag(); + + // Render error message + if (!this.IsValid && this.Page.IsPostBack && !string.IsNullOrEmpty(this._UserText)) + { + this.ErrorStyle.AddAttributesToRender(writer); + writer.RenderBeginTag(HtmlTextWriterTag.Span); + writer.Write(this.ErrorMessage); + writer.RenderEndTag(); + } + + // Render
    + writer.RenderEndTag(); + } + + /// + /// Save the controls Voewstate. + /// + /// + protected override object SaveViewState() + { + var baseState = base.SaveViewState(); + var allStates = new object[2]; + allStates[0] = baseState; + if (string.IsNullOrEmpty(this._CaptchaText)) + { + this._CaptchaText = this.GetNextCaptcha(); + } + + allStates[1] = this._CaptchaText; + + return allStates; + } + } } diff --git a/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs b/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs index 8f854d88fcf..4f34a986823 100644 --- a/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs +++ b/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs @@ -1,34 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Specialized; -using System.Drawing; -using System.Drawing.Imaging; -using System.Web; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Collections.Specialized; + using System.Drawing; + using System.Drawing.Imaging; + using System.Web; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: CaptchaHandler /// ----------------------------------------------------------------------------- /// - /// The CaptchaHandler control provides a validator to validate a CAPTCHA Challenge + /// The CaptchaHandler control provides a validator to validate a CAPTCHA Challenge. /// /// ----------------------------------------------------------------------------- public class CaptchaHandler : IHttpHandler { private const int MAX_IMAGE_WIDTH = 600; - private const int MAX_IMAGE_HEIGHT = 600; - - #region IHttpHandler Members - + private const int MAX_IMAGE_HEIGHT = 600; + public bool IsReusable { get @@ -47,8 +40,6 @@ public void ProcessRequest(HttpContext context) { bmp.Save(response.OutputStream, ImageFormat.Jpeg); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/CommandButton.cs b/DNN Platform/Library/UI/WebControls/CommandButton.cs index d0b10884793..72f7f951b65 100644 --- a/DNN Platform/Library/UI/WebControls/CommandButton.cs +++ b/DNN Platform/Library/UI/WebControls/CommandButton.cs @@ -1,27 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.UI.WebControls /// Project: DotNetNuke /// Class: CommandButton /// ----------------------------------------------------------------------------- /// - /// The CommandButton Class provides an enhanced Button control for DotNetNuke + /// The CommandButton Class provides an enhanced Button control for DotNetNuke. /// /// /// @@ -33,456 +28,473 @@ public class CommandButton : WebControl, INamingContainer private LinkButton link; private LiteralControl separator; + public event EventHandler Click; + + public event CommandEventHandler Command; + /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Separator between Buttons + /// Gets or sets the Separator between Buttons. /// - /// Defaults to 1 non-breaking spaces - /// A String + /// Defaults to 1 non-breaking spaces. + /// A String. /// ----------------------------------------------------------------------------- public string ButtonSeparator { get { - EnsureChildControls(); - return separator.Text; + this.EnsureChildControls(); + return this.separator.Text; } + set { - EnsureChildControls(); - separator.Text = value; + this.EnsureChildControls(); + this.separator.Text = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the control causes Validation to occur + /// Gets or sets a value indicating whether gets or sets whether the control causes Validation to occur. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. /// ----------------------------------------------------------------------------- public bool CausesValidation { get { - EnsureChildControls(); - return link.CausesValidation; + this.EnsureChildControls(); + return this.link.CausesValidation; } + set { - EnsureChildControls(); - icon.CausesValidation = value; - link.CausesValidation = value; + this.EnsureChildControls(); + this.icon.CausesValidation = value; + this.link.CausesValidation = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the command argument for this command button + /// Gets or sets the command argument for this command button. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string CommandArgument { get { - EnsureChildControls(); - return link.CommandArgument; + this.EnsureChildControls(); + return this.link.CommandArgument; } + set { - EnsureChildControls(); - icon.CommandArgument = value; - link.CommandArgument = value; + this.EnsureChildControls(); + this.icon.CommandArgument = value; + this.link.CommandArgument = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the command name for this command button + /// Gets or sets the command name for this command button. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string CommandName { get { - EnsureChildControls(); - return link.CommandName; + this.EnsureChildControls(); + return this.link.CommandName; } + set { - EnsureChildControls(); - icon.CommandName = value; - link.CommandName = value; + this.EnsureChildControls(); + this.icon.CommandName = value; + this.link.CommandName = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the link is displayed + /// Gets or sets a value indicating whether gets or sets whether the link is displayed. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. /// ----------------------------------------------------------------------------- public bool DisplayLink { get { - EnsureChildControls(); - return link.Visible; + this.EnsureChildControls(); + return this.link.Visible; } + set { - EnsureChildControls(); - link.Visible = value; + this.EnsureChildControls(); + this.link.Visible = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether the icon is displayed + /// Gets or sets a value indicating whether gets or sets whether the icon is displayed. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. /// ----------------------------------------------------------------------------- public bool DisplayIcon { get { - EnsureChildControls(); - return icon.Visible; + this.EnsureChildControls(); + return this.icon.Visible; } + set { - EnsureChildControls(); - icon.Visible = value; + this.EnsureChildControls(); + this.icon.Visible = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Image used for the Icon + /// Gets or sets the Image used for the Icon. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ImageUrl { get { - EnsureChildControls(); - if (string.IsNullOrEmpty(icon.ImageUrl)) - icon.ImageUrl = Entities.Icons.IconController.IconURL(IconKey, IconSize, IconStyle); - - return icon.ImageUrl; + this.EnsureChildControls(); + if (string.IsNullOrEmpty(this.icon.ImageUrl)) + { + this.icon.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); + } + + return this.icon.ImageUrl; } + set { - EnsureChildControls(); - icon.ImageUrl = value; + this.EnsureChildControls(); + this.icon.ImageUrl = value; } } /// ----------------------------------------------------------------------------- /// - /// The Icon Key to obtain ImageURL + /// Gets or sets the Icon Key to obtain ImageURL. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconKey { get; set; } /// ----------------------------------------------------------------------------- /// - /// The Icon Siz to obtain ImageURL + /// Gets or sets the Icon Siz to obtain ImageURL. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconSize { get; set; } /// ----------------------------------------------------------------------------- /// - /// The Icon Style to obtain ImageURL + /// Gets or sets the Icon Style to obtain ImageURL. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string IconStyle { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the "onClick" Attribute + /// Gets or sets the "onClick" Attribute. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string OnClick { get { - EnsureChildControls(); - return link.Attributes["onclick"]; + this.EnsureChildControls(); + return this.link.Attributes["onclick"]; } + set { - EnsureChildControls(); - if (String.IsNullOrEmpty(value)) + this.EnsureChildControls(); + if (string.IsNullOrEmpty(value)) { - icon.Attributes.Remove("onclick"); - link.Attributes.Remove("onclick"); + this.icon.Attributes.Remove("onclick"); + this.link.Attributes.Remove("onclick"); } else { - icon.Attributes.Add("onclick", value); - link.Attributes.Add("onclick", value); + this.icon.Attributes.Add("onclick", value); + this.link.Attributes.Add("onclick", value); } } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the "OnClientClick" Property + /// Gets or sets the "OnClientClick" Property. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string OnClientClick { get { - EnsureChildControls(); - return link.OnClientClick; + this.EnsureChildControls(); + return this.link.OnClientClick; } + set { - EnsureChildControls(); - icon.OnClientClick = value; - link.OnClientClick = value; + this.EnsureChildControls(); + this.icon.OnClientClick = value; + this.link.OnClientClick = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Resource Key used for the Control + /// Gets or sets the Resource Key used for the Control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ResourceKey { get { - EnsureChildControls(); - return link.Attributes["resourcekey"]; + this.EnsureChildControls(); + return this.link.Attributes["resourcekey"]; } + set { - EnsureChildControls(); - if (String.IsNullOrEmpty(value)) + this.EnsureChildControls(); + if (string.IsNullOrEmpty(value)) { - icon.Attributes.Remove("resourcekey"); - link.Attributes.Remove("resourcekey"); + this.icon.Attributes.Remove("resourcekey"); + this.link.Attributes.Remove("resourcekey"); } else { - icon.Attributes.Add("resourcekey", value); - link.Attributes.Add("resourcekey", value); + this.icon.Attributes.Add("resourcekey", value); + this.link.Attributes.Add("resourcekey", value); } } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Text used for the Control + /// Gets or sets the Text used for the Control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Text { get { - EnsureChildControls(); - return link.Text; + this.EnsureChildControls(); + return this.link.Text; } + set { - EnsureChildControls(); - link.Text = value; + this.EnsureChildControls(); + this.link.Text = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the tooltip resource key used for the Control + /// Gets or sets the tooltip resource key used for the Control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ToolTipKey { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Validation Group that this control "validates" + /// Gets or sets the Validation Group that this control "validates". /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string ValidationGroup { get { - EnsureChildControls(); - return link.ValidationGroup; + this.EnsureChildControls(); + return this.link.ValidationGroup; } + set { - EnsureChildControls(); - icon.ValidationGroup = value; - link.ValidationGroup = value; + this.EnsureChildControls(); + this.icon.ValidationGroup = value; + this.link.ValidationGroup = value; } } public string LocalResourceFile { get; set; } - public event EventHandler Click; - public event CommandEventHandler Command; + public void RegisterForPostback() + { + AJAX.RegisterPostBackControl(this.link); + AJAX.RegisterPostBackControl(this.icon); + } /// ----------------------------------------------------------------------------- /// /// CreateChildControls overrides the Base class's method to correctly build the - /// control based on the configuration + /// control based on the configuration. /// /// /// /// ----------------------------------------------------------------------------- protected override void CreateChildControls() { - Controls.Clear(); - if (String.IsNullOrEmpty(CssClass)) - { - CssClass = "CommandButton"; - } - icon = new ImageButton(); - icon.Visible = true; - icon.CausesValidation = true; - icon.Click += RaiseImageClick; - icon.Command += RaiseCommand; - Controls.Add(icon); - separator = new LiteralControl(); - separator.Text = " "; - Controls.Add(separator); - link = new LinkButton(); - link.Visible = true; - link.CausesValidation = true; - link.Click += RaiseClick; - link.Command += RaiseCommand; - Controls.Add(link); - if (DisplayIcon && !String.IsNullOrEmpty(ImageUrl)) - { - icon.EnableViewState = EnableViewState; - } - if (DisplayLink) - { - link.CssClass = CssClass; - link.EnableViewState = EnableViewState; + this.Controls.Clear(); + if (string.IsNullOrEmpty(this.CssClass)) + { + this.CssClass = "CommandButton"; + } + + this.icon = new ImageButton(); + this.icon.Visible = true; + this.icon.CausesValidation = true; + this.icon.Click += this.RaiseImageClick; + this.icon.Command += this.RaiseCommand; + this.Controls.Add(this.icon); + this.separator = new LiteralControl(); + this.separator.Text = " "; + this.Controls.Add(this.separator); + this.link = new LinkButton(); + this.link.Visible = true; + this.link.CausesValidation = true; + this.link.Click += this.RaiseClick; + this.link.Command += this.RaiseCommand; + this.Controls.Add(this.link); + if (this.DisplayIcon && !string.IsNullOrEmpty(this.ImageUrl)) + { + this.icon.EnableViewState = this.EnableViewState; + } + + if (this.DisplayLink) + { + this.link.CssClass = this.CssClass; + this.link.EnableViewState = this.EnableViewState; } } /// ----------------------------------------------------------------------------- /// - /// OnButtonClick raises the CommandButton control's Click event + /// OnButtonClick raises the CommandButton control's Click event. /// /// ----------------------------------------------------------------------------- protected virtual void OnButtonClick(EventArgs e) { - if (Click != null) + if (this.Click != null) { - Click(this, e); + this.Click(this, e); } } /// ----------------------------------------------------------------------------- /// - /// OnCommand raises the CommandButton control's Command event + /// OnCommand raises the CommandButton control's Command event. /// /// ----------------------------------------------------------------------------- protected virtual void OnCommand(CommandEventArgs e) { - if (Command != null) + if (this.Command != null) { - Command(this, e); + this.Command(this, e); } } /// ----------------------------------------------------------------------------- /// - /// OnPreRender runs just before the Render phase of the Page Life Cycle + /// OnPreRender runs just before the Render phase of the Page Life Cycle. /// /// ----------------------------------------------------------------------------- protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - EnsureChildControls(); - separator.Visible = DisplayLink && DisplayIcon; + this.EnsureChildControls(); + this.separator.Visible = this.DisplayLink && this.DisplayIcon; - LocalResourceFile = UIUtilities.GetLocalResourceFile(this); + this.LocalResourceFile = UIUtilities.GetLocalResourceFile(this); var tooltipText = string.Empty; - if (!string.IsNullOrEmpty(ToolTipKey)) + if (!string.IsNullOrEmpty(this.ToolTipKey)) { - tooltipText = Localization.GetString(ToolTipKey, LocalResourceFile); + tooltipText = Localization.GetString(this.ToolTipKey, this.LocalResourceFile); } - if (string.IsNullOrEmpty(tooltipText) && !string.IsNullOrEmpty(ToolTip)) + if (string.IsNullOrEmpty(tooltipText) && !string.IsNullOrEmpty(this.ToolTip)) { - tooltipText = ToolTip; + tooltipText = this.ToolTip; } if (!string.IsNullOrEmpty(tooltipText)) { - icon.ToolTip = link.ToolTip = icon.AlternateText = tooltipText; + this.icon.ToolTip = this.link.ToolTip = this.icon.AlternateText = tooltipText; } } - public void RegisterForPostback() - { - AJAX.RegisterPostBackControl(link); - AJAX.RegisterPostBackControl(icon); - } - /// ----------------------------------------------------------------------------- /// - /// RaiseClick runs when one of the contained Link buttons is clciked + /// RaiseImageClick runs when the Image button is clicked. /// - /// It raises a Click Event. + /// It raises a Command Event. /// - /// The object that triggers the event - /// An EventArgs object + /// The object that triggers the event. + /// An ImageClickEventArgs object. /// ----------------------------------------------------------------------------- - private void RaiseClick(object sender, EventArgs e) + protected void RaiseImageClick(object sender, ImageClickEventArgs e) { - OnButtonClick(e); + this.OnButtonClick(new EventArgs()); } /// ----------------------------------------------------------------------------- /// - /// RaiseCommand runs when one of the contained Link buttons is clicked + /// RaiseClick runs when one of the contained Link buttons is clciked. /// - /// It raises a Command Event. + /// It raises a Click Event. /// - /// The object that triggers the event - /// An CommandEventArgs object + /// The object that triggers the event. + /// An EventArgs object. /// ----------------------------------------------------------------------------- - private void RaiseCommand(object sender, CommandEventArgs e) + private void RaiseClick(object sender, EventArgs e) { - OnCommand(e); + this.OnButtonClick(e); } /// ----------------------------------------------------------------------------- /// - /// RaiseImageClick runs when the Image button is clicked + /// RaiseCommand runs when one of the contained Link buttons is clicked. /// /// It raises a Command Event. /// - /// The object that triggers the event - /// An ImageClickEventArgs object + /// The object that triggers the event. + /// An CommandEventArgs object. /// ----------------------------------------------------------------------------- - protected void RaiseImageClick(object sender, ImageClickEventArgs e) + private void RaiseCommand(object sender, CommandEventArgs e) { - OnButtonClick(new EventArgs()); + this.OnCommand(e); } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs index 270fb93aae7..c3f03deafca 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs @@ -1,186 +1,191 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: CheckBoxColumn /// ----------------------------------------------------------------------------- /// - /// The CheckBoxColumn control provides a Check Box column for a Data Grid + /// The CheckBoxColumn control provides a Check Box column for a Data Grid. /// /// ----------------------------------------------------------------------------- public class CheckBoxColumn : TemplateColumn - { - #region "Private Members" - + { private bool mAutoPostBack = true; private string mDataField = Null.NullString; private bool mEnabled = true; private string mEnabledField = Null.NullString; - private bool mHeaderCheckBox = true; - - #endregion - - #region "Constructors" - + private bool mHeaderCheckBox = true; + /// ----------------------------------------------------------------------------- - /// - /// Constructs the CheckBoxColumn + /// + /// Initializes a new instance of the class. + /// Constructs the CheckBoxColumn. /// /// ----------------------------------------------------------------------------- - public CheckBoxColumn() : this(false) + public CheckBoxColumn() + : this(false) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// Constructs the CheckBoxColumn, with an optional AutoPostBack (where each change - /// of state of a check box causes a Post Back) + /// of state of a check box causes a Post Back). /// - /// Optional set the checkboxes to postback + /// Optional set the checkboxes to postback. /// ----------------------------------------------------------------------------- public CheckBoxColumn(bool autoPostBack) { - AutoPostBack = autoPostBack; - } - - #endregion - - #region "Public Properties" - - + this.AutoPostBack = autoPostBack; + } + + public event DNNDataGridCheckedColumnEventHandler CheckedChanged; + /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the column fires a postback when any check box is - /// changed + /// Gets or sets a value indicating whether gets and sets whether the column fires a postback when any check box is + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool AutoPostBack { get { - return mAutoPostBack; + return this.mAutoPostBack; } + set { - mAutoPostBack = value; + this.mAutoPostBack = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the checkbox is checked (unless DataBound) + /// Gets or sets a value indicating whether gets and sets whether the checkbox is checked (unless DataBound). /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool Checked { get; set; } /// ----------------------------------------------------------------------------- /// - /// The Data Field that the column should bind to - /// changed + /// Gets or sets the Data Field that the column should bind to + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public string DataField { get { - return mDataField; + return this.mDataField; } + set { - mDataField = value; + this.mDataField = value; } } /// ----------------------------------------------------------------------------- /// - /// An flag that indicates whether the checkboxes are enabled (this is overridden if + /// Gets or sets a value indicating whether an flag that indicates whether the checkboxes are enabled (this is overridden if /// the EnabledField is set) - /// changed + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool Enabled { get { - return mEnabled; + return this.mEnabled; } + set { - mEnabled = value; + this.mEnabled = value; } } /// ----------------------------------------------------------------------------- /// - /// The Data Field that determines whether the checkbox is Enabled - /// changed + /// Gets or sets the Data Field that determines whether the checkbox is Enabled + /// changed. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string EnabledField { get { - return mEnabledField; + return this.mEnabledField; } + set { - mEnabledField = value; + this.mEnabledField = value; } } /// ----------------------------------------------------------------------------- /// - /// A flag that indicates whether there is a checkbox in the Header that sets all - /// the checkboxes + /// Gets or sets a value indicating whether a flag that indicates whether there is a checkbox in the Header that sets all + /// the checkboxes. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool HeaderCheckBox { get { - return mHeaderCheckBox; + return this.mHeaderCheckBox; } + set { - mHeaderCheckBox = value; + this.mHeaderCheckBox = value; } - } - - #endregion - - #region "Events" - - public event DNNDataGridCheckedColumnEventHandler CheckedChanged; - - #endregion - - #region "Private Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// Creates a CheckBoxColumnTemplate + /// Initialises the Column. /// - /// A CheckBoxColumnTemplate + /// ----------------------------------------------------------------------------- + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } + + /// ----------------------------------------------------------------------------- + /// + /// Creates a CheckBoxColumnTemplate. + /// + /// A CheckBoxColumnTemplate. /// ----------------------------------------------------------------------------- private CheckBoxColumnTemplate CreateTemplate(ListItemType type) { @@ -189,22 +194,25 @@ private CheckBoxColumnTemplate CreateTemplate(ListItemType type) { isDesignMode = true; } + var template = new CheckBoxColumnTemplate(type); if (type != ListItemType.Header) { - template.AutoPostBack = AutoPostBack; + template.AutoPostBack = this.AutoPostBack; } - template.Checked = Checked; - template.DataField = DataField; - template.Enabled = Enabled; - template.EnabledField = EnabledField; - template.CheckedChanged += OnCheckedChanged; + + template.Checked = this.Checked; + template.DataField = this.DataField; + template.Enabled = this.Enabled; + template.EnabledField = this.EnabledField; + template.CheckedChanged += this.OnCheckedChanged; if (type == ListItemType.Header) { - template.Text = HeaderText; + template.Text = this.HeaderText; template.AutoPostBack = true; - template.HeaderCheckBox = HeaderCheckBox; + template.HeaderCheckBox = this.HeaderCheckBox; } + template.DesignMode = isDesignMode; return template; } @@ -216,38 +224,12 @@ private CheckBoxColumnTemplate CreateTemplate(ListItemType type) /// ----------------------------------------------------------------------------- private void OnCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e) { - //Add the column to the Event Args + // Add the column to the Event Args e.Column = this; - if (CheckedChanged != null) - { - CheckedChanged(sender, e); - } - } - - #endregion - - #region "Public Methods" - - /// ----------------------------------------------------------------------------- - /// - /// Initialises the Column - /// - /// ----------------------------------------------------------------------------- - public override void Initialize() - { - ItemTemplate = CreateTemplate(ListItemType.Item); - EditItemTemplate = CreateTemplate(ListItemType.EditItem); - HeaderTemplate = CreateTemplate(ListItemType.Header); - if (HttpContext.Current == null) + if (this.CheckedChanged != null) { - HeaderStyle.Font.Names = new[] {"Tahoma, Verdana, Arial"}; - HeaderStyle.Font.Size = new FontUnit("10pt"); - HeaderStyle.Font.Bold = true; + this.CheckedChanged(sender, e); } - ItemStyle.HorizontalAlign = HorizontalAlign.Center; - HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs index 657e0477978..5cf30065a67 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: CheckBoxColumnTemplate /// ----------------------------------------------------------------------------- /// - /// The CheckBoxColumnTemplate provides a Template for the CheckBoxColumn + /// The CheckBoxColumnTemplate provides a Template for the CheckBoxColumn. /// /// ----------------------------------------------------------------------------- public class CheckBoxColumnTemplate : ITemplate @@ -30,244 +25,250 @@ public class CheckBoxColumnTemplate : ITemplate private string mEnabledField = Null.NullString; private bool mHeaderCheckBox = true; private ListItemType mItemType = ListItemType.Item; - private string mText = ""; + private string mText = string.Empty; - public CheckBoxColumnTemplate() : this(ListItemType.Item) + public CheckBoxColumnTemplate() + : this(ListItemType.Item) { } public CheckBoxColumnTemplate(ListItemType itemType) { - ItemType = itemType; - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether the column fires a postback when any check box is - /// changed - /// - /// A Boolean - /// ----------------------------------------------------------------------------- - public bool AutoPostBack { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether the checkbox is checked (unless DataBound) - /// - /// A Boolean - /// ----------------------------------------------------------------------------- + this.ItemType = itemType; + } + + public event DNNDataGridCheckedColumnEventHandler CheckedChanged; + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the column fires a postback when any check box is + /// changed. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public bool AutoPostBack { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the checkbox is checked (unless DataBound). + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool Checked { get; set; } /// ----------------------------------------------------------------------------- /// - /// The Data Field that the column should bind to + /// Gets or sets the Data Field that the column should bind to. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string DataField { get { - return mDataField; + return this.mDataField; } + set { - mDataField = value; + this.mDataField = value; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Design Mode of the Column - /// - /// A Boolean - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool DesignMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// An flag that indicates whether the hcekboxes are enabled (this is overridden if + /// Gets or sets a value indicating whether an flag that indicates whether the hcekboxes are enabled (this is overridden if /// the EnabledField is set - /// changed + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool Enabled { get { - return mEnabled; + return this.mEnabled; } + set { - mEnabled = value; + this.mEnabled = value; } } /// ----------------------------------------------------------------------------- /// - /// The Data Field that determines whether the checkbox is Enabled - /// changed + /// Gets or sets the Data Field that determines whether the checkbox is Enabled + /// changed. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string EnabledField { get { - return mEnabledField; + return this.mEnabledField; } + set { - mEnabledField = value; + this.mEnabledField = value; } } /// ----------------------------------------------------------------------------- /// - /// A flag that indicates whether there is a checkbox in the Header that sets all - /// the checkboxes + /// Gets or sets a value indicating whether a flag that indicates whether there is a checkbox in the Header that sets all + /// the checkboxes. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool HeaderCheckBox { get { - return mHeaderCheckBox; + return this.mHeaderCheckBox; } + set { - mHeaderCheckBox = value; + this.mHeaderCheckBox = value; } } /// ----------------------------------------------------------------------------- /// - /// The type of Template to Create + /// Gets or sets the type of Template to Create. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public ListItemType ItemType { get { - return mItemType; + return this.mItemType; } + set { - mItemType = value; + this.mItemType = value; } } /// ----------------------------------------------------------------------------- /// - /// The Text to display in a Header Template + /// Gets or sets the Text to display in a Header Template. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Text { get { - return mText; + return this.mText; } + set { - mText = value; + this.mText = value; } - } - - #region ITemplate Members - + } + /// ----------------------------------------------------------------------------- /// - /// InstantiateIn is called when the Template is instantiated by the parent control + /// InstantiateIn is called when the Template is instantiated by the parent control. /// - /// The container control + /// The container control. /// ----------------------------------------------------------------------------- public void InstantiateIn(Control container) { - if (!String.IsNullOrEmpty(Text)) + if (!string.IsNullOrEmpty(this.Text)) { - container.Controls.Add(new LiteralControl(Text + "
    ")); + container.Controls.Add(new LiteralControl(this.Text + "
    ")); } - if (ItemType != ListItemType.Header || (ItemType == ListItemType.Header && HeaderCheckBox)) + + if (this.ItemType != ListItemType.Header || (this.ItemType == ListItemType.Header && this.HeaderCheckBox)) { var box = new CheckBox(); - box.AutoPostBack = AutoPostBack; - box.DataBinding += Item_DataBinding; - box.CheckedChanged += OnCheckChanged; + box.AutoPostBack = this.AutoPostBack; + box.DataBinding += this.Item_DataBinding; + box.CheckedChanged += this.OnCheckChanged; container.Controls.Add(box); } - } - - #endregion - - public event DNNDataGridCheckedColumnEventHandler CheckedChanged; + } /// ----------------------------------------------------------------------------- /// - /// Called when the template item is Data Bound + /// Called when the template item is Data Bound. /// /// ----------------------------------------------------------------------------- private void Item_DataBinding(object sender, EventArgs e) { - var box = (CheckBox) sender; - var container = (DataGridItem) box.NamingContainer; - if (!String.IsNullOrEmpty(DataField) && ItemType != ListItemType.Header) + var box = (CheckBox)sender; + var container = (DataGridItem)box.NamingContainer; + if (!string.IsNullOrEmpty(this.DataField) && this.ItemType != ListItemType.Header) { - if (DesignMode) + if (this.DesignMode) { box.Checked = false; } else { - box.Checked = Convert.ToBoolean(DataBinder.Eval(container.DataItem, DataField)); + box.Checked = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.DataField)); } } else { - box.Checked = Checked; + box.Checked = this.Checked; } - if (!String.IsNullOrEmpty(EnabledField)) + + if (!string.IsNullOrEmpty(this.EnabledField)) { - if (DesignMode) + if (this.DesignMode) { box.Enabled = false; } else { - box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, EnabledField)); + box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.EnabledField)); } } else { - box.Enabled = Enabled; + box.Enabled = this.Enabled; } } /// ----------------------------------------------------------------------------- /// - /// Centralised Event that is raised whenever a check box's state is modified + /// Centralised Event that is raised whenever a check box's state is modified. /// /// ----------------------------------------------------------------------------- private void OnCheckChanged(object sender, EventArgs e) { - var box = (CheckBox) sender; - var container = (DataGridItem) box.NamingContainer; + var box = (CheckBox)sender; + var container = (DataGridItem)box.NamingContainer; DNNDataGridCheckChangedEventArgs evntArgs; if (container.ItemIndex == Null.NullInteger) { - evntArgs = new DNNDataGridCheckChangedEventArgs(container, box.Checked, DataField, true); + evntArgs = new DNNDataGridCheckChangedEventArgs(container, box.Checked, this.DataField, true); } else { - evntArgs = new DNNDataGridCheckChangedEventArgs(container, box.Checked, DataField, false); + evntArgs = new DNNDataGridCheckChangedEventArgs(container, box.Checked, this.DataField, false); } - if (CheckedChanged != null) + + if (this.CheckedChanged != null) { - CheckedChanged(sender, evntArgs); + this.CheckedChanged(sender, evntArgs); } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs index 7cc94b393dd..d319fc5fb81 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -18,52 +13,29 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The DNNDataGrid control provides an Enhanced Data Grid, that supports other - /// column types + /// column types. /// /// /// /// ----------------------------------------------------------------------------- public class DNNDataGrid : DataGrid - { - #region "Events" - - public event DNNDataGridCheckedColumnEventHandler ItemCheckedChanged; - - #endregion - - #region "Private Methods" - - /// ----------------------------------------------------------------------------- - /// - /// Centralised Event that is raised whenever a check box is changed. - /// - /// ----------------------------------------------------------------------------- - private void OnItemCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e) - { - if (ItemCheckedChanged != null) - { - ItemCheckedChanged(sender, e); - } - } - - #endregion - - #region "Protected Methods" - + { + public event DNNDataGridCheckedColumnEventHandler ItemCheckedChanged; + /// ----------------------------------------------------------------------------- /// - /// Called when the grid is Data Bound + /// Called when the grid is Data Bound. /// /// ----------------------------------------------------------------------------- protected override void OnDataBinding(EventArgs e) { - foreach (DataGridColumn column in Columns) + foreach (DataGridColumn column in this.Columns) { - if (ReferenceEquals(column.GetType(), typeof (CheckBoxColumn))) + if (ReferenceEquals(column.GetType(), typeof(CheckBoxColumn))) { - //Manage CheckBox column events - var cbColumn = (CheckBoxColumn) column; - cbColumn.CheckedChanged += OnItemCheckedChanged; + // Manage CheckBox column events + var cbColumn = (CheckBoxColumn)column; + cbColumn.CheckedChanged += this.OnItemCheckedChanged; } } } @@ -72,12 +44,23 @@ protected override void CreateControlHierarchy(bool useDataSource) { base.CreateControlHierarchy(useDataSource); } + + /// ----------------------------------------------------------------------------- + /// + /// Centralised Event that is raised whenever a check box is changed. + /// + /// ----------------------------------------------------------------------------- + private void OnItemCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e) + { + if (this.ItemCheckedChanged != null) + { + this.ItemCheckedChanged(sender, e); + } + } protected override void PrepareControlHierarchy() { base.PrepareControlHierarchy(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs index bef421f8051..2b20407e6fc 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Web.UI.WebControls; + public delegate void DNNDataGridCheckedColumnEventHandler(object sender, DNNDataGridCheckChangedEventArgs e); /// ----------------------------------------------------------------------------- @@ -19,22 +14,24 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The DNNDataGridCheckChangedEventArgs class is a cusom EventArgs class for - /// handling Event Args from the CheckChanged event in a CheckBox Column + /// handling Event Args from the CheckChanged event in a CheckBox Column. /// /// /// /// ----------------------------------------------------------------------------- public class DNNDataGridCheckChangedEventArgs : DataGridItemEventArgs { - public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field) : this(item, isChecked, field, false) + public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field) + : this(item, isChecked, field, false) { } - public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field, bool isAll) : base(item) + public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field, bool isAll) + : base(item) { - Checked = isChecked; - IsAll = isAll; - Field = field; + this.Checked = isChecked; + this.IsAll = isAll; + this.Field = field; } public bool Checked { get; set; } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs index 03bd41a5457..9af0684d9a4 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: DNNMultiStateBoxColumn /// ----------------------------------------------------------------------------- /// - /// The DNNMultiStateBoxColumn control provides a DNNMultiState Box column for a Data Grid + /// The DNNMultiStateBoxColumn control provides a DNNMultiState Box column for a Data Grid. /// /// ----------------------------------------------------------------------------- public class DNNMultiStateBoxColumn : TemplateColumn @@ -28,170 +23,202 @@ public class DNNMultiStateBoxColumn : TemplateColumn private string mDataField = Null.NullString; private bool mEnabled = true; private string mEnabledField = Null.NullString; - private string mImagePath = ""; - private string mSelectedStateKey = ""; - private DNNMultiStateCollection mStates; - + private string mImagePath = string.Empty; + private string mSelectedStateKey = string.Empty; + private DNNMultiStateCollection mStates; + /// ----------------------------------------------------------------------------- - /// - /// Constructs the DNNMultiStateBoxColumn + /// + /// Initializes a new instance of the class. + /// Constructs the DNNMultiStateBoxColumn. /// /// ----------------------------------------------------------------------------- - public DNNMultiStateBoxColumn() : this(false) + public DNNMultiStateBoxColumn() + : this(false) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// + /// Initializes a new instance of the class. /// Constructs the MultiStateBoxColumn, with an optional AutoPostBack (where each change - /// of state of the control causes a Post Back) + /// of state of the control causes a Post Back). /// - /// Optional set the control to postback + /// Optional set the control to postback. /// ----------------------------------------------------------------------------- public DNNMultiStateBoxColumn(bool autoPostBack) { - AutoPostBack = autoPostBack; + this.AutoPostBack = autoPostBack; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the column fires a postback when the control changes + /// Gets or sets a value indicating whether gets and sets whether the column fires a postback when the control changes. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool AutoPostBack { get { - return mAutoPostBack; + return this.mAutoPostBack; } + set { - mAutoPostBack = value; + this.mAutoPostBack = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the selected state of the DNNMultiStateBox (unless DataBound) + /// Gets or sets and sets the selected state of the DNNMultiStateBox (unless DataBound). /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public string SelectedStateKey { get { - return mSelectedStateKey; + return this.mSelectedStateKey; } + set { - mSelectedStateKey = value; + this.mSelectedStateKey = value; } } /// ----------------------------------------------------------------------------- /// - /// The Data Field that the column should bind to - /// changed + /// Gets or sets the Data Field that the column should bind to + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public string DataField { get { - return mDataField; + return this.mDataField; } + set { - mDataField = value; + this.mDataField = value; } } /// ----------------------------------------------------------------------------- /// - /// An flag that indicates whether the control is enabled (this is overridden if + /// Gets or sets a value indicating whether an flag that indicates whether the control is enabled (this is overridden if /// the EnabledField is set) - /// changed + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool Enabled { get { - return mEnabled; + return this.mEnabled; } + set { - mEnabled = value; + this.mEnabled = value; } } /// ----------------------------------------------------------------------------- /// - /// The Data Field that determines whether the control is Enabled - /// changed + /// Gets or sets the Data Field that determines whether the control is Enabled + /// changed. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string EnabledField { get { - return mEnabledField; + return this.mEnabledField; } + set { - mEnabledField = value; + this.mEnabledField = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the image path of the DNNMultiStateBox + /// Gets or sets and sets the image path of the DNNMultiStateBox. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public string ImagePath { get { - return mImagePath; + return this.mImagePath; } + set { - mImagePath = value; + this.mImagePath = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the state collection of the DNNMultiStateBox + /// Gets or sets and sets the state collection of the DNNMultiStateBox. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public DNNMultiStateCollection States { get { - if (mStates == null) + if (this.mStates == null) { - mStates = new DNNMultiStateCollection(new DNNMultiStateBox()); + this.mStates = new DNNMultiStateCollection(new DNNMultiStateBox()); } - return mStates; + + return this.mStates; } + set { - mStates = value; + this.mStates = value; } } /// ----------------------------------------------------------------------------- /// - /// Creates a DNNMultiStateBoxColumnTemplate + /// Initialises the Column. /// - /// A DNNMultiStateBoxColumnTemplate + /// ----------------------------------------------------------------------------- + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } + + /// ----------------------------------------------------------------------------- + /// + /// Creates a DNNMultiStateBoxColumnTemplate. + /// + /// A DNNMultiStateBoxColumnTemplate. /// ----------------------------------------------------------------------------- private DNNMultiStateBoxColumnTemplate CreateTemplate(ListItemType type) { @@ -200,47 +227,31 @@ private DNNMultiStateBoxColumnTemplate CreateTemplate(ListItemType type) { isDesignMode = true; } + var template = new DNNMultiStateBoxColumnTemplate(type); if (type != ListItemType.Header) { - template.AutoPostBack = AutoPostBack; + template.AutoPostBack = this.AutoPostBack; } - template.DataField = DataField; - template.Enabled = Enabled; - template.EnabledField = EnabledField; - template.ImagePath = ImagePath; - foreach (DNNMultiState objState in States) + + template.DataField = this.DataField; + template.Enabled = this.Enabled; + template.EnabledField = this.EnabledField; + template.ImagePath = this.ImagePath; + foreach (DNNMultiState objState in this.States) { template.States.Add(objState); } - template.SelectedStateKey = SelectedStateKey; + + template.SelectedStateKey = this.SelectedStateKey; if (type == ListItemType.Header) { - template.Text = HeaderText; + template.Text = this.HeaderText; template.AutoPostBack = true; } + template.DesignMode = isDesignMode; return template; } - - /// ----------------------------------------------------------------------------- - /// - /// Initialises the Column - /// - /// ----------------------------------------------------------------------------- - public override void Initialize() - { - ItemTemplate = CreateTemplate(ListItemType.Item); - EditItemTemplate = CreateTemplate(ListItemType.EditItem); - HeaderTemplate = CreateTemplate(ListItemType.Header); - if (HttpContext.Current == null) - { - HeaderStyle.Font.Names = new[] {"Tahoma, Verdana, Arial"}; - HeaderStyle.Font.Size = new FontUnit("10pt"); - HeaderStyle.Font.Bold = true; - } - ItemStyle.HorizontalAlign = HorizontalAlign.Center; - HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs index 555a4bb063f..c8e56062db8 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: DNNMultiStateBoxColumnTemplate /// ----------------------------------------------------------------------------- /// - /// The DNNMultiStateBoxColumnTemplate provides a Template for the DNNMultiStateBoxColumn + /// The DNNMultiStateBoxColumnTemplate provides a Template for the DNNMultiStateBoxColumn. /// /// ----------------------------------------------------------------------------- public class DNNMultiStateBoxColumnTemplate : ITemplate @@ -28,256 +23,265 @@ public class DNNMultiStateBoxColumnTemplate : ITemplate private string mDataField = Null.NullString; private bool mEnabled = true; private string mEnabledField = Null.NullString; - private string mImagePath = ""; + private string mImagePath = string.Empty; private ListItemType mItemType = ListItemType.Item; - private string mSelectedStateKey = ""; + private string mSelectedStateKey = string.Empty; private DNNMultiStateCollection mStates; - private string mText = ""; + private string mText = string.Empty; - public DNNMultiStateBoxColumnTemplate() : this(ListItemType.Item) + public DNNMultiStateBoxColumnTemplate() + : this(ListItemType.Item) { } public DNNMultiStateBoxColumnTemplate(ListItemType itemType) { - ItemType = itemType; + this.ItemType = itemType; } - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether the column fires a postback when the control changes - /// - /// A Boolean - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the column fires a postback when the control changes. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool AutoPostBack { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the selected state of the DNNMultiStateBox (unless DataBound) + /// Gets or sets and sets the selected state of the DNNMultiStateBox (unless DataBound). /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public string SelectedStateKey { get { - return mSelectedStateKey; + return this.mSelectedStateKey; } + set { - mSelectedStateKey = value; + this.mSelectedStateKey = value; } } /// ----------------------------------------------------------------------------- /// - /// The Data Field that the column should bind to + /// Gets or sets the Data Field that the column should bind to. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string DataField { get { - return mDataField; + return this.mDataField; } + set { - mDataField = value; + this.mDataField = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Design Mode of the Column - /// - /// A Boolean - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool DesignMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// An flag that indicates whether the control is enabled (this is overridden if + /// Gets or sets a value indicating whether an flag that indicates whether the control is enabled (this is overridden if /// the EnabledField is set - /// changed + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool Enabled { get { - return mEnabled; + return this.mEnabled; } + set { - mEnabled = value; + this.mEnabled = value; } } /// ----------------------------------------------------------------------------- /// - /// The Data Field that determines whether the control is Enabled - /// changed + /// Gets or sets the Data Field that determines whether the control is Enabled + /// changed. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string EnabledField { get { - return mEnabledField; + return this.mEnabledField; } + set { - mEnabledField = value; + this.mEnabledField = value; } } /// ----------------------------------------------------------------------------- /// - /// The type of Template to Create + /// Gets or sets the type of Template to Create. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public ListItemType ItemType { get { - return mItemType; + return this.mItemType; } + set { - mItemType = value; + this.mItemType = value; } } /// ----------------------------------------------------------------------------- /// - /// The Text to display in a Header Template + /// Gets or sets the Text to display in a Header Template. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Text { get { - return mText; + return this.mText; } + set { - mText = value; + this.mText = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the image path of the DNNMultiStateBox + /// Gets or sets and sets the image path of the DNNMultiStateBox. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public string ImagePath { get { - return mImagePath; + return this.mImagePath; } + set { - mImagePath = value; + this.mImagePath = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the state collection of the DNNMultiStateBox + /// Gets or sets and sets the state collection of the DNNMultiStateBox. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public DNNMultiStateCollection States { get { - if (mStates == null) + if (this.mStates == null) { - mStates = new DNNMultiStateCollection(new DNNMultiStateBox()); + this.mStates = new DNNMultiStateCollection(new DNNMultiStateBox()); } - return mStates; + + return this.mStates; } + set { - mStates = value; + this.mStates = value; } - } - - #region ITemplate Members - + } + /// ----------------------------------------------------------------------------- /// - /// InstantiateIn is called when the Template is instantiated by the parent control + /// InstantiateIn is called when the Template is instantiated by the parent control. /// - /// The container control - /// ----------------------------------------------------------------------------- + /// The container control. + /// ----------------------------------------------------------------------------- public void InstantiateIn(Control container) { - if (!String.IsNullOrEmpty(Text)) + if (!string.IsNullOrEmpty(this.Text)) { - container.Controls.Add(new LiteralControl(Text + "
    ")); + container.Controls.Add(new LiteralControl(this.Text + "
    ")); } - if (ItemType != ListItemType.Header) + + if (this.ItemType != ListItemType.Header) { var box = new DNNMultiStateBox(); - box.AutoPostBack = AutoPostBack; - box.ImagePath = ImagePath; - foreach (DNNMultiState objState in States) + box.AutoPostBack = this.AutoPostBack; + box.ImagePath = this.ImagePath; + foreach (DNNMultiState objState in this.States) { box.States.Add(objState); } - box.DataBinding += Item_DataBinding; + + box.DataBinding += this.Item_DataBinding; container.Controls.Add(box); } - } - - #endregion - + } + /// ----------------------------------------------------------------------------- /// - /// Called when the template item is Data Bound + /// Called when the template item is Data Bound. /// /// ----------------------------------------------------------------------------- private void Item_DataBinding(object sender, EventArgs e) { - var box = (DNNMultiStateBox) sender; - var container = (DataGridItem) box.NamingContainer; - if (!String.IsNullOrEmpty(DataField) && ItemType != ListItemType.Header) + var box = (DNNMultiStateBox)sender; + var container = (DataGridItem)box.NamingContainer; + if (!string.IsNullOrEmpty(this.DataField) && this.ItemType != ListItemType.Header) { - if (DesignMode) + if (this.DesignMode) { - box.SelectedStateKey = ""; + box.SelectedStateKey = string.Empty; } else { - box.SelectedStateKey = Convert.ToString(DataBinder.Eval(container.DataItem, DataField)); + box.SelectedStateKey = Convert.ToString(DataBinder.Eval(container.DataItem, this.DataField)); } } else { - box.SelectedStateKey = SelectedStateKey; + box.SelectedStateKey = this.SelectedStateKey; } - if (!String.IsNullOrEmpty(EnabledField)) + + if (!string.IsNullOrEmpty(this.EnabledField)) { - if (DesignMode) + if (this.DesignMode) { box.Enabled = false; } else { - box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, EnabledField)); + box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.EnabledField)); } } else { - box.Enabled = Enabled; + box.Enabled = this.Enabled; } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs index b33c5d4797a..b0d3b232138 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs @@ -1,201 +1,179 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.UI.WebControls; -using DotNetNuke.Entities.Icons; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Icons; + /// /// The ImageCommandColumn control provides an Image Command (or Hyperlink) column - /// for a Data Grid + /// for a Data Grid. /// public class ImageCommandColumn : TemplateColumn { private ImageCommandColumnEditMode _editMode = ImageCommandColumnEditMode.Command; - private bool _showImage = true; - - #region "Public Properties" - + private bool _showImage = true; private string _imageURL = string.Empty; /// - /// Gets or sets the CommandName for the Column + /// Gets or sets the CommandName for the Column. /// - /// A String + /// A String. public string CommandName { get; set; } - - + /// - /// EditMode for the Column + /// Gets or sets editMode for the Column. /// - /// A String + /// A String. public ImageCommandColumnEditMode EditMode { - get { return _editMode; } - set { _editMode = value; } + get { return this._editMode; } + set { this._editMode = value; } } - - + /// - /// Gets or sets the URL of the Image + /// Gets or sets the URL of the Image. /// - /// A String + /// A String. public string ImageURL { get { - if (!string.IsNullOrEmpty(_imageURL)) + if (!string.IsNullOrEmpty(this._imageURL)) { - return _imageURL; + return this._imageURL; } - return IconController.IconURL(IconKey, IconSize, IconStyle); + return IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); } - set { _imageURL = value; } + + set { this._imageURL = value; } } - - + /// - /// The Icon Key to obtain ImageURL + /// Gets or sets the Icon Key to obtain ImageURL. /// - /// A String + /// A String. public string IconKey { get; set; } - - + /// - /// The Icon Siz to obtain ImageURL + /// Gets or sets the Icon Siz to obtain ImageURL. /// - /// A String + /// A String. public string IconSize { get; set; } - - + /// - /// The Icon Style to obtain ImageURL + /// Gets or sets the Icon Style to obtain ImageURL. /// - /// A String + /// A String. public string IconStyle { get; set; } - - + /// - /// The Key Field that provides a Unique key to the data Item + /// Gets or sets the Key Field that provides a Unique key to the data Item. /// - /// A String + /// A String. public string KeyField { get; set; } - - + /// - /// Gets or sets the URL of the Link (unless DataBinding through KeyField) + /// Gets or sets the URL of the Link (unless DataBinding through KeyField). /// - /// A String + /// A String. public string NavigateURL { get; set; } - - + /// - /// Gets or sets the URL Formatting string + /// Gets or sets the URL Formatting string. /// - /// A String + /// A String. public string NavigateURLFormatString { get; set; } - - + /// - /// Javascript text to attach to the OnClick Event + /// Gets or sets javascript text to attach to the OnClick Event. /// - /// A String + /// A String. // ReSharper disable InconsistentNaming - public string OnClickJS { get; set; } -// ReSharper restore InconsistentNaming - - + public string OnClickJS { get; set; } + + // ReSharper restore InconsistentNaming + /// - /// Gets or sets whether an Image is displayed + /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. public bool ShowImage { - get { return _showImage; } - set { _showImage = value; } + get { return this._showImage; } + set { this._showImage = value; } } - - + /// - /// Gets or sets the Text (for Header/Footer Templates) + /// Gets or sets the Text (for Header/Footer Templates). /// - /// A String + /// A String. public string Text { get; set; } - - + /// - /// An flag that indicates whether the buttons are visible. + /// Gets or sets an flag that indicates whether the buttons are visible. /// - /// A Boolean + /// A Boolean. public string VisibleField { get; set; } + + /// + /// Initialises the Column. + /// + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); - + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } + /// - /// Creates a ImageCommandColumnTemplate + /// Creates a ImageCommandColumnTemplate. /// - /// A ImageCommandColumnTemplate + /// A ImageCommandColumnTemplate. private ImageCommandColumnTemplate CreateTemplate(ListItemType type) { bool isDesignMode = HttpContext.Current == null; var template = new ImageCommandColumnTemplate(type); if (type != ListItemType.Header) { - template.ImageURL = ImageURL; + template.ImageURL = this.ImageURL; if (!isDesignMode) { - template.CommandName = CommandName; - template.VisibleField = VisibleField; - template.KeyField = KeyField; + template.CommandName = this.CommandName; + template.VisibleField = this.VisibleField; + template.KeyField = this.KeyField; } } - template.EditMode = EditMode; - template.NavigateURL = NavigateURL; - template.NavigateURLFormatString = NavigateURLFormatString; - template.OnClickJS = OnClickJS; - template.ShowImage = ShowImage; - template.Visible = Visible; + + template.EditMode = this.EditMode; + template.NavigateURL = this.NavigateURL; + template.NavigateURLFormatString = this.NavigateURLFormatString; + template.OnClickJS = this.OnClickJS; + template.ShowImage = this.ShowImage; + template.Visible = this.Visible; - template.Text = type == ListItemType.Header ? HeaderText : Text; + template.Text = type == ListItemType.Header ? this.HeaderText : this.Text; - //Set Design Mode to True + // Set Design Mode to True template.DesignMode = isDesignMode; return template; - } - - #endregion - - #region "Public Methods" - - /// - /// Initialises the Column - /// - public override void Initialize() - { - ItemTemplate = CreateTemplate(ListItemType.Item); - EditItemTemplate = CreateTemplate(ListItemType.EditItem); - HeaderTemplate = CreateTemplate(ListItemType.Header); - - if (HttpContext.Current == null) - { - HeaderStyle.Font.Names = new[] {"Tahoma, Verdana, Arial"}; - HeaderStyle.Font.Size = new FontUnit("10pt"); - HeaderStyle.Font.Bold = true; - } - ItemStyle.HorizontalAlign = HorizontalAlign.Center; - HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnEditMode.cs b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnEditMode.cs index fa995e264f3..98b1c76ef0b 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnEditMode.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnEditMode.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- @@ -11,7 +11,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The ImageCommandColumnEditMode Enum provides an enumeration of the types - /// for how the Grid responds to an Edit Command + /// for how the Grid responds to an Edit Command. /// /// /// @@ -19,6 +19,6 @@ namespace DotNetNuke.UI.WebControls public enum ImageCommandColumnEditMode { Command, - URL + URL, } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs index 229f514476b..c9ed387dc70 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs @@ -1,352 +1,343 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.UI.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.UI.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: ImageCommandColumnTemplate /// ----------------------------------------------------------------------------- /// - /// The ImageCommandColumnTemplate provides a Template for the ImageCommandColumn + /// The ImageCommandColumnTemplate provides a Template for the ImageCommandColumn. /// /// ----------------------------------------------------------------------------- public class ImageCommandColumnTemplate : ITemplate - { - #region "Private Members" - + { private ImageCommandColumnEditMode mEditMode = ImageCommandColumnEditMode.Command; private ListItemType mItemType = ListItemType.Item; private bool mShowImage = true; - private bool mVisible = true; - - #endregion - - #region "Constructors" - - public ImageCommandColumnTemplate() : this(ListItemType.Item) + private bool mVisible = true; + + public ImageCommandColumnTemplate() + : this(ListItemType.Item) { } public ImageCommandColumnTemplate(ListItemType itemType) { - ItemType = itemType; - } - - #endregion - - #region "Public Properties" - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the CommandName for the Column - /// - /// A String - /// ----------------------------------------------------------------------------- + this.ItemType = itemType; + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the CommandName for the Column. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string CommandName { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Design Mode of the Column - /// - /// A Boolean - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool DesignMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the CommandName for the Column + /// Gets or sets the CommandName for the Column. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public ImageCommandColumnEditMode EditMode { get { - return mEditMode; + return this.mEditMode; } + set { - mEditMode = value; + this.mEditMode = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the URL of the Image - /// - /// A String - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the URL of the Image. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string ImageURL { get; set; } /// ----------------------------------------------------------------------------- /// - /// The type of Template to Create + /// Gets or sets the type of Template to Create. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public ListItemType ItemType { get { - return mItemType; + return this.mItemType; } + set { - mItemType = value; + this.mItemType = value; } } - /// ----------------------------------------------------------------------------- - /// - /// The Key Field that provides a Unique key to the data Item - /// - /// A String - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Key Field that provides a Unique key to the data Item. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string KeyField { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the URL of the Link (unless DataBinding through KeyField) - /// - /// A String - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the URL of the Link (unless DataBinding through KeyField). + /// + /// A String. + /// ----------------------------------------------------------------------------- public string NavigateURL { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the URL Formatting string - /// - /// A String - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the URL Formatting string. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string NavigateURLFormatString { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Javascript text to attach to the OnClick Event - /// - /// A String - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets javascript text to attach to the OnClick Event. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string OnClickJS { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets or sets whether an Image is displayed + /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. /// - /// Defaults to True - /// A Boolean + /// Defaults to True. + /// A Boolean. /// ----------------------------------------------------------------------------- public bool ShowImage { get { - return mShowImage; + return this.mShowImage; } + set { - mShowImage = value; + this.mShowImage = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Text (for Header/Footer Templates) - /// - /// A String - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Text (for Header/Footer Templates). + /// + /// A String. + /// ----------------------------------------------------------------------------- public string Text { get; set; } /// ----------------------------------------------------------------------------- /// - /// An flag that indicates whether the buttons are visible (this is overridden if + /// Gets or sets a value indicating whether an flag that indicates whether the buttons are visible (this is overridden if /// the VisibleField is set) - /// changed + /// changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- public bool Visible { get { - return mVisible; + return this.mVisible; } + set { - mVisible = value; + this.mVisible = value; } } - /// ----------------------------------------------------------------------------- - /// - /// An flag that indicates whether the buttons are visible. - /// - /// A Boolean - /// ----------------------------------------------------------------------------- - public string VisibleField { get; set; } - - #region ITemplate Members - /// ----------------------------------------------------------------------------- /// - /// InstantiateIn instantiates the template (implementation of ITemplate) + /// Gets or sets an flag that indicates whether the buttons are visible. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public string VisibleField { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// InstantiateIn instantiates the template (implementation of ITemplate). /// /// /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). /// ----------------------------------------------------------------------------- public void InstantiateIn(Control container) { - switch (ItemType) + switch (this.ItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: case ListItemType.SelectedItem: case ListItemType.EditItem: - if (EditMode == ImageCommandColumnEditMode.URL) + if (this.EditMode == ImageCommandColumnEditMode.URL) { var hypLink = new HyperLink(); - hypLink.ToolTip = Text; - if (!String.IsNullOrEmpty(ImageURL) && ShowImage) + hypLink.ToolTip = this.Text; + if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { var img = new Image(); - if (DesignMode) + if (this.DesignMode) { - img.ImageUrl = ImageURL.Replace("~/", "../../"); + img.ImageUrl = this.ImageURL.Replace("~/", "../../"); } else { - img.ImageUrl = ImageURL; + img.ImageUrl = this.ImageURL; } + hypLink.Controls.Add(img); - img.ToolTip = Text; + img.ToolTip = this.Text; } else { - hypLink.Text = Text; + hypLink.Text = this.Text; } - hypLink.DataBinding += Item_DataBinding; + + hypLink.DataBinding += this.Item_DataBinding; container.Controls.Add(hypLink); } else { - if (!String.IsNullOrEmpty(ImageURL) && ShowImage) + if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { var colIcon = new ImageButton(); - if (DesignMode) + if (this.DesignMode) { - colIcon.ImageUrl = ImageURL.Replace("~/", "../../"); + colIcon.ImageUrl = this.ImageURL.Replace("~/", "../../"); } else { - colIcon.ImageUrl = ImageURL; + colIcon.ImageUrl = this.ImageURL; } - colIcon.ToolTip = Text; - if (!String.IsNullOrEmpty(OnClickJS)) + + colIcon.ToolTip = this.Text; + if (!string.IsNullOrEmpty(this.OnClickJS)) { - ClientAPI.AddButtonConfirm(colIcon, OnClickJS); + ClientAPI.AddButtonConfirm(colIcon, this.OnClickJS); } - colIcon.CommandName = CommandName; - colIcon.DataBinding += Item_DataBinding; + + colIcon.CommandName = this.CommandName; + colIcon.DataBinding += this.Item_DataBinding; container.Controls.Add(colIcon); } - if (!String.IsNullOrEmpty(Text) && !ShowImage) + + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { var colLink = new LinkButton(); - colLink.ToolTip = Text; - if (!String.IsNullOrEmpty(OnClickJS)) + colLink.ToolTip = this.Text; + if (!string.IsNullOrEmpty(this.OnClickJS)) { - ClientAPI.AddButtonConfirm(colLink, OnClickJS); + ClientAPI.AddButtonConfirm(colLink, this.OnClickJS); } - colLink.CommandName = CommandName; - colLink.Text = Text; - colLink.DataBinding += Item_DataBinding; + + colLink.CommandName = this.CommandName; + colLink.Text = this.Text; + colLink.DataBinding += this.Item_DataBinding; container.Controls.Add(colLink); } } + break; case ListItemType.Footer: case ListItemType.Header: - container.Controls.Add(new LiteralControl(Text)); + container.Controls.Add(new LiteralControl(this.Text)); break; } - } - - #endregion - - #endregion - - #region "Private Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// Gets whether theButton is visible + /// Gets whether theButton is visible. /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). /// ----------------------------------------------------------------------------- private bool GetIsVisible(DataGridItem container) { bool isVisible; - if (!String.IsNullOrEmpty(VisibleField)) + if (!string.IsNullOrEmpty(this.VisibleField)) { - isVisible = Convert.ToBoolean(DataBinder.Eval(container.DataItem, VisibleField)); + isVisible = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.VisibleField)); } else { - isVisible = Visible; + isVisible = this.Visible; } + return isVisible; } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the key + /// Gets the value of the key. /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). /// ----------------------------------------------------------------------------- private int GetValue(DataGridItem container) { int keyValue = Null.NullInteger; - if (!String.IsNullOrEmpty(KeyField)) + if (!string.IsNullOrEmpty(this.KeyField)) { - keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, KeyField)); + keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, this.KeyField)); } + return keyValue; } /// ----------------------------------------------------------------------------- /// - /// Item_DataBinding runs when an Item of type ListItemType.Item is being data-bound + /// Item_DataBinding runs when an Item of type ListItemType.Item is being data-bound. /// /// /// - /// The object that triggers the event - /// An EventArgs object + /// The object that triggers the event. + /// An EventArgs object. /// ----------------------------------------------------------------------------- private void Item_DataBinding(object sender, EventArgs e) { DataGridItem container; int keyValue = Null.NullInteger; - if (EditMode == ImageCommandColumnEditMode.URL) + if (this.EditMode == ImageCommandColumnEditMode.URL) { - var hypLink = (HyperLink) sender; - container = (DataGridItem) hypLink.NamingContainer; - keyValue = GetValue(container); - if (!String.IsNullOrEmpty(NavigateURLFormatString)) + var hypLink = (HyperLink)sender; + container = (DataGridItem)hypLink.NamingContainer; + keyValue = this.GetValue(container); + if (!string.IsNullOrEmpty(this.NavigateURLFormatString)) { - hypLink.NavigateUrl = string.Format(NavigateURLFormatString, keyValue); + hypLink.NavigateUrl = string.Format(this.NavigateURLFormatString, keyValue); } else { @@ -355,27 +346,26 @@ private void Item_DataBinding(object sender, EventArgs e) } else { - //Bind Image Button - if (!String.IsNullOrEmpty(ImageURL) && ShowImage) + // Bind Image Button + if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { - var colIcon = (ImageButton) sender; - container = (DataGridItem) colIcon.NamingContainer; - keyValue = GetValue(container); + var colIcon = (ImageButton)sender; + container = (DataGridItem)colIcon.NamingContainer; + keyValue = this.GetValue(container); colIcon.CommandArgument = keyValue.ToString(); - colIcon.Visible = GetIsVisible(container); + colIcon.Visible = this.GetIsVisible(container); } - if (!String.IsNullOrEmpty(Text) && !ShowImage) + + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { - //Bind Link Button - var colLink = (LinkButton) sender; - container = (DataGridItem) colLink.NamingContainer; - keyValue = GetValue(container); + // Bind Link Button + var colLink = (LinkButton)sender; + container = (DataGridItem)colLink.NamingContainer; + keyValue = this.GetValue(container); colLink.CommandArgument = keyValue.ToString(); - colLink.Visible = GetIsVisible(container); + colLink.Visible = this.GetIsVisible(container); } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs index c645e38ffac..90535849472 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs @@ -1,23 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls.Internal { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + /// /// A TriState permission control built specifically for use in the PermissionGrid control - /// This control is not general in any way shape of form and should NOT be used outside - /// of the PermissionGrid + /// This control is not general in any way shape of form and should NOT be used outside + /// of the PermissionGrid. /// public class PermissionTriState : HiddenField { @@ -31,18 +31,19 @@ public class PermissionTriState : HiddenField public PermissionTriState() { - //kind of ugly to lookup this data each time, but doesn't seem worth the effort to - //maintain statics for the paths but require a control instance to initialize them - //and lazy load the text bits when the page instance (or localization) changes - LookupScriptValues(this, out _grantImagePath, out _denyImagePath, out _nullImagePath, out _lockImagePath, out _grantAltText, out _denyAltText, out _nullAltText); + // kind of ugly to lookup this data each time, but doesn't seem worth the effort to + // maintain statics for the paths but require a control instance to initialize them + // and lazy load the text bits when the page instance (or localization) changes + LookupScriptValues(this, out this._grantImagePath, out this._denyImagePath, out this._nullImagePath, out this._lockImagePath, out this._grantAltText, out this._denyAltText, out this._nullAltText); } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); + public bool IsFullControl { get; set; } - RegisterScripts(Page, this); - } + public bool IsView { get; set; } + + // Locked is currently not used on a post-back and therefore the + // value on postback is undefined at this time + public bool Locked { get; set; } public static void RegisterScripts(Page page, Control ctl) { @@ -64,7 +65,7 @@ public static string GetInitScript(Control ctl) LookupScriptValues(ctl, out grantImagePath, out denyImagePath, out nullImagePath, out lockImagePath, out grantAltText, out denyAltText, out nullAltText); string script = - String.Format( + string.Format( @"jQuery(document).ready( function() {{ var images = {{ 'True': '{0}', 'False': '{1}', 'Null': '{2}' }}; @@ -84,66 +85,62 @@ public static string GetInitScript(Control ctl) return script; } - private static void LookupScriptValues(Control ctl, out string grantImagePath, out string denyImagePath, out string nullImagePath, out string lockImagePath, out string grantAltText, out string denyAltText, out string nullAltText) + protected override void OnInit(EventArgs e) { - grantImagePath = IconController.IconURL("Grant"); - denyImagePath = IconController.IconURL("Deny"); - nullImagePath = IconController.IconURL("Unchecked"); - lockImagePath = IconController.IconURL("Lock"); + base.OnInit(e); - grantAltText = Localization.GetString("PermissionTypeGrant"); - denyAltText = Localization.GetString("PermissionTypeDeny"); - nullAltText = Localization.GetString("PermissionTypeNull"); + RegisterScripts(this.Page, this); } protected override void Render(HtmlTextWriter writer) { string imagePath; string altText; - switch (Value) + switch (this.Value) { case "True": - imagePath = _grantImagePath; - altText = _grantAltText; + imagePath = this._grantImagePath; + altText = this._grantAltText; break; case "False": - imagePath = _denyImagePath; - altText = _denyAltText; + imagePath = this._denyImagePath; + altText = this._denyAltText; break; default: - imagePath = _nullImagePath; - altText = _nullAltText; + imagePath = this._nullImagePath; + altText = this._nullAltText; break; } string cssClass = "tristate"; - if (Locked) + if (this.Locked) { - imagePath = _lockImagePath; + imagePath = this._lockImagePath; cssClass += " lockedPerm"; - //altText is set based on Value + + // altText is set based on Value } - if (!SupportsDenyMode) + if (!this.SupportsDenyMode) { cssClass += " noDenyPerm"; } - if (IsFullControl) + if (this.IsFullControl) { cssClass += " fullControl"; } - if (IsView && !Locked) + if (this.IsView && !this.Locked) { cssClass += " view"; } - if (!String.IsNullOrEmpty(PermissionKey) && !IsView && !IsFullControl) + if (!string.IsNullOrEmpty(this.PermissionKey) && !this.IsView && !this.IsFullControl) { - cssClass += " " + PermissionKey.ToLowerInvariant(); + cssClass += " " + this.PermissionKey.ToLowerInvariant(); } writer.Write("{1}", imagePath, altText); @@ -152,13 +149,17 @@ protected override void Render(HtmlTextWriter writer) base.Render(writer); } - public bool IsFullControl { get; set; } - - public bool IsView { get; set; } + private static void LookupScriptValues(Control ctl, out string grantImagePath, out string denyImagePath, out string nullImagePath, out string lockImagePath, out string grantAltText, out string denyAltText, out string nullAltText) + { + grantImagePath = IconController.IconURL("Grant"); + denyImagePath = IconController.IconURL("Deny"); + nullImagePath = IconController.IconURL("Unchecked"); + lockImagePath = IconController.IconURL("Lock"); - //Locked is currently not used on a post-back and therefore the - //value on postback is undefined at this time - public bool Locked { get; set; } + grantAltText = Localization.GetString("PermissionTypeGrant"); + denyAltText = Localization.GetString("PermissionTypeDeny"); + nullAltText = Localization.GetString("PermissionTypeNull"); + } public string PermissionKey { get; set; } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs index acd2b47aae7..30823300871 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs @@ -1,47 +1,49 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls.Internal { - class PermissionTriStateTemplate : ITemplate + using System; + using System.Data; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Security.Permissions; + + internal class PermissionTriStateTemplate : ITemplate { private readonly PermissionInfo _permission; public PermissionTriStateTemplate(PermissionInfo permission) { - _permission = permission; + this._permission = permission; } + + public bool IsFullControl { get; set; } + + public bool IsView { get; set; } + + public bool SupportDenyMode { get; set; } + public void InstantiateIn(Control container) { var triState = new PermissionTriState(); - triState.DataBinding += BindToTriState; + triState.DataBinding += this.BindToTriState; container.Controls.Add(triState); } - + public void BindToTriState(object sender, EventArgs e) { - var triState = (PermissionTriState) sender; - var dataRowView = ((DataRowView) ((DataGridItem)triState.NamingContainer).DataItem); + var triState = (PermissionTriState)sender; + var dataRowView = (DataRowView)((DataGridItem)triState.NamingContainer).DataItem; - triState.Value = dataRowView[_permission.PermissionName].ToString(); - triState.Locked = !bool.Parse(dataRowView[_permission.PermissionName + "_Enabled"].ToString()); - triState.SupportsDenyMode = SupportDenyMode; - triState.IsFullControl = IsFullControl; - triState.IsView = IsView; - triState.PermissionKey = _permission.PermissionKey; + triState.Value = dataRowView[this._permission.PermissionName].ToString(); + triState.Locked = !bool.Parse(dataRowView[this._permission.PermissionName + "_Enabled"].ToString()); + triState.SupportsDenyMode = this.SupportDenyMode; + triState.IsFullControl = this.IsFullControl; + triState.IsView = this.IsView; + triState.PermissionKey = this._permission.PermissionKey; } - - public bool IsFullControl { get; set; } - - public bool IsView { get; set; } - - public bool SupportDenyMode { get; set; } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs index 99d1cb23fb3..d84016d99bd 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs @@ -1,502 +1,490 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Localization; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.UI.WebControls + // ReSharper restore CheckNamespace { - - public class RolesSelectionGrid : Control, INamingContainer - { - - #region Private Members - - private readonly DataTable _dtRoleSelections = new DataTable(); - private IList _roles; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Localization; + + public class RolesSelectionGrid : Control, INamingContainer + { + private readonly DataTable _dtRoleSelections = new DataTable(); + private IList _roles; private IList _selectedRoles; - private DropDownList cboRoleGroups; - private DataGrid dgRoleSelection; - private Label lblGroups; - private Panel pnlRoleSlections; - - #endregion - - #region Public Properties - - #region DataGrid Properties - - - public TableItemStyle AlternatingItemStyle - { - get - { - return dgRoleSelection.AlternatingItemStyle; - } - } - - public bool AutoGenerateColumns - { - get - { - return dgRoleSelection.AutoGenerateColumns; - } - set - { - dgRoleSelection.AutoGenerateColumns = value; - } - } - - public int CellSpacing - { - get - { - return dgRoleSelection.CellSpacing; - } - set - { - dgRoleSelection.CellSpacing = value; - } - } - - public DataGridColumnCollection Columns - { - get - { - return dgRoleSelection.Columns; - } - } - - public TableItemStyle FooterStyle - { - get - { - return dgRoleSelection.FooterStyle; - } - } - - public GridLines GridLines - { - get - { - return dgRoleSelection.GridLines; - } - set - { - dgRoleSelection.GridLines = value; - } - } - - public TableItemStyle HeaderStyle - { - get - { - return dgRoleSelection.HeaderStyle; - } - } - - public TableItemStyle ItemStyle - { - get - { - return dgRoleSelection.ItemStyle; - } - } - - public DataGridItemCollection Items - { - get - { - return dgRoleSelection.Items; - } - } - - public TableItemStyle SelectedItemStyle - { - get - { - return dgRoleSelection.SelectedItemStyle; - } - } - - #endregion - - /// - /// List of the Names of the selected Roles - /// - public ArrayList SelectedRoleNames - { - get - { - UpdateRoleSelections(); - return (new ArrayList(CurrentRoleSelection.ToArray())); - } - set - { - CurrentRoleSelection = value.Cast().ToList(); - } - } - - /// - /// Gets and Sets the ResourceFile to localize permissions - /// - public string ResourceFile { get; set; } - - /// - /// Enable ShowAllUsers to display the virtuell "Unauthenticated Users" role - /// - public bool ShowUnauthenticatedUsers - { - get - { - if (ViewState["ShowUnauthenticatedUsers"] == null) - { - return false; - } - return Convert.ToBoolean(ViewState["ShowUnauthenticatedUsers"]); - } - set - { - ViewState["ShowUnauthenticatedUsers"] = value; - } - } - - /// - /// Enable ShowAllUsers to display the virtuell "All Users" role - /// - public bool ShowAllUsers - { - get - { - if (ViewState["ShowAllUsers"] == null) - { - return false; - } - return Convert.ToBoolean(ViewState["ShowAllUsers"]); - } - set - { - ViewState["ShowAllUsers"] = value; - } - } - - #endregion - - #region Private Properties - - private DataTable dtRolesSelection - { - get - { - return _dtRoleSelections; - } - } + private DropDownList cboRoleGroups; + private DataGrid dgRoleSelection; + private Label lblGroups; + private Panel pnlRoleSlections; + + public TableItemStyle AlternatingItemStyle + { + get + { + return this.dgRoleSelection.AlternatingItemStyle; + } + } + + public bool AutoGenerateColumns + { + get + { + return this.dgRoleSelection.AutoGenerateColumns; + } + + set + { + this.dgRoleSelection.AutoGenerateColumns = value; + } + } + + public int CellSpacing + { + get + { + return this.dgRoleSelection.CellSpacing; + } + + set + { + this.dgRoleSelection.CellSpacing = value; + } + } + + public DataGridColumnCollection Columns + { + get + { + return this.dgRoleSelection.Columns; + } + } + + public TableItemStyle FooterStyle + { + get + { + return this.dgRoleSelection.FooterStyle; + } + } + + public GridLines GridLines + { + get + { + return this.dgRoleSelection.GridLines; + } + + set + { + this.dgRoleSelection.GridLines = value; + } + } + + public TableItemStyle HeaderStyle + { + get + { + return this.dgRoleSelection.HeaderStyle; + } + } + + public TableItemStyle ItemStyle + { + get + { + return this.dgRoleSelection.ItemStyle; + } + } + + public DataGridItemCollection Items + { + get + { + return this.dgRoleSelection.Items; + } + } + + public TableItemStyle SelectedItemStyle + { + get + { + return this.dgRoleSelection.SelectedItemStyle; + } + } + + /// + /// Gets or sets list of the Names of the selected Roles. + /// + public ArrayList SelectedRoleNames + { + get + { + this.UpdateRoleSelections(); + return new ArrayList(this.CurrentRoleSelection.ToArray()); + } + + set + { + this.CurrentRoleSelection = value.Cast().ToList(); + } + } + + /// + /// Gets or sets and Sets the ResourceFile to localize permissions. + /// + public string ResourceFile { get; set; } + + /// + /// Gets or sets a value indicating whether enable ShowAllUsers to display the virtuell "Unauthenticated Users" role. + /// + public bool ShowUnauthenticatedUsers + { + get + { + if (this.ViewState["ShowUnauthenticatedUsers"] == null) + { + return false; + } + + return Convert.ToBoolean(this.ViewState["ShowUnauthenticatedUsers"]); + } + + set + { + this.ViewState["ShowUnauthenticatedUsers"] = value; + } + } + + /// + /// Gets or sets a value indicating whether enable ShowAllUsers to display the virtuell "All Users" role. + /// + public bool ShowAllUsers + { + get + { + if (this.ViewState["ShowAllUsers"] == null) + { + return false; + } + + return Convert.ToBoolean(this.ViewState["ShowAllUsers"]); + } + + set + { + this.ViewState["ShowAllUsers"] = value; + } + } + + private DataTable dtRolesSelection + { + get + { + return this._dtRoleSelections; + } + } private IList CurrentRoleSelection - { - get - { - return _selectedRoles ?? (_selectedRoles = new List()); - } + { + get + { + return this._selectedRoles ?? (this._selectedRoles = new List()); + } + set - { - _selectedRoles = value; - } - } - - #endregion - - #region Private Methods - - /// - /// Bind the data to the controls - /// - private void BindData() - { - EnsureChildControls(); - - BindRolesGrid(); - } - - /// - /// Bind the Roles data to the Grid - /// - private void BindRolesGrid() - { - dtRolesSelection.Columns.Clear(); - dtRolesSelection.Rows.Clear(); - - //Add Roles Column - var col = new DataColumn("RoleId", typeof (string)); - dtRolesSelection.Columns.Add(col); - - //Add Roles Column - col = new DataColumn("RoleName", typeof (string)); - dtRolesSelection.Columns.Add(col); - - //Add Selected Column - col = new DataColumn("Selected", typeof (bool)); - dtRolesSelection.Columns.Add(col); - - GetRoles(); - - UpdateRoleSelections(); - for (int i = 0; i <= _roles.Count - 1; i++) - { - var role = _roles[i]; - DataRow row = dtRolesSelection.NewRow(); - row["RoleId"] = role.RoleID; - row["RoleName"] = Localization.LocalizeRole(role.RoleName); - row["Selected"] = GetSelection(role.RoleName); - - dtRolesSelection.Rows.Add(row); - } - dgRoleSelection.DataSource = dtRolesSelection; - dgRoleSelection.DataBind(); - } - - private bool GetSelection(string roleName) - { - return CurrentRoleSelection.Any(r => r == roleName); - } - - /// - /// Gets the roles from the Database and loads them into the Roles property - /// - private void GetRoles() - { - int roleGroupId = -2; - if ((cboRoleGroups != null) && (cboRoleGroups.SelectedValue != null)) - { - roleGroupId = int.Parse(cboRoleGroups.SelectedValue); - } - - _roles = roleGroupId > -2 + { + this._selectedRoles = value; + } + } + + /// + /// Load the ViewState. + /// + /// The saved state. + protected override void LoadViewState(object savedState) + { + if (savedState != null) + { + // Load State from the array of objects that was saved with SaveViewState. + var myState = (object[])savedState; + + // Load Base Controls ViewState + if (myState[0] != null) + { + base.LoadViewState(myState[0]); + } + + // Load TabPermissions + if (myState[1] != null) + { + string state = Convert.ToString(myState[1]); + this.CurrentRoleSelection = state != string.Empty + ? new List(state.Split(new[] { "##" }, StringSplitOptions.None)) + : new List(); + } + } + } + + /// + /// Saves the ViewState. + /// + /// + protected override object SaveViewState() + { + var allStates = new object[2]; + + // Save the Base Controls ViewState + allStates[0] = base.SaveViewState(); + + // Persist the TabPermisisons + var sb = new StringBuilder(); + bool addDelimiter = false; + foreach (string role in this.CurrentRoleSelection) + { + if (addDelimiter) + { + sb.Append("##"); + } + else + { + addDelimiter = true; + } + + sb.Append(role); + } + + allStates[1] = sb.ToString(); + return allStates; + } + + /// + /// Bind the data to the controls. + /// + private void BindData() + { + this.EnsureChildControls(); + + this.BindRolesGrid(); + } + + /// + /// Bind the Roles data to the Grid. + /// + private void BindRolesGrid() + { + this.dtRolesSelection.Columns.Clear(); + this.dtRolesSelection.Rows.Clear(); + + // Add Roles Column + var col = new DataColumn("RoleId", typeof(string)); + this.dtRolesSelection.Columns.Add(col); + + // Add Roles Column + col = new DataColumn("RoleName", typeof(string)); + this.dtRolesSelection.Columns.Add(col); + + // Add Selected Column + col = new DataColumn("Selected", typeof(bool)); + this.dtRolesSelection.Columns.Add(col); + + this.GetRoles(); + + this.UpdateRoleSelections(); + for (int i = 0; i <= this._roles.Count - 1; i++) + { + var role = this._roles[i]; + DataRow row = this.dtRolesSelection.NewRow(); + row["RoleId"] = role.RoleID; + row["RoleName"] = Localization.LocalizeRole(role.RoleName); + row["Selected"] = this.GetSelection(role.RoleName); + + this.dtRolesSelection.Rows.Add(row); + } + + this.dgRoleSelection.DataSource = this.dtRolesSelection; + this.dgRoleSelection.DataBind(); + } + + private bool GetSelection(string roleName) + { + return this.CurrentRoleSelection.Any(r => r == roleName); + } + + /// + /// Gets the roles from the Database and loads them into the Roles property. + /// + private void GetRoles() + { + int roleGroupId = -2; + if ((this.cboRoleGroups != null) && (this.cboRoleGroups.SelectedValue != null)) + { + roleGroupId = int.Parse(this.cboRoleGroups.SelectedValue); + } + + this._roles = roleGroupId > -2 ? RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.RoleGroupID == roleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) : RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); - if (roleGroupId < 0) - { - if (ShowUnauthenticatedUsers) - { - _roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleUnauthUser), RoleName = Globals.glbRoleUnauthUserName }); - } - if (ShowAllUsers) - { - _roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers), RoleName = Globals.glbRoleAllUsersName }); - } - } - _roles = _roles.OrderBy(r => r.RoleName).ToList(); - } - - /// - /// Sets up the columns for the Grid - /// - private void SetUpRolesGrid() - { - dgRoleSelection.Columns.Clear(); - var textCol = new BoundColumn {HeaderText = " ", DataField = "RoleName"}; - textCol.ItemStyle.Width = Unit.Parse("150px"); - dgRoleSelection.Columns.Add(textCol); - var idCol = new BoundColumn {HeaderText = "", DataField = "roleid", Visible = false}; - dgRoleSelection.Columns.Add(idCol); - var checkCol = new TemplateColumn(); - var columnTemplate = new CheckBoxColumnTemplate {DataField = "Selected"}; - checkCol.ItemTemplate = columnTemplate; - checkCol.HeaderText = Localization.GetString("SelectedRole"); - checkCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center; - checkCol.HeaderStyle.Wrap = true; - dgRoleSelection.Columns.Add(checkCol); - } - - #endregion - - #region Protected Methods - - /// - /// Load the ViewState - /// - /// The saved state - protected override void LoadViewState(object savedState) - { - if (savedState != null) - { - //Load State from the array of objects that was saved with SaveViewState. - var myState = (object[]) savedState; - - //Load Base Controls ViewState - if (myState[0] != null) - { - base.LoadViewState(myState[0]); - } - - //Load TabPermissions - if (myState[1] != null) - { - string state = Convert.ToString(myState[1]); - CurrentRoleSelection = state != string.Empty - ? new List(state.Split(new[] {"##"}, StringSplitOptions.None)) - : new List(); - } - } - } - - /// - /// Saves the ViewState - /// - protected override object SaveViewState() - { - var allStates = new object[2]; - - //Save the Base Controls ViewState - allStates[0] = base.SaveViewState(); - //Persist the TabPermisisons - var sb = new StringBuilder(); - bool addDelimiter = false; - foreach (string role in CurrentRoleSelection) - { - if (addDelimiter) - { - sb.Append("##"); - } - else - { - addDelimiter = true; - } - sb.Append(role); - } - allStates[1] = sb.ToString(); - return allStates; - } - - /// - /// Creates the Child Controls - /// - protected override void CreateChildControls() - { - pnlRoleSlections = new Panel {CssClass = "dnnRolesGrid"}; - - //Optionally Add Role Group Filter - PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - ArrayList arrGroups = RoleController.GetRoleGroups(_portalSettings.PortalId); - if (arrGroups.Count > 0) - { - lblGroups = new Label {Text = Localization.GetString("RoleGroupFilter")}; - pnlRoleSlections.Controls.Add(lblGroups); - - pnlRoleSlections.Controls.Add(new LiteralControl("  ")); - - cboRoleGroups = new DropDownList {AutoPostBack = true}; - - cboRoleGroups.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); - var liItem = new ListItem(Localization.GetString("GlobalRoles"), "-1") {Selected = true}; - cboRoleGroups.Items.Add(liItem); - foreach (RoleGroupInfo roleGroup in arrGroups) - { - cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture))); - } - pnlRoleSlections.Controls.Add(cboRoleGroups); - - pnlRoleSlections.Controls.Add(new LiteralControl("

    ")); - } - dgRoleSelection = new DataGrid {AutoGenerateColumns = false, CellSpacing = 0, GridLines = GridLines.None}; - dgRoleSelection.FooterStyle.CssClass = "dnnGridFooter"; - dgRoleSelection.HeaderStyle.CssClass = "dnnGridHeader"; - dgRoleSelection.ItemStyle.CssClass = "dnnGridItem"; - dgRoleSelection.AlternatingItemStyle.CssClass = "dnnGridAltItem"; - SetUpRolesGrid(); - pnlRoleSlections.Controls.Add(dgRoleSelection); - - Controls.Add(pnlRoleSlections); - } - - /// - /// Overrides the base OnPreRender method to Bind the Grid to the Permissions - /// - protected override void OnPreRender(EventArgs e) - { - BindData(); - } - - /// - /// Updates a Selection - /// - /// The name of the role - /// - protected virtual void UpdateSelection(string roleName, bool Selected) - { - var isMatch = false; - foreach (string currentRoleName in CurrentRoleSelection) - { - if (currentRoleName == roleName) - { - //role is in collection - if (!Selected) - { - //Remove from collection as we only keep selected roles - CurrentRoleSelection.Remove(currentRoleName); - } - isMatch = true; - break; - } - } - - //Rolename not found so add new - if (!isMatch && Selected) - { - CurrentRoleSelection.Add(roleName); - } - } - - /// - /// Updates the Selections - /// - protected void UpdateSelections() - { - EnsureChildControls(); - - UpdateRoleSelections(); - } - - /// - /// Updates the permissions - /// - protected void UpdateRoleSelections() - { - if (dgRoleSelection != null) - { - foreach (DataGridItem dgi in dgRoleSelection.Items) - { - const int i = 2; - if (dgi.Cells[i].Controls.Count > 0) - { - var cb = (CheckBox) dgi.Cells[i].Controls[0]; - UpdateSelection(dgi.Cells[0].Text, cb.Checked); - } - } - } - } - - #endregion - - } + if (roleGroupId < 0) + { + if (this.ShowUnauthenticatedUsers) + { + this._roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleUnauthUser), RoleName = Globals.glbRoleUnauthUserName }); + } + + if (this.ShowAllUsers) + { + this._roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers), RoleName = Globals.glbRoleAllUsersName }); + } + } + + this._roles = this._roles.OrderBy(r => r.RoleName).ToList(); + } + + /// + /// Sets up the columns for the Grid. + /// + private void SetUpRolesGrid() + { + this.dgRoleSelection.Columns.Clear(); + var textCol = new BoundColumn { HeaderText = " ", DataField = "RoleName" }; + textCol.ItemStyle.Width = Unit.Parse("150px"); + this.dgRoleSelection.Columns.Add(textCol); + var idCol = new BoundColumn { HeaderText = string.Empty, DataField = "roleid", Visible = false }; + this.dgRoleSelection.Columns.Add(idCol); + var checkCol = new TemplateColumn(); + var columnTemplate = new CheckBoxColumnTemplate { DataField = "Selected" }; + checkCol.ItemTemplate = columnTemplate; + checkCol.HeaderText = Localization.GetString("SelectedRole"); + checkCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + checkCol.HeaderStyle.Wrap = true; + this.dgRoleSelection.Columns.Add(checkCol); + } + + /// + /// Creates the Child Controls. + /// + protected override void CreateChildControls() + { + this.pnlRoleSlections = new Panel { CssClass = "dnnRolesGrid" }; + + // Optionally Add Role Group Filter + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + ArrayList arrGroups = RoleController.GetRoleGroups(_portalSettings.PortalId); + if (arrGroups.Count > 0) + { + this.lblGroups = new Label { Text = Localization.GetString("RoleGroupFilter") }; + this.pnlRoleSlections.Controls.Add(this.lblGroups); + + this.pnlRoleSlections.Controls.Add(new LiteralControl("  ")); + + this.cboRoleGroups = new DropDownList { AutoPostBack = true }; + + this.cboRoleGroups.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); + var liItem = new ListItem(Localization.GetString("GlobalRoles"), "-1") { Selected = true }; + this.cboRoleGroups.Items.Add(liItem); + foreach (RoleGroupInfo roleGroup in arrGroups) + { + this.cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture))); + } + + this.pnlRoleSlections.Controls.Add(this.cboRoleGroups); + + this.pnlRoleSlections.Controls.Add(new LiteralControl("

    ")); + } + + this.dgRoleSelection = new DataGrid { AutoGenerateColumns = false, CellSpacing = 0, GridLines = GridLines.None }; + this.dgRoleSelection.FooterStyle.CssClass = "dnnGridFooter"; + this.dgRoleSelection.HeaderStyle.CssClass = "dnnGridHeader"; + this.dgRoleSelection.ItemStyle.CssClass = "dnnGridItem"; + this.dgRoleSelection.AlternatingItemStyle.CssClass = "dnnGridAltItem"; + this.SetUpRolesGrid(); + this.pnlRoleSlections.Controls.Add(this.dgRoleSelection); + + this.Controls.Add(this.pnlRoleSlections); + } + + /// + /// Overrides the base OnPreRender method to Bind the Grid to the Permissions. + /// + protected override void OnPreRender(EventArgs e) + { + this.BindData(); + } + + /// + /// Updates a Selection. + /// + /// The name of the role. + /// + protected virtual void UpdateSelection(string roleName, bool Selected) + { + var isMatch = false; + foreach (string currentRoleName in this.CurrentRoleSelection) + { + if (currentRoleName == roleName) + { + // role is in collection + if (!Selected) + { + // Remove from collection as we only keep selected roles + this.CurrentRoleSelection.Remove(currentRoleName); + } + + isMatch = true; + break; + } + } + + // Rolename not found so add new + if (!isMatch && Selected) + { + this.CurrentRoleSelection.Add(roleName); + } + } + + /// + /// Updates the Selections. + /// + protected void UpdateSelections() + { + this.EnsureChildControls(); + + this.UpdateRoleSelections(); + } + + /// + /// Updates the permissions. + /// + protected void UpdateRoleSelections() + { + if (this.dgRoleSelection != null) + { + foreach (DataGridItem dgi in this.dgRoleSelection.Items) + { + const int i = 2; + if (dgi.Cells[i].Controls.Count > 0) + { + var cb = (CheckBox)dgi.Cells[i].Controls[0]; + this.UpdateSelection(dgi.Cells[0].Text, cb.Checked); + } + } + } + } + } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs index e9f25a1b68a..dfb57d4a06c 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs @@ -1,56 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Web; + using System.Web.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: TextColumn /// ----------------------------------------------------------------------------- /// - /// The TextColumn control provides a custom Text Column + /// The TextColumn control provides a custom Text Column. /// /// ----------------------------------------------------------------------------- public class TextColumn : TemplateColumn - { - /// ----------------------------------------------------------------------------- - /// - /// The Data Field is the field that binds to the Text Column - /// - /// A String - /// ----------------------------------------------------------------------------- - public string DataField { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Text (for Header/Footer Templates) - /// - /// A String - /// ----------------------------------------------------------------------------- - public string Text { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Width of the Column - /// - /// A Unit - /// ----------------------------------------------------------------------------- + { + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Data Field is the field that binds to the Text Column. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string DataField { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Text (for Header/Footer Templates). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string Text { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Width of the Column. + /// + /// A Unit. + /// ----------------------------------------------------------------------------- public Unit Width { get; set; } /// ----------------------------------------------------------------------------- /// - /// Creates a TextColumnTemplate + /// Initialises the Column. /// - /// A TextColumnTemplate + /// ----------------------------------------------------------------------------- + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); + if (HttpContext.Current == null) + { + this.ItemStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.ItemStyle.Font.Size = new FontUnit("10pt"); + this.ItemStyle.HorizontalAlign = HorizontalAlign.Left; + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Left; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Creates a TextColumnTemplate. + /// + /// A TextColumnTemplate. /// ----------------------------------------------------------------------------- private TextColumnTemplate CreateTemplate(ListItemType type) { @@ -59,44 +76,25 @@ private TextColumnTemplate CreateTemplate(ListItemType type) { isDesignMode = true; } + var template = new TextColumnTemplate(type); if (type != ListItemType.Header) { - template.DataField = DataField; + template.DataField = this.DataField; } - template.Width = Width; + + template.Width = this.Width; if (type == ListItemType.Header) { - template.Text = HeaderText; + template.Text = this.HeaderText; } else { - template.Text = Text; + template.Text = this.Text; } + template.DesignMode = isDesignMode; return template; } - - /// ----------------------------------------------------------------------------- - /// - /// Initialises the Column - /// - /// ----------------------------------------------------------------------------- - public override void Initialize() - { - ItemTemplate = CreateTemplate(ListItemType.Item); - EditItemTemplate = CreateTemplate(ListItemType.EditItem); - HeaderTemplate = CreateTemplate(ListItemType.Header); - if (HttpContext.Current == null) - { - ItemStyle.Font.Names = new[] {"Tahoma, Verdana, Arial"}; - ItemStyle.Font.Size = new FontUnit("10pt"); - ItemStyle.HorizontalAlign = HorizontalAlign.Left; - HeaderStyle.Font.Names = new[] {"Tahoma, Verdana, Arial"}; - HeaderStyle.Font.Size = new FontUnit("10pt"); - HeaderStyle.Font.Bold = true; - HeaderStyle.HorizontalAlign = HorizontalAlign.Left; - } - } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs index dee4b162c70..9cba6a8d033 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs @@ -1,202 +1,180 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: TextColumnTemplate /// ----------------------------------------------------------------------------- /// - /// The TextColumnTemplate provides a Template for the TextColumn + /// The TextColumnTemplate provides a Template for the TextColumn. /// /// ----------------------------------------------------------------------------- public class TextColumnTemplate : ITemplate - { - #region "Private Members" - - private ListItemType mItemType = ListItemType.Item; - - #endregion - - #region "Constructors" - - public TextColumnTemplate() : this(ListItemType.Item) + { + private ListItemType mItemType = ListItemType.Item; + + public TextColumnTemplate() + : this(ListItemType.Item) { } public TextColumnTemplate(ListItemType itemType) { - ItemType = itemType; - } - - #endregion - - #region "Public Properties" - - /// ----------------------------------------------------------------------------- - /// - /// The Data Field is the field that binds to the Text Column - /// - /// A String - /// ----------------------------------------------------------------------------- + this.ItemType = itemType; + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Data Field is the field that binds to the Text Column. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string DataField { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Design Mode of the Column - /// - /// A Boolean - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool DesignMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// The type of Template to Create + /// Gets or sets the type of Template to Create. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public ListItemType ItemType { get { - return mItemType; + return this.mItemType; } + set { - mItemType = value; + this.mItemType = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Text (for Header/Footer Templates) - /// - /// A String - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Text (for Header/Footer Templates). + /// + /// A String. + /// ----------------------------------------------------------------------------- public string Text { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Width of the Column - /// - /// A Unit - /// ----------------------------------------------------------------------------- - public Unit Width { get; set; } - - #endregion - - #region ITemplate Members - /// ----------------------------------------------------------------------------- /// - /// InstantiateIn instantiates the template (implementation of ITemplate) + /// Gets or sets the Width of the Column. + /// + /// A Unit. + /// ----------------------------------------------------------------------------- + public Unit Width { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// InstantiateIn instantiates the template (implementation of ITemplate). /// /// /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). /// ----------------------------------------------------------------------------- public void InstantiateIn(Control container) { - switch (ItemType) + switch (this.ItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: case ListItemType.SelectedItem: var lblText = new Label(); - lblText.Width = Width; - lblText.DataBinding += Item_DataBinding; + lblText.Width = this.Width; + lblText.DataBinding += this.Item_DataBinding; container.Controls.Add(lblText); break; case ListItemType.EditItem: var txtText = new TextBox(); - txtText.Width = Width; - txtText.DataBinding += Item_DataBinding; + txtText.Width = this.Width; + txtText.DataBinding += this.Item_DataBinding; container.Controls.Add(txtText); break; case ListItemType.Footer: case ListItemType.Header: - container.Controls.Add(new LiteralControl(Text)); + container.Controls.Add(new LiteralControl(this.Text)); break; } - } - - #endregion - - #region "Private Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Data Field + /// Gets the value of the Data Field. /// - /// The parent container (DataGridItem) + /// The parent container (DataGridItem). /// ----------------------------------------------------------------------------- private string GetValue(DataGridItem container) { string itemValue = Null.NullString; - if (!String.IsNullOrEmpty(DataField)) + if (!string.IsNullOrEmpty(this.DataField)) { - if (DesignMode) + if (this.DesignMode) { - itemValue = "DataBound to " + DataField; + itemValue = "DataBound to " + this.DataField; } else { if (container.DataItem != null) { - object evaluation = DataBinder.Eval(container.DataItem, DataField); - if ((evaluation != null)) + object evaluation = DataBinder.Eval(container.DataItem, this.DataField); + if (evaluation != null) { itemValue = evaluation.ToString(); } } } } + return itemValue; } /// ----------------------------------------------------------------------------- /// - /// Item_DataBinding runs when an Item of type ListItemType.Item is being data-bound + /// Item_DataBinding runs when an Item of type ListItemType.Item is being data-bound. /// /// /// - /// The object that triggers the event - /// An EventArgs object + /// The object that triggers the event. + /// An EventArgs object. /// ----------------------------------------------------------------------------- private void Item_DataBinding(object sender, EventArgs e) { DataGridItem container; int keyValue = Null.NullInteger; - switch (ItemType) + switch (this.ItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: case ListItemType.SelectedItem: - var lblText = (Label) sender; - container = (DataGridItem) lblText.NamingContainer; - lblText.Text = GetValue(container); + var lblText = (Label)sender; + container = (DataGridItem)lblText.NamingContainer; + lblText.Text = this.GetValue(container); break; case ListItemType.EditItem: - var txtText = (TextBox) sender; - container = (DataGridItem) txtText.NamingContainer; - txtText.Text = GetValue(container); + var txtText = (TextBox)sender; + container = (DataGridItem)txtText.NamingContainer; + txtText.Text = this.GetValue(container); break; } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/DualListBox.cs b/DNN Platform/Library/UI/WebControls/DualListBox.cs index 7074d04a4fd..ab32b367192 100644 --- a/DNN Platform/Library/UI/WebControls/DualListBox.cs +++ b/DNN Platform/Library/UI/WebControls/DualListBox.cs @@ -1,49 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Reflection; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.ComponentModel; + using System.Reflection; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Localization; + public class DualListBox : WebControl, IPostBackEventHandler, IPostBackDataHandler - { - #region Private Members - + { private readonly Style _AvailableListBoxStyle = new Style(); private readonly Style _ButtonStyle = new Style(); private readonly TableStyle _ContainerStyle = new TableStyle(); private readonly Style _HeaderStyle = new Style(); private readonly Style _SelectedListBoxStyle = new Style(); private List _AddValues; - private List _RemoveValues; - - #endregion - + private List _RemoveValues; + public DualListBox() { - ShowAddButton = true; - ShowAddAllButton = true; - ShowRemoveButton = true; - ShowRemoveAllButton = true; - } - - #region Public Properties - + this.ShowAddButton = true; + this.ShowAddAllButton = true; + this.ShowRemoveButton = true; + this.ShowRemoveAllButton = true; + } + + public event DualListBoxEventHandler AddButtonClick; + + public event EventHandler AddAllButtonClick; + + public event DualListBoxEventHandler RemoveButtonClick; + public string AddAllImageURL { get; set; } public string AddAllKey { get; set; } @@ -89,168 +84,191 @@ public DualListBox() public bool CausesValidation { get; set; } public string ValidationGroup { get; set; } - - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - - #region Style Properties - + /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Available List Box Style + /// Gets the value of the Available List Box Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), - TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Available List Box.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Available List Box.")] public Style AvailableListBoxStyle { get { - return _AvailableListBoxStyle; + return this._AvailableListBoxStyle; } } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Button Style + /// Gets the value of the Button Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), - TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Button.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Button.")] public Style ButtonStyle { get { - return _ButtonStyle; + return this._ButtonStyle; } } + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Container Style + /// Gets the value of the Container Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), - TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Container.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Container.")] public TableStyle ContainerStyle { get { - return _ContainerStyle; + return this._ContainerStyle; } } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Header Style + /// Gets the value of the Header Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), - TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Header.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Header.")] public Style HeaderStyle { get { - return _HeaderStyle; + return this._HeaderStyle; } } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Selected List Box Style + /// Gets the value of the Selected List Box Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), - TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Selected List Box.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Selected List Box.")] public Style SelectedListBoxStyle { get { - return _SelectedListBoxStyle; + return this._SelectedListBoxStyle; } - } - #endregion - - #endregion - - #region IPostBackDataHandler Members - + } + public bool LoadPostData(string postDataKey, NameValueCollection postCollection) { bool retValue = Null.NullBoolean; string addItems = postCollection[postDataKey + "_Available"]; if (!string.IsNullOrEmpty(addItems)) { - _AddValues = new List(); + this._AddValues = new List(); foreach (string addItem in addItems.Split(',')) { - _AddValues.Add(addItem); + this._AddValues.Add(addItem); } + retValue = true; } + string removeItems = postCollection[postDataKey + "_Selected"]; if (!string.IsNullOrEmpty(removeItems)) { - _RemoveValues = new List(); + this._RemoveValues = new List(); foreach (string removeItem in removeItems.Split(',')) { - _RemoveValues.Add(removeItem); + this._RemoveValues.Add(removeItem); } + retValue = true; } + return retValue; } public void RaisePostDataChangedEvent() { - } - - #endregion - - #region IPostBackEventHandler Members - + } + public void RaisePostBackEvent(string eventArgument) { switch (eventArgument) { case "Add": - OnAddButtonClick(new DualListBoxEventArgs(_AddValues)); + this.OnAddButtonClick(new DualListBoxEventArgs(this._AddValues)); break; case "AddAll": - OnAddAllButtonClick(new EventArgs()); + this.OnAddAllButtonClick(new EventArgs()); break; case "Remove": - OnRemoveButtonClick(new DualListBoxEventArgs(_RemoveValues)); + this.OnRemoveButtonClick(new DualListBoxEventArgs(this._RemoveValues)); break; case "RemoveAll": - OnRemoveAllButtonClick(new EventArgs()); + this.OnRemoveAllButtonClick(new EventArgs()); break; } - } - - #endregion - - #region Events - - public event DualListBoxEventHandler AddButtonClick; - public event EventHandler AddAllButtonClick; - public event DualListBoxEventHandler RemoveButtonClick; - public event EventHandler RemoveAllButtonClick; - - #endregion + } + + public event EventHandler RemoveAllButtonClick; - #region Private Methods + protected virtual PostBackOptions GetPostBackOptions(string argument) + { + var postBackOptions = new PostBackOptions(this, argument) { RequiresJavaScriptProtocol = true }; + if (this.CausesValidation && this.Page.GetValidators(this.ValidationGroup).Count > 0) + { + postBackOptions.PerformValidation = true; + postBackOptions.ValidationGroup = this.ValidationGroup; + } + + return postBackOptions; + } + + protected void OnAddButtonClick(DualListBoxEventArgs e) + { + if (this.AddButtonClick != null) + { + this.AddButtonClick(this, e); + } + } + private NameValueCollection GetList(string listType, object dataSource) { var dataList = dataSource as IEnumerable; @@ -264,14 +282,15 @@ private NameValueCollection GetList(string listType, object dataSource) foreach (object item in dataList) { BindingFlags bindings = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; - PropertyInfo objTextProperty = item.GetType().GetProperty(DataTextField, bindings); - PropertyInfo objValueProperty = item.GetType().GetProperty(DataValueField, bindings); + PropertyInfo objTextProperty = item.GetType().GetProperty(this.DataTextField, bindings); + PropertyInfo objValueProperty = item.GetType().GetProperty(this.DataValueField, bindings); string objValue = Convert.ToString(objValueProperty.GetValue(item, null)); string objText = Convert.ToString(objTextProperty.GetValue(item, null)); list.Add(objText, objValue); } } + return list; } @@ -280,48 +299,48 @@ private void RenderButton(string buttonType, HtmlTextWriter writer) string buttonText = Null.NullString; string imageURL = Null.NullString; - //Begin Button Row + // Begin Button Row writer.RenderBeginTag(HtmlTextWriterTag.Tr); - //Begin Button Cell + // Begin Button Cell writer.RenderBeginTag(HtmlTextWriterTag.Td); switch (buttonType) { case "Add": - buttonText = string.IsNullOrEmpty(AddKey) - ? AddText - : Localization.GetString(AddKey, LocalResourceFile); - imageURL = AddImageURL; + buttonText = string.IsNullOrEmpty(this.AddKey) + ? this.AddText + : Localization.GetString(this.AddKey, this.LocalResourceFile); + imageURL = this.AddImageURL; break; case "AddAll": - buttonText = string.IsNullOrEmpty(AddAllKey) - ? AddAllText - : Localization.GetString(AddAllKey, LocalResourceFile); - imageURL = AddAllImageURL; + buttonText = string.IsNullOrEmpty(this.AddAllKey) + ? this.AddAllText + : Localization.GetString(this.AddAllKey, this.LocalResourceFile); + imageURL = this.AddAllImageURL; break; case "Remove": - buttonText = string.IsNullOrEmpty(RemoveKey) - ? RemoveText - : Localization.GetString(RemoveKey, LocalResourceFile); - imageURL = RemoveImageURL; + buttonText = string.IsNullOrEmpty(this.RemoveKey) + ? this.RemoveText + : Localization.GetString(this.RemoveKey, this.LocalResourceFile); + imageURL = this.RemoveImageURL; break; case "RemoveAll": - buttonText = string.IsNullOrEmpty(RemoveAllKey) - ? RemoveAllText - : Localization.GetString(RemoveAllKey, LocalResourceFile); - imageURL = RemoveAllImageURL; + buttonText = string.IsNullOrEmpty(this.RemoveAllKey) + ? this.RemoveAllText + : Localization.GetString(this.RemoveAllKey, this.LocalResourceFile); + imageURL = this.RemoveAllImageURL; break; } - - //Render Hyperlink - writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackEventReference(GetPostBackOptions(buttonType))); + + // Render Hyperlink + writer.AddAttribute(HtmlTextWriterAttribute.Href, this.Page.ClientScript.GetPostBackEventReference(this.GetPostBackOptions(buttonType))); writer.AddAttribute(HtmlTextWriterAttribute.Title, buttonText); writer.RenderBeginTag(HtmlTextWriterTag.A); - //Render Image + // Render Image if (!string.IsNullOrEmpty(imageURL)) { - writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveClientUrl(imageURL)); + writer.AddAttribute(HtmlTextWriterAttribute.Src, this.ResolveClientUrl(imageURL)); writer.AddAttribute(HtmlTextWriterAttribute.Title, buttonText); writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); writer.RenderBeginTag(HtmlTextWriterTag.Img); @@ -331,55 +350,57 @@ private void RenderButton(string buttonType, HtmlTextWriter writer) { writer.Write(buttonText); } - - //End of Hyperlink + + // End of Hyperlink writer.RenderEndTag(); - //End of Button Cell + // End of Button Cell writer.RenderEndTag(); - //Render end of Button Row + // Render end of Button Row writer.RenderEndTag(); } private void RenderButtons(HtmlTextWriter writer) { - //render table + // render table writer.RenderBeginTag(HtmlTextWriterTag.Table); - if (ShowAddButton) + if (this.ShowAddButton) { - RenderButton("Add", writer); + this.RenderButton("Add", writer); } - if (ShowAddAllButton) + + if (this.ShowAddAllButton) { - RenderButton("AddAll", writer); + this.RenderButton("AddAll", writer); } - //Begin Button Row + // Begin Button Row writer.RenderBeginTag(HtmlTextWriterTag.Tr); - //Begin Button Cell + // Begin Button Cell writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(" "); - //End of Button Cell + // End of Button Cell writer.RenderEndTag(); - //Render end of Button Row + // Render end of Button Row writer.RenderEndTag(); - if (ShowRemoveButton) + if (this.ShowRemoveButton) { - RenderButton("Remove", writer); + this.RenderButton("Remove", writer); } - if (ShowRemoveAllButton) + + if (this.ShowRemoveAllButton) { - RenderButton("RemoveAll", writer); + this.RenderButton("RemoveAll", writer); } - //Render end of table + // Render end of table writer.RenderEndTag(); } @@ -387,28 +408,28 @@ private void RenderListBox(string listType, object dataSource, Style style, Html { if (dataSource != null) { - NameValueCollection list = GetList(listType, dataSource); + NameValueCollection list = this.GetList(listType, dataSource); if (list != null) { if (style != null) { style.AddAttributesToRender(writer); } - - //Render ListBox + + // Render ListBox writer.AddAttribute(HtmlTextWriterAttribute.Multiple, "multiple"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID + "_" + listType); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_" + listType); writer.RenderBeginTag(HtmlTextWriterTag.Select); for (int i = 0; i <= list.Count - 1; i++) { - //Render option tags for each item + // Render option tags for each item writer.AddAttribute(HtmlTextWriterAttribute.Value, list.Get(i)); writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(list.GetKey(i)); writer.RenderEndTag(); } - - //Render ListBox end + + // Render ListBox end writer.RenderEndTag(); } } @@ -416,127 +437,104 @@ private void RenderListBox(string listType, object dataSource, Style style, Html private void RenderHeader(HtmlTextWriter writer) { - //render Header row + // render Header row writer.RenderBeginTag(HtmlTextWriterTag.Tr); - if (HeaderStyle != null) + if (this.HeaderStyle != null) { - HeaderStyle.AddAttributesToRender(writer); + this.HeaderStyle.AddAttributesToRender(writer); } + writer.RenderBeginTag(HtmlTextWriterTag.Td); - writer.Write(Localization.GetString(ID + "_Available", LocalResourceFile)); + writer.Write(Localization.GetString(this.ID + "_Available", this.LocalResourceFile)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.RenderEndTag(); - if (HeaderStyle != null) + if (this.HeaderStyle != null) { - HeaderStyle.AddAttributesToRender(writer); + this.HeaderStyle.AddAttributesToRender(writer); } + writer.RenderBeginTag(HtmlTextWriterTag.Td); - writer.Write(Localization.GetString(ID + "_Selected", LocalResourceFile)); + writer.Write(Localization.GetString(this.ID + "_Selected", this.LocalResourceFile)); writer.RenderEndTag(); - //Render end of Header Row + // Render end of Header Row writer.RenderEndTag(); } private void RenderListBoxes(HtmlTextWriter writer) { - //render List Boxes row + // render List Boxes row writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); - RenderListBox("Available", AvailableDataSource, AvailableListBoxStyle, writer); + this.RenderListBox("Available", this.AvailableDataSource, this.AvailableListBoxStyle, writer); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); - RenderButtons(writer); + this.RenderButtons(writer); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); - RenderListBox("Selected", SelectedDataSource, SelectedListBoxStyle, writer); + this.RenderListBox("Selected", this.SelectedDataSource, this.SelectedListBoxStyle, writer); writer.RenderEndTag(); - //Render end of List Boxes Row + // Render end of List Boxes Row writer.RenderEndTag(); } - protected virtual PostBackOptions GetPostBackOptions(string argument) - { - var postBackOptions = new PostBackOptions(this, argument) {RequiresJavaScriptProtocol = true}; - - if (this.CausesValidation && this.Page.GetValidators(this.ValidationGroup).Count > 0) - { - postBackOptions.PerformValidation = true; - postBackOptions.ValidationGroup = this.ValidationGroup; - } - return postBackOptions; - } - - #endregion - - #region Protected Methods - - protected void OnAddButtonClick(DualListBoxEventArgs e) - { - if (AddButtonClick != null) - { - AddButtonClick(this, e); - } - } - protected void OnAddAllButtonClick(EventArgs e) { - if (AddAllButtonClick != null) + if (this.AddAllButtonClick != null) { - AddAllButtonClick(this, e); + this.AddAllButtonClick(this, e); } } protected void OnRemoveButtonClick(DualListBoxEventArgs e) { - if (RemoveButtonClick != null) + if (this.RemoveButtonClick != null) { - RemoveButtonClick(this, e); + this.RemoveButtonClick(this, e); } } protected void OnRemoveAllButtonClick(EventArgs e) { - if (RemoveAllButtonClick != null) + if (this.RemoveAllButtonClick != null) { - RemoveAllButtonClick(this, e); + this.RemoveAllButtonClick(this, e); } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (Page != null) + if (this.Page != null) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } protected override void RenderContents(HtmlTextWriter writer) { - //render table - if (ContainerStyle != null) + // render table + if (this.ContainerStyle != null) { - ContainerStyle.AddAttributesToRender(writer); + this.ContainerStyle.AddAttributesToRender(writer); } + writer.RenderBeginTag(HtmlTextWriterTag.Table); - //Render Header Row - RenderHeader(writer); + // Render Header Row + this.RenderHeader(writer); - //Render ListBox row - RenderListBoxes(writer); + // Render ListBox row + this.RenderListBoxes(writer); - //Render end of table + // Render end of table writer.RenderEndTag(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs index fa71600f024..f55d64a9080 100644 --- a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs @@ -1,16 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Generic; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -24,23 +19,24 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class DualListBoxEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new DualListBoxEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new DualListBoxEventArgs. /// - /// The items + /// The items. /// ----------------------------------------------------------------------------- public DualListBoxEventArgs(List items) { - Items = items; + this.Items = items; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Items + /// Gets or sets and sets the Items. /// - /// A List(Of String) + /// A List(Of String). /// ----------------------------------------------------------------------------- public List Items { get; set; } } diff --git a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs index 70d5650ed52..076f2ed7ec1 100644 --- a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs +++ b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { public delegate void DualListBoxEventHandler(object sender, DualListBoxEventArgs e); diff --git a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs index 98817707491..1d254d00673 100644 --- a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs +++ b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs @@ -1,376 +1,353 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - - /// - /// Language Selector control - /// - public class LanguageSelector : Control, INamingContainer - { - - #region LanguageItemStyle enum - - public enum LanguageItemStyle - { - FlagOnly = 1, - FlagAndCaption = 2, - CaptionOnly = 3 - } - - #endregion - - #region LanguageListDirection enum - - public enum LanguageListDirection - { - Horizontal = 1, - Vertical = 2 - } - - #endregion - - #region LanguageSelectionMode enum - - /// - /// Language Selection mode, offered to the user: single select or multiple select. - /// - public enum LanguageSelectionMode - { - Multiple = 1, - Single = 2 - } - - #endregion - - #region LanguageSelectionObject enum - - /// - /// Selection object: Language ("de", "en") or Locale ("de-DE", "en-US") - /// - public enum LanguageSelectionObject - { - NeutralCulture = 1, - SpecificCulture = 2 - } - - #endregion - - private Panel pnlControl; - - #region Public Properties - - /// - /// Gets or sets selection mode (single, multiple) - /// - public LanguageSelectionMode SelectionMode - { - get - { - if (ViewState["SelectionMode"] == null) - { - return LanguageSelectionMode.Single; - } - else - { - return (LanguageSelectionMode) ViewState["SelectionMode"]; - } - } - set - { - if (SelectionMode != value) - { - ViewState["SelectionMode"] = value; - if (Controls.Count > 0) - { - CreateChildControls(); //Recreate if already created - } - } - } - } - - /// - /// Gets or sets the type of objects to be selectable: NeutralCulture ("de") or SpecificCulture ("de-DE") - /// - public LanguageSelectionObject SelectionObject - { - get - { - if (ViewState["SelectionObject"] == null) - { - return LanguageSelectionObject.SpecificCulture; - } - else - { - return (LanguageSelectionObject) ViewState["SelectionObject"]; - } - } - set - { - if ((int) SelectionMode != (int) value) - { - ViewState["SelectionObject"] = value; - if (Controls.Count > 0) - { - CreateChildControls(); //Recreate if already created - } - } - } - } - - /// - /// Gets or sets the style of the language items - /// - public LanguageItemStyle ItemStyle - { - get - { - if (ViewState["ItemStyle"] == null) - { - return LanguageItemStyle.FlagAndCaption; - } - else - { - return (LanguageItemStyle) ViewState["ItemStyle"]; - } - } - set - { - if (ItemStyle != value) - { - ViewState["ItemStyle"] = value; - if (Controls.Count > 0) - { - CreateChildControls(); //Recreate if already created - } - } - } - } - - /// - /// Gets or sets the direction of the language list - /// - public LanguageListDirection ListDirection - { - get - { - if (ViewState["ListDirection"] == null) - { - return LanguageListDirection.Vertical; - } - else - { - return (LanguageListDirection) ViewState["ListDirection"]; - } - } - set - { - if (ListDirection != value) - { - ViewState["ListDirection"] = value; - if (Controls.Count > 0) - { - CreateChildControls(); //Recreate if already created - } - } - } - } - - /// - /// Gets or sets the list of selected languages - /// - public string[] SelectedLanguages - { - get - { - EnsureChildControls(); - var a = new ArrayList(); - if (GetCultures(SelectionObject == LanguageSelectionObject.SpecificCulture).Length < 2) - { - //return single language - PortalSettings _Settings = PortalController.Instance.GetCurrentPortalSettings(); - foreach (string strLocale in LocaleController.Instance.GetLocales(_Settings.PortalId).Keys) - { - a.Add(strLocale); - } - } - else - { - //create list of selected languages - foreach (CultureInfo c in GetCultures(SelectionObject == LanguageSelectionObject.SpecificCulture)) - { - if (SelectionMode == LanguageSelectionMode.Single) - { - if (((RadioButton) pnlControl.FindControl("opt" + c.Name)).Checked) - { - a.Add(c.Name); - } - } - else - { - if (((CheckBox) pnlControl.FindControl("chk" + c.Name)).Checked) - { - a.Add(c.Name); - } - } - } - } - return a.ToArray(typeof (string)) as string[]; - } - set - { - EnsureChildControls(); - if (SelectionMode == LanguageSelectionMode.Single && value.Length > 1) - { - throw new ArgumentException("Selection mode 'single' cannot have more than one selected item."); - } - foreach (CultureInfo c in GetCultures(SelectionObject == LanguageSelectionObject.SpecificCulture)) - { - if (SelectionMode == LanguageSelectionMode.Single) - { - ((RadioButton) pnlControl.FindControl("opt" + c.Name)).Checked = false; - } - else - { - ((CheckBox) pnlControl.FindControl("chk" + c.Name)).Checked = false; - } - } - foreach (string strLocale in value) - { - if (SelectionMode == LanguageSelectionMode.Single) - { - Control ctl = pnlControl.FindControl("opt" + strLocale); - if (ctl != null) - { - ((RadioButton) ctl).Checked = true; - } - } - else - { - Control ctl = pnlControl.FindControl("chk" + strLocale); - if (ctl != null) - { - ((CheckBox) ctl).Checked = true; - } - } - } - } - } - - #endregion - - #region Protected Methods - - /// - /// Create Child Controls - /// - protected override void CreateChildControls() - { - Controls.Clear(); - pnlControl = new Panel(); - pnlControl.CssClass = "dnnLangSelector"; - - Controls.Add(pnlControl); - pnlControl.Controls.Add(new LiteralControl("
      ")); - - foreach (var c in GetCultures(SelectionObject == LanguageSelectionObject.SpecificCulture)) - { - pnlControl.Controls.Add(new LiteralControl("
    • ")); - - var lblLocale = new HtmlGenericControl("label"); - if (SelectionMode == LanguageSelectionMode.Single) - { - var optLocale = new RadioButton(); - optLocale.ID = "opt" + c.Name; - optLocale.GroupName = pnlControl.ID + "_Locale"; - if (c.Name == Localization.SystemLocale) - { - optLocale.Checked = true; - } - pnlControl.Controls.Add(optLocale); - lblLocale.Attributes["for"] = optLocale.ClientID; - } - else - { - var chkLocale = new CheckBox(); - chkLocale.ID = "chk" + c.Name; - pnlControl.Controls.Add(chkLocale); - lblLocale.Attributes["for"] = chkLocale.ClientID; - } - - pnlControl.Controls.Add(lblLocale); - if (ItemStyle != LanguageItemStyle.CaptionOnly) - { - var imgLocale = new Image(); - imgLocale.ImageUrl = ResolveUrl("~/images/Flags/" + c.Name + ".gif"); - imgLocale.AlternateText = c.DisplayName; - imgLocale.Style["vertical-align"] = "middle"; - lblLocale.Controls.Add(imgLocale); - } - if (ItemStyle != LanguageItemStyle.FlagOnly) - { - lblLocale.Controls.Add(new LiteralControl(" " + c.DisplayName)); - } - pnlControl.Controls.Add(new LiteralControl("
    • ")); - } - pnlControl.Controls.Add(new LiteralControl("
    ")); - - //Hide if not more than one language - if (GetCultures(SelectionObject == LanguageSelectionObject.SpecificCulture).Length < 2) - { - Visible = false; - } - } - - #endregion - - #region " Private Methods " - - /// - /// retrieve the cultures, currently supported by the portal - /// - /// true: locales, false: neutral languages - /// Array of cultures - private CultureInfo[] GetCultures(bool specific) - { - var a = new ArrayList(); - PortalSettings _Settings = PortalController.Instance.GetCurrentPortalSettings(); - foreach (string strLocale in LocaleController.Instance.GetLocales(_Settings.PortalId).Keys) - { - var c = new CultureInfo(strLocale); - if (specific) - { - a.Add(c); - } - else - { - CultureInfo p = c.Parent; - if (!a.Contains(p)) - { - a.Add(p); - } - } - } - return (CultureInfo[]) a.ToArray(typeof (CultureInfo)); - } - - #endregion - - } + using System; + using System.Collections; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + + /// + /// Language Selector control. + /// + public class LanguageSelector : Control, INamingContainer + { + private Panel pnlControl; + + public enum LanguageItemStyle + { + FlagOnly = 1, + FlagAndCaption = 2, + CaptionOnly = 3, + } + + public enum LanguageListDirection + { + Horizontal = 1, + Vertical = 2, + } + + /// + /// Language Selection mode, offered to the user: single select or multiple select. + /// + public enum LanguageSelectionMode + { + Multiple = 1, + Single = 2, + } + + /// + /// Selection object: Language ("de", "en") or Locale ("de-DE", "en-US"). + /// + public enum LanguageSelectionObject + { + NeutralCulture = 1, + SpecificCulture = 2, + } + + /// + /// Gets or sets selection mode (single, multiple). + /// + public LanguageSelectionMode SelectionMode + { + get + { + if (this.ViewState["SelectionMode"] == null) + { + return LanguageSelectionMode.Single; + } + else + { + return (LanguageSelectionMode)this.ViewState["SelectionMode"]; + } + } + + set + { + if (this.SelectionMode != value) + { + this.ViewState["SelectionMode"] = value; + if (this.Controls.Count > 0) + { + this.CreateChildControls(); // Recreate if already created + } + } + } + } + + /// + /// Gets or sets the type of objects to be selectable: NeutralCulture ("de") or SpecificCulture ("de-DE"). + /// + public LanguageSelectionObject SelectionObject + { + get + { + if (this.ViewState["SelectionObject"] == null) + { + return LanguageSelectionObject.SpecificCulture; + } + else + { + return (LanguageSelectionObject)this.ViewState["SelectionObject"]; + } + } + + set + { + if ((int)this.SelectionMode != (int)value) + { + this.ViewState["SelectionObject"] = value; + if (this.Controls.Count > 0) + { + this.CreateChildControls(); // Recreate if already created + } + } + } + } + + /// + /// Gets or sets the style of the language items. + /// + public LanguageItemStyle ItemStyle + { + get + { + if (this.ViewState["ItemStyle"] == null) + { + return LanguageItemStyle.FlagAndCaption; + } + else + { + return (LanguageItemStyle)this.ViewState["ItemStyle"]; + } + } + + set + { + if (this.ItemStyle != value) + { + this.ViewState["ItemStyle"] = value; + if (this.Controls.Count > 0) + { + this.CreateChildControls(); // Recreate if already created + } + } + } + } + + /// + /// Gets or sets the direction of the language list. + /// + public LanguageListDirection ListDirection + { + get + { + if (this.ViewState["ListDirection"] == null) + { + return LanguageListDirection.Vertical; + } + else + { + return (LanguageListDirection)this.ViewState["ListDirection"]; + } + } + + set + { + if (this.ListDirection != value) + { + this.ViewState["ListDirection"] = value; + if (this.Controls.Count > 0) + { + this.CreateChildControls(); // Recreate if already created + } + } + } + } + + /// + /// Gets or sets the list of selected languages. + /// + public string[] SelectedLanguages + { + get + { + this.EnsureChildControls(); + var a = new ArrayList(); + if (this.GetCultures(this.SelectionObject == LanguageSelectionObject.SpecificCulture).Length < 2) + { + // return single language + PortalSettings _Settings = PortalController.Instance.GetCurrentPortalSettings(); + foreach (string strLocale in LocaleController.Instance.GetLocales(_Settings.PortalId).Keys) + { + a.Add(strLocale); + } + } + else + { + // create list of selected languages + foreach (CultureInfo c in this.GetCultures(this.SelectionObject == LanguageSelectionObject.SpecificCulture)) + { + if (this.SelectionMode == LanguageSelectionMode.Single) + { + if (((RadioButton)this.pnlControl.FindControl("opt" + c.Name)).Checked) + { + a.Add(c.Name); + } + } + else + { + if (((CheckBox)this.pnlControl.FindControl("chk" + c.Name)).Checked) + { + a.Add(c.Name); + } + } + } + } + + return a.ToArray(typeof(string)) as string[]; + } + + set + { + this.EnsureChildControls(); + if (this.SelectionMode == LanguageSelectionMode.Single && value.Length > 1) + { + throw new ArgumentException("Selection mode 'single' cannot have more than one selected item."); + } + + foreach (CultureInfo c in this.GetCultures(this.SelectionObject == LanguageSelectionObject.SpecificCulture)) + { + if (this.SelectionMode == LanguageSelectionMode.Single) + { + ((RadioButton)this.pnlControl.FindControl("opt" + c.Name)).Checked = false; + } + else + { + ((CheckBox)this.pnlControl.FindControl("chk" + c.Name)).Checked = false; + } + } + + foreach (string strLocale in value) + { + if (this.SelectionMode == LanguageSelectionMode.Single) + { + Control ctl = this.pnlControl.FindControl("opt" + strLocale); + if (ctl != null) + { + ((RadioButton)ctl).Checked = true; + } + } + else + { + Control ctl = this.pnlControl.FindControl("chk" + strLocale); + if (ctl != null) + { + ((CheckBox)ctl).Checked = true; + } + } + } + } + } + + /// + /// Create Child Controls. + /// + protected override void CreateChildControls() + { + this.Controls.Clear(); + this.pnlControl = new Panel(); + this.pnlControl.CssClass = "dnnLangSelector"; + + this.Controls.Add(this.pnlControl); + this.pnlControl.Controls.Add(new LiteralControl("
      ")); + + foreach (var c in this.GetCultures(this.SelectionObject == LanguageSelectionObject.SpecificCulture)) + { + this.pnlControl.Controls.Add(new LiteralControl("
    • ")); + + var lblLocale = new HtmlGenericControl("label"); + if (this.SelectionMode == LanguageSelectionMode.Single) + { + var optLocale = new RadioButton(); + optLocale.ID = "opt" + c.Name; + optLocale.GroupName = this.pnlControl.ID + "_Locale"; + if (c.Name == Localization.SystemLocale) + { + optLocale.Checked = true; + } + + this.pnlControl.Controls.Add(optLocale); + lblLocale.Attributes["for"] = optLocale.ClientID; + } + else + { + var chkLocale = new CheckBox(); + chkLocale.ID = "chk" + c.Name; + this.pnlControl.Controls.Add(chkLocale); + lblLocale.Attributes["for"] = chkLocale.ClientID; + } + + this.pnlControl.Controls.Add(lblLocale); + if (this.ItemStyle != LanguageItemStyle.CaptionOnly) + { + var imgLocale = new Image(); + imgLocale.ImageUrl = this.ResolveUrl("~/images/Flags/" + c.Name + ".gif"); + imgLocale.AlternateText = c.DisplayName; + imgLocale.Style["vertical-align"] = "middle"; + lblLocale.Controls.Add(imgLocale); + } + + if (this.ItemStyle != LanguageItemStyle.FlagOnly) + { + lblLocale.Controls.Add(new LiteralControl(" " + c.DisplayName)); + } + + this.pnlControl.Controls.Add(new LiteralControl("
    • ")); + } + + this.pnlControl.Controls.Add(new LiteralControl("
    ")); + + // Hide if not more than one language + if (this.GetCultures(this.SelectionObject == LanguageSelectionObject.SpecificCulture).Length < 2) + { + this.Visible = false; + } + } + + /// + /// retrieve the cultures, currently supported by the portal. + /// + /// true: locales, false: neutral languages. + /// Array of cultures. + private CultureInfo[] GetCultures(bool specific) + { + var a = new ArrayList(); + PortalSettings _Settings = PortalController.Instance.GetCurrentPortalSettings(); + foreach (string strLocale in LocaleController.Instance.GetLocales(_Settings.PortalId).Keys) + { + var c = new CultureInfo(strLocale); + if (specific) + { + a.Add(c); + } + else + { + CultureInfo p = c.Parent; + if (!a.Contains(p)) + { + a.Add(p); + } + } + } + + return (CultureInfo[])a.ToArray(typeof(CultureInfo)); + } + } } diff --git a/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs b/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs index 7120d412e75..99a5481b202 100644 --- a/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs @@ -1,44 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Web.UI; + public class LiteralTemplate : ITemplate { private readonly Control m_objControl; - private readonly string m_strHTML = ""; + private readonly string m_strHTML = string.Empty; public LiteralTemplate(string html) { - m_strHTML = html; + this.m_strHTML = html; } public LiteralTemplate(Control ctl) { - m_objControl = ctl; - } - - #region ITemplate Members - + this.m_objControl = ctl; + } + public void InstantiateIn(Control container) { - if (m_objControl == null) + if (this.m_objControl == null) { - container.Controls.Add(new LiteralControl(m_strHTML)); + container.Controls.Add(new LiteralControl(this.m_strHTML)); } else { - container.Controls.Add(m_objControl); + container.Controls.Add(this.m_objControl); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs index 90e835d277a..6b716a4271f 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs @@ -1,32 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - /// A collection of PageHierarchyData objects + using System.Collections; + using System.Web.UI; + + /// A collection of PageHierarchyData objects. public class NavDataPageHierarchicalEnumerable : ArrayList, IHierarchicalEnumerable - { - #region IHierarchicalEnumerable Members - + { /// - /// Handles enumeration + /// Handles enumeration. /// /// /// /// public virtual IHierarchyData GetHierarchyData(object enumeratedItem) { - return (IHierarchyData) enumeratedItem; - } - - #endregion + return (IHierarchyData)enumeratedItem; + } } } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs index d6cfd2e1e3a..bb381b02efa 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs @@ -1,96 +1,99 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Portals; + public class NavDataPageHierarchyData : IHierarchyData, INavigateUIData { private readonly DNNNode m_objNode; public NavDataPageHierarchyData(DNNNode obj) { - m_objNode = obj; + this.m_objNode = obj; } /// - /// Returns nodes image + /// Gets nodes image. /// - /// + /// + /// Returns nodes image + /// /// /// public virtual string ImageUrl { get { - if (String.IsNullOrEmpty(m_objNode.Image) || m_objNode.Image.StartsWith("/")) + if (string.IsNullOrEmpty(this.m_objNode.Image) || this.m_objNode.Image.StartsWith("/")) { - return m_objNode.Image; + return this.m_objNode.Image; } else { - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectory + m_objNode.Image; + return PortalController.Instance.GetCurrentPortalSettings().HomeDirectory + this.m_objNode.Image; } } - } - - #region IHierarchyData Members - + } + /// - /// Indicates whether the hierarchical data node that the IHierarchyData object represents has any child nodes. + /// Gets a value indicating whether indicates whether the hierarchical data node that the IHierarchyData object represents has any child nodes. /// - /// + /// + /// Indicates whether the hierarchical data node that the IHierarchyData object represents has any child nodes. + /// /// /// public virtual bool HasChildren { get { - return m_objNode.HasNodes; + return this.m_objNode.HasNodes; } } /// /// Gets the hierarchical path of the node. /// - /// + /// + /// The hierarchical path of the node. + /// /// /// public virtual string Path { get { - return GetValuePath(m_objNode); + return this.GetValuePath(this.m_objNode); } } /// /// Gets the hierarchical data node that the IHierarchyData object represents. /// - /// + /// + /// The hierarchical data node that the IHierarchyData object represents. + /// /// /// public virtual object Item { get { - return m_objNode; + return this.m_objNode; } } /// /// Gets the name of the type of Object contained in the Item property. /// - /// + /// + /// The name of the type of Object contained in the Item property. + /// /// /// public virtual string Type @@ -100,114 +103,117 @@ public virtual string Type return "NavDataPageHierarchyData"; } } - + /// - /// Gets an enumeration object that represents all the child nodes of the current hierarchical node. + /// Gets node name. /// + /// + /// Returns node name + /// /// /// - public virtual IHierarchicalEnumerable GetChildren() + public virtual string Name { - var objNodes = new NavDataPageHierarchicalEnumerable(); - if (m_objNode != null) + get { - foreach (DNNNode objNode in m_objNode.DNNNodes) - { - objNodes.Add(new NavDataPageHierarchyData(objNode)); - } + return this.GetSafeValue(this.m_objNode.Text, string.Empty); } - return objNodes; } /// - /// Gets an enumeration object that represents the parent node of the current hierarchical node. + /// Gets value path of node. /// + /// + /// Returns value path of node + /// /// /// - public virtual IHierarchyData GetParent() + public virtual string Value { - if (m_objNode != null) - { - return new NavDataPageHierarchyData(m_objNode.ParentNode); - } - else + get { - return null; + return this.GetValuePath(this.m_objNode); } } - #endregion - - #region INavigateUIData Members - /// - /// Returns node name + /// Gets node navigation url. /// - /// + /// + /// Returns node navigation url + /// /// /// - public virtual string Name + public virtual string NavigateUrl { get { - return GetSafeValue(m_objNode.Text, ""); + return this.GetSafeValue(this.m_objNode.NavigateURL, string.Empty); } } /// - /// Returns value path of node + /// Gets an enumeration object that represents all the child nodes of the current hierarchical node. /// - /// /// /// - public virtual string Value + public virtual IHierarchicalEnumerable GetChildren() { - get + var objNodes = new NavDataPageHierarchicalEnumerable(); + if (this.m_objNode != null) { - return GetValuePath(m_objNode); + foreach (DNNNode objNode in this.m_objNode.DNNNodes) + { + objNodes.Add(new NavDataPageHierarchyData(objNode)); + } } + + return objNodes; } /// - /// Returns node navigation url + /// Gets an enumeration object that represents the parent node of the current hierarchical node. /// - /// /// /// - public virtual string NavigateUrl + public virtual IHierarchyData GetParent() { - get + if (this.m_objNode != null) { - return GetSafeValue(m_objNode.NavigateURL, ""); + return new NavDataPageHierarchyData(this.m_objNode.ParentNode); } - } + else + { + return null; + } + } /// - /// Returns Node description + /// Gets node description. /// - /// + /// + /// Returns Node description + /// /// /// public virtual string Description { get { - return GetSafeValue(m_objNode.ToolTip, ""); + return this.GetSafeValue(this.m_objNode.ToolTip, string.Empty); } - } - - #endregion - + } + public override string ToString() { - return m_objNode.Text; + return this.m_objNode.Text; } /// - /// Helper function to handle cases where property is null (Nothing) + /// Helper function to handle cases where property is null (Nothing). /// - /// Value to evaluate for null - /// If null, return this default + /// Value to evaluate for null. + /// If null, return this default. /// /// private string GetSafeValue(string Value, string Def) @@ -223,24 +229,26 @@ private string GetSafeValue(string Value, string Def) } /// - /// Computes valuepath necessary for ASP.NET controls to guarantee uniqueness + /// Computes valuepath necessary for ASP.NET controls to guarantee uniqueness. /// /// - /// ValuePath - /// Not sure if it is ok to hardcode the "\" separator, but also not sure where I would get it from + /// ValuePath. + /// Not sure if it is ok to hardcode the "\" separator, but also not sure where I would get it from. private string GetValuePath(DNNNode objNode) { DNNNode objParent = objNode.ParentNode; - string strPath = GetSafeValue(objNode.Key, ""); + string strPath = this.GetSafeValue(objNode.Key, string.Empty); do { if (objParent == null || objParent.Level == -1) { break; } - strPath = GetSafeValue(objParent.Key, "") + "\\" + strPath; + + strPath = this.GetSafeValue(objParent.Key, string.Empty) + "\\" + strPath; objParent = objParent.ParentNode; - } while (true); + } + while (true); return strPath; } } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSource.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSource.cs index c7c308b3a4f..19782918c71 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSource.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSource.cs @@ -1,27 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Security.Permissions; -using System.Web; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Security.Permissions; + using System.Web; + using System.Web.UI; + [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)] public class NavDataSource : HierarchicalDataSourceControl { - //Return a strongly typed view for the current data source control. + // Return a strongly typed view for the current data source control. private NavDataSourceView view; protected override HierarchicalDataSourceView GetHierarchicalView(string viewPath) { - view = new NavDataSourceView(viewPath); - return view; + this.view = new NavDataSourceView(viewPath); + return this.view; } } } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs index 672aad8bbe5..370c7c78240 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - /// The NavDataSourceView class encapsulates the capabilities of the NavDataSource data source control. + using System; + using System.Web.UI; + + /// The NavDataSourceView class encapsulates the capabilities of the NavDataSource data source control. public class NavDataSourceView : HierarchicalDataSourceView { private readonly string m_sKey; @@ -19,17 +14,17 @@ public class NavDataSourceView : HierarchicalDataSourceView public NavDataSourceView(string viewPath) { - if (String.IsNullOrEmpty(viewPath)) + if (string.IsNullOrEmpty(viewPath)) { - m_sKey = ""; + this.m_sKey = string.Empty; } else if (viewPath.IndexOf("\\") > -1) { - m_sKey = viewPath.Substring(viewPath.LastIndexOf("\\") + 1); + this.m_sKey = viewPath.Substring(viewPath.LastIndexOf("\\") + 1); } else { - m_sKey = viewPath; + this.m_sKey = viewPath; } } @@ -37,11 +32,12 @@ public string Namespace { get { - return m_sNamespace; + return this.m_sNamespace; } + set { - m_sNamespace = value; + this.m_sNamespace = value; } } @@ -57,15 +53,17 @@ public override IHierarchicalEnumerable Select() { var objPages = new NavDataPageHierarchicalEnumerable(); DNNNodeCollection objNodes; - objNodes = Navigation.GetNavigationNodes(m_sNamespace); - if (!String.IsNullOrEmpty(m_sKey)) + objNodes = Navigation.GetNavigationNodes(this.m_sNamespace); + if (!string.IsNullOrEmpty(this.m_sKey)) { - objNodes = objNodes.FindNodeByKey(m_sKey).DNNNodes; + objNodes = objNodes.FindNodeByKey(this.m_sKey).DNNNodes; } + foreach (DNNNode objNode in objNodes) { objPages.Add(new NavDataPageHierarchyData(objNode)); } + return objPages; } } diff --git a/DNN Platform/Library/UI/WebControls/PagingControl.cs b/DNN Platform/Library/UI/WebControls/PagingControl.cs index 79ef2ae72a5..25a50f5e8ba 100644 --- a/DNN Platform/Library/UI/WebControls/PagingControl.cs +++ b/DNN Platform/Library/UI/WebControls/PagingControl.cs @@ -1,166 +1,224 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Data; -using System.IO; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Internal; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.ComponentModel; + using System.Data; + using System.IO; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Services.Localization; [ToolboxData("<{0}:PagingControl runat=server>")] public class PagingControl : WebControl, IPostBackEventHandler { protected Repeater PageNumbers; + protected TableCell cellDisplayLinks; + protected TableCell cellDisplayStatus; private int _totalPages = -1; private string _CSSClassLinkActive; private string _CSSClassLinkInactive; private string _CSSClassPagingStatus; private PagingControlMode _Mode = PagingControlMode.URL; - protected TableCell cellDisplayLinks; - protected TableCell cellDisplayStatus; protected Table tablePageNumbers; - [Bindable(true), Category("Behavior"), DefaultValue("")] + public event EventHandler PageChanged; + + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("")] public string CSSClassLinkActive { get { - return String.IsNullOrEmpty(_CSSClassLinkActive) ? "" : _CSSClassLinkActive; + return string.IsNullOrEmpty(this._CSSClassLinkActive) ? string.Empty : this._CSSClassLinkActive; } + set { - _CSSClassLinkActive = value; + this._CSSClassLinkActive = value; } } - [Bindable(true), Category("Behavior"), DefaultValue("")] + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("")] public string CSSClassLinkInactive { get { - return String.IsNullOrEmpty(_CSSClassLinkInactive) ? "" : _CSSClassLinkInactive; + return string.IsNullOrEmpty(this._CSSClassLinkInactive) ? string.Empty : this._CSSClassLinkInactive; } + set { - _CSSClassLinkInactive = value; + this._CSSClassLinkInactive = value; } } - [Bindable(true), Category("Behavior"), DefaultValue("")] + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("")] public string CSSClassPagingStatus { get { - return String.IsNullOrEmpty(_CSSClassPagingStatus) ? "" : _CSSClassPagingStatus; + return string.IsNullOrEmpty(this._CSSClassPagingStatus) ? string.Empty : this._CSSClassPagingStatus; } + set { - _CSSClassPagingStatus = value; + this._CSSClassPagingStatus = value; } } - [Bindable(true), Category("Behavior"), DefaultValue("1")] + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("1")] public int CurrentPage { get; set; } public PagingControlMode Mode { get { - return _Mode; + return this._Mode; } + set { - _Mode = value; + this._Mode = value; } } - [Bindable(true), Category("Behavior"), DefaultValue("10")] + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("10")] public int PageSize { get; set; } - [Bindable(true), Category("Behavior"), DefaultValue("")] + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("")] public string QuerystringParams { get; set; } - [Bindable(true), Category("Behavior"), DefaultValue("-1")] + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("-1")] public int TabID { get; set; } - [Bindable(true), Category("Behavior"), DefaultValue("0")] + [Bindable(true)] + [Category("Behavior")] + [DefaultValue("0")] public int TotalRecords { get; set; } - #region IPostBackEventHandler Members - public void RaisePostBackEvent(string eventArgument) { - CurrentPage = int.Parse(eventArgument.Replace("Page_", "")); - OnPageChanged(new EventArgs()); + this.CurrentPage = int.Parse(eventArgument.Replace("Page_", string.Empty)); + this.OnPageChanged(new EventArgs()); } - #endregion + protected override void CreateChildControls() + { + this.tablePageNumbers = new Table(); + this.cellDisplayStatus = new TableCell(); + this.cellDisplayLinks = new TableCell(); + + // cellDisplayStatus.CssClass = "Normal"; + // cellDisplayLinks.CssClass = "Normal"; + this.tablePageNumbers.CssClass = string.IsNullOrEmpty(this.CssClass) ? "PagingTable" : this.CssClass; + var intRowIndex = this.tablePageNumbers.Rows.Add(new TableRow()); + this.PageNumbers = new Repeater(); + var I = new PageNumberLinkTemplate(this); + this.PageNumbers.ItemTemplate = I; + this.BindPageNumbers(this.TotalRecords, this.PageSize); + this.cellDisplayStatus.HorizontalAlign = HorizontalAlign.Left; - public event EventHandler PageChanged; + // cellDisplayStatus.Width = new Unit("50%"); + this.cellDisplayLinks.HorizontalAlign = HorizontalAlign.Right; + + // cellDisplayLinks.Width = new Unit("50%"); + var intTotalPages = this._totalPages; + if (intTotalPages == 0) + { + intTotalPages = 1; + } + + var str = string.Format(Localization.GetString("Pages"), this.CurrentPage, intTotalPages); + var lit = new LiteralControl(str); + this.cellDisplayStatus.Controls.Add(lit); + this.tablePageNumbers.Rows[intRowIndex].Cells.Add(this.cellDisplayStatus); + this.tablePageNumbers.Rows[intRowIndex].Cells.Add(this.cellDisplayLinks); + } + + protected void OnPageChanged(EventArgs e) + { + if (this.PageChanged != null) + { + this.PageChanged(this, e); + } + } private void BindPageNumbers(int TotalRecords, int RecordsPerPage) { const int pageLinksPerPage = 10; if (TotalRecords < 1 || RecordsPerPage < 1) { - _totalPages = 1; + this._totalPages = 1; return; } - _totalPages = TotalRecords/RecordsPerPage >= 1 ? Convert.ToInt32(Math.Ceiling(Convert.ToDouble(TotalRecords)/RecordsPerPage)) : 0; - if (_totalPages > 0) + + this._totalPages = TotalRecords / RecordsPerPage >= 1 ? Convert.ToInt32(Math.Ceiling(Convert.ToDouble(TotalRecords) / RecordsPerPage)) : 0; + if (this._totalPages > 0) { var ht = new DataTable(); ht.Columns.Add("PageNum"); DataRow tmpRow; var LowNum = 1; - var HighNum = Convert.ToInt32(_totalPages); + var HighNum = Convert.ToInt32(this._totalPages); double tmpNum; - tmpNum = CurrentPage - pageLinksPerPage/2; + tmpNum = this.CurrentPage - (pageLinksPerPage / 2); if (tmpNum < 1) { tmpNum = 1; } - if (CurrentPage > (pageLinksPerPage/2)) + + if (this.CurrentPage > (pageLinksPerPage / 2)) { LowNum = Convert.ToInt32(Math.Floor(tmpNum)); } - if (Convert.ToInt32(_totalPages) <= pageLinksPerPage) + + if (Convert.ToInt32(this._totalPages) <= pageLinksPerPage) { - HighNum = Convert.ToInt32(_totalPages); + HighNum = Convert.ToInt32(this._totalPages); } else { HighNum = LowNum + pageLinksPerPage - 1; } - if (HighNum > Convert.ToInt32(_totalPages)) + + if (HighNum > Convert.ToInt32(this._totalPages)) { - HighNum = Convert.ToInt32(_totalPages); + HighNum = Convert.ToInt32(this._totalPages); if (HighNum - LowNum < pageLinksPerPage) { LowNum = HighNum - pageLinksPerPage + 1; } } - if (HighNum > Convert.ToInt32(_totalPages)) + + if (HighNum > Convert.ToInt32(this._totalPages)) { - HighNum = Convert.ToInt32(_totalPages); + HighNum = Convert.ToInt32(this._totalPages); } + if (LowNum < 1) { LowNum = 1; } + int i; for (i = LowNum; i <= HighNum; i++) { @@ -168,21 +226,22 @@ private void BindPageNumbers(int TotalRecords, int RecordsPerPage) tmpRow["PageNum"] = i; ht.Rows.Add(tmpRow); } - PageNumbers.DataSource = ht; - PageNumbers.DataBind(); + + this.PageNumbers.DataSource = ht; + this.PageNumbers.DataBind(); } } private string CreateURL(string CurrentPage) { - switch (Mode) + switch (this.Mode) { case PagingControlMode.URL: - return !String.IsNullOrEmpty(QuerystringParams) - ? (!String.IsNullOrEmpty(CurrentPage) ? TestableGlobals.Instance.NavigateURL(TabID, "", QuerystringParams, "currentpage=" + CurrentPage) : TestableGlobals.Instance.NavigateURL(TabID, "", QuerystringParams)) - : (!String.IsNullOrEmpty(CurrentPage) ? TestableGlobals.Instance.NavigateURL(TabID, "", "currentpage=" + CurrentPage) : TestableGlobals.Instance.NavigateURL(TabID)); + return !string.IsNullOrEmpty(this.QuerystringParams) + ? (!string.IsNullOrEmpty(CurrentPage) ? TestableGlobals.Instance.NavigateURL(this.TabID, string.Empty, this.QuerystringParams, "currentpage=" + CurrentPage) : TestableGlobals.Instance.NavigateURL(this.TabID, string.Empty, this.QuerystringParams)) + : (!string.IsNullOrEmpty(CurrentPage) ? TestableGlobals.Instance.NavigateURL(this.TabID, string.Empty, "currentpage=" + CurrentPage) : TestableGlobals.Instance.NavigateURL(this.TabID)); default: - return Page.ClientScript.GetPostBackClientHyperlink(this, "Page_" + CurrentPage, false); + return this.Page.ClientScript.GetPostBackClientHyperlink(this, "Page_" + CurrentPage, false); } } @@ -193,13 +252,14 @@ private string CreateURL(string CurrentPage) /// private string GetLink(int PageNum) { - if (PageNum == CurrentPage) + if (PageNum == this.CurrentPage) { - return CSSClassLinkInactive.Trim().Length > 0 ? "[" + PageNum + "]" : "[" + PageNum + "]"; + return this.CSSClassLinkInactive.Trim().Length > 0 ? "[" + PageNum + "]" : "[" + PageNum + "]"; } - return CSSClassLinkActive.Trim().Length > 0 - ? "" + PageNum + "" - : "" + PageNum + ""; + + return this.CSSClassLinkActive.Trim().Length > 0 + ? "" + PageNum + "" + : "" + PageNum + ""; } /// @@ -209,13 +269,13 @@ private string GetLink(int PageNum) /// private string GetPreviousLink() { - return CurrentPage > 1 && _totalPages > 0 - ? (CSSClassLinkActive.Trim().Length > 0 - ? "" + + return this.CurrentPage > 1 && this._totalPages > 0 + ? (this.CSSClassLinkActive.Trim().Length > 0 + ? "" + Localization.GetString("Previous", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Previous", Localization.SharedResourceFile) + "") - : (CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("Previous", Localization.SharedResourceFile) + "" + : "" + Localization.GetString("Previous", Localization.SharedResourceFile) + "") + : (this.CSSClassLinkInactive.Trim().Length > 0 + ? "" + Localization.GetString("Previous", Localization.SharedResourceFile) + "" : "" + Localization.GetString("Previous", Localization.SharedResourceFile) + ""); } @@ -226,13 +286,13 @@ private string GetPreviousLink() /// private string GetNextLink() { - return CurrentPage != _totalPages && _totalPages > 0 - ? (CSSClassLinkActive.Trim().Length > 0 - ? "" + Localization.GetString("Next", Localization.SharedResourceFile) + + return this.CurrentPage != this._totalPages && this._totalPages > 0 + ? (this.CSSClassLinkActive.Trim().Length > 0 + ? "" + Localization.GetString("Next", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Next", Localization.SharedResourceFile) + "") - : (CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("Next", Localization.SharedResourceFile) + "" + : "" + Localization.GetString("Next", Localization.SharedResourceFile) + "") + : (this.CSSClassLinkInactive.Trim().Length > 0 + ? "" + Localization.GetString("Next", Localization.SharedResourceFile) + "" : "" + Localization.GetString("Next", Localization.SharedResourceFile) + ""); } @@ -243,14 +303,15 @@ private string GetNextLink() /// private string GetFirstLink() { - if (CurrentPage > 1 && _totalPages > 0) + if (this.CurrentPage > 1 && this._totalPages > 0) { - return CSSClassLinkActive.Trim().Length > 0 - ? "" + Localization.GetString("First", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("First", Localization.SharedResourceFile) + ""; + return this.CSSClassLinkActive.Trim().Length > 0 + ? "" + Localization.GetString("First", Localization.SharedResourceFile) + "" + : "" + Localization.GetString("First", Localization.SharedResourceFile) + ""; } - return CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("First", Localization.SharedResourceFile) + "" + + return this.CSSClassLinkInactive.Trim().Length > 0 + ? "" + Localization.GetString("First", Localization.SharedResourceFile) + "" : "" + Localization.GetString("First", Localization.SharedResourceFile) + ""; } @@ -261,104 +322,61 @@ private string GetFirstLink() /// private string GetLastLink() { - if (CurrentPage != _totalPages && _totalPages > 0) + if (this.CurrentPage != this._totalPages && this._totalPages > 0) { - return CSSClassLinkActive.Trim().Length > 0 - ? "" + Localization.GetString("Last", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; + return this.CSSClassLinkActive.Trim().Length > 0 + ? "" + Localization.GetString("Last", Localization.SharedResourceFile) + "" + : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; } - return CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("Last", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; - } - protected override void CreateChildControls() - { - tablePageNumbers = new Table(); - cellDisplayStatus = new TableCell(); - cellDisplayLinks = new TableCell(); - //cellDisplayStatus.CssClass = "Normal"; - //cellDisplayLinks.CssClass = "Normal"; - tablePageNumbers.CssClass = String.IsNullOrEmpty(CssClass) ? "PagingTable" : CssClass; - var intRowIndex = tablePageNumbers.Rows.Add(new TableRow()); - PageNumbers = new Repeater(); - var I = new PageNumberLinkTemplate(this); - PageNumbers.ItemTemplate = I; - BindPageNumbers(TotalRecords, PageSize); - cellDisplayStatus.HorizontalAlign = HorizontalAlign.Left; - //cellDisplayStatus.Width = new Unit("50%"); - cellDisplayLinks.HorizontalAlign = HorizontalAlign.Right; - //cellDisplayLinks.Width = new Unit("50%"); - var intTotalPages = _totalPages; - if (intTotalPages == 0) - { - intTotalPages = 1; - } - var str = string.Format(Localization.GetString("Pages"), CurrentPage, intTotalPages); - var lit = new LiteralControl(str); - cellDisplayStatus.Controls.Add(lit); - tablePageNumbers.Rows[intRowIndex].Cells.Add(cellDisplayStatus); - tablePageNumbers.Rows[intRowIndex].Cells.Add(cellDisplayLinks); - } - - protected void OnPageChanged(EventArgs e) - { - if (PageChanged != null) - { - PageChanged(this, e); - } + return this.CSSClassLinkInactive.Trim().Length > 0 + ? "" + Localization.GetString("Last", Localization.SharedResourceFile) + "" + : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; } protected override void Render(HtmlTextWriter output) { - if (PageNumbers == null) + if (this.PageNumbers == null) { - CreateChildControls(); + this.CreateChildControls(); } + var str = new StringBuilder(); - str.Append(GetFirstLink() + "   "); - str.Append(GetPreviousLink() + "   "); + str.Append(this.GetFirstLink() + "   "); + str.Append(this.GetPreviousLink() + "   "); var result = new StringBuilder(1024); - PageNumbers.RenderControl(new HtmlTextWriter(new StringWriter(result))); + this.PageNumbers.RenderControl(new HtmlTextWriter(new StringWriter(result))); str.Append(result.ToString()); - str.Append(GetNextLink() + "   "); - str.Append(GetLastLink() + "   "); - cellDisplayLinks.Controls.Add(new LiteralControl(str.ToString())); - tablePageNumbers.RenderControl(output); + str.Append(this.GetNextLink() + "   "); + str.Append(this.GetLastLink() + "   "); + this.cellDisplayLinks.Controls.Add(new LiteralControl(str.ToString())); + this.tablePageNumbers.RenderControl(output); } - #region Nested type: PageNumberLinkTemplate - public class PageNumberLinkTemplate : ITemplate { private readonly PagingControl _PagingControl; public PageNumberLinkTemplate(PagingControl ctlPagingControl) { - _PagingControl = ctlPagingControl; + this._PagingControl = ctlPagingControl; } - #region ITemplate Members - void ITemplate.InstantiateIn(Control container) { var l = new Literal(); - l.DataBinding += BindData; + l.DataBinding += this.BindData; container.Controls.Add(l); } - #endregion - private void BindData(object sender, EventArgs e) { Literal lc; - lc = (Literal) sender; + lc = (Literal)sender; RepeaterItem container; - container = (RepeaterItem) lc.NamingContainer; - lc.Text = _PagingControl.GetLink(Convert.ToInt32(DataBinder.Eval(container.DataItem, "PageNum"))) + "  "; + container = (RepeaterItem)lc.NamingContainer; + lc.Text = this._PagingControl.GetLink(Convert.ToInt32(DataBinder.Eval(container.DataItem, "PageNum"))) + "  "; } } - - #endregion } } diff --git a/DNN Platform/Library/UI/WebControls/PagingControlMode.cs b/DNN Platform/Library/UI/WebControls/PagingControlMode.cs index 7500317b613..bfc0e74b4ed 100644 --- a/DNN Platform/Library/UI/WebControls/PagingControlMode.cs +++ b/DNN Platform/Library/UI/WebControls/PagingControlMode.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- @@ -11,7 +11,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The PagingControlMode Enum provides an enumeration of the modes of the Paging - /// Control + /// Control. /// /// /// @@ -19,6 +19,6 @@ namespace DotNetNuke.UI.WebControls public enum PagingControlMode { PostBack, - URL + URL, } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs index a8493948bab..f951cd7e603 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Reflection; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.Reflection; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: CollectionEditorInfoFactory /// ----------------------------------------------------------------------------- /// - /// The CollectionEditorInfoAdapter control provides an Adapter for Collection Onjects + /// The CollectionEditorInfoAdapter control provides an Adapter for Collection Onjects. /// /// /// @@ -36,227 +31,229 @@ public class CollectionEditorInfoAdapter : IEditorInfoAdapter public CollectionEditorInfoAdapter(object dataSource, string name, string fieldName, Hashtable fieldNames) { - DataSource = dataSource; - FieldNames = fieldNames; - Name = name; - } - - #region IEditorInfoAdapter Members - + this.DataSource = dataSource; + this.FieldNames = fieldNames; + this.Name = name; + } + public EditorInfo CreateEditControl() { - return GetEditorInfo(); + return this.GetEditorInfo(); } public bool UpdateValue(PropertyEditorEventArgs e) { - string NameDataField = Convert.ToString(FieldNames["Name"]); - string ValueDataField = Convert.ToString(FieldNames["Value"]); + string NameDataField = Convert.ToString(this.FieldNames["Name"]); + string ValueDataField = Convert.ToString(this.FieldNames["Value"]); PropertyInfo objProperty; - string PropertyName = ""; + string PropertyName = string.Empty; bool changed = e.Changed; string name = e.Name; object oldValue = e.OldValue; object newValue = e.Value; object stringValue = e.StringValue; bool _IsDirty = Null.NullBoolean; - - //Get the Name Property - objProperty = DataSource.GetType().GetProperty(NameDataField); + + // Get the Name Property + objProperty = this.DataSource.GetType().GetProperty(NameDataField); if (objProperty != null) { - PropertyName = Convert.ToString(objProperty.GetValue(DataSource, null)); - //Do we have the item in the IEnumerable Collection being changed + PropertyName = Convert.ToString(objProperty.GetValue(this.DataSource, null)); + + // Do we have the item in the IEnumerable Collection being changed PropertyName = PropertyName.Replace(" ", "_"); if (PropertyName == name) { - //Get the Value Property - objProperty = DataSource.GetType().GetProperty(ValueDataField); - - //Set the Value property to the new value - if ((!(ReferenceEquals(newValue, oldValue))) || changed) + // Get the Value Property + objProperty = this.DataSource.GetType().GetProperty(ValueDataField); + + // Set the Value property to the new value + if ((!ReferenceEquals(newValue, oldValue)) || changed) { if (objProperty.PropertyType.FullName == "System.String") { - objProperty.SetValue(DataSource, stringValue, null); + objProperty.SetValue(this.DataSource, stringValue, null); } else { - objProperty.SetValue(DataSource, newValue, null); + objProperty.SetValue(this.DataSource, newValue, null); } + _IsDirty = true; } } } + return _IsDirty; } public bool UpdateVisibility(PropertyEditorEventArgs e) { - string nameDataField = Convert.ToString(FieldNames["Name"]); - string dataField = Convert.ToString(FieldNames["ProfileVisibility"]); + string nameDataField = Convert.ToString(this.FieldNames["Name"]); + string dataField = Convert.ToString(this.FieldNames["ProfileVisibility"]); string name = e.Name; object newValue = e.Value; bool dirty = Null.NullBoolean; - - //Get the Name Property - PropertyInfo property = DataSource.GetType().GetProperty(nameDataField); + + // Get the Name Property + PropertyInfo property = this.DataSource.GetType().GetProperty(nameDataField); if (property != null) { - string propertyName = Convert.ToString(property.GetValue(DataSource, null)); - //Do we have the item in the IEnumerable Collection being changed + string propertyName = Convert.ToString(property.GetValue(this.DataSource, null)); + + // Do we have the item in the IEnumerable Collection being changed propertyName = propertyName.Replace(" ", "_"); if (propertyName == name) { - //Get the Value Property - property = DataSource.GetType().GetProperty(dataField); - //Set the Value property to the new value - property.SetValue(DataSource, newValue, null); + // Get the Value Property + property = this.DataSource.GetType().GetProperty(dataField); + + // Set the Value property to the new value + property.SetValue(this.DataSource, newValue, null); dirty = true; } } + return dirty; - } - - #endregion - + } + /// ----------------------------------------------------------------------------- /// - /// GetEditorInfo builds an EditorInfo object for a propoerty + /// GetEditorInfo builds an EditorInfo object for a propoerty. /// /// ----------------------------------------------------------------------------- private EditorInfo GetEditorInfo() { - string CategoryDataField = Convert.ToString(FieldNames["Category"]); - string EditorDataField = Convert.ToString(FieldNames["Editor"]); - string NameDataField = Convert.ToString(FieldNames["Name"]); - string RequiredDataField = Convert.ToString(FieldNames["Required"]); - string TypeDataField = Convert.ToString(FieldNames["Type"]); - string ValidationExpressionDataField = Convert.ToString(FieldNames["ValidationExpression"]); - string ValueDataField = Convert.ToString(FieldNames["Value"]); - string VisibilityDataField = Convert.ToString(FieldNames["ProfileVisibility"]); - string MaxLengthDataField = Convert.ToString(FieldNames["Length"]); + string CategoryDataField = Convert.ToString(this.FieldNames["Category"]); + string EditorDataField = Convert.ToString(this.FieldNames["Editor"]); + string NameDataField = Convert.ToString(this.FieldNames["Name"]); + string RequiredDataField = Convert.ToString(this.FieldNames["Required"]); + string TypeDataField = Convert.ToString(this.FieldNames["Type"]); + string ValidationExpressionDataField = Convert.ToString(this.FieldNames["ValidationExpression"]); + string ValueDataField = Convert.ToString(this.FieldNames["Value"]); + string VisibilityDataField = Convert.ToString(this.FieldNames["ProfileVisibility"]); + string MaxLengthDataField = Convert.ToString(this.FieldNames["Length"]); var editInfo = new EditorInfo(); PropertyInfo property; - //Get the Name of the property + // Get the Name of the property editInfo.Name = string.Empty; - if (!String.IsNullOrEmpty(NameDataField)) + if (!string.IsNullOrEmpty(NameDataField)) { - property = DataSource.GetType().GetProperty(NameDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(NameDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - editInfo.Name = Convert.ToString(property.GetValue(DataSource, null)); + editInfo.Name = Convert.ToString(property.GetValue(this.DataSource, null)); } } - - //Get the Category of the property + + // Get the Category of the property editInfo.Category = string.Empty; - - //Get Category Field - if (!String.IsNullOrEmpty(CategoryDataField)) + + // Get Category Field + if (!string.IsNullOrEmpty(CategoryDataField)) { - property = DataSource.GetType().GetProperty(CategoryDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(CategoryDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - editInfo.Category = Convert.ToString(property.GetValue(DataSource, null)); + editInfo.Category = Convert.ToString(property.GetValue(this.DataSource, null)); } } - - //Get Value Field - editInfo.Value = string.Empty; - if (!String.IsNullOrEmpty(ValueDataField)) + + // Get Value Field + editInfo.Value = string.Empty; + if (!string.IsNullOrEmpty(ValueDataField)) { - property = DataSource.GetType().GetProperty(ValueDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(ValueDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - editInfo.Value = Convert.ToString(property.GetValue(DataSource, null)); + editInfo.Value = Convert.ToString(property.GetValue(this.DataSource, null)); } } - - //Get the type of the property - editInfo.Type = "System.String"; - if (!String.IsNullOrEmpty(TypeDataField)) + + // Get the type of the property + editInfo.Type = "System.String"; + if (!string.IsNullOrEmpty(TypeDataField)) { - property = DataSource.GetType().GetProperty(TypeDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(TypeDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - editInfo.Type = Convert.ToString(property.GetValue(DataSource, null)); + editInfo.Type = Convert.ToString(property.GetValue(this.DataSource, null)); } } - - //Get Editor Field - editInfo.Editor = "DotNetNuke.UI.WebControls.TextEditControl, DotNetNuke"; - if (!String.IsNullOrEmpty(EditorDataField)) + + // Get Editor Field + editInfo.Editor = "DotNetNuke.UI.WebControls.TextEditControl, DotNetNuke"; + if (!string.IsNullOrEmpty(EditorDataField)) { - property = DataSource.GetType().GetProperty(EditorDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(EditorDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - editInfo.Editor = EditorInfo.GetEditor(Convert.ToInt32(property.GetValue(DataSource, null))); + editInfo.Editor = EditorInfo.GetEditor(Convert.ToInt32(property.GetValue(this.DataSource, null))); } } - - //Get LabelMode Field + + // Get LabelMode Field editInfo.LabelMode = LabelMode.Left; - //Get Required Field + // Get Required Field editInfo.Required = false; - if (!String.IsNullOrEmpty(RequiredDataField)) + if (!string.IsNullOrEmpty(RequiredDataField)) { - property = DataSource.GetType().GetProperty(RequiredDataField); - if (!((property == null) || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(RequiredDataField); + if (!((property == null) || (property.GetValue(this.DataSource, null) == null))) { - editInfo.Required = Convert.ToBoolean(property.GetValue(DataSource, null)); + editInfo.Required = Convert.ToBoolean(property.GetValue(this.DataSource, null)); } } - - //Set ResourceKey Field + + // Set ResourceKey Field editInfo.ResourceKey = editInfo.Name; - editInfo.ResourceKey = string.Format("{0}_{1}", Name, editInfo.Name); + editInfo.ResourceKey = string.Format("{0}_{1}", this.Name, editInfo.Name); - //Set Style + // Set Style editInfo.ControlStyle = new Style(); - //Get Visibility Field - editInfo.ProfileVisibility = new ProfileVisibility - { - VisibilityMode = UserVisibilityMode.AllUsers - }; - if (!String.IsNullOrEmpty(VisibilityDataField)) + // Get Visibility Field + editInfo.ProfileVisibility = new ProfileVisibility + { + VisibilityMode = UserVisibilityMode.AllUsers, + }; + if (!string.IsNullOrEmpty(VisibilityDataField)) { - property = DataSource.GetType().GetProperty(VisibilityDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(VisibilityDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - editInfo.ProfileVisibility = (ProfileVisibility)property.GetValue(DataSource, null); + editInfo.ProfileVisibility = (ProfileVisibility)property.GetValue(this.DataSource, null); } } - - //Get Validation Expression Field + + // Get Validation Expression Field editInfo.ValidationExpression = string.Empty; - if (!String.IsNullOrEmpty(ValidationExpressionDataField)) + if (!string.IsNullOrEmpty(ValidationExpressionDataField)) { - property = DataSource.GetType().GetProperty(ValidationExpressionDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(ValidationExpressionDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - editInfo.ValidationExpression = Convert.ToString(property.GetValue(DataSource, null)); + editInfo.ValidationExpression = Convert.ToString(property.GetValue(this.DataSource, null)); } } - - //Get Length Field - if (!String.IsNullOrEmpty(MaxLengthDataField)) + + // Get Length Field + if (!string.IsNullOrEmpty(MaxLengthDataField)) { - property = DataSource.GetType().GetProperty(MaxLengthDataField); - if (!(property == null || (property.GetValue(DataSource, null) == null))) + property = this.DataSource.GetType().GetProperty(MaxLengthDataField); + if (!(property == null || (property.GetValue(this.DataSource, null) == null))) { - int length = Convert.ToInt32(property.GetValue(DataSource, null)); + int length = Convert.ToInt32(property.GetValue(this.DataSource, null)); var attributes = new object[1]; attributes[0] = new MaxLengthAttribute(length); editInfo.Attributes = attributes; } } - - //Remove spaces from name + + // Remove spaces from name editInfo.Name = editInfo.Name.Replace(" ", "_"); return editInfo; } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/IEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/IEditorInfoAdapter.cs index 643ad6579f2..b6daf303322 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/IEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/IEditorInfoAdapter.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- @@ -10,7 +10,7 @@ namespace DotNetNuke.UI.WebControls /// Class: IEditorInfoAdapter /// ----------------------------------------------------------------------------- /// - /// The IEditorInfoAdapter control provides an Adapter Interface for datasources + /// The IEditorInfoAdapter control provides an Adapter Interface for datasources. /// /// /// diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs index e1c7aa83c19..0f8aefe6fd4 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -21,7 +16,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The SettingsEditorInfoAdapter control provides a factory for creating the - /// appropriate EditInfo object + /// appropriate EditInfo object. /// /// /// @@ -34,46 +29,43 @@ public class SettingsEditorInfoAdapter : IEditorInfoAdapter public SettingsEditorInfoAdapter(object dataSource, object dataMember, string fieldName) { - DataMember = dataMember; - DataSource = dataSource; - FieldName = fieldName; - } - - #region IEditorInfoAdapter Members - + this.DataMember = dataMember; + this.DataSource = dataSource; + this.FieldName = fieldName; + } + public EditorInfo CreateEditControl() { - - var info = (SettingInfo) DataMember; + var info = (SettingInfo)this.DataMember; var editInfo = new EditorInfo(); - //Get the Name of the property + // Get the Name of the property editInfo.Name = info.Name; - editInfo.Category = string.Empty; + editInfo.Category = string.Empty; - //Get Value Field + // Get Value Field editInfo.Value = info.Value; - //Get the type of the property + // Get the type of the property editInfo.Type = info.Type.AssemblyQualifiedName; - //Get Editor Field + // Get Editor Field editInfo.Editor = info.Editor; - //Get LabelMode Field + // Get LabelMode Field editInfo.LabelMode = LabelMode.Left; - //Get Required Field + // Get Required Field editInfo.Required = false; - //Set ResourceKey Field + // Set ResourceKey Field editInfo.ResourceKey = editInfo.Name; - //Get Style + // Get Style editInfo.ControlStyle = new Style(); - //Get Validation Expression Field + // Get Validation Expression Field editInfo.ValidationExpression = string.Empty; return editInfo; @@ -89,16 +81,17 @@ public bool UpdateValue(PropertyEditorEventArgs e) object stringValue = e.StringValue; bool _IsDirty = Null.NullBoolean; - var settings = (Hashtable) DataSource; + var settings = (Hashtable)this.DataSource; IDictionaryEnumerator settingsEnumerator = settings.GetEnumerator(); while (settingsEnumerator.MoveNext()) { key = Convert.ToString(settingsEnumerator.Key); - //Do we have the item in the Hashtable being changed + + // Do we have the item in the Hashtable being changed if (key == name) { - //Set the Value property to the new value - if ((!(ReferenceEquals(newValue, oldValue))) || changed) + // Set the Value property to the new value + if ((!ReferenceEquals(newValue, oldValue)) || changed) { settings[key] = newValue; _IsDirty = true; @@ -106,14 +99,13 @@ public bool UpdateValue(PropertyEditorEventArgs e) } } } + return _IsDirty; } public bool UpdateVisibility(PropertyEditorEventArgs e) { return false; - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs index 24b9a133831..4c710d3c0ab 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.ComponentModel; -using System.Reflection; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.ComponentModel; + using System.Reflection; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: StandardEditorInfoAdapter /// ----------------------------------------------------------------------------- /// - /// The StandardEditorInfoAdapter control provides an Adapter for standard datasources + /// The StandardEditorInfoAdapter control provides an Adapter for standard datasources. /// /// /// @@ -34,20 +29,19 @@ public class StandardEditorInfoAdapter : IEditorInfoAdapter public StandardEditorInfoAdapter(object dataSource, string fieldName) { - DataSource = dataSource; - FieldName = fieldName; - } - - #region IEditorInfoAdapter Members - + this.DataSource = dataSource; + this.FieldName = fieldName; + } + public EditorInfo CreateEditControl() { EditorInfo editInfo = null; - PropertyInfo objProperty = GetProperty(DataSource, FieldName); + PropertyInfo objProperty = this.GetProperty(this.DataSource, this.FieldName); if (objProperty != null) { - editInfo = GetEditorInfo(DataSource, objProperty); + editInfo = this.GetEditorInfo(this.DataSource, objProperty); } + return editInfo; } @@ -57,154 +51,153 @@ public bool UpdateValue(PropertyEditorEventArgs e) object oldValue = e.OldValue; object newValue = e.Value; bool _IsDirty = Null.NullBoolean; - if (DataSource != null) + if (this.DataSource != null) { - PropertyInfo objProperty = DataSource.GetType().GetProperty(e.Name); + PropertyInfo objProperty = this.DataSource.GetType().GetProperty(e.Name); if (objProperty != null) { - if ((!(ReferenceEquals(newValue, oldValue))) || changed) + if ((!ReferenceEquals(newValue, oldValue)) || changed) { - objProperty.SetValue(DataSource, newValue, null); + objProperty.SetValue(this.DataSource, newValue, null); _IsDirty = true; } } } + return _IsDirty; } public bool UpdateVisibility(PropertyEditorEventArgs e) { return false; - } - - #endregion - + } + /// ----------------------------------------------------------------------------- /// - /// GetEditorInfo builds an EditorInfo object for a propoerty + /// GetEditorInfo builds an EditorInfo object for a propoerty. /// /// ----------------------------------------------------------------------------- private EditorInfo GetEditorInfo(object dataSource, PropertyInfo objProperty) { var editInfo = new EditorInfo(); - //Get the Name of the property + // Get the Name of the property editInfo.Name = objProperty.Name; - //Get the value of the property + // Get the value of the property editInfo.Value = objProperty.GetValue(dataSource, null); - //Get the type of the property + // Get the type of the property editInfo.Type = objProperty.PropertyType.AssemblyQualifiedName; - //Get the Custom Attributes for the property + // Get the Custom Attributes for the property editInfo.Attributes = objProperty.GetCustomAttributes(true); - //Get Category Field + // Get Category Field editInfo.Category = string.Empty; - object[] categoryAttributes = objProperty.GetCustomAttributes(typeof (CategoryAttribute), true); + object[] categoryAttributes = objProperty.GetCustomAttributes(typeof(CategoryAttribute), true); if (categoryAttributes.Length > 0) { - var category = (CategoryAttribute) categoryAttributes[0]; + var category = (CategoryAttribute)categoryAttributes[0]; editInfo.Category = category.Category; } - - //Get EditMode Field + // Get EditMode Field if (!objProperty.CanWrite) { editInfo.EditMode = PropertyEditorMode.View; } else { - object[] readOnlyAttributes = objProperty.GetCustomAttributes(typeof (IsReadOnlyAttribute), true); + object[] readOnlyAttributes = objProperty.GetCustomAttributes(typeof(IsReadOnlyAttribute), true); if (readOnlyAttributes.Length > 0) { - var readOnlyMode = (IsReadOnlyAttribute) readOnlyAttributes[0]; + var readOnlyMode = (IsReadOnlyAttribute)readOnlyAttributes[0]; if (readOnlyMode.IsReadOnly) { editInfo.EditMode = PropertyEditorMode.View; } } } - - //Get Editor Field + + // Get Editor Field editInfo.Editor = "UseSystemType"; - object[] editorAttributes = objProperty.GetCustomAttributes(typeof (EditorAttribute), true); + object[] editorAttributes = objProperty.GetCustomAttributes(typeof(EditorAttribute), true); if (editorAttributes.Length > 0) { EditorAttribute editor = null; for (int i = 0; i <= editorAttributes.Length - 1; i++) { - if (((EditorAttribute) editorAttributes[i]).EditorBaseTypeName.IndexOf("DotNetNuke.UI.WebControls.EditControl") >= 0) + if (((EditorAttribute)editorAttributes[i]).EditorBaseTypeName.IndexOf("DotNetNuke.UI.WebControls.EditControl") >= 0) { - editor = (EditorAttribute) editorAttributes[i]; + editor = (EditorAttribute)editorAttributes[i]; break; } } + if (editor != null) { editInfo.Editor = editor.EditorTypeName; } } - - //Get Required Field + + // Get Required Field editInfo.Required = false; - object[] requiredAttributes = objProperty.GetCustomAttributes(typeof (RequiredAttribute), true); + object[] requiredAttributes = objProperty.GetCustomAttributes(typeof(RequiredAttribute), true); if (requiredAttributes.Length > 0) { - //The property may contain multiple edit mode types, so make sure we only use DotNetNuke editors. - var required = (RequiredAttribute) requiredAttributes[0]; + // The property may contain multiple edit mode types, so make sure we only use DotNetNuke editors. + var required = (RequiredAttribute)requiredAttributes[0]; if (required.Required) { editInfo.Required = true; } } - - //Get Css Style + + // Get Css Style editInfo.ControlStyle = new Style(); - object[] StyleAttributes = objProperty.GetCustomAttributes(typeof (ControlStyleAttribute), true); + object[] StyleAttributes = objProperty.GetCustomAttributes(typeof(ControlStyleAttribute), true); if (StyleAttributes.Length > 0) { - var attribute = (ControlStyleAttribute) StyleAttributes[0]; + var attribute = (ControlStyleAttribute)StyleAttributes[0]; editInfo.ControlStyle.CssClass = attribute.CssClass; editInfo.ControlStyle.Height = attribute.Height; editInfo.ControlStyle.Width = attribute.Width; } - - //Get LabelMode Field + + // Get LabelMode Field editInfo.LabelMode = LabelMode.Left; - object[] labelModeAttributes = objProperty.GetCustomAttributes(typeof (LabelModeAttribute), true); + object[] labelModeAttributes = objProperty.GetCustomAttributes(typeof(LabelModeAttribute), true); if (labelModeAttributes.Length > 0) { - var mode = (LabelModeAttribute) labelModeAttributes[0]; + var mode = (LabelModeAttribute)labelModeAttributes[0]; editInfo.LabelMode = mode.Mode; } - - //Set ResourceKey Field + + // Set ResourceKey Field editInfo.ResourceKey = string.Format("{0}_{1}", dataSource.GetType().Name, objProperty.Name); - //Get Validation Expression Field + // Get Validation Expression Field editInfo.ValidationExpression = string.Empty; - object[] regExAttributes = objProperty.GetCustomAttributes(typeof (RegularExpressionValidatorAttribute), true); + object[] regExAttributes = objProperty.GetCustomAttributes(typeof(RegularExpressionValidatorAttribute), true); if (regExAttributes.Length > 0) { - var regExAttribute = (RegularExpressionValidatorAttribute) regExAttributes[0]; + var regExAttribute = (RegularExpressionValidatorAttribute)regExAttributes[0]; editInfo.ValidationExpression = regExAttribute.Expression; } - - //Set Visibility - editInfo.ProfileVisibility = new ProfileVisibility - { - VisibilityMode = UserVisibilityMode.AllUsers - }; + + // Set Visibility + editInfo.ProfileVisibility = new ProfileVisibility + { + VisibilityMode = UserVisibilityMode.AllUsers, + }; return editInfo; } /// ----------------------------------------------------------------------------- /// - /// GetProperty returns the property that is being "bound" to + /// GetProperty returns the property that is being "bound" to. /// /// ----------------------------------------------------------------------------- private PropertyInfo GetProperty(object dataSource, string fieldName) diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs index 23292371340..633d165788d 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.ComponentModel; -using System.Reflection; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.ComponentModel; + using System.Reflection; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -32,183 +27,202 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:CollectionEditorControl runat=server>")] public class CollectionEditorControl : PropertyEditorControl - { - #region Protected Members - + { /// ----------------------------------------------------------------------------- /// - /// Gets the Underlying DataSource + /// Gets or sets and sets the value of the Category. /// - /// An IEnumerable + /// A string representing the Category of the Field. /// ----------------------------------------------------------------------------- - protected override IEnumerable UnderlyingDataSource - { - get - { - return (IEnumerable)DataSource; - } - } - - #endregion - - #region Public Properties + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the Category.")] + public string CategoryDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Category + /// Gets or sets and sets the value of the Editor Type to use. /// - /// A string representing the Category of the Field + /// A string representing the Editor Type of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the Category.")] - public string CategoryDataField { get; set; } - + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the Editor Type.")] + public string EditorDataField { get; set; } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Editor Type to use + /// Gets the Underlying DataSource. /// - /// A string representing the Editor Type of the Field + /// An IEnumerable. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the Editor Type.")] - public string EditorDataField { get; set; } + protected override IEnumerable UnderlyingDataSource + { + get + { + return (IEnumerable)this.DataSource; + } + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that determines the length + /// Gets or sets and sets the value of the Field that determines the length. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that determines the length.")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that determines the length.")] public string LengthDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that is bound to the Label + /// Gets or sets and sets the value of the Field that is bound to the Label. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the Label's Text property.")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the Label's Text property.")] public string NameDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that determines whether an item is required + /// Gets or sets and sets the value of the Field that determines whether an item is required. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that determines whether an item is required.")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that determines whether an item is required.")] public string RequiredDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that is bound to the EditControl + /// Gets or sets and sets the value of the Field that is bound to the EditControl. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the EditControl's Type.")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the EditControl's Type.")] public string TypeDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that is bound to the EditControl's - /// Expression DynamicContentValidator + /// Gets or sets and sets the value of the Field that is bound to the EditControl's + /// Expression DynamicContentValidator. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the EditControl's Expression DynamicContentValidator.")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the EditControl's Expression DynamicContentValidator.")] public string ValidationExpressionDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that is bound to the EditControl + /// Gets or sets and sets the value of the Field that is bound to the EditControl. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the EditControl's Value property.")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the EditControl's Value property.")] public string ValueDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that determines whether the control is visible + /// Gets or sets and sets the value of the Field that determines whether the control is visible. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that determines whether the item is visble.")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that determines whether the item is visble.")] public string VisibleDataField { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the value of the Field that determines the visibility + /// Gets or sets and sets the value of the Field that determines the visibility. /// - /// A string representing the Name of the Field + /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that determines the visibility.")] - public string VisibilityDataField { get; set; } - - #endregion - - #region Private Methods - - private Hashtable GetFieldNames() - { - var fields = new Hashtable(); - fields.Add("Category", CategoryDataField); - fields.Add("Editor", EditorDataField); - fields.Add("Name", NameDataField); - fields.Add("Required", RequiredDataField); - fields.Add("Type", TypeDataField); - fields.Add("ValidationExpression", ValidationExpressionDataField); - fields.Add("Value", ValueDataField); - fields.Add("ProfileVisibility", VisibilityDataField); - fields.Add("Length", LengthDataField); - - return fields; - } - - #endregion - - #region Protected Methods - + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that determines the visibility.")] + public string VisibilityDataField { get; set; } + protected override void AddEditorRow(Table table, object obj) { - AddEditorRow(table, NameDataField, new CollectionEditorInfoAdapter(obj, ID, NameDataField, GetFieldNames())); + this.AddEditorRow(table, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); } protected override void AddEditorRow(Panel container, object obj) { - AddEditorRow(container, NameDataField, new CollectionEditorInfoAdapter(obj, ID, NameDataField, GetFieldNames())); + this.AddEditorRow(container, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); } + + private Hashtable GetFieldNames() + { + var fields = new Hashtable(); + fields.Add("Category", this.CategoryDataField); + fields.Add("Editor", this.EditorDataField); + fields.Add("Name", this.NameDataField); + fields.Add("Required", this.RequiredDataField); + fields.Add("Type", this.TypeDataField); + fields.Add("ValidationExpression", this.ValidationExpressionDataField); + fields.Add("Value", this.ValueDataField); + fields.Add("ProfileVisibility", this.VisibilityDataField); + fields.Add("Length", this.LengthDataField); + + return fields; + } protected override void AddEditorRow(object obj) { - AddEditorRow(this, NameDataField, new CollectionEditorInfoAdapter(obj, ID, NameDataField, GetFieldNames())); + this.AddEditorRow(this, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); } /// ----------------------------------------------------------------------------- /// - /// GetCategory gets the Category of an object - /// + /// GetCategory gets the Category of an object. + /// + /// /// ----------------------------------------------------------------------------- protected override string GetCategory(object obj) { PropertyInfo objProperty; string _Category = Null.NullString; - - //Get Category Field - if (!String.IsNullOrEmpty(CategoryDataField)) + + // Get Category Field + if (!string.IsNullOrEmpty(this.CategoryDataField)) { - objProperty = obj.GetType().GetProperty(CategoryDataField); + objProperty = obj.GetType().GetProperty(this.CategoryDataField); if (!(objProperty == null || (objProperty.GetValue(obj, null) == null))) { _Category = Convert.ToString(objProperty.GetValue(obj, null)); } } + return _Category; } /// ----------------------------------------------------------------------------- /// - /// GetGroups gets an array of Groups/Categories from the DataSource - /// + /// GetGroups gets an array of Groups/Categories from the DataSource. + ///
    + /// /// ----------------------------------------------------------------------------- protected override string[] GetGroups(IEnumerable arrObjects) { @@ -217,10 +231,10 @@ protected override string[] GetGroups(IEnumerable arrObjects) foreach (object obj in arrObjects) { - //Get Category Field - if (!String.IsNullOrEmpty(CategoryDataField)) + // Get Category Field + if (!string.IsNullOrEmpty(this.CategoryDataField)) { - objProperty = obj.GetType().GetProperty(CategoryDataField); + objProperty = obj.GetType().GetProperty(this.CategoryDataField); if (!((objProperty == null) || (objProperty.GetValue(obj, null) == null))) { string _Category = Convert.ToString(objProperty.GetValue(obj, null)); @@ -232,41 +246,44 @@ protected override string[] GetGroups(IEnumerable arrObjects) } } } + var strGroups = new string[arrGroups.Count]; for (int i = 0; i <= arrGroups.Count - 1; i++) { strGroups[i] = Convert.ToString(arrGroups[i]); } + return strGroups; } /// ----------------------------------------------------------------------------- /// - /// GetRowVisibility determines the Visibility of a row in the table + /// GetRowVisibility determines the Visibility of a row in the table. /// - /// The property + /// The property. + /// /// ----------------------------------------------------------------------------- protected override bool GetRowVisibility(object obj) { bool isVisible = true; PropertyInfo objProperty; - objProperty = obj.GetType().GetProperty(VisibleDataField); + objProperty = obj.GetType().GetProperty(this.VisibleDataField); if (!(objProperty == null || (objProperty.GetValue(obj, null) == null))) { isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null)); } - if (!isVisible && EditMode == PropertyEditorMode.Edit) + + if (!isVisible && this.EditMode == PropertyEditorMode.Edit) { - //Check if property is required - as this will need to override visibility - objProperty = obj.GetType().GetProperty(RequiredDataField); + // Check if property is required - as this will need to override visibility + objProperty = obj.GetType().GetProperty(this.RequiredDataField); if (!(objProperty == null || (objProperty.GetValue(obj, null) == null))) { isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null)); } } + return isVisible; - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs index 7f111950b46..a763276822a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + /// /// The AutoCompleteControl is the same as a TextEditControl but it looks up similar values /// in the profile of other users in the same portal and offers those in a dropdown under the text @@ -19,38 +20,20 @@ namespace DotNetNuke.UI.WebControls /// the textbox. Selection is not enforced and if a user enters a new city it is added to the list. /// [ToolboxData("<{0}:TextEditControl runat=server>")] - class AutoCompleteControl : TextEditControl - { - #region Constructors - + internal class AutoCompleteControl : TextEditControl + { public AutoCompleteControl() { - Init += AutoCompleteControl_Init; - Load += AutoCompleteControl_Load; - } - #endregion - - #region Page Events - private void AutoCompleteControl_Init(object sender, System.EventArgs e) - { - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.ProfileAutoComplete.js"); - ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.AutoComplete.css"); - JavaScript.RequestRegistration(CommonJs.jQuery); - JavaScript.RequestRegistration(CommonJs.jQueryUI); - } - - private void AutoCompleteControl_Load(object sender, System.EventArgs e) - { - - } - #endregion - + this.Init += this.AutoCompleteControl_Init; + this.Load += this.AutoCompleteControl_Load; + } + protected override void RenderEditMode(HtmlTextWriter writer) { int length = Null.NullInteger; - if ((CustomAttributes != null)) + if (this.CustomAttributes != null) { - foreach (Attribute attribute in CustomAttributes) + foreach (Attribute attribute in this.CustomAttributes) { if (attribute is MaxLengthAttribute) { @@ -60,21 +43,34 @@ protected override void RenderEditMode(HtmlTextWriter writer) } } } - ControlStyle.AddAttributesToRender(writer); + + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Value, StringValue); + writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); if (length > Null.NullInteger) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); - writer.AddAttribute("data-name", Name); + + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + writer.AddAttribute("data-name", this.Name); writer.AddAttribute("data-pid", Entities.Portals.PortalSettings.Current.PortalId.ToString()); writer.AddAttribute("data-editor", "AutoCompleteControl"); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); } + + private void AutoCompleteControl_Init(object sender, System.EventArgs e) + { + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.ProfileAutoComplete.js"); + ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.AutoComplete.css"); + JavaScript.RequestRegistration(CommonJs.jQuery); + JavaScript.RequestRegistration(CommonJs.jQueryUI); + } + private void AutoCompleteControl_Load(object sender, System.EventArgs e) + { + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs index 4fefcfc7d05..bcc5b82b1d9 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Web.UI; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -29,7 +24,7 @@ public class CheckEditControl : TrueFalseEditControl { public CheckEditControl() { - SystemType = "System.Boolean"; + this.SystemType = "System.Boolean"; } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) @@ -40,39 +35,41 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo { boolValue = true; } - if (!BooleanValue.Equals(boolValue)) + + if (!this.BooleanValue.Equals(boolValue)) { - Value = boolValue; + this.Value = boolValue; return true; } + return false; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (Page != null && EditMode == PropertyEditorMode.Edit) + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox"); - if ((BooleanValue)) + if (this.BooleanValue) { writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); writer.AddAttribute(HtmlTextWriterAttribute.Value, "1"); } else { - writer.AddAttribute(HtmlTextWriterAttribute.Value, ""); + writer.AddAttribute(HtmlTextWriterAttribute.Value, string.Empty); } writer.AddAttribute("onclick", "this.value = this.checked ? '1' : '';"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); } @@ -80,7 +77,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) protected override void RenderViewMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox"); - if ((BooleanValue)) + if (this.BooleanValue) { writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs index bcd827db442..6427137b25a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs @@ -1,210 +1,195 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Web.UI.WebControls; -using System.Web.UI; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - - [ToolboxData("<{0}:DnnCountryAutocompleteControl runat=server>")] - public class DnnCountryAutocompleteControl : EditControl - { - - #region " Controls " - private TextBox _CountryName; - private TextBox CountryName - { - get - { - if (_CountryName == null) - { - _CountryName = new TextBox(); - } - return _CountryName; - } - } - - private HiddenField _CountryId; - private HiddenField CountryId - { - get - { - if (_CountryId == null) - { - _CountryId = new HiddenField(); - } - return _CountryId; - } - } - - public override string EditControlClientId - { - get - { - EnsureChildControls(); - return CountryName.ClientID; - } - } - - #endregion - - #region " Properties " - protected override string StringValue - { - get - { - string strValue = Null.NullString; - if (Value != null) - { - strValue = Convert.ToString(Value); - } - return strValue; - } - set { this.Value = value; } - } - - protected string OldStringValue - { - get { return Convert.ToString(OldValue); } - } - #endregion - - #region " Constructors " - public DnnCountryAutocompleteControl() - { - Init += DnnCountryRegionControl_Init; - } - public DnnCountryAutocompleteControl(string type) - { - Init += DnnCountryRegionControl_Init; - SystemType = type; - } - #endregion - - #region " Overrides " - protected override void OnDataChanged(EventArgs e) - { - PropertyEditorEventArgs args = new PropertyEditorEventArgs(Name); - args.Value = StringValue; - args.OldValue = OldStringValue; - args.StringValue = StringValue; - base.OnValueChanged(args); - } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - CountryName.ControlStyle.CopyFrom(ControlStyle); - CountryName.ID = ID + "_name"; - CountryName.Attributes.Add("data-name", Name); - CountryName.Attributes.Add("data-list", "Country"); - CountryName.Attributes.Add("data-category", Category); - CountryName.Attributes.Add("data-editor", "DnnCountryAutocompleteControl"); - CountryName.Attributes.Add("data-required", Required.ToString().ToLowerInvariant()); - Controls.Add(CountryName); - - CountryId.ID = ID + "_id"; - Controls.Add(CountryId); - - } - - public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) - { - bool dataChanged = false; - string presentValue = StringValue; - string postedValue = postCollection[postDataKey + "_id"]; - if (!presentValue.Equals(postedValue)) - { - Value = postedValue; - dataChanged = true; - } - return dataChanged; - } - - protected override void OnPreRender(System.EventArgs e) - { - base.OnPreRender(e); - - LoadControls(); - - if (Page != null & EditMode == PropertyEditorMode.Edit) - { - Page.RegisterRequiresPostBack(this); - Page.RegisterRequiresPostBack(CountryId); - } - - } - - protected override void RenderEditMode(HtmlTextWriter writer) - { - RenderChildren(writer); - } - #endregion - - #region " Page Events " - private void DnnCountryRegionControl_Init(object sender, System.EventArgs e) - { - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.js"); - ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.css"); - JavaScript.RequestRegistration(CommonJs.jQuery); - JavaScript.RequestRegistration(CommonJs.jQueryUI); - } - - #endregion - - #region " Private Methods " - private void LoadControls() - { - - CountryName.Text = StringValue; - int countryId = -1; - string countryCode = StringValue; - if (!string.IsNullOrEmpty(StringValue) && int.TryParse(StringValue, out countryId)) - { - var listController = new ListController(); - var c = listController.GetListEntryInfo(countryId); - CountryName.Text = c.Text; - countryCode = c.Value; - } - CountryId.Value = StringValue; - - var regionControl2 = ControlUtilities.FindFirstDescendent(Page, c => IsCoupledRegionControl(c)); - if (regionControl2 != null) - { - regionControl2.ParentKey = "Country." + countryCode; - } - - } - - private bool IsCoupledRegionControl(Control ctr) - { - if (ctr is DNNRegionEditControl) - { - var c = (DNNRegionEditControl)ctr; - if (c.Category == this.Category) - { - return true; - } - } - return false; - } - #endregion - - } + using System; + using System.Linq; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + + [ToolboxData("<{0}:DnnCountryAutocompleteControl runat=server>")] + public class DnnCountryAutocompleteControl : EditControl + { + private TextBox _CountryName; + + private HiddenField _CountryId; + + public DnnCountryAutocompleteControl() + { + this.Init += this.DnnCountryRegionControl_Init; + } + + public DnnCountryAutocompleteControl(string type) + { + this.Init += this.DnnCountryRegionControl_Init; + this.SystemType = type; + } + + public override string EditControlClientId + { + get + { + this.EnsureChildControls(); + return this.CountryName.ClientID; + } + } + + protected override string StringValue + { + get + { + string strValue = Null.NullString; + if (this.Value != null) + { + strValue = Convert.ToString(this.Value); + } + + return strValue; + } + + set { this.Value = value; } + } + + private TextBox CountryName + { + get + { + if (this._CountryName == null) + { + this._CountryName = new TextBox(); + } + + return this._CountryName; + } + } + + private HiddenField CountryId + { + get + { + if (this._CountryId == null) + { + this._CountryId = new HiddenField(); + } + + return this._CountryId; + } + } + + protected string OldStringValue + { + get { return Convert.ToString(this.OldValue); } + } + + public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) + { + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_id"]; + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } + + protected override void OnDataChanged(EventArgs e) + { + PropertyEditorEventArgs args = new PropertyEditorEventArgs(this.Name); + args.Value = this.StringValue; + args.OldValue = this.OldStringValue; + args.StringValue = this.StringValue; + this.OnValueChanged(args); + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.CountryName.ControlStyle.CopyFrom(this.ControlStyle); + this.CountryName.ID = this.ID + "_name"; + this.CountryName.Attributes.Add("data-name", this.Name); + this.CountryName.Attributes.Add("data-list", "Country"); + this.CountryName.Attributes.Add("data-category", this.Category); + this.CountryName.Attributes.Add("data-editor", "DnnCountryAutocompleteControl"); + this.CountryName.Attributes.Add("data-required", this.Required.ToString().ToLowerInvariant()); + this.Controls.Add(this.CountryName); + + this.CountryId.ID = this.ID + "_id"; + this.Controls.Add(this.CountryId); + } + + protected override void OnPreRender(System.EventArgs e) + { + base.OnPreRender(e); + + this.LoadControls(); + + if (this.Page != null & this.EditMode == PropertyEditorMode.Edit) + { + this.Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this.CountryId); + } + } + + protected override void RenderEditMode(HtmlTextWriter writer) + { + this.RenderChildren(writer); + } + + private void DnnCountryRegionControl_Init(object sender, System.EventArgs e) + { + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.js"); + ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.css"); + JavaScript.RequestRegistration(CommonJs.jQuery); + JavaScript.RequestRegistration(CommonJs.jQueryUI); + } + + private void LoadControls() + { + this.CountryName.Text = this.StringValue; + int countryId = -1; + string countryCode = this.StringValue; + if (!string.IsNullOrEmpty(this.StringValue) && int.TryParse(this.StringValue, out countryId)) + { + var listController = new ListController(); + var c = listController.GetListEntryInfo(countryId); + this.CountryName.Text = c.Text; + countryCode = c.Value; + } + + this.CountryId.Value = this.StringValue; + + var regionControl2 = ControlUtilities.FindFirstDescendent(this.Page, c => this.IsCoupledRegionControl(c)); + if (regionControl2 != null) + { + regionControl2.ParentKey = "Country." + countryCode; + } + } + + private bool IsCoupledRegionControl(Control ctr) + { + if (ctr is DNNRegionEditControl) + { + var c = (DNNRegionEditControl)ctr; + if (c.Category == this.Category) + { + return true; + } + } + + return false; + } + } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs index a3f6bcf869a..2c1bfeca1b6 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs @@ -1,69 +1,66 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Web.UI; -using DotNetNuke.Common.Lists; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - /// ----------------------------------------------------------------------------- - /// Project: DotNetNuke - /// Namespace: DotNetNuke.UI.WebControls - /// Class: DNNCountryEditControl - /// ----------------------------------------------------------------------------- - /// - /// The DNNCountryEditControl control provides a standard UI component for editing - /// Countries - /// - /// ----------------------------------------------------------------------------- - [ToolboxData("<{0}:DNNCountryEditControl runat=server>")] - public class DNNCountryEditControl : DNNListEditControl - { - /// ----------------------------------------------------------------------------- - /// - /// Constructs a DNNCountryEditControl - /// - /// ----------------------------------------------------------------------------- - public DNNCountryEditControl() - { - AutoPostBack = true; - ListName = "Country"; - ParentKey = ""; - TextField = ListBoundField.Text; - ValueField = ListBoundField.Id; - ItemChanged += OnItemChanged; - SortAlphabetically = true; - } + using System; + using System.Linq; + using System.Web.UI; + + using DotNetNuke.Common.Lists; + + /// ----------------------------------------------------------------------------- + /// Project: DotNetNuke + /// Namespace: DotNetNuke.UI.WebControls + /// Class: DNNCountryEditControl + /// ----------------------------------------------------------------------------- + /// + /// The DNNCountryEditControl control provides a standard UI component for editing + /// Countries. + /// + /// ----------------------------------------------------------------------------- + [ToolboxData("<{0}:DNNCountryEditControl runat=server>")] + public class DNNCountryEditControl : DNNListEditControl + { + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// Constructs a DNNCountryEditControl. + /// + /// ----------------------------------------------------------------------------- + public DNNCountryEditControl() + { + this.AutoPostBack = true; + this.ListName = "Country"; + this.ParentKey = string.Empty; + this.TextField = ListBoundField.Text; + this.ValueField = ListBoundField.Id; + this.ItemChanged += this.OnItemChanged; + this.SortAlphabetically = true; + } - void OnItemChanged(object sender, PropertyEditorEventArgs e) - { - var regionContainer = ControlUtilities.FindControl(Parent, "Region", true); - if (regionContainer != null) - { - var regionControl = ControlUtilities.FindFirstDescendent(regionContainer); - if (regionControl != null) - { - var listController = new ListController(); - var countries = listController.GetListEntryInfoItems("Country"); - foreach (var checkCountry in countries) - { - if (checkCountry.EntryID.ToString() == e.StringValue) - { - var attributes = new object[1]; - attributes[0] = new ListAttribute("Region", "Country." + checkCountry.Value, ListBoundField.Id, ListBoundField.Text); - regionControl.CustomAttributes = attributes; - break; - } - } - } - } - } - } + private void OnItemChanged(object sender, PropertyEditorEventArgs e) + { + var regionContainer = ControlUtilities.FindControl(this.Parent, "Region", true); + if (regionContainer != null) + { + var regionControl = ControlUtilities.FindFirstDescendent(regionContainer); + if (regionControl != null) + { + var listController = new ListController(); + var countries = listController.GetListEntryInfoItems("Country"); + foreach (var checkCountry in countries) + { + if (checkCountry.EntryID.ToString() == e.StringValue) + { + var attributes = new object[1]; + attributes[0] = new ListAttribute("Region", "Country." + checkCountry.Value, ListBoundField.Id, ListBoundField.Text); + regionControl.CustomAttributes = attributes; + break; + } + } + } + } + } + } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs index 6525fff578c..11d1cc4d0c1 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Web; -using System.Web.UI; - -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -28,158 +23,162 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The DNNListEditControl control provides a standard UI component for selecting - /// from Lists + /// from Lists. /// /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:DNNListEditControl runat=server>")] public class DNNListEditControl : EditControl, IPostBackEventHandler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DNNListEditControl)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DNNListEditControl)); private List _listEntries; - private string _listName = ""; + private string _listName = string.Empty; public DNNListEditControl() { - ValueField = ListBoundField.Value; - TextField = ListBoundField.Text; - ParentKey = ""; - SortAlphabetically = false; + this.ValueField = ListBoundField.Value; + this.TextField = ListBoundField.Text; + this.ParentKey = string.Empty; + this.SortAlphabetically = false; } + + public event PropertyChangedEventHandler ItemChanged; /// ----------------------------------------------------------------------------- /// - /// Determines whether the List Auto Posts Back + /// Gets or sets a value indicating whether determines whether the List Auto Posts Back. /// /// ----------------------------------------------------------------------------- protected bool AutoPostBack { get; set; } /// ----------------------------------------------------------------------------- /// - /// If true the list will be sorted on the value of Text before rendering + /// Gets or sets a value indicating whether if true the list will be sorted on the value of Text before rendering. /// /// ----------------------------------------------------------------------------- - protected bool SortAlphabetically { get; set; } - - #region "Protected Properties" - + protected bool SortAlphabetically { get; set; } + /// ----------------------------------------------------------------------------- /// - /// IntegerValue returns the Integer representation of the Value + /// Gets integerValue returns the Integer representation of the Value. /// - /// An integer representing the Value + /// An integer representing the Value. /// ----------------------------------------------------------------------------- protected int IntegerValue { get { int intValue = Null.NullInteger; - if (Value == null || string.IsNullOrEmpty((string)Value)) - { - return intValue; - } - try + if (this.Value == null || string.IsNullOrEmpty((string)this.Value)) + { + return intValue; + } + + try { - intValue = Convert.ToInt32(Value); + intValue = Convert.ToInt32(this.Value); } catch (Exception exc) { Logger.Error(exc); - } + return intValue; } } /// - /// List gets the List associated with the control + /// Gets list gets the List associated with the control. /// - [Obsolete("Obsoleted in 6.0.1 use ListEntries instead. Scheduled removal in v10.0.0."), EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Obsoleted in 6.0.1 use ListEntries instead. Scheduled removal in v10.0.0.")] + [EditorBrowsable(EditorBrowsableState.Never)] protected ListEntryInfoCollection List { get { var listController = new ListController(); - return listController.GetListEntryInfoCollection(ListName, ParentKey, PortalId); + return listController.GetListEntryInfoCollection(this.ListName, this.ParentKey, this.PortalId); } } /// - /// Gets the ListEntryInfo objects associated witht the control + /// Gets the ListEntryInfo objects associated witht the control. /// protected IEnumerable ListEntries { get { - if(_listEntries == null) + if (this._listEntries == null) { var listController = new ListController(); - if (SortAlphabetically) + if (this.SortAlphabetically) { - _listEntries = listController.GetListEntryInfoItems(ListName, ParentKey, PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); + this._listEntries = listController.GetListEntryInfoItems(this.ListName, this.ParentKey, this.PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); } else { - _listEntries = listController.GetListEntryInfoItems(ListName, ParentKey, PortalId).ToList(); + this._listEntries = listController.GetListEntryInfoItems(this.ListName, this.ParentKey, this.PortalId).ToList(); } } - return _listEntries; + return this._listEntries; } } - - + /// ----------------------------------------------------------------------------- /// - /// ListName is the name of the List to display + /// Gets or sets listName is the name of the List to display. /// /// ----------------------------------------------------------------------------- protected virtual string ListName { get { - if (_listName == Null.NullString) + if (this._listName == Null.NullString) { - _listName = DataField; + this._listName = this.DataField; } - return _listName; + + return this._listName; } + set { - _listName = value; + this._listName = value; } } /// ----------------------------------------------------------------------------- /// - /// OldIntegerValue returns the Integer representation of the OldValue + /// Gets oldIntegerValue returns the Integer representation of the OldValue. /// - /// An integer representing the OldValue + /// An integer representing the OldValue. /// ----------------------------------------------------------------------------- protected int OldIntegerValue { get { int intValue = Null.NullInteger; - if (OldValue == null || string.IsNullOrEmpty(OldValue.ToString())) + if (this.OldValue == null || string.IsNullOrEmpty(this.OldValue.ToString())) { - return intValue; - } - try + return intValue; + } + + try { - //Try and cast the value to an Integer - intValue = Convert.ToInt32(OldValue); + // Try and cast the value to an Integer + intValue = Convert.ToInt32(this.OldValue); } catch (Exception exc) { Logger.Error(exc); - } + return intValue; } } /// - /// The parent key of the List to display + /// Gets or sets the parent key of the List to display. /// protected virtual string ParentKey { get; set; } @@ -192,97 +191,65 @@ protected int PortalId } /// - /// The field to display in the combo + /// Gets or sets the field to display in the combo. /// protected virtual ListBoundField TextField { get; set; } /// - /// The field to use as the combo item values + /// Gets or sets the field to use as the combo item values. /// protected virtual ListBoundField ValueField { get; set; } /// ----------------------------------------------------------------------------- /// - /// OldStringValue returns the Boolean representation of the OldValue + /// Gets oldStringValue returns the Boolean representation of the OldValue. /// - /// A String representing the OldValue + /// A String representing the OldValue. /// ----------------------------------------------------------------------------- protected string OldStringValue { get { - return Convert.ToString(OldValue); + return Convert.ToString(this.OldValue); } } /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets stringValue is the value of the control expressed as a String. /// - /// A string representing the Value + /// A string representing the Value. /// ----------------------------------------------------------------------------- protected override string StringValue { get { - return Convert.ToString(Value); + return Convert.ToString(this.Value); } + set { - if (ValueField == ListBoundField.Id) + if (this.ValueField == ListBoundField.Id) { - //Integer type field - Value = Int32.Parse(value); + // Integer type field + this.Value = int.Parse(value); } else { - //String type Field - Value = value; + // String type Field + this.Value = value; } } - } - - #endregion - - #region IPostBackEventHandler Members - + } + public void RaisePostBackEvent(string eventArgument) { - if (AutoPostBack) - { - OnItemChanged(GetEventArgs()); - } - } - - #endregion - - public event PropertyChangedEventHandler ItemChanged; - - #region "Private Methods" - - private PropertyEditorEventArgs GetEventArgs() - { - var args = new PropertyEditorEventArgs(Name); - if (ValueField == ListBoundField.Id) + if (this.AutoPostBack) { - //This is an Integer Value - args.Value = IntegerValue; - args.OldValue = OldIntegerValue; + this.OnItemChanged(this.GetEventArgs()); } - else - { - //This is a String Value - args.Value = StringValue; - args.OldValue = OldStringValue; - } - args.StringValue = StringValue; - return args; - } - - #endregion - - #region "Protected Methods" - + } + /// ----------------------------------------------------------------------------- /// /// OnAttributesChanged runs when the CustomAttributes property has changed. @@ -290,18 +257,18 @@ private PropertyEditorEventArgs GetEventArgs() /// ----------------------------------------------------------------------------- protected override void OnAttributesChanged() { - //Get the List settings out of the "Attributes" - if ((CustomAttributes != null)) + // Get the List settings out of the "Attributes" + if (this.CustomAttributes != null) { - foreach (Attribute attribute in CustomAttributes) + foreach (Attribute attribute in this.CustomAttributes) { if (attribute is ListAttribute) { - var listAtt = (ListAttribute) attribute; - ListName = listAtt.ListName; - ParentKey = listAtt.ParentKey; - TextField = listAtt.TextField; - ValueField = listAtt.ValueField; + var listAtt = (ListAttribute)attribute; + this.ListName = listAtt.ListName; + this.ParentKey = listAtt.ParentKey; + this.TextField = listAtt.TextField; + this.ValueField = listAtt.ValueField; break; } } @@ -311,30 +278,50 @@ protected override void OnAttributesChanged() /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected override void OnDataChanged(EventArgs e) { - base.OnValueChanged(GetEventArgs()); + this.OnValueChanged(this.GetEventArgs()); } + + private PropertyEditorEventArgs GetEventArgs() + { + var args = new PropertyEditorEventArgs(this.Name); + if (this.ValueField == ListBoundField.Id) + { + // This is an Integer Value + args.Value = this.IntegerValue; + args.OldValue = this.OldIntegerValue; + } + else + { + // This is a String Value + args.Value = this.StringValue; + args.OldValue = this.OldStringValue; + } + + args.StringValue = this.StringValue; + return args; + } /// ----------------------------------------------------------------------------- /// - /// OnItemChanged runs when the Item has changed + /// OnItemChanged runs when the Item has changed. /// /// ----------------------------------------------------------------------------- protected virtual void OnItemChanged(PropertyEditorEventArgs e) { - if (ItemChanged != null) + if (this.ItemChanged != null) { - ItemChanged(this, e); + this.ItemChanged(this, e); } } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- @@ -343,23 +330,24 @@ protected override void RenderViewMode(HtmlTextWriter writer) var objListController = new ListController(); ListEntryInfo entry = null; string entryText = Null.NullString; - switch (ValueField) + switch (this.ValueField) { case ListBoundField.Id: - entry = objListController.GetListEntryInfo(ListName, Convert.ToInt32(Value)); + entry = objListController.GetListEntryInfo(this.ListName, Convert.ToInt32(this.Value)); break; case ListBoundField.Text: - entryText = StringValue; + entryText = this.StringValue; break; case ListBoundField.Value: - entry = objListController.GetListEntryInfo(ListName, StringValue); + entry = objListController.GetListEntryInfo(this.ListName, this.StringValue); break; } - ControlStyle.AddAttributesToRender(writer); + + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); if (entry != null) { - switch (TextField) + switch (this.TextField) { case ListBoundField.Id: writer.Write(entry.EntryID.ToString()); @@ -376,35 +364,36 @@ protected override void RenderViewMode(HtmlTextWriter writer) { writer.Write(entryText); } - - //Close Select Tag + + // Close Select Tag writer.RenderEndTag(); } /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { - //Render the Select Tag - ControlStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); - writer.AddAttribute("data-name", Name); - writer.AddAttribute("data-list", ListName); - writer.AddAttribute("data-category", Category); - writer.AddAttribute("data-editor", "DNNListEditControl"); - if (AutoPostBack) + // Render the Select Tag + this.ControlStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + writer.AddAttribute("data-name", this.Name); + writer.AddAttribute("data-list", this.ListName); + writer.AddAttribute("data-category", this.Category); + writer.AddAttribute("data-editor", "DNNListEditControl"); + if (this.AutoPostBack) { - writer.AddAttribute(HtmlTextWriterAttribute.Onchange, Page.ClientScript.GetPostBackEventReference(this, ID)); + writer.AddAttribute(HtmlTextWriterAttribute.Onchange, this.Page.ClientScript.GetPostBackEventReference(this, this.ID)); } + writer.RenderBeginTag(HtmlTextWriterTag.Select); - //Add the Not Specified Option - if (ValueField == ListBoundField.Text) + // Add the Not Specified Option + if (this.ValueField == ListBoundField.Text) { writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); } @@ -412,9 +401,10 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); } - if (StringValue == Null.NullString) + + if (this.StringValue == Null.NullString) { - //Add the Selected Attribute + // Add the Selected Attribute writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } @@ -422,13 +412,13 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(defaultText); writer.RenderEndTag(); - - foreach (ListEntryInfo item in ListEntries) + + foreach (ListEntryInfo item in this.ListEntries) { string itemValue = Null.NullString; - - //Add the Value Attribute - switch (ValueField) + + // Add the Value Attribute + switch (this.ValueField) { case ListBoundField.Id: itemValue = item.EntryID.ToString(); @@ -440,16 +430,17 @@ protected override void RenderEditMode(HtmlTextWriter writer) itemValue = item.Value; break; } + writer.AddAttribute(HtmlTextWriterAttribute.Value, itemValue); - if (StringValue == itemValue) + if (this.StringValue == itemValue) { - //Add the Selected Attribute + // Add the Selected Attribute writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } - - //Render Option Tag - writer.RenderBeginTag(HtmlTextWriterTag.Option); - switch (TextField) + + // Render Option Tag + writer.RenderBeginTag(HtmlTextWriterTag.Option); + switch (this.TextField) { case ListBoundField.Id: writer.Write(item.EntryID.ToString()); @@ -461,13 +452,12 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.Write(item.Value.Trim()); break; } + writer.RenderEndTag(); } - - //Close Select Tag - writer.RenderEndTag(); - } - - #endregion + + // Close Select Tag + writer.RenderEndTag(); + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs index 41be7c57d5b..1bd721ad2e8 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs @@ -1,244 +1,238 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web.UI; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + + /// + /// The DNNLocaleEditControl control provides a standard UI component for selecting + /// a Locale. + /// + [ToolboxData("<{0}:DNNLocaleEditControl runat=server>")] + public class DNNLocaleEditControl : TextEditControl, IPostBackEventHandler + { + private string _DisplayMode = "Native"; + private LanguagesListType _ListType = LanguagesListType.Enabled; + + protected LanguagesListType ListType + { + get + { + return this._ListType; + } + } - /// - /// The DNNLocaleEditControl control provides a standard UI component for selecting - /// a Locale - /// - [ToolboxData("<{0}:DNNLocaleEditControl runat=server>")] - public class DNNLocaleEditControl : TextEditControl, IPostBackEventHandler - { - private string _DisplayMode = "Native"; - private LanguagesListType _ListType = LanguagesListType.Enabled; - - protected LanguagesListType ListType - { - get - { - return _ListType; - } - } - - protected string DisplayMode - { - get - { - return _DisplayMode; - } - } - - protected PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - - #region IPostBackEventHandler Members - - public void RaisePostBackEvent(string eventArgument) - { - _DisplayMode = eventArgument; - } - - #endregion - - private bool IsSelected(string locale) - { - return locale == StringValue; - } - - private void RenderModeButtons(HtmlTextWriter writer) - { - writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); - writer.AddAttribute("aria-label", "Mode"); - if (DisplayMode == "English") - { - writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Onclick, Page.ClientScript.GetPostBackEventReference(this, "English")); - } - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.RenderEndTag(); - writer.Write(Localization.GetString("EnglishName", Localization.GlobalResourceFile)); - //writer.Write("
    "); + protected string DisplayMode + { + get + { + return this._DisplayMode; + } + } - writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); + protected PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } + + public void RaisePostBackEvent(string eventArgument) + { + this._DisplayMode = eventArgument; + } + + /// + /// OnAttributesChanged runs when the CustomAttributes property has changed. + /// + protected override void OnAttributesChanged() + { + // Get the List settings out of the "Attributes" + if (this.CustomAttributes != null) + { + foreach (Attribute attribute in this.CustomAttributes) + { + var listAtt = attribute as LanguagesListTypeAttribute; + if (listAtt != null) + { + this._ListType = listAtt.ListType; + break; + } + } + } + } + + /// + /// RenderViewMode renders the View (readonly) mode of the control. + /// + /// A HtmlTextWriter. + protected override void RenderViewMode(HtmlTextWriter writer) + { + Locale locale = LocaleController.Instance.GetLocale(this.StringValue); + + this.ControlStyle.AddAttributesToRender(writer); + writer.RenderBeginTag(HtmlTextWriterTag.Div); + if (locale != null) + { + writer.Write(locale.Text); + } + + writer.RenderEndTag(); + } + + private bool IsSelected(string locale) + { + return locale == this.StringValue; + } + + private void RenderModeButtons(HtmlTextWriter writer) + { + writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); writer.AddAttribute("aria-label", "Mode"); - if (DisplayMode == "Native") - { - writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Onclick, Page.ClientScript.GetPostBackEventReference(this, "Native")); - } - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.RenderEndTag(); - - writer.Write(Localization.GetString("NativeName", Localization.GlobalResourceFile)); - } - - private void RenderOption(HtmlTextWriter writer, CultureInfo culture) - { - string localeName; - - if (DisplayMode == "Native") - { - localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.NativeName); - } - else - { - localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.EnglishName); - } - - //Add the Value Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Value, culture.Name); - - if (IsSelected(culture.Name)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); - } - - //Render Option Tag - writer.RenderBeginTag(HtmlTextWriterTag.Option); - writer.Write(localeName); - writer.RenderEndTag(); - } + if (this.DisplayMode == "English") + { + writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.Page.ClientScript.GetPostBackEventReference(this, "English")); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.RenderEndTag(); + writer.Write(Localization.GetString("EnglishName", Localization.GlobalResourceFile)); + + // writer.Write("
    "); + writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); + writer.AddAttribute("aria-label", "Mode"); + if (this.DisplayMode == "Native") + { + writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.Page.ClientScript.GetPostBackEventReference(this, "Native")); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.RenderEndTag(); - #region Protected Methods + writer.Write(Localization.GetString("NativeName", Localization.GlobalResourceFile)); + } - /// - /// OnAttributesChanged runs when the CustomAttributes property has changed. - /// - protected override void OnAttributesChanged() - { - //Get the List settings out of the "Attributes" - if ((CustomAttributes != null)) - { - foreach (Attribute attribute in CustomAttributes) - { - var listAtt = attribute as LanguagesListTypeAttribute; - if (listAtt != null) - { - _ListType = listAtt.ListType; - break; - } - } - } - } + private void RenderOption(HtmlTextWriter writer, CultureInfo culture) + { + string localeName; - /// - /// RenderViewMode renders the View (readonly) mode of the control - /// - /// A HtmlTextWriter. - protected override void RenderViewMode(HtmlTextWriter writer) - { - Locale locale = LocaleController.Instance.GetLocale(StringValue); + if (this.DisplayMode == "Native") + { + localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.NativeName); + } + else + { + localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.EnglishName); + } - ControlStyle.AddAttributesToRender(writer); - writer.RenderBeginTag(HtmlTextWriterTag.Div); - if (locale != null) - { - writer.Write(locale.Text); - } - writer.RenderEndTag(); - } + // Add the Value Attribute + writer.AddAttribute(HtmlTextWriterAttribute.Value, culture.Name); - /// - /// RenderEditMode renders the Edit mode of the control - /// - /// A HtmlTextWriter. - protected override void RenderEditMode(HtmlTextWriter writer) - { - //Render div - writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnLeft"); - writer.RenderBeginTag(HtmlTextWriterTag.Div); + if (this.IsSelected(culture.Name)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); + } - IList cultures = new List(); - switch (ListType) - { - case LanguagesListType.All: - var culturesArray = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - Array.Sort(culturesArray, new CultureInfoComparer(DisplayMode)); - cultures = culturesArray.ToList(); + // Render Option Tag + writer.RenderBeginTag(HtmlTextWriterTag.Option); + writer.Write(localeName); + writer.RenderEndTag(); + } + + /// + /// RenderEditMode renders the Edit mode of the control. + /// + /// A HtmlTextWriter. + protected override void RenderEditMode(HtmlTextWriter writer) + { + // Render div + writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnLeft"); + writer.RenderBeginTag(HtmlTextWriterTag.Div); + + IList cultures = new List(); + switch (this.ListType) + { + case LanguagesListType.All: + var culturesArray = CultureInfo.GetCultures(CultureTypes.SpecificCultures); + Array.Sort(culturesArray, new CultureInfoComparer(this.DisplayMode)); + cultures = culturesArray.ToList(); + break; + case LanguagesListType.Supported: + cultures = LocaleController.Instance.GetLocales(Null.NullInteger).Values + .Select(c => CultureInfo.GetCultureInfo(c.Code)) + .ToList(); + break; + case LanguagesListType.Enabled: + cultures = LocaleController.Instance.GetLocales(this.PortalSettings.PortalId).Values + .Select(c => CultureInfo.GetCultureInfo(c.Code)) + .ToList(); break; - case LanguagesListType.Supported: - cultures = LocaleController.Instance.GetLocales(Null.NullInteger).Values - .Select(c => CultureInfo.GetCultureInfo(c.Code)) - .ToList(); - break; - case LanguagesListType.Enabled: - cultures = LocaleController.Instance.GetLocales(PortalSettings.PortalId).Values - .Select(c => CultureInfo.GetCultureInfo(c.Code)) - .ToList(); - break; - } + } - var promptValue = StringValue == Null.NullString && cultures.Count > 1 && !Required; + var promptValue = this.StringValue == Null.NullString && cultures.Count > 1 && !this.Required; - //Render the Select Tag - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); - if (promptValue) - { + // Render the Select Tag + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + if (promptValue) + { writer.AddAttribute(HtmlTextWriterAttribute.Onchange, "onLocaleChanged(this)"); - } - writer.RenderBeginTag(HtmlTextWriterTag.Select); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Select); - //Render None selected option - //Add the Value Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); + // Render None selected option + // Add the Value Attribute + writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); - if (StringValue == Null.NullString) - { - //Add the Selected Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); - } - writer.RenderBeginTag(HtmlTextWriterTag.Option); - writer.Write(Localization.GetString("Not_Specified", Localization.SharedResourceFile)); - writer.RenderEndTag(); + if (this.StringValue == Null.NullString) + { + // Add the Selected Attribute + writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Option); + writer.Write(Localization.GetString("Not_Specified", Localization.SharedResourceFile)); + writer.RenderEndTag(); - foreach (var culture in cultures) - { - RenderOption(writer, culture); - } + foreach (var culture in cultures) + { + this.RenderOption(writer, culture); + } - //Close Select Tag + // Close Select Tag writer.RenderEndTag(); - if (promptValue) - { - writer.WriteBreak(); + if (promptValue) + { + writer.WriteBreak(); - writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnFormMessage dnnFormError"); - writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(Localization.GetString("LanguageNotSelected", Localization.SharedResourceFile)); - writer.RenderEndTag(); + writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnFormMessage dnnFormError"); + writer.RenderBeginTag(HtmlTextWriterTag.Span); + writer.Write(Localization.GetString("LanguageNotSelected", Localization.SharedResourceFile)); + writer.RenderEndTag(); - writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); - writer.RenderBeginTag(HtmlTextWriterTag.Script); - writer.Write(@" + writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); + writer.RenderBeginTag(HtmlTextWriterTag.Script); + writer.Write(@" function onLocaleChanged(element){ var $this = $(element); var $error = $this.next().next(); @@ -246,26 +240,24 @@ function onLocaleChanged(element){ value ? $error.hide() : $error.show(); }; "); - writer.RenderEndTag(); + writer.RenderEndTag(); } - //Render break - writer.Write("
    "); + // Render break + writer.Write("
    "); - //Render Span - writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnFormRadioButtons"); - writer.RenderBeginTag(HtmlTextWriterTag.Span); + // Render Span + writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnFormRadioButtons"); + writer.RenderBeginTag(HtmlTextWriterTag.Span); - //Render Button Row - RenderModeButtons(writer); + // Render Button Row + this.RenderModeButtons(writer); - //close span - writer.RenderEndTag(); + // close span + writer.RenderEndTag(); - //close div - writer.RenderEndTag(); - } - - #endregion - } + // close div + writer.RenderEndTag(); + } + } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs index e0e1e5e16fc..d71197a46ce 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Generic; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -25,17 +20,15 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The DNNPageEditControl control provides a standard UI component for selecting - /// a DNN Page + /// a DNN Page. /// /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:DNNPageEditControl runat=server>")] public class DNNPageEditControl : IntegerEditControl - { - #region "Protected Methods" - + { /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- @@ -43,66 +36,64 @@ protected override void RenderEditMode(HtmlTextWriter writer) { PortalSettings _portalSettings = Globals.GetPortalSettings(); - //Get the Pages + // Get the Pages List listTabs = TabController.GetPortalTabs(_portalSettings.PortalId, Null.NullInteger, true, "<" + Localization.GetString("None_Specified") + ">", true, false, true, true, false); - //Render the Select Tag - ControlStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); + // Render the Select Tag + this.ControlStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.RenderBeginTag(HtmlTextWriterTag.Select); for (int tabIndex = 0; tabIndex <= listTabs.Count - 1; tabIndex++) { TabInfo tab = listTabs[tabIndex]; - //Add the Value Attribute + // Add the Value Attribute writer.AddAttribute(HtmlTextWriterAttribute.Value, tab.TabID.ToString()); - if (tab.TabID == IntegerValue) + if (tab.TabID == this.IntegerValue) { - //Add the Selected Attribute + // Add the Selected Attribute writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } - - //Render Option Tag + + // Render Option Tag writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(tab.IndentedTabName); writer.RenderEndTag(); } - - //Close Select Tag + + // Close Select Tag writer.RenderEndTag(); } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View mode of the control + /// RenderViewMode renders the View mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderViewMode(HtmlTextWriter writer) { - TabInfo linkedTabInfo = TabController.Instance.GetTab(IntegerValue, Globals.GetPortalSettings().PortalId, false); + TabInfo linkedTabInfo = TabController.Instance.GetTab(this.IntegerValue, Globals.GetPortalSettings().PortalId, false); - //don't render anything if we didn't find the tab + // don't render anything if we didn't find the tab if (linkedTabInfo != null) { - //Not really sure how to get a good TabID and ModuleID but it's only for tracking so not to concerned + // Not really sure how to get a good TabID and ModuleID but it's only for tracking so not to concerned int tabID = 0; int moduleID = 0; - Int32.TryParse(Page.Request.QueryString["tabid"], out tabID); - Int32.TryParse(Page.Request.QueryString["mid"], out moduleID); + int.TryParse(this.Page.Request.QueryString["tabid"], out tabID); + int.TryParse(this.Page.Request.QueryString["mid"], out moduleID); - string url = Globals.LinkClick(StringValue, tabID, moduleID, true); - ControlStyle.AddAttributesToRender(writer); + string url = Globals.LinkClick(this.StringValue, tabID, moduleID, true); + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Href, url); writer.AddAttribute(HtmlTextWriterAttribute.Class, "Normal"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(linkedTabInfo.LocalizedTabName); writer.RenderEndTag(); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs index dd27d3e1c1b..32b02addf70 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs @@ -1,266 +1,258 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Web.UI.WebControls; -using System.Web.UI; -using DotNetNuke.Common.Utilities; -using System.Web.UI.HtmlControls; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Framework.JavaScriptLibraries; -using System.Collections.Generic; -using DotNetNuke.Common.Lists; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Client; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls -{ /// ----------------------------------------------------------------------------- - /// Project: DotNetNuke - /// Namespace: DotNetNuke.UI.WebControls - /// Class: DNNRegionEditControl - /// ----------------------------------------------------------------------------- - /// - /// The DNNRegionEditControl control provides a standard UI component for editing - /// Regions - /// - /// ----------------------------------------------------------------------------- - [ToolboxData("<{0}:DNNRegionEditControl runat=server>")] - public class DNNRegionEditControl : EditControl - { - - #region Controls - private DropDownList _Regions; - private DropDownList Regions - { - get - { - if (_Regions == null) - { - _Regions = new DropDownList(); - } - return _Regions; - } - } - - private TextBox _Region; - private TextBox Region - { - get - { - if (_Region == null) - { - _Region = new TextBox(); - } - return _Region; - } - } - - private HtmlInputHidden _InitialValue; - private HtmlInputHidden RegionCode - { - get - { - if (_InitialValue == null) - { - _InitialValue = new HtmlInputHidden(); - } - return _InitialValue; - } - } - #endregion - - #region Properties - protected override string StringValue - { - get - { - string strValue = Null.NullString; - if (Value != null) - { - strValue = Convert.ToString(Value); - } - return strValue; - } - set { this.Value = value; } - } - - protected string OldStringValue - { - get { return Convert.ToString(OldValue); } - } - - /// - /// The parent key of the List to display - /// - public string ParentKey { get; set; } - - private List _listEntries; - /// - /// Gets the ListEntryInfo objects associated witht the control - /// - protected IEnumerable ListEntries - { - get - { - if (_listEntries == null) - { - var listController = new ListController(); - _listEntries = listController.GetListEntryInfoItems("Region", ParentKey, PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); - } - - return _listEntries; - } - } - - protected int PortalId - { - get - { - return PortalController.GetEffectivePortalId(PortalSettings.Current.PortalId); - } - } - #endregion - - #region Constructors - public DNNRegionEditControl() - { - Init += DnnRegionControl_Init; - } - public DNNRegionEditControl(string type) - { - Init += DnnRegionControl_Init; - SystemType = type; - } - #endregion +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + + /// ----------------------------------------------------------------------------- + /// Project: DotNetNuke + /// Namespace: DotNetNuke.UI.WebControls + /// Class: DNNRegionEditControl + /// ----------------------------------------------------------------------------- + /// + /// The DNNRegionEditControl control provides a standard UI component for editing + /// Regions. + /// + /// ----------------------------------------------------------------------------- + [ToolboxData("<{0}:DNNRegionEditControl runat=server>")] + public class DNNRegionEditControl : EditControl + { + private DropDownList _Regions; - #region Overrides - /// ----------------------------------------------------------------------------- - /// - /// OnAttributesChanged runs when the CustomAttributes property has changed. - /// - /// ----------------------------------------------------------------------------- - protected override void OnAttributesChanged() - { - //Get the List settings out of the "Attributes" - if ((CustomAttributes != null)) - { - foreach (Attribute attribute in CustomAttributes) - { - if (attribute is ListAttribute) - { - var listAtt = (ListAttribute)attribute; - ParentKey = listAtt.ParentKey; - _listEntries = null; - break; - } - } - } - } + private TextBox _Region; - protected override void OnDataChanged(EventArgs e) - { - PropertyEditorEventArgs args = new PropertyEditorEventArgs(Name); - args.Value = StringValue; - args.OldValue = OldStringValue; - args.StringValue = StringValue; - base.OnValueChanged(args); - } + private HtmlInputHidden _InitialValue; - protected override void CreateChildControls() - { - base.CreateChildControls(); + private List _listEntries; + + public DNNRegionEditControl() + { + this.Init += this.DnnRegionControl_Init; + } + + public DNNRegionEditControl(string type) + { + this.Init += this.DnnRegionControl_Init; + this.SystemType = type; + } - Regions.ControlStyle.CopyFrom(ControlStyle); - Regions.ID = ID + "_dropdown"; - Regions.Attributes.Add("data-editor", "DNNRegionEditControl_DropDown"); - Regions.Attributes.Add("aria-label", "Region"); - Regions.Items.Add(new ListItem() { Text = "<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", Value = "" }); - Controls.Add(Regions); + /// + /// Gets or sets the parent key of the List to display. + /// + public string ParentKey { get; set; } + + protected override string StringValue + { + get + { + string strValue = Null.NullString; + if (this.Value != null) + { + strValue = Convert.ToString(this.Value); + } + + return strValue; + } + + set { this.Value = value; } + } - Region.ControlStyle.CopyFrom(ControlStyle); - Region.ID = ID + "_text"; - Region.Attributes.Add("data-editor", "DNNRegionEditControl_Text"); - Controls.Add(Region); + protected string OldStringValue + { + get { return Convert.ToString(this.OldValue); } + } + + private DropDownList Regions + { + get + { + if (this._Regions == null) + { + this._Regions = new DropDownList(); + } + + return this._Regions; + } + } + + private TextBox Region + { + get + { + if (this._Region == null) + { + this._Region = new TextBox(); + } + + return this._Region; + } + } + + private HtmlInputHidden RegionCode + { + get + { + if (this._InitialValue == null) + { + this._InitialValue = new HtmlInputHidden(); + } + + return this._InitialValue; + } + } + + /// + /// Gets the ListEntryInfo objects associated witht the control. + /// + protected IEnumerable ListEntries + { + get + { + if (this._listEntries == null) + { + var listController = new ListController(); + this._listEntries = listController.GetListEntryInfoItems("Region", this.ParentKey, this.PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); + } - RegionCode.ID = ID + "_value"; - RegionCode.Attributes.Add("data-editor", "DNNRegionEditControl_Hidden"); - Controls.Add(RegionCode); + return this._listEntries; + } + } - } + protected int PortalId + { + get + { + return PortalController.GetEffectivePortalId(PortalSettings.Current.PortalId); + } + } - public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) - { - bool dataChanged = false; - string presentValue = StringValue; - string postedValue = postCollection[postDataKey + "_value"]; - if (!presentValue.Equals(postedValue)) - { - Value = postedValue; - dataChanged = true; - } - return dataChanged; - } + public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) + { + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_value"]; + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } + + /// ----------------------------------------------------------------------------- + /// + /// OnAttributesChanged runs when the CustomAttributes property has changed. + /// + /// ----------------------------------------------------------------------------- + protected override void OnAttributesChanged() + { + // Get the List settings out of the "Attributes" + if (this.CustomAttributes != null) + { + foreach (Attribute attribute in this.CustomAttributes) + { + if (attribute is ListAttribute) + { + var listAtt = (ListAttribute)attribute; + this.ParentKey = listAtt.ParentKey; + this._listEntries = null; + break; + } + } + } + } - protected override void OnPreRender(System.EventArgs e) - { - base.OnPreRender(e); + protected override void OnDataChanged(EventArgs e) + { + PropertyEditorEventArgs args = new PropertyEditorEventArgs(this.Name); + args.Value = this.StringValue; + args.OldValue = this.OldStringValue; + args.StringValue = this.StringValue; + this.OnValueChanged(args); + } - LoadControls(); + protected override void CreateChildControls() + { + base.CreateChildControls(); - if (Page != null & EditMode == PropertyEditorMode.Edit) - { - Page.RegisterRequiresPostBack(this); - Page.RegisterRequiresPostBack(RegionCode); - } + this.Regions.ControlStyle.CopyFrom(this.ControlStyle); + this.Regions.ID = this.ID + "_dropdown"; + this.Regions.Attributes.Add("data-editor", "DNNRegionEditControl_DropDown"); + this.Regions.Attributes.Add("aria-label", "Region"); + this.Regions.Items.Add(new ListItem() { Text = "<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", Value = string.Empty }); + this.Controls.Add(this.Regions); - } + this.Region.ControlStyle.CopyFrom(this.ControlStyle); + this.Region.ID = this.ID + "_text"; + this.Region.Attributes.Add("data-editor", "DNNRegionEditControl_Text"); + this.Controls.Add(this.Region); - protected override void RenderEditMode(HtmlTextWriter writer) - { - if (ListEntries != null && ListEntries.Any()) - { - foreach (ListEntryInfo item in ListEntries) - { - Regions.Items.Add(new ListItem() { Text = item.Text, Value = item.EntryID.ToString() }); - } - } - ControlStyle.AddAttributesToRender(writer); - writer.AddAttribute("data-name", Name); - writer.AddAttribute("data-list", "Region"); - writer.AddAttribute("data-category", Category); - writer.AddAttribute("data-required", Required.ToString().ToLowerInvariant()); - writer.RenderBeginTag(HtmlTextWriterTag.Div); - RenderChildren(writer); - writer.RenderEndTag(); - } - #endregion + this.RegionCode.ID = this.ID + "_value"; + this.RegionCode.Attributes.Add("data-editor", "DNNRegionEditControl_Hidden"); + this.Controls.Add(this.RegionCode); + } - #region Page Events - private void DnnRegionControl_Init(object sender, System.EventArgs e) - { - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.js"); - ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.css"); - JavaScript.RequestRegistration(CommonJs.jQuery); - JavaScript.RequestRegistration(CommonJs.jQueryUI); - } + protected override void OnPreRender(System.EventArgs e) + { + base.OnPreRender(e); - #endregion + this.LoadControls(); - #region Private Methods - private void LoadControls() - { - RegionCode.Value = StringValue; - } - #endregion + if (this.Page != null & this.EditMode == PropertyEditorMode.Edit) + { + this.Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this.RegionCode); + } + } - } + protected override void RenderEditMode(HtmlTextWriter writer) + { + if (this.ListEntries != null && this.ListEntries.Any()) + { + foreach (ListEntryInfo item in this.ListEntries) + { + this.Regions.Items.Add(new ListItem() { Text = item.Text, Value = item.EntryID.ToString() }); + } + } + + this.ControlStyle.AddAttributesToRender(writer); + writer.AddAttribute("data-name", this.Name); + writer.AddAttribute("data-list", "Region"); + writer.AddAttribute("data-category", this.Category); + writer.AddAttribute("data-required", this.Required.ToString().ToLowerInvariant()); + writer.RenderBeginTag(HtmlTextWriterTag.Div); + this.RenderChildren(writer); + writer.RenderEndTag(); + } + + private void DnnRegionControl_Init(object sender, System.EventArgs e) + { + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.js"); + ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.css"); + JavaScript.RequestRegistration(CommonJs.jQuery); + JavaScript.RequestRegistration(CommonJs.jQueryUI); + } + + private void LoadControls() + { + this.RegionCode.Value = this.StringValue; + } + } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs index fb2216fabf8..db3b7659971 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Text.RegularExpressions; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Modules.HTMLEditorProvider; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - + using System; + using System.Collections.Specialized; + using System.Text.RegularExpressions; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Modules.HTMLEditorProvider; + /// /// The DNNRichTextEditControl control provides a standard UI component for editing - /// RichText + /// RichText. /// [ToolboxData("<{0}:DNNRichTextEditControl runat=server>")] public class DNNRichTextEditControl : TextEditControl @@ -31,12 +26,12 @@ protected Control TextEditControl { get { - if (_richTextEditor != null) + if (this._richTextEditor != null) { - return _richTextEditor.HtmlEditorControl; + return this._richTextEditor.HtmlEditorControl; } - return _defaultTextEditor; + return this._defaultTextEditor; } } @@ -44,133 +39,134 @@ protected string EditorText { get { - if (_richTextEditor != null) + if (this._richTextEditor != null) { - return _richTextEditor.Text; + return this._richTextEditor.Text; } - return _defaultTextEditor.Text; + return this._defaultTextEditor.Text; } + set { - if (_richTextEditor != null) + if (this._richTextEditor != null) { - _richTextEditor.Text = value; + this._richTextEditor.Text = value; } else { - _defaultTextEditor.Text = value; + this._defaultTextEditor.Text = value; } } } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + var dataChanged = false; + var presentValue = this.StringValue; + var postedValue = this.EditorText; + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } + protected override void CreateChildControls() { - if (EditMode == PropertyEditorMode.Edit) + if (this.EditMode == PropertyEditorMode.Edit) { var pnlEditor = new Panel(); - if(string.IsNullOrEmpty(CssClass)) + if (string.IsNullOrEmpty(this.CssClass)) { - pnlEditor.CssClass ="dnnLeft"; + pnlEditor.CssClass = "dnnLeft"; } else { - pnlEditor.CssClass = string.Format("{0} dnnLeft", CssClass); + pnlEditor.CssClass = string.Format("{0} dnnLeft", this.CssClass); } - - - _richTextEditor = HtmlEditorProvider.Instance(); - if (_richTextEditor != null) + + this._richTextEditor = HtmlEditorProvider.Instance(); + if (this._richTextEditor != null) { - _richTextEditor.ControlID = ID + "edit"; - _richTextEditor.Initialize(); - _richTextEditor.Height = ControlStyle.Height; - _richTextEditor.Width = ControlStyle.Width; - if (_richTextEditor.Height.IsEmpty) + this._richTextEditor.ControlID = this.ID + "edit"; + this._richTextEditor.Initialize(); + this._richTextEditor.Height = this.ControlStyle.Height; + this._richTextEditor.Width = this.ControlStyle.Width; + if (this._richTextEditor.Height.IsEmpty) { - _richTextEditor.Height = new Unit(250); + this._richTextEditor.Height = new Unit(250); } - _richTextEditor.Width = new Unit(400); + this._richTextEditor.Width = new Unit(400); } else { - _defaultTextEditor = new TextBox - { - ID = ID + "edit", - Width = ControlStyle.Width.IsEmpty ? new Unit(300) : ControlStyle.Width, - Height = ControlStyle.Height.IsEmpty ? new Unit(250) : ControlStyle.Height, - TextMode = TextBoxMode.MultiLine - }; - _defaultTextEditor.Attributes.Add("aria-label", "editor"); + this._defaultTextEditor = new TextBox + { + ID = this.ID + "edit", + Width = this.ControlStyle.Width.IsEmpty ? new Unit(300) : this.ControlStyle.Width, + Height = this.ControlStyle.Height.IsEmpty ? new Unit(250) : this.ControlStyle.Height, + TextMode = TextBoxMode.MultiLine, + }; + this._defaultTextEditor.Attributes.Add("aria-label", "editor"); } - Controls.Clear(); - pnlEditor.Controls.Add(TextEditControl); - Controls.Add(pnlEditor); - + this.Controls.Clear(); + pnlEditor.Controls.Add(this.TextEditControl); + this.Controls.Add(pnlEditor); } + base.CreateChildControls(); } - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - var dataChanged = false; - var presentValue = StringValue; - var postedValue = EditorText; - if (!presentValue.Equals(postedValue)) - { - Value = postedValue; - dataChanged = true; - } - return dataChanged; - } - protected override void OnDataChanged(EventArgs e) { - var strValue = RemoveBaseTags(Convert.ToString(Value)); - var strOldValue = RemoveBaseTags(Convert.ToString(OldValue)); - var args = new PropertyEditorEventArgs(Name) { Value = Page.Server.HtmlEncode(strValue), OldValue = Page.Server.HtmlEncode(strOldValue), StringValue = Page.Server.HtmlEncode(RemoveBaseTags(StringValue)) }; - base.OnValueChanged(args); - } - - private string RemoveBaseTags(String strInput) - { - return Globals.BaseTagRegex.Replace(strInput, " "); + var strValue = this.RemoveBaseTags(Convert.ToString(this.Value)); + var strOldValue = this.RemoveBaseTags(Convert.ToString(this.OldValue)); + var args = new PropertyEditorEventArgs(this.Name) { Value = this.Page.Server.HtmlEncode(strValue), OldValue = this.Page.Server.HtmlEncode(strOldValue), StringValue = this.Page.Server.HtmlEncode(this.RemoveBaseTags(this.StringValue)) }; + this.OnValueChanged(args); } protected override void OnInit(EventArgs e) { - EnsureChildControls(); + this.EnsureChildControls(); base.OnInit(e); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (EditMode == PropertyEditorMode.Edit) + if (this.EditMode == PropertyEditorMode.Edit) { - EditorText = Page.Server.HtmlDecode(Convert.ToString(Value)); + this.EditorText = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); } - if (Page != null && EditMode == PropertyEditorMode.Edit) + + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } + private string RemoveBaseTags(string strInput) + { + return Globals.BaseTagRegex.Replace(strInput, " "); + } + protected override void RenderEditMode(HtmlTextWriter writer) { - RenderChildren(writer); + this.RenderChildren(writer); } protected override void RenderViewMode(HtmlTextWriter writer) { - string propValue = Page.Server.HtmlDecode(Convert.ToString(Value)); - ControlStyle.AddAttributesToRender(writer); + string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(propValue); writer.RenderEndTag(); } - } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs index 2fc42dae88d..d954242d792 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; - -using Calendar = DotNetNuke.Common.Utilities.Calendar; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + + using Calendar = DotNetNuke.Common.Utilities.Calendar; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -36,17 +31,15 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:DateEditControl runat=server>")] public class DateEditControl : EditControl { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DateEditControl)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); private TextBox dateField; - private HyperLink linkCalendar; - - #region "Protected Properties" - + private HyperLink linkCalendar; + /// ----------------------------------------------------------------------------- /// - /// DateValue returns the Date representation of the Value + /// Gets dateValue returns the Date representation of the Value. /// - /// A Date representing the Value + /// A Date representing the Value. /// ----------------------------------------------------------------------------- protected DateTime DateValue { @@ -55,25 +48,25 @@ protected DateTime DateValue DateTime dteValue = Null.NullDate; try { - var dteString = Convert.ToString(Value); + var dteString = Convert.ToString(this.Value); DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); } catch (Exception exc) { Logger.Error(exc); - } + return dteValue; } } /// ----------------------------------------------------------------------------- /// - /// DefaultDateFormat is a string that will be used to format the date in the absence of a - /// FormatAttribute + /// Gets defaultDateFormat is a string that will be used to format the date in the absence of a + /// FormatAttribute. /// - /// A String representing the default format to use to render the date - /// A Format String + /// A String representing the default format to use to render the date. + /// A Format String. /// ----------------------------------------------------------------------------- protected virtual string DefaultFormat { @@ -85,37 +78,38 @@ protected virtual string DefaultFormat /// ----------------------------------------------------------------------------- /// - /// Format is a string that will be used to format the date in View mode + /// Gets format is a string that will be used to format the date in View mode. /// - /// A String representing the format to use to render the date - /// A Format String + /// A String representing the format to use to render the date. + /// A Format String. /// ----------------------------------------------------------------------------- protected virtual string Format { get { - string _Format = DefaultFormat; - if (CustomAttributes != null) + string _Format = this.DefaultFormat; + if (this.CustomAttributes != null) { - foreach (Attribute attribute in CustomAttributes) + foreach (Attribute attribute in this.CustomAttributes) { if (attribute is FormatAttribute) { - var formatAtt = (FormatAttribute) attribute; + var formatAtt = (FormatAttribute)attribute; _Format = formatAtt.Format; break; } } } + return _Format; } } /// ----------------------------------------------------------------------------- /// - /// OldDateValue returns the Date representation of the OldValue + /// Gets oldDateValue returns the Date representation of the OldValue. /// - /// A Date representing the OldValue + /// A Date representing the OldValue. /// ----------------------------------------------------------------------------- protected DateTime OldDateValue { @@ -124,127 +118,127 @@ protected DateTime OldDateValue DateTime dteValue = Null.NullDate; try { - //Try and cast the value to an DateTime - var dteString = OldValue as string; + // Try and cast the value to an DateTime + var dteString = this.OldValue as string; dteValue = DateTime.Parse(dteString, CultureInfo.InvariantCulture); } catch (Exception exc) { Logger.Error(exc); - } + return dteValue; } } /// - /// The Value expressed as a String + /// Gets or sets the Value expressed as a String. /// protected override string StringValue { get { string _StringValue = Null.NullString; - if ((DateValue.ToUniversalTime().Date != DateTime.Parse("1754/01/01") && DateValue != Null.NullDate)) + if (this.DateValue.ToUniversalTime().Date != DateTime.Parse("1754/01/01") && this.DateValue != Null.NullDate) { - _StringValue = DateValue.ToString(Format); + _StringValue = this.DateValue.ToString(this.Format); } + return _StringValue; } + set { - Value = DateTime.Parse(value); + this.Value = DateTime.Parse(value); } - } - - #endregion + } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + this.EnsureChildControls(); + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "date"]; + if (!presentValue.Equals(postedValue)) + { + this.Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); + dataChanged = true; + } + + return dataChanged; + } + protected override void CreateChildControls() { base.CreateChildControls(); - dateField = new TextBox(); - dateField.ControlStyle.CopyFrom(ControlStyle); - dateField.ID = ID + "date"; - Controls.Add(dateField); + this.dateField = new TextBox(); + this.dateField.ControlStyle.CopyFrom(this.ControlStyle); + this.dateField.ID = this.ID + "date"; + this.Controls.Add(this.dateField); - Controls.Add(new LiteralControl(" ")); + this.Controls.Add(new LiteralControl(" ")); - linkCalendar = new HyperLink(); - linkCalendar.CssClass = "CommandButton"; - linkCalendar.Text = "  " + Localization.GetString("Calendar"); - linkCalendar.NavigateUrl = Calendar.InvokePopupCal(dateField); - Controls.Add(linkCalendar); + this.linkCalendar = new HyperLink(); + this.linkCalendar.CssClass = "CommandButton"; + this.linkCalendar.Text = "  " + Localization.GetString("Calendar"); + this.linkCalendar.NavigateUrl = Calendar.InvokePopupCal(this.dateField); + this.Controls.Add(this.linkCalendar); } protected virtual void LoadDateControls() { - if (DateValue != Null.NullDate) - { - dateField.Text = DateValue.Date.ToString("d"); - } - } - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - EnsureChildControls(); - bool dataChanged = false; - string presentValue = StringValue; - string postedValue = postCollection[postDataKey + "date"]; - if (!presentValue.Equals(postedValue)) + if (this.DateValue != Null.NullDate) { - Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); - dataChanged = true; + this.dateField.Text = this.DateValue.Date.ToString("d"); } - - return dataChanged; } /// - /// OnDataChanged is called by the PostBack Handler when the Data has changed + /// OnDataChanged is called by the PostBack Handler when the Data has changed. /// - /// An EventArgs object + /// An EventArgs object. protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = DateValue; - args.OldValue = OldDateValue; - args.StringValue = DateValue.ToString(CultureInfo.InvariantCulture); - base.OnValueChanged(args); + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.DateValue; + args.OldValue = this.OldDateValue; + args.StringValue = this.DateValue.ToString(CultureInfo.InvariantCulture); + this.OnValueChanged(args); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - LoadDateControls(); + this.LoadDateControls(); - if (Page != null && EditMode == PropertyEditorMode.Edit) + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } /// - /// RenderEditMode is called by the base control to render the control in Edit Mode + /// RenderEditMode is called by the base control to render the control in Edit Mode. /// /// protected override void RenderEditMode(HtmlTextWriter writer) { - RenderChildren(writer); + this.RenderChildren(writer); } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderViewMode(HtmlTextWriter writer) { - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(StringValue); + writer.Write(this.StringValue); writer.RenderEndTag(); } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs index 983e2dbe130..890ea5ebc8a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Globalization; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Globalization; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -38,11 +33,11 @@ public class DateTimeEditControl : DateEditControl /// ----------------------------------------------------------------------------- /// - /// DefaultFormat is a string that will be used to format the date in the absence of a - /// FormatAttribute + /// Gets defaultFormat is a string that will be used to format the date in the absence of a + /// FormatAttribute. /// - /// A String representing the default format to use to render the date - /// A Format String + /// A String representing the default format to use to render the date. + /// A Format String. /// ----------------------------------------------------------------------------- protected override string DefaultFormat { @@ -52,123 +47,137 @@ protected override string DefaultFormat } } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + bool dataChanged = false; + DateTime presentValue = this.OldDateValue; + string postedDate = postCollection[postDataKey + "date"]; + string postedHours = postCollection[postDataKey + "hours"]; + string postedMinutes = postCollection[postDataKey + "minutes"]; + string postedAMPM = postCollection[postDataKey + "ampm"]; + DateTime postedValue = Null.NullDate; + if (!string.IsNullOrEmpty(postedDate)) + { + DateTime.TryParse(postedDate, out postedValue); + } + + if (postedHours != "12" || this.is24HourClock) + { + int hours = 0; + if (int.TryParse(postedHours, out hours)) + { + postedValue = postedValue.AddHours(hours); + } + } + + postedValue = postedValue.AddMinutes(int.Parse(postedMinutes)); + if (!this.is24HourClock && postedAMPM.Equals("PM")) + { + postedValue = postedValue.AddHours(12); + } + + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue.ToString(CultureInfo.InvariantCulture); + dataChanged = true; + } + + return dataChanged; + } + protected override void OnInit(EventArgs e) { base.OnInit(e); if (string.IsNullOrEmpty(CultureInfo.CurrentCulture.DateTimeFormat.AMDesignator)) { - is24HourClock = true; + this.is24HourClock = true; } } protected override void CreateChildControls() { base.CreateChildControls(); - Controls.Add(new LiteralControl("
    ")); - hourField = new DropDownList(); + this.Controls.Add(new LiteralControl("
    ")); + this.hourField = new DropDownList(); int maxHour = 12; int minHour = 1; - if (is24HourClock) + if (this.is24HourClock) { minHour = 0; maxHour = 23; } + for (int i = minHour; i <= maxHour; i++) { - hourField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); + this.hourField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); } - hourField.ControlStyle.CopyFrom(ControlStyle); - hourField.ID = ID + "hours"; - Controls.Add(hourField); - Controls.Add(new LiteralControl(" ")); - minutesField = new DropDownList(); + + this.hourField.ControlStyle.CopyFrom(this.ControlStyle); + this.hourField.ID = this.ID + "hours"; + this.Controls.Add(this.hourField); + this.Controls.Add(new LiteralControl(" ")); + this.minutesField = new DropDownList(); for (int i = 0; i <= 59; i++) { - minutesField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); + this.minutesField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); } - minutesField.ControlStyle.CopyFrom(ControlStyle); - minutesField.ID = ID + "minutes"; - Controls.Add(minutesField); - if (!is24HourClock) + + this.minutesField.ControlStyle.CopyFrom(this.ControlStyle); + this.minutesField.ID = this.ID + "minutes"; + this.Controls.Add(this.minutesField); + if (!this.is24HourClock) { - Controls.Add(new LiteralControl(" ")); - ampmField = new DropDownList(); - ampmField.Items.Add(new ListItem("AM", "AM")); - ampmField.Items.Add(new ListItem("PM", "PM")); - ampmField.ControlStyle.CopyFrom(ControlStyle); - ampmField.ID = ID + "ampm"; - Controls.Add(ampmField); + this.Controls.Add(new LiteralControl(" ")); + this.ampmField = new DropDownList(); + this.ampmField.Items.Add(new ListItem("AM", "AM")); + this.ampmField.Items.Add(new ListItem("PM", "PM")); + this.ampmField.ControlStyle.CopyFrom(this.ControlStyle); + this.ampmField.ID = this.ID + "ampm"; + this.Controls.Add(this.ampmField); } } protected override void LoadDateControls() { base.LoadDateControls(); - int hour = DateValue.Hour; - int minute = DateValue.Minute; + int hour = this.DateValue.Hour; + int minute = this.DateValue.Minute; bool isAM = true; - if (!is24HourClock) + if (!this.is24HourClock) { if (hour >= 12) { hour -= 12; isAM = false; } + if (hour == 0) { hour = 12; } } - if (hourField.Items.FindByValue(hour.ToString()) != null) + + if (this.hourField.Items.FindByValue(hour.ToString()) != null) { - hourField.Items.FindByValue(hour.ToString()).Selected = true; + this.hourField.Items.FindByValue(hour.ToString()).Selected = true; } - if (minutesField.Items.FindByValue(minute.ToString()) != null) + + if (this.minutesField.Items.FindByValue(minute.ToString()) != null) { - minutesField.Items.FindByValue(minute.ToString()).Selected = true; + this.minutesField.Items.FindByValue(minute.ToString()).Selected = true; } - if (!is24HourClock) + + if (!this.is24HourClock) { if (isAM) { - ampmField.SelectedIndex = 0; + this.ampmField.SelectedIndex = 0; } else { - ampmField.SelectedIndex = 1; + this.ampmField.SelectedIndex = 1; } } } - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - bool dataChanged = false; - DateTime presentValue = OldDateValue; - string postedDate = postCollection[postDataKey + "date"]; - string postedHours = postCollection[postDataKey + "hours"]; - string postedMinutes = postCollection[postDataKey + "minutes"]; - string postedAMPM = postCollection[postDataKey + "ampm"]; - DateTime postedValue = Null.NullDate; - if (!string.IsNullOrEmpty(postedDate)) - { - DateTime.TryParse(postedDate, out postedValue); - } - if (postedHours != "12" || is24HourClock) - { - int hours = 0; - if(Int32.TryParse(postedHours, out hours)) postedValue = postedValue.AddHours(hours); - } - postedValue = postedValue.AddMinutes(Int32.Parse(postedMinutes)); - if (!is24HourClock && postedAMPM.Equals("PM")) - { - postedValue = postedValue.AddHours(12); - } - if (!presentValue.Equals(postedValue)) - { - Value = postedValue.ToString(CultureInfo.InvariantCulture); - dataChanged = true; - } - return dataChanged; - } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs index c9cf1a57c6b..cffd578b371 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: EditControl /// ----------------------------------------------------------------------------- /// - /// The EditControl control provides a standard UI component for editing + /// The EditControl control provides a standard UI component for editing /// properties. /// /// @@ -31,49 +26,50 @@ namespace DotNetNuke.UI.WebControls [ValidationPropertyAttribute("Value")] public abstract class EditControl : WebControl, IPostBackDataHandler { - #region "Private Members" - private object[] _CustomAttributes; - #endregion + public event PropertyChangedEventHandler ItemAdded; + + public event PropertyChangedEventHandler ItemDeleted; - #region "Data Properties" + public event PropertyChangedEventHandler ValueChanged; /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Custom Attributes for this Control + /// Gets or sets and sets the Custom Attributes for this Control. /// - /// An array of Attributes + /// An array of Attributes. /// ----------------------------------------------------------------------------- public object[] CustomAttributes { get { - return _CustomAttributes; + return this._CustomAttributes; } + set { - _CustomAttributes = value; - if ((_CustomAttributes != null) && _CustomAttributes.Length > 0) + this._CustomAttributes = value; + if ((this._CustomAttributes != null) && this._CustomAttributes.Length > 0) { - OnAttributesChanged(); + this.OnAttributesChanged(); } } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Edit Mode of the Editor + /// Gets or sets and sets the Edit Mode of the Editor. /// - /// A boolean + /// A boolean. /// ----------------------------------------------------------------------------- public PropertyEditorMode EditMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Returns whether the + /// Gets a value indicating whether returns whether the. /// - /// A boolean + /// A boolean. /// ----------------------------------------------------------------------------- public virtual bool IsValid { @@ -85,142 +81,124 @@ public virtual bool IsValid /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Local Resource File for the Control + /// Gets or sets and sets the Local Resource File for the Control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string LocalResourceFile { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Name is the name of the field as a string - /// - /// A string representing the Name of the property - /// ----------------------------------------------------------------------------- - public string Name { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// The Category to which this edit control belongs - /// - /// A string representing the Category of the property - /// ----------------------------------------------------------------------------- - public string Category { get; set; } - - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets name is the name of the field as a string. + /// + /// A string representing the Name of the property. + /// ----------------------------------------------------------------------------- + public string Name { get; set; } + + /// ----------------------------------------------------------------------------- /// - /// OldValue is the initial value of the field + /// Gets or sets the Category to which this edit control belongs. /// - /// The initial Value of the property + /// A string representing the Category of the property. + /// ----------------------------------------------------------------------------- + public string Category { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets oldValue is the initial value of the field. + /// + /// The initial Value of the property. /// ----------------------------------------------------------------------------- public object OldValue { get; set; } /// ----------------------------------------------------------------------------- /// - /// gets and sets whether the Property is required + /// Gets or sets a value indicating whether gets and sets whether the Property is required. /// - /// The initial Value of the property + /// The initial Value of the property. /// ----------------------------------------------------------------------------- public bool Required { get; set; } /// ----------------------------------------------------------------------------- /// - /// SystemType is the System Data Type for the property + /// Gets or sets systemType is the System Data Type for the property. /// - /// A string representing the Type of the property + /// A string representing the Type of the property. /// ----------------------------------------------------------------------------- public string SystemType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Value is the value of the control + /// Gets or sets value is the value of the control. /// - /// The Value of the property + /// The Value of the property. /// ----------------------------------------------------------------------------- public object Value { get; set; } - /// - /// Set Data Field of the control. - /// - public string DataField { get; set; } - - /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets set Data Field of the control. /// - /// A string representing the Value - /// ----------------------------------------------------------------------------- - protected abstract string StringValue { get; set; } + public string DataField { get; set; } public UserInfo User { get; set; } - public virtual string EditControlClientId - { - get - { - return ClientID; - } - } - - #endregion + public virtual string EditControlClientId + { + get + { + return this.ClientID; + } + } - #region IPostBackDataHandler Members + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets stringValue is the value of the control expressed as a String. + /// + /// A string representing the Value. + /// ----------------------------------------------------------------------------- + protected abstract string StringValue { get; set; } /// ----------------------------------------------------------------------------- /// - /// LoadPostData loads the Post Back Data and determines whether the value has change + /// LoadPostData loads the Post Back Data and determines whether the value has change. /// - /// A key to the PostBack Data to load - /// A name value collection of postback data + /// A key to the PostBack Data to load. + /// A name value collection of postback data. + /// /// ----------------------------------------------------------------------------- public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { bool dataChanged = false; - string presentValue = StringValue; + string presentValue = this.StringValue; string postedValue = postCollection[postDataKey]; if (!presentValue.Equals(postedValue)) { - Value = postedValue; + this.Value = postedValue; dataChanged = true; } + return dataChanged; } /// ----------------------------------------------------------------------------- /// /// RaisePostDataChangedEvent runs when the PostBackData has changed. It triggers - /// a ValueChanged Event + /// a ValueChanged Event. /// /// ----------------------------------------------------------------------------- public void RaisePostDataChangedEvent() { - OnDataChanged(EventArgs.Empty); + this.OnDataChanged(EventArgs.Empty); } - #endregion - - #region "Events" - - public event PropertyChangedEventHandler ItemAdded; - public event PropertyChangedEventHandler ItemDeleted; - public event PropertyChangedEventHandler ValueChanged; - - #endregion - - #region "Abstract Members" - /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected abstract void OnDataChanged(EventArgs e); - #endregion - - #region "Protected Methods" - /// ----------------------------------------------------------------------------- /// /// OnAttributesChanged runs when the CustomAttributes property has changed. @@ -232,55 +210,55 @@ protected virtual void OnAttributesChanged() /// ----------------------------------------------------------------------------- /// - /// Runs when an item is added to a collection type property + /// Runs when an item is added to a collection type property. /// /// ----------------------------------------------------------------------------- protected virtual void OnItemAdded(PropertyEditorEventArgs e) { - if (ItemAdded != null) + if (this.ItemAdded != null) { - ItemAdded(this, e); + this.ItemAdded(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Runs when an item is deleted from a collection type property + /// Runs when an item is deleted from a collection type property. /// /// ----------------------------------------------------------------------------- protected virtual void OnItemDeleted(PropertyEditorEventArgs e) { - if (ItemDeleted != null) + if (this.ItemDeleted != null) { - ItemDeleted(this, e); + this.ItemDeleted(this, e); } } /// ----------------------------------------------------------------------------- /// /// OnValueChanged runs when the Value has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected virtual void OnValueChanged(PropertyEditorEventArgs e) { - if (ValueChanged != null) + if (this.ValueChanged != null) { - ValueChanged(this, e); + this.ValueChanged(this, e); } } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected virtual void RenderViewMode(HtmlTextWriter writer) { - string propValue = Page.Server.HtmlDecode(Convert.ToString(Value)); + string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); var security = PortalSecurity.Instance; writer.Write(security.InputFilter(propValue, PortalSecurity.FilterFlag.NoScripting)); @@ -289,42 +267,40 @@ protected virtual void RenderViewMode(HtmlTextWriter writer) /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected virtual void RenderEditMode(HtmlTextWriter writer) { - string propValue = Convert.ToString(Value); + string propValue = Convert.ToString(this.Value); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Value, propValue); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); } /// ----------------------------------------------------------------------------- /// - /// Render is called by the .NET framework to render the control + /// Render is called by the .NET framework to render the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void Render(HtmlTextWriter writer) { - var strOldValue = OldValue as string; - if (EditMode == PropertyEditorMode.Edit || (Required && string.IsNullOrEmpty(strOldValue))) + var strOldValue = this.OldValue as string; + if (this.EditMode == PropertyEditorMode.Edit || (this.Required && string.IsNullOrEmpty(strOldValue))) { - RenderEditMode(writer); + this.RenderEditMode(writer); } else { - RenderViewMode(writer); + this.RenderViewMode(writer); } } - - #endregion } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs index ec10f4be692..3b15b0bc4f3 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -17,7 +12,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The EditControlFactory control provides a factory for creating the - /// appropriate Edit Control + /// appropriate Edit Control. /// /// /// @@ -27,9 +22,10 @@ public class EditControlFactory /// ----------------------------------------------------------------------------- /// /// CreateEditControl creates the appropriate Control based on the EditorField or - /// TypeDataField + /// TypeDataField. /// - /// An EditorInfo object + /// An EditorInfo object. + /// /// ----------------------------------------------------------------------------- public static EditControl CreateEditControl(EditorInfo editorInfo) { @@ -37,12 +33,12 @@ public static EditControl CreateEditControl(EditorInfo editorInfo) if (editorInfo.Editor == "UseSystemType") { - //Use System Type + // Use System Type propEditor = CreateEditControlInternal(editorInfo.Type); } else { - //Use Editor + // Use Editor try { Type editType = Type.GetType(editorInfo.Editor, true, true); @@ -50,10 +46,11 @@ public static EditControl CreateEditControl(EditorInfo editorInfo) } catch (TypeLoadException) { - //Use System Type + // Use System Type propEditor = CreateEditControlInternal(editorInfo.Type); } } + propEditor.ID = editorInfo.Name; propEditor.Name = editorInfo.Name; propEditor.DataField = editorInfo.Name; @@ -95,16 +92,17 @@ private static EditControl CreateEditControlInternal(string systemType) { propEditor = new EnumEditControl(systemType); } + break; } } } catch (Exception) { - //ignore + // ignore } + return propEditor ?? new TextEditControl(systemType); } } -} - +} diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs index 6226cdc896f..a5272269387 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; -using System.Web.UI; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Globalization; + using System.Web.UI; + + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -27,135 +22,126 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:EnumEditControl runat=server>")] public class EnumEditControl : EditControl { - private readonly Type EnumType; - - #region Constructors - + private readonly Type EnumType; + /// ----------------------------------------------------------------------------- - /// - /// Constructs an EnumEditControl + /// + /// Initializes a new instance of the class. + /// Constructs an EnumEditControl. /// /// ----------------------------------------------------------------------------- public EnumEditControl() { - } - + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs an EnumEditControl + /// + /// Initializes a new instance of the class. + /// Constructs an EnumEditControl. /// /// ----------------------------------------------------------------------------- public EnumEditControl(string type) { - SystemType = type; - EnumType = Type.GetType(type); - } - - #endregion - - #region Public Properties - + this.SystemType = type; + this.EnumType = Type.GetType(type); + } + /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets stringValue is the value of the control expressed as a String. /// - /// A string representing the Value + /// A string representing the Value. /// ----------------------------------------------------------------------------- protected override string StringValue { get { - var retValue = Convert.ToInt32(Value); + var retValue = Convert.ToInt32(this.Value); return retValue.ToString(CultureInfo.InvariantCulture); } + set { - int setValue = Int32.Parse(value); - Value = setValue; + int setValue = int.Parse(value); + this.Value = setValue; } - } - - #endregion - - #region Protected Methods - + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected override void OnDataChanged(EventArgs e) { - int intValue = Convert.ToInt32(Value); - int intOldValue = Convert.ToInt32(OldValue); + int intValue = Convert.ToInt32(this.Value); + int intOldValue = Convert.ToInt32(this.OldValue); - var args = new PropertyEditorEventArgs(Name) - {Value = Enum.ToObject(EnumType, intValue), OldValue = Enum.ToObject(EnumType, intOldValue)}; + var args = new PropertyEditorEventArgs(this.Name) + { Value = Enum.ToObject(this.EnumType, intValue), OldValue = Enum.ToObject(this.EnumType, intOldValue) }; - base.OnValueChanged(args); + this.OnValueChanged(args); } /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { - Int32 propValue = Convert.ToInt32(Value); - Array enumValues = Enum.GetValues(EnumType); + int propValue = Convert.ToInt32(this.Value); + Array enumValues = Enum.GetValues(this.EnumType); - //Render the Select Tag - ControlStyle.AddAttributesToRender(writer); + // Render the Select Tag + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Select); for (int I = 0; I <= enumValues.Length - 1; I++) { int enumValue = Convert.ToInt32(enumValues.GetValue(I)); - string enumName = Enum.GetName(EnumType, enumValue); - enumName = Localization.GetString(enumName, LocalResourceFile); + string enumName = Enum.GetName(this.EnumType, enumValue); + enumName = Localization.GetString(enumName, this.LocalResourceFile); - //Add the Value Attribute + // Add the Value Attribute writer.AddAttribute(HtmlTextWriterAttribute.Value, enumValue.ToString(CultureInfo.InvariantCulture)); if (enumValue == propValue) { - //Add the Selected Attribute + // Add the Selected Attribute writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } - - //Render Option Tag + + // Render Option Tag writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(enumName); writer.RenderEndTag(); } - - //Close Select Tag + + // Close Select Tag writer.RenderEndTag(); } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderViewMode(HtmlTextWriter writer) { - Int32 propValue = Convert.ToInt32(Value); - string enumValue = Enum.Format(EnumType, propValue, "G"); + int propValue = Convert.ToInt32(this.Value); + string enumValue = Enum.Format(this.EnumType, propValue, "G"); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(enumValue); writer.RenderEndTag(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs index 22f07ae2c1b..a9d01bffb12 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -29,47 +24,44 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:IntegerEditControl runat=server>")] public class IntegerEditControl : EditControl { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (IntegerEditControl)); - #region "Constructors" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IntegerEditControl)); + /// ----------------------------------------------------------------------------- - /// - /// Constructs an IntegerEditControl + /// + /// Initializes a new instance of the class. + /// Constructs an IntegerEditControl. /// /// ----------------------------------------------------------------------------- public IntegerEditControl() { - SystemType = "System.Int32"; - } - - #endregion - - #region "Protected Properties" - + this.SystemType = "System.Int32"; + } + /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets stringValue is the value of the control expressed as a String. /// - /// A string representing the Value + /// A string representing the Value. /// ----------------------------------------------------------------------------- protected override string StringValue { get { - return IntegerValue.ToString(); + return this.IntegerValue.ToString(); } + set { - int setValue = Int32.Parse(value); - Value = setValue; + int setValue = int.Parse(value); + this.Value = setValue; } } /// ----------------------------------------------------------------------------- /// - /// IntegerValue returns the Integer representation of the Value + /// Gets integerValue returns the Integer representation of the Value. /// - /// An integer representing the Value + /// An integer representing the Value. /// ----------------------------------------------------------------------------- protected int IntegerValue { @@ -78,26 +70,26 @@ protected int IntegerValue int intValue = Null.NullInteger; try { - //Try and cast the value to an Integer - if(Value != null) + // Try and cast the value to an Integer + if (this.Value != null) { - Int32.TryParse(Value.ToString(), out intValue); + int.TryParse(this.Value.ToString(), out intValue); } } catch (Exception exc) { Logger.Error(exc); - } + return intValue; } } /// ----------------------------------------------------------------------------- /// - /// OldIntegerValue returns the Integer representation of the OldValue + /// Gets oldIntegerValue returns the Integer representation of the OldValue. /// - /// An integer representing the OldValue + /// An integer representing the OldValue. /// ----------------------------------------------------------------------------- protected int OldIntegerValue { @@ -106,55 +98,49 @@ protected int OldIntegerValue int intValue = Null.NullInteger; try { - //Try and cast the value to an Integer - int.TryParse(OldValue.ToString(), out intValue); + // Try and cast the value to an Integer + int.TryParse(this.OldValue.ToString(), out intValue); } catch (Exception exc) { Logger.Error(exc); - } + return intValue; } - } - - #endregion - - #region "Protected Methods" - + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = IntegerValue; - args.OldValue = OldIntegerValue; - args.StringValue = StringValue; - base.OnValueChanged(args); + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.IntegerValue; + args.OldValue = this.OldIntegerValue; + args.StringValue = this.StringValue; + this.OnValueChanged(args); } /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Size, "5"); - writer.AddAttribute(HtmlTextWriterAttribute.Value, StringValue); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); + writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs index 05175490ec7..59c449caa5e 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - ///----------------------------------------------------------------------------- + using System; + using System.Web.UI; + + /// ----------------------------------------------------------------------------- /// /// The MultiLineTextEditControl control provides a standard UI component for editing /// string/text properties. @@ -24,10 +19,10 @@ public class MultiLineTextEditControl : TextEditControl { protected override void RenderEditMode(HtmlTextWriter writer) { - string propValue = Convert.ToString(Value); - ControlStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); + string propValue = Convert.ToString(this.Value); + this.ControlStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.AddAttribute("aria-label", "editor"); writer.RenderBeginTag(HtmlTextWriterTag.Textarea); writer.Write(propValue); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs index 142243cdd65..4613a83d074 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -27,109 +22,115 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:TextEditControl runat=server>")] public class TextEditControl : EditControl - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a TextEditControl + /// + /// Initializes a new instance of the class. + /// Constructs a TextEditControl. /// /// ----------------------------------------------------------------------------- public TextEditControl() { - } - + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a TextEditControl + /// + /// Initializes a new instance of the class. + /// Constructs a TextEditControl. /// - /// The type of the property + /// The type of the property. /// ----------------------------------------------------------------------------- public TextEditControl(string type) { - SystemType = type; + this.SystemType = type; } /// ----------------------------------------------------------------------------- /// - /// OldStringValue returns the Boolean representation of the OldValue + /// Gets oldStringValue returns the Boolean representation of the OldValue. /// - /// A String representing the OldValue + /// A String representing the OldValue. /// ----------------------------------------------------------------------------- protected string OldStringValue { get { - return Convert.ToString(OldValue); + return Convert.ToString(this.OldValue); } } /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets stringValue is the value of the control expressed as a String. /// - /// A string representing the Value + /// A string representing the Value. /// ----------------------------------------------------------------------------- protected override string StringValue { get { string strValue = Null.NullString; - if (Value != null) + if (this.Value != null) { - strValue = Convert.ToString(Value); + strValue = Convert.ToString(this.Value); } + return strValue; } + set { - Value = value; + this.Value = value; } } /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = StringValue; - args.OldValue = OldStringValue; - args.StringValue = StringValue; - base.OnValueChanged(args); + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.StringValue; + args.OldValue = this.OldStringValue; + args.StringValue = this.StringValue; + this.OnValueChanged(args); } /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { int length = Null.NullInteger; - if ((CustomAttributes != null)) + if (this.CustomAttributes != null) { - foreach (Attribute attribute in CustomAttributes) + foreach (Attribute attribute in this.CustomAttributes) { if (attribute is MaxLengthAttribute) { - var lengthAtt = (MaxLengthAttribute) attribute; + var lengthAtt = (MaxLengthAttribute)attribute; length = lengthAtt.Length; break; } } } - ControlStyle.AddAttributesToRender(writer); + + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Value, StringValue); + writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); if (length > Null.NullInteger) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID); + + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs index 1073822ec76..732537d83fe 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -31,28 +26,24 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:TrueFalseEditControl runat=server>")] public class TrueFalseEditControl : EditControl { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (TrueFalseEditControl)); - #region "Constructors" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TrueFalseEditControl)); + /// ----------------------------------------------------------------------------- - /// - /// Constructs a TrueFalseEditControl + /// + /// Initializes a new instance of the class. + /// Constructs a TrueFalseEditControl. /// /// ----------------------------------------------------------------------------- public TrueFalseEditControl() { - SystemType = "System.Boolean"; - } - - #endregion - - #region "Public Properties" - + this.SystemType = "System.Boolean"; + } + /// ----------------------------------------------------------------------------- /// - /// BooleanValue returns the Boolean representation of the Value + /// Gets a value indicating whether booleanValue returns the Boolean representation of the Value. /// - /// A Boolean representing the Value + /// A Boolean representing the Value. /// ----------------------------------------------------------------------------- protected bool BooleanValue { @@ -61,23 +52,23 @@ protected bool BooleanValue bool boolValue = Null.NullBoolean; try { - //Try and cast the value to an Boolean - boolValue = Convert.ToBoolean(Value); + // Try and cast the value to an Boolean + boolValue = Convert.ToBoolean(this.Value); } catch (Exception exc) { Logger.Error(exc); - } + return boolValue; } } /// ----------------------------------------------------------------------------- /// - /// OldBooleanValue returns the Boolean representation of the OldValue + /// Gets a value indicating whether oldBooleanValue returns the Boolean representation of the OldValue. /// - /// A Boolean representing the OldValue + /// A Boolean representing the OldValue. /// ----------------------------------------------------------------------------- protected bool OldBooleanValue { @@ -86,92 +77,89 @@ protected bool OldBooleanValue bool boolValue = Null.NullBoolean; try { - //Try and cast the value to an Boolean - boolValue = Convert.ToBoolean(OldValue); + // Try and cast the value to an Boolean + boolValue = Convert.ToBoolean(this.OldValue); } catch (Exception exc) { Logger.Error(exc); - } + return boolValue; } } /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets stringValue is the value of the control expressed as a String. /// - /// A string representing the Value + /// A string representing the Value. /// ----------------------------------------------------------------------------- protected override string StringValue { get { - return BooleanValue.ToString(); + return this.BooleanValue.ToString(); } + set { bool setValue = bool.Parse(value); - Value = setValue; + this.Value = setValue; } - } - - #endregion - - #region "Protected Methods" - + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = BooleanValue; - args.OldValue = OldBooleanValue; - args.StringValue = StringValue; - base.OnValueChanged(args); + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.BooleanValue; + args.OldValue = this.OldBooleanValue; + args.StringValue = this.StringValue; + this.OnValueChanged(args); } /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); - if ((BooleanValue)) + if (this.BooleanValue) { writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); } + writer.AddAttribute(HtmlTextWriterAttribute.Value, "True"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(Localization.GetString("True", Localization.SharedResourceFile)); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); - if ((!BooleanValue)) + if (!this.BooleanValue) { writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); } + writer.AddAttribute(HtmlTextWriterAttribute.Value, "False"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(Localization.GetString("False", Localization.SharedResourceFile)); writer.RenderEndTag(); - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs index d9591c1e4bf..3d3956fea8a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections.Specialized; + using System.Web.UI; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -24,24 +19,23 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:VersionEditControl runat=server>")] public class VersionEditControl : EditControl - { - #region "Public Properties" - + { /// ----------------------------------------------------------------------------- /// - /// StringValue is the value of the control expressed as a String + /// Gets or sets stringValue is the value of the control expressed as a String. /// - /// A string representing the Value + /// A string representing the Value. /// ----------------------------------------------------------------------------- protected override string StringValue { get { - return Value.ToString(); + return this.Value.ToString(); } + set { - Value = new Version(value); + this.Value = new Version(value); } } @@ -49,55 +43,68 @@ protected Version Version { get { - return Value as Version; + return this.Value as Version; } - } - - #endregion + } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + string majorVersion = postCollection[postDataKey + "_Major"]; + string minorVersion = postCollection[postDataKey + "_Minor"]; + string buildVersion = postCollection[postDataKey + "_Build"]; + bool dataChanged = false; + Version presentValue = this.Version; + var postedValue = new Version(majorVersion + "." + minorVersion + "." + buildVersion); + if (!postedValue.Equals(presentValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } + protected void RenderDropDownList(HtmlTextWriter writer, string type, int val) { - //Render the Select Tag + // Render the Select Tag writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID + "_" + type); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_" + type); writer.AddStyleAttribute("width", "60px"); writer.RenderBeginTag(HtmlTextWriterTag.Select); for (int i = 0; i <= 99; i++) { - //Add the Value Attribute + // Add the Value Attribute writer.AddAttribute(HtmlTextWriterAttribute.Value, i.ToString()); if (val == i) { - //Add the Selected Attribute + // Add the Selected Attribute writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } - - //Render Option Tag + + // Render Option Tag writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(i.ToString("00")); writer.RenderEndTag(); } - - //Close Select Tag - writer.RenderEndTag(); - } - - #region "Protected Methods" + // Close Select Tag + writer.RenderEndTag(); + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event + /// Event. /// /// ----------------------------------------------------------------------------- protected override void OnDataChanged(EventArgs e) { - var args = new PropertyEditorEventArgs(Name); - args.Value = Value; - args.OldValue = OldValue; - args.StringValue = StringValue; + var args = new PropertyEditorEventArgs(this.Name); + args.Value = this.Value; + args.OldValue = this.OldValue; + args.StringValue = this.StringValue; - base.OnValueChanged(args); + this.OnValueChanged(args); } /// ----------------------------------------------------------------------------- @@ -110,74 +117,57 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (Page != null && EditMode == PropertyEditorMode.Edit) + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) { - Page.RegisterRequiresPostBack(this); + this.Page.RegisterRequiresPostBack(this); } } /// ----------------------------------------------------------------------------- /// - /// RenderEditMode renders the Edit mode of the control + /// RenderEditMode renders the Edit mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderEditMode(HtmlTextWriter writer) { - //Render a containing span Tag - ControlStyle.AddAttributesToRender(writer); + // Render a containing span Tag + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); - //Render Major - RenderDropDownList(writer, "Major", Version.Major); + // Render Major + this.RenderDropDownList(writer, "Major", this.Version.Major); writer.Write(" "); - //Render Minor - RenderDropDownList(writer, "Minor", Version.Minor); + // Render Minor + this.RenderDropDownList(writer, "Minor", this.Version.Minor); writer.Write(" "); - //Render Build - RenderDropDownList(writer, "Build", Version.Build); + // Render Build + this.RenderDropDownList(writer, "Build", this.Version.Build); - //Close Select Tag + // Close Select Tag writer.RenderEndTag(); } /// ----------------------------------------------------------------------------- /// - /// RenderViewMode renders the View (readonly) mode of the control + /// RenderViewMode renders the View (readonly) mode of the control. /// /// A HtmlTextWriter. /// ----------------------------------------------------------------------------- protected override void RenderViewMode(HtmlTextWriter writer) { - ControlStyle.AddAttributesToRender(writer); + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); - if (Version != null) + if (this.Version != null) { - writer.Write(Version.ToString(3)); + writer.Write(this.Version.ToString(3)); } + writer.RenderEndTag(); } - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - string majorVersion = postCollection[postDataKey + "_Major"]; - string minorVersion = postCollection[postDataKey + "_Minor"]; - string buildVersion = postCollection[postDataKey + "_Build"]; - bool dataChanged = false; - Version presentValue = Version; - var postedValue = new Version(majorVersion + "." + minorVersion + "." + buildVersion); - if (!postedValue.Equals(presentValue)) - { - Value = postedValue; - dataChanged = true; - } - return dataChanged; - } - - #endregion } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs index 94da5def3bf..246f6904a72 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Profile; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: EditorInfo /// ----------------------------------------------------------------------------- /// - /// The EditorInfo class provides a helper class for the Property Editor + /// The EditorInfo class provides a helper class for the Property Editor. /// /// /// @@ -31,7 +26,7 @@ public class EditorInfo { public EditorInfo() { - Visible = true; + this.Visible = true; } public object[] Attributes { get; set; } @@ -67,9 +62,10 @@ public EditorInfo() /// ----------------------------------------------------------------------------- /// /// GetEditor gets the appropriate Editor based on ID - /// properties + /// properties. /// - /// The Id of the Editor + /// The Id of the Editor. + /// /// ----------------------------------------------------------------------------- public static string GetEditor(int editorType) { @@ -83,6 +79,7 @@ public static string GetEditor(int editorType) editor = definitionEntry.TextNonLocalized; } } + return editor; } @@ -95,6 +92,7 @@ public static string GetEditor(string editorValue) { editor = definitionEntry.TextNonLocalized; } + return editor; } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs index 067de18aa51..61743aa8ddc 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { public delegate void EditorCreatedEventHandler(object sender, PropertyEditorItemEventArgs e); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs index 22a36c2798e..2269708549c 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { public delegate void PropertyChangedEventHandler(object sender, PropertyEditorEventArgs e); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs index 312849eca24..6147bf73b25 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -23,85 +18,88 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class PropertyEditorEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new PropertyEditorEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new PropertyEditorEventArgs. /// - /// The name of the property + /// The name of the property. /// ----------------------------------------------------------------------------- - public PropertyEditorEventArgs(string name) : this(name, null, null) + public PropertyEditorEventArgs(string name) + : this(name, null, null) { - } - + } + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new PropertyEditorEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new PropertyEditorEventArgs. /// - /// The name of the property - /// The new value of the property - /// The old value of the property + /// The name of the property. + /// The new value of the property. + /// The old value of the property. /// ----------------------------------------------------------------------------- public PropertyEditorEventArgs(string name, object newValue, object oldValue) { - Name = name; - Value = newValue; - OldValue = oldValue; + this.Name = name; + this.Value = newValue; + this.OldValue = oldValue; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the proeprty has changed + /// Gets or sets a value indicating whether gets and sets whether the proeprty has changed. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public bool Changed { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Index of the Item + /// Gets or sets and sets the Index of the Item. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int Index { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Key of the Item + /// Gets or sets and sets the Key of the Item. /// - /// An Object + /// An Object. /// ----------------------------------------------------------------------------- public object Key { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Name of the Property being changed + /// Gets or sets and sets the Name of the Property being changed. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string Name { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the OldValue of the Property being changed + /// Gets or sets and sets the OldValue of the Property being changed. /// - /// An Object + /// An Object. /// ----------------------------------------------------------------------------- public object OldValue { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the String Value of the Property being changed + /// Gets or sets and sets the String Value of the Property being changed. /// - /// An Object + /// An Object. /// ----------------------------------------------------------------------------- public string StringValue { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Value of the Property being changed + /// Gets or sets and sets the Value of the Property being changed. /// - /// An Object + /// An Object. /// ----------------------------------------------------------------------------- public object Value { get; set; } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs index fbc89b0adbe..a78c185ba5b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -17,29 +12,30 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The PropertyEditorItemEventArgs class is a cusom EventArgs class for - /// handling Event Args + /// handling Event Args. /// /// /// /// ----------------------------------------------------------------------------- public class PropertyEditorItemEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new PropertyEditorItemEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new PropertyEditorItemEventArgs. /// - /// The editor created + /// The editor created. /// ----------------------------------------------------------------------------- public PropertyEditorItemEventArgs(EditorInfo editor) { - Editor = editor; + this.Editor = editor; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the proeprty has changed + /// Gets or sets and sets whether the proeprty has changed. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public EditorInfo Editor { get; set; } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs index eaed25884b3..a219e91e3bc 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs @@ -1,878 +1,889 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - public enum EditorDisplayMode - { - Div, - Table - } - - public enum HelpDisplayMode - { - Never, - EditOnly, - Always - } - - /// ----------------------------------------------------------------------------- - /// Project: DotNetNuke - /// Namespace: DotNetNuke.UI.WebControls - /// Class: FieldEditorControl - /// ----------------------------------------------------------------------------- - /// - /// The FieldEditorControl control provides a Control to display Profile - /// Properties. - /// - /// - /// - /// ----------------------------------------------------------------------------- - [ToolboxData("<{0}:FieldEditorControl runat=server>")] - public class FieldEditorControl : WebControl, INamingContainer - { - #region Private Members - - private readonly List Validators = new List(); - private IEditorInfoAdapter _EditorInfoAdapter; - private bool _IsValid = true; - private StandardEditorInfoAdapter _StdAdapter; - private bool _Validated; - - #endregion - - #region Constructors - - public FieldEditorControl() - { - ValidationExpression = Null.NullString; - ShowRequired = true; - LabelMode = LabelMode.None; - EditorTypeName = Null.NullString; - EditorDisplayMode = EditorDisplayMode.Div; - HelpDisplayMode = HelpDisplayMode.Always; - VisibilityStyle = new Style(); - LabelStyle = new Style(); - HelpStyle = new Style(); - EditControlStyle = new Style(); - ErrorStyle = new Style(); - ViewStateMode = ViewStateMode.Disabled; - } - - #endregion - - #region Protected Properties - - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - - #endregion - - #region Public Properties - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the DataSource that is bound to this control - /// - /// The DataSource object - /// ----------------------------------------------------------------------------- - [Browsable(false)] - public object DataSource { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the value of the Field/property that this control displays - /// - /// A string representing the Name of the Field - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the Control.")] - public string DataField { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether the control uses Divs or Tables - /// - /// An EditorDisplayMode enum - /// ----------------------------------------------------------------------------- - public EditorDisplayMode EditorDisplayMode { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Edit Mode of the Editor - /// - /// The mode of the editor - /// ----------------------------------------------------------------------------- - public PropertyEditorMode EditMode { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Edit Control associated with the Editor - /// - /// ----------------------------------------------------------------------------- - public EditControl Editor { get; private set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Factory used to create the Control - /// - /// The mode of the editor - /// ----------------------------------------------------------------------------- - public IEditorInfoAdapter EditorInfoAdapter - { - get - { - if (_EditorInfoAdapter == null) - { - if (_StdAdapter == null) - { - _StdAdapter = new StandardEditorInfoAdapter(DataSource, DataField); - } - return _StdAdapter; - } - else - { - return _EditorInfoAdapter; - } - } - set - { - _EditorInfoAdapter = value; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Editor Type to use - /// - /// The typename of the editor - /// ----------------------------------------------------------------------------- - - public string EditorTypeName { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets a flag indicating whether the Validators should use client-side - /// validation - /// - /// A Boolean - /// ----------------------------------------------------------------------------- - public bool EnableClientValidation { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether the control displays Help - /// - /// A HelpDisplayMode enum - /// ----------------------------------------------------------------------------- - public HelpDisplayMode HelpDisplayMode { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets whether any of the properties have been changed - /// - /// A Boolean - /// ----------------------------------------------------------------------------- - public bool IsDirty { get; private set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets whether all of the properties are Valid - /// - /// A Boolean - /// ----------------------------------------------------------------------------- - public bool IsValid - { - get - { - if (!_Validated) - { - Validate(); - } - return _IsValid; - } - } - - public LabelMode LabelMode { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Local Resource File for the Control - /// - /// A String - /// ----------------------------------------------------------------------------- - public string LocalResourceFile { get; set; } - - public bool Required { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Url of the Required Image - /// - /// A String - /// ----------------------------------------------------------------------------- - public string RequiredUrl { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// gets and sets whether the Required icon is used - /// - /// ----------------------------------------------------------------------------- - public bool ShowRequired { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// gets and sets whether the Visibility control is used - /// - /// ----------------------------------------------------------------------------- - public bool ShowVisibility { get; set; } + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + + public enum EditorDisplayMode + { + Div, + Table, + } + + public enum HelpDisplayMode + { + Never, + EditOnly, + Always, + } + + /// ----------------------------------------------------------------------------- + /// Project: DotNetNuke + /// Namespace: DotNetNuke.UI.WebControls + /// Class: FieldEditorControl + /// ----------------------------------------------------------------------------- + /// + /// The FieldEditorControl control provides a Control to display Profile + /// Properties. + /// + /// + /// + /// ----------------------------------------------------------------------------- + [ToolboxData("<{0}:FieldEditorControl runat=server>")] + public class FieldEditorControl : WebControl, INamingContainer + { + private readonly List Validators = new List(); + private IEditorInfoAdapter _EditorInfoAdapter; + private bool _IsValid = true; + private StandardEditorInfoAdapter _StdAdapter; + private bool _Validated; + + public FieldEditorControl() + { + this.ValidationExpression = Null.NullString; + this.ShowRequired = true; + this.LabelMode = LabelMode.None; + this.EditorTypeName = Null.NullString; + this.EditorDisplayMode = EditorDisplayMode.Div; + this.HelpDisplayMode = HelpDisplayMode.Always; + this.VisibilityStyle = new Style(); + this.LabelStyle = new Style(); + this.HelpStyle = new Style(); + this.EditControlStyle = new Style(); + this.ErrorStyle = new Style(); + this.ViewStateMode = ViewStateMode.Disabled; + } + + public event PropertyChangedEventHandler ItemAdded; + + public event PropertyChangedEventHandler ItemChanged; + + public event EditorCreatedEventHandler ItemCreated; + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the DataSource that is bound to this control. + /// + /// The DataSource object. + /// ----------------------------------------------------------------------------- + [Browsable(false)] + public object DataSource { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the value of the Field/property that this control displays. + /// + /// A string representing the Name of the Field. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the Control.")] + public string DataField { get; set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets whether the control uses Divs or Tables. + /// + /// An EditorDisplayMode enum. + /// ----------------------------------------------------------------------------- + public EditorDisplayMode EditorDisplayMode { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Edit Mode of the Editor. + /// + /// The mode of the editor. + /// ----------------------------------------------------------------------------- + public PropertyEditorMode EditMode { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Edit Control associated with the Editor. + /// + /// ----------------------------------------------------------------------------- + public EditControl Editor { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Factory used to create the Control. + /// + /// The mode of the editor. + /// ----------------------------------------------------------------------------- + public IEditorInfoAdapter EditorInfoAdapter + { + get + { + if (this._EditorInfoAdapter == null) + { + if (this._StdAdapter == null) + { + this._StdAdapter = new StandardEditorInfoAdapter(this.DataSource, this.DataField); + } + + return this._StdAdapter; + } + else + { + return this._EditorInfoAdapter; + } + } + + set + { + this._EditorInfoAdapter = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Editor Type to use. + /// + /// The typename of the editor. + /// ----------------------------------------------------------------------------- + public string EditorTypeName { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets a flag indicating whether the Validators should use client-side + /// validation. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public bool EnableClientValidation { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets whether the control displays Help. + /// + /// A HelpDisplayMode enum. + /// ----------------------------------------------------------------------------- + public HelpDisplayMode HelpDisplayMode { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether any of the properties have been changed. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public bool IsDirty { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether all of the properties are Valid. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public bool IsValid + { + get + { + if (!this._Validated) + { + this.Validate(); + } + + return this._IsValid; + } + } + + public LabelMode LabelMode { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Local Resource File for the Control. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string LocalResourceFile { get; set; } + + public bool Required { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Url of the Required Image. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string RequiredUrl { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the Required icon is used. + /// + /// ----------------------------------------------------------------------------- + public bool ShowRequired { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the Visibility control is used. + /// + /// ----------------------------------------------------------------------------- + public bool ShowVisibility { get; set; } public UserInfo User { get; set; } - public string ValidationExpression { get; set; } - - #region Style Properties - - /// ----------------------------------------------------------------------------- - /// - /// Gets the value of the Field Style - /// - /// A Style object - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Edit Control.")] - public Style EditControlStyle { get; private set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the width of the Edit Control Column - /// - /// A Style object - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Appearance"), Description("Set the Width for the Edit Control.")] - public Unit EditControlWidth { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the value of the Error Style - /// - /// A Style object - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Error Text.")] - public Style ErrorStyle { get; private set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the value of the Label Style - /// - /// A Style object - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Help Text.")] - public Style HelpStyle { get; private set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the value of the Label Style - /// - /// A Style object - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Label Text")] - public Style LabelStyle { get; private set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the width of the Label Column - /// - /// A Style object - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Appearance"), Description("Set the Width for the Label Control.")] - public Unit LabelWidth { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the value of the Visibility Style - /// - /// A Style object - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), TypeConverter(typeof (ExpandableObjectConverter)), Description("Set the Style for the Visibility Control")] - public Style VisibilityStyle { get; private set; } - - #endregion - - #endregion - - #region Events - - public event PropertyChangedEventHandler ItemAdded; - public event PropertyChangedEventHandler ItemChanged; - public event EditorCreatedEventHandler ItemCreated; - public event PropertyChangedEventHandler ItemDeleted; - - #endregion - - #region Private Methods - - /// - /// BuildDiv creates the Control as a Div - /// - /// The EditorInfo object for this control - private void BuildDiv(EditorInfo editInfo) - { - var propLabel = new PropertyLabelControl(); + public string ValidationExpression { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the value of the Field Style. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Edit Control.")] + public Style EditControlStyle { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the width of the Edit Control Column. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Appearance")] + [Description("Set the Width for the Edit Control.")] + public Unit EditControlWidth { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the value of the Error Style. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Error Text.")] + public Style ErrorStyle { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the value of the Label Style. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Help Text.")] + public Style HelpStyle { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the value of the Label Style. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Label Text")] + public Style LabelStyle { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the width of the Label Column. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Appearance")] + [Description("Set the Width for the Label Control.")] + public Unit LabelWidth { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the value of the Visibility Style. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Visibility Control")] + public Style VisibilityStyle { get; private set; } + + public event PropertyChangedEventHandler ItemDeleted; + + /// ----------------------------------------------------------------------------- + /// + /// Binds the controls to the DataSource. + /// + /// ----------------------------------------------------------------------------- + public override void DataBind() + { + // Invoke OnDataBinding so DataBinding Event is raised + this.OnDataBinding(EventArgs.Empty); + + // Clear Existing Controls + this.Controls.Clear(); + + // Clear Child View State as controls will be loaded from DataSource + this.ClearChildViewState(); + + // Start Tracking ViewState + this.TrackViewState(); + + // Create the editor + this.CreateEditor(); + + // Set flag so CreateChildConrols should not be invoked later in control's lifecycle + this.ChildControlsCreated = true; + } + + /// ----------------------------------------------------------------------------- + /// + /// Validates the data, and sets the IsValid Property. + /// + /// ----------------------------------------------------------------------------- + public virtual void Validate() + { + this._IsValid = this.Editor.IsValid; + + if (this._IsValid) + { + IEnumerator valEnumerator = this.Validators.GetEnumerator(); + while (valEnumerator.MoveNext()) + { + var validator = (IValidator)valEnumerator.Current; + validator.Validate(); + if (!validator.IsValid) + { + this._IsValid = false; + break; + } + } + + this._Validated = true; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// CreateEditor creates the control collection for this control. + /// + /// ----------------------------------------------------------------------------- + protected virtual void CreateEditor() + { + EditorInfo editInfo = this.EditorInfoAdapter.CreateEditControl(); + + this.ID = editInfo.Name; + + if (editInfo != null) + { + editInfo.User = this.User; + + if (editInfo.EditMode == PropertyEditorMode.Edit) + { + editInfo.EditMode = this.EditMode; + } + + // Get the Editor Type to use (if specified) + if (!string.IsNullOrEmpty(this.EditorTypeName)) + { + editInfo.Editor = this.EditorTypeName; + } + + // Get the Label Mode to use (if specified) + if (this.LabelMode != LabelMode.Left) + { + editInfo.LabelMode = this.LabelMode; + } + + // if Required is specified set editors property + if (this.Required) + { + editInfo.Required = this.Required; + } + + // Get the ValidationExpression to use (if specified) + if (!string.IsNullOrEmpty(this.ValidationExpression)) + { + editInfo.ValidationExpression = this.ValidationExpression; + } + + // Raise the ItemCreated Event + this.OnItemCreated(new PropertyEditorItemEventArgs(editInfo)); + + this.Visible = editInfo.Visible; + + if (this.EditorDisplayMode == EditorDisplayMode.Div) + { + this.BuildDiv(editInfo); + } + else + { + this.BuildTable(editInfo); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is added to a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void CollectionItemAdded(object sender, PropertyEditorEventArgs e) + { + this.OnItemAdded(e); + } + + /// + /// BuildDiv creates the Control as a Div. + /// + /// The EditorInfo object for this control. + private void BuildDiv(EditorInfo editInfo) + { + var propLabel = new PropertyLabelControl(); propLabel.ViewStateMode = ViewStateMode.Disabled; - var propEditor = BuildEditor(editInfo); - var visibility = BuildVisibility(editInfo); + var propEditor = this.BuildEditor(editInfo); + var visibility = this.BuildVisibility(editInfo); - if (editInfo.LabelMode != LabelMode.None) - { - propLabel = BuildLabel(editInfo); - propLabel.EditControl = propEditor; - } + if (editInfo.LabelMode != LabelMode.None) + { + propLabel = this.BuildLabel(editInfo); + propLabel.EditControl = propEditor; + } - var strValue = editInfo.Value as string; - if (ShowRequired && editInfo.Required && (editInfo.EditMode == PropertyEditorMode.Edit || (editInfo.Required && string.IsNullOrEmpty(strValue)))) - { + var strValue = editInfo.Value as string; + if (this.ShowRequired && editInfo.Required && (editInfo.EditMode == PropertyEditorMode.Edit || (editInfo.Required && string.IsNullOrEmpty(strValue)))) + { propLabel.Required = true; - } - - if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Top) - { - Controls.Add(propLabel); - Controls.Add(propEditor); - if (visibility != null) - { - Controls.Add(visibility); - } - } - else - { - Controls.Add(propEditor); - if (visibility != null) - { - Controls.Add(visibility); - } - if ((propLabel != null)) - { - Controls.Add(propLabel); - } - } - - //Build the Validators - BuildValidators(editInfo, propEditor.ID); - if (Validators.Count > 0) - { - //Add the Validators to the editor cell - foreach (BaseValidator validator in Validators) - { - validator.Width = Width; - Controls.Add(validator); - } - } - } - - /// - /// BuildEditor creates the editor part of the Control - /// - /// The EditorInfo object for this control - private EditControl BuildEditor(EditorInfo editInfo) - { - EditControl propEditor = EditControlFactory.CreateEditControl(editInfo); + } + + if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Top) + { + this.Controls.Add(propLabel); + this.Controls.Add(propEditor); + if (visibility != null) + { + this.Controls.Add(visibility); + } + } + else + { + this.Controls.Add(propEditor); + if (visibility != null) + { + this.Controls.Add(visibility); + } + + if (propLabel != null) + { + this.Controls.Add(propLabel); + } + } + + // Build the Validators + this.BuildValidators(editInfo, propEditor.ID); + if (this.Validators.Count > 0) + { + // Add the Validators to the editor cell + foreach (BaseValidator validator in this.Validators) + { + validator.Width = this.Width; + this.Controls.Add(validator); + } + } + } + + /// + /// BuildEditor creates the editor part of the Control. + /// + /// The EditorInfo object for this control. + private EditControl BuildEditor(EditorInfo editInfo) + { + EditControl propEditor = EditControlFactory.CreateEditControl(editInfo); propEditor.ViewStateMode = ViewStateMode.Enabled; - propEditor.ControlStyle.CopyFrom(EditControlStyle); - propEditor.LocalResourceFile = LocalResourceFile; - propEditor.User = User; - if (editInfo.ControlStyle != null) - { - propEditor.ControlStyle.CopyFrom(editInfo.ControlStyle); - } - propEditor.ItemAdded += CollectionItemAdded; - propEditor.ItemDeleted += CollectionItemDeleted; - propEditor.ValueChanged += ValueChanged; - if (propEditor is DNNListEditControl) - { - var listEditor = (DNNListEditControl) propEditor; - listEditor.ItemChanged += ListItemChanged; - } - Editor = propEditor; - - return propEditor; - } - - /// - /// BuildLabel creates the label part of the Control - /// - /// The EditorInfo object for this control - private PropertyLabelControl BuildLabel(EditorInfo editInfo) - { - var propLabel = new PropertyLabelControl {ID = editInfo.Name + "_Label"}; - propLabel.HelpStyle.CopyFrom(HelpStyle); - propLabel.LabelStyle.CopyFrom(LabelStyle); - var strValue = editInfo.Value as string; - switch (HelpDisplayMode) - { - case HelpDisplayMode.Always: - propLabel.ShowHelp = true; - break; - case HelpDisplayMode.EditOnly: - if (editInfo.EditMode == PropertyEditorMode.Edit || (editInfo.Required && string.IsNullOrEmpty(strValue))) - { - propLabel.ShowHelp = true; - } - else - { - propLabel.ShowHelp = false; - } - break; - case HelpDisplayMode.Never: - propLabel.ShowHelp = false; - break; - } - propLabel.Caption = editInfo.Name; - propLabel.HelpText = editInfo.Name; - propLabel.ResourceKey = editInfo.ResourceKey; - if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Right) - { - propLabel.Width = LabelWidth; - } - return propLabel; - } - - /// - /// BuildValidators creates the validators part of the Control - /// - /// The EditorInfo object for this control - private Image BuildRequiredIcon(EditorInfo editInfo) - { - Image img = null; - var strValue = editInfo.Value as string; - if (ShowRequired && editInfo.Required && (editInfo.EditMode == PropertyEditorMode.Edit || (editInfo.Required && string.IsNullOrEmpty(strValue)))) - { - img = new Image(); - if (String.IsNullOrEmpty(RequiredUrl) || RequiredUrl == Null.NullString) - { - img.ImageUrl = "~/images/required.gif"; - } - else - { - img.ImageUrl = RequiredUrl; - } - img.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Required"); - } - return img; - } - - /// ----------------------------------------------------------------------------- - /// - /// BuildTable creates the Control as a Table - /// - /// The EditorInfo object for this control - /// ----------------------------------------------------------------------------- - private void BuildTable(EditorInfo editInfo) - { - var tbl = new Table(); - var labelCell = new TableCell(); - var editorCell = new TableCell(); - - //Build Label Cell - labelCell.VerticalAlign = VerticalAlign.Top; - labelCell.Controls.Add(BuildLabel(editInfo)); - if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Right) - { - labelCell.Width = LabelWidth; - } - //Build Editor Cell - editorCell.VerticalAlign = VerticalAlign.Top; - EditControl propEditor = BuildEditor(editInfo); - Image requiredIcon = BuildRequiredIcon(editInfo); - editorCell.Controls.Add(propEditor); - if (requiredIcon != null) - { - editorCell.Controls.Add(requiredIcon); - } - if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Right) - { - editorCell.Width = EditControlWidth; - } - VisibilityControl visibility = BuildVisibility(editInfo); - if (visibility != null) - { - editorCell.Controls.Add(new LiteralControl("  ")); - editorCell.Controls.Add(visibility); - } - - //Add cells to table - var editorRow = new TableRow(); - var labelRow = new TableRow(); - if (editInfo.LabelMode == LabelMode.Bottom || editInfo.LabelMode == LabelMode.Top || editInfo.LabelMode == LabelMode.None) - { - editorCell.ColumnSpan = 2; - editorRow.Cells.Add(editorCell); - if (editInfo.LabelMode == LabelMode.Bottom || editInfo.LabelMode == LabelMode.Top) - { - labelCell.ColumnSpan = 2; - labelRow.Cells.Add(labelCell); - } - if (editInfo.LabelMode == LabelMode.Top) - { - tbl.Rows.Add(labelRow); - } - tbl.Rows.Add(editorRow); - if (editInfo.LabelMode == LabelMode.Bottom) - { - tbl.Rows.Add(labelRow); - } - } - else if (editInfo.LabelMode == LabelMode.Left) - { - editorRow.Cells.Add(labelCell); - editorRow.Cells.Add(editorCell); - tbl.Rows.Add(editorRow); - } - else if (editInfo.LabelMode == LabelMode.Right) - { - editorRow.Cells.Add(editorCell); - editorRow.Cells.Add(labelCell); - tbl.Rows.Add(editorRow); - } - - //Build the Validators - BuildValidators(editInfo, propEditor.ID); - - var validatorsRow = new TableRow(); - var validatorsCell = new TableCell(); - validatorsCell.ColumnSpan = 2; - //Add the Validators to the editor cell - foreach (BaseValidator validator in Validators) - { - validatorsCell.Controls.Add(validator); - } - validatorsRow.Cells.Add(validatorsCell); - tbl.Rows.Add(validatorsRow); - - //Add the Table to the Controls Collection - Controls.Add(tbl); - } - - /// ----------------------------------------------------------------------------- - /// - /// BuildValidators creates the validators part of the Control - /// - /// The EditorInfo object for this control - /// Target Control Id. - /// ----------------------------------------------------------------------------- - private void BuildValidators(EditorInfo editInfo, string targetId) - { - Validators.Clear(); - - //Add Required Validators - if (editInfo.Required) - { - var reqValidator = new RequiredFieldValidator(); - reqValidator.ID = editInfo.Name + "_Req"; - reqValidator.ControlToValidate = targetId; - reqValidator.Display = ValidatorDisplay.Dynamic; - reqValidator.ControlStyle.CopyFrom(ErrorStyle); - if(String.IsNullOrEmpty(reqValidator.CssClass)) - { - reqValidator.CssClass = "dnnFormMessage dnnFormError"; - } - reqValidator.EnableClientScript = EnableClientValidation; - reqValidator.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Required"); - reqValidator.ErrorMessage = editInfo.Name + " is Required"; - Validators.Add(reqValidator); - } - - //Add Regular Expression Validators - if (!String.IsNullOrEmpty(editInfo.ValidationExpression)) - { - var regExValidator = new RegularExpressionValidator(); - regExValidator.ID = editInfo.Name + "_RegEx"; - regExValidator.ControlToValidate = targetId; - regExValidator.ValidationExpression = editInfo.ValidationExpression; - regExValidator.Display = ValidatorDisplay.Dynamic; - regExValidator.ControlStyle.CopyFrom(ErrorStyle); - if(String.IsNullOrEmpty(regExValidator.CssClass)) - { + propEditor.ControlStyle.CopyFrom(this.EditControlStyle); + propEditor.LocalResourceFile = this.LocalResourceFile; + propEditor.User = this.User; + if (editInfo.ControlStyle != null) + { + propEditor.ControlStyle.CopyFrom(editInfo.ControlStyle); + } + + propEditor.ItemAdded += this.CollectionItemAdded; + propEditor.ItemDeleted += this.CollectionItemDeleted; + propEditor.ValueChanged += this.ValueChanged; + if (propEditor is DNNListEditControl) + { + var listEditor = (DNNListEditControl)propEditor; + listEditor.ItemChanged += this.ListItemChanged; + } + + this.Editor = propEditor; + + return propEditor; + } + + /// + /// BuildLabel creates the label part of the Control. + /// + /// The EditorInfo object for this control. + private PropertyLabelControl BuildLabel(EditorInfo editInfo) + { + var propLabel = new PropertyLabelControl { ID = editInfo.Name + "_Label" }; + propLabel.HelpStyle.CopyFrom(this.HelpStyle); + propLabel.LabelStyle.CopyFrom(this.LabelStyle); + var strValue = editInfo.Value as string; + switch (this.HelpDisplayMode) + { + case HelpDisplayMode.Always: + propLabel.ShowHelp = true; + break; + case HelpDisplayMode.EditOnly: + if (editInfo.EditMode == PropertyEditorMode.Edit || (editInfo.Required && string.IsNullOrEmpty(strValue))) + { + propLabel.ShowHelp = true; + } + else + { + propLabel.ShowHelp = false; + } + + break; + case HelpDisplayMode.Never: + propLabel.ShowHelp = false; + break; + } + + propLabel.Caption = editInfo.Name; + propLabel.HelpText = editInfo.Name; + propLabel.ResourceKey = editInfo.ResourceKey; + if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Right) + { + propLabel.Width = this.LabelWidth; + } + + return propLabel; + } + + /// + /// BuildValidators creates the validators part of the Control. + /// + /// The EditorInfo object for this control. + private Image BuildRequiredIcon(EditorInfo editInfo) + { + Image img = null; + var strValue = editInfo.Value as string; + if (this.ShowRequired && editInfo.Required && (editInfo.EditMode == PropertyEditorMode.Edit || (editInfo.Required && string.IsNullOrEmpty(strValue)))) + { + img = new Image(); + if (string.IsNullOrEmpty(this.RequiredUrl) || this.RequiredUrl == Null.NullString) + { + img.ImageUrl = "~/images/required.gif"; + } + else + { + img.ImageUrl = this.RequiredUrl; + } + + img.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Required"); + } + + return img; + } + + /// ----------------------------------------------------------------------------- + /// + /// BuildTable creates the Control as a Table. + /// + /// The EditorInfo object for this control. + /// ----------------------------------------------------------------------------- + private void BuildTable(EditorInfo editInfo) + { + var tbl = new Table(); + var labelCell = new TableCell(); + var editorCell = new TableCell(); + + // Build Label Cell + labelCell.VerticalAlign = VerticalAlign.Top; + labelCell.Controls.Add(this.BuildLabel(editInfo)); + if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Right) + { + labelCell.Width = this.LabelWidth; + } + + // Build Editor Cell + editorCell.VerticalAlign = VerticalAlign.Top; + EditControl propEditor = this.BuildEditor(editInfo); + Image requiredIcon = this.BuildRequiredIcon(editInfo); + editorCell.Controls.Add(propEditor); + if (requiredIcon != null) + { + editorCell.Controls.Add(requiredIcon); + } + + if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Right) + { + editorCell.Width = this.EditControlWidth; + } + + VisibilityControl visibility = this.BuildVisibility(editInfo); + if (visibility != null) + { + editorCell.Controls.Add(new LiteralControl("  ")); + editorCell.Controls.Add(visibility); + } + + // Add cells to table + var editorRow = new TableRow(); + var labelRow = new TableRow(); + if (editInfo.LabelMode == LabelMode.Bottom || editInfo.LabelMode == LabelMode.Top || editInfo.LabelMode == LabelMode.None) + { + editorCell.ColumnSpan = 2; + editorRow.Cells.Add(editorCell); + if (editInfo.LabelMode == LabelMode.Bottom || editInfo.LabelMode == LabelMode.Top) + { + labelCell.ColumnSpan = 2; + labelRow.Cells.Add(labelCell); + } + + if (editInfo.LabelMode == LabelMode.Top) + { + tbl.Rows.Add(labelRow); + } + + tbl.Rows.Add(editorRow); + if (editInfo.LabelMode == LabelMode.Bottom) + { + tbl.Rows.Add(labelRow); + } + } + else if (editInfo.LabelMode == LabelMode.Left) + { + editorRow.Cells.Add(labelCell); + editorRow.Cells.Add(editorCell); + tbl.Rows.Add(editorRow); + } + else if (editInfo.LabelMode == LabelMode.Right) + { + editorRow.Cells.Add(editorCell); + editorRow.Cells.Add(labelCell); + tbl.Rows.Add(editorRow); + } + + // Build the Validators + this.BuildValidators(editInfo, propEditor.ID); + + var validatorsRow = new TableRow(); + var validatorsCell = new TableCell(); + validatorsCell.ColumnSpan = 2; + + // Add the Validators to the editor cell + foreach (BaseValidator validator in this.Validators) + { + validatorsCell.Controls.Add(validator); + } + + validatorsRow.Cells.Add(validatorsCell); + tbl.Rows.Add(validatorsRow); + + // Add the Table to the Controls Collection + this.Controls.Add(tbl); + } + + /// ----------------------------------------------------------------------------- + /// + /// BuildValidators creates the validators part of the Control. + /// + /// The EditorInfo object for this control. + /// Target Control Id. + /// ----------------------------------------------------------------------------- + private void BuildValidators(EditorInfo editInfo, string targetId) + { + this.Validators.Clear(); + + // Add Required Validators + if (editInfo.Required) + { + var reqValidator = new RequiredFieldValidator(); + reqValidator.ID = editInfo.Name + "_Req"; + reqValidator.ControlToValidate = targetId; + reqValidator.Display = ValidatorDisplay.Dynamic; + reqValidator.ControlStyle.CopyFrom(this.ErrorStyle); + if (string.IsNullOrEmpty(reqValidator.CssClass)) + { + reqValidator.CssClass = "dnnFormMessage dnnFormError"; + } + + reqValidator.EnableClientScript = this.EnableClientValidation; + reqValidator.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Required"); + reqValidator.ErrorMessage = editInfo.Name + " is Required"; + this.Validators.Add(reqValidator); + } + + // Add Regular Expression Validators + if (!string.IsNullOrEmpty(editInfo.ValidationExpression)) + { + var regExValidator = new RegularExpressionValidator(); + regExValidator.ID = editInfo.Name + "_RegEx"; + regExValidator.ControlToValidate = targetId; + regExValidator.ValidationExpression = editInfo.ValidationExpression; + regExValidator.Display = ValidatorDisplay.Dynamic; + regExValidator.ControlStyle.CopyFrom(this.ErrorStyle); + if (string.IsNullOrEmpty(regExValidator.CssClass)) + { regExValidator.CssClass = "dnnFormMessage dnnFormError"; - } - regExValidator.EnableClientScript = EnableClientValidation; - regExValidator.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Validation"); - regExValidator.ErrorMessage = editInfo.Name + " is Invalid"; - Validators.Add(regExValidator); - } - } - - /// - /// BuildVisibility creates the visibility part of the Control - /// - /// The EditorInfo object for this control - private VisibilityControl BuildVisibility(EditorInfo editInfo) - { - VisibilityControl visControl = null; - - if (ShowVisibility) - { - visControl = new VisibilityControl - { - ID = "_visibility", - Name = editInfo.Name, - User = User, - Value = editInfo.ProfileVisibility - }; - visControl.ControlStyle.CopyFrom(VisibilityStyle); - visControl.VisibilityChanged += VisibilityChanged; - } - return visControl; - } - - #endregion - - #region Protected Methods - - /// ----------------------------------------------------------------------------- - /// - /// CreateEditor creates the control collection for this control - /// - /// ----------------------------------------------------------------------------- - protected virtual void CreateEditor() - { - EditorInfo editInfo = EditorInfoAdapter.CreateEditControl(); - - ID = editInfo.Name; - - if (editInfo != null) - { - editInfo.User = User; - - if (editInfo.EditMode == PropertyEditorMode.Edit) - { - editInfo.EditMode = EditMode; - } - - //Get the Editor Type to use (if specified) - if (!string.IsNullOrEmpty(EditorTypeName)) - { - editInfo.Editor = EditorTypeName; - } - - //Get the Label Mode to use (if specified) - if (LabelMode != LabelMode.Left) - { - editInfo.LabelMode = LabelMode; - } - - //if Required is specified set editors property - if (Required) - { - editInfo.Required = Required; - } - - //Get the ValidationExpression to use (if specified) - if (!string.IsNullOrEmpty(ValidationExpression)) - { - editInfo.ValidationExpression = ValidationExpression; - } - - //Raise the ItemCreated Event - OnItemCreated(new PropertyEditorItemEventArgs(editInfo)); - - Visible = editInfo.Visible; - - if (EditorDisplayMode == EditorDisplayMode.Div) - { - BuildDiv(editInfo); - } - else - { - BuildTable(editInfo); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is added to a collection type property - /// - /// ----------------------------------------------------------------------------- - protected virtual void CollectionItemAdded(object sender, PropertyEditorEventArgs e) - { - OnItemAdded(e); - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is removed from a collection type property - /// - /// ----------------------------------------------------------------------------- - protected virtual void CollectionItemDeleted(object sender, PropertyEditorEventArgs e) - { - OnItemDeleted(e); - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is added to a collection type property - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnItemAdded(PropertyEditorEventArgs e) - { - if (ItemAdded != null) - { - ItemAdded(this, e); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when the Editor is Created - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnItemCreated(PropertyEditorItemEventArgs e) - { - if (ItemCreated != null) - { - ItemCreated(this, e); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is removed from a collection type property - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnItemDeleted(PropertyEditorEventArgs e) - { - if (ItemDeleted != null) - { - ItemDeleted(this, e); - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (String.IsNullOrEmpty(CssClass)) - { - CssClass = "dnnFormItem"; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when the Value of a Property changes - /// - /// ----------------------------------------------------------------------------- - protected virtual void ValueChanged(object sender, PropertyEditorEventArgs e) - { - IsDirty = EditorInfoAdapter.UpdateValue(e); - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when the Visibility of a Property changes - /// - /// ----------------------------------------------------------------------------- - protected virtual void VisibilityChanged(object sender, PropertyEditorEventArgs e) - { - IsDirty = EditorInfoAdapter.UpdateVisibility(e); - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// Binds the controls to the DataSource - /// - /// ----------------------------------------------------------------------------- - public override void DataBind() - { - //Invoke OnDataBinding so DataBinding Event is raised - base.OnDataBinding(EventArgs.Empty); - - //Clear Existing Controls - Controls.Clear(); - - //Clear Child View State as controls will be loaded from DataSource - ClearChildViewState(); - - //Start Tracking ViewState - TrackViewState(); - - //Create the editor - CreateEditor(); - - //Set flag so CreateChildConrols should not be invoked later in control's lifecycle - ChildControlsCreated = true; - } - - /// ----------------------------------------------------------------------------- - /// - /// Validates the data, and sets the IsValid Property - /// - /// ----------------------------------------------------------------------------- - public virtual void Validate() - { - _IsValid = Editor.IsValid; - - if (_IsValid) - { - IEnumerator valEnumerator = Validators.GetEnumerator(); - while (valEnumerator.MoveNext()) - { - var validator = (IValidator) valEnumerator.Current; - validator.Validate(); - if (!validator.IsValid) - { - _IsValid = false; - break; - } - } - _Validated = true; - } - } - - #endregion - - #region Event Handlers - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an Item in the List Is Changed - /// - /// Raises an ItemChanged event. - /// ----------------------------------------------------------------------------- - protected virtual void ListItemChanged(object sender, PropertyEditorEventArgs e) - { - if (ItemChanged != null) - { - ItemChanged(this, e); - } - } - - #endregion - } + } + + regExValidator.EnableClientScript = this.EnableClientValidation; + regExValidator.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Validation"); + regExValidator.ErrorMessage = editInfo.Name + " is Invalid"; + this.Validators.Add(regExValidator); + } + } + + /// + /// BuildVisibility creates the visibility part of the Control. + /// + /// The EditorInfo object for this control. + private VisibilityControl BuildVisibility(EditorInfo editInfo) + { + VisibilityControl visControl = null; + + if (this.ShowVisibility) + { + visControl = new VisibilityControl + { + ID = "_visibility", + Name = editInfo.Name, + User = this.User, + Value = editInfo.ProfileVisibility, + }; + visControl.ControlStyle.CopyFrom(this.VisibilityStyle); + visControl.VisibilityChanged += this.VisibilityChanged; + } + + return visControl; + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is removed from a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void CollectionItemDeleted(object sender, PropertyEditorEventArgs e) + { + this.OnItemDeleted(e); + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is added to a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void OnItemAdded(PropertyEditorEventArgs e) + { + if (this.ItemAdded != null) + { + this.ItemAdded(this, e); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when the Editor is Created. + /// + /// ----------------------------------------------------------------------------- + protected virtual void OnItemCreated(PropertyEditorItemEventArgs e) + { + if (this.ItemCreated != null) + { + this.ItemCreated(this, e); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is removed from a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void OnItemDeleted(PropertyEditorEventArgs e) + { + if (this.ItemDeleted != null) + { + this.ItemDeleted(this, e); + } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (string.IsNullOrEmpty(this.CssClass)) + { + this.CssClass = "dnnFormItem"; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when the Value of a Property changes. + /// + /// ----------------------------------------------------------------------------- + protected virtual void ValueChanged(object sender, PropertyEditorEventArgs e) + { + this.IsDirty = this.EditorInfoAdapter.UpdateValue(e); + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when the Visibility of a Property changes. + /// + /// ----------------------------------------------------------------------------- + protected virtual void VisibilityChanged(object sender, PropertyEditorEventArgs e) + { + this.IsDirty = this.EditorInfoAdapter.UpdateVisibility(e); + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an Item in the List Is Changed. + /// + /// Raises an ItemChanged event. + /// ----------------------------------------------------------------------------- + protected virtual void ListItemChanged(object sender, PropertyEditorEventArgs e) + { + if (this.ItemChanged != null) + { + this.ItemChanged(this, e); + } + } + } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/GroupByMode.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/GroupByMode.cs index 4a5b638f39b..8058f66fa1a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/GroupByMode.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/GroupByMode.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- /// - /// Enumeration that determines the grouping method + /// Enumeration that determines the grouping method. /// /// /// GroupByMode is used by PropertyEditorControl @@ -16,6 +16,6 @@ namespace DotNetNuke.UI.WebControls public enum GroupByMode { None = 0, - Section + Section, } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/LabelMode.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/LabelMode.cs index 89b9934b74a..f809b623e34 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/LabelMode.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/LabelMode.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- /// - /// Enumeration that determines the label mode + /// Enumeration that determines the label mode. /// /// /// LabelMode is used by PropertyEditorControl @@ -19,6 +19,6 @@ public enum LabelMode Left, Right, Top, - Bottom + Bottom, } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/ListBoundField.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/ListBoundField.cs index 0b98e62b3e5..7dd48dc4cf6 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/ListBoundField.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/ListBoundField.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- /// - /// Enumeration that determines the field that a List binds to + /// Enumeration that determines the field that a List binds to. /// /// /// LabelMode is used by PropertyEditorControl @@ -17,6 +17,6 @@ public enum ListBoundField { Id, Value, - Text + Text, } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs index e06596141d8..e59b355158f 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs @@ -1,24 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; - -using DotNetNuke.Common.Lists; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.UI.WebControls + // ReSharper restore CheckNamespace { + using System; + using System.Web.UI; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -33,9 +29,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:ProfileEditorControl runat=server>")] public class ProfileEditorControl : CollectionEditorControl - { - #region Protected Methods - + { /// ----------------------------------------------------------------------------- /// /// CreateEditor creates the control collection. @@ -43,21 +37,21 @@ public class ProfileEditorControl : CollectionEditorControl /// ----------------------------------------------------------------------------- protected override void CreateEditor() { - CategoryDataField = "PropertyCategory"; - EditorDataField = "DataType"; - NameDataField = "PropertyName"; - RequiredDataField = "Required"; - ValidationExpressionDataField = "ValidationExpression"; - ValueDataField = "PropertyValue"; - VisibleDataField = "Visible"; - VisibilityDataField = "ProfileVisibility"; - LengthDataField = "Length"; + this.CategoryDataField = "PropertyCategory"; + this.EditorDataField = "DataType"; + this.NameDataField = "PropertyName"; + this.RequiredDataField = "Required"; + this.ValidationExpressionDataField = "ValidationExpression"; + this.ValueDataField = "PropertyValue"; + this.VisibleDataField = "Visible"; + this.VisibilityDataField = "ProfileVisibility"; + this.LengthDataField = "Length"; base.CreateEditor(); - foreach (FieldEditorControl editor in Fields) + foreach (FieldEditorControl editor in this.Fields) { - //Check whether Field is readonly + // Check whether Field is readonly string fieldName = editor.Editor.Name; ProfilePropertyDefinitionCollection definitions = editor.DataSource as ProfilePropertyDefinitionCollection; ProfilePropertyDefinition definition = definitions[fieldName]; @@ -71,43 +65,42 @@ protected override void CreateEditor() } } - //We need to wire up the RegionControl to the CountryControl + // We need to wire up the RegionControl to the CountryControl if (editor.Editor is DNNRegionEditControl) { string country = null; - foreach (FieldEditorControl checkEditor in Fields) + foreach (FieldEditorControl checkEditor in this.Fields) { if (checkEditor.Editor is DNNCountryEditControl) { - if (editor.Editor.Category == checkEditor.Editor.Category) - { - var countryEdit = (DNNCountryEditControl)checkEditor.Editor; - country = Convert.ToString(countryEdit.Value); - } + if (editor.Editor.Category == checkEditor.Editor.Category) + { + var countryEdit = (DNNCountryEditControl)checkEditor.Editor; + country = Convert.ToString(countryEdit.Value); + } + } + } + + // Create a ListAttribute for the Region + string countryKey = "Unknown"; + int entryId; + if (int.TryParse(country, out entryId)) + { + ListController lc = new ListController(); + ListEntryInfo item = lc.GetListEntryInfo(entryId); + if (item != null) + { + countryKey = item.Value; } } - - //Create a ListAttribute for the Region - string countryKey = "Unknown"; - int entryId; - if (int.TryParse(country, out entryId)) - { - ListController lc = new ListController(); - ListEntryInfo item = lc.GetListEntryInfo(entryId); - if (item != null) - { - countryKey = item.Value; - } - } - countryKey = "Country." + countryKey; + + countryKey = "Country." + countryKey; var attributes = new object[1]; attributes[0] = new ListAttribute("Region", countryKey, ListBoundField.Id, ListBoundField.Text); editor.Editor.CustomAttributes = attributes; } } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs index fe8392f960e..946332d752b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs @@ -1,61 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Web.UI.WebControls; + [AttributeUsage(AttributeTargets.Property)] public sealed class ControlStyleAttribute : Attribute { private readonly string _CssClass; private readonly Unit _Height; - private readonly Unit _Width; - - /// - /// Initializes a new instance of the StyleAttribute class. + private readonly Unit _Width; + + /// + /// Initializes a new instance of the class. /// - /// The css class to apply to the associated property + /// The css class to apply to the associated property. public ControlStyleAttribute(string cssClass) { - _CssClass = cssClass; - } - - /// - /// Initializes a new instance of the StyleAttribute class. + this._CssClass = cssClass; + } + + /// + /// Initializes a new instance of the class. /// - /// The css class to apply to the associated property + /// The css class to apply to the associated property. /// control width. public ControlStyleAttribute(string cssClass, string width) { - _CssClass = cssClass; - _Width = Unit.Parse(width); - } - - /// - /// Initializes a new instance of the StyleAttribute class. + this._CssClass = cssClass; + this._Width = Unit.Parse(width); + } + + /// + /// Initializes a new instance of the class. /// - /// The css class to apply to the associated property - /// control width. - /// control height. + /// The css class to apply to the associated property. + /// control width. + /// control height. public ControlStyleAttribute(string cssClass, string width, string height) { - _CssClass = cssClass; - _Height = Unit.Parse(height); - _Width = Unit.Parse(width); + this._CssClass = cssClass; + this._Height = Unit.Parse(height); + this._Width = Unit.Parse(width); } public string CssClass { get { - return _CssClass; + return this._CssClass; } } @@ -63,7 +58,7 @@ public Unit Height { get { - return _Height; + return this._Height; } } @@ -71,7 +66,7 @@ public Unit Width { get { - return _Width; + return this._Width; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs index 98eed7ed7aa..3022d4d254b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + [AttributeUsage(AttributeTargets.Property)] public sealed class FormatAttribute : Attribute { - private readonly string _Format; - - /// - /// Initializes a new instance of the FormatAttribute class. + private readonly string _Format; + + /// + /// Initializes a new instance of the class. /// public FormatAttribute(string format) { - _Format = format; + this._Format = format; } public string Format { get { - return _Format; + return this._Format; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs index 151e218f698..6914ea512e2 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + [AttributeUsage(AttributeTargets.Property)] public sealed class IsReadOnlyAttribute : Attribute { - private readonly bool _IsReadOnly; - - /// - /// Initializes a new instance of the ReadOnlyAttribute class. + private readonly bool _IsReadOnly; + + /// + /// Initializes a new instance of the class. /// - /// A boolean that indicates whether the property is ReadOnly + /// A boolean that indicates whether the property is ReadOnly. public IsReadOnlyAttribute(bool read) { - _IsReadOnly = read; + this._IsReadOnly = read; } public bool IsReadOnly { get { - return _IsReadOnly; + return this._IsReadOnly; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs index eaadab73f39..065878be742 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + [AttributeUsage(AttributeTargets.Property)] public sealed class LabelModeAttribute : Attribute { - private readonly LabelMode _Mode; - - /// - /// Initializes a new instance of the LabelModeAttribute class. + private readonly LabelMode _Mode; + + /// + /// Initializes a new instance of the class. /// - /// The label mode to apply to the associated property + /// The label mode to apply to the associated property. public LabelModeAttribute(LabelMode mode) { - _Mode = mode; + this._Mode = mode; } public LabelMode Mode { get { - return _Mode; + return this._Mode; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs index a40d3850652..cb701383bd5 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs @@ -1,36 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + + using DotNetNuke.Services.Localization; + [AttributeUsage(AttributeTargets.Property)] public sealed class LanguagesListTypeAttribute : Attribute { - private readonly LanguagesListType _ListType; - - /// - /// Initializes a new instance of the LanguagesListTypeAttribute class. + private readonly LanguagesListType _ListType; + + /// + /// Initializes a new instance of the class. /// - /// The type of List + /// The type of List. public LanguagesListTypeAttribute(LanguagesListType type) { - _ListType = type; + this._ListType = type; } public LanguagesListType ListType { get { - return _ListType; + return this._ListType; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs index a2d7c867b5d..56681affd37 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs @@ -1,43 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + [AttributeUsage(AttributeTargets.Property)] public sealed class ListAttribute : Attribute { private readonly string _ListName; private readonly string _ParentKey; private readonly ListBoundField _TextField; - private readonly ListBoundField _ValueField; - - /// - /// Initializes a new instance of the ListAttribute class. + private readonly ListBoundField _ValueField; + + /// + /// Initializes a new instance of the class. /// - /// The name of the List to use for this property - /// The key of the parent for this List + /// The name of the List to use for this property. + /// The key of the parent for this List. /// Text Field. /// Value Field. public ListAttribute(string listName, string parentKey, ListBoundField valueField, ListBoundField textField) { - _ListName = listName; - _ParentKey = parentKey; - _TextField = textField; - _ValueField = valueField; + this._ListName = listName; + this._ParentKey = parentKey; + this._TextField = textField; + this._ValueField = valueField; } public string ListName { get { - return _ListName; + return this._ListName; } } @@ -45,7 +40,7 @@ public string ParentKey { get { - return _ParentKey; + return this._ParentKey; } } @@ -53,7 +48,7 @@ public ListBoundField TextField { get { - return _TextField; + return this._TextField; } } @@ -61,7 +56,7 @@ public ListBoundField ValueField { get { - return _ValueField; + return this._ValueField; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs index af2a784d926..80bb7b81819 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + + using DotNetNuke.Common.Utilities; + [AttributeUsage(AttributeTargets.Property)] public sealed class MaxLengthAttribute : Attribute { - private readonly int _Length = Null.NullInteger; - - /// - /// Initializes a new instance of the MaxLengthAttribute class. + private readonly int _Length = Null.NullInteger; + + /// + /// Initializes a new instance of the class. /// public MaxLengthAttribute(int length) { - _Length = length; + this._Length = length; } public int Length { get { - return _Length; + return this._Length; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs index debbb4f6287..4bb52b53781 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + [AttributeUsage(AttributeTargets.Property)] public sealed class RegularExpressionValidatorAttribute : Attribute { - private readonly string _Expression; - - /// - /// Initializes a new instance of the RegularExpressionValidatorAttribute class. + private readonly string _Expression; + + /// + /// Initializes a new instance of the class. /// public RegularExpressionValidatorAttribute(string expression) { - _Expression = expression; + this._Expression = expression; } public string Expression { get { - return _Expression; + return this._Expression; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs index 0f624b03539..acc606ff994 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs @@ -1,33 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + [AttributeUsage(AttributeTargets.Property)] public sealed class RequiredAttribute : Attribute { - private readonly bool _Required; - - /// - /// Initializes a new instance of the RequiredAttribute class. + private readonly bool _Required; + + /// + /// Initializes a new instance of the class. /// public RequiredAttribute(bool required) { - _Required = required; + this._Required = required; } public bool Required { get { - return _Required; + return this._Required; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs index 14102fe9f18..f5099522114 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + [AttributeUsage(AttributeTargets.Property)] public sealed class SortOrderAttribute : Attribute - { - /// - /// Initializes a new instance of the SortOrderAttribute class. + { + /// + /// Initializes a new instance of the class. /// /// public SortOrderAttribute(int order) { - Order = order; + this.Order = order; } - public int Order { get; set; } - public static int DefaultOrder { get { - return Int32.MaxValue; + return int.MaxValue; } } + + public int Order { get; set; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs index 069ee17ae29..9638939f036 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs @@ -1,48 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.ComponentModel; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.ComponentModel; + using System.Reflection; + public class PropertyCategoryComparer : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { if (x is PropertyInfo && y is PropertyInfo) { - var xProp = (PropertyInfo) x; - var yProp = (PropertyInfo) y; - object[] xCategory = xProp.GetCustomAttributes(typeof (CategoryAttribute), true); + var xProp = (PropertyInfo)x; + var yProp = (PropertyInfo)y; + object[] xCategory = xProp.GetCustomAttributes(typeof(CategoryAttribute), true); string xCategoryName = string.Empty; if (xCategory.Length > 0) { - xCategoryName = ((CategoryAttribute) xCategory[0]).Category; + xCategoryName = ((CategoryAttribute)xCategory[0]).Category; } else { xCategoryName = CategoryAttribute.Default.Category; } - object[] yCategory = yProp.GetCustomAttributes(typeof (CategoryAttribute), true); + + object[] yCategory = yProp.GetCustomAttributes(typeof(CategoryAttribute), true); string yCategoryName = string.Empty; if (yCategory.Length > 0) { - yCategoryName = ((CategoryAttribute) yCategory[0]).Category; + yCategoryName = ((CategoryAttribute)yCategory[0]).Category; } else { yCategoryName = CategoryAttribute.Default.Category; } + if (xCategoryName == yCategoryName) { return string.Compare(xProp.Name, yProp.Name); @@ -56,8 +51,6 @@ public int Compare(object x, object y) { throw new ArgumentException("Object is not of type PropertyInfo"); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs index 53b3a12cc48..d4d0a0c24ab 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs @@ -1,33 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.Reflection; + public class PropertyNameComparer : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { if (x is PropertyInfo && y is PropertyInfo) { - return string.Compare(((PropertyInfo) x).Name, ((PropertyInfo) y).Name); + return string.Compare(((PropertyInfo)x).Name, ((PropertyInfo)y).Name); } else { throw new ArgumentException("Object is not of type PropertyInfo"); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs index 60ff01d2880..3b1fa66f23a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs @@ -1,47 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Reflection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.Reflection; + public class PropertySortOrderComparer : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { if (x is PropertyInfo && y is PropertyInfo) { - var xProp = (PropertyInfo) x; - var yProp = (PropertyInfo) y; - object[] xSortOrder = xProp.GetCustomAttributes(typeof (SortOrderAttribute), true); - Int32 xSortOrderValue; + var xProp = (PropertyInfo)x; + var yProp = (PropertyInfo)y; + object[] xSortOrder = xProp.GetCustomAttributes(typeof(SortOrderAttribute), true); + int xSortOrderValue; if (xSortOrder.Length > 0) { - xSortOrderValue = ((SortOrderAttribute) xSortOrder[0]).Order; + xSortOrderValue = ((SortOrderAttribute)xSortOrder[0]).Order; } else { xSortOrderValue = SortOrderAttribute.DefaultOrder; } - object[] ySortOrder = yProp.GetCustomAttributes(typeof (SortOrderAttribute), true); - Int32 ySortOrderValue; + + object[] ySortOrder = yProp.GetCustomAttributes(typeof(SortOrderAttribute), true); + int ySortOrderValue; if (ySortOrder.Length > 0) { - ySortOrderValue = ((SortOrderAttribute) ySortOrder[0]).Order; + ySortOrderValue = ((SortOrderAttribute)ySortOrder[0]).Order; } else { ySortOrderValue = SortOrderAttribute.DefaultOrder; } + if (xSortOrderValue == ySortOrderValue) { return string.Compare(xProp.Name, yProp.Name); @@ -55,8 +50,6 @@ public int Compare(object x, object y) { throw new ArgumentException("Object is not of type PropertyInfo"); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs index e11a94863a8..0676ff91345 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs @@ -1,32 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + public class SettingNameComparer : IComparer - { - #region IComparer Members - + { public int Compare(object x, object y) { if (x is SettingInfo && y is SettingInfo) { - return string.Compare(((SettingInfo) x).Name, ((SettingInfo) y).Name); + return string.Compare(((SettingInfo)x).Name, ((SettingInfo)y).Name); } else { throw new ArgumentException("Object is not of type SettingInfo"); } - } - - #endregion + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs index 7b3c17a2af3..52389aa4173 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs @@ -1,70 +1,82 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.UI.WebControls + // ReSharper restore CheckNamespace { + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Reflection; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + /// ----------------------------------------------------------------------------- /// - /// The PropertyEditorControl control provides a way to display and edit any - /// properties of any Info class + /// The PropertyEditorControl control provides a way to display and edit any + /// properties of any Info class. /// /// /// /// ----------------------------------------------------------------------------- public class PropertyEditorControl : WebControl, INamingContainer - { - #region Private Members - + { private bool _itemChanged; - private Hashtable _sections; - #endregion - - #region Constructors - + private Hashtable _sections; + public PropertyEditorControl() { - VisibilityStyle = new Style(); - ItemStyle = new Style(); - LabelStyle = new Style(); - HelpStyle = new Style(); - GroupHeaderStyle = new Style(); - ErrorStyle = new Style(); - EditControlStyle = new Style(); - Fields = new ArrayList(); - ShowRequired = true; - LabelMode = LabelMode.Left; - HelpDisplayMode = HelpDisplayMode.Always; - Groups = Null.NullString; - AutoGenerate = true; - } - - #endregion - - #region Protected Members + this.VisibilityStyle = new Style(); + this.ItemStyle = new Style(); + this.LabelStyle = new Style(); + this.HelpStyle = new Style(); + this.GroupHeaderStyle = new Style(); + this.ErrorStyle = new Style(); + this.EditControlStyle = new Style(); + this.Fields = new ArrayList(); + this.ShowRequired = true; + this.LabelMode = LabelMode.Left; + this.HelpDisplayMode = HelpDisplayMode.Always; + this.Groups = Null.NullString; + this.AutoGenerate = true; + } + + public event PropertyChangedEventHandler ItemAdded; + + public event EditorCreatedEventHandler ItemCreated; + + public event PropertyChangedEventHandler ItemDeleted; + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the editor Autogenerates its editors. + /// + /// The DataSource object. + /// ----------------------------------------------------------------------------- + [Category("Behavior")] + public bool AutoGenerate { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the DataSource that is bound to this control. + /// + /// The DataSource object. + /// ----------------------------------------------------------------------------- + [Browsable(false)] + [Category("Data")] + public object DataSource { get; set; } + protected override HtmlTextWriterTag TagKey { get @@ -75,42 +87,20 @@ protected override HtmlTextWriterTag TagKey /// ----------------------------------------------------------------------------- /// - /// Gets the Underlying DataSource + /// Gets the Underlying DataSource. /// - /// An IEnumerable Boolean + /// An IEnumerable Boolean. /// ----------------------------------------------------------------------------- protected virtual IEnumerable UnderlyingDataSource { - get { return GetProperties(); } - } - - #endregion - - #region Public Properties - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets whether the editor Autogenerates its editors - /// - /// The DataSource object - /// ----------------------------------------------------------------------------- - [Category("Behavior")] - public bool AutoGenerate { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the DataSource that is bound to this control - /// - /// The DataSource object - /// ----------------------------------------------------------------------------- - [Browsable(false), Category("Data")] - public object DataSource { get; set; } + get { return this.GetProperties(); } + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Edit Mode of the Editor + /// Gets or sets and sets the Edit Mode of the Editor. /// - /// The mode of the editor + /// The mode of the editor. /// ----------------------------------------------------------------------------- [Category("Appearance")] public PropertyEditorMode EditMode { get; set; } @@ -119,67 +109,67 @@ protected virtual IEnumerable UnderlyingDataSource /// ----------------------------------------------------------------------------- /// - /// Gets and sets a flag indicating whether the Validators should use client-side - /// validation + /// Gets or sets a value indicating whether gets and sets a flag indicating whether the Validators should use client-side + /// validation. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- [Category("Behavior")] public bool EnableClientValidation { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the grouping mode + /// Gets or sets and sets the grouping mode. /// - /// A GroupByMode enum + /// A GroupByMode enum. /// ----------------------------------------------------------------------------- [Category("Appearance")] public GroupByMode GroupByMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the grouping order + /// Gets or sets and sets the grouping order. /// - /// A comma-delimited list of categories/groups + /// A comma-delimited list of categories/groups. /// ----------------------------------------------------------------------------- [Category("Appearance")] public string Groups { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the control displays Help + /// Gets or sets and sets whether the control displays Help. /// - /// A HelpDisplayMode enum + /// A HelpDisplayMode enum. /// ----------------------------------------------------------------------------- public HelpDisplayMode HelpDisplayMode { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether any of the properties have been changed + /// Gets a value indicating whether gets whether any of the properties have been changed. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- [Browsable(false)] public bool IsDirty { get { - return Fields.Cast().Any(editor => editor.Visible && editor.IsDirty); + return this.Fields.Cast().Any(editor => editor.Visible && editor.IsDirty); } } /// ----------------------------------------------------------------------------- /// - /// Gets whether all of the properties are Valid + /// Gets a value indicating whether gets whether all of the properties are Valid. /// - /// A Boolean + /// A Boolean. /// ----------------------------------------------------------------------------- [Browsable(false)] public bool IsValid { get { - return Fields.Cast().All(editor => !editor.Visible || editor.IsValid); + return this.Fields.Cast().All(editor => !editor.Visible || editor.IsValid); } } @@ -187,30 +177,30 @@ public bool IsValid /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Local Resource File for the Control + /// Gets or sets and sets the Local Resource File for the Control. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string LocalResourceFile { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Url of the Required Image + /// Gets or sets and sets the Url of the Required Image. /// - /// A String + /// A String. /// ----------------------------------------------------------------------------- public string RequiredUrl { get; set; } /// ----------------------------------------------------------------------------- /// - /// gets and sets whether the Required icon is used + /// Gets or sets a value indicating whether gets and sets whether the Required icon is used. /// /// ----------------------------------------------------------------------------- public bool ShowRequired { get; set; } /// ----------------------------------------------------------------------------- /// - /// gets and sets whether the Visibility control is used + /// Gets or sets a value indicating whether gets and sets whether the Visibility control is used. /// /// ----------------------------------------------------------------------------- [Category("Appearance")] @@ -218,11 +208,11 @@ public bool IsValid /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether to sort properties. + /// Gets or sets and sets whether to sort properties. /// - /// The Sort Mode of the editor + /// The Sort Mode of the editor. /// - /// By default all properties will be sorted + /// By default all properties will be sorted. /// /// ----------------------------------------------------------------------------- [Category("Appearance")] @@ -235,114 +225,221 @@ public bool IsValid /// Gets a collection of fields to display if AutoGenerate is false. Or the /// collection of fields generated if AutoGenerate is true. /// - /// A collection of FieldEditorControl objects + /// A collection of FieldEditorControl objects. /// ----------------------------------------------------------------------------- - [Category("Behavior"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - public ArrayList Fields { get; private set; } - - #region "Style Properties" - + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public ArrayList Fields { get; private set; } + /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Field Style + /// Gets the value of the Field Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), PersistenceMode(PersistenceMode.InnerProperty), Description("Set the Style for the Edit Control.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] + [Description("Set the Style for the Edit Control.")] public Style EditControlStyle { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the width of the Edit Control Column + /// Gets or sets and sets the width of the Edit Control Column. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Appearance"), Description("Set the Width for the Edit Control.")] + [Browsable(true)] + [Category("Appearance")] + [Description("Set the Width for the Edit Control.")] public Unit EditControlWidth { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Error Style + /// Gets the value of the Error Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), PersistenceMode(PersistenceMode.InnerProperty), Description("Set the Style for the Error Text.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] + [Description("Set the Style for the Error Text.")] public Style ErrorStyle { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Group Header Style + /// Gets the value of the Group Header Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), PersistenceMode(PersistenceMode.InnerProperty), Description("Set the Style for the Group Header Control.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] + [Description("Set the Style for the Group Header Control.")] public Style GroupHeaderStyle { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether to add a <hr> to the Group Header + /// Gets or sets a value indicating whether gets and sets whether to add a <hr> to the Group Header. /// - /// A boolean + /// A boolean. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Appearance"), Description("Set whether to include a rule
    in the Group Header.")] + [Browsable(true)] + [Category("Appearance")] + [Description("Set whether to include a rule
    in the Group Header.")] public bool GroupHeaderIncludeRule { get; set; } - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), PersistenceMode(PersistenceMode.InnerProperty), Description("Set the Style for the Help Text.")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] + [Description("Set the Style for the Help Text.")] public Style HelpStyle { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Label Style + /// Gets the value of the Label Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof(ExpandableObjectConverter)), PersistenceMode(PersistenceMode.InnerProperty), Description("Set the Style for the Label Text")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] + [Description("Set the Style for the Label Text")] public Style ItemStyle { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Label Style + /// Gets the value of the Label Style. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), PersistenceMode(PersistenceMode.InnerProperty), Description("Set the Style for the Label Text")] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] + [Description("Set the Style for the Label Text")] public Style LabelStyle { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the width of the Label Column + /// Gets or sets and sets the width of the Label Column. /// - /// A Style object + /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Appearance"), Description("Set the Width for the Label Control.")] + [Browsable(true)] + [Category("Appearance")] + [Description("Set the Width for the Label Control.")] public Unit LabelWidth { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the value of the Visibility Style + /// Gets the value of the Visibility Style. + /// + /// A Style object. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] + [Description("Set the Style for the Visibility Control")] + public Style VisibilityStyle { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Binds the controls to the DataSource. /// - /// A Style object /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), PersistenceMode(PersistenceMode.InnerProperty), Description("Set the Style for the Visibility Control")] - public Style VisibilityStyle { get; private set; } - - #endregion + public override void DataBind() + { + // Invoke OnDataBinding so DataBinding Event is raised + this.OnDataBinding(EventArgs.Empty); - #endregion + // Clear Existing Controls + this.Controls.Clear(); - #region Events + // Clear Child View State as controls will be loaded from DataSource + this.ClearChildViewState(); - public event PropertyChangedEventHandler ItemAdded; - public event EditorCreatedEventHandler ItemCreated; - public event PropertyChangedEventHandler ItemDeleted; + // Start Tracking ViewState + this.TrackViewState(); - #endregion + // Create the Editor + this.CreateEditor(); - #region Private Methods + // Set flag so CreateChildConrols should not be invoked later in control's lifecycle + this.ChildControlsCreated = true; + } + + /// ----------------------------------------------------------------------------- + /// + /// AddEditorRow builds a sigle editor row and adds it to the Table, using the + /// specified adapter. + /// + /// The Table Control to add the row to. + /// The name of property being added. + /// An IEditorInfoAdapter. + /// ----------------------------------------------------------------------------- + protected void AddEditorRow(Table table, string name, IEditorInfoAdapter adapter) + { + var row = new TableRow(); + table.Rows.Add(row); + + var cell = new TableCell(); + row.Cells.Add(cell); + + // Create a FieldEditor for this Row + var editor = new FieldEditorControl + { + DataSource = this.DataSource, + EditorInfoAdapter = adapter, + DataField = name, + EditorDisplayMode = this.DisplayMode, + EnableClientValidation = this.EnableClientValidation, + EditMode = this.EditMode, + HelpDisplayMode = this.HelpDisplayMode, + LabelMode = this.LabelMode, + LabelWidth = this.LabelWidth, + }; + this.AddEditorRow(editor, cell); + + this.Fields.Add(editor); + } + + protected void AddEditorRow(WebControl container, string name, IEditorInfoAdapter adapter) + { + var editor = new FieldEditorControl + { + DataSource = this.DataSource, + EditorInfoAdapter = adapter, + DataField = name, + EditorDisplayMode = this.DisplayMode, + EnableClientValidation = this.EnableClientValidation, + EditMode = this.EditMode, + HelpDisplayMode = this.HelpDisplayMode, + LabelMode = this.LabelMode, + LabelWidth = this.LabelWidth, + }; + this.AddEditorRow(editor, container); + this.Fields.Add(editor); + } + /// ----------------------------------------------------------------------------- /// - /// GetProperties returns an array of PropertyInfo + /// GetProperties returns an array of PropertyInfo. /// /// An array of PropertyInfo objects /// for the current DataSource object. @@ -353,15 +450,15 @@ public bool IsValid /// ----------------------------------------------------------------------------- private IEnumerable GetProperties() { - if (DataSource != null) + if (this.DataSource != null) { - //TODO: We need to add code to support using the cache in the future + // TODO: We need to add code to support using the cache in the future const BindingFlags bindings = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; - var properties = DataSource.GetType().GetProperties(bindings); + var properties = this.DataSource.GetType().GetProperties(bindings); - //Apply sort method - switch (SortMode) + // Apply sort method + switch (this.SortMode) { case PropertySortType.Alphabetical: Array.Sort(properties, new PropertyNameComparer()); @@ -373,224 +470,175 @@ private IEnumerable GetProperties() Array.Sort(properties, new PropertySortOrderComparer()); break; } + return properties; } + return null; } private void AddEditorRow(FieldEditorControl editor, WebControl container) { - editor.ControlStyle.CopyFrom(ItemStyle); - editor.LabelStyle.CopyFrom(LabelStyle); - editor.HelpStyle.CopyFrom(HelpStyle); - editor.ErrorStyle.CopyFrom(ErrorStyle); - editor.VisibilityStyle.CopyFrom(VisibilityStyle); - editor.EditControlStyle.CopyFrom(EditControlStyle); + editor.ControlStyle.CopyFrom(this.ItemStyle); + editor.LabelStyle.CopyFrom(this.LabelStyle); + editor.HelpStyle.CopyFrom(this.HelpStyle); + editor.ErrorStyle.CopyFrom(this.ErrorStyle); + editor.VisibilityStyle.CopyFrom(this.VisibilityStyle); + editor.EditControlStyle.CopyFrom(this.EditControlStyle); if (editor.EditControlWidth == Unit.Empty) { - editor.EditControlWidth = EditControlWidth; + editor.EditControlWidth = this.EditControlWidth; } - editor.LocalResourceFile = LocalResourceFile; - editor.RequiredUrl = RequiredUrl; - editor.ShowRequired = ShowRequired; - editor.ShowVisibility = ShowVisibility; - editor.User = User; - editor.Width = Width; - editor.ItemAdded += CollectionItemAdded; - editor.ItemChanged += ListItemChanged; - editor.ItemCreated += EditorItemCreated; - editor.ItemDeleted += CollectionItemDeleted; + + editor.LocalResourceFile = this.LocalResourceFile; + editor.RequiredUrl = this.RequiredUrl; + editor.ShowRequired = this.ShowRequired; + editor.ShowVisibility = this.ShowVisibility; + editor.User = this.User; + editor.Width = this.Width; + editor.ItemAdded += this.CollectionItemAdded; + editor.ItemChanged += this.ListItemChanged; + editor.ItemCreated += this.EditorItemCreated; + editor.ItemDeleted += this.CollectionItemDeleted; editor.DataBind(); container.Controls.Add(editor); - } - - #endregion - - #region Protected Methods + } /// ----------------------------------------------------------------------------- /// - /// AddEditorRow builds a sigle editor row and adds it to the Table, using the - /// specified adapter - /// - /// The Table Control to add the row to - /// The name of property being added - /// An IEditorInfoAdapter - /// ----------------------------------------------------------------------------- - protected void AddEditorRow(Table table, string name, IEditorInfoAdapter adapter) - { - var row = new TableRow(); - table.Rows.Add(row); - - var cell = new TableCell(); - row.Cells.Add(cell); - - //Create a FieldEditor for this Row - var editor = new FieldEditorControl - { - DataSource = DataSource, - EditorInfoAdapter = adapter, - DataField = name, - EditorDisplayMode = DisplayMode, - EnableClientValidation = EnableClientValidation, - EditMode = EditMode, - HelpDisplayMode = HelpDisplayMode, - LabelMode = LabelMode, - LabelWidth = LabelWidth - }; - AddEditorRow(editor, cell); - - Fields.Add(editor); - } - - protected void AddEditorRow(WebControl container, string name, IEditorInfoAdapter adapter) - { - var editor = new FieldEditorControl - { - DataSource = DataSource, - EditorInfoAdapter = adapter, - DataField = name, - EditorDisplayMode = DisplayMode, - EnableClientValidation = EnableClientValidation, - EditMode = EditMode, - HelpDisplayMode = HelpDisplayMode, - LabelMode = LabelMode, - LabelWidth = LabelWidth - }; - AddEditorRow(editor, container); - - Fields.Add(editor); - } - - /// ----------------------------------------------------------------------------- - /// - /// AddEditorRow builds a sigle editor row and adds it to the Table + /// AddEditorRow builds a sigle editor row and adds it to the Table. /// /// This method is protected so that classes that inherit from - /// PropertyEditor can modify how the Row is displayed - /// The Table Control to add the row to - /// Row Data Info. + /// PropertyEditor can modify how the Row is displayed. + /// The Table Control to add the row to. + /// Row Data Info. /// ----------------------------------------------------------------------------- protected virtual void AddEditorRow(Table table, object obj) { - var objProperty = (PropertyInfo) obj; - AddEditorRow(table, objProperty.Name, new StandardEditorInfoAdapter(DataSource, objProperty.Name)); + var objProperty = (PropertyInfo)obj; + this.AddEditorRow(table, objProperty.Name, new StandardEditorInfoAdapter(this.DataSource, objProperty.Name)); } protected virtual void AddEditorRow(Panel container, object obj) { var objProperty = (PropertyInfo)obj; - AddEditorRow(container, objProperty.Name, new StandardEditorInfoAdapter(DataSource, objProperty.Name)); + this.AddEditorRow(container, objProperty.Name, new StandardEditorInfoAdapter(this.DataSource, objProperty.Name)); } protected virtual void AddEditorRow(object obj) { var objProperty = (PropertyInfo)obj; - AddEditorRow(this, objProperty.Name, new StandardEditorInfoAdapter(DataSource, objProperty.Name)); + this.AddEditorRow(this, objProperty.Name, new StandardEditorInfoAdapter(this.DataSource, objProperty.Name)); } protected virtual void AddFields() { - foreach (FieldEditorControl editor in Fields) + foreach (FieldEditorControl editor in this.Fields) { - editor.DataSource = DataSource; - editor.EditorInfoAdapter = new StandardEditorInfoAdapter(DataSource, editor.DataField); - editor.EditorDisplayMode = DisplayMode; - editor.EnableClientValidation = EnableClientValidation; + editor.DataSource = this.DataSource; + editor.EditorInfoAdapter = new StandardEditorInfoAdapter(this.DataSource, editor.DataField); + editor.EditorDisplayMode = this.DisplayMode; + editor.EnableClientValidation = this.EnableClientValidation; if (editor.EditMode != PropertyEditorMode.View) { - editor.EditMode = EditMode; + editor.EditMode = this.EditMode; } - editor.HelpDisplayMode = HelpDisplayMode; + + editor.HelpDisplayMode = this.HelpDisplayMode; if (editor.LabelMode == LabelMode.None) { - editor.LabelMode = LabelMode; + editor.LabelMode = this.LabelMode; } + if (editor.LabelWidth == Unit.Empty) { - editor.LabelWidth = LabelWidth; + editor.LabelWidth = this.LabelWidth; } - AddEditorRow(editor, this); + this.AddEditorRow(editor, this); } } /// ----------------------------------------------------------------------------- /// - /// AddFields adds the fields that have beend defined in design mode (Autogenerate=false) + /// AddFields adds the fields that have beend defined in design mode (Autogenerate=false). /// - /// The Table Control to add the row to + /// The Table Control to add the row to. /// ----------------------------------------------------------------------------- protected virtual void AddFields(Table tbl) { - foreach (FieldEditorControl editor in Fields) + foreach (FieldEditorControl editor in this.Fields) { var row = new TableRow(); tbl.Rows.Add(row); var cell = new TableCell(); row.Cells.Add(cell); - editor.DataSource = DataSource; - editor.EditorInfoAdapter = new StandardEditorInfoAdapter(DataSource, editor.DataField); - editor.EditorDisplayMode = DisplayMode; - editor.EnableClientValidation = EnableClientValidation; + editor.DataSource = this.DataSource; + editor.EditorInfoAdapter = new StandardEditorInfoAdapter(this.DataSource, editor.DataField); + editor.EditorDisplayMode = this.DisplayMode; + editor.EnableClientValidation = this.EnableClientValidation; if (editor.EditMode != PropertyEditorMode.View) { - editor.EditMode = EditMode; + editor.EditMode = this.EditMode; } - editor.HelpDisplayMode = HelpDisplayMode; + + editor.HelpDisplayMode = this.HelpDisplayMode; if (editor.LabelMode == LabelMode.None) { - editor.LabelMode = LabelMode; + editor.LabelMode = this.LabelMode; } + if (editor.LabelWidth == Unit.Empty) { - editor.LabelWidth = LabelWidth; + editor.LabelWidth = this.LabelWidth; } - AddEditorRow(editor, cell); + this.AddEditorRow(editor, cell); } } /// ----------------------------------------------------------------------------- /// - /// AddHeader builds a group header + /// AddHeader builds a group header. /// /// This method is protected so that classes that inherit from - /// PropertyEditor can modify how the Header is displayed - /// The Table Control that contains the group + /// PropertyEditor can modify how the Header is displayed. + /// The Table Control that contains the group. /// Table Header. /// ----------------------------------------------------------------------------- protected virtual void AddHeader(Table tbl, string header) { var panel = new Panel(); - var icon = new Image {ID = "ico" + header, EnableViewState = false}; + var icon = new Image { ID = "ico" + header, EnableViewState = false }; - var spacer = new Literal {Text = " ", EnableViewState = false}; + var spacer = new Literal { Text = " ", EnableViewState = false }; - var label = new Label {ID = "lbl" + header}; - label.Attributes["resourcekey"] = ID + "_" + header + ".Header"; + var label = new Label { ID = "lbl" + header }; + label.Attributes["resourcekey"] = this.ID + "_" + header + ".Header"; label.Text = header; label.EnableViewState = false; - label.ControlStyle.CopyFrom(GroupHeaderStyle); + label.ControlStyle.CopyFrom(this.GroupHeaderStyle); panel.Controls.Add(icon); panel.Controls.Add(spacer); panel.Controls.Add(label); - if (GroupHeaderIncludeRule) + if (this.GroupHeaderIncludeRule) { panel.Controls.Add(new LiteralControl("
    ")); } - Controls.Add(panel); - - //Get the Hashtable - if (_sections == null) + + this.Controls.Add(panel); + + // Get the Hashtable + if (this._sections == null) { - _sections = new Hashtable(); + this._sections = new Hashtable(); } - _sections[icon] = tbl; + + this._sections[icon] = tbl; } /// ----------------------------------------------------------------------------- @@ -603,97 +651,99 @@ protected virtual void CreateEditor() Table table; string[] arrGroups = null; - Controls.Clear(); - if (!String.IsNullOrEmpty(Groups)) + this.Controls.Clear(); + if (!string.IsNullOrEmpty(this.Groups)) { - arrGroups = Groups.Split(','); + arrGroups = this.Groups.Split(','); } - else if (GroupByMode != GroupByMode.None) + else if (this.GroupByMode != GroupByMode.None) { - arrGroups = GetGroups(UnderlyingDataSource); + arrGroups = this.GetGroups(this.UnderlyingDataSource); } - if (!AutoGenerate) + if (!this.AutoGenerate) { - //Create a new table - if (DisplayMode == EditorDisplayMode.Div) + // Create a new table + if (this.DisplayMode == EditorDisplayMode.Div) { - AddFields(); + this.AddFields(); } else { - //Add the Table to the Controls Collection + // Add the Table to the Controls Collection table = new Table { ID = "tbl" }; - AddFields(table); - Controls.Add(table); + this.AddFields(table); + this.Controls.Add(table); } } else { - Fields.Clear(); + this.Fields.Clear(); if (arrGroups != null && arrGroups.Length > 0) { foreach (string strGroup in arrGroups) { - if (GroupByMode == GroupByMode.Section) + if (this.GroupByMode == GroupByMode.Section) { - if (DisplayMode == EditorDisplayMode.Div) + if (this.DisplayMode == EditorDisplayMode.Div) { - var groupData = UnderlyingDataSource.Cast().Where(obj => GetCategory(obj) == strGroup.Trim() && GetRowVisibility(obj)); - if (groupData.Count() > 0) - { - //Add header - var header = new HtmlGenericControl("h2"); - header.Attributes.Add("class", "dnnFormSectionHead"); - header.Attributes.Add("id", strGroup); - Controls.Add(header); - - var localizedGroupName = Localization.GetString("ProfileProperties_" + strGroup + ".Header", LocalResourceFile); - if (string.IsNullOrEmpty(localizedGroupName)) - { - localizedGroupName = strGroup; - } - var link = new HyperLink() { Text = localizedGroupName, NavigateUrl = "#" }; - header.Controls.Add(link); - - //fieldset to hold properties in group - var fieldset = new HtmlGenericControl("fieldset"); - var container = new Panel(); - fieldset.Controls.Add(container); - - foreach (object obj in groupData) - { - AddEditorRow(container, obj); - } - Controls.Add(fieldset); - } + var groupData = this.UnderlyingDataSource.Cast().Where(obj => this.GetCategory(obj) == strGroup.Trim() && this.GetRowVisibility(obj)); + if (groupData.Count() > 0) + { + // Add header + var header = new HtmlGenericControl("h2"); + header.Attributes.Add("class", "dnnFormSectionHead"); + header.Attributes.Add("id", strGroup); + this.Controls.Add(header); + + var localizedGroupName = Localization.GetString("ProfileProperties_" + strGroup + ".Header", this.LocalResourceFile); + if (string.IsNullOrEmpty(localizedGroupName)) + { + localizedGroupName = strGroup; + } + + var link = new HyperLink() { Text = localizedGroupName, NavigateUrl = "#" }; + header.Controls.Add(link); + + // fieldset to hold properties in group + var fieldset = new HtmlGenericControl("fieldset"); + var container = new Panel(); + fieldset.Controls.Add(container); + + foreach (object obj in groupData) + { + this.AddEditorRow(container, obj); + } + + this.Controls.Add(fieldset); + } } else { - //Create a new table + // Create a new table table = new Table { ID = "tbl" + strGroup }; - foreach (object obj in UnderlyingDataSource) + foreach (object obj in this.UnderlyingDataSource) { - if (GetCategory(obj) == strGroup.Trim()) + if (this.GetCategory(obj) == strGroup.Trim()) { - //Add the Editor Row to the Table - if (GetRowVisibility(obj)) + // Add the Editor Row to the Table + if (this.GetRowVisibility(obj)) { if (table.Rows.Count == 0) { - //Add a Header - AddHeader(table, strGroup); + // Add a Header + this.AddHeader(table, strGroup); } - AddEditorRow(table, obj); + this.AddEditorRow(table, obj); } } } - //Add the Table to the Controls Collection (if it has any rows) + // Add the Table to the Controls Collection (if it has any rows) if (table.Rows.Count > 0) { - Controls.Add(table); + this.Controls.Add(table); } } } @@ -701,31 +751,31 @@ protected virtual void CreateEditor() } else { - //Create a new table - if (DisplayMode == EditorDisplayMode.Div) + // Create a new table + if (this.DisplayMode == EditorDisplayMode.Div) { - foreach (object obj in UnderlyingDataSource) + foreach (object obj in this.UnderlyingDataSource) { - //Add the Editor Row to the Table - if (GetRowVisibility(obj)) + // Add the Editor Row to the Table + if (this.GetRowVisibility(obj)) { - AddEditorRow(obj); + this.AddEditorRow(obj); } } } else { table = new Table { ID = "tbl" }; - foreach (object obj in UnderlyingDataSource) + foreach (object obj in this.UnderlyingDataSource) { - if (GetRowVisibility(obj)) + if (this.GetRowVisibility(obj)) { - AddEditorRow(table, obj); + this.AddEditorRow(table, obj); } } - - //Add the Table to the Controls Collection - Controls.Add(table); + + // Add the Table to the Controls Collection + this.Controls.Add(table); } } } @@ -733,28 +783,31 @@ protected virtual void CreateEditor() /// ----------------------------------------------------------------------------- /// - /// GetCategory gets the Category of an object - /// + /// GetCategory gets the Category of an object. + /// + /// /// ----------------------------------------------------------------------------- protected virtual string GetCategory(object obj) { - var objProperty = (PropertyInfo) obj; + var objProperty = (PropertyInfo)obj; var categoryString = Null.NullString; - //Get Category Field - var categoryAttributes = objProperty.GetCustomAttributes(typeof (CategoryAttribute), true); + // Get Category Field + var categoryAttributes = objProperty.GetCustomAttributes(typeof(CategoryAttribute), true); if (categoryAttributes.Length > 0) { - var category = (CategoryAttribute) categoryAttributes[0]; + var category = (CategoryAttribute)categoryAttributes[0]; categoryString = category.Category; } + return categoryString; } /// ----------------------------------------------------------------------------- /// - /// GetGroups gets an array of Groups/Categories from the DataSource - /// + /// GetGroups gets an array of Groups/Categories from the DataSource. + /// + /// /// ----------------------------------------------------------------------------- protected virtual string[] GetGroups(IEnumerable arrObjects) { @@ -762,10 +815,10 @@ protected virtual string[] GetGroups(IEnumerable arrObjects) foreach (PropertyInfo objProperty in arrObjects) { - var categoryAttributes = objProperty.GetCustomAttributes(typeof (CategoryAttribute), true); + var categoryAttributes = objProperty.GetCustomAttributes(typeof(CategoryAttribute), true); if (categoryAttributes.Length > 0) { - var category = (CategoryAttribute) categoryAttributes[0]; + var category = (CategoryAttribute)categoryAttributes[0]; if (!arrGroups.Contains(category.Category)) { @@ -773,194 +826,165 @@ protected virtual string[] GetGroups(IEnumerable arrObjects) } } } + var strGroups = new string[arrGroups.Count]; for (int i = 0; i <= arrGroups.Count - 1; i++) { strGroups[i] = Convert.ToString(arrGroups[i]); } + return strGroups; } /// ----------------------------------------------------------------------------- /// - /// GetRowVisibility determines the Visibility of a row in the table + /// GetRowVisibility determines the Visibility of a row in the table. /// - /// The property + /// The property. + /// /// ----------------------------------------------------------------------------- protected virtual bool GetRowVisibility(object obj) { - var objProperty = (PropertyInfo) obj; + var objProperty = (PropertyInfo)obj; bool isVisible = true; - object[] browsableAttributes = objProperty.GetCustomAttributes(typeof (BrowsableAttribute), true); + object[] browsableAttributes = objProperty.GetCustomAttributes(typeof(BrowsableAttribute), true); if (browsableAttributes.Length > 0) { - var browsable = (BrowsableAttribute) browsableAttributes[0]; + var browsable = (BrowsableAttribute)browsableAttributes[0]; if (!browsable.Browsable) { isVisible = false; } } - if (!isVisible && EditMode == PropertyEditorMode.Edit) + + if (!isVisible && this.EditMode == PropertyEditorMode.Edit) { - //Check if property is required - as this will need to override visibility - object[] requiredAttributes = objProperty.GetCustomAttributes(typeof (RequiredAttribute), true); + // Check if property is required - as this will need to override visibility + object[] requiredAttributes = objProperty.GetCustomAttributes(typeof(RequiredAttribute), true); if (requiredAttributes.Length > 0) { - var required = (RequiredAttribute) requiredAttributes[0]; + var required = (RequiredAttribute)requiredAttributes[0]; if (required.Required) { isVisible = true; } } } + return isVisible; } /// ----------------------------------------------------------------------------- /// - /// Runs when an item is added to a collection type property + /// Runs when an item is added to a collection type property. /// /// ----------------------------------------------------------------------------- protected virtual void OnItemAdded(PropertyEditorEventArgs e) { - if (ItemAdded != null) + if (this.ItemAdded != null) { - ItemAdded(this, e); + this.ItemAdded(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Runs when an Editor is Created + /// Runs when an Editor is Created. /// /// ----------------------------------------------------------------------------- protected virtual void OnItemCreated(PropertyEditorItemEventArgs e) { - if (ItemCreated != null) + if (this.ItemCreated != null) { - ItemCreated(this, e); + this.ItemCreated(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Runs when an item is removed from a collection type property + /// Runs when an item is removed from a collection type property. /// /// ----------------------------------------------------------------------------- protected virtual void OnItemDeleted(PropertyEditorEventArgs e) { - if (ItemDeleted != null) + if (this.ItemDeleted != null) { - ItemDeleted(this, e); + this.ItemDeleted(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Runs just before the control is rendered + /// Runs just before the control is rendered. /// /// ----------------------------------------------------------------------------- protected override void OnPreRender(EventArgs e) { - if (_itemChanged) + if (this._itemChanged) { - //Rebind the control to the DataSource to make sure that the dependent - //editors are updated - DataBind(); + // Rebind the control to the DataSource to make sure that the dependent + // editors are updated + this.DataBind(); } - if (String.IsNullOrEmpty(CssClass)) + + if (string.IsNullOrEmpty(this.CssClass)) { - CssClass = "dnnForm"; + this.CssClass = "dnnForm"; } - - //Find the Min/Max buttons - if (GroupByMode == GroupByMode.Section && (_sections != null)) + + // Find the Min/Max buttons + if (this.GroupByMode == GroupByMode.Section && (this._sections != null)) { - foreach (DictionaryEntry key in _sections) + foreach (DictionaryEntry key in this._sections) { - var tbl = (Table) key.Value; - var icon = (Image) key.Key; - DNNClientAPI.EnableMinMax(icon, tbl, false, IconController.IconURL("Minus", "12X15"), IconController.IconURL("Plus","12X15"), DNNClientAPI.MinMaxPersistanceType.Page); + var tbl = (Table)key.Value; + var icon = (Image)key.Key; + DNNClientAPI.EnableMinMax(icon, tbl, false, IconController.IconURL("Minus", "12X15"), IconController.IconURL("Plus", "12X15"), DNNClientAPI.MinMaxPersistanceType.Page); } } + base.OnPreRender(e); - } - - #endregion - - #region Public Methods - + } + /// ----------------------------------------------------------------------------- /// - /// Binds the controls to the DataSource - /// - /// ----------------------------------------------------------------------------- - public override void DataBind() - { - //Invoke OnDataBinding so DataBinding Event is raised - base.OnDataBinding(EventArgs.Empty); - - //Clear Existing Controls - Controls.Clear(); - - //Clear Child View State as controls will be loaded from DataSource - ClearChildViewState(); - - //Start Tracking ViewState - TrackViewState(); - - //Create the Editor - CreateEditor(); - - //Set flag so CreateChildConrols should not be invoked later in control's lifecycle - ChildControlsCreated = true; - } - - #endregion - - #region Event Handlers - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is added to a collection type property + /// Runs when an item is added to a collection type property. /// /// ----------------------------------------------------------------------------- protected virtual void CollectionItemAdded(object sender, PropertyEditorEventArgs e) { - OnItemAdded(e); + this.OnItemAdded(e); } /// ----------------------------------------------------------------------------- /// - /// Runs when an item is removed from a collection type property + /// Runs when an item is removed from a collection type property. /// /// ----------------------------------------------------------------------------- protected virtual void CollectionItemDeleted(object sender, PropertyEditorEventArgs e) { - OnItemDeleted(e); + this.OnItemDeleted(e); } /// ----------------------------------------------------------------------------- /// - /// Runs when an Editor Is Created + /// Runs when an Editor Is Created. /// /// ----------------------------------------------------------------------------- protected virtual void EditorItemCreated(object sender, PropertyEditorItemEventArgs e) { - OnItemCreated(e); + this.OnItemCreated(e); } /// ----------------------------------------------------------------------------- /// - /// Runs when an Item in the List Is Changed + /// Runs when an Item in the List Is Changed. /// /// ----------------------------------------------------------------------------- protected virtual void ListItemChanged(object sender, PropertyEditorEventArgs e) { - _itemChanged = true; - } - - #endregion + this._itemChanged = true; + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorMode.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorMode.cs index 292ab2bf778..39f385f51ac 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorMode.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorMode.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- @@ -16,6 +16,6 @@ namespace DotNetNuke.UI.WebControls public enum PropertyEditorMode { Edit, - View + View, } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs index 384b9553cb7..b91117e7165 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs @@ -1,339 +1,334 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Data; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.UI.UserControls; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { - - /// - /// The PropertyLabelControl control provides a standard UI component for displaying - /// a label for a property. It contains a Label and Help Text and can be Data Bound. - /// - /// - /// - [ToolboxData("<{0}:PropertyLabelControl runat=server>")] - public class PropertyLabelControl : WebControl - { - - #region Private Members - - private string _ResourceKey; - protected LinkButton cmdHelp; - protected HtmlGenericControl label; - protected Label lblHelp; - protected Label lblLabel; + using System; + using System.ComponentModel; + using System.Data; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.UI.UserControls; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client.ClientResourceManagement; + + /// + /// The PropertyLabelControl control provides a standard UI component for displaying + /// a label for a property. It contains a Label and Help Text and can be Data Bound. + /// + /// + /// + [ToolboxData("<{0}:PropertyLabelControl runat=server>")] + public class PropertyLabelControl : WebControl + { + protected LinkButton cmdHelp; + protected HtmlGenericControl label; + private string _ResourceKey; + protected Label lblHelp; + protected Label lblLabel; protected Panel pnlTooltip; - protected Panel pnlHelp; - - #endregion - - #region Protected Members - - public PropertyLabelControl() - { - - } - - - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - - #endregion - - #region Public Properties - - /// - /// Gets and Sets the Caption Text if no ResourceKey is provided - /// - /// A string representing the Caption - [Browsable(true), Category("Appearance"), DefaultValue("Property"), Description("Enter Caption for the control.")] - public string Caption - { - get - { - EnsureChildControls(); - return lblLabel.Text; - } - set - { - EnsureChildControls(); - lblLabel.Text = value; - } - } - - public string AssociatedControlId - { - get - { - EnsureChildControls(); - return lblLabel.AssociatedControlID; - } - set - { - EnsureChildControls(); - lblLabel.AssociatedControlID = value; - } - } - - /// - /// Gets and Sets the related Edit Control - /// - /// A Control - [Browsable(false)] - public Control EditControl { get; set; } - - /// - /// Text is value of the Label Text if no ResourceKey is provided - /// - /// A string representing the Text - [Browsable(true), Category("Appearance"), DefaultValue(""), Description("Enter Help Text for the control.")] - public string HelpText - { - get - { - EnsureChildControls(); - return lblHelp.Text; - } - set - { - EnsureChildControls(); - lblHelp.Text = value; - } - } - - /// - /// ResourceKey is the root localization key for this control - /// - /// A string representing the Resource Key - /// This control will "standardise" the resource key names, so for instance - /// if the resource key is "Control", Control.Text is the label text key, Control.Help - /// is the label help text, Control.ErrorMessage is the Validation Error Message for the - /// control - /// - [Browsable(true), Category("Localization"), DefaultValue(""), Description("Enter the Resource key for the control.")] - public string ResourceKey - { - get - { - return _ResourceKey; - } - set - { - _ResourceKey = value; - - EnsureChildControls(); - - //Localize the Label and the Help text - lblHelp.Attributes["resourcekey"] = _ResourceKey + ".Help"; - lblLabel.Attributes["resourcekey"] = _ResourceKey + ".Text"; - } - } - - [Browsable(true), Category("Behavior"), DefaultValue(false), Description("Set whether the Help icon is displayed.")] - public bool ShowHelp - { - get - { - EnsureChildControls(); - return cmdHelp.Visible; - } - set - { - EnsureChildControls(); - cmdHelp.Visible = value; - } - } - - #region Data Properties - - /// - /// Gets and sets the value of the Field that is bound to the Label - /// - /// A string representing the Name of the Field - [Browsable(true), Category("Data"), DefaultValue(""), Description("Enter the name of the field that is data bound to the Label's Text property.")] - public string DataField { get; set; } - - /// - /// Gets and sets the DataSource that is bound to this control - /// - /// The DataSource object - [Browsable(false)] - public object DataSource { get; set; } - - #endregion - - #region Style Properties - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the value of the Label Style - /// - /// A string representing the Name of the Field - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), - Description("Set the Style for the Help Text.")] - public Style HelpStyle - { - get - { - EnsureChildControls(); - return pnlHelp.ControlStyle; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the value of the Label Style - /// - /// A string representing the Name of the Field - /// ----------------------------------------------------------------------------- - [Browsable(true), Category("Styles"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof (ExpandableObjectConverter)), - Description("Set the Style for the Label Text")] - public Style LabelStyle - { - get - { - EnsureChildControls(); - return lblLabel.ControlStyle; - } - } - - public bool Required { get; set; } + protected Panel pnlHelp; + + public PropertyLabelControl() + { + } + + /// + /// Gets or sets and Sets the Caption Text if no ResourceKey is provided. + /// + /// A string representing the Caption. + [Browsable(true)] + [Category("Appearance")] + [DefaultValue("Property")] + [Description("Enter Caption for the control.")] + public string Caption + { + get + { + this.EnsureChildControls(); + return this.lblLabel.Text; + } + + set + { + this.EnsureChildControls(); + this.lblLabel.Text = value; + } + } - #endregion + public string AssociatedControlId + { + get + { + this.EnsureChildControls(); + return this.lblLabel.AssociatedControlID; + } + + set + { + this.EnsureChildControls(); + this.lblLabel.AssociatedControlID = value; + } + } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + + /// + /// Gets or sets and Sets the related Edit Control. + /// + /// A Control. + [Browsable(false)] + public Control EditControl { get; set; } + + /// + /// Gets or sets text is value of the Label Text if no ResourceKey is provided. + /// + /// A string representing the Text. + [Browsable(true)] + [Category("Appearance")] + [DefaultValue("")] + [Description("Enter Help Text for the control.")] + public string HelpText + { + get + { + this.EnsureChildControls(); + return this.lblHelp.Text; + } + + set + { + this.EnsureChildControls(); + this.lblHelp.Text = value; + } + } + + /// + /// Gets or sets resourceKey is the root localization key for this control. + /// + /// A string representing the Resource Key. + /// This control will "standardise" the resource key names, so for instance + /// if the resource key is "Control", Control.Text is the label text key, Control.Help + /// is the label help text, Control.ErrorMessage is the Validation Error Message for the + /// control. + /// + [Browsable(true)] + [Category("Localization")] + [DefaultValue("")] + [Description("Enter the Resource key for the control.")] + public string ResourceKey + { + get + { + return this._ResourceKey; + } + + set + { + this._ResourceKey = value; - #endregion + this.EnsureChildControls(); - #region Protected Methods + // Localize the Label and the Help text + this.lblHelp.Attributes["resourcekey"] = this._ResourceKey + ".Help"; + this.lblLabel.Attributes["resourcekey"] = this._ResourceKey + ".Text"; + } + } + + [Browsable(true)] + [Category("Behavior")] + [DefaultValue(false)] + [Description("Set whether the Help icon is displayed.")] + public bool ShowHelp + { + get + { + this.EnsureChildControls(); + return this.cmdHelp.Visible; + } + + set + { + this.EnsureChildControls(); + this.cmdHelp.Visible = value; + } + } + + /// + /// Gets or sets and sets the value of the Field that is bound to the Label. + /// + /// A string representing the Name of the Field. + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] + [Description("Enter the name of the field that is data bound to the Label's Text property.")] + public string DataField { get; set; } + + /// + /// Gets or sets and sets the DataSource that is bound to this control. + /// + /// The DataSource object. + [Browsable(false)] + public object DataSource { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets and sets the value of the Label Style. + /// + /// A string representing the Name of the Field. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Help Text.")] + public Style HelpStyle + { + get + { + this.EnsureChildControls(); + return this.pnlHelp.ControlStyle; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets and sets the value of the Label Style. + /// + /// A string representing the Name of the Field. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Label Text")] + public Style LabelStyle + { + get + { + this.EnsureChildControls(); + return this.lblLabel.ControlStyle; + } + } - /// - /// CreateChildControls creates the control collection. - /// - protected override void CreateChildControls() - { - CssClass += "dnnLabel"; + public bool Required { get; set; } + + /// + /// CreateChildControls creates the control collection. + /// + protected override void CreateChildControls() + { + this.CssClass += "dnnLabel"; - label = new HtmlGenericControl { TagName = "label" }; + this.label = new HtmlGenericControl { TagName = "label" }; - if (!DesignMode) + if (!this.DesignMode) { - cmdHelp = new LinkButton { ID = ID + "_cmdHelp", CssClass = "dnnFormHelp", CausesValidation = false, EnableViewState = false, TabIndex = -1 }; - cmdHelp.Attributes.Add("aria-label", "Help"); - lblLabel = new Label { ID = ID + "_label", EnableViewState = false }; + this.cmdHelp = new LinkButton { ID = this.ID + "_cmdHelp", CssClass = "dnnFormHelp", CausesValidation = false, EnableViewState = false, TabIndex = -1 }; + this.cmdHelp.Attributes.Add("aria-label", "Help"); + this.lblLabel = new Label { ID = this.ID + "_label", EnableViewState = false }; - label.Controls.Add(lblLabel); + this.label.Controls.Add(this.lblLabel); - Controls.Add(label); - Controls.Add(cmdHelp); + this.Controls.Add(this.label); + this.Controls.Add(this.cmdHelp); } - pnlTooltip = new Panel { CssClass = "dnnTooltip" }; + this.pnlTooltip = new Panel { CssClass = "dnnTooltip" }; - pnlHelp = new Panel { ID = ID + "_pnlHelp", EnableViewState = false, CssClass = "dnnFormHelpContent dnnClear" }; + this.pnlHelp = new Panel { ID = this.ID + "_pnlHelp", EnableViewState = false, CssClass = "dnnFormHelpContent dnnClear" }; - pnlTooltip.Controls.Add(pnlHelp); - - lblHelp = new Label { ID = ID + "_lblHelp", EnableViewState = false }; - pnlHelp.Controls.Add(lblHelp); + this.pnlTooltip.Controls.Add(this.pnlHelp); + + this.lblHelp = new Label { ID = this.ID + "_lblHelp", EnableViewState = false }; + this.pnlHelp.Controls.Add(this.lblHelp); var aHelpPin = new HyperLink(); aHelpPin.CssClass = "pinHelp"; aHelpPin.Attributes.Add("href", "#"); aHelpPin.Attributes.Add("aria-label", "Pin"); - pnlHelp.Controls.Add(aHelpPin); - - //Controls.Add(label); - Controls.Add(pnlTooltip); - } - - /// - /// OnDataBinding runs when the Control is being Data Bound (It is triggered by - /// a call to Control.DataBind() - /// - protected override void OnDataBinding(EventArgs e) - { - //If there is a DataSource bind the relevent Properties - if (DataSource != null) - { - EnsureChildControls(); - if (!String.IsNullOrEmpty(DataField)) - { - //DataBind the Label (via the Resource Key) - var dataRow = (DataRowView) DataSource; - if (ResourceKey == string.Empty) - { - ResourceKey = Convert.ToString(dataRow[DataField]); - } - if (DesignMode) - { - label.InnerText = Convert.ToString(dataRow[DataField]); - } - } - } - } + this.pnlHelp.Controls.Add(aHelpPin); + + // Controls.Add(label); + this.Controls.Add(this.pnlTooltip); + } + + /// + /// OnDataBinding runs when the Control is being Data Bound (It is triggered by + /// a call to Control.DataBind(). + /// + protected override void OnDataBinding(EventArgs e) + { + // If there is a DataSource bind the relevent Properties + if (this.DataSource != null) + { + this.EnsureChildControls(); + if (!string.IsNullOrEmpty(this.DataField)) + { + // DataBind the Label (via the Resource Key) + var dataRow = (DataRowView)this.DataSource; + if (this.ResourceKey == string.Empty) + { + this.ResourceKey = Convert.ToString(dataRow[this.DataField]); + } + + if (this.DesignMode) + { + this.label.InnerText = Convert.ToString(dataRow[this.DataField]); + } + } + } + } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); - JavaScript.RegisterClientReference(Page, ClientAPI.ClientNamespaceReferences.dnn); + JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); - } - - /// - /// OnLoad runs just before the Control is rendered, and makes sure that any - /// properties are set properly before the control is rendered - /// - protected override void OnPreRender(EventArgs e) - { - //Make sure the Child Controls are created before assigning any properties - EnsureChildControls(); - - if (Required) + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); + } + + /// + /// OnLoad runs just before the Control is rendered, and makes sure that any + /// properties are set properly before the control is rendered. + /// + protected override void OnPreRender(EventArgs e) + { + // Make sure the Child Controls are created before assigning any properties + this.EnsureChildControls(); + + if (this.Required) { - lblLabel.CssClass += " dnnFormRequired"; + this.lblLabel.CssClass += " dnnFormRequired"; } - //DNNClientAPI.EnableMinMax(cmdHelp, pnlHelp, true, DNNClientAPI.MinMaxPersistanceType.None); - if (EditControl != null) - { - label.Attributes.Add("for", EditControl is EditControl ? ((EditControl)EditControl).EditControlClientId : EditControl.ClientID); - } + // DNNClientAPI.EnableMinMax(cmdHelp, pnlHelp, true, DNNClientAPI.MinMaxPersistanceType.None); + if (this.EditControl != null) + { + this.label.Attributes.Add("for", this.EditControl is EditControl ? ((EditControl)this.EditControl).EditControlClientId : this.EditControl.ClientID); + } - //make sure the help container have the default css class to active js handler. - if (!pnlHelp.ControlStyle.CssClass.Contains("dnnClear")) + // make sure the help container have the default css class to active js handler. + if (!this.pnlHelp.ControlStyle.CssClass.Contains("dnnClear")) { - pnlHelp.ControlStyle.CssClass = string.Format("dnnClear {0}", pnlHelp.ControlStyle.CssClass); + this.pnlHelp.ControlStyle.CssClass = string.Format("dnnClear {0}", this.pnlHelp.ControlStyle.CssClass); } - if(!pnlHelp.ControlStyle.CssClass.Contains("dnnFormHelpContent")) + + if (!this.pnlHelp.ControlStyle.CssClass.Contains("dnnFormHelpContent")) { - pnlHelp.ControlStyle.CssClass = string.Format("dnnFormHelpContent {0}", pnlHelp.ControlStyle.CssClass); + this.pnlHelp.ControlStyle.CssClass = string.Format("dnnFormHelpContent {0}", this.pnlHelp.ControlStyle.CssClass); } - } - - #endregion - } + } + } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertySortType.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertySortType.cs index 34dcee7327f..9d6c2075cbc 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertySortType.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertySortType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.WebControls { /// ----------------------------------------------------------------------------- @@ -18,6 +18,6 @@ public enum PropertySortType None = 0, Alphabetical, Category, - SortOrderAttribute + SortOrderAttribute, } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs index cbef5c14573..5aca6713b91 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs @@ -1,71 +1,66 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + + using DotNetNuke.Instrumentation; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: SettingInfo /// ----------------------------------------------------------------------------- /// - /// The SettingInfo class provides a helper class for the Settings Editor + /// The SettingInfo class provides a helper class for the Settings Editor. /// /// /// /// ----------------------------------------------------------------------------- public class SettingInfo { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SettingInfo)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SettingInfo)); private Type _Type; public SettingInfo(object name, object value) { - Name = Convert.ToString(name); - Value = value; - _Type = value.GetType(); - Editor = EditorInfo.GetEditor(-1); + this.Name = Convert.ToString(name); + this.Value = value; + this._Type = value.GetType(); + this.Editor = EditorInfo.GetEditor(-1); string strValue = Convert.ToString(value); bool IsFound = false; - if (_Type.IsEnum) + if (this._Type.IsEnum) { IsFound = true; } + if (!IsFound) { try { bool boolValue = bool.Parse(strValue); - Editor = EditorInfo.GetEditor("Checkbox"); + this.Editor = EditorInfo.GetEditor("Checkbox"); IsFound = true; } catch (Exception exc) { Logger.Error(exc); - } } + if (!IsFound) { try { int intValue = int.Parse(strValue); - Editor = EditorInfo.GetEditor("Integer"); + this.Editor = EditorInfo.GetEditor("Integer"); IsFound = true; } catch (Exception exc) { Logger.Error(exc); - } } } @@ -80,11 +75,12 @@ public Type Type { get { - return _Type; + return this._Type; } + set { - _Type = value; + this._Type = value; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs index 9a4a1516a01..f972a980dec 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.Collections; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls @@ -22,117 +17,105 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- /// /// The SettingsEditorControl control provides an Editor to edit DotNetNuke - /// Settings + /// Settings. /// /// /// /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:SettingsEditorControl runat=server>")] public class SettingsEditorControl : PropertyEditorControl - { - #region "Protected Properties" - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Underlying DataSource - /// - /// An IEnumerable + { /// ----------------------------------------------------------------------------- - protected override IEnumerable UnderlyingDataSource - { - get - { - return GetSettings(); - } - } - - #endregion - - #region "Public Properties" - - /// ----------------------------------------------------------------------------- /// - /// Gets and sets the CustomEditors that are used by this control + /// Gets or sets and sets the CustomEditors that are used by this control. /// - /// The CustomEditors object + /// The CustomEditors object. /// ----------------------------------------------------------------------------- [Browsable(false)] public Hashtable CustomEditors { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Visibility values that are used by this control + /// Gets or sets and sets the Visibility values that are used by this control. /// - /// The CustomEditors object + /// The CustomEditors object. /// ----------------------------------------------------------------------------- - public Hashtable Visibility { get; set; } - - #endregion - - #region "Private Methods" + public Hashtable Visibility { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Underlying DataSource. + /// + /// An IEnumerable. + /// ----------------------------------------------------------------------------- + protected override IEnumerable UnderlyingDataSource + { + get + { + return this.GetSettings(); + } + } + + protected override void AddEditorRow(Table table, object obj) + { + var info = (SettingInfo)obj; + this.AddEditorRow(table, info.Name, new SettingsEditorInfoAdapter(this.DataSource, obj, this.ID)); + } - /// ----------------------------------------------------------------------------- + protected override void AddEditorRow(Panel container, object obj) + { + var info = (SettingInfo)obj; + this.AddEditorRow(container, info.Name, new SettingsEditorInfoAdapter(this.DataSource, obj, this.ID)); + } + + /// ----------------------------------------------------------------------------- /// - /// GetSettings converts the DataSource into an ArrayList (IEnumerable) + /// GetSettings converts the DataSource into an ArrayList (IEnumerable). /// /// ----------------------------------------------------------------------------- private ArrayList GetSettings() { - var settings = (Hashtable) DataSource; + var settings = (Hashtable)this.DataSource; var arrSettings = new ArrayList(); IDictionaryEnumerator settingsEnumerator = settings.GetEnumerator(); while (settingsEnumerator.MoveNext()) { var info = new SettingInfo(settingsEnumerator.Key, settingsEnumerator.Value); - if ((CustomEditors != null) && (CustomEditors[settingsEnumerator.Key] != null)) + if ((this.CustomEditors != null) && (this.CustomEditors[settingsEnumerator.Key] != null)) { - info.Editor = Convert.ToString(CustomEditors[settingsEnumerator.Key]); + info.Editor = Convert.ToString(this.CustomEditors[settingsEnumerator.Key]); } + arrSettings.Add(info); } + arrSettings.Sort(new SettingNameComparer()); return arrSettings; - } - - #endregion - - #region "Protected Override Methods" - - protected override void AddEditorRow(Table table, object obj) - { - var info = (SettingInfo) obj; - AddEditorRow(table, info.Name, new SettingsEditorInfoAdapter(DataSource, obj, ID)); - } - - protected override void AddEditorRow(Panel container, object obj) - { - var info = (SettingInfo)obj; - AddEditorRow(container, info.Name, new SettingsEditorInfoAdapter(DataSource, obj, ID)); - } + } protected override void AddEditorRow(object obj) { - var info = (SettingInfo)obj; - AddEditorRow(this, info.Name, new SettingsEditorInfoAdapter(DataSource, obj, ID)); + var info = (SettingInfo)obj; + this.AddEditorRow(this, info.Name, new SettingsEditorInfoAdapter(this.DataSource, obj, this.ID)); } /// ----------------------------------------------------------------------------- /// - /// GetRowVisibility determines the Visibility of a row in the table + /// GetRowVisibility determines the Visibility of a row in the table. /// - /// The property + /// The property. + /// /// ----------------------------------------------------------------------------- protected override bool GetRowVisibility(object obj) { - var info = (SettingInfo) obj; + var info = (SettingInfo)obj; bool _IsVisible = true; - if ((Visibility != null) && (Visibility[info.Name] != null)) + if ((this.Visibility != null) && (this.Visibility[info.Name] != null)) { - _IsVisible = Convert.ToBoolean(Visibility[info.Name]); + _IsVisible = Convert.ToBoolean(this.Visibility[info.Name]); } + return _IsVisible; - } - - #endregion - } + } + } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs index d9ff3716c4f..2244c67add4 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs @@ -1,95 +1,87 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.UI.WebControls + // ReSharper restore CheckNamespace { + using System; + using System.Collections.Specialized; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + + /// + /// The VisibilityControl control provides a base control for defining visibility + /// options. + /// + /// + /// + [ToolboxData("<{0}:VisibilityControl runat=server>")] + public class VisibilityControl : WebControl, IPostBackDataHandler, INamingContainer + { + public event PropertyChangedEventHandler VisibilityChanged; + + /// + /// Gets or sets caption. + /// + /// A string representing the Name of the property. + public string Caption { get; set; } - /// - /// The VisibilityControl control provides a base control for defining visibility - /// options - /// - /// - /// - [ToolboxData("<{0}:VisibilityControl runat=server>")] - public class VisibilityControl : WebControl, IPostBackDataHandler, INamingContainer - { - protected ProfileVisibility Visibility - { - get { return Value as ProfileVisibility; } - set { Value = value; } - } - - #region Public Properties - - /// - /// Caption - /// - /// A string representing the Name of the property - public string Caption { get; set; } - - /// - /// Name is the name of the field as a string - /// - /// A string representing the Name of the property - public string Name { get; set; } + /// + /// Gets or sets name is the name of the field as a string. + /// + /// A string representing the Name of the property. + public string Name { get; set; } + + protected ProfileVisibility Visibility + { + get { return this.Value as ProfileVisibility; } + set { this.Value = value; } + } /// - /// The UserInfo object that represents the User whose profile is being displayed + /// Gets or sets the UserInfo object that represents the User whose profile is being displayed. /// public UserInfo User { get; set; } - /// - /// StringValue is the value of the control expressed as a String - /// - /// A string representing the Value - public object Value { get; set; } - - #endregion - - #region IPostBackDataHandler Members - - /// - /// LoadPostData loads the Post Back Data and determines whether the value has change - /// - /// A key to the PostBack Data to load - /// A name value collection of postback data - public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - var dataChanged = false; - var presentVisibility = Visibility.VisibilityMode; + /// + /// Gets or sets stringValue is the value of the control expressed as a String. + /// + /// A string representing the Value. + public object Value { get; set; } + + /// + /// LoadPostData loads the Post Back Data and determines whether the value has change. + /// + /// A key to the PostBack Data to load. + /// A name value collection of postback data. + /// + public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + var dataChanged = false; + var presentVisibility = this.Visibility.VisibilityMode; var postedValue = Convert.ToInt32(postCollection[postDataKey]); - var postedVisibility = (UserVisibilityMode) Enum.ToObject(typeof (UserVisibilityMode), postedValue); + var postedVisibility = (UserVisibilityMode)Enum.ToObject(typeof(UserVisibilityMode), postedValue); if (!presentVisibility.Equals(postedVisibility) || postedVisibility == UserVisibilityMode.FriendsAndGroups) - { + { if (postedVisibility == UserVisibilityMode.FriendsAndGroups) { var sb = new StringBuilder(); sb.Append("G:"); - foreach (var role in User.Social.Roles) + foreach (var role in this.User.Social.Roles) { if (postCollection[postDataKey + ":group_" + role.RoleID.ToString(CultureInfo.InvariantCulture)] != null) { @@ -98,84 +90,91 @@ public virtual bool LoadPostData(string postDataKey, NameValueCollection postCol } sb.Append(";R:"); - foreach (var relationship in User.Social.Relationships) + foreach (var relationship in this.User.Social.Relationships) { if (postCollection[postDataKey + ":relationship_" + relationship.RelationshipId.ToString(CultureInfo.InvariantCulture)] != null) { sb.Append(relationship.RelationshipId.ToString(CultureInfo.InvariantCulture) + ","); } } - - Value = new ProfileVisibility(User.PortalID, sb.ToString()) - { - VisibilityMode = postedVisibility - }; + + this.Value = new ProfileVisibility(this.User.PortalID, sb.ToString()) + { + VisibilityMode = postedVisibility, + }; } else { - Value = new ProfileVisibility - { - VisibilityMode = postedVisibility - }; + this.Value = new ProfileVisibility + { + VisibilityMode = postedVisibility, + }; } - dataChanged = true; - } - return dataChanged; - } - - /// - /// RaisePostDataChangedEvent runs when the PostBackData has changed. It triggers - /// a ValueChanged Event - /// - public void RaisePostDataChangedEvent() - { - //Raise the VisibilityChanged Event - var args = new PropertyEditorEventArgs(Name) {Value = Value}; - OnVisibilityChanged(args); - } + dataChanged = true; + } + + return dataChanged; + } - #endregion - - #region Events + /// + /// RaisePostDataChangedEvent runs when the PostBackData has changed. It triggers + /// a ValueChanged Event. + /// + public void RaisePostDataChangedEvent() + { + // Raise the VisibilityChanged Event + var args = new PropertyEditorEventArgs(this.Name) { Value = this.Value }; + this.OnVisibilityChanged(args); + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); - public event PropertyChangedEventHandler VisibilityChanged; - - #endregion + JavaScript.RequestRegistration(CommonJs.jQuery); + } - #region Private Methods + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.Page.RegisterRequiresPostBack(this); + this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "visibleChange", "$(document).ready(function(){$('.dnnFormVisibility').on('click', 'input[type=radio]', function(){$(this).parent().parent().find('ul').hide();$(this).parent().next('ul').show();});});", true); + } + private void RenderVisibility(HtmlTextWriter writer, string optionValue, UserVisibilityMode selectedVisibility, string optionText) { - //Render Li + // Render Li writer.RenderBeginTag(HtmlTextWriterTag.Li); - //Render radio button + // Render radio button writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); - writer.AddAttribute("aria-label", ID); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); + writer.AddAttribute("aria-label", this.ID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.AddAttribute(HtmlTextWriterAttribute.Value, optionValue); - if ((Visibility.VisibilityMode == selectedVisibility)) + if (this.Visibility.VisibilityMode == selectedVisibility) { writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); } + writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.Write(optionText); writer.RenderEndTag(); - //Close Li + // Close Li writer.RenderEndTag(); } private void RenderCheckboxItem(HtmlTextWriter writer, string prefix, string value, string text, bool selected) { - //Render Li + // Render Li writer.RenderBeginTag(HtmlTextWriterTag.Li); - //Render radio button + // Render radio button writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox"); - writer.AddAttribute("aria-label", ID); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID + prefix + value); + writer.AddAttribute("aria-label", this.ID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + prefix + value); writer.AddAttribute(HtmlTextWriterAttribute.Value, value); if (selected) { @@ -186,129 +185,107 @@ private void RenderCheckboxItem(HtmlTextWriter writer, string prefix, string val writer.Write(text); writer.RenderEndTag(); - //Close Li + // Close Li writer.RenderEndTag(); - } private void RenderGroups(HtmlTextWriter writer) { - foreach (var group in User.Social.Roles.Where((role) => role.SecurityMode != SecurityMode.SecurityRole)) + foreach (var group in this.User.Social.Roles.Where((role) => role.SecurityMode != SecurityMode.SecurityRole)) { - RenderCheckboxItem(writer, ":group_", group.RoleID.ToString(CultureInfo.InvariantCulture), + this.RenderCheckboxItem(writer, ":group_", group.RoleID.ToString(CultureInfo.InvariantCulture), group.RoleName, - Visibility.RoleVisibilities.Count(r => r.RoleID == group.RoleID) == 1); + this.Visibility.RoleVisibilities.Count(r => r.RoleID == group.RoleID) == 1); } } private void RenderRelationships(HtmlTextWriter writer) { - foreach (var relationship in User.Social.Relationships) + foreach (var relationship in this.User.Social.Relationships) { - RenderCheckboxItem(writer, ":relationship_", relationship.RelationshipId.ToString(CultureInfo.InvariantCulture), + this.RenderCheckboxItem(writer, ":relationship_", relationship.RelationshipId.ToString(CultureInfo.InvariantCulture), relationship.Name, - Visibility.RelationshipVisibilities.Count(r => r.RelationshipId == relationship.RelationshipId) == 1); + this.Visibility.RelationshipVisibilities.Count(r => r.RelationshipId == relationship.RelationshipId) == 1); } - } - - #endregion - - #region Protected Methods + } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - JavaScript.RequestRegistration(CommonJs.jQuery); - } - - protected override void OnPreRender(EventArgs e) + /// + /// OnVisibilityChanged runs when the Visibility has changed. It raises the VisibilityChanged + /// Event. + /// + protected virtual void OnVisibilityChanged(PropertyEditorEventArgs e) { - base.OnPreRender(e); - - Page.RegisterRequiresPostBack(this); - Page.ClientScript.RegisterClientScriptBlock(GetType(), "visibleChange", "$(document).ready(function(){$('.dnnFormVisibility').on('click', 'input[type=radio]', function(){$(this).parent().parent().find('ul').hide();$(this).parent().next('ul').show();});});", true); + if (this.VisibilityChanged != null) + { + this.VisibilityChanged(this, e); + } } - /// - /// OnVisibilityChanged runs when the Visibility has changed. It raises the VisibilityChanged - /// Event - /// - protected virtual void OnVisibilityChanged(PropertyEditorEventArgs e) - { - if (VisibilityChanged != null) - { - VisibilityChanged(this, e); - } - } - - /// - /// Render renders the control - /// - /// A HtmlTextWriter. - protected override void Render(HtmlTextWriter writer) - { - //Render Div container + /// + /// Render renders the control. + /// + /// A HtmlTextWriter. + protected override void Render(HtmlTextWriter writer) + { + // Render Div container writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnFormVisibility dnnDropdownSettings"); - writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); - writer.RenderBeginTag(HtmlTextWriterTag.Div); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.RenderBeginTag(HtmlTextWriterTag.Div); - //Render dnnButtonDropdown + // Render dnnButtonDropdown writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnButtonDropdown"); writer.RenderBeginTag(HtmlTextWriterTag.Div); - //Render dnnButton Icon + // Render dnnButton Icon writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnButtonIcon"); writer.RenderBeginTag(HtmlTextWriterTag.Div); - //writer.AddAttribute(HtmlTextWriterAttribute.Src, IconController.IconURL("Lock")); - //writer.RenderBeginTag(HtmlTextWriterTag.Img); - - //Close Image Tag - //writer.RenderEndTag(); + // writer.AddAttribute(HtmlTextWriterAttribute.Src, IconController.IconURL("Lock")); + // writer.RenderBeginTag(HtmlTextWriterTag.Img); - //Close dnnButtonIcon + // Close Image Tag + // writer.RenderEndTag(); + + // Close dnnButtonIcon writer.RenderEndTag(); - //render dnnButton Arrow + // render dnnButton Arrow writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnButtonArrow"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.RenderEndTag(); - //Close dnnButton Dropdown + // Close dnnButton Dropdown writer.RenderEndTag(); - //Render UL for radio Button List - //writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none"); + // Render UL for radio Button List + // writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnButtonDropdown-ul"); writer.RenderBeginTag(HtmlTextWriterTag.Ul); - RenderVisibility(writer, "0", UserVisibilityMode.AllUsers, Localization.GetString("Public").Trim()); + this.RenderVisibility(writer, "0", UserVisibilityMode.AllUsers, Localization.GetString("Public").Trim()); - RenderVisibility(writer, "1", UserVisibilityMode.MembersOnly, Localization.GetString("MembersOnly").Trim()); + this.RenderVisibility(writer, "1", UserVisibilityMode.MembersOnly, Localization.GetString("MembersOnly").Trim()); - RenderVisibility(writer, "2", UserVisibilityMode.AdminOnly, Localization.GetString("AdminOnly").Trim()); + this.RenderVisibility(writer, "2", UserVisibilityMode.AdminOnly, Localization.GetString("AdminOnly").Trim()); - RenderVisibility(writer, "3", UserVisibilityMode.FriendsAndGroups, Localization.GetString("FriendsGroups").Trim()); + this.RenderVisibility(writer, "3", UserVisibilityMode.FriendsAndGroups, Localization.GetString("FriendsGroups").Trim()); - //Render UL for check Box List - writer.AddStyleAttribute(HtmlTextWriterStyle.Display, Visibility.VisibilityMode == UserVisibilityMode.FriendsAndGroups ? "block" : "none"); + // Render UL for check Box List + writer.AddStyleAttribute(HtmlTextWriterStyle.Display, this.Visibility.VisibilityMode == UserVisibilityMode.FriendsAndGroups ? "block" : "none"); writer.RenderBeginTag(HtmlTextWriterTag.Ul); - RenderRelationships(writer); - RenderGroups(writer); + this.RenderRelationships(writer); + this.RenderGroups(writer); - //Close UL + // Close UL writer.RenderEndTag(); - //Close UL + // Close UL writer.RenderEndTag(); - //Close Div - writer.RenderEndTag(); - } - - #endregion - } + // Close Div + writer.RenderEndTag(); + } + } } diff --git a/DNN Platform/Library/WebControls/WebControlBase.cs b/DNN Platform/Library/WebControls/WebControlBase.cs index c20c663e693..0d2a4471df4 100644 --- a/DNN Platform/Library/WebControls/WebControlBase.cs +++ b/DNN Platform/Library/WebControls/WebControlBase.cs @@ -1,41 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.ComponentModel; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; + using System.ComponentModel; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + public abstract class WebControlBase : WebControl - { - #region "Private Members" - - private string _styleSheetUrl = ""; - private string _theme = ""; - - #endregion - - #region "Public Properties" - + { + private string _styleSheetUrl = string.Empty; + private string _theme = string.Empty; + public string Theme { get { - return _theme; + return this._theme; } + set { - _theme = value; + this._theme = value; } } @@ -51,18 +41,19 @@ public string StyleSheetUrl { get { - if ((_styleSheetUrl.StartsWith("~"))) + if (this._styleSheetUrl.StartsWith("~")) { - return Globals.ResolveUrl(_styleSheetUrl); + return Globals.ResolveUrl(this._styleSheetUrl); } else { - return _styleSheetUrl; + return this._styleSheetUrl; } } + set { - _styleSheetUrl = value; + this._styleSheetUrl = value; } } @@ -70,21 +61,20 @@ public bool IsHostMenu { get { - return Globals.IsHostTab(PortalSettings.ActiveTab.TabID); + return Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { get { return PortalController.Instance.GetCurrentPortalSettings(); } - } - - #endregion - + } + public abstract string HtmlOutput { get; } [Obsolete("There is no longer the concept of an Admin Page. All pages are controlled by Permissions. Scheduled removal in v11.0.0.", true)] @@ -99,7 +89,7 @@ public bool IsAdminMenu protected override void RenderContents(HtmlTextWriter output) { - output.Write(HtmlOutput); + output.Write(this.HtmlOutput); } } } diff --git a/DNN Platform/Library/packages.config b/DNN Platform/Library/packages.config index b5f9f070330..5c1798ceab2 100644 --- a/DNN Platform/Library/packages.config +++ b/DNN Platform/Library/packages.config @@ -11,4 +11,5 @@ + \ No newline at end of file diff --git a/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs b/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs index 2a9bdc9974c..2f06dabc0df 100644 --- a/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs +++ b/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Upgrade; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.Components { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Upgrade; + public class CoreMessagingBusinessController : IUpgradeable { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (CoreMessagingBusinessController)); - #region Implementation of IUpgradeable - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CoreMessagingBusinessController)); + public string UpgradeModule(string Version) { try @@ -35,7 +34,7 @@ public string UpgradeModule(string Version) { if (portal.UserTabId > Null.NullInteger) { - //Find TabInfo + // Find TabInfo var tab = TabController.Instance.GetTab(portal.UserTabId, portal.PortalID, true); if (tab != null) { @@ -43,11 +42,11 @@ public string UpgradeModule(string Version) { if (module.DesktopModule.FriendlyName == "Messaging") { - //Delete the Module from the Modules list + // Delete the Module from the Modules list ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); - //Add new module to the page - Upgrade.AddModuleToPage(tab, moduleDefinition.ModuleDefID, "Message Center", "", true); + // Add new module to the page + Upgrade.AddModuleToPage(tab, moduleDefinition.ModuleDefID, "Message Center", string.Empty, true); break; } @@ -56,8 +55,10 @@ public string UpgradeModule(string Version) } } } + break; } + return "Success"; } catch (Exception exc) @@ -66,8 +67,6 @@ public string UpgradeModule(string Version) return "Failed"; } - } - - #endregion + } } } diff --git a/DNN Platform/Modules/CoreMessaging/CoreMessaging.dnn b/DNN Platform/Modules/CoreMessaging/CoreMessaging.dnn index 18529ca5bd4..690158b1800 100644 --- a/DNN Platform/Modules/CoreMessaging/CoreMessaging.dnn +++ b/DNN Platform/Modules/CoreMessaging/CoreMessaging.dnn @@ -1,6 +1,6 @@ - + Message Center Core Messaging module allows users to message each other. ~/DesktopModules/CoreMessaging/Images/messaging_32X32.png diff --git a/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj b/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj index 30aa56e6534..8c3d10a9623 100644 --- a/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj +++ b/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj @@ -1,210 +1,218 @@ - - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {5DEAB0D5-0F54-44C9-A167-F48264A04B3D} - {349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - Properties - DotNetNuke.Modules.CoreMessaging - DotNetNuke.Modules.CoreMessaging - v4.7.2 - 512 - - true - - - 4.0 - - - - - - ..\..\..\..\Evoq.Content\ - true - - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 1 - bin\DotNetNuke.Modules.CoreMessaging.XML - 1591 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - bin\DotNetNuke.Modules.CoreMessaging.XML - 1591 - 7 - - - - False - ..\..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll - - - False - ..\..\DotNetNuke.Web.Client\bin\DotNetNuke.Web.Client.dll - - - - ..\..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll - False - True - - - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - - - - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll - - - - - - - - Properties\SolutionInfo.cs - - - - - - - - - Subscriptions.ascx - ASPXCodeBehind - - - Subscriptions.ascx - - - View.ascx - ASPXCodeBehind - - - View.ascx - - - - - - - - - - - - Designer - - - - - - - - - - - - - - - - - - - - - - - - - - - ASPXCodeBehind - - - - - - - - Designer - - - - - - - - {ee1329fe-fd88-4e1a-968c-345e394ef080} - DotNetNuke.Web - False - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - False - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - False - True - 9081 - / - - - False - True - http://localhost/DNN_Platform - False - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {5DEAB0D5-0F54-44C9-A167-F48264A04B3D} + {349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + Library + Properties + DotNetNuke.Modules.CoreMessaging + DotNetNuke.Modules.CoreMessaging + v4.7.2 + 512 + + true + + + 4.0 + + + + + + ..\..\..\..\Evoq.Content\ + true + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 1 + bin\DotNetNuke.Modules.CoreMessaging.XML + 1591 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + bin\DotNetNuke.Modules.CoreMessaging.XML + 1591 + 7 + + + + False + ..\..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll + + + False + ..\..\DotNetNuke.Web.Client\bin\DotNetNuke.Web.Client.dll + + + + ..\..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + False + True + + + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + + + + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll + + + + + + + + Properties\SolutionInfo.cs + + + + + + + + + Subscriptions.ascx + ASPXCodeBehind + + + Subscriptions.ascx + + + View.ascx + ASPXCodeBehind + + + View.ascx + + + + + + + + + + + + stylecop.json + + + Designer + + + + + + + + + + + + + + + + + + + + + + + + + + + ASPXCodeBehind + + + + + + + + Designer + + + + + + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + False + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + False + + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + False + True + 9081 + / + + + False + True + http://localhost/DNN_Platform + False + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/DNN Platform/Modules/CoreMessaging/Properties/AssemblyInfo.cs b/DNN Platform/Modules/CoreMessaging/Properties/AssemblyInfo.cs index b20796980eb..748caeb9d3a 100644 --- a/DNN Platform/Modules/CoreMessaging/Properties/AssemblyInfo.cs +++ b/DNN Platform/Modules/CoreMessaging/Properties/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Modules.CoreMessaging")] [assembly: AssemblyDescription("Core Messaging Module")] -// 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 +// 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)] diff --git a/DNN Platform/Modules/CoreMessaging/Services/CoreMessagingRouteMapper.cs b/DNN Platform/Modules/CoreMessaging/Services/CoreMessagingRouteMapper.cs index fcbe958b9dd..436db678463 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/CoreMessagingRouteMapper.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/CoreMessagingRouteMapper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.Services { + using DotNetNuke.Web.Api; + public sealed class CoreMessagingRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) diff --git a/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs b/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs index 48cf628fd6d..04c2fe2daa6 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Web; -using System.Web.Http; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.Services { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net.Http; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + using Newtonsoft.Json; + public class FileUploadController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FileUploadController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileUploadController)); private readonly IFileManager _fileManager = FileManager.Instance; private readonly IFolderManager _folderManager = FolderManager.Instance; @@ -31,23 +32,23 @@ public HttpResponseMessage UploadFile() var statuses = new List(); try { - //todo can we eliminate the HttpContext here - UploadWholeFile(HttpContextSource.Current, statuses); + // todo can we eliminate the HttpContext here + this.UploadWholeFile(HttpContextSource.Current, statuses); } catch (Exception exc) { Logger.Error(exc); } - return IframeSafeJson(statuses); + return this.IframeSafeJson(statuses); } private HttpResponseMessage IframeSafeJson(List statuses) { - //return json but label it as plain text + // return json but label it as plain text return new HttpResponseMessage { - Content = new StringContent(JsonConvert.SerializeObject(statuses)) + Content = new StringContent(JsonConvert.SerializeObject(statuses)), }; } @@ -57,21 +58,25 @@ private void UploadWholeFile(HttpContextBase context, ICollection s for (var i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; - if (file == null) continue; - + if (file == null) + { + continue; + } + var fileName = Path.GetFileName(file.FileName); try { - var userFolder = _folderManager.GetUserFolder(UserInfo); + var userFolder = this._folderManager.GetUserFolder(this.UserInfo); - //todo: deal with the case where the exact file name already exists. - var fileInfo = _fileManager.AddFile(userFolder, fileName, file.InputStream, true); + // todo: deal with the case where the exact file name already exists. + var fileInfo = this._fileManager.AddFile(userFolder, fileName, file.InputStream, true); var fileIcon = Entities.Icons.IconController.IconURL("Ext" + fileInfo.Extension, "32x32"); if (!File.Exists(context.Server.MapPath(fileIcon))) { fileIcon = Entities.Icons.IconController.IconURL("File", "32x32"); } + statuses.Add(new FilesStatus { success = true, @@ -92,7 +97,7 @@ private void UploadWholeFile(HttpContextBase context, ICollection s { success = false, name = fileName, - message = "File type not allowed." + message = "File type not allowed.", }); } } diff --git a/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs b/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs index 041e13be874..489aec3f998 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs @@ -1,26 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.Services { public class FilesStatus { - // ReSharper disable InconsistentNaming + // ReSharper restore InconsistentNaming + public FilesStatus() + { + } + + // ReSharper disable InconsistentNaming public bool success { get; set; } + public string name { get; set; } + public string extension { get; set; } - public string type { get; set; } - public int size { get; set; } - public string progress { get; set; } - public string url { get; set; } - public string thumbnail_url { get; set; } - public string message { get; set; } + + public string type { get; set; } + + public int size { get; set; } + + public string progress { get; set; } + + public string url { get; set; } + + public string thumbnail_url { get; set; } + + public string message { get; set; } + public int id { get; set; } - // ReSharper restore InconsistentNaming - - public FilesStatus () - { - } - } + } } diff --git a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs index 37c2b47e2a7..3a7d22425bc 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs @@ -1,54 +1,54 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Dynamic; -using System.Net; -using System.Web; -using System.Web.Http; -using System.Net.Http; -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Modules.CoreMessaging.ViewModels; -using DotNetNuke.Security; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.Services { + using System; + using System.Collections.Generic; + using System.Dynamic; + using System.Net; + using System.Net.Http; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.CoreMessaging.ViewModels; + using DotNetNuke.Security; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [SupportedModules("DotNetNuke.Modules.CoreMessaging")] [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] [DnnAuthorize] public class MessagingServiceController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (MessagingServiceController)); - #region Public Methods - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MessagingServiceController)); + [HttpGet] public HttpResponseMessage Inbox(int afterMessageId, int numberOfRecords) { try { - var messageBoxView = InternalMessagingController.Instance.GetRecentInbox(UserInfo.UserID, afterMessageId, numberOfRecords); + var messageBoxView = InternalMessagingController.Instance.GetRecentInbox(this.UserInfo.UserID, afterMessageId, numberOfRecords); var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - messageBoxView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(UserInfo.UserID, portalId); - messageBoxView.TotalConversations = InternalMessagingController.Instance.CountConversations(UserInfo.UserID, portalId); + messageBoxView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(this.UserInfo.UserID, portalId); + messageBoxView.TotalConversations = InternalMessagingController.Instance.CountConversations(this.UserInfo.UserID, portalId); - return Request.CreateResponse(HttpStatusCode.OK, messageBoxView); + return this.Request.CreateResponse(HttpStatusCode.OK, messageBoxView); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -57,17 +57,17 @@ public HttpResponseMessage Sentbox(int afterMessageId, int numberOfRecords) { try { - var messageBoxView = InternalMessagingController.Instance.GetRecentSentbox(UserInfo.UserID, afterMessageId, numberOfRecords); + var messageBoxView = InternalMessagingController.Instance.GetRecentSentbox(this.UserInfo.UserID, afterMessageId, numberOfRecords); var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - messageBoxView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(UserInfo.UserID, portalId); - messageBoxView.TotalConversations = InternalMessagingController.Instance.CountSentConversations(UserInfo.UserID, portalId); + messageBoxView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(this.UserInfo.UserID, portalId); + messageBoxView.TotalConversations = InternalMessagingController.Instance.CountSentConversations(this.UserInfo.UserID, portalId); - return Request.CreateResponse(HttpStatusCode.OK, messageBoxView); + return this.Request.CreateResponse(HttpStatusCode.OK, messageBoxView); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -76,17 +76,17 @@ public HttpResponseMessage Archived(int afterMessageId, int numberOfRecords) { try { - var messageBoxView = InternalMessagingController.Instance.GetArchivedMessages(UserInfo.UserID, afterMessageId, numberOfRecords); + var messageBoxView = InternalMessagingController.Instance.GetArchivedMessages(this.UserInfo.UserID, afterMessageId, numberOfRecords); var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - messageBoxView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(UserInfo.UserID, portalId); - messageBoxView.TotalConversations = InternalMessagingController.Instance.CountArchivedConversations(UserInfo.UserID, portalId); + messageBoxView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(this.UserInfo.UserID, portalId); + messageBoxView.TotalConversations = InternalMessagingController.Instance.CountArchivedConversations(this.UserInfo.UserID, portalId); - return Request.CreateResponse(HttpStatusCode.OK, messageBoxView); + return this.Request.CreateResponse(HttpStatusCode.OK, messageBoxView); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -96,18 +96,18 @@ public HttpResponseMessage Thread(int conversationId, int afterMessageId, int nu try { var totalRecords = 0; - var messageThreadsView = InternalMessagingController.Instance.GetMessageThread(conversationId, UserInfo.UserID, afterMessageId, numberOfRecords, ref totalRecords); + var messageThreadsView = InternalMessagingController.Instance.GetMessageThread(conversationId, this.UserInfo.UserID, afterMessageId, numberOfRecords, ref totalRecords); var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - messageThreadsView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(UserInfo.UserID, portalId); + messageThreadsView.TotalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(this.UserInfo.UserID, portalId); messageThreadsView.TotalThreads = InternalMessagingController.Instance.CountMessagesByConversation(conversationId); messageThreadsView.TotalArchivedThreads = InternalMessagingController.Instance.CountArchivedMessagesByConversation(conversationId); - return Request.CreateResponse(HttpStatusCode.OK, messageThreadsView); + return this.Request.CreateResponse(HttpStatusCode.OK, messageThreadsView); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -119,19 +119,19 @@ public HttpResponseMessage Reply(ReplyDTO postData) { postData.Body = HttpUtility.UrlDecode(postData.Body); var messageId = InternalMessagingController.Instance.ReplyMessage(postData.ConversationId, postData.Body, postData.FileIds); - var message = ToExpandoObject(InternalMessagingController.Instance.GetMessage(messageId)); + var message = this.ToExpandoObject(InternalMessagingController.Instance.GetMessage(messageId)); var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - var totalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(UserInfo.UserID, portalId); + var totalNewThreads = InternalMessagingController.Instance.CountUnreadMessages(this.UserInfo.UserID, portalId); var totalThreads = InternalMessagingController.Instance.CountMessagesByConversation(postData.ConversationId); var totalArchivedThreads = InternalMessagingController.Instance.CountArchivedMessagesByConversation(postData.ConversationId); - return Request.CreateResponse(HttpStatusCode.OK, new { Conversation = message, TotalNewThreads = totalNewThreads, TotalThreads = totalThreads, TotalArchivedThreads = totalArchivedThreads }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Conversation = message, TotalNewThreads = totalNewThreads, TotalThreads = totalThreads, TotalArchivedThreads = totalArchivedThreads }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -141,13 +141,13 @@ public HttpResponseMessage MarkArchived(ConversationDTO postData) { try { - InternalMessagingController.Instance.MarkArchived(postData.ConversationId, UserInfo.UserID); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + InternalMessagingController.Instance.MarkArchived(postData.ConversationId, this.UserInfo.UserID); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -157,13 +157,13 @@ public HttpResponseMessage MarkUnArchived(ConversationDTO postData) { try { - InternalMessagingController.Instance.MarkUnArchived(postData.ConversationId, UserInfo.UserID); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + InternalMessagingController.Instance.MarkUnArchived(postData.ConversationId, this.UserInfo.UserID); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -173,13 +173,13 @@ public HttpResponseMessage MarkRead(ConversationDTO postData) { try { - InternalMessagingController.Instance.MarkRead(postData.ConversationId, UserInfo.UserID); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + InternalMessagingController.Instance.MarkRead(postData.ConversationId, this.UserInfo.UserID); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -189,13 +189,13 @@ public HttpResponseMessage MarkUnRead(ConversationDTO postData) { try { - InternalMessagingController.Instance.MarkUnRead(postData.ConversationId, UserInfo.UserID); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + InternalMessagingController.Instance.MarkUnRead(postData.ConversationId, this.UserInfo.UserID); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -205,13 +205,13 @@ public HttpResponseMessage DeleteUserFromConversation(ConversationDTO postData) { try { - InternalMessagingController.Instance.DeleteUserFromConversation(postData.ConversationId, UserInfo.UserID); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + InternalMessagingController.Instance.DeleteUserFromConversation(postData.ConversationId, this.UserInfo.UserID); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -221,18 +221,18 @@ public HttpResponseMessage Notifications(int afterNotificationId, int numberOfRe try { var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - var notificationsDomainModel = NotificationsController.Instance.GetNotifications(UserInfo.UserID, portalId, afterNotificationId, numberOfRecords); + var notificationsDomainModel = NotificationsController.Instance.GetNotifications(this.UserInfo.UserID, portalId, afterNotificationId, numberOfRecords); var notificationsViewModel = new NotificationsViewModel { - TotalNotifications = NotificationsController.Instance.CountNotifications(UserInfo.UserID, portalId), - Notifications = new List(notificationsDomainModel.Count) + TotalNotifications = NotificationsController.Instance.CountNotifications(this.UserInfo.UserID, portalId), + Notifications = new List(notificationsDomainModel.Count), }; foreach (var notification in notificationsDomainModel) { - var user = UserController.Instance.GetUser(PortalSettings.PortalId, notification.SenderUserID); - var displayName = (user != null ? user.DisplayName : ""); + var user = UserController.Instance.GetUser(this.PortalSettings.PortalId, notification.SenderUserID); + var displayName = user != null ? user.DisplayName : string.Empty; var notificationViewModel = new NotificationViewModel { @@ -244,7 +244,7 @@ public HttpResponseMessage Notifications(int afterNotificationId, int numberOfRe SenderAvatar = UserController.Instance.GetUserProfilePictureUrl(notification.SenderUserID, 64, 64), SenderProfileUrl = Globals.UserProfileURL(notification.SenderUserID), SenderDisplayName = displayName, - Actions = new List() + Actions = new List(), }; var notificationType = NotificationsController.Instance.GetNotificationType(notification.NotificationTypeID); @@ -254,10 +254,10 @@ public HttpResponseMessage Notifications(int afterNotificationId, int numberOfRe { var notificationActionViewModel = new NotificationActionViewModel { - Name = LocalizeActionString(notificationTypeAction.NameResourceKey, notificationType.DesktopModuleId), - Description = LocalizeActionString(notificationTypeAction.DescriptionResourceKey, notificationType.DesktopModuleId), - Confirm = LocalizeActionString(notificationTypeAction.ConfirmResourceKey, notificationType.DesktopModuleId), - APICall = notificationTypeAction.APICall + Name = this.LocalizeActionString(notificationTypeAction.NameResourceKey, notificationType.DesktopModuleId), + Description = this.LocalizeActionString(notificationTypeAction.DescriptionResourceKey, notificationType.DesktopModuleId), + Confirm = this.LocalizeActionString(notificationTypeAction.ConfirmResourceKey, notificationType.DesktopModuleId), + APICall = notificationTypeAction.APICall, }; notificationViewModel.Actions.Add(notificationActionViewModel); @@ -269,20 +269,20 @@ public HttpResponseMessage Notifications(int afterNotificationId, int numberOfRe { Name = Localization.GetString("Dismiss.Text"), Description = Localization.GetString("DismissNotification.Text"), - Confirm = "", - APICall = "API/InternalServices/NotificationsService/Dismiss" + Confirm = string.Empty, + APICall = "API/InternalServices/NotificationsService/Dismiss", }); } notificationsViewModel.Notifications.Add(notificationViewModel); } - return Request.CreateResponse(HttpStatusCode.OK, notificationsViewModel); + return this.Request.CreateResponse(HttpStatusCode.OK, notificationsViewModel); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -292,12 +292,12 @@ public HttpResponseMessage CheckReplyHasRecipients(int conversationId) try { var recipientCount = InternalMessagingController.Instance.CheckReplyHasRecipients(conversationId, UserController.Instance.GetCurrentUserInfo().UserID); - return Request.CreateResponse(HttpStatusCode.OK, recipientCount); + return this.Request.CreateResponse(HttpStatusCode.OK, recipientCount); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -307,13 +307,13 @@ public HttpResponseMessage CountNotifications() try { var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - int notifications = NotificationsController.Instance.CountNotifications(UserInfo.UserID, portalId); - return Request.CreateResponse(HttpStatusCode.OK, notifications); + int notifications = NotificationsController.Instance.CountNotifications(this.UserInfo.UserID, portalId); + return this.Request.CreateResponse(HttpStatusCode.OK, notifications); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -323,13 +323,13 @@ public HttpResponseMessage CountUnreadMessages() try { var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); - var unreadMessages = InternalMessagingController.Instance.CountUnreadMessages(UserInfo.UserID, portalId); - return Request.CreateResponse(HttpStatusCode.OK, unreadMessages); + var unreadMessages = InternalMessagingController.Instance.CountUnreadMessages(this.UserInfo.UserID, portalId); + return this.Request.CreateResponse(HttpStatusCode.OK, unreadMessages); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -341,16 +341,16 @@ public HttpResponseMessage GetTotals() var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID); var totalsViewModel = new TotalsViewModel { - TotalUnreadMessages = InternalMessagingController.Instance.CountUnreadMessages(UserInfo.UserID, portalId), - TotalNotifications = NotificationsController.Instance.CountNotifications(UserInfo.UserID, portalId) + TotalUnreadMessages = InternalMessagingController.Instance.CountUnreadMessages(this.UserInfo.UserID, portalId), + TotalNotifications = NotificationsController.Instance.CountNotifications(this.UserInfo.UserID, portalId), }; - return Request.CreateResponse(HttpStatusCode.OK, totalsViewModel); + return this.Request.CreateResponse(HttpStatusCode.OK, totalsViewModel); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -360,45 +360,31 @@ public HttpResponseMessage DismissAllNotifications() { try { - var deletedCount = NotificationsController.Instance.DeleteUserNotifications(UserInfo); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", count = deletedCount }); + var deletedCount = NotificationsController.Instance.DeleteUserNotifications(this.UserInfo); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", count = deletedCount }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - } - #endregion - - #region DTO - - public class ConversationDTO - { - public int ConversationId { get; set; } - } - - public class ReplyDTO : ConversationDTO - { - public string Body { get; set; } - public IList FileIds { get; set; } - } - - #endregion - - #region Private Methods - + } + private string LocalizeActionString(string key, int desktopModuleId) { - if (string.IsNullOrEmpty(key)) return ""; - + if (string.IsNullOrEmpty(key)) + { + return string.Empty; + } + string actionString; if (desktopModuleId > 0) { - var desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, PortalSettings.PortalId); + var desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, this.PortalSettings.PortalId); - var resourceFile = string.Format("~/DesktopModules/{0}/{1}/{2}", + var resourceFile = string.Format( + "~/DesktopModules/{0}/{1}/{2}", desktopModule.FolderName.Replace("\\", "/"), Localization.LocalResourceDirectory, Localization.LocalSharedResourceFile); @@ -413,29 +399,40 @@ private string LocalizeActionString(string key, int desktopModuleId) return string.IsNullOrEmpty(actionString) ? key : actionString; } - private dynamic ToExpandoObject(Message message) - { - dynamic messageObj = new ExpandoObject(); - messageObj.PortalID = message.PortalID; - messageObj.KeyID = message.KeyID; - messageObj.MessageID = message.MessageID; - messageObj.ConversationId = message.ConversationId; - messageObj.SenderUserID = message.SenderUserID; - messageObj.From = message.From; - messageObj.To = message.To; - messageObj.Subject = message.Subject; - messageObj.Body = message.Body; - messageObj.DisplayDate = message.DisplayDate; - messageObj.ReplyAllAllowed = message.ReplyAllAllowed; - //base entity properties - messageObj.CreatedByUserID = message.CreatedByUserID; - messageObj.CreatedOnDate = message.CreatedOnDate; - messageObj.LastModifiedByUserID = message.LastModifiedByUserID; - messageObj.LastModifiedOnDate = message.LastModifiedOnDate; - - return messageObj; - } - - #endregion + private dynamic ToExpandoObject(Message message) + { + dynamic messageObj = new ExpandoObject(); + messageObj.PortalID = message.PortalID; + messageObj.KeyID = message.KeyID; + messageObj.MessageID = message.MessageID; + messageObj.ConversationId = message.ConversationId; + messageObj.SenderUserID = message.SenderUserID; + messageObj.From = message.From; + messageObj.To = message.To; + messageObj.Subject = message.Subject; + messageObj.Body = message.Body; + messageObj.DisplayDate = message.DisplayDate; + messageObj.ReplyAllAllowed = message.ReplyAllAllowed; + + // base entity properties + messageObj.CreatedByUserID = message.CreatedByUserID; + messageObj.CreatedOnDate = message.CreatedOnDate; + messageObj.LastModifiedByUserID = message.LastModifiedByUserID; + messageObj.LastModifiedOnDate = message.LastModifiedOnDate; + + return messageObj; + } + + public class ConversationDTO + { + public int ConversationId { get; set; } + } + + public class ReplyDTO : ConversationDTO + { + public string Body { get; set; } + + public IList FileIds { get; set; } + } } } diff --git a/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs b/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs index 8ed2ab7e6ab..7eae090255a 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs @@ -1,59 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using System.Xml; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Modules.CoreMessaging.ViewModels; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Services.Social.Subscriptions; -using DotNetNuke.Services.Social.Subscriptions.Entities; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.Services { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + using System.Xml; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Modules.CoreMessaging.ViewModels; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Subscriptions; + using DotNetNuke.Services.Social.Subscriptions.Entities; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class SubscriptionsController : DnnApiController { private const string SharedResources = "~/DesktopModules/CoreMessaging/App_LocalResources/SharedResources.resx"; - private const string ViewControlResources = "~/DesktopModules/CoreMessaging/App_LocalResources/View.ascx.resx"; - - #region Private Properties + private const string ViewControlResources = "~/DesktopModules/CoreMessaging/App_LocalResources/View.ascx.resx"; + private string LocalizationFolder - { - get - { - return string.Format("~/DesktopModules/{0}/App_LocalResources/", - DesktopModuleController.GetDesktopModuleByModuleName("DotNetNuke.Modules.CoreMessaging", PortalSettings.PortalId).FolderName); - } - } - #endregion - - #region Public APIs - - /// + { + get + { + return string.Format( + "~/DesktopModules/{0}/App_LocalResources/", + DesktopModuleController.GetDesktopModuleByModuleName("DotNetNuke.Modules.CoreMessaging", this.PortalSettings.PortalId).FolderName); + } + } + + /// /// Perform a search on Scoring Activities registered in the system. /// - /// Page index to begin from (0, 1, 2) - /// Number of records to return per page - /// The sort expression in the form [Description|SubscriptionType] [Asc|Desc] - /// The sorted and paged list of subscriptions + /// Page index to begin from (0, 1, 2). + /// Number of records to return per page. + /// The sort expression in the form [Description|SubscriptionType] [Asc|Desc]. + /// The sorted and paged list of subscriptions. [HttpGet] public HttpResponseMessage GetSubscriptions(int pageIndex, int pageSize, string sortExpression) { try { - var subscriptions = from s in SubscriptionController.Instance.GetUserSubscriptions(UserInfo, PortalSettings.PortalId) + var subscriptions = from s in SubscriptionController.Instance.GetUserSubscriptions(this.UserInfo, this.PortalSettings.PortalId) select GetSubscriptionViewModel(s); List sortedList; @@ -85,19 +83,19 @@ public HttpResponseMessage GetSubscriptions(int pageIndex, int pageSize, string } } - var response = new - { - Success = true, - Results = sortedList.Skip(pageIndex * pageSize).Take(pageSize).ToList(), - TotalResults = sortedList.Count() - }; + var response = new + { + Success = true, + Results = sortedList.Skip(pageIndex * pageSize).Take(pageSize).ToList(), + TotalResults = sortedList.Count(), + }; - return Request.CreateResponse(HttpStatusCode.OK, response); + return this.Request.CreateResponse(HttpStatusCode.OK, response); } catch (Exception ex) { Exceptions.LogException(ex); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } @@ -106,23 +104,23 @@ public HttpResponseMessage GetSubscriptions(int pageIndex, int pageSize, string public HttpResponseMessage UpdateSystemSubscription(InboxSubscriptionViewModel post) { try - { + { var userPreferencesController = UserPreferencesController.Instance; - var userPreference = new UserPreference - { - PortalId = UserInfo.PortalID, - UserId = UserInfo.UserID, - MessagesEmailFrequency = (Frequency) post.MsgFreq, - NotificationsEmailFrequency = (Frequency) post.NotifyFreq - }; + var userPreference = new UserPreference + { + PortalId = this.UserInfo.PortalID, + UserId = this.UserInfo.UserID, + MessagesEmailFrequency = (Frequency)post.MsgFreq, + NotificationsEmailFrequency = (Frequency)post.NotifyFreq, + }; userPreferencesController.SetUserPreference(userPreference); - - return Request.CreateResponse(HttpStatusCode.OK, userPreferencesController.GetUserPreference(UserInfo)); + + return this.Request.CreateResponse(HttpStatusCode.OK, userPreferencesController.GetUserPreference(this.UserInfo)); } catch (Exception ex) { Exceptions.LogException(ex); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } @@ -132,62 +130,59 @@ public HttpResponseMessage DeleteContentSubscription(Subscription subscription) { try { - var sub = SubscriptionController.Instance.GetUserSubscriptions(UserInfo, PortalSettings.PortalId) + var sub = SubscriptionController.Instance.GetUserSubscriptions(this.UserInfo, this.PortalSettings.PortalId) .SingleOrDefault(s => s.SubscriptionId == subscription.SubscriptionId); if (sub != null) { - SubscriptionController.Instance.DeleteSubscription(sub); + SubscriptionController.Instance.DeleteSubscription(sub); } - return Request.CreateResponse(HttpStatusCode.OK, "unsubscribed"); + return this.Request.CreateResponse(HttpStatusCode.OK, "unsubscribed"); } catch (Exception ex) { Exceptions.LogException(ex); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } - [HttpGet] - [AllowAnonymous] - public HttpResponseMessage GetLocalizationTable(string culture) - { - try - { - if (!string.IsNullOrEmpty(culture)) - { - Localization.SetThreadCultures(new CultureInfo(culture), PortalSettings); - } - - var dictionary = new Dictionary(); - - var resourcesPath = LocalizationFolder; - var files = - Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath(resourcesPath)).Select(x => new FileInfo(x).Name).Where(f => !IsLanguageSpecific(f)).ToList(); - - foreach (var kvp in files.SelectMany(f => GetLocalizationValues(resourcesPath, f, culture)).Where(kvp => !dictionary.ContainsKey(kvp.Key))) - { - dictionary.Add(kvp.Key, kvp.Value); - } - - foreach (var kvp in GetLocalizationValues(SharedResources, culture).Where(kvp => !dictionary.ContainsKey(kvp.Key))) - { - dictionary.Add(kvp.Key, kvp.Value); - } - - return Request.CreateResponse(HttpStatusCode.OK, new { Table = dictionary }); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); - } - } - #endregion - - #region Private Statics Methods + [HttpGet] + [AllowAnonymous] + public HttpResponseMessage GetLocalizationTable(string culture) + { + try + { + if (!string.IsNullOrEmpty(culture)) + { + Localization.SetThreadCultures(new CultureInfo(culture), this.PortalSettings); + } + var dictionary = new Dictionary(); + + var resourcesPath = this.LocalizationFolder; + var files = + Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath(resourcesPath)).Select(x => new FileInfo(x).Name).Where(f => !IsLanguageSpecific(f)).ToList(); + + foreach (var kvp in files.SelectMany(f => GetLocalizationValues(resourcesPath, f, culture)).Where(kvp => !dictionary.ContainsKey(kvp.Key))) + { + dictionary.Add(kvp.Key, kvp.Value); + } + + foreach (var kvp in GetLocalizationValues(SharedResources, culture).Where(kvp => !dictionary.ContainsKey(kvp.Key))) + { + dictionary.Add(kvp.Key, kvp.Value); + } + + return this.Request.CreateResponse(HttpStatusCode.OK, new { Table = dictionary }); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); + } + } + private static SubscriptionViewModel GetSubscriptionViewModel(Subscription subscription) { var model = new SubscriptionViewModel @@ -210,95 +205,95 @@ private static SubscriptionViewModel GetSubscriptionViewModel(Subscription subsc } private static bool IsLanguageSpecific(string fileName) - { - var components = fileName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); - if (components.Length > 1) - { - var language = components[components.Length - 2]; - - if (!string.IsNullOrEmpty(language)) - { - try - { - CultureInfo.GetCultureInfo(language); - - return true; - } - catch (CultureNotFoundException) - { - return false; - } - } - } - - return false; - } - - private static IEnumerable> GetLocalizationValues(string path, string file, string culture) - { - return GetLocalizationValues(string.Format("{0}/{1}", path, file), culture); - } - - private static IEnumerable> GetLocalizationValues(string fullPath, string culture) - { - using (var stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath(fullPath), FileMode.Open, FileAccess.Read)) - { - var document = new XmlDocument { XmlResolver = null }; - document.Load(stream); - - // ReSharper disable AssignNullToNotNullAttribute - var headers = document.SelectNodes(@"/root/resheader").Cast().ToArray(); - // ReSharper restore AssignNullToNotNullAttribute - - AssertHeaderValue(headers, "resmimetype", "text/microsoft-resx"); - - // ReSharper disable AssignNullToNotNullAttribute - foreach (var xmlNode in document.SelectNodes("/root/data").Cast()) - // ReSharper restore AssignNullToNotNullAttribute - { - var name = GetNameAttribute(xmlNode).Replace(".Text", string.Empty); - - if (string.IsNullOrEmpty(name)) - { - continue; - } - - var value = Localization.GetString(string.Format("{0}.Text", name), fullPath, culture); - - yield return new KeyValuePair(name, value); - } - } - } - - private static void AssertHeaderValue(IEnumerable headers, string key, string value) - { - var header = headers.FirstOrDefault(x => GetNameAttribute(x).Equals(key, StringComparison.InvariantCultureIgnoreCase)); - if (header != null) - { - if (!header.InnerText.Equals(value, StringComparison.InvariantCultureIgnoreCase)) - { - throw new ApplicationException(string.Format("Resource header '{0}' != '{1}'", key, value)); - } - } - else - { - throw new ApplicationException(string.Format("Resource header '{0}' is missing", key)); - } - } - - private static string GetNameAttribute(XmlNode node) - { - if (node.Attributes != null) - { - var attribute = node.Attributes.GetNamedItem("name"); - if (attribute != null) - { - return attribute.Value; - } - } - - return null; - } - #endregion - } + { + var components = fileName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); + if (components.Length > 1) + { + var language = components[components.Length - 2]; + + if (!string.IsNullOrEmpty(language)) + { + try + { + CultureInfo.GetCultureInfo(language); + + return true; + } + catch (CultureNotFoundException) + { + return false; + } + } + } + + return false; + } + + private static IEnumerable> GetLocalizationValues(string path, string file, string culture) + { + return GetLocalizationValues(string.Format("{0}/{1}", path, file), culture); + } + + private static IEnumerable> GetLocalizationValues(string fullPath, string culture) + { + using (var stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath(fullPath), FileMode.Open, FileAccess.Read)) + { + var document = new XmlDocument { XmlResolver = null }; + document.Load(stream); + + // ReSharper disable AssignNullToNotNullAttribute + var headers = document.SelectNodes(@"/root/resheader").Cast().ToArray(); + + // ReSharper restore AssignNullToNotNullAttribute + AssertHeaderValue(headers, "resmimetype", "text/microsoft-resx"); + + // ReSharper disable AssignNullToNotNullAttribute + foreach (var xmlNode in document.SelectNodes("/root/data").Cast()) + + // ReSharper restore AssignNullToNotNullAttribute + { + var name = GetNameAttribute(xmlNode).Replace(".Text", string.Empty); + + if (string.IsNullOrEmpty(name)) + { + continue; + } + + var value = Localization.GetString(string.Format("{0}.Text", name), fullPath, culture); + + yield return new KeyValuePair(name, value); + } + } + } + + private static void AssertHeaderValue(IEnumerable headers, string key, string value) + { + var header = headers.FirstOrDefault(x => GetNameAttribute(x).Equals(key, StringComparison.InvariantCultureIgnoreCase)); + if (header != null) + { + if (!header.InnerText.Equals(value, StringComparison.InvariantCultureIgnoreCase)) + { + throw new ApplicationException(string.Format("Resource header '{0}' != '{1}'", key, value)); + } + } + else + { + throw new ApplicationException(string.Format("Resource header '{0}' is missing", key)); + } + } + + private static string GetNameAttribute(XmlNode node) + { + if (node.Attributes != null) + { + var attribute = node.Attributes.GetNamedItem("name"); + if (attribute != null) + { + return attribute.Value; + } + } + + return null; + } + } } diff --git a/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs b/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs index b76cf35601c..a7e80124f31 100644 --- a/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs +++ b/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs @@ -1,64 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web; -using System.Web.Configuration; -using System.Web.UI; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web; + using System.Web.Configuration; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Client.ClientResourceManagement; + public partial class Subscriptions : UserControl { - private const string SharedResources = "~/DesktopModules/CoreMessaging/App_LocalResources/SharedResources.resx"; - - #region Public Properties + private const string SharedResources = "~/DesktopModules/CoreMessaging/App_LocalResources/SharedResources.resx"; + public ModuleInstanceContext ModuleContext { get; set; } public ModuleInfo ModuleConfiguration { - get { return ModuleContext != null ? ModuleContext.Configuration : null; } + get { return this.ModuleContext != null ? this.ModuleContext.Configuration : null; } + set { - ModuleContext.Configuration = value; + this.ModuleContext.Configuration = value; } } - public string LocalResourceFile { get; set; } - - #endregion - - #region Protected Methods - - protected string LocalizeString(string key) - { - return Localization.GetString(key, LocalResourceFile); - } - - #endregion - - #region Public Methods - + public string LocalResourceFile { get; set; } + public string GetSettingsAsJson() { - var settings = GetModuleSettings(PortalSettings.Current, ModuleConfiguration, Null.NullInteger); - foreach (DictionaryEntry entry in GetViewSettings()) + var settings = GetModuleSettings(PortalSettings.Current, this.ModuleConfiguration, Null.NullInteger); + foreach (DictionaryEntry entry in this.GetViewSettings()) { if (settings.ContainsKey(entry.Key)) { @@ -71,62 +59,31 @@ public string GetSettingsAsJson() } return settings.ToJson(); - } - - #endregion - - #region Event Handlers - + } + + protected string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/CoreMessaging/Scripts/LocalizationController.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/CoreMessaging/Scripts/SubscriptionsViewModel.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/CoreMessaging/Scripts/Subscription.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/DesktopModules/CoreMessaging/subscriptions.css"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/CoreMessaging/Scripts/LocalizationController.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/CoreMessaging/Scripts/SubscriptionsViewModel.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/CoreMessaging/Scripts/Subscription.js"); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/DesktopModules/CoreMessaging/subscriptions.css"); } else { - Response.Redirect(Globals.AccessDeniedURL(), false); + this.Response.Redirect(Globals.AccessDeniedURL(), false); } - } - - #endregion - - #region Private methods - - /// - /// These values are passed in as the 'settings' parameter of the JavaScript initialization function, together with - /// values that are automatically retrieved by Social Library such as portalId and moduleId. - /// - private Hashtable GetViewSettings() - { - var portalSettings = PortalSettings.Current; - var userPreferenceController = UserPreferencesController.Instance; - var user = UserController.GetUserById(portalSettings.PortalId, portalSettings.UserId); - UserPreference userPreference=null; - if (user != null) - { - userPreference = userPreferenceController.GetUserPreference(user); - } - - - const int notifyFrequency = 2; - const int messageFrequency = 0; - - return new Hashtable - { - { "moduleScope", string.Format("#{0}", ScopeWrapper.ClientID) }, - { "pageSize", 25 }, - { "notifyFrequency", userPreference != null ? (int)userPreference.NotificationsEmailFrequency : notifyFrequency }, - { "msgFrequency", userPreference != null ? (int)userPreference.MessagesEmailFrequency : messageFrequency } - }; - } + } private static Hashtable GetModuleSettings(PortalSettings portalSettings, ModuleInfo moduleInfo, int uniqueId) { @@ -185,13 +142,40 @@ private static Hashtable GetModuleSettings(PortalSettings portalSettings, Module { "usePopup", usePopup }, { "returnUrl", HttpContext.Current.Request.UrlReferrer }, { "uniqueId", uniqueId }, - }; + }; } - + private static string GetHistoryNavigationKey(string moduleName) { return HttpContext.Current.Server.HtmlEncode(moduleName.ToLowerInvariant().Replace(" ", string.Empty)); } + + /// + /// These values are passed in as the 'settings' parameter of the JavaScript initialization function, together with + /// values that are automatically retrieved by Social Library such as portalId and moduleId. + /// + private Hashtable GetViewSettings() + { + var portalSettings = PortalSettings.Current; + var userPreferenceController = UserPreferencesController.Instance; + var user = UserController.GetUserById(portalSettings.PortalId, portalSettings.UserId); + UserPreference userPreference = null; + if (user != null) + { + userPreference = userPreferenceController.GetUserPreference(user); + } + + const int notifyFrequency = 2; + const int messageFrequency = 0; + + return new Hashtable + { + { "moduleScope", string.Format("#{0}", this.ScopeWrapper.ClientID) }, + { "pageSize", 25 }, + { "notifyFrequency", userPreference != null ? (int)userPreference.NotificationsEmailFrequency : notifyFrequency }, + { "msgFrequency", userPreference != null ? (int)userPreference.MessagesEmailFrequency : messageFrequency }, + }; + } private static TimeSpan GetSessionTimeout() { @@ -220,7 +204,7 @@ private static IDictionary GetSharedResources() return new Dictionary { { "ExceptionTitle", Localization.GetString("ExceptionTitle", SharedResources) }, - { "ExceptionMessage", Localization.GetString("ExceptionMessage", SharedResources) } + { "ExceptionMessage", Localization.GetString("ExceptionMessage", SharedResources) }, }; } @@ -240,8 +224,6 @@ private static string GetLoginUrl(PortalSettings portalSettings) } return returnUrl; - } - - #endregion + } } } diff --git a/DNN Platform/Modules/CoreMessaging/View.ascx.cs b/DNN Platform/Modules/CoreMessaging/View.ascx.cs index ef0c5967aa9..9d47e9fbc35 100644 --- a/DNN Platform/Modules/CoreMessaging/View.ascx.cs +++ b/DNN Platform/Modules/CoreMessaging/View.ascx.cs @@ -1,47 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Common; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.CoreMessaging { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.Client.ClientResourceManagement; + /// ----------------------------------------------------------------------------- /// - /// The View class displays the content + /// The View class displays the content. /// /// ----------------------------------------------------------------------------- public partial class View : PortalModuleBase - { - #region Public Properties - + { public int ProfileUserId { get { var userId = Null.NullInteger; - if (!string.IsNullOrEmpty(Request.Params["UserId"])) + if (!string.IsNullOrEmpty(this.Request.Params["UserId"])) { - userId = Int32.Parse(Request.Params["UserId"]); + userId = int.Parse(this.Request.Params["UserId"]); } + return userId; } } @@ -50,77 +44,74 @@ public string ShowAttachments { get { - var allowAttachments = PortalController.GetPortalSetting("MessagingAllowAttachments", PortalId, "NO"); + var allowAttachments = PortalController.GetPortalSetting("MessagingAllowAttachments", this.PortalId, "NO"); return allowAttachments == "NO" ? "false" : "true"; } } - public bool ShowSubscriptionTab - { - get - { - return !Settings.ContainsKey("ShowSubscriptionTab") || - Settings["ShowSubscriptionTab"].ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase); - } - } - - public bool DisablePrivateMessage - { - get - { - return PortalSettings.DisablePrivateMessage && !UserInfo.IsSuperUser - && !UserInfo.IsInRole(PortalSettings.AdministratorRoleName); - - } - } - - #endregion - - #region Event Handlers + public bool ShowSubscriptionTab + { + get + { + return !this.Settings.ContainsKey("ShowSubscriptionTab") || + this.Settings["ShowSubscriptionTab"].ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase); + } + } - override protected void OnInit(EventArgs e) + public bool DisablePrivateMessage + { + get + { + return this.PortalSettings.DisablePrivateMessage && !this.UserInfo.IsSuperUser + && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName); + } + } + + protected override void OnInit(EventArgs e) { - if (!Request.IsAuthenticated) + if (!this.Request.IsAuthenticated) { // Do not redirect but hide the content of the module and display a message. - CoreMessagingContainer.Visible = false; - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ContentNotAvailable", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + this.CoreMessagingContainer.Visible = false; + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ContentNotAvailable", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); return; } - if (UserId != ProfileUserId && (PortalSettings.ActiveTab.ParentId == PortalSettings.UserTabId || TabId == PortalSettings.UserTabId)) + + if (this.UserId != this.ProfileUserId && (this.PortalSettings.ActiveTab.ParentId == this.PortalSettings.UserTabId || this.TabId == this.PortalSettings.UserTabId)) { - // Do not redirect but hide the content of the module. - CoreMessagingContainer.Visible = false; - return; + // Do not redirect but hide the content of the module. + this.CoreMessagingContainer.Visible = false; + return; } - - if (IsEditable && PermissionsNotProperlySet()) + + if (this.IsEditable && this.PermissionsNotProperlySet()) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PermissionsNotProperlySet", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PermissionsNotProperlySet", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); } ServicesFramework.Instance.RequestAjaxScriptSupport(); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); JavaScript.RequestRegistration(CommonJs.DnnPlugins); JavaScript.RequestRegistration(CommonJs.Knockout); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/CoreMessaging/Scripts/CoreMessaging.js"); - jQuery.RegisterFileUpload(Page); - AddIe7StyleSheet(); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/CoreMessaging/Scripts/CoreMessaging.js"); + jQuery.RegisterFileUpload(this.Page); + this.AddIe7StyleSheet(); base.OnInit(e); - } - - #endregion - - #region Private Methods + } + private static bool PermissionPredicate(PermissionInfoBase p) + { + return p.PermissionKey == "VIEW" && p.AllowAccess && (p.RoleName == Globals.glbRoleAllUsersName || p.RoleName == Globals.glbRoleUnauthUserName); + } + private void AddIe7StyleSheet() { - var browser = Request.Browser; + var browser = this.Request.Browser; if (browser.Type == "IE" || browser.MajorVersion < 8) { const string cssLink = ""; - Page.Header.Controls.Add(new LiteralControl(cssLink)); + this.Page.Header.Controls.Add(new LiteralControl(cssLink)); } } @@ -128,24 +119,17 @@ private bool PermissionsNotProperlySet() { List permissions; - if (ModuleConfiguration.InheritViewPermissions) + if (this.ModuleConfiguration.InheritViewPermissions) { - var tabPermissionCollection = TabPermissionController.GetTabPermissions(TabId, PortalId); + var tabPermissionCollection = TabPermissionController.GetTabPermissions(this.TabId, this.PortalId); permissions = tabPermissionCollection.ToList(); } else { - permissions = ModuleConfiguration.ModulePermissions.ToList(); + permissions = this.ModuleConfiguration.ModulePermissions.ToList(); } return permissions.Find(PermissionPredicate) != null; } - - private static bool PermissionPredicate(PermissionInfoBase p) - { - return p.PermissionKey == "VIEW" && p.AllowAccess && (p.RoleName == Globals.glbRoleAllUsersName || p.RoleName == Globals.glbRoleUnauthUserName); - } - - #endregion } } diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/InboxSubscriptionViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/InboxSubscriptionViewModel.cs index 2f76e15bcdf..33feb196f54 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/InboxSubscriptionViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/InboxSubscriptionViewModel.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Runtime.Serialization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.ViewModels { + using System.Runtime.Serialization; + public class InboxSubscriptionViewModel { [DataMember(Name = "notifyFreq")] diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs index f3ccae7c98b..ea3590f5c9c 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs @@ -1,14 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.ViewModels { public class NotificationActionViewModel { public string Name { get; set; } + public string Description { get; set; } + public string Confirm { get; set; } + public string APICall { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs index 8f4e36720cd..da6fb9d7c24 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs @@ -1,21 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.ViewModels { + using System.Collections.Generic; + public class NotificationViewModel { public int NotificationId { get; set; } + public string Subject { get; set; } + public string From { get; set; } + public string Body { get; set; } + public string SenderAvatar { get; set; } + public string SenderProfileUrl { get; set; } + public string SenderDisplayName { get; set; } + public string DisplayDate { get; set; } + public IList Actions { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs index 51c1444ae26..b20f89f5992 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.ViewModels { + using System.Collections.Generic; + public class NotificationsViewModel { public int TotalNotifications { get; set; } + public IList Notifications { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/SubscriptionViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/SubscriptionViewModel.cs index ffb5ec1a29b..81c26ba8402 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/SubscriptionViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/SubscriptionViewModel.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.ViewModels { using System.Runtime.Serialization; diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs index af1db5f56c2..bfa0f70bc7b 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.CoreMessaging.ViewModels { public class TotalsViewModel { public int TotalUnreadMessages { get; set; } + public int TotalNotifications { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/packages.config b/DNN Platform/Modules/CoreMessaging/packages.config index 4a4092b618b..6730d0b6c1b 100644 --- a/DNN Platform/Modules/CoreMessaging/packages.config +++ b/DNN Platform/Modules/CoreMessaging/packages.config @@ -1,8 +1,9 @@ - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/DDRMenu/Actions.cs b/DNN Platform/Modules/DDRMenu/Actions.cs index 5c85cd9d08c..efdf301648d 100644 --- a/DNN Platform/Modules/DDRMenu/Actions.cs +++ b/DNN Platform/Modules/DDRMenu/Actions.cs @@ -1,195 +1,198 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Web.UI; -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI; -using DotNetNuke.UI.Containers; -using DotNetNuke.UI.WebControls; -using DotNetNuke.Web.DDRMenu.DNNCommon; -using DotNetNuke.Web.DDRMenu.TemplateEngine; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - public class Actions : ActionBase - { - public string PathSystemScript { get; set; } - - public string MenuStyle { get; set; } - - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - public List ClientOptions { get; set; } - - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - public List TemplateArguments { get; set; } - - private DDRMenuNavigationProvider navProvider; - private Dictionary actions; - - protected override void OnInit(EventArgs e) - { - using (new DNNContext(this)) - { - base.OnInit(e); - - navProvider = (DDRMenuNavigationProvider)NavigationProvider.Instance("DDRMenuNavigationProvider"); - navProvider.ControlID = "ctl" + ID; - navProvider.MenuStyle = MenuStyle; - navProvider.Initialize(); - - Controls.Add(navProvider.NavigationControl); - } - } - - protected override void OnLoad(EventArgs e) - { - using (new DNNContext(this)) - { - base.OnLoad(e); - - SetMenuDefaults(); - } - } - - protected override void OnPreRender(EventArgs e) - { - using (new DNNContext(this)) - { - base.OnPreRender(e); - - try - { - navProvider.TemplateArguments = TemplateArguments; - BindMenu(Navigation.GetActionNodes(ActionRoot, this, -1)); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } - - private void BindMenu(DNNNodeCollection objNodes) - { - Visible = DisplayControl(objNodes); - if (!Visible) - { - return; - } - - navProvider.ClearNodes(); - foreach (DNNNode node in objNodes) - { - ProcessNode(node); - } - navProvider.Bind(objNodes, false); - } - - private void ActionClick(NavigationEventArgs args) - { - using (new DNNContext(this)) - { - try - { - ProcessAction(args.ID); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } - - private void AddActionIDs(ModuleAction action) - { - if (!actions.ContainsKey(action.ID)) - { - actions.Add(action.ID, action); - } - if (action.HasChildren()) - { - foreach (ModuleAction a in action.Actions) - { - AddActionIDs(a); - } - } - } - - private ModuleAction FindAction(int id) - { - if (actions == null) - { - actions = new Dictionary(); - AddActionIDs(ActionRoot); - } - - ModuleAction result; - return actions.TryGetValue(id, out result) ? result : null; - } - - private void ProcessNode(DNNNode dnnNode) - { - if (!dnnNode.IsBreak) - { - var action = FindAction(Convert.ToInt32(dnnNode.Key)); - if (action != null) - { - dnnNode.set_CustomAttribute("CommandName", action.CommandName); - dnnNode.set_CustomAttribute("CommandArgument", action.CommandArgument); - } - } - - if (!String.IsNullOrEmpty(dnnNode.JSFunction)) - { - dnnNode.JSFunction = string.Format( - "if({0}){{{1}}};", - dnnNode.JSFunction, - Page.ClientScript.GetPostBackEventReference(navProvider.NavigationControl, dnnNode.ID)); - } - - foreach (DNNNode node in dnnNode.DNNNodes) - { - ProcessNode(node); - } - } - - private void SetMenuDefaults() - { - try - { - navProvider.StyleIconWidth = 15M; - navProvider.MouseOutHideDelay = 500M; - navProvider.MouseOverAction = NavigationProvider.HoverAction.Expand; - navProvider.MouseOverDisplay = NavigationProvider.HoverDisplay.None; - navProvider.CSSControl = "ModuleTitle_MenuBar"; - navProvider.CSSContainerRoot = "ModuleTitle_MenuContainer"; - navProvider.CSSNode = "ModuleTitle_MenuItem"; - navProvider.CSSIcon = "ModuleTitle_MenuIcon"; - navProvider.CSSContainerSub = "ModuleTitle_SubMenu"; - navProvider.CSSBreak = "ModuleTitle_MenuBreak"; - navProvider.CSSNodeHover = "ModuleTitle_MenuItemSel"; - navProvider.CSSIndicateChildSub = "ModuleTitle_MenuArrow"; - navProvider.CSSIndicateChildRoot = "ModuleTitle_RootMenuArrow"; - navProvider.PathImage = Globals.ApplicationPath + "/Images/"; - navProvider.PathSystemImage = Globals.ApplicationPath + "/Images/"; - navProvider.IndicateChildImageSub = "action_right.gif"; - navProvider.IndicateChildren = true; - navProvider.StyleRoot = "background-color: Transparent; font-size: 1pt;"; - navProvider.NodeClick += ActionClick; - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI; + using DotNetNuke.UI.Containers; + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.DDRMenu.DNNCommon; + using DotNetNuke.Web.DDRMenu.TemplateEngine; + + public class Actions : ActionBase + { + private DDRMenuNavigationProvider navProvider; + private Dictionary actions; + + public string PathSystemScript { get; set; } + + public string MenuStyle { get; set; } + + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + public List ClientOptions { get; set; } + + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + public List TemplateArguments { get; set; } + + protected override void OnInit(EventArgs e) + { + using (new DNNContext(this)) + { + base.OnInit(e); + + this.navProvider = (DDRMenuNavigationProvider)NavigationProvider.Instance("DDRMenuNavigationProvider"); + this.navProvider.ControlID = "ctl" + this.ID; + this.navProvider.MenuStyle = this.MenuStyle; + this.navProvider.Initialize(); + + this.Controls.Add(this.navProvider.NavigationControl); + } + } + + protected override void OnLoad(EventArgs e) + { + using (new DNNContext(this)) + { + base.OnLoad(e); + + this.SetMenuDefaults(); + } + } + + protected override void OnPreRender(EventArgs e) + { + using (new DNNContext(this)) + { + base.OnPreRender(e); + + try + { + this.navProvider.TemplateArguments = this.TemplateArguments; + this.BindMenu(Navigation.GetActionNodes(this.ActionRoot, this, -1)); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + + private void BindMenu(DNNNodeCollection objNodes) + { + this.Visible = this.DisplayControl(objNodes); + if (!this.Visible) + { + return; + } + + this.navProvider.ClearNodes(); + foreach (DNNNode node in objNodes) + { + this.ProcessNode(node); + } + + this.navProvider.Bind(objNodes, false); + } + + private void ActionClick(NavigationEventArgs args) + { + using (new DNNContext(this)) + { + try + { + this.ProcessAction(args.ID); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + + private void AddActionIDs(ModuleAction action) + { + if (!this.actions.ContainsKey(action.ID)) + { + this.actions.Add(action.ID, action); + } + + if (action.HasChildren()) + { + foreach (ModuleAction a in action.Actions) + { + this.AddActionIDs(a); + } + } + } + + private ModuleAction FindAction(int id) + { + if (this.actions == null) + { + this.actions = new Dictionary(); + this.AddActionIDs(this.ActionRoot); + } + + ModuleAction result; + return this.actions.TryGetValue(id, out result) ? result : null; + } + + private void ProcessNode(DNNNode dnnNode) + { + if (!dnnNode.IsBreak) + { + var action = this.FindAction(Convert.ToInt32(dnnNode.Key)); + if (action != null) + { + dnnNode.set_CustomAttribute("CommandName", action.CommandName); + dnnNode.set_CustomAttribute("CommandArgument", action.CommandArgument); + } + } + + if (!string.IsNullOrEmpty(dnnNode.JSFunction)) + { + dnnNode.JSFunction = string.Format( + "if({0}){{{1}}};", + dnnNode.JSFunction, + this.Page.ClientScript.GetPostBackEventReference(this.navProvider.NavigationControl, dnnNode.ID)); + } + + foreach (DNNNode node in dnnNode.DNNNodes) + { + this.ProcessNode(node); + } + } + + private void SetMenuDefaults() + { + try + { + this.navProvider.StyleIconWidth = 15M; + this.navProvider.MouseOutHideDelay = 500M; + this.navProvider.MouseOverAction = NavigationProvider.HoverAction.Expand; + this.navProvider.MouseOverDisplay = NavigationProvider.HoverDisplay.None; + this.navProvider.CSSControl = "ModuleTitle_MenuBar"; + this.navProvider.CSSContainerRoot = "ModuleTitle_MenuContainer"; + this.navProvider.CSSNode = "ModuleTitle_MenuItem"; + this.navProvider.CSSIcon = "ModuleTitle_MenuIcon"; + this.navProvider.CSSContainerSub = "ModuleTitle_SubMenu"; + this.navProvider.CSSBreak = "ModuleTitle_MenuBreak"; + this.navProvider.CSSNodeHover = "ModuleTitle_MenuItemSel"; + this.navProvider.CSSIndicateChildSub = "ModuleTitle_MenuArrow"; + this.navProvider.CSSIndicateChildRoot = "ModuleTitle_RootMenuArrow"; + this.navProvider.PathImage = Globals.ApplicationPath + "/Images/"; + this.navProvider.PathSystemImage = Globals.ApplicationPath + "/Images/"; + this.navProvider.IndicateChildImageSub = "action_right.gif"; + this.navProvider.IndicateChildren = true; + this.navProvider.StyleRoot = "background-color: Transparent; font-size: 1pt;"; + this.navProvider.NodeClick += this.ActionClick; + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs b/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs index 48cd2c3eccb..d0c93911861 100644 --- a/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs +++ b/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs @@ -1,80 +1,112 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Reflection; -using System.Web; -using System.Web.UI; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.DNNCommon { - public class DNNContext : IDisposable - { - public static DNNContext Current { get { return (DNNContext)HttpContext.Current.Items[DataName]; } private set { HttpContext.Current.Items[DataName] = value; } } - - private readonly DNNContext savedContext; - - public Control HostControl { get; private set; } - - private Page _Page; - public Page Page { get { return _Page ?? (_Page = HostControl.Page); } } - - private PortalSettings _PortalSettings; - public PortalSettings PortalSettings { get { return _PortalSettings ?? (_PortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } } - - private TabInfo _ActiveTab; - public TabInfo ActiveTab { get { return _ActiveTab ?? (_ActiveTab = PortalSettings.ActiveTab); } } - - private string _SkinPath; - public string SkinPath { get { return _SkinPath ?? (_SkinPath = ActiveTab.SkinPath); } } - - private static string _ModuleName; - public static string ModuleName { get { return _ModuleName ?? (_ModuleName = GetModuleNameFromAssembly()); } } - - private static string _ModuleFolder; - public static string ModuleFolder - { - get - { - return _ModuleFolder ?? - (_ModuleFolder = - String.Format( - "~/DesktopModules/{0}/", DesktopModuleController.GetDesktopModuleByModuleName(ModuleName, PortalSettings.Current.PortalId).FolderName)); - } - } - - private static string _DataName; - private static string DataName { get { return _DataName ?? (_DataName = "DDRMenu.DNNContext." + ModuleName); } } - - public DNNContext(Control hostControl) - { - HostControl = hostControl; - - savedContext = Current; - Current = this; - } - - public string ResolveUrl(string relativeUrl) - { - return HostControl.ResolveUrl(relativeUrl); - } - - private static string GetModuleNameFromAssembly() - { - var moduleFullName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); -// ReSharper disable PossibleNullReferenceException - return moduleFullName.Substring(moduleFullName.LastIndexOf('.') + 1); -// ReSharper restore PossibleNullReferenceException - } - - public void Dispose() - { - Current = savedContext; - } - } + using System; + using System.IO; + using System.Reflection; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + + public class DNNContext : IDisposable + { + private static string _ModuleName; + + private static string _ModuleFolder; + + private static string _DataName; + + private readonly DNNContext savedContext; + + private Page _Page; + + private PortalSettings _PortalSettings; + + private TabInfo _ActiveTab; + + private string _SkinPath; + + public DNNContext(Control hostControl) + { + this.HostControl = hostControl; + + this.savedContext = Current; + Current = this; + } + + public static DNNContext Current + { + get { return (DNNContext)HttpContext.Current.Items[DataName]; } + private set { HttpContext.Current.Items[DataName] = value; } + } + + public static string ModuleName + { + get { return _ModuleName ?? (_ModuleName = GetModuleNameFromAssembly()); } + } + + public static string ModuleFolder + { + get + { + return _ModuleFolder ?? + (_ModuleFolder = + string.Format( + "~/DesktopModules/{0}/", DesktopModuleController.GetDesktopModuleByModuleName(ModuleName, PortalSettings.Current.PortalId).FolderName)); + } + } + + public Control HostControl { get; private set; } + + public Page Page + { + get { return this._Page ?? (this._Page = this.HostControl.Page); } + } + + public PortalSettings PortalSettings + { + get { return this._PortalSettings ?? (this._PortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } + } + + public TabInfo ActiveTab + { + get { return this._ActiveTab ?? (this._ActiveTab = this.PortalSettings.ActiveTab); } + } + + public string SkinPath + { + get { return this._SkinPath ?? (this._SkinPath = this.ActiveTab.SkinPath); } + } + + private static string DataName + { + get { return _DataName ?? (_DataName = "DDRMenu.DNNContext." + ModuleName); } + } + + public string ResolveUrl(string relativeUrl) + { + return this.HostControl.ResolveUrl(relativeUrl); + } + + public void Dispose() + { + Current = this.savedContext; + } + + private static string GetModuleNameFromAssembly() + { + var moduleFullName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); + + // ReSharper disable PossibleNullReferenceException + return moduleFullName.Substring(moduleFullName.LastIndexOf('.') + 1); + + // ReSharper restore PossibleNullReferenceException + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs b/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs index 4b8972397df..8b606aad474 100644 --- a/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs +++ b/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs @@ -1,128 +1,134 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Web; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.DNNCommon { - public class PathResolver - { - public enum RelativeTo - { - Container, - Dnn, - Manifest, - Module, - Portal, - Skin, - } - - private readonly string manifestFolder; - - public PathResolver(string manifestFolder) - { - this.manifestFolder = manifestFolder; - } - - public string Resolve(string path, params RelativeTo[] roots) - { - var context = DNNContext.Current; - - var mappings = new Dictionary - { - {"[DDRMENU]", RelativeTo.Module}, - {"[MODULE]", RelativeTo.Module}, - {"[MANIFEST]", RelativeTo.Manifest}, - {"[PORTAL]", RelativeTo.Portal}, - {"[SKIN]", RelativeTo.Skin}, - {"[CONTAINER]", RelativeTo.Container}, - {"[DNN]", RelativeTo.Dnn} - }; - foreach (var key in mappings.Keys) - { - if (path.StartsWith(key, StringComparison.InvariantCultureIgnoreCase)) - { - path = path.Substring(key.Length); - roots = new[] {mappings[key]}; - break; - } - } - - if (path.StartsWith("/")) - { - path = path.Substring(1); - } - - if (!path.StartsWith("~") && !path.Contains(":")) - { - foreach (var root in roots) - { - string resolvedPath = null; - switch (root) - { - case RelativeTo.Container: - var container = context.HostControl; - while ((container != null) && !(container is UI.Containers.Container)) - { - container = container.Parent; - } - var containerRoot = (container == null) - ? context.SkinPath -// ReSharper disable PossibleNullReferenceException - : Path.GetDirectoryName(((UI.Containers.Container)container).AppRelativeVirtualPath).Replace( -// ReSharper restore PossibleNullReferenceException - '\\', '/') + "/"; - resolvedPath = Path.Combine(containerRoot, path); - break; - case RelativeTo.Dnn: - resolvedPath = Path.Combine("~/", path); - break; - case RelativeTo.Manifest: - if (!string.IsNullOrEmpty(manifestFolder)) - { - resolvedPath = Path.Combine(manifestFolder + "/", path); - } - break; - case RelativeTo.Module: - resolvedPath = Path.Combine(DNNContext.ModuleFolder, path); - break; - case RelativeTo.Portal: - resolvedPath = Path.Combine(context.PortalSettings.HomeDirectory, path); - break; - case RelativeTo.Skin: - resolvedPath = Path.Combine(context.SkinPath, path); - break; - } - - if (!String.IsNullOrEmpty(resolvedPath)) - { - var sep = resolvedPath.LastIndexOf('/'); - var dirName = resolvedPath.Substring(0, sep + 1); - var fileName = resolvedPath.Substring(sep + 1); - - var mappedDir = HttpContext.Current.Server.MapPath(dirName); - mappedDir = mappedDir.Remove(mappedDir.Length - 1); - if (Directory.Exists(mappedDir)) - { - if (String.IsNullOrEmpty(fileName)) - return resolvedPath.Replace('\\', '/'); - - var matches = Directory.GetFileSystemEntries(mappedDir, fileName); - if (matches.Length > 0) - { - resolvedPath = (dirName + Path.GetFileName(matches[0])).Replace('\\', '/'); - return resolvedPath; - } - } - } - } - } - - return path; - } - } + using System; + using System.Collections.Generic; + using System.IO; + using System.Web; + + public class PathResolver + { + private readonly string manifestFolder; + + public PathResolver(string manifestFolder) + { + this.manifestFolder = manifestFolder; + } + + public enum RelativeTo + { + Container, + Dnn, + Manifest, + Module, + Portal, + Skin, + } + + public string Resolve(string path, params RelativeTo[] roots) + { + var context = DNNContext.Current; + + var mappings = new Dictionary + { + { "[DDRMENU]", RelativeTo.Module }, + { "[MODULE]", RelativeTo.Module }, + { "[MANIFEST]", RelativeTo.Manifest }, + { "[PORTAL]", RelativeTo.Portal }, + { "[SKIN]", RelativeTo.Skin }, + { "[CONTAINER]", RelativeTo.Container }, + { "[DNN]", RelativeTo.Dnn }, + }; + foreach (var key in mappings.Keys) + { + if (path.StartsWith(key, StringComparison.InvariantCultureIgnoreCase)) + { + path = path.Substring(key.Length); + roots = new[] { mappings[key] }; + break; + } + } + + if (path.StartsWith("/")) + { + path = path.Substring(1); + } + + if (!path.StartsWith("~") && !path.Contains(":")) + { + foreach (var root in roots) + { + string resolvedPath = null; + switch (root) + { + case RelativeTo.Container: + var container = context.HostControl; + while ((container != null) && !(container is UI.Containers.Container)) + { + container = container.Parent; + } + + var containerRoot = (container == null) + ? context.SkinPath + + // ReSharper disable PossibleNullReferenceException + : Path.GetDirectoryName(((UI.Containers.Container)container).AppRelativeVirtualPath).Replace( + + // ReSharper restore PossibleNullReferenceException + '\\', '/') + "/"; + resolvedPath = Path.Combine(containerRoot, path); + break; + case RelativeTo.Dnn: + resolvedPath = Path.Combine("~/", path); + break; + case RelativeTo.Manifest: + if (!string.IsNullOrEmpty(this.manifestFolder)) + { + resolvedPath = Path.Combine(this.manifestFolder + "/", path); + } + + break; + case RelativeTo.Module: + resolvedPath = Path.Combine(DNNContext.ModuleFolder, path); + break; + case RelativeTo.Portal: + resolvedPath = Path.Combine(context.PortalSettings.HomeDirectory, path); + break; + case RelativeTo.Skin: + resolvedPath = Path.Combine(context.SkinPath, path); + break; + } + + if (!string.IsNullOrEmpty(resolvedPath)) + { + var sep = resolvedPath.LastIndexOf('/'); + var dirName = resolvedPath.Substring(0, sep + 1); + var fileName = resolvedPath.Substring(sep + 1); + + var mappedDir = HttpContext.Current.Server.MapPath(dirName); + mappedDir = mappedDir.Remove(mappedDir.Length - 1); + if (Directory.Exists(mappedDir)) + { + if (string.IsNullOrEmpty(fileName)) + { + return resolvedPath.Replace('\\', '/'); + } + + var matches = Directory.GetFileSystemEntries(mappedDir, fileName); + if (matches.Length > 0) + { + resolvedPath = (dirName + Path.GetFileName(matches[0])).Replace('\\', '/'); + return resolvedPath; + } + } + } + } + } + + return path; + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Common/Utilities.cs b/DNN Platform/Modules/DDRMenu/Common/Utilities.cs index c75c4e48007..fcb8a663833 100644 --- a/DNN Platform/Modules/DDRMenu/Common/Utilities.cs +++ b/DNN Platform/Modules/DDRMenu/Common/Utilities.cs @@ -1,107 +1,111 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Web; -using System.Web.Caching; -using System.Xml; -using System.Xml.Serialization; -using System.Xml.Xsl; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.DNNCommon { - internal static class Utilities - { - private static readonly Dictionary serialisers = new Dictionary(); + using System; + using System.Collections.Generic; + using System.IO; + using System.Web; + using System.Web.Caching; + using System.Xml; + using System.Xml.Serialization; + using System.Xml.Xsl; - internal static string CachedFileContent(string filename) - { - var cache = HttpContext.Current.Cache; - var result = cache[filename] as string; - if (result == null) - { - result = File.ReadAllText(filename); - cache.Insert(filename, result, new CacheDependency(filename)); - } + internal static class Utilities + { + private static readonly Dictionary serialisers = new Dictionary(); - return result; - } + internal static string CachedFileContent(string filename) + { + var cache = HttpContext.Current.Cache; + var result = cache[filename] as string; + if (result == null) + { + result = File.ReadAllText(filename); + cache.Insert(filename, result, new CacheDependency(filename)); + } - internal static XmlDocument CachedXml(string filename) - { - var cache = HttpContext.Current.Cache; - var result = cache[filename] as XmlDocument; - if (result == null) - { - result = new XmlDocument { XmlResolver = null }; - result.Load(filename); - cache.Insert(filename, result, new CacheDependency(filename)); - } + return result; + } - return result; - } + internal static XmlDocument CachedXml(string filename) + { + var cache = HttpContext.Current.Cache; + var result = cache[filename] as XmlDocument; + if (result == null) + { + result = new XmlDocument { XmlResolver = null }; + result.Load(filename); + cache.Insert(filename, result, new CacheDependency(filename)); + } - internal static XslCompiledTransform CachedXslt(string filename) - { - var cache = HttpContext.Current.Cache; - var result = cache[filename] as XslCompiledTransform; - if (result == null) - { - result = new XslCompiledTransform(); - using (var reader = XmlReader.Create(filename, new XmlReaderSettings {DtdProcessing = DtdProcessing.Ignore})) - result.Load(reader); - cache.Insert(filename, result, new CacheDependency(filename)); - } + return result; + } - return result; - } + internal static XslCompiledTransform CachedXslt(string filename) + { + var cache = HttpContext.Current.Cache; + var result = cache[filename] as XslCompiledTransform; + if (result == null) + { + result = new XslCompiledTransform(); + using (var reader = XmlReader.Create(filename, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) + { + result.Load(reader); + } - internal static XmlSerializer SerialiserFor(Type t) - { - XmlSerializer result; - if (!serialisers.TryGetValue(t, out result)) - { - lock (serialisers) - { - result = (t.Name == "MenuXml") - ? new XmlSerializer(t, new XmlRootAttribute {ElementName = "Root"}) - : new XmlSerializer(t); - if (!serialisers.ContainsKey(t)) - { - serialisers.Add(t, result); - } - } - } - return result; - } + cache.Insert(filename, result, new CacheDependency(filename)); + } - internal static string ConvertToJs(object obj) - { - string result; + return result; + } - if (obj == null) - { - return "null"; - } + internal static XmlSerializer SerialiserFor(Type t) + { + XmlSerializer result; + if (!serialisers.TryGetValue(t, out result)) + { + lock (serialisers) + { + result = (t.Name == "MenuXml") + ? new XmlSerializer(t, new XmlRootAttribute { ElementName = "Root" }) + : new XmlSerializer(t); + if (!serialisers.ContainsKey(t)) + { + serialisers.Add(t, result); + } + } + } - var objType = obj.GetType(); - if (objType == typeof(bool)) - { - result = (bool)obj ? "true" : "false"; - } - else if (objType == typeof(int) || objType == typeof(decimal) || objType == typeof(double)) - { - result = obj.ToString(); - } - else - { - result = String.Format("\"{0}\"", obj.ToString().Replace("\"", "\\\"")); - } + return result; + } - return result; - } - } + internal static string ConvertToJs(object obj) + { + string result; + + if (obj == null) + { + return "null"; + } + + var objType = obj.GetType(); + if (objType == typeof(bool)) + { + result = (bool)obj ? "true" : "false"; + } + else if (objType == typeof(int) || objType == typeof(decimal) || objType == typeof(double)) + { + result = obj.ToString(); + } + else + { + result = string.Format("\"{0}\"", obj.ToString().Replace("\"", "\\\"")); + } + + return result; + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Controller.cs b/DNN Platform/Modules/DDRMenu/Controller.cs index 215b4da44a2..50b1bad8ff7 100644 --- a/DNN Platform/Modules/DDRMenu/Controller.cs +++ b/DNN Platform/Modules/DDRMenu/Controller.cs @@ -1,215 +1,216 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Reflection; -using System.Security; -using System.Text.RegularExpressions; -using System.Web; -using System.Xml; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { + using System; + using System.IO; + using System.Reflection; + using System.Security; + using System.Text.RegularExpressions; + using System.Web; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Portals; public class Controller : IUpgradeable, IPortable - { - private const string ddrMenuModuleName = "DDRMenu"; - private const string ddrMenuMmoduleDefinitionName = "DDR Menu"; - + { public static readonly Regex AscxText1Regex = new Regex(Regex.Escape(@"Namespace=""DNNDoneRight.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); public static readonly Regex AscxText2Regex = new Regex(Regex.Escape(@"Namespace=""DNNGarden.TemplateEngine"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private const string ddrMenuModuleName = "DDRMenu"; + private const string ddrMenuMmoduleDefinitionName = "DDR Menu"; public static readonly Regex AscxText3Regex = new Regex(Regex.Escape(@"Assembly=""DNNDoneRight.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); public static readonly Regex AscxText4Regex = new Regex(Regex.Escape(@"Assembly=""DNNGarden.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); public string UpgradeModule(string version) - { - UpdateWebConfig(); + { + UpdateWebConfig(); - TidyModuleDefinitions(); + TidyModuleDefinitions(); - CleanOldAssemblies(); + CleanOldAssemblies(); - CheckSkinReferences(); + CheckSkinReferences(); - return "UpgradeModule completed OK"; - } + return "UpgradeModule completed OK"; + } - public string ExportModule(int moduleId) - { + public string ExportModule(int moduleId) + { var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - var moduleSettings = module.ModuleSettings; - - var settings = new Settings - { - MenuStyle = Convert.ToString(moduleSettings["MenuStyle"]), - NodeXmlPath = Convert.ToString(moduleSettings["NodeXmlPath"]), - NodeSelector = Convert.ToString(moduleSettings["NodeSelector"]), - IncludeNodes = Convert.ToString(moduleSettings["IncludeNodes"]), - ExcludeNodes = Convert.ToString(moduleSettings["ExcludeNodes"]), - NodeManipulator = Convert.ToString(moduleSettings["NodeManipulator"]), - IncludeContext = Convert.ToBoolean(moduleSettings["IncludeContext"]), - IncludeHidden = Convert.ToBoolean(moduleSettings["IncludeHidden"]), - ClientOptions = Settings.ClientOptionsFromSettingString(Convert.ToString(moduleSettings["ClientOptions"])), - TemplateArguments = - Settings.TemplateArgumentsFromSettingString(Convert.ToString(moduleSettings["TemplateArguments"])) - }; - return settings.ToXml(); - } - - public void ImportModule(int moduleId, string content, string version, int userId) - { - var settings = Settings.FromXml(content); - - ModuleController.Instance.UpdateModuleSetting(moduleId, "MenuStyle", (settings.MenuStyle ?? "")); - ModuleController.Instance.UpdateModuleSetting(moduleId, "NodeXmlPath", (settings.NodeXmlPath ?? "")); - ModuleController.Instance.UpdateModuleSetting(moduleId, "NodeSelector", (settings.NodeSelector ?? "")); - ModuleController.Instance.UpdateModuleSetting(moduleId, "IncludeNodes", (settings.IncludeNodes ?? "")); - ModuleController.Instance.UpdateModuleSetting(moduleId, "ExcludeNodes", (settings.ExcludeNodes ?? "")); - ModuleController.Instance.UpdateModuleSetting(moduleId, "NodeManipulator", (settings.NodeManipulator ?? "")); - ModuleController.Instance.UpdateModuleSetting(moduleId, "IncludeContext", settings.IncludeContext.ToString()); - ModuleController.Instance.UpdateModuleSetting(moduleId, "IncludeHidden", settings.IncludeHidden.ToString()); - ModuleController.Instance.UpdateModuleSetting(moduleId, "TemplateArguments", Settings.ToSettingString(settings.TemplateArguments)); - ModuleController.Instance.UpdateModuleSetting(moduleId, "ClientOptions", Settings.ToSettingString(settings.ClientOptions)); - } - - private static void UpdateWebConfig() - { - const string navName = "DDRMenuNavigationProvider"; - const string navType = "DotNetNuke.Web.DDRMenu.DDRMenuNavigationProvider, DotNetNuke.Web.DDRMenu"; - - var server = HttpContext.Current.Server; - var webConfig = server.MapPath("~/web.config"); - - var configXml = new XmlDocument { XmlResolver = null }; - configXml.Load(webConfig); - var navProviders = configXml.SelectSingleNode("/configuration/dotnetnuke/navigationControl/providers") as XmlElement; -// ReSharper disable PossibleNullReferenceException - var addProvider = navProviders.SelectSingleNode("add[@name='" + navName + "']") as XmlElement; -// ReSharper restore PossibleNullReferenceException - - var needsUpdate = true; - if (addProvider == null) - { - addProvider = configXml.CreateElement("add"); - addProvider.SetAttribute("name", navName); - navProviders.AppendChild(addProvider); - } - else - { - needsUpdate = (addProvider.GetAttribute("type") != navType); - } - - if (needsUpdate) - { - addProvider.SetAttribute("type", navType); - configXml.Save(webConfig); - } - } - - private static void TidyModuleDefinitions() - { - RemoveLegacyModuleDefinitions(ddrMenuModuleName, ddrMenuMmoduleDefinitionName); - RemoveLegacyModuleDefinitions("DDRMenuAdmin", "N/A"); - } - - private static void RemoveLegacyModuleDefinitions(string moduleName, string currentModuleDefinitionName) - { - var mdc = new ModuleDefinitionController(); + var moduleSettings = module.ModuleSettings; + + var settings = new Settings + { + MenuStyle = Convert.ToString(moduleSettings["MenuStyle"]), + NodeXmlPath = Convert.ToString(moduleSettings["NodeXmlPath"]), + NodeSelector = Convert.ToString(moduleSettings["NodeSelector"]), + IncludeNodes = Convert.ToString(moduleSettings["IncludeNodes"]), + ExcludeNodes = Convert.ToString(moduleSettings["ExcludeNodes"]), + NodeManipulator = Convert.ToString(moduleSettings["NodeManipulator"]), + IncludeContext = Convert.ToBoolean(moduleSettings["IncludeContext"]), + IncludeHidden = Convert.ToBoolean(moduleSettings["IncludeHidden"]), + ClientOptions = Settings.ClientOptionsFromSettingString(Convert.ToString(moduleSettings["ClientOptions"])), + TemplateArguments = + Settings.TemplateArgumentsFromSettingString(Convert.ToString(moduleSettings["TemplateArguments"])), + }; + return settings.ToXml(); + } + + public void ImportModule(int moduleId, string content, string version, int userId) + { + var settings = Settings.FromXml(content); + + ModuleController.Instance.UpdateModuleSetting(moduleId, "MenuStyle", settings.MenuStyle ?? string.Empty); + ModuleController.Instance.UpdateModuleSetting(moduleId, "NodeXmlPath", settings.NodeXmlPath ?? string.Empty); + ModuleController.Instance.UpdateModuleSetting(moduleId, "NodeSelector", settings.NodeSelector ?? string.Empty); + ModuleController.Instance.UpdateModuleSetting(moduleId, "IncludeNodes", settings.IncludeNodes ?? string.Empty); + ModuleController.Instance.UpdateModuleSetting(moduleId, "ExcludeNodes", settings.ExcludeNodes ?? string.Empty); + ModuleController.Instance.UpdateModuleSetting(moduleId, "NodeManipulator", settings.NodeManipulator ?? string.Empty); + ModuleController.Instance.UpdateModuleSetting(moduleId, "IncludeContext", settings.IncludeContext.ToString()); + ModuleController.Instance.UpdateModuleSetting(moduleId, "IncludeHidden", settings.IncludeHidden.ToString()); + ModuleController.Instance.UpdateModuleSetting(moduleId, "TemplateArguments", Settings.ToSettingString(settings.TemplateArguments)); + ModuleController.Instance.UpdateModuleSetting(moduleId, "ClientOptions", Settings.ToSettingString(settings.ClientOptions)); + } + + private static void UpdateWebConfig() + { + const string navName = "DDRMenuNavigationProvider"; + const string navType = "DotNetNuke.Web.DDRMenu.DDRMenuNavigationProvider, DotNetNuke.Web.DDRMenu"; + + var server = HttpContext.Current.Server; + var webConfig = server.MapPath("~/web.config"); + + var configXml = new XmlDocument { XmlResolver = null }; + configXml.Load(webConfig); + var navProviders = configXml.SelectSingleNode("/configuration/dotnetnuke/navigationControl/providers") as XmlElement; + + // ReSharper disable PossibleNullReferenceException + var addProvider = navProviders.SelectSingleNode("add[@name='" + navName + "']") as XmlElement; + + // ReSharper restore PossibleNullReferenceException + var needsUpdate = true; + if (addProvider == null) + { + addProvider = configXml.CreateElement("add"); + addProvider.SetAttribute("name", navName); + navProviders.AppendChild(addProvider); + } + else + { + needsUpdate = addProvider.GetAttribute("type") != navType; + } + + if (needsUpdate) + { + addProvider.SetAttribute("type", navType); + configXml.Save(webConfig); + } + } + + private static void TidyModuleDefinitions() + { + RemoveLegacyModuleDefinitions(ddrMenuModuleName, ddrMenuMmoduleDefinitionName); + RemoveLegacyModuleDefinitions("DDRMenuAdmin", "N/A"); + } + + private static void RemoveLegacyModuleDefinitions(string moduleName, string currentModuleDefinitionName) + { + var mdc = new ModuleDefinitionController(); var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, Null.NullInteger); - if (desktopModule == null) - { - return; - } + if (desktopModule == null) + { + return; + } - var desktopModuleId = desktopModule.DesktopModuleID; + var desktopModuleId = desktopModule.DesktopModuleID; var modDefs = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId); - var currentModDefId = 0; - foreach (var modDefKeyPair in modDefs) - { + var currentModDefId = 0; + foreach (var modDefKeyPair in modDefs) + { if (modDefKeyPair.Value.FriendlyName.Equals(currentModuleDefinitionName, StringComparison.InvariantCultureIgnoreCase)) - { + { currentModDefId = modDefKeyPair.Value.ModuleDefID; - } - } + } + } - foreach (var modDefKeyPair in modDefs) - { + foreach (var modDefKeyPair in modDefs) + { var oldModDefId = modDefKeyPair.Value.ModuleDefID; - if (oldModDefId != currentModDefId) - { - foreach (ModuleInfo mod in ModuleController.Instance.GetAllModules()) - { - if (mod.ModuleDefID == oldModDefId) - { - mod.ModuleDefID = currentModDefId; + if (oldModDefId != currentModDefId) + { + foreach (ModuleInfo mod in ModuleController.Instance.GetAllModules()) + { + if (mod.ModuleDefID == oldModDefId) + { + mod.ModuleDefID = currentModDefId; ModuleController.Instance.UpdateModule(mod); - } - } + } + } - mdc.DeleteModuleDefinition(oldModDefId); - } - } + mdc.DeleteModuleDefinition(oldModDefId); + } + } modDefs = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId); - if (modDefs.Count == 0) - { - new DesktopModuleController().DeleteDesktopModule(desktopModuleId); - } - } - - private static void CleanOldAssemblies() - { - var assembliesToRemove = new[] {"DNNDoneRight.DDRMenu.dll", "DNNGarden.DDRMenu.dll"}; - - var server = HttpContext.Current.Server; - var assemblyPath = server.MapPath("~/bin/"); - foreach (var assembly in assembliesToRemove) - { - File.Delete(Path.Combine(assemblyPath, assembly)); - } - } + if (modDefs.Count == 0) + { + new DesktopModuleController().DeleteDesktopModule(desktopModuleId); + } + } + + private static void CleanOldAssemblies() + { + var assembliesToRemove = new[] { "DNNDoneRight.DDRMenu.dll", "DNNGarden.DDRMenu.dll" }; + + var server = HttpContext.Current.Server; + var assemblyPath = server.MapPath("~/bin/"); + foreach (var assembly in assembliesToRemove) + { + File.Delete(Path.Combine(assemblyPath, assembly)); + } + } private static void CheckSkinReferences() - { - var server = HttpContext.Current.Server; - var portalsRoot = server.MapPath("~/Portals/"); - foreach (var portal in Directory.GetDirectories(portalsRoot)) - { - foreach (var skinControl in Directory.GetFiles(portal, "*.ascx", SearchOption.AllDirectories)) - { - try - { - var ascxText = File.ReadAllText(skinControl); - var originalText = ascxText; + { + var server = HttpContext.Current.Server; + var portalsRoot = server.MapPath("~/Portals/"); + foreach (var portal in Directory.GetDirectories(portalsRoot)) + { + foreach (var skinControl in Directory.GetFiles(portal, "*.ascx", SearchOption.AllDirectories)) + { + try + { + var ascxText = File.ReadAllText(skinControl); + var originalText = ascxText; ascxText = AscxText1Regex.Replace(ascxText, @"Namespace=""DotNetNuke.Web.DDRMenu.TemplateEngine"""); - ascxText = AscxText2Regex.Replace(ascxText, @"Namespace=""DotNetNuke.Web.DDRMenu.TemplateEngine"""); + ascxText = AscxText2Regex.Replace(ascxText, @"Namespace=""DotNetNuke.Web.DDRMenu.TemplateEngine"""); ascxText = AscxText3Regex.Replace(ascxText, @"Assembly=""DotNetNuke.Web.DDRMenu"""); - ascxText = AscxText4Regex.Replace(ascxText, @"Assembly=""DotNetNuke.Web.DDRMenu"""); - - if (!ascxText.Equals(originalText)) - { - File.WriteAllText(skinControl, ascxText); - } - } - catch (IOException) - { - } - catch (UnauthorizedAccessException) - { - } - catch (SecurityException) - { - } - } - } - } - } + ascxText = AscxText4Regex.Replace(ascxText, @"Assembly=""DotNetNuke.Web.DDRMenu"""); + + if (!ascxText.Equals(originalText)) + { + File.WriteAllText(skinControl, ascxText); + } + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + catch (SecurityException) + { + } + } + } + } + } } diff --git a/DNN Platform/Modules/DDRMenu/DDRMenu.dnn b/DNN Platform/Modules/DDRMenu/DDRMenu.dnn index 4fd2b06f33c..84814105449 100644 --- a/DNN Platform/Modules/DDRMenu/DDRMenu.dnn +++ b/DNN Platform/Modules/DDRMenu/DDRMenu.dnn @@ -1,6 +1,6 @@  - + DDR Menu DotNetNuke Navigation Provider. diff --git a/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs b/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs index 582642ec575..fac99a45cad 100644 --- a/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs +++ b/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs @@ -1,59 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Web.DDRMenu.DNNCommon; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - internal class DDRMenuControl : WebControl, IPostBackEventHandler - { - public override bool EnableViewState { get { return false; } set { } } - - internal MenuNode RootNode { get; set; } - internal Boolean SkipLocalisation { get; set; } - internal Settings MenuSettings { get; set; } - - public delegate void MenuClickEventHandler(string id); - - public event MenuClickEventHandler NodeClick; - - private MenuBase menu; - - protected override void OnPreRender(EventArgs e) - { - using (new DNNContext(this)) - { - base.OnPreRender(e); - - MenuSettings.MenuStyle = MenuSettings.MenuStyle ?? "DNNMenu"; - menu = MenuBase.Instantiate(MenuSettings.MenuStyle); - menu.RootNode = RootNode ?? new MenuNode(); - menu.SkipLocalisation = SkipLocalisation; - menu.ApplySettings(MenuSettings); - - menu.PreRender(); - } - } - - protected override void Render(HtmlTextWriter htmlWriter) - { - using (new DNNContext(this)) - menu.Render(htmlWriter); - } - - public void RaisePostBackEvent(string eventArgument) - { - using (new DNNContext(this)) - { - if (NodeClick != null) - { - NodeClick(eventArgument); - } - } - } - } + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Web.DDRMenu.DNNCommon; + + internal class DDRMenuControl : WebControl, IPostBackEventHandler + { + private MenuBase menu; + + public delegate void MenuClickEventHandler(string id); + + public event MenuClickEventHandler NodeClick; + + public override bool EnableViewState + { + get { return false; } + set { } + } + + internal MenuNode RootNode { get; set; } + + internal bool SkipLocalisation { get; set; } + + internal Settings MenuSettings { get; set; } + + public void RaisePostBackEvent(string eventArgument) + { + using (new DNNContext(this)) + { + if (this.NodeClick != null) + { + this.NodeClick(eventArgument); + } + } + } + + protected override void OnPreRender(EventArgs e) + { + using (new DNNContext(this)) + { + base.OnPreRender(e); + + this.MenuSettings.MenuStyle = this.MenuSettings.MenuStyle ?? "DNNMenu"; + this.menu = MenuBase.Instantiate(this.MenuSettings.MenuStyle); + this.menu.RootNode = this.RootNode ?? new MenuNode(); + this.menu.SkipLocalisation = this.SkipLocalisation; + this.menu.ApplySettings(this.MenuSettings); + + this.menu.PreRender(); + } + } + + protected override void Render(HtmlTextWriter htmlWriter) + { + using (new DNNContext(this)) + { + this.menu.Render(htmlWriter); + } + } + } } diff --git a/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs b/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs index 589bfa0ba6a..d6f13fc60b3 100644 --- a/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs +++ b/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs @@ -1,211 +1,295 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Web.UI; -using DotNetNuke.Web.DDRMenu.Localisation; -using DotNetNuke.Web.DDRMenu.TemplateEngine; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.WebControls; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - public class DDRMenuNavigationProvider : NavigationProvider - { - public override Alignment ControlAlignment { get; set; } - public override bool IndicateChildren { get; set; } - public override bool PopulateNodesFromClient { get; set; } - public override decimal MouseOutHideDelay { get; set; } - public override decimal StyleBorderWidth { get; set; } - public override decimal StyleControlHeight { get; set; } - public override decimal StyleFontSize { get; set; } - public override decimal StyleIconWidth { get; set; } - public override decimal StyleNodeHeight { get; set; } - public override double EffectsDuration { get; set; } - public override HoverAction MouseOverAction { get; set; } - public override HoverDisplay MouseOverDisplay { get; set; } - public override int EffectsShadowStrength { get; set; } - public override Orientation ControlOrientation { get; set; } - public override string CSSBreadCrumbRoot { get; set; } - public override string CSSBreadCrumbSub { get; set; } - public override string CSSBreak { get; set; } - public override string CSSContainerRoot { get; set; } - public override string CSSContainerSub { get; set; } - public override string CSSIcon { get; set; } - public override string CSSIndicateChildRoot { get; set; } - public override string CSSIndicateChildSub { get; set; } - public override string CSSLeftSeparator { get; set; } - public override string CSSLeftSeparatorBreadCrumb { get; set; } - public override string CSSLeftSeparatorSelection { get; set; } - public override string CSSNode { get; set; } - public override string CSSNodeHover { get; set; } - public override string CSSNodeHoverRoot { get; set; } - public override string CSSNodeHoverSub { get; set; } - public override string CSSNodeRoot { get; set; } - public override string CSSNodeSelectedRoot { get; set; } - public override string CSSNodeSelectedSub { get; set; } - public override string CSSRightSeparator { get; set; } - public override string CSSRightSeparatorBreadCrumb { get; set; } - public override string CSSRightSeparatorSelection { get; set; } - public override string CSSSeparator { get; set; } - public override string EffectsShadowColor { get; set; } - public override string EffectsShadowDirection { get; set; } - public override string EffectsStyle { get; set; } - public override string EffectsTransition { get; set; } - public override string ForceCrawlerDisplay { get; set; } - public override string ForceDownLevel { get; set; } - public override string IndicateChildImageExpandedRoot { get; set; } - public override string IndicateChildImageExpandedSub { get; set; } - public override string IndicateChildImageRoot { get; set; } - public override string IndicateChildImageSub { get; set; } - public override string NodeLeftHTMLBreadCrumbRoot { get; set; } - public override string NodeLeftHTMLBreadCrumbSub { get; set; } - public override string NodeLeftHTMLRoot { get; set; } - public override string NodeLeftHTMLSub { get; set; } - public override string NodeRightHTMLBreadCrumbRoot { get; set; } - public override string NodeRightHTMLBreadCrumbSub { get; set; } - public override string NodeRightHTMLRoot { get; set; } - public override string NodeRightHTMLSub { get; set; } - public override string PathImage { get; set; } - public override string PathSystemImage { get; set; } - public override string PathSystemScript { get; set; } - public override string SeparatorHTML { get; set; } - public override string SeparatorLeftHTML { get; set; } - public override string SeparatorLeftHTMLActive { get; set; } - public override string SeparatorLeftHTMLBreadCrumb { get; set; } - public override string SeparatorRightHTML { get; set; } - public override string SeparatorRightHTMLActive { get; set; } - public override string SeparatorRightHTMLBreadCrumb { get; set; } - public override string StyleBackColor { get; set; } - public override string StyleFontBold { get; set; } - public override string StyleFontNames { get; set; } - public override string StyleForeColor { get; set; } - public override string StyleHighlightColor { get; set; } - public override string StyleIconBackColor { get; set; } - public override string StyleRoot { get; set; } - public override string StyleSelectionBorderColor { get; set; } - public override string StyleSelectionColor { get; set; } - public override string StyleSelectionForeColor { get; set; } - public override string StyleSub { get; set; } - public override string WorkImage { get; set; } - public override List CustomAttributes { get; set; } - - private DDRMenuControl menuControl; - - public override Control NavigationControl { get { return menuControl; } } - - public override string ControlID { get; set; } - - public override bool SupportsPopulateOnDemand { get { return false; } } - - public override string CSSControl { get; set; } - - public string MenuStyle { get; set; } - - public List TemplateArguments { get; set; } - - public override void Initialize() - { - menuControl = new DDRMenuControl {ID = ControlID, EnableViewState = false}; - menuControl.NodeClick += RaiseEvent_NodeClick; - } - - public override void Bind(DNNNodeCollection objNodes) - { - Bind(objNodes, true); - } - - public void Bind(DNNNodeCollection objNodes, bool localise) - { - var clientOptions = new List(); - - var ignoreProperties = new List - { - "CustomAttributes", - "NavigationControl", - "SupportsPopulateOnDemand", - "NodeXmlPath", - "NodeSelector", - "IncludeContext", - "IncludeHidden", - "IncludeNodes", - "ExcludeNodes", - "NodeManipulator" - }; - - foreach (var prop in - typeof(NavigationProvider).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) - { - if (!string.IsNullOrEmpty(prop.Name) && !ignoreProperties.Contains(prop.Name)) - { - var propValue = prop.GetValue(this, null); - if (propValue != null) - { - if (propValue is bool) - { - clientOptions.Add(new ClientBoolean(prop.Name, propValue.ToString())); - } - else if (propValue is int || propValue is decimal || propValue is double) - { - clientOptions.Add(new ClientNumber(prop.Name, propValue.ToString())); - } - else - { - clientOptions.Add(new ClientString(prop.Name, propValue.ToString())); - } - } - } - } - - if (CustomAttributes != null) - { - foreach (var attr in CustomAttributes) - { - if (!string.IsNullOrEmpty(attr.Name)) - { - clientOptions.Add(new ClientString(attr.Name, attr.Value)); - } - } - } - - if (localise) - { - objNodes = Localiser.LocaliseDNNNodeCollection(objNodes); - } - - menuControl.RootNode = new MenuNode(objNodes); - menuControl.SkipLocalisation = !localise; - menuControl.MenuSettings = new Settings - { - MenuStyle = GetCustomAttribute("MenuStyle") ?? MenuStyle ?? "DNNMenu", - NodeXmlPath = GetCustomAttribute("NodeXmlPath"), - NodeSelector = GetCustomAttribute("NodeSelector"), - IncludeContext = Convert.ToBoolean(GetCustomAttribute("IncludeContext") ?? "false"), - IncludeHidden = Convert.ToBoolean(GetCustomAttribute("IncludeHidden") ?? "false"), - IncludeNodes = GetCustomAttribute("IncludeNodes"), - ExcludeNodes = GetCustomAttribute("ExcludeNodes"), - NodeManipulator = GetCustomAttribute("NodeManipulator"), - ClientOptions = clientOptions, - TemplateArguments = TemplateArguments, - }; - } - - private string GetCustomAttribute(string attributeName) - { - string xmlValue = null; - if (CustomAttributes != null) - { - var xmlAttr = CustomAttributes.Find(a => a.Name.Equals(attributeName, StringComparison.InvariantCultureIgnoreCase)); - if (xmlAttr != null) - { - xmlValue = xmlAttr.Value; - } - } - return xmlValue; - } - } + using System; + using System.Collections.Generic; + using System.Reflection; + using System.Web.UI; + + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.DDRMenu.Localisation; + using DotNetNuke.Web.DDRMenu.TemplateEngine; + + public class DDRMenuNavigationProvider : NavigationProvider + { + private DDRMenuControl menuControl; + + public override Alignment ControlAlignment { get; set; } + + public override bool IndicateChildren { get; set; } + + public override bool PopulateNodesFromClient { get; set; } + + public override decimal MouseOutHideDelay { get; set; } + + public override decimal StyleBorderWidth { get; set; } + + public override decimal StyleControlHeight { get; set; } + + public override decimal StyleFontSize { get; set; } + + public override decimal StyleIconWidth { get; set; } + + public override decimal StyleNodeHeight { get; set; } + + public override double EffectsDuration { get; set; } + + public override HoverAction MouseOverAction { get; set; } + + public override HoverDisplay MouseOverDisplay { get; set; } + + public override int EffectsShadowStrength { get; set; } + + public override Orientation ControlOrientation { get; set; } + + public override string CSSBreadCrumbRoot { get; set; } + + public override string CSSBreadCrumbSub { get; set; } + + public override string CSSBreak { get; set; } + + public override string CSSContainerRoot { get; set; } + + public override string CSSContainerSub { get; set; } + + public override string CSSIcon { get; set; } + + public override string CSSIndicateChildRoot { get; set; } + + public override string CSSIndicateChildSub { get; set; } + + public override string CSSLeftSeparator { get; set; } + + public override string CSSLeftSeparatorBreadCrumb { get; set; } + + public override string CSSLeftSeparatorSelection { get; set; } + + public override string CSSNode { get; set; } + + public override string CSSNodeHover { get; set; } + + public override string CSSNodeHoverRoot { get; set; } + + public override string CSSNodeHoverSub { get; set; } + + public override string CSSNodeRoot { get; set; } + + public override string CSSNodeSelectedRoot { get; set; } + + public override string CSSNodeSelectedSub { get; set; } + + public override string CSSRightSeparator { get; set; } + + public override string CSSRightSeparatorBreadCrumb { get; set; } + + public override string CSSRightSeparatorSelection { get; set; } + + public override string CSSSeparator { get; set; } + + public override string EffectsShadowColor { get; set; } + + public override string EffectsShadowDirection { get; set; } + + public override string EffectsStyle { get; set; } + + public override string EffectsTransition { get; set; } + + public override string ForceCrawlerDisplay { get; set; } + + public override string ForceDownLevel { get; set; } + + public override string IndicateChildImageExpandedRoot { get; set; } + + public override string IndicateChildImageExpandedSub { get; set; } + + public override string IndicateChildImageRoot { get; set; } + + public override string IndicateChildImageSub { get; set; } + + public override string NodeLeftHTMLBreadCrumbRoot { get; set; } + + public override string NodeLeftHTMLBreadCrumbSub { get; set; } + + public override string NodeLeftHTMLRoot { get; set; } + + public override string NodeLeftHTMLSub { get; set; } + + public override string NodeRightHTMLBreadCrumbRoot { get; set; } + + public override string NodeRightHTMLBreadCrumbSub { get; set; } + + public override string NodeRightHTMLRoot { get; set; } + + public override string NodeRightHTMLSub { get; set; } + + public override string PathImage { get; set; } + + public override string PathSystemImage { get; set; } + + public override string PathSystemScript { get; set; } + + public override string SeparatorHTML { get; set; } + + public override string SeparatorLeftHTML { get; set; } + + public override string SeparatorLeftHTMLActive { get; set; } + + public override string SeparatorLeftHTMLBreadCrumb { get; set; } + + public override string SeparatorRightHTML { get; set; } + + public override string SeparatorRightHTMLActive { get; set; } + + public override string SeparatorRightHTMLBreadCrumb { get; set; } + + public override string StyleBackColor { get; set; } + + public override string StyleFontBold { get; set; } + + public override string StyleFontNames { get; set; } + + public override string StyleForeColor { get; set; } + + public override string StyleHighlightColor { get; set; } + + public override string StyleIconBackColor { get; set; } + + public override string StyleRoot { get; set; } + + public override string StyleSelectionBorderColor { get; set; } + + public override string StyleSelectionColor { get; set; } + + public override string StyleSelectionForeColor { get; set; } + + public override string StyleSub { get; set; } + + public override string WorkImage { get; set; } + + public override List CustomAttributes { get; set; } + + public override Control NavigationControl + { + get { return this.menuControl; } + } + + public override string ControlID { get; set; } + + public override bool SupportsPopulateOnDemand + { + get { return false; } + } + + public override string CSSControl { get; set; } + + public string MenuStyle { get; set; } + + public List TemplateArguments { get; set; } + + public override void Initialize() + { + this.menuControl = new DDRMenuControl { ID = this.ControlID, EnableViewState = false }; + this.menuControl.NodeClick += this.RaiseEvent_NodeClick; + } + + public override void Bind(DNNNodeCollection objNodes) + { + this.Bind(objNodes, true); + } + + public void Bind(DNNNodeCollection objNodes, bool localise) + { + var clientOptions = new List(); + + var ignoreProperties = new List + { + "CustomAttributes", + "NavigationControl", + "SupportsPopulateOnDemand", + "NodeXmlPath", + "NodeSelector", + "IncludeContext", + "IncludeHidden", + "IncludeNodes", + "ExcludeNodes", + "NodeManipulator", + }; + + foreach (var prop in + typeof(NavigationProvider).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) + { + if (!string.IsNullOrEmpty(prop.Name) && !ignoreProperties.Contains(prop.Name)) + { + var propValue = prop.GetValue(this, null); + if (propValue != null) + { + if (propValue is bool) + { + clientOptions.Add(new ClientBoolean(prop.Name, propValue.ToString())); + } + else if (propValue is int || propValue is decimal || propValue is double) + { + clientOptions.Add(new ClientNumber(prop.Name, propValue.ToString())); + } + else + { + clientOptions.Add(new ClientString(prop.Name, propValue.ToString())); + } + } + } + } + + if (this.CustomAttributes != null) + { + foreach (var attr in this.CustomAttributes) + { + if (!string.IsNullOrEmpty(attr.Name)) + { + clientOptions.Add(new ClientString(attr.Name, attr.Value)); + } + } + } + + if (localise) + { + objNodes = Localiser.LocaliseDNNNodeCollection(objNodes); + } + + this.menuControl.RootNode = new MenuNode(objNodes); + this.menuControl.SkipLocalisation = !localise; + this.menuControl.MenuSettings = new Settings + { + MenuStyle = this.GetCustomAttribute("MenuStyle") ?? this.MenuStyle ?? "DNNMenu", + NodeXmlPath = this.GetCustomAttribute("NodeXmlPath"), + NodeSelector = this.GetCustomAttribute("NodeSelector"), + IncludeContext = Convert.ToBoolean(this.GetCustomAttribute("IncludeContext") ?? "false"), + IncludeHidden = Convert.ToBoolean(this.GetCustomAttribute("IncludeHidden") ?? "false"), + IncludeNodes = this.GetCustomAttribute("IncludeNodes"), + ExcludeNodes = this.GetCustomAttribute("ExcludeNodes"), + NodeManipulator = this.GetCustomAttribute("NodeManipulator"), + ClientOptions = clientOptions, + TemplateArguments = this.TemplateArguments, + }; + } + + private string GetCustomAttribute(string attributeName) + { + string xmlValue = null; + if (this.CustomAttributes != null) + { + var xmlAttr = this.CustomAttributes.Find(a => a.Name.Equals(attributeName, StringComparison.InvariantCultureIgnoreCase)); + if (xmlAttr != null) + { + xmlValue = xmlAttr.Value; + } + } + + return xmlValue; + } + } } diff --git a/DNN Platform/Modules/DDRMenu/DNNAbstract.cs b/DNN Platform/Modules/DDRMenu/DNNAbstract.cs index eeeff773787..db03e37e0a8 100644 --- a/DNN Platform/Modules/DDRMenu/DNNAbstract.cs +++ b/DNN Platform/Modules/DDRMenu/DNNAbstract.cs @@ -1,92 +1,93 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// DNN 6.0.0 version - -using System; -using System.Collections.Generic; -using System.Web; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Abstractions; -using DotNetNuke.UI; -using DotNetNuke.UI.WebControls; -using DotNetNuke.Web.DDRMenu.DNNCommon; -using DotNetNuke.Web.DDRMenu.TemplateEngine; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { + using System; + using System.Collections.Generic; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.UI; + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.DDRMenu.DNNCommon; + using DotNetNuke.Web.DDRMenu.TemplateEngine; + using Microsoft.Extensions.DependencyInjection; + internal static class DNNAbstract - { - public static string GetLoginUrl() - { - var request = HttpContext.Current.Request; + { + public static string GetLoginUrl() + { + var request = HttpContext.Current.Request; + + if (request.IsAuthenticated) + { + return Globals.DependencyProvider.GetRequiredService().NavigateURL(PortalSettings.Current.ActiveTab.TabID, "Logoff"); + } + + var returnUrl = HttpContext.Current.Request.RawUrl; + if (returnUrl.IndexOf("?returnurl=") != -1) + { + returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=")); + } - if (request.IsAuthenticated) - { - return Globals.DependencyProvider.GetRequiredService().NavigateURL(PortalSettings.Current.ActiveTab.TabID, "Logoff"); - } + returnUrl = HttpUtility.UrlEncode(returnUrl); - var returnUrl = HttpContext.Current.Request.RawUrl; - if (returnUrl.IndexOf("?returnurl=") != -1) - { - returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=")); - } - returnUrl = HttpUtility.UrlEncode(returnUrl); + return Globals.LoginURL(returnUrl, !string.IsNullOrEmpty(request.QueryString["override"])); + } - return Globals.LoginURL(returnUrl, !String.IsNullOrEmpty(request.QueryString["override"])); - } + public static string GetUserUrl() + { + var request = HttpContext.Current.Request; + var portalSettings = PortalSettings.Current; + if (!request.IsAuthenticated) + { + if (portalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) + { + return Globals.RegisterURL(HttpUtility.UrlEncode(Globals.DependencyProvider.GetRequiredService().NavigateURL()), Null.NullString); + } + } + else + { + var objUserInfo = UserController.Instance.GetCurrentUserInfo(); + if (objUserInfo.UserID != -1) + { + return Globals.UserProfileURL(objUserInfo.UserID); + } + } - public static string GetUserUrl() - { - var request = HttpContext.Current.Request; - var portalSettings = PortalSettings.Current; - if (!request.IsAuthenticated) - { - if (portalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) - { - return Globals.RegisterURL(HttpUtility.UrlEncode(Globals.DependencyProvider.GetRequiredService().NavigateURL()), Null.NullString); - } - } - else - { - var objUserInfo = UserController.Instance.GetCurrentUserInfo(); - if (objUserInfo.UserID != -1) - { - return Globals.UserProfileURL(objUserInfo.UserID); - } - } - return ""; - } + return string.Empty; + } - public static string GetCurrentCulture() - { - return DNNContext.Current.PortalSettings.CultureCode; - } + public static string GetCurrentCulture() + { + return DNNContext.Current.PortalSettings.CultureCode; + } - public static IEnumerable SupportedTemplateProcessors() - { - return new ITemplateProcessor[] { new TokenTemplateProcessor(), new RazorTemplateProcessor(), new XsltTemplateProcessor()}; - } + public static IEnumerable SupportedTemplateProcessors() + { + return new ITemplateProcessor[] { new TokenTemplateProcessor(), new RazorTemplateProcessor(), new XsltTemplateProcessor() }; + } - public static int GetNavNodeOptions(bool includeHidden) - { - return (int)Navigation.NavNodeOptions.IncludeSiblings + (int)Navigation.NavNodeOptions.IncludeSelf + - (includeHidden ? (int)Navigation.NavNodeOptions.IncludeHiddenNodes : 0); - } + public static int GetNavNodeOptions(bool includeHidden) + { + return (int)Navigation.NavNodeOptions.IncludeSiblings + (int)Navigation.NavNodeOptions.IncludeSelf + + (includeHidden ? (int)Navigation.NavNodeOptions.IncludeHiddenNodes : 0); + } - public static bool IncludeHiddenSupported() - { - return true; - } + public static bool IncludeHiddenSupported() + { + return true; + } - public static void DNNNodeToMenuNode(DNNNode dnnNode, MenuNode menuNode) - { - menuNode.LargeImage = dnnNode.LargeImage; - } - } + public static void DNNNodeToMenuNode(DNNNode dnnNode, MenuNode menuNode) + { + menuNode.LargeImage = dnnNode.LargeImage; + } + } } diff --git a/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj b/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj index 1627b9c13b8..f50c76dee9e 100644 --- a/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj +++ b/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj @@ -181,6 +181,9 @@ + + stylecop.json + Designer @@ -209,6 +212,10 @@ + + + + diff --git a/DNN Platform/Modules/DDRMenu/INodeManipulator.cs b/DNN Platform/Modules/DDRMenu/INodeManipulator.cs index f4cbe4bc242..587065b0ee4 100644 --- a/DNN Platform/Modules/DDRMenu/INodeManipulator.cs +++ b/DNN Platform/Modules/DDRMenu/INodeManipulator.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Portals; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - public interface INodeManipulator - { - List ManipulateNodes(List nodes, PortalSettings portalSettings); - } + using System.Collections.Generic; + + using DotNetNuke.Entities.Portals; + + public interface INodeManipulator + { + List ManipulateNodes(List nodes, PortalSettings portalSettings); + } } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs b/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs index 95cd344baf9..d395eb65460 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs @@ -1,59 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Reflection; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.UI.WebControls; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.Localisation { + using System; + using System.Collections.Generic; + using System.Reflection; + + using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.UI.WebControls; [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public class Apollo : ILocalisation - { - private bool haveChecked; - private MethodInfo apiMember; + { + private bool haveChecked; + private MethodInfo apiMember; [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public bool HaveApi() - { - if (!haveChecked) - { - try - { + { + if (!this.haveChecked) + { + try + { if (DesktopModuleController.GetDesktopModuleByModuleName("PageLocalization", PortalSettings.Current.PortalId) != null) - { - var api = Activator.CreateInstance("Apollo.LocalizationApi", "Apollo.DNN_Localization.LocalizeTab").Unwrap(); - var apiType = api.GetType(); - apiMember = apiType.GetMethod("getLocalizedTab", new[] {typeof(TabInfo)}); - } - } -// ReSharper disable EmptyGeneralCatchClause - catch -// ReSharper restore EmptyGeneralCatchClause - { - } - haveChecked = true; - } - - return (apiMember != null); - } + { + var api = Activator.CreateInstance("Apollo.LocalizationApi", "Apollo.DNN_Localization.LocalizeTab").Unwrap(); + var apiType = api.GetType(); + this.apiMember = apiType.GetMethod("getLocalizedTab", new[] { typeof(TabInfo) }); + } + } + + // ReSharper disable EmptyGeneralCatchClause + catch + + // ReSharper restore EmptyGeneralCatchClause + { + } + + this.haveChecked = true; + } + + return this.apiMember != null; + } [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public TabInfo LocaliseTab(TabInfo tab, int portalId) - { - return apiMember.Invoke(null, new object[] {tab}) as TabInfo ?? tab; - } + { + return this.apiMember.Invoke(null, new object[] { tab }) as TabInfo ?? tab; + } [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) - { - return null; - } - } + { + return null; + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs b/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs index 289b35be8c0..58263339041 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs @@ -1,85 +1,88 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.WebControls; -using effority.Ealo.Specialized; -using EaloTabInfo = effority.Ealo.Specialized.TabInfo; -using TabInfo = DotNetNuke.Entities.Tabs.TabInfo; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.Localisation { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; + using DotNetNuke.UI.WebControls; + using effority.Ealo.Specialized; + + using EaloTabInfo = effority.Ealo.Specialized.TabInfo; + using TabInfo = DotNetNuke.Entities.Tabs.TabInfo; [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public class Ealo : ILocalisation - { - private bool haveChecked; - private bool found; + { + private bool haveChecked; + private bool found; [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public bool HaveApi() - { - if (!haveChecked) - { - found = (DesktopModuleController.GetDesktopModuleByModuleName("effority.Ealo.Tabs", PortalSettings.Current.PortalId) != null); - haveChecked = true; - } + { + if (!this.haveChecked) + { + this.found = DesktopModuleController.GetDesktopModuleByModuleName("effority.Ealo.Tabs", PortalSettings.Current.PortalId) != null; + this.haveChecked = true; + } - return found; - } + return this.found; + } [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public TabInfo LocaliseTab(TabInfo tab, int portalId) - { - return EaloWorker.LocaliseTab(tab, portalId); - } + { + return EaloWorker.LocaliseTab(tab, portalId); + } [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] public DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) - { - return null; - } + { + return null; + } + + // Separate class only instantiated if Ealo is available. + private static class EaloWorker + { + private static readonly Dictionary> ealoTabLookup = + new Dictionary>(); + + public static TabInfo LocaliseTab(TabInfo tab, int portalId) + { + var culture = DNNAbstract.GetCurrentCulture(); + Dictionary ealoTabs; + if (!ealoTabLookup.TryGetValue(culture, out ealoTabs)) + { + ealoTabs = Tabs.GetAllTabsAsDictionary(culture, true); + lock (ealoTabLookup) + { + if (!ealoTabLookup.ContainsKey(culture)) + { + ealoTabLookup.Add(culture, ealoTabs); + } + } + } - // Separate class only instantiated if Ealo is available. - static class EaloWorker - { - private static readonly Dictionary> ealoTabLookup = - new Dictionary>(); + EaloTabInfo ealoTab; + if (ealoTabs.TryGetValue(tab.TabID, out ealoTab)) + { + if (ealoTab.EaloTabName != null) + { + tab.TabName = ealoTab.EaloTabName.StringTextOrFallBack; + } - public static TabInfo LocaliseTab(TabInfo tab, int portalId) - { - var culture = DNNAbstract.GetCurrentCulture(); - Dictionary ealoTabs; - if (!ealoTabLookup.TryGetValue(culture, out ealoTabs)) - { - ealoTabs = Tabs.GetAllTabsAsDictionary(culture, true); - lock (ealoTabLookup) - { - if (!ealoTabLookup.ContainsKey(culture)) - { - ealoTabLookup.Add(culture, ealoTabs); - } - } - } + if (ealoTab.EaloTitle != null) + { + tab.Title = ealoTab.EaloTitle.StringTextOrFallBack; + } + } - EaloTabInfo ealoTab; - if (ealoTabs.TryGetValue(tab.TabID, out ealoTab)) - { - if (ealoTab.EaloTabName != null) - { - tab.TabName = ealoTab.EaloTabName.StringTextOrFallBack; - } - if (ealoTab.EaloTitle != null) - { - tab.Title = ealoTab.EaloTitle.StringTextOrFallBack; - } - } - return tab; - } - } - } + return tab; + } + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs b/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs index 06dfddc25ff..a46d03c9334 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs @@ -1,78 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Reflection; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.UI.WebControls; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.Localisation { + using System; + using System.Reflection; + + using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.UI.WebControls; public class Generic : ILocalisation - { - private bool haveChecked; - private object locApi; - private MethodInfo locTab; - private MethodInfo locNodes; + { + private bool haveChecked; + private object locApi; + private MethodInfo locTab; + private MethodInfo locNodes; + + public bool HaveApi() + { + if (!this.haveChecked) + { + var modules = DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId); + foreach (var moduleKeyPair in modules) + { + if (!string.IsNullOrEmpty(moduleKeyPair.Value.BusinessControllerClass)) + { + try + { + this.locApi = Reflection.CreateObject(moduleKeyPair.Value.BusinessControllerClass, moduleKeyPair.Value.BusinessControllerClass); + this.locTab = this.locApi.GetType().GetMethod("LocaliseTab", new[] { typeof(TabInfo), typeof(int) }); + if (this.locTab != null) + { + if (this.locTab.IsStatic) + { + this.locApi = null; + } + + break; + } + + this.locNodes = this.locApi.GetType().GetMethod("LocaliseNodes", new[] { typeof(DNNNodeCollection) }); + if (this.locNodes != null) + { + if (this.locNodes.IsStatic) + { + this.locApi = null; + } + + break; + } + } + + // ReSharper disable EmptyGeneralCatchClause + catch + { + } - public bool HaveApi() - { - if (!haveChecked) - { - var modules = DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId); - foreach (var moduleKeyPair in modules) - { - if (!String.IsNullOrEmpty(moduleKeyPair.Value.BusinessControllerClass)) - { - try - { - locApi = Reflection.CreateObject(moduleKeyPair.Value.BusinessControllerClass, moduleKeyPair.Value.BusinessControllerClass); - locTab = locApi.GetType().GetMethod("LocaliseTab", new[] {typeof(TabInfo), typeof(int)}); - if (locTab != null) - { - if (locTab.IsStatic) - { - locApi = null; - } - break; - } + // ReSharper restore EmptyGeneralCatchClause + } + } - locNodes = locApi.GetType().GetMethod("LocaliseNodes", new[] {typeof(DNNNodeCollection)}); - if (locNodes != null) - { - if (locNodes.IsStatic) - { - locApi = null; - } - break; - } - } -// ReSharper disable EmptyGeneralCatchClause - catch - { - } -// ReSharper restore EmptyGeneralCatchClause - } - } - haveChecked = true; - } + this.haveChecked = true; + } - return (locTab != null) || (locNodes != null); - } + return (this.locTab != null) || (this.locNodes != null); + } - public TabInfo LocaliseTab(TabInfo tab, int portalId) - { - return (locTab == null) ? null : (TabInfo)locTab.Invoke(locApi, new object[] {tab, portalId}); - } + public TabInfo LocaliseTab(TabInfo tab, int portalId) + { + return (this.locTab == null) ? null : (TabInfo)this.locTab.Invoke(this.locApi, new object[] { tab, portalId }); + } - public DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) - { - return (locNodes == null) ? null : (DNNNodeCollection)locNodes.Invoke(locApi, new object[] {nodes}); - } - } + public DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) + { + return (this.locNodes == null) ? null : (DNNNodeCollection)this.locNodes.Invoke(this.locApi, new object[] { nodes }); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/ILocalisation.cs b/DNN Platform/Modules/DDRMenu/Localisation/ILocalisation.cs index b7a2a704bb4..13ab426d685 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/ILocalisation.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/ILocalisation.cs @@ -1,17 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.UI.WebControls; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.Localisation { - public interface ILocalisation - { - bool HaveApi(); - TabInfo LocaliseTab(TabInfo tab, int portalId); - DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes); - } + using System.Collections.Generic; + + using DotNetNuke.Entities.Tabs; + using DotNetNuke.UI.WebControls; + + public interface ILocalisation + { + bool HaveApi(); + + TabInfo LocaliseTab(TabInfo tab, int portalId); + + DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes); + } } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs b/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs index d859a6e0c40..4af7e792a39 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs @@ -1,26 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.UI.WebControls; -using EaloTabInfo = effority.Ealo.Specialized.TabInfo; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.Localisation { - public class Localiser - { - private readonly int portalId; - private static bool apiChecked; - private static ILocalisation _LocalisationApi; - private static ILocalisation LocalisationApi - { - get - { - if (!apiChecked) - { - foreach (var api in new ILocalisation[] { new Generic(), new Ealo(), new Apollo() }) //new Adequation() + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.UI.WebControls; + + using MenuNode = DotNetNuke.Web.DDRMenu.MenuNode; + + public class Localiser + { + private static bool apiChecked; + private static ILocalisation _LocalisationApi; + private readonly int portalId; + + public Localiser(int portalId) + { + this.portalId = portalId; + } + + private static ILocalisation LocalisationApi + { + get + { + if (!apiChecked) + { + foreach (var api in new ILocalisation[] { new Generic(), new Ealo(), new Apollo() }) // new Adequation() { if (api.HaveApi()) { @@ -28,56 +35,53 @@ private static ILocalisation LocalisationApi break; } } - apiChecked = true; - } - return _LocalisationApi; - } - } - public static DNNNodeCollection LocaliseDNNNodeCollection(DNNNodeCollection nodes) - { - return (LocalisationApi == null) ? nodes : (LocalisationApi.LocaliseNodes(nodes) ?? nodes); - } + apiChecked = true; + } - public Localiser(int portalId) - { - this.portalId = portalId; - } + return _LocalisationApi; + } + } - public void LocaliseNode(MenuNode node) - { + public static DNNNodeCollection LocaliseDNNNodeCollection(DNNNodeCollection nodes) + { + return (LocalisationApi == null) ? nodes : (LocalisationApi.LocaliseNodes(nodes) ?? nodes); + } + + public void LocaliseNode(MenuNode node) + { var tab = (node.TabId > 0) ? TabController.Instance.GetTab(node.TabId, Null.NullInteger, false) : null; - if (tab != null) - { - var localised = LocaliseTab(tab); - tab = localised ?? tab; + if (tab != null) + { + var localised = this.LocaliseTab(tab); + tab = localised ?? tab; - if (localised != null) - { - node.TabId = tab.TabID; - node.Text = tab.TabName; - node.Enabled = !tab.DisableLink; - if (!tab.IsVisible) - { - node.TabId = -1; - } - } + if (localised != null) + { + node.TabId = tab.TabID; + node.Text = tab.TabName; + node.Enabled = !tab.DisableLink; + if (!tab.IsVisible) + { + node.TabId = -1; + } + } - node.Title = tab.Title; - node.Description = tab.Description; - node.Keywords = tab.KeyWords; - } - else - { - node.TabId = -1; - } + node.Title = tab.Title; + node.Description = tab.Description; + node.Keywords = tab.KeyWords; + } + else + { + node.TabId = -1; + } - node.Children.ForEach(LocaliseNode); - } + node.Children.ForEach(this.LocaliseNode); + } - private TabInfo LocaliseTab(TabInfo tab) - { - return (LocalisationApi == null) ? null : LocalisationApi.LocaliseTab(tab, portalId); - } - } + private TabInfo LocaliseTab(TabInfo tab) + { + return (LocalisationApi == null) ? null : LocalisationApi.LocaliseTab(tab, this.portalId); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/MenuBase.cs b/DNN Platform/Modules/DDRMenu/MenuBase.cs index a1cb9159177..862921f6a49 100644 --- a/DNN Platform/Modules/DDRMenu/MenuBase.cs +++ b/DNN Platform/Modules/DDRMenu/MenuBase.cs @@ -1,222 +1,255 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Web; -using System.Web.Caching; -using System.Web.Compilation; -using System.Web.UI; -using System.Xml; -using System.Xml.Serialization; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; -using DotNetNuke.UI; -using DotNetNuke.Web.DDRMenu.DNNCommon; -using DotNetNuke.Web.DDRMenu.Localisation; -using DotNetNuke.Web.DDRMenu.TemplateEngine; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - public class MenuBase - { - public static MenuBase Instantiate(string menuStyle) - { - try - { - var templateDef = TemplateDefinition.FromName(menuStyle, "*menudef.xml"); - return new MenuBase {TemplateDef = templateDef}; - } - catch (Exception exc) - { - throw new ApplicationException(String.Format("Couldn't load menu style '{0}': {1}", menuStyle, exc)); - } - } - - private Settings menuSettings; - internal MenuNode RootNode { get; set; } - internal Boolean SkipLocalisation { get; set; } - public TemplateDefinition TemplateDef { get; set; } - - private HttpContext currentContext; - private HttpContext CurrentContext { get { return currentContext ?? (currentContext = HttpContext.Current); } } - - private PortalSettings hostPortalSettings; - internal PortalSettings HostPortalSettings { get { return hostPortalSettings ?? (hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } } - - private readonly Dictionary nodeSelectorAliases = new Dictionary - { - {"rootonly", "*,0,0"}, - {"rootchildren", "+0"}, - {"currentchildren", "."} - }; - - internal void ApplySettings(Settings settings) - { - menuSettings = settings; - } - - internal virtual void PreRender() - { - TemplateDef.AddTemplateArguments(menuSettings.TemplateArguments, true); - TemplateDef.AddClientOptions(menuSettings.ClientOptions, true); - - if (!String.IsNullOrEmpty(menuSettings.NodeXmlPath)) - { - LoadNodeXml(); - } - if (!String.IsNullOrEmpty(menuSettings.NodeSelector)) - { - ApplyNodeSelector(); - } - if (!String.IsNullOrEmpty(menuSettings.IncludeNodes)) - { - FilterNodes(menuSettings.IncludeNodes, false); - } - if (!String.IsNullOrEmpty(menuSettings.ExcludeNodes)) - { - FilterNodes(menuSettings.ExcludeNodes, true); - } - if (String.IsNullOrEmpty(menuSettings.NodeXmlPath) && !SkipLocalisation) - { - new Localiser(HostPortalSettings.PortalId).LocaliseNode(RootNode); - } - if (!String.IsNullOrEmpty(menuSettings.NodeManipulator)) - { - ApplyNodeManipulator(); - } - - if (!menuSettings.IncludeHidden) - { - FilterHiddenNodes(RootNode); - } - - var imagePathOption = - menuSettings.ClientOptions.Find(o => o.Name.Equals("PathImage", StringComparison.InvariantCultureIgnoreCase)); - RootNode.ApplyContext( - imagePathOption == null ? DNNContext.Current.PortalSettings.HomeDirectory : imagePathOption.Value); - - TemplateDef.PreRender(); - } - - internal void Render(HtmlTextWriter htmlWriter) - { - if (Host.DebugMode) - { - htmlWriter.Write("", menuSettings.MenuStyle); - } - - UserInfo user = null; - if (menuSettings.IncludeContext) - { - user = UserController.Instance.GetCurrentUserInfo(); - user.Roles = user.Roles; // Touch roles to populate - } - - TemplateDef.AddClientOptions(new List {new ClientString("MenuStyle", menuSettings.MenuStyle)}, false); - - TemplateDef.Render(new MenuXml {root = RootNode, user = user}, htmlWriter); - } - - private void LoadNodeXml() - { - menuSettings.NodeXmlPath = - MapPath( - new PathResolver(TemplateDef.Folder).Resolve( - menuSettings.NodeXmlPath, - PathResolver.RelativeTo.Manifest, - PathResolver.RelativeTo.Skin, - PathResolver.RelativeTo.Module, - PathResolver.RelativeTo.Portal, - PathResolver.RelativeTo.Dnn)); - - var cache = CurrentContext.Cache; - RootNode = cache[menuSettings.NodeXmlPath] as MenuNode; - if (RootNode != null) - { - return; - } - - using (var reader = XmlReader.Create(menuSettings.NodeXmlPath)) - { - reader.ReadToFollowing("root"); - RootNode = (MenuNode)(new XmlSerializer(typeof(MenuNode), "").Deserialize(reader)); - } - cache.Insert(menuSettings.NodeXmlPath, RootNode, new CacheDependency(menuSettings.NodeXmlPath)); - } - - private void FilterNodes(string nodeString, bool exclude) - { - var nodeTextStrings = SplitAndTrim(nodeString); - var filteredNodes = new List(); + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Web; + using System.Web.Caching; + using System.Web.Compilation; + using System.Web.UI; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + using DotNetNuke.UI; + using DotNetNuke.Web.DDRMenu.DNNCommon; + using DotNetNuke.Web.DDRMenu.Localisation; + using DotNetNuke.Web.DDRMenu.TemplateEngine; + + public class MenuBase + { + private readonly Dictionary nodeSelectorAliases = new Dictionary + { + { "rootonly", "*,0,0" }, + { "rootchildren", "+0" }, + { "currentchildren", "." }, + }; + + private Settings menuSettings; + + private HttpContext currentContext; + + private PortalSettings hostPortalSettings; + + public TemplateDefinition TemplateDef { get; set; } + + internal MenuNode RootNode { get; set; } + + internal bool SkipLocalisation { get; set; } + + public static MenuBase Instantiate(string menuStyle) + { + try + { + var templateDef = TemplateDefinition.FromName(menuStyle, "*menudef.xml"); + return new MenuBase { TemplateDef = templateDef }; + } + catch (Exception exc) + { + throw new ApplicationException(string.Format("Couldn't load menu style '{0}': {1}", menuStyle, exc)); + } + } + + internal PortalSettings HostPortalSettings + { + get { return this.hostPortalSettings ?? (this.hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } + } + + private HttpContext CurrentContext + { + get { return this.currentContext ?? (this.currentContext = HttpContext.Current); } + } + + internal void ApplySettings(Settings settings) + { + this.menuSettings = settings; + } + + internal virtual void PreRender() + { + this.TemplateDef.AddTemplateArguments(this.menuSettings.TemplateArguments, true); + this.TemplateDef.AddClientOptions(this.menuSettings.ClientOptions, true); + + if (!string.IsNullOrEmpty(this.menuSettings.NodeXmlPath)) + { + this.LoadNodeXml(); + } + + if (!string.IsNullOrEmpty(this.menuSettings.NodeSelector)) + { + this.ApplyNodeSelector(); + } + + if (!string.IsNullOrEmpty(this.menuSettings.IncludeNodes)) + { + this.FilterNodes(this.menuSettings.IncludeNodes, false); + } + + if (!string.IsNullOrEmpty(this.menuSettings.ExcludeNodes)) + { + this.FilterNodes(this.menuSettings.ExcludeNodes, true); + } + + if (string.IsNullOrEmpty(this.menuSettings.NodeXmlPath) && !this.SkipLocalisation) + { + new Localiser(this.HostPortalSettings.PortalId).LocaliseNode(this.RootNode); + } + + if (!string.IsNullOrEmpty(this.menuSettings.NodeManipulator)) + { + this.ApplyNodeManipulator(); + } + + if (!this.menuSettings.IncludeHidden) + { + this.FilterHiddenNodes(this.RootNode); + } + + var imagePathOption = + this.menuSettings.ClientOptions.Find(o => o.Name.Equals("PathImage", StringComparison.InvariantCultureIgnoreCase)); + this.RootNode.ApplyContext( + imagePathOption == null ? DNNContext.Current.PortalSettings.HomeDirectory : imagePathOption.Value); + + this.TemplateDef.PreRender(); + } + + internal void Render(HtmlTextWriter htmlWriter) + { + if (Host.DebugMode) + { + htmlWriter.Write("", this.menuSettings.MenuStyle); + } + + UserInfo user = null; + if (this.menuSettings.IncludeContext) + { + user = UserController.Instance.GetCurrentUserInfo(); + user.Roles = user.Roles; // Touch roles to populate + } + + this.TemplateDef.AddClientOptions(new List { new ClientString("MenuStyle", this.menuSettings.MenuStyle) }, false); + + this.TemplateDef.Render(new MenuXml { root = this.RootNode, user = user }, htmlWriter); + } + + protected string MapPath(string path) + { + return string.IsNullOrEmpty(path) ? string.Empty : Path.GetFullPath(this.CurrentContext.Server.MapPath(path)); + } + + private static List SplitAndTrim(string str) + { + return new List(str.Split(',')).ConvertAll(s => s.Trim().ToLowerInvariant()); + } + + private void LoadNodeXml() + { + this.menuSettings.NodeXmlPath = + this.MapPath( + new PathResolver(this.TemplateDef.Folder).Resolve( + this.menuSettings.NodeXmlPath, + PathResolver.RelativeTo.Manifest, + PathResolver.RelativeTo.Skin, + PathResolver.RelativeTo.Module, + PathResolver.RelativeTo.Portal, + PathResolver.RelativeTo.Dnn)); + + var cache = this.CurrentContext.Cache; + this.RootNode = cache[this.menuSettings.NodeXmlPath] as MenuNode; + if (this.RootNode != null) + { + return; + } + + using (var reader = XmlReader.Create(this.menuSettings.NodeXmlPath)) + { + reader.ReadToFollowing("root"); + this.RootNode = (MenuNode)new XmlSerializer(typeof(MenuNode), string.Empty).Deserialize(reader); + } + + cache.Insert(this.menuSettings.NodeXmlPath, this.RootNode, new CacheDependency(this.menuSettings.NodeXmlPath)); + } + + private void FilterNodes(string nodeString, bool exclude) + { + var nodeTextStrings = SplitAndTrim(nodeString); + var filteredNodes = new List(); var tc = new TabController(); - var flattenedNodes = new MenuNode(); - - foreach (var nodeText in nodeTextStrings) - { - if (nodeText.StartsWith("[")) - { - var roleName = nodeText.Substring(1, nodeText.Length - 2); - filteredNodes.AddRange( - RootNode.Children.FindAll( - n => - { + var flattenedNodes = new MenuNode(); + + foreach (var nodeText in nodeTextStrings) + { + if (nodeText.StartsWith("[")) + { + var roleName = nodeText.Substring(1, nodeText.Length - 2); + filteredNodes.AddRange( + this.RootNode.Children.FindAll( + n => + { var tab = TabController.Instance.GetTab(n.TabId, Null.NullInteger, false); - foreach (TabPermissionInfo perm in tab.TabPermissions) - { - if (perm.AllowAccess && (perm.PermissionKey == "VIEW") && - ((perm.RoleID == -1) || (perm.RoleName.ToLowerInvariant() == roleName))) - { - return true; - } - } - return false; - })); - } + foreach (TabPermissionInfo perm in tab.TabPermissions) + { + if (perm.AllowAccess && (perm.PermissionKey == "VIEW") && + ((perm.RoleID == -1) || (perm.RoleName.ToLowerInvariant() == roleName))) + { + return true; + } + } + + return false; + })); + } else if (nodeText.StartsWith("#")) - { + { var tagName = nodeText.Substring(1, nodeText.Length - 1); - if (!string.IsNullOrEmpty(tagName)) - { - //flatten nodes first. tagged pages should be flattened and not heirarchical + if (!string.IsNullOrEmpty(tagName)) + { + // flatten nodes first. tagged pages should be flattened and not heirarchical if (flattenedNodes != new MenuNode()) - flattenedNodes.Children = RootNode.FlattenChildren(RootNode); + { + flattenedNodes.Children = this.RootNode.FlattenChildren(this.RootNode); + } filteredNodes.AddRange( flattenedNodes.Children.FindAll( n => { var tab = tc.GetTab(n.TabId, Null.NullInteger, false); - return (tab.Terms.Any(x => x.Name.ToLowerInvariant() == tagName)); + return tab.Terms.Any(x => x.Name.ToLowerInvariant() == tagName); })); - } - - } - else - { - filteredNodes.Add(RootNode.FindByNameOrId(nodeText)); - } - } + } + } + else + { + filteredNodes.Add(this.RootNode.FindByNameOrId(nodeText)); + } + } // if filtered for foksonomy tags, use flat tree to get all related pages in nodeselection - if (flattenedNodes.HasChildren()) - RootNode = flattenedNodes; + if (flattenedNodes.HasChildren()) + { + this.RootNode = flattenedNodes; + } + if (exclude) { - RootNode.RemoveAll(filteredNodes); + this.RootNode.RemoveAll(filteredNodes); } else { - RootNode.Children.RemoveAll(n => filteredNodes.Contains(n) == exclude); + this.RootNode.Children.RemoveAll(n => filteredNodes.Contains(n) == exclude); } - } + } private void FilterHiddenNodes(MenuNode parentNode) { @@ -225,130 +258,123 @@ private void FilterHiddenNodes(MenuNode parentNode) filteredNodes.AddRange( parentNode.Children.FindAll( n => - { + { var tab = TabController.Instance.GetTab(n.TabId, portalSettings.PortalId); return tab == null || !tab.IsVisible; })); parentNode.Children.RemoveAll(n => filteredNodes.Contains(n)); - parentNode.Children.ForEach(FilterHiddenNodes); + parentNode.Children.ForEach(this.FilterHiddenNodes); } private void ApplyNodeSelector() - { - string selector; - if (!nodeSelectorAliases.TryGetValue(menuSettings.NodeSelector.ToLowerInvariant(), out selector)) - { - selector = menuSettings.NodeSelector; - } - - var selectorSplit = SplitAndTrim(selector); - - var currentTabId = HostPortalSettings.ActiveTab.TabID; - - var newRoot = RootNode; - - var rootSelector = selectorSplit[0]; - if (rootSelector != "*") - { - if (rootSelector.StartsWith("+")) - { - var depth = Convert.ToInt32(rootSelector); - newRoot = RootNode; - for (var i = 0; i <= depth; i++) - { - newRoot = newRoot.Children.Find(n => n.Breadcrumb); - if (newRoot == null) - { - RootNode = new MenuNode(); - return; - } - } - } - else if (rootSelector.StartsWith("-") || rootSelector == "0" || rootSelector == ".") - { - newRoot = RootNode.FindById(currentTabId); - if (newRoot == null) - { - RootNode = new MenuNode(); - return; - } - - if (rootSelector.StartsWith("-")) - { - for (var n = Convert.ToInt32(rootSelector); n < 0; n++) - { - if (newRoot.Parent != null) - { - newRoot = newRoot.Parent; - } - } - } - } - else - { - newRoot = RootNode.FindByNameOrId(rootSelector); - if (newRoot == null) - { - RootNode = new MenuNode(); - return; - } - } - } - -// ReSharper disable PossibleNullReferenceException - RootNode = new MenuNode(newRoot.Children); -// ReSharper restore PossibleNullReferenceException - - if (selectorSplit.Count > 1) - { - for (var n = Convert.ToInt32(selectorSplit[1]); n > 0; n--) - { - var newChildren = new List(); - foreach (var child in RootNode.Children) - { - newChildren.AddRange(child.Children); - } - RootNode = new MenuNode(newChildren); - } - } - - if (selectorSplit.Count > 2) - { - var newChildren = RootNode.Children; - for (var n = Convert.ToInt32(selectorSplit[2]); n > 0; n--) - { - var nextChildren = new List(); - foreach (var child in newChildren) - { - nextChildren.AddRange(child.Children); - } - newChildren = nextChildren; - } - foreach (var node in newChildren) - { - node.Children = null; - } - } - } - - private void ApplyNodeManipulator() - { - RootNode = - new MenuNode( - ((INodeManipulator)Activator.CreateInstance(BuildManager.GetType(menuSettings.NodeManipulator, true, true))). - ManipulateNodes(RootNode.Children, HostPortalSettings)); - } - - protected string MapPath(string path) - { - return String.IsNullOrEmpty(path) ? "" : Path.GetFullPath(CurrentContext.Server.MapPath(path)); - } - - private static List SplitAndTrim(string str) - { - return new List(str.Split(',')).ConvertAll(s => s.Trim().ToLowerInvariant()); - } - } + { + string selector; + if (!this.nodeSelectorAliases.TryGetValue(this.menuSettings.NodeSelector.ToLowerInvariant(), out selector)) + { + selector = this.menuSettings.NodeSelector; + } + + var selectorSplit = SplitAndTrim(selector); + + var currentTabId = this.HostPortalSettings.ActiveTab.TabID; + + var newRoot = this.RootNode; + + var rootSelector = selectorSplit[0]; + if (rootSelector != "*") + { + if (rootSelector.StartsWith("+")) + { + var depth = Convert.ToInt32(rootSelector); + newRoot = this.RootNode; + for (var i = 0; i <= depth; i++) + { + newRoot = newRoot.Children.Find(n => n.Breadcrumb); + if (newRoot == null) + { + this.RootNode = new MenuNode(); + return; + } + } + } + else if (rootSelector.StartsWith("-") || rootSelector == "0" || rootSelector == ".") + { + newRoot = this.RootNode.FindById(currentTabId); + if (newRoot == null) + { + this.RootNode = new MenuNode(); + return; + } + + if (rootSelector.StartsWith("-")) + { + for (var n = Convert.ToInt32(rootSelector); n < 0; n++) + { + if (newRoot.Parent != null) + { + newRoot = newRoot.Parent; + } + } + } + } + else + { + newRoot = this.RootNode.FindByNameOrId(rootSelector); + if (newRoot == null) + { + this.RootNode = new MenuNode(); + return; + } + } + } + + // ReSharper disable PossibleNullReferenceException + this.RootNode = new MenuNode(newRoot.Children); + + // ReSharper restore PossibleNullReferenceException + if (selectorSplit.Count > 1) + { + for (var n = Convert.ToInt32(selectorSplit[1]); n > 0; n--) + { + var newChildren = new List(); + foreach (var child in this.RootNode.Children) + { + newChildren.AddRange(child.Children); + } + + this.RootNode = new MenuNode(newChildren); + } + } + + if (selectorSplit.Count > 2) + { + var newChildren = this.RootNode.Children; + for (var n = Convert.ToInt32(selectorSplit[2]); n > 0; n--) + { + var nextChildren = new List(); + foreach (var child in newChildren) + { + nextChildren.AddRange(child.Children); + } + + newChildren = nextChildren; + } + + foreach (var node in newChildren) + { + node.Children = null; + } + } + } + + private void ApplyNodeManipulator() + { + this.RootNode = + new MenuNode( + ((INodeManipulator)Activator.CreateInstance(BuildManager.GetType(this.menuSettings.NodeManipulator, true, true))). + ManipulateNodes(this.RootNode.Children, this.HostPortalSettings)); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/MenuNode.cs b/DNN Platform/Modules/DDRMenu/MenuNode.cs index 32fa09bb37d..5c0877e25fb 100644 --- a/DNN Platform/Modules/DDRMenu/MenuNode.cs +++ b/DNN Platform/Modules/DDRMenu/MenuNode.cs @@ -1,44 +1,85 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; -using DotNetNuke.Common; -using DotNetNuke.UI.WebControls; -using DotNetNuke.Web.DDRMenu.DNNCommon; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { + using System; + using System.Collections.Generic; + using System.Xml; + using System.Xml.Schema; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.DDRMenu.DNNCommon; + [Serializable] [XmlRoot("root", Namespace = "")] public class MenuNode : IXmlSerializable { + private List _Children; + + public MenuNode() + { + } + + public MenuNode(DNNNodeCollection dnnNodes) + { + this.Children = ConvertDNNNodeCollection(dnnNodes, this); + } + + public MenuNode(List nodes) + { + this.Children = nodes; + this.Children.ForEach(c => c.Parent = this); + } + + public int TabId { get; set; } + + public string Text { get; set; } + + public string Title { get; set; } + public static List ConvertDNNNodeCollection(DNNNodeCollection dnnNodes, MenuNode parent) { var result = new List(); foreach (DNNNode node in dnnNodes) + { result.Add(new MenuNode(node, parent)); + } + return result; } - public int TabId { get; set; } - public string Text { get; set; } - public string Title { get; set; } public string Url { get; set; } + public bool Enabled { get; set; } + public bool Selected { get; set; } + public bool Breadcrumb { get; set; } + public bool Separator { get; set; } + public string Icon { get; set; } + public string LargeImage { get; set; } + public string CommandName { get; set; } + public string CommandArgument { get; set; } - public bool First { get { return (Parent == null) || (Parent.Children[0] == this); } } - public bool Last { get { return (Parent == null) || (Parent.Children[Parent.Children.Count - 1] == this); } } + + public bool First + { + get { return (this.Parent == null) || (this.Parent.Children[0] == this); } + } + + public bool Last + { + get { return (this.Parent == null) || (this.Parent.Children[this.Parent.Children.Count - 1] == this); } + } + public string Target { get; set; } public int Depth @@ -52,69 +93,65 @@ public int Depth result++; current = current.Parent; } + return result; } } public string Keywords { get; set; } - public string Description { get; set; } - - private List _Children; - public List Children { get { return _Children ?? (_Children = new List()); } set { _Children = value; } } - public MenuNode Parent { get; set; } - - public MenuNode() - { - } + public string Description { get; set; } - public MenuNode(DNNNodeCollection dnnNodes) + public List Children { - Children = ConvertDNNNodeCollection(dnnNodes, this); + get { return this._Children ?? (this._Children = new List()); } + set { this._Children = value; } } - public MenuNode(List nodes) - { - Children = nodes; - Children.ForEach(c => c.Parent = this); - } + public MenuNode Parent { get; set; } public MenuNode(DNNNode dnnNode, MenuNode parent) { - TabId = Convert.ToInt32(dnnNode.ID); - Text = dnnNode.Text; - Url = (dnnNode.ClickAction == eClickAction.PostBack) + this.TabId = Convert.ToInt32(dnnNode.ID); + this.Text = dnnNode.Text; + this.Url = (dnnNode.ClickAction == eClickAction.PostBack) ? "postback:" + dnnNode.ID - : String.IsNullOrEmpty(dnnNode.JSFunction) ? dnnNode.NavigateURL : "javascript:" + dnnNode.JSFunction; - Enabled = dnnNode.Enabled; - Selected = dnnNode.Selected; - Breadcrumb = dnnNode.BreadCrumb; - Separator = dnnNode.IsBreak; - Icon = dnnNode.Image; - Target = dnnNode.Target; - Title = null; - Keywords = null; - Description = null; - Parent = parent; - CommandName = dnnNode.get_CustomAttribute("CommandName"); - CommandArgument = dnnNode.get_CustomAttribute("CommandArgument"); + : string.IsNullOrEmpty(dnnNode.JSFunction) ? dnnNode.NavigateURL : "javascript:" + dnnNode.JSFunction; + this.Enabled = dnnNode.Enabled; + this.Selected = dnnNode.Selected; + this.Breadcrumb = dnnNode.BreadCrumb; + this.Separator = dnnNode.IsBreak; + this.Icon = dnnNode.Image; + this.Target = dnnNode.Target; + this.Title = null; + this.Keywords = null; + this.Description = null; + this.Parent = parent; + this.CommandName = dnnNode.get_CustomAttribute("CommandName"); + this.CommandArgument = dnnNode.get_CustomAttribute("CommandArgument"); DNNAbstract.DNNNodeToMenuNode(dnnNode, this); if ((dnnNode.DNNNodes != null) && (dnnNode.DNNNodes.Count > 0)) - Children = ConvertDNNNodeCollection(dnnNode.DNNNodes, this); + { + this.Children = ConvertDNNNodeCollection(dnnNode.DNNNodes, this); + } } public MenuNode FindById(int tabId) { - if (tabId == TabId) + if (tabId == this.TabId) + { return this; + } - foreach (var child in Children) + foreach (var child in this.Children) { var result = child.FindById(tabId); if (result != null) + { return result; + } } return null; @@ -122,14 +159,18 @@ public MenuNode FindById(int tabId) public MenuNode FindByName(string tabName) { - if (tabName.Equals(Text, StringComparison.InvariantCultureIgnoreCase)) + if (tabName.Equals(this.Text, StringComparison.InvariantCultureIgnoreCase)) + { return this; + } - foreach (var child in Children) + foreach (var child in this.Children) { var result = child.FindByName(tabName); if (result != null) + { return result; + } } return null; @@ -137,7 +178,6 @@ public MenuNode FindByName(string tabName) public List FlattenChildren(MenuNode root) { - var flattened = new List(); if (root.TabId != 0) { @@ -150,7 +190,7 @@ public List FlattenChildren(MenuNode root) { foreach (var child in children) { - flattened.AddRange(FlattenChildren(child)); + flattened.AddRange(this.FlattenChildren(child)); } } @@ -159,60 +199,31 @@ public List FlattenChildren(MenuNode root) public MenuNode FindByNameOrId(string tabNameOrId) { - if (tabNameOrId.Equals(Text, StringComparison.InvariantCultureIgnoreCase)) + if (tabNameOrId.Equals(this.Text, StringComparison.InvariantCultureIgnoreCase)) + { return this; - if (tabNameOrId == TabId.ToString()) + } + + if (tabNameOrId == this.TabId.ToString()) + { return this; + } - foreach (var child in Children) + foreach (var child in this.Children) { var result = child.FindByNameOrId(tabNameOrId); if (result != null) + { return result; + } } return null; } - internal void RemoveAll(List filteredNodes) - { - this.Children.RemoveAll(filteredNodes.Contains); - foreach (var child in Children) - { - child.RemoveAll(filteredNodes); - } - } - public bool HasChildren() { - return (Children.Count > 0); - } - - internal void ApplyContext(string defaultImagePath) - { - Icon = ApplyContextToImagePath(Icon, defaultImagePath); - LargeImage = ApplyContextToImagePath(LargeImage, defaultImagePath); - - if (Url != null && Url.StartsWith("postback:")) - { - var postbackControl = DNNContext.Current.HostControl; - Url = postbackControl.Page.ClientScript.GetPostBackClientHyperlink(postbackControl, Url.Substring(9)); - } - - Children.ForEach(c => c.ApplyContext(defaultImagePath)); - } - - private string ApplyContextToImagePath(string imagePath, string defaultImagePath) - { - var result = imagePath; - if (!String.IsNullOrEmpty(result)) - { - if (result.StartsWith("~", StringComparison.InvariantCultureIgnoreCase)) - result = Globals.ResolveUrl(result); - else if (!(result.Contains("://") || result.StartsWith("/"))) - result = defaultImagePath + result; - } - return result; + return this.Children.Count > 0; } public XmlSchema GetSchema() @@ -231,53 +242,56 @@ public void ReadXml(XmlReader reader) switch (reader.Name.ToLowerInvariant()) { case "id": - TabId = Convert.ToInt32(reader.Value); + this.TabId = Convert.ToInt32(reader.Value); break; case "text": - Text = reader.Value; + this.Text = reader.Value; break; case "title": - Title = reader.Value; + this.Title = reader.Value; break; case "url": - Url = reader.Value; + this.Url = reader.Value; break; case "enabled": - Enabled = (reader.Value == "1"); + this.Enabled = reader.Value == "1"; break; case "selected": - Selected = (reader.Value == "1"); + this.Selected = reader.Value == "1"; break; case "breadcrumb": - Breadcrumb = (reader.Value == "1"); + this.Breadcrumb = reader.Value == "1"; break; case "separator": - Separator = (reader.Value == "1"); + this.Separator = reader.Value == "1"; break; case "icon": - Icon = reader.Value; + this.Icon = reader.Value; break; case "largeimage": - LargeImage = reader.Value; + this.LargeImage = reader.Value; break; case "commandname": - CommandName = reader.Value; + this.CommandName = reader.Value; break; case "commandargument": - CommandArgument = reader.Value; + this.CommandArgument = reader.Value; break; case "target": - Target = reader.Value; + this.Target = reader.Value; break; - //default: - // throw new XmlException(String.Format("Unexpected attribute '{0}'", reader.Name)); + + // default: + // throw new XmlException(String.Format("Unexpected attribute '{0}'", reader.Name)); } } while (reader.MoveToNextAttribute()); } if (empty) + { return; + } while (reader.Read()) { @@ -289,19 +303,20 @@ public void ReadXml(XmlReader reader) case "node": var child = new MenuNode { Parent = this }; child.ReadXml(reader); - Children.Add(child); + this.Children.Add(child); break; case "keywords": - Keywords = reader.ReadElementContentAsString().Trim(); + this.Keywords = reader.ReadElementContentAsString().Trim(); break; case "description": - Description = reader.ReadElementContentAsString().Trim(); + this.Description = reader.ReadElementContentAsString().Trim(); break; case "root": break; default: - throw new XmlException(String.Format("Unexpected element '{0}'", reader.Name)); + throw new XmlException(string.Format("Unexpected element '{0}'", reader.Name)); } + break; case XmlNodeType.EndElement: reader.ReadEndElement(); @@ -310,43 +325,88 @@ public void ReadXml(XmlReader reader) } } + internal void RemoveAll(List filteredNodes) + { + this.Children.RemoveAll(filteredNodes.Contains); + foreach (var child in this.Children) + { + child.RemoveAll(filteredNodes); + } + } + + internal void ApplyContext(string defaultImagePath) + { + this.Icon = this.ApplyContextToImagePath(this.Icon, defaultImagePath); + this.LargeImage = this.ApplyContextToImagePath(this.LargeImage, defaultImagePath); + + if (this.Url != null && this.Url.StartsWith("postback:")) + { + var postbackControl = DNNContext.Current.HostControl; + this.Url = postbackControl.Page.ClientScript.GetPostBackClientHyperlink(postbackControl, this.Url.Substring(9)); + } + + this.Children.ForEach(c => c.ApplyContext(defaultImagePath)); + } + + private string ApplyContextToImagePath(string imagePath, string defaultImagePath) + { + var result = imagePath; + if (!string.IsNullOrEmpty(result)) + { + if (result.StartsWith("~", StringComparison.InvariantCultureIgnoreCase)) + { + result = Globals.ResolveUrl(result); + } + else if (!(result.Contains("://") || result.StartsWith("/"))) + { + result = defaultImagePath + result; + } + } + + return result; + } + public void WriteXml(XmlWriter writer) { - if (Parent != null) + if (this.Parent != null) { writer.WriteStartElement("node"); - AddXmlAttribute(writer, "id", TabId); - AddXmlAttribute(writer, "text", Text); - AddXmlAttribute(writer, "title", Title); - AddXmlAttribute(writer, "url", Url); - AddXmlAttribute(writer, "enabled", Enabled); - AddXmlAttribute(writer, "selected", Selected); - AddXmlAttribute(writer, "breadcrumb", Breadcrumb); - AddXmlAttribute(writer, "separator", Separator); - AddXmlAttribute(writer, "target", Target); - AddXmlAttribute(writer, "icon", Icon); - AddXmlAttribute(writer, "largeimage", LargeImage); - AddXmlAttribute(writer, "commandname", CommandName); - AddXmlAttribute(writer, "commandargument", CommandArgument); - AddXmlAttribute(writer, "first", First); - AddXmlAttribute(writer, "last", Last); - AddXmlAttribute(writer, "only", First && Last); - AddXmlAttribute(writer, "depth", Depth); - AddXmlElement(writer, "keywords", Keywords); - AddXmlElement(writer, "description", Description); + AddXmlAttribute(writer, "id", this.TabId); + AddXmlAttribute(writer, "text", this.Text); + AddXmlAttribute(writer, "title", this.Title); + AddXmlAttribute(writer, "url", this.Url); + AddXmlAttribute(writer, "enabled", this.Enabled); + AddXmlAttribute(writer, "selected", this.Selected); + AddXmlAttribute(writer, "breadcrumb", this.Breadcrumb); + AddXmlAttribute(writer, "separator", this.Separator); + AddXmlAttribute(writer, "target", this.Target); + AddXmlAttribute(writer, "icon", this.Icon); + AddXmlAttribute(writer, "largeimage", this.LargeImage); + AddXmlAttribute(writer, "commandname", this.CommandName); + AddXmlAttribute(writer, "commandargument", this.CommandArgument); + AddXmlAttribute(writer, "first", this.First); + AddXmlAttribute(writer, "last", this.Last); + AddXmlAttribute(writer, "only", this.First && this.Last); + AddXmlAttribute(writer, "depth", this.Depth); + AddXmlElement(writer, "keywords", this.Keywords); + AddXmlElement(writer, "description", this.Description); } - Children.ForEach(c => c.WriteXml(writer)); + this.Children.ForEach(c => c.WriteXml(writer)); - if (Parent != null) + if (this.Parent != null) + { writer.WriteEndElement(); + } } private static void AddXmlAttribute(XmlWriter writer, string name, string value) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) + { writer.WriteAttributeString(name, value); + } } private static void AddXmlAttribute(XmlWriter writer, string name, int value) @@ -361,8 +421,10 @@ private static void AddXmlAttribute(XmlWriter writer, string name, bool value) private static void AddXmlElement(XmlWriter writer, string name, string value) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) + { writer.WriteElementString(name, value); + } } } } diff --git a/DNN Platform/Modules/DDRMenu/MenuSettings.ascx.cs b/DNN Platform/Modules/DDRMenu/MenuSettings.ascx.cs index cebb3cb168f..95f4c095405 100644 --- a/DNN Platform/Modules/DDRMenu/MenuSettings.ascx.cs +++ b/DNN Platform/Modules/DDRMenu/MenuSettings.ascx.cs @@ -1,50 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Modules; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - partial class MenuSettings : ModuleSettingsBase - { - public override void LoadSettings() - { - if (IsPostBack) - { - return; - } - MenuStyle.Value = Settings["MenuStyle"] ?? ""; - NodeXmlPath.Value = Settings["NodeXmlPath"] ?? ""; - NodeSelector.Value = Settings["NodeSelector"] ?? ""; - IncludeNodes.Value = Settings["IncludeNodes"] ?? ""; - ExcludeNodes.Value = Settings["ExcludeNodes"] ?? ""; - NodeManipulator.Value = Settings["NodeManipulator"] ?? ""; - IncludeContext.Value = Convert.ToBoolean(Settings["IncludeContext"] ?? "false"); - IncludeHidden.Value = Convert.ToBoolean(Settings["IncludeHidden"] ?? "false"); - TemplateArguments.Value = Settings["TemplateArguments"] ?? ""; - ClientOptions.Value = Settings["ClientOptions"] ?? ""; - } + using System; - public override void UpdateSettings() - { + using DotNetNuke.Entities.Modules; - ModuleController.Instance.UpdateModuleSetting(ModuleId, "MenuStyle", (MenuStyle.Value ?? "").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "NodeXmlPath", (NodeXmlPath.Value ?? "").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "NodeSelector", (NodeSelector.Value ?? "").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "IncludeNodes", (IncludeNodes.Value ?? "").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ExcludeNodes", (ExcludeNodes.Value ?? "").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "NodeManipulator", (NodeManipulator.Value ?? "").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "IncludeContext", (IncludeContext.Value ?? "false").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "IncludeHidden", (IncludeHidden.Value ?? "false").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "TemplateArguments", (TemplateArguments.Value ?? "").ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ClientOptions", (ClientOptions.Value ?? "").ToString()); - } + public partial class MenuSettings : ModuleSettingsBase + { + public override void LoadSettings() + { + if (this.IsPostBack) + { + return; + } - protected override void OnPreRender(EventArgs e) - { - IncludeHiddenSection.Visible = DNNAbstract.IncludeHiddenSupported(); - } - } + this.MenuStyle.Value = this.Settings["MenuStyle"] ?? string.Empty; + this.NodeXmlPath.Value = this.Settings["NodeXmlPath"] ?? string.Empty; + this.NodeSelector.Value = this.Settings["NodeSelector"] ?? string.Empty; + this.IncludeNodes.Value = this.Settings["IncludeNodes"] ?? string.Empty; + this.ExcludeNodes.Value = this.Settings["ExcludeNodes"] ?? string.Empty; + this.NodeManipulator.Value = this.Settings["NodeManipulator"] ?? string.Empty; + this.IncludeContext.Value = Convert.ToBoolean(this.Settings["IncludeContext"] ?? "false"); + this.IncludeHidden.Value = Convert.ToBoolean(this.Settings["IncludeHidden"] ?? "false"); + this.TemplateArguments.Value = this.Settings["TemplateArguments"] ?? string.Empty; + this.ClientOptions.Value = this.Settings["ClientOptions"] ?? string.Empty; + } + + public override void UpdateSettings() + { + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "MenuStyle", (this.MenuStyle.Value ?? string.Empty).ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "NodeXmlPath", (this.NodeXmlPath.Value ?? string.Empty).ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "NodeSelector", (this.NodeSelector.Value ?? string.Empty).ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "IncludeNodes", (this.IncludeNodes.Value ?? string.Empty).ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ExcludeNodes", (this.ExcludeNodes.Value ?? string.Empty).ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "NodeManipulator", (this.NodeManipulator.Value ?? string.Empty).ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "IncludeContext", (this.IncludeContext.Value ?? "false").ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "IncludeHidden", (this.IncludeHidden.Value ?? "false").ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "TemplateArguments", (this.TemplateArguments.Value ?? string.Empty).ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ClientOptions", (this.ClientOptions.Value ?? string.Empty).ToString()); + } + + protected override void OnPreRender(EventArgs e) + { + this.IncludeHiddenSection.Visible = DNNAbstract.IncludeHiddenSupported(); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs b/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs index 3e8cfe5afc5..07e38064420 100644 --- a/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs +++ b/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs @@ -1,99 +1,100 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Web.DDRMenu.Localisation; -using DotNetNuke.Web.DDRMenu.DNNCommon; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - partial class MenuView : ModuleBase - { - private MenuBase menu; + using System; + using System.Web.UI; - protected override void OnPreRender(EventArgs e) - { - using (new DNNContext(this)) - { - try - { - base.OnPreRender(e); + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI; + using DotNetNuke.Web.DDRMenu.DNNCommon; + using DotNetNuke.Web.DDRMenu.Localisation; - var menuStyle = GetStringSetting("MenuStyle"); - if (String.IsNullOrEmpty(menuStyle)) - { - menu = null; - return; - } + public partial class MenuView : ModuleBase + { + private MenuBase menu; - var menuSettings = new Settings - { - MenuStyle = GetStringSetting("MenuStyle"), - NodeXmlPath = GetStringSetting("NodeXmlPath"), - NodeSelector = GetStringSetting("NodeSelector"), - IncludeContext = GetBoolSetting("IncludeContext"), - IncludeHidden = GetBoolSetting("IncludeHidden"), - IncludeNodes = GetStringSetting("IncludeNodes"), - ExcludeNodes = GetStringSetting("ExcludeNodes"), - NodeManipulator = GetStringSetting("NodeManipulator"), - TemplateArguments = - DDRMenu.Settings.TemplateArgumentsFromSettingString(GetStringSetting("TemplateArguments")), - ClientOptions = - DDRMenu.Settings.ClientOptionsFromSettingString(GetStringSetting("ClientOptions")) - }; + protected override void OnPreRender(EventArgs e) + { + using (new DNNContext(this)) + { + try + { + base.OnPreRender(e); - MenuNode rootNode = null; - if (String.IsNullOrEmpty(menuSettings.NodeXmlPath)) - { - rootNode = - new MenuNode( - Localiser.LocaliseDNNNodeCollection( - Navigation.GetNavigationNodes( - ClientID, - Navigation.ToolTipSource.None, - -1, - -1, - DNNAbstract.GetNavNodeOptions(true)))); - } + var menuStyle = this.GetStringSetting("MenuStyle"); + if (string.IsNullOrEmpty(menuStyle)) + { + this.menu = null; + return; + } - menu = MenuBase.Instantiate(menuStyle); - menu.RootNode = rootNode; - menu.ApplySettings(menuSettings); + var menuSettings = new Settings + { + MenuStyle = this.GetStringSetting("MenuStyle"), + NodeXmlPath = this.GetStringSetting("NodeXmlPath"), + NodeSelector = this.GetStringSetting("NodeSelector"), + IncludeContext = this.GetBoolSetting("IncludeContext"), + IncludeHidden = this.GetBoolSetting("IncludeHidden"), + IncludeNodes = this.GetStringSetting("IncludeNodes"), + ExcludeNodes = this.GetStringSetting("ExcludeNodes"), + NodeManipulator = this.GetStringSetting("NodeManipulator"), + TemplateArguments = + DDRMenu.Settings.TemplateArgumentsFromSettingString(this.GetStringSetting("TemplateArguments")), + ClientOptions = + DDRMenu.Settings.ClientOptionsFromSettingString(this.GetStringSetting("ClientOptions")), + }; - menu.PreRender(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } + MenuNode rootNode = null; + if (string.IsNullOrEmpty(menuSettings.NodeXmlPath)) + { + rootNode = + new MenuNode( + Localiser.LocaliseDNNNodeCollection( + Navigation.GetNavigationNodes( + this.ClientID, + Navigation.ToolTipSource.None, + -1, + -1, + DNNAbstract.GetNavNodeOptions(true)))); + } - protected override void Render(HtmlTextWriter htmlWriter) - { - using (new DNNContext(this)) - { - try - { - base.Render(htmlWriter); - if (menu == null) - { - htmlWriter.WriteEncodedText("Please specify menu style in settings."); - } - else - { - menu.Render(htmlWriter); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } - } + this.menu = MenuBase.Instantiate(menuStyle); + this.menu.RootNode = rootNode; + this.menu.ApplySettings(menuSettings); + + this.menu.PreRender(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + + protected override void Render(HtmlTextWriter htmlWriter) + { + using (new DNNContext(this)) + { + try + { + base.Render(htmlWriter); + if (this.menu == null) + { + htmlWriter.WriteEncodedText("Please specify menu style in settings."); + } + else + { + this.menu.Render(htmlWriter); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + } } diff --git a/DNN Platform/Modules/DDRMenu/MenuXml.cs b/DNN Platform/Modules/DDRMenu/MenuXml.cs index e4f574a4200..8062e44a08b 100644 --- a/DNN Platform/Modules/DDRMenu/MenuXml.cs +++ b/DNN Platform/Modules/DDRMenu/MenuXml.cs @@ -1,20 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Xml.Serialization; -using DotNetNuke.Entities.Users; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - [Serializable] - [XmlRoot("xmlroot", Namespace = "")] - public class MenuXml - { -// ReSharper disable InconsistentNaming - public MenuNode root { get; set; } - public UserInfo user { get; set; } -// ReSharper restore InconsistentNaming - } + using System; + using System.Xml.Serialization; + + using DotNetNuke.Entities.Users; + + [Serializable] + [XmlRoot("xmlroot", Namespace = "")] + public class MenuXml + { + // ReSharper disable InconsistentNaming + public MenuNode root { get; set; } + + public UserInfo user { get; set; } + + // ReSharper restore InconsistentNaming + } } diff --git a/DNN Platform/Modules/DDRMenu/ModuleBase.cs b/DNN Platform/Modules/DDRMenu/ModuleBase.cs index 624d02d32a4..6c94afc115a 100644 --- a/DNN Platform/Modules/DDRMenu/ModuleBase.cs +++ b/DNN Platform/Modules/DDRMenu/ModuleBase.cs @@ -1,62 +1,65 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Modules; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - public class ModuleBase : PortalModuleBase - { - protected String GetStringSetting(String name, String defaultValue) - { - var result = Request.QueryString[name]; - if (String.IsNullOrEmpty(result)) - { - result = (String)Settings[name]; - } - if (String.IsNullOrEmpty(result)) - { - result = defaultValue; - } - - if (result != null) - { - result = result.Trim(); - } - if (result == "-") - { - result = ""; - } - - return result; - } - - protected String GetStringSetting(String name) - { - return GetStringSetting(name, ""); - } - - protected Int32 GetIntSetting(String name, Int32 defaultValue) - { - return Convert.ToInt32(GetStringSetting(name, defaultValue.ToString())); - } - - protected Int32 GetIntSetting(String name) - { - return GetIntSetting(name, 0); - } - - protected Boolean GetBoolSetting(String name, Boolean defaultValue) - { - var result = GetStringSetting(name); - return (result == "") ? defaultValue : Convert.ToBoolean(result); - } - - protected Boolean GetBoolSetting(String name) - { - return GetBoolSetting(name, false); - } - } + using System; + + using DotNetNuke.Entities.Modules; + + public class ModuleBase : PortalModuleBase + { + protected string GetStringSetting(string name, string defaultValue) + { + var result = this.Request.QueryString[name]; + if (string.IsNullOrEmpty(result)) + { + result = (string)this.Settings[name]; + } + + if (string.IsNullOrEmpty(result)) + { + result = defaultValue; + } + + if (result != null) + { + result = result.Trim(); + } + + if (result == "-") + { + result = string.Empty; + } + + return result; + } + + protected string GetStringSetting(string name) + { + return this.GetStringSetting(name, string.Empty); + } + + protected int GetIntSetting(string name, int defaultValue) + { + return Convert.ToInt32(this.GetStringSetting(name, defaultValue.ToString())); + } + + protected int GetIntSetting(string name) + { + return this.GetIntSetting(name, 0); + } + + protected bool GetBoolSetting(string name, bool defaultValue) + { + var result = this.GetStringSetting(name); + return (result == string.Empty) ? defaultValue : Convert.ToBoolean(result); + } + + protected bool GetBoolSetting(string name) + { + return this.GetBoolSetting(name, false); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/Properties/AssemblyInfo.cs b/DNN Platform/Modules/DDRMenu/Properties/AssemblyInfo.cs index 1af1204323e..291441a4a81 100644 --- a/DNN Platform/Modules/DDRMenu/Properties/AssemblyInfo.cs +++ b/DNN Platform/Modules/DDRMenu/Properties/AssemblyInfo.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Modules.DDRMenu")] diff --git a/DNN Platform/Modules/DDRMenu/Settings.cs b/DNN Platform/Modules/DDRMenu/Settings.cs index 9d10383f1d0..9c91c538144 100644 --- a/DNN Platform/Modules/DDRMenu/Settings.cs +++ b/DNN Platform/Modules/DDRMenu/Settings.cs @@ -1,104 +1,129 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Xml.Serialization; -using DotNetNuke.Web.DDRMenu.TemplateEngine; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - public class Settings - { - public string MenuStyle { get; set; } - public string NodeXmlPath { get; set; } - public string NodeSelector { get; set; } - public string IncludeNodes { get; set; } - public string ExcludeNodes { get; set; } - public string NodeManipulator { get; set; } - public bool IncludeContext { get; set; } - public bool IncludeHidden { get; set; } - - private List clientOptions; - public List ClientOptions { get { return clientOptions ?? (clientOptions = new List()); } set { clientOptions = value; } } - - private List templateArguments; - public List TemplateArguments { get { return templateArguments ?? (templateArguments = new List()); } set { templateArguments = value; } } - - public static Settings FromXml(string xml) - { - var ser = new XmlSerializer(typeof(Settings)); - using (var reader = new StringReader(xml)) - return (Settings)ser.Deserialize(reader); - } - - public string ToXml() - { - var sb = new StringBuilder(); - var ser = new XmlSerializer(typeof(Settings)); - using (var writer = new StringWriter(sb)) - ser.Serialize(writer, this); - return sb.ToString(); - } - - public override string ToString() - { - try - { - return ToXml(); - } - catch (Exception exc) - { - return exc.ToString(); - } - } - - public static List ClientOptionsFromSettingString(string s) - { - var result = new List(); - if (!string.IsNullOrEmpty(s)) - { - foreach (var clientOption in SplitIntoStrings(s)) - { - var n = clientOption.IndexOf('='); - result.Add(new ClientOption(clientOption.Substring(0, n), clientOption.Substring(n + 1))); - } - } - return result; - } - - public static List TemplateArgumentsFromSettingString(string s) - { - var result = new List(); - if (!string.IsNullOrEmpty(s)) - { - foreach (var templateArgument in SplitIntoStrings(s)) - { - var n = templateArgument.IndexOf('='); - result.Add(new TemplateArgument(templateArgument.Substring(0, n), templateArgument.Substring(n + 1))); - } - } - return result; - } - - public static string ToSettingString(List clientOptions) - { - return String.Join("\r\n", clientOptions.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); - } - - public static string ToSettingString(List templateArguments) - { - return String.Join("\r\n", templateArguments.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); - } - - private static IEnumerable SplitIntoStrings(string fullString) - { - var strings = new List(fullString.Split('\r', '\n')); - strings.RemoveAll(String.IsNullOrEmpty); - return strings; - } - } + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Xml.Serialization; + + using DotNetNuke.Web.DDRMenu.TemplateEngine; + + public class Settings + { + private List clientOptions; + + private List templateArguments; + + public string MenuStyle { get; set; } + + public string NodeXmlPath { get; set; } + + public string NodeSelector { get; set; } + + public string IncludeNodes { get; set; } + + public string ExcludeNodes { get; set; } + + public string NodeManipulator { get; set; } + + public bool IncludeContext { get; set; } + + public bool IncludeHidden { get; set; } + + public List ClientOptions + { + get { return this.clientOptions ?? (this.clientOptions = new List()); } + set { this.clientOptions = value; } + } + + public List TemplateArguments + { + get { return this.templateArguments ?? (this.templateArguments = new List()); } + set { this.templateArguments = value; } + } + + public static Settings FromXml(string xml) + { + var ser = new XmlSerializer(typeof(Settings)); + using (var reader = new StringReader(xml)) + { + return (Settings)ser.Deserialize(reader); + } + } + + public static List ClientOptionsFromSettingString(string s) + { + var result = new List(); + if (!string.IsNullOrEmpty(s)) + { + foreach (var clientOption in SplitIntoStrings(s)) + { + var n = clientOption.IndexOf('='); + result.Add(new ClientOption(clientOption.Substring(0, n), clientOption.Substring(n + 1))); + } + } + + return result; + } + + public static List TemplateArgumentsFromSettingString(string s) + { + var result = new List(); + if (!string.IsNullOrEmpty(s)) + { + foreach (var templateArgument in SplitIntoStrings(s)) + { + var n = templateArgument.IndexOf('='); + result.Add(new TemplateArgument(templateArgument.Substring(0, n), templateArgument.Substring(n + 1))); + } + } + + return result; + } + + public string ToXml() + { + var sb = new StringBuilder(); + var ser = new XmlSerializer(typeof(Settings)); + using (var writer = new StringWriter(sb)) + { + ser.Serialize(writer, this); + } + + return sb.ToString(); + } + + public override string ToString() + { + try + { + return this.ToXml(); + } + catch (Exception exc) + { + return exc.ToString(); + } + } + + public static string ToSettingString(List clientOptions) + { + return string.Join("\r\n", clientOptions.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); + } + + public static string ToSettingString(List templateArguments) + { + return string.Join("\r\n", templateArguments.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); + } + + private static IEnumerable SplitIntoStrings(string fullString) + { + var strings = new List(fullString.Split('\r', '\n')); + strings.RemoveAll(string.IsNullOrEmpty); + return strings; + } + } } diff --git a/DNN Platform/Modules/DDRMenu/SkinObject.cs b/DNN Platform/Modules/DDRMenu/SkinObject.cs index f4424531480..7792d4584ab 100644 --- a/DNN Platform/Modules/DDRMenu/SkinObject.cs +++ b/DNN Platform/Modules/DDRMenu/SkinObject.cs @@ -1,101 +1,109 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Web.UI; -using DotNetNuke.Web.DDRMenu.Localisation; -using DotNetNuke.Web.DDRMenu.DNNCommon; -using DotNetNuke.Web.DDRMenu.TemplateEngine; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI; -using DotNetNuke.UI.Skins; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu { - public class SkinObject : SkinObjectBase - { - public string MenuStyle { get; set; } - public string NodeXmlPath { get; set; } - public string NodeSelector { get; set; } - public bool IncludeContext { get; set; } - public bool IncludeHidden { get; set; } - public string IncludeNodes { get; set; } - public string ExcludeNodes { get; set; } - public string NodeManipulator { get; set; } - - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - public List ClientOptions { get; set; } - - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - public List TemplateArguments { get; set; } - - private MenuBase menu; - - protected override void OnPreRender(EventArgs e) - { - using (new DNNContext(this)) - { - try - { - base.OnPreRender(e); - - menu = MenuBase.Instantiate(MenuStyle); - menu.ApplySettings( - new Settings - { - MenuStyle = MenuStyle, - NodeXmlPath = NodeXmlPath, - NodeSelector = NodeSelector, - IncludeContext = IncludeContext, - IncludeHidden = IncludeHidden, - IncludeNodes = IncludeNodes, - ExcludeNodes = ExcludeNodes, - NodeManipulator = NodeManipulator, - ClientOptions = ClientOptions, - TemplateArguments = TemplateArguments - }); - - if (String.IsNullOrEmpty(NodeXmlPath)) - { - menu.RootNode = - new MenuNode( - Localiser.LocaliseDNNNodeCollection( - Navigation.GetNavigationNodes( - ClientID, - Navigation.ToolTipSource.None, - -1, - -1, - DNNAbstract.GetNavNodeOptions(true)))); - } - - menu.PreRender(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } - - protected override void Render(HtmlTextWriter writer) - { - using (new DNNContext(this)) - { - try - { - base.Render(writer); - menu.Render(writer); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } - } + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Web.UI; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI; + using DotNetNuke.UI.Skins; + using DotNetNuke.Web.DDRMenu.DNNCommon; + using DotNetNuke.Web.DDRMenu.Localisation; + using DotNetNuke.Web.DDRMenu.TemplateEngine; + + public class SkinObject : SkinObjectBase + { + private MenuBase menu; + + public string MenuStyle { get; set; } + + public string NodeXmlPath { get; set; } + + public string NodeSelector { get; set; } + + public bool IncludeContext { get; set; } + + public bool IncludeHidden { get; set; } + + public string IncludeNodes { get; set; } + + public string ExcludeNodes { get; set; } + + public string NodeManipulator { get; set; } + + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + public List ClientOptions { get; set; } + + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + public List TemplateArguments { get; set; } + + protected override void OnPreRender(EventArgs e) + { + using (new DNNContext(this)) + { + try + { + base.OnPreRender(e); + + this.menu = MenuBase.Instantiate(this.MenuStyle); + this.menu.ApplySettings( + new Settings + { + MenuStyle = this.MenuStyle, + NodeXmlPath = this.NodeXmlPath, + NodeSelector = this.NodeSelector, + IncludeContext = this.IncludeContext, + IncludeHidden = this.IncludeHidden, + IncludeNodes = this.IncludeNodes, + ExcludeNodes = this.ExcludeNodes, + NodeManipulator = this.NodeManipulator, + ClientOptions = this.ClientOptions, + TemplateArguments = this.TemplateArguments, + }); + + if (string.IsNullOrEmpty(this.NodeXmlPath)) + { + this.menu.RootNode = + new MenuNode( + Localiser.LocaliseDNNNodeCollection( + Navigation.GetNavigationNodes( + this.ClientID, + Navigation.ToolTipSource.None, + -1, + -1, + DNNAbstract.GetNavNodeOptions(true)))); + } + + this.menu.PreRender(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + + protected override void Render(HtmlTextWriter writer) + { + using (new DNNContext(this)) + { + try + { + base.Render(writer); + this.menu.Render(writer); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } + } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs index f1936d3c933..639fce94018 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs @@ -1,28 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Xml.Serialization; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.TemplateEngine { + using System.Xml.Serialization; + [XmlInclude(typeof(ClientBoolean))] [XmlInclude(typeof(ClientNumber))] [XmlInclude(typeof(ClientString))] public class ClientOption { - public string Name { get; set; } - public string Value { get; set; } - public ClientOption() { } public ClientOption(string name, string value) { - Name = name; - Value = value; + this.Name = name; + this.Value = value; } + + public string Name { get; set; } + + public string Value { get; set; } } public class ClientString : ClientOption @@ -33,8 +34,8 @@ public ClientString() public ClientString(string name, string value) { - Name = name; - Value = value; + this.Name = name; + this.Value = value; } } @@ -46,8 +47,8 @@ public ClientNumber() public ClientNumber(string name, string value) { - Name = name; - Value = value; + this.Name = name; + this.Value = value; } } @@ -59,8 +60,8 @@ public ClientBoolean() public ClientBoolean(string name, string value) { - Name = name; - Value = value; + this.Name = name; + this.Value = value; } } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/ITemplateProcessor.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/ITemplateProcessor.cs index 4b55755f273..15a1eee1e4a 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/ITemplateProcessor.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/ITemplateProcessor.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.UI; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.TemplateEngine { - internal interface ITemplateProcessor - { - bool LoadDefinition(TemplateDefinition baseDefinition); - void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition); - } + using System.Web.UI; + + internal interface ITemplateProcessor + { + bool LoadDefinition(TemplateDefinition baseDefinition); + + void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition); + } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs index 178b9ff39e0..f71ef651bab 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Dynamic; -using System.IO; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.WebPages; -using DotNetNuke.Web.DDRMenu.DNNCommon; -using DotNetNuke.Web.Razor; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.TemplateEngine { + using System; + using System.Collections.Generic; + using System.Dynamic; + using System.IO; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.WebPages; + + using DotNetNuke.Web.DDRMenu.DNNCommon; + using DotNetNuke.Web.Razor; + public class RazorTemplateProcessor : ITemplateProcessor { public bool LoadDefinition(TemplateDefinition baseDefinition) @@ -32,7 +33,7 @@ public bool LoadDefinition(TemplateDefinition baseDefinition) public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition) { - if (!(string.IsNullOrEmpty(liveDefinition.TemplateVirtualPath))) + if (!string.IsNullOrEmpty(liveDefinition.TemplateVirtualPath)) { var resolver = new PathResolver(liveDefinition.Folder); dynamic model = new ExpandoObject(); @@ -45,31 +46,10 @@ public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition model.SkinPath = resolver.Resolve("/", PathResolver.RelativeTo.Skin); var modelDictionary = model as IDictionary; liveDefinition.TemplateArguments.ForEach(a => modelDictionary.Add(a.Name, a.Value)); - htmlWriter.Write(RenderTemplate(liveDefinition.TemplateVirtualPath, model)); + htmlWriter.Write(this.RenderTemplate(liveDefinition.TemplateVirtualPath, model)); } } - private StringWriter RenderTemplate(string virtualPath, dynamic model) - { - var page = WebPageBase.CreateInstanceFromVirtualPath(virtualPath); - var httpContext = new HttpContextWrapper(HttpContext.Current); - var pageContext = new WebPageContext(httpContext, page, model); - - var writer = new StringWriter(); - - if (page is WebPage) - { - page.ExecutePageHierarchy(pageContext, writer); - } - else - { - var razorEngine = new RazorEngine(virtualPath, null, null); - razorEngine.Render(writer, model); - } - - return writer; - } - protected static string ConvertToJson(List options) { var result = new StringBuilder(); @@ -97,6 +77,7 @@ protected static string ConvertToJson(List options) result.AppendFormat("{0}:{1},", option.Name, option.Value); } } + if (options.Count > 0) { result.Remove(result.Length - 1, 1); @@ -106,5 +87,26 @@ protected static string ConvertToJson(List options) result.Append("}"); return result.ToString(); } + + private StringWriter RenderTemplate(string virtualPath, dynamic model) + { + var page = WebPageBase.CreateInstanceFromVirtualPath(virtualPath); + var httpContext = new HttpContextWrapper(HttpContext.Current); + var pageContext = new WebPageContext(httpContext, page, model); + + var writer = new StringWriter(); + + if (page is WebPage) + { + page.ExecutePageHierarchy(pageContext, writer); + } + else + { + var razorEngine = new RazorEngine(virtualPath, null, null); + razorEngine.Render(writer, model); + } + + return writer; + } } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs index 554817478c6..80bf8bd707c 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Web.DDRMenu.TemplateEngine { public class TemplateArgument { - public string Name { get; set; } - public string Value { get; set; } - public TemplateArgument() { } public TemplateArgument(string name, string value) { - Name = name; - Value = value; + this.Name = name; + this.Value = value; } + + public string Name { get; set; } + + public string Value { get; set; } } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs index 995d15aeaad..dd253c12942 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs @@ -1,382 +1,392 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Caching; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.DDRMenu.DNNCommon; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.TemplateEngine { - public class TemplateDefinition - { - internal string Folder; - internal string TemplatePath; - internal string TemplateVirtualPath; - internal string TemplateHeadPath; - internal readonly Dictionary> ScriptLibraries = new Dictionary>(); - internal readonly List ScriptUrls = new List(); - internal readonly List ScriptKeys = new List(); - internal readonly Dictionary Scripts = new Dictionary(); - internal readonly List StyleSheets = new List(); - internal readonly List DefaultClientOptions = new List(); - internal readonly List DefaultTemplateArguments = new List(); - internal ITemplateProcessor Processor; - - public List ClientOptions = new List(); - public List TemplateArguments = new List(); - - private static readonly Regex RegexLinks = - new Regex( - "( (href|src)=['\"]?)(?!http:|ftp:|mailto:|file:|javascript:|/)([^'\">]+['\">])", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - - internal static TemplateDefinition FromName(string templateName, string manifestName) - { - var manifestUrl = new PathResolver(null).Resolve( - templateName + "/" + manifestName, - PathResolver.RelativeTo.Container, - PathResolver.RelativeTo.Skin, - PathResolver.RelativeTo.Portal, - PathResolver.RelativeTo.Module, - PathResolver.RelativeTo.Dnn); - return FromManifest(manifestUrl); - } - - internal static TemplateDefinition FromManifest(string manifestUrl) - { - var httpContext = HttpContext.Current; - var cache = httpContext.Cache; - var manifestPath = httpContext.Server.MapPath(manifestUrl); - - var baseDef = cache[manifestPath] as TemplateDefinition; - if (baseDef == null) - { - baseDef = new TemplateDefinition {Folder = Path.GetDirectoryName(manifestUrl)}; - - var xml = new XmlDocument { XmlResolver = null }; - xml.Load(manifestPath); - - var resolver = new PathResolver(baseDef.Folder); - - // ReSharper disable PossibleNullReferenceException - foreach (XmlNode node in xml.DocumentElement.ChildNodes) - // ReSharper restore PossibleNullReferenceException - { - if (node.NodeType == XmlNodeType.Element) - { - var elt = (XmlElement)node; - switch (elt.LocalName) - { - case "template": - baseDef.TemplateVirtualPath = GetResolvedPath(elt, resolver); - baseDef.TemplatePath = httpContext.Server.MapPath(baseDef.TemplateVirtualPath); - break; - case "templateHead": - baseDef.TemplateHeadPath = httpContext.Server.MapPath(GetResolvedPath(elt, resolver)); - break; - case "scripts": - foreach (XmlElement scriptElt in elt.GetElementsByTagName("script")) - { - var jsObject = scriptElt.GetAttribute("jsObject"); - var scriptPath = String.IsNullOrEmpty(scriptElt.InnerText.Trim()) - ? "" - : Globals.ResolveUrl(GetResolvedPath(scriptElt, resolver)); - if (String.IsNullOrEmpty(jsObject)) - { - var jsLibraryName = scriptElt.GetAttribute("name"); - if (!String.IsNullOrEmpty(jsLibraryName)) - { - SpecificVersion specificityTemp; - SpecificVersion? specificity = null; - Version libraryVersion; - if (!Version.TryParse(scriptElt.GetAttribute("version"), out libraryVersion)) - { - libraryVersion = null; - } - else if (Enum.TryParse(scriptElt.GetAttribute("specificVersion"), true, out specificityTemp)) - { - specificity = specificityTemp; - } - - baseDef.ScriptLibraries[jsLibraryName] = Tuple.Create(libraryVersion, specificity); - continue; - } - - baseDef.ScriptUrls.Add(scriptPath); - continue; - } - - if (String.IsNullOrEmpty(scriptPath)) - { - // support legacy named jsObjects that map to libraries - if (jsObject.Equals("jQuery")) - { - Version libraryVersion = null; - SpecificVersion? specificity = null; - baseDef.ScriptLibraries[CommonJs.jQuery] = Tuple.Create(libraryVersion, specificity); - baseDef.ScriptLibraries[CommonJs.jQueryMigrate] = Tuple.Create(libraryVersion, specificity); - } - else if (jsObject.Equals("jQuery.ui")) - { - Version libraryVersion = null; - SpecificVersion? specificity = null; - baseDef.ScriptLibraries[CommonJs.jQueryUI] = Tuple.Create(libraryVersion, specificity); - } - - continue; - } - - var script = CreateScript(jsObject, scriptPath); - if (!String.IsNullOrEmpty(script)) - { - baseDef.ScriptKeys.Add(jsObject); - baseDef.Scripts.Add(jsObject, script); - } - } - break; - case "stylesheets": - foreach (XmlElement cssElt in elt.GetElementsByTagName("stylesheet")) - { - var cssPath = Globals.ResolveUrl(GetResolvedPath(cssElt, resolver)); - baseDef.StyleSheets.Add(cssPath); - } - break; - case "defaultClientOptions": - foreach (XmlElement optionElt in elt.GetElementsByTagName("clientOption")) - { - var optionName = optionElt.GetAttribute("name"); - var optionType = optionElt.GetAttribute("type"); - var optionValue = optionElt.GetAttribute("value"); - if (String.IsNullOrEmpty(optionType)) - { - optionType = "passthrough"; - } - switch (optionType) - { - case "number": - baseDef.DefaultClientOptions.Add(new ClientNumber(optionName, optionValue)); - break; - case "boolean": - baseDef.DefaultClientOptions.Add(new ClientBoolean(optionName, optionValue)); - break; - case "string": - baseDef.DefaultClientOptions.Add(new ClientString(optionName, optionValue)); - break; - default: - baseDef.DefaultClientOptions.Add(new ClientOption(optionName, optionValue)); - break; - } - } - break; - case "defaultTemplateArguments": - foreach (XmlElement argElt in elt.GetElementsByTagName("templateArgument")) - { - var argName = argElt.GetAttribute("name"); - var argValue = argElt.GetAttribute("value"); - baseDef.DefaultTemplateArguments.Add(new TemplateArgument(argName, argValue)); - } - break; - } - } - } - - foreach (var processor in DNNAbstract.SupportedTemplateProcessors()) - { - if (processor.LoadDefinition(baseDef)) - { - baseDef.Processor = processor; - break; - } - } - - if (baseDef.Processor == null) - { - throw new ApplicationException(String.Format("Can't find processor for manifest {0}", manifestPath)); - } - - cache.Insert(manifestPath, baseDef, new CacheDependency(new[] {manifestPath, baseDef.TemplatePath})); - } - - var result = baseDef.Clone(); - result.Reset(); - return result; - } - - private static string GetResolvedPath(XmlNode scriptElt, PathResolver pathResolver) - { - return pathResolver.Resolve( - scriptElt.InnerText.Trim(), - PathResolver.RelativeTo.Manifest, - PathResolver.RelativeTo.Skin, - PathResolver.RelativeTo.Module, - PathResolver.RelativeTo.Portal, - PathResolver.RelativeTo.Dnn); - } - - private static string CreateScript(string jsObject, string scriptPath) - { - string result; - - jsObject = jsObject ?? ""; - - if (String.IsNullOrEmpty(scriptPath)) - { - switch (jsObject) - { - case "DDRjQuery": - scriptPath = ""; - break; - default: - throw new ApplicationException(String.Format("Can't deduce script path for JavaScript object '{0}'", jsObject)); - } - } - - if (jsObject == "DDRjQuery") - { - result = String.IsNullOrEmpty(scriptPath) - ? @"" - : String.Format( - @"", - scriptPath); - } - else - { - result = String.IsNullOrEmpty(scriptPath) - ? "" - : String.Format( - @"", - GetObjectCheckScript(jsObject), - scriptPath); - } - - return result; - } - - private static string GetObjectCheckScript(string jsObject) - { - var objectParts = jsObject.Split('.'); - var objectToCheck = new StringBuilder("window"); - var objectsToCheck = new List(); - foreach (var part in objectParts) - { - objectToCheck.AppendFormat(".{0}", part); - objectsToCheck.Add(objectToCheck.ToString()); - } - return String.Join(" && ", objectsToCheck.ToArray()); - } - - public TemplateDefinition Clone() - { - return (TemplateDefinition)MemberwiseClone(); - } - - public void Reset() - { - ClientOptions = new List(DefaultClientOptions); - TemplateArguments = new List(DefaultTemplateArguments); - } - - public void AddClientOptions(List options, bool replace) - { - if (options != null) - { - foreach (var option in options) - { - var option1 = option; - if (replace) - { - ClientOptions.RemoveAll(o => o.Name == option1.Name); - } - if (!ClientOptions.Exists(o => o.Name == option1.Name)) - { - ClientOptions.Add(option); - } - } - } - } - - public void AddTemplateArguments(List args, bool replace) - { - if (args != null) - { - foreach (var arg in args) - { - var arg1 = arg; - if (replace) - { - TemplateArguments.RemoveAll(a => a.Name == arg1.Name); - } - if (!TemplateArguments.Exists(a => a.Name == arg1.Name)) - { - TemplateArguments.Add(arg); - } - } - } - } - - internal void PreRender() - { - var page = DNNContext.Current.Page; - - foreach (var stylesheet in StyleSheets) - { - ClientResourceManager.RegisterStyleSheet(page, stylesheet); - } - - foreach (var scriptUrl in ScriptUrls) - { - ClientResourceManager.RegisterScript(page, scriptUrl); - } - - foreach (var libraryInfo in ScriptLibraries) - { - var libraryName = libraryInfo.Key; - var parameters = libraryInfo.Value; - var libraryVersion = parameters.Item1; - var specificVersion = parameters.Item2; - if (libraryVersion == null) - { - JavaScript.RequestRegistration(libraryName); - } - else if (specificVersion == null) - { - JavaScript.RequestRegistration(libraryName, libraryVersion); - } - else - { - JavaScript.RequestRegistration(libraryName, libraryVersion, specificVersion.Value); - } - } - - foreach (var scriptKey in ScriptKeys) - { - var clientScript = page.ClientScript; - if (!clientScript.IsClientScriptBlockRegistered(typeof(TemplateDefinition), scriptKey)) - { - clientScript.RegisterClientScriptBlock(typeof(TemplateDefinition), scriptKey, Scripts[scriptKey], false); - } - } - - var headContent = String.IsNullOrEmpty(TemplateHeadPath) ? "" : Utilities.CachedFileContent(TemplateHeadPath); - var expandedHead = RegexLinks.Replace(headContent, "$1" + DNNContext.Current.ActiveTab.SkinPath + "$3"); - page.Header.Controls.Add(new LiteralControl(expandedHead)); - } - - internal void Render(object source, HtmlTextWriter htmlWriter) - { - Processor.Render(source, htmlWriter, this); - } - } + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Caching; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.DDRMenu.DNNCommon; + + public class TemplateDefinition + { + public List ClientOptions = new List(); + public List TemplateArguments = new List(); + + internal string Folder; + internal string TemplatePath; + internal string TemplateVirtualPath; + internal string TemplateHeadPath; + internal readonly Dictionary> ScriptLibraries = new Dictionary>(); + internal readonly List ScriptUrls = new List(); + internal readonly List ScriptKeys = new List(); + internal readonly Dictionary Scripts = new Dictionary(); + internal readonly List StyleSheets = new List(); + internal readonly List DefaultClientOptions = new List(); + internal readonly List DefaultTemplateArguments = new List(); + internal ITemplateProcessor Processor; + + private static readonly Regex RegexLinks = + new Regex( + "( (href|src)=['\"]?)(?!http:|ftp:|mailto:|file:|javascript:|/)([^'\">]+['\">])", + RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + public TemplateDefinition Clone() + { + return (TemplateDefinition)this.MemberwiseClone(); + } + + public void Reset() + { + this.ClientOptions = new List(this.DefaultClientOptions); + this.TemplateArguments = new List(this.DefaultTemplateArguments); + } + + internal static TemplateDefinition FromName(string templateName, string manifestName) + { + var manifestUrl = new PathResolver(null).Resolve( + templateName + "/" + manifestName, + PathResolver.RelativeTo.Container, + PathResolver.RelativeTo.Skin, + PathResolver.RelativeTo.Portal, + PathResolver.RelativeTo.Module, + PathResolver.RelativeTo.Dnn); + return FromManifest(manifestUrl); + } + + internal static TemplateDefinition FromManifest(string manifestUrl) + { + var httpContext = HttpContext.Current; + var cache = httpContext.Cache; + var manifestPath = httpContext.Server.MapPath(manifestUrl); + + var baseDef = cache[manifestPath] as TemplateDefinition; + if (baseDef == null) + { + baseDef = new TemplateDefinition { Folder = Path.GetDirectoryName(manifestUrl) }; + + var xml = new XmlDocument { XmlResolver = null }; + xml.Load(manifestPath); + + var resolver = new PathResolver(baseDef.Folder); + + // ReSharper disable PossibleNullReferenceException + foreach (XmlNode node in xml.DocumentElement.ChildNodes) + + // ReSharper restore PossibleNullReferenceException + { + if (node.NodeType == XmlNodeType.Element) + { + var elt = (XmlElement)node; + switch (elt.LocalName) + { + case "template": + baseDef.TemplateVirtualPath = GetResolvedPath(elt, resolver); + baseDef.TemplatePath = httpContext.Server.MapPath(baseDef.TemplateVirtualPath); + break; + case "templateHead": + baseDef.TemplateHeadPath = httpContext.Server.MapPath(GetResolvedPath(elt, resolver)); + break; + case "scripts": + foreach (XmlElement scriptElt in elt.GetElementsByTagName("script")) + { + var jsObject = scriptElt.GetAttribute("jsObject"); + var scriptPath = string.IsNullOrEmpty(scriptElt.InnerText.Trim()) + ? string.Empty + : Globals.ResolveUrl(GetResolvedPath(scriptElt, resolver)); + if (string.IsNullOrEmpty(jsObject)) + { + var jsLibraryName = scriptElt.GetAttribute("name"); + if (!string.IsNullOrEmpty(jsLibraryName)) + { + SpecificVersion specificityTemp; + SpecificVersion? specificity = null; + Version libraryVersion; + if (!Version.TryParse(scriptElt.GetAttribute("version"), out libraryVersion)) + { + libraryVersion = null; + } + else if (Enum.TryParse(scriptElt.GetAttribute("specificVersion"), true, out specificityTemp)) + { + specificity = specificityTemp; + } + + baseDef.ScriptLibraries[jsLibraryName] = Tuple.Create(libraryVersion, specificity); + continue; + } + + baseDef.ScriptUrls.Add(scriptPath); + continue; + } + + if (string.IsNullOrEmpty(scriptPath)) + { + // support legacy named jsObjects that map to libraries + if (jsObject.Equals("jQuery")) + { + Version libraryVersion = null; + SpecificVersion? specificity = null; + baseDef.ScriptLibraries[CommonJs.jQuery] = Tuple.Create(libraryVersion, specificity); + baseDef.ScriptLibraries[CommonJs.jQueryMigrate] = Tuple.Create(libraryVersion, specificity); + } + else if (jsObject.Equals("jQuery.ui")) + { + Version libraryVersion = null; + SpecificVersion? specificity = null; + baseDef.ScriptLibraries[CommonJs.jQueryUI] = Tuple.Create(libraryVersion, specificity); + } + + continue; + } + + var script = CreateScript(jsObject, scriptPath); + if (!string.IsNullOrEmpty(script)) + { + baseDef.ScriptKeys.Add(jsObject); + baseDef.Scripts.Add(jsObject, script); + } + } + + break; + case "stylesheets": + foreach (XmlElement cssElt in elt.GetElementsByTagName("stylesheet")) + { + var cssPath = Globals.ResolveUrl(GetResolvedPath(cssElt, resolver)); + baseDef.StyleSheets.Add(cssPath); + } + + break; + case "defaultClientOptions": + foreach (XmlElement optionElt in elt.GetElementsByTagName("clientOption")) + { + var optionName = optionElt.GetAttribute("name"); + var optionType = optionElt.GetAttribute("type"); + var optionValue = optionElt.GetAttribute("value"); + if (string.IsNullOrEmpty(optionType)) + { + optionType = "passthrough"; + } + + switch (optionType) + { + case "number": + baseDef.DefaultClientOptions.Add(new ClientNumber(optionName, optionValue)); + break; + case "boolean": + baseDef.DefaultClientOptions.Add(new ClientBoolean(optionName, optionValue)); + break; + case "string": + baseDef.DefaultClientOptions.Add(new ClientString(optionName, optionValue)); + break; + default: + baseDef.DefaultClientOptions.Add(new ClientOption(optionName, optionValue)); + break; + } + } + + break; + case "defaultTemplateArguments": + foreach (XmlElement argElt in elt.GetElementsByTagName("templateArgument")) + { + var argName = argElt.GetAttribute("name"); + var argValue = argElt.GetAttribute("value"); + baseDef.DefaultTemplateArguments.Add(new TemplateArgument(argName, argValue)); + } + + break; + } + } + } + + foreach (var processor in DNNAbstract.SupportedTemplateProcessors()) + { + if (processor.LoadDefinition(baseDef)) + { + baseDef.Processor = processor; + break; + } + } + + if (baseDef.Processor == null) + { + throw new ApplicationException(string.Format("Can't find processor for manifest {0}", manifestPath)); + } + + cache.Insert(manifestPath, baseDef, new CacheDependency(new[] { manifestPath, baseDef.TemplatePath })); + } + + var result = baseDef.Clone(); + result.Reset(); + return result; + } + + private static string GetResolvedPath(XmlNode scriptElt, PathResolver pathResolver) + { + return pathResolver.Resolve( + scriptElt.InnerText.Trim(), + PathResolver.RelativeTo.Manifest, + PathResolver.RelativeTo.Skin, + PathResolver.RelativeTo.Module, + PathResolver.RelativeTo.Portal, + PathResolver.RelativeTo.Dnn); + } + + private static string CreateScript(string jsObject, string scriptPath) + { + string result; + + jsObject = jsObject ?? string.Empty; + + if (string.IsNullOrEmpty(scriptPath)) + { + switch (jsObject) + { + case "DDRjQuery": + scriptPath = string.Empty; + break; + default: + throw new ApplicationException(string.Format("Can't deduce script path for JavaScript object '{0}'", jsObject)); + } + } + + if (jsObject == "DDRjQuery") + { + result = string.IsNullOrEmpty(scriptPath) + ? @"" + : string.Format( + @"", + scriptPath); + } + else + { + result = string.IsNullOrEmpty(scriptPath) + ? string.Empty + : string.Format( + @"", + GetObjectCheckScript(jsObject), + scriptPath); + } + + return result; + } + + private static string GetObjectCheckScript(string jsObject) + { + var objectParts = jsObject.Split('.'); + var objectToCheck = new StringBuilder("window"); + var objectsToCheck = new List(); + foreach (var part in objectParts) + { + objectToCheck.AppendFormat(".{0}", part); + objectsToCheck.Add(objectToCheck.ToString()); + } + + return string.Join(" && ", objectsToCheck.ToArray()); + } + + public void AddClientOptions(List options, bool replace) + { + if (options != null) + { + foreach (var option in options) + { + var option1 = option; + if (replace) + { + this.ClientOptions.RemoveAll(o => o.Name == option1.Name); + } + + if (!this.ClientOptions.Exists(o => o.Name == option1.Name)) + { + this.ClientOptions.Add(option); + } + } + } + } + + public void AddTemplateArguments(List args, bool replace) + { + if (args != null) + { + foreach (var arg in args) + { + var arg1 = arg; + if (replace) + { + this.TemplateArguments.RemoveAll(a => a.Name == arg1.Name); + } + + if (!this.TemplateArguments.Exists(a => a.Name == arg1.Name)) + { + this.TemplateArguments.Add(arg); + } + } + } + } + + internal void PreRender() + { + var page = DNNContext.Current.Page; + + foreach (var stylesheet in this.StyleSheets) + { + ClientResourceManager.RegisterStyleSheet(page, stylesheet); + } + + foreach (var scriptUrl in this.ScriptUrls) + { + ClientResourceManager.RegisterScript(page, scriptUrl); + } + + foreach (var libraryInfo in this.ScriptLibraries) + { + var libraryName = libraryInfo.Key; + var parameters = libraryInfo.Value; + var libraryVersion = parameters.Item1; + var specificVersion = parameters.Item2; + if (libraryVersion == null) + { + JavaScript.RequestRegistration(libraryName); + } + else if (specificVersion == null) + { + JavaScript.RequestRegistration(libraryName, libraryVersion); + } + else + { + JavaScript.RequestRegistration(libraryName, libraryVersion, specificVersion.Value); + } + } + + foreach (var scriptKey in this.ScriptKeys) + { + var clientScript = page.ClientScript; + if (!clientScript.IsClientScriptBlockRegistered(typeof(TemplateDefinition), scriptKey)) + { + clientScript.RegisterClientScriptBlock(typeof(TemplateDefinition), scriptKey, this.Scripts[scriptKey], false); + } + } + + var headContent = string.IsNullOrEmpty(this.TemplateHeadPath) ? string.Empty : Utilities.CachedFileContent(this.TemplateHeadPath); + var expandedHead = RegexLinks.Replace(headContent, "$1" + DNNContext.Current.ActiveTab.SkinPath + "$3"); + page.Header.Controls.Add(new LiteralControl(expandedHead)); + } + + internal void Render(object source, HtmlTextWriter htmlWriter) + { + this.Processor.Render(source, htmlWriter, this); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs index d0d103bba20..039b8a02d35 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs @@ -1,43 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.UI; -using System.Xml; -using System.Xml.Xsl; -using DotNetNuke.Web.DDRMenu.DNNCommon; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.TemplateEngine { - public class TokenTemplateProcessor : ITemplateProcessor - { - private XslCompiledTransform xsl; - private static readonly Dictionary aliases = new Dictionary - {{"page", "node"}, {"name", "text"}}; - + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI; + using System.Xml; + using System.Xml.Xsl; + + using DotNetNuke.Web.DDRMenu.DNNCommon; + + public class TokenTemplateProcessor : ITemplateProcessor + { + private static readonly Dictionary aliases = new Dictionary + { { "page", "node" }, { "name", "text" } }; private static readonly Regex TemplatesRegex = new Regex( @"(\[(?(\*|\*\>|\/\*|\>|\/\>|\?|\?!|\/\?|\=))(?[A-Z]*)(-(?[0-9A-Z]*))?\])", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private XslCompiledTransform xsl; + public bool LoadDefinition(TemplateDefinition baseDefinition) - { - if (!baseDefinition.TemplateVirtualPath.EndsWith(".txt", StringComparison.InvariantCultureIgnoreCase)) - { - return false; - } - - var templateText = Utilities.CachedFileContent(baseDefinition.TemplatePath); - var xml = new XmlDocument { XmlResolver = null }; - const string xmlNs = "http://www.w3.org/1999/XSL/Transform"; - xml.LoadXml( - @" + { + if (!baseDefinition.TemplateVirtualPath.EndsWith(".txt", StringComparison.InvariantCultureIgnoreCase)) + { + return false; + } + + var templateText = Utilities.CachedFileContent(baseDefinition.TemplatePath); + var xml = new XmlDocument { XmlResolver = null }; + const string xmlNs = "http://www.w3.org/1999/XSL/Transform"; + xml.LoadXml( + @" @@ -47,173 +48,179 @@ public bool LoadDefinition(TemplateDefinition baseDefinition) "); - var validParams = baseDefinition.DefaultTemplateArguments.ConvertAll(a => a.Name.ToLowerInvariant()); - validParams.AddRange(new[] { "controlid", "options", "dnnpath", "manifestpath", "portalpath", "skinpath" }); + var validParams = baseDefinition.DefaultTemplateArguments.ConvertAll(a => a.Name.ToLowerInvariant()); + validParams.AddRange(new[] { "controlid", "options", "dnnpath", "manifestpath", "portalpath", "skinpath" }); + + var docElt = xml.DocumentElement; + var outputElt = (XmlElement)docElt.GetElementsByTagName("output", xmlNs)[0]; + foreach (var param in validParams) + { + var elt = xml.CreateElement("param", xmlNs); + elt.SetAttribute("name", param); + docElt.InsertAfter(elt, outputElt); + } + + var current = (XmlElement)docElt.GetElementsByTagName("template", xmlNs)[1]; + var stack = new Stack(); + + var index = 0; + foreach (Match match in TemplatesRegex.Matches(templateText)) + { + current.AppendChild(xml.CreateTextNode(templateText.Substring(index, match.Index - index))); + + var directive = match.Groups["directive"].Value; + var nodeName = match.Groups["nodename"].Value.ToLowerInvariant(); + var modeName = match.Groups["modename"].Value.ToLowerInvariant(); + + string alias; + if (aliases.TryGetValue(nodeName, out alias)) + { + nodeName = alias; + } + + if (directive == "=") + { + var elt = xml.CreateElement("value-of", xmlNs); + if (validParams.Contains(nodeName)) + { + elt.SetAttribute("select", "ddr:HtmlEncode($" + nodeName + ")"); + } + else + { + elt.SetAttribute("select", "ddr:HtmlEncode(concat(" + nodeName + ", @" + nodeName + "))"); + } + + current.AppendChild(elt); + } + else if (directive == "*") + { + var elt = xml.CreateElement("for-each", xmlNs); + elt.SetAttribute("select", nodeName); + current.AppendChild(elt); + stack.Push(current); + current = elt; + } + else if (directive == "*>") + { + var elt = xml.CreateElement("apply-templates", xmlNs); + elt.SetAttribute("select", nodeName); + elt.SetAttribute("mode", "M" + modeName); + current.AppendChild(elt); + } + else if (directive == ">") + { + var elt = xml.CreateElement("template", xmlNs); + elt.SetAttribute("match", nodeName); + elt.SetAttribute("mode", "M" + modeName); + xml.DocumentElement.AppendChild(elt); + stack.Push(current); + current = elt; + } + else if (directive[0] == '?') + { + XmlElement elt; + if (nodeName != "else") + { + elt = xml.CreateElement("when", xmlNs); + var test = string.Format("{0} or (@{0}=1) or (@{0}!=0 and @{0}!=1 and @{0}!='')", nodeName); + if (directive == "?!") + { + test = string.Format("not({0})", test); + } + + elt.SetAttribute("test", test); + + var choose = xml.CreateElement("choose", xmlNs); + current.AppendChild(choose); + choose.AppendChild(elt); + stack.Push(current); + } + else + { + elt = xml.CreateElement("otherwise", xmlNs); + current.ParentNode.AppendChild(elt); + } + + current = elt; + } + else if (directive[0] == '/') + { + current = stack.Pop(); + } + + index = match.Index + match.Length; + } + + current.AppendChild(xml.CreateTextNode(templateText.Substring(index))); + + this.xsl = new XslCompiledTransform(); + this.xsl.Load(xml); + return true; + } + + public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition) + { + var resolver = new PathResolver(liveDefinition.Folder); + var args = new XsltArgumentList(); + args.AddExtensionObject("urn:ddrmenu", new XsltFunctions()); + args.AddExtensionObject("urn:dnngarden", new XsltFunctions()); + args.AddParam("controlid", string.Empty, DNNContext.Current.HostControl.ClientID); + args.AddParam("options", string.Empty, ConvertToJson(liveDefinition.ClientOptions)); + args.AddParam("dnnpath", string.Empty, resolver.Resolve("/", PathResolver.RelativeTo.Dnn)); + args.AddParam("manifestpath", string.Empty, resolver.Resolve("/", PathResolver.RelativeTo.Manifest)); + args.AddParam("portalpath", string.Empty, resolver.Resolve("/", PathResolver.RelativeTo.Portal)); + args.AddParam("skinpath", string.Empty, resolver.Resolve("/", PathResolver.RelativeTo.Skin)); + liveDefinition.TemplateArguments.ForEach(a => args.AddParam(a.Name.ToLowerInvariant(), string.Empty, a.Value)); + + var sb = new StringBuilder(); + + using (var xmlStream = new MemoryStream()) + using (var outputWriter = new StringWriter(sb)) + { + Utilities.SerialiserFor(source.GetType()).Serialize(xmlStream, source); + xmlStream.Seek(0, SeekOrigin.Begin); + this.xsl.Transform(XmlReader.Create(xmlStream), args, outputWriter); + } - var docElt = xml.DocumentElement; - var outputElt = (XmlElement)(docElt.GetElementsByTagName("output", xmlNs)[0]); - foreach (var param in validParams) - { - var elt = xml.CreateElement("param", xmlNs); - elt.SetAttribute("name", param); - docElt.InsertAfter(elt, outputElt); - } + htmlWriter.Write(HttpUtility.HtmlDecode(sb.ToString())); + } - var current = (XmlElement)(docElt.GetElementsByTagName("template", xmlNs)[1]); - var stack = new Stack(); + protected static string ConvertToJson(List options) + { + var result = new StringBuilder(); + result.Append("{"); - var index = 0; - foreach (Match match in TemplatesRegex.Matches(templateText)) + if (options != null) { - current.AppendChild(xml.CreateTextNode(templateText.Substring(index, match.Index - index))); - - var directive = match.Groups["directive"].Value; - var nodeName = match.Groups["nodename"].Value.ToLowerInvariant(); - var modeName = match.Groups["modename"].Value.ToLowerInvariant(); - - string alias; - if (aliases.TryGetValue(nodeName, out alias)) - { - nodeName = alias; - } - - if (directive == "=") - { - var elt = xml.CreateElement("value-of", xmlNs); - if (validParams.Contains(nodeName)) - { - elt.SetAttribute("select", "ddr:HtmlEncode($" + nodeName + ")"); - } - else - { - elt.SetAttribute("select", "ddr:HtmlEncode(concat(" + nodeName + ", @" + nodeName + "))"); - } - current.AppendChild(elt); - } - else if (directive == "*") - { - var elt = xml.CreateElement("for-each", xmlNs); - elt.SetAttribute("select", nodeName); - current.AppendChild(elt); - stack.Push(current); - current = elt; - } - else if (directive == "*>") - { - var elt = xml.CreateElement("apply-templates", xmlNs); - elt.SetAttribute("select", nodeName); - elt.SetAttribute("mode", "M" + modeName); - current.AppendChild(elt); - } - else if (directive == ">") - { - var elt = xml.CreateElement("template", xmlNs); - elt.SetAttribute("match", nodeName); - elt.SetAttribute("mode", "M" + modeName); - xml.DocumentElement.AppendChild(elt); - stack.Push(current); - current = elt; - } - else if (directive[0] == '?') - { - XmlElement elt; - if (nodeName != "else") - { - elt = xml.CreateElement("when", xmlNs); - var test = String.Format("{0} or (@{0}=1) or (@{0}!=0 and @{0}!=1 and @{0}!='')", nodeName); - if (directive == "?!") - { - test = String.Format("not({0})", test); - } - elt.SetAttribute("test", test); - - var choose = xml.CreateElement("choose", xmlNs); - current.AppendChild(choose); - choose.AppendChild(elt); - stack.Push(current); - } - else - { - elt = xml.CreateElement("otherwise", xmlNs); - current.ParentNode.AppendChild(elt); - } - current = elt; - } - else if (directive[0] == '/') - { - current = stack.Pop(); - } - index = match.Index + match.Length; - } - current.AppendChild(xml.CreateTextNode(templateText.Substring(index))); - - xsl = new XslCompiledTransform(); - xsl.Load(xml); - return true; - } - - public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition) - { - var resolver = new PathResolver(liveDefinition.Folder); - var args = new XsltArgumentList(); - args.AddExtensionObject("urn:ddrmenu", new XsltFunctions()); - args.AddExtensionObject("urn:dnngarden", new XsltFunctions()); - args.AddParam("controlid", "", DNNContext.Current.HostControl.ClientID); - args.AddParam("options", "", ConvertToJson(liveDefinition.ClientOptions)); - args.AddParam("dnnpath", "", resolver.Resolve("/", PathResolver.RelativeTo.Dnn)); - args.AddParam("manifestpath", "", resolver.Resolve("/", PathResolver.RelativeTo.Manifest)); - args.AddParam("portalpath", "", resolver.Resolve("/", PathResolver.RelativeTo.Portal)); - args.AddParam("skinpath", "", resolver.Resolve("/", PathResolver.RelativeTo.Skin)); - liveDefinition.TemplateArguments.ForEach(a => args.AddParam(a.Name.ToLowerInvariant(), "", a.Value)); - - var sb = new StringBuilder(); - - using (var xmlStream = new MemoryStream()) - using (var outputWriter = new StringWriter(sb)) - { - Utilities.SerialiserFor(source.GetType()).Serialize(xmlStream, source); - xmlStream.Seek(0, SeekOrigin.Begin); - xsl.Transform(XmlReader.Create(xmlStream), args, outputWriter); - } - - htmlWriter.Write(HttpUtility.HtmlDecode(sb.ToString())); - } - - protected static string ConvertToJson(List options) - { - var result = new StringBuilder(); - result.Append("{"); - - if (options != null) - { - foreach (var option in options) - { - if (option is ClientNumber) - { - result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToDecimal(option.Value))); - } - else if (option is ClientString) - { - result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(option.Value)); - } - else if (option is ClientBoolean) - { - result.AppendFormat( - "{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToBoolean(option.Value.ToLowerInvariant()))); - } - else - { - result.AppendFormat("{0}:{1},", option.Name, option.Value); - } - } - if (options.Count > 0) - { - result.Remove(result.Length - 1, 1); - } - } - - result.Append("}"); - return result.ToString(); - } - } + foreach (var option in options) + { + if (option is ClientNumber) + { + result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToDecimal(option.Value))); + } + else if (option is ClientString) + { + result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(option.Value)); + } + else if (option is ClientBoolean) + { + result.AppendFormat( + "{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToBoolean(option.Value.ToLowerInvariant()))); + } + else + { + result.AppendFormat("{0}:{1},", option.Name, option.Value); + } + } + + if (options.Count > 0) + { + result.Remove(result.Length - 1, 1); + } + } + + result.Append("}"); + return result.ToString(); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs index b49faa5c690..46a80ab8c9e 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs @@ -1,117 +1,121 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Reflection; -using System.Security; -using System.Web; -using System.Web.UI; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.DDRMenu.DNNCommon; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.TemplateEngine { - public class XsltFunctions - { - public bool UserIsInRole(string roleName) - { - return UserController.Instance.GetCurrentUserInfo().IsInRole(roleName); - } + using System; + using System.IO; + using System.Reflection; + using System.Security; + using System.Web; + using System.Web.UI; - public string GetLoginURL() - { - return DNNAbstract.GetLoginUrl(); - } + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.DDRMenu.DNNCommon; - public string GetLoginText() - { - try - { - return Localization.GetString( - HttpContext.Current.Request.IsAuthenticated ? "Logout" : "Login", - DNNContext.Current.ResolveUrl("~/Admin/Skins/" + Localization.LocalResourceDirectory + "/Login.ascx")); - } - catch (Exception) - { - return "Login"; - } - } + public class XsltFunctions + { + public bool UserIsInRole(string roleName) + { + return UserController.Instance.GetCurrentUserInfo().IsInRole(roleName); + } - public string GetUserURL() - { - return DNNAbstract.GetUserUrl(); - } + public string GetLoginURL() + { + return DNNAbstract.GetLoginUrl(); + } - public string GetUserText() - { - try - { - return HttpContext.Current.Request.IsAuthenticated - ? UserController.Instance.GetCurrentUserInfo().DisplayName - : Localization.GetString( - "Register", - // ReSharper disable PossibleNullReferenceException - (HttpContext.Current.Items["DDRMenuHostControl"] as Control).ResolveUrl( - "~/Admin/Skins/" + Localization.LocalResourceDirectory + "/User.ascx")); -// ReSharper restore PossibleNullReferenceException - } - catch (Exception exc) - { - return exc.ToString(); - } - } + public string GetLoginText() + { + try + { + return Localization.GetString( + HttpContext.Current.Request.IsAuthenticated ? "Logout" : "Login", + DNNContext.Current.ResolveUrl("~/Admin/Skins/" + Localization.LocalResourceDirectory + "/Login.ascx")); + } + catch (Exception) + { + return "Login"; + } + } - public string EscapeXML(string xml) - { - return SecurityElement.Escape(xml); - } + public string GetUserURL() + { + return DNNAbstract.GetUserUrl(); + } - public string HtmlEncode(string s) - { - return HttpUtility.HtmlEncode(s); - } + public string GetUserText() + { + try + { + return HttpContext.Current.Request.IsAuthenticated + ? UserController.Instance.GetCurrentUserInfo().DisplayName + : Localization.GetString( + "Register", - public string GetString(string name, string resourceFile) - { - var resolver = HttpContext.Current.Items["Resolver"] as PathResolver; - var resolvedFile = ""; - if (resolver != null) - { - var localFile = resolver.Resolve( - resourceFile, - PathResolver.RelativeTo.Manifest, - PathResolver.RelativeTo.Skin, - PathResolver.RelativeTo.Module, - PathResolver.RelativeTo.Dnn); - if (File.Exists(HttpContext.Current.Server.MapPath(localFile))) - { - resolvedFile = localFile; - } - } + // ReSharper disable PossibleNullReferenceException + (HttpContext.Current.Items["DDRMenuHostControl"] as Control).ResolveUrl( + "~/Admin/Skins/" + Localization.LocalResourceDirectory + "/User.ascx")); - if (String.IsNullOrEmpty(resolvedFile)) - { - resolvedFile = "~/" + resourceFile; - } - return Localization.GetString(name, resolvedFile); - } + // ReSharper restore PossibleNullReferenceException + } + catch (Exception exc) + { + return exc.ToString(); + } + } - public bool ActionCommandIs(string commandName, string constName) - { - try - { - return - commandName.Equals( - typeof(DotNetNuke.Entities.Modules.Actions.ModuleActionType).InvokeMember( - constName, BindingFlags.GetField, null, null, new object[0])); - } - catch (MissingFieldException) - { - return false; - } - } - } + public string EscapeXML(string xml) + { + return SecurityElement.Escape(xml); + } + + public string HtmlEncode(string s) + { + return HttpUtility.HtmlEncode(s); + } + + public string GetString(string name, string resourceFile) + { + var resolver = HttpContext.Current.Items["Resolver"] as PathResolver; + var resolvedFile = string.Empty; + if (resolver != null) + { + var localFile = resolver.Resolve( + resourceFile, + PathResolver.RelativeTo.Manifest, + PathResolver.RelativeTo.Skin, + PathResolver.RelativeTo.Module, + PathResolver.RelativeTo.Dnn); + if (File.Exists(HttpContext.Current.Server.MapPath(localFile))) + { + resolvedFile = localFile; + } + } + + if (string.IsNullOrEmpty(resolvedFile)) + { + resolvedFile = "~/" + resourceFile; + } + + return Localization.GetString(name, resolvedFile); + } + + public bool ActionCommandIs(string commandName, string constName) + { + try + { + return + commandName.Equals( + typeof(DotNetNuke.Entities.Modules.Actions.ModuleActionType).InvokeMember( + constName, BindingFlags.GetField, null, null, new object[0])); + } + catch (MissingFieldException) + { + return false; + } + } + } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltTemplateProcessor.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltTemplateProcessor.cs index 7b351e38319..7dd7695844a 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltTemplateProcessor.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltTemplateProcessor.cs @@ -1,27 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Xml; -using System.Xml.Xsl; -using DotNetNuke.Web.DDRMenu.DNNCommon; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Web.DDRMenu.TemplateEngine { - public class XsltTemplateProcessor : ITemplateProcessor - { - private XslCompiledTransform xsl; + using System; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Xml; + using System.Xml.Xsl; - public bool LoadDefinition(TemplateDefinition baseDefinition) - { - try - { + using DotNetNuke.Web.DDRMenu.DNNCommon; + + public class XsltTemplateProcessor : ITemplateProcessor + { + private XslCompiledTransform xsl; + + public bool LoadDefinition(TemplateDefinition baseDefinition) + { + try + { var virtualPath = baseDefinition.TemplateVirtualPath; if (!virtualPath.EndsWith(".xsl", StringComparison.InvariantCultureIgnoreCase) && !virtualPath.EndsWith(".xslt", StringComparison.InvariantCultureIgnoreCase)) @@ -29,76 +30,77 @@ public bool LoadDefinition(TemplateDefinition baseDefinition) return false; } - xsl = Utilities.CachedXslt(baseDefinition.TemplatePath); - return true; - } - catch (Exception) - { - return false; - } - } + this.xsl = Utilities.CachedXslt(baseDefinition.TemplatePath); + return true; + } + catch (Exception) + { + return false; + } + } - public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition) - { - var resolver = new PathResolver(liveDefinition.Folder); - var hostPage = DNNContext.Current.Page; + public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition) + { + var resolver = new PathResolver(liveDefinition.Folder); + var hostPage = DNNContext.Current.Page; - var args = new XsltArgumentList(); - args.AddExtensionObject("urn:ddrmenu", new XsltFunctions()); - args.AddExtensionObject("urn:dnngarden", new XsltFunctions()); - args.AddParam("ControlID", "", DNNContext.Current.HostControl.ClientID); - args.AddParam("Options", "", ConvertToJson(liveDefinition.ClientOptions)); - args.AddParam("DNNPath", "", hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Dnn))); - args.AddParam("ManifestPath", "", hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Manifest))); - args.AddParam("PortalPath", "", hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Portal))); - args.AddParam("SkinPath", "", hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Skin))); - liveDefinition.TemplateArguments.ForEach(a => args.AddParam(a.Name, "", a.Value)); + var args = new XsltArgumentList(); + args.AddExtensionObject("urn:ddrmenu", new XsltFunctions()); + args.AddExtensionObject("urn:dnngarden", new XsltFunctions()); + args.AddParam("ControlID", string.Empty, DNNContext.Current.HostControl.ClientID); + args.AddParam("Options", string.Empty, ConvertToJson(liveDefinition.ClientOptions)); + args.AddParam("DNNPath", string.Empty, hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Dnn))); + args.AddParam("ManifestPath", string.Empty, hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Manifest))); + args.AddParam("PortalPath", string.Empty, hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Portal))); + args.AddParam("SkinPath", string.Empty, hostPage.ResolveUrl(resolver.Resolve("/", PathResolver.RelativeTo.Skin))); + liveDefinition.TemplateArguments.ForEach(a => args.AddParam(a.Name, string.Empty, a.Value)); - HttpContext.Current.Items["Resolver"] = resolver; + HttpContext.Current.Items["Resolver"] = resolver; - using (var xmlStream = new MemoryStream()) - { - Utilities.SerialiserFor(source.GetType()).Serialize(xmlStream, source); - xmlStream.Seek(0, SeekOrigin.Begin); - xsl.Transform(XmlReader.Create(xmlStream), args, htmlWriter); - } - } + using (var xmlStream = new MemoryStream()) + { + Utilities.SerialiserFor(source.GetType()).Serialize(xmlStream, source); + xmlStream.Seek(0, SeekOrigin.Begin); + this.xsl.Transform(XmlReader.Create(xmlStream), args, htmlWriter); + } + } - protected static string ConvertToJson(List options) - { - var result = new StringBuilder(); - result.Append("{"); + protected static string ConvertToJson(List options) + { + var result = new StringBuilder(); + result.Append("{"); - if (options != null) - { - foreach (var option in options) - { - if (option is ClientNumber) - { - result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToDecimal(option.Value))); - } - else if (option is ClientString) - { - result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(option.Value)); - } - else if (option is ClientBoolean) - { - result.AppendFormat( - "{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToBoolean(option.Value.ToLowerInvariant()))); - } - else - { - result.AppendFormat("{0}:{1},", option.Name, option.Value); - } - } - if (options.Count > 0) - { - result.Remove(result.Length - 1, 1); - } - } + if (options != null) + { + foreach (var option in options) + { + if (option is ClientNumber) + { + result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToDecimal(option.Value))); + } + else if (option is ClientString) + { + result.AppendFormat("{0}:{1},", option.Name, Utilities.ConvertToJs(option.Value)); + } + else if (option is ClientBoolean) + { + result.AppendFormat( + "{0}:{1},", option.Name, Utilities.ConvertToJs(Convert.ToBoolean(option.Value.ToLowerInvariant()))); + } + else + { + result.AppendFormat("{0}:{1},", option.Name, option.Value); + } + } + + if (options.Count > 0) + { + result.Remove(result.Length - 1, 1); + } + } - result.Append("}"); - return result.ToString(); - } - } + result.Append("}"); + return result.ToString(); + } + } } diff --git a/DNN Platform/Modules/DDRMenu/packages.config b/DNN Platform/Modules/DDRMenu/packages.config index 015e7e36813..4fca05e5f8c 100644 --- a/DNN Platform/Modules/DDRMenu/packages.config +++ b/DNN Platform/Modules/DDRMenu/packages.config @@ -1,5 +1,6 @@ - - - - + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/DigitalAssets/ClientDialog.cs b/DNN Platform/Modules/DigitalAssets/ClientDialog.cs index 4095ad095cf..412af1cf7b2 100644 --- a/DNN Platform/Modules/DigitalAssets/ClientDialog.cs +++ b/DNN Platform/Modules/DigitalAssets/ClientDialog.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Web.UI; + public static class ClientDialog { public static void CloseClientDialog(this Page page, bool refresh) diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs index bff1e48164e..ba6b3ccbd3a 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs @@ -1,47 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.ComponentModel.Composition; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; -using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; -using DotNetNuke.Modules.DigitalAssets.Services.Models; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Assets; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.EventArgs; -using DotNetNuke.Services.Upgrade; -using DotNetNuke.Web.UI; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.ComponentModel.Composition; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; + using DotNetNuke.Modules.DigitalAssets.Services.Models; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Assets; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.EventArgs; + using DotNetNuke.Services.Upgrade; + using DotNetNuke.Web.UI; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + [Export(typeof(IDigitalAssetsController))] [ExportMetadata("Edition", "CE")] public class DigitalAssetsController : IDigitalAssetsController, IUpgradeable { protected static readonly DigitalAssetsSettingsRepository SettingsRepository = new DigitalAssetsSettingsRepository(); - private static readonly Hashtable MappedPathsSupported = new Hashtable(); - #region Static Private Methods + private static readonly Hashtable MappedPathsSupported = new Hashtable(); + private static bool IsHostMenu { get @@ -49,6 +49,34 @@ private static bool IsHostMenu return Globals.IsHostTab(PortalSettings.Current.ActiveTab.TabID); } } + + public IEnumerable GetDefaultFolderProviderValues(int moduleId) + { + var portalId = this.GetCurrentPortalId(moduleId); + + return new List + { + FolderMappingController.Instance.GetFolderMapping(portalId, "Standard"), + FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"), + FolderMappingController.Instance.GetFolderMapping(portalId, "Database"), + }; + } + + public int? GetDefaultFolderTypeId(int moduleId) + { + if (PortalSettings.Current.UserInfo.IsSuperUser && SettingsRepository.GetMode(moduleId) == DigitalAssestsMode.User) + { + return null; + } + + var folderTypeId = SettingsRepository.GetDefaultFolderTypeId(moduleId); + if (!folderTypeId.HasValue) + { + folderTypeId = FolderMappingController.Instance.GetDefaultFolderMapping(this.GetCurrentPortalId(moduleId)).FolderMappingID; + } + + return folderTypeId; + } private static string GetFileIconUrl(string extension) { @@ -58,11 +86,8 @@ private static string GetFileIconUrl(string extension) } return IconController.IconURL("ExtFile", "32x32", "Standard"); - } - - #endregion - - #region Private Methods + } + private IFolderInfo GetFolderInfo(int folderId) { var folder = FolderManager.Instance.GetFolder(folderId); @@ -70,6 +95,7 @@ private IFolderInfo GetFolderInfo(int folderId) { throw new DotNetNukeException(LocalizationHelper.GetString("FolderDoesNotExists.Error")); } + return folder; } @@ -78,7 +104,7 @@ private IEnumerable GetPermissionViewModelCollection(IFolde // TODO Split permission between CE and PE packages string[] permissionKeys = { "ADD", "BROWSE", "COPY", "READ", "WRITE", "DELETE", "MANAGE", "VIEW", "FULLCONTROL" }; - return permissionKeys.Select(permissionKey => new PermissionViewModel { Key = permissionKey, Value = HasPermission(folder, permissionKey) }).ToList(); + return permissionKeys.Select(permissionKey => new PermissionViewModel { Key = permissionKey, Value = this.HasPermission(folder, permissionKey) }).ToList(); } private FolderMappingViewModel GetFolderMappingViewModel(FolderMappingInfo folderMapping) @@ -87,7 +113,7 @@ private FolderMappingViewModel GetFolderMappingViewModel(FolderMappingInfo folde { Id = folderMapping.FolderMappingID, FolderTypeName = folderMapping.FolderProviderType, - Name = folderMapping.MappingName + Name = folderMapping.MappingName, }; } @@ -139,11 +165,11 @@ private Field GetFileSizeField(IFileInfo file) private List GetFolderPreviewFields(IFolderInfo folder) { var fields = new List - { - GetFolderSizeField(folder), - GetTotalFilesField(folder) + { + this.GetFolderSizeField(folder), + this.GetTotalFilesField(folder), }; - fields.AddRange(GetAuditFields((FolderInfo)folder, folder.PortalID)); + fields.AddRange(this.GetAuditFields((FolderInfo)folder, folder.PortalID)); return fields; } @@ -151,10 +177,10 @@ private List GetFilePreviewFields(IFileInfo file) { var fields = new List { - GetFileKindField(file), - GetFileSizeField(file), + this.GetFileKindField(file), + this.GetFileSizeField(file), }; - fields.AddRange(GetAuditFields((FileInfo)file, file.PortalId)); + fields.AddRange(this.GetAuditFields((FileInfo)file, file.PortalId)); return fields; } @@ -163,35 +189,35 @@ private IEnumerable GetAuditFields(BaseEntityInfo item, int portalId) var createdByUser = item.CreatedByUser(portalId); var lastModifiedByUser = item.LastModifiedByUser(portalId); return new List - { + { new Field(DefaultMetadataNames.Created) { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Created + ".DisplayName"), - Type = typeof(DateTime), + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Created + ".DisplayName"), + Type = typeof(DateTime), Value = item.CreatedOnDate, - StringValue = item.CreatedOnDate.ToString(CultureInfo.CurrentCulture) + StringValue = item.CreatedOnDate.ToString(CultureInfo.CurrentCulture), }, - new Field(DefaultMetadataNames.CreatedBy) + new Field(DefaultMetadataNames.CreatedBy) { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.CreatedBy + ".DisplayName"), - Type = typeof(int), + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.CreatedBy + ".DisplayName"), + Type = typeof(int), Value = item.CreatedByUserID, - StringValue = createdByUser != null ? createdByUser.DisplayName : "" + StringValue = createdByUser != null ? createdByUser.DisplayName : string.Empty, }, - new Field(DefaultMetadataNames.Modified) + new Field(DefaultMetadataNames.Modified) { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Modified + ".DisplayName"), - Type = typeof(DateTime), + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Modified + ".DisplayName"), + Type = typeof(DateTime), Value = item.LastModifiedOnDate, - StringValue = item.LastModifiedOnDate.ToString(CultureInfo.CurrentCulture) + StringValue = item.LastModifiedOnDate.ToString(CultureInfo.CurrentCulture), }, - new Field(DefaultMetadataNames.ModifiedBy) + new Field(DefaultMetadataNames.ModifiedBy) { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.ModifiedBy + ".DisplayName"), - Type = typeof(int), + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.ModifiedBy + ".DisplayName"), + Type = typeof(int), Value = item.LastModifiedByUserID, - StringValue = lastModifiedByUser != null ? lastModifiedByUser.DisplayName : "" - } + StringValue = lastModifiedByUser != null ? lastModifiedByUser.DisplayName : string.Empty + }, }; } @@ -201,6 +227,7 @@ private bool AreMappedPathsSupported(int folderMappingId) { return (bool)MappedPathsSupported[folderMappingId]; } + var folderMapping = FolderMappingController.Instance.GetFolderMapping(folderMappingId); var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); var result = folderProvider.SupportsMappedPaths; @@ -210,49 +237,19 @@ private bool AreMappedPathsSupported(int folderMappingId) private string GetUnlinkAllowedStatus(IFolderInfo folder) { - if (AreMappedPathsSupported(folder.FolderMappingID) && folder.ParentID > 0 && GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID) + if (this.AreMappedPathsSupported(folder.FolderMappingID) && folder.ParentID > 0 && this.GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID) { return "onlyUnlink"; } - if (AreMappedPathsSupported(folder.FolderMappingID)) + + if (this.AreMappedPathsSupported(folder.FolderMappingID)) { return "true"; } + return "false"; - - } - #endregion - - #region Public Methods - - public IEnumerable GetDefaultFolderProviderValues(int moduleId) - { - var portalId = GetCurrentPortalId(moduleId); - - return new List - { - FolderMappingController.Instance.GetFolderMapping(portalId, "Standard"), - FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"), - FolderMappingController.Instance.GetFolderMapping(portalId, "Database") - }; - } - - public int? GetDefaultFolderTypeId(int moduleId) - { - if (PortalSettings.Current.UserInfo.IsSuperUser && SettingsRepository.GetMode(moduleId) == DigitalAssestsMode.User) - { - return null; - } - - var folderTypeId = SettingsRepository.GetDefaultFolderTypeId(moduleId); - if (!folderTypeId.HasValue) - { - folderTypeId = FolderMappingController.Instance.GetDefaultFolderMapping(GetCurrentPortalId(moduleId)).FolderMappingID; - } - return folderTypeId; - } - - + } + public int GetCurrentPortalId(int moduleId) { if (PortalSettings.Current.UserInfo.IsSuperUser) @@ -263,13 +260,13 @@ public int GetCurrentPortalId(int moduleId) } } - return IsHostMenu ? Null.NullInteger : PortalSettings.Current.PortalId; + return IsHostMenu ? Null.NullInteger : PortalSettings.Current.PortalId; } public IEnumerable GetFolderMappings(int moduleId) { var portalId = this.GetCurrentPortalId(moduleId); - return FolderMappingController.Instance.GetFolderMappings(portalId).Select(GetFolderMappingViewModel); + return FolderMappingController.Instance.GetFolderMappings(portalId).Select(this.GetFolderMappingViewModel); } public IEnumerable GetFolders(int moduleId, int folderId) @@ -280,14 +277,15 @@ public IEnumerable GetFolders(int moduleId, int folderId) return new List(); } - var folder = GetFolderInfo(folderId); + var folder = this.GetFolderInfo(folderId); if (!FolderPermissionController.CanBrowseFolder((FolderInfo)folder)) { - //The user cannot access the content + // The user cannot access the content return new List(); } - return AssetManager.Instance.GetFolders(folder, "FolderName", true).Select(GetFolderViewModel); + + return AssetManager.Instance.GetFolders(folder, "FolderName", true).Select(this.GetFolderViewModel); } public PageViewModel GetFolderContent(int moduleId, int folderId, int startIndex, int numItems, string sortExpression) @@ -296,19 +294,19 @@ public PageViewModel GetFolderContent(int moduleId, int folderId, int startIndex var page = AssetManager.Instance.GetFolderContent(folderId, startIndex, numItems, sortExpression, subfolderFilter); return new PageViewModel { - Folder = GetFolderViewModel(page.Folder), - Items = page.Items.Select(GetItemViewModel).ToList(), - TotalCount = page.TotalCount + Folder = this.GetFolderViewModel(page.Folder), + Items = page.Items.Select(this.GetItemViewModel).ToList(), + TotalCount = page.TotalCount, }; } public void SyncFolderContent(int folderId, bool recursive) { - var folder = GetFolderInfo(folderId); + var folder = this.GetFolderInfo(folderId); if (!FolderPermissionController.CanBrowseFolder((FolderInfo)folder)) { - //The user cannot access the content + // The user cannot access the content return; } @@ -322,15 +320,15 @@ public PageViewModel SearchFolderContent(int moduleId, int folderId, string patt return new PageViewModel { - Folder = GetFolderViewModel(page.Folder), - Items = page.Items.Select(GetItemViewModel).ToList(), - TotalCount = page.TotalCount + Folder = this.GetFolderViewModel(page.Folder), + Items = page.Items.Select(this.GetItemViewModel).ToList(), + TotalCount = page.TotalCount, }; } public FolderViewModel GetFolder(int folderID) { - return GetFolderViewModel(GetFolderInfo(folderID)); + return this.GetFolderViewModel(this.GetFolderInfo(folderID)); } public FolderViewModel GetRootFolder(int moduleId) @@ -347,7 +345,7 @@ public FolderViewModel GetRootFolder(int moduleId) } var portalId = this.GetCurrentPortalId(moduleId); - return this.GetFolderViewModel(FolderManager.Instance.GetFolder(portalId, "")); + return this.GetFolderViewModel(FolderManager.Instance.GetFolder(portalId, string.Empty)); } public FolderViewModel GetGroupFolder(int groupId, PortalSettings portalSettings) @@ -363,12 +361,24 @@ public FolderViewModel GetGroupFolder(int groupId, PortalSettings portalSettings return null; } - var groupFolder = EnsureGroupFolder(groupId, portalSettings); + var groupFolder = this.EnsureGroupFolder(groupId, portalSettings); var folderViewModel = this.GetFolderViewModel(groupFolder); folderViewModel.FolderName = role.RoleName; return folderViewModel; } + public FolderViewModel GetUserFolder(UserInfo userInfo) + { + var folder = this.GetFolderViewModel(FolderManager.Instance.GetUserFolder(userInfo)); + folder.FolderName = LocalizationHelper.GetString("MyFolder"); + return folder; + } + + public FolderViewModel CreateFolder(string folderName, int folderParentID, int folderMappingID, string mappedPath) + { + return this.GetFolderViewModel(AssetManager.Instance.CreateFolder(folderName, folderParentID, folderMappingID, mappedPath)); + } + private IFolderInfo EnsureGroupFolder(int groupId, PortalSettings portalSettings) { const int AllUsersRoleId = -1; @@ -378,7 +388,7 @@ private IFolderInfo EnsureGroupFolder(int groupId, PortalSettings portalSettings { var pc = new PermissionController(); var browsePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "BROWSE").Cast().FirstOrDefault(); - var readPermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "READ").Cast().FirstOrDefault(); + var readPermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "READ").Cast().FirstOrDefault(); var writePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "WRITE").Cast().FirstOrDefault(); if (!FolderManager.Instance.FolderExists(portalSettings.PortalId, "Groups")) @@ -402,34 +412,24 @@ private IFolderInfo EnsureGroupFolder(int groupId, PortalSettings portalSettings return groupFolder; } - return FolderManager.Instance.GetFolder(portalSettings.PortalId, groupFolderPath); - } - - public FolderViewModel GetUserFolder(UserInfo userInfo) - { - var folder = GetFolderViewModel(FolderManager.Instance.GetUserFolder(userInfo)); - folder.FolderName = LocalizationHelper.GetString("MyFolder"); - return folder; - } - - public FolderViewModel CreateFolder(string folderName, int folderParentID, int folderMappingID, string mappedPath) - { - return GetFolderViewModel(AssetManager.Instance.CreateFolder( folderName,folderParentID, folderMappingID, mappedPath)); + return FolderManager.Instance.GetFolder(portalSettings.PortalId, groupFolderPath); } public ItemViewModel GetFile(int fileID) { - return GetItemViewModel(FileManager.Instance.GetFile(fileID, true)); + return this.GetItemViewModel(FileManager.Instance.GetFile(fileID, true)); } public void UnlinkFolder(int folderID) { var folder = FolderManager.Instance.GetFolder(folderID); + // Check if user has appropiate permissions - if (!HasPermission(folder, "DELETE")) + if (!this.HasPermission(folder, "DELETE")) { throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToUnlinkFolder.Error")); } + FolderManager.Instance.UnlinkFolder(folder); } @@ -440,13 +440,15 @@ public int GetMappedSubFoldersCount(IEnumerable items, int po { return totalSubfoldersCount; } + var allFolders = FolderManager.Instance.GetFolders(portalID); - foreach (var item in items.Where(i => i.IsFolder && HasPermission(FolderManager.Instance.GetFolder(i.ItemID), "VIEW"))) + foreach (var item in items.Where(i => i.IsFolder && this.HasPermission(FolderManager.Instance.GetFolder(i.ItemID), "VIEW"))) { var folder = FolderManager.Instance.GetFolder(item.ItemID); var allSubFolders = allFolders.Where(f => f.FolderPath.StartsWith(folder.FolderPath)); - totalSubfoldersCount = totalSubfoldersCount + allSubFolders.Count(f => GetUnlinkAllowedStatus(f) == "onlyUnlink"); + totalSubfoldersCount = totalSubfoldersCount + allSubFolders.Count(f => this.GetUnlinkAllowedStatus(f) == "onlyUnlink"); } + return totalSubfoldersCount; } @@ -467,17 +469,17 @@ public IEnumerable DeleteItems(IEnumerable items) } } - return nonDeletedItems.Select(GetItemPathViewModel); + return nonDeletedItems.Select(this.GetItemPathViewModel); } public ItemViewModel RenameFile(int fileID, string newFileName) { - return GetItemViewModel(AssetManager.Instance.RenameFile(fileID, newFileName)); + return this.GetItemViewModel(AssetManager.Instance.RenameFile(fileID, newFileName)); } public FolderViewModel RenameFolder(int folderID, string newFolderName) { - return GetFolderViewModel(AssetManager.Instance.RenameFolder(folderID, newFolderName)); + return this.GetFolderViewModel(AssetManager.Instance.RenameFolder(folderID, newFolderName)); } public Stream GetFileContent(int fileId, out string fileName, out string contentType) @@ -485,7 +487,7 @@ public Stream GetFileContent(int fileId, out string fileName, out string content var file = FileManager.Instance.GetFile(fileId, true); var folder = FolderManager.Instance.GetFolder(file.FolderId); - if (!HasPermission(folder, "READ")) + if (!this.HasPermission(folder, "READ")) { throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToDownload.Error")); } @@ -494,11 +496,11 @@ public Stream GetFileContent(int fileId, out string fileName, out string content fileName = file.FileName; contentType = file.ContentType; - EventManager.Instance.OnFileDownloaded(new FileDownloadedEventArgs() - { - FileInfo = file, - UserId = UserController.Instance.GetCurrentUserInfo().UserID - }); + EventManager.Instance.OnFileDownloaded(new FileDownloadedEventArgs() + { + FileInfo = file, + UserId = UserController.Instance.GetCurrentUserInfo().UserID, + }); return content; } @@ -508,7 +510,7 @@ public CopyMoveItemViewModel CopyFile(int fileId, int destinationFolderId, bool var folder = FolderManager.Instance.GetFolder(destinationFolderId); var sourceFolder = FolderManager.Instance.GetFolder(file.FolderId); - if (!HasPermission(sourceFolder, "COPY")) + if (!this.HasPermission(sourceFolder, "COPY")) { throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToCopyFolder.Error")); } @@ -541,14 +543,14 @@ public CopyMoveItemViewModel MoveFile(int fileId, int destinationFolderId, bool var file = FileManager.Instance.GetFile(fileId, true); var folder = FolderManager.Instance.GetFolder(destinationFolderId); var sourceFolder = FolderManager.Instance.GetFolder(file.FolderId); - if (!HasPermission(sourceFolder, "COPY")) + if (!this.HasPermission(sourceFolder, "COPY")) { throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToMoveFolder.Error")); } if (file.FolderId == destinationFolderId) { - // User must not move files in the same folder + // User must not move files in the same folder throw new DotNetNukeException(LocalizationHelper.GetString("DestinationFolderCannotMatchSourceFolder.Error")); } @@ -563,8 +565,8 @@ public CopyMoveItemViewModel MoveFile(int fileId, int destinationFolderId, bool public CopyMoveItemViewModel MoveFolder(int folderId, int destinationFolderId, bool overwrite) { - var folder = GetFolderInfo(folderId); - if (!HasPermission(folder, "COPY")) + var folder = this.GetFolderInfo(folderId); + if (!this.HasPermission(folder, "COPY")) { throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToMoveFolder.Error")); } @@ -581,11 +583,12 @@ public string GetUrl(int fileId) if (file != null) { var folder = FolderManager.Instance.GetFolder(file.FolderId); - if (!HasPermission(folder, "READ")) + if (!this.HasPermission(folder, "READ")) { throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToDownload.Error")); } } + return FileManager.Instance.GetUrl(file); } @@ -616,8 +619,8 @@ public virtual PreviewInfoViewModel GetFolderPreviewInfo(IFolderInfo folder) Title = LocalizationHelper.GetString("PreviewPanelTitle.Text"), ItemId = folder.FolderID, IsFolder = true, - PreviewImageUrl = GetFolderIconUrl(folder.PortalID, folder.FolderMappingID), - Fields = GetFolderPreviewFields(folder) + PreviewImageUrl = this.GetFolderIconUrl(folder.PortalID, folder.FolderMappingID), + Fields = this.GetFolderPreviewFields(folder), }; } @@ -629,27 +632,25 @@ public virtual PreviewInfoViewModel GetFilePreviewInfo(IFileInfo file, ItemViewM ItemId = file.FileId, IsFolder = false, PreviewImageUrl = item.IconUrl, - Fields = GetFilePreviewFields(file) + Fields = this.GetFilePreviewFields(file), }; return result; } - + public ZipExtractViewModel UnzipFile(int fileId, bool overwrite) { var file = FileManager.Instance.GetFile(fileId, true); var destinationFolder = FolderManager.Instance.GetFolder(file.FolderId); var invalidFiles = new List(); var filesCount = FileManager.Instance.UnzipFile(file, destinationFolder, invalidFiles); - return new ZipExtractViewModel() { Ok = true, InvalidFiles = invalidFiles, TotalCount = filesCount}; + return new ZipExtractViewModel() { Ok = true, InvalidFiles = invalidFiles, TotalCount = filesCount }; } public virtual int GetInitialTab(NameValueCollection requestParams, NameValueCollection damState) { - return 0; //Always - } - #endregion - - #region Protected Methods + return 0; // Always + } + public bool HasPermission(IFolderInfo folder, string permissionKey) { var hasPermision = PortalSettings.Current.UserInfo.IsSuperUser; @@ -661,6 +662,57 @@ public bool HasPermission(IFolderInfo folder, string permissionKey) return hasPermision; } + + public string UpgradeModule(string version) + { + try + { + switch (version) + { + case "07.01.00": + ModuleDefinitionInfo mDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Digital Asset Management"); + + // Add tab to Admin Menu + if (mDef != null) + { + var hostPage = Upgrade.AddHostPage( + "File Management", + "Manage assets.", + "~/Icons/Sigma/Files_16X16_Standard.png", + "~/Icons/Sigma/Files_32X32_Standard.png", + true); + + // Add module to page + Upgrade.AddModuleToPage(hostPage, mDef.ModuleDefID, "File Management", "~/Icons/Sigma/Files_32X32_Standard.png", true); + + Upgrade.AddAdminPages( + "File Management", + "Manage assets within the portal", + "~/Icons/Sigma/Files_16X16_Standard.png", + "~/Icons/Sigma/Files_32X32_Standard.png", + true, + mDef.ModuleDefID, + "File Management", + "~/Icons/Sigma/Files_16X16_Standard.png", + true); + } + + // Remove Host File Manager page + Upgrade.RemoveHostPage("File Manager"); + + // Remove Admin File Manager Pages + Upgrade.RemoveAdminPages("//Admin//FileManager"); + + break; + } + + return "Success"; + } + catch (Exception) + { + return "Failed"; + } + } protected ItemPathViewModel GetItemPathViewModel(IFolderInfo folder) { @@ -669,7 +721,7 @@ protected ItemPathViewModel GetItemPathViewModel(IFolderInfo folder) IsFolder = true, ItemID = folder.FolderID, DisplayPath = folder.DisplayPath, - IconUrl = GetFolderIconUrl(folder.PortalID, folder.FolderMappingID) + IconUrl = this.GetFolderIconUrl(folder.PortalID, folder.FolderMappingID), }; } @@ -680,10 +732,10 @@ protected ItemPathViewModel GetItemPathViewModel(IFileInfo file) IsFolder = false, ItemID = file.FileId, DisplayPath = file.RelativePath, - IconUrl = GetFileIconUrl(file.Extension) + IconUrl = GetFileIconUrl(file.Extension), }; } - + protected virtual FolderViewModel GetFolderViewModel(IFolderInfo folder) { var folderName = string.IsNullOrEmpty(folder.FolderName) @@ -698,23 +750,14 @@ protected virtual FolderViewModel GetFolderViewModel(IFolderInfo folder) FolderPath = folder.FolderPath, PortalID = folder.PortalID, LastModifiedOnDate = folder.LastModifiedOnDate.ToString("g"), - IconUrl = GetFolderIconUrl(folder.PortalID, folder.FolderMappingID), - Permissions = GetPermissionViewModelCollection(folder), - HasChildren = folder.HasChildren + IconUrl = this.GetFolderIconUrl(folder.PortalID, folder.FolderMappingID), + Permissions = this.GetPermissionViewModelCollection(folder), + HasChildren = folder.HasChildren, }; - folderViewModel.Attributes.Add(new KeyValuePair("UnlinkAllowedStatus", GetUnlinkAllowedStatus(folder))); + folderViewModel.Attributes.Add(new KeyValuePair("UnlinkAllowedStatus", this.GetUnlinkAllowedStatus(folder))); return folderViewModel; } - private ItemViewModel GetItemViewModel(object item) - { - var folder = item as IFolderInfo; - if (folder != null) return GetItemViewModel(folder); - - var file = item as IFileInfo; - return GetItemViewModel(file); - } - protected virtual ItemViewModel GetItemViewModel(IFolderInfo folder) { var parentFolderId = Null.NullInteger; @@ -734,15 +777,15 @@ protected virtual ItemViewModel GetItemViewModel(IFolderInfo folder) ItemName = folder.FolderName, LastModifiedOnDate = folder.LastModifiedOnDate.ToString("g"), PortalID = folder.PortalID, - IconUrl = GetFolderIconUrl(folder.PortalID, folder.FolderMappingID), - Permissions = GetPermissionViewModelCollection(folder), + IconUrl = this.GetFolderIconUrl(folder.PortalID, folder.FolderMappingID), + Permissions = this.GetPermissionViewModelCollection(folder), ParentFolderID = parentFolderId, ParentFolder = parentFolderPath, FolderMappingID = folder.FolderMappingID, - UnlinkAllowedStatus = GetUnlinkAllowedStatus(folder) + UnlinkAllowedStatus = this.GetUnlinkAllowedStatus(folder), }; } - + protected virtual ItemViewModel GetItemViewModel(IFileInfo file) { var folder = FolderManager.Instance.GetFolder(file.FolderId); @@ -754,14 +797,26 @@ protected virtual ItemViewModel GetItemViewModel(IFileInfo file) LastModifiedOnDate = file.LastModifiedOnDate.ToString("g"), PortalID = file.PortalId, IconUrl = GetFileIconUrl(file.Extension), - Permissions = GetPermissionViewModelCollection(folder), + Permissions = this.GetPermissionViewModelCollection(folder), ParentFolderID = folder.FolderID, ParentFolder = folder.FolderPath, Size = string.Format(new FileSizeFormatProvider(), "{0:fs}", file.Size), - UnlinkAllowedStatus = "false" + UnlinkAllowedStatus = "false", }; } + private ItemViewModel GetItemViewModel(object item) + { + var folder = item as IFolderInfo; + if (folder != null) + { + return this.GetItemViewModel(folder); + } + + var file = item as IFileInfo; + return this.GetItemViewModel(file); + } + protected string GetFolderIconUrl(int portalId, int folderMappingID) { var imageUrl = IconController.IconURL("ExtClosedFolder", "32x32", "Standard"); @@ -773,56 +828,6 @@ protected string GetFolderIconUrl(int portalId, int folderMappingID) } return imageUrl; - } - - #endregion - - public string UpgradeModule(string version) - { - try - { - switch (version) - { - case "07.01.00": - ModuleDefinitionInfo mDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Digital Asset Management"); - - //Add tab to Admin Menu - if (mDef != null) - { - var hostPage = Upgrade.AddHostPage("File Management", - "Manage assets.", - "~/Icons/Sigma/Files_16X16_Standard.png", - "~/Icons/Sigma/Files_32X32_Standard.png", - true); - - //Add module to page - Upgrade.AddModuleToPage(hostPage, mDef.ModuleDefID, "File Management", "~/Icons/Sigma/Files_32X32_Standard.png", true); - - Upgrade.AddAdminPages("File Management", - "Manage assets within the portal", - "~/Icons/Sigma/Files_16X16_Standard.png", - "~/Icons/Sigma/Files_32X32_Standard.png", - true, - mDef.ModuleDefID, - "File Management", - "~/Icons/Sigma/Files_16X16_Standard.png", - true); - } - - //Remove Host File Manager page - Upgrade.RemoveHostPage("File Manager"); - - //Remove Admin File Manager Pages - Upgrade.RemoveAdminPages("//Admin//FileManager"); - - break; - } - return "Success"; - } - catch (Exception) - { - return "Failed"; - } - } + } } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs index c14993a9762..0e82983c477 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs @@ -1,16 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Assets; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers { + using System; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Assets; + + public enum DigitalAssestsMode + { + Normal, + Group, + User, + } + + public enum FilterCondition + { + NotSet, + FilterByFolder, + } + public class DigitalAssetsSettingsRepository { private const string DefaultFolderTypeIdSetting = "DefaultFolderTypeId"; @@ -48,7 +61,7 @@ public DigitalAssestsMode GetMode(int moduleId) { DigitalAssestsMode mode; - if (!Enum.TryParse(GetSettingByKey(moduleId, ModeSetting), true, out mode)) + if (!Enum.TryParse(this.GetSettingByKey(moduleId, ModeSetting), true, out mode)) { return this.IsGroupMode(moduleId) ? DigitalAssestsMode.Group : DigitalAssestsMode.Normal; } @@ -56,18 +69,6 @@ public DigitalAssestsMode GetMode(int moduleId) return mode; } - private bool IsGroupMode(int moduleId) - { - var groupMode = this.GetSettingByKey(moduleId, GroupModeSetting); - - if (string.IsNullOrEmpty(groupMode)) - { - return false; - } - - return Convert.ToBoolean(groupMode); - } - public FilterCondition GetFilterCondition(int moduleId) { var setting = this.GetSettingByKey(moduleId, FilterConditionSetting); @@ -81,10 +82,22 @@ public SubfolderFilter GetSubfolderFilter(int moduleId) SubfolderFilter excludeSubfolders; return !Enum.TryParse(setting, true, out excludeSubfolders) ? SubfolderFilter.IncludeSubfoldersFolderStructure : excludeSubfolders; } - + + private bool IsGroupMode(int moduleId) + { + var groupMode = this.GetSettingByKey(moduleId, GroupModeSetting); + + if (string.IsNullOrEmpty(groupMode)) + { + return false; + } + + return Convert.ToBoolean(groupMode); + } + public void SaveDefaultFolderTypeId(int moduleId, int defaultFolderTypeId) { - ModuleController.Instance.UpdateModuleSetting(moduleId, DefaultFolderTypeIdSetting, defaultFolderTypeId.ToString(CultureInfo.InvariantCulture)); + ModuleController.Instance.UpdateModuleSetting(moduleId, DefaultFolderTypeIdSetting, defaultFolderTypeId.ToString(CultureInfo.InvariantCulture)); } public void SaveMode(int moduleId, DigitalAssestsMode mode) @@ -107,36 +120,25 @@ public void SaveFilterCondition(int moduleId, FilterCondition filterCondition) ModuleController.Instance.UpdateModuleSetting(moduleId, FilterConditionSetting, filterCondition.ToString()); } - private string GetSettingByKey(int moduleId, string key) - { - var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - var moduleSettings = module.ModuleSettings; - return (string)moduleSettings[key]; - } - internal bool SettingExists(int moduleId, string settingName) { - return !String.IsNullOrEmpty(GetSettingByKey(moduleId, settingName)); + return !string.IsNullOrEmpty(this.GetSettingByKey(moduleId, settingName)); } internal void SetDefaultFilterCondition(int moduleId) { - //handle upgrades where FilterCondition didn't exist - if (this.SettingExists(moduleId, "RootFolderId") && !this.SettingExists(moduleId, "FilterCondition")) - this.SaveFilterCondition(moduleId, FilterCondition.FilterByFolder); + // handle upgrades where FilterCondition didn't exist + if (this.SettingExists(moduleId, "RootFolderId") && !this.SettingExists(moduleId, "FilterCondition")) + { + this.SaveFilterCondition(moduleId, FilterCondition.FilterByFolder); + } } - } - - public enum DigitalAssestsMode - { - Normal, - Group, - User - } - public enum FilterCondition - { - NotSet, - FilterByFolder + private string GetSettingByKey(int moduleId, string key) + { + var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); + var moduleSettings = module.ModuleSettings; + return (string)moduleSettings[key]; + } } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs index 6dc9b25cf48..3231ef00325 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs @@ -1,32 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Collections.Specialized; -using System.IO; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; -using DotNetNuke.Modules.DigitalAssets.Services.Models; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers { + using System.Collections.Generic; + using System.Collections.Specialized; + using System.IO; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + using DotNetNuke.Modules.DigitalAssets.Services.Models; + using DotNetNuke.Services.FileSystem; + public interface IDigitalAssetsController { /// - /// Gets the list of the Folder Mappings. This list depends on the configuration of the module instanced + /// Gets the list of the Folder Mappings. This list depends on the configuration of the module instanced. /// - /// The Id of the module - /// The list of Folder Mappings + /// The Id of the module. + /// The list of Folder Mappings. IEnumerable GetFolderMappings(int moduleId); /// /// Gets the list of subfolders for the specified folder. /// - /// The Id of the module + /// The Id of the module. /// The folderItemId of the folder to get the list of subfolders. /// The list of subfolders for the specified folder. IEnumerable GetFolders(int moduleId, int parentFolderId); @@ -48,12 +48,12 @@ public interface IDigitalAssetsController /// /// Gets the root folder of the current Portal. This folder depends on the configuration of the module. /// - /// The Id of the module + /// The Id of the module. /// The root folderItem entity. FolderViewModel GetRootFolder(int moduleId); /// - /// Gets the group folder + /// Gets the group folder. /// /// The identifier of the group. /// The current portal settings. @@ -61,7 +61,7 @@ public interface IDigitalAssetsController FolderViewModel GetGroupFolder(int groupId, PortalSettings portalSettings); /// - /// Gets the user folder + /// Gets the user folder. /// /// The current user. /// The user folderItem entity. @@ -70,195 +70,196 @@ public interface IDigitalAssetsController /// /// Gets the files and folders contained in the specified folder. /// - /// The id of the Module - /// Folder Identifier - /// Start index to retrieve items - /// Max Number of items - /// The sort expression in a SQL format, e.g. FileName ASC - /// The list of files and folders contained in the specified folder paginated + /// The id of the Module. + /// Folder Identifier. + /// Start index to retrieve items. + /// Max Number of items. + /// The sort expression in a SQL format, e.g. FileName ASC. + /// The list of files and folders contained in the specified folder paginated. PageViewModel GetFolderContent(int moduleId, int folderId, int startIndex, int numItems, string sortExpression); /// /// Searches the files and folders contained in the specified folder. /// - /// The id of the Module - /// Folder Identifier - /// The pattern to search for - /// Start index to retrieve items - /// Max Number of items - /// The sort expression in a SQL format, e.g. FileName ASC - /// The list of files and folders contained in the specified folder paginated + /// The id of the Module. + /// Folder Identifier. + /// The pattern to search for. + /// Start index to retrieve items. + /// Max Number of items. + /// The sort expression in a SQL format, e.g. FileName ASC. + /// The list of files and folders contained in the specified folder paginated. PageViewModel SearchFolderContent(int moduleId, int folderId, string pattern, int startIndex, int numItems, string sortExpression); /// - /// Synchronize a folder within the File System + /// Synchronize a folder within the File System. /// - /// Reference to the folder is going to be synchronized - /// Indicates if subfolders are going to be synchronized + /// Reference to the folder is going to be synchronized. + /// Indicates if subfolders are going to be synchronized. void SyncFolderContent(int folderId, bool recursive); /// /// Gets a newly created folder. /// - /// folderName is the name of the new folder - /// The reference to the parent folder where the new folder will be create - /// folderMappingID is the mapping related with the new folder - /// mappedPath used for the mapping to folder in remove provider - /// The newly folder created under the specified parent folder + /// folderName is the name of the new folder. + /// The reference to the parent folder where the new folder will be create. + /// folderMappingID is the mapping related with the new folder. + /// mappedPath used for the mapping to folder in remove provider. + /// The newly folder created under the specified parent folder. FolderViewModel CreateFolder(string folderName, int folderParentID, int folderMappingID, string mappedPath); /// /// Renames a existing folder. /// - /// Folder reference to rename - /// The new name to set to the folder - /// The final moved folder + /// Folder reference to rename. + /// The new name to set to the folder. + /// The final moved folder. FolderViewModel RenameFolder(int folderID, string newFolderName); /// - /// Deletes a collection of items (folder and/or files) + /// Deletes a collection of items (folder and/or files). /// - /// Items list - /// all the items belong at the same Folder - /// The non deleted item list. The files / subfolders for which the user has no permissions to delete + /// Items list. + /// all the items belong at the same Folder. + /// The non deleted item list. The files / subfolders for which the user has no permissions to delete. IEnumerable DeleteItems(IEnumerable items); /// - /// Unlinks a specified folder + /// Unlinks a specified folder. /// - /// The folder ID to be unlinked + /// The folder ID to be unlinked. void UnlinkFolder(int folderID); /// - /// Get the number of subfolders which support Mapped Path + /// Get the number of subfolders which support Mapped Path. /// - /// Items list - /// Portal ID + /// Items list. + /// Portal ID. + /// int GetMappedSubFoldersCount(IEnumerable items, int portalID); /// /// Renames a existing file. /// - /// File reference to rename - /// The new name to set to the file - /// The final renamed file + /// File reference to rename. + /// The new name to set to the file. + /// The final renamed file. ItemViewModel RenameFile(int fileID, string newFileName); /// - /// Get the content of a file, ready to download + /// Get the content of a file, ready to download. /// - /// File reference to the source file - /// Returns the name of the file - /// Returns the content type of the file - /// The file content + /// File reference to the source file. + /// Returns the name of the file. + /// Returns the content type of the file. + /// The file content. Stream GetFileContent(int fileId, out string fileName, out string contentType); /// - /// Copies a file to the destination folder + /// Copies a file to the destination folder. /// - /// File reference to the source file - /// Folder reference to the destination folder - /// Overwrite destination if a file with the same name already exists - /// The response object with the result of the action + /// File reference to the source file. + /// Folder reference to the destination folder. + /// Overwrite destination if a file with the same name already exists. + /// The response object with the result of the action. CopyMoveItemViewModel CopyFile(int fileId, int destinationFolderId, bool overwrite); /// - /// Moves a file to the destination folder + /// Moves a file to the destination folder. /// - /// File reference to the source file - /// Folder reference to the destination folder - /// Overwrite destination if a file with the same name already exists - /// The response object with the result of the action + /// File reference to the source file. + /// Folder reference to the destination folder. + /// Overwrite destination if a file with the same name already exists. + /// The response object with the result of the action. CopyMoveItemViewModel MoveFile(int fileId, int destinationFolderId, bool overwrite); /// - /// Moves a Folder to the destination folder + /// Moves a Folder to the destination folder. /// - /// Folder reference to the source file - /// Folder reference to the destination folder - /// Overwrite destination if a file with the same name already exists - /// The response object with the result of the action + /// Folder reference to the source file. + /// Folder reference to the destination folder. + /// Overwrite destination if a file with the same name already exists. + /// The response object with the result of the action. CopyMoveItemViewModel MoveFolder(int folderId, int destinationFolderId, bool overwrite); /// /// Extracts the files and folders contained in the specified zip file to the specified folder. /// - /// File reference to the source file - /// Overwrite destination if a file with the same name already exists - /// The response object with the result of the action - ZipExtractViewModel UnzipFile(int fileId, bool overwrite); - + /// File reference to the source file. + /// Overwrite destination if a file with the same name already exists. + /// The response object with the result of the action. + ZipExtractViewModel UnzipFile(int fileId, bool overwrite); + /// - /// Returns all invalid chars for folder and file names + /// Returns all invalid chars for folder and file names. /// - /// A string that includes all invalid chars + /// A string that includes all invalid chars. string GetInvalidChars(); /// - /// Returns the error text when a name contains an invalid character + /// Returns the error text when a name contains an invalid character. /// - /// The error text to show when a name contains an invalid character + /// The error text to show when a name contains an invalid character. string GetInvalidCharsErrorText(); - + /// - /// Get the URL of a file + /// Get the URL of a file. /// - /// File reference to the source file - /// The URL of the file + /// File reference to the source file. + /// The URL of the file. string GetUrl(int fileId); /// - /// Returns a fields set. These fields define the Folder preview info + /// Returns a fields set. These fields define the Folder preview info. /// - /// The folder model - /// The Preview info object + /// The folder model. + /// The Preview info object. PreviewInfoViewModel GetFolderPreviewInfo(IFolderInfo folder); /// - /// Returns a fields set. These fields define the File preview info + /// Returns a fields set. These fields define the File preview info. /// - /// The file - /// The file model - /// The Preview info object + /// The file. + /// The file model. + /// The Preview info object. PreviewInfoViewModel GetFilePreviewInfo(IFileInfo file, ItemViewModel item); /// /// Get the list of the default FolderMappings, i.e.: Standard/Database/Secure, associated to the module instance. /// This depends on the configuration of the module. /// - /// The id of the Module - /// The list of default FolderMappingInfo associated + /// The id of the Module. + /// The list of default FolderMappingInfo associated. IEnumerable GetDefaultFolderProviderValues(int moduleId); /// /// Get the default FolderTypeId to use when creating new folders under the root folder. - /// This depends on the module configuration + /// This depends on the module configuration. /// - /// The Id of the module - /// The default FolderTypeId + /// The Id of the module. + /// The default FolderTypeId. int? GetDefaultFolderTypeId(int moduleId); /// - /// Gets the current Portal Id. This id depends on the configuration of the module + /// Gets the current Portal Id. This id depends on the configuration of the module. /// - /// The Id of the module - /// The id of the current portal + /// The Id of the module. + /// The id of the current portal. int GetCurrentPortalId(int moduleId); /// - /// Check if the current user has the specified permission over the specified folder + /// Check if the current user has the specified permission over the specified folder. /// - /// The folder to check - /// The permission to check - /// Returns TRUE if the current user has the specified permission over the specified folder. FALSE otherwise + /// The folder to check. + /// The permission to check. + /// Returns TRUE if the current user has the specified permission over the specified folder. FALSE otherwise. bool HasPermission(IFolderInfo folder, string permissionKey); /// - /// Get the index of the inital tab to be shown when module is loaded + /// Get the index of the inital tab to be shown when module is loaded. /// - /// Request parameters collection - /// Module State values collection - /// The index to the tab to be shown + /// Request parameters collection. + /// Module State values collection. + /// The index to the tab to be shown. int GetInitialTab(NameValueCollection requestParams, NameValueCollection damState); } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsControllerData.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsControllerData.cs index 3444d7a52a2..78753b03414 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsControllerData.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsControllerData.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers { public interface IDigitalAssetsControllerData diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/CopyMoveItemViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/CopyMoveItemViewModel.cs index fece0a73fda..3829143cdb9 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/CopyMoveItemViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/CopyMoveItemViewModel.cs @@ -1,9 +1,9 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models -{ +{ public class CopyMoveItemViewModel { public bool AlreadyExists { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ExtractedItemViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ExtractedItemViewModel.cs index 95326ea558c..c56841fb92a 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ExtractedItemViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ExtractedItemViewModel.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System; + public class ExtractedItemViewModel { public string Name { get; internal set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/Field.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/Field.cs index ae4d66f1175..06eda55487a 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/Field.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/Field.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System; + public class Field { public Field(string name) { - Name = name; + this.Name = name; } public string Name { get; private set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderMappingViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderMappingViewModel.cs index 7cd9793388a..f41168a3658 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderMappingViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderMappingViewModel.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System; + public class FolderMappingViewModel { public int Id { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderViewModel.cs index 52b71d03683..668282d2ac1 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/FolderViewModel.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System.Collections.Generic; + public class FolderViewModel { public FolderViewModel() { - Attributes = new List>(); + this.Attributes = new List>(); } - + public int FolderID { get; set; } public int FolderMappingID { get; set; } @@ -31,6 +31,6 @@ public FolderViewModel() public IEnumerable Permissions { get; set; } - public IList> Attributes { get; set; } + public IList> Attributes { get; set; } } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemBaseViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemBaseViewModel.cs index 11fa42a570d..0903a74229d 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemBaseViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemBaseViewModel.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { public class ItemBaseViewModel diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemPathViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemPathViewModel.cs index 02bd6951693..f636c903df8 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemPathViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemPathViewModel.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { public class ItemPathViewModel : ItemBaseViewModel diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemViewModel.cs index 70665a02a4d..06b84789552 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ItemViewModel.cs @@ -1,26 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System; + using System.Collections.Generic; + public class ItemViewModel : ItemBaseViewModel { public string ItemName { get; set; } - + public string IconUrl { get; set; } - + public string DisplayName { get; set; } public string LastModifiedOnDate { get; set; } - + public int PortalID { get; set; } public IEnumerable Permissions { get; set; } - + public string ParentFolder { get; set; } public int ParentFolderID { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PageViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PageViewModel.cs index 66241d23fba..f4fac81b249 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PageViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PageViewModel.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System.Collections.Generic; + public class PageViewModel { public FolderViewModel Folder { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PermissionViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PermissionViewModel.cs index 10cec9e9bab..b0e8cb9ab49 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PermissionViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PermissionViewModel.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System; + public class PermissionViewModel { public string Key { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PreviewInfoViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PreviewInfoViewModel.cs index dc1cfab2ee8..8878977a644 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PreviewInfoViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/PreviewInfoViewModel.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System; + using System.Collections.Generic; + public class PreviewInfoViewModel { public string Title; diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ZipExtractViewModel.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ZipExtractViewModel.cs index 008b64a0a44..bcc6142e2bb 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ZipExtractViewModel.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/Models/ZipExtractViewModel.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models { + using System; + using System.Collections.Generic; + public class ZipExtractViewModel { public bool Ok { get; internal set; } @@ -15,7 +15,7 @@ public class ZipExtractViewModel public ICollection Items { get; internal set; } - public IList InvalidFiles { get; set; } + public IList InvalidFiles { get; set; } public int TotalCount { get; set; } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/IFieldsControl.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/IFieldsControl.cs index 8dc29bd91ec..d0567ca9321 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/IFieldsControl.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/IFieldsControl.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint { + using System; + + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + public interface IFieldsControl { IDigitalAssetsController Controller { get; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/LocalizationHelper.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/LocalizationHelper.cs index 7af309525d1..92a9c02470b 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/LocalizationHelper.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/LocalizationHelper.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint { + using System; + + using DotNetNuke.Services.Localization; + public class LocalizationHelper { private const string ResourceFile = "DesktopModules/DigitalAssets/App_LocalResources/SharedResources"; diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/PropertiesTabContentControl.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/PropertiesTabContentControl.cs index 920bb73c706..2b262857ecd 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/PropertiesTabContentControl.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/PropertiesTabContentControl.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint { + using System; + + using DotNetNuke.Entities.Modules; + public class PropertiesTabContentControl : PortalModuleBase { public delegate void ItemUpdatedHandler(); @@ -16,14 +16,14 @@ public class PropertiesTabContentControl : PortalModuleBase public virtual void ItemUpdated() { - if (OnItemUpdated != null) + if (this.OnItemUpdated != null) { - OnItemUpdated(); + this.OnItemUpdated(); } } public virtual void DataBindItem() - { - } + { + } } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CopyToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CopyToolBarButtonExtensionPoint.cs index 33e43a7fe25..2537a3faae7 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CopyToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CopyToolBarButtonExtensionPoint.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CreateFolderToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CreateFolderToolBarButtonExtensionPoint.cs index 4d1d947c735..cf01c3669de 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CreateFolderToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/CreateFolderToolBarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs index 7a523783b48..a8ceec9cb68 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs @@ -1,29 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { + using System; + + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + public class DefaultMenuButtonItem : IMenuButtonItemExtensionPoint - { - #region Private fields - - #endregion - + { public DefaultMenuButtonItem(string itemId, string itemType, string itemCssClass, string itemText, string itemAction, string itemIcon, int itemOrder, string itemAttributes) { - ItemId = itemId; - Attributes = itemAttributes; - Type = itemType; - Text = itemText; - Icon = itemIcon; - Order = itemOrder; - CssClass = itemCssClass; - Action = itemAction; + this.ItemId = itemId; + this.Attributes = itemAttributes; + this.Type = itemType; + this.Text = itemText; + this.Icon = itemIcon; + this.Order = itemOrder; + this.CssClass = itemCssClass; + this.Action = itemAction; } public string ItemId { get; private set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DeleteToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DeleteToolBarButtonExtensionPoint.cs index 6beaa144d13..05e1e8e7332 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DeleteToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DeleteToolBarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DownloadToolbarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DownloadToolbarButtonExtensionPoint.cs index fbe4e41bade..2bf9fcb4c7c 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DownloadToolbarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DownloadToolbarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GetUrlToolbarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GetUrlToolbarButtonExtensionPoint.cs index 098bf22fdff..feb16380a93 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GetUrlToolbarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GetUrlToolbarButtonExtensionPoint.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GridViewToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GridViewToolBarButtonExtensionPoint.cs index 49280dff498..83ee0333962 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GridViewToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/GridViewToolBarButtonExtensionPoint.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ListViewToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ListViewToolBarButtonExtensionPoint.cs index 23df313aca1..50ecbb9af88 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ListViewToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ListViewToolBarButtonExtensionPoint.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs index 40b1236049a..9a5a53cfbb9 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Portals; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.Security.Permissions; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Portals; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.Security.Permissions; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] @@ -35,19 +35,19 @@ public string Action { get { - if (ModuleContext == null) + if (this.ModuleContext == null) { return string.Empty; } - if (PortalSettings.Current.EnablePopUps) - { - return ModuleContext.EditUrl("FolderMappings"); - } - else - { - return string.Format("location.href = '{0}';", ModuleContext.EditUrl("FolderMappings")); - } + if (PortalSettings.Current.EnablePopUps) + { + return this.ModuleContext.EditUrl("FolderMappings"); + } + else + { + return string.Format("location.href = '{0}';", this.ModuleContext.EditUrl("FolderMappings")); + } } } @@ -83,8 +83,11 @@ public int Order public bool Enabled { - get { return ModuleContext != null - && ModulePermissionController.CanManageModule(ModuleContext.Configuration); } + get + { + return this.ModuleContext != null + && ModulePermissionController.CanManageModule(this.ModuleContext.Configuration); + } } public ModuleInstanceContext ModuleContext { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/MoveToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/MoveToolBarButtonExtensionPoint.cs index eb68c801fe9..fa21f97a480 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/MoveToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/MoveToolBarButtonExtensionPoint.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/RenameToolbarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/RenameToolbarButtonExtensionPoint.cs index 77f50332d6a..75ddbd0ecd0 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/RenameToolbarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/RenameToolbarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsRenameToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarButtonExtensionPoint.cs index a0725cac752..0b0acd24c49 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarMenuButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarMenuButtonExtensionPoint.cs index dc969e1fdb8..432c6d07a6a 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarMenuButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/SyncToolBarMenuButtonExtensionPoint.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; - -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { + using System; + using System.Collections.Generic; + using System.ComponentModel.Composition; + + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarSyncMenuButton")] @@ -20,14 +20,14 @@ public class SyncToolBarMenuButtonExtensionPoint : IToolBarMenuButtonExtensionPo { public List Items { - get - { + get + { return new List { - new DefaultMenuButtonItem("Refresh", "", "first permission_READ permission_BROWSE", LocalizationHelper.GetString("RefreshMenuItemExtensionPoint.Text"), "dnnModule.digitalAssets.refresFolderFromMenu()", "", 0, ""), - new DefaultMenuButtonItem("Sync", "", "medium permission_MANAGE permission_WRITE", LocalizationHelper.GetString("SyncMenuItemExtensionPoint.Text"), "dnnModule.digitalAssets.syncFromMenu(false)", "", 0, ""), - new DefaultMenuButtonItem("SyncRecursively", "", "last permission_MANAGE permission_WRITE", LocalizationHelper.GetString("SyncRecursivelyMenuItemExtensionPoint.Text"), "dnnModule.digitalAssets.syncFromMenu(true)", "", 0, "") - }; + new DefaultMenuButtonItem("Refresh", string.Empty, "first permission_READ permission_BROWSE", LocalizationHelper.GetString("RefreshMenuItemExtensionPoint.Text"), "dnnModule.digitalAssets.refresFolderFromMenu()", string.Empty, 0, string.Empty), + new DefaultMenuButtonItem("Sync", string.Empty, "medium permission_MANAGE permission_WRITE", LocalizationHelper.GetString("SyncMenuItemExtensionPoint.Text"), "dnnModule.digitalAssets.syncFromMenu(false)", string.Empty, 0, string.Empty), + new DefaultMenuButtonItem("SyncRecursively", string.Empty, "last permission_MANAGE permission_WRITE", LocalizationHelper.GetString("SyncRecursivelyMenuItemExtensionPoint.Text"), "dnnModule.digitalAssets.syncFromMenu(true)", string.Empty, 0, string.Empty), + }; } } @@ -107,7 +107,7 @@ public int Order { get { - return 5; + return 5; } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ToggleLeftPaneToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ToggleLeftPaneToolBarButtonExtensionPoint.cs index 55bd6e2405f..a8c00315f3e 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ToggleLeftPaneToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ToggleLeftPaneToolBarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnlinkToolbarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnlinkToolbarButtonExtensionPoint.cs index a158bad538d..1502eedfc90 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnlinkToolbarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnlinkToolbarButtonExtensionPoint.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsUnlinkToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnzipFileToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnzipFileToolBarButtonExtensionPoint.cs index f8ce0541cbf..d64fbd54278 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnzipFileToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UnzipFileToolBarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsUnzipFileToolBarButton")] @@ -58,8 +58,8 @@ public string Icon { get { - return IconController.IconURL("Unzip", "16x16", "Gray"); - } + return IconController.IconURL("Unzip", "16x16", "Gray"); + } } public int Order diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UploadFilesToolbarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UploadFilesToolbarButtonExtensionPoint.cs index 44b72ac3813..c09561a2a54 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UploadFilesToolbarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/UploadFilesToolbarButtonExtensionPoint.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "DigitalAssetsToolBarButton")] diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ViewPropertiesSelectionToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ViewPropertiesSelectionToolBarButtonExtensionPoint.cs index 8af15e4a3b5..bd8e42be048 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ViewPropertiesSelectionToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ViewPropertiesSelectionToolBarButtonExtensionPoint.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.Entities.Icons; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.UI.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButton { - //TODO Create the Custom IToolBarButtonExtensionPoint Export attribute + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.Entities.Icons; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.UI.Modules; + + // TODO Create the Custom IToolBarButtonExtensionPoint Export attribute [Export(typeof(IToolBarButtonExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "ViewPropertiesDigitalAssetsToolBarButton")] @@ -59,7 +59,7 @@ public string Icon get { return IconController.IconURL("ViewProperties", "16x16", "ToolBar"); - } + } } public int Order diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/FileFieldsControlExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/FileFieldsControlExtensionPoint.cs index 6faef940cc8..6a13930d86c 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/FileFieldsControlExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/FileFieldsControlExtensionPoint.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.ExtensionPoints; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.UserControls { + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.ExtensionPoints; + [Export(typeof(IUserControlExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "FileFieldsControlExtensionPoint")] @@ -23,12 +23,12 @@ public string UserControlSrc public string Text { - get { return ""; } + get { return string.Empty; } } public string Icon { - get { return ""; } + get { return string.Empty; } } public int Order diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/PreviewInfoPanelExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/PreviewInfoPanelExtensionPoint.cs index 7729da9edc8..b58b75ddad5 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/PreviewInfoPanelExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/PreviewInfoPanelExtensionPoint.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.ExtensionPoints; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.UserControls { + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.ExtensionPoints; + [Export(typeof(IUserControlExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "PreviewInfoPanelExtensionPoint")] @@ -23,12 +23,12 @@ public string UserControlSrc public string Text { - get { return ""; } + get { return string.Empty; } } public string Icon { - get { return ""; } + get { return string.Empty; } } public int Order diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/SearchBoxExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/SearchBoxExtensionPoint.cs index f94adc96ad8..562639755f6 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/SearchBoxExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/SearchBoxExtensionPoint.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.ComponentModel.Composition; - -using DotNetNuke.ExtensionPoints; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.UserControls { + using System; + using System.ComponentModel.Composition; + + using DotNetNuke.ExtensionPoints; + [Export(typeof(IUserControlExtensionPoint))] [ExportMetadata("Module", "DigitalAssets")] [ExportMetadata("Name", "SearchBoxExtensionPoint")] @@ -23,12 +23,12 @@ public string UserControlSrc public string Text { - get { return ""; } + get { return string.Empty; } } public string Icon { - get { return ""; } + get { return string.Empty; } } public int Order diff --git a/DNN Platform/Modules/DigitalAssets/DotNetNuke.Modules.DigitalAssets.csproj b/DNN Platform/Modules/DigitalAssets/DotNetNuke.Modules.DigitalAssets.csproj index eab5609f596..4e948342e85 100644 --- a/DNN Platform/Modules/DigitalAssets/DotNetNuke.Modules.DigitalAssets.csproj +++ b/DNN Platform/Modules/DigitalAssets/DotNetNuke.Modules.DigitalAssets.csproj @@ -23,6 +23,7 @@ ..\..\..\ true + true @@ -348,6 +349,15 @@ + + + stylecop.json + + + + + + diff --git a/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs b/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs index 4092d6c6cc3..0250971fc19 100644 --- a/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs @@ -1,45 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Abstractions; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + public partial class EditFolderMapping : PortalModuleBase { private readonly INavigationManager _navigationManager; + + private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; + private int _folderMappingID = Null.NullInteger; + public EditFolderMapping() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Variables - - private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; - private int _folderMappingID = Null.NullInteger; - - #endregion - - #region Properties - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + public int FolderPortalID { get { - return IsHostMenu ? Null.NullInteger : PortalId; + return this.IsHostMenu ? Null.NullInteger : this.PortalId; } } @@ -47,63 +42,60 @@ public int FolderMappingID { get { - if (_folderMappingID == Null.NullInteger) + if (this._folderMappingID == Null.NullInteger) { - if (!string.IsNullOrEmpty(Request.QueryString["ItemID"])) + if (!string.IsNullOrEmpty(this.Request.QueryString["ItemID"])) { - int.TryParse(Request.QueryString["ItemID"], out _folderMappingID); + int.TryParse(this.Request.QueryString["ItemID"], out this._folderMappingID); } } - return _folderMappingID; + + return this._folderMappingID; } - } - - #endregion - - #region Event Handlers - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); - if (!UserInfo.IsSuperUser && !UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) + if (!this.UserInfo.IsSuperUser && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) { - Response.Redirect(Globals.AccessDeniedURL(), true); + this.Response.Redirect(Globals.AccessDeniedURL(), true); } - UpdateButton.Text = (FolderMappingID == Null.NullInteger) ? Localization.GetString("Add") : Localization.GetString("Update", LocalResourceFile); - CancelHyperLink.NavigateUrl = EditUrl("FolderMappings"); + this.UpdateButton.Text = (this.FolderMappingID == Null.NullInteger) ? Localization.GetString("Add") : Localization.GetString("Update", this.LocalResourceFile); + this.CancelHyperLink.NavigateUrl = this.EditUrl("FolderMappings"); - var controlTitle = Localization.GetString("ControlTitle", LocalResourceFile); - var controlTitlePrefix = (FolderMappingID == Null.NullInteger) ? Localization.GetString("New") : Localization.GetString("Edit"); + var controlTitle = Localization.GetString("ControlTitle", this.LocalResourceFile); + var controlTitlePrefix = (this.FolderMappingID == Null.NullInteger) ? Localization.GetString("New") : Localization.GetString("Edit"); - SyncWarningPlaceHolder.Visible = (FolderMappingID != Null.NullInteger); + this.SyncWarningPlaceHolder.Visible = this.FolderMappingID != Null.NullInteger; - ModuleConfiguration.ModuleControl.ControlTitle = string.Format(controlTitle, controlTitlePrefix); + this.ModuleConfiguration.ModuleControl.ControlTitle = string.Format(controlTitle, controlTitlePrefix); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - UpdateButton.Click += cmdUpdate_Click; + this.UpdateButton.Click += this.cmdUpdate_Click; try { - BindFolderMappingSettings(); + this.BindFolderMappingSettings(); - if (!IsPostBack) + if (!this.IsPostBack) { - BindFolderProviders(); + this.BindFolderProviders(); - if (FolderMappingID != Null.NullInteger) + if (this.FolderMappingID != Null.NullInteger) { - BindFolderMapping(); + this.BindFolderMapping(); - if (ProviderSettingsPlaceHolder.Controls.Count > 0 && ProviderSettingsPlaceHolder.Controls[0] is FolderMappingSettingsControlBase) + if (this.ProviderSettingsPlaceHolder.Controls.Count > 0 && this.ProviderSettingsPlaceHolder.Controls[0] is FolderMappingSettingsControlBase) { - var folderMapping = _folderMappingController.GetFolderMapping(FolderMappingID); - var settingsControl = (FolderMappingSettingsControlBase)ProviderSettingsPlaceHolder.Controls[0]; + var folderMapping = this._folderMappingController.GetFolderMapping(this.FolderMappingID); + var settingsControl = (FolderMappingSettingsControlBase)this.ProviderSettingsPlaceHolder.Controls[0]; settingsControl.LoadSettings(folderMapping.FolderMappingSettings); } } @@ -115,44 +107,52 @@ protected override void OnLoad(EventArgs e) } } - private void cmdUpdate_Click(object sender, EventArgs e) + protected void cboFolderProviders_SelectedIndexChanged(object sender, EventArgs e) { - Page.Validate("vgEditFolderMapping"); + this.BindFolderMappingSettings(); + } - if (!Page.IsValid) return; + private void cmdUpdate_Click(object sender, EventArgs e) + { + this.Page.Validate("vgEditFolderMapping"); + if (!this.Page.IsValid) + { + return; + } + try { var folderMapping = new FolderMappingInfo(); - if (FolderMappingID != Null.NullInteger) + if (this.FolderMappingID != Null.NullInteger) { - folderMapping = _folderMappingController.GetFolderMapping(FolderMappingID) ?? new FolderMappingInfo(); + folderMapping = this._folderMappingController.GetFolderMapping(this.FolderMappingID) ?? new FolderMappingInfo(); } - folderMapping.FolderMappingID = FolderMappingID; - folderMapping.MappingName = NameTextbox.Text; - folderMapping.FolderProviderType = FolderProvidersComboBox.SelectedValue; - folderMapping.PortalID = FolderPortalID; + folderMapping.FolderMappingID = this.FolderMappingID; + folderMapping.MappingName = this.NameTextbox.Text; + folderMapping.FolderProviderType = this.FolderProvidersComboBox.SelectedValue; + folderMapping.PortalID = this.FolderPortalID; var originalSettings = folderMapping.FolderMappingSettings; try { - var folderMappingID = FolderMappingID; + var folderMappingID = this.FolderMappingID; if (folderMappingID == Null.NullInteger) { - folderMappingID = _folderMappingController.AddFolderMapping(folderMapping); + folderMappingID = this._folderMappingController.AddFolderMapping(folderMapping); } else { - _folderMappingController.UpdateFolderMapping(folderMapping); + this._folderMappingController.UpdateFolderMapping(folderMapping); } - if (ProviderSettingsPlaceHolder.Controls.Count > 0 && ProviderSettingsPlaceHolder.Controls[0] is FolderMappingSettingsControlBase) + if (this.ProviderSettingsPlaceHolder.Controls.Count > 0 && this.ProviderSettingsPlaceHolder.Controls[0] is FolderMappingSettingsControlBase) { - var settingsControl = (FolderMappingSettingsControlBase)ProviderSettingsPlaceHolder.Controls[0]; + var settingsControl = (FolderMappingSettingsControlBase)this.ProviderSettingsPlaceHolder.Controls[0]; try { @@ -160,109 +160,111 @@ private void cmdUpdate_Click(object sender, EventArgs e) } catch { - if (FolderMappingID == Null.NullInteger) + if (this.FolderMappingID == Null.NullInteger) { - _folderMappingController.DeleteFolderMapping(FolderPortalID, folderMappingID); + this._folderMappingController.DeleteFolderMapping(this.FolderPortalID, folderMappingID); } + return; } } - if (FolderMappingID != Null.NullInteger) + if (this.FolderMappingID != Null.NullInteger) { // Check if some setting has changed - var updatedSettings = _folderMappingController.GetFolderMappingSettings(FolderMappingID); + var updatedSettings = this._folderMappingController.GetFolderMappingSettings(this.FolderMappingID); if (originalSettings.Keys.Cast().Any(key => updatedSettings.ContainsKey(key) && !originalSettings[key].ToString().Equals(updatedSettings[key].ToString()))) { // Re-synchronize folders using the existing mapping. It's important to synchronize them in descending order - var folders = FolderManager.Instance.GetFolders(FolderPortalID).Where(f => f.FolderMappingID == FolderMappingID).OrderByDescending(f => f.FolderPath); + var folders = FolderManager.Instance.GetFolders(this.FolderPortalID).Where(f => f.FolderMappingID == this.FolderMappingID).OrderByDescending(f => f.FolderPath); foreach (var folder in folders) { - FolderManager.Instance.Synchronize(FolderPortalID, folder.FolderPath, false, true); + FolderManager.Instance.Synchronize(this.FolderPortalID, folder.FolderPath, false, true); } } } } catch { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("DuplicateMappingName", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("DuplicateMappingName", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - if (!Response.IsRequestBeingRedirected) - Response.Redirect(_navigationManager.NavigateURL(TabId, "FolderMappings", "mid=" + ModuleId, "popUp=true")); + if (!this.Response.IsRequestBeingRedirected) + { + this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, "FolderMappings", "mid=" + this.ModuleId, "popUp=true")); + } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } - - protected void cboFolderProviders_SelectedIndexChanged(object sender, EventArgs e) - { - BindFolderMappingSettings(); - } - - #endregion - - #region Private Methods - + private void BindFolderProviders() { var defaultProviders = DefaultFolderProviders.GetDefaultProviders(); foreach (var provider in FolderProvider.GetProviderList().Keys.Where(provider => !defaultProviders.Contains(provider)).OrderBy(provider => provider)) { - FolderProvidersComboBox.AddItem(provider, provider); + this.FolderProvidersComboBox.AddItem(provider, provider); } - FolderProvidersComboBox.InsertItem(0, "", ""); + + this.FolderProvidersComboBox.InsertItem(0, string.Empty, string.Empty); } private void BindFolderMapping() { - var folderMapping = _folderMappingController.GetFolderMapping(FolderMappingID); + var folderMapping = this._folderMappingController.GetFolderMapping(this.FolderMappingID); - NameTextbox.Text = folderMapping.MappingName; + this.NameTextbox.Text = folderMapping.MappingName; - FolderProvidersComboBox.SelectedValue = folderMapping.FolderProviderType; - FolderProvidersComboBox.Enabled = false; + this.FolderProvidersComboBox.SelectedValue = folderMapping.FolderProviderType; + this.FolderProvidersComboBox.Enabled = false; } private void BindFolderMappingSettings() { string folderProviderType; - if (FolderMappingID != Null.NullInteger) + if (this.FolderMappingID != Null.NullInteger) { - var folderMapping = _folderMappingController.GetFolderMapping(FolderMappingID); + var folderMapping = this._folderMappingController.GetFolderMapping(this.FolderMappingID); folderProviderType = folderMapping.FolderProviderType; } else { - folderProviderType = FolderProvidersComboBox.SelectedValue; + folderProviderType = this.FolderProvidersComboBox.SelectedValue; } - if (string.IsNullOrEmpty(folderProviderType)) return; - + if (string.IsNullOrEmpty(folderProviderType)) + { + return; + } + var settingsControlVirtualPath = FolderProvider.Instance(folderProviderType).GetSettingsControlVirtualPath(); - if (String.IsNullOrEmpty(settingsControlVirtualPath)) return; - - var settingsControl = LoadControl(settingsControlVirtualPath); - if (settingsControl == null || !(settingsControl is FolderMappingSettingsControlBase)) return; - - // This is important to allow settings control to be localizable + if (string.IsNullOrEmpty(settingsControlVirtualPath)) + { + return; + } + + var settingsControl = this.LoadControl(settingsControlVirtualPath); + if (settingsControl == null || !(settingsControl is FolderMappingSettingsControlBase)) + { + return; + } + + // This is important to allow settings control to be localizable var baseType = settingsControl.GetType().BaseType; if (baseType != null) { settingsControl.ID = baseType.Name; } - ProviderSettingsPlaceHolder.Controls.Clear(); - ProviderSettingsPlaceHolder.Controls.Add(settingsControl); - } - - #endregion + this.ProviderSettingsPlaceHolder.Controls.Clear(); + this.ProviderSettingsPlaceHolder.Controls.Add(settingsControl); + } } } diff --git a/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs index 3cbdf0f475f..182d69904f2 100644 --- a/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs @@ -1,53 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Text.RegularExpressions; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; -using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.IO; + using System.Text.RegularExpressions; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; + using DotNetNuke.Services.FileSystem; + public partial class FileFieldsControl : PortalModuleBase, IFieldsControl { + public IDigitalAssetsController Controller { get; private set; } + + public ItemViewModel Item { get; private set; } + + protected IFileInfo File { get; private set; } + public virtual void PrepareProperties() { - FileNameInput.Text = Item.ItemName; - FileNameInvalidCharactersValidator.ValidationExpression = "^([^" + Regex.Escape(Controller.GetInvalidChars()) + "]+)$"; - FileNameInvalidCharactersValidator.ErrorMessage = Controller.GetInvalidCharsErrorText(); + this.FileNameInput.Text = this.Item.ItemName; + this.FileNameInvalidCharactersValidator.ValidationExpression = "^([^" + Regex.Escape(this.Controller.GetInvalidChars()) + "]+)$"; + this.FileNameInvalidCharactersValidator.ErrorMessage = this.Controller.GetInvalidCharsErrorText(); } private void PrepareFileAttributes() { - FileAttributeArchiveCheckBox.Checked = (File.FileAttributes & FileAttributes.Archive) == FileAttributes.Archive; - FileAttributeHiddenCheckBox.Checked = (File.FileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - FileAttributeReadonlyCheckBox.Checked = (File.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; - FileAttributeSystemCheckBox.Checked = (File.FileAttributes & FileAttributes.System) == FileAttributes.System; + this.FileAttributeArchiveCheckBox.Checked = (this.File.FileAttributes & FileAttributes.Archive) == FileAttributes.Archive; + this.FileAttributeHiddenCheckBox.Checked = (this.File.FileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; + this.FileAttributeReadonlyCheckBox.Checked = (this.File.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + this.FileAttributeSystemCheckBox.Checked = (this.File.FileAttributes & FileAttributes.System) == FileAttributes.System; } private FileAttributes GetFileAttributesUpdated(FileAttributes? attributes) { - var result = FileAttributeArchiveCheckBox.Checked ? (attributes | FileAttributes.Archive) : (attributes & ~FileAttributes.Archive); - result = FileAttributeHiddenCheckBox.Checked ? (result | FileAttributes.Hidden) : (result & ~FileAttributes.Hidden); - result = FileAttributeReadonlyCheckBox.Checked ? (result | FileAttributes.ReadOnly) : (result & ~FileAttributes.ReadOnly); - result = FileAttributeSystemCheckBox.Checked ? (result | FileAttributes.System) : (result & ~FileAttributes.System); + var result = this.FileAttributeArchiveCheckBox.Checked ? (attributes | FileAttributes.Archive) : (attributes & ~FileAttributes.Archive); + result = this.FileAttributeHiddenCheckBox.Checked ? (result | FileAttributes.Hidden) : (result & ~FileAttributes.Hidden); + result = this.FileAttributeReadonlyCheckBox.Checked ? (result | FileAttributes.ReadOnly) : (result & ~FileAttributes.ReadOnly); + result = this.FileAttributeSystemCheckBox.Checked ? (result | FileAttributes.System) : (result & ~FileAttributes.System); return result.Value; } - public IDigitalAssetsController Controller { get; private set; } - - public ItemViewModel Item { get; private set; } + public void SetController(IDigitalAssetsController damController) + { + this.Controller = damController; + } - protected IFileInfo File { get; private set; } + public void SetModuleConfiguration(ModuleInfo moduleConfiguration) + { + this.ModuleConfiguration = moduleConfiguration; + } protected override void OnInit(EventArgs e) { @@ -59,62 +69,52 @@ protected override void OnInit(EventArgs e) protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (!Page.IsPostBack) - { - PrepareProperties(); - FileAttributesContainer.Visible = File.SupportsFileAttributes; - if (File.SupportsFileAttributes) + if (!this.Page.IsPostBack) + { + this.PrepareProperties(); + this.FileAttributesContainer.Visible = this.File.SupportsFileAttributes; + if (this.File.SupportsFileAttributes) { - PrepareFileAttributes(); - } + this.PrepareFileAttributes(); + } } } - public void SetController(IDigitalAssetsController damController) - { - this.Controller = damController; - } - - public void SetModuleConfiguration(ModuleInfo moduleConfiguration) - { - this.ModuleConfiguration = moduleConfiguration; - } - public void SetItemViewModel(ItemViewModel itemViewModel) { this.Item = itemViewModel; } - + public virtual void SetPropertiesAvailability(bool availability) { - FileNameInput.Enabled = availability; - FileAttributeArchiveCheckBox.Enabled = availability; - FileAttributeHiddenCheckBox.Enabled = availability; - FileAttributeReadonlyCheckBox.Enabled = availability; - FileAttributeSystemCheckBox.Enabled = availability; + this.FileNameInput.Enabled = availability; + this.FileAttributeArchiveCheckBox.Enabled = availability; + this.FileAttributeHiddenCheckBox.Enabled = availability; + this.FileAttributeReadonlyCheckBox.Enabled = availability; + this.FileAttributeSystemCheckBox.Enabled = availability; } public virtual void SetPropertiesVisibility(bool visibility) { - FileNameInput.Visible = visibility; - FileAttributesContainer.Visible = visibility; + this.FileNameInput.Visible = visibility; + this.FileAttributesContainer.Visible = visibility; } public void SetFileInfo(IFileInfo fileInfo) { - File = fileInfo; + this.File = fileInfo; } public virtual object SaveProperties() { - Controller.RenameFile(Item.ItemID, FileNameInput.Text); - if (File.SupportsFileAttributes) + this.Controller.RenameFile(this.Item.ItemID, this.FileNameInput.Text); + if (this.File.SupportsFileAttributes) { - File = FileManager.Instance.GetFile(Item.ItemID, true); - FileManager.Instance.SetAttributes(File, GetFileAttributesUpdated(File.FileAttributes)); + this.File = FileManager.Instance.GetFile(this.Item.ItemID, true); + FileManager.Instance.SetAttributes(this.File, this.GetFileAttributesUpdated(this.File.FileAttributes)); } - return File; + return this.File; } } } diff --git a/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs b/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs index cea02617c1f..5c103561ced 100644 --- a/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs @@ -1,34 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Web.UI; -using System.Web.UI.HtmlControls; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; -using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; -using DotNetNuke.Modules.DigitalAssets.Services; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web.UI; + using System.Web.UI.HtmlControls; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; + using DotNetNuke.Modules.DigitalAssets.Services; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.UI; + public partial class FileProperties : PortalModuleBase { - private readonly IDigitalAssetsController controller = (new Factory()).DigitalAssetsController; + private readonly IDigitalAssetsController controller = new Factory().DigitalAssetsController; private IFileInfo file; private IFolderInfo folder; @@ -41,7 +41,7 @@ protected string DialogTitle { get { - return fileItem.ItemName; + return this.fileItem.ItemName; } } @@ -49,7 +49,7 @@ protected bool CanManageFolder { get { - return UserInfo.IsSuperUser || FolderPermissionController.CanManageFolder((FolderInfo)folder); + return this.UserInfo.IsSuperUser || FolderPermissionController.CanManageFolder((FolderInfo)this.folder); } } @@ -57,12 +57,11 @@ protected string ActiveTab { get { - var activeTab = Request.QueryString["activeTab"]; - return string.IsNullOrEmpty(activeTab) ? "" : System.Text.RegularExpressions.Regex.Replace(activeTab, "[^\\w]", ""); + var activeTab = this.Request.QueryString["activeTab"]; + return string.IsNullOrEmpty(activeTab) ? string.Empty : System.Text.RegularExpressions.Regex.Replace(activeTab, "[^\\w]", string.Empty); } } - - + protected override void OnInit(EventArgs e) { try @@ -71,55 +70,57 @@ protected override void OnInit(EventArgs e) JavaScript.RequestRegistration(CommonJs.DnnPlugins); - var fileId = Convert.ToInt32(Request.Params["FileId"]); - file = FileManager.Instance.GetFile(fileId, true); - fileItem = controller.GetFile(fileId); - folder = FolderManager.Instance.GetFolder(file.FolderId); + var fileId = Convert.ToInt32(this.Request.Params["FileId"]); + this.file = FileManager.Instance.GetFile(fileId, true); + this.fileItem = this.controller.GetFile(fileId); + this.folder = FolderManager.Instance.GetFolder(this.file.FolderId); - SaveButton.Click += OnSaveClick; - CancelButton.Click += OnCancelClick; + this.SaveButton.Click += this.OnSaveClick; + this.CancelButton.Click += this.OnCancelClick; - if (FolderPermissionController.CanViewFolder((FolderInfo)folder)) + if (FolderPermissionController.CanViewFolder((FolderInfo)this.folder)) { var mef = new ExtensionPointManager(); var preViewPanelExtension = mef.GetUserControlExtensionPointFirstByPriority("DigitalAssets", "PreviewInfoPanelExtensionPoint"); - previewPanelControl = Page.LoadControl(preViewPanelExtension.UserControlSrc); - PreviewPanelContainer.Controls.Add(previewPanelControl); + this.previewPanelControl = this.Page.LoadControl(preViewPanelExtension.UserControlSrc); + this.PreviewPanelContainer.Controls.Add(this.previewPanelControl); var fileFieldsExtension = mef.GetUserControlExtensionPointFirstByPriority("DigitalAssets", "FileFieldsControlExtensionPoint"); - fileFieldsControl = Page.LoadControl(fileFieldsExtension.UserControlSrc); - fileFieldsControl.ID = fileFieldsControl.GetType().BaseType.Name; - FileFieldsContainer.Controls.Add(fileFieldsControl); + this.fileFieldsControl = this.Page.LoadControl(fileFieldsExtension.UserControlSrc); + this.fileFieldsControl.ID = this.fileFieldsControl.GetType().BaseType.Name; + this.FileFieldsContainer.Controls.Add(this.fileFieldsControl); - PrepareFilePreviewInfoControl(); - PrepareFileFieldsControl(); + this.PrepareFilePreviewInfoControl(); + this.PrepareFileFieldsControl(); // Tab Extension Point var tabContentControlsInstances = new List(); foreach (var extension in mef.GetEditPageTabExtensionPoints("DigitalAssets", "FilePropertiesTab")) { - if (FolderPermissionController.HasFolderPermission(folder.FolderPermissions, extension.Permission)) + if (FolderPermissionController.HasFolderPermission(this.folder.FolderPermissions, extension.Permission)) { var liElement = new HtmlGenericControl("li") { InnerHtml = "" + extension.Text + "", }; liElement.Attributes.Add("class", extension.CssClass); liElement.Attributes.Add("id", extension.EditPageTabId + "_tab"); - Tabs.Controls.Add(liElement); + this.Tabs.Controls.Add(liElement); var container = new PanelTabExtensionControl { PanelId = extension.EditPageTabId }; - var control = (PortalModuleBase)Page.LoadControl(extension.UserControlSrc); + var control = (PortalModuleBase)this.Page.LoadControl(extension.UserControlSrc); control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); - control.ModuleConfiguration = ModuleConfiguration; + control.ModuleConfiguration = this.ModuleConfiguration; var contentControl = control as PropertiesTabContentControl; if (contentControl != null) { - contentControl.OnItemUpdated += OnItemUpdated; + contentControl.OnItemUpdated += this.OnItemUpdated; tabContentControlsInstances.Add(contentControl); } + container.Controls.Add(control); - TabsPanel.Controls.Add(container); + this.TabsPanel.Controls.Add(container); } } - tabContentControls = tabContentControlsInstances.ToList(); + + this.tabContentControls = tabContentControlsInstances.ToList(); } } catch (Exception ex) @@ -132,21 +133,21 @@ protected override void OnLoad(EventArgs e) { try { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - SetPropertiesAvailability(CanManageFolder); + this.SetPropertiesAvailability(this.CanManageFolder); } - if (!FolderPermissionController.CanViewFolder((FolderInfo)folder)) + if (!FolderPermissionController.CanViewFolder((FolderInfo)this.folder)) { - SaveButton.Visible = false; - SetPropertiesVisibility(false); - UI.Skins.Skin.AddModuleMessage(this, LocalizeString("UserCannotReadFileError"), ModuleMessage.ModuleMessageType.RedError); + this.SaveButton.Visible = false; + this.SetPropertiesVisibility(false); + UI.Skins.Skin.AddModuleMessage(this, this.LocalizeString("UserCannotReadFileError"), ModuleMessage.ModuleMessageType.RedError); } else { - SetFilePreviewInfo(); - SaveButton.Visible = FolderPermissionController.CanViewFolder((FolderInfo)folder) && FolderPermissionController.CanManageFolder((FolderInfo)folder); + this.SetFilePreviewInfo(); + this.SaveButton.Visible = FolderPermissionController.CanViewFolder((FolderInfo)this.folder) && FolderPermissionController.CanManageFolder((FolderInfo)this.folder); } } catch (DotNetNukeException dnnex) @@ -161,8 +162,8 @@ protected override void OnLoad(EventArgs e) private void OnItemUpdated() { - SetFilePreviewInfo(); - foreach (var propertiesTabContentControl in tabContentControls) + this.SetFilePreviewInfo(); + foreach (var propertiesTabContentControl in this.tabContentControls) { propertiesTabContentControl.DataBindItem(); } @@ -170,17 +171,19 @@ private void OnItemUpdated() private void OnSaveClick(object sender, EventArgs e) { - if (!Page.IsValid) + if (!this.Page.IsValid) { return; } try { - SaveFileProperties(); - Page.CloseClientDialog(true); + this.SaveFileProperties(); + this.Page.CloseClientDialog(true); } - catch (ThreadAbortException) { } + catch (ThreadAbortException) + { + } catch (DotNetNukeException dnnex) { UI.Skins.Skin.AddModuleMessage(this, dnnex.Message, ModuleMessage.ModuleMessageType.RedError); @@ -194,44 +197,44 @@ private void OnSaveClick(object sender, EventArgs e) private void OnCancelClick(object sender, EventArgs e) { - Page.CloseClientDialog(false); + this.Page.CloseClientDialog(false); } private void SaveFileProperties() { - file = (IFileInfo)((FileFieldsControl)fileFieldsControl).SaveProperties(); + this.file = (IFileInfo)((FileFieldsControl)this.fileFieldsControl).SaveProperties(); } private void SetPropertiesVisibility(bool visibility) { - ((FileFieldsControl)fileFieldsControl).SetPropertiesVisibility(visibility); + ((FileFieldsControl)this.fileFieldsControl).SetPropertiesVisibility(visibility); } private void SetPropertiesAvailability(bool availability) { - ((FileFieldsControl)fileFieldsControl).SetPropertiesAvailability(availability); + ((FileFieldsControl)this.fileFieldsControl).SetPropertiesAvailability(availability); } private void SetFilePreviewInfo() { - var previewPanelInstance = (PreviewPanelControl)previewPanelControl; - previewPanelInstance.SetPreviewInfo(controller.GetFilePreviewInfo(file, fileItem)); + var previewPanelInstance = (PreviewPanelControl)this.previewPanelControl; + previewPanelInstance.SetPreviewInfo(this.controller.GetFilePreviewInfo(this.file, this.fileItem)); } private void PrepareFilePreviewInfoControl() { - var previewPanelInstance = (PreviewPanelControl)previewPanelControl; - previewPanelInstance.SetController(controller); - previewPanelInstance.SetModuleConfiguration(ModuleConfiguration); + var previewPanelInstance = (PreviewPanelControl)this.previewPanelControl; + previewPanelInstance.SetController(this.controller); + previewPanelInstance.SetModuleConfiguration(this.ModuleConfiguration); } private void PrepareFileFieldsControl() { - var fileFieldsIntance = (FileFieldsControl)fileFieldsControl; - fileFieldsIntance.SetController(controller); - fileFieldsIntance.SetItemViewModel(fileItem); - fileFieldsIntance.SetFileInfo(file); - fileFieldsIntance.SetModuleConfiguration(ModuleConfiguration); + var fileFieldsIntance = (FileFieldsControl)this.fileFieldsControl; + fileFieldsIntance.SetController(this.controller); + fileFieldsIntance.SetItemViewModel(this.fileItem); + fileFieldsIntance.SetFileInfo(this.file); + fileFieldsIntance.SetModuleConfiguration(this.ModuleConfiguration); } } } diff --git a/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs b/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs index 01afc70f86d..488ffc601ea 100644 --- a/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs @@ -1,47 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Application; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.UI.WebControls; -using Telerik.Web.UI; -using Globals = DotNetNuke.Common.Globals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Collections.Generic; + + using DotNetNuke.Abstractions; + using DotNetNuke.Application; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + using Telerik.Web.UI; + + using Globals = DotNetNuke.Common.Globals; + public partial class FolderMappings : PortalModuleBase { private readonly INavigationManager _navigationManager; + + private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; + public FolderMappings() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Variables - - private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; - - #endregion - - #region Properties - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + public int FolderPortalID { get { - return IsHostMenu ? Null.NullInteger : PortalId; + return this.IsHostMenu ? Null.NullInteger : this.PortalId; } } @@ -51,58 +47,57 @@ protected List FolderMappingsList { try { - var obj = Session["FolderMappingsList"]; + var obj = this.Session["FolderMappingsList"]; if (obj == null) { - obj = _folderMappingController.GetFolderMappings(FolderPortalID); + obj = this._folderMappingController.GetFolderMappings(this.FolderPortalID); if (obj != null) { - Session["FolderMappingsList"] = obj; + this.Session["FolderMappingsList"] = obj; } else { obj = new List(); } } + return (List)obj; } catch { - Session["FolderMappingsList"] = null; + this.Session["FolderMappingsList"] = null; } + return new List(); } - set { Session["FolderMappingsList"] = value; } - } - - #endregion - - #region Event Handlers - + + set { this.Session["FolderMappingsList"] = value; } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); - if (!UserInfo.IsSuperUser && !UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) + if (!this.UserInfo.IsSuperUser && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) { - Response.Redirect(Globals.AccessDeniedURL(), true); + this.Response.Redirect(Globals.AccessDeniedURL(), true); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - JavaScript.RegisterClientReference(Page, ClientAPI.ClientNamespaceReferences.dnn); - CancelButton.NavigateUrl = _navigationManager.NavigateURL(); - NewMappingButton.Click += OnNewMappingClick; + JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn); + this.CancelButton.NavigateUrl = this._navigationManager.NavigateURL(); + this.NewMappingButton.Click += this.OnNewMappingClick; - if (!IsPostBack) + if (!this.IsPostBack) { - Session["FolderMappingsList"] = null; + this.Session["FolderMappingsList"] = null; - if (ModuleConfiguration.ModuleControl.SupportsPopUps) + if (this.ModuleConfiguration.ModuleControl.SupportsPopUps) { - MappingsGrid.Rebind(); + this.MappingsGrid.Rebind(); } } } @@ -111,81 +106,83 @@ protected void MappingsGrid_OnItemCommand(object source, GridCommandEventArgs e) { if (e.CommandName == "Edit") { - Response.Redirect(_navigationManager.NavigateURL(TabId, "EditFolderMapping", "mid=" + ModuleId, "popUp=true", "ItemID=" + e.CommandArgument.ToString())); + this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, "EditFolderMapping", "mid=" + this.ModuleId, "popUp=true", "ItemID=" + e.CommandArgument.ToString())); } else { - var folderMappingsList = FolderMappingsList; + var folderMappingsList = this.FolderMappingsList; var folderMapping = folderMappingsList.Find(f => f.FolderMappingID == int.Parse(e.CommandArgument.ToString())); switch (e.CommandName) { case "Delete": - _folderMappingController.DeleteFolderMapping(folderMapping.PortalID, folderMapping.FolderMappingID); + this._folderMappingController.DeleteFolderMapping(folderMapping.PortalID, folderMapping.FolderMappingID); folderMappingsList.Remove(folderMapping); break; default: break; } - FolderMappingsList = folderMappingsList; - MappingsGrid.Rebind(); + this.FolderMappingsList = folderMappingsList; + this.MappingsGrid.Rebind(); } } protected void MappingsGrid_OnItemDataBound(object sender, GridItemEventArgs e) { - if (e.Item.ItemType != GridItemType.Item && e.Item.ItemType != GridItemType.AlternatingItem) return; - - var folderMapping = (e.Item.DataItem as FolderMappingInfo); + if (e.Item.ItemType != GridItemType.Item && e.Item.ItemType != GridItemType.AlternatingItem) + { + return; + } + + var folderMapping = e.Item.DataItem as FolderMappingInfo; if (folderMapping == null || !folderMapping.IsEditable) { return; } - var cmdEditMapping = (e.Item.FindControl("EditMappingButton") as CommandButton); - if (cmdEditMapping != null) cmdEditMapping.ToolTip = Localization.GetString("cmdEdit"); - - var cmdDeleteMapping = (e.Item.FindControl("DeleteMappingButton") as CommandButton); - if (cmdDeleteMapping == null) return; - + var cmdEditMapping = e.Item.FindControl("EditMappingButton") as CommandButton; + if (cmdEditMapping != null) + { + cmdEditMapping.ToolTip = Localization.GetString("cmdEdit"); + } + + var cmdDeleteMapping = e.Item.FindControl("DeleteMappingButton") as CommandButton; + if (cmdDeleteMapping == null) + { + return; + } + cmdDeleteMapping.ToolTip = Localization.GetString("cmdDelete"); - var deleteMessage = string.Format(Localization.GetString("DeleteConfirm", LocalResourceFile), folderMapping.MappingName); + var deleteMessage = string.Format(Localization.GetString("DeleteConfirm", this.LocalResourceFile), folderMapping.MappingName); cmdDeleteMapping.OnClientClick = "return confirm(\"" + ClientAPI.GetSafeJSString(deleteMessage) + "\");"; } protected void MappingsGrid_OnNeedDataSource(object source, GridNeedDataSourceEventArgs e) { - MappingsGrid.DataSource = FolderMappingsList; + this.MappingsGrid.DataSource = this.FolderMappingsList; } protected void OnNewMappingClick(object sender, EventArgs e) { try { - Response.Redirect(_navigationManager.NavigateURL(TabId, "EditFolderMapping", "mid=" + ModuleId, "popUp=true")); + this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, "EditFolderMapping", "mid=" + this.ModuleId, "popUp=true")); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - - #region Private Methods - + } + private void UpdateFolderMappings(IList folderMappingsList) { for (var i = 3; i < folderMappingsList.Count; i++) { folderMappingsList[i].Priority = i + 1; - _folderMappingController.UpdateFolderMapping(folderMappingsList[i]); + this._folderMappingController.UpdateFolderMapping(folderMappingsList[i]); } - } - - #endregion - + } } } diff --git a/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs b/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs index 33f67e6c05c..ab39be08eb3 100644 --- a/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs @@ -1,32 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web.UI; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; -using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; -using DotNetNuke.Modules.DigitalAssets.Services; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + using DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint; + using DotNetNuke.Modules.DigitalAssets.Services; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.UI; + public partial class FolderProperties : PortalModuleBase { private static readonly DigitalAssetsSettingsRepository SettingsRepository = new DigitalAssetsSettingsRepository(); - private readonly IDigitalAssetsController controller = (new Factory()).DigitalAssetsController; + private readonly IDigitalAssetsController controller = new Factory().DigitalAssetsController; private FolderViewModel folderViewModel; private bool isRootFolder; private Control folderFieldsControl; @@ -37,7 +38,7 @@ protected bool CanManageFolder { get { - return UserInfo.IsSuperUser || FolderPermissionController.CanManageFolder((FolderInfo)Folder); + return this.UserInfo.IsSuperUser || FolderPermissionController.CanManageFolder((FolderInfo)this.Folder); } } @@ -47,7 +48,7 @@ protected string DialogTitle { get { - return string.Format(LocalizeString("DialogTitle"), folderViewModel.FolderName); + return string.Format(this.LocalizeString("DialogTitle"), this.folderViewModel.FolderName); } } @@ -55,7 +56,7 @@ protected bool IsHostPortal { get { - return IsHostMenu || controller.GetCurrentPortalId(ModuleId) == Null.NullInteger; + return this.IsHostMenu || this.controller.GetCurrentPortalId(this.ModuleId) == Null.NullInteger; } } @@ -67,57 +68,58 @@ protected override void OnInit(EventArgs e) JavaScript.RequestRegistration(CommonJs.DnnPlugins); - var folderId = Convert.ToInt32(Request.Params["FolderId"]); - Folder = FolderManager.Instance.GetFolder(folderId); - HasFullControl = UserInfo.IsSuperUser || FolderPermissionController.HasFolderPermission(Folder.FolderPermissions, "FULLCONTROL"); + var folderId = Convert.ToInt32(this.Request.Params["FolderId"]); + this.Folder = FolderManager.Instance.GetFolder(folderId); + this.HasFullControl = this.UserInfo.IsSuperUser || FolderPermissionController.HasFolderPermission(this.Folder.FolderPermissions, "FULLCONTROL"); FolderViewModel rootFolder; - switch (SettingsRepository.GetMode(ModuleId)) + switch (SettingsRepository.GetMode(this.ModuleId)) { case DigitalAssestsMode.Group: - var groupId = Convert.ToInt32(Request.Params["GroupId"]); - rootFolder = controller.GetGroupFolder(groupId, PortalSettings); + var groupId = Convert.ToInt32(this.Request.Params["GroupId"]); + rootFolder = this.controller.GetGroupFolder(groupId, this.PortalSettings); if (rootFolder == null) { throw new Exception("Invalid group folder"); } + break; case DigitalAssestsMode.User: - rootFolder = controller.GetUserFolder(PortalSettings.UserInfo); + rootFolder = this.controller.GetUserFolder(this.PortalSettings.UserInfo); break; default: - rootFolder = controller.GetRootFolder(ModuleId); + rootFolder = this.controller.GetRootFolder(this.ModuleId); break; } - isRootFolder = rootFolder.FolderID == folderId; - folderViewModel = isRootFolder ? rootFolder : controller.GetFolder(folderId); - + this.isRootFolder = rootFolder.FolderID == folderId; + this.folderViewModel = this.isRootFolder ? rootFolder : this.controller.GetFolder(folderId); + // Setup controls - CancelButton.Click += OnCancelClick; - SaveButton.Click += OnSaveClick; - PrepareFolderPreviewInfo(); - cmdCopyPerm.Click += cmdCopyPerm_Click; + this.CancelButton.Click += this.OnCancelClick; + this.SaveButton.Click += this.OnSaveClick; + this.PrepareFolderPreviewInfo(); + this.cmdCopyPerm.Click += this.cmdCopyPerm_Click; var mef = new ExtensionPointManager(); var folderFieldsExtension = mef.GetUserControlExtensionPointFirstByPriority("DigitalAssets", "FolderFieldsControlExtensionPoint"); if (folderFieldsExtension != null) { - folderFieldsControl = Page.LoadControl(folderFieldsExtension.UserControlSrc); - folderFieldsControl.ID = folderFieldsControl.GetType().BaseType.Name; - FolderDynamicFieldsContainer.Controls.Add(folderFieldsControl); - var fieldsControl = folderFieldsControl as IFieldsControl; + this.folderFieldsControl = this.Page.LoadControl(folderFieldsExtension.UserControlSrc); + this.folderFieldsControl.ID = this.folderFieldsControl.GetType().BaseType.Name; + this.FolderDynamicFieldsContainer.Controls.Add(this.folderFieldsControl); + var fieldsControl = this.folderFieldsControl as IFieldsControl; if (fieldsControl != null) { - fieldsControl.SetController(controller); + fieldsControl.SetController(this.controller); fieldsControl.SetItemViewModel(new ItemViewModel { - ItemID = folderViewModel.FolderID, + ItemID = this.folderViewModel.FolderID, IsFolder = true, - PortalID = folderViewModel.PortalID, - ItemName = folderViewModel.FolderName + PortalID = this.folderViewModel.PortalID, + ItemName = this.folderViewModel.FolderName, }); } } @@ -128,22 +130,54 @@ protected override void OnInit(EventArgs e) } } + protected override void OnLoad(EventArgs e) + { + try + { + if (!this.Page.IsPostBack) + { + this.SetupPermissionGrid(); + this.PrepareFolderProperties(); + this.SetPropertiesAvailability(FolderPermissionController.CanManageFolder((FolderInfo)this.Folder)); + } + + if (!FolderPermissionController.CanViewFolder((FolderInfo)this.Folder)) + { + this.SaveButton.Visible = false; + this.SetPropertiesVisibility(false); + UI.Skins.Skin.AddModuleMessage(this, this.LocalizeString("UserCannotReadFolderError"), ModuleMessage.ModuleMessageType.RedError); + } + else + { + this.SaveButton.Visible = FolderPermissionController.CanViewFolder((FolderInfo)this.Folder) && FolderPermissionController.CanManageFolder((FolderInfo)this.Folder); + } + } + catch (DotNetNukeException dnnex) + { + UI.Skins.Skin.AddModuleMessage(this, dnnex.Message, ModuleMessage.ModuleMessageType.RedError); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private void OnSaveClick(object sender, EventArgs e) { try { - if (!Page.IsValid) + if (!this.Page.IsValid) { return; } - SaveFolderProperties(); + this.SaveFolderProperties(); - SavePermissions(); - Page.CloseClientDialog(true); + this.SavePermissions(); + this.Page.CloseClientDialog(true); } catch (ThreadAbortException) - { + { } catch (DotNetNukeException dnnex) { @@ -158,91 +192,59 @@ private void OnSaveClick(object sender, EventArgs e) private void SaveFolderProperties() { - if (!CanManageFolder) + if (!this.CanManageFolder) { - throw new DotNetNukeException(LocalizeString("UserCannotEditFolderError")); + throw new DotNetNukeException(this.LocalizeString("UserCannotEditFolderError")); } - if (!isRootFolder) + if (!this.isRootFolder) { - controller.RenameFolder(folderViewModel.FolderID, FolderNameInput.Text); + this.controller.RenameFolder(this.folderViewModel.FolderID, this.FolderNameInput.Text); } - var fieldsControl = folderFieldsControl as IFieldsControl; + var fieldsControl = this.folderFieldsControl as IFieldsControl; if (fieldsControl != null) { - Folder = (IFolderInfo)fieldsControl.SaveProperties(); + this.Folder = (IFolderInfo)fieldsControl.SaveProperties(); } } private void SavePermissions() { - if (!CanManageFolder) + if (!this.CanManageFolder) { - throw new DotNetNukeException(LocalizeString("UserCannotChangePermissionsError")); + throw new DotNetNukeException(this.LocalizeString("UserCannotChangePermissionsError")); } - Folder = FolderManager.Instance.GetFolder(Folder.FolderID); - Folder.FolderPermissions.Clear(); - Folder.FolderPermissions.AddRange(PermissionsGrid.Permissions); - FolderPermissionController.SaveFolderPermissions(Folder); + this.Folder = FolderManager.Instance.GetFolder(this.Folder.FolderID); + this.Folder.FolderPermissions.Clear(); + this.Folder.FolderPermissions.AddRange(this.PermissionsGrid.Permissions); + FolderPermissionController.SaveFolderPermissions(this.Folder); } private void OnCancelClick(object sender, EventArgs e) { - Page.CloseClientDialog(false); + this.Page.CloseClientDialog(false); } private void cmdCopyPerm_Click(object sender, EventArgs e) { try { - FolderPermissionController.CopyPermissionsToSubfolders(Folder, PermissionsGrid.Permissions); - UI.Skins.Skin.AddModuleMessage(this, LocalizeString("PermissionsCopied"), ModuleMessage.ModuleMessageType.GreenSuccess); + FolderPermissionController.CopyPermissionsToSubfolders(this.Folder, this.PermissionsGrid.Permissions); + UI.Skins.Skin.AddModuleMessage(this, this.LocalizeString("PermissionsCopied"), ModuleMessage.ModuleMessageType.GreenSuccess); } catch (Exception ex) { - UI.Skins.Skin.AddModuleMessage(this, LocalizeString("PermissionCopyError"), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, this.LocalizeString("PermissionCopyError"), ModuleMessage.ModuleMessageType.RedError); Exceptions.ProcessModuleLoadException(this, ex); } } - protected override void OnLoad(EventArgs e) - { - try - { - if (!Page.IsPostBack) - { - SetupPermissionGrid(); - PrepareFolderProperties(); - SetPropertiesAvailability(FolderPermissionController.CanManageFolder((FolderInfo)Folder)); - } - - if (!FolderPermissionController.CanViewFolder((FolderInfo)Folder)) - { - SaveButton.Visible = false; - SetPropertiesVisibility(false); - UI.Skins.Skin.AddModuleMessage(this, LocalizeString("UserCannotReadFolderError"), ModuleMessage.ModuleMessageType.RedError); - } - else - { - SaveButton.Visible = FolderPermissionController.CanViewFolder((FolderInfo)Folder) && FolderPermissionController.CanManageFolder((FolderInfo)Folder); - } - } - catch (DotNetNukeException dnnex) - { - UI.Skins.Skin.AddModuleMessage(this, dnnex.Message, ModuleMessage.ModuleMessageType.RedError); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - private void SetPropertiesAvailability(bool availability) { - FolderNameInput.Enabled = (!isRootFolder) && availability; - var fieldsControl = folderFieldsControl as IFieldsControl; + this.FolderNameInput.Enabled = (!this.isRootFolder) && availability; + var fieldsControl = this.folderFieldsControl as IFieldsControl; if (fieldsControl != null) { fieldsControl.SetPropertiesAvailability(availability); @@ -251,10 +253,10 @@ private void SetPropertiesAvailability(bool availability) private void SetPropertiesVisibility(bool visibility) { - FolderNameInput.Visible = visibility; - FolderTypeLiteral.Visible = visibility; - FolderInfoPreviewPanel.Visible = visibility; - var fieldsControl = folderFieldsControl as IFieldsControl; + this.FolderNameInput.Visible = visibility; + this.FolderTypeLiteral.Visible = visibility; + this.FolderInfoPreviewPanel.Visible = visibility; + var fieldsControl = this.folderFieldsControl as IFieldsControl; if (fieldsControl != null) { fieldsControl.SetPropertiesVisibility(visibility); @@ -263,13 +265,13 @@ private void SetPropertiesVisibility(bool visibility) private void PrepareFolderProperties() { - FolderNameInput.Text = folderViewModel.FolderName; - FolderTypeLiteral.Text = FolderMappingController.Instance.GetFolderMapping(folderViewModel.FolderMappingID).MappingName; + this.FolderNameInput.Text = this.folderViewModel.FolderName; + this.FolderTypeLiteral.Text = FolderMappingController.Instance.GetFolderMapping(this.folderViewModel.FolderMappingID).MappingName; - FolderNameInvalidCharactersValidator.ValidationExpression = "^([^" + Regex.Escape(controller.GetInvalidChars()) + "]+)$"; - FolderNameInvalidCharactersValidator.ErrorMessage = controller.GetInvalidCharsErrorText(); + this.FolderNameInvalidCharactersValidator.ValidationExpression = "^([^" + Regex.Escape(this.controller.GetInvalidChars()) + "]+)$"; + this.FolderNameInvalidCharactersValidator.ErrorMessage = this.controller.GetInvalidCharsErrorText(); - var fieldsControl = folderFieldsControl as IFieldsControl; + var fieldsControl = this.folderFieldsControl as IFieldsControl; if (fieldsControl != null) { fieldsControl.PrepareProperties(); @@ -278,17 +280,17 @@ private void PrepareFolderProperties() private void PrepareFolderPreviewInfo() { - var folderPreviewPanel = (PreviewPanelControl)FolderInfoPreviewPanel; + var folderPreviewPanel = (PreviewPanelControl)this.FolderInfoPreviewPanel; if (folderPreviewPanel != null) { - folderPreviewPanel.SetPreviewInfo(controller.GetFolderPreviewInfo(Folder)); + folderPreviewPanel.SetPreviewInfo(this.controller.GetFolderPreviewInfo(this.Folder)); } } private void SetupPermissionGrid() { - PermissionsGrid.FolderPath = Folder.FolderPath; - PermissionsGrid.Visible = HasFullControl && !IsHostPortal; + this.PermissionsGrid.FolderPath = this.Folder.FolderPath; + this.PermissionsGrid.Visible = this.HasFullControl && !this.IsHostPortal; } } } diff --git a/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs index 28cc80c920a..d6d31b4ea50 100644 --- a/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs @@ -1,30 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Collections.Generic; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + public partial class PreviewFieldsControl : UserControl { + public List Fields { get; set; } + public void GenerateFieldsTable() { - FieldsTable.Rows.Clear(); - foreach (var field in Fields) + this.FieldsTable.Rows.Clear(); + foreach (var field in this.Fields) { var cellLabel = new TableCell { Text = field.DisplayName + ":", CssClass = "dnnModuleDigitalAssetsPreviewInfoFieldLabel" }; var cellValue = new TableCell { Text = field.StringValue, CssClass = "dnnModuleDigitalAssetsPreviewInfoFieldValue" }; var rowField = new TableRow { Cells = { cellLabel, cellValue }, CssClass = "dnnModuleDigitalAssetsPreviewInfoFieldsRow" }; - FieldsTable.Rows.Add(rowField); + this.FieldsTable.Rows.Add(rowField); } } - - public List Fields { get; set; } - } } diff --git a/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs index 07b1cddb757..c8bacdf54a8 100644 --- a/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs @@ -1,29 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using DotNetNuke.Entities.Modules; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + public partial class PreviewPanelControl : System.Web.UI.UserControl - { - #region Protected Properties + { protected string Title { get { - return PreviewInfo.Title; + return this.PreviewInfo.Title; } } - + protected string PreviewImageUrl - { + { get { - return PreviewInfo.PreviewImageUrl; + return this.PreviewInfo.PreviewImageUrl; } } @@ -31,30 +30,27 @@ protected string PreviewImageUrl protected IDigitalAssetsController Controller { get; private set; } - protected ModuleInfo ModuleConfiguration { get; private set; } - #endregion - - #region Public Methods + protected ModuleInfo ModuleConfiguration { get; private set; } + public void SetPreviewInfo(PreviewInfoViewModel previewInfoViewModel) { - PreviewInfo = previewInfoViewModel; - if (FieldsControl != null && PreviewInfo != null) + this.PreviewInfo = previewInfoViewModel; + if (this.FieldsControl != null && this.PreviewInfo != null) { - var fieldsControl = ((PreviewFieldsControl)FieldsControl); - fieldsControl.Fields = PreviewInfo.Fields; + var fieldsControl = (PreviewFieldsControl)this.FieldsControl; + fieldsControl.Fields = this.PreviewInfo.Fields; fieldsControl.GenerateFieldsTable(); } } - + public void SetController(IDigitalAssetsController damController) { - Controller = damController; + this.Controller = damController; } public void SetModuleConfiguration(ModuleInfo moduleConfiguration) { - ModuleConfiguration = moduleConfiguration; - } - #endregion + this.ModuleConfiguration = moduleConfiguration; + } } } diff --git a/DNN Platform/Modules/DigitalAssets/Properties/AssemblyInfo.cs b/DNN Platform/Modules/DigitalAssets/Properties/AssemblyInfo.cs index 7aa2dfb4799..ac3d0b16bb4 100644 --- a/DNN Platform/Modules/DigitalAssets/Properties/AssemblyInfo.cs +++ b/DNN Platform/Modules/DigitalAssets/Properties/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Modules.DigitalAssets")] [assembly: AssemblyDescription("")] -// 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 +// 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)] diff --git a/DNN Platform/Modules/DigitalAssets/SearchBoxControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/SearchBoxControl.ascx.cs index a31d4949bc5..805eeb3df4a 100644 --- a/DNN Platform/Modules/DigitalAssets/SearchBoxControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/SearchBoxControl.ascx.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + public partial class SearchBoxControl : PortalModuleBase { protected override void OnInit(EventArgs e) { - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.SearchBox.js", FileOrder.Js.DefaultPriority + 10); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.SearchBox.js", FileOrder.Js.DefaultPriority + 10); } } } diff --git a/DNN Platform/Modules/DigitalAssets/Services/ContentServiceController.cs b/DNN Platform/Modules/DigitalAssets/Services/ContentServiceController.cs index a5eb80bd233..25ae0d126e0 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/ContentServiceController.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/ContentServiceController.cs @@ -1,23 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; - -using DotNetNuke.Instrumentation; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Modules.DigitalAssets.Services.Models; -using DotNetNuke.Security; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services { - [SupportedModules("DotNetNuke.Modules.DigitalAssets")] + using System; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Modules.DigitalAssets.Services.Models; + using DotNetNuke.Security; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Web.Api; + + [SupportedModules("DotNetNuke.Modules.DigitalAssets")] [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] [DamExceptionFilter] public class ContentServiceController : DnnApiController @@ -27,7 +27,7 @@ public class ContentServiceController : DnnApiController public ContentServiceController() { var f = new Factory(); - DigitalAssetsController = f.DigitalAssetsController; + this.DigitalAssetsController = f.DigitalAssetsController; } protected IDigitalAssetsController DigitalAssetsController { get; private set; } @@ -36,132 +36,131 @@ public ContentServiceController() [ValidateAntiForgeryToken] public HttpResponseMessage GetFolderContent(GetFolderContentRequest r) { - var moduleId = Request.FindModuleId(); - var p = DigitalAssetsController.GetFolderContent(moduleId, r.FolderId, r.StartIndex, r.NumItems, r.SortExpression); - return Request.CreateResponse(HttpStatusCode.OK, p); + var moduleId = this.Request.FindModuleId(); + var p = this.DigitalAssetsController.GetFolderContent(moduleId, r.FolderId, r.StartIndex, r.NumItems, r.SortExpression); + return this.Request.CreateResponse(HttpStatusCode.OK, p); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage SearchFolderContent(SearchFolderContentRequest r) { - var moduleId = Request.FindModuleId(); - var p = DigitalAssetsController.SearchFolderContent(moduleId, r.FolderId, r.Pattern, r.StartIndex, r.NumItems, r.SortExpression); - return Request.CreateResponse(HttpStatusCode.OK, p); + var moduleId = this.Request.FindModuleId(); + var p = this.DigitalAssetsController.SearchFolderContent(moduleId, r.FolderId, r.Pattern, r.StartIndex, r.NumItems, r.SortExpression); + return this.Request.CreateResponse(HttpStatusCode.OK, p); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage DeleteItems(DeleteItemsRequest request) { - var notDeletedItems = DigitalAssetsController.DeleteItems(request.Items); - return Request.CreateResponse(HttpStatusCode.OK, notDeletedItems); + var notDeletedItems = this.DigitalAssetsController.DeleteItems(request.Items); + return this.Request.CreateResponse(HttpStatusCode.OK, notDeletedItems); } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage UnlinkFolder(UnlinkFolderRequest request) { - DigitalAssetsController.UnlinkFolder(request.FolderId); - return Request.CreateResponse(HttpStatusCode.OK); + this.DigitalAssetsController.UnlinkFolder(request.FolderId); + return this.Request.CreateResponse(HttpStatusCode.OK); } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage GetMappedSubfoldersCount(MappedPathSubFoldersCountRequest request) { - var mappedSubfoldersCount = DigitalAssetsController.GetMappedSubFoldersCount(request.Items, PortalSettings.PortalId); - return Request.CreateResponse(HttpStatusCode.OK, mappedSubfoldersCount); + var mappedSubfoldersCount = this.DigitalAssetsController.GetMappedSubFoldersCount(request.Items, this.PortalSettings.PortalId); + return this.Request.CreateResponse(HttpStatusCode.OK, mappedSubfoldersCount); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage RenameFile(RenameFileRequest request) { - try - { - var itemViewModel = DigitalAssetsController.RenameFile(request.FileId, request.NewFileName); - return Request.CreateResponse(HttpStatusCode.OK, itemViewModel); - } - catch (FileAlreadyExistsException ex) - { - return Request.CreateResponse(HttpStatusCode.InternalServerError, ex); - } - + try + { + var itemViewModel = this.DigitalAssetsController.RenameFile(request.FileId, request.NewFileName); + return this.Request.CreateResponse(HttpStatusCode.OK, itemViewModel); + } + catch (FileAlreadyExistsException ex) + { + return this.Request.CreateResponse(HttpStatusCode.InternalServerError, ex); + } } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage CopyFile(CopyMoveItemRequest request) { - var copyFileResponse = DigitalAssetsController.CopyFile(request.ItemId, request.DestinationFolderId, request.Overwrite); - return Request.CreateResponse(HttpStatusCode.OK, copyFileResponse); + var copyFileResponse = this.DigitalAssetsController.CopyFile(request.ItemId, request.DestinationFolderId, request.Overwrite); + return this.Request.CreateResponse(HttpStatusCode.OK, copyFileResponse); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage MoveFile(CopyMoveItemRequest request) { - var copyMoveFileResponse = DigitalAssetsController.MoveFile(request.ItemId, request.DestinationFolderId, request.Overwrite); - return Request.CreateResponse(HttpStatusCode.OK, copyMoveFileResponse); + var copyMoveFileResponse = this.DigitalAssetsController.MoveFile(request.ItemId, request.DestinationFolderId, request.Overwrite); + return this.Request.CreateResponse(HttpStatusCode.OK, copyMoveFileResponse); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage MoveFolder(CopyMoveItemRequest request) { - var copyMoveFolderResponse = DigitalAssetsController.MoveFolder(request.ItemId, request.DestinationFolderId, request.Overwrite); - return Request.CreateResponse(HttpStatusCode.OK, copyMoveFolderResponse); + var copyMoveFolderResponse = this.DigitalAssetsController.MoveFolder(request.ItemId, request.DestinationFolderId, request.Overwrite); + return this.Request.CreateResponse(HttpStatusCode.OK, copyMoveFolderResponse); } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage GetSubFolders(GetSubFolderRequest request) { - var moduleId = Request.FindModuleId(); - var subFolders = DigitalAssetsController.GetFolders(moduleId, request.FolderId).ToList(); - return Request.CreateResponse(HttpStatusCode.OK, subFolders); + var moduleId = this.Request.FindModuleId(); + var subFolders = this.DigitalAssetsController.GetFolders(moduleId, request.FolderId).ToList(); + return this.Request.CreateResponse(HttpStatusCode.OK, subFolders); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage RenameFolder(RenameFolderRequest request) { - DigitalAssetsController.RenameFolder(request.FolderId, request.NewFolderName); - return Request.CreateResponse(HttpStatusCode.OK, "Success"); + this.DigitalAssetsController.RenameFolder(request.FolderId, request.NewFolderName); + return this.Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage CreateNewFolder(CreateNewFolderRequest request) { - var folder = DigitalAssetsController.CreateFolder(request.FolderName, request.ParentFolderId, + var folder = this.DigitalAssetsController.CreateFolder(request.FolderName, request.ParentFolderId, request.FolderMappingId, request.MappedName); - return Request.CreateResponse(HttpStatusCode.OK, folder); + return this.Request.CreateResponse(HttpStatusCode.OK, folder); } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage SynchronizeFolder(SynchronizeFolderRequest request) { - DigitalAssetsController.SyncFolderContent(request.FolderId, request.Recursive); - return Request.CreateResponse(HttpStatusCode.OK, "Success"); + this.DigitalAssetsController.SyncFolderContent(request.FolderId, request.Recursive); + return this.Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpPost] - [ValidateAntiForgeryToken] + [ValidateAntiForgeryToken] public HttpResponseMessage UnzipFile(UnzipFileRequest request) { - var model = DigitalAssetsController.UnzipFile(request.FileId, request.Overwrite); - return Request.CreateResponse(HttpStatusCode.OK, model); + var model = this.DigitalAssetsController.UnzipFile(request.FileId, request.Overwrite); + return this.Request.CreateResponse(HttpStatusCode.OK, model); } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage GetUrl(GetUrlRequest request) { - var url = DigitalAssetsController.GetUrl(request.FileId); - return Request.CreateResponse(HttpStatusCode.OK, url); + var url = this.DigitalAssetsController.GetUrl(request.FileId); + return this.Request.CreateResponse(HttpStatusCode.OK, url); } } } diff --git a/DNN Platform/Modules/DigitalAssets/Services/DamExceptionFilterAttribute.cs b/DNN Platform/Modules/DigitalAssets/Services/DamExceptionFilterAttribute.cs index ebcc2480197..5ad27d5cf53 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/DamExceptionFilterAttribute.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/DamExceptionFilterAttribute.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Net; -using System.Net.Http; -using System.Web.Http.Filters; - -using DotNetNuke.Services.Exceptions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services { + using System.Net; + using System.Net.Http; + using System.Web.Http.Filters; + + using DotNetNuke.Services.Exceptions; + public class DamExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) diff --git a/DNN Platform/Modules/DigitalAssets/Services/DownloadServiceController.cs b/DNN Platform/Modules/DigitalAssets/Services/DownloadServiceController.cs index 02dd8f766a5..c344371042b 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/DownloadServiceController.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/DownloadServiceController.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Web.Http; - -using DotNetNuke.Instrumentation; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Security; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services { + using System; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Web.Http; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Security; + using DotNetNuke.Web.Api; + [SupportedModules("DotNetNuke.Modules.DigitalAssets")] [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] [DamExceptionFilter] @@ -25,7 +25,7 @@ public class DownloadServiceController : DnnApiController public DownloadServiceController() { var f = new Factory(); - DigitalAssetsController = f.DigitalAssetsController; + this.DigitalAssetsController = f.DigitalAssetsController; } protected IDigitalAssetsController DigitalAssetsController { get; private set; } @@ -36,12 +36,12 @@ public HttpResponseMessage Download(int fileId, bool forceDownload) var result = new HttpResponseMessage(HttpStatusCode.OK); string fileName; string contentType; - var streamContent = DigitalAssetsController.GetFileContent(fileId, out fileName, out contentType); + var streamContent = this.DigitalAssetsController.GetFileContent(fileId, out fileName, out contentType); result.Content = new StreamContent(streamContent); result.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(forceDownload ? "attachment" : "inline"); result.Content.Headers.ContentDisposition.FileName = fileName; return result; - } + } } } diff --git a/DNN Platform/Modules/DigitalAssets/Services/Factory.cs b/DNN Platform/Modules/DigitalAssets/Services/Factory.cs index 341c8fcfd5f..de273e8cd70 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Factory.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Factory.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.Linq; - -using DotNetNuke.ExtensionPoints; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services { + using System; + using System.Collections.Generic; + using System.ComponentModel.Composition; + using System.Linq; + + using DotNetNuke.ExtensionPoints; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + public class Factory { #pragma warning disable 649 @@ -21,15 +21,15 @@ public class Factory public Factory() { - ExtensionPointManager.ComposeParts(this); + ExtensionPointManager.ComposeParts(this); } public IDigitalAssetsController DigitalAssetsController { get { - var dac = controllers.SingleOrDefault(c => c.Metadata.Edition == "PE"); - return dac != null ? dac.Value : controllers.Single(c => c.Metadata.Edition == "CE").Value; + var dac = this.controllers.SingleOrDefault(c => c.Metadata.Edition == "PE"); + return dac != null ? dac.Value : this.controllers.Single(c => c.Metadata.Edition == "CE").Value; } } } diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/CopyMoveItemRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/CopyMoveItemRequest.cs index 7a7fc29e949..1643f411b87 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/CopyMoveItemRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/CopyMoveItemRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class CopyMoveItemRequest @@ -10,6 +10,6 @@ public class CopyMoveItemRequest public int DestinationFolderId { get; set; } - public bool Overwrite { get; set; } + public bool Overwrite { get; set; } } } diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/CreateNewFolderRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/CreateNewFolderRequest.cs index 7d3b9d44f32..58545519be1 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/CreateNewFolderRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/CreateNewFolderRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class CreateNewFolderRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItem.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItem.cs index cb80e355924..25774d4ebfe 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItem.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItem.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class DeleteItem diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItemsRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItemsRequest.cs index deeaae63186..40f700a1998 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItemsRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/DeleteItemsRequest.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { + using System.Collections.Generic; + public class DeleteItemsRequest { public IEnumerable Items { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/GetFolderContentRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/GetFolderContentRequest.cs index 963e69247c2..4e38b59d5e4 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/GetFolderContentRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/GetFolderContentRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class GetFolderContentRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/GetSubFolderRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/GetSubFolderRequest.cs index ea905f312ba..6c1c1973e4a 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/GetSubFolderRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/GetSubFolderRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class GetSubFolderRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/GetUrlRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/GetUrlRequest.cs index 8a72ba46148..bfaae1af5d1 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/GetUrlRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/GetUrlRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class GetUrlRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/MappedPathSubFoldersCountRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/MappedPathSubFoldersCountRequest.cs index 954d116cb3f..138415ef28b 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/MappedPathSubFoldersCountRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/MappedPathSubFoldersCountRequest.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { + using System.Collections.Generic; + + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + public class MappedPathSubFoldersCountRequest { public IEnumerable Items { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFileRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFileRequest.cs index d1a91f432cd..92ba07c1541 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFileRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFileRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class RenameFileRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFolderRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFolderRequest.cs index f6bc01c7e6d..72feb9c884a 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFolderRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/RenameFolderRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class RenameFolderRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/SearchFolderContentRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/SearchFolderContentRequest.cs index e766eba7f44..039a10604fd 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/SearchFolderContentRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/SearchFolderContentRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class SearchFolderContentRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/SynchronizeFolderRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/SynchronizeFolderRequest.cs index 89db7f629b1..3af9dc6a4b6 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/SynchronizeFolderRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/SynchronizeFolderRequest.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + public class SynchronizeFolderRequest { public int FolderId { get; set; } diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/UnlinkFolderRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/UnlinkFolderRequest.cs index 15065fdc11d..99fc49200be 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/UnlinkFolderRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/UnlinkFolderRequest.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class UnlinkFolderRequest diff --git a/DNN Platform/Modules/DigitalAssets/Services/Models/UnzipFileRequest.cs b/DNN Platform/Modules/DigitalAssets/Services/Models/UnzipFileRequest.cs index ed453f2e406..17df98cc663 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/Models/UnzipFileRequest.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/Models/UnzipFileRequest.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services.Models { public class UnzipFileRequest { public int FileId { get; set; } - public bool Overwrite { get; set; } + public bool Overwrite { get; set; } } } diff --git a/DNN Platform/Modules/DigitalAssets/Services/ServiceRouteMapper.cs b/DNN Platform/Modules/DigitalAssets/Services/ServiceRouteMapper.cs index cc8f46463f5..1f7f49e243e 100644 --- a/DNN Platform/Modules/DigitalAssets/Services/ServiceRouteMapper.cs +++ b/DNN Platform/Modules/DigitalAssets/Services/ServiceRouteMapper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets.Services { + using DotNetNuke.Web.Api; + public class ServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) diff --git a/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs b/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs index 6cbd335eba3..110e72cc3f1 100644 --- a/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Services.Assets; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Collections.Generic; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Services.Assets; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + public partial class Settings : ModuleSettingsBase { private static readonly DigitalAssetsSettingsRepository SettingsRepository = new DigitalAssetsSettingsRepository(); @@ -25,7 +25,7 @@ private DigitalAssestsMode SelectedDigitalAssestsMode get { DigitalAssestsMode mode; - Enum.TryParse(ModeComboBox.SelectedValue, true, out mode); + Enum.TryParse(this.ModeComboBox.SelectedValue, true, out mode); return mode; } } @@ -35,42 +35,37 @@ private FilterCondition SelectedFilterCondition get { FilterCondition filterCondition; - Enum.TryParse(FilterOptionsRadioButtonsList.SelectedValue, true, out filterCondition); + Enum.TryParse(this.FilterOptionsRadioButtonsList.SelectedValue, true, out filterCondition); return filterCondition; } } - protected override void OnInit(EventArgs e) - { - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.FilterViewSettings.js", FileOrder.Js.DefaultPriority); - } - /// ----------------------------------------------------------------------------- /// - /// LoadSettings loads the settings from the Database and displays them + /// LoadSettings loads the settings from the Database and displays them. /// /// ----------------------------------------------------------------------------- public override void LoadSettings() { - if (Page.IsPostBack) + if (this.Page.IsPostBack) { return; } try { - DefaultFolderTypeComboBox.DataSource = FolderMappingController.Instance.GetFolderMappings(PortalId); - DefaultFolderTypeComboBox.DataBind(); + this.DefaultFolderTypeComboBox.DataSource = FolderMappingController.Instance.GetFolderMappings(this.PortalId); + this.DefaultFolderTypeComboBox.DataBind(); - var defaultFolderTypeId = new DigitalAssetsController().GetDefaultFolderTypeId(ModuleId); + var defaultFolderTypeId = new DigitalAssetsController().GetDefaultFolderTypeId(this.ModuleId); if (defaultFolderTypeId.HasValue) { - DefaultFolderTypeComboBox.SelectedValue = defaultFolderTypeId.ToString(); + this.DefaultFolderTypeComboBox.SelectedValue = defaultFolderTypeId.ToString(); } - ModeComboBox.SelectedValue = SettingsRepository.GetMode(ModuleId).ToString(); + this.ModeComboBox.SelectedValue = SettingsRepository.GetMode(this.ModuleId).ToString(); - LoadFilterViewSettings(); + this.LoadFilterViewSettings(); } catch (Exception exc) { @@ -80,21 +75,24 @@ public override void LoadSettings() /// ----------------------------------------------------------------------------- /// - /// UpdateSettings saves the modified settings to the Database + /// UpdateSettings saves the modified settings to the Database. /// /// ----------------------------------------------------------------------------- public override void UpdateSettings() { - Page.Validate(); - if (!Page.IsValid) return; - + this.Page.Validate(); + if (!this.Page.IsValid) + { + return; + } + try { - SettingsRepository.SaveDefaultFolderTypeId(ModuleId, Convert.ToInt32(DefaultFolderTypeComboBox.SelectedValue)); - - SettingsRepository.SaveMode(ModuleId, SelectedDigitalAssestsMode); + SettingsRepository.SaveDefaultFolderTypeId(this.ModuleId, Convert.ToInt32(this.DefaultFolderTypeComboBox.SelectedValue)); - UpdateFilterViewSettings(); + SettingsRepository.SaveMode(this.ModuleId, this.SelectedDigitalAssestsMode); + + this.UpdateFilterViewSettings(); } catch (Exception exc) { @@ -102,9 +100,14 @@ public override void UpdateSettings() } } + protected override void OnInit(EventArgs e) + { + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.FilterViewSettings.js", FileOrder.Js.DefaultPriority); + } + protected void ValidateFolderIsSelected(object source, ServerValidateEventArgs args) { - if (SelectedFilterCondition == FilterCondition.FilterByFolder && FilterByFolderDropDownList.SelectedFolder == null) + if (this.SelectedFilterCondition == FilterCondition.FilterByFolder && this.FilterByFolderDropDownList.SelectedFolder == null) { args.IsValid = false; return; @@ -115,39 +118,39 @@ protected void ValidateFolderIsSelected(object source, ServerValidateEventArgs a private void LoadFilterViewSettings() { - //handle upgrades where FilterCondition didn't exist - SettingsRepository.SetDefaultFilterCondition(ModuleId); + // handle upgrades where FilterCondition didn't exist + SettingsRepository.SetDefaultFilterCondition(this.ModuleId); + + this.FilterOptionsRadioButtonsList.SelectedValue = SettingsRepository.GetFilterCondition(this.ModuleId).ToString(); + this.SubfolderFilterRadioButtonList.SelectedValue = SettingsRepository.GetSubfolderFilter(this.ModuleId).ToString(); - FilterOptionsRadioButtonsList.SelectedValue = SettingsRepository.GetFilterCondition(ModuleId).ToString(); - SubfolderFilterRadioButtonList.SelectedValue = SettingsRepository.GetSubfolderFilter(ModuleId).ToString(); - - if (FilterOptionsRadioButtonsList.SelectedValue == FilterCondition.FilterByFolder.ToString()) + if (this.FilterOptionsRadioButtonsList.SelectedValue == FilterCondition.FilterByFolder.ToString()) { - var folderId = SettingsRepository.GetRootFolderId(ModuleId); + var folderId = SettingsRepository.GetRootFolderId(this.ModuleId); if (folderId.HasValue) { var folder = FolderManager.Instance.GetFolder(folderId.Value); - FilterByFolderDropDownList.SelectedFolder = folder; + this.FilterByFolderDropDownList.SelectedFolder = folder; } } } private void UpdateFilterViewSettings() { - var filterCondition = SelectedDigitalAssestsMode != DigitalAssestsMode.Normal ? FilterCondition.NotSet : SelectedFilterCondition; + var filterCondition = this.SelectedDigitalAssestsMode != DigitalAssestsMode.Normal ? FilterCondition.NotSet : this.SelectedFilterCondition; - SettingsRepository.SaveFilterCondition(ModuleId, filterCondition); + SettingsRepository.SaveFilterCondition(this.ModuleId, filterCondition); switch (filterCondition) { case FilterCondition.NotSet: - SettingsRepository.SaveExcludeSubfolders(ModuleId, SubfolderFilter.IncludeSubfoldersFolderStructure); + SettingsRepository.SaveExcludeSubfolders(this.ModuleId, SubfolderFilter.IncludeSubfoldersFolderStructure); break; case FilterCondition.FilterByFolder: SubfolderFilter subfolderFilter; - Enum.TryParse(SubfolderFilterRadioButtonList.SelectedValue, true, out subfolderFilter); - SettingsRepository.SaveExcludeSubfolders(ModuleId, subfolderFilter); - SettingsRepository.SaveRootFolderId(ModuleId, FilterByFolderDropDownList.SelectedFolder.FolderID); + Enum.TryParse(this.SubfolderFilterRadioButtonList.SelectedValue, true, out subfolderFilter); + SettingsRepository.SaveExcludeSubfolders(this.ModuleId, subfolderFilter); + SettingsRepository.SaveRootFolderId(this.ModuleId, this.FilterByFolderDropDownList.SelectedFolder.FolderID); break; } } diff --git a/DNN Platform/Modules/DigitalAssets/View.ascx.cs b/DNN Platform/Modules/DigitalAssets/View.ascx.cs index 9a0cb2389a8..c86396010b0 100644 --- a/DNN Platform/Modules/DigitalAssets/View.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/View.ascx.cs @@ -1,46 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.ExtensionPoints; -using DotNetNuke.ExtensionPoints.Filters; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers; -using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; -using DotNetNuke.Modules.DigitalAssets.Services; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Assets; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls; - -using Telerik.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.DigitalAssets { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.ExtensionPoints; + using DotNetNuke.ExtensionPoints.Filters; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers; + using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; + using DotNetNuke.Modules.DigitalAssets.Services; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Assets; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + using Telerik.Web.UI; + public partial class View : PortalModuleBase, IActionable { private static readonly DigitalAssetsSettingsRepository SettingsRepository = new DigitalAssetsSettingsRepository(); @@ -50,43 +49,41 @@ public partial class View : PortalModuleBase, IActionable private NameValueCollection damState; private readonly INavigationManager _navigationManager; + public View() { - controller = new Factory().DigitalAssetsController; - _navigationManager = DependencyProvider.GetRequiredService(); + this.controller = new Factory().DigitalAssetsController; + this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private IExtensionPointFilter Filter + public ModuleActionCollection ModuleActions { get { - return new CompositeFilter() - .And(new FilterByHostMenu(IsHostPortal)) - .And(new FilterByUnauthenticated(HttpContext.Current.Request.IsAuthenticated)); - } - } + var actions = new ModuleActionCollection(); + if (ModulePermissionController.CanManageModule(this.ModuleConfiguration)) + { + actions.Add(this.GetNextActionID(), Localization.GetString("ManageFolderTypes", this.LocalResourceFile), string.Empty, string.Empty, "../DesktopModules/DigitalAssets/Images/manageFolderTypes.png", this.EditUrl("FolderMappings"), false, SecurityAccessLevel.Edit, true, false); - private NameValueCollection DAMState - { - get - { - if (damState == null) + foreach (var item in this.epm.GetMenuItemExtensionPoints("DigitalAssets", "ModuleActions", this.Filter)) + { + actions.Add(this.GetNextActionID(), item.Text, string.Empty, string.Empty, item.Icon, this.EditUrl(item.Value), false, SecurityAccessLevel.Edit, true, false); + } + } + else { - var stateCookie = Request.Cookies["damState-" + UserId]; - damState = HttpUtility.ParseQueryString(Uri.UnescapeDataString(stateCookie != null ? stateCookie.Value : "")); + actions = new ModuleActionCollection(); } - return damState; + return actions; } } - - #region Protected Properties - + protected int InitialTab { get { - return controller.GetInitialTab(Request.Params, DAMState); + return this.controller.GetInitialTab(this.Request.Params, this.DAMState); } } @@ -94,15 +91,39 @@ protected bool IsHostPortal { get { - return IsHostMenu || controller.GetCurrentPortalId(ModuleId) == Null.NullInteger; + return this.IsHostMenu || this.controller.GetCurrentPortalId(this.ModuleId) == Null.NullInteger; + } + } + + private IExtensionPointFilter Filter + { + get + { + return new CompositeFilter() + .And(new FilterByHostMenu(this.IsHostPortal)) + .And(new FilterByUnauthenticated(HttpContext.Current.Request.IsAuthenticated)); } } + private NameValueCollection DAMState + { + get + { + if (this.damState == null) + { + var stateCookie = this.Request.Cookies["damState-" + this.UserId]; + this.damState = HttpUtility.ParseQueryString(Uri.UnescapeDataString(stateCookie != null ? stateCookie.Value : string.Empty)); + } + + return this.damState; + } + } + protected string InvalidCharacters { get { - return GetNoControlCharsString(controller.GetInvalidChars()); + return GetNoControlCharsString(this.controller.GetInvalidChars()); } } @@ -110,7 +131,7 @@ protected string InvalidCharactersErrorText { get { - return controller.GetInvalidCharsErrorText(); + return this.controller.GetInvalidCharsErrorText(); } } @@ -126,9 +147,9 @@ protected string NavigateUrl { get { - var url = _navigationManager.NavigateURL(TabId, "ControlKey", "mid=" + ModuleId, "ReturnUrl=" + Server.UrlEncode(_navigationManager.NavigateURL())); + var url = this._navigationManager.NavigateURL(this.TabId, "ControlKey", "mid=" + this.ModuleId, "ReturnUrl=" + this.Server.UrlEncode(this._navigationManager.NavigateURL())); - //append popUp parameter + // append popUp parameter var delimiter = url.Contains("?") ? "&" : "?"; url = string.Format("{0}{1}popUp=true", url, delimiter); @@ -148,8 +169,8 @@ protected string DefaultFolderTypeId { get { - var defaultFolderTypeId = controller.GetDefaultFolderTypeId(ModuleId); - return defaultFolderTypeId.HasValue ? defaultFolderTypeId.ToString() : ""; + var defaultFolderTypeId = this.controller.GetDefaultFolderTypeId(this.ModuleId); + return defaultFolderTypeId.HasValue ? defaultFolderTypeId.ToString() : string.Empty; } } @@ -157,17 +178,133 @@ protected bool FilteredContent { get { - return SettingsRepository.GetSubfolderFilter(ModuleId) != SubfolderFilter.IncludeSubfoldersFolderStructure; + return SettingsRepository.GetSubfolderFilter(this.ModuleId) != SubfolderFilter.IncludeSubfoldersFolderStructure; } } protected string PageSize { get; private set; } - protected string ActiveView { get; private set; } + protected string ActiveView { get; private set; } + + protected FolderViewModel RootFolderViewModel { get; private set; } + + protected override void OnLoad(EventArgs e) + { + try + { + base.OnLoad(e); + + // if (IsPostBack) return; + switch (SettingsRepository.GetMode(this.ModuleId)) + { + case DigitalAssestsMode.Group: + int groupId; + if (string.IsNullOrEmpty(this.Request["groupId"]) || !int.TryParse(this.Request["groupId"], out groupId)) + { + Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + return; + } + + var groupFolder = this.controller.GetGroupFolder(groupId, this.PortalSettings); + if (groupFolder == null) + { + Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + return; + } + + this.RootFolderViewModel = groupFolder; + break; + + case DigitalAssestsMode.User: + if (this.PortalSettings.UserId == Null.NullInteger) + { + Skin.AddModuleMessage(this, Localization.GetString("InvalidUser.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + return; + } + + this.RootFolderViewModel = this.controller.GetUserFolder(this.PortalSettings.UserInfo); + break; + + default: + // handle upgrades where FilterCondition didn't exist + SettingsRepository.SetDefaultFilterCondition(this.ModuleId); + this.RootFolderViewModel = this.controller.GetRootFolder(this.ModuleId); + break; + } + + var initialPath = string.Empty; + int folderId; + if (int.TryParse(this.Request["folderId"] ?? this.DAMState["folderId"], out folderId)) + { + var folder = FolderManager.Instance.GetFolder(folderId); + if (folder != null && folder.FolderPath.StartsWith(this.RootFolderViewModel.FolderPath)) + { + initialPath = PathUtils.Instance.RemoveTrailingSlash(folder.FolderPath.Substring(this.RootFolderViewModel.FolderPath.Length)); + } + } - #endregion + this.PageSize = this.Request["pageSize"] ?? this.DAMState["pageSize"] ?? "10"; + this.ActiveView = this.Request["view"] ?? this.DAMState["view"] ?? "gridview"; - #region Private Methods + this.Page.DataBind(); + this.InitializeTreeViews(initialPath); + this.InitializeSearchBox(); + this.InitializeFolderType(); + this.InitializeGridContextMenu(); + this.InitializeEmptySpaceContextMenu(); + + this.FolderNameRegExValidator.ErrorMessage = this.controller.GetInvalidCharsErrorText(); + this.FolderNameRegExValidator.ValidationExpression = "^([^" + Regex.Escape(this.controller.GetInvalidChars()) + "]+)$"; + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected override void OnInit(EventArgs e) + { + try + { + base.OnInit(e); + + this.fileUpload.ModuleId = this.ModuleId; + this.fileUpload.Options.Parameters.Add("isHostPortal", this.IsHostPortal ? "true" : "false"); + + ServicesFramework.Instance.RequestAjaxScriptSupport(); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + + // register the telerik core js manually + var telerikCoreJs = this.Page.ClientScript.GetWebResourceUrl(typeof(RadGrid), "Telerik.Web.UI.Common.Core.js"); + ClientResourceManager.RegisterScript(this.Page, telerikCoreJs, FileOrder.Js.jQuery + 3); + + var popupFilePath = HttpContext.Current.IsDebuggingEnabled + ? "~/js/Debug/dnn.modalpopup.js" + : "~/js/dnn.modalpopup.js"; + ClientResourceManager.RegisterScript(this.Page, popupFilePath, FileOrder.Js.DnnModalPopup); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssetsController.js", FileOrder.Js.DefaultPriority); + + var i = 1; + foreach (var script in this.epm.GetScriptItemExtensionPoints("DigitalAssets")) + { + ClientResourceManager.RegisterScript(this.Page, script.ScriptName, FileOrder.Js.DefaultPriority + i++); + } + + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.js", FileOrder.Js.DefaultPriority + i); + + this.InitializeGrid(); + this.FolderTypeComboBox.ItemDataBound += this.OnItemDataBoundFolderTypeComboBox; + + this.MainToolBar.ModuleContext = this.ModuleContext; + this.SelectionToolBar.ModuleContext = this.ModuleContext; + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private static string GetNoControlCharsString(string text) { var result = new StringBuilder(); @@ -181,34 +318,34 @@ private static string GetNoControlCharsString(string text) private void InitializeFolderType() { - FolderTypeComboBox.DataSource = controller.GetFolderMappings(ModuleId); - FolderTypeComboBox.DataBind(); + this.FolderTypeComboBox.DataSource = this.controller.GetFolderMappings(this.ModuleId); + this.FolderTypeComboBox.DataBind(); } private void InitializeGrid() { - Grid.MasterTableView.PagerStyle.PrevPageToolTip = LocalizeString("PagerPreviousPage.ToolTip"); - Grid.MasterTableView.PagerStyle.NextPageToolTip = LocalizeString("PagerNextPage.ToolTip"); - Grid.MasterTableView.PagerStyle.FirstPageToolTip = LocalizeString("PagerFirstPage.ToolTip"); - Grid.MasterTableView.PagerStyle.LastPageToolTip = LocalizeString("PagerLastPage.ToolTip"); - Grid.MasterTableView.PagerStyle.PageSizeLabelText = LocalizeString("PagerPageSize.Text"); + this.Grid.MasterTableView.PagerStyle.PrevPageToolTip = this.LocalizeString("PagerPreviousPage.ToolTip"); + this.Grid.MasterTableView.PagerStyle.NextPageToolTip = this.LocalizeString("PagerNextPage.ToolTip"); + this.Grid.MasterTableView.PagerStyle.FirstPageToolTip = this.LocalizeString("PagerFirstPage.ToolTip"); + this.Grid.MasterTableView.PagerStyle.LastPageToolTip = this.LocalizeString("PagerLastPage.ToolTip"); + this.Grid.MasterTableView.PagerStyle.PageSizeLabelText = this.LocalizeString("PagerPageSize.Text"); - foreach (var columnExtension in epm.GetGridColumnExtensionPoints("DigitalAssets", "GridColumns", Filter)) + foreach (var columnExtension in this.epm.GetGridColumnExtensionPoints("DigitalAssets", "GridColumns", this.Filter)) { - var column = new DnnGridBoundColumn - { - HeaderText = columnExtension.HeaderText, - DataField = columnExtension.DataField, - UniqueName = columnExtension.UniqueName, - ReadOnly = columnExtension.ReadOnly, - Reorderable = columnExtension.Reorderable, - SortExpression = columnExtension.SortExpression, - HeaderTooltip = columnExtension.HeaderText - }; + var column = new DnnGridBoundColumn + { + HeaderText = columnExtension.HeaderText, + DataField = columnExtension.DataField, + UniqueName = columnExtension.UniqueName, + ReadOnly = columnExtension.ReadOnly, + Reorderable = columnExtension.Reorderable, + SortExpression = columnExtension.SortExpression, + HeaderTooltip = columnExtension.HeaderText, + }; column.HeaderStyle.Width = columnExtension.HeaderStyleWidth; - var index = Math.Min(columnExtension.ColumnAt, Grid.Columns.Count - 1); - Grid.Columns.AddAt(index, column); + var index = Math.Min(columnExtension.ColumnAt, this.Grid.Columns.Count - 1); + this.Grid.Columns.AddAt(index, column); } } @@ -216,12 +353,12 @@ private void LoadSubfolders(DnnTreeNode node, int folderId, string nextFolderNam { nextNode = null; nextFolderId = 0; - var folders = controller.GetFolders(ModuleId, folderId); + var folders = this.controller.GetFolders(this.ModuleId, folderId); foreach (var folder in folders) { - var hasViewPermissions = HasViewPermissions(folder.Permissions); + var hasViewPermissions = this.HasViewPermissions(folder.Permissions); var newNode = this.CreateNodeFromFolder(folder); - SetupNodeAttributes(newNode, folder.Permissions, folder); + this.SetupNodeAttributes(newNode, folder.Permissions, folder); node.Nodes.Add(newNode); @@ -236,7 +373,7 @@ private void LoadSubfolders(DnnTreeNode node, int folderId, string nextFolderNam private void InitializeTreeViews(string initialPath) { - var rootFolder = RootFolderViewModel; + var rootFolder = this.RootFolderViewModel; var rootNode = this.CreateNodeFromFolder(rootFolder); rootNode.Selected = true; @@ -246,7 +383,7 @@ private void InitializeTreeViews(string initialPath) var nextNode = rootNode; foreach (var folderName in initialPath.Split('/')) { - LoadSubfolders(nextNode, folderId, folderName, out nextNode, out folderId); + this.LoadSubfolders(nextNode, folderId, folderName, out nextNode, out folderId); if (nextNode == null) { // The requested folder does not exist or the user does not have permissions @@ -266,15 +403,15 @@ private void InitializeTreeViews(string initialPath) this.SetExpandable(rootNode, false); } - SetupNodeAttributes(rootNode, GetPermissionsForRootFolder(rootFolder.Permissions), rootFolder); + this.SetupNodeAttributes(rootNode, this.GetPermissionsForRootFolder(rootFolder.Permissions), rootFolder); - FolderTreeView.Nodes.Clear(); - DestinationTreeView.Nodes.Clear(); + this.FolderTreeView.Nodes.Clear(); + this.DestinationTreeView.Nodes.Clear(); - FolderTreeView.Nodes.Add(rootNode); - DestinationTreeView.Nodes.Add(rootNode.Clone()); + this.FolderTreeView.Nodes.Add(rootNode); + this.DestinationTreeView.Nodes.Add(rootNode.Clone()); - InitializeTreeViewContextMenu(); + this.InitializeTreeViewContextMenu(); } private DnnTreeNode CreateNodeFromFolder(FolderViewModel folder) @@ -286,7 +423,7 @@ private DnnTreeNode CreateNodeFromFolder(FolderViewModel folder) Value = folder.FolderID.ToString(CultureInfo.InvariantCulture), Category = folder.FolderMappingID.ToString(CultureInfo.InvariantCulture), }; - this.SetExpandable(node, folder.HasChildren && HasViewPermissions(folder.Permissions)); + this.SetExpandable(node, folder.HasChildren && this.HasViewPermissions(folder.Permissions)); return node; } @@ -306,195 +443,195 @@ private void SetupNodeAttributes(DnnTreeNode node, IEnumerable - + Digital Asset Management DotNetNuke Corporation Digital Asset Management module Images/Files_32x32_Standard.png diff --git a/DNN Platform/Modules/DigitalAssets/packages.config b/DNN Platform/Modules/DigitalAssets/packages.config index 4073d3c4617..78db8377d2d 100644 --- a/DNN Platform/Modules/DigitalAssets/packages.config +++ b/DNN Platform/Modules/DigitalAssets/packages.config @@ -1,10 +1,11 @@ - - - - - - - - - + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs index b8ea6c54a35..96007bd709f 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs @@ -1,37 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.IO.Compression; -using System.IO.MemoryMappedFiles; -using System.Linq; -using System.Text; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Common { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.IO.Compression; + using System.IO.MemoryMappedFiles; + using System.Linq; + using System.Text; + public static class CompressionUtil { /// /// Compress a full folder. /// - /// Full path of folder to compress - /// Full path of the archived file + /// Full path of folder to compress. + /// Full path of the archived file. public static void ZipFolder(string folderPath, string archivePath) { - if (File.Exists(archivePath)) - File.Delete(archivePath); + if (File.Exists(archivePath)) + { + File.Delete(archivePath); + } + ZipFile.CreateFromDirectory(folderPath, archivePath, CompressionLevel.Fastest, false); } /// /// Unzip compressed file to a folder. /// - /// Full path to archive with name - /// Full path to the target folder + /// Full path to archive with name. + /// Full path to the target folder. /// Overwrites the files on target if true. public static void UnZipArchive(string archivePath, string extractFolder, bool overwrite = true) { @@ -41,15 +44,19 @@ public static void UnZipArchive(string archivePath, string extractFolder, bool o /// /// Unzip compressed file to a folder. /// - /// Full path to archive with name - /// Full path to the target folder + /// Full path to archive with name. + /// Full path to the target folder. /// Overwrites the files on target if true. /// List of files to exlude from extraction. - /// Delete the files from the archive after extraction + /// Delete the files from the archive after extraction. public static void UnZipArchiveExcept(string archivePath, string extractFolder, bool overwrite = true, IEnumerable exceptionList = null, bool deleteFromSoure = false) { - if (!File.Exists(archivePath)) return; + if (!File.Exists(archivePath)) + { + return; + } + using (var archive = OpenCreate(archivePath)) { foreach ( @@ -58,16 +65,23 @@ var entry in entry => ((exceptionList != null && !exceptionList.Contains(entry.FullName)) || exceptionList == null) && - !entry.FullName.EndsWith("\\") && !entry.FullName.EndsWith("/") && entry.Length > 0) - ) + !entry.FullName.EndsWith("\\") && !entry.FullName.EndsWith("/") && entry.Length > 0)) { var path = Path.GetDirectoryName(Path.Combine(extractFolder, entry.FullName)); - if (!string.IsNullOrEmpty(path) && !Directory.Exists(path)) - Directory.CreateDirectory(path); - if (!File.Exists(Path.Combine(extractFolder, entry.FullName)) || overwrite) - entry.ExtractToFile(Path.Combine(extractFolder, entry.FullName), overwrite); - if (deleteFromSoure) - entry.Delete(); + if (!string.IsNullOrEmpty(path) && !Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + if (!File.Exists(Path.Combine(extractFolder, entry.FullName)) || overwrite) + { + entry.ExtractToFile(Path.Combine(extractFolder, entry.FullName), overwrite); + } + + if (deleteFromSoure) + { + entry.Delete(); + } } } } @@ -76,42 +90,57 @@ var entry in /// Unzip a single file from an archive. /// /// Name of the file to extract. This name should match the entry name in the archive. i.e. it should include complete folder structure inside the archive. - /// Full path to archive with name - /// Full path to the target folder + /// Full path to archive with name. + /// Full path to the target folder. /// Overwrites the file on target if true. - /// Delete the file from the archive after extraction + /// Delete the file from the archive after extraction. public static void UnZipFileFromArchive(string fileName, string archivePath, string extractFolder, bool overwrite = true, bool deleteFromSoure = false) { - if (!File.Exists(archivePath)) return; + if (!File.Exists(archivePath)) + { + return; + } + using (var archive = OpenCreate(archivePath)) { var fileUnzipFullName = Path.Combine(extractFolder, fileName); - if (File.Exists(fileUnzipFullName) && !overwrite) - return; - + if (File.Exists(fileUnzipFullName) && !overwrite) + { + return; + } + var fileEntry = archive.GetEntry(fileName); - if (!File.Exists(Path.Combine(extractFolder, fileEntry.FullName)) || overwrite) - fileEntry?.ExtractToFile(Path.Combine(extractFolder, fileName), overwrite); - if (deleteFromSoure) - fileEntry?.Delete(); + if (!File.Exists(Path.Combine(extractFolder, fileEntry.FullName)) || overwrite) + { + fileEntry?.ExtractToFile(Path.Combine(extractFolder, fileName), overwrite); + } + + if (deleteFromSoure) + { + fileEntry?.Delete(); + } } } /// /// Add files to an archive. If no archive exists, new one is created. /// - /// Source archive to write the files to + /// Source archive to write the files to. /// List containing path of files to add to archive. /// Starting index(Index in file url) of the root folder in archive based on what the folder structure starts in archive. - /// e.g. if file url is c:\\dnn\files\archived\foldername\1\file.jpg and we want to add all files in foldername folder - /// then the folder offset would be starting index of foldername + /// e.g. if file url is c:\\dnn\files\archived\foldername\1\file.jpg and we want to add all files in foldername folder + /// then the folder offset would be starting index of foldername. /// Additional root folder to be added into archive. public static void AddFilesToArchive(ZipArchive archive, IEnumerable files, int folderOffset, string folder = null) { var enumerable = files as IList ?? files.ToList(); - if (!enumerable.Any()) return; + if (!enumerable.Any()) + { + return; + } + foreach (var file in enumerable.Where(File.Exists)) { AddFileToArchive(archive, file, folderOffset, folder); @@ -121,12 +150,13 @@ public static void AddFilesToArchive(ZipArchive archive, IEnumerable fil /// /// Add single file to an archive. If no archive exists, new one is created. /// - /// Full path of file to add - /// Full path of archive file + /// Full path of file to add. + /// Full path of archive file. /// Starting index(Index in file url) of the root folder in archive based on what the folder structure starts in archive. - /// e.g. if file url is c:\\dnn\files\archived\foldername\1\file.jpg and we want to add all files in foldername folder - /// then the folder offset would be starting index of foldername - /// Additional root folder to be added into archive. + /// e.g. if file url is c:\\dnn\files\archived\foldername\1\file.jpg and we want to add all files in foldername folder + /// then the folder offset would be starting index of foldername. + /// Additional root folder to be added into archive. + /// public static bool AddFileToArchive(string file, string archivePath, int folderOffset, string folder = null) { using (var archive = OpenCreate(archivePath)) @@ -136,16 +166,16 @@ public static bool AddFileToArchive(string file, string archivePath, int folderO return AddFileToArchive(archive, file, folderOffset, folder); } } + return false; - } - - #region Private Methods - + } + public static bool AddFileToArchive(ZipArchive archive, string file, int folderOffset, string folder = null) { var entryName = file.Substring(folderOffset); // Makes the name in zip based on the folder ZipArchiveEntry existingEntry; - //Deletes if the entry already exists in archive. + + // Deletes if the entry already exists in archive. if ((existingEntry = archive.GetEntry(entryName)) != null) { existingEntry.Delete(); @@ -154,10 +184,12 @@ public static bool AddFileToArchive(ZipArchive archive, string file, int folderO var fileInfo = new FileInfo(file); if (fileInfo.Length < 1610612736) { - archive.CreateEntryFromFile(file, + archive.CreateEntryFromFile( + file, string.IsNullOrEmpty(folder) ? entryName : Path.Combine(folder, entryName), CompressionLevel.Fastest); return true; } + return false; } @@ -171,8 +203,6 @@ public static ZipArchive OpenCreate(string archiveFileName) return File.Exists(archiveFileName) ? ZipFile.Open(archiveFileName, ZipArchiveMode.Update, Encoding.UTF8) : new ZipArchive(new FileStream(archiveFileName, FileMode.Create), ZipArchiveMode.Update); - } - - #endregion + } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs index 1b152c83dfe..bd120ad62d8 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs @@ -1,28 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Components.Common { + using System; + public class Constants { /// /// This is the currently supported schema version support as of this release. - /// In future releases thi must be updated to be compatible wiht th e + /// In future releases thi must be updated to be compatible wiht th e. /// public const string CurrentSchemaVersion = "1.0.2"; + // these are set by the API caller + public const string Category_Users = "USERS"; + public const string Category_Vocabularies = "VOCABULARIES"; + internal const string ExportFolder = @"\App_Data\ExportImport\"; internal const string ExportManifestName = "export.json"; // export manifest file name internal const string ExportDbName = "export.dnndb"; // export database file name internal const string ExportZipDbName = "export_db.zip"; // export compressed database file name - internal const string ExportZipFiles = "export_files.zip"; //Compressed assets file name - internal const string ExportZipTemplates = "export_templates.zip"; //Compressed templates file name - internal const string ExportZipPackages = "export_packages.zip"; //Compressed extension packages - internal const string ExportZipThemes = "export_themes.zip"; //Compressed site used themes + internal const string ExportZipFiles = "export_files.zip"; // Compressed assets file name + internal const string ExportZipTemplates = "export_templates.zip"; // Compressed templates file name + internal const string ExportZipPackages = "export_packages.zip"; // Compressed extension packages + internal const string ExportZipThemes = "export_themes.zip"; // Compressed site used themes internal const string LogTypeSiteExport = "SITE_EXPORT"; internal const string LogTypeSiteImport = "SITE_IMPORT"; @@ -36,15 +40,11 @@ public class Constants internal const int LogColumnLength = 255; - internal static DateTime MinDbTime = new DateTime(1980, 1, 1, 0, 0, 0, DateTimeKind.Utc); - internal static DateTime MaxDbTime = new DateTime(3000, 1, 1, 0, 0, 0, DateTimeKind.Utc); - internal static int MaxZipFilesMemory = 104857600;//100 MB - internal const string SharedResources = "/DesktopModules/SiteExportImport/App_LocalResources/ExportImport.resx"; - // these are set by the API caller - public const string Category_Users = "USERS"; - public const string Category_Vocabularies = "VOCABULARIES"; + internal static DateTime MinDbTime = new DateTime(1980, 1, 1, 0, 0, 0, DateTimeKind.Utc); + internal static DateTime MaxDbTime = new DateTime(3000, 1, 1, 0, 0, 0, DateTimeKind.Utc); + internal static int MaxZipFilesMemory = 104857600; // 100 MB public const string Category_Roles = "ROLES"; public const string Category_ProfileProps = "PROFILE_PROPERTIES"; public const string Category_Content = "CONTENT"; diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Enums.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Enums.cs index 1fe4d051785..2ba9a95d403 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Enums.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Enums.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Common { public enum JobType { Export = 0, // never change these numbers - Import + Import, } public enum JobStatus @@ -16,7 +16,7 @@ public enum JobStatus InProgress, Successful, Failed, - Cancelled + Cancelled, } /// @@ -25,7 +25,7 @@ public enum JobStatus public enum ExportMode { Full = 0, - Differential = 1 + Differential = 1, } /// @@ -49,6 +49,6 @@ public enum ReportLevel Verbose, Info, Warn, - Error + Error, } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/SummaryList.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/SummaryList.cs index 8e4e3cb3d8a..176e5a704f1 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/SummaryList.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/SummaryList.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using Dnn.ExportImport.Components.Dto; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Common { + using System.Collections.Generic; + using System.Linq; + + using Dnn.ExportImport.Components.Dto; + public class SummaryList : List { public new void Add(SummaryItem item) @@ -28,7 +29,7 @@ public class SummaryList : List var summaryItems = items as IList ?? items.ToList(); foreach (var summaryItem in summaryItems.OrderBy(x => x.Order)) { - Add(summaryItem); + this.Add(summaryItem); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs index 08f3ff07a1b..78e62d437c4 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs @@ -1,35 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Reflection; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Services; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.Reflections; -using DotNetNuke.Instrumentation; -using System.Text; -using System.IO; -using System.Threading; -using Dnn.ExportImport.Components.Controllers; -using Dnn.ExportImport.Components.Providers; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules.Definitions; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Common { + using System; + using System.Collections.Generic; + using System.IO; + using System.Reflection; + using System.Text; + using System.Threading; + + using Dnn.ExportImport.Components.Controllers; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Providers; + using Dnn.ExportImport.Components.Services; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.Reflections; + using DotNetNuke.Instrumentation; + using Newtonsoft.Json; + public static class Util { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Util)); private static int _noRole = Convert.ToInt32(Globals.glbRoleNothing); + // some string extension helpers public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s); + public static bool IsNullOrWhiteSpace(this string s) => string.IsNullOrWhiteSpace(s); + public static bool HasValue(this string s) => !string.IsNullOrEmpty(s); public static IEnumerable GetPortableImplementors() @@ -48,7 +52,8 @@ public static IEnumerable GetPortableImplementors() } catch (Exception e) { - Logger.ErrorFormat("Unable to create {0} while calling BasePortableService implementors. {1}", + Logger.ErrorFormat( + "Unable to create {0} while calling BasePortableService implementors. {1}", type.FullName, e.Message); portable2Type = null; } @@ -66,9 +71,21 @@ public static string FormatSize(long bytes, byte decimals = 1) const long mb = kb * kb; const long gb = mb * kb; - if (bytes < kb) return bytes + " B"; - if (bytes < mb) return (1.0 * bytes / kb).ToString("F" + decimals) + " KB"; - if (bytes < gb) return (1.0 * bytes / mb).ToString("F" + decimals) + " MB"; + if (bytes < kb) + { + return bytes + " B"; + } + + if (bytes < mb) + { + return (1.0 * bytes / kb).ToString("F" + decimals) + " KB"; + } + + if (bytes < gb) + { + return (1.0 * bytes / mb).ToString("F" + decimals) + " MB"; + } + return (1.0 * bytes / gb).ToString("F" + decimals) + " GB"; } @@ -79,34 +96,48 @@ public static string GetExpImpJobCacheKey(ExportImportJob job) public static int GetUserIdByName(ExportImportJob importJob, int? exportedUserId, string exportUsername) { - if (!exportedUserId.HasValue || exportedUserId <= 0) - return -1; - - if (exportedUserId == 1) - return 1; // default HOST user - - if (string.IsNullOrEmpty(exportUsername)) - return -1; - + if (!exportedUserId.HasValue || exportedUserId <= 0) + { + return -1; + } + + if (exportedUserId == 1) + { + return 1; // default HOST user + } + + if (string.IsNullOrEmpty(exportUsername)) + { + return -1; + } + var user = UserController.GetUserByName(importJob.PortalId, exportUsername); - if (user == null) - return -1; - + if (user == null) + { + return -1; + } + return user.UserID < 0 ? importJob.CreatedByUserId : user.UserID; } public static int? GetRoleIdByName(int portalId, int exportRoleId, string exportRolename) { - if (string.IsNullOrEmpty(exportRolename)) return null; - + if (string.IsNullOrEmpty(exportRolename)) + { + return null; + } + var roleId = DataProvider.Instance().GetRoleIdByName(exportRoleId >= 0 ? portalId : -1, exportRolename); return roleId == _noRole ? null : (int?)roleId; } public static int? GeModuleDefIdByFriendltName(string friendlyName) { - if (string.IsNullOrEmpty(friendlyName)) return null; - + if (string.IsNullOrEmpty(friendlyName)) + { + return null; + } + var moduleDefInfo = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(friendlyName); return moduleDefInfo?.ModuleDefID; } @@ -115,9 +146,11 @@ public static int GetUserIdByName(ExportImportJob importJob, int? exportedUserId { if (string.IsNullOrEmpty(permissionCode) || string.IsNullOrEmpty(permissionKey) || - string.IsNullOrEmpty(permissionName)) - return null; - + string.IsNullOrEmpty(permissionName)) + { + return null; + } + var permission = EntitiesController.Instance.GetPermissionInfo(permissionCode, permissionKey, permissionName); return permission?.PermissionID; } @@ -125,16 +158,18 @@ public static int GetUserIdByName(ExportImportJob importJob, int? exportedUserId public static int? GetProfilePropertyId(int portalId, int? exportedProfilePropertyId, string exportProfilePropertyname) { - if (!exportedProfilePropertyId.HasValue || exportedProfilePropertyId <= 0) - return -1; - + if (!exportedProfilePropertyId.HasValue || exportedProfilePropertyId <= 0) + { + return -1; + } + var property = ProfileController.GetPropertyDefinitionByName(portalId, exportProfilePropertyname); return property?.PropertyDefinitionId; } public static int CalculateTotalPages(int totalRecords, int pageSize) { - return totalRecords % pageSize == 0 ? totalRecords / pageSize : totalRecords / pageSize + 1; + return totalRecords % pageSize == 0 ? totalRecords / pageSize : (totalRecords / pageSize) + 1; } public static void WriteJson(string filePath, T item) @@ -148,7 +183,8 @@ public static void ReadJson(string filePath, ref T item) if (File.Exists(filePath)) { var content = File.ReadAllText(filePath); - //TODO: This might throw error if file is corrupt. Should we handle error here? + + // TODO: This might throw error if file is corrupt. Should we handle error here? item = JsonConvert.DeserializeObject(content); } } @@ -176,13 +212,17 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) dateTime.Millisecond, DateTimeKind.Utc); return userInfo.LocalTime(dateTime); } + return dateTime; } public static DateTime? ToLocalDateTime(DateTime? dateTime, UserInfo userInfo) { - if (dateTime != null && dateTime.Value.Kind != DateTimeKind.Local) - return userInfo.LocalTime(dateTime.Value); + if (dateTime != null && dateTime.Value.Kind != DateTimeKind.Local) + { + return userInfo.LocalTime(dateTime.Value); + } + return dateTime; } @@ -193,8 +233,16 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) /// public static DateTime? ConvertToDbLocalTime(DateTime? dateTime) { - if (dateTime == null) return null; - if (dateTime.Value.Kind != DateTimeKind.Utc) return dateTime; + if (dateTime == null) + { + return null; + } + + if (dateTime.Value.Kind != DateTimeKind.Utc) + { + return dateTime; + } + var differenceInUtcTimes = TimeZone.CurrentTimeZone.GetUtcOffset(DateUtils.GetDatabaseUtcTime()).TotalMilliseconds; var d = dateTime.Value.ToLocalTime().AddMilliseconds(differenceInUtcTimes); @@ -208,8 +256,16 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) /// public static DateTime? ConvertToDbUtcTime(DateTime? dateTime) { - if (dateTime == null) return null; - if (dateTime.Value.Kind == DateTimeKind.Utc) return dateTime; + if (dateTime == null) + { + return null; + } + + if (dateTime.Value.Kind == DateTimeKind.Utc) + { + return dateTime; + } + var differenceInUtcTimes = TimeZone.CurrentTimeZone.GetUtcOffset(DateUtils.GetDatabaseUtcTime()).TotalMilliseconds; var d = dateTime.Value.ToUniversalTime().AddMilliseconds(differenceInUtcTimes); @@ -218,7 +274,7 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) public static string GetDateTimeString(DateTime? dateTime) { - return dateTime?.ToString(Thread.CurrentThread.CurrentUICulture) ?? ""; + return dateTime?.ToString(Thread.CurrentThread.CurrentUICulture) ?? string.Empty; } public static string FormatNumber(int? number) diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs index 2162830b196..ac48ae0c359 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs @@ -1,33 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Dto.Jobs; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Services.Log.EventLog; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Interfaces; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Localization; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Controllers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Dto.Jobs; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Interfaces; + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using Newtonsoft.Json; + public class BaseController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BaseController)); - public static readonly string ExportFolder; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BaseController)); static BaseController() { @@ -38,34 +39,15 @@ static BaseController() } } - protected void AddEventLog(int portalId, int userId, int jobId, string logTypeKey) - { - var objSecurity = PortalSecurity.Instance; - var portalInfo = PortalController.Instance.GetPortal(portalId); - var userInfo = UserController.Instance.GetUser(portalId, userId); - var username = objSecurity.InputFilter(userInfo.Username, - PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - - var log = new LogInfo - { - LogTypeKey = logTypeKey, - LogPortalID = portalId, - LogPortalName = portalInfo.PortalName, - LogUserName = username, - LogUserID = userId, - }; - - log.AddProperty("JobID", jobId.ToString()); - LogController.Instance.AddLog(log); - } - public bool CancelJob(int portalId, int jobId) { var controller = EntitiesController.Instance; var job = controller.GetJobById(jobId); - if (job == null || (job.PortalId != portalId && portalId != -1)) - return false; - + if (job == null || (job.PortalId != portalId && portalId != -1)) + { + return false; + } + controller.SetJobCancelled(job); CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); return true; @@ -75,25 +57,61 @@ public bool RemoveJob(int portalId, int jobId) { var controller = EntitiesController.Instance; var job = controller.GetJobById(jobId); - if (job == null || (job.PortalId != portalId && portalId != -1)) - return false; - + if (job == null || (job.PortalId != portalId && portalId != -1)) + { + return false; + } + CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); + // if the job is running; then it will create few exceptions in the log file controller.RemoveJob(job); DeleteJobData(job); return true; } + protected void AddEventLog(int portalId, int userId, int jobId, string logTypeKey) + { + var objSecurity = PortalSecurity.Instance; + var portalInfo = PortalController.Instance.GetPortal(portalId); + var userInfo = UserController.Instance.GetUser(portalId, userId); + var username = objSecurity.InputFilter( + userInfo.Username, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); + + var log = new LogInfo + { + LogTypeKey = logTypeKey, + LogPortalID = portalId, + LogPortalName = portalInfo.PortalName, + LogUserName = username, + LogUserID = userId, + }; + + log.AddProperty("JobID", jobId.ToString()); + LogController.Instance.AddLog(log); + } + /// - /// Retrieves one page of paginated proceessed jobs - /// + /// Retrieves one page of paginated proceessed jobs. + /// + /// public AllJobsResult GetAllJobs(int portalId, int currentPortalId, int? pageSize, int? pageIndex, int? jobType, string keywords) { - if (pageIndex < 0) pageIndex = 0; - if (pageSize < 1) pageSize = 1; - else if (pageSize > 100) pageSize = 100; - + if (pageIndex < 0) + { + pageIndex = 0; + } + + if (pageSize < 1) + { + pageSize = 1; + } + else if (pageSize > 100) + { + pageSize = 100; + } + var count = EntitiesController.Instance.GetAllJobsCount(portalId, jobType, keywords); var jobs = count <= 0 ? null @@ -107,7 +125,7 @@ public AllJobsResult GetAllJobs(int portalId, int currentPortalId, int? pageSize PortalId = portalId, PortalName = portal.PortalName, TotalJobs = count, - Jobs = jobs?.Select(ToJobItem) + Jobs = jobs?.Select(ToJobItem), }; } @@ -115,9 +133,11 @@ public JobItem GetJobDetails(int portalId, int jobId) { var controller = EntitiesController.Instance; var job = controller.GetJobById(jobId); - if (portalId != -1 && job?.PortalId != portalId) - return null; - + if (portalId != -1 && job?.PortalId != portalId) + { + return null; + } + var jobItem = ToJobItem(job); jobItem.Summary = BuildJobSummary(jobId); return jobItem; @@ -134,6 +154,35 @@ public JobItem GetJobDetails(int portalId, int jobId) return EntitiesController.Instance.GetLastJobTime(portalId, jobType); } + protected internal static void BuildJobSummary(string packageId, IExportImportRepository repository, ImportExportSummary summary) + { + var summaryItems = new SummaryList(); + var implementors = Util.GetPortableImplementors(); + var exportDto = repository.GetSingleItem(); + + foreach (var implementor in implementors) + { + implementor.Repository = repository; + summaryItems.Add(new SummaryItem + { + TotalItems = implementor.GetImportTotal(), + Category = implementor.Category, + Order = implementor.Priority, + }); + } + + summary.ExportFileInfo = GetExportFileInfo(Path.Combine(ExportFolder, packageId, Constants.ExportManifestName)); + summary.FromDate = exportDto.FromDateUtc; + summary.ToDate = exportDto.ToDateUtc; + summary.SummaryItems = summaryItems; + summary.IncludeDeletions = exportDto.IncludeDeletions; + summary.IncludeContent = exportDto.IncludeContent; + summary.IncludeExtensions = exportDto.IncludeExtensions; + summary.IncludePermissions = exportDto.IncludePermissions; + summary.IncludeProfileProperties = exportDto.IncludeProperfileProperties; + summary.ExportMode = exportDto.ExportMode; + } + protected static ImportExportSummary BuildJobSummary(int jobId) { var summaryItems = new SummaryList(); @@ -155,11 +204,15 @@ protected static ImportExportSummary BuildJobSummary(int jobId) ExportMode = exportDto.ExportMode, ExportFileInfo = job.JobType == JobType.Export ? GetExportFileInfo(Path.Combine(ExportFolder, job.Directory, Constants.ExportManifestName)) - : JsonConvert.DeserializeObject(job.JobObject).ExportFileInfo + : JsonConvert.DeserializeObject(job.JobObject).ExportFileInfo, }; var checkpoints = EntitiesController.Instance.GetJobChekpoints(jobId); - if (!checkpoints.Any()) return importExportSummary; + if (!checkpoints.Any()) + { + return importExportSummary; + } + var implementors = Util.GetPortableImplementors(); summaryItems.AddRange(checkpoints.Select(checkpoint => new SummaryItem @@ -169,41 +222,12 @@ protected static ImportExportSummary BuildJobSummary(int jobId) ProgressPercentage = Convert.ToInt32(checkpoint.Progress), Category = checkpoint.Category, Order = implementors.FirstOrDefault(x => x.Category == checkpoint.Category)?.Priority ?? 0, - Completed = checkpoint.Completed + Completed = checkpoint.Completed, })); importExportSummary.SummaryItems = summaryItems; return importExportSummary; } - protected internal static void BuildJobSummary(string packageId, IExportImportRepository repository, ImportExportSummary summary) - { - var summaryItems = new SummaryList(); - var implementors = Util.GetPortableImplementors(); - var exportDto = repository.GetSingleItem(); - - foreach (var implementor in implementors) - { - implementor.Repository = repository; - summaryItems.Add(new SummaryItem - { - TotalItems = implementor.GetImportTotal(), - Category = implementor.Category, - Order = implementor.Priority - }); - } - - summary.ExportFileInfo = GetExportFileInfo(Path.Combine(ExportFolder, packageId, Constants.ExportManifestName)); - summary.FromDate = exportDto.FromDateUtc; - summary.ToDate = exportDto.ToDateUtc; - summary.SummaryItems = summaryItems; - summary.IncludeDeletions = exportDto.IncludeDeletions; - summary.IncludeContent = exportDto.IncludeContent; - summary.IncludeExtensions = exportDto.IncludeExtensions; - summary.IncludePermissions = exportDto.IncludePermissions; - summary.IncludeProfileProperties = exportDto.IncludeProperfileProperties; - summary.ExportMode = exportDto.ExportMode; - } - protected static ExportFileInfo GetExportFileInfo(string manifestPath) { ImportPackageInfo packageInfo = null; @@ -236,13 +260,17 @@ private static JobItem ToJobItem(ExportImportJob job) Description = job.Description, CreatedOn = job.CreatedOnDate, CompletedOn = job.CompletedOnDate, - ExportFile = job.CompletedOnDate.HasValue ? job.Directory : null + ExportFile = job.CompletedOnDate.HasValue ? job.Directory : null, }; } private static void DeleteJobData(ExportImportJob job) { - if (job.JobType != JobType.Export) return; + if (job.JobType != JobType.Export) + { + return; + } + var jobFolder = Path.Combine(ExportFolder, job.Directory); try { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs index 9d676e81665..de8004efa54 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Controllers { + using System; + + using DotNetNuke.Entities.Modules; + /// - /// + /// /// public class BusinessController : IUpgradeable { /// - /// + /// /// /// /// @@ -24,9 +25,10 @@ public string UpgradeModule(string version) switch (version) { case "09.01.00": - //AddNewLogTypes(); // moved to SQL migration script + // AddNewLogTypes(); // moved to SQL migration script break; } + return "Success"; } catch (Exception) diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs index 263f6fb48e9..b3e2846fbe5 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs @@ -1,186 +1,188 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Interfaces; -using Dnn.ExportImport.Components.Providers; -using Dnn.ExportImport.Components.Scheduler; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using Dnn.ExportImport.Dto.Pages; -using DotNetNuke.Entities.Host; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Scheduling; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Interfaces; + using Dnn.ExportImport.Components.Providers; + using Dnn.ExportImport.Components.Scheduler; + using Dnn.ExportImport.Dto.Pages; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Framework; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Scheduling; + public class EntitiesController : ServiceLocator, IEntitiesController { private readonly DataProvider _dataProvider = DataProvider.Instance(); - protected override Func GetFactory() - { - return () => new EntitiesController(); - } - public ExportImportJob GetFirstActiveJob() { - return CBO.Instance.FillObject(_dataProvider.GetFirstActiveJob()); + return CBO.Instance.FillObject(this._dataProvider.GetFirstActiveJob()); } public ExportImportJob GetJobById(int jobId) { - var job = CBO.Instance.FillObject(_dataProvider.GetJobById(jobId)); - //System.Diagnostics.Trace.WriteLine($"xxxxxxxxx job id={job?.JobId} IsCancelled={job?.IsCancelled} xxxxxxxxx"); + var job = CBO.Instance.FillObject(this._dataProvider.GetJobById(jobId)); + + // System.Diagnostics.Trace.WriteLine($"xxxxxxxxx job id={job?.JobId} IsCancelled={job?.IsCancelled} xxxxxxxxx"); return job; } + protected override Func GetFactory() + { + return () => new EntitiesController(); + } + public IList GetJobSummaryLog(int jobId) { - return CBO.Instance.FillCollection(_dataProvider.GetJobSummaryLog(jobId)); + return CBO.Instance.FillCollection(this._dataProvider.GetJobSummaryLog(jobId)); } public IList GetJobFullLog(int jobId) { - return CBO.Instance.FillCollection(_dataProvider.GetJobFullLog(jobId)); + return CBO.Instance.FillCollection(this._dataProvider.GetJobFullLog(jobId)); } public int GetAllJobsCount(int? portalId, int? jobType, string keywords) { - return _dataProvider.GetAllJobsCount(portalId, jobType, keywords); + return this._dataProvider.GetAllJobsCount(portalId, jobType, keywords); } public IList GetAllJobs(int? portalId, int? pageSize, int? pageIndex, int? jobType, string keywords) { return CBO.Instance.FillCollection( - _dataProvider.GetAllJobs(portalId, pageSize, pageIndex, jobType, keywords)); + this._dataProvider.GetAllJobs(portalId, pageSize, pageIndex, jobType, keywords)); } public DateTime? GetLastJobTime(int portalId, JobType jobType) { - return _dataProvider.GetLastJobTime(portalId, jobType); + return this._dataProvider.GetLastJobTime(portalId, jobType); } public void UpdateJobInfo(ExportImportJob job) { - _dataProvider.UpdateJobInfo(job.JobId, job.Name, job.Description); + this._dataProvider.UpdateJobInfo(job.JobId, job.Name, job.Description); } public void UpdateJobStatus(ExportImportJob job) { - _dataProvider.UpdateJobStatus(job.JobId, job.JobStatus); + this._dataProvider.UpdateJobStatus(job.JobId, job.JobStatus); } public void SetJobCancelled(ExportImportJob job) { - _dataProvider.SetJobCancelled(job.JobId); + this._dataProvider.SetJobCancelled(job.JobId); } public void RemoveJob(ExportImportJob job) { - _dataProvider.RemoveJob(job.JobId); + this._dataProvider.RemoveJob(job.JobId); } public IList GetJobChekpoints(int jobId) { - return CBO.Instance.FillCollection(_dataProvider.GetJobChekpoints(jobId)); + return CBO.Instance.FillCollection(this._dataProvider.GetJobChekpoints(jobId)); } public void UpdateJobChekpoint(ExportImportChekpoint checkpoint) { - _dataProvider.UpsertJobChekpoint(checkpoint); + this._dataProvider.UpsertJobChekpoint(checkpoint); } public IList GetPortalTabs(int portalId, bool includeDeleted, bool includeSystem, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllPortalTabs(portalId, includeDeleted, includeSystem, toDate, fromDate)); + this._dataProvider.GetAllPortalTabs(portalId, includeDeleted, includeSystem, toDate, fromDate)); } public IList GetTabSettings(int tabId, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllTabSettings(tabId, toDate, fromDate)); + this._dataProvider.GetAllTabSettings(tabId, toDate, fromDate)); } public IList GetTabPermissions(int tabId, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllTabPermissions(tabId, toDate, fromDate)); + this._dataProvider.GetAllTabPermissions(tabId, toDate, fromDate)); } public IList GetTabUrls(int tabId, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllTabUrls(tabId, toDate, fromDate)); + this._dataProvider.GetAllTabUrls(tabId, toDate, fromDate)); } public IList GetModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllModules(tabId, includeDeleted, toDate, fromDate)); + this._dataProvider.GetAllModules(tabId, includeDeleted, toDate, fromDate)); } public IList GetModuleSettings(int moduleId, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllModuleSettings(moduleId, toDate, fromDate)); + this._dataProvider.GetAllModuleSettings(moduleId, toDate, fromDate)); } public IList GetModulePermissions(int moduleId, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllModulePermissions(moduleId, toDate, fromDate)); + this._dataProvider.GetAllModulePermissions(moduleId, toDate, fromDate)); } public IList GetTabModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllTabModules(tabId, includeDeleted, toDate, fromDate)); + this._dataProvider.GetAllTabModules(tabId, includeDeleted, toDate, fromDate)); } public IList GetTabModuleSettings(int tabId, DateTime toDate, DateTime? fromDate) { - return GetTabModuleSettings(tabId, true, toDate, fromDate); + return this.GetTabModuleSettings(tabId, true, toDate, fromDate); } public IList GetTabModuleSettings(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate) { return CBO.Instance.FillCollection( - _dataProvider.GetAllTabModuleSettings(tabId, includeDeleted, toDate, fromDate)); + this._dataProvider.GetAllTabModuleSettings(tabId, includeDeleted, toDate, fromDate)); } public PermissionInfo GetPermissionInfo(string permissionCode, string permissionKey, string permissionName) { return CBO.Instance.FillObject( - _dataProvider.GetPermissionInfo(permissionCode, permissionKey, permissionName)); + this._dataProvider.GetPermissionInfo(permissionCode, permissionKey, permissionName)); } public void SetTabSpecificData(int tabId, bool isDeleted, bool isVisible) { - _dataProvider.SetTabSpecificData(tabId, isDeleted, isVisible); + this._dataProvider.SetTabSpecificData(tabId, isDeleted, isVisible); } public void SetTabModuleDeleted(int tabModuleId, bool isDeleted) { - _dataProvider.SetTabModuleDeleted(tabModuleId, isDeleted); + this._dataProvider.SetTabModuleDeleted(tabModuleId, isDeleted); } public void SetUserDeleted(int portalId, int userId, bool isDeleted) { - _dataProvider.SetUserDeleted(portalId, userId, isDeleted); + this._dataProvider.SetUserDeleted(portalId, userId, isDeleted); } public void RunSchedule() { var executingServer = ServerController.GetExecutingServerName(); - var scheduleItem = SchedulingController.GetSchedule(GetSchedulerTypeFullName(), executingServer); + var scheduleItem = SchedulingController.GetSchedule(this.GetSchedulerTypeFullName(), executingServer); if (scheduleItem != null) { SchedulingProvider.Instance().RunScheduleItemNow(scheduleItem, true); @@ -194,7 +196,7 @@ public void RunSchedule() private string GetSchedulerTypeFullName() { - var type = typeof (ExportImportScheduler); + var type = typeof(ExportImportScheduler); return $"{type.FullName}, {type.Assembly.GetName().Name}"; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs index 89e665971dd..0273c3b14af 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Providers; -using Newtonsoft.Json; -using System.IO; -using Dnn.ExportImport.Components.Entities; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Controllers { + using System; + using System.IO; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Providers; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using Newtonsoft.Json; + public class ExportController : BaseController { public int QueueOperation(int userId, ExportDto exportDto) @@ -26,18 +27,21 @@ public int QueueOperation(int userId, ExportDto exportDto) var directory = dbTime.ToString("yyyy-MM-dd_HH-mm-ss"); if (exportDto.ExportMode == ExportMode.Differential) { - exportDto.FromDateUtc = GetLastJobTime(exportDto.PortalId, JobType.Export); + exportDto.FromDateUtc = this.GetLastJobTime(exportDto.PortalId, JobType.Export); } + var dataObject = JsonConvert.SerializeObject(exportDto); - exportDto.IsDirty = false;//This should be set to false for new job. + exportDto.IsDirty = false; // This should be set to false for new job. var jobId = DataProvider.Instance().AddNewJob(exportDto.PortalId, userId, JobType.Export, exportDto.ExportName, exportDto.ExportDescription, directory, dataObject); - //Run the scheduler if required. + + // Run the scheduler if required. if (exportDto.RunNow) { EntitiesController.Instance.RunSchedule(); } - AddEventLog(exportDto.PortalId, userId, jobId, Constants.LogTypeSiteExport); + + this.AddEventLog(exportDto.PortalId, userId, jobId, Constants.LogTypeSiteExport); return jobId; } @@ -53,7 +57,7 @@ public void CreatePackageManifest(ExportImportJob exportJob, ExportFileInfo expo Name = exportJob.Name, Description = exportJob.Description, ExporTime = exportJob.CreatedOnDate, - PortalName = portal?.PortalName + PortalName = portal?.PortalName, }; Util.WriteJson(filePath, packageInfo); } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs index 7fd5311033b..ea55a61ec7c 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Providers; -using Dnn.ExportImport.Repository; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Controllers { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Providers; + using Dnn.ExportImport.Repository; + using Newtonsoft.Json; + public class ImportController : BaseController { - public int QueueOperation(int userId, ImportDto importDto) { using (var repository = new ExportImportRepository(GetPackageDbPath(importDto.PackageId))) @@ -30,22 +30,24 @@ public int QueueOperation(int userId, ImportDto importDto) var dataObject = JsonConvert.SerializeObject(importDto); var jobId = DataProvider.Instance().AddNewJob( importDto.PortalId, userId, JobType.Import, null, null, importDto.PackageId, dataObject); - //Run the scheduler if required. + + // Run the scheduler if required. if (importDto.RunNow) { EntitiesController.Instance.RunSchedule(); } - AddEventLog(importDto.PortalId, userId, jobId, Constants.LogTypeSiteImport); + + this.AddEventLog(importDto.PortalId, userId, jobId, Constants.LogTypeSiteImport); return jobId; } /// - /// Get list of packages to import + /// Get list of packages to import. /// - /// Total number of packages - /// Keyword to search the import package. This will look into the package name and description - /// Order by which the packages list should be sorted. Allowed values: newest, oldest, name - /// Page index to get + /// Total number of packages. + /// Keyword to search the import package. This will look into the package name and description. + /// Order by which the packages list should be sorted. Allowed values: newest, oldest, name. + /// Page index to get. /// Page size. Should not be more than 100. /// public IEnumerable GetImportPackages(out int total, string keyword, string order = "newest", @@ -59,12 +61,12 @@ public IEnumerable GetImportPackages(out int total, string ke var importPackagesList = importPackages as IList ?? importPackages.ToList(); importPackages = !string.IsNullOrEmpty(keyword) - ? importPackagesList.Where(GetImportPackageFilterFunc(keyword)) + ? importPackagesList.Where(this.GetImportPackageFilterFunc(keyword)) : importPackagesList; total = importPackages.Count(); string sortOrder; - var orderByFunc = GetImportPackageOrderByFunc(order, out sortOrder); + var orderByFunc = this.GetImportPackageOrderByFunc(order, out sortOrder); importPackages = sortOrder == "asc" ? importPackages.OrderBy(orderByFunc) : importPackages.OrderByDescending(orderByFunc); @@ -76,14 +78,21 @@ public bool VerifyImportPackage(string packageId, ImportExportSummary summary, o bool isValid; errorMessage = string.Empty; var importFolder = Path.Combine(ExportFolder, packageId); - if (!IsValidImportFolder(importFolder)) return false; + if (!IsValidImportFolder(importFolder)) + { + return false; + } + var dbPath = UnPackDatabase(importFolder); try { using (var ctx = new ExportImportRepository(dbPath)) { - if (summary != null) - BuildJobSummary(packageId, ctx, summary); + if (summary != null) + { + BuildJobSummary(packageId, ctx, summary); + } + isValid = true; } } @@ -92,13 +101,18 @@ public bool VerifyImportPackage(string packageId, ImportExportSummary summary, o isValid = false; errorMessage = "Package is not valid. Technical Details:" + ex.Message; } + return isValid; } private static string GetPackageDbPath(string packageId) { var importFolder = Path.Combine(ExportFolder, packageId); - if (!IsValidImportFolder(importFolder)) return null; + if (!IsValidImportFolder(importFolder)) + { + return null; + } + var dbPath = UnPackDatabase(importFolder); return dbPath; } @@ -106,8 +120,11 @@ private static string GetPackageDbPath(string packageId) private static string UnPackDatabase(string folderPath) { var dbName = Path.Combine(folderPath, Constants.ExportDbName); - if (File.Exists(dbName)) - return dbName; + if (File.Exists(dbName)) + { + return dbName; + } + var zipDbName = Path.Combine(folderPath, Constants.ExportZipDbName); CompressionUtil.UnZipFileFromArchive(Constants.ExportDbName, zipDbName, folderPath, false); return dbName; @@ -142,6 +159,7 @@ private Func GetImportPackageOrderByFunc(string order sortFunc = packageInfo => packageInfo.ExporTime; break; } + return sortFunc; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs index cef1e6ce2db..c0448f04057 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs @@ -1,37 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Interfaces; -using Dnn.ExportImport.Components.Providers; -using DotNetNuke.Framework; -using DotNetNuke.Common.Utilities; -using System.Linq; -using System.Web.Caching; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.Caching; + + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Interfaces; + using Dnn.ExportImport.Components.Providers; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + public class SettingsController : ServiceLocator, ISettingsController { private const string CacheKey = "ExportImport_Settings"; private const int CacheDuration = 120; - protected override Func GetFactory() - { - return () => new SettingsController(); - } public IEnumerable GetAllSettings() { - return CBO.GetCachedObject>(new CacheItemArgs(CacheKey, CacheDuration, CacheItemPriority.Normal), - c => CBO.FillQueryable(DataProvider.Instance().GetExportImportSettings()).ToList()); + return CBO.GetCachedObject>( + new CacheItemArgs(CacheKey, CacheDuration, CacheItemPriority.Normal), + c => CBO.FillQueryable(DataProvider.Instance().GetExportImportSettings()).ToList()); } public ExportImportSetting GetSetting(string settingName) { - return GetAllSettings().ToList().FirstOrDefault(x => x.SettingName == settingName); + return this.GetAllSettings().ToList().FirstOrDefault(x => x.SettingName == settingName); + } + + protected override Func GetFactory() + { + return () => new SettingsController(); } public void AddSetting(ExportImportSetting exportImportSetting) diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs index 13311562e26..861167d2608 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs @@ -1,118 +1,135 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.ExportImport.Components.Common; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto { + using System; + + using Dnn.ExportImport.Components.Common; + using Newtonsoft.Json; + + public enum TriCheckedState + { +#if false + // for schema 1.0.0 + Checked = 0, + UnChecked = 1, + Partial = 2, +#else + UnChecked = 0, + Checked = 1, + CheckedWithAllChildren = 2, +#endif + + } + [JsonObject] public class ExportDto { public int Id { get; set; } + /// - /// Specifies the version of the exportes schema. + /// Gets or sets specifies the version of the exportes schema. /// public string SchemaVersion { get; set; } = Constants.CurrentSchemaVersion; /// - /// ID of portal to export items from. + /// Gets or sets iD of portal to export items from. /// public int PortalId { get; set; } /// - /// SKU of the product from which the export is done. + /// Gets or sets sKU of the product from which the export is done. /// public string ProductSku { get; set; } /// - /// Version of the product from which the export is done. + /// Gets or sets version of the product from which the export is done. /// public string ProductVersion { get; set; } /// - /// Name of export job. + /// Gets or sets name of export job. /// public string ExportName { get; set; } /// - /// Description of export job. + /// Gets or sets description of export job. /// public string ExportDescription { get; set; } /// - /// Names of items to export + /// Gets or sets names of items to export. /// - /// ["Content", "Assets", "Users"] + /// ["Content", "Assets", "Users"]. public string[] ItemsToExport { get; set; } /// - /// Whether to include deleted items in the export. + /// Gets or sets a value indicating whether whether to include deleted items in the export. /// Note that these will be deleted on the imported site. /// public bool IncludeDeletions { get; set; } /// - /// Whether to include the content items in the exported file. + /// Gets or sets a value indicating whether whether to include the content items in the exported file. /// This applies to items such as pages/tabs and the content of their modules. /// public bool IncludeContent { get; set; } /// - /// Whether to include item files in the exported file. + /// Gets or sets a value indicating whether whether to include item files in the exported file. /// This applies for user files and content files. - /// In case the folder's and files were included in the + /// In case the folder's and files were included in the /// then, this flag will be set to false. /// public bool IncludeFiles { get; set; } /// - /// Whether to include users in the export file or not. + /// Gets or sets a value indicating whether whether to include users in the export file or not. /// public bool IncludeUsers { get; set; } /// - /// Whether to include vocabularies in the export file or not. + /// Gets or sets a value indicating whether whether to include vocabularies in the export file or not. /// public bool IncludeVocabularies { get; set; } /// - /// Whether to include page templates in export file or not. + /// Gets or sets a value indicating whether whether to include page templates in export file or not. /// public bool IncludeTemplates { get; set; } /// - /// Whether to include profile properties in exported file. + /// Gets or sets a value indicating whether whether to include profile properties in exported file. /// When this flag is enabled only then userprofile would be exported. /// public bool IncludeProperfileProperties { get; set; } /// - /// Whether to include modules packages in exported file. + /// Gets or sets a value indicating whether whether to include modules packages in exported file. /// public bool IncludeExtensions { get; set; } /// - /// Whether to include roles or not in export file. + /// Gets or sets a value indicating whether whether to include roles or not in export file. /// If this flag is disabled, User Roles won't be exported. /// If this flag is disabled, Assets permissions won't be exported. /// public bool IncludeRoles { get; set; } /// - /// Whether to incldue permissions with each entity in export file or not. + /// Gets or sets a value indicating whether whether to incldue permissions with each entity in export file or not. /// public bool IncludePermissions { get; set; } /// - /// Export mode. Differential or Complete. + /// Gets or sets export mode. Differential or Complete. /// public ExportMode ExportMode { get; set; } /// - /// Items' last modified on or created on for the items which need to be exported. + /// Gets or sets items' last modified on or created on for the items which need to be exported. /// This time format should be local time with offset in order to bae sure to export /// items properly and reduce the possibility of export issues. /// @@ -120,31 +137,32 @@ public class ExportDto public DateTime? FromDateUtc { get; set; } /// - /// Date when job was created. - /// NOTE: This will be set internally only by the engine and not by the UI + /// Gets or sets date when job was created. + /// NOTE: This will be set internally only by the engine and not by the UI. /// [JsonProperty("ToDate")] public DateTime ToDateUtc { get; set; } [JsonIgnore] - public DateTime? FromDate => FromDateUtc; + public DateTime? FromDate => this.FromDateUtc; + [JsonIgnore] - public DateTime ToDate => ToDateUtc; + public DateTime ToDate => this.ToDateUtc; /// - /// The pages to be exported. These are the ID's (plus other information) + /// Gets or sets the pages to be exported. These are the ID's (plus other information) /// of all checked items but not their children when a parent is checked. /// If the 'TabId=-1' is included in the list, it means all site pages. /// public PageToExport[] Pages { get; set; } /// - /// Whether to run the job immediately or not. + /// Gets or sets a value indicating whether whether to run the job immediately or not. /// public bool RunNow { get; set; } /// - /// Used to determine if the DB file needs cleanup before starting import or not. + /// Gets or sets a value indicating whether used to determine if the DB file needs cleanup before starting import or not. /// public bool IsDirty { get; set; } } @@ -156,22 +174,9 @@ public class ExportDto public class PageToExport { public int TabId { get; set; } + public int ParentTabId { get; set; } + public TriCheckedState CheckedState { get; set; } } - - public enum TriCheckedState - { -#if false - // for schema 1.0.0 - Checked = 0, - UnChecked = 1, - Partial = 2, -#else - UnChecked = 0, - Checked = 1, - CheckedWithAllChildren = 2, -#endif - - } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs index 30be9668a67..7c96bce3ac2 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.ExportImport.Components.Interfaces; -using DotNetNuke.Entities.Users; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto { + using Dnn.ExportImport.Components.Interfaces; + using DotNetNuke.Entities.Users; + using Newtonsoft.Json; + /// /// Export file(s) info. /// @@ -15,17 +15,18 @@ namespace Dnn.ExportImport.Components.Dto public class ExportFileInfo : IDateTimeConverter { /// - /// Path for exported files. + /// Gets or sets path for exported files. /// public string ExportPath { get; set; } + /// - /// Formatted size of export file + /// Gets or sets formatted size of export file. /// public string ExportSize { get; set; } public void ConvertToLocal(UserInfo userInfo) { - //Nothing to convert. + // Nothing to convert. } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportDto.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportDto.cs index a3f44059ac5..4b7c14775ac 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportDto.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportDto.cs @@ -1,48 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.ExportImport.Components.Common; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto { + using Dnn.ExportImport.Components.Common; + using Newtonsoft.Json; + [JsonObject] public class ImportDto { /// - /// Specifies the version of the exportes schema. + /// Gets or sets specifies the version of the exportes schema. /// public string SchemaVersion { get; set; } = Constants.CurrentSchemaVersion; /// - /// ID of portal to import items to. + /// Gets or sets iD of portal to import items to. /// public int PortalId { get; set; } /// - /// Id of exported package to be imported + /// Gets or sets id of exported package to be imported. /// /// /// For security reasons, this name does not have a folder or extension name. /// These will be used by convention and picked from a very specific location - /// in the portal () + /// in the portal (). /// public string PackageId { get; set; } /// - /// Specifies what to do when there is a collision during the import process. - /// See + /// Gets or sets specifies what to do when there is a collision during the import process. + /// See . /// public CollisionResolution CollisionResolution { get; set; } = CollisionResolution.Ignore; /// - /// Snapshot of the export dto from the import package + /// Gets or sets snapshot of the export dto from the import package. /// public ExportDto ExportDto { get; set; } /// - /// Snapshot of the import file into. + /// Gets or sets snapshot of the import file into. /// public ExportFileInfo ExportFileInfo { get; set; } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs index 2faedd61863..e053fa8ab66 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Interfaces; -using DotNetNuke.Entities.Users; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto { + using System; + using System.Collections.Generic; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Interfaces; + using DotNetNuke.Entities.Users; + using Newtonsoft.Json; + /// /// Import/Export summary class to provide information about what will happen with this job. /// @@ -19,80 +20,97 @@ public class ImportExportSummary : IDateTimeConverter { public ImportExportSummary() { - SummaryItems = new SummaryList(); + this.SummaryItems = new SummaryList(); } + /// - /// Does this import/export includes the properties definitions or not. + /// Gets or sets a value indicating whether does this import/export includes the properties definitions or not. /// public bool IncludeProfileProperties { get; set; } + /// - /// Does this import/export includes the permission or not. + /// Gets or sets a value indicating whether does this import/export includes the permission or not. /// public bool IncludePermissions { get; set; } + /// - /// Does this import/export includes the modules or not. + /// Gets or sets a value indicating whether does this import/export includes the modules or not. /// public bool IncludeExtensions { get; set; } + /// - /// Does this import/export includes the deleted items or not. + /// Gets or sets a value indicating whether does this import/export includes the deleted items or not. /// public bool IncludeDeletions { get; set; } /// - /// Does this import/export includes content or not. + /// Gets or sets a value indicating whether does this import/export includes content or not. /// public bool IncludeContent { get; set; } /// - /// Export mode. Differential or complete. + /// Gets or sets export mode. Differential or complete. /// public ExportMode ExportMode { get; set; } /// - /// Date from which data was taken to perform export. + /// Gets or sets date from which data was taken to perform export. /// public DateTime? FromDate { get; set; } /// - /// Formatted Date from which data was taken to perform export. + /// Gets formatted Date from which data was taken to perform export. /// - public string FromDateString => Util.GetDateTimeString(FromDate); + public string FromDateString => Util.GetDateTimeString(this.FromDate); /// - /// Date till which data was taken to perform export. + /// Gets or sets date till which data was taken to perform export. /// public DateTime ToDate { get; set; } /// - /// Formatted Date till which data was taken to perform export. + /// Gets formatted Date till which data was taken to perform export. /// - public string ToDateString => Util.GetDateTimeString(ToDate); + public string ToDateString => Util.GetDateTimeString(this.ToDate); /// - /// Summary of each item export. + /// Gets or sets summary of each item export. /// public IEnumerable SummaryItems { get; set; } + /// - /// Exported file information. + /// Gets or sets exported file information. /// public ExportFileInfo ExportFileInfo { get; set; } public void ConvertToLocal(UserInfo userInfo) { - if (userInfo == null) return; - ToDate = Util.ToLocalDateTime(ToDate, userInfo); - if (FromDate != null) - FromDate = Util.ToLocalDateTime(FromDate.Value, userInfo); - ExportFileInfo?.ConvertToLocal(userInfo); + if (userInfo == null) + { + return; + } + + this.ToDate = Util.ToLocalDateTime(this.ToDate, userInfo); + if (this.FromDate != null) + { + this.FromDate = Util.ToLocalDateTime(this.FromDate.Value, userInfo); + } + + this.ExportFileInfo?.ConvertToLocal(userInfo); - if (SummaryItems == null) return; + if (this.SummaryItems == null) + { + return; + } + var tempSummaryItems = new SummaryList(); - foreach (var summaryItem in SummaryItems) + foreach (var summaryItem in this.SummaryItems) { summaryItem.ConvertToLocal(userInfo); tempSummaryItems.Add(summaryItem); } - SummaryItems = tempSummaryItems; + + this.SummaryItems = tempSummaryItems; } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs index 10cff848af6..2a5fc049718 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs @@ -1,68 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Interfaces; -using DotNetNuke.Entities.Users; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto { + using System; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Interfaces; + using DotNetNuke.Entities.Users; + using Newtonsoft.Json; + [JsonObject] public class ImportPackageInfo : IDateTimeConverter { /// - /// Package Id. Used to identify the package and path. + /// Gets or sets package Id. Used to identify the package and path. /// public string PackageId { get; set; } /// - /// Name of the package. + /// Gets or sets name of the package. /// public string Name { get; set; } /// - /// Package file name. It is just fake name for UI representation + /// Gets package file name. It is just fake name for UI representation. /// - public string FileName => PackageId; + public string FileName => this.PackageId; /// - /// DateTime when the package was exported. + /// Gets or sets dateTime when the package was exported. /// public DateTime ExporTime { get; set; } /// - /// Formatted DateTime when the package was exported. + /// Gets formatted DateTime when the package was exported. /// - public string ExporTimeString => Util.GetDateTimeString(ExporTime); + public string ExporTimeString => Util.GetDateTimeString(this.ExporTime); /// - /// The portal from which the exported package was created + /// Gets or sets the portal from which the exported package was created. /// public string PortalName { get; set; } /// - /// Package description + /// Gets or sets package description. /// public string Description { get; set; } /// - /// Path to the thumbnail image for the package. + /// Gets path to the thumbnail image for the package. /// - public string Thumb => PackageId + ".jpg"; + public string Thumb => this.PackageId + ".jpg"; /// - /// Complete summary of import package + /// Gets or sets complete summary of import package. /// public ImportExportSummary Summary { get; set; } public void ConvertToLocal(UserInfo userInfo) { - if (userInfo == null) return; - ExporTime = Util.ToLocalDateTime(ExporTime, userInfo); - Summary?.ConvertToLocal(userInfo); + if (userInfo == null) + { + return; + } + + this.ExporTime = Util.ToLocalDateTime(this.ExporTime, userInfo); + this.Summary?.ConvertToLocal(userInfo); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs index 05a069e8f61..fee0c919928 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs @@ -1,48 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Interfaces; -using DotNetNuke.Entities.Users; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto.Jobs { + using System; + using System.Collections.Generic; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Interfaces; + using DotNetNuke.Entities.Users; + using Newtonsoft.Json; + [JsonObject] public class AllJobsResult : IDateTimeConverter { public int PortalId { get; set; } + public string PortalName { get; set; } + public int TotalJobs { get; set; } - public string TotalJobsString => Util.FormatNumber(TotalJobs); + + public string TotalJobsString => Util.FormatNumber(this.TotalJobs); public DateTime? LastExportTime { get; set; } + public DateTime? LastImportTime { get; set; } - public string LastExportTimeString => Util.GetDateTimeString(LastExportTime); + public string LastExportTimeString => Util.GetDateTimeString(this.LastExportTime); - public string LastImportTimeString => Util.GetDateTimeString(LastImportTime); + public string LastImportTimeString => Util.GetDateTimeString(this.LastImportTime); public IEnumerable Jobs { get; set; } public void ConvertToLocal(UserInfo userInfo) { - LastExportTime = Util.ToLocalDateTime(LastExportTime, userInfo); - LastImportTime = Util.ToLocalDateTime(LastImportTime, userInfo); - - if (userInfo == null) return; - if (Jobs == null) return; + this.LastExportTime = Util.ToLocalDateTime(this.LastExportTime, userInfo); + this.LastImportTime = Util.ToLocalDateTime(this.LastImportTime, userInfo); + + if (userInfo == null) + { + return; + } + + if (this.Jobs == null) + { + return; + } + var tempJobs = new List(); - foreach (var job in Jobs) + foreach (var job in this.Jobs) { job.ConvertToLocal(userInfo); tempJobs.Add(job); } - Jobs = tempJobs; + + this.Jobs = tempJobs; } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs index 02e1939119a..a5a51786174 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs @@ -1,43 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Interfaces; -using DotNetNuke.Entities.Users; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto.Jobs { + using System; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Interfaces; + using DotNetNuke.Entities.Users; + using Newtonsoft.Json; + [JsonObject] public class JobItem : IDateTimeConverter { public int JobId { get; set; } + public int PortalId { get; set; } + public string User { get; set; } + public string JobType { get; set; } + public int Status { get; set; } + public bool Cancelled { get; set; } + public string JobStatus { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public DateTime CreatedOn { get; set; } - public string CreatedOnString => Util.GetDateTimeString(CreatedOn); + + public string CreatedOnString => Util.GetDateTimeString(this.CreatedOn); + public DateTime? CompletedOn { get; set; } - public string CompletedOnString => Util.GetDateTimeString(CompletedOn); + + public string CompletedOnString => Util.GetDateTimeString(this.CompletedOn); public string ExportFile { get; set; } - //public IEnumerable Summary { get; set; } + + // public IEnumerable Summary { get; set; } public ImportExportSummary Summary { get; set; } public void ConvertToLocal(UserInfo userInfo) { - if (userInfo == null) return; - Summary?.ConvertToLocal(userInfo); - CreatedOn = Util.ToLocalDateTime(CreatedOn, userInfo); - if (CompletedOn != null) - CompletedOn = Util.ToLocalDateTime(CompletedOn.Value, userInfo); + if (userInfo == null) + { + return; + } + + this.Summary?.ConvertToLocal(userInfo); + this.CreatedOn = Util.ToLocalDateTime(this.CreatedOn, userInfo); + if (this.CompletedOn != null) + { + this.CompletedOn = Util.ToLocalDateTime(this.CompletedOn.Value, userInfo); + } } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs index 6024e5fd7b4..571144071c8 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs @@ -1,19 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.ExportImport.Components.Common; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto.Jobs { + using System; + + using Dnn.ExportImport.Components.Common; + using Newtonsoft.Json; + [JsonObject] public class LogItem { public DateTime CreatedOnDate { get; set; } + public string Name { get; set; } + public string Value { get; set; } + public ReportLevel ReportLevel { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs index 73ecb027884..936b1a221eb 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Interfaces; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Dto { + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Interfaces; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using Newtonsoft.Json; + /// /// Details of the summary item to show in the export/import summary and progress. /// @@ -17,48 +17,48 @@ namespace Dnn.ExportImport.Components.Dto public class SummaryItem : IDateTimeConverter { /// - /// Category of the import/export. Also identifier for localization + /// Gets or sets category of the import/export. Also identifier for localization. /// public string Category { get; set; } /// - /// Total items to import/export. + /// Gets or sets total items to import/export. /// public int TotalItems { get; set; } /// - /// Formatted total items. + /// Gets formatted total items. /// - public string TotalItemsString => Util.FormatNumber(TotalItems); + public string TotalItemsString => Util.FormatNumber(this.TotalItems); /// - /// Items processed. + /// Gets or sets items processed. /// public int ProcessedItems { get; set; } /// - /// Is job finished or not yet. + /// Gets or sets a value indicating whether is job finished or not yet. /// public bool Completed { get; set; } /// - /// Formatted processed items. + /// Gets formatted processed items. /// - public string ProcessedItemsString => Util.FormatNumber(ProcessedItems); + public string ProcessedItemsString => Util.FormatNumber(this.ProcessedItems); /// - /// Progress in percentage. + /// Gets or sets progress in percentage. /// public int ProgressPercentage { get; set; } /// - /// Order to show on UI. + /// Gets or sets order to show on UI. /// public uint Order { get; set; } public void ConvertToLocal(UserInfo userInfo) { - //Nothing to convert. + // Nothing to convert. } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs index ba673aa1d57..a1f348427f2 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs @@ -1,47 +1,61 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Controllers; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Dto.Jobs; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Models; -using Dnn.ExportImport.Components.Services; -using Dnn.ExportImport.Dto; -using Dnn.ExportImport.Dto.Assets; -using Dnn.ExportImport.Dto.PageTemplates; -using Dnn.ExportImport.Dto.Portal; -using Dnn.ExportImport.Dto.ProfileProperties; -using Dnn.ExportImport.Interfaces; -using Dnn.ExportImport.Repository; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Scheduling; -using Newtonsoft.Json; -using PlatformDataProvider = DotNetNuke.Data.DataProvider; -using DotNetNuke.Framework.Reflections; -using Dnn.ExportImport.Dto.Users; -using DotNetNuke.Instrumentation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Engines { + using System; + using System.Collections.Generic; + using System.Data; + using System.Diagnostics; + using System.IO; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Controllers; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Dto.Jobs; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Models; + using Dnn.ExportImport.Components.Services; + using Dnn.ExportImport.Dto; + using Dnn.ExportImport.Dto.Assets; + using Dnn.ExportImport.Dto.PageTemplates; + using Dnn.ExportImport.Dto.Portal; + using Dnn.ExportImport.Dto.ProfileProperties; + using Dnn.ExportImport.Dto.Users; + using Dnn.ExportImport.Interfaces; + using Dnn.ExportImport.Repository; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.Reflections; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Scheduling; + using Newtonsoft.Json; + + using PlatformDataProvider = DotNetNuke.Data.DataProvider; + public class ExportImportEngine { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); - private const StringComparison IgnoreCaseComp = StringComparison.InvariantCultureIgnoreCase; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); private static readonly string ExportFolder; + private static readonly Tuple[] DatasetColumns = + { + new Tuple("JobId", typeof(int)), + new Tuple("Name", typeof(string)), + new Tuple("Value", typeof(string)), + new Tuple("Level", typeof(int)), + new Tuple("CreatedOnDate", typeof(DateTime)), + }; + + private readonly Stopwatch _stopWatch = Stopwatch.StartNew(); + private int _timeoutSeconds; + static ExportImportEngine() { ExportFolder = Globals.ApplicationMapPath + Constants.ExportFolder; @@ -51,8 +65,43 @@ static ExportImportEngine() } } - private readonly Stopwatch _stopWatch = Stopwatch.StartNew(); - private int _timeoutSeconds; + private static string[] NotAllowedCategoriesinRequestArray => new[] + { + Constants.Category_Content, + Constants.Category_Pages, + Constants.Category_Portal, + Constants.Category_Content, + Constants.Category_Assets, + Constants.Category_Users, + Constants.Category_UsersData, + Constants.Category_Roles, + Constants.Category_Vocabularies, + Constants.Category_Templates, + Constants.Category_ProfileProps, + Constants.Category_Packages, + Constants.Category_Workflows, + }; + + private static string[] CleanUpIgnoredClasses => new[] + { + typeof(ExportFile).Name, + typeof(ExportFolder).Name, + typeof(ExportFolderMapping).Name, + typeof(ExportFolderPermission).Name, + typeof(ExportPageTemplate).Name, + typeof(ExportPortalSetting).Name, + typeof(ExportPortalLanguage).Name, + typeof(ExportProfileProperty).Name, + typeof(ExportUser).Name, + typeof(ExportAspnetUser).Name, + typeof(ExportAspnetMembership).Name, + typeof(ExportUserAuthentication).Name, + typeof(ExportUserPortal).Name, + typeof(ExportUserProfile).Name, + typeof(ExportUserRole).Name, + }; + + private bool TimeIsUp => this._stopWatch.Elapsed.TotalSeconds > this._timeoutSeconds; public void Export(ExportImportJob exportJob, ExportImportResult result, ScheduleHistoryItem scheduleHistoryItem) { @@ -64,22 +113,22 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul return; } - _timeoutSeconds = GetTimeoutPerSlot(); + this._timeoutSeconds = GetTimeoutPerSlot(); var dbName = Path.Combine(ExportFolder, exportJob.Directory, Constants.ExportDbName); var finfo = new FileInfo(dbName); dbName = finfo.FullName; - - + var checkpoints = EntitiesController.Instance.GetJobChekpoints(exportJob.JobId); - //Delete so we start a fresh export database; only if there is no previous checkpoint exists + // Delete so we start a fresh export database; only if there is no previous checkpoint exists if (checkpoints.Count == 0) { if (finfo.Directory != null && finfo.Directory.Exists) { finfo.Directory.Delete(true); } - //Clear all the files in finfo.Directory. Create if doesn't exists. + + // Clear all the files in finfo.Directory. Create if doesn't exists. finfo.Directory?.Create(); result.AddSummary("Starting Exporting Repository", finfo.Name); } @@ -115,8 +164,9 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul exportJob.JobStatus = JobStatus.Failed; return; } + scheduleHistoryItem.AddLogNote($"
    SITE EXPORT Preparing Check Points. JOB #{exportJob.JobId}: {exportJob.Name}"); - PrepareCheckPoints(exportJob.JobId, parentServices, implementors, includedItems, checkpoints); + this.PrepareCheckPoints(exportJob.JobId, parentServices, implementors, includedItems, checkpoints); scheduleHistoryItem.AddLogNote($"
    SITE EXPORT Started. JOB #{exportJob.JobId}: {exportJob.Name}"); scheduleHistoryItem.AddLogNote($"
    Between [{exportDto.FromDateUtc ?? Constants.MinDbTime}] and [{exportDto.ToDateUtc:g}]"); @@ -152,7 +202,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul service.Result = result; service.Repository = ctx; service.CheckCancelled = CheckCancelledCallBack; - service.CheckPointStageCallback = CheckpointCallback; + service.CheckPointStageCallback = this.CheckpointCallback; service.CheckPoint = checkpoints.FirstOrDefault(cp => cp.Category == service.Category && cp.AssemblyName == serviceAssembly); if (service.CheckPoint == null) @@ -162,24 +212,26 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul JobId = exportJob.JobId, Category = service.Category, AssemblyName = serviceAssembly, - StartDate = DateUtils.GetDatabaseUtcTime() + StartDate = DateUtils.GetDatabaseUtcTime(), }; // persist the record in db - CheckpointCallback(service); + this.CheckpointCallback(service); } - else if (service.CheckPoint.StartDate == Null.NullDate) - service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); - + else if (service.CheckPoint.StartDate == Null.NullDate) + { + service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); + } + try { service.ExportData(exportJob, exportDto); - } finally { - AddLogsToDatabase(exportJob.JobId, result.CompleteLog); + this.AddLogsToDatabase(exportJob.JobId, result.CompleteLog); } + scheduleHistoryItem.AddLogNote("
    Exported: " + service.Category); } } @@ -189,33 +241,37 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul nextLevelServices.Clear(); if (implementors.Count > 0 && parentServices.Count == 0) { - //WARN: this is a case where there is a broken parent-children hierarchy + // WARN: this is a case where there is a broken parent-children hierarchy // and/or there are BasePortableService implementations without a known parent. parentServices = implementors; implementors.Clear(); scheduleHistoryItem.AddLogNote( "
    Orphaned services: " + string.Join(",", parentServices.Select(x => x.Category))); } - } while (parentServices.Count > 0 && !TimeIsUp); + } + while (parentServices.Count > 0 && !this.TimeIsUp); RemoveTokenFromCache(exportJob); } - if (TimeIsUp) + if (this.TimeIsUp) { - result.AddSummary($"Job time slot ({_timeoutSeconds} sec) expired", + result.AddSummary( + $"Job time slot ({this._timeoutSeconds} sec) expired", "Job will resume in the next scheduler iteration"); } else if (exportJob.JobStatus == JobStatus.InProgress) { - //Create Export Summary for manifest file. + // Create Export Summary for manifest file. var summary = new ImportExportSummary(); using (var ctx = new ExportImportRepository(dbName)) { BaseController.BuildJobSummary(exportJob.Directory, ctx, summary); } + DoPacking(exportJob, dbName); - //Complete the job. + + // Complete the job. exportJob.JobStatus = JobStatus.Successful; SetLastJobStartTime(scheduleHistoryItem.ScheduleID, exportJob.CreatedOnDate); @@ -223,7 +279,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul var exportFileInfo = new ExportFileInfo { ExportPath = exportJob.Directory, - ExportSize = Util.FormatSize(GetExportSize(Path.Combine(ExportFolder, exportJob.Directory))) + ExportSize = Util.FormatSize(GetExportSize(Path.Combine(ExportFolder, exportJob.Directory))), }; summary.ExportFileInfo = exportFileInfo; @@ -234,7 +290,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul public void Import(ExportImportJob importJob, ExportImportResult result, ScheduleHistoryItem scheduleHistoryItem) { scheduleHistoryItem.AddLogNote($"
    SITE IMPORT Started. JOB #{importJob.JobId}"); - _timeoutSeconds = GetTimeoutPerSlot(); + this._timeoutSeconds = GetTimeoutPerSlot(); var importDto = JsonConvert.DeserializeObject(importJob.JobObject); if (importDto == null) { @@ -301,7 +357,7 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul var includedItems = GetAllCategoriesToInclude(exportedDto, implementors); scheduleHistoryItem.AddLogNote($"
    SITE IMPORT Preparing Check Points. JOB #{importJob.JobId}: {importJob.Name}"); - PrepareCheckPoints(importJob.JobId, parentServices, implementors, includedItems, checkpoints); + this.PrepareCheckPoints(importJob.JobId, parentServices, implementors, includedItems, checkpoints); var firstIteration = true; AddJobToCache(importJob); @@ -333,7 +389,7 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul service.Result = result; service.Repository = ctx; service.CheckCancelled = CheckCancelledCallBack; - service.CheckPointStageCallback = CheckpointCallback; + service.CheckPointStageCallback = this.CheckpointCallback; service.CheckPoint = checkpoints.FirstOrDefault(cp => cp.Category == service.Category && cp.AssemblyName == serviceAssembly) ?? new ExportImportChekpoint { @@ -341,11 +397,14 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul AssemblyName = serviceAssembly, Category = service.Category, Progress = 0, - StartDate = DateUtils.GetDatabaseUtcTime() + StartDate = DateUtils.GetDatabaseUtcTime(), }; - if (service.CheckPoint.StartDate == Null.NullDate) - service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); - CheckpointCallback(service); + if (service.CheckPoint.StartDate == Null.NullDate) + { + service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); + } + + this.CheckpointCallback(service); try { @@ -353,8 +412,9 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul } finally { - AddLogsToDatabase(importJob.JobId, result.CompleteLog); + this.AddLogsToDatabase(importJob.JobId, result.CompleteLog); } + scheduleHistoryItem.AddLogNote("
    Imported: " + service.Category); } } @@ -364,19 +424,21 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul nextLevelServices.Clear(); if (implementors.Count > 0 && parentServices.Count == 0) { - //WARN: this is a case where there is a broken parent-children hierarchy + // WARN: this is a case where there is a broken parent-children hierarchy // and/or there are BasePortableService implementations without a known parent. parentServices = implementors; implementors.Clear(); scheduleHistoryItem.AddLogNote( "
    Orphaned services: " + string.Join(",", parentServices.Select(x => x.Category))); } - } while (parentServices.Count > 0 && !TimeIsUp); + } + while (parentServices.Count > 0 && !this.TimeIsUp); RemoveTokenFromCache(importJob); - if (TimeIsUp) + if (this.TimeIsUp) { - result.AddSummary($"Job time slot ({_timeoutSeconds} sec) expired", + result.AddSummary( + $"Job time slot ({this._timeoutSeconds} sec) expired", "Job will resume in the next scheduler iteration"); } else if (importJob.JobStatus == JobStatus.InProgress) @@ -390,13 +452,78 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul } } + public void AddLogsToDatabase(int jobId, ICollection completeLog) + { + if (completeLog == null || completeLog.Count == 0) + { + return; + } + + using (var table = new DataTable("ExportImportJobLogs")) + { + // must create the columns from scratch with each iteration + table.Columns.AddRange(DatasetColumns.Select( + column => new DataColumn(column.Item1, column.Item2)).ToArray()); + + // batch specific amount of record each time + const int batchSize = 500; + var toSkip = 0; + while (toSkip < completeLog.Count) + { + foreach (var item in completeLog.Skip(toSkip).Take(batchSize)) + { + var row = table.NewRow(); + row["JobId"] = jobId; + row["Name"] = item.Name.TrimToLength(Constants.LogColumnLength); + row["Value"] = item.Value.TrimToLength(Constants.LogColumnLength); + row["Level"] = (int)item.ReportLevel; + row["CreatedOnDate"] = item.CreatedOnDate; + table.Rows.Add(row); + } + + PlatformDataProvider.Instance().BulkInsert("ExportImportJobLogs_AddBulk", "@DataTable", table); + toSkip += batchSize; + table.Rows.Clear(); + } + } + + completeLog.Clear(); + } + + private static bool CheckCancelledCallBack(ExportImportJob job) + { + var job2 = CachingProvider.Instance().GetItem(Util.GetExpImpJobCacheKey(job)) as ExportImportJob; + if (job2 == null) + { + job2 = EntitiesController.Instance.GetJobById(job.JobId); + job.IsCancelled = job2.IsCancelled; + AddJobToCache(job2); + } + + return job2.IsCancelled; + } + + private static void AddJobToCache(ExportImportJob job) + { + CachingProvider.Instance().Insert(Util.GetExpImpJobCacheKey(job), job); + } + + private static void RemoveTokenFromCache(ExportImportJob job) + { + CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); + } + private void PrepareCheckPoints(int jobId, List parentServices, List implementors, HashSet includedItems, IList checkpoints) { // there must be one parent implementor at least for this to work var nextLevelServices = new List(); var firstIteration = true; - if (checkpoints.Any()) return; + if (checkpoints.Any()) + { + return; + } + do { foreach (var service in parentServices.OrderBy(x => x.Priority)) @@ -417,64 +544,44 @@ private void PrepareCheckPoints(int jobId, List parentServi service.CheckPoint = checkpoints.FirstOrDefault(cp => cp.Category == service.Category && cp.AssemblyName == serviceAssembly); - if (service.CheckPoint != null) continue; - + if (service.CheckPoint != null) + { + continue; + } + service.CheckPoint = new ExportImportChekpoint { JobId = jobId, AssemblyName = serviceAssembly, Category = service.Category, - Progress = 0 + Progress = 0, }; // persist the record in db - CheckpointCallback(service); + this.CheckpointCallback(service); } } firstIteration = false; parentServices = new List(nextLevelServices); nextLevelServices.Clear(); - } while (parentServices.Count > 0); - } - - private static bool CheckCancelledCallBack(ExportImportJob job) - { - var job2 = CachingProvider.Instance().GetItem(Util.GetExpImpJobCacheKey(job)) as ExportImportJob; - if (job2 == null) - { - job2 = EntitiesController.Instance.GetJobById(job.JobId); - job.IsCancelled = job2.IsCancelled; - AddJobToCache(job2); - } - - return job2.IsCancelled; + } + while (parentServices.Count > 0); } /// /// Callback function to provide a checkpoint mechanism for an implementation. /// - /// The implementation - /// Treu to stop further processing; false otherwise + /// The implementation. + /// Treu to stop further processing; false otherwise. private bool CheckpointCallback(BasePortableService service) { EntitiesController.Instance.UpdateJobChekpoint(service.CheckPoint); - return TimeIsUp; - } - - private bool TimeIsUp => _stopWatch.Elapsed.TotalSeconds > _timeoutSeconds; - - private static void AddJobToCache(ExportImportJob job) - { - CachingProvider.Instance().Insert(Util.GetExpImpJobCacheKey(job), job); + return this.TimeIsUp; } - private static void RemoveTokenFromCache(ExportImportJob job) - { - CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); - } - - private static HashSet GetAllCategoriesToInclude(ExportDto exportDto, + private static HashSet GetAllCategoriesToInclude( + ExportDto exportDto, List implementors) { // add all child items @@ -498,33 +605,47 @@ var name in includedItems.Add(Constants.Category_Workflows); } - if (exportDto.IncludeContent) - includedItems.Add(Constants.Category_Content); - - if (exportDto.IncludeFiles) - includedItems.Add(Constants.Category_Assets); - - if (exportDto.IncludeUsers) - includedItems.Add(Constants.Category_Users); - - if (exportDto.IncludeRoles) - includedItems.Add(Constants.Category_Roles); - - if (exportDto.IncludeVocabularies) - includedItems.Add(Constants.Category_Vocabularies); - + if (exportDto.IncludeContent) + { + includedItems.Add(Constants.Category_Content); + } + + if (exportDto.IncludeFiles) + { + includedItems.Add(Constants.Category_Assets); + } + + if (exportDto.IncludeUsers) + { + includedItems.Add(Constants.Category_Users); + } + + if (exportDto.IncludeRoles) + { + includedItems.Add(Constants.Category_Roles); + } + + if (exportDto.IncludeVocabularies) + { + includedItems.Add(Constants.Category_Vocabularies); + } + if (exportDto.IncludeTemplates) { includedItems.Add(Constants.Category_Templates); } - if (exportDto.IncludeProperfileProperties) - includedItems.Add(Constants.Category_ProfileProps); - - //This might be added always. - if (exportDto.IncludeExtensions) - includedItems.Add(Constants.Category_Packages); - + if (exportDto.IncludeProperfileProperties) + { + includedItems.Add(Constants.Category_ProfileProps); + } + + // This might be added always. + if (exportDto.IncludeExtensions) + { + includedItems.Add(Constants.Category_Packages); + } + var additionalItems = new List(); foreach (var includedItem in includedItems) { @@ -536,12 +657,15 @@ var name in additionalItems.Add(basePortableService.Category); } } + additionalItems.ForEach(i => includedItems.Add(i)); // must be included always when there is at least one other object to process - if (includedItems.Any()) - includedItems.Add(Constants.Category_Portal); - + if (includedItems.Any()) + { + includedItems.Add(Constants.Category_Portal); + } + return includedItems; } @@ -564,6 +688,7 @@ private static int GetTimeoutPerSlot() { value = 12 * 60 * 60; } + return value; } @@ -587,8 +712,11 @@ private static void DoUnPacking(ExportImportJob importJob) { var extractFolder = Path.Combine(ExportFolder, importJob.Directory); var dbName = Path.Combine(extractFolder, Constants.ExportDbName); - if (File.Exists(dbName)) - return; + if (File.Exists(dbName)) + { + return; + } + var zipDbName = Path.Combine(extractFolder, Constants.ExportZipDbName); CompressionUtil.UnZipFileFromArchive(Constants.ExportDbName, zipDbName, extractFolder, false); } @@ -605,7 +733,11 @@ private static void CleanupDatabaseIfDirty(IExportImportRepository repository) var isDirty = exportDto.IsDirty; exportDto.IsDirty = true; repository.UpdateSingleItem(exportDto); - if (!isDirty) return; + if (!isDirty) + { + return; + } + var typeLocator = new TypeLocator(); var types = typeLocator.GetAllMatchingTypes( t => t != null && t.IsClass && !t.IsAbstract && t.IsVisible && @@ -622,91 +754,12 @@ private static void CleanupDatabaseIfDirty(IExportImportRepository repository) } catch (Exception e) { - Logger.ErrorFormat("Unable to clear {0} while calling CleanupDatabaseIfDirty. Error: {1}", + Logger.ErrorFormat( + "Unable to clear {0} while calling CleanupDatabaseIfDirty. Error: {1}", type.Name, e.Message); } } - } - - private static string[] NotAllowedCategoriesinRequestArray => new[] - { - Constants.Category_Content, - Constants.Category_Pages, - Constants.Category_Portal, - Constants.Category_Content, - Constants.Category_Assets, - Constants.Category_Users, - Constants.Category_UsersData, - Constants.Category_Roles, - Constants.Category_Vocabularies, - Constants.Category_Templates, - Constants.Category_ProfileProps, - Constants.Category_Packages, - Constants.Category_Workflows, - }; - - private static string[] CleanUpIgnoredClasses => new[] - { - typeof (ExportFile).Name, - typeof (ExportFolder).Name, - typeof (ExportFolderMapping).Name, - typeof (ExportFolderPermission).Name, - typeof (ExportPageTemplate).Name, - typeof (ExportPortalSetting).Name, - typeof (ExportPortalLanguage).Name, - typeof (ExportProfileProperty).Name, - typeof (ExportUser).Name, - typeof (ExportAspnetUser).Name, - typeof (ExportAspnetMembership).Name, - typeof (ExportUserAuthentication).Name, - typeof (ExportUserPortal).Name, - typeof (ExportUserProfile).Name, - typeof (ExportUserRole).Name - }; - - public void AddLogsToDatabase(int jobId, ICollection completeLog) - { - if (completeLog == null || completeLog.Count == 0) return; - - using (var table = new DataTable("ExportImportJobLogs")) - { - // must create the columns from scratch with each iteration - table.Columns.AddRange(DatasetColumns.Select( - column => new DataColumn(column.Item1, column.Item2)).ToArray()); - - // batch specific amount of record each time - const int batchSize = 500; - var toSkip = 0; - while (toSkip < completeLog.Count) - { - foreach (var item in completeLog.Skip(toSkip).Take(batchSize)) - { - var row = table.NewRow(); - row["JobId"] = jobId; - row["Name"] = item.Name.TrimToLength(Constants.LogColumnLength); - row["Value"] = item.Value.TrimToLength(Constants.LogColumnLength); - row["Level"] = (int)item.ReportLevel; - row["CreatedOnDate"] = item.CreatedOnDate; - table.Rows.Add(row); - } - - PlatformDataProvider.Instance().BulkInsert("ExportImportJobLogs_AddBulk", "@DataTable", table); - toSkip += batchSize; - table.Rows.Clear(); - } - } - completeLog.Clear(); - } - - private static readonly Tuple[] DatasetColumns = - { - new Tuple("JobId", typeof(int)), - new Tuple("Name" , typeof(string)), - new Tuple("Value", typeof(string)), - new Tuple("Level", typeof(int)), - new Tuple("CreatedOnDate", typeof(DateTime)), - }; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs index 57204cb4d48..48d5698ffc8 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Entities { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Entities.Modules; + [Serializable] [TableName("ExportImportCheckpoints")] [PrimaryKey("CheckpointId")] @@ -18,50 +19,66 @@ public class ExportImportChekpoint : IHydratable private double _progress; public int CheckpointId { get; set; } + public int JobId { get; set; } + public string AssemblyName { get; set; } + public string Category { get; set; } + public int Stage { get; set; } // all stages start from 0 and increase + public string StageData { get; set; } // discretionary data + public DateTime StartDate { get; set; } + public DateTime LastUpdateDate { get; set; } public bool Completed { get; set; } public double Progress { - get { return _progress; } + get { return this._progress; } + set { - if (value < 0) value = 0; - else if (value > 100) value = 100; - _progress = value; + if (value < 0) + { + value = 0; + } + else if (value > 100) + { + value = 100; + } + + this._progress = value; } } public int TotalItems { get; set; } + public int ProcessedItems { get; set; } public int KeyID { - get { return CheckpointId; } - set { CheckpointId = value; } + get { return this.CheckpointId; } + set { this.CheckpointId = value; } } public void Fill(IDataReader dr) { - CheckpointId = Null.SetNullInteger(dr[nameof(CheckpointId)]); - JobId = Null.SetNullInteger(dr[nameof(JobId)]); - AssemblyName = Null.SetNullString(dr[nameof(AssemblyName)]); - Category = Null.SetNullString(dr[nameof(Category)]); - Stage = Null.SetNullInteger(dr[nameof(Stage)]); - StageData = Null.SetNullString(dr[nameof(StageData)]); - Progress = Null.SetNullInteger(dr[nameof(Progress)]); - TotalItems = Null.SetNullInteger(dr[nameof(TotalItems)]); - ProcessedItems = Null.SetNullInteger(dr[nameof(ProcessedItems)]); - StartDate = Null.SetNullDateTime(dr[nameof(StartDate)]); - LastUpdateDate = Null.SetNullDateTime(dr[nameof(LastUpdateDate)]); - Completed = Null.SetNullBoolean(dr[nameof(Completed)]); + this.CheckpointId = Null.SetNullInteger(dr[nameof(this.CheckpointId)]); + this.JobId = Null.SetNullInteger(dr[nameof(this.JobId)]); + this.AssemblyName = Null.SetNullString(dr[nameof(this.AssemblyName)]); + this.Category = Null.SetNullString(dr[nameof(this.Category)]); + this.Stage = Null.SetNullInteger(dr[nameof(this.Stage)]); + this.StageData = Null.SetNullString(dr[nameof(this.StageData)]); + this.Progress = Null.SetNullInteger(dr[nameof(this.Progress)]); + this.TotalItems = Null.SetNullInteger(dr[nameof(this.TotalItems)]); + this.ProcessedItems = Null.SetNullInteger(dr[nameof(this.ProcessedItems)]); + this.StartDate = Null.SetNullDateTime(dr[nameof(this.StartDate)]); + this.LastUpdateDate = Null.SetNullDateTime(dr[nameof(this.LastUpdateDate)]); + this.Completed = Null.SetNullBoolean(dr[nameof(this.Completed)]); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs index a43f515c6dd..0a0e101e1f1 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs @@ -1,70 +1,84 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using Dnn.ExportImport.Components.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Entities { + using System; + using System.Data; + + using Dnn.ExportImport.Components.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Entities.Modules; + [Serializable] [TableName("ExportImportJobs")] [PrimaryKey("JobId")] public class ExportImportJob : IHydratable { public int JobId { get; set; } + public int PortalId { get; set; } + public JobType JobType { get; set; } + public JobStatus JobStatus { get; set; } + public bool IsCancelled { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public int CreatedByUserId { get; set; } + public DateTime CreatedOnDate { get; set; } + public DateTime LastModifiedOnDate { get; set; } + public DateTime? CompletedOnDate { get; set; } + public string Directory { get; set; } + public string JobObject { get; set; } public int KeyID { - get { return JobId; } - set { JobId = value; } + get { return this.JobId; } + set { this.JobId = value; } } public void Fill(IDataReader dr) { - JobId = Null.SetNullInteger(dr[nameof(JobId)]); - PortalId = Null.SetNullInteger(dr[nameof(PortalId)]); - JobType = (JobType)Null.SetNullInteger(dr[nameof(JobType)]); - JobStatus = (JobStatus)Null.SetNullInteger(dr[nameof(JobStatus)]); - IsCancelled = Null.SetNullBoolean(dr[nameof(IsCancelled)]); - Name = Null.SetNullString(dr[nameof(Name)]); - Description = Null.SetNullString(dr[nameof(Description)]); - CreatedByUserId = Null.SetNullInteger(dr[nameof(CreatedByUserId)]); - CreatedOnDate = Null.SetNullDateTime(dr[nameof(CreatedOnDate)]); - LastModifiedOnDate = Null.SetNullDateTime(dr[nameof(LastModifiedOnDate)]); - CompletedOnDate = Null.SetNullDateTime(dr[nameof(CompletedOnDate)]); - Directory = Null.SetNullString(dr[nameof(Directory)]); - JobObject = Null.SetNullString(dr[nameof(JobObject)]); + this.JobId = Null.SetNullInteger(dr[nameof(this.JobId)]); + this.PortalId = Null.SetNullInteger(dr[nameof(this.PortalId)]); + this.JobType = (JobType)Null.SetNullInteger(dr[nameof(this.JobType)]); + this.JobStatus = (JobStatus)Null.SetNullInteger(dr[nameof(this.JobStatus)]); + this.IsCancelled = Null.SetNullBoolean(dr[nameof(this.IsCancelled)]); + this.Name = Null.SetNullString(dr[nameof(this.Name)]); + this.Description = Null.SetNullString(dr[nameof(this.Description)]); + this.CreatedByUserId = Null.SetNullInteger(dr[nameof(this.CreatedByUserId)]); + this.CreatedOnDate = Null.SetNullDateTime(dr[nameof(this.CreatedOnDate)]); + this.LastModifiedOnDate = Null.SetNullDateTime(dr[nameof(this.LastModifiedOnDate)]); + this.CompletedOnDate = Null.SetNullDateTime(dr[nameof(this.CompletedOnDate)]); + this.Directory = Null.SetNullString(dr[nameof(this.Directory)]); + this.JobObject = Null.SetNullString(dr[nameof(this.JobObject)]); - if (CreatedOnDate.Kind != DateTimeKind.Utc) + if (this.CreatedOnDate.Kind != DateTimeKind.Utc) { - CreatedOnDate = new DateTime( - CreatedOnDate.Year, CreatedOnDate.Month, CreatedOnDate.Day, - CreatedOnDate.Hour, CreatedOnDate.Minute, CreatedOnDate.Second, - CreatedOnDate.Millisecond, DateTimeKind.Utc); + this.CreatedOnDate = new DateTime( + this.CreatedOnDate.Year, this.CreatedOnDate.Month, this.CreatedOnDate.Day, + this.CreatedOnDate.Hour, this.CreatedOnDate.Minute, this.CreatedOnDate.Second, + this.CreatedOnDate.Millisecond, DateTimeKind.Utc); } - if (LastModifiedOnDate.Kind != DateTimeKind.Utc) + + if (this.LastModifiedOnDate.Kind != DateTimeKind.Utc) { - LastModifiedOnDate = new DateTime( - LastModifiedOnDate.Year, LastModifiedOnDate.Month, LastModifiedOnDate.Day, - LastModifiedOnDate.Hour, LastModifiedOnDate.Minute, LastModifiedOnDate.Second, - LastModifiedOnDate.Millisecond, DateTimeKind.Utc); + this.LastModifiedOnDate = new DateTime( + this.LastModifiedOnDate.Year, this.LastModifiedOnDate.Month, this.LastModifiedOnDate.Day, + this.LastModifiedOnDate.Hour, this.LastModifiedOnDate.Minute, this.LastModifiedOnDate.Second, + this.LastModifiedOnDate.Millisecond, DateTimeKind.Utc); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs index 83804c4bc14..49901ac98c2 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs @@ -1,41 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Entities { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Entities.Modules; + [Serializable] [TableName("ExportImportJobLogs")] [PrimaryKey("JobLogId")] public class ExportImportJobLog : IHydratable { public int JobLogId { get; set; } + public int JobId { get; set; } + public string Name { get; set; } + public string Value { get; set; } + public int Level { get; set; } + public DateTime CreatedOnDate { get; set; } public int KeyID { - get { return JobLogId; } - set { JobLogId = value; } + get { return this.JobLogId; } + set { this.JobLogId = value; } } public void Fill(IDataReader dr) { - JobLogId = Null.SetNullInteger(dr[nameof(JobLogId)]); - JobId = Null.SetNullInteger(dr[nameof(JobId)]); - Name = Null.SetNullString(dr[nameof(Name)]); - Value = Null.SetNullString(dr[nameof(Value)]); - Level = Null.SetNullInteger(dr[nameof(Level)]); - CreatedOnDate = Null.SetNullDateTime(dr[nameof(CreatedOnDate)]); + this.JobLogId = Null.SetNullInteger(dr[nameof(this.JobLogId)]); + this.JobId = Null.SetNullInteger(dr[nameof(this.JobId)]); + this.Name = Null.SetNullString(dr[nameof(this.Name)]); + this.Value = Null.SetNullString(dr[nameof(this.Value)]); + this.Level = Null.SetNullInteger(dr[nameof(this.Level)]); + this.CreatedOnDate = Null.SetNullDateTime(dr[nameof(this.CreatedOnDate)]); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs index 984f1c18d7e..9ed69584145 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs @@ -1,17 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Entities { + using System; + [Serializable] public class ExportImportSetting { public string SettingName { get; set; } + public string SettingValue { get; set; } + public bool SettingIsSecure { get; set; } + public int CreatedByUserId { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IDateTimeConverter.cs b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IDateTimeConverter.cs index 2a382529e66..130a271002d 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IDateTimeConverter.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IDateTimeConverter.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Interfaces { + using DotNetNuke.Entities.Users; + /// - /// Contract to convert all the datetiem properties in the class to User's local time + /// Contract to convert all the datetiem properties in the class to User's local time. /// internal interface IDateTimeConverter { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs index 0bec245263c..d1a2c9e558b 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs @@ -1,50 +1,73 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Dto.Pages; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Interfaces { + using System; + using System.Collections.Generic; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.Pages; + using DotNetNuke.Security.Permissions; + public interface IEntitiesController { ExportImportJob GetFirstActiveJob(); + ExportImportJob GetJobById(int jobId); + IList GetJobSummaryLog(int jobId); + IList GetJobFullLog(int jobId); + int GetAllJobsCount(int? portalId, int? jobType, string keywords); + IList GetAllJobs(int? portalId, int? pageSize, int? pageIndex, int? jobType, string keywords); + DateTime? GetLastJobTime(int portalId, JobType jobType); + void UpdateJobInfo(ExportImportJob job); + void UpdateJobStatus(ExportImportJob job); + void SetJobCancelled(ExportImportJob job); + void RemoveJob(ExportImportJob job); + IList GetJobChekpoints(int jobId); + void UpdateJobChekpoint(ExportImportChekpoint checkpoint); IList GetPortalTabs(int portalId, bool includeDeleted, bool includeSystem, DateTime toDate, DateTime? fromDate); + IList GetTabSettings(int tabId, DateTime toDate, DateTime? fromDate); + IList GetTabPermissions(int tabId, DateTime toDate, DateTime? fromDate); + IList GetTabUrls(int tabId, DateTime toDate, DateTime? fromDate); IList GetModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate); + IList GetModuleSettings(int moduleId, DateTime toDate, DateTime? fromDate); + IList GetModulePermissions(int moduleId, DateTime toDate, DateTime? fromDate); IList GetTabModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate); + IList GetTabModuleSettings(int tabId, DateTime toDate, DateTime? fromDate); + IList GetTabModuleSettings(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate); PermissionInfo GetPermissionInfo(string permissionCode, string permissionKey, string permissionName); void SetTabSpecificData(int tabId, bool isDeleted, bool isVisible); + void SetTabModuleDeleted(int tabModuleId, bool isDeleted); + void SetUserDeleted(int portalId, int userId, bool isDeleted); + void RunSchedule(); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs index 5ee95ebb306..17185f9ad8d 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs @@ -1,16 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using Dnn.ExportImport.Components.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Interfaces { + using System.Collections.Generic; + + using Dnn.ExportImport.Components.Entities; + public interface ISettingsController { IEnumerable GetAllSettings(); + ExportImportSetting GetSetting(string settingName); + void AddSetting(ExportImportSetting exportImportSetting); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs b/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs index ae10ade0b4a..40b2024adad 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs @@ -1,33 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto.Jobs; -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Models { + using System.Collections.Generic; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto.Jobs; + using DotNetNuke.Common.Utilities; + public class ExportImportResult { + public ExportImportResult() + { + this.CompleteLog = this.CompleteLog = new List(); + } + public int JobId { get; set; } + public IList CompleteLog { get; private set; } public IList Summary { - get { return CompleteLog.Where(item => item.ReportLevel >= ReportLevel.Info).ToList(); } - } - - public ExportImportResult() - { - CompleteLog = CompleteLog = new List(); + get { return this.CompleteLog.Where(item => item.ReportLevel >= ReportLevel.Info).ToList(); } } public LogItem AddSummary(string name, string value) { - return AddLogEntry(name, value, ReportLevel.Info); + return this.AddLogEntry(name, value, ReportLevel.Info); } public LogItem AddLogEntry(string name, string value, ReportLevel level = ReportLevel.Verbose) @@ -40,7 +42,7 @@ public LogItem AddLogEntry(string name, string value, ReportLevel level = Report CreatedOnDate = DateUtils.GetDatabaseUtcTime(), }; - CompleteLog.Add(item); + this.CompleteLog.Add(item); return item; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Models/ProgressToken.cs b/DNN Platform/Modules/DnnExportImport/Components/Models/ProgressToken.cs index 7091492c18b..15fc26aa605 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Models/ProgressToken.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Models/ProgressToken.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Models { public class ProgressToken { /// - /// This can be used as a continuation token for the operation. It + /// Gets or sets this can be used as a continuation token for the operation. It /// is an identifier for next operation/step in import/export process. /// public string ContinuationKey { get; set; } /// - /// Indicates the completed percentage progress of export/import operation. + /// Gets or sets indicates the completed percentage progress of export/import operation. /// public uint Progress { get; set; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs b/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs index f5952c1517d..b6c56dde2a0 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs @@ -1,22 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Entities; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security.Permissions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Providers { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Entities; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security.Permissions; + internal class DataProvider - { - #region Shared/Static Methods - + { private static readonly DataProvider Provider; private readonly DotNetNuke.Data.DataProvider _dataProvider = DotNetNuke.Data.DataProvider.Instance(); @@ -26,249 +25,253 @@ static DataProvider() Provider = new DataProvider(); } - public static DataProvider Instance() - { - return Provider; - } - private DataProvider() { // so it can't be instantiated outside this class - } - - #endregion + } + public static DataProvider Instance() + { + return Provider; + } + public void UpdateRecordChangers(string tableName, string primaryKeyName, int primaryKeyId, int? createdBy, int? modifiedBy) { - _dataProvider.ExecuteNonQuery( + this._dataProvider.ExecuteNonQuery( "Export_GenericUpdateRecordChangers", tableName, primaryKeyName, primaryKeyId, createdBy, modifiedBy); } public void UpdateUniqueId(string tableName, string primaryKeyName, int primaryKeyId, Guid uniqueId) { - _dataProvider.ExecuteNonQuery("Export_UpdateUniqueId", tableName, primaryKeyName, primaryKeyId, uniqueId); + this._dataProvider.ExecuteNonQuery("Export_UpdateUniqueId", tableName, primaryKeyName, primaryKeyId, uniqueId); } public void UpdateSettingRecordChangers(string tableName, string primaryKeyName, int parentKeyId, string settingName, int? createdBy, int? modifiedBy) { - _dataProvider.ExecuteNonQuery( + this._dataProvider.ExecuteNonQuery( "Export_GenedicUpdateSettingsRecordChangers", tableName, primaryKeyName, parentKeyId, settingName, createdBy, modifiedBy); } public int AddNewJob(int portalId, int userId, JobType jobType, string jobName, string jobDescription, string directory, string serializedObject) { - return _dataProvider.ExecuteScalar("ExportImportJobs_Add", portalId, + return this._dataProvider.ExecuteScalar("ExportImportJobs_Add", portalId, (int)jobType, userId, jobName, jobDescription, directory, serializedObject); } public void UpdateJobInfo(int jobId, string name, string description) { - _dataProvider.ExecuteNonQuery("ExportImportJobs_UpdateInfo", jobId, name, description); + this._dataProvider.ExecuteNonQuery("ExportImportJobs_UpdateInfo", jobId, name, description); } public void UpdateJobStatus(int jobId, JobStatus jobStatus) { DateTime? completeDate = null; - if (jobStatus == JobStatus.Failed || jobStatus == JobStatus.Successful) - completeDate = DateUtils.GetDatabaseUtcTime(); - - _dataProvider.ExecuteNonQuery( + if (jobStatus == JobStatus.Failed || jobStatus == JobStatus.Successful) + { + completeDate = DateUtils.GetDatabaseUtcTime(); + } + + this._dataProvider.ExecuteNonQuery( "ExportImportJobs_UpdateStatus", jobId, jobStatus, completeDate); } public void SetJobCancelled(int jobId) { - _dataProvider.ExecuteNonQuery("ExportImportJobs_SetCancelled", jobId); + this._dataProvider.ExecuteNonQuery("ExportImportJobs_SetCancelled", jobId); } public void RemoveJob(int jobId) { // using 60 sec timeout because cascading deletes in logs might take a lot of time - _dataProvider.ExecuteNonQuery(60, "ExportImportJobs_Remove", jobId); + this._dataProvider.ExecuteNonQuery(60, "ExportImportJobs_Remove", jobId); } public IDataReader GetExportImportSettings() { - return _dataProvider.ExecuteReader("ExportImport_Settings"); + return this._dataProvider.ExecuteReader("ExportImport_Settings"); } + public void AddExportImportSetting(ExportImportSetting exportImportSetting) { - _dataProvider.ExecuteNonQuery("ExportImport_AddSetting", exportImportSetting.SettingName, + this._dataProvider.ExecuteNonQuery("ExportImport_AddSetting", exportImportSetting.SettingName, exportImportSetting.SettingValue, exportImportSetting.SettingIsSecure, exportImportSetting.CreatedByUserId); } public IDataReader GetFirstActiveJob() { - return _dataProvider.ExecuteReader("ExportImportJobs_FirstActive"); + return this._dataProvider.ExecuteReader("ExportImportJobs_FirstActive"); } public IDataReader GetJobById(int jobId) { - return _dataProvider.ExecuteReader("ExportImportJobs_GetById", jobId); + return this._dataProvider.ExecuteReader("ExportImportJobs_GetById", jobId); } public IDataReader GetJobSummaryLog(int jobId) { - return _dataProvider.ExecuteReader("ExportImportJobLogs_Summary", jobId); + return this._dataProvider.ExecuteReader("ExportImportJobLogs_Summary", jobId); } public IDataReader GetJobFullLog(int jobId) { - return _dataProvider.ExecuteReader("ExportImportJobLogs_Full", jobId); + return this._dataProvider.ExecuteReader("ExportImportJobLogs_Full", jobId); } public int GetAllJobsCount(int? portalId, int? jobType, string keywords) { - return _dataProvider.ExecuteScalar("ExportImport_GetJobsCount", portalId, jobType, keywords); + return this._dataProvider.ExecuteScalar("ExportImport_GetJobsCount", portalId, jobType, keywords); } public IDataReader GetAllJobs(int? portalId, int? pageSize, int? pageIndex, int? jobType, string keywords) { - return _dataProvider.ExecuteReader( + return this._dataProvider.ExecuteReader( "ExportImportJobs_GetAll", portalId, pageSize, pageIndex, jobType, keywords); } public IDataReader GetJobChekpoints(int jobId) { - return _dataProvider.ExecuteReader("ExportImportCheckpoints_GetByJob", jobId); + return this._dataProvider.ExecuteReader("ExportImportCheckpoints_GetByJob", jobId); } public DateTime? GetLastJobTime(int portalId, JobType jobType) { - var datim = _dataProvider.ExecuteScalar("ExportImportJobLogs_LastJobTime", portalId, jobType); + var datim = this._dataProvider.ExecuteScalar("ExportImportJobLogs_LastJobTime", portalId, jobType); if (datim.HasValue) { var d = datim.Value; datim = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Millisecond, DateTimeKind.Utc); } + return datim; } public void UpsertJobChekpoint(ExportImportChekpoint checkpoint) { - _dataProvider.ExecuteNonQuery("ExportImportCheckpoints_Upsert", + this._dataProvider.ExecuteNonQuery( + "ExportImportCheckpoints_Upsert", checkpoint.JobId, checkpoint.AssemblyName, checkpoint.Category, checkpoint.Stage, checkpoint.StageData, - Null.SetNullInteger(Math.Floor(checkpoint.Progress)), checkpoint.TotalItems, checkpoint.ProcessedItems, _dataProvider.GetNull(checkpoint.StartDate), checkpoint.Completed); + Null.SetNullInteger(Math.Floor(checkpoint.Progress)), checkpoint.TotalItems, checkpoint.ProcessedItems, this._dataProvider.GetNull(checkpoint.StartDate), checkpoint.Completed); } public IDataReader GetAllScopeTypes() { - return _dataProvider.ExecuteReader("ExportTaxonomy_ScopeTypes"); + return this._dataProvider.ExecuteReader("ExportTaxonomy_ScopeTypes"); } public IDataReader GetAllVocabularyTypes() { - return _dataProvider.ExecuteReader("ExportTaxonomy_VocabularyTypes"); + return this._dataProvider.ExecuteReader("ExportTaxonomy_VocabularyTypes"); } public IDataReader GetAllTerms(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("ExportTaxonomy_Terms", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("ExportTaxonomy_Terms", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetAllVocabularies(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("ExportTaxonomy_Vocabularies", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("ExportTaxonomy_Vocabularies", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetAllRoleGroups(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_RoleGroups", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_RoleGroups", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetAllRoles(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_Roles", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_Roles", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetAllRoleSettings(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_RoleSettings", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_RoleSettings", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public int GetRoleIdByName(int portalId, string roleName) { - return _dataProvider.ExecuteScalar("Export_RoleIdByName", _dataProvider.GetNull(portalId), roleName); + return this._dataProvider.ExecuteScalar("Export_RoleIdByName", this._dataProvider.GetNull(portalId), roleName); } - - + public void SetRoleAutoAssign(int roleId) { - _dataProvider.ExecuteNonQuery("Export_RoleSetAutoAssign", roleId); + this._dataProvider.ExecuteNonQuery("Export_RoleSetAutoAssign", roleId); } public IDataReader GetPropertyDefinitionsByPortal(int portalId, bool includeDeleted, DateTime toDate, DateTime? fromDate) { - return _dataProvider - .ExecuteReader("Export_GetPropertyDefinitionsByPortal", portalId, includeDeleted, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider + .ExecuteReader("Export_GetPropertyDefinitionsByPortal", portalId, includeDeleted, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetAllUsers(int portalId, int pageIndex, int pageSize, bool includeDeleted, DateTime toDateUtc, DateTime? fromDateUtc) { - return _dataProvider + return this._dataProvider .ExecuteReader("Export_GetAllUsers", portalId, pageIndex, pageSize, includeDeleted, toDateUtc, - _dataProvider.GetNull(fromDateUtc), false); + this._dataProvider.GetNull(fromDateUtc), false); } public int GetUsersCount(int portalId, bool includeDeleted, DateTime toDateUtc, DateTime? fromDateUtc) { - return _dataProvider - .ExecuteScalar("Export_GetAllUsers", portalId, 0, 0, includeDeleted, toDateUtc, _dataProvider.GetNull(fromDateUtc), true); + return this._dataProvider + .ExecuteScalar("Export_GetAllUsers", portalId, 0, 0, includeDeleted, toDateUtc, this._dataProvider.GetNull(fromDateUtc), true); } public void UpdateUserChangers(int userId, string createdByUserName, string modifiedByUserName) { - _dataProvider.ExecuteNonQuery( + this._dataProvider.ExecuteNonQuery( "Export_UpdateUsersChangers", userId, createdByUserName, modifiedByUserName); } public IDataReader GetPortalSettings(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_GetPortalSettings", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_GetPortalSettings", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetPortalLanguages(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_GetPortalLanguages", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_GetPortalLanguages", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetPortalLocalizations(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_GetPortalLocalizations", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_GetPortalLocalizations", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetFolders(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_GetFolders", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_GetFolders", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetFolderPermissionsByPath(int portalId, string folderPath, DateTime toDate, DateTime? fromDate) { - return _dataProvider - .ExecuteReader("Export_GetFolderPermissionsByPath", portalId, folderPath, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider + .ExecuteReader("Export_GetFolderPermissionsByPath", portalId, folderPath, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetFolderMappings(int portalId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_GetFolderMappings", portalId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_GetFolderMappings", portalId, toDate, this._dataProvider.GetNull(fromDate)); } public IDataReader GetFiles(int portalId, int? folderId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_GetFiles", portalId, folderId, toDate, _dataProvider.GetNull(fromDate)); + return this._dataProvider.ExecuteReader("Export_GetFiles", portalId, folderId, toDate, this._dataProvider.GetNull(fromDate)); } public int? GetPermissionId(string permissionCode, string permissionKey, string permissionName) { return - CBO.GetCachedObject>(new CacheItemArgs(DataCache.PermissionsCacheKey, + CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PermissionsCacheKey, DataCache.PermissionsCacheTimeout, DataCache.PermissionsCachePriority), c => CBO.FillCollection( - _dataProvider.ExecuteReader("GetPermissions"))) + this._dataProvider.ExecuteReader("GetPermissions"))) .FirstOrDefault(x => x.PermissionCode == permissionCode && x.PermissionKey == permissionKey && x.PermissionName.Equals(permissionName, StringComparison.InvariantCultureIgnoreCase))?.PermissionID; @@ -276,102 +279,102 @@ public IDataReader GetFiles(int portalId, int? folderId, DateTime toDate, DateTi public IDataReader GetAllPortalTabs(int portalId, bool includeDeleted, bool includeSystem, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_Tabs", portalId, includeDeleted, includeSystem, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_Tabs", portalId, includeDeleted, includeSystem, toDate, fromDate); } public IDataReader GetAllTabSettings(int tabId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_TabSettings", tabId, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_TabSettings", tabId, toDate, fromDate); } public IDataReader GetAllTabPermissions(int tabId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_TabPermissions", tabId, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_TabPermissions", tabId, toDate, fromDate); } public IDataReader GetAllTabUrls(int tabId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_TabUrls", tabId, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_TabUrls", tabId, toDate, fromDate); } public IDataReader GetAllModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_Modules", tabId, includeDeleted, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_Modules", tabId, includeDeleted, toDate, fromDate); } public IDataReader GetAllModuleSettings(int moduleId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_ModuleSettings", moduleId, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_ModuleSettings", moduleId, toDate, fromDate); } public IDataReader GetAllModulePermissions(int moduleId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_ModulePermissions", moduleId, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_ModulePermissions", moduleId, toDate, fromDate); } public IDataReader GetAllTabModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_TabModules", tabId, includeDeleted, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_TabModules", tabId, includeDeleted, toDate, fromDate); } public bool CheckTabModuleUniqueIdExists(Guid uniqueId) { - return _dataProvider.ExecuteScalar("ExportImport_CheckTabModuleUniqueIdExists", uniqueId) > 0; + return this._dataProvider.ExecuteScalar("ExportImport_CheckTabModuleUniqueIdExists", uniqueId) > 0; } public bool CheckTabUniqueIdExists(Guid uniqueId) { - return _dataProvider.ExecuteScalar("ExportImport_CheckTabUniqueIdExists", uniqueId) > 0; + return this._dataProvider.ExecuteScalar("ExportImport_CheckTabUniqueIdExists", uniqueId) > 0; } public IDataReader GetAllTabModuleSettings(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_TabModuleSettings", tabId, includeDeleted, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_TabModuleSettings", tabId, includeDeleted, toDate, fromDate); } public void SetTabSpecificData(int tabId, bool isDeleted, bool isVisible) { - _dataProvider.ExecuteNonQuery("Export_SetTabSpecificData", tabId, isDeleted, isVisible); + this._dataProvider.ExecuteNonQuery("Export_SetTabSpecificData", tabId, isDeleted, isVisible); } public void SetTabModuleDeleted(int tabModuleId, bool isDeleted) { - _dataProvider.ExecuteNonQuery("Export_SetTabModuleDeleted", tabModuleId, isDeleted); + this._dataProvider.ExecuteNonQuery("Export_SetTabModuleDeleted", tabModuleId, isDeleted); } public void SetUserDeleted(int portalId, int userId, bool isDeleted) { - _dataProvider.ExecuteNonQuery("Export_SetUserDeleted", portalId, userId, isDeleted); + this._dataProvider.ExecuteNonQuery("Export_SetUserDeleted", portalId, userId, isDeleted); } public IDataReader GetPermissionInfo(string permissionCode, string permissionKey, string permissionName) { - return _dataProvider.ExecuteReader("Export_GetPermissionInfo", permissionCode, permissionKey, permissionName); + return this._dataProvider.ExecuteReader("Export_GetPermissionInfo", permissionCode, permissionKey, permissionName); } public void UpdateTabUrlChangers(int tabId, int seqNum, int? createdBy, int? modifiedBy) { - _dataProvider.ExecuteNonQuery("Export_UpdateTabUrlChangers", tabId, seqNum, createdBy, modifiedBy); + this._dataProvider.ExecuteNonQuery("Export_UpdateTabUrlChangers", tabId, seqNum, createdBy, modifiedBy); } public IDataReader GetAllWorkflows(int portalId, bool includeDeleted) { - return _dataProvider.ExecuteReader("Export_ContentWorkflows", portalId, includeDeleted); + return this._dataProvider.ExecuteReader("Export_ContentWorkflows", portalId, includeDeleted); } public IDataReader GetAllWorkflowSources(int workflowId) { - return _dataProvider.ExecuteReader("Export_ContentWorkflowSources", workflowId); + return this._dataProvider.ExecuteReader("Export_ContentWorkflowSources", workflowId); } public IDataReader GetAllWorkflowStates(int workflowId) { - return _dataProvider.ExecuteReader("Export_ContentWorkflowStates", workflowId); + return this._dataProvider.ExecuteReader("Export_ContentWorkflowStates", workflowId); } public IDataReader GetAllWorkflowStatePermissions(int workflowStateId, DateTime toDate, DateTime? fromDate) { - return _dataProvider.ExecuteReader("Export_ContentWorkflowStatePermissions", workflowStateId, toDate, fromDate); + return this._dataProvider.ExecuteReader("Export_ContentWorkflowStatePermissions", workflowStateId, toDate, fromDate); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs index c4c760045b2..1e9c2386db3 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs @@ -1,30 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text; -using System.Threading; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Controllers; -using Dnn.ExportImport.Components.Engines; -using Dnn.ExportImport.Components.Models; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Scheduling; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Scheduler { + using System; + using System.Text; + using System.Threading; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Controllers; + using Dnn.ExportImport.Components.Engines; + using Dnn.ExportImport.Components.Models; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Scheduling; + /// /// Implements a SchedulerClient for the Exporting/Importing of site items. /// public class ExportImportScheduler : SchedulerClient { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportScheduler)); - private const int EmergencyScheduleFrequency = 120; private const int DefaultScheduleFrequency = 1; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportScheduler)); private const string EmergencyScheduleFrequencyUnit = "m"; private const string DefaultScheduleFrequencyUnit = "d"; @@ -35,31 +36,29 @@ public class ExportImportScheduler : SchedulerClient private const int EmergencyHistoryNumber = 1; private const int DefaultHistoryNumber = 60; - - + public ExportImportScheduler(ScheduleHistoryItem objScheduleHistoryItem) { - ScheduleHistoryItem = objScheduleHistoryItem; + this.ScheduleHistoryItem = objScheduleHistoryItem; } public override void DoWork() { try { - //TODO: do some clean-up for very old import/export jobs/logs - + // TODO: do some clean-up for very old import/export jobs/logs var job = EntitiesController.Instance.GetFirstActiveJob(); if (job == null) { - ScheduleHistoryItem.Succeeded = true; - ScheduleHistoryItem.AddLogNote("
    No Site Export/Import jobs queued for processing."); + this.ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.AddLogNote("
    No Site Export/Import jobs queued for processing."); } else if (job.IsCancelled) { job.JobStatus = JobStatus.Cancelled; EntitiesController.Instance.UpdateJobStatus(job); - ScheduleHistoryItem.Succeeded = true; - ScheduleHistoryItem.AddLogNote("
    Site Export/Import jobs was previously cancelled."); + this.ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.AddLogNote("
    Site Export/Import jobs was previously cancelled."); } else { @@ -77,7 +76,7 @@ public override void DoWork() case JobType.Export: try { - engine.Export(job, result, ScheduleHistoryItem); + engine.Export(job, result, this.ScheduleHistoryItem); } catch (Exception ex) { @@ -85,22 +84,23 @@ public override void DoWork() engine.AddLogsToDatabase(job.JobId, result.CompleteLog); throw; } + EntitiesController.Instance.UpdateJobStatus(job); break; case JobType.Import: try { - engine.Import(job, result, ScheduleHistoryItem); + engine.Import(job, result, this.ScheduleHistoryItem); } catch (ThreadAbortException) { - ScheduleHistoryItem.TimeLapse = EmergencyScheduleFrequency; - ScheduleHistoryItem.TimeLapseMeasurement = EmergencyScheduleFrequencyUnit; - ScheduleHistoryItem.RetryTimeLapse = EmergencyScheduleRetry; - ScheduleHistoryItem.RetryTimeLapseMeasurement = EmergencyScheduleRetryUnit; - ScheduleHistoryItem.RetainHistoryNum = EmergencyHistoryNumber; + this.ScheduleHistoryItem.TimeLapse = EmergencyScheduleFrequency; + this.ScheduleHistoryItem.TimeLapseMeasurement = EmergencyScheduleFrequencyUnit; + this.ScheduleHistoryItem.RetryTimeLapse = EmergencyScheduleRetry; + this.ScheduleHistoryItem.RetryTimeLapseMeasurement = EmergencyScheduleRetryUnit; + this.ScheduleHistoryItem.RetainHistoryNum = EmergencyHistoryNumber; - SchedulingController.UpdateSchedule(ScheduleHistoryItem); + SchedulingController.UpdateSchedule(this.ScheduleHistoryItem); SchedulingController.PurgeScheduleHistory(); @@ -113,31 +113,33 @@ public override void DoWork() engine.AddLogsToDatabase(job.JobId, result.CompleteLog); throw; } + EntitiesController.Instance.UpdateJobStatus(job); if (job.JobStatus == JobStatus.Successful || job.JobStatus == JobStatus.Cancelled) { // clear everything to be sure imported items take effect DataCache.ClearCache(); } + break; default: throw new Exception("Unknown job type: " + job.JobType); } - ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.Succeeded = true; - //restore schedule item running timelapse to default. + // restore schedule item running timelapse to default. if (succeeded - && ScheduleHistoryItem.TimeLapse == EmergencyScheduleFrequency - && ScheduleHistoryItem.TimeLapseMeasurement == EmergencyScheduleFrequencyUnit) + && this.ScheduleHistoryItem.TimeLapse == EmergencyScheduleFrequency + && this.ScheduleHistoryItem.TimeLapseMeasurement == EmergencyScheduleFrequencyUnit) { - ScheduleHistoryItem.TimeLapse = DefaultScheduleFrequency; - ScheduleHistoryItem.TimeLapseMeasurement = DefaultScheduleFrequencyUnit; - ScheduleHistoryItem.RetryTimeLapse = DefaultScheduleRetry; - ScheduleHistoryItem.RetryTimeLapseMeasurement = DefaultScheduleRetryUnit; - ScheduleHistoryItem.RetainHistoryNum = DefaultHistoryNumber; + this.ScheduleHistoryItem.TimeLapse = DefaultScheduleFrequency; + this.ScheduleHistoryItem.TimeLapseMeasurement = DefaultScheduleFrequencyUnit; + this.ScheduleHistoryItem.RetryTimeLapse = DefaultScheduleRetry; + this.ScheduleHistoryItem.RetryTimeLapseMeasurement = DefaultScheduleRetryUnit; + this.ScheduleHistoryItem.RetainHistoryNum = DefaultHistoryNumber; - SchedulingController.UpdateSchedule(ScheduleHistoryItem); + SchedulingController.UpdateSchedule(this.ScheduleHistoryItem); } var sb = new StringBuilder(); @@ -152,26 +154,29 @@ public override void DoWork() { sb.Append($"
  • {entry.Name}: {entry.Value}
  • "); } + sb.Append(""); } - ScheduleHistoryItem.AddLogNote(sb.ToString()); + this.ScheduleHistoryItem.AddLogNote(sb.ToString()); engine.AddLogsToDatabase(job.JobId, result.CompleteLog); Logger.Trace("Site Export/Import: Job Finished"); } - //SetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID, ScheduleHistoryItem.StartDate); + + // SetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID, ScheduleHistoryItem.StartDate); } catch (Exception ex) { - ScheduleHistoryItem.Succeeded = false; - ScheduleHistoryItem.AddLogNote("
    Export/Import EXCEPTION: " + ex.Message); - Errored(ref ex); + this.ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.AddLogNote("
    Export/Import EXCEPTION: " + ex.Message); + this.Errored(ref ex); + // this duplicates the logging - //if (ScheduleHistoryItem.ScheduleSource != ScheduleSource.STARTED_FROM_BEGIN_REQUEST) - //{ + // if (ScheduleHistoryItem.ScheduleSource != ScheduleSource.STARTED_FROM_BEGIN_REQUEST) + // { // Exceptions.LogException(ex); - //} + // } } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs index 8c339c43507..e6aada00f44 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs @@ -1,40 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using DotNetNuke.Common.Utilities; -using System.Linq; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Common; -using Dnn.ExportImport.Components.Common; -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using Dnn.ExportImport.Dto.Assets; -using Dnn.ExportImport.Dto.Workflow; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using Newtonsoft.Json; -using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.Assets; + using Dnn.ExportImport.Dto.Workflow; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + using Newtonsoft.Json; + + using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; + public class AssetsExportService : BasePortableService { private const string DefaultUsersFoldersPath = "Users"; + + private const string UsersAssetsTempFolder = "{0}\\TempUsers\\"; - private static readonly Regex UserFolderEx = new Regex(@"users/\d+/\d+/(\d+)/", + private static readonly Regex UserFolderEx = new Regex( + @"users/\d+/\d+/(\d+)/", RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly string _assetsFolder = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\\{Constants.ExportZipFiles}"; - - private const string UsersAssetsTempFolder = "{0}\\TempUsers\\"; - public override string Category => Constants.Category_Assets; public override string ParentCategory => null; @@ -43,13 +45,19 @@ public class AssetsExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (CheckCancelled(exportJob)) return; - //Skip the export if all the folders have been processed already. - if (CheckPoint.Stage >= 1) - return; - - //Create Zip File to hold files - var skip = GetCurrentSkip(); + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + + // Create Zip File to hold files + var skip = this.GetCurrentSkip(); var currentIndex = skip; var totalFolderExported = 0; var totalFolderPermissionsExported = 0; @@ -57,9 +65,9 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var portalId = exportJob.PortalId; try { - var assetsFile = string.Format(_assetsFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); + var assetsFile = string.Format(this._assetsFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); @@ -70,18 +78,25 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) .GetFolders(portalId, toDate, fromDate)).ToList(); var totalFolders = folders.Any() ? folders.Count : 0; folders = folders.Skip(skip).ToList(); - - - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalFolders : CheckPoint.TotalItems; - CheckPoint.ProcessedItems = skip; - CheckPoint.Progress = CheckPoint.TotalItems > 0 ? skip * 100.0 / CheckPoint.TotalItems : 0; - if (CheckPointStageCallback(this)) return; + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalFolders : this.CheckPoint.TotalItems; + this.CheckPoint.ProcessedItems = skip; + this.CheckPoint.Progress = this.CheckPoint.TotalItems > 0 ? skip * 100.0 / this.CheckPoint.TotalItems : 0; + if (this.CheckPointStageCallback(this)) + { + return; + } + using (var zipArchive = CompressionUtil.OpenCreate(assetsFile)) { foreach (var folder in folders) { - if (CheckCancelled(exportJob)) break; + if (this.CheckCancelled(exportJob)) + { + break; + } + var isUserFolder = false; var files = @@ -96,132 +111,159 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) folder.Username = UserController.GetUserById(portalId, Convert.ToInt32(userId))?.Username; } + if (folder.ParentId != null && folder.ParentId > 0) { - //If parent id exists then change the parent folder id to parent id. + // If parent id exists then change the parent folder id to parent id. folder.ParentId = - Repository.GetItem( + this.Repository.GetItem( x => x.FolderId == Convert.ToInt32(folder.ParentId))?.Id; } - Repository.CreateItem(folder, null); + this.Repository.CreateItem(folder, null); totalFolderExported++; - //Include permissions only if IncludePermissions=true + + // Include permissions only if IncludePermissions=true if (exportDto.IncludePermissions) { var permissions = CBO.FillCollection(DataProvider.Instance() .GetFolderPermissionsByPath(portalId, folder.FolderPath, toDate, fromDate)); - Repository.CreateItems(permissions, folder.Id); + this.Repository.CreateItems(permissions, folder.Id); totalFolderPermissionsExported += permissions.Count; } - Repository.CreateItems(files, folder.Id); + + this.Repository.CreateItems(files, folder.Id); totalFilesExported += files.Count; var folderOffset = portal.HomeDirectoryMapPath.Length + (portal.HomeDirectoryMapPath.EndsWith("\\") ? 0 : 1); if (folder.StorageLocation != (int)FolderController.StorageLocationTypes.DatabaseSecure) { - - CompressionUtil.AddFilesToArchive(zipArchive, files.Select(file => portal.HomeDirectoryMapPath + folder.FolderPath + GetActualFileName(file)), + CompressionUtil.AddFilesToArchive(zipArchive, files.Select(file => portal.HomeDirectoryMapPath + folder.FolderPath + this.GetActualFileName(file)), folderOffset, isUserFolder ? "TempUsers" : null); - } - CheckPoint.ProcessedItems++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalFolders; - CheckPoint.StageData = null; + + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalFolders; + this.CheckPoint.StageData = null; currentIndex++; - //After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && CheckPointStageCallback(this)) return; - Repository.RebuildIndex(x => x.Id, true); - Repository.RebuildIndex(x => x.UserId); - Repository.RebuildIndex(x => x.ReferenceId); + + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } + + this.Repository.RebuildIndex(x => x.Id, true); + this.Repository.RebuildIndex(x => x.UserId); + this.Repository.RebuildIndex(x => x.ReferenceId); } } - CheckPoint.Completed = true; - CheckPoint.Stage++; + + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; currentIndex = 0; - CheckPoint.Progress = 100; + this.CheckPoint.Progress = 100; } } finally { - CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; - CheckPointStageCallback(this); - Result.AddSummary("Exported Folders", totalFolderExported.ToString()); - Result.AddSummary("Exported Folder Permissions", totalFolderPermissionsExported.ToString()); - Result.AddSummary("Exported Files", totalFilesExported.ToString()); + this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; + this.CheckPointStageCallback(this); + this.Result.AddSummary("Exported Folders", totalFolderExported.ToString()); + this.Result.AddSummary("Exported Folder Permissions", totalFolderPermissionsExported.ToString()); + this.Result.AddSummary("Exported Files", totalFilesExported.ToString()); } } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckCancelled(importJob)) return; - //Stage 1: Portals files unzipped. - //Stage 2: All folders and files imported. - //Stage 3: Synchronization completed. - //Skip the export if all the folders have been processed already. - if (CheckPoint.Stage >= 2 || CheckPoint.Completed) - return; - + if (this.CheckCancelled(importJob)) + { + return; + } + + // Stage 1: Portals files unzipped. + // Stage 2: All folders and files imported. + // Stage 3: Synchronization completed. + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 2 || this.CheckPoint.Completed) + { + return; + } + var totalFolderImported = 0; var totalFolderPermissionsImported = 0; var totalFilesImported = 0; - var skip = GetCurrentSkip(); + var skip = this.GetCurrentSkip(); var currentIndex = skip; var portalId = importJob.PortalId; var portal = PortalController.Instance.GetPortal(portalId); - var assetsFile = string.Format(_assetsFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); + var assetsFile = string.Format(this._assetsFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); var userFolderPath = string.Format(UsersAssetsTempFolder, portal.HomeDirectoryMapPath.TrimEnd('\\')); - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { if (!File.Exists(assetsFile)) { - Result.AddLogEntry("AssetsFileNotFound", "Assets file not found. Skipping assets import", + this.Result.AddLogEntry("AssetsFileNotFound", "Assets file not found. Skipping assets import", ReportLevel.Warn); - CheckPoint.Completed = true; - CheckPointStageCallback(this); + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); } else { CompressionUtil.UnZipArchive(assetsFile, portal.HomeDirectoryMapPath, importDto.CollisionResolution == CollisionResolution.Overwrite); - //Stage 1: Once unzipping of portal files is completed. - CheckPoint.Stage++; - CheckPoint.StageData = null; - CheckPoint.Progress = 10; - if (CheckPointStageCallback(this)) return; + + // Stage 1: Once unzipping of portal files is completed. + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + this.CheckPoint.Progress = 10; + if (this.CheckPointStageCallback(this)) + { + return; + } } } - if (CheckPoint.Stage == 1) + if (this.CheckPoint.Stage == 1) { try { - //Stage 2 starts - var sourceFolders = Repository.GetAllItems(x => x.CreatedOnDate, true, skip).ToList(); + // Stage 2 starts + var sourceFolders = this.Repository.GetAllItems(x => x.CreatedOnDate, true, skip).ToList(); var totalFolders = sourceFolders.Any() ? sourceFolders.Count : 0; - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalFolders : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalFolders : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + foreach (var sourceFolder in sourceFolders) { - if (CheckCancelled(importJob)) break; - // PROCESS FOLDERS - //Create new or update existing folder - if (ProcessFolder(importJob, importDto, sourceFolder)) + if (this.CheckCancelled(importJob)) + { + break; + } + + // PROCESS FOLDERS + // Create new or update existing folder + if (this.ProcessFolder(importJob, importDto, sourceFolder)) { totalFolderImported++; - //Include permissions only if permissions were exported in package. + // Include permissions only if permissions were exported in package. if (importDto.ExportDto.IncludePermissions) { // PROCESS FOLDER PERMISSIONS var sourceFolderPermissions = - Repository.GetRelatedItems(sourceFolder.Id).ToList(); - //Replace folderId for each permission with new one. + this.Repository.GetRelatedItems(sourceFolder.Id).ToList(); + + // Replace folderId for each permission with new one. sourceFolderPermissions.ForEach(x => { x.FolderId = Convert.ToInt32(sourceFolder.FolderId); @@ -229,7 +271,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) }); // PROCESS FOLDER PERMISSIONS - //File local files in the system related to the folder path. + // File local files in the system related to the folder path. var localPermissions = CBO.FillCollection(DataProvider.Instance() .GetFolderPermissionsByPath(portalId, sourceFolder.FolderPath, @@ -237,23 +279,25 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) foreach (var folderPermission in sourceFolderPermissions) { - ProcessFolderPermission(importJob, importDto, folderPermission, + this.ProcessFolderPermission(importJob, importDto, folderPermission, localPermissions); } + totalFolderPermissionsImported += sourceFolderPermissions.Count; } // PROCESS FILES var sourceFiles = - Repository.GetRelatedItems(sourceFolder.Id).ToList(); - //Replace folderId for each file with new one. + this.Repository.GetRelatedItems(sourceFolder.Id).ToList(); + + // Replace folderId for each file with new one. sourceFiles.ForEach(x => { x.FolderId = Convert.ToInt32(sourceFolder.FolderId); x.Folder = sourceFolder.FolderPath; }); - //File local files in the system related to the folder + // File local files in the system related to the folder var localFiles = CBO.FillCollection(DataProvider.Instance() .GetFiles(portalId, sourceFolder.FolderId, @@ -261,50 +305,73 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) foreach (var file in sourceFiles) { - ProcessFiles(importJob, importDto, file, localFiles); + this.ProcessFiles(importJob, importDto, file, localFiles); } + totalFilesImported += sourceFiles.Count; } currentIndex++; - CheckPoint.ProcessedItems++; - CheckPoint.Progress = 10 + CheckPoint.ProcessedItems * 90.0 / totalFolders; - //After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && CheckPointStageCallback(this)) return; + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress = 10 + (this.CheckPoint.ProcessedItems * 90.0 / totalFolders); + + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } + currentIndex = 0; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPoint.Progress = 100; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPoint.Progress = 100; } finally { - CheckPoint.StageData = currentIndex > 0 + this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; - CheckPointStageCallback(this); + this.CheckPointStageCallback(this); - Result.AddSummary("Imported Folders", totalFolderImported.ToString()); - Result.AddSummary("Imported Folder Permissions", totalFolderPermissionsImported.ToString()); - Result.AddSummary("Imported Files", totalFilesImported.ToString()); + this.Result.AddSummary("Imported Folders", totalFolderImported.ToString()); + this.Result.AddSummary("Imported Folder Permissions", totalFolderPermissionsImported.ToString()); + this.Result.AddSummary("Imported Files", totalFilesImported.ToString()); - if (Directory.Exists(userFolderPath) && currentIndex == 0) - Directory.Delete(userFolderPath, true); + if (Directory.Exists(userFolderPath) && currentIndex == 0) + { + Directory.Delete(userFolderPath, true); + } } } } public override int GetImportTotal() { - return Repository.GetCount(); + return this.Repository.GetCount(); + } + + private static bool IsUserFolder(string folderPath, out int? userId) + { + userId = null; + var match = UserFolderEx.Match(folderPath); + if (match.Success) + { + userId = int.Parse(match.Groups[1].Value); + } + + return match.Success; } private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, ExportFolder folder) { var portalId = importJob.PortalId; - if (folder == null) return false; - - var existingFolder = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().GetFolder(portalId, folder.FolderPath ?? "")); + if (folder == null) + { + return false; + } + + var existingFolder = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().GetFolder(portalId, folder.FolderPath ?? string.Empty)); var isUpdate = false; var modifiedBy = Util.GetUserIdByName(importJob, folder.LastModifiedByUserId, folder.LastModifiedByUserName); if (existingFolder != null) @@ -320,10 +387,15 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } - folder.FolderPath = string.IsNullOrEmpty(folder.FolderPath) ? "" : folder.FolderPath; + + folder.FolderPath = string.IsNullOrEmpty(folder.FolderPath) ? string.Empty : folder.FolderPath; var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, folder.FolderMappingName); - if (folderMapping == null) return false; - var workFlowId = GetLocalWorkFlowId(folder.WorkflowId); + if (folderMapping == null) + { + return false; + } + + var workFlowId = this.GetLocalWorkFlowId(folder.WorkflowId); if (isUpdate) { Util.FixDateTime(existingFolder); @@ -337,7 +409,7 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor if (folder.UserId != null && folder.UserId > 0 && !string.IsNullOrEmpty(folder.Username)) { - SyncUserFolder(importJob.PortalId, folder); + this.SyncUserFolder(importJob.PortalId, folder); } } else @@ -346,10 +418,11 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor var createdBy = Util.GetUserIdByName(importJob, folder.CreatedByUserId, folder.CreatedByUserName); if (folder.ParentId != null && folder.ParentId > 0) { - //Find the previously created parent folder id. - folder.ParentId = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().GetFolder(portalId, folder.ParentFolderPath ?? ""))?.FolderId; + // Find the previously created parent folder id. + folder.ParentId = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().GetFolder(portalId, folder.ParentFolderPath ?? string.Empty))?.FolderId; } - //ignore folders which start with Users but are not user folders. + + // ignore folders which start with Users but are not user folders. if (!folder.FolderPath.StartsWith(DefaultUsersFoldersPath)) { folder.FolderId = DotNetNuke.Data.DataProvider.Instance() @@ -359,7 +432,8 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor createdBy, folderMapping.FolderMappingID, folder.IsVersioned, workFlowId, folder.ParentId ?? Null.NullInteger); } - //Case when the folder is a user folder. + + // Case when the folder is a user folder. else if (folder.UserId != null && folder.UserId > 0 && !string.IsNullOrEmpty(folder.Username)) { var userInfo = UserController.GetUserByName(portalId, folder.Username); @@ -368,11 +442,12 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor folder.FolderId = 0; return false; } + userInfo.IsSuperUser = false; var newFolder = FolderManager.Instance.GetUserFolder(userInfo); folder.FolderId = newFolder.FolderID; folder.FolderPath = newFolder.FolderPath; - SyncUserFolder(importJob.PortalId, folder); + this.SyncUserFolder(importJob.PortalId, folder); return true; } else @@ -381,6 +456,7 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor return false; } } + return true; } @@ -389,7 +465,11 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import { var portalId = importJob.PortalId; var noRole = Convert.ToInt32(Globals.glbRoleNothing); - if (folderPermission == null) return; + if (folderPermission == null) + { + return; + } + var roleId = Util.GetRoleIdByName(portalId, folderPermission.RoleId ?? noRole, folderPermission.RoleName); var userId = UserController.GetUserByName(portalId, folderPermission.Username)?.UserID; @@ -415,6 +495,7 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } + if (isUpdate) { var modifiedBy = Util.GetUserIdByName(importJob, folderPermission.LastModifiedByUserId, @@ -439,15 +520,21 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import if (folderPermission.UserId != null && folderPermission.UserId > 0 && !string.IsNullOrEmpty(folderPermission.Username)) { folderPermission.UserId = userId; - if (folderPermission.UserId == null) - return; + if (folderPermission.UserId == null) + { + return; + } } + if (folderPermission.RoleId != null && folderPermission.RoleId > noRole && !string.IsNullOrEmpty(folderPermission.RoleName)) { folderPermission.RoleId = roleId; - if (folderPermission.RoleId == null) - return; + if (folderPermission.RoleId == null) + { + return; + } } + var createdBy = Util.GetUserIdByName(importJob, folderPermission.CreatedByUserId, folderPermission.CreatedByUserName); @@ -457,12 +544,17 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import folderPermission.UserId ?? Null.NullInteger, createdBy); } } + folderPermission.LocalId = folderPermission.FolderPermissionId; } private void ProcessFiles(ExportImportJob importJob, ImportDto importDto, ExportFile file, IEnumerable localFiles) { - if (file == null) return; + if (file == null) + { + return; + } + var existingFile = localFiles.FirstOrDefault(x => x.FileName == file.FileName); var isUpdate = false; if (existingFile != null) @@ -478,6 +570,7 @@ private void ProcessFiles(ExportImportJob importJob, ImportDto importDto, Export throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } + if (isUpdate) { var modifiedBy = Util.GetUserIdByName(importJob, file.LastModifiedByUserId, file.LastModifiedByUserName); @@ -506,13 +599,15 @@ private void ProcessFiles(ExportImportJob importJob, ImportDto importDto, Export file.Width ?? Null.NullInteger, file.Height ?? Null.NullInteger, file.ContentType, file.Folder, file.FolderId, createdBy, file.Sha1Hash, DateUtils.GetDatabaseLocalTime(), file.Title, file.Description, - file.StartDate, file.EndDate ?? Null.NullDate, file.EnablePublishPeriod, - //file.ContentItemId ?? Null.NullInteger);--If we keep it we will see FK_PK relationship errors. + file.StartDate, file.EndDate ?? Null.NullDate, file.EnablePublishPeriod, + + // file.ContentItemId ?? Null.NullInteger);--If we keep it we will see FK_PK relationship errors. Null.NullInteger); - - - if (file.Content != null) - DotNetNuke.Data.DataProvider.Instance().UpdateFileContent(file.FileId, file.Content); + + if (file.Content != null) + { + DotNetNuke.Data.DataProvider.Instance().UpdateFileContent(file.FileId, file.Content); + } } } @@ -522,31 +617,31 @@ private void SyncUserFolder(int portalId, ExportFolder folder) var tempUsersFolderPath = $"{string.Format(UsersAssetsTempFolder, portal.HomeDirectoryMapPath.TrimEnd('\\'))}{folder.FolderPath}"; var newUsersFolderPath = $"{portal.HomeDirectoryMapPath}{folder.FolderPath}"; - if (!Directory.Exists(tempUsersFolderPath)) - return; - if (!Directory.Exists(newUsersFolderPath)) - Directory.CreateDirectory(newUsersFolderPath); + if (!Directory.Exists(tempUsersFolderPath)) + { + return; + } + + if (!Directory.Exists(newUsersFolderPath)) + { + Directory.CreateDirectory(newUsersFolderPath); + } + var files = Directory.GetFiles(tempUsersFolderPath, "*.*", SearchOption.AllDirectories); var dirInfo = new DirectoryInfo(newUsersFolderPath); foreach ( var mFile in files.Select(file => new System.IO.FileInfo(file))) { - if (File.Exists(dirInfo + "\\" + mFile.Name)) - File.Delete(dirInfo + "\\" + mFile.Name); + if (File.Exists(dirInfo + "\\" + mFile.Name)) + { + File.Delete(dirInfo + "\\" + mFile.Name); + } + mFile.MoveTo(dirInfo + "\\" + mFile.Name); } } - private static bool IsUserFolder(string folderPath, out int? userId) - { - userId = null; - var match = UserFolderEx.Match(folderPath); - if (match.Success) - userId = int.Parse(match.Groups[1].Value); - return match.Success; - } - private string GetActualFileName(ExportFile objFile) { return (objFile.StorageLocation == (int)FolderController.StorageLocationTypes.SecureFileSystem) @@ -556,11 +651,12 @@ private string GetActualFileName(ExportFile objFile) private int GetCurrentSkip() { - if (!string.IsNullOrEmpty(CheckPoint.StageData)) + if (!string.IsNullOrEmpty(this.CheckPoint.StageData)) { - dynamic stageData = JsonConvert.DeserializeObject(CheckPoint.StageData); + dynamic stageData = JsonConvert.DeserializeObject(this.CheckPoint.StageData); return Convert.ToInt32(stageData.skip) ?? 0; } + return 0; } @@ -568,9 +664,10 @@ private int GetLocalWorkFlowId(int? exportedWorkFlowId) { if (exportedWorkFlowId != null && exportedWorkFlowId > 1) // 1 is direct publish { - var state = Repository.GetItem(item => item.WorkflowID == exportedWorkFlowId); + var state = this.Repository.GetItem(item => item.WorkflowID == exportedWorkFlowId); return state?.LocalId ?? -1; } + return -1; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs index 90c054fc868..b7c92b530f0 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs @@ -1,33 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Models; -using Dnn.ExportImport.Interfaces; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Models; + using Dnn.ExportImport.Interfaces; + /// /// A abstract class specifying the ability to import and export site different areas. /// public abstract class BasePortableService { /// - /// An object to record the export/import progress information. + /// Gets or sets an object to record the export/import progress information. /// This is set by the export/import engine. /// public ExportImportResult Result { get; set; } /// - /// A repository to store exported items in and to retrieve from upon import. + /// Gets or sets a repository to store exported items in and to retrieve from upon import. /// public IExportImportRepository Repository { get; set; } /// - /// A data structure representing a checkpoint for the export/import task. This can be used to tell the + /// Gets or sets a data structure representing a checkpoint for the export/import task. This can be used to tell the /// implementor where to resume it's operation if the job was interrupted previously. /// /// It is up to each BasePortableService implementor to track its own stages and status values to @@ -35,15 +36,15 @@ public abstract class BasePortableService public ExportImportChekpoint CheckPoint { get; set; } /// - /// A callback to the export/import engine to check if the undergoing export/import process was cancelled. - /// The interface concrete classes should keep checking continuously for the cancellation flag to be true + /// Gets or sets a callback to the export/import engine to check if the undergoing export/import process was cancelled. + /// The interface concrete classes should keep checking continuously for the cancellation flag to be true. /// If the callback returns true, the BasePortableService implementations should stop any work they do and /// return control to the caller immediately or as soon as possible. /// public Func CheckCancelled { get; set; } /// - /// Callback function to provide a checkpoint mechanism for an implementation. + /// Gets or sets callback function to provide a checkpoint mechanism for an implementation. /// The actual method shoul persist the reported checkpoint in the engine so if the process is interrupted, /// it can be resumed. If the reponse to calling this function was false, then the task should stop /// processing and return control immediately to the caller. @@ -54,25 +55,27 @@ public abstract class BasePortableService // The following properties and methods must be overriden in descendant classes /// - /// Category name for the exportable module. For example: "ASSETS". + /// Gets category name for the exportable module. For example: "ASSETS". /// public abstract string Category { get; } /// - /// Category name for the parent exportable module. For example: "USERS". + /// Gets category name for the parent exportable module. For example: "USERS". /// If this is null, then the category is a top parent. If this is not null, /// then this category will be included automatically when the parent is included. /// public abstract string ParentCategory { get; } /// - /// A priority for exporting/importing the object. Objects with higher + /// Gets a priority for exporting/importing the object. Objects with higher /// priority are exported/imported first. Highest priority is 0. /// public abstract uint Priority { get; } public abstract void ExportData(ExportImportJob exportJob, ExportDto exportDto); + public abstract void ImportData(ExportImportJob importJob, ImportDto importDto); + public abstract int GetImportTotal(); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs index 30a4ed95869..9b25b06eed4 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using DotNetNuke.Common.Utilities; -using System.Linq; -using DotNetNuke.Common; -using Dnn.ExportImport.Components.Common; -using System; -using System.IO; -using System.Text.RegularExpressions; -using Dnn.ExportImport.Dto.Pages; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.Pages; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer; + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + public class PackagesExportService : BasePortableService { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PackagesExportService)); @@ -31,17 +32,23 @@ public class PackagesExportService : BasePortableService public override string ParentCategory => null; - public override uint Priority => 18; //execute before pages service. + public override uint Priority => 18; // execute before pages service. public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (CheckCancelled(exportJob)) return; - //Skip the export if all the folders have been processed already. - if (CheckPoint.Stage >= 1) - return; - - //Create Zip File to hold files - var skip = GetCurrentSkip(); + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + + // Create Zip File to hold files + var skip = this.GetCurrentSkip(); var currentIndex = skip; var totalPackagesExported = 0; try @@ -49,77 +56,138 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var packagesZipFileFormat = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\\{Constants.ExportZipPackages}"; var packagesZipFile = string.Format(packagesZipFileFormat, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { var fromDate = exportDto.FromDateUtc ?? Constants.MinDbTime; var toDate = exportDto.ToDateUtc; - //export skin packages. + // export skin packages. var extensionPackagesBackupFolder = Path.Combine(Globals.ApplicationMapPath, DotNetNuke.Services.Installer.Util.BackupInstallPackageFolder); - var skinPackageFiles = Directory.GetFiles(extensionPackagesBackupFolder).Where(f => IsValidPackage(f, fromDate, toDate)).ToList(); + var skinPackageFiles = Directory.GetFiles(extensionPackagesBackupFolder).Where(f => this.IsValidPackage(f, fromDate, toDate)).ToList(); var totalPackages = skinPackageFiles.Count; - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalPackages : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalPackages : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + foreach (var file in skinPackageFiles) { - var exportPackage = GenerateExportPackage(file); + var exportPackage = this.GenerateExportPackage(file); if (exportPackage != null) { - Repository.CreateItem(exportPackage, null); + this.Repository.CreateItem(exportPackage, null); totalPackagesExported += 1; var folderOffset = Path.GetDirectoryName(file)?.Length + 1; CompressionUtil.AddFileToArchive(file, packagesZipFile, folderOffset.GetValueOrDefault(0)); } - CheckPoint.ProcessedItems++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalPackages; + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalPackages; currentIndex++; - //After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && CheckPointStageCallback(this)) return; + + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } - CheckPoint.Stage++; + this.CheckPoint.Stage++; currentIndex = 0; - CheckPoint.Completed = true; - CheckPoint.Progress = 100; + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; } } finally { - CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; - CheckPointStageCallback(this); - Result.AddSummary("Exported Packages", totalPackagesExported.ToString()); + this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; + this.CheckPointStageCallback(this); + this.Result.AddSummary("Exported Packages", totalPackagesExported.ToString()); } } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckCancelled(importJob)) return; - //Skip the export if all the templates have been processed already. - if (CheckPoint.Stage >= 1 || CheckPoint.Completed) - return; + if (this.CheckCancelled(importJob)) + { + return; + } + + // Skip the export if all the templates have been processed already. + if (this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed) + { + return; + } + + this._exportImportJob = importJob; + + this.ProcessImportModulePackages(importDto); + } + + public override int GetImportTotal() + { + return this.Repository.GetCount(); + } - _exportImportJob = importJob; + public void InstallPackage(string filePath) + { + using (var stream = new FileStream(filePath, FileMode.Open)) + { + try + { + var installer = GetInstaller(stream); + + if (installer.IsValid) + { + // Reset Log + installer.InstallerInfo.Log.Logs.Clear(); + + // Set the IgnnoreWhiteList flag + installer.InstallerInfo.IgnoreWhiteList = true; + + // Set the Repair flag + installer.InstallerInfo.RepairInstall = true; - ProcessImportModulePackages(importDto); + // Install + installer.Install(); + } + } + catch (Exception ex) + { + this.Result.AddLogEntry("Import Package error", $"{filePath}. ERROR: {ex.Message}"); + Logger.Error(ex); + } + } } - public override int GetImportTotal() + private static Installer GetInstaller(Stream stream) { - return Repository.GetCount(); + var installer = new Installer(stream, Globals.ApplicationMapPath, false, false) + { + InstallerInfo = { PortalID = Null.NullInteger }, + }; + + // Read the manifest + if (installer.InstallerInfo.ManifestFile != null) + { + installer.ReadManifest(true); + } + + return installer; } private int GetCurrentSkip() { - if (!string.IsNullOrEmpty(CheckPoint.StageData)) + if (!string.IsNullOrEmpty(this.CheckPoint.StageData)) { - dynamic stageData = JsonConvert.DeserializeObject(CheckPoint.StageData); + dynamic stageData = JsonConvert.DeserializeObject(this.CheckPoint.StageData); return Convert.ToInt32(stageData.skip) ?? 0; } + return 0; } @@ -155,7 +223,7 @@ private ExportPackage GenerateExportPackage(string filePath) return new ExportPackage { PackageFileName = fileName, PackageName = packageName, PackageType = packageType, Version = version }; } - private void ProcessImportModulePackage(ExportPackage exportPackage, String tempFolder, CollisionResolution collisionResolution) + private void ProcessImportModulePackage(ExportPackage exportPackage, string tempFolder, CollisionResolution collisionResolution) { try { @@ -169,25 +237,27 @@ private void ProcessImportModulePackage(ExportPackage exportPackage, String temp var packageName = exportPackage.PackageName; var version = exportPackage.Version; - var existPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, + var existPackage = PackageController.Instance.GetExtensionPackage( + Null.NullInteger, p => p.PackageType == packageType && p.Name == packageName); if (existPackage != null && (existPackage.Version > version || (existPackage.Version == version && collisionResolution == CollisionResolution.Ignore))) { - Result.AddLogEntry("Import Package ignores", + this.Result.AddLogEntry( + "Import Package ignores", $"{packageName} has higher version {existPackage.Version} installed, ignore import it"); return; } - InstallPackage(filePath); - Result.AddLogEntry("Import Package completed", $"{packageName} version: {version}"); - + this.InstallPackage(filePath); + this.Result.AddLogEntry("Import Package completed", $"{packageName} version: {version}"); } catch (Exception ex) { - Result.AddLogEntry("Import Package error", + this.Result.AddLogEntry( + "Import Package error", $"{exportPackage.PackageName} : {exportPackage.Version} - {ex.Message}"); Logger.Error(ex); } @@ -195,102 +265,58 @@ private void ProcessImportModulePackage(ExportPackage exportPackage, String temp private void ProcessImportModulePackages(ImportDto importDto) { - var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{_exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipPackages}"; + var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{this._exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipPackages}"; var tempFolder = $"{Path.GetDirectoryName(packageZipFile)}\\{DateTime.Now.Ticks}"; if (File.Exists(packageZipFile)) { CompressionUtil.UnZipArchive(packageZipFile, tempFolder); - var exportPackages = Repository.GetAllItems().ToList(); - - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? exportPackages.Count : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - - if (CheckPoint.Stage == 0) + var exportPackages = this.Repository.GetAllItems().ToList(); + + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? exportPackages.Count : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + + if (this.CheckPoint.Stage == 0) { try { foreach (var exportPackage in exportPackages) { - - ProcessImportModulePackage(exportPackage, tempFolder, importDto.CollisionResolution); - - CheckPoint.ProcessedItems++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / exportPackages.Count; - if (CheckPointStageCallback(this)) break; - + this.ProcessImportModulePackage(exportPackage, tempFolder, importDto.CollisionResolution); + + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / exportPackages.Count; + if (this.CheckPointStageCallback(this)) + { + break; + } } - CheckPoint.Stage++; - CheckPoint.Completed = true; + + this.CheckPoint.Stage++; + this.CheckPoint.Completed = true; } finally { - CheckPointStageCallback(this); + this.CheckPointStageCallback(this); try { FileSystemUtils.DeleteFolderRecursive(tempFolder); } catch (Exception) { - //ignore + // ignore } } } } else { - CheckPoint.Completed = true; - CheckPointStageCallback(this); - Result.AddLogEntry("PackagesFileNotFound", "Packages file not found. Skipping packages import", ReportLevel.Warn); + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); + this.Result.AddLogEntry("PackagesFileNotFound", "Packages file not found. Skipping packages import", ReportLevel.Warn); } } - - public void InstallPackage(string filePath) - { - using (var stream = new FileStream(filePath, FileMode.Open)) - { - try - { - var installer = GetInstaller(stream); - - if (installer.IsValid) - { - //Reset Log - installer.InstallerInfo.Log.Logs.Clear(); - - //Set the IgnnoreWhiteList flag - installer.InstallerInfo.IgnoreWhiteList = true; - - //Set the Repair flag - installer.InstallerInfo.RepairInstall = true; - - //Install - installer.Install(); - } - } - catch (Exception ex) - { - Result.AddLogEntry("Import Package error", $"{filePath}. ERROR: {ex.Message}"); - Logger.Error(ex); - } - } - } - - private static Installer GetInstaller(Stream stream) - { - var installer = new Installer(stream, Globals.ApplicationMapPath, false, false) - { - InstallerInfo = { PortalID = Null.NullInteger } - }; - - //Read the manifest - if (installer.InstallerInfo.ManifestFile != null) - { - installer.ReadManifest(true); - } - - return installer; - } - - } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs index 8ab1aae4d1d..b80e8f53b1b 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs @@ -1,24 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using DotNetNuke.Common.Utilities; -using System.Linq; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Common; -using Dnn.ExportImport.Components.Common; -using System; -using System.IO; -using Dnn.ExportImport.Dto.PageTemplates; -using DotNetNuke.Collections; -using DotNetNuke.Entities.Portals; -using Newtonsoft.Json; -using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.IO; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.PageTemplates; + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.FileSystem; + using Newtonsoft.Json; + + using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; + public class PageTemplatesExportService : AssetsExportService { private readonly string _templatesFolder = @@ -32,21 +34,27 @@ public class PageTemplatesExportService : AssetsExportService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (CheckCancelled(exportJob)) return; - //Skip the export if all the folders have been processed already. - if (CheckPoint.Stage >= 1) - return; - - //Create Zip File to hold files - var skip = GetCurrentSkip(); + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + + // Create Zip File to hold files + var skip = this.GetCurrentSkip(); var currentIndex = skip; var totalTemplatesExported = 0; var portalId = exportJob.PortalId; try { - var templatesFile = string.Format(_templatesFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); + var templatesFile = string.Format(this._templatesFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); @@ -60,64 +68,81 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) .ToList(); var totalTemplates = templates.Count; - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalTemplates : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalTemplates : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + foreach (var template in templates) { - Repository.CreateItem(template, null); + this.Repository.CreateItem(template, null); totalTemplatesExported += 1; var folderOffset = portal.HomeDirectoryMapPath.Length + (portal.HomeDirectoryMapPath.EndsWith("\\") ? 0 : 1); var folder = FolderManager.Instance.GetFolder(template.FolderId); CompressionUtil.AddFileToArchive( - portal.HomeDirectoryMapPath + folder.FolderPath + GetActualFileName(template), templatesFile, + portal.HomeDirectoryMapPath + folder.FolderPath + this.GetActualFileName(template), templatesFile, folderOffset); - CheckPoint.ProcessedItems++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalTemplates; + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalTemplates; currentIndex++; - //After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && CheckPointStageCallback(this)) return; + + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } - CheckPoint.Stage++; + + this.CheckPoint.Stage++; currentIndex = 0; - CheckPoint.Completed = true; - CheckPoint.Progress = 100; + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; } } finally { - CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; - CheckPointStageCallback(this); - Result.AddSummary("Exported Templates", totalTemplatesExported.ToString()); + this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; + this.CheckPointStageCallback(this); + this.Result.AddSummary("Exported Templates", totalTemplatesExported.ToString()); } } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckCancelled(importJob)) return; - //Skip the export if all the templates have been processed already. - if (CheckPoint.Stage >= 2 || CheckPoint.Completed) - return; - + if (this.CheckCancelled(importJob)) + { + return; + } + + // Skip the export if all the templates have been processed already. + if (this.CheckPoint.Stage >= 2 || this.CheckPoint.Completed) + { + return; + } + var portalId = importJob.PortalId; - var templatesFile = string.Format(_templatesFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); - var totalTemplates = GetImportTotal(); - - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalTemplates : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - - if (CheckPoint.Stage == 0) + var templatesFile = string.Format(this._templatesFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); + var totalTemplates = this.GetImportTotal(); + + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalTemplates : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + + if (this.CheckPoint.Stage == 0) { if (!File.Exists(templatesFile)) { - Result.AddLogEntry("TemplatesFileNotFound", "Templates file not found. Skipping templates import", + this.Result.AddLogEntry("TemplatesFileNotFound", "Templates file not found. Skipping templates import", ReportLevel.Warn); - CheckPoint.Completed = true; - CheckPointStageCallback(this); + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); } else { @@ -126,30 +151,34 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) CompressionUtil.UnZipArchive(templatesFile, portal.HomeDirectoryMapPath, importDto.CollisionResolution == CollisionResolution.Overwrite); - Result.AddSummary("Imported templates", totalTemplates.ToString()); - CheckPoint.Stage++; - CheckPoint.StageData = null; - CheckPoint.Progress = 90; - CheckPoint.TotalItems = totalTemplates; - CheckPoint.ProcessedItems = totalTemplates; - if (CheckPointStageCallback(this)) return; + this.Result.AddSummary("Imported templates", totalTemplates.ToString()); + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + this.CheckPoint.Progress = 90; + this.CheckPoint.TotalItems = totalTemplates; + this.CheckPoint.ProcessedItems = totalTemplates; + if (this.CheckPointStageCallback(this)) + { + return; + } } } - if (CheckPoint.Stage == 1) + + if (this.CheckPoint.Stage == 1) { Func predicate = x => x.Folder; - var templates = Repository.GetAllItems(predicate).Select(x => x.Folder).Distinct(); + var templates = this.Repository.GetAllItems(predicate).Select(x => x.Folder).Distinct(); templates.ForEach(x => FolderManager.Instance.Synchronize(importJob.PortalId, x)); - CheckPoint.Stage++; - CheckPoint.Completed = true; - CheckPoint.Progress = 100; - CheckPointStageCallback(this); + this.CheckPoint.Stage++; + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; + this.CheckPointStageCallback(this); } } public override int GetImportTotal() { - return Repository.GetCount(); + return this.Repository.GetCount(); } private string GetActualFileName(ExportPageTemplate objFile) @@ -161,11 +190,12 @@ private string GetActualFileName(ExportPageTemplate objFile) private int GetCurrentSkip() { - if (!string.IsNullOrEmpty(CheckPoint.StageData)) + if (!string.IsNullOrEmpty(this.CheckPoint.StageData)) { - dynamic stageData = JsonConvert.DeserializeObject(CheckPoint.StageData); + dynamic stageData = JsonConvert.DeserializeObject(this.CheckPoint.StageData); return Convert.ToInt32(stageData.skip) ?? 0; } + return 0; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs index 16791e80513..a17c55df943 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs @@ -1,49 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Controllers; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Engines; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Providers; -using Dnn.ExportImport.Dto.Pages; -using Dnn.ExportImport.Dto.Workflow; -using Dnn.ExportImport.Repository; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using Newtonsoft.Json; -using Util = Dnn.ExportImport.Components.Common.Util; -using InstallerUtil = DotNetNuke.Services.Installer.Util; -using TermHelper = DotNetNuke.Entities.Content.Taxonomy.TermHelper; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable SuggestBaseTypeForParameter - namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Controllers; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Engines; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Providers; + using Dnn.ExportImport.Dto.Pages; + using Dnn.ExportImport.Dto.Workflow; + using Dnn.ExportImport.Repository; + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using Newtonsoft.Json; + + using InstallerUtil = DotNetNuke.Services.Installer.Util; + using TermHelper = DotNetNuke.Entities.Content.Taxonomy.TermHelper; + using Util = Dnn.ExportImport.Components.Common.Util; + /// /// Service to export/import pages/tabs. /// public class PagesExportService : BasePortableService { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); + + private ProgressTotals _totals; + private DataProvider _dataProvider; + private ITabController _tabController; + public override string Category => Constants.Category_Pages; public override string ParentCategory => null; @@ -54,150 +61,157 @@ public class PagesExportService : BasePortableService public virtual bool IgnoreParentMatch { get; set; } = false; - protected ImportDto ImportDto => _importDto; - - private ProgressTotals _totals; - private DataProvider _dataProvider; - private ITabController _tabController; + protected ImportDto ImportDto => this._importDto; private IModuleController _moduleController; private ExportImportJob _exportImportJob; private ImportDto _importDto; private ExportDto _exportDto; private IList _exportedModuleDefinitions = new List(); - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); private Dictionary _partialImportedTabs = new Dictionary(); private Dictionary _searchedParentTabs = new Dictionary(); private IList _importContentList = new List(); // map the exported module and local module. - public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) + public static void ResetContentsFlag(ExportImportRepository repository) { - if (CheckPoint.Stage > 0) return; - if (CheckCancelled(exportJob)) return; + // reset restored flag; if it same extracted db is reused, then content will be restored + var toSkip = 0; + const int batchSize = 100; + var totalCount = repository.GetCount(); + while (totalCount > 0) + { + var items = repository.GetAllItems(skip: toSkip, max: batchSize) + .Where(item => item.IsRestored).ToList(); + if (items.Count > 0) + { + items.ForEach(item => item.IsRestored = false); + repository.UpdateItems(items); + } + + toSkip += batchSize; + totalCount -= batchSize; + } + } + public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) + { + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var checkedPages = exportDto.Pages.Where(p => p.CheckedState == TriCheckedState.Checked || p.CheckedState == TriCheckedState.CheckedWithAllChildren); if (checkedPages.Any()) { - _exportImportJob = exportJob; - _exportDto = exportDto; - _tabController = TabController.Instance; - _moduleController = ModuleController.Instance; - ProcessExportPages(); + this._exportImportJob = exportJob; + this._exportDto = exportDto; + this._tabController = TabController.Instance; + this._moduleController = ModuleController.Instance; + this.ProcessExportPages(); } - CheckPoint.Progress = 100; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPoint.StageData = null; - CheckPointStageCallback(this); + this.CheckPoint.Progress = 100; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + this.CheckPointStageCallback(this); } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckPoint.Stage > 0) return; - if (CheckCancelled(importJob)) return; - - _exportImportJob = importJob; - _importDto = importDto; - _exportDto = importDto.ExportDto; - _tabController = TabController.Instance; - _moduleController = ModuleController.Instance; - - ProcessImportPages(); - - CheckPoint.Progress = 100; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPoint.StageData = null; - CheckPointStageCallback(this); + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(importJob)) + { + return; + } + + this._exportImportJob = importJob; + this._importDto = importDto; + this._exportDto = importDto.ExportDto; + this._tabController = TabController.Instance; + this._moduleController = ModuleController.Instance; + + this.ProcessImportPages(); + + this.CheckPoint.Progress = 100; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + this.CheckPointStageCallback(this); } public override int GetImportTotal() { - return Repository.GetCount(x => x.IsSystem == IncludeSystem); - } + return this.Repository.GetCount(x => x.IsSystem == this.IncludeSystem); + } - #region import methods - - private void ProcessImportPages() + public void RestoreTab(TabInfo tab, PortalSettings portalSettings) { - _dataProvider = DataProvider.Instance(); - _totals = string.IsNullOrEmpty(CheckPoint.StageData) - ? new ProgressTotals() - : JsonConvert.DeserializeObject(CheckPoint.StageData); - - var portalId = _exportImportJob.PortalId; - - var localTabs = _tabController.GetTabsByPortal(portalId).Values.ToList(); - - var exportedTabs = Repository.GetItems(x => x.IsSystem == (Category == Constants.Category_Templates)) - .OrderBy(t => t.Level).ThenBy(t => t.ParentId).ThenBy(t => t.TabOrder).ToList(); - - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? exportedTabs.Count : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - var progressStep = 100.0 / exportedTabs.OrderByDescending(x => x.Id).Count(x => x.Id < _totals.LastProcessedId); - - var index = 0; - var referenceTabs = new List(); - _importContentList.Clear(); - foreach (var otherTab in exportedTabs) + var changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState(tab.PortalID, tab.TabID); + if (changeControlStateForTab.IsChangeControlEnabledForTab) { - if (CheckCancelled(_exportImportJob)) break; - if (_totals.LastProcessedId > index) continue; // this is the exported DB row ID; not the TabID - - ProcessImportPage(otherTab, exportedTabs, localTabs, referenceTabs); - - CheckPoint.ProcessedItems++; - CheckPoint.Progress += progressStep; - if (CheckPointStageCallback(this)) break; - - _totals.LastProcessedId = index++; - CheckPoint.StageData = JsonConvert.SerializeObject(_totals); + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); } - //repair pages which linked to other pages - RepairReferenceTabs(referenceTabs, localTabs, exportedTabs); + this._tabController.RestoreTab(tab, portalSettings); - _searchedParentTabs.Clear(); - ReportImportTotals(); + if (changeControlStateForTab.IsChangeControlEnabledForTab) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, changeControlStateForTab.IsVersioningEnabledForTab); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); + } } protected virtual void ProcessImportPage(ExportTab otherTab, IList exportedTabs, IList localTabs, IList referenceTabs) { - var portalId = _exportImportJob.PortalId; - var createdBy = Util.GetUserIdByName(_exportImportJob, otherTab.CreatedByUserID, otherTab.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, otherTab.LastModifiedByUserID, otherTab.LastModifiedByUserName); + var portalId = this._exportImportJob.PortalId; + var createdBy = Util.GetUserIdByName(this._exportImportJob, otherTab.CreatedByUserID, otherTab.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, otherTab.LastModifiedByUserID, otherTab.LastModifiedByUserName); var localTab = localTabs.FirstOrDefault(t => otherTab.UniqueId.Equals(t.UniqueId)) ?? localTabs.FirstOrDefault(t => otherTab.TabPath.Equals(t.TabPath, StringComparison.InvariantCultureIgnoreCase) && IsSameCulture(t.CultureCode, otherTab.CultureCode)); - var isParentPresent = IsParentTabPresentInExport(otherTab, exportedTabs, localTabs); + var isParentPresent = this.IsParentTabPresentInExport(otherTab, exportedTabs, localTabs); if (localTab != null) { localTab.TabSettings.Remove("TabImported"); otherTab.LocalId = localTab.TabID; - switch (_importDto.CollisionResolution) + switch (this._importDto.CollisionResolution) { case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored Tab", $"{otherTab.TabName} ({otherTab.TabPath})"); + this.Result.AddLogEntry("Ignored Tab", $"{otherTab.TabName} ({otherTab.TabPath})"); break; case CollisionResolution.Overwrite: - if (!IsTabPublished(localTab)) return; + if (!this.IsTabPublished(localTab)) + { + return; + } + SetTabData(localTab, otherTab); - localTab.StateID = GetLocalStateId(otherTab.StateID); - var parentId = IgnoreParentMatch ? otherTab.ParentId.GetValueOrDefault(Null.NullInteger) : TryFindLocalParentTabId(otherTab, exportedTabs, localTabs); + localTab.StateID = this.GetLocalStateId(otherTab.StateID); + var parentId = this.IgnoreParentMatch ? otherTab.ParentId.GetValueOrDefault(Null.NullInteger) : TryFindLocalParentTabId(otherTab, exportedTabs, localTabs); if (parentId == -1 && otherTab.ParentId > 0) { if (!isParentPresent) { - Result.AddLogEntry("Importing existing tab skipped as its parent was not found", $"{otherTab.TabName} ({otherTab.TabPath})", ReportLevel.Warn); + this.Result.AddLogEntry("Importing existing tab skipped as its parent was not found", $"{otherTab.TabName} ({otherTab.TabPath})", ReportLevel.Warn); return; } - CheckForPartialImportedTabs(otherTab); + + this.CheckForPartialImportedTabs(otherTab); } + var tabType = Globals.GetURLType(otherTab.Url); if (tabType == TabType.Tab && !referenceTabs.Contains(localTab.TabID)) { @@ -207,12 +221,14 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex // this is not saved when adding the tab; so set it explicitly localTab.IsVisible = otherTab.IsVisible; EntitiesController.Instance.SetTabSpecificData(localTab.TabID, false, localTab.IsVisible); - //Try to set the unique id of existing page same as source page unique id, if possible. This will help for future updates etc. + + // Try to set the unique id of existing page same as source page unique id, if possible. This will help for future updates etc. if (localTab.UniqueId != otherTab.UniqueId && !DataProvider.Instance().CheckTabUniqueIdExists(otherTab.UniqueId)) { localTab.UniqueId = otherTab.UniqueId; - UpdateTabUniqueId(localTab.TabID, localTab.UniqueId); + this.UpdateTabUniqueId(localTab.TabID, localTab.UniqueId); } + try { localTab.TabPermissions.Clear(); // without this the UpdateTab() could fail @@ -221,40 +237,41 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex { localTab.Url = otherTab.Url; } - SetPartialImportSettings(otherTab, localTab); - _tabController.UpdateTab(localTab); + + this.SetPartialImportSettings(otherTab, localTab); + this._tabController.UpdateTab(localTab); DotNetNuke.Data.DataProvider.Instance().UpdateTabOrder(localTab.TabID, localTab.TabOrder, localTab.ParentId, Null.NullInteger); } catch (Exception ex) { - Result.AddLogEntry($"Importing tab '{otherTab.TabName}' exception", ex.Message, ReportLevel.Error); + this.Result.AddLogEntry($"Importing tab '{otherTab.TabName}' exception", ex.Message, ReportLevel.Error); return; } - UpdateTabChangers(localTab.TabID, createdBy, modifiedBy); - UpdateDefaultLanguageGuid(portalId, localTab, otherTab, exportedTabs); - AddTabRelatedItems(localTab, otherTab, false); - TriggerImportEvent(localTab); - Result.AddLogEntry("Updated Tab", $"{otherTab.TabName} ({otherTab.TabPath})"); - _totals.TotalTabs++; + this.UpdateTabChangers(localTab.TabID, createdBy, modifiedBy); + this.UpdateDefaultLanguageGuid(portalId, localTab, otherTab, exportedTabs); + this.AddTabRelatedItems(localTab, otherTab, false); + this.TriggerImportEvent(localTab); + this.Result.AddLogEntry("Updated Tab", $"{otherTab.TabName} ({otherTab.TabPath})"); + this._totals.TotalTabs++; break; default: - throw new ArgumentOutOfRangeException(_importDto.CollisionResolution.ToString()); + throw new ArgumentOutOfRangeException(this._importDto.CollisionResolution.ToString()); } } else { localTab = new TabInfo { PortalID = portalId }; SetTabData(localTab, otherTab); - localTab.StateID = GetLocalStateId(otherTab.StateID); - var parentId = IgnoreParentMatch ? otherTab.ParentId.GetValueOrDefault(Null.NullInteger) : TryFindLocalParentTabId(otherTab, exportedTabs, localTabs); + localTab.StateID = this.GetLocalStateId(otherTab.StateID); + var parentId = this.IgnoreParentMatch ? otherTab.ParentId.GetValueOrDefault(Null.NullInteger) : TryFindLocalParentTabId(otherTab, exportedTabs, localTabs); var checkPartial = false; if (parentId == -1 && otherTab.ParentId > 0) { if (!isParentPresent) { - Result.AddLogEntry("Importing new tab skipped as its parent was not found", $"{otherTab.TabName} ({otherTab.TabPath})", ReportLevel.Warn); + this.Result.AddLogEntry("Importing new tab skipped as its parent was not found", $"{otherTab.TabName} ({otherTab.TabPath})", ReportLevel.Warn); return; } @@ -269,9 +286,10 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex { localTab.Url = otherTab.Url; } + localTab.UniqueId = Guid.NewGuid(); - SetPartialImportSettings(otherTab, localTab); - otherTab.LocalId = localTab.TabID = _tabController.AddTab(localTab, false); + this.SetPartialImportSettings(otherTab, localTab); + otherTab.LocalId = localTab.TabID = this._tabController.AddTab(localTab, false); DotNetNuke.Data.DataProvider.Instance().UpdateTabOrder(localTab.TabID, localTab.TabOrder, localTab.ParentId, Null.NullInteger); localTabs.Add(localTab); @@ -282,67 +300,151 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex if (checkPartial) { - CheckForPartialImportedTabs(otherTab); + this.CheckForPartialImportedTabs(otherTab); } } catch (Exception ex) { - Result.AddLogEntry($"Importing tab '{otherTab.TabName}' exception", ex.Message, ReportLevel.Error); + this.Result.AddLogEntry($"Importing tab '{otherTab.TabName}' exception", ex.Message, ReportLevel.Error); return; } - UpdateTabChangers(localTab.TabID, createdBy, modifiedBy); + this.UpdateTabChangers(localTab.TabID, createdBy, modifiedBy); // this is not saved upon updating the tab localTab.IsVisible = otherTab.IsVisible; EntitiesController.Instance.SetTabSpecificData(localTab.TabID, false, localTab.IsVisible); - //_tabController.UpdateTab(localTab); // to clear cache - //Try to set the unique id of existing page same as source page unique id, if possible. This will help for future updates etc. + + // _tabController.UpdateTab(localTab); // to clear cache + // Try to set the unique id of existing page same as source page unique id, if possible. This will help for future updates etc. if (!DataProvider.Instance().CheckTabUniqueIdExists(otherTab.UniqueId)) { localTab.UniqueId = otherTab.UniqueId; - UpdateTabUniqueId(localTab.TabID, localTab.UniqueId); + this.UpdateTabUniqueId(localTab.TabID, localTab.UniqueId); } - Result.AddLogEntry("Added Tab", $"{otherTab.TabName} ({otherTab.TabPath})"); - _totals.TotalTabs++; - UpdateDefaultLanguageGuid(portalId, localTab, otherTab, exportedTabs); - AddTabRelatedItems(localTab, otherTab, true); - TriggerImportEvent(localTab); + this.Result.AddLogEntry("Added Tab", $"{otherTab.TabName} ({otherTab.TabPath})"); + this._totals.TotalTabs++; + this.UpdateDefaultLanguageGuid(portalId, localTab, otherTab, exportedTabs); + this.AddTabRelatedItems(localTab, otherTab, true); + this.TriggerImportEvent(localTab); } + var portalSettings = new PortalSettings(portalId); if (otherTab.IsDeleted) { - _tabController.SoftDeleteTab(localTab.TabID, portalSettings); + this._tabController.SoftDeleteTab(localTab.TabID, portalSettings); } else { - var tab = _tabController.GetTab(localTab.TabID, portalId); + var tab = this._tabController.GetTab(localTab.TabID, portalId); if (tab.IsDeleted) { - RestoreTab(tab, portalSettings); + this.RestoreTab(tab, portalSettings); } } - UpdateParentInPartialImportTabs(localTab, otherTab, portalId, exportedTabs, localTabs); + + this.UpdateParentInPartialImportTabs(localTab, otherTab, portalId, exportedTabs, localTabs); } - public void RestoreTab(TabInfo tab, PortalSettings portalSettings) + private static int TryFindLocalParentTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs) { - var changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState(tab.PortalID, tab.TabID); - if (changeControlStateForTab.IsChangeControlEnabledForTab) + return TryFindLocalTabId(exportedTab, exportedTabs, localTabs, exportedTab.ParentId); + } + + private static int TryFindLocalTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs, int? tabId) + { + if (tabId.HasValue && tabId.Value > 0) { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); + var otherParent = exportedTabs.FirstOrDefault(t => t.TabId == tabId); + if (otherParent != null) + { + if (otherParent.LocalId.HasValue) + { + var localTab = localTabs.FirstOrDefault(t => t.TabID == otherParent.LocalId); + if (localTab != null) + { + return localTab.TabID; + } + } + } + else if (exportedTab.TabPath.HasValue()) + { + var index = exportedTab.TabPath.LastIndexOf(@"//", StringComparison.Ordinal); + if (index > 0) + { + var path = exportedTab.TabPath.Substring(0, index); + var localTab = localTabs.FirstOrDefault(t => + path.Equals(t.TabPath, StringComparison.InvariantCultureIgnoreCase) + && IsSameCulture(t.CultureCode, exportedTab.CultureCode)); + if (localTab != null) + { + return localTab.TabID; + } + } + } } - _tabController.RestoreTab(tab, portalSettings); + return -1; + } + + private void ProcessImportPages() + { + this._dataProvider = DataProvider.Instance(); + this._totals = string.IsNullOrEmpty(this.CheckPoint.StageData) + ? new ProgressTotals() + : JsonConvert.DeserializeObject(this.CheckPoint.StageData); - if (changeControlStateForTab.IsChangeControlEnabledForTab) + var portalId = this._exportImportJob.PortalId; + + var localTabs = this._tabController.GetTabsByPortal(portalId).Values.ToList(); + + var exportedTabs = this.Repository.GetItems(x => x.IsSystem == (this.Category == Constants.Category_Templates)) + .OrderBy(t => t.Level).ThenBy(t => t.ParentId).ThenBy(t => t.TabOrder).ToList(); + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? exportedTabs.Count : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + + var progressStep = 100.0 / exportedTabs.OrderByDescending(x => x.Id).Count(x => x.Id < this._totals.LastProcessedId); + + var index = 0; + var referenceTabs = new List(); + this._importContentList.Clear(); + foreach (var otherTab in exportedTabs) { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, changeControlStateForTab.IsVersioningEnabledForTab); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); + if (this.CheckCancelled(this._exportImportJob)) + { + break; + } + + if (this._totals.LastProcessedId > index) + { + continue; // this is the exported DB row ID; not the TabID + } + + this.ProcessImportPage(otherTab, exportedTabs, localTabs, referenceTabs); + + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress += progressStep; + if (this.CheckPointStageCallback(this)) + { + break; + } + + this._totals.LastProcessedId = index++; + this.CheckPoint.StageData = JsonConvert.SerializeObject(this._totals); } + + // repair pages which linked to other pages + this.RepairReferenceTabs(referenceTabs, localTabs, exportedTabs); + + this._searchedParentTabs.Clear(); + this.ReportImportTotals(); } /// @@ -369,7 +471,6 @@ private void UpdateDefaultLanguageGuid(int portalId, TabInfo localTab, ExportTab // 3. Find corresponding id of local default lang tab // 4. Take UniqueId of local default lang tab and set it for the page we are going to create/update // 5. Use fallback value if something from above scenario does not work - if (exportedTab.DefaultLanguageGuid == Null.NullGuid) { return; @@ -380,7 +481,7 @@ private void UpdateDefaultLanguageGuid(int portalId, TabInfo localTab, ExportTab if (defaultLanguagePageToImport != null && defaultLanguagePageToImport.LocalId.HasValue) { - var defaultLanguagePageLocal = _tabController.GetTab(defaultLanguagePageToImport.LocalId.Value, portalId); + var defaultLanguagePageLocal = this._tabController.GetTab(defaultLanguagePageToImport.LocalId.Value, portalId); if (defaultLanguagePageLocal != null) { @@ -388,6 +489,7 @@ private void UpdateDefaultLanguageGuid(int portalId, TabInfo localTab, ExportTab return; } } + localTab.DefaultLanguageGuid = exportedTab.DefaultLanguageGuid ?? Null.NullGuid; } @@ -395,7 +497,7 @@ private void TriggerImportEvent(TabInfo localTab) { try { - //update tab with import flag, to trigger update event handler. + // update tab with import flag, to trigger update event handler. if (localTab.TabSettings.ContainsKey("TabImported")) { localTab.TabSettings["TabImported"] = "Y"; @@ -404,7 +506,8 @@ private void TriggerImportEvent(TabInfo localTab) { localTab.TabSettings.Add("TabImported", "Y"); } - _tabController.UpdateTab(localTab); + + this._tabController.UpdateTab(localTab); TabController.Instance.DeleteTabSetting(localTab.TabID, "TabImported"); } catch (Exception) @@ -415,52 +518,53 @@ private void TriggerImportEvent(TabInfo localTab) private void AddTabRelatedItems(TabInfo localTab, ExportTab otherTab, bool isNew) { - _totals.TotalTabSettings += ImportTabSettings(localTab, otherTab, isNew); - _totals.TotalTabPermissions += ImportTabPermissions(localTab, otherTab, isNew); - _totals.TotalTabUrls += ImportTabUrls(localTab, otherTab, isNew); - _totals.TotalTabModules += ImportTabModulesAndRelatedItems(localTab, otherTab, isNew); + this._totals.TotalTabSettings += this.ImportTabSettings(localTab, otherTab, isNew); + this._totals.TotalTabPermissions += this.ImportTabPermissions(localTab, otherTab, isNew); + this._totals.TotalTabUrls += this.ImportTabUrls(localTab, otherTab, isNew); + this._totals.TotalTabModules += this.ImportTabModulesAndRelatedItems(localTab, otherTab, isNew); } private int ImportTabSettings(TabInfo localTab, ExportTab otherTab, bool isNew) { - var tabSettings = Repository.GetRelatedItems(otherTab.Id).ToList(); + var tabSettings = this.Repository.GetRelatedItems(otherTab.Id).ToList(); foreach (var other in tabSettings) { var localValue = isNew ? string.Empty : Convert.ToString(localTab.TabSettings[other.SettingName]); if (string.IsNullOrEmpty(localValue)) { - _tabController.UpdateTabSetting(localTab.TabID, other.SettingName, other.SettingValue); - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - _dataProvider.UpdateSettingRecordChangers("TabSettings", "TabID", + this._tabController.UpdateTabSetting(localTab.TabID, other.SettingName, other.SettingValue); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this._dataProvider.UpdateSettingRecordChangers("TabSettings", "TabID", localTab.TabID, other.SettingName, createdBy, modifiedBy); - Result.AddLogEntry("Added tab setting", $"{other.SettingName} - {other.TabID}"); + this.Result.AddLogEntry("Added tab setting", $"{other.SettingName} - {other.TabID}"); } else { - switch (_importDto.CollisionResolution) + switch (this._importDto.CollisionResolution) { case CollisionResolution.Overwrite: if (localValue != other.SettingValue) { // the next will clear the cache - _tabController.UpdateTabSetting(localTab.TabID, other.SettingName, other.SettingValue); - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - _dataProvider.UpdateSettingRecordChangers("TabSettings", "TabID", + this._tabController.UpdateTabSetting(localTab.TabID, other.SettingName, other.SettingValue); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this._dataProvider.UpdateSettingRecordChangers("TabSettings", "TabID", localTab.TabID, other.SettingName, createdBy, modifiedBy); - Result.AddLogEntry("Updated tab setting", $"{other.SettingName} - {other.TabID}"); + this.Result.AddLogEntry("Updated tab setting", $"{other.SettingName} - {other.TabID}"); } else { goto case CollisionResolution.Ignore; } + break; case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored tab setting", other.SettingName); + this.Result.AddLogEntry("Ignored tab setting", other.SettingName); break; default: - throw new ArgumentOutOfRangeException(_importDto.CollisionResolution.ToString()); + throw new ArgumentOutOfRangeException(this._importDto.CollisionResolution.ToString()); } } } @@ -470,15 +574,19 @@ private int ImportTabSettings(TabInfo localTab, ExportTab otherTab, bool isNew) private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNew) { - if (!_exportDto.IncludePermissions) return 0; + if (!this._exportDto.IncludePermissions) + { + return 0; + } + var noRole = Convert.ToInt32(Globals.glbRoleNothing); var count = 0; - var tabPermissions = Repository.GetRelatedItems(otherTab.Id).ToList(); + var tabPermissions = this.Repository.GetRelatedItems(otherTab.Id).ToList(); var localTabPermissions = localTab.TabPermissions.OfType().ToList(); foreach (var other in tabPermissions) { - var roleId = Util.GetRoleIdByName(_importDto.PortalId, other.RoleID ?? noRole, other.RoleName); - var userId = UserController.GetUserByName(_importDto.PortalId, other.Username)?.UserID; + var roleId = Util.GetRoleIdByName(this._importDto.PortalId, other.RoleID ?? noRole, other.RoleName); + var userId = UserController.GetUserByName(this._importDto.PortalId, other.Username)?.UserID; var local = isNew ? null : localTabPermissions.FirstOrDefault( x => x.PermissionCode == other.PermissionCode && x.PermissionKey == other.PermissionKey @@ -487,30 +595,29 @@ private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNe var isUpdate = false; if (local != null) { - switch (_importDto.CollisionResolution) + switch (this._importDto.CollisionResolution) { case CollisionResolution.Overwrite: isUpdate = true; break; case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored tab permission", other.PermissionKey); + this.Result.AddLogEntry("Ignored tab permission", other.PermissionKey); break; default: - throw new ArgumentOutOfRangeException(_importDto.CollisionResolution.ToString()); + throw new ArgumentOutOfRangeException(this._importDto.CollisionResolution.ToString()); } } if (isUpdate) { - //UNDONE: Do we really need to update an existing permission? It won't do anything; permissions are immutable - //Result.AddLogEntry("Updated tab permission", other.PermissionKey); + // UNDONE: Do we really need to update an existing permission? It won't do anything; permissions are immutable + // Result.AddLogEntry("Updated tab permission", other.PermissionKey); } else { var permissionId = DataProvider.Instance().GetPermissionId(other.PermissionCode, other.PermissionKey, other.PermissionName); if (permissionId != null) { - local = new TabPermissionInfo { TabID = localTab.TabID, @@ -522,39 +629,47 @@ private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNe PermissionKey = other.PermissionKey, PermissionName = other.PermissionName, AllowAccess = other.AllowAccess, - PermissionID = permissionId.Value + PermissionID = permissionId.Value, }; if (other.UserID != null && other.UserID > 0 && !string.IsNullOrEmpty(other.Username)) { if (userId == null) { - Result.AddLogEntry("Couldn't add tab permission; User is undefined!", + this.Result.AddLogEntry( + "Couldn't add tab permission; User is undefined!", $"{other.PermissionKey} - {other.PermissionID}", ReportLevel.Warn); continue; } + local.UserID = userId.Value; } + if (other.RoleID != null && other.RoleID > noRole && !string.IsNullOrEmpty(other.RoleName)) { if (roleId == null) { - Result.AddLogEntry("Couldn't add tab permission; Role is undefined!", + this.Result.AddLogEntry( + "Couldn't add tab permission; Role is undefined!", $"{other.PermissionKey} - {other.PermissionID}", ReportLevel.Warn); continue; } + local.RoleID = roleId.Value; } + localTab.TabPermissions.Add(local, true); - //UNDONE: none set; not possible until after saving all tab permissions as donbefore exiting this method - //var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - //var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - //UpdateTabPermissionChangers(local.TabPermissionID, createdBy, modifiedBy); - Result.AddLogEntry("Added tab permission", $"{other.PermissionKey} - {other.PermissionID}"); + + // UNDONE: none set; not possible until after saving all tab permissions as donbefore exiting this method + // var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + // var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + // UpdateTabPermissionChangers(local.TabPermissionID, createdBy, modifiedBy); + this.Result.AddLogEntry("Added tab permission", $"{other.PermissionKey} - {other.PermissionID}"); count++; } else { - Result.AddLogEntry("Couldn't add tab permission; Permission is undefined!", + this.Result.AddLogEntry( + "Couldn't add tab permission; Permission is undefined!", $"{other.PermissionKey} - {other.PermissionID}", ReportLevel.Warn); } } @@ -571,38 +686,39 @@ private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNe private int ImportTabUrls(TabInfo localTab, ExportTab otherTab, bool isNew) { var count = 0; - var tabUrls = Repository.GetRelatedItems(otherTab.Id).ToList(); + var tabUrls = this.Repository.GetRelatedItems(otherTab.Id).ToList(); var localUrls = localTab.TabUrls; foreach (var other in tabUrls) { var local = isNew ? null : localUrls.FirstOrDefault(url => url.SeqNum == other.SeqNum); if (local != null) { - switch (_importDto.CollisionResolution) + switch (this._importDto.CollisionResolution) { case CollisionResolution.Overwrite: try { local.Url = other.Url; - TabController.Instance.SaveTabUrl(local, _importDto.PortalId, true); - Result.AddLogEntry("Update Tab Url", other.Url); + TabController.Instance.SaveTabUrl(local, this._importDto.PortalId, true); + this.Result.AddLogEntry("Update Tab Url", other.Url); count++; } catch (Exception ex) { - Result.AddLogEntry("EXCEPTION updating tab, Tab ID=" + local.TabId, ex.Message, ReportLevel.Error); + this.Result.AddLogEntry("EXCEPTION updating tab, Tab ID=" + local.TabId, ex.Message, ReportLevel.Error); } + break; case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored tab url", other.Url); + this.Result.AddLogEntry("Ignored tab url", other.Url); break; default: - throw new ArgumentOutOfRangeException(_importDto.CollisionResolution.ToString()); + throw new ArgumentOutOfRangeException(this._importDto.CollisionResolution.ToString()); } } else { - var alias = PortalAliasController.Instance.GetPortalAliasesByPortalId(_importDto.PortalId).FirstOrDefault(a => a.IsPrimary); + var alias = PortalAliasController.Instance.GetPortalAliasesByPortalId(this._importDto.PortalId).FirstOrDefault(a => a.IsPrimary); local = new TabUrlInfo { TabId = localTab.TabID, @@ -618,18 +734,18 @@ private int ImportTabUrls(TabInfo localTab, ExportTab otherTab, bool isNew) try { - TabController.Instance.SaveTabUrl(local, _importDto.PortalId, true); + TabController.Instance.SaveTabUrl(local, this._importDto.PortalId, true); - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - _dataProvider.UpdateTabUrlChangers(local.TabId, local.SeqNum, createdBy, modifiedBy); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this._dataProvider.UpdateTabUrlChangers(local.TabId, local.SeqNum, createdBy, modifiedBy); - Result.AddLogEntry("Added Tab Url", other.Url); + this.Result.AddLogEntry("Added Tab Url", other.Url); count++; } catch (Exception ex) { - Result.AddLogEntry("EXCEPTION adding tab, Tab ID=" + local.TabId, ex.Message, ReportLevel.Error); + this.Result.AddLogEntry("EXCEPTION adding tab, Tab ID=" + local.TabId, ex.Message, ReportLevel.Error); } } } @@ -640,17 +756,17 @@ private int ImportTabUrls(TabInfo localTab, ExportTab otherTab, bool isNew) private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab, bool isNew) { var count = 0; - var exportedModules = Repository.GetRelatedItems(otherTab.Id).ToList(); - var exportedTabModules = Repository.GetRelatedItems(otherTab.Id) + var exportedModules = this.Repository.GetRelatedItems(otherTab.Id).ToList(); + var exportedTabModules = this.Repository.GetRelatedItems(otherTab.Id) .OrderBy(m => m.PaneName?.ToLowerInvariant()).ThenBy(m => m.ModuleOrder).ToList(); var localExportModules = isNew ? new List() : EntitiesController.Instance.GetModules(localTab.TabID, true, Constants.MaxDbTime, null).ToList(); - var localTabModules = isNew ? new List() : _moduleController.GetTabModules(localTab.TabID).Values.ToList(); + var localTabModules = isNew ? new List() : this._moduleController.GetTabModules(localTab.TabID).Values.ToList(); var allExistingIds = localTabModules.Select(l => l.ModuleID).ToList(); var allImportedIds = new List(); - var localOrders = BuildModuleOrders(localTabModules); - var exportOrders = BuildModuleOrders(exportedTabModules); + var localOrders = this.BuildModuleOrders(localTabModules); + var exportOrders = this.BuildModuleOrders(exportedTabModules); foreach (var other in exportedTabModules) { var locals = new List(localTabModules.Where(m => m.UniqueId == other.UniqueId && m.IsDeleted == other.IsDeleted)); @@ -658,22 +774,26 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab { locals = new List(localTabModules.Where(m => m.ModuleDefinition.FriendlyName == other.FriendlyName && m.PaneName == other.PaneName - && ModuleOrderMatched(m, other, localOrders, exportOrders) + && this.ModuleOrderMatched(m, other, localOrders, exportOrders) && m.IsDeleted == other.IsDeleted)).ToList(); } var otherModule = exportedModules.FirstOrDefault(m => m.ModuleID == other.ModuleID); - if (otherModule == null) continue; // must not happen - + if (otherModule == null) + { + continue; // must not happen + } + var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(other.FriendlyName); if (moduleDefinition == null) { - Result.AddLogEntry("Error adding tab module, ModuleDef=" + other.FriendlyName, + this.Result.AddLogEntry( + "Error adding tab module, ModuleDef=" + other.FriendlyName, "The modue definition is not present in the system", ReportLevel.Error); continue; // the module is not installed, therefore ignore it } - var sharedModules = Repository.FindItems(m => m.ModuleID == other.ModuleID); + var sharedModules = this.Repository.FindItems(m => m.ModuleID == other.ModuleID); var sharedModule = sharedModules.FirstOrDefault(m => m.LocalId.HasValue); if (locals.Count == 0) @@ -705,7 +825,8 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab Header = other.Header, Footer = other.Footer, CultureCode = other.CultureCode, - //UniqueId = other.UniqueId, + + // UniqueId = other.UniqueId, UniqueId = DataProvider.Instance().CheckTabModuleUniqueIdExists(other.UniqueId) ? Guid.NewGuid() : other.UniqueId, VersionGuid = other.VersionGuid, DefaultLanguageGuid = other.DefaultLanguageGuid ?? Guid.Empty, @@ -715,53 +836,53 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab IsShareableViewOnly = other.IsShareableViewOnly, StartDate = otherModule.StartDate.GetValueOrDefault(DateTime.MinValue), EndDate = otherModule.EndDate.GetValueOrDefault(DateTime.MinValue), - PortalID = _exportImportJob.PortalId + PortalID = this._exportImportJob.PortalId, }; - //Logger.Error($"Local Tab ID={local.TabID}, ModuleID={local.ModuleID}, ModuleDefID={local.ModuleDefID}"); + // Logger.Error($"Local Tab ID={local.TabID}, ModuleID={local.ModuleID}, ModuleDefID={local.ModuleDefID}"); try { - //this will create up to 2 records: Module (if it is not already there) and TabModule - otherModule.LocalId = _moduleController.AddModule(local); + // this will create up to 2 records: Module (if it is not already there) and TabModule + otherModule.LocalId = this._moduleController.AddModule(local); other.LocalId = local.TabModuleID; - Repository.UpdateItem(otherModule); + this.Repository.UpdateItem(otherModule); allImportedIds.Add(local.ModuleID); // this is not saved upon adding the module if (other.IsDeleted && !otherTab.IsDeleted) { local.IsDeleted = other.IsDeleted; - _moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); + this._moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); } - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - UpdateTabModuleChangers(local.TabModuleID, createdBy, modifiedBy); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this.UpdateTabModuleChangers(local.TabModuleID, createdBy, modifiedBy); if (sharedModule == null) { - createdBy = Util.GetUserIdByName(_exportImportJob, otherModule.CreatedByUserID, otherModule.CreatedByUserName); - modifiedBy = Util.GetUserIdByName(_exportImportJob, otherModule.LastModifiedByUserID, otherModule.LastModifiedByUserName); - UpdateModuleChangers(local.ModuleID, createdBy, modifiedBy); + createdBy = Util.GetUserIdByName(this._exportImportJob, otherModule.CreatedByUserID, otherModule.CreatedByUserName); + modifiedBy = Util.GetUserIdByName(this._exportImportJob, otherModule.LastModifiedByUserID, otherModule.LastModifiedByUserName); + this.UpdateModuleChangers(local.ModuleID, createdBy, modifiedBy); - _totals.TotalModuleSettings += ImportModuleSettings(local, otherModule, isNew); - _totals.TotalModulePermissions += ImportModulePermissions(local, otherModule, isNew); - _totals.TotalTabModuleSettings += ImportTabModuleSettings(local, other, isNew); + this._totals.TotalModuleSettings += this.ImportModuleSettings(local, otherModule, isNew); + this._totals.TotalModulePermissions += this.ImportModulePermissions(local, otherModule, isNew); + this._totals.TotalTabModuleSettings += this.ImportTabModuleSettings(local, other, isNew); - if (_exportDto.IncludeContent) + if (this._exportDto.IncludeContent) { - _totals.TotalContents += ImportPortableContent(localTab.TabID, local, otherModule, isNew); + this._totals.TotalContents += this.ImportPortableContent(localTab.TabID, local, otherModule, isNew); } - Result.AddLogEntry("Added module", local.ModuleID.ToString()); + this.Result.AddLogEntry("Added module", local.ModuleID.ToString()); } - Result.AddLogEntry("Added tab module", local.TabModuleID.ToString()); + this.Result.AddLogEntry("Added tab module", local.TabModuleID.ToString()); count++; } catch (Exception ex) { - Result.AddLogEntry("EXCEPTION importing tab module, Module ID=" + local.ModuleID, ex.Message, ReportLevel.Error); + this.Result.AddLogEntry("EXCEPTION importing tab module, Module ID=" + local.ModuleID, ex.Message, ReportLevel.Error); Logger.Error(ex); } } @@ -804,7 +925,8 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab Header = other.Header, Footer = other.Footer, CultureCode = other.CultureCode, - //UniqueId = other.UniqueId, + + // UniqueId = other.UniqueId, UniqueId = DataProvider.Instance().CheckTabModuleUniqueIdExists(other.UniqueId) ? Guid.NewGuid() : other.UniqueId, VersionGuid = other.VersionGuid, DefaultLanguageGuid = other.DefaultLanguageGuid ?? Guid.Empty, @@ -812,23 +934,27 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab InheritViewPermissions = other.InheritViewPermissions, IsShareable = other.IsShareable, IsShareableViewOnly = other.IsShareableViewOnly, - PortalID = _exportImportJob.PortalId + PortalID = this._exportImportJob.PortalId, }; - //this will create up to 2 records: Module (if it is not already there) and TabModule - otherModule.LocalId = _moduleController.AddModule(local); + // this will create up to 2 records: Module (if it is not already there) and TabModule + otherModule.LocalId = this._moduleController.AddModule(local); other.LocalId = local.TabModuleID; - Repository.UpdateItem(otherModule); + this.Repository.UpdateItem(otherModule); allImportedIds.Add(local.ModuleID); // this is not saved upon updating the module if (isDeleted != other.IsDeleted && !otherTab.IsDeleted) { local.IsDeleted = other.IsDeleted; - if (other.IsDeleted) - _moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); - else - _moduleController.RestoreModule(local); + if (other.IsDeleted) + { + this._moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); + } + else + { + this._moduleController.RestoreModule(local); + } } } else @@ -881,15 +1007,15 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab if (local.UniqueId != other.UniqueId && !DataProvider.Instance().CheckTabModuleUniqueIdExists(other.UniqueId)) { local.UniqueId = other.UniqueId; - UpdateModuleUniqueId(local.TabModuleID, other.UniqueId); + this.UpdateModuleUniqueId(local.TabModuleID, other.UniqueId); } // updates both module and tab module db records - UpdateModuleWithIsDeletedHandling(other, otherModule, local); + this.UpdateModuleWithIsDeletedHandling(other, otherModule, local); other.LocalId = local.TabModuleID; otherModule.LocalId = localExpModule.ModuleID; - Repository.UpdateItem(otherModule); + this.Repository.UpdateItem(otherModule); allImportedIds.Add(local.ModuleID); // this is not saved upon updating the module @@ -898,49 +1024,49 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab local.IsDeleted = other.IsDeleted; if (other.IsDeleted) { - _moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); + this._moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); } else { - _moduleController.RestoreModule(local); + this._moduleController.RestoreModule(local); } } } - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - UpdateTabModuleChangers(local.TabModuleID, createdBy, modifiedBy); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this.UpdateTabModuleChangers(local.TabModuleID, createdBy, modifiedBy); - createdBy = Util.GetUserIdByName(_exportImportJob, otherModule.CreatedByUserID, otherModule.CreatedByUserName); - modifiedBy = Util.GetUserIdByName(_exportImportJob, otherModule.LastModifiedByUserID, otherModule.LastModifiedByUserName); - UpdateModuleChangers(local.ModuleID, createdBy, modifiedBy); + createdBy = Util.GetUserIdByName(this._exportImportJob, otherModule.CreatedByUserID, otherModule.CreatedByUserName); + modifiedBy = Util.GetUserIdByName(this._exportImportJob, otherModule.LastModifiedByUserID, otherModule.LastModifiedByUserName); + this.UpdateModuleChangers(local.ModuleID, createdBy, modifiedBy); - _totals.TotalTabModuleSettings += ImportTabModuleSettings(local, other, isNew); + this._totals.TotalTabModuleSettings += this.ImportTabModuleSettings(local, other, isNew); - _totals.TotalModuleSettings += ImportModuleSettings(local, otherModule, isNew); - _totals.TotalModulePermissions += ImportModulePermissions(local, otherModule, isNew); + this._totals.TotalModuleSettings += this.ImportModuleSettings(local, otherModule, isNew); + this._totals.TotalModulePermissions += this.ImportModulePermissions(local, otherModule, isNew); - if (_exportDto.IncludeContent) + if (this._exportDto.IncludeContent) { - _totals.TotalContents += ImportPortableContent(localTab.TabID, local, otherModule, isNew); + this._totals.TotalContents += this.ImportPortableContent(localTab.TabID, local, otherModule, isNew); } - Result.AddLogEntry("Updated tab module", local.TabModuleID.ToString()); - Result.AddLogEntry("Updated module", local.ModuleID.ToString()); + this.Result.AddLogEntry("Updated tab module", local.TabModuleID.ToString()); + this.Result.AddLogEntry("Updated module", local.ModuleID.ToString()); count++; } catch (Exception ex) { - Result.AddLogEntry("EXCEPTION importing tab module, Module ID=" + local.ModuleID, ex.Message, ReportLevel.Error); + this.Result.AddLogEntry("EXCEPTION importing tab module, Module ID=" + local.ModuleID, ex.Message, ReportLevel.Error); Logger.Error(ex); } } } } - if (!isNew && _exportDto.ExportMode == ExportMode.Full && - _importDto.CollisionResolution == CollisionResolution.Overwrite) + if (!isNew && this._exportDto.ExportMode == ExportMode.Full && + this._importDto.CollisionResolution == CollisionResolution.Overwrite) { // delete left over tab modules for full import in an existing page var unimported = allExistingIds.Distinct().Except(allImportedIds); @@ -948,31 +1074,32 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab { try { - _moduleController.DeleteTabModule(localTab.TabID, moduleId, false); + this._moduleController.DeleteTabModule(localTab.TabID, moduleId, false); } catch (Exception ex) { Logger.Error(new Exception($"Delete TabModule Failed: {moduleId}", ex)); } - Result.AddLogEntry("Removed existing tab module", "Module ID=" + moduleId); + + this.Result.AddLogEntry("Removed existing tab module", "Module ID=" + moduleId); } } return count; } - + /* - Update Modules.IsDeleted with ExportModule.IsDeleted and not ExportTabModule.IsDeleted. + Update Modules.IsDeleted with ExportModule.IsDeleted and not ExportTabModule.IsDeleted. ExportTabModule.IsDeleted may different from ExportModule.IsDeleted when Module is deleted. - Change ModuleInfo.IsDeleted to ExportModule.IsDeleted and reverting to ExportMabModule.IsDeleted after + Change ModuleInfo.IsDeleted to ExportModule.IsDeleted and reverting to ExportMabModule.IsDeleted after updating Modules. */ private void UpdateModuleWithIsDeletedHandling(ExportTabModule exportTabModule, ExportModule exportModule, ModuleInfo importModule) { importModule.IsDeleted = exportModule.IsDeleted; - ActionInWorkflowlessContext(importModule.TabID, () => + this.ActionInWorkflowlessContext(importModule.TabID, () => { - _moduleController.UpdateModule(importModule); + this._moduleController.UpdateModule(importModule); }); importModule.IsDeleted = exportTabModule.IsDeleted; } @@ -1051,46 +1178,47 @@ private IDictionary BuildModuleOrders(IList modules) private int ImportModuleSettings(ModuleInfo localModule, ExportModule otherModule, bool isNew) { var count = 0; - var moduleSettings = Repository.GetRelatedItems(otherModule.Id).ToList(); + var moduleSettings = this.Repository.GetRelatedItems(otherModule.Id).ToList(); foreach (var other in moduleSettings) { var localValue = isNew ? string.Empty : Convert.ToString(localModule.ModuleSettings[other.SettingName]); if (string.IsNullOrEmpty(localValue)) { - _moduleController.UpdateModuleSetting(localModule.ModuleID, other.SettingName, other.SettingValue); - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - _dataProvider.UpdateSettingRecordChangers("ModuleSettings", "ModuleID", + this._moduleController.UpdateModuleSetting(localModule.ModuleID, other.SettingName, other.SettingValue); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this._dataProvider.UpdateSettingRecordChangers("ModuleSettings", "ModuleID", localModule.ModuleID, other.SettingName, createdBy, modifiedBy); - Result.AddLogEntry("Added module setting", $"{other.SettingName} - {other.ModuleID}"); + this.Result.AddLogEntry("Added module setting", $"{other.SettingName} - {other.ModuleID}"); count++; } else { - switch (_importDto.CollisionResolution) + switch (this._importDto.CollisionResolution) { case CollisionResolution.Overwrite: if (localValue != other.SettingValue) { // the next will clear the cache - _moduleController.UpdateModuleSetting(localModule.ModuleID, other.SettingName, other.SettingValue); - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - _dataProvider.UpdateSettingRecordChangers("ModuleSettings", "ModuleID", + this._moduleController.UpdateModuleSetting(localModule.ModuleID, other.SettingName, other.SettingValue); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this._dataProvider.UpdateSettingRecordChangers("ModuleSettings", "ModuleID", localModule.ModuleID, other.SettingName, createdBy, modifiedBy); - Result.AddLogEntry("Updated module setting", $"{other.SettingName} - {other.ModuleID}"); + this.Result.AddLogEntry("Updated module setting", $"{other.SettingName} - {other.ModuleID}"); count++; } else { goto case CollisionResolution.Ignore; } + break; case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored module setting", other.SettingName); + this.Result.AddLogEntry("Ignored module setting", other.SettingName); break; default: - throw new ArgumentOutOfRangeException(_importDto.CollisionResolution.ToString()); + throw new ArgumentOutOfRangeException(this._importDto.CollisionResolution.ToString()); } } } @@ -1102,19 +1230,18 @@ private int ImportModulePermissions(ModuleInfo localModule, ExportModule otherMo { var count = 0; var noRole = Convert.ToInt32(Globals.glbRoleNothing); - var modulePermissions = Repository.GetRelatedItems(otherModule.Id).ToList(); + var modulePermissions = this.Repository.GetRelatedItems(otherModule.Id).ToList(); var localModulePermissions = isNew ? new List() : localModule.ModulePermissions.OfType().ToList(); foreach (var other in modulePermissions) { - var userId = UserController.GetUserByName(_importDto.PortalId, other.Username)?.UserID; - var roleId = Util.GetRoleIdByName(_importDto.PortalId, other.RoleID ?? noRole, other.RoleName); + var userId = UserController.GetUserByName(this._importDto.PortalId, other.Username)?.UserID; + var roleId = Util.GetRoleIdByName(this._importDto.PortalId, other.RoleID ?? noRole, other.RoleName); var permissionId = DataProvider.Instance().GetPermissionId(other.PermissionCode, other.PermissionKey, other.PermissionName); if (permissionId != null) { - var local = new ModulePermissionInfo { ModuleID = localModule.ModuleID, @@ -1125,24 +1252,31 @@ private int ImportModulePermissions(ModuleInfo localModule, ExportModule otherMo PermissionKey = other.PermissionKey, PermissionName = other.PermissionName, AllowAccess = other.AllowAccess, - PermissionID = permissionId.Value + PermissionID = permissionId.Value, }; if (other.UserID != null && other.UserID > 0 && !string.IsNullOrEmpty(other.Username)) { - if (userId == null) - continue; + if (userId == null) + { + continue; + } + local.UserID = userId.Value; } + if (other.RoleID != null && other.RoleID > noRole && !string.IsNullOrEmpty(other.RoleName)) { - if (roleId == null) - continue; + if (roleId == null) + { + continue; + } + local.RoleID = roleId.Value; } other.LocalId = localModule.ModulePermissions.Add(local, true); - Result.AddLogEntry("Added module permission", $"{other.PermissionKey} - {other.PermissionID}"); + this.Result.AddLogEntry("Added module permission", $"{other.PermissionKey} - {other.PermissionID}"); count++; } } @@ -1157,38 +1291,38 @@ private int ImportModulePermissions(ModuleInfo localModule, ExportModule otherMo private int ImportPortableContent(int tabId, ModuleInfo localModule, ExportModule otherModule, bool isNew) { - var exportedContent = Repository.FindItems(m => m.ModuleID == otherModule.ModuleID).ToList(); + var exportedContent = this.Repository.FindItems(m => m.ModuleID == otherModule.ModuleID).ToList(); if (exportedContent.Count > 0) { var moduleDef = ModuleDefinitionController.GetModuleDefinitionByID(localModule.ModuleDefID); - var desktopModuleInfo = DesktopModuleController.GetDesktopModule(moduleDef.DesktopModuleID, _exportDto.PortalId); + var desktopModuleInfo = DesktopModuleController.GetDesktopModule(moduleDef.DesktopModuleID, this._exportDto.PortalId); if (!string.IsNullOrEmpty(desktopModuleInfo?.BusinessControllerClass)) { try { - var module = _moduleController.GetModule(localModule.ModuleID, tabId, true); + var module = this._moduleController.GetModule(localModule.ModuleID, tabId, true); if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && module.DesktopModule.IsPortable) { var businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); var controller = businessController as IPortable; if (controller != null) { - //Note: there is no chek whether the content exists or not to manage conflict resolution - if (isNew || _importDto.CollisionResolution == CollisionResolution.Overwrite) + // Note: there is no chek whether the content exists or not to manage conflict resolution + if (isNew || this._importDto.CollisionResolution == CollisionResolution.Overwrite) { var restoreCount = 0; var version = DotNetNukeContext.Current.Application.Version.ToString(3); - ActionInWorkflowlessContext(tabId, () => + this.ActionInWorkflowlessContext(tabId, () => { foreach (var moduleContent in exportedContent) { if (!moduleContent.IsRestored - || !_importContentList.Any(i => i.ExportModuleId == otherModule.ModuleID && i.LocalModuleId == localModule.ModuleID)) + || !this._importContentList.Any(i => i.ExportModuleId == otherModule.ModuleID && i.LocalModuleId == localModule.ModuleID)) { try { - _importContentList.Add(new ImportModuleMapping { ExportModuleId = otherModule.ModuleID, LocalModuleId = localModule.ModuleID }); + this._importContentList.Add(new ImportModuleMapping { ExportModuleId = otherModule.ModuleID, LocalModuleId = localModule.ModuleID }); var content = moduleContent.XmlContent; if (content.IndexOf('\x03') >= 0) { @@ -1196,15 +1330,16 @@ private int ImportPortableContent(int tabId, ModuleInfo localModule, ExportModul content = content.Replace('\x03', ' '); } - controller.ImportModule(localModule.ModuleID, content, version, _exportImportJob.CreatedByUserId); + controller.ImportModule(localModule.ModuleID, content, version, this._exportImportJob.CreatedByUserId); moduleContent.IsRestored = true; - Repository.UpdateItem(moduleContent); + this.Repository.UpdateItem(moduleContent); restoreCount++; } catch (Exception ex) { - Result.AddLogEntry("Error importing module data, Module ID=" + localModule.ModuleID, ex.Message, ReportLevel.Error); - Logger.ErrorFormat("ModuleContent: (Module ID={0}). Error: {1}{2}{3}", + this.Result.AddLogEntry("Error importing module data, Module ID=" + localModule.ModuleID, ex.Message, ReportLevel.Error); + Logger.ErrorFormat( + "ModuleContent: (Module ID={0}). Error: {1}{2}{3}", localModule.ModuleID, ex, Environment.NewLine, moduleContent.XmlContent); } } @@ -1213,7 +1348,7 @@ private int ImportPortableContent(int tabId, ModuleInfo localModule, ExportModul if (restoreCount > 0) { - Result.AddLogEntry("Added/Updated module content inside Tab ID=" + tabId, "Module ID=" + localModule.ModuleID); + this.Result.AddLogEntry("Added/Updated module content inside Tab ID=" + tabId, "Module ID=" + localModule.ModuleID); return restoreCount; } } @@ -1222,18 +1357,19 @@ private int ImportPortableContent(int tabId, ModuleInfo localModule, ExportModul } catch (Exception ex) { - Result.AddLogEntry("Error cerating business class type", desktopModuleInfo.BusinessControllerClass, ReportLevel.Error); + this.Result.AddLogEntry("Error cerating business class type", desktopModuleInfo.BusinessControllerClass, ReportLevel.Error); Logger.Error("Error cerating business class type. " + ex); } } } + return 0; } private void ActionInWorkflowlessContext(int tabId, Action action) { bool versionEnabledPortalLevel, versionEnabledTabLevel, workflowEnabledPortalLevel, workflowEnabledTabLevel; - DisableVersioning(tabId, out versionEnabledPortalLevel, out versionEnabledTabLevel, out workflowEnabledPortalLevel, out workflowEnabledTabLevel); + this.DisableVersioning(tabId, out versionEnabledPortalLevel, out versionEnabledTabLevel, out workflowEnabledPortalLevel, out workflowEnabledTabLevel); try { @@ -1241,17 +1377,18 @@ private void ActionInWorkflowlessContext(int tabId, Action action) } finally { - RestoreVersioning(tabId, versionEnabledPortalLevel, versionEnabledTabLevel, workflowEnabledPortalLevel, workflowEnabledTabLevel); + this.RestoreVersioning(tabId, versionEnabledPortalLevel, versionEnabledTabLevel, workflowEnabledPortalLevel, workflowEnabledTabLevel); } } - private void DisableVersioning(int tabId, + private void DisableVersioning( + int tabId, out bool versionEnabledPortalLevel, out bool versionEnabledTabLevel, out bool workflowEnabledPortalLevel, out bool workflowEnabledTabLevel) { - var portalId = _importDto.PortalId; + var portalId = this._importDto.PortalId; versionEnabledPortalLevel = TabVersionSettings.Instance.IsVersioningEnabled(portalId); versionEnabledTabLevel = TabVersionSettings.Instance.IsVersioningEnabled(portalId, tabId); TabVersionSettings.Instance.SetEnabledVersioningForPortal(portalId, false); @@ -1263,13 +1400,14 @@ private void DisableVersioning(int tabId, workflowSettings.SetWorkflowEnabled(portalId, tabId, false); } - private void RestoreVersioning(int tabId, + private void RestoreVersioning( + int tabId, bool versionEnabledPortalLevel, bool versionEnabledTabLevel, bool workflowEnabledPortalLevel, bool workflowEnabledTabLevel) { - var portalId = _importDto.PortalId; + var portalId = this._importDto.PortalId; TabVersionSettings.Instance.SetEnabledVersioningForPortal(portalId, versionEnabledPortalLevel); TabVersionSettings.Instance.SetEnabledVersioningForTab(tabId, versionEnabledTabLevel); TabWorkflowSettings.Instance.SetWorkflowEnabled(portalId, workflowEnabledPortalLevel); @@ -1279,47 +1417,48 @@ private void RestoreVersioning(int tabId, private int ImportTabModuleSettings(ModuleInfo localTabModule, ExportTabModule otherTabModule, bool isNew) { var count = 0; - var tabModuleSettings = Repository.GetRelatedItems(otherTabModule.Id).ToList(); + var tabModuleSettings = this.Repository.GetRelatedItems(otherTabModule.Id).ToList(); foreach (var other in tabModuleSettings) { - var localValue = isNew ? "" : Convert.ToString(localTabModule.TabModuleSettings[other.SettingName]); + var localValue = isNew ? string.Empty : Convert.ToString(localTabModule.TabModuleSettings[other.SettingName]); if (string.IsNullOrEmpty(localValue)) { // the next will clear the cache - _moduleController.UpdateTabModuleSetting(localTabModule.TabModuleID, other.SettingName, other.SettingValue); - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - _dataProvider.UpdateSettingRecordChangers("TabModuleSettings", "TabModuleID", + this._moduleController.UpdateTabModuleSetting(localTabModule.TabModuleID, other.SettingName, other.SettingValue); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this._dataProvider.UpdateSettingRecordChangers("TabModuleSettings", "TabModuleID", localTabModule.TabModuleID, other.SettingName, createdBy, modifiedBy); - Result.AddLogEntry("Added tab module setting", $"{other.SettingName} - {other.TabModuleID}"); + this.Result.AddLogEntry("Added tab module setting", $"{other.SettingName} - {other.TabModuleID}"); count++; } else { - switch (_importDto.CollisionResolution) + switch (this._importDto.CollisionResolution) { case CollisionResolution.Overwrite: if (localValue != other.SettingValue) { // the next will clear the cache - _moduleController.UpdateTabModuleSetting(localTabModule.TabModuleID, other.SettingName, other.SettingValue); - var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); - var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); - _dataProvider.UpdateSettingRecordChangers("TabModuleSettings", "TabModuleID", + this._moduleController.UpdateTabModuleSetting(localTabModule.TabModuleID, other.SettingName, other.SettingValue); + var createdBy = Util.GetUserIdByName(this._exportImportJob, other.CreatedByUserID, other.CreatedByUserName); + var modifiedBy = Util.GetUserIdByName(this._exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); + this._dataProvider.UpdateSettingRecordChangers("TabModuleSettings", "TabModuleID", localTabModule.TabModuleID, other.SettingName, createdBy, modifiedBy); - Result.AddLogEntry("Updated tab module setting", $"{other.SettingName} - {other.TabModuleID}"); + this.Result.AddLogEntry("Updated tab module setting", $"{other.SettingName} - {other.TabModuleID}"); count++; } else { goto case CollisionResolution.Ignore; } + break; case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored module setting", other.SettingName); + this.Result.AddLogEntry("Ignored module setting", other.SettingName); break; default: - throw new ArgumentOutOfRangeException(_importDto.CollisionResolution.ToString()); + throw new ArgumentOutOfRangeException(this._importDto.CollisionResolution.ToString()); } } } @@ -1327,43 +1466,6 @@ private int ImportTabModuleSettings(ModuleInfo localTabModule, ExportTabModule o return count; } - private static int TryFindLocalParentTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs) - { - return TryFindLocalTabId(exportedTab, exportedTabs, localTabs, exportedTab.ParentId); - } - - private static int TryFindLocalTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs, int? tabId) - { - if (tabId.HasValue && tabId.Value > 0) - { - var otherParent = exportedTabs.FirstOrDefault(t => t.TabId == tabId); - if (otherParent != null) - { - if (otherParent.LocalId.HasValue) - { - var localTab = localTabs.FirstOrDefault(t => t.TabID == otherParent.LocalId); - if (localTab != null) - return localTab.TabID; - } - } - else if (exportedTab.TabPath.HasValue()) - { - var index = exportedTab.TabPath.LastIndexOf(@"//", StringComparison.Ordinal); - if (index > 0) - { - var path = exportedTab.TabPath.Substring(0, index); - var localTab = localTabs.FirstOrDefault(t => - path.Equals(t.TabPath, StringComparison.InvariantCultureIgnoreCase) - && IsSameCulture(t.CultureCode, exportedTab.CultureCode)); - if (localTab != null) - return localTab.TabID; - } - } - } - - return -1; - } - private static bool IsSameCulture(string sourceCultureCode, string targetCultureCode) { sourceCultureCode = !string.IsNullOrWhiteSpace(sourceCultureCode) ? sourceCultureCode : Localization.SystemLocale; @@ -1382,7 +1484,8 @@ private static void SetTabData(TabInfo localTab, ExportTab otherTab) localTab.Title = otherTab.Title; localTab.Description = otherTab.Description; localTab.KeyWords = otherTab.KeyWords; - //localTab.IsDeleted = otherTab.IsDeleted; // DO NOT enable this; leave this to other logic + + // localTab.IsDeleted = otherTab.IsDeleted; // DO NOT enable this; leave this to other logic localTab.Url = otherTab.Url; localTab.SkinSrc = otherTab.SkinSrc; localTab.ContainerSrc = otherTab.ContainerSrc; @@ -1395,7 +1498,8 @@ private static void SetTabData(TabInfo localTab, ExportTab otherTab) localTab.SiteMapPriority = otherTab.SiteMapPriority; localTab.IconFileLarge = otherTab.IconFileLarge; localTab.CultureCode = otherTab.CultureCode; - //localTab.UniqueId = otherTab.UniqueId; + + // localTab.UniqueId = otherTab.UniqueId; localTab.VersionGuid = otherTab.VersionGuid; localTab.LocalizedVersionGuid = otherTab.LocalizedVersionGuid; localTab.Level = otherTab.Level; @@ -1405,13 +1509,41 @@ private static void SetTabData(TabInfo localTab, ExportTab otherTab) localTab.Terms.Clear(); localTab.Terms.AddRange(TermHelper.ToTabTerms(otherTab.Tags, localTab.PortalID)); } + + private static bool IsTabIncluded(ExportTabInfo tab, IList allTabs, PageToExport[] selectedPages) + { + var first = true; + while (tab != null) + { + var pg = selectedPages.FirstOrDefault(p => p.TabId == tab.TabID); + if (pg != null) + { + if (first) + { + // this is the current page we are checking for. + return pg.CheckedState == TriCheckedState.Checked || pg.CheckedState == TriCheckedState.CheckedWithAllChildren; + } + + // this is a [grand] parent of the page we are checking for. + if (pg.CheckedState == TriCheckedState.CheckedWithAllChildren) + { + return true; + } + } + + first = false; + tab = allTabs.FirstOrDefault(t => t.TabID == tab.ParentID); + } + + return false; + } private void RepairReferenceTabs(IList referenceTabs, IList localTabs, IList exportTabs) { foreach (var tabId in referenceTabs) { var localTab = localTabs.FirstOrDefault(t => t.TabID == tabId); - if (localTab != null && Int32.TryParse(localTab.Url, out int urlTabId)) + if (localTab != null && int.TryParse(localTab.Url, out int urlTabId)) { var exportTab = exportTabs.FirstOrDefault(t => t.TabId == urlTabId); if (exportTab != null && exportTab.LocalId.HasValue) @@ -1421,212 +1553,237 @@ private void RepairReferenceTabs(IList referenceTabs, IList localT } } } - } - - #region Methods for updating CreatedBy and ModifiedBy of various tables - + } + private void UpdateTabChangers(int tabId, int createdBy, int modifiedBy) { - _dataProvider.UpdateRecordChangers("Tabs", "TabID", tabId, createdBy, modifiedBy); + this._dataProvider.UpdateRecordChangers("Tabs", "TabID", tabId, createdBy, modifiedBy); } // ReSharper disable UnusedMember.Local private void UpdateTabPermissionChangers(int tabPermissionId, int createdBy, int modifiedBy) { - _dataProvider.UpdateRecordChangers("TabPermission", "TabPermissionID", tabPermissionId, createdBy, modifiedBy); + this._dataProvider.UpdateRecordChangers("TabPermission", "TabPermissionID", tabPermissionId, createdBy, modifiedBy); } private void UpdateTabSettingChangers(int tabId, string settingName, int createdBy, int modifiedBy) { - _dataProvider.UpdateSettingRecordChangers("TabSettings", "TabID", tabId, settingName, createdBy, modifiedBy); + this._dataProvider.UpdateSettingRecordChangers("TabSettings", "TabID", tabId, settingName, createdBy, modifiedBy); } private void UpdateTabUrlChangers(int tabUrlId, int createdBy, int modifiedBy) { - _dataProvider.UpdateRecordChangers("TabUrls", "TabUrlID", tabUrlId, createdBy, modifiedBy); + this._dataProvider.UpdateRecordChangers("TabUrls", "TabUrlID", tabUrlId, createdBy, modifiedBy); } private void UpdateTabModuleChangers(int tabModuleId, int createdBy, int modifiedBy) { - _dataProvider.UpdateRecordChangers("TabModules", "TabModuleID", tabModuleId, createdBy, modifiedBy); + this._dataProvider.UpdateRecordChangers("TabModules", "TabModuleID", tabModuleId, createdBy, modifiedBy); } private void UpdateTabModuleSettingsChangers(int tabModuleId, string settingName, int createdBy, int modifiedBy) { - _dataProvider.UpdateSettingRecordChangers("TabModuleSettings", "TabModuleID", tabModuleId, settingName, createdBy, modifiedBy); + this._dataProvider.UpdateSettingRecordChangers("TabModuleSettings", "TabModuleID", tabModuleId, settingName, createdBy, modifiedBy); } private void UpdateModuleChangers(int moduleId, int createdBy, int modifiedBy) { - _dataProvider.UpdateRecordChangers("Modules", "ModuleID", moduleId, createdBy, modifiedBy); + this._dataProvider.UpdateRecordChangers("Modules", "ModuleID", moduleId, createdBy, modifiedBy); } private void UpdateModulePermissionChangers(int modulePermissionId, int createdBy, int modifiedBy) { - _dataProvider.UpdateRecordChangers("ModulePermission", "ModulePermissionID", modulePermissionId, createdBy, modifiedBy); + this._dataProvider.UpdateRecordChangers("ModulePermission", "ModulePermissionID", modulePermissionId, createdBy, modifiedBy); } private void UpdateModuleSettingsChangers(int moduleId, string settingName, int createdBy, int modifiedBy) { - _dataProvider.UpdateSettingRecordChangers("ModuleSettings", "ModuleID", moduleId, settingName, createdBy, modifiedBy); + this._dataProvider.UpdateSettingRecordChangers("ModuleSettings", "ModuleID", moduleId, settingName, createdBy, modifiedBy); } private void UpdateTabUniqueId(int tabId, Guid uniqueId) { - _dataProvider.UpdateUniqueId("Tabs", "TabID", tabId, uniqueId); + this._dataProvider.UpdateUniqueId("Tabs", "TabID", tabId, uniqueId); } private void UpdateModuleUniqueId(int tabModuleId, Guid uniqueId) { - _dataProvider.UpdateUniqueId("TabModules", "TabModuleID", tabModuleId, uniqueId); - } - - - #endregion - - #endregion - - #region export methods - + this._dataProvider.UpdateUniqueId("TabModules", "TabModuleID", tabModuleId, uniqueId); + } + private void ProcessExportPages() { - var selectedPages = _exportDto.Pages; - _totals = string.IsNullOrEmpty(CheckPoint.StageData) + var selectedPages = this._exportDto.Pages; + this._totals = string.IsNullOrEmpty(this.CheckPoint.StageData) ? new ProgressTotals() - : JsonConvert.DeserializeObject(CheckPoint.StageData); + : JsonConvert.DeserializeObject(this.CheckPoint.StageData); - var portalId = _exportImportJob.PortalId; + var portalId = this._exportImportJob.PortalId; - var toDate = _exportImportJob.CreatedOnDate.ToLocalTime(); - var fromDate = (_exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); + var toDate = this._exportImportJob.CreatedOnDate.ToLocalTime(); + var fromDate = (this._exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var isAllIncluded = selectedPages.Any(p => p.TabId == -1 && p.CheckedState == TriCheckedState.CheckedWithAllChildren); - var allTabs = EntitiesController.Instance.GetPortalTabs(portalId, - _exportDto.IncludeDeletions, IncludeSystem, toDate, fromDate) // ordered by TabID + var allTabs = EntitiesController.Instance.GetPortalTabs( + portalId, + this._exportDto.IncludeDeletions, this.IncludeSystem, toDate, fromDate) // ordered by TabID .OrderBy(tab => tab.TabPath).ToArray(); - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? allTabs.Length : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? allTabs.Length : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + var progressStep = 100.0 / allTabs.Length; - CheckPoint.TotalItems = IncludeSystem || isAllIncluded + this.CheckPoint.TotalItems = this.IncludeSystem || isAllIncluded ? allTabs.Length : allTabs.Count(otherPg => IsTabIncluded(otherPg, allTabs, selectedPages)); - //Note: We assume no new tabs were added while running; otherwise, some tabs might get skipped. + // Note: We assume no new tabs were added while running; otherwise, some tabs might get skipped. for (var index = 0; index < allTabs.Length; index++) { - if (CheckCancelled(_exportImportJob)) break; - + if (this.CheckCancelled(this._exportImportJob)) + { + break; + } + var otherPg = allTabs.ElementAt(index); - if (_totals.LastProcessedId > index) continue; - - if (IncludeSystem || isAllIncluded || IsTabIncluded(otherPg, allTabs, selectedPages)) + if (this._totals.LastProcessedId > index) + { + continue; + } + + if (this.IncludeSystem || isAllIncluded || IsTabIncluded(otherPg, allTabs, selectedPages)) { - var tab = _tabController.GetTab(otherPg.TabID, portalId); - //Do not export tab which has never been published. + var tab = this._tabController.GetTab(otherPg.TabID, portalId); + + // Do not export tab which has never been published. if (tab.HasBeenPublished) { - var exportPage = SaveExportPage(tab); + var exportPage = this.SaveExportPage(tab); - _totals.TotalTabSettings += - ExportTabSettings(exportPage, toDate, fromDate); + this._totals.TotalTabSettings += + this.ExportTabSettings(exportPage, toDate, fromDate); - _totals.TotalTabPermissions += - ExportTabPermissions(exportPage, toDate, fromDate); + this._totals.TotalTabPermissions += + this.ExportTabPermissions(exportPage, toDate, fromDate); - _totals.TotalTabUrls += - ExportTabUrls(exportPage, toDate, fromDate); + this._totals.TotalTabUrls += + this.ExportTabUrls(exportPage, toDate, fromDate); - _totals.TotalModules += - ExportTabModulesAndRelatedItems(exportPage, toDate, fromDate); + this._totals.TotalModules += + this.ExportTabModulesAndRelatedItems(exportPage, toDate, fromDate); - _totals.TotalTabModules += - ExportTabModules(exportPage, _exportDto.IncludeDeletions, toDate, fromDate); + this._totals.TotalTabModules += + this.ExportTabModules(exportPage, this._exportDto.IncludeDeletions, toDate, fromDate); - _totals.TotalTabModuleSettings += - ExportTabModuleSettings(exportPage, _exportDto.IncludeDeletions, toDate, fromDate); - _totals.TotalTabs++; + this._totals.TotalTabModuleSettings += + this.ExportTabModuleSettings(exportPage, this._exportDto.IncludeDeletions, toDate, fromDate); + this._totals.TotalTabs++; } - _totals.LastProcessedId = index; + + this._totals.LastProcessedId = index; } - CheckPoint.Progress += progressStep; - CheckPoint.ProcessedItems++; - CheckPoint.StageData = JsonConvert.SerializeObject(_totals); - if (CheckPointStageCallback(this)) break; + this.CheckPoint.Progress += progressStep; + this.CheckPoint.ProcessedItems++; + this.CheckPoint.StageData = JsonConvert.SerializeObject(this._totals); + if (this.CheckPointStageCallback(this)) + { + break; + } } - ReportExportTotals(); - UpdateTotalProcessedPackages(); + this.ReportExportTotals(); + this.UpdateTotalProcessedPackages(); } private int ExportTabSettings(ExportTab exportPage, DateTime toDate, DateTime? fromDate) { var tabSettings = EntitiesController.Instance.GetTabSettings(exportPage.TabId, toDate, fromDate); - if (tabSettings.Count > 0) - Repository.CreateItems(tabSettings, exportPage.Id); + if (tabSettings.Count > 0) + { + this.Repository.CreateItems(tabSettings, exportPage.Id); + } + return tabSettings.Count; } private int ExportTabPermissions(ExportTab exportPage, DateTime toDate, DateTime? fromDate) { - if (!_exportDto.IncludePermissions) return 0; - + if (!this._exportDto.IncludePermissions) + { + return 0; + } + var tabPermissions = EntitiesController.Instance.GetTabPermissions(exportPage.TabId, toDate, fromDate); - if (tabPermissions.Count > 0) - Repository.CreateItems(tabPermissions, exportPage.Id); + if (tabPermissions.Count > 0) + { + this.Repository.CreateItems(tabPermissions, exportPage.Id); + } + return tabPermissions.Count; } private int ExportTabUrls(ExportTab exportPage, DateTime toDate, DateTime? fromDate) { var tabUrls = EntitiesController.Instance.GetTabUrls(exportPage.TabId, toDate, fromDate); - if (tabUrls.Count > 0) - Repository.CreateItems(tabUrls, exportPage.Id); + if (tabUrls.Count > 0) + { + this.Repository.CreateItems(tabUrls, exportPage.Id); + } + return tabUrls.Count; } private int ExportTabModules(ExportTab exportPage, bool includeDeleted, DateTime toDate, DateTime? fromDate) { var tabModules = EntitiesController.Instance.GetTabModules(exportPage.TabId, includeDeleted, toDate, fromDate); - if (tabModules.Count > 0) - Repository.CreateItems(tabModules, exportPage.Id); + if (tabModules.Count > 0) + { + this.Repository.CreateItems(tabModules, exportPage.Id); + } + return tabModules.Count; } private int ExportTabModuleSettings(ExportTab exportPage, bool includeDeleted, DateTime toDate, DateTime? fromDate) { var tabModuleSettings = EntitiesController.Instance.GetTabModuleSettings(exportPage.TabId, includeDeleted, toDate, fromDate); - if (tabModuleSettings.Count > 0) - Repository.CreateItems(tabModuleSettings, exportPage.Id); + if (tabModuleSettings.Count > 0) + { + this.Repository.CreateItems(tabModuleSettings, exportPage.Id); + } + return tabModuleSettings.Count; } private int ExportTabModulesAndRelatedItems(ExportTab exportPage, DateTime toDate, DateTime? fromDate) { - var modules = EntitiesController.Instance.GetModules(exportPage.TabId, _exportDto.IncludeDeletions, toDate, fromDate); + var modules = EntitiesController.Instance.GetModules(exportPage.TabId, this._exportDto.IncludeDeletions, toDate, fromDate); if (modules.Count > 0) { - Repository.CreateItems(modules, exportPage.Id); + this.Repository.CreateItems(modules, exportPage.Id); foreach (var exportModule in modules) { - _totals.TotalModuleSettings += - ExportModuleSettings(exportModule, toDate, fromDate); + this._totals.TotalModuleSettings += + this.ExportModuleSettings(exportModule, toDate, fromDate); - _totals.TotalModulePermissions += - ExportModulePermissions(exportModule, toDate, fromDate); + this._totals.TotalModulePermissions += + this.ExportModulePermissions(exportModule, toDate, fromDate); - if (_exportDto.IncludeContent) + if (this._exportDto.IncludeContent) { - _totals.TotalContents += - ExportPortableContent(exportPage, exportModule, toDate, fromDate); + this._totals.TotalContents += + this.ExportPortableContent(exportPage, exportModule, toDate, fromDate); } - _totals.TotalPackages += - ExportModulePackage(exportModule); + this._totals.TotalPackages += + this.ExportModulePackage(exportModule); } } @@ -1635,9 +1792,9 @@ private int ExportTabModulesAndRelatedItems(ExportTab exportPage, DateTime toDat private int ExportModulePackage(ExportModule exportModule) { - if (!_exportedModuleDefinitions.Contains(exportModule.ModuleDefID) && _exportDto.IncludeExtensions) + if (!this._exportedModuleDefinitions.Contains(exportModule.ModuleDefID) && this._exportDto.IncludeExtensions) { - var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{_exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipPackages}"; + var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{this._exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipPackages}"; var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(exportModule.ModuleDefID); var desktopModuleId = moduleDefinition.DesktopModuleID; var desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger); @@ -1651,15 +1808,16 @@ private int ExportModulePackage(ExportModule exportModule) var offset = Path.GetDirectoryName(filePath)?.Length + 1; CompressionUtil.AddFileToArchive(filePath, packageZipFile, offset.GetValueOrDefault(0)); - Repository.CreateItem(new ExportPackage - { - PackageName = package.Name, - Version = package.Version, - PackageType = package.PackageType, - PackageFileName = InstallerUtil.GetPackageBackupName(package) - }, null); + this.Repository.CreateItem( + new ExportPackage + { + PackageName = package.Name, + Version = package.Version, + PackageType = package.PackageType, + PackageFileName = InstallerUtil.GetPackageBackupName(package), + }, null); - _exportedModuleDefinitions.Add(exportModule.ModuleDefID); + this._exportedModuleDefinitions.Add(exportModule.ModuleDefID); return 1; } catch (Exception ex) @@ -1667,49 +1825,57 @@ private int ExportModulePackage(ExportModule exportModule) Logger.Error(ex); return 0; } - } } + return 0; } private int ExportModuleSettings(ExportModule exportModule, DateTime toDate, DateTime? fromDate) { var moduleSettings = EntitiesController.Instance.GetModuleSettings(exportModule.ModuleID, toDate, fromDate); - if (moduleSettings.Count > 0) - Repository.CreateItems(moduleSettings, exportModule.Id); + if (moduleSettings.Count > 0) + { + this.Repository.CreateItems(moduleSettings, exportModule.Id); + } + return moduleSettings.Count; } private int ExportModulePermissions(ExportModule exportModule, DateTime toDate, DateTime? fromDate) { var modulePermission = EntitiesController.Instance.GetModulePermissions(exportModule.ModuleID, toDate, fromDate); - if (modulePermission.Count > 0) - Repository.CreateItems(modulePermission, exportModule.Id); + if (modulePermission.Count > 0) + { + this.Repository.CreateItems(modulePermission, exportModule.Id); + } + return modulePermission.Count; } // Note: until now there is no use of time range for content // ReSharper disable UnusedParameter.Local private int ExportPortableContent(ExportTab exportPage, ExportModule exportModule, DateTime toDate, DateTime? fromDat) + // ReSharper enable UnusedParameter.Local { // check if module's contnt was exported before - var existingItems = Repository.FindItems(m => m.ModuleID == exportModule.ModuleID); + var existingItems = this.Repository.FindItems(m => m.ModuleID == exportModule.ModuleID); if (!existingItems.Any()) { var moduleDef = ModuleDefinitionController.GetModuleDefinitionByID(exportModule.ModuleDefID); - var desktopModuleInfo = DesktopModuleController.GetDesktopModule(moduleDef.DesktopModuleID, _exportDto.PortalId); + var desktopModuleInfo = DesktopModuleController.GetDesktopModule(moduleDef.DesktopModuleID, this._exportDto.PortalId); if (!string.IsNullOrEmpty(desktopModuleInfo?.BusinessControllerClass)) { try { - var module = _moduleController.GetModule(exportModule.ModuleID, exportPage.TabId, true); + var module = this._moduleController.GetModule(exportModule.ModuleID, exportPage.TabId, true); if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && module.DesktopModule.IsPortable) { try { - var businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, + var businessController = Reflection.CreateObject( + module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); var controller = businessController as IPortable; var content = controller?.ExportModule(module.ModuleID); @@ -1722,23 +1888,24 @@ private int ExportPortableContent(ExportTab exportPage, ExportModule exportModul XmlContent = content, }; - Repository.CreateItem(record, exportModule.Id); + this.Repository.CreateItem(record, exportModule.Id); return 1; } } catch (Exception e) { - Result.AddLogEntry("Error exporting module data, Module ID=" + exportModule.ModuleID, e.Message, ReportLevel.Error); + this.Result.AddLogEntry("Error exporting module data, Module ID=" + exportModule.ModuleID, e.Message, ReportLevel.Error); } } } catch (Exception ex) { - Result.AddLogEntry("Error cerating business class type", desktopModuleInfo.BusinessControllerClass, ReportLevel.Error); + this.Result.AddLogEntry("Error cerating business class type", desktopModuleInfo.BusinessControllerClass, ReportLevel.Error); Logger.Error("Error cerating business class type. " + ex); } } } + return 0; } @@ -1783,123 +1950,95 @@ private ExportTab SaveExportPage(TabInfo tab) TabPath = tab.TabPath, HasBeenPublished = tab.HasBeenPublished, IsSystem = tab.IsSystem, - StateID = tab.StateID + StateID = tab.StateID, }; - Repository.CreateItem(exportPage, null); - Result.AddLogEntry("Exported page", tab.TabName + " (" + tab.TabPath + ")"); + this.Repository.CreateItem(exportPage, null); + this.Result.AddLogEntry("Exported page", tab.TabName + " (" + tab.TabPath + ")"); return exportPage; - } - - #endregion - - #region helper methods - - private static bool IsTabIncluded(ExportTabInfo tab, IList allTabs, PageToExport[] selectedPages) - { - var first = true; - while (tab != null) - { - var pg = selectedPages.FirstOrDefault(p => p.TabId == tab.TabID); - if (pg != null) - { - if (first) - { - // this is the current page we are checking for. - return pg.CheckedState == TriCheckedState.Checked || pg.CheckedState == TriCheckedState.CheckedWithAllChildren; - } - - // this is a [grand] parent of the page we are checking for. - if (pg.CheckedState == TriCheckedState.CheckedWithAllChildren) - { - return true; - } - } - - first = false; - tab = allTabs.FirstOrDefault(t => t.TabID == tab.ParentID); - } - - return false; - } - - public static void ResetContentsFlag(ExportImportRepository repository) - { - // reset restored flag; if it same extracted db is reused, then content will be restored - var toSkip = 0; - const int batchSize = 100; - var totalCount = repository.GetCount(); - while (totalCount > 0) - { - var items = repository.GetAllItems(skip: toSkip, max: batchSize) - .Where(item => item.IsRestored).ToList(); - if (items.Count > 0) - { - items.ForEach(item => item.IsRestored = false); - repository.UpdateItems(items); - } - toSkip += batchSize; - totalCount -= batchSize; - } - } + } private void ReportExportTotals() { - ReportTotals("Exported"); + this.ReportTotals("Exported"); } private void ReportImportTotals() { - ReportTotals("Imported"); + this.ReportTotals("Imported"); } private void ReportTotals(string prefix) { - Result.AddSummary(prefix + " Tabs", _totals.TotalTabs.ToString()); - Result.AddLogEntry(prefix + " Tab Settings", _totals.TotalTabSettings.ToString()); - Result.AddLogEntry(prefix + " Tab Permissions", _totals.TotalTabPermissions.ToString()); - Result.AddLogEntry(prefix + " Tab Urls", _totals.TotalTabUrls.ToString()); - Result.AddLogEntry(prefix + " Modules", _totals.TotalModules.ToString()); - Result.AddLogEntry(prefix + " Module Settings", _totals.TotalModuleSettings.ToString()); - Result.AddLogEntry(prefix + " Module Permissions", _totals.TotalModulePermissions.ToString()); - Result.AddLogEntry(prefix + " Tab Modules", _totals.TotalTabModules.ToString()); - Result.AddLogEntry(prefix + " Tab Module Settings", _totals.TotalTabModuleSettings.ToString()); - Result.AddLogEntry(prefix + " Module Packages", _totals.TotalPackages.ToString()); + this.Result.AddSummary(prefix + " Tabs", this._totals.TotalTabs.ToString()); + this.Result.AddLogEntry(prefix + " Tab Settings", this._totals.TotalTabSettings.ToString()); + this.Result.AddLogEntry(prefix + " Tab Permissions", this._totals.TotalTabPermissions.ToString()); + this.Result.AddLogEntry(prefix + " Tab Urls", this._totals.TotalTabUrls.ToString()); + this.Result.AddLogEntry(prefix + " Modules", this._totals.TotalModules.ToString()); + this.Result.AddLogEntry(prefix + " Module Settings", this._totals.TotalModuleSettings.ToString()); + this.Result.AddLogEntry(prefix + " Module Permissions", this._totals.TotalModulePermissions.ToString()); + this.Result.AddLogEntry(prefix + " Tab Modules", this._totals.TotalTabModules.ToString()); + this.Result.AddLogEntry(prefix + " Tab Module Settings", this._totals.TotalTabModuleSettings.ToString()); + this.Result.AddLogEntry(prefix + " Module Packages", this._totals.TotalPackages.ToString()); } private void UpdateTotalProcessedPackages() { - //HACK: get skin packages checkpoint and add "_totals.TotalPackages" to it - var packagesCheckpoint = EntitiesController.Instance.GetJobChekpoints(_exportImportJob.JobId).FirstOrDefault( + // HACK: get skin packages checkpoint and add "_totals.TotalPackages" to it + var packagesCheckpoint = EntitiesController.Instance.GetJobChekpoints(this._exportImportJob.JobId).FirstOrDefault( cp => cp.Category == Constants.Category_Packages); if (packagesCheckpoint != null) { - //Note: if restart of job occurs, these will report wrong values - packagesCheckpoint.TotalItems += _totals.TotalPackages; - packagesCheckpoint.ProcessedItems += _totals.TotalPackages; + // Note: if restart of job occurs, these will report wrong values + packagesCheckpoint.TotalItems += this._totals.TotalPackages; + packagesCheckpoint.ProcessedItems += this._totals.TotalPackages; EntitiesController.Instance.UpdateJobChekpoint(packagesCheckpoint); } } private int GetLocalStateId(int exportedStateId) { - var exportWorkflowState = Repository.GetItem(item => item.StateID == exportedStateId); + var exportWorkflowState = this.Repository.GetItem(item => item.StateID == exportedStateId); var stateId = exportWorkflowState?.LocalId ?? Null.NullInteger; - if (stateId <= 0) return stateId; + if (stateId <= 0) + { + return stateId; + } + var state = WorkflowStateManager.Instance.GetWorkflowState(stateId); - if (state == null) return -1; + if (state == null) + { + return -1; + } + var workflow = WorkflowManager.Instance.GetWorkflow(state.WorkflowID); - if (workflow == null) return -1; + if (workflow == null) + { + return -1; + } + return workflow.FirstState.StateID; } private bool IsTabPublished(TabInfo tab) { var stateId = tab.StateID; - if (stateId <= 0) return true; + if (stateId <= 0) + { + return true; + } + var state = WorkflowStateManager.Instance.GetWorkflowState(stateId); - if (state == null) return true; + if (state == null) + { + return true; + } + var workflow = WorkflowManager.Instance.GetWorkflow(state.WorkflowID); - if (workflow == null) return true; + if (workflow == null) + { + return true; + } + return workflow.LastState.StateID == stateId; } @@ -1914,7 +2053,7 @@ private bool IsParentTabPresentInExport(ExportTab exportedTab, IList { if (parentId != -1) { - if (IsParentAlreadyCheck(parentId)) + if (this.IsParentAlreadyCheck(parentId)) { return true; } @@ -1926,8 +2065,8 @@ private bool IsParentTabPresentInExport(ExportTab exportedTab, IList var parentFound = exportedTabs.FirstOrDefault(t => t.TabId == parentId); if (parentFound != null) { - AddToParentSearched(parentFound.TabId, true); - isParentPresent = IsParentTabPresentInExport(parentFound, exportedTabs, localTabs); + this.AddToParentSearched(parentFound.TabId, true); + isParentPresent = this.IsParentTabPresentInExport(parentFound, exportedTabs, localTabs); return isParentPresent; } else @@ -1943,7 +2082,7 @@ private bool IsParentTabPresentInExport(ExportTab exportedTab, IList if (isTabUrlParsed) { - if (IsParentAlreadyCheck(parentIdUrl)) + if (this.IsParentAlreadyCheck(parentIdUrl)) { return true; } @@ -1955,8 +2094,8 @@ private bool IsParentTabPresentInExport(ExportTab exportedTab, IList var parentFound = exportedTabs.FirstOrDefault(t => t.TabId == parentIdUrl); if (parentFound != null) { - AddToParentSearched(parentFound.TabId, false); - isParentPresent = IsParentTabPresentInExport(parentFound, exportedTabs, localTabs); + this.AddToParentSearched(parentFound.TabId, false); + isParentPresent = this.IsParentTabPresentInExport(parentFound, exportedTabs, localTabs); } else { @@ -1965,32 +2104,33 @@ private bool IsParentTabPresentInExport(ExportTab exportedTab, IList } } } + return isParentPresent; } private bool IsParentAlreadyCheck(int parentId) { - return _searchedParentTabs.ContainsKey(parentId); + return this._searchedParentTabs.ContainsKey(parentId); } private void AddToParentSearched(int tabId, bool isParentId) { - if (!_searchedParentTabs.ContainsKey(tabId)) + if (!this._searchedParentTabs.ContainsKey(tabId)) { - _searchedParentTabs.Add(tabId, isParentId); + this._searchedParentTabs.Add(tabId, isParentId); } } private void UpdateParentInPartialImportTabs(TabInfo localTab, ExportTab parentExportedTab, int portalId, IList exportTabs, IList localTabs) { - if (!_searchedParentTabs.ContainsKey(parentExportedTab.TabId)) + if (!this._searchedParentTabs.ContainsKey(parentExportedTab.TabId)) { return; } var parentId = parentExportedTab.TabId; - var tabsToUpdateGuids = _partialImportedTabs.Where(t => t.Value == parentId).ToList(); + var tabsToUpdateGuids = this._partialImportedTabs.Where(t => t.Value == parentId).ToList(); foreach (var tabGuid in tabsToUpdateGuids) { @@ -1998,11 +2138,11 @@ private void UpdateParentInPartialImportTabs(TabInfo localTab, ExportTab parentE if (localTabToUpdate != null) { - var tabWithoutParentId = _tabController.GetTab(localTabToUpdate.TabID, portalId); + var tabWithoutParentId = this._tabController.GetTab(localTabToUpdate.TabID, portalId); if (tabWithoutParentId != null) { - if (_searchedParentTabs[parentExportedTab.TabId]) + if (this._searchedParentTabs[parentExportedTab.TabId]) { tabWithoutParentId.ParentId = localTab.TabID; @@ -2017,8 +2157,8 @@ private void UpdateParentInPartialImportTabs(TabInfo localTab, ExportTab parentE tabWithoutParentId.Url = localTab.TabID.ToString(); } - _tabController.UpdateTab(tabWithoutParentId); - _partialImportedTabs.Remove(tabGuid.Key); + this._tabController.UpdateTab(tabWithoutParentId); + this._partialImportedTabs.Remove(tabGuid.Key); } } } @@ -2026,7 +2166,7 @@ private void UpdateParentInPartialImportTabs(TabInfo localTab, ExportTab parentE private void SetPartialImportSettings(ExportTab exportedTab, TabInfo localTab) { - if (exportedTab.LocalId != null && _partialImportedTabs.ContainsKey(exportedTab.LocalId.GetValueOrDefault(Null.NullInteger)) && (exportedTab.ParentId.GetValueOrDefault(Null.NullInteger) != -1)) + if (exportedTab.LocalId != null && this._partialImportedTabs.ContainsKey(exportedTab.LocalId.GetValueOrDefault(Null.NullInteger)) && (exportedTab.ParentId.GetValueOrDefault(Null.NullInteger) != -1)) { localTab.ParentId = -1; localTab.IsVisible = false; @@ -2041,27 +2181,23 @@ private void CheckForPartialImportedTabs(ExportTab tabToExport) { if (int.TryParse(tabToExport.Url, out exportTabParentId)) { - AddToPartialImportedTabs(tabToExport.LocalId.GetValueOrDefault(Null.NullInteger), exportTabParentId); + this.AddToPartialImportedTabs(tabToExport.LocalId.GetValueOrDefault(Null.NullInteger), exportTabParentId); } } else { - AddToPartialImportedTabs(tabToExport.LocalId.GetValueOrDefault(Null.NullInteger), exportTabParentId); + this.AddToPartialImportedTabs(tabToExport.LocalId.GetValueOrDefault(Null.NullInteger), exportTabParentId); } } private void AddToPartialImportedTabs(int localTabId, int exportTabParentId) { - if (!_partialImportedTabs.ContainsKey(localTabId) && exportTabParentId != -1) + if (!this._partialImportedTabs.ContainsKey(localTabId) && exportTabParentId != -1) { - _partialImportedTabs.Add(localTabId, exportTabParentId); + this._partialImportedTabs.Add(localTabId, exportTabParentId); } - } - - #endregion - - #region private classes - + } + [JsonObject] private class ProgressTotals { @@ -2070,17 +2206,25 @@ private class ProgressTotals public int LastProcessedId { get; set; } public int TotalTabs { get; set; } + public int TotalTabSettings { get; set; } + public int TotalTabPermissions { get; set; } + public int TotalTabUrls { get; set; } public int TotalModules { get; set; } + public int TotalModulePermissions { get; set; } + public int TotalModuleSettings { get; set; } + public int TotalContents { get; set; } + public int TotalPackages { get; set; } public int TotalTabModules { get; set; } + public int TotalTabModuleSettings { get; set; } } @@ -2089,7 +2233,6 @@ private class ImportModuleMapping public int ExportModuleId { get; set; } public int LocalModuleId { get; set; } - } - #endregion + } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs index 8312abbf6c6..ee0701dbacb 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs @@ -1,22 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using DotNetNuke.Common.Utilities; -using System; -using System.Globalization; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Controllers; -using Dnn.ExportImport.Dto.Portal; -using DotNetNuke.Services.Localization; -using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Controllers; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.Portal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Localization; + + using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; + /// /// Service to export/import portal data. /// @@ -32,10 +34,18 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); - if (CheckPoint.Stage > 1) return; - if (CheckCancelled(exportJob)) return; + if (this.CheckPoint.Stage > 1) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + List portalLanguages = null; - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { var portalSettings = new List(); var settingToMigrate = @@ -45,76 +55,100 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { portalSettings = CBO.FillCollection(DataProvider.Instance().GetPortalSettings(exportJob.PortalId, toDate, fromDate)); - //Migrate only allowed portal settings. + // Migrate only allowed portal settings. portalSettings = portalSettings.Where(x => settingToMigrate.Any(setting => setting.Trim().Equals(x.SettingName, StringComparison.InvariantCultureIgnoreCase))).ToList(); - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? portalSettings.Count : CheckPoint.TotalItems; - if (CheckPoint.TotalItems == portalSettings.Count) + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? portalSettings.Count : this.CheckPoint.TotalItems; + if (this.CheckPoint.TotalItems == portalSettings.Count) { portalLanguages = CBO.FillCollection( DataProvider.Instance().GetPortalLanguages(exportJob.PortalId, toDate, fromDate)); - CheckPoint.TotalItems += portalLanguages.Count; + this.CheckPoint.TotalItems += portalLanguages.Count; } - CheckPointStageCallback(this); + + this.CheckPointStageCallback(this); - Repository.CreateItems(portalSettings); + this.Repository.CreateItems(portalSettings); } - Result.AddSummary("Exported Portal Settings", portalSettings.Count.ToString()); + + this.Result.AddSummary("Exported Portal Settings", portalSettings.Count.ToString()); - CheckPoint.Progress = 50; - CheckPoint.ProcessedItems = portalSettings.Count; - CheckPoint.Stage++; - if (CheckPointStageCallback(this)) return; + this.CheckPoint.Progress = 50; + this.CheckPoint.ProcessedItems = portalSettings.Count; + this.CheckPoint.Stage++; + if (this.CheckPointStageCallback(this)) + { + return; + } } - if (CheckPoint.Stage == 1) + if (this.CheckPoint.Stage == 1) { - if (CheckCancelled(exportJob)) return; - if (portalLanguages == null) + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (portalLanguages == null) + { portalLanguages = CBO.FillCollection(DataProvider.Instance() - .GetPortalLanguages(exportJob.PortalId, toDate, fromDate)); - - Repository.CreateItems(portalLanguages); - Result.AddSummary("Exported Portal Languages", portalLanguages.Count.ToString()); - CheckPoint.Progress = 100; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPoint.ProcessedItems += portalLanguages.Count; - CheckPointStageCallback(this); + .GetPortalLanguages(exportJob.PortalId, toDate, fromDate)); + } + + this.Repository.CreateItems(portalLanguages); + this.Result.AddSummary("Exported Portal Languages", portalLanguages.Count.ToString()); + this.CheckPoint.Progress = 100; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPoint.ProcessedItems += portalLanguages.Count; + this.CheckPointStageCallback(this); } } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? GetImportTotal() : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - if (CheckPoint.Stage > 1) return; - if (CheckPoint.Stage == 0) + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? this.GetImportTotal() : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + + if (this.CheckPoint.Stage > 1) + { + return; + } + + if (this.CheckPoint.Stage == 0) { - var portalSettings = Repository.GetAllItems().ToList(); - ProcessPortalSettings(importJob, importDto, portalSettings); - CheckPoint.TotalItems = GetImportTotal(); - Result.AddSummary("Imported Portal Settings", portalSettings.Count.ToString()); - CheckPoint.Progress += 50; - CheckPoint.Stage++; - CheckPoint.ProcessedItems = portalSettings.Count; - if (CheckPointStageCallback(this)) return; + var portalSettings = this.Repository.GetAllItems().ToList(); + this.ProcessPortalSettings(importJob, importDto, portalSettings); + this.CheckPoint.TotalItems = this.GetImportTotal(); + this.Result.AddSummary("Imported Portal Settings", portalSettings.Count.ToString()); + this.CheckPoint.Progress += 50; + this.CheckPoint.Stage++; + this.CheckPoint.ProcessedItems = portalSettings.Count; + if (this.CheckPointStageCallback(this)) + { + return; + } } - if (CheckPoint.Stage == 1) + + if (this.CheckPoint.Stage == 1) { - var portalLanguages = Repository.GetAllItems().ToList(); - ProcessPortalLanguages(importJob, importDto, portalLanguages); - Result.AddSummary("Imported Portal Languages", portalLanguages.Count.ToString()); - CheckPoint.Progress += 50; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPoint.ProcessedItems += portalLanguages.Count; - CheckPointStageCallback(this); + var portalLanguages = this.Repository.GetAllItems().ToList(); + this.ProcessPortalLanguages(importJob, importDto, portalLanguages); + this.Result.AddSummary("Imported Portal Languages", portalLanguages.Count.ToString()); + this.CheckPoint.Progress += 50; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPoint.ProcessedItems += portalLanguages.Count; + this.CheckPointStageCallback(this); } + /* ProgressPercentage = 0; var portalLocalizations = Repository.GetAllItems().ToList(); @@ -126,7 +160,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) public override int GetImportTotal() { - return Repository.GetCount() + Repository.GetCount(); + return this.Repository.GetCount() + this.Repository.GetCount(); } private void ProcessPortalSettings(ExportImportJob importJob, ImportDto importDto, @@ -137,8 +171,11 @@ private void ProcessPortalSettings(ExportImportJob importJob, ImportDto importDt CBO.FillCollection(DataProvider.Instance().GetPortalSettings(portalId, DateUtils.GetDatabaseUtcTime().AddYears(1), null)); foreach (var exportPortalSetting in portalSettings) { - if (CheckCancelled(importJob)) return; - + if (this.CheckCancelled(importJob)) + { + return; + } + var existingPortalSetting = localPortalSettings.FirstOrDefault( t => @@ -155,12 +192,13 @@ private void ProcessPortalSettings(ExportImportJob importJob, ImportDto importDt isUpdate = true; break; case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored portal settings", exportPortalSetting.SettingName); + this.Result.AddLogEntry("Ignored portal settings", exportPortalSetting.SettingName); continue; default: throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } + if (isUpdate) { var modifiedBy = Util.GetUserIdByName(importJob, exportPortalSetting.LastModifiedByUserId, @@ -170,7 +208,7 @@ private void ProcessPortalSettings(ExportImportJob importJob, ImportDto importDt DotNetNuke.Data.DataProvider.Instance() .UpdatePortalSetting(importJob.PortalId, exportPortalSetting.SettingName, exportPortalSetting.SettingValue, modifiedBy, exportPortalSetting.CultureCode, exportPortalSetting.IsSecure); - Result.AddLogEntry("Updated portal settings", exportPortalSetting.SettingName); + this.Result.AddLogEntry("Updated portal settings", exportPortalSetting.SettingName); } else { @@ -180,7 +218,7 @@ private void ProcessPortalSettings(ExportImportJob importJob, ImportDto importDt .UpdatePortalSetting(importJob.PortalId, exportPortalSetting.SettingName, exportPortalSetting.SettingValue, createdBy, exportPortalSetting.CultureCode, exportPortalSetting.IsSecure); - Result.AddLogEntry("Added portal settings", exportPortalSetting.SettingName); + this.Result.AddLogEntry("Added portal settings", exportPortalSetting.SettingName); } } } @@ -194,8 +232,11 @@ private void ProcessPortalLanguages(ExportImportJob importJob, ImportDto importD var localLanguages = CBO.FillCollection(DotNetNuke.Data.DataProvider.Instance().GetLanguages()); foreach (var exportPortalLanguage in portalLanguages) { - if (CheckCancelled(importJob)) return; - + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, exportPortalLanguage.CreatedByUserId, exportPortalLanguage.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, exportPortalLanguage.LastModifiedByUserId, exportPortalLanguage.LastModifiedByUserName); @@ -207,11 +248,12 @@ private void ProcessPortalLanguages(ExportImportJob importJob, ImportDto importD { Code = exportPortalLanguage.CultureCode, Fallback = Localization.SystemLocale, - Text = CultureInfo.GetCultureInfo(exportPortalLanguage.CultureCode).NativeName + Text = CultureInfo.GetCultureInfo(exportPortalLanguage.CultureCode).NativeName, }; Localization.SaveLanguage(locale); localLanguageId = locale.LanguageId; } + var existingPortalLanguage = localPortalLanguages.FirstOrDefault( t => @@ -225,26 +267,27 @@ private void ProcessPortalLanguages(ExportImportJob importJob, ImportDto importD isUpdate = true; break; case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored portal language", exportPortalLanguage.CultureCode); + this.Result.AddLogEntry("Ignored portal language", exportPortalLanguage.CultureCode); continue; default: throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } + if (isUpdate) { DotNetNuke.Data.DataProvider.Instance() .UpdatePortalLanguage(importJob.PortalId, localLanguageId.GetValueOrDefault(exportPortalLanguage.LanguageId), exportPortalLanguage.IsPublished, modifiedBy); - Result.AddLogEntry("Updated portal language", exportPortalLanguage.CultureCode); + this.Result.AddLogEntry("Updated portal language", exportPortalLanguage.CultureCode); } else { exportPortalLanguage.PortalLanguageId = DotNetNuke.Data.DataProvider.Instance() .AddPortalLanguage(importJob.PortalId, localLanguageId.GetValueOrDefault(exportPortalLanguage.LanguageId), exportPortalLanguage.IsPublished, createdBy); - Result.AddLogEntry("Added portal language", exportPortalLanguage.CultureCode); + this.Result.AddLogEntry("Added portal language", exportPortalLanguage.CultureCode); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs index 6aad21650f0..24ee145f4a9 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs @@ -1,18 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Dto.ProfileProperties; -using DotNetNuke.Common.Utilities; -using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.ProfileProperties; + using DotNetNuke.Common.Utilities; + + using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; + public class ProfilePropertiesService : BasePortableService { public override string Category => Constants.Category_ProfileProps; @@ -25,42 +27,66 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); - if (CheckCancelled(exportJob)) return; - if (CheckPoint.Stage > 0) return; - if (CheckCancelled(exportJob)) return; - + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var profileProperties = CBO.FillCollection( DataProvider.Instance() .GetPropertyDefinitionsByPortal(exportJob.PortalId, exportDto.IncludeDeletions, toDate, fromDate)).ToList(); - CheckPoint.Progress = 50; - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? profileProperties.Count : CheckPoint.TotalItems; - CheckPointStageCallback(this); + this.CheckPoint.Progress = 50; + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? profileProperties.Count : this.CheckPoint.TotalItems; + this.CheckPointStageCallback(this); - if (CheckCancelled(exportJob)) return; - Repository.CreateItems(profileProperties); - Result.AddSummary("Exported Profile Properties", profileProperties.Count.ToString()); - CheckPoint.Progress = 100; - CheckPoint.ProcessedItems = profileProperties.Count; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPointStageCallback(this); + if (this.CheckCancelled(exportJob)) + { + return; + } + + this.Repository.CreateItems(profileProperties); + this.Result.AddSummary("Exported Profile Properties", profileProperties.Count.ToString()); + this.CheckPoint.Progress = 100; + this.CheckPoint.ProcessedItems = profileProperties.Count; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPointStageCallback(this); } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckPoint.Stage > 0) return; - var profileProperties = Repository.GetAllItems().ToList(); - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? profileProperties.Count : CheckPoint.TotalItems; - CheckPointStageCallback(this); + if (this.CheckPoint.Stage > 0) + { + return; + } + + var profileProperties = this.Repository.GetAllItems().ToList(); + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? profileProperties.Count : this.CheckPoint.TotalItems; + this.CheckPointStageCallback(this); foreach (var profileProperty in profileProperties) { - if (CheckCancelled(importJob)) return; - + if (this.CheckCancelled(importJob)) + { + return; + } + var existingProfileProperty = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance() .GetPropertyDefinitionByName(importJob.PortalId, profileProperty.PropertyName)); @@ -87,20 +113,21 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } - Result.AddSummary("Imported Profile Properties", profileProperties.Count.ToString()); - CheckPoint.ProcessedItems = profileProperties.Count; - CheckPoint.Completed = true; - CheckPoint.Progress = 100; - CheckPoint.Stage++; - CheckPointStageCallback(this); + this.Result.AddSummary("Imported Profile Properties", profileProperties.Count.ToString()); + this.CheckPoint.ProcessedItems = profileProperties.Count; + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; + this.CheckPoint.Stage++; + this.CheckPointStageCallback(this); } public override int GetImportTotal() { - return Repository.GetCount(); + return this.Repository.GetCount(); } - private static void ProcessCreateProfileProperty(ExportImportJob importJob, + private static void ProcessCreateProfileProperty( + ExportImportJob importJob, ExportProfileProperty profileProperty, int createdById) { DotNetNuke.Data.DataProvider.Instance() @@ -116,7 +143,8 @@ private static void ProcessUpdateProfileProperty(ExportProfileProperty profilePr int modifiedById) { DotNetNuke.Data.DataProvider.Instance() - .UpdatePropertyDefinition(existingProfileProperty.PropertyDefinitionId, + .UpdatePropertyDefinition( + existingProfileProperty.PropertyDefinitionId, profileProperty.DataType ?? Null.NullInteger, profileProperty.DefaultValue, profileProperty.PropertyCategory, profileProperty.PropertyName, profileProperty.ReadOnly, profileProperty.Required, diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs index dccb0941829..23687b9cdd9 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Providers; -using Dnn.ExportImport.Dto.Roles; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Security.Roles; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Providers; + using Dnn.ExportImport.Dto.Roles; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Security.Roles; + public class RolesExportService : BasePortableService { public override string Category => Constants.Category_Roles; @@ -27,119 +28,188 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); - if (CheckPoint.Stage > 2) return; + if (this.CheckPoint.Stage > 2) + { + return; + } + List roles = null; List roleSettings = null; - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { - if (CheckCancelled(exportJob)) return; - + if (this.CheckCancelled(exportJob)) + { + return; + } + var roleGroups = CBO.FillCollection( DataProvider.Instance().GetAllRoleGroups(exportJob.PortalId, toDate, fromDate)); - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? roleGroups.Count : CheckPoint.TotalItems; - if (CheckPoint.TotalItems == roleGroups.Count) + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? roleGroups.Count : this.CheckPoint.TotalItems; + if (this.CheckPoint.TotalItems == roleGroups.Count) { roles = CBO.FillCollection( DataProvider.Instance().GetAllRoles(exportJob.PortalId, toDate, fromDate)); roleSettings = CBO.FillCollection( DataProvider.Instance().GetAllRoleSettings(exportJob.PortalId, toDate, fromDate)); - CheckPoint.TotalItems += roles.Count + roleSettings.Count; + this.CheckPoint.TotalItems += roles.Count + roleSettings.Count; } - CheckPointStageCallback(this); - - Repository.CreateItems(roleGroups); - Result.AddSummary("Exported Role Groups", roleGroups.Count.ToString()); - CheckPoint.ProcessedItems = roleGroups.Count; - CheckPoint.Progress = 30; - CheckPoint.Stage++; - if (CheckPointStageCallback(this)) return; + + this.CheckPointStageCallback(this); + + this.Repository.CreateItems(roleGroups); + this.Result.AddSummary("Exported Role Groups", roleGroups.Count.ToString()); + this.CheckPoint.ProcessedItems = roleGroups.Count; + this.CheckPoint.Progress = 30; + this.CheckPoint.Stage++; + if (this.CheckPointStageCallback(this)) + { + return; + } } - if (CheckPoint.Stage == 1) + if (this.CheckPoint.Stage == 1) { - if (CheckCancelled(exportJob)) return; - if (roles == null) + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (roles == null) + { roles = CBO.FillCollection( - DataProvider.Instance().GetAllRoles(exportJob.PortalId, toDate, fromDate)); - Repository.CreateItems(roles); - Result.AddSummary("Exported Roles", roles.Count.ToString()); - CheckPoint.Progress = 80; - CheckPoint.ProcessedItems += roles.Count; - CheckPoint.Stage++; - if (CheckPointStageCallback(this)) return; + DataProvider.Instance().GetAllRoles(exportJob.PortalId, toDate, fromDate)); + } + + this.Repository.CreateItems(roles); + this.Result.AddSummary("Exported Roles", roles.Count.ToString()); + this.CheckPoint.Progress = 80; + this.CheckPoint.ProcessedItems += roles.Count; + this.CheckPoint.Stage++; + if (this.CheckPointStageCallback(this)) + { + return; + } } - if (CheckPoint.Stage == 2) + if (this.CheckPoint.Stage == 2) { - if (CheckCancelled(exportJob)) return; - if (roleSettings == null) + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (roleSettings == null) + { roleSettings = CBO.FillCollection( - DataProvider.Instance().GetAllRoleSettings(exportJob.PortalId, toDate, fromDate)); - Repository.CreateItems(roleSettings); - Result.AddSummary("Exported Role Settings", roleSettings.Count.ToString()); - CheckPoint.Progress = 100; - CheckPoint.ProcessedItems += roleSettings.Count; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPointStageCallback(this); + DataProvider.Instance().GetAllRoleSettings(exportJob.PortalId, toDate, fromDate)); + } + + this.Repository.CreateItems(roleSettings); + this.Result.AddSummary("Exported Role Settings", roleSettings.Count.ToString()); + this.CheckPoint.Progress = 100; + this.CheckPoint.ProcessedItems += roleSettings.Count; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPointStageCallback(this); } } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckPoint.Stage > 2) return; - - if (CheckCancelled(importJob)) return; - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? GetImportTotal() : CheckPoint.TotalItems; - CheckPointStageCallback(this); - - var otherRoleGroups = Repository.GetAllItems().ToList(); - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage > 2) + { + return; + } + + if (this.CheckCancelled(importJob)) + { + return; + } + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? this.GetImportTotal() : this.CheckPoint.TotalItems; + this.CheckPointStageCallback(this); + + var otherRoleGroups = this.Repository.GetAllItems().ToList(); + if (this.CheckPoint.Stage == 0) { - ProcessRoleGroups(importJob, importDto, otherRoleGroups); - Repository.UpdateItems(otherRoleGroups); - Result.AddSummary("Imported Role Groups", otherRoleGroups.Count.ToString()); - CheckPoint.Progress = 40; - CheckPoint.ProcessedItems = otherRoleGroups.Count; - CheckPoint.Stage++; - if (CheckPointStageCallback(this)) return; + this.ProcessRoleGroups(importJob, importDto, otherRoleGroups); + this.Repository.UpdateItems(otherRoleGroups); + this.Result.AddSummary("Imported Role Groups", otherRoleGroups.Count.ToString()); + this.CheckPoint.Progress = 40; + this.CheckPoint.ProcessedItems = otherRoleGroups.Count; + this.CheckPoint.Stage++; + if (this.CheckPointStageCallback(this)) + { + return; + } } - if (CheckCancelled(importJob)) return; - var otherRoles = Repository.GetAllItems().ToList(); - if (CheckPoint.Stage == 1) + if (this.CheckCancelled(importJob)) + { + return; + } + + var otherRoles = this.Repository.GetAllItems().ToList(); + if (this.CheckPoint.Stage == 1) { - Result.AddSummary("Imported Roles", otherRoles.Count.ToString()); - ProcessRoles(importJob, importDto, otherRoleGroups, otherRoles); - Repository.UpdateItems(otherRoles); - CheckPoint.Progress = 50; - CheckPoint.ProcessedItems += otherRoles.Count; - CheckPoint.Stage++; - if (CheckPointStageCallback(this)) return; + this.Result.AddSummary("Imported Roles", otherRoles.Count.ToString()); + this.ProcessRoles(importJob, importDto, otherRoleGroups, otherRoles); + this.Repository.UpdateItems(otherRoles); + this.CheckPoint.Progress = 50; + this.CheckPoint.ProcessedItems += otherRoles.Count; + this.CheckPoint.Stage++; + if (this.CheckPointStageCallback(this)) + { + return; + } } - if (CheckPoint.Stage == 2) + if (this.CheckPoint.Stage == 2) { - if (CheckCancelled(importJob)) return; - var otherRoleSettings = Repository.GetAllItems().ToList(); - ProcessRoleSettings(importJob, importDto, otherRoles, otherRoleSettings); - Repository.UpdateItems(otherRoleSettings); - Result.AddSummary("Imported Role Settings", otherRoleSettings.Count.ToString()); - CheckPoint.Progress = 100; - CheckPoint.ProcessedItems += otherRoleSettings.Count; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPointStageCallback(this); + if (this.CheckCancelled(importJob)) + { + return; + } + + var otherRoleSettings = this.Repository.GetAllItems().ToList(); + this.ProcessRoleSettings(importJob, importDto, otherRoles, otherRoleSettings); + this.Repository.UpdateItems(otherRoleSettings); + this.Result.AddSummary("Imported Role Settings", otherRoleSettings.Count.ToString()); + this.CheckPoint.Progress = 100; + this.CheckPoint.ProcessedItems += otherRoleSettings.Count; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPointStageCallback(this); } } public override int GetImportTotal() { - return Repository.GetCount() + Repository.GetCount() + - Repository.GetCount(); + return this.Repository.GetCount() + this.Repository.GetCount() + + this.Repository.GetCount(); + } + + private static void RefreshRecordsUserIds(IEnumerable roleGroupItems) + { + var provider = DataProvider.Instance(); + foreach (var roleGroupItem in roleGroupItems) + { + provider.UpdateRecordChangers("RoleGroups", "RoleGroupID", + roleGroupItem.RoleGroupId, roleGroupItem.CreatedBy, roleGroupItem.ModifiedBy); + } + } + + private static void RefreshRecordsUserIds(IEnumerable roleItems) + { + var provider = DataProvider.Instance(); + foreach (var roleItem in roleItems) + { + provider.UpdateRecordChangers("Roles", "RoleID", + roleItem.RoleId, roleItem.CreatedBy, roleItem.ModifiedBy); + } } private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, @@ -150,7 +220,11 @@ private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, var localRoleGroups = CBO.FillCollection(DataProvider.Instance().GetAllRoleGroups(portalId, DateUtils.GetDatabaseUtcTime().AddYears(1), null)); foreach (var other in otherRoleGroups) { - if (CheckCancelled(importJob)) return; + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, other.CreatedByUserID, other.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, other.LastModifiedByUserID, other.LastModifiedByUserName); var local = localRoleGroups.FirstOrDefault(t => t.RoleGroupName == other.RoleGroupName); @@ -161,7 +235,7 @@ private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, switch (importDto.CollisionResolution) { case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored role group", other.RoleGroupName); + this.Result.AddLogEntry("Ignored role group", other.RoleGroupName); break; case CollisionResolution.Overwrite: var roleGroup = new RoleGroupInfo(local.RoleGroupID, portalId, false) @@ -172,7 +246,7 @@ private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, RoleController.UpdateRoleGroup(roleGroup, false); changedGroups.Add(new RoleGroupItem(roleGroup.RoleGroupID, createdBy, modifiedBy)); DataCache.ClearCache(string.Format(DataCache.RoleGroupsCacheKey, local.RoleGroupID)); - Result.AddLogEntry("Updated role group", other.RoleGroupName); + this.Result.AddLogEntry("Updated role group", other.RoleGroupName); break; default: throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); @@ -188,11 +262,14 @@ private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, }; other.LocalId = RoleController.AddRoleGroup(roleGroup); changedGroups.Add(new RoleGroupItem(roleGroup.RoleGroupID, createdBy, modifiedBy)); - Result.AddLogEntry("Added role group", other.RoleGroupName); + this.Result.AddLogEntry("Added role group", other.RoleGroupName); } } - if (changedGroups.Count > 0) - RefreshRecordsUserIds(changedGroups); + + if (changedGroups.Count > 0) + { + RefreshRecordsUserIds(changedGroups); + } } private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, @@ -202,7 +279,11 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, var portalId = importJob.PortalId; foreach (var other in otherRoles) { - if (CheckCancelled(importJob)) return; + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, other.CreatedByUserID, other.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, other.LastModifiedByUserID, other.LastModifiedByUserName); var localRoleInfo = RoleController.Instance.GetRoleByName(portalId, other.RoleName); @@ -212,7 +293,7 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, switch (importDto.CollisionResolution) { case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored role", other.RoleName); + this.Result.AddLogEntry("Ignored role", other.RoleName); break; case CollisionResolution.Overwrite: var group = other.RoleGroupID.HasValue @@ -220,11 +301,11 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, : null; localRoleInfo.RoleName = other.RoleName; - localRoleInfo.AutoAssignment = false; //other.AutoAssignment; CP: said do not do this + localRoleInfo.AutoAssignment = false; // other.AutoAssignment; CP: said do not do this localRoleInfo.BillingFrequency = other.BillingFrequency; localRoleInfo.BillingPeriod = other.BillingPeriod ?? 0; localRoleInfo.Description = other.Description; - localRoleInfo.IconFile = other.IconFile; //TODO: map to local file + localRoleInfo.IconFile = other.IconFile; // TODO: map to local file localRoleInfo.IsPublic = other.IsPublic; localRoleInfo.IsSystemRole = other.IsSystemRole; localRoleInfo.RoleGroupID = group?.LocalId ?? Null.NullInteger; @@ -240,11 +321,13 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, roleItems.Add(new RoleItem(localRoleInfo.RoleID, createdBy, modifiedBy)); // do not assign existing users to the roles automatically - if (other.AutoAssignment) - DataProvider.Instance().SetRoleAutoAssign(localRoleInfo.RoleID); - + if (other.AutoAssignment) + { + DataProvider.Instance().SetRoleAutoAssign(localRoleInfo.RoleID); + } + RoleController.Instance.ClearRoleCache(localRoleInfo.RoleID); - Result.AddLogEntry("Updated role", other.RoleName); + this.Result.AddLogEntry("Updated role", other.RoleName); break; default: throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); @@ -265,7 +348,7 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, BillingFrequency = other.BillingFrequency, BillingPeriod = other.BillingPeriod ?? 0, Description = other.Description, - IconFile = other.IconFile, //TODO: map to local file + IconFile = other.IconFile, // TODO: map to local file IsPublic = other.IsPublic, IsSystemRole = other.IsSystemRole, RoleGroupID = group?.LocalId ?? Null.NullInteger, @@ -281,13 +364,15 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, other.LocalId = RoleController.Instance.AddRole(roleInfo, false); roleItems.Add(new RoleItem(roleInfo.RoleID, createdBy, modifiedBy)); RoleController.Instance.ClearRoleCache(roleInfo.RoleID); - Result.AddLogEntry("Added role", other.RoleName); + this.Result.AddLogEntry("Added role", other.RoleName); } } - //set created/updated for any added/modified item - if (roleItems.Count > 0) - RefreshRecordsUserIds(roleItems); + // set created/updated for any added/modified item + if (roleItems.Count > 0) + { + RefreshRecordsUserIds(roleItems); + } } private void ProcessRoleSettings(ExportImportJob importJob, ImportDto importDto, @@ -297,18 +382,29 @@ private void ProcessRoleSettings(ExportImportJob importJob, ImportDto importDto, var portalId = importJob.PortalId; foreach (var other in otherRoleSettings) { - if (CheckCancelled(importJob)) return; + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, other.CreatedByUserID, other.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, other.LastModifiedByUserID, other.LastModifiedByUserName); var otherRole = otherRoles.FirstOrDefault(r => r.RoleID == other.RoleID); - if (otherRole == null || !otherRole.LocalId.HasValue) continue; + if (otherRole == null || !otherRole.LocalId.HasValue) + { + continue; + } + var localRoleInfo = RoleController.Instance.GetRoleById(portalId, otherRole.LocalId.Value); - if (localRoleInfo == null) continue; - + if (localRoleInfo == null) + { + continue; + } + switch (importDto.CollisionResolution) { case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored role setting", other.SettingName); + this.Result.AddLogEntry("Ignored role setting", other.SettingName); break; case CollisionResolution.Overwrite: string settingValue; @@ -318,46 +414,29 @@ private void ProcessRoleSettings(ExportImportJob importJob, ImportDto importDto, changedSettings.Add(new SettingItem(localRoleInfo.RoleID, other.SettingName, createdBy, modifiedBy)); localRoleInfo.Settings[other.SettingName] = other.SettingValue; RoleController.Instance.UpdateRoleSettings(localRoleInfo, false); - Result.AddLogEntry("Updated role setting", other.SettingName); - //No need to clear cache as the caller will do it one time at end + this.Result.AddLogEntry("Updated role setting", other.SettingName); + + // No need to clear cache as the caller will do it one time at end } else { - Result.AddLogEntry("Ignored role setting", other.SettingName); + this.Result.AddLogEntry("Ignored role setting", other.SettingName); } + break; default: throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } - } - if (changedSettings.Count > 0) - RefreshRecordsUserIds(changedSettings); - + if (changedSettings.Count > 0) + { + RefreshRecordsUserIds(changedSettings); + } + RoleController.Instance.ClearRoleCache(importJob.PortalId); } - private static void RefreshRecordsUserIds(IEnumerable roleGroupItems) - { - var provider = DataProvider.Instance(); - foreach (var roleGroupItem in roleGroupItems) - { - provider.UpdateRecordChangers("RoleGroups", "RoleGroupID", - roleGroupItem.RoleGroupId, roleGroupItem.CreatedBy, roleGroupItem.ModifiedBy); - } - } - - private static void RefreshRecordsUserIds(IEnumerable roleItems) - { - var provider = DataProvider.Instance(); - foreach (var roleItem in roleItems) - { - provider.UpdateRecordChangers("Roles", "RoleID", - roleItem.RoleId, roleItem.CreatedBy, roleItem.ModifiedBy); - } - } - private static void RefreshRecordsUserIds(IEnumerable settingItems) { var provider = DataProvider.Instance(); @@ -370,46 +449,53 @@ private static void RefreshRecordsUserIds(IEnumerable settingItems) private struct RoleGroupItem { - public int RoleGroupId { get; } - public int CreatedBy { get; } - public int ModifiedBy { get; } - public RoleGroupItem(int roleGroupId, int createdBy, int modifiedBy) { - RoleGroupId = roleGroupId; - CreatedBy = createdBy; - ModifiedBy = modifiedBy; + this.RoleGroupId = roleGroupId; + this.CreatedBy = createdBy; + this.ModifiedBy = modifiedBy; } + + public int RoleGroupId { get; } + + public int CreatedBy { get; } + + public int ModifiedBy { get; } } private struct RoleItem { - public int RoleId { get; } - public int CreatedBy { get; } - public int ModifiedBy { get; } - public RoleItem(int roleId, int createdBy, int modifiedBy) { - RoleId = roleId; - CreatedBy = createdBy; - ModifiedBy = modifiedBy; + this.RoleId = roleId; + this.CreatedBy = createdBy; + this.ModifiedBy = modifiedBy; } + + public int RoleId { get; } + + public int CreatedBy { get; } + + public int ModifiedBy { get; } } private struct SettingItem { + public SettingItem(int roleId, string settingName, int createdBy, int modifiedBy) + { + this.RoleId = roleId; + this.Name = settingName; + this.CreatedBy = createdBy; + this.ModifiedBy = modifiedBy; + } + public int RoleId { get; } + public string Name { get; } + public int CreatedBy { get; } + public int ModifiedBy { get; } - - public SettingItem(int roleId, string settingName, int createdBy, int modifiedBy) - { - RoleId = roleId; - Name = settingName; - CreatedBy = createdBy; - ModifiedBy = modifiedBy; - } } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs index c68bbcf0c66..a80fbda0fec 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Common; -using Dnn.ExportImport.Components.Common; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Dnn.ExportImport.Dto.Pages; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.UI.Skins; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.Pages; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.UI.Skins; + public class ThemesExportService : BasePortableService { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ThemesExportService)); @@ -34,15 +35,21 @@ public class ThemesExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (CheckCancelled(exportJob)) return; - //Skip the export if all the folders have been processed already. - if (CheckPoint.Stage >= 1) - return; - - _exportImportJob = exportJob; - _portalSettings = new PortalSettings(exportJob.PortalId); - - //Create Zip File to hold files + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + + this._exportImportJob = exportJob; + this._portalSettings = new PortalSettings(exportJob.PortalId); + + // Create Zip File to hold files var currentIndex = 0; var totalThemesExported = 0; try @@ -50,21 +57,24 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var packagesZipFileFormat = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\\{Constants.ExportZipThemes}"; var packagesZipFile = string.Format(packagesZipFileFormat, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { - //export skin packages. - var exportThemes = GetExportThemes(); + // export skin packages. + var exportThemes = this.GetExportThemes(); var totalThemes = exportThemes.Count; - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalThemes : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalThemes : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + using (var archive = CompressionUtil.OpenCreate(packagesZipFile)) { foreach (var theme in exportThemes) { - var filePath = SkinController.FormatSkinSrc(theme, _portalSettings); + var filePath = SkinController.FormatSkinSrc(theme, this._portalSettings); var physicalPath = Path.Combine(Globals.ApplicationMapPath, filePath.TrimStart('/')); if (Directory.Exists(physicalPath)) { @@ -73,51 +83,65 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var folderOffset = Path.Combine(Globals.ApplicationMapPath, "Portals").Length + 1; CompressionUtil.AddFileToArchive(archive, file, folderOffset); } + totalThemesExported += 1; } - CheckPoint.ProcessedItems++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalThemes; + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalThemes; currentIndex++; - //After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && CheckPointStageCallback(this)) return; + + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } } - CheckPoint.Stage++; - CheckPoint.Completed = true; - CheckPoint.Progress = 100; + this.CheckPoint.Stage++; + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; } } finally { - CheckPointStageCallback(this); - Result.AddSummary("Exported Themes", totalThemesExported.ToString()); + this.CheckPointStageCallback(this); + this.Result.AddSummary("Exported Themes", totalThemesExported.ToString()); } } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckCancelled(importJob)) return; - //Skip the export if all the templates have been processed already. - if (CheckPoint.Stage >= 1 || CheckPoint.Completed) - return; - - _exportImportJob = importJob; - - var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{_exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipThemes}"; + if (this.CheckCancelled(importJob)) + { + return; + } + + // Skip the export if all the templates have been processed already. + if (this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed) + { + return; + } + + this._exportImportJob = importJob; + + var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{this._exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipThemes}"; var tempFolder = $"{Path.GetDirectoryName(packageZipFile)}\\{DateTime.Now.Ticks}"; if (File.Exists(packageZipFile)) { CompressionUtil.UnZipArchive(packageZipFile, tempFolder); var exporeFiles = Directory.Exists(tempFolder) ? Directory.GetFiles(tempFolder, "*.*", SearchOption.AllDirectories) : new string[0]; var portalSettings = new PortalSettings(importDto.PortalId); - _importCount = exporeFiles.Length; - - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? exporeFiles.Length : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; - - if (CheckPoint.Stage == 0) + this._importCount = exporeFiles.Length; + + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? exporeFiles.Length : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + + if (this.CheckPoint.Stage == 0) { try { @@ -128,8 +152,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var checkFolder = file.Replace(tempFolder + "\\", string.Empty).Split('\\')[0]; var relativePath = file.Substring((tempFolder + "\\" + checkFolder + "\\").Length); string targetPath; - - + if (checkFolder == "_default") { targetPath = Path.Combine(Globals.HostMapPath, relativePath); @@ -155,62 +178,63 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) File.Copy(file, targetPath, true); } - Result.AddLogEntry("Import Theme File completed", targetPath); - CheckPoint.ProcessedItems++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / exporeFiles.Length; - CheckPointStageCallback(this); // just to update the counts without exit logic + this.Result.AddLogEntry("Import Theme File completed", targetPath); + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / exporeFiles.Length; + this.CheckPointStageCallback(this); // just to update the counts without exit logic } catch (Exception ex) { - Result.AddLogEntry("Import Theme error", file); + this.Result.AddLogEntry("Import Theme error", file); Logger.Error(ex); } } - CheckPoint.Stage++; - CheckPoint.Completed = true; + + this.CheckPoint.Stage++; + this.CheckPoint.Completed = true; } finally { - CheckPointStageCallback(this); + this.CheckPointStageCallback(this); FileSystemUtils.DeleteFolderRecursive(tempFolder); } } } else { - CheckPoint.Completed = true; - CheckPointStageCallback(this); - Result.AddLogEntry("ThemesFileNotFound", "Themes file not found. Skipping themes import", ReportLevel.Warn); + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); + this.Result.AddLogEntry("ThemesFileNotFound", "Themes file not found. Skipping themes import", ReportLevel.Warn); } } public override int GetImportTotal() { - return _importCount; + return this._importCount; } private IList GetExportThemes() { var exportThemes = new List(); - //get site level themes - exportThemes.Add(_portalSettings.DefaultPortalSkin); - exportThemes.Add(_portalSettings.DefaultPortalContainer); + // get site level themes + exportThemes.Add(this._portalSettings.DefaultPortalSkin); + exportThemes.Add(this._portalSettings.DefaultPortalContainer); - if (!exportThemes.Contains(_portalSettings.DefaultAdminSkin)) + if (!exportThemes.Contains(this._portalSettings.DefaultAdminSkin)) { - exportThemes.Add(_portalSettings.DefaultAdminSkin); + exportThemes.Add(this._portalSettings.DefaultAdminSkin); } - if (!exportThemes.Contains(_portalSettings.DefaultAdminContainer)) + if (!exportThemes.Contains(this._portalSettings.DefaultAdminContainer)) { - exportThemes.Add(_portalSettings.DefaultAdminContainer); + exportThemes.Add(this._portalSettings.DefaultAdminContainer); } - exportThemes.AddRange(LoadExportThemesForPages()); - exportThemes.AddRange(LoadExportContainersForModules()); + exportThemes.AddRange(this.LoadExportThemesForPages()); + exportThemes.AddRange(this.LoadExportContainersForModules()); - //get the theme packages + // get the theme packages var themePackages = new List(); foreach (var theme in exportThemes) { @@ -228,7 +252,7 @@ private IList LoadExportThemesForPages() { var exportThemes = new List(); - foreach (var exportTab in Repository.GetAllItems()) + foreach (var exportTab in this.Repository.GetAllItems()) { if (!string.IsNullOrEmpty(exportTab.SkinSrc) && !exportThemes.Contains(exportTab.SkinSrc)) { @@ -248,7 +272,7 @@ private IList LoadExportContainersForModules() { var exportThemes = new List(); - foreach (var module in Repository.GetAllItems()) + foreach (var module in this.Repository.GetAllItems()) { if (!string.IsNullOrEmpty(module.ContainerSrc) && !exportThemes.Contains(module.ContainerSrc)) { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs index d957e3863d5..b7bd39f93a6 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs @@ -1,28 +1,56 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Dto.Assets; -using Dnn.ExportImport.Dto.Users; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.Assets; + using Dnn.ExportImport.Dto.Users; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + /// /// Supplementary service to import users additional data. /// public class UsersDataExportService : BasePortableService { + private static readonly Tuple[] UserRolesDatasetColumns = + { + new Tuple("PortalId", typeof(int)), + new Tuple("UserId", typeof(int)), + new Tuple("RoleId", typeof(int)), + new Tuple("ExpiryDate", typeof(DateTime)), + new Tuple("IsTrialUsed", typeof(bool)), + new Tuple("EffectiveDate", typeof(DateTime)), + new Tuple("CreatedByUserId", typeof(int)), + new Tuple("LastModifiedByUserId", typeof(int)), + new Tuple("Status", typeof(int)), + new Tuple("IsOwner", typeof(bool)), + new Tuple("IsSuperUser", typeof(bool)), + }; + + private static readonly Tuple[] UserProfileDatasetColumns = + { + new Tuple("PortalId", typeof(int)), + new Tuple("UserId", typeof(int)), + new Tuple("PropertyDefinitionId", typeof(int)), + new Tuple("PropertyValue", typeof(string)), + new Tuple("PropertyText", typeof(string)), + new Tuple("Visibility", typeof(int)), + new Tuple("ExtendedVisibility", typeof(string)), + new Tuple("IsSuperUser", typeof(bool)), + }; + public override string Category => Constants.Category_UsersData; public override string ParentCategory => Constants.Category_Users; @@ -31,48 +59,63 @@ public class UsersDataExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - CheckPoint.Progress += 100; - CheckPoint.Completed = true; - CheckPoint.TotalItems = 0; - CheckPoint.ProcessedItems = 0; - CheckPointStageCallback(this); - //No implementation required in export users child as everything is exported in parent service. + this.CheckPoint.Progress += 100; + this.CheckPoint.Completed = true; + this.CheckPoint.TotalItems = 0; + this.CheckPoint.ProcessedItems = 0; + this.CheckPointStageCallback(this); + + // No implementation required in export users child as everything is exported in parent service. } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckCancelled(importJob)) return; - + if (this.CheckCancelled(importJob)) + { + return; + } + var pageIndex = 0; const int pageSize = Constants.DefaultPageSize; var totalUserRolesImported = 0; var totalProfilesImported = 0; var totalProcessed = 0; - var totalUsers = Repository.GetCount(); + var totalUsers = this.Repository.GetCount(); if (totalUsers == 0) { - CheckPoint.Completed = true; - CheckPointStageCallback(this); + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); return; } + var totalPages = Util.CalculateTotalPages(totalUsers, pageSize); - //Skip the import if all the users has been processed already. - if (CheckPoint.Stage >= totalPages) - return; - - pageIndex = CheckPoint.Stage; + + // Skip the import if all the users has been processed already. + if (this.CheckPoint.Stage >= totalPages) + { + return; + } + + pageIndex = this.CheckPoint.Stage; - var totalUsersToBeProcessed = totalUsers - pageIndex * pageSize; + var totalUsersToBeProcessed = totalUsers - (pageIndex * pageSize); - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalUsers : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalUsers : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + var includeProfile = importDto.ExportDto.IncludeProperfileProperties; try { - Repository.RebuildIndex(x => x.ReferenceId); - if (includeProfile) - Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); + if (includeProfile) + { + this.Repository.RebuildIndex(x => x.ReferenceId); + } + var portalId = importJob.PortalId; using (var tableUserProfile = new DataTable("UserProfile")) using (var tableUserRoles = new DataTable("UserRoles")) @@ -83,25 +126,41 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var dataProvider = DotNetNuke.Data.DataProvider.Instance(); while (totalProcessed < totalUsersToBeProcessed) { - if (CheckCancelled(importJob)) return; - var users = Repository.GetAllItems(null, true, pageIndex * pageSize, pageSize).ToList(); + if (this.CheckCancelled(importJob)) + { + return; + } + + var users = this.Repository.GetAllItems(null, true, pageIndex * pageSize, pageSize).ToList(); var tempUserRolesCount = 0; var tempUserProfileCount = 0; try { foreach (var user in users) { - if (CheckCancelled(importJob)) return; - //Find the correct userId from the system which was added/updated by UserExportService. + if (this.CheckCancelled(importJob)) + { + return; + } + + // Find the correct userId from the system which was added/updated by UserExportService. var userId = UserController.GetUserByName(user.Username)?.UserID; if (userId != null) { - var userRoles = Repository.GetRelatedItems(user.Id).ToList(); + var userRoles = this.Repository.GetRelatedItems(user.Id).ToList(); foreach (var userRole in userRoles) { var roleId = Util.GetRoleIdByName(importJob.PortalId, userRole.RoleId, userRole.RoleName); - if (roleId == null) continue; - if (!(roleId > Convert.ToInt32(Globals.glbRoleNothing))) continue; + if (roleId == null) + { + continue; + } + + if (!(roleId > Convert.ToInt32(Globals.glbRoleNothing))) + { + continue; + } + var userRoleRow = tableUserRoles.NewRow(); userRoleRow["PortalId"] = portalId; userRoleRow["UserId"] = userId; @@ -117,17 +176,23 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) tableUserRoles.Rows.Add(userRoleRow); tempUserRolesCount++; } + if (includeProfile) { var userProfiles = - Repository.GetRelatedItems(user.Id).ToList(); + this.Repository.GetRelatedItems(user.Id).ToList(); foreach (var userProfile in userProfiles) { - var profileDefinitionId = Util.GetProfilePropertyId(importJob.PortalId, + var profileDefinitionId = Util.GetProfilePropertyId( + importJob.PortalId, userProfile.PropertyDefinitionId, userProfile.PropertyName); - if (profileDefinitionId == null || profileDefinitionId == -1) continue; + if (profileDefinitionId == null || profileDefinitionId == -1) + { + continue; + } + var value = userProfile.PropertyValue; - if (userProfile.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) && (value = GetUserPhotoId(portalId, value, user)) == null) + if (userProfile.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) && (value = this.GetUserPhotoId(portalId, value, user)) == null) { continue; } @@ -147,8 +212,10 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } } + var overwrite = importDto.CollisionResolution == CollisionResolution.Overwrite; - //Bulk insert the data in DB + + // Bulk insert the data in DB DotNetNuke.Data.DataProvider.Instance() .BulkInsert("ExportImport_AddUpdateUserRolesBulk", "@DataTable", tableUserRoles, new Dictionary { { "Overwrite", overwrite } }); totalUserRolesImported += tempUserRolesCount; @@ -161,55 +228,77 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) totalProfilesImported += tempUserProfileCount; } - CheckPoint.ProcessedItems += users.Count; + this.CheckPoint.ProcessedItems += users.Count; totalProcessed += users.Count; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalUsers; - CheckPoint.StageData = null; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; + this.CheckPoint.StageData = null; } catch (Exception ex) { - Result.AddLogEntry($"Importing Users Data from {pageIndex * pageSize} to {pageIndex * pageSize + pageSize} exception", ex.Message, ReportLevel.Error); + this.Result.AddLogEntry($"Importing Users Data from {pageIndex * pageSize} to {(pageIndex * pageSize) + pageSize} exception", ex.Message, ReportLevel.Error); } + tableUserRoles.Rows.Clear(); tableUserProfile.Rows.Clear(); pageIndex++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalUsers; - CheckPoint.Stage++; - CheckPoint.StageData = null; - if (CheckPointStageCallback(this)) return; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + if (this.CheckPointStageCallback(this)) + { + return; + } } } - CheckPoint.Completed = true; - CheckPoint.Progress = 100; + + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; } finally { - CheckPointStageCallback(this); - Result.AddSummary("Imported User Roles", totalUserRolesImported.ToString()); + this.CheckPointStageCallback(this); + this.Result.AddSummary("Imported User Roles", totalUserRolesImported.ToString()); if (includeProfile) { - Result.AddSummary("Imported User Profiles", totalProfilesImported.ToString()); + this.Result.AddSummary("Imported User Profiles", totalProfilesImported.ToString()); } } } + public override int GetImportTotal() + { + return this.Repository.GetCount(); + } + private string GetUserPhotoId(int portalId, string importFileId, ExportUser user) { int profilePictureId; if (string.IsNullOrEmpty(importFileId) || - !int.TryParse(importFileId, out profilePictureId)) return null; + !int.TryParse(importFileId, out profilePictureId)) + { + return null; + } + var files = FolderManager.Instance.GetFiles( FolderManager.Instance.GetUserFolder( UserController.GetUserByName(portalId, user.Username))) .ToList(); - if (!files.Any()) return null; + if (!files.Any()) + { + return null; + } + var importUserFolder = - Repository.GetItem(x => x.UserId == user.UserId); - if (importUserFolder == null) return null; + this.Repository.GetItem(x => x.UserId == user.UserId); + if (importUserFolder == null) + { + return null; + } + { var profilePicture = - Repository.GetRelatedItems(importUserFolder.Id) + this.Repository.GetRelatedItems(importUserFolder.Id) .FirstOrDefault(x => x.FileId == profilePictureId); if (profilePicture != null && files.Any(x => x.FileName == profilePicture.FileName)) @@ -220,39 +309,8 @@ private string GetUserPhotoId(int portalId, string importFileId, ExportUser user .FileId); } } + return null; } - - public override int GetImportTotal() - { - return Repository.GetCount(); - } - - private static readonly Tuple[] UserRolesDatasetColumns = - { - new Tuple("PortalId", typeof (int)), - new Tuple("UserId", typeof (int)), - new Tuple("RoleId", typeof (int)), - new Tuple("ExpiryDate", typeof (DateTime)), - new Tuple("IsTrialUsed", typeof (bool)), - new Tuple("EffectiveDate", typeof (DateTime)), - new Tuple("CreatedByUserId", typeof (int)), - new Tuple("LastModifiedByUserId", typeof (int)), - new Tuple("Status", typeof (int)), - new Tuple("IsOwner", typeof (bool)), - new Tuple("IsSuperUser", typeof (bool)), - }; - - private static readonly Tuple[] UserProfileDatasetColumns = - { - new Tuple("PortalId", typeof (int)), - new Tuple("UserId", typeof (int)), - new Tuple("PropertyDefinitionId", typeof (int)), - new Tuple("PropertyValue", typeof (string)), - new Tuple("PropertyText", typeof (string)), - new Tuple("Visibility", typeof (int)), - new Tuple("ExtendedVisibility", typeof (string)), - new Tuple("IsSuperUser", typeof (bool)) - }; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs index 0a4b09a7e64..0c04c532b5a 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs @@ -1,26 +1,67 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using DotNetNuke.Common.Utilities; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Dto.Users; -using DotNetNuke.Data.PetaPoco; -using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Dto.Users; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data.PetaPoco; + + using DataProvider = Dnn.ExportImport.Components.Providers.DataProvider; + /// /// Service to export/import users. /// public class UsersExportService : BasePortableService { + private static readonly Tuple[] UsersDatasetColumns = + { + new Tuple("PortalId", typeof(int)), + new Tuple("Username", typeof(string)), + new Tuple("FirstName", typeof(string)), + new Tuple("LastName", typeof(string)), + new Tuple("AffiliateId", typeof(int)), + new Tuple("IsSuperUser", typeof(bool)), + new Tuple("Email", typeof(string)), + new Tuple("DisplayName", typeof(string)), + new Tuple("UpdatePassword", typeof(bool)), + new Tuple("Authorised", typeof(bool)), + new Tuple("CreatedByUserID", typeof(int)), + new Tuple("VanityUrl", typeof(string)), + new Tuple("RefreshRoles", typeof(bool)), + new Tuple("LastIPAddress", typeof(string)), + new Tuple("PasswordResetToken", typeof(Guid)), + new Tuple("PasswordResetExpiration", typeof(DateTime)), + new Tuple("IsDeleted", typeof(bool)), + new Tuple("LastModifiedByUserID", typeof(int)), + new Tuple("ApplicationId", typeof(Guid)), + new Tuple("AspUserId", typeof(Guid)), + new Tuple("MobileAlias", typeof(string)), + new Tuple("IsAnonymous", typeof(bool)), + new Tuple("Password", typeof(string)), + new Tuple("PasswordFormat", typeof(int)), + new Tuple("PasswordSalt", typeof(string)), + new Tuple("MobilePIN", typeof(string)), + new Tuple("PasswordQuestion", typeof(string)), + new Tuple("PasswordAnswer", typeof(string)), + new Tuple("IsApproved", typeof(bool)), + new Tuple("IsLockedOut", typeof(bool)), + new Tuple("FailedPasswordAttemptCount", typeof(int)), + new Tuple("FailedPasswordAnswerAttemptCount", typeof(int)), + new Tuple("Comment", typeof(string)), + new Tuple("AuthenticationType", typeof(string)), + new Tuple("AuthenticationToken", typeof(string)), + }; + public override string Category => Constants.Category_Users; public override string ParentCategory => null; @@ -29,7 +70,11 @@ public class UsersExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (CheckCancelled(exportJob)) return; + if (this.CheckCancelled(exportJob)) + { + return; + } + var fromDateUtc = exportDto.FromDateUtc; var toDateUtc = exportDto.ToDateUtc; @@ -46,31 +91,43 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var totalUsers = DataProvider.Instance().GetUsersCount(portalId, exportDto.IncludeDeletions, toDateUtc, fromDateUtc); if (totalUsers == 0) { - CheckPoint.Completed = true; - CheckPointStageCallback(this); + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); return; } + var totalPages = Util.CalculateTotalPages(totalUsers, pageSize); - //Skip the export if all the users has been processed already. - if (CheckPoint.Stage >= totalPages) - return; - - //Check if there is any pending stage or partially processed data. - if (CheckPoint.Stage > 0) + // Skip the export if all the users has been processed already. + if (this.CheckPoint.Stage >= totalPages) + { + return; + } + + // Check if there is any pending stage or partially processed data. + if (this.CheckPoint.Stage > 0) { - pageIndex = CheckPoint.Stage; + pageIndex = this.CheckPoint.Stage; } - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalUsers : CheckPoint.TotalItems; - CheckPoint.ProcessedItems = CheckPoint.Stage * pageSize; - if (CheckPointStageCallback(this)) return; + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalUsers : this.CheckPoint.TotalItems; + this.CheckPoint.ProcessedItems = this.CheckPoint.Stage * pageSize; + if (this.CheckPointStageCallback(this)) + { + return; + } + var includeProfile = exportDto.IncludeProperfileProperties; try { while (pageIndex < totalPages) { - if (CheckCancelled(exportJob)) return; + if (this.CheckCancelled(exportJob)) + { + return; + } + var exportUsersList = new List(); var exportAspnetUserList = new List(); var exportAspnetMembershipList = new List(); @@ -96,6 +153,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { CBO.FillCollection(reader, exportUserProfileList, false); } + reader.NextResult(); CBO.FillCollection(reader, exportUserPortalList, false); @@ -107,7 +165,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) CBO.FillCollection(reader, exportAspnetMembershipList, true); } - Repository.CreateItems(exportUsersList, null); + this.Repository.CreateItems(exportUsersList, null); totalUsersExported += exportUsersList.Count; exportUserAuthenticationList.ForEach( @@ -115,7 +173,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { x.ReferenceId = exportUsersList.FirstOrDefault(user => user.UserId == x.UserId)?.Id; }); - Repository.CreateItems(exportUserAuthenticationList, null); + this.Repository.CreateItems(exportUserAuthenticationList, null); totalAuthenticationExported += exportUserAuthenticationList.Count; exportUserRoleList.ForEach( @@ -123,7 +181,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { x.ReferenceId = exportUsersList.FirstOrDefault(user => user.UserId == x.UserId)?.Id; }); - Repository.CreateItems(exportUserRoleList, null); + this.Repository.CreateItems(exportUserRoleList, null); totalUserRolesExported += exportUserRoleList.Count; if (includeProfile) { @@ -132,15 +190,16 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { x.ReferenceId = exportUsersList.FirstOrDefault(user => user.UserId == x.UserId)?.Id; }); - Repository.CreateItems(exportUserProfileList, null); + this.Repository.CreateItems(exportUserProfileList, null); totalProfilesExported += exportUserProfileList.Count; } + exportUserPortalList.ForEach( x => { x.ReferenceId = exportUsersList.FirstOrDefault(user => user.UserId == x.UserId)?.Id; }); - Repository.CreateItems(exportUserPortalList, null); + this.Repository.CreateItems(exportUserPortalList, null); totalPortalsExported += exportUserPortalList.Count; exportAspnetUserList.ForEach( @@ -148,7 +207,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { x.ReferenceId = exportUsersList.FirstOrDefault(user => user.Username == x.UserName)?.Id; }); - Repository.CreateItems(exportAspnetUserList, null); + this.Repository.CreateItems(exportAspnetUserList, null); totalAspnetUserExported += exportAspnetUserList.Count; exportAspnetMembershipList.ForEach( @@ -156,83 +215,105 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { x.ReferenceId = exportAspnetUserList.FirstOrDefault(user => user.UserId == x.UserId)?.Id; }); - Repository.CreateItems(exportAspnetMembershipList, null); + this.Repository.CreateItems(exportAspnetMembershipList, null); totalAspnetMembershipExported += exportAspnetMembershipList.Count; - CheckPoint.ProcessedItems += exportUsersList.Count; + this.CheckPoint.ProcessedItems += exportUsersList.Count; } catch (Exception ex) { - Result.AddLogEntry($"Exporting Users from {pageIndex * pageSize} to {pageIndex * pageSize + pageSize} exception", ex.Message, ReportLevel.Error); + this.Result.AddLogEntry($"Exporting Users from {pageIndex * pageSize} to {(pageIndex * pageSize) + pageSize} exception", ex.Message, ReportLevel.Error); } - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalUsers; - CheckPoint.Stage++; - if (CheckPointStageCallback(this)) return; - //Rebuild the indexes in the exported database. - Repository.RebuildIndex(x => x.Id, true); - Repository.RebuildIndex(x => x.ReferenceId); - Repository.RebuildIndex(x => x.ReferenceId); - Repository.RebuildIndex(x => x.ReferenceId); - Repository.RebuildIndex(x => x.ReferenceId); - Repository.RebuildIndex(x => x.ReferenceId); - if (includeProfile) - Repository.RebuildIndex(x => x.ReferenceId); + + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; + this.CheckPoint.Stage++; + if (this.CheckPointStageCallback(this)) + { + return; + } + + // Rebuild the indexes in the exported database. + this.Repository.RebuildIndex(x => x.Id, true); + this.Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); + if (includeProfile) + { + this.Repository.RebuildIndex(x => x.ReferenceId); + } + pageIndex++; } - CheckPoint.Completed = true; - CheckPoint.Progress = 100; + + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; } finally { - CheckPointStageCallback(this); - Result.AddSummary("Exported Users", totalUsersExported.ToString()); - Result.AddSummary("Exported User Portals", totalPortalsExported.ToString()); - Result.AddSummary("Exported User Roles", totalUserRolesExported.ToString()); + this.CheckPointStageCallback(this); + this.Result.AddSummary("Exported Users", totalUsersExported.ToString()); + this.Result.AddSummary("Exported User Portals", totalPortalsExported.ToString()); + this.Result.AddSummary("Exported User Roles", totalUserRolesExported.ToString()); if (includeProfile) { - Result.AddSummary("Exported User Profiles", totalProfilesExported.ToString()); + this.Result.AddSummary("Exported User Profiles", totalProfilesExported.ToString()); } - Result.AddSummary("Exported User Authentication", totalAuthenticationExported.ToString()); - Result.AddSummary("Exported Aspnet User", totalAspnetUserExported.ToString()); - Result.AddSummary("Exported Aspnet Membership", totalAspnetMembershipExported.ToString()); + + this.Result.AddSummary("Exported User Authentication", totalAuthenticationExported.ToString()); + this.Result.AddSummary("Exported Aspnet User", totalAspnetUserExported.ToString()); + this.Result.AddSummary("Exported Aspnet Membership", totalAspnetMembershipExported.ToString()); } } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckCancelled(importJob)) return; - + if (this.CheckCancelled(importJob)) + { + return; + } + const int pageSize = Constants.DefaultPageSize; var totalUsersImported = 0; var totalPortalsImported = 0; var totalAspnetUserImported = 0; var totalAspnetMembershipImported = 0; var totalUserAuthenticationCount = 0; - var totalUsers = Repository.GetCount(); + var totalUsers = this.Repository.GetCount(); if (totalUsers == 0) { - CheckPoint.Completed = true; - CheckPointStageCallback(this); + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); return; } + var totalPages = Util.CalculateTotalPages(totalUsers, pageSize); - //Skip the import if all the users has been processed already. - if (CheckPoint.Stage >= totalPages) - return; - - var pageIndex = CheckPoint.Stage; + + // Skip the import if all the users has been processed already. + if (this.CheckPoint.Stage >= totalPages) + { + return; + } + + var pageIndex = this.CheckPoint.Stage; - var totalUsersToBeProcessed = totalUsers - pageIndex * pageSize; - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? totalUsers : CheckPoint.TotalItems; - if (CheckPointStageCallback(this)) return; + var totalUsersToBeProcessed = totalUsers - (pageIndex * pageSize); + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalUsers : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + try { - Repository.RebuildIndex(x => x.Id, true); - Repository.RebuildIndex(x => x.ReferenceId); - Repository.RebuildIndex(x => x.ReferenceId); - Repository.RebuildIndex(x => x.ReferenceId); - Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.Id, true); + this.Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); + this.Repository.RebuildIndex(x => x.ReferenceId); var portalId = importJob.PortalId; var dataProvider = DotNetNuke.Data.DataProvider.Instance(); using (var table = new DataTable("Users")) @@ -242,9 +323,13 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) UsersDatasetColumns.Select(column => new DataColumn(column.Item1, column.Item2)).ToArray()); while (totalUsersImported < totalUsersToBeProcessed) { - if (CheckCancelled(importJob)) return; + if (this.CheckCancelled(importJob)) + { + return; + } + var users = - Repository.GetAllItems(null, true, pageIndex * pageSize, pageSize).ToList(); + this.Repository.GetAllItems(null, true, pageIndex * pageSize, pageSize).ToList(); var tempAspUserCount = 0; var tempAspMembershipCount = 0; var tempUserPortalCount = 0; @@ -253,15 +338,20 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { foreach (var user in users) { - if (CheckCancelled(importJob)) return; + if (this.CheckCancelled(importJob)) + { + return; + } + var row = table.NewRow(); - var userPortal = Repository.GetRelatedItems(user.Id).FirstOrDefault(); - var userAuthentication = Repository.GetRelatedItems(user.Id).FirstOrDefault(); - //Aspnet Users and Membership - var aspNetUser = Repository.GetRelatedItems(user.Id).FirstOrDefault(); + var userPortal = this.Repository.GetRelatedItems(user.Id).FirstOrDefault(); + var userAuthentication = this.Repository.GetRelatedItems(user.Id).FirstOrDefault(); + + // Aspnet Users and Membership + var aspNetUser = this.Repository.GetRelatedItems(user.Id).FirstOrDefault(); var aspnetMembership = aspNetUser != null - ? Repository.GetRelatedItems(aspNetUser.Id).FirstOrDefault() + ? this.Repository.GetRelatedItems(aspNetUser.Id).FirstOrDefault() : null; row["PortalId"] = portalId; @@ -294,6 +384,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) row["RefreshRoles"] = DBNull.Value; row["IsDeleted"] = DBNull.Value; } + if (userAuthentication != null) { tempUserAuthenticationCount += 1; @@ -309,7 +400,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) if (aspNetUser != null) { tempAspUserCount += 1; - row["ApplicationId"] = GetApplicationId(); + row["ApplicationId"] = this.GetApplicationId(); row["AspUserId"] = aspNetUser.UserId; row["MobileAlias"] = aspNetUser.MobileAlias; row["IsAnonymous"] = aspNetUser.IsAnonymous; @@ -350,8 +441,10 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) table.Rows.Add(row); } + var overwrite = importDto.CollisionResolution == CollisionResolution.Overwrite; - //Bulk insert the data in DB + + // Bulk insert the data in DB DotNetNuke.Data.DataProvider.Instance() .BulkInsert("ExportImport_AddUpdateUsersBulk", "@DataTable", table, new Dictionary { { "Overwrite", overwrite } }); totalUsersImported += users.Count; @@ -359,87 +452,55 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) totalAspnetMembershipImported += tempAspMembershipCount; totalPortalsImported += tempUserPortalCount; totalUserAuthenticationCount += tempUserAuthenticationCount; - CheckPoint.ProcessedItems += users.Count; + this.CheckPoint.ProcessedItems += users.Count; } catch (Exception ex) { - Result.AddLogEntry($"Importing Users from {pageIndex * pageSize} to {pageIndex * pageSize + pageSize} exception", ex.Message, ReportLevel.Error); + this.Result.AddLogEntry($"Importing Users from {pageIndex * pageSize} to {(pageIndex * pageSize) + pageSize} exception", ex.Message, ReportLevel.Error); } + table.Rows.Clear(); pageIndex++; - CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / totalUsers; - CheckPoint.Stage++; - CheckPoint.StageData = null; - if (CheckPointStageCallback(this)) return; + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + if (this.CheckPointStageCallback(this)) + { + return; + } } } - CheckPoint.Completed = true; - CheckPoint.Progress = 100; + + this.CheckPoint.Completed = true; + this.CheckPoint.Progress = 100; } finally { - CheckPointStageCallback(this); - Result.AddSummary("Imported Users", totalUsersImported.ToString()); - Result.AddSummary("Imported User Portals", totalPortalsImported.ToString()); - Result.AddSummary("Import User Authentications", totalUserAuthenticationCount.ToString()); - Result.AddSummary("Imported Aspnet Users", totalAspnetUserImported.ToString()); - Result.AddSummary("Imported Aspnet Memberships", totalAspnetMembershipImported.ToString()); + this.CheckPointStageCallback(this); + this.Result.AddSummary("Imported Users", totalUsersImported.ToString()); + this.Result.AddSummary("Imported User Portals", totalPortalsImported.ToString()); + this.Result.AddSummary("Import User Authentications", totalUserAuthenticationCount.ToString()); + this.Result.AddSummary("Imported Aspnet Users", totalAspnetUserImported.ToString()); + this.Result.AddSummary("Imported Aspnet Memberships", totalAspnetMembershipImported.ToString()); } } public override int GetImportTotal() { - return Repository.GetCount(); + return this.Repository.GetCount(); } private Guid GetApplicationId() { using (var db = - new PetaPocoDataContext(DotNetNuke.Data.DataProvider.Instance().Settings["connectionStringName"], + new PetaPocoDataContext( + DotNetNuke.Data.DataProvider.Instance().Settings["connectionStringName"], "aspnet_")) { - return db.ExecuteScalar(CommandType.Text, + return db.ExecuteScalar( + CommandType.Text, "SELECT TOP 1 ApplicationId FROM aspnet_Applications"); } } - - private static readonly Tuple[] UsersDatasetColumns = - { - new Tuple("PortalId", typeof (int)), - new Tuple("Username", typeof (string)), - new Tuple("FirstName", typeof (string)), - new Tuple("LastName", typeof (string)), - new Tuple("AffiliateId", typeof (int)), - new Tuple("IsSuperUser", typeof (bool)), - new Tuple("Email", typeof (string)), - new Tuple("DisplayName", typeof (string)), - new Tuple("UpdatePassword", typeof (bool)), - new Tuple("Authorised", typeof (bool)), - new Tuple("CreatedByUserID", typeof (int)), - new Tuple("VanityUrl", typeof (string)), - new Tuple("RefreshRoles", typeof (bool)), - new Tuple("LastIPAddress", typeof (string)), - new Tuple("PasswordResetToken", typeof (Guid)), - new Tuple("PasswordResetExpiration", typeof (DateTime)), - new Tuple("IsDeleted", typeof (bool)), - new Tuple("LastModifiedByUserID", typeof (int)), - new Tuple("ApplicationId", typeof (Guid)), - new Tuple("AspUserId", typeof (Guid)), - new Tuple("MobileAlias", typeof (string)), - new Tuple("IsAnonymous", typeof (bool)), - new Tuple("Password", typeof (string)), - new Tuple("PasswordFormat", typeof (int)), - new Tuple("PasswordSalt", typeof (string)), - new Tuple("MobilePIN", typeof (string)), - new Tuple("PasswordQuestion", typeof (string)), - new Tuple("PasswordAnswer", typeof (string)), - new Tuple("IsApproved", typeof (bool)), - new Tuple("IsLockedOut", typeof (bool)), - new Tuple("FailedPasswordAttemptCount", typeof (int)), - new Tuple("FailedPasswordAnswerAttemptCount", typeof (int)), - new Tuple("Comment", typeof (string)), - new Tuple("AuthenticationType", typeof (string)), - new Tuple("AuthenticationToken", typeof (string)) - }; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs index e9690f77638..44f9cb0c2f6 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs @@ -1,21 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Providers; -using Dnn.ExportImport.Dto.Taxonomy; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Taxonomy; -using Util = DotNetNuke.Entities.Content.Common.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Providers; + using Dnn.ExportImport.Dto.Taxonomy; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Taxonomy; + + using Util = DotNetNuke.Entities.Content.Common.Util; + public class VocabularyService : BasePortableService { public override string Category => Constants.Category_Vocabularies; @@ -26,114 +28,148 @@ public class VocabularyService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (CheckPoint.Stage > 0) return; - if (CheckCancelled(exportJob)) return; - + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); List vocabularyTypes = null; - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage == 0) { var taxonomyTerms = GetTaxonomyTerms(exportDto.PortalId, toDate, fromDate); var taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); if (taxonomyTerms.Count > 0 || taxonomyVocabularies.Count > 0) { var scopeTypes = CBO.FillCollection(DataProvider.Instance().GetAllScopeTypes()); - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? scopeTypes.Count : CheckPoint.TotalItems; - if (CheckPoint.TotalItems == scopeTypes.Count) + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? scopeTypes.Count : this.CheckPoint.TotalItems; + if (this.CheckPoint.TotalItems == scopeTypes.Count) { vocabularyTypes = CBO.FillCollection(DataProvider.Instance().GetAllVocabularyTypes()); taxonomyTerms = GetTaxonomyTerms(exportDto.PortalId, toDate, fromDate); taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); - CheckPoint.TotalItems += taxonomyTerms.Count + taxonomyVocabularies.Count; + this.CheckPoint.TotalItems += taxonomyTerms.Count + taxonomyVocabularies.Count; } - CheckPointStageCallback(this); + + this.CheckPointStageCallback(this); - Repository.CreateItems(scopeTypes); - //Result.AddSummary("Exported Taxonomy Scopes", scopeTypes.Count.ToString()); -- not imported so don't show - //CheckPoint.ProcessedItems += scopeTypes.Count; + this.Repository.CreateItems(scopeTypes); + + // Result.AddSummary("Exported Taxonomy Scopes", scopeTypes.Count.ToString()); -- not imported so don't show + // CheckPoint.ProcessedItems += scopeTypes.Count; } - CheckPoint.Progress = 25; + + this.CheckPoint.Progress = 25; - if (taxonomyVocabularies == null) taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); + if (taxonomyVocabularies == null) + { + taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); + } + if (taxonomyTerms.Count > 0 || taxonomyVocabularies.Count > 0) { - if (vocabularyTypes == null) - vocabularyTypes = CBO.FillCollection(DataProvider.Instance().GetAllVocabularyTypes()); - Repository.CreateItems(vocabularyTypes); - //Result.AddSummary("Exported Vocabulary Types", vocabularyTypes.Count.ToString()); -- not imported so don't show - //CheckPoint.ProcessedItems += vocabularyTypes.Count; + if (vocabularyTypes == null) + { + vocabularyTypes = CBO.FillCollection(DataProvider.Instance().GetAllVocabularyTypes()); + } + + this.Repository.CreateItems(vocabularyTypes); + + // Result.AddSummary("Exported Vocabulary Types", vocabularyTypes.Count.ToString()); -- not imported so don't show + // CheckPoint.ProcessedItems += vocabularyTypes.Count; } - Repository.CreateItems(taxonomyTerms); - Result.AddSummary("Exported Vocabularies", taxonomyTerms.Count.ToString()); - CheckPoint.Progress = 75; - CheckPoint.ProcessedItems += taxonomyTerms.Count; - CheckPoint.Stage++; - if (CheckPointStageCallback(this)) return; - - if (taxonomyVocabularies == null) taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); - Repository.CreateItems(taxonomyVocabularies); - Result.AddSummary("Exported Terms", taxonomyVocabularies.Count.ToString()); - CheckPoint.Progress = 100; - CheckPoint.ProcessedItems += taxonomyVocabularies.Count; - CheckPoint.Stage++; - CheckPoint.Completed = true; - CheckPointStageCallback(this); + this.Repository.CreateItems(taxonomyTerms); + this.Result.AddSummary("Exported Vocabularies", taxonomyTerms.Count.ToString()); + this.CheckPoint.Progress = 75; + this.CheckPoint.ProcessedItems += taxonomyTerms.Count; + this.CheckPoint.Stage++; + if (this.CheckPointStageCallback(this)) + { + return; + } + + if (taxonomyVocabularies == null) + { + taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); + } + + this.Repository.CreateItems(taxonomyVocabularies); + this.Result.AddSummary("Exported Terms", taxonomyVocabularies.Count.ToString()); + this.CheckPoint.Progress = 100; + this.CheckPoint.ProcessedItems += taxonomyVocabularies.Count; + this.CheckPoint.Stage++; + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); } } - private static List GetTaxonomyTerms(int portalId, DateTime toDate, DateTime? fromDate) - { - return CBO.FillCollection(DataProvider.Instance().GetAllTerms(portalId, toDate, fromDate)); - } - - private static List GetTaxonomyVocabularies(int portalId, DateTime toDate, DateTime? fromDate) - { - return CBO.FillCollection(DataProvider.Instance().GetAllVocabularies(portalId, toDate, fromDate)); - } - public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckPoint.Stage > 0) return; - if (CheckCancelled(importJob)) return; - - //Update the total items count in the check points. This should be updated only once. - CheckPoint.TotalItems = CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? GetImportTotal() : CheckPoint.TotalItems; - if (CheckPoint.Stage == 0) + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(importJob)) + { + return; + } + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? this.GetImportTotal() : this.CheckPoint.TotalItems; + if (this.CheckPoint.Stage == 0) { - var otherScopeTypes = Repository.GetAllItems().ToList(); - //the table Taxonomy_ScopeTypes is used for lookup only and never changed/updated in the database - //CheckPoint.Progress = 10; + var otherScopeTypes = this.Repository.GetAllItems().ToList(); + + // the table Taxonomy_ScopeTypes is used for lookup only and never changed/updated in the database + // CheckPoint.Progress = 10; - //var otherVocabularyTypes = Repository.GetAllItems().ToList(); - //the table Taxonomy_VocabularyTypes is used for lookup only and never changed/updated in the database - CheckPoint.Progress = 20; + // var otherVocabularyTypes = Repository.GetAllItems().ToList(); + // the table Taxonomy_VocabularyTypes is used for lookup only and never changed/updated in the database + this.CheckPoint.Progress = 20; - var otherVocabularies = Repository.GetAllItems().ToList(); - ProcessVocabularies(importJob, importDto, otherScopeTypes, otherVocabularies); - Repository.UpdateItems(otherVocabularies); - Result.AddSummary("Imported Vocabularies", otherVocabularies.Count.ToString()); - CheckPoint.Progress = 60; - CheckPoint.ProcessedItems += otherVocabularies.Count; + var otherVocabularies = this.Repository.GetAllItems().ToList(); + this.ProcessVocabularies(importJob, importDto, otherScopeTypes, otherVocabularies); + this.Repository.UpdateItems(otherVocabularies); + this.Result.AddSummary("Imported Vocabularies", otherVocabularies.Count.ToString()); + this.CheckPoint.Progress = 60; + this.CheckPoint.ProcessedItems += otherVocabularies.Count; - var otherTaxonomyTerms = Repository.GetAllItems().ToList(); - ProcessTaxonomyTerms(importJob, importDto, otherVocabularies, otherTaxonomyTerms); - Repository.UpdateItems(otherTaxonomyTerms); - Result.AddSummary("Imported Terms", otherTaxonomyTerms.Count.ToString()); - CheckPoint.Progress = 100; - CheckPoint.ProcessedItems += otherTaxonomyTerms.Count; - CheckPoint.Stage++; - CheckPoint.Completed = true; - CheckPointStageCallback(this); + var otherTaxonomyTerms = this.Repository.GetAllItems().ToList(); + this.ProcessTaxonomyTerms(importJob, importDto, otherVocabularies, otherTaxonomyTerms); + this.Repository.UpdateItems(otherTaxonomyTerms); + this.Result.AddSummary("Imported Terms", otherTaxonomyTerms.Count.ToString()); + this.CheckPoint.Progress = 100; + this.CheckPoint.ProcessedItems += otherTaxonomyTerms.Count; + this.CheckPoint.Stage++; + this.CheckPoint.Completed = true; + this.CheckPointStageCallback(this); } } public override int GetImportTotal() { - return Repository.GetCount() + Repository.GetCount(); + return this.Repository.GetCount() + this.Repository.GetCount(); + } + + private static List GetTaxonomyTerms(int portalId, DateTime toDate, DateTime? fromDate) + { + return CBO.FillCollection(DataProvider.Instance().GetAllTerms(portalId, toDate, fromDate)); + } + + private static List GetTaxonomyVocabularies(int portalId, DateTime toDate, DateTime? fromDate) + { + return CBO.FillCollection(DataProvider.Instance().GetAllVocabularies(portalId, toDate, fromDate)); } private void ProcessVocabularies(ExportImportJob importJob, ImportDto importDto, @@ -165,7 +201,7 @@ private void ProcessVocabularies(ExportImportJob importJob, ImportDto importDto, switch (importDto.CollisionResolution) { case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored vocabulary", other.Name); + this.Result.AddLogEntry("Ignored vocabulary", other.Name); break; case CollisionResolution.Overwrite: var vocabulary = new Vocabulary(other.Name, other.Description) @@ -176,7 +212,7 @@ private void ProcessVocabularies(ExportImportJob importJob, ImportDto importDto, ScopeTypeId = scope?.LocalId ?? other.ScopeTypeID, }; dataService.UpdateVocabulary(vocabulary, modifiedBy); - Result.AddLogEntry("Updated vocabulary", other.Name); + this.Result.AddLogEntry("Updated vocabulary", other.Name); changed = true; break; default: @@ -193,19 +229,23 @@ private void ProcessVocabularies(ExportImportJob importJob, ImportDto importDto, ScopeTypeId = scope?.LocalId ?? other.ScopeTypeID, }; other.LocalId = dataService.AddVocabulary(vocabulary, createdBy); - Result.AddLogEntry("Added vocabulary", other.Name); + this.Result.AddLogEntry("Added vocabulary", other.Name); changed = true; } } - if (changed) - DataCache.ClearCache(DataCache.VocabularyCacheKey); + + if (changed) + { + DataCache.ClearCache(DataCache.VocabularyCacheKey); + } } private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto, IList otherVocabularies, IList otherTaxonomyTerms) { var dataService = Util.GetDataService(); - //var vocabularyController = new VocabularyController(); + + // var vocabularyController = new VocabularyController(); var localTaxonomyTerms = GetTaxonomyTerms(importDto.PortalId, DateUtils.GetDatabaseUtcTime().AddYears(1), null); foreach (var other in otherTaxonomyTerms) { @@ -223,7 +263,7 @@ private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto switch (importDto.CollisionResolution) { case CollisionResolution.Ignore: - Result.AddLogEntry("Ignored taxonomy", other.Name); + this.Result.AddLogEntry("Ignored taxonomy", other.Name); break; case CollisionResolution.Overwrite: var parent = other.ParentTermID.HasValue @@ -244,8 +284,9 @@ private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto { dataService.UpdateSimpleTerm(term, modifiedBy); } + DataCache.ClearCache(string.Format(DataCache.TermCacheKey, term.TermId)); - Result.AddLogEntry("Updated taxonomy", other.Name); + this.Result.AddLogEntry("Updated taxonomy", other.Name); break; default: throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); @@ -261,12 +302,11 @@ private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto ParentTermId = parent?.LocalId, Weight = other.Weight, }; - - + other.LocalId = isHierarchical ? dataService.AddHeirarchicalTerm(term, createdBy) : dataService.AddSimpleTerm(term, createdBy); - Result.AddLogEntry("Added taxonomy", other.Name); + this.Result.AddLogEntry("Added taxonomy", other.Name); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs index 5d96e7eee7d..b50003b4b17 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs @@ -1,25 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Dto; -using Dnn.ExportImport.Components.Entities; -using Dnn.ExportImport.Components.Providers; -using Dnn.ExportImport.Dto.Taxonomy; -using Dnn.ExportImport.Dto.Workflow; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Components.Services { + using System; + using System.Collections.Generic; + using System.Linq; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Dto; + using Dnn.ExportImport.Components.Entities; + using Dnn.ExportImport.Components.Providers; + using Dnn.ExportImport.Dto.Taxonomy; + using Dnn.ExportImport.Dto.Workflow; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + public class WorkflowsExportService : BasePortableService { public override string Category => Constants.Category_Workflows; @@ -30,16 +31,21 @@ public class WorkflowsExportService : BasePortableService public override int GetImportTotal() { - return Repository.GetCount() + Repository.GetCount(); - } - - #region Exporting - + return this.Repository.GetCount() + this.Repository.GetCount(); + } + public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (CheckPoint.Stage > 0) return; - if (CheckCancelled(exportJob)) return; - + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); @@ -53,56 +59,33 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) defaultWorkflow.IsDefault = true; } - CheckPoint.TotalItems = contentWorkflows.Count; - Repository.CreateItems(contentWorkflows); - Result.AddLogEntry("Exported ContentWorkflows", contentWorkflows.Count.ToString()); + this.CheckPoint.TotalItems = contentWorkflows.Count; + this.Repository.CreateItems(contentWorkflows); + this.Result.AddLogEntry("Exported ContentWorkflows", contentWorkflows.Count.ToString()); foreach (var workflow in contentWorkflows) { var contentWorkflowStates = GetWorkflowStates(workflow.WorkflowID); - Repository.CreateItems(contentWorkflowStates, workflow.Id); + this.Repository.CreateItems(contentWorkflowStates, workflow.Id); foreach (var workflowState in contentWorkflowStates) { var contentWorkflowStatePermissions = GetWorkflowStatePermissions(workflowState.StateID, toDate, fromDate); - Repository.CreateItems(contentWorkflowStatePermissions, workflowState.Id); + this.Repository.CreateItems(contentWorkflowStatePermissions, workflowState.Id); } } } - CheckPoint.Progress = 100; - CheckPoint.Completed = true; - CheckPoint.Stage++; - CheckPoint.StageData = null; - CheckPointStageCallback(this); - } - - private static List GetWorkflows(int portalId, bool includeDeletions) - { - return CBO.FillCollection( - DataProvider.Instance().GetAllWorkflows(portalId, includeDeletions)); - } - - private static List GetWorkflowStates(int workflowId) - { - return CBO.FillCollection( - DataProvider.Instance().GetAllWorkflowStates(workflowId)); - } - - private static List GetWorkflowStatePermissions( - int stateId, DateTime toDate, DateTime? fromDate) - { - return CBO.FillCollection( - DataProvider.Instance().GetAllWorkflowStatePermissions(stateId, toDate, fromDate)); + this.CheckPoint.Progress = 100; + this.CheckPoint.Completed = true; + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + this.CheckPointStageCallback(this); } - - #endregion - - #region Importing - + public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (CheckCancelled(importJob) || CheckPoint.Stage >= 1 || CheckPoint.Completed || CheckPointStageCallback(this)) + if (this.CheckCancelled(importJob) || this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed || this.CheckPointStageCallback(this)) { return; } @@ -110,13 +93,10 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var workflowManager = WorkflowManager.Instance; var workflowStateManager = WorkflowStateManager.Instance; var portalId = importJob.PortalId; - var importWorkflows = Repository.GetAllItems().ToList(); + var importWorkflows = this.Repository.GetAllItems().ToList(); var existWorkflows = workflowManager.GetWorkflows(portalId).ToList(); var defaultTabWorkflowId = importWorkflows.FirstOrDefault(w => w.IsDefault)?.WorkflowID ?? 1; - CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? importWorkflows.Count : CheckPoint.TotalItems; - - #region importing workflows - + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? importWorkflows.Count : this.CheckPoint.TotalItems; foreach (var importWorkflow in importWorkflows) { var workflow = existWorkflows.FirstOrDefault(w => w.WorkflowName == importWorkflow.WorkflowName); @@ -130,7 +110,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) workflow.Description = importWorkflow.Description; workflow.WorkflowKey = importWorkflow.WorkflowKey; workflowManager.UpdateWorkflow(workflow); - Result.AddLogEntry("Updated workflow", workflow.WorkflowName); + this.Result.AddLogEntry("Updated workflow", workflow.WorkflowName); } } } @@ -145,7 +125,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) }; workflowManager.AddWorkflow(workflow); - Result.AddLogEntry("Added workflow", workflow.WorkflowName); + this.Result.AddLogEntry("Added workflow", workflow.WorkflowName); if (importWorkflow.WorkflowID == defaultTabWorkflowId) { @@ -153,11 +133,8 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } - importWorkflow.LocalId = workflow.WorkflowID; - - #region importing workflow states - - var importStates = Repository.GetRelatedItems(importWorkflow.Id).ToList(); + importWorkflow.LocalId = workflow.WorkflowID; + var importStates = this.Repository.GetRelatedItems(importWorkflow.Id).ToList(); foreach (var importState in importStates) { var workflowState = workflow.States.FirstOrDefault(s => s.StateName == importState.StateName); @@ -170,7 +147,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) workflowState.SendNotification = importState.SendNotification; workflowState.SendNotificationToAdministrators = importState.SendNotificationToAdministrators; workflowStateManager.UpdateWorkflowState(workflowState); - Result.AddLogEntry("Updated workflow state", workflowState.StateID.ToString()); + this.Result.AddLogEntry("Updated workflow state", workflowState.StateID.ToString()); } } else @@ -182,18 +159,16 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) Order = importState.Order, IsSystem = importState.IsSystem, SendNotification = importState.SendNotification, - SendNotificationToAdministrators = importState.SendNotificationToAdministrators + SendNotificationToAdministrators = importState.SendNotificationToAdministrators, }; WorkflowStateManager.Instance.AddWorkflowState(workflowState); - Result.AddLogEntry("Added workflow state", workflowState.StateID.ToString()); + this.Result.AddLogEntry("Added workflow state", workflowState.StateID.ToString()); } - importState.LocalId = workflowState.StateID; - - #region importin permissions - + + importState.LocalId = workflowState.StateID; if (!workflowState.IsSystem) { - var importPermissions = Repository.GetRelatedItems(importState.Id).ToList(); + var importPermissions = this.Repository.GetRelatedItems(importState.Id).ToList(); foreach (var importPermission in importPermissions) { var permissionId = DataProvider.Instance().GetPermissionId( @@ -218,10 +193,12 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (userId == null) { - Result.AddLogEntry("Couldn't add tab permission; User is undefined!", + this.Result.AddLogEntry( + "Couldn't add tab permission; User is undefined!", $"{importPermission.PermissionKey} - {importPermission.PermissionID}", ReportLevel.Warn); continue; } + permission.UserID = userId.Value; } @@ -229,10 +206,12 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (roleId == null) { - Result.AddLogEntry("Couldn't add tab permission; Role is undefined!", + this.Result.AddLogEntry( + "Couldn't add tab permission; Role is undefined!", $"{importPermission.PermissionKey} - {importPermission.PermissionID}", ReportLevel.Warn); continue; } + permission.RoleID = roleId.Value; } @@ -243,13 +222,13 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) x => x.PermissionCode == importPermission.PermissionCode && x.PermissionKey == importPermission.PermissionKey && x.PermissionName.Equals(importPermission.PermissionName, StringComparison.InvariantCultureIgnoreCase) && x.RoleID == roleId && x.UserID == userId); - - + if (local == null) { workflowStateManager.AddWorkflowStatePermission(permission, -1); importPermission.LocalId = permission.WorkflowStatePermissionID; - Result.AddLogEntry("Added workflow state permission", + this.Result.AddLogEntry( + "Added workflow state permission", permission.WorkflowStatePermissionID.ToString()); } else @@ -259,35 +238,46 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } catch (Exception ex) { - Result.AddLogEntry("Exception adding workflow state permission", ex.Message, ReportLevel.Error); + this.Result.AddLogEntry("Exception adding workflow state permission", ex.Message, ReportLevel.Error); } } } - } - - #endregion - } - - #endregion - - Repository.UpdateItems(importStates); - Result.AddSummary("Imported Workflow", importWorkflows.Count.ToString()); - CheckPoint.ProcessedItems++; - CheckPointStageCallback(this); // no need to return; very small amount of data processed - } - - #endregion + } + } + + this.Repository.UpdateItems(importStates); + this.Result.AddSummary("Imported Workflow", importWorkflows.Count.ToString()); + this.CheckPoint.ProcessedItems++; + this.CheckPointStageCallback(this); // no need to return; very small amount of data processed + } + + this.Repository.UpdateItems(importWorkflows); + + this.CheckPoint.Stage++; + this.CheckPoint.StageData = null; + this.CheckPoint.Progress = 100; + this.CheckPoint.TotalItems = importWorkflows.Count; + this.CheckPoint.ProcessedItems = importWorkflows.Count; + this.CheckPointStageCallback(this); + } - Repository.UpdateItems(importWorkflows); + private static List GetWorkflows(int portalId, bool includeDeletions) + { + return CBO.FillCollection( + DataProvider.Instance().GetAllWorkflows(portalId, includeDeletions)); + } - CheckPoint.Stage++; - CheckPoint.StageData = null; - CheckPoint.Progress = 100; - CheckPoint.TotalItems = importWorkflows.Count; - CheckPoint.ProcessedItems = importWorkflows.Count; - CheckPointStageCallback(this); + private static List GetWorkflowStates(int workflowId) + { + return CBO.FillCollection( + DataProvider.Instance().GetAllWorkflowStates(workflowId)); } - #endregion + private static List GetWorkflowStatePermissions( + int stateId, DateTime toDate, DateTime? fromDate) + { + return CBO.FillCollection( + DataProvider.Instance().GetAllWorkflowStatePermissions(stateId, toDate, fromDate)); + } } } diff --git a/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj b/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj index 534c39145d8..529932b5161 100644 --- a/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj +++ b/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj @@ -1,178 +1,184 @@ - - - - - Debug - AnyCPU - {E29D5AAB-B4AE-4DE0-8443-EBF40865030A} - Library - Properties - Dnn.ExportImport - DotNetNuke.SiteExportImport - v4.7.2 - 512 - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - bin\DotNetNuke.SiteExportImport.xml - 1591 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - bin\DotNetNuke.SiteExportImport.xml - 1591 - 7 - - - - ..\..\..\packages\LiteDB.3.1.0\lib\net35\LiteDB.dll - True - - - - False - ..\..\..\Packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll - - - - - - - - - - ..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - True - - - - - ..\..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - True - - - - - - - Properties\SolutionInfo.cs - - - True - True - ExportImport.resx - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - - - - - - {3cd5f6b8-8360-4862-80b6-f402892db7dd} - DotNetNuke.Instrumentation - - - {ee1329fe-fd88-4e1a-968c-345e394ef080} - DotNetNuke.Web - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {2c624453-4ed2-4bcb-9d71-664ac7d5955c} - DnnExportImportLibrary - - - - - - - - - - - - - ResXFileCodeGenerator - ExportImport.Designer.cs - - - - - + + + + + Debug + AnyCPU + {E29D5AAB-B4AE-4DE0-8443-EBF40865030A} + Library + Properties + Dnn.ExportImport + DotNetNuke.SiteExportImport + v4.7.2 + 512 + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + bin\DotNetNuke.SiteExportImport.xml + 1591 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + bin\DotNetNuke.SiteExportImport.xml + 1591 + 7 + + + + ..\..\..\packages\LiteDB.3.1.0\lib\net35\LiteDB.dll + True + + + + False + ..\..\..\Packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + ..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + True + + + + + ..\..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + True + + + + + + + Properties\SolutionInfo.cs + + + True + True + ExportImport.resx + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Designer + + + + + + + + + + {3cd5f6b8-8360-4862-80b6-f402892db7dd} + DotNetNuke.Instrumentation + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {2c624453-4ed2-4bcb-9d71-664ac7d5955c} + DnnExportImportLibrary + + + + + stylecop.json + + + + + + + + + + + ResXFileCodeGenerator + ExportImport.Designer.cs + + + + + + + + + --> \ No newline at end of file diff --git a/DNN Platform/Modules/DnnExportImport/Properties/AssemblyInfo.cs b/DNN Platform/Modules/DnnExportImport/Properties/AssemblyInfo.cs index 3091e64cce1..4c78a68ad1c 100644 --- a/DNN Platform/Modules/DnnExportImport/Properties/AssemblyInfo.cs +++ b/DNN Platform/Modules/DnnExportImport/Properties/AssemblyInfo.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; [assembly: AssemblyTitle("DnnExportImport")] diff --git a/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs b/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs index 88a70bd3611..5aa56b4ba78 100644 --- a/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs +++ b/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using Dnn.ExportImport.Components.Common; -using Dnn.ExportImport.Components.Controllers; -using Dnn.ExportImport.Components.Dto; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Services { + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using Dnn.ExportImport.Components.Common; + using Dnn.ExportImport.Components.Controllers; + using Dnn.ExportImport.Components.Dto; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Api; + [RequireHost] public class ExportImportController : DnnApiController { @@ -22,9 +23,9 @@ public class ExportImportController : DnnApiController public HttpResponseMessage Export(ExportDto exportDto) { var controller = new ExportController(); - var jobId = controller.QueueOperation(PortalSettings.UserId, exportDto); + var jobId = controller.QueueOperation(this.PortalSettings.UserId, exportDto); - return Request.CreateResponse(HttpStatusCode.OK, new { jobId }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { jobId }); } [HttpPost] @@ -35,10 +36,11 @@ public HttpResponseMessage Import(ImportDto importDto) string message; if (controller.VerifyImportPackage(importDto.PackageId, null, out message)) { - var jobId = controller.QueueOperation(PortalSettings.UserId, importDto); - return Request.CreateResponse(HttpStatusCode.OK, new { jobId }); + var jobId = controller.QueueOperation(this.PortalSettings.UserId, importDto); + return this.Request.CreateResponse(HttpStatusCode.OK, new { jobId }); } - return Request.CreateErrorResponse(HttpStatusCode.BadRequest, message); + + return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, message); } [HttpGet] @@ -48,18 +50,18 @@ public HttpResponseMessage VerifyImportPackage(string packageId) string message; var summary = new ImportExportSummary(); var isValid = controller.VerifyImportPackage(packageId, summary, out message); - summary.ConvertToLocal(UserInfo); + summary.ConvertToLocal(this.UserInfo); return isValid - ? Request.CreateResponse(HttpStatusCode.OK, summary) - : Request.CreateErrorResponse(HttpStatusCode.BadRequest, message); + ? this.Request.CreateResponse(HttpStatusCode.OK, summary) + : this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, message); } /// - /// Get list of packages to import + /// Get list of packages to import. /// - /// Keyword to search the import package. This will look into the package name and description - /// Order by which the packages list should be sorted. Allowed values: newest, oldest, name - /// Page index to get + /// Keyword to search the import package. This will look into the package name and description. + /// Order by which the packages list should be sorted. Allowed values: newest, oldest, name. + /// Page index to get. /// Page size. Should not be more than 100. /// [HttpGet] @@ -69,8 +71,8 @@ public HttpResponseMessage GetImportPackages(string keyword = "", string order = var controller = new ImportController(); int total; var packages = controller.GetImportPackages(out total, keyword, order, pageIndex, pageSize).ToList(); - packages.ForEach(package => package.ConvertToLocal(UserInfo)); - return Request.CreateResponse(HttpStatusCode.OK, new { packages, total }); + packages.ForEach(package => package.ConvertToLocal(this.UserInfo)); + return this.Request.CreateResponse(HttpStatusCode.OK, new { packages, total }); } // this is POST so users can't cancel using a simple browser link @@ -79,8 +81,8 @@ public HttpResponseMessage GetImportPackages(string keyword = "", string order = public HttpResponseMessage CancelProcess([FromUri] int jobId) { var controller = new BaseController(); - var cancelStatus = controller.CancelJob(UserInfo.IsSuperUser ? -1 : PortalSettings.PortalId, jobId); - return Request.CreateResponse( + var cancelStatus = controller.CancelJob(this.UserInfo.IsSuperUser ? -1 : this.PortalSettings.PortalId, jobId); + return this.Request.CreateResponse( cancelStatus ? HttpStatusCode.OK : HttpStatusCode.BadRequest, new { success = cancelStatus }); } @@ -90,27 +92,31 @@ public HttpResponseMessage CancelProcess([FromUri] int jobId) public HttpResponseMessage RemoveJob([FromUri] int jobId) { var controller = new BaseController(); - var cancelStatus = controller.RemoveJob(UserInfo.IsSuperUser ? -1 : PortalSettings.PortalId, jobId); - return Request.CreateResponse( + var cancelStatus = controller.RemoveJob(this.UserInfo.IsSuperUser ? -1 : this.PortalSettings.PortalId, jobId); + return this.Request.CreateResponse( cancelStatus ? HttpStatusCode.OK : HttpStatusCode.BadRequest, new { success = cancelStatus }); } [HttpGet] public HttpResponseMessage LastJobTime(int portal, JobType jobType) { - if (!UserInfo.IsSuperUser && portal != PortalSettings.PortalId) + if (!this.UserInfo.IsSuperUser && portal != this.PortalSettings.PortalId) { var error = Localization.GetString("NotPortalAdmin", Constants.SharedResources); - return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); + return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } - if (portal < 0) - return Request.CreateErrorResponse(HttpStatusCode.BadRequest, - Localization.GetString("InvalidPortal", Constants.SharedResources)); - + if (portal < 0) + { + return this.Request.CreateErrorResponse( + HttpStatusCode.BadRequest, + Localization.GetString("InvalidPortal", Constants.SharedResources)); + } + var controller = new BaseController(); var lastTime = controller.GetLastJobTime(portal, jobType); - return Request.CreateResponse(HttpStatusCode.OK, + return this.Request.CreateResponse( + HttpStatusCode.OK, new { lastTime = Util.GetDateTimeString(lastTime) }); } @@ -118,26 +124,28 @@ public HttpResponseMessage LastJobTime(int portal, JobType jobType) public HttpResponseMessage AllJobs(int portal, int? pageSize = 10, int? pageIndex = 0, int? jobType = null, string keywords = null) { - if (!UserInfo.IsSuperUser && portal != PortalSettings.PortalId) + if (!this.UserInfo.IsSuperUser && portal != this.PortalSettings.PortalId) { var error = Localization.GetString("NotPortalAdmin", Constants.SharedResources); - return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); + return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } + var controller = new BaseController(); - var jobs = controller.GetAllJobs(portal, PortalSettings.PortalId, pageSize, pageIndex, jobType, keywords); - jobs?.ConvertToLocal(UserInfo); - return Request.CreateResponse(HttpStatusCode.OK, jobs); + var jobs = controller.GetAllJobs(portal, this.PortalSettings.PortalId, pageSize, pageIndex, jobType, keywords); + jobs?.ConvertToLocal(this.UserInfo); + return this.Request.CreateResponse(HttpStatusCode.OK, jobs); } [HttpGet] public HttpResponseMessage JobDetails(int jobId) { var controller = new BaseController(); - var job = controller.GetJobDetails(UserInfo.IsSuperUser ? -1 : PortalSettings.PortalId, jobId); - job?.ConvertToLocal(UserInfo); + var job = controller.GetJobDetails(this.UserInfo.IsSuperUser ? -1 : this.PortalSettings.PortalId, jobId); + job?.ConvertToLocal(this.UserInfo); return job != null - ? Request.CreateResponse(HttpStatusCode.OK, job) - : Request.CreateResponse(HttpStatusCode.BadRequest, + ? this.Request.CreateResponse(HttpStatusCode.OK, job) + : this.Request.CreateResponse( + HttpStatusCode.BadRequest, new { message = Localization.GetString("JobNotExist", Constants.SharedResources) }); } } diff --git a/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs b/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs index da0d3999ff5..4dfb62f5e4b 100644 --- a/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs +++ b/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Services { + using DotNetNuke.Web.Api; + public class ServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute routeManager) { - routeManager.MapHttpRoute("SiteExportImport", - "default", - "{controller}/{action}", - new[] { typeof(ServiceRouteMapper).Namespace }); + routeManager.MapHttpRoute( + "SiteExportImport", + "default", + "{controller}/{action}", + new[] { typeof(ServiceRouteMapper).Namespace }); } } } diff --git a/DNN Platform/Modules/DnnExportImport/dnn_SiteExportImport.dnn b/DNN Platform/Modules/DnnExportImport/dnn_SiteExportImport.dnn index 27de8fc759c..61e587929d1 100644 --- a/DNN Platform/Modules/DnnExportImport/dnn_SiteExportImport.dnn +++ b/DNN Platform/Modules/DnnExportImport/dnn_SiteExportImport.dnn @@ -1,6 +1,6 @@ - + Site Export Import DotNetNuke Corporation Site Export Import Library Images/Files_32x32_Standard.png diff --git a/DNN Platform/Modules/DnnExportImport/packages.config b/DNN Platform/Modules/DnnExportImport/packages.config index 0dcaa4416b2..9bdd5552f1e 100644 --- a/DNN Platform/Modules/DnnExportImport/packages.config +++ b/DNN Platform/Modules/DnnExportImport/packages.config @@ -1,7 +1,8 @@ - - - - - - + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj b/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj index 013aa681945..bcea679154e 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj +++ b/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj @@ -1,101 +1,108 @@ - - - - - Debug - AnyCPU - {2C624453-4ED2-4BCB-9D71-664AC7D5955C} - Library - Properties - Dnn.ExportImport - DotNetNuke.SiteExportImport.Library - v4.7.2 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - 1591 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - 1591 - 7 - - - - ..\..\..\packages\LiteDB.3.1.0\lib\net35\LiteDB.dll - True - - - - - - - Properties\SolutionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + AnyCPU + {2C624453-4ED2-4BCB-9D71-664AC7D5955C} + Library + Properties + Dnn.ExportImport + DotNetNuke.SiteExportImport.Library + v4.7.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 1591 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 1591 + 7 + + + + ..\..\..\packages\LiteDB.3.1.0\lib\net35\LiteDB.dll + True + + + + + + + Properties\SolutionInfo.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + stylecop.json + + + + + + + + + --> \ No newline at end of file diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs index 5fa13b6f8a1..2be58dbf294 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs @@ -1,19 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Assets { + using System; + public class ExportFile : BasicExportImportDto { public int FileId { get; set; } + public string FileName { get; set; } + public string Extension { get; set; } + public int Size { get; set; } + public int? Width { get; set; } + public int? Height { get; set; } + public string ContentType { get; set; } public int FolderId { get; set; } @@ -24,14 +30,18 @@ public class ExportFile : BasicExportImportDto public int? CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } public Guid UniqueId { get; set; } + public Guid VersionGuid { get; set; } public string Sha1Hash { get; set; } @@ -39,17 +49,21 @@ public class ExportFile : BasicExportImportDto public DateTime LastModificationTime { get; set; } public string Title { get; set; } + public DateTime StartDate { get; set; } + public bool EnablePublishPeriod { get; set; } + public DateTime? EndDate { get; set; } + public int PublishedVersion { get; set; } public int? ContentItemId { get; set; } public bool HasBeenPublished { get; set; } + public string Description { get; set; } - - + public int StorageLocation { get; set; } public bool IsCached { get; set; } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs index b455540dd02..c5051e53eae 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs @@ -1,32 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Assets { + using System; + public class ExportFolder : BasicExportImportDto { public int FolderId { get; set; } public string FolderPath { get; set; } + public int StorageLocation { get; set; } + public bool IsProtected { get; set; } + public bool IsCached { get; set; } + public DateTime? LastUpdated { get; set; } public int? CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } + public Guid UniqueId { get; set; } + public Guid VersionGuid { get; set; } + public int FolderMappingId { get; set; } public string FolderMappingName { get; set; } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs index 16a24ea32ce..6647498e5b0 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs @@ -1,27 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Assets { - public class ExportFolderMapping: BasicExportImportDto + using System; + + public class ExportFolderMapping : BasicExportImportDto { public int FolderMappingId { get; set; } public string MappingName { get; set; } + public string FolderProviderType { get; set; } + public int? Priority { get; set; } public int? CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs index bf6130dc610..ea8e48ea577 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Assets { - public class ExportFolderPermission:BasicExportImportDto + using System; + + public class ExportFolderPermission : BasicExportImportDto { public int FolderPermissionId { get; set; } @@ -38,13 +38,14 @@ public class ExportFolderPermission:BasicExportImportDto public int? CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } - } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/BasicExportImportDto.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/BasicExportImportDto.cs index f60ccd45210..ea978ab9884 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/BasicExportImportDto.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/BasicExportImportDto.cs @@ -1,23 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto { public abstract class BasicExportImportDto { /// - /// Id of the object in the export/import database. + /// Gets or sets id of the object in the export/import database. /// public virtual int Id { get; set; } /// - /// Referenced Id (i.e., foreighn key) for another object in the export/import database. + /// Gets or sets referenced Id (i.e., foreighn key) for another object in the export/import database. /// public virtual int? ReferenceId { get; set; } /// - /// Id of the object in the local database. Note that this is use only during + /// Gets or sets id of the object in the local database. Note that this is use only during /// the import process and must remain NULL during the export process. /// public virtual int? LocalId { get; set; } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs index 2dae092ff4c..d3b285c7201 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.ExportImport.Dto.Assets; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.PageTemplates { + using Dnn.ExportImport.Dto.Assets; + public class ExportPageTemplate : ExportFile { } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs index f4fba5dc28a..1c3489239fc 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs @@ -1,34 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportModule : BasicExportImportDto { public int ModuleID { get; set; } + public int ModuleDefID { get; set; } + public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName + public bool AllTabs { get; set; } + public bool IsDeleted { get; set; } + public bool? InheritViewPermissions { get; set; } + public DateTime? StartDate { get; set; } + public DateTime? EndDate { get; set; } + public DateTime? LastContentModifiedOnDate { get; set; } + public int? ContentItemID { get; set; } + public bool IsShareable { get; set; } + public bool IsShareableViewOnly { get; set; } public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs index b60431c6d06..4bbaab24a7c 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Pages { public class ExportModuleContent : BasicExportImportDto { public int ModuleID { get; set; } + public int ModuleDefID { get; set; } + public bool IsRestored { get; set; } + public string XmlContent { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs index b3f4dcb0268..9499e866cb7 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs @@ -1,33 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportModulePermission : BasicExportImportDto { public int ModulePermissionID { get; set; } + public int ModuleID { get; set; } + public int PermissionID { get; set; } + public string PermissionCode { get; set; } + public string PermissionKey { get; set; } + public string PermissionName { get; set; } + public bool AllowAccess { get; set; } + public int? RoleID { get; set; } + public string RoleName { get; set; } + public int? UserID { get; set; } + public string Username { get; set; } public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs index 80d8b970881..73b8e990fc7 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs @@ -1,24 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportModuleSetting : BasicExportImportDto { public int ModuleID { get; set; } + public string SettingName { get; set; } + public string SettingValue { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportPackage.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportPackage.cs index 1f0b34c9c7a..eb527c4c2cc 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportPackage.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportPackage.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportPackage : BasicExportImportDto { public string PackageType { get; set; } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs index 9a85e7f5ede..5474133b3b5 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs @@ -1,54 +1,92 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportTab : BasicExportImportDto { public int TabId { get; set; } + public int TabOrder { get; set; } + public string TabName { get; set; } + public bool IsVisible { get; set; } + public int? ParentId { get; set; } + public string IconFile { get; set; } + public bool DisableLink { get; set; } + public string Title { get; set; } + public string Description { get; set; } + public string KeyWords { get; set; } + public bool IsDeleted { get; set; } + public string Url { get; set; } + public string SkinSrc { get; set; } + public string ContainerSrc { get; set; } + public DateTime? StartDate { get; set; } + public DateTime? EndDate { get; set; } + public int? RefreshInterval { get; set; } + public string PageHeadText { get; set; } + public bool IsSecure { get; set; } + public bool PermanentRedirect { get; set; } + public float SiteMapPriority { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } + public string IconFileLarge { get; set; } + public string CultureCode { get; set; } - public int? ContentItemID { get; set; } //FK + + public int? ContentItemID { get; set; } // FK + public Guid UniqueId { get; set; } + public Guid VersionGuid { get; set; } + public Guid? DefaultLanguageGuid { get; set; } + public Guid LocalizedVersionGuid { get; set; } + public int Level { get; set; } + public string TabPath { get; set; } + public bool HasBeenPublished { get; set; } + public bool IsSystem { get; set; } + public int StateID { get; set; } + public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } + public string Tags { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs index 0f42793f415..405ba3379d3 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Pages { public class ExportTabInfo { public int TabID { get; set; } + public int ParentID { get; set; } + public string TabName { get; set; } + public string TabPath { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs index f710f5107fd..1db3dcb9764 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs @@ -1,54 +1,90 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportTabModule : BasicExportImportDto { public int TabModuleID { get; set; } + public int TabID { get; set; } + public int ModuleID { get; set; } + public string PaneName { get; set; } + public int ModuleOrder { get; set; } + public int CacheTime { get; set; } + public string Alignment { get; set; } + public string Color { get; set; } + public string Border { get; set; } + public string IconFile { get; set; } + public int Visibility { get; set; } + public string ContainerSrc { get; set; } + public bool DisplayTitle { get; set; } + public bool DisplayPrint { get; set; } + public bool DisplaySyndicate { get; set; } + public bool IsWebSlice { get; set; } + public string WebSliceTitle { get; set; } + public DateTime? WebSliceExpiryDate { get; set; } + public int? WebSliceTTL { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } + public bool IsDeleted { get; set; } + public string CacheMethod { get; set; } + public string ModuleTitle { get; set; } + public string Header { get; set; } + public string Footer { get; set; } + public string CultureCode { get; set; } + public Guid UniqueId { get; set; } + public Guid VersionGuid { get; set; } + public Guid? DefaultLanguageGuid { get; set; } + public Guid LocalizedVersionGuid { get; set; } + public bool InheritViewPermissions { get; set; } + public bool IsShareable { get; set; } + public bool IsShareableViewOnly { get; set; } public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName + public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs index aa180e2c65c..26d2385b909 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs @@ -1,24 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportTabModuleSetting : BasicExportImportDto { public int TabModuleID { get; set; } + public string SettingName { get; set; } + public string SettingValue { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs index 410077c4078..3136a0d226a 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs @@ -1,35 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportTabPermission : BasicExportImportDto { public int TabPermissionID { get; set; } + public int TabID { get; set; } + public int PermissionID { get; set; } + public string PermissionCode { get; set; } + public string PermissionKey { get; set; } + public string PermissionName { get; set; } + public bool AllowAccess { get; set; } + public int? RoleID { get; set; } + public string RoleName { get; set; } + public int? UserID { get; set; } + public string Username { get; set; } + public int? ModuleDefID { get; set; } + public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs index db75fc79aef..f1f47de6218 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs @@ -1,24 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportTabSetting : BasicExportImportDto { public int TabID { get; set; } + public string SettingName { get; set; } + public string SettingValue { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs index 8a84ef8942c..ec7098ed0a9 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs @@ -1,31 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Pages { + using System; + public class ExportTabUrl : BasicExportImportDto { public int TabID { get; set; } + public int SeqNum { get; set; } + public string Url { get; set; } + public string QueryString { get; set; } + public string HttpStatus { get; set; } + public string CultureCode { get; set; } + public bool IsSystem { get; set; } + public int? PortalAliasId { get; set; } + public int? PortalAliasUsage { get; set; } // PortalAliasUsageType + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string HTTPAlias { get; set; } + public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs index 02ad2f26d0e..e33e3894c79 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Portal { + using System; + public class ExportPortalLanguage : BasicExportImportDto { public int PortalLanguageId { get; set; } @@ -16,13 +16,16 @@ public class ExportPortalLanguage : BasicExportImportDto public int? CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } + public bool IsPublished { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs index 0f870659e7f..e36518555f1 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs @@ -1,28 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Portal { + using System; + public class ExportPortalSetting : BasicExportImportDto { public int PortalSettingId { get; set; } public string SettingName { get; set; } + public string SettingValue { get; set; } public int? CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } + public string CultureCode { get; set; } + public bool IsSecure { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs index abbca8c935c..c35ba0c8cf2 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.ProfileProperties { + using System; + public class ExportProfileProperty : BasicExportImportDto { public int PropertyDefinitionId { get; set; } @@ -13,26 +13,39 @@ public class ExportProfileProperty : BasicExportImportDto public int? ModuleDefId { get; set; } public bool Deleted { get; set; } + public int? DataType { get; set; } + public string DefaultValue { get; set; } + public string PropertyCategory { get; set; } + public string PropertyName { get; set; } + public int Length { get; set; } + public bool Required { get; set; } + public string ValidationExpression { get; set; } + public int ViewOrder { get; set; } + public bool Visible { get; set; } public int? CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } + public int DefaultVisibility { get; set; } + public bool ReadOnly { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs index c282727e76d..b78f7ff05f0 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs @@ -1,38 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Roles { + using System; + public class ExportRole : BasicExportImportDto { public int RoleID { get; set; } + public string RoleName { get; set; } + public string Description { get; set; } + public decimal? ServiceFee { get; set; } + public string BillingFrequency { get; set; } + public int? TrialPeriod { get; set; } + public string TrialFrequency { get; set; } + public int? BillingPeriod { get; set; } + public decimal? TrialFee { get; set; } + public bool IsPublic { get; set; } + public bool AutoAssignment { get; set; } + public int? RoleGroupID { get; set; } + public string RSVPCode { get; set; } + public string IconFile { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } + public int Status { get; set; } + public int SecurityMode { get; set; } + public bool IsSystemRole { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs index 423356305ce..27d3cb88326 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs @@ -1,24 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Roles { + using System; + public class ExportRoleGroup : BasicExportImportDto { public int RoleGroupID { get; set; } + public string RoleGroupName { get; set; } + public string Description { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs index e1dc679e5a3..edfea721833 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs @@ -1,25 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Roles { + using System; + public class ExportRoleSetting : BasicExportImportDto { public int RoleSettingID { get; set; } + public int RoleID { get; set; } + public string SettingName { get; set; } + public string SettingValue { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs index 8171c337594..814388f7437 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Taxonomy { public class TaxonomyScopeType : BasicExportImportDto { public int ScopeTypeID { get; set; } + public string ScopeType { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs index 77769a76188..5edd7e4218d 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs @@ -1,29 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Taxonomy { + using System; + public class TaxonomyTerm : BasicExportImportDto { public int TermID { get; set; } + public int VocabularyID { get; set; } + public int? ParentTermID { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public int Weight { get; set; } - //public int TermLeft { get; set; } - //public int TermRight { get; set; } + + // public int TermLeft { get; set; } + // public int TermRight { get; set; } public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs index a00095d3f82..abae42646df 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs @@ -1,29 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace Dnn.ExportImport.Dto.Taxonomy { + using System; + public class TaxonomyVocabulary : BasicExportImportDto { public int VocabularyID { get; set; } + public int VocabularyTypeID { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public int Weight { get; set; } + public int? ScopeID { get; set; } + public int ScopeTypeID { get; set; } + public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } + public bool IsSystem { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs index 4f8ff6fdfd0..cf60360ecd0 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Taxonomy { public class TaxonomyVocabularyType : BasicExportImportDto { public int VocabularyTypeID { get; set; } // enum VocabularyType + public string VocabularyType { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs index 08053f5c844..3612a00534d 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs @@ -1,35 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Users { + using System; + public class ExportAspnetMembership : BasicExportImportDto { public Guid ApplicationId { get; set; } + public Guid UserId { get; set; } + public string Password { get; set; } + public int PasswordFormat { get; set; } + public string PasswordSalt { get; set; } public virtual string MobilePin { get; set; } public string Email { get; set; } + public string LoweredEmail { get; set; } + public string PasswordQuestion { get; set; } + public string PasswordAnswer { get; set; } + public bool IsApproved { get; set; } + public bool IsLockedOut { get; set; } + public DateTime CreateDate { get; set; } + public DateTime LastLoginDate { get; set; } + public DateTime LastPasswordChangedDate { get; set; } + public DateTime LastLockoutDate { get; set; } + public int FailedPasswordAttemptCount { get; set; } + public DateTime FailedPasswordAttemptWindowStart { get; set; } + public int FailedPasswordAnswerAttemptCount { get; set; } + public DateTime FailedPasswordAnswerAttemptWindowStart { get; set; } + public string Comment { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs index 3f4af503f13..560ef0e4327 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs @@ -1,19 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Users { + using System; + public class ExportAspnetUser : BasicExportImportDto { public Guid ApplicationId { get; set; } + public Guid UserId { get; set; } + public string UserName { get; set; } + public string LoweredUserName { get; set; } + public string MobileAlias { get; set; } + public bool IsAnonymous { get; set; } + public DateTime? LastActivityDate { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs index b9546894ecc..55d7bb8a1a2 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Users { + using System; + public class ExportUser : BasicExportImportDto { public int RowId { get; set; } @@ -13,26 +13,39 @@ public class ExportUser : BasicExportImportDto public int UserId { get; set; } public string Username { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public bool IsSuperUser { get; set; } + public int? AffiliateId { get; set; } + public string Email { get; set; } + public string DisplayName { get; set; } + public bool UpdatePassword { get; set; } public string LastIpAddress { get; set; } public bool IsDeletedPortal { get; set; } - public int CreatedByUserId { get; set; } //How do we insert this value? - public string CreatedByUserName { get; set; }//This could be used to find "CreatedByUserId" + public int CreatedByUserId { get; set; } // How do we insert this value? + + public string CreatedByUserName { get; set; }// This could be used to find "CreatedByUserId" + public DateTime? CreatedOnDate { get; set; } - public int LastModifiedByUserId { get; set; } //How do we insert this value? - public string LastModifiedByUserName { get; set; }//This could be used to find "LastModifiedByUserId" + public int LastModifiedByUserId { get; set; } // How do we insert this value? + + public string LastModifiedByUserName { get; set; }// This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } + public Guid? PasswordResetToken { get; set; } + public DateTime? PasswordResetExpiration { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs index 186c424f898..fbb18be7d1c 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs @@ -1,27 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Users { - public class ExportUserAuthentication:BasicExportImportDto + using System; + + public class ExportUserAuthentication : BasicExportImportDto { public int UserAuthenticationId { get; set; } public int UserId { get; set; } public string AuthenticationType { get; set; } + public string AuthenticationToken { get; set; } + public int CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" public DateTime CreatedOnDate { get; set; } + public int LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime LastModifiedOnDate { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs index c5d5a423cf8..b29e8955eb0 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs @@ -1,18 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Users { + using System; + public class ExportUserPortal : BasicExportImportDto { public int UserId { get; set; } + public DateTime CreatedDate { get; set; } + public bool Authorised { get; set; } + public bool IsDeleted { get; set; } + public bool RefreshRoles { get; set; } + public string VanityUrl { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs index abb361cc4f8..c4ec1b9e5dd 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Users { + using System; + public class ExportUserProfile : BasicExportImportDto { public int ProfileId { get; set; } @@ -17,9 +17,13 @@ public class ExportUserProfile : BasicExportImportDto public string PropertyName { get; set; } public string PropertyValue { get; set; } + public string PropertyText { get; set; } + public int Visibility { get; set; } + public DateTime LastUpdatedDate { get; set; } + public string ExtendedVisibility { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs index c5a1f1cb278..96c71d17cc3 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Users { + using System; + public class ExportUserRole : BasicExportImportDto { public int UserRoleId { get; set; } @@ -17,19 +17,25 @@ public class ExportUserRole : BasicExportImportDto public string RoleName { get; set; } public DateTime? ExpiryDate { get; set; } + public bool IsTrialUsed { get; set; } + public DateTime? EffectiveDate { get; set; } public int CreatedByUserId { get; set; } - public string CreatedByUserName { get; set; } //This could be used to find "CreatedByUserId" + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + public DateTime CreatedOnDate { get; set; } public int LastModifiedByUserId { get; set; } - public string LastModifiedByUserName { get; set; } //This could be used to find "LastModifiedByUserId" + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + public DateTime? LastModifiedOnDate { get; set; } + public int Status { get; set; } + public bool IsOwner { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs index f2c0aea1e3e..103f8812262 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs @@ -1,22 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Workflow { public class ExportWorkflow : BasicExportImportDto { public int WorkflowID { get; set; } + public string WorkflowName { get; set; } + public string Description { get; set; } + public bool IsDeleted { get; set; } + public bool StartAfterCreating { get; set; } + public bool StartAfterEditing { get; set; } + public bool DispositionEnabled { get; set; } + public bool IsSystem { get; set; } + public string WorkflowKey { get; set; } + public bool IsDefault { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs index 1ca00136152..f0e0896874e 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs @@ -1,27 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Workflow { public class ExportWorkflowState : BasicExportImportDto { public int StateID { get; set; } + public int WorkflowID { get; set; } + public string StateName { get; set; } + public int Order { get; set; } + public bool IsActive { get; set; } + public bool SendEmail { get; set; } + public bool SendMessage { get; set; } + public bool IsDisposalState { get; set; } + public string OnCompleteMessageSubject { get; set; } + public string OnCompleteMessageBody { get; set; } + public string OnDiscardMessageSubject { get; set; } + public string OnDiscardMessageBody { get; set; } + public bool IsSystem { get; set; } + public bool SendNotification { get; set; } + public bool SendNotificationToAdministrators { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs index 0a2ff3b778f..a34006026a0 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs @@ -1,34 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// ReSharper disable InconsistentNaming - -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Dto.Workflow { + using System; + public class ExportWorkflowStatePermission : BasicExportImportDto { public int WorkflowStatePermissionID { get; set; } + public int StateID { get; set; } + public int PermissionID { get; set; } + public string PermissionCode { get; set; } + public string PermissionKey { get; set; } + public string PermissionName { get; set; } + public bool AllowAccess { get; set; } + public int? RoleID { get; set; } + public string RoleName { get; set; } + public int? UserID { get; set; } + public string Username { get; set; } - //public int? ModuleDefID { get; set; } - + + // public int? ModuleDefID { get; set; } public int? CreatedByUserID { get; set; } + public DateTime? CreatedOnDate { get; set; } + public int? LastModifiedByUserID { get; set; } + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs b/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs index 217ae91ddf3..0278e907b9a 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs @@ -1,26 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using Dnn.ExportImport.Dto; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Interfaces { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + + using Dnn.ExportImport.Dto; + public interface IExportImportRepository : IDisposable { - T AddSingleItem(T item) where T : class; - T UpdateSingleItem(T item) where T : class; - T GetSingleItem() where T : class; - - T CreateItem(T item, int? referenceId) where T : BasicExportImportDto; + T AddSingleItem(T item) + where T : class; + + T UpdateSingleItem(T item) + where T : class; + + T GetSingleItem() + where T : class; + + T CreateItem(T item, int? referenceId) + where T : BasicExportImportDto; void CreateItems(IEnumerable items, int? referenceId = null) where T : BasicExportImportDto; - IEnumerable GetItems(Expression> predicate, + IEnumerable GetItems( + Expression> predicate, Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto; @@ -28,15 +36,20 @@ IEnumerable GetAllItems( Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto; - int GetCount() where T : BasicExportImportDto; + int GetCount() + where T : BasicExportImportDto; - void RebuildIndex(Expression> predicate, bool unique = false) where T : BasicExportImportDto; + void RebuildIndex(Expression> predicate, bool unique = false) + where T : BasicExportImportDto; - int GetCount(Expression> predicate) where T : BasicExportImportDto; + int GetCount(Expression> predicate) + where T : BasicExportImportDto; + T GetItem(Expression> predicate) where T : BasicExportImportDto; - T GetItem(int id) where T : BasicExportImportDto; + T GetItem(int id) + where T : BasicExportImportDto; IEnumerable GetItems(IEnumerable idList) where T : BasicExportImportDto; @@ -44,15 +57,20 @@ IEnumerable GetItems(IEnumerable idList) IEnumerable GetRelatedItems(int referenceId) where T : BasicExportImportDto; - IEnumerable FindItems(Expression> predicate) where T : BasicExportImportDto; + IEnumerable FindItems(Expression> predicate) + where T : BasicExportImportDto; - void UpdateItem(T item) where T : BasicExportImportDto; + void UpdateItem(T item) + where T : BasicExportImportDto; - void UpdateItems(IEnumerable items) where T : BasicExportImportDto; + void UpdateItems(IEnumerable items) + where T : BasicExportImportDto; - bool DeleteItem(int id) where T : BasicExportImportDto; + bool DeleteItem(int id) + where T : BasicExportImportDto; - void DeleteItems(Expression> deleteExpression) where T : BasicExportImportDto; + void DeleteItems(Expression> deleteExpression) + where T : BasicExportImportDto; void CleanUpLocal(string collectionName); } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Properties/AssemblyInfo.cs b/DNN Platform/Modules/DnnExportImportLibrary/Properties/AssemblyInfo.cs index dd5366fffdb..b969423234e 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Properties/AssemblyInfo.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Properties/AssemblyInfo.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; [assembly: AssemblyTitle("DnnExportImportLibrary")] diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs b/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs index d2ef2a333de..c9f8195b4f9 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs @@ -1,120 +1,147 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; -using Dnn.ExportImport.Dto; -using Dnn.ExportImport.Interfaces; -using LiteDB; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.ExportImport.Repository { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Threading; + + using Dnn.ExportImport.Dto; + using Dnn.ExportImport.Interfaces; + using LiteDB; + public class ExportImportRepository : IExportImportRepository { private LiteDatabase _liteDb; public ExportImportRepository(string dbFileName) { - _liteDb = new LiteDatabase(dbFileName); - _liteDb.Mapper.EmptyStringToNull = false; - _liteDb.Mapper.TrimWhitespace = false; + this._liteDb = new LiteDatabase(dbFileName); + this._liteDb.Mapper.EmptyStringToNull = false; + this._liteDb.Mapper.TrimWhitespace = false; } ~ExportImportRepository() { - Dispose(false); + this.Dispose(false); } public void Dispose() { - Dispose(true); + this.Dispose(true); } - private void Dispose(bool isDisposing) + public T AddSingleItem(T item) + where T : class { - var temp = Interlocked.Exchange(ref _liteDb, null); - temp?.Dispose(); - if (isDisposing) - GC.SuppressFinalize(this); - } - - public T AddSingleItem(T item) where T : class - { - var collection = DbCollection(); + var collection = this.DbCollection(); collection.Insert(item); return item; } - public T UpdateSingleItem(T item) where T : class + public T UpdateSingleItem(T item) + where T : class { - var collection = DbCollection(); + var collection = this.DbCollection(); collection.Update(item); return item; } - public T GetSingleItem() where T : class + private void Dispose(bool isDisposing) { - var collection = DbCollection(); + var temp = Interlocked.Exchange(ref this._liteDb, null); + temp?.Dispose(); + if (isDisposing) + { + GC.SuppressFinalize(this); + } + } + + public T GetSingleItem() + where T : class + { + var collection = this.DbCollection(); var first = collection.Min(); return collection.FindById(first); } - public T CreateItem(T item, int? referenceId) where T : BasicExportImportDto + public T CreateItem(T item, int? referenceId) + where T : BasicExportImportDto { - if (item == null) return null; - var collection = DbCollection(); + if (item == null) + { + return null; + } + + var collection = this.DbCollection(); if (referenceId != null) { item.ReferenceId = referenceId; } + item.Id = collection.Insert(item); return item; } - public void CreateItems(IEnumerable items, int? referenceId = null) where T : BasicExportImportDto + public void CreateItems(IEnumerable items, int? referenceId = null) + where T : BasicExportImportDto { - if (items == null) return; + if (items == null) + { + return; + } + var allItems = items as List ?? items.ToList(); - if (allItems.Count == 0) return; - - var collection = DbCollection(); + if (allItems.Count == 0) + { + return; + } + + var collection = this.DbCollection(); if (referenceId != null) { allItems.ForEach(x => { x.ReferenceId = referenceId; }); } + collection.Insert(allItems); } - public T GetItem(Expression> predicate) where T : BasicExportImportDto + public T GetItem(Expression> predicate) + where T : BasicExportImportDto { - return InternalGetItems(predicate).FirstOrDefault(); + return this.InternalGetItems(predicate).FirstOrDefault(); } - public IEnumerable GetItems(Expression> predicate, + public IEnumerable GetItems( + Expression> predicate, Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto { - return InternalGetItems(predicate, orderKeySelector, asc, skip, max); + return this.InternalGetItems(predicate, orderKeySelector, asc, skip, max); } - public int GetCount() where T : BasicExportImportDto + public int GetCount() + where T : BasicExportImportDto { - var collection = DbCollection(); + var collection = this.DbCollection(); return collection?.Count() ?? 0; } - public int GetCount(Expression> predicate) where T : BasicExportImportDto + + public int GetCount(Expression> predicate) + where T : BasicExportImportDto { - var collection = DbCollection(); + var collection = this.DbCollection(); return collection?.Count(predicate) ?? 0; } - public void RebuildIndex(Expression> predicate, bool unique = false) where T : BasicExportImportDto + public void RebuildIndex(Expression> predicate, bool unique = false) + where T : BasicExportImportDto { - var collection = DbCollection(); + var collection = this.DbCollection(); collection.EnsureIndex(predicate, unique); } @@ -122,87 +149,117 @@ public IEnumerable GetAllItems( Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto { - return InternalGetItems(null, orderKeySelector, asc, skip, max); + return this.InternalGetItems(null, orderKeySelector, asc, skip, max); + } + + public T GetItem(int id) + where T : BasicExportImportDto + { + var collection = this.DbCollection(); + return collection.FindById(id); + } + + public IEnumerable GetItems(IEnumerable idList) + where T : BasicExportImportDto + { + Expression> predicate = p => idList.Contains(p.Id); + return this.InternalGetItems(predicate); } - private IEnumerable InternalGetItems(Expression> predicate, + private IEnumerable InternalGetItems( + Expression> predicate, Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto { - var collection = DbCollection(); + var collection = this.DbCollection(); var result = predicate != null ? collection.Find(predicate, skip ?? 0, max ?? int.MaxValue) : collection.Find(Query.All(), skip ?? 0, max ?? int.MaxValue); - if (orderKeySelector != null) - result = asc ? result.OrderBy(orderKeySelector) : result.OrderByDescending(orderKeySelector); - + if (orderKeySelector != null) + { + result = asc ? result.OrderBy(orderKeySelector) : result.OrderByDescending(orderKeySelector); + } + return result.AsEnumerable(); } - public T GetItem(int id) where T : BasicExportImportDto - { - var collection = DbCollection(); - return collection.FindById(id); - } - - public IEnumerable GetItems(IEnumerable idList) - where T : BasicExportImportDto - { - Expression> predicate = p => idList.Contains(p.Id); - return InternalGetItems(predicate); - } - public IEnumerable GetRelatedItems(int referenceId) where T : BasicExportImportDto { Expression> predicate = p => p.ReferenceId == referenceId; - return InternalGetItems(predicate); + return this.InternalGetItems(predicate); } - public IEnumerable FindItems(Expression> predicate) where T : BasicExportImportDto + public IEnumerable FindItems(Expression> predicate) + where T : BasicExportImportDto { - var collection = DbCollection(); + var collection = this.DbCollection(); return collection.Find(predicate); } - public void UpdateItem(T item) where T : BasicExportImportDto + public void UpdateItem(T item) + where T : BasicExportImportDto { - if (item == null) return; - var collection = DbCollection(); - if (collection.FindById(item.Id) == null) throw new KeyNotFoundException(); + if (item == null) + { + return; + } + + var collection = this.DbCollection(); + if (collection.FindById(item.Id) == null) + { + throw new KeyNotFoundException(); + } + collection.Update(item); } - public void UpdateItems(IEnumerable items) where T : BasicExportImportDto + public void UpdateItems(IEnumerable items) + where T : BasicExportImportDto { var allItems = items as T[] ?? items.ToArray(); - if (allItems.Length == 0) return; - - var collection = DbCollection(); + if (allItems.Length == 0) + { + return; + } + + var collection = this.DbCollection(); collection.Update(allItems); } - public bool DeleteItem(int id) where T : BasicExportImportDto + public bool DeleteItem(int id) + where T : BasicExportImportDto { - var collection = DbCollection(); + var collection = this.DbCollection(); var item = collection.FindById(id); - if (item == null) throw new KeyNotFoundException(); + if (item == null) + { + throw new KeyNotFoundException(); + } + return collection.Delete(id); } - public void DeleteItems(Expression> deleteExpression) where T : BasicExportImportDto + public void DeleteItems(Expression> deleteExpression) + where T : BasicExportImportDto { - var collection = DbCollection(); - if (deleteExpression != null) - collection.Delete(deleteExpression); + var collection = this.DbCollection(); + if (deleteExpression != null) + { + collection.Delete(deleteExpression); + } } public void CleanUpLocal(string collectionName) { - if (!_liteDb.CollectionExists(collectionName)) return; - var collection = _liteDb.GetCollection(collectionName); + if (!this._liteDb.CollectionExists(collectionName)) + { + return; + } + + var collection = this._liteDb.GetCollection(collectionName); var documentsToUpdate = collection.Find(Query.All()).ToList(); documentsToUpdate.ForEach(x => { @@ -213,7 +270,7 @@ public void CleanUpLocal(string collectionName) private LiteCollection DbCollection() { - return _liteDb.GetCollection(typeof(T).Name); + return this._liteDb.GetCollection(typeof(T).Name); } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/packages.config b/DNN Platform/Modules/DnnExportImportLibrary/packages.config index 3b060073ba5..7f196becf5f 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/packages.config +++ b/DNN Platform/Modules/DnnExportImportLibrary/packages.config @@ -1,4 +1,5 @@ - - - + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/Groups/Components/Constants.cs b/DNN Platform/Modules/Groups/Components/Constants.cs index 6da0051dea7..0d0478e4519 100644 --- a/DNN Platform/Modules/Groups/Components/Constants.cs +++ b/DNN Platform/Modules/Groups/Components/Constants.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; - -namespace DotNetNuke.Modules.Groups.Components { - public class Constants { - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Groups.Components +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + public class Constants + { internal const string DefaultRoleGroupSetting = "DefaultRoleGroup_Setting"; internal const string DefautlGroupViewMode = "DefaultGroupViewMode_Setting"; internal const string GroupViewPage = "GroupViewPage_Setting"; @@ -22,25 +22,24 @@ public class Constants { internal const string GroupListSearchEnabled = "GroupListSearchEnabled_Setting"; internal const string GroupListSortField = "GroupListSortField_Setting"; internal const string GroupListSortDirection = "GroupListSortDirection_Setting"; - + internal const string GroupViewTemplate = "GroupViewTemplate_Setting"; internal const string GroupListTemplate = "GroupListTemplate_Setting"; internal const string GroupModerationEnabled = "GroupModerationEnabled_Setting"; - internal const string GroupPendingNotification = "GroupPendingNotification"; //Sent to Moderators when a group is created and moderation is enabled. - internal const string GroupApprovedNotification = "GroupApprovedNotification"; //Sent to group creator when group is approved. - internal const string GroupCreatedNotification = "GroupCreatedNotification"; //Sent to Admins/Moderators when a new group is created and moderation is disabled. - internal const string GroupRejectedNotification = "GroupRejectedNotification"; //Sent to group creator when a group is rejected. - - internal const string MemberPendingNotification = "GroupMemberPendingNotification"; //Sent to Group Owners when a new member has requested access to a private group. - internal const string MemberApprovedNotification = "GroupMemberApprovedNotification"; //Sent to Member when membership is approved. - internal const string MemberJoinedNotification = "MemberJoinedNotification"; //Sent to Group Owners when a new member has joined a public group. - internal const string MemberRejectedNotification = "GroupMemberRejectedNotification"; //Sent to requesting member when membership is rejected. - + internal const string GroupPendingNotification = "GroupPendingNotification"; // Sent to Moderators when a group is created and moderation is enabled. + internal const string GroupApprovedNotification = "GroupApprovedNotification"; // Sent to group creator when group is approved. + internal const string GroupCreatedNotification = "GroupCreatedNotification"; // Sent to Admins/Moderators when a new group is created and moderation is disabled. + internal const string GroupRejectedNotification = "GroupRejectedNotification"; // Sent to group creator when a group is rejected. + internal const string MemberPendingNotification = "GroupMemberPendingNotification"; // Sent to Group Owners when a new member has requested access to a private group. + internal const string MemberApprovedNotification = "GroupMemberApprovedNotification"; // Sent to Member when membership is approved. + internal const string MemberJoinedNotification = "MemberJoinedNotification"; // Sent to Group Owners when a new member has joined a public group. + internal const string MemberRejectedNotification = "GroupMemberRejectedNotification"; // Sent to requesting member when membership is rejected. + internal const string SharedResourcesPath = "~/DesktopModules/SocialGroups/App_LocalResources/SharedResources.resx"; internal const string ModulePath = "~/DesktopModules/SocialGroups/"; - internal const string DefaultGroupName = "Social Groups"; + internal const string DefaultGroupName = "Social Groups"; } } diff --git a/DNN Platform/Modules/Groups/Components/Content.cs b/DNN Platform/Modules/Groups/Components/Content.cs index 12691d15e7a..2581b5f1cad 100644 --- a/DNN Platform/Modules/Groups/Components/Content.cs +++ b/DNN Platform/Modules/Groups/Components/Content.cs @@ -1,64 +1,101 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using DotNetNuke.Entities.Content; -using DotNetNuke.Security.Roles; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Common.Utilities; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Entities.Groups +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Security.Roles; + + public class Content + { + /// + /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. + /// + /// The primary key value (ContentTypeID) from the core API's Content Types table. + internal static int GetContentTypeID(string ContentTypeName) + { + var typeController = new ContentTypeController(); + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t; + int contentTypeId; + + if (colContentTypes.Count() > 0) + { + var contentType = colContentTypes.Single(); + contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; + } + else + { + contentTypeId = CreateContentType(ContentTypeName); + } -namespace DotNetNuke.Entities.Groups { - public class Content { + return contentTypeId; + } + /// - /// This should only run after the Post exists in the data store. + /// This should only run after the Post exists in the data store. /// /// The newly created ContentItemID from the data store. /// This is for the first question in the thread. Not for replies or items with ParentID > 0. - internal ContentItem CreateContentItem(RoleInfo objItem, int tabId) { + internal ContentItem CreateContentItem(RoleInfo objItem, int tabId) + { var typeController = new ContentTypeController(); string contentTypeName = "DNNCorp_SocialGroup"; - if (objItem.RoleID > 0) { + if (objItem.RoleID > 0) + { contentTypeName = "DNNCorp_SocialGroup"; } - var colContentTypes = (from t in typeController.GetContentTypes() where t.ContentType == contentTypeName select t); + + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == contentTypeName select t; int contentTypeID; - if (colContentTypes.Count() > 0) { + if (colContentTypes.Count() > 0) + { var contentType = colContentTypes.Single(); contentTypeID = contentType == null ? CreateContentType(contentTypeName) : contentType.ContentTypeId; - } else { + } + else + { contentTypeID = CreateContentType(contentTypeName); } - var objContent = new ContentItem { + var objContent = new ContentItem + { Content = objItem.RoleName, ContentTypeId = contentTypeID, Indexed = false, ContentKey = "GroupId=" + objItem.RoleID, ModuleID = -1, - TabID = tabId + TabID = tabId, }; objContent.ContentItemId = Util.GetContentController().AddContentItem(objContent); // Add Terms - //var cntTerm = new Terms(); - //cntTerm.ManageQuestionTerms(objPost, objContent); - + // var cntTerm = new Terms(); + // cntTerm.ManageQuestionTerms(objPost, objContent); return objContent; } /// /// This is used to update the content in the ContentItems table. Should be called when a question is updated. /// - internal void UpdateContentItem(RoleInfo objItem, int tabId) { - ContentItem objContent = null; //Util.GetContentController().; - - if (objContent == null) return; + internal void UpdateContentItem(RoleInfo objItem, int tabId) + { + ContentItem objContent = null; // Util.GetContentController().; + + if (objContent == null) + { + return; + } + objContent.Content = objItem.RoleName; objContent.TabID = tabId; objContent.ContentKey = "GroupId=" + objItem.RoleID; // we reset this just in case the page changed. @@ -66,59 +103,43 @@ internal void UpdateContentItem(RoleInfo objItem, int tabId) { Util.GetContentController().UpdateContentItem(objContent); // Update Terms - //var cntTerm = new Terms(); - //cntTerm.ManageQuestionTerms(objPost, objContent); + // var cntTerm = new Terms(); + // cntTerm.ManageQuestionTerms(objPost, objContent); } /// /// This removes a content item associated with a question/thread from the data store. Should run every time an entire thread is deleted. /// /// - internal void DeleteContentItem(int contentItemID) { - if (contentItemID <= Null.NullInteger) return; + internal void DeleteContentItem(int contentItemID) + { + if (contentItemID <= Null.NullInteger) + { + return; + } + var objContent = Util.GetContentController().GetContentItem(contentItemID); - if (objContent == null) return; - - // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) - //var cntTerms = new Terms(); - //cntTerms.RemoveQuestionTerms(objContent); - + if (objContent == null) + { + return; + } + + // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) + // var cntTerms = new Terms(); + // cntTerms.RemoveQuestionTerms(objContent); Util.GetContentController().DeleteContentItem(objContent); } - - /// - /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. - /// - /// The primary key value (ContentTypeID) from the core API's Content Types table. - internal static int GetContentTypeID(string ContentTypeName) { - var typeController = new ContentTypeController(); - var colContentTypes = (from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t); - int contentTypeId; - - if (colContentTypes.Count() > 0) { - var contentType = colContentTypes.Single(); - contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; - } else { - contentTypeId = CreateContentType(ContentTypeName); - } - - return contentTypeId; - } - - #region Private Methods - + /// /// Creates a Content Type (for taxonomy) in the data store. /// /// The primary key value of the new ContentType. - private static int CreateContentType(string ContentTypeName) { + private static int CreateContentType(string ContentTypeName) + { var typeController = new ContentTypeController(); var objContentType = new ContentType { ContentType = ContentTypeName }; return typeController.AddContentType(objContentType); - } - - #endregion - + } } } diff --git a/DNN Platform/Modules/Groups/Components/GroupInfo.cs b/DNN Platform/Modules/Groups/Components/GroupInfo.cs index c46e2f2c2d5..acced559719 100644 --- a/DNN Platform/Modules/Groups/Components/GroupInfo.cs +++ b/DNN Platform/Modules/Groups/Components/GroupInfo.cs @@ -1,141 +1,168 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Xml; -using System.Xml.Serialization; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Security.Roles; -using System.Collections; -using DotNetNuke.Security.Roles.Internal; -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Groups { - public class GroupInfo : RoleInfo, IPropertyAccess + using System; + using System.Collections; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Tokens; + + public class GroupInfo : RoleInfo, IPropertyAccess { - //private RoleInfo roleInfo; - public GroupInfo() { - + // private RoleInfo roleInfo; + public GroupInfo() + { } - public GroupInfo(RoleInfo roleInfo) { - RoleID = roleInfo.RoleID; - RoleName = roleInfo.RoleName; - Description = roleInfo.Description; - PortalID = roleInfo.PortalID; - SecurityMode = roleInfo.SecurityMode; - ServiceFee = roleInfo.ServiceFee; - RSVPCode = roleInfo.RSVPCode; - - - - - + + public GroupInfo(RoleInfo roleInfo) + { + this.RoleID = roleInfo.RoleID; + this.RoleName = roleInfo.RoleName; + this.Description = roleInfo.Description; + this.PortalID = roleInfo.PortalID; + this.SecurityMode = roleInfo.SecurityMode; + this.ServiceFee = roleInfo.ServiceFee; + this.RSVPCode = roleInfo.RSVPCode; } - //public RoleInfo Role { + + // public RoleInfo Role { // get { // return roleInfo; // } // set { // roleInfo = value; // } - //} - //public int GroupId { + // } + // public int GroupId { // get { // return RoleID; // } - //} - - //public int ModuleId { get; set; } + // } - - public string Street { - get { - return GetString("Street", string.Empty); - } - set { - SetString("Street",value); + // public int ModuleId { get; set; } + public string Street + { + get + { + return this.GetString("Street", string.Empty); + } + + set + { + this.SetString("Street", value); } } - public string City { - get { - return GetString("City", string.Empty); - } - set { - SetString("City", value); + + public string City + { + get + { + return this.GetString("City", string.Empty); + } + + set + { + this.SetString("City", value); } } - public string Region { - get { - return GetString("Region", string.Empty); + public string Region + { + get + { + return this.GetString("Region", string.Empty); } - set { - SetString("Region",value); + + set + { + this.SetString("Region", value); } } - public string Country { - get { - return GetString("Country", string.Empty); + public string Country + { + get + { + return this.GetString("Country", string.Empty); } - set { - SetString("Country",value); + + set + { + this.SetString("Country", value); } } - public string PostalCode { - get { - return GetString("PostalCode", string.Empty); + public string PostalCode + { + get + { + return this.GetString("PostalCode", string.Empty); } - set { - SetString("PostalCode",value); + + set + { + this.SetString("PostalCode", value); } } - public string Website { - get { - return GetString("Website", string.Empty); + public string Website + { + get + { + return this.GetString("Website", string.Empty); } - set { - SetString("Website",value); + + set + { + this.SetString("Website", value); } } - - - public bool Featured { - get { - return Convert.ToBoolean(GetString("Featured","false")); - } - set { - SetString("Featured", value.ToString()); + + public bool Featured + { + get + { + return Convert.ToBoolean(this.GetString("Featured", "false")); + } + + set + { + this.SetString("Featured", value.ToString()); } } - - - - - private string GetString(string keyName, string defaultValue) { - if (Settings == null) { + + private string GetString(string keyName, string defaultValue) + { + if (this.Settings == null) + { return defaultValue; } - if (Settings.ContainsKey(keyName)) { - return Settings[keyName]; - } else { + + if (this.Settings.ContainsKey(keyName)) + { + return this.Settings[keyName]; + } + else + { return defaultValue; } } - private void SetString(string keyName, string value) { - if (Settings.ContainsKey(keyName)) { - Settings[keyName] = value; - } else { - Settings.Add(keyName, value); + + private void SetString(string keyName, string value) + { + if (this.Settings.ContainsKey(keyName)) + { + this.Settings[keyName] = value; + } + else + { + this.Settings.Add(keyName, value); } } - } } diff --git a/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs b/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs index f5a80b4a069..294c08c2adb 100644 --- a/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs +++ b/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs @@ -1,25 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Services.Journal; -using DotNetNuke.Entities.Groups; -using DotNetNuke.Security.Roles; -using DotNetNuke.Entities.Users; - -namespace DotNetNuke.Modules.Groups.Components { - public class GroupItemTokenReplace : Services.Tokens.BaseCustomTokenReplace { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Groups.Components +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Entities.Groups; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Journal; + using DotNetNuke.Services.Tokens; + + public class GroupItemTokenReplace : Services.Tokens.BaseCustomTokenReplace + { public GroupItemTokenReplace(RoleInfo groupInfo) { - PropertySource["groupitem"] = groupInfo; + this.PropertySource["groupitem"] = groupInfo; } - public string ReplaceGroupItemTokens(string source) { - return base.ReplaceTokens(source); + + public string ReplaceGroupItemTokens(string source) + { + return this.ReplaceTokens(source); } } } diff --git a/DNN Platform/Modules/Groups/Components/GroupMemberType.cs b/DNN Platform/Modules/Groups/Components/GroupMemberType.cs index 673f4843b76..1d8f717a27e 100644 --- a/DNN Platform/Modules/Groups/Components/GroupMemberType.cs +++ b/DNN Platform/Modules/Groups/Components/GroupMemberType.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups.Components { internal class GroupMemberType { public int GroupMemberTypeId { get; set; } + public string GroupMemberTypeName { get; set; } } } diff --git a/DNN Platform/Modules/Groups/Components/GroupUtilities.cs b/DNN Platform/Modules/Groups/Components/GroupUtilities.cs index 7389f15b33e..747261aedba 100644 --- a/DNN Platform/Modules/Groups/Components/GroupUtilities.cs +++ b/DNN Platform/Modules/Groups/Components/GroupUtilities.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Journal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Groups.Components { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Journal; + public class GroupUtilities { public static void CreateJournalEntry(RoleInfo roleInfo, UserInfo createdBy) { var journalController = JournalController.Instance; var journalItem = new JournalItem(); - - string url = ""; - + + string url = string.Empty; + if (roleInfo.Settings.ContainsKey("URL")) { url = roleInfo.Settings["URL"]; @@ -33,23 +28,25 @@ public static void CreateJournalEntry(RoleInfo roleInfo, UserInfo createdBy) journalItem.ProfileId = createdBy.UserID; journalItem.UserId = createdBy.UserID; journalItem.Title = roleInfo.RoleName; - journalItem.ItemData = new ItemData {Url = url}; + journalItem.ItemData = new ItemData { Url = url }; journalItem.SocialGroupId = roleInfo.RoleID; journalItem.Summary = roleInfo.Description; journalItem.Body = null; journalItem.JournalTypeId = journalController.GetJournalType("groupcreate").JournalTypeId; journalItem.ObjectKey = string.Format("groupcreate:{0}:{1}", roleInfo.RoleID.ToString(CultureInfo.InvariantCulture), createdBy.UserID.ToString(CultureInfo.InvariantCulture)); - - if (journalController.GetJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey) != null) - journalController.DeleteJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey); - - + + if (journalController.GetJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey) != null) + { + journalController.DeleteJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey); + } + journalItem.SecuritySet = string.Empty; - - if (roleInfo.IsPublic) - journalItem.SecuritySet += "E,"; - - + + if (roleInfo.IsPublic) + { + journalItem.SecuritySet += "E,"; + } + journalController.SaveJournalItem(journalItem, null); } } diff --git a/DNN Platform/Modules/Groups/Components/GroupViewParser.cs b/DNN Platform/Modules/Groups/Components/GroupViewParser.cs index 31eefbd4396..7cc312d6a42 100644 --- a/DNN Platform/Modules/Groups/Components/GroupViewParser.cs +++ b/DNN Platform/Modules/Groups/Components/GroupViewParser.cs @@ -1,40 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Roles; -using DotNetNuke.Entities.Users; -using DotNetNuke.Common; -using DotNetNuke.Services.Localization; -using DotNetNuke.Abstractions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups.Components { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + public class GroupViewParser { - protected INavigationManager NavigationManager { get; } - PortalSettings PortalSettings { get; set; } - RoleInfo RoleInfo { get; set; } - UserInfo CurrentUser { get; set; } - public string Template { get; set; } - public int GroupViewTabId { get; set; } - public string GroupEditUrl { get; set; } - public GroupViewParser(PortalSettings portalSettings, RoleInfo roleInfo, UserInfo currentUser, string template, int groupViewTabId) { - PortalSettings = portalSettings; - RoleInfo = roleInfo; - CurrentUser = currentUser; - Template = template; - GroupViewTabId = groupViewTabId; - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.PortalSettings = portalSettings; + this.RoleInfo = roleInfo; + this.CurrentUser = currentUser; + this.Template = template; + this.GroupViewTabId = groupViewTabId; + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string Template { get; set; } + + public int GroupViewTabId { get; set; } + + protected INavigationManager NavigationManager { get; } + + private PortalSettings PortalSettings { get; set; } + + private RoleInfo RoleInfo { get; set; } + + private UserInfo CurrentUser { get; set; } + + public string GroupEditUrl { get; set; } public string ParseView() { @@ -43,7 +50,7 @@ public string ParseView() if (HttpContext.Current.Request.IsAuthenticated) { - var userRoleInfo = CurrentUser.Social.Roles.FirstOrDefault(r => r.RoleID == RoleInfo.RoleID); + var userRoleInfo = this.CurrentUser.Social.Roles.FirstOrDefault(r => r.RoleID == this.RoleInfo.RoleID); if (userRoleInfo != null) { @@ -53,7 +60,8 @@ public string ParseView() membershipPending = true; } } - if (RoleInfo.CreatedByUserID == CurrentUser.UserID || CurrentUser.IsSuperUser) + + if (this.RoleInfo.CreatedByUserID == this.CurrentUser.UserID || this.CurrentUser.IsSuperUser) { isOwner = true; } @@ -63,44 +71,49 @@ public string ParseView() if (isOwner) { - - Template = Template.Replace("[GROUPEDITBUTTON]", String.Format(editUrl, GroupEditUrl)); - Template = Utilities.ParseTokenWrapper(Template, "IsNotOwner", false); - Template = Utilities.ParseTokenWrapper(Template, "IsOwner", true); + this.Template = this.Template.Replace("[GROUPEDITBUTTON]", string.Format(editUrl, this.GroupEditUrl)); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotOwner", false); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsOwner", true); } - else if (CurrentUser.IsInRole(RoleInfo.RoleName)) + else if (this.CurrentUser.IsInRole(this.RoleInfo.RoleName)) { - Template = Utilities.ParseTokenWrapper(Template, "IsNotOwner", true); - Template = Utilities.ParseTokenWrapper(Template, "IsOwner", false); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotOwner", true); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsOwner", false); } - Template = Utilities.ParseTokenWrapper(Template, "IsNotOwner", false); - Template = Utilities.ParseTokenWrapper(Template, "IsOwner", false); - - if (CurrentUser.IsInRole(RoleInfo.RoleName) || !HttpContext.Current.Request.IsAuthenticated || membershipPending) - Template = Utilities.ParseTokenWrapper(Template, "IsNotMember", false); - else - Template = Utilities.ParseTokenWrapper(Template, "IsNotMember", true); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotOwner", false); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsOwner", false); - if (CurrentUser.IsInRole(RoleInfo.RoleName)) + if (this.CurrentUser.IsInRole(this.RoleInfo.RoleName) || !HttpContext.Current.Request.IsAuthenticated || membershipPending) + { + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotMember", false); + } + else + { + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotMember", true); + } + + if (this.CurrentUser.IsInRole(this.RoleInfo.RoleName)) { - Template = Utilities.ParseTokenWrapper(Template, "IsMember", true); - Template = Utilities.ParseTokenWrapper(Template, "IsPendingMember", false); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsMember", true); + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsPendingMember", false); } - else - Template = Utilities.ParseTokenWrapper(Template, "IsMember", false); - - Template = Utilities.ParseTokenWrapper(Template, "AllowJoin", RoleInfo.IsPublic); + else + { + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsMember", false); + } + + this.Template = Utilities.ParseTokenWrapper(this.Template, "AllowJoin", this.RoleInfo.IsPublic); - Template = Template.Replace("[GROUPEDITBUTTON]", String.Empty); + this.Template = this.Template.Replace("[GROUPEDITBUTTON]", string.Empty); - var url = NavigationManager.NavigateURL(GroupViewTabId, "", new String[] { "groupid=" + RoleInfo.RoleID.ToString() }); + var url = this.NavigationManager.NavigateURL(this.GroupViewTabId, string.Empty, new string[] { "groupid=" + this.RoleInfo.RoleID.ToString() }); - Template = Utilities.ParseTokenWrapper(Template, "IsPendingMember", membershipPending); - Template = Template.Replace("[groupviewurl]", url); - Components.GroupItemTokenReplace tokenReplace = new Components.GroupItemTokenReplace(RoleInfo); - Template = tokenReplace.ReplaceGroupItemTokens(Template); - return Template; + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsPendingMember", membershipPending); + this.Template = this.Template.Replace("[groupviewurl]", url); + Components.GroupItemTokenReplace tokenReplace = new Components.GroupItemTokenReplace(this.RoleInfo); + this.Template = tokenReplace.ReplaceGroupItemTokens(this.Template); + return this.Template; } } } diff --git a/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs b/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs index b34bab733c2..71384bd1b02 100644 --- a/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs +++ b/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Social.Notifications; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups.Components { + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Social.Notifications; + public class GroupsBusinessController : IUpgradeable { public string UpgradeModule(string version) @@ -16,10 +17,10 @@ public string UpgradeModule(string version) switch (version) { case "06.02.00": - AddNotificationTypes(); + this.AddNotificationTypes(); break; case "06.02.04": - RemoveRejectActionForCreatedNotification(); + this.RemoveRejectActionForCreatedNotification(); break; case "07.00.00": ConvertNotificationTypeActionsFor700(); @@ -41,10 +42,9 @@ private static void ConvertNotificationTypeActionsFor700() if (actions.Any()) { - foreach (var action in actions) { - action.APICall = action.APICall.Replace(".ashx", ""); + action.APICall = action.APICall.Replace(".ashx", string.Empty); NotificationsController.Instance.DeleteNotificationTypeAction(action.NotificationTypeActionId); } @@ -56,106 +56,107 @@ private static void ConvertNotificationTypeActionsFor700() private void RemoveRejectActionForCreatedNotification() { var notificationType = NotificationsController.Instance.GetNotificationType(Constants.GroupCreatedNotification); - if(notificationType == null) + if (notificationType == null) { return; } var action = NotificationsController.Instance.GetNotificationTypeAction(notificationType.NotificationTypeId, "RejectGroup"); - if(action == null) + if (action == null) { return; } + NotificationsController.Instance.DeleteNotificationTypeAction(action.NotificationTypeActionId); } private void AddNotificationTypes() { var actions = new List(); - - //DesktopModule should not be null + + // DesktopModule should not be null var deskModuleId = DesktopModuleController.GetDesktopModuleByFriendlyName("Social Groups").DesktopModuleID; - //GroupPendingNotification - var type = new NotificationType { Name = "GroupPendingNotification", Description = "Group Pending Notification", DesktopModuleId = deskModuleId}; + // GroupPendingNotification + var type = new NotificationType { Name = "GroupPendingNotification", Description = "Group Pending Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { - actions.Add(new NotificationTypeAction - { - NameResourceKey = "Approve", - DescriptionResourceKey = "ApproveGroup", - APICall = "API/SocialGroups/ModerationService/ApproveGroup" - }); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "RejectGroup", - DescriptionResourceKey = "RejectGroup", - APICall = "API/SocialGroups/ModerationService/RejectGroup" - }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "Approve", + DescriptionResourceKey = "ApproveGroup", + APICall = "API/SocialGroups/ModerationService/ApproveGroup", + }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "RejectGroup", + DescriptionResourceKey = "RejectGroup", + APICall = "API/SocialGroups/ModerationService/RejectGroup", + }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); } - //GroupApprovedNotification + // GroupApprovedNotification type = new NotificationType { Name = "GroupApprovedNotification", Description = "Group Approved Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { NotificationsController.Instance.CreateNotificationType(type); } - //GroupCreatedNotification + // GroupCreatedNotification type = new NotificationType { Name = "GroupCreatedNotification", Description = "Group Created Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { actions.Clear(); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "RejectGroup", - DescriptionResourceKey = "RejectGroup", - ConfirmResourceKey = "DeleteItem", - APICall = "API/SocialGroups/ModerationService/RejectGroup" - }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "RejectGroup", + DescriptionResourceKey = "RejectGroup", + ConfirmResourceKey = "DeleteItem", + APICall = "API/SocialGroups/ModerationService/RejectGroup", + }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); } - //GroupRejectedNotification + // GroupRejectedNotification type = new NotificationType { Name = "GroupRejectedNotification", Description = "Group Rejected Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { NotificationsController.Instance.CreateNotificationType(type); } - //GroupMemberPendingNotification + // GroupMemberPendingNotification type = new NotificationType { Name = "GroupMemberPendingNotification", Description = "Group Member Pending Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { actions.Clear(); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "Approve", - DescriptionResourceKey = "ApproveGroupMember", - ConfirmResourceKey = "", - APICall = "API/SocialGroups/ModerationService/ApproveMember" - }); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "RejectMember", - DescriptionResourceKey = "RejectGroupMember", - APICall = "API/SocialGroups/ModerationService/RejectMember" - }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "Approve", + DescriptionResourceKey = "ApproveGroupMember", + ConfirmResourceKey = string.Empty, + APICall = "API/SocialGroups/ModerationService/ApproveMember", + }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "RejectMember", + DescriptionResourceKey = "RejectGroupMember", + APICall = "API/SocialGroups/ModerationService/RejectMember", + }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); } - //GroupMemberApprovedNotification + // GroupMemberApprovedNotification type = new NotificationType { Name = "GroupMemberApprovedNotification", Description = "Group Member Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { NotificationsController.Instance.CreateNotificationType(type); } - //GroupMemberRejectedNotification + // GroupMemberRejectedNotification type = new NotificationType { Name = "GroupMemberRejectedNotification", Description = "Group Rejected Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { diff --git a/DNN Platform/Modules/Groups/Components/GroupsRouteMapper.cs b/DNN Platform/Modules/Groups/Components/GroupsRouteMapper.cs index a81a54994b2..eaabd0f512b 100644 --- a/DNN Platform/Modules/Groups/Components/GroupsRouteMapper.cs +++ b/DNN Platform/Modules/Groups/Components/GroupsRouteMapper.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Web.Api; - -namespace DotNetNuke.Modules.Groups +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Groups { - public class ServiceRouteMapper : IServiceRouteMapper + using System; + + using DotNetNuke.Web.Api; + + public class ServiceRouteMapper : IServiceRouteMapper { - public void RegisterRoutes(IMapRoute mapRouteManager) + public void RegisterRoutes(IMapRoute mapRouteManager) { mapRouteManager.MapHttpRoute("SocialGroups", "default", "{controller}/{action}", new[] { "DotNetNuke.Modules.Groups" }); } diff --git a/DNN Platform/Modules/Groups/Components/Notifications.cs b/DNN Platform/Modules/Groups/Components/Notifications.cs index 092717f6b1e..ac4dd2be9a0 100644 --- a/DNN Platform/Modules/Groups/Components/Notifications.cs +++ b/DNN Platform/Modules/Groups/Components/Notifications.cs @@ -1,27 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Localization; -using DotNetNuke.Common; - -namespace DotNetNuke.Modules.Groups.Components { - public class Notifications { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Groups.Components +{ + using System; + using System.Collections.Generic; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Notifications; + + public class Notifications + { internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators) { - return AddGroupNotification(notificationTypeName, tabId, moduleId, group, initiatingUser, moderators, null as UserInfo); + return this.AddGroupNotification(notificationTypeName, tabId, moduleId, group, initiatingUser, moderators, null as UserInfo); + } + + internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators, UserInfo recipient) + { + return this.AddGroupNotification(notificationTypeName, tabId, moduleId, group, initiatingUser, moderators, recipient == null ? null : new List { recipient }); } - internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators, UserInfo recipient) - { - return AddGroupNotification(notificationTypeName, tabId, moduleId, group, initiatingUser, moderators, recipient == null ? null : new List { recipient }); - } - internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators, IList recipients) { + + internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators, IList recipients) + { var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName); var tokenReplace = new GroupItemTokenReplace(group); @@ -29,31 +34,32 @@ internal virtual Notification AddGroupNotification(string notificationTypeName, subject = tokenReplace.ReplaceGroupItemTokens(subject); var body = Localization.GetString(notificationTypeName + ".Body", Constants.SharedResourcesPath); - + body = tokenReplace.ReplaceGroupItemTokens(body); body = body.Replace("Public.Text", Localization.GetString("Public.Text", Constants.SharedResourcesPath)); body = body.Replace("Private.Text", Localization.GetString("Private.Text", Constants.SharedResourcesPath)); bool dismiss = notificationTypeName != Constants.GroupPendingNotification; - var notification = new Notification - { - NotificationTypeID = notificationType.NotificationTypeId, - Subject = subject, - Body = body, - IncludeDismissAction = dismiss, - SenderUserID = initiatingUser.UserID, - Context = String.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID) - }; + var notification = new Notification + { + NotificationTypeID = notificationType.NotificationTypeId, + Subject = subject, + Body = body, + IncludeDismissAction = dismiss, + SenderUserID = initiatingUser.UserID, + Context = string.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID), + }; NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, moderators, recipients); return notification; } - internal virtual Notification AddGroupOwnerNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser) + + internal virtual Notification AddGroupOwnerNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser) { var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName); var tokenReplace = new GroupItemTokenReplace(group); - + var subject = Localization.GetString(notificationTypeName + ".Subject", Constants.SharedResourcesPath); var body = Localization.GetString(notificationTypeName + ".Body", Constants.SharedResourcesPath); subject = subject.Replace("[DisplayName]", initiatingUser.DisplayName); @@ -74,11 +80,10 @@ internal virtual Notification AddGroupOwnerNotification(string notificationTypeN roleOwners.Add(UserController.GetUserById(group.PortalID, userRoleInfo.UserID)); } } + roleOwners.Add(roleCreator); - - - - //Need to add from sender details + + // Need to add from sender details var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, @@ -86,13 +91,15 @@ internal virtual Notification AddGroupOwnerNotification(string notificationTypeN Body = body, IncludeDismissAction = true, SenderUserID = initiatingUser.UserID, - Context = String.Format("{0}:{1}:{2}:{3}", tabId, moduleId, group.RoleID, initiatingUser.UserID) + Context = string.Format("{0}:{1}:{2}:{3}", tabId, moduleId, group.RoleID, initiatingUser.UserID), }; NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, roleOwners); return notification; } - internal virtual Notification AddMemberNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo sender, UserInfo recipient) { + + internal virtual Notification AddMemberNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo sender, UserInfo recipient) + { var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName); var subject = Localization.GetString(notificationTypeName + ".Subject", Constants.SharedResourcesPath); @@ -106,7 +113,7 @@ internal virtual Notification AddMemberNotification(string notificationTypeName, body = body.Replace("[ProfileUrl]", Globals.UserProfileURL(recipient.UserID)); body = tokenReplace.ReplaceGroupItemTokens(body); - //Need to add from sender details + // Need to add from sender details var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, @@ -114,7 +121,7 @@ internal virtual Notification AddMemberNotification(string notificationTypeName, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID, - Context = String.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID) + Context = string.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID), }; NotificationsController.Instance.SendNotification(notification, recipient.PortalID, null, new List { recipient }); diff --git a/DNN Platform/Modules/Groups/Components/Utilities.cs b/DNN Platform/Modules/Groups/Components/Utilities.cs index 2678b923f00..12af3904236 100644 --- a/DNN Platform/Modules/Groups/Components/Utilities.cs +++ b/DNN Platform/Modules/Groups/Components/Utilities.cs @@ -1,38 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Text.RegularExpressions; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; - -namespace DotNetNuke.Modules.Groups { - public class Utilities { - internal static string ParseTokenWrapper(string Template, string Token, bool Condition) { - var pattern = "(\\[" + Token + "\\](.*?)\\[\\/" + Token + "\\])"; - var regExp = RegexUtils.GetCachedRegex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline); - var matches = regExp.Matches(Template); - foreach (Match match in matches) - { - Template = Template.Replace(match.Value, Condition ? match.Groups[2].Value : string.Empty); - } - return Template; - } +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Groups +{ + using System; + using System.Text.RegularExpressions; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using Microsoft.Extensions.DependencyInjection; + + public class Utilities + { public static string NavigateUrl(int TabId, string[] @params) { - return Globals.DependencyProvider.GetRequiredService()?.NavigateURL(TabId, "", @params); + return Globals.DependencyProvider.GetRequiredService()?.NavigateURL(TabId, string.Empty, @params); } + public static string[] AddParams(string param, string[] currParams) { var tmpParams = new string[] { param }; var intLength = tmpParams.Length; var currLength = currParams.Length; - Array.Resize(ref tmpParams, (intLength + currLength)); + Array.Resize(ref tmpParams, intLength + currLength); currParams.CopyTo(tmpParams, intLength); return tmpParams; } + + internal static string ParseTokenWrapper(string Template, string Token, bool Condition) + { + var pattern = "(\\[" + Token + "\\](.*?)\\[\\/" + Token + "\\])"; + var regExp = RegexUtils.GetCachedRegex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline); + var matches = regExp.Matches(Template); + foreach (Match match in matches) + { + Template = Template.Replace(match.Value, Condition ? match.Groups[2].Value : string.Empty); + } + + return Template; + } } } diff --git a/DNN Platform/Modules/Groups/Create.ascx.cs b/DNN Platform/Modules/Groups/Create.ascx.cs index a8e0ee50c0f..27877ac071d 100644 --- a/DNN Platform/Modules/Groups/Create.ascx.cs +++ b/DNN Platform/Modules/Groups/Create.ascx.cs @@ -1,98 +1,99 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Common; -using DotNetNuke.Security.Roles; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.FileSystem; -using System.IO; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Modules.Groups.Components; -using DotNetNuke.Abstractions; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups { - + using System; + using System.Collections.Generic; + using System.IO; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + using Microsoft.Extensions.DependencyInjection; + public partial class Create : GroupsModuleBase { private readonly INavigationManager _navigationManager; + public Create() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); } + protected override void OnInit(EventArgs e) { - InitializeComponent(); + this.InitializeComponent(); base.OnInit(e); } - - private void InitializeComponent() + + protected void Page_Load(object sender, EventArgs e) { - Load += Page_Load; - btnCreate.Click += Create_Click; - btnCancel.Click += Cancel_Click; + JavaScript.RequestRegistration(CommonJs.DnnPlugins); } - - protected void Page_Load(object sender, EventArgs e) + private void InitializeComponent() { - JavaScript.RequestRegistration(CommonJs.DnnPlugins); + this.Load += this.Page_Load; + this.btnCreate.Click += this.Create_Click; + this.btnCancel.Click += this.Cancel_Click; } private void Cancel_Click(object sender, EventArgs e) { - Response.Redirect(ModuleContext.NavigateUrl(TabId, string.Empty, false, null)); + this.Response.Redirect(this.ModuleContext.NavigateUrl(this.TabId, string.Empty, false, null)); } + private void Create_Click(object sender, EventArgs e) { var ps = Security.PortalSecurity.Instance; - txtGroupName.Text = ps.InputFilter(txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoScripting); - txtGroupName.Text = ps.InputFilter(txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoMarkup); + this.txtGroupName.Text = ps.InputFilter(this.txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoScripting); + this.txtGroupName.Text = ps.InputFilter(this.txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoMarkup); - txtDescription.Text = ps.InputFilter(txtDescription.Text, Security.PortalSecurity.FilterFlag.NoScripting); - txtDescription.Text = ps.InputFilter(txtDescription.Text, Security.PortalSecurity.FilterFlag.NoMarkup); - if (RoleController.Instance.GetRoleByName(PortalId, txtGroupName.Text) != null) + this.txtDescription.Text = ps.InputFilter(this.txtDescription.Text, Security.PortalSecurity.FilterFlag.NoScripting); + this.txtDescription.Text = ps.InputFilter(this.txtDescription.Text, Security.PortalSecurity.FilterFlag.NoMarkup); + if (RoleController.Instance.GetRoleByName(this.PortalId, this.txtGroupName.Text) != null) { - lblInvalidGroupName.Visible = true; + this.lblInvalidGroupName.Visible = true; return; } - - + var modRoles = new List(); - var modUsers = new List(); - foreach (ModulePermissionInfo modulePermissionInfo in ModulePermissionController.GetModulePermissions(ModuleId, TabId)) + var modUsers = new List(); + foreach (ModulePermissionInfo modulePermissionInfo in ModulePermissionController.GetModulePermissions(this.ModuleId, this.TabId)) { if (modulePermissionInfo.PermissionKey == "MODGROUP" && modulePermissionInfo.AllowAccess) { - if (modulePermissionInfo.RoleID > int.Parse(Globals.glbRoleNothing)) - { - modRoles.Add(RoleController.Instance.GetRoleById(PortalId, modulePermissionInfo.RoleID)); - } - else if (modulePermissionInfo.UserID > Null.NullInteger) - { - modUsers.Add(UserController.GetUserById(PortalId, modulePermissionInfo.UserID)); - } + if (modulePermissionInfo.RoleID > int.Parse(Globals.glbRoleNothing)) + { + modRoles.Add(RoleController.Instance.GetRoleById(this.PortalId, modulePermissionInfo.RoleID)); + } + else if (modulePermissionInfo.UserID > Null.NullInteger) + { + modUsers.Add(UserController.GetUserById(this.PortalId, modulePermissionInfo.UserID)); + } } } var roleInfo = new RoleInfo() { - PortalID = PortalId, - RoleName = txtGroupName.Text, - Description = txtDescription.Text, + PortalID = this.PortalId, + RoleName = this.txtGroupName.Text, + Description = this.txtDescription.Text, SecurityMode = SecurityMode.SocialGroup, Status = RoleStatus.Approved, - IsPublic = rdAccessTypePublic.Checked + IsPublic = this.rdAccessTypePublic.Checked, }; var userRoleStatus = RoleStatus.Pending; - if (GroupModerationEnabled) + if (this.GroupModerationEnabled) { roleInfo.Status = RoleStatus.Pending; userRoleStatus = RoleStatus.Pending; @@ -102,74 +103,76 @@ private void Create_Click(object sender, EventArgs e) userRoleStatus = RoleStatus.Approved; } - var objModulePermissions = new ModulePermissionCollection(CBO.FillCollection(DataProvider.Instance().GetModulePermissionsByModuleID(ModuleId, -1), typeof(ModulePermissionInfo))); + var objModulePermissions = new ModulePermissionCollection(CBO.FillCollection(DataProvider.Instance().GetModulePermissionsByModuleID(this.ModuleId, -1), typeof(ModulePermissionInfo))); if (ModulePermissionController.HasModulePermission(objModulePermissions, "MODGROUP")) { roleInfo.Status = RoleStatus.Approved; userRoleStatus = RoleStatus.Approved; } - var roleGroupId = DefaultRoleGroupId; - if (roleGroupId < Null.NullInteger) - { - roleGroupId = Null.NullInteger; - } - roleInfo.RoleGroupID = roleGroupId; + var roleGroupId = this.DefaultRoleGroupId; + if (roleGroupId < Null.NullInteger) + { + roleGroupId = Null.NullInteger; + } + + roleInfo.RoleGroupID = roleGroupId; roleInfo.RoleID = RoleController.Instance.AddRole(roleInfo); - roleInfo = RoleController.Instance.GetRoleById(PortalId, roleInfo.RoleID); + roleInfo = RoleController.Instance.GetRoleById(this.PortalId, roleInfo.RoleID); - var groupUrl = _navigationManager.NavigateURL(GroupViewTabId, "", new String[] {"groupid=" + roleInfo.RoleID.ToString()}); - if (groupUrl.StartsWith("http://") || groupUrl.StartsWith("https://")) - { - const int startIndex = 8; // length of https:// - groupUrl = groupUrl.Substring(groupUrl.IndexOf("/", startIndex, StringComparison.InvariantCultureIgnoreCase)); - } - roleInfo.Settings.Add("URL", groupUrl); + var groupUrl = this._navigationManager.NavigateURL(this.GroupViewTabId, string.Empty, new string[] { "groupid=" + roleInfo.RoleID.ToString() }); + if (groupUrl.StartsWith("http://") || groupUrl.StartsWith("https://")) + { + const int startIndex = 8; // length of https:// + groupUrl = groupUrl.Substring(groupUrl.IndexOf("/", startIndex, StringComparison.InvariantCultureIgnoreCase)); + } + + roleInfo.Settings.Add("URL", groupUrl); - roleInfo.Settings.Add("GroupCreatorName", UserInfo.DisplayName); - roleInfo.Settings.Add("ReviewMembers", chkMemberApproved.Checked.ToString()); + roleInfo.Settings.Add("GroupCreatorName", this.UserInfo.DisplayName); + roleInfo.Settings.Add("ReviewMembers", this.chkMemberApproved.Checked.ToString()); RoleController.Instance.UpdateRoleSettings(roleInfo, true); - if (inpFile.PostedFile != null && inpFile.PostedFile.ContentLength > 0) + if (this.inpFile.PostedFile != null && this.inpFile.PostedFile.ContentLength > 0) { IFileManager _fileManager = FileManager.Instance; IFolderManager _folderManager = FolderManager.Instance; - var rootFolderPath = PathUtils.Instance.FormatFolderPath(PortalSettings.HomeDirectory); + var rootFolderPath = PathUtils.Instance.FormatFolderPath(this.PortalSettings.HomeDirectory); - IFolderInfo groupFolder = _folderManager.GetFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); + IFolderInfo groupFolder = _folderManager.GetFolder(this.PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); if (groupFolder == null) { - groupFolder = _folderManager.AddFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); + groupFolder = _folderManager.AddFolder(this.PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); } + if (groupFolder != null) { - var fileName = Path.GetFileName(inpFile.PostedFile.FileName); - var fileInfo = _fileManager.AddFile(groupFolder, fileName, inpFile.PostedFile.InputStream, true); + var fileName = Path.GetFileName(this.inpFile.PostedFile.FileName); + var fileInfo = _fileManager.AddFile(groupFolder, fileName, this.inpFile.PostedFile.InputStream, true); roleInfo.IconFile = "FileID=" + fileInfo.FileId; RoleController.Instance.UpdateRole(roleInfo); } } var notifications = new Notifications(); - - - RoleController.Instance.AddUserRole(PortalId, UserId, roleInfo.RoleID, userRoleStatus, true, Null.NullDate, Null.NullDate); + + RoleController.Instance.AddUserRole(this.PortalId, this.UserId, roleInfo.RoleID, userRoleStatus, true, Null.NullDate, Null.NullDate); if (roleInfo.Status == RoleStatus.Pending) { - //Send notification to Group Moderators to approve/reject group. - notifications.AddGroupNotification(Constants.GroupPendingNotification, GroupViewTabId, ModuleId, roleInfo, UserInfo, modRoles, modUsers); + // Send notification to Group Moderators to approve/reject group. + notifications.AddGroupNotification(Constants.GroupPendingNotification, this.GroupViewTabId, this.ModuleId, roleInfo, this.UserInfo, modRoles, modUsers); } else { - //Send notification to Group Moderators informing of new group. - notifications.AddGroupNotification(Constants.GroupCreatedNotification, GroupViewTabId, ModuleId, roleInfo, UserInfo, modRoles, modUsers); + // Send notification to Group Moderators informing of new group. + notifications.AddGroupNotification(Constants.GroupCreatedNotification, this.GroupViewTabId, this.ModuleId, roleInfo, this.UserInfo, modRoles, modUsers); - //Add entry to journal. - GroupUtilities.CreateJournalEntry(roleInfo, UserInfo); + // Add entry to journal. + GroupUtilities.CreateJournalEntry(roleInfo, this.UserInfo); } - Response.Redirect(ModuleContext.NavigateUrl(TabId, string.Empty, false, null)); + this.Response.Redirect(this.ModuleContext.NavigateUrl(this.TabId, string.Empty, false, null)); } } } diff --git a/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj b/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj index 3a9179c47d5..e173507eaa9 100644 --- a/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj +++ b/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj @@ -202,6 +202,9 @@ + + stylecop.json + Designer @@ -255,7 +258,10 @@ Designer - + + + + diff --git a/DNN Platform/Modules/Groups/GroupEdit.ascx.cs b/DNN Platform/Modules/Groups/GroupEdit.ascx.cs index 591e67c7acc..57b28676f93 100644 --- a/DNN Platform/Modules/Groups/GroupEdit.ascx.cs +++ b/DNN Platform/Modules/Groups/GroupEdit.ascx.cs @@ -1,159 +1,168 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Common.Utilities; -using System.IO; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups { + using System; + using System.IO; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + using Microsoft.Extensions.DependencyInjection; + public partial class GroupEdit : GroupsModuleBase { private readonly INavigationManager _navigationManager; + public GroupEdit() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); } protected override void OnInit(EventArgs e) { - InitializeComponent(); + this.InitializeComponent(); base.OnInit(e); } - - private void InitializeComponent() - { - Load += Page_Load; - btnSave.Click += Save_Click; - btnCancel.Click += Cancel_Click; - } - - + protected void Page_Load(object sender, EventArgs e) { JavaScript.RequestRegistration(CommonJs.DnnPlugins); - imgGroup.Src = Page.ResolveUrl("~/DesktopModules/SocialGroups/Images/") + "sample-group-profile.jpg"; - if (!Page.IsPostBack && GroupId > 0) + this.imgGroup.Src = this.Page.ResolveUrl("~/DesktopModules/SocialGroups/Images/") + "sample-group-profile.jpg"; + if (!this.Page.IsPostBack && this.GroupId > 0) { - var roleInfo = RoleController.Instance.GetRoleById(PortalId, GroupId); + var roleInfo = RoleController.Instance.GetRoleById(this.PortalId, this.GroupId); if (roleInfo != null) { - if (!UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) + if (!this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) { - if (roleInfo.CreatedByUserID != UserInfo.UserID) + if (roleInfo.CreatedByUserID != this.UserInfo.UserID) { - Response.Redirect(ModuleContext.NavigateUrl(TabId, "", false, new String[] { "groupid=" + GroupId.ToString() })); + this.Response.Redirect(this.ModuleContext.NavigateUrl(this.TabId, string.Empty, false, new string[] { "groupid=" + this.GroupId.ToString() })); } } - txtGroupName.Visible = !roleInfo.IsSystemRole; - reqGroupName.Enabled = !roleInfo.IsSystemRole; - - if(!roleInfo.IsSystemRole) - txtGroupName.Text = roleInfo.RoleName; - else - litGroupName.Text = roleInfo.RoleName; - - txtDescription.Text = roleInfo.Description; - rdAccessTypePrivate.Checked = !roleInfo.IsPublic; - rdAccessTypePublic.Checked = roleInfo.IsPublic; - - + this.txtGroupName.Visible = !roleInfo.IsSystemRole; + this.reqGroupName.Enabled = !roleInfo.IsSystemRole; + + if (!roleInfo.IsSystemRole) + { + this.txtGroupName.Text = roleInfo.RoleName; + } + else + { + this.litGroupName.Text = roleInfo.RoleName; + } + + this.txtDescription.Text = roleInfo.Description; + this.rdAccessTypePrivate.Checked = !roleInfo.IsPublic; + this.rdAccessTypePublic.Checked = roleInfo.IsPublic; + if (roleInfo.Settings.ContainsKey("ReviewMembers")) { - chkMemberApproved.Checked = Convert.ToBoolean(roleInfo.Settings["ReviewMembers"].ToString()); + this.chkMemberApproved.Checked = Convert.ToBoolean(roleInfo.Settings["ReviewMembers"].ToString()); } - imgGroup.Src = roleInfo.PhotoURL; + + this.imgGroup.Src = roleInfo.PhotoURL; } else { - Response.Redirect(ModuleContext.NavigateUrl(TabId, "", false)); + this.Response.Redirect(this.ModuleContext.NavigateUrl(this.TabId, string.Empty, false)); } } } + + private void InitializeComponent() + { + this.Load += this.Page_Load; + this.btnSave.Click += this.Save_Click; + this.btnCancel.Click += this.Cancel_Click; + } + private void Cancel_Click(object sender, EventArgs e) { - Response.Redirect(ModuleContext.NavigateUrl(TabId, "", false, new String[] { "groupid=" + GroupId.ToString() })); + this.Response.Redirect(this.ModuleContext.NavigateUrl(this.TabId, string.Empty, false, new string[] { "groupid=" + this.GroupId.ToString() })); } private void Save_Click(object sender, EventArgs e) { - if (GroupId > 0) + if (this.GroupId > 0) { Security.PortalSecurity ps = Security.PortalSecurity.Instance; - txtGroupName.Text = ps.InputFilter(txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoScripting); - txtGroupName.Text = ps.InputFilter(txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoMarkup); - txtDescription.Text = ps.InputFilter(txtDescription.Text, Security.PortalSecurity.FilterFlag.NoScripting); - txtDescription.Text = ps.InputFilter(txtDescription.Text, Security.PortalSecurity.FilterFlag.NoMarkup); + this.txtGroupName.Text = ps.InputFilter(this.txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoScripting); + this.txtGroupName.Text = ps.InputFilter(this.txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoMarkup); + this.txtDescription.Text = ps.InputFilter(this.txtDescription.Text, Security.PortalSecurity.FilterFlag.NoScripting); + this.txtDescription.Text = ps.InputFilter(this.txtDescription.Text, Security.PortalSecurity.FilterFlag.NoMarkup); - var roleInfo = RoleController.Instance.GetRoleById(PortalId, GroupId); + var roleInfo = RoleController.Instance.GetRoleById(this.PortalId, this.GroupId); if (roleInfo != null) { - - if (txtGroupName.Visible) //if this is visible assume that we're editing the groupname + if (this.txtGroupName.Visible) // if this is visible assume that we're editing the groupname { - if (txtGroupName.Text != roleInfo.RoleName) + if (this.txtGroupName.Text != roleInfo.RoleName) { - if (RoleController.Instance.GetRoleByName(PortalId, txtGroupName.Text) != null) + if (RoleController.Instance.GetRoleByName(this.PortalId, this.txtGroupName.Text) != null) { - lblInvalidGroupName.Visible = true; + this.lblInvalidGroupName.Visible = true; return; } } } - if(!roleInfo.IsSystemRole) + if (!roleInfo.IsSystemRole) { - roleInfo.RoleName = txtGroupName.Text; + roleInfo.RoleName = this.txtGroupName.Text; } - roleInfo.Description = txtDescription.Text; - roleInfo.IsPublic = rdAccessTypePublic.Checked; - - if (roleInfo.Settings.ContainsKey("ReviewMembers")) - roleInfo.Settings["ReviewMembers"] = chkMemberApproved.Checked.ToString(); - else - roleInfo.Settings.Add("ReviewMembers", chkMemberApproved.Checked.ToString()); - + roleInfo.Description = this.txtDescription.Text; + roleInfo.IsPublic = this.rdAccessTypePublic.Checked; + + if (roleInfo.Settings.ContainsKey("ReviewMembers")) + { + roleInfo.Settings["ReviewMembers"] = this.chkMemberApproved.Checked.ToString(); + } + else + { + roleInfo.Settings.Add("ReviewMembers", this.chkMemberApproved.Checked.ToString()); + } + RoleController.Instance.UpdateRoleSettings(roleInfo, true); RoleController.Instance.UpdateRole(roleInfo); - if (inpFile.PostedFile.ContentLength > 0) + if (this.inpFile.PostedFile.ContentLength > 0) { IFileManager _fileManager = FileManager.Instance; IFolderManager _folderManager = FolderManager.Instance; - var rootFolderPath = PathUtils.Instance.FormatFolderPath(PortalSettings.HomeDirectory); + var rootFolderPath = PathUtils.Instance.FormatFolderPath(this.PortalSettings.HomeDirectory); - IFolderInfo groupFolder = _folderManager.GetFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); + IFolderInfo groupFolder = _folderManager.GetFolder(this.PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); if (groupFolder == null) { - groupFolder = _folderManager.AddFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); + groupFolder = _folderManager.AddFolder(this.PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); } + if (groupFolder != null) { - var fileName = Path.GetFileName(inpFile.PostedFile.FileName); - var fileInfo = _fileManager.AddFile(groupFolder, fileName, inpFile.PostedFile.InputStream, true); + var fileName = Path.GetFileName(this.inpFile.PostedFile.FileName); + var fileInfo = _fileManager.AddFile(groupFolder, fileName, this.inpFile.PostedFile.InputStream, true); roleInfo.IconFile = "FileID=" + fileInfo.FileId; RoleController.Instance.UpdateRole(roleInfo); } } - //Clear Roles Cache + // Clear Roles Cache DataCache.RemoveCache("GetRoles"); - } - Response.Redirect(_navigationManager.NavigateURL(TabId, "", new String[] { "groupid=" + GroupId.ToString() })); + this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, string.Empty, new string[] { "groupid=" + this.GroupId.ToString() })); } } } diff --git a/DNN Platform/Modules/Groups/GroupListControl.cs b/DNN Platform/Modules/Groups/GroupListControl.cs index f0d3256d093..6fa218063e9 100644 --- a/DNN Platform/Modules/Groups/GroupListControl.cs +++ b/DNN Platform/Modules/Groups/GroupListControl.cs @@ -1,45 +1,54 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Entities.Users; -using DotNetNuke.Modules.Groups.Components; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups.Controls { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Reflection; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Localization; + [DefaultProperty("Text")] [ToolboxData("<{0}:GroupListControl runat=server>")] public class GroupListControl : WebControl { - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] - public String ItemTemplate { get; set; } + public UserInfo currentUser; + + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] + public string ItemTemplate { get; set; } - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] - public String HeaderTemplate { get; set; } + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] + public string HeaderTemplate { get; set; } - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] - public String FooterTemplate { get; set; } + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] + public string FooterTemplate { get; set; } - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] - public String RowHeaderTemplate { get; set; } + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] + public string RowHeaderTemplate { get; set; } - [DefaultValue(""), PersistenceMode(PersistenceMode.InnerProperty)] - public String RowFooterTemplate { get; set; } + [DefaultValue("")] + [PersistenceMode(PersistenceMode.InnerProperty)] + public string RowFooterTemplate { get; set; } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { get @@ -75,126 +84,126 @@ public PortalSettings PortalSettings [DefaultValue(false)] public bool DisplayCurrentUserGroups { get; set; } - public UserInfo currentUser; - public int GroupViewTabId { get; set; } protected override void OnInit(EventArgs e) { base.OnInit(e); - currentUser = UserController.Instance.GetCurrentUserInfo(); - - } - - private static bool TestPredicateGroup(IEnumerable> predicates, RoleInfo ri) - { - return predicates.All(p => p(ri)); - } - - private static object GetOrderByProperty(object obj, string property) - { - var propertyInfo = obj.GetType().GetProperty(property, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); - return propertyInfo == null ? null : propertyInfo.GetValue(obj, null); + this.currentUser = UserController.Instance.GetCurrentUserInfo(); } protected override void Render(HtmlTextWriter output) { var whereCls = new List> { - grp => grp.SecurityMode != SecurityMode.SecurityRole && grp.Status == RoleStatus.Approved + grp => grp.SecurityMode != SecurityMode.SecurityRole && grp.Status == RoleStatus.Approved, }; - if (RoleGroupId >= -1) - { - whereCls.Add(grp => grp.RoleGroupID == RoleGroupId); - } - - if (DisplayCurrentUserGroups) - whereCls.Add(grp => currentUser.IsInRole(grp.RoleName)); - else - whereCls.Add(grp => grp.IsPublic || currentUser.IsInRole(grp.RoleName) || currentUser.IsInRole(PortalSettings.AdministratorRoleName)); - - if (!string.IsNullOrEmpty(SearchFilter)) + if (this.RoleGroupId >= -1) { - whereCls.Add(grp => grp.RoleName.ToLowerInvariant().Contains(SearchFilter.ToLowerInvariant()) || grp.Description.ToLowerInvariant().Contains(SearchFilter.ToLowerInvariant())); + whereCls.Add(grp => grp.RoleGroupID == this.RoleGroupId); } - var roles = RoleController.Instance.GetRoles(PortalSettings.PortalId, grp => TestPredicateGroup(whereCls, grp)); - - if (SortDirection.ToLowerInvariant() == "asc") - roles = roles.OrderBy(info => GetOrderByProperty(info, SortField)).ToList(); - else - roles = roles.OrderByDescending(info => GetOrderByProperty(info, SortField)).ToList(); - - decimal pages = (decimal)roles.Count / (decimal)PageSize; - - - output.Write(HeaderTemplate); - - - ItemTemplate = ItemTemplate.Replace("{resx:posts}", Localization.GetString("posts", Constants.SharedResourcesPath)); - ItemTemplate = ItemTemplate.Replace("{resx:members}", Localization.GetString("members", Constants.SharedResourcesPath)); - ItemTemplate = ItemTemplate.Replace("{resx:photos}", Localization.GetString("photos", Constants.SharedResourcesPath)); - ItemTemplate = ItemTemplate.Replace("{resx:documents}", Localization.GetString("documents", Constants.SharedResourcesPath)); - - ItemTemplate = ItemTemplate.Replace("{resx:Join}", Localization.GetString("Join", Constants.SharedResourcesPath)); - ItemTemplate = ItemTemplate.Replace("{resx:Pending}", Localization.GetString("Pending", Constants.SharedResourcesPath)); - ItemTemplate = ItemTemplate.Replace("{resx:LeaveGroup}", Localization.GetString("LeaveGroup", Constants.SharedResourcesPath)); - ItemTemplate = ItemTemplate.Replace("[GroupViewTabId]", GroupViewTabId.ToString()); - - if (roles.Count == 0) - output.Write(String.Format("
    {0}
    ", Localization.GetString("NoGroupsFound", Constants.SharedResourcesPath))); + if (this.DisplayCurrentUserGroups) + { + whereCls.Add(grp => this.currentUser.IsInRole(grp.RoleName)); + } + else + { + whereCls.Add(grp => grp.IsPublic || this.currentUser.IsInRole(grp.RoleName) || this.currentUser.IsInRole(this.PortalSettings.AdministratorRoleName)); + } + + if (!string.IsNullOrEmpty(this.SearchFilter)) + { + whereCls.Add(grp => grp.RoleName.ToLowerInvariant().Contains(this.SearchFilter.ToLowerInvariant()) || grp.Description.ToLowerInvariant().Contains(this.SearchFilter.ToLowerInvariant())); + } + var roles = RoleController.Instance.GetRoles(this.PortalSettings.PortalId, grp => TestPredicateGroup(whereCls, grp)); + + if (this.SortDirection.ToLowerInvariant() == "asc") + { + roles = roles.OrderBy(info => GetOrderByProperty(info, this.SortField)).ToList(); + } + else + { + roles = roles.OrderByDescending(info => GetOrderByProperty(info, this.SortField)).ToList(); + } + + decimal pages = (decimal)roles.Count / (decimal)this.PageSize; + + output.Write(this.HeaderTemplate); + + this.ItemTemplate = this.ItemTemplate.Replace("{resx:posts}", Localization.GetString("posts", Constants.SharedResourcesPath)); + this.ItemTemplate = this.ItemTemplate.Replace("{resx:members}", Localization.GetString("members", Constants.SharedResourcesPath)); + this.ItemTemplate = this.ItemTemplate.Replace("{resx:photos}", Localization.GetString("photos", Constants.SharedResourcesPath)); + this.ItemTemplate = this.ItemTemplate.Replace("{resx:documents}", Localization.GetString("documents", Constants.SharedResourcesPath)); + + this.ItemTemplate = this.ItemTemplate.Replace("{resx:Join}", Localization.GetString("Join", Constants.SharedResourcesPath)); + this.ItemTemplate = this.ItemTemplate.Replace("{resx:Pending}", Localization.GetString("Pending", Constants.SharedResourcesPath)); + this.ItemTemplate = this.ItemTemplate.Replace("{resx:LeaveGroup}", Localization.GetString("LeaveGroup", Constants.SharedResourcesPath)); + this.ItemTemplate = this.ItemTemplate.Replace("[GroupViewTabId]", this.GroupViewTabId.ToString()); + + if (roles.Count == 0) + { + output.Write(string.Format("
    {0}
    ", Localization.GetString("NoGroupsFound", Constants.SharedResourcesPath))); + } if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["page"])) { - CurrentIndex = Convert.ToInt32(HttpContext.Current.Request.QueryString["page"].ToString()); - CurrentIndex = CurrentIndex - 1; + this.CurrentIndex = Convert.ToInt32(HttpContext.Current.Request.QueryString["page"].ToString()); + this.CurrentIndex = this.CurrentIndex - 1; } int rowItem = 0; - int recordStart = (CurrentIndex * PageSize); - - if (CurrentIndex == 0) - recordStart = 0; + int recordStart = this.CurrentIndex * this.PageSize; + if (this.CurrentIndex == 0) + { + recordStart = 0; + } - for (int x = recordStart; x < (recordStart + PageSize); x++) + for (int x = recordStart; x < (recordStart + this.PageSize); x++) { - if (x > roles.Count - 1) - break; - + if (x > roles.Count - 1) + { + break; + } + var role = roles[x]; - string rowTemplate = ItemTemplate; - - if (rowItem == 0) - output.Write(RowHeaderTemplate); + string rowTemplate = this.ItemTemplate; - var groupParser = new GroupViewParser(PortalSettings, role, currentUser, rowTemplate, GroupViewTabId); + if (rowItem == 0) + { + output.Write(this.RowHeaderTemplate); + } + + var groupParser = new GroupViewParser(this.PortalSettings, role, this.currentUser, rowTemplate, this.GroupViewTabId); output.Write(groupParser.ParseView()); rowItem += 1; - if (rowItem == ItemsPerRow) + if (rowItem == this.ItemsPerRow) { - output.Write(RowFooterTemplate); + output.Write(this.RowFooterTemplate); rowItem = 0; } } - if (rowItem > 0) - output.Write(RowFooterTemplate); - + if (rowItem > 0) + { + output.Write(this.RowFooterTemplate); + } - output.Write(FooterTemplate); + output.Write(this.FooterTemplate); int TotalPages = Convert.ToInt32(System.Math.Ceiling(pages)); - - - if (TotalPages == 0) - TotalPages = 1; - + + if (TotalPages == 0) + { + TotalPages = 1; + } + string sUrlFormat = "{2}"; string[] currParams = new string[] { }; @@ -219,26 +228,33 @@ protected override void Render(HtmlTextWriter output) @params = new string[] { "page=" + x.ToString() }; } - string sUrl = Utilities.NavigateUrl(TabId, @params); + string sUrl = Utilities.NavigateUrl(this.TabId, @params); string cssClass = "pagerItem"; - if (x - 1 == CurrentIndex) - cssClass = "pagerItemSelected"; - + if (x - 1 == this.CurrentIndex) + { + cssClass = "pagerItemSelected"; + } sb.AppendFormat(sUrlFormat, sUrl, cssClass, x.ToString()); } - } output.Write("
    "); output.Write(sb.ToString()); output.Write("
    "); - } + private static bool TestPredicateGroup(IEnumerable> predicates, RoleInfo ri) + { + return predicates.All(p => p(ri)); + } + private static object GetOrderByProperty(object obj, string property) + { + var propertyInfo = obj.GetType().GetProperty(property, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); + return propertyInfo == null ? null : propertyInfo.GetValue(obj, null); + } } - } diff --git a/DNN Platform/Modules/Groups/GroupView.ascx.cs b/DNN Platform/Modules/Groups/GroupView.ascx.cs index cf53e7e7993..a0ef0d538e1 100644 --- a/DNN Platform/Modules/Groups/GroupView.ascx.cs +++ b/DNN Platform/Modules/Groups/GroupView.ascx.cs @@ -1,52 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke; -using DotNetNuke.UI.WebControls; -using DotNetNuke.Common; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Services.Localization; -using DotNetNuke.Modules.Groups.Components; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.WebControls; + public partial class GroupView : GroupsModuleBase { protected void Page_Load(object sender, EventArgs e) { - - RoleInfo role = RoleController.Instance.GetRole(PortalId, r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == GroupId); - if (role == null && GroupId > 0) + RoleInfo role = RoleController.Instance.GetRole(this.PortalId, r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == this.GroupId); + if (role == null && this.GroupId > 0) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("GroupIdNotFound", Constants.SharedResourcesPath), ModuleMessage.ModuleMessageType.YellowWarning); } - if (role == null && (UserInfo.IsInRole(PortalSettings.AdministratorRoleName) || UserInfo.IsSuperUser)) + if (role == null && (this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) || this.UserInfo.IsSuperUser)) { role = new RoleInfo(); role.RoleID = -1; - role.RoleName = Localization.GetString("Sample_RoleName", LocalResourceFile); - role.Description = Localization.GetString("Sample_RoleDescription", LocalResourceFile); - + role.RoleName = Localization.GetString("Sample_RoleName", this.LocalResourceFile); + role.Description = Localization.GetString("Sample_RoleDescription", this.LocalResourceFile); } - if (role == null) - litOutput.Text = string.Empty; + if (role == null) + { + this.litOutput.Text = string.Empty; + } else { var resxPath = Constants.SharedResourcesPath; - var template = GroupViewTemplate; + var template = this.GroupViewTemplate; template = template.Replace("{resx:posts}", Localization.GetString("posts", resxPath)); template = template.Replace("{resx:members}", Localization.GetString("members", resxPath)); template = template.Replace("{resx:photos}", Localization.GetString("photos", resxPath)); @@ -57,16 +58,13 @@ protected void Page_Load(object sender, EventArgs e) template = template.Replace("{resx:Pending}", Localization.GetString("Pending", resxPath)); template = template.Replace("{resx:LeaveGroup}", Localization.GetString("LeaveGroup", resxPath)); template = template.Replace("{resx:EditGroup}", Localization.GetString("EditGroup", resxPath)); - template = template.Replace("[GroupViewTabId]", GroupViewTabId.ToString()); - - - var groupParser = new GroupViewParser(PortalSettings, role, UserInfo, template, TabId); - groupParser.GroupEditUrl = GetEditUrl(); - - litOutput.Text = groupParser.ParseView(); + template = template.Replace("[GroupViewTabId]", this.GroupViewTabId.ToString()); + + var groupParser = new GroupViewParser(this.PortalSettings, role, this.UserInfo, template, this.TabId); + groupParser.GroupEditUrl = this.GetEditUrl(); + this.litOutput.Text = groupParser.ParseView(); } - } } } diff --git a/DNN Platform/Modules/Groups/GroupsModuleBase.cs b/DNN Platform/Modules/Groups/GroupsModuleBase.cs index e37a7e7c810..3c0391ad8a7 100644 --- a/DNN Platform/Modules/Groups/GroupsModuleBase.cs +++ b/DNN Platform/Modules/Groups/GroupsModuleBase.cs @@ -1,46 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Modules.Groups.Components; -using System; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Groups { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security.Permissions; + using Microsoft.Extensions.DependencyInjection; + public class GroupsModuleBase : PortalModuleBase { - protected INavigationManager NavigationManager { get; } public GroupsModuleBase() { - NavigationManager = DependencyProvider.GetRequiredService(); + this.NavigationManager = this.DependencyProvider.GetRequiredService(); } public enum GroupMode { Setup = 0, List = 1, - View = 2 - } - - #region Public Properties + View = 2, + } + public GroupMode LoadView { get { var mode = GroupMode.Setup; - if (Settings.ContainsKey(Constants.GroupLoadView)) + if (this.Settings.ContainsKey(Constants.GroupLoadView)) { - switch (Settings[Constants.GroupLoadView].ToString()) + switch (this.Settings[Constants.GroupLoadView].ToString()) { case "List": mode = GroupMode.List; @@ -50,126 +44,150 @@ public GroupMode LoadView break; } } + return mode; } } + + protected INavigationManager NavigationManager { get; } + public int GroupId { get { int groupId = -1; - if (string.IsNullOrEmpty(Request.QueryString["GroupId"])) + if (string.IsNullOrEmpty(this.Request.QueryString["GroupId"])) { return groupId; } - if (int.TryParse(Request.QueryString["GroupId"], out groupId)) + + if (int.TryParse(this.Request.QueryString["GroupId"], out groupId)) { return groupId; } + return -1; } } + public int DefaultRoleGroupId { get { - var roleGroupId = Null.NullInteger; - if (Settings.ContainsKey(Constants.DefaultRoleGroupSetting)) + var roleGroupId = Null.NullInteger; + if (this.Settings.ContainsKey(Constants.DefaultRoleGroupSetting)) { int id; - if (int.TryParse(Settings[Constants.DefaultRoleGroupSetting].ToString(), out id)) - roleGroupId = id; + if (int.TryParse(this.Settings[Constants.DefaultRoleGroupSetting].ToString(), out id)) + { + roleGroupId = id; + } } return roleGroupId; // -2 is for "< All Roles >" } } + public int GroupListTabId { get { - if (Settings.ContainsKey(Constants.GroupListPage)) + if (this.Settings.ContainsKey(Constants.GroupListPage)) { - return Convert.ToInt32(Settings[Constants.GroupListPage].ToString()); + return Convert.ToInt32(this.Settings[Constants.GroupListPage].ToString()); } - return TabId; + + return this.TabId; } } + public int GroupViewTabId { get { - if (Settings.ContainsKey(Constants.GroupViewPage)) + if (this.Settings.ContainsKey(Constants.GroupViewPage)) { - return Convert.ToInt32(Settings[Constants.GroupViewPage].ToString()); + return Convert.ToInt32(this.Settings[Constants.GroupViewPage].ToString()); } - return TabId; + + return this.TabId; } } + public string GroupViewTemplate { get { - string template = LocalizeString("GroupViewTemplate.Text"); - if (Settings.ContainsKey(Constants.GroupViewTemplate)) + string template = this.LocalizeString("GroupViewTemplate.Text"); + if (this.Settings.ContainsKey(Constants.GroupViewTemplate)) { - if (!string.IsNullOrEmpty(Settings[Constants.GroupViewTemplate].ToString())) + if (!string.IsNullOrEmpty(this.Settings[Constants.GroupViewTemplate].ToString())) { - template = Settings[Constants.GroupViewTemplate].ToString(); + template = this.Settings[Constants.GroupViewTemplate].ToString(); } } + return template; } } + public string GroupListTemplate { get { - string template = LocalizeString("GroupListTemplate.Text"); - if (Settings.ContainsKey(Constants.GroupListTemplate)) + string template = this.LocalizeString("GroupListTemplate.Text"); + if (this.Settings.ContainsKey(Constants.GroupListTemplate)) { - if (!string.IsNullOrEmpty(Settings[Constants.GroupListTemplate].ToString())) + if (!string.IsNullOrEmpty(this.Settings[Constants.GroupListTemplate].ToString())) { - template = Settings[Constants.GroupListTemplate].ToString(); + template = this.Settings[Constants.GroupListTemplate].ToString(); } } + return template; } } + public string DefaultGroupMode { get { - if (Settings.ContainsKey(Constants.DefautlGroupViewMode)) + if (this.Settings.ContainsKey(Constants.DefautlGroupViewMode)) { - return Settings[Constants.DefautlGroupViewMode].ToString(); + return this.Settings[Constants.DefautlGroupViewMode].ToString(); } - return ""; + + return string.Empty; } } + public bool GroupModerationEnabled { get { - if (Settings.ContainsKey(Constants.GroupModerationEnabled)) + if (this.Settings.ContainsKey(Constants.GroupModerationEnabled)) { - return Convert.ToBoolean(Settings[Constants.GroupModerationEnabled].ToString()); + return Convert.ToBoolean(this.Settings[Constants.GroupModerationEnabled].ToString()); } + return false; } } + public bool CanCreate { get { - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { - if (UserInfo.IsSuperUser) + if (this.UserInfo.IsSuperUser) { return true; } - return ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, "CREATEGROUP"); + + return ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, "CREATEGROUP"); } + return false; } } @@ -178,7 +196,7 @@ public string GroupListFilter { get { - return Request.QueryString["Filter"]; + return this.Request.QueryString["Filter"]; } } @@ -186,83 +204,83 @@ public int GroupListPageSize { get { - if (Settings.ContainsKey(Constants.GroupListPageSize)) + if (this.Settings.ContainsKey(Constants.GroupListPageSize)) { - if (!string.IsNullOrEmpty(Settings[Constants.GroupListPageSize].ToString())) + if (!string.IsNullOrEmpty(this.Settings[Constants.GroupListPageSize].ToString())) { - return Convert.ToInt32(Settings[Constants.GroupListPageSize].ToString()); + return Convert.ToInt32(this.Settings[Constants.GroupListPageSize].ToString()); } } + return 20; } } + public bool GroupListSearchEnabled { get { var enableSearch = false; - if (Settings.ContainsKey(Constants.GroupListSearchEnabled)) + if (this.Settings.ContainsKey(Constants.GroupListSearchEnabled)) { - if (!string.IsNullOrEmpty(Settings[Constants.GroupListSearchEnabled].ToString())) + if (!string.IsNullOrEmpty(this.Settings[Constants.GroupListSearchEnabled].ToString())) { - bool.TryParse(Settings[Constants.GroupListSearchEnabled].ToString(), out enableSearch); + bool.TryParse(this.Settings[Constants.GroupListSearchEnabled].ToString(), out enableSearch); } } return enableSearch; } } + public string GroupListSortField { get { - return Settings.ContainsKey(Constants.GroupListSortField) ? Settings[Constants.GroupListSortField].ToString() : ""; + return this.Settings.ContainsKey(Constants.GroupListSortField) ? this.Settings[Constants.GroupListSortField].ToString() : string.Empty; } } + public string GroupListSortDirection { get { - return Settings.ContainsKey(Constants.GroupListSortDirection) ? Settings[Constants.GroupListSortDirection].ToString() : ""; + return this.Settings.ContainsKey(Constants.GroupListSortDirection) ? this.Settings[Constants.GroupListSortDirection].ToString() : string.Empty; } } + public bool GroupListUserGroupsOnly { get { var userGroupsOnly = false; - if (Settings.ContainsKey(Constants.GroupListUserGroupsOnly)) + if (this.Settings.ContainsKey(Constants.GroupListUserGroupsOnly)) { - if (!string.IsNullOrEmpty(Settings[Constants.GroupListUserGroupsOnly].ToString())) + if (!string.IsNullOrEmpty(this.Settings[Constants.GroupListUserGroupsOnly].ToString())) { - bool.TryParse(Settings[Constants.GroupListUserGroupsOnly].ToString(), out userGroupsOnly); + bool.TryParse(this.Settings[Constants.GroupListUserGroupsOnly].ToString(), out userGroupsOnly); } } return userGroupsOnly; } - } - - - #endregion - - #region Public Methods + } + public string GetCreateUrl() { - return ModuleContext.EditUrl("Create"); //.NavigateUrl(GroupCreateTabId,"",true,null); + return this.ModuleContext.EditUrl("Create"); // .NavigateUrl(GroupCreateTabId,"",true,null); } public string GetClearFilterUrl() { - return NavigationManager.NavigateURL(TabId, ""); + return this.NavigationManager.NavigateURL(this.TabId, string.Empty); } public string GetEditUrl() { - return ModuleContext.EditUrl("GroupId", GroupId.ToString("D"), "Edit"); - } - #endregion + return this.ModuleContext.EditUrl("GroupId", this.GroupId.ToString("D"), "Edit"); + } } } diff --git a/DNN Platform/Modules/Groups/GroupsSettingsBase.cs b/DNN Platform/Modules/Groups/GroupsSettingsBase.cs index db6b2e4318c..34a562cbb4c 100644 --- a/DNN Platform/Modules/Groups/GroupsSettingsBase.cs +++ b/DNN Platform/Modules/Groups/GroupsSettingsBase.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Groups { + using DotNetNuke.Entities.Modules; + public class GroupsSettingsBase : ModuleSettingsBase { } diff --git a/DNN Platform/Modules/Groups/List.ascx.cs b/DNN Platform/Modules/Groups/List.ascx.cs index 04d21e0eaa1..75a67bb5311 100644 --- a/DNN Platform/Modules/Groups/List.ascx.cs +++ b/DNN Platform/Modules/Groups/List.ascx.cs @@ -1,65 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Framework; + using Microsoft.Extensions.DependencyInjection; + public partial class List : GroupsModuleBase { - public INavigationManager _navigationManager { get; } public List() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); } + + public INavigationManager _navigationManager { get; } + protected void Page_Load(object sender, EventArgs e) { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - panelSearch.Visible = GroupListSearchEnabled; + this.panelSearch.Visible = this.GroupListSearchEnabled; - ctlGroupList.TabId = TabId; - ctlGroupList.GroupViewTabId = GroupViewTabId; - ctlGroupList.RoleGroupId = DefaultRoleGroupId; - ctlGroupList.PageSize = GroupListPageSize; - ctlGroupList.DisplayCurrentUserGroups = GroupListUserGroupsOnly; - ctlGroupList.SearchFilter = GroupListFilter; - ctlGroupList.SortField = GroupListSortField; - ctlGroupList.SortDirection = GroupListSortDirection; + this.ctlGroupList.TabId = this.TabId; + this.ctlGroupList.GroupViewTabId = this.GroupViewTabId; + this.ctlGroupList.RoleGroupId = this.DefaultRoleGroupId; + this.ctlGroupList.PageSize = this.GroupListPageSize; + this.ctlGroupList.DisplayCurrentUserGroups = this.GroupListUserGroupsOnly; + this.ctlGroupList.SearchFilter = this.GroupListFilter; + this.ctlGroupList.SortField = this.GroupListSortField; + this.ctlGroupList.SortDirection = this.GroupListSortDirection; - if (!string.IsNullOrEmpty(GroupListSortField)) + if (!string.IsNullOrEmpty(this.GroupListSortField)) { - ctlGroupList.SortField = GroupListSortField; + this.ctlGroupList.SortField = this.GroupListSortField; } - if (!string.IsNullOrEmpty(GroupListSortDirection)) + if (!string.IsNullOrEmpty(this.GroupListSortDirection)) { - ctlGroupList.SortDirection = GroupListSortDirection; + this.ctlGroupList.SortDirection = this.GroupListSortDirection; } - - - if (!String.IsNullOrEmpty(GroupListTemplate)) + + if (!string.IsNullOrEmpty(this.GroupListTemplate)) { - ctlGroupList.ItemTemplate = GroupListTemplate; + this.ctlGroupList.ItemTemplate = this.GroupListTemplate; } - if (!string.IsNullOrEmpty(GroupListFilter)) + if (!string.IsNullOrEmpty(this.GroupListFilter)) { - txtFilter.Text = GroupListFilter; + this.txtFilter.Text = this.GroupListFilter; } - } protected void btnSearch_Click(object sender, EventArgs e) { - if(!Page.IsValid) return; - - Response.Redirect(_navigationManager.NavigateURL(TabId, "", "filter=" + txtFilter.Text.Trim())); + if (!this.Page.IsValid) + { + return; + } + + this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, string.Empty, "filter=" + this.txtFilter.Text.Trim())); } } } diff --git a/DNN Platform/Modules/Groups/ListSettings.ascx.cs b/DNN Platform/Modules/Groups/ListSettings.ascx.cs index eef0e455bb1..a90f79acc18 100644 --- a/DNN Platform/Modules/Groups/ListSettings.ascx.cs +++ b/DNN Platform/Modules/Groups/ListSettings.ascx.cs @@ -1,103 +1,99 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Localization; -using System.Web.UI.WebControls; -using DotNetNuke.Modules.Groups.Components; -using DotNetNuke.Entities.Tabs; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules.Definitions; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Groups { + using System; + using System.Collections.Generic; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// - /// The Settings class manages Module Settings + /// The Settings class manages Module Settings. /// /// ----------------------------------------------------------------------------- public partial class ListSettings : GroupsSettingsBase - { - #region Base Method Implementations - + { /// ----------------------------------------------------------------------------- /// - /// LoadSettings loads the settings from the Database and displays them + /// LoadSettings loads the settings from the Database and displays them. /// /// ----------------------------------------------------------------------------- public override void LoadSettings() { try { - if (Page.IsPostBack == false) + if (this.Page.IsPostBack == false) { - BindGroups(); - BindPages(); - - if (Settings.ContainsKey(Constants.DefaultRoleGroupSetting)) { - drpRoleGroup.SelectedIndex = drpRoleGroup.Items.IndexOf(drpRoleGroup.Items.FindByValue(Settings[Constants.DefaultRoleGroupSetting].ToString())); + this.BindGroups(); + this.BindPages(); + + if (this.Settings.ContainsKey(Constants.DefaultRoleGroupSetting)) + { + this.drpRoleGroup.SelectedIndex = this.drpRoleGroup.Items.IndexOf(this.drpRoleGroup.Items.FindByValue(this.Settings[Constants.DefaultRoleGroupSetting].ToString())); } - if (Settings.ContainsKey(Constants.GroupViewPage)) { - drpGroupViewPage.SelectedIndex = drpGroupViewPage.Items.IndexOf(drpGroupViewPage.Items.FindByValue(Settings[Constants.GroupViewPage].ToString())); + if (this.Settings.ContainsKey(Constants.GroupViewPage)) + { + this.drpGroupViewPage.SelectedIndex = this.drpGroupViewPage.Items.IndexOf(this.drpGroupViewPage.Items.FindByValue(this.Settings[Constants.GroupViewPage].ToString())); } - if (Settings.ContainsKey(Constants.GroupListTemplate)) { - txtListTemplate.Text = Settings[Constants.GroupListTemplate].ToString(); + if (this.Settings.ContainsKey(Constants.GroupListTemplate)) + { + this.txtListTemplate.Text = this.Settings[Constants.GroupListTemplate].ToString(); } - if (Settings.ContainsKey(Constants.GroupViewTemplate)) + if (this.Settings.ContainsKey(Constants.GroupViewTemplate)) { - txtViewTemplate.Text = Settings[Constants.GroupViewTemplate].ToString(); + this.txtViewTemplate.Text = this.Settings[Constants.GroupViewTemplate].ToString(); } - if (Settings.ContainsKey(Constants.GroupModerationEnabled)) + if (this.Settings.ContainsKey(Constants.GroupModerationEnabled)) { - chkGroupModeration.Checked = Convert.ToBoolean(Settings[Constants.GroupModerationEnabled].ToString()); + this.chkGroupModeration.Checked = Convert.ToBoolean(this.Settings[Constants.GroupModerationEnabled].ToString()); } - if (Settings.ContainsKey(Constants.GroupLoadView)) { - drpViewMode.SelectedIndex = drpViewMode.Items.IndexOf(drpViewMode.Items.FindByValue(Settings[Constants.GroupLoadView].ToString())); + if (this.Settings.ContainsKey(Constants.GroupLoadView)) + { + this.drpViewMode.SelectedIndex = this.drpViewMode.Items.IndexOf(this.drpViewMode.Items.FindByValue(this.Settings[Constants.GroupLoadView].ToString())); } - if (Settings.ContainsKey(Constants.GroupListPageSize)) + if (this.Settings.ContainsKey(Constants.GroupListPageSize)) { - txtPageSize.Text = Settings[Constants.GroupListPageSize].ToString(); + this.txtPageSize.Text = this.Settings[Constants.GroupListPageSize].ToString(); } - if (Settings.ContainsKey(Constants.GroupListUserGroupsOnly)) + if (this.Settings.ContainsKey(Constants.GroupListUserGroupsOnly)) { - chkUserGroups.Checked = Convert.ToBoolean(Settings[Constants.GroupListUserGroupsOnly].ToString()); + this.chkUserGroups.Checked = Convert.ToBoolean(this.Settings[Constants.GroupListUserGroupsOnly].ToString()); } - if (Settings.ContainsKey(Constants.GroupListSearchEnabled)) + if (this.Settings.ContainsKey(Constants.GroupListSearchEnabled)) { - chkEnableSearch.Checked = Convert.ToBoolean(Settings[Constants.GroupListSearchEnabled].ToString()); + this.chkEnableSearch.Checked = Convert.ToBoolean(this.Settings[Constants.GroupListSearchEnabled].ToString()); } - if (Settings.ContainsKey(Constants.GroupListSortField)) + if (this.Settings.ContainsKey(Constants.GroupListSortField)) { - lstSortField.SelectedIndex = lstSortField.Items.IndexOf(lstSortField.Items.FindByValue(Settings[Constants.GroupListSortField].ToString())); + this.lstSortField.SelectedIndex = this.lstSortField.Items.IndexOf(this.lstSortField.Items.FindByValue(this.Settings[Constants.GroupListSortField].ToString())); } - if (Settings.ContainsKey(Constants.GroupListSortDirection)) + if (this.Settings.ContainsKey(Constants.GroupListSortDirection)) { - radSortDirection.SelectedIndex = radSortDirection.Items.IndexOf(radSortDirection.Items.FindByValue(Settings[Constants.GroupListSortDirection].ToString())); + this.radSortDirection.SelectedIndex = this.radSortDirection.Items.IndexOf(this.radSortDirection.Items.FindByValue(this.Settings[Constants.GroupListSortDirection].ToString())); } } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -105,61 +101,63 @@ public override void LoadSettings() /// ----------------------------------------------------------------------------- /// - /// UpdateSettings saves the modified settings to the Database + /// UpdateSettings saves the modified settings to the Database. /// /// ----------------------------------------------------------------------------- public override void UpdateSettings() { try { - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.DefaultRoleGroupSetting, drpRoleGroup.SelectedItem.Value); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupViewPage, drpGroupViewPage.SelectedItem.Value); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListTemplate, txtListTemplate.Text); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupViewTemplate, txtViewTemplate.Text); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupModerationEnabled, chkGroupModeration.Checked.ToString()); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupLoadView, drpViewMode.SelectedItem.Value); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListPageSize, txtPageSize.Text); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListSearchEnabled, chkEnableSearch.Checked.ToString()); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListSortField, lstSortField.SelectedItem.Value); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListSortDirection, radSortDirection.SelectedItem.Value); - ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListUserGroupsOnly, chkUserGroups.Checked.ToString()); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.DefaultRoleGroupSetting, this.drpRoleGroup.SelectedItem.Value); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupViewPage, this.drpGroupViewPage.SelectedItem.Value); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListTemplate, this.txtListTemplate.Text); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupViewTemplate, this.txtViewTemplate.Text); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupModerationEnabled, this.chkGroupModeration.Checked.ToString()); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupLoadView, this.drpViewMode.SelectedItem.Value); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListPageSize, this.txtPageSize.Text); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListSearchEnabled, this.chkEnableSearch.Checked.ToString()); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListSortField, this.lstSortField.SelectedItem.Value); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListSortDirection, this.radSortDirection.SelectedItem.Value); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupListUserGroupsOnly, this.chkUserGroups.Checked.ToString()); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - private void BindGroups() { - var arrGroups = RoleController.GetRoleGroups(PortalId); - drpRoleGroup.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); - drpRoleGroup.Items.Add(new ListItem(Localization.GetString("GlobalRoles"), "-1")); + } + + private void BindGroups() + { + var arrGroups = RoleController.GetRoleGroups(this.PortalId); + this.drpRoleGroup.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); + this.drpRoleGroup.Items.Add(new ListItem(Localization.GetString("GlobalRoles"), "-1")); - foreach (RoleGroupInfo roleGroup in arrGroups) { - drpRoleGroup.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString())); + foreach (RoleGroupInfo roleGroup in arrGroups) + { + this.drpRoleGroup.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString())); } } - private void BindPages() { - foreach (ModuleInfo moduleInfo in ModuleController.Instance.GetModules(PortalId)) + + private void BindPages() + { + foreach (ModuleInfo moduleInfo in ModuleController.Instance.GetModules(this.PortalId)) { if (moduleInfo.DesktopModule.ModuleName.Contains("Social Groups") && moduleInfo.IsDeleted == false) { - TabInfo tabInfo = TabController.Instance.GetTab(moduleInfo.TabID, PortalId, false); - if (tabInfo != null) + TabInfo tabInfo = TabController.Instance.GetTab(moduleInfo.TabID, this.PortalId, false); + if (tabInfo != null) { - if (tabInfo.IsDeleted == false) + if (tabInfo.IsDeleted == false) { - foreach (KeyValuePair def in moduleInfo.DesktopModule.ModuleDefinitions) + foreach (KeyValuePair def in moduleInfo.DesktopModule.ModuleDefinitions) { - if (moduleInfo.ModuleDefinition.FriendlyName == def.Key) + if (moduleInfo.ModuleDefinition.FriendlyName == def.Key) { - if (drpGroupViewPage.Items.FindByValue(tabInfo.TabID.ToString()) == null) + if (this.drpGroupViewPage.Items.FindByValue(tabInfo.TabID.ToString()) == null) { - drpGroupViewPage.Items.Add(new ListItem(tabInfo.TabName + " - " + def.Key, tabInfo.TabID.ToString())); + this.drpGroupViewPage.Items.Add(new ListItem(tabInfo.TabName + " - " + def.Key, tabInfo.TabID.ToString())); } } - } } } diff --git a/DNN Platform/Modules/Groups/Loader.ascx.cs b/DNN Platform/Modules/Groups/Loader.ascx.cs index efadfdf7c08..ed49efe9cb3 100644 --- a/DNN Platform/Modules/Groups/Loader.ascx.cs +++ b/DNN Platform/Modules/Groups/Loader.ascx.cs @@ -1,20 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Modules.Groups.Components; - -namespace DotNetNuke.Modules.Groups { - public partial class Loader : GroupsModuleBase { - protected void Page_Load(object sender, EventArgs e) { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Groups +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Modules.Groups.Components; + + public partial class Loader : GroupsModuleBase + { + protected void Page_Load(object sender, EventArgs e) + { string path = Constants.ModulePath; - switch (LoadView) { + switch (this.LoadView) + { case GroupMode.Setup: path += "Setup.ascx"; break; @@ -25,10 +30,11 @@ protected void Page_Load(object sender, EventArgs e) { path += "GroupView.ascx"; break; } + GroupsModuleBase ctl = new GroupsModuleBase(); - ctl = (GroupsModuleBase)LoadControl(path); + ctl = (GroupsModuleBase)this.LoadControl(path); ctl.ModuleConfiguration = this.ModuleConfiguration; - plhContent.Controls.Add(ctl); + this.plhContent.Controls.Add(ctl); } } } diff --git a/DNN Platform/Modules/Groups/ModerationServiceController.cs b/DNN Platform/Modules/Groups/ModerationServiceController.cs index e8a5ec7fc51..32f230b2ed5 100644 --- a/DNN Platform/Modules/Groups/ModerationServiceController.cs +++ b/DNN Platform/Modules/Groups/ModerationServiceController.cs @@ -1,48 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Web.Http; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Modules.Groups.Components; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; -using DotNetNuke.Security; -using DotNetNuke.Abstractions; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Groups { + using System; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [DnnAuthorize] public class ModerationServiceController : DnnApiController { - protected INavigationManager NavigationManager { get; } - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ModerationServiceController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModerationServiceController)); private int _tabId; private int _moduleId; + + protected INavigationManager NavigationManager { get; } private int _roleId; private int _memberId; private RoleInfo _roleInfo; public ModerationServiceController(INavigationManager navigationManager) { - NavigationManager = navigationManager; - } - - public class NotificationDTO - { - public int NotificationId { get; set; } + this.NavigationManager = navigationManager; } [HttpPost] @@ -51,37 +47,43 @@ public HttpResponseMessage ApproveGroup(NotificationDTO postData) { try { - var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID); - if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - + var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - ParseKey(notification.Context); - if (_roleInfo == null) + this.ParseKey(notification.Context); + if (this._roleInfo == null) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role"); } - if (!IsMod()) + + if (!this.IsMod()) { - return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!"); + return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!"); } - _roleInfo.Status = RoleStatus.Approved; - RoleController.Instance.UpdateRole(_roleInfo); - var roleCreator = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID); - //Update the original creator's role - RoleController.Instance.UpdateUserRole(PortalSettings.PortalId, roleCreator.UserID, _roleInfo.RoleID, RoleStatus.Approved, true, false); - GroupUtilities.CreateJournalEntry(_roleInfo, roleCreator); + + this._roleInfo.Status = RoleStatus.Approved; + RoleController.Instance.UpdateRole(this._roleInfo); + var roleCreator = UserController.GetUserById(this.PortalSettings.PortalId, this._roleInfo.CreatedByUserID); + + // Update the original creator's role + RoleController.Instance.UpdateUserRole(this.PortalSettings.PortalId, roleCreator.UserID, this._roleInfo.RoleID, RoleStatus.Approved, true, false); + GroupUtilities.CreateJournalEntry(this._roleInfo, roleCreator); var notifications = new Notifications(); - var siteAdmin = UserController.GetUserById(PortalSettings.PortalId, PortalSettings.AdministratorId); - notifications.AddGroupNotification(Constants.GroupApprovedNotification, _tabId, _moduleId, _roleInfo, siteAdmin, new List { _roleInfo }); + var siteAdmin = UserController.GetUserById(this.PortalSettings.PortalId, this.PortalSettings.AdministratorId); + notifications.AddGroupNotification(Constants.GroupApprovedNotification, this._tabId, this._moduleId, this._roleInfo, siteAdmin, new List { this._roleInfo }); NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -91,33 +93,38 @@ public HttpResponseMessage RejectGroup(NotificationDTO postData) { try { - var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID); - if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - + var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - ParseKey(notification.Context); - if (_roleInfo == null) + this.ParseKey(notification.Context); + if (this._roleInfo == null) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role"); } - if (!IsMod()) + + if (!this.IsMod()) { - return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!"); + return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!"); } + var notifications = new Notifications(); - var roleCreator = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID); - var siteAdmin = UserController.GetUserById(PortalSettings.PortalId, PortalSettings.AdministratorId); - notifications.AddGroupNotification(Constants.GroupRejectedNotification, _tabId, _moduleId, _roleInfo, siteAdmin, new List { _roleInfo }, roleCreator); + var roleCreator = UserController.GetUserById(this.PortalSettings.PortalId, this._roleInfo.CreatedByUserID); + var siteAdmin = UserController.GetUserById(this.PortalSettings.PortalId, this.PortalSettings.AdministratorId); + notifications.AddGroupNotification(Constants.GroupRejectedNotification, this._tabId, this._moduleId, this._roleInfo, siteAdmin, new List { this._roleInfo }, roleCreator); - var role = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == _roleId); + var role = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == this._roleId); RoleController.Instance.DeleteRole(role); NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -129,33 +136,33 @@ public HttpResponseMessage JoinGroup(RoleDTO postData) { try { - if (UserInfo.UserID >= 0 && postData.RoleId > -1) + if (this.UserInfo.UserID >= 0 && postData.RoleId > -1) { - _roleInfo = RoleController.Instance.GetRoleById(PortalSettings.PortalId, postData.RoleId); - if (_roleInfo != null) + this._roleInfo = RoleController.Instance.GetRoleById(this.PortalSettings.PortalId, postData.RoleId); + if (this._roleInfo != null) { - var requireApproval = false; - if(_roleInfo.Settings.ContainsKey("ReviewMembers")) - requireApproval = Convert.ToBoolean(_roleInfo.Settings["ReviewMembers"]); - + if (this._roleInfo.Settings.ContainsKey("ReviewMembers")) + { + requireApproval = Convert.ToBoolean(this._roleInfo.Settings["ReviewMembers"]); + } - if ((_roleInfo.IsPublic || UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) && !requireApproval) + if ((this._roleInfo.IsPublic || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) && !requireApproval) { - RoleController.Instance.AddUserRole(PortalSettings.PortalId, UserInfo.UserID, _roleInfo.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - RoleController.Instance.UpdateRole(_roleInfo); + RoleController.Instance.AddUserRole(this.PortalSettings.PortalId, this.UserInfo.UserID, this._roleInfo.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + RoleController.Instance.UpdateRole(this._roleInfo); - var url = NavigationManager.NavigateURL(postData.GroupViewTabId, "", new[] { "groupid=" + _roleInfo.RoleID }); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", URL = url }); - + var url = this.NavigationManager.NavigateURL(postData.GroupViewTabId, string.Empty, new[] { "groupid=" + this._roleInfo.RoleID }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", URL = url }); } - if (_roleInfo.IsPublic && requireApproval) + + if (this._roleInfo.IsPublic && requireApproval) { - RoleController.Instance.AddUserRole(PortalSettings.PortalId, UserInfo.UserID, _roleInfo.RoleID, RoleStatus.Pending, false, Null.NullDate, Null.NullDate); + RoleController.Instance.AddUserRole(this.PortalSettings.PortalId, this.UserInfo.UserID, this._roleInfo.RoleID, RoleStatus.Pending, false, Null.NullDate, Null.NullDate); var notifications = new Notifications(); - notifications.AddGroupOwnerNotification(Constants.MemberPendingNotification, _tabId, _moduleId, _roleInfo, UserInfo); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", URL = string.Empty }); + notifications.AddGroupOwnerNotification(Constants.MemberPendingNotification, this._tabId, this._moduleId, this._roleInfo, this.UserInfo); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", URL = string.Empty }); } } } @@ -163,16 +170,15 @@ public HttpResponseMessage JoinGroup(RoleDTO postData) catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } - public class RoleDTO + public class NotificationDTO { - public int RoleId { get; set; } - public int GroupViewTabId { get; set; } + public int NotificationId { get; set; } } [HttpPost] @@ -185,16 +191,17 @@ public HttpResponseMessage LeaveGroup(RoleDTO postData) try { - if (UserInfo.UserID >= 0 && postData.RoleId > 0) + if (this.UserInfo.UserID >= 0 && postData.RoleId > 0) { - _roleInfo = RoleController.Instance.GetRoleById(PortalSettings.PortalId, postData.RoleId); + this._roleInfo = RoleController.Instance.GetRoleById(this.PortalSettings.PortalId, postData.RoleId); - if (_roleInfo != null) + if (this._roleInfo != null) { - if (UserInfo.IsInRole(_roleInfo.RoleName)) + if (this.UserInfo.IsInRole(this._roleInfo.RoleName)) { - RoleController.DeleteUserRole(UserInfo, _roleInfo, PortalSettings, false); + RoleController.DeleteUserRole(this.UserInfo, this._roleInfo, this.PortalSettings, false); } + success = true; } } @@ -202,131 +209,147 @@ public HttpResponseMessage LeaveGroup(RoleDTO postData) catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - if(success) + if (success) { - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); + + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } - + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage ApproveMember(NotificationDTO postData) { try { - var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID); - if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - + var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - ParseKey(notification.Context); - if (_memberId <= 0) + this.ParseKey(notification.Context); + if (this._memberId <= 0) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Member"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Member"); } - if (_roleInfo == null) + if (this._roleInfo == null) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Role"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Role"); } - var member = UserController.GetUserById(PortalSettings.PortalId, _memberId); + var member = UserController.GetUserById(this.PortalSettings.PortalId, this._memberId); if (member != null) { - var memberRoleInfo = RoleController.Instance.GetUserRole(PortalSettings.PortalId, _memberId, _roleInfo.RoleID); + var memberRoleInfo = RoleController.Instance.GetUserRole(this.PortalSettings.PortalId, this._memberId, this._roleInfo.RoleID); memberRoleInfo.Status = RoleStatus.Approved; - RoleController.Instance.UpdateUserRole(PortalSettings.PortalId, _memberId, _roleInfo.RoleID, RoleStatus.Approved, false, false); - + RoleController.Instance.UpdateUserRole(this.PortalSettings.PortalId, this._memberId, this._roleInfo.RoleID, RoleStatus.Approved, false, false); + var notifications = new Notifications(); - var groupOwner = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID); - notifications.AddMemberNotification(Constants.MemberApprovedNotification, _tabId, _moduleId, _roleInfo, groupOwner, member); + var groupOwner = UserController.GetUserById(this.PortalSettings.PortalId, this._roleInfo.CreatedByUserID); + notifications.AddMemberNotification(Constants.MemberApprovedNotification, this._tabId, this._moduleId, this._roleInfo, groupOwner, member); NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - } catch (Exception exc) + } + catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage RejectMember(NotificationDTO postData) { try { - var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID); - if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - + var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - ParseKey(notification.Context); - if (_memberId <= 0) + this.ParseKey(notification.Context); + if (this._memberId <= 0) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Member"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Member"); } - if (_roleInfo == null) + + if (this._roleInfo == null) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Role"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Role"); } - var member = UserController.GetUserById(PortalSettings.PortalId, _memberId); - - - + var member = UserController.GetUserById(this.PortalSettings.PortalId, this._memberId); + if (member != null) { - RoleController.DeleteUserRole(member, _roleInfo, PortalSettings, false) ; + RoleController.DeleteUserRole(member, this._roleInfo, this.PortalSettings, false); var notifications = new Notifications(); - var groupOwner = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID); - notifications.AddMemberNotification(Constants.MemberRejectedNotification, _tabId, _moduleId, _roleInfo, groupOwner, member); + var groupOwner = UserController.GetUserById(this.PortalSettings.PortalId, this._roleInfo.CreatedByUserID); + notifications.AddMemberNotification(Constants.MemberRejectedNotification, this._tabId, this._moduleId, this._roleInfo, groupOwner, member); NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - } catch (Exception exc) + } + catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } - + + public class RoleDTO + { + public int RoleId { get; set; } + + public int GroupViewTabId { get; set; } + } + private void ParseKey(string key) { - _tabId = -1; - _moduleId = -1; - _roleId = -1; - _memberId = -1; - _roleInfo = null; - if (!String.IsNullOrEmpty(key)) + this._tabId = -1; + this._moduleId = -1; + this._roleId = -1; + this._memberId = -1; + this._roleInfo = null; + if (!string.IsNullOrEmpty(key)) { string[] keys = key.Split(':'); - _tabId = Convert.ToInt32(keys[0]); - _moduleId = Convert.ToInt32(keys[1]); - _roleId = Convert.ToInt32(keys[2]); + this._tabId = Convert.ToInt32(keys[0]); + this._moduleId = Convert.ToInt32(keys[1]); + this._roleId = Convert.ToInt32(keys[2]); if (keys.Length > 3) { - _memberId = Convert.ToInt32(keys[3]); + this._memberId = Convert.ToInt32(keys[3]); } } - if (_roleId > 0) + + if (this._roleId > 0) { - _roleInfo = RoleController.Instance.GetRoleById(PortalSettings.PortalId, _roleId); + this._roleInfo = RoleController.Instance.GetRoleById(this.PortalSettings.PortalId, this._roleId); } } private bool IsMod() { - var objModulePermissions = new ModulePermissionCollection(CBO.FillCollection(DataProvider.Instance().GetModulePermissionsByModuleID(_moduleId, -1), typeof(ModulePermissionInfo))); + var objModulePermissions = new ModulePermissionCollection(CBO.FillCollection(DataProvider.Instance().GetModulePermissionsByModuleID(this._moduleId, -1), typeof(ModulePermissionInfo))); return ModulePermissionController.HasModulePermission(objModulePermissions, "MODGROUP"); } } diff --git a/DNN Platform/Modules/Groups/Properties/AssemblyInfo.cs b/DNN Platform/Modules/Groups/Properties/AssemblyInfo.cs index 7de3d5117f6..c9a1e38c52f 100644 --- a/DNN Platform/Modules/Groups/Properties/AssemblyInfo.cs +++ b/DNN Platform/Modules/Groups/Properties/AssemblyInfo.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System; using System.Reflection; using System.Runtime.InteropServices; -// -// General Information about an assembly is controlled through the following +// 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. // diff --git a/DNN Platform/Modules/Groups/Setup.ascx.cs b/DNN Platform/Modules/Groups/Setup.ascx.cs index beeb35d6c2a..e96166156c1 100644 --- a/DNN Platform/Modules/Groups/Setup.ascx.cs +++ b/DNN Platform/Modules/Groups/Setup.ascx.cs @@ -1,81 +1,76 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Modules.Groups.Components; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Groups { + using System; + using System.Collections; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.UI.Skins; + public partial class Setup : GroupsModuleBase { - protected void Page_Load(object sender, EventArgs e) - { - btnGo.Visible = Request.IsAuthenticated; - btnGo.Enabled = Request.IsAuthenticated; - btnGo.Click += btGo_Click; - } - public void btGo_Click(object sender, EventArgs e) { - //Setup Child Page - Main View/Activity - TabInfo tab = CreatePage(PortalSettings.ActiveTab, PortalId, TabId, "Group Activity", false); + // Setup Child Page - Main View/Activity + TabInfo tab = this.CreatePage(this.PortalSettings.ActiveTab, this.PortalId, this.TabId, "Group Activity", false); - //Add Module to Child Page - int groupViewModuleId = AddModule(tab, PortalId, "Social Groups", "ContentPane"); - int journalModuleId = AddModule(tab, PortalId, "Journal", "ContentPane"); - int consoleId = AddModule(tab, PortalId, "Console", "RightPane"); + // Add Module to Child Page + int groupViewModuleId = this.AddModule(tab, this.PortalId, "Social Groups", "ContentPane"); + int journalModuleId = this.AddModule(tab, this.PortalId, "Journal", "ContentPane"); + int consoleId = this.AddModule(tab, this.PortalId, "Console", "RightPane"); ModuleInfo groupConsoleModule = ModuleController.Instance.GetModule(consoleId, tab.TabID, false); - TabInfo memberTab = CreatePage(PortalSettings.ActiveTab, PortalId, tab.TabID, "Members", true); + TabInfo memberTab = this.CreatePage(this.PortalSettings.ActiveTab, this.PortalId, tab.TabID, "Members", true); ModuleController.Instance.CopyModule(groupConsoleModule, memberTab, "RightPane", true); ModuleInfo groupViewModule = ModuleController.Instance.GetModule(groupViewModuleId, tab.TabID, false); ModuleController.Instance.CopyModule(groupViewModule, memberTab, "ContentPane", true); - AddModule(memberTab, PortalId, "DotNetNuke.Modules.MemberDirectory", "ContentPane"); - - - //List Settings - ModuleController.Instance.UpdateTabModuleSetting(TabModuleId, Constants.GroupLoadView, GroupMode.List.ToString()); - ModuleController.Instance.UpdateTabModuleSetting(TabModuleId, Constants.GroupViewPage, tab.TabID.ToString(CultureInfo.InvariantCulture)); - - //Default Social Groups - var defaultGroup = RoleController.GetRoleGroupByName(PortalId, Constants.DefaultGroupName); - var groupId = -2; - if (defaultGroup != null) - { - groupId = defaultGroup.RoleGroupID; - } - else - { - var groupInfo = new RoleGroupInfo(); - groupInfo.PortalID = PortalId; + this.AddModule(memberTab, this.PortalId, "DotNetNuke.Modules.MemberDirectory", "ContentPane"); + + // List Settings + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupLoadView, GroupMode.List.ToString()); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.GroupViewPage, tab.TabID.ToString(CultureInfo.InvariantCulture)); + + // Default Social Groups + var defaultGroup = RoleController.GetRoleGroupByName(this.PortalId, Constants.DefaultGroupName); + var groupId = -2; + if (defaultGroup != null) + { + groupId = defaultGroup.RoleGroupID; + } + else + { + var groupInfo = new RoleGroupInfo(); + groupInfo.PortalID = this.PortalId; groupInfo.RoleGroupName = Constants.DefaultGroupName; groupInfo.Description = Constants.DefaultGroupName; - groupId = RoleController.AddRoleGroup(groupInfo); - } - ModuleController.Instance.UpdateTabModuleSetting(TabModuleId, Constants.DefaultRoleGroupSetting, groupId.ToString()); + groupId = RoleController.AddRoleGroup(groupInfo); + } + + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, Constants.DefaultRoleGroupSetting, groupId.ToString()); - Response.Redirect(Request.RawUrl); + this.Response.Redirect(this.Request.RawUrl); + } + + protected void Page_Load(object sender, EventArgs e) + { + this.btnGo.Visible = this.Request.IsAuthenticated; + this.btnGo.Enabled = this.Request.IsAuthenticated; + this.btnGo.Click += this.btGo_Click; } private TabInfo CreatePage(TabInfo tab, int portalId, int parentTabId, string tabName, bool includeInMenu) @@ -104,7 +99,7 @@ private TabInfo CreatePage(TabInfo tab, int portalId, int parentTabId, string ta TabID = -1, TabPermissionID = -1, UserID = t.UserID, - Username = t.Username + Username = t.Username, }; newTab.TabPermissions.Add(tNew); } @@ -115,20 +110,21 @@ private TabInfo CreatePage(TabInfo tab, int portalId, int parentTabId, string ta newTab.TabName = tabName; newTab.Title = tabName; newTab.IsVisible = includeInMenu; - newTab.SkinSrc = GetSkin(); + newTab.SkinSrc = this.GetSkin(); id = TabController.Instance.AddTab(newTab); newTab = TabController.Instance.GetTab(id, portalId, true); } + return newTab; } private string GetSkin() { - //attempt to find and load a skin from the assigned skinned source - var skinSource = PortalSettings.DefaultPortalSkin; + // attempt to find and load a skin from the assigned skinned source + var skinSource = this.PortalSettings.DefaultPortalSkin; - var tab = TabController.Instance.GetTab(TabId, PortalId, false); + var tab = TabController.Instance.GetTab(this.TabId, this.PortalId, false); if (!string.IsNullOrEmpty(tab.SkinSrc)) { @@ -137,30 +133,32 @@ private string GetSkin() else { skinSource = SkinController.FormatSkinPath(skinSource) + "groups.ascx"; - var physicalSkinFile = SkinController.FormatSkinSrc(skinSource, PortalSettings); + var physicalSkinFile = SkinController.FormatSkinSrc(skinSource, this.PortalSettings); if (!File.Exists(HttpContext.Current.Server.MapPath(physicalSkinFile))) { - skinSource = ""; //this will load the default skin + skinSource = string.Empty; // this will load the default skin } } + return skinSource; } private int AddModule(TabInfo tab, int portalId, string moduleName, string pane) { - var module = ModuleController.Instance.GetTabModules(tab.TabID).Values.SingleOrDefault(m => m.DesktopModule.ModuleName == moduleName); + var module = ModuleController.Instance.GetTabModules(tab.TabID).Values.SingleOrDefault(m => m.DesktopModule.ModuleName == moduleName); int id = -1; if (module == null) { - int desktopModuleId = GetDesktopModuleId(portalId, moduleName); + int desktopModuleId = this.GetDesktopModuleId(portalId, moduleName); int moduleId = -1; if (desktopModuleId > -1) { if (moduleId <= 0) { - moduleId = AddNewModule(tab, string.Empty, desktopModuleId, pane, 0, string.Empty); + moduleId = this.AddNewModule(tab, string.Empty, desktopModuleId, pane, 0, string.Empty); } + id = moduleId; ModuleInfo mi = ModuleController.Instance.GetModule(moduleId, tab.TabID, false); if (moduleName == "Social Groups") @@ -168,6 +166,7 @@ private int AddModule(TabInfo tab, int portalId, string moduleName, string pane) ModuleController.Instance.UpdateTabModuleSetting(mi.TabModuleID, Constants.GroupLoadView, GroupMode.View.ToString()); ModuleController.Instance.UpdateTabModuleSetting(mi.TabModuleID, Constants.GroupListPage, tab.TabID.ToString(CultureInfo.InvariantCulture)); } + if (moduleName == "Console") { ModuleController.Instance.UpdateModuleSetting(mi.ModuleID, "AllowSizeChange", "False"); @@ -177,10 +176,11 @@ private int AddModule(TabInfo tab, int portalId, string moduleName, string pane) ModuleController.Instance.UpdateModuleSetting(mi.ModuleID, "DefaultSize", "IconNone"); ModuleController.Instance.UpdateModuleSetting(mi.ModuleID, "ParentTabID", tab.TabID.ToString(CultureInfo.InvariantCulture)); } + if (moduleName == "DotNetNuke.Modules.MemberDirectory") { ModuleController.Instance.UpdateModuleSetting(mi.ModuleID, "FilterBy", "Group"); - ModuleController.Instance.UpdateModuleSetting(mi.ModuleID, "FilterPropertyValue", ""); + ModuleController.Instance.UpdateModuleSetting(mi.ModuleID, "FilterPropertyValue", string.Empty); ModuleController.Instance.UpdateModuleSetting(mi.ModuleID, "FilterValue", "-1"); ModuleController.Instance.UpdateTabModuleSetting(mi.TabModuleID, "DisplaySearch", "False"); } @@ -221,6 +221,7 @@ private int AddNewModule(TabInfo tab, string title, int desktopModuleId, string { objModule.ModuleTitle = title; } + objModule.PaneName = paneName; objModule.ModuleDefID = objModuleDefinition.ModuleDefID; objModule.CacheTime = 0; @@ -235,38 +236,41 @@ private int AddNewModule(TabInfo tab, string title, int desktopModuleId, string { if (objTabPermission.PermissionKey == "VIEW" && permissionType == 0) { - //Don't need to explicitly add View permisisons if "Same As Page" + // Don't need to explicitly add View permisisons if "Same As Page" continue; } // get the system module permissions for the permissionkey ArrayList arrSystemModulePermissions = objPermissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", objTabPermission.PermissionKey); + // loop through the system module permissions for (j = 0; j <= arrSystemModulePermissions.Count - 1; j++) { // create the module permission PermissionInfo objSystemModulePermission = default(PermissionInfo); - objSystemModulePermission = (PermissionInfo) arrSystemModulePermissions[j]; + objSystemModulePermission = (PermissionInfo)arrSystemModulePermissions[j]; if (objSystemModulePermission.PermissionKey == "VIEW" && permissionType == 1 && objTabPermission.PermissionKey != "EDIT") { - //Only Page Editors get View permissions if "Page Editors Only" + // Only Page Editors get View permissions if "Page Editors Only" continue; } - ModulePermissionInfo objModulePermission = AddModulePermission(objModule, - objSystemModulePermission, - objTabPermission.RoleID, - objTabPermission.UserID, - objTabPermission.AllowAccess); + ModulePermissionInfo objModulePermission = this.AddModulePermission( + objModule, + objSystemModulePermission, + objTabPermission.RoleID, + objTabPermission.UserID, + objTabPermission.AllowAccess); // ensure that every EDIT permission which allows access also provides VIEW permission if (objModulePermission.PermissionKey == "EDIT" & objModulePermission.AllowAccess) { - ModulePermissionInfo objModuleViewperm = AddModulePermission(objModule, - (PermissionInfo) arrSystemModuleViewPermissions[0], - objModulePermission.RoleID, - objModulePermission.UserID, - true); + ModulePermissionInfo objModuleViewperm = this.AddModulePermission( + objModule, + (PermissionInfo)arrSystemModuleViewPermissions[0], + objModulePermission.RoleID, + objModulePermission.UserID, + true); } } } @@ -276,6 +280,7 @@ private int AddNewModule(TabInfo tab, string title, int desktopModuleId, string return ModuleController.Instance.AddModule(objModule); } + return -1; } @@ -294,6 +299,7 @@ private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, Permissio { objModule.ModulePermissions = new ModulePermissionCollection(); } + if (!objModule.ModulePermissions.Contains(objModulePermission)) { objModule.ModulePermissions.Add(objModulePermission); diff --git a/DNN Platform/Modules/Groups/SocialGroups.dnn b/DNN Platform/Modules/Groups/SocialGroups.dnn index 472f656371f..1e23d1bc116 100644 --- a/DNN Platform/Modules/Groups/SocialGroups.dnn +++ b/DNN Platform/Modules/Groups/SocialGroups.dnn @@ -1,6 +1,6 @@ - + Social Groups DotNetNuke Corporation Social Groups module ~/DesktopModules/SocialGroups/Images/Social_Groups_32X32.png diff --git a/DNN Platform/Modules/Groups/View.ascx.cs b/DNN Platform/Modules/Groups/View.ascx.cs index 437743da879..00950eca756 100644 --- a/DNN Platform/Modules/Groups/View.ascx.cs +++ b/DNN Platform/Modules/Groups/View.ascx.cs @@ -1,57 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Modules.Groups.Components; -using DotNetNuke.Common; -using DotNetNuke.Framework; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Groups { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.Groups.Components; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// - /// The ViewSocialGroups class displays the content + /// The ViewSocialGroups class displays the content. /// /// ----------------------------------------------------------------------------- public partial class View : GroupsModuleBase { private readonly INavigationManager _navigationManager; + public View() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Event Handlers - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + protected override void OnInit(EventArgs e) { - InitializeComponent(); + this.InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { - Load += Page_Load; + this.Load += this.Page_Load; } - - + /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// ----------------------------------------------------------------------------- private void Page_Load(object sender, EventArgs e) @@ -59,25 +52,23 @@ private void Page_Load(object sender, EventArgs e) try { JavaScript.RequestRegistration(CommonJs.DnnPlugins); - if (GroupId < 0) { - if (TabId != GroupListTabId && !UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) { - Response.Redirect(_navigationManager.NavigateURL(GroupListTabId)); + if (this.GroupId < 0) + { + if (this.TabId != this.GroupListTabId && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) + { + this.Response.Redirect(this._navigationManager.NavigateURL(this.GroupListTabId)); } } - GroupsModuleBase ctl = (GroupsModuleBase)LoadControl(ControlPath); + + GroupsModuleBase ctl = (GroupsModuleBase)this.LoadControl(this.ControlPath); ctl.ModuleConfiguration = this.ModuleConfiguration; - plhContent.Controls.Clear(); - plhContent.Controls.Add(ctl); - + this.plhContent.Controls.Clear(); + this.plhContent.Controls.Add(ctl); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - - + } } } diff --git a/DNN Platform/Modules/Groups/packages.config b/DNN Platform/Modules/Groups/packages.config index 4073d3c4617..78db8377d2d 100644 --- a/DNN Platform/Modules/Groups/packages.config +++ b/DNN Platform/Modules/Groups/packages.config @@ -1,10 +1,11 @@ - - - - - - - - - + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/HTML/AssemblyInfo.cs b/DNN Platform/Modules/HTML/AssemblyInfo.cs index 7f7eba62199..0c079432882 100644 --- a/DNN Platform/Modules/HTML/AssemblyInfo.cs +++ b/DNN Platform/Modules/HTML/AssemblyInfo.cs @@ -1,25 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; -using System.Runtime.InteropServices; - - -#endregion - -// 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. - -// Review the values of the assembly attributes - +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. + +// Review the values of the assembly attributes [assembly: AssemblyTitle("DotNetNuke.Modules.Html")] [assembly: AssemblyDescription("HTML Module for Open Source Web Application Framework")] [assembly: ComVisible(false)] -//The following GUID is for the ID of the typelib if this project is exposed to COM - + +// The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("334e9cee-0d47-4d70-924b-b5098a3432cb")] diff --git a/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs b/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs index b71188587c9..56eacafcc99 100644 --- a/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs +++ b/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs @@ -1,30 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Permissions { + using System.Collections; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : CompareWorkflowStatePermissions + /// Class : CompareWorkflowStatePermissions /// ----------------------------------------------------------------------------- /// - /// CompareWorkflowStatePermissions provides the a custom IComparer implementation for - /// WorkflowStatePermissionInfo objects + /// CompareWorkflowStatePermissions provides the a custom IComparer implementation for + /// WorkflowStatePermissionInfo objects. /// internal class CompareWorkflowStatePermissions : IComparer - { - #region IComparer Interface - + { public int Compare(object x, object y) { - return ((WorkflowStatePermissionInfo) x).WorkflowStatePermissionID.CompareTo(((WorkflowStatePermissionInfo) y).WorkflowStatePermissionID); - } - - #endregion + return ((WorkflowStatePermissionInfo)x).WorkflowStatePermissionID.CompareTo(((WorkflowStatePermissionInfo)y).WorkflowStatePermissionID); + } } } diff --git a/DNN Platform/Modules/HTML/Components/DataProvider.cs b/DNN Platform/Modules/HTML/Components/DataProvider.cs index 92533f28628..05f066e33a7 100644 --- a/DNN Platform/Modules/HTML/Components/DataProvider.cs +++ b/DNN Platform/Modules/HTML/Components/DataProvider.cs @@ -1,24 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html.Components { + using System; + using System.Data; + /// ----------------------------------------------------------------------------- /// - /// The DataProvider is an abstract class that provides the Data Access Layer for the HtmlText module + /// The DataProvider is an abstract class that provides the Data Access Layer for the HtmlText module. /// /// /// public class DataProvider - { - #region Shared/Static Methods - - // singleton reference to the instantiated object - + { + // singleton reference to the instantiated object private static readonly DataProvider provider; // constructor @@ -31,25 +28,21 @@ static DataProvider() public static DataProvider Instance() { return provider; - } - - #endregion - - #region Virtual Methods - + } + public virtual IDataReader GetHtmlText(int ModuleID, int ItemID) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetHtmlText", ModuleID, ItemID)); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetHtmlText", ModuleID, ItemID); } public virtual IDataReader GetTopHtmlText(int ModuleID, bool IsPublished) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetTopHtmlText", ModuleID, IsPublished)); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetTopHtmlText", ModuleID, IsPublished); } public virtual IDataReader GetAllHtmlText(int ModuleID) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetAllHtmlText", ModuleID)); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetAllHtmlText", ModuleID); } public virtual int AddHtmlText(int ModuleID, string Content, string Summary, int StateID, bool IsPublished, int CreatedByUserID, int History) @@ -69,7 +62,7 @@ public virtual void DeleteHtmlText(int ModuleID, int ItemID) public virtual IDataReader GetHtmlTextLog(int ItemID) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetHtmlTextLog", ItemID)); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetHtmlTextLog", ItemID); } public virtual void AddHtmlTextLog(int ItemID, int StateID, string Comment, bool Approved, int CreatedByUserID) @@ -79,7 +72,7 @@ public virtual void AddHtmlTextLog(int ItemID, int StateID, string Comment, bool public virtual IDataReader GetHtmlTextUser(int UserID) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetHtmlTextUser", UserID)); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetHtmlTextUser", UserID); } public virtual void AddHtmlTextUser(int ItemID, int StateID, int ModuleID, int TabID, int UserID) @@ -94,24 +87,22 @@ public virtual void DeleteHtmlTextUsers() public virtual IDataReader GetWorkflows(int PortalID) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflows", PortalID)); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflows", PortalID); } public virtual IDataReader GetWorkflowStates(int WorkflowID) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflowStates", WorkflowID)); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflowStates", WorkflowID); } public virtual IDataReader GetWorkflowStatePermissions() { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflowStatePermissions")); + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflowStatePermissions"); } public virtual IDataReader GetWorkflowStatePermissionsByStateID(int StateID) { - return (DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflowStatePermissionsByStateID", StateID)); - } - - #endregion + return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflowStatePermissionsByStateID", StateID); + } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs b/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs index 53195cd028c..13ab8d69807 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs @@ -1,30 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Modules; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html.Components { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Entities.Modules; + public class HtmlModuleBase : PortalModuleBase { private HtmlModuleSettings _settings; + public new HtmlModuleSettings Settings { get { - if (_settings == null) + if (this._settings == null) { var repo = new HtmlModuleSettingsRepository(); - _settings = repo.GetSettings(this.ModuleConfiguration); + this._settings = repo.GetSettings(this.ModuleConfiguration); } - return _settings; + + return this._settings; } - set { _settings = value; } + + set { this._settings = value; } } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs b/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs index 69c7c31d7d4..16bbff5ac35 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules.Settings; -using System.Web.Caching; -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html.Components { + using System; + using System.Web.Caching; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules.Settings; + /// - /// An example implementation of the + /// An example implementation of the . /// /// - /// HtmlModuleSettings provides a strongly typed list of properties used by + /// HtmlModuleSettings provides a strongly typed list of properties used by /// the HTML module. Settings will automatically be serialized and deserialized /// for storage in the underlying settings table. /// @@ -29,12 +30,12 @@ public class HtmlModuleSettings [ModuleSetting(Prefix = "HtmlText_")] public int SearchDescLength { get; set; } = 100; - [ModuleSetting()] + [ModuleSetting] public int WorkFlowID { get; set; } = -1; } /// - /// The used for storing and retrieving + /// The used for storing and retrieving . /// public class HtmlModuleSettingsRepository : SettingsRepository { diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs index 004e456f004..3ab6195d0b8 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs @@ -1,59 +1,217 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.UI; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Modules.Html.Components; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Abstractions; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Html { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.Html.Components; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Services.Tokens; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: HtmlTextController /// ----------------------------------------------------------------------------- /// - /// The HtmlTextController is the Controller class for managing HtmlText information the HtmlText module + /// The HtmlTextController is the Controller class for managing HtmlText information the HtmlText module. /// /// /// public class HtmlTextController : ModuleSearchBase, IPortable, IUpgradeable { - public const int MAX_DESCRIPTION_LENGTH = 100; + public const int MAX_DESCRIPTION_LENGTH = 100; private const string PortalRootToken = "{{PortalRoot}}"; - protected INavigationManager NavigationManager { get; } + public HtmlTextController() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + } + + protected INavigationManager NavigationManager { get; } + + /// ----------------------------------------------------------------------------- + /// + /// FormatHtmlText formats HtmlText content for display in the browser. + /// + /// + /// + /// The ModuleID. + /// The HtmlText Content. + /// Module Settings. + /// The Portal Settings. + /// The Page Instance. + /// + public static string FormatHtmlText(int moduleId, string content, HtmlModuleSettings settings, PortalSettings portalSettings, Page page) + { + // token replace + if (settings.ReplaceTokens) + { + var tr = new HtmlTokenReplace(page) + { + AccessingUser = UserController.Instance.GetCurrentUserInfo(), + DebugMessages = portalSettings.UserMode != PortalSettings.Mode.View, + ModuleId = moduleId, + PortalSettings = portalSettings, + }; + content = tr.ReplaceEnvironmentTokens(content); + } + + // Html decode content + content = HttpUtility.HtmlDecode(content); + + // manage relative paths + content = ManageRelativePaths(content, portalSettings.HomeDirectory, "src", portalSettings.PortalId); + content = ManageRelativePaths(content, portalSettings.HomeDirectory, "background", portalSettings.PortalId); + + return content; + } + + public static string ManageRelativePaths(string strHTML, string strUploadDirectory, string strToken, int intPortalID) + { + int P = 0; + int R = 0; + int S = 0; + int tLen = 0; + string strURL = null; + var sbBuff = new StringBuilder(string.Empty); + + if (!string.IsNullOrEmpty(strHTML)) + { + tLen = strToken.Length + 2; + string uploadDirectory = strUploadDirectory.ToLowerInvariant(); + + // find position of first occurrance: + P = strHTML.IndexOf(strToken + "=\"", StringComparison.InvariantCultureIgnoreCase); + while (P != -1) + { + sbBuff.Append(strHTML.Substring(S, P - S + tLen)); + + // keep charactes left of URL + S = P + tLen; + + // save startpos of URL + R = strHTML.IndexOf("\"", S); + + // end of URL + if (R >= 0) + { + strURL = strHTML.Substring(S, R - S).ToLowerInvariant(); + } + else + { + strURL = strHTML.Substring(S).ToLowerInvariant(); + } + + if (strHTML.Substring(P + tLen, 10).Equals("data:image", StringComparison.InvariantCultureIgnoreCase)) + { + P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); + continue; + } + + // if we are linking internally + if (!strURL.Contains("://")) + { + // remove the leading portion of the path if the URL contains the upload directory structure + string strDirectory = uploadDirectory; + if (!strDirectory.EndsWith("/")) + { + strDirectory += "/"; + } + + if (strURL.IndexOf(strDirectory) != -1) + { + S = S + strURL.IndexOf(strDirectory) + strDirectory.Length; + strURL = strURL.Substring(strURL.IndexOf(strDirectory) + strDirectory.Length); + } + + // add upload directory + if (!strURL.StartsWith("/") + && !string.IsNullOrEmpty(strURL.Trim())) // We don't write the UploadDirectory if the token/attribute has not value. Therefore we will avoid an unnecessary request + { + sbBuff.Append(uploadDirectory); + } + } + + // find position of next occurrance + P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); + } + + if (S > -1) + { + sbBuff.Append(strHTML.Substring(S)); + } + + // append characters of last URL and behind + } + + return sbBuff.ToString(); + } + + public string ReplaceWithRootToken(Match m) + { + var domain = m.Groups["domain"].Value; + + // Relative url + if (string.IsNullOrEmpty(domain)) + { + return PortalRootToken; + } + + var aliases = PortalAliasController.Instance.GetPortalAliases(); + if (!aliases.Contains(domain)) + { + // this is no not a portal url so even if it contains /portals/.. + // we do not need to replace it with a token + return m.ToString(); + } + + // full qualified portal url that needs to be tokenized + var result = domain + PortalRootToken; + var protocol = m.Groups["protocol"].Value; + return string.IsNullOrEmpty(protocol) ? result : protocol + result; } - #region Private Methods + /// ----------------------------------------------------------------------------- + /// + /// DeleteHtmlText deletes an HtmlTextInfo object for the Module and Item. + /// + /// + /// + /// The ID of the Module. + /// The ID of the Item. + public void DeleteHtmlText(int ModuleID, int ItemID) + { + DataProvider.Instance().DeleteHtmlText(ModuleID, ItemID); + + // refresh output cache + ModuleController.SynchronizeModule(ModuleID); + } private static void AddHtmlNotification(string subject, string body, UserInfo user) { @@ -61,7 +219,7 @@ private static void AddHtmlNotification(string subject, string body, UserInfo us var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var sender = UserController.GetUserById(portalSettings.PortalId, portalSettings.AdministratorId); - var notification = new Notification {NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID}; + var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID }; NotificationsController.Instance.SendNotification(notification, portalSettings.PortalId, null, new List { user }); } @@ -75,11 +233,11 @@ private void ClearModuleSettings(ModuleInfo objModule) /// ----------------------------------------------------------------------------- /// - /// CreateUserNotifications creates HtmlTextUser records and optionally sends email notifications to participants in a Workflow + /// CreateUserNotifications creates HtmlTextUser records and optionally sends email notifications to participants in a Workflow. /// /// /// - /// An HtmlTextInfo object + /// An HtmlTextInfo object. private void CreateUserNotifications(HtmlTextInfo objHtmlText) { var _htmlTextUserController = new HtmlTextUserController(); @@ -90,7 +248,7 @@ private void CreateUserNotifications(HtmlTextInfo objHtmlText) _htmlTextUserController.DeleteHtmlTextUsers(); // ensure we have latest htmltext object loaded - objHtmlText = GetHtmlText(objHtmlText.ModuleID, objHtmlText.ItemID); + objHtmlText = this.GetHtmlText(objHtmlText.ModuleID, objHtmlText.ItemID); // build collection of users to notify var objWorkflow = new WorkflowStateController(); @@ -114,7 +272,7 @@ private void CreateUserNotifications(HtmlTextInfo objHtmlText) { int roleId = permission.RoleID; RoleInfo objRole = RoleController.Instance.GetRole(objHtmlText.PortalID, r => r.RoleID == roleId); - if ((objRole != null)) + if (objRole != null) { foreach (UserRoleInfo objUserRole in RoleController.Instance.GetUserRoles(objHtmlText.PortalID, null, objRole.RoleName)) { @@ -145,18 +303,18 @@ private void CreateUserNotifications(HtmlTextInfo objHtmlText) PortalSettings objPortalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (objPortalSettings != null) { - string strResourceFile = string.Format("{0}/DesktopModules/{1}/{2}/{3}", - Globals.ApplicationPath, - objModule.DesktopModule.FolderName, - Localization.LocalResourceDirectory, - Localization.LocalSharedResourceFile); + string strResourceFile = string.Format( + "{0}/DesktopModules/{1}/{2}/{3}", + Globals.ApplicationPath, + objModule.DesktopModule.FolderName, + Localization.LocalResourceDirectory, + Localization.LocalSharedResourceFile); string strSubject = Localization.GetString("NotificationSubject", strResourceFile); string strBody = Localization.GetString("NotificationBody", strResourceFile); - strBody = strBody.Replace("[URL]", NavigationManager.NavigateURL(objModule.TabID)); + strBody = strBody.Replace("[URL]", this.NavigationManager.NavigateURL(objModule.TabID)); strBody = strBody.Replace("[STATE]", objHtmlText.StateName); // process user notification collection - foreach (int intUserID in arrUsers) { // create user notification record @@ -208,10 +366,12 @@ private string DeTokeniseLinks(string content, int portalId) { portalRoot = "/" + portalRoot; } + if (!portalRoot.EndsWith("/")) { portalRoot = portalRoot + "/"; } + content = Regex.Replace(content, PortalRootToken + "\\/{0,1}", portalRoot, RegexOptions.IgnoreCase); return content; @@ -219,13 +379,14 @@ private string DeTokeniseLinks(string content, int portalId) private string TokeniseLinks(string content, int portalId) { - //Replace any relative portal root reference by a token "{{PortalRoot}}" + // Replace any relative portal root reference by a token "{{PortalRoot}}" var portal = PortalController.Instance.GetPortal(portalId); var portalRoot = UrlUtils.Combine(Globals.ApplicationPath, portal.HomeDirectory); if (!portalRoot.StartsWith("/")) { portalRoot = "/" + portalRoot; } + if (!portalRoot.EndsWith("/")) { portalRoot = portalRoot + "/"; @@ -238,99 +399,19 @@ private string TokeniseLinks(string content, int portalId) (?(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+))? (?" + portalRoot + "))"; - var matchEvaluator = new MatchEvaluator(ReplaceWithRootToken); + var matchEvaluator = new MatchEvaluator(this.ReplaceWithRootToken); var exp = RegexUtils.GetCachedRegex(regex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); return exp.Replace(content, matchEvaluator); } - public string ReplaceWithRootToken(Match m) - { - var domain = m.Groups["domain"].Value; - - // Relative url - if (string.IsNullOrEmpty(domain)) - { - return PortalRootToken; - } - - var aliases = PortalAliasController.Instance.GetPortalAliases(); - if (!aliases.Contains(domain)) - { - // this is no not a portal url so even if it contains /portals/.. - // we do not need to replace it with a token - return m.ToString(); - } - - // full qualified portal url that needs to be tokenized - var result = domain + PortalRootToken; - var protocol = m.Groups["protocol"].Value; - return string.IsNullOrEmpty(protocol) ? result : protocol + result; - } - - #endregion - - #region Public Methods - - /// ----------------------------------------------------------------------------- - /// - /// DeleteHtmlText deletes an HtmlTextInfo object for the Module and Item - /// - /// - /// - /// The ID of the Module - /// The ID of the Item - public void DeleteHtmlText(int ModuleID, int ItemID) - { - DataProvider.Instance().DeleteHtmlText(ModuleID, ItemID); - - // refresh output cache - ModuleController.SynchronizeModule(ModuleID); - } - - /// ----------------------------------------------------------------------------- - /// - /// FormatHtmlText formats HtmlText content for display in the browser - /// - /// - /// - /// The ModuleID - /// The HtmlText Content - /// Module Settings - /// The Portal Settings. - /// The Page Instance. - public static string FormatHtmlText(int moduleId, string content, HtmlModuleSettings settings, PortalSettings portalSettings, Page page) - { - // token replace - - if (settings.ReplaceTokens) - { - var tr = new HtmlTokenReplace(page) - { - AccessingUser = UserController.Instance.GetCurrentUserInfo(), - DebugMessages = portalSettings.UserMode != PortalSettings.Mode.View, - ModuleId = moduleId, - PortalSettings = portalSettings - }; - content = tr.ReplaceEnvironmentTokens(content); - } - - // Html decode content - content = HttpUtility.HtmlDecode(content); - - // manage relative paths - content = ManageRelativePaths(content, portalSettings.HomeDirectory, "src", portalSettings.PortalId); - content = ManageRelativePaths(content, portalSettings.HomeDirectory, "background", portalSettings.PortalId); - - return content; - } - /// ----------------------------------------------------------------------------- /// - /// GetAllHtmlText gets a collection of HtmlTextInfo objects for the Module and Workflow + /// GetAllHtmlText gets a collection of HtmlTextInfo objects for the Module and Workflow. /// /// /// - /// The ID of the Module + /// The ID of the Module. + /// public List GetAllHtmlText(int ModuleID) { return CBO.FillCollection(DataProvider.Instance().GetAllHtmlText(ModuleID)); @@ -338,12 +419,13 @@ public List GetAllHtmlText(int ModuleID) /// ----------------------------------------------------------------------------- /// - /// GetHtmlText gets the HtmlTextInfo object for the Module, Item, and Workflow + /// GetHtmlText gets the HtmlTextInfo object for the Module, Item, and Workflow. /// /// /// - /// The ID of the Module - /// The ID of the Item + /// The ID of the Module. + /// The ID of the Item. + /// public HtmlTextInfo GetHtmlText(int ModuleID, int ItemID) { return CBO.FillObject(DataProvider.Instance().GetHtmlText(ModuleID, ItemID)); @@ -351,13 +433,14 @@ public HtmlTextInfo GetHtmlText(int ModuleID, int ItemID) /// ----------------------------------------------------------------------------- /// - /// GetTopHtmlText gets the most recent HtmlTextInfo object for the Module, Workflow, and State + /// GetTopHtmlText gets the most recent HtmlTextInfo object for the Module, Workflow, and State. /// /// /// - /// The ID of the Module - /// Whether the content has been published or not - /// The Workflow ID + /// The ID of the Module. + /// Whether the content has been published or not. + /// The Workflow ID. + /// public HtmlTextInfo GetTopHtmlText(int moduleId, bool isPublished, int workflowId) { var htmlText = CBO.FillObject(DataProvider.Instance().GetTopHtmlText(moduleId, isPublished)); @@ -374,25 +457,28 @@ public HtmlTextInfo GetTopHtmlText(int moduleId, bool isPublished, int workflowI htmlText.StateID = htmlText.IsPublished ? workflowStateController.GetLastWorkflowStateID(workflowId) : workflowStateController.GetFirstWorkflowStateID(workflowId); + // update object - UpdateHtmlText(htmlText, GetMaximumVersionHistory(htmlText.PortalID)); + this.UpdateHtmlText(htmlText, this.GetMaximumVersionHistory(htmlText.PortalID)); // get object again htmlText = CBO.FillObject(DataProvider.Instance().GetTopHtmlText(moduleId, false)); } } + return htmlText; } /// ----------------------------------------------------------------------------- /// - /// GetWorkFlow retrieves the currently active Workflow for the Portal + /// GetWorkFlow retrieves the currently active Workflow for the Portal. /// /// /// - /// The ID of the Module - /// The Tab ID - /// The ID of the Portal + /// The ID of the Module. + /// The Tab ID. + /// The ID of the Portal. + /// public KeyValuePair GetWorkflow(int ModuleId, int TabId, int PortalId) { int workFlowId = Null.NullInteger; @@ -416,6 +502,7 @@ public KeyValuePair GetWorkflow(int ModuleId, int TabId, int Portal workFlowId = settings.WorkFlowID; workFlowType = "Module"; } + if (workFlowId == Null.NullInteger) { // if undefined at module level, get from tab settings @@ -453,88 +540,14 @@ public KeyValuePair GetWorkflow(int ModuleId, int TabId, int Portal return new KeyValuePair(workFlowType, workFlowId); } - public static string ManageRelativePaths(string strHTML, string strUploadDirectory, string strToken, int intPortalID) - { - int P = 0; - int R = 0; - int S = 0; - int tLen = 0; - string strURL = null; - var sbBuff = new StringBuilder(""); - - if (!string.IsNullOrEmpty(strHTML)) - { - tLen = strToken.Length + 2; - string uploadDirectory = strUploadDirectory.ToLowerInvariant(); - - //find position of first occurrance: - P = strHTML.IndexOf(strToken + "=\"", StringComparison.InvariantCultureIgnoreCase); - while (P != -1) - { - sbBuff.Append(strHTML.Substring(S, P - S + tLen)); - //keep charactes left of URL - S = P + tLen; - //save startpos of URL - R = strHTML.IndexOf("\"", S); - //end of URL - if (R >= 0) - { - strURL = strHTML.Substring(S, R - S).ToLowerInvariant(); - } - else - { - strURL = strHTML.Substring(S).ToLowerInvariant(); - } - - if (strHTML.Substring(P + tLen, 10).Equals("data:image", StringComparison.InvariantCultureIgnoreCase)) - { - P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); - continue; - } - - // if we are linking internally - if (!strURL.Contains("://")) - { - // remove the leading portion of the path if the URL contains the upload directory structure - string strDirectory = uploadDirectory; - if (!strDirectory.EndsWith("/")) - { - strDirectory += "/"; - } - if (strURL.IndexOf(strDirectory) != -1) - { - S = S + strURL.IndexOf(strDirectory) + strDirectory.Length; - strURL = strURL.Substring(strURL.IndexOf(strDirectory) + strDirectory.Length); - } - // add upload directory - if (!strURL.StartsWith("/") - && !String.IsNullOrEmpty(strURL.Trim())) //We don't write the UploadDirectory if the token/attribute has not value. Therefore we will avoid an unnecessary request - { - sbBuff.Append(uploadDirectory); - } - } - //find position of next occurrance - P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); - } - - if (S > -1) - { - sbBuff.Append(strHTML.Substring(S)); - } - //append characters of last URL and behind - } - - return sbBuff.ToString(); - } - /// ----------------------------------------------------------------------------- /// - /// UpdateHtmlText creates a new HtmlTextInfo object or updates an existing HtmlTextInfo object + /// UpdateHtmlText creates a new HtmlTextInfo object or updates an existing HtmlTextInfo object. /// /// /// - /// An HtmlTextInfo object - /// The maximum number of versions to retain + /// An HtmlTextInfo object. + /// The maximum number of versions to retain. public void UpdateHtmlText(HtmlTextInfo htmlContent, int MaximumVersionHistory) { var _workflowStateController = new WorkflowStateController(); @@ -545,7 +558,7 @@ public void UpdateHtmlText(HtmlTextInfo htmlContent, int MaximumVersionHistory) { if (htmlContent.WorkflowName != "[REPAIR_WORKFLOW]") { - HtmlTextInfo objContent = GetTopHtmlText(htmlContent.ModuleID, false, htmlContent.WorkflowID); + HtmlTextInfo objContent = this.GetTopHtmlText(htmlContent.ModuleID, false, htmlContent.WorkflowID); if (objContent != null) { if (objContent.StateID == _workflowStateController.GetLastWorkflowStateID(htmlContent.WorkflowID)) @@ -573,18 +586,19 @@ public void UpdateHtmlText(HtmlTextInfo htmlContent, int MaximumVersionHistory) if (blnCreateNewVersion) { // add content - htmlContent.ItemID = DataProvider.Instance().AddHtmlText(htmlContent.ModuleID, - htmlContent.Content, - htmlContent.Summary, - htmlContent.StateID, - htmlContent.IsPublished, - UserController.Instance.GetCurrentUserInfo().UserID, - MaximumVersionHistory); + htmlContent.ItemID = DataProvider.Instance().AddHtmlText( + htmlContent.ModuleID, + htmlContent.Content, + htmlContent.Summary, + htmlContent.StateID, + htmlContent.IsPublished, + UserController.Instance.GetCurrentUserInfo().UserID, + MaximumVersionHistory); } else { // update content - DataProvider.Instance().UpdateHtmlText(htmlContent.ItemID, htmlContent.Content, htmlContent.Summary, htmlContent.StateID, htmlContent.IsPublished, UserController.Instance.GetCurrentUserInfo().UserID); + DataProvider.Instance().UpdateHtmlText(htmlContent.ItemID, htmlContent.Content, htmlContent.Summary, htmlContent.StateID, htmlContent.IsPublished, UserController.Instance.GetCurrentUserInfo().UserID); } // add log history @@ -597,7 +611,7 @@ public void UpdateHtmlText(HtmlTextInfo htmlContent, int MaximumVersionHistory) objLogs.AddHtmlTextLog(logInfo); // create user notifications - CreateUserNotifications(htmlContent); + this.CreateUserNotifications(htmlContent); // refresh output cache ModuleController.SynchronizeModule(htmlContent.ModuleID); @@ -605,14 +619,14 @@ public void UpdateHtmlText(HtmlTextInfo htmlContent, int MaximumVersionHistory) /// ----------------------------------------------------------------------------- /// - /// UpdateWorkFlow updates the currently active Workflow + /// UpdateWorkFlow updates the currently active Workflow. /// /// /// - /// The type of workflow (Module | Page | Site) - /// The ID of the Workflow - /// The ID of the object to apply the update to (depends on WorkFlowType) - /// Should existing settings be overwritten? + /// The type of workflow (Module | Page | Site). + /// The ID of the Workflow. + /// The ID of the object to apply the update to (depends on WorkFlowType). + /// Should existing settings be overwritten?. public void UpdateWorkflow(int ObjectID, string WorkFlowType, int WorkflowID, bool ReplaceExistingSettings) { switch (WorkFlowType) @@ -624,39 +638,43 @@ public void UpdateWorkflow(int ObjectID, string WorkFlowType, int WorkflowID, bo TabController.Instance.UpdateTabSetting(ObjectID, "WorkflowID", WorkflowID.ToString()); if (ReplaceExistingSettings) { - //Get All Modules on the current Tab + // Get All Modules on the current Tab foreach (var kvp in ModuleController.Instance.GetTabModules(ObjectID)) { - ClearModuleSettings(kvp.Value); + this.ClearModuleSettings(kvp.Value); } } + break; case "Site": PortalController.UpdatePortalSetting(ObjectID, "WorkflowID", WorkflowID.ToString()); if (ReplaceExistingSettings) { - //Get All Tabs aon the Site + // Get All Tabs aon the Site foreach (var kvp in TabController.Instance.GetTabsByPortal(ObjectID)) { TabController.Instance.DeleteTabSetting(kvp.Value.TabID, "WorkFlowID"); } - //Get All Modules in the current Site + + // Get All Modules in the current Site foreach (ModuleInfo objModule in ModuleController.Instance.GetModules(ObjectID)) { - ClearModuleSettings(objModule); + this.ClearModuleSettings(objModule); } } + break; } } /// ----------------------------------------------------------------------------- /// - /// GetMaximumVersionHistory retrieves the maximum number of versions to store for a module + /// GetMaximumVersionHistory retrieves the maximum number of versions to store for a module. /// /// /// - /// The ID of the Portal + /// The ID of the Portal. + /// public int GetMaximumVersionHistory(int PortalID) { int intMaximumVersionHistory = -1; @@ -668,6 +686,7 @@ public int GetMaximumVersionHistory(int PortalID) if (intMaximumVersionHistory == -1) { intMaximumVersionHistory = 5; + // default PortalController.UpdatePortalSetting(PortalID, "MaximumVersionHistory", intMaximumVersionHistory.ToString()); } @@ -677,18 +696,19 @@ public int GetMaximumVersionHistory(int PortalID) /// ----------------------------------------------------------------------------- /// - /// UpdateWorkFlowID updates the currently active WorkflowID for the Portal + /// UpdateWorkFlowID updates the currently active WorkflowID for the Portal. /// /// /// - /// The ID of the Portal - /// The MaximumVersionHistory + /// The ID of the Portal. + /// The MaximumVersionHistory. public void UpdateMaximumVersionHistory(int PortalID, int MaximumVersionHistory) { // data integrity check if (MaximumVersionHistory < 0) { MaximumVersionHistory = 5; + // default } @@ -700,31 +720,26 @@ public void UpdateMaximumVersionHistory(int PortalID, int MaximumVersionHistory) } } - #endregion - - #region Optional Interfaces - - #region IPortable Members - - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// - /// ExportModule implements the IPortable ExportModule Interface + /// ExportModule implements the IPortable ExportModule Interface. /// /// /// - /// The Id of the module to be exported + /// The Id of the module to be exported. + /// public string ExportModule(int moduleId) { - string xml = ""; + string xml = string.Empty; ModuleInfo module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - int workflowID = GetWorkflow(moduleId, module.TabID, module.PortalID).Value; + int workflowID = this.GetWorkflow(moduleId, module.TabID, module.PortalID).Value; - HtmlTextInfo content = GetTopHtmlText(moduleId, true, workflowID); - if ((content != null)) + HtmlTextInfo content = this.GetTopHtmlText(moduleId, true, workflowID); + if (content != null) { xml += ""; - xml += "" + XmlUtils.XMLEncode(TokeniseLinks(content.Content, module.PortalID)) + ""; + xml += "" + XmlUtils.XMLEncode(this.TokeniseLinks(content.Content, module.PortalID)) + ""; xml += ""; } @@ -733,50 +748,49 @@ public string ExportModule(int moduleId) /// ----------------------------------------------------------------------------- /// - /// ImportModule implements the IPortable ImportModule Interface + /// ImportModule implements the IPortable ImportModule Interface. /// /// /// - /// The ID of the Module being imported - /// The Content being imported - /// The Version of the Module Content being imported - /// The UserID of the User importing the Content + /// The ID of the Module being imported. + /// The Content being imported. + /// The Version of the Module Content being imported. + /// The UserID of the User importing the Content. public void ImportModule(int ModuleID, string Content, string Version, int UserId) { ModuleInfo module = ModuleController.Instance.GetModule(ModuleID, Null.NullInteger, true); var workflowStateController = new WorkflowStateController(); - int workflowID = GetWorkflow(ModuleID, module.TabID, module.PortalID).Value; + int workflowID = this.GetWorkflow(ModuleID, module.TabID, module.PortalID).Value; XmlNode xml = Globals.GetContent(Content, "htmltext"); var htmlContent = new HtmlTextInfo(); htmlContent.ModuleID = ModuleID; + // convert Version to System.Version var objVersion = new Version(Version); if (objVersion >= new Version(5, 1, 0)) { // current module content - htmlContent.Content = DeTokeniseLinks(xml.SelectSingleNode("content").InnerText, module.PortalID); + htmlContent.Content = this.DeTokeniseLinks(xml.SelectSingleNode("content").InnerText, module.PortalID); } else { // legacy module content - htmlContent.Content = DeTokeniseLinks(xml.SelectSingleNode("desktophtml").InnerText, module.PortalID); + htmlContent.Content = this.DeTokeniseLinks(xml.SelectSingleNode("desktophtml").InnerText, module.PortalID); } + htmlContent.WorkflowID = workflowID; htmlContent.StateID = workflowStateController.GetFirstWorkflowStateID(workflowID); + // import - UpdateHtmlText(htmlContent, GetMaximumVersionHistory(module.PortalID)); + this.UpdateHtmlText(htmlContent, this.GetMaximumVersionHistory(module.PortalID)); } - #endregion - - #region ModuleSearchBase - public override IList GetModifiedSearchDocuments(ModuleInfo modInfo, DateTime beginDateUtc) { - var workflowId = GetWorkflow(modInfo.ModuleID, modInfo.TabID, modInfo.PortalID).Value; + var workflowId = this.GetWorkflow(modInfo.ModuleID, modInfo.TabID, modInfo.PortalID).Value; var searchDocuments = new List(); - var htmlTextInfo = GetTopHtmlText(modInfo.ModuleID, true, workflowId); + var htmlTextInfo = this.GetTopHtmlText(modInfo.ModuleID, true, workflowId); var repo = new HtmlModuleSettingsRepository(); var settings = repo.GetSettings(modInfo); @@ -796,7 +810,7 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modI Title = modInfo.ModuleTitle, Description = description, Body = strContent, - ModifiedTimeUtc = htmlTextInfo.LastModifiedOnDate.ToUniversalTime() + ModifiedTimeUtc = htmlTextInfo.LastModifiedOnDate.ToUniversalTime(), }; if (modInfo.Terms != null && modInfo.Terms.Count > 0) @@ -810,38 +824,15 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modI return searchDocuments; } - private static List CollectHierarchicalTags(List terms) - { - Func, List, List> collectTagsFunc = null; - collectTagsFunc = (ts, tags) => - { - if (ts != null && ts.Count > 0) - { - foreach (var t in ts) - { - tags.Add(t.Name); - tags.AddRange(collectTagsFunc(t.ChildTerms, new List())); - } - } - return tags; - }; - - return collectTagsFunc(terms, new List()); - } - - #endregion - - #region IUpgradeable Members - public string UpgradeModule(string Version) { switch (Version) { case "05.01.02": - //remove the Code SubDirectory + // remove the Code SubDirectory Config.RemoveCodeSubDirectory("HTML"); - //Once the web.config entry is done we can safely remove the HTML folder + // Once the web.config entry is done we can safely remove the HTML folder var arrPaths = new string[1]; arrPaths[0] = "App_Code\\HTML\\"; FileSystemUtils.DeleteFiles(arrPaths); @@ -853,11 +844,31 @@ public string UpgradeModule(string Version) break; case "06.02.00": - AddNotificationTypes(); + this.AddNotificationTypes(); break; } - return string.Empty; + return string.Empty; + } + + private static List CollectHierarchicalTags(List terms) + { + Func, List, List> collectTagsFunc = null; + collectTagsFunc = (ts, tags) => + { + if (ts != null && ts.Count > 0) + { + foreach (var t in ts) + { + tags.Add(t.Name); + tags.AddRange(collectTagsFunc(t.ChildTerms, new List())); + } + } + + return tags; + }; + + return collectTagsFunc(terms, new List()); } private void AddNotificationTypes() @@ -868,9 +879,5 @@ private void AddNotificationTypes() NotificationsController.Instance.CreateNotificationType(type); } } - - #endregion - - #endregion } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs b/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs index 48a6006af79..779b6ad8afe 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html { + using System; + + using DotNetNuke.Entities; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: HtmlTextInfo /// ----------------------------------------------------------------------------- /// - /// Defines an instance of an HtmlText object + /// Defines an instance of an HtmlText object. /// /// /// @@ -22,7 +23,7 @@ public class HtmlTextInfo : BaseEntityInfo { // local property declarations private bool _Approved = true; - private string _Comment = ""; + private string _Comment = string.Empty; private bool _IsActive = true; private int _ItemID = -1; @@ -33,11 +34,12 @@ public int ItemID { get { - return _ItemID; + return this._ItemID; } + set { - _ItemID = value; + this._ItemID = value; } } @@ -65,11 +67,12 @@ public bool IsActive { get { - return _IsActive; + return this._IsActive; } + set { - _IsActive = value; + this._IsActive = value; } } @@ -77,11 +80,12 @@ public string Comment { get { - return _Comment; + return this._Comment; } + set { - _Comment = value; + this._Comment = value; } } @@ -89,16 +93,17 @@ public bool Approved { get { - return _Approved; + return this._Approved; } + set { - _Approved = value; + this._Approved = value; } } public string DisplayName { get; set; } - public string Summary { get; set; } + public string Summary { get; set; } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs index 8b54dc7a4a1..6bade8b65f0 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs @@ -1,57 +1,53 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Modules.Html.Components; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html { + using System.Collections; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.Html.Components; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: HtmlTextLogController /// ----------------------------------------------------------------------------- /// - /// The HtmlTextLogController is the Controller class for managing Log History information the HtmlText module + /// The HtmlTextLogController is the Controller class for managing Log History information the HtmlText module. /// /// /// /// ----------------------------------------------------------------------------- public class HtmlTextLogController - { - #region Public Methods - + { /// ----------------------------------------------------------------------------- /// - /// GetHtmlTextLog retrieves a collection of HtmlTextLogInfo objects for an Item + /// GetHtmlTextLog retrieves a collection of HtmlTextLogInfo objects for an Item. /// /// /// - /// The Id of the Item + /// The Id of the Item. + /// /// ----------------------------------------------------------------------------- public ArrayList GetHtmlTextLog(int ItemID) { - return CBO.FillCollection(DataProvider.Instance().GetHtmlTextLog(ItemID), typeof (HtmlTextLogInfo)); + return CBO.FillCollection(DataProvider.Instance().GetHtmlTextLog(ItemID), typeof(HtmlTextLogInfo)); } /// ----------------------------------------------------------------------------- /// - /// AddHtmlTextLog creates a new HtmlTextLog for an Item + /// AddHtmlTextLog creates a new HtmlTextLog for an Item. /// /// /// - /// An HtmlTextLogInfo object + /// An HtmlTextLogInfo object. /// ----------------------------------------------------------------------------- public void AddHtmlTextLog(HtmlTextLogInfo objHtmlTextLog) { DataProvider.Instance().AddHtmlTextLog(objHtmlTextLog.ItemID, objHtmlTextLog.StateID, objHtmlTextLog.Comment, objHtmlTextLog.Approved, UserController.Instance.GetCurrentUserInfo().UserID); - } - - #endregion + } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextLogInfo.cs b/DNN Platform/Modules/HTML/Components/HtmlTextLogInfo.cs index d883e792fc3..85abaf157eb 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextLogInfo.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextLogInfo.cs @@ -1,19 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html { + using System; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: HtmlTextLogInfo /// ----------------------------------------------------------------------------- /// - /// Defines an instance of an HtmlTextLog object + /// Defines an instance of an HtmlTextLog object. /// /// /// diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs index f6f5072ec99..90fee4842da 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs @@ -1,50 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Modules.Html.Components; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html { + using System.Collections; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Modules.Html.Components; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: HtmlTextUserController /// ----------------------------------------------------------------------------- /// - /// The HtmlTextUserController is the Controller class for managing User information the HtmlText module + /// The HtmlTextUserController is the Controller class for managing User information the HtmlText module. /// /// /// /// ----------------------------------------------------------------------------- public class HtmlTextUserController - { - #region Public Methods - + { /// ----------------------------------------------------------------------------- /// - /// GetHtmlTextUser retrieves a collection of HtmlTextUserInfo objects for an Item + /// GetHtmlTextUser retrieves a collection of HtmlTextUserInfo objects for an Item. /// /// /// - /// The Id of the User + /// The Id of the User. + /// /// ----------------------------------------------------------------------------- public ArrayList GetHtmlTextUser(int UserID) { - return CBO.FillCollection(DataProvider.Instance().GetHtmlTextUser(UserID), typeof (HtmlTextUserInfo)); + return CBO.FillCollection(DataProvider.Instance().GetHtmlTextUser(UserID), typeof(HtmlTextUserInfo)); } /// ----------------------------------------------------------------------------- /// - /// AddHtmlTextUser creates a new HtmlTextUser for an Item + /// AddHtmlTextUser creates a new HtmlTextUser for an Item. /// /// /// - /// An HtmlTextUserInfo object + /// An HtmlTextUserInfo object. /// ----------------------------------------------------------------------------- public void AddHtmlTextUser(HtmlTextUserInfo objHtmlTextUser) { @@ -53,7 +51,7 @@ public void AddHtmlTextUser(HtmlTextUserInfo objHtmlTextUser) /// ----------------------------------------------------------------------------- /// - /// DeleteHtmlTextUsers cleans up old HtmlTextUser records + /// DeleteHtmlTextUsers cleans up old HtmlTextUser records. /// /// /// @@ -61,8 +59,6 @@ public void AddHtmlTextUser(HtmlTextUserInfo objHtmlTextUser) public void DeleteHtmlTextUsers() { DataProvider.Instance().DeleteHtmlTextUsers(); - } - - #endregion + } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs b/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs index cdb82d9fee1..688e6fbbc69 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs @@ -1,35 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: HtmlTextUserInfo /// ----------------------------------------------------------------------------- /// - /// Defines an instance of an HtmlTextUser object + /// Defines an instance of an HtmlTextUser object. /// /// /// /// ----------------------------------------------------------------------------- public class HtmlTextUserInfo - { - #region Private Member - // local property declarations - private ModuleInfo _Module; - - #endregion - - #region Public Properties + { + // local property declarations + private ModuleInfo _Module; + public int ItemID { get; set; } public int StateID { get; set; } @@ -43,10 +38,11 @@ public string ModuleTitle get { string _ModuleTitle = Null.NullString; - if (Module != null) + if (this.Module != null) { - _ModuleTitle = Module.ModuleTitle; + _ModuleTitle = this.Module.ModuleTitle; } + return _ModuleTitle; } } @@ -55,20 +51,19 @@ public ModuleInfo Module { get { - if (_Module == null) + if (this._Module == null) { - _Module = ModuleController.Instance.GetModule(ModuleID, TabID, false); + this._Module = ModuleController.Instance.GetModule(this.ModuleID, this.TabID, false); } - return _Module; + + return this._Module; } } - - + public int TabID { get; set; } public int UserID { get; set; } - public DateTime CreatedOnDate { get; set; } - #endregion + public DateTime CreatedOnDate { get; set; } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs b/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs index 89ed8f3c417..b662047dabc 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs @@ -1,23 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Web.Caching; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Modules.Html.Components; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html { + using System.Collections; + using System.Web.Caching; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Modules.Html.Components; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: WorkflowStateController /// ----------------------------------------------------------------------------- /// - /// The WorkflowStateController is the Controller class for managing workflows and states for the HtmlText module + /// The WorkflowStateController is the Controller class for managing workflows and states for the HtmlText module. /// /// /// @@ -27,89 +26,93 @@ public class WorkflowStateController private const string WORKFLOW_CACHE_KEY = "Workflow{0}"; private const int WORKFLOW_CACHE_TIMEOUT = 20; - private const CacheItemPriority WORKFLOW_CACHE_PRIORITY = CacheItemPriority.Normal; - - #region Public Methods - + private const CacheItemPriority WORKFLOW_CACHE_PRIORITY = CacheItemPriority.Normal; + /// ----------------------------------------------------------------------------- /// - /// GetWorkFlows retrieves a collection of workflows for the portal + /// GetWorkFlows retrieves a collection of workflows for the portal. /// /// /// - /// The ID of the Portal + /// The ID of the Portal. + /// /// ----------------------------------------------------------------------------- public ArrayList GetWorkflows(int PortalID) { - return CBO.FillCollection(DataProvider.Instance().GetWorkflows(PortalID), typeof (WorkflowStateInfo)); + return CBO.FillCollection(DataProvider.Instance().GetWorkflows(PortalID), typeof(WorkflowStateInfo)); } /// ----------------------------------------------------------------------------- /// - /// GetWorkFlowStates retrieves a collection of WorkflowStateInfo objects for the Workflow from the cache + /// GetWorkFlowStates retrieves a collection of WorkflowStateInfo objects for the Workflow from the cache. /// /// /// - /// The ID of the Workflow + /// The ID of the Workflow. + /// /// ----------------------------------------------------------------------------- public ArrayList GetWorkflowStates(int WorkflowID) { string cacheKey = string.Format(WORKFLOW_CACHE_KEY, WorkflowID); - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, WORKFLOW_CACHE_TIMEOUT, WORKFLOW_CACHE_PRIORITY, WorkflowID), GetWorkflowStatesCallBack); + return CBO.GetCachedObject(new CacheItemArgs(cacheKey, WORKFLOW_CACHE_TIMEOUT, WORKFLOW_CACHE_PRIORITY, WorkflowID), this.GetWorkflowStatesCallBack); } /// ----------------------------------------------------------------------------- /// - /// GetWorkFlowStatesCallback retrieves a collection of WorkflowStateInfo objects for the Workflow from the database + /// GetWorkFlowStatesCallback retrieves a collection of WorkflowStateInfo objects for the Workflow from the database. /// /// /// - /// Arguments passed by the GetWorkflowStates method + /// Arguments passed by the GetWorkflowStates method. + /// /// ----------------------------------------------------------------------------- public object GetWorkflowStatesCallBack(CacheItemArgs cacheItemArgs) { - var WorkflowID = (int) (cacheItemArgs.ParamList[0]); - return CBO.FillCollection(DataProvider.Instance().GetWorkflowStates(WorkflowID), typeof (WorkflowStateInfo)); + var WorkflowID = (int)cacheItemArgs.ParamList[0]; + return CBO.FillCollection(DataProvider.Instance().GetWorkflowStates(WorkflowID), typeof(WorkflowStateInfo)); } /// ----------------------------------------------------------------------------- /// - /// GetFirstWorkFlowStateID retrieves the first StateID for the Workflow + /// GetFirstWorkFlowStateID retrieves the first StateID for the Workflow. /// /// /// - /// The ID of the Workflow + /// The ID of the Workflow. + /// /// ----------------------------------------------------------------------------- public int GetFirstWorkflowStateID(int WorkflowID) { int intStateID = -1; - ArrayList arrWorkflowStates = GetWorkflowStates(WorkflowID); + ArrayList arrWorkflowStates = this.GetWorkflowStates(WorkflowID); if (arrWorkflowStates.Count > 0) { - intStateID = ((WorkflowStateInfo) (arrWorkflowStates[0])).StateID; + intStateID = ((WorkflowStateInfo)arrWorkflowStates[0]).StateID; } + return intStateID; } /// ----------------------------------------------------------------------------- /// - /// GetPreviousWorkFlowStateID retrieves the previous StateID for the Workflow and State specified + /// GetPreviousWorkFlowStateID retrieves the previous StateID for the Workflow and State specified. /// /// /// - /// The ID of the Workflow - /// The ID of the State + /// The ID of the Workflow. + /// The ID of the State. + /// /// ----------------------------------------------------------------------------- public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) { int intPreviousStateID = -1; - ArrayList arrWorkflowStates = GetWorkflowStates(WorkflowID); + ArrayList arrWorkflowStates = this.GetWorkflowStates(WorkflowID); int intItem = 0; // locate the current state for (intItem = 0; intItem < arrWorkflowStates.Count; intItem++) { - if (((WorkflowStateInfo) (arrWorkflowStates[intItem])).StateID == StateID) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID == StateID) { intPreviousStateID = StateID; break; @@ -122,11 +125,12 @@ public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) intItem = intItem - 1; while (intItem >= 0) { - if (((WorkflowStateInfo) (arrWorkflowStates[intItem])).IsActive) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).IsActive) { - intPreviousStateID = ((WorkflowStateInfo) (arrWorkflowStates[intItem])).StateID; + intPreviousStateID = ((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID; break; } + intItem = intItem - 1; } } @@ -134,7 +138,7 @@ public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) // if none found then reset to first state if (intPreviousStateID == -1) { - intPreviousStateID = GetFirstWorkflowStateID(WorkflowID); + intPreviousStateID = this.GetFirstWorkflowStateID(WorkflowID); } return intPreviousStateID; @@ -142,23 +146,24 @@ public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) /// ----------------------------------------------------------------------------- /// - /// GetNextWorkFlowStateID retrieves the next StateID for the Workflow and State specified + /// GetNextWorkFlowStateID retrieves the next StateID for the Workflow and State specified. /// /// /// - /// The ID of the Workflow - /// The ID of the State + /// The ID of the Workflow. + /// The ID of the State. + /// /// ----------------------------------------------------------------------------- public int GetNextWorkflowStateID(int WorkflowID, int StateID) { int intNextStateID = -1; - ArrayList arrWorkflowStates = GetWorkflowStates(WorkflowID); + ArrayList arrWorkflowStates = this.GetWorkflowStates(WorkflowID); int intItem = 0; // locate the current state for (intItem = 0; intItem < arrWorkflowStates.Count; intItem++) { - if (((WorkflowStateInfo) (arrWorkflowStates[intItem])).StateID == StateID) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID == StateID) { intNextStateID = StateID; break; @@ -171,11 +176,12 @@ public int GetNextWorkflowStateID(int WorkflowID, int StateID) intItem = intItem + 1; while (intItem < arrWorkflowStates.Count) { - if (((WorkflowStateInfo) (arrWorkflowStates[intItem])).IsActive) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).IsActive) { - intNextStateID = ((WorkflowStateInfo) (arrWorkflowStates[intItem])).StateID; + intNextStateID = ((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID; break; } + intItem = intItem + 1; } } @@ -183,7 +189,7 @@ public int GetNextWorkflowStateID(int WorkflowID, int StateID) // if none found then reset to first state if (intNextStateID == -1) { - intNextStateID = GetFirstWorkflowStateID(WorkflowID); + intNextStateID = this.GetFirstWorkflowStateID(WorkflowID); } return intNextStateID; @@ -191,23 +197,23 @@ public int GetNextWorkflowStateID(int WorkflowID, int StateID) /// ----------------------------------------------------------------------------- /// - /// GetLastWorkFlowStateID retrieves the last StateID for the Workflow + /// GetLastWorkFlowStateID retrieves the last StateID for the Workflow. /// /// /// - /// The ID of the Workflow + /// The ID of the Workflow. + /// /// ----------------------------------------------------------------------------- public int GetLastWorkflowStateID(int WorkflowID) { int intStateID = -1; - ArrayList arrWorkflowStates = GetWorkflowStates(WorkflowID); + ArrayList arrWorkflowStates = this.GetWorkflowStates(WorkflowID); if (arrWorkflowStates.Count > 0) { - intStateID = ((WorkflowStateInfo) (arrWorkflowStates[arrWorkflowStates.Count - 1])).StateID; + intStateID = ((WorkflowStateInfo)arrWorkflowStates[arrWorkflowStates.Count - 1]).StateID; } + return intStateID; - } - - #endregion + } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs b/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs index 8b1b572e26b..cb42d8b5e2c 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Html { + using System; + /// ----------------------------------------------------------------------------- /// Namespace: DotNetNuke.Modules.Html /// Project: DotNetNuke /// Class: WorkflowStateInfo /// ----------------------------------------------------------------------------- /// - /// Defines an instance of a WorkflowState object + /// Defines an instance of a WorkflowState object. /// /// /// @@ -21,7 +21,6 @@ namespace DotNetNuke.Modules.Html public class WorkflowStateInfo { // local property declarations - private bool _IsActive = true; // public properties @@ -47,11 +46,12 @@ public bool IsActive { get { - return _IsActive; + return this._IsActive; } + set { - _IsActive = value; + this._IsActive = value; } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs index 9bc9c24cc78..dba64ca00ee 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs @@ -1,42 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : WorkflowStatePermissionCollection + /// Class : WorkflowStatePermissionCollection /// ----------------------------------------------------------------------------- /// /// DesktopModulePermissionCollection provides the a custom collection for WorkflowStatePermissionInfo - /// objects + /// objects. /// /// ----------------------------------------------------------------------------- [Serializable] public class WorkflowStatePermissionCollection : CollectionBase - { - #region Constructors - + { public WorkflowStatePermissionCollection() { } public WorkflowStatePermissionCollection(ArrayList WorkflowStatePermissions) { - AddRange(WorkflowStatePermissions); + this.AddRange(WorkflowStatePermissions); } public WorkflowStatePermissionCollection(WorkflowStatePermissionCollection WorkflowStatePermissions) { - AddRange(WorkflowStatePermissions); + this.AddRange(WorkflowStatePermissions); } public WorkflowStatePermissionCollection(ArrayList WorkflowStatePermissions, int WorkflowStatePermissionID) @@ -45,34 +43,27 @@ public WorkflowStatePermissionCollection(ArrayList WorkflowStatePermissions, int { if (permission.WorkflowStatePermissionID == WorkflowStatePermissionID) { - Add(permission); + this.Add(permission); } } - } - - #endregion - - #region Public Properties - + } + public WorkflowStatePermissionInfo this[int index] { get { - return (WorkflowStatePermissionInfo) (List[index]); + return (WorkflowStatePermissionInfo)this.List[index]; } + set { - List[index] = value; + this.List[index] = value; } - } - - #endregion - - #region Public Methods - + } + public int Add(WorkflowStatePermissionInfo value) { - return List.Add(value); + return this.List.Add(value); } public int Add(WorkflowStatePermissionInfo value, bool checkForDuplicates) @@ -80,12 +71,12 @@ public int Add(WorkflowStatePermissionInfo value, bool checkForDuplicates) int id = Null.NullInteger; if (!checkForDuplicates) { - id = Add(value); + id = this.Add(value); } else { bool isMatch = false; - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) { @@ -93,11 +84,13 @@ public int Add(WorkflowStatePermissionInfo value, bool checkForDuplicates) break; } } + if (!isMatch) { - id = Add(value); + id = this.Add(value); } } + return id; } @@ -105,7 +98,7 @@ public void AddRange(ArrayList WorkflowStatePermissions) { foreach (WorkflowStatePermissionInfo permission in WorkflowStatePermissions) { - Add(permission); + this.Add(permission); } } @@ -113,20 +106,21 @@ public void AddRange(WorkflowStatePermissionCollection WorkflowStatePermissions) { foreach (WorkflowStatePermissionInfo permission in WorkflowStatePermissions) { - Add(permission); + this.Add(permission); } } public bool CompareTo(WorkflowStatePermissionCollection objWorkflowStatePermissionCollection) { - if (objWorkflowStatePermissionCollection.Count != Count) + if (objWorkflowStatePermissionCollection.Count != this.Count) { return false; } - InnerList.Sort(new CompareWorkflowStatePermissions()); + + this.InnerList.Sort(new CompareWorkflowStatePermissions()); objWorkflowStatePermissionCollection.InnerList.Sort(new CompareWorkflowStatePermissions()); - for (int i = 0; i < Count; i++) + for (int i = 0; i < this.Count; i++) { if (objWorkflowStatePermissionCollection[i].WorkflowStatePermissionID != this[i].WorkflowStatePermissionID || objWorkflowStatePermissionCollection[i].AllowAccess != this[i].AllowAccess) { @@ -139,31 +133,31 @@ public bool CompareTo(WorkflowStatePermissionCollection objWorkflowStatePermissi public bool Contains(WorkflowStatePermissionInfo value) { - return List.Contains(value); + return this.List.Contains(value); } public int IndexOf(WorkflowStatePermissionInfo value) { - return List.IndexOf(value); + return this.List.IndexOf(value); } public void Insert(int index, WorkflowStatePermissionInfo value) { - List.Insert(index, value); + this.List.Insert(index, value); } public void Remove(WorkflowStatePermissionInfo value) { - List.Remove(value); + this.List.Remove(value); } public void Remove(int permissionID, int roleID, int userID) { - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { if (permission.PermissionID == permissionID && permission.UserID == userID && permission.RoleID == roleID) { - List.Remove(permission); + this.List.Remove(permission); break; } } @@ -173,18 +167,17 @@ public List ToList() { var list = new List(); - foreach (PermissionInfoBase permission in List) + foreach (PermissionInfoBase permission in this.List) { list.Add(permission); } + return list; } public string ToString(string key) { - return PermissionController.BuildPermissions(List, key); - } - - #endregion + return PermissionController.BuildPermissions(this.List, key); + } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs index 2085eef49fb..46f213952f9 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs @@ -1,28 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Web.Caching; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Modules.Html; -using DotNetNuke.Modules.Html.Components; -using DotNetNuke.Services.Exceptions; - - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Permissions { + using System; + using System.Collections.Generic; + using System.Data; + using System.Web.Caching; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Modules.Html; + using DotNetNuke.Modules.Html.Components; + using DotNetNuke.Services.Exceptions; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : WorkflowStatePermissionController + /// Class : WorkflowStatePermissionController /// ----------------------------------------------------------------------------- /// - /// WorkflowStatePermissionController provides the Business Layer for DesktopModule Permissions + /// WorkflowStatePermissionController provides the Business Layer for DesktopModule Permissions. /// /// ----------------------------------------------------------------------------- public class WorkflowStatePermissionController @@ -31,28 +29,69 @@ public class WorkflowStatePermissionController public const CacheItemPriority WorkflowStatePermissionCachePriority = CacheItemPriority.Normal; public const int WorkflowStatePermissionCacheTimeOut = 20; - private static readonly DataProvider provider = DataProvider.Instance(); + private static readonly DataProvider provider = DataProvider.Instance(); + + /// ----------------------------------------------------------------------------- + /// + /// GetWorkflowStatePermissions gets a WorkflowStatePermissionCollection. + /// + /// The ID of the State. + /// + /// ----------------------------------------------------------------------------- + public static WorkflowStatePermissionCollection GetWorkflowStatePermissions(int StateID) + { + bool bFound = false; + + // Get the WorkflowStatePermission Dictionary + Dictionary dicWorkflowStatePermissions = GetWorkflowStatePermissions(); - #region Private Shared Methods + // Get the Collection from the Dictionary + WorkflowStatePermissionCollection WorkflowStatePermissions = null; + bFound = dicWorkflowStatePermissions.TryGetValue(StateID, out WorkflowStatePermissions); + if (!bFound) + { + // try the database + WorkflowStatePermissions = new WorkflowStatePermissionCollection( + CBO.FillCollection(provider.GetWorkflowStatePermissionsByStateID(StateID), typeof(WorkflowStatePermissionInfo)), + StateID); + } + + return WorkflowStatePermissions; + } + /// ----------------------------------------------------------------------------- /// - /// GetWorkflowStatePermissions gets a Dictionary of WorkflowStatePermissionCollections by + /// HasWorkflowStatePermission checks whether the current user has a specific WorkflowState Permission. + /// + /// The Permissions for the WorkflowState. + /// The Permission to check. + /// + /// ----------------------------------------------------------------------------- + public static bool HasWorkflowStatePermission(WorkflowStatePermissionCollection objWorkflowStatePermissions, string permissionKey) + { + return PortalSecurity.IsInRoles(objWorkflowStatePermissions.ToString(permissionKey)); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetWorkflowStatePermissions gets a Dictionary of WorkflowStatePermissionCollections by /// WorkflowState. /// /// ----------------------------------------------------------------------------- private static Dictionary GetWorkflowStatePermissions() { - return CBO.GetCachedObject>(new CacheItemArgs(WorkflowStatePermissionCacheKey, WorkflowStatePermissionCachePriority), - GetWorkflowStatePermissionsCallBack); + return CBO.GetCachedObject>( + new CacheItemArgs(WorkflowStatePermissionCacheKey, WorkflowStatePermissionCachePriority), + GetWorkflowStatePermissionsCallBack); } /// ----------------------------------------------------------------------------- /// - /// GetWorkflowStatePermissionsCallBack gets a Dictionary of WorkflowStatePermissionCollections by + /// GetWorkflowStatePermissionsCallBack gets a Dictionary of WorkflowStatePermissionCollections by /// WorkflowState from the the Database. /// - /// The CacheItemArgs object that contains the parameters needed for the database call + /// The CacheItemArgs object that contains the parameters needed for the database call. /// ----------------------------------------------------------------------------- private static object GetWorkflowStatePermissionsCallBack(CacheItemArgs cacheItemArgs) { @@ -62,9 +101,9 @@ private static object GetWorkflowStatePermissionsCallBack(CacheItemArgs cacheIte /// ----------------------------------------------------------------------------- /// /// FillWorkflowStatePermissionDictionary fills a Dictionary of WorkflowStatePermissions from a - /// dataReader + /// dataReader. /// - /// The IDataReader + /// The IDataReader. /// ----------------------------------------------------------------------------- private static Dictionary FillWorkflowStatePermissionDictionary(IDataReader dr) { @@ -80,18 +119,18 @@ private static Dictionary FillWorkflowSt // add WorkflowState Permission to dictionary if (dic.ContainsKey(obj.StateID)) { - //Add WorkflowStatePermission to WorkflowStatePermission Collection already in dictionary for StateId + // Add WorkflowStatePermission to WorkflowStatePermission Collection already in dictionary for StateId dic[obj.StateID].Add(obj); } else { - //Create new WorkflowStatePermission Collection for WorkflowStatePermissionID + // Create new WorkflowStatePermission Collection for WorkflowStatePermissionID var collection = new WorkflowStatePermissionCollection(); - //Add Permission to Collection + // Add Permission to Collection collection.Add(obj); - //Add Collection to Dictionary + // Add Collection to Dictionary dic.Add(obj.StateID, collection); } } @@ -108,53 +147,8 @@ private static Dictionary FillWorkflowSt dr.Close(); } } + return dic; - } - - #endregion - - #region Public Shared Methods - - /// ----------------------------------------------------------------------------- - /// - /// GetWorkflowStatePermissions gets a WorkflowStatePermissionCollection - /// - /// The ID of the State - /// ----------------------------------------------------------------------------- - public static WorkflowStatePermissionCollection GetWorkflowStatePermissions(int StateID) - { - bool bFound = false; - - //Get the WorkflowStatePermission Dictionary - Dictionary dicWorkflowStatePermissions = GetWorkflowStatePermissions(); - - //Get the Collection from the Dictionary - WorkflowStatePermissionCollection WorkflowStatePermissions = null; - bFound = dicWorkflowStatePermissions.TryGetValue(StateID, out WorkflowStatePermissions); - - if (!bFound) - { - //try the database - WorkflowStatePermissions = new WorkflowStatePermissionCollection(CBO.FillCollection(provider.GetWorkflowStatePermissionsByStateID(StateID), typeof (WorkflowStatePermissionInfo)), - StateID); - } - - return WorkflowStatePermissions; - } - - - /// ----------------------------------------------------------------------------- - /// - /// HasWorkflowStatePermission checks whether the current user has a specific WorkflowState Permission - /// - /// The Permissions for the WorkflowState - /// The Permission to check - /// ----------------------------------------------------------------------------- - public static bool HasWorkflowStatePermission(WorkflowStatePermissionCollection objWorkflowStatePermissions, string permissionKey) - { - return PortalSecurity.IsInRoles(objWorkflowStatePermissions.ToString(permissionKey)); - } - - #endregion + } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs index a16a9edaa31..41016d4b8e7 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs @@ -1,115 +1,127 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Security.Permissions { + using System; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke + /// Project : DotNetNuke /// Namespace: DotNetNuke.Security.Permissions - /// Class : DesktopModulePermissionInfo + /// Class : DesktopModulePermissionInfo /// ----------------------------------------------------------------------------- /// - /// DesktopModulePermissionInfo provides the Entity Layer for DesktopModulePermissionInfo - /// Permissions + /// DesktopModulePermissionInfo provides the Entity Layer for DesktopModulePermissionInfo + /// Permissions. /// /// ----------------------------------------------------------------------------- [Serializable] public class WorkflowStatePermissionInfo : PermissionInfoBase, IHydratable { // local property declarations - private int _StateID; - private int _WorkflowStatePermissionID; - - #region Constructors - + private int _WorkflowStatePermissionID; + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new WorkflowStatePermissionInfo + /// + /// Initializes a new instance of the class. + /// Constructs a new WorkflowStatePermissionInfo. /// /// ----------------------------------------------------------------------------- public WorkflowStatePermissionInfo() { - _WorkflowStatePermissionID = Null.NullInteger; - _StateID = Null.NullInteger; - } - - //New - + this._WorkflowStatePermissionID = Null.NullInteger; + this._StateID = Null.NullInteger; + } + + // New + /// ----------------------------------------------------------------------------- - /// - /// Constructs a new WorkflowStatePermissionInfo + /// + /// Initializes a new instance of the class. + /// Constructs a new WorkflowStatePermissionInfo. /// - /// A PermissionInfo object + /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public WorkflowStatePermissionInfo(PermissionInfo permission) : this() + public WorkflowStatePermissionInfo(PermissionInfo permission) + : this() { - ModuleDefID = permission.ModuleDefID; - PermissionCode = permission.PermissionCode; - PermissionID = permission.PermissionID; - PermissionKey = permission.PermissionKey; - PermissionName = permission.PermissionName; - } - - #endregion - - #region Public Properties - + this.ModuleDefID = permission.ModuleDefID; + this.PermissionCode = permission.PermissionCode; + this.PermissionID = permission.PermissionID; + this.PermissionKey = permission.PermissionKey; + this.PermissionName = permission.PermissionName; + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the WorkflowState Permission ID + /// Gets or sets and sets the WorkflowState Permission ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int WorkflowStatePermissionID { get { - return _WorkflowStatePermissionID; + return this._WorkflowStatePermissionID; } + set { - _WorkflowStatePermissionID = value; + this._WorkflowStatePermissionID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the State ID + /// Gets or sets and sets the State ID. /// - /// An Integer + /// An Integer. /// ----------------------------------------------------------------------------- public int StateID { get { - return _StateID; + return this._StateID; } + set { - _StateID = value; + this._StateID = value; } - } - - #endregion - - #region Public Methods + } /// ----------------------------------------------------------------------------- /// - /// Compares if two WorkflowStatePermissionInfo objects are equivalent/equal + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public int KeyID + { + get + { + return this.WorkflowStatePermissionID; + } + + set + { + this.WorkflowStatePermissionID = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Compares if two WorkflowStatePermissionInfo objects are equivalent/equal. /// - /// a WorkflowStatePermissionObject + /// a WorkflowStatePermissionObject. /// true if the permissions being passed represents the same permission - /// in the current object + /// in the current object. /// /// /// This function is needed to prevent adding duplicates to the WorkflowStatePermissionCollection. @@ -123,15 +135,18 @@ public override bool Equals(object obj) { return false; } + if (ReferenceEquals(this, obj)) { return true; } + if (obj.GetType() != typeof(WorkflowStatePermissionInfo)) { return false; } - return Equals((WorkflowStatePermissionInfo)obj); + + return this.Equals((WorkflowStatePermissionInfo)obj); } public bool Equals(WorkflowStatePermissionInfo other) @@ -140,58 +155,36 @@ public bool Equals(WorkflowStatePermissionInfo other) { return false; } + if (ReferenceEquals(this, other)) { return true; } - return (AllowAccess == other.AllowAccess) && (StateID == other.StateID) && (RoleID == other.RoleID) && (PermissionID == other.PermissionID); + + return (this.AllowAccess == other.AllowAccess) && (this.StateID == other.StateID) && (this.RoleID == other.RoleID) && (this.PermissionID == other.PermissionID); } - + public override int GetHashCode() { unchecked { - return (_StateID*397) ^ _WorkflowStatePermissionID; + return (this._StateID * 397) ^ this._WorkflowStatePermissionID; } - } - - #endregion - - #region IHydratable Implementation - + } + /// ----------------------------------------------------------------------------- /// - /// Fills a WorkflowStatePermissionInfo from a Data Reader + /// Fills a WorkflowStatePermissionInfo from a Data Reader. /// - /// The Data Reader to use + /// The Data Reader to use. /// ----------------------------------------------------------------------------- public void Fill(IDataReader dr) { - //Call the base classes fill method to populate base class proeprties - base.FillInternal(dr); + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); - WorkflowStatePermissionID = Null.SetNullInteger(dr["WorkflowStatePermissionID"]); - StateID = Null.SetNullInteger(dr["StateID"]); + this.WorkflowStatePermissionID = Null.SetNullInteger(dr["WorkflowStatePermissionID"]); + this.StateID = Null.SetNullInteger(dr["StateID"]); } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Key ID - /// - /// An Integer - /// ----------------------------------------------------------------------------- - public int KeyID - { - get - { - return WorkflowStatePermissionID; - } - set - { - WorkflowStatePermissionID = value; - } - } - - #endregion } } diff --git a/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj b/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj index 241991b2144..4a4f40e4791 100644 --- a/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj +++ b/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj @@ -28,6 +28,7 @@ + true @@ -187,6 +188,9 @@ + + stylecop.json + @@ -252,5 +256,9 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/HTML/EditHtml.ascx.cs b/DNN Platform/Modules/HTML/EditHtml.ascx.cs index a1bf18da9ae..ed9e00d5c75 100644 --- a/DNN Platform/Modules/HTML/EditHtml.ascx.cs +++ b/DNN Platform/Modules/HTML/EditHtml.ascx.cs @@ -1,67 +1,77 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Linq; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Common.Utilities; -using Telerik.Web.UI; -using DotNetNuke.Modules.Html.Components; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Html { + using System; + using System.Collections; + using System.Linq; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.Html.Components; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + using Telerik.Web.UI; /// - /// The EditHtml PortalModuleBase is used to manage Html + /// The EditHtml PortalModuleBase is used to manage Html. /// /// /// public partial class EditHtml : HtmlModuleBase { private readonly INavigationManager _navigationManager; - public EditHtml() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members private readonly HtmlTextController _htmlTextController = new HtmlTextController(); private readonly HtmlTextLogController _htmlTextLogController = new HtmlTextLogController(); private readonly WorkflowStateController _workflowStateController = new WorkflowStateController(); - #endregion - - #region Nested type: WorkflowType + public EditHtml() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } private enum WorkflowType { DirectPublish = 1, - ContentStaging = 2 + ContentStaging = 2, } - #endregion + protected string CurrentView + { + get + { + if (this.phEdit.Visible) + { + return "EditView"; + } + else if (this.phPreview.Visible) + { + return "PreviewView"; + } - #region Private Properties + if (this.phHistory.Visible) + { + return "HistoryView"; + } + else + { + return string.Empty; + } + } + } private int WorkflowID { @@ -69,14 +79,14 @@ private int WorkflowID { int workflowID; - if (ViewState["WorkflowID"] == null) + if (this.ViewState["WorkflowID"] == null) { - workflowID = _htmlTextController.GetWorkflow(ModuleId, TabId, PortalId).Value; - ViewState.Add("WorkflowID", workflowID); + workflowID = this._htmlTextController.GetWorkflow(this.ModuleId, this.TabId, this.PortalId).Value; + this.ViewState.Add("WorkflowID", workflowID); } else { - workflowID = int.Parse(ViewState["WorkflowID"].ToString()); + workflowID = int.Parse(this.ViewState["WorkflowID"].ToString()); } return workflowID; @@ -87,16 +97,18 @@ private string TempContent { get { - var content = ""; - if ((ViewState["TempContent"] != null)) + var content = string.Empty; + if (this.ViewState["TempContent"] != null) { - content = ViewState["TempContent"].ToString(); + content = this.ViewState["TempContent"].ToString(); } + return content; } + set { - ViewState["TempContent"] = value; + this.ViewState["TempContent"] = value; } } @@ -105,37 +117,176 @@ private WorkflowType CurrentWorkflowType get { var currentWorkflowType = default(WorkflowType); - if (ViewState["_currentWorkflowType"] != null) + if (this.ViewState["_currentWorkflowType"] != null) { - currentWorkflowType = (WorkflowType) Enum.Parse(typeof (WorkflowType), ViewState["_currentWorkflowType"].ToString()); + currentWorkflowType = (WorkflowType)Enum.Parse(typeof(WorkflowType), this.ViewState["_currentWorkflowType"].ToString()); } return currentWorkflowType; } + set { - ViewState["_currentWorkflowType"] = value; + this.ViewState["_currentWorkflowType"] = value; } } - protected string CurrentView + protected override void OnInit(EventArgs e) { - get + base.OnInit(e); + + this.hlCancel.NavigateUrl = this._navigationManager.NavigateURL(); + + this.cmdEdit.Click += this.OnEditClick; + this.cmdPreview.Click += this.OnPreviewClick; + this.cmdHistory.Click += this.OnHistoryClick; + this.cmdMasterContent.Click += this.OnMasterContentClick; + this.ddlRender.SelectedIndexChanged += this.OnRenderSelectedIndexChanged; + this.cmdSave.Click += this.OnSaveClick; + this.dgHistory.RowDataBound += this.OnHistoryGridItemDataBound; + this.dgVersions.RowCommand += this.OnVersionsGridItemCommand; + this.dgVersions.RowDataBound += this.OnVersionsGridItemDataBound; + this.dgVersions.PageIndexChanged += this.OnVersionsGridPageIndexChanged; + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + try { - if (phEdit.Visible) - return "EditView"; - else if (phPreview.Visible) - return "PreviewView"; - if (phHistory.Visible) - return "HistoryView"; - else - return ""; + var htmlContentItemID = -1; + var htmlContent = this._htmlTextController.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); + + if (htmlContent != null) + { + htmlContentItemID = htmlContent.ItemID; + } + + if (!this.Page.IsPostBack) + { + var workflowStates = this._workflowStateController.GetWorkflowStates(this.WorkflowID); + var maxVersions = this._htmlTextController.GetMaximumVersionHistory(this.PortalId); + var userCanEdit = this.UserInfo.IsSuperUser || PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); + + this.lblMaxVersions.Text = maxVersions.ToString(); + this.dgVersions.PageSize = Math.Min(Math.Max(maxVersions, 5), 10); // min 5, max 10 + + switch (workflowStates.Count) + { + case 1: + this.CurrentWorkflowType = WorkflowType.DirectPublish; + break; + case 2: + this.CurrentWorkflowType = WorkflowType.ContentStaging; + break; + } + + if (htmlContentItemID != -1) + { + this.DisplayContent(htmlContent); + + // DisplayPreview(htmlContent); + this.DisplayHistory(htmlContent); + } + else + { + this.DisplayInitialContent(workflowStates[0] as WorkflowStateInfo); + } + + this.divPublish.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; + this.phCurrentVersion.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; + this.phPreviewVersion.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; + + // DisplayVersions(); + this.BindRenderItems(); + this.ddlRender.SelectedValue = this.txtContent.Mode; + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); } } - #endregion + protected void OnSaveClick(object sender, EventArgs e) + { + const bool redirect = true; + + try + { + // get content + var htmlContent = this.GetLatestHTMLContent(); + + var aliases = from PortalAliasInfo pa in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalSettings.PortalId) + select pa.HTTPAlias; + string content; + if (this.phEdit.Visible) + { + content = this.txtContent.Text; + } + else + { + content = this.hfEditor.Value; + } + + if (this.Request.QueryString["nuru"] == null) + { + content = HtmlUtils.AbsoluteToRelativeUrls(content, aliases); + } + + htmlContent.Content = content; + + var draftStateID = this._workflowStateController.GetFirstWorkflowStateID(this.WorkflowID); + var publishedStateID = this._workflowStateController.GetLastWorkflowStateID(this.WorkflowID); + + switch (this.CurrentWorkflowType) + { + case WorkflowType.DirectPublish: + this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); + + break; + case WorkflowType.ContentStaging: + if (this.chkPublish.Checked) + { + // if it's already published set it to draft + if (htmlContent.StateID == publishedStateID) + { + htmlContent.StateID = draftStateID; + } + else + { + htmlContent.StateID = publishedStateID; + + // here it's in published mode + } + } + else + { + // if it's already published set it back to draft + if (htmlContent.StateID != draftStateID) + { + htmlContent.StateID = draftStateID; + } + } - #region Private Methods + this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); + break; + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + UI.Skins.Skin.AddModuleMessage(this.Page, "Error occurred: ", exc.Message, ModuleMessage.ModuleMessageType.RedError); + return; + } + + // redirect back to portal + if (redirect) + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + } /// /// Displays the history of an html content item in a grid in the preview section. @@ -143,43 +294,45 @@ protected string CurrentView /// Content of the HTML. private void DisplayHistory(HtmlTextInfo htmlContent) { - dnnSitePanelEditHTMLHistory.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; - fsEditHtmlHistory.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; + this.dnnSitePanelEditHTMLHistory.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; + this.fsEditHtmlHistory.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; - if (((CurrentWorkflowType == WorkflowType.DirectPublish))) + if (this.CurrentWorkflowType == WorkflowType.DirectPublish) { return; } - var htmlLogging = _htmlTextLogController.GetHtmlTextLog(htmlContent.ItemID); - dgHistory.DataSource = htmlLogging; - dgHistory.DataBind(); - dnnSitePanelEditHTMLHistory.Visible = htmlLogging.Count != 0; - fsEditHtmlHistory.Visible = htmlLogging.Count != 0; + var htmlLogging = this._htmlTextLogController.GetHtmlTextLog(htmlContent.ItemID); + this.dgHistory.DataSource = htmlLogging; + this.dgHistory.DataBind(); + + this.dnnSitePanelEditHTMLHistory.Visible = htmlLogging.Count != 0; + this.fsEditHtmlHistory.Visible = htmlLogging.Count != 0; } /// - /// Displays the versions of the html content in the versions section + /// Displays the versions of the html content in the versions section. /// private void DisplayVersions() { - var versions = _htmlTextController.GetAllHtmlText(ModuleId); + var versions = this._htmlTextController.GetAllHtmlText(this.ModuleId); foreach (var item in versions) { - item.StateName = GetLocalizedString(item.StateName); + item.StateName = this.GetLocalizedString(item.StateName); } - dgVersions.DataSource = versions; - dgVersions.DataBind(); - phEdit.Visible = false; - phPreview.Visible = false; - phHistory.Visible = true; - cmdEdit.Enabled = true; - cmdPreview.Enabled = true; - cmdHistory.Enabled = false; - cmdMasterContent.Visible = false; - ddlRender.Visible = false; + this.dgVersions.DataSource = versions; + this.dgVersions.DataBind(); + + this.phEdit.Visible = false; + this.phPreview.Visible = false; + this.phHistory.Visible = true; + this.cmdEdit.Enabled = true; + this.cmdPreview.Enabled = true; + this.cmdHistory.Enabled = false; + this.cmdMasterContent.Visible = false; + this.ddlRender.Visible = false; } /// @@ -187,14 +340,14 @@ private void DisplayVersions() /// private void DisplayMasterLanguageContent() { - //Get master language - var objModule = ModuleController.Instance.GetModule(ModuleId, TabId, false); + // Get master language + var objModule = ModuleController.Instance.GetModule(this.ModuleId, this.TabId, false); if (objModule.DefaultLanguageModule != null) { - var masterContent = _htmlTextController.GetTopHtmlText(objModule.DefaultLanguageModule.ModuleID, false, WorkflowID); + var masterContent = this._htmlTextController.GetTopHtmlText(objModule.DefaultLanguageModule.ModuleID, false, this.WorkflowID); if (masterContent != null) { - placeMasterContent.Controls.Add(new LiteralControl(HtmlTextController.FormatHtmlText(objModule.DefaultLanguageModule.ModuleID, FormatContent(masterContent.Content), Settings, PortalSettings, Page))); + this.placeMasterContent.Controls.Add(new LiteralControl(HtmlTextController.FormatHtmlText(objModule.DefaultLanguageModule.ModuleID, this.FormatContent(masterContent.Content), this.Settings, this.PortalSettings, this.Page))); } } } @@ -205,125 +358,126 @@ private void DisplayMasterLanguageContent() /// Content of the HTML. private void DisplayContent(HtmlTextInfo htmlContent) { - lblCurrentWorkflowInUse.Text = GetLocalizedString(htmlContent.WorkflowName); - lblCurrentWorkflowState.Text = GetLocalizedString(htmlContent.StateName); - lblCurrentVersion.Text = htmlContent.Version.ToString(); - txtContent.Text = FormatContent(htmlContent.Content); - phEdit.Visible = true; - phPreview.Visible = false; - phHistory.Visible = false; - cmdEdit.Enabled = false; - cmdPreview.Enabled = true; - cmdHistory.Enabled = true; - //DisplayMasterLanguageContent(); - DisplayMasterContentButton(); - ddlRender.Visible = true; + this.lblCurrentWorkflowInUse.Text = this.GetLocalizedString(htmlContent.WorkflowName); + this.lblCurrentWorkflowState.Text = this.GetLocalizedString(htmlContent.StateName); + this.lblCurrentVersion.Text = htmlContent.Version.ToString(); + this.txtContent.Text = this.FormatContent(htmlContent.Content); + this.phEdit.Visible = true; + this.phPreview.Visible = false; + this.phHistory.Visible = false; + this.cmdEdit.Enabled = false; + this.cmdPreview.Enabled = true; + this.cmdHistory.Enabled = true; + + // DisplayMasterLanguageContent(); + this.DisplayMasterContentButton(); + this.ddlRender.Visible = true; } private void DisplayMasterContentButton() { - var objModule = ModuleController.Instance.GetModule(ModuleId, TabId, false); + var objModule = ModuleController.Instance.GetModule(this.ModuleId, this.TabId, false); if (objModule.DefaultLanguageModule != null) { - cmdMasterContent.Visible = true; - cmdMasterContent.Text = Localization.GetString("cmdShowMasterContent", LocalResourceFile); - - cmdMasterContent.Text = phMasterContent.Visible ? - Localization.GetString("cmdHideMasterContent", LocalResourceFile) : - Localization.GetString("cmdShowMasterContent", LocalResourceFile); + this.cmdMasterContent.Visible = true; + this.cmdMasterContent.Text = Localization.GetString("cmdShowMasterContent", this.LocalResourceFile); + this.cmdMasterContent.Text = this.phMasterContent.Visible ? + Localization.GetString("cmdHideMasterContent", this.LocalResourceFile) : + Localization.GetString("cmdShowMasterContent", this.LocalResourceFile); } } /// - /// Displays the content preview in the preview section + /// Displays the content preview in the preview section. /// /// Content of the HTML. private void DisplayPreview(HtmlTextInfo htmlContent) { - lblPreviewVersion.Text = htmlContent.Version.ToString(); - lblPreviewWorkflowInUse.Text = GetLocalizedString(htmlContent.WorkflowName); - lblPreviewWorkflowState.Text = GetLocalizedString(htmlContent.StateName); - litPreview.Text = HtmlTextController.FormatHtmlText(ModuleId, htmlContent.Content, Settings, PortalSettings, Page); - phEdit.Visible = false; - phPreview.Visible = true; - phHistory.Visible = false; - cmdEdit.Enabled = true; - cmdPreview.Enabled = false; - cmdHistory.Enabled = true; - DisplayHistory(htmlContent); - cmdMasterContent.Visible = false; - ddlRender.Visible = false; + this.lblPreviewVersion.Text = htmlContent.Version.ToString(); + this.lblPreviewWorkflowInUse.Text = this.GetLocalizedString(htmlContent.WorkflowName); + this.lblPreviewWorkflowState.Text = this.GetLocalizedString(htmlContent.StateName); + this.litPreview.Text = HtmlTextController.FormatHtmlText(this.ModuleId, htmlContent.Content, this.Settings, this.PortalSettings, this.Page); + this.phEdit.Visible = false; + this.phPreview.Visible = true; + this.phHistory.Visible = false; + this.cmdEdit.Enabled = true; + this.cmdPreview.Enabled = false; + this.cmdHistory.Enabled = true; + this.DisplayHistory(htmlContent); + this.cmdMasterContent.Visible = false; + this.ddlRender.Visible = false; } /// - /// Displays the preview in the preview section + /// Displays the preview in the preview section. /// /// Content of the HTML. private void DisplayPreview(string htmlContent) { - litPreview.Text = HtmlTextController.FormatHtmlText(ModuleId, htmlContent, Settings, PortalSettings, Page); - divPreviewVersion.Visible = false; - divPreviewWorlflow.Visible = false; + this.litPreview.Text = HtmlTextController.FormatHtmlText(this.ModuleId, htmlContent, this.Settings, this.PortalSettings, this.Page); + this.divPreviewVersion.Visible = false; + this.divPreviewWorlflow.Visible = false; - divPreviewWorkflowState.Visible = true; - lblPreviewWorkflowState.Text = GetLocalizedString("EditPreviewState"); + this.divPreviewWorkflowState.Visible = true; + this.lblPreviewWorkflowState.Text = this.GetLocalizedString("EditPreviewState"); - phEdit.Visible = false; - phPreview.Visible = true; - phHistory.Visible = false; - cmdEdit.Enabled = true; - cmdPreview.Enabled = false; - cmdHistory.Enabled = true; - cmdMasterContent.Visible = false; - ddlRender.Visible = false; + this.phEdit.Visible = false; + this.phPreview.Visible = true; + this.phHistory.Visible = false; + this.cmdEdit.Enabled = true; + this.cmdPreview.Enabled = false; + this.cmdHistory.Enabled = true; + this.cmdMasterContent.Visible = false; + this.ddlRender.Visible = false; } private void DisplayEdit(string htmlContent) { - txtContent.Text = htmlContent; - phEdit.Visible = true; - phPreview.Visible = false; - phHistory.Visible = false; - cmdEdit.Enabled = false; - cmdPreview.Enabled = true; - cmdHistory.Enabled = true; - DisplayMasterContentButton(); - ddlRender.Visible = true; - + this.txtContent.Text = htmlContent; + this.phEdit.Visible = true; + this.phPreview.Visible = false; + this.phHistory.Visible = false; + this.cmdEdit.Enabled = false; + this.cmdPreview.Enabled = true; + this.cmdHistory.Enabled = true; + this.DisplayMasterContentButton(); + this.ddlRender.Visible = true; } /// - /// Displays the content but hide the editor if editing is locked from the current user + /// Displays the content but hide the editor if editing is locked from the current user. /// /// Content of the HTML. /// Last content of the published. private void DisplayLockedContent(HtmlTextInfo htmlContent, HtmlTextInfo lastPublishedContent) { - txtContent.Visible = false; - cmdSave.Visible = false; - //cmdPreview.Enabled = false; - divPublish.Visible = false; + this.txtContent.Visible = false; + this.cmdSave.Visible = false; - divSubmittedContent.Visible = true; + // cmdPreview.Enabled = false; + this.divPublish.Visible = false; - lblCurrentWorkflowInUse.Text = GetLocalizedString(htmlContent.WorkflowName); - lblCurrentWorkflowState.Text = GetLocalizedString(htmlContent.StateName); + this.divSubmittedContent.Visible = true; - litCurrentContentPreview.Text = HtmlTextController.FormatHtmlText(ModuleId, htmlContent.Content, Settings, PortalSettings, Page); - lblCurrentVersion.Text = htmlContent.Version.ToString(); - DisplayVersions(); + this.lblCurrentWorkflowInUse.Text = this.GetLocalizedString(htmlContent.WorkflowName); + this.lblCurrentWorkflowState.Text = this.GetLocalizedString(htmlContent.StateName); - if ((lastPublishedContent != null)) + this.litCurrentContentPreview.Text = HtmlTextController.FormatHtmlText(this.ModuleId, htmlContent.Content, this.Settings, this.PortalSettings, this.Page); + this.lblCurrentVersion.Text = htmlContent.Version.ToString(); + this.DisplayVersions(); + + if (lastPublishedContent != null) { - DisplayPreview(lastPublishedContent); - //DisplayHistory(lastPublishedContent); + this.DisplayPreview(lastPublishedContent); + + // DisplayHistory(lastPublishedContent); } else { - dnnSitePanelEditHTMLHistory.Visible = false; - fsEditHtmlHistory.Visible = false; - DisplayPreview(htmlContent.Content); + this.dnnSitePanelEditHTMLHistory.Visible = false; + this.fsEditHtmlHistory.Visible = false; + this.DisplayPreview(htmlContent.Content); } } @@ -333,28 +487,24 @@ private void DisplayLockedContent(HtmlTextInfo htmlContent, HtmlTextInfo lastPub /// The first state. private void DisplayInitialContent(WorkflowStateInfo firstState) { - cmdHistory.Enabled = false; + this.cmdHistory.Enabled = false; - txtContent.Text = GetLocalizedString("AddContent"); - litPreview.Text = GetLocalizedString("AddContent"); - lblCurrentWorkflowInUse.Text = firstState.WorkflowName; - lblPreviewWorkflowInUse.Text = firstState.WorkflowName; - divPreviewVersion.Visible = false; + this.txtContent.Text = this.GetLocalizedString("AddContent"); + this.litPreview.Text = this.GetLocalizedString("AddContent"); + this.lblCurrentWorkflowInUse.Text = firstState.WorkflowName; + this.lblPreviewWorkflowInUse.Text = firstState.WorkflowName; + this.divPreviewVersion.Visible = false; - dnnSitePanelEditHTMLHistory.Visible = false; - fsEditHtmlHistory.Visible = false; + this.dnnSitePanelEditHTMLHistory.Visible = false; + this.fsEditHtmlHistory.Visible = false; - divCurrentWorkflowState.Visible = false; - phCurrentVersion.Visible = false; - divPreviewWorkflowState.Visible = false; + this.divCurrentWorkflowState.Visible = false; + this.phCurrentVersion.Visible = false; + this.divPreviewWorkflowState.Visible = false; - lblPreviewWorkflowState.Text = firstState.StateName; + this.lblPreviewWorkflowState.Text = firstState.StateName; } - #endregion - - #region Private Functions - /// /// Formats the content to make it html safe. /// @@ -363,8 +513,8 @@ private void DisplayInitialContent(WorkflowStateInfo firstState) private string FormatContent(string htmlContent) { var strContent = HttpUtility.HtmlDecode(htmlContent); - strContent = HtmlTextController.ManageRelativePaths(strContent, PortalSettings.HomeDirectory, "src", PortalId); - strContent = HtmlTextController.ManageRelativePaths(strContent, PortalSettings.HomeDirectory, "background", PortalId); + strContent = HtmlTextController.ManageRelativePaths(strContent, this.PortalSettings.HomeDirectory, "src", this.PortalId); + strContent = HtmlTextController.ManageRelativePaths(strContent, this.PortalSettings.HomeDirectory, "background", this.PortalId); return HttpUtility.HtmlEncode(strContent); } @@ -375,31 +525,31 @@ private string FormatContent(string htmlContent) /// private string GetLocalizedString(string str) { - var localizedString = Localization.GetString(str, LocalResourceFile); - return (string.IsNullOrEmpty(localizedString) ? str : localizedString); + var localizedString = Localization.GetString(str, this.LocalResourceFile); + return string.IsNullOrEmpty(localizedString) ? str : localizedString; } /// - /// Gets the latest html content of the module + /// Gets the latest html content of the module. /// /// private HtmlTextInfo GetLatestHTMLContent() { - var htmlContent = _htmlTextController.GetTopHtmlText(ModuleId, false, WorkflowID); + var htmlContent = this._htmlTextController.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); if (htmlContent == null) { htmlContent = new HtmlTextInfo(); htmlContent.ItemID = -1; - htmlContent.StateID = _workflowStateController.GetFirstWorkflowStateID(WorkflowID); - htmlContent.WorkflowID = WorkflowID; - htmlContent.ModuleID = ModuleId; + htmlContent.StateID = this._workflowStateController.GetFirstWorkflowStateID(this.WorkflowID); + htmlContent.WorkflowID = this.WorkflowID; + htmlContent.ModuleID = this.ModuleId; } return htmlContent; } /// - /// Returns whether or not the user has review permissions to this module + /// Returns whether or not the user has review permissions to this module. /// /// Content of the HTML. /// @@ -409,94 +559,30 @@ private bool UserCanReview(HtmlTextInfo htmlContent) } /// - /// Gets the last published version of this module + /// Gets the last published version of this module. /// /// The published state ID. /// private HtmlTextInfo GetLastPublishedVersion(int publishedStateID) { - return (from version in _htmlTextController.GetAllHtmlText(ModuleId) where version.StateID == publishedStateID orderby version.Version descending select version).ToList()[0]; - } - - #endregion - - #region Event Handlers - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - hlCancel.NavigateUrl = _navigationManager.NavigateURL(); - - cmdEdit.Click += OnEditClick; - cmdPreview.Click += OnPreviewClick; - cmdHistory.Click += OnHistoryClick; - cmdMasterContent.Click += OnMasterContentClick; - ddlRender.SelectedIndexChanged += OnRenderSelectedIndexChanged; - cmdSave.Click += OnSaveClick; - dgHistory.RowDataBound += OnHistoryGridItemDataBound; - dgVersions.RowCommand += OnVersionsGridItemCommand; - dgVersions.RowDataBound += OnVersionsGridItemDataBound; - dgVersions.PageIndexChanged += OnVersionsGridPageIndexChanged; + return (from version in this._htmlTextController.GetAllHtmlText(this.ModuleId) where version.StateID == publishedStateID orderby version.Version descending select version).ToList()[0]; } private void OnRenderSelectedIndexChanged(object sender, EventArgs e) { - txtContent.ChangeMode(ddlRender.SelectedValue); + this.txtContent.ChangeMode(this.ddlRender.SelectedValue); } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); + protected void OnEditClick(object sender, EventArgs e) + { try { - var htmlContentItemID = -1; - var htmlContent = _htmlTextController.GetTopHtmlText(ModuleId, false, WorkflowID); + this.DisplayEdit(this.hfEditor.Value); - if ((htmlContent != null)) + if (this.phMasterContent.Visible) { - htmlContentItemID = htmlContent.ItemID; + this.DisplayMasterLanguageContent(); } - - if (!Page.IsPostBack) - { - var workflowStates = _workflowStateController.GetWorkflowStates(WorkflowID); - var maxVersions = _htmlTextController.GetMaximumVersionHistory(PortalId); - var userCanEdit = UserInfo.IsSuperUser || PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); - - lblMaxVersions.Text = maxVersions.ToString(); - dgVersions.PageSize = Math.Min(Math.Max(maxVersions, 5), 10); //min 5, max 10 - - switch (workflowStates.Count) - { - case 1: - CurrentWorkflowType = WorkflowType.DirectPublish; - break; - case 2: - CurrentWorkflowType = WorkflowType.ContentStaging; - break; - } - - if (htmlContentItemID != -1) - { - DisplayContent(htmlContent); - //DisplayPreview(htmlContent); - DisplayHistory(htmlContent); - } - else - { - DisplayInitialContent(workflowStates[0] as WorkflowStateInfo); - } - - divPublish.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; - phCurrentVersion.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; - phPreviewVersion.Visible = CurrentWorkflowType != WorkflowType.DirectPublish; - //DisplayVersions(); - - BindRenderItems(); - ddlRender.SelectedValue = txtContent.Mode; - } - } catch (Exception exc) { @@ -504,132 +590,16 @@ protected override void OnLoad(EventArgs e) } } - protected void OnSaveClick(object sender, EventArgs e) + protected void OnPreviewClick(object sender, EventArgs e) { - const bool redirect = true; - try { - // get content - var htmlContent = GetLatestHTMLContent(); - - var aliases = from PortalAliasInfo pa in PortalAliasController.Instance.GetPortalAliasesByPortalId(PortalSettings.PortalId) - select pa.HTTPAlias; - string content; - if (phEdit.Visible) - content = txtContent.Text; - else - content = hfEditor.Value; - - - if (Request.QueryString["nuru"] == null) + if (this.phEdit.Visible) { - content = HtmlUtils.AbsoluteToRelativeUrls(content, aliases); + this.hfEditor.Value = this.txtContent.Text; } - htmlContent.Content = content; - - var draftStateID = _workflowStateController.GetFirstWorkflowStateID(WorkflowID); - var publishedStateID = _workflowStateController.GetLastWorkflowStateID(WorkflowID); - - switch (CurrentWorkflowType) - { - case WorkflowType.DirectPublish: - _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId)); - - break; - case WorkflowType.ContentStaging: - if (chkPublish.Checked) - { - //if it's already published set it to draft - if (htmlContent.StateID == publishedStateID) - { - htmlContent.StateID = draftStateID; - } - else - { - htmlContent.StateID = publishedStateID; - //here it's in published mode - } - } - else - { - //if it's already published set it back to draft - if ((htmlContent.StateID != draftStateID)) - { - htmlContent.StateID = draftStateID; - } - } - _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId)); - break; - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - UI.Skins.Skin.AddModuleMessage(Page, "Error occurred: ", exc.Message, ModuleMessage.ModuleMessageType.RedError); - return; - } - - // redirect back to portal - if (redirect) - { - Response.Redirect(_navigationManager.NavigateURL(), true); - } - } - protected void OnEditClick(object sender, EventArgs e) - { - try - { - DisplayEdit(hfEditor.Value); - - if (phMasterContent.Visible) - DisplayMasterLanguageContent(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - protected void OnPreviewClick(object sender, EventArgs e) - { - try - { - if (phEdit.Visible) - hfEditor.Value = txtContent.Text; - DisplayPreview(phEdit.Visible ? txtContent.Text : hfEditor.Value); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - private void OnHistoryClick(object sender, EventArgs e) - { - try - { - if (phEdit.Visible) - hfEditor.Value = txtContent.Text; - DisplayVersions(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - - private void OnMasterContentClick(object sender, EventArgs e) - { - try - { - phMasterContent.Visible = !phMasterContent.Visible; - cmdMasterContent.Text = phMasterContent.Visible ? - Localization.GetString("cmdHideMasterContent", LocalResourceFile) : - Localization.GetString("cmdShowMasterContent", LocalResourceFile); - - if (phMasterContent.Visible) - DisplayMasterLanguageContent(); + this.DisplayPreview(this.phEdit.Visible ? this.txtContent.Text : this.hfEditor.Value); } catch (Exception exc) { @@ -643,9 +613,9 @@ protected void OnHistoryGridItemDataBound(object sender, GridViewRowEventArgs e) if (item.RowType == DataControlRowType.DataRow) { - //Localize columns - item.Cells[2].Text = Localization.GetString(item.Cells[2].Text, LocalResourceFile); - item.Cells[3].Text = Localization.GetString(item.Cells[3].Text, LocalResourceFile); + // Localize columns + item.Cells[2].Text = Localization.GetString(item.Cells[2].Text, this.LocalResourceFile); + item.Cells[3].Text = Localization.GetString(item.Cells[3].Text, this.LocalResourceFile); } } @@ -655,43 +625,44 @@ protected void OnVersionsGridItemCommand(object source, GridViewCommandEventArgs { HtmlTextInfo htmlContent; - //disable delete button if user doesn't have delete rights??? + // disable delete button if user doesn't have delete rights??? switch (e.CommandName.ToLowerInvariant()) { case "remove": - htmlContent = GetHTMLContent(e); - _htmlTextController.DeleteHtmlText(ModuleId, htmlContent.ItemID); + htmlContent = this.GetHTMLContent(e); + this._htmlTextController.DeleteHtmlText(this.ModuleId, htmlContent.ItemID); break; case "rollback": - htmlContent = GetHTMLContent(e); + htmlContent = this.GetHTMLContent(e); htmlContent.ItemID = -1; - htmlContent.ModuleID = ModuleId; - htmlContent.WorkflowID = WorkflowID; - htmlContent.StateID = _workflowStateController.GetFirstWorkflowStateID(WorkflowID); - _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId)); + htmlContent.ModuleID = this.ModuleId; + htmlContent.WorkflowID = this.WorkflowID; + htmlContent.StateID = this._workflowStateController.GetFirstWorkflowStateID(this.WorkflowID); + this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); break; case "preview": - htmlContent = GetHTMLContent(e); - DisplayPreview(htmlContent); + htmlContent = this.GetHTMLContent(e); + this.DisplayPreview(htmlContent); break; } - if ((e.CommandName.ToLowerInvariant() != "preview")) + if (e.CommandName.ToLowerInvariant() != "preview") { - var latestContent = _htmlTextController.GetTopHtmlText(ModuleId, false, WorkflowID); + var latestContent = this._htmlTextController.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); if (latestContent == null) { - DisplayInitialContent(_workflowStateController.GetWorkflowStates(WorkflowID)[0] as WorkflowStateInfo); + this.DisplayInitialContent(this._workflowStateController.GetWorkflowStates(this.WorkflowID)[0] as WorkflowStateInfo); } else { - DisplayContent(latestContent); - //DisplayPreview(latestContent); - //DisplayVersions(); + this.DisplayContent(latestContent); + + // DisplayPreview(latestContent); + // DisplayVersions(); } } - //Module failed to load + // Module failed to load } catch (Exception exc) { @@ -699,9 +670,41 @@ protected void OnVersionsGridItemCommand(object source, GridViewCommandEventArgs } } - private HtmlTextInfo GetHTMLContent(GridViewCommandEventArgs e) + private void OnHistoryClick(object sender, EventArgs e) + { + try + { + if (this.phEdit.Visible) + { + this.hfEditor.Value = this.txtContent.Text; + } + + this.DisplayVersions(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + private void OnMasterContentClick(object sender, EventArgs e) { - return _htmlTextController.GetHtmlText(ModuleId, int.Parse(e.CommandArgument.ToString())); + try + { + this.phMasterContent.Visible = !this.phMasterContent.Visible; + this.cmdMasterContent.Text = this.phMasterContent.Visible ? + Localization.GetString("cmdHideMasterContent", this.LocalResourceFile) : + Localization.GetString("cmdShowMasterContent", this.LocalResourceFile); + + if (this.phMasterContent.Visible) + { + this.DisplayMasterLanguageContent(); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } } protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e) @@ -711,9 +714,9 @@ protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e var htmlContent = e.Row.DataItem as HtmlTextInfo; var createdBy = "Default"; - if ((htmlContent.CreatedByUserID != -1)) + if (htmlContent.CreatedByUserID != -1) { - var createdByByUser = UserController.GetUserById(PortalId, htmlContent.CreatedByUserID); + var createdByByUser = UserController.GetUserById(this.PortalId, htmlContent.CreatedByUserID); if (createdByByUser != null) { createdBy = createdByByUser.DisplayName; @@ -731,10 +734,10 @@ protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e switch (imageButton.CommandName.ToLowerInvariant()) { case "rollback": - //hide rollback for the first item - if (dgVersions.CurrentPageIndex == 0) + // hide rollback for the first item + if (this.dgVersions.CurrentPageIndex == 0) { - if ((e.Row.RowIndex == 0)) + if (e.Row.RowIndex == 0) { imageButton.Visible = false; break; @@ -745,13 +748,14 @@ protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e break; case "remove": - var msg = GetLocalizedString("DeleteVersion.Confirm"); + var msg = this.GetLocalizedString("DeleteVersion.Confirm"); msg = msg.Replace("[VERSION]", htmlContent.Version.ToString()).Replace("[STATE]", htmlContent.StateName).Replace("[DATECREATED]", htmlContent.CreatedOnDate.ToString()) .Replace("[USERNAME]", createdBy); imageButton.OnClientClick = "return confirm(\"" + msg + "\");"; - //hide the delete button - var showDelete = UserInfo.IsSuperUser || PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); + + // hide the delete button + var showDelete = this.UserInfo.IsSuperUser || PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); if (!showDelete) { @@ -769,20 +773,22 @@ protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e protected void OnVersionsGridPageIndexChanged(object source, EventArgs e) { - DisplayVersions(); + this.DisplayVersions(); + } + + private HtmlTextInfo GetHTMLContent(GridViewCommandEventArgs e) + { + return this._htmlTextController.GetHtmlText(this.ModuleId, int.Parse(e.CommandArgument.ToString())); } private void BindRenderItems() { - if (txtContent.IsRichEditorAvailable) + if (this.txtContent.IsRichEditorAvailable) { - ddlRender.Items.Add(new ListItem(LocalizeString("liRichText"), "RICH")); + this.ddlRender.Items.Add(new ListItem(this.LocalizeString("liRichText"), "RICH")); } - ddlRender.Items.Add(new ListItem(LocalizeString("liBasicText"), "BASIC")); + this.ddlRender.Items.Add(new ListItem(this.LocalizeString("liBasicText"), "BASIC")); } - - #endregion - } } diff --git a/DNN Platform/Modules/HTML/HtmlModule.ascx.cs b/DNN Platform/Modules/HTML/HtmlModule.ascx.cs index 71ee5a34d33..483a1a2352a 100644 --- a/DNN Platform/Modules/HTML/HtmlModule.ascx.cs +++ b/DNN Platform/Modules/HTML/HtmlModule.ascx.cs @@ -1,34 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.WebControls; -using DotNetNuke.Modules.Html.Components; -using DotNetNuke.Abstractions; - - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Html { + using System; + using System.Web.UI; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Modules.Html.Components; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// - /// The HtmlModule Class provides the UI for displaying the Html + /// The HtmlModule Class provides the UI for displaying the Html. /// /// /// @@ -39,20 +33,121 @@ public partial class HtmlModule : HtmlModuleBase, IActionable private int WorkflowID; private readonly INavigationManager _navigationManager; + public HtmlModule() { - _navigationManager = DependencyProvider.GetRequiredService(); - } + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets moduleActions is an interface property that returns the module actions collection for the module. + /// + /// + /// + /// ----------------------------------------------------------------------------- + public ModuleActionCollection ModuleActions + { + get + { + // add the Edit Text action + var Actions = new ModuleActionCollection(); + Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + string.Empty, + this.EditUrl(), + false, + SecurityAccessLevel.Edit, + true, + false); - #region "Private Methods" + // get the content + var objHTML = new HtmlTextController(); + var objWorkflow = new WorkflowStateController(); + this.WorkflowID = objHTML.GetWorkflow(this.ModuleId, this.TabId, this.PortalId).Value; - #endregion + HtmlTextInfo objContent = objHTML.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); + if (objContent != null) + { + // if content is in the first state + if (objContent.StateID == objWorkflow.GetFirstWorkflowStateID(this.WorkflowID)) + { + // if not direct publish workflow + if (objWorkflow.GetWorkflowStates(this.WorkflowID).Count > 1) + { + // add publish action + Actions.Add( + this.GetNextActionID(), + Localization.GetString("PublishContent.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + "publish", + "grant.gif", + string.Empty, + true, + SecurityAccessLevel.Edit, + true, + false); + } + } + else + { + // if the content is not in the last state of the workflow then review is required + if (objContent.StateID != objWorkflow.GetLastWorkflowStateID(this.WorkflowID)) + { + // if the user has permissions to review the content + if (WorkflowStatePermissionController.HasWorkflowStatePermission(WorkflowStatePermissionController.GetWorkflowStatePermissions(objContent.StateID), "REVIEW")) + { + // add approve and reject actions + Actions.Add( + this.GetNextActionID(), + Localization.GetString("ApproveContent.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "grant.gif", + this.EditUrl("action", "approve", "Review"), + false, + SecurityAccessLevel.Edit, + true, + false); + Actions.Add( + this.GetNextActionID(), + Localization.GetString("RejectContent.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "deny.gif", + this.EditUrl("action", "reject", "Review"), + false, + SecurityAccessLevel.Edit, + true, + false); + } + } + } + } - #region "Event Handlers" + // add mywork to action menu + Actions.Add( + this.GetNextActionID(), + Localization.GetString("MyWork.Action", this.LocalResourceFile), + "MyWork.Action", + string.Empty, + "view.gif", + this.EditUrl("MyWork"), + false, + SecurityAccessLevel.Edit, + true, + false); + return Actions; + } + } + /// ----------------------------------------------------------------------------- /// - /// Page_Init runs when the control is initialized + /// Page_Init runs when the control is initialized. /// /// /// @@ -60,14 +155,14 @@ public HtmlModule() protected override void OnInit(EventArgs e) { base.OnInit(e); - lblContent.UpdateLabel += lblContent_UpdateLabel; - EditorEnabled = PortalSettings.InlineEditorEnabled; + this.lblContent.UpdateLabel += this.lblContent_UpdateLabel; + this.EditorEnabled = this.PortalSettings.InlineEditorEnabled; try { - WorkflowID = new HtmlTextController().GetWorkflow(ModuleId, TabId, PortalId).Value; + this.WorkflowID = new HtmlTextController().GetWorkflow(this.ModuleId, this.TabId, this.PortalId).Value; - //Add an Action Event Handler to the Skin - AddActionHandler(ModuleAction_Click); + // Add an Action Event Handler to the Skin + this.AddActionHandler(this.ModuleAction_Click); } catch (Exception exc) { @@ -77,7 +172,7 @@ protected override void OnInit(EventArgs e) /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -90,84 +185,84 @@ protected override void OnLoad(EventArgs e) var objHTML = new HtmlTextController(); // edit in place - if (EditorEnabled && IsEditable && PortalSettings.UserMode == PortalSettings.Mode.Edit) + if (this.EditorEnabled && this.IsEditable && this.PortalSettings.UserMode == PortalSettings.Mode.Edit) { - EditorEnabled = true; + this.EditorEnabled = true; } else { - EditorEnabled = false; + this.EditorEnabled = false; } // get content HtmlTextInfo htmlTextInfo = null; - string contentString = ""; + string contentString = string.Empty; - htmlTextInfo = objHTML.GetTopHtmlText(ModuleId, !IsEditable, WorkflowID); + htmlTextInfo = objHTML.GetTopHtmlText(this.ModuleId, !this.IsEditable, this.WorkflowID); - if ((htmlTextInfo != null)) + if (htmlTextInfo != null) { - //don't decode yet (this is done in FormatHtmlText) + // don't decode yet (this is done in FormatHtmlText) contentString = htmlTextInfo.Content; } else { // get default content from resource file - if (PortalSettings.UserMode == PortalSettings.Mode.Edit) + if (this.PortalSettings.UserMode == PortalSettings.Mode.Edit) { - if (EditorEnabled) + if (this.EditorEnabled) { - contentString = Localization.GetString("AddContentFromToolBar.Text", LocalResourceFile); + contentString = Localization.GetString("AddContentFromToolBar.Text", this.LocalResourceFile); } else { - contentString = Localization.GetString("AddContentFromActionMenu.Text", LocalResourceFile); + contentString = Localization.GetString("AddContentFromActionMenu.Text", this.LocalResourceFile); } } else { // hide the module if no content and in view mode - ContainerControl.Visible = false; + this.ContainerControl.Visible = false; } } // token replace - EditorEnabled = EditorEnabled && !Settings.ReplaceTokens; + this.EditorEnabled = this.EditorEnabled && !this.Settings.ReplaceTokens; // localize toolbar - if (EditorEnabled) + if (this.EditorEnabled) { - foreach (DNNToolBarButton button in editorDnnToobar.Buttons) + foreach (DNNToolBarButton button in this.editorDnnToobar.Buttons) { - button.ToolTip = Localization.GetString(button.ToolTip + ".ToolTip", LocalResourceFile); + button.ToolTip = Localization.GetString(button.ToolTip + ".ToolTip", this.LocalResourceFile); } } else { - editorDnnToobar.Visible = false; + this.editorDnnToobar.Visible = false; } - lblContent.EditEnabled = EditorEnabled; + this.lblContent.EditEnabled = this.EditorEnabled; // add content to module - lblContent.Controls.Add(new LiteralControl(HtmlTextController.FormatHtmlText(ModuleId, contentString, Settings, PortalSettings, Page))); + this.lblContent.Controls.Add(new LiteralControl(HtmlTextController.FormatHtmlText(this.ModuleId, contentString, this.Settings, this.PortalSettings, this.Page))); - //set normalCheckBox on the content wrapper to prevent form decoration if its disabled. - if (!Settings.UseDecorate) + // set normalCheckBox on the content wrapper to prevent form decoration if its disabled. + if (!this.Settings.UseDecorate) { - lblContent.CssClass = string.Format("{0} normalCheckBox", lblContent.CssClass); + this.lblContent.CssClass = string.Format("{0} normalCheckBox", this.lblContent.CssClass); } - if (IsPostBack && AJAX.IsEnabled() && AJAX.GetScriptManager(Page).IsInAsyncPostBack) + if (this.IsPostBack && AJAX.IsEnabled() && AJAX.GetScriptManager(this.Page).IsInAsyncPostBack) { var resetScript = $@" if(typeof dnn !== 'undefined' && typeof dnn.controls !== 'undefined' && typeof dnn.controls.controls !== 'undefined'){{ - var control = dnn.controls.controls['{lblContent.ClientID}']; - if(control && control.container !== $get('{lblContent.ClientID}')){{ - dnn.controls.controls['{lblContent.ClientID}'] = null; + var control = dnn.controls.controls['{this.lblContent.ClientID}']; + if(control && control.container !== $get('{this.lblContent.ClientID}')){{ + dnn.controls.controls['{this.lblContent.ClientID}'] = null; }} }};"; - ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), $"ResetHtmlModule{ClientID}", resetScript, true); + ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), $"ResetHtmlModule{this.ClientID}", resetScript, true); } } catch (Exception exc) @@ -178,7 +273,7 @@ protected override void OnLoad(EventArgs e) /// ----------------------------------------------------------------------------- /// - /// lblContent_UpdateLabel allows for inline editing of content + /// lblContent_UpdateLabel allows for inline editing of content. /// /// /// @@ -188,16 +283,16 @@ private void lblContent_UpdateLabel(object source, DNNLabelEditEventArgs e) try { // verify security - if ((!PortalSecurity.Instance.InputFilter(e.Text, PortalSecurity.FilterFlag.NoScripting).Equals(e.Text))) + if (!PortalSecurity.Instance.InputFilter(e.Text, PortalSecurity.FilterFlag.NoScripting).Equals(e.Text)) { throw new SecurityException(); } - else if (EditorEnabled && IsEditable && PortalSettings.UserMode == PortalSettings.Mode.Edit) + else if (this.EditorEnabled && this.IsEditable && this.PortalSettings.UserMode == PortalSettings.Mode.Edit) { // get content var objHTML = new HtmlTextController(); var objWorkflow = new WorkflowStateController(); - HtmlTextInfo objContent = objHTML.GetTopHtmlText(ModuleId, false, WorkflowID); + HtmlTextInfo objContent = objHTML.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); if (objContent == null) { objContent = new HtmlTextInfo(); @@ -205,13 +300,13 @@ private void lblContent_UpdateLabel(object source, DNNLabelEditEventArgs e) } // set content attributes - objContent.ModuleID = ModuleId; - objContent.Content = Server.HtmlEncode(e.Text); - objContent.WorkflowID = WorkflowID; - objContent.StateID = objWorkflow.GetFirstWorkflowStateID(WorkflowID); + objContent.ModuleID = this.ModuleId; + objContent.Content = this.Server.HtmlEncode(e.Text); + objContent.WorkflowID = this.WorkflowID; + objContent.StateID = objWorkflow.GetFirstWorkflowStateID(this.WorkflowID); // save the content - objHTML.UpdateHtmlText(objContent, objHTML.GetMaximumVersionHistory(PortalId)); + objHTML.UpdateHtmlText(objContent, objHTML.GetMaximumVersionHistory(this.PortalId)); } else { @@ -226,7 +321,7 @@ private void lblContent_UpdateLabel(object source, DNNLabelEditEventArgs e) /// ----------------------------------------------------------------------------- /// - /// ModuleAction_Click handles all ModuleAction events raised from the action menu + /// ModuleAction_Click handles all ModuleAction events raised from the action menu. /// /// /// @@ -238,23 +333,23 @@ private void ModuleAction_Click(object sender, ActionEventArgs e) if (e.Action.CommandArgument == "publish") { // verify security - if (IsEditable && PortalSettings.UserMode == PortalSettings.Mode.Edit) + if (this.IsEditable && this.PortalSettings.UserMode == PortalSettings.Mode.Edit) { // get content var objHTML = new HtmlTextController(); - HtmlTextInfo objContent = objHTML.GetTopHtmlText(ModuleId, false, WorkflowID); + HtmlTextInfo objContent = objHTML.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); var objWorkflow = new WorkflowStateController(); - if (objContent.StateID == objWorkflow.GetFirstWorkflowStateID(WorkflowID)) + if (objContent.StateID == objWorkflow.GetFirstWorkflowStateID(this.WorkflowID)) { // publish content objContent.StateID = objWorkflow.GetNextWorkflowStateID(objContent.WorkflowID, objContent.StateID); // save the content - objHTML.UpdateHtmlText(objContent, objHTML.GetMaximumVersionHistory(PortalId)); + objHTML.UpdateHtmlText(objContent, objHTML.GetMaximumVersionHistory(this.PortalId)); // refresh page - Response.Redirect(_navigationManager.NavigateURL(), true); + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } } } @@ -263,113 +358,6 @@ private void ModuleAction_Click(object sender, ActionEventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - - #region "Optional Interfaces" - - /// ----------------------------------------------------------------------------- - /// - /// ModuleActions is an interface property that returns the module actions collection for the module - /// - /// - /// - /// ----------------------------------------------------------------------------- - public ModuleActionCollection ModuleActions - { - get - { - // add the Edit Text action - var Actions = new ModuleActionCollection(); - Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), - ModuleActionType.AddContent, - "", - "", - EditUrl(), - false, - SecurityAccessLevel.Edit, - true, - false); - - // get the content - var objHTML = new HtmlTextController(); - var objWorkflow = new WorkflowStateController(); - WorkflowID = objHTML.GetWorkflow(ModuleId, TabId, PortalId).Value; - - HtmlTextInfo objContent = objHTML.GetTopHtmlText(ModuleId, false, WorkflowID); - if ((objContent != null)) - { - // if content is in the first state - if (objContent.StateID == objWorkflow.GetFirstWorkflowStateID(WorkflowID)) - { - // if not direct publish workflow - if (objWorkflow.GetWorkflowStates(WorkflowID).Count > 1) - { - // add publish action - Actions.Add(GetNextActionID(), - Localization.GetString("PublishContent.Action", LocalResourceFile), - ModuleActionType.AddContent, - "publish", - "grant.gif", - "", - true, - SecurityAccessLevel.Edit, - true, - false); - } - } - else - { - // if the content is not in the last state of the workflow then review is required - if (objContent.StateID != objWorkflow.GetLastWorkflowStateID(WorkflowID)) - { - // if the user has permissions to review the content - if (WorkflowStatePermissionController.HasWorkflowStatePermission(WorkflowStatePermissionController.GetWorkflowStatePermissions(objContent.StateID), "REVIEW")) - { - // add approve and reject actions - Actions.Add(GetNextActionID(), - Localization.GetString("ApproveContent.Action", LocalResourceFile), - ModuleActionType.AddContent, - "", - "grant.gif", - EditUrl("action", "approve", "Review"), - false, - SecurityAccessLevel.Edit, - true, - false); - Actions.Add(GetNextActionID(), - Localization.GetString("RejectContent.Action", LocalResourceFile), - ModuleActionType.AddContent, - "", - "deny.gif", - EditUrl("action", "reject", "Review"), - false, - SecurityAccessLevel.Edit, - true, - false); - } - } - } - } - - // add mywork to action menu - Actions.Add(GetNextActionID(), - Localization.GetString("MyWork.Action", LocalResourceFile), - "MyWork.Action", - "", - "view.gif", - EditUrl("MyWork"), - false, - SecurityAccessLevel.Edit, - true, - false); - - return Actions; - } - } - - #endregion + } } } diff --git a/DNN Platform/Modules/HTML/MyWork.ascx.cs b/DNN Platform/Modules/HTML/MyWork.ascx.cs index 86c2dd8aa68..db11ea0da71 100644 --- a/DNN Platform/Modules/HTML/MyWork.ascx.cs +++ b/DNN Platform/Modules/HTML/MyWork.ascx.cs @@ -1,72 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Html { - + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using Microsoft.Extensions.DependencyInjection; + /// - /// MyWork allows a user to view any outstanding workflow items + /// MyWork allows a user to view any outstanding workflow items. /// /// /// public partial class MyWork : PortalModuleBase { private readonly INavigationManager _navigationManager; + public MyWork() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Protected Methods - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + public string FormatURL(object dataItem) { - var objHtmlTextUser = (HtmlTextUserInfo) dataItem; - return "" + objHtmlTextUser.ModuleTitle + " ( " + objHtmlTextUser.StateName + " )"; - } - - #endregion - - #region Event Handlers - + var objHtmlTextUser = (HtmlTextUserInfo)dataItem; + return "" + objHtmlTextUser.ModuleTitle + " ( " + objHtmlTextUser.StateName + " )"; + } + /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// protected override void OnLoad(EventArgs e) { base.OnLoad(e); - hlCancel.NavigateUrl = _navigationManager.NavigateURL(); + this.hlCancel.NavigateUrl = this._navigationManager.NavigateURL(); try { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { var objHtmlTextUsers = new HtmlTextUserController(); - dgTabs.DataSource = objHtmlTextUsers.GetHtmlTextUser(UserInfo.UserID); - dgTabs.DataBind(); + this.dgTabs.DataSource = objHtmlTextUsers.GetHtmlTextUser(this.UserInfo.UserID); + this.dgTabs.DataBind(); } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - + } } } diff --git a/DNN Platform/Modules/HTML/Settings.ascx.cs b/DNN Platform/Modules/HTML/Settings.ascx.cs index 54fd84fb165..7922315633c 100644 --- a/DNN Platform/Modules/HTML/Settings.ascx.cs +++ b/DNN Platform/Modules/HTML/Settings.ascx.cs @@ -1,81 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Modules.Html.Components; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Html { - + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Modules.Html.Components; + using DotNetNuke.Services.Exceptions; + /// - /// The Settings ModuleSettingsBase is used to manage the - /// settings for the HTML Module + /// The Settings ModuleSettingsBase is used to manage the + /// settings for the HTML Module. /// /// /// public partial class Settings : ModuleSettingsBase { private HtmlModuleSettings _moduleSettings; + private new HtmlModuleSettings ModuleSettings { get { - return _moduleSettings ?? (_moduleSettings = new HtmlModuleSettingsRepository().GetSettings(this.ModuleConfiguration)); + return this._moduleSettings ?? (this._moduleSettings = new HtmlModuleSettingsRepository().GetSettings(this.ModuleConfiguration)); } - } - - - #region Event Handlers - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - cboWorkflow.SelectedIndexChanged += OnWorkflowSelectedIndexChanged; - } - - protected void OnWorkflowSelectedIndexChanged(object sender, EventArgs e) - { - DisplayWorkflowDetails(); - } - - #endregion - - #region Private Methods - - private void DisplayWorkflowDetails() - { - if ((cboWorkflow.SelectedValue != null)) - { - var objWorkflow = new WorkflowStateController(); - var strDescription = ""; - var arrStates = objWorkflow.GetWorkflowStates(int.Parse(cboWorkflow.SelectedValue)); - if (arrStates.Count > 0) - { - foreach (WorkflowStateInfo objState in arrStates) - { - strDescription = strDescription + " >> " + "" + objState.StateName + ""; - } - strDescription = strDescription + "
    " + ((WorkflowStateInfo)arrStates[0]).Description; - } - lblDescription.Text = strDescription; - } - } - - #endregion - - #region Base Method Implementations - + } + /// - /// LoadSettings loads the settings from the Database and displays them + /// LoadSettings loads the settings from the Database and displays them. /// /// /// @@ -83,41 +38,43 @@ public override void LoadSettings() { try { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { var htmlTextController = new HtmlTextController(); var workflowStateController = new WorkflowStateController(); - chkReplaceTokens.Checked = ModuleSettings.ReplaceTokens; - cbDecorate.Checked = ModuleSettings.UseDecorate; + this.chkReplaceTokens.Checked = this.ModuleSettings.ReplaceTokens; + this.cbDecorate.Checked = this.ModuleSettings.UseDecorate; // get workflow/version settings var workflows = new ArrayList(); - foreach (WorkflowStateInfo state in workflowStateController.GetWorkflows(PortalId)) + foreach (WorkflowStateInfo state in workflowStateController.GetWorkflows(this.PortalId)) { if (!state.IsDeleted) { workflows.Add(state); } } - cboWorkflow.DataSource = workflows; - cboWorkflow.DataBind(); - var workflow = htmlTextController.GetWorkflow(ModuleId, TabId, PortalId); - if ((cboWorkflow.FindItemByValue(workflow.Value.ToString()) != null)) + + this.cboWorkflow.DataSource = workflows; + this.cboWorkflow.DataBind(); + var workflow = htmlTextController.GetWorkflow(this.ModuleId, this.TabId, this.PortalId); + if (this.cboWorkflow.FindItemByValue(workflow.Value.ToString()) != null) { - cboWorkflow.FindItemByValue(workflow.Value.ToString()).Selected = true; + this.cboWorkflow.FindItemByValue(workflow.Value.ToString()).Selected = true; } - DisplayWorkflowDetails(); - - - if (rblApplyTo.Items.FindByValue(workflow.Key) != null) + + this.DisplayWorkflowDetails(); + + if (this.rblApplyTo.Items.FindByValue(workflow.Key) != null) { - rblApplyTo.Items.FindByValue(workflow.Key).Selected = true; + this.rblApplyTo.Items.FindByValue(workflow.Key).Selected = true; } - txtSearchDescLength.Text = ModuleSettings.SearchDescLength.ToString(); + this.txtSearchDescLength.Text = this.ModuleSettings.SearchDescLength.ToString(); } - //Module failed to load + + // Module failed to load } catch (Exception exc) { @@ -126,7 +83,7 @@ public override void LoadSettings() } /// - /// UpdateSettings saves the modified settings to the Database + /// UpdateSettings saves the modified settings to the Database. /// public override void UpdateSettings() { @@ -135,16 +92,16 @@ public override void UpdateSettings() var htmlTextController = new HtmlTextController(); // update replace token setting - ModuleSettings.ReplaceTokens = chkReplaceTokens.Checked; - ModuleSettings.UseDecorate = cbDecorate.Checked; - ModuleSettings.SearchDescLength = int.Parse(txtSearchDescLength.Text); + this.ModuleSettings.ReplaceTokens = this.chkReplaceTokens.Checked; + this.ModuleSettings.UseDecorate = this.cbDecorate.Checked; + this.ModuleSettings.SearchDescLength = int.Parse(this.txtSearchDescLength.Text); var repo = new HtmlModuleSettingsRepository(); - repo.SaveSettings(this.ModuleConfiguration, ModuleSettings); + repo.SaveSettings(this.ModuleConfiguration, this.ModuleSettings); // disable module caching if token replace is enabled - if (chkReplaceTokens.Checked) + if (this.chkReplaceTokens.Checked) { - ModuleInfo module = ModuleController.Instance.GetModule(ModuleId, TabId, false); + ModuleInfo module = ModuleController.Instance.GetModule(this.ModuleId, this.TabId, false); if (module.CacheTime > 0) { module.CacheTime = 0; @@ -153,28 +110,57 @@ public override void UpdateSettings() } // update workflow/version settings - switch (rblApplyTo.SelectedValue) + switch (this.rblApplyTo.SelectedValue) { case "Module": - htmlTextController.UpdateWorkflow(ModuleId, rblApplyTo.SelectedValue, Int32.Parse(cboWorkflow.SelectedValue), chkReplace.Checked); + htmlTextController.UpdateWorkflow(this.ModuleId, this.rblApplyTo.SelectedValue, int.Parse(this.cboWorkflow.SelectedValue), this.chkReplace.Checked); break; case "Page": - htmlTextController.UpdateWorkflow(TabId, rblApplyTo.SelectedValue, Int32.Parse(cboWorkflow.SelectedValue), chkReplace.Checked); + htmlTextController.UpdateWorkflow(this.TabId, this.rblApplyTo.SelectedValue, int.Parse(this.cboWorkflow.SelectedValue), this.chkReplace.Checked); break; case "Site": - htmlTextController.UpdateWorkflow(PortalId, rblApplyTo.SelectedValue, Int32.Parse(cboWorkflow.SelectedValue), chkReplace.Checked); + htmlTextController.UpdateWorkflow(this.PortalId, this.rblApplyTo.SelectedValue, int.Parse(this.cboWorkflow.SelectedValue), this.chkReplace.Checked); break; } - //Module failed to load + // Module failed to load } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.cboWorkflow.SelectedIndexChanged += this.OnWorkflowSelectedIndexChanged; } - #endregion - + protected void OnWorkflowSelectedIndexChanged(object sender, EventArgs e) + { + this.DisplayWorkflowDetails(); + } + + private void DisplayWorkflowDetails() + { + if (this.cboWorkflow.SelectedValue != null) + { + var objWorkflow = new WorkflowStateController(); + var strDescription = string.Empty; + var arrStates = objWorkflow.GetWorkflowStates(int.Parse(this.cboWorkflow.SelectedValue)); + if (arrStates.Count > 0) + { + foreach (WorkflowStateInfo objState in arrStates) + { + strDescription = strDescription + " >> " + "" + objState.StateName + ""; + } + + strDescription = strDescription + "
    " + ((WorkflowStateInfo)arrStates[0]).Description; + } + + this.lblDescription.Text = strDescription; + } + } } } diff --git a/DNN Platform/Modules/HTML/dnn_HTML.dnn b/DNN Platform/Modules/HTML/dnn_HTML.dnn index 1ed1a87bb03..c740ae5227b 100644 --- a/DNN Platform/Modules/HTML/dnn_HTML.dnn +++ b/DNN Platform/Modules/HTML/dnn_HTML.dnn @@ -1,6 +1,6 @@  - + HTML This module renders a block of HTML or Text content. The Html/Text module allows authorized users to edit the content either inline or in a separate administration page. Optional tokens can be used that get replaced dynamically during display. All versions of content are stored in the database including the ability to rollback to an older version. DesktopModules\HTML\Images\html.png diff --git a/DNN Platform/Modules/HTML/packages.config b/DNN Platform/Modules/HTML/packages.config index 015e7e36813..4fca05e5f8c 100644 --- a/DNN Platform/Modules/HTML/packages.config +++ b/DNN Platform/Modules/HTML/packages.config @@ -1,5 +1,6 @@ - - - - + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/HtmlEditorManager/AssemblyInfo.cs b/DNN Platform/Modules/HtmlEditorManager/AssemblyInfo.cs index 9b809a52fc1..2e2e812f8b8 100644 --- a/DNN Platform/Modules/HtmlEditorManager/AssemblyInfo.cs +++ b/DNN Platform/Modules/HtmlEditorManager/AssemblyInfo.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke Html Editor Management")] diff --git a/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs b/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs index 5116a2fca5a..f31330f2029 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs @@ -1,38 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; -using System.Text; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Security; -using DotNetNuke.Services.Installer.Packages; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.HtmlEditorManager.Components { using System; + using System.IO; + using System.Text; + using System.Xml; + using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security; using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Installer.Packages; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Log.EventLog; using DotNetNuke.Services.Upgrade; /// - /// Class that contains upgrade procedures + /// Class that contains upgrade procedures. /// public class UpgradeController : IUpgradeable { - /// The module folder location + /// The module folder location. private const string ModuleFolder = "~/DesktopModules/Admin/HtmlEditorManager"; /// Called when a module is upgraded. /// The version. - /// Success if all goes well, otherwise, Failed + /// Success if all goes well, otherwise, Failed. public string UpgradeModule(string version) { try @@ -67,26 +66,30 @@ public string UpgradeModule(string version) break; case "09.01.01": - if (RadEditorProviderInstalled()) + if (this.RadEditorProviderInstalled()) { UpdateRadCfgFiles(); } - if (TelerikAssemblyExists()) + + if (this.TelerikAssemblyExists()) { UpdateWebConfigFile(); } + break; case "09.02.00": - if (TelerikAssemblyExists()) + if (this.TelerikAssemblyExists()) { UpdateTelerikEncryptionKey("Telerik.Web.UI.DialogParametersEncryptionKey"); } + break; case "09.02.01": - if (TelerikAssemblyExists()) + if (this.TelerikAssemblyExists()) { UpdateTelerikEncryptionKey("Telerik.Upload.ConfigurationHashKey"); } + break; } } @@ -101,41 +104,6 @@ public string UpgradeModule(string version) return "Success"; } - /// Gets the module definition identifier. - /// Name of the module. - /// Name of the module definition. - /// The Module Id for the HTML Editor Management module - private int GetModuleDefinitionID(string moduleName, string moduleDefinitionName) - { - // get desktop module - DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, Null.NullInteger); - if (desktopModule == null) - { - return -1; - } - - // get module definition - ModuleDefinitionInfo moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName( - moduleDefinitionName, - desktopModule.DesktopModuleID); - if (moduleDefinition == null) - { - return -1; - } - - return moduleDefinition.ModuleDefID; - } - - private bool RadEditorProviderInstalled() - { - return PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals("DotNetNuke.RadEditorProvider")) != null; - } - - private bool TelerikAssemblyExists() - { - return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); - } - private static void UpdateRadCfgFiles() { var folder = Path.Combine(Globals.ApplicationMapPath, @"DesktopModules\Admin\RadEditorProvider\ConfigFile"); @@ -149,7 +117,10 @@ private static void UpdateRadCfgFiles(string folder, string mask) var files = Directory.GetFiles(folder, mask); foreach (var fname in files) { - if (fname.Contains(".Original.xml")) continue; + if (fname.Contains(".Original.xml")) + { + continue; + } try { @@ -165,7 +136,7 @@ private static void UpdateRadCfgFiles(string folder, string mask) if (filter.InnerText == "*.*") { changed = true; - filter.InnerXml = ""; + filter.InnerXml = string.Empty; foreach (var extension in allowedDocExtensions) { var node = doc.CreateElement("item"); @@ -190,6 +161,41 @@ private static void UpdateRadCfgFiles(string folder, string mask) } } + /// Gets the module definition identifier. + /// Name of the module. + /// Name of the module definition. + /// The Module Id for the HTML Editor Management module. + private int GetModuleDefinitionID(string moduleName, string moduleDefinitionName) + { + // get desktop module + DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, Null.NullInteger); + if (desktopModule == null) + { + return -1; + } + + // get module definition + ModuleDefinitionInfo moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName( + moduleDefinitionName, + desktopModule.DesktopModuleID); + if (moduleDefinition == null) + { + return -1; + } + + return moduleDefinition.ModuleDefID; + } + + private bool RadEditorProviderInstalled() + { + return PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals("DotNetNuke.RadEditorProvider")) != null; + } + + private bool TelerikAssemblyExists() + { + return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); + } + private static string UpdateWebConfigFile() { return UpdateTelerikEncryptionKey("Telerik.AsyncUpload.ConfigurationEncryptionKey"); @@ -199,28 +205,28 @@ private static string UpdateTelerikEncryptionKey(string keyName) { const string defaultValue = "MDEyMzQ1Njc4OUFCQ0RFRjAxMjM0NTY3ODlBQkNERUYwMTIzNDU2Nzg5QUJDREVG"; - var strError = ""; + var strError = string.Empty; var currentKey = Config.GetSetting(keyName); if (string.IsNullOrEmpty(currentKey) || defaultValue.Equals(currentKey) || currentKey.Length < 40) { try { - //open the web.config + // open the web.config var xmlConfig = Config.Load(); - //save the current config file + // save the current config file Config.BackupConfig(); - //create a random Telerik encryption key and add it under + // create a random Telerik encryption key and add it under var newKey = PortalSecurity.Instance.CreateKey(32); newKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(newKey)); Config.AddAppSetting(xmlConfig, keyName, newKey); - //save a copy of the exitsing web.config + // save a copy of the exitsing web.config var backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); strError += Config.Save(xmlConfig, backupFolder + "web_.config") + Environment.NewLine; - //save the web.config + // save the web.config strError += Config.Save(xmlConfig) + Environment.NewLine; } catch (Exception ex) @@ -228,7 +234,8 @@ private static string UpdateTelerikEncryptionKey(string keyName) strError += ex.Message; } } + return strError; } - } + } } diff --git a/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs b/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs index 8de4bdbf740..07a56295685 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.HtmlEditorManager.Views { using DotNetNuke.Entities.Modules; diff --git a/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj b/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj index 6a7d173c7d4..a0f7fe74f8f 100644 --- a/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj +++ b/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj @@ -27,6 +27,7 @@ ..\..\..\..\Evoq.Content\ true + true @@ -116,6 +117,9 @@ + + stylecop.json + Designer @@ -159,6 +163,10 @@ InvalidConfiguration.ascx.cs + + + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) diff --git a/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs b/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs index 3864fe04fb1..ff900ad12e5 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs @@ -1,8 +1,6 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Client.ClientResourceManagement; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.HtmlEditorManager.Presenters { @@ -18,20 +16,21 @@ namespace DotNetNuke.Modules.HtmlEditorManager.Presenters using DotNetNuke.Entities.Users; using DotNetNuke.Modules.HtmlEditorManager.ViewModels; using DotNetNuke.Modules.HtmlEditorManager.Views; + using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Web.Mvp; using DotNetNuke.Web.UI; using DotNetNuke.Web.UI.WebControls; /// - /// Presenter for Provider Configuration + /// Presenter for Provider Configuration. /// [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public class ProviderConfigurationPresenter : ModulePresenter { - /// The HTML editor node + /// The HTML editor node. private const string HtmlEditorNode = "/configuration/dotnetnuke/htmlEditor"; - /// The dot net nuke document + /// The dot net nuke document. private XmlDocument dotnetNukeDocument; /// Initializes a new instance of the class. @@ -73,13 +72,13 @@ private void View_Initialize(object sender, EventArgs e) this.View.Editor.Controls.Add(this.LoadCurrentEditor()); // hack: force DNN to load the Telerik Combobox skin. Needed for the RadEditor provider - //TODO: Remove as the included file path isn't distributed with installs - ClientResourceManager.RegisterStyleSheet(View.Editor.Page, "~/Portals/_default/Skins/_default/WebControlSkin/Default/ComboBox.Default.css"); + // TODO: Remove as the included file path isn't distributed with installs + ClientResourceManager.RegisterStyleSheet(this.View.Editor.Page, "~/Portals/_default/Skins/_default/WebControlSkin/Default/ComboBox.Default.css"); } /// Loads the current editor. /// Name of the editor. - /// The editor based on the current editor settings in the web configuration + /// The editor based on the current editor settings in the web configuration. private Control LoadCurrentEditor(string editorName) { XmlDocument dnnConfiguration = this.DNNConfiguration; @@ -109,7 +108,7 @@ private Control LoadCurrentEditor(string editorName) } /// Loads the current editor. - /// The editor based on the current editor settings in the web configuration + /// The editor based on the current editor settings in the web configuration. private Control LoadCurrentEditor() { return this.LoadCurrentEditor(this.GetSelectedEditor()); @@ -165,7 +164,7 @@ private XmlNode GetHtmlEditorProviderNode(XmlDocument dnnConfiguration) } /// Gets the provider list. - /// A list of the installed providers + /// A list of the installed providers. private List GetAvailableEditors() { var editors = new List(); @@ -193,7 +192,7 @@ private List GetAvailableEditors() } /// Gets the selected editor. - /// The currently configured editor + /// The currently configured editor. private string GetSelectedEditor() { XmlDocument xmlConfig = this.DNNConfiguration; diff --git a/DNN Platform/Modules/HtmlEditorManager/ViewModels/ProviderConfigurationViewModel.cs b/DNN Platform/Modules/HtmlEditorManager/ViewModels/ProviderConfigurationViewModel.cs index b59fe324416..0aaea8c6d26 100644 --- a/DNN Platform/Modules/HtmlEditorManager/ViewModels/ProviderConfigurationViewModel.cs +++ b/DNN Platform/Modules/HtmlEditorManager/ViewModels/ProviderConfigurationViewModel.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.HtmlEditorManager.ViewModels { using System.Collections.Generic; /// - /// Model for provider configuration + /// Model for provider configuration. /// public class ProviderConfigurationViewModel { diff --git a/DNN Platform/Modules/HtmlEditorManager/Views/EditorEventArgs.cs b/DNN Platform/Modules/HtmlEditorManager/Views/EditorEventArgs.cs index f125d979035..a7fac9e345e 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Views/EditorEventArgs.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Views/EditorEventArgs.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.HtmlEditorManager.Views { using System; /// - /// Contains information about the selected editor when saving + /// Contains information about the selected editor when saving. /// public class EditorEventArgs : EventArgs { diff --git a/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs b/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs index 8174b906817..9bd2eedab05 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.HtmlEditorManager.Views { using System; @@ -11,7 +11,7 @@ namespace DotNetNuke.Modules.HtmlEditorManager.Views using DotNetNuke.Web.Mvp; /// - /// Interface for the Provider Configuration View + /// Interface for the Provider Configuration View. /// [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface IProviderConfigurationView : IModuleView diff --git a/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs b/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs index 31ec4cc4fbe..f0e57a3ffe2 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs @@ -1,20 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common; -using DotNetNuke.Entities.Users; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.HtmlEditorManager.Views { using System; using System.Web.UI.WebControls; - using ViewModels; - using Web.Mvp; + using DotNetNuke.Common; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.HtmlEditorManager.ViewModels; + using DotNetNuke.Web.Mvp; /// - /// View control for selecting an HTML provider + /// View control for selecting an HTML provider. /// [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public partial class ProviderConfiguration : ModuleView, IProviderConfigurationView @@ -40,6 +39,11 @@ public PlaceHolder Editor } } + public void Refresh() + { + this.Response.Redirect(this.Request.RawUrl, true); + } + /// Handles the Click event of the SaveButton control. /// The source of the event. /// The instance containing the event data. @@ -56,20 +60,16 @@ protected void ProvidersDropDownList_SelectedIndexChanged(object sender, EventAr this.EditorChanged(this, new EditorEventArgs(this.ProvidersDropDownList.SelectedValue)); } - public void Refresh() - { - Response.Redirect(Request.RawUrl, true); - } - protected override void OnInit(EventArgs e) { var currentUser = UserController.Instance.GetCurrentUserInfo(); if (currentUser == null || !currentUser.IsSuperUser) { - LocalResourceFile = "/DesktopModules/Admin/HtmlEditorManager/App_LocalResources/ProviderConfiguration.ascx.resx"; - Globals.Redirect(Globals.AccessDeniedURL(LocalizeString("CannotManageHTMLEditorProviders")), true); + this.LocalResourceFile = "/DesktopModules/Admin/HtmlEditorManager/App_LocalResources/ProviderConfiguration.ascx.resx"; + Globals.Redirect(Globals.AccessDeniedURL(this.LocalizeString("CannotManageHTMLEditorProviders")), true); } + base.OnInit(e); - } + } } } diff --git a/DNN Platform/Modules/HtmlEditorManager/dnn_HtmlEditorManager.dnn b/DNN Platform/Modules/HtmlEditorManager/dnn_HtmlEditorManager.dnn index 0b19a3adeee..812e0654aa7 100644 --- a/DNN Platform/Modules/HtmlEditorManager/dnn_HtmlEditorManager.dnn +++ b/DNN Platform/Modules/HtmlEditorManager/dnn_HtmlEditorManager.dnn @@ -1,6 +1,6 @@  - + Html Editor Management Images/HtmlEditorManager_Standard_32x32.png A module used to configure toolbar items, behavior, and other options used in the DotNetNuke HtmlEditor Provider. diff --git a/DNN Platform/Modules/HtmlEditorManager/packages.config b/DNN Platform/Modules/HtmlEditorManager/packages.config index db1132d353b..316a1122697 100644 --- a/DNN Platform/Modules/HtmlEditorManager/packages.config +++ b/DNN Platform/Modules/HtmlEditorManager/packages.config @@ -1,4 +1,5 @@  + \ No newline at end of file diff --git a/DNN Platform/Modules/Journal/Components/Constants.cs b/DNN Platform/Modules/Journal/Components/Constants.cs index 338dde19bad..94c4dfd7942 100644 --- a/DNN Platform/Modules/Journal/Components/Constants.cs +++ b/DNN Platform/Modules/Journal/Components/Constants.cs @@ -1,11 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Search.Internals; - -namespace DotNetNuke.Modules.Journal.Components { - public class Constants { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal.Components +{ + using DotNetNuke.Services.Search.Internals; + + public class Constants + { internal const string SharedResourcesPath = "~/DesktopModules/Journal/App_LocalResources/SharedResources.resx"; internal const string DefaultPageSize = "Journal_PageSize"; internal const string AllowFiles = "Journal_AllowFiles"; diff --git a/DNN Platform/Modules/Journal/Components/FeatureController.cs b/DNN Platform/Modules/Journal/Components/FeatureController.cs index 745aa7e3585..455c2a76fff 100644 --- a/DNN Platform/Modules/Journal/Components/FeatureController.cs +++ b/DNN Platform/Modules/Journal/Components/FeatureController.cs @@ -1,8 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal.Components +{ + /* ' Copyright (c) 2011 DotNetNuke Corporation ' All rights reserved. ' @@ -14,109 +16,105 @@ ' */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Journal; -using DotNetNuke.Services.Search.Controllers; -using DotNetNuke.Services.Search.Entities; - -namespace DotNetNuke.Modules.Journal.Components { - + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Journal; + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// - /// The Controller class for Journal + /// The Controller class for Journal. /// /// ----------------------------------------------------------------------------- - - //uncomment the interfaces to add the support. + // uncomment the interfaces to add the support. public class FeatureController : ModuleSearchBase, IModuleSearchResultController { - protected INavigationManager NavigationManager { get; } public FeatureController() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - #region Optional Interfaces - + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + } + + protected INavigationManager NavigationManager { get; } + /// ----------------------------------------------------------------------------- /// - /// ExportModule implements the IPortable ExportModule Interface + /// ExportModule implements the IPortable ExportModule Interface. /// - /// The Id of the module to be exported + /// The Id of the module to be exported. + /// /// ----------------------------------------------------------------------------- - public string ExportModule(int moduleID) { - //string strXML = ""; + public string ExportModule(int moduleID) + { + // string strXML = ""; - //List colJournals = GetJournals(ModuleID); - //if (colJournals.Count != 0) - //{ + // List colJournals = GetJournals(ModuleID); + // if (colJournals.Count != 0) + // { // strXML += ""; - // foreach (JournalInfo objJournal in colJournals) + // foreach (JournalInfo objJournal in colJournals) // { // strXML += ""; // strXML += "" + DotNetNuke.Common.Utilities.XmlUtils.XMLEncode(objJournal.Content) + ""; // strXML += ""; // } // strXML += ""; - //} - - //return strXML; + // } + // return strXML; throw new NotImplementedException("The method or operation is not implemented."); } /// ----------------------------------------------------------------------------- /// - /// ImportModule implements the IPortable ImportModule Interface + /// ImportModule implements the IPortable ImportModule Interface. /// - /// The Id of the module to be imported - /// The content to be imported - /// The version of the module to be imported - /// The Id of the user performing the import + /// The Id of the module to be imported. + /// The content to be imported. + /// The version of the module to be imported. + /// The Id of the user performing the import. /// ----------------------------------------------------------------------------- - public void ImportModule(int moduleID, string content, string version, int userId) { - //XmlNode xmlJournals = DotNetNuke.Common.Globals.GetContent(Content, "Journals"); - //foreach (XmlNode xmlJournal in xmlJournals.SelectNodes("Journal")) - //{ + public void ImportModule(int moduleID, string content, string version, int userId) + { + // XmlNode xmlJournals = DotNetNuke.Common.Globals.GetContent(Content, "Journals"); + // foreach (XmlNode xmlJournal in xmlJournals.SelectNodes("Journal")) + // { // JournalInfo objJournal = new JournalInfo(); // objJournal.ModuleId = ModuleID; // objJournal.Content = xmlJournal.SelectSingleNode("content").InnerText; // objJournal.CreatedByUser = UserID; // AddJournal(objJournal); - //} - + // } throw new NotImplementedException("The method or operation is not implemented."); } /// ----------------------------------------------------------------------------- /// - /// UpgradeModule implements the IUpgradeable Interface + /// UpgradeModule implements the IUpgradeable Interface. /// - /// The current version of the module + /// The current version of the module. + /// /// ----------------------------------------------------------------------------- - public string UpgradeModule(string version) { + public string UpgradeModule(string version) + { throw new NotImplementedException("The method or operation is not implemented."); - } - - #endregion - - #region Implement ModuleSearchBase - + } + public override IList GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDateUtc) { var searchDocuments = new Dictionary(); @@ -134,7 +132,8 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modu while (reader.Read()) { var journalId = Convert.ToInt32(reader["JournalId"]); - //var journalTypeId = reader["JournalTypeId"].ToString(); + + // var journalTypeId = reader["JournalTypeId"].ToString(); var userId = Convert.ToInt32(reader["UserId"]); var dateUpdated = Convert.ToDateTime(reader["DateUpdated"]); var profileId = reader["ProfileId"].ToString(); @@ -163,11 +162,11 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modu AuthorUserId = userId, Keywords = new Dictionary { - {"TabId", tabId}, - {"TabModuleId", tabModuleId}, - {"ProfileId", profileId}, - {"GroupId", groupId} - } + { "TabId", tabId }, + { "TabModuleId", tabModuleId }, + { "ProfileId", profileId }, + { "GroupId", groupId } + }, }; searchDocuments.Add(key, searchDocument); @@ -189,8 +188,8 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modu break; } - //index comments for this journal - AddCommentItems(journalIds, searchDocuments); + // index comments for this journal + this.AddCommentItems(journalIds, searchDocuments); } } } @@ -200,12 +199,8 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modu } return searchDocuments.Values.ToList(); - } - - #endregion - - #region Implement IModuleSearchController - + } + public bool HasViewPermission(SearchResult searchResult) { if (!searchResult.UniqueKey.StartsWith("JI_", StringComparison.InvariantCultureIgnoreCase)) @@ -236,7 +231,7 @@ public bool HasViewPermission(SearchResult searchResult) return true; } - //do not show items in private group + // do not show items in private group if (securityKeys.Any(s => s.StartsWith("R"))) { var groupId = Convert.ToInt32(securityKeys.First(s => s.StartsWith("R")).Substring(1)); @@ -274,29 +269,26 @@ public string GetDocUrl(SearchResult searchResult) var journalId = Convert.ToInt32(searchResult.UniqueKey.Split('_')[1]); var groupId = Convert.ToInt32(searchResult.Keywords["GroupId"]); var tabId = Convert.ToInt32(searchResult.Keywords["TabId"]); - //var tabModuleId = Convert.ToInt32(searchResult.Keywords["TabModuleId"]); + + // var tabModuleId = Convert.ToInt32(searchResult.Keywords["TabModuleId"]); var profileId = Convert.ToInt32(searchResult.Keywords["ProfileId"]); if (groupId > 0 && tabId > 0) { - url = NavigationManager.NavigateURL(tabId, string.Empty, "GroupId=" + groupId, "jid=" + journalId); + url = this.NavigationManager.NavigateURL(tabId, string.Empty, "GroupId=" + groupId, "jid=" + journalId); } else if (tabId == portalSettings.UserTabId) { - url = NavigationManager.NavigateURL(portalSettings.UserTabId, string.Empty, string.Format("userId={0}", profileId), "jid=" + journalId); + url = this.NavigationManager.NavigateURL(portalSettings.UserTabId, string.Empty, string.Format("userId={0}", profileId), "jid=" + journalId); } else { - url = NavigationManager.NavigateURL(tabId, string.Empty, "jid=" + journalId); + url = this.NavigationManager.NavigateURL(tabId, string.Empty, "jid=" + journalId); } return url; - } - - #endregion - - #region Private Methods - + } + private void AddCommentItems(Dictionary journalIds, IDictionary searchDocuments) { var comments = JournalController.Instance.GetCommentsByJournalIds(journalIds.Keys.ToList()); @@ -312,9 +304,6 @@ private void AddCommentItems(Dictionary journalIds, IDictionary[^\]]*)\]\]\>", RegexOptions.Compiled); + + private readonly string url = string.Empty; + private bool isAdmin; + private bool isUnverifiedUser; + + public int JournalId { get; set; } + + protected INavigationManager NavigationManager { get; } + + private PortalSettings PortalSettings { get; set; } + + private int ProfileId { get; set; } + + private int SocialGroupId { get; set; } + + private int ModuleId { get; set; } + + private UserInfo CurrentUser { get; set; } + + private int OwnerPortalId { get; set; } private static readonly Regex TemplateRegex = new Regex("{CanComment}(.*?){/CanComment}", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - public JournalParser(PortalSettings portalSettings, int moduleId, int profileId, int socialGroupId, UserInfo userInfo) + private static readonly Regex BaseUrlRegex = new Regex("\\[BaseUrl\\]", RegexOptions.Compiled | RegexOptions.IgnoreCase); + + public JournalParser(PortalSettings portalSettings, int moduleId, int profileId, int socialGroupId, UserInfo userInfo) { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - PortalSettings = portalSettings; - ModuleId = moduleId; - ProfileId = profileId; - SocialGroupId = socialGroupId; - CurrentUser = userInfo; - url = PortalSettings.DefaultPortalAlias; - OwnerPortalId = portalSettings.PortalId; - ModuleInfo moduleInfo = ModuleController.Instance.GetModule(moduleId, PortalSettings.ActiveTab.TabID, false); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.PortalSettings = portalSettings; + this.ModuleId = moduleId; + this.ProfileId = profileId; + this.SocialGroupId = socialGroupId; + this.CurrentUser = userInfo; + this.url = this.PortalSettings.DefaultPortalAlias; + this.OwnerPortalId = portalSettings.PortalId; + ModuleInfo moduleInfo = ModuleController.Instance.GetModule(moduleId, this.PortalSettings.ActiveTab.TabID, false); if (moduleInfo.OwnerPortalID != portalSettings.PortalId) { - OwnerPortalId = moduleInfo.OwnerPortalID; + this.OwnerPortalId = moduleInfo.OwnerPortalID; } - if (string.IsNullOrEmpty(url)) { - url = HttpContext.Current.Request.Url.Host; + if (string.IsNullOrEmpty(this.url)) + { + this.url = HttpContext.Current.Request.Url.Host; } - url = string.Format("{0}://{1}{2}", - UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request) ? "https" : "http", - url, - !HttpContext.Current.Request.Url.IsDefaultPort && !url.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty); - } - - private static readonly Regex BaseUrlRegex = new Regex("\\[BaseUrl\\]", RegexOptions.Compiled | RegexOptions.IgnoreCase); + + this.url = string.Format( + "{0}://{1}{2}", + UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request) ? "https" : "http", + this.url, + !HttpContext.Current.Request.Url.IsDefaultPort && !this.url.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty); + } - public string GetList(int currentIndex, int rows) + public string GetList(int currentIndex, int rows) { - if (CurrentUser.UserID > 0) { - isAdmin = CurrentUser.IsInRole(PortalSettings.AdministratorRoleName); + if (this.CurrentUser.UserID > 0) + { + this.isAdmin = this.CurrentUser.IsInRole(this.PortalSettings.AdministratorRoleName); } - isUnverifiedUser = !CurrentUser.IsSuperUser && CurrentUser.IsInRole("Unverified Users"); + + this.isUnverifiedUser = !this.CurrentUser.IsSuperUser && this.CurrentUser.IsInRole("Unverified Users"); - var journalControllerInternal = InternalJournalController.Instance; - var sb = new StringBuilder(); + var journalControllerInternal = InternalJournalController.Instance; + var sb = new StringBuilder(); string statusTemplate = Localization.GetString("journal_status", ResxPath); string linkTemplate = Localization.GetString("journal_link", ResxPath); string photoTemplate = Localization.GetString("journal_photo", ResxPath); string fileTemplate = Localization.GetString("journal_file", ResxPath); - statusTemplate = BaseUrlRegex.Replace(statusTemplate, url); - linkTemplate = BaseUrlRegex.Replace(linkTemplate, url); - photoTemplate = BaseUrlRegex.Replace(photoTemplate, url); - fileTemplate = BaseUrlRegex.Replace(fileTemplate, url); + statusTemplate = BaseUrlRegex.Replace(statusTemplate, this.url); + linkTemplate = BaseUrlRegex.Replace(linkTemplate, this.url); + photoTemplate = BaseUrlRegex.Replace(photoTemplate, this.url); + fileTemplate = BaseUrlRegex.Replace(fileTemplate, this.url); string comment = Localization.GetString("comment", ResxPath); IList journalList; - if (JournalId > 0) + if (this.JournalId > 0) { - var journal = JournalController.Instance.GetJournalItem(PortalSettings.PortalId, CurrentUser.UserID, - JournalId, false, false, true); + var journal = JournalController.Instance.GetJournalItem(this.PortalSettings.PortalId, this.CurrentUser.UserID, + this.JournalId, false, false, true); journalList = new List(); if (journal != null) { journalList.Add(journal); } } - else if (ProfileId > 0) + else if (this.ProfileId > 0) { - journalList = journalControllerInternal.GetJournalItemsByProfile(OwnerPortalId, ModuleId, CurrentUser.UserID, ProfileId, currentIndex, rows); + journalList = journalControllerInternal.GetJournalItemsByProfile(this.OwnerPortalId, this.ModuleId, this.CurrentUser.UserID, this.ProfileId, currentIndex, rows); } - else if (SocialGroupId > 0) + else if (this.SocialGroupId > 0) { - journalList = journalControllerInternal.GetJournalItemsByGroup(OwnerPortalId, ModuleId, CurrentUser.UserID, SocialGroupId, currentIndex, rows); + journalList = journalControllerInternal.GetJournalItemsByGroup(this.OwnerPortalId, this.ModuleId, this.CurrentUser.UserID, this.SocialGroupId, currentIndex, rows); } else { - journalList = journalControllerInternal.GetJournalItems(OwnerPortalId, ModuleId, CurrentUser.UserID, currentIndex, rows); + journalList = journalControllerInternal.GetJournalItems(this.OwnerPortalId, this.ModuleId, this.CurrentUser.UserID, currentIndex, rows); } var journalIds = journalList.Select(ji => ji.JournalId).ToList(); IList comments = JournalController.Instance.GetCommentsByJournalIds(journalIds); - foreach (JournalItem ji in journalList) { - string replacement = GetStringReplacement(ji); + foreach (JournalItem ji in journalList) + { + string replacement = this.GetStringReplacement(ji); - string rowTemplate; - if (ji.JournalType == "status") { + string rowTemplate; + if (ji.JournalType == "status") + { rowTemplate = statusTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } else if (ji.JournalType == "link") { + } + else if (ji.JournalType == "link") + { rowTemplate = linkTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } else if (ji.JournalType == "photo") { + } + else if (ji.JournalType == "photo") + { rowTemplate = photoTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } else if (ji.JournalType == "file") { + } + else if (ji.JournalType == "file") + { rowTemplate = fileTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } else { - rowTemplate = GetJournalTemplate(ji.JournalType, ji); + } + else + { + rowTemplate = this.GetJournalTemplate(ji.JournalType, ji); } - var ctl = new JournalControl(); + var ctl = new JournalControl(); bool isLiked = false; - ctl.LikeList = GetLikeListHTML(ji, ref isLiked); - ctl.LikeLink = String.Empty; - ctl.CommentLink = String.Empty; + ctl.LikeList = this.GetLikeListHTML(ji, ref isLiked); + ctl.LikeLink = string.Empty; + ctl.CommentLink = string.Empty; - ctl.AuthorNameLink = "" + ji.JournalAuthor.Name + ""; - if (CurrentUser.UserID > 0 && !isUnverifiedUser) + ctl.AuthorNameLink = "" + ji.JournalAuthor.Name + ""; + if (this.CurrentUser.UserID > 0 && !this.isUnverifiedUser) { if (!ji.CommentsDisabled) { @@ -164,9 +186,9 @@ public string GetList(int currentIndex, int rows) } } - ctl.CommentArea = GetCommentAreaHTML(ji, comments); - ji.TimeFrame = DateUtils.CalculateDateForDisplay(ji.DateCreated); - ji.DateCreated = CurrentUser.LocalTime(ji.DateCreated); + ctl.CommentArea = this.GetCommentAreaHTML(ji, comments); + ji.TimeFrame = DateUtils.CalculateDateForDisplay(ji.DateCreated); + ji.DateCreated = this.CurrentUser.LocalTime(ji.DateCreated); if (ji.Summary != null) { @@ -178,132 +200,173 @@ public string GetList(int currentIndex, int rows) ji.Body = ji.Body.Replace(Environment.NewLine, "
    "); } - var tokenReplace = new JournalItemTokenReplace(ji, ctl); - string tmp = tokenReplace.ReplaceJournalItemTokens(rowTemplate); + var tokenReplace = new JournalItemTokenReplace(ji, ctl); + string tmp = tokenReplace.ReplaceJournalItemTokens(rowTemplate); tmp = tmp.Replace("
    ", "
    "); sb.Append("
    "); - if (isAdmin || CurrentUser.UserID == ji.UserId || (ProfileId > Null.NullInteger && CurrentUser.UserID == ProfileId)) { + if (this.isAdmin || this.CurrentUser.UserID == ji.UserId || (this.ProfileId > Null.NullInteger && this.CurrentUser.UserID == this.ProfileId)) + { sb.Append("
    "); } - sb.Append(tmp); - sb.Append("
    "); - } + + sb.Append(tmp); + sb.Append(""); + } - return Utilities.LocalizeControl(sb.ToString()); - } + return Utilities.LocalizeControl(sb.ToString()); + } internal string GetJournalTemplate(string journalType, JournalItem ji) { string template = Localization.GetString("journal_" + journalType, ResxPath); - if (String.IsNullOrEmpty(template)) + if (string.IsNullOrEmpty(template)) { template = Localization.GetString("journal_generic", ResxPath); } - template = BaseUrlRegex.Replace(template, url); + template = BaseUrlRegex.Replace(template, this.url); template = template.Replace("[journalitem:action]", Localization.GetString(journalType + ".Action", ResxPath)); - var replacement = GetStringReplacement(ji); + var replacement = this.GetStringReplacement(ji); return TemplateRegex.Replace(template, replacement); } - internal string GetLikeListHTML(JournalItem ji, ref bool isLiked) + internal string GetLikeListHTML(JournalItem ji, ref bool isLiked) { - var sb = new StringBuilder(); + var sb = new StringBuilder(); isLiked = false; - if (ji.JournalXML == null) { - return string.Empty; - } - XmlNodeList xLikes = ji.JournalXML.DocumentElement.SelectNodes("//likes/u"); - if (xLikes == null){ - return string.Empty; - } - foreach(XmlNode xLike in xLikes) { - if (Convert.ToInt32(xLike.Attributes["uid"].Value) == CurrentUser.UserID){ - ji.CurrentUserLikes = true; + if (ji.JournalXML == null) + { + return string.Empty; + } + + XmlNodeList xLikes = ji.JournalXML.DocumentElement.SelectNodes("//likes/u"); + if (xLikes == null) + { + return string.Empty; + } + + foreach (XmlNode xLike in xLikes) + { + if (Convert.ToInt32(xLike.Attributes["uid"].Value) == this.CurrentUser.UserID) + { + ji.CurrentUserLikes = true; isLiked = true; - break; - } - - } - int xc = 0; - sb.Append("
    "); - if (xLikes.Count == 1 && ji.CurrentUserLikes) { - sb.Append("{resx:youlikethis}"); - } else if (xLikes.Count > 1) { - if (ji.CurrentUserLikes) { - sb.Append("{resx:you}"); - xc += 1; - } - foreach (XmlNode l in xLikes) { - int userId = Convert.ToInt32(l.Attributes["uid"].Value); - string name = l.Attributes["un"].Value; - if (userId != CurrentUser.UserID) { - if (xc < xLikes.Count - 1 && xc > 0 && xc < 3) { - sb.Append(", "); - } else if (xc > 0 & xc < xLikes.Count & xc < 3) { - sb.Append(" {resx:and} "); - } else if (xc >= 3) { - int diff = (xLikes.Count - xc); - sb.Append(" {resx:and} " + (xLikes.Count - xc).ToString(CultureInfo.InvariantCulture)); - if (diff > 1) { - sb.Append(" {resx:others}"); - } else { - sb.Append(" {resx:other}"); - } - break; - } - sb.AppendFormat("{1}", userId, name); - xc += 1; - } - } - if (xc == 1) { - sb.Append(" {resx:likesthis}"); - } else if (xc>1) { - sb.Append(" {resx:likethis}"); - } - - } else { - foreach (XmlNode l in xLikes) { - int userId = Convert.ToInt32(l.Attributes["uid"].Value); - string name = l.Attributes["un"].Value; - sb.AppendFormat("{1}", userId, name); - xc += 1; - if (xc == xLikes.Count - 1) { - sb.Append(" {resx:and} "); - } else if (xc < xLikes.Count - 1) { - sb.Append(", "); - } - } - if (xc == 1) { - sb.Append(" {resx:likesthis}"); - } else if (xc>1) { - sb.Append(" {resx:likethis}"); - } - } - - - sb.Append("
    "); - return sb.ToString(); - } + break; + } + } + + int xc = 0; + sb.Append("
    "); + if (xLikes.Count == 1 && ji.CurrentUserLikes) + { + sb.Append("{resx:youlikethis}"); + } + else if (xLikes.Count > 1) + { + if (ji.CurrentUserLikes) + { + sb.Append("{resx:you}"); + xc += 1; + } + + foreach (XmlNode l in xLikes) + { + int userId = Convert.ToInt32(l.Attributes["uid"].Value); + string name = l.Attributes["un"].Value; + if (userId != this.CurrentUser.UserID) + { + if (xc < xLikes.Count - 1 && xc > 0 && xc < 3) + { + sb.Append(", "); + } + else if (xc > 0 & xc < xLikes.Count & xc < 3) + { + sb.Append(" {resx:and} "); + } + else if (xc >= 3) + { + int diff = xLikes.Count - xc; + sb.Append(" {resx:and} " + (xLikes.Count - xc).ToString(CultureInfo.InvariantCulture)); + if (diff > 1) + { + sb.Append(" {resx:others}"); + } + else + { + sb.Append(" {resx:other}"); + } + + break; + } + + sb.AppendFormat("{1}", userId, name); + xc += 1; + } + } + + if (xc == 1) + { + sb.Append(" {resx:likesthis}"); + } + else if (xc > 1) + { + sb.Append(" {resx:likethis}"); + } + } + else + { + foreach (XmlNode l in xLikes) + { + int userId = Convert.ToInt32(l.Attributes["uid"].Value); + string name = l.Attributes["un"].Value; + sb.AppendFormat("{1}", userId, name); + xc += 1; + if (xc == xLikes.Count - 1) + { + sb.Append(" {resx:and} "); + } + else if (xc < xLikes.Count - 1) + { + sb.Append(", "); + } + } + + if (xc == 1) + { + sb.Append(" {resx:likesthis}"); + } + else if (xc > 1) + { + sb.Append(" {resx:likethis}"); + } + } + + sb.Append("
    "); + return sb.ToString(); + } - internal string GetCommentAreaHTML(JournalItem journal, IList comments) { + internal string GetCommentAreaHTML(JournalItem journal, IList comments) + { if (journal.CommentsHidden) { return string.Empty; } + var sb = new StringBuilder(); - sb.AppendFormat("
      ", journal.JournalId); - foreach(CommentInfo ci in comments) { - if (ci.JournalId == journal.JournalId) - { - sb.Append(GetCommentRow(journal, ci)); + sb.AppendFormat("
        ", journal.JournalId); + foreach (CommentInfo ci in comments) + { + if (ci.JournalId == journal.JournalId) + { + sb.Append(this.GetCommentRow(journal, ci)); } } - if (CurrentUser.UserID > 0 && !journal.CommentsDisabled) - { - sb.AppendFormat("
      • ", journal.JournalId); - sb.AppendFormat("", journal.JournalId); + + if (this.CurrentUser.UserID > 0 && !journal.CommentsDisabled) + { + sb.AppendFormat("
      • ", journal.JournalId); + sb.AppendFormat("", journal.JournalId); sb.Append("
        {resx:leavecomment}
      • "); sb.Append("
      • "); sb.Append("{resx:comment}
      • "); @@ -313,16 +376,19 @@ internal string GetCommentAreaHTML(JournalItem journal, IList comme return sb.ToString(); } - internal string GetCommentRow(JournalItem journal, CommentInfo comment) { + internal string GetCommentRow(JournalItem journal, CommentInfo comment) + { var sb = new StringBuilder(); string pic = UserController.Instance.GetUserProfilePictureUrl(comment.UserId, 32, 32); sb.AppendFormat("
      • ", comment.CommentId); - if (comment.UserId == CurrentUser.UserID || journal.UserId == CurrentUser.UserID || isAdmin) { + if (comment.UserId == this.CurrentUser.UserID || journal.UserId == this.CurrentUser.UserID || this.isAdmin) + { sb.Append("
        "); } + sb.AppendFormat("", pic); sb.Append("

        "); - string userUrl = NavigationManager.NavigateURL(PortalSettings.UserTabId, string.Empty, new[] { "userId=" + comment.UserId }); + string userUrl = this.NavigationManager.NavigateURL(this.PortalSettings.UserTabId, string.Empty, new[] { "userId=" + comment.UserId }); sb.AppendFormat("{0}", comment.DisplayName, userUrl); if (comment.CommentXML != null && comment.CommentXML.SelectSingleNode("/root/comment") != null) @@ -337,6 +403,7 @@ internal string GetCommentRow(JournalItem journal, CommentInfo comment) { { text = comment.CommentXML.SelectSingleNode("/root/comment").InnerText; } + sb.Append(text.Replace("\n", "
        ")); } else @@ -345,28 +412,28 @@ internal string GetCommentRow(JournalItem journal, CommentInfo comment) { } var timeFrame = DateUtils.CalculateDateForDisplay(comment.DateCreated); - comment.DateCreated = CurrentUser.LocalTime(comment.DateCreated); + comment.DateCreated = this.CurrentUser.LocalTime(comment.DateCreated); sb.AppendFormat("{1}", comment.DateCreated, timeFrame); sb.Append("

        "); sb.Append("
      • "); return sb.ToString(); - } - - #region Private Methods + } + private string GetStringReplacement(JournalItem journalItem) { string replacement = string.Empty; - if (CurrentUser.UserID > 0 && SocialGroupId <= 0 && !isUnverifiedUser) + if (this.CurrentUser.UserID > 0 && this.SocialGroupId <= 0 && !this.isUnverifiedUser) { replacement = "$1"; } - if (CurrentUser.UserID > 0 && journalItem.SocialGroupId > 0 && !isUnverifiedUser) + + if (this.CurrentUser.UserID > 0 && journalItem.SocialGroupId > 0 && !this.isUnverifiedUser) { - replacement = CurrentUser.IsInRole(journalItem.JournalOwner.Name) ? "$1" : string.Empty; + replacement = this.CurrentUser.IsInRole(journalItem.JournalOwner.Name) ? "$1" : string.Empty; } + return replacement; - } - #endregion + } } } diff --git a/DNN Platform/Modules/Journal/Components/LinkInfo.cs b/DNN Platform/Modules/Journal/Components/LinkInfo.cs index 9a89f840ff5..53b68f8e5b2 100644 --- a/DNN Platform/Modules/Journal/Components/LinkInfo.cs +++ b/DNN Platform/Modules/Journal/Components/LinkInfo.cs @@ -1,18 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; - -namespace DotNetNuke.Modules.Journal.Components { - public class LinkInfo { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal.Components +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + public class LinkInfo + { public string URL { get; set; } + public string Title { get; set; } + public string Description { get; set; } + public List Images { get; set; } - } } diff --git a/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs b/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs index 48e9f56779c..803f31f9245 100644 --- a/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs +++ b/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs @@ -1,38 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Globalization; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Common; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Journal.Components { - public class ProfilePicPropertyAccess: IPropertyAccess + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Tokens; + + public class ProfilePicPropertyAccess : IPropertyAccess { private readonly int _userId; - public int Size { get; set; } = 32; - public ProfilePicPropertyAccess(int userId) { - _userId = userId; + this._userId = userId; } + public int Size { get; set; } = 32; + public CacheLevel Cacheability => CacheLevel.notCacheable; public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { - if (propertyName.ToLowerInvariant() == "relativeurl") { int size; - if (int.TryParse(format, out size)) { - Size = size; + if (int.TryParse(format, out size)) + { + this.Size = size; } - return UserController.Instance.GetUserProfilePictureUrl(_userId, Size, Size); + + return UserController.Instance.GetUserProfilePictureUrl(this._userId, this.Size, this.Size); } + propertyNotFound = true; return string.Empty; } diff --git a/DNN Platform/Modules/Journal/Components/Utilities.cs b/DNN Platform/Modules/Journal/Components/Utilities.cs index 7e148ab166e..98e27170a73 100644 --- a/DNN Platform/Modules/Journal/Components/Utilities.cs +++ b/DNN Platform/Modules/Journal/Components/Utilities.cs @@ -1,26 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Net; -using System.Text; -using System.IO; -using System.Drawing; -using System.Text.RegularExpressions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; - -namespace DotNetNuke.Modules.Journal.Components { - public class Utilities { - - private static readonly Regex PageRegex = new Regex("<(title)[^>]*?>((?:.|\\n)*?)", +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal.Components +{ + using System; + using System.Collections.Generic; + using System.Drawing; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + + public class Utilities + { + private static readonly Regex PageRegex = new Regex( + "<(title)[^>]*?>((?:.|\\n)*?)", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); - private static readonly Regex MetaRegex = new Regex(" ]+)\\s*)?)*)/?\\s*>", + private static readonly Regex MetaRegex = new Regex( + " ]+)\\s*)?)*)/?\\s*>", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); private static readonly Regex MetaSubRegex = new Regex( @@ -35,96 +39,164 @@ public class Utilities { private static readonly Regex HtmlTextRegex = new Regex("<(.|\\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - internal static Bitmap GetImageFromURL(string url) { + public static string LocalizeControl(string controlText) + { + string sKey = string.Empty; + string sReplace = string.Empty; + MatchCollection matches = default(MatchCollection); + matches = ResexRegex.Matches(controlText); + foreach (Match match in matches) + { + sKey = match.Value; + sReplace = GetSharedResource(sKey); + + string newValue = match.Value; + if (!string.IsNullOrEmpty(sReplace)) + { + newValue = sReplace; + } + + controlText = controlText.Replace(sKey, newValue); + } + + return controlText; + } + + public static string GetSharedResource(string key) + { + string sValue = key; + sValue = DotNetNuke.Services.Localization.Localization.GetString(key, Constants.SharedResourcesPath); + if (sValue == string.Empty) + { + return key; + } + else + { + return sValue; + } + } + + internal static Bitmap GetImageFromURL(string url) + { string sImgName = string.Empty; System.Net.WebRequest myRequest = default(System.Net.WebRequest); Bitmap bmp = null; - try { + try + { myRequest = System.Net.WebRequest.Create(url); myRequest.Proxy = null; - using (WebResponse myResponse = myRequest.GetResponse()) { - using (Stream myStream = myResponse.GetResponseStream()) { + using (WebResponse myResponse = myRequest.GetResponse()) + { + using (Stream myStream = myResponse.GetResponseStream()) + { string sContentType = myResponse.ContentType; string sExt = string.Empty; - if (sContentType.Contains("png")) { + if (sContentType.Contains("png")) + { sExt = ".png"; - } else if (sContentType.Contains("jpg")) { + } + else if (sContentType.Contains("jpg")) + { sExt = ".jpg"; - } else if (sContentType.Contains("jpeg")) { + } + else if (sContentType.Contains("jpeg")) + { sExt = ".jpg"; - } else if (sContentType.Contains("gif")) { + } + else if (sContentType.Contains("gif")) + { sExt = ".gif"; } - if (!string.IsNullOrEmpty(sExt)) { + + if (!string.IsNullOrEmpty(sExt)) + { bmp = new Bitmap(myStream); } - } } return bmp; - - - } catch { + } + catch + { return null; } - } - static internal string PrepareURL(string url) { + internal static string PrepareURL(string url) + { url = url.Trim(); - if (!url.StartsWith("http")) { + if (!url.StartsWith("http")) + { url = "http://" + url; } - if (url.Contains("https://")) { + + if (url.Contains("https://")) + { url = url.Replace("https://", "http://"); } - if (url.Contains("http://http://")) { + + if (url.Contains("http://http://")) + { url = url.Replace("http://http://", "http://"); } - if (!(url.IndexOf("http://") == 0)) { + + if (!(url.IndexOf("http://") == 0)) + { url = "http://" + url; } + Uri objURI = null; objURI = new Uri(url); return url; - } - static internal LinkInfo GetLinkData(string URL) { + internal static LinkInfo GetLinkData(string URL) + { string sPage = GetPageFromURL(ref URL, string.Empty, string.Empty); LinkInfo link = new LinkInfo(); - if (string.IsNullOrEmpty(sPage)) { + if (string.IsNullOrEmpty(sPage)) + { return link; } + string sTitle = string.Empty; string sDescription = string.Empty; string sImage = string.Empty; - + link.URL = URL; link.Images = new List(); Match m = PageRegex.Match(sPage); - if (m.Success) { + if (m.Success) + { link.Title = m.Groups[2].ToString().Trim(); } - // + MatchCollection matches = default(MatchCollection); matches = MetaRegex.Matches(sPage); int i = 0; - foreach (Match match in matches) { + foreach (Match match in matches) + { string sTempDesc = match.Groups[0].Value; - foreach (Match subM in MetaSubRegex.Matches(sTempDesc)) { - if (subM.Groups[4].Value.Equals("OG:DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) { + foreach (Match subM in MetaSubRegex.Matches(sTempDesc)) + { + if (subM.Groups[4].Value.Equals("OG:DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) + { link.Description = subM.Groups[9].Value; - } else if (subM.Groups[4].Value.Equals("DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) { + } + else if (subM.Groups[4].Value.Equals("DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) + { link.Description = subM.Groups[9].Value; } - if (subM.Groups[4].Value.Equals("OG:TITLE", StringComparison.InvariantCultureIgnoreCase)) { + + if (subM.Groups[4].Value.Equals("OG:TITLE", StringComparison.InvariantCultureIgnoreCase)) + { link.Title = subM.Groups[9].Value; } - - if (subM.Groups[4].Value.Equals("OG:IMAGE", StringComparison.InvariantCultureIgnoreCase)) { + + if (subM.Groups[4].Value.Equals("OG:IMAGE", StringComparison.InvariantCultureIgnoreCase)) + { sImage = subM.Groups[9].Value; ImageInfo img = new ImageInfo(); img.URL = sImage; @@ -133,61 +205,82 @@ static internal LinkInfo GetLinkData(string URL) { } } } - if (!string.IsNullOrEmpty(link.Description)) { + + if (!string.IsNullOrEmpty(link.Description)) + { link.Description = HttpUtility.HtmlDecode(link.Description); link.Description = HttpUtility.UrlDecode(link.Description); link.Description = RemoveHTML(link.Description); } - if (!string.IsNullOrEmpty(link.Title)) { + + if (!string.IsNullOrEmpty(link.Title)) + { link.Title = link.Title.Replace("&", "&"); } + matches = MetaSubRegex2.Matches(sPage); string imgList = string.Empty; string hostUrl = string.Empty; - if (!URL.Contains("http")) { + if (!URL.Contains("http")) + { URL = "http://" + URL; - } + } + Uri uri = new Uri(URL); hostUrl = uri.Host; - if (URL.Contains("https:")) { + if (URL.Contains("https:")) + { hostUrl = "https://" + hostUrl; - } else { + } + else + { hostUrl = "http://" + hostUrl; } - foreach (Match match in matches) { + + foreach (Match match in matches) + { string sImg = match.Groups[5].Value; - if (string.IsNullOrEmpty(sImg)) { + if (string.IsNullOrEmpty(sImg)) + { sImg = match.Groups[8].Value; } - if (!string.IsNullOrEmpty(sImg)) { - if (!sImg.Contains("http")) { + + if (!string.IsNullOrEmpty(sImg)) + { + if (!sImg.Contains("http")) + { sImg = hostUrl + sImg; } - + ImageInfo img = new ImageInfo(); img.URL = sImg; - if (!imgList.Contains(sImg)) { + if (!imgList.Contains(sImg)) + { Bitmap bmp = Utilities.GetImageFromURL(sImg); - if ((bmp != null)) { - if (bmp.Height > 25 & bmp.Height < 500 & bmp.Width > 25 & bmp.Width < 500) { + if (bmp != null) + { + if (bmp.Height > 25 & bmp.Height < 500 & bmp.Width > 25 & bmp.Width < 500) + { link.Images.Add(img); imgList += sImg; i += 1; - } } } - if (i == 10) { - break; + + if (i == 10) + { + break; } } - } + return link; } - static internal string GetPageFromURL(ref string url, string username, string password) { - + + internal static string GetPageFromURL(ref string url, string username, string password) + { url = PrepareURL(url); HttpWebRequest objWebRequest = default(HttpWebRequest); HttpWebResponse objWebResponse = default(HttpWebResponse); @@ -197,19 +290,22 @@ static internal string GetPageFromURL(ref string url, string username, string pa objWebRequest.KeepAlive = false; objWebRequest.Proxy = null; objWebRequest.CookieContainer = cookies; - if (!string.IsNullOrEmpty(username) & !string.IsNullOrEmpty(password)) { + if (!string.IsNullOrEmpty(username) & !string.IsNullOrEmpty(password)) + { NetworkCredential nc = new NetworkCredential(username, password); objWebRequest.Credentials = nc; } + string sHTML = string.Empty; - try { + try + { objWebResponse = (HttpWebResponse)objWebRequest.GetResponse(); Encoding enc = Encoding.UTF8; - - + string contentType = objWebResponse.ContentType; - if ((objWebRequest.HaveResponse == true) & objWebResponse.StatusCode == HttpStatusCode.OK) { + if ((objWebRequest.HaveResponse == true) & objWebResponse.StatusCode == HttpStatusCode.OK) + { objWebResponse.Cookies = objWebRequest.CookieContainer.GetCookies(objWebRequest.RequestUri); using (Stream objStream = objWebResponse.GetResponseStream()) using (StreamReader objStreamReader = new StreamReader(objStream, enc)) @@ -219,40 +315,15 @@ static internal string GetPageFromURL(ref string url, string username, string pa objStream.Close(); } } + objWebResponse.Close(); - } catch (Exception ex) { + } + catch (Exception ex) + { Services.Exceptions.Exceptions.LogException(ex); } - - return sHTML; - } - - public static string LocalizeControl(string controlText) { - string sKey = ""; - string sReplace = ""; - MatchCollection matches = default(MatchCollection); - matches = ResexRegex.Matches(controlText); - foreach (Match match in matches) { - sKey = match.Value; - sReplace = GetSharedResource(sKey); - - string newValue = match.Value; - if (!string.IsNullOrEmpty(sReplace)) { - newValue = sReplace; - } - controlText = controlText.Replace(sKey, newValue); - } - return controlText; - } - public static string GetSharedResource(string key) { - string sValue = key; - sValue = DotNetNuke.Services.Localization.Localization.GetString(key, Constants.SharedResourcesPath); - if (sValue == string.Empty) { - return key; - } else { - return sValue; - } + return sHTML; } public static string RemoveHTML(string sText) @@ -261,6 +332,7 @@ public static string RemoveHTML(string sText) { return string.Empty; } + sText = HttpUtility.HtmlDecode(sText); sText = HttpUtility.UrlDecode(sText); sText = sText.Trim(); @@ -277,7 +349,7 @@ public static string RemoveHTML(string sText) public static bool AreFriends(UserInfo profileUser, UserInfo currentUser) { var friendsRelationShip = RelationshipController.Instance.GetFriendRelationship(profileUser, currentUser); - return (friendsRelationShip != null && friendsRelationShip.Status == RelationshipStatus.Accepted); + return friendsRelationShip != null && friendsRelationShip.Status == RelationshipStatus.Accepted; } } } diff --git a/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj b/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj index 3922bdfe195..160720431cc 100644 --- a/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj +++ b/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj @@ -26,6 +26,7 @@ ..\..\..\..\Evoq.Content\ true + true @@ -189,6 +190,9 @@ + + stylecop.json + Designer @@ -248,6 +252,10 @@ Designer + + + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) diff --git a/DNN Platform/Modules/Journal/Edit.ascx.cs b/DNN Platform/Modules/Journal/Edit.ascx.cs index 6608e85c78b..12098f09d16 100644 --- a/DNN Platform/Modules/Journal/Edit.ascx.cs +++ b/DNN Platform/Modules/Journal/Edit.ascx.cs @@ -1,59 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal +{ + /* ' Copyright (c) 2010 DotNetNuke Corporation ' All rights reserved. -' +' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. -' +' */ -using System; -using DotNetNuke.Services.Exceptions; - -namespace DotNetNuke.Modules.Journal { - + using System; + + using DotNetNuke.Services.Exceptions; + /// ----------------------------------------------------------------------------- /// - /// The EditJournal class is used to manage content + /// The EditJournal class is used to manage content. /// /// ----------------------------------------------------------------------------- - public partial class Edit : JournalModuleBase { - - #region Event Handlers - - override protected void OnInit(EventArgs e) { - InitializeComponent(); + public partial class Edit : JournalModuleBase + { + protected override void OnInit(EventArgs e) + { + this.InitializeComponent(); base.OnInit(e); } - private void InitializeComponent() { + private void InitializeComponent() + { this.Load += new System.EventHandler(this.Page_Load); } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// ----------------------------------------------------------------------------- - private void Page_Load(object sender, System.EventArgs e) { - try { - //Implement your edit logic for your module - - } catch (Exception exc) //Module failed to load + private void Page_Load(object sender, System.EventArgs e) + { + try + { + // Implement your edit logic for your module + } + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - + } } - } diff --git a/DNN Platform/Modules/Journal/FileUploadController.cs b/DNN Platform/Modules/Journal/FileUploadController.cs index 4c46ddd3386..793a5a0e5b7 100644 --- a/DNN Platform/Modules/Journal/FileUploadController.cs +++ b/DNN Platform/Modules/Journal/FileUploadController.cs @@ -1,26 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Web; -using System.Web.Http; -using DotNetNuke.Common; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Journal; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Journal { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net.Http; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Journal; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + using Newtonsoft.Json; + public class FileUploadController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FileUploadController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileUploadController)); + + private static readonly List ImageExtensions = new List { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG", ".ICO", ".SVG" }; [DnnAuthorize] [HttpPost] @@ -30,56 +33,59 @@ public HttpResponseMessage UploadFile() var statuses = new List(); try { - //todo can we eliminate the HttpContext here - UploadWholeFile(HttpContextSource.Current, statuses); + // todo can we eliminate the HttpContext here + this.UploadWholeFile(HttpContextSource.Current, statuses); } catch (Exception exc) { Logger.Error(exc); } - return IframeSafeJson(statuses); + return this.IframeSafeJson(statuses); + } + + private static bool IsImageExtension(string extension) + { + return ImageExtensions.Contains(extension.ToUpper()); } private HttpResponseMessage IframeSafeJson(List statuses) { - //return json but label it as plain text + // return json but label it as plain text return new HttpResponseMessage { - Content = new StringContent(JsonConvert.SerializeObject(statuses)) + Content = new StringContent(JsonConvert.SerializeObject(statuses)), }; } - private static readonly List ImageExtensions = new List { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG", ".ICO", ".SVG" }; - - private static bool IsImageExtension(string extension) - { - return ImageExtensions.Contains(extension.ToUpper()); - } - // Upload entire file private void UploadWholeFile(HttpContextBase context, ICollection statuses) { for (var i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; - if (file == null) continue; - + if (file == null) + { + continue; + } + var fileName = Path.GetFileName(file.FileName); - //fix any filename issues that would cause double escaping exceptions + + // fix any filename issues that would cause double escaping exceptions if (IsImageExtension(Path.GetExtension(fileName))) { - fileName = fileName.Replace("+", ""); + fileName = fileName.Replace("+", string.Empty); } - + try { - var fileInfo = JournalController.Instance.SaveJourmalFile(ActiveModule, UserInfo, fileName, file.InputStream); + var fileInfo = JournalController.Instance.SaveJourmalFile(this.ActiveModule, this.UserInfo, fileName, file.InputStream); var fileIcon = Entities.Icons.IconController.IconURL("Ext" + fileInfo.Extension, "32x32"); if (!File.Exists(context.Server.MapPath(fileIcon))) { fileIcon = Entities.Icons.IconController.IconURL("File", "32x32"); } + statuses.Add(new FilesStatus { success = true, @@ -100,7 +106,7 @@ private void UploadWholeFile(HttpContextBase context, ICollection s { success = false, name = fileName, - message = "File type not allowed." + message = "File type not allowed.", }); } } diff --git a/DNN Platform/Modules/Journal/FilesStatus.cs b/DNN Platform/Modules/Journal/FilesStatus.cs index 4b4c6f85256..3057120dadd 100644 --- a/DNN Platform/Modules/Journal/FilesStatus.cs +++ b/DNN Platform/Modules/Journal/FilesStatus.cs @@ -1,26 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Journal { public class FilesStatus { - // ReSharper disable InconsistentNaming + // ReSharper restore InconsistentNaming + public FilesStatus() + { + } + + // ReSharper disable InconsistentNaming public bool success { get; set; } + public string name { get; set; } + public string extension { get; set; } - public string type { get; set; } - public int size { get; set; } - public string progress { get; set; } - public string url { get; set; } - public string thumbnail_url { get; set; } - public string message { get; set; } + + public string type { get; set; } + + public int size { get; set; } + + public string progress { get; set; } + + public string url { get; set; } + + public string thumbnail_url { get; set; } + + public string message { get; set; } + public int file_id { get; set; } - // ReSharper restore InconsistentNaming - - public FilesStatus () - { - } - } + } } diff --git a/DNN Platform/Modules/Journal/Journal.dnn b/DNN Platform/Modules/Journal/Journal.dnn index 4e0be69a371..1e02cc6a95b 100644 --- a/DNN Platform/Modules/Journal/Journal.dnn +++ b/DNN Platform/Modules/Journal/Journal.dnn @@ -1,6 +1,6 @@ - + Journal DotNetNuke Corporation Journal module DesktopModules/Journal/Images/journal_32X32.png diff --git a/DNN Platform/Modules/Journal/JournalList.cs b/DNN Platform/Modules/Journal/JournalList.cs index 31171c0cda3..5a864c79fcd 100644 --- a/DNN Platform/Modules/Journal/JournalList.cs +++ b/DNN Platform/Modules/Journal/JournalList.cs @@ -1,26 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -namespace DotNetNuke.Modules.Journal { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + [DefaultProperty("Text")] [ToolboxData("<{0}:JournalList runat=server>")] - public class JournalList : WebControl { + public class JournalList : WebControl + { public int PortalId { get; set; } + public int ProfileId { get; set; } + public int SocialGroupId { get; set; } + public int DisplayMode { get; set; } - - protected override void Render(HtmlTextWriter output) { + + protected override void Render(HtmlTextWriter output) + { output.Write("Hello World"); } } diff --git a/DNN Platform/Modules/Journal/JournalListControl.cs b/DNN Platform/Modules/Journal/JournalListControl.cs index c8efa9e1f0a..47c9b57c23c 100644 --- a/DNN Platform/Modules/Journal/JournalListControl.cs +++ b/DNN Platform/Modules/Journal/JournalListControl.cs @@ -1,44 +1,54 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Journal; -using DotNetNuke.Services.Tokens; -using System.IO; -using System.Text.RegularExpressions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Modules.Journal.Components; - -namespace DotNetNuke.Modules.Journal.Controls { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal.Controls +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.IO; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Modules.Journal.Components; + using DotNetNuke.Services.Journal; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Tokens; + [DefaultProperty("Text")] [ToolboxData("<{0}:JournalListControl runat=server>")] - public class JournalListControl : WebControl { - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public PortalSettings portalSettings { - get { + public class JournalListControl : WebControl + { + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public PortalSettings portalSettings + { + get + { return PortalController.Instance.GetCurrentPortalSettings(); } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public UserInfo userInfo { - get { + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public UserInfo userInfo + { + get + { return UserController.Instance.GetCurrentUserInfo(); } } - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int JournalId { get @@ -62,16 +72,18 @@ public int JournalId public int CurrentIndex { get; set; } - protected override void Render(HtmlTextWriter output) + protected override void Render(HtmlTextWriter output) { - if (Enabled) { - if (CurrentIndex < 0) { - CurrentIndex = 0; + if (this.Enabled) + { + if (this.CurrentIndex < 0) + { + this.CurrentIndex = 0; } - JournalParser jp = new JournalParser(portalSettings, ModuleId, ProfileId, SocialGroupId, userInfo){JournalId = JournalId}; - output.Write(jp.GetList(CurrentIndex, PageSize)); + + JournalParser jp = new JournalParser(this.portalSettings, this.ModuleId, this.ProfileId, this.SocialGroupId, this.userInfo) { JournalId = this.JournalId }; + output.Write(jp.GetList(this.CurrentIndex, this.PageSize)); } - } } } diff --git a/DNN Platform/Modules/Journal/JournalModuleBase.cs b/DNN Platform/Modules/Journal/JournalModuleBase.cs index fd876b5acaf..fba7560e6f5 100644 --- a/DNN Platform/Modules/Journal/JournalModuleBase.cs +++ b/DNN Platform/Modules/Journal/JournalModuleBase.cs @@ -1,77 +1,99 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal +{ + /* ' Copyright (c) 2010 DotNetNuke Corporation ' All rights reserved. -' +' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. -' +' */ -using DotNetNuke.Modules.Journal.Components; -using System; -namespace DotNetNuke.Modules.Journal { - - public class JournalModuleBase : DotNetNuke.Entities.Modules.PortalModuleBase { - public enum JournalMode { + using System; + + using DotNetNuke.Modules.Journal.Components; + + public class JournalModuleBase : DotNetNuke.Entities.Modules.PortalModuleBase + { + public enum JournalMode + { Auto = 0, Profile = 1, - Group = 2 + Group = 2, } - public JournalMode FilterMode { - get { - if (!Settings.ContainsKey(Constants.JournalFilterMode)) { + + public JournalMode FilterMode + { + get + { + if (!this.Settings.ContainsKey(Constants.JournalFilterMode)) + { return JournalMode.Auto; - } else { - if (String.IsNullOrEmpty(Settings[Constants.JournalFilterMode].ToString())) { + } + else + { + if (string.IsNullOrEmpty(this.Settings[Constants.JournalFilterMode].ToString())) + { return JournalMode.Auto; - } else { - return (JournalMode)Convert.ToInt16(Settings[Constants.JournalFilterMode].ToString()); + } + else + { + return (JournalMode)Convert.ToInt16(this.Settings[Constants.JournalFilterMode].ToString()); } } - } } - public int GroupId { - get { + + public int GroupId + { + get + { int groupId = -1; - if (!String.IsNullOrEmpty(Request.QueryString["groupid"])) { - if (Int32.TryParse(Request.QueryString["groupid"], out groupId)) { + if (!string.IsNullOrEmpty(this.Request.QueryString["groupid"])) + { + if (int.TryParse(this.Request.QueryString["groupid"], out groupId)) + { return groupId; - } else { + } + else + { return -1; } - } else { + } + else + { return -1; } } } + public bool EditorEnabled { get { - if (!Settings.ContainsKey(Constants.JournalEditorEnabled)) + if (!this.Settings.ContainsKey(Constants.JournalEditorEnabled)) { return true; - } else + } + else { - if (String.IsNullOrEmpty(Settings[Constants.JournalEditorEnabled].ToString())) + if (string.IsNullOrEmpty(this.Settings[Constants.JournalEditorEnabled].ToString())) { return true; - } else + } + else { - return (bool)Convert.ToBoolean(Settings[Constants.JournalEditorEnabled].ToString()); + return (bool)Convert.ToBoolean(this.Settings[Constants.JournalEditorEnabled].ToString()); } } } } - } - } diff --git a/DNN Platform/Modules/Journal/JournalRouteMapper.cs b/DNN Platform/Modules/Journal/JournalRouteMapper.cs index f651e674ccc..0dc30721cea 100644 --- a/DNN Platform/Modules/Journal/JournalRouteMapper.cs +++ b/DNN Platform/Modules/Journal/JournalRouteMapper.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Journal { + using System; + + using DotNetNuke.Web.Api; + public class JournalRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) diff --git a/DNN Platform/Modules/Journal/JournalSettingsBase.cs b/DNN Platform/Modules/Journal/JournalSettingsBase.cs index 7ac910ff524..275e1a6cadd 100644 --- a/DNN Platform/Modules/Journal/JournalSettingsBase.cs +++ b/DNN Platform/Modules/Journal/JournalSettingsBase.cs @@ -1,27 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal +{ + /* ' Copyright (c) 2011 DotNetNuke Corporation ' All rights reserved. -' +' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. -' +' */ -using DotNetNuke.Entities.Modules; - -namespace DotNetNuke.Modules.Journal { - - public class JournalSettingsBase : ModuleSettingsBase { - - - + using DotNetNuke.Entities.Modules; + + public class JournalSettingsBase : ModuleSettingsBase + { } - } diff --git a/DNN Platform/Modules/Journal/MyFiles.ascx.cs b/DNN Platform/Modules/Journal/MyFiles.ascx.cs index 5f41804eb23..13c18e49624 100644 --- a/DNN Platform/Modules/Journal/MyFiles.ascx.cs +++ b/DNN Platform/Modules/Journal/MyFiles.ascx.cs @@ -1,53 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Localization; -using DotNetNuke.Entities.Host; - -namespace DotNetNuke.Modules.Journal { - public partial class MyFiles : PortalModuleBase { - override protected void OnInit(EventArgs e) { - InitializeComponent(); +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal +{ + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + + public partial class MyFiles : PortalModuleBase + { + protected override void OnInit(EventArgs e) + { + this.InitializeComponent(); base.OnInit(e); } - - private void InitializeComponent() { - this.Load += new System.EventHandler(this.Page_Load); - btnUp.Click += new System.EventHandler(this.btnUp_Upload); - } - protected void Page_Load(object sender, EventArgs e) { - + + protected void Page_Load(object sender, EventArgs e) + { } - protected void btnUp_Upload(object sender, EventArgs e) { + + protected void btnUp_Upload(object sender, EventArgs e) + { var folderManager = FolderManager.Instance; - var userFolder = folderManager.GetUserFolder(UserInfo); + var userFolder = folderManager.GetUserFolder(this.UserInfo); string message = string.Empty; IFileInfo fi = null; - try { - fi = FileManager.Instance.AddFile(userFolder, fileUp.PostedFile.FileName, fileUp.PostedFile.InputStream, true); - } catch (PermissionsNotMetException) { + try + { + fi = FileManager.Instance.AddFile(userFolder, this.fileUp.PostedFile.FileName, this.fileUp.PostedFile.InputStream, true); + } + catch (PermissionsNotMetException) + { message = string.Format(Localization.GetString("InsufficientFolderPermission"), userFolder.FolderPath); - - } catch (NoSpaceAvailableException) { - message = string.Format(Localization.GetString("DiskSpaceExceeded"), fileUp.PostedFile.FileName); - } catch (InvalidFileExtensionException) { - message = string.Format(Localization.GetString("RestrictedFileType"), fileUp.PostedFile.FileName, Host.AllowedExtensionWhitelist.ToDisplayString()); - } catch { - message = string.Format(Localization.GetString("SaveFileError"), fileUp.PostedFile.FileName); + } + catch (NoSpaceAvailableException) + { + message = string.Format(Localization.GetString("DiskSpaceExceeded"), this.fileUp.PostedFile.FileName); + } + catch (InvalidFileExtensionException) + { + message = string.Format(Localization.GetString("RestrictedFileType"), this.fileUp.PostedFile.FileName, Host.AllowedExtensionWhitelist.ToDisplayString()); + } + catch + { + message = string.Format(Localization.GetString("SaveFileError"), this.fileUp.PostedFile.FileName); } - if (String.IsNullOrEmpty(message) && fi != null) { - litOut.Text = ""; - - } else { - litOut.Text = message; + + if (string.IsNullOrEmpty(message) && fi != null) + { + this.litOut.Text = ""; + } + else + { + this.litOut.Text = message; } } + + private void InitializeComponent() + { + this.Load += new System.EventHandler(this.Page_Load); + this.btnUp.Click += new System.EventHandler(this.btnUp_Upload); + } } } diff --git a/DNN Platform/Modules/Journal/NotificationServicesController.cs b/DNN Platform/Modules/Journal/NotificationServicesController.cs index 2c417bcf0e7..1c9a434d04c 100644 --- a/DNN Platform/Modules/Journal/NotificationServicesController.cs +++ b/DNN Platform/Modules/Journal/NotificationServicesController.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Services.Journal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; - -using System; -using System.Net; -using System.Net.Http; -using System.Web.Http; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Journal { + using System; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Services.Journal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] [ValidateAntiForgeryToken] public class NotificationServicesController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(NotificationServicesController)); - public class NotificationDTO - { - public int NotificationId { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage ViewJournal(NotificationDTO postData) @@ -37,21 +32,21 @@ public HttpResponseMessage ViewJournal(NotificationDTO postData) { var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - if(notification != null && notification.Context != null && notification.Context.Contains("_")) + if (notification != null && notification.Context != null && notification.Context.Contains("_")) { - //Dismiss the notification - NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, UserInfo.UserID); + // Dismiss the notification + NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, this.UserInfo.UserID); var context = notification.Context.Split('_'); var userId = Convert.ToInt32(context[0]); var journalId = Convert.ToInt32(context[1]); - var ji = JournalController.Instance.GetJournalItem(PortalSettings.PortalId, userId, journalId); + var ji = JournalController.Instance.GetJournalItem(this.PortalSettings.PortalId, userId, journalId); if (ji.ProfileId != Null.NullInteger) { - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(ji.ProfileId) }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(ji.ProfileId) }); } - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(userId) }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(userId) }); } } catch (Exception exc) @@ -59,8 +54,12 @@ public HttpResponseMessage ViewJournal(NotificationDTO postData) Logger.Error(exc); } - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } + public class NotificationDTO + { + public int NotificationId { get; set; } + } } } diff --git a/DNN Platform/Modules/Journal/Properties/AssemblyInfo.cs b/DNN Platform/Modules/Journal/Properties/AssemblyInfo.cs index 2767df8ca3d..6abf1ec40de 100644 --- a/DNN Platform/Modules/Journal/Properties/AssemblyInfo.cs +++ b/DNN Platform/Modules/Journal/Properties/AssemblyInfo.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System; using System.Reflection; using System.Runtime.InteropServices; -// -// General Information about an assembly is controlled through the following +// 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. // diff --git a/DNN Platform/Modules/Journal/ServicesController.cs b/DNN Platform/Modules/Journal/ServicesController.cs index 50df58391b7..8beeb59b4c3 100644 --- a/DNN Platform/Modules/Journal/ServicesController.cs +++ b/DNN Platform/Modules/Journal/ServicesController.cs @@ -1,61 +1,108 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Http; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Instrumentation; -using DotNetNuke.Modules.Journal.Components; -using DotNetNuke.Security; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Journal; -using DotNetNuke.Services.Journal.Internal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Journal { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Http; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.Journal.Components; + using DotNetNuke.Security; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Journal; + using DotNetNuke.Services.Journal.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] [SupportedModules("Journal")] public class ServicesController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (ServicesController)); - private const int MentionNotificationLength = 100; private const string MentionNotificationSuffix = "..."; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServicesController)); private const string MentionIdentityChar = "@"; - private static readonly string [] AcceptedFileExtensions = { "jpg", "png", "gif", "jpe", "jpeg", "tiff", "bmp" }; + private static readonly string[] AcceptedFileExtensions = { "jpg", "png", "gif", "jpe", "jpeg", "tiff", "bmp" }; - #region Public Methods - public class CreateDTO + [HttpPost] + [ValidateAntiForgeryToken] + [DnnAuthorize(DenyRoles = "Unverified Users")] + public HttpResponseMessage Create(CreateDTO postData) { - public string Text { get; set; } - public int ProfileId { get; set; } - public string JournalType { get; set; } - public string ItemData { get; set; } - public string SecuritySet { get; set; } - public int GroupId { get; set; } - public IList Mentions { get; set; } + try + { + int userId = this.UserInfo.UserID; + IDictionary mentionedUsers = new Dictionary(); + + if (postData.ProfileId == -1) + { + postData.ProfileId = userId; + } + + this.checkProfileAccess(postData.ProfileId, this.UserInfo); + + this.checkGroupAccess(postData); + + var journalItem = this.prepareJournalItem(postData, mentionedUsers); + + JournalController.Instance.SaveJournalItem(journalItem, this.ActiveModule); + + var originalSummary = journalItem.Summary; + this.SendMentionNotifications(mentionedUsers, journalItem, originalSummary); + + return this.Request.CreateResponse(HttpStatusCode.OK, journalItem); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } } - public class MentionDTO + [HttpPost] + [ValidateAntiForgeryToken] + [DnnAuthorize(DenyRoles = "Unverified Users")] + public HttpResponseMessage Delete(JournalIdDTO postData) { - public string DisplayName { get; set; } - public int UserId { get; set; } + try + { + var jc = JournalController.Instance; + var ji = jc.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); + + if (ji == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); + } + + if (ji.UserId == this.UserInfo.UserID || ji.ProfileId == this.UserInfo.UserID || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) + { + jc.DeleteJournalItem(this.PortalSettings.PortalId, this.UserInfo.UserID, postData.JournalId); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + + return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } } private static bool IsImageFile(string relativePath) @@ -66,14 +113,15 @@ private static bool IsImageFile(string relativePath) } if (relativePath.Contains("?")) - { - relativePath = relativePath.Substring(0, - relativePath.IndexOf("?", StringComparison.InvariantCultureIgnoreCase)); - } - - - var extension = relativePath.Substring(relativePath.LastIndexOf(".", - StringComparison.Ordinal) + 1).ToLowerInvariant(); + { + relativePath = relativePath.Substring( + 0, + relativePath.IndexOf("?", StringComparison.InvariantCultureIgnoreCase)); + } + + var extension = relativePath.Substring(relativePath.LastIndexOf( + ".", + StringComparison.Ordinal) + 1).ToLowerInvariant(); return AcceptedFileExtensions.Contains(extension); } @@ -81,39 +129,75 @@ private static bool IsAllowedLink(string url) { return !string.IsNullOrEmpty(url) && !url.Contains("//"); } + + public class CreateDTO + { + public string Text { get; set; } + + public int ProfileId { get; set; } + + public string JournalType { get; set; } + + public string ItemData { get; set; } + + public string SecuritySet { get; set; } + + public int GroupId { get; set; } + + public IList Mentions { get; set; } + } + + public class MentionDTO + { + public string DisplayName { get; set; } + + public int UserId { get; set; } + } [HttpPost] [ValidateAntiForgeryToken] - [DnnAuthorize(DenyRoles = "Unverified Users")] - public HttpResponseMessage Create(CreateDTO postData) + [DnnAuthorize(DenyRoles = "Unverified Users")] + public HttpResponseMessage SoftDelete(JournalIdDTO postData) { try { - int userId = UserInfo.UserID; - IDictionary mentionedUsers = new Dictionary(); + var jc = JournalController.Instance; + var ji = jc.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); - if (postData.ProfileId == -1) + if (ji == null) { - postData.ProfileId = userId; + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); } - checkProfileAccess(postData.ProfileId, UserInfo); - - checkGroupAccess(postData); - - var journalItem = prepareJournalItem(postData, mentionedUsers); - - JournalController.Instance.SaveJournalItem(journalItem, ActiveModule); + if (ji.UserId == this.UserInfo.UserID || ji.ProfileId == this.UserInfo.UserID || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) + { + jc.SoftDeleteJournalItem(this.PortalSettings.PortalId, this.UserInfo.UserID, postData.JournalId); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } - var originalSummary = journalItem.Summary; - SendMentionNotifications(mentionedUsers, journalItem, originalSummary); + return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } - return Request.CreateResponse(HttpStatusCode.OK, journalItem); + [HttpPost] + [ValidateAntiForgeryToken] + [DnnAuthorize] + public HttpResponseMessage PreviewUrl(PreviewDTO postData) + { + try + { + var link = Utilities.GetLinkData(postData.Url); + return this.Request.CreateResponse(HttpStatusCode.OK, link); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -122,8 +206,8 @@ private void checkProfileAccess(int profileId, UserInfo currentUser) { if (profileId != currentUser.UserID) { - var profileUser = UserController.Instance.GetUser(PortalSettings.PortalId, profileId); - if (profileUser == null || (!UserInfo.IsInRole(PortalSettings.AdministratorRoleName) && !Utilities.AreFriends(profileUser, currentUser))) + var profileUser = UserController.Instance.GetUser(this.PortalSettings.PortalId, profileId); + if (profileUser == null || (!this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) && !Utilities.AreFriends(profileUser, currentUser))) { throw new ArgumentException("you have no permission to post journal on current profile page."); } @@ -136,10 +220,10 @@ private void checkGroupAccess(CreateDTO postData) { postData.ProfileId = -1; - RoleInfo roleInfo = RoleController.Instance.GetRoleById(ActiveModule.OwnerPortalID, postData.GroupId); + RoleInfo roleInfo = RoleController.Instance.GetRoleById(this.ActiveModule.OwnerPortalID, postData.GroupId); if (roleInfo != null) { - if (!UserInfo.IsInRole(PortalSettings.AdministratorRoleName) && !UserInfo.IsInRole(roleInfo.RoleName)) + if (!this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) && !this.UserInfo.IsInRole(roleInfo.RoleName)) { throw new ArgumentException("you have no permission to post journal on current group."); } @@ -172,12 +256,12 @@ private JournalItem prepareJournalItem(CreateDTO postData, IDictionary 2000) { @@ -224,7 +308,7 @@ private JournalItem prepareJournalItem(CreateDTO postData, IDictionary Mentions { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] [DnnAuthorize(DenyRoles = "Unverified Users")] @@ -397,30 +382,40 @@ public HttpResponseMessage CommentSave(CommentSaveDTO postData) IDictionary mentionedUsers = new Dictionary(); var originalComment = comment; - comment = ParseMentions(comment, postData.Mentions, ref mentionedUsers); + comment = this.ParseMentions(comment, postData.Mentions, ref mentionedUsers); var ci = new CommentInfo { JournalId = postData.JournalId, Comment = comment }; - ci.UserId = UserInfo.UserID; - ci.DisplayName = UserInfo.DisplayName; + ci.UserId = this.UserInfo.UserID; + ci.DisplayName = this.UserInfo.DisplayName; JournalController.Instance.SaveComment(ci); - var ji = JournalController.Instance.GetJournalItem(ActiveModule.OwnerPortalID, UserInfo.UserID, postData.JournalId); - var jp = new JournalParser(PortalSettings, ActiveModule.ModuleID, ji.ProfileId, -1, UserInfo); + var ji = JournalController.Instance.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); + var jp = new JournalParser(this.PortalSettings, this.ActiveModule.ModuleID, ji.ProfileId, -1, this.UserInfo); - SendMentionNotifications(mentionedUsers, ji, originalComment, "Comment"); + this.SendMentionNotifications(mentionedUsers, ji, originalComment, "Comment"); - return Request.CreateResponse(HttpStatusCode.OK, jp.GetCommentRow(ji, ci), "text/html"); + return this.Request.CreateResponse(HttpStatusCode.OK, jp.GetCommentRow(ji, ci), "text/html"); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } + + public class PreviewDTO + { + public string Url { get; set; } + } - public class CommentDeleteDTO + public class GetListForProfileDTO { - public int JournalId { get; set; } - public int CommentId { get; set; } + public int ProfileId { get; set; } + + public int GroupId { get; set; } + + public int RowIndex { get; set; } + + public int MaxRows { get; set; } } [HttpPost] @@ -433,84 +428,70 @@ public HttpResponseMessage CommentDelete(CommentDeleteDTO postData) var ci = JournalController.Instance.GetComment(postData.CommentId); if (ci == null) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "delete failed"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "delete failed"); } - var ji = JournalController.Instance.GetJournalItem(ActiveModule.OwnerPortalID, UserInfo.UserID, postData.JournalId); + var ji = JournalController.Instance.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); if (ji == null) { - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); } - if (ci.UserId == UserInfo.UserID || ji.UserId == UserInfo.UserID || UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) + if (ci.UserId == this.UserInfo.UserID || ji.UserId == this.UserInfo.UserID || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) { JournalController.Instance.DeleteComment(postData.JournalId, postData.CommentId); - return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); + return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } - public class SuggestDTO + [HttpGet] + [DnnAuthorize(DenyRoles = "Unverified Users")] + public HttpResponseMessage GetSuggestions(string keyword) { - public string displayName { get; set; } - public int userId { get; set; } - public string avatar { get; set; } - public string key { get; set; } - } - - [HttpGet] - [DnnAuthorize(DenyRoles = "Unverified Users")] - public HttpResponseMessage GetSuggestions(string keyword) - { - try - { + try + { var findedUsers = new List(); - var relations = RelationshipController.Instance.GetUserRelationships(UserInfo); - foreach (var ur in relations) - { - var targetUserId = ur.UserId == UserInfo.UserID ? ur.RelatedUserId : ur.UserId; - var targetUser = UserController.GetUserById(PortalSettings.PortalId, targetUserId); - var relationship = RelationshipController.Instance.GetRelationship(ur.RelationshipId); - if (ur.Status == RelationshipStatus.Accepted && targetUser != null - && ((relationship.RelationshipTypeId == (int)DefaultRelationshipTypes.Followers && ur.RelatedUserId == UserInfo.UserID) - || relationship.RelationshipTypeId == (int)DefaultRelationshipTypes.Friends - ) - && (targetUser.DisplayName.ToLowerInvariant().Contains(keyword.ToLowerInvariant()) - || targetUser.DisplayName.ToLowerInvariant().Contains(keyword.Replace("-", " ").ToLowerInvariant()) - ) - && findedUsers.All(s => s.userId != targetUser.UserID) - ) - { - findedUsers.Add(new SuggestDTO - { - displayName = targetUser.DisplayName.Replace(" ", "-"), - userId = targetUser.UserID, - avatar = targetUser.Profile.PhotoURL, - key = keyword - }); - } - } - - return Request.CreateResponse(HttpStatusCode.OK, findedUsers.Cast().Take(5)); - } - catch (Exception exc) - { - Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - #endregion + var relations = RelationshipController.Instance.GetUserRelationships(this.UserInfo); + foreach (var ur in relations) + { + var targetUserId = ur.UserId == this.UserInfo.UserID ? ur.RelatedUserId : ur.UserId; + var targetUser = UserController.GetUserById(this.PortalSettings.PortalId, targetUserId); + var relationship = RelationshipController.Instance.GetRelationship(ur.RelationshipId); + if (ur.Status == RelationshipStatus.Accepted && targetUser != null + && ((relationship.RelationshipTypeId == (int)DefaultRelationshipTypes.Followers && ur.RelatedUserId == this.UserInfo.UserID) + || relationship.RelationshipTypeId == (int)DefaultRelationshipTypes.Friends) + && (targetUser.DisplayName.ToLowerInvariant().Contains(keyword.ToLowerInvariant()) + || targetUser.DisplayName.ToLowerInvariant().Contains(keyword.Replace("-", " ").ToLowerInvariant())) + && findedUsers.All(s => s.userId != targetUser.UserID)) + { + findedUsers.Add(new SuggestDTO + { + displayName = targetUser.DisplayName.Replace(" ", "-"), + userId = targetUser.UserID, + avatar = targetUser.Profile.PhotoURL, + key = keyword, + }); + } + } - #region Private Methods + return this.Request.CreateResponse(HttpStatusCode.OK, findedUsers.Cast().Take(5)); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + private string ParseMentions(string content, IList mentions, ref IDictionary mentionedUsers) { if (mentions == null || mentions.Count == 0) @@ -520,29 +501,31 @@ private string ParseMentions(string content, IList mentions, ref IDi foreach (var mention in mentions) { - var user = UserController.GetUserById(PortalSettings.PortalId, mention.UserId); + var user = UserController.GetUserById(this.PortalSettings.PortalId, mention.UserId); if (user != null) { - var relationship = RelationshipController.Instance.GetFollowingRelationship(UserInfo, user) ?? - RelationshipController.Instance.GetFriendRelationship(UserInfo, user); + var relationship = RelationshipController.Instance.GetFollowingRelationship(this.UserInfo, user) ?? + RelationshipController.Instance.GetFriendRelationship(this.UserInfo, user); if (relationship != null && relationship.Status == RelationshipStatus.Accepted) { - var userLink = string.Format("{1}", - Globals.UserProfileURL(user.UserID), - MentionIdentityChar + user.DisplayName); + var userLink = string.Format( + "{1}", + Globals.UserProfileURL(user.UserID), + MentionIdentityChar + user.DisplayName); content = content.Replace(MentionIdentityChar + mention.DisplayName, userLink); mentionedUsers.Add(mention.DisplayName, user); } } } + return content; } private void SendMentionNotifications(IDictionary mentionedUsers, JournalItem item, string originalSummary, string type = "Post") { - //send notification to the mention users + // send notification to the mention users var subjectTemplate = Utilities.GetSharedResource("Notification_Mention.Subject"); var bodyTemplate = Utilities.GetSharedResource("Notification_Mention.Body"); var mentionType = Utilities.GetSharedResource("Notification_MentionType_" + type); @@ -556,20 +539,48 @@ private void SendMentionNotifications(IDictionary mentionedUse { mentionText = mentionText.Substring(0, MentionNotificationLength) + MentionNotificationSuffix; } + var notification = new Notification { - Subject = string.Format(subjectTemplate, UserInfo.DisplayName, mentionType), + Subject = string.Format(subjectTemplate, this.UserInfo.DisplayName, mentionType), Body = string.Format(bodyTemplate, mentionText), NotificationTypeID = notificationType.NotificationTypeId, - SenderUserID = UserInfo.UserID, + SenderUserID = this.UserInfo.UserID, IncludeDismissAction = true, - Context = string.Format("{0}_{1}", UserInfo.UserID, item.JournalId) + Context = string.Format("{0}_{1}", this.UserInfo.UserID, item.JournalId), }; - Services.Social.Notifications.NotificationsController.Instance.SendNotification(notification, PortalSettings.PortalId, null, new List { mentionUser }); + Services.Social.Notifications.NotificationsController.Instance.SendNotification(notification, this.PortalSettings.PortalId, null, new List { mentionUser }); } } + public class CommentSaveDTO + { + public int JournalId { get; set; } + + public string Comment { get; set; } + + public IList Mentions { get; set; } + } + + public class CommentDeleteDTO + { + public int JournalId { get; set; } + + public int CommentId { get; set; } + } + + public class SuggestDTO + { + public string displayName { get; set; } + + public int userId { get; set; } + + public string avatar { get; set; } + + public string key { get; set; } + } + private bool IsCurrentUserFile(IFileInfo file) { if (file == null) @@ -577,7 +588,7 @@ private bool IsCurrentUserFile(IFileInfo file) return false; } - var userFolders = GetUserFolders(); + var userFolders = this.GetUserFolders(); return userFolders.Any(f => file.FolderId == f.FolderID); } @@ -586,9 +597,9 @@ private IList GetUserFolders() { var folders = new List(); - var userFolder = FolderManager.Instance.GetUserFolder(UserInfo); + var userFolder = FolderManager.Instance.GetUserFolder(this.UserInfo); folders.Add(userFolder); - folders.AddRange(GetSubFolders(userFolder)); + folders.AddRange(this.GetSubFolders(userFolder)); return folders; } @@ -599,12 +610,10 @@ private IList GetSubFolders(IFolderInfo parentFolder) foreach (var folder in FolderManager.Instance.GetFolders(parentFolder)) { folders.Add(folder); - folders.AddRange(GetSubFolders(folder)); + folders.AddRange(this.GetSubFolders(folder)); } return folders; - } - - #endregion + } } } diff --git a/DNN Platform/Modules/Journal/Settings.ascx.cs b/DNN Platform/Modules/Journal/Settings.ascx.cs index 86b6973f51e..dafe9c3c503 100644 --- a/DNN Platform/Modules/Journal/Settings.ascx.cs +++ b/DNN Platform/Modules/Journal/Settings.ascx.cs @@ -1,122 +1,150 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal +{ + /* ' Copyright (c) 2011 DotNetNuke Corporation ' All rights reserved. -' +' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. -' +' */ -using System; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Modules.Journal.Components; -using DotNetNuke.Services.Journal; -using System.Web.UI.WebControls; - -using DotNetNuke.Services.Journal.Internal; -using DotNetNuke.Services.Localization; - - -namespace DotNetNuke.Modules.Journal { - + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Modules.Journal.Components; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Journal; + using DotNetNuke.Services.Journal.Internal; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// - /// The Settings class manages Module Settings + /// The Settings class manages Module Settings. /// /// ----------------------------------------------------------------------------- - public partial class Settings : JournalSettingsBase { - - #region Base Method Implementations - + public partial class Settings : JournalSettingsBase + { /// ----------------------------------------------------------------------------- /// - /// LoadSettings loads the settings from the Database and displays them + /// LoadSettings loads the settings from the Database and displays them. /// /// ----------------------------------------------------------------------------- - public override void LoadSettings() { - try { - if (Page.IsPostBack == false) { - BindJournalTypes(); - //Check for existing settings and use those on this page - if (Settings.ContainsKey(Constants.DefaultPageSize)) { - drpDefaultPageSize.SelectedIndex = drpDefaultPageSize.Items.IndexOf(drpDefaultPageSize.Items.FindByValue(Settings[Constants.DefaultPageSize].ToString())); - } else { - drpDefaultPageSize.SelectedIndex = drpDefaultPageSize.Items.IndexOf(drpDefaultPageSize.Items.FindByValue("20")); - + public override void LoadSettings() + { + try + { + if (this.Page.IsPostBack == false) + { + this.BindJournalTypes(); + + // Check for existing settings and use those on this page + if (this.Settings.ContainsKey(Constants.DefaultPageSize)) + { + this.drpDefaultPageSize.SelectedIndex = this.drpDefaultPageSize.Items.IndexOf(this.drpDefaultPageSize.Items.FindByValue(this.Settings[Constants.DefaultPageSize].ToString())); + } + else + { + this.drpDefaultPageSize.SelectedIndex = this.drpDefaultPageSize.Items.IndexOf(this.drpDefaultPageSize.Items.FindByValue("20")); } - if (Settings.ContainsKey(Constants.MaxCharacters)) { - drpMaxMessageLength.SelectedIndex = drpMaxMessageLength.Items.IndexOf(drpMaxMessageLength.Items.FindByValue(Settings[Constants.MaxCharacters].ToString())); - } else { - drpMaxMessageLength.SelectedIndex = drpMaxMessageLength.Items.IndexOf(drpMaxMessageLength.Items.FindByValue("250")); - + + if (this.Settings.ContainsKey(Constants.MaxCharacters)) + { + this.drpMaxMessageLength.SelectedIndex = this.drpMaxMessageLength.Items.IndexOf(this.drpMaxMessageLength.Items.FindByValue(this.Settings[Constants.MaxCharacters].ToString())); + } + else + { + this.drpMaxMessageLength.SelectedIndex = this.drpMaxMessageLength.Items.IndexOf(this.drpMaxMessageLength.Items.FindByValue("250")); } - if (Settings.ContainsKey(Constants.AllowFiles)) { - chkAllowFiles.Checked = Convert.ToBoolean(Settings[Constants.AllowFiles].ToString()); - } else { - chkAllowFiles.Checked = true; + + if (this.Settings.ContainsKey(Constants.AllowFiles)) + { + this.chkAllowFiles.Checked = Convert.ToBoolean(this.Settings[Constants.AllowFiles].ToString()); + } + else + { + this.chkAllowFiles.Checked = true; } - if (Settings.ContainsKey(Constants.AllowPhotos)) { - chkAllowPhotos.Checked = Convert.ToBoolean(Settings[Constants.AllowPhotos].ToString()); - } else { - chkAllowPhotos.Checked = true; + + if (this.Settings.ContainsKey(Constants.AllowPhotos)) + { + this.chkAllowPhotos.Checked = Convert.ToBoolean(this.Settings[Constants.AllowPhotos].ToString()); + } + else + { + this.chkAllowPhotos.Checked = true; } - if (Settings.ContainsKey(Constants.AllowResizePhotos)) + if (this.Settings.ContainsKey(Constants.AllowResizePhotos)) { - chkAllowResize.Checked = Convert.ToBoolean(Settings[Constants.AllowResizePhotos].ToString()); + this.chkAllowResize.Checked = Convert.ToBoolean(this.Settings[Constants.AllowResizePhotos].ToString()); } else { - chkAllowResize.Checked = false; + this.chkAllowResize.Checked = false; } - if (Settings.ContainsKey(Constants.JournalEditorEnabled)) + if (this.Settings.ContainsKey(Constants.JournalEditorEnabled)) { - chkEnableEditor.Checked = Convert.ToBoolean(Settings[Constants.JournalEditorEnabled].ToString()); - } else + this.chkEnableEditor.Checked = Convert.ToBoolean(this.Settings[Constants.JournalEditorEnabled].ToString()); + } + else { - chkEnableEditor.Checked = true; + this.chkEnableEditor.Checked = true; } - if (!chkEnableEditor.Checked) + + if (!this.chkEnableEditor.Checked) { - chkAllowFiles.Enabled = false; - chkAllowPhotos.Enabled = false; + this.chkAllowFiles.Enabled = false; + this.chkAllowPhotos.Enabled = false; } - chkAllowResize.Enabled = chkEnableEditor.Checked && chkAllowPhotos.Checked; + this.chkAllowResize.Enabled = this.chkEnableEditor.Checked && this.chkAllowPhotos.Checked; - foreach (ListItem li in chkJournalFilters.Items) { + foreach (ListItem li in this.chkJournalFilters.Items) + { li.Selected = true; } - if (Settings.ContainsKey(Constants.JournalFilters)) { - if (String.IsNullOrEmpty(Settings[Constants.JournalFilters].ToString())) { - foreach (ListItem li in chkJournalFilters.Items) { + + if (this.Settings.ContainsKey(Constants.JournalFilters)) + { + if (string.IsNullOrEmpty(this.Settings[Constants.JournalFilters].ToString())) + { + foreach (ListItem li in this.chkJournalFilters.Items) + { li.Selected = true; } - } else { - foreach (ListItem li in chkJournalFilters.Items) { + } + else + { + foreach (ListItem li in this.chkJournalFilters.Items) + { li.Selected = false; } - foreach (string s in Settings[Constants.JournalFilters].ToString().Split(';')) { - foreach (ListItem li in chkJournalFilters.Items) { - if (li.Value == s) { + + foreach (string s in this.Settings[Constants.JournalFilters].ToString().Split(';')) + { + foreach (ListItem li in this.chkJournalFilters.Items) + { + if (li.Value == s) + { li.Selected = true; } } } } } - } - } catch (Exception exc) //Module failed to load + } + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -124,54 +152,58 @@ public override void LoadSettings() { /// ----------------------------------------------------------------------------- /// - /// UpdateSettings saves the modified settings to the Database + /// UpdateSettings saves the modified settings to the Database. /// /// ----------------------------------------------------------------------------- - public override void UpdateSettings() { - try { - ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.DefaultPageSize, drpDefaultPageSize.SelectedItem.Value); - ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.AllowFiles, chkAllowFiles.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.AllowPhotos, chkAllowPhotos.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.AllowResizePhotos, chkAllowResize.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.JournalEditorEnabled, chkEnableEditor.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.MaxCharacters, drpMaxMessageLength.SelectedItem.Value); - string journalTypes = ""; + public override void UpdateSettings() + { + try + { + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.DefaultPageSize, this.drpDefaultPageSize.SelectedItem.Value); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.AllowFiles, this.chkAllowFiles.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.AllowPhotos, this.chkAllowPhotos.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.AllowResizePhotos, this.chkAllowResize.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.JournalEditorEnabled, this.chkEnableEditor.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.MaxCharacters, this.drpMaxMessageLength.SelectedItem.Value); + string journalTypes = string.Empty; bool allTypes = true; - foreach (ListItem li in chkJournalFilters.Items) { - if (!li.Selected) { + foreach (ListItem li in this.chkJournalFilters.Items) + { + if (!li.Selected) + { allTypes = false; } } + var jc = InternalJournalController.Instance; - jc.DeleteFilters(PortalId, ModuleId); + jc.DeleteFilters(this.PortalId, this.ModuleId); - foreach (ListItem li in chkJournalFilters.Items) { - if (li.Selected) { - if (!allTypes) { - jc.SaveFilters(PortalId, ModuleId, Convert.ToInt32(li.Value)); + foreach (ListItem li in this.chkJournalFilters.Items) + { + if (li.Selected) + { + if (!allTypes) + { + jc.SaveFilters(this.PortalId, this.ModuleId, Convert.ToInt32(li.Value)); journalTypes += li.Value + ";"; } - } } + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.JournalFilters, journalTypes); - - } catch (Exception exc) //Module failed to load + } + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - #region Private Methods - private void BindJournalTypes() { - foreach (JournalTypeInfo journalTypeInfo in JournalController.Instance.GetJournalTypes(PortalId)) + } + + private void BindJournalTypes() + { + foreach (JournalTypeInfo journalTypeInfo in JournalController.Instance.GetJournalTypes(this.PortalId)) { - chkJournalFilters.Items.Add(new ListItem(Localization.GetString(journalTypeInfo.JournalType, "~/desktopmodules/journal/app_localresources/sharedresources.resx"), journalTypeInfo.JournalTypeId.ToString())); + this.chkJournalFilters.Items.Add(new ListItem(Localization.GetString(journalTypeInfo.JournalType, "~/desktopmodules/journal/app_localresources/sharedresources.resx"), journalTypeInfo.JournalTypeId.ToString())); } - } - #endregion + } } - -} - +} diff --git a/DNN Platform/Modules/Journal/UserFolderHelper.cs b/DNN Platform/Modules/Journal/UserFolderHelper.cs index e64cef58464..f201bc3248a 100644 --- a/DNN Platform/Modules/Journal/UserFolderHelper.cs +++ b/DNN Platform/Modules/Journal/UserFolderHelper.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.Journal { + using System; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.FileSystem; + public class UserFolderHelper { public UserFolderHelper(PortalSettings portalSettings) { - UserFolder = FolderManager.Instance.GetUserFolder(portalSettings.UserInfo); + this.UserFolder = FolderManager.Instance.GetUserFolder(portalSettings.UserInfo); } public IFolderInfo UserFolder { get; set; } @@ -22,7 +22,7 @@ public string UserFolderPhysicalPath { get { - return UserFolder.PhysicalPath; + return this.UserFolder.PhysicalPath; } } @@ -30,7 +30,7 @@ public string UserFolderPath { get { - return UserFolder.FolderPath; + return this.UserFolder.FolderPath; } } } diff --git a/DNN Platform/Modules/Journal/View.ascx.cs b/DNN Platform/Modules/Journal/View.ascx.cs index 213ccd40c71..a0e302f8116 100644 --- a/DNN Platform/Modules/Journal/View.ascx.cs +++ b/DNN Platform/Modules/Journal/View.ascx.cs @@ -1,8 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -/* +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Modules.Journal +{ + /* ' Copyright (c) 2011 DotNetNuke Corporation ' All rights reserved. ' @@ -14,33 +16,32 @@ ' */ -using System; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Modules.Journal.Components; -using DotNetNuke.Security.Roles; -using DotNetNuke.Abstractions; - -namespace DotNetNuke.Modules.Journal { - + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.Journal.Components; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// - /// The ViewJournal class displays the content + /// The ViewJournal class displays the content. /// /// ----------------------------------------------------------------------------- - public partial class View : JournalModuleBase { - - private readonly INavigationManager _navigationManager; + public partial class View : JournalModuleBase + { public int PageSize = 20; public bool AllowPhotos = true; + private readonly INavigationManager _navigationManager; public bool AllowFiles = true; public int MaxMessageLength = 250; public bool CanRender = true; @@ -56,161 +57,168 @@ public partial class View : JournalModuleBase { public View() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Event Handlers - - override protected void OnInit(EventArgs e) + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + + protected override void OnInit(EventArgs e) { JavaScript.RequestRegistration(CommonJs.DnnPlugins); JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); JavaScript.RequestRegistration(CommonJs.Knockout); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journal.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journalcomments.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/mentionsInput.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/Scripts/json2.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Journal/Scripts/journal.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Journal/Scripts/journalcomments.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Journal/Scripts/mentionsInput.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/json2.js"); - var isAdmin = UserInfo.IsInRole(RoleController.Instance.GetRoleById(PortalId, PortalSettings.AdministratorRoleId).RoleName); - if (!Request.IsAuthenticated || (!UserInfo.IsSuperUser && !isAdmin && UserInfo.IsInRole("Unverified Users"))) + var isAdmin = this.UserInfo.IsInRole(RoleController.Instance.GetRoleById(this.PortalId, this.PortalSettings.AdministratorRoleId).RoleName); + if (!this.Request.IsAuthenticated || (!this.UserInfo.IsSuperUser && !isAdmin && this.UserInfo.IsInRole("Unverified Users"))) { - ShowEditor = false; + this.ShowEditor = false; } else { - ShowEditor = EditorEnabled; + this.ShowEditor = this.EditorEnabled; } - if (Settings.ContainsKey(Constants.DefaultPageSize)) + if (this.Settings.ContainsKey(Constants.DefaultPageSize)) { - PageSize = Convert.ToInt16(Settings[Constants.DefaultPageSize]); + this.PageSize = Convert.ToInt16(this.Settings[Constants.DefaultPageSize]); } - if (Settings.ContainsKey(Constants.MaxCharacters)) + + if (this.Settings.ContainsKey(Constants.MaxCharacters)) { - MaxMessageLength = Convert.ToInt16(Settings[Constants.MaxCharacters]); + this.MaxMessageLength = Convert.ToInt16(this.Settings[Constants.MaxCharacters]); } - if (Settings.ContainsKey(Constants.AllowPhotos)) + + if (this.Settings.ContainsKey(Constants.AllowPhotos)) { - AllowPhotos = Convert.ToBoolean(Settings[Constants.AllowPhotos]); + this.AllowPhotos = Convert.ToBoolean(this.Settings[Constants.AllowPhotos]); } - if (Settings.ContainsKey(Constants.AllowFiles)) + + if (this.Settings.ContainsKey(Constants.AllowFiles)) { - AllowFiles = Convert.ToBoolean(Settings[Constants.AllowFiles]); + this.AllowFiles = Convert.ToBoolean(this.Settings[Constants.AllowFiles]); } - ctlJournalList.Enabled = true; - ctlJournalList.ProfileId = -1; - ctlJournalList.PageSize = PageSize; - ctlJournalList.ModuleId = ModuleId; + + this.ctlJournalList.Enabled = true; + this.ctlJournalList.ProfileId = -1; + this.ctlJournalList.PageSize = this.PageSize; + this.ctlJournalList.ModuleId = this.ModuleId; - ModuleInfo moduleInfo = ModuleContext.Configuration; + ModuleInfo moduleInfo = this.ModuleContext.Configuration; - foreach (var module in ModuleController.Instance.GetTabModules(TabId).Values) + foreach (var module in ModuleController.Instance.GetTabModules(this.TabId).Values) { if (module.ModuleDefinition.FriendlyName == "Social Groups") { - if (GroupId == -1 && FilterMode == JournalMode.Auto) + if (this.GroupId == -1 && this.FilterMode == JournalMode.Auto) { - ShowEditor = false; - ctlJournalList.Enabled = false; + this.ShowEditor = false; + this.ctlJournalList.Enabled = false; } - if (GroupId > 0) + if (this.GroupId > 0) { - RoleInfo roleInfo = RoleController.Instance.GetRoleById(moduleInfo.OwnerPortalID, GroupId); + RoleInfo roleInfo = RoleController.Instance.GetRoleById(moduleInfo.OwnerPortalID, this.GroupId); if (roleInfo != null) { - if (UserInfo.IsInRole(roleInfo.RoleName)) + if (this.UserInfo.IsInRole(roleInfo.RoleName)) { - ShowEditor = true; - CanComment = true; - IsGroup = true; - } else + this.ShowEditor = true; + this.CanComment = true; + this.IsGroup = true; + } + else { - ShowEditor = false; - CanComment = false; + this.ShowEditor = false; + this.CanComment = false; } - if (!roleInfo.IsPublic && !ShowEditor) + if (!roleInfo.IsPublic && !this.ShowEditor) { - ctlJournalList.Enabled = false; + this.ctlJournalList.Enabled = false; } - if (roleInfo.IsPublic && !ShowEditor) + + if (roleInfo.IsPublic && !this.ShowEditor) { - ctlJournalList.Enabled = true; + this.ctlJournalList.Enabled = true; } - if (roleInfo.IsPublic && ShowEditor) + + if (roleInfo.IsPublic && this.ShowEditor) { - ctlJournalList.Enabled = true; + this.ctlJournalList.Enabled = true; } + if (roleInfo.IsPublic) { - IsPublicGroup = true; + this.IsPublicGroup = true; } } else { - ShowEditor = false; - ctlJournalList.Enabled = false; + this.ShowEditor = false; + this.ctlJournalList.Enabled = false; } } - } } - if (!String.IsNullOrEmpty(Request.QueryString["userId"])) + if (!string.IsNullOrEmpty(this.Request.QueryString["userId"])) { - ctlJournalList.ProfileId = Convert.ToInt32(Request.QueryString["userId"]); - if (!UserInfo.IsSuperUser && !isAdmin && ctlJournalList.ProfileId != UserId) + this.ctlJournalList.ProfileId = Convert.ToInt32(this.Request.QueryString["userId"]); + if (!this.UserInfo.IsSuperUser && !isAdmin && this.ctlJournalList.ProfileId != this.UserId) { - ShowEditor = ShowEditor && Utilities.AreFriends(UserController.GetUserById(PortalId, ctlJournalList.ProfileId), UserInfo); + this.ShowEditor = this.ShowEditor && Utilities.AreFriends(UserController.GetUserById(this.PortalId, this.ctlJournalList.ProfileId), this.UserInfo); } } - else if (GroupId > 0) + else if (this.GroupId > 0) { - ctlJournalList.SocialGroupId = Convert.ToInt32(Request.QueryString["groupId"]); + this.ctlJournalList.SocialGroupId = Convert.ToInt32(this.Request.QueryString["groupId"]); } - InitializeComponent(); + this.InitializeComponent(); base.OnInit(e); } - private void InitializeComponent() { - Load += Page_Load; + private void InitializeComponent() + { + this.Load += this.Page_Load; } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// ----------------------------------------------------------------------------- - private void Page_Load(object sender, EventArgs e) { + private void Page_Load(object sender, EventArgs e) + { try { - BaseUrl = Globals.ApplicationPath; - BaseUrl = BaseUrl.EndsWith("/") ? BaseUrl : BaseUrl + "/"; - BaseUrl += "DesktopModules/Journal/"; + this.BaseUrl = Globals.ApplicationPath; + this.BaseUrl = this.BaseUrl.EndsWith("/") ? this.BaseUrl : this.BaseUrl + "/"; + this.BaseUrl += "DesktopModules/Journal/"; - ProfilePage = _navigationManager.NavigateURL(PortalSettings.UserTabId, string.Empty, new[] {"userId=xxx"}); + this.ProfilePage = this._navigationManager.NavigateURL(this.PortalSettings.UserTabId, string.Empty, new[] { "userId=xxx" }); - if (!String.IsNullOrEmpty(Request.QueryString["userId"])) + if (!string.IsNullOrEmpty(this.Request.QueryString["userId"])) { - Pid = Convert.ToInt32(Request.QueryString["userId"]); - ctlJournalList.ProfileId = Pid; + this.Pid = Convert.ToInt32(this.Request.QueryString["userId"]); + this.ctlJournalList.ProfileId = this.Pid; } - else if (GroupId > 0) + else if (this.GroupId > 0) { - Gid = GroupId; - ctlJournalList.SocialGroupId = GroupId; + this.Gid = this.GroupId; + this.ctlJournalList.SocialGroupId = this.GroupId; } - ctlJournalList.PageSize = PageSize; + + this.ctlJournalList.PageSize = this.PageSize; } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - #endregion + } } } diff --git a/DNN Platform/Modules/Journal/packages.config b/DNN Platform/Modules/Journal/packages.config index 4073d3c4617..78db8377d2d 100644 --- a/DNN Platform/Modules/Journal/packages.config +++ b/DNN Platform/Modules/Journal/packages.config @@ -1,10 +1,11 @@ - - - - - - - - - + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/MemberDirectory/AssemblyInfo.cs b/DNN Platform/Modules/MemberDirectory/AssemblyInfo.cs index b3feca3f92a..97e7f2d92cf 100644 --- a/DNN Platform/Modules/MemberDirectory/AssemblyInfo.cs +++ b/DNN Platform/Modules/MemberDirectory/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("MemberDirectory")] [assembly: AssemblyDescription("")] -// 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 +// 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)] diff --git a/DNN Platform/Modules/MemberDirectory/Components/UpgradeController.cs b/DNN Platform/Modules/MemberDirectory/Components/UpgradeController.cs index 689d9d2ca5c..0b83ecd5b42 100644 --- a/DNN Platform/Modules/MemberDirectory/Components/UpgradeController.cs +++ b/DNN Platform/Modules/MemberDirectory/Components/UpgradeController.cs @@ -1,66 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; -using System.Web; -using System.Xml; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; - -using System; - -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Upgrade; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.MemberDirectory.Components { + using System; + using System.IO; + using System.Web; + using System.Xml; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Upgrade; + + public class UpgradeController : IUpgradeable + { + public string UpgradeModule(string Version) + { + try + { + switch (Version) + { + case "07.00.06": + this.UpdateDisplaySearchSettings(); + break; + } + } + catch (Exception ex) + { + ExceptionLogController xlc = new ExceptionLogController(); + xlc.AddLog(ex); - public class UpgradeController : IUpgradeable - { - public string UpgradeModule(string Version) - { - try - { - switch (Version) - { - case "07.00.06": - UpdateDisplaySearchSettings(); - break; - } - } - catch (Exception ex) - { - ExceptionLogController xlc = new ExceptionLogController(); - xlc.AddLog(ex); - - return "Failed"; - } + return "Failed"; + } - return "Success"; - } + return "Success"; + } - private void UpdateDisplaySearchSettings() - { + private void UpdateDisplaySearchSettings() + { foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { foreach (ModuleInfo module in ModuleController.Instance.GetModulesByDefinition(portal.PortalID, "Member Directory")) - { - foreach (ModuleInfo tabModule in ModuleController.Instance.GetAllTabsModulesByModuleID(module.ModuleID)) - { - bool oldValue; + { + foreach (ModuleInfo tabModule in ModuleController.Instance.GetAllTabsModulesByModuleID(module.ModuleID)) + { + bool oldValue; if (tabModule.TabModuleSettings.ContainsKey("DisplaySearch") && bool.TryParse(tabModule.TabModuleSettings["DisplaySearch"].ToString(), out oldValue)) - { + { ModuleController.Instance.UpdateTabModuleSetting(tabModule.TabModuleID, "DisplaySearch", oldValue ? "Both" : "None"); - } - } - } + } + } + } } - } - } + } + } } diff --git a/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj b/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj index 3af02580ee1..6f69ebaf27a 100644 --- a/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj +++ b/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj @@ -27,6 +27,7 @@ ..\..\..\..\Evoq.Content\ true + true @@ -125,6 +126,9 @@ + + stylecop.json + Designer @@ -181,6 +185,10 @@ False + + + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) diff --git a/DNN Platform/Modules/MemberDirectory/MemberDirectory.dnn b/DNN Platform/Modules/MemberDirectory/MemberDirectory.dnn index 67b8a874c94..5a7e262f5b5 100644 --- a/DNN Platform/Modules/MemberDirectory/MemberDirectory.dnn +++ b/DNN Platform/Modules/MemberDirectory/MemberDirectory.dnn @@ -1,6 +1,6 @@ - + Member Directory The Member Directory module displays a list of Members based on role, profile property or relationship. ~/DesktopModules/MemberDirectory/Images/member_list_32X32.png diff --git a/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs b/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs index e93c2bd1171..75390317942 100644 --- a/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs +++ b/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs @@ -1,41 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Common.Lists; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Modules.MemberDirectory.ViewModels; -using DotNetNuke.Security.Roles; -using DotNetNuke.Web.Mvp; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.MemberDirectory.Presenters { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Modules.MemberDirectory.ViewModels; + using DotNetNuke.Security.Roles; + using DotNetNuke.Web.Mvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public class ModuleSettingsPresenter : ModuleSettingsPresenter, MemberDirectorySettingsModel> { public ModuleSettingsPresenter(ISettingsView view) : base(view) { - } protected override void OnLoad() { base.OnLoad(); - View.Model.Groups = RoleController.Instance.GetRoles(PortalId, r => r.Status == RoleStatus.Approved); - View.Model.Relationships = RelationshipController.Instance.GetRelationshipsByPortalId(PortalId); + this.View.Model.Groups = RoleController.Instance.GetRoles(this.PortalId, r => r.Status == RoleStatus.Approved); + this.View.Model.Relationships = RelationshipController.Instance.GetRelationshipsByPortalId(this.PortalId); - View.Model.ProfileProperties = new List(); - foreach (ProfilePropertyDefinition definition in ProfileController.GetPropertyDefinitionsByPortal(PortalId)) + this.View.Model.ProfileProperties = new List(); + foreach (ProfilePropertyDefinition definition in ProfileController.GetPropertyDefinitionsByPortal(this.PortalId)) { var controller = new ListController(); ListEntryInfo textType = controller.GetListEntryInfo("DataType", "Text"); @@ -43,7 +37,7 @@ protected override void OnLoad() ListEntryInfo countryType = controller.GetListEntryInfo("DataType", "Country"); if (definition.DataType == textType.EntryID || definition.DataType == regionType.EntryID || definition.DataType == countryType.EntryID) { - View.Model.ProfileProperties.Add(definition); + this.View.Model.ProfileProperties.Add(definition); } } } diff --git a/DNN Platform/Modules/MemberDirectory/Services/Member.cs b/DNN Platform/Modules/MemberDirectory/Services/Member.cs index 28130cf0bef..84287971378 100644 --- a/DNN Platform/Modules/MemberDirectory/Services/Member.cs +++ b/DNN Platform/Modules/MemberDirectory/Services/Member.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Threading; -using System.Net; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Tokens; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.MemberDirectory.Services { + using System; + using System.Collections.Generic; + using System.Net; + using System.Threading; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Tokens; + public class Member { private UserInfo _user; @@ -24,74 +24,74 @@ public class Member public Member(UserInfo user, PortalSettings settings) { - _user = user; - _settings = settings; - _viewer = settings.UserInfo; + this._user = user; + this._settings = settings; + this._viewer = settings.UserInfo; } public int MemberId { - get { return _user.UserID; } + get { return this._user.UserID; } } public string City { - get { return GetProfileProperty("City"); } + get { return this.GetProfileProperty("City"); } } public string Country { - get { return GetProfileProperty("Country"); } + get { return this.GetProfileProperty("Country"); } } public string DisplayName { - get { return _user.DisplayName; } + get { return this._user.DisplayName; } } public string Email { - get { return (_viewer.IsInRole(_settings.AdministratorRoleName)) ? _user.Email : String.Empty; } + get { return this._viewer.IsInRole(this._settings.AdministratorRoleName) ? this._user.Email : string.Empty; } } public string FirstName { - get { return GetProfileProperty("FirstName"); } + get { return this.GetProfileProperty("FirstName"); } } public int FollowerStatus { - get { return (_user.Social.Follower == null) ? 0 : (int)_user.Social.Follower.Status; } + get { return (this._user.Social.Follower == null) ? 0 : (int)this._user.Social.Follower.Status; } } public int FollowingStatus { - get { return (_user.Social.Following == null) ? 0 : (int)_user.Social.Following.Status; } + get { return (this._user.Social.Following == null) ? 0 : (int)this._user.Social.Following.Status; } } public int FriendId { - get { return (_user.Social.Friend == null) ? -1 : (int)_user.Social.Friend.RelatedUserId; } + get { return (this._user.Social.Friend == null) ? -1 : (int)this._user.Social.Friend.RelatedUserId; } } public int FriendStatus { - get { return (_user.Social.Friend == null) ? 0 : (int)_user.Social.Friend.Status; } + get { return (this._user.Social.Friend == null) ? 0 : (int)this._user.Social.Friend.Status; } } public string LastName { - get { return GetProfileProperty("LastName"); } + get { return this.GetProfileProperty("LastName"); } } public string Phone { - get { return GetProfileProperty("Telephone"); } + get { return this.GetProfileProperty("Telephone"); } } public string PhotoURL { - get { return _user.Profile.PhotoURL; } + get { return this._user.Profile.PhotoURL; } } public Dictionary ProfileProperties @@ -100,50 +100,52 @@ public Dictionary ProfileProperties { var properties = new Dictionary(); bool propertyNotFound = false; - var propertyAccess = new ProfilePropertyAccess(_user); - foreach(ProfilePropertyDefinition property in _user.Profile.ProfileProperties) + var propertyAccess = new ProfilePropertyAccess(this._user); + foreach (ProfilePropertyDefinition property in this._user.Profile.ProfileProperties) { - string value = propertyAccess.GetProperty(property.PropertyName, - String.Empty, - Thread.CurrentThread.CurrentUICulture, - _viewer, - Scope.DefaultSettings, - ref propertyNotFound); - - properties[property.PropertyName] = string.IsNullOrEmpty(value) ? "" : Common.Utilities.HtmlUtils.Clean(HttpUtility.HtmlDecode(value), false); + string value = propertyAccess.GetProperty( + property.PropertyName, + string.Empty, + Thread.CurrentThread.CurrentUICulture, + this._viewer, + Scope.DefaultSettings, + ref propertyNotFound); + + properties[property.PropertyName] = string.IsNullOrEmpty(value) ? string.Empty : Common.Utilities.HtmlUtils.Clean(HttpUtility.HtmlDecode(value), false); } + return properties; } } public string Title { - get { return _user.Profile.Title; } + get { return this._user.Profile.Title; } } public string UserName { - get { return (_viewer.IsInRole(_settings.AdministratorRoleName)) ? _user.Username : String.Empty; } + get { return this._viewer.IsInRole(this._settings.AdministratorRoleName) ? this._user.Username : string.Empty; } } public string Website { - get { return GetProfileProperty("Website"); } + get { return this.GetProfileProperty("Website"); } } public string ProfileUrl { - get { return Globals.UserProfileURL(MemberId); } + get { return Globals.UserProfileURL(this.MemberId); } } /// - /// This method returns the value of the ProfileProperty if is defined, otherwise it returns an Empty string + /// This method returns the value of the ProfileProperty if is defined, otherwise it returns an Empty string. /// - /// property name - /// property value + /// property name. + /// property value. private string GetProfileProperty(string propertyName) { - var profileProperties = ProfileProperties; + var profileProperties = this.ProfileProperties; string value; return profileProperties.TryGetValue(propertyName, out value) ? value : string.Empty; diff --git a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs index e16e5caefe1..b7f34e35750 100644 --- a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs +++ b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs @@ -1,36 +1,83 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using DotNetNuke.Common.Lists; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Web.Api; -using DotNetNuke.Entities.Users.Social; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.MemberDirectory.Services { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Web.Api; + [SupportedModules("DotNetNuke.Modules.MemberDirectory")] [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] public class MemberDirectoryController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (MemberDirectoryController)); - #region Private Methods + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MemberDirectoryController)); + + [HttpGet] + public HttpResponseMessage AdvancedSearch(int userId, int groupId, int pageIndex, int pageSize, string searchTerm1, string searchTerm2, string searchTerm3, string searchTerm4) + { + try + { + if (userId < 0) + { + userId = this.PortalSettings.UserId; + } + + var searchField1 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField1", "DisplayName"); + var searchField2 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField2", "Email"); + var searchField3 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField3", "City"); + var searchField4 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField4", "Country"); + + var propertyNames = string.Empty; + var propertyValues = string.Empty; + AddSearchTerm(ref propertyNames, ref propertyValues, searchField1, searchTerm1); + AddSearchTerm(ref propertyNames, ref propertyValues, searchField2, searchTerm2); + AddSearchTerm(ref propertyNames, ref propertyValues, searchField3, searchTerm3); + AddSearchTerm(ref propertyNames, ref propertyValues, searchField4, searchTerm4); + var members = this.GetUsers(userId, groupId, searchTerm1, pageIndex, pageSize, propertyNames, propertyValues); + return this.Request.CreateResponse(HttpStatusCode.OK, this.GetMembers(members)); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpGet] + public HttpResponseMessage BasicSearch(int groupId, string searchTerm, int pageIndex, int pageSize) + { + try + { + var users = this.GetUsers(-1, groupId, string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.Trim(), pageIndex, pageSize, string.Empty, string.Empty); + return this.Request.CreateResponse(HttpStatusCode.OK, this.GetMembers(users)); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + private static void AddSearchTerm(ref string propertyNames, ref string propertyValues, string name, string value) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { propertyNames += name + ","; @@ -39,6 +86,7 @@ private static void AddSearchTerm(ref string propertyNames, ref string propertyV { value = GetMatchedListEntryIds(name, value); } + propertyValues += value + ","; } } @@ -54,55 +102,57 @@ private static string GetMatchedListEntryIds(string name, string value) return $"${string.Join("$", listEntries)}$"; } + private static string GetSetting(IDictionary settings, string key, string defaultValue) + { + var setting = defaultValue; + if (settings[key] != null) + { + setting = Convert.ToString(settings[key]); + } + + return setting; + } + private bool CanViewGroupMembers(int portalId, int groupId) { var group = RoleController.Instance.GetRole(portalId, r => r.RoleID == groupId); - if(group == null) + if (group == null) { return false; } var canView = (group.SecurityMode == SecurityMode.SecurityRole) - ? (PortalSettings.UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) - : (PortalSettings.UserInfo.IsInRole(group.RoleName)); + ? this.PortalSettings.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) + : this.PortalSettings.UserInfo.IsInRole(group.RoleName); - //if current user can view the group page and group is public, then should be able to view members. - if (!canView) - { - canView = ModulePermissionController.CanViewModule(ActiveModule) && group.IsPublic; - } + // if current user can view the group page and group is public, then should be able to view members. + if (!canView) + { + canView = ModulePermissionController.CanViewModule(this.ActiveModule) && group.IsPublic; + } + return canView; } private IList GetMembers(IEnumerable users) { - return users.Select(user => new Member(user, PortalSettings)).ToList(); - } - - private static string GetSetting(IDictionary settings, string key, string defaultValue) - { - var setting = defaultValue; - if (settings[key] != null) - { - setting = Convert.ToString(settings[key]); - } - return setting; + return users.Select(user => new Member(user, this.PortalSettings)).ToList(); } private IEnumerable GetUsers(int userId, int groupId, string searchTerm, int pageIndex, int pageSize, string propertyNames, string propertyValues) { - var portalId = PortalSettings.PortalId; - var isAdmin = PortalSettings.UserInfo.IsInRole(PortalSettings.AdministratorRoleName); + var portalId = this.PortalSettings.PortalId; + var isAdmin = this.PortalSettings.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName); - var filterBy = GetSetting(ActiveModule.ModuleSettings, "FilterBy", String.Empty); - var filterValue = GetSetting(ActiveModule.ModuleSettings, "FilterValue", String.Empty); + var filterBy = GetSetting(this.ActiveModule.ModuleSettings, "FilterBy", string.Empty); + var filterValue = GetSetting(this.ActiveModule.ModuleSettings, "FilterValue", string.Empty); if (filterBy == "Group" && filterValue == "-1" && groupId > 0) { filterValue = groupId.ToString(); } - var sortField = GetSetting(ActiveModule.TabModuleSettings, "SortField", "DisplayName"); + var sortField = GetSetting(this.ActiveModule.TabModuleSettings, "SortField", "DisplayName"); // QuickFix DNN-6096. See: https://dnntracker.atlassian.net/browse/DNN-6096 // Instead of changing the available SortFields, we'll use "UserId" as SortField if the TabModuleSetting SortField was CreatedOnDate. @@ -113,11 +163,11 @@ private IEnumerable GetUsers(int userId, int groupId, string searchTer sortField = "UserId"; } - var sortOrder = GetSetting(ActiveModule.TabModuleSettings, "SortOrder", "ASC"); + var sortOrder = GetSetting(this.ActiveModule.TabModuleSettings, "SortOrder", "ASC"); - var excludeHostUsers = Boolean.Parse(GetSetting(ActiveModule.TabModuleSettings, "ExcludeHostUsers", "false")); + var excludeHostUsers = bool.Parse(GetSetting(this.ActiveModule.TabModuleSettings, "ExcludeHostUsers", "false")); var isBasicSearch = false; - if (String.IsNullOrEmpty(propertyNames)) + if (string.IsNullOrEmpty(propertyNames)) { isBasicSearch = true; AddSearchTerm(ref propertyNames, ref propertyValues, "DisplayName", searchTerm); @@ -132,106 +182,62 @@ private IEnumerable GetUsers(int userId, int groupId, string searchTer case "Group": if (groupId == -1) { - groupId = Int32.Parse(filterValue); + groupId = int.Parse(filterValue); } - if (CanViewGroupMembers(portalId, groupId)) + + if (this.CanViewGroupMembers(portalId, groupId)) { - users = UserController.Instance.GetUsersAdvancedSearch(portalId, PortalSettings.UserId, userId, + users = UserController.Instance.GetUsersAdvancedSearch(portalId, this.PortalSettings.UserId, userId, groupId, -1, isAdmin, pageIndex, pageSize, - sortField, (sortOrder == "ASC"), + sortField, sortOrder == "ASC", propertyNames, propertyValues); } else { users = new List(); } + break; case "Relationship": - users = UserController.Instance.GetUsersAdvancedSearch(portalId, PortalSettings.UserId, userId, -1, - Int32.Parse(filterValue), isAdmin, pageIndex, pageSize, - sortField, (sortOrder == "ASC"), + users = UserController.Instance.GetUsersAdvancedSearch(portalId, this.PortalSettings.UserId, userId, -1, + int.Parse(filterValue), isAdmin, pageIndex, pageSize, + sortField, sortOrder == "ASC", propertyNames, propertyValues); break; case "ProfileProperty": - var propertyValue = GetSetting(ActiveModule.ModuleSettings, "FilterPropertyValue", String.Empty); + var propertyValue = GetSetting(this.ActiveModule.ModuleSettings, "FilterPropertyValue", string.Empty); AddSearchTerm(ref propertyNames, ref propertyValues, filterValue, propertyValue); - users = UserController.Instance.GetUsersAdvancedSearch(portalId, PortalSettings.UserId, userId, -1, + users = UserController.Instance.GetUsersAdvancedSearch(portalId, this.PortalSettings.UserId, userId, -1, -1, isAdmin, pageIndex, pageSize, - sortField, (sortOrder == "ASC"), + sortField, sortOrder == "ASC", propertyNames, propertyValues); break; default: - users = isBasicSearch ? UserController.Instance.GetUsersBasicSearch(PortalSettings.PortalId, pageIndex, pageSize, - sortField, (sortOrder == "ASC"), + users = isBasicSearch ? UserController.Instance.GetUsersBasicSearch(this.PortalSettings.PortalId, pageIndex, pageSize, + sortField, sortOrder == "ASC", "DisplayName", searchTerm) : - UserController.Instance.GetUsersAdvancedSearch(portalId, PortalSettings.UserId, userId, -1, + UserController.Instance.GetUsersAdvancedSearch(portalId, this.PortalSettings.UserId, userId, -1, -1, isAdmin, pageIndex, pageSize, - sortField, (sortOrder == "ASC"), + sortField, sortOrder == "ASC", propertyNames, propertyValues); break; } + if (excludeHostUsers) - { - return FilterExcludedUsers(users); + { + return this.FilterExcludedUsers(users); } + return users; } private IEnumerable FilterExcludedUsers(IEnumerable users) { return users.Where(u => !u.IsSuperUser).Select(u => u).ToList(); - } - - #endregion - - #region Public Methods - - [HttpGet] - public HttpResponseMessage AdvancedSearch(int userId, int groupId, int pageIndex, int pageSize, string searchTerm1, string searchTerm2, string searchTerm3, string searchTerm4) - { - try - { - if (userId < 0) userId = PortalSettings.UserId; - - var searchField1 = GetSetting(ActiveModule.TabModuleSettings, "SearchField1", "DisplayName"); - var searchField2 = GetSetting(ActiveModule.TabModuleSettings, "SearchField2", "Email"); - var searchField3 = GetSetting(ActiveModule.TabModuleSettings, "SearchField3", "City"); - var searchField4 = GetSetting(ActiveModule.TabModuleSettings, "SearchField4", "Country"); - - var propertyNames = ""; - var propertyValues = ""; - AddSearchTerm(ref propertyNames, ref propertyValues, searchField1, searchTerm1); - AddSearchTerm(ref propertyNames, ref propertyValues, searchField2, searchTerm2); - AddSearchTerm(ref propertyNames, ref propertyValues, searchField3, searchTerm3); - AddSearchTerm(ref propertyNames, ref propertyValues, searchField4, searchTerm4); - - var members = GetUsers(userId, groupId, searchTerm1, pageIndex, pageSize, propertyNames, propertyValues); - return Request.CreateResponse(HttpStatusCode.OK, GetMembers(members)); - } - catch (Exception exc) - { - Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpGet] - public HttpResponseMessage BasicSearch(int groupId, string searchTerm, int pageIndex, int pageSize) - { - try - { - var users = GetUsers(-1, groupId, string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.Trim(), pageIndex, pageSize, "", ""); - return Request.CreateResponse(HttpStatusCode.OK, GetMembers(users)); - } - catch (Exception exc) - { - Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } + } [HttpGet] public HttpResponseMessage GetMember(int userId) @@ -239,15 +245,15 @@ public HttpResponseMessage GetMember(int userId) try { var users = new List(); - var user = UserController.GetUserById(PortalSettings.PortalId, userId); + var user = UserController.GetUserById(this.PortalSettings.PortalId, userId); users.Add(user); - return Request.CreateResponse(HttpStatusCode.OK, GetMembers(users)); + return this.Request.CreateResponse(HttpStatusCode.OK, this.GetMembers(users)); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -256,16 +262,16 @@ public HttpResponseMessage GetSuggestions(int groupId, string displayName) { try { - var names = (from UserInfo user in GetUsers(-1, groupId, displayName.Trim(), 0, 10, "", "") + var names = (from UserInfo user in this.GetUsers(-1, groupId, displayName.Trim(), 0, 10, string.Empty, string.Empty) select new { label = user.DisplayName, value = user.DisplayName, userId = user.UserID }) .ToList(); - return Request.CreateResponse(HttpStatusCode.OK, names); + return this.Request.CreateResponse(HttpStatusCode.OK, names); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -275,14 +281,14 @@ public HttpResponseMessage AcceptFriend(FriendDTO postData) { try { - var friend = UserController.GetUserById(PortalSettings.PortalId, postData.FriendId); + var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); FriendsController.Instance.AcceptFriend(friend); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -292,14 +298,14 @@ public HttpResponseMessage AddFriend(FriendDTO postData) { try { - var friend = UserController.GetUserById(PortalSettings.PortalId, postData.FriendId); + var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); FriendsController.Instance.AddFriend(friend); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -309,14 +315,14 @@ public HttpResponseMessage Follow(FollowDTO postData) { try { - var follow = UserController.GetUserById(PortalSettings.PortalId, postData.FollowId); + var follow = UserController.GetUserById(this.PortalSettings.PortalId, postData.FollowId); FollowersController.Instance.FollowUser(follow); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -326,14 +332,14 @@ public HttpResponseMessage RemoveFriend(FriendDTO postData) { try { - var friend = UserController.GetUserById(PortalSettings.PortalId, postData.FriendId); + var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); FriendsController.Instance.DeleteFriend(friend); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } @@ -343,21 +349,17 @@ public HttpResponseMessage UnFollow(FollowDTO postData) { try { - var follow = UserController.GetUserById(PortalSettings.PortalId, postData.FollowId); + var follow = UserController.GetUserById(this.PortalSettings.PortalId, postData.FollowId); FollowersController.Instance.UnFollowUser(follow); - return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"}); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } catch (Exception exc) { Logger.Error(exc); - return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - } - - #endregion - - #region DTO - + } + public class FollowDTO { public int FollowId { get; set; } @@ -366,8 +368,6 @@ public class FollowDTO public class FriendDTO { public int FriendId { get; set; } - } - - #endregion + } } } diff --git a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryServiceRouteMapper.cs b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryServiceRouteMapper.cs index 8db5c0a0c01..122e2428dcb 100644 --- a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryServiceRouteMapper.cs +++ b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryServiceRouteMapper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.MemberDirectory.Services { + using DotNetNuke.Web.Api; + public class MemberDirectoryServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) diff --git a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs index 726d7844f7d..197b2ba7426 100644 --- a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs +++ b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs @@ -1,37 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Modules.MemberDirectory.Presenters; -using DotNetNuke.Modules.MemberDirectory.ViewModels; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Mvp; -using DotNetNuke.Web.UI.WebControls.Extensions; - -using WebFormsMvp; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.MemberDirectory { + using System; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Modules.MemberDirectory.Presenters; + using DotNetNuke.Modules.MemberDirectory.ViewModels; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Mvp; + using DotNetNuke.Web.UI.WebControls.Extensions; + using WebFormsMvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] [PresenterBinding(typeof(ModuleSettingsPresenter))] public partial class Settings : SettingsView { + public const int DefaultPageSize = 20; + private static string templatePath = "~/DesktopModules/MemberDirectory/Templates/"; private string _defaultSearchField1 = "DisplayName"; @@ -43,7 +40,7 @@ public partial class Settings : SettingsView private string _defaultSortOrder = "ASC"; private string _defaultFilterBy = "None"; - private string _defaultFilterValue = String.Empty; + private string _defaultFilterValue = string.Empty; private string _defaultDisplaySearch = "Both"; private string _defaultEnablePopUp = "false"; @@ -56,10 +53,11 @@ public static string DefaultAlternateItemTemplate get { string template; - using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(templatePath + "AlternateItemTemplate.htm"))) + using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(templatePath + "AlternateItemTemplate.htm"))) { template = sr.ReadToEnd(); } + return template; } } @@ -73,12 +71,11 @@ public static string DefaultItemTemplate { template = sr.ReadToEnd(); } + return template; } } - public const int DefaultPageSize = 20; - public static string DefaultPopUpTemplate { get @@ -88,6 +85,7 @@ public static string DefaultPopUpTemplate { template = sr.ReadToEnd(); } + return template; } } @@ -96,166 +94,162 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - AutoDataBind = false; + this.AutoDataBind = false; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if(!IsPostBack) + if (!this.IsPostBack) { - if (Model.Groups.Count > 0) + if (this.Model.Groups.Count > 0) { - groupList.DataSource = Model.Groups; - groupList.DataBind(); - groupList.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), Null.NullInteger.ToString())); + this.groupList.DataSource = this.Model.Groups; + this.groupList.DataBind(); + this.groupList.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), Null.NullInteger.ToString())); } else { - filterBySelector.Items.FindByValue("Group").Enabled = false; + this.filterBySelector.Items.FindByValue("Group").Enabled = false; } - foreach (var rel in Model.Relationships) + foreach (var rel in this.Model.Relationships) { - relationShipList.AddItem(Localization.GetString(rel.Name,Localization.SharedResourceFile),rel.RelationshipId.ToString()); + this.relationShipList.AddItem(Localization.GetString(rel.Name, Localization.SharedResourceFile), rel.RelationshipId.ToString()); } - - + var profileResourceFile = "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx"; + + System.Web.UI.WebControls.ListItemCollection propertiesCollection = this.GetPropertiesCollection(profileResourceFile); + + // Bind the ListItemCollection to the list + this.propertyList.DataSource = propertiesCollection; + this.propertyList.DataBind(); - - System.Web.UI.WebControls.ListItemCollection propertiesCollection = GetPropertiesCollection(profileResourceFile); - - - //Bind the ListItemCollection to the list - propertyList.DataSource = propertiesCollection; - propertyList.DataBind(); - - //Insert custom properties to the Search field lists - propertiesCollection.Insert(0,new ListItem(Localization.GetString("Username",LocalResourceFile),"Username")); - propertiesCollection.Insert(1, new ListItem(Localization.GetString("DisplayName", LocalResourceFile), "DisplayName")); - propertiesCollection.Insert(2, new ListItem(Localization.GetString("Email", LocalResourceFile), "Email")); + // Insert custom properties to the Search field lists + propertiesCollection.Insert(0, new ListItem(Localization.GetString("Username", this.LocalResourceFile), "Username")); + propertiesCollection.Insert(1, new ListItem(Localization.GetString("DisplayName", this.LocalResourceFile), "DisplayName")); + propertiesCollection.Insert(2, new ListItem(Localization.GetString("Email", this.LocalResourceFile), "Email")); - //Bind the properties collection in the Search Field Lists + // Bind the properties collection in the Search Field Lists + this.searchField1List.DataSource = propertiesCollection; + this.searchField1List.DataBind(); - searchField1List.DataSource = propertiesCollection; - searchField1List.DataBind(); + this.searchField2List.DataSource = propertiesCollection; + this.searchField2List.DataBind(); - searchField2List.DataSource = propertiesCollection; - searchField2List.DataBind(); + this.searchField3List.DataSource = propertiesCollection; + this.searchField3List.DataBind(); - searchField3List.DataSource = propertiesCollection; - searchField3List.DataBind(); + this.searchField4List.DataSource = propertiesCollection; + this.searchField4List.DataBind(); - searchField4List.DataSource = propertiesCollection; - searchField4List.DataBind(); + this.filterBySelector.Select(this._filterBy, false, 0); - filterBySelector.Select(_filterBy, false, 0); - - switch (_filterBy) + switch (this._filterBy) { case "Group": - groupList.Select(_filterValue, false, 0); + this.groupList.Select(this._filterValue, false, 0); break; case "Relationship": - relationShipList.Select(_filterValue, false, 0); + this.relationShipList.Select(this._filterValue, false, 0); break; case "ProfileProperty": - propertyList.Select(_filterValue, false, 0); + this.propertyList.Select(this._filterValue, false, 0); break; case "User": break; } - searchField1List.Select(GetTabModuleSetting("SearchField1", _defaultSearchField1)); - searchField2List.Select(GetTabModuleSetting("SearchField2", _defaultSearchField2)); - searchField3List.Select(GetTabModuleSetting("SearchField3", _defaultSearchField3)); - searchField4List.Select(GetTabModuleSetting("SearchField4", _defaultSearchField4)); - - ExcludeHostUsersCheckBox.Checked = Boolean.Parse(GetTabModuleSetting("ExcludeHostUsers", "false")); - } - } + this.searchField1List.Select(this.GetTabModuleSetting("SearchField1", this._defaultSearchField1)); + this.searchField2List.Select(this.GetTabModuleSetting("SearchField2", this._defaultSearchField2)); + this.searchField3List.Select(this.GetTabModuleSetting("SearchField3", this._defaultSearchField3)); + this.searchField4List.Select(this.GetTabModuleSetting("SearchField4", this._defaultSearchField4)); - private ListItemCollection GetPropertiesCollection(string profileResourceFile) - { - var result = new ListItemCollection(); - foreach (var property in Model.ProfileProperties) - { - result.Add(new ListItem(GetLocalizeName(property.PropertyName,profileResourceFile),property.PropertyName)); + this.ExcludeHostUsersCheckBox.Checked = bool.Parse(this.GetTabModuleSetting("ExcludeHostUsers", "false")); } - - return result; } protected override void OnSettingsLoaded() { base.OnSettingsLoaded(); - if(!IsPostBack) + if (!this.IsPostBack) { - BindSortList(); + this.BindSortList(); - itemTemplate.Text = GetTabModuleSetting("ItemTemplate", DefaultItemTemplate); - alternateItemTemplate.Text = GetTabModuleSetting("AlternateItemTemplate", DefaultAlternateItemTemplate); - popUpTemplate.Text = GetTabModuleSetting("PopUpTemplate", DefaultPopUpTemplate); - displaySearchList.Select(GetTabModuleSetting("DisplaySearch", _defaultDisplaySearch)); - enablePopUp.Checked = Boolean.Parse(GetTabModuleSetting("EnablePopUp", _defaultEnablePopUp)); + this.itemTemplate.Text = this.GetTabModuleSetting("ItemTemplate", DefaultItemTemplate); + this.alternateItemTemplate.Text = this.GetTabModuleSetting("AlternateItemTemplate", DefaultAlternateItemTemplate); + this.popUpTemplate.Text = this.GetTabModuleSetting("PopUpTemplate", DefaultPopUpTemplate); + this.displaySearchList.Select(this.GetTabModuleSetting("DisplaySearch", this._defaultDisplaySearch)); + this.enablePopUp.Checked = bool.Parse(this.GetTabModuleSetting("EnablePopUp", this._defaultEnablePopUp)); - _filterBy = GetModuleSetting("FilterBy", _defaultFilterBy); - _filterValue = GetModuleSetting("FilterValue", _defaultFilterValue); - propertyValue.Text = GetModuleSetting("FilterPropertyValue", String.Empty); + this._filterBy = this.GetModuleSetting("FilterBy", this._defaultFilterBy); + this._filterValue = this.GetModuleSetting("FilterValue", this._defaultFilterValue); + this.propertyValue.Text = this.GetModuleSetting("FilterPropertyValue", string.Empty); - sortFieldList.Select(GetTabModuleSetting("SortField", _defaultSortField)); - sortOrderList.Select(GetTabModuleSetting("SortOrder", _defaultSortOrder)); + this.sortFieldList.Select(this.GetTabModuleSetting("SortField", this._defaultSortField)); + this.sortOrderList.Select(this.GetTabModuleSetting("SortOrder", this._defaultSortOrder)); - pageSize.Text = GetTabModuleSetting("PageSize", DefaultPageSize.ToString(CultureInfo.InvariantCulture)); - disablePager.Checked = Boolean.Parse(GetTabModuleSetting("DisablePaging", "False")); + this.pageSize.Text = this.GetTabModuleSetting("PageSize", DefaultPageSize.ToString(CultureInfo.InvariantCulture)); + this.disablePager.Checked = bool.Parse(this.GetTabModuleSetting("DisablePaging", "False")); } } protected override void OnSavingSettings() { - Model.TabModuleSettings["ItemTemplate"] = itemTemplate.Text; - Model.TabModuleSettings["AlternateItemTemplate"] = alternateItemTemplate.Text; - Model.TabModuleSettings["PopUpTemplate"] = popUpTemplate.Text; - Model.TabModuleSettings["EnablePopUp"] = enablePopUp.Checked.ToString(CultureInfo.InvariantCulture); + this.Model.TabModuleSettings["ItemTemplate"] = this.itemTemplate.Text; + this.Model.TabModuleSettings["AlternateItemTemplate"] = this.alternateItemTemplate.Text; + this.Model.TabModuleSettings["PopUpTemplate"] = this.popUpTemplate.Text; + this.Model.TabModuleSettings["EnablePopUp"] = this.enablePopUp.Checked.ToString(CultureInfo.InvariantCulture); - _filterBy = filterBySelector.SelectedValue; - Model.ModuleSettings["FilterBy"] = _filterBy; + this._filterBy = this.filterBySelector.SelectedValue; + this.Model.ModuleSettings["FilterBy"] = this._filterBy; - switch (_filterBy) + switch (this._filterBy) { case "Group": - Model.ModuleSettings["FilterValue"] = groupList.SelectedValue; + this.Model.ModuleSettings["FilterValue"] = this.groupList.SelectedValue; break; case "Relationship": - Model.ModuleSettings["FilterValue"] = relationShipList.SelectedValue; + this.Model.ModuleSettings["FilterValue"] = this.relationShipList.SelectedValue; break; case "ProfileProperty": - Model.ModuleSettings["FilterValue"] = propertyList.SelectedValue; + this.Model.ModuleSettings["FilterValue"] = this.propertyList.SelectedValue; break; } - Model.ModuleSettings["FilterPropertyValue"] = propertyValue.Text; + this.Model.ModuleSettings["FilterPropertyValue"] = this.propertyValue.Text; + + this.Model.TabModuleSettings["SortField"] = this.sortFieldList.SelectedValue; + this.Model.TabModuleSettings["SortOrder"] = this.sortOrderList.SelectedValue; - Model.TabModuleSettings["SortField"] = sortFieldList.SelectedValue; - Model.TabModuleSettings["SortOrder"] = sortOrderList.SelectedValue; + this.Model.TabModuleSettings["SearchField1"] = this.searchField1List.SelectedValue; + this.Model.TabModuleSettings["SearchField2"] = this.searchField2List.SelectedValue; + this.Model.TabModuleSettings["SearchField3"] = this.searchField3List.SelectedValue; + this.Model.TabModuleSettings["SearchField4"] = this.searchField4List.SelectedValue; + this.Model.TabModuleSettings["DisplaySearch"] = this.displaySearchList.SelectedValue; - Model.TabModuleSettings["SearchField1"] = searchField1List.SelectedValue; - Model.TabModuleSettings["SearchField2"] = searchField2List.SelectedValue; - Model.TabModuleSettings["SearchField3"] = searchField3List.SelectedValue; - Model.TabModuleSettings["SearchField4"] = searchField4List.SelectedValue; - Model.TabModuleSettings["DisplaySearch"] = displaySearchList.SelectedValue; + this.Model.TabModuleSettings["DisablePaging"] = this.disablePager.Checked.ToString(CultureInfo.InvariantCulture); + this.Model.TabModuleSettings["PageSize"] = this.pageSize.Text; - Model.TabModuleSettings["DisablePaging"] = disablePager.Checked.ToString(CultureInfo.InvariantCulture); - Model.TabModuleSettings["PageSize"] = pageSize.Text; - - Model.TabModuleSettings["ExcludeHostUsers"] = ExcludeHostUsersCheckBox.Checked.ToString(CultureInfo.InvariantCulture); + this.Model.TabModuleSettings["ExcludeHostUsers"] = this.ExcludeHostUsersCheckBox.Checked.ToString(CultureInfo.InvariantCulture); base.OnSavingSettings(); } + private ListItemCollection GetPropertiesCollection(string profileResourceFile) + { + var result = new ListItemCollection(); + foreach (var property in this.Model.ProfileProperties) + { + result.Add(new ListItem(this.GetLocalizeName(property.PropertyName, profileResourceFile), property.PropertyName)); + } + + return result; + } + private string GetLocalizeName(string propertyName, string resourceFile) { var name = Localization.GetString("ProfileProperties_" + propertyName, resourceFile); @@ -264,33 +258,34 @@ private string GetLocalizeName(string propertyName, string resourceFile) private void BindSortList() { - sortFieldList.Items.Add(AddSearchItem("UserId")); - sortFieldList.Items.Add(AddSearchItem("LastName")); - sortFieldList.Items.Add(AddSearchItem("DisplayName")); - sortFieldList.Items.Add(AddSearchItem("CreatedOnDate", "DateCreated")); + this.sortFieldList.Items.Add(this.AddSearchItem("UserId")); + this.sortFieldList.Items.Add(this.AddSearchItem("LastName")); + this.sortFieldList.Items.Add(this.AddSearchItem("DisplayName")); + this.sortFieldList.Items.Add(this.AddSearchItem("CreatedOnDate", "DateCreated")); var controller = new ListController(); var imageDataType = controller.GetListEntryInfo("DataType", "Image"); - foreach (ProfilePropertyDefinition definition in Model.ProfileProperties) + foreach (ProfilePropertyDefinition definition in this.Model.ProfileProperties) { if (imageDataType != null && definition.DataType != imageDataType.EntryID) { - sortFieldList.Items.Add(AddSearchItem(definition.PropertyName)); + this.sortFieldList.Items.Add(this.AddSearchItem(definition.PropertyName)); } } } private ListItem AddSearchItem(string name) { - return AddSearchItem(name, name); + return this.AddSearchItem(name, name); } private ListItem AddSearchItem(string name, string resourceKey) { - var text = Localization.GetString(resourceKey, LocalResourceFile); - if (String.IsNullOrEmpty(text)) + var text = Localization.GetString(resourceKey, this.LocalResourceFile); + if (string.IsNullOrEmpty(text)) { text = resourceKey; } + var item = new ListItem(text, name); return item; } diff --git a/DNN Platform/Modules/MemberDirectory/View.ascx.cs b/DNN Platform/Modules/MemberDirectory/View.ascx.cs index e596201f2ac..9bb03aca794 100644 --- a/DNN Platform/Modules/MemberDirectory/View.ascx.cs +++ b/DNN Platform/Modules/MemberDirectory/View.ascx.cs @@ -1,71 +1,79 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Reflection; -using System.Web.Routing; -using System.Web.UI; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.MemberDirectory { + using System; + using System.Collections; + using System.Reflection; + using System.Web.Routing; + using System.Web.UI; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Client.ClientResourceManagement; + public partial class View : ProfileModuleUserControlBase { - protected override void OnInit(EventArgs e) + public override bool DisplayModule { - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); - JavaScript.RequestRegistration(CommonJs.Knockout); - - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/MemberDirectory/Scripts/MemberDirectory.js"); - AddIe7StyleSheet(); - - searchBar.Visible = DisplaySearch != "None"; - advancedSearchBar.Visible = DisplaySearch == "Both"; - popUpPanel.Visible = EnablePopUp; - loadMore.Visible = !DisablePaging; - - base.OnInit(e); + get + { + return !(this.ProfileUserId == this.ModuleContext.PortalSettings.UserId && this.FilterBy == "User") && this.ModuleContext.PortalSettings.UserId > -1; + } } + public string ProfileResourceFile + { + get { return "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx"; } + } + protected string AlternateItemTemplate { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "AlternateItemTemplate", Settings.DefaultAlternateItemTemplate); } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "AlternateItemTemplate", Settings.DefaultAlternateItemTemplate); } } protected bool DisablePaging { - get { return bool.Parse(GetSetting(ModuleContext.Configuration.TabModuleSettings, "DisablePaging", "false")); } + get { return bool.Parse(this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "DisablePaging", "false")); } } protected string DisplaySearch { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "DisplaySearch", "Both"); } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "DisplaySearch", "Both"); } + } + + protected override void OnInit(EventArgs e) + { + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); + JavaScript.RequestRegistration(CommonJs.Knockout); + + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/MemberDirectory/Scripts/MemberDirectory.js"); + this.AddIe7StyleSheet(); + + this.searchBar.Visible = this.DisplaySearch != "None"; + this.advancedSearchBar.Visible = this.DisplaySearch == "Both"; + this.popUpPanel.Visible = this.EnablePopUp; + this.loadMore.Visible = !this.DisablePaging; + + base.OnInit(e); } protected bool EnablePopUp { - get { return bool.Parse(GetSetting(ModuleContext.Configuration.TabModuleSettings, "EnablePopUp", "false")); } + get { return bool.Parse(this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "EnablePopUp", "false")); } } protected string FilterBy { - get { return GetSetting(ModuleContext.Configuration.ModuleSettings, "FilterBy", "None"); } + get { return this.GetSetting(this.ModuleContext.Configuration.ModuleSettings, "FilterBy", "None"); } } protected int GroupId @@ -73,43 +81,31 @@ protected int GroupId get { int groupId = Null.NullInteger; - if (!string.IsNullOrEmpty(Request.Params["GroupId"])) + if (!string.IsNullOrEmpty(this.Request.Params["GroupId"])) { - groupId = Int32.Parse(Request.Params["GroupId"]); + groupId = int.Parse(this.Request.Params["GroupId"]); } + return groupId; } } protected string ItemTemplate { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "ItemTemplate", Settings.DefaultItemTemplate); } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "ItemTemplate", Settings.DefaultItemTemplate); } } protected int PageSize { get { - return GetSettingAsInt32(ModuleContext.Configuration.TabModuleSettings, "PageSize", Settings.DefaultPageSize); + return this.GetSettingAsInt32(this.ModuleContext.Configuration.TabModuleSettings, "PageSize", Settings.DefaultPageSize); } } protected string PopUpTemplate { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "PopUpTemplate", Settings.DefaultPopUpTemplate); } - } - - public override bool DisplayModule - { - get - { - return !(ProfileUserId == ModuleContext.PortalSettings.UserId && FilterBy == "User") && ModuleContext.PortalSettings.UserId > -1; - } - } - - public string ProfileResourceFile - { - get { return "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx"; } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "PopUpTemplate", Settings.DefaultPopUpTemplate); } } protected string ProfileUrlUserToken @@ -122,61 +118,58 @@ protected string ProfileUrlUserToken protected string SearchField1 { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "SearchField1", "DisplayName"); } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "SearchField1", "DisplayName"); } } protected string SearchField2 { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "SearchField2", "Email"); } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "SearchField2", "Email"); } } protected string SearchField3 { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "SearchField3", "City"); } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "SearchField3", "City"); } } protected string SearchField4 { - get { return GetSetting(ModuleContext.Configuration.TabModuleSettings, "SearchField4", "Country"); } + get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "SearchField4", "Country"); } } protected string ViewProfileUrl { get { - return NavigationManager.NavigateURL(ModuleContext.PortalSettings.UserTabId, "", "userId=PROFILEUSER"); + return this.NavigationManager.NavigateURL(this.ModuleContext.PortalSettings.UserTabId, string.Empty, "userId=PROFILEUSER"); } } - protected bool DisablePrivateMessage - { - get - { - return PortalSettings.DisablePrivateMessage && !UserInfo.IsSuperUser - && !UserInfo.IsInRole(PortalSettings.AdministratorRoleName); - - } - } - - protected PortalSettings PortalSettings - { - get { return PortalController.Instance.GetCurrentPortalSettings(); } - } - - protected UserInfo UserInfo - { - get { return UserController.Instance.GetCurrentUserInfo(); } - } + protected bool DisablePrivateMessage + { + get + { + return this.PortalSettings.DisablePrivateMessage && !this.UserInfo.IsSuperUser + && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName); + } + } - #region Private Helper Functions + protected PortalSettings PortalSettings + { + get { return PortalController.Instance.GetCurrentPortalSettings(); } + } + protected UserInfo UserInfo + { + get { return UserController.Instance.GetCurrentUserInfo(); } + } + private void AddIe7StyleSheet() { - var browser = Request.Browser; + var browser = this.Request.Browser; if (browser.Type == "IE" || browser.MajorVersion < 8) { const string cssLink = @""; - Page.Header.Controls.Add(new LiteralControl(cssLink)); + this.Page.Header.Controls.Add(new LiteralControl(cssLink)); } } @@ -187,6 +180,7 @@ private string GetSetting(Hashtable settings, string key, string defaultValue) { setting = Convert.ToString(settings[key]); } + return setting; } @@ -197,9 +191,8 @@ private int GetSettingAsInt32(Hashtable settings, string key, int defaultValue) { setting = Convert.ToInt32(settings[key]); } + return setting; - } - - #endregion + } } } diff --git a/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs b/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs index 370544dedcc..3d2dae84849 100644 --- a/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs +++ b/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Security.Roles; -using DotNetNuke.Web.Mvp; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.MemberDirectory.ViewModels { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Security.Roles; + using DotNetNuke.Web.Mvp; + [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public class MemberDirectorySettingsModel : SettingsModel { diff --git a/DNN Platform/Modules/MemberDirectory/packages.config b/DNN Platform/Modules/MemberDirectory/packages.config index e94ef92b0b5..2e66578e1e2 100644 --- a/DNN Platform/Modules/MemberDirectory/packages.config +++ b/DNN Platform/Modules/MemberDirectory/packages.config @@ -1,9 +1,10 @@ - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs index 368093bc405..406babb8f74 100644 --- a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs @@ -1,23 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using Microsoft.Extensions.DependencyInjection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.RazorHost { + using System; + using System.IO; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public partial class AddScript : ModuleUserControlBase { @@ -26,12 +21,7 @@ public partial class AddScript : ModuleUserControlBase public AddScript() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - private void DisplayExtension() - { - fileExtension.Text = "." + scriptFileType.SelectedValue.ToLowerInvariant(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] @@ -39,9 +29,9 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - cmdCancel.Click += cmdCancel_Click; - cmdAdd.Click += cmdAdd_Click; - scriptFileType.SelectedIndexChanged += scriptFileType_SelectedIndexChanged; + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdAdd.Click += this.cmdAdd_Click; + this.scriptFileType.SelectedIndexChanged += this.scriptFileType_SelectedIndexChanged; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] @@ -49,7 +39,12 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - DisplayExtension(); + this.DisplayExtension(); + } + + private void DisplayExtension() + { + this.fileExtension.Text = "." + this.scriptFileType.SelectedValue.ToLowerInvariant(); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] @@ -57,9 +52,9 @@ protected void cmdCancel_Click(object sender, EventArgs e) { try { - Response.Redirect(ModuleContext.EditUrl("Edit"), true); + this.Response.Redirect(this.ModuleContext.EditUrl("Edit"), true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -70,27 +65,27 @@ protected void cmdAdd_Click(object sender, EventArgs e) { try { - if (!ModuleContext.PortalSettings.UserInfo.IsSuperUser) + if (!this.ModuleContext.PortalSettings.UserInfo.IsSuperUser) { - Response.Redirect(_navigationManager.NavigateURL("Access Denied"), true); + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); } - if (Page.IsValid) + if (this.Page.IsValid) { - string scriptFileName = "_" + Path.GetFileNameWithoutExtension(fileName.Text) + "." + scriptFileType.SelectedValue.ToLowerInvariant(); + string scriptFileName = "_" + Path.GetFileNameWithoutExtension(this.fileName.Text) + "." + this.scriptFileType.SelectedValue.ToLowerInvariant(); - string srcFile = Server.MapPath(string.Format(razorScriptFileFormatString, scriptFileName)); + string srcFile = this.Server.MapPath(string.Format(this.razorScriptFileFormatString, scriptFileName)); // write file StreamWriter objStream = null; objStream = File.CreateText(srcFile); - objStream.WriteLine(Localization.GetString("NewScript", LocalResourceFile)); + objStream.WriteLine(Localization.GetString("NewScript", this.LocalResourceFile)); objStream.Close(); - Response.Redirect(ModuleContext.EditUrl("Edit"), true); + this.Response.Redirect(this.ModuleContext.EditUrl("Edit"), true); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -98,7 +93,7 @@ protected void cmdAdd_Click(object sender, EventArgs e) private void scriptFileType_SelectedIndexChanged(object sender, EventArgs e) { - DisplayExtension(); + this.DisplayExtension(); } } } diff --git a/DNN Platform/Modules/RazorHost/AssemblyInfo.cs b/DNN Platform/Modules/RazorHost/AssemblyInfo.cs index f066a4f7e8c..dd893557e48 100644 --- a/DNN Platform/Modules/RazorHost/AssemblyInfo.cs +++ b/DNN Platform/Modules/RazorHost/AssemblyInfo.cs @@ -1,25 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System.Reflection; -using System.Runtime.InteropServices; - -#endregion - -// 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. - -// Review the values of the assembly attributes - +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. + +// Review the values of the assembly attributes [assembly: AssemblyTitle("DotNetNuke.Modules.RazorHostView")] [assembly: AssemblyDescription("Razor Host Module")] [assembly: ComVisible(false)] -//The following GUID is for the ID of the typelib if this project is exposed to COM - -[assembly: Guid("dba19364-20c8-49ec-9c3a-69008fe699f6")] - +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("dba19364-20c8-49ec-9c3a-69008fe699f6")] diff --git a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs index e9fde1e82bd..bd635fe9a12 100644 --- a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs +++ b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs @@ -1,37 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Web.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Installer; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.RazorHost { + using System; + using System.Collections.Generic; + using System.IO; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Installer; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public partial class CreateModule : ModuleUserControlBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CreateModule)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CreateModule)); private readonly INavigationManager _navigationManager; private string razorScriptFileFormatString = "~/DesktopModules/RazorModules/RazorHost/Scripts/{0}"; @@ -39,7 +34,7 @@ public partial class CreateModule : ModuleUserControlBase public CreateModule() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] @@ -47,7 +42,7 @@ protected string ModuleControl { get { - return Path.GetFileNameWithoutExtension(scriptList.SelectedValue).TrimStart('_') + ".ascx"; + return Path.GetFileNameWithoutExtension(this.scriptList.SelectedValue).TrimStart('_') + ".ascx"; } } @@ -57,50 +52,78 @@ protected string RazorScriptFile get { string m_RazorScriptFile = Null.NullString; - var scriptFileSetting = ModuleContext.Settings["ScriptFile"] as string; - if (! (string.IsNullOrEmpty(scriptFileSetting))) + var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; + if (!string.IsNullOrEmpty(scriptFileSetting)) { - m_RazorScriptFile = string.Format(razorScriptFileFormatString, scriptFileSetting); + m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); } + return m_RazorScriptFile; } } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdCreate.Click += this.cmdCreate_Click; + this.scriptList.SelectedIndexChanged += this.scriptList_SelectedIndexChanged; + } + + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + if (!this.ModuleContext.PortalSettings.UserInfo.IsSuperUser) + { + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + } + + if (!this.Page.IsPostBack) + { + this.LoadScripts(); + this.DisplayFile(); + } + } + private void Create() { - //Create new Folder - string folderMapPath = Server.MapPath(string.Format("~/DesktopModules/RazorModules/{0}", txtFolder.Text)); + // Create new Folder + string folderMapPath = this.Server.MapPath(string.Format("~/DesktopModules/RazorModules/{0}", this.txtFolder.Text)); if (Directory.Exists(folderMapPath)) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("FolderExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("FolderExists", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } else { - //Create folder + // Create folder Directory.CreateDirectory(folderMapPath); } - //Create new Module Control - string moduleControlMapPath = folderMapPath + "/" + ModuleControl; + // Create new Module Control + string moduleControlMapPath = folderMapPath + "/" + this.ModuleControl; try { using (var moduleControlWriter = new StreamWriter(moduleControlMapPath)) { - moduleControlWriter.Write(Localization.GetString("ModuleControlText.Text", LocalResourceFile)); + moduleControlWriter.Write(Localization.GetString("ModuleControlText.Text", this.LocalResourceFile)); moduleControlWriter.Flush(); } } catch (Exception ex) { Exceptions.LogException(ex); - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ModuleControlCreationError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ModuleControlCreationError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - //Copy Script to new Folder - string scriptSourceFile = Server.MapPath(string.Format(razorScriptFileFormatString, scriptList.SelectedValue)); - string scriptTargetFile = folderMapPath + "/" + scriptList.SelectedValue; + // Copy Script to new Folder + string scriptSourceFile = this.Server.MapPath(string.Format(this.razorScriptFileFormatString, this.scriptList.SelectedValue)); + string scriptTargetFile = folderMapPath + "/" + this.scriptList.SelectedValue; try { File.Copy(scriptSourceFile, scriptTargetFile); @@ -108,64 +131,63 @@ private void Create() catch (Exception ex) { Exceptions.LogException(ex); - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ScriptCopyError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ScriptCopyError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - //Create new Manifest in target folder - string manifestMapPath = folderMapPath + "/" + ModuleControl.Replace(".ascx", ".dnn"); - try - { - using (var manifestWriter = new StreamWriter(manifestMapPath)) - { - string manifestTemplate = Localization.GetString("ManifestText.Text", LocalResourceFile); - string manifest = string.Format(manifestTemplate, txtName.Text, txtDescription.Text, txtFolder.Text, ModuleControl, scriptList.SelectedValue); - manifestWriter.Write(manifest); - manifestWriter.Flush(); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ManifestCreationError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - return; - } - - //Register Module - ModuleDefinitionInfo moduleDefinition = ImportManifest(manifestMapPath); - - //remove the manifest file - try - { - FileWrapper.Instance.Delete(manifestMapPath); - } - catch (Exception ex) - { - Logger.Error(ex); - } - - - //Optionally goto new Page - if (chkAddPage.Checked) + // Create new Manifest in target folder + string manifestMapPath = folderMapPath + "/" + this.ModuleControl.Replace(".ascx", ".dnn"); + try + { + using (var manifestWriter = new StreamWriter(manifestMapPath)) + { + string manifestTemplate = Localization.GetString("ManifestText.Text", this.LocalResourceFile); + string manifest = string.Format(manifestTemplate, this.txtName.Text, this.txtDescription.Text, this.txtFolder.Text, this.ModuleControl, this.scriptList.SelectedValue); + manifestWriter.Write(manifest); + manifestWriter.Flush(); + } + } + catch (Exception ex) { - string tabName = "Test " + txtName.Text + " Page"; + Exceptions.LogException(ex); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ManifestCreationError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + return; + } + + // Register Module + ModuleDefinitionInfo moduleDefinition = this.ImportManifest(manifestMapPath); + + // remove the manifest file + try + { + FileWrapper.Instance.Delete(manifestMapPath); + } + catch (Exception ex) + { + Logger.Error(ex); + } + + // Optionally goto new Page + if (this.chkAddPage.Checked) + { + string tabName = "Test " + this.txtName.Text + " Page"; string tabPath = Globals.GenerateTabPath(Null.NullInteger, tabName); - int tabID = TabController.GetTabByTabPath(ModuleContext.PortalId, tabPath, ModuleContext.PortalSettings.CultureCode); + int tabID = TabController.GetTabByTabPath(this.ModuleContext.PortalId, tabPath, this.ModuleContext.PortalSettings.CultureCode); if (tabID == Null.NullInteger) { - //Create a new page + // Create a new page var newTab = new TabInfo(); - newTab.TabName = "Test " + txtName.Text + " Page"; + newTab.TabName = "Test " + this.txtName.Text + " Page"; newTab.ParentId = Null.NullInteger; - newTab.PortalID = ModuleContext.PortalId; + newTab.PortalID = this.ModuleContext.PortalId; newTab.IsVisible = true; - newTab.TabID = TabController.Instance.AddTabBefore(newTab, ModuleContext.PortalSettings.AdminTabId); + newTab.TabID = TabController.Instance.AddTabBefore(newTab, this.ModuleContext.PortalSettings.AdminTabId); var objModule = new ModuleInfo(); - objModule.Initialize(ModuleContext.PortalId); + objModule.Initialize(this.ModuleContext.PortalId); - objModule.PortalID = ModuleContext.PortalId; + objModule.PortalID = this.ModuleContext.PortalId; objModule.TabID = newTab.TabID; objModule.ModuleOrder = Null.NullInteger; objModule.ModuleTitle = moduleDefinition.FriendlyName; @@ -175,17 +197,17 @@ private void Create() objModule.AllTabs = false; ModuleController.Instance.AddModule(objModule); - Response.Redirect(_navigationManager.NavigateURL(newTab.TabID), true); + this.Response.Redirect(this._navigationManager.NavigateURL(newTab.TabID), true); } else { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabExists", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } } else { - //Redirect to main extensions page - Response.Redirect(_navigationManager.NavigateURL(), true); + // Redirect to main extensions page + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } } @@ -194,14 +216,14 @@ private ModuleDefinitionInfo ImportManifest(string manifest) ModuleDefinitionInfo moduleDefinition = null; try { - var _Installer = new Installer(manifest, Request.MapPath("."), true); + var _Installer = new Installer(manifest, this.Request.MapPath("."), true); if (_Installer.IsValid) { - //Reset Log + // Reset Log _Installer.InstallerInfo.Log.Logs.Clear(); - //Install + // Install _Installer.Install(); if (_Installer.IsValid) @@ -218,20 +240,20 @@ private ModuleDefinitionInfo ImportManifest(string manifest) } else { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InstallError.Text", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - phInstallLogs.Controls.Add(_Installer.InstallerInfo.Log.GetLogsTable()); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InstallError.Text", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + this.phInstallLogs.Controls.Add(_Installer.InstallerInfo.Log.GetLogsTable()); } } else { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InstallError.Text", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - phInstallLogs.Controls.Add(_Installer.InstallerInfo.Log.GetLogsTable()); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InstallError.Text", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + this.phInstallLogs.Controls.Add(_Installer.InstallerInfo.Log.GetLogsTable()); } } catch (Exception exc) { Exceptions.LogException(exc); - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ImportControl.ErrorMessage", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ImportControl.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } return moduleDefinition; @@ -239,63 +261,37 @@ private ModuleDefinitionInfo ImportManifest(string manifest) private void LoadScripts() { - string basePath = Server.MapPath(razorScriptFolder); - var scriptFileSetting = ModuleContext.Settings["ScriptFile"] as string; + string basePath = this.Server.MapPath(this.razorScriptFolder); + var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; - foreach (string script in Directory.GetFiles(Server.MapPath(razorScriptFolder), "*.??html")) + foreach (string script in Directory.GetFiles(this.Server.MapPath(this.razorScriptFolder), "*.??html")) { - string scriptPath = script.Replace(basePath, ""); + string scriptPath = script.Replace(basePath, string.Empty); var item = new ListItem(scriptPath, scriptPath); - if (! (string.IsNullOrEmpty(scriptFileSetting)) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) + if (!string.IsNullOrEmpty(scriptFileSetting) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) { item.Selected = true; } - scriptList.Items.Add(item); + + this.scriptList.Items.Add(item); } } private void DisplayFile() { - string scriptFile = string.Format(razorScriptFileFormatString, scriptList.SelectedValue); - - lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", LocalResourceFile), scriptFile); - lblModuleControl.Text = string.Format(Localization.GetString("SourceControl", LocalResourceFile), ModuleControl); - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - cmdCancel.Click += cmdCancel_Click; - cmdCreate.Click += cmdCreate_Click; - scriptList.SelectedIndexChanged += scriptList_SelectedIndexChanged; - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); + string scriptFile = string.Format(this.razorScriptFileFormatString, this.scriptList.SelectedValue); - if (! ModuleContext.PortalSettings.UserInfo.IsSuperUser) - { - Response.Redirect(_navigationManager.NavigateURL("Access Denied"), true); - } - - if (! Page.IsPostBack) - { - LoadScripts(); - DisplayFile(); - } + this.lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", this.LocalResourceFile), scriptFile); + this.lblModuleControl.Text = string.Format(Localization.GetString("SourceControl", this.LocalResourceFile), this.ModuleControl); } private void cmdCancel_Click(object sender, EventArgs e) { try { - Response.Redirect(_navigationManager.NavigateURL(), true); + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -305,17 +301,17 @@ private void cmdCreate_Click(object sender, EventArgs e) { try { - if (! ModuleContext.PortalSettings.UserInfo.IsSuperUser) + if (!this.ModuleContext.PortalSettings.UserInfo.IsSuperUser) { - Response.Redirect(_navigationManager.NavigateURL("Access Denied"), true); + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); } - if (Page.IsValid) + if (this.Page.IsValid) { - Create(); + this.Create(); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -323,7 +319,7 @@ private void cmdCreate_Click(object sender, EventArgs e) private void scriptList_SelectedIndexChanged(object sender, EventArgs e) { - DisplayFile(); + this.DisplayFile(); } } } diff --git a/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj b/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj index 7f61d63974f..cb460f99ef3 100644 --- a/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj +++ b/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj @@ -1,248 +1,256 @@ - - - - - Debug - AnyCPU - - - - - {94C9A90C-C0E9-41D0-AC33-FA5B35CB9C7D} - {349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - Properties - - - DotNetNuke.Modules.RazorHost - v4.7.2 - Custom - false - - - 4.0 - - - - - - - - - true - full - DEBUG;TRACE - bin\ - bin\DotNetNuke.Modules.RazorHost.XML - 4 - 1591 - 7 - - - pdbonly - TRACE - true - bin\ - bin\DotNetNuke.Modules.RazorHost.XML - 1591 - 7 - - - - - - - - - On - - - - False - ..\..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll - - - ..\..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll - - - ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - - - - - - - - - - ..\..\Components\Telerik\bin\Telerik.Web.UI.dll - False - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SolutionInfo.cs - - - - AddScript.ascx - - - AddScript.ascx - aspxcodebehind - - - CreateModule.ascx - - - CreateModule.ascx - aspxcodebehind - - - EditScript.ascx - - - EditScript.ascx - aspxcodebehind - - - RazorHost.ascx - - - RazorHost.ascx - ASPXCodeBehind - - - - Settings.ascx - - - Settings.ascx - aspxcodebehind - - - - - - - - - - - - - - - Designer - - - - - Designer - - - - - - - - - - - - - - - - - - - - - - - - - - {6928a9b1-f88a-4581-a132-d3eb38669bb0} - DotNetNuke.Abstractions - - - {9806c125-8ca9-48cc-940a-ccd0442c5993} - DotNetNuke.Web.Razor - - - {B1699614-39D4-468A-AB1D-A2FBA97CADDF} - DotNetNuke.Web - False - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - - - - - - - - - - - - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - False - True - 60155 - / - - - False - True - http://localhost/DNN_Platform - False - - - - - + + + + + Debug + AnyCPU + + + + + {94C9A90C-C0E9-41D0-AC33-FA5B35CB9C7D} + {349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + Library + Properties + + + DotNetNuke.Modules.RazorHost + v4.7.2 + Custom + false + + + 4.0 + + + + + + + + + + true + full + DEBUG;TRACE + bin\ + bin\DotNetNuke.Modules.RazorHost.XML + 4 + 1591 + 7 + + + pdbonly + TRACE + true + bin\ + bin\DotNetNuke.Modules.RazorHost.XML + 1591 + 7 + + + + + + + + + On + + + + False + ..\..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll + + + ..\..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll + + + ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + + + + + + + + ..\..\Components\Telerik\bin\Telerik.Web.UI.dll + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SolutionInfo.cs + + + + AddScript.ascx + + + AddScript.ascx + aspxcodebehind + + + CreateModule.ascx + + + CreateModule.ascx + aspxcodebehind + + + EditScript.ascx + + + EditScript.ascx + aspxcodebehind + + + RazorHost.ascx + + + RazorHost.ascx + ASPXCodeBehind + + + + Settings.ascx + + + Settings.ascx + aspxcodebehind + + + + + + + + + + + + + + + stylecop.json + + + Designer + + + + + Designer + + + + + + + + + + + + + + + + + + + + + + + + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + + + {9806c125-8ca9-48cc-940a-ccd0442c5993} + DotNetNuke.Web.Razor + + + {B1699614-39D4-468A-AB1D-A2FBA97CADDF} + DotNetNuke.Web + False + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + + + + + + + + + + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + False + True + 60155 + / + + + False + True + http://localhost/DNN_Platform + False + + + + + \ No newline at end of file diff --git a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs index 05df9ae999b..7eb84b83271 100644 --- a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs @@ -1,26 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.RazorHost { + using System; + using System.IO; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public partial class EditScript : ModuleUserControlBase { @@ -30,7 +25,7 @@ public partial class EditScript : ModuleUserControlBase public EditScript() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] @@ -39,89 +34,91 @@ protected string RazorScriptFile get { string m_RazorScriptFile = Null.NullString; - var scriptFileSetting = ModuleContext.Settings["ScriptFile"] as string; - if (!(string.IsNullOrEmpty(scriptFileSetting))) + var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; + if (!string.IsNullOrEmpty(scriptFileSetting)) { - m_RazorScriptFile = string.Format(razorScriptFileFormatString, scriptFileSetting); + m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); } + return m_RazorScriptFile; } } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdSave.Click += this.cmdSave_Click; + this.cmdSaveClose.Click += this.cmdSaveClose_Click; + this.cmdAdd.Click += this.cmdAdd_Click; + this.scriptList.SelectedIndexChanged += this.scriptList_SelectedIndexChanged; + } + + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + if (!this.Page.IsPostBack) + { + this.LoadScripts(); + this.DisplayFile(); + } + } + private void LoadScripts() { - string basePath = Server.MapPath(razorScriptFolder); - var scriptFileSetting = ModuleContext.Settings["ScriptFile"] as string; + string basePath = this.Server.MapPath(this.razorScriptFolder); + var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; - foreach (string script in Directory.GetFiles(Server.MapPath(razorScriptFolder), "*.??html")) + foreach (string script in Directory.GetFiles(this.Server.MapPath(this.razorScriptFolder), "*.??html")) { - string scriptPath = script.Replace(basePath, ""); + string scriptPath = script.Replace(basePath, string.Empty); var item = new ListItem(scriptPath, scriptPath); - if (!(string.IsNullOrEmpty(scriptFileSetting)) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) + if (!string.IsNullOrEmpty(scriptFileSetting) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) { item.Selected = true; } - scriptList.Items.Add(item); + + this.scriptList.Items.Add(item); } } private void DisplayFile() { - var scriptFileSetting = ModuleContext.Settings["ScriptFile"] as string; - string scriptFile = string.Format(razorScriptFileFormatString, scriptList.SelectedValue); - string srcFile = Server.MapPath(scriptFile); + var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; + string scriptFile = string.Format(this.razorScriptFileFormatString, this.scriptList.SelectedValue); + string srcFile = this.Server.MapPath(scriptFile); - lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", LocalResourceFile), scriptFile); + this.lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", this.LocalResourceFile), scriptFile); StreamReader objStreamReader = null; objStreamReader = File.OpenText(srcFile); - txtSource.Text = objStreamReader.ReadToEnd(); + this.txtSource.Text = objStreamReader.ReadToEnd(); objStreamReader.Close(); - if (!(string.IsNullOrEmpty(scriptFileSetting))) + if (!string.IsNullOrEmpty(scriptFileSetting)) { - isCurrentScript.Checked = (scriptList.SelectedValue.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()); + this.isCurrentScript.Checked = this.scriptList.SelectedValue.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant(); } } private void SaveScript() { - string srcFile = Server.MapPath(string.Format(razorScriptFileFormatString, scriptList.SelectedValue)); + string srcFile = this.Server.MapPath(string.Format(this.razorScriptFileFormatString, this.scriptList.SelectedValue)); // write file StreamWriter objStream = null; objStream = File.CreateText(srcFile); - objStream.WriteLine(txtSource.Text); + objStream.WriteLine(this.txtSource.Text); objStream.Close(); - if (isCurrentScript.Checked) + if (this.isCurrentScript.Checked) { - //Update setting - ModuleController.Instance.UpdateModuleSetting(ModuleContext.ModuleId, "ScriptFile", scriptList.SelectedValue); - } - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - cmdCancel.Click += cmdCancel_Click; - cmdSave.Click += cmdSave_Click; - cmdSaveClose.Click += cmdSaveClose_Click; - cmdAdd.Click += cmdAdd_Click; - scriptList.SelectedIndexChanged += scriptList_SelectedIndexChanged; - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - if (!Page.IsPostBack) - { - LoadScripts(); - DisplayFile(); + // Update setting + ModuleController.Instance.UpdateModuleSetting(this.ModuleContext.ModuleId, "ScriptFile", this.scriptList.SelectedValue); } } @@ -129,9 +126,9 @@ private void cmdCancel_Click(object sender, EventArgs e) { try { - Response.Redirect(_navigationManager.NavigateURL(), true); + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -141,9 +138,9 @@ private void cmdSave_Click(object sender, EventArgs e) { try { - SaveScript(); + this.SaveScript(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -153,10 +150,10 @@ private void cmdSaveClose_Click(object sender, EventArgs e) { try { - SaveScript(); - Response.Redirect(_navigationManager.NavigateURL(), true); + this.SaveScript(); + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -166,9 +163,9 @@ private void cmdAdd_Click(object sender, EventArgs e) { try { - Response.Redirect(ModuleContext.EditUrl("Add"), true); + this.Response.Redirect(this.ModuleContext.EditUrl("Add"), true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -176,9 +173,7 @@ private void cmdAdd_Click(object sender, EventArgs e) private void scriptList_SelectedIndexChanged(object sender, EventArgs e) { - DisplayFile(); + this.DisplayFile(); } - - } } diff --git a/DNN Platform/Modules/RazorHost/Manifest.dnn b/DNN Platform/Modules/RazorHost/Manifest.dnn index 7c035b102ce..cfc393afdf5 100644 --- a/DNN Platform/Modules/RazorHost/Manifest.dnn +++ b/DNN Platform/Modules/RazorHost/Manifest.dnn @@ -1,6 +1,6 @@  - + {0} {1} diff --git a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs index 206c028ec50..3054eeaec5a 100644 --- a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs +++ b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs @@ -1,72 +1,67 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Security; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Razor; -using System; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.RazorHost { + using System; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Security; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Razor; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public partial class RazorHost : RazorModuleBase, IActionable { private string razorScriptFileFormatString = "~/DesktopModules/RazorModules/RazorHost/Scripts/{0}"; - + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override string RazorScriptFile + public ModuleActionCollection ModuleActions { get { - string m_RazorScriptFile = base.RazorScriptFile; - var scriptFileSetting = ModuleContext.Settings["ScriptFile"] as string; - if (! (string.IsNullOrEmpty(scriptFileSetting))) - { - m_RazorScriptFile = string.Format(razorScriptFileFormatString, scriptFileSetting); - } - return m_RazorScriptFile; + var Actions = new ModuleActionCollection(); + Actions.Add( + this.ModuleContext.GetNextActionID(), + Localization.GetString(ModuleActionType.EditContent, this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "edit.gif", + this.ModuleContext.EditUrl(), + false, + SecurityAccessLevel.Host, + true, + false); + Actions.Add( + this.ModuleContext.GetNextActionID(), + Localization.GetString("CreateModule.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "edit.gif", + this.ModuleContext.EditUrl("CreateModule"), + false, + SecurityAccessLevel.Host, + true, + false); + return Actions; } - } - - #region IActionable Members + } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public ModuleActionCollection ModuleActions + protected override string RazorScriptFile { get { - var Actions = new ModuleActionCollection(); - Actions.Add(ModuleContext.GetNextActionID(), - Localization.GetString(ModuleActionType.EditContent, LocalResourceFile), - ModuleActionType.AddContent, - "", - "edit.gif", - ModuleContext.EditUrl(), - false, - SecurityAccessLevel.Host, - true, - false); - Actions.Add(ModuleContext.GetNextActionID(), - Localization.GetString("CreateModule.Action", LocalResourceFile), - ModuleActionType.AddContent, - "", - "edit.gif", - ModuleContext.EditUrl("CreateModule"), - false, - SecurityAccessLevel.Host, - true, - false); - return Actions; + string m_RazorScriptFile = base.RazorScriptFile; + var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; + if (!string.IsNullOrEmpty(scriptFileSetting)) + { + m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); + } + + return m_RazorScriptFile; } - } - - #endregion + } } } diff --git a/DNN Platform/Modules/RazorHost/RazorHost.dnn b/DNN Platform/Modules/RazorHost/RazorHost.dnn index 12e74d48d8d..b9c5e656927 100644 --- a/DNN Platform/Modules/RazorHost/RazorHost.dnn +++ b/DNN Platform/Modules/RazorHost/RazorHost.dnn @@ -1,6 +1,6 @@  - + Razor Host The Razor Host module allows developers to host Razor Scripts. diff --git a/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs b/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs index c66eaa66b7d..80235e66cf9 100644 --- a/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs +++ b/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs @@ -1,39 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.UI; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.RazorHost { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public static class RazorHostSettingsExtensions { [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public static Settings LoadRazorSettingsControl(this UserControl parent, ModuleInfo configuration, string localResourceFile) { - var control = (Settings) parent.LoadControl("~/DesktopModules/RazorModules/RazorHost/Settings.ascx"); + var control = (Settings)parent.LoadControl("~/DesktopModules/RazorModules/RazorHost/Settings.ascx"); control.ModuleConfiguration = configuration; control.LocalResourceFile = localResourceFile; EnsureEditScriptControlIsRegistered(configuration.ModuleDefID); return control; } - - + private static void EnsureEditScriptControlIsRegistered(int moduleDefId) { - if (ModuleControlController.GetModuleControlByControlKey("EditRazorScript", moduleDefId) != null) return; - var m = new ModuleControlInfo - { - ControlKey = "EditRazorScript", - ControlSrc = "DesktopModules/RazorModules/RazorHost/EditScript.ascx", - ControlTitle = "Edit Script", - ControlType = SecurityAccessLevel.Host, - ModuleDefID = moduleDefId - }; + if (ModuleControlController.GetModuleControlByControlKey("EditRazorScript", moduleDefId) != null) + { + return; + } + + var m = new ModuleControlInfo + { + ControlKey = "EditRazorScript", + ControlSrc = "DesktopModules/RazorModules/RazorHost/EditScript.ascx", + ControlTitle = "Edit Script", + ControlType = SecurityAccessLevel.Host, + ModuleDefID = moduleDefId, + }; ModuleControlController.UpdateModuleControl(m); } } diff --git a/DNN Platform/Modules/RazorHost/Settings.ascx.cs b/DNN Platform/Modules/RazorHost/Settings.ascx.cs index 655a1192361..81bdf8f15d7 100644 --- a/DNN Platform/Modules/RazorHost/Settings.ascx.cs +++ b/DNN Platform/Modules/RazorHost/Settings.ascx.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.RazorHost { + using System; + using System.IO; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Modules; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public partial class Settings : ModuleSettingsBase { @@ -22,18 +17,19 @@ public partial class Settings : ModuleSettingsBase [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public override void LoadSettings() { - string basePath = Server.MapPath(razorScriptFolder); - var scriptFileSetting = Settings["ScriptFile"] as string; + string basePath = this.Server.MapPath(this.razorScriptFolder); + var scriptFileSetting = this.Settings["ScriptFile"] as string; - foreach (string script in Directory.GetFiles(Server.MapPath(razorScriptFolder), "*.??html")) + foreach (string script in Directory.GetFiles(this.Server.MapPath(this.razorScriptFolder), "*.??html")) { - string scriptPath = script.Replace(basePath, ""); + string scriptPath = script.Replace(basePath, string.Empty); var item = new ListItem(scriptPath, scriptPath); - if (! (string.IsNullOrEmpty(scriptFileSetting)) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) + if (!string.IsNullOrEmpty(scriptFileSetting) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) { item.Selected = true; } - scriptList.Items.Add(item); + + this.scriptList.Items.Add(item); } base.LoadSettings(); @@ -42,7 +38,7 @@ public override void LoadSettings() [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public override void UpdateSettings() { - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ScriptFile", scriptList.SelectedValue); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ScriptFile", this.scriptList.SelectedValue); } } } diff --git a/DNN Platform/Modules/RazorHost/packages.config b/DNN Platform/Modules/RazorHost/packages.config index 015e7e36813..4fca05e5f8c 100644 --- a/DNN Platform/Modules/RazorHost/packages.config +++ b/DNN Platform/Modules/RazorHost/packages.config @@ -1,5 +1,6 @@ - - - - + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs index 0d6b0edb7d9..737a1a01349 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs @@ -1,42 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Facebook.Components { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + public class FacebookClient : OAuthClientBase - { - #region Constructors - - public FacebookClient(int portalId, AuthMode mode) + { + public FacebookClient(int portalId, AuthMode mode) : base(portalId, mode, "Facebook") { - TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token"); - TokenMethod = HttpMethod.GET; - AuthorizationEndpoint = new Uri("https://graph.facebook.com/oauth/authorize"); - MeGraphEndpoint = new Uri("https://graph.facebook.com/me?fields=id,name,email,first_name,last_name,link,birthday,gender,locale,timezone,updated_time"); + this.TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token"); + this.TokenMethod = HttpMethod.GET; + this.AuthorizationEndpoint = new Uri("https://graph.facebook.com/oauth/authorize"); + this.MeGraphEndpoint = new Uri("https://graph.facebook.com/me?fields=id,name,email,first_name,last_name,link,birthday,gender,locale,timezone,updated_time"); - Scope = "email"; + this.Scope = "email"; - AuthTokenName = "FacebookUserToken"; - - OAuthVersion = "2.0"; - - LoadTokenCookie(String.Empty); - } + this.AuthTokenName = "FacebookUserToken"; - #endregion + this.OAuthVersion = "2.0"; + this.LoadTokenCookie(string.Empty); + } + protected override TimeSpan GetExpiry(string responseText) { TimeSpan expiry = TimeSpan.MinValue; @@ -45,17 +37,19 @@ protected override TimeSpan GetExpiry(string responseText) var dictionary = Json.Deserialize>(responseText); expiry = new TimeSpan(0, 0, Convert.ToInt32(dictionary["expires_in"])); } + return expiry; } protected override string GetToken(string responseText) { - string authToken = String.Empty; + string authToken = string.Empty; if (!string.IsNullOrEmpty(responseText)) { var dictionary = Json.Deserialize>(responseText); authToken = Convert.ToString(dictionary["access_token"]); } + return authToken; } } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs index ed87a63d6fd..7d28ae96d4b 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs @@ -1,37 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Runtime.Serialization; - -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Facebook.Components { + using System; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Authentication.OAuth; + [DataContract] public class FacebookUserData : UserData - { - #region Overrides - + { public override string FirstName { - get { return FacebookFirstName; } + get { return this.FacebookFirstName; } set { } } public override string LastName { - get { return FacebookLastName; } + get { return this.FacebookLastName; } set { } - } - - #endregion - + } + [DataMember(Name = "birthday")] public string Birthday { get; set; } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj index 8c315f13e55..6bace8d1ad3 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj @@ -25,6 +25,7 @@ + true @@ -99,8 +100,12 @@ + + stylecop.json + + @@ -119,6 +124,10 @@ False + + + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Facebook_Auth.dnn b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Facebook_Auth.dnn index e1c1e1d1acc..c9e49383d47 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Facebook_Auth.dnn +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Facebook_Auth.dnn @@ -1,6 +1,6 @@ - + DotNetNuke Facebook Authentication Project The DotNetNuke Facebook Authentication Project is an Authentication provider for DotNetNuke that uses Facebook authentication to authenticate users. diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs index 2297d37bd4a..4c55495c0eb 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs @@ -1,68 +1,64 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Specialized; -using DotNetNuke.Authentication.Facebook.Components; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Facebook { + using System; + using System.Collections.Specialized; + + using DotNetNuke.Authentication.Facebook.Components; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Facebook"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Facebook"; } + } protected override UserData GetCurrentUser() { - return OAuthClient.GetCurrentUser(); + return this.OAuthClient.GetCurrentUser(); } protected override void OnInit(EventArgs e) { base.OnInit(e); - loginButton.Click += loginButton_Click; - registerButton.Click += loginButton_Click; + this.loginButton.Click += this.loginButton_Click; + this.registerButton.Click += this.loginButton_Click; - OAuthClient = new FacebookClient(PortalId, Mode); + this.OAuthClient = new FacebookClient(this.PortalId, this.Mode); - loginItem.Visible = (Mode == AuthMode.Login); - registerItem.Visible = (Mode == AuthMode.Register); + this.loginItem.Visible = this.Mode == AuthMode.Login; + this.registerItem.Visible = this.Mode == AuthMode.Register; } protected override void AddCustomProperties(NameValueCollection properties) { base.AddCustomProperties(properties); - var facebookUserData = OAuthClient.GetCurrentUser(); - if (facebookUserData.Link != null) { + var facebookUserData = this.OAuthClient.GetCurrentUser(); + if (facebookUserData.Link != null) + { properties.Add("Facebook", facebookUserData.Link.ToString()); } } private void loginButton_Click(object sender, EventArgs e) { - AuthorisationResult result = OAuthClient.Authorize(); + AuthorisationResult result = this.OAuthClient.Authorize(); if (result == AuthorisationResult.Denied) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PrivateConfirmationMessage", Localization.SharedResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - } } } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Properties/AssemblyInfo.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Properties/AssemblyInfo.cs index 45a75aa6404..1301baef7e6 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Properties/AssemblyInfo.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Properties/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Authentication.Facebook")] [assembly: AssemblyDescription("")] -// 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 +// 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)] diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Settings.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Settings.ascx.cs index 89c19ca7e78..60ee7cdc761 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Settings.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Settings.ascx.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Facebook { + using System; + + using DotNetNuke.Services.Authentication.OAuth; + public partial class Settings : OAuthSettingsBase { protected override string AuthSystemApplicationName diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/packages.config b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs index f9a7cb0ed41..6ea653bb010 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs @@ -1,44 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; -using System.Web.Script.Serialization; - -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Google.Components { + using System; + using System.Collections.Generic; + using System.Web; + using System.Web.Script.Serialization; + + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + public class GoogleClient : OAuthClientBase - { - #region Constructors - - public GoogleClient(int portalId, AuthMode mode) + { + public GoogleClient(int portalId, AuthMode mode) : base(portalId, mode, "Google") { - TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"); - TokenMethod = HttpMethod.POST; - AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth"); - MeGraphEndpoint = new Uri("https://www.googleapis.com/oauth2/v1/userinfo"); - - Scope = HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"); + this.TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"); + this.TokenMethod = HttpMethod.POST; + this.AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth"); + this.MeGraphEndpoint = new Uri("https://www.googleapis.com/oauth2/v1/userinfo"); - AuthTokenName = "GoogleUserToken"; + this.Scope = HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"); - OAuthVersion = "2.0"; - - LoadTokenCookie(String.Empty); - } + this.AuthTokenName = "GoogleUserToken"; - #endregion + this.OAuthVersion = "2.0"; + this.LoadTokenCookie(string.Empty); + } + protected override TimeSpan GetExpiry(string responseText) { var jsonSerializer = new JavaScriptSerializer(); diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs index fb8a73c1f86..3bb6852c31a 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs @@ -1,42 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Runtime.Serialization; - -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Google.Components { + using System.Runtime.Serialization; + + using DotNetNuke.Services.Authentication.OAuth; + [DataContract] public class GoogleUserData : UserData - { - #region Overrides - + { public override string FirstName { - get { return GivenName; } + get { return this.GivenName; } set { } } public override string LastName { - get { return FamilyName; } + get { return this.FamilyName; } set { } } public override string ProfileImage { - get { return Picture; } + get { return this.Picture; } set { } - } - - #endregion - + } + [DataMember(Name = "given_name")] public string GivenName { get; set; } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj index 92348724b98..1d30862b058 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj @@ -1,143 +1,152 @@ - - - - - Debug - AnyCPU - - - 2.0 - {0304B44C-EA08-434E-A368-65F619FC67A5} - {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - DotNetNuke.Authentication.Google - DotNetNuke.Authentication.Google - v4.7.2 - false - - - - 4.0 - - - - - - - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - bin\DotNetNuke.Authentication.Google.XML - 1591 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - bin\DotNetNuke.Authentication.Google.XML - 1591 - 7 - - - - - - - - - - - - - - - - - - - - SolutionInfo.cs - - - - - Login.ascx - ASPXCodeBehind - - - Login.ascx - - - - Settings.ascx - ASPXCodeBehind - - - Settings.ascx - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - False - - - - - Designer - - - - - - - - - - - Designer - - - - - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - False - True - 26658 - / - - - False - True - http://localhost/DNN_Platform - False - - - - - + + + + + Debug + AnyCPU + + + 2.0 + {0304B44C-EA08-434E-A368-65F619FC67A5} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + DotNetNuke.Authentication.Google + DotNetNuke.Authentication.Google + v4.7.2 + false + + + + 4.0 + + + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + bin\DotNetNuke.Authentication.Google.XML + 1591 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + bin\DotNetNuke.Authentication.Google.XML + 1591 + 7 + + + + + + + + + + + + + + + + + + + + SolutionInfo.cs + + + + + Login.ascx + ASPXCodeBehind + + + Login.ascx + + + + Settings.ascx + ASPXCodeBehind + + + Settings.ascx + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + False + + + + + Designer + + + + + + + + + + + Designer + + + + + stylecop.json + + + + + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + False + True + 26658 + / + + + False + True + http://localhost/DNN_Platform + False + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Google_Auth.dnn b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Google_Auth.dnn index e9ad67b91b3..0335e398c32 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Google_Auth.dnn +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Google_Auth.dnn @@ -1,6 +1,6 @@ - + DotNetNuke Google Authentication Project The DotNetNuke Google Authentication Project is an Authentication provider for DotNetNuke that uses Google authentication to authenticate users. diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs index d1165788d07..4c328f94fb0 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs @@ -1,58 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Authentication.Google.Components; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Google { + using System; + + using DotNetNuke.Authentication.Google.Components; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Google"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Google"; } + } protected override UserData GetCurrentUser() { - return OAuthClient.GetCurrentUser(); + return this.OAuthClient.GetCurrentUser(); } protected override void OnInit(EventArgs e) { base.OnInit(e); - loginButton.Click += loginButton_Click; - registerButton.Click += loginButton_Click; + this.loginButton.Click += this.loginButton_Click; + this.registerButton.Click += this.loginButton_Click; - OAuthClient = new GoogleClient(PortalId, Mode); + this.OAuthClient = new GoogleClient(this.PortalId, this.Mode); - loginItem.Visible = (Mode == AuthMode.Login); - registerItem.Visible = (Mode == AuthMode.Register); + this.loginItem.Visible = this.Mode == AuthMode.Login; + this.registerItem.Visible = this.Mode == AuthMode.Register; } private void loginButton_Click(object sender, EventArgs e) { - AuthorisationResult result = OAuthClient.Authorize(); + AuthorisationResult result = this.OAuthClient.Authorize(); if (result == AuthorisationResult.Denied) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PrivateConfirmationMessage", Localization.SharedResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - } } } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Properties/AssemblyInfo.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Properties/AssemblyInfo.cs index ed5c04b9f66..db004941138 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Properties/AssemblyInfo.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Properties/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Authentication.Google")] [assembly: AssemblyDescription("")] -// 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 +// 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)] diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Settings.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Settings.ascx.cs index 228c48fd5b1..8bce5280a42 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Settings.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Settings.ascx.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Authentication.Google.Components; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Google { + using System; + + using DotNetNuke.Authentication.Google.Components; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Exceptions; + public partial class Settings : OAuthSettingsBase { protected override string AuthSystemApplicationName diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/packages.config b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs index 6daad535041..390aa06ff1c 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs @@ -1,45 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; -using System.Web.Script.Serialization; - -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.LiveConnect.Components { + using System; + using System.Collections.Generic; + using System.Web; + using System.Web.Script.Serialization; + + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + public class LiveClient : OAuthClientBase - { - #region Constructors - - public LiveClient(int portalId, AuthMode mode) : base(portalId, mode, "Live") + { + public LiveClient(int portalId, AuthMode mode) + : base(portalId, mode, "Live") { - //DNN-6464 Correct TokenEndpoint and AuthorizationEndpoint Urls + // DNN-6464 Correct TokenEndpoint and AuthorizationEndpoint Urls // Add TokenMethod of Post to conform to other OAuth extensions - TokenMethod = HttpMethod.POST; - TokenEndpoint = new Uri("https://login.live.com/oauth20_token.srf"); - AuthorizationEndpoint = new Uri("https://login.live.com/oauth20_authorize.srf"); - MeGraphEndpoint = new Uri("https://apis.live.net/v5.0/me"); - - Scope = HttpContext.Current.Server.UrlEncode("wl.signin wl.basic wl.emails"); + this.TokenMethod = HttpMethod.POST; + this.TokenEndpoint = new Uri("https://login.live.com/oauth20_token.srf"); + this.AuthorizationEndpoint = new Uri("https://login.live.com/oauth20_authorize.srf"); + this.MeGraphEndpoint = new Uri("https://apis.live.net/v5.0/me"); - AuthTokenName = "LiveUserToken"; + this.Scope = HttpContext.Current.Server.UrlEncode("wl.signin wl.basic wl.emails"); - OAuthVersion = "2.0"; - - LoadTokenCookie(String.Empty); - } + this.AuthTokenName = "LiveUserToken"; - #endregion + this.OAuthVersion = "2.0"; + this.LoadTokenCookie(string.Empty); + } + protected override TimeSpan GetExpiry(string responseText) { var jsonSerializer = new JavaScriptSerializer(); diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs index 937af695ef8..a5f50d71bd7 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs @@ -1,38 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Runtime.Serialization; -using System.Collections.Generic; - -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.LiveConnect.Components { + using System; + using System.Collections.Generic; + using System.Runtime.Serialization; + + using DotNetNuke.Services.Authentication.OAuth; + [DataContract] public class LiveUserData : UserData - { - #region Overrides - + { public override string FirstName { - get { return LiveFirstName; } + get { return this.LiveFirstName; } set { } } public override string LastName { - get { return LiveLastName; } + get { return this.LiveLastName; } set { } - } - - #endregion - + } + [DataMember(Name = "link")] public Uri Link { get; set; } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj index 1559e6ddb18..e81c69ab859 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj @@ -1,141 +1,150 @@ - - - - - Debug - AnyCPU - - - 2.0 - {46924A38-CAB7-485D-9301-191E35F6255F} - {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - DotNetNuke.Authentication.LiveConnect - DotNetNuke.Authentication.LiveConnect - v4.7.2 - false - - - - 4.0 - - - - - - - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - 1591 - bin\DotNetNuke.Authentication.LiveConnect.XML - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - 1591 - bin\DotNetNuke.Authentication.LiveConnect.XML - 7 - - - - - - - - - - - - - - - - - - SolutionInfo.cs - - - - - Login.ascx - ASPXCodeBehind - - - Login.ascx - - - - Settings.ascx - ASPXCodeBehind - - - Settings.ascx - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - False - - - - - Designer - - - - - - - - - - - Designer - - - - - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - False - True - 28864 - / - - - False - True - http://localhost/DNN_Platform - False - - - - - + + + + + Debug + AnyCPU + + + 2.0 + {46924A38-CAB7-485D-9301-191E35F6255F} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + DotNetNuke.Authentication.LiveConnect + DotNetNuke.Authentication.LiveConnect + v4.7.2 + false + + + + 4.0 + + + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + 1591 + bin\DotNetNuke.Authentication.LiveConnect.XML + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + 1591 + bin\DotNetNuke.Authentication.LiveConnect.XML + 7 + + + + + + + + + + + + + + + + + + SolutionInfo.cs + + + + + Login.ascx + ASPXCodeBehind + + + Login.ascx + + + + Settings.ascx + ASPXCodeBehind + + + Settings.ascx + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + False + + + + + Designer + + + + + + + + + + + Designer + + + + + stylecop.json + + + + + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + False + True + 28864 + / + + + False + True + http://localhost/DNN_Platform + False + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Live_Auth.dnn b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Live_Auth.dnn index fb34982f6b5..8d109f5f789 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Live_Auth.dnn +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Live_Auth.dnn @@ -1,6 +1,6 @@ - + DotNetNuke Live Authentication Project The DotNetNuke Live Authentication Project is an Authentication provider for DotNetNuke that uses diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs index 91536dbe8b9..0051d01ef6b 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs @@ -1,58 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Authentication.LiveConnect.Components; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.LiveConnect { + using System; + + using DotNetNuke.Authentication.LiveConnect.Components; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Live"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Live"; } + } protected override UserData GetCurrentUser() { - return OAuthClient.GetCurrentUser(); + return this.OAuthClient.GetCurrentUser(); } protected override void OnInit(EventArgs e) { base.OnInit(e); - loginButton.Click += loginButton_Click; - registerButton.Click += loginButton_Click; + this.loginButton.Click += this.loginButton_Click; + this.registerButton.Click += this.loginButton_Click; - OAuthClient = new LiveClient(PortalId, Mode); + this.OAuthClient = new LiveClient(this.PortalId, this.Mode); - loginItem.Visible = (Mode == AuthMode.Login); - registerItem.Visible = (Mode == AuthMode.Register); + this.loginItem.Visible = this.Mode == AuthMode.Login; + this.registerItem.Visible = this.Mode == AuthMode.Register; } private void loginButton_Click(object sender, EventArgs e) { - AuthorisationResult result = OAuthClient.Authorize(); + AuthorisationResult result = this.OAuthClient.Authorize(); if (result == AuthorisationResult.Denied) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PrivateConfirmationMessage", Localization.SharedResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - } } } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Properties/AssemblyInfo.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Properties/AssemblyInfo.cs index efa0af1c2a7..56589c47a72 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Properties/AssemblyInfo.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Properties/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Authentication.LiveConnect")] [assembly: AssemblyDescription("")] -// 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 +// 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)] diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Settings.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Settings.ascx.cs index 391c906fb5b..477eb5b48b2 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Settings.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Settings.ascx.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.LiveConnect { + using System; + + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Exceptions; + public partial class Settings : OAuthSettingsBase { protected override string AuthSystemApplicationName diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/packages.config b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterClient.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterClient.cs index f9788b3799e..c8ac38553d9 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterClient.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterClient.cs @@ -1,34 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Twitter.Components { + using System; + + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + public class TwitterClient : OAuthClientBase { public TwitterClient(int portalId, AuthMode mode) : base(portalId, mode, "Twitter") { - AuthorizationEndpoint = new Uri("https://api.twitter.com/oauth/authorize"); - RequestTokenEndpoint = new Uri("https://api.twitter.com/oauth/request_token"); - RequestTokenMethod = HttpMethod.POST; - TokenEndpoint = new Uri("https://api.twitter.com/oauth/access_token"); - MeGraphEndpoint = new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"); + this.AuthorizationEndpoint = new Uri("https://api.twitter.com/oauth/authorize"); + this.RequestTokenEndpoint = new Uri("https://api.twitter.com/oauth/request_token"); + this.RequestTokenMethod = HttpMethod.POST; + this.TokenEndpoint = new Uri("https://api.twitter.com/oauth/access_token"); + this.MeGraphEndpoint = new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"); - AuthTokenName = "TwitterUserToken"; + this.AuthTokenName = "TwitterUserToken"; - OAuthVersion = "1.0"; + this.OAuthVersion = "1.0"; - LoadTokenCookie(String.Empty); + this.LoadTokenCookie(string.Empty); } } } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs index 6546082083b..7f01a498645 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs @@ -1,48 +1,39 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Runtime.Serialization; - -using DotNetNuke.Services.Authentication.OAuth; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Twitter.Components { + using System.Runtime.Serialization; + + using DotNetNuke.Services.Authentication.OAuth; + [DataContract] public class TwitterUserData : UserData - { - #region Overrides - + { public override string DisplayName { - get { return ScreenName; } + get { return this.ScreenName; } set { } } public override string Locale { - get { return LanguageCode; } + get { return this.LanguageCode; } set { } } public override string ProfileImage { - get { return ProfileImageUrl; } + get { return this.ProfileImageUrl; } set { } } public override string Website { - get { return Url; } + get { return this.Url; } set { } - } - - #endregion - + } + [DataMember(Name = "screen_name")] public string ScreenName { get; set; } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj index fe16fc2d30e..0aaed56b295 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj @@ -1,144 +1,153 @@ - - - - - Debug - AnyCPU - - - 2.0 - {1C882AA9-2198-41EF-B325-605340FDEFE5} - {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - DotNetNuke.Authentication.Twitter - DotNetNuke.Authentication.Twitter - v4.7.2 - false - - - - 4.0 - - - - - - - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - bin\DotNetNuke.Authentication.Twitter.XML - 1591 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - 1591 - bin\DotNetNuke.Authentication.Twitter.XML - 7 - - - - - - - - - - - - - - - - - - - SolutionInfo.cs - - - - Login.ascx - ASPXCodeBehind - - - Login.ascx - - - - - Settings.ascx - ASPXCodeBehind - - - Settings.ascx - - - - - - - - - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - False - - - - - - - - - Designer - - - - - Designer - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - False - True - 26668 - / - - - False - True - http://localhost/DNN_Platform - False - - - - - + + + + + Debug + AnyCPU + + + 2.0 + {1C882AA9-2198-41EF-B325-605340FDEFE5} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + DotNetNuke.Authentication.Twitter + DotNetNuke.Authentication.Twitter + v4.7.2 + false + + + + 4.0 + + + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + bin\DotNetNuke.Authentication.Twitter.XML + 1591 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + 1591 + bin\DotNetNuke.Authentication.Twitter.XML + 7 + + + + + + + + + + + + + + + + + + + SolutionInfo.cs + + + + Login.ascx + ASPXCodeBehind + + + Login.ascx + + + + + Settings.ascx + ASPXCodeBehind + + + Settings.ascx + + + + + + + + + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + False + + + + + + stylecop.json + + + + + + + Designer + + + + + Designer + + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + False + True + 26668 + / + + + False + True + http://localhost/DNN_Platform + False + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs index 4cf74669986..9b386f7d239 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs @@ -1,66 +1,60 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Authentication.Twitter.Components; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Twitter { + using System; + + using DotNetNuke.Authentication.Twitter.Components; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Twitter"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Twitter"; } + } protected override UserData GetCurrentUser() { - return OAuthClient.GetCurrentUser(); + return this.OAuthClient.GetCurrentUser(); } protected override void AddCustomProperties(System.Collections.Specialized.NameValueCollection properties) { base.AddCustomProperties(properties); - properties.Add("Twitter", string.Format("http://twitter.com/{0}", OAuthClient.GetCurrentUser().ScreenName)); + properties.Add("Twitter", string.Format("http://twitter.com/{0}", this.OAuthClient.GetCurrentUser().ScreenName)); } protected override void OnInit(EventArgs e) { base.OnInit(e); - loginButton.Click += loginButton_Click; - registerButton.Click += loginButton_Click; + this.loginButton.Click += this.loginButton_Click; + this.registerButton.Click += this.loginButton_Click; - OAuthClient = new TwitterClient(PortalId, Mode); + this.OAuthClient = new TwitterClient(this.PortalId, this.Mode); - loginItem.Visible = (Mode == AuthMode.Login); - registerItem.Visible = (Mode == AuthMode.Register); + this.loginItem.Visible = this.Mode == AuthMode.Login; + this.registerItem.Visible = this.Mode == AuthMode.Register; } private void loginButton_Click(object sender, EventArgs e) { - OAuthClient.CallbackUri = new Uri(OAuthClient.CallbackUri + "?state=Twitter"); - AuthorisationResult result = OAuthClient.Authorize(); + this.OAuthClient.CallbackUri = new Uri(this.OAuthClient.CallbackUri + "?state=Twitter"); + AuthorisationResult result = this.OAuthClient.Authorize(); if (result == AuthorisationResult.Denied) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PrivateConfirmationMessage", Localization.SharedResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - } } } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Properties/AssemblyInfo.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Properties/AssemblyInfo.cs index 3d12e372538..38ed2dbcef7 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Properties/AssemblyInfo.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Properties/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Authentication.Twitter")] [assembly: AssemblyDescription("")] -// 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 +// 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)] diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Settings.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Settings.ascx.cs index 564fbcfc81d..fe5c8bf9fff 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Settings.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Settings.ascx.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Authentication.Twitter { + using System; + + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Exceptions; + public partial class Settings : OAuthSettingsBase { protected override string AuthSystemApplicationName diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Twitter_Auth.dnn b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Twitter_Auth.dnn index b892d974f61..2bc2765e051 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Twitter_Auth.dnn +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Twitter_Auth.dnn @@ -1,6 +1,6 @@ - + DotNetNuke Twitter Authentication Project The DotNetNuke Twitter Authentication Project is an Authentication provider for DotNetNuke that uses diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/packages.config b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj index 6040eba8cef..53a175a79f8 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj @@ -1,76 +1,84 @@ - - - - Debug - AnyCPU - {2C25580C-A971-4F0B-9F70-436A35C2473E} - Library - Properties - DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider - DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider - v4.7.2 - 512 - true - - - true - full - false - bin\Providers - DEBUG;TRACE - prompt - 4 - bin\Providers\DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.xml - 1591,0618 - 7 - - - pdbonly - true - bin\Providers - TRACE - prompt - 4 - bin\Providers\DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.xml - 1591,0618 - 7 - - - - - - - - - - - - - - - - - - - - Properties\SolutionInfo.cs - - - - - - - - - - {3cd5f6b8-8360-4862-80b6-f402892db7dd} - DotNetNuke.Instrumentation - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - - + + + + Debug + AnyCPU + {2C25580C-A971-4F0B-9F70-436A35C2473E} + Library + Properties + DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider + DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider + v4.7.2 + 512 + true + + + true + full + false + bin\Providers + DEBUG;TRACE + prompt + 4 + bin\Providers\DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.xml + 1591,0618 + 7 + + + pdbonly + true + bin\Providers + TRACE + prompt + 4 + bin\Providers\DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.xml + 1591,0618 + 7 + + + + + + + + + + + + + + + + + + + + Properties\SolutionInfo.cs + + + stylecop.json + + + + + + + + + + + {3cd5f6b8-8360-4862-80b6-f402892db7dd} + DotNetNuke.Instrumentation + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/Properties/AssemblyInfo.cs b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/Properties/AssemblyInfo.cs index f45cccbb772..23748cdba0b 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/Properties/AssemblyInfo.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/Properties/AssemblyInfo.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; -using System.Runtime.InteropServices; - -#endregion - +using System.Runtime.InteropServices; + [assembly: AssemblyTitle("DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider")] [assembly: AssemblyDescription("Open Source Web Application Framework")] [assembly: Guid("2c25580c-a971-4f0b-9f70-436a35c2473e")] diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs index 96cb2824236..9e5a2d48509 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs @@ -2,38 +2,107 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -using System; -using System.Linq; -using System.Net; -using System.Threading; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using HttpWebRequest = System.Net.HttpWebRequest; - namespace DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider { + using System; + using System.Linq; + using System.Net; + using System.Threading; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + + using HttpWebRequest = System.Net.HttpWebRequest; + public class SimpleWebFarmCachingProvider : CachingProvider { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SimpleWebFarmCachingProvider)); - private readonly int executionTimeout = 5000; //Limit timeout to 5 seconds as cache operations should be quick + private readonly int executionTimeout = 5000; // Limit timeout to 5 seconds as cache operations should be quick + + public override void Clear(string type, string data) + { + // Clear the local cache + this.ClearCacheInternal(type, data, true); + + // Per API implementation standards only notify others if expiration has not been desabled + if (CacheExpirationDisable) + { + return; + } + + // Notify other servers + this.NotifyOtherServers("Clear~" + type, data); + } - #region Server Notification Methods + public override void Remove(string key) + { + // Remove from local cache + this.RemoveInternal(key); + + // Per API implementation standards only notify others if expiration has not been disabled + if (CacheExpirationDisable) + { + return; + } + + // Notify Other Servers + this.NotifyOtherServers("Remove", key); + } + + /// + /// This method responds to an incoming request to process synchronization from an additional server. + /// + /// + /// This is internal as it should only be called from . + /// + /// The command to process, currently supported Remove and Clear~{Type}. + /// Additional detail to pass to the caching sub-system. + internal void ProcessSynchronizationRequest(string command, string detail) + { + // Handle basic removal + if (command.StartsWith("remove", StringComparison.OrdinalIgnoreCase)) + { + this.RemoveInternal(detail); + return; + } + // A clear method will have additional type information included, split using the ~ character + if (command.StartsWith("clear~", StringComparison.InvariantCultureIgnoreCase)) + { + var commandParts = command.Split('~'); + this.ClearCacheInternal(commandParts[1], detail, true); + } + } + + private static void HandleNotificationTimeout(object state, bool timedOut) + { + if (!timedOut) + { + return; + } + + // Abort if possible + var request = (HttpWebRequest)state; + request?.Abort(); + } + private void NotifyOtherServers(string command, string detail) { - //Do not send notifications to other servers if currently upgrading - if (Globals.Status != Globals.UpgradeStatus.None) - return; - - //Get all servers currently in the database that could be used for synchronization, excluding this one - // But focus on only servers that could be used for this application and notifications - // including activity within 60 minutes + // Do not send notifications to other servers if currently upgrading + if (Globals.Status != Globals.UpgradeStatus.None) + { + return; + } + + // Get all servers currently in the database that could be used for synchronization, excluding this one + // But focus on only servers that could be used for this application and notifications + // including activity within 60 minutes var lastActivityDate = DateTime.Now.AddHours(-1); var additionalServers = ServerController.GetEnabledServers() .Where(s => !string.IsNullOrWhiteSpace(s.Url) @@ -41,50 +110,54 @@ private void NotifyOtherServers(string command, string detail) && s.ServerName != Globals.ServerName) .ToList(); - //If we have no additional servers do nothing - if (additionalServers.Count == 0) - return; - - //Otherwise notify each server + // If we have no additional servers do nothing + if (additionalServers.Count == 0) + { + return; + } + + // Otherwise notify each server foreach (var server in additionalServers) { - //Setup parameters for sending - var commandParameter = (Host.DebugMode) ? command : UrlUtils.EncryptParameter(command, Host.GUID); - var detailParameter = (Host.DebugMode) ? detail : UrlUtils.EncryptParameter(detail, Host.GUID); + // Setup parameters for sending + var commandParameter = Host.DebugMode ? command : UrlUtils.EncryptParameter(command, Host.GUID); + var detailParameter = Host.DebugMode ? detail : UrlUtils.EncryptParameter(detail, Host.GUID); var protocol = HostController.Instance.GetBoolean("UseSSLForCacheSync", false) ? "https://" : "http://"; var notificationUrl = $"{protocol}{server.Url}/SimpleWebFarmSync.aspx?command={commandParameter}&detail={detailParameter}"; - //Build a webrequest + // Build a webrequest var notificationRequest = WebRequest.CreateHttp(notificationUrl); - //Create a cookie container so we can get cookies and use default credentials + // Create a cookie container so we can get cookies and use default credentials notificationRequest.CookieContainer = new CookieContainer(); notificationRequest.UseDefaultCredentials = true; - + // Start the asynchronous request - var result = (notificationRequest.BeginGetResponse(OnServerNotificationCompleteCallback, notificationRequest)); + var result = notificationRequest.BeginGetResponse(this.OnServerNotificationCompleteCallback, notificationRequest); - //Register timeout + // Register timeout // TODO: Review possible use of async/await C# 7 implementation - ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, HandleNotificationTimeout, notificationRequest, executionTimeout, true); + ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, HandleNotificationTimeout, notificationRequest, this.executionTimeout, true); } } private void OnServerNotificationCompleteCallback(IAsyncResult asynchronousResult) { - //Get the request from the state object + // Get the request from the state object var request = (HttpWebRequest)asynchronousResult.AsyncState; try { - //Get the response - using (var response = (HttpWebResponse) (request.EndGetResponse(asynchronousResult))) + // Get the response + using (var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) { - //If status code is ok do nothing - if (response.StatusCode == HttpStatusCode.OK) - return; - - //Otherwise log the failure + // If status code is ok do nothing + if (response.StatusCode == HttpStatusCode.OK) + { + return; + } + + // Otherwise log the failure Exceptions.LogException(new ApplicationException( $"Error sending cache server notification. Url: {request.RequestUri.AbsoluteUri} with a status code {response.StatusCode}")); } @@ -97,76 +170,5 @@ private void OnServerNotificationCompleteCallback(IAsyncResult asynchronousResul } } } - - - private static void HandleNotificationTimeout(object state, bool timedOut) - { - if (!timedOut) - return; - - //Abort if possible - var request = (HttpWebRequest) state; - request?.Abort(); - } - - #endregion - - #region Synchronization Implementation - - /// - /// This method responds to an incoming request to process synchronization from an additional server - /// - /// - /// This is internal as it should only be called from - /// - /// The command to process, currently supported Remove and Clear~{Type} - /// Additional detail to pass to the caching sub-system - internal void ProcessSynchronizationRequest(string command, string detail) - { - //Handle basic removal - if (command.StartsWith("remove", StringComparison.OrdinalIgnoreCase)) - { - RemoveInternal(detail); - return; - } - - //A clear method will have additional type information included, split using the ~ character - if (command.StartsWith("clear~", StringComparison.InvariantCultureIgnoreCase)) - { - var commandParts = command.Split('~'); - ClearCacheInternal(commandParts[1], detail, true); - } - } - #endregion - - #region Default Caching Implementation Overrides - - public override void Clear(string type, string data) - { - //Clear the local cache - ClearCacheInternal(type, data, true); - - //Per API implementation standards only notify others if expiration has not been desabled - if (CacheExpirationDisable) - return; - - //Notify other servers - NotifyOtherServers("Clear~" + type, data); - } - - public override void Remove(string key) - { - //Remove from local cache - RemoveInternal(key); - - //Per API implementation standards only notify others if expiration has not been disabled - if (CacheExpirationDisable) - return; - - //Notify Other Servers - NotifyOtherServers("Remove", key); - } - - #endregion } } diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.dnn b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.dnn index c5a07fbe771..11064ed0f78 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.dnn +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.dnn @@ -1,6 +1,6 @@  - + DotNetNuke Simple Web Farm Caching Provider DotNetNuke Simple Web Farm Caching Provider diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs index 9c9be2ed820..9cc193912cb 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs @@ -2,33 +2,45 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -using System.Web; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Services.Cache; - namespace DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider { + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Services.Cache; + /// /// This synchronization handler receives requests from other servers and passes them to the cache system for - /// processing. Error handling is purposefully allowed to bubble up from here to ensure the caller is notified + /// processing. Error handling is purposefully allowed to bubble up from here to ensure the caller is notified. /// public class SimpleWebFarmSynchronizationHandler : IHttpHandler { + /// + /// Gets a value indicating whether indicates that this handler can be reused for multiple requests. + /// + public bool IsReusable => true; + public void ProcessRequest(HttpContext context) { - //Validate the request for required inputs, return if no action possible - if (string.IsNullOrWhiteSpace(context.Request.QueryString["command"])) - return; //No command we cannot process - - if (string.IsNullOrWhiteSpace(context.Request.QueryString["detail"])) - return; //No action we cannot return - - //Only continue if our provider is current - if (!(CachingProvider.Instance() is Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)) - return; - - //Get the values, noting that if in debug we are not encrypted + // Validate the request for required inputs, return if no action possible + if (string.IsNullOrWhiteSpace(context.Request.QueryString["command"])) + { + return; // No command we cannot process + } + + if (string.IsNullOrWhiteSpace(context.Request.QueryString["detail"])) + { + return; // No action we cannot return + } + + // Only continue if our provider is current + if (!(CachingProvider.Instance() is Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)) + { + return; + } + + // Get the values, noting that if in debug we are not encrypted var command = Host.DebugMode ? context.Request.QueryString["command"] : UrlUtils.DecryptParameter(context.Request.QueryString["command"], Host.GUID); @@ -37,14 +49,9 @@ public void ProcessRequest(HttpContext context) ? context.Request.QueryString["detail"] : UrlUtils.DecryptParameter(context.Request.QueryString["detail"], Host.GUID); - //Pass the action on, if the current caching provider is ours - var provider = (Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider) CachingProvider.Instance(); + // Pass the action on, if the current caching provider is ours + var provider = (Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)CachingProvider.Instance(); provider.ProcessSynchronizationRequest(command, detail); } - - /// - /// Indicates that this handler can be reused for multiple requests - /// - public bool IsReusable => true; } -} \ No newline at end of file +} diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/packages.config b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs index 9986598c6bf..404883c9bde 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs @@ -1,129 +1,143 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Configuration; -using DotNetNuke.Instrumentation; -using DotNetNuke.Providers.AspNetClientCapabilityProvider.Properties; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.AspNetClientCapabilityProvider { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Configuration; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Providers.AspNetClientCapabilityProvider.Properties; + /// - /// AspNet Browser Implementation of IClientCapability + /// AspNet Browser Implementation of IClientCapability. /// public class AspNetClientCapability : Services.ClientCapability.ClientCapability { + // set all agent identifiers are in lowercase for faster comparison + private const string WindowsPcAgent = "windows nt"; + private const string WindowsPhoneAgent = "windows phone"; + private const string AndroidAgent = "android"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetClientCapability)); - private readonly IDictionary _properties; - - public override string this[string name] - { - get - { - if (_properties != null && _properties.ContainsKey(name)) - { - return _properties[name]; - } - - return (Capabilities != null && Capabilities.ContainsKey(name)) ? Capabilities[name] : string.Empty; - } - } - - #region Constructor + private static readonly Regex MobileCheck = + new Regex( + @"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", + RegexOptions.Compiled, TimeSpan.FromSeconds(2)); - /// + private static readonly Regex TabletRegex = new Regex("ipad|xoom|sch-i800|playbook|tablet|kindle|nexus", RegexOptions.Compiled, TimeSpan.FromSeconds(2)); + + private readonly IDictionary _properties; + + /// + /// Initializes a new instance of the class. /// Constructs a new instance of ClientCapability. /// public AspNetClientCapability(string userAgent, HttpCapabilitiesBase browserCaps) { - UserAgent = userAgent; + this.UserAgent = userAgent; if (browserCaps != null) { - ID = browserCaps.Id; - ScreenResolutionWidthInPixels = browserCaps.ScreenPixelsWidth; - ScreenResolutionHeightInPixels = browserCaps.ScreenPixelsHeight; - IsTouchScreen = false; - BrowserName = browserCaps.Browser; - if(browserCaps.Capabilities != null) - { - Capabilities = browserCaps.Capabilities.Cast() + this.ID = browserCaps.Id; + this.ScreenResolutionWidthInPixels = browserCaps.ScreenPixelsWidth; + this.ScreenResolutionHeightInPixels = browserCaps.ScreenPixelsHeight; + this.IsTouchScreen = false; + this.BrowserName = browserCaps.Browser; + if (browserCaps.Capabilities != null) + { + this.Capabilities = browserCaps.Capabilities.Cast() .ToDictionary(kvp => Convert.ToString(kvp.Key), kvp => Convert.ToString(kvp.Value)); } else { - Capabilities = new Dictionary(); + this.Capabilities = new Dictionary(); } - SupportsFlash = false; - HtmlPreferedDTD = null; + + this.SupportsFlash = false; + this.HtmlPreferedDTD = null; - if (UserAgent.Length < 4) + if (this.UserAgent.Length < 4) { return; } - var lowerAgent = UserAgent.ToLowerInvariant(); - IsMobile = browserCaps.IsMobileDevice || GetIfMobile(lowerAgent); - IsTablet = GetIfTablet(lowerAgent); + var lowerAgent = this.UserAgent.ToLowerInvariant(); + this.IsMobile = browserCaps.IsMobileDevice || GetIfMobile(lowerAgent); + this.IsTablet = GetIfTablet(lowerAgent); try { - DetectOperatingSystem(lowerAgent, Capabilities); + DetectOperatingSystem(lowerAgent, this.Capabilities); } catch (Exception ex) { Logger.Error(ex); } } - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Constructs a new instance of ClientCapability. /// - public AspNetClientCapability(HttpRequest request) : this(request.UserAgent ?? "", request.Browser) + public AspNetClientCapability(HttpRequest request) + : this(request.UserAgent ?? string.Empty, request.Browser) { - - } - - /// + } + + /// + /// Initializes a new instance of the class. /// Constructs a new instance of ClientCapability. /// public AspNetClientCapability(IDictionary properties) { - _properties = properties; + this._properties = properties; - if (_properties != null) + if (this._properties != null) { // Set Lite properties - ID = GetStringValue(_properties, "Id"); - IsMobile = GetBoolValue(_properties, "IsMobile"); - ScreenResolutionWidthInPixels = GetIntValue(_properties, "ScreenPixelsWidth"); - ScreenResolutionHeightInPixels = GetIntValue(_properties, "ScreenPixelsHeight"); + this.ID = GetStringValue(this._properties, "Id"); + this.IsMobile = GetBoolValue(this._properties, "IsMobile"); + this.ScreenResolutionWidthInPixels = GetIntValue(this._properties, "ScreenPixelsWidth"); + this.ScreenResolutionHeightInPixels = GetIntValue(this._properties, "ScreenPixelsHeight"); + // Set Premium properties - IsTablet = GetBoolValue(_properties, "IsTablet"); - IsTouchScreen = GetBoolValue(_properties, "HasTouchScreen"); - BrowserName = GetStringValue(_properties, "BrowserName"); - Capabilities = GetCapabilities(_properties); - - SupportsFlash = false; - HtmlPreferedDTD = null; - - //set IsMobile to false when IsTablet is true. - if (IsTablet) - IsMobile = false; + this.IsTablet = GetBoolValue(this._properties, "IsTablet"); + this.IsTouchScreen = GetBoolValue(this._properties, "HasTouchScreen"); + this.BrowserName = GetStringValue(this._properties, "BrowserName"); + this.Capabilities = GetCapabilities(this._properties); + + this.SupportsFlash = false; + this.HtmlPreferedDTD = null; + + // set IsMobile to false when IsTablet is true. + if (this.IsTablet) + { + this.IsMobile = false; + } } - } - - #endregion + } - #region Private Methods + public override string this[string name] + { + get + { + if (this._properties != null && this._properties.ContainsKey(name)) + { + return this._properties[name]; + } + return (this.Capabilities != null && this.Capabilities.ContainsKey(name)) ? this.Capabilities[name] : string.Empty; + } + } + /// /// Returns a dictionary of capability names and values as strings based on the object /// keys and values held in the browser capabilities provided. The value string may @@ -133,7 +147,7 @@ public AspNetClientCapability(IDictionary properties) /// Device related capabilities with property names and values converted to strings. private static IDictionary GetCapabilities(IDictionary properties) { - return properties.Keys.ToDictionary(key => key, key => String.Join(Constants.ValueSeperator, properties[key].ToArray())); + return properties.Keys.ToDictionary(key => key, key => string.Join(Constants.ValueSeperator, properties[key].ToArray())); } /// @@ -147,8 +161,11 @@ private static bool GetBoolValue(IDictionary properties, string { bool value; if (properties.ContainsKey(property) && - bool.TryParse(properties[property], out value)) - return value; + bool.TryParse(properties[property], out value)) + { + return value; + } + return false; } @@ -163,8 +180,11 @@ private static int GetIntValue(IDictionary properties, string pr { int value; if (properties.ContainsKey(property) && - int.TryParse(properties[property], out value)) - return value; + int.TryParse(properties[property], out value)) + { + return value; + } + return 0; } @@ -180,13 +200,6 @@ private static string GetStringValue(IDictionary properties, str return properties.ContainsKey(property) ? properties[property] : null; } - private static readonly Regex MobileCheck = - new Regex( - @"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", - RegexOptions.Compiled, TimeSpan.FromSeconds(2)); - - private static readonly Regex TabletRegex = new Regex("ipad|xoom|sch-i800|playbook|tablet|kindle|nexus", RegexOptions.Compiled, TimeSpan.FromSeconds(2)); - private static bool GetIfMobile(string userAgent) { return MobileCheck.IsMatch(userAgent); @@ -249,7 +262,7 @@ private static void DetectOperatingSystem(string userAgent, IDictionary - /// AspNet.BrowserDetector implementation of ClientCapabilityProvider + /// AspNet.BrowserDetector implementation of ClientCapabilityProvider. /// public class AspNetClientCapabilityProvider : ClientCapabilityProvider - { - #region Static Methods - + { private static readonly object _allCapabilitiesLock = new object(); private static IQueryable _allCapabilities; @@ -32,6 +26,16 @@ public class AspNetClientCapabilityProvider : ClientCapabilityProvider private static Dictionary> _allClientCapabilityValues; private static IDictionary _highPiorityCapabilityValues; + + private static IDictionary _dummyProperies; + + /// + /// Gets a value indicating whether indicates whether tablet detection is supported in the available data set. + /// + public override bool SupportsTabletDetection + { + get { return false; } + } private static IQueryable AllCapabilities { @@ -43,11 +47,12 @@ private static IQueryable AllCapabilities { if (_allCapabilities == null) { - var capabilities = new List {new AspNetClientCapability(HttpContext.Current.Request)}; + var capabilities = new List { new AspNetClientCapability(HttpContext.Current.Request) }; _allCapabilities = capabilities.AsQueryable(); } } } + return _allCapabilities; } } @@ -64,12 +69,12 @@ private static IDictionary> ClientCapabilityValues { _allClientCapabilityValues = new Dictionary>(); - //TODO :Implement - //foreach (var property in DataProvider.Properties) - //{ + // TODO :Implement + // foreach (var property in DataProvider.Properties) + // { // var values = property.Values.Select(value => value.Name).ToList(); // _allClientCapabilityValues.Add(property.Name, values); - //} + // } } } @@ -81,6 +86,7 @@ private static IDictionary> ClientCapabilityValues { return HighPiorityCapabilityValues[kvp.Key]; } + return 0; }).ThenBy(kvp => kvp.Key).ToDictionary(pair => pair.Key, pair => pair.Value); } @@ -95,25 +101,19 @@ private static IDictionary HighPiorityCapabilityValues { return _highPiorityCapabilityValues ?? (_highPiorityCapabilityValues = new Dictionary { - {"IsMobile", 100}, - {"IsTablet", 95}, - {"PlatformName", 90}, - {"BrowserName", 85}, - {"BrowserVersion", 80}, - {"HasTouchScreen", 75}, - {"PlatformVersion", 70}, - {"ScreenPixelsWidth", 65}, - {"ScreenPixelsHeight", 60}, - {"HardwareVendor", 55} + { "IsMobile", 100 }, + { "IsTablet", 95 }, + { "PlatformName", 90 }, + { "BrowserName", 85 }, + { "BrowserVersion", 80 }, + { "HasTouchScreen", 75 }, + { "PlatformVersion", 70 }, + { "ScreenPixelsWidth", 65 }, + { "ScreenPixelsHeight", 60 }, + { "HardwareVendor", 55 }, }); } - } - - #endregion - - #region ClientCapabilityProvider Override Methods - - private static IDictionary _dummyProperies; + } private static IDictionary DummyProperties { @@ -122,21 +122,34 @@ private static IDictionary DummyProperties return _dummyProperies ?? (_dummyProperies = new Dictionary { - {"Id", "UNKNOWN"}, - {"IsMobile", "false"}, - {"ScreenPixelsWidth", "600"}, - {"ScreenPixelsHeight", "800"}, - {"IsTablet", "false"}, - {"HasTouchScreen", "false"}, - {"BrowserName", "???"}, - {"SupportsFlash", "false"}, + { "Id", "UNKNOWN" }, + { "IsMobile", "false" }, + { "ScreenPixelsWidth", "600" }, + { "ScreenPixelsHeight", "800" }, + { "IsTablet", "false" }, + { "HasTouchScreen", "false" }, + { "BrowserName", "???" }, + { "SupportsFlash", "false" }, }); } } + + public static HttpBrowserCapabilities GetHttpBrowserCapabilities(NameValueCollection headers, string userAgent) + { + var factory = new BrowserCapabilitiesFactory(); + var browserCaps = new HttpBrowserCapabilities(); + var hashtable = new Hashtable(180, StringComparer.OrdinalIgnoreCase); + hashtable[string.Empty] = userAgent; + browserCaps.Capabilities = hashtable; + factory.ConfigureBrowserCapabilities(headers, browserCaps); + factory.ConfigureCustomCapabilities(headers, browserCaps); + return browserCaps; + } /// /// Returns ClientCapability based on the user agent provided. - /// + /// + /// public override IClientCapability GetClientCapability(string userAgent) { if (string.IsNullOrEmpty(userAgent)) @@ -149,7 +162,8 @@ public override IClientCapability GetClientCapability(string userAgent) /// /// Returns ClientCapability based on device Id provided. - /// + /// + /// public override IClientCapability GetClientCapabilityById(string deviceId) { Requires.NotNullOrEmpty("deviceId", deviceId); @@ -158,57 +172,26 @@ public override IClientCapability GetClientCapabilityById(string deviceId) } /// - /// Returns available Capability Values for every Capability Name + /// Returns available Capability Values for every Capability Name. /// /// - /// Dictionary of Capability Name along with List of possible values of the Capability + /// Dictionary of Capability Name along with List of possible values of the Capability. /// - /// Capability Name = mobile_browser, value = Safari, Andriod Webkit + /// Capability Name = mobile_browser, value = Safari, Andriod Webkit. public override IDictionary> GetAllClientCapabilityValues() { return ClientCapabilityValues; } /// - /// Returns All available Client Capabilities present + /// Returns All available Client Capabilities present. /// /// - /// List of IClientCapability present + /// List of IClientCapability present. /// public override IQueryable GetAllClientCapabilities() { return AllCapabilities; - } - - #endregion - - #region Override Properties - - /// - /// Indicates whether tablet detection is supported in the available data set. - /// - public override bool SupportsTabletDetection - { - get { return false; } - } - - #endregion - - #region Private Methods - - - public static HttpBrowserCapabilities GetHttpBrowserCapabilities(NameValueCollection headers, string userAgent) - { - var factory = new BrowserCapabilitiesFactory(); - var browserCaps = new HttpBrowserCapabilities(); - var hashtable = new Hashtable(180, StringComparer.OrdinalIgnoreCase); - hashtable[string.Empty] = userAgent; - browserCaps.Capabilities = hashtable; - factory.ConfigureBrowserCapabilities(headers, browserCaps); - factory.ConfigureCustomCapabilities(headers, browserCaps); - return browserCaps; - } - - #endregion + } } } diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.dnn b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.dnn index 27e40225f92..7e80353a1a9 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.dnn +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.dnn @@ -1,6 +1,6 @@ - + DotNetNuke ASP.NET Client Capability Provider ASP.NET Device Detection / Client Capability Provider ~/Providers/ClientCapabilityProviders/AspNetClientCapabilityProvider/Images/mobiledevicedet_32X32.png diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs index 3e7b1b73eb3..3b2666fe18c 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs @@ -1,26 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Providers.AspNetClientCapabilityProvider.Properties; -using DotNetNuke.Services.Installer; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mobile; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.AspNetClientCapabilityProvider.Components { - + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Providers.AspNetClientCapabilityProvider.Properties; + using DotNetNuke.Services.Installer; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mobile; + /// ----------------------------------------------------------------------------- - /// + /// /// The FeatureController class for the modules. /// /// @@ -28,17 +27,10 @@ namespace DotNetNuke.Providers.AspNetClientCapabilityProvider.Components /// /// /// ----------------------------------------------------------------------------- - public class FeatureController : IUpgradeable - { - #region Constants - - private const string ResourceFileRelativePath = "~/Providers/ClientCapabilityProviders/AspNetClientCapabilityProvider/App_LocalResources/SharedResources.resx"; - - #endregion - - #region Interfaces - + { + private const string ResourceFileRelativePath = "~/Providers/ClientCapabilityProviders/AspNetClientCapabilityProvider/App_LocalResources/SharedResources.resx"; + /// /// Handles upgrading the module and adding the module to the hosts menu. /// @@ -52,16 +44,44 @@ public string UpgradeModule(string version) var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == Constants.PackageName); var moduleTabs = TabController.Instance.GetTabsByPackageID(-1, package.PackageID, false); - if (moduleTabs.Count > 0) - return string.Empty; - - RemoveWurflProvider(); + if (moduleTabs.Count > 0) + { + return string.Empty; + } + + this.RemoveWurflProvider(); break; } return Localization.GetString("SuccessMessage", ResourceFileRelativePath); } + private static IDictionary CreateMappedCapabilities() + { + var mappingCapabilites = new Dictionary + { + { "is_wireless_device", "IsMobile" }, + { "resolution_width", "ScreenPixelsWidth" }, + { "resolution_height", "ScreenPixelsHeight" }, + }; + + if (DotNetNukeContext.Current.Application.Name != "DNNCORP.CE") + { + mappingCapabilites.Add("is_tablet", "IsTablet"); + mappingCapabilites.Add("device_os", "PlatformName"); + mappingCapabilites.Add("mobile_browser", "BrowserName"); + mappingCapabilites.Add("mobile_browser_version", "BrowserVersion"); + mappingCapabilites.Add("device_os_version", "PlatformVersion"); + mappingCapabilites.Add("brand_name", "HardwareVendor"); + mappingCapabilites.Add("cookie_support", "CookiesCapable"); + mappingCapabilites.Add("model_name", "HardwareModel"); + mappingCapabilites.Add("physical_screen_height", "ScreenMMHeight"); + mappingCapabilites.Add("physical_screen_width", "ScreenMMWidth"); + } + + return mappingCapabilites; + } + private void RemoveWurflProvider() { var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.WURFLClientCapabilityProvider"); @@ -71,7 +91,7 @@ private void RemoveWurflProvider() installer.UnInstall(true); } - UpdateRules(); + this.UpdateRules(); } private void UpdateRules() @@ -123,7 +143,7 @@ private void UpdateRules() } } - //remove the deleted rules + // remove the deleted rules foreach (var deletedRule in deletedRules) { controller.DeleteRule(redirection.PortalId, redirection.Id, deletedRule.Id); @@ -133,32 +153,5 @@ private void UpdateRules() controller.Save(redirection); } } - - private static IDictionary CreateMappedCapabilities() - { - var mappingCapabilites = new Dictionary - { - {"is_wireless_device", "IsMobile"}, - {"resolution_width", "ScreenPixelsWidth"}, - {"resolution_height", "ScreenPixelsHeight"} - }; - - if (DotNetNukeContext.Current.Application.Name != "DNNCORP.CE") - { - mappingCapabilites.Add("is_tablet", "IsTablet"); - mappingCapabilites.Add("device_os", "PlatformName"); - mappingCapabilites.Add("mobile_browser", "BrowserName"); - mappingCapabilites.Add("mobile_browser_version", "BrowserVersion"); - mappingCapabilites.Add("device_os_version", "PlatformVersion"); - mappingCapabilites.Add("brand_name", "HardwareVendor"); - mappingCapabilites.Add("cookie_support", "CookiesCapable"); - mappingCapabilites.Add("model_name", "HardwareModel"); - mappingCapabilites.Add("physical_screen_height", "ScreenMMHeight"); - mappingCapabilites.Add("physical_screen_width", "ScreenMMWidth"); - } - return mappingCapabilites; - } - - #endregion } } diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj index e13a9cc5093..f4dd6a0c49d 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj @@ -1,133 +1,141 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {A3B3F1E8-6C1A-4E35-A5B4-51ECC5A43AF7} - Library - DotNetNuke.Providers.AspNetClientCapabilityProvider - DotNetNuke.Providers.AspNetClientCapabilityProvider - v4.7.2 - - - - true - full - TRACE;DEBUG - bin\Providers\ - 4 - bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml - 1591,0618 - 7 - - - pdbonly - TRACE - true - bin\Providers\ - bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml - prompt - 1591,0618 - 7 - - - true - full - DEBUG;TRACE;CLOUD;CLOUD_DEBUG - bin\Providers\ - 4 - bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml - 1591,0618 - 7 - - - pdbonly - TRACE;CLOUD;CLOUD_RELEASE - true - bin\Providers\ - bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml - prompt - 1591,0618 - 7 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Properties\SolutionInfo.cs - - - - - - - - - - - Designer - - - - - - - - - - - - - - - {3cd5f6b8-8360-4862-80b6-f402892db7dd} - DotNetNuke.Instrumentation - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {A3B3F1E8-6C1A-4E35-A5B4-51ECC5A43AF7} + Library + DotNetNuke.Providers.AspNetClientCapabilityProvider + DotNetNuke.Providers.AspNetClientCapabilityProvider + v4.7.2 + + + + true + full + TRACE;DEBUG + bin\Providers\ + 4 + bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml + 1591,0618 + 7 + + + pdbonly + TRACE + true + bin\Providers\ + bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml + prompt + 1591,0618 + 7 + + + true + full + DEBUG;TRACE;CLOUD;CLOUD_DEBUG + bin\Providers\ + 4 + bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml + 1591,0618 + 7 + + + pdbonly + TRACE;CLOUD;CLOUD_RELEASE + true + bin\Providers\ + bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml + prompt + 1591,0618 + 7 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Properties\SolutionInfo.cs + + + + + + + + + + + stylecop.json + + + Designer + + + + + + + + + + + + + + + + {3cd5f6b8-8360-4862-80b6-f402892db7dd} + DotNetNuke.Instrumentation + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/AssemblyInfo.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/AssemblyInfo.cs index 203e2e4febd..9608b2a9936 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/AssemblyInfo.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/AssemblyInfo.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; -using System.Runtime.InteropServices; - -#endregion - +using System.Runtime.InteropServices; + [assembly: AssemblyTitle("DotNetNuke.Providers.AspNetClientCapabilityProvider")] [assembly: AssemblyDescription("Open Source Web Application Framework")] [assembly: Guid("E4C6B3F6-406A-4FD5-996A-C0C2E89A2D84")] diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/Constants.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/Constants.cs index 8d492246a79..c218ed5a0c8 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/Constants.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/Constants.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.AspNetClientCapabilityProvider.Properties { /// diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs index ab79e6e6280..4df38e46c4b 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.AspNetClientCapabilityProvider.Properties { + using System; + /// /// A list of constants to use with the purchase solution. /// diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/packages.config b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureBlob.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureBlob.cs index 6ccffdfba48..8a4e219d387 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureBlob.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureBlob.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Microsoft.WindowsAzure.Storage.Blob; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider { + using System; + + using Microsoft.WindowsAzure.Storage.Blob; + [Serializable] public class AzureBlob { @@ -22,18 +23,18 @@ public AzureBlob(CloudBlob blob) return; } - _relativePath = blob.RelativePath(); - _lastModifiedUtc = blob.Properties.LastModified.GetValueOrDefault(DateTimeOffset.MinValue).UtcDateTime; - _length = blob.Properties.Length; - _etag = blob.Properties.ETag; + this._relativePath = blob.RelativePath(); + this._lastModifiedUtc = blob.Properties.LastModified.GetValueOrDefault(DateTimeOffset.MinValue).UtcDateTime; + this._length = blob.Properties.Length; + this._etag = blob.Properties.ETag; } - public string RelativePath => _relativePath; + public string RelativePath => this._relativePath; - public DateTime LastModifiedUtc => _lastModifiedUtc; + public DateTime LastModifiedUtc => this._lastModifiedUtc; - public long Length => _length; + public long Length => this._length; - public string ETag => _etag; + public string ETag => this._etag; } } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs index b4fa6969891..93d42b82374 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs @@ -1,31 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading; -using System.Web.Caching; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Providers.FolderProviders.Components; -using DotNetNuke.Services.FileSystem; -using Microsoft.WindowsAzure.Storage; -using Microsoft.WindowsAzure.Storage.Auth; -using Microsoft.WindowsAzure.Storage.Blob; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider { - /// - /// Windows Azure Storage Folder Provider - /// + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net; + using System.Threading; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Providers.FolderProviders.Components; + using DotNetNuke.Services.FileSystem; + using Microsoft.WindowsAzure.Storage; + using Microsoft.WindowsAzure.Storage.Auth; + using Microsoft.WindowsAzure.Storage.Blob; + + /// + /// Windows Azure Storage Folder Provider. + /// public class AzureFolderProvider : BaseRemoteStorageProvider { - public AzureFolderProvider() { ServicePointManager.DefaultConnectionLimit = 100; @@ -40,6 +40,7 @@ protected override string FileNotFoundMessage return "Azure File Not Found"; } } + protected override string ObjectCacheKey { get { return "Azure_Object_{0}_{1}"; } @@ -48,71 +49,155 @@ protected override string ObjectCacheKey protected override string ListObjectsCacheKey { get { return "Azure_ListObjects_{0}"; } - } + } + + /// + /// Azure Storage doesn't support folders, so we create a file in order for the folder to not be deleted during future synchronizations. + /// The file has an extension not allowed by host. This way the file won't be added during synchronizations. + /// + public override void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) + { + Requires.NotNull("folderPath", folderPath); + Requires.NotNull("folderMapping", folderMapping); - #region Private Methods + this.UpdateFileInternal(new MemoryStream(), folderMapping, mappedPath + Constants.PlaceHolderFileName); + } - private static void CheckSettings(FolderMappingInfo folderMapping) + /// + /// Gets the direct Url to the file. + /// + /// + public override string GetFileUrl(IFileInfo file) { - var settings = folderMapping.FolderMappingSettings; + Requires.NotNull("file", file); - if (string.IsNullOrEmpty((string)settings[Constants.AccountName]) || - string.IsNullOrEmpty((string)settings[Constants.AccountKey]) || - string.IsNullOrEmpty((string)settings[Constants.Container]) || - string.IsNullOrEmpty((string)settings[Constants.UseHttps])) + var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); + var directLink = string.IsNullOrEmpty(GetSetting(folderMapping, Constants.DirectLink)) || GetSetting(folderMapping, Constants.DirectLink).ToLowerInvariant() == "true"; + + if (directLink) { - throw new Exception("Settings cannot be found."); - } - } + var folder = FolderManager.Instance.GetFolder(file.FolderId); + var uri = folder.MappedPath + file.FileName; - private CloudBlobContainer GetContainer(FolderMappingInfo folderMapping) - { + var container = this.GetContainer(folderMapping); + var blob = container.GetBlobReference(uri); + var absuri = blob.Uri.AbsoluteUri; + var customDomain = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.CustomDomain); - CheckSettings(folderMapping); + if (!string.IsNullOrEmpty(customDomain)) + { + var customUri = new UriBuilder(customDomain).Uri; + absuri = + new UriBuilder(blob.Uri.AbsoluteUri) { Host = customUri.Host, Scheme = customUri.Scheme, Port = customUri.Port } + .Uri.AbsoluteUri; + } - var accountName = GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountName); - var accountKey = GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountKey); - var container = GetSetting(folderMapping, Constants.Container); - var useHttps = GetBooleanSetting(folderMapping, Constants.UseHttps); + const string groupPolicyIdentifier = "DNNFileManagerPolicy"; - var sc = new StorageCredentials(accountName, accountKey); - var csa = new CloudStorageAccount(sc, useHttps); - var blobClient = csa.CreateCloudBlobClient(); - return blobClient.GetContainerReference(container); - } + var permissions = container.GetPermissions(); + + SharedAccessBlobPolicy policy; + + permissions.SharedAccessPolicies.TryGetValue(groupPolicyIdentifier, out policy); + + if (policy == null) + { + policy = new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100) }; + + permissions.SharedAccessPolicies.Add(groupPolicyIdentifier, policy); + } + else + { + policy.Permissions = SharedAccessBlobPermissions.Read; + policy.SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100); + } + + /* + * Workaround for CONTENT-3662 + * The Azure Client Storage api has issue when used with Italian Thread.Culture or eventually other cultures + * (see this article for further information https://connect.microsoft.com/VisualStudio/feedback/details/760974/windows-azure-sdk-cloudblobcontainer-setpermissions-permissions-as-microsoft-windowsazure-storageclient-blobcontainerpermissions-error). + * This code changes the thread culture to en-US + */ + var currentCulture = Thread.CurrentThread.CurrentCulture; + if (currentCulture.Name != "en-US") + { + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); + } - #endregion + container.SetPermissions(permissions); + var signature = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy(), groupPolicyIdentifier); + + // Reset original Thread Culture + if (currentCulture.Name != "en-US") + { + Thread.CurrentThread.CurrentCulture = currentCulture; + } + + return absuri + signature; + } + + return FileLinkClickController.Instance.GetFileLinkClick(file); + } + protected override void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri) { - var container = GetContainer(folderMapping); + var container = this.GetContainer(folderMapping); var sourceBlob = container.GetBlobReference(sourceUri); var newBlob = container.GetBlobReference(newUri); newBlob.StartCopy(sourceBlob.Uri); - ClearCache(folderMapping.FolderMappingID); + this.ClearCache(folderMapping.FolderMappingID); } protected override void DeleteFileInternal(FolderMappingInfo folderMapping, string uri) { - var container = GetContainer(folderMapping); + var container = this.GetContainer(folderMapping); var blob = container.GetBlobReference(uri); blob.DeleteIfExists(); - ClearCache(folderMapping.FolderMappingID); + this.ClearCache(folderMapping.FolderMappingID); + } + + private static void CheckSettings(FolderMappingInfo folderMapping) + { + var settings = folderMapping.FolderMappingSettings; + + if (string.IsNullOrEmpty((string)settings[Constants.AccountName]) || + string.IsNullOrEmpty((string)settings[Constants.AccountKey]) || + string.IsNullOrEmpty((string)settings[Constants.Container]) || + string.IsNullOrEmpty((string)settings[Constants.UseHttps])) + { + throw new Exception("Settings cannot be found."); + } } + private CloudBlobContainer GetContainer(FolderMappingInfo folderMapping) + { + CheckSettings(folderMapping); + + var accountName = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountName); + var accountKey = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountKey); + var container = GetSetting(folderMapping, Constants.Container); + var useHttps = GetBooleanSetting(folderMapping, Constants.UseHttps); + + var sc = new StorageCredentials(accountName, accountKey); + var csa = new CloudStorageAccount(sc, useHttps); + var blobClient = csa.CreateCloudBlobClient(); + return blobClient.GetContainerReference(container); + } + protected override void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder) { - DeleteFileInternal(folderMapping, folder.MappedPath + Constants.PlaceHolderFileName); + this.DeleteFileInternal(folderMapping, folder.MappedPath + Constants.PlaceHolderFileName); } protected override Stream GetFileStreamInternal(FolderMappingInfo folderMapping, string uri) { - var container = GetContainer(folderMapping); + var container = this.GetContainer(folderMapping); var blob = container.GetBlockBlobReference(uri); var memoryStream = new MemoryStream(); @@ -124,15 +209,17 @@ protected override Stream GetFileStreamInternal(FolderMappingInfo folderMapping, protected override IList GetObjectList(FolderMappingInfo folderMapping) { - var cacheKey = string.Format(ListObjectsCacheKey, folderMapping.FolderMappingID); - - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, - ListObjectsCacheTimeout, - CacheItemPriority.Default, - folderMapping.FolderMappingID), - c => + var cacheKey = string.Format(this.ListObjectsCacheKey, folderMapping.FolderMappingID); + + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + this.ListObjectsCacheTimeout, + CacheItemPriority.Default, + folderMapping.FolderMappingID), + c => { - var container = GetContainer(folderMapping); + var container = this.GetContainer(folderMapping); var synchBatchSize = GetIntegerSetting(folderMapping, Constants.SyncBatchSize, Constants.DefaultSyncBatchSize); BlobContinuationToken continuationToken = null; @@ -141,27 +228,26 @@ protected override IList GetObjectList(FolderMappingInfo fol var list = new List(); do { - //This overload allows control of the page size. You can return all remaining results by passing null for the maxResults parameter, - //or by calling a different overload. - resultSegment = container.ListBlobsSegmented("", true, BlobListingDetails.All, synchBatchSize, continuationToken, null, null); + // This overload allows control of the page size. You can return all remaining results by passing null for the maxResults parameter, + // or by calling a different overload. + resultSegment = container.ListBlobsSegmented(string.Empty, true, BlobListingDetails.All, synchBatchSize, continuationToken, null, null); foreach (var blobItem in resultSegment.Results) { - list.Add(new AzureRemoteStorageItem {Blob = new AzureBlob(blobItem as CloudBlob)}); + list.Add(new AzureRemoteStorageItem { Blob = new AzureBlob(blobItem as CloudBlob) }); } - //Get the continuation token. + // Get the continuation token. continuationToken = resultSegment.ContinuationToken; } while (continuationToken != null); - + return list; }); - } protected override void MoveFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri) { - var container = GetContainer(folderMapping); + var container = this.GetContainer(folderMapping); var sourceBlob = container.GetBlobReference(sourceUri); var newBlob = container.GetBlobReference(newUri); @@ -169,12 +255,12 @@ protected override void MoveFileInternal(FolderMappingInfo folderMapping, string newBlob.StartCopy(sourceBlob.Uri); sourceBlob.Delete(); - ClearCache(folderMapping.FolderMappingID); + this.ClearCache(folderMapping.FolderMappingID); } protected override void MoveFolderInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri) { - var container = GetContainer(folderMapping); + var container = this.GetContainer(folderMapping); var directory = container.GetDirectoryReference(sourceUri); var blobs = directory.ListBlobs(true); @@ -186,12 +272,12 @@ protected override void MoveFolderInternal(FolderMappingInfo folderMapping, stri blob.Delete(); } - ClearCache(folderMapping.FolderMappingID); + this.ClearCache(folderMapping.FolderMappingID); } protected override void UpdateFileInternal(Stream stream, FolderMappingInfo folderMapping, string uri) { - var container = GetContainer(folderMapping); + var container = this.GetContainer(folderMapping); var blob = container.GetBlockBlobReference(uri); stream.Seek(0, SeekOrigin.Begin); @@ -199,104 +285,15 @@ protected override void UpdateFileInternal(Stream stream, FolderMappingInfo fold // Set the content type blob.Properties.ContentType = FileContentTypeManager.Instance.GetContentType(Path.GetExtension(uri)); - blob.SetProperties(); - - ClearCache(folderMapping.FolderMappingID); - } - - #region FolderProvider Methods - - /// - /// Azure Storage doesn't support folders, so we create a file in order for the folder to not be deleted during future synchronizations. - /// The file has an extension not allowed by host. This way the file won't be added during synchronizations. - /// - public override void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) - { - Requires.NotNull("folderPath", folderPath); - Requires.NotNull("folderMapping", folderMapping); - - UpdateFileInternal(new MemoryStream(), folderMapping, mappedPath + Constants.PlaceHolderFileName); - } - - /// - /// Gets the direct Url to the file. - /// - public override string GetFileUrl(IFileInfo file) - { - Requires.NotNull("file", file); - - var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - var directLink = string.IsNullOrEmpty(GetSetting(folderMapping, Constants.DirectLink)) || GetSetting(folderMapping, Constants.DirectLink).ToLowerInvariant() == "true"; - - if (directLink) - { - var folder = FolderManager.Instance.GetFolder(file.FolderId); - var uri = folder.MappedPath + file.FileName; - - var container = GetContainer(folderMapping); - var blob = container.GetBlobReference(uri); - var absuri = blob.Uri.AbsoluteUri; - var customDomain = GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.CustomDomain); - - if (!string.IsNullOrEmpty(customDomain)) - { - var customUri = new UriBuilder(customDomain).Uri; - absuri = - new UriBuilder(blob.Uri.AbsoluteUri) { Host = customUri.Host, Scheme = customUri.Scheme, Port = customUri.Port } - .Uri.AbsoluteUri; - } - - const string groupPolicyIdentifier = "DNNFileManagerPolicy"; - - var permissions = container.GetPermissions(); - - SharedAccessBlobPolicy policy; - - permissions.SharedAccessPolicies.TryGetValue(groupPolicyIdentifier, out policy); - - if (policy == null) - { - policy = new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100)}; - - permissions.SharedAccessPolicies.Add(groupPolicyIdentifier, policy); - } - else - { - policy.Permissions = SharedAccessBlobPermissions.Read; - policy.SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100); - } - - /* - * Workaround for CONTENT-3662 - * The Azure Client Storage api has issue when used with Italian Thread.Culture or eventually other cultures - * (see this article for further information https://connect.microsoft.com/VisualStudio/feedback/details/760974/windows-azure-sdk-cloudblobcontainer-setpermissions-permissions-as-microsoft-windowsazure-storageclient-blobcontainerpermissions-error). - * This code changes the thread culture to en-US - */ - var currentCulture = Thread.CurrentThread.CurrentCulture; - if (currentCulture.Name != "en-US") - { - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); - } + blob.SetProperties(); - container.SetPermissions(permissions); - - var signature = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy(), groupPolicyIdentifier); - - // Reset original Thread Culture - if (currentCulture.Name != "en-US") - { - Thread.CurrentThread.CurrentCulture = currentCulture; - } - - return absuri + signature; - } - - return FileLinkClickController.Instance.GetFileLinkClick(file); - } + this.ClearCache(folderMapping.FolderMappingID); + } /// /// Gets the URL of the image to display in FileManager tree. - /// + /// + /// public override string GetFolderProviderIconPath() { return Globals.ResolveUrl("~/Providers/FolderProviders/AzureFolderProvider/images/FolderAzure_32x32_Standard.png"); @@ -305,8 +302,8 @@ public override string GetFolderProviderIconPath() public List GetAllContainers(FolderMappingInfo folderMapping) { List containers = new List(); - var accountName = GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountName); - var accountKey = GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountKey); + var accountName = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountName); + var accountKey = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountKey); var useHttps = GetBooleanSetting(folderMapping, Constants.UseHttps); var sc = new StorageCredentials(accountName, accountKey); @@ -314,9 +311,6 @@ public List GetAllContainers(FolderMappingInfo folderMapping) var blobClient = csa.CreateCloudBlobClient(); blobClient.ListContainers().ToList().ForEach(x => containers.Add(x.Name)); return containers; - } - - #endregion - + } } } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs index b58c9f94395..5031f811a20 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using DotNetNuke.Providers.FolderProviders.Components; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider { + using System; + using System.Web; + + using DotNetNuke.Providers.FolderProviders.Components; + [Serializable] public class AzureRemoteStorageItem : IRemoteStorageItem { @@ -17,15 +18,15 @@ public string Key { get { - var path = Blob.RelativePath.Replace("+", "%2b"); + var path = this.Blob.RelativePath.Replace("+", "%2b"); return HttpUtility.UrlDecode(path); } } - public DateTime LastModified => Blob.LastModifiedUtc; + public DateTime LastModified => this.Blob.LastModifiedUtc; - public long Size => Blob.Length; + public long Size => this.Blob.Length; - public string HashCode => Blob.ETag; + public string HashCode => this.Blob.ETag; } } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs index 8f1b8c0ed10..654d0172254 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Microsoft.WindowsAzure.Storage.Blob; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider { + using Microsoft.WindowsAzure.Storage.Blob; + internal static class BlobItemExtensions { public static string RelativePath(this IListBlobItem item) diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Constants.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Constants.cs index 1ae5a811768..b55e98a6f98 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Constants.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Constants.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider { internal class Constants diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs index 594bcc6b8e6..75f28e002a9 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs @@ -1,29 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Linq; -using System.Web.UI.WebControls; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using Microsoft.WindowsAzure.Storage; -using Microsoft.WindowsAzure.Storage.Auth; -using Microsoft.WindowsAzure.Storage.Blob; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider { - /// - /// Windows Azure Storage Settings Control - /// + using System; + using System.Collections; + using System.Linq; + using System.Web.UI.WebControls; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using Microsoft.WindowsAzure.Storage; + using Microsoft.WindowsAzure.Storage.Auth; + using Microsoft.WindowsAzure.Storage.Blob; + + /// + /// Windows Azure Storage Settings Control. + /// public partial class Settings : FolderMappingSettingsControlBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Settings)); - - #region Overrided Methods - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Settings)); + /// /// Loads concrete settings. /// @@ -33,52 +32,52 @@ public override void LoadSettings(Hashtable folderMappingSettings) var folderProvider = FolderProvider.Instance(Constants.FolderProviderType); if (folderMappingSettings.ContainsKey(Constants.AccountName)) { - tbAccountName.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountName); + this.tbAccountName.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountName); } if (folderMappingSettings.ContainsKey(Constants.AccountKey)) { - tbAccountKey.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountKey); + this.tbAccountKey.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountKey); } - if (tbAccountName.Text.Length > 0 && tbAccountKey.Text.Length > 0) + if (this.tbAccountName.Text.Length > 0 && this.tbAccountKey.Text.Length > 0) { - var bucketName = ""; + var bucketName = string.Empty; if (folderMappingSettings.ContainsKey(Constants.Container)) { bucketName = folderMappingSettings[Constants.Container].ToString(); } - LoadContainers(); + this.LoadContainers(); - var bucket = ddlContainers.Items.FindByText(bucketName); + var bucket = this.ddlContainers.Items.FindByText(bucketName); if (bucket != null) { - ddlContainers.SelectedIndex = ddlContainers.Items.IndexOf(bucket); + this.ddlContainers.SelectedIndex = this.ddlContainers.Items.IndexOf(bucket); } } if (folderMappingSettings.ContainsKey(Constants.UseHttps)) { - chkUseHttps.Checked = bool.Parse(folderMappingSettings[Constants.UseHttps].ToString()); + this.chkUseHttps.Checked = bool.Parse(folderMappingSettings[Constants.UseHttps].ToString()); } - chkDirectLink.Checked = !folderMappingSettings.ContainsKey(Constants.DirectLink) || folderMappingSettings[Constants.DirectLink].ToString().ToLowerInvariant() == "true"; + this.chkDirectLink.Checked = !folderMappingSettings.ContainsKey(Constants.DirectLink) || folderMappingSettings[Constants.DirectLink].ToString().ToLowerInvariant() == "true"; if (folderMappingSettings.ContainsKey(Constants.CustomDomain)) { - tbCustomDomain.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.CustomDomain); + this.tbCustomDomain.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.CustomDomain); } if (folderMappingSettings.ContainsKey(Constants.SyncBatchSize) && folderMappingSettings[Constants.SyncBatchSize] != null) { - tbSyncBatchSize.Text = folderMappingSettings[Constants.SyncBatchSize].ToString(); + this.tbSyncBatchSize.Text = folderMappingSettings[Constants.SyncBatchSize].ToString(); } else { - tbSyncBatchSize.Text = Constants.DefaultSyncBatchSize.ToString(); + this.tbSyncBatchSize.Text = Constants.DefaultSyncBatchSize.ToString(); } } @@ -88,9 +87,9 @@ public override void LoadSettings(Hashtable folderMappingSettings) /// The folder mapping identifier. public override void UpdateSettings(int folderMappingID) { - Page.Validate(); + this.Page.Validate(); - if (!Page.IsValid) + if (!this.Page.IsValid) { throw new Exception(); } @@ -98,36 +97,71 @@ public override void UpdateSettings(int folderMappingID) var folderMappingController = FolderMappingController.Instance; var folderMapping = folderMappingController.GetFolderMapping(folderMappingID); - var accountName = GetAccountName(); - var accountKey = GetAccountKey(); - var container = GetContainer(); - var useHttps = GetUseHttps(); - var customDomain = GetCustomDomain(); - var synchBatchSize = GetSynchBatchSize(); + var accountName = this.GetAccountName(); + var accountKey = this.GetAccountKey(); + var container = this.GetContainer(); + var useHttps = this.GetUseHttps(); + var customDomain = this.GetCustomDomain(); + var synchBatchSize = this.GetSynchBatchSize(); if (AreThereFolderMappingsWithSameSettings(folderMapping, accountName, container)) { - valContainerName.ErrorMessage = Localization.GetString("MultipleFolderMappingsWithSameSettings.ErrorMessage", LocalResourceFile); - valContainerName.IsValid = false; + this.valContainerName.ErrorMessage = Localization.GetString("MultipleFolderMappingsWithSameSettings.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; throw new Exception(); } - + folderMapping.FolderMappingSettings[Constants.AccountName] = accountName; folderMapping.FolderMappingSettings[Constants.AccountKey] = accountKey; folderMapping.FolderMappingSettings[Constants.Container] = container; folderMapping.FolderMappingSettings[Constants.UseHttps] = useHttps; - folderMapping.FolderMappingSettings[Constants.DirectLink] = chkDirectLink.Checked; + folderMapping.FolderMappingSettings[Constants.DirectLink] = this.chkDirectLink.Checked; folderMapping.FolderMappingSettings[Constants.CustomDomain] = customDomain; folderMapping.FolderMappingSettings[Constants.SyncBatchSize] = synchBatchSize; folderMappingController.UpdateFolderMapping(folderMapping); - } + } + + /// + /// + protected void ddlContainers_SelectedIndexChanged(object sender, EventArgs e) + { + if (this.ddlContainers.SelectedIndex != 1) + { + return; + } + + if (this.tbAccountName.Text.Trim().Length > 0 && this.tbAccountKey.Text.Trim().Length > 0) + { + this.ddlContainers.Items.Clear(); - #endregion + this.ddlContainers.Items.Add(Localization.GetString("SelectContainer", this.LocalResourceFile)); + this.ddlContainers.Items.Add(Localization.GetString("RefreshContainerList", this.LocalResourceFile)); - #region Private Methods + this.LoadContainers(); + if (this.ddlContainers.Items.Count == 3) + { + // If there is only one container, then select it + this.ddlContainers.SelectedValue = this.ddlContainers.Items[2].Value; + } + } + else + { + this.valContainerName.ErrorMessage = Localization.GetString("CredentialsRequired.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + } + } + + /// + /// + protected void btnNewContainer_Click(object sender, EventArgs e) + { + this.SelectContainerPanel.Visible = false; + this.CreateContainerPanel.Visible = true; + } + private static bool AreThereFolderMappingsWithSameSettings(FolderMappingInfo folderMapping, string accountName, string container) { var folderMappingController = FolderMappingController.Instance; @@ -141,21 +175,24 @@ private static bool AreThereFolderMappingsWithSameSettings(FolderMappingInfo fol private string GetUseHttps() { - return chkUseHttps.Checked.ToString(); + return this.chkUseHttps.Checked.ToString(); } private string GetContainer() { string container; - if (SelectContainerPanel.Visible) + if (this.SelectContainerPanel.Visible) { - container = ddlContainers.SelectedValue; + container = this.ddlContainers.SelectedValue; } else { - container = tbContainerName.Text.Trim().ToLowerInvariant(); - if (!CreateContainer(container)) throw new Exception(); + container = this.tbContainerName.Text.Trim().ToLowerInvariant(); + if (!this.CreateContainer(container)) + { + throw new Exception(); + } } return container; @@ -163,9 +200,9 @@ private string GetContainer() private bool CreateContainer(string containerName) { - var accountName = tbAccountName.Text.Trim(); - var accountKey = tbAccountKey.Text.Trim(); - var useHttps = chkUseHttps.Checked; + var accountName = this.tbAccountName.Text.Trim(); + var accountKey = this.tbAccountKey.Text.Trim(); + var useHttps = this.chkUseHttps.Checked; StorageCredentials sc; @@ -177,12 +214,12 @@ private bool CreateContainer(string containerName) { Logger.Error(ex); - valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", LocalResourceFile); - valContainerName.IsValid = false; + this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; return false; } - + var csa = new CloudStorageAccount(sc, useHttps); var blobClient = csa.CreateCloudBlobClient(); var container = blobClient.GetContainerReference(containerName); @@ -205,69 +242,72 @@ private bool CreateContainer(string containerName) switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode) { case "AccountNotFound": - valContainerName.ErrorMessage = Localization.GetString("AccountNotFound.ErrorMessage", - LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString( + "AccountNotFound.ErrorMessage", + this.LocalResourceFile); break; case "AuthenticationFailure": - valContainerName.ErrorMessage = Localization.GetString( - "AuthenticationFailure.ErrorMessage", LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString( + "AuthenticationFailure.ErrorMessage", this.LocalResourceFile); break; case "AccessDenied": - valContainerName.ErrorMessage = Localization.GetString("AccessDenied.ErrorMessage", - LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString( + "AccessDenied.ErrorMessage", + this.LocalResourceFile); break; case "ContainerAlreadyExists": return true; default: Logger.Error(ex); - valContainerName.ErrorMessage = Localization.GetString("NewContainer.ErrorMessage", - LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString( + "NewContainer.ErrorMessage", + this.LocalResourceFile); break; } } else { - valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; + this.valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; } } catch (Exception ex) { Logger.Error(ex); - valContainerName.ErrorMessage = Localization.GetString("NewContainer.ErrorMessage", LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString("NewContainer.ErrorMessage", this.LocalResourceFile); } - valContainerName.IsValid = false; + this.valContainerName.IsValid = false; return false; } private string GetAccountKey() { - return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(tbAccountKey.Text); + return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbAccountKey.Text); } private string GetAccountName() { - return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(tbAccountName.Text); + return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbAccountName.Text); } private string GetCustomDomain() { - return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(tbCustomDomain.Text); + return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbCustomDomain.Text); } private string GetSynchBatchSize() { - return tbSyncBatchSize.Text; + return this.tbSyncBatchSize.Text; } private void LoadContainers() { - var accountName = tbAccountName.Text.Trim(); - var accountKey = tbAccountKey.Text.Trim(); - var useHttps = chkUseHttps.Checked; + var accountName = this.tbAccountName.Text.Trim(); + var accountKey = this.tbAccountKey.Text.Trim(); + var useHttps = this.chkUseHttps.Checked; StorageCredentials sc; - + try { sc = new StorageCredentials(accountName, accountKey); @@ -276,9 +316,9 @@ private void LoadContainers() { Logger.Error(ex); - valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", LocalResourceFile); - valContainerName.IsValid = false; - + this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + return; } @@ -289,94 +329,54 @@ private void LoadContainers() { foreach (var container in blobClient.ListContainers()) { - ddlContainers.Items.Add(container.Name); + this.ddlContainers.Items.Add(container.Name); } } catch (StorageException ex) { - if(ex.RequestInformation.ExtendedErrorInformation != null) - { + if (ex.RequestInformation.ExtendedErrorInformation != null) + { switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode) { case "AuthenticationFailure": - valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); break; default: Logger.Error(ex); - valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", this.LocalResourceFile); break; } } else { - valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; + this.valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; } - valContainerName.IsValid = false; + this.valContainerName.IsValid = false; } catch (Exception ex) { Logger.Error(ex); - valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", LocalResourceFile); - valContainerName.IsValid = false; + this.valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; } - } - - #endregion - - #region Event Handlers - - /// - /// - protected void ddlContainers_SelectedIndexChanged(object sender, EventArgs e) - { - if (ddlContainers.SelectedIndex != 1) return; - - if (tbAccountName.Text.Trim().Length > 0 && tbAccountKey.Text.Trim().Length > 0) - { - ddlContainers.Items.Clear(); - - ddlContainers.Items.Add(Localization.GetString("SelectContainer", LocalResourceFile)); - ddlContainers.Items.Add(Localization.GetString("RefreshContainerList", LocalResourceFile)); - - LoadContainers(); - - if (ddlContainers.Items.Count == 3) - { - // If there is only one container, then select it - ddlContainers.SelectedValue = ddlContainers.Items[2].Value; - } - } - else - { - valContainerName.ErrorMessage = Localization.GetString("CredentialsRequired.ErrorMessage", LocalResourceFile); - valContainerName.IsValid = false; - } - } - - /// - /// - protected void btnNewContainer_Click(object sender, EventArgs e) - { - SelectContainerPanel.Visible = false; - CreateContainerPanel.Visible = true; - } + } /// /// protected void btnSelectExistingContainer_Click(object sender, EventArgs e) { - SelectContainerPanel.Visible = true; - CreateContainerPanel.Visible = false; + this.SelectContainerPanel.Visible = true; + this.CreateContainerPanel.Visible = false; } /// /// protected void valContainerName_ServerValidate(object source, ServerValidateEventArgs args) { - if (SelectContainerPanel.Visible) + if (this.SelectContainerPanel.Visible) { - if (ddlContainers.SelectedIndex > 1) + if (this.ddlContainers.SelectedIndex > 1) { args.IsValid = true; return; @@ -384,17 +384,15 @@ protected void valContainerName_ServerValidate(object source, ServerValidateEven } else { - if (tbContainerName.Text.Trim().Length > 0) + if (this.tbContainerName.Text.Trim().Length > 0) { args.IsValid = true; return; } } - valContainerName.ErrorMessage = Localization.GetString("valContainerName.ErrorMessage", LocalResourceFile); + this.valContainerName.ErrorMessage = Localization.GetString("valContainerName.ErrorMessage", this.LocalResourceFile); args.IsValid = false; - } - - #endregion + } } } diff --git a/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs b/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs index d33fc69e781..947288712f6 100644 --- a/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs +++ b/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs @@ -1,109 +1,112 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web.Caching; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Security; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.Components { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Security; + using DotNetNuke.Services.FileSystem; + public abstract class BaseRemoteStorageProvider : FolderProvider - { - #region Private Members - + { private readonly string _encryptionKey = Host.GUID; - private readonly PortalSecurity _portalSecurity = PortalSecurity.Instance; - #endregion - - #region Private Methods - - private IRemoteStorageItem GetStorageItemInternal(FolderMappingInfo folderMapping, string key) + private readonly PortalSecurity _portalSecurity = PortalSecurity.Instance; + + public override bool SupportsMappedPaths { - var cacheKey = string.Format(ObjectCacheKey, folderMapping.FolderMappingID, key); - - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, - ObjectCacheTimeout, - CacheItemPriority.Default, - folderMapping.FolderMappingID), - c => - { - var list = GetObjectList(folderMapping, key); - - //return list.FirstOrDefault(i => i.Key == key); - return list.FirstOrDefault(i => i.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); - }); - + get { return true; } } - - #endregion - - #region Protected Properties + public override bool SupportsMoveFile + { + get { return false; } + } + protected virtual string FileNotFoundMessage { - get { return String.Empty; } + get { return string.Empty; } } - + protected virtual string ObjectCacheKey { - get { return String.Empty; } + get { return string.Empty; } } protected virtual int ObjectCacheTimeout { get { return 150; } } + + private IRemoteStorageItem GetStorageItemInternal(FolderMappingInfo folderMapping, string key) + { + var cacheKey = string.Format(this.ObjectCacheKey, folderMapping.FolderMappingID, key); + + return CBO.GetCachedObject( + new CacheItemArgs( + cacheKey, + this.ObjectCacheTimeout, + CacheItemPriority.Default, + folderMapping.FolderMappingID), + c => + { + var list = this.GetObjectList(folderMapping, key); + + // return list.FirstOrDefault(i => i.Key == key); + return list.FirstOrDefault(i => i.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); + }); + } protected virtual string ListObjectsCacheKey { - get { return String.Empty; } + get { return string.Empty; } } protected virtual int ListObjectsCacheTimeout { get { return 300; } - } - - #endregion + } - public override bool SupportsMappedPaths + public override bool SupportsMoveFolder { get { return true; } - } - - public override bool SupportsMoveFile + } + + /// + /// Adds a new folder. + /// + public override void AddFolder(string folderPath, FolderMappingInfo folderMapping) { - get { return false; } + this.AddFolder(folderPath, folderMapping, folderPath); } - public override bool SupportsMoveFolder + /// + /// Adds a new file to the specified folder. + /// + public override void AddFile(IFolderInfo folder, string fileName, Stream content) { - get { return true; } - } - - #region Protected Methods - - protected abstract void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); - - protected abstract void DeleteFileInternal(FolderMappingInfo folderMapping, string uri); + Requires.NotNull("folder", folder); + Requires.NotNullOrEmpty("fileName", fileName); + Requires.NotNull("content", content); - protected abstract void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder); + this.UpdateFile(folder, fileName, content); + } protected static bool GetBooleanSetting(FolderMappingInfo folderMapping, string settingName) { - return Boolean.Parse(folderMapping.FolderMappingSettings[settingName].ToString()); + return bool.Parse(folderMapping.FolderMappingSettings[settingName].ToString()); } - + protected static int GetIntegerSetting(FolderMappingInfo folderMapping, string settingName, int defaultValue) { int value; @@ -111,26 +114,33 @@ protected static int GetIntegerSetting(FolderMappingInfo folderMapping, string s { return value; } + return defaultValue; } + + protected abstract void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); - protected abstract Stream GetFileStreamInternal(FolderMappingInfo folderMapping, string uri); - - protected abstract IList GetObjectList(FolderMappingInfo folderMapping); + protected abstract void DeleteFileInternal(FolderMappingInfo folderMapping, string uri); - protected virtual IList GetObjectList(FolderMappingInfo folderMapping, string path) - { - return GetObjectList(folderMapping); - } + protected abstract void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder); protected static string GetSetting(FolderMappingInfo folderMapping, string settingName) { Requires.NotNull(nameof(folderMapping), folderMapping); Requires.NotNullOrEmpty(nameof(settingName), settingName); - + return folderMapping.FolderMappingSettings[settingName]?.ToString(); } + protected abstract Stream GetFileStreamInternal(FolderMappingInfo folderMapping, string uri); + + protected abstract IList GetObjectList(FolderMappingInfo folderMapping); + + protected virtual IList GetObjectList(FolderMappingInfo folderMapping, string path) + { + return this.GetObjectList(folderMapping); + } + protected abstract void MoveFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); protected abstract void MoveFolderInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); @@ -139,36 +149,16 @@ protected static string GetSetting(FolderMappingInfo folderMapping, string setti protected virtual IRemoteStorageItem GetStorageItem(FolderMappingInfo folderMapping, string key) { - return GetStorageItemInternal(folderMapping, key); - } - #endregion - - /// - /// Adds a new folder - /// - public override void AddFolder(string folderPath, FolderMappingInfo folderMapping) - { - AddFolder(folderPath, folderMapping, folderPath); - } - - /// - /// Adds a new file to the specified folder. - /// - public override void AddFile(IFolderInfo folder, string fileName, Stream content) - { - Requires.NotNull("folder", folder); - Requires.NotNullOrEmpty("fileName", fileName); - Requires.NotNull("content", content); - - UpdateFile(folder, fileName, content); - } + return this.GetStorageItemInternal(folderMapping, key); + } public virtual void ClearCache(int folderMappingId) { - var cacheKey = String.Format(ListObjectsCacheKey, folderMappingId); + var cacheKey = string.Format(this.ListObjectsCacheKey, folderMappingId); DataCache.RemoveCache(cacheKey); - //Clear cached objects - DataCache.ClearCache(String.Format(ObjectCacheKey, folderMappingId, String.Empty)); + + // Clear cached objects + DataCache.ClearCache(string.Format(this.ObjectCacheKey, folderMappingId, string.Empty)); } /// @@ -181,9 +171,12 @@ public override void CopyFile(string folderPath, string fileName, string newFold Requires.NotNull("newFolderPath", newFolderPath); Requires.NotNull("folderMapping", folderMapping); - if (folderPath == newFolderPath) return; - - CopyFileInternal(folderMapping, folderPath + fileName, newFolderPath + fileName); + if (folderPath == newFolderPath) + { + return; + } + + this.CopyFileInternal(folderMapping, folderPath + fileName, newFolderPath + fileName); } /// @@ -197,7 +190,7 @@ public override void DeleteFile(IFileInfo file) var folder = FolderManager.Instance.GetFolder(file.FolderId); - DeleteFileInternal(folderMapping, folder.MappedPath + file.FileName); + this.DeleteFileInternal(folderMapping, folder.MappedPath + file.FileName); } /// @@ -209,44 +202,47 @@ public override void DeleteFolder(IFolderInfo folder) var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - DeleteFolderInternal(folderMapping, folder); + this.DeleteFolderInternal(folderMapping, folder); } /// /// Checks the existence of the specified file. - /// + /// + /// public override bool FileExists(IFolderInfo folder, string fileName) { Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("fileName", fileName); var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - var item = GetStorageItem(folderMapping, folder.MappedPath + fileName); - return (item != null); + var item = this.GetStorageItem(folderMapping, folder.MappedPath + fileName); + return item != null; } /// /// Checks the existence of the specified folder. - /// + /// + /// public override bool FolderExists(string folderPath, FolderMappingInfo folderMapping) { Requires.NotNull("folderPath", folderPath); Requires.NotNull("folderMapping", folderMapping); - //the root folder should always exist. - if (folderPath == "") + // the root folder should always exist. + if (folderPath == string.Empty) { return true; } - var list = GetObjectList(folderMapping, folderPath); + var list = this.GetObjectList(folderMapping, folderPath); return list.Any(o => o.Key.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase)); } /// /// Amazon doesn't support file attributes. - /// + /// + /// public override FileAttributes? GetFileAttributes(IFileInfo file) { return null; @@ -254,33 +250,33 @@ public override bool FolderExists(string folderPath, FolderMappingInfo folderMap /// /// Gets the list of file names contained in the specified folder. - /// + /// + /// public override string[] GetFiles(IFolderInfo folder) { Requires.NotNull("folder", folder); var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - var list = GetObjectList(folderMapping, folder.MappedPath); + var list = this.GetObjectList(folderMapping, folder.MappedPath); var mappedPath = folder.MappedPath; - //return (from i in list + // return (from i in list // let f = i.Key // let r = (!string.IsNullOrEmpty(mappedPath) ? f.Replace(mappedPath, "") : f) // where f.StartsWith(mappedPath, true, CultureInfo.InvariantCulture) && f.Length > mappedPath.Length && r.IndexOf("/", StringComparison.Ordinal) == -1 // select Path.GetFileName(f)).ToArray(); - var pattern = "^" + mappedPath; - return (from i in list - let f = i.Key - let r = (!string.IsNullOrEmpty(mappedPath) ? Regex.Replace(f, pattern, "", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) : f) + return (from i in list + let f = i.Key + let r = !string.IsNullOrEmpty(mappedPath) ? Regex.Replace(f, pattern, string.Empty, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) : f where f.StartsWith(mappedPath, true, CultureInfo.InvariantCulture) && f.Length > mappedPath.Length && r.IndexOf("/", StringComparison.Ordinal) == -1 select Path.GetFileName(f)).ToArray(); - } /// /// Gets the file length. - /// + /// + /// public override long GetFileSize(IFileInfo file) { Requires.NotNull("file", file); @@ -288,18 +284,19 @@ public override long GetFileSize(IFileInfo file) var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); var folder = FolderManager.Instance.GetFolder(file.FolderId); - var item = GetStorageItem(folderMapping, folder.MappedPath + file.FileName); + var item = this.GetStorageItem(folderMapping, folder.MappedPath + file.FileName); if (item == null) { - throw new FileNotFoundException(FileNotFoundMessage, file.RelativePath); + throw new FileNotFoundException(this.FileNotFoundMessage, file.RelativePath); } + return item.Size; - } /// /// Gets a file Stream of the specified file. - /// + /// + /// public override Stream GetFileStream(IFileInfo file) { Requires.NotNull("file", file); @@ -308,12 +305,13 @@ public override Stream GetFileStream(IFileInfo file) var folder = FolderManager.Instance.GetFolder(file.FolderId); - return GetFileStreamInternal(folderMapping, folder.MappedPath + file.FileName); + return this.GetFileStreamInternal(folderMapping, folder.MappedPath + file.FileName); } /// /// Gets a file Stream of the specified file. - /// + /// + /// public override Stream GetFileStream(IFolderInfo folder, string fileName) { Requires.NotNull("folder", folder); @@ -321,12 +319,13 @@ public override Stream GetFileStream(IFolderInfo folder, string fileName) var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - return GetFileStreamInternal(folderMapping, folder.MappedPath + fileName); + return this.GetFileStreamInternal(folderMapping, folder.MappedPath + fileName); } /// /// Gets the time when the specified file was last modified. - /// + /// + /// public override DateTime GetLastModificationTime(IFileInfo file) { Requires.NotNull("file", file); @@ -334,38 +333,40 @@ public override DateTime GetLastModificationTime(IFileInfo file) var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); var folder = FolderManager.Instance.GetFolder(file.FolderId); - var item = GetStorageItem(folderMapping, folder.MappedPath+file.FileName); + var item = this.GetStorageItem(folderMapping, folder.MappedPath + file.FileName); if (item == null) { - throw new FileNotFoundException(FileNotFoundMessage, file.RelativePath); + throw new FileNotFoundException(this.FileNotFoundMessage, file.RelativePath); } - return item.LastModified; + + return item.LastModified; } /// /// Gets the list of subfolders for the specified folder. - /// + /// + /// public override IEnumerable GetSubFolders(string folderPath, FolderMappingInfo folderMapping) { Requires.NotNull("folderPath", folderPath); Requires.NotNull("folderMapping", folderMapping); - var list = GetObjectList(folderMapping, folderPath); - + var list = this.GetObjectList(folderMapping, folderPath); + var pattern = "^" + Regex.Escape(folderPath); - return (from o in list - let f = o.Key - let r = - (!string.IsNullOrEmpty(folderPath) - ? Regex.Replace(f, pattern, "", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) - : f) - where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase) - && f.Length > folderPath.Length - && r.IndexOf("/", StringComparison.Ordinal) > -1 - select folderPath + r.Substring(0, r.IndexOf("/", StringComparison.Ordinal)) + "/").Distinct().ToList(); - - //var mylist = (from o in list + return (from o in list + let f = o.Key + let r = + !string.IsNullOrEmpty(folderPath) + ? Regex.Replace(f, pattern, string.Empty, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) + : f + where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase) + && f.Length > folderPath.Length + && r.IndexOf("/", StringComparison.Ordinal) > -1 + select folderPath + r.Substring(0, r.IndexOf("/", StringComparison.Ordinal)) + "/").Distinct().ToList(); + + // var mylist = (from o in list // let f = o.Key // let r = (!string.IsNullOrEmpty(folderPath) ? RegexUtils.GetCachedRegex(Regex.Escape(folderPath)).Replace(f, string.Empty, 1) : f) // where f.StartsWith(folderPath) @@ -373,8 +374,7 @@ where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase) // && r.IndexOf("/", StringComparison.Ordinal) > -1 // select folderPath + r.Substring(0, r.IndexOf("/", StringComparison.Ordinal)) + "/").Distinct().ToList(); - //return mylist; - + // return mylist; } /// @@ -382,10 +382,11 @@ where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase) /// /// /// For now, it returns false always until we find a better way to check if the file is synchronized. - /// + /// + /// public override bool IsInSync(IFileInfo file) { - return Convert.ToInt32((file.LastModificationTime - GetLastModificationTime(file)).TotalSeconds) == 0; + return Convert.ToInt32((file.LastModificationTime - this.GetLastModificationTime(file)).TotalSeconds) == 0; } /// @@ -397,7 +398,7 @@ public override void MoveFolder(string folderPath, string newFolderPath, FolderM Requires.NotNullOrEmpty("newFolderPath", newFolderPath); Requires.NotNull("folderMapping", folderMapping); - MoveFolderInternal(folderMapping, folderPath, newFolderPath); + this.MoveFolderInternal(folderMapping, folderPath, newFolderPath); } /// @@ -412,7 +413,7 @@ public override void RenameFile(IFileInfo file, string newFileName) var folder = FolderManager.Instance.GetFolder(file.FolderId); - MoveFileInternal(folderMapping, folder.MappedPath + file.FileName, folder.MappedPath + newFileName); + this.MoveFileInternal(folderMapping, folder.MappedPath + file.FileName, folder.MappedPath + newFileName); } /// @@ -432,7 +433,7 @@ public override void RenameFolder(IFolderInfo folder, string newFolderName) mappedPath.Substring(0, mappedPath.LastIndexOf(folder.FolderName, StringComparison.Ordinal)) + newFolderName); - MoveFolderInternal(folderMapping, mappedPath, newMappedPath); + this.MoveFolderInternal(folderMapping, mappedPath, newMappedPath); } } @@ -445,7 +446,8 @@ public override void SetFileAttributes(IFileInfo file, FileAttributes fileAttrib /// /// Amazon doesn't support file attributes. - /// + /// + /// public override bool SupportsFileAttributes() { return false; @@ -463,7 +465,7 @@ public override void UpdateFile(IFileInfo file, Stream content) var folder = FolderManager.Instance.GetFolder(file.FolderId); - UpdateFileInternal(content, folderMapping, folder.MappedPath + file.FileName); + this.UpdateFileInternal(content, folderMapping, folder.MappedPath + file.FileName); } /// @@ -477,7 +479,7 @@ public override void UpdateFile(IFolderInfo folder, string fileName, Stream cont var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - UpdateFileInternal(content, folderMapping, folder.MappedPath + fileName); + this.UpdateFileInternal(content, folderMapping, folder.MappedPath + fileName); } public override string GetHashCode(IFileInfo file) @@ -486,21 +488,23 @@ public override string GetHashCode(IFileInfo file) var folder = FolderManager.Instance.GetFolder(file.FolderId); var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - var item = GetStorageItem(folderMapping, folder.MappedPath + file.FileName); + var item = this.GetStorageItem(folderMapping, folder.MappedPath + file.FileName); if (item == null) { - throw new FileNotFoundException(FileNotFoundMessage, file.RelativePath); + throw new FileNotFoundException(this.FileNotFoundMessage, file.RelativePath); } - return (item.Size == file.Size) ? item.HashCode : String.Empty; + + return (item.Size == file.Size) ? item.HashCode : string.Empty; } public override string GetHashCode(IFileInfo file, Stream fileContent) { - if (FileExists(FolderManager.Instance.GetFolder(file.FolderId), file.FileName)) + if (this.FileExists(FolderManager.Instance.GetFolder(file.FolderId), file.FileName)) { - return GetHashCode(file); + return this.GetHashCode(file); } - return String.Empty; + + return string.Empty; } } } diff --git a/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs b/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs index 8b68b1e59c2..1a7b4fd157e 100644 --- a/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs +++ b/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.Components { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Installer.Packages; + public class BusinessController : IUpgradeable { public string UpgradeModule(string version) @@ -26,6 +27,7 @@ public string UpgradeModule(string version) { DataProvider.Instance().UnRegisterAssembly(package.PackageID, "Microsoft.WindowsAzure.StorageClient.dll"); } + break; } diff --git a/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs b/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs index d45f220378d..d32c5a880ba 100644 --- a/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs +++ b/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs @@ -1,15 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Providers.FolderProviders.Components { + using System; + public interface IRemoteStorageItem { string Key { get; } + DateTime LastModified { get; } + long Size { get; } string HashCode { get; } diff --git a/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj b/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj index 3a2fb2c34ed..28f401c29e4 100644 --- a/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj +++ b/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj @@ -1,140 +1,148 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {B267CE88-DFFC-4BD8-9962-319E79C52526} - Library - Properties - DotNetNuke.Providers.FolderProviders - DotNetNuke.Providers.FolderProviders - v4.7.2 - 512 - - ..\..\..\ - true - - - true - full - false - bin\Providers - DEBUG;TRACE - prompt - 4 - bin\Providers\DotNetNuke.Providers.FolderProviders.XML - 7 - 1591 - - - pdbonly - true - bin\Providers - TRACE - prompt - 4 - bin\Providers\DotNetNuke.Providers.FolderProviders.XML - 1591 - 7 - - - true - full - false - bin\Providers - DEBUG;TRACE;CLOUD;CLOUD_DEBUG - prompt - 4 - bin\Providers\DotNetNuke.Providers.FolderProviders.XML - 7 - 1591 - - - pdbonly - true - bin\Providers - TRACE;CLOUD;CLOUD_RELEASE - prompt - 4 - bin\Providers\DotNetNuke.Providers.FolderProviders.XML - 1591 - 7 - - - - - False - ..\..\Components\WindowsAzure\Microsoft.WindowsAzure.Storage.dll - - - - - - - - - - - - - SolutionInfo.cs - - - - - - - - Settings.ascx - ASPXCodeBehind - - - Settings.ascx.cs - - - - - - - - - - - - - Designer - - - ASPXCodeBehind - - - - - Designer - - - - - - - - {3cd5f6b8-8360-4862-80b6-f402892db7dd} - DotNetNuke.Instrumentation - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {B267CE88-DFFC-4BD8-9962-319E79C52526} + Library + Properties + DotNetNuke.Providers.FolderProviders + DotNetNuke.Providers.FolderProviders + v4.7.2 + 512 + + ..\..\..\ + true + + + true + full + false + bin\Providers + DEBUG;TRACE + prompt + 4 + bin\Providers\DotNetNuke.Providers.FolderProviders.XML + 7 + 1591 + + + pdbonly + true + bin\Providers + TRACE + prompt + 4 + bin\Providers\DotNetNuke.Providers.FolderProviders.XML + 1591 + 7 + + + true + full + false + bin\Providers + DEBUG;TRACE;CLOUD;CLOUD_DEBUG + prompt + 4 + bin\Providers\DotNetNuke.Providers.FolderProviders.XML + 7 + 1591 + + + pdbonly + true + bin\Providers + TRACE;CLOUD;CLOUD_RELEASE + prompt + 4 + bin\Providers\DotNetNuke.Providers.FolderProviders.XML + 1591 + 7 + + + + + False + ..\..\Components\WindowsAzure\Microsoft.WindowsAzure.Storage.dll + + + + + + + + + + + + + SolutionInfo.cs + + + + + + + + Settings.ascx + ASPXCodeBehind + + + Settings.ascx.cs + + + + + + + + + + + + stylecop.json + + + + Designer + + + ASPXCodeBehind + + + + + Designer + + + + + + + + + {3cd5f6b8-8360-4862-80b6-f402892db7dd} + DotNetNuke.Instrumentation + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/DNN Platform/Providers/FolderProviders/FolderProviders.dnn b/DNN Platform/Providers/FolderProviders/FolderProviders.dnn index 736393606bb..07c06a779f1 100644 --- a/DNN Platform/Providers/FolderProviders/FolderProviders.dnn +++ b/DNN Platform/Providers/FolderProviders/FolderProviders.dnn @@ -1,6 +1,6 @@  - + DotNetNuke Folder Providers Azure Folder Providers for DotNetNuke. diff --git a/DNN Platform/Providers/FolderProviders/Properties/AssemblyInfo.cs b/DNN Platform/Providers/FolderProviders/Properties/AssemblyInfo.cs index 99d27069765..8b411a792f3 100644 --- a/DNN Platform/Providers/FolderProviders/Properties/AssemblyInfo.cs +++ b/DNN Platform/Providers/FolderProviders/Properties/AssemblyInfo.cs @@ -1,11 +1,8 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; using System.Reflection; -#endregion [assembly: AssemblyTitle("DotNetNuke")] diff --git a/DNN Platform/Providers/FolderProviders/packages.config b/DNN Platform/Providers/FolderProviders/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Providers/FolderProviders/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Skins/Xcillion/DNN_Skin_Xcillion.dnn b/DNN Platform/Skins/Xcillion/DNN_Skin_Xcillion.dnn index b0df718658c..59863f5baf6 100644 --- a/DNN Platform/Skins/Xcillion/DNN_Skin_Xcillion.dnn +++ b/DNN Platform/Skins/Xcillion/DNN_Skin_Xcillion.dnn @@ -1,6 +1,6 @@ - + Xcillion @@ -29,7 +29,7 @@ - + Xcillion diff --git a/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj b/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj index 4101a5f0c78..e464fe92ab7 100644 --- a/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj +++ b/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj @@ -1,226 +1,239 @@ - - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {104C9117-430C-4389-B67D-B1EFCF8146CB} - {349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - Properties - DotNetNuke.Skins.Xcillion - DotNetNuke.Skins.Xcillion - v4.7.2 - 512 - - true - - - 4.0 - - - - - - ..\..\..\ - true - - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 1 - bin\DotNetNuke.Skins.Xcillion.XML - 1591 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - bin\DotNetNuke.Skins.Xcillion.XML - 1591 - 7 - - - - - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - - - - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll - - - - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - False - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - False - True - 9081 - / - - - False - True - http://localhost/DNN_Platform - False - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {104C9117-430C-4389-B67D-B1EFCF8146CB} + {349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + Library + Properties + DotNetNuke.Skins.Xcillion + DotNetNuke.Skins.Xcillion + v4.7.2 + 512 + + true + + + 4.0 + + + + + + ..\..\..\ + true + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 1 + bin\DotNetNuke.Skins.Xcillion.XML + 1591 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + bin\DotNetNuke.Skins.Xcillion.XML + 1591 + 7 + + + + + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + + + + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll + + + + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + stylecop.json + + + + + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + False + True + 9081 + / + + + False + True + http://localhost/DNN_Platform + False + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/DNN Platform/Skins/Xcillion/packages.config b/DNN Platform/Skins/Xcillion/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Skins/Xcillion/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Syndication/DotNetNuke.Syndication.csproj b/DNN Platform/Syndication/DotNetNuke.Syndication.csproj index c8f0bf39a11..094b0dc7459 100644 --- a/DNN Platform/Syndication/DotNetNuke.Syndication.csproj +++ b/DNN Platform/Syndication/DotNetNuke.Syndication.csproj @@ -1,107 +1,119 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {9F2F4076-D434-448F-9CBB-7BF7A9766AB1} - Library - Properties - DotNetNuke.Services.Syndication - DotNetNuke.Services.Syndication - v4.7.2 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - full - bin\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - bin\DotNetNuke.Services.Syndication.xml - 1591 - 7 - - - pdbonly - bin\ - TRACE - prompt - 4 - true - AllRules.ruleset - 1591 - bin\DotNetNuke.Services.Syndication.xml - true - 7 - - - - False - ..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll - - - - - - - - - - SolutionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - $(MSBuildProjectDirectory)\..\.. - - - - - - - - - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {9F2F4076-D434-448F-9CBB-7BF7A9766AB1} + Library + Properties + DotNetNuke.Services.Syndication + DotNetNuke.Services.Syndication + v4.7.2 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + bin\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + bin\DotNetNuke.Services.Syndication.xml + 1591 + 7 + + + pdbonly + bin\ + TRACE + prompt + 4 + true + AllRules.ruleset + 1591 + bin\DotNetNuke.Services.Syndication.xml + true + 7 + + + + False + ..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll + + + + + + + + + + SolutionInfo.cs + + + + + + + + + + + + + + + + + + + + + + + + + + stylecop.json + + + + + + + + + + + + $(MSBuildProjectDirectory)\..\.. + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Syndication/OPML/Opml.cs b/DNN Platform/Syndication/OPML/Opml.cs index da58963e0b2..29c379918bd 100644 --- a/DNN Platform/Syndication/OPML/Opml.cs +++ b/DNN Platform/Syndication/OPML/Opml.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Xml; - -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Xml; + + using DotNetNuke.Instrumentation; + /// - /// Class for managing an OPML feed + /// Class for managing an OPML feed. /// public class Opml { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Opml)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Opml)); private DateTime _dateCreated = DateTime.MinValue; private DateTime _dateModified = DateTime.MinValue; private string _docs = string.Empty; @@ -38,18 +33,19 @@ public class Opml public Opml() { - _outlines = new OpmlOutlines(); + this._outlines = new OpmlOutlines(); } public DateTime UtcExpiry { get { - return _utcExpiry; + return this._utcExpiry; } + set { - _utcExpiry = value; + this._utcExpiry = value; } } @@ -57,11 +53,12 @@ public string Title { get { - return _title; + return this._title; } + set { - _title = value; + this._title = value; } } @@ -69,11 +66,12 @@ public DateTime DateCreated { get { - return _dateCreated; + return this._dateCreated; } + set { - _dateCreated = value; + this._dateCreated = value; } } @@ -81,11 +79,12 @@ public DateTime DateModified { get { - return _dateModified; + return this._dateModified; } + set { - _dateModified = value; + this._dateModified = value; } } @@ -93,11 +92,12 @@ public string OwnerName { get { - return _ownerName; + return this._ownerName; } + set { - _ownerName = value; + this._ownerName = value; } } @@ -105,11 +105,12 @@ public string OwnerEmail { get { - return _ownerEmail; + return this._ownerEmail; } + set { - _ownerEmail = value; + this._ownerEmail = value; } } @@ -117,11 +118,12 @@ public string OwnerId { get { - return _ownerId; + return this._ownerId; } + set { - _ownerId = value; + this._ownerId = value; } } @@ -129,11 +131,12 @@ public string Docs { get { - return _docs; + return this._docs; } + set { - _docs = value; + this._docs = value; } } @@ -141,11 +144,12 @@ public string ExpansionState { get { - return _expansionState; + return this._expansionState; } + set { - _expansionState = value; + this._expansionState = value; } } @@ -153,11 +157,12 @@ public string VertScrollState { get { - return _vertScrollState; + return this._vertScrollState; } + set { - _vertScrollState = value; + this._vertScrollState = value; } } @@ -165,11 +170,12 @@ public string WindowTop { get { - return _windowTop; + return this._windowTop; } + set { - _windowTop = value; + this._windowTop = value; } } @@ -177,11 +183,12 @@ public string WindowLeft { get { - return _windowLeft; + return this._windowLeft; } + set { - _windowLeft = value; + this._windowLeft = value; } } @@ -189,11 +196,12 @@ public string WindowBottom { get { - return _windowBottom; + return this._windowBottom; } + set { - _windowBottom = value; + this._windowBottom = value; } } @@ -201,11 +209,12 @@ public string WindowRight { get { - return _windowRight; + return this._windowRight; } + set { - _windowRight = value; + this._windowRight = value; } } @@ -213,22 +222,43 @@ public OpmlOutlines Outlines { get { - return _outlines; + return this._outlines; } + set { - _outlines = value; + this._outlines = value; + } + } + + public static Opml LoadFromUrl(Uri uri) + { + return OpmlDownloadManager.GetOpmlFeed(uri); + } + + public static Opml LoadFromFile(string path) + { + try + { + var opmlDoc = new XmlDocument { XmlResolver = null }; + opmlDoc.Load(path); + + return LoadFromXml(opmlDoc); + } + catch + { + return new Opml(); } } public void AddOutline(OpmlOutline item) { - _outlines.Add(item); + this._outlines.Add(item); } public void AddOutline(string text, string type, Uri xmlUrl, string category) { - AddOutline(text, type, xmlUrl, category, null); + this.AddOutline(text, type, xmlUrl, category, null); } public void AddOutline(string text, string type, Uri xmlUrl, string category, OpmlOutlines outlines) @@ -239,120 +269,100 @@ public void AddOutline(string text, string type, Uri xmlUrl, string category, Op item.XmlUrl = xmlUrl; item.Category = category; item.Outlines = outlines; - _outlines.Add(item); + this._outlines.Add(item); } public string GetXml() { - return opmlDoc.OuterXml; + return this.opmlDoc.OuterXml; } public void Save(string fileName) { - opmlDoc = new XmlDocument { XmlResolver = null }; - XmlElement opml = opmlDoc.CreateElement("opml"); + this.opmlDoc = new XmlDocument { XmlResolver = null }; + XmlElement opml = this.opmlDoc.CreateElement("opml"); opml.SetAttribute("version", "2.0"); - opmlDoc.AppendChild(opml); + this.opmlDoc.AppendChild(opml); - // create head - XmlElement head = opmlDoc.CreateElement("head"); + // create head + XmlElement head = this.opmlDoc.CreateElement("head"); opml.AppendChild(head); // set Title - XmlElement title = opmlDoc.CreateElement("title"); - title.InnerText = Title; + XmlElement title = this.opmlDoc.CreateElement("title"); + title.InnerText = this.Title; head.AppendChild(title); // set date created - XmlElement dateCreated = opmlDoc.CreateElement("dateCreated"); - dateCreated.InnerText = DateCreated != DateTime.MinValue ? DateCreated.ToString("r", null) : DateTime.Now.ToString("r", null); + XmlElement dateCreated = this.opmlDoc.CreateElement("dateCreated"); + dateCreated.InnerText = this.DateCreated != DateTime.MinValue ? this.DateCreated.ToString("r", null) : DateTime.Now.ToString("r", null); head.AppendChild(dateCreated); // set date modified - XmlElement dateModified = opmlDoc.CreateElement("dateModified"); - dateCreated.InnerText = DateModified != DateTime.MinValue ? DateModified.ToString("r", null) : DateTime.Now.ToString("r", null); + XmlElement dateModified = this.opmlDoc.CreateElement("dateModified"); + dateCreated.InnerText = this.DateModified != DateTime.MinValue ? this.DateModified.ToString("r", null) : DateTime.Now.ToString("r", null); head.AppendChild(dateModified); // set owner email - XmlElement ownerEmail = opmlDoc.CreateElement("ownerEmail"); - ownerEmail.InnerText = OwnerEmail; + XmlElement ownerEmail = this.opmlDoc.CreateElement("ownerEmail"); + ownerEmail.InnerText = this.OwnerEmail; head.AppendChild(ownerEmail); // set owner name - XmlElement ownerName = opmlDoc.CreateElement("ownerName"); - ownerName.InnerText = OwnerName; + XmlElement ownerName = this.opmlDoc.CreateElement("ownerName"); + ownerName.InnerText = this.OwnerName; head.AppendChild(ownerName); // set owner id - XmlElement ownerId = opmlDoc.CreateElement("ownerId"); - ownerId.InnerText = OwnerId; + XmlElement ownerId = this.opmlDoc.CreateElement("ownerId"); + ownerId.InnerText = this.OwnerId; head.AppendChild(ownerId); // set docs - XmlElement docs = opmlDoc.CreateElement("docs"); - docs.InnerText = Docs; + XmlElement docs = this.opmlDoc.CreateElement("docs"); + docs.InnerText = this.Docs; head.AppendChild(docs); // set expansionState - XmlElement expansionState = opmlDoc.CreateElement("expansionState"); - expansionState.InnerText = ExpansionState; + XmlElement expansionState = this.opmlDoc.CreateElement("expansionState"); + expansionState.InnerText = this.ExpansionState; head.AppendChild(expansionState); // set vertScrollState - XmlElement vertScrollState = opmlDoc.CreateElement("vertScrollState"); - vertScrollState.InnerText = VertScrollState; + XmlElement vertScrollState = this.opmlDoc.CreateElement("vertScrollState"); + vertScrollState.InnerText = this.VertScrollState; head.AppendChild(vertScrollState); // set windowTop - XmlElement windowTop = opmlDoc.CreateElement("windowTop"); - windowTop.InnerText = WindowTop; + XmlElement windowTop = this.opmlDoc.CreateElement("windowTop"); + windowTop.InnerText = this.WindowTop; head.AppendChild(windowTop); // set windowLeft - XmlElement windowLeft = opmlDoc.CreateElement("windowLeft"); - windowLeft.InnerText = WindowLeft; + XmlElement windowLeft = this.opmlDoc.CreateElement("windowLeft"); + windowLeft.InnerText = this.WindowLeft; head.AppendChild(windowLeft); // set windowBottom - XmlElement windowBottom = opmlDoc.CreateElement("windowBottom"); - windowBottom.InnerText = WindowBottom; + XmlElement windowBottom = this.opmlDoc.CreateElement("windowBottom"); + windowBottom.InnerText = this.WindowBottom; head.AppendChild(windowBottom); // set windowRight - XmlElement windowRight = opmlDoc.CreateElement("windowRight"); - windowRight.InnerText = WindowRight; + XmlElement windowRight = this.opmlDoc.CreateElement("windowRight"); + windowRight.InnerText = this.WindowRight; head.AppendChild(windowRight); // create body - XmlElement opmlBody = opmlDoc.CreateElement("body"); + XmlElement opmlBody = this.opmlDoc.CreateElement("body"); opml.AppendChild(opmlBody); - foreach (OpmlOutline outline in _outlines) + foreach (OpmlOutline outline in this._outlines) { opmlBody.AppendChild(outline.ToXml); } - opmlDoc.Save(fileName); - } - - public static Opml LoadFromUrl(Uri uri) - { - return (OpmlDownloadManager.GetOpmlFeed(uri)); - } - - public static Opml LoadFromFile(string path) - { - try - { - var opmlDoc = new XmlDocument { XmlResolver = null }; - opmlDoc.Load(path); - - return (LoadFromXml(opmlDoc)); - } - catch - { - return (new Opml()); - } + this.opmlDoc.Save(fileName); } public static Opml LoadFromXml(XmlDocument doc) @@ -453,7 +463,7 @@ public static Opml LoadFromXml(XmlDocument doc) } catch { - return (new Opml()); + return new Opml(); } } @@ -463,35 +473,35 @@ internal static OpmlOutline ParseXml(XmlElement node) newOutline.Text = ParseElement(node, "text"); newOutline.Type = ParseElement(node, "type"); - newOutline.IsComment = (ParseElement(node, "isComment") == "true" ? true : false); - newOutline.IsBreakpoint = (ParseElement(node, "isBreakpoint") == "true" ? true : false); + newOutline.IsComment = ParseElement(node, "isComment") == "true" ? true : false; + newOutline.IsBreakpoint = ParseElement(node, "isBreakpoint") == "true" ? true : false; try { newOutline.Created = DateTime.Parse(ParseElement(node, "created")); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } newOutline.Category = ParseElement(node, "category"); try { newOutline.XmlUrl = new Uri(ParseElement(node, "xmlUrl")); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } try { newOutline.HtmlUrl = new Uri(ParseElement(node, "htmlUrl")); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } newOutline.Language = ParseElement(node, "language"); newOutline.Title = ParseElement(node, "title"); @@ -500,10 +510,10 @@ internal static OpmlOutline ParseXml(XmlElement node) { newOutline.Url = new Uri(ParseElement(node, "url")); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } newOutline.Description = ParseElement(node, "description"); @@ -521,7 +531,7 @@ internal static OpmlOutline ParseXml(XmlElement node) private static string ParseElement(XmlElement node, string attribute) { string attrValue = node.GetAttribute(attribute); - return (!String.IsNullOrEmpty(attrValue) ? attrValue : string.Empty); + return !string.IsNullOrEmpty(attrValue) ? attrValue : string.Empty; } } } diff --git a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs index bf5eb4720f7..4c0ed9fb59c 100644 --- a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs +++ b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Web; -using System.Xml; - -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Web; + using System.Xml; + + using DotNetNuke.Instrumentation; + /// - /// Helper class that provides memory and disk caching of the downloaded feeds + /// Helper class that provides memory and disk caching of the downloaded feeds. /// internal class OpmlDownloadManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (OpmlDownloadManager)); private const string OPML_Dir = "/OPML/"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OpmlDownloadManager)); private static readonly OpmlDownloadManager _theManager = new OpmlDownloadManager(); private readonly Dictionary _cache; @@ -33,12 +28,12 @@ internal class OpmlDownloadManager private OpmlDownloadManager() { // create in-memory cache - _cache = new Dictionary(); + this._cache = new Dictionary(); - _defaultTtlMinutes = 60; + this._defaultTtlMinutes = 60; // prepare disk directory - _directoryOnDisk = PrepareTempDir(); + this._directoryOnDisk = PrepareTempDir(); } public static Opml GetOpmlFeed(Uri uri) @@ -50,13 +45,13 @@ internal Opml GetFeed(Uri uri) { Opml opmlFeed = null; - lock (_cache) + lock (this._cache) { - if (_cache.TryGetValue(uri.AbsoluteUri, out opmlFeed)) + if (this._cache.TryGetValue(uri.AbsoluteUri, out opmlFeed)) { if (DateTime.UtcNow > opmlFeed.UtcExpiry) { - _cache.Remove(uri.AbsoluteUri); + this._cache.Remove(uri.AbsoluteUri); opmlFeed = null; } } @@ -64,25 +59,60 @@ internal Opml GetFeed(Uri uri) if (opmlFeed == null) { - opmlFeed = DownloadOpmlFeed(uri); + opmlFeed = this.DownloadOpmlFeed(uri); - lock (_cache) + lock (this._cache) { - _cache[uri.AbsoluteUri] = opmlFeed; + this._cache[uri.AbsoluteUri] = opmlFeed; } } return opmlFeed; } + + private static string PrepareTempDir() + { + string tempDir = null; + + try + { + string d = HttpContext.Current.Server.MapPath(Settings.CacheRoot + OPML_Dir); + + if (!Directory.Exists(d)) + { + Directory.CreateDirectory(d); + } + + tempDir = d; + } + catch + { + // don't cache on disk if can't do it + } + + return tempDir; + } + + private static string GetTempFileNamePrefixFromUrl(Uri uri) + { + try + { + return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); + } + catch + { + return "opml"; + } + } private Opml DownloadOpmlFeed(Uri uri) { // look for disk cache first - Opml opmlFeed = TryLoadFromDisk(uri); + Opml opmlFeed = this.TryLoadFromDisk(uri); if (opmlFeed != null) { - return (opmlFeed); + return opmlFeed; } // May fail under partial trust @@ -94,31 +124,31 @@ private Opml DownloadOpmlFeed(Uri uri) opmlDoc.Load(new MemoryStream(feed)); opmlFeed = Opml.LoadFromXml(opmlDoc); - opmlFeed.UtcExpiry = DateTime.UtcNow.AddMinutes(_defaultTtlMinutes); + opmlFeed.UtcExpiry = DateTime.UtcNow.AddMinutes(this._defaultTtlMinutes); // save to disk - TrySaveToDisk(opmlDoc, uri, opmlFeed.UtcExpiry); + this.TrySaveToDisk(opmlDoc, uri, opmlFeed.UtcExpiry); } catch { - return (new Opml()); + return new Opml(); } - return (opmlFeed); + return opmlFeed; } private Opml TryLoadFromDisk(Uri uri) { - if (_directoryOnDisk == null) + if (this._directoryOnDisk == null) { - return (null); // no place to cache + return null; // no place to cache } // look for all files matching the prefix // looking for the one matching url that is not expired // removing expired (or invalid) ones string pattern = GetTempFileNamePrefixFromUrl(uri) + "_*.opml.resources"; - string[] files = Directory.GetFiles(_directoryOnDisk, pattern, SearchOption.TopDirectoryOnly); + string[] files = Directory.GetFiles(this._directoryOnDisk, pattern, SearchOption.TopDirectoryOnly); foreach (string opmlFilename in files) { @@ -162,10 +192,10 @@ private Opml TryLoadFromDisk(Uri uri) { File.Delete(opmlFilename); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } // try next file continue; @@ -187,7 +217,7 @@ private Opml TryLoadFromDisk(Uri uri) private void TrySaveToDisk(XmlDocument doc, Uri uri, DateTime utcExpiry) { - if (_directoryOnDisk == null) + if (this._directoryOnDisk == null) { return; } @@ -198,48 +228,12 @@ private void TrySaveToDisk(XmlDocument doc, Uri uri, DateTime utcExpiry) try { - doc.Save(Path.Combine(_directoryOnDisk, fileName)); + doc.Save(Path.Combine(this._directoryOnDisk, fileName)); } catch { // can't save to disk - not a problem } } - - - private static string PrepareTempDir() - { - string tempDir = null; - - try - { - string d = HttpContext.Current.Server.MapPath(Settings.CacheRoot + OPML_Dir); - - if (!Directory.Exists(d)) - { - Directory.CreateDirectory(d); - } - - tempDir = d; - } - catch - { - // don't cache on disk if can't do it - } - - return tempDir; - } - - private static string GetTempFileNamePrefixFromUrl(Uri uri) - { - try - { - return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); - } - catch - { - return "opml"; - } - } } } diff --git a/DNN Platform/Syndication/OPML/OpmlOutline.cs b/DNN Platform/Syndication/OPML/OpmlOutline.cs index cb81e262c0e..95a4a2222b9 100644 --- a/DNN Platform/Syndication/OPML/OpmlOutline.cs +++ b/DNN Platform/Syndication/OPML/OpmlOutline.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + using System.Xml; + /// - /// Class for managing an OPML feed outline + /// Class for managing an OPML feed outline. /// public class OpmlOutline { @@ -27,18 +22,19 @@ public class OpmlOutline public OpmlOutline() { - Outlines = new OpmlOutlines(); + this.Outlines = new OpmlOutlines(); } public string Description { get { - return _description; + return this._description; } + set { - _description = value; + this._description = value; } } @@ -46,11 +42,12 @@ public string Title { get { - return _title; + return this._title; } + set { - _title = value; + this._title = value; } } @@ -58,11 +55,12 @@ public string Type { get { - return _type; + return this._type; } + set { - _type = value; + this._type = value; } } @@ -70,11 +68,12 @@ public string Text { get { - return _text; + return this._text; } + set { - _text = value; + this._text = value; } } @@ -88,11 +87,12 @@ public DateTime Created { get { - return _created; + return this._created; } + set { - _created = value; + this._created = value; } } @@ -104,11 +104,12 @@ public string Category { get { - return _category; + return this._category; } + set { - _category = value; + this._category = value; } } @@ -116,11 +117,12 @@ public string Language { get { - return _language; + return this._language; } + set { - _language = value; + this._language = value; } } @@ -131,8 +133,7 @@ public string Version return "2.0"; } } - - + public OpmlOutlines Outlines { get; set; } public XmlElement ToXml @@ -142,60 +143,60 @@ public XmlElement ToXml var opmlDoc = new XmlDocument { XmlResolver = null }; XmlElement outlineNode = opmlDoc.CreateElement("outline"); - if (!String.IsNullOrEmpty(Title)) + if (!string.IsNullOrEmpty(this.Title)) { - outlineNode.SetAttribute("title", Title); + outlineNode.SetAttribute("title", this.Title); } - if (!String.IsNullOrEmpty(Description)) + if (!string.IsNullOrEmpty(this.Description)) { - outlineNode.SetAttribute("description", Description); + outlineNode.SetAttribute("description", this.Description); } - if (!String.IsNullOrEmpty(Text)) + if (!string.IsNullOrEmpty(this.Text)) { - outlineNode.SetAttribute("text", Text); + outlineNode.SetAttribute("text", this.Text); } - if (!String.IsNullOrEmpty(Type)) + if (!string.IsNullOrEmpty(this.Type)) { - outlineNode.SetAttribute("type", Type); + outlineNode.SetAttribute("type", this.Type); } - if (!String.IsNullOrEmpty(Language)) + if (!string.IsNullOrEmpty(this.Language)) { - outlineNode.SetAttribute("language", Language); + outlineNode.SetAttribute("language", this.Language); } - if (!String.IsNullOrEmpty(Category)) + if (!string.IsNullOrEmpty(this.Category)) { - outlineNode.SetAttribute("category", Category); + outlineNode.SetAttribute("category", this.Category); } - if (Created > DateTime.MinValue) + if (this.Created > DateTime.MinValue) { - outlineNode.SetAttribute("created", Created.ToString("r", null)); + outlineNode.SetAttribute("created", this.Created.ToString("r", null)); } - if (HtmlUrl != null) + if (this.HtmlUrl != null) { - outlineNode.SetAttribute("htmlUrl", HtmlUrl.ToString()); + outlineNode.SetAttribute("htmlUrl", this.HtmlUrl.ToString()); } - if (XmlUrl != null) + if (this.XmlUrl != null) { - outlineNode.SetAttribute("xmlUrl", XmlUrl.ToString()); + outlineNode.SetAttribute("xmlUrl", this.XmlUrl.ToString()); } - if (Url != null) + if (this.Url != null) { - outlineNode.SetAttribute("url", Url.ToString()); + outlineNode.SetAttribute("url", this.Url.ToString()); } - outlineNode.SetAttribute("isComment", (IsComment ? "true" : "false")); - outlineNode.SetAttribute("isBreakpoint", (IsBreakpoint ? "true" : "false")); + outlineNode.SetAttribute("isComment", this.IsComment ? "true" : "false"); + outlineNode.SetAttribute("isBreakpoint", this.IsBreakpoint ? "true" : "false"); - foreach (OpmlOutline childOutline in Outlines) + foreach (OpmlOutline childOutline in this.Outlines) { outlineNode.AppendChild(childOutline.ToXml); } diff --git a/DNN Platform/Syndication/Properties/AssemblyInfo.cs b/DNN Platform/Syndication/Properties/AssemblyInfo.cs index 276e179e0a3..cf3226f927f 100644 --- a/DNN Platform/Syndication/Properties/AssemblyInfo.cs +++ b/DNN Platform/Syndication/Properties/AssemblyInfo.cs @@ -1,14 +1,9 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information using System; -using System.Reflection; - -#endregion - +using System.Reflection; + [assembly: AssemblyTitle("DotNetNuke.Syndication")] [assembly: AssemblyDescription("")] diff --git a/DNN Platform/Syndication/RSS/GenericRssChannel.cs b/DNN Platform/Syndication/RSS/GenericRssChannel.cs index 5ac38786aab..099ff853d9a 100644 --- a/DNN Platform/Syndication/RSS/GenericRssChannel.cs +++ b/DNN Platform/Syndication/RSS/GenericRssChannel.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.Collections.Generic; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System.Collections; + using System.Collections.Generic; + using System.Xml; + /// - /// Class to consume (or create) a channel in a late-bound way + /// Class to consume (or create) a channel in a late-bound way. /// public sealed class GenericRssChannel : RssChannelBase { @@ -25,23 +20,24 @@ public sealed class GenericRssChannel : RssChannelBase 0 && data.Count >= maxItems) { diff --git a/DNN Platform/Syndication/RSS/GenericRssElement.cs b/DNN Platform/Syndication/RSS/GenericRssElement.cs index 2a49885fa6a..b47e0e05b28 100644 --- a/DNN Platform/Syndication/RSS/GenericRssElement.cs +++ b/DNN Platform/Syndication/RSS/GenericRssElement.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System.Collections.Generic; + /// - /// Late-bound RSS element (used for late bound item and image) + /// Late-bound RSS element (used for late bound item and image). /// public sealed class GenericRssElement : RssElementBase { @@ -27,11 +22,12 @@ public string this[string attributeName] { get { - return GetAttributeValue(attributeName); + return this.GetAttributeValue(attributeName); } + set { - Attributes[attributeName] = value; + this.Attributes[attributeName] = value; } } } diff --git a/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs b/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs index 88402f63b39..25f7fc934d9 100644 --- a/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs +++ b/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Syndication { /// - /// Late-bound RSS HTTP Handler to publish RSS channel + /// Late-bound RSS HTTP Handler to publish RSS channel. /// public class GenericRssHttpHandlerBase : RssHttpHandlerBase { diff --git a/DNN Platform/Syndication/RSS/RssChannelBase.cs b/DNN Platform/Syndication/RSS/RssChannelBase.cs index 5354ad11190..5803e2c71a7 100644 --- a/DNN Platform/Syndication/RSS/RssChannelBase.cs +++ b/DNN Platform/Syndication/RSS/RssChannelBase.cs @@ -1,22 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System.Collections.Generic; + using System.Xml; + /// - /// Base class for RSS channel (for strongly-typed and late-bound channel types) + /// Base class for RSS channel (for strongly-typed and late-bound channel types). /// /// /// - public abstract class RssChannelBase : RssElementBase where RssItemType : RssElementBase, new() where RssImageType : RssElementBase, new() + public abstract class RssChannelBase : RssElementBase + where RssItemType : RssElementBase, new() + where RssImageType : RssElementBase, new() { private readonly List _items = new List(); private RssImageType _image; @@ -26,7 +23,7 @@ public List Items { get { - return _items; + return this._items; } } @@ -34,42 +31,44 @@ internal string Url { get { - return _url; + return this._url; } } - protected void LoadFromUrl(string url) + public XmlDocument SaveAsXml() { - // download the feed - RssChannelDom dom = RssDownloadManager.GetChannel(url); - - // create the channel - LoadFromDom(dom); - - // remember the url - _url = url; + return this.SaveAsXml(RssXmlHelper.CreateEmptyRssXml()); } - protected void LoadFromXml(XmlDocument doc) + public XmlDocument SaveAsXml(XmlDocument EmptyRssXml) { - // parse XML - RssChannelDom dom = RssXmlHelper.ParseChannelXml(doc); + XmlDocument doc = EmptyRssXml; + XmlNode channelNode = RssXmlHelper.SaveRssElementAsXml(doc.DocumentElement, this, "channel"); - // create the channel - LoadFromDom(dom); + if (this._image != null) + { + RssXmlHelper.SaveRssElementAsXml(channelNode, this._image, "image"); + } + + foreach (RssItemType item in this._items) + { + RssXmlHelper.SaveRssElementAsXml(channelNode, item, "item"); + } + + return doc; } internal void LoadFromDom(RssChannelDom dom) { // channel attributes - SetAttributes(dom.Channel); + this.SetAttributes(dom.Channel); // image attributes if (dom.Image != null) { var image = new RssImageType(); image.SetAttributes(dom.Image); - _image = image; + this._image = image; } // items @@ -77,41 +76,39 @@ internal void LoadFromDom(RssChannelDom dom) { var item = new RssItemType(); item.SetAttributes(i); - _items.Add(item); + this._items.Add(item); } } - public XmlDocument SaveAsXml() + protected void LoadFromUrl(string url) { - return SaveAsXml(RssXmlHelper.CreateEmptyRssXml()); - } + // download the feed + RssChannelDom dom = RssDownloadManager.GetChannel(url); - public XmlDocument SaveAsXml(XmlDocument EmptyRssXml) - { - XmlDocument doc = EmptyRssXml; - XmlNode channelNode = RssXmlHelper.SaveRssElementAsXml(doc.DocumentElement, this, "channel"); + // create the channel + this.LoadFromDom(dom); - if (_image != null) - { - RssXmlHelper.SaveRssElementAsXml(channelNode, _image, "image"); - } + // remember the url + this._url = url; + } - foreach (RssItemType item in _items) - { - RssXmlHelper.SaveRssElementAsXml(channelNode, item, "item"); - } + protected void LoadFromXml(XmlDocument doc) + { + // parse XML + RssChannelDom dom = RssXmlHelper.ParseChannelXml(doc); - return doc; + // create the channel + this.LoadFromDom(dom); } protected RssImageType GetImage() { - if (_image == null) + if (this._image == null) { - _image = new RssImageType(); + this._image = new RssImageType(); } - return _image; + return this._image; } } } diff --git a/DNN Platform/Syndication/RSS/RssChannelDom.cs b/DNN Platform/Syndication/RSS/RssChannelDom.cs index 9f8ca94acfb..2eba4db526e 100644 --- a/DNN Platform/Syndication/RSS/RssChannelDom.cs +++ b/DNN Platform/Syndication/RSS/RssChannelDom.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + /// - /// Internal representation of parsed RSS channel + /// Internal representation of parsed RSS channel. /// internal class RssChannelDom { @@ -23,17 +18,17 @@ internal class RssChannelDom internal RssChannelDom(Dictionary channel, Dictionary image, List> items) { - _channel = channel; - _image = image; - _items = items; - _utcExpiry = DateTime.MaxValue; + this._channel = channel; + this._image = image; + this._items = items; + this._utcExpiry = DateTime.MaxValue; } internal Dictionary Channel { get { - return _channel; + return this._channel; } } @@ -41,7 +36,7 @@ internal Dictionary Image { get { - return _image; + return this._image; } } @@ -49,7 +44,7 @@ internal List> Items { get { - return _items; + return this._items; } } @@ -57,13 +52,13 @@ internal DateTime UtcExpiry { get { - return _utcExpiry; + return this._utcExpiry; } } internal void SetExpiry(DateTime utcExpiry) { - _utcExpiry = utcExpiry; + this._utcExpiry = utcExpiry; } } } diff --git a/DNN Platform/Syndication/RSS/RssDataSource.cs b/DNN Platform/Syndication/RSS/RssDataSource.cs index 9a0a072b39c..e715b253a1d 100644 --- a/DNN Platform/Syndication/RSS/RssDataSource.cs +++ b/DNN Platform/Syndication/RSS/RssDataSource.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections; -using System.ComponentModel; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System.Collections; + using System.ComponentModel; + using System.Web.UI; + /// - /// RSS data source control implementation, including the designer + /// RSS data source control implementation, including the designer. /// [DefaultProperty("Url")] public class RssDataSource : DataSourceControl @@ -26,19 +21,19 @@ public GenericRssChannel Channel { get { - if (_channel == null) + if (this._channel == null) { - if (string.IsNullOrEmpty(_url)) + if (string.IsNullOrEmpty(this._url)) { - _channel = new GenericRssChannel(); + this._channel = new GenericRssChannel(); } else { - _channel = GenericRssChannel.LoadChannel(_url); + this._channel = GenericRssChannel.LoadChannel(this._url); } } - return _channel; + return this._channel; } } @@ -48,24 +43,24 @@ public string Url { get { - return _url; + return this._url; } set { - _channel = null; - _url = value; + this._channel = null; + this._url = value; } } protected override DataSourceView GetView(string viewName) { - if (_itemsView == null) + if (this._itemsView == null) { - _itemsView = new RssDataSourceView(this, viewName); + this._itemsView = new RssDataSourceView(this, viewName); } - return _itemsView; + return this._itemsView; } } @@ -73,19 +68,20 @@ public class RssDataSourceView : DataSourceView { private readonly RssDataSource _owner; - internal RssDataSourceView(RssDataSource owner, string viewName) : base(owner, viewName) + internal RssDataSourceView(RssDataSource owner, string viewName) + : base(owner, viewName) { - _owner = owner; + this._owner = owner; } public override void Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) { - callback(ExecuteSelect(arguments)); + callback(this.ExecuteSelect(arguments)); } protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) { - return _owner.Channel.SelectItems(_owner.MaxItems); + return this._owner.Channel.SelectItems(this._owner.MaxItems); } } } diff --git a/DNN Platform/Syndication/RSS/RssDownloadManager.cs b/DNN Platform/Syndication/RSS/RssDownloadManager.cs index fee49955830..cbaa59e6c6f 100644 --- a/DNN Platform/Syndication/RSS/RssDownloadManager.cs +++ b/DNN Platform/Syndication/RSS/RssDownloadManager.cs @@ -1,29 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Web; -using System.Xml; - -using DotNetNuke.Instrumentation; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Web; + using System.Xml; + + using DotNetNuke.Instrumentation; + /// - /// Helper class that provides memory and disk caching of the downloaded feeds + /// Helper class that provides memory and disk caching of the downloaded feeds. /// internal class RssDownloadManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (RssDownloadManager)); private const string RSS_Dir = "/RSS/"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RssDownloadManager)); private static readonly RssDownloadManager _theManager = new RssDownloadManager(); private readonly Dictionary _cache; @@ -33,18 +28,40 @@ internal class RssDownloadManager private RssDownloadManager() { // create in-memory cache - _cache = new Dictionary(); + this._cache = new Dictionary(); - _defaultTtlMinutes = 2; + this._defaultTtlMinutes = 2; // prepare disk directory - _directoryOnDisk = PrepareTempDir(); + this._directoryOnDisk = PrepareTempDir(); + } + + public static RssChannelDom GetChannel(string url) + { + return _theManager.GetChannelDom(url); + } + + private static int GetTtlFromString(string ttlString, int defaultTtlMinutes) + { + if (!string.IsNullOrEmpty(ttlString)) + { + int ttlMinutes; + if (int.TryParse(ttlString, out ttlMinutes)) + { + if (ttlMinutes >= 0) + { + return ttlMinutes; + } + } + } + + return defaultTtlMinutes; } private RssChannelDom DownloadChannelDom(string url) { // look for disk cache first - RssChannelDom dom = TryLoadFromDisk(url); + RssChannelDom dom = this.TryLoadFromDisk(url); if (dom != null) { @@ -64,19 +81,19 @@ private RssChannelDom DownloadChannelDom(string url) // set expiry string ttlString = null; dom.Channel.TryGetValue("ttl", out ttlString); - int ttlMinutes = GetTtlFromString(ttlString, _defaultTtlMinutes); + int ttlMinutes = GetTtlFromString(ttlString, this._defaultTtlMinutes); DateTime utcExpiry = DateTime.UtcNow.AddMinutes(ttlMinutes); dom.SetExpiry(utcExpiry); // save to disk - TrySaveToDisk(doc, url, utcExpiry); + this.TrySaveToDisk(doc, url, utcExpiry); return dom; } private RssChannelDom TryLoadFromDisk(string url) { - if (_directoryOnDisk == null) + if (this._directoryOnDisk == null) { return null; // no place to cache } @@ -85,7 +102,7 @@ private RssChannelDom TryLoadFromDisk(string url) // looking for the one matching url that is not expired // removing expired (or invalid) ones string pattern = GetTempFileNamePrefixFromUrl(url) + "_*.rss.resources"; - string[] files = Directory.GetFiles(_directoryOnDisk, pattern, SearchOption.TopDirectoryOnly); + string[] files = Directory.GetFiles(this._directoryOnDisk, pattern, SearchOption.TopDirectoryOnly); foreach (string rssFilename in files) { @@ -129,10 +146,10 @@ private RssChannelDom TryLoadFromDisk(string url) { File.Delete(rssFilename); } - catch (Exception ex) - { - Logger.Error(ex); - } + catch (Exception ex) + { + Logger.Error(ex); + } // try next file continue; @@ -154,7 +171,7 @@ private RssChannelDom TryLoadFromDisk(string url) private void TrySaveToDisk(XmlDocument doc, string url, DateTime utcExpiry) { - if (_directoryOnDisk == null) + if (this._directoryOnDisk == null) { return; } @@ -165,7 +182,7 @@ private void TrySaveToDisk(XmlDocument doc, string url, DateTime utcExpiry) try { - doc.Save(Path.Combine(_directoryOnDisk, fileName)); + doc.Save(Path.Combine(this._directoryOnDisk, fileName)); } catch { @@ -177,13 +194,13 @@ private RssChannelDom GetChannelDom(string url) { RssChannelDom dom = null; - lock (_cache) + lock (this._cache) { - if (_cache.TryGetValue(url, out dom)) + if (this._cache.TryGetValue(url, out dom)) { if (DateTime.UtcNow > dom.UtcExpiry) { - _cache.Remove(url); + this._cache.Remove(url); dom = null; } } @@ -191,39 +208,17 @@ private RssChannelDom GetChannelDom(string url) if (dom == null) { - dom = DownloadChannelDom(url); + dom = this.DownloadChannelDom(url); - lock (_cache) + lock (this._cache) { - _cache[url] = dom; + this._cache[url] = dom; } } return dom; } - public static RssChannelDom GetChannel(string url) - { - return _theManager.GetChannelDom(url); - } - - private static int GetTtlFromString(string ttlString, int defaultTtlMinutes) - { - if (!string.IsNullOrEmpty(ttlString)) - { - int ttlMinutes; - if (int.TryParse(ttlString, out ttlMinutes)) - { - if (ttlMinutes >= 0) - { - return ttlMinutes; - } - } - } - - return defaultTtlMinutes; - } - private static string PrepareTempDir() { string tempDir = null; diff --git a/DNN Platform/Syndication/RSS/RssElementBase.cs b/DNN Platform/Syndication/RSS/RssElementBase.cs index eb60d4baedc..a9d77371002 100644 --- a/DNN Platform/Syndication/RSS/RssElementBase.cs +++ b/DNN Platform/Syndication/RSS/RssElementBase.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + /// /// The base class for all RSS elements (item, image, channel) - /// has collection of attributes + /// has collection of attributes. /// public abstract class RssElementBase { @@ -23,7 +18,7 @@ protected internal Dictionary Attributes { get { - return _attributes; + return this._attributes; } } @@ -33,14 +28,14 @@ public virtual void SetDefaults() internal void SetAttributes(Dictionary attributes) { - _attributes = attributes; + this._attributes = attributes; } protected string GetAttributeValue(string attributeName) { string attributeValue; - if (!_attributes.TryGetValue(attributeName, out attributeValue)) + if (!this._attributes.TryGetValue(attributeName, out attributeValue)) { attributeValue = string.Empty; } @@ -50,7 +45,7 @@ protected string GetAttributeValue(string attributeName) protected void SetAttributeValue(string attributeName, string attributeValue) { - _attributes[attributeName] = attributeValue; + this._attributes[attributeName] = attributeValue; } } } diff --git a/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs b/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs index 16cb91f68f4..c823c473070 100644 --- a/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs +++ b/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.ComponentModel; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + using System.ComponentModel; + /// - /// Helper class to enable the data binding logic generate column names at runtime + /// Helper class to enable the data binding logic generate column names at runtime. /// internal class RssElementCustomTypeDescriptor : ICustomTypeDescriptor { @@ -21,11 +16,9 @@ internal class RssElementCustomTypeDescriptor : ICustomTypeDescriptor public RssElementCustomTypeDescriptor(Dictionary attributes) { - _attributes = attributes; - } - - #region ICustomTypeDescriptor Members - + this._attributes = attributes; + } + AttributeCollection ICustomTypeDescriptor.GetAttributes() { return AttributeCollection.Empty; @@ -33,7 +26,7 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() string ICustomTypeDescriptor.GetClassName() { - return GetType().Name; + return this.GetType().Name; } string ICustomTypeDescriptor.GetComponentName() @@ -73,39 +66,36 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { - return GetPropertyDescriptors(); + return this.GetPropertyDescriptors(); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { - return GetPropertyDescriptors(); + return this.GetPropertyDescriptors(); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return (pd is RssElementCustomPropertyDescriptor) ? this : null; - } - - #endregion - + } + private PropertyDescriptorCollection GetPropertyDescriptors() { - var propertyDescriptors = new PropertyDescriptor[_attributes.Count]; + var propertyDescriptors = new PropertyDescriptor[this._attributes.Count]; int i = 0; - foreach (KeyValuePair a in _attributes) + foreach (KeyValuePair a in this._attributes) { propertyDescriptors[i++] = new RssElementCustomPropertyDescriptor(a.Key); } return new PropertyDescriptorCollection(propertyDescriptors); - } - - #region Nested type: RssElementCustomPropertyDescriptor - + } + private class RssElementCustomPropertyDescriptor : PropertyDescriptor { - public RssElementCustomPropertyDescriptor(string propertyName) : base(propertyName, null) + public RssElementCustomPropertyDescriptor(string propertyName) + : base(propertyName, null) { } @@ -113,7 +103,7 @@ public override Type ComponentType { get { - return typeof (RssElementCustomTypeDescriptor); + return typeof(RssElementCustomTypeDescriptor); } } @@ -129,7 +119,7 @@ public override Type PropertyType { get { - return typeof (string); + return typeof(string); } } @@ -159,7 +149,7 @@ public override object GetValue(object o) { string propertyValue; - if (element._attributes.TryGetValue(Name, out propertyValue)) + if (element._attributes.TryGetValue(this.Name, out propertyValue)) { return propertyValue; } @@ -167,8 +157,6 @@ public override object GetValue(object o) return string.Empty; } - } - - #endregion + } } } diff --git a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs index 2e9e6eda57e..4921676a41e 100644 --- a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs +++ b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs @@ -1,39 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Web; + using System.Xml; + public delegate void InitEventHandler(object source, EventArgs e); public delegate void PreRenderEventHandler(object source, EventArgs e); /// - /// Base class for RssHttpHandler - Generic handler and strongly typed ones are derived from it + /// Base class for RssHttpHandler - Generic handler and strongly typed ones are derived from it. /// /// /// /// - public abstract class RssHttpHandlerBase : IHttpHandler where RssChannelType : RssChannelBase, new() - where RssItemType : RssElementBase, new() - where RssImageType : RssElementBase, new() + public abstract class RssHttpHandlerBase : IHttpHandler + where RssChannelType : RssChannelBase, new() + where RssItemType : RssElementBase, new() + where RssImageType : RssElementBase, new() { private RssChannelType _channel; private HttpContext _context; + + public event InitEventHandler Init; + + public event PreRenderEventHandler PreRender; + + bool IHttpHandler.IsReusable + { + get + { + return false; + } + } protected RssChannelType Channel { get { - return _channel; + return this._channel; } } @@ -41,18 +49,16 @@ protected HttpContext Context { get { - return _context; + return this._context; } - } - - #region IHttpHandler Members - + } + void IHttpHandler.ProcessRequest(HttpContext context) { - InternalInit(context); + this.InternalInit(context); // let inherited handlers setup any special handling - OnInit(EventArgs.Empty); + this.OnInit(EventArgs.Empty); // parse the channel name and the user name from the query string string userName; @@ -60,34 +66,21 @@ void IHttpHandler.ProcessRequest(HttpContext context) RssHttpHandlerHelper.ParseChannelQueryString(context.Request, out channelName, out userName); // populate items (call the derived class) - PopulateChannel(channelName, userName); + this.PopulateChannel(channelName, userName); - OnPreRender(EventArgs.Empty); + this.OnPreRender(EventArgs.Empty); - Render(new XmlTextWriter(Context.Response.OutputStream, null)); + this.Render(new XmlTextWriter(this.Context.Response.OutputStream, null)); } - bool IHttpHandler.IsReusable - { - get - { - return false; - } - } - - #endregion - - public event InitEventHandler Init; - public event PreRenderEventHandler PreRender; - /// /// Triggers the Init event. /// protected virtual void OnInit(EventArgs ea) { - if (Init != null) + if (this.Init != null) { - Init(this, ea); + this.Init(this, ea); } } @@ -96,31 +89,31 @@ protected virtual void OnInit(EventArgs ea) /// protected virtual void OnPreRender(EventArgs ea) { - if (PreRender != null) + if (this.PreRender != null) { - PreRender(this, ea); + this.PreRender(this, ea); } } - private void InternalInit(HttpContext context) - { - _context = context; - - // create the channel - _channel = new RssChannelType(); - _channel.SetDefaults(); - - Context.Response.ContentType = "text/xml"; - } - protected virtual void PopulateChannel(string channelName, string userName) { } protected virtual void Render(XmlTextWriter writer) { - XmlDocument doc = _channel.SaveAsXml(); + XmlDocument doc = this._channel.SaveAsXml(); doc.Save(writer); } + + private void InternalInit(HttpContext context) + { + this._context = context; + + // create the channel + this._channel = new RssChannelType(); + this._channel.SetDefaults(); + + this.Context.Response.ContentType = "text/xml"; + } } } diff --git a/DNN Platform/Syndication/RSS/RssHttpHandlerHelper.cs b/DNN Platform/Syndication/RSS/RssHttpHandlerHelper.cs index 8ac67a0e087..a1c428fbce6 100644 --- a/DNN Platform/Syndication/RSS/RssHttpHandlerHelper.cs +++ b/DNN Platform/Syndication/RSS/RssHttpHandlerHelper.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.Security; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Web; + using System.Web.Security; + /// - /// Helper class (for RssHtppHandler) to pack and unpack user name and channel to from/to query string + /// Helper class (for RssHtppHandler) to pack and unpack user name and channel to from/to query string. /// public class RssHttpHandlerHelper { @@ -58,6 +53,7 @@ internal static void ParseChannelQueryString(HttpRequest request, out string cha if (string.IsNullOrEmpty(ticket)) { userName = string.Empty; + // optional unencrypted channel name channelName = request.QueryString["c"]; } diff --git a/DNN Platform/Syndication/RSS/RssHyperLink.cs b/DNN Platform/Syndication/RSS/RssHyperLink.cs index 33d4b06133e..00386d48605 100644 --- a/DNN Platform/Syndication/RSS/RssHyperLink.cs +++ b/DNN Platform/Syndication/RSS/RssHyperLink.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + /// - /// RssHyperLink control - works with RssHttpHandler + /// RssHyperLink control - works with RssHttpHandler. /// public class RssHyperLink : HyperLink { @@ -22,7 +17,7 @@ public class RssHyperLink : HyperLink public RssHyperLink() { - Text = "RSS"; + this.Text = "RSS"; } // passed to RssHttpHandler @@ -30,11 +25,12 @@ public string ChannelName { get { - return _channelName; + return this._channelName; } + set { - _channelName = value; + this._channelName = value; } } @@ -43,27 +39,28 @@ public bool IncludeUserName { get { - return _includeUserName; + return this._includeUserName; } + set { - _includeUserName = value; + this._includeUserName = value; } } protected override void OnPreRender(EventArgs e) { // modify the NavigateUrl to include optional user name and channel name - string channel = _channelName != null ? _channelName : string.Empty; - string user = _includeUserName ? Context.User.Identity.Name : string.Empty; - NavigateUrl = RssHttpHandlerHelper.GenerateChannelLink(NavigateUrl, channel, user); + string channel = this._channelName != null ? this._channelName : string.Empty; + string user = this._includeUserName ? this.Context.User.Identity.Name : string.Empty; + this.NavigateUrl = RssHttpHandlerHelper.GenerateChannelLink(this.NavigateUrl, channel, user); // add to tag (if is present) - if (Page.Header != null) + if (this.Page.Header != null) { - string title = string.IsNullOrEmpty(channel) ? Text : channel; + string title = string.IsNullOrEmpty(channel) ? this.Text : channel; - Page.Header.Controls.Add(new LiteralControl(string.Format("\r\n", title, NavigateUrl))); + this.Page.Header.Controls.Add(new LiteralControl(string.Format("\r\n", title, this.NavigateUrl))); } base.OnPreRender(e); diff --git a/DNN Platform/Syndication/RSS/RssXmlHelper.cs b/DNN Platform/Syndication/RSS/RssXmlHelper.cs index 9a58f86b110..ac89dabbc14 100644 --- a/DNN Platform/Syndication/RSS/RssXmlHelper.cs +++ b/DNN Platform/Syndication/RSS/RssXmlHelper.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Web; -using System.Xml; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { + using System; + using System.Collections.Generic; + using System.Web; + using System.Xml; + internal class RssXmlHelper { /// - /// Internal helper class for XML to RSS conversion (and for generating XML from RSS) + /// Internal helper class for XML to RSS conversion (and for generating XML from RSS). /// /// /// @@ -67,10 +62,12 @@ internal static RssChannelDom ParseChannelXml(XmlDocument doc) { channelAttributes = ParseAttributesFromXml(n); } + if (n.Name == "image") { imageAttributes = ParseAttributesFromXml(n); } + if (n.Name == "item") { itemsAttributesList.Add(ParseAttributesFromXml(n)); diff --git a/DNN Platform/Syndication/Settings.cs b/DNN Platform/Syndication/Settings.cs index ea385da1d0f..3c9c89e3b2b 100644 --- a/DNN Platform/Syndication/Settings.cs +++ b/DNN Platform/Syndication/Settings.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Services.Syndication { internal static class Settings diff --git a/DNN Platform/Syndication/packages.config b/DNN Platform/Syndication/packages.config new file mode 100644 index 00000000000..e619441b462 --- /dev/null +++ b/DNN Platform/Syndication/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/App.config b/DNN Platform/Tests/App.config index 345b03ceaa4..9125c5046a1 100644 --- a/DNN Platform/Tests/App.config +++ b/DNN Platform/Tests/App.config @@ -1,400 +1,400 @@ - - - - -
        - - - -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        -
        - -
        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + +
        + + + +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/CachedWebPage.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/CachedWebPage.cs index 4e5c15a4641..f4e8a5badb8 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/CachedWebPage.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/CachedWebPage.cs @@ -1,29 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework { + using System; + internal class CachedWebPage { private string[] _inputFields; public CachedWebPage(string token, string[] fields) { - FetchDateTime = DateTime.Now; - VerificationToken = token; - InputFields = fields; + this.FetchDateTime = DateTime.Now; + this.VerificationToken = token; + this.InputFields = fields; } public DateTime FetchDateTime { get; private set; } // when was this loaded + public string VerificationToken { get; private set; } public string[] InputFields { - get { return _inputFields.Clone() as string[]; } - private set { _inputFields = value; } + get { return this._inputFields.Clone() as string[]; } + private set { this._inputFields = value; } } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/ModuleController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/ModuleController.cs index 746479cc0e7..38f23056870 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/ModuleController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/ModuleController.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using DNN.Integration.Test.Framework.Helpers; -using DNN.Integration.Test.Framework.Scripts; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Controllers { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Text; + + using DNN.Integration.Test.Framework.Helpers; + using DNN.Integration.Test.Framework.Scripts; + public static class ModuleController { private const string PortalIdMarker = @"'$[portal_id]'"; @@ -45,9 +46,11 @@ public static int AddModulePermission(int roleId, int moduleId, string permissio var result = DatabaseHelper.ExecuteQuery(script); - if (result.Count > 0 && result[0].ContainsKey("ModulePermissionId")) - return int.Parse(result[0]["ModulePermissionId"].ToString()); - + if (result.Count > 0 && result[0].ContainsKey("ModulePermissionId")) + { + return int.Parse(result[0]["ModulePermissionId"].ToString()); + } + return -1; } @@ -57,11 +60,11 @@ public static void DeleteModulePermission(int modulePermissionId) } /// - /// Deletes a module from the specified tab and clears host cache + /// Deletes a module from the specified tab and clears host cache. /// - /// tabId on which module is deleted - /// moduleId that is deleted - /// if True, then softdeleted, otherwise harddeleted + /// tabId on which module is deleted. + /// moduleId that is deleted. + /// if True, then softdeleted, otherwise harddeleted. public static void DeleteTabModule(int tabId, int moduleId, bool softDelete) { DatabaseHelper.ExecuteStoredProcedure("DeleteTabModule", tabId, moduleId, softDelete); diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PermissionController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PermissionController.cs index b61806797b8..66e5f6e3c22 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PermissionController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PermissionController.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using DNN.Integration.Test.Framework.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Controllers { + using System.Linq; + + using DNN.Integration.Test.Framework.Helpers; + public class PermissionController { public static dynamic GetPermission(string code, string key) diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PortalController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PortalController.cs index e896c3a76f2..d6a9fb3c2c0 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PortalController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/PortalController.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Linq; -using System.Text; -using DNN.Integration.Test.Framework.Helpers; -using DNN.Integration.Test.Framework.Scripts; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Controllers { + using System; + using System.Globalization; + using System.Linq; + using System.Text; + + using DNN.Integration.Test.Framework.Helpers; + using DNN.Integration.Test.Framework.Scripts; + public static class PortalController { private const string PortalIdMarker = @"'$[portal_id]'"; @@ -24,7 +25,7 @@ public static TimeZoneInfo GetTimeZone(int portalId) .ToString(); var timeZoneString = DatabaseHelper.ExecuteQuery(script).First()["SettingValue"].ToString(); - + return TimeZoneInfo.FindSystemTimeZoneById(timeZoneString); } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs index 33aae691d0c..be6f21acf2f 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Globalization; -using System.Linq; -using System.Text; -using DNN.Integration.Test.Framework.Helpers; -using DNN.Integration.Test.Framework.Scripts; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Controllers { + using System.Globalization; + using System.Linq; + using System.Text; + + using DNN.Integration.Test.Framework.Helpers; + using DNN.Integration.Test.Framework.Scripts; + public static class RoleController { private const string PortalIdMarker = @"'$[portal_id]'"; @@ -34,6 +35,24 @@ public static int CreateRoleIfNotPresent(string roleName, int portalId = 0) return -1; } + /// + /// Get RoleId for role "Registered Users". + /// + /// + public static int GetRegisteredUsersRoleId(int portalId = 0) + { + return GetRoleId("Registered Users", portalId); + } + + /// + /// Get RoleId for role "Administrators". + /// + /// + public static int GetAdministratorsRoleId(int portalId = 0) + { + return GetRoleId("Administrators", portalId); + } + private static int CreateRole(string roleName, string roleDescription, int portalId = 0) { var fileContent = SqlScripts.SingleRoleCreation; @@ -51,28 +70,11 @@ private static int CreateRole(string roleName, string roleDescription, int porta return GetRoleId(roleName); } - /// - /// Get RoleId for role "Registered Users" - /// - public static int GetRegisteredUsersRoleId(int portalId = 0) - { - return GetRoleId("Registered Users", portalId); - } - - /// - /// Get RoleId for role "Administrators" - /// - public static int GetAdministratorsRoleId(int portalId = 0) - { - return GetRoleId("Administrators", portalId); - } - public static int GetRoleId(string roleName, int portalId = 0) { // The fix for DNN-4288 prevented virtual roles from getting virtual // roles (i.e., with RoleID <= 0 which includes Administrator role). - //var results = DatabaseHelper.ExecuteStoredProcedure("GetRolesBasicSearch", portalId, 0, 10, roleName); - + // var results = DatabaseHelper.ExecuteStoredProcedure("GetRolesBasicSearch", portalId, 0, 10, roleName); roleName = roleName.Replace("'", string.Empty); var query = string.Format("SELECT RoleID FROM {{objectQualifier}}Roles WHERE RoleName = N'{0}' AND PortalID={1};", roleName, portalId); var results = DatabaseHelper.ExecuteQuery(query).ToArray(); diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs index ac6a79cfc4f..924e6b22651 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading; -using DNN.Integration.Test.Framework.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Threading; + + using DNN.Integration.Test.Framework.Helpers; + public enum SchedulingMode { Disabled = 0, @@ -20,8 +21,7 @@ public enum SchedulingMode public static class SchedulerController { - //private const string SchedulerModeName = "SchedulerMode"; - + // private const string SchedulerModeName = "SchedulerMode"; public static void DisableAllSchedulers(bool clearCache = true) { SetSchedulingMode(SchedulingMode.Disabled, clearCache); @@ -30,8 +30,10 @@ public static void DisableAllSchedulers(bool clearCache = true) public static void DisableAppStartDelay(bool clearCache = true) { DatabaseHelper.ExecuteStoredProcedure("UpdateHostSetting", "SchedulerdelayAtAppStart", "0", false, 1); - if (clearCache) - WebApiTestHelper.ClearHostCache(); + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); + } } public static void DisableScheduler(string schedulerName, bool clearCache = false) @@ -39,8 +41,10 @@ public static void DisableScheduler(string schedulerName, bool clearCache = fals var query = string.Format( "UPDATE {{objectQualifier}}Schedule SET Enabled=0 WHERE FriendlyName = '{0}';", schedulerName); DatabaseHelper.ExecuteNonQuery(query); - if (clearCache) - WebApiTestHelper.ClearHostCache(); + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); + } } public static void EnableScheduler(string schedulerName, bool clearCache = false) @@ -48,8 +52,10 @@ public static void EnableScheduler(string schedulerName, bool clearCache = false var query = string.Format( "UPDATE {{objectQualifier}}Schedule SET Enabled=1 WHERE FriendlyName = '{0}';", schedulerName); DatabaseHelper.ExecuteNonQuery(query); - if (clearCache) - WebApiTestHelper.ClearHostCache(); + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); + } } public static SchedulingMode GetSchedulingMode() @@ -68,8 +74,10 @@ public static void SetSchedulingMode(SchedulingMode mode, bool clearCache = true if (current != mode) { DatabaseHelper.ExecuteStoredProcedure("UpdateHostSetting", "SchedulerMode", mode.ToString("D"), false, 1); - if (clearCache) - WebApiTestHelper.ClearHostCache(); // must clear the site Cache afterwards + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); // must clear the site Cache afterwards + } } } @@ -92,11 +100,11 @@ public static IDictionary GetSchedulerByName(string schedulerNam } /// - /// Runs a specific scheduler and returns the resul depending on the passed flags + /// Runs a specific scheduler and returns the resul depending on the passed flags. /// - /// Name of the scheduler in the database + /// Name of the scheduler in the database. /// Maimum amount of time to wait for the task to finish. - /// Result of running the taske (depends on the flags) + /// Result of running the taske (depends on the flags). /// /// If maxWaitSeconds is less than or equals 0: the return result is only the result of the call /// to the "Run Now" button of the Edit Scheduler UI page. @@ -112,10 +120,12 @@ public static bool RunScheduler(string schedulerName, int maxWaitSeconds = 0) try { var schedulInfo = GetSchedulerByName(schedulerName); - if (schedulInfo == null || schedulInfo.Count == 0) - return false; - - // HOST modules have only single instance, so don't worry about receiving multiple rows + if (schedulInfo == null || schedulInfo.Count == 0) + { + return false; + } + + // HOST modules have only single instance, so don't worry about receiving multiple rows var results = ModuleController.GetModulesByFriendlyName(DnnDataHelper.PortalId, "Scheduler"); var moduleId = results.SelectMany(x => x.Where(y => y.Key == "ModuleID").Select(y => (int)y.Value)).FirstOrDefault(); @@ -129,29 +139,35 @@ public static bool RunScheduler(string schedulerName, int maxWaitSeconds = 0) } var resp = TriggerScheduler(schedulInfo, moduleId); + // only OK is a successful POST in this case; all other codes are failures if (resp.StatusCode != HttpStatusCode.OK) { - Console.WriteLine(@"Error running scheduler {0}. Status: {1} - {2}", + Console.WriteLine( + @"Error running scheduler {0}. Status: {1} - {2}", schedulerName, resp.StatusCode, resp.StatusDescription); return false; } - //DisableScheduler(schedulerName); // un-necessary + // DisableScheduler(schedulerName); // un-necessary SetSchedulingMode(SchedulingMode.Disabled); disabled = true; - if (maxWaitSeconds <= 0) - return true; - - // wait for task to finish + if (maxWaitSeconds <= 0) + { + return true; + } + + // wait for task to finish var latestRunInfo = WaitForTaskToFinish(lastRunInfo, maxWaitSeconds); return latestRunInfo.Succeeded; } finally { - if (!disabled) - SetSchedulingMode(SchedulingMode.Disabled); + if (!disabled) + { + SetSchedulingMode(SchedulingMode.Disabled); + } } } @@ -166,22 +182,23 @@ private static HttpWebResponse TriggerScheduler(IDictionary sche var fieldsPrefix = string.Format("dnn$ctr{0}$EditSchedule", moduleId); var postData = new Dictionary { - {fieldsPrefix + "$chkEnabled", "on"}, - {fieldsPrefix + "$txtServers", ""}, - {fieldsPrefix + "$ddlAttachToEvent", "None"}, - {fieldsPrefix + "$ddlRetainHistoryNum", "100"}, - {fieldsPrefix + "$ddlRetryTimeLapseMeasurement", "Minutes"}, - {fieldsPrefix + "$ddlTimeLapseMeasurement", "Hours"}, - {fieldsPrefix + "$startScheduleDatePicker$dateInput", ""}, - {fieldsPrefix + "$startScheduleDatePicker", ""}, - {fieldsPrefix + "$txtFriendlyName", scheduleFriendlyName}, - {fieldsPrefix + "$txtObjectDependencies", objectDependencies}, - {fieldsPrefix + "$txtRetryTimeLapse", "30"}, - {fieldsPrefix + "$txtTimeLapse", "1"}, - {fieldsPrefix + "$txtType", scheduleTypeName}, - {"__EVENTTARGET", fieldsPrefix + "$cmdRun"}, // button action; if missing, no click action is performed - {"__EVENTARGUMENT", ""}, - {"__ASYNCPOST", ""}, + { fieldsPrefix + "$chkEnabled", "on" }, + { fieldsPrefix + "$txtServers", string.Empty }, + { fieldsPrefix + "$ddlAttachToEvent", "None" }, + { fieldsPrefix + "$ddlRetainHistoryNum", "100" }, + { fieldsPrefix + "$ddlRetryTimeLapseMeasurement", "Minutes" }, + { fieldsPrefix + "$ddlTimeLapseMeasurement", "Hours" }, + { fieldsPrefix + "$startScheduleDatePicker$dateInput", string.Empty }, + { fieldsPrefix + "$startScheduleDatePicker", string.Empty }, + { fieldsPrefix + "$txtFriendlyName", scheduleFriendlyName }, + { fieldsPrefix + "$txtObjectDependencies", objectDependencies }, + { fieldsPrefix + "$txtRetryTimeLapse", "30" }, + { fieldsPrefix + "$txtTimeLapse", "1" }, + { fieldsPrefix + "$txtType", scheduleTypeName }, + { "__EVENTTARGET", fieldsPrefix + "$cmdRun" }, // button action; if missing, no click action is performed + { "__EVENTARGUMENT", string.Empty }, + { "__ASYNCPOST", string.Empty }, + // all other inputs/fields are left as is }; @@ -212,10 +229,10 @@ private static ScheduleHistoryInfo WaitForTaskToFinish(ScheduleHistoryInfo lastR } /// - /// Finds the last time a specific scheduler was run and the ID of the last run + /// Finds the last time a specific scheduler was run and the ID of the last run. /// - /// Scheduler ID to inquire - /// If no previous run exists, it returns ID as -1 + /// Scheduler ID to inquire. + /// If no previous run exists, it returns ID as -1. private static ScheduleHistoryInfo LastRunningScheduleItem(int scheduleId) { const string script = @"IF EXISTS (SELECT 1 FROM {{objectQualifier}}ScheduleHistory WHERE ScheduleId = {0}) @@ -236,21 +253,15 @@ ORDER BY ScheduleHistoryId DESC public class ScheduleHistoryInfo { - public int ScheduleId { get; } - public int ScheduleHistoryId { get; } - public DateTime EndDate { get; } - public bool Succeeded { get; } - public string LogNotes { get; } - public ScheduleHistoryInfo(IDictionary queryResult) { try { - ScheduleId = Convert.ToInt32(queryResult["ScheduleId"]); - ScheduleHistoryId = Convert.ToInt32(queryResult["ScheduleHistoryId"]); - EndDate = Convert.ToDateTime(queryResult["EndDate"]); - Succeeded = Convert.ToBoolean(queryResult["Succeeded"]); - LogNotes = queryResult["LogNotes"].ToString(); + this.ScheduleId = Convert.ToInt32(queryResult["ScheduleId"]); + this.ScheduleHistoryId = Convert.ToInt32(queryResult["ScheduleHistoryId"]); + this.EndDate = Convert.ToDateTime(queryResult["EndDate"]); + this.Succeeded = Convert.ToBoolean(queryResult["Succeeded"]); + this.LogNotes = queryResult["LogNotes"].ToString(); } catch (Exception e) { @@ -262,21 +273,31 @@ public ScheduleHistoryInfo(IDictionary queryResult) internal ScheduleHistoryInfo(int scheduleId, int scheduleHistoryID, DateTime endDate, bool succeeded) { - ScheduleId = scheduleId; - ScheduleHistoryId = scheduleHistoryID; - EndDate = endDate; - Succeeded = succeeded; - LogNotes = string.Empty; + this.ScheduleId = scheduleId; + this.ScheduleHistoryId = scheduleHistoryID; + this.EndDate = endDate; + this.Succeeded = succeeded; + this.LogNotes = string.Empty; } // clones another info with success as false internal ScheduleHistoryInfo(ScheduleHistoryInfo lastRunInfo) { - ScheduleId = lastRunInfo.ScheduleId; - ScheduleHistoryId = lastRunInfo.ScheduleHistoryId; - EndDate = lastRunInfo.EndDate; - Succeeded = false; - LogNotes = lastRunInfo.LogNotes; + this.ScheduleId = lastRunInfo.ScheduleId; + this.ScheduleHistoryId = lastRunInfo.ScheduleHistoryId; + this.EndDate = lastRunInfo.EndDate; + this.Succeeded = false; + this.LogNotes = lastRunInfo.LogNotes; } + + public int ScheduleId { get; } + + public int ScheduleHistoryId { get; } + + public DateTime EndDate { get; } + + public bool Succeeded { get; } + + public string LogNotes { get; } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs index 72d0605eac4..c795c1472a0 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs @@ -1,15 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DNN.Integration.Test.Framework.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Controllers { + using System; + using System.Collections.Generic; + + using DNN.Integration.Test.Framework.Helpers; + public static class TabController { + private static int PortalId => DnnDataHelper.PortalId; + public static int GetTabIdByTabName(string tabName) { var query = string.Format( @@ -37,15 +40,17 @@ public static int GetTabIdByPathName(string tabPath) public static int GetModuleIdInsidePage(int pageId) { return DatabaseHelper.ExecuteScalar( - string.Format(@" + string.Format( + @" SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules WHERE TabId = '{0}' AND PaneName='contentPane' AND ContainerSrc IS NULL AND ISNULL(PortalID,0)={1};", pageId, PortalId)); } /// - /// Returns all the tab related columns from vw_tabinfo - /// + /// Returns all the tab related columns from vw_tabinfo. + ///
        + /// public static dynamic GetTabInfo(int tabId) { var sql = string.Format(@"SELECT TOP 1 * FROM {{objectQualifier}}vw_Tabs WHERE TabId = '{0}' ORDER BY TabId ASC", tabId); @@ -53,16 +58,17 @@ public static dynamic GetTabInfo(int tabId) } /// - /// Gets list of all modules on a page + /// Gets list of all modules on a page. /// - /// Id of the page - /// List of all the modules on a page + /// Id of the page. + /// List of all the modules on a page. public static List GetAllModuleIdInsidePage(int pageId) { - var squery = string.Format(@" + var squery = string.Format( + @" SELECT ModuleID FROM {{objectQualifier}}vw_TabModules WHERE TabId = '{0}' AND ISNULL(PortalID,0)={1};", - pageId, PortalId); + pageId, PortalId); var result = DatabaseHelper.ExecuteQuery(squery); var listOfModules = new List(); foreach (var item in result) @@ -71,18 +77,20 @@ SELECT ModuleID FROM {{objectQualifier}}vw_TabModules item.TryGetValue("ModuleID", out moduleId); listOfModules.Add(Convert.ToInt32(moduleId)); } + return listOfModules; } /// - /// Gets ModuleID of the first module on a page (any pane) + /// Gets ModuleID of the first module on a page (any pane). /// - /// id of the tab - /// Returns ModuleID of the first module (top(1)) on a page + /// id of the tab. + /// Returns ModuleID of the first module (top(1)) on a page. public static int GetModuleIdInsidePageAnyPane(int pageId) { return DatabaseHelper.ExecuteScalar( - string.Format(@" + string.Format( + @" SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules WHERE TabId = '{0}' AND ContainerSrc IS NULL AND ISNULL(PortalID,0)={1};", pageId, PortalId)); @@ -90,7 +98,8 @@ SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules public static int GetModuleIdInsidePage(int tabId, string moduleFriendlyName) { - var query1 = string.Format(@" + var query1 = string.Format( + @" SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules tm INNER JOIN {{objectQualifier}}DesktopModules dm ON dm.DesktopModuleId = tm.DesktopModuleId INNER JOIN {{objectQualifier}}ModuleDefinitions md ON md.ModuleDefID = tm.ModuleDefID @@ -111,8 +120,8 @@ SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules tm public static string GetTabPath(string tabPath) { var parts = tabPath.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - var path = ""; - var name = ""; + var path = string.Empty; + var name = string.Empty; foreach (var s in parts) { path += "//" + s; @@ -127,14 +136,16 @@ public static string GetTabPath(string tabPath) public static int GetTabModuleId(int tabId, int moduledId) { return DatabaseHelper.ExecuteScalar( - string.Format(@" + string.Format( + @" SELECT TOP(1) TabModuleID FROM {{objectQualifier}}TabModules WHERE TabID = {0} AND ModuleID = {1};", tabId, moduledId)); } - + /// - /// Returns all the tab urls - /// + /// Returns all the tab urls. + ///
        + /// public static IList GetTabUrls(int tabId) { var sql = string.Format(@"SELECT * FROM {{objectQualifier}}TabUrls WHERE TabId = '{0}' ORDER BY SeqNum DESC", tabId); @@ -142,7 +153,7 @@ public static IList GetTabUrls(int tabId) } /// - /// Adds tab setting. Deletes existing setting first + /// Adds tab setting. Deletes existing setting first. /// public static void SaveTabSetting(int tabId, string settingName, string settingValue) { @@ -151,25 +162,24 @@ public static void SaveTabSetting(int tabId, string settingName, string settingV } /// - /// Adds tab setting. Does not delete existing setting first + /// Adds tab setting. Does not delete existing setting first. /// public static void AddTabSetting(int tabId, string settingName, string settingValue) { - DatabaseHelper.ExecuteStoredProcedure("UpdateTabSetting", + DatabaseHelper.ExecuteStoredProcedure( + "UpdateTabSetting", tabId, settingName, settingValue, - 1); //CreatedByUserID + 1); // CreatedByUserID } /// - /// Deletes tab setting + /// Deletes tab setting. /// public static void DeleteTabSetting(int tabId, string settingName) { DatabaseHelper.ExecuteStoredProcedure("DeleteTabSetting", tabId, settingName); } - - private static int PortalId => DnnDataHelper.PortalId; } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs index 9eb3b231351..73f972aa41e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Linq; -using System.Text; -using DNN.Integration.Test.Framework.Helpers; -using DNN.Integration.Test.Framework.Scripts; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Controllers { + using System; + using System.Globalization; + using System.Linq; + using System.Text; + + using DNN.Integration.Test.Framework.Helpers; + using DNN.Integration.Test.Framework.Scripts; + public static class UserController { - private static readonly string UserToCopy = AppConfigHelper.HostUserName; - private const string PortalIdMarker = @"'$[portal_id]'"; private const string UserToCopyMarker = @"$[users_to_copy]"; + + private static readonly string UserToCopy = AppConfigHelper.HostUserName; private const string FirstNameMarker = @"$[first_name]"; private const string LastNameMarker = @"$[last_name]"; private const string IsSuperUserMarker = @"'$[isSuperUser]'"; @@ -24,44 +25,45 @@ public static class UserController private const string UserIdMarker = @"'$[user_id]'"; private const string CreateFriendsMarker = @"'$[CreateFriends]'"; private const string CreateFollowersMarker = @"'$[CreateFollowers]'"; - - + /// - /// Creates a new user with Registered User Role and with the same password as the host user + /// Creates a new user with Registered User Role and with the same password as the host user. /// - /// First name of the user - /// Last name of the user - /// PortalID to create the user under - /// Id of the created user - /// Username created is firstname.lastname - public static int CreateRegisteredUser(string firstName = IntegrationConstants.RuFirstName, + /// First name of the user. + /// Last name of the user. + /// PortalID to create the user under. + /// Id of the created user. + /// Username created is firstname.lastname. + public static int CreateRegisteredUser( + string firstName = IntegrationConstants.RuFirstName, string lastName = IntegrationConstants.RuLastName, int portalId = 0) { - return CreateUser(new CreateUserParams {FirstName = firstName, LastName = lastName, PortalId = portalId}); + return CreateUser(new CreateUserParams { FirstName = firstName, LastName = lastName, PortalId = portalId }); } /// - /// Creates a new SuperUser and with the same password as the host user + /// Creates a new SuperUser and with the same password as the host user. /// - /// First name of the user - /// Last name of the user - /// PortalID to create the user under - /// Id of the created user - /// Username created is firstname.lastname + /// First name of the user. + /// Last name of the user. + /// PortalID to create the user under. + /// Id of the created user. + /// Username created is firstname.lastname. public static int CreateSuperUser(string firstName, string lastName, int portalId = 0) { - return CreateUser(new CreateUserParams { FirstName = firstName, LastName = lastName, PortalId = portalId, SuperUser = true}); + return CreateUser(new CreateUserParams { FirstName = firstName, LastName = lastName, PortalId = portalId, SuperUser = true }); } /// - /// Creates a new user with Administrator Role and with the same password as the host user + /// Creates a new user with Administrator Role and with the same password as the host user. /// - /// First name of the administrator user - /// Last name of the administrator user - /// PortalID to create the user under - /// Id of the created user - /// Username created is firstname.lastname - public static int CreateAdministratorUser(string firstName = IntegrationConstants.AdminFirstName, + /// First name of the administrator user. + /// Last name of the administrator user. + /// PortalID to create the user under. + /// Id of the created user. + /// Username created is firstname.lastname. + public static int CreateAdministratorUser( + string firstName = IntegrationConstants.AdminFirstName, string lastName = IntegrationConstants.AdminLastName, int portalId = 0) { return CreateUser(new CreateUserParams { FirstName = firstName, LastName = lastName, PortalId = portalId, Role = "Administrators" }); @@ -73,17 +75,44 @@ public static int GetUserId(string username) return results.SelectMany(x => x.Where(y => y.Key == "UserId").Select(y => (int)y.Value)).FirstOrDefault(); } + public static void DeleteUser(int userId) + { + var fileContent = SqlScripts.UserDelete; + var script = new StringBuilder(fileContent) + .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) + .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) + .ToString(); + + DatabaseHelper.ExecuteQuery(script); + } + + public static TimeZoneInfo GetUserPreferredTimeZone(int userId, int portalId) + { + var fileContent = SqlScripts.UserGetPreferredTimeZone; + var script = new StringBuilder(fileContent) + .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) + .Replace(PortalIdMarker, portalId.ToString(CultureInfo.InvariantCulture)) + .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) + .ToString(); + + var timeZoneString = DatabaseHelper.ExecuteQuery(script).First()["PropertyValue"].ToString(); + + return TimeZoneInfo.FindSystemTimeZoneById(timeZoneString); + } + private static int CreateUser(CreateUserParams parms) { parms.FirstName = parms.FirstName.Replace("'", "''"); parms.LastName = parms.LastName.Replace("'", "''"); var username = parms.FirstName + "." + parms.LastName; var uid = GetUserId(username); - if (uid > 0) - return uid; - - //create role if not present - RoleController.CreateRoleIfNotPresent(parms.Role); + if (uid > 0) + { + return uid; + } + + // create role if not present + RoleController.CreateRoleIfNotPresent(parms.Role); var fileContent = SqlScripts.SingleUserCreation; var masterScript = new StringBuilder(fileContent) @@ -100,44 +129,25 @@ private static int CreateUser(CreateUserParams parms) .Replace(IsSuperUserMarker, parms.SuperUser ? "1" : "0") .Replace(CreateFriendsMarker, parms.AutoCreateFriends ? "1" : "0") .Replace(CreateFollowersMarker, parms.AutoCreateFollowersAndFollowings ? "1" : "0") - .Replace(RoleMarker, string.IsNullOrEmpty(parms.Role) ? "" : parms.Role); + .Replace(RoleMarker, string.IsNullOrEmpty(parms.Role) ? string.Empty : parms.Role); DatabaseHelper.ExecuteQuery(script.ToString()); return GetUserId(username); } - public static void DeleteUser(int userId) - { - var fileContent = SqlScripts.UserDelete; - var script = new StringBuilder(fileContent) - .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) - .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) - .ToString(); - - DatabaseHelper.ExecuteQuery(script); - } - - public static TimeZoneInfo GetUserPreferredTimeZone(int userId, int portalId) - { - var fileContent = SqlScripts.UserGetPreferredTimeZone; - var script = new StringBuilder(fileContent) - .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) - .Replace(PortalIdMarker, portalId.ToString(CultureInfo.InvariantCulture)) - .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) - .ToString(); - - var timeZoneString = DatabaseHelper.ExecuteQuery(script).First()["PropertyValue"].ToString(); - - return TimeZoneInfo.FindSystemTimeZoneById(timeZoneString); - } - public class CreateUserParams { public string FirstName { get; set; } - public string LastName{ get; set; } - public int PortalId{ get; set; } - public bool SuperUser{ get; set; } + + public string LastName { get; set; } + + public int PortalId { get; set; } + + public bool SuperUser { get; set; } + public string Role { get; set; } + public bool AutoCreateFriends { get; set; } + public bool AutoCreateFollowersAndFollowings { get; set; } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/DNN.Integration.Test.Framework.csproj b/DNN Platform/Tests/DNN.Integration.Test.Framework/DNN.Integration.Test.Framework.csproj index abc261942e8..4030f417ae1 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/DNN.Integration.Test.Framework.csproj +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/DNN.Integration.Test.Framework.csproj @@ -1,117 +1,124 @@ - - - - - Debug - AnyCPU - {8F727796-7C6C-4F42-B385-67B06ECD358E} - Library - Properties - DNN.Integration.Test.Framework - DNN.Integration.Test.Framework - v4.7.2 - 512 - - - - AnyCPU - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - 1591, 618 - 7 - - - AnyCPU - pdbonly - true - bin\ - TRACE - prompt - 4 - 1591, 618 - 7 - - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - True - - - ..\..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll - True - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - - ..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - True - - - - - - - - - - Properties\SolutionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - - - - - + + + + + Debug + AnyCPU + {8F727796-7C6C-4F42-B385-67B06ECD358E} + Library + Properties + DNN.Integration.Test.Framework + DNN.Integration.Test.Framework + v4.7.2 + 512 + + + + AnyCPU + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + 1591, 618 + 7 + + + AnyCPU + pdbonly + true + bin\ + TRACE + prompt + 4 + 1591, 618 + 7 + + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + True + + + ..\..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + True + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + + ..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + True + + + + + + + + + + Properties\SolutionInfo.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + stylecop.json + + + + + + + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs index 198bf2a6dee..01813db46c1 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs @@ -1,21 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework { public class FileParameter { - public byte[] File { get; set; } - public string FileName { get; set; } - public string ContentType { get; set; } - public FileParameter(byte[] file) : this(file, null) { } - public FileParameter(byte[] file, string filename) : this(file, filename, null) { } + public FileParameter(byte[] file) + : this(file, null) + { + } + + public FileParameter(byte[] file, string filename) + : this(file, filename, null) + { + } + public FileParameter(byte[] file, string filename, string contenttype) { - File = file; - FileName = filename; - ContentType = contenttype; + this.File = file; + this.FileName = filename; + this.ContentType = contenttype; } + + public byte[] File { get; set; } + + public string FileName { get; set; } + + public string ContentType { get; set; } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs index ff7bc8b5f16..2c4168364c2 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Configuration; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System.Configuration; + public static class AppConfigHelper { private const string DefaultWebsiteName = "http://dnnce.lvh.me"; @@ -20,6 +20,15 @@ public static class AppConfigHelper private static string _connectionString; private static string _loginCookieString; + public static string ConnectionString => + _connectionString ?? (_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString); + + public static string ObjectQualifier => + _objectQualifier ?? (_objectQualifier = GetAppSetting("objectQualifier")); + + public static string SiteUrl => + _siteUrl ?? (_siteUrl = GetAppSetting("siteUrl") ?? DefaultWebsiteName); + public static string GetAppSetting(string key) { return ConfigurationManager.AppSettings[key]; @@ -37,22 +46,13 @@ public static int GetAppSettingAsInt(string key, int defaultValue) return int.TryParse(GetAppSetting(key), out value) ? value : defaultValue; } - public static string ConnectionString => - _connectionString ?? (_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString); - - public static string ObjectQualifier => - _objectQualifier ?? (_objectQualifier = GetAppSetting("objectQualifier")); - - public static string SiteUrl => - _siteUrl ?? (_siteUrl = GetAppSetting("siteUrl") ?? DefaultWebsiteName); - - public static string HostUserName => + public static string HostUserName => _hostUserName ?? (_hostUserName = GetAppSetting("hostUserName") ?? DefaultHostName); - public static string HostPassword => + public static string HostPassword => _hostPassword ?? (_hostPassword = GetAppSetting("hostPassword") ?? DefaultHostPwd); - public static string LoginCookie => + public static string LoginCookie => _loginCookieString ?? (_loginCookieString = GetAppSetting("loginCookie") ?? DefaultLoginCookie); } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs index e978122e8b5..47db24e083a 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System.Linq; + using System.Web; + public static class ContentItemHelper { /// - /// Get a string array representing the tags associated to a content item + /// Get a string array representing the tags associated to a content item. /// - /// The id of the content item - /// An array of tags + /// The id of the content item. + /// An array of tags. public static string[] GetTags(int contentItemId) { var tagsQuery = @"SELECT t.Name Name @@ -25,13 +25,14 @@ public static string[] GetTags(int contentItemId) } /// - /// Adds a valid Fake Content item + /// Adds a valid Fake Content item. /// - /// The TabId to associate the content item to - /// the ContentItemId of the create content item + /// The TabId to associate the content item to. + /// the ContentItemId of the create content item. public static int AddContentItem(int tabId) { - var query = string.Format(@"INSERT {{objectQualifier}}ContentItems(Content, ContentTypeID, TabID, ModuleID) + var query = string.Format( + @"INSERT {{objectQualifier}}ContentItems(Content, ContentTypeID, TabID, ModuleID) VALUES ('test', (SELECT TOP 1 ContentTypeID FROM {{objectQualifier}}ContentTypes),{0}, -1); SELECT SCOPE_IDENTITY()", tabId); @@ -39,12 +40,13 @@ public static int AddContentItem(int tabId) } /// - /// Removes a content item + /// Removes a content item. /// - /// The id of the content item to remove + /// The id of the content item to remove. public static void RemoveContentItem(int contentItemId) { - var query = string.Format(@"DELETE + var query = string.Format( + @"DELETE FROM {{objectQualifier}}ContentItems WHERE ContentItemId = '{0}'", contentItemId); diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs index 9af9313f3e0..4e3ef150bb3 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs @@ -1,24 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Dynamic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data.PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + using System.Dynamic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data.PetaPoco; + public static class DatabaseHelper { private const string QualifierPrefix = "{objectQualifier}"; - private static string ReplaceQueryQualifier(string input) + private static IDictionary ValuesDictionary { - return input.Replace(QualifierPrefix, AppConfigHelper.ObjectQualifier); + // case insensitive dictionary keys + get { return new Dictionary(StringComparer.InvariantCultureIgnoreCase); } } public static bool CanConnectToDatabase() @@ -41,6 +43,11 @@ public static T ExecuteScalar(string queryString, params object[] args) return PetaPocoHelper.ExecuteScalar(AppConfigHelper.ConnectionString, CommandType.Text, qstr, args); } + private static string ReplaceQueryQualifier(string input) + { + return input.Replace(QualifierPrefix, AppConfigHelper.ObjectQualifier); + } + public static IEnumerable ExecuteQuery(string queryString) { using (var connection = new SqlConnection(AppConfigHelper.ConnectionString)) @@ -77,18 +84,20 @@ public static IList> ExecuteQuery(string queryString { values.Add(reader.GetName(i), reader.GetValue(i)); } + results.Add(values); } } } } + return results; } /// - /// Returns a dynamic object with rows and columns + /// Returns a dynamic object with rows and columns. /// - /// Row can be accessed by return[0]. Column can be accessed by return[0].ColumnName. Column names are case sensitive + /// Row can be accessed by return[0]. Column can be accessed by return[0].ColumnName. Column names are case sensitive. public static IList ExecuteDynamicQuery(string queryString) { var results = new List(); @@ -103,18 +112,21 @@ public static IList ExecuteDynamicQuery(string queryString) { while (reader.Read()) { - var values = new ExpandoObject() as IDictionary; + var values = new ExpandoObject() as IDictionary; for (var i = 0; i < reader.FieldCount; i++) { values.Add(reader.GetName(i), reader.GetValue(i)); - //values[reader.GetName(i)] = reader.GetValue(i); - //values.Add(reader.GetName(i), reader.GetValue(i)); + + // values[reader.GetName(i)] = reader.GetValue(i); + // values.Add(reader.GetName(i), reader.GetValue(i)); } + results.Add(values); } } } } + return results; } @@ -134,8 +146,9 @@ public static int ExecuteNonQuery(string queryString) /// /// Executes a specific STORED PROCEDURE. - /// The SP passed must not have the ObjectQualifier in its name; otherwise duplicate qualifier will be prefixed - /// + /// The SP passed must not have the ObjectQualifier in its name; otherwise duplicate qualifier will be prefixed. + ///
        + /// public static IList> ExecuteStoredProcedure(string procedureName, params object[] sqlParameters) { var results = new List>(); @@ -149,16 +162,19 @@ public static IList> ExecuteStoredProcedure(string p { values.Add(reader.GetName(i), reader.GetValue(i)); } + results.Add(values); } } + return results; } - + /// /// Executes a specific STORED PROCEDURE. - /// The SP passed must not have the ObjectQualifier in its name; otherwise duplicate qualifier will be prefixed - /// + /// The SP passed must not have the ObjectQualifier in its name; otherwise duplicate qualifier will be prefixed. + /// + /// public static IEnumerable ExecuteStoredProcedure(string procedureName, params object[] sqlParameters) { procedureName = ReplaceQueryQualifier(AppConfigHelper.ObjectQualifier + procedureName); @@ -168,7 +184,8 @@ public static IEnumerable ExecuteStoredProcedure(string procedureN /// /// Retrieves the total count of records of a table or view in the database. /// - /// DO NOT perfix the table/view name with a qualifier. + /// DO NOT perfix the table/view name with a qualifier. + /// public static int GetRecordsCount(string tableOrViewName, string whereCondition = null) { var queryString = ReplaceQueryQualifier(string.Format("SELECT COUNT(*) FROM [{0}{1}]", QualifierPrefix, tableOrViewName)); @@ -185,10 +202,12 @@ public static int GetRecordsCount(string tableOrViewName, string whereCondition /// Retrieves the maximum ID of a column of a table or view in the database. /// /// DO NOT perfix the table/view name with a qualifier. - /// If no record exists in the table, -1 is returned. + /// If no record exists in the table, -1 is returned. + /// public static int GetLastRecordId(string tableOrViewName, string columnName, string whereCondition = null) { - var query = string.Format("SELECT COALESCE(MAX([{0}]), -1) FROM [{1}{2}]", + var query = string.Format( + "SELECT COALESCE(MAX([{0}]), -1) FROM [{1}{2}]", columnName, QualifierPrefix, tableOrViewName); var queryString = ReplaceQueryQualifier(query); @@ -215,16 +234,12 @@ public static IDictionary GetRecordById(string tableOrViewName, { values.Add(reader.GetName(i), reader.GetValue(i)); } + break; // get the first record only } } + return values; } - - private static IDictionary ValuesDictionary - { - // case insensitive dictionary keys - get { return new Dictionary(StringComparer.InvariantCultureIgnoreCase); } - } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs index f9629e74bf1..df520f9b41a 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { public static class DnnDataHelper @@ -14,14 +14,18 @@ public static int PortalId { if (!_portalId.HasValue) { - var alias = AppConfigHelper.SiteUrl.Replace("http://", "").Replace("https://", ""); - if (alias.EndsWith("/")) - alias = alias.Substring(0, alias.Length - 1); + var alias = AppConfigHelper.SiteUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); + if (alias.EndsWith("/")) + { + alias = alias.Substring(0, alias.Length - 1); + } + var query = string.Format( "SELECT TOP(1) PortalID FROM {{objectQualifier}}PortalAlias WHERE HTTPAlias='{0}'", alias); var id = DatabaseHelper.ExecuteScalar(query); _portalId = id; } + return _portalId.Value; } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs index 020e408c2dd..3d9969c0a47 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs @@ -1,18 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System.IO; + using System.Reflection; + public static class FileHelper { public static string GetAbsoluteDir(string relativePathIn) { - if (!relativePathIn.StartsWith("\\")) relativePathIn = "\\" + relativePathIn; - + if (!relativePathIn.StartsWith("\\")) + { + relativePathIn = "\\" + relativePathIn; + } + var rootDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var pathOut = rootDirectory + relativePathIn; diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs index dd4d16e0ac7..fe51064368f 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System; + using System.Globalization; + using System.IO; + public static class FolderHelper { private const int ByteOffset = 255; diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs index 014aa1bf237..b84c6309e3e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System; + public static class HostSettingsHelper { public static string GetHostSettingValue(string hostSettingName) { - var query = string.Format("SELECT TOP(1) SettingValue FROM {{objectQualifier}}HostSettings WHERE SettingName='" + hostSettingName +"';"); + var query = string.Format("SELECT TOP(1) SettingValue FROM {{objectQualifier}}HostSettings WHERE SettingName='" + hostSettingName + "';"); return DatabaseHelper.ExecuteScalar(query); } @@ -27,9 +27,11 @@ public static bool AddSettingIfMissing(string settingName, string settingValue, bool recycleAppIfAdded = false) { var currentValue = GetHostSettingValue(settingName); - if (!string.IsNullOrEmpty(currentValue)) - return false; - + if (!string.IsNullOrEmpty(currentValue)) + { + return false; + } + var query = string.Format( @"INSERT INTO {{objectQualifier}}HostSettings (SettingName, SettingValue, SettingIsSecure, CreatedOnDate) " + @"VALUES(N'{0}', N'{1}', '0', {{ts: '{2:yyyy-MM-dd HH:mm.ss.fff}'}})", diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs index 5e181081d0e..96ae1ba1059 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.ComponentModel; -using DotNetNuke.Services.Cache; -using Moq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using DotNetNuke.ComponentModel; + using DotNetNuke.Services.Cache; + using Moq; + /// /// Class copied from Platform Tests: DotNetNuke.Tests.Utilities.Mocks.MockComponentProvider - /// - /// This class helps to mock any components that have been registered using the ComponentFactory + /// + /// This class helps to mock any components that have been registered using the ComponentFactory. /// public static class MockComponentHelper { @@ -20,14 +20,15 @@ public static Mock CreateDataCacheProvider() return CreateNew(); } - public static Mock CreateNew() where T : class + public static Mock CreateNew() + where T : class { if (ComponentFactory.Container == null) { ComponentFactory.Container = new SimpleContainer(); } - //Try and get mock + // Try and get mock var mockComp = ComponentFactory.GetComponent>(); var objComp = ComponentFactory.GetComponent(); diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs index d022669d5d7..e29c16c3e5b 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Entities.Portals; + public class PortalAliasHelper { public static PortalAliasInfo GetPrimaryPortalAlias(int portalId = 0) @@ -27,7 +28,8 @@ public static IEnumerable GetAllPortalAliaes() public static void AddPortalAlias(PortalAliasInfo portal) { - DatabaseHelper.ExecuteStoredProcedure("AddPortalAlias", + DatabaseHelper.ExecuteStoredProcedure( + "AddPortalAlias", portal.PortalID, portal.HTTPAlias, portal.CultureCode, diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs index ded4a4d02f1..69c305fd22e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System; + using System.Linq; + + using DotNetNuke.Entities.Portals; + public class PortalInfoHelper { public static PortalInfo GetPortalInfo(int portalId) @@ -17,44 +18,43 @@ public static PortalInfo GetPortalInfo(int portalId) public static void UpdatePortalInfo(PortalInfo portal) { - DatabaseHelper.ExecuteStoredProcedure("UpdatePortalInfo", - portal.PortalID, - portal.PortalGroupID, - portal.PortalName, - portal.LogoFile, - portal.FooterText, - DBNull.Value, // portal expiry date - portal.UserRegistration, - portal.BannerAdvertising, - portal.Currency, - portal.AdministratorId, - portal.HostFee, - portal.HostSpace, - portal.PageQuota, - portal.UserQuota, - portal.PaymentProcessor, - portal.ProcessorUserId, - portal.ProcessorPassword, - portal.Description, - portal.KeyWords, - portal.BackgroundFile, - portal.SiteLogHistory, - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.DefaultLanguage, - portal.HomeDirectory, - portal.LastModifiedByUserID, - portal.CultureCode); + DatabaseHelper.ExecuteStoredProcedure( + "UpdatePortalInfo", + portal.PortalID, + portal.PortalGroupID, + portal.PortalName, + portal.LogoFile, + portal.FooterText, + DBNull.Value, // portal expiry date + portal.UserRegistration, + portal.BannerAdvertising, + portal.Currency, + portal.AdministratorId, + portal.HostFee, + portal.HostSpace, + portal.PageQuota, + portal.UserQuota, + portal.PaymentProcessor, + portal.ProcessorUserId, + portal.ProcessorPassword, + portal.Description, + portal.KeyWords, + portal.BackgroundFile, + portal.SiteLogHistory, + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.DefaultLanguage, + portal.HomeDirectory, + portal.LastModifiedByUserID, + portal.CultureCode); } - - } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs index d3cfd648de9..a3af620095a 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs @@ -1,43 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { public static class PortalSettingsHelper { /// - /// Gets a portal setting value + /// Gets a portal setting value. /// - /// The name of the setting - /// The optional PortalId, default to 0 - /// The string value of the setting + /// The name of the setting. + /// The optional PortalId, default to 0. + /// The string value of the setting. public static string GetPortalSetting(string settingName, int portalId = 0) { - var query = string.Format(@"SELECT SettingValue + var query = string.Format( + @"SELECT SettingValue FROM {{objectQualifier}}PortalSettings WHERE SettingName = '{0}' AND PortalId = {1}", settingName, portalId); - + return DatabaseHelper.ExecuteScalar(query); } /// - /// Sets a portal setting value, adding or updating the setting as required + /// Sets a portal setting value, adding or updating the setting as required. /// - /// The name of the setting - /// The value of the setting - /// The optional PortalId, default to 0 + /// The name of the setting. + /// The value of the setting. + /// The optional PortalId, default to 0. /// This flag specifies whether the value is encrypted or not, defaults to false. public static void SetPortalSetting(string settingName, string settingValue, int portalId = 0, bool isSecure = false) { - var query = string.Format(@"MERGE INTO {{objectQualifier}}PortalSettings s + var query = string.Format( + @"MERGE INTO {{objectQualifier}}PortalSettings s USING (SELECT {2} PortalId, '{0}' SettingName, '{1}' SettingValue, {3} Sec) AS v ON s.SettingName = v.SettingName WHEN MATCHED THEN UPDATE SET s.SettingValue = v.SettingValue, SettingIsSecure = v.Sec WHEN NOT MATCHED THEN INSERT (PortalId, SettingName, SettingValue, SettingIsSecure) VALUES (v.PortalId, v.SettingName, v.SettingValue, v.Sec);", - settingName, settingValue, portalId, isSecure ? "1" : "0"); + settingName, settingValue, portalId, isSecure ? "1" : "0"); DatabaseHelper.ExecuteNonQuery(query); WebApiTestHelper.ClearHostCache(); diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/StoredProcedureStatsHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/StoredProcedureStatsHelper.cs index 6a3cbc572a9..fe995a18399 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/StoredProcedureStatsHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/StoredProcedureStatsHelper.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { public static class StoredProcedureStatsHelper diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs index 4cff449fdff..670ea9b8371 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Net; -using System.Security.Cryptography; -using System.Text; -using DNN.Integration.Test.Framework.Controllers; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Helpers { + using System; + using System.Collections.Generic; + using System.Net; + using System.Security.Cryptography; + using System.Text; + + using DNN.Integration.Test.Framework.Controllers; + using NUnit.Framework; + public static class WebApiTestHelper { private static IWebApiConnector _anonymousConnector; @@ -20,16 +21,10 @@ public static class WebApiTestHelper private static readonly string HostGuid = HostSettingsHelper.GetHostSettingValue("GUID"); - internal static void ClearCachedConnections() - { - _anonymousConnector = null; - CachedConnections.Clear(); - } - /// - /// Returns a coonector to access the default site annonymously + /// Returns a coonector to access the default site annonymously. /// - /// IWebApiConnector object to perform more actions + /// IWebApiConnector object to perform more actions. public static IWebApiConnector GetAnnonymousConnector(string url = null) { url = url ?? AppConfigHelper.SiteUrl; @@ -49,11 +44,17 @@ SELECT TOP 1 m.ModuleID FROM {{objectQualifier}}TabModules tm return new Dictionary { - {"TabId", tabId.ToString()}, - {"ModuleId", moduleId.ToString()} + { "TabId", tabId.ToString() }, + { "ModuleId", moduleId.ToString() }, }; } + internal static void ClearCachedConnections() + { + _anonymousConnector = null; + CachedConnections.Clear(); + } + public static IWebApiConnector PrepareNewUser(out int userId, out string username, out int fileId, int portalId = 0) { username = $"testuser{Rnd.Next(1000, 9999)}"; @@ -61,7 +62,6 @@ public static IWebApiConnector PrepareNewUser(out int userId, out string usernam using (WebApiTestHelper.Register(username, AppConfigHelper.HostPassword, username, email)) { - } userId = DatabaseHelper.ExecuteScalar($"SELECT UserId FROM {{objectQualifier}}Users WHERE Username = '{username}'"); @@ -80,8 +80,9 @@ public static IWebApiConnector PrepareNewUser(out int userId, out string usernam } /// - /// Register a user by using the Registration form - /// + /// Register a user by using the Registration form. + /// + /// public static HttpWebResponse Register(string userName, string password, string displayName, string email, string url = null, bool encriptFieldsNames = true) { @@ -90,22 +91,35 @@ public static HttpWebResponse Register(string userName, string password, string var postData = new Dictionary { - {registerFieldsPrefix + CodifyInputName("Username", "TextBox", encriptFieldsNames), userName }, - {registerFieldsPrefix + CodifyInputName("Password", "TextBox", encriptFieldsNames), password}, - {registerFieldsPrefix + CodifyInputName("PasswordConfirm", "TextBox", encriptFieldsNames), password}, - {registerFieldsPrefix + CodifyInputName("DisplayName", "TextBox", encriptFieldsNames), displayName}, - {registerFieldsPrefix + CodifyInputName("Email", "TextBox", encriptFieldsNames), email}, - {"__EVENTTARGET", "dnn$ctr$Register$registerButton"}, - {"__EVENTARGUMENT", ""}, - {"__ASYNCPOST", "true"} + { registerFieldsPrefix + CodifyInputName("Username", "TextBox", encriptFieldsNames), userName }, + { registerFieldsPrefix + CodifyInputName("Password", "TextBox", encriptFieldsNames), password }, + { registerFieldsPrefix + CodifyInputName("PasswordConfirm", "TextBox", encriptFieldsNames), password }, + { registerFieldsPrefix + CodifyInputName("DisplayName", "TextBox", encriptFieldsNames), displayName }, + { registerFieldsPrefix + CodifyInputName("Email", "TextBox", encriptFieldsNames), email }, + { "__EVENTTARGET", "dnn$ctr$Register$registerButton" }, + { "__EVENTARGUMENT", string.Empty }, + { "__ASYNCPOST", "true" }, }; url = url ?? AppConfigHelper.SiteUrl; var excludedInputPrefixes = new List(); - var connector = WebApiConnector.GetWebConnector(url, ""); + var connector = WebApiConnector.GetWebConnector(url, string.Empty); return connector.PostUserForm(registerRelativeUrl, postData, excludedInputPrefixes, false); } + public static string GenerateSha256Hash(this string str) + { + return str.GenerateHash("SHA256"); + } + + /// Generate a MD5 hash of a string. + /// + /// + public static string GenerateMd5(this string str) + { + return str.GenerateHash("MD5"); + } + private static string CodifyInputName(string originalId, string sufix, bool encriptName) { var transformedId = encriptName ? CodifyString(originalId) : originalId; @@ -131,57 +145,18 @@ private static string GenerateHash(string str) } } - public static string GenerateSha256Hash(this string str) - { - return str.GenerateHash("SHA256"); - } - - /// Generate a MD5 hash of a string - /// - public static string GenerateMd5(this string str) - { - return str.GenerateHash("MD5"); - } - - private static string GenerateHash(this string str, string hashType) - { - var hasher = HashAlgorithm.Create(hashType); - if (hasher == null) throw new InvalidOperationException("No hashing type found by name " + hashType); - using (hasher) - { - //convert our string into byte array - var byteArray = Encoding.UTF8.GetBytes(str); - - //get the hashed values created by our SHA1CryptoServiceProvider - var hashedByteArray = hasher.ComputeHash(byteArray); - - //create a StringBuilder object - var stringBuilder = new StringBuilder(); - - //loop to each each byte - foreach (var b in hashedByteArray) - { - //append it to our StringBuilder - stringBuilder.Append(b.ToString("x2").ToLowerInvariant()); - } - - //return the hashed value - return stringBuilder.ToString(); - } - } - /// - /// Creates a Registered User and performs Login for that user in as well. + /// Creates a Registered User and performs Login for that user in as well. /// Password used is same as that for Host. Existing user is used if it's already present. /// - /// IWebApiConnector object to perform more actions + /// IWebApiConnector object to perform more actions. public static IWebApiConnector LoginRegisteredUser(string firstName = IntegrationConstants.RuFirstName, string lastName = IntegrationConstants.RuLastName, string url = null) { IWebApiConnector connector; url = url ?? AppConfigHelper.SiteUrl; var username = firstName + "." + lastName; var key = string.Join("_", url, username); - if (!CachedConnections.TryGetValue(key, out connector) || + if (!CachedConnections.TryGetValue(key, out connector) || connector.LoggedInAtTime < DateTime.Now.AddMinutes(-19.5)) { var portalId = GetPortalFromUrl(url); @@ -200,10 +175,10 @@ public static IWebApiConnector LoginRegisteredUser(string firstName = Integratio } /// - /// Creates an Administrator and performs Login for that user in as well. + /// Creates an Administrator and performs Login for that user in as well. /// Password used is same as that for Host. Existing user is used if it's already present. /// - /// WebApiConnector object to perform more actions + /// WebApiConnector object to perform more actions. public static IWebApiConnector LoginAdministrator(string firstName = IntegrationConstants.AdminFirstName, string lastName = IntegrationConstants.AdminLastName, string url = null) { IWebApiConnector connector; @@ -227,19 +202,50 @@ public static IWebApiConnector LoginAdministrator(string firstName = Integration return connector; } + private static string GenerateHash(this string str, string hashType) + { + var hasher = HashAlgorithm.Create(hashType); + if (hasher == null) + { + throw new InvalidOperationException("No hashing type found by name " + hashType); + } + + using (hasher) + { + // convert our string into byte array + var byteArray = Encoding.UTF8.GetBytes(str); + + // get the hashed values created by our SHA1CryptoServiceProvider + var hashedByteArray = hasher.ComputeHash(byteArray); + + // create a StringBuilder object + var stringBuilder = new StringBuilder(); + + // loop to each each byte + foreach (var b in hashedByteArray) + { + // append it to our StringBuilder + stringBuilder.Append(b.ToString("x2").ToLowerInvariant()); + } + + // return the hashed value + return stringBuilder.ToString(); + } + } + /// /// Logs in Host. /// - /// IWebApiConnector object to perform more actions + /// IWebApiConnector object to perform more actions. public static IWebApiConnector LoginHost() { return LoginUser(AppConfigHelper.HostUserName); } /// - /// Logs in an already registered user (regardless of the user's role) + /// Logs in an already registered user (regardless of the user's role). /// - /// IWebApiConnector object to perform more actions + /// IWebApiConnector object to perform more actions. public static IWebApiConnector LoginUser(string username, string url = null) { IWebApiConnector connector; @@ -266,21 +272,21 @@ public static int GetPortalFromUrl(string url) } /// - /// Logs in as host and clears host cache + /// Logs in as host and clears host cache. /// - /// IWebApiConnector object to perform more actions + /// IWebApiConnector object to perform more actions. public static IWebApiConnector ClearHostCache() { var connector = LoginUser(AppConfigHelper.HostUserName); - //connector.PostJson("API/internalservices/controlbar/ClearHostCache", null); + + // connector.PostJson("API/internalservices/controlbar/ClearHostCache", null); connector.PostJson("API/PersonaBar/Server/ClearCache", null); return connector; } /// - /// Logs in as host and recycle the application + /// Logs in as host and recycle the application. /// - /// IWebApiConnector object to perform more actions public static void RecycleApplication() { var connector = LoginUser(AppConfigHelper.HostUserName); @@ -288,9 +294,9 @@ public static void RecycleApplication() } /// - /// Returns TabId and ModuleId headers for a Page to be passed in a Post WebApi call + /// Returns TabId and ModuleId headers for a Page to be passed in a Post WebApi call. /// - /// double-slashed prefixed page name, e.g. //Home or //Groups//GroupSpaces//Members + /// double-slashed prefixed page name, e.g. //Home or //Groups//GroupSpaces//Members. /// public static Dictionary GetTabModuleHeaders(string tabPath) { @@ -299,16 +305,16 @@ public static Dictionary GetTabModuleHeaders(string tabPath) return new Dictionary { - {"TabID", tabId.ToString("D")}, - {"ModuleID", moduleId.ToString("D")}, + { "TabID", tabId.ToString("D") }, + { "ModuleID", moduleId.ToString("D") }, }; } /// - /// Returns TabId and ModuleId headers for a Page and Module to be passed in a Post WebApi call + /// Returns TabId and ModuleId headers for a Page and Module to be passed in a Post WebApi call. /// - /// Module's friendly name, e.g. Wiki or Activity Stream - /// double-slashed prefixed page name, e.g. //Home or //Groups//GroupSpaces//Members + /// Module's friendly name, e.g. Wiki or Activity Stream. + /// double-slashed prefixed page name, e.g. //Home or //Groups//GroupSpaces//Members. /// public static Dictionary GetTabModuleHeaders(string moduleFriendlyName, string tabPath) { @@ -317,8 +323,8 @@ public static Dictionary GetTabModuleHeaders(string moduleFriend return new Dictionary { - {"TabID", tabId.ToString("D")}, - {"ModuleID", moduleId.ToString("D")}, + { "TabID", tabId.ToString("D") }, + { "ModuleID", moduleId.ToString("D") }, }; } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs index 5e55bdcf574..35f127df5d5 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs @@ -1,34 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework { + using System; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + public interface IWebApiConnector { int UserId { get; } + string UserName { get; } + bool IsLoggedIn { get; } + CookieContainer SessionCookies { get; } - DateTime LoggedInAtTime { get; } + + DateTime LoggedInAtTime { get; } + TimeSpan Timeout { get; set; } + Uri Domain { get; } + string UserAgentValue { get; set; } + bool AvoidCaching { get; set; } + void Logout(); + bool Login(string password); HttpResponseMessage UploadUserFile(string fileName, bool waitHttpResponse = true, int userId = -1); + HttpResponseMessage ActivityStreamUploadUserFile(IDictionary headers, string fileName); bool UploadCmsFile(string fileName, string portalFolder); - HttpResponseMessage PostJson(string relativeUrl, + HttpResponseMessage PostJson( + string relativeUrl, object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false); HttpWebResponse PostUserForm(string relativeUrl, IDictionary formFields, @@ -40,9 +52,8 @@ HttpWebResponse MultipartFormDataPost( HttpResponseMessage GetContent( string relativeUrl, object parameters, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true); - HttpResponseMessage GetContent(string relativeUrl, + HttpResponseMessage GetContent( + string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true); - - bool AvoidCaching { get; set; } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationConstants.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationConstants.cs index f042e53aeef..29a63e9396c 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationConstants.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationConstants.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework { public static class IntegrationConstants diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs index d56eab05aa2..afb9b84ee85 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs @@ -1,38 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; -using System.Net; -using System.Threading; -using DNN.Integration.Test.Framework.Helpers; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework { + using System; + using System.Globalization; + using System.Net; + using System.Threading; + + using DNN.Integration.Test.Framework.Helpers; + using NUnit.Framework; + public abstract class IntegrationTestBase { - public static string ConnectionString { get; } - //public static string DatabaseName { get; } - - #region static constructor - + // public static string DatabaseName { get; } static IntegrationTestBase() { ServicePointManager.Expect100Continue = false; + // setup of the whole system: take a snapshot and keep using it for all tests Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); ConnectionString = AppConfigHelper.ConnectionString; - //DatabaseName = GetDbNameFromConnectionString(ConnectionString); + + // DatabaseName = GetDbNameFromConnectionString(ConnectionString); - //SchedulerController.DisableAllSchedulers(false); - //SchedulerController.DisableAppStartDelay(false); - } - - #endregion + // SchedulerController.DisableAllSchedulers(false); + // SchedulerController.DisableAppStartDelay(false); + } + + public static string ConnectionString { get; } + public static void LogText(string text) + { + // Don't write anything to console when we run in TeamCity + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) + { + Console.WriteLine(text); + } + } + [TestFixtureSetUp] public virtual void TestFixtureSetUp() { @@ -48,12 +56,5 @@ private static string GetDbNameFromConnectionString(string connectionString) var builder = new System.Data.Common.DbConnectionStringBuilder { ConnectionString = connectionString }; return builder["Database"] as string; } - - public static void LogText(string text) - { - // Don't write anything to console when we run in TeamCity - if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) - Console.WriteLine(text); - } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Properties/AssemblyInfo.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Properties/AssemblyInfo.cs index 4da7559d236..62181f19a15 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Properties/AssemblyInfo.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Properties/AssemblyInfo.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; [assembly: AssemblyTitle("DNN.Integration.Test.Framework")] diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs index b97e4984ab2..18eebb13c0e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework.Scripts { public static class SqlScripts @@ -576,21 +576,6 @@ INSERT INTO [dbo].[{objectQualifier}ModulePermission] SELECT SCOPE_IDENTITY() AS ModulePermissionId"; - public static string UserGetPreferredTimeZone = @" - DECLARE @UserId INT - DECLARE @PortalID INT - DECLARE @PropertyDefinitionId INT - - SET @UserId = '$[user_id]' - SET @PortalID = '$[portal_id]' - - SELECT TOP 1 @PropertyDefinitionId = PropertyDefinitionID - FROM [dbo].[{objectQualifier}ProfilePropertyDefinition] - WHERE PortalID = @PortalID AND PropertyName = 'PreferredTimeZone' AND PropertyCategory = 'Preferences' - - SELECT PropertyValue FROM [dbo].[{objectQualifier}UserProfile] - WHERE PropertyDefinitionID = @PropertyDefinitionId AND [UserId] = @UserId"; - public const string PortalGetTimeZone = @" DECLARE @PortalID INT SET @PortalID = '$[portal_id]' @@ -616,6 +601,21 @@ FROM dbo.{objectQualifier}DesktopModules dtm AND (dtm.FriendlyName = @friendlyName OR mdfn.FriendlyName = @friendlyName) ORDER BY dtm.FriendlyName, mdfn.FriendlyName, dtm.DesktopModuleID, mdfn.ModuleDefID, mdl.ModuleID;"; + public static string UserGetPreferredTimeZone = @" + DECLARE @UserId INT + DECLARE @PortalID INT + DECLARE @PropertyDefinitionId INT + + SET @UserId = '$[user_id]' + SET @PortalID = '$[portal_id]' + + SELECT TOP 1 @PropertyDefinitionId = PropertyDefinitionID + FROM [dbo].[{objectQualifier}ProfilePropertyDefinition] + WHERE PortalID = @PortalID AND PropertyName = 'PreferredTimeZone' AND PropertyCategory = 'Preferences' + + SELECT PropertyValue FROM [dbo].[{objectQualifier}UserProfile] + WHERE PropertyDefinitionID = @PropertyDefinitionId AND [UserId] = @UserId"; + public const string TableExist = @" IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.[{objectQualifier}$[table_name]]') AND type in (N'U')) SELECT 1 diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs index da47725a1cb..f4b014e6b25 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs @@ -1,155 +1,155 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Cache; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Xml; -using System.Xml.Linq; -using DotNetNuke.Common.Utilities; -using DNN.Integration.Test.Framework.Controllers; -using DNN.Integration.Test.Framework.Helpers; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework { + using System; + using System.Collections.Generic; + using System.Configuration; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Cache; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Xml; + using System.Xml.Linq; + + using DNN.Integration.Test.Framework.Controllers; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Common.Utilities; + internal class WebApiConnector : IWebApiConnector, IDisposable { - + public const string FileFilters = + "swf,jpg,jpeg,jpe,gif,bmp,png,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,xml," + + "xsl,xsd,css,zip,template,htmtemplate,ico,avi,mpg,mpeg,mp3,wmv,mov,wav"; + + public const string RqVerifTokenName = "__RequestVerificationToken"; + public const string RqVerifTokenNameNoUndescrores = "RequestVerificationToken"; + + private const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"; + + private const string LoginPath = "/Login"; + private static readonly Dictionary CachedPages = new Dictionary(); public static WebApiConnector GetWebConnector(string siteUrl, string userName) { return new WebApiConnector(siteUrl) { - UserName = (userName ?? string.Empty).Replace("'", string.Empty) + UserName = (userName ?? string.Empty).Replace("'", string.Empty), }; } - - public const string FileFilters = - "swf,jpg,jpeg,jpe,gif,bmp,png,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,xml," + - "xsl,xsd,css,zip,template,htmtemplate,ico,avi,mpg,mpeg,mp3,wmv,mov,wav"; - - private const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"; + private const string LogoffPath = "/Home/ctl/Logoff"; + + // private const string LogoffPath = "/Home/ctl/Logoff.aspx"; + // private const string LogoffPath = "/Logoff.aspx"); + // private const string LogoffPath = "/Home/tabid/55/ctl/LogOff/Default.aspx"); + private const string UploadFileRequestPath = "API/internalservices/fileupload/postfile"; private string _userAgentValue; public string UserAgentValue { - get { return _userAgentValue ?? (_userAgentValue = ConfigurationManager.AppSettings["HttpUserAgent"] ?? DefaultUserAgent); } - set { _userAgentValue = value; } + get { return this._userAgentValue ?? (this._userAgentValue = ConfigurationManager.AppSettings["HttpUserAgent"] ?? DefaultUserAgent); } + set { this._userAgentValue = value; } } - - private const string LoginPath = "/Login"; - private const string LogoffPath = "/Home/ctl/Logoff"; - //private const string LogoffPath = "/Home/ctl/Logoff.aspx"; - //private const string LogoffPath = "/Logoff.aspx"); - //private const string LogoffPath = "/Home/tabid/55/ctl/LogOff/Default.aspx"); - - const string UploadFileRequestPath = "API/internalservices/fileupload/postfile"; - const string ActivityStreamUploadFilePath = "API/DNNCorp/ActivityStream/FileUpload/UploadFile"; + private const string ActivityStreamUploadFilePath = "API/DNNCorp/ActivityStream/FileUpload/UploadFile"; + private static readonly Regex HtmlFormInuts = new Regex( + @"", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); private int _userId; public bool AvoidCaching { get; set; } - void ResetUserId() - { - _userId = -1; - } - /// - /// The userID will be available only if the user is logged in. + /// Gets the userID will be available only if the user is logged in. /// After obtaining it for the first time, it will be cached until logout. /// public int UserId { get { - if (_userId <= 0 && IsLoggedIn) + if (this._userId <= 0 && this.IsLoggedIn) { - _userId = UserController.GetUserId(UserName); + this._userId = UserController.GetUserId(this.UserName); } - return _userId; + return this._userId; } } public string UserName { get; private set; } + public bool IsLoggedIn { get; private set; } - public const string RqVerifTokenName = "__RequestVerificationToken"; - public const string RqVerifTokenNameNoUndescrores = "RequestVerificationToken"; + private void ResetUserId() + { + this._userId = -1; + } + + // ============================================================================== + // Adapted from http://www.briangrinstead.com/blog/multipart-form-post-in-c# + private static readonly Encoding Encoding = Encoding.UTF8; + private CookieContainer _sessionCookiesContainer; private Cookie _cookieVerificationToken; private string _inputFieldVerificationToken; private string _currentTabId; - public TimeSpan Timeout { get; set; } - public Uri Domain { get; } - private WebApiConnector(string siteUrl) { - Timeout = TimeSpan.FromMinutes(1); - Domain = new Uri(siteUrl); - IsLoggedIn = false; - ResetUserId(); - _sessionCookiesContainer = new CookieContainer(); - _cookieVerificationToken = new Cookie(RqVerifTokenName, string.Empty, "/", Domain.Host); - AvoidCaching = false; - } - - public void Dispose() - { - Logout(); + this.Timeout = TimeSpan.FromMinutes(1); + this.Domain = new Uri(siteUrl); + this.IsLoggedIn = false; + this.ResetUserId(); + this._sessionCookiesContainer = new CookieContainer(); + this._cookieVerificationToken = new Cookie(RqVerifTokenName, string.Empty, "/", this.Domain.Host); + this.AvoidCaching = false; } - private void EnsureLoggedIn() - { - if (!IsLoggedIn) - { - Console.WriteLine(@"User not logged in yet"); - throw new WebApiException(new HttpRequestException("User not logged in yet."), - new HttpResponseMessage(HttpStatusCode.Unauthorized)); - } - } + public TimeSpan Timeout { get; set; } + + public Uri Domain { get; } public CookieContainer SessionCookies { get { - EnsureLoggedIn(); - return _sessionCookiesContainer; + this.EnsureLoggedIn(); + return this._sessionCookiesContainer; } } public DateTime LoggedInAtTime { get; private set; } + public void Dispose() + { + this.Logout(); + } + public void Logout() { - if (IsLoggedIn) + if (this.IsLoggedIn) { - LoggedInAtTime = DateTime.MinValue; - IsLoggedIn = false; - ResetUserId(); + this.LoggedInAtTime = DateTime.MinValue; + this.IsLoggedIn = false; + this.ResetUserId(); try { - var requestUriString = CombineUrlPath(Domain, LogoffPath); - var httpWebRequest1 = (HttpWebRequest) WebRequest.Create(requestUriString); + var requestUriString = CombineUrlPath(this.Domain, LogoffPath); + var httpWebRequest1 = (HttpWebRequest)WebRequest.Create(requestUriString); httpWebRequest1.Method = "GET"; httpWebRequest1.KeepAlive = false; - httpWebRequest1.CookieContainer = _sessionCookiesContainer; + httpWebRequest1.CookieContainer = this._sessionCookiesContainer; httpWebRequest1.ReadWriteTimeout = 90; - httpWebRequest1.UserAgent = UserAgentValue; + httpWebRequest1.UserAgent = this.UserAgentValue; using (httpWebRequest1.GetResponse()) { // no need to read the response stream after we logoff @@ -157,79 +157,150 @@ public void Logout() } finally { - _cookieVerificationToken = null; - _sessionCookiesContainer = new CookieContainer(); + this._cookieVerificationToken = null; + this._sessionCookiesContainer = new CookieContainer(); - var url = CombineUrlPath(Domain, "/"); + var url = CombineUrlPath(this.Domain, "/"); CachedWebPage cachedPage; - if (!AvoidCaching && CachedPages.TryGetValue(url, out cachedPage) && + if (!this.AvoidCaching && CachedPages.TryGetValue(url, out cachedPage) && cachedPage.FetchDateTime < DateTime.Now.AddMinutes(-19.5)) { - _inputFieldVerificationToken = cachedPage.VerificationToken; + this._inputFieldVerificationToken = cachedPage.VerificationToken; } - else - _inputFieldVerificationToken = null; + else + { + this._inputFieldVerificationToken = null; + } } } } - public bool Login(string password) + private void EnsureLoggedIn() { - if (IsLoggedIn) return true; + if (!this.IsLoggedIn) + { + Console.WriteLine(@"User not logged in yet"); + throw new WebApiException( + new HttpRequestException("User not logged in yet."), + new HttpResponseMessage(HttpStatusCode.Unauthorized)); + } + } - // This method uses multi-part parameters in the post body - // the response is similar to this: - // code => HTTP/1.1 302 Found - // body => Object moved

        Object moved to here.

        + public bool Login(string password) + { + if (this.IsLoggedIn) + { + return true; + } + + // This method uses multi-part parameters in the post body + // the response is similar to this: + // code => HTTP/1.1 302 Found + // body => Object moved

        Object moved to here.

        const string fieldsPrefix = "dnn$ctr$Login$Login_DNN"; var postData = new Dictionary { - {fieldsPrefix + "$txtUsername", UserName}, - {fieldsPrefix + "$txtPassword", password}, - {"__EVENTTARGET", fieldsPrefix + "$cmdLogin"}, // most important field; button action - {"__EVENTARGUMENT", ""} + { fieldsPrefix + "$txtUsername", this.UserName }, + { fieldsPrefix + "$txtPassword", password }, + { "__EVENTTARGET", fieldsPrefix + "$cmdLogin" }, // most important field; button action + { "__EVENTARGUMENT", string.Empty }, }; var excludedInputPrefixes = new List(); - //CombineUrlPath(_domain, LoginPath); - using (var httpResponse2 = PostUserForm(LoginPath, postData, excludedInputPrefixes, false)) + // CombineUrlPath(_domain, LoginPath); + using (var httpResponse2 = this.PostUserForm(LoginPath, postData, excludedInputPrefixes, false)) { if (httpResponse2 != null && httpResponse2.StatusCode < HttpStatusCode.BadRequest) // < 400 { using (httpResponse2) { - VerifyLogInCookie(httpResponse2); + this.VerifyLogInCookie(httpResponse2); } } } - if (IsLoggedIn) + if (this.IsLoggedIn) + { + this.LoggedInAtTime = DateTime.Now; + } + + return this.IsLoggedIn; + } + + public HttpResponseMessage UploadUserFile(string fileName, bool waitHttpResponse = true, int userId = -1) + { + this.EnsureLoggedIn(); + + var folder = "Users"; + if (userId > Null.NullInteger) + { + var rootFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.Root); + var subFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.SubFolder); + folder = $"Users/{rootFolder}/{subFolder}/{userId}/"; + } + + return this.UploadFile(fileName, folder, waitHttpResponse); + } + + public HttpResponseMessage ActivityStreamUploadUserFile(IDictionary headers, string fileName) + { + this.EnsureLoggedIn(); + return this.ActivityStreamUploadFile(headers, fileName); + } + + private static string GetVerificationToken(string pageData) + { + if (!string.IsNullOrEmpty(pageData)) { - LoggedInAtTime = DateTime.Now; + const string str1 = "= str1.Length) + { + var num1 = pageData.IndexOf("\"", startIndex1, StringComparison.Ordinal); + return pageData.Substring(startIndex1, num1 - startIndex1); + } } - return IsLoggedIn; + return string.Empty; } + private static string GetCurrentTabId(string pageData) + { + if (!string.IsNullOrEmpty(pageData)) + { + var match = Regex.Match(pageData, "`sf_tabId`:`(\\d+)`"); + if (match.Success) + { + return match.Groups[1].Value; + } + } + + return string.Empty; + } + private void VerifyLogInCookie(HttpWebResponse httpResponse) { var cookie = AppConfigHelper.LoginCookie; var loginCookie = httpResponse.Cookies[cookie]; if (loginCookie != null) { - IsLoggedIn = true; - ExtractVerificationCookie(httpResponse.Headers["Set-Cookie"] ?? string.Empty); + this.IsLoggedIn = true; + this.ExtractVerificationCookie(httpResponse.Headers["Set-Cookie"] ?? string.Empty); using (var rs = httpResponse.GetResponseStream()) { - if (rs != null && httpResponse.StatusCode == HttpStatusCode.OK) + if (rs != null && httpResponse.StatusCode == HttpStatusCode.OK) + { using (var sr = new StreamReader(rs, Encoding.UTF8)) { var data = sr.ReadToEnd(); var token = GetVerificationToken(data); - if (!string.IsNullOrEmpty(token)) - _inputFieldVerificationToken = token; - } + if (!string.IsNullOrEmpty(token)) + { + this._inputFieldVerificationToken = token; + } + } + } } } } @@ -246,101 +317,126 @@ private void ExtractVerificationCookie(string cookiesString) { if (part2.Contains(RqVerifTokenName)) { - _cookieVerificationToken.Value = part2.Split('=')[1]; + this._cookieVerificationToken.Value = part2.Split('=')[1]; } else if (part2.Contains("path")) { - _cookieVerificationToken.Path = part2.Split('=')[1]; + this._cookieVerificationToken.Path = part2.Split('=')[1]; } else if (part2.Contains("HttpOnly")) { - _cookieVerificationToken.HttpOnly = true; + this._cookieVerificationToken.HttpOnly = true; } } + break; } } } - private static string GetVerificationToken(string pageData) + public bool UploadCmsFile(string fileName, string portalFolder) { - if (!string.IsNullOrEmpty(pageData)) - { - const string str1 = "= str1.Length) - { - var num1 = pageData.IndexOf("\"", startIndex1, StringComparison.Ordinal); - return pageData.Substring(startIndex1, num1 - startIndex1); - } - } - - return string.Empty; + this.EnsureLoggedIn(); + var result = this.UploadFile(fileName, portalFolder); + return result.IsSuccessStatusCode; } - - private static string GetCurrentTabId(string pageData) + + public HttpResponseMessage PostJson( + string relativeUrl, + object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) { - if (!string.IsNullOrEmpty(pageData)) + if (!ignoreLoggedIn) + { + this.EnsureLoggedIn(); + } + + using (var client = this.CreateHttpClient("/", true)) { - var match = Regex.Match(pageData, "`sf_tabId`:`(\\d+)`"); - if (match.Success) + var rqHeaders = client.DefaultRequestHeaders; + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); + rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); + rqHeaders.UserAgent.Clear(); + rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); + + if (contentHeaders != null) { - return match.Groups[1].Value; + foreach (var hdr in contentHeaders) + { + if (rqHeaders.Contains(hdr.Key)) + { + rqHeaders.Remove(hdr.Key); + } + + rqHeaders.Add(hdr.Key, hdr.Value); + } } - } - return string.Empty; + var requestUriString = CombineUrlPath(this.Domain, relativeUrl); + var result = client.PostAsJsonAsync(requestUriString, content).Result; + return !waitHttpResponse + ? result + : EnsureSuccessResponse(result, "PostJson", requestUriString); + } } - #region file uploading - - public HttpResponseMessage UploadUserFile(string fileName, bool waitHttpResponse = true, int userId = -1) + public HttpResponseMessage PutJson( + string relativeUrl, + object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) { - EnsureLoggedIn(); - - var folder = "Users"; - if (userId > Null.NullInteger) + if (!ignoreLoggedIn) + { + this.EnsureLoggedIn(); + } + + using (var client = this.CreateHttpClient("/", true)) { - var rootFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.Root); - var subFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.SubFolder); - folder = $"Users/{rootFolder}/{subFolder}/{userId}/"; - } + var rqHeaders = client.DefaultRequestHeaders; + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); + rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); + rqHeaders.UserAgent.Clear(); + rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); - return UploadFile(fileName, folder, waitHttpResponse); - } + if (contentHeaders != null) + { + foreach (var hdr in contentHeaders) + { + if (rqHeaders.Contains(hdr.Key)) + { + rqHeaders.Remove(hdr.Key); + } - public HttpResponseMessage ActivityStreamUploadUserFile(IDictionary headers, string fileName) - { - EnsureLoggedIn(); - return ActivityStreamUploadFile(headers, fileName); - } + rqHeaders.Add(hdr.Key, hdr.Value); + } + } - public bool UploadCmsFile(string fileName, string portalFolder) - { - EnsureLoggedIn(); - var result = UploadFile(fileName, portalFolder); - return result.IsSuccessStatusCode; + var requestUriString = CombineUrlPath(this.Domain, relativeUrl); + var result = client.PutAsJsonAsync(requestUriString, content).Result; + return !waitHttpResponse + ? result + : EnsureSuccessResponse(result, "PutJson", requestUriString); + } } private HttpResponseMessage UploadFile(string fileName, string portalFolder, bool waitHttpResponse = true) { - using (var client = CreateHttpClient("/", true)) + using (var client = this.CreateHttpClient("/", true)) { - var headers = client.DefaultRequestHeaders; headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.8)); - headers.UserAgent.ParseAdd(UserAgentValue); + headers.UserAgent.ParseAdd(this.UserAgentValue); - if (string.IsNullOrEmpty(_inputFieldVerificationToken)) + if (string.IsNullOrEmpty(this._inputFieldVerificationToken)) { var resultGet = client.GetAsync("/").Result; var data = resultGet.Content.ReadAsStringAsync().Result; - _inputFieldVerificationToken = GetVerificationToken(data); + this._inputFieldVerificationToken = GetVerificationToken(data); - if (!string.IsNullOrEmpty(_inputFieldVerificationToken)) + if (!string.IsNullOrEmpty(this._inputFieldVerificationToken)) { - client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, _inputFieldVerificationToken); + client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); } else { @@ -353,7 +449,7 @@ private HttpResponseMessage UploadFile(string fileName, string portalFolder, boo { new KeyValuePair("\"folder\"", portalFolder), new KeyValuePair("\"filter\"", FileFilters), - new KeyValuePair("\"overwrite\"", "true") + new KeyValuePair("\"overwrite\"", "true"), }; foreach (var keyValuePair in values) @@ -366,12 +462,12 @@ private HttpResponseMessage UploadFile(string fileName, string portalFolder, boo fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fi.Name, - Name = "\"postfile\"" + Name = "\"postfile\"", }; content.Add(fileContent); - client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgentValue); + client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgentValue); var result = client.PostAsync(UploadFileRequestPath, content).Result; return !waitHttpResponse ? result @@ -384,19 +480,19 @@ private HttpResponseMessage ActivityStreamUploadFile( { using (var clientHandler = new HttpClientHandler { - AllowAutoRedirect = false + AllowAutoRedirect = false, }) using (var client = new HttpClient(clientHandler)) { - clientHandler.CookieContainer = _sessionCookiesContainer; - client.BaseAddress = Domain; - client.Timeout = Timeout; + clientHandler.CookieContainer = this._sessionCookiesContainer; + client.BaseAddress = this.Domain; + client.Timeout = this.Timeout; var rqHeaders = client.DefaultRequestHeaders; rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.8)); rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/png")); - rqHeaders.UserAgent.ParseAdd(UserAgentValue); + rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); var resultGet = client.GetAsync("/").Result; var data = resultGet.Content.ReadAsStringAsync().Result; @@ -409,14 +505,14 @@ private HttpResponseMessage ActivityStreamUploadFile( { Console.WriteLine(@"Cannot find '{0}' in the page input fields (B)", RqVerifTokenName); } - + var content = new MultipartFormDataContent(); var fi = new FileInfo(fileName); var fileContent = new ByteArrayContent(File.ReadAllBytes(fileName)); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"files[]\"", - FileName = "\"" + fi.Name + "\"" + FileName = "\"" + fi.Name + "\"", }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); @@ -428,83 +524,142 @@ private HttpResponseMessage ActivityStreamUploadFile( ? result : EnsureSuccessResponse(result, "ActivityStreamUploadFile", ActivityStreamUploadFilePath); } - } + } - #endregion - - - #region API requests / uploading content - - public HttpResponseMessage PostJson(string relativeUrl, - object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) + public HttpWebResponse PostUserForm(string relativeUrl, IDictionary formFields, + List excludedInputPrefixes, bool checkUserLoggedIn = true, bool followRedirect = false) { - if(!ignoreLoggedIn) - EnsureLoggedIn(); + if (checkUserLoggedIn) + { + this.EnsureLoggedIn(); + } + + var clientHandler = new HttpClientHandler + { + CookieContainer = this._sessionCookiesContainer, + }; - using (var client = CreateHttpClient("/", true)) + var postParameters = new Dictionary(); + string[] inputFields; + using (var client = new HttpClient(clientHandler) { - var rqHeaders = client.DefaultRequestHeaders; - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); - rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); - rqHeaders.UserAgent.Clear(); - rqHeaders.UserAgent.ParseAdd(UserAgentValue); + BaseAddress = this.Domain, + Timeout = this.Timeout, + }) + { + inputFields = this.GetPageInputFields(client, relativeUrl); + } - if (contentHeaders != null) + var firstField = formFields.First().Key; + if (!inputFields.Any(f => f.Contains(firstField))) + { + // the form doesn't have the proper input fields + Console.WriteLine( + @"Either User '{0}' has no rights to post to this page {1} or " + + @"this page does not contain correct form ", this.UserName, relativeUrl); + + // return null; + } + + foreach (var field in inputFields) + { + XElement xe = null; + try { - foreach (var hdr in contentHeaders) - { - if (rqHeaders.Contains(hdr.Key)) - { - rqHeaders.Remove(hdr.Key); - } + // fixes the error in HTML file input fields; e.g.: + // + // but should work with XHTML file input fields; e.g.: + // + var text = field.Contains(" multiple") && !field.Contains(" multiple=") + ? field.Replace(" multiple", string.Empty) + : field; - rqHeaders.Add(hdr.Key, hdr.Value); - } + xe = XElement.Parse(text); + } + catch (XmlException ex) + { + Console.WriteLine(@"XmlException: cannot parse input fields: {0}. Ex: {1}", field, ex.Message); } - var requestUriString = CombineUrlPath(Domain, relativeUrl); - var result = client.PostAsJsonAsync(requestUriString, content).Result; - return !waitHttpResponse - ? result - : EnsureSuccessResponse(result, "PostJson", requestUriString); - } - } + var attrs = xe == null + ? new XAttribute[0] + : xe.Attributes().ToArray(); - public HttpResponseMessage PutJson(string relativeUrl, - object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) - { - if (!ignoreLoggedIn) - EnsureLoggedIn(); + var inputType = attrs.FirstOrDefault(a => a.Name == "type"); + var inputName = attrs.FirstOrDefault(a => a.Name == "name"); + var inputValue = attrs.FirstOrDefault(a => a.Name == "value"); - using (var client = CreateHttpClient("/", true)) - { - var rqHeaders = client.DefaultRequestHeaders; - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); - rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); - rqHeaders.UserAgent.Clear(); - rqHeaders.UserAgent.ParseAdd(UserAgentValue); - - if (contentHeaders != null) + if (inputType != null && inputName != null) { - foreach (var hdr in contentHeaders) + switch (inputType.Value) { - if (rqHeaders.Contains(hdr.Key)) - { - rqHeaders.Remove(hdr.Key); - } - - rqHeaders.Add(hdr.Key, hdr.Value); + case "hidden": + { + if (!postParameters.ContainsKey(inputName.Value)) + { + var value = inputValue == null ? string.Empty : inputValue.Value; + if (formFields.ContainsKey(inputName.Value)) + { + value = formFields[inputName.Value].ToString(); + } + + postParameters.Add(inputName.Value, value); + } + } + + break; + case "text": + case "checkbox": + case "radio": + if (formFields.ContainsKey(inputName.Value) && + !postParameters.ContainsKey(inputName.Value)) + { + postParameters.Add(inputName.Value, formFields[inputName.Value]); + } + + break; + + // other types as "submit", etc. are ignored/discarded } } + } - var requestUriString = CombineUrlPath(Domain, relativeUrl); - var result = client.PutAsJsonAsync(requestUriString, content).Result; - return !waitHttpResponse - ? result - : EnsureSuccessResponse(result, "PutJson", requestUriString); + foreach (var field in formFields) + { + if (!postParameters.ContainsKey(field.Key)) + { + postParameters.Add(field.Key, field.Value); + } + } + + if (excludedInputPrefixes != null) + { + var keys = postParameters.Keys.ToArray(); + + var filteredKeys = from prefix in excludedInputPrefixes + from key in keys + where key.StartsWith(prefix) + select key; + + foreach (var key in filteredKeys) + { + postParameters.Remove(key); + } } + + if (postParameters.Count > 0) + { + var url = CombineUrlPath(this.Domain, relativeUrl); + return this.MultipartFormDataPost(url, this.UserAgentValue, postParameters, null, followRedirect); + } + + return null; + } + + public HttpWebResponse MultipartFormDataPost(string relativeUrl, IDictionary postParameters, IDictionary headers = null, bool followRedirect = false) + { + var url = CombineUrlPath(this.Domain, relativeUrl); + return this.MultipartFormDataPost(url, this.UserAgentValue, postParameters, headers, followRedirect); } private HttpClient CreateHttpClient(string path, bool autoRedirect) @@ -512,31 +667,31 @@ private HttpClient CreateHttpClient(string path, bool autoRedirect) var clientHandler = new HttpClientHandler { AllowAutoRedirect = autoRedirect, - CookieContainer = _sessionCookiesContainer, + CookieContainer = this._sessionCookiesContainer, }; - var url = CombineUrlPath(Domain, path); + var url = CombineUrlPath(this.Domain, path); var client = new HttpClient(clientHandler) { - BaseAddress = Domain, - Timeout = Timeout + BaseAddress = this.Domain, + Timeout = this.Timeout, }; - if (string.IsNullOrEmpty(_inputFieldVerificationToken)) + if (string.IsNullOrEmpty(this._inputFieldVerificationToken)) { - client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgentValue); + client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgentValue); var resultGet = client.GetAsync(url).Result; var data = resultGet.Content.ReadAsStringAsync().Result; - _inputFieldVerificationToken = GetVerificationToken(data); - client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, _inputFieldVerificationToken); + this._inputFieldVerificationToken = GetVerificationToken(data); + client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); - _currentTabId = GetCurrentTabId(data); - client.DefaultRequestHeaders.Add("TabId", _currentTabId); + this._currentTabId = GetCurrentTabId(data); + client.DefaultRequestHeaders.Add("TabId", this._currentTabId); } else { - client.DefaultRequestHeaders.Add("TabId", _currentTabId); - client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, _inputFieldVerificationToken); + client.DefaultRequestHeaders.Add("TabId", this._currentTabId); + client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); } return client; @@ -545,15 +700,15 @@ private HttpClient CreateHttpClient(string path, bool autoRedirect) private string[] GetPageInputFields(HttpClient client, string path) { CachedWebPage cachedPage = null; - var url = CombineUrlPath(Domain, path); - if (!IsLoggedIn || AvoidCaching || + var url = CombineUrlPath(this.Domain, path); + if (!this.IsLoggedIn || this.AvoidCaching || (!CachedPages.TryGetValue(url, out cachedPage) || cachedPage.FetchDateTime < DateTime.Now.AddMinutes(-19.5))) { try { var requestVerificationToken = string.Empty; - client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgentValue); + client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgentValue); var resultGet = client.GetAsync(url).Result; var data = resultGet.Content.ReadAsStringAsync().Result; const string str1 = "", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); - - public HttpWebResponse PostUserForm(string relativeUrl, IDictionary formFields, - List excludedInputPrefixes, bool checkUserLoggedIn = true, bool followRedirect = false) - { - if (checkUserLoggedIn) - EnsureLoggedIn(); - - var clientHandler = new HttpClientHandler - { - CookieContainer = _sessionCookiesContainer, - }; - - var postParameters = new Dictionary(); - string[] inputFields; - using (var client = new HttpClient(clientHandler) - { - BaseAddress = Domain, - Timeout = Timeout - }) - { - inputFields = GetPageInputFields(client, relativeUrl); - } - - var firstField = formFields.First().Key; - if (!inputFields.Any(f => f.Contains(firstField))) - { - // the form doesn't have the proper input fields - Console.WriteLine( - @"Either User '{0}' has no rights to post to this page {1} or " + - @"this page does not contain correct form ", UserName, relativeUrl); - //return null; - } - - foreach (var field in inputFields) - { - XElement xe = null; - try - { - // fixes the error in HTML file input fields; e.g.: - // - // but should work with XHTML file input fields; e.g.: - // - var text = field.Contains(" multiple") && !field.Contains(" multiple=") - ? field.Replace(" multiple", "") - : field; - - xe = XElement.Parse(text); - } - catch (XmlException ex) - { - Console.WriteLine(@"XmlException: cannot parse input fields: {0}. Ex: {1}", field, ex.Message); - } - - var attrs = xe == null - ? new XAttribute[0] - : xe.Attributes().ToArray(); - - var inputType = attrs.FirstOrDefault(a => "type" == a.Name); - var inputName = attrs.FirstOrDefault(a => "name" == a.Name); - var inputValue = attrs.FirstOrDefault(a => "value" == a.Name); - - if (inputType != null && inputName != null) - { - switch (inputType.Value) - { - case "hidden": - { - if (!postParameters.ContainsKey(inputName.Value)) - { - var value = inputValue == null ? "" : inputValue.Value; - if (formFields.ContainsKey(inputName.Value)) - value = formFields[inputName.Value].ToString(); - postParameters.Add(inputName.Value, value); - } - } - break; - case "text": - case "checkbox": - case "radio": - if (formFields.ContainsKey(inputName.Value) && - !postParameters.ContainsKey(inputName.Value)) - postParameters.Add(inputName.Value, formFields[inputName.Value]); - break; - // other types as "submit", etc. are ignored/discarded - } - } - } - - foreach (var field in formFields) - { - if (!postParameters.ContainsKey(field.Key)) - postParameters.Add(field.Key, field.Value); - } + } - if (excludedInputPrefixes != null) - { - var keys = postParameters.Keys.ToArray(); - - var filteredKeys = from prefix in excludedInputPrefixes - from key in keys - where key.StartsWith(prefix) - select key; - - foreach (var key in filteredKeys) - { - postParameters.Remove(key); - } - } - - if (postParameters.Count > 0) - { - var url = CombineUrlPath(Domain, relativeUrl); - return MultipartFormDataPost(url, UserAgentValue, postParameters, null, followRedirect); - } - - return null; - } - - // ============================================================================== - // Adapted from http://www.briangrinstead.com/blog/multipart-form-post-in-c# - - private static readonly Encoding Encoding = Encoding.UTF8; - - public HttpWebResponse MultipartFormDataPost(string relativeUrl, IDictionary postParameters, IDictionary headers = null, bool followRedirect = false) - { - var url = CombineUrlPath(Domain, relativeUrl); - return MultipartFormDataPost(url, UserAgentValue, postParameters, headers, followRedirect); - } - - private HttpWebResponse MultipartFormDataPost( - string postUrl, string userAgent, IDictionary postParameters, IDictionary headers = null, bool followRedirect = false) + public HttpResponseMessage GetContent( + string relativeUrl, object parameters, Dictionary contentHeaders = null, + bool waitHttpResponse = true, bool autoRedirect = true) { - var formDataBoundary = string.Format("----WebKitFormBoundary{0:X16}", DateTime.Now.Ticks); - var contentType = "multipart/form-data; boundary=" + formDataBoundary; - var formData = GetMultipartFormData(postParameters, formDataBoundary); - return PostForm(postUrl, userAgent, contentType, headers, formData, followRedirect); + var url = relativeUrl + "?" + QueryStringFromObject(parameters); + return this.GetContent(url, contentHeaders, waitHttpResponse, autoRedirect); } - private HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, IDictionary headers, byte[] formData, bool followRedirect) + public HttpResponseMessage GetContent( + string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true) { - var request = WebRequest.Create(postUrl) as HttpWebRequest; - - if (request == null) + using (var client = this.CreateHttpClient("/", autoRedirect)) { - throw new NullReferenceException("request is not a http request"); - } + var rqHeaders = client.DefaultRequestHeaders; + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); + rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); + rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); - // Set up the request properties. - request.Method = "POST"; - request.ContentType = contentType; - request.UserAgent = userAgent; - request.CookieContainer = _sessionCookiesContainer; - request.ContentLength = formData.Length; - request.Headers.Add(RqVerifTokenNameNoUndescrores, _inputFieldVerificationToken); - if (headers != null) - { - foreach (var h in headers) + if (contentHeaders != null) { - request.Headers.Add(h.Key, h.Value); + foreach (var hdr in contentHeaders) + { + rqHeaders.Add(hdr.Key, hdr.Value); + } } - } - - request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; - request.KeepAlive = true; - request.ReadWriteTimeout = 90; - request.AllowAutoRedirect = followRedirect; - request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); - - // You could add authentication here as well if needed: - // request.PreAuthenticate = true; - // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; - // request.Headers.Add("Authorization", "Basic " + - // Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password"))); - // Send the form data to the request. - using (var requestStream = request.GetRequestStream()) - { - requestStream.Write(formData, 0, formData.Length); - return request.GetResponse() as HttpWebResponse; + var requestUriString = CombineUrlPath(this.Domain, relativeUrl); + var uri = new Uri(requestUriString); + var result = client.GetAsync(uri.AbsoluteUri).Result; + return !waitHttpResponse + ? result + : EnsureSuccessResponse(result, "GetContent", uri.AbsoluteUri); } } @@ -785,9 +788,11 @@ private static byte[] GetMultipartFormData(IEnumerable postParameters, IDictionary headers = null, bool followRedirect = false) { - var properties = from p in query.GetType().GetProperties() - where p.GetValue(query, null) != null - select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(query, null).ToString()); - - return String.Join("&", properties.ToArray()); + var formDataBoundary = string.Format("----WebKitFormBoundary{0:X16}", DateTime.Now.Ticks); + var contentType = "multipart/form-data; boundary=" + formDataBoundary; + var formData = GetMultipartFormData(postParameters, formDataBoundary); + return this.PostForm(postUrl, userAgent, contentType, headers, formData, followRedirect); } - public HttpResponseMessage GetContent( - string relativeUrl, object parameters, Dictionary contentHeaders = null, - bool waitHttpResponse = true, bool autoRedirect = true) + private HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, IDictionary headers, byte[] formData, bool followRedirect) { - var url = relativeUrl + "?" + QueryStringFromObject(parameters); - return GetContent(url, contentHeaders, waitHttpResponse, autoRedirect); - } + var request = WebRequest.Create(postUrl) as HttpWebRequest; - public HttpResponseMessage GetContent( - string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true) - { - using (var client = CreateHttpClient("/", autoRedirect)) + if (request == null) { - var rqHeaders = client.DefaultRequestHeaders; - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); - rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); - rqHeaders.UserAgent.ParseAdd(UserAgentValue); + throw new NullReferenceException("request is not a http request"); + } - if (contentHeaders != null) + // Set up the request properties. + request.Method = "POST"; + request.ContentType = contentType; + request.UserAgent = userAgent; + request.CookieContainer = this._sessionCookiesContainer; + request.ContentLength = formData.Length; + request.Headers.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); + if (headers != null) + { + foreach (var h in headers) { - foreach (var hdr in contentHeaders) - { - rqHeaders.Add(hdr.Key, hdr.Value); - } + request.Headers.Add(h.Key, h.Value); } + } - var requestUriString = CombineUrlPath(Domain, relativeUrl); - var uri = new Uri(requestUriString); - var result = client.GetAsync(uri.AbsoluteUri).Result; - return !waitHttpResponse - ? result - : EnsureSuccessResponse(result, "GetContent", uri.AbsoluteUri); + request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; + request.KeepAlive = true; + request.ReadWriteTimeout = 90; + request.AllowAutoRedirect = followRedirect; + request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); + + // You could add authentication here as well if needed: + // request.PreAuthenticate = true; + // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; + // request.Headers.Add("Authorization", "Basic " + + // Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password"))); + + // Send the form data to the request. + using (var requestStream = request.GetRequestStream()) + { + requestStream.Write(formData, 0, formData.Length); + return request.GetResponse() as HttpWebResponse; } } + private static string QueryStringFromObject(object query) + { + var properties = from p in query.GetType().GetProperties() + where p.GetValue(query, null) != null + select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(query, null).ToString()); + + return string.Join("&", properties.ToArray()); + } + private static HttpResponseMessage EnsureSuccessResponse(HttpResponseMessage result, string source, string url) { var body = string.Empty; diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs index 177f4314858..881b6926954 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs @@ -1,50 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DNN.Integration.Test.Framework { + using System; + using System.Net.Http; + + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + /// /// Represents a non successful response while executing a WebApi call. /// public class WebApiException : Exception - { - /// - /// Initializes a new instance of the WebApiException class, with the specified inner exception and response - /// message that caused the exception + { + /// + /// Initializes a new instance of the class, with the specified inner exception and response. + /// message that caused the exception. /// - /// The original exception - /// The result of the request + /// The original exception. + /// The result of the request. public WebApiException(Exception innerException, HttpResponseMessage result) : base(innerException.Message, innerException) { - Result = result; + this.Result = result; } public WebApiException(Exception innerException, HttpResponseMessage result, string body) : this(innerException, result) { - Body = body; + this.Body = body; } /// - /// The result of the request. Can be used to retrieve additional info like HTTP status code + /// Gets the result of the request. Can be used to retrieve additional info like HTTP status code. /// public HttpResponseMessage Result { get; private set; } /// - /// Body from the Get Response. Available when exception is thrown as well. + /// Gets body from the Get Response. Available when exception is thrown as well. /// public string Body { get; private set; } public dynamic BodyAsJson() { - return JsonConvert.DeserializeObject(Body); + return JsonConvert.DeserializeObject(this.Body); } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/packages.config b/DNN Platform/Tests/DNN.Integration.Test.Framework/packages.config index 8cb9d3edd76..80bdfba0190 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/packages.config +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/packages.config @@ -1,8 +1,9 @@ - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs index 422e5dfa8e9..a731448dfd2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs @@ -1,48 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Linq; -using System.Web.Hosting; -using DotNetNuke.ComponentModel; -using DotNetNuke.Providers.AspNetClientCapabilityProvider; -using DotNetNuke.Tests.Utilities.Mocks; - -using NUnit.Framework; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.AspNetClientCapabilityProvider { + using System; + using System.IO; + using System.Linq; + using System.Web.Hosting; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Providers.AspNetClientCapabilityProvider; + using DotNetNuke.Tests.Utilities.Mocks; + using NUnit.Framework; + [TestFixture] public class AspNetClientCapabilityProviderTest - { - #region Private Variables - private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; - - #endregion - - #region UserAgent - - private const String iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; - - #endregion - - #region Setup & TearDown - + { + private const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; + private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; + [SetUp] public void Setup() { - _clientCapabilityProvider = new Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider(); + this._clientCapabilityProvider = new Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider(); - ComponentFactory.Container = new SimpleContainer(); - var dataProvider = MockComponentProvider.CreateDataProvider(); - dataProvider.Setup(d => d.GetProviderPath()).Returns(""); - MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); + ComponentFactory.Container = new SimpleContainer(); + var dataProvider = MockComponentProvider.CreateDataProvider(); + dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); - //create the bin folder + // create the bin folder var folderPath = HostingEnvironment.ApplicationPhysicalPath + "bin"; if (!Directory.Exists(folderPath)) { @@ -53,31 +42,24 @@ public void Setup() [TearDown] public void TearDown() { - - } - - #endregion - - #region Testing Getting ClientCapabilities based on clientID - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void AspNetClientCapabilityProvider_GetClientCapabilityById_ThrowsException_For_Empty_ClientCapabilityId() { - //Act - string nullClientCapabilityId = String.Empty; - var clientCapabilitiesByNullId = _clientCapabilityProvider.GetClientCapabilityById(nullClientCapabilityId); + // Act + string nullClientCapabilityId = string.Empty; + var clientCapabilitiesByNullId = this._clientCapabilityProvider.GetClientCapabilityById(nullClientCapabilityId); } [Test] [ExpectedException(typeof(ArgumentException))] public void AspNetClientCapabilityProvider_GetClientCapabilityById_ThrowsException_For_Null_ClientCapabilityId() { - //Act + // Act string nullClientCapabilityId = null; - var clientCapabilitiesByEmptyId = _clientCapabilityProvider.GetClientCapabilityById(nullClientCapabilityId); - } - - #endregion + var clientCapabilitiesByEmptyId = this._clientCapabilityProvider.GetClientCapabilityById(nullClientCapabilityId); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs index d4ac0f23892..a39bc7abf0e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs @@ -1,169 +1,152 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web; -using System.Web.Configuration; -using DotNetNuke.ComponentModel; -using DotNetNuke.Providers.AspNetClientCapabilityProvider; -using DotNetNuke.Tests.Utilities.Mocks; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.AspNetClientCapabilityProviderTest { + using System; + using System.IO; + using System.Web; + using System.Web.Configuration; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Providers.AspNetClientCapabilityProvider; + using DotNetNuke.Tests.Utilities.Mocks; + using NUnit.Framework; + [TestFixture] public class AspNetClientCapabilityTest - { - #region Private Variables - private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; - - #endregion - - #region User Agents - - public const String iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; - - public const String wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; - - public const String msIE8UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)"; - public const String msIE9UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; - public const String msIE10UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; - - public const String fireFox5NT61UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:5.0) Gecko/20110619 Firefox/5.0"; - - public const String iPadTabletUserAgent = "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10"; - public const String samsungGalaxyTablet = "Mozilla/5.0 (Linux; U; Android 2.2; en-gb; SAMSUNG GT-P1000 Tablet Build/MASTER) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; - - public const String winTabletPC = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; Tablet PC 2.0)"; - - - public const String htcDesireVer1Sub22UserAgent = "Mozilla/5.0 (Linux; U; Android 2.2; sv-se; Desire_A8181 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; - public const String blackBerry9105V1 = "BlackBerry9105/5.0.0.696 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133"; - - #endregion - - #region Setup & TearDown - + { + public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; + public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; + + private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; + + public const string msIE8UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)"; + public const string msIE9UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; + public const string msIE10UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; + + public const string fireFox5NT61UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:5.0) Gecko/20110619 Firefox/5.0"; + + public const string iPadTabletUserAgent = "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10"; + public const string samsungGalaxyTablet = "Mozilla/5.0 (Linux; U; Android 2.2; en-gb; SAMSUNG GT-P1000 Tablet Build/MASTER) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; + + public const string winTabletPC = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; Tablet PC 2.0)"; + + public const string htcDesireVer1Sub22UserAgent = "Mozilla/5.0 (Linux; U; Android 2.2; sv-se; Desire_A8181 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; + public const string blackBerry9105V1 = "BlackBerry9105/5.0.0.696 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133"; + [SetUp] public void Setup() { - _clientCapabilityProvider = new Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider(); + this._clientCapabilityProvider = new Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider(); - ComponentFactory.Container = new SimpleContainer(); - var dataProvider = MockComponentProvider.CreateDataProvider(); - dataProvider.Setup(d => d.GetProviderPath()).Returns(""); - MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); + ComponentFactory.Container = new SimpleContainer(); + var dataProvider = MockComponentProvider.CreateDataProvider(); + dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); } [TearDown] public void TearDown() { - - } - - #endregion - - #region Testing IsMobile for common smart phones and Tablets - + } + [Test] public void AspNetClientCapability_IsMobile_Returns_True_For_BlackBerry9105V1() { - //Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(blackBerry9105V1); + // Arrange + var clientCapability = this._clientCapabilityProvider.GetClientCapability(blackBerry9105V1); // Act var bIsMobile = clientCapability.IsMobile; - //Assert + // Assert Assert.IsTrue(bIsMobile); } - - + [Test] public void AspNetClientCapability_IsMobile_Returns_True_For_IPhone() { // Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(iphoneUserAgent); + var clientCapability = this._clientCapabilityProvider.GetClientCapability(iphoneUserAgent); // Act var bIsMobile = clientCapability.IsMobile; - //Assert + // Assert Assert.IsTrue(bIsMobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_True_For_WP7() { - //Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(wp7UserAgent); + // Arrange + var clientCapability = this._clientCapabilityProvider.GetClientCapability(wp7UserAgent); // Act var bIsMobile = clientCapability.IsMobile; - //Assert + // Assert Assert.IsTrue(bIsMobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_True_For_IPad() { - //Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(iPadTabletUserAgent); + // Arrange + var clientCapability = this._clientCapabilityProvider.GetClientCapability(iPadTabletUserAgent); - // Act + // Act var bIsMobile = clientCapability.IsMobile; - //Assert + // Assert Assert.IsTrue(bIsMobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_True_For_SamsungGalaxyGTP1000() { - //var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", string.Empty); - //simulator.SetHeader("user-agent", samsungGalaxyTablet); - //simulator.SimulateRequest(); - //var capabilities = new HttpCapabilitiesDefaultProvider().GetBrowserCapabilities(HttpContext.Current.Request); - - //Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(samsungGalaxyTablet); + // var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", string.Empty); + // simulator.SetHeader("user-agent", samsungGalaxyTablet); + // simulator.SimulateRequest(); + // var capabilities = new HttpCapabilitiesDefaultProvider().GetBrowserCapabilities(HttpContext.Current.Request); + + // Arrange + var clientCapability = this._clientCapabilityProvider.GetClientCapability(samsungGalaxyTablet); // Act var isMobile = clientCapability.IsMobile; - //Assert + // Assert Assert.IsTrue(isMobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_False_For_EmptyUserAgent() { - //Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(String.Empty); + // Arrange + var clientCapability = this._clientCapabilityProvider.GetClientCapability(string.Empty); // Act var bIsMmobile = clientCapability.IsMobile; - //Assert + // Assert Assert.IsFalse(bIsMmobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_False_For_NullUserAgent() { - //Arrange - String agent = null; - var AspNetClientCapability = _clientCapabilityProvider.GetClientCapability(agent); + // Arrange + string agent = null; + var AspNetClientCapability = this._clientCapabilityProvider.GetClientCapability(agent); // Act var bIsMobile = AspNetClientCapability.IsMobile; - //Assert + // Assert Assert.IsFalse(bIsMobile); } @@ -171,84 +154,77 @@ public void AspNetClientCapability_IsMobile_Returns_False_For_NullUserAgent() public void AspNetClientCapability_IsMobile_Returns_True_For_HTCDesireVer1Sub22() { // Arrange - var AspNetClientCapability = _clientCapabilityProvider.GetClientCapability(htcDesireVer1Sub22UserAgent); + var AspNetClientCapability = this._clientCapabilityProvider.GetClientCapability(htcDesireVer1Sub22UserAgent); // Act var bIsMobile = AspNetClientCapability.IsMobile; - //Assert + // Assert Assert.IsTrue(bIsMobile); - } - - #endregion - - #region Testing IsMobible for common desktop browsers - + } + [Test] public void AspNetClientCapability_IsMobile_Returns_False_For_InternetExplorer8() { - //Arrange - var AspNetClientCapability = _clientCapabilityProvider.GetClientCapability(msIE8UserAgent); + // Arrange + var AspNetClientCapability = this._clientCapabilityProvider.GetClientCapability(msIE8UserAgent); // Act var bIsMobile = AspNetClientCapability.IsMobile; - //Assert + // Assert Assert.IsFalse(bIsMobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_False_For_InternetExplorer9() { - //Arrange - var AspNetClientCapability = _clientCapabilityProvider.GetClientCapability(msIE9UserAgent); + // Arrange + var AspNetClientCapability = this._clientCapabilityProvider.GetClientCapability(msIE9UserAgent); // Act var bIsMobile = AspNetClientCapability.IsMobile; - //Assert + // Assert Assert.IsFalse(bIsMobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_False_For_InternetExplorer10() { - //Arrange - var AspNetClientCapability = _clientCapabilityProvider.GetClientCapability(msIE10UserAgent); + // Arrange + var AspNetClientCapability = this._clientCapabilityProvider.GetClientCapability(msIE10UserAgent); // Act var bIsMobile = AspNetClientCapability.IsMobile; - //Assert + // Assert Assert.IsFalse(bIsMobile); } [Test] public void AspNetClientCapability_IsMobile_Returns_False_For_FireFox() { - //Arrange - var AspNetClientCapability = _clientCapabilityProvider.GetClientCapability(fireFox5NT61UserAgent); + // Arrange + var AspNetClientCapability = this._clientCapabilityProvider.GetClientCapability(fireFox5NT61UserAgent); // Act var bIsMobile = AspNetClientCapability.IsMobile; - //Assert + // Assert Assert.IsFalse(bIsMobile); - } - - #endregion - - #region Testing IsTables False for non Tablet devices and User Agents + } + [Test] public void AspNetClientCapability_IsTablet_Returns_False_For_IPhone() { // Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(iphoneUserAgent); + var clientCapability = this._clientCapabilityProvider.GetClientCapability(iphoneUserAgent); // Act var bIsTablet = clientCapability.IsTablet; - //Assert + // Assert Assert.IsFalse(bIsTablet); } @@ -256,51 +232,39 @@ public void AspNetClientCapability_IsTablet_Returns_False_For_IPhone() public void AspNetClientCapability_IsTablet_Returns_True_For_PCTablet() { // Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(winTabletPC); + var clientCapability = this._clientCapabilityProvider.GetClientCapability(winTabletPC); // Act var bIsTablet = clientCapability.IsTablet; - //Assert + // Assert Assert.IsTrue(bIsTablet); - } - - #endregion - - #region Testing SupportsFlash True User Agents of known Devices - + } + [Test] public void AspNetClientCapability_SupportsFlash_Returns_True_For_HTCDesireVer1Sub22() { // Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(htcDesireVer1Sub22UserAgent); + var clientCapability = this._clientCapabilityProvider.GetClientCapability(htcDesireVer1Sub22UserAgent); // Act var bSupportsFlash = clientCapability.SupportsFlash; - //Assert + // Assert Assert.IsFalse(bSupportsFlash); - } - - #endregion - - #region Testing SupportsFlash False User Agents of known Devices - + } + [Test] public void AspNetClientCapability_SupportsFlash_Returns_False_For_WindowsPhone7() { // Arrange - var clientCapability = _clientCapabilityProvider.GetClientCapability(wp7UserAgent); + var clientCapability = this._clientCapabilityProvider.GetClientCapability(wp7UserAgent); // Act var bIsTablet = clientCapability.IsTablet; - //Assert + // Assert Assert.IsFalse(bIsTablet); - } - - #endregion - + } } - } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/DotNetNuke.Tests.AspNetCCP.csproj b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/DotNetNuke.Tests.AspNetCCP.csproj index cf1a2d094ac..823e768a1e7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/DotNetNuke.Tests.AspNetCCP.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/DotNetNuke.Tests.AspNetCCP.csproj @@ -1,107 +1,114 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {64BA74E9-411E-4DC1-91CB-DEF7F22468AD} - Library - Properties - DotNetNuke.Tests.AspNetClientCapabilityProviderTest - DotNetNuke.Tests.AspNetClientCapabilityProviderTest - v4.7.2 - 512 - ..\..\..\..\Evoq.Content\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - 7 - - - - ..\..\..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll - True - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - - - - - - - - - - - - - - - - {DDF18E36-41A0-4CA7-A098-78CA6E6F41C1} - DotNetNuke.Instrumentation - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {a3b3f1e8-6c1a-4e35-a5b4-51ecc5a43af7} - DotNetNuke.Providers.AspNetCCP - - - {5AECE021-E449-4A7F-BF82-2FA7B236ED3E} - DotNetNuke.Tests.Utilities - - - - - Designer - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {64BA74E9-411E-4DC1-91CB-DEF7F22468AD} + Library + Properties + DotNetNuke.Tests.AspNetClientCapabilityProviderTest + DotNetNuke.Tests.AspNetClientCapabilityProviderTest + v4.7.2 + 512 + ..\..\..\..\Evoq.Content\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 7 + + + + ..\..\..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll + True + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + + + + + + + + + + + + + + + + {DDF18E36-41A0-4CA7-A098-78CA6E6F41C1} + DotNetNuke.Instrumentation + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {a3b3f1e8-6c1a-4e35-a5b4-51ecc5a43af7} + DotNetNuke.Providers.AspNetCCP + + + {5AECE021-E449-4A7F-BF82-2FA7B236ED3E} + DotNetNuke.Tests.Utilities + + + + + stylecop.json + + + Designer + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/Properties/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/Properties/AssemblyInfo.cs index 1de7f19f32f..332012d6a2d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/Properties/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/Properties/AssemblyInfo.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Test.AspNetClientCapabilityProvider")] @@ -18,8 +18,8 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// 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 +// 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)] @@ -29,11 +29,11 @@ // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/packages.config index 74848f88682..295260c892e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/packages.config @@ -1,7 +1,8 @@ - - - - - - + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/AssemblyInfo.cs index cc59856ba4a..e964c84022d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/AssemblyInfo.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Tests.Authentication")] [assembly: AssemblyDescription("Open Source Web Application Framework")] @@ -16,25 +15,20 @@ [assembly: AssemblyProduct("https://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2012 by DotNetNuke Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DotNetNuke")] - - -// 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 + +// 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("d75fde76-1008-42ce-82ab-1f00c1dab8ef")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision -// - [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/DotNetNuke.Tests.Authentication.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/DotNetNuke.Tests.Authentication.csproj index df083b21e1a..e40072ea892 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/DotNetNuke.Tests.Authentication.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/DotNetNuke.Tests.Authentication.csproj @@ -1,132 +1,139 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {0E8502FD-DE8B-46A5-AB96-B1BE39777917} - Library - Properties - DotNetNuke.Tests.Authentication - DotNetNuke.Tests.Authentication - v4.7.2 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - - - 4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - ..\..\..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - - - - - - - ..\..\Components\Telerik\bin\Telerik.Web.UI.dll - - - - - - - - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {07e655de-0dd2-4874-bb0c-e818d24c9b59} - DotNetNuke.Authentication.Facebook - - - {0304b44c-ea08-434e-a368-65f619fc67a5} - DotNetNuke.Authentication.Google - - - {46924a38-cab7-485d-9301-191e35f6255f} - DotNetNuke.Authentication.LiveConnect - - - {1c882aa9-2198-41ef-b325-605340fdefe5} - DotNetNuke.Authentication.Twitter - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {0E8502FD-DE8B-46A5-AB96-B1BE39777917} + Library + Properties + DotNetNuke.Tests.Authentication + DotNetNuke.Tests.Authentication + v4.7.2 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + + + 4.0 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + ..\..\..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + + + + + + + ..\..\Components\Telerik\bin\Telerik.Web.UI.dll + + + + + + + + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {07e655de-0dd2-4874-bb0c-e818d24c9b59} + DotNetNuke.Authentication.Facebook + + + {0304b44c-ea08-434e-a368-65f619fc67a5} + DotNetNuke.Authentication.Google + + + {46924a38-cab7-485d-9301-191e35f6255f} + DotNetNuke.Authentication.LiveConnect + + + {1c882aa9-2198-41ef-b325-605340fdefe5} + DotNetNuke.Authentication.Twitter + + + + + + + + stylecop.json + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/FacebookUserDataTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/FacebookUserDataTests.cs index e2d63f29b26..303bce42c60 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/FacebookUserDataTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/FacebookUserDataTests.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Authentication.Facebook.Components; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Authentication.OAuth; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Authentication { + using System; + + using DotNetNuke.Authentication.Facebook.Components; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Authentication.OAuth; + using NUnit.Framework; + [TestFixture] public class FacebookUserDataTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/GoogleUserDataTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/GoogleUserDataTests.cs index 0baa428ce13..5defa461d9e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/GoogleUserDataTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/GoogleUserDataTests.cs @@ -1,15 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Authentication.Google.Components; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Authentication.OAuth; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Authentication { + using DotNetNuke.Authentication.Google.Components; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Authentication.OAuth; + using NUnit.Framework; + [TestFixture] public class GoogleUserDataTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/LiveUserDataTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/LiveUserDataTests.cs index b132b874eec..320cf4a9758 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/LiveUserDataTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/LiveUserDataTests.cs @@ -1,15 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Authentication.LiveConnect.Components; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Authentication.OAuth; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Authentication { + using DotNetNuke.Authentication.LiveConnect.Components; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Authentication.OAuth; + using NUnit.Framework; + [TestFixture] public class LiveUserDataTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/TwitterUserDataTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/TwitterUserDataTests.cs index 10486890b38..c025d01475a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/TwitterUserDataTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/TwitterUserDataTests.cs @@ -1,15 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Authentication.Twitter.Components; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Authentication.OAuth; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Authentication { + using DotNetNuke.Authentication.Twitter.Components; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Authentication.OAuth; + using NUnit.Framework; + [TestFixture] public class TwitterUserDataTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/packages.config index 53b44f9d8fe..97fd3abee1b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Authentication/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Authentication/packages.config @@ -1,6 +1,7 @@ - - - - - + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/AssemblyInfo.cs index daf8558a3bc..4fe2eb3e0db 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/AssemblyInfo.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Tests.Content")] [assembly: AssemblyDescription("Open Source Web Application Framework")] @@ -16,25 +15,20 @@ [assembly: AssemblyProduct("https://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2018 by DotNetNuke Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DotNetNuke")] - - -// 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 + +// 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("72dae17b-530c-4613-b492-1e9c977d97ee")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision -// - [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs index b9b8c4f04f4..62f40288699 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs @@ -1,30 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Tests.Content.Mocks; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; - -using NUnit.Framework; -using FileController = DotNetNuke.Entities.Content.AttachmentController; -using Util = DotNetNuke.Entities.Content.Common.Util; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Content { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + + using FileController = DotNetNuke.Entities.Content.AttachmentController; + using Util = DotNetNuke.Entities.Content.Common.Util; + [TestFixture] public class AttachmentControllerTests { @@ -33,8 +33,8 @@ public class AttachmentControllerTests [SetUp] public void SetUp() { - //Register MockCachingProvider - mockCache = MockComponentProvider.CreateNew(); + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); } @@ -42,58 +42,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #region Utility methods - - private static Mock DataServiceFactory() - { - var dataService = new Mock(); - - dataService.Setup(ds => - ds.SynchronizeMetaData( - It.IsAny(), - It.IsAny>>(), - It.IsAny>>())) - .Callback>, IEnumerable>>( - (ci, added, deleted) => - { - deleted.ToList().ForEach( - item => dataService.Object.DeleteMetaData(ci, item.Key, item.Value)); - - added.ToList().ForEach( - item => dataService.Object.AddMetaData(ci, item.Key, item.Value)); - }); - - // Register controller types that are dependent on our IDataService. - var contentController = new ContentController(dataService.Object); - - ComponentFactory.RegisterComponentInstance(new FileController(contentController)); - ComponentFactory.RegisterComponentInstance(contentController); - ComponentFactory.RegisterComponentInstance(MockHelper.CreateMockFileManager().Object); - - return dataService; - } - - private static Mock DataServiceFactoryWithLocalMetaData(ref Dictionary metadata) - { - var dataService = DataServiceFactory(); - - var closure = metadata; - - dataService.Setup(ds => ds.GetMetaData(It.IsAny())).Returns(() => MockHelper.CreateMetaDataReaderFromDictionary(closure)); - dataService.Setup(ds => ds.AddMetaData(It.IsAny(), It.IsAny(), It.IsAny())). - Callback((ci, name, value) => closure[name] = value); - dataService.Setup(ds => ds.DeleteMetaData(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((ci, key, val) => closure.Remove(key)); - - return dataService; - } - - #endregion - - #region FileController Tests - + } + [Test] public void Test_Add_File_To_Content_Item_Without_Metadata() { @@ -104,7 +54,7 @@ public void Test_Add_File_To_Content_Item_Without_Metadata() // Return empty set of metadata. dataService.Setup(ds => ds.GetMetaData(It.IsAny())).Returns(MockHelper.CreateEmptyMetaDataReader); - + var content = ContentTestHelper.CreateValidContentItem(); content.Metadata.Clear(); @@ -120,7 +70,7 @@ public void Test_Add_File_To_Content_Item_Without_Metadata() fileController.AddFileToContent(contentId, ContentTestHelper.CreateValidFile(0)); dataService.Verify( - ds => ds.AddMetaData(It.IsAny(), FileController.FilesKey, new[] {0}.ToJson())); + ds => ds.AddMetaData(It.IsAny(), FileController.FilesKey, new[] { 0 }.ToJson())); } [Test] @@ -130,7 +80,7 @@ public void Test_Load_Attachments_From_DataService() { ContentTestHelper.CreateValidFile(0), ContentTestHelper.CreateValidFile(1), - ContentTestHelper.CreateValidFile(2) + ContentTestHelper.CreateValidFile(2), }; var dataService = DataServiceFactory(); @@ -141,7 +91,7 @@ public void Test_Load_Attachments_From_DataService() ds => ds.GetMetaData(It.IsAny())).Returns( () => MockHelper.CreateMetaDataReaderWithFiles(files, new IFileInfo[0], new IFileInfo[0])); - + var contentItem = Util.GetContentController().GetContentItem(Constants.CONTENT_ValidContentItemId); Assert.IsNotNull(contentItem); @@ -154,6 +104,50 @@ public void Test_Load_Attachments_From_DataService() Assert.AreEqual(contentItem.Files[1].FileId, 1); Assert.AreEqual(contentItem.Files[2].FileId, 2); } + + private static Mock DataServiceFactory() + { + var dataService = new Mock(); + + dataService.Setup(ds => + ds.SynchronizeMetaData( + It.IsAny(), + It.IsAny>>(), + It.IsAny>>())) + .Callback>, IEnumerable>>( + (ci, added, deleted) => + { + deleted.ToList().ForEach( + item => dataService.Object.DeleteMetaData(ci, item.Key, item.Value)); + + added.ToList().ForEach( + item => dataService.Object.AddMetaData(ci, item.Key, item.Value)); + }); + + // Register controller types that are dependent on our IDataService. + var contentController = new ContentController(dataService.Object); + + ComponentFactory.RegisterComponentInstance(new FileController(contentController)); + ComponentFactory.RegisterComponentInstance(contentController); + ComponentFactory.RegisterComponentInstance(MockHelper.CreateMockFileManager().Object); + + return dataService; + } + + private static Mock DataServiceFactoryWithLocalMetaData(ref Dictionary metadata) + { + var dataService = DataServiceFactory(); + + var closure = metadata; + + dataService.Setup(ds => ds.GetMetaData(It.IsAny())).Returns(() => MockHelper.CreateMetaDataReaderFromDictionary(closure)); + dataService.Setup(ds => ds.AddMetaData(It.IsAny(), It.IsAny(), It.IsAny())). + Callback((ci, name, value) => closure[name] = value); + dataService.Setup(ds => ds.DeleteMetaData(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((ci, key, val) => closure.Remove(key)); + + return dataService; + } [Test] public void Test_Add_Attachments_With_FileController() @@ -166,7 +160,7 @@ public void Test_Add_Attachments_With_FileController() // Use a closure to store the metadata locally in this method. var data = new Dictionary(); - + dataService.Setup( ds => ds.GetMetaData(It.IsAny())).Returns( @@ -207,7 +201,7 @@ public void Test_Add_Attachments_With_FileController() dataService.Verify( ds => ds.AddMetaData(It.IsAny(), FileController.FilesKey, "[0]"), Times.Once()); - + dataService.Verify( ds => ds.AddMetaData(It.IsAny(), FileController.FilesKey, "[0,1]"), Times.Once()); } @@ -257,7 +251,7 @@ public void Set_MetaData_To_Empty_Value_Deletes_Row() Assert.AreEqual(0, emptyFiles.Count); } - /// This test should be moved elsewhere (cb) + /// This test should be moved elsewhere (cb). [Test] public void Set_MetaData_To_Same_Value_Doesnt_Update_Database_Entry() { @@ -275,7 +269,7 @@ public void Set_MetaData_To_Same_Value_Doesnt_Update_Database_Entry() dataService.Verify(ds => ds.DeleteMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Never()); contentItem.ContentTitle = "Foobar"; - + contentController.UpdateContentItem(contentItem); dataService.Verify(ds => ds.AddMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Once()); @@ -288,8 +282,7 @@ public void Set_MetaData_To_Same_Value_Doesnt_Update_Database_Entry() // Should be a no-op since no real data changed dataService.Verify(ds => ds.AddMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Once()); dataService.Verify(ds => ds.DeleteMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Never()); - - + // Really update contentItem.ContentTitle = "SNAFU"; @@ -297,8 +290,6 @@ public void Set_MetaData_To_Same_Value_Doesnt_Update_Database_Entry() dataService.Verify(ds => ds.AddMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Exactly(2)); dataService.Verify(ds => ds.DeleteMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Once()); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs index 897f6bd83cd..ddad1ef1213 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs @@ -1,29 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Content.Mocks; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Content { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Summary description for ContentItemTests + /// Summary description for ContentItemTests. /// [TestFixture] public class ContentControllerTests @@ -32,51 +32,44 @@ public class ContentControllerTests private Mock _mockCache; private Mock _mockDataProvider; - private Mock _mockSearchHelper; - - #region Test Initialize - + private Mock _mockSearchHelper; + [SetUp] public void SetUp() { - _mockCache = MockComponentProvider.CreateNew(); - _mockDataProvider = MockComponentProvider.CreateDataProvider(); - _mockSearchHelper = new Mock(); + this._mockCache = MockComponentProvider.CreateNew(); + this._mockDataProvider = MockComponentProvider.CreateDataProvider(); + this._mockSearchHelper = new Mock(); - Services.Search.Internals.SearchHelper.SetTestableInstance(_mockSearchHelper.Object); + Services.Search.Internals.SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); - _mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns( + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns( (string searchTypeName) => new SearchType { SearchTypeName = searchTypeName, SearchTypeId = ModuleSearchTypeId }); - } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddContentItem Tests - + } + [Test] public void ContentController_AddContentItem_Throws_On_Null_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.AddContentItem(null)); } [Test] public void ContentController_AddContentItem_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange Mock mockDataService = new Mock(); - + ContentController controller = new ContentController(mockDataService.Object); ComponentFactory.RegisterComponentInstance(controller); @@ -84,17 +77,17 @@ public void ContentController_AddContentItem_Calls_DataService_On_Valid_Argument ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Constants.CONTENT_ValidContentItemId; - //Act + // Act int contentId = controller.AddContentItem(content); - //Assert + // Assert mockDataService.Verify(ds => ds.AddContentItem(content, It.IsAny())); } [Test] public void ContentController_AddContentItem_Returns_ValidId_On_Valid_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddContentItem(It.IsAny(), It.IsAny())).Returns(Constants.CONTENT_AddContentItemId); ContentController controller = new ContentController(mockDataService.Object); @@ -104,17 +97,17 @@ public void ContentController_AddContentItem_Returns_ValidId_On_Valid_ContentIte ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Constants.CONTENT_ValidContentItemId; - //Act + // Act int contentId = controller.AddContentItem(content); - //Assert + // Assert Assert.AreEqual(Constants.CONTENT_AddContentItemId, contentId); } [Test] public void ContentController_AddContentItem_Sets_ContentItemId_Property_On_Valid_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddContentItem(It.IsAny(), It.IsAny())).Returns(Constants.CONTENT_AddContentItemId); ContentController controller = new ContentController(mockDataService.Object); @@ -124,188 +117,174 @@ public void ContentController_AddContentItem_Sets_ContentItemId_Property_On_Vali ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Constants.CONTENT_ValidContentItemId; - //Act + // Act int contentId = controller.AddContentItem(content); - //Assert + // Assert Assert.AreEqual(Constants.CONTENT_AddContentItemId, content.ContentItemId); - } - - #endregion - - #region DeleteContentItem Tests - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ContentController_DeleteContentItem_Throws_On_Null_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + + // Act, Arrange controller.DeleteContentItem(null); } [Test] public void ContentController_DeleteContentItem_Throws_On_Negative_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.DeleteContentItem(content)); } [Test] public void ContentController_DeleteContentItem_Calls_DataService_On_Valid_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Constants.CONTENT_DeleteContentItemId; - //Act + // Act controller.DeleteContentItem(content); - //Assert + // Assert mockDataService.Verify(ds => ds.DeleteContentItem(content.ContentItemId)); - } - - #endregion - - #region GetContentItem Tests - + } + [Test] public void ContentController_GetContentItem_Throws_On_Negative_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.GetContentItem(Null.NullInteger)); } [Test] public void ContentController_GetContentItem_Returns_Null_On_InValid_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentItem(Constants.CONTENT_InValidContentItemId)).Returns(MockHelper.CreateEmptyContentItemReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act ContentItem content = controller.GetContentItem(Constants.CONTENT_InValidContentItemId); - //Assert + // Assert Assert.IsNull(content); } [Test] public void ContentController_GetContentItem_Calls_DataService_On_Valid_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentItem(Constants.CONTENT_ValidContentItemId)).Returns(MockHelper.CreateValidContentItemReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act ContentItem content = controller.GetContentItem(Constants.CONTENT_ValidContentItemId); - //Assert + // Assert mockDataService.Verify(ds => ds.GetContentItem(Constants.CONTENT_ValidContentItemId)); } [Test] public void ContentController_GetContentItem_Returns_ContentItem_On_Valid_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentItem(Constants.CONTENT_ValidContentItemId)).Returns(MockHelper.CreateValidContentItemReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act ContentItem content = controller.GetContentItem(Constants.CONTENT_ValidContentItemId); - //Assert + // Assert Assert.AreEqual(Constants.CONTENT_ValidContentItemId, content.ContentItemId); Assert.AreEqual(ContentTestHelper.GetContent(Constants.CONTENT_ValidContentItemId), content.Content); Assert.AreEqual(ContentTestHelper.GetContentKey(Constants.CONTENT_ValidContentItemId), content.ContentKey); - } - - #endregion - - #region GetContentItemsByTerm Tests - + } + [Test] public void ContentController_GetContentItemsByTerm_Throws_On_Null_Term() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.GetContentItemsByTerm(Null.NullString)); } [Test] public void ContentController_GetContentItemsByTerm_Calls_DataService() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentItemsByTerm(Constants.TERM_ValidName)).Returns(MockHelper.CreateValidContentItemReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act IQueryable contentItems = controller.GetContentItemsByTerm(Constants.TERM_ValidName); - //Assert + // Assert mockDataService.Verify(ds => ds.GetContentItemsByTerm(Constants.TERM_ValidName)); } [Test] public void ContentController_GetContentItemsByTerm_Returns_Empty_List_If_Term_Not_Used() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentItemsByTerm(Constants.TERM_UnusedName)).Returns(MockHelper.CreateEmptyContentItemReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act IQueryable contentItems = controller.GetContentItemsByTerm(Constants.TERM_UnusedName); - //Assert + // Assert Assert.AreEqual(0, contentItems.Count()); } [Test] public void ContentController_GetContentItemsByTerm_Returns_List_Of_ContentItems() { - //Arrange + // Arrange Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetContentItemsByTerm(Constants.TERM_ValidName)).Returns(MockHelper.CreateValidContentItemsReader(Constants.CONTENT_TaggedItemCount, - Constants.CONTENT_IndexedFalse, - Null.NullInteger, - Constants.TERM_ValidName)); + mockDataService.Setup(ds => ds.GetContentItemsByTerm(Constants.TERM_ValidName)).Returns(MockHelper.CreateValidContentItemsReader( + Constants.CONTENT_TaggedItemCount, + Constants.CONTENT_IndexedFalse, + Null.NullInteger, + Constants.TERM_ValidName)); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act IQueryable contentItems = controller.GetContentItemsByTerm(Constants.TERM_ValidName); - //Assert + // Assert Assert.AreEqual(Constants.CONTENT_TaggedItemCount, contentItems.Count()); - } - - #endregion - - #region GetContentItemsByContentType - + } + [Test] public void ContentController_GetContentItemsByContentType_Returns_Results() { @@ -314,7 +293,7 @@ public void ContentController_GetContentItemsByContentType_Returns_Results() .Returns(MockHelper.CreateValidContentItemsReader(10, true, 0, null)); var controller = new ContentController(mock.Object); - + var items = controller.GetContentItemsByContentType(10).ToArray(); Assert.AreEqual(items.Length, 10); @@ -331,12 +310,8 @@ public void ContentController_GetContentItemsByContentType_Invalid_Id_Returns_No var items = controller.GetContentItemsByContentType(-1).ToArray(); Assert.IsEmpty(items); - } - - #endregion - - #region GetContentItensByModuleId - + } + [Test] public void GetContentItemsByModuleId_With_Negative_ModuleId_Returns_ContentItems() { @@ -351,85 +326,78 @@ public void GetContentItemsByModuleId_With_Negative_ModuleId_Returns_ContentItem Assert.AreEqual(negative.Length, 10); Assert.AreEqual(positive.Length, 1); - } - - #endregion - - #region GetUnIndexedContentItems Tests - + } + [Test] public void ContentController_GetUnIndexedContentItems_Calls_DataService() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetUnIndexedContentItems()).Returns(MockHelper.CreateValidContentItemReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act IQueryable contentItems = controller.GetUnIndexedContentItems(); - //Assert + // Assert mockDataService.Verify(ds => ds.GetUnIndexedContentItems()); } [Test] public void ContentController_GetUnIndexedContentItems_Returns_EmptyList_If_No_UnIndexed_Items() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetUnIndexedContentItems()).Returns(MockHelper.CreateEmptyContentItemReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act IQueryable contentItems = controller.GetUnIndexedContentItems(); - //Assert + // Assert Assert.AreEqual(0, contentItems.Count()); } [Test] public void ContentController_GetUnIndexedContentItems_Returns_List_Of_UnIndexedContentItems() { - //Arrange + // Arrange Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetUnIndexedContentItems()).Returns(MockHelper.CreateValidContentItemsReader(Constants.CONTENT_IndexedFalseItemCount, - Constants.CONTENT_IndexedFalse, - Null.NullInteger, - Null.NullString)); + mockDataService.Setup(ds => ds.GetUnIndexedContentItems()).Returns(MockHelper.CreateValidContentItemsReader( + Constants.CONTENT_IndexedFalseItemCount, + Constants.CONTENT_IndexedFalse, + Null.NullInteger, + Null.NullString)); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act IQueryable contentItems = controller.GetUnIndexedContentItems(); - //Assert + // Assert Assert.AreEqual(Constants.CONTENT_IndexedFalseItemCount, contentItems.Count()); foreach (ContentItem content in contentItems) { Assert.IsFalse(content.Indexed); } - } - - #endregion - - #region UpdateContentItem Tests - + } + [Test] public void ContentController_UpdateContentItem_Throws_On_Null_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.UpdateContentItem(null)); } [Test] public void ContentController_UpdateContentItem_Throws_On_Negative_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); @@ -442,7 +410,7 @@ public void ContentController_UpdateContentItem_Throws_On_Negative_ContentItemId [Test] public void ContentController_UpdateContentItem_Calls_DataService_On_Valid_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); @@ -453,165 +421,153 @@ public void ContentController_UpdateContentItem_Calls_DataService_On_Valid_Conte content.Content = Constants.CONTENT_UpdateContent; content.ContentKey = Constants.CONTENT_UpdateContentKey; - //Act + // Act controller.UpdateContentItem(content); - //Assert + // Assert mockDataService.Verify(ds => ds.UpdateContentItem(content, It.IsAny())); - } - - #endregion - - #region AddMetaData Tests - + } + [Test] public void ContentController_AddMetaData_Throws_On_Null_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.AddMetaData(null, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); } [Test] public void ContentController_AddMetaData_Throws_On_Negative_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.AddMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); } [Test] public void ContentController_AddMetaData_Throws_On_Null_MetaDataName() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - + ContentItem content = ContentTestHelper.CreateValidContentItem(); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.AddMetaData(content, Null.NullString, Constants.CONTENT_ValidMetaDataValue)); } [Test] public void ContentController_AddMetaData_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Constants.CONTENT_ValidContentItemId; - //Act + // Act controller.AddMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue); - //Assert + // Assert mockDataService.Verify(ds => ds.AddMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); - } - - #endregion - - #region DeleteMetaData Tests - + } + [Test] public void ContentController_DeleteMetaData_Throws_On_Null_ContentItem() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.AddMetaData(null, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); } [Test] public void ContentController_DeleteMetaData_Throws_On_Negative_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.DeleteMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); } [Test] public void ContentController_DeleteMetaData_Throws_On_Null_MetaDataName() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.AddMetaData(content, Null.NullString, Constants.CONTENT_ValidMetaDataValue)); } [Test] public void ContentController_DeleteMetaData_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); content.ContentItemId = Constants.CONTENT_ValidContentItemId; - //Act + // Act controller.DeleteMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue); - //Assert + // Assert mockDataService.Verify(ds => ds.DeleteMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); - } - - #endregion - - #region GetMetaData Tests - + } + [Test] public void ContentController_GetMetaData_Throws_On_Negative_ContentItemId() { - //Arrange + // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => controller.GetMetaData(Null.NullInteger)); } [Test] public void ContentController_GetMetaData_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetMetaData(Constants.CONTENT_ValidContentItemId)).Returns(MockHelper.CreateValidMetaDataReader()); ContentController controller = new ContentController(mockDataService.Object); - //Act + // Act NameValueCollection metaData = controller.GetMetaData(Constants.CONTENT_ValidContentItemId); - //Assert + // Assert mockDataService.Verify(ds => ds.GetMetaData(Constants.CONTENT_ValidContentItemId)); } [Test] public void ContentController_GetMetaData_Returns_NameValueCollection_Of_MetaData() { - //Arrange + // Arrange Mock mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetMetaData(Constants.CONTENT_ValidContentItemId)).Returns(MockHelper.CreateValidMetaDataReader()); @@ -629,25 +585,21 @@ public void ContentController_GetMetaData_Returns_NameValueCollection_Of_MetaDat added.ToList().ForEach( item => mockDataService.Object.AddMetaData(ci, item.Key, item.Value)); }); - + var controller = new ContentController(mockDataService.Object); - //Act + // Act var metaData = controller.GetMetaData(Constants.CONTENT_ValidContentItemId); - //Assert + // Assert Assert.AreEqual(Constants.CONTENT_MetaDataCount, metaData.Count); - } - - #endregion - - #region Title Tests - + } + [Test] public void ContentController_Title_Is_Saved_On_Add() { var mockDataService = new Mock(); - + mockDataService.Setup( ds => ds.AddContentItem( @@ -682,10 +634,10 @@ public void ContentController_Title_Is_Saved_On_Add() content.ContentItemId = Constants.CONTENT_ValidContentItemId; content.ContentTitle = Constants.CONTENT_ValidTitle; - //Act + // Act controller.AddContentItem(content); - //Assert + // Assert mockDataService.Verify(ds => ds.AddMetaData(content, AttachmentController.TitleKey, Constants.CONTENT_ValidTitle)); } @@ -724,17 +676,15 @@ public void ContentController_Title_Is_Saved_On_Update() content.ContentItemId = Constants.CONTENT_ValidContentItemId; content.ContentTitle = Constants.CONTENT_ValidTitle; - //Act + // Act controller.AddContentItem(content); content.ContentTitle = Constants.CONTENT_ValidTitle2; controller.UpdateContentItem(content); - //Assert + // Assert mockDataService.Verify(ds => ds.AddMetaData(content, AttachmentController.TitleKey, Constants.CONTENT_ValidTitle)); mockDataService.Verify(ds => ds.AddMetaData(content, AttachmentController.TitleKey, Constants.CONTENT_ValidTitle2)); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs index 16f2c88fc87..9c6795d39e9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs @@ -1,190 +1,174 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Content.Mocks; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Content { + using System; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Summary description for ContentTypeTests + /// Summary description for ContentTypeTests. /// [TestFixture] public class ContentTypeControllerTests { - private Mock mockCache; - - #region Test Initialize - + private Mock mockCache; + [SetUp] public void SetUp() { - //Register MockCachingProvider - mockCache = MockComponentProvider.CreateNew(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(String.Empty); + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddContentType - + } + [Test] public void ContentTypeController_AddContentType_Throws_On_Null_ContentType() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => contentTypeController.AddContentType(null)); } [Test] public void ContentTypeController_AddContentType_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); ContentType contentType = ContentTestHelper.CreateValidContentType(); - //Act + // Act int contentTypeId = contentTypeController.AddContentType(contentType); - //Assert + // Assert mockDataService.Verify(ds => ds.AddContentType(contentType)); } [Test] public void ContentTypeController_AddContentType_Returns_ValidId_On_Valid_ContentType() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddContentType(It.IsAny())).Returns(Constants.CONTENTTYPE_AddContentTypeId); var contentTypeController = new ContentTypeController(mockDataService.Object); var contentType = ContentTestHelper.CreateValidContentType(); - //Act + // Act int contentTypeId = contentTypeController.AddContentType(contentType); - //Assert + // Assert Assert.AreEqual(Constants.CONTENTTYPE_AddContentTypeId, contentTypeId); } [Test] public void ContentTypeController_AddContentType_Sets_ValidId_On_Valid_ContentType() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddContentType(It.IsAny())).Returns(Constants.CONTENTTYPE_AddContentTypeId); var contentTypeController = new ContentTypeController(mockDataService.Object); var contentType = ContentTestHelper.CreateValidContentType(); - //Act + // Act contentTypeController.AddContentType(contentType); - //Assert + // Assert Assert.AreEqual(Constants.CONTENTTYPE_AddContentTypeId, contentType.ContentTypeId); - } - - #endregion - - #region DeleteContentType - + } + [Test] public void ContentTypeController_DeleteContentType_Throws_On_Null_ContentType() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => contentTypeController.DeleteContentType(null)); } [Test] public void ContentTypeController_DeleteContentType_Throws_On_Negative_ContentTypeId() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); ContentType contentType = ContentTestHelper.CreateValidContentType(); contentType.ContentTypeId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => contentTypeController.DeleteContentType(contentType)); } [Test] public void ContentTypeController_DeleteContentType_Calls_DataService_On_Valid_ContentTypeId() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); var contentType = ContentTestHelper.CreateValidContentType(); contentType.ContentTypeId = Constants.CONTENTTYPE_ValidContentTypeId; - //Act + // Act contentTypeController.DeleteContentType(contentType); - //Assert + // Assert mockDataService.Verify(ds => ds.DeleteContentType(contentType)); - } - - #endregion - - #region GetContentTypes - + } + [Test] public void ContentTypeController_GetContentTypes_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentTypes()).Returns(MockHelper.CreateValidContentTypesReader(Constants.CONTENTTYPE_ValidContentTypeCount)); var contentTypeController = new ContentTypeController(mockDataService.Object); - //Act + // Act var contentTypes = contentTypeController.GetContentTypes(); - //Assert + // Assert mockDataService.Verify(ds => ds.GetContentTypes()); } [Test] public void ContentTypeController_GetContentTypes_Returns_Empty_List_Of_ContentTypes_If_No_ContentTypes() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentTypes()).Returns(MockHelper.CreateEmptyContentTypeReader()); var contentTypeController = new ContentTypeController(mockDataService.Object); - //Act + // Act var contentTypes = contentTypeController.GetContentTypes(); - //Assert + // Assert Assert.IsNotNull(contentTypes); Assert.AreEqual(0, contentTypes.Count()); } @@ -192,37 +176,33 @@ public void ContentTypeController_GetContentTypes_Returns_Empty_List_Of_ContentT [Test] public void ContentTypeController_GetContentTypes_Returns_List_Of_ContentTypes() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetContentTypes()).Returns(MockHelper.CreateValidContentTypesReader(Constants.CONTENTTYPE_ValidContentTypeCount)); var contentTypeController = new ContentTypeController(mockDataService.Object); - //Act + // Act var contentTypes = contentTypeController.GetContentTypes(); - //Assert + // Assert Assert.AreEqual(Constants.CONTENTTYPE_ValidContentTypeCount, contentTypes.Count()); - } - - #endregion - - #region UpdateContentType - + } + [Test] public void ContentTypeController_UpdateContentType_Throws_On_Null_ContentType() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => contentTypeController.UpdateContentType(null)); } [Test] public void ContentTypeController_UpdateContentType_Throws_On_Negative_ContentTypeId() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); @@ -235,7 +215,7 @@ public void ContentTypeController_UpdateContentType_Throws_On_Negative_ContentTy [Test] public void ContentTypeController_UpdateContentType_Calls_DataService_On_Valid_ContentType() { - //Arrange + // Arrange var mockDataService = new Mock(); var contentTypeController = new ContentTypeController(mockDataService.Object); @@ -243,13 +223,11 @@ public void ContentTypeController_UpdateContentType_Calls_DataService_On_Valid_C contentType.ContentTypeId = Constants.CONTENTTYPE_UpdateContentTypeId; contentType.ContentType = Constants.CONTENTTYPE_UpdateContentType; - //Act + // Act contentTypeController.UpdateContentType(contentType); - //Assert + // Assert mockDataService.Verify(ds => ds.UpdateContentType(contentType)); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/DotNetNuke.Tests.Content.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Content/DotNetNuke.Tests.Content.csproj index 2c6d589a7a4..702d7839a45 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/DotNetNuke.Tests.Content.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/DotNetNuke.Tests.Content.csproj @@ -1,146 +1,153 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {22A67B3F-D9B6-4447-A3F7-E387075AF969} - Library - Properties - DotNetNuke.Tests.Content - DotNetNuke.Tests.Content - v4.7.2 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - - - 4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - ..\..\..\..\Evoq.Content\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - - False - ..\..\DotNetNuke.Log4net\bin\dotnetnuke.log4net.dll - - - ..\..\..\Packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - False - ..\..\..\Packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - - - - - - - ..\..\Components\Telerik\bin\Telerik.Web.UI.dll - - - - - - - - - Code - - - - - - - - {04f77171-0634-46e0-a95e-d7477c88712e} - DotNetNuke.Log4Net - - - {B1699614-39D4-468A-AB1D-A2FBA97CADDF} - DotNetNuke.Web - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {2595aade-d3e0-4205-b8af-109cb23f4223} - DotNetNuke.Tests.Data - - - {68368906-57dd-40d1-ac10-35211a17d617} - DotNetNuke.Tests.Utilities - - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {22A67B3F-D9B6-4447-A3F7-E387075AF969} + Library + Properties + DotNetNuke.Tests.Content + DotNetNuke.Tests.Content + v4.7.2 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + + + 4.0 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + ..\..\..\..\Evoq.Content\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + + False + ..\..\DotNetNuke.Log4net\bin\dotnetnuke.log4net.dll + + + ..\..\..\Packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + False + ..\..\..\Packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + + + + + + + ..\..\Components\Telerik\bin\Telerik.Web.UI.dll + + + + + + + + + Code + + + + + + + + {04f77171-0634-46e0-a95e-d7477c88712e} + DotNetNuke.Log4Net + + + {B1699614-39D4-468A-AB1D-A2FBA97CADDF} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {2595aade-d3e0-4205-b8af-109cb23f4223} + DotNetNuke.Tests.Data + + + {68368906-57dd-40d1-ac10-35211a17d617} + DotNetNuke.Tests.Utilities + + + + + + + + stylecop.json + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs index 789604d110e..41c34cfeecb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs @@ -1,29 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; -using System.Linq.Expressions; -using System.Web; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Web.Validators; - -using Moq; -using FileController = DotNetNuke.Entities.Content.AttachmentController; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Content.Mocks { + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; + using System.Linq.Expressions; + using System.Web; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Web.Validators; + using Moq; + + using FileController = DotNetNuke.Entities.Content.AttachmentController; + public static class MockHelper { internal static IQueryable TestVocabularies @@ -48,6 +48,16 @@ internal static IQueryable TestVocabularies return vocabularies.AsQueryable(); } } + + internal static IDataReader CreateEmptyContentItemReader() + { + return CreateContentItemTable().CreateDataReader(); + } + + internal static IDataReader CreateEmptyContentTypeReader() + { + return CreateContentTypeTable().CreateDataReader(); + } private static void AddBaseEntityColumns(DataTable table) { @@ -114,6 +124,7 @@ private static DataTable CreateContentTypeTable() // Create columns, ID and Name. DataColumn idColumn = table.Columns.Add("ContentTypeID", typeof(int)); table.Columns.Add("ContentType", typeof(string)); + // Set the ID column as the primary key column. table.PrimaryKey = new[] { idColumn }; @@ -128,6 +139,7 @@ private static DataTable CreateScopeTypeTable() // Create columns, ID and Name. DataColumn idColumn = table.Columns.Add("ScopeTypeID", typeof(int)); table.Columns.Add("ScopeType", typeof(string)); + // Set the ID column as the primary key column. table.PrimaryKey = new[] { idColumn }; @@ -179,15 +191,16 @@ private static DataTable CreateVocabularyTable() return table; } - private static Mock RegisterMockController(Mock mock) where TMock : class + private static Mock RegisterMockController(Mock mock) + where TMock : class { if (ComponentFactory.Container == null) { - //Create a Container + // Create a Container ComponentFactory.Container = new SimpleContainer(); } - //Try and get mock + // Try and get mock var getMock = ComponentFactory.GetComponent>(); if (getMock == null) @@ -199,20 +212,10 @@ private static Mock RegisterMockController(Mock mock) where ComponentFactory.RegisterComponentInstance>(getMock); ComponentFactory.RegisterComponentInstance(getMock.Object); } + return getMock; } - - internal static IDataReader CreateEmptyContentItemReader() - { - return CreateContentItemTable().CreateDataReader(); - } - - internal static IDataReader CreateEmptyContentTypeReader() - { - return CreateContentTypeTable().CreateDataReader(); - } - internal static IDataReader CreateEmptyScopeTypeReader() { return CreateScopeTypeTable().CreateDataReader(); @@ -238,20 +241,21 @@ internal static Mock CreateMockVocabularyController() var mockVocabularies = new Mock(); mockVocabularies.Setup(v => v.GetVocabularies()).Returns(TestVocabularies); - //Register Mock + // Register Mock return RegisterMockController(mockVocabularies); } internal static IDataReader CreateValidContentItemReader() { DataTable table = CreateContentItemTable(); - AddContentItemToTable(table, - Constants.CONTENT_ValidContentItemId, - ContentTestHelper.GetContent(Constants.CONTENT_ValidContentItemId), - ContentTestHelper.GetContentKey(Constants.CONTENT_ValidContentItemId), - true, - Constants.USER_ValidId, - Null.NullString); + AddContentItemToTable( + table, + Constants.CONTENT_ValidContentItemId, + ContentTestHelper.GetContent(Constants.CONTENT_ValidContentItemId), + ContentTestHelper.GetContentKey(Constants.CONTENT_ValidContentItemId), + true, + Constants.USER_ValidId, + Null.NullString); return table.CreateDataReader(); } @@ -260,13 +264,14 @@ internal static IDataReader CreateValidContentItemReader(ContentItem contentItem { DataTable table = CreateContentItemTable(); - AddContentItemToTable(table, - contentItem.ContentItemId, - ContentTestHelper.GetContent(contentItem.ContentItemId), - ContentTestHelper.GetContentKey(contentItem.ContentItemId), - true, - Constants.USER_ValidId, - Null.NullString); + AddContentItemToTable( + table, + contentItem.ContentItemId, + ContentTestHelper.GetContent(contentItem.ContentItemId), + ContentTestHelper.GetContentKey(contentItem.ContentItemId), + true, + Constants.USER_ValidId, + Null.NullString); return table.CreateDataReader(); } @@ -328,7 +333,7 @@ internal static IDataReader CreateValidMetaDataReader() { for (int i = 0; i < Constants.CONTENT_MetaDataCount; i++) { - table.Rows.Add(new object[] { String.Format("{0} {1}", Constants.CONTENT_ValidMetaDataName, i), Constants.CONTENT_ValidMetaDataValue }); + table.Rows.Add(new object[] { string.Format("{0} {1}", Constants.CONTENT_ValidMetaDataName, i), Constants.CONTENT_ValidMetaDataValue }); } return table.CreateDataReader(); @@ -382,16 +387,16 @@ internal static IDataReader CreateEmptyMetaDataReader() internal static IDataReader CreateValidTermReader() { DataTable table = CreateTermTable(); - AddTermToTable(table, - Constants.TERM_ValidTermId, - Constants.TERM_ValidContent1, - Constants.TERM_ValidVocabulary1, - Constants.TERM_ValidName, - Constants.TERM_ValidName, - Constants.TERM_ValidWeight, - Constants.TERM_ValidParentTermId); - - + AddTermToTable( + table, + Constants.TERM_ValidTermId, + Constants.TERM_ValidContent1, + Constants.TERM_ValidVocabulary1, + Constants.TERM_ValidName, + Constants.TERM_ValidName, + Constants.TERM_ValidWeight, + Constants.TERM_ValidParentTermId); + return table.CreateDataReader(); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs index 1a36e02e405..f69499e287f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs @@ -1,130 +1,118 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Content.Mocks; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Content { + using System; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Summary description for ScopeTypeTests + /// Summary description for ScopeTypeTests. /// [TestFixture] public class ScopeTypeControllerTests { - private Mock mockCache; - - #region Test Initialize - + private Mock mockCache; + [SetUp] public void SetUp() { - //Register MockCachingProvider - mockCache = MockComponentProvider.CreateNew(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(String.Empty); + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddScopeType - + } + [Test] public void ScopeTypeController_AddScopeType_Throws_On_Null_ScopeType() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => scopeTypeController.AddScopeType(null)); } [Test] public void ScopeTypeController_AddScopeType_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); var scopeType = ContentTestHelper.CreateValidScopeType(); - //Act + // Act int scopeTypeId = scopeTypeController.AddScopeType(scopeType); - //Assert + // Assert mockDataService.Verify(ds => ds.AddScopeType(scopeType)); } [Test] public void ScopeTypeController_AddScopeType_Returns_ValidId_On_Valid_ScopeType() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddScopeType(It.IsAny())).Returns(Constants.SCOPETYPE_AddScopeTypeId); var scopeTypeController = new ScopeTypeController(mockDataService.Object); ScopeType scopeType = ContentTestHelper.CreateValidScopeType(); - //Act + // Act int scopeTypeId = scopeTypeController.AddScopeType(scopeType); - //Assert + // Assert Assert.AreEqual(Constants.SCOPETYPE_AddScopeTypeId, scopeTypeId); } [Test] public void ScopeTypeController_AddScopeType_Sets_ValidId_On_Valid_ScopeType() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddScopeType(It.IsAny())).Returns(Constants.SCOPETYPE_AddScopeTypeId); var scopeTypeController = new ScopeTypeController(mockDataService.Object); var scopeType = ContentTestHelper.CreateValidScopeType(); - //Act + // Act scopeTypeController.AddScopeType(scopeType); - //Assert + // Assert Assert.AreEqual(Constants.SCOPETYPE_AddScopeTypeId, scopeType.ScopeTypeId); - } - - #endregion - - #region DeleteScopeType - + } + [Test] public void ScopeTypeController_DeleteScopeType_Throws_On_Null_ScopeType() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => scopeTypeController.DeleteScopeType(null)); } [Test] public void ScopeTypeController_DeleteScopeType_Throws_On_Negative_ScopeTypeId() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); @@ -137,51 +125,47 @@ public void ScopeTypeController_DeleteScopeType_Throws_On_Negative_ScopeTypeId() [Test] public void ScopeTypeController_DeleteScopeType_Calls_DataService_On_Valid_ContentTypeId() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); var scopeType = ContentTestHelper.CreateValidScopeType(); scopeType.ScopeTypeId = Constants.SCOPETYPE_ValidScopeTypeId; - //Act + // Act scopeTypeController.DeleteScopeType(scopeType); - //Assert + // Assert mockDataService.Verify(ds => ds.DeleteScopeType(scopeType)); - } - - #endregion - - #region GetScopeTypes - + } + [Test] public void ScopeTypeController_GetScopeTypes_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateValidScopeTypesReader(Constants.SCOPETYPE_ValidScopeTypeCount)); var scopeTypeController = new ScopeTypeController(mockDataService.Object); - //Act + // Act IQueryable scopeTypes = scopeTypeController.GetScopeTypes(); - //Assert + // Assert mockDataService.Verify(ds => ds.GetScopeTypes()); } [Test] public void ScopeTypeController_GetScopeTypes_Returns_Empty_List_Of_ScopeTypes_If_No_ScopeTypes() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateEmptyScopeTypeReader()); var scopeTypeController = new ScopeTypeController(mockDataService.Object); - //Act + // Act var scopeTypes = scopeTypeController.GetScopeTypes(); - //Assert + // Assert Assert.IsNotNull(scopeTypes); Assert.AreEqual(0, scopeTypes.Count()); } @@ -189,37 +173,33 @@ public void ScopeTypeController_GetScopeTypes_Returns_Empty_List_Of_ScopeTypes_I [Test] public void ScopeTypeController_GetScopeTypes_Returns_List_Of_ScopeTypes() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetScopeTypes()).Returns(MockHelper.CreateValidScopeTypesReader(Constants.SCOPETYPE_ValidScopeTypeCount)); var scopeTypeController = new ScopeTypeController(mockDataService.Object); - //Act + // Act var scopeTypes = scopeTypeController.GetScopeTypes(); - //Assert + // Assert Assert.AreEqual(Constants.SCOPETYPE_ValidScopeTypeCount, scopeTypes.Count()); - } - - #endregion - - #region UpdateScopeType - + } + [Test] public void ScopeTypeController_UpdateScopeType_Throws_On_Null_ScopeType() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => scopeTypeController.UpdateScopeType(null)); } [Test] public void ScopeTypeController_UpdateScopeType_Throws_On_Negative_ScopeTypeId() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); @@ -232,7 +212,7 @@ public void ScopeTypeController_UpdateScopeType_Throws_On_Negative_ScopeTypeId() [Test] public void ScopeTypeController_UpdateScopeType_Calls_DataService_On_Valid_ContentType() { - //Arrange + // Arrange var mockDataService = new Mock(); var scopeTypeController = new ScopeTypeController(mockDataService.Object); @@ -240,13 +220,11 @@ public void ScopeTypeController_UpdateScopeType_Calls_DataService_On_Valid_Conte scopeType.ScopeTypeId = Constants.SCOPETYPE_UpdateScopeTypeId; scopeType.ScopeType = Constants.SCOPETYPE_UpdateScopeType; - //Act + // Act scopeTypeController.UpdateScopeType(scopeType); - //Assert + // Assert mockDataService.Verify(ds => ds.UpdateScopeType(scopeType)); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs index 92055eae7ef..ea47617e103 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs @@ -1,97 +1,90 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Content.Mocks; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Content { + using System; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Summary description for TermTests + /// Summary description for TermTests. /// [TestFixture] public class TermControllerTests { - private Mock mockCache; - - #region Test Initialize - + private Mock mockCache; + [SetUp] public void SetUp() { Mock vocabularyController = MockHelper.CreateMockVocabularyController(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(String.Empty); - //Register MockCachingProvider - mockCache = MockComponentProvider.CreateNew(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); + + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddTerm - + } + [Test] public void TermController_AddTerm_Throws_On_Null_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.AddTerm(null)); } [Test] public void TermController_AddTerm_Throws_On_Invalid_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); term.Name = Constants.TERM_InValidName; - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.AddTerm(term)); } [Test] public void TermController_AddTerm_Throws_On_Negative_VocabularyId() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.AddTerm(term)); } [Test] public void TermController_AddTerm_Should_Call_DataService_AddSimpleTerm_If_Term_Is_Simple_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -107,7 +100,7 @@ public void TermController_AddTerm_Should_Call_DataService_AddSimpleTerm_If_Term [Test] public void TermController_AddTerm_Should_Call_DataService_AddHeirarchicalTerm_If_Term_Is_Heirarchical_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -123,121 +116,117 @@ public void TermController_AddTerm_Should_Call_DataService_AddHeirarchicalTerm_I [Test] public void TermController_AddTerm_Returns_Valid_Id_On_Valid_Term_If_Term_Is_Simple_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); mockDataService.Setup(ds => ds.AddSimpleTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - //Act + // Act int termId = termController.AddTerm(term); - //Assert + // Assert Assert.AreEqual(Constants.TERM_AddTermId, termId); } [Test] public void TermController_AddTerm_Sets_Valid_Id_On_Valid_Term_If_Term_Is_Simple_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); mockDataService.Setup(ds => ds.AddSimpleTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - //Act + // Act termController.AddTerm(term); - //Assert + // Assert Assert.AreEqual(Constants.TERM_AddTermId, term.TermId); } [Test] public void TermController_AddTerm_Returns_Valid_Id_On_Valid_Term_If_Term_Is_Heirarchical_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); mockDataService.Setup(ds => ds.AddHeirarchicalTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); - //Act + // Act int termId = termController.AddTerm(term); - //Assert + // Assert Assert.AreEqual(Constants.TERM_AddTermId, termId); } [Test] public void TermController_AddTerm_Sets_Valid_Id_On_Valid_Term_If_Term_Is_Heirarchical_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); mockDataService.Setup(ds => ds.AddHeirarchicalTerm(It.IsAny(), It.IsAny())).Returns(Constants.TERM_AddTermId); Term term = ContentTestHelper.CreateValidHeirarchicalTerm(Constants.VOCABULARY_HierarchyVocabularyId, Constants.TERM_ValidParentTermId); - //Act + // Act termController.AddTerm(term); - //Assert + // Assert Assert.AreEqual(Constants.TERM_AddTermId, term.TermId); } [Test] public void TermController_AddTerm_Clears_Term_Cache_On_Valid_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - //Act + // Act termController.AddTerm(term); - //Assert - mockCache.Verify(cache => cache.Remove(String.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - - #endregion - - #region AddTermToContent - + // Assert + this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); + } + [Test] public void TermController_AddTermToContent_Throws_On_Null_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); ContentItem content = ContentTestHelper.CreateValidContentItem(); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.AddTermToContent(null, content)); } [Test] public void TermController_AddTermToContent_Throws_On_Null_ContentItem() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.AddTermToContent(term, null)); } [Test] public void TermController_AddTermToContent_Should_Call_DataService_If_Valid_Params() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -249,41 +238,37 @@ public void TermController_AddTermToContent_Should_Call_DataService_If_Valid_Par // Assert mockDataService.Verify(ds => ds.AddTermToContent(term, content)); - } - - #endregion - - #region DeleteTerm - + } + [Test] public void TermController_DeleteTerm_Throws_On_Null_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.DeleteTerm(null)); } [Test] public void TermController_DeleteTerm_Throws_On_Negative_TermId() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); var term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); term.TermId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.DeleteTerm(term)); } [Test] public void TermController_DeleteTerm_Should_Call_DataService_DeleteSimpleTerm_If_Term_Is_Simple_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -300,7 +285,7 @@ public void TermController_DeleteTerm_Should_Call_DataService_DeleteSimpleTerm_I [Test] public void TermController_DeleteTerm_Should_Call_DataService_DeleteHeirarchicalTerm_If_Term_Is_Heirarchical_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -317,129 +302,123 @@ public void TermController_DeleteTerm_Should_Call_DataService_DeleteHeirarchical [Test] public void TermController_DeleteTerm_Clears_Term_Cache_On_Valid_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - var term = new Term(Constants.VOCABULARY_ValidVocabularyId) {TermId = Constants.TERM_DeleteTermId}; + var term = new Term(Constants.VOCABULARY_ValidVocabularyId) { TermId = Constants.TERM_DeleteTermId }; - //Act + // Act termController.DeleteTerm(term); - //Assert - mockCache.Verify(cache => cache.Remove(String.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - - #endregion - - #region GetTerm - + // Assert + this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); + } + [Test] public void TermController_GetTerm_Throws_On_Negative_TermId() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.GetTerm(Null.NullInteger)); } [Test] public void TermController_GetTerm_Returns_Null_On_InValidTermId() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_InValidTermId)).Returns(MockHelper.CreateEmptyTermReader()); var termController = new TermController(mockDataService.Object); - //Act + // Act Term term = termController.GetTerm(Constants.TERM_InValidTermId); - //Assert + // Assert Assert.IsNull(term); } [Test] public void TermController_GetTerm_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_ValidTermId)).Returns(MockHelper.CreateValidTermReader()); var termController = new TermController(mockDataService.Object); - //Act + // Act Term term = termController.GetTerm(Constants.TERM_ValidTermId); - //Assert + // Assert mockDataService.Verify(ds => ds.GetTerm(Constants.TERM_ValidTermId)); } [Test] public void TermController_GetTerm_Returns_Term_On_Valid_TermId() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetTerm(Constants.TERM_ValidTermId)).Returns(MockHelper.CreateValidTermReader()); var termController = new TermController(mockDataService.Object); - //Act + // Act var term = termController.GetTerm(Constants.TERM_ValidTermId); - //Assert + // Assert Assert.AreEqual(Constants.TERM_ValidTermId, term.TermId); Assert.AreEqual(Constants.TERM_ValidName, term.Name); - } - - #endregion - - #region GetTermsByContent - + } + [Test] public void TermController_GetTermsByContent_Throws_On_Invalid_ContentItemId() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.GetTermsByContent(Null.NullInteger)); } [Test] public void TermController_GetTermsByContent_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader(Constants.TERM_ValidCountForContent1, - v => Constants.TERM_ValidVocabularyId, - c => Constants.TERM_ValidContent1)); + mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( + Constants.TERM_ValidCountForContent1, + v => Constants.TERM_ValidVocabularyId, + c => Constants.TERM_ValidContent1)); var termController = new TermController(mockDataService.Object); - //Act + // Act IQueryable terms = termController.GetTermsByContent(Constants.TERM_ValidContent1); - //Assert + // Assert mockDataService.Verify(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)); } [Test] public void TermController_GetTermsByContent_Returns_Terms_On_Valid_ContentItemId() { - //Arrange + // Arrange var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader(Constants.TERM_ValidCountForContent1, - v => Constants.TERM_ValidVocabularyId, - c => Constants.TERM_ValidContent1)); + mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( + Constants.TERM_ValidCountForContent1, + v => Constants.TERM_ValidVocabularyId, + c => Constants.TERM_ValidContent1)); var termController = new TermController(mockDataService.Object); - //Act + // Act var terms = termController.GetTermsByContent(Constants.TERM_ValidContent1).ToList(); - //Assert + // Assert Assert.AreEqual(Constants.TERM_ValidCountForContent1, terms.Count); for (int i = 0; i < Constants.TERM_ValidCountForContent1; i++) @@ -447,40 +426,37 @@ public void TermController_GetTermsByContent_Returns_Terms_On_Valid_ContentItemI Assert.AreEqual(i + Constants.TERM_ValidTermId, terms[i].TermId); Assert.AreEqual(ContentTestHelper.GetTermName(i + Constants.TERM_ValidTermId), terms[i].Name); } - } - - #endregion - - #region GetTermsByVocabulary - + } + [Test] public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyId() { - //Arrange + // Arrange var mockDataService = new Mock(); - MockComponentProvider.CreateDataProvider().Setup(c=>c.GetProviderPath()).Returns(String.Empty); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.GetTermsByVocabulary(Null.NullInteger)); } [Test] public void TermController_GetTermsByVocabulary_Returns_Terms_On_Valid_VocabularyId() { - //Arrange + // Arrange var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1)).Returns(MockHelper.CreateValidTermsReader(Constants.TERM_ValidCountForVocabulary1, - v => Constants.TERM_ValidVocabulary1, - c => Constants.TERM_ValidContent1)); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(String.Empty); + mockDataService.Setup(ds => ds.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1)).Returns(MockHelper.CreateValidTermsReader( + Constants.TERM_ValidCountForVocabulary1, + v => Constants.TERM_ValidVocabulary1, + c => Constants.TERM_ValidContent1)); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); var termController = new TermController(mockDataService.Object); - //Act + // Act var terms = termController.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1).ToList(); - //Assert + // Assert Assert.AreEqual(Constants.TERM_ValidCountForVocabulary1, terms.Count); for (int i = 0; i < Constants.TERM_ValidCountForVocabulary1; i++) @@ -493,33 +469,29 @@ public void TermController_GetTermsByVocabulary_Returns_Terms_On_Valid_Vocabular [Test] public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyName() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.GetTermsByVocabulary(Null.NullString)); - } - - #endregion - - #region RemoveTermsFromContent - + } + [Test] public void TermController_RemoveTermsFromContent_Throws_On_Null_ContentItem() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.RemoveTermsFromContent(null)); } [Test] public void TermController_RemoveTermsFromContent_Should_Call_DataService_If_Valid_Params() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -530,67 +502,63 @@ public void TermController_RemoveTermsFromContent_Should_Call_DataService_If_Val // Assert mockDataService.Verify(ds => ds.RemoveTermsFromContent(content)); - } - - #endregion - - #region UpdateTerm - + } + [Test] public void TermController_UpdateTerm_Throws_On_Null_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.UpdateTerm(null)); } [Test] public void TermController_UpdateTerm_Throws_On_Negative_TermId() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.UpdateTerm(term)); } [Test] public void TermController_UpdateTerm_Throws_On_Invalid_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); Term term = ContentTestHelper.CreateValidSimpleTerm(Constants.VOCABULARY_ValidVocabularyId); term.Name = Constants.TERM_InValidName; - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.UpdateTerm(term)); } [Test] public void TermController_UpdateTerm_Throws_On_Negative_VocabularyId() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); Term term = ContentTestHelper.CreateValidSimpleTerm(Null.NullInteger); - //Act, Arrange + // Act, Arrange Assert.Throws(() => termController.UpdateTerm(term)); } [Test] public void TermController_UpdateTerm_Should_Call_DataService_UpdateSimpleTerm_If_Term_Is_Simple_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -609,7 +577,7 @@ public void TermController_UpdateTerm_Should_Call_DataService_UpdateSimpleTerm_I [Test] public void TermController_UpdateTerm_Should_Call_DataService_UpdateHeirarchicalTerm_If_Term_Is_Heirarchical_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -628,7 +596,7 @@ public void TermController_UpdateTerm_Should_Call_DataService_UpdateHeirarchical [Test] public void TermController_UpdateTerm_Clears_Term_Cache_On_Valid_Term() { - //Arrange + // Arrange var mockDataService = new Mock(); var termController = new TermController(mockDataService.Object); @@ -637,13 +605,11 @@ public void TermController_UpdateTerm_Clears_Term_Cache_On_Valid_Term() term.Name = Constants.TERM_UpdateName; term.Weight = Constants.TERM_UpdateWeight; - //Act + // Act termController.UpdateTerm(term); - //Assert - mockCache.Verify(cache => cache.Remove(String.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - - #endregion + // Assert + this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs index 2cb49ca167a..aa595198f06 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs @@ -1,345 +1,323 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content.Data; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Content.Mocks; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Content { + using System; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Data; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Content.Mocks; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Summary description for VocabularyTests + /// Summary description for VocabularyTests. /// [TestFixture] public class VocabularyControllerTests { - private Mock mockCache; - - #region Test Initialize - + private Mock mockCache; + [SetUp] public void SetUp() { - //Register MockCachingProvider - mockCache = MockComponentProvider.CreateNew(); - MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(String.Empty); + // Register MockCachingProvider + this.mockCache = MockComponentProvider.CreateNew(); + MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddVocabulary - + } + [Test] public void VocabularyController_AddVocabulary_Throws_On_Null_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.AddVocabulary(null)); } [Test] public void VocabularyController_AddVocabulary_Throws_On_Invalid_Name() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.Name = Constants.VOCABULARY_InValidName; - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.AddVocabulary(vocabulary)); } [Test] public void VocabularyController_AddVocabulary_Throws_On_Negative_ScopeTypeID() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.ScopeTypeId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.AddVocabulary(vocabulary)); } [Test] public void VocabularyController_AddVocabulary_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - //Act + // Act int vocabularyId = vocabularyController.AddVocabulary(vocabulary); - //Assert + // Assert mockDataService.Verify(ds => ds.AddVocabulary(vocabulary, It.IsAny())); } [Test] public void VocabularyController_AddVocabulary_Returns_ValidId_On_Valid_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddVocabulary(It.IsAny(), It.IsAny())).Returns(Constants.VOCABULARY_AddVocabularyId); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - //Act + // Act int vocabularyId = vocabularyController.AddVocabulary(vocabulary); - //Assert + // Assert Assert.AreEqual(Constants.VOCABULARY_AddVocabularyId, vocabularyId); } [Test] public void VocabularyController_AddVocabulary_Sets_ValidId_On_Valid_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddVocabulary(It.IsAny(), It.IsAny())).Returns(Constants.VOCABULARY_AddVocabularyId); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - //Act + // Act vocabularyController.AddVocabulary(vocabulary); - //Assert + // Assert Assert.AreEqual(Constants.VOCABULARY_AddVocabularyId, vocabulary.VocabularyId); } [Test] public void VocabularyController_AddVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); - //Act + // Act vocabularyController.AddVocabulary(vocabulary); - //Assert - mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - - #endregion - - #region DeleteVocabulary - + // Assert + this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); + } + [Test] public void VocabularyController_DeleteVocabulary_Throws_On_Null_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.DeleteVocabulary(null)); } [Test] public void VocabularyController_DeleteVocabulary_Throws_On_Negative_VocabularyId() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = new Vocabulary(); vocabulary.VocabularyId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.DeleteVocabulary(vocabulary)); } [Test] public void VocabularyController_DeleteVocabulary_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.VocabularyId = Constants.VOCABULARY_ValidVocabularyId; - //Act + // Act vocabularyController.DeleteVocabulary(vocabulary); - //Assert + // Assert mockDataService.Verify(ds => ds.DeleteVocabulary(vocabulary)); } [Test] public void VocabularyController_DeleteVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.VocabularyId = Constants.VOCABULARY_ValidVocabularyId; - //Act + // Act vocabularyController.DeleteVocabulary(vocabulary); - //Assert - mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - - #endregion - - #region GetVocabularies - + // Assert + this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); + } + [Test] public void VocabularyController_GetVocabularies_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetVocabularies()).Returns(MockHelper.CreateValidVocabulariesReader(Constants.VOCABULARY_ValidCount)); var vocabularyController = new VocabularyController(mockDataService.Object); - //Act + // Act IQueryable vocabularys = vocabularyController.GetVocabularies(); - //Assert + // Assert mockDataService.Verify(ds => ds.GetVocabularies()); } [Test] public void VocabularyController_GetVocabularies_Returns_List_Of_Vocabularies() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetVocabularies()).Returns(MockHelper.CreateValidVocabulariesReader(Constants.VOCABULARY_ValidCount)); var vocabularyController = new VocabularyController(mockDataService.Object); - //Act + // Act IQueryable vocabularys = vocabularyController.GetVocabularies(); - //Assert + // Assert Assert.AreEqual(Constants.VOCABULARY_ValidCount, vocabularys.Count()); - } - - #endregion - - #region UpdateVocabulary - + } + [Test] public void VocabularyController_UpdateVocabulary_Throws_On_Null_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.UpdateVocabulary(null)); } [Test] public void VocabularyController_UpdateVocabulary_Throws_On_Negative_VocabularyId() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.VocabularyId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); } [Test] public void VocabularyController_UpdateVocabulary_Throws_On_Invalid_Name() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.Name = Constants.VOCABULARY_InValidName; - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); } [Test] public void VocabularyController_UpdateVocabulary_Throws_On_Negative_ScopeTypeID() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.ScopeTypeId = Null.NullInteger; - //Act, Arrange + // Act, Arrange Assert.Throws(() => vocabularyController.UpdateVocabulary(vocabulary)); } [Test] public void VocabularyController_UpdateVocabulary_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.VocabularyId = Constants.VOCABULARY_UpdateVocabularyId; - //Act + // Act vocabularyController.UpdateVocabulary(vocabulary); - //Assert + // Assert mockDataService.Verify(ds => ds.UpdateVocabulary(vocabulary, It.IsAny())); } [Test] public void VocabularyController__UpdateVocabulary_Clears_Vocabulary_Cache_On_Valid_Vocabulary() { - //Arrange + // Arrange var mockDataService = new Mock(); var vocabularyController = new VocabularyController(mockDataService.Object); Vocabulary vocabulary = ContentTestHelper.CreateValidVocabulary(); vocabulary.VocabularyId = Constants.VOCABULARY_UpdateVocabularyId; - //Act + // Act vocabularyController.UpdateVocabulary(vocabulary); - //Assert - mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - - #endregion + // Assert + this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config b/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config index 9a323d5bf20..d3f880af864 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config @@ -1,27 +1,27 @@ - - - - -
        - - - - - - - - - - - - - - - - - - - - - + + + + +
        + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Content/packages.config index 7641c2a4248..4506cb7ef82 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/packages.config @@ -1,7 +1,8 @@ - - - - - - + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/AssemblyInfo.cs index da871f5d3ed..2b92bc77fad 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/AssemblyInfo.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Library.Tests")] [assembly: AssemblyDescription("Open Source Web Application Framework - Test Project")] @@ -16,27 +15,23 @@ [assembly: AssemblyProduct("https://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2018 by DotNetNuke Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DotNetNuke")] - - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM componenets. If you need to access a type in this assembly from + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. 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("87fa9a95-fc7c-43d9-b548-a43988fcd5c1")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Revision and Build Numbers +// You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: - [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs index 93887f3b345..5336aa828fc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs @@ -1,21 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.Text; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Tests.Utilities.Mocks; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Caching { + using System; + using System.Data; + using System.Text; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Tests.Utilities.Mocks; + using NUnit.Framework; + /// - /// Summary description for DataCacheTests + /// Summary description for DataCacheTests. /// [TestFixture] public class CBOTest @@ -23,40 +22,36 @@ public class CBOTest [SetUp] public void SetUp() { - //Create a Container + // Create a Container ComponentFactory.Container = new SimpleContainer(); MockComponentProvider.CreateDataCacheProvider(); } - - + [Test] public void CBO_FillObject_int() { var cboTable = new DataTable("CBOTable"); var colValue = 12; - cboTable.Columns.Add("IntProp", typeof (int)); + cboTable.Columns.Add("IntProp", typeof(int)); cboTable.Rows.Add(colValue); - //Assert.AreEqual(12, moq.Object["TestColumn"]); - + // Assert.AreEqual(12, moq.Object["TestColumn"]); var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); Assert.IsNotNull(result); Assert.AreEqual(colValue, result.IntProp); } - - + [Test] public void CBO_FillObject_string() { var cboTable = new DataTable("CBOTable"); var colValue = Guid.NewGuid().ToString(); - cboTable.Columns.Add("StringProp", typeof (String)); + cboTable.Columns.Add("StringProp", typeof(string)); cboTable.Rows.Add(colValue); - //Assert.AreEqual(12, moq.Object["TestColumn"]); - + // Assert.AreEqual(12, moq.Object["TestColumn"]); var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -70,11 +65,10 @@ public void CBO_FillObject_datetime() var cboTable = new DataTable("CBOTable"); var colValue = new DateTime(2010, 12, 11, 10, 9, 8); - cboTable.Columns.Add("DateTimeProp", typeof (DateTime)); + cboTable.Columns.Add("DateTimeProp", typeof(DateTime)); cboTable.Rows.Add(colValue); - //Assert.AreEqual(12, moq.Object["TestColumn"]); - + // Assert.AreEqual(12, moq.Object["TestColumn"]); var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -83,16 +77,16 @@ public void CBO_FillObject_datetime() } [Test] - //DNNPRO-13404 - Object does not implement IConvertible + + // DNNPRO-13404 - Object does not implement IConvertible public void CBO_FillObject_binary() { var cboTable = new DataTable("CBOTable"); var colValue = Encoding.ASCII.GetBytes("Hello This is test"); - cboTable.Columns.Add("ByteArrayProp", typeof (byte[])); + cboTable.Columns.Add("ByteArrayProp", typeof(byte[])); cboTable.Rows.Add(colValue); - - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -106,10 +100,9 @@ public void CBO_FillObject_binary_to_Array() var cboTable = new DataTable("CBOTable"); var colValue = Encoding.ASCII.GetBytes("Hello This is test"); - cboTable.Columns.Add("ArrayProp", typeof (byte[])); + cboTable.Columns.Add("ArrayProp", typeof(byte[])); cboTable.Rows.Add(colValue); - - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -123,10 +116,9 @@ public void CBO_FillObject_bit() var cboTable = new DataTable("CBOTable"); var colValue = true; - cboTable.Columns.Add("BitProp", typeof (Boolean)); + cboTable.Columns.Add("BitProp", typeof(bool)); cboTable.Rows.Add(colValue); - - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -140,10 +132,9 @@ public void CBO_FillObject_decimal() var cboTable = new DataTable("CBOTable"); decimal colValue = 12.99m; - cboTable.Columns.Add("DecimalProp", typeof (decimal)); + cboTable.Columns.Add("DecimalProp", typeof(decimal)); cboTable.Rows.Add(colValue); - - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -157,10 +148,9 @@ public void CBO_FillObject_int_to_boolean_true() var cboTable = new DataTable("CBOTable"); decimal colValue = 1; - cboTable.Columns.Add("BitProp", typeof (int)); + cboTable.Columns.Add("BitProp", typeof(int)); cboTable.Rows.Add(colValue); - - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -174,10 +164,9 @@ public void CBO_FillObject_int_to_boolean_false() var cboTable = new DataTable("CBOTable"); decimal colValue = 0; - cboTable.Columns.Add("BitProp", typeof (int)); + cboTable.Columns.Add("BitProp", typeof(int)); cboTable.Rows.Add(colValue); - - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -189,11 +178,17 @@ public void CBO_FillObject_int_to_boolean_false() public class IntPoco { public int IntProp { get; set; } + public string StringProp { get; set; } + public DateTime DateTimeProp { get; set; } - public Byte[] ByteArrayProp { get; set; } + + public byte[] ByteArrayProp { get; set; } + public Array ArrayProp { get; set; } - public Boolean BitProp { get; set; } + + public bool BitProp { get; set; } + public decimal DecimalProp { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/CollectionExtensionTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/CollectionExtensionTests.cs index 0f2ddc31fc6..e5469f1fb4d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/CollectionExtensionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/CollectionExtensionTests.cs @@ -1,22 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.Web.UI; -using System.Xml; -using System.Xml.Linq; - -using DotNetNuke.Collections; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.Web.UI; + using System.Xml; + using System.Xml.Linq; + + using DotNetNuke.Collections; + using NUnit.Framework; + [TestFixture] public class CollectionExtensionTests : AssertionHelper { @@ -27,7 +26,7 @@ public void get_null_string_from_hashtable_for_missing_value() var value = table.GetValueOrDefault("cat id"); - Expect(value, Is.Null); + this.Expect(value, Is.Null); } [Test] @@ -37,7 +36,7 @@ public void can_get_string_from_hashtable() var value = table.GetValueOrDefault("app id"); - Expect(value, Is.EqualTo("abc123")); + this.Expect(value, Is.EqualTo("abc123")); } [Test] @@ -47,7 +46,7 @@ public void get_string_from_hashtable_when_default_is_provided() var value = table.GetValueOrDefault("app id", "abracadabra"); - Expect(value, Is.EqualTo("abc123")); + this.Expect(value, Is.EqualTo("abc123")); } [Test] @@ -57,7 +56,7 @@ public void can_get_default_string_from_hashtable() var value = table.GetValueOrDefault("cat id", "Frank"); - Expect(value, Is.EqualTo("Frank")); + this.Expect(value, Is.EqualTo("Frank")); } [Test] @@ -67,7 +66,7 @@ public void can_get_bool_from_hashtable() var value = table.GetValueOrDefault("app id"); - Expect(value, Is.True); + this.Expect(value, Is.True); } [Test] @@ -77,7 +76,7 @@ public void get_bool_from_hashtable_when_default_is_provided() var value = table.GetValueOrDefault("app id", false); - Expect(value, Is.True); + this.Expect(value, Is.True); } [Test] @@ -88,7 +87,7 @@ public void can_get_default_bool_from_hashtable() value = table.GetValueOrDefault("Allow Windows Live Writer", value); - Expect(value, Is.True); + this.Expect(value, Is.True); } [Test] @@ -98,7 +97,7 @@ public void get_false_from_hashtable_for_missing_value() var value = table.GetValueOrDefault("Allow Windows Live Writer"); - Expect(value, Is.False); + this.Expect(value, Is.False); } [Test] @@ -119,7 +118,7 @@ public void get_bool_with_custom_converter_from_hashtable() return allowed; }); - Expect(value, Is.True); + this.Expect(value, Is.True); } [Test] @@ -129,7 +128,7 @@ public void get_int() var value = collection.GetValueOrDefault("appId"); - Expect(value, Is.EqualTo(123)); + this.Expect(value, Is.EqualTo(123)); } [Test] @@ -139,7 +138,7 @@ public void get_decimal() var value = collection.GetValueOrDefault("appId"); - Expect(value, Is.EqualTo(1.23m)); + this.Expect(value, Is.EqualTo(1.23m)); } [Test] @@ -150,7 +149,7 @@ public void get_decimal_from_other_culture() var value = collection.GetValueOrDefault("appId"); - Expect(value, Is.EqualTo(1.23m)); + this.Expect(value, Is.EqualTo(1.23m)); } [Test] @@ -160,7 +159,7 @@ public void get_datetime() var value = collection.GetValueOrDefault("startDate"); - Expect(value, Is.EqualTo(new DateTime(2012, 5, 4))); + this.Expect(value, Is.EqualTo(new DateTime(2012, 5, 4))); } [Test] @@ -170,7 +169,7 @@ public void get_null_string_without_default() var value = collection.GetValue("app id"); - Expect(value, Is.Null); + this.Expect(value, Is.Null); } [Test] @@ -180,7 +179,7 @@ public void get_null_string_with_default() var value = collection.GetValueOrDefault("app id", "a default value"); - Expect(value, Is.Null); + this.Expect(value, Is.Null); } [Test] @@ -190,7 +189,7 @@ public void get_nullable_datetime() var value = collection.GetValue("startDate"); - Expect(value, Is.Null); + this.Expect(value, Is.Null); } [Test] @@ -201,7 +200,7 @@ public void get_datetime_from_other_culture() var value = collection.GetValueOrDefault("startDate"); - Expect(value, Is.EqualTo(new DateTime(2012, 5, 4))); + this.Expect(value, Is.EqualTo(new DateTime(2012, 5, 4))); } [Test] @@ -211,7 +210,7 @@ public void get_from_statebag() var value = collection.GetValueOrDefault("appId"); - Expect(value, Is.EqualTo("123")); + this.Expect(value, Is.EqualTo("123")); } [Test] @@ -223,7 +222,7 @@ public void get_from_xnode() var value = node.GetValueOrDefault("id"); - Expect(value, Is.EqualTo(14)); + this.Expect(value, Is.EqualTo(14)); } [Test] @@ -237,7 +236,7 @@ public void get_from_xmlnode() var value = doc.DocumentElement.GetValueOrDefault("id"); - Expect(value, Is.EqualTo(13)); + this.Expect(value, Is.EqualTo(13)); } [Test] @@ -247,7 +246,7 @@ public void can_get_timespan_with_custom_converter() var value = collection.GetValueOrDefault("length", TimeSpan.Parse); - Expect(value, Is.EqualTo(TimeSpan.FromSeconds(4210))); + this.Expect(value, Is.EqualTo(TimeSpan.FromSeconds(4210))); } [Test] @@ -257,7 +256,7 @@ public void can_get_empty_boolean_from_form() var value = collection.GetValueOrDefault("radio", CollectionExtensions.GetFlexibleBooleanParsingFunction()); - Expect(value, Is.False); + this.Expect(value, Is.False); } [Test] @@ -267,7 +266,7 @@ public void can_get_boolean_from_form() var value = collection.GetValueOrDefault("radio", CollectionExtensions.GetFlexibleBooleanParsingFunction()); - Expect(value, Is.True); + this.Expect(value, Is.True); } [Test] @@ -277,7 +276,7 @@ public void flexible_boolean_parsing_is_case_insensitive() var value = collection.GetValueOrDefault("question", CollectionExtensions.GetFlexibleBooleanParsingFunction("yes")); - Expect(value, Is.True); + this.Expect(value, Is.True); } [Test] @@ -287,7 +286,7 @@ public void can_convert_namevaluecollection_to_lookup() var lookup = collection.ToLookup(); - Expect(lookup["question"], Is.EquivalentTo(new[] { "YES" })); + this.Expect(lookup["question"], Is.EquivalentTo(new[] { "YES" })); } [Test] @@ -297,7 +296,7 @@ public void can_convert_namevaluecollection_with_multiple_values_to_lookup() var lookup = collection.ToLookup(); - Expect(lookup["question"], Is.EquivalentTo(new[] { "A", "B", "C", })); + this.Expect(lookup["question"], Is.EquivalentTo(new[] { "A", "B", "C", })); } [Test] @@ -307,7 +306,7 @@ public void can_get_null_value_rather_than_default() var value = dictionary.GetValueOrDefault("question", "yes"); - Expect(value, Is.Null); + this.Expect(value, Is.Null); } [Test] @@ -317,7 +316,7 @@ public void can_get_empty_string_rather_than_default() var value = dictionary.GetValueOrDefault("question", "yes"); - Expect(value, Is.Empty); + this.Expect(value, Is.Empty); } [Test] @@ -327,7 +326,7 @@ public void can_get_value_without_default() var value = dictionary.GetValue("question"); - Expect(value, Is.EqualTo("what is it")); + this.Expect(value, Is.EqualTo("what is it")); } [Test] @@ -337,7 +336,7 @@ public void can_get_value_without_default_with_custom_converter() var value = dictionary.GetValue("question", (object v) => v is string ? 10 : 20); - Expect(value, Is.EqualTo(10)); + this.Expect(value, Is.EqualTo(10)); } [Test] @@ -347,7 +346,7 @@ public void can_get_value_without_default_from_namevaluecollection() var value = collection.GetValue("question"); - Expect(value, Is.EqualTo("what is it")); + this.Expect(value, Is.EqualTo("what is it")); } [Test] @@ -357,7 +356,7 @@ public void can_get_value_containing_comma_from_namevaluecollection() var value = collection.GetValue("question"); - Expect(value, Is.EqualTo("what, is it?")); + this.Expect(value, Is.EqualTo("what, is it?")); } [Test] @@ -367,7 +366,7 @@ public void can_get_multiple_values_from_namevaluecollection() var value = collection.GetValues("state"); - Expect(value, Is.EquivalentTo(new[] { "CA", "BC", })); + this.Expect(value, Is.EquivalentTo(new[] { "CA", "BC", })); } [Test] @@ -377,7 +376,7 @@ public void can_get_sequence_with_single_value_from_namevaluecollection() var value = collection.GetValues("state"); - Expect(value, Is.EquivalentTo(new[] { "CA" })); + this.Expect(value, Is.EquivalentTo(new[] { "CA" })); } [Test] @@ -387,7 +386,7 @@ public void can_get_sequence_with_no_value_from_namevaluecollection() var value = collection.GetValues("cat"); - Expect(value, Is.Empty); + this.Expect(value, Is.Empty); } [Test] @@ -397,7 +396,7 @@ public void can_get_multiple_values_from_namevaluecollection_with_custom_convert var value = collection.GetValues("state", v => int.Parse(v, CultureInfo.InvariantCulture) + 10); - Expect(value, Is.EquivalentTo(new[] { 22, 11 })); + this.Expect(value, Is.EquivalentTo(new[] { 22, 11 })); } [Test] @@ -407,7 +406,7 @@ public void can_get_value_without_default_from_statebag() var value = dictionary.GetValue("question"); - Expect(value, Is.EqualTo("what is it")); + this.Expect(value, Is.EqualTo("what is it")); } [Test] @@ -419,7 +418,7 @@ public void can_get_value_without_default_from_xnode() var value = node.GetValue("id"); - Expect(value, Is.EqualTo(21)); + this.Expect(value, Is.EqualTo(21)); } [Test] @@ -433,7 +432,7 @@ public void can_get_value_without_default_from_xmlnode() var value = doc.DocumentElement.GetValue("id"); - Expect(value, Is.EqualTo(123)); + this.Expect(value, Is.EqualTo(123)); } [Test] @@ -441,7 +440,7 @@ public void getvalue_throws_argumentexception_when_value_is_not_present() { var dictionary = new Hashtable { { "question", "what is it" } }; - Expect(() => dictionary.GetValue("answer"), Throws.ArgumentException.With.Property("ParamName").EqualTo("key")); + this.Expect(() => dictionary.GetValue("answer"), Throws.ArgumentException.With.Property("ParamName").EqualTo("key")); } [Test] @@ -449,7 +448,7 @@ public void throws_invalidoperationexception_when_lookup_has_multiple_values() { var collection = new NameValueCollection { { "state", "CA" }, { "state", "BC" } }; - Expect(() => collection.GetValueOrDefault("state"), Throws.InvalidOperationException); + this.Expect(() => collection.GetValueOrDefault("state"), Throws.InvalidOperationException); } [Test] @@ -457,7 +456,7 @@ public void throws_argumentnullexception_when_dictionary_is_null() { IDictionary dictionary = null; - Expect(() => dictionary.GetValueOrDefault("value ID"), Throws.TypeOf().With.Property("ParamName").EqualTo("dictionary")); + this.Expect(() => dictionary.GetValueOrDefault("value ID"), Throws.TypeOf().With.Property("ParamName").EqualTo("dictionary")); } [Test] @@ -465,7 +464,7 @@ public void throws_argumentnullexception_when_xelement_is_null() { XElement node = null; - Expect(() => node.GetValueOrDefault("value ID"), Throws.TypeOf().With.Property("ParamName").EqualTo("node")); + this.Expect(() => node.GetValueOrDefault("value ID"), Throws.TypeOf().With.Property("ParamName").EqualTo("node")); } [Test] @@ -473,7 +472,7 @@ public void throws_argumentnullexception_when_xmlnode_is_null() { XmlNode node = null; - Expect(() => node.GetValueOrDefault("value ID"), Throws.TypeOf().With.Property("ParamName").EqualTo("node")); + this.Expect(() => node.GetValueOrDefault("value ID"), Throws.TypeOf().With.Property("ParamName").EqualTo("node")); } [Test] @@ -483,7 +482,7 @@ public void does_not_throw_invalidcastexception_when_value_is_null_for_reference var value = dictionary.GetValueOrDefault("length"); - Expect(value, Is.Null); + this.Expect(value, Is.Null); } [Test] @@ -491,7 +490,7 @@ public void tolookup_throws_argumentnullexception_when_namevaluecollection_is_nu { NameValueCollection col = null; - Expect(() => col.ToLookup(), Throws.TypeOf().With.Property("ParamName").EqualTo("collection")); + this.Expect(() => col.ToLookup(), Throws.TypeOf().With.Property("ParamName").EqualTo("collection")); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedDictionaryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedDictionaryTests.cs index 4c95404c370..7cca65f3653 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedDictionaryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedDictionaryTests.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class ExclusiveLockSharedDictionaryTests : SharedDictionaryTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedListTests.cs index e1795d64f97..d4ed7545825 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockSharedListTests.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class ExclusiveLockSharedListTests : SharedListTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockStrategyTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockStrategyTests.cs index 60adaab37c4..4c96a9cdebf 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockStrategyTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ExclusiveLockStrategyTests.cs @@ -1,16 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections.Generic; + + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class ExclusiveLockStrategyTests : LockStrategyTests { @@ -21,11 +20,11 @@ internal override ILockStrategy GetLockStrategy() protected override IEnumerable> GetObjectDisposedExceptionMethods() { - var l = (List>) base.GetObjectDisposedExceptionMethods(); + var l = (List>)base.GetObjectDisposedExceptionMethods(); l.Add((ILockStrategy strategy) => { - ExclusiveLockStrategy els = (ExclusiveLockStrategy) strategy; + ExclusiveLockStrategy els = (ExclusiveLockStrategy)strategy; els.Exit(); }); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs index b975e2a15b4..b0797887759 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs @@ -1,71 +1,74 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Threading; - -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections.Generic; + using System.Threading; + + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + public abstract class LockStrategyTests { - internal abstract ILockStrategy GetLockStrategy(); - [Test] public void DoubleDisposeAllowed() { - var strategy = GetLockStrategy(); + var strategy = this.GetLockStrategy(); strategy.Dispose(); strategy.Dispose(); - //no exception on 2nd dispose + + // no exception on 2nd dispose } - [Test, ExpectedException(typeof (LockRecursionException))] + [Test] + [ExpectedException(typeof(LockRecursionException))] public virtual void DoubleReadLockThrows() { - using (var strategy = GetLockStrategy()) + using (var strategy = this.GetLockStrategy()) { using (var readLock1 = strategy.GetReadLock()) { using (var readLock2 = strategy.GetReadLock()) { - //do nothing + // do nothing } } } } + + internal abstract ILockStrategy GetLockStrategy(); - [Test, ExpectedException(typeof (LockRecursionException))] + [Test] + [ExpectedException(typeof(LockRecursionException))] public void ReadAndWriteLockOnSameThreadThrows() { - using (var strategy = GetLockStrategy()) + using (var strategy = this.GetLockStrategy()) { using (var readLock1 = strategy.GetReadLock()) { using (var readLock2 = strategy.GetWriteLock()) { - //do nothing + // do nothing } } } } - [Test, ExpectedException(typeof (LockRecursionException))] + [Test] + [ExpectedException(typeof(LockRecursionException))] public void WriteAndReadLockOnSameThreadThrows() { - using (var strategy = GetLockStrategy()) + using (var strategy = this.GetLockStrategy()) { using (var readLock1 = strategy.GetWriteLock()) { using (var readLock2 = strategy.GetReadLock()) { - //do nothing + // do nothing } } } @@ -74,7 +77,7 @@ public void WriteAndReadLockOnSameThreadThrows() [Test] public void DoubleReadLockOnDifferentThreads() { - using (var strategy = GetLockStrategy()) + using (var strategy = this.GetLockStrategy()) { if (strategy.SupportsConcurrentReads) { @@ -83,10 +86,10 @@ public void DoubleReadLockOnDifferentThreads() var t = new Thread(GetReadLock); t.Start(strategy); - //sleep and let new thread run + // sleep and let new thread run t.Join(TimeSpan.FromMilliseconds(100)); - //assert that read thread has terminated + // assert that read thread has terminated Console.WriteLine(t.ThreadState.ToString()); Assert.IsTrue(t.ThreadState == ThreadState.Stopped); } @@ -97,7 +100,7 @@ public void DoubleReadLockOnDifferentThreads() [Test] public void DoubleWriteLockOnDifferentThreadsWaits() { - using (ILockStrategy strategy = GetLockStrategy()) + using (ILockStrategy strategy = this.GetLockStrategy()) { Thread t; using (var writeLock1 = strategy.GetWriteLock()) @@ -105,40 +108,42 @@ public void DoubleWriteLockOnDifferentThreadsWaits() t = new Thread(GetWriteLock); t.Start(strategy); - //sleep and let new thread run and block + // sleep and let new thread run and block Thread.Sleep(50); - //assert that write thread has not terminated + // assert that write thread has not terminated Assert.IsTrue(t.IsAlive); - } //release write lock + } // release write lock Thread.Sleep(50); - //assert that getwritelock did complete once first writelock was released it's call + // assert that getwritelock did complete once first writelock was released it's call Assert.IsFalse(t.IsAlive); } } - [Test, ExpectedException(typeof (LockRecursionException))] + [Test] + [ExpectedException(typeof(LockRecursionException))] public virtual void DoubleWriteLockThrows() { - using (ILockStrategy strategy = GetLockStrategy()) + using (ILockStrategy strategy = this.GetLockStrategy()) { using (var writeLock1 = strategy.GetWriteLock()) { using (var writeLock2 = strategy.GetWriteLock()) { - //do nothing + // do nothing } } } } - [Test, ExpectedException(typeof (ObjectDisposedException))] + [Test] + [ExpectedException(typeof(ObjectDisposedException))] [TestCaseSource("GetObjectDisposedExceptionMethods")] public void MethodsThrowAfterDisposed(Action methodCall) { - var strategy = GetLockStrategy(); + var strategy = this.GetLockStrategy(); strategy.Dispose(); methodCall.Invoke(strategy); @@ -149,26 +154,28 @@ public void ReadLockPreventsWriteLock() { Thread t = null; - using (var strategy = GetLockStrategy()) + using (var strategy = this.GetLockStrategy()) { using (var readLock = strategy.GetReadLock()) { t = new Thread(GetWriteLock); t.Start(strategy); - //sleep and let new thread run + // sleep and let new thread run Thread.Sleep(100); - //assert that write thread is still waiting + // assert that write thread is still waiting Assert.IsTrue(t.IsAlive); } - //release read lock + + // release read lock - //sleep and let write thread finish up + // sleep and let write thread finish up Thread.Sleep(100); Assert.IsFalse(t.IsAlive); } - //release controller + + // release controller } [Test] @@ -176,21 +183,22 @@ public void OnlyOneWriteLockAllowed() { Thread t = null; - using (var strategy = GetLockStrategy()) + using (var strategy = this.GetLockStrategy()) { using (var writeLock = strategy.GetWriteLock()) { t = new Thread(GetWriteLock); t.Start(strategy); - //sleep and let new thread run + // sleep and let new thread run Thread.Sleep(100); - //assert that write thread is still waiting + // assert that write thread is still waiting Assert.IsTrue(t.IsAlive); } - //release write lock - //sleep and let write thread finish up + + // release write lock + // sleep and let write thread finish up Thread.Sleep(100); Assert.IsFalse(t.IsAlive); } @@ -201,7 +209,7 @@ public void MultipleReadLocksAllowed() { Thread t = null; - using (var strategy = GetLockStrategy()) + using (var strategy = this.GetLockStrategy()) { if (strategy.SupportsConcurrentReads) { @@ -210,10 +218,10 @@ public void MultipleReadLocksAllowed() t = new Thread(GetReadLock); t.Start(strategy); - //sleep and let new thread run + // sleep and let new thread run Thread.Sleep(100); - //assert that read thread has terminated + // assert that read thread has terminated Assert.IsFalse(t.IsAlive); } } @@ -223,8 +231,7 @@ public void MultipleReadLocksAllowed() } } } - - + protected virtual IEnumerable> GetObjectDisposedExceptionMethods() { var l = new List>(); @@ -239,19 +246,19 @@ protected virtual IEnumerable> GetObjectDisposedExceptionM private static void GetReadLock(object obj) { - var strategy = (ILockStrategy) obj; + var strategy = (ILockStrategy)obj; using (var readLock = strategy.GetReadLock()) { - //do nothing + // do nothing } } private static void GetWriteLock(object obj) { - var strategy = (ILockStrategy) obj; + var strategy = (ILockStrategy)obj; using (var writeLock = strategy.GetWriteLock()) { - //do nothing + // do nothing } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs index ef12ac47c9b..f14d50771b4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs @@ -1,27 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading; - -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Threading; + + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class NaiveLockingListTests { - //Most of the tests here are very simple, as the real functionality is provided by List - //these tests only ensure that the methods are actually wired up - //Complicated threading tests would be nice, but are not practical as the - //NaiveLockList releases all locks immediately making it impossible to ensure - //a lock is held while launching another thread in the test - + // Most of the tests here are very simple, as the real functionality is provided by List + // these tests only ensure that the methods are actually wired up + // Complicated threading tests would be nice, but are not practical as the + // NaiveLockList releases all locks immediately making it impossible to ensure + // a lock is held while launching another thread in the test [Test] public void Add() { @@ -29,22 +27,22 @@ public void Add() list.Add("sumthin"); - CollectionAssert.AreEqual(new[] {"sumthin"}, list); + CollectionAssert.AreEqual(new[] { "sumthin" }, list); } [Test] public void Clear() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; list.Clear(); - CollectionAssert.AreEqual(new int[] {}, list); + CollectionAssert.AreEqual(new int[] { }, list); } [Test] public void Contains() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; Assert.IsTrue(list.Contains(2)); Assert.IsFalse(list.Contains(9999)); @@ -53,7 +51,7 @@ public void Contains() [Test] public void CopyTo() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; var dest = new int[4]; list.CopyTo(dest, 0); @@ -64,17 +62,17 @@ public void CopyTo() [Test] public void Remove() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; list.Remove(2); - CollectionAssert.AreEqual(new[] {0, 1, 3}, list); + CollectionAssert.AreEqual(new[] { 0, 1, 3 }, list); } [Test] public void Count() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; Assert.AreEqual(4, list.Count); } @@ -82,7 +80,7 @@ public void Count() [Test] public void IndexOf() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; Assert.AreEqual(2, list.IndexOf(2)); } @@ -90,37 +88,38 @@ public void IndexOf() [Test] public void Insert() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; list.Insert(2, 999); - CollectionAssert.AreEqual(new[] {0, 1, 999, 2, 3}, list); + CollectionAssert.AreEqual(new[] { 0, 1, 999, 2, 3 }, list); } [Test] public void RemoveAt() { - var list = new NaiveLockingList {0, 1, 999, 2, 3}; + var list = new NaiveLockingList { 0, 1, 999, 2, 3 }; list.RemoveAt(2); - CollectionAssert.AreEqual(new[] {0, 1, 2, 3}, list); + CollectionAssert.AreEqual(new[] { 0, 1, 2, 3 }, list); } [Test] public void IndexOperator() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; list[2] = 999; Assert.AreEqual(999, list[2]); } - [Test, ExpectedException(typeof (LockRecursionException))] + [Test] + [ExpectedException(typeof(LockRecursionException))] public void NoWritesWhileEnumerating() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; using (list.GetEnumerator()) { @@ -131,7 +130,7 @@ public void NoWritesWhileEnumerating() [Test] public void CanWriteAfterEnumerating() { - var list = new NaiveLockingList {0, 1, 2, 3}; + var list = new NaiveLockingList { 0, 1, 2, 3 }; using (IEnumerator e = list.GetEnumerator()) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs index 468691252ea..2f581fee789 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs @@ -1,35 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; - -using DotNetNuke.Collections; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections.Generic; + + using DotNetNuke.Collections; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class PageSelectorTests - { - #region Setup/Teardown - + { + private IEnumerable list; + [SetUp] public void SetUp() { - list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - } - - #endregion - - private IEnumerable list; + this.list = Util.CreateIntegerList(Constants.PAGE_TotalCount); + } [Test] [TestCase(0)] @@ -37,13 +27,13 @@ public void SetUp() [TestCase(Constants.PAGE_Last)] public void PageSelector_Returns_CorrectPage_When_Given_Valid_Index(int index) { - //Arrange - var selector = new PageSelector(list, Constants.PAGE_RecordCount); + // Arrange + var selector = new PageSelector(this.list, Constants.PAGE_RecordCount); - //Act + // Act IPagedList pagedList = selector.GetPage(index); - //Assert + // Assert Assert.AreEqual(index, pagedList.PageIndex); } @@ -52,13 +42,13 @@ public void PageSelector_Returns_CorrectPage_When_Given_Valid_Index(int index) [TestCase(8)] public void PageSelector_Returns_Correct_RecordCount_When_Given_Valid_Index(int pageSize) { - //Arrange - var selector = new PageSelector(list, pageSize); + // Arrange + var selector = new PageSelector(this.list, pageSize); - //Act + // Act IPagedList pagedList = selector.GetPage(Constants.PAGE_First); - //Assert + // Assert Assert.AreEqual(pageSize, pagedList.PageSize); } @@ -69,36 +59,36 @@ public void PageSelector_Returns_Correct_RecordCount_When_Given_Valid_Index(int [TestCase(4, 4)] public void PageSelector_Returns_Correct_Values_When_Given_Valid_Index_And_PageSize(int index, int pageSize) { - //Arrange - var selector = new PageSelector(list, pageSize); + // Arrange + var selector = new PageSelector(this.list, pageSize); - //Act + // Act IPagedList pagedList = selector.GetPage(index); - //Assert + // Assert for (int i = 0; i < pageSize; i++) { - Assert.AreEqual(index*pageSize + i, pagedList[i]); + Assert.AreEqual((index * pageSize) + i, pagedList[i]); } } [Test] public void PageSelector_Throws_When_Given_InValid_Index() { - //Arrange - var selector = new PageSelector(list, Constants.PAGE_RecordCount); + // Arrange + var selector = new PageSelector(this.list, Constants.PAGE_RecordCount); - //Assert + // Assert Assert.Throws(() => selector.GetPage(Constants.PAGE_OutOfRange)); } [Test] public void PageSelector_Throws_When_Given_Negative_Index() { - //Arrange - var selector = new PageSelector(list, Constants.PAGE_RecordCount); + // Arrange + var selector = new PageSelector(this.list, Constants.PAGE_RecordCount); - //Assert + // Assert Assert.Throws(() => selector.GetPage(Constants.PAGE_NegativeIndex)); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs index b3d28ea4a33..eb4105b6f8a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs @@ -1,22 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Collections; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Collections; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class PagedListTests { @@ -27,14 +21,14 @@ public class PagedListTests [TestCase(12, 2)] public void PagedList_Constructor_Succeeds_When_Given_Valid_Index(int totalCount, int pageIndex) { - //Arrange + // Arrange IQueryable list = Util.CreateIntegerList(totalCount).AsQueryable(); - //Act + // Act new PagedList(list, pageIndex, Constants.PAGE_RecordCount); - //Assert - //asserted by no exception :) + // Assert + // asserted by no exception :) } [Test] @@ -44,24 +38,23 @@ public void PagedList_Constructor_Succeeds_When_Given_Valid_Index(int totalCount [TestCase(12, 2)] public void PagedList_Constructor_Overload_Succeeds_When_Given_Valid_Index(int totalCount, int pageIndex) { - //Arrange + // Arrange IQueryable list = Util.CreateIntegerList(Constants.PAGE_RecordCount).AsQueryable(); - //Act + // Act new PagedList(list, totalCount, pageIndex, Constants.PAGE_RecordCount); - //Assert - //asserted by no exception :) + // Assert + // asserted by no exception :) } - - + [Test] [TestCase(0, 1)] [TestCase(5, 1)] [TestCase(7, 2)] public void PagedList_Constructor_Throws_When_Given_InValid_Index(int totalCount, int pageIndex) { - //Arrange + // Arrange IQueryable list = Util.CreateIntegerList(totalCount).AsQueryable(); Assert.Throws(() => new PagedList(list, pageIndex, Constants.PAGE_RecordCount)); @@ -73,7 +66,7 @@ public void PagedList_Constructor_Throws_When_Given_InValid_Index(int totalCount [TestCase(7, 2)] public void PagedList_Constructor_Overload_Throws_When_Given_InValid_Index(int totalCount, int pageIndex) { - //Arrange + // Arrange IQueryable list = Util.CreateIntegerList(Constants.PAGE_RecordCount).AsQueryable(); Assert.Throws(() => new PagedList(list, totalCount, pageIndex, Constants.PAGE_RecordCount)); @@ -85,7 +78,7 @@ public void PagedList_Constructor_Overload_Throws_When_Given_InValid_Index(int t [TestCase(7, 2)] public void PagedList_Constructor_Throws_When_Given_Invalid_PageSize(int totalCount, int pageIndex) { - //Arrange + // Arrange IQueryable list = Util.CreateIntegerList(totalCount).AsQueryable(); Assert.Throws(() => new PagedList(list, pageIndex, -1)); @@ -97,29 +90,29 @@ public void PagedList_Constructor_Throws_When_Given_Invalid_PageSize(int totalCo [TestCase(7, 2)] public void PagedList_Constructor_Overload_Throws_When_Given_Invalid_PageSize(int totalCount, int pageIndex) { - //Arrange + // Arrange IQueryable list = Util.CreateIntegerList(Constants.PAGE_RecordCount).AsQueryable(); Assert.Throws(() => new PagedList(list, totalCount, pageIndex, -1)); } - + [Test] public void PagedList_Constructor_Throws_When_Given_Negative_Index() { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act, Assert + // Act, Assert Assert.Throws(() => new PagedList(list, Constants.PAGE_NegativeIndex, Constants.PAGE_RecordCount)); } [Test] public void PagedList_Constructor_Overload_Throws_When_Given_Negative_Index() { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_RecordCount); - //Act, Assert + // Act, Assert Assert.Throws(() => new PagedList(list, Constants.PAGE_TotalCount, Constants.PAGE_NegativeIndex, Constants.PAGE_RecordCount)); } @@ -129,13 +122,13 @@ public void PagedList_Constructor_Overload_Throws_When_Given_Negative_Index() [TestCase(Constants.PAGE_Last, false)] public void PagedList_HasNextPage_Has_Correct_Value_When_Given_Valid_Index(int index, bool hasNext) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, Constants.PAGE_RecordCount); - //Assert + // Assert Assert.AreEqual(hasNext, pagedList.HasNextPage); } @@ -145,13 +138,13 @@ public void PagedList_HasNextPage_Has_Correct_Value_When_Given_Valid_Index(int i [TestCase(Constants.PAGE_Last, true)] public void PagedList_HasPreviousPage_Has_Correct_Value_When_Given_Valid_Index(int index, bool hasPrevious) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, Constants.PAGE_RecordCount); - //Assert + // Assert Assert.AreEqual(hasPrevious, pagedList.HasPreviousPage); } @@ -161,13 +154,13 @@ public void PagedList_HasPreviousPage_Has_Correct_Value_When_Given_Valid_Index(i [TestCase(Constants.PAGE_Last, false)] public void PagedList_IsFirstPage_Has_Correct_Value_When_Given_Valid_Index(int index, bool isFirst) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, Constants.PAGE_RecordCount); - //Assert + // Assert Assert.AreEqual(isFirst, pagedList.IsFirstPage); } @@ -177,13 +170,13 @@ public void PagedList_IsFirstPage_Has_Correct_Value_When_Given_Valid_Index(int i [TestCase(Constants.PAGE_Last, true)] public void PagedList_IsLastPage_Has_Correct_Value_When_Given_Valid_Index(int index, bool isLast) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, Constants.PAGE_RecordCount); - //Assert + // Assert Assert.AreEqual(isLast, pagedList.IsLastPage); } @@ -193,13 +186,13 @@ public void PagedList_IsLastPage_Has_Correct_Value_When_Given_Valid_Index(int in [TestCase(Constants.PAGE_Last)] public void PagedList_Returns_Correct_Page_When_Given_Valid_Index(int index) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, Constants.PAGE_RecordCount); - //Assert + // Assert Assert.AreEqual(index, pagedList.PageIndex); } @@ -208,13 +201,13 @@ public void PagedList_Returns_Correct_Page_When_Given_Valid_Index(int index) [TestCase(8)] public void PagedList_Returns_Correct_RecordCount_When_Given_Valid_Index(int pageSize) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, Constants.PAGE_First, pageSize); - //Assert + // Assert Assert.AreEqual(pageSize, pagedList.PageSize); } @@ -225,16 +218,16 @@ public void PagedList_Returns_Correct_RecordCount_When_Given_Valid_Index(int pag [TestCase(4, 4)] public void PagedList_Returns_Correct_Values_When_Given_Valid_Index_And_PageSize(int index, int pageSize) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, pageSize); - //Assert + // Assert for (int i = 0; i < pageSize; i++) { - Assert.AreEqual(index*pageSize + i, pagedList[i]); + Assert.AreEqual((index * pageSize) + i, pagedList[i]); } } @@ -245,13 +238,13 @@ public void PagedList_Returns_Correct_Values_When_Given_Valid_Index_And_PageSize [TestCase(1, 10, 3)] public void PagedList_Sets_Correct_PageCount(int index, int pageSize, int pageCount) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, pageSize); - //Assert + // Assert Assert.AreEqual(pageCount, pagedList.PageCount); } @@ -262,13 +255,13 @@ public void PagedList_Sets_Correct_PageCount(int index, int pageSize, int pageCo [TestCase(4, 4)] public void PagedList_Sets_TotalCount_To_Total_Number_Of_Items(int index, int pageSize) { - //Arrange + // Arrange List list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act var pagedList = new PagedList(list, index, pageSize); - //Assert + // Assert Assert.AreEqual(Constants.PAGE_TotalCount, pagedList.TotalCount); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagingExtensionsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagingExtensionsTests.cs index 692356a4a70..ef5e466317b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagingExtensionsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagingExtensionsTests.cs @@ -1,34 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Collections; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core.Collections { + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Collections; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class PagingExtensionsTests { [Test] public void PagingExtensions_InPagesOf_Returns_PageSelector() { - //Arrange + // Arrange IQueryable queryable = Util.CreateIntegerList(Constants.PAGE_TotalCount).AsQueryable(); - //Act + // Act PageSelector pageSelector = queryable.InPagesOf(Constants.PAGE_RecordCount); - //Assert + // Assert Assert.IsInstanceOf>(pageSelector); } @@ -39,13 +33,13 @@ public void PagingExtensions_InPagesOf_Returns_PageSelector() [TestCase(4, 4)] public void PagingExtensions_ToPagedList_Returns_PagedList_From_Enumerable(int index, int pageSize) { - //Arrange + // Arrange List enumerable = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act IPagedList pagedList = enumerable.ToPagedList(index, pageSize); - //Assert + // Assert Assert.IsInstanceOf>(pagedList); } @@ -57,13 +51,13 @@ public void PagingExtensions_ToPagedList_Returns_PagedList_From_Enumerable(int i public void PagingExtensions_ToPagedList_Returns_PagedList_From_Enumerable_With_Correct_Index_AndPageSize( int index, int pageSize) { - //Arrange + // Arrange List enumerable = Util.CreateIntegerList(Constants.PAGE_TotalCount); - //Act + // Act IPagedList pagedList = enumerable.ToPagedList(index, pageSize); - //Assert + // Assert Assert.AreEqual(index, pagedList.PageIndex); Assert.AreEqual(pageSize, pagedList.PageSize); } @@ -75,13 +69,13 @@ public void PagingExtensions_ToPagedList_Returns_PagedList_From_Enumerable_With_ [TestCase(4, 4)] public void PagingExtensions_ToPagedList_Returns_PagedList_From_Queryable(int index, int pageSize) { - //Arrange + // Arrange IQueryable queryable = Util.CreateIntegerList(Constants.PAGE_TotalCount).AsQueryable(); - //Act + // Act IPagedList pagedList = queryable.ToPagedList(index, pageSize); - //Assert + // Assert Assert.IsInstanceOf>(pagedList); } @@ -93,13 +87,13 @@ public void PagingExtensions_ToPagedList_Returns_PagedList_From_Queryable(int in public void PagingExtensions_ToPagedList_Returns_PagedList_From_Queryable_With_Correct_Index_AndPageSize( int index, int pageSize) { - //Arrange + // Arrange IQueryable queryable = Util.CreateIntegerList(Constants.PAGE_TotalCount).AsQueryable(); - //Act + // Act IPagedList pagedList = queryable.ToPagedList(index, pageSize); - //Assert + // Assert Assert.AreEqual(index, pagedList.PageIndex); Assert.AreEqual(pageSize, pagedList.PageSize); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedDictionaryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedDictionaryTests.cs index bf1d7f938a9..24fa84ef347 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedDictionaryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedDictionaryTests.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class ReaderWriterLockSharedDictionaryTests : SharedDictionaryTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedListTests.cs index 3637642c06b..93074344aac 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockSharedListTests.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class ReaderWriterLockSharedListTests : SharedListTests { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs index d9047179638..38264958a19 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs @@ -1,21 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class ReaderWriterLockStrategyTests : LockStrategyTests { - internal override ILockStrategy GetLockStrategy() - { - return new ReaderWriterLockStrategy(); - } - [Test] // no ExpectedException attribute public override void DoubleReadLockThrows() { @@ -27,5 +21,10 @@ public override void DoubleWriteLockThrows() { base.DoubleWriteLockThrows(); } + + internal override ILockStrategy GetLockStrategy() + { + return new ReaderWriterLockStrategy(); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs index d57e361dd2f..a80075c5986 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs @@ -1,15 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Threading; - -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using System.Threading; + + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + [TestFixture] public class ReaderWriterSlimLockTests { @@ -22,7 +21,8 @@ public void DoubleDisposeAllowed() scl.Dispose(); scl.Dispose(); - //no exception on 2nd dispose + + // no exception on 2nd dispose } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs index 2f84040f4cf..2e5dad8037f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs @@ -1,18 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading; - -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + public abstract class SharedDictionaryTests { public abstract LockingStrategy LockingStrategy { get; } @@ -23,7 +22,7 @@ public void TryAdd() const string KEY = "key"; const string VALUE = "value"; - var sharedDictionary = new SharedDictionary(LockingStrategy); + var sharedDictionary = new SharedDictionary(this.LockingStrategy); bool doInsert = false; using (ISharedCollectionLock l = sharedDictionary.GetReadLock()) @@ -45,25 +44,30 @@ public void TryAdd() } } - CollectionAssert.AreEqual(new Dictionary {{KEY, VALUE}}, sharedDictionary.BackingDictionary); + CollectionAssert.AreEqual(new Dictionary { { KEY, VALUE } }, sharedDictionary.BackingDictionary); } - [Test, ExpectedException(typeof (WriteLockRequiredException)), TestCaseSource("GetWriteMethods")] + [Test] + [ExpectedException(typeof(WriteLockRequiredException))] + [TestCaseSource("GetWriteMethods")] public void WriteRequiresLock(Action> writeAction) { - writeAction.Invoke(InitSharedDictionary("key", "value")); + writeAction.Invoke(this.InitSharedDictionary("key", "value")); } - [Test, ExpectedException(typeof (ReadLockRequiredException)), TestCaseSource("GetReadMethods")] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] + [TestCaseSource("GetReadMethods")] public void ReadRequiresLock(Action> readAction) { - readAction.Invoke(InitSharedDictionary("key", "value")); + readAction.Invoke(this.InitSharedDictionary("key", "value")); } - [Test, ExpectedException(typeof (ReadLockRequiredException))] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedReadLockDeniesRead() { - var d = new SharedDictionary(LockingStrategy); + var d = new SharedDictionary(this.LockingStrategy); ISharedCollectionLock l = d.GetReadLock(); l.Dispose(); @@ -71,10 +75,11 @@ public void DisposedReadLockDeniesRead() d.ContainsKey("foo"); } - [Test, ExpectedException(typeof (ReadLockRequiredException))] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedWriteLockDeniesRead() { - var d = new SharedDictionary(LockingStrategy); + var d = new SharedDictionary(this.LockingStrategy); ISharedCollectionLock l = d.GetWriteLock(); l.Dispose(); @@ -82,10 +87,11 @@ public void DisposedWriteLockDeniesRead() d.ContainsKey("foo"); } - [Test, ExpectedException(typeof (WriteLockRequiredException))] + [Test] + [ExpectedException(typeof(WriteLockRequiredException))] public void DisposedWriteLockDeniesWrite() { - var d = new SharedDictionary(LockingStrategy); + var d = new SharedDictionary(this.LockingStrategy); ISharedCollectionLock l = d.GetWriteLock(); l.Dispose(); @@ -96,7 +102,7 @@ public void DisposedWriteLockDeniesWrite() [Test] public void WriteLockEnablesRead() { - var d = InitSharedDictionary("key", "value"); + var d = this.InitSharedDictionary("key", "value"); string actualValue = null; using (ISharedCollectionLock l = d.GetWriteLock()) @@ -110,7 +116,7 @@ public void WriteLockEnablesRead() [Test] public void CanGetAnotherLockAfterDisposingLock() { - var d = new SharedDictionary(LockingStrategy); + var d = new SharedDictionary(this.LockingStrategy); ISharedCollectionLock l = d.GetReadLock(); l.Dispose(); @@ -121,23 +127,25 @@ public void CanGetAnotherLockAfterDisposingLock() [Test] public void DoubleDispose() { - var d = new SharedDictionary(LockingStrategy); + var d = new SharedDictionary(this.LockingStrategy); d.Dispose(); d.Dispose(); } - [Test, ExpectedException(typeof (ObjectDisposedException))] + [Test] + [ExpectedException(typeof(ObjectDisposedException))] [TestCaseSource("GetObjectDisposedExceptionMethods")] public void MethodsThrowAfterDisposed(Action> methodCall) { - var d = new SharedDictionary(LockingStrategy); + var d = new SharedDictionary(this.LockingStrategy); d.Dispose(); methodCall.Invoke(d); } - [Test, ExpectedException(typeof (LockRecursionException))] + [Test] + [ExpectedException(typeof(LockRecursionException))] public void TwoDictsShareALockWriteTest() { ILockStrategy ls = new ReaderWriterLockStrategy(); @@ -148,17 +156,17 @@ public void TwoDictsShareALockWriteTest() { using (ISharedCollectionLock writeLock = d2.GetWriteLock()) { - //do nothing + // do nothing } } } protected IEnumerable>> GetObjectDisposedExceptionMethods() { - var l = new List>> {(SharedDictionary d) => d.GetReadLock(), (SharedDictionary d) => d.GetWriteLock()}; + var l = new List>> { (SharedDictionary d) => d.GetReadLock(), (SharedDictionary d) => d.GetWriteLock() }; - l.AddRange(GetReadMethods()); - l.AddRange(GetWriteMethods()); + l.AddRange(this.GetReadMethods()); + l.AddRange(this.GetWriteMethods()); return l; } @@ -171,7 +179,7 @@ protected IEnumerable>> GetReadMethods() l.Add(d => d.Contains(new KeyValuePair("key", "value"))); l.Add(d => Console.WriteLine(d.Count)); l.Add(d => d.GetEnumerator()); - l.Add(d => ((IEnumerable) d).GetEnumerator()); + l.Add(d => ((IEnumerable)d).GetEnumerator()); l.Add(d => Console.WriteLine(d.IsReadOnly)); l.Add(d => Console.WriteLine(d["key"])); l.Add(d => Console.WriteLine(d.Keys)); @@ -185,7 +193,7 @@ protected IEnumerable>> GetReadMethods() l.Add((SharedDictionary d) => { - string value = ""; + string value = string.Empty; d.TryGetValue("key", out value); }); @@ -208,7 +216,7 @@ protected IEnumerable>> GetWriteMethods( private SharedDictionary InitSharedDictionary(TKey key, TValue value) { - var sharedDict = new SharedDictionary(LockingStrategy); + var sharedDict = new SharedDictionary(this.LockingStrategy); sharedDict.BackingDictionary.Add(key, value); return sharedDict; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs index 82ca0959221..b2d1de1de16 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs @@ -1,17 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Threading; - -using DotNetNuke.Collections.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Collections { + using System; + using System.Collections.Generic; + using System.Threading; + + using DotNetNuke.Collections.Internal; + using NUnit.Framework; + public abstract class SharedListTests { internal abstract LockingStrategy LockingStrategy { get; } @@ -21,7 +20,7 @@ public void TryAdd() { const string value = "value"; - var sharedList = new SharedList(LockingStrategy); + var sharedList = new SharedList(this.LockingStrategy); bool doInsert = false; using (ISharedCollectionLock l = sharedList.GetReadLock()) @@ -43,25 +42,30 @@ public void TryAdd() } } - CollectionAssert.AreEqual(new List {value}, sharedList.BackingList); + CollectionAssert.AreEqual(new List { value }, sharedList.BackingList); } - [Test, ExpectedException(typeof (WriteLockRequiredException)), TestCaseSource("GetWriteMethods")] + [Test] + [ExpectedException(typeof(WriteLockRequiredException))] + [TestCaseSource("GetWriteMethods")] public void WriteRequiresLock(Action> writeAction) { - writeAction.Invoke(InitSharedList("value")); + writeAction.Invoke(this.InitSharedList("value")); } - [Test, ExpectedException(typeof (ReadLockRequiredException)), TestCaseSource("GetReadMethods")] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] + [TestCaseSource("GetReadMethods")] public void ReadRequiresLock(Action> readAction) { - readAction.Invoke(InitSharedList("value")); + readAction.Invoke(this.InitSharedList("value")); } - [Test, ExpectedException(typeof (ReadLockRequiredException))] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedReadLockDeniesRead() { - var d = new SharedList(LockingStrategy); + var d = new SharedList(this.LockingStrategy); ISharedCollectionLock l = d.GetReadLock(); l.Dispose(); @@ -69,10 +73,11 @@ public void DisposedReadLockDeniesRead() d.Contains("foo"); } - [Test, ExpectedException(typeof (ReadLockRequiredException))] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedWriteLockDeniesRead() { - var d = new SharedList(LockingStrategy); + var d = new SharedList(this.LockingStrategy); ISharedCollectionLock l = d.GetWriteLock(); l.Dispose(); @@ -80,10 +85,11 @@ public void DisposedWriteLockDeniesRead() d.Contains("foo"); } - [Test, ExpectedException(typeof (WriteLockRequiredException))] + [Test] + [ExpectedException(typeof(WriteLockRequiredException))] public void DisposedWriteLockDeniesWrite() { - var sharedList = new SharedList(LockingStrategy); + var sharedList = new SharedList(this.LockingStrategy); ISharedCollectionLock l = sharedList.GetWriteLock(); l.Dispose(); @@ -94,7 +100,7 @@ public void DisposedWriteLockDeniesWrite() [Test] public void WriteLockEnablesRead() { - var sharedList = InitSharedList("value"); + var sharedList = this.InitSharedList("value"); string actualValue = null; using (ISharedCollectionLock l = sharedList.GetWriteLock()) @@ -108,7 +114,7 @@ public void WriteLockEnablesRead() [Test] public void CanGetAnotherLockAfterDisposingLock() { - var d = new SharedList(LockingStrategy); + var d = new SharedList(this.LockingStrategy); ISharedCollectionLock l = d.GetReadLock(); l.Dispose(); @@ -119,23 +125,25 @@ public void CanGetAnotherLockAfterDisposingLock() [Test] public void DoubleDispose() { - var d = new SharedList(LockingStrategy); + var d = new SharedList(this.LockingStrategy); d.Dispose(); d.Dispose(); } - [Test, ExpectedException(typeof (ObjectDisposedException))] + [Test] + [ExpectedException(typeof(ObjectDisposedException))] [TestCaseSource("GetObjectDisposedExceptionMethods")] public void MethodsThrowAfterDisposed(Action> methodCall) { - var d = new SharedList(LockingStrategy); + var d = new SharedList(this.LockingStrategy); d.Dispose(); methodCall.Invoke(d); } - [Test, ExpectedException(typeof (LockRecursionException))] + [Test] + [ExpectedException(typeof(LockRecursionException))] public void TwoDictsShareALockWriteTest() { ILockStrategy ls = new ReaderWriterLockStrategy(); @@ -146,17 +154,17 @@ public void TwoDictsShareALockWriteTest() { using (ISharedCollectionLock writeLock = d2.GetWriteLock()) { - //do nothing + // do nothing } } } protected IEnumerable>> GetObjectDisposedExceptionMethods() { - var list = new List>> {(SharedList l) => l.GetReadLock(), (SharedList l) => l.GetWriteLock()}; + var list = new List>> { (SharedList l) => l.GetReadLock(), (SharedList l) => l.GetWriteLock() }; - list.AddRange(GetReadMethods()); - list.AddRange(GetWriteMethods()); + list.AddRange(this.GetReadMethods()); + list.AddRange(this.GetWriteMethods()); return list; } @@ -183,14 +191,14 @@ protected IEnumerable>> GetReadMethods() protected IEnumerable>> GetWriteMethods() { - var list = new List>> {l => l.Add("more"), l => l.Clear(), l => l.Remove("value"), l => l.Insert(0, "more"), l => l[0] = "more", l => l.RemoveAt(0)}; + var list = new List>> { l => l.Add("more"), l => l.Clear(), l => l.Remove("value"), l => l.Insert(0, "more"), l => l[0] = "more", l => l.RemoveAt(0) }; return list; } private SharedList InitSharedList(T value) { - var list = new SharedList(LockingStrategy); + var list = new SharedList(this.LockingStrategy); list.BackingList.Add(value); return list; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs index 2cbc2ecd24c..74fa0cf825d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs @@ -1,27 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Abstractions; -using DotNetNuke.Abstractions.Portals; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; -using Moq; -using NUnit.Framework; -using System.Collections.Generic; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Common { + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using Moq; + using NUnit.Framework; + [TestFixture] public class NavigationManagerTests { - private INavigationManager _navigationManager; private const int TabID = 100; private const int PortalID = 7; + private INavigationManager _navigationManager; private const string DefaultURLPattern = "/Default.aspx?tabid={0}"; private const string DefaultSuperTabPattern = "&portalid={0}"; private const string ControlKeyPattern = "&ctl={0}"; @@ -30,8 +31,7 @@ public class NavigationManagerTests [TestFixtureSetUp] public void Setup() { - - _navigationManager = new NavigationManager(PortalControllerMock()); + this._navigationManager = new NavigationManager(PortalControllerMock()); TabController.SetTestableInstance(TabControllerMock()); LocaleController.SetTestableInstance(LocaleControllerMock()); @@ -55,12 +55,13 @@ PortalSettings PortalSettingsMock() ActiveTab = new TabInfo { TabID = TabID - } + }, }; return portalSettings; } } + ITabController TabControllerMock() { var mockTabController = new Mock(); @@ -71,11 +72,12 @@ ITabController TabControllerMock() .Setup(x => x.GetTab(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new TabInfo { - CultureCode = "en-US" + CultureCode = "en-US", }); return mockTabController.Object; } + ILocaleController LocaleControllerMock() { var mockLocaleController = new Mock(); @@ -84,7 +86,7 @@ ILocaleController LocaleControllerMock() .Returns(new Dictionary { { "en-US", new Locale() }, - { "TEST", new Locale() } + { "TEST", new Locale() }, }); return mockLocaleController.Object; @@ -94,7 +96,7 @@ ILocaleController LocaleControllerMock() [TestFixtureTearDown] public void TearDown() { - _navigationManager = null; + this._navigationManager = null; TabController.ClearInstance(); LocaleController.ClearInstance(); } @@ -103,7 +105,7 @@ public void TearDown() public void NavigateUrlTest() { var expected = string.Format(DefaultURLPattern, TabID); - var actual = _navigationManager.NavigateURL(); + var actual = this._navigationManager.NavigateURL(); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -123,7 +125,7 @@ public void NavigateUrlTest() public void NavigateUrl_CustomTabID(int tabId) { var expected = string.Format(DefaultURLPattern, tabId); - var actual = _navigationManager.NavigateURL(tabId); + var actual = this._navigationManager.NavigateURL(tabId); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -134,7 +136,7 @@ public void NavigateUrl_CustomTab_NotSuperTab() { var customTabId = 55; var expected = string.Format(DefaultURLPattern, customTabId); - var actual = _navigationManager.NavigateURL(customTabId, false); + var actual = this._navigationManager.NavigateURL(customTabId, false); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -154,7 +156,7 @@ public void NavigateUrl_CustomTab_NotSuperTab() public void NavigateUrl_CustomTab_IsSuperTab(int tabId) { var expected = string.Format(DefaultURLPattern, tabId) + string.Format(DefaultSuperTabPattern, PortalID); - var actual = _navigationManager.NavigateURL(tabId, true); + var actual = this._navigationManager.NavigateURL(tabId, true); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -164,11 +166,11 @@ public void NavigateUrl_CustomTab_IsSuperTab(int tabId) [Ignore] public void NavigateUrl_ControlKey_AccessDenied() { - // TODO - We can't properly test this until we migrate + // TODO - We can't properly test this until we migrate // Globals.AccessDeniedURL to an interface in the abstraction // project. The dependencies go very deep and make it very // difficult to properly test just the NavigationManager logic. - var actual = _navigationManager.NavigateURL("Access Denied"); + var actual = this._navigationManager.NavigateURL("Access Denied"); } [Test] @@ -176,7 +178,7 @@ public void NavigateUrl_ControlKey() { var controlKey = "My-Control-Key"; var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey); - var actual = _navigationManager.NavigateURL(controlKey); + var actual = this._navigationManager.NavigateURL(controlKey); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -187,7 +189,7 @@ public void NavigateUrl_ControlKey_EmptyAdditionalParameter() { var controlKey = "My-Control-Key"; var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey); - var actual = _navigationManager.NavigateURL(controlKey, new string[0]); + var actual = this._navigationManager.NavigateURL(controlKey, new string[0]); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -201,7 +203,7 @@ public void NavigateUrl_ControlKey_SingleAdditionalParameter() var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey) + $"&{parameters[0]}"; - var actual = _navigationManager.NavigateURL(controlKey, parameters); + var actual = this._navigationManager.NavigateURL(controlKey, parameters); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -219,14 +221,16 @@ public void NavigateUrl_ControlKey_SingleAdditionalParameter() public void NavigateUrl_ControlKey_MultipleAdditionalParameter(int count) { string[] parameters = new string[count]; - for (int index = 0; index < count; index++) - parameters[index] = $"My-Parameter{index}"; - + for (int index = 0; index < count; index++) + { + parameters[index] = $"My-Parameter{index}"; + } + var controlKey = "My-Control-Key"; var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey) + parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); - var actual = _navigationManager.NavigateURL(controlKey, parameters); + var actual = this._navigationManager.NavigateURL(controlKey, parameters); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -247,7 +251,7 @@ public void NavigateUrl_TabID_ControlKey(int tabId) { var controlKey = "My-Control-Key"; var expected = string.Format(DefaultURLPattern, tabId) + string.Format(ControlKeyPattern, controlKey); - var actual = _navigationManager.NavigateURL(tabId, controlKey); + var actual = this._navigationManager.NavigateURL(tabId, controlKey); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -267,7 +271,7 @@ public void NavigateUrl_TabID_ControlKey(int tabId) public void NavigateUrl_TabID_EmptyControlKey(int tabId) { var expected = string.Format(DefaultURLPattern, tabId); - var actual = _navigationManager.NavigateURL(tabId, string.Empty); + var actual = this._navigationManager.NavigateURL(tabId, string.Empty); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -287,7 +291,7 @@ public void NavigateUrl_TabID_EmptyControlKey(int tabId) public void NavigateUrl_TabID_NullControlKey(int tabId) { var expected = string.Format(DefaultURLPattern, tabId); - var actual = _navigationManager.NavigateURL(tabId, string.Empty); + var actual = this._navigationManager.NavigateURL(tabId, string.Empty); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -307,17 +311,21 @@ public void NavigateUrl_TabID_NullControlKey(int tabId) public void NavigateUrl_TabID_ControlKey_Parameter(int count, string controlKey) { string[] parameters = new string[count]; - for (int index = 0; index < count; index++) - parameters[index] = $"My-Parameter{index}"; - + for (int index = 0; index < count; index++) + { + parameters[index] = $"My-Parameter{index}"; + } + var customTabId = 51; var expected = string.Format(DefaultURLPattern, customTabId) + string.Format(ControlKeyPattern, controlKey); - if (parameters.Length > 0) - expected += parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); - - var actual = _navigationManager.NavigateURL(customTabId, controlKey, parameters); + if (parameters.Length > 0) + { + expected += parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); + } + + var actual = this._navigationManager.NavigateURL(customTabId, controlKey, parameters); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -339,7 +347,7 @@ public void NavigateUrl_TabID_ControlKey_NullParameter(int tabId, string control var expected = string.Format(DefaultURLPattern, tabId) + string.Format(ControlKeyPattern, controlKey); - var actual = _navigationManager.NavigateURL(tabId, controlKey, null); + var actual = this._navigationManager.NavigateURL(tabId, controlKey, null); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -361,7 +369,7 @@ public void NavigateUrl_TabId_NullSettings_ControlKey(int tabId, string controlK var expected = string.Format(DefaultURLPattern, tabId) + string.Format(ControlKeyPattern, controlKey); - var actual = _navigationManager.NavigateURL(tabId, default(IPortalSettings), controlKey, null); + var actual = this._navigationManager.NavigateURL(tabId, default(IPortalSettings), controlKey, null); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); @@ -389,7 +397,7 @@ public void NavigateUrl_TabId_Settings_ControlKey(int tabId, string controlKey) string.Format(ControlKeyPattern, controlKey) + string.Format(LanguagePattern, "en-US"); - var actual = _navigationManager.NavigateURL(tabId, mockSettings.Object, controlKey, null); + var actual = this._navigationManager.NavigateURL(tabId, mockSettings.Object, controlKey, null); Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs index a3f79ad1478..e8d0ba1acf1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs @@ -1,27 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.ComponentModel { + using System; + using System.Collections; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Summary description for ComponentFactoryTests + /// Summary description for ComponentFactoryTests. /// [TestFixture] public class ComponentFactoryTests - { - #region InstallComponents - + { + public static IContainer CreateMockContainer() + { + var mockContainer = new Mock(); + IContainer container = mockContainer.Object; + ComponentFactory.Container = container; + return container; + } + [TearDown] public void TearDown() { @@ -33,7 +37,7 @@ public void ComponentFactory_InstallComponents_Should_Accept_Empty_InstallersArr { IContainer container = CreateMockContainer(); - ComponentFactory.InstallComponents(new IComponentInstaller[0] {}); + ComponentFactory.InstallComponents(new IComponentInstaller[0] { }); } [Test] @@ -58,30 +62,20 @@ public void ComponentFactory_InstallComponents_Should_Throw_On_Null_Installer_In [Test] public void DNNPRO_13443_ComponentFactory_DuplicatedInsert() { - //Setup + // Setup var testComp1 = new ArrayList(); var testComp2 = new ArrayList(); testComp1.Add("testComp1"); testComp2.Add("testComp2"); - //Act + // Act ComponentFactory.RegisterComponentInstance(testComp1); ComponentFactory.RegisterComponentInstance(testComp2); - //Assert + // Assert var retreivedComponent = ComponentFactory.GetComponent(); Assert.AreEqual(testComp1, retreivedComponent); - } - - #endregion - - public static IContainer CreateMockContainer() - { - var mockContainer = new Mock(); - IContainer container = mockContainer.Object; - ComponentFactory.Container = container; - return container; - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService.cs index 1029a3a0955..af53a765bb5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.ComponentModel.Helpers { public interface IService diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService2.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService2.cs index a135608fd0e..ead8f8d351c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService2.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService2.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.ComponentModel.Helpers { public interface IService2 diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs index 5a33d487e9e..7374e438abc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.ComponentModel.Helpers { public class Service2Impl : IService2 @@ -10,16 +10,12 @@ public class Service2Impl : IService2 public Service2Impl(IService service) { - _service = service; - } - - #region IService2 Members - + this._service = service; + } + public IService Service { - get { return _service; } - } - - #endregion + get { return this._service; } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/ServiceImpl.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/ServiceImpl.cs index 984584b6b36..90fcd26ce64 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/ServiceImpl.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/ServiceImpl.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.ComponentModel.Helpers { + using System; + public class ServiceImpl : IService { private static readonly Random rnd = new Random(); @@ -13,7 +13,7 @@ public class ServiceImpl : IService public int Id { - get { return id; } + get { return this.id; } } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs index e018d14fbee..7e362bdfe71 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.ComponentModel; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.ComponentModel { + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.ComponentModel; + using NUnit.Framework; + [TestFixture] public class SimpleContainerTests { [Test] - //DNN-17622 http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=17622&PROJID=2 + + // DNN-17622 http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=17622&PROJID=2 public void GetComponenetListSupportsInterfaces() { var container = new SimpleContainer(); @@ -23,7 +23,7 @@ public void GetComponenetListSupportsInterfaces() var retrieved = container.GetComponentList(typeof(IList)); - CollectionAssert.AreEqual(new List {"payload"}, retrieved); + CollectionAssert.AreEqual(new List { "payload" }, retrieved); } [Test] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/ConfigurationSettingsComparer.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/ConfigurationSettingsComparer.cs index 796be48da86..c9bd9725f02 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/ConfigurationSettingsComparer.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/ConfigurationSettingsComparer.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities; + public class ConfigurationSettingsComparer : EqualityComparer { public override bool Equals(ConfigurationSetting x, ConfigurationSetting y) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs index 6c71af6ed82..73d4bdbaeab 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs @@ -1,65 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Host { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class HostControllerTest { private DataTable _hostSettingsTable; private Mock _mockCache; private Mock _mockData; - - + [SetUp] public void SetUp() { - _mockCache = MockComponentProvider.CreateDataCacheProvider(); + this._mockCache = MockComponentProvider.CreateDataCacheProvider(); MockComponentProvider.CreateEventLogController(); - - - - _hostSettingsTable = new DataTable("HostSettings"); - - var nameCol = _hostSettingsTable.Columns.Add("SettingName"); - _hostSettingsTable.Columns.Add("SettingValue"); - _hostSettingsTable.Columns.Add("SettingIsSecure"); - _hostSettingsTable.PrimaryKey = new[] {nameCol}; - - _hostSettingsTable.Rows.Add("String_1_S", "String_1_S", true); - _hostSettingsTable.Rows.Add("String_2_S", "String_1_S", true); - _hostSettingsTable.Rows.Add("String_3_U", "Value_3_U", false); - _hostSettingsTable.Rows.Add("String_4_U", "Value_4_U", false); - _hostSettingsTable.Rows.Add("Int_5_U", "5", false); - _hostSettingsTable.Rows.Add("Int_6_S", "6", true); - _hostSettingsTable.Rows.Add("Double_7_S", "7", true); - _hostSettingsTable.Rows.Add("Double_8_U", "8", false); - _hostSettingsTable.Rows.Add("Bool_9_U", false, false); - _hostSettingsTable.Rows.Add("Bool_10_S", false, true); - - - _mockData = MockComponentProvider.CreateDataProvider(); - _mockData.Setup(c => c.GetHostSettings()).Returns(_hostSettingsTable.CreateDataReader()); - _mockData.Setup(c => c.GetProviderPath()).Returns(String.Empty); - - + + this._hostSettingsTable = new DataTable("HostSettings"); + + var nameCol = this._hostSettingsTable.Columns.Add("SettingName"); + this._hostSettingsTable.Columns.Add("SettingValue"); + this._hostSettingsTable.Columns.Add("SettingIsSecure"); + this._hostSettingsTable.PrimaryKey = new[] { nameCol }; + + this._hostSettingsTable.Rows.Add("String_1_S", "String_1_S", true); + this._hostSettingsTable.Rows.Add("String_2_S", "String_1_S", true); + this._hostSettingsTable.Rows.Add("String_3_U", "Value_3_U", false); + this._hostSettingsTable.Rows.Add("String_4_U", "Value_4_U", false); + this._hostSettingsTable.Rows.Add("Int_5_U", "5", false); + this._hostSettingsTable.Rows.Add("Int_6_S", "6", true); + this._hostSettingsTable.Rows.Add("Double_7_S", "7", true); + this._hostSettingsTable.Rows.Add("Double_8_U", "8", false); + this._hostSettingsTable.Rows.Add("Bool_9_U", false, false); + this._hostSettingsTable.Rows.Add("Bool_10_S", false, true); + + this._mockData = MockComponentProvider.CreateDataProvider(); + this._mockData.Setup(c => c.GetHostSettings()).Returns(this._hostSettingsTable.CreateDataReader()); + this._mockData.Setup(c => c.GetProviderPath()).Returns(string.Empty); + DataCache.ClearCache(); } @@ -68,35 +61,28 @@ public void TearDown() { MockComponentProvider.ResetContainer(); } - - private string GetValue(string key) - { - return _hostSettingsTable.Rows.Find(key)["SettingValue"].ToString(); - } - - #region Get Dictionaries - + [Test] public void HostController_GetSettings_GetList() { - //Arrange + // Arrange var expectedDic = new Dictionary(); - foreach (DataRow row in _hostSettingsTable.Rows) + foreach (DataRow row in this._hostSettingsTable.Rows) { var conf = new ConfigurationSetting(); conf.Key = row["SettingName"].ToString(); conf.Value = row["SettingValue"].ToString(); bool IsSecure; - Boolean.TryParse(row["SettingIsSecure"].ToString(), out IsSecure); + bool.TryParse(row["SettingIsSecure"].ToString(), out IsSecure); conf.IsSecure = IsSecure; expectedDic.Add(conf.Key, conf); } - //Act + // Act var settingsDic = HostController.Instance.GetSettings(); - //Assert + // Assert foreach (var currentConfig in settingsDic) { Assert.AreEqual(currentConfig.Key, currentConfig.Value.Key); @@ -108,176 +94,169 @@ public void HostController_GetSettings_GetList() [Test] public void HostController_GetSettingsDictionary_GetList() { - //Arrange - //Convert table to Dictionary - var expectedDic = _hostSettingsTable.Rows.Cast().ToDictionary(row => row["SettingName"].ToString(), row => row["SettingValue"].ToString()); + // Arrange + // Convert table to Dictionary + var expectedDic = this._hostSettingsTable.Rows.Cast().ToDictionary(row => row["SettingName"].ToString(), row => row["SettingValue"].ToString()); - //Act + // Act var settingsDic = HostController.Instance.GetSettingsDictionary(); - - - //Assert + + // Assert CollectionAssert.AreEquivalent(expectedDic.Values, settingsDic.Values); - } - - #endregion - - #region Update Value + } + private string GetValue(string key) + { + return this._hostSettingsTable.Rows.Find(key)["SettingValue"].ToString(); + } + [Test] public void HostController_Update_ExistingValue() { - //Arrange + // Arrange const string key = "String_1_S"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - //Act + // Act HostController.Instance.Update(key, value); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); } [Test] public void HostController_Update_ExistingValue_ResetCache() { - //Arrange + // Arrange const string key = "String_1_S"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - //Act + // Act HostController.Instance.Update(key, value); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); } [Test] public void HostController_Update_ExistingValue_ResetCache_With_Overload() { - //Arrange + // Arrange const string key = "String_1_S"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - //Act + // Act HostController.Instance.Update(key, value, true); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Exactly(1)); } [Test] public void HostController_Update_ExistingValue_Dont_Reset_Cache() { - //Arrange + // Arrange const string key = "String_1_S"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); + this._mockData.Setup(c => c.GetHostSetting(key).Read()).Returns(true); - //Act + // Act HostController.Instance.Update(key, value, false); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - //Clear was not called a second time - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + + // Clear was not called a second time + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); } [Test] public void HostController_Update_Dictionary() { - //Arrange + // Arrange var settings = new Dictionary { - {"String_1_S", "MyValue"}, + { "String_1_S", "MyValue" }, }; - //Act + // Act HostController.Instance.Update(settings); - //Assert - _mockData.Verify(c => c.UpdateHostSetting("String_1_S", "MyValue", false, It.IsAny()), Times.Exactly(1)); - _mockCache.Verify(c => c.Clear("Host", ""), Times.Exactly(1)); - } - - #endregion - - #region Create Value - + // Assert + this._mockData.Verify(c => c.UpdateHostSetting("String_1_S", "MyValue", false, It.IsAny()), Times.Exactly(1)); + this._mockCache.Verify(c => c.Clear("Host", string.Empty), Times.Exactly(1)); + } + [Test] public void HostController_Update_NewValue() { - //Arrange + // Arrange const string key = "MyKey"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - //Act + // Act HostController.Instance.Update(key, value); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); } [Test] public void HostController_Update_NewValue_ResetCache_With_Overload() { - //Arrange + // Arrange const string key = "MyKey"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - //Act + // Act HostController.Instance.Update(key, value, true); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); } [Test] public void HostController_Update_NewValue_ResetCache() { - //Arrange + // Arrange const string key = "MyKey"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - //Act + // Act HostController.Instance.Update(key, value); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Once); } [Test] public void HostController_Update_NewValue_Dont_Reset_Cache() { - //Arrange + // Arrange const string key = "MyKey"; const string value = "MyValue"; - _mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); + this._mockData.Setup(c => c.GetHostSetting(It.IsAny()).Read()).Returns(false); - //Act + // Act HostController.Instance.Update(key, value, false); - //Assert - _mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - _mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); - } - - #endregion - - #region GetString() - + // Assert + this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); + this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); + } + [Test] [TestCase("String_1_S")] [TestCase("String_2_S")] @@ -285,11 +264,10 @@ public void HostController_Update_NewValue_Dont_Reset_Cache() [TestCase("String_4_U")] public void HostController_GetString_If_Key_Exists(string key) { - Assert.AreEqual(HostController.Instance.GetString(key), GetValue(key)); - Assert.AreEqual(HostController.Instance.GetString(key, "Hello Default"), GetValue(key)); + Assert.AreEqual(HostController.Instance.GetString(key), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetString(key, "Hello Default"), this.GetValue(key)); } - - + [Test] [TestCase("BadKey1")] [TestCase("AAAAAAA")] @@ -313,20 +291,16 @@ public void HostController_GetString_InvalidKey_Returns_Default_Value(string key public void HostController_GetString_NullEmpty(string key) { HostController.Instance.GetString(key); - } - - #endregion - - #region GetInteger() - + } + [Test] [TestCase("Int_5_U")] [TestCase("Int_6_S")] public void HostController_GetInteger_If_Key_Exists(string key) { int s = HostController.Instance.GetInteger(key); - Assert.AreEqual(s.ToString(), GetValue(key)); - Assert.AreEqual(HostController.Instance.GetInteger(key, 12).ToString(), GetValue(key)); + Assert.AreEqual(s.ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetInteger(key, 12).ToString(), this.GetValue(key)); } [Test] @@ -352,23 +326,18 @@ public void HostController_GetInteger_InvalidKey_Returns_Default_Value(string ke public void HostController_GetInteger_NullEmpty(string key) { HostController.Instance.GetInteger(key); - } - - #endregion - - #region GetBoolean() - + } + [Test] [TestCase("Bool_9_U")] [TestCase("Bool_10_S")] public void HostController_GetBoolean_If_Key_Exists(string key) { - Assert.AreEqual(HostController.Instance.GetBoolean(key).ToString(), GetValue(key)); - Assert.AreEqual(HostController.Instance.GetBoolean(key, false).ToString(), GetValue(key)); - Assert.AreEqual(HostController.Instance.GetBoolean(key, true).ToString(), GetValue(key)); + Assert.AreEqual(HostController.Instance.GetBoolean(key).ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetBoolean(key, false).ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetBoolean(key, true).ToString(), this.GetValue(key)); } - - + [Test] [TestCase("BadKey1")] [TestCase("AAAAAAA")] @@ -385,8 +354,7 @@ public void HostController_GetBoolean_InvalidKey_Returns_Default_Value(string ke Assert.AreEqual(HostController.Instance.GetBoolean(key, true), true); Assert.AreEqual(HostController.Instance.GetBoolean(key, false), false); } - - + [Test] [TestCase("")] [TestCase(null)] @@ -394,20 +362,16 @@ public void HostController_GetBoolean_InvalidKey_Returns_Default_Value(string ke public void HostController_GetBoolean_NullEmpty(string key) { HostController.Instance.GetBoolean(key); - } - - #endregion - - #region GetDouble() - + } + [Test] [TestCase("Double_7_S")] [TestCase("Double_8_U")] public void HostController_GetDouble_If_Key_Exists(string key) { - Double s = HostController.Instance.GetDouble(key); - Assert.AreEqual(s.ToString(), GetValue(key)); - Assert.AreEqual(HostController.Instance.GetDouble(key, 54.54).ToString(), GetValue(key)); + double s = HostController.Instance.GetDouble(key); + Assert.AreEqual(s.ToString(), this.GetValue(key)); + Assert.AreEqual(HostController.Instance.GetDouble(key, 54.54).ToString(), this.GetValue(key)); } [Test] @@ -433,8 +397,6 @@ public void HostController_GetDouble_InvalidKey_Returns_Default_Value(string key public void HostController_GetDouble_NullEmpty(string key) { HostController.Instance.GetDouble(key); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs index 741b97397dd..18efe757c04 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Social.Subscriptions.Entities; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging.Builders { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Social.Subscriptions.Entities; + using DotNetNuke.Tests.Utilities; + public class SubscriptionBuilder { private int subscriptionId; @@ -23,15 +24,15 @@ public class SubscriptionBuilder internal SubscriptionBuilder() { - subscriptionId = 1; - userId = Constants.USER_InValidId; - subscriptionTypeId = 1; - portalId = Constants.PORTAL_ValidPortalId; - moduleId = Null.NullInteger; - tabId = Null.NullInteger; - objectKey = "content"; - description = "my content description"; - objectData = ""; + this.subscriptionId = 1; + this.userId = Constants.USER_InValidId; + this.subscriptionTypeId = 1; + this.portalId = Constants.PORTAL_ValidPortalId; + this.moduleId = Null.NullInteger; + this.tabId = Null.NullInteger; + this.objectKey = "content"; + this.description = "my content description"; + this.objectData = string.Empty; } internal SubscriptionBuilder WithSubscriptionId(int subscriptionId) @@ -69,7 +70,7 @@ internal SubscriptionBuilder WithDescription(string description) this.description = description; return this; } - + internal SubscriptionBuilder WithModuleId(int moduleId) { this.moduleId = moduleId; @@ -80,24 +81,23 @@ internal SubscriptionBuilder WithTabId(int tabId) { this.tabId = tabId; return this; - } + } internal Subscription Build() { - return new Subscription - { - SubscriptionTypeId = subscriptionTypeId, - SubscriptionId = subscriptionId, - CreatedOnDate = DateTime.UtcNow, - ModuleId = moduleId, - ObjectKey = objectKey, - Description = description, - PortalId = portalId, - TabId = tabId, - UserId = userId, - ObjectData = objectData - }; - + return new Subscription + { + SubscriptionTypeId = this.subscriptionTypeId, + SubscriptionId = this.subscriptionId, + CreatedOnDate = DateTime.UtcNow, + ModuleId = this.moduleId, + ObjectKey = this.objectKey, + Description = this.description, + PortalId = this.portalId, + TabId = this.tabId, + UserId = this.userId, + ObjectData = this.objectData, + }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs index e75126e47c8..94ff287619a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging.Builders { - class SubscriptionTypeBuilder + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Social.Subscriptions.Entities; + + internal class SubscriptionTypeBuilder { private int subscriptionTypeId; private string subscriptionName; @@ -16,10 +16,10 @@ class SubscriptionTypeBuilder internal SubscriptionTypeBuilder() { - subscriptionTypeId = 1; - subscriptionName = "MySubscriptionType"; - friendlyName = "My Subscription Type"; - desktopModuleId = Null.NullInteger; + this.subscriptionTypeId = 1; + this.subscriptionName = "MySubscriptionType"; + this.friendlyName = "My Subscription Type"; + this.desktopModuleId = Null.NullInteger; } internal SubscriptionTypeBuilder WithSubscriptionTypeId(int subscriptionTypeId) @@ -36,13 +36,13 @@ internal SubscriptionTypeBuilder WithSubscriptionName(string subscriptionName) internal SubscriptionType Build() { - return new SubscriptionType - { - SubscriptionTypeId = subscriptionTypeId, - SubscriptionName = subscriptionName, - DesktopModuleId = desktopModuleId, - FriendlyName = friendlyName - }; + return new SubscriptionType + { + SubscriptionTypeId = this.subscriptionTypeId, + SubscriptionName = this.subscriptionName, + DesktopModuleId = this.desktopModuleId, + FriendlyName = this.friendlyName, + }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/UserPreferenceBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/UserPreferenceBuilder.cs index c53ae975564..9cf2ce8c779 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/UserPreferenceBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/UserPreferenceBuilder.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging.Builders { + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Tests.Utilities; + internal class UserPreferenceBuilder { private int userId; @@ -16,20 +16,20 @@ internal class UserPreferenceBuilder internal UserPreferenceBuilder() { - userId = Constants.USER_InValidId; - portalId = Constants.PORTAL_ValidPortalId; - messagesEmailFrequency = Frequency.Instant; - notificationsEmailFrequency = Frequency.Hourly; + this.userId = Constants.USER_InValidId; + this.portalId = Constants.PORTAL_ValidPortalId; + this.messagesEmailFrequency = Frequency.Instant; + this.notificationsEmailFrequency = Frequency.Hourly; } internal UserPreference Build() { return new UserPreference { - UserId = userId, - PortalId = portalId, - MessagesEmailFrequency = messagesEmailFrequency, - NotificationsEmailFrequency = notificationsEmailFrequency + UserId = this.userId, + PortalId = this.portalId, + MessagesEmailFrequency = this.messagesEmailFrequency, + NotificationsEmailFrequency = this.notificationsEmailFrequency, }; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Helpers/SetupCachingProviderHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Helpers/SetupCachingProviderHelper.cs index 38d23d8645e..8a54f80d94a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Helpers/SetupCachingProviderHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Helpers/SetupCachingProviderHelper.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Cache; -using Moq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging.Helpers { + using System.Collections.Generic; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Cache; + using Moq; + public class SetupCachingProviderHelper { public static void SetupCachingProvider(Mock mockCachingProvider) { mockCachingProvider.Setup(c => c.GetItem(It.IsAny())) - .Returns((key => + .Returns(key => { if (key.Contains("Portal-1_")) { @@ -22,8 +23,9 @@ public static void SetupCachingProvider(Mock mockCachingProvide return portals; } + return key.Contains("PortalGroups") ? new List() : null; - })); + }); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs index 04717495aab..9851c0f78d9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs @@ -1,46 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Text; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Portals.Internal; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Messaging.Data; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Services.Social.Messaging.Exceptions; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming namespace DotNetNuke.Tests.Core.Controllers.Messaging { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Text; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Portals.Internal; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Messaging.Data; + using DotNetNuke.Services.Social.Messaging.Exceptions; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Testing various aspects of MessagingController + /// Testing various aspects of MessagingController. /// [TestFixture] public class MessagingControllerTests - { - #region "Private Properties" - + { private Mock _mockDataService; private MessagingController _messagingController; private InternalMessagingControllerImpl _internalMessagingController; @@ -65,54 +61,49 @@ public class MessagingControllerTests private UserInfo _adminUserInfo; private UserInfo _hostUserInfo; private UserInfo _user12UserInfo; - private UserInfo _groupOwnerUserInfo; - - #endregion - - #region "Set Up" - + private UserInfo _groupOwnerUserInfo; + [SetUp] public void SetUp() { - ComponentFactory.Container = new SimpleContainer(); - _mockDataService = new Mock(); - _dataProvider = MockComponentProvider.CreateDataProvider(); - _mockRoleProvider = MockComponentProvider.CreateRoleProvider(); - _mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); + this._mockDataService = new Mock(); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + this._mockRoleProvider = MockComponentProvider.CreateRoleProvider(); + this._mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); MockComponentProvider.CreateEventLogController(); - _mockLocalizationProvider = MockComponentProvider.CreateLocalizationProvider(); - _mockLocalizationProvider.Setup(l => l.GetString(It.IsAny(), It.IsAny())).Returns("{0}_{1}"); + this._mockLocalizationProvider = MockComponentProvider.CreateLocalizationProvider(); + this._mockLocalizationProvider.Setup(l => l.GetString(It.IsAny(), It.IsAny())).Returns("{0}_{1}"); - _messagingController = new MessagingController(_mockDataService.Object); - _internalMessagingController = new InternalMessagingControllerImpl(_mockDataService.Object); - _mockMessagingController = new Mock { CallBase = true }; - _mockInternalMessagingController = new Mock { CallBase = true }; + this._messagingController = new MessagingController(this._mockDataService.Object); + this._internalMessagingController = new InternalMessagingControllerImpl(this._mockDataService.Object); + this._mockMessagingController = new Mock { CallBase = true }; + this._mockInternalMessagingController = new Mock { CallBase = true }; - _portalController = new Mock(); - _portalController.Setup(c => c.GetPortalSettings(It.IsAny())).Returns(new Dictionary()); - PortalController.SetTestableInstance(_portalController.Object); + this._portalController = new Mock(); + this._portalController.Setup(c => c.GetPortalSettings(It.IsAny())).Returns(new Dictionary()); + PortalController.SetTestableInstance(this._portalController.Object); - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _folderManager = new Mock(); - _fileManager = new Mock(); - _folderPermissionController = new Mock(); + this._folderManager = new Mock(); + this._fileManager = new Mock(); + this._folderPermissionController = new Mock(); - FolderManager.RegisterInstance(_folderManager.Object); - FileManager.RegisterInstance(_fileManager.Object); - FolderPermissionController.SetTestableInstance(_folderPermissionController.Object); + FolderManager.RegisterInstance(this._folderManager.Object); + FileManager.RegisterInstance(this._fileManager.Object); + FolderPermissionController.SetTestableInstance(this._folderPermissionController.Object); - SetupDataProvider(); - SetupRoleProvider(); - SetupDataTables(); - SetupUsers(); - SetupPortalSettings(); - SetupCachingProvider(); - SetupFileControllers(); + this.SetupDataProvider(); + this.SetupRoleProvider(); + this.SetupDataTables(); + this.SetupUsers(); + this.SetupPortalSettings(); + this.SetupCachingProvider(); + this.SetupFileControllers(); - _mockInternalMessagingController.Setup(m => m.GetLastSentMessage(It.IsAny())).Returns((Message)null); + this._mockInternalMessagingController.Setup(m => m.GetLastSentMessage(It.IsAny())).Returns((Message)null); } [TearDown] @@ -121,11 +112,28 @@ public void TearDown() ComponentFactory.Container = null; PortalController.ClearInstance(); } + + [Test] + public void MessagingController_Constructor_Throws_On_Null_DataService() + { + // Arrange + + // Act, Assert + Assert.Throws(() => new MessagingController(null)); + } + + [Test] + public void AttachmentsAllowed_Returns_True_When_MessagingAllowAttachments_Setting_Is_YES() + { + this._mockMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("YES"); + var result = this._mockInternalMessagingController.Object.AttachmentsAllowed(Constants.CONTENT_ValidPortalId); + Assert.IsTrue(result); + } private void SetupDataProvider() { - //Standard DataProvider Path for Logging - _dataProvider.Setup(d => d.GetProviderPath()).Returns(""); + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); var dataTable = new DataTable("Languages"); var pkId = dataTable.Columns.Add("LanguageID", typeof(int)); @@ -139,30 +147,30 @@ private void SetupDataProvider() dataTable.PrimaryKey = new[] { pkId }; dataTable.Rows.Add(1, "en-US", "English (United States)", null, -1, "2011-05-04 09:42:11.530", -1, "2011-05-04 09:42:11.530"); - _dataProvider.Setup(x => x.GetLanguages()).Returns(dataTable.CreateDataReader()); + this._dataProvider.Setup(x => x.GetLanguages()).Returns(dataTable.CreateDataReader()); } private void SetupUsers() { - _adminUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Admin, UserID = Constants.UserID_Admin, Roles = new[] { Constants.RoleName_Administrators } }; - _hostUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Host, UserID = Constants.UserID_Host, IsSuperUser = true }; - _user12UserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_User12, UserID = Constants.UserID_User12 }; - _groupOwnerUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_FirstSocialGroupOwner, UserID = Constants.UserID_FirstSocialGroupOwner }; + this._adminUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Admin, UserID = Constants.UserID_Admin, Roles = new[] { Constants.RoleName_Administrators } }; + this._hostUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Host, UserID = Constants.UserID_Host, IsSuperUser = true }; + this._user12UserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_User12, UserID = Constants.UserID_User12 }; + this._groupOwnerUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_FirstSocialGroupOwner, UserID = Constants.UserID_FirstSocialGroupOwner }; } private void SetupPortalSettings() { - var portalSettings = new PortalSettings - { - AdministratorRoleName = Constants.RoleName_Administrators - }; + var portalSettings = new PortalSettings + { + AdministratorRoleName = Constants.RoleName_Administrators, + }; - _portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); + this._portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); } private void SetupCachingProvider() { - _mockCacheProvider.Setup(c => c.GetItem(It.IsAny())).Returns((key => + this._mockCacheProvider.Setup(c => c.GetItem(It.IsAny())).Returns(key => { if (key.Contains("Portal-1_")) { @@ -177,7 +185,7 @@ private void SetupCachingProvider() } return null; - })); + }); } private void SetupRoleProvider() @@ -187,77 +195,46 @@ private void SetupRoleProvider() var user12RoleInfoforRegisteredUsers = new UserRoleInfo { RoleName = Constants.RoleName_RegisteredUsers, RoleID = Constants.RoleID_RegisteredUsers, UserID = Constants.UserID_User12 }; var userFirstSocialGroupOwner = new UserRoleInfo { RoleName = Constants.RoleName_FirstSocialGroup, RoleID = Constants.RoleID_FirstSocialGroup, UserID = Constants.UserID_FirstSocialGroupOwner, IsOwner = true }; - _mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_Admin), It.IsAny())).Returns(new List { adminRoleInfoForAdministrators, adminRoleInfoforRegisteredUsers }); - _mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_User12), It.IsAny())).Returns(new List { user12RoleInfoforRegisteredUsers }); - _mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_FirstSocialGroupOwner), It.IsAny())).Returns(new List { userFirstSocialGroupOwner }); + this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_Admin), It.IsAny())).Returns(new List { adminRoleInfoForAdministrators, adminRoleInfoforRegisteredUsers }); + this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_User12), It.IsAny())).Returns(new List { user12RoleInfoforRegisteredUsers }); + this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_FirstSocialGroupOwner), It.IsAny())).Returns(new List { userFirstSocialGroupOwner }); } private void SetupFileControllers() { - _folderManager.Setup(f => f.GetFolder(It.IsAny())).Returns(new FolderInfo()); - _fileManager.Setup(f => f.GetFile(It.IsAny())).Returns(new FileInfo()); - _folderPermissionController.Setup(f => f.CanViewFolder(It.IsAny())).Returns(true); - } - - #endregion - - #region Constructor Tests - - [Test] - public void MessagingController_Constructor_Throws_On_Null_DataService() - { - //Arrange - - //Act, Assert - Assert.Throws(() => new MessagingController(null)); - } - - #endregion - - #region Easy Wrapper APIs Tests - - #region AttachmentsAllowed - - [Test] - public void AttachmentsAllowed_Returns_True_When_MessagingAllowAttachments_Setting_Is_YES() - { - _mockMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("YES"); - var result = _mockInternalMessagingController.Object.AttachmentsAllowed(Constants.CONTENT_ValidPortalId); - Assert.IsTrue(result); - } + this._folderManager.Setup(f => f.GetFolder(It.IsAny())).Returns(new FolderInfo()); + this._fileManager.Setup(f => f.GetFile(It.IsAny())).Returns(new FileInfo()); + this._folderPermissionController.Setup(f => f.CanViewFolder(It.IsAny())).Returns(true); + } [Test] public void IncludeAttachments_Returns_True_When_MessagingIncludeAttachments_Setting_Is_YES() { - _mockMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("YES"); - var result = _mockInternalMessagingController.Object.IncludeAttachments(Constants.CONTENT_ValidPortalId); + this._mockMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("YES"); + var result = this._mockInternalMessagingController.Object.IncludeAttachments(Constants.CONTENT_ValidPortalId); Assert.IsTrue(result); } [Test] public void AttachmentsAllowed_Returns_False_When_MessagingAllowAttachments_Setting_Is_Not_YES() { - _mockInternalMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("NO"); - var result = _mockInternalMessagingController.Object.AttachmentsAllowed(Constants.CONTENT_ValidPortalId); + this._mockInternalMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("NO"); + var result = this._mockInternalMessagingController.Object.AttachmentsAllowed(Constants.CONTENT_ValidPortalId); Assert.IsFalse(result); - } - - #endregion - - #region GetArchivedMessages - + } + [Test] public void GetArchivedMessages_Calls_DataService_GetArchiveBoxView_With_Default_Values() { - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _user12UserInfo.PortalID = Constants.PORTAL_Zero; + this._user12UserInfo.PortalID = Constants.PORTAL_Zero; - _mockInternalMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(_user12UserInfo); + this._mockInternalMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(this._user12UserInfo); - _dtMessageConversationView.Clear(); + this._dtMessageConversationView.Clear(); - _mockDataService + this._mockDataService .Setup(ds => ds.GetArchiveBoxView( Constants.UserID_User12, Constants.PORTAL_Zero, @@ -265,89 +242,77 @@ public void GetArchivedMessages_Calls_DataService_GetArchiveBoxView_With_Default It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(_dtMessageConversationView.CreateDataReader()) + .Returns(this._dtMessageConversationView.CreateDataReader()) .Verifiable(); - _mockInternalMessagingController.Object.GetArchivedMessages(Constants.UserID_User12, 0, 0); - - _mockInternalMessagingController.Verify(); - } - - #endregion - - #region GetMessageThread + this._mockInternalMessagingController.Object.GetArchivedMessages(Constants.UserID_User12, 0, 0); + this._mockInternalMessagingController.Verify(); + } + [Test] public void GetMessageThread_Calls_DataService_GetMessageThread() { var totalRecords = 0; - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _dtMessageThreadsView.Clear(); + this._dtMessageThreadsView.Clear(); - _mockDataService.Setup(ds => ds.GetMessageThread(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), ref totalRecords)).Returns(_dtMessageThreadsView.CreateDataReader()).Verifiable(); - _mockInternalMessagingController.Object.GetMessageThread(0, 0, 0, 0, "", false, ref totalRecords); - _mockDataService.Verify(); + this._mockDataService.Setup(ds => ds.GetMessageThread(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), ref totalRecords)).Returns(this._dtMessageThreadsView.CreateDataReader()).Verifiable(); + this._mockInternalMessagingController.Object.GetMessageThread(0, 0, 0, 0, string.Empty, false, ref totalRecords); + this._mockDataService.Verify(); } [Test] public void GetMessageThread_Calls_Overload_With_Default_Values() { int[] totalRecords = { 0 }; - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetMessageThread(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), MessagingController.ConstSortColumnDate, !MessagingController.ConstAscending, ref totalRecords[0])) .Verifiable(); - _mockInternalMessagingController.Object.GetMessageThread(0, 0, 0, 0, ref totalRecords[0]); - - _mockInternalMessagingController.Verify(); - } - - #endregion - - #region GetRecentSentbox + this._mockInternalMessagingController.Object.GetMessageThread(0, 0, 0, 0, ref totalRecords[0]); + this._mockInternalMessagingController.Verify(); + } + [Test] public void GetRecentSentbox_Calls_Overload_With_Default_Values() { - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetRecentSentbox(Constants.UserID_User12, MessagingController.ConstDefaultPageIndex, MessagingController.ConstDefaultPageSize)) .Verifiable(); - _mockInternalMessagingController.Object.GetRecentSentbox(Constants.UserID_User12); + this._mockInternalMessagingController.Object.GetRecentSentbox(Constants.UserID_User12); - _mockInternalMessagingController.Verify(); + this._mockInternalMessagingController.Verify(); } [Test] public void GetRecentSentbox_Calls_GetSentbox_With_Default_Values() { - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetSentbox(Constants.UserID_User12, It.IsAny(), It.IsAny(), MessagingController.ConstSortColumnDate, !MessagingController.ConstAscending)) .Verifiable(); - _mockInternalMessagingController.Object.GetRecentSentbox(Constants.UserID_User12); - - _mockInternalMessagingController.Verify(); - } - - #endregion - - #region GetSentbox + this._mockInternalMessagingController.Object.GetRecentSentbox(Constants.UserID_User12); + this._mockInternalMessagingController.Verify(); + } + [Test] public void GetSentbox_Calls_DataService_GetSentBoxView_With_Default_Values() { - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _user12UserInfo.PortalID = Constants.PORTAL_Zero; + this._user12UserInfo.PortalID = Constants.PORTAL_Zero; - _mockInternalMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(_user12UserInfo); + this._mockInternalMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(this._user12UserInfo); - _dtMessageConversationView.Clear(); + this._dtMessageConversationView.Clear(); - _mockDataService + this._mockDataService .Setup(ds => ds.GetSentBoxView( Constants.UserID_User12, Constants.PORTAL_Zero, @@ -355,126 +320,118 @@ public void GetSentbox_Calls_DataService_GetSentBoxView_With_Default_Values() It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(_dtMessageConversationView.CreateDataReader()) + .Returns(this._dtMessageConversationView.CreateDataReader()) .Verifiable(); - _mockInternalMessagingController.Object.GetSentbox( + this._mockInternalMessagingController.Object.GetSentbox( Constants.UserID_User12, 0, 0, - "", + string.Empty, false, MessageReadStatus.Any, MessageArchivedStatus.Any); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] public void GetSentbox_Calls_Overload_With_Default_Values() { - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetSentbox(Constants.UserID_User12, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), MessageReadStatus.Any, MessageArchivedStatus.UnArchived)) .Verifiable(); - _mockInternalMessagingController.Object.GetSentbox(Constants.UserID_User12, 0, 0, "", false); - - _mockInternalMessagingController.Verify(); - } - - #endregion - - #region RecipientLimit + this._mockInternalMessagingController.Object.GetSentbox(Constants.UserID_User12, 0, 0, string.Empty, false); + this._mockInternalMessagingController.Verify(); + } + [Test] public void RecipientLimit_Returns_MessagingRecipientLimit_Setting() { const int expected = 10; - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetPortalSettingAsInteger("MessagingRecipientLimit", Constants.CONTENT_ValidPortalId, It.IsAny())) .Returns(expected); - var actual = _mockInternalMessagingController.Object.RecipientLimit(Constants.CONTENT_ValidPortalId); + var actual = this._mockInternalMessagingController.Object.RecipientLimit(Constants.CONTENT_ValidPortalId); Assert.AreEqual(expected, actual); - } - - #endregion - - #region CreateMessageTests - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Null_Message() { - //Act, Assert - _messagingController.SendMessage(null, new List(), new List(), new List(), _user12UserInfo); + // Act, Assert + this._messagingController.SendMessage(null, new List(), new List(), new List(), this._user12UserInfo); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Null_Body_And_Subject() { - //Act, Assert - _messagingController.SendMessage(new Message(), new List(), new List(), new List(), _user12UserInfo); + // Act, Assert + this._messagingController.SendMessage(new Message(), new List(), new List(), new List(), this._user12UserInfo); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Null_Roles_And_Users() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; - //Act, Assert - _messagingController.SendMessage(message, null, null, null, _user12UserInfo); + // Act, Assert + this._messagingController.SendMessage(message, null, null, null, this._user12UserInfo); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Empty_Roles_And_Users_Lists() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; - //Act, Assert - _messagingController.SendMessage(message, new List(), new List(), null, _user12UserInfo); + // Act, Assert + this._messagingController.SendMessage(message, new List(), new List(), null, this._user12UserInfo); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Roles_And_Users_With_No_DisplayNames() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; - //Act, Assert - _messagingController.SendMessage(message, new List { new RoleInfo() }, new List { new UserInfo() }, null, _user12UserInfo); + // Act, Assert + this._messagingController.SendMessage(message, new List { new RoleInfo() }, new List { new UserInfo() }, null, this._user12UserInfo); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Large_Subject() { - //Arrange + // Arrange var subject = new StringBuilder(); for (var i = 0; i <= 40; i++) { subject.Append("1234567890"); } - //Arrange + // Arrange var message = new Message { Subject = subject.ToString(), Body = "body" }; - //Act, Assert - _messagingController.SendMessage(message, new List { new RoleInfo() }, new List { new UserInfo() }, null, _user12UserInfo); + // Act, Assert + this._messagingController.SendMessage(message, new List { new RoleInfo() }, new List { new UserInfo() }, null, this._user12UserInfo); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Large_To() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var roles = new List(); var users = new List(); @@ -485,141 +442,142 @@ public void MessagingController_CreateMessage_Throws_On_Large_To() users.Add(new UserInfo { DisplayName = "1234567890" }); } - //Act, Assert - _messagingController.SendMessage(message, roles, users, null, _user12UserInfo); + // Act, Assert + this._messagingController.SendMessage(message, roles, users, null, this._user12UserInfo); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Null_Sender() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; - //Act - _messagingController.SendMessage(message, new List { role }, new List { user }, null, null); + // Act + this._messagingController.SendMessage(message, new List { role }, new List { user }, null, null); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Negative_SenderID() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; var sender = new UserInfo { DisplayName = "user11" }; - //Act - _messagingController.SendMessage(message, new List { role }, new List { user }, null, sender); + // Act + this._messagingController.SendMessage(message, new List { role }, new List { user }, null, sender); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_SendingToRole_ByNonAdmin() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = Constants.USER_ElevenName, UserID = Constants.USER_ElevenId }; - var role = new RoleInfo { RoleName = Constants.RoleName_FirstSocialGroup, RoleID = Constants.RoleID_FirstSocialGroup }; + var role = new RoleInfo { RoleName = Constants.RoleName_FirstSocialGroup, RoleID = Constants.RoleID_FirstSocialGroup }; var mockDataService = new Mock(); var messagingController = new MessagingController(mockDataService.Object); - _dtMessageRecipients.Clear(); - mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(_dtMessageRecipients.CreateDataReader()); + this._dtMessageRecipients.Clear(); + mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(this._dtMessageRecipients.CreateDataReader()); - //Act - messagingController.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, _user12UserInfo); + // Act + messagingController.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, this._user12UserInfo); } - //[Test] + // [Test] [ExpectedException(typeof(AttachmentsNotAllowed))] public void MessagingController_CreateMessage_Throws_On_Passing_Attachments_When_Its_Not_Enabled() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = Constants.USER_ElevenName, UserID = Constants.USER_ElevenId }; var mockDataService = new Mock(); var messagingController = new MessagingController(mockDataService.Object); - //disable caching - _mockCacheProvider.Setup(mc => mc.GetItem(It.IsAny())).Returns(null); + // disable caching + this._mockCacheProvider.Setup(mc => mc.GetItem(It.IsAny())).Returns(null); - _dtPortalSettings.Clear(); - _dtPortalSettings.Rows.Add(Constants.PORTALSETTING_MessagingAllowAttachments_Name, Constants.PORTALSETTING_MessagingAllowAttachments_Value_NO, Constants.CULTURE_EN_US); - _dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(_dtPortalSettings.CreateDataReader()); + this._dtPortalSettings.Clear(); + this._dtPortalSettings.Rows.Add(Constants.PORTALSETTING_MessagingAllowAttachments_Name, Constants.PORTALSETTING_MessagingAllowAttachments_Value_NO, Constants.CULTURE_EN_US); + this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this._dtPortalSettings.CreateDataReader()); - _dtMessageRecipients.Clear(); - mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(_dtMessageRecipients.CreateDataReader()); + this._dtMessageRecipients.Clear(); + mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(this._dtMessageRecipients.CreateDataReader()); - //Act - messagingController.SendMessage(message, null, new List { user }, new List { Constants.FOLDER_ValidFileId }, _user12UserInfo); + // Act + messagingController.SendMessage(message, null, new List { user }, new List { Constants.FOLDER_ValidFileId }, this._user12UserInfo); } [Test] public void MessagingController_CreateMessage_Calls_DataService_SaveSocialMessage_On_Valid_Message() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, this._adminUserInfo); - //Assert - _mockDataService.Verify(ds => ds.SaveMessage(It.Is(v => v.PortalID == Constants.PORTAL_Zero && v.Subject == "subject" + // Assert + this._mockDataService.Verify(ds => ds.SaveMessage( + It.Is(v => v.PortalID == Constants.PORTAL_Zero && v.Subject == "subject" && v.Body == "body" && v.To == "role1,user1" - && v.SenderUserID == _adminUserInfo.UserID) - , It.IsAny() - , It.IsAny())); + && v.SenderUserID == this._adminUserInfo.UserID), + It.IsAny(), + It.IsAny())); } [Test] public void MessagingController_Filters_Input_When_ProfanityFilter_Is_Enabled() { - //Arrange + // Arrange var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; var message = new Message { Subject = "subject", Body = "body" }; - _dtMessageRecipients.Clear(); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(_dtMessageRecipients.CreateDataReader()); + this._dtMessageRecipients.Clear(); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController + this._mockMessagingController .Setup(mc => mc.GetPortalSetting("MessagingProfanityFilters", It.IsAny(), It.IsAny())) .Returns("YES"); - _mockMessagingController.Setup(mc => mc.InputFilter("subject")).Returns("subject_filtered"); - _mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); - _mockInternalMessagingController.Setup(mc => mc.GetMessageRecipient(It.IsAny(), It.IsAny())); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.InputFilter("subject")).Returns("subject_filtered"); + this._mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipient(It.IsAny(), It.IsAny())); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, this._adminUserInfo); - //Assert + // Assert Assert.AreEqual("subject_filtered", message.Subject); Assert.AreEqual("body_filtered", message.Body); } @@ -627,71 +585,71 @@ public void MessagingController_Filters_Input_When_ProfanityFilter_Is_Enabled() [Test] public void MessagingController_CreateMessage_For_CommonUser_Calls_DataService_SaveSocialMessageRecipient_Then_CreateSocialMessageRecipientsForRole() { - //Arrange + // Arrange var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; var message = new Message { Subject = "subject", Body = "body" }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - //this pattern is based on: http://dpwhelan.com/blog/software-development/moq-sequences/ + // this pattern is based on: http://dpwhelan.com/blog/software-development/moq-sequences/ var callingSequence = 0; - //Arrange for Assert - _mockDataService.Setup(ds => ds.CreateMessageRecipientsForRole(It.IsAny(), It.IsAny(), It.IsAny())).Callback(() => Assert.That(callingSequence++, Is.EqualTo(0))); - _mockDataService.Setup(ds => ds.SaveMessageRecipient(It.IsAny(), It.IsAny())).Callback(() => Assert.That(callingSequence++, Is.GreaterThan(0))); + // Arrange for Assert + this._mockDataService.Setup(ds => ds.CreateMessageRecipientsForRole(It.IsAny(), It.IsAny(), It.IsAny())).Callback(() => Assert.That(callingSequence++, Is.EqualTo(0))); + this._mockDataService.Setup(ds => ds.SaveMessageRecipient(It.IsAny(), It.IsAny())).Callback(() => Assert.That(callingSequence++, Is.GreaterThan(0))); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, this._adminUserInfo); - //SaveMessageRecipient is called twice, one for sent message and second for receive + // SaveMessageRecipient is called twice, one for sent message and second for receive } [Test] public void MessagingController_CreateMessage_Trims_Comma_For_One_User() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = Constants.USER_TenName, UserID = Constants.USER_TenId }; var sender = new UserInfo { DisplayName = Constants.USER_ElevenName, UserID = Constants.USER_ElevenId }; var mockDataService = new Mock(); var messagingController = new MessagingController(mockDataService.Object); - _mockInternalMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), _user12UserInfo.PortalID, It.IsAny())).Returns(0); + this._mockInternalMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), this._user12UserInfo.PortalID, It.IsAny())).Returns(0); mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_ElevenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act + // Act messagingController.SendMessage(message, new List(), new List { user }, null, sender); - //Assert + // Assert Assert.AreEqual(message.To, Constants.USER_TenName); } [Test] public void MessagingController_CreateMessage_Trims_Comma_For_Two_Users() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user10 = new UserInfo { DisplayName = Constants.USER_TenName, UserID = Constants.USER_TenId }; var user11 = new UserInfo { DisplayName = Constants.USER_ElevenName, UserID = Constants.USER_ElevenId }; @@ -699,619 +657,603 @@ public void MessagingController_CreateMessage_Trims_Comma_For_Two_Users() var mockDataService = new Mock(); var messagingController = new MessagingController(mockDataService.Object); - _mockInternalMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), _user12UserInfo.PortalID, It.IsAny())).Returns(0); + this._mockInternalMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), this._user12UserInfo.PortalID, It.IsAny())).Returns(0); - _dtMessageRecipients.Clear(); + this._dtMessageRecipients.Clear(); var recipientId = 0; - //_dtMessageRecipients.Rows.Add(Constants.Messaging_RecipientId_2, Constants.USER_Null, Constants.Messaging_UnReadMessage, Constants.Messaging_UnArchivedMessage); - + + // _dtMessageRecipients.Rows.Add(Constants.Messaging_RecipientId_2, Constants.USER_Null, Constants.Messaging_UnReadMessage, Constants.Messaging_UnArchivedMessage); mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())) - .Callback(() => _dtMessageRecipients.Rows.Add(recipientId++, Constants.USER_Null, Constants.Messaging_UnReadMessage, Constants.Messaging_UnArchivedMessage)) - .Returns(() => _dtMessageRecipients.CreateDataReader()); + .Callback(() => this._dtMessageRecipients.Rows.Add(recipientId++, Constants.USER_Null, Constants.Messaging_UnReadMessage, Constants.Messaging_UnArchivedMessage)) + .Returns(() => this._dtMessageRecipients.CreateDataReader()); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act + // Act messagingController.SendMessage(message, new List(), new List { user10, user11 }, null, sender); - //Assert + // Assert Assert.AreEqual(message.To, Constants.USER_TenName + "," + Constants.USER_ElevenName); } [Test] public void MessagingController_CreateMessage_Trims_Comma_For_One_Role() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var role = new RoleInfo { RoleName = Constants.RoleName_Administrators }; - _dtMessageRecipients.Clear(); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(_dtMessageRecipients.CreateDataReader()); + this._dtMessageRecipients.Clear(); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List(), null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List(), null, this._adminUserInfo); - //Assert + // Assert Assert.AreEqual(message.To, Constants.RoleName_Administrators); } [Test] public void MessagingController_CreateMessage_Trims_Comma_For_Two_Roles() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var role1 = new RoleInfo { RoleName = Constants.RoleName_Administrators }; var role2 = new RoleInfo { RoleName = Constants.RoleName_Subscribers }; - _dtMessageRecipients.Clear(); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(_dtMessageRecipients.CreateDataReader()); + this._dtMessageRecipients.Clear(); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())).Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role1, role2 }, new List(), null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role1, role2 }, new List(), null, this._adminUserInfo); - //Assert + // Assert Assert.AreEqual(message.To, Constants.RoleName_Administrators + "," + Constants.RoleName_Subscribers); } [Test] public void MessagingController_CreateMessage_Calls_DataService_SaveSocialMessageAttachment_On_Passing_Attachments() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, this._adminUserInfo); - //Assert - _mockDataService.Verify(ds => ds.SaveMessageAttachment(It.Is(v => v.MessageID == message.MessageID), It.IsAny())); + // Assert + this._mockDataService.Verify(ds => ds.SaveMessageAttachment(It.Is(v => v.MessageID == message.MessageID), It.IsAny())); } [Test] public void MessagingController_CreateMessage_Calls_DataService_CreateSocialMessageRecipientsForRole_On_Passing_Role_ByAdmin() { - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var role = new RoleInfo { RoleName = Constants.RoleName_RegisteredUsers, RoleID = Constants.RoleID_RegisteredUsers }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _user12UserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._user12UserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { _user12UserInfo }, new List { Constants.FOLDER_ValidFileId }, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { this._user12UserInfo }, new List { Constants.FOLDER_ValidFileId }, this._adminUserInfo); - //Assert - _mockDataService.Verify(ds => ds.CreateMessageRecipientsForRole(message.MessageID, Constants.RoleID_RegisteredUsers.ToString(), It.IsAny())); + // Assert + this._mockDataService.Verify(ds => ds.CreateMessageRecipientsForRole(message.MessageID, Constants.RoleID_RegisteredUsers.ToString(), It.IsAny())); } [Test] public void MessagingController_CreateMessage_Calls_DataService_CreateSocialMessageRecipientsForRole_On_Passing_Role_ByHost() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var role = new RoleInfo { RoleName = Constants.RoleName_RegisteredUsers, RoleID = Constants.RoleID_RegisteredUsers }; var mockDataService = new Mock(); var messagingController = new MessagingController(mockDataService.Object); - mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _user12UserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._user12UserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _hostUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._hostUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - messagingController.SendMessage(message, new List { role }, new List { _user12UserInfo }, new List { Constants.FOLDER_ValidFileId }, _hostUserInfo); + // Act + messagingController.SendMessage(message, new List { role }, new List { this._user12UserInfo }, new List { Constants.FOLDER_ValidFileId }, this._hostUserInfo); - //Assert + // Assert mockDataService.Verify(ds => ds.CreateMessageRecipientsForRole(message.MessageID, Constants.RoleID_RegisteredUsers.ToString(), It.IsAny())); } [Test] public void MessagingController_CreateMessage_Calls_DataService_CreateSocialMessageRecipientsForRole_On_Passing_Roles() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role1 = new RoleInfo { RoleName = "role1", RoleID = Constants.RoleID_RegisteredUsers }; var role2 = new RoleInfo { RoleName = "role2", RoleID = Constants.RoleID_Administrators }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role1, role2 }, new List { user }, new List { Constants.FOLDER_ValidFileId }, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role1, role2 }, new List { user }, new List { Constants.FOLDER_ValidFileId }, this._adminUserInfo); - //Assert - _mockDataService.Verify(ds => ds.CreateMessageRecipientsForRole(message.MessageID, Constants.RoleID_RegisteredUsers + "," + Constants.RoleID_Administrators, It.IsAny())); + // Assert + this._mockDataService.Verify(ds => ds.CreateMessageRecipientsForRole(message.MessageID, Constants.RoleID_RegisteredUsers + "," + Constants.RoleID_Administrators, It.IsAny())); } [Test] public void MessagingController_CreateMessage_Calls_DataService_CreateSocialMessageRecipientsForRole_On_Passing_Roles_ByRoleOwner() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = Constants.RoleName_FirstSocialGroup, RoleID = Constants.RoleID_FirstSocialGroup }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockInternalMessagingController.Setup(mc => mc.GetMessageRecipient(It.IsAny(), It.IsAny())); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipient(It.IsAny(), It.IsAny())); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, _groupOwnerUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, this._groupOwnerUserInfo); - //Assert - _mockDataService.Verify(ds => ds.CreateMessageRecipientsForRole(It.IsAny(), It.IsAny(), It.IsAny())); + // Assert + this._mockDataService.Verify(ds => ds.CreateMessageRecipientsForRole(It.IsAny(), It.IsAny(), It.IsAny())); } [Test] public void MessagingController_CreateMessage_Calls_DataService_SaveSocialMessageRecipient_On_Passing_Users() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, this._adminUserInfo); - //Assert - _mockDataService.Verify(ds => ds.SaveMessageRecipient(It.Is(v => v.MessageID == message.MessageID && v.UserID == user.UserID), It.IsAny())); + // Assert + this._mockDataService.Verify(ds => ds.SaveMessageRecipient(It.Is(v => v.MessageID == message.MessageID && v.UserID == user.UserID), It.IsAny())); } [Test] public void MessagingController_CreateMessage_Sets_ReplyAll_To_False_On_Passing_Roles() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1", RoleID = Constants.RoleID_RegisteredUsers }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, new List { Constants.FOLDER_ValidFileId }, this._adminUserInfo); - //Assert + // Assert Assert.AreEqual(message.ReplyAllAllowed, false); } [Test] public void MessagingController_CreateMessage_Sets_ReplyAll_To_True_On_Passing_User() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var mockDataService = new Mock(); var messagingController = new MessagingController(mockDataService.Object); mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - messagingController.SendMessage(message, new List(), new List { user }, new List { Constants.FOLDER_ValidFileId }, _adminUserInfo); + // Act + messagingController.SendMessage(message, new List(), new List { user }, new List { Constants.FOLDER_ValidFileId }, this._adminUserInfo); - //Assert + // Assert Assert.AreEqual(message.ReplyAllAllowed, true); } [Test] public void MessagingController_CreateMessage_Adds_Sender_As_Recipient_When_Not_Aready_A_Recipient() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, this._adminUserInfo); - //Assert - _mockDataService.Verify(ds => ds.SaveMessageRecipient(It.Is(v => v.MessageID == message.MessageID && v.UserID == _adminUserInfo.UserID), It.IsAny())); + // Assert + this._mockDataService.Verify(ds => ds.SaveMessageRecipient(It.Is(v => v.MessageID == message.MessageID && v.UserID == this._adminUserInfo.UserID), It.IsAny())); } [Test] public void MessagingController_CreateMessage_Marks_Message_As_Dispatched_For_Sender_When_Not_Already_A_Recipient() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - _mockDataService.Setup(ds => ds.SaveMessageRecipient(It.Is(mr => mr.UserID == _adminUserInfo.UserID), It.IsAny())).Returns(Constants.Messaging_RecipientId_1); + this._mockDataService.Setup(ds => ds.SaveMessageRecipient(It.Is(mr => mr.UserID == this._adminUserInfo.UserID), It.IsAny())).Returns(Constants.Messaging_RecipientId_1); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, _adminUserInfo); + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, this._adminUserInfo); - //Assert - _mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1)); + // Assert + this._mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1)); } [Test] public void MessagingController_CreateMessage_Does_Not_Mark_Message_As_Dispatched_For_Sender_When_Already_A_Recipient() { - //Arrange + // Arrange var message = new Message { Subject = "subject", Body = "body" }; var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; var role = new RoleInfo { RoleName = "role1" }; - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), Constants.USER_TenId)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), _adminUserInfo.UserID)) - .Callback(SetupDataTables) - .Returns(_dtMessageRecipients.CreateDataReader()); + this._mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), this._adminUserInfo.UserID)) + .Callback(this.SetupDataTables) + .Returns(this._dtMessageRecipients.CreateDataReader()); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(ims => ims.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns((MessageRecipient)null); - _mockDataService.Setup(ds => ds.SaveMessageRecipient(It.Is(mr => mr.UserID == _adminUserInfo.UserID), It.IsAny())).Returns(Constants.Messaging_RecipientId_1); + this._mockDataService.Setup(ds => ds.SaveMessageRecipient(It.Is(mr => mr.UserID == this._adminUserInfo.UserID), It.IsAny())).Returns(Constants.Messaging_RecipientId_1); - //Act - _mockMessagingController.Object.SendMessage(message, new List { role }, new List { user, _adminUserInfo }, null, _adminUserInfo); - - //Assert - _mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1), Times.Never()); - } - - #endregion - - #region ReplyMessageTests + // Act + this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user, this._adminUserInfo }, null, this._adminUserInfo); + // Assert + this._mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1), Times.Never()); + } + [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_ReplyMessage_Throws_On_Null_Sender() { - //Arrange + // Arrange - //Act - _internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, "body", null, null); + // Act + this._internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, "body", null, null); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_ReplyMessage_Throws_On_Negative_SenderID() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11" }; - //Act - _internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, "body", null, sender); + // Act + this._internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, "body", null, sender); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_ReplyMessage_Throws_On_Null_Subject() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11", UserID = Constants.USER_TenId }; - //Act, Assert - _internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, null, null, sender); + // Act, Assert + this._internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, null, null, sender); } [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_ReplyMessage_Throws_On_Empty_Subject() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11", UserID = Constants.USER_TenId }; - //Act, Assert - _internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, "", null, sender); + // Act, Assert + this._internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, string.Empty, null, sender); } [Test] [ExpectedException(typeof(AttachmentsNotAllowed))] public void MessagingController_ReplyMessage_Throws_On_Passing_Attachments_When_Its_Not_Enabled() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11", UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); - _mockInternalMessagingController.Setup(imc => imc.AttachmentsAllowed(Constants.PORTAL_Zero)).Returns(false); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); + this._mockInternalMessagingController.Setup(imc => imc.AttachmentsAllowed(Constants.PORTAL_Zero)).Returns(false); - //Act, Assert - _internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, "body", new List { Constants.FOLDER_ValidFileId }, sender); + // Act, Assert + this._internalMessagingController.ReplyMessage(Constants.Messaging_MessageId_1, "body", new List { Constants.FOLDER_ValidFileId }, sender); } [Test] public void MessagingController_ReplyMessage_Filters_Input_When_ProfanityFilter_Is_Enabled() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11", UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); - _mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); + this._mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); + this._mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); - _mockMessagingController + this._mockMessagingController .Setup(mc => mc.GetPortalSetting("MessagingProfanityFilters", It.IsAny(), It.IsAny())) .Returns("YES"); - _mockInternalMessagingController.Setup(imc => imc.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns(new MessageRecipient()); + this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns(new MessageRecipient()); - _mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); + this._mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); - _mockDataService.Verify(ds => ds.CreateMessageReply(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())); + this._mockDataService.Verify(ds => ds.CreateMessageReply(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())); } [Test] [ExpectedException(typeof(MessageOrRecipientNotFoundException))] public void MessagingController_ReplyMessage_Throws_When_Message_Or_Recipient_Are_Not_Found() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11", UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); - _mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); + this._mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); + this._mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); - _mockMessagingController + this._mockMessagingController .Setup(mc => mc.GetPortalSetting("MessagingProfanityFilters", It.IsAny(), It.IsAny())) .Returns("NO"); - _mockDataService.Setup(ds => ds.CreateMessageReply(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(-1); + this._mockDataService.Setup(ds => ds.CreateMessageReply(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(-1); - _mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); + this._mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); } [Test] public void MessagingController_ReplyMessage_Marks_Message_As_Read_By_Sender() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11", UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); - _mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); + this._mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); + this._mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); - _mockMessagingController + this._mockMessagingController .Setup(mc => mc.GetPortalSetting("MessagingProfanityFilters", It.IsAny(), It.IsAny())) .Returns("NO"); - _mockInternalMessagingController.Setup(imc => imc.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns(new MessageRecipient()); + this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns(new MessageRecipient()); - _mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); + this._mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); - _mockInternalMessagingController.Verify(imc => imc.MarkRead(It.IsAny(), sender.UserID)); + this._mockInternalMessagingController.Verify(imc => imc.MarkRead(It.IsAny(), sender.UserID)); } [Test] public void MessagingController_ReplyMessage_Marks_Message_As_Dispatched_For_Sender() { - //Arrange + // Arrange var sender = new UserInfo { DisplayName = "user11", UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); - _mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); + this._mockMessagingController.Setup(mc => mc.InputFilter("body")).Returns("body_filtered"); + this._mockMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(new UserInfo()); - _mockMessagingController + this._mockMessagingController .Setup(mc => mc.GetPortalSetting("MessagingProfanityFilters", It.IsAny(), It.IsAny())) .Returns("NO"); - _mockInternalMessagingController.Setup(imc => imc.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns(new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_1 }); - - _mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); + this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipient(It.IsAny(), It.IsAny())).Returns(new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_1 }); - _mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1)); - } - - #endregion - - #region Setting Message Status Tests + this._mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); + this._mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1)); + } + [Test] public void MessagingController_SetReadMessage_Calls_DataService_UpdateSocialMessageReadStatus() { - //Arrange + // Arrange var messageInstance = CreateValidMessage(); var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; - //Act - _internalMessagingController.MarkRead(messageInstance.ConversationId, user.UserID); + // Act + this._internalMessagingController.MarkRead(messageInstance.ConversationId, user.UserID); - //Assert - _mockDataService.Verify(ds => ds.UpdateMessageReadStatus(messageInstance.ConversationId, user.UserID, true)); + // Assert + this._mockDataService.Verify(ds => ds.UpdateMessageReadStatus(messageInstance.ConversationId, user.UserID, true)); } [Test] public void MessagingController_SetUnReadMessage_Calls_DataService_UpdateSocialMessageReadStatus() { - //Arrange + // Arrange var messageInstance = CreateValidMessage(); var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; - //Act - _internalMessagingController.MarkUnRead(messageInstance.ConversationId, user.UserID); + // Act + this._internalMessagingController.MarkUnRead(messageInstance.ConversationId, user.UserID); - //Assert - _mockDataService.Verify(ds => ds.UpdateMessageReadStatus(messageInstance.ConversationId, user.UserID, false)); + // Assert + this._mockDataService.Verify(ds => ds.UpdateMessageReadStatus(messageInstance.ConversationId, user.UserID, false)); } [Test] public void MessagingController_SetArchivedMessage_Calls_DataService_UpdateSocialMessageArchivedStatus() { - //Arrange + // Arrange var messageInstance = CreateValidMessage(); var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; - //Act - _internalMessagingController.MarkArchived(messageInstance.ConversationId, user.UserID); + // Act + this._internalMessagingController.MarkArchived(messageInstance.ConversationId, user.UserID); - //Assert - _mockDataService.Verify(ds => ds.UpdateMessageArchivedStatus(messageInstance.ConversationId, user.UserID, true)); + // Assert + this._mockDataService.Verify(ds => ds.UpdateMessageArchivedStatus(messageInstance.ConversationId, user.UserID, true)); } [Test] public void MessagingController_SetUnArchivedMessage_Calls_DataService_UpdateSocialMessageArchivedStatus() { - //Arrange + // Arrange var messageInstance = CreateValidMessage(); var user = new UserInfo { DisplayName = "user1", UserID = Constants.USER_TenId }; - //Act - _internalMessagingController.MarkUnArchived(messageInstance.ConversationId, user.UserID); - - //Assert - _mockDataService.Verify(ds => ds.UpdateMessageArchivedStatus(messageInstance.ConversationId, user.UserID, false)); - } - - #endregion - - #region GetMessageRecipient + // Act + this._internalMessagingController.MarkUnArchived(messageInstance.ConversationId, user.UserID); + // Assert + this._mockDataService.Verify(ds => ds.UpdateMessageArchivedStatus(messageInstance.ConversationId, user.UserID, false)); + } + [Test] public void GetSocialMessageRecipient_Calls_DataService_GetSocialMessageRecipientByMessageAndUser() { - _dtMessageRecipients.Clear(); - _mockDataService + this._dtMessageRecipients.Clear(); + this._mockDataService .Setup(ds => ds.GetMessageRecipientByMessageAndUser(Constants.Messaging_MessageId_1, Constants.UserID_User12)) - .Returns(_dtMessageRecipients.CreateDataReader()) + .Returns(this._dtMessageRecipients.CreateDataReader()) .Verifiable(); - _internalMessagingController.GetMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - - _mockDataService.Verify(); - } - - #endregion - - #region WaitTimeForNextMessage + this._internalMessagingController.GetMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + this._mockDataService.Verify(); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void WaitTimeForNextMessage_Throws_On_Null_Sender() { - _internalMessagingController.WaitTimeForNextMessage(null); + this._internalMessagingController.WaitTimeForNextMessage(null); } [Test] public void WaitTimeForNextMessage_Returns_Zero_When_MessagingThrottlingInterval_Is_Zero() { - _user12UserInfo.PortalID = Constants.CONTENT_ValidPortalId; - _mockMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), _user12UserInfo.PortalID, 0.5)).Returns(0.5); + this._user12UserInfo.PortalID = Constants.CONTENT_ValidPortalId; + this._mockMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), this._user12UserInfo.PortalID, 0.5)).Returns(0.5); - var result = _mockInternalMessagingController.Object.WaitTimeForNextMessage(_user12UserInfo); + var result = this._mockInternalMessagingController.Object.WaitTimeForNextMessage(this._user12UserInfo); Assert.AreEqual(0, result); } @@ -1319,12 +1261,12 @@ public void WaitTimeForNextMessage_Returns_Zero_When_MessagingThrottlingInterval [Test] public void WaitTimeForNextMessage_Returns_Zero_When_Sender_Is_Admin_Or_Host() { - _adminUserInfo.PortalID = Constants.CONTENT_ValidPortalId; + this._adminUserInfo.PortalID = Constants.CONTENT_ValidPortalId; - _mockMessagingController.Setup(mc => mc.GetPortalSettingAsInteger(It.IsAny(), _adminUserInfo.PortalID, Null.NullInteger)).Returns(1); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(true); + this._mockMessagingController.Setup(mc => mc.GetPortalSettingAsInteger(It.IsAny(), this._adminUserInfo.PortalID, Null.NullInteger)).Returns(1); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(true); - var result = _mockInternalMessagingController.Object.WaitTimeForNextMessage(_adminUserInfo); + var result = this._mockInternalMessagingController.Object.WaitTimeForNextMessage(this._adminUserInfo); Assert.AreEqual(0, result); } @@ -1332,14 +1274,14 @@ public void WaitTimeForNextMessage_Returns_Zero_When_Sender_Is_Admin_Or_Host() [Test] public void WaitTimeForNextMessage_Returns_Zero_When_The_User_Has_No_Previous_Conversations() { - _user12UserInfo.PortalID = Constants.CONTENT_ValidPortalId; + this._user12UserInfo.PortalID = Constants.CONTENT_ValidPortalId; - _mockMessagingController.Setup(mc => mc.GetPortalSettingAsInteger(It.IsAny(), _user12UserInfo.PortalID, Null.NullInteger)).Returns(1); - _mockMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(false); + this._mockMessagingController.Setup(mc => mc.GetPortalSettingAsInteger(It.IsAny(), this._user12UserInfo.PortalID, Null.NullInteger)).Returns(1); + this._mockMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(false); - _mockInternalMessagingController.Setup(mc => mc.GetLastSentMessage(_user12UserInfo)).Returns((Message) null); + this._mockInternalMessagingController.Setup(mc => mc.GetLastSentMessage(this._user12UserInfo)).Returns((Message)null); - var result = _mockInternalMessagingController.Object.WaitTimeForNextMessage(_user12UserInfo); + var result = this._mockInternalMessagingController.Object.WaitTimeForNextMessage(this._user12UserInfo); Assert.AreEqual(0, result); } @@ -1353,186 +1295,140 @@ public void WaitTimeForNextMessage_Returns_The_Number_Of_Seconds_Since_Last_Mess var culture = CultureInfo.GetCultureInfo("en-US"); var actualDate = DateTime.Parse(actualDateString, culture); var lastMessageDate = DateTime.Parse(lastMessageDateString, culture); - _user12UserInfo.PortalID = Constants.CONTENT_ValidPortalId; - _mockInternalMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), _user12UserInfo.PortalID, It.IsAny())).Returns(throttlingInterval); - _mockInternalMessagingController.Setup(mc => mc.IsAdminOrHost(_adminUserInfo)).Returns(false); - _dtMessages.Clear(); - _dtMessages.Rows.Add(-1, 1, 1, "", "", "", "", -1, -1, -1, -1, lastMessageDate, -1, Null.NullDate); - var dr = _dtMessages.CreateDataReader(); + this._user12UserInfo.PortalID = Constants.CONTENT_ValidPortalId; + this._mockInternalMessagingController.Setup(mc => mc.GetPortalSettingAsDouble(It.IsAny(), this._user12UserInfo.PortalID, It.IsAny())).Returns(throttlingInterval); + this._mockInternalMessagingController.Setup(mc => mc.IsAdminOrHost(this._adminUserInfo)).Returns(false); + this._dtMessages.Clear(); + this._dtMessages.Rows.Add(-1, 1, 1, string.Empty, string.Empty, string.Empty, string.Empty, -1, -1, -1, -1, lastMessageDate, -1, Null.NullDate); + var dr = this._dtMessages.CreateDataReader(); var message = CBO.FillObject(dr); - _mockInternalMessagingController.Setup(mc => mc.GetLastSentMessage(It.IsAny())).Returns(message); - _mockInternalMessagingController.Setup(mc => mc.GetDateTimeNow()).Returns(actualDate); - var result = _mockInternalMessagingController.Object.WaitTimeForNextMessage(_user12UserInfo); + this._mockInternalMessagingController.Setup(mc => mc.GetLastSentMessage(It.IsAny())).Returns(message); + this._mockInternalMessagingController.Setup(mc => mc.GetDateTimeNow()).Returns(actualDate); + var result = this._mockInternalMessagingController.Object.WaitTimeForNextMessage(this._user12UserInfo); Assert.AreEqual(expected, result); - } - - #endregion - - #region GetInbox - + } + [Test] public void GetInbox_Calls_DataService_GetMessageBoxView() { - DataService.RegisterInstance(_mockDataService.Object); + DataService.RegisterInstance(this._mockDataService.Object); - _dtMessageConversationView.Clear(); + this._dtMessageConversationView.Clear(); - _user12UserInfo.PortalID = Constants.PORTAL_Zero; + this._user12UserInfo.PortalID = Constants.PORTAL_Zero; - _mockInternalMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(_user12UserInfo); - _mockDataService.Setup(ds => ds.GetInBoxView(It.IsAny(), Constants.PORTAL_Zero, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), MessageReadStatus.Any, MessageArchivedStatus.Any, MessageSentStatus.Received)).Returns(_dtMessageConversationView.CreateDataReader()).Verifiable(); - _mockInternalMessagingController.Object.GetInbox(0, 0, 0, "", false, MessageReadStatus.Any, MessageArchivedStatus.Any); - _mockDataService.Verify(); + this._mockInternalMessagingController.Setup(mc => mc.GetCurrentUserInfo()).Returns(this._user12UserInfo); + this._mockDataService.Setup(ds => ds.GetInBoxView(It.IsAny(), Constants.PORTAL_Zero, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), MessageReadStatus.Any, MessageArchivedStatus.Any, MessageSentStatus.Received)).Returns(this._dtMessageConversationView.CreateDataReader()).Verifiable(); + this._mockInternalMessagingController.Object.GetInbox(0, 0, 0, string.Empty, false, MessageReadStatus.Any, MessageArchivedStatus.Any); + this._mockDataService.Verify(); } [Test] public void GetInbox_Calls_Overload_With_Default_Values() { - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetInbox(Constants.UserID_User12, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), MessageReadStatus.Any, MessageArchivedStatus.UnArchived)) .Verifiable(); - _mockInternalMessagingController.Object.GetInbox(Constants.UserID_User12, 0, 0, "", false); - - _mockInternalMessagingController.Verify(); - } - - #endregion - - #region GetRecentInbox + this._mockInternalMessagingController.Object.GetInbox(Constants.UserID_User12, 0, 0, string.Empty, false); + this._mockInternalMessagingController.Verify(); + } + [Test] public void GetRecentInbox_Calls_GetInbox_With_Default_Values() { - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetInbox(Constants.UserID_User12, It.IsAny(), It.IsAny(), MessagingController.ConstSortColumnDate, !MessagingController.ConstAscending)) .Verifiable(); - _mockInternalMessagingController.Object.GetRecentInbox(Constants.UserID_User12, 0, 0); + this._mockInternalMessagingController.Object.GetRecentInbox(Constants.UserID_User12, 0, 0); - _mockInternalMessagingController.Verify(); + this._mockInternalMessagingController.Verify(); } [Test] public void GetRecentInbox_Calls_Overload_With_Default_Values() { - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetRecentInbox(Constants.UserID_User12, MessagingController.ConstDefaultPageIndex, MessagingController.ConstDefaultPageSize)) .Verifiable(); - _mockInternalMessagingController.Object.GetRecentInbox(Constants.UserID_User12); - - _mockInternalMessagingController.Verify(); - } - - #endregion - - #region CountArchivedMessagesByConversation + this._mockInternalMessagingController.Object.GetRecentInbox(Constants.UserID_User12); + this._mockInternalMessagingController.Verify(); + } + [Test] public void CountArchivedMessagesByConversation_Calls_DataService_CountArchivedMessagesByConversation() { - _mockDataService.Setup(ds => ds.CountArchivedMessagesByConversation(It.IsAny())).Verifiable(); - _internalMessagingController.CountArchivedMessagesByConversation(1); - _mockDataService.Verify(); - } - - #endregion - - #region CountMessagesByConversation - + this._mockDataService.Setup(ds => ds.CountArchivedMessagesByConversation(It.IsAny())).Verifiable(); + this._internalMessagingController.CountArchivedMessagesByConversation(1); + this._mockDataService.Verify(); + } + [Test] public void CountMessagesByConversation_Calls_DataService_CountMessagesByConversation() { - _mockDataService.Setup(ds => ds.CountMessagesByConversation(It.IsAny())).Verifiable(); - _internalMessagingController.CountMessagesByConversation(1); - _mockDataService.Verify(); - } - - #endregion - - #region CountConversations - + this._mockDataService.Setup(ds => ds.CountMessagesByConversation(It.IsAny())).Verifiable(); + this._internalMessagingController.CountMessagesByConversation(1); + this._mockDataService.Verify(); + } + [Test] public void CountConversations_Calls_DataService_CountTotalConversations() { - _mockDataService.Setup(ds => ds.CountTotalConversations(It.IsAny(), It.IsAny())).Verifiable(); - _internalMessagingController.CountConversations(Constants.UserID_User12, Constants.PORTAL_Zero); - _mockDataService.Verify(); - } - - #endregion - - #region CountUnreadMessages - + this._mockDataService.Setup(ds => ds.CountTotalConversations(It.IsAny(), It.IsAny())).Verifiable(); + this._internalMessagingController.CountConversations(Constants.UserID_User12, Constants.PORTAL_Zero); + this._mockDataService.Verify(); + } + [Test] public void CountUnreadMessages_Calls_DataService_CountNewThreads() { - _mockDataService.Setup(ds => ds.CountNewThreads(It.IsAny(), It.IsAny())).Verifiable(); - _internalMessagingController.CountUnreadMessages(Constants.UserID_User12, Constants.PORTAL_Zero); - _mockDataService.Verify(); - } - - #endregion - - #region CountSentMessages - + this._mockDataService.Setup(ds => ds.CountNewThreads(It.IsAny(), It.IsAny())).Verifiable(); + this._internalMessagingController.CountUnreadMessages(Constants.UserID_User12, Constants.PORTAL_Zero); + this._mockDataService.Verify(); + } + [Test] public void CountSentMessages_Calls_DataService_CountSentMessages() { - _mockDataService.Setup(ds => ds.CountSentMessages(It.IsAny(), It.IsAny())).Verifiable(); - _internalMessagingController.CountSentMessages(Constants.UserID_User12, Constants.PORTAL_Zero); - _mockDataService.Verify(); - } - - #endregion - - #region CountArchivedMessages - + this._mockDataService.Setup(ds => ds.CountSentMessages(It.IsAny(), It.IsAny())).Verifiable(); + this._internalMessagingController.CountSentMessages(Constants.UserID_User12, Constants.PORTAL_Zero); + this._mockDataService.Verify(); + } + [Test] public void CountArchivedMessages_Calls_DataService_CountArchivedMessages() { - _mockDataService.Setup(ds => ds.CountArchivedMessages(It.IsAny(), It.IsAny())).Verifiable(); - _internalMessagingController.CountArchivedMessages(Constants.UserID_User12, Constants.PORTAL_Zero); - _mockDataService.Verify(); - } - - #endregion - - #region DeleteMessageRecipient - + this._mockDataService.Setup(ds => ds.CountArchivedMessages(It.IsAny(), It.IsAny())).Verifiable(); + this._internalMessagingController.CountArchivedMessages(Constants.UserID_User12, Constants.PORTAL_Zero); + this._mockDataService.Verify(); + } + [Test] public void DeleteMessageRecipient_Calls_DataService_DeleteMessageRecipientByMessageAndUser() { - _mockDataService.Setup(ds => ds.DeleteMessageRecipientByMessageAndUser(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); - _internalMessagingController.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - _mockDataService.Verify(); - } - - #endregion - - #region GetMessageRecipients - + this._mockDataService.Setup(ds => ds.DeleteMessageRecipientByMessageAndUser(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); + this._internalMessagingController.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + this._mockDataService.Verify(); + } + [Test] public void GetMessageRecipients_Calls_DataService_GetMessageRecipientsByMessage() { - _dtMessageRecipients.Clear(); + this._dtMessageRecipients.Clear(); - _mockDataService + this._mockDataService .Setup(ds => ds.GetMessageRecipientsByMessage(Constants.Messaging_MessageId_1)) - .Returns(_dtMessageRecipients.CreateDataReader()) + .Returns(this._dtMessageRecipients.CreateDataReader()) .Verifiable(); - _internalMessagingController.GetMessageRecipients(Constants.Messaging_MessageId_1); - _mockDataService.Verify(); - } - - #endregion - - #endregion - - #region "Private Methods" - + this._internalMessagingController.GetMessageRecipients(Constants.Messaging_MessageId_1); + this._mockDataService.Verify(); + } + private static Message CreateValidMessage() { var message = new Message @@ -1543,92 +1439,91 @@ private static Message CreateValidMessage() ConversationId = 1, ReplyAllAllowed = false, SenderUserID = 1, - NotificationTypeID = 1 + NotificationTypeID = 1, }; return message; } private void SetupDataTables() { - //Messages - _dtMessages = new DataTable("Messages"); - var pkMessagesMessageID = _dtMessages.Columns.Add("MessageID", typeof(int)); - _dtMessages.Columns.Add("PortalId", typeof(int)); - _dtMessages.Columns.Add("NotificationTypeID", typeof(int)); - _dtMessages.Columns.Add("To", typeof(string)); - _dtMessages.Columns.Add("From", typeof(string)); - _dtMessages.Columns.Add("Subject", typeof(string)); - _dtMessages.Columns.Add("Body", typeof(string)); - _dtMessages.Columns.Add("ConversationId", typeof(int)); - _dtMessages.Columns.Add("ReplyAllAllowed", typeof(bool)); - _dtMessages.Columns.Add("SenderUserID", typeof(int)); - _dtMessages.Columns.Add("CreatedByUserID", typeof(int)); - _dtMessages.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtMessages.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtMessages.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - _dtMessages.PrimaryKey = new[] { pkMessagesMessageID }; - - //MessageRecipients - _dtMessageRecipients = new DataTable("MessageRecipients"); - var pkMessageRecipientID = _dtMessageRecipients.Columns.Add("RecipientID", typeof(int)); - _dtMessageRecipients.Columns.Add("MessageID", typeof(int)); - _dtMessageRecipients.Columns.Add("UserID", typeof(int)); - _dtMessageRecipients.Columns.Add("Read", typeof(bool)); - _dtMessageRecipients.Columns.Add("Archived", typeof(bool)); - _dtMessageRecipients.Columns.Add("CreatedByUserID", typeof(int)); - _dtMessageRecipients.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtMessageRecipients.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtMessageRecipients.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - _dtMessageRecipients.PrimaryKey = new[] { pkMessageRecipientID }; - - //MessageAttachments - _dtMessageAttachment = new DataTable("MessageAttachments"); - var pkMessageAttachmentID = _dtMessageAttachment.Columns.Add("MessageAttachmentID", typeof(int)); - _dtMessageAttachment.Columns.Add("MessageID", typeof(int)); - _dtMessageAttachment.Columns.Add("FileID", typeof(int)); - _dtMessageAttachment.Columns.Add("CreatedByUserID", typeof(int)); - _dtMessageAttachment.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtMessageAttachment.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtMessageAttachment.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - _dtMessageAttachment.PrimaryKey = new[] { pkMessageAttachmentID }; - - //Portal Settings - _dtPortalSettings = new DataTable("PortalSettings"); - _dtPortalSettings.Columns.Add("SettingName", typeof(string)); - _dtPortalSettings.Columns.Add("SettingValue", typeof(string)); - _dtPortalSettings.Columns.Add("CultureCode", typeof(string)); - _dtPortalSettings.Columns.Add("CreatedByUserID", typeof(int)); - _dtPortalSettings.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtPortalSettings.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtPortalSettings.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - //Message Conversation - _dtMessageConversationView = new DataTable(); - _dtMessageConversationView.Columns.Add("RowNumber", typeof(int)); - _dtMessageConversationView.Columns.Add("AttachmentCount", typeof(int)); - _dtMessageConversationView.Columns.Add("NewThreadCount", typeof(int)); - _dtMessageConversationView.Columns.Add("ThreadCount", typeof(int)); - _dtMessageConversationView.Columns.Add("MessageID", typeof(int)); - _dtMessageConversationView.Columns.Add("To", typeof(string)); - _dtMessageConversationView.Columns.Add("From", typeof(string)); - _dtMessageConversationView.Columns.Add("Subject", typeof(string)); - _dtMessageConversationView.Columns.Add("Body", typeof(string)); - _dtMessageConversationView.Columns.Add("ConversationID", typeof(int)); - _dtMessageConversationView.Columns.Add("ReplyAllAllowed", typeof(bool)); - _dtMessageConversationView.Columns.Add("SenderUserID", typeof(int)); - _dtMessageConversationView.Columns.Add("CreatedByUserID", typeof(int)); - _dtMessageConversationView.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtMessageConversationView.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtMessageConversationView.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - //Thread View - _dtMessageThreadsView = new DataTable(); - _dtMessageThreadsView.Columns.Add("TotalThreads", typeof(int)); - _dtMessageThreadsView.Columns.Add("TotalNewThreads", typeof(int)); - _dtMessageThreadsView.Columns.Add("TotalArchivedThreads", typeof(int)); - } - - #endregion + // Messages + this._dtMessages = new DataTable("Messages"); + var pkMessagesMessageID = this._dtMessages.Columns.Add("MessageID", typeof(int)); + this._dtMessages.Columns.Add("PortalId", typeof(int)); + this._dtMessages.Columns.Add("NotificationTypeID", typeof(int)); + this._dtMessages.Columns.Add("To", typeof(string)); + this._dtMessages.Columns.Add("From", typeof(string)); + this._dtMessages.Columns.Add("Subject", typeof(string)); + this._dtMessages.Columns.Add("Body", typeof(string)); + this._dtMessages.Columns.Add("ConversationId", typeof(int)); + this._dtMessages.Columns.Add("ReplyAllAllowed", typeof(bool)); + this._dtMessages.Columns.Add("SenderUserID", typeof(int)); + this._dtMessages.Columns.Add("CreatedByUserID", typeof(int)); + this._dtMessages.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtMessages.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtMessages.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this._dtMessages.PrimaryKey = new[] { pkMessagesMessageID }; + + // MessageRecipients + this._dtMessageRecipients = new DataTable("MessageRecipients"); + var pkMessageRecipientID = this._dtMessageRecipients.Columns.Add("RecipientID", typeof(int)); + this._dtMessageRecipients.Columns.Add("MessageID", typeof(int)); + this._dtMessageRecipients.Columns.Add("UserID", typeof(int)); + this._dtMessageRecipients.Columns.Add("Read", typeof(bool)); + this._dtMessageRecipients.Columns.Add("Archived", typeof(bool)); + this._dtMessageRecipients.Columns.Add("CreatedByUserID", typeof(int)); + this._dtMessageRecipients.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtMessageRecipients.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtMessageRecipients.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this._dtMessageRecipients.PrimaryKey = new[] { pkMessageRecipientID }; + + // MessageAttachments + this._dtMessageAttachment = new DataTable("MessageAttachments"); + var pkMessageAttachmentID = this._dtMessageAttachment.Columns.Add("MessageAttachmentID", typeof(int)); + this._dtMessageAttachment.Columns.Add("MessageID", typeof(int)); + this._dtMessageAttachment.Columns.Add("FileID", typeof(int)); + this._dtMessageAttachment.Columns.Add("CreatedByUserID", typeof(int)); + this._dtMessageAttachment.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtMessageAttachment.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtMessageAttachment.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this._dtMessageAttachment.PrimaryKey = new[] { pkMessageAttachmentID }; + + // Portal Settings + this._dtPortalSettings = new DataTable("PortalSettings"); + this._dtPortalSettings.Columns.Add("SettingName", typeof(string)); + this._dtPortalSettings.Columns.Add("SettingValue", typeof(string)); + this._dtPortalSettings.Columns.Add("CultureCode", typeof(string)); + this._dtPortalSettings.Columns.Add("CreatedByUserID", typeof(int)); + this._dtPortalSettings.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtPortalSettings.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtPortalSettings.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + // Message Conversation + this._dtMessageConversationView = new DataTable(); + this._dtMessageConversationView.Columns.Add("RowNumber", typeof(int)); + this._dtMessageConversationView.Columns.Add("AttachmentCount", typeof(int)); + this._dtMessageConversationView.Columns.Add("NewThreadCount", typeof(int)); + this._dtMessageConversationView.Columns.Add("ThreadCount", typeof(int)); + this._dtMessageConversationView.Columns.Add("MessageID", typeof(int)); + this._dtMessageConversationView.Columns.Add("To", typeof(string)); + this._dtMessageConversationView.Columns.Add("From", typeof(string)); + this._dtMessageConversationView.Columns.Add("Subject", typeof(string)); + this._dtMessageConversationView.Columns.Add("Body", typeof(string)); + this._dtMessageConversationView.Columns.Add("ConversationID", typeof(int)); + this._dtMessageConversationView.Columns.Add("ReplyAllAllowed", typeof(bool)); + this._dtMessageConversationView.Columns.Add("SenderUserID", typeof(int)); + this._dtMessageConversationView.Columns.Add("CreatedByUserID", typeof(int)); + this._dtMessageConversationView.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtMessageConversationView.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtMessageConversationView.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + // Thread View + this._dtMessageThreadsView = new DataTable(); + this._dtMessageThreadsView.Columns.Add("TotalThreads", typeof(int)); + this._dtMessageThreadsView.Columns.Add("TotalNewThreads", typeof(int)); + this._dtMessageThreadsView.Columns.Add("TotalArchivedThreads", typeof(int)); + } } } + // ReSharper restore InconsistentNaming diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs index c30d6001749..56207233b5d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using DotNetNuke.Services.Social.Subscriptions.Entities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging.Mocks { + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Services.Social.Subscriptions.Entities; + internal class SubscriptionDataReaderMockHelper { internal static IDataReader CreateEmptySubscriptionReader() @@ -23,6 +24,7 @@ internal static IDataReader CreateSubscriptionReader(IEnumerable s { AddSubscriptionToTable(datatable, subscription); } + return datatable.CreateDataReader(); } @@ -47,16 +49,17 @@ private static DataTable CreateSubscriptionTable() private static void AddSubscriptionToTable(DataTable table, Subscription subscription) { - table.Rows.Add(new object[] { - subscription.SubscriptionId, + table.Rows.Add(new object[] + { + subscription.SubscriptionId, subscription.UserId, - subscription.PortalId, - subscription.SubscriptionTypeId, + subscription.PortalId, + subscription.SubscriptionTypeId, subscription.ObjectKey, subscription.Description, subscription.CreatedOnDate, subscription.ModuleId, - subscription.TabId + subscription.TabId, }); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionTypeDataReaderMockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionTypeDataReaderMockHelper.cs index 60407ab6c71..b8cc60f9838 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionTypeDataReaderMockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionTypeDataReaderMockHelper.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging.Mocks { + using System.Data; + internal class SubscriptionTypeDataReaderMockHelper { internal static IDataReader CreateEmptySubscriptionTypeReader() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs index 3991c576f51..f81aeba8127 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Data; -using DotNetNuke.Services.Social.Messaging; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging.Mocks { + using System.Data; + + using DotNetNuke.Services.Social.Messaging; + internal class UserPreferenceDataReaderMockHelper { internal static IDataReader CreateEmptyUserPreferenceReader() @@ -38,11 +39,12 @@ private static DataTable CreateUserPreferenceTable() private static void AddUserPreferenceToTable(DataTable table, UserPreference userPreference) { - table.Rows.Add(new object[] { - 1, + table.Rows.Add(new object[] + { + 1, userPreference.PortalId, - userPreference.UserId, - userPreference.MessagesEmailFrequency, + userPreference.UserId, + userPreference.MessagesEmailFrequency, userPreference.NotificationsEmailFrequency, }); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs index d951ae50af4..c463bfc183d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs @@ -1,40 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Text; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Services.Social.Messaging.Exceptions; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Services.Social.Notifications.Data; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming namespace DotNetNuke.Tests.Core.Controllers.Messaging { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Text; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Messaging.Exceptions; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Services.Social.Notifications.Data; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class NotificationsControllerTests - { - #region Private Properties - + { private Mock _mockDataService; private Mock _portalController; private Mock _portalGroupController; @@ -47,47 +43,37 @@ public class NotificationsControllerTests private Mock _cachingProvider; private DataTable _dtNotificationTypes; private DataTable _dtNotificationTypeActions; - private DataTable _dtNotificationActions; - - #endregion - - #region SetUp - + private DataTable _dtNotificationActions; + [SetUp] public void SetUp() { ComponentFactory.Container = new SimpleContainer(); - _mockDataService = new Mock(); - _portalController = new Mock(); - _portalGroupController = new Mock(); + this._mockDataService = new Mock(); + this._portalController = new Mock(); + this._portalGroupController = new Mock(); - _mockMessagingDataService = new Mock(); - _dataProvider = MockComponentProvider.CreateDataProvider(); - _cachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this._mockMessagingDataService = new Mock(); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); - _notificationsController = new NotificationsController(_mockDataService.Object, _mockMessagingDataService.Object); - _mockNotificationsController = new Mock { CallBase = true }; + this._notificationsController = new NotificationsController(this._mockDataService.Object, this._mockMessagingDataService.Object); + this._mockNotificationsController = new Mock { CallBase = true }; - _mockMessagingController = new Mock(); - MessagingController.SetTestableInstance(_mockMessagingController.Object); - PortalController.SetTestableInstance(_portalController.Object); - PortalGroupController.RegisterInstance(_portalGroupController.Object); + this._mockMessagingController = new Mock(); + MessagingController.SetTestableInstance(this._mockMessagingController.Object); + PortalController.SetTestableInstance(this._portalController.Object); + PortalGroupController.RegisterInstance(this._portalGroupController.Object); - _mockInternalMessagingController = new Mock(); - InternalMessagingController.SetTestableInstance(_mockInternalMessagingController.Object); + this._mockInternalMessagingController = new Mock(); + InternalMessagingController.SetTestableInstance(this._mockInternalMessagingController.Object); - DataService.RegisterInstance(_mockDataService.Object); - DotNetNuke.Services.Social.Messaging.Data.DataService.RegisterInstance(_mockMessagingDataService.Object); - - SetupDataProvider(); - SetupDataTables(); - } - - private void SetupDataProvider() - { - //Standard DataProvider Path for Logging - _dataProvider.Setup(d => d.GetProviderPath()).Returns(""); + DataService.RegisterInstance(this._mockDataService.Object); + DotNetNuke.Services.Social.Messaging.Data.DataService.RegisterInstance(this._mockMessagingDataService.Object); + + this.SetupDataProvider(); + this.SetupDataTables(); } [TearDown] @@ -97,17 +83,19 @@ public void TearDown() MessagingController.ClearInstance(); PortalController.ClearInstance(); InternalMessagingController.ClearInstance(); - } - - #endregion - - #region CreateNotificationType - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void CreateNotificationType_Throws_On_Null_NotificationType() { - _notificationsController.CreateNotificationType(null); + this._notificationsController.CreateNotificationType(null); + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); } [Test] @@ -119,21 +107,21 @@ public void CreateNotificationType_Throws_On_Null_Or_Empty_Name(string name) var notificationType = CreateNewNotificationType(); notificationType.Name = name; - _notificationsController.CreateNotificationType(notificationType); + this._notificationsController.CreateNotificationType(notificationType); } [Test] public void CreateNotificationType_Calls_DataService_CreateNotificationType() { - _mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - _mockDataService + this._mockDataService .Setup(ds => ds.CreateNotificationType(Constants.Messaging_NotificationTypeName, It.IsAny(), It.IsAny(), It.IsAny(), Constants.UserID_User12, It.IsAny())) .Verifiable(); - _mockNotificationsController.Object.CreateNotificationType(CreateNewNotificationType()); + this._mockNotificationsController.Object.CreateNotificationType(CreateNewNotificationType()); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] @@ -146,7 +134,7 @@ public void CreateNotificationType_Returns_Object_With_Valid_TimeToLive(int actu var notificationType = CreateNewNotificationType(); notificationType.TimeToLive = actualTimeToLive; - _notificationsController.CreateNotificationType(notificationType); + this._notificationsController.CreateNotificationType(notificationType); Assert.AreEqual(expectedTimeToLiveTotalMinutes, (int)notificationType.TimeToLive.TotalMinutes); } @@ -156,9 +144,9 @@ public void CreateNotificationType_Makes_Valid_Object() { var expectedNotificationType = CreateValidNotificationType(); - _mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - _mockDataService + this._mockDataService .Setup(ds => ds.CreateNotificationType( expectedNotificationType.Name, expectedNotificationType.Description, @@ -168,84 +156,76 @@ public void CreateNotificationType_Makes_Valid_Object() .Returns(Constants.Messaging_NotificationTypeId); var actualNotificationType = CreateNewNotificationType(); - _mockNotificationsController.Object.CreateNotificationType(actualNotificationType); + this._mockNotificationsController.Object.CreateNotificationType(actualNotificationType); Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); - } - - #endregion - - #region DeleteNotificationType - + } + [Test] public void DeleteNotificationType_Calls_DataService_DeleteNotificationType() { - _mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)).Verifiable(); - _mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()); - _mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); - _mockDataService.Verify(); + this._mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)).Verifiable(); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()); + this._mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); + this._mockDataService.Verify(); } [Test] public void DeleteNotificationType_Removes_Cache_Object() { - _mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)); - _mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()).Verifiable(); - _mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); - _mockNotificationsController.Verify(); - } - - #endregion - - #region GetNotificationType - + this._mockDataService.Setup(ds => ds.DeleteNotificationType(Constants.Messaging_NotificationTypeId)); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()).Verifiable(); + this._mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); + this._mockNotificationsController.Verify(); + } + [Test] public void GetNotificationType_By_Id_Gets_Object_From_Cache() { - _cachingProvider.Object.PurgeCache(); - _cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - _notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); - _cachingProvider.Verify(); + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); + this._cachingProvider.Verify(); } [Test] public void GetNotificationType_By_Id_Calls_DataService_GetNotificationType_When_Object_Is_Not_In_Cache() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); var messageTypeDataTable = new DataTable(); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationType(Constants.Messaging_NotificationTypeId)) .Returns(messageTypeDataTable.CreateDataReader()) .Verifiable(); - _notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] public void GetNotificationType_By_Id_Returns_Valid_Object() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); var expectedNotificationType = CreateValidNotificationType(); - _dtNotificationTypes.Rows.Clear(); + this._dtNotificationTypes.Rows.Clear(); - _dtNotificationTypes.Rows.Add( + this._dtNotificationTypes.Rows.Add( expectedNotificationType.NotificationTypeId, expectedNotificationType.Name, expectedNotificationType.Description, (int)expectedNotificationType.TimeToLive.TotalMinutes, expectedNotificationType.DesktopModuleId); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationType(Constants.Messaging_NotificationTypeId)) - .Returns(_dtNotificationTypes.CreateDataReader()); + .Returns(this._dtNotificationTypes.CreateDataReader()); - var actualNotificationType = _notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); + var actualNotificationType = this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeId); Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); } @@ -256,73 +236,70 @@ public void GetNotificationType_By_Id_Returns_Valid_Object() [ExpectedException(typeof(ArgumentException))] public void GetNotificationType_By_Name_Throws_On_Null_Or_Empty_Name(string name) { - _notificationsController.GetNotificationType(name); + this._notificationsController.GetNotificationType(name); } [Test] public void GetNotificationType_By_Name_Gets_Object_From_Cache() { - _cachingProvider.Object.PurgeCache(); - _cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - _notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); - _cachingProvider.Verify(); + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); + this._cachingProvider.Verify(); } [Test] public void GetNotificationType_By_Name_Calls_DataService_GetNotificationTypeByName_When_Object_Is_Not_In_Cache() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationTypeByName(Constants.Messaging_NotificationTypeName)) - .Returns(_dtNotificationTypes.CreateDataReader()) + .Returns(this._dtNotificationTypes.CreateDataReader()) .Verifiable(); - _notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); + this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] public void GetNotificationType_By_Name_Returns_Valid_Object() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); var expectedNotificationType = CreateValidNotificationType(); - _dtNotificationTypes.Rows.Clear(); + this._dtNotificationTypes.Rows.Clear(); - _dtNotificationTypes.Rows.Add( + this._dtNotificationTypes.Rows.Add( expectedNotificationType.NotificationTypeId, expectedNotificationType.Name, expectedNotificationType.Description, (int)expectedNotificationType.TimeToLive.TotalMinutes, expectedNotificationType.DesktopModuleId); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationTypeByName(Constants.Messaging_NotificationTypeName)) - .Returns(_dtNotificationTypes.CreateDataReader()); + .Returns(this._dtNotificationTypes.CreateDataReader()); - var actualNotificationType = _notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); + var actualNotificationType = this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); - } - - #endregion - - #region AddNotificationTypeAction + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetNotificationTypeActions_Throws_On_Null() { - _notificationsController.SetNotificationTypeActions(null, Constants.Messaging_NotificationTypeId); + this._notificationsController.SetNotificationTypeActions(null, Constants.Messaging_NotificationTypeId); } [Test] [ExpectedException(typeof(ArgumentException))] public void SetNotificationTypeActions_Throws_On_EmptyList() { - _notificationsController.SetNotificationTypeActions(new List(), Constants.Messaging_NotificationTypeId); + this._notificationsController.SetNotificationTypeActions(new List(), Constants.Messaging_NotificationTypeId); } [Test] @@ -333,7 +310,7 @@ public void SetNotificationTypeActions_Throws_On_Null_Or_Empty_Name(string name) { var action = CreateNewNotificationTypeAction(); action.NameResourceKey = name; - _notificationsController.SetNotificationTypeActions(new [] {action}, Constants.Messaging_NotificationTypeId); + this._notificationsController.SetNotificationTypeActions(new[] { action }, Constants.Messaging_NotificationTypeId); } [Test] @@ -344,36 +321,37 @@ public void SetNotificationTypeActions_Throws_On_Null_Or_Empty_APICall(string ap { var action = CreateNewNotificationTypeAction(); action.APICall = apiCall; - _notificationsController.SetNotificationTypeActions(new[] { action }, Constants.Messaging_NotificationTypeId); + this._notificationsController.SetNotificationTypeActions(new[] { action }, Constants.Messaging_NotificationTypeId); } [Test] public void SetNotificationTypeActions_Calls_DataService_AddNotificationTypeAction_For_Each_Of_Two_Actions() { - _mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - -// _mockDataService -// .Setup(ds => ds.AddNotificationTypeAction( -// Constants.Messaging_NotificationTypeId, -// Constants.Messaging_NotificationTypeActionNameResourceKey, -// Constants.Messaging_NotificationTypeActionDescriptionResourceKey, -// Constants.Messaging_NotificationTypeActionConfirmResourceKey, -// Constants.Messaging_NotificationTypeActionAPICall, -// Constants.UserID_User12)) -// .Verifiable(); - - _mockNotificationsController.Setup(nc => nc.GetNotificationTypeAction(It.IsAny())); - - _mockNotificationsController.Object.SetNotificationTypeActions( - new [] {CreateNewNotificationTypeAction(), CreateNewNotificationTypeAction()}, + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + + // _mockDataService + // .Setup(ds => ds.AddNotificationTypeAction( + // Constants.Messaging_NotificationTypeId, + // Constants.Messaging_NotificationTypeActionNameResourceKey, + // Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + // Constants.Messaging_NotificationTypeActionConfirmResourceKey, + // Constants.Messaging_NotificationTypeActionAPICall, + // Constants.UserID_User12)) + // .Verifiable(); + this._mockNotificationsController.Setup(nc => nc.GetNotificationTypeAction(It.IsAny())); + + this._mockNotificationsController.Object.SetNotificationTypeActions( + new[] { CreateNewNotificationTypeAction(), CreateNewNotificationTypeAction() }, Constants.Messaging_NotificationTypeId); - _mockDataService.Verify(x => x.AddNotificationTypeAction(Constants.Messaging_NotificationTypeId, - Constants.Messaging_NotificationTypeActionNameResourceKey, - Constants.Messaging_NotificationTypeActionDescriptionResourceKey, - Constants.Messaging_NotificationTypeActionConfirmResourceKey, - Constants.Messaging_NotificationTypeActionAPICall, - Constants.UserID_User12), Times.Exactly(2)); + this._mockDataService.Verify( + x => x.AddNotificationTypeAction( + Constants.Messaging_NotificationTypeId, + Constants.Messaging_NotificationTypeActionNameResourceKey, + Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + Constants.Messaging_NotificationTypeActionConfirmResourceKey, + Constants.Messaging_NotificationTypeActionAPICall, + Constants.UserID_User12), Times.Exactly(2)); } [Test] @@ -381,9 +359,9 @@ public void SetNotificationTypeActions_Sets_NotificationTypeActionId_And_Notific { var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - _mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - _mockDataService + this._mockDataService .Setup(ds => ds.AddNotificationTypeAction( expectedNotificationTypeAction.NotificationTypeId, expectedNotificationTypeAction.NameResourceKey, @@ -393,76 +371,68 @@ public void SetNotificationTypeActions_Sets_NotificationTypeActionId_And_Notific Constants.UserID_User12)) .Returns(expectedNotificationTypeAction.NotificationTypeActionId); - _mockNotificationsController + this._mockNotificationsController .Setup(nc => nc.GetNotificationTypeAction(expectedNotificationTypeAction.NotificationTypeActionId)) .Returns(expectedNotificationTypeAction); - + var action = CreateNewNotificationTypeAction(); - _mockNotificationsController.Object.SetNotificationTypeActions(new []{action}, expectedNotificationTypeAction.NotificationTypeId); + this._mockNotificationsController.Object.SetNotificationTypeActions(new[] { action }, expectedNotificationTypeAction.NotificationTypeId); Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, action)); - } - - #endregion - - #region DeleteNotificationTypeAction - + } + [Test] public void DeleteNotificationTypeAction_Calls_DataService_DeleteNotificationTypeAction() { - _mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)).Verifiable(); - _mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()); - _mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - _mockDataService.Verify(); + this._mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)).Verifiable(); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()); + this._mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + this._mockDataService.Verify(); } [Test] public void DeleteNotificationTypeAction_Removes_Cache_Object() { - _mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)); - _mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()).Verifiable(); - _mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - _mockNotificationsController.Verify(); - } - - #endregion - - #region GetNotificationTypeAction - + this._mockDataService.Setup(ds => ds.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)); + this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()).Verifiable(); + this._mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + this._mockNotificationsController.Verify(); + } + [Test] public void GetNotificationTypeAction_By_Id_Gets_Object_From_Cache() { - _cachingProvider.Object.PurgeCache(); - _cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - _notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - _cachingProvider.Verify(); + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + this._cachingProvider.Verify(); } [Test] public void GetNotificationTypeAction_By_Id_Calls_DataService_GetNotificationTypeAction_When_Object_Is_Not_In_Cache() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)) - .Returns(_dtNotificationTypeActions.CreateDataReader()) + .Returns(this._dtNotificationTypeActions.CreateDataReader()) .Verifiable(); - _notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] public void GetNotificationTypeAction_By_Id_Returns_Valid_Object() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - _dtNotificationTypeActions.Clear(); + this._dtNotificationTypeActions.Clear(); - _dtNotificationTypeActions.Rows.Add( + this._dtNotificationTypeActions.Rows.Add( expectedNotificationTypeAction.NotificationTypeActionId, expectedNotificationTypeAction.NotificationTypeId, expectedNotificationTypeAction.NameResourceKey, @@ -471,11 +441,11 @@ public void GetNotificationTypeAction_By_Id_Returns_Valid_Object() expectedNotificationTypeAction.Order, expectedNotificationTypeAction.APICall); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId)) - .Returns(_dtNotificationTypeActions.CreateDataReader); + .Returns(this._dtNotificationTypeActions.CreateDataReader); - var actualNotificationTypeAction = _notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); + var actualNotificationTypeAction = this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeAction)); } @@ -486,45 +456,45 @@ public void GetNotificationTypeAction_By_Id_Returns_Valid_Object() [ExpectedException(typeof(ArgumentException))] public void GetNotificationTypeAction_By_Name_Throws_On_Null_Or_Empty_Name(string name) { - _notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, name); + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, name); } [Test] public void GetNotificationTypeAction_By_Name_Gets_Object_From_Cache() { - _cachingProvider.Object.PurgeCache(); - _cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); - _notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); - _cachingProvider.Verify(); + this._cachingProvider.Object.PurgeCache(); + this._cachingProvider.Setup(cp => cp.GetItem(It.IsAny())).Verifiable(); + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); + this._cachingProvider.Verify(); } [Test] public void GetNotificationTypeAction_By_Name_Calls_DataService_GetNotificationTypeActionByName_When_Object_Is_Not_In_Cache() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationTypeActionByName( Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey)) - .Returns(_dtNotificationTypeActions.CreateDataReader()) + .Returns(this._dtNotificationTypeActions.CreateDataReader()) .Verifiable(); - _notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); + this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] public void GetNotificationTypeAction_By_Name_Returns_Valid_Object() { - _cachingProvider.Object.PurgeCache(); + this._cachingProvider.Object.PurgeCache(); var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - _dtNotificationTypeActions.Clear(); + this._dtNotificationTypeActions.Clear(); - _dtNotificationTypeActions.Rows.Add( + this._dtNotificationTypeActions.Rows.Add( expectedNotificationTypeAction.NotificationTypeActionId, expectedNotificationTypeAction.NotificationTypeId, expectedNotificationTypeAction.NameResourceKey, @@ -533,32 +503,28 @@ public void GetNotificationTypeAction_By_Name_Returns_Valid_Object() expectedNotificationTypeAction.Order, expectedNotificationTypeAction.APICall); - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationTypeActionByName( Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey)) - .Returns(_dtNotificationTypeActions.CreateDataReader()); + .Returns(this._dtNotificationTypeActions.CreateDataReader()); - var actualNotificationTypeAction = _notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); + var actualNotificationTypeAction = this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeAction)); - } - - #endregion - - #region GetNotificationTypeActions - + } + [Test] public void GetNotificationTypeActions_Calls_DataService_GetNotificationTypeActions() { - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId)) - .Returns(_dtNotificationTypeActions.CreateDataReader()) + .Returns(this._dtNotificationTypeActions.CreateDataReader()) .Verifiable(); - _notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); + this._notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] @@ -566,9 +532,9 @@ public void GetNotificationTypeActions_Returns_Valid_Object() { var expectedNotificationTypeAction = CreateValidNotificationTypeAction(); - _dtNotificationTypeActions.Clear(); + this._dtNotificationTypeActions.Clear(); - _dtNotificationTypeActions.Rows.Add( + this._dtNotificationTypeActions.Rows.Add( expectedNotificationTypeAction.NotificationTypeActionId, expectedNotificationTypeAction.NotificationTypeId, expectedNotificationTypeAction.NameResourceKey, @@ -577,18 +543,14 @@ public void GetNotificationTypeActions_Returns_Valid_Object() expectedNotificationTypeAction.Order, expectedNotificationTypeAction.APICall); - _mockDataService.Setup(ds => ds.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId)).Returns(_dtNotificationTypeActions.CreateDataReader()); + this._mockDataService.Setup(ds => ds.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId)).Returns(this._dtNotificationTypeActions.CreateDataReader()); - var actualNotificationTypeActions = _notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); + var actualNotificationTypeActions = this._notificationsController.GetNotificationTypeActions(Constants.Messaging_NotificationTypeId); Assert.AreEqual(1, actualNotificationTypeActions.Count); Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeActions[0])); - } - - #endregion - - #region SendNotification - + } + [Test] public void SendNotification_Sets_Empty_SenderUserId_With_Admin() { @@ -596,12 +558,12 @@ public void SendNotification_Sets_Empty_SenderUserId_With_Admin() { UserID = Constants.UserID_Admin, DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.CONTENT_ValidPortalId + PortalID = Constants.CONTENT_ValidPortalId, }; - _mockNotificationsController.Setup(nc => nc.GetAdminUser()).Returns(adminUser); + this._mockNotificationsController.Setup(nc => nc.GetAdminUser()).Returns(adminUser); - _mockNotificationsController + this._mockNotificationsController .Setup(nc => nc.SendNotification( It.IsAny(), Constants.PORTAL_Zero, @@ -610,7 +572,7 @@ public void SendNotification_Sets_Empty_SenderUserId_With_Admin() var notification = CreateUnsavedNotification(); - _mockNotificationsController.Object.SendNotification( + this._mockNotificationsController.Object.SendNotification( notification, Constants.PORTAL_Zero, new List(), @@ -632,10 +594,10 @@ public void SendNotification_Throws_On_Null_Or_Empty_Subject_And_Body(string sub notification.Body = body; var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - _notificationsController.SendNotification( - notification, + this._notificationsController.SendNotification( + notification, Constants.PORTAL_Zero, new List(), new List()); @@ -646,9 +608,9 @@ public void SendNotification_Throws_On_Null_Or_Empty_Subject_And_Body(string sub public void SendNotification_Throws_On_Null_Roles_And_Users() { var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - _notificationsController.SendNotification( + this._notificationsController.SendNotification( CreateUnsavedNotification(), Constants.PORTAL_Zero, null, @@ -665,12 +627,13 @@ public void SendNotification_Throws_On_Large_Subject() { subject.Append("1234567890"); } + notification.Subject = subject.ToString(); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - _notificationsController.SendNotification( + this._notificationsController.SendNotification( notification, Constants.PORTAL_Zero, new List(), @@ -682,9 +645,9 @@ public void SendNotification_Throws_On_Large_Subject() public void SendNotification_Throws_On_Roles_And_Users_With_No_DisplayNames() { var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - _notificationsController.SendNotification( + this._notificationsController.SendNotification( CreateUnsavedNotification(), Constants.PORTAL_Zero, new List(), @@ -705,9 +668,9 @@ public void SendNotification_Throws_On_Large_To_List() } var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - _notificationsController.SendNotification( + this._notificationsController.SendNotification( CreateUnsavedNotification(), Constants.PORTAL_Zero, roles, @@ -717,16 +680,16 @@ public void SendNotification_Throws_On_Large_To_List() [Test] public void SendNotification_Calls_DataService_On_Valid_Notification() { - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero - }; + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.PORTAL_Zero, + }; - _mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); var roles = new List(); var users = new List @@ -735,28 +698,28 @@ public void SendNotification_Calls_DataService_On_Valid_Notification() { UserID = Constants.UserID_User12, DisplayName = Constants.UserDisplayName_User12 - } + }, }; - _mockDataService + this._mockDataService .Setup(ds => ds.SendNotification( It.IsAny(), Constants.PORTAL_Zero)) .Verifiable(); - _mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); var notification = CreateUnsavedNotification(); notification.SenderUserID = adminUser.UserID; notification.SendToast = false; - _mockNotificationsController.Object.SendNotification( + this._mockNotificationsController.Object.SendNotification( notification, Constants.PORTAL_Zero, roles, users); - _mockDataService.Verify(); + this._mockDataService.Verify(); } [Test] @@ -766,16 +729,16 @@ public void SendNotification_Calls_DataService_On_Valid_Notification_When_Portal { UserID = Constants.UserID_Admin, DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero + PortalID = Constants.PORTAL_Zero, }; - _mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); - + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); - _portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); + List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); + this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); var roles = new List(); var users = new List @@ -784,29 +747,30 @@ public void SendNotification_Calls_DataService_On_Valid_Notification_When_Portal { UserID = Constants.UserID_User12, DisplayName = Constants.UserDisplayName_User12 - } + }, }; - _mockDataService + this._mockDataService .Setup(ds => ds.SendNotification( It.IsAny(), Constants.PORTAL_Zero)) .Verifiable(); - _mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); var notification = CreateUnsavedNotification(); notification.SenderUserID = adminUser.UserID; notification.SendToast = false; - _mockNotificationsController.Object.SendNotification( + this._mockNotificationsController.Object.SendNotification( notification, Constants.PORTAL_Zero, roles, users); - _mockDataService.Verify(); + this._mockDataService.Verify(); } + [Test] public void SendNotification_Calls_Messaging_DataService_CreateSocialMessageRecipientsForRole_When_Passing_Roles() { @@ -814,12 +778,12 @@ public void SendNotification_Calls_Messaging_DataService_CreateSocialMessageReci { UserID = Constants.UserID_Admin, DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero + PortalID = Constants.PORTAL_Zero, }; - _mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); var roles = new List { @@ -827,36 +791,36 @@ public void SendNotification_Calls_Messaging_DataService_CreateSocialMessageReci { RoleID = Constants.RoleID_RegisteredUsers, RoleName = Constants.RoleName_RegisteredUsers - } + }, }; var users = new List(); - _mockDataService + this._mockDataService .Setup(ds => ds.SendNotification( It.IsAny(), Constants.PORTAL_Zero)) .Returns(Constants.Messaging_MessageId_1); - _mockMessagingDataService + this._mockMessagingDataService .Setup(mds => mds.CreateMessageRecipientsForRole( Constants.Messaging_MessageId_1, Constants.RoleID_RegisteredUsers.ToString(CultureInfo.InvariantCulture), It.IsAny())) .Verifiable(); - _mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); var notification = CreateUnsavedNotification(); notification.SenderUserID = adminUser.UserID; notification.SendToast = false; - _mockNotificationsController.Object.SendNotification( + this._mockNotificationsController.Object.SendNotification( notification, Constants.PORTAL_Zero, roles, users); - _mockMessagingDataService.Verify(); + this._mockMessagingDataService.Verify(); } [Test] @@ -866,58 +830,58 @@ public void SendNotification_Calls_Messaging_DataService_SaveSocialMessageRecipi { UserID = Constants.UserID_Admin, DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero + PortalID = Constants.PORTAL_Zero, }; - _mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); var roles = new List(); var users = new List { new UserInfo { - UserID = Constants.UserID_User12, + UserID = Constants.UserID_User12, DisplayName = Constants.UserDisplayName_User12 - } + }, }; - _mockDataService + this._mockDataService .Setup(ds => ds.SendNotification( It.IsAny(), Constants.PORTAL_Zero)) .Returns(Constants.Messaging_MessageId_1); - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetMessageRecipient( Constants.Messaging_MessageId_1, Constants.UserID_User12)) .Returns((MessageRecipient)null); - _mockMessagingDataService + this._mockMessagingDataService .Setup(mds => mds.SaveMessageRecipient( - It.Is(mr => - mr.MessageID == Constants.Messaging_MessageId_1 && - mr.UserID == Constants.UserID_User12 && - mr.Read == false && + It.Is(mr => + mr.MessageID == Constants.Messaging_MessageId_1 && + mr.UserID == Constants.UserID_User12 && + mr.Read == false && mr.RecipientID == Null.NullInteger), It.IsAny())) .Verifiable(); - _mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); var notification = CreateUnsavedNotification(); notification.SenderUserID = adminUser.UserID; notification.SendToast = false; - _mockNotificationsController.Object.SendNotification( + this._mockNotificationsController.Object.SendNotification( notification, Constants.PORTAL_Zero, roles, users); - _mockMessagingDataService.Verify(); + this._mockMessagingDataService.Verify(); } [Test] @@ -929,43 +893,43 @@ public void SendNotification_Returns_Valid_Object() { UserID = Constants.UserID_Admin, DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero + PortalID = Constants.PORTAL_Zero, }; - _mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); + this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); var roles = new List(); var users = new List { new UserInfo { - UserID = Constants.UserID_User12, + UserID = Constants.UserID_User12, DisplayName = Constants.UserDisplayName_User12 - } + }, }; - _mockDataService + this._mockDataService .Setup(ds => ds.SendNotification( It.IsAny(), Constants.PORTAL_Zero)) .Returns(Constants.Messaging_MessageId_1); - _mockMessagingDataService + this._mockMessagingDataService .Setup(mds => mds.CreateMessageRecipientsForRole( Constants.Messaging_MessageId_1, Constants.RoleID_RegisteredUsers.ToString(CultureInfo.InvariantCulture), It.IsAny())); - _mockInternalMessagingController + this._mockInternalMessagingController .Setup(mc => mc.GetMessageRecipient( Constants.Messaging_MessageId_1, Constants.UserID_User12)) .Returns((MessageRecipient)null); - _mockMessagingDataService + this._mockMessagingDataService .Setup(mds => mds.SaveMessageRecipient( It.Is(mr => mr.MessageID == Constants.Messaging_MessageId_1 && @@ -974,122 +938,106 @@ public void SendNotification_Returns_Valid_Object() mr.RecipientID == Null.NullInteger), It.IsAny())); - _mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); + this._mockNotificationsController.Setup(nc => nc.GetExpirationDate(It.IsAny())).Returns(DateTime.MinValue); var notification = CreateUnsavedNotification(); notification.SenderUserID = adminUser.UserID; notification.SendToast = false; - _mockNotificationsController.Object.SendNotification( + this._mockNotificationsController.Object.SendNotification( notification, - Constants.PORTAL_Zero, + Constants.PORTAL_Zero, roles, users); Assert.IsTrue(new NotificationComparer().Equals(expectedNotification, notification)); - } - - #endregion - - #region DeleteNotification - + } + [Test] public void DeleteNotification_Calls_DataService_DeleteNotification() { var messageRecipients = new List { - new MessageRecipient() + new MessageRecipient(), }; - _mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); - - _mockDataService.Setup(ds => ds.DeleteNotification(Constants.Messaging_MessageId_1)).Verifiable(); - _notificationsController.DeleteNotification(Constants.Messaging_MessageId_1); - _mockDataService.Verify(); - } - - #endregion - - #region GetNotifications + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); + this._mockDataService.Setup(ds => ds.DeleteNotification(Constants.Messaging_MessageId_1)).Verifiable(); + this._notificationsController.DeleteNotification(Constants.Messaging_MessageId_1); + this._mockDataService.Verify(); + } + [Test] public void GetNotifications_Calls_DataService_GetNotifications() { - _mockDataService - .Setup(ds => ds.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero,It.IsAny(), It.IsAny())) + this._mockDataService + .Setup(ds => ds.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, It.IsAny(), It.IsAny())) .Returns(new DataTable().CreateDataReader()) .Verifiable(); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - - _notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); - _mockDataService.Verify(); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + + this._notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); + this._mockDataService.Verify(); } [Test] public void GetNotifications_Calls_DataService_GetNotifications_When_Portal_Is_In_Group() { - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, It.IsAny(), It.IsAny())) .Returns(new DataTable().CreateDataReader()) .Verifiable(); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - List portalGroups = new List(){CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId,Constants.PORTAL_Zero)}; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); - _portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); + List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); + this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); - _notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); - _mockDataService.Verify(); + this._notificationsController.GetNotifications(Constants.UserID_User12, Constants.PORTAL_Zero, 0, 10); + this._mockDataService.Verify(); } [Test] public void GetNotifications_Calls_DataService_GetNotificationByContext() { - _mockDataService + this._mockDataService .Setup(ds => ds.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext)) .Returns(new DataTable().CreateDataReader()) .Verifiable(); - _notificationsController.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext); - _mockDataService.Verify(); - } - - #endregion - - #region CountNotifications - + this._notificationsController.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext); + this._mockDataService.Verify(); + } + [Test] public void CountNotifications_Calls_DataService_CountNotifications() { - _mockDataService.Setup(ds => ds.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero)).Verifiable(); - _notificationsController.CountNotifications(Constants.UserID_User12,Constants.PORTAL_Zero); - _mockDataService.Verify(); - } - - #endregion - - #region DeleteNotificationRecipient - + this._mockDataService.Setup(ds => ds.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero)).Verifiable(); + this._notificationsController.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero); + this._mockDataService.Verify(); + } + [Test] public void DeleteNotificationRecipient_Calls_MessagingController_DeleteMessageRecipient() { - _mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); - _mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); - _notificationsController.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - _mockMessagingController.Verify(); + this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); + this._notificationsController.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + this._mockMessagingController.Verify(); } [Test] public void DeleteNotificationRecipientByContext_Calls_DeleteMessageRecipient() { - _mockNotificationsController.Setup(mc => mc.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); - _mockNotificationsController.Setup(mc => mc.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext)) + this._mockNotificationsController.Setup(mc => mc.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); + this._mockNotificationsController.Setup(mc => mc.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext)) .Returns(new List { new Notification { NotificationID = Constants.Messaging_MessageId_1 } }); - _mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext, Constants.UserID_User12); - _mockMessagingController.Verify(); + this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext, Constants.UserID_User12); + this._mockMessagingController.Verify(); } [Test] @@ -1097,70 +1045,62 @@ public void DeleteNotificationRecipient_Does_Not_Delete_Notification_When_There_ { var messageRecipients = new List { - new MessageRecipient() + new MessageRecipient(), }; - _mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); - _mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); - _mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - - _mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1), Times.Never()); + this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(messageRecipients); + this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + + this._mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1), Times.Never()); } [Test] public void DeleteNotificationRecipient_Deletes_Notification_When_There_Are_No_More_Recipients() { - _mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); - _mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); - _mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); - _mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1)); - } - - #endregion - - #region DeleteAllNotificationRecipients - + this._mockInternalMessagingController.Setup(mc => mc.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12)); + this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); + this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); + this._mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1)); + } + [Test] public void DeleteAllNotificationRecipients_Calls_DeleteNotificationRecipient_For_Each_Recipient() { var recipients = new List { - new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_1 }, - new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_2 } + new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_1 }, + new MessageRecipient { RecipientID = Constants.Messaging_RecipientId_2 }, }; - _mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(recipients); + this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(recipients); - _mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); + this._mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); - _mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Exactly(2)); + this._mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Exactly(2)); } [Test] public void DeleteAllNotificationRecipients_Does_Not_Call_DeleteNotificationRecipient_When_Notification_Has_No_Recipients() { - _mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); - _mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); - _mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Never()); - } - - #endregion - - #region Private Methods - + this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); + this._mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); + this._mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Never()); + } + private static Notification CreateUnsavedNotification() { - return new Notification - { - NotificationTypeID = Constants.Messaging_NotificationTypeId, - Subject = Constants.Messaging_NotificationSubject, - Body = Constants.Messaging_NotificationBody, - To = Constants.UserDisplayName_User12, - From = Constants.UserDisplayName_Admin, - SenderUserID = Constants.UserID_Admin, - Context = Constants.Messaging_NotificationContext, - SendToast = false - }; + return new Notification + { + NotificationTypeID = Constants.Messaging_NotificationTypeId, + Subject = Constants.Messaging_NotificationSubject, + Body = Constants.Messaging_NotificationBody, + To = Constants.UserDisplayName_User12, + From = Constants.UserDisplayName_Admin, + SenderUserID = Constants.UserID_Admin, + Context = Constants.Messaging_NotificationContext, + SendToast = false, + }; } private static Notification CreateValidNotification() @@ -1186,7 +1126,7 @@ private static NotificationType CreateNewNotificationType() Description = Constants.Messaging_NotificationTypeDescription, TimeToLive = new TimeSpan(0, Constants.Messaging_NotificationTypeTTL, 0), DesktopModuleId = Constants.Messaging_NotificationTypeDesktopModuleId, - IsTask = false + IsTask = false, }; } @@ -1202,18 +1142,18 @@ private static NotificationTypeAction CreateValidNotificationTypeAction() private static NotificationTypeAction CreateNewNotificationTypeAction() { - return new NotificationTypeAction - { - APICall = Constants.Messaging_NotificationTypeActionAPICall, - ConfirmResourceKey = Constants.Messaging_NotificationTypeActionConfirmResourceKey, - DescriptionResourceKey = Constants.Messaging_NotificationTypeActionDescriptionResourceKey, - NameResourceKey = Constants.Messaging_NotificationTypeActionNameResourceKey - }; + return new NotificationTypeAction + { + APICall = Constants.Messaging_NotificationTypeActionAPICall, + ConfirmResourceKey = Constants.Messaging_NotificationTypeActionConfirmResourceKey, + DescriptionResourceKey = Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + NameResourceKey = Constants.Messaging_NotificationTypeActionNameResourceKey, + }; } private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) { - var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId}; + var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; return mockPortalInfo; } @@ -1224,61 +1164,64 @@ private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int mast PortalGroupId = portalGroupId, MasterPortalId = masterPortalId, PortalGroupName = Constants.PORTALGROUP_ValidName, - PortalGroupDescription = Constants.PORTALGROUP_ValidDescription + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, }; - + return mockPortalGroupInfo; } private void SetupDataTables() { - _dtNotificationTypes = new DataTable(); - _dtNotificationTypes.Columns.Add("NotificationTypeID", typeof(int)); - _dtNotificationTypes.Columns.Add("Name", typeof(string)); - _dtNotificationTypes.Columns.Add("Description", typeof(string)); - _dtNotificationTypes.Columns.Add("TTL", typeof(int)); - _dtNotificationTypes.Columns.Add("DesktopModuleID", typeof(int)); - _dtNotificationTypes.Columns.Add("CreatedByUserID", typeof(int)); - _dtNotificationTypes.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtNotificationTypes.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtNotificationTypes.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - _dtNotificationTypes.Columns.Add("IsTask", typeof(bool)); - - _dtNotificationTypeActions = new DataTable(); - _dtNotificationTypeActions.Columns.Add("NotificationTypeActionID", typeof(int)); - _dtNotificationTypeActions.Columns.Add("NotificationTypeID", typeof(int)); - _dtNotificationTypeActions.Columns.Add("NameResourceKey", typeof(string)); - _dtNotificationTypeActions.Columns.Add("DescriptionResourceKey", typeof(string)); - _dtNotificationTypeActions.Columns.Add("ConfirmResourceKey", typeof(string)); - _dtNotificationTypeActions.Columns.Add("Order", typeof(int)); - _dtNotificationTypeActions.Columns.Add("APICall", typeof(string)); - _dtNotificationTypeActions.Columns.Add("CreatedByUserID", typeof(int)); - _dtNotificationTypeActions.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtNotificationTypeActions.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtNotificationTypeActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - _dtNotificationActions = new DataTable(); - _dtNotificationActions.Columns.Add("NotificationActionID"); - _dtNotificationActions.Columns.Add("MessageID"); - _dtNotificationActions.Columns.Add("NotificationTypeActionID"); - _dtNotificationActions.Columns.Add("Key"); - _dtNotificationActions.Columns.Add("CreatedByUserID", typeof(int)); - _dtNotificationActions.Columns.Add("CreatedOnDate", typeof(DateTime)); - _dtNotificationActions.Columns.Add("LastModifiedByUserID", typeof(int)); - _dtNotificationActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - } - - #endregion - - #region Private Classes - + this._dtNotificationTypes = new DataTable(); + this._dtNotificationTypes.Columns.Add("NotificationTypeID", typeof(int)); + this._dtNotificationTypes.Columns.Add("Name", typeof(string)); + this._dtNotificationTypes.Columns.Add("Description", typeof(string)); + this._dtNotificationTypes.Columns.Add("TTL", typeof(int)); + this._dtNotificationTypes.Columns.Add("DesktopModuleID", typeof(int)); + this._dtNotificationTypes.Columns.Add("CreatedByUserID", typeof(int)); + this._dtNotificationTypes.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtNotificationTypes.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtNotificationTypes.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + this._dtNotificationTypes.Columns.Add("IsTask", typeof(bool)); + + this._dtNotificationTypeActions = new DataTable(); + this._dtNotificationTypeActions.Columns.Add("NotificationTypeActionID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("NotificationTypeID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("NameResourceKey", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("DescriptionResourceKey", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("ConfirmResourceKey", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("Order", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("APICall", typeof(string)); + this._dtNotificationTypeActions.Columns.Add("CreatedByUserID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtNotificationTypeActions.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtNotificationTypeActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + this._dtNotificationActions = new DataTable(); + this._dtNotificationActions.Columns.Add("NotificationActionID"); + this._dtNotificationActions.Columns.Add("MessageID"); + this._dtNotificationActions.Columns.Add("NotificationTypeActionID"); + this._dtNotificationActions.Columns.Add("Key"); + this._dtNotificationActions.Columns.Add("CreatedByUserID", typeof(int)); + this._dtNotificationActions.Columns.Add("CreatedOnDate", typeof(DateTime)); + this._dtNotificationActions.Columns.Add("LastModifiedByUserID", typeof(int)); + this._dtNotificationActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + } + private class NotificationTypeComparer : IEqualityComparer { public bool Equals(NotificationType x, NotificationType y) { - if (x == null) return y == null; - if (y == null) return false; - + if (x == null) + { + return y == null; + } + + if (y == null) + { + return false; + } + return x.NotificationTypeId == y.NotificationTypeId && x.Name == y.Name && @@ -1298,9 +1241,16 @@ private class NotificationTypeActionComparer : IEqualityComparer { public bool Equals(Notification x, Notification y) { - if (x == null) return y == null; - if (y == null) return false; - + if (x == null) + { + return y == null; + } + + if (y == null) + { + return false; + } + return x.NotificationID == y.NotificationID && x.NotificationTypeID == y.NotificationTypeID && @@ -1339,9 +1296,8 @@ public int GetHashCode(Notification obj) { throw new NotImplementedException(); } - } - - #endregion + } } } + // ReSharper restore InconsistentNaming diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs index 6a7975ef334..18650a19510 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Social.Subscriptions; -using DotNetNuke.Services.Social.Subscriptions.Data; -using DotNetNuke.Services.Social.Subscriptions.Entities; -using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; -using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging { + using System; + + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Subscriptions; + using DotNetNuke.Services.Social.Subscriptions.Data; + using DotNetNuke.Services.Social.Subscriptions.Entities; + using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; + using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class SubscriptionControllerTests { @@ -28,26 +29,25 @@ public class SubscriptionControllerTests public void SetUp() { // Setup Mocks and Stub - mockDataService = new Mock(); - mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); - subscriptionSecurityController = new Mock(); + this.mockDataService = new Mock(); + this.mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); + this.subscriptionSecurityController = new Mock(); - DataService.SetTestableInstance(mockDataService.Object); - SubscriptionSecurityController.SetTestableInstance(subscriptionSecurityController.Object); + DataService.SetTestableInstance(this.mockDataService.Object); + SubscriptionSecurityController.SetTestableInstance(this.subscriptionSecurityController.Object); // Setup SUT - subscriptionController = new SubscriptionController(); + this.subscriptionController = new SubscriptionController(); } - + [TearDown] public void TearDown() { DataService.ClearInstance(); SubscriptionSecurityController.ClearInstance(); MockComponentProvider.ResetContainer(); - } - - #region IsSubscribed method tests + } + [Test] public void IsSubscribed_ShouldReturnFalse_IfUserIsNotSubscribed() { @@ -55,16 +55,16 @@ public void IsSubscribed_ShouldReturnFalse_IfUserIsNotSubscribed() var subscription = new SubscriptionBuilder() .Build(); - mockDataService.Setup(ds => ds.IsSubscribed( + this.mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, It.IsAny(), It.IsAny())).Returns(SubscriptionDataReaderMockHelper.CreateEmptySubscriptionReader()); - - //Act - var isSubscribed = subscriptionController.IsSubscribed(subscription); + + // Act + var isSubscribed = this.subscriptionController.IsSubscribed(subscription); // Assert Assert.AreEqual(false, isSubscribed); @@ -77,9 +77,9 @@ public void IsSubscribed_ShouldReturnFalse_WhenUserDoesNotHavePermissionOnTheSub var subscription = new SubscriptionBuilder() .Build(); - var subscriptionCollection = new[] {subscription}; + var subscriptionCollection = new[] { subscription }; - mockDataService.Setup(ds => ds.IsSubscribed( + this.mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, @@ -87,11 +87,11 @@ public void IsSubscribed_ShouldReturnFalse_WhenUserDoesNotHavePermissionOnTheSub It.IsAny(), It.IsAny())).Returns(SubscriptionDataReaderMockHelper.CreateSubscriptionReader(subscriptionCollection)); - subscriptionSecurityController + this.subscriptionSecurityController .Setup(ssc => ssc.HasPermission(It.IsAny())).Returns(false); - //Act - var isSubscribed = subscriptionController.IsSubscribed(subscription); + // Act + var isSubscribed = this.subscriptionController.IsSubscribed(subscription); // Assert Assert.AreEqual(false, isSubscribed); @@ -106,7 +106,7 @@ public void IsSubscribed_ShouldReturnTrue_WhenUserHasPermissionOnTheSubscription var subscriptionCollection = new[] { subscription }; - mockDataService.Setup(ds => ds.IsSubscribed( + this.mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, @@ -114,11 +114,11 @@ public void IsSubscribed_ShouldReturnTrue_WhenUserHasPermissionOnTheSubscription It.IsAny(), It.IsAny())).Returns(SubscriptionDataReaderMockHelper.CreateSubscriptionReader(subscriptionCollection)); - subscriptionSecurityController + this.subscriptionSecurityController .Setup(ssc => ssc.HasPermission(It.IsAny())).Returns(true); - //Act - var isSubscribed = subscriptionController.IsSubscribed(subscription); + // Act + var isSubscribed = this.subscriptionController.IsSubscribed(subscription); // Assert Assert.AreEqual(true, isSubscribed); @@ -131,7 +131,7 @@ public void IsSubscribed_ShouldCallDataService_WhenNoError() var subscription = new SubscriptionBuilder() .Build(); - mockDataService.Setup(ds => ds.IsSubscribed( + this.mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, @@ -139,26 +139,25 @@ public void IsSubscribed_ShouldCallDataService_WhenNoError() subscription.ModuleId, subscription.TabId)).Returns(SubscriptionDataReaderMockHelper.CreateEmptySubscriptionReader()).Verifiable(); - //Act - subscriptionController.IsSubscribed(subscription); + // Act + this.subscriptionController.IsSubscribed(subscription); // Assert - mockDataService.Verify(ds => ds.IsSubscribed( + this.mockDataService.Verify( + ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, subscription.ModuleId, subscription.TabId), Times.Once); - } - #endregion - - #region AddSubscription method tests + } + [Test] public void AddSubscription_ShouldThrowArgumentNullException_WhenSubscriptionIsNull() { - //Act, Arrange - Assert.Throws(() => subscriptionController.AddSubscription(null)); + // Act, Arrange + Assert.Throws(() => this.subscriptionController.AddSubscription(null)); } [Test] @@ -169,8 +168,8 @@ public void AddSubscription_ShouldThrowArgumentOutOfRangeException_WhenSubscript .WithUserId(-1) .Build(); - //Act, Assert - Assert.Throws(() => subscriptionController.AddSubscription(subscription)); + // Act, Assert + Assert.Throws(() => this.subscriptionController.AddSubscription(subscription)); } [Test] @@ -181,8 +180,8 @@ public void AddSubscription_ShouldThrowArgumentOutOfRangeException_WhenSubscript .WithSubscriptionTypeId(-1) .Build(); - //Act, Assert - Assert.Throws(() => subscriptionController.AddSubscription(subscription)); + // Act, Assert + Assert.Throws(() => this.subscriptionController.AddSubscription(subscription)); } [Test] @@ -193,32 +192,33 @@ public void AddSubscription_ShouldThrowArgumentNullException_WhenSubscriptionObj .WithObjectKey(null) .Build(); - //Act, Assert - Assert.Throws(() => subscriptionController.AddSubscription(subscription)); + // Act, Assert + Assert.Throws(() => this.subscriptionController.AddSubscription(subscription)); } - + [Test] public void AddSubscription_ShouldCallDataService_WhenNoError() { // Arrange var subscription = new SubscriptionBuilder() .Build(); - - mockDataService.Setup(ds => ds.AddSubscription( - subscription.UserId, - subscription.PortalId, - subscription.SubscriptionTypeId, - subscription.ObjectKey, - subscription.Description, - subscription.ModuleId, + + this.mockDataService.Setup(ds => ds.AddSubscription( + subscription.UserId, + subscription.PortalId, + subscription.SubscriptionTypeId, + subscription.ObjectKey, + subscription.Description, + subscription.ModuleId, subscription.TabId, subscription.ObjectData)).Verifiable(); - //Act - subscriptionController.AddSubscription(subscription); + // Act + this.subscriptionController.AddSubscription(subscription); // Assert - mockDataService.Verify(ds => ds.AddSubscription( + this.mockDataService.Verify( + ds => ds.AddSubscription( subscription.UserId, subscription.PortalId, subscription.SubscriptionTypeId, @@ -238,7 +238,7 @@ public void AddSubscription_ShouldFilledUpTheSubscriptionIdPropertyOfTheInputSub var subscription = new SubscriptionBuilder() .Build(); - mockDataService.Setup(ds => ds.AddSubscription( + this.mockDataService.Setup(ds => ds.AddSubscription( subscription.UserId, subscription.PortalId, subscription.SubscriptionTypeId, @@ -248,20 +248,18 @@ public void AddSubscription_ShouldFilledUpTheSubscriptionIdPropertyOfTheInputSub subscription.TabId, subscription.ObjectData)).Returns(expectedSubscriptionId); - //Act - subscriptionController.AddSubscription(subscription); + // Act + this.subscriptionController.AddSubscription(subscription); // Assert Assert.AreEqual(expectedSubscriptionId, subscription.SubscriptionId); - } - #endregion - - #region DeleteSubscription method tests + } + [Test] public void DeleteSubscription_ShouldThrowArgumentNullException_WhenSubscriptionIsNull() { - //Act, Assert - Assert.Throws(() => subscriptionController.DeleteSubscription(null)); + // Act, Assert + Assert.Throws(() => this.subscriptionController.DeleteSubscription(null)); } [Test] @@ -271,21 +269,21 @@ public void DeleteSubscriptionType_ShouldCallDeleteSubscriptionDataService_WhenS var subscription = new SubscriptionBuilder() .Build(); - mockDataService.Setup(ds => ds.IsSubscribed( + this.mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, subscription.ObjectKey, It.IsAny(), - It.IsAny())).Returns(SubscriptionDataReaderMockHelper.CreateSubscriptionReader(new [] { subscription })); + It.IsAny())).Returns(SubscriptionDataReaderMockHelper.CreateSubscriptionReader(new[] { subscription })); + + this.mockDataService.Setup(ds => ds.DeleteSubscription(It.IsAny())).Verifiable(); - mockDataService.Setup(ds => ds.DeleteSubscription(It.IsAny())).Verifiable(); - - //Act - subscriptionController.DeleteSubscription(subscription); + // Act + this.subscriptionController.DeleteSubscription(subscription); - //Assert - mockDataService.Verify(ds => ds.DeleteSubscription(It.IsAny()), Times.Once); + // Assert + this.mockDataService.Verify(ds => ds.DeleteSubscription(It.IsAny()), Times.Once); } [Test] @@ -295,7 +293,7 @@ public void DeleteSubscriptionType_ShouldNotCallDeleteSubscriptionDataService_Wh var subscription = new SubscriptionBuilder() .Build(); - mockDataService.Setup(ds => ds.IsSubscribed( + this.mockDataService.Setup(ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, subscription.SubscriptionTypeId, @@ -303,12 +301,11 @@ public void DeleteSubscriptionType_ShouldNotCallDeleteSubscriptionDataService_Wh It.IsAny(), It.IsAny())).Returns(SubscriptionDataReaderMockHelper.CreateEmptySubscriptionReader()); - //Act - subscriptionController.DeleteSubscription(subscription); + // Act + this.subscriptionController.DeleteSubscription(subscription); - //Assert - mockDataService.Verify(ds => ds.DeleteSubscription(It.IsAny()), Times.Never); - } - #endregion + // Assert + this.mockDataService.Verify(ds => ds.DeleteSubscription(It.IsAny()), Times.Never); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs index f7a9f7da7b4..96e2ce0974e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs @@ -1,44 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Social.Subscriptions; -using DotNetNuke.Services.Social.Subscriptions.Data; -using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; -using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Subscriptions; + using DotNetNuke.Services.Social.Subscriptions.Data; + using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; + using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class SubscriptionTypeControllerTests { + private const string SubscriptionTypesCacheKey = "DNN_" + DataCache.SubscriptionTypesCacheKey; + private SubscriptionTypeController subscriptionTypeController; private Mock mockDataService; private Mock mockCacheProvider; - private const string SubscriptionTypesCacheKey = "DNN_" + DataCache.SubscriptionTypesCacheKey; - [SetUp] public void SetUp() { // Setup Mocks and Stub - mockDataService = new Mock(); - mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); + this.mockDataService = new Mock(); + this.mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); - DataService.SetTestableInstance(mockDataService.Object); - - // Setup SUT - subscriptionTypeController = new SubscriptionTypeController(); - } + DataService.SetTestableInstance(this.mockDataService.Object); - #region GetSubscriptionTypes method tests + // Setup SUT + this.subscriptionTypeController = new SubscriptionTypeController(); + } + [Test] public void GetSubscriptionTypes_ShouldCallDataService_WhenNoError() { @@ -49,41 +49,37 @@ public void GetSubscriptionTypes_ShouldCallDataService_WhenNoError() .Returns("0"); HostController.RegisterInstance(mockHostController.Object); - mockDataService + this.mockDataService .Setup(ds => ds.GetSubscriptionTypes()) .Returns(SubscriptionTypeDataReaderMockHelper.CreateEmptySubscriptionTypeReader()) .Verifiable(); - - //Act - subscriptionTypeController.GetSubscriptionTypes(); - //Assert - mockDataService.Verify(ds => ds.GetSubscriptionTypes(), Times.Once()); + // Act + this.subscriptionTypeController.GetSubscriptionTypes(); + + // Assert + this.mockDataService.Verify(ds => ds.GetSubscriptionTypes(), Times.Once()); } [Test] public void GetSubscriptionTypes_ShouldThrowArgumentNullException_WhenPredicateIsNull() { - //Act, Arrange - Assert.Throws(() => subscriptionTypeController.GetSubscriptionTypes(null)); - } - #endregion - - #region GetSubscriptionType method tests + // Act, Arrange + Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionTypes(null)); + } + [Test] public void GetSubscriptionType_ShouldThrowArgumentNullException_WhenPredicateIsNull() { - //Act, Assert - Assert.Throws(() => subscriptionTypeController.GetSubscriptionType(null)); - } - #endregion - - #region AddSubscriptionType method tests + // Act, Assert + Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionType(null)); + } + [Test] public void AddSubscriptionType_ShouldThrowArgumentNullException_WhenSubscriptionTypeIsNull() { - //Act, Arrange - Assert.Throws(() => subscriptionTypeController.AddSubscriptionType(null)); + // Act, Arrange + Assert.Throws(() => this.subscriptionTypeController.AddSubscriptionType(null)); } [Test] @@ -93,17 +89,17 @@ public void AddSubscriptionType_ShouldFilledUpTheSubscriptionTypeIdPropertyOfThe const int expectedSubscriptionTypeId = 12; var subscriptionType = new SubscriptionTypeBuilder().Build(); - mockDataService + this.mockDataService .Setup(ds => ds.AddSubscriptionType( - subscriptionType.SubscriptionName, - subscriptionType.FriendlyName, + subscriptionType.SubscriptionName, + subscriptionType.FriendlyName, subscriptionType.DesktopModuleId)) .Returns(expectedSubscriptionTypeId); - //Act - subscriptionTypeController.AddSubscriptionType(subscriptionType); + // Act + this.subscriptionTypeController.AddSubscriptionType(subscriptionType); - //Assert + // Assert Assert.AreEqual(expectedSubscriptionTypeId, subscriptionType.SubscriptionTypeId); } @@ -111,20 +107,18 @@ public void AddSubscriptionType_ShouldFilledUpTheSubscriptionTypeIdPropertyOfThe public void AddSubscriptionType_ShouldCleanCache_WhenNoError() { // Arrange - mockDataService.Setup(ds => ds.AddSubscriptionType(It.IsAny(), It.IsAny(), It.IsAny())); - mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); + this.mockDataService.Setup(ds => ds.AddSubscriptionType(It.IsAny(), It.IsAny(), It.IsAny())); + this.mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); var subscriptionType = new SubscriptionTypeBuilder().Build(); - //Act - subscriptionTypeController.AddSubscriptionType(subscriptionType); - - //Assert - mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); - } - #endregion + // Act + this.subscriptionTypeController.AddSubscriptionType(subscriptionType); - #region DeleteSubscriptionType method tests + // Assert + this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); + } + [Test] public void DeleteSubscriptionType_ShouldThrowArgumentOutOfRangeException_WhenSubscriptionTypeIdIsNegative() { @@ -134,31 +128,31 @@ public void DeleteSubscriptionType_ShouldThrowArgumentOutOfRangeException_WhenSu .Build(); // Act, Assert - Assert.Throws(() => subscriptionTypeController.DeleteSubscriptionType(subscriptionType)); + Assert.Throws(() => this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType)); } [Test] public void DeleteSubscriptionType_ShouldThrowNullArgumentException_WhenSubscriptionTypeIsNull() { // Act, Assert - Assert.Throws(() => subscriptionTypeController.DeleteSubscriptionType(null)); + Assert.Throws(() => this.subscriptionTypeController.DeleteSubscriptionType(null)); } [Test] public void DeleteSubscriptionType_ShouldCallDataService_WhenNoError() { - // Arrange + // Arrange var subscriptionType = new SubscriptionTypeBuilder().Build(); - mockDataService + this.mockDataService .Setup(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId)) .Verifiable(); - - //Act - subscriptionTypeController.DeleteSubscriptionType(subscriptionType); - //Assert - mockDataService.Verify(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId), Times.Once()); + // Act + this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType); + + // Assert + this.mockDataService.Verify(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId), Times.Once()); } [Test] @@ -167,17 +161,16 @@ public void DeleteSubscriptionType_ShouldCleanCache_WhenNoError() // Arrange var subscriptionType = new SubscriptionTypeBuilder().Build(); - mockDataService.Setup(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId)); - mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); - - //Act - subscriptionTypeController.DeleteSubscriptionType(subscriptionType); + this.mockDataService.Setup(ds => ds.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId)); + this.mockCacheProvider.Setup(cp => cp.Remove(SubscriptionTypesCacheKey)).Verifiable(); - //Assert - mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); - } - #endregion + // Act + this.subscriptionTypeController.DeleteSubscriptionType(subscriptionType); + // Assert + this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); + } + [TearDown] public void TearDown() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs index 9ecdddba4f8..928b7a92a3e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs @@ -1,26 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Social.Messaging; -using DotNetNuke.Services.Social.Messaging.Data; -using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; -using DotNetNuke.Tests.Core.Controllers.Messaging.Helpers; -using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Messaging { + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Social.Messaging; + using DotNetNuke.Services.Social.Messaging.Data; + using DotNetNuke.Tests.Core.Controllers.Messaging.Builders; + using DotNetNuke.Tests.Core.Controllers.Messaging.Helpers; + using DotNetNuke.Tests.Core.Controllers.Messaging.Mocks; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class UserPreferencesControllerTests { @@ -32,68 +33,64 @@ public class UserPreferencesControllerTests public void SetUp() { // Setup Mocks and Stub - mockDataService = new Mock(); - mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); + this.mockDataService = new Mock(); + this.mockCacheProvider = MockComponentProvider.CreateDataCacheProvider(); - DataService.RegisterInstance(mockDataService.Object); - SetupCachingProviderHelper.SetupCachingProvider(mockCacheProvider); + DataService.RegisterInstance(this.mockDataService.Object); + SetupCachingProviderHelper.SetupCachingProvider(this.mockCacheProvider); // Setup SUT - userPrefencesController = new UserPreferencesController(); + this.userPrefencesController = new UserPreferencesController(); } [TearDown] public void TearDown() { ComponentFactory.Container = null; - } - - #region Constructor tests + } + [Test] public void UserPreferencesController_ShouldThrowArgumentNullException_WhenNullDataServiceIsPassedInTheConstructor() { - //Act, Assert + // Act, Assert Assert.Throws(() => new UserPreferencesController(null)); - } - #endregion - - #region SetUserPreference tests + } + [Test] public void SetUserPreference_ShouldCallDataService_WhenNoError() { // Arrange var userPreference = new UserPreferenceBuilder().Build(); - mockDataService.Setup(ds => ds.SetUserPreference( - userPreference.PortalId, - userPreference.UserId, - (int) userPreference.MessagesEmailFrequency, + this.mockDataService.Setup(ds => ds.SetUserPreference( + userPreference.PortalId, + userPreference.UserId, + (int)userPreference.MessagesEmailFrequency, (int)userPreference.NotificationsEmailFrequency)).Verifiable(); - //Act - userPrefencesController.SetUserPreference(userPreference); + // Act + this.userPrefencesController.SetUserPreference(userPreference); // Assert - mockDataService.Verify(ds => ds.SetUserPreference( + this.mockDataService.Verify( + ds => ds.SetUserPreference( userPreference.PortalId, userPreference.UserId, (int)userPreference.MessagesEmailFrequency, (int)userPreference.NotificationsEmailFrequency), Times.Once); - } - #endregion - - #region GetUserPreference tests + } + [Test] public void GetUserPreference_ShouldReturnNullObject_WhenUserDoesNotHavePreference() { // Arrange var user = GetValidUser(); - mockDataService.Setup(ds => ds.GetUserPreference( + this.mockDataService.Setup(ds => ds.GetUserPreference( Constants.PORTAL_ValidPortalId, Constants.UserID_User12)).Returns(UserPreferenceDataReaderMockHelper.CreateEmptyUserPreferenceReader); - //Act - var userPreference = userPrefencesController.GetUserPreference(user); + // Act + var userPreference = this.userPrefencesController.GetUserPreference(user); // Assert Assert.IsNull(userPreference); @@ -109,11 +106,11 @@ public void GetUserPreference_ShouldReturnUserPreference_WhenUserHasPreference() .Build(); var user = GetValidUser(); - mockDataService.Setup(ds => ds.GetUserPreference(Constants.PORTAL_ValidPortalId,Constants.UserID_User12)) + this.mockDataService.Setup(ds => ds.GetUserPreference(Constants.PORTAL_ValidPortalId, Constants.UserID_User12)) .Returns(UserPreferenceDataReaderMockHelper.CreateUserPreferenceReader(expectedUserPreference)); - //Act - var userPreference = userPrefencesController.GetUserPreference(user); + // Act + var userPreference = this.userPrefencesController.GetUserPreference(user); // Assert Assert.IsNotNull(userPreference); @@ -121,16 +118,15 @@ public void GetUserPreference_ShouldReturnUserPreference_WhenUserHasPreference() Assert.AreEqual(expectedUserPreference.NotificationsEmailFrequency, userPreference.NotificationsEmailFrequency); Assert.AreEqual(user.PortalID, userPreference.PortalId); Assert.AreEqual(user.UserID, userPreference.UserId); - } - #endregion - + } + private static UserInfo GetValidUser() { return new UserInfo { DisplayName = Constants.UserDisplayName_User12, UserID = Constants.UserID_User12, - PortalID = Constants.PORTAL_ValidPortalId + PortalID = Constants.PORTAL_ValidPortalId, }; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs index 6748014e30a..6f554a11169 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs @@ -1,88 +1,87 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.IO; -using System.Threading; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Portals.Internal; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Portal { + using System.Collections.Generic; + using System.IO; + using System.Threading; + + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Portals.Internal; + using Moq; + using NUnit.Framework; + [TestFixture] public class PortalControllerTests { - private Mock _mockPortalTemplateIO; private const string HostMapPath = @"C:\path"; - private const string DefaultName = "Default"; + + private Mock _mockPortalTemplateIO; + private const string DefaultDeName = "Rückstellungs-Web site"; + private const string DefaultDeDescription = "A new german description"; private static readonly string DefaultPath = MakePath(DefaultName); private static readonly string DefaultDePath = MakePath(DefaultName, "de-DE"); - private const string DefaultDeName = "Rückstellungs-Web site"; - const string DefaultDeDescription = "A new german description"; + private const string StaticName = "Static"; + + private const string StaticDescription = "An description from a template file"; + private const string AlternateName = "Alternate"; + + private const string AlternateDeName = "Alternate in German"; + private const string ResourceName = "Resource"; + private static readonly Dictionary DefaultExpectationsDe = new Dictionary { - {"Name", DefaultDeName }, - {"TemplateFilePath", DefaultPath}, - {"LanguageFilePath", DefaultDePath}, - {"CultureCode", "de-DE"}, - {"Description", DefaultDeDescription} + { "Name", DefaultDeName }, + { "TemplateFilePath", DefaultPath }, + { "LanguageFilePath", DefaultDePath }, + { "CultureCode", "de-DE" }, + { "Description", DefaultDeDescription }, }; private static readonly string DefaultUsPath = MakePath(DefaultName, "en-US"); private static readonly Dictionary DefaultExpectationsUs = new Dictionary { - {"Name", DefaultName }, - {"TemplateFilePath", DefaultPath}, - {"LanguageFilePath", DefaultUsPath}, - {"CultureCode", "en-US"}, + { "Name", DefaultName }, + { "TemplateFilePath", DefaultPath }, + { "LanguageFilePath", DefaultUsPath }, + { "CultureCode", "en-US" }, }; - - private const string StaticName = "Static"; - readonly static string CultureCode = Thread.CurrentThread.CurrentCulture.Name; + private static readonly string CultureCode = Thread.CurrentThread.CurrentCulture.Name; private static readonly string StaticPath = MakePath(StaticName); - const string StaticDescription = "An description from a template file"; private static readonly Dictionary StaticExpectations = new Dictionary { - {"Name", StaticName}, - {"TemplateFilePath", StaticPath}, - {"Description", StaticDescription}, - {"CultureCode", CultureCode} + { "Name", StaticName }, + { "TemplateFilePath", StaticPath }, + { "Description", StaticDescription }, + { "CultureCode", CultureCode }, }; - - private const string AlternateName = "Alternate"; private static readonly string AlternatePath = MakePath(AlternateName); private static readonly string AlternateDePath = MakePath(AlternateName, "de-DE"); - private const string AlternateDeName = "Alternate in German"; private static readonly Dictionary AlternateExpectationsDe = new Dictionary { - {"Name", AlternateDeName }, - {"TemplateFilePath", AlternatePath}, - {"LanguageFilePath", AlternateDePath}, - {"CultureCode", "de-DE"}, + { "Name", AlternateDeName }, + { "TemplateFilePath", AlternatePath }, + { "LanguageFilePath", AlternateDePath }, + { "CultureCode", "de-DE" }, }; - - private const string ResourceName = "Resource"; private static readonly string ResourcePath = MakePath(ResourceName); private static readonly string ResourceFilePath = ResourcePath + ".resources"; private static readonly Dictionary ResourceExpectations = new Dictionary { - {"Name", ResourceName}, - {"TemplateFilePath", ResourcePath}, - {"ResourceFilePath", ResourceFilePath}, - {"CultureCode", CultureCode} + { "Name", ResourceName }, + { "TemplateFilePath", ResourcePath }, + { "ResourceFilePath", ResourceFilePath }, + { "CultureCode", CultureCode }, }; [SetUp] public void SetUp() { - _mockPortalTemplateIO = new Mock(); - PortalTemplateIO.SetTestableInstance(_mockPortalTemplateIO.Object); + this._mockPortalTemplateIO = new Mock(); + PortalTemplateIO.SetTestableInstance(this._mockPortalTemplateIO.Object); } [TearDown] @@ -90,64 +89,62 @@ public void TearDown() { PortalTemplateIO.ClearInstance(); } - + [Test] public void NoTemplatesReturnsEmptyList() { - //Arrange - - - //Act + // Arrange + + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); - //Assert + // Assert Assert.AreEqual(0, templates.Count); } [Test] public void LanguageFileWithoutATemplateIsIgnored() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(ToEnumerable(DefaultDePath)); + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(this.ToEnumerable(DefaultDePath)); - //Act + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); - //Assert + // Assert Assert.AreEqual(0, templates.Count); } [Test] public void TemplatesWithNoLanguageFilesAreLoaded() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(ToEnumerable(StaticPath)); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(StaticPath)).Returns(CreateTemplateFileReader(StaticDescription)); - - //Act + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(StaticPath)); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(StaticPath)).Returns(this.CreateTemplateFileReader(StaticDescription)); + + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); - //Assert + // Assert Assert.AreEqual(1, templates.Count); AssertTemplateInfo(StaticExpectations, templates[0]); } - - + [Test] public void TemplateWith2Languages() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(ToEnumerable(DefaultPath)); - _mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(ToEnumerable(DefaultDePath, DefaultUsPath)); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "en-US")).Returns(DefaultUsPath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultUsPath)).Returns(CreateLanguageFileReader(DefaultName)); - - //Act + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(DefaultPath)); + this._mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(this.ToEnumerable(DefaultDePath, DefaultUsPath)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(this.CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "en-US")).Returns(DefaultUsPath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultUsPath)).Returns(this.CreateLanguageFileReader(DefaultName)); + + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); - //Assert + // Assert Assert.AreEqual(2, templates.Count); AssertTemplateInfo(DefaultExpectationsDe, templates[0]); AssertTemplateInfo(DefaultExpectationsUs, templates[1]); @@ -156,20 +153,20 @@ public void TemplateWith2Languages() [Test] public void TwoTemplatesAssortedLanguages() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns( ToEnumerable(DefaultPath, AlternatePath) ); - _mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(ToEnumerable(DefaultDePath, DefaultUsPath, AlternateDePath )); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "en-US")).Returns(DefaultUsPath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultUsPath)).Returns(CreateLanguageFileReader(DefaultName)); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(AlternatePath, "de-DE")).Returns(AlternateDePath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(AlternateDePath)).Returns(CreateLanguageFileReader(AlternateDeName)); - - //Act + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(DefaultPath, AlternatePath)); + this._mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(this.ToEnumerable(DefaultDePath, DefaultUsPath, AlternateDePath)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(this.CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "en-US")).Returns(DefaultUsPath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultUsPath)).Returns(this.CreateLanguageFileReader(DefaultName)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(AlternatePath, "de-DE")).Returns(AlternateDePath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(AlternateDePath)).Returns(this.CreateLanguageFileReader(AlternateDeName)); + + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); - //Assert + // Assert Assert.AreEqual(3, templates.Count); AssertTemplateInfo(DefaultExpectationsDe, templates[0]); AssertTemplateInfo(DefaultExpectationsUs, templates[1]); @@ -179,14 +176,14 @@ public void TwoTemplatesAssortedLanguages() [Test] public void ResourceFileIsLocatedWhenPresent() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(ToEnumerable(ResourcePath)); - _mockPortalTemplateIO.Setup(x => x.GetResourceFilePath(ResourcePath)).Returns(ResourceFilePath); + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(ResourcePath)); + this._mockPortalTemplateIO.Setup(x => x.GetResourceFilePath(ResourcePath)).Returns(ResourceFilePath); - //Act + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); - //Assert + // Assert Assert.AreEqual(1, templates.Count); AssertTemplateInfo(ResourceExpectations, templates[0]); } @@ -194,16 +191,16 @@ public void ResourceFileIsLocatedWhenPresent() [Test] public void SingleTemplateAndLanguage() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(ToEnumerable(DefaultPath)); - _mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(ToEnumerable(DefaultDePath)); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(DefaultPath)); + this._mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(this.ToEnumerable(DefaultDePath)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(this.CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); - //Act + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); - //Assert + // Assert Assert.AreEqual(1, templates.Count); AssertTemplateInfo(DefaultExpectationsDe, templates[0]); } @@ -211,71 +208,50 @@ public void SingleTemplateAndLanguage() [Test] public void ATemplateCanBeLoadedDirectly() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(ToEnumerable(DefaultPath)); - _mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(ToEnumerable(DefaultDePath)); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(DefaultPath)); + this._mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(this.ToEnumerable(DefaultDePath)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(this.CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); - //Act + // Act var template = PortalController.Instance.GetPortalTemplate(DefaultPath, "de-DE"); - //Assert + // Assert AssertTemplateInfo(DefaultExpectationsDe, template); } [Test] public void GetPortalTemplateReturnsNullIfCultureDoesNotMatch() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(ToEnumerable(DefaultPath)); - _mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(ToEnumerable(DefaultDePath)); - _mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(DefaultPath)); + this._mockPortalTemplateIO.Setup(x => x.EnumerateLanguageFiles()).Returns(this.ToEnumerable(DefaultDePath)); + this._mockPortalTemplateIO.Setup(x => x.GetLanguageFilePath(DefaultPath, "de-DE")).Returns(DefaultDePath); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(DefaultDePath)).Returns(this.CreateLanguageFileReader(DefaultDeName, DefaultDeDescription)); - //Act + // Act var template = PortalController.Instance.GetPortalTemplate(DefaultPath, "de"); - //Assert + // Assert Assert.IsNull(template); } [Test] public void GetPortalTemplateCanReturnAStaticTemplate() { - //Arrange - _mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(ToEnumerable(StaticPath)); - _mockPortalTemplateIO.Setup(x => x.OpenTextReader(StaticPath)).Returns(CreateTemplateFileReader(StaticDescription)); + // Arrange + this._mockPortalTemplateIO.Setup(x => x.EnumerateTemplates()).Returns(this.ToEnumerable(StaticPath)); + this._mockPortalTemplateIO.Setup(x => x.OpenTextReader(StaticPath)).Returns(this.CreateTemplateFileReader(StaticDescription)); - //Act + // Act var template = PortalController.Instance.GetPortalTemplate(StaticPath, CultureCode); - //Assert + // Assert AssertTemplateInfo(StaticExpectations, template); } - private TextReader CreateLanguageFileReader(string name) - { - return CreateLanguageFileReader(name, null); - } - - private TextReader CreateLanguageFileReader(string name, string description) - { - if(description != null) - { - description = string.Format("{0}", description); - } - var xml = string.Format("{0}{1}", name, description); - return new StringReader(xml); - } - - TextReader CreateTemplateFileReader(string description) - { - var xml = string.Format("{0}", description); - return new StringReader(xml); - } - - private static void AssertTemplateInfo(Dictionary expectations , PortalController.PortalTemplateInfo templateInfo) + private static void AssertTemplateInfo(Dictionary expectations, PortalController.PortalTemplateInfo templateInfo) { AssertTemplateField(expectations, "Name", templateInfo.Name); AssertTemplateField(expectations, "TemplateFilePath", templateInfo.TemplateFilePath); @@ -289,7 +265,7 @@ private static void AssertTemplateField(Dictionary expectations, { string expected; expectations.TryGetValue(key, out expected); - if(string.IsNullOrEmpty(expected)) + if (string.IsNullOrEmpty(expected)) { Assert.IsNullOrEmpty(value, string.Format("Checking value of " + key)); } @@ -299,9 +275,26 @@ private static void AssertTemplateField(Dictionary expectations, } } - private IEnumerable ToEnumerable(params T[] input) + private TextReader CreateLanguageFileReader(string name) { - return input; + return this.CreateLanguageFileReader(name, null); + } + + private TextReader CreateLanguageFileReader(string name, string description) + { + if (description != null) + { + description = string.Format("{0}", description); + } + + var xml = string.Format("{0}{1}", name, description); + return new StringReader(xml); + } + + private TextReader CreateTemplateFileReader(string description) + { + var xml = string.Format("{0}", description); + return new StringReader(xml); } private static string MakePath(string name) @@ -314,5 +307,10 @@ private static string MakePath(string name, string culture) { return string.Format(@"{0}.{1}.resx", MakePath(name), culture); } + + private IEnumerable ToEnumerable(params T[] input) + { + return input; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs index 8046bdd3f29..2828e16f7af 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs @@ -1,42 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Portals.Data; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Portal { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Portals.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + // ReSharper disable InconsistentNaming - [TestFixture] public class PortalGroupControllerTests { private Mock _mockData; #pragma warning disable 649 - private UserCopiedCallback userCopied; + private UserCopiedCallback userCopied; #pragma warning restore 649 - - #region Test Initialize - + [SetUp] public void SetUp() { - _mockData = MockComponentProvider.CreateDataProvider(); + this._mockData = MockComponentProvider.CreateDataProvider(); DataTable hostSettingsTable = new DataTable("HostSettings"); var nameCol = hostSettingsTable.Columns.Add("SettingName"); @@ -45,27 +40,23 @@ public void SetUp() hostSettingsTable.PrimaryKey = new[] { nameCol }; hostSettingsTable.Rows.Add("PerformanceSetting", "0", false); - _mockData.Setup(c => c.GetHostSettings()).Returns(hostSettingsTable.CreateDataReader()); + this._mockData.Setup(c => c.GetHostSettings()).Returns(hostSettingsTable.CreateDataReader()); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region Constructor Tests - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_Constructor_Throws_On_Null_DataService() { - //Arrange + // Arrange var mockPortalController = new Mock(); - //Act, Assert + // Act, Assert new PortalGroupController(null, mockPortalController.Object); } @@ -73,68 +64,63 @@ public void PortalGroupController_Constructor_Throws_On_Null_DataService() [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_Constructor_Throws_On_Null_PortalController() { - //Arrange + // Arrange var mockDataService = new Mock(); - //Act, Assert + // Act, Assert new PortalGroupController(mockDataService.Object, null); - } - - #endregion - - #region AddPortalToGroup Tests - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_AddPortalToGroup_Throws_On_Null_PortalGroup() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; - //Act, Assert - controller.AddPortalToGroup(portal, null, userCopied); + // Act, Assert + controller.AddPortalToGroup(portal, null, this.userCopied); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_AddPortalToGroup_Throws_On_Null_Portal() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - - - //Act, Assert - controller.AddPortalToGroup(null, portalGroup, userCopied); + + // Act, Assert + controller.AddPortalToGroup(null, portalGroup, this.userCopied); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalGroupId() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - var portal = new PortalInfo {PortalID = Constants.PORTAL_ValidPortalId}; + var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = -1 }; - //Act, Assert - controller.AddPortalToGroup(portal, portalGroup, userCopied); + // Act, Assert + controller.AddPortalToGroup(portal, portalGroup, this.userCopied); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalId() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); @@ -143,31 +129,27 @@ public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalId() PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - //Act, Assert - controller.AddPortalToGroup(portal, portalGroup, userCopied); - } - - #endregion - - #region AddPortalGroup Tests - + // Act, Assert + controller.AddPortalToGroup(portal, portalGroup, this.userCopied); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_AddPortalGroup_Throws_On_Null_PortalGroup() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - //Act, Assert + // Act, Assert controller.AddPortalGroup(null); } [Test] public void PortalGroupController_AddPortalGroup_Calls_DataService_On_Valid_Arguments() { - //Arrange + // Arrange MockComponentProvider.CreateNew(); var mockDataService = new Mock(); var mockPortalController = new Mock(); @@ -176,17 +158,17 @@ public void PortalGroupController_AddPortalGroup_Calls_DataService_On_Valid_Argu PortalGroupInfo portalGroup = CreateValidPortalGroup(); portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - //Act + // Act controller.AddPortalGroup(portalGroup); - //Assert + // Assert mockDataService.Verify(ds => ds.AddPortalGroup(portalGroup, It.IsAny())); } [Test] public void PortalGroupController_AddPortalGroup_Calls_PortalController_On_Valid_Arguments() { - //Arrange + // Arrange MockComponentProvider.CreateNew(); var mockDataService = new Mock(); var masterPortal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; @@ -198,10 +180,10 @@ public void PortalGroupController_AddPortalGroup_Calls_PortalController_On_Valid PortalGroupInfo portalGroup = CreateValidPortalGroup(); portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - //Act + // Act controller.AddPortalGroup(portalGroup); - //Assert + // Assert mockPortalController.Verify(pc => pc.GetPortal(portalGroup.MasterPortalId)); mockPortalController.Verify(pc => pc.UpdatePortalInfo(masterPortal)); } @@ -209,7 +191,7 @@ public void PortalGroupController_AddPortalGroup_Calls_PortalController_On_Valid [Test] public void PortalGroupController_AddPortalGroup_Returns_ValidId_On_Valid_PortalGroup() { - //Arrange + // Arrange MockComponentProvider.CreateNew(); var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddPortalGroup(It.IsAny(), It.IsAny())).Returns(Constants.PORTALGROUP_AddPortalGroupId); @@ -219,17 +201,17 @@ public void PortalGroupController_AddPortalGroup_Returns_ValidId_On_Valid_Portal PortalGroupInfo portalGroup = CreateValidPortalGroup(); portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - //Act + // Act int portalGroupId = controller.AddPortalGroup(portalGroup); - //Assert + // Assert Assert.AreEqual(Constants.PORTALGROUP_AddPortalGroupId, portalGroupId); } [Test] public void PortalGroupController_AddPortalGroup_Sets_PortalGroupId_Property_On_Valid_PortalGroup() { - //Arrange + // Arrange MockComponentProvider.CreateNew(); var mockDataService = new Mock(); mockDataService.Setup(ds => ds.AddPortalGroup(It.IsAny(), It.IsAny())).Returns(Constants.PORTALGROUP_AddPortalGroupId); @@ -239,27 +221,23 @@ public void PortalGroupController_AddPortalGroup_Sets_PortalGroupId_Property_On_ PortalGroupInfo portalGroup = CreateValidPortalGroup(); portalGroup.PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId; - //Act + // Act controller.AddPortalGroup(portalGroup); - //Assert + // Assert Assert.AreEqual(Constants.PORTALGROUP_AddPortalGroupId, portalGroup.PortalGroupId); - } - - #endregion - - #region DeletePortalGroup Tests - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_DeletePortalGroup_Throws_On_Null_PortalGroup() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - //Act, Assert + // Act, Assert controller.DeletePortalGroup(null); } @@ -267,7 +245,7 @@ public void PortalGroupController_DeletePortalGroup_Throws_On_Null_PortalGroup() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void PortalGroupController_DeletePortalGroup_Throws_On_Negative_PortalGroupId() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); @@ -275,14 +253,14 @@ public void PortalGroupController_DeletePortalGroup_Throws_On_Negative_PortalGro PortalGroupInfo portalGroup = CreateValidPortalGroup(); portalGroup.PortalGroupId = Null.NullInteger; - //Act, Assert + // Act, Assert controller.DeletePortalGroup(portalGroup); } [Test] public void PortalGroupController_DeletePortalGroup_Calls_DataService_On_Valid_PortalGroupId() { - //Arrange + // Arrange MockComponentProvider.CreateNew(); var mockDataService = new Mock(); var mockPortalController = new Mock(); @@ -291,22 +269,18 @@ public void PortalGroupController_DeletePortalGroup_Calls_DataService_On_Valid_P PortalGroupInfo portalGroup = CreateValidPortalGroup(); portalGroup.PortalGroupId = Constants.PORTALGROUP_DeletePortalGroupId; - //Act + // Act controller.DeletePortalGroup(portalGroup); - //Assert + // Assert mockDataService.Verify(ds => ds.DeletePortalGroup(portalGroup)); - } - - #endregion - - #region GetPortalGroups Tests - + } + [Test] public void PortalGroupController_GetPortalGroups_Calls_DataService() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateNew(); mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); @@ -316,17 +290,17 @@ public void PortalGroupController_GetPortalGroups_Calls_DataService() var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - //Act + // Act controller.GetPortalGroups(); - //Assert + // Assert mockDataService.Verify(ds => ds.GetPortalGroups()); } [Test] public void PortalGroupController_GetPortalGroups_Returns_EmptyList_If_No_Items() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateNew(); mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); @@ -336,72 +310,68 @@ public void PortalGroupController_GetPortalGroups_Returns_EmptyList_If_No_Items( var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - //Act + // Act IEnumerable portalGroups = controller.GetPortalGroups(); - //Assert + // Assert Assert.AreEqual(0, portalGroups.Count()); } [Test] public void PortalGroupController_GetPortalGroups_Returns_List_Of_PortalGroups() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateNew(); mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader(Constants.PORTALGROUP_ValidPortalGroupCount, - Constants.USER_ValidId)); + mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader( + Constants.PORTALGROUP_ValidPortalGroupCount, + Constants.USER_ValidId)); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - //Act + // Act IEnumerable portalGroups = controller.GetPortalGroups(); - //Assert + // Assert Assert.AreEqual(Constants.PORTALGROUP_ValidPortalGroupCount, portalGroups.Count()); - } - - #endregion - - #region RemovePortalFromGroup Tests - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_PortalGroup() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); var portal = new PortalInfo { PortalID = Constants.PORTAL_ValidPortalId }; - //Act, Assert - controller.RemovePortalFromGroup(portal, null, false, userCopied); + // Act, Assert + controller.RemovePortalFromGroup(portal, null, false, this.userCopied); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_Portal() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - - - //Act, Assert - controller.RemovePortalFromGroup(null, portalGroup, false, userCopied); + + // Act, Assert + controller.RemovePortalFromGroup(null, portalGroup, false, this.userCopied); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_PortalGroupId() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); @@ -410,15 +380,15 @@ public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_Porta PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = -1 }; - //Act, Assert - controller.RemovePortalFromGroup(portal, portalGroup, false, userCopied); + // Act, Assert + controller.RemovePortalFromGroup(portal, portalGroup, false, this.userCopied); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_PortalId() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); @@ -427,31 +397,27 @@ public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_Porta PortalGroupInfo portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - //Act, Assert - controller.RemovePortalFromGroup(portal, portalGroup, false, userCopied); - } - - #endregion - - #region UpdatePortalGroup Tests - + // Act, Assert + controller.RemovePortalFromGroup(portal, portalGroup, false, this.userCopied); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_UpdatePortalGroup_Throws_On_Null_PortalGroup() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); - //Act, Assert + // Act, Assert controller.UpdatePortalGroup(null); } [Test] public void PortalGroupController_UpdatePortalGroup_Throws_On_Negative_PortalGroupId() { - //Arrange + // Arrange var mockDataService = new Mock(); var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); @@ -465,7 +431,7 @@ public void PortalGroupController_UpdatePortalGroup_Throws_On_Negative_PortalGro [Test] public void PortalGroupController_UpdatePortalGroup_Calls_DataService_On_Valid_PortalGroup() { - //Arrange + // Arrange MockComponentProvider.CreateNew(); var mockDataService = new Mock(); var mockPortalController = new Mock(); @@ -476,15 +442,13 @@ public void PortalGroupController_UpdatePortalGroup_Calls_DataService_On_Valid_P portalGroup.PortalGroupName = Constants.PORTALGROUP_UpdateName; portalGroup.PortalGroupDescription = Constants.PORTALGROUP_UpdateDescription; - //Act + // Act controller.UpdatePortalGroup(portalGroup); - //Assert + // Assert mockDataService.Verify(ds => ds.UpdatePortalGroup(portalGroup, It.IsAny())); - } - - #endregion - + } + private static DataTable CreatePortalGroupTable() { // Create Categories table. @@ -509,22 +473,22 @@ private static DataTable CreatePortalGroupTable() private static string GetName(int i) { - return String.Format(String.Format(Constants.PORTALGROUP_ValidNameFormat, i)); + return string.Format(string.Format(Constants.PORTALGROUP_ValidNameFormat, i)); } private static string GetDescription(int i) { - return String.Format(String.Format(Constants.PORTALGROUP_ValidDescriptionFormat, i)); + return string.Format(string.Format(Constants.PORTALGROUP_ValidDescriptionFormat, i)); } private static PortalGroupInfo CreateValidPortalGroup() { - var portalGroup = new PortalGroupInfo - { - PortalGroupName = Constants.PORTALGROUP_ValidName, - PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, - MasterPortalId = Constants.PORTAL_ValidPortalId - }; + var portalGroup = new PortalGroupInfo + { + PortalGroupName = Constants.PORTALGROUP_ValidName, + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, + MasterPortalId = Constants.PORTAL_ValidPortalId, + }; return portalGroup; } @@ -542,16 +506,15 @@ private static IDataReader CreateValidPortalGroupsReader(int count, int startUse { i, -1, - name, + name, description, domain, - userId + userId, }); } return table.CreateDataReader(); } - } // ReSharper restore InconsistentNaming diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs index 25335ed7e80..288665d2fb4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs @@ -1,26 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Search.Controllers; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core.Controllers.Search { + using System; + + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + /// - /// Search Crawler for Module Content + /// Search Crawler for Module Content. /// /// public class FakeResultController : BaseResultController - { - #region Abstract Class Implmentation - + { public override bool HasViewPermission(SearchResult searchResult) { return true; @@ -28,11 +21,9 @@ public override bool HasViewPermission(SearchResult searchResult) // Returns the URL to the first instance of the module the user has access to view public override string GetDocUrl(SearchResult searchResult) - { - return "http://www.google.com"; - } - - #endregion + { + return "http://www.google.com"; + } } public class NoPermissionFakeResultController : FakeResultController @@ -42,7 +33,7 @@ public override bool HasViewPermission(SearchResult searchResult) { // This logic tests that based on ID we give permission to test recursive // search in SearchControllerImpl.GetSecurityTrimmedResults() method. - //The logic here is all documents with AuthorUserId's 6-9, 16-19, 26-29, etc. have + // The logic here is all documents with AuthorUserId's 6-9, 16-19, 26-29, etc. have // permission, while the rest don't return (searchResult.AuthorUserId % 10) > 5; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs index 1a4bf19a244..bb227586b68 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs @@ -1,37 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Threading; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Search { + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Threading; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Testing various aspects of SearchController + /// Testing various aspects of SearchController. /// [TestFixture] public class InternalSearchControllerTests - { - - #region Constants - + { + private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; + private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; + private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; + public enum SearchTypeIds { ModuleSearchTypeId = 1, @@ -39,15 +39,11 @@ public enum SearchTypeIds DocumentSearchTypeId, UrlSearchTypeId, OtherSearchTypeId, - UnknownSearchTypeId + UnknownSearchTypeId, } - - private const int ModuleSearchTypeId = (int) SearchTypeIds.ModuleSearchTypeId; - private const int TabSearchTypeId = (int) SearchTypeIds.TabSearchTypeId; - private const int DocumentSearchTypeId = (int) SearchTypeIds.DocumentSearchTypeId; - private const int UrlSearchTypeId = (int) SearchTypeIds.UrlSearchTypeId; - private const int OtherSearchTypeId = (int) SearchTypeIds.OtherSearchTypeId; - private const int UnknownSearchTypeId = (int) SearchTypeIds.UnknownSearchTypeId; + private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; + private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; + private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; private const int PortalId0 = 0; private const int PortalId1 = 1; @@ -79,15 +75,9 @@ public enum SearchTypeIds private const int LanguageIdEnFr = 2; private const int LanguageIdItIt = 3; private const int LanguageIdEsEs = 4; - - + private const string SearchIndexFolder = @"App_Data\InternalSearchTests"; - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - - #endregion - - #region Private Properties - + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private Mock _mockHostController; private Mock _mockCachingProvider; private Mock _mockDataProvider; @@ -96,116 +86,126 @@ public enum SearchTypeIds private Mock _mockUserController; private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - - #endregion - - #region Set Up - + private LuceneControllerImpl _luceneController; + [SetUp] public void SetUp() { ComponentFactory.Container = new SimpleContainer(); MockComponentProvider.ResetContainer(); - _mockDataProvider = MockComponentProvider.CreateDataProvider(); - _mockLocaleController = MockComponentProvider.CreateLocaleController(); - _mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - - _mockUserController = new Mock(); - _mockHostController = new Mock(); - _mockSearchHelper = new Mock(); + this._mockDataProvider = MockComponentProvider.CreateDataProvider(); + this._mockLocaleController = MockComponentProvider.CreateLocaleController(); + this._mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - SetupDataProvider(); - SetupHostController(); - SetupSearchHelper(); - SetupLocaleController(); + this._mockUserController = new Mock(); + this._mockHostController = new Mock(); + this._mockSearchHelper = new Mock(); - _mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())) - .Returns((int portalId, int userId) => GetUserByIdCallback(portalId, userId)); - UserController.SetTestableInstance(_mockUserController.Object); + this.SetupDataProvider(); + this.SetupHostController(); + this.SetupSearchHelper(); + this.SetupLocaleController(); - - CreateNewLuceneControllerInstance(); + this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())) + .Returns((int portalId, int userId) => this.GetUserByIdCallback(portalId, userId)); + UserController.SetTestableInstance(this._mockUserController.Object); + + this.CreateNewLuceneControllerInstance(); } [TearDown] public void TearDown() { - _luceneController.Dispose(); - DeleteIndexFolder(); + this._luceneController.Dispose(); + this.DeleteIndexFolder(); InternalSearchController.ClearInstance(); UserController.ClearInstance(); SearchHelper.ClearInstance(); LuceneController.ClearInstance(); - _luceneController = null; - } + this._luceneController = null; + } + + [Test] + public void SearchController_Add_Throws_On_Null_SearchDocument() + { + // Arrange - #endregion + // Act, Assert + Assert.Throws(() => this._internalSearchController.AddSearchDocument(null)); + } - #region Private Methods + [Test] + public void SearchController_Add_Throws_On_Null_Or_Empty_UniqueuKey() + { + // Arrange + // Act, Assert + Assert.Throws(() => this._internalSearchController.AddSearchDocument(new SearchDocument())); + } + private void CreateNewLuceneControllerInstance() { - DeleteIndexFolder(); + this.DeleteIndexFolder(); InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); - _internalSearchController = InternalSearchController.Instance; + this._internalSearchController = InternalSearchController.Instance; - if (_luceneController != null) + if (this._luceneController != null) { LuceneController.ClearInstance(); - _luceneController.Dispose(); + this._luceneController.Dispose(); } - _luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(_luceneController); + + this._luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this._luceneController); } private void SetupHostController() { - _mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - _mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(_readerStaleTimeSpan); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())) + this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())) .Returns(Constants.DefaultSearchDescriptionBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - HostController.RegisterInstance(_mockHostController.Object); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + HostController.RegisterInstance(this._mockHostController.Object); } private void SetupLocaleController() { - _mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale {LanguageId = -1, Code = string.Empty}); - _mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale {LanguageId = LanguageIdEnUs, Code = CultureEnUs}); - _mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale {LanguageId = LanguageIdEnFr, Code = CultureEnCa}); - _mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale {LanguageId = LanguageIdItIt, Code = CultureItIt}); - _mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale {LanguageId = LanguageIdEsEs, Code = CultureEsEs}); - - _mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale {LanguageId = LanguageIdEnUs, Code = CultureEnUs}); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale {LanguageId = LanguageIdEnUs, Code = CultureEnUs}); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale {LanguageId = LanguageIdEnFr, Code = CultureEnCa}); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale {LanguageId = LanguageIdItIt, Code = CultureItIt}); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale {LanguageId = LanguageIdEsEs, Code = CultureEsEs}); + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); } private void SetupDataProvider() { - //Standard DataProvider Path for Logging - _mockDataProvider.Setup(d => d.GetProviderPath()).Returns(""); + // Standard DataProvider Path for Logging + this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); DataTableReader searchTypes = null; - _mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) - .Callback(() => searchTypes = GetAllSearchTypes().CreateDataReader()) + this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) + .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) .Returns(() => searchTypes); - _mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); + this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); } private IDataReader GetPortalsCallBack(string culture) { - return GetPortalCallBack(PortalId0, CultureEnUs); + return this.GetPortalCallBack(PortalId0, CultureEnUs); } private IDataReader GetPortalCallBack(int portalId, string culture) @@ -221,7 +221,7 @@ private IDataReader GetPortalCallBack(int portalId, string culture) "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", - "LastModifiedOnDate", "CultureCode" + "LastModifiedOnDate", "CultureCode", }; foreach (var col in cols) @@ -240,34 +240,34 @@ private IDataReader GetPortalCallBack(int portalId, string culture) private void SetupSearchHelper() { - _mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - _mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(GetSynonymsCallBack); - _mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())) - .Returns((string name) => new SearchType {SearchTypeId = 0, SearchTypeName = name}); - _mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(GetSearchTypeByNameCallback); - _mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(GetSearchTypes()); - _mockSearchHelper.Setup(c => c.GetSynonymsGroups(It.IsAny(), It.IsAny())).Returns(GetSynonymsGroupsCallBack); - _mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( + this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(this.GetSynonymsCallBack); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())) + .Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); + this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); + this._mockSearchHelper.Setup(c => c.GetSynonymsGroups(It.IsAny(), It.IsAny())).Returns(this.GetSynonymsGroupsCallBack); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( new SearchStopWords { PortalId = 0, CultureCode = CultureEsEs, StopWords = "los,de,el", }); - _mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())) + this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new SearchHelperImpl().RephraseSearchText); - _mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(_mockSearchHelper.Object); + this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); } private IList GetSynonymsGroupsCallBack() { var groups = new List { - new SynonymsGroup {PortalId = 0, SynonymsGroupId = 1, SynonymsTags = string.Join(",", TermDNN, TermDotNetNuke)}, - new SynonymsGroup {PortalId = 0, SynonymsGroupId = 2, SynonymsTags = string.Join(",", TermLaptop, TermNotebook)}, - new SynonymsGroup {PortalId = 0, SynonymsGroupId = 3, SynonymsTags = string.Join(",", TermJump, TermLeap, TermHop)} + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 1, SynonymsTags = string.Join(",", TermDNN, TermDotNetNuke) }, + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 2, SynonymsTags = string.Join(",", TermLaptop, TermNotebook) }, + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 3, SynonymsTags = string.Join(",", TermJump, TermLeap, TermHop) }, }; return groups; @@ -275,7 +275,7 @@ private IList GetSynonymsGroupsCallBack() private SearchType GetSearchTypeByNameCallback(string searchTypeName) { - var searchType = new SearchType {SearchTypeName = searchTypeName, SearchTypeId = 0}; + var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; switch (searchTypeName) { case ModuleSearchTypeName: @@ -301,26 +301,28 @@ private SearchType GetSearchTypeByNameCallback(string searchTypeName) private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) { var synonyms = new List(); - if (term == "fox") - synonyms.Add("wolf"); - + if (term == "fox") + { + synonyms.Add("wolf"); + } + return synonyms; } private UserInfo GetUserByIdCallback(int portalId, int userId) { - return new UserInfo {UserID = userId, DisplayName = "User" + userId, PortalID = portalId}; + return new UserInfo { UserID = userId, DisplayName = "User" + userId, PortalID = portalId }; } private DataTable GetAllSearchTypes() { var dtSearchTypes = new DataTable("SearchTypes"); - var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof (int)); - dtSearchTypes.Columns.Add("SearchTypeName", typeof (string)); - dtSearchTypes.Columns.Add("SearchResultClass", typeof (string)); - dtSearchTypes.PrimaryKey = new[] {pkId}; + var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); + dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); + dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); + dtSearchTypes.PrimaryKey = new[] { pkId }; - //Create default Crawler + // Create default Crawler dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); @@ -334,16 +336,16 @@ private IEnumerable GetSearchTypes() { var searchTypes = new List { - new SearchType {SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass}, - new SearchType {SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass}, - new SearchType {SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass}, + new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, new SearchType { SearchTypeId = DocumentSearchTypeId, SearchTypeName = DocumentSearchTypeName, - SearchResultClass = NoPermissionFakeResultControllerClass + SearchResultClass = NoPermissionFakeResultControllerClass, }, - new SearchType {SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass} + new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, }; return searchTypes; @@ -353,111 +355,86 @@ private void DeleteIndexFolder() { try { - if (Directory.Exists(SearchIndexFolder)) - Directory.Delete(SearchIndexFolder, true); + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } } catch (Exception ex) { Console.WriteLine(ex); } - } - - #endregion - - #region Add Tests - - [Test] - public void SearchController_Add_Throws_On_Null_SearchDocument() - { - //Arrange - - //Act, Assert - Assert.Throws(() => _internalSearchController.AddSearchDocument(null)); - } - - [Test] - public void SearchController_Add_Throws_On_Null_Or_Empty_UniqueuKey() - { - //Arrange - - //Act, Assert - Assert.Throws(() => _internalSearchController.AddSearchDocument(new SearchDocument())); - } + } [Test] public void SearchController_Add_Throws_On_Null_OrEmpty_Title() { - //Arrange + // Arrange - //Act, Assert + // Act, Assert Assert.Throws( - () => _internalSearchController.AddSearchDocument(new SearchDocument {UniqueKey = Guid.NewGuid().ToString()})); + () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString() })); } - - + [Test] public void SearchController_AddSearchDcoumets_Does_Not_Throw_On_Null_OrEmpty_Title() { - //Arrange - var documents = new List {new SearchDocument {UniqueKey = Guid.NewGuid().ToString()}}; + // Arrange + var documents = new List { new SearchDocument { UniqueKey = Guid.NewGuid().ToString() } }; - //Act, Assert - _internalSearchController.AddSearchDocuments(documents); + // Act, Assert + this._internalSearchController.AddSearchDocuments(documents); } [Test] public void SearchController_AddSearchDcoumets_Does_Not_Throw_On_Empty_Search_Document() { - //Arrange - var documents = new List {new SearchDocument()}; + // Arrange + var documents = new List { new SearchDocument() }; - //Act, Assert - _internalSearchController.AddSearchDocuments(documents); + // Act, Assert + this._internalSearchController.AddSearchDocuments(documents); } [Test] public void SearchController_Add_Throws_On_Zero_SearchTypeId() { - //Arrange + // Arrange - //Act, Assert + // Act, Assert Assert.Throws( - () => _internalSearchController.AddSearchDocument(new SearchDocument {UniqueKey = Guid.NewGuid().ToString()})); + () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString() })); } [Test] public void SearchController_Add_Throws_On_Negative_SearchTypeId() { - //Arrange + // Arrange - //Act, Assert + // Act, Assert Assert.Throws( () => - _internalSearchController.AddSearchDocument(new SearchDocument {UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = -1})); + this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = -1 })); } [Test] public void SearchController_Add_Throws_On_DateTimeMin_ModifiedTimeUtc() { - //Arrange + // Arrange - //Act, Assert + // Act, Assert Assert.Throws( - () => _internalSearchController.AddSearchDocument(new SearchDocument {UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = 1})); - } - - #endregion - - #region Delete Tests - + () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = 1 })); + } + [Test] public void SearchController_Add_Then_Delete_ModuleDefinition_WorksAsExpected() { - //Arrange + // Arrange const int totalDocs = 10; var now = DateTime.UtcNow; - //Act + // Act for (var i = 1; i <= totalDocs; i++) { var doc = new SearchDocument @@ -470,28 +447,28 @@ public void SearchController_Add_Then_Delete_ModuleDefinition_WorksAsExpected() ModifiedTimeUtc = now, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); } - //Assert - var stats = GetSearchStatistics(); + // Assert + var stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - //Act - delete last item - var searchDoc = new SearchDocument {ModuleDefId = totalDocs}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete last item + var searchDoc = new SearchDocument { ModuleDefId = totalDocs }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); Assert.AreEqual(1, stats.TotalDeletedDocuments); - //Act - delete first item - searchDoc = new SearchDocument {ModuleDefId = 1}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete first item + searchDoc = new SearchDocument { ModuleDefId = 1 }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); Assert.AreEqual(2, stats.TotalDeletedDocuments); } @@ -499,11 +476,11 @@ public void SearchController_Add_Then_Delete_ModuleDefinition_WorksAsExpected() [Test] public void SearchController_Add_Then_Delete_Module_WorksAsExpected() { - //Arrange + // Arrange const int totalDocs = 10; var now = DateTime.UtcNow; - //Act + // Act for (var i = 1; i <= totalDocs; i++) { var doc = new SearchDocument @@ -516,28 +493,28 @@ public void SearchController_Add_Then_Delete_Module_WorksAsExpected() ModifiedTimeUtc = now, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); } - //Assert - var stats = GetSearchStatistics(); + // Assert + var stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - //Act - delete last item - var searchDoc = new SearchDocument {ModuleId = totalDocs}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete last item + var searchDoc = new SearchDocument { ModuleId = totalDocs }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); Assert.AreEqual(1, stats.TotalDeletedDocuments); - //Act - delete first item - searchDoc = new SearchDocument {ModuleId = 1}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete first item + searchDoc = new SearchDocument { ModuleId = 1 }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); Assert.AreEqual(2, stats.TotalDeletedDocuments); } @@ -545,16 +522,16 @@ public void SearchController_Add_Then_Delete_Module_WorksAsExpected() [Test] public void SearchController_Add_Then_Delete_Portals_WorksAsExpected() { - //Arrange + // Arrange const int totalDocs = 10; // must be even var now = DateTime.UtcNow; - //Act + // Act for (var i = 1; i <= totalDocs; i++) { var doc = new SearchDocument { - PortalId = i <= (totalDocs/2) ? PortalId0 : PortalId1, + PortalId = i <= (totalDocs / 2) ? PortalId0 : PortalId1, UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = now, @@ -562,31 +539,31 @@ public void SearchController_Add_Then_Delete_Portals_WorksAsExpected() ModuleDefId = 10, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); } - //Assert - var stats = GetSearchStatistics(); + // Assert + var stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - //Act - delete all portal 1 items - var searchDoc = new SearchDocument {PortalId = PortalId1}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete all portal 1 items + var searchDoc = new SearchDocument { PortalId = PortalId1 }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - delete all portal 1 - stats = GetSearchStatistics(); - Assert.AreEqual(totalDocs/2, stats.TotalActiveDocuments); - Assert.AreEqual(totalDocs/2, stats.TotalDeletedDocuments); + // Assert - delete all portal 1 + stats = this.GetSearchStatistics(); + Assert.AreEqual(totalDocs / 2, stats.TotalActiveDocuments); + Assert.AreEqual(totalDocs / 2, stats.TotalDeletedDocuments); } [Test] public void SearchController_Add_Then_Delete_Roles_WorksAsExpected() { - //Arrange + // Arrange const int totalDocs = 10; var now = DateTime.UtcNow; - //Act + // Act for (var i = 1; i <= totalDocs; i++) { var doc = new SearchDocument @@ -600,28 +577,28 @@ public void SearchController_Add_Then_Delete_Roles_WorksAsExpected() ModuleDefId = 10, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); } - //Assert - var stats = GetSearchStatistics(); + // Assert + var stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - //Act - delete last item - var searchDoc = new SearchDocument {RoleId = totalDocs}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete last item + var searchDoc = new SearchDocument { RoleId = totalDocs }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); Assert.AreEqual(1, stats.TotalDeletedDocuments); - //Act - delete first item - searchDoc = new SearchDocument {RoleId = 1}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete first item + searchDoc = new SearchDocument { RoleId = 1 }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); Assert.AreEqual(2, stats.TotalDeletedDocuments); } @@ -629,11 +606,11 @@ public void SearchController_Add_Then_Delete_Roles_WorksAsExpected() [Test] public void SearchController_Add_Then_Delete_Tabs_WorksAsExpected() { - //Arrange + // Arrange const int totalDocs = 10; var now = DateTime.UtcNow; - //Act + // Act for (var i = 1; i <= totalDocs; i++) { var doc = new SearchDocument @@ -645,28 +622,28 @@ public void SearchController_Add_Then_Delete_Tabs_WorksAsExpected() ModifiedTimeUtc = now, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); } - //Assert - var stats = GetSearchStatistics(); + // Assert + var stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - //Act - delete last item - var searchDoc = new SearchDocument {TabId = totalDocs}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete last item + var searchDoc = new SearchDocument { TabId = totalDocs }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); Assert.AreEqual(1, stats.TotalDeletedDocuments); - //Act - delete first item - searchDoc = new SearchDocument {TabId = 1}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete first item + searchDoc = new SearchDocument { TabId = 1 }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); Assert.AreEqual(2, stats.TotalDeletedDocuments); } @@ -674,11 +651,11 @@ public void SearchController_Add_Then_Delete_Tabs_WorksAsExpected() [Test] public void SearchController_Add_Then_Delete_Users_WorksAsExpected() { - //Arrange + // Arrange const int totalDocs = 10; var now = DateTime.UtcNow; - //Act + // Act for (var i = 1; i <= totalDocs; i++) { var doc = new SearchDocument @@ -692,39 +669,39 @@ public void SearchController_Add_Then_Delete_Users_WorksAsExpected() ModuleDefId = 10, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); } - //Assert - var stats = GetSearchStatistics(); + // Assert + var stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs, stats.TotalActiveDocuments); - //Act - delete last item - var searchDoc = new SearchDocument {AuthorUserId = totalDocs}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete last item + var searchDoc = new SearchDocument { AuthorUserId = totalDocs }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 1, stats.TotalActiveDocuments); Assert.AreEqual(1, stats.TotalDeletedDocuments); - //Act - delete first item - searchDoc = new SearchDocument {AuthorUserId = 1}; - _internalSearchController.DeleteSearchDocument(searchDoc); + // Act - delete first item + searchDoc = new SearchDocument { AuthorUserId = 1 }; + this._internalSearchController.DeleteSearchDocument(searchDoc); - //Assert - stats = GetSearchStatistics(); + // Assert + stats = this.GetSearchStatistics(); Assert.AreEqual(totalDocs - 2, stats.TotalActiveDocuments); Assert.AreEqual(2, stats.TotalDeletedDocuments); } private SearchStatistics GetSearchStatistics() { - _internalSearchController.Commit(); - Thread.Sleep((int)(_readerStaleTimeSpan * 1000)); // time to flush data to Lucene - return _internalSearchController.GetSearchStatistics(); - } - + this._internalSearchController.Commit(); + Thread.Sleep((int)(this._readerStaleTimeSpan * 1000)); // time to flush data to Lucene + return this._internalSearchController.GetSearchStatistics(); + } + #if false // the rules have changed and these are invalid tests now [Test] public void SearchController_Delete_Throws_On_Null_Or_Empty_UniqueuKey() @@ -756,8 +733,6 @@ public void SearchController_Delete_Throws_On_Negative_SearchTypeId() Assert.Throws(() => _internalSearchController.DeleteSearchDocument(searchDoc)); } #endif - - #endregion - + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs index e2ee8c065e9..0e8ea3fd40f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs @@ -1,124 +1,135 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Tests.Utilities.Mocks; -using Lucene.Net.Documents; -using Lucene.Net.Index; -using Lucene.Net.QueryParsers; -using Lucene.Net.Search; - -using Moq; - -using NUnit.Framework; -using DotNetNuke.Entities.Controllers; - -using Directory = System.IO.Directory; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core.Controllers.Search { - /// - /// Testing various aspects of LuceneController - /// - [TestFixture] - public class LuceneControllerTests - { - #region Private Properties & Constants - - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - private const string SearchIndexFolder = @"App_Data\LuceneTests"; - private const string WriteLockFile = "write.lock"; - private const string Line1 = "the quick brown fox jumps over the lazy dog"; - private const string Line2 = "the quick gold fox jumped over the lazy black dog"; - private const string Line3 = "the quick fox jumps over the black dog"; - private const string Line4 = "the red fox jumped over the lazy dark gray dog"; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Tests.Utilities.Mocks; + using Lucene.Net.Documents; + using Lucene.Net.Index; + using Lucene.Net.QueryParsers; + using Lucene.Net.Search; + using Moq; + using NUnit.Framework; + + using Directory = System.IO.Directory; + + /// + /// Testing various aspects of LuceneController. + /// + [TestFixture] + public class LuceneControllerTests + { + private const string SearchIndexFolder = @"App_Data\LuceneTests"; + private const string WriteLockFile = "write.lock"; + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; + private const string Line1 = "the quick brown fox jumps over the lazy dog"; + private const string Line2 = "the quick gold fox jumped over the lazy black dog"; + private const string Line3 = "the quick fox jumps over the black dog"; + private const string Line4 = "the red fox jumped over the lazy dark gray dog"; private const string Line_Chinese = "这里是中文的内容"; private const string SearchKeyword_Line1 = "fox"; private const string SearchKeyword_Chinese = "中文"; - private const string EmptyCustomAnalyzer = ""; - private const string InvalidCustomAnalyzer = "Lucene.Net.Analysis.Cn.ChineseInvalidAnalyzer"; + private const string EmptyCustomAnalyzer = ""; + private const string InvalidCustomAnalyzer = "Lucene.Net.Analysis.Cn.ChineseInvalidAnalyzer"; private const string ValidCustomAnalyzer = "Lucene.Net.Analysis.Cn.ChineseAnalyzer, Lucene.Net.Contrib.Analyzers"; - private const int DefaultSearchRetryTimes = 5; + private const int DefaultSearchRetryTimes = 5; + + // Arrange + private const int TotalTestDocs2Create = 5; + private const string ContentFieldName = "content"; private Mock _mockHostController; private LuceneControllerImpl _luceneController; private Mock _cachingProvider; private Mock _mockSearchHelper; - private Mock _mockSearchQuery; + private Mock _mockSearchQuery; - #endregion + [SetUp] + public void SetUp() + { + ComponentFactory.Container = new SimpleContainer(); + this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); - #region Set Up + this._mockHostController = new Mock(); + this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); + HostController.RegisterInstance(this._mockHostController.Object); - [SetUp] - public void SetUp() - { - ComponentFactory.Container = new SimpleContainer(); - _cachingProvider = MockComponentProvider.CreateDataCacheProvider(); - - _mockHostController = new Mock(); - _mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - _mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(_readerStaleTimeSpan); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); - HostController.RegisterInstance(_mockHostController.Object); - - _mockSearchHelper = new Mock(); - _mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(GetSynonymsCallBack); - _mockSearchHelper.Setup(c => c.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); - _mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - _mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(_mockSearchHelper.Object); - - _mockSearchQuery = new Mock(); - - DeleteIndexFolder(); - CreateNewLuceneControllerInstance(); - } - - [TearDown] + this._mockSearchHelper = new Mock(); + this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); + this._mockSearchHelper.Setup(c => c.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); + this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); + + this._mockSearchQuery = new Mock(); + + this.DeleteIndexFolder(); + this.CreateNewLuceneControllerInstance(); + } + + [TearDown] public void TearDown() { - _luceneController.Dispose(); - DeleteIndexFolder(); + this._luceneController.Dispose(); + this.DeleteIndexFolder(); SearchHelper.ClearInstance(); } + [Test] + public void LuceneController_SearchFolderIsAsExpected() + { + var inf1 = new DirectoryInfo(SearchIndexFolder); + var inf2 = new DirectoryInfo(this._luceneController.IndexFolder); + Assert.AreEqual(inf1.FullName, inf2.FullName); + } - #endregion + [Test] + public void LuceneController_Add_Throws_On_Null_Document() + { + // Arrange - #region Private Methods + // Act, Assert + Assert.Throws(() => this._luceneController.Add(null)); + } private void CreateNewLuceneControllerInstance() { - if (_luceneController != null) + if (this._luceneController != null) { LuceneController.ClearInstance(); - _luceneController.Dispose(); + this._luceneController.Dispose(); } - _luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(_luceneController); + + this._luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this._luceneController); } private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) { var synonyms = new List(); if (term == "fox") + { synonyms.Add("wolf"); + } return synonyms; } @@ -128,79 +139,61 @@ private void DeleteIndexFolder() try { if (Directory.Exists(SearchIndexFolder)) + { Directory.Delete(SearchIndexFolder, true); + } } - catch(Exception ex) + catch (Exception ex) { Console.WriteLine(ex); } } /// - /// Adds standarad SearchDocs in Lucene Index + /// Adds standarad SearchDocs in Lucene Index. /// private void AddStandardDocs() { - string[] lines = { - Line1, Line2, Line3, Line4 + string[] lines = + { + Line1, Line2, Line3, Line4, }; - AddLinesAsSearchDocs(lines); + this.AddLinesAsSearchDocs(lines); } private void AddLinesAsSearchDocs(IEnumerable lines) - { - foreach (var line in lines) - { - var field = new Field(Constants.ContentTag, line, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - var doc = new Document(); - doc.Add(field); - _luceneController.Add(doc); - } - - _luceneController.Commit(); - } - - #endregion - - #region Add Tests - - [Test] - public void LuceneController_SearchFolderIsAsExpected() { - var inf1 = new DirectoryInfo(SearchIndexFolder); - var inf2 = new DirectoryInfo(_luceneController.IndexFolder); - Assert.AreEqual(inf1.FullName, inf2.FullName); - } - - [Test] - public void LuceneController_Add_Throws_On_Null_Document() - { - //Arrange + foreach (var line in lines) + { + var field = new Field(Constants.ContentTag, line, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); + var doc = new Document(); + doc.Add(field); + this._luceneController.Add(doc); + } - //Act, Assert - Assert.Throws(() => _luceneController.Add(null)); + this._luceneController.Commit(); } public void LuceneController_Add_Throws_On_Null_Query() { - //Arrange + // Arrange - //Act, Assert - Assert.Throws(() => _luceneController.Delete(null)); + // Act, Assert + Assert.Throws(() => this._luceneController.Delete(null)); } [Test] public void LuceneController_Add_Empty_FiledsCollection_DoesNot_Create_Index() { - //Arrange - - //Act - _luceneController.Add(new Document()); - _luceneController.Commit(); + // Arrange + + // Act + this._luceneController.Add(new Document()); + this._luceneController.Commit(); var numFiles = 0; - DeleteIndexFolder(); + this.DeleteIndexFolder(); Assert.AreEqual(0, numFiles); } @@ -208,21 +201,21 @@ public void LuceneController_Add_Empty_FiledsCollection_DoesNot_Create_Index() [Test] public void LuceneController_GetsHighlightedDesc() { - //Arrange + // Arrange const string fieldName = "content"; const string fieldValue = Line1; - //Act + // Act var field = new Field(fieldName, fieldValue, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); var doc = new Document(); doc.Add(field); - _luceneController.Add(doc); - _luceneController.Commit(); + this._luceneController.Add(doc); + this._luceneController.Commit(); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery {Query = new TermQuery(new Term(fieldName, "fox"))})); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); - //Assert + // Assert Assert.AreEqual(1, hits.Results.Count()); Assert.AreEqual("brown fox jumps over the lazy dog", hits.Results.ElementAt(0).ContentSnippet); } @@ -230,23 +223,24 @@ public void LuceneController_GetsHighlightedDesc() [Test] public void LuceneController_HighlightedDescHtmlEncodesOutput() { - //Arrange + // Arrange const string fieldName = "content"; const string fieldValue = ""; const string expectedResult = " src='fox' type='text/javascript'></script>"; + // Note that we mustn't get " src='fox' type='text/javascript'>" as this causes browser rendering issues - //Act + // Act var field = new Field(fieldName, fieldValue, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); var doc = new Document(); doc.Add(field); - _luceneController.Add(doc); - _luceneController.Commit(); + this._luceneController.Add(doc); + this._luceneController.Commit(); - var hits = _luceneController.Search( CreateSearchContext(new LuceneQuery {Query = new TermQuery(new Term(fieldName, "fox"))})); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); - //Assert + // Assert Assert.AreEqual(1, hits.Results.Count()); Assert.AreEqual(expectedResult, hits.Results.ElementAt(0).ContentSnippet); } @@ -254,37 +248,33 @@ public void LuceneController_HighlightedDescHtmlEncodesOutput() [Test] public void LuceneController_FindsResultsUsingNearRealtimeSearchWithoutCommit() { - //Arrange + // Arrange const string fieldName = "content"; const string fieldValue = Line1; - //Act + // Act var field = new Field(fieldName, fieldValue, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); var doc = new Document(); doc.Add(field); - _luceneController.Add(doc); - // DONOT commit here to enable testing near-realtime of search writer - //_luceneController.Commit(); + this._luceneController.Add(doc); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); + // DONOT commit here to enable testing near-realtime of search writer + // _luceneController.Commit(); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(fieldName, "fox")) })); - //Assert + // Assert Assert.AreEqual(1, hits.Results.Count()); } - #endregion - - #region pagination tests - [Test] public void LuceneController_Search_Returns_Correct_Total_Hits() { - //Arrange - AddStandardDocs(); + // Arrange + this.AddStandardDocs(); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery {Query = new TermQuery(new Term(Constants.ContentTag, "fox"))})); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")) })); - //Assert + // Assert Assert.AreEqual(4, hits.TotalHits); Assert.AreEqual(4, hits.Results.Count()); } @@ -292,12 +282,12 @@ public void LuceneController_Search_Returns_Correct_Total_Hits() [Test] public void LuceneController_Search_Request_For_1_Result_Returns_1_Record_But_More_TotalHits() { - //Arrange - AddStandardDocs(); + // Arrange + this.AddStandardDocs(); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 1 })); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 1 })); - //Assert + // Assert Assert.AreEqual(4, hits.TotalHits); Assert.AreEqual(1, hits.Results.Count()); } @@ -305,12 +295,12 @@ public void LuceneController_Search_Request_For_1_Result_Returns_1_Record_But_Mo [Test] public void LuceneController_Search_Request_For_4_Records_Returns_4_Records_With_4_TotalHits_Based_On_PageIndex1_PageSize4() { - //Arrange - AddStandardDocs(); + // Arrange + this.AddStandardDocs(); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); - //Assert + // Assert Assert.AreEqual(4, hits.TotalHits); Assert.AreEqual(4, hits.Results.Count()); } @@ -318,12 +308,12 @@ public void LuceneController_Search_Request_For_4_Records_Returns_4_Records_With [Test] public void LuceneController_Search_Request_For_4_Records_Returns_4_Records_With_4_TotalHits_Based_On_PageIndex4_PageSize1() { - //Arrange - AddStandardDocs(); + // Arrange + this.AddStandardDocs(); + + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = new TermQuery(new Term(Constants.ContentTag, "fox")), PageIndex = 1, PageSize = 4 })); - - //Assert + // Assert Assert.AreEqual(4, hits.TotalHits); Assert.AreEqual(4, hits.Results.Count()); } @@ -331,135 +321,135 @@ public void LuceneController_Search_Request_For_4_Records_Returns_4_Records_With [Test] public void LuceneController_Search_Request_For_NonExisting_PageNumbers_Returns_No_Record() { - //Arrange - AddStandardDocs(); + // Arrange + this.AddStandardDocs(); - var hits = _luceneController.Search(CreateSearchContext( - new LuceneQuery{ - Query = new TermQuery(new Term(Constants.ContentTag, "fox")), - PageIndex = 5, - PageSize = 10 - })); + var hits = this._luceneController.Search(this.CreateSearchContext( + new LuceneQuery + { + Query = new TermQuery(new Term(Constants.ContentTag, "fox")), + PageIndex = 5, + PageSize = 10, + })); - //Assert + // Assert Assert.AreEqual(4, hits.TotalHits); Assert.AreEqual(0, hits.Results.Count()); } - [Test] public void LuceneController_Search_Request_For_PagIndex2_PageSize1_Returns_2nd_Record_Only() { - //Arrange - AddStandardDocs(); + // Arrange + this.AddStandardDocs(); var query = new LuceneQuery - { - Query = new TermQuery(new Term(Constants.ContentTag, "quick")), PageIndex = 2, PageSize = 1 - }; + { + Query = new TermQuery(new Term(Constants.ContentTag, "quick")), + PageIndex = 2, + PageSize = 1, + }; - var hits = _luceneController.Search(CreateSearchContext(query)); + var hits = this._luceneController.Search(this.CreateSearchContext(query)); - //Assert + // Assert Assert.AreEqual(3, hits.TotalHits); Assert.AreEqual(1, hits.Results.Count()); + // for some reason, this search's docs have scoring as // Line1=0.3125, Line1=0.3125, Line2=0.3125, Line2=0.3750 Assert.AreEqual(Line1, hits.Results.ElementAt(0).Document.GetField(Constants.ContentTag).StringValue); } - #endregion - - #region search tests [Test] public void LuceneController_NumericRangeCheck() { - //Arrange + // Arrange const string fieldName = "content"; - //Act + // Act - //Add first numeric field + // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - _luceneController.Add(doc1); + this._luceneController.Add(doc1); - //Add second numeric field + // Add second numeric field var doc2 = new Document(); doc2.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(2)); - _luceneController.Add(doc2); + this._luceneController.Add(doc2); - //Add third numeric field + // Add third numeric field var doc3 = new Document(); doc3.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(3)); - _luceneController.Add(doc3); + this._luceneController.Add(doc3); - //Add fourth numeric field + // Add fourth numeric field var doc4 = new Document(); doc4.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(4)); - _luceneController.Add(doc4); + this._luceneController.Add(doc4); - _luceneController.Commit(); + this._luceneController.Commit(); var query = NumericRangeQuery.NewIntRange(fieldName, 2, 3, true, true); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = query })); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(2, hits.Results.Count()); } [Test] public void LuceneController_DateRangeCheck() { - //Arrange + // Arrange const string fieldName = "content"; var dates = new List { DateTime.Now.AddYears(-3), DateTime.Now.AddYears(-2), DateTime.Now.AddYears(-1), DateTime.Now }; - //Act + // Act foreach (var date in dates) { var doc = new Document(); doc.Add(new NumericField(fieldName, Field.Store.YES, true).SetLongValue(long.Parse(date.ToString(Constants.DateTimeFormat)))); - _luceneController.Add(doc); + this._luceneController.Add(doc); } - _luceneController.Commit(); + this._luceneController.Commit(); var futureTime = DateTime.Now.AddMinutes(1).ToString(Constants.DateTimeFormat); var query = NumericRangeQuery.NewLongRange(fieldName, long.Parse(futureTime), long.Parse(futureTime), true, true); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = query })); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(0, hits.Results.Count()); query = NumericRangeQuery.NewLongRange(fieldName, long.Parse(DateTime.Now.AddDays(-1).ToString(Constants.DateTimeFormat)), long.Parse(DateTime.Now.ToString(Constants.DateTimeFormat)), true, true); - hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = query })); + hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(1, hits.Results.Count()); query = NumericRangeQuery.NewLongRange(fieldName, long.Parse(DateTime.Now.AddDays(-368).ToString(Constants.DateTimeFormat)), long.Parse(DateTime.Now.ToString(Constants.DateTimeFormat)), true, true); - hits = _luceneController.Search(CreateSearchContext(new LuceneQuery {Query = query})); + hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = query })); Assert.AreEqual(2, hits.Results.Count()); } [Test] public void LuceneController_Search_Throws_On_Null_LuceneQuery() { - Assert.Throws(() => _luceneController.Search(CreateSearchContext(null))); + Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(null))); } [Test] public void LuceneController_Search_Throws_On_Null_Query() { - Assert.Throws(() => _luceneController.Search(CreateSearchContext(new LuceneQuery()))); + Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(new LuceneQuery()))); } [Test] public void LuceneController_Search_Throws_On_Zero_PageSize() { - Assert.Throws(() => _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageSize = 0 }))); + Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageSize = 0 }))); } [Test] public void LuceneController_Search_Throws_On_Zero_PageIndex() { - Assert.Throws(() => _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageIndex = 0 }))); + Assert.Throws(() => this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = new BooleanQuery(), PageIndex = 0 }))); } [Test] @@ -468,28 +458,29 @@ public void LuceneController_Search_Throws_On_Zero_PageIndex() [TestCase(ValidCustomAnalyzer)] public void LuceneController_Search_With_Chinese_Chars_And_Custom_Analyzer(string customAlalyzer = "") { - _mockHostController.Setup(c => c.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); - //Arrange + this._mockHostController.Setup(c => c.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); + + // Arrange const string fieldName = "content"; const string fieldValue = Line_Chinese; - //Act + // Act var field = new Field(fieldName, fieldValue, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); var doc = new Document(); doc.Add(field); - _luceneController.Add(doc); - _luceneController.Commit(); + this._luceneController.Add(doc); + this._luceneController.Commit(); - var analyzer = _luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); + var analyzer = this._luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); var keywordQuery = new BooleanQuery(); var parserContent = new QueryParser(Constants.LuceneVersion, fieldName, analyzer); var parsedQueryContent = parserContent.Parse(SearchKeyword_Chinese); keywordQuery.Add(parsedQueryContent, Occur.SHOULD); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = keywordQuery })); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = keywordQuery })); - //Assert + // Assert if (customAlalyzer == ValidCustomAnalyzer) { Assert.AreEqual(1, hits.Results.Count()); @@ -507,75 +498,75 @@ public void LuceneController_Search_With_Chinese_Chars_And_Custom_Analyzer(strin [TestCase(ValidCustomAnalyzer)] public void LuceneController_Search_With_English_Chars_And_Custom_Analyzer(string customAlalyzer = "") { - _mockHostController.Setup(c => c.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); - //Arrange + this._mockHostController.Setup(c => c.GetString(Constants.SearchCustomAnalyzer, It.IsAny())).Returns(customAlalyzer); + + // Arrange const string fieldName = "content"; const string fieldValue = Line1; - //Act + // Act var field = new Field(fieldName, fieldValue, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); var doc = new Document(); doc.Add(field); - _luceneController.Add(doc); - _luceneController.Commit(); + this._luceneController.Add(doc); + this._luceneController.Commit(); - var analyzer = _luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); + var analyzer = this._luceneController.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); var keywordQuery = new BooleanQuery(); var parserContent = new QueryParser(Constants.LuceneVersion, fieldName, analyzer); var parsedQueryContent = parserContent.Parse(SearchKeyword_Line1); keywordQuery.Add(parsedQueryContent, Occur.SHOULD); - var hits = _luceneController.Search(CreateSearchContext(new LuceneQuery { Query = keywordQuery })); + var hits = this._luceneController.Search(this.CreateSearchContext(new LuceneQuery { Query = keywordQuery })); - //Assert + // Assert Assert.AreEqual(1, hits.Results.Count()); Assert.AreEqual("brown fox jumps over the lazy dog", hits.Results.ElementAt(0).ContentSnippet); - } - #endregion - - #region fuzzy search [Test] public void LuceneController_Search_Single_FuzzyQuery() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { "fuzzy", - "wuzzy" + "wuzzy", }; const string keyword = "wuzza"; - AddLinesAsSearchDocs(docs); + this.AddLinesAsSearchDocs(docs); - //Act + // Act var luceneQuery = new LuceneQuery { Query = new FuzzyQuery(new Term(Constants.ContentTag, keyword)) }; - var previews = _luceneController.Search(CreateSearchContext(luceneQuery)); + var previews = this._luceneController.Search(this.CreateSearchContext(luceneQuery)); - //Assert + // Assert Assert.AreEqual(2, previews.Results.Count()); } [Test] public void LuceneController_Search_Double_FuzzyQuery() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { "home", "homez", // note home and homes could be returned by PorterFilter "fuzzy", - "wuzzy" + "wuzzy", }; - string[] keywords = { + string[] keywords = + { "wuzza", - "homy" + "homy", }; - AddLinesAsSearchDocs(docs); + this.AddLinesAsSearchDocs(docs); - //Act + // Act var finalQuery = new BooleanQuery(); foreach (var keyword in keywords) { @@ -583,239 +574,223 @@ public void LuceneController_Search_Double_FuzzyQuery() } var luceneQuery = new LuceneQuery { Query = finalQuery }; - var previews = _luceneController.Search(CreateSearchContext(luceneQuery)); + var previews = this._luceneController.Search(this.CreateSearchContext(luceneQuery)); - //Assert + // Assert Assert.AreEqual(3, previews.Results.Count()); } - #endregion - #region search reader tests [Test] public void LuceneController_Throws_SearchIndexEmptyException_WhenNoDataInSearch() { - Assert.Throws(() => { var r = _luceneController.GetSearcher(); }); + Assert.Throws(() => { var r = this._luceneController.GetSearcher(); }); } [Test] - public void LuceneController_ReaderNotChangedBeforeTimeSpanElapsed() - { - //Arrange + public void LuceneController_ReaderNotChangedBeforeTimeSpanElapsed() + { + // Arrange const string fieldName = "content"; - //Act + // Act - //Add first numeric field + // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - _luceneController.Add(doc1); - _luceneController.Commit(); + this._luceneController.Add(doc1); + this._luceneController.Commit(); - var reader = _luceneController.GetSearcher(); - Thread.Sleep(TimeSpan.FromSeconds(_readerStaleTimeSpan / 2)); + var reader = this._luceneController.GetSearcher(); + Thread.Sleep(TimeSpan.FromSeconds(this._readerStaleTimeSpan / 2)); - Assert.AreSame(reader, _luceneController.GetSearcher()); + Assert.AreSame(reader, this._luceneController.GetSearcher()); } [Test] public void LuceneController_ReaderNotChangedIfNoIndexUpdated() { - //Arrange + // Arrange const string fieldName = "content"; - //Act + // Act - //Add first numeric field + // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - _luceneController.Add(doc1); - _luceneController.Commit(); + this._luceneController.Add(doc1); + this._luceneController.Commit(); - var reader = _luceneController.GetSearcher(); - Thread.Sleep(TimeSpan.FromSeconds(_readerStaleTimeSpan * 1.1)); + var reader = this._luceneController.GetSearcher(); + Thread.Sleep(TimeSpan.FromSeconds(this._readerStaleTimeSpan * 1.1)); - Assert.AreSame(reader, _luceneController.GetSearcher()); + Assert.AreSame(reader, this._luceneController.GetSearcher()); } [Test] public void LuceneController_ReaderIsChangedWhenIndexIsUpdatedAndTimeIsElapsed() { - //Arrange + // Arrange const string fieldName = "content"; - //Act + // Act - //Add first numeric field + // Add first numeric field var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - _luceneController.Add(doc1); - _luceneController.Commit(); + this._luceneController.Add(doc1); + this._luceneController.Commit(); - var reader = _luceneController.GetSearcher(); - Thread.Sleep(TimeSpan.FromSeconds(_readerStaleTimeSpan * 1.1)); + var reader = this._luceneController.GetSearcher(); + Thread.Sleep(TimeSpan.FromSeconds(this._readerStaleTimeSpan * 1.1)); - //Add second numeric field + // Add second numeric field var doc2 = new Document(); doc2.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(2)); - _luceneController.Add(doc2); - - //var lastAcccess = Directory.GetLastWriteTime(_luceneController.IndexFolder); - //Directory.SetLastWriteTime(_luceneController.IndexFolder, lastAcccess + TimeSpan.FromSeconds(1)); + this._luceneController.Add(doc2); - Assert.AreNotSame(reader, _luceneController.GetSearcher()); + // var lastAcccess = Directory.GetLastWriteTime(_luceneController.IndexFolder); + // Directory.SetLastWriteTime(_luceneController.IndexFolder, lastAcccess + TimeSpan.FromSeconds(1)); + Assert.AreNotSame(reader, this._luceneController.GetSearcher()); } - #endregion - #region Locking Tests + [Test] + public void LuceneController_LockFileWhenExistsDoesNotCauseProblemForFirstIController() + { + // Arrange + const string fieldName = "content"; + var lockFile = Path.Combine(SearchIndexFolder, WriteLockFile); + if (!Directory.Exists(SearchIndexFolder)) + { + Directory.CreateDirectory(SearchIndexFolder); + } - [Test] - public void LuceneController_LockFileWhenExistsDoesNotCauseProblemForFirstIController() - { - //Arrange - const string fieldName = "content"; - var lockFile = Path.Combine(SearchIndexFolder, WriteLockFile); - if (!Directory.Exists(SearchIndexFolder)) Directory.CreateDirectory(SearchIndexFolder); - if (!File.Exists(lockFile)) - { - File.Create(lockFile).Close(); - } + if (!File.Exists(lockFile)) + { + File.Create(lockFile).Close(); + } - //Act - var doc1 = new Document(); - doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); + // Act + var doc1 = new Document(); + doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - //Assert + // Assert Assert.True(File.Exists(lockFile)); - Assert.DoesNotThrow(() => _luceneController.Add(doc1)); - } + Assert.DoesNotThrow(() => this._luceneController.Add(doc1)); + } - [Test] + [Test] public void LuceneController_LockFileCanBeObtainedByOnlySingleController() { - //Arrange + // Arrange const string fieldName = "content"; var lockFile = Path.Combine(SearchIndexFolder, WriteLockFile); - //Act + // Act var doc1 = new Document(); doc1.Add(new NumericField(fieldName, Field.Store.YES, true).SetIntValue(1)); - _luceneController.Add(doc1); + this._luceneController.Add(doc1); // create another controller then try to access the already locked index by the first one var secondController = new LuceneControllerImpl(); - //Assert + // Assert Assert.True(File.Exists(lockFile)); Assert.Throws(() => secondController.Add(doc1)); } - #endregion + [Test] + public void LuceneController_DocumentMaxAndCountAreCorrect() + { + this.AddTestDocs(); + + Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create, this._luceneController.SearchbleDocsCount()); + } - #region Added/Deleted documents count and ptimization tests + [Test] + public void LuceneController_TestDeleteBeforeOptimize() + { + // Arrange + this.AddTestDocs(); + var delCount = this.DeleteTestDocs(); - //Arrange - const int TotalTestDocs2Create = 5; - const string ContentFieldName = "content"; + Assert.IsTrue(this._luceneController.HasDeletions()); + Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create - delCount, this._luceneController.SearchbleDocsCount()); + } private int AddTestDocs() { - //Act + // Act for (var i = 0; i < TotalTestDocs2Create; i++) { var doc = new Document(); + // format to "D#" because LengthFilter will not consider words of length < 3 or > 255 characters in length (defaults) doc.Add(new Field(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen), Field.Store.YES, Field.Index.ANALYZED)); - _luceneController.Add(doc); + this._luceneController.Add(doc); } - _luceneController.Commit(); + this._luceneController.Commit(); return TotalTestDocs2Create; } private int DeleteTestDocs() { - //Act - // delete odd docs => [1, 3] + // Act + // delete odd docs => [1, 3] var delCount = 0; for (var i = 1; i < TotalTestDocs2Create; i += 2) { // format to "D#" because LengthFilter will not consider the defaults for these values - _luceneController.Delete(new TermQuery(new Term(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen)))); + this._luceneController.Delete(new TermQuery(new Term(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen)))); delCount++; } - _luceneController.Commit(); + this._luceneController.Commit(); return delCount; } - - [Test] - public void LuceneController_DocumentMaxAndCountAreCorrect() - { - AddTestDocs(); - - Assert.AreEqual(TotalTestDocs2Create, _luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create, _luceneController.SearchbleDocsCount()); - } - - [Test] - public void LuceneController_TestDeleteBeforeOptimize() - { - //Arrange - AddTestDocs(); - var delCount = DeleteTestDocs(); - - Assert.IsTrue(_luceneController.HasDeletions()); - Assert.AreEqual(TotalTestDocs2Create, _luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create - delCount, _luceneController.SearchbleDocsCount()); - } - [Test] public void LuceneController_TestDeleteAfterOptimize() { - //Arrange - AddTestDocs(); - var delCount = DeleteTestDocs(); + // Arrange + this.AddTestDocs(); + var delCount = this.DeleteTestDocs(); - _luceneController.OptimizeSearchIndex(true); + this._luceneController.OptimizeSearchIndex(true); - Assert.AreEqual(TotalTestDocs2Create, _luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create - delCount, _luceneController.SearchbleDocsCount()); + Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create - delCount, this._luceneController.SearchbleDocsCount()); } [Test] public void LuceneController_TestGetSearchStatistics() { - //Arrange - var addedCount = AddTestDocs(); - var delCount = DeleteTestDocs(); - var statistics = _luceneController.GetSearchStatistics(); + // Arrange + var addedCount = this.AddTestDocs(); + var delCount = this.DeleteTestDocs(); + var statistics = this._luceneController.GetSearchStatistics(); Assert.IsNotNull(statistics); Assert.AreEqual(statistics.TotalDeletedDocuments, delCount); Assert.AreEqual(statistics.TotalActiveDocuments, addedCount - delCount); } - #endregion - - #region Tests for other controllers but need to be run from this location (they enforce tesing private components in others) [Test] public void SearchController_LuceneControllerReaderIsNotNullWhenWriterIsNull() { - //Arrange - AddTestDocs(); - CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion + // Arrange + this.AddTestDocs(); + this.CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion - //Assert - Assert.IsNotNull(_luceneController.GetSearcher()); + // Assert + Assert.IsNotNull(this._luceneController.GetSearcher()); } - #endregion - private LuceneSearchContext CreateSearchContext(LuceneQuery luceneQuery) { - return new LuceneSearchContext {LuceneQuery = luceneQuery, SearchQuery = _mockSearchQuery.Object }; + return new LuceneSearchContext { LuceneQuery = luceneQuery, SearchQuery = this._mockSearchQuery.Object }; } } } - diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs index ef8f71508a9..366b311530f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs @@ -1,43 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; -using System.Threading; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Search.Controllers; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; -using Constants = DotNetNuke.Services.Search.Internals.Constants; -using DotNetNuke.Entities.Controllers; - -using Lucene.Net.Documents; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Search { + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; + using System.Threading; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Tests.Utilities.Mocks; + using Lucene.Net.Documents; + using Moq; + using NUnit.Framework; + + using Constants = DotNetNuke.Services.Search.Internals.Constants; + /// - /// Testing various aspects of SearchController + /// Testing various aspects of SearchController. /// [TestFixture] public class SearchControllerTests - { - - #region Constants - + { + private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; + private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; + private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; + public enum SearchTypeIds { ModuleSearchTypeId = 1, @@ -45,12 +44,8 @@ public enum SearchTypeIds DocumentSearchTypeId, UrlSearchTypeId, OtherSearchTypeId, - UnknownSearchTypeId + UnknownSearchTypeId, } - - private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; - private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; - private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; @@ -125,12 +120,8 @@ public enum SearchTypeIds private const int CustomBoost = 80; private const string SearchIndexFolder = @"App_Data\SearchTests"; + private const int DefaultSearchRetryTimes = 5; private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - private const int DefaultSearchRetryTimes = 5; - #endregion - - #region Private Properties - private Mock _mockHostController; private Mock _mockCachingProvider; private Mock _mockDataProvider; @@ -140,120 +131,192 @@ public enum SearchTypeIds private SearchControllerImpl _searchController; private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - - #endregion - - #region Set Up - + private LuceneControllerImpl _luceneController; + [SetUp] public void SetUp() { ComponentFactory.Container = new SimpleContainer(); MockComponentProvider.ResetContainer(); - _mockDataProvider = MockComponentProvider.CreateDataProvider(); - _mockLocaleController = MockComponentProvider.CreateLocaleController(); - _mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - - _mockUserController = new Mock(); - _mockHostController = new Mock(); - _mockSearchHelper = new Mock(); + this._mockDataProvider = MockComponentProvider.CreateDataProvider(); + this._mockLocaleController = MockComponentProvider.CreateLocaleController(); + this._mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - SetupDataProvider(); - SetupHostController(); - SetupSearchHelper(); - SetupLocaleController(); + this._mockUserController = new Mock(); + this._mockHostController = new Mock(); + this._mockSearchHelper = new Mock(); - _mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns((int portalId, int userId) => GetUserByIdCallback(portalId, userId)); - UserController.SetTestableInstance(_mockUserController.Object); + this.SetupDataProvider(); + this.SetupHostController(); + this.SetupSearchHelper(); + this.SetupLocaleController(); - - CreateNewLuceneControllerInstance(); + this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns((int portalId, int userId) => this.GetUserByIdCallback(portalId, userId)); + UserController.SetTestableInstance(this._mockUserController.Object); + + this.CreateNewLuceneControllerInstance(); } [TearDown] public void TearDown() { - _luceneController.Dispose(); - DeleteIndexFolder(); + this._luceneController.Dispose(); + this.DeleteIndexFolder(); InternalSearchController.ClearInstance(); UserController.ClearInstance(); SearchHelper.ClearInstance(); - LuceneController.ClearInstance(); - _luceneController = null; + LuceneController.ClearInstance(); + this._luceneController = null; + } + + [Test] + public void SearchController_Search_Throws_On_Null_Query() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this._searchController.SiteSearch(null)); + } + + [Test] + public void SearchController_Search_Throws_On_Empty_TypeId_Collection() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this._searchController.SiteSearch(new SearchQuery { KeyWords = "word" })); } - #endregion + /// + /// Executes function proc on a separate thread respecting the given timeout value. + /// + /// + /// The function to execute. + /// The timeout duration. + /// R. + /// From: http://stackoverflow.com/questions/9460661/implementing-regex-timeout-in-net-4. + private static R ExecuteWithTimeout(Func proc, TimeSpan timeout) + { + var r = default(R); // init default return value + Exception ex = null; // records inter-thread exception + + // define a thread to wrap 'proc' + var t = new Thread(() => + { + try + { + r = proc(); + } + catch (Exception e) + { + // this can get set to ThreadAbortException + ex = e; + + Console.WriteLine("Exception hit"); + } + }); - #region Private Methods + t.Start(); // start running 'proc' thread wrapper + + // from docs: "The Start method does not return until the new thread has started running." + if (t.Join(timeout) == false) + { + t.Abort(); // die evil thread! + + // Abort raises the ThreadAbortException + int i = 0; + while ((t.Join(1) == false) && (i < 20)) + { + // 20 ms wait possible here + i++; + } + + if (i >= 20) + { + // we didn't abort, might want to log this or take some other action + // this can happen if you are doing something indefinitely hinky in a + // finally block (cause the finally be will executed before the Abort + // completes. + Console.WriteLine("Abort didn't work as expected"); + } + } + if (ex != null) + { + throw ex; // oops + } + + return r; // ah! + } + private void CreateNewLuceneControllerInstance(bool reCreate = false) { InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); - _internalSearchController = InternalSearchController.Instance; - _searchController = new SearchControllerImpl(); + this._internalSearchController = InternalSearchController.Instance; + this._searchController = new SearchControllerImpl(); if (!reCreate) { - DeleteIndexFolder(); + this.DeleteIndexFolder(); - if (_luceneController != null) + if (this._luceneController != null) { LuceneController.ClearInstance(); - _luceneController.Dispose(); + this._luceneController.Dispose(); } - _luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(_luceneController); + + this._luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this._luceneController); } } private void SetupHostController() { - _mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - _mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(_readerStaleTimeSpan); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchDescriptionBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); - HostController.RegisterInstance(_mockHostController.Object); + this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchDescriptionBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); + HostController.RegisterInstance(this._mockHostController.Object); } private void SetupLocaleController() { - _mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); - _mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - _mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - _mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - _mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - _mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - _mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); } private void SetupDataProvider() { - //Standard DataProvider Path for Logging - _mockDataProvider.Setup(d => d.GetProviderPath()).Returns(""); + // Standard DataProvider Path for Logging + this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); DataTableReader searchTypes = null; - _mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) - .Callback(() => searchTypes = GetAllSearchTypes().CreateDataReader()) + this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) + .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) .Returns(() => searchTypes); - _mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); + this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); } private IDataReader GetPortalsCallBack(string culture) { - return GetPortalCallBack(PortalId0, CultureEnUs); + return this.GetPortalCallBack(PortalId0, CultureEnUs); } private IDataReader GetPortalCallBack(int portalId, string culture) @@ -261,12 +324,12 @@ private IDataReader GetPortalCallBack(int portalId, string culture) var table = new DataTable("Portal"); var cols = new[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode" - }; + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; foreach (var col in cols) { @@ -284,27 +347,27 @@ private IDataReader GetPortalCallBack(int portalId, string culture) private void SetupSearchHelper() { - _mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - _mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(GetSynonymsCallBack); - _mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); - _mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(GetSearchTypeByNameCallback); - _mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(GetSearchTypes()); - _mockSearchHelper.Setup(x => x.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); - _mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( + this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); + this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( new SearchStopWords { PortalId = 0, CultureCode = CultureEsEs, StopWords = "los,de,el", }); - _mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnUs)).Returns( + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnUs)).Returns( new SearchStopWords { PortalId = 0, CultureCode = CultureEnUs, StopWords = "the,over", }); - _mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnCa)).Returns( + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnCa)).Returns( new SearchStopWords { PortalId = 0, @@ -312,9 +375,9 @@ private void SetupSearchHelper() StopWords = "the,over", }); - _mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new SearchHelperImpl().RephraseSearchText); - _mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(_mockSearchHelper.Object); + this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new SearchHelperImpl().RephraseSearchText); + this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); } private SearchType GetSearchTypeByNameCallback(string searchTypeName) @@ -345,17 +408,21 @@ private SearchType GetSearchTypeByNameCallback(string searchTypeName) private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) { var synonyms = new List(); - if (term == "fox") - synonyms.Add("wolf"); - + if (term == "fox") + { + synonyms.Add("wolf"); + } + return synonyms; } private UserInfo GetUserByIdCallback(int portalId, int userId) { - if (portalId == PortalId12 && userId == StandardAuthorId) - return new UserInfo { UserID = userId, DisplayName = StandardAuthorDisplayName }; - + if (portalId == PortalId12 && userId == StandardAuthorId) + { + return new UserInfo { UserID = userId, DisplayName = StandardAuthorDisplayName }; + } + return null; } @@ -367,7 +434,7 @@ private DataTable GetAllSearchTypes() dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); dtSearchTypes.PrimaryKey = new[] { pkId }; - //Create default Crawler + // Create default Crawler dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); @@ -381,11 +448,11 @@ private IEnumerable GetSearchTypes() { var searchTypes = new List { - new SearchType {SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass}, - new SearchType {SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass}, - new SearchType {SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass}, - new SearchType {SearchTypeId = DocumentSearchTypeId, SearchTypeName = DocumentSearchTypeName, SearchResultClass = NoPermissionFakeResultControllerClass}, - new SearchType {SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass} + new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = DocumentSearchTypeId, SearchTypeName = DocumentSearchTypeName, SearchResultClass = NoPermissionFakeResultControllerClass }, + new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, }; return searchTypes; @@ -395,8 +462,10 @@ private void DeleteIndexFolder() { try { - if (Directory.Exists(SearchIndexFolder)) - Directory.Delete(SearchIndexFolder, true); + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } } catch (Exception ex) { @@ -405,11 +474,12 @@ private void DeleteIndexFolder() } /// - /// Returns few SearchDocs + /// Returns few SearchDocs. /// private IEnumerable GetStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) { - var searchDocs = new List { + var searchDocs = new List + { new SearchDocument { PortalId = PortalId0, Tags = new List { Tag0, Tag1, TagOldest, Tag0WithSpace }, Title = Line1 }, new SearchDocument { PortalId = PortalId0, Tags = new List { Tag1, Tag2, TagNeutral }, Title = Line2, CultureCode = CultureEnUs }, new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line3, CultureCode = CultureItIt }, @@ -434,11 +504,12 @@ private IEnumerable GetStandardSearchDocs(int searchTypeId = Mod private IEnumerable GetSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) { - var searchDocs = new List { - new SearchDocument { PortalId = PortalId0, Title = Line1, Keywords = {{"title", "Hello"}}, Body = "Hello1 World"}, - new SearchDocument { PortalId = PortalId0, Title = Line2, Keywords = {{"subject", "Hello"}}, Body = "Hello2 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line3, Keywords = {{"comments", "Hello"}}, Body = "Hello3 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line4, Keywords = {{"authorname", "Hello"}}, Body = "Hello4 World" }, + var searchDocs = new List + { + new SearchDocument { PortalId = PortalId0, Title = Line1, Keywords = { { "title", "Hello" } }, Body = "Hello1 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line2, Keywords = { { "subject", "Hello" } }, Body = "Hello2 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line3, Keywords = { { "comments", "Hello" } }, Body = "Hello3 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line4, Keywords = { { "authorname", "Hello" } }, Body = "Hello4 World" }, }; var now = DateTime.UtcNow.AddYears(-searchDocs.Count); @@ -457,26 +528,26 @@ private IEnumerable GetSearchDocsForCustomBoost(int searchTypeId } /// - /// Adds standarad SearchDocs in Lucene Index + /// Adds standarad SearchDocs in Lucene Index. /// - /// Number of dcuments added + /// Number of dcuments added. private int AddStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) { - var docs = GetStandardSearchDocs(searchTypeId).ToArray(); - _internalSearchController.AddSearchDocuments(docs); + var docs = this.GetStandardSearchDocs(searchTypeId).ToArray(); + this._internalSearchController.AddSearchDocuments(docs); return docs.Length; } private int AddSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) { - var docs = GetSearchDocsForCustomBoost(searchTypeId).ToArray(); - _internalSearchController.AddSearchDocuments(docs); + var docs = this.GetSearchDocsForCustomBoost(searchTypeId).ToArray(); + this._internalSearchController.AddSearchDocuments(docs); return docs.Length; } private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) - { - var doc1 = new SearchDocument + { + var doc1 = new SearchDocument { Title = "Title", UniqueKey = "key1", @@ -485,7 +556,7 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue50 } }, - }; + }; var doc2 = new SearchDocument { Title = "Title", @@ -494,7 +565,7 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue100 } }, - }; + }; var doc3 = new SearchDocument { Title = "Title", @@ -503,7 +574,7 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue200 } }, - }; + }; var doc4 = new SearchDocument { Title = "Title", @@ -512,7 +583,7 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue500 } }, - }; + }; var doc5 = new SearchDocument { Title = "Title", @@ -521,12 +592,12 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue1000 } }, - }; - - var docs = new List() {doc1, doc2, doc3, doc4, doc5}; - - _internalSearchController.AddSearchDocuments(docs); - + }; + + var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; + + this._internalSearchController.AddSearchDocuments(docs); + return docs.Count; } @@ -540,7 +611,7 @@ private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } } + Keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, }; var doc2 = new SearchDocument { @@ -549,7 +620,7 @@ private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord2Value } } + Keywords = new Dictionary() { { KeyWord1Name, KeyWord2Value } }, }; var doc3 = new SearchDocument { @@ -558,7 +629,7 @@ private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord3Value } } + Keywords = new Dictionary() { { KeyWord1Name, KeyWord3Value } }, }; var doc4 = new SearchDocument { @@ -567,7 +638,7 @@ private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord4Value } } + Keywords = new Dictionary() { { KeyWord1Name, KeyWord4Value } }, }; var doc5 = new SearchDocument { @@ -576,30 +647,30 @@ private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord5Value } } + Keywords = new Dictionary() { { KeyWord1Name, KeyWord5Value } }, }; var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; - _internalSearchController.AddSearchDocuments(docs); + this._internalSearchController.AddSearchDocuments(docs); return docs.Count; } - private int AddDocuments(IList titles, string body, int searchTypeId = OtherSearchTypeId) + private int AddDocuments(IList titles, string body, int searchTypeId = OtherSearchTypeId) { var count = 0; - foreach (var doc in titles.Select(title => new SearchDocument - { - Title = title, - UniqueKey = Guid.NewGuid().ToString(), - Body = body, - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12 - })) - { - _internalSearchController.AddSearchDocument(doc); + foreach (var doc in titles.Select(title => new SearchDocument + { + Title = title, + UniqueKey = Guid.NewGuid().ToString(), + Body = body, + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + })) + { + this._internalSearchController.AddSearchDocument(doc); count++; } @@ -616,10 +687,10 @@ private int AddDocumentsWithKeywords(IEnumerable keywords, string title, Keywords = new Dictionary() { { KeyWord1Name, keyword } }, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12 + PortalId = PortalId12, })) { - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); count++; } @@ -631,163 +702,77 @@ private void AddLinesAsSearchDocs(IList lines, int searchTypeId = OtherS var now = DateTime.UtcNow - TimeSpan.FromSeconds(lines.Count()); var i = 0; - _internalSearchController.AddSearchDocuments( + this._internalSearchController.AddSearchDocuments( lines.Select(line => new SearchDocument { Title = line, UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = searchTypeId, - ModifiedTimeUtc = now.AddSeconds(i++) + ModifiedTimeUtc = now.AddSeconds(i++), }).ToList()); } private SearchResults SearchForKeyword(string keyword, int searchTypeId = OtherSearchTypeId, bool useWildcard = false, bool allowLeadingWildcard = false) { - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = useWildcard, AllowLeadingWildcard = allowLeadingWildcard }; - return _searchController.SiteSearch(query); + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = useWildcard, AllowLeadingWildcard = allowLeadingWildcard }; + return this._searchController.SiteSearch(query); } private SearchResults SearchForKeywordWithWildCard(string keyword, int searchTypeId = OtherSearchTypeId) { var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = true }; - return _searchController.SiteSearch(query); + return this._searchController.SiteSearch(query); } private SearchResults SearchForKeywordInModule(string keyword, int searchTypeId = ModuleSearchTypeId) { var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId } }; - return _searchController.SiteSearch(query); + return this._searchController.SiteSearch(query); } private string StipEllipses(string text) { - return text.Replace("...", "").Trim(); - } - - /// - /// Executes function proc on a separate thread respecting the given timeout value. - /// - /// - /// The function to execute. - /// The timeout duration. - /// R - /// From: http://stackoverflow.com/questions/9460661/implementing-regex-timeout-in-net-4 - private static R ExecuteWithTimeout(Func proc, TimeSpan timeout) - { - var r = default(R); // init default return value - Exception ex = null; // records inter-thread exception - - // define a thread to wrap 'proc' - var t = new Thread(() => - { - try - { - r = proc(); - } - catch (Exception e) - { - // this can get set to ThreadAbortException - ex = e; - - Console.WriteLine("Exception hit"); - - } - }); - - t.Start(); // start running 'proc' thread wrapper - // from docs: "The Start method does not return until the new thread has started running." - - if (t.Join(timeout) == false) - { - t.Abort(); // die evil thread! - // Abort raises the ThreadAbortException - int i = 0; - while ((t.Join(1) == false) && (i < 20)) - { - // 20 ms wait possible here - i++; - } - if (i >= 20) - { - // we didn't abort, might want to log this or take some other action - // this can happen if you are doing something indefinitely hinky in a - // finally block (cause the finally be will executed before the Abort - // completes. - Console.WriteLine("Abort didn't work as expected"); - } - } - - if (ex != null) - { - throw ex; // oops - } - return r; // ah! - } - - #endregion - - #region Search Tests - - [Test] - public void SearchController_Search_Throws_On_Null_Query() - { - //Arrange - - //Act, Assert - Assert.Throws(() => _searchController.SiteSearch(null)); - } - - [Test] - public void SearchController_Search_Throws_On_Empty_TypeId_Collection() - { - //Arrange - - //Act, Assert - Assert.Throws(() => _searchController.SiteSearch(new SearchQuery { KeyWords = "word" })); + return text.Replace("...", string.Empty).Trim(); } [Test] public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing() { - //Arrange + // Arrange var document = new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "< ExecuteWithTimeout( () => { - _internalSearchController.AddSearchDocument(document); + this._internalSearchController.AddSearchDocument(document); return false; }, TimeSpan.FromSeconds(1))); - } - - #endregion - - #region Add and Search Tests - + } + [Test] public void SearchController_Added_Item_IsRetrieved() { - //Arrange + // Arrange var doc = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - //Act - _internalSearchController.AddSearchDocument(doc); + // Act + this._internalSearchController.AddSearchDocument(doc); - var result = SearchForKeyword("hello"); + var result = this.SearchForKeyword("hello"); - //Assert + // Assert Assert.AreEqual(1, result.Results.Count); Assert.AreEqual(result.Results[0].UniqueKey, doc.UniqueKey); Assert.AreEqual(result.Results[0].Title, doc.Title); @@ -796,118 +781,122 @@ public void SearchController_Added_Item_IsRetrieved() [Test] public void SearchController_EnsureIndexIsAppended_When_Index_Is_NotDeleted_InBetween() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { Line1, Line2, }; - //Act + // Act - //Add first document + // Add first document var doc1 = new SearchDocument { Title = docs[0], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - _internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc1); - //first luceneQuery + // first luceneQuery var query1 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; - var search1 = _searchController.SiteSearch(query1); + var search1 = this._searchController.SiteSearch(query1); - //Assert + // Assert Assert.AreEqual(1, search1.Results.Count); - //Add second document + // Add second document var doc2 = new SearchDocument { Title = docs[1], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - _internalSearchController.AddSearchDocument(doc2); - CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion + this._internalSearchController.AddSearchDocument(doc2); + this.CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion - //second luceneQuery + // second luceneQuery var query2 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; - var search2 = _searchController.SiteSearch(query2); + var search2 = this._searchController.SiteSearch(query2); - //Assert + // Assert Assert.AreEqual(2, search2.Results.Count); } [Test] public void SearchController_Getsearch_TwoTermsSearch() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { Line1, Line2, Line3, Line4, - Line5 + Line5, }; - AddLinesAsSearchDocs(docs); + this.AddLinesAsSearchDocs(docs); - //Act - var search = SearchForKeyword("fox jumps"); + // Act + var search = this.SearchForKeyword("fox jumps"); - //Assert + // Assert Assert.AreEqual(docs.Length, search.Results.Count); - //Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); - //Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); + + // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); + // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); } [Test] public void SearchController_GetResult_TwoTermsSearch() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { Line1, Line2, Line3, Line4, - Line5 + Line5, }; - AddLinesAsSearchDocs(docs); + this.AddLinesAsSearchDocs(docs); - //Act - var search = SearchForKeyword("fox jumps"); + // Act + var search = this.SearchForKeyword("fox jumps"); - //Assert + // Assert Assert.AreEqual(docs.Length, search.Results.Count); - //Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); - //Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); + + // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); + // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); } [Test] public void SearchController_GetResult_PortalIdSearch() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, PortalIds = new List { PortalId0 } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); } [Test] public void SearchController_GetResult_SearchTypeIdSearch() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); } - - + [Test] public void SearchController_SearchFindsAnalyzedVeryLongWords() { - //Arrange - //const string fieldName = Constants.ContentTag; + // Arrange + // const string fieldName = Constants.ContentTag; const string veryLongWord = // 107 characters "NowIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountryalsoIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountry"; @@ -918,81 +907,54 @@ public void SearchController_SearchFindsAnalyzedVeryLongWords() SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleId = 1, - ModuleDefId = 1 + ModuleDefId = 1, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); - //Act + // Act var query = new SearchQuery { KeyWords = veryLongWord, SearchTypeIds = new List { ModuleSearchTypeId } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual("" + veryLongWord + "", StipEllipses(search.Results[0].Snippet).Trim()); - } - #endregion - - #region Security Trimming Tests - + Assert.AreEqual("" + veryLongWord + "", this.StipEllipses(search.Results[0].Snippet).Trim()); + } + [Test] public void SearchController_SecurityTrimmedTest_ReturnsNoResultsWhenHavingNoPermission() { - //Arrange - AddStandardSearchDocs(DocumentSearchTypeId); + // Arrange + this.AddStandardSearchDocs(DocumentSearchTypeId); - //Act - var result = SearchForKeyword("fox", DocumentSearchTypeId); + // Act + var result = this.SearchForKeyword("fox", DocumentSearchTypeId); - //Assert + // Assert // by default AuthorUserId = 0 which have no permission, so this passes Assert.AreEqual(0, result.Results.Count); } - /// - /// Sets up some data for testing security trimming. - /// In the tests below, the users will have access to the follwoing documents - /// { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29, ..., etc. } - /// The tests check that pagination qith various page sizes returns the proper groupings - /// - private void SetupSecurityTrimmingDocs(int totalDocs, int searchType = DocumentSearchTypeId) - { - var docModifyTime = DateTime.UtcNow - TimeSpan.FromSeconds(totalDocs); - for (var i = 0; i < totalDocs; i++) - { - _internalSearchController.AddSearchDocument(new SearchDocument - { - AuthorUserId = i, - Title = "Fox and Dog", - Body = Line1, - Tags = new[] { Tag0, Tag1 }, - SearchTypeId = searchType, - UniqueKey = Guid.NewGuid().ToString(), - ModifiedTimeUtc = docModifyTime.AddSeconds(i), - }); - } - } - [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 1, PageSize = 4, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(query.PageSize, result.Results.Count); Assert.AreEqual(new[] { 6, 7, 8, 9 }, ids); @@ -1001,50 +963,74 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1B() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 1, PageSize = 6, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(query.PageSize, result.Results.Count); Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17 }, ids); } + /// + /// Sets up some data for testing security trimming. + /// In the tests below, the users will have access to the follwoing documents + /// { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29, ..., etc. } + /// The tests check that pagination qith various page sizes returns the proper groupings. + /// + private void SetupSecurityTrimmingDocs(int totalDocs, int searchType = DocumentSearchTypeId) + { + var docModifyTime = DateTime.UtcNow - TimeSpan.FromSeconds(totalDocs); + for (var i = 0; i < totalDocs; i++) + { + this._internalSearchController.AddSearchDocument(new SearchDocument + { + AuthorUserId = i, + Title = "Fox and Dog", + Body = Line1, + Tags = new[] { Tag0, Tag1 }, + SearchTypeId = searchType, + UniqueKey = Guid.NewGuid().ToString(), + ModifiedTimeUtc = docModifyTime.AddSeconds(i), + }); + } + } + [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 1, PageSize = 8, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(query.PageSize, result.Results.Count); Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19 }, ids); @@ -1053,24 +1039,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1D() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; // user should have access to some documnets here - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 1, PageSize = 100, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(4 * 3, result.TotalHits); Assert.AreEqual(4 * 3, result.Results.Count); Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29 }, ids); @@ -1079,24 +1065,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1D [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1E() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = TabSearchTypeId; // user should have access to all documnets here - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 1, PageSize = 10, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).Skip(1).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs, result.TotalHits); Assert.AreEqual(query.PageSize, result.Results.Count); Assert.AreEqual(Enumerable.Range(1, 9).ToArray(), ids); @@ -1105,24 +1091,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1E [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1F() { - //Arrange + // Arrange const int maxDocs = 100; const int stype = TabSearchTypeId; // user should have access to all documnets here - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 10, PageSize = 10, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs, result.TotalHits); Assert.AreEqual(query.PageSize, result.Results.Count); Assert.AreEqual(Enumerable.Range(90, 10).ToArray(), ids); @@ -1131,24 +1117,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1F [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2A() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 2, PageSize = 5, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(5, result.Results.Count); Assert.AreEqual(new[] { 17, 18, 19, 26, 27 }, ids); @@ -1157,24 +1143,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2A [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2B() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 2, PageSize = 6, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(6, result.Results.Count); Assert.AreEqual(new[] { 18, 19, 26, 27, 28, 29 }, ids); @@ -1183,24 +1169,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2B [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2C() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var query = new SearchQuery { PageIndex = 2, PageSize = 8, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(query); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(4, result.Results.Count); Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); @@ -1209,24 +1195,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2C [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3A() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var queryPg3 = new SearchQuery { PageIndex = 3, PageSize = 4, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(queryPg3); + var result = this._searchController.SiteSearch(queryPg3); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(queryPg3.PageSize, result.Results.Count); Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); @@ -1235,24 +1221,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3A [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3B() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var queryPg3 = new SearchQuery { PageIndex = 3, PageSize = 5, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(queryPg3); + var result = this._searchController.SiteSearch(queryPg3); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(2, result.Results.Count); Assert.AreEqual(new[] { 28, 29 }, ids); @@ -1261,24 +1247,24 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3B [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3C() { - //Arrange + // Arrange const int maxDocs = 30; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var queryPg3 = new SearchQuery { PageIndex = 3, PageSize = 8, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(queryPg3); + var result = this._searchController.SiteSearch(queryPg3); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert + // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); Assert.AreEqual(0, result.Results.Count); Assert.AreEqual(new int[] { }, ids); @@ -1287,37 +1273,33 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3C [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage5() { - //Arrange + // Arrange const int maxDocs = 100; const int stype = DocumentSearchTypeId; - SetupSecurityTrimmingDocs(maxDocs, stype); + this.SetupSecurityTrimmingDocs(maxDocs, stype); - //Act + // Act var queryPg3 = new SearchQuery { PageIndex = 5, PageSize = 8, KeyWords = "fox", - SearchTypeIds = new[] { stype } + SearchTypeIds = new[] { stype }, }; - var result = _searchController.SiteSearch(queryPg3); + var result = this._searchController.SiteSearch(queryPg3); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - //Assert - Assert.AreEqual(maxDocs - 10 * 6, result.TotalHits); + // Assert + Assert.AreEqual(maxDocs - (10 * 6), result.TotalHits); Assert.AreEqual(queryPg3.PageSize, result.Results.Count); Assert.AreEqual(new int[] { 86, 87, 88, 89, 96, 97, 98, 99 }, ids); - } - - #endregion - - #region Supplied Data Tests - + } + [Test] public void SearchController_GetResult_Returns_Correct_SuppliedData_When_Optionals_Are_Supplied() { - //Arrange + // Arrange var modifiedDateTime = DateTime.UtcNow; var numericKeys = new Dictionary() { { NumericKey1, NumericValue1 }, { NumericKey2, NumericValue2 } }; var keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value }, { KeyWord2Name, KeyWord2Value } }; @@ -1340,14 +1322,14 @@ public void SearchController_GetResult_Returns_Correct_SuppliedData_When_Optiona QueryString = StandardQueryString, Tags = tags, NumericKeys = numericKeys, - Keywords = keywords + Keywords = keywords, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); - //run luceneQuery on common keyword between both the docs - var search = SearchForKeywordInModule("Title"); + // run luceneQuery on common keyword between both the docs + var search = this.SearchForKeywordInModule("Title"); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(PortalId12, search.Results[0].PortalId); Assert.AreEqual(StandardTabId, search.Results[0].TabId); @@ -1376,7 +1358,7 @@ public void SearchController_GetResult_Returns_Correct_SuppliedData_When_Optiona [Test] public void SearchController_GetResult_Returns_EmptyData_When_Optionals_Are_Not_Supplied() { - //Arrange + // Arrange var modifiedDateTime = DateTime.UtcNow; var doc = new SearchDocument { @@ -1386,11 +1368,11 @@ public void SearchController_GetResult_Returns_EmptyData_When_Optionals_Are_Not_ SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = modifiedDateTime, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); - var search = SearchForKeyword("Title"); + var search = this.SearchForKeyword("Title"); - //Assert - + // Assert - Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(PortalId0, search.Results[0].PortalId); Assert.AreEqual(0, search.Results[0].TabId); @@ -1413,41 +1395,43 @@ public void SearchController_GetResult_Returns_EmptyData_When_Optionals_Are_Not_ [Test] public void SearchController_GetsHighlightedDesc() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { Line1, Line2, Line3, Line4, - Line5 + Line5, }; - AddLinesAsSearchDocs(docs); + this.AddLinesAsSearchDocs(docs); - //Act - var search = SearchForKeyword("fox"); + // Act + var search = this.SearchForKeyword("fox"); - //Assert + // Assert Assert.AreEqual(docs.Length, search.Results.Count); - Assert.IsTrue(new[] + Assert.IsTrue( + new[] { "brown fox jumps over the lazy dog", "quick fox jumps over the black dog - Italian", "gold fox jumped over the lazy black dog", "e red fox jumped over the lazy dark gray dog", - "quick fox jumps over the white dog - los de el Espana" - }.SequenceEqual(search.Results.Select(r => StipEllipses(r.Snippet))), + "quick fox jumps over the white dog - los de el Espana", + }.SequenceEqual(search.Results.Select(r => this.StipEllipses(r.Snippet))), "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Snippet))); } [Test] public void SearchController_CorrectDocumentCultureIsUsedAtIndexing() { - //Arrange + // Arrange // assign a culture that is different than the current one var isNonEnglishEnv = Thread.CurrentThread.CurrentCulture.Name != CultureEsEs; string cultureCode, title, searchWord; - //Act + // Act if (isNonEnglishEnv) { cultureCode = CultureEsEs; @@ -1461,170 +1445,161 @@ public void SearchController_CorrectDocumentCultureIsUsedAtIndexing() title = Line3; } - _internalSearchController.AddSearchDocument( + this._internalSearchController.AddSearchDocument( new SearchDocument { Title = title, UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, - CultureCode = cultureCode + CultureCode = cultureCode, }); - _internalSearchController.Commit(); + this._internalSearchController.Commit(); - var searches = SearchForKeyword(searchWord); + var searches = this.SearchForKeyword(searchWord); - //Assert + // Assert Assert.AreEqual(1, searches.TotalHits); Assert.AreEqual(cultureCode, searches.Results[0].CultureCode); - } - - #endregion - - #region DateRange Tests - + } + [Test] public void SearchController_GetResult_TimeRangeSearch_Ignores_When_Only_BeginDate_Specified() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, BeginModifiedTimeUtc = DateTime.Now }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); } [Test] public void SearchController_GetResult_TimeRangeSearch_Resturns_Scoped_Results_When_BeginDate_Is_After_End_Date() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, BeginModifiedTimeUtc = DateTime.Now, - EndModifiedTimeUtc = DateTime.Now.AddSeconds(-1) + EndModifiedTimeUtc = DateTime.Now.AddSeconds(-1), }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); } [Test] public void SearchController_GetResult_TimeRangeSearch_Resturns_Scoped_Results_When_Both_Dates_Specified() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); var stypeIds = new List { ModuleSearchTypeId }; var utcNow = DateTime.UtcNow.AddDays(1); - const SortFields sfield = SortFields.LastModified; + const SortFields sfield = SortFields.LastModified; - //Act and Assert - just a bit later + // Act and Assert - just a bit later var query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddSeconds(1), EndModifiedTimeUtc = utcNow.AddDays(1) }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); Assert.AreEqual(0, search.Results.Count); - //Act and Assert - 10 day + // Act and Assert - 10 day query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-10), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = _searchController.SiteSearch(query); + search = this._searchController.SiteSearch(query); Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(Line5, search.Results[0].Title); - //Act and Assert - 1 year or so + // Act and Assert - 1 year or so query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-368), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = _searchController.SiteSearch(query); + search = this._searchController.SiteSearch(query); Assert.AreEqual(2, search.Results.Count); Assert.AreEqual(Line5, search.Results[0].Title); Assert.AreEqual(Line4, search.Results[1].Title); - //Act and Assert - 2 years or so + // Act and Assert - 2 years or so query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-800), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = _searchController.SiteSearch(query); + search = this._searchController.SiteSearch(query); Assert.AreEqual(3, search.Results.Count); Assert.AreEqual(Line5, search.Results[0].Title); Assert.AreEqual(Line4, search.Results[1].Title); Assert.AreEqual(Line3, search.Results[2].Title); - //Act and Assert - 3 years or so + // Act and Assert - 3 years or so query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-1200), EndModifiedTimeUtc = utcNow.AddDays(1) }; - search = _searchController.SiteSearch(query); + search = this._searchController.SiteSearch(query); Assert.AreEqual(4, search.Results.Count); Assert.AreEqual(Line5, search.Results[0].Title); Assert.AreEqual(Line4, search.Results[1].Title); Assert.AreEqual(Line3, search.Results[2].Title); Assert.AreEqual(Line2, search.Results[3].Title); - //Act and Assert - 2 to 3 years or so + // Act and Assert - 2 to 3 years or so query = new SearchQuery { SearchTypeIds = stypeIds, SortField = sfield, BeginModifiedTimeUtc = utcNow.AddDays(-1200), EndModifiedTimeUtc = utcNow.AddDays(-800) }; - search = _searchController.SiteSearch(query); + search = this._searchController.SiteSearch(query); Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(Line2, search.Results[0].Title); - } - - #endregion - - #region Tag Tests - + } + [Test] public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Single_Result() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0 } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); } [Test] public void SearchController_GetResult_TagSearch_Single_Tag_With_Space_Returns_Single_Result() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0WithSpace } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); } - - + [Test] public void SearchController_GetResult_TagSearch_Lowercase_Search_Returns_PropercaseTag_Single_Result() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { TagNeutral.ToLowerInvariant() } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); } [Test] public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Two_Results() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag1 } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(2, search.Results.Count); Assert.AreEqual(Tag0, search.Results[0].Tags.ElementAt(0)); Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(1)); @@ -1635,28 +1610,28 @@ public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Two_Results( [Test] public void SearchController_GetResult_TagSearch_Two_Tags_Returns_Nothing() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag0, Tag4 } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(0, search.Results.Count); } [Test] public void SearchController_GetResult_TagSearch_Two_Tags_Returns_Single_Results() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, Tags = new List { Tag1, Tag2 } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(Tag1, search.Results[0].Tags.ElementAt(0)); Assert.AreEqual(Tag2, search.Results[0].Tags.ElementAt(1)); @@ -1665,94 +1640,90 @@ public void SearchController_GetResult_TagSearch_Two_Tags_Returns_Single_Results [Test] public void SearchController_GetResult_TagSearch_With_Vowel_Tags_Returns_Data() { - //Arrange + // Arrange const string keyword = "awesome"; var doc1 = new SearchDocument { UniqueKey = "key01", Title = keyword, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { TagTootsie } }; - //Act - _internalSearchController.AddSearchDocument(doc1); + // Act + this._internalSearchController.AddSearchDocument(doc1); var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { OtherSearchTypeId }, Tags = new List { TagTootsie } }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); - } - - #endregion - - #region Sort Tests - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void SearchController_GetResult_Throws_When_CustomNumericField_Is_Specified_And_CustomSortField_Is_Not() { - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomNumericField + SortField = SortFields.CustomNumericField, }; - _searchController.SiteSearch(query); - } + this._searchController.SiteSearch(query); + } [Test] [ExpectedException(typeof(ArgumentException))] public void SearchController_GetResult_Throws_When_CustomStringField_Is_Specified_And_CustomSortField_Is_Not() { - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.CustomStringField + SortField = SortFields.CustomStringField, }; - _searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } [Test] [ExpectedException(typeof(ArgumentException))] public void SearchController_GetResult_Throws_When_NumericKey_Is_Specified_And_CustomSortField_Is_Not() { - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.NumericKey + SortField = SortFields.NumericKey, }; - _searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } [Test] [ExpectedException(typeof(ArgumentException))] public void SearchController_GetResult_Throws_When_Keyword_Is_Specified_And_CustomSortField_Is_Not() { - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Keyword + SortField = SortFields.Keyword, }; - _searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } - + [Test] public void SearchController_GetResult_Sorty_By_Date_Returns_Latest_Docs_First() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.LastModified - }; - var search = _searchController.SiteSearch(query); + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.LastModified, + }; + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); Assert.AreEqual(Tag3, search.Results[1].Tags.ElementAt(0)); @@ -1767,19 +1738,19 @@ public void SearchController_GetResult_Sorty_By_Date_Returns_Latest_Docs_First() [Test] public void SearchController_GetResult_Sorty_By_Date_Ascending_Returns_Earliest_Docs_First() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.LastModified, - SortDirection = SortDirections.Ascending + SortDirection = SortDirections.Ascending, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.Greater(search.Results[1].DisplayModifiedTime, search.Results[0].DisplayModifiedTime); Assert.Greater(search.Results[2].DisplayModifiedTime, search.Results[1].DisplayModifiedTime); @@ -1793,20 +1764,20 @@ public void SearchController_GetResult_Sorty_By_Date_Ascending_Returns_Earliest_ [Test] public void SearchController_GetResult_Sorty_By_NumericKeys_Ascending_Returns_Smaller_Numers_First() { - var added = AddDocumentsWithNumericKeys(); + var added = this.AddDocumentsWithNumericKeys(); - //Act + // Act var query = new SearchQuery { KeyWords = "Title", SearchTypeIds = new List { OtherSearchTypeId }, SortField = SortFields.NumericKey, SortDirection = SortDirections.Ascending, - CustomSortField = NumericKey1 + CustomSortField = NumericKey1, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.Greater(search.Results[1].NumericKeys[NumericKey1], search.Results[0].NumericKeys[NumericKey1]); Assert.Greater(search.Results[2].NumericKeys[NumericKey1], search.Results[1].NumericKeys[NumericKey1]); @@ -1815,20 +1786,20 @@ public void SearchController_GetResult_Sorty_By_NumericKeys_Ascending_Returns_Sm [Test] public void SearchController_GetResult_Sorty_By_NumericKeys_Descending_Returns_Bigger_Numbers_First() { - var added = AddDocumentsWithNumericKeys(); + var added = this.AddDocumentsWithNumericKeys(); - //Act + // Act var query = new SearchQuery { KeyWords = "Title", SearchTypeIds = new List { OtherSearchTypeId }, SortField = SortFields.NumericKey, SortDirection = SortDirections.Descending, - CustomSortField = NumericKey1 + CustomSortField = NumericKey1, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.Greater(search.Results[0].NumericKeys[NumericKey1], search.Results[1].NumericKeys[NumericKey1]); Assert.Greater(search.Results[1].NumericKeys[NumericKey1], search.Results[2].NumericKeys[NumericKey1]); @@ -1837,48 +1808,48 @@ public void SearchController_GetResult_Sorty_By_NumericKeys_Descending_Returns_B [Test] public void SearchController_GetResult_Sorty_By_Title_Ascending_Returns_Alphabetic_Ascending() { - var titles = new List {"cat", "ant", "dog", "antelope", "zebra", "yellow", " "}; + var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - var added = AddDocuments(titles, "animal"); + var added = this.AddDocuments(titles, "animal"); - //Act + // Act var query = new SearchQuery { KeyWords = "animal", SearchTypeIds = new List { OtherSearchTypeId }, SortField = SortFields.Title, - SortDirection = SortDirections.Ascending + SortDirection = SortDirections.Ascending, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); var count = 0; foreach (var title in titles.OrderBy(s => s)) { Assert.AreEqual(title, search.Results[count++].Title); - } - } + } + } [Test] public void SearchController_GetResult_Sorty_By_Title_Descending_Returns_Alphabetic_Descending() { var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - var added = AddDocuments(titles, "animal"); + var added = this.AddDocuments(titles, "animal"); - //Act + // Act var query = new SearchQuery { KeyWords = "animal", SearchTypeIds = new List { OtherSearchTypeId }, SortField = SortFields.Title, - SortDirection = SortDirections.Descending + SortDirection = SortDirections.Descending, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); var count = 0; @@ -1893,20 +1864,20 @@ public void SearchController_GetResult_Sorty_By_Keyword_Ascending_Returns_Alphab { var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - var added = AddDocumentsWithKeywords(titles, "animal"); + var added = this.AddDocumentsWithKeywords(titles, "animal"); - //Act + // Act var query = new SearchQuery { KeyWords = "animal", SearchTypeIds = new List { OtherSearchTypeId }, SortField = SortFields.Keyword, SortDirection = SortDirections.Ascending, - CustomSortField = KeyWord1Name + CustomSortField = KeyWord1Name, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); var count = 0; @@ -1921,20 +1892,20 @@ public void SearchController_GetResult_Sorty_By_Keyword_Descending_Returns_Alpha { var titles = new List { "cat", "ant", "dog", "antelope", "zebra", "yellow", " " }; - var added = AddDocumentsWithKeywords(titles, "animal"); + var added = this.AddDocumentsWithKeywords(titles, "animal"); - //Act + // Act var query = new SearchQuery { KeyWords = "animal", SearchTypeIds = new List { OtherSearchTypeId }, SortField = SortFields.Keyword, SortDirection = SortDirections.Descending, - CustomSortField = KeyWord1Name + CustomSortField = KeyWord1Name, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); var count = 0; @@ -1947,89 +1918,87 @@ public void SearchController_GetResult_Sorty_By_Keyword_Descending_Returns_Alpha [Test] public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Descending_Order_Does_Not_Throw() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.CustomStringField, SortDirection = SortDirections.Descending, - CustomSortField = "unknown" + CustomSortField = "unknown", }; - _searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } - - + [Test] public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Ascending_Order_Does_Not_Throw() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.CustomStringField, SortDirection = SortDirections.Ascending, - CustomSortField = "unknown" + CustomSortField = "unknown", }; - _searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } [Test] public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Descending_Order_Does_Not_Throw() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.CustomNumericField, SortDirection = SortDirections.Descending, - CustomSortField = "unknown" + CustomSortField = "unknown", }; - _searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } - - + [Test] public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Ascending_Order_Does_Not_Throw() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.CustomNumericField, SortDirection = SortDirections.Ascending, - CustomSortField = "unknown" + CustomSortField = "unknown", }; - _searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } [Test] public void SearchController_GetResult_Sorty_By_Relevance_Returns_TopHit_Docs_First() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - KeyWords = "brown OR fox" - }; - var search = _searchController.SiteSearch(query); + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + KeyWords = "brown OR fox", + }; + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.AreEqual(true, search.Results[0].Snippet.Contains("brown") && search.Results[0].Snippet.Contains("dog")); } @@ -2037,22 +2006,22 @@ public void SearchController_GetResult_Sorty_By_Relevance_Returns_TopHit_Docs_Fi [Test] public void SearchController_GetResult_Sorty_By_RelevanceAndTitleKeyword_Returns_TopHit_Docs_First() { - _mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(CustomBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(CustomBoost); - //Arrange - var added = AddSearchDocsForCustomBoost(); - CreateNewLuceneControllerInstance(true); + // Arrange + var added = this.AddSearchDocsForCustomBoost(); + this.CreateNewLuceneControllerInstance(true); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.Relevance, - KeyWords = "Hello" + KeyWords = "Hello", }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.AreEqual(true, search.Results[0].Body.Contains("Hello1")); } @@ -2060,21 +2029,22 @@ public void SearchController_GetResult_Sorty_By_RelevanceAndTitleKeyword_Returns [Test] public void SearchController_GetResult_Sorty_By_RelevanceAndSubjectKeyword_Returns_TopHit_Docs_First() { - _mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(CustomBoost); - CreateNewLuceneControllerInstance(true); - //Arrange - var added = AddSearchDocsForCustomBoost(); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(CustomBoost); + this.CreateNewLuceneControllerInstance(true); + + // Arrange + var added = this.AddSearchDocsForCustomBoost(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.Relevance, - KeyWords = "Hello" + KeyWords = "Hello", }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.AreEqual(true, search.Results[0].Body.Contains("Hello2")); } @@ -2082,21 +2052,22 @@ public void SearchController_GetResult_Sorty_By_RelevanceAndSubjectKeyword_Retur [Test] public void SearchController_GetResult_Sorty_By_RelevanceAndCommentKeyword_Returns_TopHit_Docs_First() { - _mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(CustomBoost); - CreateNewLuceneControllerInstance(true); - //Arrange - var added = AddSearchDocsForCustomBoost(); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(CustomBoost); + this.CreateNewLuceneControllerInstance(true); + + // Arrange + var added = this.AddSearchDocsForCustomBoost(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.Relevance, - KeyWords = "Hello" + KeyWords = "Hello", }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.AreEqual(true, search.Results[0].Body.Contains("Hello3")); } @@ -2104,21 +2075,22 @@ public void SearchController_GetResult_Sorty_By_RelevanceAndCommentKeyword_Retur [Test] public void SearchController_GetResult_Sorty_By_RelevanceAndAuthorKeyword_Returns_TopHit_Docs_First() { - _mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(CustomBoost); - CreateNewLuceneControllerInstance(true); - //Arrange - var added = AddSearchDocsForCustomBoost(); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(CustomBoost); + this.CreateNewLuceneControllerInstance(true); + + // Arrange + var added = this.AddSearchDocsForCustomBoost(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.Relevance, - KeyWords = "Hello" + KeyWords = "Hello", }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.AreEqual(true, search.Results[0].Body.Contains("Hello4")); } @@ -2126,77 +2098,70 @@ public void SearchController_GetResult_Sorty_By_RelevanceAndAuthorKeyword_Return [Test] public void SearchController_GetResult_Sorty_By_Relevance_Ascending_Does_Not_Change_Sequence_Of_Results() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act + // Act var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, SortField = SortFields.Relevance, SortDirection = SortDirections.Ascending, - KeyWords = "brown OR fox" + KeyWords = "brown OR fox", }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(added, search.Results.Count); Assert.AreEqual(true, search.Results[0].Snippet.Contains("brown") && search.Results[0].Snippet.Contains("dog")); - } - - #endregion - - #region Locale Tests - + } + [Test] public void SearchController_GetResult_By_Locale_Returns_Specific_And_Neutral_Locales() { - //Arrange - AddStandardSearchDocs(); + // Arrange + this.AddStandardSearchDocs(); - //Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.LastModified, - CultureCode = CultureItIt - }; - var search = _searchController.SiteSearch(query); + // Act + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.LastModified, + CultureCode = CultureItIt, + }; + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(2, search.Results.Count, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); Assert.AreEqual(Line3, search.Results[0].Title); Assert.AreEqual(Line1, search.Results[1].Title); - } - - - #endregion - - #region Add and Delete Tests + } + [Test] public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_Content_With_Same_Key() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { Line1, Line2, }; const string docKey = "key1"; - //Act + // Act - //Add first document + // Add first document var doc1 = new SearchDocument { Title = docs[0], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - _internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc1); - //Add second document with same key + // Add second document with same key var doc2 = new SearchDocument { Title = docs[1], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - _internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc2); - //run luceneQuery on common keyword between both the docs - var search = SearchForKeyword("fox"); + // run luceneQuery on common keyword between both the docs + var search = this.SearchForKeyword("fox"); - //Assert - there should just be one entry - first one must have been removed. + // Assert - there should just be one entry - first one must have been removed. Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(docs[1], search.Results[0].Title); } @@ -2213,7 +2178,7 @@ public void SearchController_Add_Does_Not_Throw_On_Empty_Url() QueryString = "?foo=bar", }; - Assert.DoesNotThrow(() => _internalSearchController.AddSearchDocument(doc)); + Assert.DoesNotThrow(() => this._internalSearchController.AddSearchDocument(doc)); } [Test] @@ -2223,163 +2188,153 @@ public void SearchController_Add_Does_Not_Throw_On_Empty_Title() { UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow + ModifiedTimeUtc = DateTime.UtcNow, }; - Assert.DoesNotThrow(() => _internalSearchController.AddSearchDocument(doc)); - } - - #endregion - - #region IsActive Tests + Assert.DoesNotThrow(() => this._internalSearchController.AddSearchDocument(doc)); + } + [Test] public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_When_IsActive_Is_False() { - //Arrange - string[] docs = { + // Arrange + string[] docs = + { Line1, Line2, }; const string docKey = "key1"; - //Act + // Act - //Add first document + // Add first document var doc1 = new SearchDocument { Title = docs[0], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - _internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc1); - //Add second document with same key + // Add second document with same key var doc2 = new SearchDocument { Title = docs[1], UniqueKey = docKey, SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, IsActive = false }; - _internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc2); - //run luceneQuery on common keyword between both the docs - var search = SearchForKeyword("fox"); + // run luceneQuery on common keyword between both the docs + var search = this.SearchForKeyword("fox"); - //Assert - there should not be any record. + // Assert - there should not be any record. Assert.AreEqual(0, search.Results.Count); - } - - #endregion - - #region accents tests - // Note: these tests needs to pass through the analyzer which is utilized - // in SearchControllerImpl but not LuceneControllerImpl. - + } + + // Note: these tests needs to pass through the analyzer which is utilized + // in SearchControllerImpl but not LuceneControllerImpl. [Test] public void SearchController_SearchFindsAccentedAndNonAccentedWords() { - //Arrange - string[] lines = { + // Arrange + string[] lines = + { "zèbre or panthère", "zebre without accent", - "panthere without accent" + "panthere without accent", }; - AddLinesAsSearchDocs(lines); + this.AddLinesAsSearchDocs(lines); - //Act - var searches1 = SearchForKeyword("zèbre"); - var searches2 = SearchForKeyword("zebre"); + // Act + var searches1 = this.SearchForKeyword("zèbre"); + var searches2 = this.SearchForKeyword("zebre"); - //Assert + // Assert Assert.AreEqual(2, searches1.TotalHits); - Assert.AreEqual("zèbre or panthère", StipEllipses(searches1.Results[0].Snippet).Trim()); - Assert.AreEqual("zebre without accent", StipEllipses(searches1.Results[1].Snippet).Trim()); + Assert.AreEqual("zèbre or panthère", this.StipEllipses(searches1.Results[0].Snippet).Trim()); + Assert.AreEqual("zebre without accent", this.StipEllipses(searches1.Results[1].Snippet).Trim()); Assert.AreEqual(2, searches2.TotalHits); - Assert.AreEqual("zèbre or panthère", StipEllipses(searches2.Results[0].Snippet).Trim()); - Assert.AreEqual("zebre without accent", StipEllipses(searches2.Results[1].Snippet).Trim()); + Assert.AreEqual("zèbre or panthère", this.StipEllipses(searches2.Results[0].Snippet).Trim()); + Assert.AreEqual("zebre without accent", this.StipEllipses(searches2.Results[1].Snippet).Trim()); } [Test] public void SearchController_PorterFilterTest() { - //Arrange - string[] lines = { + // Arrange + string[] lines = + { "field1_value", "field2_value", }; - AddLinesAsSearchDocs(lines); + this.AddLinesAsSearchDocs(lines); - //Act - var search1 = SearchForKeyword(lines[0]); - var search2 = SearchForKeyword("\"" + lines[1] + "\""); + // Act + var search1 = this.SearchForKeyword(lines[0]); + var search2 = this.SearchForKeyword("\"" + lines[1] + "\""); - //Assert + // Assert Assert.AreEqual(1, search1.TotalHits); Assert.AreEqual(1, search2.TotalHits); - Assert.AreEqual("" + lines[0] + "", StipEllipses(search1.Results[0].Snippet).Trim()); - Assert.AreEqual("" + lines[1] + "", StipEllipses(search2.Results[0].Snippet).Trim()); + Assert.AreEqual("" + lines[0] + "", this.StipEllipses(search1.Results[0].Snippet).Trim()); + Assert.AreEqual("" + lines[1] + "", this.StipEllipses(search2.Results[0].Snippet).Trim()); } [Test] public void SearchController_SearchFindsStemmedWords() { - //Arrange - string[] lines = { + // Arrange + string[] lines = + { "I ride my bike to work", "All team are riding their bikes", "The boy rides his bike to school", - "This sentence is missing the bike ri... word" + "This sentence is missing the bike ri... word", }; - AddLinesAsSearchDocs(lines); + this.AddLinesAsSearchDocs(lines); - //Act - var search = SearchForKeyword("ride"); + // Act + var search = this.SearchForKeyword("ride"); - //Assert + // Assert Assert.AreEqual(3, search.TotalHits); - Assert.AreEqual("I ride my bike to work", StipEllipses(search.Results[0].Snippet)); - Assert.AreEqual("m are riding their bikes", StipEllipses(search.Results[1].Snippet)); - Assert.AreEqual("e boy rides his bike to school", StipEllipses(search.Results[2].Snippet)); - } - - #endregion - - #region synonyms tests - + Assert.AreEqual("I ride my bike to work", this.StipEllipses(search.Results[0].Snippet)); + Assert.AreEqual("m are riding their bikes", this.StipEllipses(search.Results[1].Snippet)); + Assert.AreEqual("e boy rides his bike to school", this.StipEllipses(search.Results[2].Snippet)); + } + [Test] public void SearchController_Search_Synonym_Works() { - //Arrange - var added = AddStandardSearchDocs(); + // Arrange + var added = this.AddStandardSearchDocs(); - //Act - var search = SearchForKeywordInModule("wolf"); + // Act + var search = this.SearchForKeywordInModule("wolf"); - //Assert + // Assert Assert.AreEqual(added, search.TotalHits); - var snippets = search.Results.Select(result => StipEllipses(result.Snippet)).OrderBy(s => s).ToArray(); + var snippets = search.Results.Select(result => this.StipEllipses(result.Snippet)).OrderBy(s => s).ToArray(); Assert.AreEqual("brown fox jumps over the lazy dog", snippets[0]); Assert.AreEqual("e red fox jumped over the lazy dark gray dog", snippets[1]); Assert.AreEqual("gold fox jumped over the lazy black dog", snippets[2]); Assert.AreEqual("quick fox jumps over the black dog - Italian", snippets[3]); - } - #endregion - - #region Field Boosting Tests + } + [Test] public void SearchController_Title_Ranked_Higher_Than_Body() { - //Arrange + // Arrange var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "Hello World" }; var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "cow is gone" }; var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; - //Act - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.Commit(); - + // Act + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.Commit(); + + var result = this.SearchForKeyword("cow"); - var result = SearchForKeyword("cow"); - - //Assert + // Assert Assert.AreEqual(result.TotalHits, 2); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); @@ -2388,21 +2343,20 @@ public void SearchController_Title_Ranked_Higher_Than_Body() [Test] public void SearchController_Title_Ranked_Higher_Than_Body_Regardless_Of_Document_Sequence() { - //Arrange + // Arrange var doc1 = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "cow is gone" }; var doc2 = new SearchDocument { UniqueKey = "key02", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; var doc3 = new SearchDocument { UniqueKey = "key03", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - //Act - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.Commit(); - + // Act + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.Commit(); + + var result = this.SearchForKeyword("cow"); - var result = SearchForKeyword("cow"); - - //Assert + // Assert Assert.AreEqual(result.TotalHits, 2); Assert.AreEqual(doc3.UniqueKey, result.Results[0].UniqueKey); Assert.AreEqual(doc1.UniqueKey, result.Results[1].UniqueKey); @@ -2411,19 +2365,19 @@ public void SearchController_Title_Ranked_Higher_Than_Body_Regardless_Of_Documen [Test] public void SearchController_Title_Ranked_Higher_Than_Tag() { - //Arrange + // Arrange var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "Hello World" }; var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { "cow", "hello", "world" } }; var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "random text" }; - //Act - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.Commit(); - var result = SearchForKeyword("cow"); + // Act + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.Commit(); + var result = this.SearchForKeyword("cow"); - //Assert + // Assert Assert.AreEqual(result.TotalHits, 2); Console.WriteLine("first score: {0} {1}", result.Results[0].UniqueKey, result.Results[0].DisplayScore); Console.WriteLine("second score: {0} {1}", result.Results[1].UniqueKey, result.Results[1].DisplayScore); @@ -2434,28 +2388,25 @@ public void SearchController_Title_Ranked_Higher_Than_Tag() [Test] public void SearchController_RankingTest_With_Vowel() { - //Arrange + // Arrange var doc1 = new SearchDocument { UniqueKey = "key01", Title = "tootsie", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Tags = new List { "tootsie" } }; var doc3 = new SearchDocument { UniqueKey = "key03", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Keywords = new Dictionary() { { KeyWord1Name, "tootsie" } } }; var doc4 = new SearchDocument { UniqueKey = "key04", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Description = "tootsie" }; var doc5 = new SearchDocument { UniqueKey = "key05", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "hello tootsie" }; - - - - //Act - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.AddSearchDocument(doc4); - _internalSearchController.AddSearchDocument(doc5); - - _internalSearchController.Commit(); - - - var result = SearchForKeyword("tootsie"); - - //Assert + + // Act + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.AddSearchDocument(doc4); + this._internalSearchController.AddSearchDocument(doc5); + + this._internalSearchController.Commit(); + + var result = this.SearchForKeyword("tootsie"); + + // Assert Assert.AreEqual(5, result.TotalHits); foreach (var searchResult in result.Results) { @@ -2466,25 +2417,22 @@ public void SearchController_RankingTest_With_Vowel() Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); Assert.AreEqual(doc3.UniqueKey, result.Results[2].UniqueKey); Assert.AreEqual(doc4.UniqueKey, result.Results[3].UniqueKey); - } - - #endregion - - #region FileName Tests + } + [Test] public void SearchController_FileNameTest_With_WildCard() { - //Arrange + // Arrange var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - //Act - _internalSearchController.AddSearchDocument(doc1); + // Act + this._internalSearchController.AddSearchDocument(doc1); - _internalSearchController.Commit(); + this._internalSearchController.Commit(); - var result = SearchForKeywordWithWildCard("file"); + var result = this.SearchForKeywordWithWildCard("file"); - //Assert + // Assert Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); } @@ -2492,17 +2440,17 @@ public void SearchController_FileNameTest_With_WildCard() [Test] public void SearchController_Full_FileNameTest_Without_WildCard() { - //Arrange + // Arrange var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - //Act - _internalSearchController.AddSearchDocument(doc1); + // Act + this._internalSearchController.AddSearchDocument(doc1); - _internalSearchController.Commit(); + this._internalSearchController.Commit(); - var result = SearchForKeywordWithWildCard("file.ext"); + var result = this.SearchForKeywordWithWildCard("file.ext"); - //Assert + // Assert Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); } @@ -2510,24 +2458,58 @@ public void SearchController_Full_FileNameTest_Without_WildCard() [Test] public void SearchController_Full_FileNameTest_With_WildCard() { - //Arrange + // Arrange var doc1 = new SearchDocument { UniqueKey = "key01", Title = "file.ext", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - //Act - _internalSearchController.AddSearchDocument(doc1); + // Act + this._internalSearchController.AddSearchDocument(doc1); - _internalSearchController.Commit(); + this._internalSearchController.Commit(); - var result = SearchForKeyword("file.ext"); + var result = this.SearchForKeyword("file.ext"); - //Assert + // Assert Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); + } + + [Test] + public void SearchController_Scope_By_FolderName() + { + // Arrange + this.AddFoldersAndFiles(); + + // Act + var result1 = this.SearchForKeyword("kw-folderName:Images/*"); + var result2 = this.SearchForKeyword("kw-folderName:Images/DNN/*"); + var result3 = this.SearchForKeywordWithWildCard("kw-folderName:Images/* AND spacer"); + + // Assert + Assert.AreEqual(5, result1.TotalHits); + Assert.AreEqual(2, result2.TotalHits); + Assert.AreEqual(1, result3.TotalHits); } - #endregion - #region folder scope search tests + [Test] + public void SearchController_Scope_By_FolderName_With_Spaces() + { + // Arrange + this.AddFoldersAndFiles(); + + // Act - Space is replaced by < + var query1 = new SearchQuery { KeyWords = "kw-folderName:Images/*", SearchTypeIds = new[] { OtherSearchTypeId }, WildCardSearch = false }; + var query2 = new SearchQuery { KeyWords = "kw-folderName:my @@ -2541,10 +2523,9 @@ private void AddFoldersAndFiles() { "tuesday.jpg", "My { { "folderName", file.Value.ToLowerInvariant() } } + Keywords = new Dictionary { { "folderName", file.Value.ToLowerInvariant() } }, }; - _internalSearchController.AddSearchDocument(doc); + this._internalSearchController.AddSearchDocument(doc); } - _internalSearchController.Commit(); + this._internalSearchController.Commit(); } - - [Test] - public void SearchController_Scope_By_FolderName() - { - //Arrange - AddFoldersAndFiles(); - - //Act - var result1 = SearchForKeyword("kw-folderName:Images/*"); - var result2 = SearchForKeyword("kw-folderName:Images/DNN/*"); - var result3 = SearchForKeywordWithWildCard("kw-folderName:Images/* AND spacer"); - - //Assert - Assert.AreEqual(5, result1.TotalHits); - Assert.AreEqual(2, result2.TotalHits); - Assert.AreEqual(1, result3.TotalHits); - } - - [Test] - public void SearchController_Scope_By_FolderName_With_Spaces() - { - //Arrange - AddFoldersAndFiles(); - - //Act - Space is replaced by < - var query1 = new SearchQuery {KeyWords = "kw-folderName:Images/*", SearchTypeIds = new[] { OtherSearchTypeId }, WildCardSearch = false }; - var query2 = new SearchQuery { KeyWords = "kw-folderName:my() { { NumericKey1, NumericValue50 } }, SearchTypeIds = new List { OtherSearchTypeId }, - WildCardSearch = false + WildCardSearch = false, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(NumericValue50, search.Results[0].NumericKeys[NumericKey1]); } @@ -2945,131 +2869,117 @@ public void SearchController_GetResult_Works_With_Custom_Numeric_Querirs() [Test] public void SearchController_GetResult_Works_With_CustomKeyword_Querirs() { + this.AddDocumentsWithKeywords(); - AddDocumentsWithKeywords(); - - //Act + // Act var query = new SearchQuery { CustomKeywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, SearchTypeIds = new List { OtherSearchTypeId }, - WildCardSearch = false + WildCardSearch = false, }; - var search = _searchController.SiteSearch(query); + var search = this._searchController.SiteSearch(query); - //Assert + // Assert Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(KeyWord1Value, search.Results[0].Keywords[KeyWord1Name]); - } - - #endregion - - #region Leading Wildcard search tests - - [Test] - public void SearchController_EnableLeadingWildcard_Should_Not_Return_Results_When_Property_Is_False() - { - _mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); - - //Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - - //Act - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.Commit(); - - - var result = SearchForKeyword("rld", OtherSearchTypeId, true, false); - - //Assert - Assert.AreEqual(0, result.TotalHits); - } - - [Test] - public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_True() - { - _mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); - - //Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - - //Act - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.Commit(); - + } + + [Test] + public void SearchController_EnableLeadingWildcard_Should_Not_Return_Results_When_Property_Is_False() + { + this._mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); - var result = SearchForKeyword("rld", OtherSearchTypeId, true, true); + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - //Assert - Assert.AreEqual(1, result.TotalHits); - Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); - } + // Act + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.Commit(); + + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); - [Test] - public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_False_But_Host_Setting_Is_True() - { - _mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("Y"); + // Assert + Assert.AreEqual(0, result.TotalHits); + } - //Arrange - var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; - var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "" }; + [Test] + public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_True() + { + this._mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("N"); - //Act - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.Commit(); + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + // Act + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.Commit(); + + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, true); - var result = SearchForKeyword("rld", OtherSearchTypeId, true, false); + // Assert + Assert.AreEqual(1, result.TotalHits); + Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); + } - //Assert - Assert.AreEqual(1, result.TotalHits); - Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); - } + [Test] + public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Property_Is_False_But_Host_Setting_Is_True() + { + this._mockHostController.Setup(c => c.GetString("Search_AllowLeadingWildcard", It.IsAny())).Returns("Y"); - #endregion + // Arrange + var doc1 = new SearchDocument { UniqueKey = "key01", Title = "cow is gone", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc2 = new SearchDocument { UniqueKey = "key02", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; + var doc3 = new SearchDocument { UniqueKey = "key03", Title = "I'm here", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = string.Empty }; - #region stop-words tests + // Act + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.Commit(); + + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); + // Assert + Assert.AreEqual(1, result.TotalHits); + Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); + } + [Test] public void SearchController_Search_StopWords_Works() { - //Arrange - var added = AddStandardSearchDocs(); - _internalSearchController.Commit(); + // Arrange + var added = this.AddStandardSearchDocs(); + this._internalSearchController.Commit(); - //Act - var search = SearchForKeywordInModule("the"); + // Act + var search = this.SearchForKeywordInModule("the"); - //Assert + // Assert // the word "the" is ignored in all languages except es-ES Assert.AreEqual(1, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - //Act - search = SearchForKeywordInModule("over"); + // Act + search = this.SearchForKeywordInModule("over"); - //Assert + // Assert // we won't find "over" in neutral, en-US, and en-CA documents, but will find it in the es-ES and it-IT documents. Assert.AreEqual(2, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - //Act - search = SearchForKeywordInModule("los"); + // Act + search = this.SearchForKeywordInModule("los"); - //Assert + // Assert // we won't find "los" in the es-ES document. Assert.AreEqual(0, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - } - #endregion - + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs index 9b1b191e639..35e21b0e764 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs @@ -1,30 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; -using System; -using System.Data; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Search { + using System; + using System.Data; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Testing various aspects of SearchController + /// Testing various aspects of SearchController. /// [TestFixture] public class SearchHelperTests - { - - #region constants - + { private const int OtherSearchTypeId = 2; private const string TermDNN = "DNN"; private const string TermDotNetNuke = "DotnetNuke"; @@ -34,43 +32,57 @@ public class SearchHelperTests private const string TermLeap = "Leap"; private const string TermHop = "Hop"; private const int PortalId0 = 0; - private const string CultureEnUs = "en-US"; - - #endregion - - #region Private Properties - + private const string CultureEnUs = "en-US"; private Mock _dataProvider; private Mock _cachingProvider; - private SearchHelperImpl _searchHelper; - - #endregion - - #region Set Up - + private SearchHelperImpl _searchHelper; + [SetUp] public void SetUp() { ComponentFactory.Container = new SimpleContainer(); - _cachingProvider = MockComponentProvider.CreateDataCacheProvider(); - _dataProvider = MockComponentProvider.CreateDataProvider(); - SetupDataProvider(); - _searchHelper = new SearchHelperImpl(); + this._cachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + this.SetupDataProvider(); + this._searchHelper = new SearchHelperImpl(); DataCache.ClearCache(); + } + + [Test] + public void SearchHelper_GetSynonyms_Two_Terms_Returns_Correct_Results() + { + // Arrange + + // Act + var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermDNN).ToArray(); + + // Assert + Assert.AreEqual(1, synonyms.Count()); + Assert.AreEqual(TermDotNetNuke.ToLowerInvariant(), synonyms[0]); } - #endregion + [Test] + public void SearchHelper_GetSynonyms_Three_Terms_Returns_Correct_Results() + { + // Arrange - #region Private Methods + // Act + var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermHop).ToArray(); + // Assert + Assert.AreEqual(2, synonyms.Count()); + Assert.AreEqual(TermJump.ToLowerInvariant(), synonyms[0]); + Assert.AreEqual(TermLeap.ToLowerInvariant(), synonyms[1]); + } + private void SetupDataProvider() { - //Standard DataProvider Path for Logging - _dataProvider.Setup(d => d.GetProviderPath()).Returns(""); + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - _dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); + this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - _dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(GetPortalSettingsCallBack); + this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); var dataTable = new DataTable("SynonymsGroups"); var pkId = dataTable.Columns.Add("SynonymsGroupID", typeof(int)); @@ -83,13 +95,13 @@ private void SetupDataProvider() dataTable.PrimaryKey = new[] { pkId }; - //Create some test data + // Create some test data var now = DateTime.Now; dataTable.Rows.Add(1, string.Join(",", new[] { TermDNN, TermDotNetNuke }), 1, now, 1, now, 0); dataTable.Rows.Add(2, string.Join(",", new[] { TermLaptop, TermNotebook }), 1, now, 1, now, 0); dataTable.Rows.Add(3, string.Join(",", new[] { TermJump, TermLeap, TermHop }), 1, now, 1, now, 0); - _dataProvider.Setup(x => x.GetAllSynonymsGroups(0, It.IsAny())).Returns(dataTable.CreateDataReader()); + this._dataProvider.Setup(x => x.GetAllSynonymsGroups(0, It.IsAny())).Returns(dataTable.CreateDataReader()); } private IDataReader GetPortalSettingsCallBack(int portalId, string culture) @@ -98,7 +110,7 @@ private IDataReader GetPortalSettingsCallBack(int portalId, string culture) var cols = new string[] { - "SettingName","SettingValue","CreatedByUserID","CreatedOnDate","LastModifiedByUserID","LastModifiedOnDate","CultureCode" + "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", }; foreach (var col in cols) @@ -113,7 +125,7 @@ private IDataReader GetPortalSettingsCallBack(int portalId, string culture) private IDataReader GetPortalsCallBack(string culture) { - return GetPortalCallBack(PortalId0, CultureEnUs); + return this.GetPortalCallBack(PortalId0, CultureEnUs); } private IDataReader GetPortalCallBack(int portalId, string culture) @@ -125,7 +137,7 @@ private IDataReader GetPortalCallBack(int portalId, string culture) "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode" + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", }; foreach (var col in cols) @@ -137,281 +149,245 @@ private IDataReader GetPortalCallBack(int portalId, string culture) table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); return table.CreateDataReader(); - } - - #endregion - - #region Synonyms Tests - - [Test] - public void SearchHelper_GetSynonyms_Two_Terms_Returns_Correct_Results() - { - //Arrange - - //Act - var synonyms = _searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermDNN).ToArray(); - - //Assert - Assert.AreEqual(1, synonyms.Count()); - Assert.AreEqual(TermDotNetNuke.ToLowerInvariant(), synonyms[0]); - } - - [Test] - public void SearchHelper_GetSynonyms_Three_Terms_Returns_Correct_Results() - { - //Arrange - - //Act - var synonyms = _searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermHop).ToArray(); - - //Assert - Assert.AreEqual(2, synonyms.Count()); - Assert.AreEqual(TermJump.ToLowerInvariant(), synonyms[0]); - Assert.AreEqual(TermLeap.ToLowerInvariant(), synonyms[1]); - } - - #endregion - - #region Rephrasing Search Text Tests - + } + [Test] public void SearchHelper_Rephrase_NoWildCardButExact_1() { - //Arrange + // Arrange const string inPhrase = "\"brown fox\""; const string expected = inPhrase; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, false); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_NoWildCardButExact_2() { - //Arrange + // Arrange const string inPhrase = "\"brown fox\" -\"(Lazy) dog\" jumps"; const string expected = inPhrase; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, false); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_NoWildCardNoExact() { - //Arrange + // Arrange const string inPhrase = "(brown) OR (fox AND dog) +jumbs"; const string expected = inPhrase; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, false); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, false); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_0() { - //Arrange + // Arrange const string inPhrase = "fox dog"; const string expected = "(fox OR fox*) (dog OR dog*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_1() { - //Arrange + // Arrange const string inPhrase = "(lazy-dog)"; const string expected = "(lazy-dog OR lazy-dog*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_2() { - //Arrange + // Arrange const string inPhrase = "fox (dog)"; const string expected = "(fox OR fox*) (dog OR dog*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_3() { - //Arrange + // Arrange const string inPhrase = "(dog) fox"; const string expected = "(dog OR dog*) (fox OR fox*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_4() { - //Arrange + // Arrange const string inPhrase = "brown fox (lazy) dog"; const string expected = "(brown OR brown*) (fox OR fox*) (lazy OR lazy*) (dog OR dog*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_5() { - //Arrange + // Arrange const string inPhrase = "(brown fox) lazy dog"; const string expected = "((brown OR brown*) (fox OR fox*)) (lazy OR lazy*) (dog OR dog*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_6() { - //Arrange + // Arrange const string inPhrase = "brown fox (lazy dog)"; const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) (dog OR dog*))"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_7() { - //Arrange + // Arrange const string inPhrase = "brown fox (lazy AND dog)"; const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) AND (dog OR dog*))"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardNoExact_8() { - //Arrange + // Arrange const string inPhrase = "brown fox (lazy and dog)"; const string expected = "(brown OR brown*) (fox OR fox*) ((lazy OR lazy*) (and OR and*) (dog OR dog*))"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardWithExact_1() { - //Arrange + // Arrange const string inPhrase = "\"brown fox\""; const string expected = inPhrase; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardWithExact_2() { - //Arrange + // Arrange const string inPhrase = "\"brown fox\" dog"; const string expected = "\"brown fox\" (dog OR dog*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardWithExact_3() { - //Arrange + // Arrange const string inPhrase = "The +\"brown fox\" -\"Lazy dog\" jumps"; const string expected = "(The OR The*) +\"brown fox\" -\"Lazy dog\" (jumps OR jumps*)"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] public void SearchHelper_Rephrase_WildCardWithTilde_4() { - //Arrange + // Arrange const string inPhrase = "dog jump~2"; const string expected = "(dog OR dog*) jump~2"; - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); } [Test] - //Arrange + + // Arrange [TestCase("Cäu", "(Cau OR Cau*)")] [TestCase("Cäutätörül", "(Cautatorul OR Cautatorul*)")] [TestCase("Ãbcdef", "(Abcdef OR Abcdef*)")] public void SearchHelper_Rephrase_AccentedCharsReplaced_Replaced(string inPhrase, string expected) { - //Act - var analyzed = _searchHelper.RephraseSearchText(inPhrase, true); + // Act + var analyzed = this._searchHelper.RephraseSearchText(inPhrase, true); - //Assert + // Assert Assert.AreEqual(expected, analyzed); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs index 706733484b1..ae872d4a358 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs @@ -1,252 +1,247 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Services.Search.Internals; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Search { + using System; + using System.Collections.Generic; + + using DotNetNuke.Services.Search.Internals; + using NUnit.Framework; + [TestFixture] public class SearchQueryStringParserTests - { - #region GetLastModifiedDate Method Tests + { public void GetLastModifiedDate_ShouldReturnOneDayAgoDate_WhenKeywordsHaveAfterDay() { - //Arrange + // Arrange const string keywords = "mysearch after:day"; var outputKeywords = string.Empty; - //Act + // Act var date = SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(DateTime.UtcNow.AddDays(-1).Date, date.Date); } [Test] public void GetLastModifiedDate_ShouldReturnOneWeekAgoDate_WhenKeywordsHaveAfterWeek() { - //Arrange + // Arrange const string keywords = "mysearch after:week"; var outputKeywords = string.Empty; - //Act + // Act var date = SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(DateTime.UtcNow.AddDays(-7).Date, date.Date); } [Test] public void GetLastModifiedDate_ShouldReturnOneMonthAgoDate_WhenKeywordsHaveAfterMonth() { - //Arrange + // Arrange const string keywords = "mysearch after:month"; var outputKeywords = string.Empty; - //Act + // Act var date = SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(DateTime.UtcNow.AddMonths(-1).Date, date.Date); } [Test] public void GetLastModifiedDate_ShouldReturnOneQuarterAgoDate_WhenKeywordsHaveAfterQuarter() { - //Arrange + // Arrange const string keywords = "mysearch after:quarter"; var outputKeywords = string.Empty; - //Act + // Act var date = SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(DateTime.UtcNow.AddMonths(-3).Date, date.Date); } [Test] public void GetLastModifiedDate_ShouldReturnOneYearAgoDate_WhenKeywordsHaveAfterYear() { - //Arrange + // Arrange const string keywords = "mysearch after:year"; var outputKeywords = string.Empty; - //Act + // Act var date = SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(DateTime.UtcNow.AddYears(-1).Date, date.Date); } [Test] public void GetLastModifiedDate_ShouldReturnMinDate_WhenKeywordsDoNotHaveAfterParameter() { - //Arrange + // Arrange const string keywords = "mysearch "; var outputKeywords = string.Empty; - //Act + // Act var date = SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(DateTime.MinValue, date); } [Test] public void GetLastModifiedDate_ShouldSetOutputKeywordsEqualsToTrimmedKeywordsWithoutAfterParameter_WhenKeywordsHaveAfterParameter() { - //Arrange + // Arrange const string keywords = " mysearch [tag1][tag2][tag3] after:week "; const string expectedOutputKeywords = "mysearch [tag1][tag2][tag3]"; var outputKeywords = string.Empty; - //Act + // Act SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); } [Test] public void GetLastModifiedDate_ShouldSetOutputKeywordsEqualsToTrimmedKeywords_WhenKeywordsDoNotHaveAfterParameter() { - //Arrange + // Arrange const string keywords = " mysearch [tag1][tag2][tag3] "; const string expectedOutputKeywords = "mysearch [tag1][tag2][tag3]"; var outputKeywords = string.Empty; - //Act + // Act SearchQueryStringParser.Instance.GetLastModifiedDate(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); - } - #endregion - - #region GetSearchTypeList Method Tests + } + [Test] public void GetSearchTypeList_ShouldReturnSearchTypeList_WhenKeywordsHaveTypeParameter() { - //Arrange + // Arrange const string keywords = "mysearch type:Documents,Pages"; var expectedSearchTypeList = new List { "Documents", "Pages" }; var outputKeywords = string.Empty; - //Act + // Act var searchTypeList = SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedSearchTypeList, searchTypeList); } [Test] public void GetSearchTypeList_ShouldReturnEmptySearchTypeList_WhenKeywordsDoNotHaveTypeParameter() { - //Arrange + // Arrange const string keywords = "mysearch "; var outputKeywords = string.Empty; - //Act + // Act var searchTypeList = SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(0, searchTypeList.Count); } [Test] public void GetSearchTypeList_ShouldSetOutputKeywordsEqualsToTrimmedKeywordsWithoutTypeParameter_WhenKeywordsHaveTypeParameter() { - //Arrange + // Arrange const string keywords = " mysearch [tag1][tag2][tag3] type:Documents "; const string expectedOutputKeywords = "mysearch [tag1][tag2][tag3]"; var outputKeywords = string.Empty; - //Act + // Act SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); } [Test] public void GetSearchTypeList_ShouldSetOutputKeywordsEqualsToTrimmedKeywords_WhenKeywordsDoNotHaveTypeParameter() { - //Arrange + // Arrange const string keywords = " mysearch [tag1][tag2][tag3] "; const string expectedOutputKeywords = "mysearch [tag1][tag2][tag3]"; var outputKeywords = string.Empty; - //Act + // Act SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); - } - #endregion - - #region GetTags Method Tests + } + [Test] public void GetTags_ShouldReturnTagsList_WhenKeywordsHaveTags() { - //Arrange + // Arrange const string keywords = "mysearch [tag][tag2]"; var expectedTagsList = new List { "tag", "tag2" }; var outputKeywords = string.Empty; - //Act + // Act var tagsList = SearchQueryStringParser.Instance.GetTags(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedTagsList, tagsList); } [Test] public void GetTags_ShouldReturnEmptyTagList_WhenKeywordsDoNotHaveTags() { - //Arrange + // Arrange const string keywords = "mysearch "; var outputKeywords = string.Empty; - //Act + // Act var tagsList = SearchQueryStringParser.Instance.GetTags(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(0, tagsList.Count); } [Test] public void GetTags_ShouldSetOutputKeywordsEqualsToTrimmedKeywordsWithoutTags_WhenKeywordsHaveTags() { - //Arrange + // Arrange const string keywords = "mysearch [tag][tag2][tag3]"; const string expectedOutputKeywords = "mysearch"; var outputKeywords = string.Empty; - //Act + // Act SearchQueryStringParser.Instance.GetTags(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); } [Test] public void GetTags_ShouldSetOutputKeywordsEqualsToTrimmedKeywords_WhenKeywordsDoNotHaveTags() { - //Arrange + // Arrange const string keywords = " mysearch after:week "; const string expectedOutputKeywords = "mysearch after:week"; var outputKeywords = string.Empty; - //Act + // Act SearchQueryStringParser.Instance.GetTags(keywords, out outputKeywords); - //Assert + // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); - } - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs index ff90215ff8a..4e314d843a5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs @@ -1,80 +1,72 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Entities.Users.Social.Data; -using DotNetNuke.Entities.Users.Social.Internal; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Controllers.Social { - /// - /// Testing various aspects of RelationshipController - /// - [TestFixture] - public class RelationshipControllerTests - { - #region Private Properties - + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Entities.Users.Social.Data; + using DotNetNuke.Entities.Users.Social.Internal; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + + /// + /// Testing various aspects of RelationshipController. + /// + [TestFixture] + public class RelationshipControllerTests + { private Mock mockCachingProvider; - private Mock _portalController; + private Mock _portalController; private Mock _portalGroupController; private DataTable dtRelationshipTypes; private DataTable dtRelationships; private DataTable dtUserRelationships; - private DataTable dtUserRelationshipPreferences; - - #endregion - - #region Set Up - - [SetUp] - public void SetUp() - { + private DataTable dtUserRelationshipPreferences; + + [SetUp] + public void SetUp() + { ComponentFactory.Container = new SimpleContainer(); var mockDataProvider = MockComponentProvider.CreateDataProvider(); - mockDataProvider.Setup(dp => dp.GetProviderPath()).Returns(""); + mockDataProvider.Setup(dp => dp.GetProviderPath()).Returns(string.Empty); - mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this.mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); MockComponentProvider.CreateEventLogController(); - _portalController = new Mock(); - PortalController.SetTestableInstance(_portalController.Object); + this._portalController = new Mock(); + PortalController.SetTestableInstance(this._portalController.Object); + + this._portalGroupController = new Mock(); + PortalGroupController.RegisterInstance(this._portalGroupController.Object); - _portalGroupController = new Mock(); - PortalGroupController.RegisterInstance(_portalGroupController.Object); - var mockHostController = new Mock(); mockHostController.Setup(c => c.GetString("PerformanceSetting")).Returns("0"); HostController.RegisterInstance(mockHostController.Object); var mockUserController = new Mock(); - mockUserController.Setup(c => c.GetCurrentUserInfo()).Returns(new UserInfo() { UserID = 1}); + mockUserController.Setup(c => c.GetCurrentUserInfo()).Returns(new UserInfo() { UserID = 1 }); UserController.SetTestableInstance(mockUserController.Object); - CreateLocalizationProvider(); + this.CreateLocalizationProvider(); - SetupDataTables(); - } + this.SetupDataTables(); + } [TearDown] public void TearDown() @@ -82,84 +74,75 @@ public void TearDown() ComponentFactory.Container = null; PortalController.ClearInstance(); UserController.ClearInstance(); - } - - #endregion - - #region Constructor Tests - + } + [Test] public void RelationshipController_Constructor_Throws_On_Null_DataService() { - //Arrange + // Arrange var mockEventLogController = new Mock(); - //Act, Assert + // Act, Assert Assert.Throws(() => new RelationshipControllerImpl(null, mockEventLogController.Object)); } [Test] public void RelationshipController_Constructor_Throws_On_Null_EventLogController() { - //Arrange + // Arrange var mockDataService = new Mock(); - //Act, Assert + // Act, Assert Assert.Throws(() => new RelationshipControllerImpl(mockDataService.Object, null)); - } - - #endregion - - #region RelationshipType Tests - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteRelationshipType_Throws_On_Null_RelationshipType() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.DeleteRelationshipType(null); } [Test] public void RelationshipController_DeleteRelationshipType_Calls_DataService() { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID - }; + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; - //Act + // Act relationshipController.DeleteRelationshipType(relationshipType); - //Assert + // Assert mockDataService.Verify(d => d.DeleteRelationshipType(Constants.SOCIAL_FollowerRelationshipTypeID)); } [Test] public void RelationshipController_DeleteRelationshipType_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); - var relationshipController = CreateRelationshipController(mockEventLogController); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - Name = Constants.SOCIAL_RelationshipTypeName - }; - - - //Act + this.CreateLocalizationProvider(); + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + Name = Constants.SOCIAL_RelationshipTypeName, + }; + + // Act relationshipController.DeleteRelationshipType(relationshipType); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_RelationshipType_Deleted, Constants.SOCIAL_RelationshipTypeName, Constants.SOCIAL_FollowerRelationshipTypeID); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); } @@ -167,46 +150,46 @@ public void RelationshipController_DeleteRelationshipType_Calls_EventLogControll [Test] public void RelationshipController_DeleteRelationshipType_Calls_DataCache_RemoveCache() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; - //Act + // Act relationshipController.DeleteRelationshipType(relationshipType); - //Assert - mockCachingProvider.Verify(e => e.Remove(cacheKey)); + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); } [Test] public void RelationshipController_GetAllRelationshipTypes_Calls_DataService() { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationshipTypes = relationshipController.GetAllRelationshipTypes(); - //Assert + // Assert mockDataService.Verify(d => d.GetAllRelationshipTypes()); } [Test] public void RelationshipController_GetRelationshipType_Calls_DataService_If_Not_Cached() { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationshipTypes = relationshipController.GetRelationshipType(Constants.SOCIAL_FriendRelationshipTypeID); - //Assert + // Assert mockDataService.Verify(d => d.GetAllRelationshipTypes()); } @@ -215,28 +198,28 @@ public void RelationshipController_GetRelationshipType_Calls_DataService_If_Not_ [TestCase(Constants.SOCIAL_FollowerRelationshipTypeID)] public void RelationshipController_GetRelationshipType_Returns_RelationshipType_For_Valid_ID(int relationshipTypeId) { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationshipType = relationshipController.GetRelationshipType(relationshipTypeId); - //Assert + // Assert Assert.AreEqual(relationshipTypeId, relationshipType.RelationshipTypeId); } [Test] public void RelationshipController_GetRelationshipType_Returns_Null_For_InValid_ID() { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationshipType = relationshipController.GetRelationshipType(Constants.SOCIAL_InValidRelationshipType); - //Assert + // Assert Assert.IsNull(relationshipType); } @@ -244,50 +227,50 @@ public void RelationshipController_GetRelationshipType_Returns_Null_For_InValid_ [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_SaveRelationshipType_Throws_On_Null_RelationshipType() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.SaveRelationshipType(null); } [Test] public void RelationshipController_SaveRelationshipType_Calls_DataService() { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID - }; + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; - //Act + // Act relationshipController.SaveRelationshipType(relationshipType); - //Assert + // Assert mockDataService.Verify(d => d.SaveRelationshipType(relationshipType, It.IsAny())); } [Test] public void RelationshipController_SaveRelationshipType_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); + this.CreateLocalizationProvider(); - var relationshipController = CreateRelationshipController(mockEventLogController); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - Name = Constants.SOCIAL_RelationshipTypeName - }; + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + Name = Constants.SOCIAL_RelationshipTypeName, + }; - //Act + // Act relationshipController.SaveRelationshipType(relationshipType); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_RelationshipType_Updated, Constants.SOCIAL_RelationshipTypeName); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); } @@ -295,73 +278,69 @@ public void RelationshipController_SaveRelationshipType_Calls_EventLogController [Test] public void RelationshipController_SaveRelationshipType_Calls_DataCache_RemoveCache() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; - //Act + // Act relationshipController.SaveRelationshipType(relationshipType); - //Assert - mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - - #endregion - - #region Relationship Tests - + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteRelationship_Throws_On_Null_Relationship() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.DeleteRelationship(null); } [Test] public void RelationshipController_DeleteRelationship_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); - var relationshipController = CreateRelationshipController(mockDataService); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID - }; + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + }; - //Act + // Act relationshipController.DeleteRelationship(relationship); - //Assert + // Assert mockDataService.Verify(d => d.DeleteRelationship(Constants.SOCIAL_FollowerRelationshipID)); } [Test] public void RelationshipController_DeleteRelationship_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); + this.CreateLocalizationProvider(); - var relationshipController = CreateRelationshipController(mockEventLogController); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - Name = Constants.SOCIAL_RelationshipName - }; + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + Name = Constants.SOCIAL_RelationshipName, + }; - //Act + // Act relationshipController.DeleteRelationship(relationship); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_Relationship_Deleted, Constants.SOCIAL_RelationshipName, Constants.SOCIAL_FollowerRelationshipID); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); } @@ -369,22 +348,22 @@ public void RelationshipController_DeleteRelationship_Calls_EventLogController_A [Test] public void RelationshipController_DeleteRelationship_Calls_DataCache_RemoveCache() { - //Arrange + // Arrange var portalId = 1; - var relationshipController = CreateRelationshipController(); + var relationshipController = this.CreateRelationshipController(); var cacheKey = CachingProvider.GetCacheKey(string.Format(DataCache.RelationshipByPortalIDCacheKey, portalId)); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - PortalId = portalId, - UserId = -1 - }; - - //Act + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + PortalId = portalId, + UserId = -1, + }; + + // Act relationshipController.DeleteRelationship(relationship); - //Assert - mockCachingProvider.Verify(e => e.Remove(cacheKey)); + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); } [Test] @@ -392,57 +371,58 @@ public void RelationshipController_DeleteRelationship_Calls_DataCache_RemoveCach [TestCase(Constants.SOCIAL_FollowerRelationshipID, DefaultRelationshipTypes.Followers)] public void RelationshipController_GetRelationship_Returns_Relationship_For_Valid_ID(int relationshipId, DefaultRelationshipTypes defaultType) { - //Arrange + // Arrange var mockDataService = new Mock(); - dtRelationships.Clear(); - dtRelationships.Rows.Add(relationshipId, defaultType, defaultType.ToString(), defaultType.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); - mockDataService.Setup(md => md.GetRelationship(relationshipId)).Returns(dtRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + this.dtRelationships.Clear(); + this.dtRelationships.Rows.Add(relationshipId, defaultType, defaultType.ToString(), defaultType.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); + mockDataService.Setup(md => md.GetRelationship(relationshipId)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationship = relationshipController.GetRelationship(relationshipId); - //Assert + // Assert Assert.AreEqual(relationshipId, relationship.RelationshipId); } [Test] public void RelationshipController_GetRelationship_Returns_Null_For_InValid_ID() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtRelationships.Clear(); - mockDataService.Setup(md => md.GetRelationship(It.IsAny())).Returns(dtRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + this.dtRelationships.Clear(); + mockDataService.Setup(md => md.GetRelationship(It.IsAny())).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationship = relationshipController.GetRelationship(Constants.SOCIAL_InValidRelationship); - //Assert + // Assert Assert.IsNull(relationship); } [Test] public void RelationshipController_GetRelationshipsByUserID_Returns_List_Of_Relationships_For_Valid_User() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtRelationships.Clear(); - for (int i = 1; i <= 5; i ++) + this.dtRelationships.Clear(); + for (int i = 1; i <= 5; i++) { - dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), - DefaultRelationshipTypes.Friends.ToString(), - Constants.PORTAL_Zero, - Constants.USER_ValidId, + this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), + DefaultRelationshipTypes.Friends.ToString(), + Constants.PORTAL_Zero, + Constants.USER_ValidId, RelationshipStatus.None); } - mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_ValidId)).Returns(dtRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + + mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_ValidId)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationships = relationshipController.GetRelationshipsByUserId(Constants.USER_ValidId); - //Assert + // Assert Assert.IsInstanceOf>(relationships); Assert.AreEqual(5, relationships.Count); } @@ -450,16 +430,16 @@ public void RelationshipController_GetRelationshipsByUserID_Returns_List_Of_Rela [Test] public void RelationshipController_GetRelationshipsByUserID_Returns_EmptyList_Of_Relationships_For_InValid_User() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtRelationships.Clear(); - mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_InValidId)).Returns(dtRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + this.dtRelationships.Clear(); + mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_InValidId)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var relationships = relationshipController.GetRelationshipsByUserId(Constants.USER_InValidId); - //Assert + // Assert Assert.IsInstanceOf>(relationships); Assert.AreEqual(0, relationships.Count); } @@ -467,27 +447,28 @@ public void RelationshipController_GetRelationshipsByUserID_Returns_EmptyList_Of [Test] public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Relationships_For_Valid_Portal() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtRelationships.Clear(); + this.dtRelationships.Clear(); for (int i = 1; i <= 5; i++) { - dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), + this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), DefaultRelationshipTypes.Friends.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); } - mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(dtRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - //Act + // Act var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Zero); - //Assert + // Assert Assert.IsInstanceOf>(relationships); Assert.AreEqual(5, relationships.Count); } @@ -495,30 +476,31 @@ public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Re [Test] public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Relationships_For_Valid_Portal_When_Portal_Is_In_Group() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtRelationships.Clear(); + this.dtRelationships.Clear(); for (int i = 1; i <= 5; i++) { - dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), + this.dtRelationships.Rows.Add(i, DefaultRelationshipTypes.Friends, DefaultRelationshipTypes.Friends.ToString(), DefaultRelationshipTypes.Friends.ToString(), Constants.PORTAL_Zero, Constants.USER_Null, RelationshipStatus.None); } - mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(dtRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Constants.PORTALGROUP_ValidPortalGroupId); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Zero)).Returns(mockPortalInfo); - List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); - _portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); + List portalGroups = new List() { CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero) }; // CreatePortalGroupInfo(Constants.PORTALGROUP_ValidPortalGroupId, Constants.PORTAL_Zero); + this._portalGroupController.Setup(pgc => pgc.GetPortalGroups()).Returns(portalGroups); - //Act + // Act var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Zero); - //Assert + // Assert Assert.IsInstanceOf>(relationships); Assert.AreEqual(5, relationships.Count); } @@ -526,19 +508,19 @@ public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Re [Test] public void RelationshipController_GetRelationshipsByPortalID_Returns_EmptyList_Of_Relationships_For_InValid_Portal() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtRelationships.Clear(); - mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Null)).Returns(dtRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + this.dtRelationships.Clear(); + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Null)).Returns(this.dtRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Null, Null.NullInteger); - _portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Null)).Returns(mockPortalInfo); + this._portalController.Setup(pc => pc.GetPortal(Constants.PORTAL_Null)).Returns(mockPortalInfo); - //Act + // Act var relationships = relationshipController.GetRelationshipsByPortalId(Constants.PORTAL_Null); - //Assert + // Assert Assert.IsInstanceOf>(relationships); Assert.AreEqual(0, relationships.Count); } @@ -547,50 +529,50 @@ public void RelationshipController_GetRelationshipsByPortalID_Returns_EmptyList_ [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_SaveRelationship_Throws_On_Null_Relationship() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.SaveRelationship(null); } [Test] public void RelationshipController_SaveRelationship_Calls_DataService() { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); - var relationship = new Relationship - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID - }; + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var relationship = new Relationship + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + }; - //Act + // Act relationshipController.SaveRelationship(relationship); - //Assert + // Assert mockDataService.Verify(d => d.SaveRelationship(relationship, It.IsAny())); } [Test] public void RelationshipController_SaveRelationship_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); + this.CreateLocalizationProvider(); - var relationshipController = CreateRelationshipController(mockEventLogController); - var relationship = new Relationship - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - Name = Constants.SOCIAL_RelationshipName - }; + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var relationship = new Relationship + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + Name = Constants.SOCIAL_RelationshipName, + }; - //Act + // Act relationshipController.SaveRelationship(relationship); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_Relationship_Updated, Constants.SOCIAL_RelationshipName); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); } @@ -598,75 +580,70 @@ public void RelationshipController_SaveRelationship_Calls_EventLogController_Add [Test] public void RelationshipController_SaveRelationship_Calls_DataCache_RemoveCache() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); var relationshipType = new RelationshipType() { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, }; - //Act + // Act relationshipController.SaveRelationshipType(relationshipType); - //Assert - mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - - #endregion - - #region UserRelationship Tests - + // Assert + this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteUserRelationship_Throws_On_Null_UserRelationship() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.DeleteUserRelationship(null); } [Test] public void RelationshipController_DeleteUserRelationship_Calls_DataService() { - //Arrange - var mockDataService = CreateMockDataServiceWithRelationshipTypes(); - var relationshipController = CreateRelationshipController(mockDataService); - var userRelationship = new UserRelationship() - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11 - }; + // Arrange + var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); + var relationshipController = this.CreateRelationshipController(mockDataService); + var userRelationship = new UserRelationship() + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + }; - //Act + // Act relationshipController.DeleteUserRelationship(userRelationship); - //Assert + // Assert mockDataService.Verify(d => d.DeleteUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11)); } [Test] public void RelationshipController_DeleteUserRelationship_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); - - var relationshipController = CreateRelationshipController(mockEventLogController); - var userRelationship = new UserRelationship - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - UserId = Constants.USER_ElevenId, - RelatedUserId = Constants.USER_TenId - }; - - - //Act + this.CreateLocalizationProvider(); + + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var userRelationship = new UserRelationship + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + UserId = Constants.USER_ElevenId, + RelatedUserId = Constants.USER_TenId, + }; + + // Act relationshipController.DeleteUserRelationship(userRelationship); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_UserRelationship_Deleted, Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_ElevenId, Constants.USER_TenId); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); } @@ -676,55 +653,56 @@ public void RelationshipController_DeleteUserRelationship_Calls_EventLogControll [TestCase(Constants.SOCIAL_UserRelationshipIDUser12User13, 12, 13)] public void RelationshipController_GetUserRelationship_Returns_Relationship_For_Valid_ID(int userRelationshipId, int userId, int relatedUserId) { - //Arrange + // Arrange var mockDataService = new Mock(); - dtUserRelationships.Clear(); - dtUserRelationships.Rows.Add(userRelationshipId, userId, relatedUserId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); - mockDataService.Setup(md => md.GetUserRelationship(userRelationshipId)).Returns(dtUserRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + this.dtUserRelationships.Clear(); + this.dtUserRelationships.Rows.Add(userRelationshipId, userId, relatedUserId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); + mockDataService.Setup(md => md.GetUserRelationship(userRelationshipId)).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var userRelationship = relationshipController.GetUserRelationship(userRelationshipId); - //Assert + // Assert Assert.AreEqual(userRelationshipId, userRelationship.UserRelationshipId); } [Test] public void RelationshipController_GetUserRelationship_Returns_Null_For_InValid_ID() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtUserRelationships.Clear(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + this.dtUserRelationships.Clear(); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var userRelationship = relationshipController.GetUserRelationship(Constants.SOCIAL_InValidUserRelationship); - //Assert + // Assert Assert.IsNull(userRelationship); } [Test] public void RelationshipController_GetUserRelationships_Returns_List_Of_UserRelationships_For_Valid_User() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtUserRelationships.Clear(); + this.dtUserRelationships.Clear(); for (int i = 1; i <= 5; i++) { - dtUserRelationships.Rows.Add(i, Constants.USER_ValidId, Constants.USER_TenId, + this.dtUserRelationships.Rows.Add(i, Constants.USER_ValidId, Constants.USER_TenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); } - mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_ValidId)).Returns(dtUserRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + + mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_ValidId)).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act - var user = new UserInfo {UserID = Constants.USER_ValidId}; + // Act + var user = new UserInfo { UserID = Constants.USER_ValidId }; var userRelationships = relationshipController.GetUserRelationships(user); - //Assert + // Assert Assert.IsInstanceOf>(userRelationships); Assert.AreEqual(5, userRelationships.Count); } @@ -732,133 +710,127 @@ public void RelationshipController_GetUserRelationships_Returns_List_Of_UserRela [Test] public void RelationshipController_GetUserRelationships_Returns_EmptyList_Of_UserRelationships_For_InValid_User() { - //Arrange + // Arrange var mockDataService = new Mock(); - dtUserRelationships.Clear(); + this.dtUserRelationships.Clear(); - mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_InValidId)).Returns(dtUserRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_InValidId)).Returns(this.dtUserRelationships.CreateDataReader()); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var user = new UserInfo { UserID = Constants.USER_InValidId }; var userRelationships = relationshipController.GetUserRelationships(user); - //Assert + // Assert Assert.IsInstanceOf>(userRelationships); Assert.AreEqual(0, userRelationships.Count); } - - + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_SaveUserRelationship_Throws_On_Null_UserRelationship() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.SaveUserRelationship(null); } [Test] public void RelationshipController_SaveUserRelationship_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); - var relationshipController = CreateRelationshipController(mockDataService); - var userRelationship = new UserRelationship() - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11 - }; + var relationshipController = this.CreateRelationshipController(mockDataService); + var userRelationship = new UserRelationship() + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + }; - //Act + // Act relationshipController.SaveUserRelationship(userRelationship); - //Assert + // Assert mockDataService.Verify(d => d.SaveUserRelationship(userRelationship, It.IsAny())); } [Test] public void RelationshipController_SaveUserRelationship_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.SaveUserRelationship(It.IsAny(), It.IsAny())) .Returns(Constants.SOCIAL_UserRelationshipIDUser10User11); var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); + this.CreateLocalizationProvider(); var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - var userRelationship = new UserRelationship - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - UserId = Constants.USER_ElevenId, - RelatedUserId = Constants.USER_TenId - }; - - - //Act + var userRelationship = new UserRelationship + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + UserId = Constants.USER_ElevenId, + RelatedUserId = Constants.USER_TenId, + }; + + // Act relationshipController.SaveUserRelationship(userRelationship); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_UserRelationship_Updated, Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_ElevenId, Constants.USER_TenId); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - #endregion - - #region UserRelationshipPreference Tests - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteUserRelationshipPreference_Throws_On_Null_UserRelationshipPreference() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.DeleteUserRelationshipPreference(null); } [Test] public void RelationshipController_DeleteUserRelationshipPreference_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); - var relationshipController = CreateRelationshipController(mockDataService); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11 - }; + var relationshipController = this.CreateRelationshipController(mockDataService); + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + }; - //Act + // Act relationshipController.DeleteUserRelationshipPreference(preference); - //Assert + // Assert mockDataService.Verify(d => d.DeleteUserRelationshipPreference(Constants.SOCIAL_PrefereceIDForUser11)); } [Test] public void RelationshipController_DeleteUserRelationshipPreference_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); - - var relationshipController = CreateRelationshipController(mockEventLogController); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID - }; + this.CreateLocalizationProvider(); + + var relationshipController = this.CreateRelationshipController(mockEventLogController); + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; - //Act + // Act relationshipController.DeleteUserRelationshipPreference(preference); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_UserRelationshipPreference_Deleted, Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); } @@ -866,32 +838,32 @@ public void RelationshipController_DeleteUserRelationshipPreference_Calls_EventL [Test] public void RelationshipController_GetUserRelationshipPreference_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetUserRelationshipPreferenceById(It.IsAny())) - .Returns(dtUserRelationshipPreferences.CreateDataReader); - var relationshipController = CreateRelationshipController(mockDataService); + .Returns(this.dtUserRelationshipPreferences.CreateDataReader); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var preference = relationshipController.GetUserRelationshipPreference(Constants.SOCIAL_PrefereceIDForUser11); - //Assert + // Assert mockDataService.Verify(d => d.GetUserRelationshipPreferenceById(Constants.SOCIAL_PrefereceIDForUser11)); } [Test] public void RelationshipController_GetUserRelationshipPreference_Overload_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.GetUserRelationshipPreference(It.IsAny(), It.IsAny())) - .Returns(dtUserRelationshipPreferences.CreateDataReader); - var relationshipController = CreateRelationshipController(mockDataService); + .Returns(this.dtUserRelationshipPreferences.CreateDataReader); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var preference = relationshipController.GetUserRelationshipPreference(Constants.USER_ValidId, Constants.SOCIAL_FriendRelationshipID); - //Assert + // Assert mockDataService.Verify(d => d.GetUserRelationshipPreference(Constants.USER_ValidId, Constants.SOCIAL_FriendRelationshipID)); } @@ -899,208 +871,196 @@ public void RelationshipController_GetUserRelationshipPreference_Overload_Calls_ [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_SaveUserRelationshipPreference_Throws_On_Null_UserRelationshipPreference() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); - //Act, Assert + // Act, Assert relationshipController.SaveUserRelationshipPreference(null); } [Test] public void RelationshipController_SaveUserRelationshipPreference_Calls_DataService() { - //Arrange + // Arrange var mockDataService = new Mock(); - var relationshipController = CreateRelationshipController(mockDataService); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID - }; - - //Act + var relationshipController = this.CreateRelationshipController(mockDataService); + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; + + // Act relationshipController.SaveUserRelationshipPreference(preference); - //Assert + // Assert mockDataService.Verify(d => d.SaveUserRelationshipPreference(preference, It.IsAny())); } [Test] public void RelationshipController_SaveUserRelationshipPreference_Calls_EventLogController_AddLog() { - //Arrange + // Arrange var mockDataService = new Mock(); mockDataService.Setup(ds => ds.SaveUserRelationshipPreference(It.IsAny(), It.IsAny())) .Returns(Constants.SOCIAL_PrefereceIDForUser11); var mockEventLogController = new Mock(); mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); - CreateLocalizationProvider(); + this.CreateLocalizationProvider(); var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID - }; - - //Act + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; + + // Act relationshipController.SaveUserRelationshipPreference(preference); - //Assert + // Assert var logContent = string.Format(Constants.LOCALIZATION_UserRelationshipPreference_Updated, Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - - #endregion - - #region Relationship Business APIs Tests - - #region InitiateUserRelationship Tests - + } + [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void RelationshipController_InitiateUserRelationship_Throws_On_Negative_RelationshipID() { - //Arrange - var relationshipController = CreateRelationshipController(); + // Arrange + var relationshipController = this.CreateRelationshipController(); var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; - var targetUser = new UserInfo {UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero}; + var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; var relationship = new Relationship(); - //Act, Assert + // Act, Assert relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - } + } - [Test] + [Test] public void RelationshipController_InitiateUserRelationship_Returns_Status_Accepted_When_Default_Relationship_Action_Is_Accepted() { - //Arrange + // Arrange var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; - - dtUserRelationships.Rows.Clear(); - dtUserRelationshipPreferences.Rows.Clear(); - //setup mock DataService + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); + + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(dtRelationshipTypes.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - //Assert + // Assert Assert.AreEqual(userRelationship.Status, RelationshipStatus.Accepted); } [Test] public void RelationshipController_InitiateUserRelationship_Returns_Status_Initiated_When_Default_Relationship_Action_Is_None() { - //Arrange + // Arrange var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.None }; - dtUserRelationships.Rows.Clear(); - dtUserRelationshipPreferences.Rows.Clear(); + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); - //setup mock DataService + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(dtRelationshipTypes.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - //Assert + // Assert Assert.AreEqual(userRelationship.Status, RelationshipStatus.Pending); } [Test] public void RelationshipController_InitiateUserRelationship_Returns_Status_Accepted_When_TargetUsers_Relationship_Action_Is_Accepted() { - //Arrange + // Arrange var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; - dtUserRelationships.Rows.Clear(); - dtUserRelationshipPreferences.Rows.Clear(); - dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.Accepted); + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.Accepted); - //setup mock DataService + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(dtRelationshipTypes.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - //Assert + // Assert Assert.AreEqual(userRelationship.Status, RelationshipStatus.Accepted); } [Test] public void RelationshipController_InitiateUserRelationship_Returns_Status_Initiated_When_TargetUsers_Relationship_Action_Is_None() { - //Arrange + // Arrange var initiatingUser = new UserInfo { UserID = Constants.USER_TenId, PortalID = Constants.PORTAL_Zero }; var targetUser = new UserInfo { UserID = Constants.USER_ElevenId, PortalID = Constants.PORTAL_Zero }; var relationship = new Relationship { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, DefaultResponse = RelationshipStatus.Accepted }; - dtUserRelationships.Rows.Clear(); - dtUserRelationshipPreferences.Rows.Clear(); - dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.None); + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Clear(); + this.dtUserRelationshipPreferences.Rows.Add(Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_TenId, Constants.USER_ElevenId, RelationshipStatus.None); - //setup mock DataService + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); - mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(dtUserRelationshipPreferences.CreateDataReader()); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(dtRelationshipTypes.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationshipPreference(It.IsAny(), It.IsAny())).Returns(this.dtUserRelationshipPreferences.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act var userRelationship = relationshipController.InitiateUserRelationship(initiatingUser, targetUser, relationship); - //Assert + // Assert Assert.AreEqual(userRelationship.Status, RelationshipStatus.Pending); - } - - #endregion - - #region UpdateRelationship Tests - - #region UserRelationshipDoesNotExist Exception - + } + [Test] [ExpectedException(typeof(UserRelationshipDoesNotExistException))] public void RelationshipController_RemoveUserRelationship_Throws_On_NonExistent_Relationship() { - //Arrange + // Arrange - //No UserRelationship between user10 and user11 - dtUserRelationships.Rows.Clear(); + // No UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); - //setup mock DataService + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act, Assert + // Act, Assert relationshipController.RemoveUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); } @@ -1108,84 +1068,91 @@ public void RelationshipController_RemoveUserRelationship_Throws_On_NonExistent_ [ExpectedException(typeof(UserRelationshipDoesNotExistException))] public void RelationshipController_AcceptRelationship_Throws_On_NonExistent_Relationship() { - //Arrange + // Arrange - //No UserRelationship between user10 and user11 - dtUserRelationships.Rows.Clear(); + // No UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); - //setup mock DataService + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act, Assert + // Act, Assert relationshipController.AcceptUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - } - - #endregion - - #region Verify Update of UserRelationship Status calls Data Layer - + } + [Test] public void RelationshipController_AcceptUserRelationship_Calls_DataService_On_Valid_RelationshipID() { - //Arrange + // Arrange - //Any UserRelationship between user10 and user11 - dtUserRelationships.Rows.Clear(); - dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); + // Any UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); - //setup mock DataService + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); mockDataService.Setup(md => md.SaveUserRelationship(It.IsAny(), It.IsAny())); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act relationshipController.AcceptUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - //Assert + // Assert mockDataService.Verify(ds => ds.SaveUserRelationship(It.IsAny(), It.IsAny())); } [Test] public void RelationshipController_RemoveUserRelationship_Calls_DataService_On_Valid_RelationshipID() { - //Arrange + // Arrange - //Any UserRelationship between user10 and user11 - dtUserRelationships.Rows.Clear(); - dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); + // Any UserRelationship between user10 and user11 + this.dtUserRelationships.Rows.Clear(); + this.dtUserRelationships.Rows.Add(Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_TenId, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); - //setup mock DataService + // setup mock DataService var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(dtUserRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetUserRelationship(It.IsAny())).Returns(this.dtUserRelationships.CreateDataReader()); mockDataService.Setup(md => md.DeleteUserRelationship(It.IsAny())); - var relationshipController = CreateRelationshipController(mockDataService); + var relationshipController = this.CreateRelationshipController(mockDataService); - //Act + // Act relationshipController.RemoveUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - //Assert + // Assert mockDataService.Verify(ds => ds.DeleteUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11)); - } - - #endregion + } - #endregion - - #endregion + private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) + { + var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; + return mockPortalInfo; + } - #region Private Methods + private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int masterPortalId) + { + var mockPortalGroupInfo = new PortalGroupInfo + { + PortalGroupId = portalGroupId, + MasterPortalId = masterPortalId, + PortalGroupName = Constants.PORTALGROUP_ValidName, + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, + }; + return mockPortalGroupInfo; + } + private Mock CreateMockDataServiceWithRelationshipTypes() { var mockDataService = new Mock(); - mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(dtRelationshipTypes.CreateDataReader()); - mockDataService.Setup(md => md.GetRelationshipsByPortalId(It.IsAny())).Returns(dtRelationships.CreateDataReader()); + mockDataService.Setup(md => md.GetAllRelationshipTypes()).Returns(this.dtRelationshipTypes.CreateDataReader()); + mockDataService.Setup(md => md.GetRelationshipsByPortalId(It.IsAny())).Returns(this.dtRelationships.CreateDataReader()); return mockDataService; } @@ -1219,7 +1186,7 @@ private void CreateLocalizationProvider() private RelationshipControllerImpl CreateRelationshipController() { var mockDataService = new Mock(); - return CreateRelationshipController(mockDataService); + return this.CreateRelationshipController(mockDataService); } private RelationshipControllerImpl CreateRelationshipController(Mock mockDataService) @@ -1236,88 +1203,65 @@ private RelationshipControllerImpl CreateRelationshipController(Mock + + stylecop.json + App.config Designer @@ -254,6 +257,10 @@ Always + + + + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs index 5c98139edbc..6ea0a60a62d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs @@ -1,26 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Modules.Settings { + using System; using System.Collections; using System.Collections.Generic; using System.Web.Caching; - + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; - + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + public abstract class BaseSettingsTests { + public readonly object[] SettingsCases = + { + new object[] { "AbcdeF#2@kfdfdfds", 9, 1.45, false, new DateTime(2015, 11, 30, 13, 45, 16), TimeSpan.Zero, TestingEnum.Value1, default(ComplexType), }, + new object[] { "Bsskk41233[]#%&", -5, -13456.456, true, DateTime.Today.AddDays(-1), new TimeSpan(1, 5, 6, 7), TestingEnum.Value2, new ComplexType(8, -10), }, + }; + protected const string SettingNamePrefix = "UnitTestSetting_"; protected const int ModuleId = 1234; protected const int TabModuleId = 653; @@ -34,36 +39,44 @@ public abstract class BaseSettingsTests protected Mock MockModuleController; protected Mock MockPortalController; + public enum TestingEnum + { + Value1, + Value2, + } + + protected static ModuleInfo GetModuleInfo => new ModuleInfo { ModuleID = ModuleId, TabModuleID = TabModuleId, TabID = TabId, PortalID = PortalId, }; + [TestFixtureSetUp] public virtual void TestFixtureSetUp() { - MockRepository = new MockRepository(MockBehavior.Default); - MockHostController = MockRepository.Create(); + this.MockRepository = new MockRepository(MockBehavior.Default); + this.MockHostController = this.MockRepository.Create(); } [SetUp] - public virtual void SetUp() + public virtual void SetUp() { - //Mock Repository and component factory - MockRepository = new MockRepository(MockBehavior.Default); + // Mock Repository and component factory + this.MockRepository = new MockRepository(MockBehavior.Default); ComponentFactory.Container = new SimpleContainer(); // Setup Mock - MockCache = MockComponentProvider.CreateNew(); - HostController.RegisterInstance(MockHostController.Object); + this.MockCache = MockComponentProvider.CreateNew(); + HostController.RegisterInstance(this.MockHostController.Object); - MockPortalController = MockRepository.Create(); - PortalController.SetTestableInstance(MockPortalController.Object); - MockModuleController = MockRepository.Create(); - ModuleController.SetTestableInstance(MockModuleController.Object); + this.MockPortalController = this.MockRepository.Create(); + PortalController.SetTestableInstance(this.MockPortalController.Object); + this.MockModuleController = this.MockRepository.Create(); + ModuleController.SetTestableInstance(this.MockModuleController.Object); // Setup mock cache - MockCacheCollection = new Hashtable(); - MockHostController.Setup(hc => hc.GetString("PerformanceSetting")).Returns("3"); - MockCache.Setup(c => c.Insert(It.IsAny(), It.IsAny())).Callback((string cacheKey, object itemToCache) => MockCacheCollection[cacheKey] = itemToCache); - MockCache.Setup(c => c.Insert(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((string cacheKey, object itemToCache, DNNCacheDependency dcd, DateTime dt, TimeSpan ts, CacheItemPriority cip, CacheItemRemovedCallback circ) => MockCacheCollection[cacheKey] = itemToCache); - MockCache.Setup(c => c.GetItem(It.IsAny())).Returns((string cacheKey) => MockCacheCollection[cacheKey]); + this.MockCacheCollection = new Hashtable(); + this.MockHostController.Setup(hc => hc.GetString("PerformanceSetting")).Returns("3"); + this.MockCache.Setup(c => c.Insert(It.IsAny(), It.IsAny())).Callback((string cacheKey, object itemToCache) => this.MockCacheCollection[cacheKey] = itemToCache); + this.MockCache.Setup(c => c.Insert(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((string cacheKey, object itemToCache, DNNCacheDependency dcd, DateTime dt, TimeSpan ts, CacheItemPriority cip, CacheItemRemovedCallback circ) => this.MockCacheCollection[cacheKey] = itemToCache); + this.MockCache.Setup(c => c.GetItem(It.IsAny())).Returns((string cacheKey) => this.MockCacheCollection[cacheKey]); } [TearDown] @@ -74,20 +87,6 @@ public virtual void TearDown() ModuleController.ClearInstance(); } - public enum TestingEnum - { - Value1, - Value2 - } - - public readonly object[] SettingsCases = - { - new object[] { "AbcdeF#2@kfdfdfds", 9, 1.45, false, new DateTime(2015, 11, 30, 13, 45, 16), TimeSpan.Zero, TestingEnum.Value1, new ComplexType(), }, - new object[] { "Bsskk41233[]#%&", -5, -13456.456, true, DateTime.Today.AddDays(-1), new TimeSpan(1,5,6,7), TestingEnum.Value2, new ComplexType(8, -10), }, - }; - - protected static ModuleInfo GetModuleInfo => new ModuleInfo { ModuleID = ModuleId, TabModuleID = TabModuleId, TabID = TabId, PortalID = PortalId, }; - protected static string CacheKey(ModuleInfo moduleInfo) => $"SettingsModule{moduleInfo.TabModuleID}"; protected static string ModuleSettingsCacheKey(ModuleInfo moduleInfo) => $"ModuleSettings{moduleInfo.TabID}"; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexType.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexType.cs index 7babbd761d0..f6e5a13a03c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexType.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexType.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Modules.Settings { public struct ComplexType @@ -13,6 +13,7 @@ public ComplexType(int x, int y) } public int X { get; private set; } + public int Y { get; private set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexTypeSerializer.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexTypeSerializer.cs index 86ec22f6fd6..fbdb37d38dd 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexTypeSerializer.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ComplexTypeSerializer.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Modules.Settings { using System; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs index 14256fa7240..7bebab06a2a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs @@ -1,32 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Settings; -using Moq; -using NUnit.Framework; -using System.Globalization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Modules.Settings { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Settings; + using Moq; + using NUnit.Framework; + [TestFixture] public class ModuleSettingsTests : BaseSettingsTests { + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + public class ModulesSettings { [ModuleSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = ""; + public string StringProperty { get; set; } = string.Empty; [ModuleSetting(Prefix = SettingNamePrefix)] public int IntegerProperty { get; set; } [ModuleSetting(Prefix = SettingNamePrefix)] public double DoubleProperty { get; set; } - + [ModuleSetting(Prefix = SettingNamePrefix)] public bool BooleanProperty { get; set; } @@ -43,38 +68,16 @@ public class ModulesSettings public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); } - public class ModulesSettingsRepository : SettingsRepository { } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } + public class ModulesSettingsRepository : SettingsRepository + { + } [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("en-US")] public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -82,7 +85,7 @@ public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_en_US(stri [SetCulture("fr-FR")] public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -90,7 +93,7 @@ public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_fr_FR(stri [SetCulture("he-IL")] public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -98,7 +101,7 @@ public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_he_IL(stri [SetCulture("ru-RU")] public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -109,72 +112,74 @@ public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_tr_TR(stri this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - private void SaveSettings_CallsUpdateModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, - bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + [Test] + public void SaveSettings_UpdatesCache() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new ModulesSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; - - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "StringProperty", stringValue)); - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); + var settings = new ModulesSettings(); + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new ModulesSettingsRepository(); - //Act + // Act settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new ModulesSettings(); - MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new ModulesSettings()); var settingsRepository = new ModulesSettingsRepository(); - //Act - settingsRepository.SaveSettings(moduleInfo, settings); + // Act + settingsRepository.GetSettings(moduleInfo); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } - - [Test] - public void GetSettings_CallsGetCachedObject() + + private void SaveSettings_CallsUpdateModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, + bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; + var settings = new ModulesSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "StringProperty", stringValue)); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); - MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new ModulesSettings()); var settingsRepository = new ModulesSettingsRepository(); - //Act - settingsRepository.GetSettings(moduleInfo); + // Act + settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] @@ -182,7 +187,7 @@ public void GetSettings_CallsGetCachedObject() [SetCulture("ar-JO")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -190,7 +195,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string str [SetCulture("ca-ES")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -198,7 +203,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string str [SetCulture("zh-CN")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -206,7 +211,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string str [SetCulture("en-US")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -214,7 +219,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string str [SetCulture("fr-FR")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -222,7 +227,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string str [SetCulture("he-IL")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -230,7 +235,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string str [SetCulture("ru-RU")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -238,13 +243,13 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string str [SetCulture("tr-TR")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } public void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; var moduleSettings = new Hashtable { @@ -258,14 +263,14 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringVal { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, }; - MockModuleSettings(moduleInfo, moduleSettings); + this.MockModuleSettings(moduleInfo, moduleSettings); var settingsRepository = new ModulesSettingsRepository(); - //Act + // Act var settings = settingsRepository.GetSettings(moduleInfo); - //Assert + // Assert Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); @@ -274,7 +279,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringVal Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); - MockRepository.VerifyAll(); + this.MockRepository.VerifyAll(); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs index c2078865cda..37a8486b546 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs @@ -1,43 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules.Settings; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Modules.Settings { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules.Settings; + using NUnit.Framework; + [TestFixture] public class NullableSettingsTests : BaseSettingsTests { - public class MyNullableSettings + public readonly object[] NullableCases = { - [ModuleSetting] - public string StringProperty { get; set; } = "Default Value"; - - [PortalSetting] - public int? IntegerProperty { get; set; } = 500; - - [ModuleSetting] - public DateTime? DateTimeProperty { get; set; } = DateTime.MaxValue; - - [TabModuleSetting] - public TimeSpan? TimeSpanProperty { get; set; } = TimeSpan.FromHours(12); - } - - public class MyNullableSettingsRepository : SettingsRepository { } - + new object[] { null, null, null, null, }, + new object[] { string.Empty, -1, DateTime.UtcNow, TimeSpan.FromMilliseconds(3215648), }, + new object[] { "lorem ipsum", 456, DateTime.Now, DateTime.Today - DateTime.Now, }, + }; + [Test] [TestCaseSource(nameof(NullableCases))] [SetCulture("ar-JO")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_ar_JO(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -45,7 +36,7 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_ar_JO(string str [SetCulture("ca-ES")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_ca_ES(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -53,15 +44,34 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_ca_ES(string str [SetCulture("zh-CN")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_zh_CN(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } + + public class MyNullableSettings + { + [ModuleSetting] + public string StringProperty { get; set; } = "Default Value"; + + [PortalSetting] + public int? IntegerProperty { get; set; } = 500; + + [ModuleSetting] + public DateTime? DateTimeProperty { get; set; } = DateTime.MaxValue; + + [TabModuleSetting] + public TimeSpan? TimeSpanProperty { get; set; } = TimeSpan.FromHours(12); + } + + public class MyNullableSettingsRepository : SettingsRepository + { + } [Test] [TestCaseSource(nameof(NullableCases))] [SetCulture("en-US")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_en_US(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -69,7 +79,7 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_en_US(string str [SetCulture("fr-FR")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_fr_FR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -77,7 +87,7 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_fr_FR(string str [SetCulture("he-IL")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_he_IL(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -85,7 +95,7 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_he_IL(string str [SetCulture("ru-RU")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_ru_RU(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -93,70 +103,74 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_ru_RU(string str [SetCulture("tr-TR")] public void SaveSettings_CallsUpdateSetting_WithRightParameters_tr_TR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); + this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } - private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + [Test] + public void SaveSettings_UpdatesCache() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyNullableSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - }; - - var expectedStringValue = stringValue ?? string.Empty; - MockModuleController.Setup(pc => pc.UpdateModuleSetting(ModuleId, "StringProperty", expectedStringValue)); - var integerString = integerValue?.ToString() ?? string.Empty; - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, "IntegerProperty", integerString, true, Null.NullString, false)); - var dateTimeString = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty; - MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, "DateTimeProperty", dateTimeString)); - var timeSpanString = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty; - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, "TimeSpanProperty", timeSpanString)); + var settings = new MyNullableSettings(); + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new MyNullableSettingsRepository(); - //Act + // Act settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyNullableSettings(); - MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyNullableSettings()); var settingsRepository = new MyNullableSettingsRepository(); - //Act - settingsRepository.SaveSettings(moduleInfo, settings); + // Act + settingsRepository.GetSettings(moduleInfo); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } - [Test] - public void GetSettings_CallsGetCachedObject() + private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; + var settings = new MyNullableSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + }; + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + var expectedStringValue = stringValue ?? string.Empty; + this.MockModuleController.Setup(pc => pc.UpdateModuleSetting(ModuleId, "StringProperty", expectedStringValue)); + var integerString = integerValue?.ToString() ?? string.Empty; + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, "IntegerProperty", integerString, true, Null.NullString, false)); + var dateTimeString = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty; + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, "DateTimeProperty", dateTimeString)); + var timeSpanString = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty; + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, "TimeSpanProperty", timeSpanString)); - MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyNullableSettings()); var settingsRepository = new MyNullableSettingsRepository(); - //Act - settingsRepository.GetSettings(moduleInfo); + // Act + settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] @@ -164,7 +178,7 @@ public void GetSettings_CallsGetCachedObject() [SetCulture("ar-JO")] public void GetSettings_GetsValues_FromCorrectSettings_ar_JO(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -172,7 +186,7 @@ public void GetSettings_GetsValues_FromCorrectSettings_ar_JO(string stringValue, [SetCulture("ca-ES")] public void GetSettings_GetsValues_FromCorrectSettings_ca_ES(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -180,7 +194,7 @@ public void GetSettings_GetsValues_FromCorrectSettings_ca_ES(string stringValue, [SetCulture("zh-CN")] public void GetSettings_GetsValues_FromCorrectSettings_zh_CN(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -188,7 +202,7 @@ public void GetSettings_GetsValues_FromCorrectSettings_zh_CN(string stringValue, [SetCulture("en-US")] public void GetSettings_GetsValues_FromCorrectSettings_en_US(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -196,7 +210,7 @@ public void GetSettings_GetsValues_FromCorrectSettings_en_US(string stringValue, [SetCulture("fr-FR")] public void GetSettings_GetsValues_FromCorrectSettings_fr_FR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -204,7 +218,7 @@ public void GetSettings_GetsValues_FromCorrectSettings_fr_FR(string stringValue, [SetCulture("he-IL")] public void GetSettings_GetsValues_FromCorrectSettings_he_IL(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -212,7 +226,7 @@ public void GetSettings_GetsValues_FromCorrectSettings_he_IL(string stringValue, [SetCulture("ru-RU")] public void GetSettings_GetsValues_FromCorrectSettings_ru_RU(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } [Test] @@ -220,40 +234,33 @@ public void GetSettings_GetsValues_FromCorrectSettings_ru_RU(string stringValue, [SetCulture("tr-TR")] public void GetSettings_GetsValues_FromCorrectSettings_tr_TR(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); + this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } private void GetSettings_GetsValues_FromCorrectSettings(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { - //Arrange + // Arrange var expectedStringValue = stringValue ?? string.Empty; var moduleInfo = GetModuleInfo; var portalSettings = new Dictionary { ["IntegerProperty"] = integerValue?.ToString() ?? string.Empty, }; var moduleSettings = new Hashtable { ["DateTimeProperty"] = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty, ["StringProperty"] = expectedStringValue, }; var tabModuleSettings = new Hashtable { ["TimeSpanProperty"] = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty, }; - MockPortalSettings(moduleInfo, portalSettings); - MockModuleSettings(moduleInfo, moduleSettings); - MockTabModuleSettings(moduleInfo, tabModuleSettings); + this.MockPortalSettings(moduleInfo, portalSettings); + this.MockModuleSettings(moduleInfo, moduleSettings); + this.MockTabModuleSettings(moduleInfo, tabModuleSettings); var settingsRepository = new MyNullableSettingsRepository(); - //Act + // Act var settings = settingsRepository.GetSettings(moduleInfo); - //Assert + // Assert Assert.AreEqual(expectedStringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one"); Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); - MockRepository.VerifyAll(); + this.MockRepository.VerifyAll(); } - - public readonly object[] NullableCases = - { - new object[] { null, null, null, null, }, - new object[] { "", -1, DateTime.UtcNow, TimeSpan.FromMilliseconds(3215648), }, - new object[] { "lorem ipsum", 456, DateTime.Now, DateTime.Today - DateTime.Now, }, - }; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs index bfcf6b6fcc5..997a80aeb93 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs @@ -1,25 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules.Settings; -using DotNetNuke.Entities.Portals; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Modules.Settings { + using System; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules.Settings; + using DotNetNuke.Entities.Portals; + using Moq; + using NUnit.Framework; + [TestFixture] public class PortalSettingsTests : BaseSettingsTests { + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + public class MyPortalSettings { [PortalSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = ""; + public string StringProperty { get; set; } = string.Empty; [PortalSetting(Prefix = SettingNamePrefix)] public int IntegerProperty { get; set; } @@ -43,38 +68,16 @@ public class MyPortalSettings public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); } - public class MyPortalSettingsRepository : SettingsRepository { } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } + public class MyPortalSettingsRepository : SettingsRepository + { + } [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("en-US")] public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -82,7 +85,7 @@ public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_en_US(stri [SetCulture("fr-FR")] public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -90,7 +93,7 @@ public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_fr_FR(stri [SetCulture("he-IL")] public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -98,7 +101,7 @@ public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_he_IL(stri [SetCulture("ru-RU")] public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -106,75 +109,75 @@ public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ru_RU(stri [SetCulture("tr-TR")] public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - private void SaveSettings_CallsUpdatePortalSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, - bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + [Test] + public void SaveSettings_UpdatesCache() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyPortalSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; - - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "StringProperty", stringValue, true, Null.NullString, false)); - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "IntegerProperty", integerValue.ToString(), true, Null.NullString, false)); - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture), true, Null.NullString, false)); - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString(), true, Null.NullString, false)); - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture), true, Null.NullString, false)); - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture), true, Null.NullString, false)); - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "EnumProperty", enumValue.ToString(), true, Null.NullString, false)); - MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}", true, Null.NullString, false)); + var settings = new MyPortalSettings(); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new MyPortalSettingsRepository(); - //Act + // Act settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyPortalSettings(); - MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyPortalSettings()); var settingsRepository = new MyPortalSettingsRepository(); - //Act - settingsRepository.SaveSettings(moduleInfo, settings); + // Act + settingsRepository.GetSettings(moduleInfo); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } - [Test] - public void GetSettings_CallsGetCachedObject() + private void SaveSettings_CallsUpdatePortalSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, + bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; + var settings = new MyPortalSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "StringProperty", stringValue, true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "IntegerProperty", integerValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "EnumProperty", enumValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}", true, Null.NullString, false)); - MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyPortalSettings()); var settingsRepository = new MyPortalSettingsRepository(); - //Act - settingsRepository.GetSettings(moduleInfo); + // Act + settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] @@ -182,7 +185,7 @@ public void GetSettings_CallsGetCachedObject() [SetCulture("ar-JO")] public void GetSettings_GetsValuesFrom_PortalSettings_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -190,7 +193,7 @@ public void GetSettings_GetsValuesFrom_PortalSettings_ar_JO(string stringValue, [SetCulture("ca-ES")] public void GetSettings_GetsValuesFrom_PortalSettings_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -198,7 +201,7 @@ public void GetSettings_GetsValuesFrom_PortalSettings_ca_ES(string stringValue, [SetCulture("zh-CN")] public void GetSettings_GetsValuesFrom_PortalSettings_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -206,7 +209,7 @@ public void GetSettings_GetsValuesFrom_PortalSettings_zh_CN(string stringValue, [SetCulture("en-US")] public void GetSettings_GetsValuesFrom_PortalSettings_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -214,7 +217,7 @@ public void GetSettings_GetsValuesFrom_PortalSettings_en_US(string stringValue, [SetCulture("fr-FR")] public void GetSettings_GetsValuesFrom_PortalSettings_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -222,7 +225,7 @@ public void GetSettings_GetsValuesFrom_PortalSettings_fr_FR(string stringValue, [SetCulture("he-IL")] public void GetSettings_GetsValuesFrom_PortalSettings_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -230,7 +233,7 @@ public void GetSettings_GetsValuesFrom_PortalSettings_he_IL(string stringValue, [SetCulture("ru-RU")] public void GetSettings_GetsValuesFrom_PortalSettings_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -238,12 +241,12 @@ public void GetSettings_GetsValuesFrom_PortalSettings_ru_RU(string stringValue, [SetCulture("tr-TR")] public void GetSettings_GetsValuesFrom_PortalSettings_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_PortalSettings(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } private void GetSettings_GetsValuesFrom_PortalSettings(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; var portalSettings = new Dictionary { @@ -257,14 +260,14 @@ private void GetSettings_GetsValuesFrom_PortalSettings(string stringValue, int i { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, }; - MockPortalSettings(moduleInfo, portalSettings); + this.MockPortalSettings(moduleInfo, portalSettings); var settingsRepository = new MyPortalSettingsRepository(); - //Act + // Act var settings = settingsRepository.GetSettings(moduleInfo); - //Assert + // Assert Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); @@ -273,7 +276,7 @@ private void GetSettings_GetsValuesFrom_PortalSettings(string stringValue, int i Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); - MockRepository.VerifyAll(); + this.MockRepository.VerifyAll(); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs index 9fa59ccc73f..37a4d45709d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs @@ -1,27 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Settings; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Modules.Settings { - using System.Runtime.Remoting.Channels; - + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Settings; + using Moq; + using NUnit.Framework; + [TestFixture] public class TabModuleSettingsTests : BaseSettingsTests { + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + public class MyTabModuleSettings { [TabModuleSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = ""; + public string StringProperty { get; set; } = string.Empty; [TabModuleSetting(Prefix = SettingNamePrefix)] public int IntegerProperty { get; set; } @@ -45,38 +68,16 @@ public class MyTabModuleSettings public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); } - public class MyTabModuleSettingsRepository : SettingsRepository { } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } + public class MyTabModuleSettingsRepository : SettingsRepository + { + } [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("en-US")] public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -84,7 +85,7 @@ public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_en_US(s [SetCulture("fr-FR")] public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -92,7 +93,7 @@ public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_fr_FR(s [SetCulture("he-IL")] public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -100,7 +101,7 @@ public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_he_IL(s [SetCulture("ru-RU")] public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -108,74 +109,77 @@ public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ru_RU(s [SetCulture("tr-TR")] public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - private void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + [Test] + public void SaveSettings_UpdatesCache() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyTabModuleSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; - - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "StringProperty", stringValue)); - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); - MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); + var settings = new MyTabModuleSettings(); + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new MyTabModuleSettingsRepository(); - //Act + // Act settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyTabModuleSettings(); - MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyTabModuleSettings()); var settingsRepository = new MyTabModuleSettingsRepository(); - //Act - settingsRepository.SaveSettings(moduleInfo, settings); + // Act + settingsRepository.GetSettings(moduleInfo); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } - [Test] - public void GetSettings_CallsGetCachedObject() + private void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; + var settings = new MyTabModuleSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "StringProperty", stringValue)); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); - MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyTabModuleSettings()); var settingsRepository = new MyTabModuleSettingsRepository(); - //Act - settingsRepository.GetSettings(moduleInfo); + // Act + settingsRepository.SaveSettings(moduleInfo, settings); - //Assert - MockRepository.VerifyAll(); + // Assert + this.MockRepository.VerifyAll(); } [Test] @@ -183,7 +187,7 @@ public void GetSettings_CallsGetCachedObject() [SetCulture("ar-JO")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -191,7 +195,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ar_JO(string str [SetCulture("ca-ES")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -199,7 +203,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ca_ES(string str [SetCulture("zh-CN")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -207,7 +211,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_zh_CN(string str [SetCulture("en-US")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -215,7 +219,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_en_US(string str [SetCulture("fr-FR")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -223,7 +227,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_fr_FR(string str [SetCulture("he-IL")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -231,7 +235,7 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_he_IL(string str [SetCulture("ru-RU")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } [Test] @@ -239,12 +243,12 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_ru_RU(string str [SetCulture("tr-TR")] public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_tr_TR(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } private void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { - //Arrange + // Arrange var moduleInfo = GetModuleInfo; var tabModuleSettings = new Hashtable { @@ -258,14 +262,14 @@ private void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringVa { SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}" }, }; - MockTabModuleSettings(moduleInfo, tabModuleSettings); + this.MockTabModuleSettings(moduleInfo, tabModuleSettings); var settingsRepository = new MyTabModuleSettingsRepository(); - //Act + // Act var settings = settingsRepository.GetSettings(moduleInfo); - //Assert + // Assert Assert.AreEqual(stringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one"); Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one"); Assert.AreEqual(doubleValue, settings.DoubleProperty, "The retrieved double property value is not equal to the stored one"); @@ -274,7 +278,7 @@ private void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringVa Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); Assert.AreEqual(enumValue, settings.EnumProperty, "The retrieved enum property value is not equal to the stored one"); Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); - MockRepository.VerifyAll(); + this.MockRepository.VerifyAll(); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs index 3a3b1b3813d..6b365064301 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs @@ -1,19 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using DotNetNuke.Entities; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Portals { + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Reflection; + + using DotNetNuke.Entities; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + public class PortalSettingsControllerTestFactory + // ReSharper disable once InconsistentNaming { internal static string FilePath @@ -27,22 +29,6 @@ internal static string FilePath } } - internal static Dictionary GetHostSettings() - { - var settings = new Dictionary(); - - //Read Test Settings - Util.ReadStream(FilePath, "HostSettings", (line, header) => - { - string[] fields = line.Split(','); - string key = fields[0].Trim(); - string value = fields[1].Trim(); - - settings.Add(key, value); - }); - return settings; - } - internal static IEnumerable LoadPortalSettings_Loads_Default_Value { get @@ -55,16 +41,16 @@ internal static IEnumerable LoadPortalSettings_Loads_Default_Value var testName = "Load_Default_Value"; string[] headers = header.Split(','); string[] fields = line.Split(','); - for (int i = 0; i < fields.Length; i++ ) + for (int i = 0; i < fields.Length; i++) { string key = headers[i].Trim(new[] { '\t', '"' }); - string val = fields[i].Trim(new[] {'\t', '"'}); + string val = fields[i].Trim(new[] { '\t', '"' }); fieldList[key] = val; } testName += "_"; - + testName += fields[0]; testData.Add(new TestCaseData(fieldList).SetName(testName)); @@ -104,5 +90,21 @@ internal static IEnumerable LoadPortalSettings_Loads_Setting_Value return testData; } } + + internal static Dictionary GetHostSettings() + { + var settings = new Dictionary(); + + // Read Test Settings + Util.ReadStream(FilePath, "HostSettings", (line, header) => + { + string[] fields = line.Split(','); + string key = fields[0].Trim(); + string value = fields[1].Trim(); + + settings.Add(key, value); + }); + return settings; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs index 35e8448fb32..9c53a1f0c7e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.Serialization; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Localization; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.UI.Skins; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Portals { + using System; + using System.Collections.Generic; + using System.Reflection; + using System.Runtime.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Localization; + using DotNetNuke.Tests.Utilities.Mocks; + using DotNetNuke.UI.Skins; + using Moq; + using NUnit.Framework; + [TestFixture] public class PortalSettingsControllerTests { @@ -56,13 +57,13 @@ public void TearDown() [TestCaseSource(typeof(PortalSettingsControllerTestFactory), "LoadPortalSettings_Loads_Default_Value")] public void LoadPortalSettings_Loads_Default_Value(Dictionary testFields) { - //Arrange + // Arrange var propertyName = testFields["PropertyName"]; var settingName = testFields["SettingName"]; - var isHostDefault = Boolean.Parse(testFields["IsHostDefault"]); + var isHostDefault = bool.Parse(testFields["IsHostDefault"]); var defaultValue = testFields["DefaultValue"]; var controller = new PortalSettingsController(); - var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString}; + var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); var mockPortalController = new Mock(); @@ -77,11 +78,11 @@ public void LoadPortalSettings_Loads_Default_Value(Dictionary te mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) .Returns((string s1, string s2) => hostSettings[s1]); mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) - .Returns((string s, bool b) => Boolean.Parse(hostSettings[s])); + .Returns((string s, bool b) => bool.Parse(hostSettings[s])); mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) - .Returns((string s, int i) => Int32.Parse(hostSettings[s])); + .Returns((string s, int i) => int.Parse(hostSettings[s])); mockHostController.Setup(c => c.GetInteger(It.IsAny())) - .Returns((string s) => Int32.Parse(hostSettings[s])); + .Returns((string s) => int.Parse(hostSettings[s])); HostController.RegisterInstance(mockHostController.Object); if (isHostDefault) @@ -89,11 +90,10 @@ public void LoadPortalSettings_Loads_Default_Value(Dictionary te defaultValue = hostSettings[settingName]; } - //Act + // Act controller.LoadPortalSettings(settings); - - - //Assert + + // Assert var property = settings.GetType().GetProperty(propertyName); var actualValue = property.GetValue(settings, null); if (actualValue is bool) @@ -110,11 +110,11 @@ public void LoadPortalSettings_Loads_Default_Value(Dictionary te [TestCaseSource(typeof(PortalSettingsControllerTestFactory), "LoadPortalSettings_Loads_Setting_Value")] public void LoadPortalSettings_Loads_Setting_Value(Dictionary testFields) { - //Arrange + // Arrange var propertyName = testFields["PropertyName"]; var settingName = testFields["SettingName"]; var settingValue = testFields["SettingValue"]; - var propertyValue = (testFields.ContainsKey("PropertyValue")) ? testFields["PropertyValue"] : settingValue; + var propertyValue = testFields.ContainsKey("PropertyValue") ? testFields["PropertyValue"] : settingValue; var controller = new PortalSettingsController(); var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); @@ -131,15 +131,15 @@ public void LoadPortalSettings_Loads_Setting_Value(Dictionary te mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) .Returns((string s1, string s2) => hostSettings[s1]); mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) - .Returns((string s, bool b) => Boolean.Parse(hostSettings[s])); + .Returns((string s, bool b) => bool.Parse(hostSettings[s])); mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) - .Returns((string s, int i) => Int32.Parse(hostSettings[s])); + .Returns((string s, int i) => int.Parse(hostSettings[s])); HostController.RegisterInstance(mockHostController.Object); - //Act + // Act controller.LoadPortalSettings(settings); - //Assert + // Assert var property = settings.GetType().GetProperty(propertyName); var actualValue = property.GetValue(settings, null); if (actualValue is bool) @@ -155,7 +155,7 @@ public void LoadPortalSettings_Loads_Setting_Value(Dictionary te [Test] public void LoadPortalSettings_Sets_TimeZone_Property_To_Local_TimeZone() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; var hostSettings = PortalSettingsControllerTestFactory.GetHostSettings(); @@ -172,36 +172,36 @@ public void LoadPortalSettings_Sets_TimeZone_Property_To_Local_TimeZone() mockHostController.Setup(c => c.GetString(It.IsAny(), It.IsAny())) .Returns((string s1, string s2) => hostSettings[s1]); mockHostController.Setup(c => c.GetBoolean(It.IsAny(), It.IsAny())) - .Returns((string s, bool b) => Boolean.Parse(hostSettings[s])); + .Returns((string s, bool b) => bool.Parse(hostSettings[s])); mockHostController.Setup(c => c.GetInteger(It.IsAny(), It.IsAny())) - .Returns((string s, int i) => Int32.Parse(hostSettings[s])); + .Returns((string s, int i) => int.Parse(hostSettings[s])); HostController.RegisterInstance(mockHostController.Object); - //Act + // Act controller.LoadPortalSettings(settings); - //Assert + // Assert Assert.AreEqual(TimeZoneInfo.Local, settings.TimeZone); } [Test] public void LoadPortal_Loads_Portal_Property_Values() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var portal = new PortalInfo() { - Users = 2, - Pages = 5, + Users = 2, + Pages = 5, DefaultLanguage = Localization.SystemLocale, - HomeDirectory = "Portals/0" + HomeDirectory = "Portals/0", }; var settings = new PortalSettings() { PortalId = ValidPortalId, CultureCode = Null.NullString }; - //Act - controller.LoadPortal(portal,settings); + // Act + controller.LoadPortal(portal, settings); - //Assert + // Assert Assert.AreEqual(portal.AdminTabId, settings.AdminTabId); Assert.AreEqual(portal.AdministratorId, settings.AdministratorId); Assert.AreEqual(portal.AdministratorRoleId, settings.AdministratorRoleId); @@ -248,7 +248,7 @@ public void LoadPortal_Loads_Portal_Property_Values() [Test] public void GetActiveTab_Gets_Correct_Tab_If_Valid_Portal_TabId() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; @@ -262,17 +262,17 @@ public void GetActiveTab_Gets_Correct_Tab_If_Valid_Portal_TabId() mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act var tab = controller.GetActiveTab(ValidTabId, settings); - //Assert + // Assert Assert.AreEqual(validTab.TabID, tab.TabID); } [Test] public void GetActiveTab_Gets_Correct_Tab_If_Valid_Host_TabId() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = HostTabId, PortalID = HostPortalId }; @@ -286,22 +286,22 @@ public void GetActiveTab_Gets_Correct_Tab_If_Valid_Host_TabId() mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection()); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act var tab = controller.GetActiveTab(HostTabId, settings); - //Assert + // Assert Assert.AreEqual(validTab.TabID, tab.TabID); } [Test] public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_SplashTab_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, CultureCode = Null.NullString}; - var splashTabId = new TabInfo {TabID = SplashTabId, PortalID = ValidPortalId}; + var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, CultureCode = Null.NullString }; + var splashTabId = new TabInfo { TabID = SplashTabId, PortalID = ValidPortalId }; - var mockLocaleController = new Mock (); + var mockLocaleController = new Mock(); mockLocaleController.Setup(c => c.GetLocales(ValidPortalId)).Returns(new Dictionary()); LocaleController.RegisterInstance(mockLocaleController.Object); @@ -309,17 +309,17 @@ public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_SplashTab_Set() mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { splashTabId })); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act var tab = controller.GetActiveTab(InValidTabId, settings); - //Assert + // Assert Assert.AreEqual(SplashTabId, tab.TabID); } [Test] public void GetActiveTab_Gets_Home_Tab_If_InValid_TabId_And_Home_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, HomeTabId = HomeTabId, CultureCode = Null.NullString }; var homeTabId = new TabInfo { TabID = HomeTabId, PortalID = ValidPortalId }; @@ -332,19 +332,19 @@ public void GetActiveTab_Gets_Home_Tab_If_InValid_TabId_And_Home_Set() mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { homeTabId })); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act var tab = controller.GetActiveTab(InValidTabId, settings); - //Assert + // Assert Assert.AreEqual(HomeTabId, tab.TabID); } [Test] public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_Both_HomeTab_And_SplashTab_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, HomeTabId = HomeTabId, CultureCode = Null.NullString}; + var settings = new PortalSettings { PortalId = ValidPortalId, SplashTabId = SplashTabId, HomeTabId = HomeTabId, CultureCode = Null.NullString }; var splashTabId = new TabInfo { TabID = SplashTabId, PortalID = ValidPortalId }; var homeTabId = new TabInfo { TabID = HomeTabId, PortalID = ValidPortalId }; @@ -356,17 +356,17 @@ public void GetActiveTab_Gets_Splash_Tab_If_InValid_TabId_And_Both_HomeTab_And_S mockTabController.Setup(c => c.GetTabsByPortal(ValidPortalId)).Returns(new TabCollection(new List { splashTabId, homeTabId })); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act var tab = controller.GetActiveTab(InValidTabId, settings); - //Assert + // Assert Assert.AreEqual(SplashTabId, tab.TabID); } [Test] public void GetActiveTab_Sets_StartDate_And_EndDate_Of_Tab_If_Not_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; @@ -380,10 +380,10 @@ public void GetActiveTab_Sets_StartDate_And_EndDate_Of_Tab_If_Not_Set() mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act var tab = controller.GetActiveTab(ValidTabId, settings); - //Assert + // Assert Assert.AreEqual(DateTime.MinValue, tab.StartDate); Assert.AreEqual(DateTime.MaxValue, tab.EndDate); } @@ -391,9 +391,9 @@ public void GetActiveTab_Sets_StartDate_And_EndDate_Of_Tab_If_Not_Set() [Test] public void ConfigureTab_Uses_PortalSettings_DefaultSkin_If_SkinSrc_Not_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString}; + var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; settings.ActiveTab = validTab; @@ -411,20 +411,20 @@ public void ConfigureTab_Uses_PortalSettings_DefaultSkin_If_SkinSrc_Not_Set() mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert Assert.AreEqual(DefaultSkin, settings.ActiveTab.SkinSrc); } [Test] public void ConfigureTab_Uses_Tab_SkinSrc_If_SkinSrc_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = TabSkin}; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = TabSkin }; settings.ActiveTab = validTab; var mockLocaleController = new Mock(); @@ -440,17 +440,17 @@ public void ConfigureTab_Uses_Tab_SkinSrc_If_SkinSrc_Set() mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); HostController.RegisterInstance(mockHostController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert Assert.AreEqual(TabSkin, settings.ActiveTab.SkinSrc); } [Test] public void ConfigureTab_Formats_Tab_SkinSrc_If_Neccessary() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalSkin = DefaultSkin, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = GlobalTabSkin }; @@ -469,17 +469,17 @@ public void ConfigureTab_Formats_Tab_SkinSrc_If_Neccessary() mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); HostController.RegisterInstance(mockHostController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert Assert.AreEqual(SkinController.FormatSkinSrc(GlobalTabSkin, settings), settings.ActiveTab.SkinSrc); } [Test] public void ConfigureTab_Uses_PortalSettings_DefaultContainer_If_ContainerSrc_Not_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId }; @@ -499,17 +499,17 @@ public void ConfigureTab_Uses_PortalSettings_DefaultContainer_If_ContainerSrc_No mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); HostController.RegisterInstance(mockHostController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert Assert.AreEqual(DefaultContainer, settings.ActiveTab.ContainerSrc); } [Test] public void ConfigureTab_Uses_Tab_ContainerSrc_If_ContainerSrc_Set() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ContainerSrc = TabContainer }; @@ -525,17 +525,17 @@ public void ConfigureTab_Uses_Tab_ContainerSrc_If_ContainerSrc_Set() mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert Assert.AreEqual(TabContainer, settings.ActiveTab.ContainerSrc); } [Test] public void ConfigureTab_Formats_Tab_ContainerSrc_If_Neccessary() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, DefaultPortalContainer = DefaultContainer, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ContainerSrc = GlobalTabContainer }; @@ -551,19 +551,19 @@ public void ConfigureTab_Formats_Tab_ContainerSrc_If_Neccessary() mockTabController.Setup(c => c.GetTabsByPortal(HostPortalId)).Returns(new TabCollection()); TabController.SetTestableInstance(mockTabController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert Assert.AreEqual(SkinController.FormatSkinSrc(GlobalTabContainer, settings), settings.ActiveTab.ContainerSrc); } [Test] public void ConfigureTab_Builds_Breadcrumbs_For_Tab() { - //Arrange + // Arrange var controller = new PortalSettingsController(); - var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString}; + var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, SkinSrc = GlobalTabSkin }; settings.ActiveTab = validTab; @@ -580,10 +580,10 @@ public void ConfigureTab_Builds_Breadcrumbs_For_Tab() mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); HostController.RegisterInstance(mockHostController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert Assert.NotNull(settings.ActiveTab.BreadCrumbs); Assert.AreEqual(1, settings.ActiveTab.BreadCrumbs.Count); } @@ -591,10 +591,10 @@ public void ConfigureTab_Builds_Breadcrumbs_For_Tab() [Test] public void ConfigureTab_Builds_Breadcrumbs_For_Tab_And_Parent() { - //Arrange + // Arrange var controller = new PortalSettingsController(); var settings = new PortalSettings { PortalId = ValidPortalId, CultureCode = Null.NullString }; - var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ParentId = ParentTabId}; + var validTab = new TabInfo { TabID = ValidTabId, PortalID = ValidPortalId, ParentId = ParentTabId }; var parentTab = new TabInfo { TabID = ParentTabId, PortalID = ValidPortalId }; settings.ActiveTab = validTab; settings.ActiveTab.SkinSrc = TabSkin; @@ -612,10 +612,10 @@ public void ConfigureTab_Builds_Breadcrumbs_For_Tab_And_Parent() mockHostController.Setup(c => c.GetString("DefaultPortalContainer")).Returns("DefaultPortalContainer"); HostController.RegisterInstance(mockHostController.Object); - //Act + // Act controller.ConfigureActiveTab(settings); - //Assert + // Assert var actualParent = settings.ActiveTab.BreadCrumbs[0] as TabInfo; var actualTab = settings.ActiveTab.BreadCrumbs[1] as TabInfo; Assert.AreEqual(2, settings.ActiveTab.BreadCrumbs.Count); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs index c4c52035549..e0893017f4e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Portals { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class PortalSettingsTests { @@ -31,316 +32,316 @@ public void TearDown() [Test] public void Constructor_Creates_Registration_Property() { - //Arrange + // Arrange - //Act + // Act var settings = new PortalSettings(); - //Assert + // Assert Assert.IsNotNull(settings.Registration); } [Test] public void Constructor_Sets_PortalId_When_Passed_PortalId() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - //Act + // Act var settings = new PortalSettings(ValidTabId, ValidPortalId); - //Assert + // Assert Assert.AreEqual(ValidPortalId, settings.PortalId); } [Test] public void Constructor_Sets_PortalId_When_Passed_PortalAlias() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(ValidPortalId); + var portalAlias = this.CreatePortalAlias(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert Assert.AreEqual(ValidPortalId, settings.PortalId); } [Test] public void Constructor_Sets_PortalAlias_When_Passed_PortalAlias() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(ValidPortalId); + var portalAlias = this.CreatePortalAlias(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert Assert.AreEqual(portalAlias, settings.PortalAlias); } [Test] public void Constructor_Sets_PortalId_When_Passed_Portal() { - //Arrange + // Arrange var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portal = CreatePortal(ValidPortalId); + var portal = this.CreatePortal(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portal); - //Assert + // Assert Assert.AreEqual(ValidPortalId, settings.PortalId); } [Test] public void Constructor_Does_Not_Set_PortalId_When_Passed_Null_Portal() { - //Arrange + // Arrange var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portal = CreatePortal(ValidPortalId); + var portal = this.CreatePortal(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, (PortalInfo)null); - //Assert + // Assert Assert.AreEqual(InValidPortalId, settings.PortalId); } [Test] public void Constructor_Calls_PortalController_GetPortal_When_Passed_PortalId() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - //Act + // Act var settings = new PortalSettings(ValidTabId, ValidPortalId); - //Assert + // Assert mockPortalController.Verify(c => c.GetPortal(ValidPortalId)); } [Test] public void Constructor_Calls_PortalController_GetPortal_When_Passed_PortalAlias() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(ValidPortalId); + var portalAlias = this.CreatePortalAlias(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert mockPortalController.Verify(c => c.GetPortal(ValidPortalId)); } [Test] public void Constructor_Calls_PortalSettingsController_LoadPortal_When_Passed_Portal() - { - //Arrange - var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - - var portal = CreatePortal(ValidPortalId); - - //Act - var settings = new PortalSettings(ValidTabId, portal); - - //Assert + { + // Arrange + var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); + + var portal = this.CreatePortal(ValidPortalId); + + // Act + var settings = new PortalSettings(ValidTabId, portal); + + // Assert mockPortalSettingsController.Verify(c => c.LoadPortal(portal, settings)); } [Test] public void Constructor_Calls_PortalSettingsController_LoadPortal_When_Passed_Valid_PortalAlias() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalController = new Mock(); mockPortalController.Setup(c => c.GetPortal(ValidPortalId)).Returns(portal); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(ValidPortalId); + var portalAlias = this.CreatePortalAlias(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.LoadPortal(portal, settings)); } [Test] public void Constructor_Does_Not_Call_PortalSettingsController_LoadPortal_When_Portal_Is_Null() { - //Arrange + // Arrange var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - //Act - var settings = new PortalSettings(ValidTabId, (PortalInfo) null); + // Act + var settings = new PortalSettings(ValidTabId, (PortalInfo)null); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.LoadPortal(It.IsAny(), settings), Times.Never); } [Test] public void Constructor_Does_Not_Call_PortalSettingsController_LoadPortal_When_Passed_InValid_PortalAlias() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalController = new Mock(); mockPortalController.Setup(c => c.GetPortal(ValidPortalId)).Returns(portal); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(InValidPortalId); + var portalAlias = this.CreatePortalAlias(InValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.LoadPortal(portal, settings), Times.Never); } [Test] public void Constructor_Calls_PortalSettingsController_LoadPortalSettings_When_Passed_PortalId() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - //Act + // Act var settings = new PortalSettings(ValidTabId, ValidPortalId); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.LoadPortalSettings(settings)); } [Test] public void Constructor_Calls_PortalSettingsController_LoadPortalSettings_When_Passed_Portal() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portal = CreatePortal(ValidPortalId); + var portal = this.CreatePortal(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portal); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.LoadPortalSettings(settings)); } [Test] public void Constructor_Calls_PortalSettingsController_LoadPortalSettings_When_Passed_PortalAlias() { - //Arrange + // Arrange var mockPortalController = new Mock(); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(ValidPortalId); + var portalAlias = this.CreatePortalAlias(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.LoadPortalSettings(settings)); } [Test] public void Constructor_Calls_PortalSettingsController_GetActiveTab_When_Passed_Portal() { - //Arrange + // Arrange var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portal = CreatePortal(ValidPortalId); + var portal = this.CreatePortal(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portal); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.GetActiveTab(ValidTabId, settings)); } [Test] public void Constructor_Calls_PortalSettingsController_GetActiveTab_When_Passed_Valid_PortalAlias() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalController = new Mock(); mockPortalController.Setup(c => c.GetPortal(ValidPortalId)).Returns(portal); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(ValidPortalId); + var portalAlias = this.CreatePortalAlias(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert mockPortalSettingsController.Verify(c => c.GetActiveTab(ValidTabId, settings)); } [Test] public void Constructor_Does_Not_Call_PortalSettingsController_GetActiveTab_When_Portal_Is_Null() { - //Arrange + // Arrange var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - //Act + // Act var settings = new PortalSettings(ValidTabId, (PortalInfo)null); - //Assert - mockPortalSettingsController.Verify(c => c.GetActiveTab(ValidTabId,settings), Times.Never); + // Assert + mockPortalSettingsController.Verify(c => c.GetActiveTab(ValidTabId, settings), Times.Never); } [Test] public void Constructor_Does_Not_Call_PortalSettingsController_GetActiveTab_When_Passed_InValid_PortalAlias() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalController = new Mock(); mockPortalController.Setup(c => c.GetPortal(ValidPortalId)).Returns(portal); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - var portalAlias = CreatePortalAlias(InValidPortalId); + var portalAlias = this.CreatePortalAlias(InValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert - mockPortalSettingsController.Verify(c => c.GetActiveTab(ValidTabId,settings), Times.Never); + // Assert + mockPortalSettingsController.Verify(c => c.GetActiveTab(ValidTabId, settings), Times.Never); } [Test] public void Constructor_Sets_ActiveTab_Property_If_Valid_TabId_And_PortalId() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalController = new Mock(); mockPortalController.Setup(c => c.GetPortal(ValidPortalId)).Returns(portal); PortalController.SetTestableInstance(mockPortalController.Object); @@ -349,18 +350,18 @@ public void Constructor_Sets_ActiveTab_Property_If_Valid_TabId_And_PortalId() .Setup(c => c.GetActiveTab(ValidTabId, It.IsAny())) .Returns(new TabInfo()); - //Act + // Act var settings = new PortalSettings(ValidTabId, ValidPortalId); - //Assert + // Assert Assert.NotNull(settings.ActiveTab); } [Test] public void Constructor_Sets_ActiveTab_Property_To_Null_If_InValid_TabId_And_PortalId() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalController = new Mock(); mockPortalController.Setup(c => c.GetPortal(ValidPortalId)).Returns(portal); PortalController.SetTestableInstance(mockPortalController.Object); @@ -369,35 +370,35 @@ public void Constructor_Sets_ActiveTab_Property_To_Null_If_InValid_TabId_And_Por .Setup(c => c.GetActiveTab(InValidTabId, It.IsAny())) .Returns((TabInfo)null); - //Act + // Act var settings = new PortalSettings(ValidTabId, ValidPortalId); - //Assert + // Assert Assert.Null(settings.ActiveTab); } [Test] public void Constructor_Sets_ActiveTab_Property_If_Valid_TabId_And_Portal() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); mockPortalSettingsController .Setup(c => c.GetActiveTab(ValidTabId, It.IsAny())) .Returns(new TabInfo()); - //Act + // Act var settings = new PortalSettings(ValidTabId, portal); - //Assert + // Assert Assert.NotNull(settings.ActiveTab); } [Test] public void Constructor_Sets_ActiveTab_Property_If_Valid_TabId_And_PortalAlias() { - //Arrange - var portal = CreatePortal(ValidPortalId); + // Arrange + var portal = this.CreatePortal(ValidPortalId); var mockPortalController = new Mock(); mockPortalController.Setup(c => c.GetPortal(ValidPortalId)).Returns(portal); PortalController.SetTestableInstance(mockPortalController.Object); @@ -406,12 +407,12 @@ public void Constructor_Sets_ActiveTab_Property_If_Valid_TabId_And_PortalAlias() .Setup(c => c.GetActiveTab(ValidTabId, It.IsAny())) .Returns(new TabInfo()); - var portalAlias = CreatePortalAlias(ValidPortalId); + var portalAlias = this.CreatePortalAlias(ValidPortalId); - //Act + // Act var settings = new PortalSettings(ValidTabId, portalAlias); - //Assert + // Assert Assert.NotNull(settings.ActiveTab); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Tabs/TabControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Tabs/TabControllerTests.cs index aede0968201..bbcae3c0593 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Tabs/TabControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Tabs/TabControllerTests.cs @@ -1,13 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Tests.Utilities.Mocks; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Entities.Tabs { + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Tests.Utilities.Mocks; + using NUnit.Framework; + [TestFixture] public class TabControllerTests { @@ -16,7 +16,7 @@ public void SetUp() { MockComponentProvider.CreateDataProvider(); } - + [TearDown] public void TearDown() { @@ -55,13 +55,13 @@ public void TearDown() [TestCase("Register")] public void IsValidadTab_Returns_False_For_Forbidden_PageNames(string tabName) { - //Arrange + // Arrange string invalidType; - //Act + // Act var isValid = TabController.IsValidTabName(tabName, out invalidType); - //Assert + // Assert Assert.IsFalse(isValid, "A forbidden tab name is allowed"); Assert.AreEqual("InvalidTabName", invalidType, "The invalidType is not the expected one"); } @@ -69,13 +69,13 @@ public void IsValidadTab_Returns_False_For_Forbidden_PageNames(string tabName) [Test] public void IsValidadTab_Returns_False_For_Empty_PageNames() { - //Arrange + // Arrange string invalidType; - //Act - var isValid = TabController.IsValidTabName("", out invalidType); + // Act + var isValid = TabController.IsValidTabName(string.Empty, out invalidType); - //Assert + // Assert Assert.IsFalse(isValid, "An empty tab name is allowed"); Assert.AreEqual("EmptyTabName", invalidType, "The invalidType is not the expected one"); } @@ -86,15 +86,15 @@ public void IsValidadTab_Returns_False_For_Empty_PageNames() [TestCase("products")] public void IsValidadTab_Returns_True_For_Regular_PageNames(string tabName) { - //Arrange + // Arrange string invalidType; - //Act + // Act var isValid = TabController.IsValidTabName(tabName, out invalidType); - //Assert + // Assert Assert.IsTrue(isValid, "A regular tab name is not allowed"); - Assert.AreEqual("", invalidType, "The invalidType is not the expected one"); + Assert.AreEqual(string.Empty, invalidType, "The invalidType is not the expected one"); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Urls/FriendlyUrlControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Urls/FriendlyUrlControllerTests.cs index 38785aaa0a4..aedf2712645 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Urls/FriendlyUrlControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Urls/FriendlyUrlControllerTests.cs @@ -1,20 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core { + using System; using System.Collections.Generic; using System.Diagnostics; + using System.Linq; using DotNetNuke.Entities.Urls; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; [TestFixture] public class FriendlyUrlControllerTests @@ -24,7 +23,7 @@ public class FriendlyUrlControllerTests [SetUp] public void SetUp() { - _mockCache = MockComponentProvider.CreateNew(); + this._mockCache = MockComponentProvider.CreateNew(); } [Test] @@ -245,8 +244,8 @@ private static FriendlyUrlOptions CreateFriendlyUrlOptions( ReplaceDoubleChars = replaceDoubleChars, ReplaceCharWithChar = replaceCharacterDictionary, PageExtension = (pageExtensionUsageType == PageExtensionUsageType.Never) - ? "" - : pageExtension + ? string.Empty + : pageExtension, }; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs index e8aa7edb17c..8e1cb404511 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs @@ -1,31 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -using DotNetNuke.Common.Utilities; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using NUnit.Framework; + [TestFixture] public class EscapedStringTest { [Test] public void SimpleCase() { - DoTest(new[] { "first", "second" }, "first,second"); + this.DoTest(new[] { "first", "second" }, "first,second"); } [Test] public void CombinesWithSpecifiedSeperator() { - string result = EscapedString.Combine(new[] {"first", "second"}, ';'); + string result = EscapedString.Combine(new[] { "first", "second" }, ';'); Assert.AreEqual("first;second", result); } @@ -35,91 +34,91 @@ public void SeperatesWithSpecifiedSeperator() { IEnumerable result = EscapedString.Seperate("first]second", ']'); - CollectionAssert.AreEqual(new[] {"first", "second"}, result); + CollectionAssert.AreEqual(new[] { "first", "second" }, result); } [Test] public void EmbeddedSeperator() { - DoTest(new[] { "fi,rst", "second" }, @"fi\,rst,second"); + this.DoTest(new[] { "fi,rst", "second" }, @"fi\,rst,second"); } [Test] public void DoubleSeperator() { - DoTest(new[] { "fi,,rst", "second" }, @"fi\,\,rst,second"); + this.DoTest(new[] { "fi,,rst", "second" }, @"fi\,\,rst,second"); } [Test] public void MultipleSeperators() { - DoTest(new[] { "fi,rst", ",second," }, @"fi\,rst,\,second\,"); + this.DoTest(new[] { "fi,rst", ",second," }, @"fi\,rst,\,second\,"); } [Test] public void EscapeCharacter() { - DoTest(new[] { @"fi\rst", "second" }, @"fi\\rst,second"); + this.DoTest(new[] { @"fi\rst", "second" }, @"fi\\rst,second"); } [Test] public void EmbeddedEscapeSequence() { - DoTest(new[] { @"fi\,rst", "second" }, @"fi\\\,rst,second"); + this.DoTest(new[] { @"fi\,rst", "second" }, @"fi\\\,rst,second"); } [Test] public void CrazyContrivedStuff() { - DoTest(new[] { @"\\\,,fi\,rst,,\,\\", "second" }, @"\\\\\\\,\,fi\\\,rst\,\,\\\,\\\\,second"); + this.DoTest(new[] { @"\\\,,fi\,rst,,\,\\", "second" }, @"\\\\\\\,\,fi\\\,rst\,\,\\\,\\\\,second"); } [Test] public void EmptyElement() { - DoTest(new[] { "first", "", "third" }, "first,,third"); + this.DoTest(new[] { "first", string.Empty, "third" }, "first,,third"); } [Test] public void MultipleEmptyElements() { - DoTest(new[] {"", "", ""}, ",,"); + this.DoTest(new[] { string.Empty, string.Empty, string.Empty }, ",,"); } [Test] public void EmptyEnumerable() { - DoTest(new object[] {}, ""); + this.DoTest(new object[] { }, string.Empty); } [Test] public void SingleElement() { - DoTest(new [] {"only item here"}, "only item here"); + this.DoTest(new[] { "only item here" }, "only item here"); } [Test] public void AllEscapeChars() { - DoTest(new [] {@"\", @"\\", @"\\\"}, @"\\,\\\\,\\\\\\"); + this.DoTest(new[] { @"\", @"\\", @"\\\" }, @"\\,\\\\,\\\\\\"); } [Test] public void AllSeperatorChars() { - DoTest(new [] {",", ",,", ",,,"}, @"\,,\,\,,\,\,\,"); + this.DoTest(new[] { ",", ",,", ",,," }, @"\,,\,\,,\,\,\,"); } [Test] public void AllEscapedSeperators() { - DoTest(new [] {@"\,", @"\,\,", @"\,\,\,"}, @"\\\,,\\\,\\\,,\\\,\\\,\\\,"); + this.DoTest(new[] { @"\,", @"\,\,", @"\,\,\," }, @"\\\,,\\\,\\\,,\\\,\\\,\\\,"); } private void DoTest(IEnumerable enumerable, string s) { - CombineTest(enumerable, s); - SeperateTest(enumerable.Cast(), s); + this.CombineTest(enumerable, s); + this.SeperateTest(enumerable.Cast(), s); } private void SeperateTest(IEnumerable expected, string data) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs index 56efa95a34f..93d0130320f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Linq; -using System.Reflection; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Tests.Utilities.Mocks; -using ICSharpCode.SharpZipLib.Zip; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core { + using System; + using System.IO; + using System.Linq; + using System.Reflection; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Tests.Utilities.Mocks; + using ICSharpCode.SharpZipLib.Zip; + using NUnit.Framework; + /// - /// FileSystemUtilsTests + /// FileSystemUtilsTests. /// [TestFixture] public class FileSystemUtilsTests @@ -29,12 +30,11 @@ public void SetUp() field.SetValue(null, null); var rootPath = Path.Combine(Globals.ApplicationMapPath, "FileSystemUtilsTest"); - PrepareRootPath(rootPath); + this.PrepareRootPath(rootPath); field.SetValue(null, rootPath); } - - + [TestCase("/")] [TestCase("//")] [TestCase("///")] @@ -49,8 +49,8 @@ public void SetUp() [TestCase("..\\")] public void DeleteFiles_Should_Not_Able_To_Delete_Root_Folder(string path) { - //Action - FileSystemUtils.DeleteFiles(new string[] {path}); + // Action + FileSystemUtils.DeleteFiles(new string[] { path }); var files = Directory.GetFiles(Globals.ApplicationMapPath, "*.*", SearchOption.AllDirectories); Assert.Greater(files.Length, 0); @@ -59,8 +59,8 @@ public void DeleteFiles_Should_Not_Able_To_Delete_Root_Folder(string path) [Test] public void AddToZip_Should_Able_To_Add_Multiple_Files() { - //Action - DeleteZippedFiles(); + // Action + this.DeleteZippedFiles(); var zipFilePath = Path.Combine(Globals.ApplicationMapPath, $"Test{Guid.NewGuid().ToString().Substring(0, 8)}.zip"); var files = Directory.GetFiles(Globals.ApplicationMapPath, "*.*", SearchOption.TopDirectoryOnly); using (var stream = File.Create(zipFilePath)) @@ -78,12 +78,13 @@ public void AddToZip_Should_Able_To_Add_Multiple_Files() zipStream.Close(); } - //Assert + // Assert var destPath = Path.Combine(Globals.ApplicationMapPath, Path.GetFileNameWithoutExtension(zipFilePath)); if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } + try { using (var stream = File.OpenRead(zipFilePath)) @@ -98,24 +99,24 @@ public void AddToZip_Should_Able_To_Add_Multiple_Files() } finally { - DeleteZippedFiles(); - DeleteUnzippedFolder(destPath); + this.DeleteZippedFiles(); + this.DeleteUnzippedFolder(destPath); } } [Test] public void DeleteFile_Should_Delete_File() { - //Action + // Action var testPath = Globals.ApplicationMapPath + $"/Test{Guid.NewGuid().ToString().Substring(0, 8)}.txt"; using (StreamWriter sw = File.CreateText(testPath)) { sw.WriteLine("48"); } - + FileSystemUtils.DeleteFile(testPath); - //Assert + // Assert bool res = File.Exists(testPath.Replace("/", "\\")); Assert.IsFalse(res); } @@ -127,15 +128,15 @@ public void DeleteFile_Should_Delete_File() [TestCase("Test/Test ")] public void FixPath_Should_Change_Slashes_And_Trim(string input) { - //Action + // Action var result = FileSystemUtils.FixPath(input); - //Assert + // Assert if (string.IsNullOrEmpty(input)) { Assert.IsTrue(input == result); } - else if(string.IsNullOrWhiteSpace(input)) + else if (string.IsNullOrWhiteSpace(input)) { Assert.IsTrue(result == string.Empty); } @@ -144,7 +145,6 @@ public void FixPath_Should_Change_Slashes_And_Trim(string input) Assert.IsFalse(result.Contains(" ")); Assert.IsFalse(result.Contains("/")); } - } private void PrepareRootPath(string rootPath) @@ -171,10 +171,11 @@ private void DeleteZippedFiles() } catch (Exception) { - //ignore + // ignore } } } + private void DeleteUnzippedFolder(string zippedFolder) { try @@ -183,7 +184,7 @@ private void DeleteUnzippedFolder(string zippedFolder) } catch (Exception) { - //ignore + // ignore } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs index cb4db70804a..63a2d0ca75b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Reflection; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Tests.Instance.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core.Framework.JavaScriptLibraries { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using System.Web; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Tests.Instance.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + public class JavaScriptTests { private const string ScriptPrefix = "JSL."; @@ -28,7 +29,7 @@ public class JavaScriptTests [SetUp] public void Setup() { - //fix Globals.Status + // fix Globals.Status var status = typeof(Globals).GetField("_status", BindingFlags.Static | BindingFlags.NonPublic); status.SetValue(null, Globals.UpgradeStatus.None); @@ -53,196 +54,197 @@ public void TearDown() [Test] public void CanRegisterLibraryByName() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("Test"); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void CanRegisterLibraryByNameWithMismatchedCase() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("test"); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void CanRegisterLibraryByNameAndVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 2)); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void CanRegisterLibraryByNameAndExactVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 2), SpecificVersion.Exact); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void CanRegisterLibraryByNameWithMismatchedCaseAndExactVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("test", new Version(2, 2, 2), SpecificVersion.Exact); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void FailToRegisterLibraryByNameAndMismatchedVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 0)); - //Assert + // Assert Assert.AreNotEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void FailToRegisterLibraryByNameAndMismatchedExactVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 0), SpecificVersion.Exact); - //Assert + // Assert Assert.AreNotEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void CanRegisterLibraryByNameAndSameMinorVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 0), SpecificVersion.LatestMinor); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void CanRegisterLibraryByNameWithMismatchedCaseAndSameMinorVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("test", new Version(2, 2, 0), SpecificVersion.LatestMinor); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void FallbackToHighestVersionLibraryWhenDifferentMinorVersion() { - //Arrange - int lowerVersionJavaScriptLibraryId = libraryIdCounter++; - int higherVersionJavaScriptLibraryId = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(2, 1, 0), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); - - //Act + // Arrange + int lowerVersionJavaScriptLibraryId = this.libraryIdCounter++; + int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController( + new JavaScriptLibrary + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(2, 1, 0), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); + + // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 2), SpecificVersion.LatestMinor); - //Assert + // Assert Assert.AreNotEqual(true, this._httpContext.Items[ScriptPrefix + lowerVersionJavaScriptLibraryId]); Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + higherVersionJavaScriptLibraryId]); } @@ -250,25 +252,26 @@ public void FallbackToHighestVersionLibraryWhenDifferentMinorVersion() [Test] public void FallbackToHighestVersionLibraryWhenDifferentMinorVersionWithMismatchedCase() { - //Arrange - int lowerVersionJavaScriptLibraryId = libraryIdCounter++; - int higherVersionJavaScriptLibraryId = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "test", - Version = new Version(2, 1, 0), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); - - //Act + // Arrange + int lowerVersionJavaScriptLibraryId = this.libraryIdCounter++; + int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController( + new JavaScriptLibrary + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "test", + Version = new Version(2, 1, 0), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); + + // Act JavaScript.RequestRegistration("test", new Version(2, 2, 2), SpecificVersion.LatestMinor); - //Assert + // Assert Assert.AreNotEqual(true, this._httpContext.Items[ScriptPrefix + lowerVersionJavaScriptLibraryId]); Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + higherVersionJavaScriptLibraryId]); } @@ -276,63 +279,64 @@ public void FallbackToHighestVersionLibraryWhenDifferentMinorVersionWithMismatch [Test] public void CanRegisterLibraryByNameAndSameMajorVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("Test", new Version(2, 1, 1), SpecificVersion.LatestMajor); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void CanRegisterLibraryByNameWithMismatchedCaseAndSameMajorVersion() { - //Arrange - int JavaScriptLibraryID = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary + // Arrange + int JavaScriptLibraryID = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController(new JavaScriptLibrary { JavaScriptLibraryID = JavaScriptLibraryID, LibraryName = "Test", Version = new Version(2, 2, 2), }); - //Act + // Act JavaScript.RequestRegistration("test", new Version(2, 1, 1), SpecificVersion.LatestMajor); - //Assert + // Assert Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + JavaScriptLibraryID]); } [Test] public void FallbackToHighestVersionLibraryWhenDifferentMajorVersion() { - //Arrange - int lowerVersionJavaScriptLibraryId = libraryIdCounter++; - int higherVersionJavaScriptLibraryId = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(1, 2, 2), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); - - //Act + // Arrange + int lowerVersionJavaScriptLibraryId = this.libraryIdCounter++; + int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController( + new JavaScriptLibrary + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(1, 2, 2), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); + + // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 2), SpecificVersion.LatestMajor); - //Assert + // Assert Assert.AreNotEqual(true, this._httpContext.Items[ScriptPrefix + lowerVersionJavaScriptLibraryId]); Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + higherVersionJavaScriptLibraryId]); } @@ -340,25 +344,26 @@ public void FallbackToHighestVersionLibraryWhenDifferentMajorVersion() [Test] public void FallbackToHighestVersionLibraryWhenDifferentMajorVersionWithMismatchedCase() { - //Arrange - int lowerVersionJavaScriptLibraryId = libraryIdCounter++; - int higherVersionJavaScriptLibraryId = libraryIdCounter++; - SetupJavaScriptLibraryController(new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "test", - Version = new Version(1, 2, 2), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); - - //Act + // Arrange + int lowerVersionJavaScriptLibraryId = this.libraryIdCounter++; + int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; + this.SetupJavaScriptLibraryController( + new JavaScriptLibrary + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "test", + Version = new Version(1, 2, 2), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); + + // Act JavaScript.RequestRegistration("test", new Version(2, 2, 2), SpecificVersion.LatestMajor); - //Assert + // Assert Assert.AreNotEqual(true, this._httpContext.Items[ScriptPrefix + lowerVersionJavaScriptLibraryId]); Assert.AreEqual(true, this._httpContext.Items[ScriptPrefix + higherVersionJavaScriptLibraryId]); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/ServicesFrameworkTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/ServicesFrameworkTests.cs index 82673af1ffd..08b3d132a8f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/ServicesFrameworkTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/ServicesFrameworkTests.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.Framework; -using DotNetNuke.Tests.Instance.Utilities; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Framework { + using System; + + using DotNetNuke.Framework; + using DotNetNuke.Tests.Instance.Utilities; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + public class ServicesFrameworkTests { [SetUp] @@ -19,7 +19,6 @@ public void Setup() HttpContextHelper.RegisterMockHttpContext(); var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", "c:\\"); simulator.SimulateRequest(new Uri("http://localhost/dnn/Default.aspx")); - } [TearDown] @@ -31,19 +30,19 @@ public void TearDown() [Test] public void RequestingAjaxAntiForgeryIsNoted() { - //Arrange + // Arrange - //Act + // Act ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - //Assert + // Assert Assert.IsTrue(ServicesFrameworkInternal.Instance.IsAjaxAntiForgerySupportRequired); } [Test] public void NoAjaxAntiForgeryRequestMeansNotRequired() { - //Assert + // Assert Assert.IsFalse(ServicesFrameworkInternal.Instance.IsAjaxAntiForgerySupportRequired); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs index f8c564cf973..04e935e69b3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Builders { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Tests.Utilities; + internal class FileInfoBuilder { private int fileId; @@ -19,17 +20,17 @@ internal class FileInfoBuilder private DateTime endDate; private bool enablePublishPeriod; private int folderMappingID; - + internal FileInfoBuilder() { - fileId = Constants.FOLDER_ValidFileId; - portalId = Constants.CONTENT_ValidPortalId; - startDate = DateTime.Today; - endDate = DateTime.MaxValue; - enablePublishPeriod = false; - contentItemId = Null.NullInteger; - folderMappingID = Constants.FOLDER_ValidFolderMappingID; - folderId = Constants.FOLDER_ValidFolderId; + this.fileId = Constants.FOLDER_ValidFileId; + this.portalId = Constants.CONTENT_ValidPortalId; + this.startDate = DateTime.Today; + this.endDate = DateTime.MaxValue; + this.enablePublishPeriod = false; + this.contentItemId = Null.NullInteger; + this.folderMappingID = Constants.FOLDER_ValidFolderMappingID; + this.folderId = Constants.FOLDER_ValidFolderId; } internal FileInfoBuilder WithFileId(int fileId) @@ -64,17 +65,17 @@ internal FileInfoBuilder WithEnablePublishPeriod(bool enablePublishPeriod) internal FileInfo Build() { - return new FileInfo - { - FileId = fileId, - PortalId = portalId, - StartDate = startDate, - EnablePublishPeriod = enablePublishPeriod, - EndDate = endDate, - ContentItemID = contentItemId, - FolderMappingID = folderMappingID, - FolderId = folderId - }; + return new FileInfo + { + FileId = this.fileId, + PortalId = this.portalId, + StartDate = this.startDate, + EnablePublishPeriod = this.enablePublishPeriod, + EndDate = this.endDate, + ContentItemID = this.contentItemId, + FolderMappingID = this.folderMappingID, + FolderId = this.folderId, + }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FolderInfoBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FolderInfoBuilder.cs index a54e381a9e4..c2ce4adbd90 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FolderInfoBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FolderInfoBuilder.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Tests.Utilities; -using Moq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Builders { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Tests.Utilities; + using Moq; + internal class FolderInfoBuilder { private int portalId; @@ -17,16 +18,17 @@ internal class FolderInfoBuilder private string folderPath; private string physicalPath; private int folderMappingID; - + internal FolderInfoBuilder() { - portalId = Constants.CONTENT_ValidPortalId; - folderPath = Constants.FOLDER_ValidFolderRelativePath; - physicalPath = Constants.FOLDER_ValidFolderPath; - folderMappingID = Constants.FOLDER_ValidFolderMappingID; - folderId = Constants.FOLDER_ValidFolderId; - physicalPath = ""; + this.portalId = Constants.CONTENT_ValidPortalId; + this.folderPath = Constants.FOLDER_ValidFolderRelativePath; + this.physicalPath = Constants.FOLDER_ValidFolderPath; + this.folderMappingID = Constants.FOLDER_ValidFolderMappingID; + this.folderId = Constants.FOLDER_ValidFolderId; + this.physicalPath = string.Empty; } + internal FolderInfoBuilder WithPhysicalPath(string phisicalPath) { this.physicalPath = phisicalPath; @@ -41,13 +43,13 @@ internal FolderInfoBuilder WithFolderId(int folderId) internal IFolderInfo Build() { - var mock = new Mock(); - mock.Setup(f => f.FolderID).Returns(folderId); - mock.Setup(f => f.PortalID).Returns(portalId); - mock.Setup(f => f.FolderPath).Returns(folderPath); - mock.Setup(f => f.PhysicalPath).Returns(physicalPath); - mock.Setup(f => f.FolderMappingID).Returns(folderMappingID); - + var mock = new Mock(); + mock.Setup(f => f.FolderID).Returns(this.folderId); + mock.Setup(f => f.PortalID).Returns(this.portalId); + mock.Setup(f => f.FolderPath).Returns(this.folderPath); + mock.Setup(f => f.PhysicalPath).Returns(this.physicalPath); + mock.Setup(f => f.FolderMappingID).Returns(this.folderMappingID); + return mock.Object; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs index 7341ce4f8d9..1992aad09bc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs @@ -1,51 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Caching; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Providers.Caching; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Caching { + using System; + using System.Web.Caching; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Providers.Caching; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + /// - /// Summary description for DataCacheTests + /// Summary description for DataCacheTests. /// [TestFixture] public class DataCacheTests { - private Mock mockCache; - - #region Test Initialization and Cleanup - + private Mock mockCache; + [SetUp] public void SetUp() { - //Create a Container + // Create a Container ComponentFactory.Container = new SimpleContainer(); - mockCache = MockComponentProvider.CreateNew(); - } - - #endregion - - #region GetCache Tests - + this.mockCache = MockComponentProvider.CreateNew(); + } + [Test] public void DataCache_GetCache_Should_Return_On_Correct_CacheKey() { // Arrange - mockCache.Setup(cache => cache.GetItem(GetDnnCacheKey(Constants.CACHEING_ValidKey))).ReturnsValidValue(); + this.mockCache.Setup(cache => cache.GetItem(this.GetDnnCacheKey(Constants.CACHEING_ValidKey))).ReturnsValidValue(); // Act object cacheValue = DataCache.GetCache(Constants.CACHEING_ValidKey); @@ -59,7 +51,7 @@ public void DataCache_GetCache_Should_Return_On_Correct_CacheKey() public void DataCache_GetCache_Should_Return_Null_On_Incorrect_CacheKey() { // Arrange - mockCache.Setup(cache => cache.GetItem(GetDnnCacheKey(Constants.CACHEING_InValidKey))).Returns(null); + this.mockCache.Setup(cache => cache.GetItem(this.GetDnnCacheKey(Constants.CACHEING_InValidKey))).Returns(null); // Act object cacheValue = DataCache.GetCache(Constants.CACHEING_InValidKey); @@ -74,17 +66,13 @@ public void DataCache_GetCache_Should_Return_Null_On_Incorrect_CacheKey() public void DataCache_GetCache_Should_Throw_On_NullOrEmpty_CacheKey(string key) { Assert.Throws(() => DataCache.GetCache(key)); - } - - #endregion - - #region GetCache Tests - + } + [Test] public void DataCache_GetCacheOfT_Should_Return_On_Correct_CacheKey() { // Arrange - mockCache.Setup(cache => cache.GetItem(GetDnnCacheKey(Constants.CACHEING_ValidKey))).ReturnsValidValue(); + this.mockCache.Setup(cache => cache.GetItem(this.GetDnnCacheKey(Constants.CACHEING_ValidKey))).ReturnsValidValue(); // Act object cacheValue = DataCache.GetCache(Constants.CACHEING_ValidKey); @@ -98,7 +86,7 @@ public void DataCache_GetCacheOfT_Should_Return_On_Correct_CacheKey() public void DataCache_GetCacheOfT_Should_Return_Null_On_Incorrect_CacheKey() { // Arrange - mockCache.Setup(cache => cache.GetItem(GetDnnCacheKey(Constants.CACHEING_InValidKey))).Returns(null); + this.mockCache.Setup(cache => cache.GetItem(this.GetDnnCacheKey(Constants.CACHEING_InValidKey))).Returns(null); // Act object cacheValue = DataCache.GetCache(Constants.CACHEING_InValidKey); @@ -113,12 +101,8 @@ public void DataCache_GetCacheOfT_Should_Return_Null_On_Incorrect_CacheKey() public void DataCache_GetCacheOfT_Should_Throw_On_NullOrEmpty_CacheKey(string key) { Assert.Throws(() => DataCache.GetCache(key)); - } - - #endregion - - #region RemoveCache Tests - + } + [Test] public void DataCache_RemoveCache_Should_Succeed_On_Valid_CacheKey() { @@ -128,7 +112,7 @@ public void DataCache_RemoveCache_Should_Succeed_On_Valid_CacheKey() DataCache.RemoveCache(Constants.CACHEING_ValidKey); // Assert - mockCache.Verify(cache => cache.Remove(GetDnnCacheKey(Constants.CACHEING_ValidKey))); + this.mockCache.Verify(cache => cache.Remove(this.GetDnnCacheKey(Constants.CACHEING_ValidKey))); } [Test] @@ -137,14 +121,8 @@ public void DataCache_RemoveCache_Should_Succeed_On_Valid_CacheKey() public void DataCache_RemoveCache_Should_Throw_On_NullOrEmpty_CacheKey(string key) { Assert.Throws(() => DataCache.RemoveCache(key)); - } - - #endregion - - #region SetCache Tests - - #region SetCache(string, object) Tests - + } + [Test] [TestCase(null)] [TestCase("")] @@ -163,27 +141,24 @@ public void DataCache_SetCache_Should_Succeed_On_Valid_CacheKey_And_Any_Value() // Assert DNNCacheDependency dep = null; - mockCache.Verify( + this.mockCache.Verify( cache => - cache.Insert(GetDnnCacheKey(Constants.CACHEING_ValidKey), - Constants.CACHEING_ValidValue, - dep, - Cache.NoAbsoluteExpiration, - Cache.NoSlidingExpiration, - CacheItemPriority.Normal, - DataCache.ItemRemovedCallback)); - } - - #endregion - - #region SetCache(string, object, CacheDependency) Tests - + cache.Insert( + this.GetDnnCacheKey(Constants.CACHEING_ValidKey), + Constants.CACHEING_ValidValue, + dep, + Cache.NoAbsoluteExpiration, + Cache.NoSlidingExpiration, + CacheItemPriority.Normal, + DataCache.ItemRemovedCallback)); + } + [Test] [TestCase(null)] [TestCase("")] public void DataCache_SetCache_With_Dependency_Should_Throw_On_Null_CacheKey(string key) { - DNNCacheDependency dep = CreateTestDependency(); // Dependency type or value doesn't matter + DNNCacheDependency dep = this.CreateTestDependency(); // Dependency type or value doesn't matter Assert.Throws(() => DataCache.SetCache(key, Constants.CACHEING_ValidValue, dep)); } @@ -191,27 +166,24 @@ public void DataCache_SetCache_With_Dependency_Should_Throw_On_Null_CacheKey(str public void DataCache_SetCache_With_Dependency_Should_Succeed_On_Valid_CacheKey_And_Any_Value() { // Arrange - DNNCacheDependency dep = CreateTestDependency(); // Dependency type or value doesn't matter + DNNCacheDependency dep = this.CreateTestDependency(); // Dependency type or value doesn't matter // Act DataCache.SetCache(Constants.CACHEING_ValidKey, Constants.CACHEING_ValidValue, dep); // Assert - mockCache.Verify( + this.mockCache.Verify( cache => - cache.Insert(GetDnnCacheKey(Constants.CACHEING_ValidKey), - Constants.CACHEING_ValidValue, - dep, - Cache.NoAbsoluteExpiration, - Cache.NoSlidingExpiration, - CacheItemPriority.Normal, - DataCache.ItemRemovedCallback)); - } - - #endregion - - #region SetCache(string, object, DateTime) Tests - + cache.Insert( + this.GetDnnCacheKey(Constants.CACHEING_ValidKey), + Constants.CACHEING_ValidValue, + dep, + Cache.NoAbsoluteExpiration, + Cache.NoSlidingExpiration, + CacheItemPriority.Normal, + DataCache.ItemRemovedCallback)); + } + [Test] [TestCase(null)] [TestCase("")] @@ -232,21 +204,18 @@ public void DataCache_SetCache_With_AbsoluteExpiration_Should_Succeed_On_Valid_C // Assert DNNCacheDependency dep = null; - mockCache.Verify( + this.mockCache.Verify( cache => - cache.Insert(GetDnnCacheKey(Constants.CACHEING_ValidKey), - Constants.CACHEING_ValidValue, - dep, - absExpiry, - Cache.NoSlidingExpiration, - CacheItemPriority.Normal, - DataCache.ItemRemovedCallback)); - } - - #endregion - - #region SetCache(string, object, TimeSpan) Tests - + cache.Insert( + this.GetDnnCacheKey(Constants.CACHEING_ValidKey), + Constants.CACHEING_ValidValue, + dep, + absExpiry, + Cache.NoSlidingExpiration, + CacheItemPriority.Normal, + DataCache.ItemRemovedCallback)); + } + [Test] [TestCase(null)] [TestCase("")] @@ -268,27 +237,24 @@ public void DataCache_SetCache_With_SlidingExpiration_Should_Succeed_On_Valid_Ca // Assert // Assert DNNCacheDependency dep = null; - mockCache.Verify( + this.mockCache.Verify( cache => - cache.Insert(GetDnnCacheKey(Constants.CACHEING_ValidKey), - Constants.CACHEING_ValidValue, - dep, - Cache.NoAbsoluteExpiration, - slidingExpiry, - CacheItemPriority.Normal, - DataCache.ItemRemovedCallback)); - } - - #endregion - - #region SetCache(string, object, CacheDependency, DateTime, TimeSpan) Tests - + cache.Insert( + this.GetDnnCacheKey(Constants.CACHEING_ValidKey), + Constants.CACHEING_ValidValue, + dep, + Cache.NoAbsoluteExpiration, + slidingExpiry, + CacheItemPriority.Normal, + DataCache.ItemRemovedCallback)); + } + [Test] [TestCase(null)] [TestCase("")] public void DataCache_SetCache_With_CacheDependency_AbsoluteExpiration_SlidingExpiration_Should_Throw_On_Null_CacheKey(string key) { - DNNCacheDependency dep = CreateTestDependency(); // Dependency type or value doesn't matter + DNNCacheDependency dep = this.CreateTestDependency(); // Dependency type or value doesn't matter DateTime absExpiry = DateTime.Today.AddDays(1); // DateTime doesn't matter TimeSpan slidingExpiry = TimeSpan.FromMinutes(5); // TimeSpan doesn't matter Assert.Throws(() => DataCache.SetCache(key, Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry)); @@ -298,7 +264,7 @@ public void DataCache_SetCache_With_CacheDependency_AbsoluteExpiration_SlidingEx public void DataCache_SetCache_With_CacheDependency_AbsoluteExpiration_SlidingExpiration_Should_Succeed_On_Valid_CacheKey_And_Any_Value() { // Arrange - DNNCacheDependency dep = CreateTestDependency(); // Dependency type or value doesn't matter + DNNCacheDependency dep = this.CreateTestDependency(); // Dependency type or value doesn't matter DateTime absExpiry = DateTime.Today.AddDays(1); // DateTime doesn't matter TimeSpan slidingExpiry = TimeSpan.FromMinutes(5); // TimeSpan doesn't matter @@ -306,21 +272,17 @@ public void DataCache_SetCache_With_CacheDependency_AbsoluteExpiration_SlidingEx DataCache.SetCache(Constants.CACHEING_ValidKey, Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry); // Assert - mockCache.Verify( + this.mockCache.Verify( cache => - cache.Insert(GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, DataCache.ItemRemovedCallback)); - } - - #endregion - - #region SetCache(string, object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback) Tests - + cache.Insert(this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, DataCache.ItemRemovedCallback)); + } + [Test] [TestCase(null)] [TestCase("")] public void DataCache_SetCache_With_Priority_Should_Throw_On_Null_CacheKey(string key) { - DNNCacheDependency dep = CreateTestDependency(); // Dependency type or value doesn't matter + DNNCacheDependency dep = this.CreateTestDependency(); // Dependency type or value doesn't matter DateTime absExpiry = DateTime.Today.AddDays(1); // DateTime doesn't matter TimeSpan slidingExpiry = TimeSpan.FromMinutes(5); // TimeSpan doesn't matter CacheItemPriority priority = CacheItemPriority.High; // Priority doesn't matter @@ -331,7 +293,7 @@ public void DataCache_SetCache_With_Priority_Should_Throw_On_Null_CacheKey(strin public void DataCache_SetCache_With_Priority_Should_Succeed_On_Valid_CacheKey_And_Any_Value() { // Arrange - DNNCacheDependency dep = CreateTestDependency(); // Dependency type or value doesn't matter + DNNCacheDependency dep = this.CreateTestDependency(); // Dependency type or value doesn't matter DateTime absExpiry = DateTime.Today.AddDays(1); // DateTime doesn't matter TimeSpan slidingExpiry = TimeSpan.FromMinutes(5); // TimeSpan doesn't matter CacheItemPriority priority = CacheItemPriority.High; // Priority doesn't matter @@ -340,32 +302,26 @@ public void DataCache_SetCache_With_Priority_Should_Succeed_On_Valid_CacheKey_An DataCache.SetCache(Constants.CACHEING_ValidKey, Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, priority, null); // Assert - mockCache.Verify(cache => cache.Insert(GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, priority, DataCache.ItemRemovedCallback)); + this.mockCache.Verify(cache => cache.Insert(this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, priority, DataCache.ItemRemovedCallback)); } [Test] public void DataCache_SetCache_With_Callback_Should_Succeed_On_Valid_CacheKey_And_Any_Value() { // Arrange - DNNCacheDependency dep = CreateTestDependency(); // Dependency type or value doesn't matter + DNNCacheDependency dep = this.CreateTestDependency(); // Dependency type or value doesn't matter DateTime absExpiry = DateTime.Today.AddDays(1); // DateTime doesn't matter TimeSpan slidingExpiry = TimeSpan.FromMinutes(5); // TimeSpan doesn't matter - CacheItemRemovedCallback callback = ItemRemovedCallback; + CacheItemRemovedCallback callback = this.ItemRemovedCallback; // Act - DataCache.SetCache(Constants.CACHEING_ValidKey, Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, ItemRemovedCallback); + DataCache.SetCache(Constants.CACHEING_ValidKey, Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, this.ItemRemovedCallback); // Assert - mockCache.Verify( - cache => cache.Insert(GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, ItemRemovedCallback)); - } - - #endregion - - #endregion - - #region Private Helper Methods - + this.mockCache.Verify( + cache => cache.Insert(this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, this.ItemRemovedCallback)); + } + private DNNCacheDependency CreateTestDependency() { return new DNNCacheDependency("C:\\testdependency.txt"); @@ -373,14 +329,12 @@ private DNNCacheDependency CreateTestDependency() private string GetDnnCacheKey(string cacheKey) { - return String.Format("DNN_{0}", cacheKey); + return string.Format("DNN_{0}", cacheKey); } private void ItemRemovedCallback(string key, object value, CacheItemRemovedReason removedReason) { - //do nothing - } - - #endregion + // do nothing + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/MoqExtensions.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/MoqExtensions.cs index 7f408363ddb..2662bb7f32c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/MoqExtensions.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/MoqExtensions.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Utilities; - -using Moq.Language.Flow; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Providers.Caching { + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Utilities; + using Moq.Language.Flow; + public static class MoqExtensions { public static IReturnsResult ReturnsValidValue(this ISetup ret) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs index 68c4d9df704..343967a2053 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs @@ -1,75 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + [TestFixture] public class DatabaseFolderProviderTests - { - #region Private Variables - + { private DatabaseFolderProvider _dfp; private Mock _mockData; private Mock _folderInfo; private Mock _fileInfo; private Mock _folderManager; - private Mock _fileManager; - - #endregion - - #region Setup & TearDown - + private Mock _fileManager; + [SetUp] public void Setup() { - _dfp = new DatabaseFolderProvider(); - _mockData = MockComponentProvider.CreateDataProvider(); - _folderInfo = new Mock(); - _fileInfo = new Mock(); - _folderManager = new Mock(); - _fileManager = new Mock(); + this._dfp = new DatabaseFolderProvider(); + this._mockData = MockComponentProvider.CreateDataProvider(); + this._folderInfo = new Mock(); + this._fileInfo = new Mock(); + this._folderManager = new Mock(); + this._fileManager = new Mock(); - FolderManager.RegisterInstance(_folderManager.Object); - FileManager.RegisterInstance(_fileManager.Object); + FolderManager.RegisterInstance(this._folderManager.Object); + FileManager.RegisterInstance(this._fileManager.Object); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() { var stream = new Mock(); - _dfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); + this._dfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); } [Test] @@ -80,57 +68,49 @@ public void AddFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock(); - _dfp.AddFile(_folderInfo.Object, fileName, stream.Object); - } - - #endregion - - #region DeleteFile - + this._dfp.AddFile(this._folderInfo.Object, fileName, stream.Object); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() { - _dfp.DeleteFile(null); + this._dfp.DeleteFile(null); } [Test] public void DeleteFile_Calls_DataProvider_ClearFileContent() { - _fileInfo.Setup(fi => fi.FileId).Returns(Constants.FOLDER_ValidFileId); + this._fileInfo.Setup(fi => fi.FileId).Returns(Constants.FOLDER_ValidFileId); - _dfp.DeleteFile(_fileInfo.Object); - - _mockData.Verify(md => md.ClearFileContent(Constants.FOLDER_ValidFileId), Times.Once()); - } - - #endregion - - #region FileExists + this._dfp.DeleteFile(this._fileInfo.Object); + this._mockData.Verify(md => md.ClearFileContent(Constants.FOLDER_ValidFileId), Times.Once()); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() { - _dfp.FileExists(null, Constants.FOLDER_ValidFileName); + this._dfp.FileExists(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_FileName() { - _dfp.FileExists(_folderInfo.Object, null); + this._dfp.FileExists(this._folderInfo.Object, null); } [Test] public void ExistsFile_Returns_True_When_File_Exists() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _fileManager.Setup(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, true)).Returns(new FileInfo()); + this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true)).Returns(new FileInfo()); - var result = _dfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._dfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsTrue(result); } @@ -138,26 +118,22 @@ public void ExistsFile_Returns_True_When_File_Exists() [Test] public void ExistsFile_Returns_False_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); FileInfo file = null; - _fileManager.Setup(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(file); + this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(file); - var result = _dfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._dfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); - } - - #endregion - - #region FolderExists - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderMapping() { - _dfp.FolderExists(Constants.FOLDER_ValidFolderPath, null); + this._dfp.FolderExists(Constants.FOLDER_ValidFolderPath, null); } [Test] @@ -166,7 +142,7 @@ public void ExistsFolder_Throws_On_Null_FolderPath() { var folderMapping = new FolderMappingInfo(); - _dfp.FolderExists(null, folderMapping); + this._dfp.FolderExists(null, folderMapping); } [Test] @@ -175,9 +151,9 @@ public void ExistsFolder_Returns_True_When_Folder_Exists() var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; - _folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(new FolderInfo()); + this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(new FolderInfo()); - var result = _dfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + var result = this._dfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsTrue(result); } @@ -189,34 +165,26 @@ public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() folderMapping.PortalID = Constants.CONTENT_ValidPortalId; FolderInfo folder = null; - _folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(folder); + this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(folder); - var result = _dfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + var result = this._dfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsFalse(result); - } - - #endregion - - #region GetFileAttributes - + } + [Test] public void GetFileAttributes_Returns_Null() { - var result = _dfp.GetFileAttributes(It.IsAny()); + var result = this._dfp.GetFileAttributes(It.IsAny()); Assert.IsNull(result); - } - - #endregion - - #region GetFiles - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFiles_Throws_On_Null_Folder() { - _dfp.GetFiles(null); + this._dfp.GetFiles(null); } [Test] @@ -224,33 +192,33 @@ public void GetFiles_Calls_FolderManager_GetFilesByFolder() { var fileInfos = new List { - new FileInfo { FileName = "" }, - new FileInfo { FileName = "" }, - new FileInfo { FileName = "" } + new FileInfo { FileName = string.Empty }, + new FileInfo { FileName = string.Empty }, + new FileInfo { FileName = string.Empty }, }; - _folderManager.Setup(fm => fm.GetFiles(_folderInfo.Object)).Returns((IList)fileInfos); + this._folderManager.Setup(fm => fm.GetFiles(this._folderInfo.Object)).Returns((IList)fileInfos); - _dfp.GetFiles(_folderInfo.Object); + this._dfp.GetFiles(this._folderInfo.Object); - _folderManager.Verify(fm => fm.GetFiles(_folderInfo.Object), Times.Once()); + this._folderManager.Verify(fm => fm.GetFiles(this._folderInfo.Object), Times.Once()); } [Test] public void GetFiles_Count_Equals_DataProvider_GetFiles_Count() { - var expectedFiles = new string[] { "", "", "" }; + var expectedFiles = new string[] { string.Empty, string.Empty, string.Empty }; var fileInfos = new List { - new FileInfo { FileName = "" }, - new FileInfo { FileName = "" }, - new FileInfo { FileName = "" } + new FileInfo { FileName = string.Empty }, + new FileInfo { FileName = string.Empty }, + new FileInfo { FileName = string.Empty }, }; - _folderManager.Setup(fm => fm.GetFiles(_folderInfo.Object)).Returns((IList)fileInfos); + this._folderManager.Setup(fm => fm.GetFiles(this._folderInfo.Object)).Returns((IList)fileInfos); - var files = _dfp.GetFiles(_folderInfo.Object); + var files = this._dfp.GetFiles(this._folderInfo.Object); Assert.AreEqual(expectedFiles.Length, files.Length); } @@ -264,45 +232,41 @@ public void GetFiles_Returns_Valid_FileNames_When_Folder_Contains_Files() { new FileInfo { FileName = "file1.txt" }, new FileInfo { FileName = "file2.txt" }, - new FileInfo { FileName = "file3.txt" } + new FileInfo { FileName = "file3.txt" }, }; - _folderManager.Setup(fm => fm.GetFiles(_folderInfo.Object)).Returns((IList)fileInfos); + this._folderManager.Setup(fm => fm.GetFiles(this._folderInfo.Object)).Returns((IList)fileInfos); - var files = _dfp.GetFiles(_folderInfo.Object); + var files = this._dfp.GetFiles(this._folderInfo.Object); CollectionAssert.AreEqual(expectedFiles, files); - } - - #endregion - - #region GetFileContent - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileStream_Throws_On_Null_Folder() { - _dfp.GetFileStream(null, Constants.FOLDER_ValidFileName); + this._dfp.GetFileStream(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentException))] public void GetFileStream_Throws_On_NullOrEmpty_FileName() { - _dfp.GetFileStream(_folderInfo.Object, null); + this._dfp.GetFileStream(this._folderInfo.Object, null); } [Test] public void GetFileStream_Calls_FileManager_GetFile() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _fileManager.Setup(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns((IFileInfo)null); + this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns((IFileInfo)null); - _dfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._dfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _fileManager.Verify(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, true), Times.Once()); + this._fileManager.Verify(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true), Times.Once()); } [Test] @@ -310,20 +274,20 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { var validFileBytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); var _filesTable = new DataTable("Files"); _filesTable.Columns.Add("Content", typeof(byte[])); _filesTable.Rows.Add(validFileBytes); - _mockData.Setup(md => md.GetFileContent(Constants.FOLDER_ValidFileId)).Returns(_filesTable.CreateDataReader()); + this._mockData.Setup(md => md.GetFileContent(Constants.FOLDER_ValidFileId)).Returns(_filesTable.CreateDataReader()); - _fileManager.Setup(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, true)) + this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true)) .Returns(new FileInfo { FileId = Constants.FOLDER_ValidFileId, PortalId = Constants.CONTENT_ValidPortalId }); - var result = _dfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._dfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); byte[] resultBytes; var buffer = new byte[16 * 1024]; @@ -334,6 +298,7 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { ms.Write(buffer, 0, read); } + resultBytes = ms.ToArray(); } @@ -343,55 +308,43 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() [Test] public void GetFileStream_Returns_Null_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _fileManager.Setup(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())) + this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())) .Returns((IFileInfo)null); - var result = _dfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._dfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsNull(result); - } - - #endregion - - #region GetFolderProviderIconPath - + } + [Test] public void GetImageUrl_Calls_IconControllerWrapper_IconURL() { var iconControllerWrapper = new Mock(); IconControllerWrapper.RegisterInstance(iconControllerWrapper.Object); - _dfp.GetFolderProviderIconPath(); + this._dfp.GetFolderProviderIconPath(); iconControllerWrapper.Verify(icw => icw.IconURL("FolderDatabase", "32x32"), Times.Once()); - } - - #endregion - - #region GetLastModificationTime - + } + [Test] public void GetLastModificationTime_Returns_Null_Date() { var expectedResult = Null.NullDate; - var result = _dfp.GetLastModificationTime(_fileInfo.Object); + var result = this._dfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedResult, result); - } - - #endregion - - #region GetSubFolders - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderMapping() { - _dfp.GetSubFolders(Constants.FOLDER_ValidFolderPath, null).ToList(); + this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderPath, null).ToList(); } [Test] @@ -400,7 +353,7 @@ public void GetSubFolders_Throws_On_Null_FolderPath() { var folderMappingInfo = new FolderMappingInfo(); - _dfp.GetSubFolders(null, folderMappingInfo).ToList(); + this._dfp.GetSubFolders(null, folderMappingInfo).ToList(); } [Test] @@ -409,12 +362,12 @@ public void GetSubFolders_Calls_FolderManager_GetFoldersByParentFolder() var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; - _folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); - _folderManager.Setup(fm => fm.GetFolders(_folderInfo.Object)).Returns(new List()); + this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolders(this._folderInfo.Object)).Returns(new List()); - _dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); - _folderManager.Verify(fm => fm.GetFolders(_folderInfo.Object), Times.Once()); + this._folderManager.Verify(fm => fm.GetFolders(this._folderInfo.Object), Times.Once()); } [Test] @@ -423,15 +376,16 @@ public void GetSubFolders_Count_Equals_DataProvider_GetFoldersByParentFolder_Cou var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; - var subFolders = new List() { + var subFolders = new List() + { new FolderInfo { FolderPath = Constants.FOLDER_ValidSubFolderRelativePath }, - new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath } + new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath }, }; - _folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); - _folderManager.Setup(fm => fm.GetFolders(_folderInfo.Object)).Returns(subFolders); + this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolders(this._folderInfo.Object)).Returns(subFolders); - var result = _dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + var result = this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); Assert.AreEqual(subFolders.Count, result.Count); } @@ -439,62 +393,52 @@ public void GetSubFolders_Count_Equals_DataProvider_GetFoldersByParentFolder_Cou [Test] public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() { - var expectedResult = new List { + var expectedResult = new List + { Constants.FOLDER_ValidSubFolderRelativePath, - Constants.FOLDER_OtherValidSubFolderRelativePath + Constants.FOLDER_OtherValidSubFolderRelativePath, }; var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; - var subFolders = new List { + var subFolders = new List + { new FolderInfo { FolderPath = Constants.FOLDER_ValidSubFolderRelativePath }, - new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath } + new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath }, }; - _folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); - _folderManager.Setup(fm => fm.GetFolders(_folderInfo.Object)).Returns(subFolders); + this._folderManager.Setup(fm => fm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolders(this._folderInfo.Object)).Returns(subFolders); - var result = _dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + var result = this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); CollectionAssert.AreEqual(expectedResult, result); - } - - #endregion - - #region IsInSync - + } + [Test] public void IsInSync_Returns_True() { - var result = _dfp.IsInSync(It.IsAny()); + var result = this._dfp.IsInSync(It.IsAny()); Assert.IsTrue(result); - } - - #endregion - - #region SupportsFileAttributes - + } + [Test] public void SupportsFileAttributes_Returns_False() { - var result = _dfp.SupportsFileAttributes(); + var result = this._dfp.SupportsFileAttributes(); Assert.IsFalse(result); - } - - #endregion - - #region UpdateFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Folder() { var stream = new Mock(); - - _dfp.UpdateFile(null, Constants.FOLDER_ValidFileName, stream.Object); + + this._dfp.UpdateFile(null, Constants.FOLDER_ValidFileName, stream.Object); } [Test] @@ -505,37 +449,35 @@ public void UpdateFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock(); - _dfp.UpdateFile(_folderInfo.Object, fileName, stream.Object); + this._dfp.UpdateFile(this._folderInfo.Object, fileName, stream.Object); } [Test] public void UpdateFile_Calls_DataProvider_UpdateFileContent_When_File_Exists() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _fileInfo.Setup(fi => fi.FileId).Returns(Constants.FOLDER_ValidFileId); + this._fileInfo.Setup(fi => fi.FileId).Returns(Constants.FOLDER_ValidFileId); - _fileManager.Setup(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, true)).Returns(_fileInfo.Object); + this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, true)).Returns(this._fileInfo.Object); - _dfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, new MemoryStream(new byte[16 * 1024])); + this._dfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, new MemoryStream(new byte[16 * 1024])); - _mockData.Verify(md => md.UpdateFileContent(Constants.FOLDER_ValidFileId, It.IsAny()), Times.Once()); + this._mockData.Verify(md => md.UpdateFileContent(Constants.FOLDER_ValidFileId, It.IsAny()), Times.Once()); } [Test] public void UpdateFile_Does_Not_Call_DataProvider_UpdateFileContent_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _fileManager.Setup(fm => fm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns((IFileInfo)null); + this._fileManager.Setup(fm => fm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns((IFileInfo)null); - _dfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, null); - - _mockData.Verify(md => md.UpdateFileContent(It.IsAny(), It.IsAny()), Times.Never()); - } + this._dfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); - #endregion + this._mockData.Verify(md => md.UpdateFileContent(It.IsAny(), It.IsAny()), Times.Never()); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs index 8dd42cce1f4..37b60981f8f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs @@ -1,20 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - -using DotNetNuke.Services.FileSystem.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System.Collections.Generic; + + using DotNetNuke.Services.FileSystem.Internal; + using NUnit.Framework; + [TestFixture] public class DefaultFolderProvidersTests - { - #region GetDefaultProviders Tests - + { [Test] public void GetDefaultProviders_Should_Return_3_Valid_Providers() { @@ -23,8 +20,6 @@ public void GetDefaultProviders_Should_Return_3_Valid_Providers() var defaultProviders = DefaultFolderProviders.GetDefaultProviders(); CollectionAssert.AreEqual(expectedValues, defaultProviders); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs index ac61e9a1394..a245a53dbe5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs @@ -1,55 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Drawing; -using System.IO; -using System.Reflection; -using System.Text; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.Security.Permissions; -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + using System.Collections.Generic; + using System.Data; + using System.Drawing; + using System.IO; + using System.Reflection; + using System.Text; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class FileContentTypeManagerTests - { - #region Private Variables - - - #endregion - - #region Setup & TearDown - + { [SetUp] public void Setup() { - var _mockData = MockComponentProvider.CreateDataProvider(); - var _mockCache = MockComponentProvider.CreateDataCacheProvider(); - var _globals = new Mock(); - var _cbo = new Mock(); + var _mockData = MockComponentProvider.CreateDataProvider(); + var _mockCache = MockComponentProvider.CreateDataCacheProvider(); + var _globals = new Mock(); + var _cbo = new Mock(); - _mockData.Setup(m => m.GetProviderPath()).Returns(String.Empty); + _mockData.Setup(m => m.GetProviderPath()).Returns(string.Empty); - TestableGlobals.SetTestableInstance(_globals.Object); - CBO.SetTestableInstance(_cbo.Object); + TestableGlobals.SetTestableInstance(_globals.Object); + CBO.SetTestableInstance(_cbo.Object); } [TearDown] @@ -57,12 +50,8 @@ public void TearDown() { TestableGlobals.ClearInstance(); CBO.ClearInstance(); - } - - #endregion - - #region GetContentType - + } + [Test] public void GetContentType_Returns_Known_Value_When_Extension_Is_Not_Managed() { @@ -73,16 +62,14 @@ public void GetContentType_Returns_Known_Value_When_Extension_Is_Not_Managed() Assert.AreEqual("application/octet-stream", contentType); } - [Test] - public void GetContentType_Returns_Correct_Value_For_Extension() - { - const string notManagedExtension = "htm"; - - var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); + [Test] + public void GetContentType_Returns_Correct_Value_For_Extension() + { + const string notManagedExtension = "htm"; - Assert.AreEqual("text/html", contentType); - } + var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); - #endregion + Assert.AreEqual("text/html", contentType); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs index e3753a7fc92..4b50cc9d7a9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs @@ -1,46 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Tests.Core.Providers.Builders; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Tests.Core.Providers.Builders; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + public class FileDeletionControllerTests { - private Mock _mockFileLockingController; + private Mock _mockFileLockingController; private Mock _mockData; private Mock _fileVersionController; private Mock _folderMappingController; private Mock _mockFolderProvider; private Mock _mockContentController; - + [SetUp] public void Setup() { - _mockFileLockingController = new Mock(); - _mockData = MockComponentProvider.CreateDataProvider(); - _fileVersionController = new Mock(); - _folderMappingController = new Mock(); - _mockFolderProvider = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); - _mockContentController = new Mock(); - - FileLockingController.SetTestableInstance(_mockFileLockingController.Object); - FileVersionController.RegisterInstance(_fileVersionController.Object); - FolderMappingController.RegisterInstance(_folderMappingController.Object); - - ComponentFactory.RegisterComponentInstance(_mockContentController.Object); + this._mockFileLockingController = new Mock(); + this._mockData = MockComponentProvider.CreateDataProvider(); + this._fileVersionController = new Mock(); + this._folderMappingController = new Mock(); + this._mockFolderProvider = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); + this._mockContentController = new Mock(); + + FileLockingController.SetTestableInstance(this._mockFileLockingController.Object); + FileVersionController.RegisterInstance(this._fileVersionController.Object); + FolderMappingController.RegisterInstance(this._folderMappingController.Object); + + ComponentFactory.RegisterComponentInstance(this._mockContentController.Object); } [TearDown] @@ -53,115 +53,114 @@ public void TearDown() [Test] public void DeleteFile_Calls_FolderProviderDeleteFile() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder().Build(); - _fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); + this._fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - _mockData.Setup(md => md.DeleteFile(It.IsAny(), It.IsAny(), It.IsAny())); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockData.Setup(md => md.DeleteFile(It.IsAny(), It.IsAny(), It.IsAny())); - _mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)).Verifiable(); + this._mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)).Verifiable(); string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); - //Act + // Act FileDeletionController.Instance.DeleteFile(fileInfo); - //Assert - _mockFolderProvider.Verify(); + // Assert + this._mockFolderProvider.Verify(); } [Test] [ExpectedException(typeof(FileLockedException))] public void DeleteFile_Throws_WhenFileIsLocked() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder().Build(); - + string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(true); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(true); - //Act - FileDeletionController.Instance.DeleteFile(fileInfo); + // Act + FileDeletionController.Instance.DeleteFile(fileInfo); } [Test] [ExpectedException(typeof(FolderProviderException))] public void DeleteFile_Throws_WhenFolderProviderThrows() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder().Build(); - - _fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); + + this._fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); - - _mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)).Throws(); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); - + this._mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)).Throws(); + FileDeletionController.Instance.DeleteFile(fileInfo); } [Test] public void DeleteFileData_Calls_DataProviderDeleteFile() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder().Build(); - _fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); + this._fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - _mockData.Setup(md => md.DeleteFile(Constants.CONTENT_ValidPortalId, It.IsAny(), Constants.FOLDER_ValidFolderId)).Verifiable(); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)); + this._mockData.Setup(md => md.DeleteFile(Constants.CONTENT_ValidPortalId, It.IsAny(), Constants.FOLDER_ValidFolderId)).Verifiable(); + + this._mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)); string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); - //Act + // Act FileDeletionController.Instance.DeleteFileData(fileInfo); - //Assert - _mockData.Verify(); + // Assert + this._mockData.Verify(); } [Test] public void DeleteFileData_Calls_ContentControllerDeleteContentItem() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder() .WithContentItemId(Constants.CONTENT_ValidContentItemId) .Build(); - - _fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); + + this._fileVersionController.Setup(fv => fv.DeleteAllUnpublishedVersions(fileInfo, false)); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockData.Setup(md => md.DeleteFile(It.IsAny(), It.IsAny(), It.IsAny())); + this._mockData.Setup(md => md.DeleteFile(It.IsAny(), It.IsAny(), It.IsAny())); - _mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)); + this._mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)); - _mockContentController.Setup(mcc => mcc.DeleteContentItem(Constants.CONTENT_ValidContentItemId)).Verifiable(); + this._mockContentController.Setup(mcc => mcc.DeleteContentItem(Constants.CONTENT_ValidContentItemId)).Verifiable(); string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); - //Act + // Act FileDeletionController.Instance.DeleteFileData(fileInfo); - //Assert - _mockContentController.Verify(); + // Assert + this._mockContentController.Verify(); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs index 4cfa236beb8..4898fb2825f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs @@ -1,71 +1,69 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Tests.Core.Providers.Builders; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Tests.Core.Providers.Builders; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class FileLockingControllerTests { - private Mock _mockWorkFlowEngine; + private Mock _mockWorkFlowEngine; private Mock _mockUserSecurityController; - + [SetUp] public void Setup() { - _mockWorkFlowEngine = new Mock(); - _mockUserSecurityController = new Mock(); - - WorkflowEngine.SetTestableInstance(_mockWorkFlowEngine.Object); - UserSecurityController.SetTestableInstance(_mockUserSecurityController.Object); + this._mockWorkFlowEngine = new Mock(); + this._mockUserSecurityController = new Mock(); + WorkflowEngine.SetTestableInstance(this._mockWorkFlowEngine.Object); + UserSecurityController.SetTestableInstance(this._mockUserSecurityController.Object); } [TearDown] public void TearDown() - { - UserSecurityController.ClearInstance(); + { + UserSecurityController.ClearInstance(); MockComponentProvider.ResetContainer(); - } - - #region IsFileLocked Method Tests + } + [Test] public void IsFileLocked_ReturnsTrue_WhenPublishPeriodIsOut() { - //Arrange - //_fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - //_fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - //_fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - //_fileInfo.Setup(fi => fi.EnablePublishPeriod).Returns(true); - //_fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Today.AddDays(-2)); - //_fileInfo.Setup(fi => fi.EndDate).Returns(DateTime.Today.AddDays(-1)); - //_fileInfo.Setup(fi => fi.ContentItemID).Returns(Null.NullInteger); + // Arrange + // _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + // _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + // _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + // _fileInfo.Setup(fi => fi.EnablePublishPeriod).Returns(true); + // _fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Today.AddDays(-2)); + // _fileInfo.Setup(fi => fi.EndDate).Returns(DateTime.Today.AddDays(-1)); + // _fileInfo.Setup(fi => fi.ContentItemID).Returns(Null.NullInteger); var fileInfo = new FileInfoBuilder() .WithStartDate(DateTime.Today.AddDays(-2)) .WithEndDate(DateTime.Today.AddDays(-1)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); - //Act + // Act string someReason; var result = FileLockingController.Instance.IsFileLocked(fileInfo, out someReason); - //Assert + // Assert Assert.IsTrue(result); Assert.AreEqual(someReason, "FileLockedOutOfPublishPeriodError"); } @@ -73,21 +71,21 @@ public void IsFileLocked_ReturnsTrue_WhenPublishPeriodIsOut() [Test] public void IsFileLocked_ReturnsTrue_WhenWorkflowIsNotComplete() { - //Arrange - var fileInfo = new FileInfoBuilder() + // Arrange + var fileInfo = new FileInfoBuilder() .WithEndDate(DateTime.Today.AddDays(2)) .WithEnablePublishPeriod(true) .WithContentItemId(It.IsAny()) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); - _mockWorkFlowEngine.Setup(mwc => mwc.IsWorkflowCompleted(It.IsAny())).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); + this._mockWorkFlowEngine.Setup(mwc => mwc.IsWorkflowCompleted(It.IsAny())).Returns(false); - //Act + // Act string someReason; var result = FileLockingController.Instance.IsFileLocked(fileInfo, out someReason); - //Assert + // Assert Assert.IsTrue(result); Assert.AreEqual(someReason, "FileLockedRunningWorkflowError"); } @@ -95,159 +93,155 @@ public void IsFileLocked_ReturnsTrue_WhenWorkflowIsNotComplete() [Test] public void IsFileLocked_ReturnsFalse_WhenUserIsHostOrAdmin() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder() .WithStartDate(DateTime.Today.AddDays(-2)) .WithEndDate(DateTime.Today.AddDays(-1)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(true); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(true); - //Act + // Act string someReason; var result = FileLockingController.Instance.IsFileLocked(fileInfo, out someReason); - //Assert + // Assert Assert.IsFalse(result); } [Test] public void IsFileLocked_ReturnsFalse_WhenPublishPeriodIsIn() { - //Arrange - var fileInfo = new FileInfoBuilder() + // Arrange + var fileInfo = new FileInfoBuilder() .WithEndDate(DateTime.Today.AddDays(2)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); - //Act + // Act string someReason; var result = FileLockingController.Instance.IsFileLocked(fileInfo, out someReason); - //Assert + // Assert Assert.IsFalse(result); } [Test] public void IsFileLocked_ReturnsFalse_WhenPublishPeriodHasNotEndDate() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder() .WithEndDate(DateTime.Today.AddDays(2)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); - //Act + // Act string someReason; var result = FileLockingController.Instance.IsFileLocked(fileInfo, out someReason); - //Assert + // Assert Assert.IsFalse(result); } [Test] public void IsFileLocked_ReturnsFalse_WhenPublishPeriodIsDisabled() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder().Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(Constants.CONTENT_ValidPortalId)).Returns(false); - //Act + // Act string someReason; var result = FileLockingController.Instance.IsFileLocked(fileInfo, out someReason); - //Assert + // Assert Assert.IsFalse(result); - } - #endregion - - #region IsFileOutOfPublishPeriod Method Tests + } + [Test] public void IsFileOutOfPublishPeriod_ReturnsTrue_WhenPublishPeriodIsOut() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder() .WithStartDate(DateTime.Today.AddDays(-2)) .WithEndDate(DateTime.Today.AddDays(-1)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); - - //Act - var result = FileLockingController.Instance.IsFileOutOfPublishPeriod(fileInfo, It.IsAny(),It.IsAny()); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); + + // Act + var result = FileLockingController.Instance.IsFileOutOfPublishPeriod(fileInfo, It.IsAny(), It.IsAny()); - //Assert + // Assert Assert.IsTrue(result); } [Test] public void IsFileOutOfPublishPeriod_ReturnsFalse_WhenUserIsHostOrAdmin() { - //Arrange + // Arrange var fileInfo = new FileInfoBuilder() .WithStartDate(DateTime.Today.AddDays(-2)) .WithEndDate(DateTime.Today.AddDays(-1)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(true); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(true); - //Act + // Act var result = FileLockingController.Instance.IsFileOutOfPublishPeriod(fileInfo, It.IsAny(), It.IsAny()); - //Assert + // Assert Assert.IsFalse(result); } [Test] public void IsFileOutOfPublishPeriod_ReturnsFalse_WhenPublishPeriodIsIn() { - //Arrange - var fileInfo = new FileInfoBuilder() + // Arrange + var fileInfo = new FileInfoBuilder() .WithEndDate(DateTime.Today.AddDays(2)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); - //Act + // Act var result = FileLockingController.Instance.IsFileOutOfPublishPeriod(fileInfo, It.IsAny(), It.IsAny()); - //Assert + // Assert Assert.IsFalse(result); } [Test] public void IsFileOutOfPublishPeriod_ReturnsFalse_WhenPublishPeriodHasNotEndDate() { - //Arrange - var fileInfo = new FileInfoBuilder() + // Arrange + var fileInfo = new FileInfoBuilder() .WithEndDate(DateTime.Today.AddDays(2)) .WithEnablePublishPeriod(true) .Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); - //Act + // Act var result = FileLockingController.Instance.IsFileOutOfPublishPeriod(fileInfo, It.IsAny(), It.IsAny()); - //Assert + // Assert Assert.IsFalse(result); } [Test] public void IsFileOutOfPublishPeriod_ReturnsFalse_WhenPublishPeriodIsDisabled() { - //Arrange - + // Arrange var fileInfo = new FileInfoBuilder().Build(); - _mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); + this._mockUserSecurityController.Setup(msc => msc.IsHostAdminUser(It.IsAny(), It.IsAny())).Returns(false); - //Act + // Act var result = FileLockingController.Instance.IsFileOutOfPublishPeriod(fileInfo, It.IsAny(), It.IsAny()); - //Assert + // Assert Assert.IsFalse(result); - } - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs index 1eb7fbe8c82..e0585b69ce0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs @@ -1,42 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Drawing; -using System.IO; -using System.Reflection; -using System.Text; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Workflow; -using DotNetNuke.Entities.Content.Workflow.Entities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Log.EventLog; -using Moq; - -using NUnit.Framework; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + using System.Collections.Generic; + using System.Data; + using System.Drawing; + using System.IO; + using System.Reflection; + using System.Text; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Entities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + [TestFixture] public class FileManagerTests - { - #region Private Variables - + { private FileManager _fileManager; private Mock _folderManager; private Mock _folderPermissionController; @@ -56,54 +54,50 @@ public class FileManagerTests private Mock> _fileEventHandlersContainer; private Mock _mockFileLockingController; private Mock _mockFileDeletionController; - private Mock _hostController; - - #endregion - - #region Setup & TearDown - + private Mock _hostController; + [SetUp] public void Setup() { - _mockData = MockComponentProvider.CreateDataProvider(); - _mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); - _mockCache = MockComponentProvider.CreateDataCacheProvider(); - - _folderManager = new Mock(); - _folderPermissionController = new Mock(); - _portalController = new Mock(); - _hostController = new Mock(); - _folderMappingController = new Mock(); - _fileVersionController = new Mock(); - _workflowManager = new Mock(); - _fileEventHandlersContainer = new Mock>(); - _globals = new Mock(); - _cbo = new Mock(); - _pathUtils = new Mock(); - _mockFileLockingController = new Mock(); - _mockFileDeletionController = new Mock(); - + this._mockData = MockComponentProvider.CreateDataProvider(); + this._mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); + this._mockCache = MockComponentProvider.CreateDataCacheProvider(); + + this._folderManager = new Mock(); + this._folderPermissionController = new Mock(); + this._portalController = new Mock(); + this._hostController = new Mock(); + this._folderMappingController = new Mock(); + this._fileVersionController = new Mock(); + this._workflowManager = new Mock(); + this._fileEventHandlersContainer = new Mock>(); + this._globals = new Mock(); + this._cbo = new Mock(); + this._pathUtils = new Mock(); + this._mockFileLockingController = new Mock(); + this._mockFileDeletionController = new Mock(); + EventLogController.SetTestableInstance(Mock.Of()); - FolderManager.RegisterInstance(_folderManager.Object); - FolderPermissionController.SetTestableInstance(_folderPermissionController.Object); - PortalController.SetTestableInstance(_portalController.Object); - HostController.RegisterInstance(_hostController.Object); - FolderMappingController.RegisterInstance(_folderMappingController.Object); - TestableGlobals.SetTestableInstance(_globals.Object); - CBO.SetTestableInstance(_cbo.Object); - PathUtils.RegisterInstance(_pathUtils.Object); - FileVersionController.RegisterInstance(_fileVersionController.Object); - WorkflowManager.SetTestableInstance(_workflowManager.Object); - EventHandlersContainer.RegisterInstance(_fileEventHandlersContainer.Object); - _mockFileManager = new Mock { CallBase = true }; - - _folderInfo = new Mock(); - _fileInfo = new Mock(); - - _fileManager = new FileManager(); - - FileLockingController.SetTestableInstance(_mockFileLockingController.Object); - FileDeletionController.SetTestableInstance(_mockFileDeletionController.Object); + FolderManager.RegisterInstance(this._folderManager.Object); + FolderPermissionController.SetTestableInstance(this._folderPermissionController.Object); + PortalController.SetTestableInstance(this._portalController.Object); + HostController.RegisterInstance(this._hostController.Object); + FolderMappingController.RegisterInstance(this._folderMappingController.Object); + TestableGlobals.SetTestableInstance(this._globals.Object); + CBO.SetTestableInstance(this._cbo.Object); + PathUtils.RegisterInstance(this._pathUtils.Object); + FileVersionController.RegisterInstance(this._fileVersionController.Object); + WorkflowManager.SetTestableInstance(this._workflowManager.Object); + EventHandlersContainer.RegisterInstance(this._fileEventHandlersContainer.Object); + this._mockFileManager = new Mock { CallBase = true }; + + this._folderInfo = new Mock(); + this._fileInfo = new Mock(); + + this._fileManager = new FileManager(); + + FileLockingController.SetTestableInstance(this._mockFileLockingController.Object); + FileDeletionController.SetTestableInstance(this._mockFileDeletionController.Object); } [TearDown] @@ -117,18 +111,13 @@ public void TearDown() FileDeletionController.ClearInstance(); MockComponentProvider.ResetContainer(); PortalController.ClearInstance(); - - } - - #endregion - - #region AddFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() { - _fileManager.AddFile(null, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); + this._fileManager.AddFile(null, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); } [Test] @@ -137,112 +126,102 @@ public void AddFile_Throws_On_Null_Folder() [ExpectedException(typeof(ArgumentException))] public void AddFile_Throws_On_Null_Or_Empty_FileName(string fileName) { - _fileManager.AddFile(_folderInfo.Object, fileName, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); + this._fileManager.AddFile(this._folderInfo.Object, fileName, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()); } [Test] [ExpectedException(typeof(ArgumentException))] public void AddFile_Throws_On_Null_FileContent() { - _fileManager.AddFile(_folderInfo.Object, It.IsAny(), null, It.IsAny(), It.IsAny(), It.IsAny()); + this._fileManager.AddFile(this._folderInfo.Object, It.IsAny(), null, It.IsAny(), It.IsAny(), It.IsAny()); } [Test] [ExpectedException(typeof(PermissionsNotMetException))] public void AddFile_Throws_When_Permissions_Are_Not_Met() { - _folderPermissionController.Setup(fpc => fpc.CanAddFolder(_folderInfo.Object)).Returns(false); + this._folderPermissionController.Setup(fpc => fpc.CanAddFolder(this._folderInfo.Object)).Returns(false); - _fileManager.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, new MemoryStream(), It.IsAny(), true, It.IsAny()); + this._fileManager.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, new MemoryStream(), It.IsAny(), true, It.IsAny()); } [Test] [ExpectedException(typeof(NoSpaceAvailableException))] public void AddFile_Throws_When_Portal_Has_No_Space_Available() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _mockData.Setup(c => c.GetProviderPath()).Returns(String.Empty); + this._mockData.Setup(c => c.GetProviderPath()).Returns(string.Empty); var fileContent = new MemoryStream(); - _globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(false); - - _mockFileManager.Setup(fm => fm.CreateFileContentItem()).Returns(new ContentItem()); - _mockFileManager.Setup(fm => fm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); + this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(false); - _mockFileManager.Object.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + this._mockFileManager.Setup(fm => fm.CreateFileContentItem()).Returns(new ContentItem()); + this._mockFileManager.Setup(fm => fm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); + + this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); } [Test] public void AddFile_Checks_Space_For_Stream_Length() { - //Arrange - PrepareFileSecurityCheck(); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); + // Arrange + this.PrepareFileSecurityCheck(); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); var fileContent = new MemoryStream(Encoding.ASCII.GetBytes("some data here")); - _portalController.Setup(pc => pc.HasSpaceAvailable(It.IsAny(), It.IsAny())).Returns(true); - - _globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); - + this._portalController.Setup(pc => pc.HasSpaceAvailable(It.IsAny(), It.IsAny())).Returns(true); + this._globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - _mockFolder.Setup(mf => mf.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); - _mockFolder.Setup(mf => mf.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); - - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); - _mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); - _mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); - + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _workflowManager.Setup(we => we.GetWorkflow(It.IsAny())).Returns((Workflow)null); + this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); + this._mockFolder.Setup(mf => mf.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); - //Act - _mockFileManager.Object.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, false, Constants.CONTENTTYPE_ValidContentType); + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); + this._mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); + + this._workflowManager.Setup(we => we.GetWorkflow(It.IsAny())).Returns((Workflow)null); - //Assert - _portalController.Verify(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)); - } + // Act + this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, false, Constants.CONTENTTYPE_ValidContentType); - class UnSeekableStream : MemoryStream - { - public override bool CanSeek - { - get { return false; } - } + // Assert + this._portalController.Verify(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)); } [Test] [ExpectedException(typeof(InvalidFileExtensionException))] public void AddFile_Throws_When_Extension_Is_Invalid() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var fileContent = new MemoryStream(); - _portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(false); + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(false); - _mockFileManager.Object.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); } [TestCase("invalid_script.svg")] @@ -251,35 +230,111 @@ public void AddFile_Throws_When_Extension_Is_Invalid() [ExpectedException(typeof(InvalidFileContentException))] public void AddFile_Throws_When_File_Content_Is_Invalid(string fileName) { - PrepareFileSecurityCheck(); + this.PrepareFileSecurityCheck(); using (var fileContent = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Resources\\{fileName}"))) { - _portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); + this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); - _mockFileManager.Object.AddFile(_folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); } } [Test] public void AddFile_No_Error_When_File_Content_Is_Valid() { - PrepareFileSecurityCheck(); + this.PrepareFileSecurityCheck(); using (var fileContent = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\valid.svg"))) { - _portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); - _mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); + this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidSvgFileName)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); + + this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + } + } - _mockFileManager.Object.AddFile(_folderInfo.Object, Constants.FOLDER_ValidSvgFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + private class UnSeekableStream : MemoryStream + { + public override bool CanSeek + { + get { return false; } } } + [Test] + public void AddFile_Does_Not_Call_FolderProvider_AddFile_When_Not_Overwritting_And_File_Exists() + { + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); + + var fileContent = new MemoryStream(); + + this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); + + this._globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); + this._mockFolder.Setup(mf => mf.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)); + this._mockFolder.Setup(mf => mf.GetHashCode(It.IsAny())).Returns("aaa"); + + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.UpdateFile(It.IsAny(), It.IsAny())); + this._mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); + + this._workflowManager.Setup(wc => wc.GetWorkflow(It.IsAny())).Returns((Workflow)null); + + this._mockData.Setup( + md => + md.AddFile( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Returns(Constants.FOLDER_ValidFileId); + + this._mockData.Setup(md => md.UpdateFileLastModificationTime(It.IsAny(), It.IsAny())); + + this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); + + this._mockFolder.Verify(mf => mf.AddFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void CopyFile_Throws_On_Null_File() + { + this._fileManager.CopyFile(null, this._folderInfo.Object); + } + private void PrepareFileSecurityCheck() { - _mockData.Setup(p => p.GetListEntriesByListName("FileSecurityChecker", string.Empty, Null.NullInteger)).Returns(() => + this._mockData.Setup(p => p.GetListEntriesByListName("FileSecurityChecker", string.Empty, Null.NullInteger)).Returns(() => { var dataTable = new DataTable(); dataTable.Columns.Add("EntryID", typeof(int)); @@ -306,97 +361,26 @@ private void PrepareFileSecurityCheck() dataTable.Rows.Add(1, "FileSecurityChecker", "svg", "DotNetNuke.Services.FileSystem.Internal.SecurityCheckers.SvgFileChecker, DotNetNuke", - 0, 0, -1, -0, "", -1, 1, "", "", "", 0, 1, 0, -1, DateTime.Now, -1, DateTime.Now); + 0, 0, -1, -0, string.Empty, -1, 1, string.Empty, string.Empty, string.Empty, 0, 1, 0, -1, DateTime.Now, -1, DateTime.Now); return dataTable.CreateDataReader(); }); - _hostController.Setup(c => c.GetString("PerformanceSetting")).Returns("NoCaching"); - _globals.Setup(g => g.HostMapPath).Returns(AppDomain.CurrentDomain.BaseDirectory); + this._hostController.Setup(c => c.GetString("PerformanceSetting")).Returns("NoCaching"); + this._globals.Setup(g => g.HostMapPath).Returns(AppDomain.CurrentDomain.BaseDirectory); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - } - - [Test] - public void AddFile_Does_Not_Call_FolderProvider_AddFile_When_Not_Overwritting_And_File_Exists() - { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderInfo.Setup(fi => fi.WorkflowID).Returns(Null.NullInteger); - - var fileContent = new MemoryStream(); - - _portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)).Returns(true); - - _globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - _mockFolder.Setup(mf => mf.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); - _mockFolder.Setup(mf => mf.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)); - _mockFolder.Setup(mf => mf.GetHashCode(It.IsAny())).Returns("aaa"); - - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); - _mockFileManager.Setup(mfm => mfm.UpdateFile(It.IsAny(), It.IsAny())); - _mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); - - _workflowManager.Setup(wc => wc.GetWorkflow(It.IsAny())).Returns((Workflow)null); - - _mockData.Setup( - md => - md.AddFile(It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Returns(Constants.FOLDER_ValidFileId); - - _mockData.Setup(md => md.UpdateFileLastModificationTime(It.IsAny(), It.IsAny())); - - _mockFileManager.Object.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); - - _mockFolder.Verify(mf => mf.AddFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - } - - #endregion - - #region CopyFile - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void CopyFile_Throws_On_Null_File() - { - _fileManager.CopyFile(null, _folderInfo.Object); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void CopyFile_Throws_On_Null_DestinationFolder() { - _fileManager.CopyFile(_fileInfo.Object, null); + this._fileManager.CopyFile(this._fileInfo.Object, null); } [Test] @@ -405,178 +389,166 @@ public void CopyFile_Calls_FileManager_AddFile_When_FolderMapping_Of_Source_And_ const int sourceFolderMappingID = Constants.FOLDER_ValidFolderMappingID; const int destinationFolderMappingID = Constants.FOLDER_ValidFolderMappingID + 1; - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.ContentType).Returns(Constants.CONTENTTYPE_ValidContentType); - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(sourceFolderMappingID); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.ContentType).Returns(Constants.CONTENTTYPE_ValidContentType); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(sourceFolderMappingID); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(destinationFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(destinationFolderMappingID); var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var fileContent = new MemoryStream(bytes); - _mockFileManager.Setup(mfm => mfm.GetFileContent(_fileInfo.Object)).Returns(fileContent); - _mockFileManager.Setup(mfm => mfm.CopyContentItem(It.IsAny())).Returns(Constants.CONTENT_ValidContentItemId); - _mockFileManager.Setup(mfm => mfm.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny(), true, true, Constants.CONTENTTYPE_ValidContentType)); + this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); + this._mockFileManager.Setup(mfm => mfm.CopyContentItem(It.IsAny())).Returns(Constants.CONTENT_ValidContentItemId); + this._mockFileManager.Setup(mfm => mfm.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny(), true, true, Constants.CONTENTTYPE_ValidContentType)); - _mockFileManager.Object.CopyFile(_fileInfo.Object, _folderInfo.Object); + this._mockFileManager.Object.CopyFile(this._fileInfo.Object, this._folderInfo.Object); - _mockFileManager.Verify(fm => fm.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, true, Constants.CONTENTTYPE_ValidContentType), Times.Once()); + this._mockFileManager.Verify(fm => fm.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, true, true, Constants.CONTENTTYPE_ValidContentType), Times.Once()); } [Test] [ExpectedException(typeof(PermissionsNotMetException))] public void CopyFile_Throws_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Equal_And_Cannot_Add_Folder() { - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderPermissionController.Setup(fpc => fpc.CanAddFolder(_folderInfo.Object)).Returns(false); + this._folderPermissionController.Setup(fpc => fpc.CanAddFolder(this._folderInfo.Object)).Returns(false); - _fileManager.CopyFile(_fileInfo.Object, _folderInfo.Object); + this._fileManager.CopyFile(this._fileInfo.Object, this._folderInfo.Object); } [Test] [ExpectedException(typeof(NoSpaceAvailableException))] public void CopyFile_Throws_When_FolderMapping_Of_Source_And_Destination_Folders_Are_Equal_And_Portal_Has_No_Space_Available() { - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _fileInfo.Setup(fi => fi.Size).Returns(Constants.FOLDER_ValidFileSize); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - _folderPermissionController.Setup(fpc => fpc.CanAddFolder(_folderInfo.Object)).Returns(true); - _portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileSize)).Returns(false); - - _fileManager.CopyFile(_fileInfo.Object, _folderInfo.Object); - } - - #endregion + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.Size).Returns(Constants.FOLDER_ValidFileSize); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - #region DeleteFile + this._folderPermissionController.Setup(fpc => fpc.CanAddFolder(this._folderInfo.Object)).Returns(true); + this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileSize)).Returns(false); + this._fileManager.CopyFile(this._fileInfo.Object, this._folderInfo.Object); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() { - _fileManager.DeleteFile(null); + this._fileManager.DeleteFile(null); } [Test] public void DeleteFile_Calls_FileDeletionControllerDeleteFile() { - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(_fileInfo.Object)).Verifiable(); + this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(this._fileInfo.Object)).Verifiable(); - _mockFileManager.Object.DeleteFile(_fileInfo.Object); + this._mockFileManager.Object.DeleteFile(this._fileInfo.Object); - _mockFileDeletionController.Verify(); + this._mockFileDeletionController.Verify(); } [Test] [ExpectedException(typeof(FolderProviderException))] public void DeleteFile_Throws_WhenFileDeletionControllerThrows() { - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(_fileInfo.Object)) + this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(this._fileInfo.Object)) .Throws(); - _mockFileManager.Object.DeleteFile(_fileInfo.Object); - } - - #endregion - - #region WriteFileToResponse - + this._mockFileManager.Object.DeleteFile(this._fileInfo.Object); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DownloadFile_Throws_On_Null_File() { - _fileManager.WriteFileToResponse(null, ContentDisposition.Inline); + this._fileManager.WriteFileToResponse(null, ContentDisposition.Inline); } [Test] [ExpectedException(typeof(PermissionsNotMetException))] public void DownloadFile_Throws_When_Permissions_Are_Not_Met() { - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - _folderPermissionController.Setup(fpc => fpc.CanViewFolder(_folderInfo.Object)).Returns(false); + this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(false); - _fileManager.WriteFileToResponse(_fileInfo.Object, ContentDisposition.Inline); + this._fileManager.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); } [Test] public void DownloadFile_Calls_FileManager_AutoSyncFile_When_File_AutoSync_Is_Enabled() { - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - _folderPermissionController.Setup(fpc => fpc.CanViewFolder(_folderInfo.Object)).Returns(true); + this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(true); - _mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(true); - _mockFileManager.Setup(mfm => mfm.AutoSyncFile(_fileInfo.Object)).Verifiable(); - _mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(_fileInfo.Object, It.IsAny())); + this._mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(true); + this._mockFileManager.Setup(mfm => mfm.AutoSyncFile(this._fileInfo.Object)).Verifiable(); + this._mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this._fileInfo.Object, It.IsAny())); - _mockFileManager.Object.WriteFileToResponse(_fileInfo.Object, ContentDisposition.Inline); + this._mockFileManager.Object.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); - _mockFileManager.Verify(); + this._mockFileManager.Verify(); } [Test] public void DownloadFile_Does_Not_Call_FileManager_AutoSyncFile_When_File_AutoSync_Is_Not_Enabled() { - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - _folderPermissionController.Setup(fpc => fpc.CanViewFolder(_folderInfo.Object)).Returns(true); + this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(true); - _mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); - _mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(_fileInfo.Object, It.IsAny())); + this._mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); + this._mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this._fileInfo.Object, It.IsAny())); - _mockFileManager.Object.WriteFileToResponse(_fileInfo.Object, ContentDisposition.Inline); + this._mockFileManager.Object.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); - _mockFileManager.Verify(mfm => mfm.AutoSyncFile(_fileInfo.Object), Times.Never()); + this._mockFileManager.Verify(mfm => mfm.AutoSyncFile(this._fileInfo.Object), Times.Never()); } [Test] public void DownloadFile_Calls_FileManager_WriteBytesToHttpContext() { - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - _folderPermissionController.Setup(fpc => fpc.CanViewFolder(_folderInfo.Object)).Returns(true); - - _mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); - _mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(_fileInfo.Object, It.IsAny())).Verifiable(); - - _mockFileManager.Object.WriteFileToResponse(_fileInfo.Object, ContentDisposition.Inline); - - _mockFileManager.Verify(); - } + this._folderPermissionController.Setup(fpc => fpc.CanViewFolder(this._folderInfo.Object)).Returns(true); - #endregion + this._mockFileManager.Setup(mfm => mfm.IsFileAutoSyncEnabled()).Returns(false); + this._mockFileManager.Setup(mfm => mfm.WriteFileToHttpContext(this._fileInfo.Object, It.IsAny())).Verifiable(); - #region FileExists + this._mockFileManager.Object.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); + this._mockFileManager.Verify(); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() { - _fileManager.FileExists(null, It.IsAny()); + this._fileManager.FileExists(null, It.IsAny()); } [Test] @@ -585,62 +557,62 @@ public void ExistsFile_Throws_On_Null_Folder() [ExpectedException(typeof(ArgumentException))] public void ExistsFile_Throws_On_Null_Or_Empty_FileName(string fileName) { - _fileManager.FileExists(_folderInfo.Object, fileName); + this._fileManager.FileExists(this._folderInfo.Object, fileName); } [Test] public void ExistsFile_Calls_FileManager_GetFile() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _mockFileManager.Setup(mfm => mfm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(null).Verifiable(); + this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(null).Verifiable(); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFileManager.Object.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _mockFileManager.Verify(); + this._mockFileManager.Verify(); } [Test] public void ExistsFile_Calls_FolderProvider_ExistsFile() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _mockFileManager.Setup(mfm => mfm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(_fileInfo.Object); + this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true).Verifiable(); + this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true).Verifiable(); - _mockFileManager.Object.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _mockFolder.Verify(); + this._mockFolder.Verify(); } [Test] public void ExistsFile_Returns_True_When_File_Exists() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _mockFileManager.Setup(mfm => mfm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(_fileInfo.Object); + this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); + this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(true); - var result = _mockFileManager.Object.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsTrue(result); } @@ -648,19 +620,19 @@ public void ExistsFile_Returns_True_When_File_Exists() [Test] public void ExistsFile_Returns_False_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _mockFileManager.Setup(mfm => mfm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(_fileInfo.Object); + this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); + this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Returns(false); - var result = _mockFileManager.Object.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); } @@ -669,234 +641,218 @@ public void ExistsFile_Returns_False_When_File_Does_Not_Exist() [ExpectedException(typeof(FolderProviderException))] public void ExistsFile_Throws_When_FolderProvider_Throws() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _mockFileManager.Setup(mfm => mfm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(_fileInfo.Object); + this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(this._fileInfo.Object); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName)).Throws(); - - _mockFileManager.Object.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); - } - - #endregion - - #region GetFile + this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Throws(); + this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); + } + [Test] [TestCase(null)] [TestCase("")] [ExpectedException(typeof(ArgumentException))] public void GetFile_Throws_On_Null_Or_Empty_FileName(string fileName) { - _fileManager.GetFile(_folderInfo.Object, fileName); + this._fileManager.GetFile(this._folderInfo.Object, fileName); } [Test] public void GetFile_Calls_DataProvider_GetFile() { - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); + this._mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); - _fileManager.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._fileManager.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _mockData.Verify(); + this._mockData.Verify(); } [Test] public void GetFile_Handles_Path_In_Portal_Root() { - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, "")).Returns(_folderInfo.Object).Verifiable(); - _mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, string.Empty)).Returns(this._folderInfo.Object).Verifiable(); + this._mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); - _fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileName); + this._fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileName); - _folderManager.Verify(); - _mockData.Verify(); + this._folderManager.Verify(); + this._mockData.Verify(); } [Test] public void GetFile_Handles_Path_Beyond_Portal_Root() { - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object).Verifiable(); - _mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); - - _fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath + Constants.FOLDER_ValidFileName); - - _folderManager.Verify(); - _mockData.Verify(); - } - - #endregion + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderManager.Setup(x => x.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object).Verifiable(); + this._mockData.Setup(md => md.GetFile(Constants.FOLDER_ValidFileName, Constants.FOLDER_ValidFolderId, It.IsAny())).Returns(It.IsAny()).Verifiable(); - #region GetFile + this._fileManager.GetFile(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath + Constants.FOLDER_ValidFileName); + this._folderManager.Verify(); + this._mockData.Verify(); + } + [Test] public void GetFileByID_Does_Not_Call_DataCache_GetCache_If_FileId_Is_Not_Valid() { - _mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(_fileInfo.Object).Verifiable(); + this._mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(this._fileInfo.Object).Verifiable(); - _fileManager.GetFile(Constants.FOLDER_InvalidFileId); + this._fileManager.GetFile(Constants.FOLDER_InvalidFileId); - _mockCache.Verify(mc => mc.GetItem(It.IsAny()), Times.Never()); + this._mockCache.Verify(mc => mc.GetItem(It.IsAny()), Times.Never()); } [Test] public void GetFileByID_Calls_DataCache_GetCache_First() { - _mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(_fileInfo.Object).Verifiable(); + this._mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(this._fileInfo.Object).Verifiable(); - _fileManager.GetFile(Constants.FOLDER_ValidFileId); + this._fileManager.GetFile(Constants.FOLDER_ValidFileId); - _mockCache.Verify(); + this._mockCache.Verify(); } [Test] public void GetFileByID_Calls_DataProvider_GetFileById_When_File_Is_Not_In_Cache() { - _mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(null); + this._mockCache.Setup(mc => mc.GetItem(It.IsAny())).Returns(null); - _fileManager.GetFile(Constants.FOLDER_ValidFileId); - - _mockData.Verify(md => md.GetFileById(Constants.FOLDER_ValidFileId, It.IsAny()), Times.Once()); - } - - #endregion - - #region MoveFile + this._fileManager.GetFile(Constants.FOLDER_ValidFileId); + this._mockData.Verify(md => md.GetFileById(Constants.FOLDER_ValidFileId, It.IsAny()), Times.Once()); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void MoveFile_Throws_On_Null_File() { - _fileManager.MoveFile(null, _folderInfo.Object); + this._fileManager.MoveFile(null, this._folderInfo.Object); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void MoveFile_Throws_On_Null_DestinationFolder() { - _fileManager.MoveFile(_fileInfo.Object, null); + this._fileManager.MoveFile(this._fileInfo.Object, null); } [Test] public void MoveFile_Calls_FolderProvider_AddFile_And_DeleteFile_And_FileManager_UpdateFile() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); var fileContent = new MemoryStream(); - _mockFileManager.Setup(mfm => mfm.GetFileContent(_fileInfo.Object)).Returns(fileContent); + this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(_fileInfo.Object, out someString)).Returns(false); - _mockFileManager.Setup(mfm => mfm.MoveVersions(_fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this._fileInfo.Object, out someString)).Returns(false); + this._mockFileManager.Setup(mfm => mfm.MoveVersions(this._fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); - _mockFolder.Setup(mf => mf.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); - _mockFolder.Setup(mf => mf.DeleteFile(_fileInfo.Object)).Verifiable(); + this._mockFolder.Setup(mf => mf.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFile(this._fileInfo.Object)).Verifiable(); - _mockFileManager.Setup(mfm => mfm.UpdateFile(_fileInfo.Object)).Verifiable(); + this._mockFileManager.Setup(mfm => mfm.UpdateFile(this._fileInfo.Object)).Verifiable(); - _mockFileManager.Object.MoveFile(_fileInfo.Object, _folderInfo.Object); + this._mockFileManager.Object.MoveFile(this._fileInfo.Object, this._folderInfo.Object); - _mockFolder.Verify(); - _mockFileManager.Verify(); + this._mockFolder.Verify(); + this._mockFileManager.Verify(); } [Test] public void MoveFile_Updates_FolderId_And_Folder() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _fileInfo.Setup(fi => fi.Folder).Returns(Constants.FOLDER_ValidFolderRelativePath); - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.Folder).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _fileInfo.SetupSet(fi => fi.FolderId = Constants.FOLDER_OtherValidFolderId).Verifiable(); - _fileInfo.SetupSet(fi => fi.Folder = Constants.FOLDER_OtherValidFolderRelativePath).Verifiable(); + this._fileInfo.SetupSet(fi => fi.FolderId = Constants.FOLDER_OtherValidFolderId).Verifiable(); + this._fileInfo.SetupSet(fi => fi.Folder = Constants.FOLDER_OtherValidFolderRelativePath).Verifiable(); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); var fileContent = new MemoryStream(); - _mockFileManager.Setup(mfm => mfm.GetFileContent(_fileInfo.Object)).Returns(fileContent); + this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(_fileInfo.Object, out someString)).Returns(false); - _mockFileManager.Setup(mfm => mfm.MoveVersions(_fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); - _mockFileManager.Object.MoveFile(_fileInfo.Object, _folderInfo.Object); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this._fileInfo.Object, out someString)).Returns(false); + this._mockFileManager.Setup(mfm => mfm.MoveVersions(this._fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); + this._mockFileManager.Object.MoveFile(this._fileInfo.Object, this._folderInfo.Object); - _fileInfo.Verify(); + this._fileInfo.Verify(); } [Test] public void MoveFile_Calls_DeleteFile_When_A_File_With_The_Same_Name_Exists_On_The_Destination_Folder() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_OtherValidFolderId); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); var fileContent = new MemoryStream(); - _mockFileManager.Setup(mfm => mfm.GetFileContent(_fileInfo.Object)).Returns(fileContent); + this._mockFileManager.Setup(mfm => mfm.GetFileContent(this._fileInfo.Object)).Returns(fileContent); string someString; - _mockFileLockingController.Setup(mflc => mflc.IsFileLocked(_fileInfo.Object, out someString)).Returns(false); - _mockFileManager.Setup(mfm => mfm.MoveVersions(_fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); + this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(this._fileInfo.Object, out someString)).Returns(false); + this._mockFileManager.Setup(mfm => mfm.MoveVersions(this._fileInfo.Object, It.IsAny(), It.IsAny(), It.IsAny())); var existingFile = new FileInfo(); - _mockFileManager.Setup(mfm => mfm.GetFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(existingFile); - - _mockFileManager.Setup(mfm => mfm.DeleteFile(existingFile)).Verifiable(); - - _mockFileManager.Object.MoveFile(_fileInfo.Object, _folderInfo.Object); - - _mockFileManager.Verify(); - } + this._mockFileManager.Setup(mfm => mfm.GetFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, It.IsAny())).Returns(existingFile); - #endregion + this._mockFileManager.Setup(mfm => mfm.DeleteFile(existingFile)).Verifiable(); - #region RenameFile + this._mockFileManager.Object.MoveFile(this._fileInfo.Object, this._folderInfo.Object); + this._mockFileManager.Verify(); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFile_Throws_On_Null_File() { - _fileManager.RenameFile(null, It.IsAny()); + this._fileManager.RenameFile(null, It.IsAny()); } [Test] @@ -905,155 +861,148 @@ public void RenameFile_Throws_On_Null_File() [ExpectedException(typeof(ArgumentException))] public void RenameFile_Throws_On_Null_Or_Empty_NewFileName(string newFileName) { - _fileManager.RenameFile(_fileInfo.Object, newFileName); + this._fileManager.RenameFile(this._fileInfo.Object, newFileName); } [Test] public void RenameFile_Calls_FolderProvider_RenameFile_When_FileNames_Are_Distinct_And_NewFileName_Does_Not_Exist() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - _mockFileManager.Setup(mfm => mfm.FileExists(_folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); - _mockFileManager.Setup(mfm => mfm.UpdateFile(_fileInfo.Object)); - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.FileExists(this._folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); + this._mockFileManager.Setup(mfm => mfm.UpdateFile(this._fileInfo.Object)); + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); var folderMapping = new FolderMappingInfo(); folderMapping.FolderProviderType = Constants.FOLDER_ValidFolderProviderType; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFileManager.Object.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherValidFileName); + this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); - _mockFolder.Verify(mf => mf.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherValidFileName), Times.Once()); + this._mockFolder.Verify(mf => mf.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName), Times.Once()); } [Test] public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_FileNames_Are_Equal() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileManager.RenameFile(_fileInfo.Object, Constants.FOLDER_ValidFileName); + this._fileManager.RenameFile(this._fileInfo.Object, Constants.FOLDER_ValidFileName); - _mockFolder.Verify(mf => mf.RenameFile(_fileInfo.Object, It.IsAny()), Times.Never()); + this._mockFolder.Verify(mf => mf.RenameFile(this._fileInfo.Object, It.IsAny()), Times.Never()); } [Test] [ExpectedException(typeof(FileAlreadyExistsException))] public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_NewFileName_Exists() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - _mockFileManager.Setup(mfm => mfm.FileExists(_folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(true); - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.FileExists(this._folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(true); + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); - _mockFileManager.Object.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherValidFileName); + this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); } [Test] [ExpectedException(typeof(InvalidFileExtensionException))] public void RenameFile_Does_Not_Call_FolderProvider_RenameFile_When_InvalidExtensionType() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); - _mockFileManager.Setup(fm => fm.IsAllowedExtension(It.IsAny())).Returns(false); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); + this._mockFileManager.Setup(fm => fm.IsAllowedExtension(It.IsAny())).Returns(false); - _mockFileManager.Object.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherInvalidFileNameExtension); + this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherInvalidFileNameExtension); } [Test] [ExpectedException(typeof(FolderProviderException))] public void RenameFile_Throws_When_FolderProvider_Throws() { - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._fileInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); - _mockFileManager.Setup(mfm => mfm.FileExists(_folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); - _mockFileManager.Setup(mfm => mfm.UpdateFile(_fileInfo.Object)); - _mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.FileExists(this._folderInfo.Object, Constants.FOLDER_OtherValidFileName, It.IsAny())).Returns(false); + this._mockFileManager.Setup(mfm => mfm.UpdateFile(this._fileInfo.Object)); + this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_OtherValidFileName)).Returns(true); var folderMapping = new FolderMappingInfo(); folderMapping.FolderProviderType = Constants.FOLDER_ValidFolderProviderType; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherValidFileName)).Throws(); - - _mockFileManager.Object.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherValidFileName); - } - - #endregion - - #region UnzipFile + this._mockFolder.Setup(mf => mf.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName)).Throws(); + this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UnzipFile_Throws_On_Null_File() { - _fileManager.UnzipFile(null, It.IsAny()); + this._fileManager.UnzipFile(null, It.IsAny()); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void UnzipFile_Throws_On_Null_DestinationFolder() { - _fileManager.UnzipFile(It.IsAny(), null); + this._fileManager.UnzipFile(It.IsAny(), null); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void UnzipFile_Throws_When_File_Extension_Is_Not_Zip() { - _fileInfo.Setup(fi => fi.Extension).Returns("txt"); + this._fileInfo.Setup(fi => fi.Extension).Returns("txt"); - _fileManager.UnzipFile(_fileInfo.Object, It.IsAny()); + this._fileManager.UnzipFile(this._fileInfo.Object, It.IsAny()); } [Test] public void UnzipFile_Calls_FileManager_ExtractFiles() { - _fileInfo.Setup(fi => fi.Extension).Returns("zip"); - - _mockFileManager.Setup(mfm => mfm.ExtractFiles(_fileInfo.Object, _folderInfo.Object, null)).Verifiable(); - - _mockFileManager.Object.UnzipFile(_fileInfo.Object, _folderInfo.Object); - - _mockFileManager.Verify(); - } + this._fileInfo.Setup(fi => fi.Extension).Returns("zip"); - #endregion + this._mockFileManager.Setup(mfm => mfm.ExtractFiles(this._fileInfo.Object, this._folderInfo.Object, null)).Verifiable(); - #region UpdateFile + this._mockFileManager.Object.UnzipFile(this._fileInfo.Object, this._folderInfo.Object); + this._mockFileManager.Verify(); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_File() { - _fileManager.UpdateFile(null); + this._fileManager.UpdateFile(null); } [Test] public void UpdateFile_Calls_DataProvider_UpdateFile() { - _fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - _mockFileManager.Object.UpdateFile(_fileInfo.Object); + this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + this._mockFileManager.Object.UpdateFile(this._fileInfo.Object); - _mockData.Verify(md => md.UpdateFile( + this._mockData.Verify( + md => md.UpdateFile( It.IsAny(), It.IsAny(), It.IsAny(), @@ -1079,7 +1028,7 @@ public void UpdateFile_Calls_DataProvider_UpdateFile() [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_File_Overload() { - _fileManager.UpdateFile(null, It.IsAny()); + this._fileManager.UpdateFile(null, It.IsAny()); } [Test] @@ -1087,22 +1036,22 @@ public void UpdateFile_Sets_With_And_Height_When_File_Is_Image() { var image = new Bitmap(10, 20); - _mockFileManager.Setup(mfm => mfm.IsImageFile(_fileInfo.Object)).Returns(true); - _mockFileManager.Setup(mfm => mfm.GetImageFromStream(It.IsAny())).Returns(image); - _mockFileManager.Setup(mfm => mfm.GetHash(_fileInfo.Object)); + this._mockFileManager.Setup(mfm => mfm.IsImageFile(this._fileInfo.Object)).Returns(true); + this._mockFileManager.Setup(mfm => mfm.GetImageFromStream(It.IsAny())).Returns(image); + this._mockFileManager.Setup(mfm => mfm.GetHash(this._fileInfo.Object)); var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var stream = new MemoryStream(bytes); - _fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - _folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); - _mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); + this._mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); - _mockFileManager.Object.UpdateFile(_fileInfo.Object, stream); + this._mockFileManager.Object.UpdateFile(this._fileInfo.Object, stream); - _fileInfo.VerifySet(fi => fi.Width = 10); - _fileInfo.VerifySet(fi => fi.Height = 20); + this._fileInfo.VerifySet(fi => fi.Width = 10); + this._fileInfo.VerifySet(fi => fi.Height = 20); } [Test] @@ -1111,17 +1060,17 @@ public void UpdateFile_Sets_SHA1Hash() var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var stream = new MemoryStream(bytes); - _mockFileManager.Setup(mfm => mfm.IsImageFile(_fileInfo.Object)).Returns(false); - _mockFileManager.Setup(mfm => mfm.GetHash(stream)).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._mockFileManager.Setup(mfm => mfm.IsImageFile(this._fileInfo.Object)).Returns(false); + this._mockFileManager.Setup(mfm => mfm.GetHash(stream)).Returns(Constants.FOLDER_UnmodifiedFileHash); - _fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - _folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); - _mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); + this._mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); - _mockFileManager.Object.UpdateFile(_fileInfo.Object, stream); + this._mockFileManager.Object.UpdateFile(this._fileInfo.Object, stream); - _fileInfo.VerifySet(fi => fi.SHA1Hash = Constants.FOLDER_UnmodifiedFileHash); + this._fileInfo.VerifySet(fi => fi.SHA1Hash = Constants.FOLDER_UnmodifiedFileHash); } [Test] @@ -1130,35 +1079,31 @@ public void UpdateFile_Calls_FileManager_UpdateFile_Overload() var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var stream = new MemoryStream(bytes); - _mockFileManager.Setup(mfm => mfm.IsImageFile(_fileInfo.Object)).Returns(false); - _mockFileManager.Setup(mfm => mfm.GetHash(_fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._mockFileManager.Setup(mfm => mfm.IsImageFile(this._fileInfo.Object)).Returns(false); + this._mockFileManager.Setup(mfm => mfm.GetHash(this._fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); - _fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); + this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); - _folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); - _mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._folderMappingController.Setup(mp => mp.GetFolderMapping(It.IsAny())).Returns(new FolderMappingInfo() { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }); + this._mockFolder.Setup(fp => fp.GetHashCode(It.IsAny(), It.IsAny())).Returns(Constants.FOLDER_UnmodifiedFileHash); - _mockFileManager.Object.UpdateFile(_fileInfo.Object, stream); - - _mockFileManager.Verify(mfm => mfm.UpdateFile(_fileInfo.Object), Times.Once()); - } - - #endregion - - #region GetSeekableStream + this._mockFileManager.Object.UpdateFile(this._fileInfo.Object, stream); + this._mockFileManager.Verify(mfm => mfm.UpdateFile(this._fileInfo.Object), Times.Once()); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSeekableStream_Throws_On_Null_Stream() { - _fileManager.GetSeekableStream(null); + this._fileManager.GetSeekableStream(null); } [Test] public void GetSeekableStream_Returns_The_Same_Stream_If_It_Is_Seekable() { var inputStream = new MemoryStream(); - var seekableStream = _fileManager.GetSeekableStream(inputStream); + var seekableStream = this._fileManager.GetSeekableStream(inputStream); Assert.AreEqual(inputStream, seekableStream); } @@ -1170,15 +1115,12 @@ public void GetSeekableStream_Calls_GetHostMapPath_And_Creates_A_Temporary_FileS inputStream.Setup(s => s.CanSeek).Returns(false); inputStream.Setup(s => s.Read(It.IsAny(), It.IsAny(), It.IsAny())).Returns(0); - _mockFileManager.Setup(mfm => mfm.GetHostMapPath()).Returns("").Verifiable(); - _mockFileManager.Setup(mfm => mfm.GetAutoDeleteFileStream(It.Is((string x) => x.EndsWith(".resx")))).Returns(new MemoryStream()).Verifiable(); - - _mockFileManager.Object.GetSeekableStream(inputStream.Object); - - _mockFileManager.Verify(); - } + this._mockFileManager.Setup(mfm => mfm.GetHostMapPath()).Returns(string.Empty).Verifiable(); + this._mockFileManager.Setup(mfm => mfm.GetAutoDeleteFileStream(It.Is((string x) => x.EndsWith(".resx")))).Returns(new MemoryStream()).Verifiable(); + this._mockFileManager.Object.GetSeekableStream(inputStream.Object); - #endregion + this._mockFileManager.Verify(); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs index 49801b4a42b..14c8a1a8ef2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs @@ -1,38 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; -using System.Web.Caching; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Tests.Core.Providers.Builders; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - -using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; + using System.Web.Caching; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Tests.Core.Providers.Builders; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + + using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; + [TestFixture] public class FolderManagerTests - { - #region Private Variables - + { private FolderManager _folderManager; private Mock _mockFolder; private Mock _mockData; @@ -40,44 +36,39 @@ public class FolderManagerTests private Mock _folderInfo; private Mock _folderMappingController; private Mock _directory; - private Mock _file; + private Mock _file; private Mock _cbo; private Mock _pathUtils; private Mock _mockUserSecurityController; - private Mock _mockFileDeletionController; - - #endregion - - #region Setup & TearDown - + private Mock _mockFileDeletionController; + [SetUp] public void Setup() { - _mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); - _mockData = MockComponentProvider.CreateDataProvider(); + this._mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); + this._mockData = MockComponentProvider.CreateDataProvider(); - _folderMappingController = new Mock(); - _directory = new Mock(); - _file = new Mock(); - _cbo = new Mock(); - _pathUtils = new Mock(); - _mockUserSecurityController = new Mock(); - _mockFileDeletionController = new Mock(); + this._folderMappingController = new Mock(); + this._directory = new Mock(); + this._file = new Mock(); + this._cbo = new Mock(); + this._pathUtils = new Mock(); + this._mockUserSecurityController = new Mock(); + this._mockFileDeletionController = new Mock(); - FolderMappingController.RegisterInstance(_folderMappingController.Object); - DirectoryWrapper.RegisterInstance(_directory.Object); - FileWrapper.RegisterInstance(_file.Object); - CBO.SetTestableInstance(_cbo.Object); - PathUtils.RegisterInstance(_pathUtils.Object); - UserSecurityController.SetTestableInstance(_mockUserSecurityController.Object); - FileDeletionController.SetTestableInstance(_mockFileDeletionController.Object); + FolderMappingController.RegisterInstance(this._folderMappingController.Object); + DirectoryWrapper.RegisterInstance(this._directory.Object); + FileWrapper.RegisterInstance(this._file.Object); + CBO.SetTestableInstance(this._cbo.Object); + PathUtils.RegisterInstance(this._pathUtils.Object); + UserSecurityController.SetTestableInstance(this._mockUserSecurityController.Object); + FileDeletionController.SetTestableInstance(this._mockFileDeletionController.Object); - _mockFolderManager = new Mock { CallBase = true }; + this._mockFolderManager = new Mock { CallBase = true }; - _folderManager = new FolderManager(); - - _folderInfo = new Mock(); + this._folderManager = new FolderManager(); + this._folderInfo = new Mock(); } [TearDown] @@ -89,49 +80,45 @@ public void TearDown() CBO.ClearInstance(); FileDeletionController.ClearInstance(); MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddFolder - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFolder_Throws_On_Null_FolderPath() { - _folderManager.AddFolder(It.IsAny(), null); + this._folderManager.AddFolder(It.IsAny(), null); } - //[Test] - //public void AddFolder_Calls_FolderProvider_AddFolder() - //{ + // [Test] + // public void AddFolder_Calls_FolderProvider_AddFolder() + // { // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); // _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - // var folderMapping = new FolderMappingInfo + // var folderMapping = new FolderMappingInfo // { // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, // FolderProviderType = Constants.FOLDER_ValidFolderProviderType, // PortalID = Constants.CONTENT_ValidPortalId // }; - // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Verifiable(); + // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Verifiable(); - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath)); // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)); - // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - // _mockFolder.Verify(); - //} + // _mockFolder.Verify(); + // } - //[Test] - //[ExpectedException(typeof(FolderProviderException))] - //public void AddFolder_Throws_When_FolderProvider_Throws() - //{ + // [Test] + // [ExpectedException(typeof(FolderProviderException))] + // public void AddFolder_Throws_When_FolderProvider_Throws() + // { // var folderMapping = new FolderMappingInfo // { // PortalID = Constants.CONTENT_ValidPortalId, @@ -139,51 +126,49 @@ public void AddFolder_Throws_On_Null_FolderPath() // FolderProviderType = Constants.FOLDER_ValidFolderProviderType // }; - // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); + // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Throws(); - // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - //} + // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + // } - //[Test] - //public void AddFolder_Calls_FolderManager_CreateFolderInFileSystem_And_CreateFolderInDatabase_If_Folder_Does_Not_Exist() - //{ + // [Test] + // public void AddFolder_Calls_FolderManager_CreateFolderInFileSystem_And_CreateFolderInDatabase_If_Folder_Does_Not_Exist() + // { // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); // _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - // var folderMapping = new FolderMappingInfo + // var folderMapping = new FolderMappingInfo // { // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, // FolderProviderType = Constants.FOLDER_ValidFolderProviderType, // PortalID = Constants.CONTENT_ValidPortalId // }; - // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)); + // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)); - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath)).Verifiable(); // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); - // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - - // _mockFolderManager.Verify(); - //} + // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + // _mockFolderManager.Verify(); + // } [Test] [ExpectedException(typeof(FolderAlreadyExistsException))] public void AddFolder_Throws_When_Folder_Already_Exists() { var folderMapping = new FolderMappingInfo { - PortalID = Constants.CONTENT_ValidPortalId + PortalID = Constants.CONTENT_ValidPortalId, }; - _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(true); - - _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(true); + this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); } [Test] @@ -193,19 +178,19 @@ public void AddFolder_Throws_When_FolderPath_Is_Invalid() // arrange var folderMapping = new FolderMappingInfo { - PortalID = Constants.CONTENT_ValidPortalId + PortalID = Constants.CONTENT_ValidPortalId, }; - _mockFolderManager + this._mockFolderManager .Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())) .Returns(false); - _mockFolderManager + this._mockFolderManager .Setup(mfm => mfm.IsValidFolderPath(It.IsAny())) .Returns(false); // act - _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); // assert (implicit) } @@ -216,7 +201,7 @@ public void IsValidFolderPath_Returns_True_When_FolderPath_Is_Valid() // arrange (implicit) // act - var result = _mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_ValidSubFolderRelativePath); + var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_ValidSubFolderRelativePath); // assert Assert.IsTrue(result); @@ -228,69 +213,65 @@ public void IsValidFolderPath_Returns_False_When_FolderPath_Is_Invalid() // arrange (implicit) // act - var result = _mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_InvalidSubFolderRelativePath); + var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_InvalidSubFolderRelativePath); // assert Assert.IsFalse(result); - } - - #endregion - - #region DeleteFolder - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFolder_Throws_On_Null_Folder() { - _folderManager.DeleteFolder(null); + this._folderManager.DeleteFolder(null); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFolder_Throws_OnNullFolder_WhenRecursive() { - //Arrange + // Arrange var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - //Act + // Act var notDeletedSubfolders = new List(); - _folderManager.DeleteFolder(null, notDeletedSubfolders); + this._folderManager.DeleteFolder(null, notDeletedSubfolders); } [Test] public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive() { - //Arrange + // Arrange var folderInfo = new FolderInfoBuilder() .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) .Build(); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - _mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); - _mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(new List()); - _mockUserSecurityController.Setup(musc => musc.HasFolderPermission(folderInfo, "DELETE")).Returns(true); + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(folderInfo, "DELETE")).Returns(true); - //Act + // Act var subfoldersNotDeleted = new List(); - _mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); - //Assert - _mockFolder.Verify(); + // Assert + this._mockFolder.Verify(); Assert.AreEqual(0, subfoldersNotDeleted.Count); } [Test] public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive_WhenExistSubfolders() { - //Arrange + // Arrange var folderInfo = new FolderInfoBuilder() .WithFolderId(1) .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) @@ -298,7 +279,7 @@ public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive_WhenExist var subfolder1 = new FolderInfoBuilder() .WithFolderId(2) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath+"\\subfolder1") + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder1") .Build(); var subfolder2 = new FolderInfoBuilder() .WithFolderId(3) @@ -307,38 +288,38 @@ public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive_WhenExist var subfolders = new List { subfolder1, - subfolder2 + subfolder2, }; var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); - _mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)).Verifiable(); - _mockFolder.Setup(mf => mf.DeleteFolder(subfolder2)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder2)).Verifiable(); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - _mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); - _mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); - _mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); - _mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); - //Act + // Act var subfoldersNotDeleted = new List(); - _mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); - //Assert - _mockFolder.Verify(); + // Assert + this._mockFolder.Verify(); Assert.AreEqual(0, subfoldersNotDeleted.Count); } [Test] public void DeleteFolder_SubFoldersCollectionIsNotEmpty_WhenRecursive_WhenUserHasNotDeletePermission() { - //Arrange + // Arrange var folderInfo = new FolderInfoBuilder() .WithFolderId(1) .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) @@ -355,37 +336,37 @@ public void DeleteFolder_SubFoldersCollectionIsNotEmpty_WhenRecursive_WhenUserHa var subfolders = new List { subfolder1, - subfolder2 + subfolder2, }; var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)); - _mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)); - - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - _mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); - _mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); - _mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); - _mockUserSecurityController.Setup(musc => musc.HasFolderPermission(subfolder2, "DELETE")).Returns(false); - _mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsNotIn(subfolder2), "DELETE")).Returns(true); + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(subfolder2, "DELETE")).Returns(false); + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsNotIn(subfolder2), "DELETE")).Returns(true); - //Act + // Act var subfoldersNotDeleted = new List(); - _mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); - //Assert - Assert.AreEqual(2, subfoldersNotDeleted.Count); //folderInfo and subfolder2 are not deleted + // Assert + Assert.AreEqual(2, subfoldersNotDeleted.Count); // folderInfo and subfolder2 are not deleted } [Test] [ExpectedException(typeof(FileLockedException))] public void DeleteFolder_Throws_OnFileDeletionControllerThrows_WhenRecursive_WhenFileIsLocked() { - //Arrange + // Arrange var folderInfo = new FolderInfoBuilder() .WithFolderId(1) .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) @@ -400,138 +381,132 @@ public void DeleteFolder_Throws_OnFileDeletionControllerThrows_WhenRecursive_Whe var files = new List { fileInfo1, - fileInfo2 + fileInfo2, }; var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - //_mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - _mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); - - _mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(files); + // _mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); - _mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(files); - _mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo1)); - _mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo2)).Throws(); + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); - - //Act - _mockFolderManager.Object.DeleteFolder(folderInfo, new List()); + this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo1)); + this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo2)).Throws(); + + // Act + this._mockFolderManager.Object.DeleteFolder(folderInfo, new List()); } [Test] public void DeleteFolder_Calls_FolderProvider_DeleteFolder() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Verifiable(); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - _mockFolderManager.Object.DeleteFolder(_folderInfo.Object); + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); - _mockFolder.Verify(); + this._mockFolder.Verify(); } [Test] [ExpectedException(typeof(FolderProviderException))] public void DeleteFolder_Throws_When_FolderProvider_Throws() { - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object)).Throws(); + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Throws(); - _mockFolderManager.Object.DeleteFolder(_folderInfo.Object); + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); } [Test] public void DeleteFolder_Calls_Directory_Delete_When_Directory_Exists() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object)); + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); - _directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - _directory.Setup(d => d.Delete(Constants.FOLDER_ValidFolderPath, true)).Verifiable(); + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this._directory.Setup(d => d.Delete(Constants.FOLDER_ValidFolderPath, true)).Verifiable(); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - _mockFolderManager.Object.DeleteFolder(_folderInfo.Object); + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); - _directory.Verify(); + this._directory.Verify(); } [Test] public void DeleteFolder_Calls_FolderManager_DeleteFolder_Overload() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object)); + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); - _mockFolderManager.Object.DeleteFolder(_folderInfo.Object); - - _mockFolderManager.Verify(); - } - - #endregion - - #region FolderExists + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + this._mockFolderManager.Verify(); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderPath() { - _folderManager.FolderExists(Constants.CONTENT_ValidPortalId, null); + this._folderManager.FolderExists(Constants.CONTENT_ValidPortalId, null); } [Test] public void ExistsFolder_Calls_FolderManager_GetFolder() { - _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object).Verifiable(); + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object).Verifiable(); - _mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - _mockFolderManager.Verify(); + this._mockFolderManager.Verify(); } [Test] public void ExistsFolder_Returns_True_When_Folder_Exists() { - _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); - var result = _mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.IsTrue(result); } @@ -539,51 +514,47 @@ public void ExistsFolder_Returns_True_When_Folder_Exists() [Test] public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() { - _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); - var result = _mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.IsFalse(result); - } - - #endregion - - #region GetFiles - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFilesByFolder_Throws_On_Null_Folder() { - _folderManager.GetFiles(null); + this._folderManager.GetFiles(null); } [Test] public void GetFilesByFolder_Calls_DataProvider_GetFiles() { - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var files = new DataTable(); files.Columns.Add("FolderName"); var dr = files.CreateDataReader(); - _mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr).Verifiable(); + this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr).Verifiable(); var filesList = new List { new FileInfo() { FileName = Constants.FOLDER_ValidFileName } }; - _cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - _folderManager.GetFiles(_folderInfo.Object); + this._folderManager.GetFiles(this._folderInfo.Object); - _mockData.Verify(); + this._mockData.Verify(); } [Test] public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() { - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var files = new DataTable(); files.Columns.Add("FileName"); @@ -591,13 +562,13 @@ public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() var dr = files.CreateDataReader(); - _mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); + this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); var filesList = new List { new FileInfo { FileName = Constants.FOLDER_ValidFileName } }; - _cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - var result = _folderManager.GetFiles(_folderInfo.Object).ToList(); + var result = this._folderManager.GetFiles(this._folderInfo.Object).ToList(); Assert.AreEqual(1, result.Count); } @@ -605,8 +576,8 @@ public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() [Test] public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files() { - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); var files = new DataTable(); files.Columns.Add("FileName"); @@ -615,36 +586,32 @@ public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files( var dr = files.CreateDataReader(); - _mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); + this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); var filesList = new List { new FileInfo { FileName = Constants.FOLDER_ValidFileName }, - new FileInfo { FileName = Constants.FOLDER_OtherValidFileName } + new FileInfo { FileName = Constants.FOLDER_OtherValidFileName }, }; - _cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - var result = _folderManager.GetFiles(_folderInfo.Object).Cast(); + var result = this._folderManager.GetFiles(this._folderInfo.Object).Cast(); CollectionAssert.AreEqual(filesList, result); - } - - #endregion - - #region GetFolder - + } + [Test] public void GetFolder_Calls_DataProvider_GetFolder() { var folderDataTable = new DataTable(); folderDataTable.Columns.Add("FolderName"); - _mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(folderDataTable.CreateDataReader()).Verifiable(); + this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(folderDataTable.CreateDataReader()).Verifiable(); - _folderManager.GetFolder(Constants.FOLDER_ValidFolderId); + this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); - _mockData.Verify(); + this._mockData.Verify(); } [Test] @@ -655,10 +622,10 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist() var dr = folderDataTable.CreateDataReader(); - _mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); - _cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); + this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); - var result = _folderManager.GetFolder(Constants.FOLDER_ValidFolderId); + var result = this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); Assert.IsNull(result); } @@ -666,9 +633,9 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist() [Test] public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() { - _folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); + this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); - _pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); + this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); var folderDataTable = new DataTable(); folderDataTable.Columns.Add("FolderName"); @@ -676,13 +643,13 @@ public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() var dr = folderDataTable.CreateDataReader(); - _mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); + this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; - _cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); - var result = _mockFolderManager.Object.GetFolder(Constants.FOLDER_ValidFolderId); + var result = this._mockFolderManager.Object.GetFolder(Constants.FOLDER_ValidFolderId); Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); } @@ -691,7 +658,7 @@ public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() [ExpectedException(typeof(ArgumentNullException))] public void GetFolder_Throws_On_Null_FolderPath() { - _folderManager.GetFolder(It.IsAny(), null); + this._folderManager.GetFolder(It.IsAny(), null); } [Test] @@ -699,25 +666,25 @@ public void GetFolder_Calls_GetFolders() { var foldersSorted = new List(); - _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted).Verifiable(); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted).Verifiable(); - _mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - _mockFolderManager.Verify(); + this._mockFolderManager.Verify(); } [Test] public void GetFolder_Calls_DataProvider_GetFolder_When_Folder_Is_Not_In_Cache() { - _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); var foldersSorted = new List(); - _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); - _mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - _mockData.Verify(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath), Times.Once()); + this._mockData.Verify(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath), Times.Once()); } [Test] @@ -728,13 +695,13 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist_Overload() var dr = folderDataTable.CreateDataReader(); - _mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); + this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); - _cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); - _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - var result = _mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.IsNull(result); } @@ -742,8 +709,8 @@ public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist_Overload() [Test] public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload() { - _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - _pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); var folderDataTable = new DataTable(); folderDataTable.Columns.Add("FolderName"); @@ -751,38 +718,34 @@ public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload() var dr = folderDataTable.CreateDataReader(); - _mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); + this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; - _cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); - _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - var result = _mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); - } - - #endregion - - #region GetFolders - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFoldersByParentFolder_Throws_On_Null_ParentFolder() { - _folderManager.GetFolders((IFolderInfo)null); + this._folderManager.GetFolders((IFolderInfo)null); } [Test] public void GetFoldersByParentFolder_Returns_Empty_List_When_ParentFolder_Contains_No_Subfolders() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - var result = _mockFolderManager.Object.GetFolders(_folderInfo.Object).ToList(); + var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); Assert.AreEqual(0, result.Count); } @@ -790,48 +753,40 @@ public void GetFoldersByParentFolder_Returns_Empty_List_When_ParentFolder_Contai [Test] public void GetFoldersByParentFolder_Returns_Valid_Subfolders() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); var foldersSorted = new List { - new FolderInfo { FolderID = Constants.FOLDER_ValidFolderId, ParentID = Null.NullInteger} , - new FolderInfo { FolderID = Constants.FOLDER_OtherValidFolderId, ParentID = Constants.FOLDER_ValidFolderId} + new FolderInfo { FolderID = Constants.FOLDER_ValidFolderId, ParentID = Null.NullInteger }, + new FolderInfo { FolderID = Constants.FOLDER_OtherValidFolderId, ParentID = Constants.FOLDER_ValidFolderId }, }; - _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); - var result = _mockFolderManager.Object.GetFolders(_folderInfo.Object).ToList(); + var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); Assert.AreEqual(1, result.Count); Assert.AreEqual(Constants.FOLDER_OtherValidFolderId, result[0].FolderID); - } - - #endregion - - #region GetFolders - + } + [Test] public void GetFolders_Calls_CBO_GetCachedObject() { var folders = new List(); - _cbo.Setup(cbo => cbo.GetCachedObject>(It.IsAny(), It.IsAny(), false)).Returns(folders).Verifiable(); - - _mockFolderManager.Object.GetFolders(Constants.CONTENT_ValidPortalId); - - _cbo.Verify(); - } - - #endregion + this._cbo.Setup(cbo => cbo.GetCachedObject>(It.IsAny(), It.IsAny(), false)).Returns(folders).Verifiable(); - #region RenameFolder + this._mockFolderManager.Object.GetFolders(Constants.CONTENT_ValidPortalId); + this._cbo.Verify(); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFolder_Throws_On_Null_Folder() { - _folderManager.RenameFolder(null, It.IsAny()); + this._folderManager.RenameFolder(null, It.IsAny()); } [Test] @@ -840,45 +795,42 @@ public void RenameFolder_Throws_On_Null_Folder() [ExpectedException(typeof(ArgumentException))] public void RenameFolder_Throws_On_Null_Or_Empty_NewFolderName(string newFolderName) { - _folderManager.RenameFolder(_folderInfo.Object, newFolderName); + this._folderManager.RenameFolder(this._folderInfo.Object, newFolderName); } [Test] [ExpectedException(typeof(FolderAlreadyExistsException))] public void RenameFolder_Throws_When_DestinationFolder_Exists() { - _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderName)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - - _folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - - _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); - - _mockFolderManager.Object.RenameFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderName); - } + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderName)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - #endregion + this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - #region UpdateFolder + this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); + this._mockFolderManager.Object.RenameFolder(this._folderInfo.Object, Constants.FOLDER_OtherValidFolderName); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFolder_Throws_On_Null_Folder() { - _folderManager.UpdateFolder(null); + this._folderManager.UpdateFolder(null); } [Test] public void UpdateFolder_Calls_DataProvider_UpdateFolder() { - _mockFolderManager.Setup(mfm => mfm.AddLogEntry(_folderInfo.Object, It.IsAny())); - _mockFolderManager.Setup(mfm => mfm.SaveFolderPermissions(_folderInfo.Object)); - _mockFolderManager.Setup(mfm => mfm.ClearFolderCache(It.IsAny())); + this._mockFolderManager.Setup(mfm => mfm.AddLogEntry(this._folderInfo.Object, It.IsAny())); + this._mockFolderManager.Setup(mfm => mfm.SaveFolderPermissions(this._folderInfo.Object)); + this._mockFolderManager.Setup(mfm => mfm.ClearFolderCache(It.IsAny())); - _mockFolderManager.Object.UpdateFolder(_folderInfo.Object); + this._mockFolderManager.Object.UpdateFolder(this._folderInfo.Object); - _mockData.Verify(md => md.UpdateFolder( + this._mockData.Verify( + md => md.UpdateFolder( It.IsAny(), It.IsAny(), It.IsAny(), @@ -893,41 +845,33 @@ public void UpdateFolder_Calls_DataProvider_UpdateFolder() It.IsAny(), It.IsAny(), It.IsAny()), Times.Once()); - } - - #endregion - - #region Synchronize - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void SynchronizeFolder_Throws_On_Null_RelativePath() { - _folderManager.Synchronize(It.IsAny(), null, It.IsAny(), It.IsAny()); + this._folderManager.Synchronize(It.IsAny(), null, It.IsAny(), It.IsAny()); } - + [Test] [ExpectedException(typeof(NoNetworkAvailableException))] public void SynchronizeFolder_Throws_When_Some_Folder_Mapping_Requires_Network_Connectivity_But_There_Is_No_Network_Available() { - _mockFolderManager.Setup(mfm => mfm.AreThereFolderMappingsRequiringNetworkConnectivity(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false)).Returns(true); - _mockFolderManager.Setup(mfm => mfm.IsNetworkAvailable()).Returns(false); - - _mockFolderManager.Object.Synchronize(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false, false); - } - - #endregion - - #region GetFileSystemFolders + this._mockFolderManager.Setup(mfm => mfm.AreThereFolderMappingsRequiringNetworkConnectivity(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false)).Returns(true); + this._mockFolderManager.Setup(mfm => mfm.IsNetworkAvailable()).Returns(false); + this._mockFolderManager.Object.Synchronize(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false, false); + } + [Test] public void GetFileSystemFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() { - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); - var result = _mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.IsEmpty(result); } @@ -935,11 +879,11 @@ public void GetFileSystemFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() [Test] public void GetFileSystemFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() { - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - var result = _mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.AreEqual(1, result.Count); Assert.IsTrue(result.Values[0].ExistsInFileSystem); @@ -948,32 +892,28 @@ public void GetFileSystemFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_ [Test] public void GetFileSystemFolders_Calls_FolderManager_GetFileSystemFoldersRecursive_When_Folder_Exists_And_Is_Recursive() { - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) .Returns(Constants.FOLDER_ValidFolderPath); - _mockFolderManager.Setup(mfm => mfm.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)) + this._mockFolderManager.Setup(mfm => mfm.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)) .Returns(It.IsAny>()) .Verifiable(); - _directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - - _mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); - - _mockFolderManager.Verify(); - } - - #endregion + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - #region GetFileSystemFoldersRecursive + this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); + this._mockFolderManager.Verify(); + } + [Test] public void GetFileSystemFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() { - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - _directory.Setup(d => d.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); + this._directory.Setup(d => d.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); - var result = _mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath); + var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath); Assert.AreEqual(1, result.Count); } @@ -983,25 +923,24 @@ public void GetFileSystemFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree { var relativePaths = new Dictionary { - {@"C:\folder", "folder/"}, - {@"C:\folder\subfolder", "folder/subfolder/"}, - {@"C:\folder\subfolder2", "folder/subfolder2/"}, - {@"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/"}, - {@"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/"} + { @"C:\folder", "folder/" }, + { @"C:\folder\subfolder", "folder/subfolder/" }, + { @"C:\folder\subfolder2", "folder/subfolder2/" }, + { @"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/" }, + { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, }; - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) .Returns((portalID, physicalPath) => relativePaths[physicalPath]); var directories = new List { @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; - _directory.Setup(d => d.GetDirectories(It.IsAny())) + this._directory.Setup(d => d.GetDirectories(It.IsAny())) .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); - var result = _mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); + var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); Assert.AreEqual(5, result.Count); - } [Test] @@ -1009,39 +948,35 @@ public void GetFileSystemFoldersRecursive_Sets_ExistsInFileSystem_For_All_Items( { var relativePaths = new Dictionary { - {@"C:\folder", "folder/"}, - {@"C:\folder\subfolder", "folder/subfolder/"}, - {@"C:\folder\subfolder2", "folder/subfolder2/"}, - {@"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/"}, - {@"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/"} + { @"C:\folder", "folder/" }, + { @"C:\folder\subfolder", "folder/subfolder/" }, + { @"C:\folder\subfolder2", "folder/subfolder2/" }, + { @"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/" }, + { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, }; - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) .Returns((portalID, physicalPath) => relativePaths[physicalPath]); var directories = new List { @"C:\folder", @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; - _directory.Setup(d => d.GetDirectories(It.IsAny())) + this._directory.Setup(d => d.GetDirectories(It.IsAny())) .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); - var result = _mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); + var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); foreach (var mergedTreeItem in result.Values) { Assert.True(mergedTreeItem.ExistsInFileSystem); } - } - - #endregion - - #region GetDatabaseFolders - + } + [Test] public void GetDatabaseFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() { - _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); - var result = _mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.IsEmpty(result); } @@ -1049,9 +984,9 @@ public void GetDatabaseFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() [Test] public void GetDatabaseFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() { - _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); - var result = _mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); Assert.AreEqual(1, result.Count); Assert.IsTrue(result.Values[0].ExistsInDatabase); @@ -1060,33 +995,29 @@ public void GetDatabaseFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Re [Test] public void GetDatabaseFolders_Calls_FolderManager_GetDatabaseFoldersRecursive_When_Folder_Exists_And_Is_Recursive() { - _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) - .Returns(_folderInfo.Object); + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + .Returns(this._folderInfo.Object); - _mockFolderManager.Setup(mfm => mfm.GetDatabaseFoldersRecursive(_folderInfo.Object)) + this._mockFolderManager.Setup(mfm => mfm.GetDatabaseFoldersRecursive(this._folderInfo.Object)) .Returns(It.IsAny>()) .Verifiable(); - _mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); - - _mockFolderManager.Verify(); - } - - #endregion - - #region GetDatabaseFoldersRecursive + this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); + this._mockFolderManager.Verify(); + } + [Test] public void GetDatabaseFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() { - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var subfolders = new List(); - _mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(subfolders); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(this._folderInfo.Object)).Returns(subfolders); - var result = _mockFolderManager.Object.GetDatabaseFoldersRecursive(_folderInfo.Object); + var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); Assert.AreEqual(1, result.Count); } @@ -1094,24 +1025,24 @@ public void GetDatabaseFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Ha [Test] public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() { - _folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var subfolders = new List { - new FolderInfo {FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}, - new FolderInfo {FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}, - new FolderInfo {FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}, - new FolderInfo {FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID} + new FolderInfo { FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo { FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo { FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, }; - _mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) .Returns(parent => subfolders.FindAll(sub => sub.FolderPath.StartsWith(parent.FolderPath) && sub.FolderPath.Length > parent.FolderPath.Length && sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); - var result = _mockFolderManager.Object.GetDatabaseFoldersRecursive(_folderInfo.Object); + var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); Assert.AreEqual(5, result.Count); } @@ -1119,116 +1050,107 @@ public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() [Test] public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() { - _folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var subfolders = new List { - new FolderInfo() {FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}, - new FolderInfo() {FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}, - new FolderInfo() {FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}, - new FolderInfo() {FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID} + new FolderInfo() { FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo() { FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo() { FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo() { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, }; - _mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) .Returns(parent => subfolders.FindAll(sub => sub.FolderPath.StartsWith(parent.FolderPath) && sub.FolderPath.Length > parent.FolderPath.Length && sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); - var result = _mockFolderManager.Object.GetDatabaseFoldersRecursive(_folderInfo.Object); + var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); foreach (var mergedTreeItem in result.Values) { Assert.True(mergedTreeItem.ExistsInDatabase); } - } - - #endregion - - #region GetFolderMappingFoldersRecursive - - //[Test] - //public void GetFolderMappingFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() - //{ - // var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - // var subfolders = new List(); - - // _mockFolder.Setup(mf => mf.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping)).Returns(subfolders); - - // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, Constants.FOLDER_ValidFolderRelativePath); - - // Assert.AreEqual(1, result.Count); - //} - - //[Test] - //public void GetFolderMappingFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() - //{ - // var mockCache = MockComponentProvider.CreateNew(); - // mockCache.Setup(c => c.GetItem(It.IsAny())).Returns(null); - - // var settings = new Hashtable(); - // settings["SyncAllSubFolders"] = "true"; - - // _folderMappingController.Setup(c => c.GetFolderMappingSettings(It.IsAny())).Returns(settings); - - // var hostSettingsTable = new DataTable("HostSettings"); - // var nameCol = hostSettingsTable.Columns.Add("SettingName"); - // hostSettingsTable.Columns.Add("SettingValue"); - // hostSettingsTable.Columns.Add("SettingIsSecure"); - // hostSettingsTable.PrimaryKey = new[] { nameCol }; - - // _mockData.Setup(c => c.GetHostSettings()).Returns(hostSettingsTable.CreateDataReader()); - // _mockData.Setup(c => c.GetProviderPath()).Returns(String.Empty); - - // var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - // var subfolders = new List { "folder/subfolder", "folder/subfolder2", "folder/subfolder2/subsubfolder", "folder/subfolder2/subsubfolder2" }; - - // _mockFolder.Setup(mf => mf.GetSubFolders(It.IsAny(), folderMapping)) - // .Returns((parent, fm) => subfolders.FindAll(sub => - // sub.StartsWith(parent) && - // sub.Length > parent.Length && - // sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/"))); - - // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/"); - - // Assert.AreEqual(5, result.Count); - //} - - //[Test] - //public void GetDatabaseFoldersRecursive_Sets_ExistsInFolderMappings_For_All_Items() - //{ - // var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - // var subfolders = new List { "folder/subfolder", "folder/subfolder2", "folder/subfolder2/subsubfolder", "folder/subfolder2/subsubfolder2" }; - - // _mockFolder.Setup(mf => mf.GetSubFolders(It.IsAny(), folderMapping)) - // .Returns((parent, fm) => subfolders.FindAll(sub => - // sub.StartsWith(parent) && - // sub.Length > parent.Length && - // sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/"))); - - // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/"); - - // foreach (var mergedTreeItem in result.Values) - // { - // Assert.True(mergedTreeItem.ExistsInFolderMappings.Contains(Constants.FOLDER_ValidFolderMappingID)); - // } - //} - - #endregion - - #region MergeFolderLists - + } + + // [Test] + // public void GetFolderMappingFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() + // { + // var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + // var subfolders = new List(); + + // _mockFolder.Setup(mf => mf.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping)).Returns(subfolders); + + // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, Constants.FOLDER_ValidFolderRelativePath); + + // Assert.AreEqual(1, result.Count); + // } + + // [Test] + // public void GetFolderMappingFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() + // { + // var mockCache = MockComponentProvider.CreateNew(); + // mockCache.Setup(c => c.GetItem(It.IsAny())).Returns(null); + + // var settings = new Hashtable(); + // settings["SyncAllSubFolders"] = "true"; + + // _folderMappingController.Setup(c => c.GetFolderMappingSettings(It.IsAny())).Returns(settings); + + // var hostSettingsTable = new DataTable("HostSettings"); + // var nameCol = hostSettingsTable.Columns.Add("SettingName"); + // hostSettingsTable.Columns.Add("SettingValue"); + // hostSettingsTable.Columns.Add("SettingIsSecure"); + // hostSettingsTable.PrimaryKey = new[] { nameCol }; + + // _mockData.Setup(c => c.GetHostSettings()).Returns(hostSettingsTable.CreateDataReader()); + // _mockData.Setup(c => c.GetProviderPath()).Returns(String.Empty); + + // var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + // var subfolders = new List { "folder/subfolder", "folder/subfolder2", "folder/subfolder2/subsubfolder", "folder/subfolder2/subsubfolder2" }; + + // _mockFolder.Setup(mf => mf.GetSubFolders(It.IsAny(), folderMapping)) + // .Returns((parent, fm) => subfolders.FindAll(sub => + // sub.StartsWith(parent) && + // sub.Length > parent.Length && + // sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/"))); + + // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/"); + + // Assert.AreEqual(5, result.Count); + // } + + // [Test] + // public void GetDatabaseFoldersRecursive_Sets_ExistsInFolderMappings_For_All_Items() + // { + // var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + // var subfolders = new List { "folder/subfolder", "folder/subfolder2", "folder/subfolder2/subsubfolder", "folder/subfolder2/subsubfolder2" }; + + // _mockFolder.Setup(mf => mf.GetSubFolders(It.IsAny(), folderMapping)) + // .Returns((parent, fm) => subfolders.FindAll(sub => + // sub.StartsWith(parent) && + // sub.Length > parent.Length && + // sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/"))); + + // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/"); + + // foreach (var mergedTreeItem in result.Values) + // { + // Assert.True(mergedTreeItem.ExistsInFolderMappings.Contains(Constants.FOLDER_ValidFolderMappingID)); + // } + // } [Test] public void MergeFolderLists_Returns_Empty_List_When_Both_Lists_Are_Empty() { var list1 = new SortedList(); var list2 = new SortedList(); - var result = _folderManager.MergeFolderLists(list1, list2); + var result = this._folderManager.MergeFolderLists(list1, list2); Assert.IsEmpty(result); } @@ -1238,937 +1160,928 @@ public void MergeFolderLists_Count_Equals_The_Intersection_Count_Between_Both_Li { var list1 = new SortedList { - {"folder1", new FolderManager.MergedTreeItem {FolderPath = "folder1"}}, - {"folder2", new FolderManager.MergedTreeItem {FolderPath = "folder2"}} + { "folder1", new FolderManager.MergedTreeItem { FolderPath = "folder1" } }, + { "folder2", new FolderManager.MergedTreeItem { FolderPath = "folder2" } }, }; var list2 = new SortedList { - {"folder1", new FolderManager.MergedTreeItem {FolderPath = "folder1"}}, - {"folder3", new FolderManager.MergedTreeItem {FolderPath = "folder3"}} + { "folder1", new FolderManager.MergedTreeItem { FolderPath = "folder1" } }, + { "folder3", new FolderManager.MergedTreeItem { FolderPath = "folder3" } }, }; - var result = _folderManager.MergeFolderLists(list1, list2); + var result = this._folderManager.MergeFolderLists(list1, list2); Assert.AreEqual(3, result.Count); - } - - //[Test] - //public void MergeFolderLists_Merges_TreeItem_Properties() - //{ - // var list1 = new SortedList - // { - // { - // "folder1", - // new FolderManager.MergedTreeItem {FolderPath = "folder1", ExistsInFileSystem = true, ExistsInDatabase = true, FolderMappingID = Constants.FOLDER_ValidFolderMappingID} - // } - // }; - - // var list2 = new SortedList - // { - // { - // "folder1", - // new FolderManager.MergedTreeItem {FolderPath = "folder1", ExistsInFileSystem = false, ExistsInDatabase = false, ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID}} - // } - // }; - - // var result = _folderManager.MergeFolderLists(list1, list2); - - // Assert.AreEqual(1, result.Count); - // Assert.IsTrue(result.Values[0].ExistsInFileSystem); - // Assert.IsTrue(result.Values[0].ExistsInDatabase); - // Assert.AreEqual(Constants.FOLDER_ValidFolderMappingID, result.Values[0].FolderMappingID); - // Assert.IsTrue(result.Values[0].ExistsInFolderMappings.Contains(Constants.FOLDER_ValidFolderMappingID)); - //} - - #endregion - - #region ProcessMergedTreeItem - - //[Test] - //public void ProcessMergedTreeItem_Sets_StorageLocation_To_Default_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Not_Default_And_Has_SubFolders() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID - // } - // }, - // {Constants.FOLDER_ValidSubFolderRelativePath, new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidSubFolderRelativePath}} - // }; - - // var folderMappingOfItem = new FolderMappingInfo(); - // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = 1 }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); - - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); - // _mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(new List()); - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, 1)).Verifiable(); - - // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Deletes_Folder_From_FileSystem_And_Database_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Not_Default_And_Has_Not_SubFolders() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo(); - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); - - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); - // _mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(new List()); - - // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // _directory.Verify(d => d.Delete(Constants.FOLDER_ValidFolderPath, false), Times.Once()); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Default() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Sets_StorageLocation_To_The_Highest_Priority_One_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Default_And_Folder_Does_Not_Contain_Files() - //{ - // const int externalStorageLocation = 15; - // const string externalMappingName = "External Mapping"; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = "StandardFolderProvider" }; - - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = externalMappingName }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); - - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) - // .Returns(_folderInfo.Object); - - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); - - // var mockFolder = MockComponentProvider.CreateFolderProvider("StandardFolderProvider"); - - // mockFolder.Setup(mf => mf.GetFiles(_folderInfo.Object)).Returns(new string[0]); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalMappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Default_And_Folder_Contains_Files() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = "StandardFolderProvider", MappingName = "Default Mapping" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) - // .Returns(_folderInfo.Object); - - // var mockFolder = MockComponentProvider.CreateFolderProvider("StandardFolderProvider"); - - // mockFolder.Setup(mf => mf.GetFiles(_folderInfo.Object)).Returns(new string[1]); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Sets_StorageLocation_To_The_Highest_Priority_One_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Different_From_Actual() - //{ - // const int externalStorageLocation = 15; - // const string externalMappingName = "External Mapping"; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; - - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = externalMappingName }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); - - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalMappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_More_Than_One_FolderMappings_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "Default Mapping" }; - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1, MappingName = "External Mapping" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Null_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, MappingName = "Default Mapping" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.IsNull(result); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Creates_Folder_In_Database_With_Default_StorageLocation_When_Folder_Exists_Only_In_FileSystem() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidFolderRelativePath, ExistsInFileSystem = true, ExistsInDatabase = false} - // } - // }; - - // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; - - // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); - - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); - - // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_Database_With_Default_StorageLocation_When_Folder_Exists_Only_In_FileSystem_And_One_Or_More_FolderMappings_And_Folder_Contains_Files() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = false, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, MappingName = "Default Mapping" }; - - // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - - // _directory.Setup(d => d.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(new string[1]); - - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, defaultFolderMapping.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_FileSystem_And_One_Or_More_FolderMappings_And_Folder_Does_Not_Contain_Files() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = true, - // ExistsInDatabase = false, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = "External Mapping" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - - // _directory.Setup(d => d.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); - - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Default() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.IsNull(result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_Default_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Not_Default_And_Folder_Has_SubFolders() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID - // } - // }, - // {Constants.FOLDER_ValidSubFolderRelativePath, new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidSubFolderRelativePath}} - // }; - - // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = 1 }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(new FolderMappingInfo()); - // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, defaultFolderMapping.FolderMappingID)).Verifiable(); - - // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Deletes_Folder_In_Database_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Not_Default_And_Folder_Has_Not_SubFolders() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID - // } - // } - // }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(new FolderMappingInfo()); - - // _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); - - // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_Only_External_FolderMapping_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Default_But_Not_Database() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.IsNull(result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Default_But_Not_Database() - //{ - // const int externalStorageLocation1 = 15; - // const int externalStorageLocation2 = 16; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation1, externalStorageLocation2} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; - - // var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = externalStorageLocation1, Priority = 0, MappingName = "External Mapping" }; - - // var externalFolderMapping2 = new FolderMappingInfo { Priority = 1 }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation1)).Returns(externalFolderMapping1); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation2)).Returns(externalFolderMapping2); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation1)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Database_And_Folder_Does_Not_Contain_Files() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "DatabaseFolderProvider" }; - - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = "External Mapping" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); - // _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny(), It.IsAny())).Returns(new List()); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Database_And_Folder_Contains_Files() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "DatabaseFolderProvider", MappingName = "Database Mapping" }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); - // _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny(), It.IsAny())).Returns(new List { new FileInfo() }); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Different_From_Actual() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo(); - - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.IsNull(result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_IsDifferent_From_Actual() - //{ - // const int externalStorageLocation1 = 15; - // const int externalStorageLocation2 = 16; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {externalStorageLocation1, externalStorageLocation2} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo(); - - // var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = externalStorageLocation1, Priority = 0, MappingName = "External Mapping" }; - - // var externalFolderMapping2 = new FolderMappingInfo { Priority = 1 }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation1)).Returns(externalFolderMapping1); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation2)).Returns(externalFolderMapping2); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation1)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.IsNull(result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = true, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation} - // } - // } - // }; - - // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "External Mapping" }; - - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1 }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_One_FolderMapping() - //{ - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = false, - // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID} - // } - // } - // }; - - // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(externalFolderMapping); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.IsNull(result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - //[Test] - //public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_More_Than_One_FolderMapping() - //{ - // const int externalStorageLocation = 15; - - // var mergedTree = new SortedList - // { - // { - // Constants.FOLDER_ValidFolderRelativePath, - // new FolderManager.MergedTreeItem { - // FolderPath = Constants.FOLDER_ValidFolderRelativePath, - // ExistsInFileSystem = false, - // ExistsInDatabase = false, - // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation} - // } - // } - // }; - - // var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "External Mapping" }; - - // var externalFolderMapping2 = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1 }; - - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(externalFolderMapping1); - // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping2); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); - - // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); - - // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result); - // _mockFolderManager.Verify(); - // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); - // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); - //} - - #endregion - - #region MoveFolder - + } + + // [Test] + // public void MergeFolderLists_Merges_TreeItem_Properties() + // { + // var list1 = new SortedList + // { + // { + // "folder1", + // new FolderManager.MergedTreeItem {FolderPath = "folder1", ExistsInFileSystem = true, ExistsInDatabase = true, FolderMappingID = Constants.FOLDER_ValidFolderMappingID} + // } + // }; + + // var list2 = new SortedList + // { + // { + // "folder1", + // new FolderManager.MergedTreeItem {FolderPath = "folder1", ExistsInFileSystem = false, ExistsInDatabase = false, ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID}} + // } + // }; + + // var result = _folderManager.MergeFolderLists(list1, list2); + + // Assert.AreEqual(1, result.Count); + // Assert.IsTrue(result.Values[0].ExistsInFileSystem); + // Assert.IsTrue(result.Values[0].ExistsInDatabase); + // Assert.AreEqual(Constants.FOLDER_ValidFolderMappingID, result.Values[0].FolderMappingID); + // Assert.IsTrue(result.Values[0].ExistsInFolderMappings.Contains(Constants.FOLDER_ValidFolderMappingID)); + // } + + // [Test] + // public void ProcessMergedTreeItem_Sets_StorageLocation_To_Default_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Not_Default_And_Has_SubFolders() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID + // } + // }, + // {Constants.FOLDER_ValidSubFolderRelativePath, new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidSubFolderRelativePath}} + // }; + + // var folderMappingOfItem = new FolderMappingInfo(); + // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = 1 }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); + + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); + // _mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(new List()); + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, 1)).Verifiable(); + + // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Deletes_Folder_From_FileSystem_And_Database_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Not_Default_And_Has_Not_SubFolders() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo(); + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); + // _mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(new List()); + + // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // _directory.Verify(d => d.Delete(Constants.FOLDER_ValidFolderPath, false), Times.Once()); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Default() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Sets_StorageLocation_To_The_Highest_Priority_One_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Default_And_Folder_Does_Not_Contain_Files() + // { + // const int externalStorageLocation = 15; + // const string externalMappingName = "External Mapping"; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = "StandardFolderProvider" }; + + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = externalMappingName }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); + + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + // .Returns(_folderInfo.Object); + + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); + + // var mockFolder = MockComponentProvider.CreateFolderProvider("StandardFolderProvider"); + + // mockFolder.Setup(mf => mf.GetFiles(_folderInfo.Object)).Returns(new string[0]); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalMappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Default_And_Folder_Contains_Files() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = "StandardFolderProvider", MappingName = "Default Mapping" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + // .Returns(_folderInfo.Object); + + // var mockFolder = MockComponentProvider.CreateFolderProvider("StandardFolderProvider"); + + // mockFolder.Setup(mf => mf.GetFiles(_folderInfo.Object)).Returns(new string[1]); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Sets_StorageLocation_To_The_Highest_Priority_One_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Different_From_Actual() + // { + // const int externalStorageLocation = 15; + // const string externalMappingName = "External Mapping"; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; + + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = externalMappingName }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); + + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalMappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_More_Than_One_FolderMappings_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "Default Mapping" }; + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1, MappingName = "External Mapping" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Null_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, MappingName = "Default Mapping" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.IsNull(result); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Creates_Folder_In_Database_With_Default_StorageLocation_When_Folder_Exists_Only_In_FileSystem() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidFolderRelativePath, ExistsInFileSystem = true, ExistsInDatabase = false} + // } + // }; + + // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; + + // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); + + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); + + // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_Database_With_Default_StorageLocation_When_Folder_Exists_Only_In_FileSystem_And_One_Or_More_FolderMappings_And_Folder_Contains_Files() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = false, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, MappingName = "Default Mapping" }; + + // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + + // _directory.Setup(d => d.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(new string[1]); + + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, defaultFolderMapping.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_FileSystem_And_One_Or_More_FolderMappings_And_Folder_Does_Not_Contain_Files() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = true, + // ExistsInDatabase = false, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = "External Mapping" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + + // _directory.Setup(d => d.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); + + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Default() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.IsNull(result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_Default_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Not_Default_And_Folder_Has_SubFolders() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID + // } + // }, + // {Constants.FOLDER_ValidSubFolderRelativePath, new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidSubFolderRelativePath}} + // }; + + // var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = 1 }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(new FolderMappingInfo()); + // _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, defaultFolderMapping.FolderMappingID)).Verifiable(); + + // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Deletes_Folder_In_Database_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Not_Default_And_Folder_Has_Not_SubFolders() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID + // } + // } + // }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(new FolderMappingInfo()); + + // _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + + // _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_Only_External_FolderMapping_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Default_But_Not_Database() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.IsNull(result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Default_But_Not_Database() + // { + // const int externalStorageLocation1 = 15; + // const int externalStorageLocation2 = 16; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation1, externalStorageLocation2} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" }; + + // var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = externalStorageLocation1, Priority = 0, MappingName = "External Mapping" }; + + // var externalFolderMapping2 = new FolderMappingInfo { Priority = 1 }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation1)).Returns(externalFolderMapping1); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation2)).Returns(externalFolderMapping2); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation1)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Database_And_Folder_Does_Not_Contain_Files() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "DatabaseFolderProvider" }; + + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = "External Mapping" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); + // _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny(), It.IsAny())).Returns(new List()); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Database_And_Folder_Contains_Files() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "DatabaseFolderProvider", MappingName = "Database Mapping" }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object); + // _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny(), It.IsAny())).Returns(new List { new FileInfo() }); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Different_From_Actual() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo(); + + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.IsNull(result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_IsDifferent_From_Actual() + // { + // const int externalStorageLocation1 = 15; + // const int externalStorageLocation2 = 16; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {externalStorageLocation1, externalStorageLocation2} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo(); + + // var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = externalStorageLocation1, Priority = 0, MappingName = "External Mapping" }; + + // var externalFolderMapping2 = new FolderMappingInfo { Priority = 1 }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation1)).Returns(externalFolderMapping1); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation2)).Returns(externalFolderMapping2); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation1)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.IsNull(result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = true, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation} + // } + // } + // }; + + // var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "External Mapping" }; + + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1 }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_One_FolderMapping() + // { + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = false, + // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID} + // } + // } + // }; + + // var externalFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(externalFolderMapping); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.IsNull(result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } + + // [Test] + // public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_More_Than_One_FolderMapping() + // { + // const int externalStorageLocation = 15; + + // var mergedTree = new SortedList + // { + // { + // Constants.FOLDER_ValidFolderRelativePath, + // new FolderManager.MergedTreeItem { + // FolderPath = Constants.FOLDER_ValidFolderRelativePath, + // ExistsInFileSystem = false, + // ExistsInDatabase = false, + // ExistsInFolderMappings = new List {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation} + // } + // } + // }; + + // var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "External Mapping" }; + + // var externalFolderMapping2 = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1 }; + + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(externalFolderMapping1); + // _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping2); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); + + // var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId); + + // Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result); + // _mockFolderManager.Verify(); + // _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); + // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); + // } [Test] [ExpectedException(typeof(ArgumentNullException))] public void MoveFolder_Throws_On_Null_Folder() { - _folderManager.MoveFolder(null, It.IsAny()); + this._folderManager.MoveFolder(null, It.IsAny()); } [Test] @@ -2177,108 +2090,103 @@ public void MoveFolder_Throws_On_Null_Folder() [ExpectedException(typeof(ArgumentException))] public void MoveFolder_Throws_On_Null_Or_Emtpy_NewFolderPath(string newFolderPath) { - _folderManager.MoveFolder(_folderInfo.Object, newFolderPath); + this._folderManager.MoveFolder(this._folderInfo.Object, newFolderPath); } [Test] public void MoveFolder_Returns_The_Same_Folder_If_The_Paths_Are_The_Same() { - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); IFolderInfo destinationFolder = new FolderInfo(); destinationFolder.FolderPath = Constants.FOLDER_ValidFolderRelativePath; - _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - var movedFolder = _folderManager.MoveFolder(_folderInfo.Object, destinationFolder); + var movedFolder = this._folderManager.MoveFolder(this._folderInfo.Object, destinationFolder); - Assert.AreEqual(_folderInfo.Object, movedFolder); + Assert.AreEqual(this._folderInfo.Object, movedFolder); } [Test] [ExpectedException(typeof(InvalidOperationException))] public void MoveFolder_Throws_When_Move_Operation_Is_Not_Valid() { - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + IFolderInfo destinationFolder = new FolderInfo(); destinationFolder.FolderPath = Constants.FOLDER_OtherValidFolderRelativePath; destinationFolder.FolderMappingID = Constants.FOLDER_ValidFolderMappingID; - _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - - _mockFolderManager.Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())).Returns(false); - _mockFolderManager.Setup(mfm => mfm.CanMoveBetweenFolderMappings(It.IsAny(), It.IsAny())).Returns(true); - _mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, destinationFolder, It.IsAny())).Returns(false); - - _mockFolderManager.Object.MoveFolder(_folderInfo.Object, destinationFolder); - } - - //[Test] - //public void MoveFolder_Calls_Internal_OverwriteFolder_When_Target_Folder_Already_Exists() - //{ - // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - // _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - - // _mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); - - // var folders = new List { _folderInfo.Object }; - // var targetFolder = new FolderInfo { FolderPath = Constants.FOLDER_OtherValidFolderRelativePath }; - - // _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(folders); - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(targetFolder); - - // _mockFolderManager.Setup(mfm => mfm.OverwriteFolder(_folderInfo.Object, targetFolder, It.IsAny>(), It.IsAny>())).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.RenameFolderInFileSystem(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)); - - // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath); - - // _mockFolderManager.Verify(); - //} - - //[Test] - //public void MoveFolder_Calls_Internal_MoveFolder_When_Target_Folder_Does_Not_Exist() - //{ - // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - // _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - - // _mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); - - // var folders = new List { _folderInfo.Object }; - - // _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(folders); - // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns((IFolderInfo)null); - - // _mockFolderManager.Setup( - // mfm => - // mfm.MoveFolder(_folderInfo.Object, - // Constants.FOLDER_OtherValidFolderRelativePath, - // Constants.FOLDER_OtherValidFolderRelativePath, - // It.IsAny>(), - // _folderInfo.Object, - // It.IsAny>())).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.RenameFolderInFileSystem(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)); - - // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath); - - // _mockFolderManager.Verify(); - //} - - #endregion - - #region OverwriteFolder (Internal method) - + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + + this._mockFolderManager.Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())).Returns(false); + this._mockFolderManager.Setup(mfm => mfm.CanMoveBetweenFolderMappings(It.IsAny(), It.IsAny())).Returns(true); + this._mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(this._folderInfo.Object, destinationFolder, It.IsAny())).Returns(false); + + this._mockFolderManager.Object.MoveFolder(this._folderInfo.Object, destinationFolder); + } + + // [Test] + // public void MoveFolder_Calls_Internal_OverwriteFolder_When_Target_Folder_Already_Exists() + // { + // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + // _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + + // _mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); + + // var folders = new List { _folderInfo.Object }; + // var targetFolder = new FolderInfo { FolderPath = Constants.FOLDER_OtherValidFolderRelativePath }; + + // _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(folders); + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(targetFolder); + + // _mockFolderManager.Setup(mfm => mfm.OverwriteFolder(_folderInfo.Object, targetFolder, It.IsAny>(), It.IsAny>())).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.RenameFolderInFileSystem(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)); + + // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath); + + // _mockFolderManager.Verify(); + // } + + // [Test] + // public void MoveFolder_Calls_Internal_MoveFolder_When_Target_Folder_Does_Not_Exist() + // { + // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + // _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + + // _mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); + + // var folders = new List { _folderInfo.Object }; + + // _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(folders); + // _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns((IFolderInfo)null); + + // _mockFolderManager.Setup( + // mfm => + // mfm.MoveFolder(_folderInfo.Object, + // Constants.FOLDER_OtherValidFolderRelativePath, + // Constants.FOLDER_OtherValidFolderRelativePath, + // It.IsAny>(), + // _folderInfo.Object, + // It.IsAny>())).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.RenameFolderInFileSystem(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)); + + // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath); + + // _mockFolderManager.Verify(); + // } [Test] public void OverwriteFolder_Calls_MoveFile_For_Each_File_In_Source_Folder() { - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var destinationFolder = new FolderInfo(); @@ -2287,21 +2195,21 @@ public void OverwriteFolder_Calls_MoveFile_For_Each_File_In_Source_Folder() var file3 = new FileInfo(); var files = new List { file1, file2, file3 }; - _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); var fileManager = new Mock(); FileManager.RegisterInstance(fileManager.Object); fileManager.Setup(fm => fm.MoveFile(It.IsAny(), destinationFolder)); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); var folderMapping = new FolderMappingInfo(); - _mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); + this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); - _mockFolderManager.Object.OverwriteFolder(_folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); + this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); fileManager.Verify(fm => fm.MoveFile(It.IsAny(), destinationFolder), Times.Exactly(3)); } @@ -2312,25 +2220,25 @@ public void OverwriteFolder_Deletes_Source_Folder_In_Database() var fileManager = new Mock(); FileManager.RegisterInstance(fileManager.Object); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var files = new List(); - _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); var destinationFolder = new FolderInfo(); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); var folderMapping = new FolderMappingInfo(); - _mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); + this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); - _mockFolderManager.Object.OverwriteFolder(_folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); + this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); - _mockFolderManager.Verify(); + this._mockFolderManager.Verify(); } [Test] @@ -2339,78 +2247,72 @@ public void OverwriteFolder_Adds_Folder_To_FoldersToDelete_If_FolderMapping_Is_E var fileManager = new Mock(); FileManager.RegisterInstance(fileManager.Object); - _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - _folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); var files = new List(); - _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); var destinationFolder = new FolderInfo(); - _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); var folderMapping = new FolderMappingInfo(); - _mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - _mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); + this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); var foldersToDelete = new SortedList(); - _mockFolderManager.Object.OverwriteFolder(_folderInfo.Object, destinationFolder, new Dictionary(), foldersToDelete); + this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), foldersToDelete); Assert.AreEqual(1, foldersToDelete.Count); - } - - #endregion - - #region MoveFolder (Internal method) - - //[Test] - //public void MoveFolder_Calls_FolderProvider_MoveFolder_When_FolderMapping_Is_Not_Already_Processed_And_Is_Editable() - //{ - // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - - // var subFolder = new FolderInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; - // var folderMappingsProcessed = new List(); - // var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - // var folderMappings = new Dictionary(); - - // _mockFolderManager.Setup(mfm => mfm.GetFolderMapping(folderMappings, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - // _mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); - - // _mockFolder.Setup(mf => mf.MoveFolder(Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_OtherValidFolderRelativePath, folderMapping)).Verifiable(); - - // _mockFolderManager.Setup(mfm => mfm.UpdateFolder(subFolder)); - - // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, - // Constants.FOLDER_OtherValidFolderRelativePath, - // Constants.FOLDER_OtherValidFolderRelativePath, - // folderMappingsProcessed, - // subFolder, - // folderMappings); - - // _mockFolder.Verify(); - //} - - //[Test] - //public void MoveFolder_Calls_UpdateFolder() - //{ - // var subFolder = new FolderInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; - // var folderMappingsProcessed = new List { Constants.FOLDER_ValidFolderMappingID }; - // var folderMappings = new Dictionary(); - - // _mockFolderManager.Setup(mfm => mfm.UpdateFolder(subFolder)).Verifiable(); - - // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, - // Constants.FOLDER_OtherValidFolderRelativePath, - // Constants.FOLDER_OtherValidFolderRelativePath, - // folderMappingsProcessed, - // subFolder, - // folderMappings); - - // _mockFolderManager.Verify(); - //} - - #endregion + } + + // [Test] + // public void MoveFolder_Calls_FolderProvider_MoveFolder_When_FolderMapping_Is_Not_Already_Processed_And_Is_Editable() + // { + // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + + // var subFolder = new FolderInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; + // var folderMappingsProcessed = new List(); + // var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + // var folderMappings = new Dictionary(); + + // _mockFolderManager.Setup(mfm => mfm.GetFolderMapping(folderMappings, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + // _mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); + + // _mockFolder.Setup(mf => mf.MoveFolder(Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_OtherValidFolderRelativePath, folderMapping)).Verifiable(); + + // _mockFolderManager.Setup(mfm => mfm.UpdateFolder(subFolder)); + + // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, + // Constants.FOLDER_OtherValidFolderRelativePath, + // Constants.FOLDER_OtherValidFolderRelativePath, + // folderMappingsProcessed, + // subFolder, + // folderMappings); + + // _mockFolder.Verify(); + // } + + // [Test] + // public void MoveFolder_Calls_UpdateFolder() + // { + // var subFolder = new FolderInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID }; + // var folderMappingsProcessed = new List { Constants.FOLDER_ValidFolderMappingID }; + // var folderMappings = new Dictionary(); + + // _mockFolderManager.Setup(mfm => mfm.UpdateFolder(subFolder)).Verifiable(); + + // _mockFolderManager.Object.MoveFolder(_folderInfo.Object, + // Constants.FOLDER_OtherValidFolderRelativePath, + // Constants.FOLDER_OtherValidFolderRelativePath, + // folderMappingsProcessed, + // subFolder, + // folderMappings); + + // _mockFolderManager.Verify(); + // } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs index 05f1d4bce18..d5f6a7ef03f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs @@ -1,28 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + using System.IO; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class SecureFolderProviderTests - { - #region Private Variables - + { private SecureFolderProvider _sfp; private Mock _folderInfo; private Mock _fileInfo; @@ -30,48 +26,40 @@ public class SecureFolderProviderTests private Mock _directoryWrapper; private Mock _folderManager; private Mock _fileManager; - private Mock _pathUtils; - - #endregion - - #region Setup - + private Mock _pathUtils; + [SetUp] public void Setup() { - _sfp = new SecureFolderProvider(); - _folderInfo = new Mock(); - _fileInfo = new Mock(); - _fileWrapper = new Mock(); - _directoryWrapper = new Mock(); - _folderManager = new Mock(); - _fileManager = new Mock(); - _pathUtils = new Mock(); + this._sfp = new SecureFolderProvider(); + this._folderInfo = new Mock(); + this._fileInfo = new Mock(); + this._fileWrapper = new Mock(); + this._directoryWrapper = new Mock(); + this._folderManager = new Mock(); + this._fileManager = new Mock(); + this._pathUtils = new Mock(); - FileWrapper.RegisterInstance(_fileWrapper.Object); - DirectoryWrapper.RegisterInstance(_directoryWrapper.Object); - FolderManager.RegisterInstance(_folderManager.Object); - FileManager.RegisterInstance(_fileManager.Object); - PathUtils.RegisterInstance(_pathUtils.Object); + FileWrapper.RegisterInstance(this._fileWrapper.Object); + DirectoryWrapper.RegisterInstance(this._directoryWrapper.Object); + FolderManager.RegisterInstance(this._folderManager.Object); + FileManager.RegisterInstance(this._fileManager.Object); + PathUtils.RegisterInstance(this._pathUtils.Object); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } - - #endregion - - #region AddFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() { var stream = new Mock(); - _sfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); + this._sfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); } [Test] @@ -82,87 +70,79 @@ public void AddFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock(); - _sfp.AddFile(_folderInfo.Object, fileName, stream.Object); + this._sfp.AddFile(this._folderInfo.Object, fileName, stream.Object); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Content() { - _sfp.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, null); - } - - #endregion - - #region DeleteFile - + this._sfp.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() { - _sfp.DeleteFile(null); + this._sfp.DeleteFile(null); } [Test] public void DeleteFile_Calls_FileWrapper_Delete_When_File_Exists() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(true); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(true); - _sfp.DeleteFile(_fileInfo.Object); + this._sfp.DeleteFile(this._fileInfo.Object); - _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidSecureFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidSecureFilePath), Times.Once()); } [Test] public void DeleteFile_Does_Not_Call_FileWrapper_Delete_When_File_Does_Not_Exists() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _sfp.DeleteFile(_fileInfo.Object); - - _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Never()); - } + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); - #endregion - - #region FileExists + this._sfp.DeleteFile(this._fileInfo.Object); + this._fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Never()); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() { - _sfp.FileExists(null, Constants.FOLDER_ValidFileName); + this._sfp.FileExists(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_FileName() { - _sfp.FileExists(_folderInfo.Object, null); + this._sfp.FileExists(this._folderInfo.Object, null); } [Test] public void ExistsFile_Calls_FileWrapper_Exists() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _fileWrapper.Verify(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath), Times.Once()); } [Test] public void ExistsFile_Returns_True_When_File_Exists() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(true); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(true); - var result = _sfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsTrue(result); } @@ -170,24 +150,20 @@ public void ExistsFile_Returns_True_When_File_Exists() [Test] public void ExistsFile_Returns_False_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(false); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(false); - var result = _sfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); - } - - #endregion - - #region FolderExists - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderMapping() { - _sfp.FolderExists(Constants.FOLDER_ValidFolderPath, null); + this._sfp.FolderExists(Constants.FOLDER_ValidFolderPath, null); } [Test] @@ -196,7 +172,7 @@ public void ExistsFolder_Throws_On_Null_FolderPath() { var folderMapping = new FolderMappingInfo(); - _sfp.FolderExists(null, folderMapping); + this._sfp.FolderExists(null, folderMapping); } [Test] @@ -204,11 +180,11 @@ public void ExistsFolder_Calls_DirectoryWrapper_Exists() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); - _directoryWrapper.Verify(dw => dw.Exists(Constants.FOLDER_ValidFolderPath), Times.Once()); + this._directoryWrapper.Verify(dw => dw.Exists(Constants.FOLDER_ValidFolderPath), Times.Once()); } [Test] @@ -216,11 +192,11 @@ public void ExistsFolder_Returns_True_When_Folder_Exists() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this._directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - var result = _sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + var result = this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsTrue(result); } @@ -230,34 +206,30 @@ public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); + this._directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); - var result = _sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + var result = this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsFalse(result); - } - - #endregion - - #region GetFileAttributes - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileAttributes_Throws_On_Null_File() { - _sfp.GetFileAttributes(null); + this._sfp.GetFileAttributes(null); } [Test] public void GetFileAttributes_Calls_FileWrapper_GetAttributes() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _sfp.GetFileAttributes(_fileInfo.Object); + this._sfp.GetFileAttributes(this._fileInfo.Object); - _fileWrapper.Verify(fw => fw.GetAttributes(Constants.FOLDER_ValidSecureFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.GetAttributes(Constants.FOLDER_ValidSecureFilePath), Times.Once()); } [Test] @@ -265,11 +237,11 @@ public void GetFileAttributes_Returns_File_Attributes_When_File_Exists() { var expectedFileAttributes = FileAttributes.Normal; - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidSecureFilePath)).Returns(expectedFileAttributes); + this._fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidSecureFilePath)).Returns(expectedFileAttributes); - var result = _sfp.GetFileAttributes(_fileInfo.Object); + var result = this._sfp.GetFileAttributes(this._fileInfo.Object); Assert.AreEqual(expectedFileAttributes, result); } @@ -277,46 +249,42 @@ public void GetFileAttributes_Returns_File_Attributes_When_File_Exists() [Test] public void GetFileAttributes_Returns_Null_When_File_Does_Not_Exist() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidSecureFilePath)).Throws(); + this._fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidSecureFilePath)).Throws(); - var result = _sfp.GetFileAttributes(_fileInfo.Object); + var result = this._sfp.GetFileAttributes(this._fileInfo.Object); Assert.IsNull(result); - } - - #endregion - - #region GetFiles - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFiles_Throws_On_Null_Folder() { - _sfp.GetFiles(null); + this._sfp.GetFiles(null); } [Test] public void GetFiles_Calls_DirectoryWrapper_GetFiles() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.GetFiles(_folderInfo.Object); + this._sfp.GetFiles(this._folderInfo.Object); - _directoryWrapper.Verify(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)); + this._directoryWrapper.Verify(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)); } [Test] public void GetFiles_Count_Equals_DirectoryWrapper_GetFiles_Count() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); var filesReturned = new string[] { "C:\\folder\\file1.txt.resources", "C:\\folder\\file2.txt.resources", "C:\\folder\\file3.txt.resources" }; - _directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); + this._directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); - var files = _sfp.GetFiles(_folderInfo.Object); + var files = this._sfp.GetFiles(this._folderInfo.Object); Assert.AreEqual(filesReturned.Length, files.Length); } @@ -324,44 +292,40 @@ public void GetFiles_Count_Equals_DirectoryWrapper_GetFiles_Count() [Test] public void GetFiles_Return_Valid_FileNames_When_Folder_Contains_Files() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); var filesReturned = new string[] { "C:\\folder\\file1.txt.resources", "C:\\folder\\file2.txt.resources", "C:\\folder\\file3.txt.resources" }; var expectedValues = new string[] { "file1.txt", "file2.txt", "file3.txt" }; - _directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); + this._directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); - var files = _sfp.GetFiles(_folderInfo.Object); + var files = this._sfp.GetFiles(this._folderInfo.Object); CollectionAssert.AreEqual(expectedValues, files); - } - - #endregion - - #region GetFileContent - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileStream_Throws_On_Null_Folder() { - _sfp.GetFileStream(null, Constants.FOLDER_ValidFileName); + this._sfp.GetFileStream(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentException))] public void GetFileStream_Throws_On_Null_FileName() { - _sfp.GetFileStream(_folderInfo.Object, null); + this._sfp.GetFileStream(this._folderInfo.Object, null); } [Test] public void GetFileStream_Calls_FileWrapper_OpenRead() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _fileWrapper.Verify(fw => fw.OpenRead(Constants.FOLDER_ValidSecureFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.OpenRead(Constants.FOLDER_ValidSecureFilePath), Times.Once()); } [Test] @@ -370,11 +334,11 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() var validFileBytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var memoryStream = new MemoryStream(validFileBytes); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidSecureFilePath)).Returns(memoryStream); + this._fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidSecureFilePath)).Returns(memoryStream); - var result = _sfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); byte[] resultBytes; var buffer = new byte[16 * 1024]; @@ -385,6 +349,7 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { ms.Write(buffer, 0, read); } + resultBytes = ms.ToArray(); } @@ -394,49 +359,41 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() [Test] public void GetFileStream_Returns_Null_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidSecureFilePath)).Throws(); + this._fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidSecureFilePath)).Throws(); - var result = _sfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsNull(result); - } - - #endregion - - #region GetFolderProviderIconPath - + } + [Test] public void GetImageUrl_Calls_IconControllerWrapper_IconURL() { var iconControllerWrapper = new Mock(); IconControllerWrapper.RegisterInstance(iconControllerWrapper.Object); - _sfp.GetFolderProviderIconPath(); + this._sfp.GetFolderProviderIconPath(); iconControllerWrapper.Verify(icw => icw.IconURL("FolderSecure", "32x32"), Times.Once()); - } - - #endregion - - #region GetLastModificationTime - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetLastModificationTime_Throws_On_Null_File() { - _sfp.GetLastModificationTime(null); + this._sfp.GetLastModificationTime(null); } [Test] public void GetLastModificationTime_Calls_FileWrapper_GetLastWriteTime() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _sfp.GetLastModificationTime(_fileInfo.Object); + this._sfp.GetLastModificationTime(this._fileInfo.Object); - _fileWrapper.Verify(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidSecureFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidSecureFilePath), Times.Once()); } [Test] @@ -444,11 +401,11 @@ public void GetLastModificationTime_Returns_Valid_Date_When_File_Exists() { var expectedDate = DateTime.Now; - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidSecureFilePath)).Returns(expectedDate); + this._fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidSecureFilePath)).Returns(expectedDate); - var result = _sfp.GetLastModificationTime(_fileInfo.Object); + var result = this._sfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedDate, result); } @@ -458,24 +415,20 @@ public void GetLastModificationTime_Returns_Null_Date_When_File_Does_Not_Exist() { var expectedDate = Null.NullDate; - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidSecureFilePath)).Throws(); + this._fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidSecureFilePath)).Throws(); - var result = _sfp.GetLastModificationTime(_fileInfo.Object); + var result = this._sfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedDate, result); - } - - #endregion - - #region GetSubFolders - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderMapping() { - _sfp.GetSubFolders(Constants.FOLDER_ValidFolderPath, null).ToList(); + this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderPath, null).ToList(); } [Test] @@ -484,7 +437,7 @@ public void GetSubFolders_Throws_On_Null_FolderPath() { var folderMapping = new FolderMappingInfo(); - _sfp.GetSubFolders(null, folderMapping).ToList(); + this._sfp.GetSubFolders(null, folderMapping).ToList(); } [Test] @@ -492,11 +445,11 @@ public void GetSubFolders_Calls_DirectoryWrapper_GetFiles() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); - _directoryWrapper.Verify(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath), Times.Once()); + this._directoryWrapper.Verify(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath), Times.Once()); } [Test] @@ -504,18 +457,19 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] { + var subFolders = new[] + { Constants.FOLDER_ValidSubFolderPath, - Constants.FOLDER_OtherValidSubFolderPath + Constants.FOLDER_OtherValidSubFolderPath, }; - _directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); + this._directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); - var result = _sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + var result = this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); Assert.AreEqual(subFolders.Length, result.Count); } @@ -523,49 +477,47 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() [Test] public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() { - var expectedSubFolders = new[] { + var expectedSubFolders = new[] + { Constants.FOLDER_ValidSubFolderRelativePath, - Constants.FOLDER_OtherValidSubFolderRelativePath + Constants.FOLDER_OtherValidSubFolderRelativePath, }; var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] { + var subFolders = new[] + { Constants.FOLDER_ValidSubFolderPath, - Constants.FOLDER_OtherValidSubFolderPath + Constants.FOLDER_OtherValidSubFolderPath, }; - _directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); + this._directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); - var result = _sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + var result = this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); CollectionAssert.AreEqual(expectedSubFolders, result); - } - - #endregion - - #region IsInSync - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void IsInSync_Throws_On_Null_File() { - _sfp.IsInSync(null); + this._sfp.IsInSync(null); } [Test] public void IsInSync_Returns_True_When_File_Is_In_Sync() { - _fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); var sfp = new Mock { CallBase = true }; - sfp.Setup(fp => fp.GetHash(_fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); + sfp.Setup(fp => fp.GetHash(this._fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); - var result = sfp.Object.IsInSync(_fileInfo.Object); + var result = sfp.Object.IsInSync(this._fileInfo.Object); Assert.IsTrue(result); } @@ -573,25 +525,21 @@ public void IsInSync_Returns_True_When_File_Is_In_Sync() [Test] public void IsInSync_Returns_True_When_File_Is_Not_In_Sync() { - _fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); var sfp = new Mock { CallBase = true }; - sfp.Setup(fp => fp.GetHash(_fileInfo.Object)).Returns(Constants.FOLDER_ModifiedFileHash); + sfp.Setup(fp => fp.GetHash(this._fileInfo.Object)).Returns(Constants.FOLDER_ModifiedFileHash); - var result = sfp.Object.IsInSync(_fileInfo.Object); + var result = sfp.Object.IsInSync(this._fileInfo.Object); Assert.IsTrue(result); - } - - #endregion - - #region RenameFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFile_Throws_On_Null_File() { - _sfp.RenameFile(null, Constants.FOLDER_ValidFileName); + this._sfp.RenameFile(null, Constants.FOLDER_ValidFileName); } [Test] @@ -600,43 +548,39 @@ public void RenameFile_Throws_On_Null_File() [ExpectedException(typeof(ArgumentException))] public void RenameFile_Throws_On_NullOrEmpty_NewFileName(string newFileName) { - _sfp.RenameFile(_fileInfo.Object, newFileName); + this._sfp.RenameFile(this._fileInfo.Object, newFileName); } [Test] public void RenameFile_Calls_FileWrapper_Move_When_FileNames_Are_Not_Equal() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherValidFileName); + this._sfp.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); - _fileWrapper.Verify(fw => fw.Move(Constants.FOLDER_ValidSecureFilePath, Constants.FOLDER_OtherValidSecureFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.Move(Constants.FOLDER_ValidSecureFilePath, Constants.FOLDER_OtherValidSecureFilePath), Times.Once()); } [Test] public void RenameFile_Does_Not_Call_FileWrapper_Move_When_FileNames_Are_Equal() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _sfp.RenameFile(_fileInfo.Object, Constants.FOLDER_ValidFileName); - - _fileWrapper.Verify(fw => fw.Move(It.IsAny(), It.IsAny()), Times.Never()); - } - - #endregion - - #region SetFileAttributes + this._sfp.RenameFile(this._fileInfo.Object, Constants.FOLDER_ValidFileName); + this._fileWrapper.Verify(fw => fw.Move(It.IsAny(), It.IsAny()), Times.Never()); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetFileAttributes_Throws_On_Null_File() { - _sfp.SetFileAttributes(null, FileAttributes.Archive); + this._sfp.SetFileAttributes(null, FileAttributes.Archive); } [Test] @@ -644,36 +588,28 @@ public void SetFileAttributes_Calls_FileWrapper_SetAttributes() { const FileAttributes validFileAttributes = FileAttributes.Archive; - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - _sfp.SetFileAttributes(_fileInfo.Object, validFileAttributes); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Verify(fw => fw.SetAttributes(Constants.FOLDER_ValidSecureFilePath, validFileAttributes), Times.Once()); - } - - #endregion - - #region SupportsFileAttributes + this._sfp.SetFileAttributes(this._fileInfo.Object, validFileAttributes); + this._fileWrapper.Verify(fw => fw.SetAttributes(Constants.FOLDER_ValidSecureFilePath, validFileAttributes), Times.Once()); + } + [Test] public void SupportsFileAttributes_Returns_True() { - var result = _sfp.SupportsFileAttributes(); + var result = this._sfp.SupportsFileAttributes(); Assert.IsTrue(result); - } - - #endregion - - #region UpdateFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Folder() { var stream = new Mock(); - _sfp.UpdateFile(null, Constants.FOLDER_ValidFileName, stream.Object); + this._sfp.UpdateFile(null, Constants.FOLDER_ValidFileName, stream.Object); } [Test] @@ -684,44 +620,42 @@ public void UpdateFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock(); - _sfp.UpdateFile(_folderInfo.Object, fileName, stream.Object); + this._sfp.UpdateFile(this._folderInfo.Object, fileName, stream.Object); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Content() { - _sfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, null); + this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); } [Test] public void UpdateFile_Calls_FileWrapper_Delete_When_File_Exists() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(true); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(true); var stream = new Mock(); - _sfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); + this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); - _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidSecureFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidSecureFilePath), Times.Once()); } [Test] public void UpdateFile_Calls_FileWrapper_Create() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(false); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidSecureFilePath)).Returns(false); var stream = new Mock(); - _sfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); - - _fileWrapper.Verify(fw => fw.Create(Constants.FOLDER_ValidSecureFilePath), Times.Once()); - } + this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); - #endregion + this._fileWrapper.Verify(fw => fw.Create(Constants.FOLDER_ValidSecureFilePath), Times.Once()); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs index a3ac717f25e..61a22a0ce6d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs @@ -1,35 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using DotNetNuke.Abstractions; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Cryptography; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Localization; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Folder { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Cryptography; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Localization; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class StandardFolderProviderTests - { - #region Private Variables - + { private StandardFolderProvider _sfp; private Mock _folderInfo; private Mock _fileInfo; @@ -40,10 +37,8 @@ public class StandardFolderProviderTests private Mock _pathUtils; private Mock _portalControllerMock; private Mock _cryptographyProviderMock; - private Mock _localeControllerMock; - #endregion - - #region Setup + private Mock _localeControllerMock; + [TestFixtureSetUp] public void FixtureSetup() { @@ -56,45 +51,62 @@ public void FixtureSetup() [SetUp] public void Setup() { - _sfp = new StandardFolderProvider(); - _folderInfo = new Mock(); - _fileInfo = new Mock(); - _fileWrapper = new Mock(); - _directoryWrapper = new Mock(); - _folderManager = new Mock(); - _fileManager = new Mock(); - _pathUtils = new Mock(); - _portalControllerMock = new Mock(); - _portalControllerMock.Setup(p => p.GetPortalSettings(Constants.CONTENT_ValidPortalId)) - .Returns(GetPortalSettingsDictionaryMock()); - _portalControllerMock.Setup(p => p.GetCurrentPortalSettings()).Returns(GetPortalSettingsMock()); - _cryptographyProviderMock = new Mock(); - _cryptographyProviderMock.Setup(c => c.EncryptParameter(It.IsAny(), It.IsAny())) + this._sfp = new StandardFolderProvider(); + this._folderInfo = new Mock(); + this._fileInfo = new Mock(); + this._fileWrapper = new Mock(); + this._directoryWrapper = new Mock(); + this._folderManager = new Mock(); + this._fileManager = new Mock(); + this._pathUtils = new Mock(); + this._portalControllerMock = new Mock(); + this._portalControllerMock.Setup(p => p.GetPortalSettings(Constants.CONTENT_ValidPortalId)) + .Returns(this.GetPortalSettingsDictionaryMock()); + this._portalControllerMock.Setup(p => p.GetCurrentPortalSettings()).Returns(this.GetPortalSettingsMock()); + this._cryptographyProviderMock = new Mock(); + this._cryptographyProviderMock.Setup(c => c.EncryptParameter(It.IsAny(), It.IsAny())) .Returns(Guid.NewGuid().ToString("N")); - _localeControllerMock = new Mock(); - _localeControllerMock.Setup(l => l.GetLocales(Constants.CONTENT_ValidPortalId)).Returns(new Dictionary + this._localeControllerMock = new Mock(); + this._localeControllerMock.Setup(l => l.GetLocales(Constants.CONTENT_ValidPortalId)).Returns(new Dictionary { - {"en-us", new Locale()} + { "en-us", new Locale() }, }); - FileWrapper.RegisterInstance(_fileWrapper.Object); - DirectoryWrapper.RegisterInstance(_directoryWrapper.Object); - FolderManager.RegisterInstance(_folderManager.Object); - FileManager.RegisterInstance(_fileManager.Object); - PathUtils.RegisterInstance(_pathUtils.Object); - PortalController.SetTestableInstance(_portalControllerMock.Object); - ComponentFactory.RegisterComponentInstance("CryptographyProviderMock", _cryptographyProviderMock.Object); - LocaleController.RegisterInstance(_localeControllerMock.Object); + FileWrapper.RegisterInstance(this._fileWrapper.Object); + DirectoryWrapper.RegisterInstance(this._directoryWrapper.Object); + FolderManager.RegisterInstance(this._folderManager.Object); + FileManager.RegisterInstance(this._fileManager.Object); + PathUtils.RegisterInstance(this._pathUtils.Object); + PortalController.SetTestableInstance(this._portalControllerMock.Object); + ComponentFactory.RegisterComponentInstance("CryptographyProviderMock", this._cryptographyProviderMock.Object); + LocaleController.RegisterInstance(this._localeControllerMock.Object); + } + + [TearDown] + public void TearDown() + { + MockComponentProvider.ResetContainer(); + TestableGlobals.ClearInstance(); + PortalController.ClearInstance(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void AddFile_Throws_On_Null_Folder() + { + var stream = new Mock(); + + this._sfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); } private Dictionary GetPortalSettingsDictionaryMock() { - var portalSettingsDictionary = new Dictionary(); + var portalSettingsDictionary = new Dictionary(); portalSettingsDictionary.Add("AddCachebusterToResourceUris", true.ToString()); return portalSettingsDictionary; } - + private PortalSettings GetPortalSettingsMock() { var portalSettingsMock = new Mock(); @@ -106,27 +118,6 @@ private PortalSettings GetPortalSettingsMock() return portalSettingsMock.Object; } - [TearDown] - public void TearDown() - { - MockComponentProvider.ResetContainer(); - TestableGlobals.ClearInstance(); - PortalController.ClearInstance(); - } - - #endregion - - #region AddFile - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void AddFile_Throws_On_Null_Folder() - { - var stream = new Mock(); - - _sfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); - } - [Test] [TestCase(null)] [TestCase("")] @@ -135,87 +126,78 @@ public void AddFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock(); - _sfp.AddFile(_folderInfo.Object, fileName, stream.Object); + this._sfp.AddFile(this._folderInfo.Object, fileName, stream.Object); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Content() { - _sfp.AddFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, null); - } - - #endregion - - #region DeleteFile - + this._sfp.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() { - _sfp.DeleteFile(null); - } - - //[Test] - //public void DeleteFile_Calls_FileWrapper_Delete_When_File_Exists() - //{ - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); - - // _sfp.DeleteFile(_fileInfo.Object); - - // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Once()); - //} - - //[Test] - //public void DeleteFile_Does_Not_Call_FileWrapper_Delete_When_File_Does_Not_Exist() - //{ - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); - - // _sfp.DeleteFile(_fileInfo.Object); - - // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Never()); - //} - - #endregion - - #region FileExists - + this._sfp.DeleteFile(null); + } + + // [Test] + // public void DeleteFile_Calls_FileWrapper_Delete_When_File_Exists() + // { + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + + // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); + + // _sfp.DeleteFile(_fileInfo.Object); + + // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Once()); + // } + + // [Test] + // public void DeleteFile_Does_Not_Call_FileWrapper_Delete_When_File_Does_Not_Exist() + // { + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + + // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); + + // _sfp.DeleteFile(_fileInfo.Object); + + // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Never()); + // } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() { - _sfp.FileExists(null, Constants.FOLDER_ValidFileName); + this._sfp.FileExists(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_FileName() { - _sfp.FileExists(_folderInfo.Object, null); + this._sfp.FileExists(this._folderInfo.Object, null); } [Test] public void ExistsFile_Calls_FileWrapper_Exists() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _fileWrapper.Verify(fw => fw.Exists(Constants.FOLDER_ValidFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.Exists(Constants.FOLDER_ValidFilePath), Times.Once()); } [Test] public void ExistsFile_Returns_True_When_File_Exists() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); - var result = _sfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsTrue(result); } @@ -223,24 +205,20 @@ public void ExistsFile_Returns_True_When_File_Exists() [Test] public void ExistsFile_Returns_False_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); - var result = _sfp.FileExists(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); - } - - #endregion - - #region FolderExists - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderMapping() { - _sfp.FolderExists(Constants.FOLDER_ValidFolderPath, null); + this._sfp.FolderExists(Constants.FOLDER_ValidFolderPath, null); } [Test] @@ -249,7 +227,7 @@ public void ExistsFolder_Throws_On_Null_FolderPath() { var folderMapping = new FolderMappingInfo(); - _sfp.FolderExists(null, folderMapping); + this._sfp.FolderExists(null, folderMapping); } [Test] @@ -257,11 +235,11 @@ public void ExistsFolder_Calls_DirectoryWrapper_Exists() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); - _directoryWrapper.Verify(dw => dw.Exists(Constants.FOLDER_ValidFolderPath), Times.Once()); + this._directoryWrapper.Verify(dw => dw.Exists(Constants.FOLDER_ValidFolderPath), Times.Once()); } [Test] @@ -269,11 +247,11 @@ public void ExistsFolder_Returns_True_When_Folder_Exists() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this._directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - var result = _sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + var result = this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsTrue(result); } @@ -283,93 +261,84 @@ public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); + this._directoryWrapper.Setup(dw => dw.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); - var result = _sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); + var result = this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsFalse(result); - } - - #endregion - - #region GetFileAttributes - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileAttributes_Throws_On_Null_File() { - _sfp.GetFileAttributes(null); + this._sfp.GetFileAttributes(null); } - //[Test] - //public void GetFileAttributes_Calls_FileWrapper_GetAttributes() - //{ + // [Test] + // public void GetFileAttributes_Calls_FileWrapper_GetAttributes() + // { // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - // _sfp.GetFileAttributes(_fileInfo.Object); + // _sfp.GetFileAttributes(_fileInfo.Object); - // _fileWrapper.Verify(fw => fw.GetAttributes(Constants.FOLDER_ValidFilePath), Times.Once()); - //} + // _fileWrapper.Verify(fw => fw.GetAttributes(Constants.FOLDER_ValidFilePath), Times.Once()); + // } - //[Test] - //public void GetFileAttributes_Returns_File_Attributes_When_File_Exists() - //{ + // [Test] + // public void GetFileAttributes_Returns_File_Attributes_When_File_Exists() + // { // var expectedFileAttributes = FileAttributes.Normal; - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidFilePath)).Returns(expectedFileAttributes); + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - // var result = _sfp.GetFileAttributes(_fileInfo.Object); + // _fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidFilePath)).Returns(expectedFileAttributes); - // Assert.AreEqual(expectedFileAttributes, result); - //} + // var result = _sfp.GetFileAttributes(_fileInfo.Object); + // Assert.AreEqual(expectedFileAttributes, result); + // } [Test] public void GetFileAttributes_Returns_Null_When_File_Does_Not_Exist() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidFilePath)).Throws(); + this._fileWrapper.Setup(fw => fw.GetAttributes(Constants.FOLDER_ValidFilePath)).Throws(); - var result = _sfp.GetFileAttributes(_fileInfo.Object); + var result = this._sfp.GetFileAttributes(this._fileInfo.Object); Assert.IsNull(result); - } - - #endregion - - #region GetFiles - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFiles_Throws_On_Null_Folder() { - _sfp.GetFiles(null); + this._sfp.GetFiles(null); } [Test] public void GetFiles_Calls_DirectoryWrapper_GetFiles() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.GetFiles(_folderInfo.Object); + this._sfp.GetFiles(this._folderInfo.Object); - _directoryWrapper.Verify(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)); + this._directoryWrapper.Verify(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)); } [Test] public void GetFiles_Count_Equals_DirectoryWrapper_GetFiles_Count() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - var filesReturned = new[] { "", "", "" }; + var filesReturned = new[] { string.Empty, string.Empty, string.Empty }; - _directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); + this._directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); - var files = _sfp.GetFiles(_folderInfo.Object); + var files = this._sfp.GetFiles(this._folderInfo.Object); Assert.AreEqual(filesReturned.Length, files.Length); } @@ -377,44 +346,40 @@ public void GetFiles_Count_Equals_DirectoryWrapper_GetFiles_Count() [Test] public void GetFiles_Returns_Valid_FileNames_When_Folder_Contains_Files() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); var filesReturned = new[] { "C:\\folder\\file1.txt", "C:\\folder\\file2.txt", "C:\\folder\\file3.txt" }; var expectedValues = new[] { "file1.txt", "file2.txt", "file3.txt" }; - _directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); + this._directoryWrapper.Setup(dw => dw.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(filesReturned); - var files = _sfp.GetFiles(_folderInfo.Object); + var files = this._sfp.GetFiles(this._folderInfo.Object); CollectionAssert.AreEqual(expectedValues, files); - } - - #endregion - - #region GetFileContent - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileStream_Throws_On_Null_Folder() { - _sfp.GetFileStream(null, Constants.FOLDER_ValidFileName); + this._sfp.GetFileStream(null, Constants.FOLDER_ValidFileName); } [Test] [ExpectedException(typeof(ArgumentException))] public void GetFileStream_Throws_On_Null_FileName() { - _sfp.GetFileStream(_folderInfo.Object, null); + this._sfp.GetFileStream(this._folderInfo.Object, null); } [Test] public void GetFileStream_Calls_FileWrapper_OpenRead() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - _fileWrapper.Verify(fw => fw.OpenRead(Constants.FOLDER_ValidFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.OpenRead(Constants.FOLDER_ValidFilePath), Times.Once()); } [Test] @@ -423,11 +388,11 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() var validFileBytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var memoryStream = new MemoryStream(validFileBytes); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidFilePath)).Returns(memoryStream); + this._fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidFilePath)).Returns(memoryStream); - var result = _sfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); byte[] resultBytes; var buffer = new byte[16 * 1024]; @@ -438,6 +403,7 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { ms.Write(buffer, 0, read); } + resultBytes = ms.ToArray(); } @@ -447,88 +413,75 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() [Test] public void GetFileStream_Returns_Null_When_File_Does_Not_Exist() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidFilePath)).Throws(); + this._fileWrapper.Setup(fw => fw.OpenRead(Constants.FOLDER_ValidFilePath)).Throws(); - var result = _sfp.GetFileStream(_folderInfo.Object, Constants.FOLDER_ValidFileName); + var result = this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsNull(result); - } - - #endregion - - #region GetFolderProviderIconPath - + } + [Test] public void GetImageUrl_Calls_IconControllerWrapper_IconURL() { var iconControllerWrapper = new Mock(); IconControllerWrapper.RegisterInstance(iconControllerWrapper.Object); - _sfp.GetFolderProviderIconPath(); + this._sfp.GetFolderProviderIconPath(); iconControllerWrapper.Verify(icw => icw.IconURL("FolderStandard", "32x32"), Times.Once()); - } - - #endregion - - #region GetLastModificationTime - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetLastModificationTime_Throws_On_Null_File() { - _sfp.GetLastModificationTime(null); + this._sfp.GetLastModificationTime(null); } - //[Test] - //public void GetLastModificationTime_Calls_FileWrapper_GetLastWriteTime() - //{ + // [Test] + // public void GetLastModificationTime_Calls_FileWrapper_GetLastWriteTime() + // { // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - // _sfp.GetLastModificationTime(_fileInfo.Object); + // _sfp.GetLastModificationTime(_fileInfo.Object); - // _fileWrapper.Verify(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidFilePath), Times.Once()); - //} + // _fileWrapper.Verify(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidFilePath), Times.Once()); + // } - //[Test] - //public void GetLastModificationTime_Returns_Valid_Date_When_File_Exists() - //{ + // [Test] + // public void GetLastModificationTime_Returns_Valid_Date_When_File_Exists() + // { // var expectedDate = DateTime.Now; - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidFilePath)).Returns(expectedDate); + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - // var result = _sfp.GetLastModificationTime(_fileInfo.Object); + // _fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidFilePath)).Returns(expectedDate); - // Assert.AreEqual(expectedDate, result); - //} + // var result = _sfp.GetLastModificationTime(_fileInfo.Object); + // Assert.AreEqual(expectedDate, result); + // } [Test] public void GetLastModificationTime_Returns_Null_Date_When_File_Does_Not_Exist() { var expectedDate = Null.NullDate; - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidFilePath)).Throws(); + this._fileWrapper.Setup(fw => fw.GetLastWriteTime(Constants.FOLDER_ValidFilePath)).Throws(); - var result = _sfp.GetLastModificationTime(_fileInfo.Object); + var result = this._sfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedDate, result); - } - - #endregion - - #region GetSubFolders - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderMapping() { - _sfp.GetSubFolders(Constants.FOLDER_ValidFolderPath, null).ToList(); + this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderPath, null).ToList(); } [Test] @@ -537,7 +490,7 @@ public void GetSubFolders_Throws_On_Null_FolderPath() { var folderMapping = new FolderMappingInfo(); - _sfp.GetSubFolders(null, folderMapping).ToList(); + this._sfp.GetSubFolders(null, folderMapping).ToList(); } [Test] @@ -545,11 +498,11 @@ public void GetSubFolders_Calls_DirectoryWrapper_GetDirectories() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(folderMapping.PortalID, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); - _directoryWrapper.Verify(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath), Times.Once()); + this._directoryWrapper.Verify(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath), Times.Once()); } [Test] @@ -557,18 +510,19 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() { var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] { + var subFolders = new[] + { Constants.FOLDER_ValidSubFolderPath, - Constants.FOLDER_OtherValidSubFolderPath + Constants.FOLDER_OtherValidSubFolderPath, }; - _directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); + this._directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); - var result = _sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + var result = this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); Assert.AreEqual(subFolders.Length, result.Count); } @@ -576,53 +530,81 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() [Test] public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() { - var expectedSubFolders = new[] { + var expectedSubFolders = new[] + { Constants.FOLDER_ValidSubFolderRelativePath, - Constants.FOLDER_OtherValidSubFolderRelativePath + Constants.FOLDER_OtherValidSubFolderRelativePath, }; var folderMapping = new FolderMappingInfo { PortalID = Constants.CONTENT_ValidPortalId }; - _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); - _pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] { + var subFolders = new[] + { Constants.FOLDER_ValidSubFolderPath, - Constants.FOLDER_OtherValidSubFolderPath + Constants.FOLDER_OtherValidSubFolderPath, }; - _directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); + this._directoryWrapper.Setup(dw => dw.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(subFolders); - var result = _sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); + var result = this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); CollectionAssert.AreEqual(expectedSubFolders, result); - } + } + + [Test] + public void GetFileUrl_WhenCurrentPortalSettingsReturnsNull_DontThrow() + { + // arrange + var sfp = new Mock + { + CallBase = true + }; + + sfp.Setup(x => x.GetPortalSettings(Constants.CONTENT_ValidPortalId)) + .Returns(GetPortalSettingsMock()); + + _fileInfo.Setup(x => x.FileName) + .Returns(Constants.FOLDER_ValidFileName); - #endregion + _fileInfo.Setup(x => x.PortalId) + .Returns(Constants.CONTENT_ValidPortalId); - #region GetFilesUrl + _portalControllerMock.Setup(x => x.GetCurrentPortalSettings()) + .Returns(null); + + // act + string fileUrl = null; + TestDelegate action = () => fileUrl = sfp.Object.GetFileUrl(_fileInfo.Object); + + // assert + Assert.DoesNotThrow(action); + Assert.IsNotNull(fileUrl); + } [Test] [TestCase("(")] [TestCase(")")] - [TestCase("")] + [TestCase("")] public void GetFileUrl_ReturnsStandardUrl_WhenFileUrlDoesNotContainInvalidCharactes(string fileNameChar) { - //Arrange + // Arrange var sfp = new Mock { CallBase = true }; - var portalSettingsMock = GetPortalSettingsMock(); + var portalSettingsMock = this.GetPortalSettingsMock(); sfp.Setup(fp => fp.GetPortalSettings(Constants.CONTENT_ValidPortalId)).Returns(portalSettingsMock); - _fileInfo.Setup(f => f.FileName).Returns($"MyFileName {fileNameChar} Copy"); - _fileInfo.Setup(f => f.PortalId).Returns(Constants.CONTENT_ValidPortalId); - - //Act - var fileUrl = sfp.Object.GetFileUrl(_fileInfo.Object); + this._fileInfo.Setup(f => f.FileName).Returns($"MyFileName {fileNameChar} Copy"); + this._fileInfo.Setup(f => f.PortalId).Returns(Constants.CONTENT_ValidPortalId); - //Assert + // Act + var fileUrl = sfp.Object.GetFileUrl(this._fileInfo.Object); + + // Assert Assert.IsFalse(fileUrl.ToLowerInvariant().Contains("linkclick")); } - + [Test] [TestCase("?")] [TestCase("&")] @@ -636,39 +618,36 @@ public void GetFileUrl_ReturnsStandardUrl_WhenFileUrlDoesNotContainInvalidCharac [TestCase("%")] public void GetFileUrl_ReturnsLinkclickUrl_WhenFileUrlContainsInvalidCharactes(string fileNameChar) { - //Arrange + // Arrange var sfp = new Mock { CallBase = true }; - var portalSettingsMock = GetPortalSettingsMock(); + var portalSettingsMock = this.GetPortalSettingsMock(); sfp.Setup(fp => fp.GetPortalSettings(Constants.CONTENT_ValidPortalId)).Returns(portalSettingsMock); - _fileInfo.Setup(f => f.FileName).Returns($"MyFileName {fileNameChar} Copy"); - _fileInfo.Setup(f => f.PortalId).Returns(Constants.CONTENT_ValidPortalId); + this._fileInfo.Setup(f => f.FileName).Returns($"MyFileName {fileNameChar} Copy"); + this._fileInfo.Setup(f => f.PortalId).Returns(Constants.CONTENT_ValidPortalId); - //Act - var fileUrl = sfp.Object.GetFileUrl(_fileInfo.Object); + // Act + var fileUrl = sfp.Object.GetFileUrl(this._fileInfo.Object); - //Assert + // Assert Assert.IsTrue(fileUrl.ToLowerInvariant().Contains("linkclick")); - } - #endregion - - #region IsInSync - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void IsInSync_Throws_On_Null_File() { - _sfp.IsInSync(null); + this._sfp.IsInSync(null); } [Test] public void IsInSync_Returns_True_When_File_Is_In_Sync() { - _fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); var sfp = new Mock { CallBase = true }; - sfp.Setup(fp => fp.GetHash(_fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); + sfp.Setup(fp => fp.GetHash(this._fileInfo.Object)).Returns(Constants.FOLDER_UnmodifiedFileHash); - var result = sfp.Object.IsInSync(_fileInfo.Object); + var result = sfp.Object.IsInSync(this._fileInfo.Object); Assert.IsTrue(result); } @@ -676,25 +655,21 @@ public void IsInSync_Returns_True_When_File_Is_In_Sync() [Test] public void IsInSync_Returns_True_When_File_Is_Not_In_Sync() { - _fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); + this._fileInfo.Setup(fi => fi.SHA1Hash).Returns(Constants.FOLDER_UnmodifiedFileHash); var sfp = new Mock { CallBase = true }; - sfp.Setup(fp => fp.GetHash(_fileInfo.Object)).Returns(Constants.FOLDER_ModifiedFileHash); + sfp.Setup(fp => fp.GetHash(this._fileInfo.Object)).Returns(Constants.FOLDER_ModifiedFileHash); - var result = sfp.Object.IsInSync(_fileInfo.Object); + var result = sfp.Object.IsInSync(this._fileInfo.Object); Assert.IsTrue(result); - } - - #endregion - - #region RenameFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFile_Throws_On_Null_File() { - _sfp.RenameFile(null, Constants.FOLDER_ValidFileName); + this._sfp.RenameFile(null, Constants.FOLDER_ValidFileName); } [Test] @@ -703,80 +678,67 @@ public void RenameFile_Throws_On_Null_File() [ExpectedException(typeof(ArgumentException))] public void RenameFile_Throws_On_NullOrEmpty_NewFileName(string newFileName) { - _sfp.RenameFile(_fileInfo.Object, newFileName); + this._sfp.RenameFile(this._fileInfo.Object, newFileName); } [Test] public void RenameFile_Calls_FileWrapper_Move_When_FileNames_Are_Not_Equal() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - _fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); - _folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(_folderInfo.Object); - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); + this._fileInfo.Setup(fi => fi.FolderId).Returns(Constants.FOLDER_ValidFolderId); + this._folderManager.Setup(fm => fm.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(this._folderInfo.Object); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _sfp.RenameFile(_fileInfo.Object, Constants.FOLDER_OtherValidFileName); + this._sfp.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); - _fileWrapper.Verify(fw => fw.Move(Constants.FOLDER_ValidFilePath, Constants.FOLDER_OtherValidFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.Move(Constants.FOLDER_ValidFilePath, Constants.FOLDER_OtherValidFilePath), Times.Once()); } [Test] public void RenameFile_Does_Not_Call_FileWrapper_Move_When_FileNames_Are_Equal() { - _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - _fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - - _sfp.RenameFile(_fileInfo.Object, Constants.FOLDER_ValidFileName); - - _fileWrapper.Verify(fw => fw.Move(It.IsAny(), It.IsAny()), Times.Never()); - } + this._fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + this._fileInfo.Setup(fi => fi.FileName).Returns(Constants.FOLDER_ValidFileName); - #endregion - - #region SetFileAttributes + this._sfp.RenameFile(this._fileInfo.Object, Constants.FOLDER_ValidFileName); + this._fileWrapper.Verify(fw => fw.Move(It.IsAny(), It.IsAny()), Times.Never()); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetFileAttributes_Throws_On_Null_File() { - _sfp.SetFileAttributes(null, FileAttributes.Archive); - } - - //[Test] - //public void SetFileAttributes_Calls_FileWrapper_SetAttributes() - //{ - // const FileAttributes validFileAttributes = FileAttributes.Archive; - - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _sfp.SetFileAttributes(_fileInfo.Object, validFileAttributes); - - // _fileWrapper.Verify(fw => fw.SetAttributes(Constants.FOLDER_ValidFilePath, validFileAttributes), Times.Once()); - //} - - #endregion - - #region SupportsFileAttributes - + this._sfp.SetFileAttributes(null, FileAttributes.Archive); + } + + // [Test] + // public void SetFileAttributes_Calls_FileWrapper_SetAttributes() + // { + // const FileAttributes validFileAttributes = FileAttributes.Archive; + + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + + // _sfp.SetFileAttributes(_fileInfo.Object, validFileAttributes); + + // _fileWrapper.Verify(fw => fw.SetAttributes(Constants.FOLDER_ValidFilePath, validFileAttributes), Times.Once()); + // } [Test] public void SupportsFileAttributes_Returns_True() { - var result = _sfp.SupportsFileAttributes(); + var result = this._sfp.SupportsFileAttributes(); Assert.IsTrue(result); - } - - #endregion - - #region UpdateFile - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Folder() { var stream = new Mock(); - _sfp.UpdateFile(null, Constants.FOLDER_ValidFileName, stream.Object); + this._sfp.UpdateFile(null, Constants.FOLDER_ValidFileName, stream.Object); } [Test] @@ -787,44 +749,42 @@ public void UpdateFile_Throws_On_NullOrEmpty_FileName(string fileName) { var stream = new Mock(); - _sfp.UpdateFile(_folderInfo.Object, fileName, stream.Object); + this._sfp.UpdateFile(this._folderInfo.Object, fileName, stream.Object); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Content() { - _sfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, null); + this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); } [Test] public void UpdateFile_Calls_FileWrapper_Delete_When_File_Exists() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); var stream = new Mock(); - _sfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); + this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); - _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Once()); + this._fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Once()); } [Test] public void UpdateFile_Calls_FileWrapper_Create() { - _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); + this._fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); var stream = new Mock(); - _sfp.UpdateFile(_folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); - - _fileWrapper.Verify(fw => fw.Create(Constants.FOLDER_ValidFilePath), Times.Once()); - } + this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); - #endregion + this._fileWrapper.Verify(fw => fw.Create(Constants.FOLDER_ValidFilePath), Times.Once()); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs index 39dc3e79906..cfc39211bca 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs @@ -1,27 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Reflection; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Membership; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Profile; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Membership { + using System; + using System.Reflection; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Membership; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Profile; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class MembershipProviderTests : DnnUnitTest { @@ -67,8 +68,8 @@ public void TearDown() { } - //TODO: Must be moved to integration tests. - //Note: this is the only test in core unit testing project that requires a working db connection to run. + // TODO: Must be moved to integration tests. + // Note: this is the only test in core unit testing project that requires a working db connection to run. [Test] [Ignore] public void Password_Should_Saved_In_History_During_Create_User() @@ -76,7 +77,7 @@ public void Password_Should_Saved_In_History_During_Create_User() var user = CreateNewUser(); var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", AppDomain.CurrentDomain.BaseDirectory); - simulator.SimulateRequest(new Uri(WebsiteAppPath)); + simulator.SimulateRequest(new Uri(this.WebsiteAppPath)); HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current); HttpContextSource.RegisterInstance(httpContextBase); @@ -117,7 +118,8 @@ private static UserInfo CreateNewUser() UserInfo user = null; - Assert.DoesNotThrow(() => + Assert.DoesNotThrow( + () => { user = new UserInfo { @@ -131,7 +133,7 @@ private static UserInfo CreateNewUser() { Approved = true, Password = Constants.DefaultPassword - } + }, }; }, "Make sure your connection string is set correctly in the App.config file"); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs index 28d1129b1e0..cd8dd5ba728 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Web; -using DotNetNuke.Common; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Permissions { + using System.Collections.Generic; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class PermissionTests : DnnUnitTest { @@ -69,7 +70,7 @@ public void PortalSecurity_IsInRoles_NonAdmin_IsInRole_Is_True() [Test] public void PortalSecurity_IsInRoles_NonAdminUser_True_WhenRoleIsFollowerRoleAndRoleEntityIsFollowedByUser() { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = Constants.USER_TenId }; var relatedUser = new UserInfo { IsSuperUser = false, UserID = Constants.USER_ValidId }; string roles = "FOLLOWER:" + relatedUser.UserID; @@ -87,14 +88,14 @@ public void PortalSecurity_IsInRoles_NonAdminUser_True_WhenRoleIsFollowerRoleAnd var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsTrue(PortalSecurity.IsInRoles(user, portalSettings, roles)); } [Test] public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFollowerRoleAndRoleEntityIsNotFollowedByUser() { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = Constants.USER_TenId }; var relatedUser = new UserInfo { IsSuperUser = false, UserID = Constants.USER_ValidId }; string roles = "FOLLOWER:" + relatedUser.UserID; @@ -112,7 +113,7 @@ public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFollowerRoleAn var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsFalse(PortalSecurity.IsInRoles(user, portalSettings, roles)); } @@ -121,7 +122,7 @@ public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFollowerRoleAn [TestCase(RelationshipStatus.Pending)] public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFollowerRoleAndRelationshipIsNotAccepted(RelationshipStatus relationshipStatus) { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = Constants.USER_TenId }; var relatedUser = new UserInfo { IsSuperUser = false, UserID = Constants.USER_ValidId }; string roles = "FOLLOWER:" + relatedUser.UserID; @@ -139,17 +140,17 @@ public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFollowerRoleAn var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsFalse(PortalSecurity.IsInRoles(user, portalSettings, roles)); } [Test] public void PortalSecurity_IsInRoles_NonAdminUser_True_WhenRoleIsFriendRoleAndRoleEntityIsFriend() { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = Constants.USER_TenId }; var relatedUser = new UserInfo { IsSuperUser = false, UserID = Constants.USER_ValidId }; - string roles = "FRIEND:"+relatedUser.UserID; + string roles = "FRIEND:" + relatedUser.UserID; var mockUserController = new Mock(); mockUserController.Setup(uc => uc.GetUserById(It.IsAny(), Constants.USER_ValidId)).Returns(relatedUser); @@ -159,19 +160,19 @@ public void PortalSecurity_IsInRoles_NonAdminUser_True_WhenRoleIsFriendRoleAndRo mockRelationShipController.Setup( rsc => rsc.GetFriendRelationship(It.Is(u => u.UserID == Constants.USER_TenId), It.Is(u => u.UserID == Constants.USER_ValidId))) - .Returns(new UserRelationship() {Status = RelationshipStatus.Accepted}); + .Returns(new UserRelationship() { Status = RelationshipStatus.Accepted }); RelationshipController.SetTestableInstance(mockRelationShipController.Object); - + var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsTrue(PortalSecurity.IsInRoles(user, portalSettings, roles)); } [Test] public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFriendRoleAndRoleEntityIsNotFriend() { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = Constants.USER_TenId }; var relatedUser = new UserInfo { IsSuperUser = false, UserID = Constants.USER_ValidId }; string roles = "FRIEND:" + relatedUser.UserID; @@ -189,7 +190,7 @@ public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFriendRoleAndR var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsFalse(PortalSecurity.IsInRoles(user, portalSettings, roles)); } @@ -198,7 +199,7 @@ public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFriendRoleAndR [TestCase(RelationshipStatus.Pending)] public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFriendRoleAndRelationshipIsNotAccepted(RelationshipStatus relationshipStatus) { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = Constants.USER_TenId }; var relatedUser = new UserInfo { IsSuperUser = false, UserID = Constants.USER_ValidId }; string roles = "FRIEND:" + relatedUser.UserID; @@ -216,34 +217,33 @@ public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsFriendRoleAndR var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsFalse(PortalSecurity.IsInRoles(user, portalSettings, roles)); } [Test] public void PortalSecurity_IsInRoles_NonAdminUser_True_WhenRoleIsOwnerRoleAndRoleEntityIsUser() { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = UserId }; - string roles = "OWNER:"+UserId; + string roles = "OWNER:" + UserId; var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsTrue(PortalSecurity.IsInRoles(user, portalSettings, roles)); } - - + [Test] public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsOwnerRoleAndRoleEntityIsNotUser() { - //Arrange + // Arrange var user = new UserInfo { IsSuperUser = false, UserID = UserId }; - string roles = "OWNER:" + UserId+1; + string roles = "OWNER:" + UserId + 1; var portalSettings = SetupPortalSettings(); - //Act and Assert + // Act and Assert Assert.IsFalse(PortalSecurity.IsInRoles(user, portalSettings, roles)); } @@ -261,46 +261,44 @@ public void PortalSecurity_IsInRoles_NonAdmin_In_Deny_Role_Is_False() Assert.IsFalse(PortalSecurity.IsInRoles(user, portalSettings, roles)); } - //[Test] - //public void CorePermissionProvider_HasModuleAccess_Super_User_Is_Always_True() - //{ + // [Test] + // public void CorePermissionProvider_HasModuleAccess_Super_User_Is_Always_True() + // { // CreateUser(true, new List() { "SomeRoleName" }); - // var permissionProvider = new CorePermissionProvider(); + // var permissionProvider = new CorePermissionProvider(); // Assert.IsTrue(permissionProvider.HasModuleAccess(SecurityAccessLevel.Anonymous, "", new ModuleInfo())); - //} - - - //[Test] - //public void CorePermissionProvider_HasModuleAccess_SecurityLevelAnonymous_Is_Always_True() - //{ + // } + + // [Test] + // public void CorePermissionProvider_HasModuleAccess_SecurityLevelAnonymous_Is_Always_True() + // { // CreateUser(false, new List() { "SomeRoleName" }); - // var permissionProvider = new CorePermissionProvider(); + // var permissionProvider = new CorePermissionProvider(); // Assert.IsTrue(permissionProvider.HasModuleAccess(SecurityAccessLevel.Anonymous, "", new ModuleInfo())); - //} + // } - //[Test] - //public void CorePermissionProvider_HasModuleAccess_SecurityLevelHost_Is_False_For_Non_SuperUser() - //{ + // [Test] + // public void CorePermissionProvider_HasModuleAccess_SecurityLevelHost_Is_False_For_Non_SuperUser() + // { // CreateUser(false, new List() { "SomeRoleName" }); - // var permissionProvider = new CorePermissionProvider(); + // var permissionProvider = new CorePermissionProvider(); // Assert.IsFalse(permissionProvider.HasModuleAccess(SecurityAccessLevel.Host, "", new ModuleInfo())); - //} + // } - //[Test] - //public void CorePermissionProvider_HasModuleAccess_SecurityLevelView_Is_False_For_User_Without_View_Role() - //{ + // [Test] + // public void CorePermissionProvider_HasModuleAccess_SecurityLevelView_Is_False_For_User_Without_View_Role() + // { // CreateUser(false, new List() { "RoleWithoutViewPermission" }); // var modulePermissionCollection = new ModulePermissionCollection(); // AddModulePermission(modulePermissionCollection, "View", Convert.ToInt32(SetupPortalSettings().AdministratorRoleId)); // var module = new ModuleInfo {InheritViewPermissions = false, ModulePermissions = modulePermissionCollection}; - // var permissionProvider = new CorePermissionProvider(); + // var permissionProvider = new CorePermissionProvider(); // Assert.IsFalse(permissionProvider.HasModuleAccess(SecurityAccessLevel.View, "", module)); - //} - + // } private static PortalSettings SetupPortalSettings() { var mockPortalController = new Mock(); @@ -310,6 +308,14 @@ private static PortalSettings SetupPortalSettings() return portalSettings; } + private static void AddModulePermission(ModulePermissionCollection permissions, string key, int roleId) + { + var permissionController = new PermissionController(); + var permission = (PermissionInfo)permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", key)[0]; + var modulePermission = new ModulePermissionInfo { PermissionID = permission.PermissionID, RoleID = roleId, AllowAccess = true }; + permissions.Add(modulePermission); + } + private void CreateUser(bool isSuperUser, IEnumerable Roles) { var user = new UserInfo { IsSuperUser = isSuperUser, UserID = UserId }; @@ -319,21 +325,13 @@ private void CreateUser(bool isSuperUser, IEnumerable Roles) { userRoles.Add(new UserRoleInfo() { RoleName = role, Status = RoleStatus.Approved }); } + mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == UserId), It.IsAny())).Returns(userRoles); - var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator(WebsitePhysicalAppPath); + var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator(this.WebsitePhysicalAppPath); simulator.SimulateRequest(); HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current); HttpContextSource.RegisterInstance(httpContextBase); HttpContext.Current.Items["UserInfo"] = user; } - - private static void AddModulePermission(ModulePermissionCollection permissions, string key, int roleId) - { - var permissionController = new PermissionController(); - var permission = (PermissionInfo)permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", key)[0]; - var modulePermission = new ModulePermissionInfo { PermissionID = permission.PermissionID, RoleID = roleId, AllowAccess = true }; - permissions.Add(modulePermission); - } - } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs index 5db1443b4dd..8c55d236b50 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs @@ -1,16 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities.Internal; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities.Internal; + using NUnit.Framework; + [TestFixture] public class RetryableActionTests { @@ -19,8 +18,8 @@ public class RetryableActionTests [SetUp] public void Setup() { - _sleepMonitor = new SleepMonitor(); - RetryableAction.SleepAction = _sleepMonitor.GoToSleep; + this._sleepMonitor = new SleepMonitor(); + RetryableAction.SleepAction = this._sleepMonitor.GoToSleep; } [Test] @@ -53,9 +52,9 @@ public void DelaysIncreaseWithEachRetry() retryable.TryIt(); - var firstRetry = _sleepMonitor.SleepPeriod[0]; - var secondRetry = _sleepMonitor.SleepPeriod[1]; - var thirdRetry = _sleepMonitor.SleepPeriod[2]; + var firstRetry = this._sleepMonitor.SleepPeriod[0]; + var secondRetry = this._sleepMonitor.SleepPeriod[1]; + var thirdRetry = this._sleepMonitor.SleepPeriod[2]; Assert.AreEqual(5, firstRetry); Assert.AreEqual(50, secondRetry); @@ -83,34 +82,37 @@ private static RetryableAction CreateRetryable(Action action, int factor) } } - class SleepMonitor + internal class SleepMonitor { private readonly List _periods = new List(); - public void GoToSleep(int delay) - { - _periods.Add(delay); - } - public IList SleepPeriod { get { - return _periods.AsReadOnly(); + return this._periods.AsReadOnly(); } } + + public void GoToSleep(int delay) + { + this._periods.Add(delay); + } } - class ActionMonitor + internal class ActionMonitor { private int _failuresRemaining; private readonly List _callTimes = new List(); - public ActionMonitor() : this(0) {} + public ActionMonitor() + : this(0) + { + } public ActionMonitor(int failureCount) { - _failuresRemaining = failureCount; + this._failuresRemaining = failureCount; } public int TimesCalled { get; private set; } @@ -119,22 +121,22 @@ public IList CallTime { get { - return _callTimes.AsReadOnly(); + return this._callTimes.AsReadOnly(); } } public void Action() { - _callTimes.Add(DateTime.Now); - TimesCalled++; + this._callTimes.Add(DateTime.Now); + this.TimesCalled++; - if(_failuresRemaining != 0) + if (this._failuresRemaining != 0) { - if (_failuresRemaining > 0) + if (this._failuresRemaining > 0) { - _failuresRemaining--; + this._failuresRemaining--; } - + throw new Exception("it failed"); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs index 1b27c9bdf13..fa4d275f24b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs @@ -1,41 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using NUnit.Framework; -using DotNetNuke.Security; - - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Security.PortalSecurity { + using DotNetNuke.Security; + using NUnit.Framework; + [TestFixture] public class PortalSecurityTest - { - #region Setup + { [SetUp] public void Setup() { - } - - #endregion - - #region Tear Down + } + [TearDown] public void TearDown() { - } - #endregion - - #region Test Methods - [TestCase("", " ", + } + + [TestCase("", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase("Hi this is personal Test for source tag ", " ", + [TestCase("Hi this is personal Test for source tag ", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase("{Upper case}", " ", + [TestCase("{Upper case}", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] @@ -43,21 +36,21 @@ public void TearDown() DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - - [TestCase("", " ", + + [TestCase("", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] [TestCase("Hi this is personal Test for source tag ", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | - DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting )] + DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] [TestCase("Upper case", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | - DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting )] + DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] [TestCase("Source with attribute", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | - DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting )] - - [TestCase("", " ", + DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] + + [TestCase("", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] [TestCase("Hi this is personal Test for source tag ", " ", @@ -69,65 +62,69 @@ public void TearDown() [TestCase("Source with attribute", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - - [TestCase("", "<source></source>", + + [TestCase("", "<source></source>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase("Hi this is personal Test for source tag ", + [TestCase( + "Hi this is personal Test for source tag ", "<source>Hi this is personal Test for source tag</source> ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] [TestCase("{Upper case}", "<SOURCE>{Upper case}</SOURCE>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase("Source with attribute", + [TestCase( + "Source with attribute", "<source src="https://google.com">Source with attribute</source>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - - [TestCase("", "<source></source>", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup )] - [TestCase("Hi this is personal Test for source tag ", + + [TestCase("", "<source></source>", + DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] + [TestCase( + "Hi this is personal Test for source tag ", "<source>Hi this is personal Test for source tag</source> ", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup )] + DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] [TestCase("Upper case", "<SOURCE>Upper case</SOURCE>", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup )] - [TestCase("Source with attribute", + DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] + [TestCase( + "Source with attribute", "<source src="https://google.com">Source with attribute</source>", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup )] - - [TestCase("", " ", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting )] + DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] + + [TestCase("", " ", + DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] [TestCase("Hi this is personal Test for source tag ", " ", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting )] + DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] [TestCase("Upper case", " ", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting )] + DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] [TestCase("Source with attribute", " ", - DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting )] - - [TestCase("", "", + DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting)] + + [TestCase("", "", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase("Hi this is personal Test for source tag ", + [TestCase( + "Hi this is personal Test for source tag ", "Hi this is personal Test for source tag ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] [TestCase("Upper case", "Upper case", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase("Source with attribute", + [TestCase( + "Source with attribute", "Source with attribute", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - public void Html_Source_Tag_Should_Not_Be_Allowed(string html, string expectedOutput, + public void Html_Source_Tag_Should_Not_Be_Allowed(string html, string expectedOutput, DotNetNuke.Security.PortalSecurity.FilterFlag markup) { - //Arrange + // Arrange var portalSecurity = new DotNetNuke.Security.PortalSecurity(); - //Act + // Act var filterOutput = portalSecurity.InputFilter(html, markup); - //Assert + // Assert Assert.AreEqual(filterOutput, expectedOutput); - } - #endregion + } } - } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs index af069643f6d..ba7a2a015b0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs @@ -1,158 +1,141 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Reflection; -using System.Web; - -using DotNetNuke.Services.ClientCapability; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.ClientCapability { - /// - /// Summary description for FacebookRequestController - /// - [TestFixture] - public class FacebookRequestControllerTests - { - #region "Private Properties" - - private IDictionary _requestDics; - - #endregion - - #region "Set Up" - - [SetUp] - public void SetUp() - { - _requestDics = new Dictionary(); - _requestDics.Add("Empty", string.Empty); - _requestDics.Add("Valid", "vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsIjAiOiJwYXlsb2FkIiwidXNlcl9pZCI6ICIxIiwiZXhwaXJlcyI6IjEzMjUzNzU5OTkifQ=="); - - _requestDics.Add("ValidForAPage", "ylleuHAFR0DTpZ3bNr0fjMp7X7le_j8_HN3ONpbbgkk.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTMxOTQ4ODEwNywicGFnZSI6eyJpZCI6IjEzMDYzNDU0MDM3MjcyOCIsImxpa2VkIjpmYWxzZSwiYWRtaW4iOnRydWV9LCJ1c2VyIjp7ImNvdW50cnkiOiJjYSIsImxvY2FsZSI6ImVuX1VTIiwiYWdlIjp7Im1pbiI6MjF9fX0"); - //json data "{\"algorithm\":\"HMAC-SHA256\",\"issued_at\":1319488107,\"page\":{\"id\":\"130634540372728\",\"liked\":false,\"admin\":true},\"user\":{\"country\":\"ca\",\"locale\":\"en_US\",\"age\":{\"min\":21}}}" - - _requestDics.Add("Invalid", "Invalid Content"); - } - - #endregion - - #region "Tests" - - [Test] - public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Empty_Request_String() - { - var request = FacebookRequestController.GetFacebookDetailsFromRequest(_requestDics["Empty"]); - Assert.IsNull(request); - } + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Reflection; + using System.Web; + + using DotNetNuke.Services.ClientCapability; + using NUnit.Framework; + + /// + /// Summary description for FacebookRequestController. + /// + [TestFixture] + public class FacebookRequestControllerTests + { + private IDictionary _requestDics; + + [SetUp] + public void SetUp() + { + this._requestDics = new Dictionary(); + this._requestDics.Add("Empty", string.Empty); + this._requestDics.Add("Valid", "vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsIjAiOiJwYXlsb2FkIiwidXNlcl9pZCI6ICIxIiwiZXhwaXJlcyI6IjEzMjUzNzU5OTkifQ=="); + + this._requestDics.Add("ValidForAPage", "ylleuHAFR0DTpZ3bNr0fjMp7X7le_j8_HN3ONpbbgkk.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTMxOTQ4ODEwNywicGFnZSI6eyJpZCI6IjEzMDYzNDU0MDM3MjcyOCIsImxpa2VkIjpmYWxzZSwiYWRtaW4iOnRydWV9LCJ1c2VyIjp7ImNvdW50cnkiOiJjYSIsImxvY2FsZSI6ImVuX1VTIiwiYWdlIjp7Im1pbiI6MjF9fX0"); + + // json data "{\"algorithm\":\"HMAC-SHA256\",\"issued_at\":1319488107,\"page\":{\"id\":\"130634540372728\",\"liked\":false,\"admin\":true},\"user\":{\"country\":\"ca\",\"locale\":\"en_US\",\"age\":{\"min\":21}}}" + this._requestDics.Add("Invalid", "Invalid Content"); + } + + [Test] + public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Empty_Request_String() + { + var request = FacebookRequestController.GetFacebookDetailsFromRequest(this._requestDics["Empty"]); + Assert.IsNull(request); + } - [Test] - public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Invalid_Request_String() - { - var request = FacebookRequestController.GetFacebookDetailsFromRequest(_requestDics["Invalid"]); - Assert.IsNull(request); - } + [Test] + public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Invalid_Request_String() + { + var request = FacebookRequestController.GetFacebookDetailsFromRequest(this._requestDics["Invalid"]); + Assert.IsNull(request); + } - [Test] - public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Valid_Request_String() - { - var request = FacebookRequestController.GetFacebookDetailsFromRequest(_requestDics["Valid"]); - Assert.AreEqual(true, request.IsValid); - } + [Test] + public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Valid_Request_String() + { + var request = FacebookRequestController.GetFacebookDetailsFromRequest(this._requestDics["Valid"]); + Assert.AreEqual(true, request.IsValid); + } [Test] public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Valid_Request_String_ForAPage() { - var request = FacebookRequestController.GetFacebookDetailsFromRequest(_requestDics["ValidForAPage"]); + var request = FacebookRequestController.GetFacebookDetailsFromRequest(this._requestDics["ValidForAPage"]); Assert.AreEqual(true, request.IsValid); Assert.AreEqual("HMAC-SHA256", request.Algorithm); Assert.AreEqual(ConvertToTimestamp(1319488107), request.IssuedAt); - - //user stuff + + // user stuff Assert.AreEqual("ca", request.UserCountry); Assert.AreEqual("en_US", request.UserLocale); Assert.AreEqual(21, request.UserMinAge); Assert.AreEqual(0, request.UserMaxAge); - //page + // page Assert.AreEqual("130634540372728", request.PageId); Assert.AreEqual(false, request.PageLiked); Assert.AreEqual(true, request.PageUserAdmin); } - [Test] - public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Empty_Request() - { - var request = FacebookRequestController.GetFacebookDetailsFromRequest(null as HttpRequest); - Assert.IsNull(request); - } - - [Test] - public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Get_Request() - { - HttpRequest httpRequest = new HttpRequest("unittest.aspx", "http://localhost/unittest.aspx", ""); - httpRequest.RequestType = "GET"; - - var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); - Assert.IsNull(request); - } - - [Test] - public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Post_Invalid_Request() - { - HttpRequest httpRequest = new HttpRequest("unittest.aspx", "http://localhost/unittest.aspx", ""); - httpRequest.RequestType = "POST"; - SetReadonly(httpRequest.Form, false); - httpRequest.Form.Add("signed_request", _requestDics["Invalid"]); + [Test] + public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Empty_Request() + { + var request = FacebookRequestController.GetFacebookDetailsFromRequest(null as HttpRequest); + Assert.IsNull(request); + } - var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); - Assert.IsNull(request); - } + [Test] + public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Get_Request() + { + HttpRequest httpRequest = new HttpRequest("unittest.aspx", "http://localhost/unittest.aspx", string.Empty); + httpRequest.RequestType = "GET"; - [Test] - public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Post_Valid_Request() - { - HttpRequest httpRequest = new HttpRequest("unittest.aspx", "http://localhost/unittest.aspx", ""); - httpRequest.RequestType = "POST"; - SetReadonly(httpRequest.Form, false); - httpRequest.Form.Add("signed_request", _requestDics["Valid"]); + var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); + Assert.IsNull(request); + } - var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); - Assert.AreEqual(true, request.IsValid); - } + [Test] + public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Post_Invalid_Request() + { + HttpRequest httpRequest = new HttpRequest("unittest.aspx", "http://localhost/unittest.aspx", string.Empty); + httpRequest.RequestType = "POST"; + this.SetReadonly(httpRequest.Form, false); + httpRequest.Form.Add("signed_request", this._requestDics["Invalid"]); - #endregion + var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); + Assert.IsNull(request); + } - #region "Private Methods" + [Test] + public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Post_Valid_Request() + { + HttpRequest httpRequest = new HttpRequest("unittest.aspx", "http://localhost/unittest.aspx", string.Empty); + httpRequest.RequestType = "POST"; + this.SetReadonly(httpRequest.Form, false); + httpRequest.Form.Add("signed_request", this._requestDics["Valid"]); - private void SetReadonly(NameValueCollection collection, bool readOnly) - { - var readOnlyProperty = collection.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance); - if(readOnlyProperty != null) - { - readOnlyProperty.SetValue(collection, readOnly, null); - } - } + var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); + Assert.AreEqual(true, request.IsValid); + } /// - /// method for converting a System.DateTime value to a UNIX Timestamp + /// method for converting a System.DateTime value to a UNIX Timestamp. /// - /// date to convert + /// date to convert. /// private static DateTime ConvertToTimestamp(long value) { - //create Timespan by subtracting the value provided from - //the Unix Epoch + // create Timespan by subtracting the value provided from + // the Unix Epoch DateTime epoc = new DateTime(1970, 1, 1, 0, 0, 0, 0); return epoc.AddSeconds((double)value); + } + + private void SetReadonly(NameValueCollection collection, bool readOnly) + { + var readOnlyProperty = collection.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance); + if (readOnlyProperty != null) + { + readOnlyProperty.SetValue(collection, readOnly, null); + } } - - #endregion - } + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/TestClientCapability.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/TestClientCapability.cs index b10079b26c7..b5d687b3287 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/TestClientCapability.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/TestClientCapability.cs @@ -1,24 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.ClientCapability { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + public class TestClientCapability : DotNetNuke.Services.ClientCapability.ClientCapability { public override string this[string name] { get { - if (Capabilities.ContainsKey(name)) + if (this.Capabilities.ContainsKey(name)) { - return Capabilities[name]; + return this.Capabilities[name]; } return string.Empty; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs index 324a3a05ffc..18590dc879b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Services.Cryptography; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.CryptographyProviders { + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Services.Cryptography; + using NUnit.Framework; + [TestFixture] public class CoreCryptographyProviderTests { @@ -27,12 +27,13 @@ public void EncryptData_Should_Return_Encrypted_String() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - //Arrange + + // Arrange - //Act + // Act var encryptedValue = _provider.EncryptParameter(message, encryptionKey); - //Assert + // Assert Assert.AreNotEqual(message, encryptedValue); } @@ -41,12 +42,13 @@ public void DecryptData_Should_Return_Empty_String_If_Data_Is_Not_Encypted() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - //Arrange + + // Arrange - //Act + // Act var decryptedValue = _provider.DecryptParameter(message, encryptionKey); - //Assert + // Assert Assert.AreEqual(string.Empty, decryptedValue); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs index 1af3e707e9c..d4aa78800cd 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Services.Cryptography; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.CryptographyProviders { + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Services.Cryptography; + using NUnit.Framework; + [TestFixture] public class FipsCompilanceCryptographyProviderTests { @@ -27,12 +27,13 @@ public void EncryptData_Should_Return_Encrypted_String() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - //Arrange + + // Arrange - //Act + // Act var encryptedValue = _provider.EncryptParameter(message, encryptionKey); - //Assert + // Assert Assert.AreNotEqual(message, encryptedValue); } @@ -41,12 +42,13 @@ public void DecryptData_Should_Return_Empty_String_If_Data_Is_Not_Encypted() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - //Arrange + + // Arrange - //Act + // Act var decryptedValue = _provider.DecryptParameter(message, encryptionKey); - //Assert + // Assert Assert.AreEqual(string.Empty, decryptedValue); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs index c5570907042..06119c8b4fc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs @@ -1,13 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Common.Utilities; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services { + using DotNetNuke.Common.Utilities; + using NUnit.Framework; + /// /// [TestFixture] @@ -17,7 +16,7 @@ public class HtmlUtilsTests "Hello World!

        This is a sample HTML text for testing!

        \"HappyFaceAlt\"

        \"\"

        DotNetNuke Corp."; private const string Filters = "alt|href|src|title"; - private string _expected = ""; + private string _expected = string.Empty; [SetUp] public void SetUp() @@ -47,76 +46,76 @@ public void DNN_12926_IsHtml_Detection() [TearDown] public void TearDown() { - } - - #region HTML Cleaning Tests - + } + [Test] public void HtmlUtils_CleanWithTagInfo_Should_Return_Clean_Content_With_Attribute_Values() { // Arrange - SetUp(); - _expected = + this.SetUp(); + this._expected = "Hello World This is a sample HTML text for testing DotNetNuke Corp HappyFaceAlt HappyFaceTitle /dotnetnuke_enterprise/Portals/0/Telerik/images/Emoticons/1.gif http://localhost/dotnetnuke_enterprise/Portals/0/aspnet.gif https://www.dnnsoftware.com "; // Act object retValue = HtmlUtils.CleanWithTagInfo(HtmlStr, Filters, true); + // Assert - Assert.AreEqual(_expected, retValue); + Assert.AreEqual(this._expected, retValue); // TearDown - TearDown(); + this.TearDown(); } [Test] public void HtmlUtils_CleanWithTagInfo_Should_Return_Clean_Content_Without_Attribute_Values() { // Arrange - SetUp(); - _expected = "Hello World This is a sample HTML text for testing DotNetNuke Corp "; + this.SetUp(); + this._expected = "Hello World This is a sample HTML text for testing DotNetNuke Corp "; // Act object retValue = HtmlUtils.CleanWithTagInfo(HtmlStr, " ", true); + // Assert - Assert.AreEqual(_expected, retValue); + Assert.AreEqual(this._expected, retValue); // TearDown - TearDown(); + this.TearDown(); } [Test] public void HtmlUtils_StripUnspecifiedTags_Should_Return_Attribute_Values() { // Arrange - SetUp(); - _expected = + this.SetUp(); + this._expected = "Hello World!This is a sample HTML text for testing!DotNetNuke Corp. \"HappyFaceAlt\" \"HappyFaceTitle\" \"/dotnetnuke_enterprise/Portals/0/Telerik/images/Emoticons/1.gif\" \"\" \"http://localhost/dotnetnuke_enterprise/Portals/0/aspnet.gif\" \"https://www.dnnsoftware.com\""; // Act object retValue = HtmlUtils.StripUnspecifiedTags(HtmlStr, Filters, false); + // Assert - Assert.AreEqual(_expected, retValue); + Assert.AreEqual(this._expected, retValue); // TearDown - TearDown(); + this.TearDown(); } [Test] public void HtmlUtils_StripUnspecifiedTags_Should_Not_Return_Attribute_Values() { // Arrange - SetUp(); - _expected = "Hello World!This is a sample HTML text for testing!DotNetNuke Corp."; + this.SetUp(); + this._expected = "Hello World!This is a sample HTML text for testing!DotNetNuke Corp."; // Act object retValue = HtmlUtils.StripUnspecifiedTags(HtmlStr, " ", false); + // Assert - Assert.AreEqual(_expected, retValue); + Assert.AreEqual(this._expected, retValue); // TearDown - TearDown(); - } - - #endregion + this.TearDown(); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs index 12617cc94d1..acbd67a8543 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs @@ -1,41 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Localization.Internal; -using DotNetNuke.Tests.Utilities; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.Localization { + using System; + using System.Web; + + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Localization.Internal; + using DotNetNuke.Tests.Utilities; + using Moq; + using NUnit.Framework; + [TestFixture] public class LocalizationTests { private Mock _mockHttpContext; private HttpContextBase _httpContext; - private readonly string[] _standardCultureCodes = new[] { "en-US", "de-DE", "fr-CA", "Lt-sr-SP", "kok-IN"}; + private readonly string[] _standardCultureCodes = new[] { "en-US", "de-DE", "fr-CA", "Lt-sr-SP", "kok-IN" }; [SetUp] public void Setup() { - _mockHttpContext = HttpContextHelper.RegisterMockHttpContext(); - _httpContext = _mockHttpContext.Object; + this._mockHttpContext = HttpContextHelper.RegisterMockHttpContext(); + this._httpContext = this._mockHttpContext.Object; } [Test] public void NoMatchReturnsFallback() { const string fallback = "fallback"; - //Arrange - - //Act - var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(new string[0], fallback); + + // Arrange + + // Act + var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(new string[0], fallback); - //Assert + // Assert Assert.AreEqual(ret, fallback); } @@ -43,90 +45,87 @@ public void NoMatchReturnsFallback() [ExpectedException(typeof(ArgumentException))] public void CultureCodesCannotBeNull() { - //Arrange - - - //Act + // Arrange + + // Act TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(null); - //Assert + // Assert } [Test] [ExpectedException(typeof(ArgumentException))] public void FallBackCannotBeNull() { - //Arrange - - - //Act + // Arrange + + // Act TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(new string[0], null); - //Assert + // Assert } [Test] public void PerfectMatchPossible() { - //Arrange - _mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] {"de-DE"}); + // Arrange + this._mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] { "de-DE" }); - //Act - var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(_standardCultureCodes); + // Act + var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(this._standardCultureCodes); - //Assert + // Assert Assert.AreEqual(ret, "de-DE"); } [Test] public void QParamsAreIgnored() { - //Arrange - _mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] { "de-DE;q=0.8" }); + // Arrange + this._mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] { "de-DE;q=0.8" }); - //Act - var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(_standardCultureCodes); + // Act + var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(this._standardCultureCodes); - //Assert + // Assert Assert.AreEqual(ret, "de-DE"); } [Test] public void MatchOnOnlyLanguage() { - //Arrange - _mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] { "fr-FR" }); + // Arrange + this._mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] { "fr-FR" }); - //Act - var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(_standardCultureCodes); + // Act + var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(this._standardCultureCodes); - //Assert + // Assert Assert.AreEqual(ret, "fr-CA"); } [Test] public void PerfectMatchPreferredToFirstMatch() { - //Arrange - _mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] { "fr-FR" }); + // Arrange + this._mockHttpContext.Setup(x => x.Request.UserLanguages).Returns(new[] { "fr-FR" }); - //Act - var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(new[] {"fr-CA", "fr-FR"}); + // Act + var ret = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(new[] { "fr-CA", "fr-FR" }); - //Assert + // Assert Assert.AreEqual(ret, "fr-FR"); } - - + [Test] [TestCase("My/Path/To/File with.locale-extension")] [TestCase("My\\Path\\To\\File with.locale-extension")] public void ParseLocaleFromResxFileName(string fileName) { - foreach (var standardCultureCode in _standardCultureCodes) + foreach (var standardCultureCode in this._standardCultureCodes) { var f = fileName + "." + standardCultureCode + ".resx"; - Assert.AreEqual(f.GetLocaleCodeFromFileName(), standardCultureCode); + Assert.AreEqual(f.GetLocaleCodeFromFileName(), standardCultureCode); } } @@ -135,7 +134,7 @@ public void ParseLocaleFromResxFileName(string fileName) [TestCase("My\\Path\\To\\File with.locale-extension")] public void ParseFileNameFromResxFile(string fileName) { - foreach (var standardCultureCode in _standardCultureCodes) + foreach (var standardCultureCode in this._standardCultureCodes) { var f = fileName + "." + standardCultureCode + ".resx"; Assert.AreEqual(f.GetFileNameFromLocalizedResxFile(), fileName); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs index f308f6d0ead..03032d7a0d5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs @@ -1,186 +1,169 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Services.Mobile; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.Mobile { - /// - /// Summary description for PreviewProfileControllerTests - /// - [TestFixture] - public class PreviewProfileControllerTests - { - #region "Private Properties" - - private Mock _dataProvider; - - private DataTable _dtProfiles; - - #endregion - - #region "Set Up" - - [SetUp] - public void SetUp() - { - ComponentFactory.Container = new SimpleContainer(); - _dataProvider = MockComponentProvider.CreateDataProvider(); - _dataProvider.Setup(d => d.GetProviderPath()).Returns(""); - MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); - - _dtProfiles = new DataTable("PreviewProfiles"); - var pkCol = _dtProfiles.Columns.Add("Id", typeof(int)); - _dtProfiles.Columns.Add("PortalId", typeof(int)); - _dtProfiles.Columns.Add("Name", typeof(string)); - _dtProfiles.Columns.Add("Width", typeof(int)); - _dtProfiles.Columns.Add("Height", typeof(int)); - _dtProfiles.Columns.Add("UserAgent", typeof(string)); - _dtProfiles.Columns.Add("SortOrder", typeof(int)); - - _dtProfiles.PrimaryKey = new[] { pkCol }; - - _dataProvider.Setup(d => - d.SavePreviewProfile(It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Returns( - (id, portalId, name, width, height, userAgent, sortOrder, userId) => - { - if (id == -1) - { - if (_dtProfiles.Rows.Count == 0) - { - id = 1; - } - else - { - id = Convert.ToInt32(_dtProfiles.Select("", "Id Desc")[0]["Id"]) + 1; - } - - var row = _dtProfiles.NewRow(); - row["Id"] = id; - row["PortalId"] = portalId; - row["name"] = name; - row["width"] = width; - row["height"] = height; - row["useragent"] = userAgent; - row["sortorder"] = sortOrder; - - _dtProfiles.Rows.Add(row); - } - else - { - var rows = _dtProfiles.Select("Id = " + id); - if (rows.Length == 1) - { - var row = rows[0]; - - row["name"] = name; - row["width"] = width; - row["height"] = height; - row["useragent"] = userAgent; - row["sortorder"] = sortOrder; - } - } - - return id; - }); - - _dataProvider.Setup(d => d.GetPreviewProfiles(It.IsAny())).Returns((portalId) => { return GetProfilesCallBack(portalId); }); - _dataProvider.Setup(d => d.DeletePreviewProfile(It.IsAny())).Callback((id) => - { - var rows = _dtProfiles.Select("Id = " + id); - if (rows.Length == 1) - { - _dtProfiles.Rows.Remove(rows[0]); - } - }); - } - - #endregion - - #region "Test" - - [Test] - public void PreviewProfileController_Save_Valid_Profile() - { - var profile = new PreviewProfile { Name = "Test R", PortalId = 0, Width = 800, Height = 480 }; - new PreviewProfileController().Save(profile); - - var dataReader = _dataProvider.Object.GetPreviewProfiles(0); - var affectedCount = 0; - while (dataReader.Read()) - { - affectedCount++; - } - Assert.AreEqual(1, affectedCount); - } - - - [Test] - public void PreviewProfileController_GetProfilesByPortal_With_Valid_PortalID() - { - PrepareData(); - - IList list = new PreviewProfileController().GetProfilesByPortal(0); - - Assert.AreEqual(3, list.Count); - } - - [Test] - public void PreviewProfileController_Delete_With_ValidID() - { - PrepareData(); - new PreviewProfileController().Delete(0, 1); - - IList list = new PreviewProfileController().GetProfilesByPortal(0); - - Assert.AreEqual(2, list.Count); - } - - #endregion - - #region "Private Methods" - - private IDataReader GetProfilesCallBack(int portalId) - { - var dtCheck = _dtProfiles.Clone(); - foreach (var row in _dtProfiles.Select("PortalId = " + portalId)) - { - dtCheck.Rows.Add(row.ItemArray); - } - - return dtCheck.CreateDataReader(); - } - - private void PrepareData() - { - _dtProfiles.Rows.Add(1, 0, "R1", 640, 480, "", 1); - _dtProfiles.Rows.Add(2, 0, "R2", 640, 480, "", 2); - _dtProfiles.Rows.Add(3, 0, "R3", 640, 480, "", 3); - _dtProfiles.Rows.Add(4, 1, "R4", 640, 480, "", 4); - _dtProfiles.Rows.Add(5, 1, "R5", 640, 480, "", 5); - _dtProfiles.Rows.Add(6, 1, "R6", 640, 480, "", 6); - } - - #endregion - } + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Services.Mobile; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + + /// + /// Summary description for PreviewProfileControllerTests. + /// + [TestFixture] + public class PreviewProfileControllerTests + { + private Mock _dataProvider; + + private DataTable _dtProfiles; + + [SetUp] + public void SetUp() + { + ComponentFactory.Container = new SimpleContainer(); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); + + this._dtProfiles = new DataTable("PreviewProfiles"); + var pkCol = this._dtProfiles.Columns.Add("Id", typeof(int)); + this._dtProfiles.Columns.Add("PortalId", typeof(int)); + this._dtProfiles.Columns.Add("Name", typeof(string)); + this._dtProfiles.Columns.Add("Width", typeof(int)); + this._dtProfiles.Columns.Add("Height", typeof(int)); + this._dtProfiles.Columns.Add("UserAgent", typeof(string)); + this._dtProfiles.Columns.Add("SortOrder", typeof(int)); + + this._dtProfiles.PrimaryKey = new[] { pkCol }; + + this._dataProvider.Setup(d => + d.SavePreviewProfile( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())).Returns( + (id, portalId, name, width, height, userAgent, sortOrder, userId) => + { + if (id == -1) + { + if (this._dtProfiles.Rows.Count == 0) + { + id = 1; + } + else + { + id = Convert.ToInt32(this._dtProfiles.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; + } + + var row = this._dtProfiles.NewRow(); + row["Id"] = id; + row["PortalId"] = portalId; + row["name"] = name; + row["width"] = width; + row["height"] = height; + row["useragent"] = userAgent; + row["sortorder"] = sortOrder; + + this._dtProfiles.Rows.Add(row); + } + else + { + var rows = this._dtProfiles.Select("Id = " + id); + if (rows.Length == 1) + { + var row = rows[0]; + + row["name"] = name; + row["width"] = width; + row["height"] = height; + row["useragent"] = userAgent; + row["sortorder"] = sortOrder; + } + } + + return id; + }); + + this._dataProvider.Setup(d => d.GetPreviewProfiles(It.IsAny())).Returns((portalId) => { return this.GetProfilesCallBack(portalId); }); + this._dataProvider.Setup(d => d.DeletePreviewProfile(It.IsAny())).Callback((id) => + { + var rows = this._dtProfiles.Select("Id = " + id); + if (rows.Length == 1) + { + this._dtProfiles.Rows.Remove(rows[0]); + } + }); + } + + [Test] + public void PreviewProfileController_Save_Valid_Profile() + { + var profile = new PreviewProfile { Name = "Test R", PortalId = 0, Width = 800, Height = 480 }; + new PreviewProfileController().Save(profile); + + var dataReader = this._dataProvider.Object.GetPreviewProfiles(0); + var affectedCount = 0; + while (dataReader.Read()) + { + affectedCount++; + } + + Assert.AreEqual(1, affectedCount); + } + + [Test] + public void PreviewProfileController_GetProfilesByPortal_With_Valid_PortalID() + { + this.PrepareData(); + + IList list = new PreviewProfileController().GetProfilesByPortal(0); + + Assert.AreEqual(3, list.Count); + } + + [Test] + public void PreviewProfileController_Delete_With_ValidID() + { + this.PrepareData(); + new PreviewProfileController().Delete(0, 1); + + IList list = new PreviewProfileController().GetProfilesByPortal(0); + + Assert.AreEqual(2, list.Count); + } + + private IDataReader GetProfilesCallBack(int portalId) + { + var dtCheck = this._dtProfiles.Clone(); + foreach (var row in this._dtProfiles.Select("PortalId = " + portalId)) + { + dtCheck.Rows.Add(row.ItemArray); + } + + return dtCheck.CreateDataReader(); + } + + private void PrepareData() + { + this._dtProfiles.Rows.Add(1, 0, "R1", 640, 480, string.Empty, 1); + this._dtProfiles.Rows.Add(2, 0, "R2", 640, 480, string.Empty, 2); + this._dtProfiles.Rows.Add(3, 0, "R3", 640, 480, string.Empty, 3); + this._dtProfiles.Rows.Add(4, 1, "R4", 640, 480, string.Empty, 4); + this._dtProfiles.Rows.Add(5, 1, "R5", 640, 480, string.Empty, 5); + this._dtProfiles.Rows.Add(6, 1, "R6", 640, 480, string.Empty, 6); + } + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs index 0af5b788e9e..03fd64ba6e6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs @@ -1,53 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Data; -using System.Reflection; -using System.Web; -using DotNetNuke.Abstractions; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.ClientCapability; -using DotNetNuke.Services.Mobile; -using DotNetNuke.Tests.Core.Services.ClientCapability; -using DotNetNuke.Tests.Instance.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.Mobile { - /// - /// Summary description for RedirectionControllerTests - /// - [TestFixture] + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Data; + using System.Reflection; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.ClientCapability; + using DotNetNuke.Services.Mobile; + using DotNetNuke.Tests.Core.Services.ClientCapability; + using DotNetNuke.Tests.Instance.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + + /// + /// Summary description for RedirectionControllerTests. + /// + [TestFixture] public class RedirectionControllerTests - { - #region Private Properties - + { + public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; + public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; + private Mock _dataProvider; - private RedirectionController _redirectionController; + private RedirectionController _redirectionController; private Mock _clientCapabilityProvider; - private Mock _mockHostController; + private Mock _mockHostController; private DataTable _dtRedirections; - private DataTable _dtRules; - - public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; - public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; + private DataTable _dtRules; public const string msIE8UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)"; public const string msIE9UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; public const string msIE10UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; @@ -59,17 +56,17 @@ public class RedirectionControllerTests public const string blackBerry9105V1 = "BlackBerry9105/5.0.0.696 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133"; public const string motorolaRIZRSymbianOSOpera865 = "MOTORIZR-Z8/46.00.00 Mozilla/4.0 (compatible; MSIE 6.0; Symbian OS; 356) Opera 8.65 [it] UP.Link/6.3.0.0.0"; - public const int Portal0 = 0; + public const int Portal0 = 0; public const int Portal1 = 1; public const int Portal2 = 2; public const int Page1 = 1; public const int Page2 = 2; public const int Page3 = 3; - public const int SortOrder1 = 1; + public const int SortOrder1 = 1; public const int SortOrder2 = 1; public const int SortOrder3 = 1; - public const string PortalAlias0 = "www.portal0.com"; - public const string PortalAlias1 = "www.portal1.com"; + public const string PortalAlias0 = "www.portal0.com"; + public const string PortalAlias1 = "www.portal1.com"; public const int AnotherPageOnSamePortal = 56; public const int DeletedPageOnSamePortal = 59; public const int DeletedPageOnSamePortal2 = 94; @@ -78,42 +75,39 @@ public class RedirectionControllerTests public const int MobileLandingPage = 91; public const int TabletLandingPage = 92; public const int AllMobileLandingPage = 93; - public const bool EnabledFlag = true; + public const bool EnabledFlag = true; public const bool DisabledFlag = false; public const bool IncludeChildTabsFlag = true; - public const string ExternalSite = "https://dnncommunity.org"; + public const string ExternalSite = "https://dnncommunity.org"; - private const string DisableMobileRedirectCookieName = "disablemobileredirect"; - private const string DisableRedirectPresistCookieName = "disableredirectpresist"; - private const string DisableMobileRedirectQueryStringName = "nomo"; - - #endregion - - #region Set Up - [SetUp] - public void SetUp() - { - SetupContianer(); + private const string DisableMobileRedirectCookieName = "disablemobileredirect"; + private const string DisableRedirectPresistCookieName = "disableredirectpresist"; + private const string DisableMobileRedirectQueryStringName = "nomo"; + + [SetUp] + public void SetUp() + { + this.SetupContianer(); ComponentFactory.Container = new SimpleContainer(); UnitTestHelper.ClearHttpContext(); - _dataProvider = MockComponentProvider.CreateDataProvider(); - MockComponentProvider.CreateDataCacheProvider(); - MockComponentProvider.CreateEventLogController(); - _clientCapabilityProvider = MockComponentProvider.CreateNew(); - _mockHostController = new Mock(); - HostController.RegisterInstance(_mockHostController.Object); + this._dataProvider = MockComponentProvider.CreateDataProvider(); + MockComponentProvider.CreateDataCacheProvider(); + MockComponentProvider.CreateEventLogController(); + this._clientCapabilityProvider = MockComponentProvider.CreateNew(); + this._mockHostController = new Mock(); + HostController.RegisterInstance(this._mockHostController.Object); - _redirectionController = new RedirectionController(); + this._redirectionController = new RedirectionController(); - SetupDataProvider(); - SetupClientCapabilityProvider(); - SetupRoleProvider(); + this.SetupDataProvider(); + this.SetupClientCapabilityProvider(); + this.SetupRoleProvider(); var tabController = TabController.Instance; var dataProviderField = tabController.GetType().GetField("_dataProvider", BindingFlags.NonPublic | BindingFlags.Instance); if (dataProviderField != null) { - dataProviderField.SetValue(tabController, _dataProvider.Object); + dataProviderField.SetValue(tabController, this._dataProvider.Object); } } @@ -125,297 +119,280 @@ public void TearDown() CachingProvider.Instance().PurgeCache(); MockComponentProvider.ResetContainer(); UnitTestHelper.ClearHttpContext(); - if (_dtRedirections != null) + if (this._dtRedirections != null) { - _dtRedirections.Dispose(); - _dtRedirections = null; + this._dtRedirections.Dispose(); + this._dtRedirections = null; } - if (_dtRules != null) + + if (this._dtRules != null) { - _dtRules.Dispose(); - _dtRules = null; + this._dtRules.Dispose(); + this._dtRules = null; } + ComponentFactory.Container = null; } + + [Test] + public void RedirectionController_Save_Valid_Redirection() + { + var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, Type = RedirectionType.MobilePhone, TargetType = TargetType.Portal, TargetValue = Portal1 }; + this._redirectionController.Save(redirection); + + var dataReader = this._dataProvider.Object.GetRedirections(Portal0); + var affectedCount = 0; + while (dataReader.Read()) + { + affectedCount++; + } + + Assert.AreEqual(1, affectedCount); + } + + [Test] + public void RedirectionController_Save_ValidRedirection_With_Rules() + { + var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, IncludeChildTabs = true, Type = RedirectionType.Other, TargetType = TargetType.Portal, TargetValue = Portal1 }; + redirection.MatchRules.Add(new MatchRule { Capability = "Platform", Expression = "IOS" }); + redirection.MatchRules.Add(new MatchRule { Capability = "Version", Expression = "5" }); + this._redirectionController.Save(redirection); + + var dataReader = this._dataProvider.Object.GetRedirections(Portal0); + var affectedCount = 0; + while (dataReader.Read()) + { + affectedCount++; + } + + Assert.AreEqual(1, affectedCount); + + var getRe = this._redirectionController.GetRedirectionsByPortal(Portal0)[0]; + Assert.AreEqual(2, getRe.MatchRules.Count); + } private void SetupContianer() { var navigationManagerMock = new Mock(); - navigationManagerMock.Setup(x => x.NavigateURL(It.IsAny())).Returns(x => NavigateUrl(x)); + navigationManagerMock.Setup(x => x.NavigateURL(It.IsAny())).Returns(x => this.NavigateUrl(x)); var containerMock = new Mock(); containerMock.Setup(x => x.GetService(typeof(INavigationManager))).Returns(navigationManagerMock.Object); Globals.DependencyProvider = containerMock.Object; - } - #endregion - - #region Tests - - #region CURD API Tests - + } [Test] - public void RedirectionController_Save_Valid_Redirection() - { - var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, Type = RedirectionType.MobilePhone, TargetType = TargetType.Portal, TargetValue = Portal1 }; - _redirectionController.Save(redirection); - - var dataReader = _dataProvider.Object.GetRedirections(Portal0); - var affectedCount = 0; - while (dataReader.Read()) - { - affectedCount++; - } - Assert.AreEqual(1, affectedCount); - } - - [Test] - public void RedirectionController_Save_ValidRedirection_With_Rules() - { - var redirection = new Redirection { Name = "Test R", PortalId = Portal0, SortOrder = 1, SourceTabId = -1, IncludeChildTabs = true, Type = RedirectionType.Other, TargetType = TargetType.Portal, TargetValue = Portal1 }; - redirection.MatchRules.Add(new MatchRule { Capability = "Platform", Expression = "IOS" }); - redirection.MatchRules.Add(new MatchRule { Capability = "Version", Expression = "5" }); - _redirectionController.Save(redirection); - - var dataReader = _dataProvider.Object.GetRedirections(Portal0); - var affectedCount = 0; - while (dataReader.Read()) - { - affectedCount++; - } - Assert.AreEqual(1, affectedCount); - - var getRe = _redirectionController.GetRedirectionsByPortal(Portal0)[0]; - Assert.AreEqual(2, getRe.MatchRules.Count); - } - - [Test] - public void RedirectionController_GetRedirectionsByPortal_With_Valid_PortalID() - { - PrepareData(); + public void RedirectionController_GetRedirectionsByPortal_With_Valid_PortalID() + { + this.PrepareData(); - IList list = _redirectionController.GetRedirectionsByPortal(Portal0); + IList list = this._redirectionController.GetRedirectionsByPortal(Portal0); - Assert.AreEqual(7, list.Count); - } + Assert.AreEqual(7, list.Count); + } - [Test] - public void RedirectionController_Delete_With_ValidID() - { - PrepareData(); - _redirectionController.Delete(Portal0, 1); + [Test] + public void RedirectionController_Delete_With_ValidID() + { + this.PrepareData(); + this._redirectionController.Delete(Portal0, 1); - IList list = _redirectionController.GetRedirectionsByPortal(Portal0); + IList list = this._redirectionController.GetRedirectionsByPortal(Portal0); - Assert.AreEqual(6, list.Count); - } + Assert.AreEqual(6, list.Count); + } [Test] public void RedirectionController_PurgeInvalidRedirections_DoNotPurgeRuleForNonDeletetedSource() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); - _redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(1, _redirectionController.GetRedirectionsByPortal(0).Count); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(1, this._redirectionController.GetRedirectionsByPortal(0).Count); } [Test] public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedSource() { - _dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, DeletedPageOnSamePortal2, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag }); - _redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(0, _redirectionController.GetRedirectionsByPortal(0).Count); + this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, DeletedPageOnSamePortal2, IncludeChildTabsFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag }); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); } [Test] public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedTargetPortal() { - _dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Portal, Portal2, EnabledFlag }); - _redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(0, _redirectionController.GetRedirectionsByPortal(0).Count); + this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Portal, Portal2, EnabledFlag }); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); } [Test] public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletetedTargetTab() { - _dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, DeletedPageOnSamePortal2, EnabledFlag }); - _redirectionController.PurgeInvalidRedirections(0); - Assert.AreEqual(0, _redirectionController.GetRedirectionsByPortal(0).Count); - } - - #endregion - - #region Get Redirections URL Tests - + this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, DeletedPageOnSamePortal2, EnabledFlag }); + this._redirectionController.PurgeInvalidRedirections(0); + Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); + } + [Test] [ExpectedException(typeof(ArgumentException))] public void RedirectionController_GetRedirectionUrl_Throws_On_Null_UserAgent() { - _redirectionController.GetRedirectUrl(null, Portal0, 0); + this._redirectionController.GetRedirectUrl(null, Portal0, 0); } - + [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Redirection_IsNotSet() - { - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); - } + { + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); + } [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Redirection_IsNotEnabled() { - PrepareSingleDisabledRedirectionRule(); - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); - } + this.PrepareSingleDisabledRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, HomePageOnPortal0)); + } [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_UserAgent_Is_Desktop() { - PrepareData(); - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(msIE9UserAgent, Portal0, HomePageOnPortal0)); + this.PrepareData(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(msIE9UserAgent, Portal0, HomePageOnPortal0)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_CurrentPage_IsSameAs_TargetPage_OnMobile() { - PreparePortalToAnotherPageOnSamePortal(); - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); + this.PreparePortalToAnotherPageOnSamePortal(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_TargetPage_IsDeleted() { - //prepare rule to a deleted tab on the same portal - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, AnotherPageOnSamePortal, EnabledFlag, (int)TargetType.Tab, DeletedPageOnSamePortal, 1); - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); + // prepare rule to a deleted tab on the same portal + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, AnotherPageOnSamePortal, EnabledFlag, (int)TargetType.Tab, DeletedPageOnSamePortal, 1); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_CurrentPortal_IsSameAs_TargetPortal_OnMobile() { - PrepareSamePortalToSamePortalRedirectionRule(); - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); + this.PrepareSamePortalToSamePortalRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, AnotherPageOnSamePortal)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_TargetPageOnSamePortal_When_Surfing_HomePage_OnMobile() { - PreparePortalToAnotherPageOnSamePortal(); - Assert.AreEqual(NavigateUrl(AnotherPageOnSamePortal), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + this.PreparePortalToAnotherPageOnSamePortal(); + Assert.AreEqual(this.NavigateUrl(AnotherPageOnSamePortal), this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); } - //[Test] - //public void RedirectionController_GetRedirectionUrl_Returns_HomePageOfOtherPortal_When_Surfing_AnyPageOfCurrentPortal_OnMobile() - //{ + // [Test] + // public void RedirectionController_GetRedirectionUrl_Returns_HomePageOfOtherPortal_When_Surfing_AnyPageOfCurrentPortal_OnMobile() + // { // PrepareHomePageToHomePageRedirectionRule(); // Assert.AreEqual(DotNetNuke.Common.Globals.AddHTTP(PortalAlias1), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - // Assert.AreEqual(DotNetNuke.Common.Globals.AddHTTP(PortalAlias1), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); - //} - + // Assert.AreEqual(DotNetNuke.Common.Globals.AddHTTP(PortalAlias1), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); + // } [Test] public void RedirectionController_GetRedirectionUrl_Returns_ExternalSite_When_Surfing_AnyPageOfCurrentPortal_OnMobile() { - PrepareExternalSiteRedirectionRule(); - Assert.AreEqual(ExternalSite, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - Assert.AreEqual(ExternalSite, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); + this.PrepareExternalSiteRedirectionRule(); + Assert.AreEqual(ExternalSite, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + Assert.AreEqual(ExternalSite, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 2)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_MobileLanding_ForMobile_And_TabletLanding_ForTablet() { - PrepareMobileAndTabletRedirectionRuleWithMobileFirst(); - Assert.AreEqual(NavigateUrl(MobileLandingPage), _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - Assert.AreEqual(NavigateUrl(TabletLandingPage), _redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1)); + this.PrepareMobileAndTabletRedirectionRuleWithMobileFirst(); + Assert.AreEqual(this.NavigateUrl(MobileLandingPage), this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + Assert.AreEqual(this.NavigateUrl(TabletLandingPage), this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_TabletLanding_ForTablet_And_MobileLanding_ForMobile() { - PrepareMobileAndTabletRedirectionRuleWithAndTabletRedirectionRuleTabletFirst(); - Assert.AreEqual(NavigateUrl(MobileLandingPage), _redirectionController.GetRedirectUrl(iphoneUserAgent, 0, 1)); - Assert.AreEqual(NavigateUrl(TabletLandingPage), _redirectionController.GetRedirectUrl(iPadTabletUserAgent, 0, 1)); + this.PrepareMobileAndTabletRedirectionRuleWithAndTabletRedirectionRuleTabletFirst(); + Assert.AreEqual(this.NavigateUrl(MobileLandingPage), this._redirectionController.GetRedirectUrl(iphoneUserAgent, 0, 1)); + Assert.AreEqual(this.NavigateUrl(TabletLandingPage), this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, 0, 1)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_SameLandingPage_For_AllMobile() { - PrepareAllMobileRedirectionRule(); - string mobileLandingPage = _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1); - string tabletLandingPage = _redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1); - Assert.AreEqual(NavigateUrl(AllMobileLandingPage), mobileLandingPage); - Assert.AreEqual(NavigateUrl(AllMobileLandingPage), tabletLandingPage); + this.PrepareAllMobileRedirectionRule(); + string mobileLandingPage = this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1); + string tabletLandingPage = this._redirectionController.GetRedirectUrl(iPadTabletUserAgent, Portal0, 1); + Assert.AreEqual(this.NavigateUrl(AllMobileLandingPage), mobileLandingPage); + Assert.AreEqual(this.NavigateUrl(AllMobileLandingPage), tabletLandingPage); Assert.AreEqual(mobileLandingPage, tabletLandingPage); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Capability_DoesNot_Match() { - PrepareOperaBrowserOnSymbianOSRedirectionRule(); - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + this.PrepareOperaBrowserOnSymbianOSRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_ValidUrl_When_Capability_Matches() { - PrepareOperaBrowserOnSymbianOSRedirectionRule(); - Assert.AreEqual(NavigateUrl(AnotherPageOnSamePortal), _redirectionController.GetRedirectUrl(motorolaRIZRSymbianOSOpera865, Portal0, 1)); + this.PrepareOperaBrowserOnSymbianOSRedirectionRule(); + Assert.AreEqual(this.NavigateUrl(AnotherPageOnSamePortal), this._redirectionController.GetRedirectUrl(motorolaRIZRSymbianOSOpera865, Portal0, 1)); } [Test] public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_NotAll_Capability_Matches() { - PrepareOperaBrowserOnIPhoneOSRedirectionRule(); - Assert.AreEqual(string.Empty, _redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - } - - - #endregion - - #region Get FullSite Url Tests - - [Test] + this.PrepareOperaBrowserOnIPhoneOSRedirectionRule(); + Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); + } + + [Test] public void RedirectionController_GetFullSiteUrl_With_NoRedirections() - { - var url = _redirectionController.GetFullSiteUrl(Portal0, HomePageOnPortal0); + { + var url = this._redirectionController.GetFullSiteUrl(Portal0, HomePageOnPortal0); - Assert.AreEqual(string.Empty, url); - } + Assert.AreEqual(string.Empty, url); + } - //[Test] - //public void RedirectionController_GetFullSiteUrl_When_Redirect_Between_Different_Portals() - //{ + // [Test] + // public void RedirectionController_GetFullSiteUrl_When_Redirect_Between_Different_Portals() + // { // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, "1", 1); - // var url = _redirectionController.GetFullSiteUrl(Portal1, HomePageOnPortal1); - - // Assert.AreEqual(Globals.AddHTTP(PortalAlias0), url); - //} - - //[Test] - //public void RedirectionController_GetFullSiteUrl_When_Redirect_In_Same_Portal() - //{ - // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, 1); - - // var url = _redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); - - // //Assert.AreEqual(string.Empty, url); - //} + // var url = _redirectionController.GetFullSiteUrl(Portal1, HomePageOnPortal1); - [Test] - public void RedirectionController_GetFullSiteUrl_When_Redirect_To_DifferentUrl() - { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); + // Assert.AreEqual(Globals.AddHTTP(PortalAlias0), url); + // } - var url = _redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); + // [Test] + // public void RedirectionController_GetFullSiteUrl_When_Redirect_In_Same_Portal() + // { + // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, 1); - Assert.AreEqual(string.Empty, url); - } + // var url = _redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); - #endregion + // //Assert.AreEqual(string.Empty, url); + // } + [Test] + public void RedirectionController_GetFullSiteUrl_When_Redirect_To_DifferentUrl() + { + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); - #region Get MobileSite Url Tests + var url = this._redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); + Assert.AreEqual(string.Empty, url); + } + [Test] public void RedirectionController_GetMobileSiteUrl_With_NoRedirections() { - var url = _redirectionController.GetMobileSiteUrl(Portal0, HomePageOnPortal0); + var url = this._redirectionController.GetMobileSiteUrl(Portal0, HomePageOnPortal0); Assert.AreEqual(string.Empty, url); } @@ -426,429 +403,425 @@ public void RedirectionController_GetMobileSiteUrl_Returns_Page_Specific_Url_Whe string redirectUrlPage1 = "m.yahoo.com"; string redirectUrlPage2 = "m.cnn.com"; - //first page goes to one url - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, Page1, EnabledFlag, (int)TargetType.Url, redirectUrlPage1, 1); + // first page goes to one url + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, Page1, EnabledFlag, (int)TargetType.Url, redirectUrlPage1, 1); + + // second page goes to another url (this is Tablet - it should not matter) + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, Page2, EnabledFlag, (int)TargetType.Url, redirectUrlPage2, 1); - //second page goes to another url (this is Tablet - it should not matter) - _dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, Page2, EnabledFlag, (int)TargetType.Url, redirectUrlPage2, 1); + var mobileUrlForPage1 = this._redirectionController.GetMobileSiteUrl(Portal0, Page1); + var mobileUrlForPage2 = this._redirectionController.GetMobileSiteUrl(Portal0, Page2); + var mobileUrlForPage3 = this._redirectionController.GetMobileSiteUrl(Portal0, Page3); - var mobileUrlForPage1 = _redirectionController.GetMobileSiteUrl(Portal0, Page1); - var mobileUrlForPage2 = _redirectionController.GetMobileSiteUrl(Portal0, Page2); - var mobileUrlForPage3 = _redirectionController.GetMobileSiteUrl(Portal0, Page3); + // First Page returns link to first url + Assert.AreEqual(string.Format("{0}?nomo=0", redirectUrlPage1), mobileUrlForPage1); - //First Page returns link to first url - Assert.AreEqual(String.Format("{0}?nomo=0",redirectUrlPage1), mobileUrlForPage1); + // Second Page returns link to second url + Assert.AreEqual(string.Format("{0}?nomo=0", redirectUrlPage2), mobileUrlForPage2); - //Second Page returns link to second url - Assert.AreEqual(String.Format("{0}?nomo=0", redirectUrlPage2), mobileUrlForPage2); - - //Third Page returns link to first url - as this is the first found url and third page has no redirect defined - Assert.AreEqual(mobileUrlForPage3, String.Format("{0}?nomo=0", redirectUrlPage1)); + // Third Page returns link to first url - as this is the first found url and third page has no redirect defined + Assert.AreEqual(mobileUrlForPage3, string.Format("{0}?nomo=0", redirectUrlPage1)); } - //[Test] - //public void RedirectionController_GetMobileSiteUrl_Works_When_Page_Redirects_To_Another_Portal() - //{ + // [Test] + // public void RedirectionController_GetMobileSiteUrl_Works_When_Page_Redirects_To_Another_Portal() + // { // //first page goes to one second portal - // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, Portal1, 1); + // _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, Portal1, 1); - // var mobileUrlForPage1 = _redirectionController.GetMobileSiteUrl(Portal0, Page1); + // var mobileUrlForPage1 = _redirectionController.GetMobileSiteUrl(Portal0, Page1); - // //First Page returns link to home page of other portal + // //First Page returns link to home page of other portal // Assert.AreEqual(Globals.AddHTTP(PortalAlias1), mobileUrlForPage1); - //} - + // } [Test] public void RedirectionController_GetMobileSiteUrl_When_Redirect_To_DifferentUrl() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, HomePageOnPortal0, EnabledFlag, (int)TargetType.Url, ExternalSite, 1); - var url = _redirectionController.GetMobileSiteUrl(Portal1, AnotherPageOnSamePortal); + var url = this._redirectionController.GetMobileSiteUrl(Portal1, AnotherPageOnSamePortal); Assert.AreEqual(string.Empty, url); + } + + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_In_Normal_Action() + { + var app = this.GenerateApplication(); + + Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); } - #endregion - - #region Redirect Enable/Disable Tests - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_In_Normal_Action() - { - var app = GenerateApplication(); - - Assert.IsTrue(_redirectionController.IsRedirectAllowedForTheSession(app)); - } - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1() - { - var app = GenerateApplication(); - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); - - Assert.IsFalse(_redirectionController.IsRedirectAllowedForTheSession(app)); - Assert.IsNotNull(app.Request.Cookies[DisableMobileRedirectCookieName]); - Assert.IsNotNull(app.Request.Cookies[DisableRedirectPresistCookieName]); - } - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_0() - { - var app = GenerateApplication(); - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); - - Assert.IsTrue(_redirectionController.IsRedirectAllowedForTheSession(app)); - } - - [Test] - public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1_And_Then_Setback_To_0() - { - var app = GenerateApplication(); - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); - Assert.IsFalse(_redirectionController.IsRedirectAllowedForTheSession(app)); - - app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); - Assert.IsTrue(_redirectionController.IsRedirectAllowedForTheSession(app)); - } - - #endregion - - #endregion - - #region Private Methods - - private void SetupDataProvider() - { - _dataProvider.Setup(d => d.GetProviderPath()).Returns(""); - - _dtRedirections = new DataTable("Redirections"); - var pkCol = _dtRedirections.Columns.Add("Id", typeof(int)); - _dtRedirections.Columns.Add("PortalId", typeof(int)); - _dtRedirections.Columns.Add("Name", typeof(string)); - _dtRedirections.Columns.Add("Type", typeof(int)); - _dtRedirections.Columns.Add("SortOrder", typeof(int)); - _dtRedirections.Columns.Add("SourceTabId", typeof(int)); - _dtRedirections.Columns.Add("IncludeChildTabs", typeof(bool)); - _dtRedirections.Columns.Add("TargetType", typeof(int)); - _dtRedirections.Columns.Add("TargetValue", typeof(object)); - _dtRedirections.Columns.Add("Enabled", typeof(bool)); - - _dtRedirections.PrimaryKey = new[] { pkCol }; - - _dtRules = new DataTable("Rules"); - var pkCol1 = _dtRules.Columns.Add("Id", typeof(int)); - _dtRules.Columns.Add("RedirectionId", typeof(int)); - _dtRules.Columns.Add("Capability", typeof(string)); - _dtRules.Columns.Add("Expression", typeof(string)); - - _dtRules.PrimaryKey = new[] { pkCol1 }; - - _dataProvider.Setup(d => - d.SaveRedirection(It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Returns( - (id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled, userId) => - { - if (id == -1) - { - if (_dtRedirections.Rows.Count == 0) - { - id = 1; - } - else - { - id = Convert.ToInt32(_dtRedirections.Select("", "Id Desc")[0]["Id"]) + 1; - } - - var row = _dtRedirections.NewRow(); - row["Id"] = id; - row["PortalId"] = portalId; - row["name"] = name; - row["type"] = type; - row["sortOrder"] = sortOrder; - row["sourceTabId"] = sourceTabId; - row["includeChildTabs"] = includeChildTabs; - row["targetType"] = targetType; - row["targetValue"] = targetValue; - row["enabled"] = enabled; - - _dtRedirections.Rows.Add(row); - } - else - { - var rows = _dtRedirections.Select("Id = " + id); - if (rows.Length == 1) - { - var row = rows[0]; - - row["name"] = name; - row["type"] = type; - row["sortOrder"] = sortOrder; - row["sourceTabId"] = sourceTabId; - row["includeChildTabs"] = includeChildTabs; - row["targetType"] = targetType; - row["targetValue"] = targetValue; - row["enabled"] = enabled; - } - } - - return id; - }); - - _dataProvider.Setup(d => d.GetRedirections(It.IsAny())).Returns(GetRedirectionsCallBack); - _dataProvider.Setup(d => d.DeleteRedirection(It.IsAny())).Callback((id) => - { - var rows = _dtRedirections.Select("Id = " + id); - if (rows.Length == 1) - { - _dtRedirections.Rows.Remove(rows[0]); - } - }); - - _dataProvider.Setup(d => d.SaveRedirectionRule(It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Callback((id, rid, capbility, expression) => - { - if (id == -1) - { - if (_dtRules.Rows.Count == 0) - { - id = 1; - } - else - { - id = Convert.ToInt32(_dtRules.Select("", "Id Desc")[0]["Id"]) + 1; - } - - var row = _dtRules.NewRow(); - row["Id"] = id; - row["RedirectionId"] = rid; - row["capability"] = capbility; - row["expression"] = expression; - - _dtRules.Rows.Add(row); - } - else - { - var rows = _dtRules.Select("Id = " + id); - if (rows.Length == 1) - { - var row = rows[0]; - - row["capability"] = capbility; - row["expression"] = expression; - } - } - }); - - _dataProvider.Setup(d => d.GetRedirectionRules(It.IsAny())).Returns(GetRedirectionRulesCallBack); - _dataProvider.Setup(d => d.DeleteRedirectionRule(It.IsAny())).Callback((id) => - { - var rows = _dtRules.Select("Id = " + id); - if (rows.Length == 1) - { - _dtRules.Rows.Remove(rows[0]); - } - }); - - _dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); - _dataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(GetTabsCallBack); - _dataProvider.Setup(d => d.GetTab(It.IsAny())).Returns(GetTabCallBack); - _dataProvider.Setup(d => d.GetTabModules(It.IsAny())).Returns(GetTabModulesCallBack); - _dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(GetPortalSettingsCallBack); - _dataProvider.Setup(d => d.GetAllRedirections()).Returns(GetAllRedirectionsCallBack); - - var portalDataService = MockComponentProvider.CreateNew(); - portalDataService.Setup(p => p.GetPortalGroups()).Returns(GetPortalGroupsCallBack); - } - - private void SetupClientCapabilityProvider() - { - _clientCapabilityProvider.Setup(p => p.GetClientCapability(It.IsAny())).Returns(GetClientCapabilityCallBack); - } - - private void SetupRoleProvider() - { - var mockRoleProvider = MockComponentProvider.CreateNew(); - } - - private IDataReader GetRedirectionsCallBack(int portalId) - { - var dtCheck = _dtRedirections.Clone(); - foreach (var row in _dtRedirections.Select("PortalId = " + portalId)) - { - dtCheck.Rows.Add(row.ItemArray); - } - - return dtCheck.CreateDataReader(); - } - - private IDataReader GetRedirectionRulesCallBack(int rid) - { - var dtCheck = _dtRules.Clone(); - foreach (var row in _dtRules.Select("RedirectionId = " + rid)) - { - dtCheck.Rows.Add(row.ItemArray); - } - - return dtCheck.CreateDataReader(); - } + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1() + { + var app = this.GenerateApplication(); + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); + + Assert.IsFalse(this._redirectionController.IsRedirectAllowedForTheSession(app)); + Assert.IsNotNull(app.Request.Cookies[DisableMobileRedirectCookieName]); + Assert.IsNotNull(app.Request.Cookies[DisableRedirectPresistCookieName]); + } - private IDataReader GetPortalsCallBack(string culture) + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_0() { - return GetPortalCallBack(Portal0, DotNetNuke.Services.Localization.Localization.SystemLocale); + var app = this.GenerateApplication(); + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); + + Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); } - private IDataReader GetPortalCallBack(int portalId, string culture) - { - DataTable table = new DataTable("Portal"); + [Test] + public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Param_Set_To_1_And_Then_Setback_To_0() + { + var app = this.GenerateApplication(); + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "1"); + Assert.IsFalse(this._redirectionController.IsRedirectAllowedForTheSession(app)); + + app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); + Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); + } + + private void SetupDataProvider() + { + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + this._dtRedirections = new DataTable("Redirections"); + var pkCol = this._dtRedirections.Columns.Add("Id", typeof(int)); + this._dtRedirections.Columns.Add("PortalId", typeof(int)); + this._dtRedirections.Columns.Add("Name", typeof(string)); + this._dtRedirections.Columns.Add("Type", typeof(int)); + this._dtRedirections.Columns.Add("SortOrder", typeof(int)); + this._dtRedirections.Columns.Add("SourceTabId", typeof(int)); + this._dtRedirections.Columns.Add("IncludeChildTabs", typeof(bool)); + this._dtRedirections.Columns.Add("TargetType", typeof(int)); + this._dtRedirections.Columns.Add("TargetValue", typeof(object)); + this._dtRedirections.Columns.Add("Enabled", typeof(bool)); + + this._dtRedirections.PrimaryKey = new[] { pkCol }; + + this._dtRules = new DataTable("Rules"); + var pkCol1 = this._dtRules.Columns.Add("Id", typeof(int)); + this._dtRules.Columns.Add("RedirectionId", typeof(int)); + this._dtRules.Columns.Add("Capability", typeof(string)); + this._dtRules.Columns.Add("Expression", typeof(string)); + + this._dtRules.PrimaryKey = new[] { pkCol1 }; + + this._dataProvider.Setup(d => + d.SaveRedirection( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())).Returns( + (id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled, userId) => + { + if (id == -1) + { + if (this._dtRedirections.Rows.Count == 0) + { + id = 1; + } + else + { + id = Convert.ToInt32(this._dtRedirections.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; + } + + var row = this._dtRedirections.NewRow(); + row["Id"] = id; + row["PortalId"] = portalId; + row["name"] = name; + row["type"] = type; + row["sortOrder"] = sortOrder; + row["sourceTabId"] = sourceTabId; + row["includeChildTabs"] = includeChildTabs; + row["targetType"] = targetType; + row["targetValue"] = targetValue; + row["enabled"] = enabled; + + this._dtRedirections.Rows.Add(row); + } + else + { + var rows = this._dtRedirections.Select("Id = " + id); + if (rows.Length == 1) + { + var row = rows[0]; + + row["name"] = name; + row["type"] = type; + row["sortOrder"] = sortOrder; + row["sourceTabId"] = sourceTabId; + row["includeChildTabs"] = includeChildTabs; + row["targetType"] = targetType; + row["targetValue"] = targetValue; + row["enabled"] = enabled; + } + } + + return id; + }); + + this._dataProvider.Setup(d => d.GetRedirections(It.IsAny())).Returns(this.GetRedirectionsCallBack); + this._dataProvider.Setup(d => d.DeleteRedirection(It.IsAny())).Callback((id) => + { + var rows = this._dtRedirections.Select("Id = " + id); + if (rows.Length == 1) + { + this._dtRedirections.Rows.Remove(rows[0]); + } + }); + + this._dataProvider.Setup(d => d.SaveRedirectionRule( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())).Callback((id, rid, capbility, expression) => + { + if (id == -1) + { + if (this._dtRules.Rows.Count == 0) + { + id = 1; + } + else + { + id = Convert.ToInt32(this._dtRules.Select(string.Empty, "Id Desc")[0]["Id"]) + 1; + } + + var row = this._dtRules.NewRow(); + row["Id"] = id; + row["RedirectionId"] = rid; + row["capability"] = capbility; + row["expression"] = expression; + + this._dtRules.Rows.Add(row); + } + else + { + var rows = this._dtRules.Select("Id = " + id); + if (rows.Length == 1) + { + var row = rows[0]; + + row["capability"] = capbility; + row["expression"] = expression; + } + } + }); + + this._dataProvider.Setup(d => d.GetRedirectionRules(It.IsAny())).Returns(this.GetRedirectionRulesCallBack); + this._dataProvider.Setup(d => d.DeleteRedirectionRule(It.IsAny())).Callback((id) => + { + var rows = this._dtRules.Select("Id = " + id); + if (rows.Length == 1) + { + this._dtRules.Rows.Remove(rows[0]); + } + }); + + this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + this._dataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(this.GetTabsCallBack); + this._dataProvider.Setup(d => d.GetTab(It.IsAny())).Returns(this.GetTabCallBack); + this._dataProvider.Setup(d => d.GetTabModules(It.IsAny())).Returns(this.GetTabModulesCallBack); + this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); + this._dataProvider.Setup(d => d.GetAllRedirections()).Returns(this.GetAllRedirectionsCallBack); - var cols = new string[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode" - }; + var portalDataService = MockComponentProvider.CreateNew(); + portalDataService.Setup(p => p.GetPortalGroups()).Returns(this.GetPortalGroupsCallBack); + } - foreach (var col in cols) - { - table.Columns.Add(col); - } + private void SetupClientCapabilityProvider() + { + this._clientCapabilityProvider.Setup(p => p.GetClientCapability(It.IsAny())).Returns(this.GetClientCapabilityCallBack); + } - int homePage = 55; - if (portalId == Portal0) - homePage = HomePageOnPortal0; - else if (portalId == Portal1) - homePage = HomePageOnPortal1; + private void SetupRoleProvider() + { + var mockRoleProvider = MockComponentProvider.CreateNew(); + } + private IDataReader GetRedirectionsCallBack(int portalId) + { + var dtCheck = this._dtRedirections.Clone(); + foreach (var row in this._dtRedirections.Select("PortalId = " + portalId)) + { + dtCheck.Rows.Add(row.ItemArray); + } + + return dtCheck.CreateDataReader(); + } + + private IDataReader GetRedirectionRulesCallBack(int rid) + { + var dtCheck = this._dtRules.Clone(); + foreach (var row in this._dtRules.Select("RedirectionId = " + rid)) + { + dtCheck.Rows.Add(row.ItemArray); + } + + return dtCheck.CreateDataReader(); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(Portal0, DotNetNuke.Services.Localization.Localization.SystemLocale); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + DataTable table = new DataTable("Portal"); + + var cols = new string[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + int homePage = 55; + if (portalId == Portal0) + { + homePage = HomePageOnPortal0; + } + else if (portalId == Portal1) + { + homePage = HomePageOnPortal1; + } + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); - return table.CreateDataReader(); - } - - private DataTable GetTabsDataTable() - { - DataTable table = new DataTable("Tabs"); - - var cols = new string[] - { - "TabID","UniqueId","VersionGuid","DefaultLanguageGuid","LocalizedVersionGuid","TabOrder","PortalID","TabName","IsVisible","ParentId","Level","IconFile","IconFileLarge","DisableLink","Title","Description","KeyWords","IsDeleted","SkinSrc","ContainerSrc","TabPath","StartDate","EndDate","Url","HasChildren","RefreshInterval","PageHeadText","IsSecure","PermanentRedirect","SiteMapPriority","ContentItemID","Content","ContentTypeID","ModuleID","ContentKey","Indexed","CultureCode","CreatedByUserID","CreatedOnDate","LastModifiedByUserID","LastModifiedOnDate","StateID", "HasBeenPublished","IsSystem" - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - table.Rows.Add(HomePageOnPortal1, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal1, "HomePageOnPortal1", true, null, "0", null, null, false, "", "", "", false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal1", null, null, "", false, null, null, false, false, "0.5", "89", "HomePageOnPortal1", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(HomePageOnPortal0, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal0, "HomePageOnPortal0", true, null, "0", null, null, false, "", "", "", false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal0", null, null, "", false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(AnotherPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "4", Portal0, "AnotherPageOnSamePortal", true, null, "0", null, null, false, "", "", "", false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AnotherPageOnSamePortal", null, null, "", false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(MobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "5", Portal0, "MobileLandingPage", true, null, "0", null, null, false, "", "", "", false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//MobileLandingPage", null, null, "", false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(TabletLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "6", Portal0, "TabletLandingPage", true, null, "0", null, null, false, "", "", "", false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//TabletLandingPage", null, null, "", false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(AllMobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "7", Portal0, "AllMobileLandingPage", true, null, "0", null, null, false, "", "", "", false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AllMobileLandingPage", null, null, "", false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - table.Rows.Add(DeletedPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "8", Portal0, "A Deleted Page", true, null, "0", null, null, false, "", "", "", true, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//DeletedPage", null, null, "", false, null, null, false, false, "0.5", "90", "Deleted Page", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); - - return table; - } - - private IDataReader GetTabsCallBack(int portalId) - { - var table = GetTabsDataTable(); - var newTable = table.Clone(); - foreach (var row in table.Select("PortalID = " + portalId)) - { - newTable.Rows.Add(row.ItemArray); - } - - return newTable.CreateDataReader(); - } - - private IDataReader GetTabCallBack(int tabId) - { - var table = GetTabsDataTable(); - var newTable = table.Clone(); - foreach (var row in table.Select("TabID = " + tabId)) - { - newTable.Rows.Add(row.ItemArray); - } - - return newTable.CreateDataReader(); - } - - private IDataReader GetTabModulesCallBack(int tabId) - { - DataTable table = new DataTable("TabModules"); - - var cols = new string[] - { - "PortalID","TabID","TabModuleID","ModuleID","ModuleDefID","ModuleOrder","PaneName","ModuleTitle","CacheTime","CacheMethod","Alignment","Color","Border","IconFile","AllTabs","Visibility","IsDeleted","Header","Footer","StartDate","EndDate","ContainerSrc","DisplayTitle","DisplayPrint","DisplaySyndicate","IsWebSlice","WebSliceTitle","WebSliceExpiryDate","WebSliceTTL","InheritViewPermissions","DesktopModuleID","DefaultCacheTime","ModuleControlID","BusinessControllerClass","IsAdmin","SupportedFeatures","ContentItemID","Content","ContentTypeID","ContentKey","Indexed","CreatedByUserID","CreatedOnDate","LastModifiedByUserID","LastModifiedOnDate","LastContentModifiedOnDate","UniqueId","VersionGuid","DefaultLanguageGuid","LocalizedVersionGuid","CultureCode" - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - table.Columns["ModuleID"].DataType = typeof (int); - - var portalId = tabId == HomePageOnPortal0 ? Portal0 : Portal1; - - table.Rows.Add(portalId, tabId, 51, 362, 117, 1, "ContentPane", "DotNetNuke® Enterprise Edition", "3600", "FileModuleCachingProvider", "left", null, null, null, false, "2", false, null, null, null, null, "[G]Containers/DarkKnight/Banner.ascx", true, false, false, false, null, null, "0", true, "75", "1200", "240", "DotNetNuke.Modules.HtmlPro.HtmlTextController", false, "7", "90", "DotNetNuke® Enterprise Edition", "2", null, false, "-1", DateTime.Now, "-1", DateTime.Now, DateTime.Now, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), null); - - return table.CreateDataReader(); - } - - private IDataReader GetPortalSettingsCallBack(int portalId, string culture) - { - DataTable table = new DataTable("PortalSettings"); - - var cols = new string[] - { - "SettingName","SettingValue","CreatedByUserID","CreatedOnDate","LastModifiedByUserID","LastModifiedOnDate","CultureCode" - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - var alias = portalId == Portal0 ? PortalAlias0 : PortalAlias1; - - table.Rows.Add("DefaultPortalAlias", alias, "-1", DateTime.Now, "-1", DateTime.Now, "en-us"); - - return table.CreateDataReader(); - } - - private IDataReader GetPortalGroupsCallBack() - { - DataTable table = new DataTable("PortalGroups"); - - var cols = new string[] - { - "PortalGroupID","MasterPortalID","PortalGroupName","PortalGroupDescription","AuthenticationDomain","CreatedByUserID","CreatedOnDate","LastModifiedByUserID","LastModifiedOnDate" - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - table.Rows.Add(1, 0, "Portal Group", "", "", -1, DateTime.Now, -1, DateTime.Now); - - return table.CreateDataReader(); - } - - private IClientCapability GetClientCapabilityCallBack(string userAgent) - { + return table.CreateDataReader(); + } + + private DataTable GetTabsDataTable() + { + DataTable table = new DataTable("Tabs"); + + var cols = new string[] + { + "TabID", "UniqueId", "VersionGuid", "DefaultLanguageGuid", "LocalizedVersionGuid", "TabOrder", "PortalID", "TabName", "IsVisible", "ParentId", "Level", "IconFile", "IconFileLarge", "DisableLink", "Title", "Description", "KeyWords", "IsDeleted", "SkinSrc", "ContainerSrc", "TabPath", "StartDate", "EndDate", "Url", "HasChildren", "RefreshInterval", "PageHeadText", "IsSecure", "PermanentRedirect", "SiteMapPriority", "ContentItemID", "Content", "ContentTypeID", "ModuleID", "ContentKey", "Indexed", "CultureCode", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "StateID", "HasBeenPublished", "IsSystem", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Rows.Add(HomePageOnPortal1, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal1, "HomePageOnPortal1", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal1", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal1", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(HomePageOnPortal0, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "3", Portal0, "HomePageOnPortal0", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//HomePageOnPortal0", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(AnotherPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "4", Portal0, "AnotherPageOnSamePortal", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AnotherPageOnSamePortal", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(MobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "5", Portal0, "MobileLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//MobileLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(TabletLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "6", Portal0, "TabletLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//TabletLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(AllMobileLandingPage, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "7", Portal0, "AllMobileLandingPage", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, false, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//AllMobileLandingPage", null, null, string.Empty, false, null, null, false, false, "0.5", "89", "HomePageOnPortal0", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + table.Rows.Add(DeletedPageOnSamePortal, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), "8", Portal0, "A Deleted Page", true, null, "0", null, null, false, string.Empty, string.Empty, string.Empty, true, "[G]Skins/DarkKnight/Home-Mega-Menu.ascx", "[G]Containers/DarkKnight/SubTitle_Grey.ascx", "//DeletedPage", null, null, string.Empty, false, null, null, false, false, "0.5", "90", "Deleted Page", "1", "-1", null, false, null, "-1", DateTime.Now, "-1", DateTime.Now, "0", true, false); + + return table; + } + + private IDataReader GetTabsCallBack(int portalId) + { + var table = this.GetTabsDataTable(); + var newTable = table.Clone(); + foreach (var row in table.Select("PortalID = " + portalId)) + { + newTable.Rows.Add(row.ItemArray); + } + + return newTable.CreateDataReader(); + } + + private IDataReader GetTabCallBack(int tabId) + { + var table = this.GetTabsDataTable(); + var newTable = table.Clone(); + foreach (var row in table.Select("TabID = " + tabId)) + { + newTable.Rows.Add(row.ItemArray); + } + + return newTable.CreateDataReader(); + } + + private IDataReader GetTabModulesCallBack(int tabId) + { + DataTable table = new DataTable("TabModules"); + + var cols = new string[] + { + "PortalID", "TabID", "TabModuleID", "ModuleID", "ModuleDefID", "ModuleOrder", "PaneName", "ModuleTitle", "CacheTime", "CacheMethod", "Alignment", "Color", "Border", "IconFile", "AllTabs", "Visibility", "IsDeleted", "Header", "Footer", "StartDate", "EndDate", "ContainerSrc", "DisplayTitle", "DisplayPrint", "DisplaySyndicate", "IsWebSlice", "WebSliceTitle", "WebSliceExpiryDate", "WebSliceTTL", "InheritViewPermissions", "DesktopModuleID", "DefaultCacheTime", "ModuleControlID", "BusinessControllerClass", "IsAdmin", "SupportedFeatures", "ContentItemID", "Content", "ContentTypeID", "ContentKey", "Indexed", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "LastContentModifiedOnDate", "UniqueId", "VersionGuid", "DefaultLanguageGuid", "LocalizedVersionGuid", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Columns["ModuleID"].DataType = typeof(int); + + var portalId = tabId == HomePageOnPortal0 ? Portal0 : Portal1; + + table.Rows.Add(portalId, tabId, 51, 362, 117, 1, "ContentPane", "DotNetNuke® Enterprise Edition", "3600", "FileModuleCachingProvider", "left", null, null, null, false, "2", false, null, null, null, null, "[G]Containers/DarkKnight/Banner.ascx", true, false, false, false, null, null, "0", true, "75", "1200", "240", "DotNetNuke.Modules.HtmlPro.HtmlTextController", false, "7", "90", "DotNetNuke® Enterprise Edition", "2", null, false, "-1", DateTime.Now, "-1", DateTime.Now, DateTime.Now, Guid.NewGuid(), Guid.NewGuid(), null, Guid.NewGuid(), null); + + return table.CreateDataReader(); + } + + private IDataReader GetPortalSettingsCallBack(int portalId, string culture) + { + DataTable table = new DataTable("PortalSettings"); + + var cols = new string[] + { + "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + var alias = portalId == Portal0 ? PortalAlias0 : PortalAlias1; + + table.Rows.Add("DefaultPortalAlias", alias, "-1", DateTime.Now, "-1", DateTime.Now, "en-us"); + + return table.CreateDataReader(); + } + + private IDataReader GetPortalGroupsCallBack() + { + DataTable table = new DataTable("PortalGroups"); + + var cols = new string[] + { + "PortalGroupID", "MasterPortalID", "PortalGroupName", "PortalGroupDescription", "AuthenticationDomain", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Rows.Add(1, 0, "Portal Group", string.Empty, string.Empty, -1, DateTime.Now, -1, DateTime.Now); + + return table.CreateDataReader(); + } + + private IClientCapability GetClientCapabilityCallBack(string userAgent) + { IClientCapability clientCapability = new TestClientCapability(); if (userAgent == iphoneUserAgent) { @@ -864,117 +837,113 @@ private IClientCapability GetClientCapabilityCallBack(string userAgent) } else if (userAgent == motorolaRIZRSymbianOSOpera865) { - clientCapability.IsMobile = true; + clientCapability.IsMobile = true; clientCapability.Capabilities.Add("mobile_browser", "Opera Mini"); clientCapability.Capabilities.Add("device_os", "Symbian OS"); } - + return clientCapability; - } - - private IDataReader GetAllRedirectionsCallBack() - { - return _dtRedirections.CreateDataReader(); - } - - private void PrepareData() - { - //id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled - _dtRedirections.Rows.Add(1, Portal0, "R4", (int)RedirectionType.Other, 4, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - _dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - _dtRedirections.Rows.Add(3, Portal0, "R3", (int)RedirectionType.AllMobile, 3, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - _dtRedirections.Rows.Add(4, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - _dtRedirections.Rows.Add(5, Portal0, "R5", (int)RedirectionType.MobilePhone, 5, HomePageOnPortal0, EnabledFlag, (int)TargetType.Portal, "1", EnabledFlag); - _dtRedirections.Rows.Add(6, Portal0, "R6", (int)RedirectionType.MobilePhone, 6, -1, DisabledFlag, (int)TargetType.Tab, HomePageOnPortal0, EnabledFlag); - _dtRedirections.Rows.Add(7, Portal0, "R7", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, EnabledFlag); - - //id, redirectionId, capability, expression - _dtRules.Rows.Add(1, 1, "mobile_browser", "Safari"); - _dtRules.Rows.Add(2, 1, "device_os_version", "4.0"); - - _dtRedirections.Rows.Add(8, Portal1, "R8", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); - _dtRedirections.Rows.Add(9, Portal1, "R9", (int)RedirectionType.Tablet, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); - _dtRedirections.Rows.Add(10, Portal1, "R10", (int)RedirectionType.AllMobile, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); - } + } + + private IDataReader GetAllRedirectionsCallBack() + { + return this._dtRedirections.CreateDataReader(); + } + + private void PrepareData() + { + // id, portalId, name, type, sortOrder, sourceTabId, includeChildTabs, targetType, targetValue, enabled + this._dtRedirections.Rows.Add(1, Portal0, "R4", (int)RedirectionType.Other, 4, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(3, Portal0, "R3", (int)RedirectionType.AllMobile, 3, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(4, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(5, Portal0, "R5", (int)RedirectionType.MobilePhone, 5, HomePageOnPortal0, EnabledFlag, (int)TargetType.Portal, "1", EnabledFlag); + this._dtRedirections.Rows.Add(6, Portal0, "R6", (int)RedirectionType.MobilePhone, 6, -1, DisabledFlag, (int)TargetType.Tab, HomePageOnPortal0, EnabledFlag); + this._dtRedirections.Rows.Add(7, Portal0, "R7", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, EnabledFlag); + + // id, redirectionId, capability, expression + this._dtRules.Rows.Add(1, 1, "mobile_browser", "Safari"); + this._dtRules.Rows.Add(2, 1, "device_os_version", "4.0"); + + this._dtRedirections.Rows.Add(8, Portal1, "R8", (int)RedirectionType.MobilePhone, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); + this._dtRedirections.Rows.Add(9, Portal1, "R9", (int)RedirectionType.Tablet, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); + this._dtRedirections.Rows.Add(10, Portal1, "R10", (int)RedirectionType.AllMobile, 1, -1, EnabledFlag, (int)TargetType.Portal, 2, true); + } private void PrepareOperaBrowserOnSymbianOSRedirectionRule() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); - //id, redirectionId, capability, expression - _dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); - _dtRules.Rows.Add(2, 1, "device_os", "Symbian OS"); + // id, redirectionId, capability, expression + this._dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); + this._dtRules.Rows.Add(2, 1, "device_os", "Symbian OS"); } private void PrepareOperaBrowserOnIPhoneOSRedirectionRule() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Other, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); - //id, redirectionId, capability, expression - _dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); - _dtRules.Rows.Add(2, 1, "device_os", "iPhone OS"); + // id, redirectionId, capability, expression + this._dtRules.Rows.Add(1, 1, "mobile_browser", "Opera Mini"); + this._dtRules.Rows.Add(2, 1, "device_os", "iPhone OS"); } private void PreparePortalToAnotherPageOnSamePortal() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, AnotherPageOnSamePortal, EnabledFlag); } private void PrepareSamePortalToSamePortalRedirectionRule() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, Portal0, 1); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Portal, Portal0, 1); } private void PrepareExternalSiteRedirectionRule() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, 1); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 7, -1, DisabledFlag, (int)TargetType.Url, ExternalSite, 1); } private void PrepareMobileAndTabletRedirectionRuleWithMobileFirst() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); - _dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.MobilePhone, 1, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.Tablet, 2, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); } private void PrepareMobileAndTabletRedirectionRuleWithAndTabletRedirectionRuleTabletFirst() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Tablet, 1, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); - _dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.MobilePhone, 2, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); - + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.Tablet, 1, -1, DisabledFlag, (int)TargetType.Tab, TabletLandingPage, EnabledFlag); + this._dtRedirections.Rows.Add(2, Portal0, "R2", (int)RedirectionType.MobilePhone, 2, -1, DisabledFlag, (int)TargetType.Tab, MobileLandingPage, EnabledFlag); } private void PrepareAllMobileRedirectionRule() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, EnabledFlag); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, EnabledFlag); } private void PrepareSingleDisabledRedirectionRule() { - _dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, DisabledFlag); + this._dtRedirections.Rows.Add(1, Portal0, "R1", (int)RedirectionType.AllMobile, 1, -1, DisabledFlag, (int)TargetType.Tab, AllMobileLandingPage, DisabledFlag); } - private HttpApplication GenerateApplication() - { + private HttpApplication GenerateApplication() + { var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", "c:\\"); simulator.SimulateRequest(new Uri("http://localhost/dnn/Default.aspx")); - var app = new HttpApplication(); + var app = new HttpApplication(); - var requestProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); - requestProp.SetValue(HttpContext.Current.Request.QueryString, false, null); - - var stateProp = typeof(HttpApplication).GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic); - stateProp.SetValue(app, HttpContext.Current); - - return app; - } + var requestProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); + requestProp.SetValue(HttpContext.Current.Request.QueryString, false, null); + var stateProp = typeof(HttpApplication).GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic); + stateProp.SetValue(app, HttpContext.Current); + return app; + } + private string NavigateUrl(int tabId) { return string.Format("/Default.aspx?tabid={0}", tabId); - } - - #endregion - } + } + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs index 515caf76371..dba880e0079 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs @@ -1,19 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Globalization; - -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.Tokens { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Tokens; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class PropertyAccessTests { @@ -25,25 +24,25 @@ public class PropertyAccessTests [TestCase("", true)] public void TicksPropertyAcccess_GetProperty_Sets_PropertyNotFound(string propertyName, bool expected) { - //Arrange + // Arrange var ticksPropertyAccess = new TicksPropertyAccess(); var accessingUser = new UserInfo(); - //Act + // Act bool propertyNotFound = false; - string propertyValue = ticksPropertyAccess.GetProperty(propertyName, "", CultureInfo.InvariantCulture, + string propertyValue = ticksPropertyAccess.GetProperty(propertyName, string.Empty, CultureInfo.InvariantCulture, accessingUser, Scope.DefaultSettings, ref propertyNotFound); - //Assert + // Assert Assert.AreEqual(expected, propertyNotFound); } - + [Test] [TestCase("today")] [TestCase("ticksperday")] public void TicksPropertyAcccess_GetProperty_Returns_Correct_String(string propertyName) { - //Arrange + // Arrange var ticksPropertyAccess = new TicksPropertyAccess(); var accessingUser = new UserInfo(); @@ -61,12 +60,12 @@ public void TicksPropertyAcccess_GetProperty_Returns_Correct_String(string prope break; } - //Act + // Act bool propertyNotFound = false; - string propertyValue = ticksPropertyAccess.GetProperty(propertyName, "", CultureInfo.InvariantCulture, + string propertyValue = ticksPropertyAccess.GetProperty(propertyName, string.Empty, CultureInfo.InvariantCulture, accessingUser, Scope.DefaultSettings, ref propertyNotFound); - //Assert + // Assert Assert.AreEqual(expected.ToString(CultureInfo.InvariantCulture), propertyValue); } @@ -79,17 +78,16 @@ public void TicksPropertyAcccess_GetProperty_Returns_Correct_String(string prope [TestCase("", true)] public void DateTimePropertyAcccess_GetProperty_Sets_PropertyNotFound(string propertyName, bool expected) { - //Arrange + // Arrange var dtPropertyAccess = new DateTimePropertyAccess(); - var accessingUser = new UserInfo {Profile = new UserProfile {PreferredTimeZone = TimeZoneInfo.Local}}; - - - //Act + var accessingUser = new UserInfo { Profile = new UserProfile { PreferredTimeZone = TimeZoneInfo.Local } }; + + // Act bool propertyNotFound = false; - string propertyValue = dtPropertyAccess.GetProperty(propertyName, "", CultureInfo.InvariantCulture, + string propertyValue = dtPropertyAccess.GetProperty(propertyName, string.Empty, CultureInfo.InvariantCulture, accessingUser, Scope.DefaultSettings, ref propertyNotFound); - //Assert + // Assert Assert.AreEqual(expected, propertyNotFound); } @@ -104,12 +102,12 @@ public void DateTimePropertyAcccess_GetProperty_Sets_PropertyNotFound(string pro [TestCase("utc", "it")] public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_For_Culture(string propertyName, string cultureName) { - //Arrange + // Arrange var dtPropertyAccess = new DateTimePropertyAccess(); var accessingUser = new UserInfo { Profile = new UserProfile { PreferredTimeZone = TimeZoneInfo.Local } }; var culture = new CultureInfo(cultureName); - string expected = String.Empty; + string expected = string.Empty; switch (propertyName) { @@ -126,82 +124,79 @@ public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_For_Cultu expected = DateTime.Now.ToUniversalTime().ToString("g", culture); break; } - - - //Act + + // Act bool propertyNotFound = false; - string propertyValue = dtPropertyAccess.GetProperty(propertyName, "", culture, + string propertyValue = dtPropertyAccess.GetProperty(propertyName, string.Empty, culture, accessingUser, Scope.DefaultSettings, ref propertyNotFound); - //Assert + // Assert Assert.AreEqual(expected, propertyValue); } - [Test] - [TestCase("current", "", "D")] - [TestCase("now", "", "g")] - [TestCase("system", "", "g")] - [TestCase("utc", "", "g")] - [TestCase("current", "fr", "g")] - [TestCase("now", "de", "mmm yyyy")] - [TestCase("system", "en", "dd/mm/yy")] - [TestCase("utc", "it", "mmm dd, yyyy")] - public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_Given_Format_And_Culture(string propertyName, string cultureName, string format) - { - //Arrange - var dtPropertyAccess = new DateTimePropertyAccess(); - var accessingUser = new UserInfo { Profile = new UserProfile { PreferredTimeZone = TimeZoneInfo.Local } }; - var culture = new CultureInfo(cultureName); - - - string expected = String.Empty; - - switch (propertyName) - { - case "current": - expected = DateTime.Now.ToString(format, culture); - break; - case "now": - expected = DateTime.Now.ToString(format, culture); - break; - case "system": - expected = DateTime.Now.ToString(format, culture); - break; - case "utc": - expected = DateTime.Now.ToUniversalTime().ToString(format, culture); - break; - } - - - //Act - bool propertyNotFound = false; - string propertyValue = dtPropertyAccess.GetProperty(propertyName, format, culture, - accessingUser, Scope.DefaultSettings, ref propertyNotFound); - - //Assert - Assert.AreEqual(expected, propertyValue); - } + [Test] + [TestCase("current", "", "D")] + [TestCase("now", "", "g")] + [TestCase("system", "", "g")] + [TestCase("utc", "", "g")] + [TestCase("current", "fr", "g")] + [TestCase("now", "de", "mmm yyyy")] + [TestCase("system", "en", "dd/mm/yy")] + [TestCase("utc", "it", "mmm dd, yyyy")] + public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_Given_Format_And_Culture(string propertyName, string cultureName, string format) + { + // Arrange + var dtPropertyAccess = new DateTimePropertyAccess(); + var accessingUser = new UserInfo { Profile = new UserProfile { PreferredTimeZone = TimeZoneInfo.Local } }; + var culture = new CultureInfo(cultureName); + + string expected = string.Empty; + + switch (propertyName) + { + case "current": + expected = DateTime.Now.ToString(format, culture); + break; + case "now": + expected = DateTime.Now.ToString(format, culture); + break; + case "system": + expected = DateTime.Now.ToString(format, culture); + break; + case "utc": + expected = DateTime.Now.ToUniversalTime().ToString(format, culture); + break; + } + + // Act + bool propertyNotFound = false; + string propertyValue = dtPropertyAccess.GetProperty(propertyName, format, culture, + accessingUser, Scope.DefaultSettings, ref propertyNotFound); + + // Assert + Assert.AreEqual(expected, propertyValue); + } [Test] [TestCase("current", "Tokyo Standard Time")] [TestCase("now", "Azores Standard Time")] public void DateTimePropertyAcccess_GetProperty_Adjusts_For_TimeZone(string propertyName, string timeZoneId) { - //Arrange + // Arrange var dtPropertyAccess = new DateTimePropertyAccess(); var userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); - var timeZoneProfileProperty = new ProfilePropertyDefinition(Constants.PORTAL_Zero) - { - PropertyName = "PreferredTimeZone", - PropertyValue = timeZoneId - }; + var timeZoneProfileProperty = new ProfilePropertyDefinition(Constants.PORTAL_Zero) + { + PropertyName = "PreferredTimeZone", + PropertyValue = timeZoneId, + }; var userProfile = new UserProfile(); userProfile.ProfileProperties.Add(timeZoneProfileProperty); var accessingUser = new UserInfo { Profile = userProfile }; var culture = CultureInfo.InvariantCulture; - string expected = String.Empty; + string expected = string.Empty; switch (propertyName) { @@ -218,14 +213,13 @@ public void DateTimePropertyAcccess_GetProperty_Adjusts_For_TimeZone(string prop expected = DateTime.Now.ToUniversalTime().ToString("g", culture); break; } - - - //Act + + // Act bool propertyNotFound = false; - string propertyValue = dtPropertyAccess.GetProperty(propertyName, "", culture, + string propertyValue = dtPropertyAccess.GetProperty(propertyName, string.Empty, culture, accessingUser, Scope.DefaultSettings, ref propertyNotFound); - //Assert + // Assert Assert.AreEqual(expected, propertyValue); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs index ab4ab3c1664..d1454d75f6c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/TokenReplaceTests.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Tokens; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.Tokens { + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Tokens; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class TokenReplaceTests { @@ -28,18 +28,18 @@ public class TokenReplaceTests [SetUp] public void SetUp() { - _mockCache = MockComponentProvider.CreateDataCacheProvider(); - _mockHostController = new Mock(); - _portalController = new Mock(); - _moduleController = new Mock(); - _userController = new Mock(); - PortalController.SetTestableInstance(_portalController.Object); - ModuleController.SetTestableInstance(_moduleController.Object); - UserController.SetTestableInstance(_userController.Object); - HostController.RegisterInstance(_mockHostController.Object); - SetupPortalSettings(); - SetupModuleInfo(); - SetupUserInfo(); + this._mockCache = MockComponentProvider.CreateDataCacheProvider(); + this._mockHostController = new Mock(); + this._portalController = new Mock(); + this._moduleController = new Mock(); + this._userController = new Mock(); + PortalController.SetTestableInstance(this._portalController.Object); + ModuleController.SetTestableInstance(this._moduleController.Object); + UserController.SetTestableInstance(this._userController.Object); + HostController.RegisterInstance(this._mockHostController.Object); + this.SetupPortalSettings(); + this.SetupModuleInfo(); + this.SetupUserInfo(); } [TearDown] @@ -55,14 +55,14 @@ public void TearDown() [TestCase("This is just plain text")] public void TextInputIsReturnedUnModified(string sourceText) { - //Arrange + // Arrange var tokenReplace = new TokenReplace(Scope.DefaultSettings, PortalSettings.Current.DefaultLanguage, PortalSettings.Current, UserController.Instance.GetUser(1, 1), 1); - //Act + // Act var outputText = tokenReplace.ReplaceEnvironmentTokens(sourceText); - //Assert + // Assert Assert.AreEqual(outputText, sourceText); } @@ -72,14 +72,14 @@ public void TextInputIsReturnedUnModified(string sourceText) [TestCase("[JavaScript:{ jsname: \"Knockout\" }] [JavaScript:{ path: \"~/DesktopModules/Dnn/ContactList/ClientScripts/contacts.js\"}]")] public void ObjectInputIsReturnedBlank(string sourceText) { - //Arrange + // Arrange var tokenReplace = new TokenReplace(Scope.DefaultSettings, PortalSettings.Current.DefaultLanguage, PortalSettings.Current, UserController.Instance.GetUser(1, 1), 1); - //Act + // Act var outputText = tokenReplace.ReplaceEnvironmentTokens(sourceText); - //Assert + // Assert Assert.AreEqual(outputText.Trim(), string.Empty); } @@ -88,10 +88,10 @@ private void SetupPortalSettings() var portalSettings = new PortalSettings { AdministratorRoleName = Utilities.Constants.RoleName_Administrators, - ActiveTab = new TabInfo { ModuleID = 1, TabID = 1 } + ActiveTab = new TabInfo { ModuleID = 1, TabID = 1 }, }; - _portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); + this._portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); } private void SetupModuleInfo() @@ -99,10 +99,10 @@ private void SetupModuleInfo() var moduleInfo = new ModuleInfo { ModuleID = 1, - PortalID = _portalController.Object.GetCurrentPortalSettings().PortalId + PortalID = this._portalController.Object.GetCurrentPortalSettings().PortalId, }; - _moduleController.Setup(mc => mc.GetModule(It.IsAny(), It.IsAny(), It.IsAny())) + this._moduleController.Setup(mc => mc.GetModule(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(moduleInfo); } @@ -112,9 +112,9 @@ private void SetupUserInfo() { UserID = 1, Username = "admin", - PortalID = _portalController.Object.GetCurrentPortalSettings().PortalId + PortalID = this._portalController.Object.GetCurrentPortalSettings().PortalId, }; - _userController.Setup(uc => uc.GetUser(It.IsAny(), It.IsAny())).Returns(userInfo); + this._userController.Setup(uc => uc.GetUser(It.IsAny(), It.IsAny())).Returns(userInfo); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs index 1a91cbc8fea..19260665959 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UserRequest/UserRequestIPAddressControllerTest.cs @@ -1,108 +1,109 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Portals; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using NUnit.Framework; -using DotNetNuke.Entities.Controllers; -using System.Web; -using DotNetNuke.Tests.Utilities; -using System.Collections.Specialized; -using DotNetNuke.Services.UserRequest; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services.UserRequest { + using System.Collections.Specialized; + using System.Web; + + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.UserRequest; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] - class UserRequestIPAddressControllerTest + internal class UserRequestIPAddressControllerTest { private Mock _mockPortalController; private Mock _mockHostController; private Mock _mockhttpContext; private Mock _mockRequest; - + private UserRequestIPAddressController _userRequestIPAddressController; [SetUp] public void Setup() { NameValueCollection serverVariables = new NameValueCollection(); - + // Setup Mock - _mockhttpContext = HttpContextHelper.RegisterMockHttpContext(); - _mockRequest = Mock.Get(_mockhttpContext.Object.Request); - _mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); - _mockHostController = MockComponentProvider.CreateNew(); - _mockPortalController = MockComponentProvider.CreateNew(); - PortalController.SetTestableInstance(_mockPortalController.Object); + this._mockhttpContext = HttpContextHelper.RegisterMockHttpContext(); + this._mockRequest = Mock.Get(this._mockhttpContext.Object.Request); + this._mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); + this._mockHostController = MockComponentProvider.CreateNew(); + this._mockPortalController = MockComponentProvider.CreateNew(); + PortalController.SetTestableInstance(this._mockPortalController.Object); // System under test - _userRequestIPAddressController = new UserRequestIPAddressController(); + this._userRequestIPAddressController = new UserRequestIPAddressController(); } [TearDown] public void TearDown() { MockComponentProvider.ResetContainer(); - } + } - [TestCase("111.111.111.111","X-Forwarded-For")] + [TestCase("111.111.111.111", "X-Forwarded-For")] [TestCase("111.111.111.111,123.112.11.33", "X-Forwarded-For")] [TestCase("111.111.111.111", "X-ProxyUser-Ip")] [TestCase("111.111.111.111,23.112.11.33", "X-ProxyUser-Ip")] public void UserRequestIPAddress_ShouldReturnIP_IfAnyHeaderIsPresent(string requestIp, string headerName) { - //Arrange - var expectedIp = "111.111.111.111"; + // Arrange + var expectedIp = "111.111.111.111"; NameValueCollection headersWithXForwardedHeaders = new NameValueCollection(); headersWithXForwardedHeaders.Add(headerName, requestIp); - _mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); - _mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); + this._mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); + this._mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); - //Act - string userRequestIPAddress = _userRequestIPAddressController.GetUserRequestIPAddress(_mockhttpContext.Object.Request); + // Act + string userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - //Assert + // Assert Assert.AreEqual(expectedIp, userRequestIPAddress); } [Test] public void UserRequestIPAddress_ShouldReturnIP_IfRemoteAddrServerVariablePresent() { - //Arrange + // Arrange var expectedIp = "111.111.111.111"; var remoteVariable = "REMOTE_ADDR"; var requestIp = "111.111.111.111"; NameValueCollection serverVariables = new NameValueCollection(); serverVariables.Add(remoteVariable, requestIp); - _mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); + this._mockRequest.Setup(x => x.ServerVariables).Returns(serverVariables); - //Act - var userRequestIPAddress = _userRequestIPAddressController.GetUserRequestIPAddress(_mockhttpContext.Object.Request); + // Act + var userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - //Assert + // Assert Assert.AreSame(expectedIp, userRequestIPAddress); - _mockRequest.VerifyGet(r => r.ServerVariables); - _mockRequest.VerifyGet(r => r.Headers); - _mockHostController.Verify(hc => hc.GetString(It.IsAny(), It.IsAny())); + this._mockRequest.VerifyGet(r => r.ServerVariables); + this._mockRequest.VerifyGet(r => r.Headers); + this._mockHostController.Verify(hc => hc.GetString(It.IsAny(), It.IsAny())); } [Test] public void UserRequestIPAddress_ShouldReturnIP_IfUserHostAddress() { - //Arrange + // Arrange var expectedIp = "111.111.111.111"; - _mockRequest.Setup(x => x.UserHostAddress).Returns(expectedIp); + this._mockRequest.Setup(x => x.UserHostAddress).Returns(expectedIp); - //Act - var userRequestIPAddress = _userRequestIPAddressController.GetUserRequestIPAddress(_mockhttpContext.Object.Request); + // Act + var userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - //Assert + // Assert Assert.AreSame(expectedIp, userRequestIPAddress); - _mockRequest.VerifyGet(r => r.UserHostAddress); + this._mockRequest.VerifyGet(r => r.UserHostAddress); } [TestCase("abc.111.eer")] @@ -110,18 +111,18 @@ public void UserRequestIPAddress_ShouldReturnIP_IfUserHostAddress() [TestCase("244.275.111.111")] public void UserRequestIPAddress_ShouldReturnEmptyString_IfIPAddressIsNotValid(string requestIp) { - //Arrange - var headerName = "X-Forwarded-For"; + // Arrange + var headerName = "X-Forwarded-For"; NameValueCollection headersWithXForwardedHeaders = new NameValueCollection(); headersWithXForwardedHeaders.Add(headerName, requestIp); - _mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); - _mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); - - //Act - var userRequestIPAddress = _userRequestIPAddressController.GetUserRequestIPAddress(_mockhttpContext.Object.Request); + this._mockRequest.Setup(x => x.Headers).Returns(headersWithXForwardedHeaders); + this._mockHostController.Setup(hc => hc.GetString(It.IsAny(), It.IsAny())).Returns(headerName); + + // Act + var userRequestIPAddress = this._userRequestIPAddressController.GetUserRequestIPAddress(this._mockhttpContext.Object.Request); - //Assert + // Assert Assert.AreSame(string.Empty, userRequestIPAddress); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UtilTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UtilTest.cs index 4a718e7ac7a..1bfc19db23c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UtilTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/UtilTest.cs @@ -1,28 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Diagnostics; -using System.IO; -using System.Threading.Tasks; -using DotNetNuke.Services.Installer; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Services { + using System.Diagnostics; + using System.IO; + using System.Threading.Tasks; + + using DotNetNuke.Services.Installer; + using NUnit.Framework; + [TestFixture] public class UtilTest { [Test] public void Dnn_9838_TryToCreateAndExecute_UnsuccesfulRewrite() { - TryToRewriteFile(lockFileFor: 1000, tryRewriteFileFor: 500, isRewritten: false); + this.TryToRewriteFile(lockFileFor: 1000, tryRewriteFileFor: 500, isRewritten: false); } [Test] public void Dnn_9838_TryToCreateAndExecute_SuccessfulRewrite() { - TryToRewriteFile(lockFileFor: 500, tryRewriteFileFor: 1000, isRewritten: true); + this.TryToRewriteFile(lockFileFor: 500, tryRewriteFileFor: 1000, isRewritten: true); } private void TryToRewriteFile(int lockFileFor, int tryRewriteFileFor, bool isRewritten) @@ -34,13 +35,11 @@ private void TryToRewriteFile(int lockFileFor, int tryRewriteFileFor, bool isRew var task = Task.Run(() => { - Debug.WriteLine("fileStream locked"); Task.Delay(lockFileFor).Wait(); fileStream.Dispose(); Debug.WriteLine("fileStream unlocked"); - }); Debug.WriteLine("Rewrite process attempts started"); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs index 077f193a47a..14c88f5518f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs @@ -1,19 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Tests.Utilities.Mocks; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Core.Providers.Caching { + using System; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Tests.Utilities.Mocks; + using NUnit.Framework; + /// - /// Summary description for DataCacheTests + /// Summary description for DataCacheTests. /// [TestFixture] public class TabCollectionsTest @@ -24,16 +23,15 @@ public void SetUp() ComponentFactory.Container = new SimpleContainer(); MockComponentProvider.CreateDataCacheProvider(); } - - + [Test] public void DNN_13659_WithTabName_NullTabName() { - //Setup + // Setup var tabCollection = new TabCollection(); - tabCollection.Add(new TabInfo {PortalID = 1, TabID = 1}); + tabCollection.Add(new TabInfo { PortalID = 1, TabID = 1 }); - //Act + // Act var tab = tabCollection.WithTabName("TestName"); Assert.IsNull(tab); @@ -42,48 +40,48 @@ public void DNN_13659_WithTabName_NullTabName() [Test] public void WithTabName_Match() { - //Setup + // Setup var tabCollection = new TabCollection(); - tabCollection.Add(new TabInfo {TabName = "TestName1", PortalID = 1, TabID = 1}); - tabCollection.Add(new TabInfo {TabName = "TestName2", PortalID = 1, TabID = 2}); - tabCollection.Add(new TabInfo {TabName = "TestName3", PortalID = 1, TabID = 3}); + tabCollection.Add(new TabInfo { TabName = "TestName1", PortalID = 1, TabID = 1 }); + tabCollection.Add(new TabInfo { TabName = "TestName2", PortalID = 1, TabID = 2 }); + tabCollection.Add(new TabInfo { TabName = "TestName3", PortalID = 1, TabID = 3 }); - //Act + // Act var tab = tabCollection.WithTabName("TestName2"); - //Assert + // Assert Assert.AreEqual("TestName2", tab.TabName); } [Test] public void WithTabName_NoMatch() { - //Setup + // Setup var tabCollection = new TabCollection(); - tabCollection.Add(new TabInfo {TabName = "TestName1", PortalID = 1, TabID = 1}); - tabCollection.Add(new TabInfo {TabName = "TestName2", PortalID = 1, TabID = 2}); - tabCollection.Add(new TabInfo {TabName = "TestName3", PortalID = 1, TabID = 3}); + tabCollection.Add(new TabInfo { TabName = "TestName1", PortalID = 1, TabID = 1 }); + tabCollection.Add(new TabInfo { TabName = "TestName2", PortalID = 1, TabID = 2 }); + tabCollection.Add(new TabInfo { TabName = "TestName3", PortalID = 1, TabID = 3 }); - //Act + // Act var tab = tabCollection.WithTabName("NO_MATCH"); - //Assert + // Assert Assert.IsNull(tab); } [Test] public void WithTabName_Empty() { - //Setup + // Setup var tabCollection = new TabCollection(); - tabCollection.Add(new TabInfo {TabName = "TestName1", PortalID = 1, TabID = 1}); - tabCollection.Add(new TabInfo {TabName = "TestName2", PortalID = 1, TabID = 2}); - tabCollection.Add(new TabInfo {TabName = "TestName3", PortalID = 1, TabID = 3}); + tabCollection.Add(new TabInfo { TabName = "TestName1", PortalID = 1, TabID = 1 }); + tabCollection.Add(new TabInfo { TabName = "TestName2", PortalID = 1, TabID = 2 }); + tabCollection.Add(new TabInfo { TabName = "TestName3", PortalID = 1, TabID = 3 }); - //Act - var tab = tabCollection.WithTabName(String.Empty); + // Act + var tab = tabCollection.WithTabName(string.Empty); - //Assert + // Assert Assert.IsNull(tab); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Core/packages.config index 53b44f9d8fe..97fd3abee1b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/packages.config @@ -1,6 +1,7 @@ - - - - - + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/AssemblyInfo.cs index 61c914d2fe5..0a05a50c8c1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/AssemblyInfo.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Tests.Data")] [assembly: AssemblyDescription("Open Source Web Application Framework")] @@ -16,27 +15,23 @@ [assembly: AssemblyProduct("https://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2018 by DotNetNuke Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DotNetNuke")] - - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM componenets. If you need to access a type in this assembly from + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. 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("64515746-cc3b-4467-b393-55410c33b5a3")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Revision and Build Numbers +// You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: - [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataAssert.cs index b689220cd5c..0944ada730a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataAssert.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using NUnit.Framework; + public class DataAssert { public static void IsFieldValueEqual(T expectedValue, string databaseName, string tableName, string field, string primaryKeyField, int id) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataContextTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataContextTests.cs index ff938378e5b..4654a404a47 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataContextTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataContextTests.cs @@ -1,24 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Configuration; - -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using System.Collections.Generic; + using System.Configuration; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + using PetaPoco; + [TestFixture] public class DataContextTests { // ReSharper disable InconsistentNaming - [SetUp] public void SetUp() { @@ -26,11 +25,11 @@ public void SetUp() ComponentFactory.RegisterComponentInstance(new SqlDataProvider()); ComponentFactory.RegisterComponentSettings(new Dictionary() { - {"name", "SqlDataProvider"}, - {"type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke"}, - {"connectionStringName", "SiteSqlServer"}, - {"objectQualifier", ""}, - {"databaseOwner", "dbo."} + { "name", "SqlDataProvider" }, + { "type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke" }, + { "connectionStringName", "SiteSqlServer" }, + { "objectQualifier", string.Empty }, + { "databaseOwner", "dbo." }, }); } @@ -42,12 +41,12 @@ public void TearDown() [Test] public void DataContext_Instance_Method_Returns_PetaPocoDataContext() { - //Arrange + // Arrange - //Act + // Act var context = DataContext.Instance(); - //Assert + // Assert Assert.IsInstanceOf(context); Assert.IsInstanceOf(context); } @@ -55,13 +54,13 @@ public void DataContext_Instance_Method_Returns_PetaPocoDataContext() [Test] public void DataContext_Instance_Method_Returns_Default_PetaPocoDataContext_Instance() { - //Arrange + // Arrange var connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString; - //Act + // Act var context = (PetaPocoDataContext)DataContext.Instance(); - //Assert + // Assert Database db = Util.GetPrivateMember(context, "_database"); Assert.AreEqual(connectionString, Util.GetPrivateMember(db, "_connectionString")); } @@ -71,13 +70,13 @@ public void DataContext_Instance_Method_Returns_Default_PetaPocoDataContext_Inst [TestCase("Test")] public void DataContext_Instance_Method_Returns_Named_PetaPocoDataContext_Instance(string name) { - //Arrange + // Arrange var connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString; - //Act + // Act var context = (PetaPocoDataContext)DataContext.Instance(name); - //Assert + // Assert Database db = Util.GetPrivateMember(context, "_database"); Assert.AreEqual(connectionString, Util.GetPrivateMember(db, "_connectionString")); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataProviderTests.cs index ae7e36f5de1..80bbcd7e8a0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataProviderTests.cs @@ -1,36 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Tests.Data.Fakes; -using DotNetNuke.Tests.Utilities.Mocks; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using System; + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Tests.Data.Fakes; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class DataProviderTests { [Test] public void DataProvider_Instance_Method_Returns_Instance() { - //Arrange + // Arrange ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDataProvider(new Dictionary())); - //Act + // Act var provider = DataProvider.Instance(); - //Assert + // Assert Assert.IsInstanceOf(provider); Assert.IsInstanceOf(provider); } @@ -38,16 +36,16 @@ public void DataProvider_Instance_Method_Returns_Instance() [Test] public void DataProvider_ConnectionString_Property_Is_Valid() { - //Arrange + // Arrange ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDataProvider(new Dictionary())); var connectionString = Config.GetConnectionString(); - //Act + // Act var provider = DataProvider.Instance(); - //Assert + // Assert Assert.AreEqual(connectionString, provider.ConnectionString); } @@ -56,17 +54,17 @@ public void DataProvider_ConnectionString_Property_Is_Valid() [TestCase("dbo.")] public void DataProvider_DatabaseOwner_Property_Is_Valid(string databaseOwner) { - //Arrange + // Arrange var settings = new Dictionary(); settings["databaseOwner"] = databaseOwner; ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDataProvider(settings)); - //Act + // Act var provider = DataProvider.Instance(); - //Assert + // Assert Assert.AreEqual(databaseOwner, provider.DatabaseOwner); } @@ -75,17 +73,17 @@ public void DataProvider_DatabaseOwner_Property_Is_Valid(string databaseOwner) [TestCase("dnn_")] public void DataProvider_ObjectQualifier_Property_Is_Valid(string objectQualifier) { - //Arrange + // Arrange var settings = new Dictionary(); settings["objectQualifier"] = objectQualifier; ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDataProvider(settings)); - //Act + // Act var provider = DataProvider.Instance(); - //Assert + // Assert Assert.AreEqual(objectQualifier, provider.ObjectQualifier); } @@ -94,17 +92,17 @@ public void DataProvider_ObjectQualifier_Property_Is_Valid(string objectQualifie [TestCase("FakeDataProvider")] public void DataProvider_ProviderName_Property_Is_Valid(string providerName) { - //Arrange + // Arrange var settings = new Dictionary(); settings["providerName"] = providerName; ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDataProvider(settings)); - //Act + // Act var provider = DataProvider.Instance(); - //Assert + // Assert Assert.AreEqual(providerName, provider.ProviderName); } @@ -113,19 +111,18 @@ public void DataProvider_ProviderName_Property_Is_Valid(string providerName) [TestCase("someOtherPath")] public void DataProvider_ProviderPath_Property_Is_Valid(string providerPath) { - //Arrange + // Arrange var settings = new Dictionary(); settings["providerPath"] = providerPath; ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDataProvider(settings)); - //Act + // Act var provider = DataProvider.Instance(); - //Assert + // Assert Assert.AreEqual(providerPath, provider.ProviderPath); } - } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs index 73c9d0d7581..c7a0f97ae21 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs @@ -1,21 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.Data.SqlServerCe; -using System.IO; -using System.Text.RegularExpressions; -using DotNetNuke.Data; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using System; + using System.Data; + using System.Data.SqlServerCe; + using System.IO; + using System.Text.RegularExpressions; + + using DotNetNuke.Data; + using DotNetNuke.Tests.Utilities; + public class DataUtil - { - #region Public Methods - + { public static void CreateDatabase(string databaseName) { if (File.Exists(databaseName)) @@ -48,32 +47,32 @@ public static int ExecuteScalar(string databaseName, string sqlScript) public static string GetConnectionString(string databaseName) { - return String.Format("Data Source = {0};", databaseName); + return string.Format("Data Source = {0};", databaseName); } public static T GetFieldValue(string databaseName, string tableName, string field, string primaryKeyField, string primaryKeyValue) { - return ExecuteQuery(databaseName, String.Format(DataResources.GetFieldValue, field, tableName, primaryKeyField, primaryKeyValue), (cmd) => (T)cmd.ExecuteScalar()); + return ExecuteQuery(databaseName, string.Format(DataResources.GetFieldValue, field, tableName, primaryKeyField, primaryKeyValue), (cmd) => (T)cmd.ExecuteScalar()); } public static int GetLastAddedRecordID(string databaseName, string tableName, string primaryKeyField) { - return ExecuteScalar(databaseName, String.Format(DataResources.GetLastAddedRecordID, tableName, primaryKeyField)); + return ExecuteScalar(databaseName, string.Format(DataResources.GetLastAddedRecordID, tableName, primaryKeyField)); } public static int GetRecordCount(string databaseName, string tableName) { - return ExecuteScalar(databaseName, String.Format(DataResources.RecordCountScript, tableName)); + return ExecuteScalar(databaseName, string.Format(DataResources.RecordCountScript, tableName)); } public static int GetRecordCount(string databaseName, string tableName, string field, string value) { - return ExecuteScalar(databaseName, String.Format(DataResources.GetRecordCountByField, tableName, field, value)); + return ExecuteScalar(databaseName, string.Format(DataResources.GetRecordCountByField, tableName, field, value)); } public static DataTable GetTable(string databaseName, string tableName) { - return ExecuteQuery(databaseName, String.Format(DataResources.GetTable, tableName), + return ExecuteQuery(databaseName, string.Format(DataResources.GetTable, tableName), (cmd) => { var reader = cmd.ExecuteReader(); @@ -97,13 +96,12 @@ public static void SetUpDatabase(int count) { index = 0; } - ExecuteNonQuery(Constants.PETAPOCO_DatabaseName, String.Format(Constants.PETAPOCO_InsertDogRow, _dogNames[index], _dogAges[index])); + + ExecuteNonQuery(Constants.PETAPOCO_DatabaseName, string.Format(Constants.PETAPOCO_InsertDogRow, _dogNames[index], _dogAges[index])); index++; - } - } - - #endregion - + } + } + private static TReturn ExecuteQuery(string databaseName, string sqlScript, Func command) { using (var connection = new SqlCeConnection(GetConnectionString(databaseName))) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/DatabaseConnectionProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/DatabaseConnectionProviderTests.cs index d9d7f57b57c..03d43859e9d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/DatabaseConnectionProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/DatabaseConnectionProviderTests.cs @@ -1,29 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Tests.Data.Fakes; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Tests.Data.Fakes; + using NUnit.Framework; + [TestFixture] public class DatabaseConnectionProviderTests { [Test] public void DatabaseConnectionProvider_Instance_Method_Returns_Instance() { - //Arrange + // Arrange ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDbConnectionProvider()); - //Act + // Act var provider = DatabaseConnectionProvider.Instance(); - //Assert + // Assert Assert.IsInstanceOf(provider); Assert.IsInstanceOf(provider); } @@ -31,15 +30,15 @@ public void DatabaseConnectionProvider_Instance_Method_Returns_Instance() [Test] public void DatabaseConnectionProvider_Instance_Method_Returns_Same_Instances() { - //Arrange + // Arrange ComponentFactory.Container = new SimpleContainer(); ComponentFactory.RegisterComponentInstance(new FakeDbConnectionProvider()); - //Act + // Act var provider1 = DatabaseConnectionProvider.Instance(); var provider2 = DatabaseConnectionProvider.Instance(); - //Assert + // Assert Assert.IsInstanceOf(provider1); Assert.IsInstanceOf(provider2); Assert.AreSame(provider1, provider2); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/DotNetNuke.Tests.Data.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Data/DotNetNuke.Tests.Data.csproj index f70da21bf13..c1d181cbde1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/DotNetNuke.Tests.Data.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/DotNetNuke.Tests.Data.csproj @@ -1,170 +1,177 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {2595AADE-D3E0-4205-B8AF-109CB23F4223} - Library - Properties - DotNetNuke.Tests.Data - DotNetNuke.Tests.Data - v4.7.2 - 512 - {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - ..\..\..\..\Evoq.Content\ - true - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - - ..\..\..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll - True - - - ..\..\Components\DataAccessBlock\bin\Microsoft.ApplicationBlocks.Data.dll - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - ..\..\Library\bin\PetaPoco.dll - - - - - - - ..\..\..\packages\Microsoft.SqlServer.Compact.4.0.8876.1\lib\net40\System.Data.SqlServerCe.dll - - - - - - - - - - - - - - DataResources.resx - True - True - - - - - - - - - - - - - ResXFileCodeGenerator - DataResources.Designer.cs - Designer - - - - - {ddf18e36-41a0-4ca7-a098-78ca6e6f41c1} - DotNetNuke.Instrumentation - - - {04f77171-0634-46e0-a95e-d7477c88712e} - DotNetNuke.Log4Net - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {68368906-57dd-40d1-ac10-35211a17d617} - DotNetNuke.Tests.Utilities - - - - - - - - App.config - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {2595AADE-D3E0-4205-B8AF-109CB23F4223} + Library + Properties + DotNetNuke.Tests.Data + DotNetNuke.Tests.Data + v4.7.2 + 512 + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + ..\..\..\..\Evoq.Content\ + true + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + + ..\..\..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll + True + + + ..\..\Components\DataAccessBlock\bin\Microsoft.ApplicationBlocks.Data.dll + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + ..\..\Library\bin\PetaPoco.dll + + + + + + + ..\..\..\packages\Microsoft.SqlServer.Compact.4.0.8876.1\lib\net40\System.Data.SqlServerCe.dll + + + + + + + + + + + + + + DataResources.resx + True + True + + + + + + + + + + + + + ResXFileCodeGenerator + DataResources.Designer.cs + Designer + + + + + {ddf18e36-41a0-4ca7-a098-78ca6e6f41c1} + DotNetNuke.Instrumentation + + + {04f77171-0634-46e0-a95e-d7477c88712e} + DotNetNuke.Log4Net + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {68368906-57dd-40d1-ac10-35211a17d617} + DotNetNuke.Tests.Utilities + + + + + + + + stylecop.json + + + App.config + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + if not exist "$(TargetDir)x86" md "$(TargetDir)x86" xcopy /s /y "$(SolutionDir)packages\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\x86\*.*" "$(TargetDir)x86" if not exist "$(TargetDir)amd64" md "$(TargetDir)amd64" - xcopy /s /y "$(SolutionDir)packages\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\amd64\*.*" "$(TargetDir)amd64" - + xcopy /s /y "$(SolutionDir)packages\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\amd64\*.*" "$(TargetDir)amd64" + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs index 671ee0c7c97..4d7bbbeb947 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs @@ -1,23 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Fakes { + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Data; + internal class FakeDataProvider : DataProvider { - public FakeDataProvider(Dictionary settings ) + public FakeDataProvider(Dictionary settings) { - Settings = settings; - } - - #region Overrides of DataProvider - + this.Settings = settings; + } + public override bool IsConnectionValid { get { throw new System.NotImplementedException(); } @@ -124,8 +122,6 @@ public override IDataReader ExecuteSQLTemp(string connectionString, string sql, public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage) { throw new System.NotImplementedException(); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDbConnectionProvider.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDbConnectionProvider.cs index 39e573c00fa..b79d457c268 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDbConnectionProvider.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDbConnectionProvider.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Data; -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Fakes { + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Data; + internal class FakeDbConnectionProvider : DatabaseConnectionProvider { public override int ExecuteNonQuery(string connectionString, CommandType commandType, int commandTimeout, string query) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeRepository.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeRepository.cs index 77f51a0aa06..f0ad09299b5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeRepository.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeRepository.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - -using DotNetNuke.Collections; -using DotNetNuke.Data; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Fakes { - public class FakeRepository : RepositoryBase where T : class + using System.Collections.Generic; + + using DotNetNuke.Collections; + using DotNetNuke.Data; + + public class FakeRepository : RepositoryBase + where T : class { public override void Delete(string sqlCondition, params object[] args) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs index a46e73a5a0b..f52a908e91f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs @@ -1,19 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Models { + using System; + + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Tests.Utilities; + [Cacheable(Constants.CACHE_CatsKey, Constants.CACHE_Priority, Constants.CACHE_TimeOut)] [Scope(Constants.CACHE_ScopeModule)] public class CacheableCat { public int? Age { get; set; } + public int ModuleId { get; set; } + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs index 23267ccb506..cc2a7cc398e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs @@ -1,18 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Models { + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Tests.Utilities; + [Cacheable(Constants.CACHE_DogsKey, Constants.CACHE_Priority, Constants.CACHE_TimeOut)] [Scope(Constants.CACHE_ScopeAll)] public class CacheableDog { public int? Age { get; set; } + public int ID { get; set; } + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs index 8f2a92864be..b1c2704c47f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs @@ -1,18 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Models { + using System; + + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Tests.Utilities; + [Scope(Constants.CACHE_ScopeModule)] public class Cat { public int? Age { get; set; } + public int ModuleId { get; set; } + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs index b1abf79fecc..bd8a7e94858 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs @@ -1,13 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Models { public class Dog { public int? Age { get; set; } + public int ID { get; set; } + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs index 28d71fd00bb..6bf7e04588d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.ComponentModel.DataAnnotations; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data.Models { + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Tests.Utilities; + [PrimaryKey(Constants.TABLENAME_Person_Key)] [TableName(Constants.TABLENAME_Person)] public class Person { public int? Age { get; set; } + public int ID { get; set; } [ColumnName(Constants.COLUMNNAME_PersonName)] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs index 941c6db4601..781972ca453 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs @@ -1,47 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Caching; -using DotNetNuke.Collections; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Services.Cache; -using DotNetNuke.Tests.Data.Fakes; -using DotNetNuke.Tests.Data.Models; -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; -using Moq.Protected; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using System; + using System.Collections.Generic; + using System.Web.Caching; + + using DotNetNuke.Collections; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Services.Cache; + using DotNetNuke.Tests.Data.Fakes; + using DotNetNuke.Tests.Data.Models; + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using Moq.Protected; + using NUnit.Framework; + [TestFixture] public class RepositoryBaseTests { // ReSharper disable InconsistentNaming - [SetUp] public void SetUp() { MockComponentProvider.ResetContainer(); - } - - #region Constructor Tests - + } + [Test] public void RepositoryBase_Constructor_Sets_CacheArgs_Null_If_Not_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsNull(Util.GetPrivateMember, CacheItemArgs>(baseRepo, "CacheArgs")); } @@ -49,12 +47,12 @@ public void RepositoryBase_Constructor_Sets_CacheArgs_Null_If_Not_Cacheable() [Test] public void RepositoryBase_Constructor_Sets_CacheArgs_If_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsNotNull(Util.GetPrivateMember, CacheItemArgs>(baseRepo, "CacheArgs")); } @@ -62,12 +60,12 @@ public void RepositoryBase_Constructor_Sets_CacheArgs_If_Cacheable() [Test] public void RepositoryBase_Constructor_Sets_Valid_CacheArgs_If_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var cacheArgs = Util.GetPrivateMember, CacheItemArgs>(repo, "CacheArgs"); Assert.AreEqual(Constants.CACHE_DogsKey, cacheArgs.CacheKey); Assert.AreEqual(Constants.CACHE_Priority, cacheArgs.CachePriority); @@ -77,12 +75,12 @@ public void RepositoryBase_Constructor_Sets_Valid_CacheArgs_If_Cacheable() [Test] public void RepositoryBase_Constructor_Sets_IsCacheable_False_If_Not_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsFalse(Util.GetPrivateMember, bool>(baseRepo, "IsCacheable")); } @@ -90,12 +88,12 @@ public void RepositoryBase_Constructor_Sets_IsCacheable_False_If_Not_Cacheable() [Test] public void RepositoryBase_Constructor_Sets_IsCacheable_True_If_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsTrue(Util.GetPrivateMember, bool>(baseRepo, "IsCacheable")); } @@ -103,12 +101,12 @@ public void RepositoryBase_Constructor_Sets_IsCacheable_True_If_Cacheable() [Test] public void RepositoryBase_Constructor_Sets_IsScoped_False_If_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsFalse(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } @@ -116,12 +114,12 @@ public void RepositoryBase_Constructor_Sets_IsScoped_False_If_Not_Scoped() [Test] public void RepositoryBase_Constructor_Sets_IsScoped_False_If_Cacheable_And_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsFalse(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } @@ -129,25 +127,25 @@ public void RepositoryBase_Constructor_Sets_IsScoped_False_If_Cacheable_And_Not_ [Test] public void RepositoryBase_Constructor_Sets_IsScoped_True_If_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsTrue(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } - + [Test] public void RepositoryBase_Constructor_Sets_IsScoped_True_If_Cacheable_And_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsTrue(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } @@ -155,38 +153,38 @@ public void RepositoryBase_Constructor_Sets_IsScoped_True_If_Cacheable_And_Scope [Test] public void RepositoryBase_Constructor_Sets_Scope_Empty_If_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; - Assert.AreEqual(String.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); + Assert.AreEqual(string.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); } [Test] public void RepositoryBase_Constructor_Sets_Scope_Empty_If_Cacheable_And_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; - Assert.AreEqual(String.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); + Assert.AreEqual(string.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); } [Test] public void RepositoryBase_Constructor_Sets_Scope_If_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.AreEqual(Constants.CACHE_ScopeModule, Util.GetPrivateMember, string>(baseRepo, "Scope")); } @@ -194,30 +192,26 @@ public void RepositoryBase_Constructor_Sets_Scope_If_Scoped() [Test] public void RepositoryBase_Constructor_Sets_Scope_If_Cacheable_And_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.AreEqual(Constants.CACHE_ScopeModule, Util.GetPrivateMember, string>(baseRepo, "Scope")); - } - - #endregion - - #region Initialize Tests - + } + [Test] public void RepositoryBase_Initialize_Sets_CacheArgs_Null_If_Not_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - repo.Initialize(String.Empty); + repo.Initialize(string.Empty); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsNull(Util.GetPrivateMember, CacheItemArgs>(baseRepo, "CacheArgs")); } @@ -225,13 +219,13 @@ public void RepositoryBase_Initialize_Sets_CacheArgs_Null_If_Not_Cacheable() [Test] public void RepositoryBase_Initialize_Sets_CacheArgs_If_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); repo.Initialize(Constants.CACHE_DogsKey); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsNotNull(Util.GetPrivateMember, CacheItemArgs>(baseRepo, "CacheArgs")); } @@ -239,13 +233,13 @@ public void RepositoryBase_Initialize_Sets_CacheArgs_If_Cacheable() [Test] public void RepositoryBase_Initialize_Sets_Valid_CacheArgs_If_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); repo.Initialize(Constants.CACHE_DogsKey, Constants.CACHE_TimeOut, Constants.CACHE_Priority); - //Assert + // Assert var cacheArgs = Util.GetPrivateMember, CacheItemArgs>(repo, "CacheArgs"); Assert.AreEqual(Constants.CACHE_DogsKey, cacheArgs.CacheKey); Assert.AreEqual(Constants.CACHE_Priority, cacheArgs.CachePriority); @@ -255,12 +249,12 @@ public void RepositoryBase_Initialize_Sets_Valid_CacheArgs_If_Cacheable() [Test] public void RepositoryBase_Initialize_Sets_IsCacheable_False_If_Not_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsFalse(Util.GetPrivateMember, bool>(baseRepo, "IsCacheable")); } @@ -268,13 +262,13 @@ public void RepositoryBase_Initialize_Sets_IsCacheable_False_If_Not_Cacheable() [Test] public void RepositoryBase_Initialize_Sets_IsCacheable_True_If_Cacheable() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); repo.Initialize(Constants.CACHE_DogsKey); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsTrue(Util.GetPrivateMember, bool>(baseRepo, "IsCacheable")); } @@ -282,13 +276,13 @@ public void RepositoryBase_Initialize_Sets_IsCacheable_True_If_Cacheable() [Test] public void RepositoryBase_Initialize_Sets_IsScoped_False_If_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - repo.Initialize(String.Empty); + repo.Initialize(string.Empty); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsFalse(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } @@ -296,13 +290,13 @@ public void RepositoryBase_Initialize_Sets_IsScoped_False_If_Not_Scoped() [Test] public void RepositoryBase_Initialize_Sets_IsScoped_False_If_Cacheable_And_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); repo.Initialize(Constants.CACHE_DogsKey, Constants.CACHE_TimeOut, Constants.CACHE_Priority); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsFalse(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } @@ -310,13 +304,13 @@ public void RepositoryBase_Initialize_Sets_IsScoped_False_If_Cacheable_And_Not_S [Test] public void RepositoryBase_Initialize_Sets_IsScoped_True_If_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - repo.Initialize(String.Empty, 20, CacheItemPriority.Default, Constants.CACHE_ScopeModule); + repo.Initialize(string.Empty, 20, CacheItemPriority.Default, Constants.CACHE_ScopeModule); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsTrue(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } @@ -324,13 +318,13 @@ public void RepositoryBase_Initialize_Sets_IsScoped_True_If_Scoped() [Test] public void RepositoryBase_Initialize_Sets_IsScoped_True_If_Cacheable_And_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); repo.Initialize(Constants.CACHE_CatsKey, Constants.CACHE_TimeOut, Constants.CACHE_Priority, Constants.CACHE_ScopeModule); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.IsTrue(Util.GetPrivateMember, bool>(baseRepo, "IsScoped")); } @@ -338,41 +332,41 @@ public void RepositoryBase_Initialize_Sets_IsScoped_True_If_Cacheable_And_Scoped [Test] public void RepositoryBase_Initialize_Sets_Scope_Empty_If_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - repo.Initialize(String.Empty); + repo.Initialize(string.Empty); - //Assert + // Assert var baseRepo = repo as RepositoryBase; - Assert.AreEqual(String.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); + Assert.AreEqual(string.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); } [Test] public void RepositoryBase_Initialize_Sets_Scope_Empty_If_Cacheable_And_Not_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); repo.Initialize(Constants.CACHE_DogsKey, Constants.CACHE_TimeOut, Constants.CACHE_Priority); - //Assert + // Assert var baseRepo = repo as RepositoryBase; - Assert.AreEqual(String.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); + Assert.AreEqual(string.Empty, Util.GetPrivateMember, string>(baseRepo, "Scope")); } [Test] public void RepositoryBase_Initialize_Sets_Scope_If_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); - repo.Initialize(String.Empty, 20, CacheItemPriority.Default, Constants.CACHE_ScopeModule); + repo.Initialize(string.Empty, 20, CacheItemPriority.Default, Constants.CACHE_ScopeModule); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.AreEqual(Constants.CACHE_ScopeModule, Util.GetPrivateMember, string>(baseRepo, "Scope")); } @@ -380,25 +374,21 @@ public void RepositoryBase_Initialize_Sets_Scope_If_Scoped() [Test] public void RepositoryBase_Initialize_Sets_Scope_If_Cacheable_And_Scoped() { - //Arrange + // Arrange - //Act + // Act var repo = new FakeRepository(); repo.Initialize(Constants.CACHE_CatsKey, Constants.CACHE_TimeOut, Constants.CACHE_Priority, Constants.CACHE_ScopeModule); - //Assert + // Assert var baseRepo = repo as RepositoryBase; Assert.AreEqual(Constants.CACHE_ScopeModule, Util.GetPrivateMember, string>(baseRepo, "Scope")); - } - - #endregion - - #region Delete Tests - + } + [Test] public void RepositoryBase_Delete_Clears_Cache_If_Cacheable() { - //Arrange + // Arrange var cacheKey = CachingProvider.GetCacheKey(Constants.CACHE_DogsKey); var mockCache = MockComponentProvider.CreateDataCacheProvider(); @@ -406,68 +396,64 @@ public void RepositoryBase_Delete_Clears_Cache_If_Cacheable() var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Delete(new CacheableDog()); - //Assert + // Assert mockCache.Verify(c => c.Remove(cacheKey), Times.Once()); } [Test] public void RepositoryBase_Delete_Clears_Cache_If_Cacheable_And_Scoped() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockCache = MockComponentProvider.CreateDataCacheProvider(); mockCache.Setup(c => c.GetItem(cacheKey)).Returns(new List()); var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Delete(new CacheableCat { ModuleId = Constants.MODULE_ValidId }); - //Assert + // Assert mockCache.Verify(c => c.Remove(cacheKey), Times.Once()); } [Test] public void RepositoryBase_Delete_Does_Not_Clear_Cache_If_Not_Cacheable() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Delete(new Dog()); - //Assert + // Assert mockCache.Verify(c => c.Remove(It.IsAny()), Times.Never()); } [Test] public void RepositoryBase_Delete_Calls_DeleteInternal() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup("DeleteInternal", ItExpr.IsAny()); - //Act + // Act mockRepository.Object.Delete(new Dog()); - //Assert + // Assert mockRepository.Protected().Verify("DeleteInternal", Times.Once(), ItExpr.IsAny()); - } - - #endregion - - #region Get Tests - + } + [Test] public void RepositoryBase_Get_Checks_Cache_If_Cacheable() { - //Arrange + // Arrange var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -476,47 +462,47 @@ public void RepositoryBase_Get_Checks_Cache_If_Cacheable() var mockRepository = new Mock>(); - //Act + // Act var list = mockRepository.Object.Get(); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey))); } [Test] public void RepositoryBase_Get_Does_Not_Check_Cache_If_Not_Cacheable() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act var list = mockRepository.Object.Get(); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never()); } [Test] public void RepositoryBase_Get_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act var list = mockRepository.Object.Get(); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_CatsKey)), Times.Never()); } [Test] public void RepositoryBase_Get_Calls_GetAllInternal_If_Cacheable_And_Cache_Expired() { - //Arrange + // Arrange var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -526,45 +512,45 @@ public void RepositoryBase_Get_Calls_GetAllInternal_If_Cacheable_And_Cache_Expir var mockRepository = new Mock>(); mockRepository.Protected().Setup("GetInternal"); - //Act + // Act var list = mockRepository.Object.Get(); - //Assert + // Assert mockRepository.Protected().Verify("GetInternal", Times.Once()); } [Test] public void RepositoryBase_Get_Calls_GetAllInternal_If_Not_Cacheable() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup("GetInternal"); - //Act + // Act var list = mockRepository.Object.Get(); - //Assert + // Assert mockRepository.Protected().Verify("GetInternal", Times.Once()); } [Test] public void RepositoryBase_Get_Calls_GetAllInternal_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup("GetInternal"); - //Act + // Act var list = mockRepository.Object.Get(); - //Assert + // Assert mockRepository.Protected().Verify("GetInternal", Times.Once()); } [Test] public void RepositoryBase_Get_Does_Not_Call_GetAllInternal_If_Cacheable_And_Cache_Valid() { - //Arrange + // Arrange var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -574,22 +560,18 @@ public void RepositoryBase_Get_Does_Not_Call_GetAllInternal_If_Cacheable_And_Cac var mockRepository = new Mock>(); mockRepository.Protected().Setup("GetInternal"); - //Act + // Act var list = mockRepository.Object.Get(); - //Assert + // Assert mockRepository.Protected().Verify("GetInternal", Times.Never()); - } - - #endregion - - #region Get Tests - + } + [Test] public void RepositoryBase_Get_Overload_Checks_Cache_If_Cacheable_And_Scoped() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -599,66 +581,66 @@ public void RepositoryBase_Get_Overload_Checks_Cache_If_Cacheable_And_Scoped() var mockRepository = new Mock>(); - //Act + // Act var list = mockRepository.Object.Get(Constants.MODULE_ValidId); - //Assert + // Assert mockCache.Verify(c => c.GetItem(cacheKey)); } [Test] public void RepositoryBase_Get_Overload_Throws_If_Not_Cacheable() { - //Arrange + // Arrange var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.Get(Constants.MODULE_ValidId)); } [Test] public void RepositoryBase_Get_Overload_Throws_If_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.Get(Constants.MODULE_ValidId)); } [Test] public void RepositoryBase_Get_Overload_Throws_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.Get(Constants.MODULE_ValidId)); } [Test] public void RepositoryBase_Get_Overload_Calls_GetAllByScopeInternal_If_Not_Cacheable_And_Is_Scoped() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetByScopeInternal", ItExpr.IsAny()); - //Act + // Act var list = mockRepository.Object.Get(Constants.MODULE_ValidId); - //Assert + // Assert mockRepository.Protected().Verify>("GetByScopeInternal", Times.Once(), ItExpr.IsAny()); } [Test] public void RepositoryBase_Get_Overload_Calls_GetAllByScopeInternal_If_Cacheable_And_Cache_Expired() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -669,18 +651,18 @@ public void RepositoryBase_Get_Overload_Calls_GetAllByScopeInternal_If_Cacheable var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetByScopeInternal", ItExpr.IsAny()); - //Act + // Act var list = mockRepository.Object.Get(Constants.MODULE_ValidId); - //Assert + // Assert mockRepository.Protected().Verify>("GetByScopeInternal", Times.Once(), ItExpr.IsAny()); } [Test] public void RepositoryBase_Get_Overload_Does_Not_Call_GetAllByScopeInternal_If_Cacheable_And_Cache_Valid() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -691,21 +673,17 @@ public void RepositoryBase_Get_Overload_Does_Not_Call_GetAllByScopeInternal_If_C var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetByScopeInternal", ItExpr.IsAny()); - //Act + // Act var list = mockRepository.Object.Get(Constants.MODULE_ValidId); - //Assert + // Assert mockRepository.Protected().Verify>("GetByScopeInternal", Times.Never(), ItExpr.IsAny()); - } - - #endregion - - #region GetById Tests - + } + [Test] public void RepositoryBase_GetById_Checks_Cache_If_Cacheable() { - //Arrange + // Arrange var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -714,75 +692,75 @@ public void RepositoryBase_GetById_Checks_Cache_If_Cacheable() var mockRepository = new Mock>(); - //Act + // Act var dog = mockRepository.Object.GetById(Constants.PETAPOCO_ValidDogId); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey))); } [Test] public void RepositoryBase_GetById_Does_Not_Check_Cache_If_Not_Cacheable() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act var dog = mockRepository.Object.GetById(Constants.PETAPOCO_ValidDogId); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never()); } [Test] public void RepositoryBase_GetById_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act var cat = mockRepository.Object.GetById(Constants.PETAPOCO_ValidCatId); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never()); } [Test] public void RepositoryBase_GetById_Calls_GetByIdInternal_If_Not_Cacheable() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup("GetByIdInternal", ItExpr.IsAny()); - //Act + // Act var dog = mockRepository.Object.GetById(Constants.PETAPOCO_ValidDogId); - //Assert + // Assert mockRepository.Protected().Verify("GetByIdInternal", Times.Once(), ItExpr.IsAny()); } [Test] public void RepositoryBase_GetById_Calls_GetByIdInternal_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup("GetByIdInternal", ItExpr.IsAny()); - //Act + // Act var cat = mockRepository.Object.GetById(Constants.PETAPOCO_ValidCatId); - //Assert + // Assert mockRepository.Protected().Verify("GetByIdInternal", Times.Once(), ItExpr.IsAny()); } [Test] public void RepositoryBase_GetById_Does_Not_Call_GetByIdInternal_If_Cacheable_And_Cache_Valid() { - //Arrange + // Arrange var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -792,22 +770,18 @@ public void RepositoryBase_GetById_Does_Not_Call_GetByIdInternal_If_Cacheable_An var mockRepository = new Mock>(); mockRepository.Protected().Setup("GetByIdInternal", ItExpr.IsAny()); - //Act + // Act var dog = mockRepository.Object.GetById(Constants.PETAPOCO_ValidDogId); - //Assert + // Assert mockRepository.Protected().Verify("GetByIdInternal", Times.Never(), ItExpr.IsAny()); - } - - #endregion - - #region GetById Tests - + } + [Test] public void RepositoryBase_GetById_Overload_Checks_Cache_If_Cacheable_And_Scoped() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -817,43 +791,39 @@ public void RepositoryBase_GetById_Overload_Checks_Cache_If_Cacheable_And_Scoped var mockRepository = new Mock>(); - //Act + // Act var cat = mockRepository.Object.GetById(Constants.PETAPOCO_ValidCatId, Constants.MODULE_ValidId); - //Assert + // Assert mockCache.Verify(c => c.GetItem(cacheKey)); } [Test] public void RepositoryBase_GetById_Overload_Throws_If_Not_Cacheable() { - //Arrange + // Arrange var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.GetById(Constants.PETAPOCO_ValidDogId, Constants.MODULE_ValidId)); } [Test] public void RepositoryBase_GetById_Overload_Throws__If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.GetById(Constants.PETAPOCO_ValidDogId, Constants.MODULE_ValidId)); - } - - #endregion - - #region GetPage Tests - + } + [Test] public void RepositoryBase_GetPage_Checks_Cache_If_Cacheable() { - //Arrange + // Arrange var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -862,75 +832,75 @@ public void RepositoryBase_GetPage_Checks_Cache_If_Cacheable() var mockRepository = new Mock>(); - //Act + // Act var dogs = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey))); } [Test] public void RepositoryBase_GetPage_Does_Not_Check_Cache_If_Not_Cacheable() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act var dogs = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never()); } [Test] public void RepositoryBase_GetPage_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act var cats = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never()); } [Test] public void RepositoryBase_GetPage_Calls_GetAllByPageInternal_If_Not_Cacheable() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetPageInternal", ItExpr.IsAny(), ItExpr.IsAny()); - //Act + // Act var dogs = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockRepository.Protected().Verify>("GetPageInternal", Times.Once(), ItExpr.IsAny(), ItExpr.IsAny()); } [Test] public void RepositoryBase_GetPage_Calls_GetAllByPageInternal_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetPageInternal", ItExpr.IsAny(), ItExpr.IsAny()); - //Act + // Act var cats = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockRepository.Protected().Verify>("GetPageInternal", Times.Once(), ItExpr.IsAny(), ItExpr.IsAny()); } [Test] public void RepositoryBase_GetPage_Does_Not_Call_GetAllByPageInternal_If_Cacheable_And_Cache_Valid() { - //Arrange + // Arrange var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -941,22 +911,18 @@ public void RepositoryBase_GetPage_Does_Not_Call_GetAllByPageInternal_If_Cacheab var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetPageInternal", ItExpr.IsAny(), ItExpr.IsAny()); - //Act + // Act var dogs = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockRepository.Protected().Verify>("GetPageInternal", Times.Never(), ItExpr.IsAny(), ItExpr.IsAny()); - } - - #endregion - - #region GetPage Tests - + } + [Test] public void RepositoryBase_GetPage_Overload_Checks_Cache_If_Cacheable_And_Scoped() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -966,66 +932,66 @@ public void RepositoryBase_GetPage_Overload_Checks_Cache_If_Cacheable_And_Scoped var mockRepository = new Mock>(); - //Act + // Act var cats = mockRepository.Object.GetPage(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockCache.Verify(c => c.GetItem(cacheKey)); } [Test] public void RepositoryBase_GetPage_Overload_Throws_If_Not_Cacheable() { - //Arrange + // Arrange var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.GetPage(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount)); } [Test] public void RepositoryBase_GetPage_Overload_Throws_If_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.GetPage(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount)); } [Test] public void RepositoryBase_GetPage_Overload_Throws_If_Cacheable_But_Not_Scoped() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act, Assert + // Act, Assert Assert.Throws(() => mockRepository.Object.GetPage(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount)); } [Test] public void RepositoryBase_GetPage_Overload_Calls_GetAllByScopeAndPageInternal_If_Not_Cacheable_And_Is_Scoped() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetPageByScopeInternal", ItExpr.IsAny(), ItExpr.IsAny(), ItExpr.IsAny()); - //Act + // Act var cats = mockRepository.Object.GetPage(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockRepository.Protected().Verify>("GetPageByScopeInternal", Times.Once(), ItExpr.IsAny(), ItExpr.IsAny(), ItExpr.IsAny()); } [Test] public void RepositoryBase_GetPage_Overload_Calls_GetAllByScopeInternal_If_Cacheable_And_Cache_Expired() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("0"); @@ -1038,20 +1004,20 @@ public void RepositoryBase_GetPage_Overload_Calls_GetAllByScopeInternal_If_Cache .Returns(new List()); var mockData = MockComponentProvider.CreateDataProvider(); - mockData.Setup(d => d.GetProviderPath()).Returns(String.Empty); + mockData.Setup(d => d.GetProviderPath()).Returns(string.Empty); - //Act + // Act var cats = mockRepository.Object.GetPage(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockRepository.Protected().Verify>("GetByScopeInternal", Times.Once(), ItExpr.IsAny()); } [Test] public void RepositoryBase_GetPage_Overload_Does_Not_Call_GetAllByScopeInternal_If_Cacheable_And_Cache_Valid() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockHostController = MockComponentProvider.CreateNew(); mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3"); @@ -1062,21 +1028,17 @@ public void RepositoryBase_GetPage_Overload_Does_Not_Call_GetAllByScopeInternal_ var mockRepository = new Mock>(); mockRepository.Protected().Setup>("GetByScopeInternal", ItExpr.IsAny()); - //Act + // Act var cats = mockRepository.Object.GetPage(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert mockRepository.Protected().Verify>("GetByScopeInternal", Times.Never(), ItExpr.IsAny()); - } - - #endregion - - #region Insert Tests - + } + [Test] public void RepositoryBase_Insert_Clears_Cache_If_Cacheable() { - //Arrange + // Arrange var cacheKey = CachingProvider.GetCacheKey(Constants.CACHE_DogsKey); var mockCache = MockComponentProvider.CreateDataCacheProvider(); @@ -1084,68 +1046,64 @@ public void RepositoryBase_Insert_Clears_Cache_If_Cacheable() var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Insert(new CacheableDog()); - //Assert + // Assert mockCache.Verify(c => c.Remove(cacheKey), Times.Once()); } [Test] public void RepositoryBase_Insert_Clears_Cache_If_Cacheable_And_Scoped() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockCache = MockComponentProvider.CreateDataCacheProvider(); mockCache.Setup(c => c.GetItem(cacheKey)).Returns(new List()); var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Insert(new CacheableCat { ModuleId = Constants.MODULE_ValidId }); - //Assert + // Assert mockCache.Verify(c => c.Remove(cacheKey), Times.Once()); } [Test] public void RepositoryBase_Insert_Does_Not_Clear_Cache_If_Not_Cacheable() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Insert(new Dog()); - //Assert + // Assert mockCache.Verify(c => c.Remove(It.IsAny()), Times.Never()); } [Test] public void RepositoryBase_Insert_Calls_InsertInternal() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup("InsertInternal", ItExpr.IsAny()); - //Act + // Act mockRepository.Object.Insert(new Dog()); - //Assert + // Assert mockRepository.Protected().Verify("InsertInternal", Times.Once(), ItExpr.IsAny()); - } - - #endregion - - #region Update Tests - + } + [Test] public void RepositoryBase_Update_Clears_Cache_If_Cacheable() { - //Arrange + // Arrange var cacheKey = CachingProvider.GetCacheKey(Constants.CACHE_DogsKey); var mockCache = MockComponentProvider.CreateDataCacheProvider(); @@ -1153,62 +1111,60 @@ public void RepositoryBase_Update_Clears_Cache_If_Cacheable() var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Update(new CacheableDog()); - //Assert + // Assert mockCache.Verify(c => c.Remove(cacheKey), Times.Once()); } [Test] public void RepositoryBase_Update_Clears_Cache_If_Cacheable_And_Scoped() { - //Arrange - var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); + // Arrange + var cacheKey = CachingProvider.GetCacheKey(string.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId)); var mockCache = MockComponentProvider.CreateDataCacheProvider(); mockCache.Setup(c => c.GetItem(cacheKey)).Returns(new List()); var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Update(new CacheableCat { ModuleId = Constants.MODULE_ValidId }); - //Assert + // Assert mockCache.Verify(c => c.Remove(cacheKey), Times.Once()); } [Test] public void RepositoryBase_Update_Does_Not_Clear_Cache_If_Not_Cacheable() { - //Arrange + // Arrange var mockCache = MockComponentProvider.CreateDataCacheProvider(); var mockRepository = new Mock>(); - //Act + // Act mockRepository.Object.Update(new Dog()); - //Assert + // Assert mockCache.Verify(c => c.Remove(It.IsAny()), Times.Never()); } [Test] public void RepositoryBase_Update_Calls_UpdateInternal() { - //Arrange + // Arrange var mockRepository = new Mock>(); mockRepository.Protected().Setup("UpdateInternal", ItExpr.IsAny()); - //Act + // Act mockRepository.Object.Update(new Dog()); - //Assert + // Assert mockRepository.Protected().Verify("UpdateInternal", Times.Once(), ItExpr.IsAny()); - } - #endregion - - // ReSharper restore InconsistentNaming - + } + + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Data/packages.config index a66673d77cd..f49a8207a2a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/packages.config @@ -1,8 +1,9 @@ - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/FluentMapperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/FluentMapperTests.cs index abfef104797..471178d1900 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/FluentMapperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/FluentMapperTests.cs @@ -1,84 +1,84 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Tests.Data.Models; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using System; + + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Tests.Data.Models; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + using PetaPoco; + [TestFixture] public class FluentMapperTests { - [Test] public void FluentMapper_Constructor_Initialises_TablePrefix_Property() { - //Arrange + // Arrange - //Act + // Act var mapper = new FluentMapper(Constants.TABLENAME_Prefix); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Prefix, Util.GetPrivateMember, string>(mapper, "_tablePrefix")); } [Test] public void FluentMapper_GetTableInfo_Returns_TableInfo() { - //Arrange + // Arrange var mapper = new FluentMapper(Constants.TABLENAME_Prefix); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.IsInstanceOf(ti); } [Test] public void FluentMapper_Maps_TableName_To_Value_Provided() { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.TABLENAME_Dog); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Dog, ti.TableName); } [Test] public void FluentMapper_Adds_TablePrefix_To_Value_Provided() { - //Arrange + // Arrange var mapper = new FluentMapper(Constants.TABLENAME_Prefix); mapper.TableName(Constants.TABLENAME_Dog); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Prefix + Constants.TABLENAME_Dog, ti.TableName); } [Test] public void FluentMapper_Does_Not_Map_TableName_To_Attribute() { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.TABLENAME_Dog); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.AreNotEqual(Constants.TABLENAME_Person, ti.TableName); Assert.AreEqual(Constants.TABLENAME_Dog, ti.TableName); } @@ -86,67 +86,67 @@ public void FluentMapper_Does_Not_Map_TableName_To_Attribute() [Test] public void FluentMapper_Sets_TableName_To_Null_If_Not_Provided() { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.IsNull(ti.TableName); } [Test] public void FluentMapper_Sets_PrimaryKey_To_Provided_Value() { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); mapper.PrimaryKey(Constants.TABLENAME_Key); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Key, ti.PrimaryKey); } [Test] public void FluentMapper_Does_Not_Set_PrimaryKey_To_Attribute() { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); mapper.PrimaryKey(Constants.TABLENAME_Key); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.AreNotEqual(Constants.TABLENAME_Person_Key, ti.PrimaryKey); } [Test] public void FluentMapper_Sets_PrimaryKey_To_Null_If_Not_Provided() { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.IsNull(ti.PrimaryKey); } [Test] public void FluentMapper_Sets_AutoIncrement_To_False() { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.IsFalse(ti.AutoIncrement); } @@ -154,81 +154,81 @@ public void FluentMapper_Sets_AutoIncrement_To_False() [TestCase(false)] public void FluentMapper_Sets_AutoIncrement_To_Value_Provided(bool autoIncrement) { - //Arrange - var mapper = new FluentMapper(String.Empty); + // Arrange + var mapper = new FluentMapper(string.Empty); mapper.PrimaryKey("ID", autoIncrement); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.AreEqual(autoIncrement, ti.AutoIncrement); } [Test] public void FluentMapper_GetColumnInfo_Returns_Null_If_Not_Provided() { - //Arrange + // Arrange var mapper = new FluentMapper(Constants.TABLENAME_Prefix); var dogType = typeof(Dog); var dogProperty = dogType.GetProperty(Constants.COLUMNNAME_Name); - //Act + // Act var ci = mapper.GetColumnInfo(dogProperty); - //Assert + // Assert Assert.IsNull(ci); } [Test] public void FluentMapper_GetColumnInfo_Returns_ColumnInfo() { - //Arrange + // Arrange var mapper = new FluentMapper(Constants.TABLENAME_Prefix); mapper.Property(d => d.Name, Constants.COLUMNNAME_Name); var dogType = typeof(Dog); var dogProperty = dogType.GetProperty(Constants.COLUMNNAME_Name); - //Act + // Act var ci = mapper.GetColumnInfo(dogProperty); - //Assert + // Assert Assert.IsInstanceOf(ci); } [Test] public void FluentMapper_GetColumnInfo_Maps_ColumnName_To_Value_Provided() { - //Arrange + // Arrange var mapper = new FluentMapper(Constants.TABLENAME_Prefix); mapper.Property(d => d.Name, Constants.COLUMNNAME_Name); var personType = typeof(Dog); var personProperty = personType.GetProperty(Constants.COLUMNNAME_Name); - //Act + // Act var ci = mapper.GetColumnInfo(personProperty); - //Assert + // Assert Assert.AreEqual(Constants.COLUMNNAME_Name, ci.ColumnName); } [Test] public void FluentMapper_GetColumnInfo_Does_Not_Map_ColumnName_To_Attribute() { - //Arrange + // Arrange var mapper = new FluentMapper(Constants.TABLENAME_Prefix); mapper.Property(d => d.Name, Constants.COLUMNNAME_Name); var personType = typeof(Person); var personProperty = personType.GetProperty(Constants.COLUMNNAME_Name); - //Act + // Act var ci = mapper.GetColumnInfo(personProperty); - //Assert + // Assert Assert.AreNotEqual(Constants.COLUMNNAME_PersonName, ci.ColumnName); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs index 0b287244a59..1c5a635c4fa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs @@ -1,30 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Configuration; -using DotNetNuke.Data; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Tests.Data.Models; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; - -using PetaPoco; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Data { + using System; + using System.Collections.Generic; + using System.Configuration; + + using DotNetNuke.Data; + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Tests.Data.Models; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + using PetaPoco; + [TestFixture] public class PetaPocoDataContextTests - { - // ReSharper disable InconsistentNaming - #region Setup/Teardown - + { + private const string connectionStringName = "PetaPoco"; + private const string tablePrefix = "dnn_"; + + // ReSharper disable InconsistentNaming [SetUp] public void SetUp() { @@ -33,21 +29,14 @@ public void SetUp() [TearDown] public void TearDown() { - } - - #endregion - - private const string connectionStringName = "PetaPoco"; - private const string tablePrefix = "dnn_"; - - #region Constructor Tests - + } + [Test] public void PetaPocoDataContext_Constructors_Throw_On_Null_ConnectionString() { - //Arrange + // Arrange - //Act, Assert + // Act, Assert Assert.Throws(() => new PetaPocoDataContext(null)); Assert.Throws(() => new PetaPocoDataContext(null, tablePrefix)); } @@ -55,46 +44,46 @@ public void PetaPocoDataContext_Constructors_Throw_On_Null_ConnectionString() [Test] public void PetaPocoDataContext_Constructors_Throw_On_Empty_ConnectionString() { - //Arrange + // Arrange - //Act, Assert - Assert.Throws(() => new PetaPocoDataContext(String.Empty)); - Assert.Throws(() => new PetaPocoDataContext(String.Empty, tablePrefix)); + // Act, Assert + Assert.Throws(() => new PetaPocoDataContext(string.Empty)); + Assert.Throws(() => new PetaPocoDataContext(string.Empty, tablePrefix)); } [Test] public void PetaPocoDataContext_Constructor_Initialises_Database_Property() { - //Arrange + // Arrange - //Act + // Act var context = new PetaPocoDataContext(connectionStringName); - //Assert + // Assert Assert.IsInstanceOf(Util.GetPrivateMember(context, "_database")); } [Test] public void PetaPocoDataContext_Constructor_Initialises_TablePrefix_Property() { - //Arrange + // Arrange - //Act + // Act var context = new PetaPocoDataContext(connectionStringName, tablePrefix); - //Assert + // Assert Assert.AreEqual(tablePrefix, context.TablePrefix); } [Test] public void PetaPocoDataContext_Constructor_Initialises_Mapper_Property() { - //Arrange + // Arrange - //Act + // Act var context = new PetaPocoDataContext(connectionStringName); - //Assert + // Assert Assert.IsInstanceOf(Util.GetPrivateMember(context, "_mapper")); Assert.IsInstanceOf(Util.GetPrivateMember(context, "_mapper")); } @@ -102,137 +91,121 @@ public void PetaPocoDataContext_Constructor_Initialises_Mapper_Property() [Test] public void PetaPocoDataContext_Constructor_Initialises_FluentMappers_Property() { - //Arrange + // Arrange - //Act + // Act var context = new PetaPocoDataContext(connectionStringName); - //Assert + // Assert Assert.IsInstanceOf>(context.FluentMappers); - Assert.AreEqual(0,context.FluentMappers.Count); + Assert.AreEqual(0, context.FluentMappers.Count); } [Test] public void PetaPocoDataContext_Constructor_Initialises_Database_Property_With_Correct_Connection() { - //Arrange + // Arrange - //Act + // Act var context = new PetaPocoDataContext(connectionStringName); - //Assert + // Assert Database db = Util.GetPrivateMember(context, "_database"); string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; Assert.AreEqual(connectionString, Util.GetPrivateMember(db, "_connectionString")); - } - - #endregion - - #region BeginTransaction Tests - + } + [Test] public void PetaPocoDataContext_BeginTransaction_Increases_Database_Transaction_Count() { - //Arrange + // Arrange const int transactionDepth = 1; var context = new PetaPocoDataContext(connectionStringName); Database db = Util.GetPrivateMember(context, "_database"); Util.SetPrivateMember(db, "_transactionDepth", transactionDepth); - //Act + // Act context.BeginTransaction(); - //Assert + // Assert Assert.AreEqual(transactionDepth + 1, Util.GetPrivateMember(db, "_transactionDepth")); - } - - #endregion - - #region Commit Tests - + } + [Test] public void PetaPocoDataContext_Commit_Decreases_Database_Transaction_Count() { - //Arrange + // Arrange const int transactionDepth = 2; var context = new PetaPocoDataContext(connectionStringName); Database db = Util.GetPrivateMember(context, "_database"); Util.SetPrivateMember(db, "_transactionDepth", transactionDepth); - //Act + // Act context.Commit(); - //Assert + // Assert Assert.AreEqual(transactionDepth - 1, Util.GetPrivateMember(db, "_transactionDepth")); } [Test] public void PetaPocoDataContext_Commit_Sets_Database_TransactionCancelled_False() { - //Arrange + // Arrange const int transactionDepth = 2; var context = new PetaPocoDataContext(connectionStringName); Database db = Util.GetPrivateMember(context, "_database"); Util.SetPrivateMember(db, "_transactionDepth", transactionDepth); - //Act + // Act context.Commit(); - //Assert + // Assert Assert.AreEqual(false, Util.GetPrivateMember(db, "_transactionCancelled")); - } - - #endregion - - #region RollbackTransaction Tests - + } + [Test] public void PetaPocoDataContext_RollbackTransaction_Decreases_Database_Transaction_Count() { - //Arrange + // Arrange const int transactionDepth = 2; var context = new PetaPocoDataContext(connectionStringName); Database db = Util.GetPrivateMember(context, "_database"); Util.SetPrivateMember(db, "_transactionDepth", transactionDepth); - //Act + // Act context.RollbackTransaction(); - //Assert + // Assert Assert.AreEqual(transactionDepth - 1, Util.GetPrivateMember(db, "_transactionDepth")); } [Test] public void PetaPocoDataContext_RollbackTransaction_Sets_Database_TransactionCancelled_True() { - //Arrange + // Arrange const int transactionDepth = 2; var context = new PetaPocoDataContext(connectionStringName); Database db = Util.GetPrivateMember(context, "_database"); Util.SetPrivateMember(db, "_transactionDepth", transactionDepth); - //Act + // Act context.RollbackTransaction(); - //Assert + // Assert Assert.AreEqual(true, Util.GetPrivateMember(db, "_transactionCancelled")); - } - - #endregion - - #region GetRepository Tests - + } + [Test] public void PetaPocoDataContext_GetRepository_Returns_Repository() { - //Arrange + // Arrange var context = new PetaPocoDataContext(connectionStringName); - //Act + // Act var repo = context.GetRepository(); - //Assert + // Assert Assert.IsInstanceOf>(repo); Assert.IsInstanceOf>(repo); } @@ -240,26 +213,26 @@ public void PetaPocoDataContext_GetRepository_Returns_Repository() [Test] public void PetaPocoDataContext_GetRepository_Sets_Repository_Database_Property() { - //Arrange + // Arrange var context = new PetaPocoDataContext(connectionStringName); - //Act + // Act var repo = (PetaPocoRepository)context.GetRepository(); - //Assert + // Assert Assert.IsInstanceOf(Util.GetPrivateMember, Database>(repo, "_database")); } [Test] public void PetaPocoDataContext_GetRepository_Uses_PetaPocoMapper_If_No_FluentMapper() { - //Arrange + // Arrange var context = new PetaPocoDataContext(connectionStringName); - //Act + // Act var repo = (PetaPocoRepository)context.GetRepository(); - //Assert + // Assert Assert.IsInstanceOf(Util.GetPrivateMember, IMapper>(repo, "_mapper")); Assert.IsInstanceOf(Util.GetPrivateMember, IMapper>(repo, "_mapper")); } @@ -267,20 +240,18 @@ public void PetaPocoDataContext_GetRepository_Uses_PetaPocoMapper_If_No_FluentMa [Test] public void PetaPocoDataContext_GetRepository_Uses_FluentMapper_If_FluentMapper_Defined() { - //Arrange + // Arrange var context = new PetaPocoDataContext(connectionStringName); context.AddFluentMapper(); - //Act + // Act var repo = (PetaPocoRepository)context.GetRepository(); - //Assert + // Assert Assert.IsInstanceOf(Util.GetPrivateMember, IMapper>(repo, "_mapper")); Assert.IsInstanceOf>(Util.GetPrivateMember, IMapper>(repo, "_mapper")); - } - - #endregion - - // ReSharper restore InconsistentNaming + } + + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs index 08cefdf0d97..dfa1ce753ae 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs @@ -1,36 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -using DotNetNuke.Collections; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Tests.Data.Models; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; -using PetaPoco; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Data { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.Collections; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Tests.Data.Models; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + using PetaPoco; + [TestFixture] public class PetaPocoIntegrationTests { - private Dictionary _mappers; - - // ReSharper disable InconsistentNaming - #region Setup/Teardown - + private const string ConnectionStringName = "PetaPoco"; + + private Dictionary _mappers; + + // ReSharper disable InconsistentNaming [SetUp] public void SetUp() { @@ -38,162 +32,163 @@ public void SetUp() ComponentFactory.RegisterComponentInstance(new SqlDataProvider()); ComponentFactory.RegisterComponentSettings(new Dictionary() { - {"name", "SqlDataProvider"}, - {"type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke"}, - {"connectionStringName", "SiteSqlServer"}, - {"objectQualifier", ""}, - {"databaseOwner", "dbo."} + { "name", "SqlDataProvider" }, + { "type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke" }, + { "connectionStringName", "SiteSqlServer" }, + { "objectQualifier", string.Empty }, + { "databaseOwner", "dbo." }, }); - var dogMapper = new FluentMapper("") + var dogMapper = new FluentMapper(string.Empty) .TableName(Constants.PETAPOCO_DogTableName) .PrimaryKey("ID") .Property(d => d.ID, "ID") .Property(d => d.Age, "Age") .Property(d => d.Name, "Name"); - var catMapper = new FluentMapper("") + var catMapper = new FluentMapper(string.Empty) .TableName(Constants.PETAPOCO_DogTableName) .Property(d => d.Age, "Age") .Property(d => d.Name, "Name"); - _mappers = new Dictionary {{typeof (Dog), dogMapper}}; - _mappers = new Dictionary { { typeof(Cat), catMapper } }; + this._mappers = new Dictionary { { typeof(Dog), dogMapper } }; + this._mappers = new Dictionary { { typeof(Cat), catMapper } }; } [TearDown] public void TearDown() { DataUtil.DeleteDatabase(Constants.PETAPOCO_DatabaseName); - } - - #endregion - - private const string ConnectionStringName = "PetaPoco"; + } [Test] public void PetaPoco_Add_Inserts_Item() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Insert(dog); } - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, actualCount); } [Test] public void PetaPoco_Add_Inserts_Item_Using_FluentMapper() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; - using (var dataContext = new PetaPocoDataContext(ConnectionStringName, String.Empty, _mappers)) + using (var dataContext = new PetaPocoDataContext(ConnectionStringName, string.Empty, this._mappers)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Insert(dog); } - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, actualCount); } [Test] public void PetaPoco_Delete_Deletes_Item() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Delete(dog); } - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); } [Test] public void PetaPoco_Delete_Deletes_Item_Using_FluentMapper() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; - using (var dataContext = new PetaPocoDataContext(ConnectionStringName, String.Empty, _mappers)) + using (var dataContext = new PetaPocoDataContext(ConnectionStringName, string.Empty, this._mappers)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Delete(dog); } - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); } [Test] public void PetaPoco_Delete_Overload_Deletes_Item() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Delete("WHERE ID = @0", Constants.PETAPOCO_DeleteDogId); } - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); } @@ -203,7 +198,7 @@ public void PetaPoco_Delete_Overload_Deletes_Item() [TestCase(2, "WHERE Name LIKE @0", "B%")] public void PetaPoco_Find_Returns_Correct_Rows(int count, string sqlCondition, object arg) { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); IEnumerable dogs; @@ -211,11 +206,11 @@ public void PetaPoco_Find_Returns_Correct_Rows(int count, string sqlCondition, o { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogs = dogRepository.Find(sqlCondition, arg); } - //Assert + // Assert Assert.AreEqual(count, dogs.Count()); } @@ -225,7 +220,7 @@ public void PetaPoco_Find_Returns_Correct_Rows(int count, string sqlCondition, o [TestCase(5)] public void PetaPoco_Get_Returns_All_Items(int count) { - //Arrange + // Arrange DataUtil.SetUpDatabase(count); IEnumerable dogs; @@ -233,12 +228,11 @@ public void PetaPoco_Get_Returns_All_Items(int count) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogs = dogRepository.Get(); } - - - //Assert + + // Assert Assert.AreEqual(count, dogs.Count()); } @@ -248,7 +242,7 @@ public void PetaPoco_Get_Returns_All_Items(int count) [TestCase(Constants.PAGE_Last, Constants.PAGE_RecordCount)] public void PetaPoco_GetAll_Overload_Returns_Page_Of_Items(int pageIndex, int pageSize) { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PAGE_TotalCount); IPagedList dogs; @@ -256,19 +250,18 @@ public void PetaPoco_GetAll_Overload_Returns_Page_Of_Items(int pageIndex, int pa { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogs = dogRepository.GetPage(pageIndex, pageSize); } - - - //Assert + + // Assert Assert.AreEqual(pageSize, dogs.PageSize); } [Test] public void PetaPoco_GetById_Returns_Single_Item() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); Dog dog; @@ -276,11 +269,11 @@ public void PetaPoco_GetById_Returns_Single_Item() { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dog = dogRepository.GetById(Constants.PETAPOCO_ValidDogId); } - //Assert + // Assert Assert.IsInstanceOf(dog); Assert.AreEqual(Constants.PETAPOCO_ValidDogAge, dog.Age); Assert.AreEqual(Constants.PETAPOCO_ValidDogName, dog.Name); @@ -289,19 +282,19 @@ public void PetaPoco_GetById_Returns_Single_Item() [Test] public void PetaPoco_GetById_Returns_Single_Item_Using_FluentMapper() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); Dog dog; - using (var dataContext = new PetaPocoDataContext(ConnectionStringName, String.Empty, _mappers)) + using (var dataContext = new PetaPocoDataContext(ConnectionStringName, string.Empty, this._mappers)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dog = dogRepository.GetById(Constants.PETAPOCO_ValidDogId); } - //Assert + // Assert Assert.IsInstanceOf(dog); Assert.AreEqual(Constants.PETAPOCO_ValidDogAge, dog.Age); Assert.AreEqual(Constants.PETAPOCO_ValidDogName, dog.Name); @@ -310,33 +303,33 @@ public void PetaPoco_GetById_Returns_Single_Item_Using_FluentMapper() [Test] public void PetaPoco_Update_Updates_Item() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; - //Act + // Act using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Update(dog); } - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, table.Rows.Count); foreach (DataRow row in table.Rows) { - if ((int) row["ID"] == Constants.PETAPOCO_UpdateDogId) + if ((int)row["ID"] == Constants.PETAPOCO_UpdateDogId) { Assert.AreEqual(row["Age"], Constants.PETAPOCO_UpdateDogAge); Assert.AreEqual(row["Name"], Constants.PETAPOCO_UpdateDogName); @@ -347,26 +340,26 @@ public void PetaPoco_Update_Updates_Item() [Test] public void PetaPoco_Update_Updates_Item_Using_FluentMapper() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; - //Act - using (var dataContext = new PetaPocoDataContext(ConnectionStringName, String.Empty, _mappers)) + // Act + using (var dataContext = new PetaPocoDataContext(ConnectionStringName, string.Empty, this._mappers)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Update(dog); } - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, table.Rows.Count); @@ -380,22 +373,23 @@ public void PetaPoco_Update_Updates_Item_Using_FluentMapper() } } } + [Test] public void PetaPoco_Update_Overload_Updates_Item() { - //Arrange + // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - //Act + // Act using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) { IRepository dogRepository = dataContext.GetRepository(); - //Act + // Act dogRepository.Update("SET Age=@1, Name=@2 WHERE ID=@0", Constants.PETAPOCO_UpdateDogId, Constants.PETAPOCO_UpdateDogAge, Constants.PETAPOCO_UpdateDogName); } - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, table.Rows.Count); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs index fafa2d1be96..394abd97cbe 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs @@ -1,196 +1,182 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Tests.Data.Models; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using System; + + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Tests.Data.Models; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + using PetaPoco; + [TestFixture] public class PetaPocoMapperTests - { - // ReSharper disable InconsistentNaming - - #region Constructor Tests - + { + // ReSharper disable InconsistentNaming [Test] public void PetaPocoMapper_Constructor_Initialises_TablePrefix_Property() { - //Arrange + // Arrange - //Act + // Act var mapper = new PetaPocoMapper(Constants.TABLENAME_Prefix); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Prefix, Util.GetPrivateMember(mapper, "_tablePrefix")); - } - - #endregion - - #region GetTableInfo Tests - + } + [Test] public void PetaPocoMapper_GetTableInfo_Returns_TableInfo() { - //Arrange + // Arrange var mapper = new PetaPocoMapper(Constants.TABLENAME_Prefix); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.IsInstanceOf(ti); } [Test] public void PetaPocoMapper_Maps_TableName_To_Plural_Of_ObjectName() { - //Arrange - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var mapper = new PetaPocoMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Dog, ti.TableName); } [Test] public void PetaPocoMapper_Adds_Prefix_To_Plural_Of_ObjectName() { - //Arrange + // Arrange var mapper = new PetaPocoMapper(Constants.TABLENAME_Prefix); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Prefix + Constants.TABLENAME_Dog, ti.TableName); } [Test] public void PetaPocoMapper_Maps_TableName_To_Attribute() { - //Arrange - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var mapper = new PetaPocoMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Person, ti.TableName); } [Test] public void PetaPocoMapper_Adds_Prefix_To_Attribute() { - //Arrange + // Arrange var mapper = new PetaPocoMapper(Constants.TABLENAME_Prefix); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Prefix + Constants.TABLENAME_Person, ti.TableName); } [Test] public void PetaPocoMapper_Sets_PrimaryKey_To_Attribute() { - //Arrange - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var mapper = new PetaPocoMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Person)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Person_Key, ti.PrimaryKey); } [Test] public void PetaPocoMapper_Sets_PrimaryKey_To_ID_If_No_Attribute() { - //Arrange - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var mapper = new PetaPocoMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.AreEqual(Constants.TABLENAME_Key, ti.PrimaryKey); } [Test] public void PetaPocoMapper_Sets_AutoIncrement_To_True() { - //Arrange - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var mapper = new PetaPocoMapper(string.Empty); - //Act + // Act var ti = mapper.GetTableInfo(typeof(Dog)); - //Assert + // Assert Assert.IsTrue(ti.AutoIncrement); - } - - #endregion - - #region GetColumnInfo Tests - + } + [Test] public void PetaPocoMapper_GetColumnInfo_Returns_ColumnInfo() { - //Arrange + // Arrange var mapper = new PetaPocoMapper(Constants.TABLENAME_Prefix); - var dogType = typeof (Dog); + var dogType = typeof(Dog); var dogProperty = dogType.GetProperty(Constants.COLUMNNAME_Name); - //Act + // Act var ci = mapper.GetColumnInfo(dogProperty); - //Assert + // Assert Assert.IsInstanceOf(ci); } [Test] public void PetaPocoMapper_GetColumnInfo_Maps_ColumnName_To_Attribute() { - //Arrange + // Arrange var mapper = new PetaPocoMapper(Constants.TABLENAME_Prefix); var personType = typeof(Person); var personProperty = personType.GetProperty(Constants.COLUMNNAME_Name); - //Act + // Act var ci = mapper.GetColumnInfo(personProperty); - //Assert + // Assert Assert.AreEqual(Constants.COLUMNNAME_PersonName, ci.ColumnName); } [Test] public void PetaPocoMapper_GetColumnInfo_Maps_ColumnName_To_PropertyName_If_No_Attribute() { - //Arrange + // Arrange var mapper = new PetaPocoMapper(Constants.TABLENAME_Prefix); var dogType = typeof(Dog); var dogProperty = dogType.GetProperty(Constants.COLUMNNAME_Name); - //Act + // Act var ci = mapper.GetColumnInfo(dogProperty); - //Assert + // Assert Assert.AreEqual(Constants.COLUMNNAME_Name, ci.ColumnName); - } - - #endregion - - // ReSharper restore InconsistentNaming + } + + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs index 838abe23661..08ba316ec55 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs @@ -1,30 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Tests.Data.Models; -using DotNetNuke.Tests.Utilities; - -using Moq; - -using NUnit.Framework; - -using PetaPoco; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Data { + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Tests.Data.Models; + using DotNetNuke.Tests.Utilities; + using Moq; + using NUnit.Framework; + using PetaPoco; + [TestFixture] public class PetaPocoRepositoryTests { // ReSharper disable InconsistentNaming - private const string connectionStringName = "PetaPoco"; private readonly string[] _dogAges = Constants.PETAPOCO_DogAges.Split(','); private readonly string[] _dogNames = Constants.PETAPOCO_DogNames.Split(','); @@ -37,11 +34,11 @@ public void SetUp() ComponentFactory.RegisterComponentInstance(new SqlDataProvider()); ComponentFactory.RegisterComponentSettings(new Dictionary() { - {"name", "SqlDataProvider"}, - {"type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke"}, - {"connectionStringName", "SiteSqlServer"}, - {"objectQualifier", ""}, - {"databaseOwner", "dbo."} + { "name", "SqlDataProvider" }, + { "type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke" }, + { "connectionStringName", "SiteSqlServer" }, + { "objectQualifier", string.Empty }, + { "databaseOwner", "dbo." }, }); } @@ -49,76 +46,70 @@ public void SetUp() public void TearDown() { DataUtil.DeleteDatabase(Constants.PETAPOCO_DatabaseName); - } - - #region Constructor Tests - + } + [Test] public void PetaPocoRepository_Constructor_Throws_On_Null_Database() { - //Arrange + // Arrange var mockMapper = new Mock(); - //Act, Assert + // Act, Assert Assert.Throws(() => new PetaPocoRepository(null, mockMapper.Object)); } [Test] public void PetaPocoRepository_Constructor_Registers_Mapper() { - //Arrange + // Arrange var mockMapper = new Mock(); var db = new Database(connectionStringName); - //Act + // Act #pragma warning disable 168 var repo = new PetaPocoRepository(db, mockMapper.Object); #pragma warning restore 168 - //Assert + // Assert Assert.AreSame(mockMapper.Object, Mappers.GetMapper(typeof(Dog), mockMapper.Object)); - } - - #endregion - - #region Get Tests - + } + [Test] [TestCase(0)] [TestCase(1)] [TestCase(5)] public void PetaPocoRepository_Get_Returns_All_Rows(int count) { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(count); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act IEnumerable dogs = repository.Get(); - //Assert + // Assert Assert.AreEqual(count, dogs.Count()); } [Test] public void PetaPocoRepository_Get_Returns_List_Of_Models() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dogs = repository.Get().ToList(); - //Assert + // Assert for (int i = 0; i < dogs.Count(); i++) { Assert.IsInstanceOf(dogs[i]); @@ -128,29 +119,29 @@ public void PetaPocoRepository_Get_Returns_List_Of_Models() [Test] public void PetaPocoRepository_Get_Returns_Models_With_Correct_Properties() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dogs = repository.Get(); - //Assert + // Assert var dog = dogs.First(); - Assert.AreEqual(_dogAges[0], dog.Age.ToString()); - Assert.AreEqual(_dogNames[0], dog.Name); + Assert.AreEqual(this._dogAges[0], dog.Age.ToString()); + Assert.AreEqual(this._dogNames[0], dog.Name); } [Test] public void PetaPocoRepository_Get_Returns_Models_With_Correct_Properties_Using_FluentMapper() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new FluentMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.PETAPOCO_DogTableName); mapper.Property(d => d.Age, "Age"); mapper.Property(d => d.Name, "Name"); @@ -159,61 +150,57 @@ public void PetaPocoRepository_Get_Returns_Models_With_Correct_Properties_Using_ var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dogs = repository.Get(); - //Assert + // Assert var dog = dogs.First(); - Assert.AreEqual(_dogAges[0], dog.Age.ToString()); - Assert.AreEqual(_dogNames[0], dog.Name); - } - - #endregion - - #region GetById Tests - + Assert.AreEqual(this._dogAges[0], dog.Age.ToString()); + Assert.AreEqual(this._dogNames[0], dog.Name); + } + [Test] public void PetaPocoRepository_GetById_Returns_Instance_Of_Model_If_Valid_Id() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dog = repository.GetById(Constants.PETAPOCO_ValidDogId); - //Assert + // Assert Assert.IsInstanceOf(dog); } [Test] public void PetaPocoRepository_GetById_Returns_Null_If_InValid_Id() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dog = repository.GetById(Constants.PETAPOCO_InvalidDogId); - //Assert + // Assert Assert.IsNull(dog); } [Test] public void PetaPocoRepository_GetById_Returns_Null_If_InValid_Id_Using_FluentMapper() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new FluentMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.PETAPOCO_DogTableName); mapper.PrimaryKey("ID"); mapper.Property(d => d.ID, "ID"); @@ -224,28 +211,28 @@ public void PetaPocoRepository_GetById_Returns_Null_If_InValid_Id_Using_FluentMa var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dog = repository.GetById(Constants.PETAPOCO_InvalidDogId); - //Assert + // Assert Assert.IsNull(dog); } [Test] public void PetaPocoRepository_GetById_Returns_Model_With_Correct_Properties() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dog = repository.GetById(Constants.PETAPOCO_ValidDogId); - //Assert + // Assert Assert.AreEqual(Constants.PETAPOCO_ValidDogAge, dog.Age); Assert.AreEqual(Constants.PETAPOCO_ValidDogName, dog.Name); } @@ -253,9 +240,9 @@ public void PetaPocoRepository_GetById_Returns_Model_With_Correct_Properties() [Test] public void PetaPocoRepository_GetById_Returns_Model_With_Correct_Properties_Using_FluentMapper() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new FluentMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.PETAPOCO_DogTableName); mapper.PrimaryKey("ID"); mapper.Property(d => d.ID, "ID"); @@ -266,88 +253,86 @@ public void PetaPocoRepository_GetById_Returns_Model_With_Correct_Properties_Usi var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dog = repository.GetById(Constants.PETAPOCO_ValidDogId); - //Assert + // Assert Assert.AreEqual(Constants.PETAPOCO_ValidDogAge, dog.Age); Assert.AreEqual(Constants.PETAPOCO_ValidDogName, dog.Name); - } - - #endregion - - #region Add Tests - + } + [Test] public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; - //Act + // Act repository.Insert(dog); - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, actualCount); } [Test] public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ID() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; - //Act + // Act repository.Insert(dog); - //Assert - int newId = DataUtil.GetLastAddedRecordID(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName, Constants.TABLENAME_Key); + // Assert + int newId = DataUtil.GetLastAddedRecordID( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName, Constants.TABLENAME_Key); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, newId); } [Test] public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ColumnValues() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; - //Act + // Act repository.Insert(dog); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); DataRow row = table.Rows[table.Rows.Count - 1]; @@ -358,9 +343,9 @@ public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_Colum [Test] public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ColumnValues_Using_FluentMapper() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new FluentMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.PETAPOCO_DogTableName); mapper.PrimaryKey("ID"); mapper.Property(d => d.ID, "ID"); @@ -373,71 +358,68 @@ public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_Colum var dog = new Dog { Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName + Name = Constants.PETAPOCO_InsertDogName, }; - //Act + // Act repository.Insert(dog); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); DataRow row = table.Rows[table.Rows.Count - 1]; Assert.AreEqual(Constants.PETAPOCO_InsertDogAge, row["Age"]); Assert.AreEqual(Constants.PETAPOCO_InsertDogName, row["Name"]); - } - - #endregion - - #region Delete Tests - + } + [Test] public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; - //Act + // Act repository.Delete(dog); - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); } [Test] public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; - //Act + // Act repository.Delete(dog); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); foreach (DataRow row in table.Rows) { @@ -448,9 +430,9 @@ public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID [Test] public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID_Using_FluentMapper() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new FluentMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.PETAPOCO_DogTableName); mapper.PrimaryKey("ID"); mapper.Property(d => d.ID, "ID"); @@ -464,13 +446,13 @@ public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID { ID = Constants.PETAPOCO_DeleteDogId, Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName + Name = Constants.PETAPOCO_DeleteDogName, }; - //Act + // Act repository.Delete(dog); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); foreach (DataRow row in table.Rows) { @@ -481,36 +463,37 @@ public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID [Test] public void PetaPocoRepository_Delete_Does_Nothing_With_Invalid_ID() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_InvalidDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_InvalidDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; - //Act + // Act repository.Delete(dog); - //Assert - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); } [Test] public void PetaPocoRepository_Delete_Does_Nothing_With_Invalid_ID_Using_FluentMapper() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new FluentMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.PETAPOCO_DogTableName); mapper.PrimaryKey("ID"); mapper.Property(d => d.ID, "ID"); @@ -524,58 +507,56 @@ public void PetaPocoRepository_Delete_Does_Nothing_With_Invalid_ID_Using_FluentM { ID = Constants.PETAPOCO_InvalidDogId, Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName + Name = Constants.PETAPOCO_DeleteDogName, }; - //Act + // Act repository.Delete(dog); - //Assert - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); - } - - #endregion - - #region Delete(sql, args) Tests - + } + [Test] public void PetaPocoRepository_Delete_Overload_Deletes_Item_From_DataBase() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act repository.Delete("WHERE ID = @0", Constants.PETAPOCO_DeleteDogId); - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); } [Test] public void PetaPocoRepository_Delete_Overload_Deletes_Item_From_DataBase_With_Correct_ID() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act repository.Delete("WHERE ID = @0", Constants.PETAPOCO_DeleteDogId); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); foreach (DataRow row in table.Rows) { @@ -586,88 +567,81 @@ public void PetaPocoRepository_Delete_Overload_Deletes_Item_From_DataBase_With_C [Test] public void PetaPocoRepository_Delete_Overload_Does_Nothing_With_Invalid_ID() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act repository.Delete("WHERE ID = @0", Constants.PETAPOCO_InvalidDogId); - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); - } - - #endregion - - #region Find Tests - + } + [Test] [TestCase(1, "WHERE ID < @0", 2)] [TestCase(4, "WHERE Age <= @0", 5)] [TestCase(2, "WHERE Name LIKE @0", "B%")] public void PetaPocoRepository_Find_Returns_Correct_Rows(int count, string sqlCondition, object arg) { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act IEnumerable dogs = repository.Find(sqlCondition, arg); - //Assert + // Assert Assert.AreEqual(count, dogs.Count()); - } - - #endregion - - #region GetPage Tests - + } + [Test] [TestCase(Constants.PAGE_First, Constants.PAGE_RecordCount)] [TestCase(Constants.PAGE_Second, Constants.PAGE_RecordCount)] [TestCase(Constants.PAGE_Last, Constants.PAGE_RecordCount)] public void PetaPocoRepository_GetPage_Overload_Returns_Page_Of_Rows(int pageIndex, int pageSize) { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PAGE_TotalCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dogs = repository.GetPage(pageIndex, pageSize); - //Assert + // Assert Assert.AreEqual(pageSize, dogs.PageSize); } [Test] public void PetaPocoRepository_GetPage_Overload_Returns_List_Of_Models() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PAGE_TotalCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dogs = repository.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert for (int i = 0; i < dogs.Count(); i++) { Assert.IsInstanceOf(dogs[i]); @@ -677,21 +651,21 @@ public void PetaPocoRepository_GetPage_Overload_Returns_List_Of_Models() [Test] public void PetaPocoRepository_GetPage_Overload_Returns_Models_With_Correct_Properties() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PAGE_TotalCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dogs = repository.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount); - //Assert + // Assert var dog = dogs.First(); - Assert.AreEqual(_dogAges[0], dog.Age.ToString()); - Assert.AreEqual(_dogNames[0], dog.Name); + Assert.AreEqual(this._dogAges[0], dog.Age.ToString()); + Assert.AreEqual(this._dogNames[0], dog.Name); } [Test] @@ -700,73 +674,70 @@ public void PetaPocoRepository_GetPage_Overload_Returns_Models_With_Correct_Prop [TestCase(2, 4, 9)] public void PetaPocoRepository_GetPage_Overload_Returns_Correct_Page(int pageIndex, int pageSize, int firstId) { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PAGE_TotalCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act var dogs = repository.GetPage(pageIndex, pageSize); - //Assert + // Assert var dog = dogs.First(); Assert.AreEqual(firstId, dog.ID); - } - - #endregion - - #region Update Tests - + } + [Test] public void PetaPocoRepository_Update_Updates_Item_In_DataBase() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; - //Act + // Act repository.Update(dog); - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); } [Test] public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; - //Act + // Act repository.Update(dog); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); foreach (DataRow row in table.Rows) { @@ -781,9 +752,9 @@ public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID() [Test] public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID_Using_FluentMapper() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new FluentMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new FluentMapper(string.Empty); mapper.TableName(Constants.PETAPOCO_DogTableName); mapper.PrimaryKey("ID"); mapper.Property(d => d.ID, "ID"); @@ -797,13 +768,13 @@ public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID_Using_FluentM { ID = Constants.PETAPOCO_UpdateDogId, Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName + Name = Constants.PETAPOCO_UpdateDogName, }; - //Act + // Act repository.Update(dog); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); foreach (DataRow row in table.Rows) { @@ -813,47 +784,44 @@ public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID_Using_FluentM Assert.AreEqual(Constants.PETAPOCO_UpdateDogName, row["Name"]); } } - } - - #endregion - - #region Update(sql, args) Tests - + } + [Test] public void PetaPocoRepository_Update_Overload_Updates_Item_In_DataBase() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act repository.Update("SET Age=@1, Name=@2 WHERE ID=@0", Constants.PETAPOCO_UpdateDogId, Constants.PETAPOCO_UpdateDogAge, Constants.PETAPOCO_UpdateDogName); - //Assert - int actualCount = DataUtil.GetRecordCount(Constants.PETAPOCO_DatabaseName, - Constants.PETAPOCO_DogTableName); + // Assert + int actualCount = DataUtil.GetRecordCount( + Constants.PETAPOCO_DatabaseName, + Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); } [Test] public void PetaPocoRepository_Update_Overload_Updates_Item_With_Correct_ID() { - //Arrange - var db = CreatePecaPocoDatabase(); - var mapper = new PetaPocoMapper(String.Empty); + // Arrange + var db = this.CreatePecaPocoDatabase(); + var mapper = new PetaPocoMapper(string.Empty); DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - //Act + // Act repository.Update("SET Age=@1, Name=@2 WHERE ID=@0", Constants.PETAPOCO_UpdateDogId, Constants.PETAPOCO_UpdateDogAge, Constants.PETAPOCO_UpdateDogName); - //Assert + // Assert DataTable table = DataUtil.GetTable(Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); foreach (DataRow row in table.Rows) { @@ -863,10 +831,8 @@ public void PetaPocoRepository_Update_Overload_Updates_Item_With_Correct_ID() Assert.AreEqual(Constants.PETAPOCO_UpdateDogName, row["Name"]); } } - } - - #endregion - + } + private Database CreatePecaPocoDatabase() { var db = new Database(connectionStringName); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj index b89b33a8555..ae1fca959f5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj @@ -167,8 +167,14 @@ DotNetNuke.Tests.Utilities - + + + + + + stylecop.json + App.config Designer diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/PageSettingsBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/PageSettingsBuilder.cs index 52af9da14bb..fe38474671a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/PageSettingsBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/PageSettingsBuilder.cs @@ -1,131 +1,132 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using DotNetNuke.Tests.Integration.Executers.Dto; -using NTestDataBuilder; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Builders { + using System; + using System.Collections.Generic; + + using DotNetNuke.Tests.Integration.Executers.Dto; + using NTestDataBuilder; + public class PageSettingsBuilder : TestDataBuilder { public PageSettingsBuilder() { - WithTabId(0); - WithName("RB" + Guid.NewGuid().ToString().Replace("-","")); - WithPageType(string.Empty); - WithUrl(string.Empty); - WithPermission(new TabPermissions()); + this.WithTabId(0); + this.WithName("RB" + Guid.NewGuid().ToString().Replace("-", string.Empty)); + this.WithPageType(string.Empty); + this.WithUrl(string.Empty); + this.WithPermission(new TabPermissions()); } public PageSettingsBuilder WithTabId(int tabId) { - Set(x => x.tabId, tabId); + this.Set(x => x.tabId, tabId); return this; } public PageSettingsBuilder WithPageType(string pageType) { - Set(x => x.pageType, pageType); + this.Set(x => x.pageType, pageType); return this; } public PageSettingsBuilder WithName(string name) { - Set(x => x.Name, name); + this.Set(x => x.Name, name); return this; } public PageSettingsBuilder WithStartDate(DateTime startDate) { - Set(x => x.startDate, startDate); + this.Set(x => x.startDate, startDate); return this; } public PageSettingsBuilder WithEndDate(DateTime endDate) { - Set(x => x.endDate, endDate); + this.Set(x => x.endDate, endDate); return this; } public PageSettingsBuilder WithKeyWords(string keyWords) { - Set(x => x.keywords, keyWords); + this.Set(x => x.keywords, keyWords); return this; } public PageSettingsBuilder WithDescription(string description) { - Set(x => x.Description, description); + this.Set(x => x.Description, description); return this; } - + public PageSettingsBuilder WithUrl(string url) { - Set(x => x.Url, url); + this.Set(x => x.Url, url); return this; } public PageSettingsBuilder WithPermission(TabPermissions permissions) { - Set(x => x.permissions, permissions); + this.Set(x => x.permissions, permissions); return this; } public PageSettingsBuilder WithTemplateTabId(int templateTabId) { - Set(x => x.templateTabId, templateTabId); + this.Set(x => x.templateTabId, templateTabId); return this; } public PageSettingsBuilder WithCopyModules(IList modules) { - Set(x => x.modules, modules); + this.Set(x => x.modules, modules); return this; } public PageSettingsBuilder WithSecure(bool secure) { - Set(x => x.isSecure, secure); + this.Set(x => x.isSecure, secure); return this; } protected override PageSettings BuildObject() { - var name = GetOrDefault(p => p.Name); + var name = this.GetOrDefault(p => p.Name); var pageSettings = new PageSettings { ApplyWorkflowToChildren = false, - created = "", + created = string.Empty, customUrlEnabled = true, hasChild = false, - Hierarchy = "", + Hierarchy = string.Empty, IncludeInMenu = true, isCopy = false, isWorkflowCompleted = true, isWorkflowPropagationAvailable = false, - keywords = GetOrDefault(p => p.keywords), - localizedName = "", + keywords = this.GetOrDefault(p => p.keywords), + localizedName = string.Empty, Name = name, - pageType = GetOrDefault(p => p.pageType), - tabId = GetOrDefault(p => p.tabId), - tags = "", - thumbnail = "", - title = "", + pageType = this.GetOrDefault(p => p.pageType), + tabId = this.GetOrDefault(p => p.tabId), + tags = string.Empty, + thumbnail = string.Empty, + title = string.Empty, trackLinks = false, type = 0, - workflowId = GetOrDefault(p => p.workflowId), - Url = GetOrDefault(p => p.Url), - Description = GetOrDefault(p => p.Description), - startDate = GetOrDefault(p => p.startDate), - endDate = GetOrDefault(p => p.endDate), - permissions = GetOrDefault(p => p.permissions), - templateTabId = GetOrDefault(p => p.templateTabId), - modules = GetOrDefault(p => p.modules), - isSecure = GetOrDefault(p => p.isSecure) + workflowId = this.GetOrDefault(p => p.workflowId), + Url = this.GetOrDefault(p => p.Url), + Description = this.GetOrDefault(p => p.Description), + startDate = this.GetOrDefault(p => p.startDate), + endDate = this.GetOrDefault(p => p.endDate), + permissions = this.GetOrDefault(p => p.permissions), + templateTabId = this.GetOrDefault(p => p.templateTabId), + modules = this.GetOrDefault(p => p.modules), + isSecure = this.GetOrDefault(p => p.isSecure), }; return pageSettings; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs index e6fbefcd1df..428c9fa3ad6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs @@ -1,37 +1,54 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Tests.Integration.Executers.Dto; -using NTestDataBuilder; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Builders { + using System.Collections.Generic; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Tests.Integration.Executers.Dto; + using NTestDataBuilder; + public class TabPermissionsBuilder : TestDataBuilder { public TabPermissionsBuilder() { - WithTabId(Null.NullInteger); + this.WithTabId(Null.NullInteger); } - public TabPermissionsBuilder WithTabId(int tabId) { Set(x => x.TabId, tabId); return this; } + public TabPermissionsBuilder WithTabId(int tabId) + { + this.Set(x => x.TabId, tabId); + return this; + } - public TabPermissionsBuilder WithPermissionDefinitions(IList permissionDefinitions) { Set(x => x.PermissionDefinitions, permissionDefinitions); return this; } + public TabPermissionsBuilder WithPermissionDefinitions(IList permissionDefinitions) + { + this.Set(x => x.PermissionDefinitions, permissionDefinitions); + return this; + } - public TabPermissionsBuilder WithRolePermissions(IList rolePermissions) { Set(x => x.RolePermissions, rolePermissions); return this; } + public TabPermissionsBuilder WithRolePermissions(IList rolePermissions) + { + this.Set(x => x.RolePermissions, rolePermissions); + return this; + } - public TabPermissionsBuilder WithUserPermissions(IList userPermissions) { Set(x => x.UserPermissions, userPermissions); return this; } + public TabPermissionsBuilder WithUserPermissions(IList userPermissions) + { + this.Set(x => x.UserPermissions, userPermissions); + return this; + } protected override TabPermissions BuildObject() { return new TabPermissions { - TabId = GetOrDefault(x => x.TabId), - PermissionDefinitions = GetOrDefault(x => x.PermissionDefinitions), - RolePermissions = GetOrDefault(x => x.RolePermissions), - UserPermissions = GetOrDefault(x => x.UserPermissions), + TabId = this.GetOrDefault(x => x.TabId), + PermissionDefinitions = this.GetOrDefault(x => x.PermissionDefinitions), + RolePermissions = this.GetOrDefault(x => x.RolePermissions), + UserPermissions = this.GetOrDefault(x => x.UserPermissions), }; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/CopyModuleItem.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/CopyModuleItem.cs index d616e1bc2ee..5eb2cd7cc79 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/CopyModuleItem.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/CopyModuleItem.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using DotNetNuke.Entities.Modules; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Dto { + using System; + using System.Data; + + using DotNetNuke.Entities.Modules; + public class CopyModuleItem : IHydratable { public int Id { get; set; } @@ -16,14 +17,14 @@ public class CopyModuleItem : IHydratable public int KeyID { - get { return Id; } - set { Id = value; } + get { return this.Id; } + set { this.Id = value; } } public void Fill(IDataReader dr) { - Id = Convert.ToInt32(dr["ModuleId"]); - Title = Convert.ToString(dr["ModuleTitle"]); + this.Id = Convert.ToInt32(dr["ModuleId"]); + this.Title = Convert.ToString(dr["ModuleTitle"]); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs index 2512de35228..bf81f1d1c99 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs @@ -1,41 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Dto { + using System; + using System.Collections.Generic; + public class PageSettings { public bool ApplyWorkflowToChildren { get; set; } + public string created { get; set; } + public bool customUrlEnabled { get; set; } + public bool hasChild { get; set; } + public string Hierarchy { get; set; } + public bool IncludeInMenu { get; set; } + public bool isCopy { get; set; } + public bool isWorkflowCompleted { get; set; } + public bool isWorkflowPropagationAvailable { get; set; } + public string keywords { get; set; } + public string localizedName { get; set; } + public string Name { get; set; } + public string pageType { get; set; } + public int tabId { get; set; } + public string tags { get; set; } + public string thumbnail { get; set; } + public string title { get; set; } + public bool trackLinks { get; set; } + public int type { get; set; } + public int workflowId { get; set; } + public string Url { get; set; } + public string Description { get; set; } + public DateTime? startDate { get; set; } + public DateTime? endDate { get; set; } + public TabPermissions permissions { get; set; } + public int templateTabId { get; set; } - public IList modules { get; set; } - public bool isSecure { get; set; } + + public IList modules { get; set; } + + public bool isSecure { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/Permission.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/Permission.cs index 07753a92d91..e4f00ca5bc6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/Permission.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/Permission.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Dto { public class Permission { public int PermissionId { get; set; } - + public string PermissionName { get; set; } - + public bool FullControl { get; set; } - + public bool View { get; set; } - + public bool AllowAccess { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/RolePermission.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/RolePermission.cs index 7b8ae72aa1a..9ca7b629793 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/RolePermission.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/RolePermission.cs @@ -1,21 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Dto { + using System.Collections.Generic; + public class RolePermission { public int RoleId { get; set; } - + public string RoleName { get; set; } - + public IList Permissions { get; set; } - + public bool Locked { get; set; } - + public bool IsDefault { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/TabPermissions.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/TabPermissions.cs index 9538632f426..f3abdfeadc4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/TabPermissions.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/TabPermissions.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Dto { + using System.Collections.Generic; + public class TabPermissions { public int TabId { get; set; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/UserPermission.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/UserPermission.cs index 72b51db65f9..3a1c9e9c21e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/UserPermission.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/UserPermission.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers.Dto { + using System.Collections.Generic; + public class UserPermission { public int UserId { get; set; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs index 9dc51f40f05..c83cd16859b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs @@ -1,16 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers { public class PagesExecuter : WebApiExecuter - { - #region Page Setting API action methods - + { public PagesExecuter GetPageDetails(int pageId) { - Responses.Add(Connector.GetContent( + this.Responses.Add(this.Connector.GetContent( "API/PersonaBar/Pages/GetPageDetails?pageId=" + pageId)); return this; @@ -18,11 +16,10 @@ public PagesExecuter GetPageDetails(int pageId) public dynamic SavePageDetails(dynamic pageDetails) { - Responses.Add(Connector.PostJson("API/PersonaBar/Pages/SavePageDetails", + this.Responses.Add(this.Connector.PostJson( + "API/PersonaBar/Pages/SavePageDetails", pageDetails)); - return GetLastDeserializeResponseMessage(); - } - - #endregion + return this.GetLastDeserializeResponseMessage(); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs index 351e2a913d6..9eca5061a46 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs @@ -1,94 +1,101 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using DotNetNuke.Tests.Utilities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Executers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Tests.Utilities; + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + public enum LoginAsUser { GivenUserName = 0, AnonymousUser, RegisteredUser, - Host - }; + Host, + } public abstract class WebApiExecuter { public Func Login; + protected Func Anonymous; + + protected List Responses = new List(); + private LoginAsUser _loginAs; + private IWebApiConnector _connector; + + protected WebApiExecuter() + { + this.LoginAs = LoginAsUser.RegisteredUser; + this.Login = WebApiTestHelper.LoginRegisteredUser; + this.Anonymous = WebApiTestHelper.GetAnnonymousConnector; + + this.UserFirstName = Constants.RuFirstName; + this.UserLastName = Constants.RuLastName; + } public LoginAsUser LoginAs { get { - return _loginAs; + return this._loginAs; } + set { - _loginAs = value; - _connector = null; + this._loginAs = value; + this._connector = null; } } public string UserFirstName { get; set; } + public string UserLastName { get; set; } - protected Func Anonymous; - private IWebApiConnector _connector; - - protected WebApiExecuter() - { - LoginAs = LoginAsUser.RegisteredUser; - Login = WebApiTestHelper.LoginRegisteredUser; - Anonymous = WebApiTestHelper.GetAnnonymousConnector; - - UserFirstName = Constants.RuFirstName; - UserLastName = Constants.RuLastName; - } - public IWebApiConnector Connector { get { - if (_connector == null) + if (this._connector == null) { - switch (LoginAs) + switch (this.LoginAs) { case LoginAsUser.RegisteredUser: - _connector = Login(UserFirstName, UserLastName, null); + this._connector = this.Login(this.UserFirstName, this.UserLastName, null); break; case LoginAsUser.AnonymousUser: - _connector = Anonymous(null); + this._connector = this.Anonymous(null); break; case LoginAsUser.Host: - _connector = WebApiTestHelper.LoginHost(); + this._connector = WebApiTestHelper.LoginHost(); break; default: - _connector = Login(UserFirstName, UserLastName, null); + this._connector = this.Login(this.UserFirstName, this.UserLastName, null); break; } } - return _connector; + + return this._connector; } + set { - _connector = value; - var userName = _connector.UserName.Split('.'); + this._connector = value; + var userName = this._connector.UserName.Split('.'); if (userName.Length == 2) { - UserFirstName = userName[0]; - UserLastName = userName[1]; + this.UserFirstName = userName[0]; + this.UserLastName = userName[1]; } } } @@ -97,7 +104,7 @@ public string UserName { get { - return Connector.UserName; + return this.Connector.UserName; } } @@ -105,7 +112,7 @@ public string DisplayName { get { - return string.Join(" ", UserFirstName, UserLastName); + return string.Join(" ", this.UserFirstName, this.UserLastName); } } @@ -113,49 +120,49 @@ public int UserId { get { - return DatabaseHelper.ExecuteScalar($"SELECT UserId FROM {{objectQualifier}}Users WHERE UserName = '{UserName}'"); + return DatabaseHelper.ExecuteScalar($"SELECT UserId FROM {{objectQualifier}}Users WHERE UserName = '{this.UserName}'"); } } - protected List Responses = new List(); - public HttpResponseMessage GetLastResponseMessage() { - return Responses.Last(); + return this.Responses.Last(); } /// - /// Return the last executer's response deserialized + /// Return the last executer's response deserialized. /// - /// Thrown when the executer does not have any response + /// Thrown when the executer does not have any response. /// public JContainer GetLastDeserializeResponseMessage() { - if (!Responses.Any()) + if (!this.Responses.Any()) { throw new InvalidOperationException("GetLastDeserializeResponseMessage cannot be called when the Executer does not have any Responses"); } - var data = Responses.Last().Content.ReadAsStringAsync().Result; + + var data = this.Responses.Last().Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject(data); } public IEnumerable GetResponseMessages() { - return Responses.ToArray(); + return this.Responses.ToArray(); } /// - /// Return the list of the executer's responses deserialized + /// Return the list of the executer's responses deserialized. /// - /// Thrown when the executer does not have any response + /// Thrown when the executer does not have any response. /// public IEnumerable GetDeserializeResponseMessages() { - if (!Responses.Any()) + if (!this.Responses.Any()) { throw new InvalidOperationException("GetDeserializeResponseMessages cannot be called when the Executer does not have any Responses"); } - return GetResponseMessages().Select(r => JsonConvert.DeserializeObject(r.Content.ReadAsStringAsync().Result)); + + return this.GetResponseMessages().Select(r => JsonConvert.DeserializeObject(r.Content.ReadAsStringAsync().Result)); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs index 349edf9baa8..4c32fbda29d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs @@ -1,73 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Tests.Integration.Executers; -using DotNetNuke.Tests.Integration.Executers.Builders; -using DotNetNuke.Tests.Integration.Executers.Dto; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Controllers; -using DNN.Integration.Test.Framework.Helpers; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Modules.DDRMenu { + using System.Collections.Generic; + using System.Configuration; + using System.Linq; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Controllers; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Tests.Integration.Executers; + using DotNetNuke.Tests.Integration.Executers.Builders; + using DotNetNuke.Tests.Integration.Executers.Dto; + using NUnit.Framework; + [TestFixture] public class DDRMenuTests : IntegrationTestBase - { - #region Fields - + { private readonly string _hostName; - private readonly string _hostPass; - - #endregion - - #region SetUp - + private readonly string _hostPass; + public DDRMenuTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; - _hostName = ConfigurationManager.AppSettings["hostUsername"]; - _hostPass = ConfigurationManager.AppSettings["hostPassword"]; + this._hostName = ConfigurationManager.AppSettings["hostUsername"]; + this._hostPass = ConfigurationManager.AppSettings["hostPassword"]; } [TestFixtureSetUp] public override void TestFixtureSetUp() { base.TestFixtureSetUp(); - } - - #endregion - - #region Tests - + } + [Test] public void Page_Should_Able_To_Duplicate_With_Ddr_Menu_On_It() { - //Create new page with DDR Menu on it + // Create new page with DDR Menu on it int tabId; - CreateNewPage(Null.NullInteger, out tabId); + this.CreateNewPage(Null.NullInteger, out tabId); int moduleId; - AddModuleToPage(tabId, "DDRMenu", out moduleId); + this.AddModuleToPage(tabId, "DDRMenu", out moduleId); - //apply module settings. + // apply module settings. ModuleController.SetModuleSettingValue(moduleId, "MenuStyle", "Menus/MainMenu"); - //Copy Page + // Copy Page int copyTabId; - CreateNewPage(tabId, out copyTabId); - } - - - - #endregion - - #region Private Methods - + this.CreateNewPage(tabId, out copyTabId); + } + private IWebApiConnector CreateNewPage(int templateTabId, out int tabId) { var pagesExecuter = new PagesExecuter { Connector = WebApiTestHelper.LoginHost() }; @@ -105,7 +90,7 @@ private IWebApiConnector AddModuleToPage(int tabId, string moduleName, out int m Pane = "ContentPane", AddExistingModule = false, CopyModule = false, - Sort = -1 + Sort = -1, }; var headers = new Dictionary { { "TabId", tabId.ToString() } }; var response = connector.PostJson("API/internalservices/controlbar/AddModule", postData, headers) @@ -113,8 +98,6 @@ private IWebApiConnector AddModuleToPage(int tabId, string moduleName, out int m moduleId = Json.Deserialize(response).TabModuleID; return connector; - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DigitalAssets/DigitalAssetsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DigitalAssets/DigitalAssetsTests.cs index ec002bcf07c..8a9788b11c5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DigitalAssets/DigitalAssetsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DigitalAssets/DigitalAssetsTests.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.IO; -using DotNetNuke.Common.Utilities; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Modules.DigitalAssets { + using System; + using System.Collections.Generic; + using System.Configuration; + using System.IO; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Common.Utilities; + using NUnit.Framework; + [TestFixture] public class DigitalAssetsTests : IntegrationTestBase { @@ -23,17 +24,17 @@ public void File_Url_Should_Update_After_Rename_Folder() { var connector = WebApiTestHelper.LoginAdministrator(); - var folder = CreateNewFolder(connector); + var folder = this.CreateNewFolder(connector); var folderId = Convert.ToInt32(folder.FolderID); var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files\\Test.png"); connector.UploadCmsFile(filePath, folder.FolderPath.ToString()); - var fileId = GetFileId(folderId, "Test.png"); + var fileId = this.GetFileId(folderId, "Test.png"); var newFolderName = Guid.NewGuid().ToString(); - RenameFolder(connector, folderId, newFolderName); + this.RenameFolder(connector, folderId, newFolderName); var getUrlApi = "API/DigitalAssets/ContentService/GetUrl"; - var fileUrl = connector.PostJson(getUrlApi, new {fileId = fileId}, GetRequestHeaders()).Content.ReadAsStringAsync().Result; + var fileUrl = connector.PostJson(getUrlApi, new { fileId = fileId }, this.GetRequestHeaders()).Content.ReadAsStringAsync().Result; Assert.IsTrue(fileUrl.Contains(newFolderName)); } @@ -41,13 +42,13 @@ public void File_Url_Should_Update_After_Rename_Folder() private int GetRootFolderId() { return DatabaseHelper.ExecuteScalar( - $"SELECT FolderID FROM {{objectQualifier}}[Folders] WHERE PortalId = {PortalId} AND FolderPath = ''"); + $"SELECT FolderID FROM {{objectQualifier}}[Folders] WHERE PortalId = {this.PortalId} AND FolderPath = ''"); } private int GetStandardFolderMappingId() { return DatabaseHelper.ExecuteScalar( - $"SELECT FolderMappingId from {{objectQualifier}}[FolderMappings] where PortalID = {PortalId} and MappingName = 'Standard'"); + $"SELECT FolderMappingId from {{objectQualifier}}[FolderMappings] where PortalID = {this.PortalId} and MappingName = 'Standard'"); } private int GetFileId(int folderId, string fileName) @@ -58,17 +59,17 @@ private int GetFileId(int folderId, string fileName) private dynamic CreateNewFolder(IWebApiConnector connector) { - var rootFolderId = GetRootFolderId(); + var rootFolderId = this.GetRootFolderId(); var apiUrl = "API/DigitalAssets/ContentService/CreateNewFolder"; var postData = new { FolderName = Guid.NewGuid().ToString(), ParentFolderId = rootFolderId, - FolderMappingId = GetStandardFolderMappingId(), - MappedName = string.Empty + FolderMappingId = this.GetStandardFolderMappingId(), + MappedName = string.Empty, }; - var response = connector.PostJson(apiUrl, postData, GetRequestHeaders()); + var response = connector.PostJson(apiUrl, postData, this.GetRequestHeaders()); return Json.Deserialize(response.Content.ReadAsStringAsync().Result); } @@ -78,15 +79,15 @@ private void RenameFolder(IWebApiConnector connector, int folderId, string newFo var postData = new { folderId = folderId, - newFolderName = newFolderName + newFolderName = newFolderName, }; - connector.PostJson(apiUrl, postData, GetRequestHeaders()); + connector.PostJson(apiUrl, postData, this.GetRequestHeaders()); } private IDictionary GetRequestHeaders() { - return WebApiTestHelper.GetRequestHeaders("//Admin//FileManagement", "Digital Asset Management", PortalId); + return WebApiTestHelper.GetRequestHeaders("//Admin//FileManagement", "Digital Asset Management", this.PortalId); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs index c8770a20f72..f54cd85a395 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs @@ -1,36 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using DotNetNuke.Common.Utilities; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Modules.Journal { + using System; + using System.Collections.Generic; + using System.Configuration; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Common.Utilities; + using NUnit.Framework; + [TestFixture] public class PostJournalTests : IntegrationTestBase - { - #region Fields - + { + private static readonly Random rnd = new Random(); + private readonly string _hostName; private readonly string _hostPass; - private readonly int PortalId = 0; - - #endregion - - #region SetUp - + private readonly int PortalId = 0; + public PostJournalTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; - _hostName = ConfigurationManager.AppSettings["hostUsername"]; - _hostPass = ConfigurationManager.AppSettings["hostPassword"]; + this._hostName = ConfigurationManager.AppSettings["hostUsername"]; + this._hostPass = ConfigurationManager.AppSettings["hostPassword"]; } [TestFixtureSetUp] @@ -39,39 +36,36 @@ public override void TestFixtureSetUp() base.TestFixtureSetUp(); try { - if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) - DatabaseHelper.ExecuteNonQuery("TRUNCATE TABLE {objectQualifier}JsonWebTokens"); + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) + { + DatabaseHelper.ExecuteNonQuery("TRUNCATE TABLE {objectQualifier}JsonWebTokens"); + } } catch (Exception) { // ignored } - } - - #endregion - - #region Tests - + } + [Test] public void Journal_Should_Able_To_Attach_Files_Upload_By_Himself() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username} Post", profileId = userId, groupId = -1, journalType = "file", - securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}" + securitySet = "E", + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; - - - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); } [Test] @@ -79,9 +73,10 @@ public void Journal_Should_Not_Able_To_Attach_Files_Upload_By_Other_User() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); - fileId = DatabaseHelper.ExecuteScalar($"SELECT MIN(FileId) FROM {{objectQualifier}}Files WHERE PortalId = {PortalId}"); - //POST JOURNAL + var connector = this.PrepareNewUser(out userId, out username, out fileId); + fileId = DatabaseHelper.ExecuteScalar($"SELECT MIN(FileId) FROM {{objectQualifier}}Files WHERE PortalId = {this.PortalId}"); + + // POST JOURNAL var postData = new { text = $"{username} Post", @@ -89,21 +84,21 @@ public void Journal_Should_Not_Able_To_Attach_Files_Upload_By_Other_User() groupId = -1, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; var exceptionThrown = false; var exceptionMessage = string.Empty; try { - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); } catch (WebApiException ex) { exceptionThrown = true; exceptionMessage = Json.Deserialize(ex.Body).ExceptionMessage; } - + Assert.IsTrue(exceptionThrown, "Should throw out exception"); Assert.AreEqual("you have no permission to attach files not belongs to you.", exceptionMessage); } @@ -113,9 +108,9 @@ public void Journal_Should_Not_Able_To_Post_On_Other_User_Profile_Page() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username} Post", @@ -123,14 +118,14 @@ public void Journal_Should_Not_Able_To_Post_On_Other_User_Profile_Page() groupId = -1, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; var exceptionThrown = false; var exceptionMessage = string.Empty; try { - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); } catch (WebApiException ex) { @@ -147,16 +142,16 @@ public void Journal_Should_Able_To_Post_On_Friends_Profile_Page() { int userId1, fileId1, userId2, fileId2; string username1, username2; - var connector1 = PrepareNewUser(out userId1, out username1, out fileId1); - var connector2 = PrepareNewUser(out userId2, out username2, out fileId2); + var connector1 = this.PrepareNewUser(out userId1, out username1, out fileId1); + var connector2 = this.PrepareNewUser(out userId2, out username2, out fileId2); - //ADD FRIENDS - connector1.PostJson("/API/MemberDirectory/MemberDirectory/AddFriend", new {friendId = userId2}, GetRequestHeaders("Member Directory")); + // ADD FRIENDS + connector1.PostJson("/API/MemberDirectory/MemberDirectory/AddFriend", new { friendId = userId2 }, this.GetRequestHeaders("Member Directory")); var notificationId = DatabaseHelper.ExecuteScalar($"SELECT TOP 1 MessageID FROM {{objectQualifier}}CoreMessaging_Messages WHERE SenderUserID = {userId1}"); - connector2.PostJson("/API/InternalServices/RelationshipService/AcceptFriend", new { NotificationId = notificationId }, GetRequestHeaders()); + connector2.PostJson("/API/InternalServices/RelationshipService/AcceptFriend", new { NotificationId = notificationId }, this.GetRequestHeaders()); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username1} Post", @@ -164,10 +159,10 @@ public void Journal_Should_Able_To_Post_On_Friends_Profile_Page() groupId = -1, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId1}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId1}\"}}", }; - connector1.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector1.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); } [Test] @@ -175,11 +170,11 @@ public void Journal_Should_Able_To_Post_On_Group_Already_Join() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); - var groupId = CreateNewGroup(username.Replace("testuser", "testrole")); - AddUserToGroup(groupId, userId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); + var groupId = this.CreateNewGroup(username.Replace("testuser", "testrole")); + this.AddUserToGroup(groupId, userId); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username} Post", @@ -187,10 +182,10 @@ public void Journal_Should_Able_To_Post_On_Group_Already_Join() groupId = groupId, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); } [Test] @@ -198,10 +193,10 @@ public void Journal_Should_Not_Able_To_Post_On_Group_Not_Join() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); - var groupId = CreateNewGroup(username.Replace("testuser", "testrole")); + var connector = this.PrepareNewUser(out userId, out username, out fileId); + var groupId = this.CreateNewGroup(username.Replace("testuser", "testrole")); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username} Post", @@ -209,14 +204,14 @@ public void Journal_Should_Not_Able_To_Post_On_Group_Not_Join() groupId = groupId, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; var exceptionThrown = false; var exceptionMessage = string.Empty; try { - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); } catch (WebApiException ex) { @@ -233,9 +228,9 @@ public void Journal_Should_Not_Able_To_Post_Xss_Code_In_ImageUrl() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username} Post", @@ -243,10 +238,10 @@ public void Journal_Should_Not_Able_To_Post_Xss_Code_In_ImageUrl() groupId = -1, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"javascript:alert(1);\\\" onerror=\\\"alert(2);.png\",\"Url\":\"fileid={fileId}\"}}" + itemData = $"{{\"ImageUrl\":\"javascript:alert(1);\\\" onerror=\\\"alert(2);.png\",\"Url\":\"fileid={fileId}\"}}", }; - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); var itemData = DatabaseHelper.ExecuteScalar($"SELECT ItemData FROM {{objectQualifier}}Journal WHERE UserId = {userId}"); var imageUrl = Json.Deserialize(itemData).ImageUrl.ToString(); @@ -261,9 +256,9 @@ public void Journal_Should_Not_Able_To_Post_Xss_Code_In_Url() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username} Post", @@ -271,10 +266,10 @@ public void Journal_Should_Not_Able_To_Post_Xss_Code_In_Url() groupId = -1, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"javascript:alert(1);\", \"Title\": \"Test.png\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"javascript:alert(1);\", \"Title\": \"Test.png\"}}", }; - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); var itemData = DatabaseHelper.ExecuteScalar($"SELECT ItemData FROM {{objectQualifier}}Journal WHERE UserId = {userId}"); var url = Json.Deserialize(itemData).Url.ToString(); @@ -287,9 +282,9 @@ public void Journal_Should_Not_Able_To_Post_Extenal_Link_In_Url() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); - //POST JOURNAL + // POST JOURNAL var postData = new { text = $"{username} Post", @@ -297,10 +292,10 @@ public void Journal_Should_Not_Able_To_Post_Extenal_Link_In_Url() groupId = -1, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"http://www.dnnsoftware.com\", \"Title\": \"Test.png\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"http://www.dnnsoftware.com\", \"Title\": \"Test.png\"}}", }; - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); var itemData = DatabaseHelper.ExecuteScalar($"SELECT ItemData FROM {{objectQualifier}}Journal WHERE UserId = {userId}"); var url = Json.Deserialize(itemData).Url.ToString(); @@ -313,9 +308,9 @@ public void Journal_Should_Able_See_By_All_When_Set_Security_To_Everyone() { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); - //POST JOURNAL + // POST JOURNAL var journalText = $"{username} Post"; var postData = new { @@ -324,10 +319,10 @@ public void Journal_Should_Able_See_By_All_When_Set_Security_To_Everyone() groupId = -1, journalType = "file", securitySet = "E", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); var response = connector.GetContent($"/Activity-Feed/userId/{userId}").Content.ReadAsStringAsync().Result; Assert.Greater(response.IndexOf(journalText), 0); @@ -342,10 +337,10 @@ public void Journal_Should_Only_Able_See_By_Members_When_Set_Security_To_Communi { int userId1, fileId1, userId2, fileId2; string username1, username2; - var connector1 = PrepareNewUser(out userId1, out username1, out fileId1); - var connector2 = PrepareNewUser(out userId2, out username2, out fileId2); + var connector1 = this.PrepareNewUser(out userId1, out username1, out fileId1); + var connector2 = this.PrepareNewUser(out userId2, out username2, out fileId2); - //POST JOURNAL + // POST JOURNAL var journalText = $"{username1} Post"; var postData = new { @@ -354,10 +349,10 @@ public void Journal_Should_Only_Able_See_By_Members_When_Set_Security_To_Communi groupId = -1, journalType = "file", securitySet = "C", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId1}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId1}\"}}", }; - connector1.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector1.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); var response = connector2.GetContent($"/Activity-Feed/userId/{userId1}").Content.ReadAsStringAsync().Result; Assert.Greater(response.IndexOf(journalText), 0); @@ -372,18 +367,17 @@ public void Journal_Should_Only_Able_See_By_Friends_When_Set_Security_To_Friends { int userId1, fileId1, userId2, fileId2, userId3, fileId3; string username1, username2, username3; - var connector1 = PrepareNewUser(out userId1, out username1, out fileId1); - var connector2 = PrepareNewUser(out userId2, out username2, out fileId2); - var connector3 = PrepareNewUser(out userId3, out username3, out fileId3); + var connector1 = this.PrepareNewUser(out userId1, out username1, out fileId1); + var connector2 = this.PrepareNewUser(out userId2, out username2, out fileId2); + var connector3 = this.PrepareNewUser(out userId3, out username3, out fileId3); - //ADD FRIENDS - connector1.PostJson("/API/MemberDirectory/MemberDirectory/AddFriend", new { friendId = userId2 }, GetRequestHeaders("Member Directory")); + // ADD FRIENDS + connector1.PostJson("/API/MemberDirectory/MemberDirectory/AddFriend", new { friendId = userId2 }, this.GetRequestHeaders("Member Directory")); var notificationId = DatabaseHelper.ExecuteScalar($"SELECT TOP 1 MessageID FROM {{objectQualifier}}CoreMessaging_Messages WHERE SenderUserID = {userId1}"); - connector2.PostJson("/API/InternalServices/RelationshipService/AcceptFriend", new { NotificationId = notificationId }, GetRequestHeaders()); - - - //POST JOURNAL + connector2.PostJson("/API/InternalServices/RelationshipService/AcceptFriend", new { NotificationId = notificationId }, this.GetRequestHeaders()); + + // POST JOURNAL var journalText = $"{username1} Post"; var postData = new { @@ -392,10 +386,10 @@ public void Journal_Should_Only_Able_See_By_Friends_When_Set_Security_To_Friends groupId = -1, journalType = "file", securitySet = "F", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId1}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId1}\"}}", }; - connector1.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector1.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); var response = connector2.GetContent($"/Activity-Feed/userId/{userId1}").Content.ReadAsStringAsync().Result; Assert.Greater(response.IndexOf(journalText), 0); @@ -409,9 +403,9 @@ public void Journal_Should_Only_Able_See_By_Himself_When_Set_Security_To_Private { int userId, fileId; string username; - var connector = PrepareNewUser(out userId, out username, out fileId); + var connector = this.PrepareNewUser(out userId, out username, out fileId); - //POST JOURNAL + // POST JOURNAL var journalText = $"{username} Post"; var postData = new { @@ -420,10 +414,10 @@ public void Journal_Should_Only_Able_See_By_Himself_When_Set_Security_To_Private groupId = -1, journalType = "file", securitySet = "P", - itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}" + itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; - connector.PostJson("/API/Journal/Services/Create", postData, GetRequestHeaders()); + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); var response = connector.GetContent($"/Activity-Feed/userId/{userId}").Content.ReadAsStringAsync().Result; Assert.Greater(response.IndexOf(journalText), 0); @@ -431,16 +425,11 @@ public void Journal_Should_Only_Able_See_By_Himself_When_Set_Security_To_Private var hostConnector = WebApiTestHelper.LoginHost(); response = hostConnector.GetContent($"/Activity-Feed/userId/{userId}").Content.ReadAsStringAsync().Result; Assert.AreEqual(response.IndexOf(journalText), -1); - } - - #endregion - - #region Private Methods - private static readonly Random rnd = new Random(); + } private IWebApiConnector PrepareNewUser(out int userId, out string username, out int fileId) { - return WebApiTestHelper.PrepareNewUser(out userId, out username, out fileId, PortalId); + return WebApiTestHelper.PrepareNewUser(out userId, out username, out fileId, this.PortalId); } private int CreateNewGroup(string roleName) @@ -458,10 +447,10 @@ private int CreateNewGroup(string roleName) status = 1, isPublic = true, autoAssign = false, - isSystem = false + isSystem = false, }); - return DatabaseHelper.ExecuteScalar($"SELECT RoleId FROM {{objectQualifier}}Roles WHERE RoleName = '{roleName}' AND PortalId = {PortalId}"); + return DatabaseHelper.ExecuteScalar($"SELECT RoleId FROM {{objectQualifier}}Roles WHERE RoleName = '{roleName}' AND PortalId = {this.PortalId}"); } private void AddUserToGroup(int groupId, int userId) @@ -473,15 +462,13 @@ private void AddUserToGroup(int groupId, int userId) { userId = userId, roleId = groupId, - isAdd = true + isAdd = true, }); } private IDictionary GetRequestHeaders(string moduleName = "Journal") { - return WebApiTestHelper.GetRequestHeaders("//ActivityFeed", moduleName, PortalId); - } - - #endregion + return WebApiTestHelper.GetRequestHeaders("//ActivityFeed", moduleName, this.PortalId); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs index 5ed89b630ee..65ab13c5583 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using Newtonsoft.Json; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.PersonaBar.Content.Pages { + using System; + using System.Collections.Generic; + using System.Linq; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using Newtonsoft.Json; + using NUnit.Framework; + [TestFixture] public class AddPageTests : IntegrationTestBase { @@ -26,11 +27,11 @@ public void Add_Multi_Pages_For_Exisitng_Shoul_Return_Results() { BulkPages = "Page_" + rnd, ParentId = -1, - Keywords = "", - Tags = "", + Keywords = string.Empty, + Tags = string.Empty, IncludeInMenu = true, StartDate = null, - EndDate = null + EndDate = null, }; Console.WriteLine(@"Add bulk pages request = {0}", JsonConvert.SerializeObject(addPagesDto)); @@ -46,18 +47,23 @@ public void Add_Multi_Pages_For_Exisitng_Shoul_Return_Results() Console.WriteLine(@"Verify bulk pages ersponse = {0}", response2); Assert.AreEqual(0, int.Parse(result2.Status.ToString())); Assert.IsNotNullOrEmpty(result2.Response.Pages.First().ErrorMessage); - } - - #region helper classes + } + [JsonObject] public class BulkPage { public string BulkPages { get; set; } + public int ParentId { get; set; } + public string Keywords { get; set; } + public string Tags { get; set; } + public bool IncludeInMenu { get; set; } + public DateTime? StartDate { get; set; } + public DateTime? EndDate { get; set; } } @@ -65,8 +71,11 @@ public class BulkPage public class BulkPageResponseItem { public string PageName { get; set; } + public int Status { get; set; } + public int TabId { get; set; } + public string ErrorMessage { get; set; } } @@ -74,6 +83,7 @@ public class BulkPageResponseItem public class BulkPageResponse { public int OverallStatus { get; set; } + public IEnumerable Pages { get; set; } } @@ -81,8 +91,8 @@ public class BulkPageResponse public class BulkPageResponseWrapper { public int Status { get; set; } + public BulkPageResponse Response { get; set; } - } - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs index 39fa1f9f6d8..344223607fe 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using DotNetNuke.Tests.Integration.Executers; -using DotNetNuke.Tests.Integration.Executers.Builders; -using Newtonsoft.Json; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.PersonaBar.Content.Pages { + using System; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Tests.Integration.Executers; + using DotNetNuke.Tests.Integration.Executers.Builders; + using Newtonsoft.Json; + using NUnit.Framework; + [TestFixture] public class PageUrlsTests : IntegrationTestBase { @@ -22,16 +23,15 @@ public class PageUrlsTests : IntegrationTestBase private const string UpdateLanguageApi = "/API/PersonaBar/SiteSettings/UpdateLanguage"; private const string CreateCustomUrlApi = "/API/PersonaBar/Pages/CreateCustomUrl"; private const string EnglishLanguageCode = "en-US"; - private const string SpainishLanguageCode = "es-ES"; - - #region Tests + private const string SpainishLanguageCode = "es-ES"; + [Test] public void Page_Url_Should_Able_To_Add_On_English_Disabled_Site() { var isEnglishEnabled = true; dynamic languageSettings = null; - //set default language to Spanish and disable en-US if it's enabled + // set default language to Spanish and disable en-US if it's enabled var connector = PrepareTest(out isEnglishEnabled, out languageSettings); var postData = new { @@ -39,26 +39,22 @@ public void Page_Url_Should_Able_To_Add_On_English_Disabled_Site() saveUrl = new { SiteAliasKey = 1, - Path = "/Path" + Guid.NewGuid().ToString().Replace("-", ""), + Path = "/Path" + Guid.NewGuid().ToString().Replace("-", string.Empty), QueryString = string.Empty, LocaleKey = 1, StatusCodeKey = 200, SiteAliasUsage = 2 - } + }, }; var response = connector.PostJson(CreateCustomUrlApi, postData, null).Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject(response); - //reset changes + // reset changes ResetChanges(connector, isEnglishEnabled, languageSettings); Assert.IsTrue(bool.Parse(result.Success.ToString())); - } - - #endregion - - #region Private Methods - + } + private static IWebApiConnector PrepareTest(out bool isEnglishEnabled, out dynamic languageSettings) { var connector = WebApiTestHelper.LoginHost(); @@ -76,10 +72,12 @@ private static IWebApiConnector PrepareTest(out bool isEnglishEnabled, out dynam connector.PostJson(AddLanguageApi, new { Code = SpainishLanguageCode }); UpdateLanguageSettings(connector, languageSettings, SpainishLanguageCode); } + if (isEnglishEnabled) { EnableEnglish(connector, false); } + return connector; } @@ -89,6 +87,7 @@ private static void ResetChanges(IWebApiConnector connector, bool isEnglishEnabl { EnableEnglish(connector, true); } + if (string.Compare(languageSettings.SiteDefaultLanguage.Value, EnglishLanguageCode, StringComparison.InvariantCultureIgnoreCase) == 0) { UpdateLanguageSettings(connector, languageSettings, EnglishLanguageCode); @@ -105,7 +104,7 @@ private static void UpdateLanguageSettings(IWebApiConnector connector, dynamic l languageSettings.EnableBrowserLanguage, languageSettings.AllowUserUICulture, languageSettings.CultureCode, - languageSettings.AllowContentLocalization + languageSettings.AllowContentLocalization, }); } @@ -115,7 +114,7 @@ private static void EnableEnglish(IWebApiConnector connector, bool enabled) { LanguageId = 1, Code = EnglishLanguageCode, - Enabled = enabled + Enabled = enabled, }); } @@ -127,8 +126,6 @@ private static int CreateNewPage(IWebApiConnector connector) var pageDetail = pagesExecuter.SavePageDetails(pageSettingsBuilder.Build()); Assert.NotNull(pageDetail.Page, "The system must create the page and return its details in the response"); return (int)pageDetail.Page.id; - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Manage/Users/UsersFiltersTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Manage/Users/UsersFiltersTests.cs index a7087489993..a7850730d22 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Manage/Users/UsersFiltersTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Manage/Users/UsersFiltersTests.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using Newtonsoft.Json; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.PersonaBar.Manage.Users { + using System; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using Newtonsoft.Json; + using NUnit.Framework; + [TestFixture] public class UsersFiltersTests : IntegrationTestBase { @@ -35,8 +36,8 @@ public override void TestFixtureSetUp() int userId, fileId; string userName; WebApiTestHelper.PrepareNewUser(out userId, out userName, out fileId); - _userIds[i] = userId; - _userNames[i] = userName; + this._userIds[i] = userId; + this._userNames[i] = userName; Console.WriteLine(@"Created test users => id: {0}, username: {1}", userId, userName); } @@ -44,23 +45,23 @@ public override void TestFixtureSetUp() var userIdx = 0; // make first user as admin - var makeAdminItem = new { RoleId = 0, UserId = _userIds[userIdx] }; + var makeAdminItem = new { RoleId = 0, UserId = this._userIds[userIdx] }; var response = hostConnector.PostJson(MakeAdminApi, makeAdminItem).Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject(response); - Assert.AreEqual(_userNames[userIdx], result.displayName.ToString()); + Assert.AreEqual(this._userNames[userIdx], result.displayName.ToString()); // Unauthorize the next 2 new users for (userIdx = 1; userIdx <= 2; userIdx++) { - var unauthorizeLink = string.Format(UnauthorizeApi, _userIds[userIdx]); - response = hostConnector.PostJson(unauthorizeLink, "").Content.ReadAsStringAsync().Result; + var unauthorizeLink = string.Format(UnauthorizeApi, this._userIds[userIdx]); + response = hostConnector.PostJson(unauthorizeLink, string.Empty).Content.ReadAsStringAsync().Result; result = JsonConvert.DeserializeObject(response); Assert.IsTrue(bool.Parse(result.Success.ToString())); } // soft delete the next new user - var deleteLink = string.Format(DeleteApi, _userIds[userIdx]); - response = hostConnector.PostJson(deleteLink, "").Content.ReadAsStringAsync().Result; + var deleteLink = string.Format(DeleteApi, this._userIds[userIdx]); + response = hostConnector.PostJson(deleteLink, string.Empty).Content.ReadAsStringAsync().Result; result = JsonConvert.DeserializeObject(response); Assert.IsTrue(bool.Parse(result.Success.ToString())); } @@ -94,7 +95,7 @@ public void GetUsersAsAdminWithVariousFiltersShoudlReturnExpectedResult(string a // Arrange: all is done in TestFixtureSetUp() // Act - var adminConnector = WebApiTestHelper.LoginUser(_userNames[0]); + var adminConnector = WebApiTestHelper.LoginUser(this._userNames[0]); var response = adminConnector.GetContent(apiMethod, null).Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject(response); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs index b31218c968f..e42c042ff91 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs @@ -1,40 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Net; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Tests.Integration.Executers; -using DotNetNuke.Tests.Integration.Executers.Builders; -using DotNetNuke.Tests.Integration.Executers.Dto; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.PersonaBar.Pages { + using System.Collections.Generic; + using System.Configuration; + using System.Linq; + using System.Net; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Tests.Integration.Executers; + using DotNetNuke.Tests.Integration.Executers.Builders; + using DotNetNuke.Tests.Integration.Executers.Dto; + using NUnit.Framework; + [TestFixture] public class PagesManagementTests : IntegrationTestBase - { - #region Fields - + { private readonly string _hostName; private readonly string _hostPass; - private readonly int PortalId = 0; - - #endregion - - #region SetUp - + private readonly int PortalId = 0; + public PagesManagementTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; - _hostName = ConfigurationManager.AppSettings["hostUsername"]; - _hostPass = ConfigurationManager.AppSettings["hostPassword"]; + this._hostName = ConfigurationManager.AppSettings["hostUsername"]; + this._hostPass = ConfigurationManager.AppSettings["hostPassword"]; } [TestFixtureSetUp] @@ -44,9 +39,9 @@ public override void TestFixtureSetUp() ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; - UpdateSslSettings(true); + this.UpdateSslSettings(true); - UpdateContentLocalization(true); + this.UpdateContentLocalization(true); } [TestFixtureTearDown] @@ -54,22 +49,18 @@ public override void TestFixtureTearDown() { base.TestFixtureTearDown(); - UpdateSslSettings(false); - - UpdateContentLocalization(false); - } - - #endregion - - #region Tests + this.UpdateSslSettings(false); + this.UpdateContentLocalization(false); + } + [Test] public void Page_Marked_As_Secure_Should_Able_To_Management_In_Insecure_Channel() { int tabId; - var connector = CreateNewSecurePage(out tabId); + var connector = this.CreateNewSecurePage(out tabId); - //Try to request the GetLocalization API + // Try to request the GetLocalization API var response = connector.GetContent($"API/PersonaBar/Pages/GetTabLocalization?pageId={tabId}", null, true, false); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } @@ -80,7 +71,7 @@ private void UpdateContentLocalization(bool enabled) var postData = new { - PortalId = PortalId, + PortalId = this.PortalId, ContentLocalizationEnabled = false, SystemDefaultLanguage = "English (United States)", SystemDefaultLanguageIcon = "/images/Flags/en-US.gif", @@ -90,29 +81,25 @@ private void UpdateContentLocalization(bool enabled) EnableBrowserLanguage = true, AllowUserUICulture = false, CultureCode = "en-US", - AllowContentLocalization = enabled + AllowContentLocalization = enabled, }; connector.PostJson("API/PersonaBar/SiteSettings/UpdateLanguageSettings", postData); connector.PostJson( enabled - ? $"API/PersonaBar/Languages/EnableLocalizedContent?portalId={PortalId}&translatePages=false" - : $"API/PersonaBar/Languages/DisableLocalizedContent?portalId={PortalId}", new {}); + ? $"API/PersonaBar/Languages/EnableLocalizedContent?portalId={this.PortalId}&translatePages=false" + : $"API/PersonaBar/Languages/DisableLocalizedContent?portalId={this.PortalId}", new { }); } private void UpdateSslSettings(bool sslEnabled) { var connector = WebApiTestHelper.LoginHost(); - var postData = new {SSLEnabled = sslEnabled, SSLEnforced = false, SSLURL = "", STDURL = "", SSLOffloadHeader = ""}; + var postData = new { SSLEnabled = sslEnabled, SSLEnforced = false, SSLURL = string.Empty, STDURL = string.Empty, SSLOffloadHeader = string.Empty }; connector.PostJson("API/PersonaBar/Security/UpdateSslSettings", postData); - } - - #endregion - - #region Private Methods - + } + private IWebApiConnector CreateNewSecurePage(out int tabId) { var pagesExecuter = new PagesExecuter { Connector = WebApiTestHelper.LoginHost() }; @@ -128,8 +115,6 @@ private IWebApiConnector CreateNewSecurePage(out int tabId) tabId = (int)pageDetail.Page.id; return pagesExecuter.Connector; - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Properties/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Properties/AssemblyInfo.cs index 8978e2ddb6b..ee5dff4a4a2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Properties/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Properties/AssemblyInfo.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Library.Tests")] [assembly: AssemblyDescription("Open Source Web Application Framework - Test Project")] @@ -16,27 +15,23 @@ [assembly: AssemblyProduct("http://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2018 by Dnn Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DotNetNuke")] - - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM componenets. If you need to access a type in this assembly from + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. 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("87fa9a95-fc7c-43d9-b548-a43988fcd5c1")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Revision and Build Numbers +// You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: - [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs index 9e8ca2283f2..1f36c87f6aa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs @@ -1,50 +1,72 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Diagnostics; -using System.IO; -using System.Reflection; -using System.Xml; - -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Services.Installer { + using System; + using System.Diagnostics; + using System.IO; + using System.Reflection; + using System.Xml; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class XmlMergeTests : DnnUnitTest { - private readonly Assembly _assembly = typeof (XmlMergeTests).Assembly; private const bool OutputXml = true; + private readonly Assembly _assembly = typeof(XmlMergeTests).Assembly; + + [SetUp] + public void SetUp() + { + AppDomain.CurrentDomain.SetData("APPBASE", this.WebsitePhysicalAppPath); + + LoggerSource.SetTestableInstance(new TestLogSource()); + } + + // ReSharper disable PossibleNullReferenceException + [Test] + public void SimpleUpdate() + { + XmlDocument targetDoc = this.ExecuteMerge(); + + // children are in correct location + XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); + Assert.AreEqual(2, nodes.Count); + + // children only inserted once + nodes = targetDoc.SelectNodes("//child"); + Assert.AreEqual(2, nodes.Count); + } /// /// Merges the Merge and Target files based on the name of the calling method. /// - /// xml files must be embedded resources in the MergeFiles folder named {method}Merge.xml and {method}Target.xml - /// XmlDocument with the result of the merge operation + /// xml files must be embedded resources in the MergeFiles folder named {method}Merge.xml and {method}Target.xml. + /// XmlDocument with the result of the merge operation. private XmlDocument ExecuteMerge() { - return ExecuteMerge(null); + return this.ExecuteMerge(null); } /// - /// As ExecuteMerge but allows the merge file prefix to be specified + /// As ExecuteMerge but allows the merge file prefix to be specified. /// private XmlDocument ExecuteMerge(string mergeName) { - string testMethodName = GetTestMethodName(); + string testMethodName = this.GetTestMethodName(); - XmlMerge merge = GetXmlMerge(mergeName ?? testMethodName); - XmlDocument targetDoc = LoadTargetDoc(testMethodName); + XmlMerge merge = this.GetXmlMerge(mergeName ?? testMethodName); + XmlDocument targetDoc = this.LoadTargetDoc(testMethodName); merge.UpdateConfig(targetDoc); - WriteToDebug(targetDoc); + this.WriteToDebug(targetDoc); return targetDoc; } @@ -59,7 +81,8 @@ private string GetTestMethodName() { name = st.GetFrame(i).GetMethod().Name; i++; - } while (name == "ExecuteMerge"); + } + while (name == "ExecuteMerge"); return name; } @@ -67,11 +90,13 @@ private string GetTestMethodName() private XmlDocument LoadTargetDoc(string testMethodName) { using (Stream targetStream = - _assembly.GetManifestResourceStream(string.Format("DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Target.xml", - testMethodName))) + this._assembly.GetManifestResourceStream(string.Format( + "DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Target.xml", + testMethodName))) { - Debug.Assert(targetStream != null, - string.Format("Unable to location embedded resource for {0}Target.xml", testMethodName)); + Debug.Assert( + targetStream != null, + string.Format("Unable to location embedded resource for {0}Target.xml", testMethodName)); var targetDoc = new XmlDocument { XmlResolver = null }; targetDoc.Load(targetStream); return targetDoc; @@ -81,21 +106,24 @@ private XmlDocument LoadTargetDoc(string testMethodName) private XmlMerge GetXmlMerge(string fileName) { using (Stream mergeStream = - _assembly.GetManifestResourceStream(string.Format("DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Merge.xml", - fileName))) + this._assembly.GetManifestResourceStream(string.Format( + "DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Merge.xml", + fileName))) { - Debug.Assert(mergeStream != null, - string.Format("Unable to location embedded resource for {0}Merge.xml", fileName)); + Debug.Assert( + mergeStream != null, + string.Format("Unable to location embedded resource for {0}Merge.xml", fileName)); var merge = new XmlMerge(mergeStream, "version", "sender"); return merge; } } private void WriteToDebug(XmlDocument targetDoc) - { -// ReSharper disable ConditionIsAlwaysTrueOrFalse - if (OutputXml) -// ReSharper restore ConditionIsAlwaysTrueOrFalse + { + // ReSharper disable ConditionIsAlwaysTrueOrFalse + if (OutputXml) + + // ReSharper restore ConditionIsAlwaysTrueOrFalse { using (var writer = new StreamWriter(new MemoryStream())) { @@ -109,39 +137,16 @@ private void WriteToDebug(XmlDocument targetDoc) } } - [SetUp] - public void SetUp() - { - AppDomain.CurrentDomain.SetData("APPBASE", WebsitePhysicalAppPath); - - LoggerSource.SetTestableInstance(new TestLogSource()); - } - -// ReSharper disable PossibleNullReferenceException - [Test] - public void SimpleUpdate() - { - XmlDocument targetDoc = ExecuteMerge(); - - //children are in correct location - XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); - Assert.AreEqual(2, nodes.Count); - - //children only inserted once - nodes = targetDoc.SelectNodes("//child"); - Assert.AreEqual(2, nodes.Count); - } - [Test] public void SimpleUpdateInLocation() { - XmlDocument targetDoc = ExecuteMerge("SimpleUpdate"); + XmlDocument targetDoc = this.ExecuteMerge("SimpleUpdate"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/location/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); } @@ -149,13 +154,13 @@ public void SimpleUpdateInLocation() [Test] public void SimpleUpdateInLocationWithDistractingLocations() { - XmlDocument targetDoc = ExecuteMerge("SimpleUpdate"); + XmlDocument targetDoc = this.ExecuteMerge("SimpleUpdate"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/location/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); } @@ -163,13 +168,13 @@ public void SimpleUpdateInLocationWithDistractingLocations() [Test] public void UpdateWithTargetPath() { - XmlDocument targetDoc = ExecuteMerge(); + XmlDocument targetDoc = this.ExecuteMerge(); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); } @@ -177,13 +182,13 @@ public void UpdateWithTargetPath() [Test] public void UpdateInLocationWithTargetPath() { - XmlDocument targetDoc = ExecuteMerge("UpdateWithTargetPath"); + XmlDocument targetDoc = this.ExecuteMerge("UpdateWithTargetPath"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/location/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); } @@ -191,13 +196,13 @@ public void UpdateInLocationWithTargetPath() [Test] public void UpdateWithDistractingLocationAndTargetPath() { - XmlDocument targetDoc = ExecuteMerge("UpdateWithTargetPath"); + XmlDocument targetDoc = this.ExecuteMerge("UpdateWithTargetPath"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); } @@ -205,13 +210,13 @@ public void UpdateWithDistractingLocationAndTargetPath() [Test] public void UpdateInLocationWithDistractingLocationAndTargetPath() { - XmlDocument targetDoc = ExecuteMerge("UpdateWithTargetPath"); + XmlDocument targetDoc = this.ExecuteMerge("UpdateWithTargetPath"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/location/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); } @@ -219,24 +224,24 @@ public void UpdateInLocationWithDistractingLocationAndTargetPath() [Test] public void UpdateInFirstLocationWithDistractingLocationAndTargetPath() { - XmlDocument targetDoc = ExecuteMerge("UpdateWithTargetPath"); + XmlDocument targetDoc = this.ExecuteMerge("UpdateWithTargetPath"); - //children are in correct location - //first location/updateme has updated node + // children are in correct location + // first location/updateme has updated node XmlNode root = targetDoc.SelectSingleNode("/configuration/location[1]"); XmlNodeList nodes = root.SelectNodes("updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //second location/updateme still empty + // second location/updateme still empty root = targetDoc.SelectSingleNode("/configuration/location[2]"); nodes = root.SelectNodes("updateme/children/child"); Assert.AreEqual(0, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); - //two instances of location/updateme exist + // two instances of location/updateme exist nodes = targetDoc.SelectNodes("//configuration/location/updateme"); Assert.AreEqual(2, nodes.Count); } @@ -244,9 +249,9 @@ public void UpdateInFirstLocationWithDistractingLocationAndTargetPath() [Test] public void SimpleAdd() { - XmlDocument targetDoc = ExecuteMerge(); + XmlDocument targetDoc = this.ExecuteMerge(); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); Assert.AreEqual(2, nodes.Count); } @@ -254,22 +259,22 @@ public void SimpleAdd() [Test] public void AddWithLocation() { - XmlDocument targetDoc = ExecuteMerge("SimpleAdd"); + XmlDocument targetDoc = this.ExecuteMerge("SimpleAdd"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //second location/updateme still empty + // second location/updateme still empty var root = targetDoc.SelectSingleNode("/configuration/location[2]"); nodes = root.SelectNodes("updateme/children/child"); Assert.AreEqual(0, nodes.Count); - //children only inserted once + // children only inserted once nodes = targetDoc.SelectNodes("//child"); Assert.AreEqual(2, nodes.Count); - //1 instance of location/updateme exist + // 1 instance of location/updateme exist nodes = targetDoc.SelectNodes("//configuration/location/updateme"); Assert.AreEqual(1, nodes.Count); } @@ -277,13 +282,13 @@ public void AddWithLocation() [Test] public void SimpleInsertBefore() { - XmlDocument targetDoc = ExecuteMerge(); + XmlDocument targetDoc = this.ExecuteMerge(); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //inserted before node2 + // inserted before node2 XmlNode node = targetDoc.SelectSingleNode("/configuration/updateme"); Assert.AreEqual("node2", node.NextSibling.Name); } @@ -291,13 +296,13 @@ public void SimpleInsertBefore() [Test] public void InsertBeforeInLocation() { - XmlDocument targetDoc = ExecuteMerge("SimpleInsertBefore"); + XmlDocument targetDoc = this.ExecuteMerge("SimpleInsertBefore"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/location/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //inserted before node2 + // inserted before node2 XmlNode node = targetDoc.SelectSingleNode("/configuration/location/updateme"); Assert.AreEqual("node2", node.NextSibling.Name); } @@ -305,13 +310,13 @@ public void InsertBeforeInLocation() [Test] public void SimpleInsertAfter() { - XmlDocument targetDoc = ExecuteMerge(); + XmlDocument targetDoc = this.ExecuteMerge(); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //inserted before node2 + // inserted before node2 XmlNode node = targetDoc.SelectSingleNode("/configuration/updateme"); Assert.AreEqual("node1", node.PreviousSibling.Name); } @@ -319,13 +324,13 @@ public void SimpleInsertAfter() [Test] public void InsertAfterInLocation() { - XmlDocument targetDoc = ExecuteMerge("SimpleInsertAfter"); + XmlDocument targetDoc = this.ExecuteMerge("SimpleInsertAfter"); - //children are in correct location + // children are in correct location XmlNodeList nodes = targetDoc.SelectNodes("/configuration/location/updateme/children/child"); Assert.AreEqual(2, nodes.Count); - //inserted before node2 + // inserted before node2 XmlNode node = targetDoc.SelectSingleNode("/configuration/location/updateme"); Assert.AreEqual("node2", node.NextSibling.Name); } @@ -333,13 +338,13 @@ public void InsertAfterInLocation() [Test] public void SimpleRemove() { - XmlDocument targetDoc = ExecuteMerge(); + XmlDocument targetDoc = this.ExecuteMerge(); - //node is gone + // node is gone var nodes = targetDoc.SelectNodes("//removeme"); Assert.AreEqual(0, nodes.Count); - //other nodes still present + // other nodes still present nodes = targetDoc.SelectNodes("/configuration/distraction"); Assert.AreEqual(1, nodes.Count); } @@ -347,13 +352,13 @@ public void SimpleRemove() [Test] public void RemoveFromLocation() { - XmlDocument targetDoc = ExecuteMerge("SimpleRemove"); + XmlDocument targetDoc = this.ExecuteMerge("SimpleRemove"); - //node is gone + // node is gone var nodes = targetDoc.SelectNodes("//removeme"); Assert.AreEqual(0, nodes.Count); - //other nodes still present + // other nodes still present nodes = targetDoc.SelectNodes("/configuration/distraction"); Assert.AreEqual(1, nodes.Count); } @@ -361,7 +366,7 @@ public void RemoveFromLocation() [Test] public void SimpleRemoveAttribute() { - var targetDoc = ExecuteMerge(); + var targetDoc = this.ExecuteMerge(); var node = targetDoc.SelectSingleNode("/configuration/updateme"); Assert.AreEqual(0, node.Attributes.Count); @@ -370,7 +375,7 @@ public void SimpleRemoveAttribute() [Test] public void RemoveAttributeFromLocation() { - var targetDoc = ExecuteMerge("SimpleRemoveAttribute"); + var targetDoc = this.ExecuteMerge("SimpleRemoveAttribute"); var node = targetDoc.SelectSingleNode("/configuration/location/updateme"); Assert.AreEqual(0, node.Attributes.Count); @@ -379,7 +384,7 @@ public void RemoveAttributeFromLocation() [Test] public void SimpleInsertAttribute() { - var targetDoc = ExecuteMerge(); + var targetDoc = this.ExecuteMerge(); var node = targetDoc.SelectSingleNode("/configuration/updateme"); Assert.AreEqual(2, node.Attributes.Count); @@ -389,7 +394,7 @@ public void SimpleInsertAttribute() [Test] public void InsertAttributeInLocation() { - var targetDoc = ExecuteMerge("SimpleInsertAttribute"); + var targetDoc = this.ExecuteMerge("SimpleInsertAttribute"); var node = targetDoc.SelectSingleNode("/configuration/location/updateme"); Assert.AreEqual(2, node.Attributes.Count); @@ -399,7 +404,7 @@ public void InsertAttributeInLocation() [Test] public void UpdateAttributeInLocation() { - var targetDoc = ExecuteMerge("SimpleInsertAttribute"); + var targetDoc = this.ExecuteMerge("SimpleInsertAttribute"); var node = targetDoc.SelectSingleNode("/configuration/location/updateme"); Assert.AreEqual(2, node.Attributes.Count); @@ -409,69 +414,67 @@ public void UpdateAttributeInLocation() [Test] public void SimpleUpdateWithKey() { - var targetDoc = ExecuteMerge(); + var targetDoc = this.ExecuteMerge(); - //a key was added + // a key was added var nodes = targetDoc.SelectNodes("/configuration/updateme/add"); Assert.AreEqual(1, nodes.Count); - - //test attribute is set + + // test attribute is set var node = nodes[0]; Assert.AreEqual("foo", node.Attributes["test"].Value); - } [Test] public void UpdateWithKeyInLocation() { - var targetDoc = ExecuteMerge("SimpleUpdateWithKey"); + var targetDoc = this.ExecuteMerge("SimpleUpdateWithKey"); - //a key was added + // a key was added var nodes = targetDoc.SelectNodes("/configuration/location/updateme/add"); Assert.AreEqual(1, nodes.Count); - //test attribute is set + // test attribute is set var node = nodes[0]; Assert.AreEqual("foo", node.Attributes["test"].Value); - } [Test] public void NoChangeOnOverwrite() { - XmlMerge merge = GetXmlMerge(nameof(NoChangeOnOverwrite)); - XmlDocument targetDoc = LoadTargetDoc(nameof(NoChangeOnOverwrite)); + XmlMerge merge = this.GetXmlMerge(nameof(this.NoChangeOnOverwrite)); + XmlDocument targetDoc = this.LoadTargetDoc(nameof(this.NoChangeOnOverwrite)); merge.UpdateConfig(targetDoc); - WriteToDebug(targetDoc); + this.WriteToDebug(targetDoc); var nodes = targetDoc.SelectNodes("/configuration/appSettings/add"); Assert.AreEqual(3, nodes.Count); - + Assert.False(merge.ConfigUpdateChangedNodes); } [Test] public void ShouldChangeOnOverwrite() { - XmlMerge merge = GetXmlMerge(nameof(ShouldChangeOnOverwrite)); - XmlDocument targetDoc = LoadTargetDoc(nameof(ShouldChangeOnOverwrite)); + XmlMerge merge = this.GetXmlMerge(nameof(this.ShouldChangeOnOverwrite)); + XmlDocument targetDoc = this.LoadTargetDoc(nameof(this.ShouldChangeOnOverwrite)); merge.UpdateConfig(targetDoc); - WriteToDebug(targetDoc); + this.WriteToDebug(targetDoc); var nodes = targetDoc.SelectNodes("/configuration/appSettings/add"); Assert.AreEqual(3, nodes.Count); - + Assert.True(merge.ConfigUpdateChangedNodes); } [Test] public void ShouldPreserveEmptyNamespaceOnSave() { - var targetDoc = ExecuteMerge(); + var targetDoc = this.ExecuteMerge(); var ns = new XmlNamespaceManager(targetDoc.NameTable); ns.AddNamespace("ab", "urn:schemas-microsoft-com:asm.v1"); @@ -488,152 +491,150 @@ public void ShouldPreserveEmptyNamespaceOnSave() var dependentAssembly = nodesWithoutNamespace[0]; var bindingRedirect = dependentAssembly.SelectSingleNode("bindingRedirect", ns); Assert.AreEqual("4.1.0.0", bindingRedirect.Attributes["newVersion"].Value); + } + + // ReSharper restore PossibleNullReferenceException + } + + internal class TestLogSource : ILoggerSource + { + public ILog GetLogger(string name) + { + return new TestLogger(); } -// ReSharper restore PossibleNullReferenceException + public ILog GetLogger(Type type) + { + return new TestLogger(); + } } - class TestLogSource : ILoggerSource - { - - public ILog GetLogger(string name) - { - return new TestLogger(); - } - - public ILog GetLogger(Type type) - { - return new TestLogger(); - } - } - - class TestLogger : ILog - { - - public void Debug(object message, Exception exception) - { - } - - public void Debug(object message) - { - } - - public void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - } - - public void DebugFormat(string format, params object[] args) - { - } - - public void Error(object message, Exception exception) - { - } - - public void Error(object message) - { - } - - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - } - - public void ErrorFormat(string format, params object[] args) - { - } - - public void Fatal(object message, Exception exception) - { - } - - public void Fatal(object message) - { - } - - public void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - } - - public void FatalFormat(string format, params object[] args) - { - } - - public void Info(object message, Exception exception) - { - } - - public void Info(object message) - { - } - - public void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - } - - public void InfoFormat(string format, params object[] args) - { - } - - public bool IsDebugEnabled - { - get { return false; } - } - - public bool IsErrorEnabled - { - get { return false; } - } - - public bool IsFatalEnabled - { - get { return false; } - } - - public bool IsInfoEnabled - { - get { return false; } - } - - public bool IsTraceEnabled - { - get { return false; } - } - - public bool IsWarnEnabled - { - get { return false; } - } - - public void Trace(object message, Exception exception) - { - } - - public void Trace(object message) - { - } - - public void TraceFormat(IFormatProvider provider, string format, params object[] args) - { - } - - public void TraceFormat(string format, params object[] args) - { - } - - public void Warn(object message, Exception exception) - { - } - - public void Warn(object message) - { - } - - public void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - } - - public void WarnFormat(string format, params object[] args) - { - } - } + internal class TestLogger : ILog + { + public bool IsDebugEnabled + { + get { return false; } + } + + public bool IsErrorEnabled + { + get { return false; } + } + + public bool IsFatalEnabled + { + get { return false; } + } + + public void Debug(object message, Exception exception) + { + } + + public void Debug(object message) + { + } + + public void DebugFormat(IFormatProvider provider, string format, params object[] args) + { + } + + public void DebugFormat(string format, params object[] args) + { + } + + public void Error(object message, Exception exception) + { + } + + public void Error(object message) + { + } + + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + } + + public void ErrorFormat(string format, params object[] args) + { + } + + public void Fatal(object message, Exception exception) + { + } + + public void Fatal(object message) + { + } + + public void FatalFormat(IFormatProvider provider, string format, params object[] args) + { + } + + public void FatalFormat(string format, params object[] args) + { + } + + public void Info(object message, Exception exception) + { + } + + public void Info(object message) + { + } + + public void InfoFormat(IFormatProvider provider, string format, params object[] args) + { + } + + public void InfoFormat(string format, params object[] args) + { + } + + public bool IsInfoEnabled + { + get { return false; } + } + + public bool IsTraceEnabled + { + get { return false; } + } + + public bool IsWarnEnabled + { + get { return false; } + } + + public void Trace(object message, Exception exception) + { + } + + public void Trace(object message) + { + } + + public void TraceFormat(IFormatProvider provider, string format, params object[] args) + { + } + + public void TraceFormat(string format, params object[] args) + { + } + + public void Warn(object message, Exception exception) + { + } + + public void Warn(object message) + { + } + + public void WarnFormat(IFormatProvider provider, string format, params object[] args) + { + } + + public void WarnFormat(string format, params object[] args) + { + } + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/TestSetup.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/TestSetup.cs index ec9f43a19e8..d2be7df99f3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/TestSetup.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/TestSetup.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + /* using DotNetNuke.Tests.Utilities.Mocks; using NUnit.Framework; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs index 76605c54f28..4867dc352c7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs @@ -1,51 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Configuration; -using System.Net; -using System.Net.Http; -using System.Web; -using DNN.Integration.Test.Framework; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Tests.DotNetNukeWeb { + using System; + using System.Configuration; + using System.Net; + using System.Net.Http; + using System.Web; + + using DNN.Integration.Test.Framework; + using NUnit.Framework; + [TestFixture] public class DotNetNukeWebTests : IntegrationTestBase - { - #region private data - + { + private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; + private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; + private readonly HttpClient _httpClient; private readonly TimeSpan _timeout = TimeSpan.FromSeconds(30); - private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; - private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; - public DotNetNukeWebTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; var siteUri = new Uri(url); - _httpClient = new HttpClient { BaseAddress = siteUri, Timeout = _timeout }; - } - - #endregion - - #region tests - + this._httpClient = new HttpClient { BaseAddress = siteUri, Timeout = this._timeout }; + } + [Test] [TestCase(GetMonikerQuery)] [TestCase(GetModuleDetailsQuery)] public void CallingHelperForAnonymousUserShouldReturnSuccess(string query) { - var result = _httpClient.GetAsync(query + HttpUtility.UrlEncode("ViewProfile")).Result; + var result = this._httpClient.GetAsync(query + HttpUtility.UrlEncode("ViewProfile")).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs index 847263f6a7e..ee2364f81ec 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs @@ -1,33 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Controllers; -using DNN.Integration.Test.Framework.Helpers; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Profile; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Localization; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Tests { + using System; + using System.Collections.Generic; + using System.Configuration; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Controllers; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Profile; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using NUnit.Framework; + public class FriendsTests : IntegrationTestBase { - private const int PortalId = 0; private const string FirstLanguage = "en-US"; private const string SecondLanguage = "fr-FR"; @@ -40,40 +40,39 @@ public void SetUp() ComponentFactory.RegisterComponentInstance(new SqlDataProvider()); ComponentFactory.RegisterComponentSettings(new Dictionary() { - {"name", "SqlDataProvider"}, - {"type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke"}, - {"connectionStringName", "SiteSqlServer"}, - {"objectQualifier", ConfigurationManager.AppSettings["objectQualifier"]}, - {"databaseOwner", "dbo."} + { "name", "SqlDataProvider" }, + { "type", "DotNetNuke.Data.SqlDataProvider, DotNetNuke" }, + { "connectionStringName", "SiteSqlServer" }, + { "objectQualifier", ConfigurationManager.AppSettings["objectQualifier"] }, + { "databaseOwner", "dbo." }, }); ComponentFactory.InstallComponents(new ProviderInstaller("caching", typeof(CachingProvider), typeof(FBCachingProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("members", typeof(MembershipProvider), typeof(AspNetMembershipProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("profiles", typeof(ProfileProvider), typeof(DNNProfileProvider))); - } [Test] public void Friend_Request_Should_Match_Target_User_Culture() { - PrepareSecondLanguage(); + this.PrepareSecondLanguage(); int userId1, userId2, fileId1, fileId2; string userName1, userName2; - CreateNewUser(out userId1, out userName1, out fileId1); - CreateNewUser(out userId2, out userName2, out fileId2); + this.CreateNewUser(out userId1, out userName1, out fileId1); + this.CreateNewUser(out userId2, out userName2, out fileId2); - UpdateUserProfile(userId1, UserProfile.USERPROFILE_PreferredLocale, FirstLanguage); - UpdateUserProfile(userId2, UserProfile.USERPROFILE_PreferredLocale, SecondLanguage); + this.UpdateUserProfile(userId1, UserProfile.USERPROFILE_PreferredLocale, FirstLanguage); + this.UpdateUserProfile(userId2, UserProfile.USERPROFILE_PreferredLocale, SecondLanguage); WebApiTestHelper.ClearHostCache(); var connector = WebApiTestHelper.LoginUser(userName1); connector.PostJson("API/MemberDirectory/MemberDirectory/AddFriend", new { - friendId = userId2 - }, GetRequestHeaders()); + friendId = userId2, + }, this.GetRequestHeaders()); - var notificationTitle = GetNotificationTitle(userId1); + var notificationTitle = this.GetNotificationTitle(userId1); - //the notification should use french language: testuser8836 veut être amis avec vous + // the notification should use french language: testuser8836 veut être amis avec vous Assert.AreEqual($"{userName1} veut être amis", notificationTitle); } @@ -90,23 +89,22 @@ private void UpdateUserProfile(int userId, string propertyName, string propertyV private void PrepareSecondLanguage() { - if (!LanguageEnabled(PortalId, SecondLanguage)) + if (!this.LanguageEnabled(PortalId, SecondLanguage)) { - } } private bool LanguageEnabled(int portalId, string secondLanguage) { - var portalLanguages = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguagesByPortal(portalId)); + var portalLanguages = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguagesByPortal(portalId)); if (!portalLanguages.ContainsKey(secondLanguage)) { var connector = WebApiTestHelper.LoginHost(); - connector.PostJson($"API/PersonaBar/Extensions/ParseLanguagePackage?cultureCode={secondLanguage}", new {}); + connector.PostJson($"API/PersonaBar/Extensions/ParseLanguagePackage?cultureCode={secondLanguage}", new { }); connector.PostJson($"API/PersonaBar/Extensions/InstallAvailablePackage", new { PackageType = "CoreLanguagePack", - FileName = "installlanguage.resources" + FileName = "installlanguage.resources", }); var language = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguages())[secondLanguage]; @@ -117,9 +115,10 @@ private bool LanguageEnabled(int portalId, string secondLanguage) Code = language.Code, Enabled = true, IsDefault = false, - Roles = "Administrators" + Roles = "Administrators", }); } + return false; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs index c1574e327dd..f1c7476e0d0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs @@ -1,32 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Configuration; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading; -using System.Web; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using Newtonsoft.Json; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Tests.Jwt { + using System; + using System.Configuration; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Threading; + using System.Web; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using Newtonsoft.Json; + using NUnit.Framework; + [TestFixture] public class JwtAuthTest : IntegrationTestBase - { - #region private data + { + public const string ExtendTokenQuery = "/API/JwtAuth/mobile/extendtoken"; + private const string LoginQuery = "/API/JwtAuth/mobile/login"; + private const string LogoutQuery = "/API/JwtAuth/mobile/logout"; + private const string TestGetQuery = "/API/JwtAuth/mobile/testget"; + private const string TestPostQuery = "/API/JwtAuth/mobile/testpost"; + private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; + private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; + private static readonly Encoding TextEncoder = Encoding.UTF8; private readonly string _hostName; private readonly string _hostPass; private readonly HttpClient _httpClient; - - private static readonly Encoding TextEncoder = Encoding.UTF8; #if DEBUG // for degugging and setting breakpoints private readonly TimeSpan _timeout = TimeSpan.FromSeconds(300); @@ -34,21 +40,13 @@ public class JwtAuthTest : IntegrationTestBase private readonly TimeSpan _timeout = TimeSpan.FromSeconds(30); #endif - private const string LoginQuery = "/API/JwtAuth/mobile/login"; - private const string LogoutQuery = "/API/JwtAuth/mobile/logout"; - public const string ExtendTokenQuery = "/API/JwtAuth/mobile/extendtoken"; - private const string TestGetQuery = "/API/JwtAuth/mobile/testget"; - private const string TestPostQuery = "/API/JwtAuth/mobile/testpost"; - private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; - private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; - public JwtAuthTest() { var url = ConfigurationManager.AppSettings["siteUrl"]; var siteUri = new Uri(url); - _httpClient = new HttpClient { BaseAddress = siteUri, Timeout = _timeout }; - _hostName = ConfigurationManager.AppSettings["hostUsername"]; - _hostPass = ConfigurationManager.AppSettings["hostPassword"]; + this._httpClient = new HttpClient { BaseAddress = siteUri, Timeout = this._timeout }; + this._hostName = ConfigurationManager.AppSettings["hostUsername"]; + this._hostPass = ConfigurationManager.AppSettings["hostPassword"]; } [TestFixtureSetUp] @@ -57,24 +55,22 @@ public override void TestFixtureSetUp() base.TestFixtureSetUp(); try { - if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) - DatabaseHelper.ExecuteNonQuery("TRUNCATE TABLE {objectQualifier}JsonWebTokens"); + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) + { + DatabaseHelper.ExecuteNonQuery("TRUNCATE TABLE {objectQualifier}JsonWebTokens"); + } } catch (Exception) { // ignored } - } - - #endregion - - #region tests - + } + [Test] public void InvalidUserLoginShouldFail() { - var credentials = new { u = _hostName, p = _hostPass + "." }; - var result = _httpClient.PostAsJsonAsync(LoginQuery, credentials).Result; + var credentials = new { u = this._hostName, p = this._hostPass + "." }; + var result = this._httpClient.PostAsJsonAsync(LoginQuery, credentials).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); @@ -83,7 +79,7 @@ public void InvalidUserLoginShouldFail() [Test] public void ValidUserLoginShouldPass() { - var token = GetAuthorizationTokenFor(_hostName, _hostPass); + var token = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); Assert.IsNotNull(token.UserId); Assert.IsNotNull(token.AccessToken); Assert.IsNotNull(token.DisplayName); @@ -101,18 +97,18 @@ public void ValidUserLoginShouldPass() [Test] public void RequestUsingInvaldatedTokenAfterLogoutShouldFail() { - var token = GetAuthorizationTokenFor(_hostName, _hostPass); + var token = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); - SetAuthHeaderToken(token.AccessToken); - var result1 = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(token.AccessToken); + var result1 = this._httpClient.GetAsync(TestGetQuery).Result; var content1 = result1.Content.ReadAsStringAsync().Result; LogText(@"content1 => " + content1); Assert.AreEqual(HttpStatusCode.OK, result1.StatusCode); - LogoutUser(token.AccessToken); + this.LogoutUser(token.AccessToken); - SetAuthHeaderToken(token.AccessToken); - var result2 = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(token.AccessToken); + var result2 = this._httpClient.GetAsync(TestGetQuery).Result; var content2 = result2.Content.ReadAsStringAsync().Result; LogText(@"content2 => " + content2); Assert.AreEqual(HttpStatusCode.Unauthorized, result2.StatusCode); @@ -121,7 +117,7 @@ public void RequestUsingInvaldatedTokenAfterLogoutShouldFail() [Test] public void RequestWithoutTokenShouldFail() { - var result = _httpClient.GetAsync(TestGetQuery).Result; + var result = this._httpClient.GetAsync(TestGetQuery).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); @@ -130,9 +126,9 @@ public void RequestWithoutTokenShouldFail() [Test] public void ValidatedUserGetRequestShouldPass() { - var token = GetAuthorizationTokenFor(_hostName, _hostPass); - SetAuthHeaderToken(token.AccessToken); - var result = _httpClient.GetAsync(TestGetQuery).Result; + var token = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + this.SetAuthHeaderToken(token.AccessToken); + var result = this._httpClient.GetAsync(TestGetQuery).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); @@ -142,9 +138,9 @@ public void ValidatedUserGetRequestShouldPass() [Test] public void ValidatedUserPostRequestShouldPass() { - var token = GetAuthorizationTokenFor(_hostName, _hostPass); - SetAuthHeaderToken(token.AccessToken); - var result = _httpClient.PostAsJsonAsync(TestPostQuery, new { text = "Integraton Testing Rocks!" }).Result; + var token = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + this.SetAuthHeaderToken(token.AccessToken); + var result = this._httpClient.PostAsJsonAsync(TestPostQuery, new { text = "Integraton Testing Rocks!" }).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); @@ -155,8 +151,8 @@ public void ValidatedUserPostRequestShouldPass() [Test] public void RenewValidTokenShouldPass() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); - var token2 = RenewAuthorizationToken(token1); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + var token2 = this.RenewAuthorizationToken(token1); Assert.AreNotEqual(token1.AccessToken, token2.AccessToken); Assert.AreEqual(token1.RenewalToken, token2.RenewalToken); Assert.AreEqual(token1.DisplayName, token2.DisplayName); @@ -165,14 +161,14 @@ public void RenewValidTokenShouldPass() [Test] public void UsingOriginalAccessTokenAfterRenewalShouldFail() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); - var token2 = RenewAuthorizationToken(token1); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + var token2 = this.RenewAuthorizationToken(token1); Assert.AreNotEqual(token1.AccessToken, token2.AccessToken); Assert.AreEqual(token1.RenewalToken, token2.RenewalToken); Assert.AreEqual(token1.DisplayName, token2.DisplayName); - SetAuthHeaderToken(token1.AccessToken); - var result = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(token1.AccessToken); + var result = this._httpClient.GetAsync(TestGetQuery).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); @@ -181,34 +177,34 @@ public void UsingOriginalAccessTokenAfterRenewalShouldFail() [Test] public void TryingToRenewUsingSameTokenMoreTHanOneTimeShouldFail() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); - RenewAuthorizationToken(token1); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + this.RenewAuthorizationToken(token1); - SetAuthHeaderToken(token1.AccessToken); - var result = _httpClient.PostAsJsonAsync(ExtendTokenQuery, new { rtoken = token1.RenewalToken }).Result; + this.SetAuthHeaderToken(token1.AccessToken); + var result = this._httpClient.PostAsJsonAsync(ExtendTokenQuery, new { rtoken = token1.RenewalToken }).Result; Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); } [Test] public void RenewMultipleTimesShouldPass() { - RenewAuthorizationToken( - RenewAuthorizationToken( - RenewAuthorizationToken( - GetAuthorizationTokenFor(_hostName, _hostPass)))); + this.RenewAuthorizationToken( + this.RenewAuthorizationToken( + this.RenewAuthorizationToken( + this.GetAuthorizationTokenFor(this._hostName, this._hostPass)))); } [Test] public void UsingTheNewAccessTokenAfterRenewalShouldPass() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); - var token2 = RenewAuthorizationToken(token1); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + var token2 = this.RenewAuthorizationToken(token1); Assert.AreNotEqual(token1.AccessToken, token2.AccessToken); Assert.AreEqual(token1.RenewalToken, token2.RenewalToken); Assert.AreEqual(token1.DisplayName, token2.DisplayName); - SetAuthHeaderToken(token2.AccessToken); - var result = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(token2.AccessToken); + var result = this._httpClient.GetAsync(TestGetQuery).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); @@ -217,18 +213,18 @@ public void UsingTheNewAccessTokenAfterRenewalShouldPass() [Test] public void TamperedTokenShouldFail() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); // tampered header - SetAuthHeaderToken("x" + token1.AccessToken); - var result = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken("x" + token1.AccessToken); + var result = this._httpClient.GetAsync(TestGetQuery).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); // tampered signature - SetAuthHeaderToken(token1.AccessToken + "y"); - result = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(token1.AccessToken + "y"); + result = this._httpClient.GetAsync(TestGetQuery).Result; content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); @@ -236,8 +232,8 @@ public void TamperedTokenShouldFail() // tampered claims var idx = token1.AccessToken.IndexOf('.'); var tampered = token1.AccessToken.Substring(0, idx + 10) + "z" + token1.AccessToken.Substring(idx + 10); - SetAuthHeaderToken(tampered); - result = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(tampered); + result = this._httpClient.GetAsync(TestGetQuery).Result; content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); @@ -246,7 +242,7 @@ public void TamperedTokenShouldFail() [Test] public void ExtendingTokenWithinLastHourExtendsUpToRenewalExpiry() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); var parts = token1.AccessToken.Split('.'); var decoded = DecodeBase64(parts[1]); dynamic claims = JsonConvert.DeserializeObject(decoded); @@ -256,7 +252,7 @@ public void ExtendingTokenWithinLastHourExtendsUpToRenewalExpiry() DatabaseHelper.ExecuteNonQuery(query); WebApiTestHelper.ClearHostCache(); - var token2 = RenewAuthorizationToken(token1); + var token2 = this.RenewAuthorizationToken(token1); parts = token2.AccessToken.Split('.'); decoded = DecodeBase64(parts[1]); claims = JsonConvert.DeserializeObject(decoded); @@ -277,7 +273,7 @@ public void ExtendingTokenWithinLastHourExtendsUpToRenewalExpiry() [Test] public void UsingExpiredAccessTokenShouldFail() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); var parts = token1.AccessToken.Split('.'); var decoded = DecodeBase64(parts[1]); dynamic claims = JsonConvert.DeserializeObject(decoded); @@ -287,8 +283,8 @@ public void UsingExpiredAccessTokenShouldFail() DatabaseHelper.ExecuteNonQuery(query); WebApiTestHelper.ClearHostCache(); - SetAuthHeaderToken(token1.AccessToken); - var result = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(token1.AccessToken); + var result = this._httpClient.GetAsync(TestGetQuery).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); @@ -297,7 +293,7 @@ public void UsingExpiredAccessTokenShouldFail() [Test] public void UsingExpiredRenewalTokenShouldFail() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); var parts = token1.AccessToken.Split('.'); var decoded = DecodeBase64(parts[1]); dynamic claims = JsonConvert.DeserializeObject(decoded); @@ -307,8 +303,8 @@ public void UsingExpiredRenewalTokenShouldFail() DatabaseHelper.ExecuteNonQuery(query); WebApiTestHelper.ClearHostCache(); - SetAuthHeaderToken(token1.AccessToken); - var result = _httpClient.GetAsync(TestGetQuery).Result; + this.SetAuthHeaderToken(token1.AccessToken); + var result = this._httpClient.GetAsync(TestGetQuery).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); @@ -317,7 +313,7 @@ public void UsingExpiredRenewalTokenShouldFail() [Test] public void TryingToRenewUsingAnExpiredRenewalTokenShouldFail() { - var token1 = GetAuthorizationTokenFor(_hostName, _hostPass); + var token1 = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); var parts = token1.AccessToken.Split('.'); var decoded = DecodeBase64(parts[1]); dynamic claims = JsonConvert.DeserializeObject(decoded); @@ -327,8 +323,8 @@ public void TryingToRenewUsingAnExpiredRenewalTokenShouldFail() DatabaseHelper.ExecuteNonQuery(query); WebApiTestHelper.ClearHostCache(); - SetAuthHeaderToken(token1.AccessToken); - var result = _httpClient.PostAsJsonAsync(ExtendTokenQuery, new { rtoken = token1.RenewalToken }).Result; + this.SetAuthHeaderToken(token1.AccessToken); + var result = this._httpClient.PostAsJsonAsync(ExtendTokenQuery, new { rtoken = token1.RenewalToken }).Result; Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); } @@ -337,9 +333,9 @@ public void TryingToRenewUsingAnExpiredRenewalTokenShouldFail() [TestCase(GetModuleDetailsQuery)] public void CallingHelperForLoggedinUserShouldReturnSuccess(string query) { - var token = GetAuthorizationTokenFor(_hostName, _hostPass); - SetAuthHeaderToken(token.AccessToken); - var result = _httpClient.GetAsync(query + HttpUtility.UrlEncode("ViewProfile")).Result; + var token = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + this.SetAuthHeaderToken(token.AccessToken); + var result = this._httpClient.GetAsync(query + HttpUtility.UrlEncode("ViewProfile")).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.NotNull(content); @@ -349,7 +345,7 @@ public void CallingHelperForLoggedinUserShouldReturnSuccess(string query) [Test] public void ValidatingSuccessWhenUsingExistingMoniker() { - //Arrange + // Arrange const string query1 = @"SELECT TOP(1) TabModuleId FROM {objectQualifier}TabModules WHERE TabId IN (SELECT TabId FROM {objectQualifier}Tabs WHERE TabName='Activity Feed') @@ -363,11 +359,11 @@ WHERE TabId IN (SELECT TabId FROM {objectQualifier}Tabs WHERE TabName='Activity WebApiTestHelper.ClearHostCache(); // Act - var token = GetAuthorizationTokenFor(_hostName, _hostPass); - SetAuthHeaderToken(token.AccessToken); - SetMonikerHeader("myjournal"); - var postItem = new {ProfileId = 1, GroupId = -1, RowIndex = 0, MaxRows = 1}; - var result = _httpClient.PostAsJsonAsync( + var token = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + this.SetAuthHeaderToken(token.AccessToken); + this.SetMonikerHeader("myjournal"); + var postItem = new { ProfileId = 1, GroupId = -1, RowIndex = 0, MaxRows = 1 }; + var result = this._httpClient.PostAsJsonAsync( "/API/Journal/Services/GetListForProfile", postItem).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); @@ -377,7 +373,7 @@ WHERE TabId IN (SELECT TabId FROM {objectQualifier}Tabs WHERE TabName='Activity [Test] public void ValidatingFailureWhenUsingNonExistingMoniker() { - //Arrange + // Arrange const string query1 = @"SELECT TOP(1) TabModuleId FROM {objectQualifier}TabModules WHERE TabId IN (SELECT TabId FROM {objectQualifier}Tabs WHERE TabName='Activity Feed') @@ -390,47 +386,55 @@ WHERE TabId IN (SELECT TabId FROM {objectQualifier}Tabs WHERE TabName='Activity WebApiTestHelper.ClearHostCache(); // Act - var token = GetAuthorizationTokenFor(_hostName, _hostPass); - SetAuthHeaderToken(token.AccessToken); - SetMonikerHeader("myjournal"); - var postItem = new {ProfileId = 1, GroupId = -1, RowIndex = 0, MaxRows = 1}; - var result = _httpClient.PostAsJsonAsync( + var token = this.GetAuthorizationTokenFor(this._hostName, this._hostPass); + this.SetAuthHeaderToken(token.AccessToken); + this.SetMonikerHeader("myjournal"); + var postItem = new { ProfileId = 1, GroupId = -1, RowIndex = 0, MaxRows = 1 }; + var result = this._httpClient.PostAsJsonAsync( "/API/Journal/Services/GetListForProfile", postItem).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); - } + } - // template to help in copy/paste of new test methods + private static string DecodeBase64(string b64Str) + { + // fix Base64 string padding + var mod = b64Str.Length % 4; + if (mod != 0) + { + b64Str += new string('=', 4 - mod); + } + + return TextEncoder.GetString(Convert.FromBase64String(b64Str)); + } + + // template to help in copy/paste of new test methods /* [Test] public void TemplateMethod() { Assert.Fail(); } - */ - - #endregion - - #region helpers - + */ + private LoginResultData GetAuthorizationTokenFor(string uname, string upass) { var credentials = new { u = uname, p = upass }; - var result = _httpClient.PostAsJsonAsync(LoginQuery, credentials).Result; + var result = this._httpClient.PostAsJsonAsync(LoginQuery, credentials).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var token = result.Content.ReadAsAsync().Result; Assert.IsNotNull(token); LogText(@"AuthToken => " + JsonConvert.SerializeObject(token)); - _httpClient.DefaultRequestHeaders.Clear(); + this._httpClient.DefaultRequestHeaders.Clear(); return token; } private LoginResultData RenewAuthorizationToken(LoginResultData currentToken) { Thread.Sleep(1000); // must delay at least 1 second so the expiry time is different - SetAuthHeaderToken(currentToken.AccessToken); - var result = _httpClient.PostAsJsonAsync(ExtendTokenQuery, new { rtoken = currentToken.RenewalToken }).Result; + this.SetAuthHeaderToken(currentToken.AccessToken); + var result = this._httpClient.PostAsJsonAsync(ExtendTokenQuery, new { rtoken = currentToken.RenewalToken }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var token = result.Content.ReadAsAsync().Result; Assert.IsNotNull(token); @@ -440,8 +444,8 @@ private LoginResultData RenewAuthorizationToken(LoginResultData currentToken) private void LogoutUser(string accessToken) { - SetAuthHeaderToken(accessToken); - var result = _httpClient.GetAsync(LogoutQuery).Result; + this.SetAuthHeaderToken(accessToken); + var result = this._httpClient.GetAsync(LogoutQuery).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var content = result.Content.ReadAsStringAsync().Result; dynamic response = !string.IsNullOrEmpty(content) ? JsonConvert.DeserializeObject(content) : null; @@ -450,27 +454,15 @@ private void LogoutUser(string accessToken) private void SetAuthHeaderToken(string token, string scheme = "Bearer") { - _httpClient.DefaultRequestHeaders.Authorization = + this._httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(scheme.Trim() + " " + token.Trim()); } private void SetMonikerHeader(string monikerValue) { - _httpClient.DefaultRequestHeaders.Add("X-DNN-MONIKER", monikerValue); - } - - private static string DecodeBase64(string b64Str) - { - // fix Base64 string padding - var mod = b64Str.Length % 4; - if (mod != 0) b64Str += new string('=', 4 - mod); - return TextEncoder.GetString(Convert.FromBase64String(b64Str)); + this._httpClient.DefaultRequestHeaders.Add("X-DNN-MONIKER", monikerValue); } - - #endregion - - #region supporting classes - + [JsonObject] public class LoginResultData { @@ -485,8 +477,6 @@ public class LoginResultData [JsonProperty("renewalToken")] public string RenewalToken { get; set; } - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Library/ImageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Library/ImageHandlerTests.cs index d341202ea31..601ebdabcea 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Library/ImageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Library/ImageHandlerTests.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using DotNetNuke.Entities.Portals; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Tests.Library { + using System.Linq; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Entities.Portals; + using NUnit.Framework; + [TestFixture] public class ImageHandlerTests : IntegrationTestBase { @@ -52,7 +53,6 @@ public void Using_Image_Handler_From_All_Alias_ShouldPass() Skin = primary.Skin, BrowserType = primary.BrowserType, IsPrimary = false, - }; } else diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs index 532ca958030..d920498b1d8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs @@ -1,22 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DNN.Integration.Test.Framework.Helpers; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Tests.Portals { + using System; + using System.Linq; + + using DNN.Integration.Test.Framework.Helpers; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class PortalInfoTests : DnnWebTest { - public PortalInfoTests() : base(Constants.PORTAL_Zero) + public PortalInfoTests() + : base(Constants.PORTAL_Zero) { } @@ -31,11 +33,11 @@ public void Processor_Password_In_DB_Must_Be_Encrypted() PortalController.Instance.UpdatePortalInfo(firstPortal); var result = DatabaseHelper.ExecuteScalar( - @"SELECT TOP(1) COALESCE(ProcessorPassword, '') FROM {objectQualifier}Portals WHERE PortalID=" + PortalId); + @"SELECT TOP(1) COALESCE(ProcessorPassword, '') FROM {objectQualifier}Portals WHERE PortalID=" + this.PortalId); var decrypted = DotNetNuke.Security.FIPSCompliant.DecryptAES(result, Config.GetDecryptionkey(), Host.GUID); - Assert.AreNotEqual(result, ""); + Assert.AreNotEqual(result, string.Empty); Assert.AreNotEqual(result, decrypted); Assert.AreEqual(decrypted, newPassword); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs index b333d05e981..780883ce220 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs @@ -1,59 +1,62 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Tests.Utilities; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Tests.Portals { + using System; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] public class PortalSettingsTests : DnnWebTest { private string _settingName; private string _settingValue; - public PortalSettingsTests() : base(Constants.PORTAL_Zero) + public PortalSettingsTests() + : base(Constants.PORTAL_Zero) { } [SetUp] public void Setup() { - _settingName = "NameToCheckFor"; + this._settingName = "NameToCheckFor"; + // we need different value so when we save we force going to database - _settingValue = "ValueToCheckFor_" + new Random().Next(1, 100); + this._settingValue = "ValueToCheckFor_" + new Random().Next(1, 100); } [Test] public void Saving_Non_Secure_Value_Doesnt_Encrypt_It() { - //Act - PortalController.UpdatePortalSetting(PortalId, _settingName, _settingValue, true, null, false); - var result = PortalController.GetPortalSetting(_settingName, PortalId, ""); + // Act + PortalController.UpdatePortalSetting(this.PortalId, this._settingName, this._settingValue, true, null, false); + var result = PortalController.GetPortalSetting(this._settingName, this.PortalId, string.Empty); - //Assert - Assert.AreNotEqual(result, ""); - Assert.AreEqual(_settingValue, result); + // Assert + Assert.AreNotEqual(result, string.Empty); + Assert.AreEqual(this._settingValue, result); } [Test] public void Saving_Secure_Value_Encrypts_It() { - //Act - PortalController.UpdatePortalSetting(PortalId, _settingName, _settingValue, true, null, true); + // Act + PortalController.UpdatePortalSetting(this.PortalId, this._settingName, this._settingValue, true, null, true); - var result = PortalController.GetPortalSetting(_settingName, PortalId, ""); + var result = PortalController.GetPortalSetting(this._settingName, this.PortalId, string.Empty); var decrypted = DotNetNuke.Security.FIPSCompliant.DecryptAES(result, Config.GetDecryptionkey(), Host.GUID); - //Assert - Assert.AreNotEqual(result, ""); - Assert.AreNotEqual(_settingValue, result); - Assert.AreEqual(decrypted, _settingValue); + // Assert + Assert.AreNotEqual(result, string.Empty); + Assert.AreNotEqual(this._settingValue, result); + Assert.AreEqual(decrypted, this._settingValue); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs index 9261a60dab5..e0a5f425c9d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net; -using System.Net.Http; -using DNN.Integration.Test.Framework; -using DNN.Integration.Test.Framework.Helpers; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Integration.Tests.Security { + using System; + using System.Net; + using System.Net.Http; + + using DNN.Integration.Test.Framework; + using DNN.Integration.Test.Framework.Helpers; + using NUnit.Framework; + [TestFixture] public class AuthCookieTests : IntegrationTestBase { @@ -27,8 +28,8 @@ public void Using_Logged_Out_Cookie_Should_Be_Unauthorized() cookies.Add(session.SessionCookies.GetCookies(session.Domain)); // make sure the request succeeds when the user is logged in - //var result1 = session.GetContent(GetPortaslApi, null, false); -- use same method to validate - var result1 = SendDirectGetRequest(session.Domain, GetPortaslApi, session.Timeout, cookies); + // var result1 = session.GetContent(GetPortaslApi, null, false); -- use same method to validate + var result1 = this.SendDirectGetRequest(session.Domain, GetPortaslApi, session.Timeout, cookies); Assert.IsTrue(result1.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.OK, result1.StatusCode); @@ -36,18 +37,11 @@ public void Using_Logged_Out_Cookie_Should_Be_Unauthorized() Assert.IsFalse(session.IsLoggedIn); // make sure the request fails when using the same cookies before logging out - var result2 = SendDirectGetRequest(session.Domain, GetPortaslApi, session.Timeout, cookies); + var result2 = this.SendDirectGetRequest(session.Domain, GetPortaslApi, session.Timeout, cookies); Assert.IsFalse(result2.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.Unauthorized, result2.StatusCode); } - - private HttpResponseMessage SendDirectGetRequest(Uri domain, string path, TimeSpan timeout, CookieContainer cookies) - { - var client = CreateHttpClient(domain, timeout, cookies); - return client.GetAsync(path).Result; - } - - #region This is duplicated from the connector with tweaking to use direct calling to control the cookies + private static HttpClient CreateHttpClient(Uri domain, TimeSpan timeout, CookieContainer cookies) { var clientHandler = new HttpClientHandler @@ -59,12 +53,16 @@ private static HttpClient CreateHttpClient(Uri domain, TimeSpan timeout, CookieC var client = new HttpClient(clientHandler) { BaseAddress = domain, - Timeout = timeout + Timeout = timeout, }; return client; - } + } - #endregion + private HttpResponseMessage SendDirectGetRequest(Uri domain, string path, TimeSpan timeout, CookieContainer cookies) + { + var client = CreateHttpClient(domain, timeout, cookies); + return client.GetAsync(path).Result; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Integration/packages.config index 5f9964cfa94..3e2870b85fe 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/packages.config @@ -1,13 +1,14 @@ - - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.UI/AssemblyInfo.cs index ee265cf86cb..43be95a53e1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/AssemblyInfo.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Tests.UI")] [assembly: AssemblyDescription("Open Source Web Application Framework")] @@ -16,27 +15,23 @@ [assembly: AssemblyProduct("https://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2018 by DotNetNuke Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DotNetNuke")] - - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM componenets. If you need to access a type in this assembly from + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. 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("f6b15e10-1d6a-4626-b355-fd0227da78ff")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Revision and Build Numbers +// You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: - [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj b/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj index 4ad0a9a63b0..68a30fae87b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj @@ -1,118 +1,125 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {5484768D-80AA-4D07-86F0-8CB0A06AFD99} - Library - Properties - DotNetNuke.Tests.UI - DotNetNuke.Tests.UI - v4.7.2 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - - - 4.0 - false - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - ..\..\..\..\Evoq.Content\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - - - - - - - - - - - {ee1329fe-fd88-4e1a-968c-345e394ef080} - DotNetNuke.Web - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {68368906-57dd-40d1-ac10-35211a17d617} - DotNetNuke.Tests.Utilities - - - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {5484768D-80AA-4D07-86F0-8CB0A06AFD99} + Library + Properties + DotNetNuke.Tests.UI + DotNetNuke.Tests.UI + v4.7.2 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + + + 4.0 + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + ..\..\..\..\Evoq.Content\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + + + + + + + + + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {68368906-57dd-40d1-ac10-35211a17d617} + DotNetNuke.Tests.Utilities + + + + + + + + + stylecop.json + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs index edb03b1442b..7934ca4ef15 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs @@ -1,18 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.ComponentModel.DataAnnotations; -using System.Linq; - -using DotNetNuke.Web.Validators; - -using NUnit.Framework; - -using ValidationResult = DotNetNuke.Web.Validators.ValidationResult; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.UI.Validation { + using System.ComponentModel.DataAnnotations; + using System.Linq; + + using DotNetNuke.Web.Validators; + using NUnit.Framework; + + using ValidationResult = DotNetNuke.Web.Validators.ValidationResult; + [TestFixture] public class DataAnnotationsObjectValidatorTests { @@ -24,28 +23,13 @@ public static string ErrorMessage { return ErrorMessageConst; } - } - - #region Nested type: TestClass - - public class TestClass - { - [Required(ErrorMessage = "Dude, you forgot to enter a {0}")] - public object Foo { get; set; } - - [StringLength(5, ErrorMessageResourceName = "ErrorMessage", ErrorMessageResourceType = typeof (DataAnnotationsObjectValidatorTests))] - public string Bar { get; set; } - } - - #endregion - - #region Tests - + } + [Test] public void ValidateObject_Returns_Successful_Result_If_All_Attributes_On_All_Properties_Validate() { // Arrange - TestClass cls = new TestClass {Foo = new object(), Bar = "Baz"}; + TestClass cls = new TestClass { Foo = new object(), Bar = "Baz" }; DataAnnotationsObjectValidator validator = new DataAnnotationsObjectValidator(); // Act @@ -59,7 +43,7 @@ public void ValidateObject_Returns_Successful_Result_If_All_Attributes_On_All_Pr public void ValidateObject_Returns_Failed_Result_If_Any_Attribute_Does_Not_Validate() { // Arrange - TestClass cls = new TestClass {Foo = new object(), Bar = "BarBaz"}; + TestClass cls = new TestClass { Foo = new object(), Bar = "BarBaz" }; DataAnnotationsObjectValidator validator = new DataAnnotationsObjectValidator(); // Act @@ -73,7 +57,7 @@ public void ValidateObject_Returns_Failed_Result_If_Any_Attribute_Does_Not_Valid public void ValidateObject_Collects_Error_Messages_From_Validation_Attributes() { // Arrange - TestClass cls = new TestClass {Foo = null, Bar = "BarBaz"}; + TestClass cls = new TestClass { Foo = null, Bar = "BarBaz" }; DataAnnotationsObjectValidator validator = new DataAnnotationsObjectValidator(); // Act @@ -84,12 +68,21 @@ public void ValidateObject_Collects_Error_Messages_From_Validation_Attributes() Assert.AreEqual("Dude, you forgot to enter a Foo", result.Errors.Where(e => e.PropertyName == "Foo").Single().ErrorMessage); Assert.AreEqual("Yo, you have to specify 5 characters for Bar", result.Errors.Where(e => e.PropertyName == "Bar").Single().ErrorMessage); } + + public class TestClass + { + [Required(ErrorMessage = "Dude, you forgot to enter a {0}")] + public object Foo { get; set; } + + [StringLength(5, ErrorMessageResourceName = "ErrorMessage", ErrorMessageResourceType = typeof(DataAnnotationsObjectValidatorTests))] + public string Bar { get; set; } + } [Test] public void ValidateObject_Collects_ValidationAttribute_Objects_From_Failed_Validation() { // Arrange - TestClass cls = new TestClass {Foo = null, Bar = "BarBaz"}; + TestClass cls = new TestClass { Foo = null, Bar = "BarBaz" }; DataAnnotationsObjectValidator validator = new DataAnnotationsObjectValidator(); // Act @@ -99,8 +92,6 @@ public void ValidateObject_Collects_ValidationAttribute_Objects_From_Failed_Vali Assert.IsFalse(result.IsValid); Assert.IsInstanceOf(result.Errors.Single(e => e.PropertyName == "Foo").Validator); Assert.IsInstanceOf(result.Errors.Single(e => e.PropertyName == "Bar").Validator); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs index f9d05e40b9d..e676dfc9143 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs @@ -1,27 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; - -using DotNetNuke.Tests.Utilities; -using DotNetNuke.Web.Validators; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.UI.Validation { + using System.Linq; + + using DotNetNuke.Tests.Utilities; + using DotNetNuke.Web.Validators; + using Moq; + using NUnit.Framework; + [TestFixture] public class ValidatorTests { - private static readonly ValidationResult FailedResult = new ValidationResult(new[] {new ValidationError()}); - - private static readonly ValidationResult AnotherFailedResult = new ValidationResult(new[] {new ValidationError()}); - - #region Tests + private static readonly ValidationResult FailedResult = new ValidationResult(new[] { new ValidationError() }); + private static readonly ValidationResult AnotherFailedResult = new ValidationResult(new[] { new ValidationError() }); + [Test] public void ValidateObject_Returns_Successful_Result_If_All_Validators_Return_Successful() { @@ -66,13 +62,9 @@ public void ValidateObject_Collects_Errors_From_All_Validators() // Assert Assert.IsFalse(result.IsValid); Assert.AreEqual(2, result.Errors.Count()); - EnumerableAssert.ElementsMatch(new[] {FailedResult, AnotherFailedResult}, result.Errors, (e, a) => ReferenceEquals(e.Errors.First(), a)); - } - - #endregion - - #region Helpers - + EnumerableAssert.ElementsMatch(new[] { FailedResult, AnotherFailedResult }, result.Errors, (e, a) => ReferenceEquals(e.Errors.First(), a)); + } + private static void SetupValidators(Validator validator, object target, params ValidationResult[] validationResults) { validator.Validators.Clear(); @@ -82,8 +74,6 @@ private static void SetupValidators(Validator validator, object target, params V mockValidator.Setup(v => v.ValidateObject(target)).Returns(validationResults[i]); validator.Validators.Add(mockValidator.Object); } - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.UI/packages.config index 53b44f9d8fe..97fd3abee1b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/packages.config @@ -1,6 +1,7 @@ - - - - - + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj index c6ad5ecdfe4..42295f10c70 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj @@ -1,215 +1,222 @@ - - - - - Debug - AnyCPU - {F9CE7C63-C729-4E3A-A266-6B23D75A1247} - Library - Properties - DotNetNuke.Tests.Urls - DotNetNuke.Tests.Urls - v4.7.2 - 512 - ..\..\..\..\Evoq.Content\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - 7 - - - - False - ..\..\HttpModules\bin\DotNetNuke.HttpModules.dll - - - False - ..\..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll - - - False - ..\..\DotNetNuke.Log4net\bin\dotnetnuke.log4net.dll - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - ..\..\Components\PetaPoco\bin\PetaPoco.dll - - - - - - - - - - - - - - - - - - - - - - - - - App.config - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {5AECE021-E449-4A7F-BF82-2FA7B236ED3E} - DotNetNuke.Tests.Utilities - - - - - - - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + + Debug + AnyCPU + {F9CE7C63-C729-4E3A-A266-6B23D75A1247} + Library + Properties + DotNetNuke.Tests.Urls + DotNetNuke.Tests.Urls + v4.7.2 + 512 + ..\..\..\..\Evoq.Content\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 7 + + + + False + ..\..\HttpModules\bin\DotNetNuke.HttpModules.dll + + + False + ..\..\DotNetNuke.Instrumentation\bin\DotNetNuke.Instrumentation.dll + + + False + ..\..\DotNetNuke.Log4net\bin\dotnetnuke.log4net.dll + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + ..\..\Components\PetaPoco\bin\PetaPoco.dll + + + + + + + + + + + + + + + + + + + + + + + + + stylecop.json + + + App.config + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {5AECE021-E449-4A7F-BF82-2FA7B236ED3E} + DotNetNuke.Tests.Utilities + + + + + + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/ExtensionUrlProviderControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/ExtensionUrlProviderControllerTests.cs index e687101f72f..71fab27b60f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/ExtensionUrlProviderControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/ExtensionUrlProviderControllerTests.cs @@ -1,8 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { using System; @@ -86,7 +85,7 @@ private static DataSet GetDataSetForExtensionUrlProvidersCall() var providerTabsTable = getExtensionUrlProvidersDataSet.Tables.Add(); providerTabsTable.Columns.AddRange(new[] { new DataColumn("ExtensionUrlProviderID", typeof(int)), new DataColumn("TabId", typeof(int)), }); - + return getExtensionUrlProvidersDataSet; } @@ -112,7 +111,7 @@ public override bool AlwaysUsesDnnPagePath(int portalId) throw new NotImplementedException(); } - public override string ChangeFriendlyUrl(TabInfo tab, string friendlyUrlPath, FriendlyUrlOptions options, string cultureCode, ref string endingPageName, out bool useDnnPagePath, ref List messages) + public override string ChangeFriendlyUrl(TabInfo tab, string friendlyUrlPath, FriendlyUrlOptions options, string cultureCode, ref string endingPageName, out bool useDnnPagePath, ref List messages) { throw new NotImplementedException(); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs index 061512374d3..abfcdea3525 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { + using System; + using System.Collections.Generic; + public static class Extensions { public static string GetValue(this Dictionary dic, string key) { - return GetValue(dic, key, String.Empty); + return GetValue(dic, key, string.Empty); } public static string GetValue(this Dictionary dic, string key, string defaultValue) @@ -21,8 +21,8 @@ public static string GetValue(this Dictionary dic, string key, s { returnValue = dic[key]; } + return returnValue; } - } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs index 5662fe4281e..6e25f1e4ea9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs @@ -1,51 +1,51 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.HttpModules.UrlRewrite; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { + using System; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.HttpModules.UrlRewrite; + using DotNetNuke.Services.Localization; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] - public class FriendlyUrlTests : UrlTestBase + public class FriendlyUrlTests : UrlTestBase { private const string _defaultPage = Globals.glbDefaultPage; - private int _tabId; private const string _aboutUsPageName = "About Us"; + private int _tabId; private string _redirectMode; private Locale _customLocale; private PortalAliasInfo _primaryAlias; - public FriendlyUrlTests() : base(0) { } - - #region SetUp and TearDown - + public FriendlyUrlTests() + : base(0) + { + } + [SetUp] public override void SetUp() { base.SetUp(); - UpdateTabName(_tabId, "About Us"); + this.UpdateTabName(this._tabId, "About Us"); CacheController.FlushPageIndexFromCache(); - GetDefaultAlias(); - _redirectMode = PortalController.GetPortalSetting("PortalAliasMapping", PortalId, "CANONICALURL"); - _primaryAlias = null; - _customLocale = null; + this.GetDefaultAlias(); + this._redirectMode = PortalController.GetPortalSetting("PortalAliasMapping", this.PortalId, "CANONICALURL"); + this._primaryAlias = null; + this._customLocale = null; } [TestFixtureSetUp] @@ -53,35 +53,36 @@ public override void TestFixtureSetUp() { base.TestFixtureSetUp(); - var tab = TabController.Instance.GetTabByName(_aboutUsPageName, PortalId); + var tab = TabController.Instance.GetTabByName(_aboutUsPageName, this.PortalId); if (tab == null) { - CreateTab(_aboutUsPageName); - tab = TabController.Instance.GetTabByName(_aboutUsPageName, PortalId); + this.CreateTab(_aboutUsPageName); + tab = TabController.Instance.GetTabByName(_aboutUsPageName, this.PortalId); } - _tabId = tab.TabID; + + this._tabId = tab.TabID; - //Add Portal Aliases + // Add Portal Aliases var aliasController = PortalAliasController.Instance; - TestUtil.ReadStream(String.Format("{0}", "Aliases"), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => { string[] fields = line.Split(','); - var alias = aliasController.GetPortalAlias(fields[0], PortalId); + var alias = aliasController.GetPortalAlias(fields[0], this.PortalId); if (alias == null) { - alias = new PortalAliasInfo - { - HTTPAlias = fields[0], - PortalID = PortalId - }; + alias = new PortalAliasInfo + { + HTTPAlias = fields[0], + PortalID = this.PortalId, + }; PortalAliasController.Instance.AddPortalAlias(alias); } }); - TestUtil.ReadStream(String.Format("{0}", "Users"), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Users"), (line, header) => { string[] fields = line.Split(','); - TestUtil.AddUser(PortalId, fields[0].Trim(), fields[1].Trim(), fields[2].Trim()); + TestUtil.AddUser(this.PortalId, fields[0].Trim(), fields[1].Trim(), fields[2].Trim()); }); } @@ -90,24 +91,25 @@ public override void TearDown() { base.TearDown(); - UpdateTabName(_tabId, "About Us"); + this.UpdateTabName(this._tabId, "About Us"); - if (_customLocale != null) + if (this._customLocale != null) { - Localization.RemoveLanguageFromPortals(_customLocale.LanguageId, true); - Localization.DeleteLanguage(_customLocale, true); + Localization.RemoveLanguageFromPortals(this._customLocale.LanguageId, true); + Localization.DeleteLanguage(this._customLocale, true); } - if (_primaryAlias != null) + + if (this._primaryAlias != null) { - PortalAliasController.Instance.DeletePortalAlias(_primaryAlias); + PortalAliasController.Instance.DeletePortalAlias(this._primaryAlias); } - SetDefaultAlias(DefaultAlias); - PortalController.UpdatePortalSetting(PortalId, "PortalAliasMapping", _redirectMode); + this.SetDefaultAlias(this.DefaultAlias); + PortalController.UpdatePortalSetting(this.PortalId, "PortalAliasMapping", this._redirectMode); - foreach (var tabUrl in CBO.FillCollection(DataProvider.Instance().GetTabUrls(PortalId))) + foreach (var tabUrl in CBO.FillCollection(DataProvider.Instance().GetTabUrls(this.PortalId))) { - TabController.Instance.DeleteTabUrl(tabUrl, PortalId, true); + TabController.Instance.DeleteTabUrl(tabUrl, this.PortalId, true); } } @@ -116,54 +118,66 @@ public override void TestFixtureTearDown() { base.TestFixtureTearDown(); - var aliasController =PortalAliasController.Instance; - TestUtil.ReadStream(String.Format("{0}", "Aliases"), (line, header) => + var aliasController = PortalAliasController.Instance; + TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => { string[] fields = line.Split(','); - var alias = aliasController.GetPortalAlias(fields[0], PortalId); + var alias = aliasController.GetPortalAlias(fields[0], this.PortalId); PortalAliasController.Instance.DeletePortalAlias(alias); }); - TestUtil.ReadStream(String.Format("{0}", "Users"), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Users"), (line, header) => { string[] fields = line.Split(','); - TestUtil.DeleteUser(PortalId, fields[0]); + TestUtil.DeleteUser(this.PortalId, fields[0]); }); + } + + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_BaseTestCases")] + public void AdvancedUrlProvider_BaseFriendlyUrl(Dictionary testFields) + { + this.ExecuteTest("Base", testFields); } - #endregion - - #region Private Methods - + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_ImprovedTestCases")] + public void AdvancedUrlProvider_ImprovedFriendlyUrl(Dictionary testFields) + { + this.ExecuteTest("Improved", testFields); + } + private void ExecuteTest(string test, Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); - SetDefaultAlias(testFields); + this.SetDefaultAlias(testFields); - ExecuteTest(test, settings, testFields); + this.ExecuteTest(test, settings, testFields); } private void ExecuteTest(string test, FriendlyUrlSettings settings, Dictionary testFields) { var tabName = testFields["Page Name"]; - var tab = TabController.Instance.GetTabByName(tabName, PortalId); - if (tab == null) - Assert.Fail($"TAB with name [{tabName}] is not found!"); - - ExecuteTestForTab(test, tab, settings, testFields); + var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); + if (tab == null) + { + Assert.Fail($"TAB with name [{tabName}] is not found!"); + } + + this.ExecuteTestForTab(test, tab, settings, testFields); } private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings settings, Dictionary testFields) { var httpAlias = testFields["Alias"]; - var defaultAlias = testFields.GetValue("DefaultAlias", String.Empty); + var defaultAlias = testFields.GetValue("DefaultAlias", string.Empty); var tabName = testFields["Page Name"]; var scheme = testFields["Scheme"]; var parameters = testFields["Params"]; var result = testFields["Expected Url"]; var customPage = testFields.GetValue("Custom Page Name", _defaultPage); - string vanityUrl = testFields.GetValue("VanityUrl", String.Empty); + string vanityUrl = testFields.GetValue("VanityUrl", string.Empty); var httpAliasFull = scheme + httpAlias + "/"; var expectedResult = result.Replace("{alias}", httpAlias) @@ -172,44 +186,44 @@ private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings set .Replace("{tabId}", tab.TabID.ToString()) .Replace("{vanityUrl}", vanityUrl) .Replace("{defaultPage}", _defaultPage); - - - if (!String.IsNullOrEmpty(parameters) && !parameters.StartsWith("&")) + + if (!string.IsNullOrEmpty(parameters) && !parameters.StartsWith("&")) { parameters = "&" + parameters; } - var userName = testFields.GetValue("UserName", String.Empty); - if (!String.IsNullOrEmpty(userName)) + var userName = testFields.GetValue("UserName", string.Empty); + if (!string.IsNullOrEmpty(userName)) { - var user = UserController.GetUserByName(PortalId, userName); + var user = UserController.GetUserByName(this.PortalId, userName); if (user != null) { expectedResult = expectedResult.Replace("{userId}", user.UserID.ToString()); parameters = parameters.Replace("{userId}", user.UserID.ToString()); } } - - + var baseUrl = httpAliasFull + "Default.aspx?TabId=" + tab.TabID + parameters; string testUrl; if (test == "Base") { - testUrl = AdvancedFriendlyUrlProvider.BaseFriendlyUrl(tab, - baseUrl, - customPage, - httpAlias, - settings); + testUrl = AdvancedFriendlyUrlProvider.BaseFriendlyUrl( + tab, + baseUrl, + customPage, + httpAlias, + settings); } else { - testUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - baseUrl, - customPage, - httpAlias, - true, - settings, - Guid.Empty); + testUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + baseUrl, + customPage, + httpAlias, + true, + settings, + Guid.Empty); } Assert.IsTrue(expectedResult.Equals(testUrl, StringComparison.InvariantCultureIgnoreCase)); @@ -217,59 +231,42 @@ private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings set private void UpdateTabName(int tabId, string newName) { - var tab = TabController.Instance.GetTab(tabId, PortalId, false); + var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); tab.TabName = newName; TabController.Instance.UpdateTab(tab); - } - - #endregion - - #region Tests - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_BaseTestCases")] - public void AdvancedUrlProvider_BaseFriendlyUrl(Dictionary testFields) - { - ExecuteTest("Base", testFields); - } - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_ImprovedTestCases")] - public void AdvancedUrlProvider_ImprovedFriendlyUrl(Dictionary testFields) - { - ExecuteTest("Improved", testFields); - } + } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_SpaceEncodingTestCases")] public void AdvancedUrlProvider_SpaceEncoding(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", "SpaceEncoding", PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", "SpaceEncoding", this.PortalId); settings.ReplaceSpaceWith = " "; string spaceEncoding = testFields.GetValue("SpaceEncoding"); - if (!String.IsNullOrEmpty(spaceEncoding)) + if (!string.IsNullOrEmpty(spaceEncoding)) { settings.SpaceEncodingValue = spaceEncoding; } - ExecuteTest("Improved", settings, testFields); + this.ExecuteTest("Improved", settings, testFields); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_PageExtensionTestCases")] public void AdvancedUrlProvider_PageExtension(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", "PageExtension", PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", "PageExtension", this.PortalId); string pageExtensionUsageType = testFields.GetValue("PageExtensionUsageType"); string pageExtension = testFields.GetValue("PageExtension"); - if (!String.IsNullOrEmpty(pageExtension)) + if (!string.IsNullOrEmpty(pageExtension)) { settings.PageExtension = pageExtension; } + switch (pageExtensionUsageType) { case "AlwaysUse": @@ -283,7 +280,7 @@ public void AdvancedUrlProvider_PageExtension(Dictionary testFie break; } - ExecuteTest("Improved", settings, testFields); + this.ExecuteTest("Improved", settings, testFields); } [Test] @@ -293,45 +290,45 @@ public void AdvancedUrlProvider_PrimaryPortalAlias(Dictionary te string defaultAlias = testFields["DefaultAlias"]; string redirectMode = testFields["RedirectMode"]; - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", "PrimaryPortalAlias", PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", "PrimaryPortalAlias", this.PortalId); string language = testFields["Language"].Trim(); - if (!String.IsNullOrEmpty(language)) + if (!string.IsNullOrEmpty(language)) { - _customLocale = new Locale { Code = language, Fallback = "en-US" }; - _customLocale.Text = CultureInfo.GetCultureInfo(_customLocale.Code).NativeName; - Localization.SaveLanguage(_customLocale); - Localization.AddLanguageToPortals(_customLocale.LanguageId); + this._customLocale = new Locale { Code = language, Fallback = "en-US" }; + this._customLocale.Text = CultureInfo.GetCultureInfo(this._customLocale.Code).NativeName; + Localization.SaveLanguage(this._customLocale); + Localization.AddLanguageToPortals(this._customLocale.LanguageId); - //add new primary alias - _primaryAlias = new PortalAliasInfo + // add new primary alias + this._primaryAlias = new PortalAliasInfo { - PortalID = PortalId, + PortalID = this.PortalId, HTTPAlias = defaultAlias, CultureCode = language, - IsPrimary = true + IsPrimary = true, }; - _primaryAlias.PortalAliasID = PortalAliasController.Instance.AddPortalAlias(_primaryAlias); + this._primaryAlias.PortalAliasID = PortalAliasController.Instance.AddPortalAlias(this._primaryAlias); } else { - SetDefaultAlias(defaultAlias); + this.SetDefaultAlias(defaultAlias); } - PortalController.UpdatePortalSetting(PortalId, "PortalAliasMapping", redirectMode); + PortalController.UpdatePortalSetting(this.PortalId, "PortalAliasMapping", redirectMode); - ExecuteTest("Improved", settings, testFields); + this.ExecuteTest("Improved", settings, testFields); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_RegexTestCases")] public void AdvancedUrlProvider_Regex(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); string regexSetting = testFields["Setting"]; string regexValue = testFields["Value"]; - if (!String.IsNullOrEmpty(regexValue)) + if (!string.IsNullOrEmpty(regexValue)) { switch (regexSetting) { @@ -368,97 +365,96 @@ public void AdvancedUrlProvider_Regex(Dictionary testFields) } } - ExecuteTest("Improved", settings, testFields); + this.ExecuteTest("Improved", settings, testFields); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_ReplaceCharsTestCases")] public void AdvancedUrlProvider_ReplaceChars(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); string testPageName = testFields.GetValue("TestPageName"); TabInfo tab = null; - if (!String.IsNullOrEmpty(testPageName)) + if (!string.IsNullOrEmpty(testPageName)) { var tabName = testFields["Page Name"]; - tab = TabController.Instance.GetTabByName(tabName, PortalId); + tab = TabController.Instance.GetTabByName(tabName, this.PortalId); tab.TabName = testPageName; TabController.Instance.UpdateTab(tab); - //Refetch tab from DB + // Refetch tab from DB tab = TabController.Instance.GetTab(tab.TabID, tab.PortalID, false); } string autoAscii = testFields.GetValue("AutoAscii"); - if (!String.IsNullOrEmpty(autoAscii)) + if (!string.IsNullOrEmpty(autoAscii)) { settings.AutoAsciiConvert = Convert.ToBoolean(autoAscii); } TestUtil.GetReplaceCharDictionary(testFields, settings.ReplaceCharacterDictionary); - ExecuteTestForTab("Improved", tab, settings, testFields); + this.ExecuteTestForTab("Improved", tab, settings, testFields); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_ReplaceSpaceTestCases")] public void AdvancedUrlProvider_ReplaceSpace(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); string replaceSpaceWith = testFields.GetValue("ReplaceSpaceWith"); - if (!String.IsNullOrEmpty(replaceSpaceWith)) + if (!string.IsNullOrEmpty(replaceSpaceWith)) { settings.ReplaceSpaceWith = replaceSpaceWith; } - ExecuteTest("Improved", settings, testFields); + this.ExecuteTest("Improved", settings, testFields); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_VanityUrlTestCases")] public void AdvancedUrlProvider_VanityUrl(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); - var vanityUrl = testFields.GetValue("VanityUrl", String.Empty); - var userName = testFields.GetValue("UserName", String.Empty); - var vanityUrlPrefix = testFields.GetValue("VanityUrlPrefix", String.Empty); - if (!String.IsNullOrEmpty(vanityUrlPrefix)) + var vanityUrl = testFields.GetValue("VanityUrl", string.Empty); + var userName = testFields.GetValue("UserName", string.Empty); + var vanityUrlPrefix = testFields.GetValue("VanityUrlPrefix", string.Empty); + if (!string.IsNullOrEmpty(vanityUrlPrefix)) { settings.VanityUrlPrefix = vanityUrlPrefix; } - if (!String.IsNullOrEmpty(userName)) + if (!string.IsNullOrEmpty(userName)) { - var user = UserController.GetUserByName(PortalId, userName); + var user = UserController.GetUserByName(this.PortalId, userName); if (user != null) { user.VanityUrl = vanityUrl; - UserController.UpdateUser(PortalId, user); + UserController.UpdateUser(this.PortalId, user); } } - ExecuteTest("Improved", settings, testFields); + + this.ExecuteTest("Improved", settings, testFields); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_ForceLowerCaseTestCases")] public void AdvancedUrlProvider_ForceLowerCase(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); string forceLowerCaseRegex = testFields.GetValue("ForceLowerCaseRegex"); - if (!String.IsNullOrEmpty(forceLowerCaseRegex)) + if (!string.IsNullOrEmpty(forceLowerCaseRegex)) { settings.ForceLowerCaseRegex = forceLowerCaseRegex; } - ExecuteTest("Improved", settings, testFields); - } - - #endregion + this.ExecuteTest("Improved", settings, testFields); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/Properties/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/Properties/AssemblyInfo.cs index 997c35312ad..39c7f4d96c3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/Properties/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/Properties/AssemblyInfo.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Tests.Urls")] @@ -18,8 +18,8 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// 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 +// 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)] @@ -29,11 +29,11 @@ // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs index 1609e6e983d..334299063ec 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs @@ -1,39 +1,54 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; - - -using DotNetNuke.Entities.Users; -using DotNetNuke.Tests.Utilities; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { + using System; + using System.Collections.Generic; + using System.IO; + using System.Reflection; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Tests.Utilities; + public class TestUtil { + internal static string EmbeddedFilePath + { + get { return "DotNetNuke.Tests.Urls.TestFiles"; } + } + + internal static string FilePath + { + get + { + var uri = new System.Uri(Assembly.GetExecutingAssembly().CodeBase); + string path = Path.GetFullPath(uri.AbsolutePath).Replace("%20", " "); + + return Path.Combine(path.Substring(0, path.IndexOf("bin", System.StringComparison.Ordinal)), "TestFiles"); + } + } + internal static void AddUser(int portalId, string userName, string password, string vanityUrl) { var user = UserController.GetUserByName(portalId, userName); if (user == null) { - //Add User + // Add User user = new UserInfo { PortalID = portalId, Username = userName, Email = userName + "@changeme.invalid", VanityUrl = vanityUrl, - Membership = { Password = password, Approved = true } + Membership = { Password = password, Approved = true }, }; UserController.CreateUser(ref user); } else { - //Update User + // Update User user.VanityUrl = vanityUrl; user.IsDeleted = false; UserController.UpdateUser(portalId, user); @@ -49,26 +64,9 @@ internal static void DeleteUser(int portalId, string userName) } } - - internal static string EmbeddedFilePath - { - get { return "DotNetNuke.Tests.Urls.TestFiles"; } - } - - internal static string FilePath - { - get - { - var uri = new System.Uri(Assembly.GetExecutingAssembly().CodeBase); - string path = Path.GetFullPath(uri.AbsolutePath).Replace("%20", " "); - - return Path.Combine(path.Substring(0, path.IndexOf("bin", System.StringComparison.Ordinal)), "TestFiles"); - } - } - internal static string GetEmbeddedFileName(string fileName) { - string fullName = String.Format("{0}.{1}", EmbeddedFilePath, fileName); + string fullName = string.Format("{0}.{1}", EmbeddedFilePath, fileName); if (!fullName.ToLowerInvariant().EndsWith(".csv")) { fullName += ".csv"; @@ -86,7 +84,7 @@ internal static void GetReplaceCharDictionary(Dictionary testFie { string replaceCharWithChar = testFields.GetValue("ReplaceChars"); - if (!String.IsNullOrEmpty(replaceCharWithChar)) + if (!string.IsNullOrEmpty(replaceCharWithChar)) { string[] pairs = replaceCharWithChar.Split(';'); foreach (string pair in pairs) @@ -98,10 +96,12 @@ internal static void GetReplaceCharDictionary(Dictionary testFie { key = vals[0]; } + if (vals.GetUpperBound(0) >= 1) { val = vals[1]; } + if (key != null && val != null) { replaceCharacterDictionary.Add(key, val); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs index 7de3de165c2..1e364675313 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs @@ -1,11 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { public static class UrlAssert { - } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs index 7a3daf4ae04..d706c937253 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs @@ -1,36 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.HttpModules.UrlRewrite; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Localization; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.HttpModules.UrlRewrite; + using DotNetNuke.Services.Localization; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + [TestFixture] - public class UrlRewriteTests : UrlTestBase + public class UrlRewriteTests : UrlTestBase { private const string _defaultPage = Globals.glbDefaultPage; - private int _tabId; private const string _testPage = "Test Page"; private const string _aboutUsPageName = "About Us"; + private int _tabId; private string _redirectMode; private Locale _customLocale; private string _securePageName; @@ -38,13 +37,75 @@ public class UrlRewriteTests : UrlTestBase private bool _sslEnforced; private bool _sslEnabled; - public UrlRewriteTests() : base(0) { } + public UrlRewriteTests() + : base(0) + { + } + + [SetUp] + public override void SetUp() + { + base.SetUp(); + + this.DeleteTab(_testPage); + this.CreateTab(_testPage); + this.UpdateTabName(this._tabId, "About Us"); + this.UpdateTabSkin(this._tabId, string.Empty); + CacheController.FlushPageIndexFromCache(); + this.GetDefaultAlias(); + this._redirectMode = PortalController.GetPortalSetting("PortalAliasMapping", this.PortalId, "CANONICALURL"); + this._sslEnforced = PortalController.GetPortalSettingAsBoolean("SSLEnforced", this.PortalId, false); + this._sslEnabled = PortalController.GetPortalSettingAsBoolean("SSLEnabled", this.PortalId, false); + this._primaryAlias = null; + this._customLocale = null; + DataCache.ClearCache(); + } - #region Private Methods + [TearDown] + public override void TearDown() + { + base.TearDown(); + + this.DeleteTab(_testPage); + this.UpdateTabName(this._tabId, "About Us"); + this.UpdateTabSkin(this._tabId, "[G]Skins/Xcillion/Inner.ascx"); + + if (!string.IsNullOrEmpty(this._securePageName)) + { + var tab = TabController.Instance.GetTabByName(this._securePageName, this.PortalId); + if (tab != null) + { + tab.IsSecure = false; + this.UpdateTab(tab); + } + } + + if (this._customLocale != null) + { + Localization.RemoveLanguageFromPortals(this._customLocale.LanguageId, true); + Localization.DeleteLanguage(this._customLocale, true); + } + + if (this._primaryAlias != null) + { + PortalAliasController.Instance.DeletePortalAlias(this._primaryAlias); + } + + this.SetDefaultAlias(this.DefaultAlias); + PortalController.UpdatePortalSetting(this.PortalId, "PortalAliasMapping", this._redirectMode, true, "en-us"); + PortalController.UpdatePortalSetting(this.PortalId, "SSLEnforced", this._sslEnforced.ToString(), true, "en-us"); + PortalController.UpdatePortalSetting(this.PortalId, "SSLEnabled", this._sslEnabled.ToString(), true, "en-us"); + + foreach (var tabUrl in CBO.FillCollection(DataProvider.Instance().GetTabUrls(this.PortalId))) + { + TabController.Instance.DeleteTabUrl(tabUrl, this.PortalId, true); + } + } + private void CreateSimulatedRequest(Uri url) { - var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", WebsitePhysicalAppPath); + var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", this.WebsitePhysicalAppPath); simulator.SimulateRequest(url); var browserCaps = new HttpBrowserCapabilities { Capabilities = new Hashtable() }; @@ -55,27 +116,28 @@ private void ProcessRequest(FriendlyUrlSettings settings, UrlTestHelper testHelp { var provider = new AdvancedUrlRewriter(); - provider.ProcessTestRequestWithContext(HttpContext.Current, - HttpContext.Current.Request.Url, - true, - testHelper.Result, - settings); + provider.ProcessTestRequestWithContext( + HttpContext.Current, + HttpContext.Current.Request.Url, + true, + testHelper.Result, + settings); testHelper.Response = HttpContext.Current.Response; } private string ReplaceTokens(Dictionary testFields, string url, string tabId) { - var defaultAlias = testFields.GetValue("DefaultAlias", String.Empty); - var httpAlias = testFields.GetValue("Alias", String.Empty); + var defaultAlias = testFields.GetValue("DefaultAlias", string.Empty); + var httpAlias = testFields.GetValue("Alias", string.Empty); var tabName = testFields["Page Name"]; - var vanityUrl = testFields.GetValue("VanityUrl", String.Empty); - var homeTabId = testFields.GetValue("HomeTabId", String.Empty); + var vanityUrl = testFields.GetValue("VanityUrl", string.Empty); + var homeTabId = testFields.GetValue("HomeTabId", string.Empty); - var userName = testFields.GetValue("UserName", String.Empty); - string userId = String.Empty; - if (!String.IsNullOrEmpty(userName)) + var userName = testFields.GetValue("UserName", string.Empty); + string userId = string.Empty; + if (!string.IsNullOrEmpty(userName)) { - var user = UserController.GetUserByName(PortalId, userName); + var user = UserController.GetUserByName(this.PortalId, userName); if (user != null) { userId = user.UserID.ToString(); @@ -86,111 +148,47 @@ private string ReplaceTokens(Dictionary testFields, string url, .Replace("{usealias}", defaultAlias) .Replace("{tabName}", tabName) .Replace("{tabId}", tabId) - .Replace("{portalId}", PortalId.ToString()) + .Replace("{portalId}", this.PortalId.ToString()) .Replace("{vanityUrl}", vanityUrl) .Replace("{userId}", userId) .Replace("{defaultPage}", _defaultPage); - } - - #endregion - - #region SetUp and TearDown - - [SetUp] - public override void SetUp() - { - base.SetUp(); - - DeleteTab(_testPage); - CreateTab(_testPage); - UpdateTabName(_tabId, "About Us"); - UpdateTabSkin(_tabId, ""); - CacheController.FlushPageIndexFromCache(); - GetDefaultAlias(); - _redirectMode = PortalController.GetPortalSetting("PortalAliasMapping", PortalId, "CANONICALURL"); - _sslEnforced = PortalController.GetPortalSettingAsBoolean("SSLEnforced", PortalId, false); - _sslEnabled = PortalController.GetPortalSettingAsBoolean("SSLEnabled", PortalId, false); - _primaryAlias = null; - _customLocale = null; - DataCache.ClearCache(); - } - - [TearDown] - public override void TearDown() - { - base.TearDown(); - - DeleteTab(_testPage); - UpdateTabName(_tabId, "About Us"); - UpdateTabSkin(_tabId, "[G]Skins/Xcillion/Inner.ascx"); - - if (!String.IsNullOrEmpty(_securePageName)) - { - var tab = TabController.Instance.GetTabByName(_securePageName, PortalId); - if (tab != null) - { - tab.IsSecure = false; - - UpdateTab(tab); - } - } - - if (_customLocale != null) - { - Localization.RemoveLanguageFromPortals(_customLocale.LanguageId, true); - Localization.DeleteLanguage(_customLocale, true); - } - if (_primaryAlias != null) - { - PortalAliasController.Instance.DeletePortalAlias(_primaryAlias); - } - - SetDefaultAlias(DefaultAlias); - PortalController.UpdatePortalSetting(PortalId, "PortalAliasMapping", _redirectMode, true, "en-us"); - PortalController.UpdatePortalSetting(PortalId, "SSLEnforced", _sslEnforced.ToString(), true, "en-us"); - PortalController.UpdatePortalSetting(PortalId, "SSLEnabled", _sslEnabled.ToString(), true, "en-us"); - - foreach (var tabUrl in CBO.FillCollection(DataProvider.Instance().GetTabUrls(PortalId))) - { - TabController.Instance.DeleteTabUrl(tabUrl, PortalId, true); - } - - } + } [TestFixtureSetUp] public override void TestFixtureSetUp() { base.TestFixtureSetUp(); - var tab = TabController.Instance.GetTabByName(_aboutUsPageName, PortalId); + var tab = TabController.Instance.GetTabByName(_aboutUsPageName, this.PortalId); if (tab == null) { - CreateTab(_aboutUsPageName); - tab = TabController.Instance.GetTabByName(_aboutUsPageName, PortalId); + this.CreateTab(_aboutUsPageName); + tab = TabController.Instance.GetTabByName(_aboutUsPageName, this.PortalId); } - _tabId = tab.TabID; + + this._tabId = tab.TabID; - //Add Portal Aliases + // Add Portal Aliases var aliasController = PortalAliasController.Instance; - TestUtil.ReadStream(String.Format("{0}", "Aliases"), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => { string[] fields = line.Split(','); - var alias = aliasController.GetPortalAlias(fields[0], PortalId); + var alias = aliasController.GetPortalAlias(fields[0], this.PortalId); if (alias == null) { alias = new PortalAliasInfo { HTTPAlias = fields[0], - PortalID = PortalId + PortalID = this.PortalId, }; PortalAliasController.Instance.AddPortalAlias(alias); } }); - TestUtil.ReadStream(String.Format("{0}", "Users"), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Users"), (line, header) => { string[] fields = line.Split(','); - TestUtil.AddUser(PortalId, fields[0].Trim(), fields[1].Trim(), fields[2].Trim()); + TestUtil.AddUser(this.PortalId, fields[0].Trim(), fields[1].Trim(), fields[2].Trim()); }); } @@ -200,83 +198,133 @@ public override void TestFixtureTearDown() base.TestFixtureTearDown(); var aliasController = PortalAliasController.Instance; - TestUtil.ReadStream(String.Format("{0}", "Aliases"), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => { string[] fields = line.Split(','); - var alias = aliasController.GetPortalAlias(fields[0], PortalId); + var alias = aliasController.GetPortalAlias(fields[0], this.PortalId); PortalAliasController.Instance.DeletePortalAlias(alias); }); - TestUtil.ReadStream(String.Format("{0}", "Users"), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Users"), (line, header) => { string[] fields = line.Split(','); - TestUtil.DeleteUser(PortalId, fields[0]); + TestUtil.DeleteUser(this.PortalId, fields[0]); }); + } + + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_BasicTestCases")] + public void AdvancedUrlRewriter_BasicTest(Dictionary testFields) + { + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); + this.ExecuteTest(settings, testFields, true); } - #endregion + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_DeletedTabHandlingTestCases")] + public void AdvancedUrlRewriter_DeletedTabHandling(Dictionary testFields) + { + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); + + var tab = TabController.Instance.GetTabByName(_testPage, this.PortalId); + if (Convert.ToBoolean(testFields["HardDeleted"])) + { + this.DeleteTab(_testPage); + CacheController.FlushPageIndexFromCache(); + } + else + { + tab.IsDeleted = Convert.ToBoolean(testFields["SoftDeleted"]); + tab.DisableLink = Convert.ToBoolean(testFields["Disabled"]); + if (Convert.ToBoolean(testFields["Expired"])) + { + tab.EndDate = DateTime.Now - TimeSpan.FromDays(1); + } + + this.UpdateTab(tab); + CacheController.FlushPageIndexFromCache(); + } + + string deletedTabHandling = testFields.GetValue("DeletedTabHandling"); - #region Private Methods + if (!string.IsNullOrEmpty(deletedTabHandling)) + { + switch (deletedTabHandling) + { + case "Do404Error": + settings.DeletedTabHandlingType = DeletedTabHandlingType.Do404Error; + break; + default: + settings.DeletedTabHandlingType = DeletedTabHandlingType.Do301RedirectToPortalHome; + break; + } + } + + this.SetDefaultAlias(testFields); + this.ExecuteTest(settings, testFields, true); + } + private void DeleteTab(string tabName) { - var tab = TabController.Instance.GetTabByName(tabName, PortalId); + var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); if (tab != null) { - TabController.Instance.DeleteTab(tab.TabID, PortalId); + TabController.Instance.DeleteTab(tab.TabID, this.PortalId); } } private void ExecuteTestForTab(TabInfo tab, FriendlyUrlSettings settings, Dictionary testFields) { - var httpAlias = testFields.GetValue("Alias", String.Empty); + var httpAlias = testFields.GetValue("Alias", string.Empty); var scheme = testFields["Scheme"]; var url = testFields["Test Url"]; var result = testFields["Expected Url"]; - var expectedStatus = Int32.Parse(testFields["Status"]); + var expectedStatus = int.Parse(testFields["Status"]); var redirectUrl = testFields.GetValue("Final Url"); var redirectReason = testFields.GetValue("RedirectReason"); var tabID = (tab == null) ? "-1" : tab.TabID.ToString(); - var expectedResult = ReplaceTokens(testFields, result, tabID); - var testurl = ReplaceTokens(testFields, url, tabID); - var expectedRedirectUrl = ReplaceTokens(testFields, redirectUrl, tabID); + var expectedResult = this.ReplaceTokens(testFields, result, tabID); + var testurl = this.ReplaceTokens(testFields, url, tabID); + var expectedRedirectUrl = this.ReplaceTokens(testFields, redirectUrl, tabID); - CreateSimulatedRequest(new Uri(testurl)); + this.CreateSimulatedRequest(new Uri(testurl)); var request = HttpContext.Current.Request; - var testHelper = new UrlTestHelper - { - HttpAliasFull = scheme + httpAlias + "/", - Result = new UrlAction(request) - { - IsSecureConnection = request.IsSecureConnection, - RawUrl = request.RawUrl - }, - RequestUri = new Uri(testurl), - QueryStringCol = new NameValueCollection() - }; - - ProcessRequest(settings, testHelper); - - //Test expected response status + var testHelper = new UrlTestHelper + { + HttpAliasFull = scheme + httpAlias + "/", + Result = new UrlAction(request) + { + IsSecureConnection = request.IsSecureConnection, + RawUrl = request.RawUrl, + }, + RequestUri = new Uri(testurl), + QueryStringCol = new NameValueCollection(), + }; + + this.ProcessRequest(settings, testHelper); + + // Test expected response status Assert.AreEqual(expectedStatus, testHelper.Response.StatusCode); switch (expectedStatus) { case 200: - //Test expected rewrite path - if (!String.IsNullOrEmpty(expectedResult)) + // Test expected rewrite path + if (!string.IsNullOrEmpty(expectedResult)) { Assert.AreEqual(expectedResult, testHelper.Result.RewritePath.TrimStart('/')); } + break; case 301: case 302: - //Test for final Url if redirected + // Test for final Url if redirected Assert.IsTrue(expectedRedirectUrl.Equals(testHelper.Result.FinalUrl.TrimStart('/'), StringComparison.InvariantCultureIgnoreCase)); Assert.AreEqual(redirectReason, testHelper.Result.Reason.ToString(), "Redirect reason incorrect"); break; @@ -286,14 +334,14 @@ private void ExecuteTestForTab(TabInfo tab, FriendlyUrlSettings settings, Dictio private void ExecuteTest(FriendlyUrlSettings settings, Dictionary testFields, bool setDefaultAlias) { var tabName = testFields["Page Name"]; - var tab = TabController.Instance.GetTabByName(tabName, PortalId); + var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); if (setDefaultAlias) { - SetDefaultAlias(testFields); + this.SetDefaultAlias(testFields); } - ExecuteTestForTab(tab, settings, testFields); + this.ExecuteTestForTab(tab, settings, testFields); } private void UpdateTab(TabInfo tab) @@ -302,79 +350,21 @@ private void UpdateTab(TabInfo tab) { TabController.Instance.UpdateTab(tab); } - } private void UpdateTabName(int tabId, string newName) { - var tab = TabController.Instance.GetTab(tabId, PortalId, false); + var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); tab.TabName = newName; TabController.Instance.UpdateTab(tab); } private void UpdateTabSkin(int tabId, string newSkin) { - var tab = TabController.Instance.GetTab(tabId, PortalId, false); + var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); tab.SkinSrc = newSkin; TabController.Instance.UpdateTab(tab); - } - - #endregion - - #region Tests - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_BasicTestCases")] - public void AdvancedUrlRewriter_BasicTest(Dictionary testFields) - { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); - - ExecuteTest(settings, testFields, true); - } - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_DeletedTabHandlingTestCases")] - public void AdvancedUrlRewriter_DeletedTabHandling(Dictionary testFields) - { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); - - var tab = TabController.Instance.GetTabByName(_testPage, PortalId); - if (Convert.ToBoolean(testFields["HardDeleted"])) - { - DeleteTab(_testPage); - CacheController.FlushPageIndexFromCache(); - } - else - { - tab.IsDeleted = Convert.ToBoolean(testFields["SoftDeleted"]); - tab.DisableLink = Convert.ToBoolean(testFields["Disabled"]); - if (Convert.ToBoolean(testFields["Expired"])) - { - tab.EndDate = DateTime.Now - TimeSpan.FromDays(1); - } - UpdateTab(tab); - CacheController.FlushPageIndexFromCache(); - } - - string deletedTabHandling = testFields.GetValue("DeletedTabHandling"); - - if (!String.IsNullOrEmpty(deletedTabHandling)) - { - switch (deletedTabHandling) - { - case "Do404Error": - settings.DeletedTabHandlingType = DeletedTabHandlingType.Do404Error; - break; - default: - settings.DeletedTabHandlingType = DeletedTabHandlingType.Do301RedirectToPortalHome; - break; - } - } - - SetDefaultAlias(testFields); - - ExecuteTest(settings, testFields, true); - } + } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_DoNotRedirect")] @@ -383,54 +373,54 @@ public void AdvancedUrlRewriter_DoNotRedirect(Dictionary testFie var tabName = testFields["Page Name"]; var doNotRedirect = testFields["DoNotRedirect"]; - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); - UpdateTabSetting(tabName, "DoNotRedirect", doNotRedirect); + this.UpdateTabSetting(tabName, "DoNotRedirect", doNotRedirect); settings.UseBaseFriendlyUrls = testFields["UseBaseFriendlyUrls"]; - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); - UpdateTabSetting(tabName, "DoNotRedirect", "False"); + this.UpdateTabSetting(tabName, "DoNotRedirect", "False"); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_ForwardExternalUrlTestCases")] public void AdvancedUrlRewriter_ForwardExternalUrls(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); - var tab = TabController.Instance.GetTabByName(_testPage, PortalId); + var tab = TabController.Instance.GetTabByName(_testPage, this.PortalId); tab.Url = testFields["ExternalUrl"]; TabController.Instance.UpdateTab(tab); - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_ForceLowerCaseTestCases")] public void AdvancedUrlRewriter_ForceLowerCase(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); string forceLowerCaseRegex = testFields.GetValue("ForceLowerCaseRegex"); - if (!String.IsNullOrEmpty(forceLowerCaseRegex)) + if (!string.IsNullOrEmpty(forceLowerCaseRegex)) { settings.ForceLowerCaseRegex = forceLowerCaseRegex; } - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_RegexTestCases")] public void AdvancedUrlRewriter_Regex(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); string regexSetting = testFields["Setting"]; string regexValue = testFields["Value"]; - if (!String.IsNullOrEmpty(regexValue)) + if (!string.IsNullOrEmpty(regexValue)) { switch (regexSetting) { @@ -467,72 +457,72 @@ public void AdvancedUrlRewriter_Regex(Dictionary testFields) } } - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_ReplaceCharsTestCases")] public void AdvancedUrlRewriter_ReplaceChars(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); string testPageName = testFields.GetValue("TestPageName"); TabInfo tab = null; - if (!String.IsNullOrEmpty(testPageName)) + if (!string.IsNullOrEmpty(testPageName)) { var tabName = testFields["Page Name"]; - tab = TabController.Instance.GetTabByName(tabName, PortalId); + tab = TabController.Instance.GetTabByName(tabName, this.PortalId); tab.TabName = testPageName; TabController.Instance.UpdateTab(tab); - //Refetch tab from DB + // Refetch tab from DB tab = TabController.Instance.GetTab(tab.TabID, tab.PortalID, false); } string autoAscii = testFields.GetValue("AutoAscii"); - if (!String.IsNullOrEmpty(autoAscii)) + if (!string.IsNullOrEmpty(autoAscii)) { settings.AutoAsciiConvert = Convert.ToBoolean(autoAscii); } TestUtil.GetReplaceCharDictionary(testFields, settings.ReplaceCharacterDictionary); - SetDefaultAlias(testFields); + this.SetDefaultAlias(testFields); - ExecuteTestForTab(tab, settings, testFields); + this.ExecuteTestForTab(tab, settings, testFields); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_ReplaceSpaceTestCases")] public void AdvancedUrlRewriter_ReplaceSpace(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); string replaceSpaceWith = testFields.GetValue("ReplaceSpaceWith"); - if (!String.IsNullOrEmpty(replaceSpaceWith)) + if (!string.IsNullOrEmpty(replaceSpaceWith)) { settings.ReplaceSpaceWith = replaceSpaceWith; } - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_SiteRootRedirectTestCases")] public void AdvancedUrlRewriter_SiteRootRedirect(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", "SiteRootRedirect", PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", "SiteRootRedirect", this.PortalId); string scheme = testFields["Scheme"]; - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); if (testFields["TestName"].Contains("Resubmit")) { var httpAlias = testFields["Alias"]; settings.DoNotRedirectRegex = scheme + httpAlias; - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); } } @@ -542,17 +532,16 @@ public void AdvancedUrlRewriter_0_PrimaryPortalAlias(Dictionary { string defaultAlias = testFields["DefaultAlias"]; - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); string language = testFields["Language"].Trim(); string skin = testFields["Skin"].Trim(); - if (!String.IsNullOrEmpty(language)) + if (!string.IsNullOrEmpty(language)) { - _customLocale = new Locale { Code = language, Fallback = "en-US" }; - _customLocale.Text = CultureInfo.GetCultureInfo(_customLocale.Code).NativeName; - Localization.SaveLanguage(_customLocale); - Localization.AddLanguageToPortals(_customLocale.LanguageId); - + this._customLocale = new Locale { Code = language, Fallback = "en-US" }; + this._customLocale.Text = CultureInfo.GetCultureInfo(this._customLocale.Code).NativeName; + Localization.SaveLanguage(this._customLocale); + Localization.AddLanguageToPortals(this._customLocale.LanguageId); } if (testFields.ContainsKey("Final Url")) @@ -560,28 +549,29 @@ public void AdvancedUrlRewriter_0_PrimaryPortalAlias(Dictionary testFields["Final Url"] = testFields["Final Url"].Replace("{useAlias}", defaultAlias); } - PortalController.UpdatePortalSetting(PortalId, "PortalAliasMapping", "REDIRECT", true, "en-us"); - var alias = PortalAliasController.Instance.GetPortalAlias(defaultAlias, PortalId); + PortalController.UpdatePortalSetting(this.PortalId, "PortalAliasMapping", "REDIRECT", true, "en-us"); + var alias = PortalAliasController.Instance.GetPortalAlias(defaultAlias, this.PortalId); if (alias == null) { alias = new PortalAliasInfo { HTTPAlias = defaultAlias, - PortalID = PortalId, - IsPrimary = true + PortalID = this.PortalId, + IsPrimary = true, }; - if (!(String.IsNullOrEmpty(language) && String.IsNullOrEmpty(skin))) + if (!(string.IsNullOrEmpty(language) && string.IsNullOrEmpty(skin))) { alias.CultureCode = language; alias.Skin = skin; } - PortalAliasController.Instance.AddPortalAlias(alias); + + PortalAliasController.Instance.AddPortalAlias(alias); } - SetDefaultAlias(defaultAlias); - ExecuteTest(settings, testFields, false); - - - alias = PortalAliasController.Instance.GetPortalAlias(defaultAlias, PortalId); + + this.SetDefaultAlias(defaultAlias); + this.ExecuteTest(settings, testFields, false); + + alias = PortalAliasController.Instance.GetPortalAlias(defaultAlias, this.PortalId); if (alias != null) { PortalAliasController.Instance.DeletePortalAlias(alias); @@ -592,64 +582,65 @@ public void AdvancedUrlRewriter_0_PrimaryPortalAlias(Dictionary [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_VanityUrlTestCases")] public void AdvancedUrlRewriter_VanityUrl(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); settings.DeletedTabHandlingType = DeletedTabHandlingType.Do301RedirectToPortalHome; - var vanityUrl = testFields.GetValue("VanityUrl", String.Empty); - var userName = testFields.GetValue("UserName", String.Empty); - var redirectOld = testFields.GetValue("RedirectOldProfileUrl", String.Empty); + var vanityUrl = testFields.GetValue("VanityUrl", string.Empty); + var userName = testFields.GetValue("UserName", string.Empty); + var redirectOld = testFields.GetValue("RedirectOldProfileUrl", string.Empty); - if (!String.IsNullOrEmpty(userName)) + if (!string.IsNullOrEmpty(userName)) { - var user = UserController.GetUserByName(PortalId, userName); + var user = UserController.GetUserByName(this.PortalId, userName); if (user != null) { user.VanityUrl = vanityUrl; - UserController.UpdateUser(PortalId, user); + UserController.UpdateUser(this.PortalId, user); } } - if (!String.IsNullOrEmpty(redirectOld)) + if (!string.IsNullOrEmpty(redirectOld)) { settings.RedirectOldProfileUrl = Convert.ToBoolean(redirectOld); } - ExecuteTest(settings, testFields, true); + + this.ExecuteTest(settings, testFields, true); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_SecureRedirectTestCases")] public void AdvancedUrlRewriter_SecureRedirect(Dictionary testFields) { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); var isClient = Convert.ToBoolean(testFields["Client"]); - _securePageName = testFields["Page Name"].Trim(); + this._securePageName = testFields["Page Name"].Trim(); - PortalController.UpdatePortalSetting(PortalId, "SSLEnforced", testFields["Enforced"].Trim(), true, "en-us"); - PortalController.UpdatePortalSetting(PortalId, "SSLEnabled", testFields["Enabled"].Trim(), true, "en-us"); + PortalController.UpdatePortalSetting(this.PortalId, "SSLEnforced", testFields["Enforced"].Trim(), true, "en-us"); + PortalController.UpdatePortalSetting(this.PortalId, "SSLEnabled", testFields["Enabled"].Trim(), true, "en-us"); var isSecure = Convert.ToBoolean(testFields["IsSecure"].Trim()); if (isSecure) { - var tab = TabController.Instance.GetTabByName(_securePageName, PortalId); + var tab = TabController.Instance.GetTabByName(this._securePageName, this.PortalId); tab.IsSecure = true; - UpdateTab(tab); + this.UpdateTab(tab); } settings.SSLClientRedirect = isClient; - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_JiraTests")] public void AdvancedUrlRewriter_JiraTests(Dictionary testFields) { - var testName = testFields.GetValue("Test File", String.Empty); + var testName = testFields.GetValue("Test File", string.Empty); - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", "Jira_Tests", testName + ".csv", PortalId); + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", "Jira_Tests", testName + ".csv", this.PortalId); var dictionary = UrlTestFactoryClass.GetDictionary("UrlRewrite", "Jira_Tests", testName + "_dic.csv"); int homeTabId = -1; @@ -658,25 +649,24 @@ public void AdvancedUrlRewriter_JiraTests(Dictionary testFields) switch (keyValuePair.Key) { case "HomeTabId": - homeTabId = UpdateHomeTab(Int32.Parse(keyValuePair.Value)); + homeTabId = this.UpdateHomeTab(int.Parse(keyValuePair.Value)); break; default: break; } } - ExecuteTest(settings, testFields, true); + this.ExecuteTest(settings, testFields, true); if (homeTabId != -1) { - UpdateHomeTab(homeTabId); + this.UpdateHomeTab(homeTabId); } - } private int UpdateHomeTab(int homeTabId) { - var portalInfo = PortalController.Instance.GetPortal(PortalId); + var portalInfo = PortalController.Instance.GetPortal(this.PortalId); int oldHomeTabId = portalInfo.HomeTabId; portalInfo.HomeTabId = homeTabId; @@ -685,11 +675,9 @@ private int UpdateHomeTab(int homeTabId) private void UpdateTabSetting(string tabName, string settingName, string settingValue) { - var tab = TabController.Instance.GetTabByName(tabName, PortalId); + var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); tab.TabSettings[settingName] = settingValue; TabController.Instance.UpdateTab(tab); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs index fe4b2600baf..10c0b8c5496 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs @@ -1,97 +1,96 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; - -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Tests.Utilities; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { + using System; + using System.Collections.Generic; + using System.Data; + + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Tests.Utilities; + using NUnit.Framework; + public class UrlTestBase : DnnWebTest { - public UrlTestBase(int portalId) : base(portalId) + public UrlTestBase(int portalId) + : base(portalId) { } protected virtual string DefaultAlias { get; private set; } - protected virtual string TestType { get { return String.Empty; } } - - #region SetUp and TearDown - + protected virtual string TestType + { + get { return string.Empty; } + } + public virtual void SetUp() { - ExecuteScriptFile(String.Format("{0}\\{1}\\{2}", TestType, GetTestFolder(), "SetUp.sql")); + this.ExecuteScriptFile(string.Format("{0}\\{1}\\{2}", this.TestType, this.GetTestFolder(), "SetUp.sql")); } public virtual void TestFixtureSetUp() { - ExecuteScriptFile(String.Format("{0}\\{1}", TestType, "SetUp.sql")); + this.ExecuteScriptFile(string.Format("{0}\\{1}", this.TestType, "SetUp.sql")); } public virtual void TearDown() { - ExecuteScriptFile(String.Format("{0}\\{1}\\{2}", TestType, GetTestFolder(), "TearDown.sql")); + this.ExecuteScriptFile(string.Format("{0}\\{1}\\{2}", this.TestType, this.GetTestFolder(), "TearDown.sql")); } public virtual void TestFixtureTearDown() { - ExecuteScriptFile(String.Format("{0}\\{1}", TestType, "TearDown.sql")); - } - - #endregion - + this.ExecuteScriptFile(string.Format("{0}\\{1}", this.TestType, "TearDown.sql")); + } + protected void CreateTab(string tabName) { - var tab = new TabInfo { PortalID = PortalId, TabName = tabName }; + var tab = new TabInfo { PortalID = this.PortalId, TabName = tabName }; TabController.Instance.AddTab(tab); } - private void ExecuteScriptFile(string fileName) + protected void GetDefaultAlias() { - var sql = TestUtil.ReadStream(fileName); - - if (!String.IsNullOrEmpty(sql)) + foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId)) { - DataProvider.Instance().ExecuteScript(sql); + if (alias.IsPrimary) + { + this.DefaultAlias = alias.HTTPAlias; + break; + } } } - private string GetTestFolder() + protected void SetDefaultAlias(Dictionary testFields) { - var testName = TestContext.CurrentContext.Test.Name; - return testName.Substring(0, testName.IndexOf("_", StringComparison.Ordinal)); + this.SetDefaultAlias(testFields["Alias"]); } - protected void GetDefaultAlias() + private void ExecuteScriptFile(string fileName) { - foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(PortalId)) + var sql = TestUtil.ReadStream(fileName); + + if (!string.IsNullOrEmpty(sql)) { - if (alias.IsPrimary) - { - DefaultAlias = alias.HTTPAlias; - break; - } + DataProvider.Instance().ExecuteScript(sql); } } - protected void SetDefaultAlias(Dictionary testFields) + private string GetTestFolder() { - SetDefaultAlias(testFields["Alias"]); + var testName = TestContext.CurrentContext.Test.Name; + return testName.Substring(0, testName.IndexOf("_", StringComparison.Ordinal)); } protected void SetDefaultAlias(string defaultAlias) { - foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(PortalId)) + foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId)) { if (string.Equals(alias.HTTPAlias, defaultAlias, StringComparison.InvariantCultureIgnoreCase)) { @@ -101,8 +100,5 @@ protected void SetDefaultAlias(string defaultAlias) } } } - - - } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs index cb0c8784f97..0fc4b40a55a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs @@ -1,68 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; - -using DotNetNuke.Entities.Urls; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { + using System; + using System.Collections; + using System.Collections.Generic; + + using DotNetNuke.Entities.Urls; + using NUnit.Framework; + internal static class UrlTestFactoryClass { - private static void GetTestsWithAliases(string testType, string testName, ArrayList testData) + internal static IEnumerable FriendlyUrl_BaseTestCases { - TestUtil.ReadStream(String.Format("{0}", "Aliases"), (line, header) => + get { - string[] fields = line.Split(','); - GetTests(fields[1].Trim(), fields[0].Trim(), testType, testName, testData); - }); - + var testData = new ArrayList(); + + TestUtil.ReadStream("FriendlyUrl\\BaseTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + + return testData; + } } - private static void GetTests(string testPrefix, string alias, string testType, string testName, ArrayList testData) + internal static IEnumerable FriendlyUrl_ForceLowerCaseTestCases { - try + get { - //Read Test File Data - TestUtil.ReadStream(String.Format("{0}\\{1}\\{2}", testType, testName, "TestFile"), (line, header) => - { - var fieldList = new Dictionary(); - fieldList["TestName"] = testName; - fieldList["Alias"] = alias; - string[] headers = header.Split(','); - string[] fields = line.Split(','); - for (int i = 0; i < fields.Length; i++ ) - { - string key = headers[i].Trim(new[] { '\t', '"' }); - string val = fields[i].Trim(new[] {'\t', '"'}); + var testData = new ArrayList(); - fieldList[key] = val; - } + GetTestsWithAliases("FriendlyUrl", "ForceLowerCase", testData); - string name = testName + "_"; - if (!String.IsNullOrEmpty(testPrefix)) - { - name += testPrefix + "_"; - } - name += fields[0]; + return testData; + } + } - testData.Add(new TestCaseData(fieldList).SetName(name)); - }); - } - // ReSharper disable RedundantCatchClause - #pragma warning disable 168 - catch (Exception exc) - #pragma warning restore 168 + internal static IEnumerable FriendlyUrl_ImprovedTestCases + { + get { + var testData = new ArrayList(); - throw; + TestUtil.ReadStream("FriendlyUrl\\ImprovedTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + + return testData; } - // ReSharper restore RedundantCatchClause } internal static FriendlyUrlSettings GetSettings(string testType, string testName, int portalId) @@ -74,8 +58,8 @@ internal static FriendlyUrlSettings GetSettings(string testType, string testName { var settings = new FriendlyUrlSettings(portalId); - //Read Test Settings - TestUtil.ReadStream(String.Format("{0}\\{1}\\{2}", testType, testName, settingsFile), (line, header) => + // Read Test Settings + TestUtil.ReadStream(string.Format("{0}\\{1}\\{2}", testType, testName, settingsFile), (line, header) => { string[] fields = line.Split(','); string key = fields[0].Trim(); @@ -105,57 +89,73 @@ internal static FriendlyUrlSettings GetSettings(string testType, string testName }); return settings; } - - internal static Dictionary GetDictionary(string testType, string testName, string settingsFile) + + private static void GetTestsWithAliases(string testType, string testName, ArrayList testData) { - var dictionary = new Dictionary(); - - //Read Test Settings - TestUtil.ReadStream(String.Format("{0}\\{1}\\{2}", testType, testName, settingsFile), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => { string[] fields = line.Split(','); - string key = fields[0].Trim(); - string value = fields[1].Trim(); - - dictionary.Add(key, value); + GetTests(fields[1].Trim(), fields[0].Trim(), testType, testName, testData); }); - return dictionary; } - internal static IEnumerable FriendlyUrl_BaseTestCases + private static void GetTests(string testPrefix, string alias, string testType, string testName, ArrayList testData) { - get + try { - var testData = new ArrayList(); + // Read Test File Data + TestUtil.ReadStream(string.Format("{0}\\{1}\\{2}", testType, testName, "TestFile"), (line, header) => + { + var fieldList = new Dictionary(); + fieldList["TestName"] = testName; + fieldList["Alias"] = alias; + string[] headers = header.Split(','); + string[] fields = line.Split(','); + for (int i = 0; i < fields.Length; i++) + { + string key = headers[i].Trim(new[] { '\t', '"' }); + string val = fields[i].Trim(new[] { '\t', '"' }); - TestUtil.ReadStream("FriendlyUrl\\BaseTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + fieldList[key] = val; + } - return testData; - } - } + string name = testName + "_"; + if (!string.IsNullOrEmpty(testPrefix)) + { + name += testPrefix + "_"; + } + + name += fields[0]; - internal static IEnumerable FriendlyUrl_ForceLowerCaseTestCases - { - get + testData.Add(new TestCaseData(fieldList).SetName(name)); + }); + } + + // ReSharper disable RedundantCatchClause +#pragma warning disable 168 + catch (Exception exc) +#pragma warning restore 168 { - var testData = new ArrayList(); - - GetTestsWithAliases("FriendlyUrl", "ForceLowerCase", testData); - - return testData; + throw; } + + // ReSharper restore RedundantCatchClause } - internal static IEnumerable FriendlyUrl_ImprovedTestCases + internal static Dictionary GetDictionary(string testType, string testName, string settingsFile) { - get - { - var testData = new ArrayList(); + var dictionary = new Dictionary(); - TestUtil.ReadStream("FriendlyUrl\\ImprovedTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + // Read Test Settings + TestUtil.ReadStream(string.Format("{0}\\{1}\\{2}", testType, testName, settingsFile), (line, header) => + { + string[] fields = line.Split(','); + string key = fields[0].Trim(); + string value = fields[1].Trim(); - return testData; - } + dictionary.Add(key, value); + }); + return dictionary; } internal static IEnumerable FriendlyUrl_PageExtensionTestCases @@ -177,7 +177,7 @@ internal static IEnumerable FriendlyUrl_PrimaryPortalAliasTestCases var testData = new ArrayList(); GetTestsWithAliases("FriendlyUrl", "PrimaryPortalAlias", testData); - + return testData; } } @@ -321,7 +321,7 @@ internal static IEnumerable UrlRewrite_PrimaryPortalAliasTestCases var testData = new ArrayList(); GetTestsWithAliases("UrlRewrite", "PrimaryPortalAlias", testData); - GetTests(String.Empty, String.Empty, "UrlRewrite", "PrimaryPortalAlias_Default", testData); + GetTests(string.Empty, string.Empty, "UrlRewrite", "PrimaryPortalAlias_Default", testData); return testData; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs index 625fc283cec..7a21392def7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs @@ -1,21 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using System.Web; - -using DotNetNuke.Entities.Urls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Urls { + using System; + using System.Collections.Specialized; + using System.Web; + + using DotNetNuke.Entities.Urls; + internal class UrlTestHelper { public Uri RequestUri { get; set; } + public UrlAction Result { get; set; } + public NameValueCollection QueryStringCol { get; set; } + public string HttpAliasFull { get; set; } + public HttpResponse Response { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Urls/packages.config index 5d90198d8bc..2b03ba86c18 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/packages.config @@ -1,5 +1,6 @@ - - - - + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/AssemblyInfo.cs index d944c4805d0..3cef58519d7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/AssemblyInfo.cs @@ -1,14 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("TestUtilities")] [assembly: AssemblyDescription("Open Source Web Application Framework")] @@ -16,28 +15,24 @@ [assembly: AssemblyProduct("https://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2018 by DotNetNuke Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DotNetNuke")] - - -// 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 + +// 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("f9904f9b-176f-469d-a5fd-f3011b2cc52e")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] - [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs index 712859f0f11..41fd7e82ecf 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs @@ -1,27 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Caching; -using DotNetNuke.Entities.Content.Taxonomy; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable InconsistentNaming - namespace DotNetNuke.Tests.Utilities { + using System.Web.Caching; + + using DotNetNuke.Entities.Content.Taxonomy; + public class Constants - { - #region Cacheing Constants - + { public const string CACHEING_InValidKey = "InValidKey"; public const string CACHEING_ParamCacheKey = "CacheKey"; public const string CACHEING_ValidKey = "ValidKey"; - public const string CACHEING_ValidValue = "ValidValue"; - - #endregion - - #region User Constants - + public const string CACHEING_ValidValue = "ValidValue"; public const int USER_Null = -1; public const int USER_ValidId = 200; public const int USER_InValidId = 42; @@ -29,7 +22,7 @@ public class Constants public const int USER_TenId = 10; public const string USER_TenName = "user10"; public const int USER_ElevenId = 11; - public const string USER_ElevenName = "user11"; + public const string USER_ElevenName = "user11"; public const int UserID_Host = 1; public const int UserID_Admin = 2; public const int UserID_User12 = 12; @@ -43,13 +36,7 @@ public class Constants public const string UserDisplayName_FirstSocialGroupOwner = "First Social Group Owner"; public const string RuFirstName = "TestUser"; public const string RuLastName = "Automation"; - public const string DefaultPassword = "dnnhost"; - - - #endregion - - #region Role Constants - + public const string DefaultPassword = "dnnhost"; public const int RoleID_Administrators = 0; public const int RoleID_RegisteredUsers = 1; public const int RoleID_Subscribers = 2; @@ -60,23 +47,13 @@ public class Constants public const string RoleName_RegisteredUsers = "RegisteredUsers"; public const string RoleName_Subscribers = "Subscribers"; public const string RoleName_Translator_EN_US = "translator_EN_US"; - public const string RoleName_FirstSocialGroup = "First Social Group"; - - #endregion - - #region Portal Constants - + public const string RoleName_FirstSocialGroup = "First Social Group"; public const int PORTAL_Zero = 0; public const int PORTAL_One = 1; public const int PORTAL_Null = -1; public const int PORTAL_InValidPortalId = -1; - public const int PORTAL_ValidPortalId = 1; - - - #endregion - - #region PortalSettings Constants - + public const int PORTAL_ValidPortalId = 1; + /// The setting name that stores whether attachments are allowed. public const string PORTALSETTING_MessagingAllowAttachments_Name = "MessagingAllowAttachments"; @@ -84,22 +61,13 @@ public class Constants public const string PORTALSETTING_MessagingIncludeAttachments_Name = "MessagingIncludeAttachments"; public const string PORTALSETTING_MessagingAllowAttachments_Value_YES = "YES"; - public const string PORTALSETTING_MessagingAllowAttachments_Value_NO = "NO"; - - #endregion - - #region Culture Constants - - public const string CULTURE_EN_US = "en-US"; - #endregion - - #region PortalGroup Constants - + public const string PORTALSETTING_MessagingAllowAttachments_Value_NO = "NO"; + public const string CULTURE_EN_US = "en-US"; public const int PORTALGROUP_ValidPortalGroupId = 1; public const int PORTALGROUP_AddPortalGroupId = 2; public const int PORTALGROUP_DeletePortalGroupId = 3; - public const int PORTALGROUP_InValidPortalGroupId = 999; - + public const int PORTALGROUP_InValidPortalGroupId = 999; + public const string PORTALGROUP_ValidName = "PortalGroupName"; public const string PORTALGROUP_ValidDescription = "PortalGroupDescription"; public const int PORTALGROUP_UpdatePortalGroupId = 4; @@ -109,12 +77,9 @@ public class Constants public const int PORTALGROUP_ValidPortalGroupCount = 5; public const string PORTALGROUP_ValidNameFormat = "PortalGroupName {0}"; - public const string PORTALGROUP_ValidDescriptionFormat = "PortalGroupDescription {0}"; - #endregion - - #region ContentItem Constants - - //Valid Content values + public const string PORTALGROUP_ValidDescriptionFormat = "PortalGroupDescription {0}"; + + // Valid Content values public const int CONTENT_ValidContentItemId = 1; public const string CONTENT_ValidContent = "Content"; public const string CONTENT_ValidContentKey = "ContentKey"; @@ -130,7 +95,7 @@ public class Constants public const int CONTENT_ValidStartTabId = 10; public const int CONTENT_ValidStartModuleId = 100; - //InValid Content values + // InValid Content values public const int CONTENT_InValidContentItemId = 999; public const string CONTENT_InValidContent = ""; public const int CONTENT_InValidModuleId = 888; @@ -156,12 +121,7 @@ public class Constants public const string CONTENT_NewMetaDataValue = "My abstract"; public const string CONTENT_InValidMetaDataName = "InvalidName"; public const string CONTENT_InValidMetaDataValue = "InvalidValue"; - public const int CONTENT_MetaDataCount = 4; - - #endregion - - #region ContentType Constants - + public const int CONTENT_MetaDataCount = 4; public const int CONTENTTYPE_ValidContentTypeId = 1; public const string CONTENTTYPE_ValidContentType = "ContentType Name"; @@ -210,12 +170,7 @@ public class Constants public const int CONTENTTYPE_ValidContentTemplateId = 2; public const int CONTENTTYPE_ValidContentTemplateCount = 7; public const int CONTENTTYPE_InValidContentTemplateId = -1; - public const int CONTENTTYPE_UpdateContentTemplateId = 4; - - #endregion - - #region ScopeType Constants - + public const int CONTENTTYPE_UpdateContentTemplateId = 4; public const int SCOPETYPE_ValidScopeTypeId = 1; public const string SCOPETYPE_ValidScopeType = "ScopeType Name"; @@ -232,22 +187,12 @@ public class Constants public const string SCOPETYPE_GetByNameScopeType = "TestGetByName"; public const string SCOPETYPE_OriginalUpdateScopeType = "TestUpdate"; - public const string SCOPETYPE_UpdateScopeType = "Update Name"; - - #endregion - - #region Tag Constants - + public const string SCOPETYPE_UpdateScopeType = "Update Name"; public const int TAG_DuplicateContentItemId = 1; public const int TAG_DuplicateTermId = 6; public const int TAG_NoContentContentId = 99; public const int TAG_ValidContentId = 1; - public const int TAG_ValidContentCount = 2; - - #endregion - - #region Term Constants - + public const int TAG_ValidContentCount = 2; public const string TERM_CacheKey = "DNN_Terms_{0}"; public const int TERM_ValidTermId = 1; @@ -279,12 +224,7 @@ public class Constants public const int TERM_ValidCountForContent1 = 2; public const int TERM_ValidContent1 = 1; - public const int TERM_ValidContent2 = 2; - - #endregion - - #region Vocabulary Constants - + public const int TERM_ValidContent2 = 2; public const string VOCABULARY_CacheKey = "DNN_Vocabularies"; public const int VOCABULARY_ValidVocabularyId = 1; @@ -318,12 +258,7 @@ public class Constants public const string VOCABULARY_ValidNameFormat = "Vocabulary Name {0}"; public const int VOCABULARY_ValidCountForScope1 = 2; public const int VOCABULARY_ValidScope1 = 1; - public const int VOCABULARY_ValidScope2 = 2; - - #endregion - - #region Folder Constants - + public const int VOCABULARY_ValidScope2 = 2; public const int FOLDER_ValidFileId = 1; public const int FOLDER_InvalidFileId = -1; public const int FOLDER_ValidFileSize = 16; @@ -359,12 +294,7 @@ public class Constants public const string FOLDER_OtherValidSubFolderRelativePath = "folder/othersubfolder/"; public const string FOLDER_ModifiedFileHash = "0123456789X"; public const string FOLDER_UnmodifiedFileHash = "0123456789"; - public const string FOLDER_FileStartDate = "2010-01-01T00:00:00"; - - #endregion - - #region Social constants - + public const string FOLDER_FileStartDate = "2010-01-01T00:00:00"; public const int SOCIAL_InValidRelationshipType = 999; public const int SOCIAL_InValidRelationship = 999; public const int SOCIAL_InValidUserRelationship = 999; @@ -399,19 +329,13 @@ public class Constants public const string LOCALIZATION_UserRelationship_Added = "Added UserRelationship ID {0}, UserID {1}, RelatedUserID {2}"; public const string LOCALIZATION_UserRelationship_Updated_Key = "UserRelationship_Updated"; public const string LOCALIZATION_UserRelationship_Updated = "Updated UserRelationship ID {0}, UserID {1}, RelatedUserID {2}"; - - + public const string LOCALIZATION_UserRelationshipPreference_Deleted_Key = "UserRelationshipPreference_Deleted"; public const string LOCALIZATION_UserRelationshipPreference_Deleted = "Deleted UserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; public const string LOCALIZATION_UserRelationshipPreference_Added_Key = "UserRelationshipPreference_Added"; public const string LOCALIZATION_UserRelationshipPreference_Added = "Added UserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; public const string LOCALIZATION_UserRelationshipPreference_Updated_Key = "UserRelationshipPreference_Updated"; - public const string LOCALIZATION_UserRelationshipPreference_Updated = "UpdatedUserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; - - #endregion - - #region SocialMessaging constants - + public const string LOCALIZATION_UserRelationshipPreference_Updated = "UpdatedUserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; public const bool Messaging_ReadMessage = true; public const bool Messaging_UnReadMessage = false; public const bool Messaging_ArchivedMessage = true; @@ -434,12 +358,7 @@ public class Constants public const string Messaging_NotificationSubject = "Friend Request Received"; public const string Messaging_NotificationBody = "You've received a new friend request from {0}"; public const bool Messaging_IncludeDismissAction = true; - public const string Messaging_NotificationContext = "context"; - - #endregion - - #region Data Constants - + public const string Messaging_NotificationContext = "context"; public const string COLUMNNAME_Name = "Name"; public const string COLUMNNAME_PersonName = "PersonName"; @@ -476,18 +395,12 @@ public class Constants public const string CACHE_ScopeModule = "ModuleId"; public const int CACHE_TimeOut = 10; public const CacheItemPriority CACHE_Priority = CacheItemPriority.High; - - + public const string TABLENAME_Dog = "Dogs"; public const string TABLENAME_Key = "ID"; public const string TABLENAME_Prefix = "dnn_"; public const string TABLENAME_Person = "People"; - public const string TABLENAME_Person_Key = "PersonID"; - - #endregion - - #region PagedLists Constants - + public const string TABLENAME_Person_Key = "PersonID"; public const int PAGE_First = 0; public const int PAGE_Second = 1; public const int PAGE_Last = 4; @@ -495,10 +408,7 @@ public class Constants public const int PAGE_TotalCount = 22; public const int PAGE_NegativeIndex = -1; - public const int PAGE_OutOfRange = 5; - - #endregion - + public const int PAGE_OutOfRange = 5; public const int TAB_ValidId = 10; public const int TAB_InValidId = -1; public const int MODULE_ValidId = 100; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs index 95773546a61..090b0467461 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Security.Cryptography; -using System.Text; - -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System; + using System.Security.Cryptography; + using System.Text; + + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Services.FileSystem; + public class ContentTestHelper { public static ContentItem CreateValidContentItem() { - ContentItem content = new ContentItem {Content = Constants.CONTENT_ValidContent, ContentKey = Constants.CONTENT_ValidContentKey, Indexed = Constants.CONTENT_IndexedFalse}; + ContentItem content = new ContentItem { Content = Constants.CONTENT_ValidContent, ContentKey = Constants.CONTENT_ValidContentKey, Indexed = Constants.CONTENT_IndexedFalse }; return content; } @@ -28,7 +28,7 @@ public static ContentType CreateValidContentType() public static Term CreateValidHeirarchicalTerm(int vocabularyId, int parentId) { - Term term = new Term(vocabularyId) {Name = Constants.TERM_ValidName, Description = Constants.TERM_ValidName, Weight = Constants.TERM_ValidWeight, ParentTermId = parentId}; + Term term = new Term(vocabularyId) { Name = Constants.TERM_ValidName, Description = Constants.TERM_ValidName, Weight = Constants.TERM_ValidWeight, ParentTermId = parentId }; return term; } @@ -40,20 +40,20 @@ public static ScopeType CreateValidScopeType() public static Term CreateValidSimpleTerm(int vocabularyId) { - Term term = new Term(vocabularyId) {Name = Constants.TERM_ValidName, Description = Constants.TERM_ValidName, Weight = Constants.TERM_ValidWeight}; + Term term = new Term(vocabularyId) { Name = Constants.TERM_ValidName, Description = Constants.TERM_ValidName, Weight = Constants.TERM_ValidWeight }; return term; } public static Vocabulary CreateValidVocabulary() { - Vocabulary vocabulary = new Vocabulary - { - Name = Constants.VOCABULARY_ValidName, - Type = Constants.VOCABULARY_ValidType, - ScopeTypeId = Constants.VOCABULARY_ValidScopeTypeId, - ScopeId = Constants.VOCABULARY_ValidScopeId, - Weight = Constants.VOCABULARY_ValidWeight - }; + Vocabulary vocabulary = new Vocabulary + { + Name = Constants.VOCABULARY_ValidName, + Type = Constants.VOCABULARY_ValidType, + ScopeTypeId = Constants.VOCABULARY_ValidScopeTypeId, + ScopeId = Constants.VOCABULARY_ValidScopeId, + Weight = Constants.VOCABULARY_ValidWeight, + }; return vocabulary; } @@ -87,39 +87,39 @@ public static FileInfo CreateValidFile(int fileId) StorageLocation = 0, UniqueId = Guid.NewGuid(), VersionGuid = Guid.NewGuid(), - Width = 0 + Width = 0, }; } } public static string GetContent(int i) { - return String.Format(String.Format(Constants.CONTENT_ValidContentFormat, i)); + return string.Format(string.Format(Constants.CONTENT_ValidContentFormat, i)); } public static string GetContentKey(int i) { - return String.Format(String.Format(Constants.CONTENT_ValidContentKeyFormat, i)); + return string.Format(string.Format(Constants.CONTENT_ValidContentKeyFormat, i)); } public static string GetContentType(int i) { - return String.Format(Constants.CONTENTTYPE_ValidContentTypeFormat, i); + return string.Format(Constants.CONTENTTYPE_ValidContentTypeFormat, i); } public static string GetScopeType(int i) { - return String.Format(Constants.SCOPETYPE_ValidScopeTypeFormat, i); + return string.Format(Constants.SCOPETYPE_ValidScopeTypeFormat, i); } public static string GetTermName(int i) { - return String.Format(Constants.TERM_ValidNameFormat, i); + return string.Format(Constants.TERM_ValidNameFormat, i); } public static string GetVocabularyName(int i) { - return String.Format(Constants.VOCABULARY_ValidNameFormat, i); + return string.Format(Constants.VOCABULARY_ValidNameFormat, i); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnUnitTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnUnitTest.cs index 91f8dd96139..8dd0bb6eb1e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnUnitTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnUnitTest.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Configuration; -using System.IO; -using System.Reflection; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System.Configuration; + using System.IO; + using System.Reflection; + using System.Web; + public class DnnUnitTest { public DnnUnitTest() @@ -16,10 +16,10 @@ public DnnUnitTest() var uri = new System.Uri(Assembly.GetExecutingAssembly().CodeBase); string path = HttpUtility.UrlDecode(Path.GetFullPath(uri.AbsolutePath)); - WebsiteAppPath = "http://localhost/DNN_Platform"; + this.WebsiteAppPath = "http://localhost/DNN_Platform"; var websiteRootPath = path.Substring(0, path.IndexOf("DNN Platform", System.StringComparison.Ordinal)); - WebsitePhysicalAppPath = Path.Combine(websiteRootPath, "Website"); - HighlightDataPath = Path.Combine(websiteRootPath, "DNN Platform//Modules//PreviewProfileManagement//Resources//highlightDevices.xml"); + this.WebsitePhysicalAppPath = Path.Combine(websiteRootPath, "Website"); + this.HighlightDataPath = Path.Combine(websiteRootPath, "DNN Platform//Modules//PreviewProfileManagement//Resources//highlightDevices.xml"); } public string HighlightDataPath { get; set; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs index efcd094144c..5e2eb43bef3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs @@ -1,50 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Configuration; -using System.Net; -using System.Reflection; -using System.Web; -using System.Web.Security; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.ComponentModel; -using DotNetNuke.Modules.HTMLEditorProvider; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Profile; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.ClientCapability; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.ModuleCache; -using DotNetNuke.Services.OutputCache; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Search; -using DotNetNuke.Services.Sitemap; -using DotNetNuke.Services.Url.FriendlyUrl; - -using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; -using RoleProvider = DotNetNuke.Security.Roles.RoleProvider; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System; + using System.Configuration; + using System.Net; + using System.Reflection; + using System.Web; + using System.Web.Security; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Modules.HTMLEditorProvider; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Profile; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.ClientCapability; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.ModuleCache; + using DotNetNuke.Services.OutputCache; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Search; + using DotNetNuke.Services.Sitemap; + using DotNetNuke.Services.Url.FriendlyUrl; + + using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; + using RoleProvider = DotNetNuke.Security.Roles.RoleProvider; + public class DnnWebTest : DnnUnitTest { - public int PortalId { get; private set; } - private static bool alreadyLoaded = false; public DnnWebTest(int portalId) { - var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", WebsitePhysicalAppPath); - simulator.SimulateRequest(new Uri(WebsiteAppPath)); + var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", this.WebsitePhysicalAppPath); + simulator.SimulateRequest(new Uri(this.WebsiteAppPath)); InstallComponents(); @@ -53,19 +51,19 @@ public DnnWebTest(int portalId) LoadDnnProviders("data;logging;caching;authentication;members;roles;profiles;permissions;folder;clientcapability"); - //fix Globals.ApplicationMapPath - var appPath = WebsitePhysicalAppPath; + // fix Globals.ApplicationMapPath + var appPath = this.WebsitePhysicalAppPath; if (!string.IsNullOrEmpty(appPath)) { var mappath = typeof(Globals).GetField("_applicationMapPath", BindingFlags.Static | BindingFlags.NonPublic); mappath.SetValue(null, appPath); } - //fix Globals.Status + // fix Globals.Status var status = typeof(Globals).GetField("_status", BindingFlags.Static | BindingFlags.NonPublic); status.SetValue(null, Globals.UpgradeStatus.None); - //fix membership + // fix membership var providerProp = typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic); providerProp.SetValue(null, Membership.Providers["AspNetSqlMembershipProvider"]); @@ -73,12 +71,14 @@ public DnnWebTest(int portalId) var ps = new Entities.Portals.PortalSettings(59, objPortalAliasInfo); HttpContext.Current.Items.Add("PortalSettings", ps); - PortalId = portalId; + this.PortalId = portalId; } + + public int PortalId { get; private set; } private static void InstallComponents() { - Globals.ServerName = String.IsNullOrEmpty(Config.GetSetting("ServerName")) + Globals.ServerName = string.IsNullOrEmpty(Config.GetSetting("ServerName")) ? Dns.GetHostName() : Config.GetSetting("ServerName"); @@ -109,12 +109,12 @@ private static void InstallComponents() ComponentFactory.InstallComponents(new ProviderInstaller("htmlEditor", typeof(HtmlEditorProvider), ComponentLifeStyleType.Transient)); ComponentFactory.InstallComponents(new ProviderInstaller("navigationControl", typeof(NavigationProvider), ComponentLifeStyleType.Transient)); ComponentFactory.InstallComponents(new ProviderInstaller("clientcapability", typeof(ClientCapabilityProvider))); - } - private static void RegisterIfNotAlreadyRegistered() where TConcrete : class, new() + private static void RegisterIfNotAlreadyRegistered() + where TConcrete : class, new() { - RegisterIfNotAlreadyRegistered(""); + RegisterIfNotAlreadyRegistered(string.Empty); } private static void RegisterIfNotAlreadyRegistered(string name) @@ -124,7 +124,7 @@ private static void RegisterIfNotAlreadyRegistered(string var provider = ComponentFactory.GetComponent(); if (provider == null) { - if (String.IsNullOrEmpty(name)) + if (string.IsNullOrEmpty(name)) { ComponentFactory.RegisterComponentInstance(new TConcrete()); } @@ -137,7 +137,7 @@ private static void RegisterIfNotAlreadyRegistered(string /// /// This proc loads up specified DNN providers, because the BuildManager doesn't get the context right - /// The providers are cahced so that the DNN base buildManager calls don't have to load up hte providers + /// The providers are cahced so that the DNN base buildManager calls don't have to load up hte providers. /// private static void LoadDnnProviders(string providerList) { @@ -145,6 +145,7 @@ private static void LoadDnnProviders(string providerList) { return; } + alreadyLoaded = true; if (providerList != null) { @@ -162,7 +163,7 @@ private static void LoadDnnProviders(string providerList) var type = providerValue.Type; var assembly = providerValue.Name; - if (type.Contains(", ")) //get the straight typename, no assembly, for the cache key + if (type.Contains(", ")) // get the straight typename, no assembly, for the cache key { assembly = type.Substring(type.IndexOf(", ") + 1); type = type.Substring(0, type.IndexOf(", ")); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj index 1458b6cbf6b..0f38dc99d65 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj @@ -1,139 +1,146 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {68368906-57DD-40D1-AC10-35211A17D617} - Library - Properties - DotNetNuke.Tests.Utilities - DotNetNuke.Tests.Utilities - v4.7.2 - 512 - - - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - ..\..\..\..\Evoq.Content\ - true - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - AllRules.ruleset - 1591 - 7 - - - - ..\..\..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll - - - False - ..\..\..\..\..\Windows\System32\inetsrv\Microsoft.Web.Administration.dll - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - - ..\..\..\packages\System.Management.Automation.6.1.7601.17515\lib\net45\System.Management.Automation.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {68368906-57DD-40D1-AC10-35211A17D617} + Library + Properties + DotNetNuke.Tests.Utilities + DotNetNuke.Tests.Utilities + v4.7.2 + 512 + + + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + ..\..\..\..\Evoq.Content\ + true + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + AllRules.ruleset + 1591 + 7 + + + + ..\..\..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll + + + False + ..\..\..\..\..\Windows\System32\inetsrv\Microsoft.Web.Administration.dll + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + + ..\..\..\packages\System.Management.Automation.6.1.7601.17515\lib\net45\System.Management.Automation.dll + True + + + + + + + + + + + + + + + + + + + + + + + + + Code + + + + + + + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + + + stylecop.json + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/EnumerableAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/EnumerableAssert.cs index b15044be4b2..6cdcb69f8ea 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/EnumerableAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/EnumerableAssert.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System; + using System.Collections.Generic; + + using NUnit.Framework; + public static class EnumerableAssert { public static void ElementsAreEqual(IEnumerable expected, IEnumerable actual) @@ -28,7 +28,7 @@ public static void ElementsAreEqual(IEnumerable expected, IEnumerable a public static void ElementsMatch(IEnumerable expected, IEnumerable actual, Func matcher) { - ElementsMatch(expected, actual, matcher, String.Empty, new string[0]); + ElementsMatch(expected, actual, matcher, string.Empty, new string[0]); } public static void ElementsMatch(IEnumerable expected, IEnumerable actual, Func matcher, string message) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs index c6d4875b891..9917c138cdb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs @@ -1,33 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Reflection; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System; + using System.Reflection; + + using NUnit.Framework; + [Obsolete("Use Assert.Exception or ExpectedExceptionAttribute. Scheduled removal in v11.0.0.")] public static class ExceptionAssert { - //public static void Throws(Action act) where TException : Exception - //{ + // public static void Throws(Action act) where TException : Exception + // { // Throws(act, ex => true); - //} + // } - //public static void Throws(string message, Action act) where TException : Exception - //{ + // public static void Throws(string message, Action act) where TException : Exception + // { // Throws(act, ex => ex.Message.Equals(message, StringComparison.Ordinal)); - //} - - public static void Throws(string message, Action act, Predicate checker) where TException : Exception + // } + public static void Throws(string message, Action act, Predicate checker) + where TException : Exception { Throws(act, ex => ex.Message.Equals(message, StringComparison.Ordinal) && checker(ex)); } - public static void Throws(Action act, Predicate checker) where TException : Exception + public static void Throws(Action act, Predicate checker) + where TException : Exception { bool matched = false; bool thrown = false; @@ -40,7 +41,7 @@ public static void Throws(Action act, Predicate checker) TException tex = ex as TException; if (tex == null) { - if (typeof (TException) == typeof (TargetInvocationException)) + if (typeof(TException) == typeof(TargetInvocationException)) { // The only place we do special processing is TargetInvocationException, but if that's // what the user expected, we don't do anything @@ -52,12 +53,14 @@ public static void Throws(Action act, Predicate checker) { throw; } + tex = tiex.InnerException as TException; if (tex == null) { throw; } } + thrown = true; matched = checker(tex); if (!matched) @@ -68,24 +71,25 @@ public static void Throws(Action act, Predicate checker) if (!thrown) { - throw new AssertionException(String.Format("Expected exception of type '{0}' was not thrown", typeof (TException).FullName)); + throw new AssertionException(string.Format("Expected exception of type '{0}' was not thrown", typeof(TException).FullName)); } else if (!matched) { - throw new AssertionException(String.Format("Expected exception of type '{0}' was thrown but did not match the configured criteria", typeof (TException).FullName)); + throw new AssertionException(string.Format("Expected exception of type '{0}' was thrown but did not match the configured criteria", typeof(TException).FullName)); } } public static void ThrowsArgNull(string paramName, Action act) { - Throws(act, ex => String.Equals(ex.ParamName, paramName, StringComparison.Ordinal)); + Throws(act, ex => string.Equals(ex.ParamName, paramName, StringComparison.Ordinal)); } public static void ThrowsArgNullOrEmpty(string paramName, Action act) { - Throws(String.Format("Argument cannot be null or an empty string{1}Parameter name: {0}", paramName, Environment.NewLine), - act, - ex => String.Equals(ex.ParamName, paramName, StringComparison.Ordinal)); + Throws( + string.Format("Argument cannot be null or an empty string{1}Parameter name: {0}", paramName, Environment.NewLine), + act, + ex => string.Equals(ex.ParamName, paramName, StringComparison.Ordinal)); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Fakes/FakeCachingProvider.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Fakes/FakeCachingProvider.cs index c548427a81a..2c3847e9b7d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Fakes/FakeCachingProvider.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Fakes/FakeCachingProvider.cs @@ -1,34 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web.Caching; -using DotNetNuke.Services.Cache; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities.Fakes { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Web.Caching; + + using DotNetNuke.Services.Cache; + public class FakeCachingProvider : CachingProvider { private Dictionary _dictionary; public FakeCachingProvider(Dictionary dictionary) { - _dictionary = dictionary; + this._dictionary = dictionary; } public override void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) { - _dictionary[cacheKey] = itemToCache; + this._dictionary[cacheKey] = itemToCache; } public override object GetItem(string cacheKey) { - return _dictionary.ContainsKey(cacheKey) ? _dictionary[cacheKey] : null; + return this._dictionary.ContainsKey(cacheKey) ? this._dictionary[cacheKey] : null; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/FileAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/FileAssert.cs index c697c0d56f6..44141d2adc5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/FileAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/FileAssert.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System; + using System.IO; + + using NUnit.Framework; + public static class FileAssert { public static void TextFilesAreEqual(string expectedFile, string actualFile) { - TextFilesAreEqual(expectedFile, actualFile, String.Empty); + TextFilesAreEqual(expectedFile, actualFile, string.Empty); } public static void TextFilesAreEqual(string expectedFile, string actualFile, string message) @@ -25,7 +25,7 @@ public static void TextFilesAreEqual(string expectedFile, string actualFile, str public static void BinaryFilesAreEqual(string expectedFile, string actualFile) { - BinaryFilesAreEqual(expectedFile, actualFile, String.Empty); + BinaryFilesAreEqual(expectedFile, actualFile, string.Empty); } public static void BinaryFilesAreEqual(string expectedFile, string actualFile, string message) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs index e3b003e45fd..3f99fec9bc0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs @@ -1,18 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections; -using System.Collections.Specialized; -using System.Web; -using DotNetNuke.Common; -using Moq; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System.Collections; + using System.Collections.Specialized; + using System.IO; + using System.Web; + + using DotNetNuke.Common; + using Moq; + public class HttpContextHelper { + /// + /// Return Response object with default values for missing ones + /// _mockRequest = Mock.Get(_mockhttpContext.Object.Request); + /// syntax _mockRequest.SetupGet(x => x.[PropertyName]).Returns(...); + /// e.g. SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()). + /// + /// HttpResponseBase. + public static Mock RegisterMockHttpContext() + { + var mock = CrateMockHttpContext(); + HttpContextSource.RegisterInstance(mock.Object); + return mock; + } + private static Mock CrateMockHttpContext() { var context = new Mock(); @@ -48,30 +63,16 @@ private static HttpResponseBase GetMockResponseBase() private static HttpRequestBase GetMockRequestBase() { var request = new Mock(); - request.SetupAllProperties(); + request.SetupAllProperties(); request.SetupGet(x => x.Headers).Returns(new NameValueCollection()); request.SetupGet(x => x.InputStream).Returns(new MemoryStream()); request.SetupGet(x => x.Params).Returns(new NameValueCollection()); - request.SetupGet(x => x.QueryString).Returns(new NameValueCollection()); + request.SetupGet(x => x.QueryString).Returns(new NameValueCollection()); request.SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()); - request.SetupGet(x => x.UserAgent).Returns(string.Empty); + request.SetupGet(x => x.UserAgent).Returns(string.Empty); request.SetupGet(x => x.UserHostAddress).Returns(string.Empty); request.SetupGet(x => x.UserLanguages).Returns(new[] { string.Empty }); return request.Object; } - - /// - /// Return Response object with default values for missing ones - /// _mockRequest = Mock.Get(_mockhttpContext.Object.Request); - /// syntax _mockRequest.SetupGet(x => x.[PropertyName]).Returns(...); - /// e.g. SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()); - /// - /// HttpResponseBase - public static Mock RegisterMockHttpContext() - { - var mock = CrateMockHttpContext(); - HttpContextSource.RegisterInstance(mock.Object); - return mock; - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs index 0a748c64e95..df689d674aa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using System.Configuration; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.Configuration; -using System.Web.Hosting; -using System.Web.SessionState; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Instance.Utilities.HttpSimulator { + using System; + using System.Collections.Specialized; + using System.Configuration; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.Configuration; + using System.Web.Hosting; + using System.Web.SessionState; + public enum HttpVerb { GET, @@ -24,73 +24,90 @@ public enum HttpVerb DELETE, } - /// - /// Useful class for simulating the HttpContext. This does not actually - /// make an HttpRequest, it merely simulates the state that your code - /// would be in "as if" handling a request. Thus the HttpContext.Current + /// + /// Useful class for simulating the HttpContext. This does not actually + /// make an HttpRequest, it merely simulates the state that your code + /// would be in "as if" handling a request. Thus the HttpContext.Current /// property is populated. /// public class HttpSimulator : IDisposable { - private static readonly string WebsitePhysicalAppPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"]; + private static readonly string WebsitePhysicalAppPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"]; private StringBuilder _builder; private Uri _referer; private readonly NameValueCollection _formVars = new NameValueCollection(); private readonly NameValueCollection _headers = new NameValueCollection(); - public HttpSimulator() : this("/", WebsitePhysicalAppPath) + private string _applicationPath = "/"; + + private string _physicalApplicationPath = WebsitePhysicalAppPath; + + private string _physicalPath = WebsitePhysicalAppPath; + + public HttpSimulator() + : this("/", WebsitePhysicalAppPath) { } - public HttpSimulator(string applicationPath) : this(applicationPath, WebsitePhysicalAppPath) + public HttpSimulator(string applicationPath) + : this(applicationPath, WebsitePhysicalAppPath) { - } public HttpSimulator(string applicationPath, string physicalApplicationPath) { - ApplicationPath = applicationPath; - PhysicalApplicationPath = physicalApplicationPath; + this.ApplicationPath = applicationPath; + this.PhysicalApplicationPath = physicalApplicationPath; } + public string Host { get; private set; } + + public string LocalPath { get; private set; } + + public int Port { get; private set; } + /// /// Sets up the HttpContext objects to simulate a GET request. /// /// - /// Simulates a request to http://localhost/ - /// + /// Simulates a request to http://localhost/. + /// + /// public HttpSimulator SimulateRequest() { - return SimulateRequest(new Uri("http://localhost/")); + return this.SimulateRequest(new Uri("http://localhost/")); } /// /// Sets up the HttpContext objects to simulate a GET request. /// - /// + /// + /// public HttpSimulator SimulateRequest(Uri url) { - return SimulateRequest(url, HttpVerb.GET); + return this.SimulateRequest(url, HttpVerb.GET); } /// /// Sets up the HttpContext objects to simulate a request. /// /// - /// + /// + /// public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb) { - return SimulateRequest(url, httpVerb, null, null); + return this.SimulateRequest(url, httpVerb, null, null); } /// /// Sets up the HttpContext objects to simulate a POST request. /// /// - /// + /// + /// public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables) { - return SimulateRequest(url, HttpVerb.POST, formVariables, null); + return this.SimulateRequest(url, HttpVerb.POST, formVariables, null); } /// @@ -98,10 +115,11 @@ public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables) /// /// /// - /// + /// + /// public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables, NameValueCollection headers) { - return SimulateRequest(url, HttpVerb.POST, formVariables, headers); + return this.SimulateRequest(url, HttpVerb.POST, formVariables, headers); } /// @@ -109,374 +127,26 @@ public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables, /// /// /// - /// + /// + /// public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection headers) { - return SimulateRequest(url, httpVerb, null, headers); + return this.SimulateRequest(url, httpVerb, null, headers); } /// - /// Sets up the HttpContext objects to simulate a request. - /// - /// - /// - /// - /// - protected virtual HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection formVariables, NameValueCollection headers) - { - HttpContext.Current = null; - - ParseRequestUrl(url); - - if (ResponseWriter == null) - { - _builder = new StringBuilder(); - ResponseWriter = new StringWriter(_builder); - } - - SetHttpRuntimeInternals(); - - var query = ExtractQueryStringPart(url); - - if (formVariables != null) - _formVars.Add(formVariables); - - if (_formVars.Count > 0) - httpVerb = HttpVerb.POST; //Need to enforce this. - - if (headers != null) - _headers.Add(headers); - - WorkerRequest = new SimulatedHttpRequest(ApplicationPath, PhysicalApplicationPath, PhysicalPath, Page, query, ResponseWriter, Host, Port, httpVerb.ToString()); - - WorkerRequest.Form.Add(_formVars); - WorkerRequest.Headers.Add(_headers); - - if (_referer != null) - WorkerRequest.SetReferer(_referer); - - InitializeSession(); - - InitializeApplication(); - - #region Console Debug INfo - - //Console.WriteLine("host: " + Host); - //Console.WriteLine("virtualDir: " + _applicationPath); - //Console.WriteLine("page: " + LocalPath); - //Console.WriteLine("pathPartAfterApplicationPart: " + Page); - //Console.WriteLine("appPhysicalDir: " + _physicalApplicationPath); - //if (HttpContext.Current != null) - //{ - // Console.WriteLine("Request.Url.LocalPath: " + HttpContext.Current.Request.Url.LocalPath); - // Console.WriteLine("Request.Url.Host: " + HttpContext.Current.Request.Url.Host); - // Console.WriteLine("Request.FilePath: " + HttpContext.Current.Request.FilePath); - // Console.WriteLine("Request.Path: " + HttpContext.Current.Request.Path); - // Console.WriteLine("Request.RawUrl: " + HttpContext.Current.Request.RawUrl); - // Console.WriteLine("Request.Url: " + HttpContext.Current.Request.Url); - // Console.WriteLine("Request.Url.Port: " + HttpContext.Current.Request.Url.Port); - // Console.WriteLine("Request.ApplicationPath: " + HttpContext.Current.Request.ApplicationPath); - // Console.WriteLine("Request.PhysicalPath: " + HttpContext.Current.Request.PhysicalPath); - //} - //Console.WriteLine("HttpRuntime.AppDomainAppPath: " + HttpRuntime.AppDomainAppPath); - //Console.WriteLine("HttpRuntime.AppDomainAppVirtualPath: " + HttpRuntime.AppDomainAppVirtualPath); - //Console.WriteLine("HostingEnvironment.ApplicationPhysicalPath: " + HostingEnvironment.ApplicationPhysicalPath); - //Console.WriteLine("HostingEnvironment.ApplicationVirtualPath: " + HostingEnvironment.ApplicationVirtualPath); - - #endregion - - return this; - } - - private static void InitializeApplication() - { - var appFactoryType = Type.GetType("System.Web.HttpApplicationFactory, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); - var appFactory = ReflectionHelper.GetStaticFieldValue("_theApplicationFactory", appFactoryType); - ReflectionHelper.SetPrivateInstanceFieldValue("_state", appFactory, HttpContext.Current.Application); - } - - private void InitializeSession() - { - HttpContext.Current = new HttpContext(WorkerRequest); - HttpContext.Current.Items.Clear(); - var session = (HttpSessionState)ReflectionHelper.Instantiate(typeof(HttpSessionState), new[] { typeof(IHttpSessionState) }, new FakeHttpSessionState()); - - HttpContext.Current.Items.Add("AspSession", session); - } - - public class FakeHttpSessionState : NameObjectCollectionBase, IHttpSessionState - { - private readonly string _sessionId = Guid.NewGuid().ToString(); - private int _timeout = 30; //minutes - private const bool _isNewSession = true; - private readonly HttpStaticObjectsCollection _staticObjects = new HttpStaticObjectsCollection(); - private readonly object _syncRoot = new Object(); - - /// - ///Ends the current session. - /// - /// - public void Abandon() - { - BaseClear(); - } - - /// - ///Adds a new item to the session-state collection. - /// - /// - ///The name of the item to add to the session-state collection. - ///The value of the item to add to the session-state collection. - public void Add(string name, object value) - { - BaseAdd(name, value); - } - - /// - ///Deletes an item from the session-state item collection. - /// - /// - ///The name of the item to delete from the session-state item collection. - public void Remove(string name) - { - BaseRemove(name); - } - - /// - ///Deletes an item at a specified index from the session-state item collection. - /// - /// - ///The index of the item to remove from the session-state collection. - public void RemoveAt(int index) - { - BaseRemoveAt(index); - } - - /// - ///Clears all values from the session-state item collection. - /// - /// - public void Clear() - { - BaseClear(); - } - - /// - ///Clears all values from the session-state item collection. - /// - /// - public void RemoveAll() - { - BaseClear(); - } - - /// - ///Copies the collection of session-state item values to a one-dimensional array, starting at the specified index in the array. - /// - /// - ///The that receives the session values. - ///The index in array where copying starts. - public void CopyTo(Array array, int index) - { - throw new NotImplementedException(); - } - - /// - ///Gets the unique session identifier for the session. - /// - /// - /// - ///The session ID. - /// - /// - public string SessionID - { - get { return _sessionId; } - } - - /// - ///Gets and sets the time-out period (in minutes) allowed between requests before the session-state provider terminates the session. - /// - /// - /// - ///The time-out period, in minutes. - /// - /// - public int Timeout - { - get { return _timeout; } - set { _timeout = value; } - } - - /// - ///Gets a value indicating whether the session was created with the current request. - /// - /// - /// - ///true if the session was created with the current request; otherwise, false. - /// - /// - public bool IsNewSession - { - get { return _isNewSession; } - } - - /// - ///Gets the current session-state mode. - /// - /// - /// - ///One of the values. - /// - /// - public SessionStateMode Mode - { - get { return SessionStateMode.InProc; } - } - - /// - ///Gets a value indicating whether the session ID is embedded in the URL or stored in an HTTP cookie. - /// - /// - /// - ///true if the session is embedded in the URL; otherwise, false. - /// - /// - public bool IsCookieless - { - get { return false; } - } - - /// - ///Gets a value that indicates whether the application is configured for cookieless sessions. - /// - /// - /// - ///One of the values that indicate whether the application is configured for cookieless sessions. The default is . - /// - /// - public HttpCookieMode CookieMode - { - get { return HttpCookieMode.UseCookies; } - } - - /// - ///Gets or sets the locale identifier (LCID) of the current session. - /// - /// - /// - ///A instance that specifies the culture of the current session. - /// - /// - public int LCID { get; set; } - - /// - ///Gets or sets the code-page identifier for the current session. - /// - /// - /// - ///The code-page identifier for the current session. - /// - /// - public int CodePage { get; set; } - - /// - ///Gets a collection of objects declared by <object Runat="Server" Scope="Session"/> tags within the ASP.NET application file Global.asax. - /// - /// - /// - ///An containing objects declared in the Global.asax file. - /// - /// - public HttpStaticObjectsCollection StaticObjects - { - get { return _staticObjects; } - } - - /// - ///Gets or sets a session-state item value by name. - /// - /// - /// - ///The session-state item value specified in the name parameter. - /// - /// - ///The key name of the session-state item value. - public object this[string name] - { - get { return BaseGet(name); } - set { BaseSet(name, value); } - } - - /// - ///Gets or sets a session-state item value by numerical index. - /// - /// - /// - ///The session-state item value specified in the index parameter. - /// - /// - ///The numerical index of the session-state item value. - public object this[int index] - { - get { return BaseGet(index); } - set { BaseSet(index, value); } - } - - /// - ///Gets an object that can be used to synchronize access to the collection of session-state values. - /// - /// - /// - ///An object that can be used to synchronize access to the collection. - /// - /// - public object SyncRoot - { - get { return _syncRoot; } - } - - - - /// - ///Gets a value indicating whether access to the collection of session-state values is synchronized (thread safe). - /// - /// - ///true if access to the collection is synchronized (thread safe); otherwise, false. - /// - /// - public bool IsSynchronized - { - get { return true; } - } - - /// - ///Gets a value indicating whether the session is read-only. - /// - /// - /// - ///true if the session is read-only; otherwise, false. - /// - /// - bool IHttpSessionState.IsReadOnly - { - get - { - return true; - } - } - } - - /// /// Sets the referer for the request. Uses a fluent interface. /// /// /// public HttpSimulator SetReferer(Uri referer) { - if(WorkerRequest != null) - WorkerRequest.SetReferer(referer); - _referer = referer; + if (this.WorkerRequest != null) + { + this.WorkerRequest.SetReferer(referer); + } + + this._referer = referer; return this; } @@ -488,10 +158,12 @@ public HttpSimulator SetReferer(Uri referer) /// public HttpSimulator SetFormVariable(string name, string value) { - if (WorkerRequest != null) - throw new InvalidOperationException("Cannot set form variables after calling Simulate()."); - - _formVars.Add(name, value); + if (this.WorkerRequest != null) + { + throw new InvalidOperationException("Cannot set form variables after calling Simulate()."); + } + + this._formVars.Add(name, value); return this; } @@ -504,141 +176,477 @@ public HttpSimulator SetFormVariable(string name, string value) /// public HttpSimulator SetHeader(string name, string value) { - if (WorkerRequest != null) - throw new InvalidOperationException("Cannot set headers after calling Simulate()."); + if (this.WorkerRequest != null) + { + throw new InvalidOperationException("Cannot set headers after calling Simulate()."); + } + + this._headers.Add(name, value); - _headers.Add(name, value); + return this; + } + /// + /// Sets up the HttpContext objects to simulate a request. + /// + /// + /// + /// + /// + /// + protected virtual HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection formVariables, NameValueCollection headers) + { + HttpContext.Current = null; + + this.ParseRequestUrl(url); + + if (this.ResponseWriter == null) + { + this._builder = new StringBuilder(); + this.ResponseWriter = new StringWriter(this._builder); + } + + this.SetHttpRuntimeInternals(); + + var query = ExtractQueryStringPart(url); + + if (formVariables != null) + { + this._formVars.Add(formVariables); + } + + if (this._formVars.Count > 0) + { + httpVerb = HttpVerb.POST; // Need to enforce this. + } + + if (headers != null) + { + this._headers.Add(headers); + } + + this.WorkerRequest = new SimulatedHttpRequest(this.ApplicationPath, this.PhysicalApplicationPath, this.PhysicalPath, this.Page, query, this.ResponseWriter, this.Host, this.Port, httpVerb.ToString()); + + this.WorkerRequest.Form.Add(this._formVars); + this.WorkerRequest.Headers.Add(this._headers); + + if (this._referer != null) + { + this.WorkerRequest.SetReferer(this._referer); + } + + this.InitializeSession(); + + InitializeApplication(); + + // Console.WriteLine("host: " + Host); + // Console.WriteLine("virtualDir: " + _applicationPath); + // Console.WriteLine("page: " + LocalPath); + // Console.WriteLine("pathPartAfterApplicationPart: " + Page); + // Console.WriteLine("appPhysicalDir: " + _physicalApplicationPath); + // if (HttpContext.Current != null) + // { + // Console.WriteLine("Request.Url.LocalPath: " + HttpContext.Current.Request.Url.LocalPath); + // Console.WriteLine("Request.Url.Host: " + HttpContext.Current.Request.Url.Host); + // Console.WriteLine("Request.FilePath: " + HttpContext.Current.Request.FilePath); + // Console.WriteLine("Request.Path: " + HttpContext.Current.Request.Path); + // Console.WriteLine("Request.RawUrl: " + HttpContext.Current.Request.RawUrl); + // Console.WriteLine("Request.Url: " + HttpContext.Current.Request.Url); + // Console.WriteLine("Request.Url.Port: " + HttpContext.Current.Request.Url.Port); + // Console.WriteLine("Request.ApplicationPath: " + HttpContext.Current.Request.ApplicationPath); + // Console.WriteLine("Request.PhysicalPath: " + HttpContext.Current.Request.PhysicalPath); + // } + // Console.WriteLine("HttpRuntime.AppDomainAppPath: " + HttpRuntime.AppDomainAppPath); + // Console.WriteLine("HttpRuntime.AppDomainAppVirtualPath: " + HttpRuntime.AppDomainAppVirtualPath); + // Console.WriteLine("HostingEnvironment.ApplicationPhysicalPath: " + HostingEnvironment.ApplicationPhysicalPath); + // Console.WriteLine("HostingEnvironment.ApplicationVirtualPath: " + HostingEnvironment.ApplicationVirtualPath); return this; } - private void ParseRequestUrl(Uri url) + private static void InitializeApplication() + { + var appFactoryType = Type.GetType("System.Web.HttpApplicationFactory, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); + var appFactory = ReflectionHelper.GetStaticFieldValue("_theApplicationFactory", appFactoryType); + ReflectionHelper.SetPrivateInstanceFieldValue("_state", appFactory, HttpContext.Current.Application); + } + + private void InitializeSession() + { + HttpContext.Current = new HttpContext(this.WorkerRequest); + HttpContext.Current.Items.Clear(); + var session = (HttpSessionState)ReflectionHelper.Instantiate(typeof(HttpSessionState), new[] { typeof(IHttpSessionState) }, new FakeHttpSessionState()); + + HttpContext.Current.Items.Add("AspSession", session); + } + + public class FakeHttpSessionState : NameObjectCollectionBase, IHttpSessionState { - if (url == null) - return; - Host = url.Host; - Port = url.Port; - LocalPath = url.LocalPath; - Page = StripPrecedingSlashes(RightAfter(url.LocalPath, ApplicationPath)); - _physicalPath = Path.Combine(_physicalApplicationPath, Page.Replace("/", @"\")); + private const bool _isNewSession = true; + private readonly string _sessionId = Guid.NewGuid().ToString(); + private int _timeout = 30; // minutes + private readonly HttpStaticObjectsCollection _staticObjects = new HttpStaticObjectsCollection(); + private readonly object _syncRoot = new object(); + + /// + /// Gets the unique session identifier for the session. + /// + /// + /// + /// The session ID. + /// + /// + public string SessionID + { + get { return this._sessionId; } + } + + /// + /// Gets or sets and sets the time-out period (in minutes) allowed between requests before the session-state provider terminates the session. + /// + /// + /// + /// The time-out period, in minutes. + /// + /// + public int Timeout + { + get { return this._timeout; } + set { this._timeout = value; } + } + + /// + /// Gets a value indicating whether the session was created with the current request. + /// + /// + /// + /// true if the session was created with the current request; otherwise, false. + /// + /// + public bool IsNewSession + { + get { return _isNewSession; } + } + + /// + /// Ends the current session. + /// + /// + public void Abandon() + { + this.BaseClear(); + } + + /// + /// Adds a new item to the session-state collection. + /// + /// + /// The name of the item to add to the session-state collection. + /// The value of the item to add to the session-state collection. + public void Add(string name, object value) + { + this.BaseAdd(name, value); + } + + /// + /// Deletes an item from the session-state item collection. + /// + /// + /// The name of the item to delete from the session-state item collection. + public void Remove(string name) + { + this.BaseRemove(name); + } + + /// + /// Deletes an item at a specified index from the session-state item collection. + /// + /// + /// The index of the item to remove from the session-state collection. + public void RemoveAt(int index) + { + this.BaseRemoveAt(index); + } + + /// + /// Clears all values from the session-state item collection. + /// + /// + public void Clear() + { + this.BaseClear(); + } + + /// + /// Clears all values from the session-state item collection. + /// + /// + public void RemoveAll() + { + this.BaseClear(); + } + + /// + /// Copies the collection of session-state item values to a one-dimensional array, starting at the specified index in the array. + /// + /// + /// The that receives the session values. + /// The index in array where copying starts. + public void CopyTo(Array array, int index) + { + throw new NotImplementedException(); + } + + /// + /// Gets the current session-state mode. + /// + /// + /// + /// One of the values. + /// + /// + public SessionStateMode Mode + { + get { return SessionStateMode.InProc; } + } + + /// + /// Gets a value indicating whether the session ID is embedded in the URL or stored in an HTTP cookie. + /// + /// + /// + /// true if the session is embedded in the URL; otherwise, false. + /// + /// + public bool IsCookieless + { + get { return false; } + } + + /// + /// Gets a value that indicates whether the application is configured for cookieless sessions. + /// + /// + /// + /// One of the values that indicate whether the application is configured for cookieless sessions. The default is . + /// + /// + public HttpCookieMode CookieMode + { + get { return HttpCookieMode.UseCookies; } + } + + /// + /// Gets or sets the locale identifier (LCID) of the current session. + /// + /// + /// + /// A instance that specifies the culture of the current session. + /// + /// + public int LCID { get; set; } + + /// + /// Gets or sets the code-page identifier for the current session. + /// + /// + /// + /// The code-page identifier for the current session. + /// + /// + public int CodePage { get; set; } + + /// + /// Gets a collection of objects declared by <object Runat="Server" Scope="Session"/> tags within the ASP.NET application file Global.asax. + /// + /// + /// + /// An containing objects declared in the Global.asax file. + /// + /// + public HttpStaticObjectsCollection StaticObjects + { + get { return this._staticObjects; } + } + + /// + /// Gets an object that can be used to synchronize access to the collection of session-state values. + /// + /// + /// + /// An object that can be used to synchronize access to the collection. + /// + /// + public object SyncRoot + { + get { return this._syncRoot; } + } + + /// + /// Gets a value indicating whether access to the collection of session-state values is synchronized (thread safe). + /// + /// + /// true if access to the collection is synchronized (thread safe); otherwise, false. + /// + /// + public bool IsSynchronized + { + get { return true; } + } + + /// + /// Gets a value indicating whether the session is read-only. + /// + /// + /// + /// true if the session is read-only; otherwise, false. + /// + /// + bool IHttpSessionState.IsReadOnly + { + get + { + return true; + } + } + + /// + /// Gets or sets a session-state item value by name. + /// + /// + /// + /// The session-state item value specified in the name parameter. + /// + /// + /// The key name of the session-state item value. + public object this[string name] + { + get { return this.BaseGet(name); } + set { this.BaseSet(name, value); } + } + + /// + /// Gets or sets a session-state item value by numerical index. + /// + /// + /// + /// The session-state item value specified in the index parameter. + /// + /// + /// The numerical index of the session-state item value. + public object this[int index] + { + get { return this.BaseGet(index); } + set { this.BaseSet(index, value); } + } } - static string RightAfter(string original, string search) - { - if (search.Length > original.Length || search.Length == 0) - return original; + private static string RightAfter(string original, string search) + { + if (search.Length > original.Length || search.Length == 0) + { + return original; + } + original = original.Trim(); search = search.Trim(); - var searchIndex = original.IndexOf(search, 0, StringComparison.InvariantCultureIgnoreCase); - - if (searchIndex < 0) - return original; - //mod to add one onto the search length - otherwise strange results?? - //return original.Substring(original.IndexOf(search) + search.Length + 1); - //return original.Substring(original.IndexOf(search) + search.Length); - //original = original.Substring(searchIndex, original.Length - searchIndex); - //return original.Replace(search,""); + var searchIndex = original.IndexOf(search, 0, StringComparison.InvariantCultureIgnoreCase); + + if (searchIndex < 0) + { + return original; + } + + // mod to add one onto the search length - otherwise strange results?? + // return original.Substring(original.IndexOf(search) + search.Length + 1); + // return original.Substring(original.IndexOf(search) + search.Length); + // original = original.Substring(searchIndex, original.Length - searchIndex); + // return original.Replace(search,""); var regexMatch = @"(" + search + ")(?.+)"; const string regexReplace = @"${keep}"; - var result = Regex.Replace(original, regexMatch, regexReplace, RegexOptions.IgnoreCase ); + var result = Regex.Replace(original, regexMatch, regexReplace, RegexOptions.IgnoreCase); return result; - } - - public string Host { get; private set; } - - public string LocalPath { get; private set; } - - public int Port { get; private set; } + } - /// - /// Portion of the URL after the application. - /// - public string Page { get; private set; } + private void ParseRequestUrl(Uri url) + { + if (url == null) + { + return; + } + + this.Host = url.Host; + this.Port = url.Port; + this.LocalPath = url.LocalPath; + this.Page = StripPrecedingSlashes(RightAfter(url.LocalPath, this.ApplicationPath)); + this._physicalPath = Path.Combine(this._physicalApplicationPath, this.Page.Replace("/", @"\")); + } - private string _applicationPath = "/"; + /// + /// Gets portion of the URL after the application. + /// + public string Page { get; private set; } - /// - /// The same thing as the IIS Virtual directory. It's + /// + /// Gets or sets the same thing as the IIS Virtual directory. It's /// what gets returned by Request.ApplicationPath. /// public string ApplicationPath { - get { return _applicationPath; } - set - { - _applicationPath = value ?? "/"; - _applicationPath = NormalizeSlashes(_applicationPath); + get { return this._applicationPath; } + + set + { + this._applicationPath = value ?? "/"; + this._applicationPath = NormalizeSlashes(this._applicationPath); } } - private string _physicalApplicationPath = WebsitePhysicalAppPath; - /// - /// Physical path to the application (used for simulation purposes). + /// Gets or sets physical path to the application (used for simulation purposes). /// public string PhysicalApplicationPath { - get { return _physicalApplicationPath; } - set + get { return this._physicalApplicationPath; } + + set { - _physicalApplicationPath = value ?? WebsitePhysicalAppPath; - //strip trailing backslashes. - _physicalApplicationPath = StripTrailingBackSlashes(_physicalApplicationPath) + @"\"; + this._physicalApplicationPath = value ?? WebsitePhysicalAppPath; + + // strip trailing backslashes. + this._physicalApplicationPath = StripTrailingBackSlashes(this._physicalApplicationPath) + @"\"; } } - private string _physicalPath = WebsitePhysicalAppPath; - /// - /// Physical path to the requested file (used for simulation purposes). + /// Gets physical path to the requested file (used for simulation purposes). /// public string PhysicalPath { - get { return _physicalPath; } + get { return this._physicalPath; } } - public TextWriter ResponseWriter { get; set; } + public TextWriter ResponseWriter { get; set; } - /// - /// Returns the text from the response to the simulated request. + /// + /// Gets the text from the response to the simulated request. /// public string ResponseText { get { - return (_builder ?? new StringBuilder()).ToString(); + return (this._builder ?? new StringBuilder()).ToString(); } } - public SimulatedHttpRequest WorkerRequest { get; private set; } - - private static string ExtractQueryStringPart(Uri url) - { - var query = url.Query; - return query.StartsWith("?") ? query.Substring(1) : query; - } + public SimulatedHttpRequest WorkerRequest { get; private set; } - void SetHttpRuntimeInternals() + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + /// 2. + public void Dispose() { - //We cheat by using reflection. - - // get singleton property value - var runtime = ReflectionHelper.GetStaticFieldValue("_theRuntime", typeof (HttpRuntime)); - - // set app path property value - ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppPath", runtime, PhysicalApplicationPath); - // set app virtual path property value - const string vpathTypeName = "System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; - var virtualPath = ReflectionHelper.Instantiate(vpathTypeName, new[] { typeof(string) }, new object[] { ApplicationPath }); - ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppVPath", runtime, virtualPath); - - // set codegen dir property value - ReflectionHelper.SetPrivateInstanceFieldValue("_codegenDir", runtime, PhysicalApplicationPath); - - var environment = GetHostingEnvironment(); - ReflectionHelper.SetPrivateInstanceFieldValue("_appPhysicalPath", environment, PhysicalApplicationPath); - ReflectionHelper.SetPrivateInstanceFieldValue("_appVirtualPath", environment, virtualPath); - ReflectionHelper.SetPrivateInstanceFieldValue("_configMapPath", environment, new ConfigMapPath(this)); + HttpContext.Current = null; } protected static HostingEnvironment GetHostingEnvironment() @@ -650,29 +658,63 @@ protected static HostingEnvironment GetHostingEnvironment() } catch (InvalidOperationException) { - //Shoot, we need to grab it via reflection. + // Shoot, we need to grab it via reflection. environment = ReflectionHelper.GetStaticFieldValue("_theHostingEnvironment", typeof(HostingEnvironment)); } + return environment; - } - - #region --- Text Manipulation Methods for slashes --- + } + protected static string NormalizeSlashes(string s) { - if (String.IsNullOrEmpty(s) || s == "/") - return "/"; - + if (string.IsNullOrEmpty(s) || s == "/") + { + return "/"; + } + s = s.Replace(@"\", "/"); - //Reduce multiple slashes in row to single. + // Reduce multiple slashes in row to single. var normalized = Regex.Replace(s, "(/)/+", "$1"); - //Strip left. + + // Strip left. normalized = StripPrecedingSlashes(normalized); - //Strip right. + + // Strip right. normalized = StripTrailingSlashes(normalized); return "/" + normalized; } + private static string ExtractQueryStringPart(Uri url) + { + var query = url.Query; + return query.StartsWith("?") ? query.Substring(1) : query; + } + + private void SetHttpRuntimeInternals() + { + // We cheat by using reflection. + + // get singleton property value + var runtime = ReflectionHelper.GetStaticFieldValue("_theRuntime", typeof(HttpRuntime)); + + // set app path property value + ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppPath", runtime, this.PhysicalApplicationPath); + + // set app virtual path property value + const string vpathTypeName = "System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; + var virtualPath = ReflectionHelper.Instantiate(vpathTypeName, new[] { typeof(string) }, new object[] { this.ApplicationPath }); + ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppVPath", runtime, virtualPath); + + // set codegen dir property value + ReflectionHelper.SetPrivateInstanceFieldValue("_codegenDir", runtime, this.PhysicalApplicationPath); + + var environment = GetHostingEnvironment(); + ReflectionHelper.SetPrivateInstanceFieldValue("_appPhysicalPath", environment, this.PhysicalApplicationPath); + ReflectionHelper.SetPrivateInstanceFieldValue("_appVirtualPath", environment, virtualPath); + ReflectionHelper.SetPrivateInstanceFieldValue("_configMapPath", environment, new ConfigMapPath(this)); + } + protected static string StripPrecedingSlashes(string s) { return Regex.Replace(s, "^/*(.*)", "$1"); @@ -685,17 +727,16 @@ protected static string StripTrailingSlashes(string s) protected static string StripTrailingBackSlashes(string s) { - return String.IsNullOrEmpty(s) ? string.Empty : Regex.Replace(s, @"(.*)\\*$", "$1", RegexOptions.RightToLeft); - } - - #endregion - + return string.IsNullOrEmpty(s) ? string.Empty : Regex.Replace(s, @"(.*)\\*$", "$1", RegexOptions.RightToLeft); + } + internal class ConfigMapPath : IConfigMapPath { private readonly HttpSimulator _requestSimulation; + public ConfigMapPath(HttpSimulator simulation) { - _requestSimulation = simulation; + this._requestSimulation = simulation; } public string GetMachineConfigFilename() @@ -725,23 +766,14 @@ public void ResolveSiteArgument(string siteArgument, out string siteName, out st public string MapPath(string siteId, string path) { - var page = StripPrecedingSlashes(RightAfter(path, _requestSimulation.ApplicationPath)); - return Path.Combine(_requestSimulation.PhysicalApplicationPath, page.Replace("/", @"\")); + var page = StripPrecedingSlashes(RightAfter(path, this._requestSimulation.ApplicationPath)); + return Path.Combine(this._requestSimulation.PhysicalApplicationPath, page.Replace("/", @"\")); } public string GetAppPathForPath(string siteId, string path) { - return _requestSimulation.ApplicationPath; + return this._requestSimulation.ApplicationPath; } } - - /// - ///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - ///2 - public void Dispose() - { - HttpContext.Current = null; - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs index 17d218e4c1c..b6e25611a57 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs @@ -1,64 +1,42 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using System.Reflection; -using System.Web; -using System.Web.Hosting; -using DotNetNuke.Tests.Instance.Utilities.HttpSimulator; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace UnitTests.Subtext { + using System; + using System.Collections.Specialized; + using System.Reflection; + using System.Web; + using System.Web.Hosting; + + using DotNetNuke.Tests.Instance.Utilities.HttpSimulator; + using NUnit.Framework; + ////[TestFixture] public class HttpSimulatorTests { - internal class TestHttpHandler : IHttpHandler + ////[Test] + public void CanGetSetSession() { - public void ProcessRequest(HttpContext context) + using (new HttpSimulator("/", @"c:\inetpub\").SimulateRequest()) { - var physicalPath = context.Request.MapPath("/MyHandler.ashx"); - var username = context.Request.Form["username"]; - var id = context.Request.QueryString["id"]; - if (context.Request.UrlReferrer == null) return; - var referer = context.Request.UrlReferrer.ToString(); - - //Imagine, if you will, a bunch of complex interesting - //and fascinating logic here. - - context.Response.Write(physicalPath + ":" + username + ":" + id + ":" + referer); + HttpContext.Current.Session["Test"] = "Success"; + Assert.AreEqual("Success", HttpContext.Current.Session["Test"], "Was not able to retrieve session variable."); } + } - public bool IsReusable + ////[Test] + public void CanGetSetApplicationVariables() + { + using (new HttpSimulator("/", @"c:\inetpub\").SimulateRequest()) { - get { return true; } + HttpContext.Current.Application["Test"] = "Success"; + Assert.AreEqual("Success", HttpContext.Current.Application["Test"], "Was not able to retrieve application variable."); } } - ////[Test] - public void CanGetSetSession() - { - using (new HttpSimulator("/", @"c:\inetpub\").SimulateRequest()) - { - HttpContext.Current.Session["Test"] = "Success"; - Assert.AreEqual("Success", HttpContext.Current.Session["Test"], "Was not able to retrieve session variable."); - } - } - - ////[Test] - public void CanGetSetApplicationVariables() - { - using (new HttpSimulator("/", @"c:\inetpub\").SimulateRequest()) - { - HttpContext.Current.Application["Test"] = "Success"; - Assert.AreEqual("Success", HttpContext.Current.Application["Test"], "Was not able to retrieve application variable."); - } - } - - ////[Test] + ////[Test] public void TestHttpHandlerWritesCorrectResponse() { using (var simulator = new HttpSimulator("/", @"c:\inetpub\")) @@ -73,7 +51,32 @@ public void TestHttpHandlerWritesCorrectResponse() const string expected = @"c:\inetpub\MyHandler.ashx:phil:1234:http://example.com/1/"; Assert.AreEqual(expected, simulator.ResponseText, "The Expected Response is all wrong."); - } //HttpContext.Current is set to null again. + } // HttpContext.Current is set to null again. + } + + internal class TestHttpHandler : IHttpHandler + { + public bool IsReusable + { + get { return true; } + } + + public void ProcessRequest(HttpContext context) + { + var physicalPath = context.Request.MapPath("/MyHandler.ashx"); + var username = context.Request.Form["username"]; + var id = context.Request.QueryString["id"]; + if (context.Request.UrlReferrer == null) + { + return; + } + + var referer = context.Request.UrlReferrer.ToString(); + + // Imagine, if you will, a bunch of complex interesting + // and fascinating logic here. + context.Response.Write(physicalPath + ":" + username + ":" + id + ":" + referer); + } } ////[Test] @@ -84,6 +87,7 @@ public void CanDispose() simulator.SimulateRequest(); Assert.IsNotNull(HttpContext.Current); } + Assert.IsNull(HttpContext.Current); } @@ -129,13 +133,17 @@ public void CanGetQueryString() { var simulator = new HttpSimulator(); simulator.SimulateRequest(new Uri("http://localhost/Test.aspx?param1=value1¶m2=value2¶m3=value3")); - for (var i = 1; i <= 3; i++) - Assert.AreEqual("value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); - + for (var i = 1; i <= 3; i++) + { + Assert.AreEqual("value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); + } + simulator.SimulateRequest(new Uri("http://localhost/Test.aspx?param1=new-value1¶m2=new-value2¶m3=new-value3¶m4=new-value4")); - for (var i = 1; i <= 4; i++) - Assert.AreEqual("new-value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); - + for (var i = 1; i <= 4; i++) + { + Assert.AreEqual("new-value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); + } + simulator.SimulateRequest(new Uri("http://localhost/Test.aspx?")); Assert.AreEqual(string.Empty, HttpContext.Current.Request.QueryString.ToString()); Assert.AreEqual(0, HttpContext.Current.Request.QueryString.Count); @@ -143,19 +151,19 @@ public void CanGetQueryString() simulator.SimulateRequest(new Uri("http://localhost/Test.aspx")); Assert.AreEqual(string.Empty, HttpContext.Current.Request.QueryString.ToString()); Assert.AreEqual(0, HttpContext.Current.Request.QueryString.Count); - + simulator.SimulateRequest(new Uri("http://localhost/Test.aspx?param-name")); Assert.AreEqual("param-name", HttpContext.Current.Request.QueryString.ToString()); Assert.AreEqual(1, HttpContext.Current.Request.QueryString.Count); Assert.IsNull(HttpContext.Current.Request.QueryString["param-name"]); - } - - // //[Test] + } + + // //[Test] public void CanSimulateFormPost() { using (var simulator = new HttpSimulator()) { - var form = new NameValueCollection {{"Test1", "Value1"}, {"Test2", "Value2"}}; + var form = new NameValueCollection { { "Test1", "Value1" }, { "Test2", "Value2" } }; simulator.SimulateRequest(new Uri("http://localhost/Test.aspx"), form); Assert.AreEqual("Value1", HttpContext.Current.Request.Form["Test1"]); @@ -171,9 +179,9 @@ public void CanSimulateFormPost() Assert.AreEqual("Value1", HttpContext.Current.Request.Form["Test1"]); Assert.AreEqual("Value2", HttpContext.Current.Request.Form["Test2"]); } - } - - // //[Test] + } + + // //[Test] public void CanGetResponse() { var simulator = new HttpSimulator(); @@ -181,9 +189,9 @@ public void CanGetResponse() HttpContext.Current.Response.Write("Hello World!"); HttpContext.Current.Response.Flush(); Assert.AreEqual("Hello World!", simulator.ResponseText); - } - - // //[Test] + } + + // //[Test] public void CanGetReferer() { var simulator = new HttpSimulator(); @@ -209,7 +217,7 @@ public void CanParseRequestUrl(string url, string appPath, string physicalPath, Assert.AreEqual(expectedAppDomainAppPath, simulator.PhysicalApplicationPath); } - //[RowTest] + // [RowTest] ////[Row("http://localhost/AppPath/default.aspx", "/AppPath", "/AppPath/default.aspx")] ////[Row("http://localhost/AppPath/default.aspx", "/", "/AppPath/default.aspx")] public void CanGetLocalPathCorrectly(string url, string appPath, string expectedLocalPath) @@ -220,7 +228,7 @@ public void CanGetLocalPathCorrectly(string url, string appPath, string expected Assert.AreEqual(expectedLocalPath, HttpContext.Current.Request.Url.LocalPath); } - //[RowTest] + // [RowTest] //////[Row("http://localhost:60653/Test.aspx", null, null, "localhost", 60653, "/", "/Test.aspx", @"c:\InetPub\wwwRoot\")] //////[Row("http://localhost:60653/Test.aspx", "/", @"c:\InetPub\wwwRoot\", "localhost", 60653, "/", "/Test.aspx", @"c:\InetPub\wwwRoot\")] //////[Row("http://localhost:60653/Test/Test.aspx", "/", @"c:\InetPub\wwwRoot\", "localhost", 60653, "/", "/Test/Test.aspx", @"c:\InetPub\wwwRoot\")] @@ -238,7 +246,7 @@ public void CanSimulateRequest(string url, string appPath, string physicalPath, Assert.AreEqual(expectedLocalPath, HttpContext.Current.Request.Url.LocalPath); } - //[RowTest] + // [RowTest] ////[Row("/", "/", @"c:\inetpub\wwwroot\")] ////[Row("/Test/Test.aspx", "/", @"c:\inetpub\wwwroot\Test\Test.aspx")] ////[Row("/Test/Blah/Test.aspx", "/", @"c:\inetpub\wwwroot\Test\Blah\Test.aspx")] @@ -250,7 +258,7 @@ public void CanMapPath(string virtualPath, string appPath, string expectedMapPat var simulator = new HttpSimulator(appPath, @"c:\inetpub\wwwroot\"); simulator.SimulateRequest(url); - //Create a virtual path object. + // Create a virtual path object. var vpath = ReflectionHelper.Instantiate("System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", new[] { typeof(string) }, virtualPath); Assert.IsNotNull(vpath); @@ -265,18 +273,17 @@ public void CanMapPath(string virtualPath, string appPath, string expectedMapPat Console.WriteLine("vpath.VirtualPathString == '{0}'", vpathString); var mapping = ReflectionHelper.InvokeNonPublicMethod(typeof(HostingEnvironment), "GetVirtualPathToFileMapping", vpath); - Console.WriteLine("GetVirtualPathToFileMapping: --->{0}<---", (mapping ?? "{NULL}")); + Console.WriteLine("GetVirtualPathToFileMapping: --->{0}<---", mapping ?? "{NULL}"); var o = ReflectionHelper.GetPrivateInstanceFieldValue("_configMapPath", environment); Console.WriteLine("_configMapPath: {0}", o ?? "{null}"); - - + var mappedPath = ReflectionHelper.InvokeNonPublicMethod(environment, "MapPathActual", vpath, false); Console.WriteLine("MAPPED: " + mappedPath); Assert.AreEqual(expectedMapPath, HttpContext.Current.Request.MapPath(virtualPath)); } - //[Test] + // [Test] public void CanInstantiateVirtualPath() { var virtualPathType = Type.GetType("System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true); @@ -284,7 +291,7 @@ public void CanInstantiateVirtualPath() Assert.IsNotNull(constructor); } - //[Test] + // [Test] public void CanGetHostingEnvironment() { var environment = HttpSimulatorTester.CallGetEnvironment(); @@ -293,7 +300,7 @@ public void CanGetHostingEnvironment() Assert.IsNotNull(environment); } - //[RowTest] + // [RowTest] ////[Row("/", "/")] ////[Row("", "/")] ////[Row("/test", "/test")] @@ -309,7 +316,7 @@ public void CanNormalizeSlashes(string s, string expected) Assert.AreEqual(expected, HttpSimulatorTester.CallNormalizeSlashes(s)); } - //[Test] + // [Test] public void CanStripTrailing() { Assert.AreEqual(@"c:\blah\blah2", HttpSimulatorTester.CallStripTrailingBackSlashes(@"c:\blah\blah2\")); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs index 9857d715b47..fdbe2e5fd0c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs @@ -1,38 +1,41 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Instance.Utilities.HttpSimulator { - /// - /// Helper class to simplify common reflection tasks. - /// - public static class ReflectionHelper - { - /// - /// Returns the value of the private member specified. - /// - /// Name of the member. - /// Type of the member. - public static T GetStaticFieldValue(string fieldName, Type type) - { - var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); - if(field != null) - { - return (T)field.GetValue(type); - } - return default(T); - } + using System; + using System.Reflection; + + /// + /// Helper class to simplify common reflection tasks. + /// + public static class ReflectionHelper + { + /// + /// Returns the value of the private member specified. + /// + /// Name of the member. + /// Type of the member. + /// + public static T GetStaticFieldValue(string fieldName, Type type) + { + var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); + if (field != null) + { + return (T)field.GetValue(type); + } + + return default(T); + } - /// - /// Returns the value of the private member specified. - /// - /// Name of the member. - /// - public static T GetStaticFieldValue(string fieldName, string typeName) + /// + /// Returns the value of the private member specified. + /// + /// Name of the member. + /// + /// + public static T GetStaticFieldValue(string fieldName, string typeName) { var type = Type.GetType(typeName, true); var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); @@ -40,6 +43,7 @@ public static T GetStaticFieldValue(string fieldName, string typeName) { return (T)field.GetValue(type); } + return default(T); } @@ -52,42 +56,48 @@ public static T GetStaticFieldValue(string fieldName, string typeName) public static void SetStaticFieldValue(string fieldName, Type type, T value) { var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); - if (field == null) - throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); - + if (field == null) + { + throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); + } + field.SetValue(null, value); } - /// - /// Sets the value of the private static member. - /// - /// - /// - /// - public static void SetStaticFieldValue(string fieldName, string typeName, T value) + /// + /// Sets the value of the private static member. + /// + /// + /// + /// + public static void SetStaticFieldValue(string fieldName, string typeName, T value) { var type = Type.GetType(typeName, true); var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); - if (field == null) - throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); - + if (field == null) + { + throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); + } + field.SetValue(null, value); } - /// - /// Returns the value of the private member specified. - /// - /// Name of the member. - /// The object that contains the member. - public static T GetPrivateInstanceFieldValue(string fieldName, object source) - { - var field = source.GetType().GetField(fieldName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); - if(field != null) - { - return (T)field.GetValue(source); - } - return default(T); - } + /// + /// Returns the value of the private member specified. + /// + /// Name of the member. + /// The object that contains the member. + /// + public static T GetPrivateInstanceFieldValue(string fieldName, object source) + { + var field = source.GetType().GetField(fieldName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); + if (field != null) + { + return (T)field.GetValue(source); + } + + return default(T); + } /// /// Returns the value of the private member specified. @@ -98,9 +108,11 @@ public static T GetPrivateInstanceFieldValue(string fieldName, object source) public static void SetPrivateInstanceFieldValue(string memberName, object source, object value) { var field = source.GetType().GetField(memberName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); - if (field == null) - throw new ArgumentException(string.Format("Could not find the private instance field '{0}'",memberName)); - + if (field == null) + { + throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", memberName)); + } + field.SetValue(source, value); } @@ -109,18 +121,18 @@ public static object Instantiate(string typeName) return Instantiate(typeName, null, null); } - public static object Instantiate(string typeName, Type[] constructorArgumentTypes, params object[] constructorParameterValues) + public static object Instantiate(string typeName, Type[] constructorArgumentTypes, params object[] constructorParameterValues) { - return Instantiate(Type.GetType(typeName, true), constructorArgumentTypes, constructorParameterValues); + return Instantiate(Type.GetType(typeName, true), constructorArgumentTypes, constructorParameterValues); } - public static object Instantiate(Type type, Type[] constructorArgumentTypes, params object[] constructorParameterValues) - { - var constructor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, constructorArgumentTypes, null); - return constructor.Invoke(constructorParameterValues); - } + public static object Instantiate(Type type, Type[] constructorArgumentTypes, params object[] constructorParameterValues) + { + var constructor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, constructorArgumentTypes, null); + return constructor.Invoke(constructorParameterValues); + } - /// + /// /// Invokes a non-public static method. /// /// @@ -133,48 +145,58 @@ public static TReturn InvokeNonPublicMethod(Type type, string methodNam var paramTypes = Array.ConvertAll(parameters, o => o.GetType()); var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static, null, paramTypes, null); - if (method == null) - throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); - + if (method == null) + { + throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); + } + return (TReturn)method.Invoke(null, parameters); } - public static TReturn InvokeNonPublicMethod(object source, string methodName, params object[] parameters) + public static TReturn InvokeNonPublicMethod(object source, string methodName, params object[] parameters) { var paramTypes = Array.ConvertAll(parameters, o => o.GetType()); var method = source.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null); - if (method == null) - throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); - + if (method == null) + { + throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); + } + return (TReturn)method.Invoke(source, parameters); } public static TReturn InvokeProperty(object source, string propertyName) { var propertyInfo = source.GetType().GetProperty(propertyName); - if (propertyInfo == null) - throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); - + if (propertyInfo == null) + { + throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); + } + return (TReturn)propertyInfo.GetValue(source, null); } - public static TReturn InvokeNonPublicProperty(object source, string propertyName) + public static TReturn InvokeNonPublicProperty(object source, string propertyName) { var propertyInfo = source.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance, null, typeof(TReturn), new Type[0], null); - if (propertyInfo == null) - throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); - - return (TReturn) propertyInfo.GetValue(source, null); + if (propertyInfo == null) + { + throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); + } + + return (TReturn)propertyInfo.GetValue(source, null); } public static object InvokeNonPublicProperty(object source, string propertyName) { var propertyInfo = source.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance); - if (propertyInfo == null) - throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); - + if (propertyInfo == null) + { + throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); + } + return propertyInfo.GetValue(source, null); } - } + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs index ea6590bf972..106cba4bfc6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs @@ -1,28 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Specialized; -using System.IO; -using System.Linq; -using System.Text; -using System.Web.Hosting; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Instance.Utilities.HttpSimulator { - /// - /// Used to simulate an HttpRequest. - /// - public class SimulatedHttpRequest : SimpleWorkerRequest - { - Uri _referer; - readonly string _host; - readonly string _verb; - readonly int _port; - readonly string _physicalFilePath; - - /// + using System; + using System.Collections.Specialized; + using System.IO; + using System.Linq; + using System.Text; + using System.Web.Hosting; + + /// + /// Used to simulate an HttpRequest. + /// + public class SimulatedHttpRequest : SimpleWorkerRequest + { + private Uri _referer; + private readonly string _host; + private readonly string _verb; + private readonly int _port; + private readonly string _physicalFilePath; + + /// + /// Initializes a new instance of the class. /// Creates a new instance. /// /// App virtual dir. @@ -34,134 +35,147 @@ public class SimulatedHttpRequest : SimpleWorkerRequest /// Host. /// Port to request. /// The HTTP Verb to use. - public SimulatedHttpRequest(string applicationPath, string physicalAppPath, string physicalFilePath, string page, string query, TextWriter output, string host, int port, string verb) : base(applicationPath, physicalAppPath, page, query, output) - { - Form = new NameValueCollection(); - Headers = new NameValueCollection(); - if (host == null) - throw new ArgumentNullException("host", "Host cannot be null."); + public SimulatedHttpRequest(string applicationPath, string physicalAppPath, string physicalFilePath, string page, string query, TextWriter output, string host, int port, string verb) + : base(applicationPath, physicalAppPath, page, query, output) + { + this.Form = new NameValueCollection(); + this.Headers = new NameValueCollection(); + if (host == null) + { + throw new ArgumentNullException("host", "Host cannot be null."); + } + + if (host.Length == 0) + { + throw new ArgumentException("Host cannot be empty.", "host"); + } + + if (applicationPath == null) + { + throw new ArgumentNullException("applicationPath", "Can't create a request with a null application path. Try empty string."); + } + + this._host = host; + this._verb = verb; + this._port = port; + this._physicalFilePath = physicalFilePath; + } - if(host.Length == 0) - throw new ArgumentException("Host cannot be empty.", "host"); + // public override string GetProtocol() + // { + // return (_port == 443) ? "https:" : "http:"; + // } - if (applicationPath == null) - throw new ArgumentNullException("applicationPath", "Can't create a request with a null application path. Try empty string."); + /// + /// Gets the headers. + /// + /// The headers. + public NameValueCollection Headers { get; private set; } - _host = host; - _verb = verb; - _port = port; - _physicalFilePath = physicalFilePath; - } + /// + /// Gets the format exception. + /// + /// The format exception. + public NameValueCollection Form { get; private set; } - internal void SetReferer(Uri referer) + /// + /// Returns the specified member of the request header. + /// + /// + /// The HTTP verb returned in the request + /// header. + /// + public override string GetHttpVerbName() { - _referer = referer; + return this._verb; } - /// - /// Returns the specified member of the request header. - /// - /// - /// The HTTP verb returned in the request - /// header. - /// - public override string GetHttpVerbName() - { - return _verb; - } - - /// - /// Gets the name of the server. - /// - /// - public override string GetServerName() - { - return _host; - } - - public override int GetLocalPort() - { - return _port; - } - - public override bool IsSecure() + /// + /// Gets the name of the server. + /// + /// + public override string GetServerName() { - return (_port == 443) ? true : false; + return this._host; } - //public override string GetProtocol() - //{ - // return (_port == 443) ? "https:" : "http:"; - //} + internal void SetReferer(Uri referer) + { + this._referer = referer; + } - /// - /// Gets the headers. - /// - /// The headers. - public NameValueCollection Headers { get; private set; } + public override int GetLocalPort() + { + return this._port; + } - /// - /// Gets the format exception. - /// - /// The format exception. - public NameValueCollection Form { get; private set; } + public override bool IsSecure() + { + return (this._port == 443) ? true : false; + } - /// - /// Get all nonstandard HTTP header name-value pairs. - /// - /// An array of header name-value pairs. - public override string[][] GetUnknownRequestHeaders() - { - if(Headers == null || Headers.Count == 0) - { - return null; - } - var headersArray = new string[Headers.Count][]; - for(var i = 0; i < Headers.Count; i++) - { - headersArray[i] = new string[2]; - headersArray[i][0] = Headers.Keys[i]; - headersArray[i][1] = Headers[i]; - } - return headersArray; - } + /// + /// Get all nonstandard HTTP header name-value pairs. + /// + /// An array of header name-value pairs. + public override string[][] GetUnknownRequestHeaders() + { + if (this.Headers == null || this.Headers.Count == 0) + { + return null; + } + + var headersArray = new string[this.Headers.Count][]; + for (var i = 0; i < this.Headers.Count; i++) + { + headersArray[i] = new string[2]; + headersArray[i][0] = this.Headers.Keys[i]; + headersArray[i][1] = this.Headers[i]; + } + + return headersArray; + } public override string GetKnownRequestHeader(int index) { - if (index == 0x24) - return _referer == null ? string.Empty : _referer.ToString(); - - if (index == 12 && _verb == "POST") - return "application/x-www-form-urlencoded"; - + if (index == 0x24) + { + return this._referer == null ? string.Empty : this._referer.ToString(); + } + + if (index == 12 && this._verb == "POST") + { + return "application/x-www-form-urlencoded"; + } + return base.GetKnownRequestHeader(index); } - public override string GetFilePathTranslated() + public override string GetFilePathTranslated() + { + return this._physicalFilePath; + } + + /// + /// Reads request data from the client (when not preloaded). + /// + /// The number of bytes read. + public override byte[] GetPreloadedEntityBody() + { + return Encoding.UTF8.GetBytes(this.Form.Keys.Cast().Aggregate(string.Empty, (current, key) => current + string.Format("{0}={1}&", key, this.Form[key]))); + } + + /// + /// Returns a value indicating whether all request data + /// is available and no further reads from the client are required. + /// + /// + /// if all request data is available; otherwise, + /// . + /// + public override bool IsEntireEntityBodyIsPreloaded() { - return _physicalFilePath; + return true; } - - /// - /// Reads request data from the client (when not preloaded). - /// - /// The number of bytes read. - public override byte[] GetPreloadedEntityBody() - { - return Encoding.UTF8.GetBytes(Form.Keys.Cast().Aggregate(string.Empty, (current, key) => current + string.Format("{0}={1}&", key, Form[key]))); - } - - /// - /// Returns a value indicating whether all request data - /// is available and no further reads from the client are required. - /// - /// - /// if all request data is available; otherwise, - /// . - /// - public override bool IsEntireEntityBodyIsPreloaded() - { - return true; - } - } + } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs index bb66cf908d7..1af19ebfbb6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs @@ -1,34 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + + using NUnit.Framework; + public static class MailAssert - { - #region Private Methods + { + public static void Base64EncodedContentLineContains(string expectedValue, string toAddress, string findByText) + { + var contentLine = ConvertEmailContentFromBase64ToUnicode(GetEmailFileName(toAddress, findByText)); + + Assert.IsTrue(contentLine.Contains(expectedValue)); + } + public static void ContentLineContains(string expectedValue, string toAddress, string findByText) + { + var contentLine = FindContentUsingRegex(expectedValue, GetEmailFileName(toAddress, findByText)); + + Assert.IsFalse(string.IsNullOrEmpty(contentLine)); + } + private static string ConvertEmailContentFromBase64ToUnicode(string emailFileName) { string emailContent = File.ReadAllText(emailFileName); - //Separate the content from the EmailAddress information + // Separate the content from the EmailAddress information const string contentLineRegex = "(base64)(.*(\n)+)+"; Match match = Regex.Match(@emailContent, contentLineRegex, RegexOptions.Singleline); Assert.IsTrue(match.Success, "Could not find content Line! Looking in file: " + emailFileName); - //Convert the EmailAddress content - emailContent = match.Groups[2].Value.Replace("\r\n", ""); + // Convert the EmailAddress content + emailContent = match.Groups[2].Value.Replace("\r\n", string.Empty); byte[] b = Convert.FromBase64String(emailContent); - String decodedEmailContent = Encoding.ASCII.GetString(b); + string decodedEmailContent = Encoding.ASCII.GetString(b); return decodedEmailContent; } @@ -38,7 +50,7 @@ private static string FindContentUsingRegex(string content, string emailFileName string contentLineRegex = @content + ".*"; Match match = Regex.Match(@emailContent, @contentLineRegex); Assert.IsTrue(match.Success, "Could not find content Line! Looking in file: " + emailFileName); - String contentLine = match.Value; + string contentLine = match.Value; return contentLine; } @@ -48,7 +60,7 @@ private static string FindEmailLineUsingRegex(string linePrefix, string emailFil string lineRegex = @"^(" + linePrefix + @"): (.+)"; Match match = Regex.Match(@emailContent, @lineRegex, RegexOptions.Multiline); Assert.IsTrue(match.Success, "Could not find " + linePrefix + " Line! Looking in file: " + emailFileName); - String line = match.Value; + string line = match.Value; return line; } @@ -58,7 +70,7 @@ private static string FindLineUsingRegex(string linePrefix, string emailFileName string lineRegex = linePrefix + @": .*"; Match match = Regex.Match(@emailContent, @lineRegex); Assert.IsTrue(match.Success, "Could not find " + linePrefix + " Line! Looking in file: " + emailFileName); - String line = match.Value; + string line = match.Value; return line; } @@ -72,7 +84,7 @@ private static string GetEmailFileName(string toAddress, string findByText, stri var physicalPath = Directory.GetCurrentDirectory(); var packagePath = physicalPath.Replace("\\Fixtures", "\\Packages"); var emailPath = packagePath + "\\TestEmails"; - var emailFileName = String.Empty; + var emailFileName = string.Empty; foreach (var email in Directory.GetFiles(emailPath)) { @@ -83,28 +95,11 @@ private static string GetEmailFileName(string toAddress, string findByText, stri break; } } + Assert.IsTrue(emailFileName != null, message + " The test was searching in: " + emailPath); - - return emailFileName; - } - - #endregion - #region Public Methods - - public static void Base64EncodedContentLineContains(string expectedValue, string toAddress, string findByText) - { - var contentLine = ConvertEmailContentFromBase64ToUnicode(GetEmailFileName(toAddress, findByText)); - - Assert.IsTrue(contentLine.Contains(expectedValue)); - } - - public static void ContentLineContains(string expectedValue, string toAddress, string findByText) - { - var contentLine = FindContentUsingRegex(expectedValue, GetEmailFileName(toAddress, findByText)); - - Assert.IsFalse(String.IsNullOrEmpty(contentLine)); - } + return emailFileName; + } public static void FromLineContains(string expectedValue, string toAddress, string findByText) { @@ -137,8 +132,6 @@ public static void ToLineContains(string expectedValue, string toAddress, string string toLine = FindEmailLineUsingRegex("To", GetEmailFileName(toAddress, findByText)); Assert.IsTrue(toLine.Contains(expectedValue)); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs index 8e08c51a474..0bb20ebb5ce 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs @@ -1,30 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; - -using Moq; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities.Mocks { + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using Moq; + public class MockComponentProvider { - public static Mock CreateNew() where T : class + public static Mock CreateNew() + where T : class { if (ComponentFactory.Container == null) { ResetContainer(); } - //Try and get mock + // Try and get mock var mockComp = ComponentFactory.GetComponent>(); var objComp = ComponentFactory.GetComponent(); @@ -42,14 +42,15 @@ public static Mock CreateNew() where T : class return mockComp; } - public static Mock CreateNew(string name) where T : class + public static Mock CreateNew(string name) + where T : class { if (ComponentFactory.Container == null) { ResetContainer(); } - //Try and get mock + // Try and get mock var mockComp = ComponentFactory.GetComponent>(); var objComp = ComponentFactory.GetComponent(name); @@ -94,7 +95,7 @@ public static Mock CreateLocalizationProvider() public static Mock CreateLocaleController() { - return CreateNew(); + return CreateNew(); } public static Mock CreateRoleProvider() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/PowershellManager.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/PowershellManager.cs index 5d76d2673e8..31c6f82e1f1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/PowershellManager.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/PowershellManager.cs @@ -1,16 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Management.Automation.Runspaces; -using System.Management.Automation; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.UI.WatiN.Utilities { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Management.Automation; + using System.Management.Automation.Runspaces; + using System.Text; + public class PowershellManager { public static void ExecutePowershellScript(string scriptPath, string executionPolicy, params string[] parameters) @@ -21,9 +21,9 @@ public static void ExecutePowershellScript(string scriptPath, string executionPo using (RunspaceInvoke invoker = new RunspaceInvoke()) { - invoker.Invoke(String.Format("Set-ExecutionPolicy {0}", executionPolicy)); + invoker.Invoke(string.Format("Set-ExecutionPolicy {0}", executionPolicy)); Command myCommand = new Command(scriptPath); - for(int i=0; i < parameters.Length; i++) + for (int i = 0; i < parameters.Length; i++) { myCommand.Parameters.Add(new CommandParameter(null, parameters[i])); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs index 741f4fbe34d..9409ab16bdc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Hosting; -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Instance.Utilities { + using System; + using System.IO; + using System.Web.Hosting; + /// /// Used to simulate an HttpRequest. /// public class SimulatedHttpRequest : SimpleWorkerRequest { - readonly string _host; - - /// + private readonly string _host; + + /// + /// Initializes a new instance of the class. /// Creates a new instance. /// /// App virtual dir. @@ -24,11 +25,15 @@ public class SimulatedHttpRequest : SimpleWorkerRequest /// Query. /// Output. /// Host. - public SimulatedHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output, string host): base(appVirtualDir, appPhysicalDir, page, query, output) + public SimulatedHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output, string host) + : base(appVirtualDir, appPhysicalDir, page, query, output) { - if (string.IsNullOrEmpty(host)) - throw new ArgumentNullException("host", "Host cannot be null nor empty."); - _host = host; + if (string.IsNullOrEmpty(host)) + { + throw new ArgumentNullException("host", "Host cannot be null nor empty."); + } + + this._host = host; } /// @@ -37,7 +42,7 @@ public SimulatedHttpRequest(string appVirtualDir, string appPhysicalDir, string /// public override string GetServerName() { - return _host; + return this._host; } /// @@ -47,12 +52,14 @@ public override string GetServerName() /// public override string MapPath(string virtualPath) { - var path = ""; - var appPath = GetAppPath(); - - if (appPath != null) - path = Path.Combine(appPath, virtualPath); + var path = string.Empty; + var appPath = this.GetAppPath(); + if (appPath != null) + { + path = Path.Combine(appPath, virtualPath); + } + return path; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/UnitTestHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/UnitTestHelper.cs index c251f8afe42..3790de44e30 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/UnitTestHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/UnitTestHelper.cs @@ -1,17 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Instance.Utilities { + using System; + using System.IO; + using System.Web; + public static class UnitTestHelper { /// - /// Sets the HTTP context with a valid simulated request + /// Sets the HTTP context with a valid simulated request. /// /// Host. /// Application. diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs index d44481004de..776d67d1a0c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Utilities { + using System; + using System.Collections.Generic; + using System.IO; + using System.Reflection; + public static class Util { public static List CreateIntegerList(int count) @@ -18,6 +18,7 @@ public static List CreateIntegerList(int count) { list.Add(i); } + return list; } @@ -39,7 +40,7 @@ public static TMember GetPrivateMember(TInstance instance, s result = (TMember)property.GetValue(instance, null); } } - else if(member.MemberType == MemberTypes.Field) + else if (member.MemberType == MemberTypes.Field) { var field = member as FieldInfo; if (field != null) @@ -65,7 +66,7 @@ public static void SetPrivateMember(TInstance instance, strin public static string GetFileName(string testFilesFolder, string fileName) { - string fullName = String.Format("{0}\\{1}", testFilesFolder, fileName); + string fullName = string.Format("{0}\\{1}", testFilesFolder, fileName); if (!fullName.ToLowerInvariant().EndsWith(".csv") && !fullName.ToLowerInvariant().EndsWith(".sql")) { fullName += ".csv"; @@ -82,13 +83,14 @@ public static Stream GetFileStream(string testFilesFolder, string fileName) { stream = new FileStream(GetFileName(testFilesFolder, fileName), FileMode.Open, FileAccess.Read); } + return stream; } public static string ReadStream(string testFilesFolder, string fileName) { - string text = String.Empty; - Stream stream = GetFileStream(testFilesFolder,fileName); + string text = string.Empty; + Stream stream = GetFileStream(testFilesFolder, fileName); if (stream != null) { using (var reader = new StreamReader(GetFileStream(testFilesFolder, fileName))) @@ -96,23 +98,24 @@ public static string ReadStream(string testFilesFolder, string fileName) text = reader.ReadToEnd(); } } + return text; } public static void ReadStream(string testFilesFolder, string fileName, Action onReadLine) { - string text = String.Empty; + string text = string.Empty; var stream = GetFileStream(testFilesFolder, fileName); if (stream != null) { using (var reader = new StreamReader(GetFileStream(testFilesFolder, fileName))) { string line; - string header = String.Empty; + string header = string.Empty; int count = 0; while ((line = reader.ReadLine()) != null) { - //Ignore first line + // Ignore first line if (count > 0) { onReadLine(line, header); @@ -121,12 +124,11 @@ public static void ReadStream(string testFilesFolder, string fileName, Action - - - - - + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DictionaryAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DictionaryAssert.cs index 3da1e92d3ab..08e3bd01b96 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DictionaryAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DictionaryAssert.cs @@ -1,13 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Web.Routing; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc { + using System.Collections.Generic; + using System.Web.Routing; + + using NUnit.Framework; + public static class DictionaryAssert { public static void ContainsEntries(object expected, IDictionary actual) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj index 66e52914ab4..6c9aedb30fc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj @@ -1,155 +1,162 @@ - - - - - Debug - AnyCPU - {AF3A5042-B67B-4F84-9E40-BE06B1105337} - Library - Properties - DotNetNuke.Tests.Web.Mvc - DotNetNuke.Tests.Web.Mvc - v4.7.2 - 512 - ..\..\..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - 7 - - - - ..\..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll - - - ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - - - True - ..\..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - True - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - - ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.Helpers.dll - True - - - False - ..\..\..\Packages\Microsoft.AspNet.Mvc.5.1.3\lib\net45\System.Web.Mvc.dll - - - ..\..\..\packages\Microsoft.AspNet.Razor.3.1.1\lib\net45\System.Web.Razor.dll - True - - - ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.dll - True - - - ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Deployment.dll - True - - - ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Razor.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {0fca217a-5f9a-4f5b-a31b-86d64ae65198} - DotNetNuke.DependencyInjection - - - {64dc5798-9d37-4f8d-97dd-8403e6e70dd3} - DotNetNuke.Web.Mvc - - - {6B29ADED-7B56-4484-BEA5-C0E09079535B} - DotNetNuke.Library - - - {68368906-57DD-40D1-AC10-35211A17D617} - DotNetNuke.Tests.Utilities - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + + Debug + AnyCPU + {AF3A5042-B67B-4F84-9E40-BE06B1105337} + Library + Properties + DotNetNuke.Tests.Web.Mvc + DotNetNuke.Tests.Web.Mvc + v4.7.2 + 512 + ..\..\..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 7 + + + + ..\..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll + + + ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + True + ..\..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + True + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + + ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.Helpers.dll + True + + + False + ..\..\..\Packages\Microsoft.AspNet.Mvc.5.1.3\lib\net45\System.Web.Mvc.dll + + + ..\..\..\packages\Microsoft.AspNet.Razor.3.1.1\lib\net45\System.Web.Razor.dll + True + + + ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.dll + True + + + ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Deployment.dll + True + + + ..\..\..\packages\Microsoft.AspNet.WebPages.3.1.1\lib\net45\System.Web.WebPages.Razor.dll + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + stylecop.json + + + + + + + {0fca217a-5f9a-4f5b-a31b-86d64ae65198} + DotNetNuke.DependencyInjection + + + {64dc5798-9d37-4f8d-97dd-8403e6e70dd3} + DotNetNuke.Web.Mvc + + + {6B29ADED-7B56-4484-BEA5-C0E09079535B} + DotNetNuke.Library + + + {68368906-57DD-40D1-AC10-35211A17D617} + DotNetNuke.Tests.Utilities + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Dog.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Dog.cs index 0e2bfe48ae9..0ce5a43c4e5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Dog.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Dog.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Fakes { public class Dog diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeController.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeController.cs index 48cb209ee40..ce0c9a23fd1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Fakes { + using System.Web.Mvc; + public class FakeController : Controller { public ActionResult Index() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeDnnController.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeDnnController.cs index 13ea6ad37a1..090b488fd6a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeDnnController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/FakeDnnController.cs @@ -1,30 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using System.Web.Routing; -using DotNetNuke.Tests.Web.Mvc.Fakes.Filters; -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Fakes { + using System; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Tests.Web.Mvc.Fakes.Filters; + using DotNetNuke.Web.Mvc.Framework.Controllers; + public class FakeDnnController : DnnController { public ActionResult Action1() { - return View("Action1"); + return this.View("Action1"); } public ActionResult Action2() { - return View("Action2", "Master2"); + return this.View("Action2", "Master2"); } public ActionResult Action3(Dog dog) { - return View("Action3", "Master3", dog); + return this.View("Action3", "Master3", dog); } [FakeHandleExceptionRedirect] @@ -36,13 +37,13 @@ public ActionResult ActionWithExceptionFilter() [FakeOnExecutingRedirect] public ActionResult ActionWithOnExecutingFilter() { - return View("Action1"); + return this.View("Action1"); } [FakeOnExecutedRedirect] public ActionResult ActionWithOnExecutedFilter() { - return View("Action1"); + return this.View("Action1"); } public void MockInitialize(RequestContext requestContext) @@ -50,7 +51,7 @@ public void MockInitialize(RequestContext requestContext) // Mocking out the entire MvcHandler and Controller lifecycle proved to be difficult // This method executes the initialization logic that occurs on every request which is // executed from the Execute method. - Initialize(requestContext); - } + this.Initialize(requestContext); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeHandleExceptionRedirectAttribute.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeHandleExceptionRedirectAttribute.cs index a8981fd7e61..742dde62abc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeHandleExceptionRedirectAttribute.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeHandleExceptionRedirectAttribute.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Fakes.Filters { + using System.Web.Mvc; + public class FakeHandleExceptionRedirectAttribute : FakeRedirectAttribute, IExceptionFilter - { + { public static bool IsExceptionHandled { get; set; } + public void OnException(ExceptionContext filterContext) { filterContext.Result = Result; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutedRedirectAttribute.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutedRedirectAttribute.cs index 0f7291bab7d..31c3f2af76d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutedRedirectAttribute.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutedRedirectAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Fakes.Filters { + using System.Web.Mvc; + public class FakeOnExecutedRedirectAttribute : FakeRedirectAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutingRedirectAttribute.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutingRedirectAttribute.cs index 5d5f846ea17..1ed1cc4ddff 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutingRedirectAttribute.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeOnExecutingRedirectAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Fakes.Filters { + using System.Web.Mvc; + public class FakeOnExecutingRedirectAttribute : FakeRedirectAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeRedirectAttribute.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeRedirectAttribute.cs index 556a7b466e5..b83b792b242 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeRedirectAttribute.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Fakes/Filters/FakeRedirectAttribute.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Fakes.Filters { + using System.Web.Mvc; + public abstract class FakeRedirectAttribute : ActionFilterAttribute { public static ActionResult Result = new EmptyResult(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs index c2f6f04b9ac..c7bdeafdf68 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Web.Mvc; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Web.Mvc.Framework.ActionFilters; -using Moq; -using Moq.Protected; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework.Attributes { + using System.Collections.Generic; + using System.Web.Mvc; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Web.Mvc.Framework.ActionFilters; + using Moq; + using Moq.Protected; + using NUnit.Framework; + [TestFixture] - class DnnAuthorizeAttributeTests + internal class DnnAuthorizeAttributeTests { private MockRepository _mockRepository; private Mock _mockActionDescriptor; @@ -25,120 +26,95 @@ class DnnAuthorizeAttributeTests [SetUp] public void Setup() { - _mockRepository = new MockRepository(MockBehavior.Default); + this._mockRepository = new MockRepository(MockBehavior.Default); - _mockActionDescriptor = _mockRepository.Create(); - _mockControllerDescriptor = _mockRepository.Create(); - _mockRoleController = _mockRepository.Create(); + this._mockActionDescriptor = this._mockRepository.Create(); + this._mockControllerDescriptor = this._mockRepository.Create(); + this._mockRoleController = this._mockRepository.Create(); - _mockDnnAuthorizeAttribute = _mockRepository.Create(); - _mockDnnAuthorizeAttribute.CallBase = true; + this._mockDnnAuthorizeAttribute = this._mockRepository.Create(); + this._mockDnnAuthorizeAttribute.CallBase = true; } [Test] public void AnonymousUser_IsNotAllowed_If_AllowAnonymousAtribute_IsNotPresent() { // Arrange - _mockDnnAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); - var sut = _mockDnnAuthorizeAttribute.Object; - - _mockActionDescriptor.Setup(x => x.IsDefined(typeof (AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockDnnAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); + var sut = this._mockDnnAuthorizeAttribute.Object; + + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var controllerContext = new ControllerContext(); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } [Test] public void AnonymousUser_IsAllowed_If_AllowAnonymousAtribute_IsAtControllerLevel() { // Arrange - var sut = _mockDnnAuthorizeAttribute.Object; + var sut = this._mockDnnAuthorizeAttribute.Object; - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var controllerContext = new ControllerContext(); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } [Test] public void AnonymousUser_IsAllowed_If_AllowAnonymousAtribute_IsAtActionLevel() { // Arrange - - var sut = _mockDnnAuthorizeAttribute.Object; + var sut = this._mockDnnAuthorizeAttribute.Object; - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); var controllerContext = new ControllerContext(); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } [Test] public void RegisteredUser_IsAllowed_ByDefault() { // Arrange - - _mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); - _mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); - var sut = _mockDnnAuthorizeAttribute.Object; - - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); - - var controllerContext = new ControllerContext(); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); - - // Act - sut.OnAuthorization(context); + this._mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); + this._mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); + var sut = this._mockDnnAuthorizeAttribute.Object; - // Assert - _mockRepository.VerifyAll(); - } + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); - private UserInfo SetUpUserWithRole(string roleName) - { - var user = new UserInfo - { - UserID = 1, - PortalID = 1 - }; - - var roles = new List - { - new UserRoleInfo - { - RoleName = roleName, - Status = RoleStatus.Approved - } - }; + var controllerContext = new ControllerContext(); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); - _mockRoleController.Setup(x => x.GetUserRoles(user, true)).Returns(roles); - RoleController.SetTestableInstance(_mockRoleController.Object); + // Act + sut.OnAuthorization(context); - return user; + // Assert + this._mockRepository.VerifyAll(); } [Test] @@ -147,26 +123,26 @@ public void RegisteredUser_IsDenied_If_IncludedIn_DeniedRoles() // Arrange const string roleName = "MyRole"; - var user = SetUpUserWithRole(roleName); - - _mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); - _mockDnnAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); - _mockDnnAuthorizeAttribute.Protected().Setup("GetCurrentUser").Returns(user); - var sut = _mockDnnAuthorizeAttribute.Object; + var user = this.SetUpUserWithRole(roleName); + + this._mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); + this._mockDnnAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); + this._mockDnnAuthorizeAttribute.Protected().Setup("GetCurrentUser").Returns(user); + var sut = this._mockDnnAuthorizeAttribute.Object; sut.DenyRoles = roleName; - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var controllerContext = new ControllerContext(); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } [Test] @@ -176,25 +152,48 @@ public void RegisteredUser_IsAllowed_If_IncludedIn_DeniedRoles_But_IsSuperUser() const string roleName = "MyRole"; var user = new UserInfo { IsSuperUser = true }; - - _mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); - _mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); - _mockDnnAuthorizeAttribute.Protected().Setup("GetCurrentUser").Returns(user); - var sut = _mockDnnAuthorizeAttribute.Object; + + this._mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); + this._mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); + this._mockDnnAuthorizeAttribute.Protected().Setup("GetCurrentUser").Returns(user); + var sut = this._mockDnnAuthorizeAttribute.Object; sut.DenyRoles = roleName; - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var controllerContext = new ControllerContext(); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); + } + + private UserInfo SetUpUserWithRole(string roleName) + { + var user = new UserInfo + { + UserID = 1, + PortalID = 1, + }; + + var roles = new List + { + new UserRoleInfo + { + RoleName = roleName, + Status = RoleStatus.Approved + }, + }; + + this._mockRoleController.Setup(x => x.GetUserRoles(user, true)).Returns(roles); + RoleController.SetTestableInstance(this._mockRoleController.Object); + + return user; } [Test] @@ -203,26 +202,26 @@ public void RegisteredUser_IsDenied_If_IncludedIn_StaticRoles() // Arrange const string roleName = "MyRole"; - var user = SetUpUserWithRole(roleName); + var user = this.SetUpUserWithRole(roleName); - _mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); - _mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); - _mockDnnAuthorizeAttribute.Protected().Setup("GetCurrentUser").Returns(user); - var sut = _mockDnnAuthorizeAttribute.Object; + this._mockDnnAuthorizeAttribute.Protected().Setup("IsAuthenticated").Returns(true); + this._mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); + this._mockDnnAuthorizeAttribute.Protected().Setup("GetCurrentUser").Returns(user); + var sut = this._mockDnnAuthorizeAttribute.Object; sut.StaticRoles = roleName; - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var controllerContext = new ControllerContext(); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnHandleErrorAttributeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnHandleErrorAttributeTests.cs index 4c00f354228..c81ba3ec2e0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnHandleErrorAttributeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnHandleErrorAttributeTests.cs @@ -1,17 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Mvc; -using DotNetNuke.Tests.Web.Mvc.Fakes; -using DotNetNuke.Web.Mvc.Framework.ActionFilters; -using Moq; -using Moq.Protected; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework.Attributes { + using System; + using System.Web.Mvc; + + using DotNetNuke.Tests.Web.Mvc.Fakes; + using DotNetNuke.Web.Mvc.Framework.ActionFilters; + using Moq; + using Moq.Protected; + using NUnit.Framework; + [TestFixture] public class DnnHandleErrorAttributeTests { @@ -28,21 +29,21 @@ public void OnException_Throws_InvalidOPerationExcption_IfNotUsedIn_IDnnControll var ex = Assert.Throws(() => sut.OnException(exceptionContext)); Assert.AreEqual(expectedMessage, ex.Message); } - + [Test] public void OnException_Logs_TheException() { - // Arrange + // Arrange var testException = new Exception(); var exceptionContext = new ExceptionContext { Controller = new FakeDnnController(), - Exception = testException + Exception = testException, }; var mockDnnHandleErrorAttribute = new Mock { CallBase = true }; mockDnnHandleErrorAttribute.Protected().Setup("LogException", testException); - + var sut = mockDnnHandleErrorAttribute.Object; // Act diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnModuleAuthorizeAttributeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnModuleAuthorizeAttributeTests.cs index 52820d47faa..e339af50c47 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnModuleAuthorizeAttributeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnModuleAuthorizeAttributeTests.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework.ActionFilters; -using Moq; -using Moq.Protected; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework.Attributes { + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework.ActionFilters; + using Moq; + using Moq.Protected; + using NUnit.Framework; + [TestFixture] - class DnnModuleAuthorizeAttributeTests + internal class DnnModuleAuthorizeAttributeTests { private MockRepository _mockRepository; private Mock _mockActionDescriptor; @@ -24,126 +25,126 @@ class DnnModuleAuthorizeAttributeTests [SetUp] public void Setup() { - _mockRepository = new MockRepository(MockBehavior.Default); + this._mockRepository = new MockRepository(MockBehavior.Default); - _mockActionDescriptor = _mockRepository.Create(); - _mockControllerDescriptor = _mockRepository.Create(); + this._mockActionDescriptor = this._mockRepository.Create(); + this._mockControllerDescriptor = this._mockRepository.Create(); - _mockDnnModuleAuthorizeAttribute = _mockRepository.Create(); - _mockDnnModuleAuthorizeAttribute.CallBase = true; + this._mockDnnModuleAuthorizeAttribute = this._mockRepository.Create(); + this._mockDnnModuleAuthorizeAttribute.CallBase = true; } [Test] public void AnonymousUser_IsNotAllowed_If_AllowAnonymousAttribute_IsNotPresent() { // Arrange - _mockDnnModuleAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); - var sut = _mockDnnModuleAuthorizeAttribute.Object; + this._mockDnnModuleAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); + var sut = this._mockDnnModuleAuthorizeAttribute.Object; - _mockActionDescriptor.Setup(x => x.IsDefined(typeof (AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); - var fakeController = new Fakes.FakeDnnController { ModuleContext = new ModuleInstanceContext() }; + var fakeController = new Fakes.FakeDnnController { ModuleContext = new ModuleInstanceContext() }; var controllerContext = new ControllerContext(new RequestContext(), fakeController); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } [Test] public void AnonymousUser_IsAllowed_If_AllowAnonymousAttribute_IsAtControllerLevel() { // Arrange - var sut = _mockDnnModuleAuthorizeAttribute.Object; + var sut = this._mockDnnModuleAuthorizeAttribute.Object; - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var fakeController = new Fakes.FakeDnnController { ModuleContext = new ModuleInstanceContext() }; var controllerContext = new ControllerContext(new RequestContext(), fakeController); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } [Test] public void AnonymousUser_IsAllowed_If_AllowAnonymousAttribute_IsAtActionLevel() { // Arrange - var sut = _mockDnnModuleAuthorizeAttribute.Object; + var sut = this._mockDnnModuleAuthorizeAttribute.Object; + + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true); - var fakeController = new Fakes.FakeDnnController { ModuleContext = new ModuleInstanceContext() }; var controllerContext = new ControllerContext(new RequestContext(), fakeController); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - //Assert.IsTrue(a.IsAuthorized); - _mockRepository.VerifyAll(); + // Assert.IsTrue(a.IsAuthorized); + this._mockRepository.VerifyAll(); } [Test] public void RegisteredUser_IsAllowed_IfHasModuleAccess() { // Arrange - var sut = _mockDnnModuleAuthorizeAttribute.Object; - _mockDnnModuleAuthorizeAttribute.Protected().Setup("HasModuleAccess").Returns(true); - _mockDnnModuleAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); + var sut = this._mockDnnModuleAuthorizeAttribute.Object; + this._mockDnnModuleAuthorizeAttribute.Protected().Setup("HasModuleAccess").Returns(true); + this._mockDnnModuleAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny()); - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var moduleContext = new ModuleInstanceContext(); moduleContext.Configuration = new ModuleInfo(); var fakeController = new Fakes.FakeDnnController { ModuleContext = moduleContext }; var controllerContext = new ControllerContext(new RequestContext(), fakeController); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); - + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); + // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } [Test] public void RegisteredUser_IsDenied_IfHasNoModuleAccess() { // Arrange - var sut = _mockDnnModuleAuthorizeAttribute.Object; - _mockDnnModuleAuthorizeAttribute.Protected().Setup("HasModuleAccess").Returns(false); - _mockDnnModuleAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); + var sut = this._mockDnnModuleAuthorizeAttribute.Object; + this._mockDnnModuleAuthorizeAttribute.Protected().Setup("HasModuleAccess").Returns(false); + this._mockDnnModuleAuthorizeAttribute.Protected().Setup("HandleUnauthorizedRequest", ItExpr.IsAny()); - _mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); - _mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(_mockControllerDescriptor.Object); + this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); + this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var moduleContext = new ModuleInstanceContext(); moduleContext.Configuration = new ModuleInfo(); var fakeController = new Fakes.FakeDnnController { ModuleContext = moduleContext }; var controllerContext = new ControllerContext(new RequestContext(), fakeController); - var context = new AuthorizationContext(controllerContext, _mockActionDescriptor.Object); + var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert - _mockRepository.VerifyAll(); + this._mockRepository.VerifyAll(); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Controllers/DnnControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Controllers/DnnControllerTests.cs index bb290c3299c..e33020ab52c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Controllers/DnnControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Controllers/DnnControllerTests.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Tests.Web.Mvc.Fakes; -using DotNetNuke.Web.Mvc.Framework.ActionResults; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework.Controllers { + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Tests.Web.Mvc.Fakes; + using DotNetNuke.Web.Mvc.Framework.ActionResults; + using NUnit.Framework; + [TestFixture] public class DnnControllerTests { @@ -19,40 +20,40 @@ public class DnnControllerTests [Test] public void ActivePage_Property_Is_Null_If_PortalSettings_Not_Set_In_Context() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); - //Assert + // Assert Assert.IsNull(controller.ActivePage); } [Test] public void PortalSettings_Property_Is_Null_If_Not_Set_In_Context() { - //Arrange + // Arrange HttpContextBase context = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(context); + // Act + var controller = this.SetupController(context); - //Assert + // Assert Assert.IsNull(controller.PortalSettings); } [Test] public void ResultOfLastExecute_Returns_ViewResult() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); controller.ActionInvoker.InvokeAction(controller.ControllerContext, "Action1"); - //Assert + // Assert Assert.NotNull(controller.ResultOfLastExecute); Assert.IsInstanceOf(controller.ResultOfLastExecute); } @@ -60,41 +61,41 @@ public void ResultOfLastExecute_Returns_ViewResult() [Test] public void User_Property_Is_Null_If_PortalSettings_Not_Set_In_Context() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); - //Assert + // Assert Assert.IsNull(controller.User); } [Test] public void View_Returns_DnnViewResult() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); var viewResult = controller.Action1(); - //Assert + // Assert Assert.IsInstanceOf(viewResult); } [Test] public void View_Returns_DnnViewResult_With_Correct_ViewName() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); var viewResult = controller.Action1(); - //Assert + // Assert var dnnViewResult = viewResult as DnnViewResult; Assert.NotNull(dnnViewResult); Assert.AreEqual("Action1", dnnViewResult.ViewName); @@ -103,14 +104,14 @@ public void View_Returns_DnnViewResult_With_Correct_ViewName() [Test] public void View_Returns_DnnViewResult_With_Correct_MasterName() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); var viewResult = controller.Action2(); - //Assert + // Assert var dnnViewResult = viewResult as DnnViewResult; Assert.NotNull(dnnViewResult); Assert.AreEqual("Action2", dnnViewResult.ViewName); @@ -120,15 +121,15 @@ public void View_Returns_DnnViewResult_With_Correct_MasterName() [Test] public void View_Returns_DnnViewResult_With_Correct_ViewData() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); controller.ViewData.Add("key", "value"); var viewResult = controller.Action2(); - //Assert + // Assert var dnnViewResult = viewResult as DnnViewResult; Assert.NotNull(dnnViewResult); Assert.AreEqual("value", dnnViewResult.ViewData["key"]); @@ -137,15 +138,15 @@ public void View_Returns_DnnViewResult_With_Correct_ViewData() [Test] public void View_Returns_DnnViewResult_With_Correct_Model() { - //Arrange + // Arrange var dog = new Dog() { Name = "Fluffy" }; HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); var viewResult = controller.Action3(dog); - //Assert + // Assert var dnnViewResult = viewResult as DnnViewResult; Assert.NotNull(dnnViewResult); Assert.AreEqual(dog, dnnViewResult.ViewData.Model); @@ -154,15 +155,15 @@ public void View_Returns_DnnViewResult_With_Correct_Model() [Test] public void View_Returns_DnnViewResult_With_Correct_ViewEngines() { - //Arrange - var dog = new Dog() {Name = "Fluffy"}; + // Arrange + var dog = new Dog() { Name = "Fluffy" }; HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); var viewResult = controller.Action3(dog); - //Assert + // Assert var dnnViewResult = viewResult as DnnViewResult; Assert.NotNull(dnnViewResult); Assert.AreEqual(controller.ViewEngineCollection, dnnViewResult.ViewEngineCollection); @@ -171,21 +172,21 @@ public void View_Returns_DnnViewResult_With_Correct_ViewEngines() [Test] public void Initialize_CreatesInstance_Of_DnnUrlHelper() { - //Arrange + // Arrange HttpContextBase httpContextBase = MockHelper.CreateMockHttpContext(); - //Act - var controller = SetupController(httpContextBase); + // Act + var controller = this.SetupController(httpContextBase); controller.MockInitialize(httpContextBase.Request.RequestContext); - //Assert + // Assert Assert.NotNull(controller.Url); } private FakeDnnController SetupController(HttpContextBase context) { var controller = new FakeDnnController(); - controller.ControllerContext = new ControllerContext(context, new RouteData(), controller ); + controller.ControllerContext = new ControllerContext(context, new RouteData(), controller); return controller; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs index a27f73005cb..f0cc2ae5171 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs @@ -1,37 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web.Mvc; -using DotNetNuke.Tests.Web.Mvc.Fakes; -using DotNetNuke.Web.Mvc.Framework; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Helpers; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework { + using System.Web.Mvc; + + using DotNetNuke.Tests.Web.Mvc.Fakes; + using DotNetNuke.Web.Mvc.Framework; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Helpers; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnWebViewPageTests { [Test] public void InitHelpers_Sets_Dnn_Property() { - //Arrange + // Arrange var mockViewPage = new Mock() { CallBase = true }; var mockController = new Mock(); var mockDnnController = mockController.As(); - var viewContext = new ViewContext - { - Controller = mockController.Object - }; + var viewContext = new ViewContext + { + Controller = mockController.Object, + }; mockViewPage.Object.ViewContext = viewContext; - //Act + // Act mockViewPage.Object.InitHelpers(); - //Assert + // Assert Assert.NotNull(mockViewPage.Object.Dnn); Assert.IsInstanceOf(mockViewPage.Object.Dnn); } @@ -39,20 +40,20 @@ public void InitHelpers_Sets_Dnn_Property() [Test] public void InitHelpers_Sets_Html_Property() { - //Arrange + // Arrange var mockViewPage = new Mock() { CallBase = true }; var mockController = new Mock(); var mockDnnController = mockController.As(); var viewContext = new ViewContext { - Controller = mockController.Object + Controller = mockController.Object, }; mockViewPage.Object.ViewContext = viewContext; - //Act + // Act mockViewPage.Object.InitHelpers(); - //Assert + // Assert Assert.NotNull(mockViewPage.Object.Html); Assert.IsInstanceOf(mockViewPage.Object.Html); } @@ -60,20 +61,20 @@ public void InitHelpers_Sets_Html_Property() [Test] public void InitHelpers_Sets_Dnn_Property_For_Strongly_Typed_Helper() { - //Arrange + // Arrange var mockViewPage = new Mock>() { CallBase = true }; var mockController = new Mock(); var mockDnnController = mockController.As(); var viewContext = new ViewContext { - Controller = mockController.Object + Controller = mockController.Object, }; mockViewPage.Object.ViewContext = viewContext; - //Act + // Act mockViewPage.Object.InitHelpers(); - //Assert + // Assert Assert.NotNull(mockViewPage.Object.Html); Assert.IsInstanceOf>(mockViewPage.Object.Html); } @@ -81,20 +82,20 @@ public void InitHelpers_Sets_Dnn_Property_For_Strongly_Typed_Helper() [Test] public void InitHelpers_Sets_Url_Property() { - //Arrange + // Arrange var mockViewPage = new Mock() { CallBase = true }; var mockController = new Mock(); var mockDnnController = mockController.As(); var viewContext = new ViewContext { - Controller = mockController.Object + Controller = mockController.Object, }; mockViewPage.Object.ViewContext = viewContext; - //Act + // Act mockViewPage.Object.InitHelpers(); - //Assert + // Assert Assert.NotNull(mockViewPage.Object.Url); Assert.IsInstanceOf(mockViewPage.Object.Url); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs index 2e6dc75a7db..3d35584e2a1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs @@ -1,20 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using System.Web.Mvc; -using DotNetNuke.Common; -using DotNetNuke.Web.Mvc.Framework; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Framework.Modules; -using DotNetNuke.Web.Mvc.Routing; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework { + using System.Linq; + using System.Web.Mvc; + + using DotNetNuke.Common; + using DotNetNuke.Web.Mvc.Framework; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Framework.Modules; + using DotNetNuke.Web.Mvc.Routing; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using NUnit.Framework; + [TestFixture] public class ModuleDelegatingViewEngineTests { @@ -31,12 +32,14 @@ public void Should_Forward_FindPartialView_To_Current_ModuleApplication_ViewEngi { // Arrange var mockEngines = new Mock(); - var result = new ViewEngineResult(new[] {"foo", "bar", "baz"}); + var result = new ViewEngineResult(new[] { "foo", "bar", "baz" }); var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); + // ReSharper disable ConvertToConstant.Local string viewName = "Foo"; + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindPartialView(context, viewName)) .Returns(result); @@ -60,13 +63,15 @@ public void Should_Forward_FindView_To_Current_ModuleApplication_ViewEngineColle { // Arrange var mockEngines = new Mock(); - var result = new ViewEngineResult(new[] {"foo", "bar", "baz"}); + var result = new ViewEngineResult(new[] { "foo", "bar", "baz" }); var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); + // ReSharper disable ConvertToConstant.Local var viewName = "Foo"; var masterName = "Bar"; + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindView(context, viewName, masterName)) .Returns(result); @@ -96,9 +101,11 @@ public void Should_Track_ViewEngine_View_Pairs_On_FindView_And_Releases_View_App var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); + // ReSharper disable ConvertToConstant.Local string viewName = "Foo"; string masterName = "Bar"; + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindView(context, viewName, masterName)) .Returns(result); @@ -126,8 +133,10 @@ public void Should_Track_ViewEngine_View_Pairs_On_FindPartialView_And_Releases_V var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); + // ReSharper disable ConvertToConstant.Local string viewName = "Foo"; + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindPartialView(context, viewName)) .Returns(result); @@ -188,13 +197,12 @@ private static void SetupMockModuleApplication(ControllerContext context, ViewEn mockApp.Object.ViewEngines = engines; (context.Controller as IDnnController).ViewEngineCollectionEx = engines; - var activeModuleRequest = new ModuleRequestResult - { - ModuleApplication = mockApp.Object - }; + var activeModuleRequest = new ModuleRequestResult + { + ModuleApplication = mockApp.Object, + }; context.HttpContext.SetModuleRequestResult(activeModuleRequest); } } - } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs index ec3679dce84..44ad62612f0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Framework.Modules; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework.Modules { + using System; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Framework.Modules; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using NUnit.Framework; + [TestFixture] public class ModuleApplicationTests { @@ -175,8 +176,7 @@ public void ExecuteRequest_Executes_Constructed_Controller_And_Provides_RequestC // Assert controller.Verify(c => c.Execute(It.Is(rc => rc.HttpContext == moduleRequestContext.HttpContext && - rc.RouteData.GetRequiredString("controller") == ControllerName)) - ); + rc.RouteData.GetRequiredString("controller") == ControllerName))); } [Test] @@ -245,14 +245,13 @@ private static ModuleRequestContext CreateModuleContext(string controllerName, s routeData.Values.Add("controller", controllerName); routeData.Values.Add("action", actionName); - var moduleContext = new ModuleInstanceContext {Configuration = new ModuleInfo {ModuleID = 42}}; - return new ModuleRequestContext - { - HttpContext = MockHelper.CreateMockHttpContext("http://localhost/Portal/Page/ModuleRoute"), - RouteData = routeData, - ModuleContext = moduleContext - }; + var moduleContext = new ModuleInstanceContext { Configuration = new ModuleInfo { ModuleID = 42 } }; + return new ModuleRequestContext + { + HttpContext = MockHelper.CreateMockHttpContext("http://localhost/Portal/Page/ModuleRoute"), + RouteData = routeData, + ModuleContext = moduleContext, + }; } - } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs index 9d861ac2209..de56ea753e5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Management.Instrumentation; -using System.Web; -using System.Web.Mvc; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Web.Mvc.Common; -using DotNetNuke.Web.Mvc.Framework; -using DotNetNuke.Web.Mvc.Framework.ActionResults; -using DotNetNuke.Web.Mvc.Framework.Modules; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework.Modules { + using System; + using System.Collections.Generic; + using System.IO; + using System.Management.Instrumentation; + using System.Web; + using System.Web.Mvc; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Web.Mvc.Common; + using DotNetNuke.Web.Mvc.Framework; + using DotNetNuke.Web.Mvc.Framework.ActionResults; + using DotNetNuke.Web.Mvc.Framework.Modules; + using Moq; + using NUnit.Framework; + [TestFixture] public class ModuleExecutionEngineTests { @@ -34,7 +35,7 @@ public void ExecuteModule_Returns_Null_If_Application_Is_Null() { // Arrange var engine = new ModuleExecutionEngine(); - var requestContext = new ModuleRequestContext() {ModuleApplication = null}; + var requestContext = new ModuleRequestContext() { ModuleApplication = null }; // Act ModuleRequestResult result = engine.ExecuteModule(requestContext); @@ -81,7 +82,7 @@ public void ExecuteModule_Returns_Result_Of_Executing_ModuleApplication() [Test] public void ExecuteModuleResult_Calls_IDnnViewResult_ExecuteResult() { - //Arrange + // Arrange var engine = new ModuleExecutionEngine(); var actionResultMock = new Mock(); @@ -89,24 +90,23 @@ public void ExecuteModuleResult_Calls_IDnnViewResult_ExecuteResult() var viewResultMock = actionResultMock.As(); var controllerContext = MockHelper.CreateMockControllerContext(); - var moduleRequestResult = new ModuleRequestResult - { - ActionResult = actionResultMock.Object, - ControllerContext = controllerContext - }; + var moduleRequestResult = new ModuleRequestResult + { + ActionResult = actionResultMock.Object, + ControllerContext = controllerContext, + }; - //Act + // Act engine.ExecuteModuleResult(moduleRequestResult, new StringWriter()); - - - //Arrange + + // Arrange viewResultMock.Verify(v => v.ExecuteResult(It.IsAny(), It.IsAny())); } [Test] public void ExecuteModuleResult_Calls_IDnnViewResult_ExecuteResult_With_ModuleRequestResult_ControllerContext() { - //Arrange + // Arrange var engine = new ModuleExecutionEngine(); var actionResultMock = new Mock(); @@ -114,17 +114,16 @@ public void ExecuteModuleResult_Calls_IDnnViewResult_ExecuteResult_With_ModuleRe var viewResultMock = actionResultMock.As(); var controllerContext = MockHelper.CreateMockControllerContext(); - var moduleRequestResult = new ModuleRequestResult - { - ActionResult = actionResultMock.Object, - ControllerContext = controllerContext - }; + var moduleRequestResult = new ModuleRequestResult + { + ActionResult = actionResultMock.Object, + ControllerContext = controllerContext, + }; - //Act + // Act engine.ExecuteModuleResult(moduleRequestResult, new StringWriter()); - - - //Arrange + + // Arrange viewResultMock.Verify(v => v.ExecuteResult(controllerContext, It.IsAny())); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ResultCapturingActionInvokerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ResultCapturingActionInvokerTests.cs index d02f9aa35c2..cd2647f3a8a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ResultCapturingActionInvokerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ResultCapturingActionInvokerTests.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Tests.Web.Mvc.Fakes; -using DotNetNuke.Web.Mvc.Framework.Modules; -using NUnit.Framework; -using DotNetNuke.Tests.Web.Mvc.Fakes.Filters; -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Framework.Modules { + using System; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Tests.Web.Mvc.Fakes; + using DotNetNuke.Tests.Web.Mvc.Fakes.Filters; + using DotNetNuke.Web.Mvc.Framework.Modules; + using NUnit.Framework; + [TestFixture] public class ResultCapturingActionInvokerTests { @@ -21,92 +22,92 @@ public class ResultCapturingActionInvokerTests [SetUp] public void Setup() { - _actionInvoker = new ResultCapturingActionInvoker(); + this._actionInvoker = new ResultCapturingActionInvoker(); } [TearDown] public void TearDown() { - _actionInvoker = null; + this._actionInvoker = null; } [Test] public void InvokeActionResult_Sets_ResultOfLastInvoke() { - //Arrange + // Arrange HttpContextBase context = MockHelper.CreateMockHttpContext(); var controller = new FakeController(); controller.ControllerContext = new ControllerContext(context, new RouteData(), controller); - //Act - _actionInvoker.InvokeAction(controller.ControllerContext, "Index"); + // Act + this._actionInvoker.InvokeAction(controller.ControllerContext, "Index"); - //Assert - Assert.IsNotNull(_actionInvoker.ResultOfLastInvoke); - Assert.IsInstanceOf(_actionInvoker.ResultOfLastInvoke); - } + // Assert + Assert.IsNotNull(this._actionInvoker.ResultOfLastInvoke); + Assert.IsInstanceOf(this._actionInvoker.ResultOfLastInvoke); + } [Test] public void ActionInvoker_InvokeExceptionFilters_IsExceptionHandled_True() { - //Arrange + // Arrange var httpContextBase = MockHelper.CreateMockHttpContext(); - var controller = SetupController(httpContextBase); + var controller = this.SetupController(httpContextBase); FakeHandleExceptionRedirectAttribute.IsExceptionHandled = true; var expectedResult = FakeHandleExceptionRedirectAttribute.Result; - //Act - _actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithExceptionFilter)); + // Act + this._actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithExceptionFilter)); - //Assert - Assert.AreEqual(expectedResult, _actionInvoker.ResultOfLastInvoke); + // Assert + Assert.AreEqual(expectedResult, this._actionInvoker.ResultOfLastInvoke); } [Test] public void ActionInvoker_InvokeExceptionFilters_IsExceptionHandled_False() { - //Arrange + // Arrange var httpContextBase = MockHelper.CreateMockHttpContext(); - var controller = SetupController(httpContextBase); + var controller = this.SetupController(httpContextBase); FakeHandleExceptionRedirectAttribute.IsExceptionHandled = false; var expectedResult = FakeRedirectAttribute.Result; - //Act - Assert.Throws(() => _actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithExceptionFilter))); + // Act + Assert.Throws(() => this._actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithExceptionFilter))); - //Assert - Assert.AreEqual(expectedResult, _actionInvoker.ResultOfLastInvoke); + // Assert + Assert.AreEqual(expectedResult, this._actionInvoker.ResultOfLastInvoke); } [Test] public void ActionInvoker_InvokeOnExecutingFilters() { - //Arrange + // Arrange var httpContextBase = MockHelper.CreateMockHttpContext(); - var controller = SetupController(httpContextBase); + var controller = this.SetupController(httpContextBase); var expectedResult = FakeRedirectAttribute.Result; - //Act - _actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithOnExecutingFilter)); + // Act + this._actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithOnExecutingFilter)); - //Assert - Assert.AreEqual(expectedResult, _actionInvoker.ResultOfLastInvoke); + // Assert + Assert.AreEqual(expectedResult, this._actionInvoker.ResultOfLastInvoke); } [Test] public void ActionInvoker_InvokeOnExecutedFilters() { - //Arrange + // Arrange var httpContextBase = MockHelper.CreateMockHttpContext(); - var controller = SetupController(httpContextBase); + var controller = this.SetupController(httpContextBase); var expectedResult = FakeRedirectAttribute.Result; - //Act - _actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithOnExecutedFilter)); + // Act + this._actionInvoker.InvokeAction(controller.ControllerContext, nameof(FakeDnnController.ActionWithOnExecutedFilter)); - //Assert - Assert.AreEqual(expectedResult, _actionInvoker.ResultOfLastInvoke); + // Assert + Assert.AreEqual(expectedResult, this._actionInvoker.ResultOfLastInvoke); } private FakeDnnController SetupController(HttpContextBase context) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHelperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHelperTests.cs index 2d839bddc4c..46a22f77de5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHelperTests.cs @@ -1,71 +1,72 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Mvc; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Helpers; -using Moq; -using NUnit.Framework; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ObjectCreationAsStatement - namespace DotNetNuke.Tests.Web.Mvc.Helpers { + using System; + using System.Web.Mvc; + + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Helpers; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnHelperTests { private Mock _mockController; - private Mock _mockViewDataContainer ; + private Mock _mockViewDataContainer; private ViewContext _viewContext; [SetUp] public void SetUp() { - _mockController = new Mock(); - _viewContext = new ViewContext(); + this._mockController = new Mock(); + this._viewContext = new ViewContext(); - _mockViewDataContainer = new Mock(); + this._mockViewDataContainer = new Mock(); } [Test] public void Constructor_Throws_On_Null_ViewContext() { - //Act,Assert - Assert.Throws(() => new DnnHelper(null, _mockViewDataContainer.Object)); + // Act,Assert + Assert.Throws(() => new DnnHelper(null, this._mockViewDataContainer.Object)); } [Test] public void Constructor_Throws_On_Null_ViewDataContainer() { - //Act,Assert - Assert.Throws(() => new DnnHelper(null, _mockViewDataContainer.Object)); + // Act,Assert + Assert.Throws(() => new DnnHelper(null, this._mockViewDataContainer.Object)); } [Test] public void Constructor_Throws_On_Invalid_Controller_Property() { - //Arrange - _viewContext.Controller = _mockController.Object; + // Arrange + this._viewContext.Controller = this._mockController.Object; - //Act,Assert - Assert.Throws(() => new DnnHelper(_viewContext, _mockViewDataContainer.Object)); + // Act,Assert + Assert.Throws(() => new DnnHelper(this._viewContext, this._mockViewDataContainer.Object)); } [Test] public void Constructor_Sets_ModuleContext_Property() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); - var mockDnnController = _mockController.As(); + var mockDnnController = this._mockController.As(); mockDnnController.Setup(c => c.ModuleContext).Returns(expectedContext); - _viewContext.Controller = _mockController.Object; + this._viewContext.Controller = this._mockController.Object; - //Act - var helper = new DnnHelper(_viewContext, _mockViewDataContainer.Object); + // Act + var helper = new DnnHelper(this._viewContext, this._mockViewDataContainer.Object); - //Assert + // Assert Assert.AreEqual(expectedContext, helper.ModuleContext); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHtmlHelperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHtmlHelperTests.cs index ffdc5e09b37..1ac08086873 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHtmlHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnHtmlHelperTests.cs @@ -1,126 +1,126 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web; -using System.Web.Mvc; -using DotNetNuke.Tests.Web.Mvc.Fakes; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Helpers; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ObjectCreationAsStatement - namespace DotNetNuke.Tests.Web.Mvc.Helpers { + using System; + using System.Web; + using System.Web.Mvc; + + using DotNetNuke.Tests.Web.Mvc.Fakes; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Helpers; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnHtmlHelperTests { [Test] public void Constructor_Throws_On_Null_ViewContext() { - //Arrange + // Arrange var viewDataContainer = new Mock(); - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(null, viewDataContainer.Object)); } [Test] public void Strongly_Typed_Constructor_Throws_On_Null_ViewContext() { - //Arrange + // Arrange var viewDataContainer = new Mock(); - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(null, viewDataContainer.Object)); } [Test] public void Constructor_Throws_On_Null_ViewDataContainer() { - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(new ViewContext(), null)); } [Test] public void Strongly_Typed_Constructor_Throws_On_Null_ViewDataContainer() { - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(new ViewContext(), null)); } [Test] public void Constructor_Throws_On_Null_RouteCollection() { - //Arrange + // Arrange var viewDataContainer = new Mock(); - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(new ViewContext(), viewDataContainer.Object, null)); } [Test] public void Strongly_Typed_Constructor_Throws_On_Null_RouteCollection() { - //Arrange + // Arrange var viewDataContainer = new Mock(); - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(new ViewContext(), viewDataContainer.Object, null)); } [Test] public void Constructor_Throws_On_Invalid_Controller_Property() { - //Arrange + // Arrange var viewDataContainer = new Mock(); var mockController = new Mock(); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(viewContext, viewDataContainer.Object)); } [Test] public void Strongly_Typed_Constructor_Throws_On_Invalid_Controller_Property() { - //Arrange + // Arrange var mockViewDataContainer = new Mock(); mockViewDataContainer.Setup(d => d.ViewData).Returns(new ViewDataDictionary()); var mockController = new Mock(); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnHtmlHelper(viewContext, mockViewDataContainer.Object)); } [Test] public void Constructor_Sets_ModuleContext_Property() { - //Arrange + // Arrange var viewDataContainer = new Mock(); var mockController = new Mock(); var mockDnnController = mockController.As(); var expectedContext = new ModuleInstanceContext(); mockDnnController.Setup(c => c.ModuleContext).Returns(expectedContext); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act + // Act var helper = new DnnHtmlHelper(viewContext, viewDataContainer.Object); - //Assert + // Assert Assert.AreEqual(expectedContext, helper.ModuleContext); } [Test] public void Strongly_Typed_Constructor_Sets_ModuleContext_Property() { - //Arrange + // Arrange var mockViewDataContainer = new Mock(); mockViewDataContainer.Setup(d => d.ViewData).Returns(new ViewDataDictionary()); var mockController = new Mock(); @@ -128,37 +128,37 @@ public void Strongly_Typed_Constructor_Sets_ModuleContext_Property() var mockDnnController = mockController.As(); var expectedContext = new ModuleInstanceContext(); mockDnnController.Setup(c => c.ModuleContext).Returns(expectedContext); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act + // Act var helper = new DnnHtmlHelper(viewContext, mockViewDataContainer.Object); - //Assert + // Assert Assert.AreEqual(expectedContext, helper.ModuleContext); } [Test] public void ViewContext_Property_Returns_Passed_in_ViewContext() { - //Arrange + // Arrange var mockViewDataContainer = new Mock(); mockViewDataContainer.Setup(d => d.ViewData).Returns(new ViewDataDictionary()); var mockController = new Mock(); var mockDnnController = mockController.As(); mockDnnController.Setup(c => c.ModuleContext).Returns(new ModuleInstanceContext()); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act + // Act var helper = new DnnHtmlHelper(viewContext, mockViewDataContainer.Object); - //Assert + // Assert Assert.AreEqual(viewContext, helper.ViewContext); } [Test] public void ViewDataContainer_Property_Returns_Passed_in_ViewDataContainer() { - //Arrange + // Arrange var mockViewDataContainer = new Mock(); var expectedViewData = new ViewDataDictionary(); mockViewDataContainer.Setup(d => d.ViewData).Returns(expectedViewData); @@ -166,19 +166,19 @@ public void ViewDataContainer_Property_Returns_Passed_in_ViewDataContainer() var mockController = new Mock(); var mockDnnController = mockController.As(); mockDnnController.Setup(c => c.ModuleContext).Returns(new ModuleInstanceContext()); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act + // Act var helper = new DnnHtmlHelper(viewContext, mockViewDataContainer.Object); - //Assert + // Assert Assert.AreEqual(expectedViewData, helper.ViewData); } [Test] public void Strongly_Typed_ViewDataContainer_Property_Returns_Passed_in_Model() { - //Arrange + // Arrange var mockViewDataContainer = new Mock(); var expectedViewData = new ViewDataDictionary(); var expectedModel = new Dog(); @@ -188,19 +188,19 @@ public void Strongly_Typed_ViewDataContainer_Property_Returns_Passed_in_Model() var mockController = new Mock(); var mockDnnController = mockController.As(); mockDnnController.Setup(c => c.ModuleContext).Returns(new ModuleInstanceContext()); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act + // Act var helper = new DnnHtmlHelper(viewContext, mockViewDataContainer.Object); - //Assert + // Assert Assert.AreEqual(expectedModel, helper.ViewData.Model); } [Test] public void EnableClientValidation_Updates_Context() { - //Arrange + // Arrange var mockViewPage = new Mock() { CallBase = true }; var mockController = new Mock(); var mockDnnController = mockController.As(); @@ -209,18 +209,18 @@ public void EnableClientValidation_Updates_Context() mockViewContext.Setup(c => c.Controller).Returns(mockController.Object); mockViewPage.Object.ViewContext = mockViewContext.Object; mockViewPage.Object.InitHelpers(); - - //Act + + // Act mockViewPage.Object.Html.EnableClientValidation(true); - //Assert + // Assert Assert.IsTrue(mockViewPage.Object.ViewContext.ClientValidationEnabled); } [Test] public void EnableUnobtrusiveJavaScript_Updates_Context() { - //Arrange + // Arrange var mockViewPage = new Mock() { CallBase = true }; var mockController = new Mock(); var mockDnnController = mockController.As(); @@ -230,10 +230,10 @@ public void EnableUnobtrusiveJavaScript_Updates_Context() mockViewPage.Object.ViewContext = mockViewContext.Object; mockViewPage.Object.InitHelpers(); - //Act + // Act mockViewPage.Object.Html.EnableUnobtrusiveJavaScript(true); - //Assert + // Assert Assert.IsTrue(mockViewPage.Object.ViewContext.UnobtrusiveJavaScriptEnabled); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs index 03d20df0856..d74836eee2a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.ComponentModel; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvc.Framework.Controllers; -using DotNetNuke.Web.Mvc.Helpers; -using DotNetNuke.Web.Mvc.Routing; -using Moq; -using NUnit.Framework; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ObjectCreationAsStatement - namespace DotNetNuke.Tests.Web.Mvc.Helpers { + using System; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.ComponentModel; + using DotNetNuke.Tests.Utilities.Mocks; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvc.Framework.Controllers; + using DotNetNuke.Web.Mvc.Helpers; + using DotNetNuke.Web.Mvc.Routing; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnUrlHelperTests { @@ -29,56 +30,56 @@ public void SetUp() [Test] public void Constructor_Throws_On_Null_ViewContext() { - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnUrlHelper(null)); } [Test] public void Constructor_Throws_On_Null_RequestContext() { - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnUrlHelper(null, new Mock().Object)); } [Test] public void Constructor_Throws_On_Null_Controller() { - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnUrlHelper(new Mock().Object, null)); } [Test] public void Constructor_Throws_On_Invalid_Controller_Property() { - //Arrange + // Arrange var mockController = new Mock(); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act,Assert + // Act,Assert Assert.Throws(() => new DnnUrlHelper(viewContext)); } [Test] public void ViewContext_Constructor_Sets_ModuleContext_Property() { - //Arrange + // Arrange var mockController = new Mock(); var mockDnnController = mockController.As(); var expectedContext = new ModuleInstanceContext(); mockDnnController.Setup(c => c.ModuleContext).Returns(expectedContext); - var viewContext = new ViewContext {Controller = mockController.Object}; + var viewContext = new ViewContext { Controller = mockController.Object }; - //Act + // Act var helper = new DnnUrlHelper(viewContext); - //Assert + // Assert Assert.AreEqual(expectedContext, helper.ModuleContext); } [Test] public void RequestContext_Constructor_Sets_ModuleContext_Property() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var mockController = new Mock(); @@ -87,10 +88,10 @@ public void RequestContext_Constructor_Sets_ModuleContext_Property() var requestContext = new RequestContext(); - //Act + // Act var helper = new DnnUrlHelper(requestContext, mockController.Object); - //Assert + // Assert Assert.NotNull(helper); Assert.AreEqual(expectedContext, helper.ModuleContext); } @@ -98,15 +99,15 @@ public void RequestContext_Constructor_Sets_ModuleContext_Property() [Test] public void Action_Method_ViewContext_RetrievesRawUrl() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var rawUrl = "http://base.url/"; var helper = ArrangeHelper(expectedContext, rawUrl); - //Act + // Act var result = helper.Action(); - //Assert + // Assert Assert.NotNull(result); Assert.AreEqual(rawUrl, result); } @@ -114,15 +115,15 @@ public void Action_Method_ViewContext_RetrievesRawUrl() [Test] public void Action_Method_RequestContext_RetrievesRawUrl() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var rawUrl = "http://base.url/"; var helper = ArrangeHelper(expectedContext, rawUrl, false); - //Act + // Act var result = helper.Action(); - //Assert + // Assert Assert.NotNull(result); Assert.AreEqual(rawUrl, result); } @@ -130,117 +131,117 @@ public void Action_Method_RequestContext_RetrievesRawUrl() [Test] public void Action_Method_Calls_ModuleRouteProvider() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); var mockRouteProvider = new Mock(); ComponentFactory.RegisterComponentInstance(mockRouteProvider.Object); - //Act + // Act helper.Action("foo"); - //Assert + // Assert mockRouteProvider.Verify(p => p.GenerateUrl(It.IsAny(), expectedContext)); } [Test] public void Action_Overload_1__Method_Calls_ModuleRouteProvider() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); var mockRouteProvider = new Mock(); ComponentFactory.RegisterComponentInstance(mockRouteProvider.Object); - //Act + // Act helper.Action("foo", new RouteValueDictionary()); - //Assert + // Assert mockRouteProvider.Verify(p => p.GenerateUrl(It.IsAny(), expectedContext)); } [Test] public void Action_Overload_2_Method_Calls_ModuleRouteProvider() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); var mockRouteProvider = new Mock(); ComponentFactory.RegisterComponentInstance(mockRouteProvider.Object); - //Act + // Act helper.Action("foo", "bar"); - //Assert + // Assert mockRouteProvider.Verify(p => p.GenerateUrl(It.IsAny(), expectedContext)); } [Test] public void Action_Overload_3_Method_Calls_ModuleRouteProvider() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); var mockRouteProvider = new Mock(); ComponentFactory.RegisterComponentInstance(mockRouteProvider.Object); - //Act + // Act helper.Action("foo", "bar", new RouteValueDictionary()); - //Assert + // Assert mockRouteProvider.Verify(p => p.GenerateUrl(It.IsAny(), expectedContext)); } [Test] public void Action_Overload_4_Method_Calls_ModuleRouteProvider() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); var mockRouteProvider = new Mock(); ComponentFactory.RegisterComponentInstance(mockRouteProvider.Object); - //Act + // Act helper.Action("foo", new { id = 5 }); - //Assert + // Assert mockRouteProvider.Verify(p => p.GenerateUrl(It.IsAny(), expectedContext)); } [Test] public void Action_Overload_5_Method_Calls_ModuleRouteProvider() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); var mockRouteProvider = new Mock(); ComponentFactory.RegisterComponentInstance(mockRouteProvider.Object); - //Act + // Act helper.Action("foo", "bar", new { id = 5 }); - //Assert + // Assert mockRouteProvider.Verify(p => p.GenerateUrl(It.IsAny(), expectedContext)); } [Test] public void Content_Method_Calls_Returns_Correct_Url() { - //Arrange + // Arrange var context = new ModuleInstanceContext(); var helper = ArrangeHelper(context, "http://foo.com/foo"); string expectedResult = "/foo/test.css"; - //Act + // Act var url = helper.Content("~/test.css"); - //Assert + // Assert Assert.IsNotNull(url); Assert.True(expectedResult.Equals(url)); } @@ -248,15 +249,15 @@ public void Content_Method_Calls_Returns_Correct_Url() [Test] public void IsLocalUrl_Method_Calls_Returns_Correct_Result() { - //Arrange + // Arrange var context = new ModuleInstanceContext(); var helper = ArrangeHelper(context, "http://foo.com"); - //Act + // Act var withOuterUrl = helper.IsLocalUrl("http://dnnsoftware.com"); var withLocalUrl = helper.IsLocalUrl("~/foo/foo.html"); - - //Assert + + // Assert Assert.IsFalse(withOuterUrl); Assert.IsTrue(withLocalUrl); } @@ -264,11 +265,10 @@ public void IsLocalUrl_Method_Calls_Returns_Correct_Result() [Test] public void GenerateUrl_Method_Passes_Correct_RouteValueCollection_To_ModuleRouteProvider() { - //Arrange + // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); - - + RouteValueDictionary routeValues = null; var mockRouteProvider = new Mock(); mockRouteProvider.Setup(p => p.GenerateUrl(It.IsAny(), expectedContext)) @@ -276,10 +276,10 @@ public void GenerateUrl_Method_Passes_Correct_RouteValueCollection_To_ModuleRout ComponentFactory.RegisterComponentInstance(mockRouteProvider.Object); - //Act + // Act helper.Action("foo", "bar", new { id = 5 }); - //Assert + // Assert Assert.AreEqual(3, routeValues.Values.Count); Assert.IsTrue(routeValues.ContainsKey("action")); Assert.IsTrue(routeValues.ContainsKey("controller")); @@ -297,8 +297,8 @@ private static DnnUrlHelper ArrangeHelper(ModuleInstanceContext expectedContext, var routeData = new RouteData(); routeData.Values["controller"] = "bar"; routeData.Values["action"] = "foo"; - var context = MockHelper.CreateMockControllerContext(url!=null? MockHelper.CreateMockHttpContext(url):null, routeData); - + var context = MockHelper.CreateMockControllerContext(url != null ? MockHelper.CreateMockHttpContext(url) : null, routeData); + mockDnnController.Setup(c => c.ModuleContext).Returns(expectedContext); mockDnnController.Setup(c => c.ControllerContext).Returns(context); @@ -306,9 +306,11 @@ private static DnnUrlHelper ArrangeHelper(ModuleInstanceContext expectedContext, { var viewContext = new ViewContext { Controller = mockController.Object }; - if (!string.IsNullOrEmpty(url)) - viewContext.RequestContext = new RequestContext(MockHelper.CreateMockHttpContext(url), routeData); - + if (!string.IsNullOrEmpty(url)) + { + viewContext.RequestContext = new RequestContext(MockHelper.CreateMockHttpContext(url), routeData); + } + return new DnnUrlHelper(viewContext); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/ViewResultExtensionsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/ViewResultExtensionsTests.cs index 7de0287a049..0f35fa363fa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/ViewResultExtensionsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/ViewResultExtensionsTests.cs @@ -1,56 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Web.Mvc.Framework.ActionResults; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Helpers { + using System; + using System.IO; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Web.Mvc.Framework.ActionResults; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnViewResultTests { [Test] public void ExecuteResult_Throws_With_Null_ControllerContext() { - //Arrange + // Arrange var result = new DnnViewResult(); - - //Act, Assert + + // Act, Assert Assert.Throws(() => result.ExecuteResult(null, new StringWriter())); } [Test] public void ExecuteResult_Throws_With_Null_TextWriter() { - //Arrange + // Arrange var result = new DnnViewResult(); var context = MockHelper.CreateMockControllerContext(); - //Act, Assert + // Act, Assert Assert.Throws(() => result.ExecuteResult(context, null)); } [Test] public void ExecuteResult_Throws_With_Empty_ViewName_And_No_Action() { - //Arrange + // Arrange var result = new DnnViewResult(); var context = MockHelper.CreateMockControllerContext(); - //Act, Assert + // Act, Assert Assert.Throws(() => result.ExecuteResult(context, new StringWriter())); } [Test] public void ExecuteResult_Calls_ViewEngine_FindView_If_View_Is_Null() { - //Arrange + // Arrange var result = new DnnViewResult(); var routeData = new RouteData(); @@ -66,10 +67,10 @@ public void ExecuteResult_Calls_ViewEngine_FindView_If_View_Is_Null() result.ViewEngineCollection.Clear(); result.ViewEngineCollection.Add(mockViewEngine.Object); - //Act + // Act result.ExecuteResult(context, new StringWriter()); - //Assert + // Assert Assert.AreSame(mockView.Object, result.View); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs index c020f964b53..51389f7565a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.IO; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using Moq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.IO; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + + using Moq; + public class MockHelper { public static HttpContextBase CreateMockHttpContext() @@ -38,7 +39,7 @@ public static HttpContextBase CreateMockHttpContext(Dictionary i .Returns(mockRequest.Object); mockContext.SetupGet(c => c.Response) .Returns(mockResponse.Object); - + return mockContext.Object; } @@ -87,7 +88,7 @@ public static ControllerContext CreateMockControllerContext(RouteData routeDatae public static ControllerContext CreateMockControllerContext(HttpContextBase httpContext, RouteData routeData) { - return new ControllerContext(httpContext?? CreateMockHttpContext(), routeData, new Mock().Object); + return new ControllerContext(httpContext ?? CreateMockHttpContext(), routeData, new Mock().Object); } public static ViewContext CreateViewContext(string url) @@ -96,14 +97,16 @@ public static ViewContext CreateViewContext(string url) routeData.Values["controller"] = "Controller"; routeData.Values["action"] = "Action"; routeData.Values["id"] = "Id"; - var controllerContext = new ControllerContext(CreateMockHttpContext(url), - routeData, - new Mock().Object); - return new ViewContext(controllerContext, - new Mock().Object, - new ViewDataDictionary(), - new TempDataDictionary(), - new StringWriter()); + var controllerContext = new ControllerContext( + CreateMockHttpContext(url), + routeData, + new Mock().Object); + return new ViewContext( + controllerContext, + new Mock().Object, + new ViewDataDictionary(), + new TempDataDictionary(), + new StringWriter()); } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Properties/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Properties/AssemblyInfo.cs index 61c8c332c71..a17ac9b26ce 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Properties/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Properties/AssemblyInfo.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Tests.Web.Mvc")] @@ -18,8 +18,8 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// 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 +// 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)] @@ -29,11 +29,11 @@ // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs index afc7107f94c..6c3f39a54ef 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs @@ -1,15 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Web.Mvc; -using System.Web.Routing; -using DotNetNuke.Web.Mvc.Framework.ActionResults; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc { + using System; + using System.Web.Mvc; + using System.Web.Routing; + + using DotNetNuke.Web.Mvc.Framework.ActionResults; + using NUnit.Framework; + public static class ResultAssert { public static void IsEmpty(ActionResult result) @@ -24,7 +25,7 @@ public static void IsUnauthorized(ActionResult result) public static void IsView(ActionResult result, string viewName) { - IsView(result, viewName, String.Empty, new RouteValueDictionary()); + IsView(result, viewName, string.Empty, new RouteValueDictionary()); } public static void IsView(ActionResult result, string viewName, string masterName, RouteValueDictionary expectedViewData) @@ -35,7 +36,9 @@ public static void IsView(ActionResult result, string viewName, string masterNam DictionaryAssert.ContainsEntries(expectedViewData, viewResult.ViewData); } - private static TCast AssertCast(this ActionResult result) where TCast : class + + private static TCast AssertCast(this ActionResult result) + where TCast : class { var castResult = result as TCast; Assert.IsNotNull(castResult); @@ -44,9 +47,9 @@ private static TCast AssertCast(this ActionResult result) where TCast : c private static void StringsEqualOrBothNullOrEmpty(string expected, string actual) { - if (String.IsNullOrEmpty(expected)) + if (string.IsNullOrEmpty(expected)) { - Assert.IsTrue(String.IsNullOrEmpty(actual)); + Assert.IsTrue(string.IsNullOrEmpty(actual)); } else { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Routing/HttpContextExtensionsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Routing/HttpContextExtensionsTests.cs index d0b1115c94d..3bc8e46c0ef 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Routing/HttpContextExtensionsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Routing/HttpContextExtensionsTests.cs @@ -1,43 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Web; -using DotNetNuke.Web.Mvc.Framework.Modules; -using DotNetNuke.Web.Mvc.Routing; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvc.Routing { + using System.Web; + + using DotNetNuke.Web.Mvc.Framework.Modules; + using DotNetNuke.Web.Mvc.Routing; + using Moq; + using NUnit.Framework; + [TestFixture] public class HttpContextExtensionsTests { [Test] public void GetModuleRequestResult_Returns_ModuleRequestResult_If_Present() { - //Arrange + // Arrange var httpContext = MockHelper.CreateMockHttpContext(); var expectedResult = new ModuleRequestResult(); httpContext.Items[HttpContextExtensions.ModuleRequestResultKey] = expectedResult; - //Act + // Act var result = httpContext.GetModuleRequestResult(); - //Assert + // Assert Assert.AreSame(expectedResult, result); } [Test] public void GetModuleRequestResult_Returns_Null_If_Not_Present() { - //Arrange + // Arrange var httpContext = MockHelper.CreateMockHttpContext(); - //Act + // Act var result = httpContext.GetModuleRequestResult(); - //Assert + // Assert Assert.IsNull(result); } @@ -49,7 +50,7 @@ public void HasModuleRequestResult_Returns_True_If_Present() var expectedResult = new ModuleRequestResult(); httpContext.Items[HttpContextExtensions.ModuleRequestResultKey] = expectedResult; - //Act and Assert + // Act and Assert Assert.IsTrue(httpContext.HasModuleRequestResult()); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config index 6e583871502..7729029ef39 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config @@ -10,4 +10,5 @@ + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs index 61c679dc282..74bf3ab3cda 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs @@ -1,30 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using DotNetNuke.Web.Api.Auth; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + + using DotNetNuke.Web.Api.Auth; + using NUnit.Framework; + [TestFixture] public class BasicAuthMessageHandlerTests { [Test] public void SetsWwwAuthenticateHeaderOn401() { - //Arrange - var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) {RequestMessage = new HttpRequestMessage()}; + // Arrange + var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = new HttpRequestMessage() }; - //Act + // Act var handler = new BasicAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert Assert.AreEqual("Basic", response.Headers.WwwAuthenticate.First().Scheme); Assert.AreEqual("realm=\"DNNAPI\"", response.Headers.WwwAuthenticate.First().Parameter); } @@ -32,31 +33,31 @@ public void SetsWwwAuthenticateHeaderOn401() [Test] public void OmitsWwwAuthenticateHeaderOn401FromXmlHttpRequest() { - //Arrange - var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) - {RequestMessage = new HttpRequestMessage()}; + // Arrange + var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) + { RequestMessage = new HttpRequestMessage() }; response.RequestMessage.Headers.Add("X-REQUESTED-WITH", "XmlHttpRequest"); - //Act + // Act var handler = new BasicAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert CollectionAssert.IsEmpty(response.Headers.WwwAuthenticate); } [Test] public void MissingXmlHttpRequestValueDoesntThrowNullException() { - //Arrange + // Arrange var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = new HttpRequestMessage() }; - response.RequestMessage.Headers.Add("X-REQUESTED-WITH", ""); + response.RequestMessage.Headers.Add("X-REQUESTED-WITH", string.Empty); - //Act + // Act var handler = new BasicAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert Assert.AreEqual("Basic", response.Headers.WwwAuthenticate.First().Scheme); Assert.AreEqual("realm=\"DNNAPI\"", response.Headers.WwwAuthenticate.First().Parameter); } @@ -64,20 +65,20 @@ public void MissingXmlHttpRequestValueDoesntThrowNullException() [Test] public void ResponseWithNullRequestReturnsUnauthorized() { - //Arrange + // Arrange var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = null }; - //Act + // Act var handler = new BasicAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert Assert.AreEqual("Basic", response.Headers.WwwAuthenticate.First().Scheme); Assert.AreEqual("realm=\"DNNAPI\"", response.Headers.WwwAuthenticate.First().Parameter); } - //todo unit test actual authentication code - //very hard to unit test inbound authentication code as it dips into untestable bits of usercontroller etc. - //need to write controllers with interfaces and servicelocator + // todo unit test actual authentication code + // very hard to unit test inbound authentication code as it dips into untestable bits of usercontroller etc. + // need to write controllers with interfaces and servicelocator } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DigestAuthMessageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DigestAuthMessageHandlerTests.cs index 04a6e0f9144..cec873fb5e8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DigestAuthMessageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DigestAuthMessageHandlerTests.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using DotNetNuke.Security.Membership; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.Web.Api.Auth; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + + using DotNetNuke.Security.Membership; + using DotNetNuke.Tests.Utilities.Mocks; + using DotNetNuke.Web.Api.Auth; + using NUnit.Framework; + [TestFixture] public class DigestAuthMessageHandlerTests { @@ -26,14 +27,14 @@ public void Setup() [Test] public void SetsWwwAuthenticateHeaderOn401() { - //Arrange + // Arrange var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = new HttpRequestMessage() }; - //Act + // Act var handler = new DigestAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert Assert.AreEqual("Digest", response.Headers.WwwAuthenticate.First().Scheme); StringAssert.Contains("realm=\"DNNAPI\"", response.Headers.WwwAuthenticate.First().Parameter); } @@ -41,30 +42,30 @@ public void SetsWwwAuthenticateHeaderOn401() [Test] public void OmitsWwwAuthenticateHeaderOn401FromXmlHttpRequest() { - //Arrange + // Arrange var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = new HttpRequestMessage() }; response.RequestMessage.Headers.Add("X-REQUESTED-WITH", "XmlHttpRequest"); - //Act + // Act var handler = new DigestAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert CollectionAssert.IsEmpty(response.Headers.WwwAuthenticate); } [Test] public void MissingXmlHttpRequestValueDoesntThrowNullException() { - //Arrange + // Arrange var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = new HttpRequestMessage() }; - response.RequestMessage.Headers.Add("X-REQUESTED-WITH", ""); + response.RequestMessage.Headers.Add("X-REQUESTED-WITH", string.Empty); - //Act + // Act var handler = new DigestAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert Assert.AreEqual("Digest", response.Headers.WwwAuthenticate.First().Scheme); StringAssert.Contains("realm=\"DNNAPI\"", response.Headers.WwwAuthenticate.First().Parameter); } @@ -72,20 +73,20 @@ public void MissingXmlHttpRequestValueDoesntThrowNullException() [Test] public void ResponseWithNullRequestReturnsUnauthorized() { - //Arrange + // Arrange var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = null }; - //Act + // Act var handler = new DigestAuthMessageHandler(true, false); - handler.OnOutboundResponse(response, new CancellationToken()); + handler.OnOutboundResponse(response, CancellationToken.None); - //Assert + // Assert Assert.AreEqual("Digest", response.Headers.WwwAuthenticate.First().Scheme); StringAssert.Contains("realm=\"DNNAPI\"", response.Headers.WwwAuthenticate.First().Parameter); } - //todo unit test actual authentication code - //very hard to unit test inbound authentication code as it dips into untestable bits of usercontroller etc. - //need to write controllers with interfaces and servicelocator + // todo unit test actual authentication code + // very hard to unit test inbound authentication code as it dips into untestable bits of usercontroller etc. + // need to write controllers with interfaces and servicelocator } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnActionFilterProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnActionFilterProviderTests.cs index e8a6349f90c..0eb1f7f3eb8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnActionFilterProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnActionFilterProviderTests.cs @@ -1,19 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.ObjectModel; -using System.Linq; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Filters; -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System.Collections.ObjectModel; + using System.Linq; + using System.Web.Http; + using System.Web.Http.Controllers; + using System.Web.Http.Filters; + + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnActionFilterProviderTests { @@ -32,11 +33,11 @@ public void RequiresHostAttributeAddedWhenNoOtherActionFiltersPresent() var configuration = new HttpConfiguration(); - //Act + // Act var filterProvider = new DnnActionFilterProvider(); var filters = filterProvider.GetFilters(configuration, actionDescriptor).ToList(); - //Assert + // Assert Assert.AreEqual(1, filters.Count); Assert.IsInstanceOf(filters.First().Instance); } @@ -46,7 +47,7 @@ public void RequiresHostAttributeNotAddedWhenAnOverrideAuthFilterPresent() { // Arrange var adMock = new Mock(); - adMock.Setup(ad => ad.GetFilters()).Returns(new Collection(new []{ new DnnAuthorizeAttribute() })); + adMock.Setup(ad => ad.GetFilters()).Returns(new Collection(new[] { new DnnAuthorizeAttribute() })); var cdMock = new Mock(); cdMock.Setup(cd => cd.GetFilters()).Returns(new Collection()); @@ -56,11 +57,11 @@ public void RequiresHostAttributeNotAddedWhenAnOverrideAuthFilterPresent() var configuration = new HttpConfiguration(); - //Act + // Act var filterProvider = new DnnActionFilterProvider(); var filters = filterProvider.GetFilters(configuration, actionDescriptor).ToList(); - //Assert + // Assert Assert.AreEqual(1, filters.Count); Assert.IsInstanceOf(filters.First().Instance); } @@ -80,11 +81,11 @@ public void RequiresHostAttributeAddedWhenNoOverrideAuthFilterPresent() var configuration = new HttpConfiguration(); - //Act + // Act var filterProvider = new DnnActionFilterProvider(); var filters = filterProvider.GetFilters(configuration, actionDescriptor).ToList(); - //Assert + // Assert Assert.AreEqual(2, filters.Count); Assert.IsInstanceOf(filters.Last().Instance); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs index 39738383936..5272f04399c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using System.Web.Http; -using System.Web.Http.Hosting; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Internal; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Web.Api; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Net.Http; + using System.Web.Http; + using System.Web.Http.Hosting; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Web.Api; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnApiControllerTests { - internal class DnnApiControllerHelper : DnnApiController {} - [TearDown] public void TearDown() { @@ -29,7 +28,7 @@ public void TearDown() [Test] public void GetsModuleInfoViaTheTabModuleInfoProviders() { - //Arrange + // Arrange var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -38,12 +37,12 @@ public void GetsModuleInfoViaTheTabModuleInfoProviders() configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - var controller = new DnnApiControllerHelper {Request = request}; + var controller = new DnnApiControllerHelper { Request = request }; - //Act + // Act var result = controller.ActiveModule; - //Assert + // Assert Assert.AreEqual(expectedModule, result); provider.Verify(x => x.TryFindModuleInfo(request, out expectedModule), Times.Once()); } @@ -51,40 +50,44 @@ public void GetsModuleInfoViaTheTabModuleInfoProviders() [Test] public void GetsPortalSettingsViaTestablePortalController() { - //Arrange + // Arrange var controller = new DnnApiControllerHelper(); var mockPortalController = new Mock(); var expectedPortalSettings = new PortalSettings(); mockPortalController.Setup(x => x.GetCurrentPortalSettings()).Returns(expectedPortalSettings); PortalController.SetTestableInstance(mockPortalController.Object); - //Act + // Act var result = controller.PortalSettings; - //Assert + // Assert mockPortalController.Verify(x => x.GetCurrentPortalSettings(), Times.Once()); Assert.AreEqual(expectedPortalSettings, result); - } - - //A test that would be nice to run, but I see not good way to test the source of the - //userinfo -// [Test] -// public void UserInfoComesFromPortalSettings() -// { -// //Arrange -// var controller = new DnnApiControllerHelper(); -// var mockPortalController = new Mock(); -// var expectedPortalSettings = new PortalSettings(); - //expectedPortalSettings.UserInfo = ?????? -// mockPortalController.Setup(x => x.GetCurrentPortalSettings()).Returns(expectedPortalSettings); -// TestablePortalController.SetTestableInstance(mockPortalController.Object); -// -// //Act -// var result = controller.PortalSettings; -// -// //Assert -// mockPortalController.Verify(x => x.GetCurrentPortalSettings(), Times.Once()); -// Assert.AreEqual(expectedPortalSettings, result); -// } + } + + internal class DnnApiControllerHelper : DnnApiController + { + } + + // A test that would be nice to run, but I see not good way to test the source of the + // userinfo + // [Test] + // public void UserInfoComesFromPortalSettings() + // { + // //Arrange + // var controller = new DnnApiControllerHelper(); + // var mockPortalController = new Mock(); + // var expectedPortalSettings = new PortalSettings(); + // expectedPortalSettings.UserInfo = ?????? + // mockPortalController.Setup(x => x.GetCurrentPortalSettings()).Returns(expectedPortalSettings); + // TestablePortalController.SetTestableInstance(mockPortalController.Object); + // + // //Act + // var result = controller.PortalSettings; + // + // //Assert + // mockPortalController.Verify(x => x.GetCurrentPortalSettings(), Times.Once()); + // Assert.AreEqual(expectedPortalSettings, result); + // } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnHttpControllerSelectorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnHttpControllerSelectorTests.cs index 324c3e0411f..97b60b09f8f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnHttpControllerSelectorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnHttpControllerSelectorTests.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Net.Http; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Dispatcher; -using System.Web.Http.Hosting; -using System.Web.Http.Routing; -using DotNetNuke.Web.Api; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Net.Http; + using System.Web.Http; + using System.Web.Http.Controllers; + using System.Web.Http.Dispatcher; + using System.Web.Http.Hosting; + using System.Web.Http.Routing; + + using DotNetNuke.Web.Api; + using Moq; + using NUnit.Framework; + [TestFixture] public class DnnHttpControllerSelectorTests { @@ -39,7 +40,7 @@ public void SelectControllerIsCaseInsensitive(string controllerTypeName) var request = new HttpRequestMessage(); IHttpRouteData routeData = GetRouteData(); routeData.Values["controller"] = controllerTypeName; - routeData.Route.SetNameSpaces(new[] {expectedNamespace}); + routeData.Route.SetNameSpaces(new[] { expectedNamespace }); request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData; var selector = new DnnHttpControllerSelector(configuration); @@ -62,7 +63,7 @@ public void SelectControllerIgnoresControllersInUnexpectedNamespaces() var configuration = new HttpConfiguration(); var controllerTypeResolver = new Mock(); configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object); - + Type controllerType = GetMockControllerType(controllerName, unexpectedNamespace); controllerTypeResolver .Setup(c => c.GetControllerTypes(It.IsAny())) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpConfigurationExtensionTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpConfigurationExtensionTests.cs index 1df1592321a..0dabf013a95 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpConfigurationExtensionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpConfigurationExtensionTests.cs @@ -1,56 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using System.Web.Http; -using DotNetNuke.Web.Api; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System.Collections.Generic; + using System.Linq; + using System.Web.Http; + + using DotNetNuke.Web.Api; + using NUnit.Framework; + [TestFixture] public class HttpConfigurationExtensionTests { [Test] public void GetTabAndModuleInfoProvidersReturnsEmptyWhenNoProvidersAdded() { - //Arrange + // Arrange var configuration = new HttpConfiguration(); - //Act + // Act var providers = configuration.GetTabAndModuleInfoProviders(); - //Assert + // Assert CollectionAssert.IsEmpty(providers); } [Test] public void AddTabAndModuleInfoProviderWorksForFirstProvider() { - //Arrange + // Arrange var configuration = new HttpConfiguration(); - //Act + // Act configuration.AddTabAndModuleInfoProvider(new StandardTabAndModuleInfoProvider()); - //Assert + // Assert Assert.AreEqual(1, ((IEnumerable)configuration.Properties["TabAndModuleInfoProvider"]).Count()); } [Test] public void AddTabAndModuleInfoProviderWorksForManyProviders() { - //Arrange + // Arrange var configuration = new HttpConfiguration(); - //Act + // Act configuration.AddTabAndModuleInfoProvider(new StandardTabAndModuleInfoProvider()); configuration.AddTabAndModuleInfoProvider(new StandardTabAndModuleInfoProvider()); configuration.AddTabAndModuleInfoProvider(new StandardTabAndModuleInfoProvider()); - //Assert + // Assert Assert.AreEqual(3, ((IEnumerable)configuration.Properties["TabAndModuleInfoProvider"]).Count()); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpRequestMessageExtensionsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpRequestMessageExtensionsTests.cs index 886199449e1..382ceee0710 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpRequestMessageExtensionsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/HttpRequestMessageExtensionsTests.cs @@ -1,24 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Net.Http; -using System.Web.Http; -using System.Web.Http.Hosting; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Web.Api; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System.Net.Http; + using System.Web.Http; + using System.Web.Http.Hosting; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Web.Api; + using Moq; + using NUnit.Framework; + [TestFixture] public class HttpRequestMessageExtensionsTests { [Test] public void FindTabIdTriesAllProviders() { - //Arrange + // Arrange var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -28,17 +29,17 @@ public void FindTabIdTriesAllProviders() configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - //Act + // Act request.FindTabId(); - //Assert + // Assert provider.Verify(x => x.TryFindTabId(request, out i), Times.Exactly(2)); } [Test] public void FindTabIdStopCallingProvidersAfterOneSuccess() { - //Arrange + // Arrange var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -48,17 +49,17 @@ public void FindTabIdStopCallingProvidersAfterOneSuccess() configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - //Act + // Act request.FindTabId(); - //Assert + // Assert provider.Verify(x => x.TryFindTabId(request, out i), Times.Once()); } [Test] public void FindModuleIdTriesAllProviders() { - //Arrange + // Arrange var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -68,17 +69,17 @@ public void FindModuleIdTriesAllProviders() configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - //Act + // Act request.FindModuleId(); - //Assert + // Assert provider.Verify(x => x.TryFindModuleId(request, out i), Times.Exactly(2)); } [Test] public void FindModuleIdStopCallingProvidersAfterOneSuccess() { - //Arrange + // Arrange var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -88,17 +89,17 @@ public void FindModuleIdStopCallingProvidersAfterOneSuccess() configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - //Act + // Act request.FindModuleId(); - //Assert + // Assert provider.Verify(x => x.TryFindModuleId(request, out i), Times.Once()); } [Test] public void FindModuleInfoTriesAllProviders() { - //Arrange + // Arrange var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -108,17 +109,17 @@ public void FindModuleInfoTriesAllProviders() configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - //Act + // Act request.FindModuleInfo(); - //Assert + // Assert provider.Verify(x => x.TryFindModuleInfo(request, out moduleInfo), Times.Exactly(2)); } [Test] public void FindModuleInfoStopCallingProvidersAfterOneSuccess() { - //Arrange + // Arrange var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -128,10 +129,10 @@ public void FindModuleInfoStopCallingProvidersAfterOneSuccess() configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - //Act + // Act request.FindModuleInfo(); - //Assert + // Assert provider.Verify(x => x.TryFindModuleInfo(request, out moduleInfo), Times.Once()); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs index 59482e88d30..9c96ab95922 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs @@ -1,23 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.DependencyInjection; -using DotNetNuke.Web.Api.Internal; -using Microsoft.Extensions.DependencyInjection; -using NUnit.Framework; -using System; -using System.Linq; -using System.Web.Http.Dependencies; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api.Internals { + using System; + using System.Linq; + using System.Web.Http.Dependencies; + + using DotNetNuke.Services.DependencyInjection; + using DotNetNuke.Web.Api.Internal; + using Microsoft.Extensions.DependencyInjection; + using NUnit.Framework; + [TestFixture] public class DnnDependencyResolverTests { private IServiceProvider _serviceProvider; private IDependencyResolver _dependencyResolver; + private interface ITestService + { + } + [TestFixtureSetUp] public void FixtureSetUp() { @@ -25,38 +30,40 @@ public void FixtureSetUp() services.AddSingleton(sp => new FakeScopeAccessor(sp.CreateScope())); services.AddScoped(typeof(ITestService), typeof(TestService)); - _serviceProvider = services.BuildServiceProvider(); - _dependencyResolver = new DnnDependencyResolver(_serviceProvider); + this._serviceProvider = services.BuildServiceProvider(); + this._dependencyResolver = new DnnDependencyResolver(this._serviceProvider); } [TestFixtureTearDown] public void FixtureTearDown() { - _dependencyResolver = null; - - if (_serviceProvider is IDisposable disposable) - disposable.Dispose(); - - _serviceProvider = null; + this._dependencyResolver = null; + + if (this._serviceProvider is IDisposable disposable) + { + disposable.Dispose(); + } + + this._serviceProvider = null; } [Test] public void NotNull() { - Assert.NotNull(_dependencyResolver); + Assert.NotNull(this._dependencyResolver); } [Test] public void IsOfTypeDnnDependencyResolver() { - Assert.IsInstanceOf(_dependencyResolver); + Assert.IsInstanceOf(this._dependencyResolver); } [Test] public void GetTestService() { var expected = new TestService(); - var actual = _dependencyResolver.GetService(typeof(ITestService)); + var actual = this._dependencyResolver.GetService(typeof(ITestService)); Assert.NotNull(actual); Assert.AreEqual(expected.GetType(), actual.GetType()); @@ -66,7 +73,7 @@ public void GetTestService() public void GetTestServices() { var expected = new TestService(); - var actual = _dependencyResolver.GetServices(typeof(ITestService)).ToArray(); + var actual = this._dependencyResolver.GetServices(typeof(ITestService)).ToArray(); Assert.NotNull(actual); Assert.AreEqual(1, actual.Length); @@ -76,7 +83,7 @@ public void GetTestServices() [Test] public void BeginScope() { - var actual = _dependencyResolver.BeginScope(); + var actual = this._dependencyResolver.BeginScope(); Assert.NotNull(actual); Assert.IsInstanceOf(actual); @@ -85,7 +92,7 @@ public void BeginScope() [Test] public void BeginScope_GetService() { - var scope = _dependencyResolver.BeginScope(); + var scope = this._dependencyResolver.BeginScope(); var expected = new TestService(); var actual = scope.GetService(typeof(ITestService)); @@ -97,7 +104,7 @@ public void BeginScope_GetService() [Test] public void BeginScope_GetServices() { - var scope = _dependencyResolver.BeginScope(); + var scope = this._dependencyResolver.BeginScope(); var expected = new TestService(); var actual = scope.GetServices(typeof(ITestService)).ToArray(); @@ -106,9 +113,10 @@ public void BeginScope_GetServices() Assert.AreEqual(1, actual.Length); Assert.AreEqual(expected.GetType(), actual[0].GetType()); } - - private interface ITestService { } - private class TestService : ITestService { } + + private class TestService : ITestService + { + } private class FakeScopeAccessor : IScopeAccessor { @@ -121,7 +129,7 @@ public FakeScopeAccessor(IServiceScope fakeScope) public IServiceScope GetScope() { - return fakeScope; + return this.fakeScope; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs index 8cf3d9fcc31..c61b8e80007 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs @@ -1,35 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Security.Cryptography; -using System.Threading; -using Dnn.AuthServices.Jwt.Auth; -using Dnn.AuthServices.Jwt.Components.Entity; -using Dnn.AuthServices.Jwt.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.Web.ConfigSection; -using Moq; -using NUnit.Framework; -using System.Text; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Data; -using DotNetNuke.Security.Membership; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Collections.Generic; + using System.Data; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Security.Cryptography; + using System.Text; + using System.Threading; + + using Dnn.AuthServices.Jwt.Auth; + using Dnn.AuthServices.Jwt.Components.Entity; + using Dnn.AuthServices.Jwt.Data; + using DotNetNuke.Data; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + using DotNetNuke.Tests.Utilities.Mocks; + using DotNetNuke.Web.ConfigSection; + using Moq; + using NUnit.Framework; + [TestFixture] public class JwtAuthMessageHandlerTests - { - #region setting/mocked data and methods - + { + // { "type":"JWT","alg":"HS256"} . {"sub":"host","nbf":1,"exp":4102444799,"sid":"0123456789ABCDEF"} . (HS256_KEY="secret") + private const string ValidToken = + "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0.nfWCOVNk5M7L7EPDe3i3j4aAPRerbxgmcjOxaC-LWUQ"; + private Mock _mockDataProvider; private Mock _mockMembership; private Mock _mockDataService; @@ -37,43 +40,68 @@ public class JwtAuthMessageHandlerTests private Mock _mockUserController; private Mock _mockPortalController; - //{ "type":"JWT","alg":"HS256"} . {"sub":"host","nbf":1,"exp":4102444799,"sid":"0123456789ABCDEF"} . (HS256_KEY="secret") - private const string ValidToken = - "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0.nfWCOVNk5M7L7EPDe3i3j4aAPRerbxgmcjOxaC-LWUQ"; - public void SetupMockServices() { MockComponentProvider.CreateDataCacheProvider(); - _mockDataService = new Mock(); - _mockDataProvider = MockComponentProvider.CreateDataProvider(); - _mockPortalController = new Mock(); - _mockUserController = new Mock(); - _mockMembership = MockComponentProvider.CreateNew(); - - _mockDataProvider.Setup(d => d.GetProviderPath()).Returns(""); - _mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); - _mockDataProvider.Setup(d => d.GetUser(It.IsAny(), It.IsAny())).Returns(GetUser); - _mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(GetPortalGroups); - Entities.Portals.Data.DataService.RegisterInstance(_mockDataService.Object); - - _mockMembership.Setup(m => m.PasswordRetrievalEnabled).Returns(true); - _mockMembership.Setup(m => m.GetUser(It.IsAny(), It.IsAny())).Returns((int portalId, int userId) => GetUserByIdCallback(portalId, userId)); - - _mockJwtDataService = new Mock(); - _mockJwtDataService.Setup(x => x.GetTokenById(It.IsAny())).Returns((string sid) => GetPersistedToken(sid)); - DataService.RegisterInstance(_mockJwtDataService.Object); - - PortalController.SetTestableInstance(_mockPortalController.Object); - _mockPortalController.Setup(x => x.GetPortal(It.IsAny())).Returns( - new PortalInfo {PortalID = 0, PortalGroupID = -1, UserTabId = 55}); - _mockPortalController.Setup(x => x.GetPortalSettings(It.IsAny())).Returns((int portalId) => new Dictionary()); - _mockPortalController.Setup(x => x.GetCurrentPortalSettings()).Returns(() => new PortalSettings()); - - UserController.SetTestableInstance(_mockUserController.Object); - _mockUserController.Setup(x => x.GetUserById(It.IsAny(), It.IsAny())).Returns( + this._mockDataService = new Mock(); + this._mockDataProvider = MockComponentProvider.CreateDataProvider(); + this._mockPortalController = new Mock(); + this._mockUserController = new Mock(); + this._mockMembership = MockComponentProvider.CreateNew(); + + this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); + this._mockDataProvider.Setup(d => d.GetUser(It.IsAny(), It.IsAny())).Returns(GetUser); + this._mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(this.GetPortalGroups); + Entities.Portals.Data.DataService.RegisterInstance(this._mockDataService.Object); + + this._mockMembership.Setup(m => m.PasswordRetrievalEnabled).Returns(true); + this._mockMembership.Setup(m => m.GetUser(It.IsAny(), It.IsAny())).Returns((int portalId, int userId) => GetUserByIdCallback(portalId, userId)); + + this._mockJwtDataService = new Mock(); + this._mockJwtDataService.Setup(x => x.GetTokenById(It.IsAny())).Returns((string sid) => GetPersistedToken(sid)); + DataService.RegisterInstance(this._mockJwtDataService.Object); + + PortalController.SetTestableInstance(this._mockPortalController.Object); + this._mockPortalController.Setup(x => x.GetPortal(It.IsAny())).Returns( + new PortalInfo { PortalID = 0, PortalGroupID = -1, UserTabId = 55 }); + this._mockPortalController.Setup(x => x.GetPortalSettings(It.IsAny())).Returns((int portalId) => new Dictionary()); + this._mockPortalController.Setup(x => x.GetCurrentPortalSettings()).Returns(() => new PortalSettings()); + + UserController.SetTestableInstance(this._mockUserController.Object); + this._mockUserController.Setup(x => x.GetUserById(It.IsAny(), It.IsAny())).Returns( (int portalId, int userId) => GetUserByIdCallback(portalId, userId)); - //_mockUserController.Setup(x => x.ValidateUser(It.IsAny(), It.IsAny(), It.IsAny())).Returns(UserValidStatus.VALID); + + // _mockUserController.Setup(x => x.ValidateUser(It.IsAny(), It.IsAny(), It.IsAny())).Returns(UserValidStatus.VALID); + } + + [Test] + public void ReturnsResponseAsReceived() + { + // Arrange + var response = new HttpResponseMessage(HttpStatusCode.OK) { RequestMessage = new HttpRequestMessage() }; + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response2 = handler.OnOutboundResponse(response, CancellationToken.None); + + // Assert + Assert.AreEqual(response, response2); + } + + [Test] + public void MissingAuthoizationHeaderReturnsNullResponse() + { + // Arrange + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response = handler.OnInboundRequest(request, CancellationToken.None); + + // Assert + Assert.IsNull(response); } private static IDataReader GetUser() @@ -108,24 +136,6 @@ private static IDataReader GetUser() return table.CreateDataReader(); } - private IDataReader GetPortalGroups() - { - var table = new DataTable("ModuleDefinitions"); - var pkId = table.Columns.Add("PortalGroupID", typeof(int)); - table.Columns.Add("MasterPortalID", typeof(int)); - table.Columns.Add("PortalGroupName", typeof(string)); - table.Columns.Add("PortalGroupDescription", typeof(string)); - table.Columns.Add("AuthenticationDomain", typeof(string)); - table.Columns.Add("CreatedByUserID", typeof(int)); - table.Columns.Add("CreatedOnDate", typeof(DateTime)); - table.Columns.Add("LastModifiedByUserID", typeof(int)); - table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - table.PrimaryKey = new[] { pkId }; - - table.Rows.Add(0, 0, "test", "descr", "domain", -1, DateTime.Now, -1, DateTime.Now); - return table.CreateDataReader(); - } - private static IDataReader GetPortalsCallBack(string culture) { return GetPortalCallBack(0, culture); @@ -146,7 +156,7 @@ private static IDataReader GetPortalCallBack(int portalId, string culture) "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", - "CultureCode" + "CultureCode", }; foreach (var col in cols) @@ -165,9 +175,28 @@ private static IDataReader GetPortalCallBack(int portalId, string culture) return table.CreateDataReader(); } + private IDataReader GetPortalGroups() + { + var table = new DataTable("ModuleDefinitions"); + var pkId = table.Columns.Add("PortalGroupID", typeof(int)); + table.Columns.Add("MasterPortalID", typeof(int)); + table.Columns.Add("PortalGroupName", typeof(string)); + table.Columns.Add("PortalGroupDescription", typeof(string)); + table.Columns.Add("AuthenticationDomain", typeof(string)); + table.Columns.Add("CreatedByUserID", typeof(int)); + table.Columns.Add("CreatedOnDate", typeof(DateTime)); + table.Columns.Add("LastModifiedByUserID", typeof(int)); + table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + table.PrimaryKey = new[] { pkId }; + + table.Rows.Add(0, 0, "test", "descr", "domain", -1, DateTime.Now, -1, DateTime.Now); + return table.CreateDataReader(); + } + private static PersistedToken GetPersistedToken(string sessionId) { - if ("0123456789ABCDEF".Equals(sessionId)) + if ("0123456789ABCDEF".Equals(sessionId)) + { return new PersistedToken { TokenId = sessionId, @@ -176,8 +205,9 @@ private static PersistedToken GetPersistedToken(string sessionId) UserId = 1, TokenHash = GetHashedStr(ValidToken), RenewalHash = "renewal-hash", - }; - + }; + } + return null; } @@ -188,139 +218,106 @@ private static UserInfo GetUserByIdCallback(int portalId, int userId) switch (userId) { case 1: - return new UserInfo {UserID = userId, Username = "host", DisplayName = "Host User"}; + return new UserInfo { UserID = userId, Username = "host", DisplayName = "Host User" }; case 2: - return new UserInfo {UserID = userId, Username = "admin", DisplayName = "Admin User"}; + return new UserInfo { UserID = userId, Username = "admin", DisplayName = "Admin User" }; case 3: - return new UserInfo {UserID = userId, Username = "reguser", DisplayName = "Registered User"}; + return new UserInfo { UserID = userId, Username = "reguser", DisplayName = "Registered User" }; } } return null; - } - - #endregion - - [Test] - public void ReturnsResponseAsReceived() - { - //Arrange - var response = new HttpResponseMessage(HttpStatusCode.OK) {RequestMessage = new HttpRequestMessage()}; - - //Act - var handler = new JwtAuthMessageHandler(true, false); - var response2 = handler.OnOutboundResponse(response, new CancellationToken()); - - //Assert - Assert.AreEqual(response, response2); - } - - [Test] - public void MissingAuthoizationHeaderReturnsNullResponse() - { - //Arrange - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); - - //Act - var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, new CancellationToken()); - - //Assert - Assert.IsNull(response); - } + } [Test] public void WrongAuthoizationSchemeReturnsNullResponse() { - //Arrange + // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); request.Headers.Authorization = AuthenticationHeaderValue.Parse("Basic "); - //Act + // Act var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, new CancellationToken()); + var response = handler.OnInboundRequest(request, CancellationToken.None); - //Assert + // Assert Assert.IsNull(response); } [Test] public void MissingAuthoizationTokenReturnsNullResponse() { - //Arrange + // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); request.Headers.Authorization = AuthenticationHeaderValue.Parse("Bearer "); - //Act + // Act var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, new CancellationToken()); + var response = handler.OnInboundRequest(request, CancellationToken.None); - //Assert + // Assert Assert.IsNull(response); } [Test] public void AuthoizationTokenWithMissingComponentsReturnsNullResponse() { - //Arrange + // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); request.Headers.Authorization = AuthenticationHeaderValue.Parse( "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0"); - //Act + // Act var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, new CancellationToken()); + var response = handler.OnInboundRequest(request, CancellationToken.None); - //Assert + // Assert Assert.IsNull(response); } [Test] public void AuthoizationTokenWithWrongSchemeTypeReturnsNullResponse() { - //Arrange + // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); request.Headers.Authorization = AuthenticationHeaderValue.Parse( "Bearer eyJ0eXBlIjoieHh4IiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0.nfWCOVNk5M7L7EPDe3i3j4aAPRerbxgmcjOxaC-LWUQ"); - //Act + // Act var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, new CancellationToken()); + var response = handler.OnInboundRequest(request, CancellationToken.None); - //Assert + // Assert Assert.IsNull(response); } [Test] public void AuthoizationTokenWithoorResponse() { - //Arrange + // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); request.Headers.Authorization = AuthenticationHeaderValue.Parse("Bearer " + ValidToken); - //Act - SetupMockServices(); + // Act + this.SetupMockServices(); var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, new CancellationToken()); + var response = handler.OnInboundRequest(request, CancellationToken.None); - //Assert + // Assert Assert.IsNull(response); - } - - //todo unit test actual authentication code - // very hard to unit test inbound authentication code as it dips into untestable bits of - // UserController, etc. Need to write controllers with interfaces and ServiceLocator<>. - - #region helpers - - //private static string DecodeBase64(string b64Str) - //{ - // // fix Base64 string padding - // var mod = b64Str.Length % 4; - // if (mod != 0) b64Str += new string('=', 4 - mod); - // return Encoding.UTF8.GetString(Convert.FromBase64String(b64Str)); - //} - + } + + // todo unit test actual authentication code + // very hard to unit test inbound authentication code as it dips into untestable bits of + // UserController, etc. Need to write controllers with interfaces and ServiceLocator<>. + + // private static string DecodeBase64(string b64Str) + // { + // // fix Base64 string padding + // var mod = b64Str.Length % 4; + // if (mod != 0) b64Str += new string('=', 4 - mod); + // return Encoding.UTF8.GetString(Convert.FromBase64String(b64Str)); + // } private static string EncodeBase64(byte[] data) { return Convert.ToBase64String(data).TrimEnd('='); @@ -332,8 +329,6 @@ private static string GetHashedStr(string data) { return EncodeBase64(hasher.ComputeHash(Encoding.UTF8.GetBytes(data))); } - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs index c0737a786ae..2498ae861f2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Abstractions; -using DotNetNuke.Common; -using DotNetNuke.Common.Internal; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Web.Api; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Web.Api; + using Moq; + using NUnit.Framework; + [TestFixture] public class PortalAliasRouteManagerTests { @@ -35,8 +36,7 @@ public void TearDown() PortalAliasController.ClearInstance(); TestableGlobals.ClearInstance(); } - - + [Test] [TestCase("mfn", "url", 0, "API/mfn/url")] [TestCase("mfn", "url", 1, "{prefix0}/API/mfn/url")] @@ -44,13 +44,12 @@ public void TearDown() [TestCase("fee/foo", "{contoller}/{action}/{id}", 4, "{prefix0}/{prefix1}/{prefix2}/{prefix3}/API/fee/foo/{contoller}/{action}/{id}")] public void GetRouteUrl(string moduleFolderName, string url, int count, string expected) { - //Arrange - - - //Act + // Arrange + + // Act string result = new PortalAliasRouteManager().GetRouteUrl(moduleFolderName, url, count); - //Assert + // Assert Assert.AreEqual(expected, result); } @@ -59,81 +58,84 @@ public void GetRouteUrl(string moduleFolderName, string url, int count, string e [TestCase("name", -1, typeof(ArgumentOutOfRangeException), "count should be >= 0")] public void GetRouteUrlThrowsOnBadArguments(string moduleFolderName, int count, Type expectedException, string message) { - //Arrange - - - //Act + // Arrange + + // Act try { new PortalAliasRouteManager().GetRouteUrl(moduleFolderName, "url", count); } - catch(Exception e) + catch (Exception e) { - if(e.GetType() == expectedException) + if (e.GetType() == expectedException) { Assert.Pass(); return; } } - //Assert + // Assert Assert.Fail(message); } [Test] public void ParentPortalOnVirtualDirReturnsAnEmptyPrefix() { - //Arrange + // Arrange var mockPortalController = new Mock(); - var portals = new ArrayList {new PortalInfo {PortalID = 1}}; + var portals = new ArrayList { new PortalInfo { PortalID = 1 } }; mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalAliasController = new Mock(); mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] - {new PortalAliasInfo {HTTPAlias = "valid.lvh.me/vdir"}}); + { + new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" } + }); PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); var mockGlobals = new Mock(); mockGlobals.Setup(x => x.ApplicationPath).Returns("/vdir"); TestableGlobals.SetTestableInstance(mockGlobals.Object); - //Act + // Act List prefixes = new PortalAliasRouteManager().GetRoutePrefixCounts().ToList(); - //Assert - CollectionAssert.AreEquivalent(new[] {0}, prefixes); + // Assert + CollectionAssert.AreEquivalent(new[] { 0 }, prefixes); } [Test] public void SingleParentPortalReturnsAnEmptyPrefix() { - //Arrange + // Arrange var mockPortalController = new Mock(); - var portals = new ArrayList {new PortalInfo {PortalID = 1}}; + var portals = new ArrayList { new PortalInfo { PortalID = 1 } }; mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalAliasController = new Mock(); mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] - {new PortalAliasInfo {HTTPAlias = "valid.lvh.me"}}); + { + new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } + }); PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); var mockGlobals = new Mock(); - mockGlobals.Setup(x => x.ApplicationPath).Returns(""); + mockGlobals.Setup(x => x.ApplicationPath).Returns(string.Empty); TestableGlobals.SetTestableInstance(mockGlobals.Object); - //Act + // Act List prefixes = new PortalAliasRouteManager().GetRoutePrefixCounts().ToList(); - //Assert - CollectionAssert.AreEquivalent(new[] {0}, prefixes); + // Assert + CollectionAssert.AreEquivalent(new[] { 0 }, prefixes); } [Test] public void PrefixCountsAreCached() { - //Arrange + // Arrange var mockPortalController = new Mock(); var portals = new ArrayList { new PortalInfo { PortalID = 1 } }; mockPortalController.Setup(x => x.GetPortals()).Returns(portals); @@ -144,22 +146,22 @@ public void PrefixCountsAreCached() PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); var mockGlobals = new Mock(); - mockGlobals.Setup(x => x.ApplicationPath).Returns(""); + mockGlobals.Setup(x => x.ApplicationPath).Returns(string.Empty); TestableGlobals.SetTestableInstance(mockGlobals.Object); - //Act + // Act var parm = new PortalAliasRouteManager(); parm.GetRoutePrefixCounts(); parm.GetRoutePrefixCounts(); - //Assert + // Assert mockPortalController.Verify(x => x.GetPortals(), Times.Once()); } [Test] public void PrefixCountsCacheCanBeCleared() { - //Arrange + // Arrange var mockPortalController = new Mock(); var portals = new ArrayList { new PortalInfo { PortalID = 1 } }; mockPortalController.Setup(x => x.GetPortals()).Returns(portals); @@ -170,33 +172,33 @@ public void PrefixCountsCacheCanBeCleared() PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); var mockGlobals = new Mock(); - mockGlobals.Setup(x => x.ApplicationPath).Returns(""); + mockGlobals.Setup(x => x.ApplicationPath).Returns(string.Empty); TestableGlobals.SetTestableInstance(mockGlobals.Object); - //Act + // Act var parm = new PortalAliasRouteManager(); parm.GetRoutePrefixCounts(); parm.ClearCachedData(); parm.GetRoutePrefixCounts(); - //Assert + // Assert mockPortalController.Verify(x => x.GetPortals(), Times.Exactly(2)); } [Test] public void VirtralDirWithChildPortalHasABlankAndASinglePrefix() { - //Arrange + // Arrange var mockPortalController = new Mock(); - var portals = new ArrayList {new PortalInfo {PortalID = 1}}; + var portals = new ArrayList { new PortalInfo { PortalID = 1 } }; mockPortalController.Setup(x => x.GetPortals()).Returns(portals); PortalController.SetTestableInstance(mockPortalController.Object); var mockPortalAliasController = new Mock(); mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] { - new PortalAliasInfo {HTTPAlias = "valid.lvh.me/vdir"}, - new PortalAliasInfo {HTTPAlias = "valid.lvh.me/vdir/child"} + new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" }, + new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir/child" }, }); PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); @@ -204,11 +206,11 @@ public void VirtralDirWithChildPortalHasABlankAndASinglePrefix() mockGlobals.Setup(x => x.ApplicationPath).Returns("/vdir"); TestableGlobals.SetTestableInstance(mockGlobals.Object); - //Act + // Act List prefixes = new PortalAliasRouteManager().GetRoutePrefixCounts().ToList(); - //Assert - CollectionAssert.AreEqual(new[] {1, 0}, prefixes); + // Assert + CollectionAssert.AreEqual(new[] { 1, 0 }, prefixes); } [Test] @@ -217,13 +219,12 @@ public void VirtralDirWithChildPortalHasABlankAndASinglePrefix() [TestCase("first", "second", 99, "first-second-99")] public void GetRouteNameHashesNameInCorrectFormat(string moduleFolderName, string routeName, int count, string expected) { - //Arrange - - - //Act + // Arrange + + // Act var result = new PortalAliasRouteManager().GetRouteName(moduleFolderName, routeName, count); - //Assert + // Assert Assert.AreEqual(expected, result); } @@ -233,13 +234,12 @@ public void GetRouteNameHashesNameInCorrectFormat(string moduleFolderName, strin [TestCase("first", "second", "ce.lvh.me/child1/child2/child3/child4/child5", "first-second-5")] public void GetRouteNameWithPortalAliasInfoHashesNameInCorrectFormat(string moduleFolderName, string routeName, string httpAlias, string expected) { - //Arrange - - - //Act - var result = new PortalAliasRouteManager().GetRouteName(moduleFolderName, routeName, new PortalAliasInfo {HTTPAlias = httpAlias}); + // Arrange + + // Act + var result = new PortalAliasRouteManager().GetRouteName(moduleFolderName, routeName, new PortalAliasInfo { HTTPAlias = httpAlias }); - //Assert + // Assert Assert.AreEqual(expected, result); } @@ -249,68 +249,65 @@ public void GetRouteNameWithPortalAliasInfoHashesNameInCorrectFormat(string modu [ExpectedException(typeof(ArgumentException))] public void GetRouteNameThrowsOnEmptyModuleFolderName(string moduleFolderName) { - //Arrange - + // Arrange + + // Act + new PortalAliasRouteManager().GetRouteName(moduleFolderName, string.Empty, 0); - //Act - new PortalAliasRouteManager().GetRouteName(moduleFolderName, "", 0); - - //Assert + // Assert } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void GetRouteNameThrowsOnCountLessThan0() { - //Arrange - - - //Act - new PortalAliasRouteManager().GetRouteName("foo", "", -1); + // Arrange + + // Act + new PortalAliasRouteManager().GetRouteName("foo", string.Empty, -1); - //Assert + // Assert } [Test] - public void GetAllRouteValuesWorksWithNullRouteValues () + public void GetAllRouteValuesWorksWithNullRouteValues() { - //Arrange - - - //Act - new PortalAliasRouteManager().GetAllRouteValues(new PortalAliasInfo {HTTPAlias = ""}, null); + // Arrange + + // Act + new PortalAliasRouteManager().GetAllRouteValues(new PortalAliasInfo { HTTPAlias = string.Empty }, null); - //Assert + // Assert Assert.Pass(); } [Test] public void GetAllRouteValuesPreservesPassedInRouteValues() { - //Arrange - - - //Act - var result = new PortalAliasRouteManager().GetAllRouteValues(new PortalAliasInfo {HTTPAlias = ""}, - new {value1 = 1, value2 = 2}); - - //Assert - var expected = new Dictionary {{"value1", 1}, {"value2", 2}}; + // Arrange + + // Act + var result = new PortalAliasRouteManager().GetAllRouteValues( + new PortalAliasInfo { HTTPAlias = string.Empty }, + new { value1 = 1, value2 = 2 }); + + // Assert + var expected = new Dictionary { { "value1", 1 }, { "value2", 2 } }; CollectionAssert.AreEquivalent(expected, result); } [Test] public void GetAllRouteValuesExtractsChildPortalParams() { - //Arrange - - - //Act + // Arrange + + // Act var result = - new PortalAliasRouteManager().GetAllRouteValues(new PortalAliasInfo {HTTPAlias = "ce.lvh.me/child"}, - null); + new PortalAliasRouteManager().GetAllRouteValues( + new PortalAliasInfo { HTTPAlias = "ce.lvh.me/child" }, + null); - //Assert + // Assert var expected = new Dictionary { { "prefix0", "child" } }; CollectionAssert.AreEquivalent(expected, result); } @@ -318,16 +315,16 @@ public void GetAllRouteValuesExtractsChildPortalParams() [Test] public void GetAllRouteValuesExtractsManyChildPortalParamsAndPreservesRouteValues() { - //Arrange - - - //Act + // Arrange + + // Act var result = - new PortalAliasRouteManager().GetAllRouteValues(new PortalAliasInfo { HTTPAlias = "ce.lvh.me/child0/child1/child2/child3" }, - new {value1 = 1, value2 = 2}); + new PortalAliasRouteManager().GetAllRouteValues( + new PortalAliasInfo { HTTPAlias = "ce.lvh.me/child0/child1/child2/child3" }, + new { value1 = 1, value2 = 2 }); - //Assert - var expected = new Dictionary { { "prefix0", "child0" }, { "prefix1", "child1" }, { "prefix2", "child2" }, { "prefix3", "child3" }, { "value1", 1}, {"value2", 2} }; + // Assert + var expected = new Dictionary { { "prefix0", "child0" }, { "prefix1", "child1" }, { "prefix2", "child2" }, { "prefix3", "child3" }, { "value1", 1 }, { "value2", 2 } }; CollectionAssert.AreEquivalent(expected, result); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs index ca549ddccf8..b36709b0bc5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs @@ -1,100 +1,71 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Diagnostics; - -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { - //various ServiceRouteMappers that will be reflected upon by the tests - + using System; + using System.Diagnostics; + + using DotNetNuke.Web.Api; + + // various ServiceRouteMappers that will be reflected upon by the tests public class ReflectedServiceRouteMappers - { - #region Nested type: EmbeddedServiceRouteMapper - + { public class EmbeddedServiceRouteMapper : IServiceRouteMapper - { - #region IServiceRouteMapper Members - + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } - - #endregion - } - - #endregion + } + } } public class ExceptionOnCreateInstanceServiceRouteMapper : IServiceRouteMapper { public ExceptionOnCreateInstanceServiceRouteMapper(int i) { - //no default constructor prevents Activator.CreateInstance from working + // no default constructor prevents Activator.CreateInstance from working Debug.WriteLine(i); - } - - #region IServiceRouteMapper Members - + } + public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } - - #endregion + } } public class ExceptionOnRegisterServiceRouteMapper : IServiceRouteMapper - { - #region IServiceRouteMapper Members - + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } - - #endregion + } } public class FakeServiceRouteMapper : IServiceRouteMapper { - public static int RegistrationCalls { get; set; } - - #region IServiceRouteMapper Members - + public static int RegistrationCalls { get; set; } + public void RegisterRoutes(IMapRoute mapRouteManager) { RegistrationCalls++; - } - - #endregion + } } public abstract class AbstractServiceRouteMapper : IServiceRouteMapper - { - #region IServiceRouteMapper Members - + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } - - #endregion + } } internal class InternalServiceRouteMapper : IServiceRouteMapper - { - #region IServiceRouteMapper Members - + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs index 1ec74690dbe..0c4c27776b2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs @@ -1,31 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Web.Routing; -using DotNetNuke.Abstractions; -using DotNetNuke.Common; -using DotNetNuke.DependencyInjection; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework.Internal.Reflection; -using DotNetNuke.Framework.Reflections; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using NUnit.Framework; -using ServicesRoutingManager = DotNetNuke.Web.Api.Internal.ServicesRoutingManager; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Web.Routing; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.DependencyInjection; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework.Internal.Reflection; + using DotNetNuke.Framework.Reflections; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using NUnit.Framework; + + using ServicesRoutingManager = DotNetNuke.Web.Api.Internal.ServicesRoutingManager; + [TestFixture] public class ServiceRoutingManagerTests { // ReSharper disable UnusedMember.Local private readonly List _emptyStringArrays = new List - {null, new string[0], new[] {""}, new string[] {null}}; + { null, new string[0], new[] { string.Empty }, new string[] { null } }; + // ReSharper restore UnusedMember.Local private Mock _mockPortalController; private IPortalController _portalController; @@ -35,9 +38,9 @@ public void Setup() { FakeServiceRouteMapper.RegistrationCalls = 0; - _mockPortalController = new Mock(); - _portalController = _mockPortalController.Object; - PortalController.SetTestableInstance(_portalController); + this._mockPortalController = new Mock(); + this._portalController = this._mockPortalController.Object; + PortalController.SetTestableInstance(this._portalController); var navigationManagerMock = new Mock(); var services = new ServiceCollection(); @@ -50,9 +53,11 @@ public void TearDown() { PortalController.ClearInstance(); - if (Globals.DependencyProvider is IDisposable disposable) - disposable.Dispose(); - + if (Globals.DependencyProvider is IDisposable disposable) + { + disposable.Dispose(); + } + Globals.DependencyProvider = null; } @@ -61,30 +66,28 @@ public void LocatesAllServiceRouteMappers() { var assemblyLocator = new Mock(); - //including the assembly with object ensures that the assignabliity is done correctly + // including the assembly with object ensures that the assignabliity is done correctly var assembliesToReflect = new IAssembly[2]; - assembliesToReflect[0] = new AssemblyWrapper(GetType().Assembly); - assembliesToReflect[1] = new AssemblyWrapper(typeof (Object).Assembly); + assembliesToReflect[0] = new AssemblyWrapper(this.GetType().Assembly); + assembliesToReflect[1] = new AssemblyWrapper(typeof(object).Assembly); assemblyLocator.Setup(x => x.Assemblies).Returns(assembliesToReflect); - var locator = new TypeLocator {AssemblyLocator = assemblyLocator.Object}; + var locator = new TypeLocator { AssemblyLocator = assemblyLocator.Object }; List types = locator.GetAllMatchingTypes(ServicesRoutingManager.IsValidServiceRouteMapper).ToList(); - //if new ServiceRouteMapper classes are added to the assembly they willl likely need to be added here + // if new ServiceRouteMapper classes are added to the assembly they willl likely need to be added here CollectionAssert.AreEquivalent( new[] { - typeof (FakeServiceRouteMapper), - typeof (ReflectedServiceRouteMappers.EmbeddedServiceRouteMapper), - typeof (ExceptionOnCreateInstanceServiceRouteMapper), - typeof (ExceptionOnRegisterServiceRouteMapper) + typeof(FakeServiceRouteMapper), + typeof(ReflectedServiceRouteMappers.EmbeddedServiceRouteMapper), + typeof(ExceptionOnCreateInstanceServiceRouteMapper), + typeof(ExceptionOnRegisterServiceRouteMapper), }, types); } - - - + [Test] public void NameSpaceRequiredOnMapRouteCalls([ValueSource("_emptyStringArrays")] string[] namespaces) { @@ -100,14 +103,14 @@ public void RegisterRoutesIsCalledOnAllServiceRouteMappersEvenWhenSomeThrowExcep var assembly = new Mock(); assembly.Setup(x => x.GetTypes()).Returns(new[] { - typeof (ExceptionOnRegisterServiceRouteMapper), - typeof (ExceptionOnCreateInstanceServiceRouteMapper), - typeof (FakeServiceRouteMapper) + typeof(ExceptionOnRegisterServiceRouteMapper), + typeof(ExceptionOnCreateInstanceServiceRouteMapper), + typeof(FakeServiceRouteMapper), }); var al = new Mock(); - al.Setup(x => x.Assemblies).Returns(new[] {assembly.Object}); - var tl = new TypeLocator {AssemblyLocator = al.Object}; - var srm = new ServicesRoutingManager(new RouteCollection()) {TypeLocator = tl}; + al.Setup(x => x.Assemblies).Returns(new[] { assembly.Object }); + var tl = new TypeLocator { AssemblyLocator = al.Object }; + var srm = new ServicesRoutingManager(new RouteCollection()) { TypeLocator = tl }; srm.RegisterRoutes(); @@ -119,11 +122,11 @@ public void RegisterRoutesIsCalledOnServiceRouteMappers() { FakeServiceRouteMapper.RegistrationCalls = 0; var assembly = new Mock(); - assembly.Setup(x => x.GetTypes()).Returns(new[] {typeof (FakeServiceRouteMapper)}); + assembly.Setup(x => x.GetTypes()).Returns(new[] { typeof(FakeServiceRouteMapper) }); var al = new Mock(); - al.Setup(x => x.Assemblies).Returns(new[] {assembly.Object}); - var tl = new TypeLocator {AssemblyLocator = al.Object}; - var srm = new ServicesRoutingManager(new RouteCollection()) {TypeLocator = tl}; + al.Setup(x => x.Assemblies).Returns(new[] { assembly.Object }); + var tl = new TypeLocator { AssemblyLocator = al.Object }; + var srm = new ServicesRoutingManager(new RouteCollection()) { TypeLocator = tl }; srm.RegisterRoutes(); @@ -143,22 +146,22 @@ public void UniqueNameRequiredOnMapRouteCalls(string uniqueName) [Test] public void UrlCanStartWithSlash() { - //Arrange - _mockPortalController.Setup(x => x.GetPortals()).Returns(new ArrayList()); - - //Act + // Arrange + this._mockPortalController.Setup(x => x.GetPortals()).Returns(new ArrayList()); + + // Act var srm = new ServicesRoutingManager(new RouteCollection()); - //Assert + // Assert Assert.DoesNotThrow(() => srm.MapHttpRoute("name", "default", "/url", null, new[] { "foo" })); } [Test] public void NameIsInsertedInRouteDataTokens() { - //Arrange + // Arrange var portalInfo = new ArrayList { new PortalInfo { PortalID = 0 } }; - _mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); + this._mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); var mockPac = new Mock(); mockPac.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); PortalAliasController.SetTestableInstance(mockPac.Object); @@ -166,20 +169,20 @@ public void NameIsInsertedInRouteDataTokens() var routeCollection = new RouteCollection(); var srm = new ServicesRoutingManager(routeCollection); - //Act + // Act srm.MapHttpRoute("folder", "default", "url", new[] { "foo" }); - //Assert - var route = (Route) routeCollection[0]; + // Assert + var route = (Route)routeCollection[0]; Assert.AreEqual("folder-default-0", route.DataTokens["Name"]); } [Test] public void TwoRoutesOnTheSameFolderHaveSimilarNames() { - //Arrange + // Arrange var portalInfo = new ArrayList { new PortalInfo { PortalID = 0 } }; - _mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); + this._mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); var mockPac = new Mock(); mockPac.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); PortalAliasController.SetTestableInstance(mockPac.Object); @@ -187,11 +190,11 @@ public void TwoRoutesOnTheSameFolderHaveSimilarNames() var routeCollection = new RouteCollection(); var srm = new ServicesRoutingManager(routeCollection); - //Act + // Act srm.MapHttpRoute("folder", "default", "url", new[] { "foo" }); srm.MapHttpRoute("folder", "another", "alt/url", new[] { "foo" }); - //Assert + // Assert var route = (Route)routeCollection[0]; Assert.AreEqual("folder-default-0", route.DataTokens["Name"]); route = (Route)routeCollection[1]; @@ -201,9 +204,9 @@ public void TwoRoutesOnTheSameFolderHaveSimilarNames() [Test] public void RoutesShouldHaveBackwardCompability() { - //Arrange + // Arrange var portalInfo = new ArrayList { new PortalInfo { PortalID = 0 } }; - _mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); + this._mockPortalController.Setup(x => x.GetPortals()).Returns(portalInfo); var mockPac = new Mock(); mockPac.Setup(x => x.GetPortalAliasesByPortalId(0)).Returns(new[] { new PortalAliasInfo { HTTPAlias = "www.foo.com" } }); PortalAliasController.SetTestableInstance(mockPac.Object); @@ -211,10 +214,10 @@ public void RoutesShouldHaveBackwardCompability() var routeCollection = new RouteCollection(); var srm = new ServicesRoutingManager(routeCollection); - //Act + // Act srm.MapHttpRoute("folder", "default", "url", new[] { "foo" }); - //Assert + // Assert var route = (Route)routeCollection[0]; Assert.AreEqual("folder-default-0", route.DataTokens["Name"]); route = (Route)routeCollection[1]; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs index 6f2c7b3eaf9..90df3a9b156 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs @@ -1,26 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Net.Http; -using System.Web; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.Web.Api; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Net.Http; + using System.Web; + + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Tests.Utilities.Mocks; + using DotNetNuke.Web.Api; + using Moq; + using NUnit.Framework; + [TestFixture] public class StandardTabAndModuleInfoProviderTests { + private const int ValidPortalId = 0; + private const int ValidTabModuleId = 999; + private Mock _mockModuleController; private IModuleController _moduleController; private Mock _mockTabController; @@ -31,9 +35,6 @@ public class StandardTabAndModuleInfoProviderTests private ITabModulesController _tabModuleController; private TabInfo _tabInfo; private ModuleInfo _moduleInfo; - - private const int ValidPortalId = 0; - private const int ValidTabModuleId = 999; private const int ValidModuleId = 456; private const int ValidTabId = 46; @@ -44,29 +45,72 @@ public class StandardTabAndModuleInfoProviderTests public void Setup() { MockComponentProvider.CreateDataCacheProvider(); - _mockDataProvider = MockComponentProvider.CreateDataProvider(); - _mockDataProvider.Setup(d => d.GetProviderPath()).Returns(""); - _mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); + this._mockDataProvider = MockComponentProvider.CreateDataProvider(); + this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); - RegisterMock(ModuleController.SetTestableInstance, out _mockModuleController, out _moduleController); - RegisterMock(TabController.SetTestableInstance, out _mockTabController, out _tabController); - RegisterMock(TabModulesController.SetTestableInstance, out _mockTabModuleController, out _tabModuleController); + this.RegisterMock(ModuleController.SetTestableInstance, out this._mockModuleController, out this._moduleController); + this.RegisterMock(TabController.SetTestableInstance, out this._mockTabController, out this._tabController); + this.RegisterMock(TabModulesController.SetTestableInstance, out this._mockTabModuleController, out this._tabModuleController); - _tabInfo = new TabInfo { TabID = ValidTabId }; - _moduleInfo = new ModuleInfo + this._tabInfo = new TabInfo { TabID = ValidTabId }; + this._moduleInfo = new ModuleInfo { - TabModuleID = ValidTabModuleId, TabID = ValidTabId, ModuleID = ValidModuleId, PortalID = ValidPortalId + TabModuleID = ValidTabModuleId, + TabID = ValidTabId, + ModuleID = ValidModuleId, + PortalID = ValidPortalId, }; - _mockTabController.Setup(x => x.GetTab(ValidTabId, ValidPortalId)).Returns(_tabInfo); - _mockModuleController.Setup(x => x.GetModule(ValidModuleId, ValidTabId, false)).Returns(_moduleInfo); - _mockModuleController.Setup(x => x.GetTabModule(ValidTabModuleId)).Returns(_moduleInfo); - _mockTabModuleController.Setup(x => x.GetTabModuleIdsBySetting(MonikerSettingName, MonikerSettingValue)).Returns( + this._mockTabController.Setup(x => x.GetTab(ValidTabId, ValidPortalId)).Returns(this._tabInfo); + this._mockModuleController.Setup(x => x.GetModule(ValidModuleId, ValidTabId, false)).Returns(this._moduleInfo); + this._mockModuleController.Setup(x => x.GetTabModule(ValidTabModuleId)).Returns(this._moduleInfo); + this._mockTabModuleController.Setup(x => x.GetTabModuleIdsBySetting(MonikerSettingName, MonikerSettingValue)).Returns( new List { ValidTabModuleId }); - _mockTabModuleController.Setup(x => x.GetTabModuleSettingsByName(MonikerSettingName)).Returns( + this._mockTabModuleController.Setup(x => x.GetTabModuleSettingsByName(MonikerSettingName)).Returns( new Dictionary { { ValidTabModuleId, MonikerSettingValue } }); } + [TearDown] + public void TearDown() + { + ModuleController.ClearInstance(); + TabController.ClearInstance(); + } + + [Test] + public void ValidTabAndModuleIdLoadsActiveModule() + { + // Arrange + var request = new HttpRequestMessage(); + request.Headers.Add("tabid", ValidTabId.ToString(CultureInfo.InvariantCulture)); + request.Headers.Add("moduleid", ValidModuleId.ToString(CultureInfo.InvariantCulture)); + + // Act + ModuleInfo returnedModuleInfo; + var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); + + // Assert + Assert.IsTrue(result); + Assert.AreSame(this._moduleInfo, returnedModuleInfo); + } + + [Test] + public void ExistingMonikerValueInHeaderShouldFindTheCorrectModuleInfo() + { + // Arrange + var request = new HttpRequestMessage(); + request.Headers.Add("X-DNN-MONIKER", MonikerSettingValue); + + // Act + ModuleInfo returnedModuleInfo; + var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); + + // Assert + Assert.IsTrue(result); + Assert.AreSame(this._moduleInfo, returnedModuleInfo); + } + private static IDataReader GetPortalsCallBack(string culture) { return GetPortalCallBack(0, culture); @@ -87,7 +131,7 @@ private static IDataReader GetPortalCallBack(int portalId, string culture) "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", - "CultureCode" + "CultureCode", }; foreach (var col in cols) @@ -106,82 +150,43 @@ private static IDataReader GetPortalCallBack(int portalId, string culture) return table.CreateDataReader(); } - [TearDown] - public void TearDown() - { - ModuleController.ClearInstance(); - TabController.ClearInstance(); - } - - private void RegisterMock(Action register, out Mock mock, out T instance) where T : class + private void RegisterMock(Action register, out Mock mock, out T instance) + where T : class { mock = new Mock(); instance = mock.Object; register(instance); } - [Test] - public void ValidTabAndModuleIdLoadsActiveModule() - { - //Arrange - var request = new HttpRequestMessage(); - request.Headers.Add("tabid", ValidTabId.ToString(CultureInfo.InvariantCulture)); - request.Headers.Add("moduleid", ValidModuleId.ToString(CultureInfo.InvariantCulture)); - - //Act - ModuleInfo returnedModuleInfo; - var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - - //Assert - Assert.IsTrue(result); - Assert.AreSame(_moduleInfo, returnedModuleInfo); - } - - [Test] - public void ExistingMonikerValueInHeaderShouldFindTheCorrectModuleInfo() - { - //Arrange - var request = new HttpRequestMessage(); - request.Headers.Add("X-DNN-MONIKER", MonikerSettingValue); - - //Act - ModuleInfo returnedModuleInfo; - var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - - //Assert - Assert.IsTrue(result); - Assert.AreSame(_moduleInfo, returnedModuleInfo); - } - [Test] public void ExistingMonikerValueInQueryStringShouldFindTheCorrectModuleInfo() { - //Arrange + // Arrange var request = new HttpRequestMessage(); request.RequestUri = new Uri( "http://mysite.lvh.me/API/internalservices/controlbar/ToggleUserMode?moniker=" + HttpUtility.UrlEncode(MonikerSettingValue)); - //Act + // Act ModuleInfo returnedModuleInfo; var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - //Assert + // Assert Assert.IsTrue(result); - Assert.AreSame(_moduleInfo, returnedModuleInfo); + Assert.AreSame(this._moduleInfo, returnedModuleInfo); } [Test] public void NonExistingMonikerValueShouldFailToReturnResult() { - //Arrange + // Arrange var request = new HttpRequestMessage(); request.Headers.Add("X-DNN-MONIKER", "This moniker does not exist"); - //Act + // Act ModuleInfo returnedModuleInfo; var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - //Assert + // Assert Assert.IsFalse(result); Assert.IsNull(returnedModuleInfo); } @@ -189,14 +194,14 @@ public void NonExistingMonikerValueShouldFailToReturnResult() [Test] public void MissingAllHeadersShouldFailToReturnResult() { - //Arrange + // Arrange var request = new HttpRequestMessage(); - //Act + // Act ModuleInfo returnedModuleInfo; var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - //Assert + // Assert Assert.IsFalse(result); Assert.IsNull(returnedModuleInfo); } @@ -204,18 +209,18 @@ public void MissingAllHeadersShouldFailToReturnResult() [Test] public void OmittedTabIdWillNotLoadModule() { - //Arrange - //no tabid + // Arrange + // no tabid var request = new HttpRequestMessage(); request.Headers.Add("moduleid", ValidModuleId.ToString(CultureInfo.InvariantCulture)); - - //Act + + // Act ModuleInfo returnedModuleInfo; var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - //Assert - _mockTabController.Verify(x => x.GetTab(It.IsAny(), It.IsAny()), Times.Never()); - _mockModuleController.Verify(x => x.GetModule(It.IsAny(), It.IsAny(), false), Times.Never()); + // Assert + this._mockTabController.Verify(x => x.GetTab(It.IsAny(), It.IsAny()), Times.Never()); + this._mockModuleController.Verify(x => x.GetModule(It.IsAny(), It.IsAny(), false), Times.Never()); Assert.IsNull(returnedModuleInfo); Assert.IsFalse(result); } @@ -223,17 +228,17 @@ public void OmittedTabIdWillNotLoadModule() [Test] public void OmittedModuleIdWillNotLoadModule() { - //Arrange - //no moduleid + // Arrange + // no moduleid var request = new HttpRequestMessage(); request.Headers.Add("tabid", ValidTabId.ToString(CultureInfo.InvariantCulture)); - //Act + // Act ModuleInfo returnedModuleInfo; var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - //Assert - _mockModuleController.Verify(x => x.GetModule(It.IsAny(), It.IsAny(), false), Times.Never()); + // Assert + this._mockModuleController.Verify(x => x.GetModule(It.IsAny(), It.IsAny(), false), Times.Never()); Assert.IsNull(returnedModuleInfo); Assert.IsFalse(result); } @@ -241,16 +246,16 @@ public void OmittedModuleIdWillNotLoadModule() [Test] public void TabIdInHeaderTakesPriority() { - //Arrange + // Arrange var request = new HttpRequestMessage(); request.Headers.Add("tabid", ValidTabId.ToString(CultureInfo.InvariantCulture)); request.RequestUri = new Uri(string.Format("http://foo.com?{0}={1}", "tabid", ValidTabId + 1)); - - //Act + + // Act int tabId; var result = new StandardTabAndModuleInfoProvider().TryFindTabId(request, out tabId); - //Assert + // Assert Assert.AreEqual(ValidTabId, tabId); Assert.IsTrue(result); } @@ -258,16 +263,16 @@ public void TabIdInHeaderTakesPriority() [Test] public void ModuleIdInHeaderTakesPriority() { - //Arrange + // Arrange var request = new HttpRequestMessage(); request.Headers.Add("moduleid", ValidTabId.ToString(CultureInfo.InvariantCulture)); request.RequestUri = new Uri(string.Format("http://foo.com?{0}={1}", "moduleid", ValidTabId + 1)); - //Act + // Act int moduleId; var result = new StandardTabAndModuleInfoProvider().TryFindModuleId(request, out moduleId); - //Assert + // Assert Assert.AreEqual(ValidTabId, moduleId); Assert.IsTrue(result); } @@ -278,15 +283,15 @@ public void ModuleIdInHeaderTakesPriority() [TestCase("tAbiD")] public void TabIdInHeaderAllowsTabIdToBeFound(string headerName) { - //Arrange + // Arrange var request = new HttpRequestMessage(); request.Headers.Add(headerName, ValidTabId.ToString(CultureInfo.InvariantCulture)); - //Act + // Act int tabId; var result = new StandardTabAndModuleInfoProvider().TryFindTabId(request, out tabId); - //Assert + // Assert Assert.AreEqual(ValidTabId, tabId); Assert.IsTrue(result); } @@ -297,15 +302,15 @@ public void TabIdInHeaderAllowsTabIdToBeFound(string headerName) [TestCase("modULeid")] public void ModuleIdInHeaderAllowsModuleIdToBeFound(string headerName) { - //Arrange + // Arrange var request = new HttpRequestMessage(); request.Headers.Add(headerName, ValidModuleId.ToString(CultureInfo.InvariantCulture)); - //Act + // Act int moduleId; var result = new StandardTabAndModuleInfoProvider().TryFindModuleId(request, out moduleId); - //Assert + // Assert Assert.AreEqual(ValidModuleId, moduleId); Assert.IsTrue(result); } @@ -316,15 +321,15 @@ public void ModuleIdInHeaderAllowsModuleIdToBeFound(string headerName) [TestCase("X-DNN-MONIKER")] public void MonikerInHeaderAllowsModuleToBeFound(string headerName) { - //Arrange + // Arrange var request = new HttpRequestMessage(); request.Headers.Add(headerName, MonikerSettingValue); - //Act + // Act int moduleId; var result = new StandardTabAndModuleInfoProvider().TryFindModuleId(request, out moduleId); - //Assert + // Assert Assert.IsTrue(result); Assert.AreEqual(ValidModuleId, moduleId); } @@ -335,17 +340,17 @@ public void MonikerInHeaderAllowsModuleToBeFound(string headerName) [TestCase("tAbiD")] public void TabIdInQueryStringAllowsTabIdToBeFound(string paramName) { - //Arrange + // Arrange var request = new HttpRequestMessage { - RequestUri = new Uri(string.Format("http://foo.com?{0}={1}", paramName, ValidTabId)) + RequestUri = new Uri(string.Format("http://foo.com?{0}={1}", paramName, ValidTabId)), }; - //Act + // Act int tabId; var result = new StandardTabAndModuleInfoProvider().TryFindTabId(request, out tabId); - //Assert + // Assert Assert.AreEqual(ValidTabId, tabId); Assert.IsTrue(result); } @@ -356,17 +361,17 @@ public void TabIdInQueryStringAllowsTabIdToBeFound(string paramName) [TestCase("modULeid")] public void ModuleIdInQueryStringAllowsModuleIdToBeFound(string paramName) { - //Arrange + // Arrange var request = new HttpRequestMessage { - RequestUri = new Uri(string.Format("http://foo.com?{0}={1}", paramName, ValidModuleId)) + RequestUri = new Uri(string.Format("http://foo.com?{0}={1}", paramName, ValidModuleId)), }; - //Act + // Act int moduleId; var result = new StandardTabAndModuleInfoProvider().TryFindModuleId(request, out moduleId); - //Assert + // Assert Assert.AreEqual(ValidModuleId, moduleId); Assert.IsTrue(result); } @@ -374,13 +379,13 @@ public void ModuleIdInQueryStringAllowsModuleIdToBeFound(string paramName) [Test] public void NoTabIdInRequestReturnsNoTabId() { - //Arrange + // Arrange - //Act + // Act int tabId; var result = new StandardTabAndModuleInfoProvider().TryFindTabId(new HttpRequestMessage(), out tabId); - //Assert + // Assert Assert.IsFalse(result); Assert.AreEqual(-1, tabId); } @@ -388,13 +393,13 @@ public void NoTabIdInRequestReturnsNoTabId() [Test] public void NoModuleIdInRequestReturnsNoModuleId() { - //Arrange + // Arrange - //Act + // Act int moduleId; var result = new StandardTabAndModuleInfoProvider().TryFindModuleId(new HttpRequestMessage(), out moduleId); - //Assert + // Assert Assert.IsFalse(result); Assert.AreEqual(-1, moduleId); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/TypeLocatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/TypeLocatorTests.cs index 2606d54f340..a028f675032 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/TypeLocatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/TypeLocatorTests.cs @@ -1,33 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; - -using DotNetNuke.Framework.Internal.Reflection; -using DotNetNuke.Framework.Reflections; - -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Linq; + + using DotNetNuke.Framework.Internal.Reflection; + using DotNetNuke.Framework.Reflections; + using Moq; + using NUnit.Framework; + public class TypeLocatorTests { [Test] public void LocateAllMatchingTypes() { var assembly = new Mock(); - assembly.Setup(x => x.GetTypes()).Returns(new[] {typeof(TypeLocatorTests), typeof(ServiceRoutingManagerTests)}); + assembly.Setup(x => x.GetTypes()).Returns(new[] { typeof(TypeLocatorTests), typeof(ServiceRoutingManagerTests) }); var assemblyLocator = new Mock(); - assemblyLocator.Setup(x => x.Assemblies).Returns(new[] {assembly.Object}); + assemblyLocator.Setup(x => x.Assemblies).Returns(new[] { assembly.Object }); - var typeLocator = new TypeLocator {AssemblyLocator = assemblyLocator.Object}; + var typeLocator = new TypeLocator { AssemblyLocator = assemblyLocator.Object }; var types = typeLocator.GetAllMatchingTypes(x => true).ToList(); - CollectionAssert.AreEquivalent(new[]{typeof(TypeLocatorTests), typeof(ServiceRoutingManagerTests)}, types); + CollectionAssert.AreEquivalent(new[] { typeof(TypeLocatorTests), typeof(ServiceRoutingManagerTests) }, types); assembly.Verify(x => x.GetTypes(), Times.Once()); assemblyLocator.Verify(x => x.Assemblies, Times.Once()); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs index 779f0416fb2..0b6278f91c6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs @@ -1,20 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Net.Http; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Routing; - -using DotNetNuke.Web.Api; -using DotNetNuke.Web.Api.Internal; -using Moq; -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Api { + using System; + using System.Net.Http; + using System.Web.Http; + using System.Web.Http.Controllers; + using System.Web.Http.Routing; + + using DotNetNuke.Web.Api; + using DotNetNuke.Web.Api.Internal; + using Moq; + using NUnit.Framework; + [TestFixture] public class ValidateAntiForgeryTokenAttributeTests { @@ -25,60 +25,62 @@ public void TearDown() } [Test] - [TestCase("{0}={1}; ")] //simple - [TestCase("foo=fee; {0}={1}; key=value")] //normal - [TestCase("bad name=value; {0}={1}; good_name=value; ")] //bad whitespace - [TestCase("foo=fee; {0}={1}")] //no terminating semi-colon + [TestCase("{0}={1}; ")] // simple + [TestCase("foo=fee; {0}={1}; key=value")] // normal + [TestCase("bad name=value; {0}={1}; good_name=value; ")] // bad whitespace + [TestCase("foo=fee; {0}={1}")] // no terminating semi-colon public void LocateCookies(string cookieFormat) { - LocatesCookie(cookieFormat, "__RequestVerificationToken_thiscanbemany_characters_in_some_cases", "some text goes here"); + this.LocatesCookie(cookieFormat, "__RequestVerificationToken_thiscanbemany_characters_in_some_cases", "some text goes here"); } - - + [Test] - //real world data from a request that fails when using the WebAPI .GetCookies method - [TestCase("StayInEditMode=NO; ASP.NET_SessionId=yumytgeltkonngafni2h3i55; __RequestVerificationToken_LzYyMA__=dL23/UED9k98Xl4yO6jaXu6Oa29D6dLtjucfyukq7nV2ET6hBznoTS74x0yXuj8TS8qIoXcYa+6FkeE38qKQkR9KUq48oEeikLLdhIOZSkaDYsmgXQ7uKwNFK4k=; Panel-FriendlyUrl=false; dnnSitePanel-LoadFiles=true; dnnSitePanel-SEOSettings=true; dnnSitePanel-GeneralSettings=true; dnnSitePanel-EntryOptions=true; dnnSitePanel-AdvancedSettings=true; __RequestVerificationToken_L05lYnVsYQ__=C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=; SuggestionCustom=false; SuggestionTemplate=false; dnnTabs-dnnEditRole=0; dnnTabs-dnnBlogOptions=0; dnnSitePanel-RSSSettings=false; dnnSitePanel-CommentSettings=false; dnnTabs-dnnRecycleBin=0; dnnTabs-dnnManageUsers=0; Panel-Authentication Systems=false; .DOTNETNUKECTP270=63191FCE95736673FF53435768B2BB9838233821C4653EA0F3940432D05EF501878DE0A353C4B5474D52F5A28638BDDE1FB4269AB674C8283361C56A8CEC70243424414BB3871EB0918B840C6092CBD348A714BDD7D12A6B0441BC3BB96FC1DF963AA7A7; Panel-HostDetails=false; Panel-SMTP=false; .NEBULAX12=4C3B5C2B5C1DA13493A114CDE53CF487907FAF66AAAF04972CBF4E63E779580FE385D0759DDCA946775D0B0300A712052D4169DC93CC0B380D3970238B80E2850077573B22C9D1B8FB119867874667CA350057F392EE89E2205184FE53F3AB949578298E; __RequestVerificationToken_LzYyMw__=RtpaumwI56fNPCA7js90MRMECcEkR78oHrHn82YQOHXy3O3p53dEklX/485E+GMGGN/D/pzhN4UUI3eJs7be/1Tbkv8mwsMO9WAfFulwZazuktqwlmAyuI5BOj4=; dnnSitePanel-SiteDetails=false; dnnSitePanel-Appearance=true; dnnPanel-ViewLog=true; .ASPXANONYMOUS=N2HauUbbzQEkAAAAZWRmODRjODEtODBhOS00NGJhLTlhYTAtZDk5YTcxZTgzYzlm0; dnnSitePanel-Usability=true; dnnPanel-ExtensionPackageSettings=false; dnnSitePanel-Pages=true; dnnPanel-TabsOtherSettings=false; dnnPanel-TabsCacheSettings=false; dnnPanel-TabsAppearance=true; __RequestVerificationToken_L0NUUA2=rXptF4iP2vio-YQMbnxOp66oECpG2DQe6llUiWmiyjJvYjtWcx9XrjymOMwCheiGNogAbrv0RTPDGe2VGxswX0NVX02PZ-U2RwViRYhATUvcymdrc9jV3ygC0_w1; __RequestVerificationToken_LzcwMA2=LDfpU-HI96zNfH6FfLc45T9v8Ltr0OzwYWsaUVs-hGW1gVnLzYoVUm9xcQDkwjjrve_MbAQx6WuNq5Om2C8TEPRk_tXGDe7d3ibvXZVd0iUXYmSjoapYZ6FnjA41; undefined=false; dnn_ctr345_EditExtension_ModuleEditor_moduleSettingsHead=false; Panel-Widgets=false; Panel-Skin Objects=false; Panel-Skins=false; Panel-Providers=false; dnnPanel-LogSendExceptions=false; dnnPanel-ModuleAppearance=false; dnnPanel-ModuleOtherSettings=true; dnnTabs-dnnModuleSettings=3; dnnTabs-dnnHostSettings=0; Panel-Configuration=false; .DOTNETNUKE7PEBETA=197F580A056BEFB9E793BA8629133538298764AD055A68BABD9B93BD80F15A2B8734CD12D6CCA5B2BD8154319B932286A886074B57EAF06FA1E5E8DFA89FBF4192AA0E2F099554E5220DE12A632D5D58AA0272250CE67F93DD33CD3A4A411603252D0CB2; __RequestVerificationToken_LzdQRQ2=IKW7w2KnSu53WEJR0RKvhOcb2f_tyrxeSNuxOGoKmRIyvNFHnj4V_yZsE3J4cJILVeOP15sPmFbukzCpejZL7Ltmlx_XxDFRknrN-xJ4_5cPcppIGFCrl7o0akE1; .DOTNETNUKE=A43776EA5CEDF9E63B890A79E803F54FF72FD3718F9633C80C94C60EA43990EC24A7791B354E21A3CDDDF81F6AE0602A332770B6BA2AF48CED1973061A15F72CF78E8D9A1D33ED882B8E66E3CF9588325709E287FBA83CD11D58A84D03923716EC74B0FF; authentication=DNN; Panel-Libraries=false; dnnTabs-dnnExtensions=0; Panel-Modules=true; 51D=3155378975999999999; __RequestVerificationToken_L09yaW9u0=erx2uolpjtcgKYekq_Blw9bjJTsGB78wa-HREzGMXgpNM6fKGv1MvQ5mHj2KQLfBwyUzkHR3rC6XlTgf4NlcMhm2FyInWqaiPfU9w6lBj5EQeu-Wl3YXLuQrDgM1; .ORIONNEBULA7=1B487CE9A95CC1E925AEA02D9535E3E27F7536663EF7DD451996E3D7ADD474C410352960C16D7B38E19ECF2056927C2DEB23DABE85BB90EF0CC80226D00B6D90C21D45BA77F4D62C0C58FD5303672812C1A58783A50B58D34C245CC56694C176EA8F2541; __RequestVerificationToken_L1ZlaWw1=aAOphH6E9pSOu9yjGvTGhlaXHDL-Z5RQtPcb9-aAYSOJ674286gvW65ui7tm7iBr6COrjRN2UXeI6fQQyiL7Q8ctc59K5YQ5jM2K09l3fnag-3FZ1zz3W6d6iGE1; dnnTabs-dnnSiteSettings=1; dnnTabs-tabSettingsForm=0; .VeilNebula7=7DE1D60FF03633EF8611505BBB7201942C6C236AD8C289B22FE2BE48647D2626D55DF84ACA02094C3D253A1EBBABD48C0A008538E0C3AB4DA96ABC95EFA947DC2D74FF79D9478674D0BA35D3D2EAE94E2B5CDDC43915E11B90B361CEE799F3C421ECE499; language=en-US; LastPageId=0:64; dnnTabs-smMainContent=0", "__RequestVerificationToken_L05lYnVsYQ__" , "C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=" )] + + // real world data from a request that fails when using the WebAPI .GetCookies method + [TestCase("StayInEditMode=NO; ASP.NET_SessionId=yumytgeltkonngafni2h3i55; __RequestVerificationToken_LzYyMA__=dL23/UED9k98Xl4yO6jaXu6Oa29D6dLtjucfyukq7nV2ET6hBznoTS74x0yXuj8TS8qIoXcYa+6FkeE38qKQkR9KUq48oEeikLLdhIOZSkaDYsmgXQ7uKwNFK4k=; Panel-FriendlyUrl=false; dnnSitePanel-LoadFiles=true; dnnSitePanel-SEOSettings=true; dnnSitePanel-GeneralSettings=true; dnnSitePanel-EntryOptions=true; dnnSitePanel-AdvancedSettings=true; __RequestVerificationToken_L05lYnVsYQ__=C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=; SuggestionCustom=false; SuggestionTemplate=false; dnnTabs-dnnEditRole=0; dnnTabs-dnnBlogOptions=0; dnnSitePanel-RSSSettings=false; dnnSitePanel-CommentSettings=false; dnnTabs-dnnRecycleBin=0; dnnTabs-dnnManageUsers=0; Panel-Authentication Systems=false; .DOTNETNUKECTP270=63191FCE95736673FF53435768B2BB9838233821C4653EA0F3940432D05EF501878DE0A353C4B5474D52F5A28638BDDE1FB4269AB674C8283361C56A8CEC70243424414BB3871EB0918B840C6092CBD348A714BDD7D12A6B0441BC3BB96FC1DF963AA7A7; Panel-HostDetails=false; Panel-SMTP=false; .NEBULAX12=4C3B5C2B5C1DA13493A114CDE53CF487907FAF66AAAF04972CBF4E63E779580FE385D0759DDCA946775D0B0300A712052D4169DC93CC0B380D3970238B80E2850077573B22C9D1B8FB119867874667CA350057F392EE89E2205184FE53F3AB949578298E; __RequestVerificationToken_LzYyMw__=RtpaumwI56fNPCA7js90MRMECcEkR78oHrHn82YQOHXy3O3p53dEklX/485E+GMGGN/D/pzhN4UUI3eJs7be/1Tbkv8mwsMO9WAfFulwZazuktqwlmAyuI5BOj4=; dnnSitePanel-SiteDetails=false; dnnSitePanel-Appearance=true; dnnPanel-ViewLog=true; .ASPXANONYMOUS=N2HauUbbzQEkAAAAZWRmODRjODEtODBhOS00NGJhLTlhYTAtZDk5YTcxZTgzYzlm0; dnnSitePanel-Usability=true; dnnPanel-ExtensionPackageSettings=false; dnnSitePanel-Pages=true; dnnPanel-TabsOtherSettings=false; dnnPanel-TabsCacheSettings=false; dnnPanel-TabsAppearance=true; __RequestVerificationToken_L0NUUA2=rXptF4iP2vio-YQMbnxOp66oECpG2DQe6llUiWmiyjJvYjtWcx9XrjymOMwCheiGNogAbrv0RTPDGe2VGxswX0NVX02PZ-U2RwViRYhATUvcymdrc9jV3ygC0_w1; __RequestVerificationToken_LzcwMA2=LDfpU-HI96zNfH6FfLc45T9v8Ltr0OzwYWsaUVs-hGW1gVnLzYoVUm9xcQDkwjjrve_MbAQx6WuNq5Om2C8TEPRk_tXGDe7d3ibvXZVd0iUXYmSjoapYZ6FnjA41; undefined=false; dnn_ctr345_EditExtension_ModuleEditor_moduleSettingsHead=false; Panel-Widgets=false; Panel-Skin Objects=false; Panel-Skins=false; Panel-Providers=false; dnnPanel-LogSendExceptions=false; dnnPanel-ModuleAppearance=false; dnnPanel-ModuleOtherSettings=true; dnnTabs-dnnModuleSettings=3; dnnTabs-dnnHostSettings=0; Panel-Configuration=false; .DOTNETNUKE7PEBETA=197F580A056BEFB9E793BA8629133538298764AD055A68BABD9B93BD80F15A2B8734CD12D6CCA5B2BD8154319B932286A886074B57EAF06FA1E5E8DFA89FBF4192AA0E2F099554E5220DE12A632D5D58AA0272250CE67F93DD33CD3A4A411603252D0CB2; __RequestVerificationToken_LzdQRQ2=IKW7w2KnSu53WEJR0RKvhOcb2f_tyrxeSNuxOGoKmRIyvNFHnj4V_yZsE3J4cJILVeOP15sPmFbukzCpejZL7Ltmlx_XxDFRknrN-xJ4_5cPcppIGFCrl7o0akE1; .DOTNETNUKE=A43776EA5CEDF9E63B890A79E803F54FF72FD3718F9633C80C94C60EA43990EC24A7791B354E21A3CDDDF81F6AE0602A332770B6BA2AF48CED1973061A15F72CF78E8D9A1D33ED882B8E66E3CF9588325709E287FBA83CD11D58A84D03923716EC74B0FF; authentication=DNN; Panel-Libraries=false; dnnTabs-dnnExtensions=0; Panel-Modules=true; 51D=3155378975999999999; __RequestVerificationToken_L09yaW9u0=erx2uolpjtcgKYekq_Blw9bjJTsGB78wa-HREzGMXgpNM6fKGv1MvQ5mHj2KQLfBwyUzkHR3rC6XlTgf4NlcMhm2FyInWqaiPfU9w6lBj5EQeu-Wl3YXLuQrDgM1; .ORIONNEBULA7=1B487CE9A95CC1E925AEA02D9535E3E27F7536663EF7DD451996E3D7ADD474C410352960C16D7B38E19ECF2056927C2DEB23DABE85BB90EF0CC80226D00B6D90C21D45BA77F4D62C0C58FD5303672812C1A58783A50B58D34C245CC56694C176EA8F2541; __RequestVerificationToken_L1ZlaWw1=aAOphH6E9pSOu9yjGvTGhlaXHDL-Z5RQtPcb9-aAYSOJ674286gvW65ui7tm7iBr6COrjRN2UXeI6fQQyiL7Q8ctc59K5YQ5jM2K09l3fnag-3FZ1zz3W6d6iGE1; dnnTabs-dnnSiteSettings=1; dnnTabs-tabSettingsForm=0; .VeilNebula7=7DE1D60FF03633EF8611505BBB7201942C6C236AD8C289B22FE2BE48647D2626D55DF84ACA02094C3D253A1EBBABD48C0A008538E0C3AB4DA96ABC95EFA947DC2D74FF79D9478674D0BA35D3D2EAE94E2B5CDDC43915E11B90B361CEE799F3C421ECE499; language=en-US; LastPageId=0:64; dnnTabs-smMainContent=0", "__RequestVerificationToken_L05lYnVsYQ__", "C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=")] public void LocatesCookie(string cookieFormat, string cookieName, string cookieValue) { - //Arrange + // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/"); request.Headers.Add("Cookie", string.Format(cookieFormat, cookieName, cookieValue)); request.Headers.Add("RequestVerificationToken", "anything_is_fine"); var config = new HttpConfiguration(); var controllerContext = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request); var actionContext = new HttpActionContext(controllerContext, new Mock().Object); - var authFilterContext = new AuthFilterContext(actionContext, ""); + var authFilterContext = new AuthFilterContext(actionContext, string.Empty); var mockAntiForgery = new Mock(); mockAntiForgery.Setup(x => x.CookieName).Returns(cookieName); AntiForgery.SetTestableInstance(mockAntiForgery.Object); - //Act + // Act var vaft = new ValidateAntiForgeryTokenAttribute(); - //Assert.IsTrue(ValidateAntiForgeryTokenAttribute.IsAuthorized(authFilterContext)); + + // Assert.IsTrue(ValidateAntiForgeryTokenAttribute.IsAuthorized(authFilterContext)); Assert.DoesNotThrow(() => { vaft.OnActionExecuting(authFilterContext.ActionContext); }); - //Assert + // Assert mockAntiForgery.Verify(x => x.Validate(cookieValue, It.IsAny()), Times.Once()); } [Test] - [TestCase("StayInEditMode=NO; ASP.NET_SessionId=yumytgeltkonngafni2h3i55; __RequestVerificationToken_LzYyMA__=dL23/UED9k98Xl4yO6jaXu6Oa29D6dLtjucfyukq7nV2ET6hBznoTS74x0yXuj8TS8qIoXcYa+6FkeE38qKQkR9KUq48oEeikLLdhIOZSkaDYsmgXQ7uKwNFK4k=; Panel-FriendlyUrl=false; dnnSitePanel-LoadFiles=true; dnnSitePanel-SEOSettings=true; dnnSitePanel-GeneralSettings=true; dnnSitePanel-EntryOptions=true; dnnSitePanel-AdvancedSettings=true; __RequestVerificationToken_L05lYnVsYQ__=C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=; SuggestionCustom=false; SuggestionTemplate=false; dnnTabs-dnnEditRole=0; dnnTabs-dnnBlogOptions=0; dnnSitePanel-RSSSettings=false; dnnSitePanel-CommentSettings=false; dnnTabs-dnnRecycleBin=0; dnnTabs-dnnManageUsers=0; Panel-Authentication Systems=false; .DOTNETNUKECTP270=63191FCE95736673FF53435768B2BB9838233821C4653EA0F3940432D05EF501878DE0A353C4B5474D52F5A28638BDDE1FB4269AB674C8283361C56A8CEC70243424414BB3871EB0918B840C6092CBD348A714BDD7D12A6B0441BC3BB96FC1DF963AA7A7; Panel-HostDetails=false; Panel-SMTP=false; .NEBULAX12=4C3B5C2B5C1DA13493A114CDE53CF487907FAF66AAAF04972CBF4E63E779580FE385D0759DDCA946775D0B0300A712052D4169DC93CC0B380D3970238B80E2850077573B22C9D1B8FB119867874667CA350057F392EE89E2205184FE53F3AB949578298E; __RequestVerificationToken_LzYyMw__=RtpaumwI56fNPCA7js90MRMECcEkR78oHrHn82YQOHXy3O3p53dEklX/485E+GMGGN/D/pzhN4UUI3eJs7be/1Tbkv8mwsMO9WAfFulwZazuktqwlmAyuI5BOj4=; dnnSitePanel-SiteDetails=false; dnnSitePanel-Appearance=true; dnnPanel-ViewLog=true; .ASPXANONYMOUS=N2HauUbbzQEkAAAAZWRmODRjODEtODBhOS00NGJhLTlhYTAtZDk5YTcxZTgzYzlm0; dnnSitePanel-Usability=true; dnnPanel-ExtensionPackageSettings=false; dnnSitePanel-Pages=true; dnnPanel-TabsOtherSettings=false; dnnPanel-TabsCacheSettings=false; dnnPanel-TabsAppearance=true; __RequestVerificationToken_L0NUUA2=rXptF4iP2vio-YQMbnxOp66oECpG2DQe6llUiWmiyjJvYjtWcx9XrjymOMwCheiGNogAbrv0RTPDGe2VGxswX0NVX02PZ-U2RwViRYhATUvcymdrc9jV3ygC0_w1; __RequestVerificationToken_LzcwMA2=LDfpU-HI96zNfH6FfLc45T9v8Ltr0OzwYWsaUVs-hGW1gVnLzYoVUm9xcQDkwjjrve_MbAQx6WuNq5Om2C8TEPRk_tXGDe7d3ibvXZVd0iUXYmSjoapYZ6FnjA41; undefined=false; dnn_ctr345_EditExtension_ModuleEditor_moduleSettingsHead=false; Panel-Widgets=false; Panel-Skin Objects=false; Panel-Skins=false; Panel-Providers=false; dnnPanel-LogSendExceptions=false; dnnPanel-ModuleAppearance=false; dnnPanel-ModuleOtherSettings=true; dnnTabs-dnnModuleSettings=3; dnnTabs-dnnHostSettings=0; Panel-Configuration=false; .DOTNETNUKE7PEBETA=197F580A056BEFB9E793BA8629133538298764AD055A68BABD9B93BD80F15A2B8734CD12D6CCA5B2BD8154319B932286A886074B57EAF06FA1E5E8DFA89FBF4192AA0E2F099554E5220DE12A632D5D58AA0272250CE67F93DD33CD3A4A411603252D0CB2; __RequestVerificationToken_LzdQRQ2=IKW7w2KnSu53WEJR0RKvhOcb2f_tyrxeSNuxOGoKmRIyvNFHnj4V_yZsE3J4cJILVeOP15sPmFbukzCpejZL7Ltmlx_XxDFRknrN-xJ4_5cPcppIGFCrl7o0akE1; .DOTNETNUKE=A43776EA5CEDF9E63B890A79E803F54FF72FD3718F9633C80C94C60EA43990EC24A7791B354E21A3CDDDF81F6AE0602A332770B6BA2AF48CED1973061A15F72CF78E8D9A1D33ED882B8E66E3CF9588325709E287FBA83CD11D58A84D03923716EC74B0FF; authentication=DNN; Panel-Libraries=false; dnnTabs-dnnExtensions=0; Panel-Modules=true; 51D=3155378975999999999; __RequestVerificationToken_L09yaW9u0=erx2uolpjtcgKYekq_Blw9bjJTsGB78wa-HREzGMXgpNM6fKGv1MvQ5mHj2KQLfBwyUzkHR3rC6XlTgf4NlcMhm2FyInWqaiPfU9w6lBj5EQeu-Wl3YXLuQrDgM1; .ORIONNEBULA7=1B487CE9A95CC1E925AEA02D9535E3E27F7536663EF7DD451996E3D7ADD474C410352960C16D7B38E19ECF2056927C2DEB23DABE85BB90EF0CC80226D00B6D90C21D45BA77F4D62C0C58FD5303672812C1A58783A50B58D34C245CC56694C176EA8F2541; __RequestVerificationToken_L1ZlaWw1=aAOphH6E9pSOu9yjGvTGhlaXHDL-Z5RQtPcb9-aAYSOJ674286gvW65ui7tm7iBr6COrjRN2UXeI6fQQyiL7Q8ctc59K5YQ5jM2K09l3fnag-3FZ1zz3W6d6iGE1; dnnTabs-dnnSiteSettings=1; dnnTabs-tabSettingsForm=0; .VeilNebula7=7DE1D60FF03633EF8611505BBB7201942C6C236AD8C289B22FE2BE48647D2626D55DF84ACA02094C3D253A1EBBABD48C0A008538E0C3AB4DA96ABC95EFA947DC2D74FF79D9478674D0BA35D3D2EAE94E2B5CDDC43915E11B90B361CEE799F3C421ECE499; language=en-US; LastPageId=0:64; dnnTabs-smMainContent=0", "__RequestVerificationToken_L05lYnVsYQ__" , "C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=" )] + [TestCase("StayInEditMode=NO; ASP.NET_SessionId=yumytgeltkonngafni2h3i55; __RequestVerificationToken_LzYyMA__=dL23/UED9k98Xl4yO6jaXu6Oa29D6dLtjucfyukq7nV2ET6hBznoTS74x0yXuj8TS8qIoXcYa+6FkeE38qKQkR9KUq48oEeikLLdhIOZSkaDYsmgXQ7uKwNFK4k=; Panel-FriendlyUrl=false; dnnSitePanel-LoadFiles=true; dnnSitePanel-SEOSettings=true; dnnSitePanel-GeneralSettings=true; dnnSitePanel-EntryOptions=true; dnnSitePanel-AdvancedSettings=true; __RequestVerificationToken_L05lYnVsYQ__=C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=; SuggestionCustom=false; SuggestionTemplate=false; dnnTabs-dnnEditRole=0; dnnTabs-dnnBlogOptions=0; dnnSitePanel-RSSSettings=false; dnnSitePanel-CommentSettings=false; dnnTabs-dnnRecycleBin=0; dnnTabs-dnnManageUsers=0; Panel-Authentication Systems=false; .DOTNETNUKECTP270=63191FCE95736673FF53435768B2BB9838233821C4653EA0F3940432D05EF501878DE0A353C4B5474D52F5A28638BDDE1FB4269AB674C8283361C56A8CEC70243424414BB3871EB0918B840C6092CBD348A714BDD7D12A6B0441BC3BB96FC1DF963AA7A7; Panel-HostDetails=false; Panel-SMTP=false; .NEBULAX12=4C3B5C2B5C1DA13493A114CDE53CF487907FAF66AAAF04972CBF4E63E779580FE385D0759DDCA946775D0B0300A712052D4169DC93CC0B380D3970238B80E2850077573B22C9D1B8FB119867874667CA350057F392EE89E2205184FE53F3AB949578298E; __RequestVerificationToken_LzYyMw__=RtpaumwI56fNPCA7js90MRMECcEkR78oHrHn82YQOHXy3O3p53dEklX/485E+GMGGN/D/pzhN4UUI3eJs7be/1Tbkv8mwsMO9WAfFulwZazuktqwlmAyuI5BOj4=; dnnSitePanel-SiteDetails=false; dnnSitePanel-Appearance=true; dnnPanel-ViewLog=true; .ASPXANONYMOUS=N2HauUbbzQEkAAAAZWRmODRjODEtODBhOS00NGJhLTlhYTAtZDk5YTcxZTgzYzlm0; dnnSitePanel-Usability=true; dnnPanel-ExtensionPackageSettings=false; dnnSitePanel-Pages=true; dnnPanel-TabsOtherSettings=false; dnnPanel-TabsCacheSettings=false; dnnPanel-TabsAppearance=true; __RequestVerificationToken_L0NUUA2=rXptF4iP2vio-YQMbnxOp66oECpG2DQe6llUiWmiyjJvYjtWcx9XrjymOMwCheiGNogAbrv0RTPDGe2VGxswX0NVX02PZ-U2RwViRYhATUvcymdrc9jV3ygC0_w1; __RequestVerificationToken_LzcwMA2=LDfpU-HI96zNfH6FfLc45T9v8Ltr0OzwYWsaUVs-hGW1gVnLzYoVUm9xcQDkwjjrve_MbAQx6WuNq5Om2C8TEPRk_tXGDe7d3ibvXZVd0iUXYmSjoapYZ6FnjA41; undefined=false; dnn_ctr345_EditExtension_ModuleEditor_moduleSettingsHead=false; Panel-Widgets=false; Panel-Skin Objects=false; Panel-Skins=false; Panel-Providers=false; dnnPanel-LogSendExceptions=false; dnnPanel-ModuleAppearance=false; dnnPanel-ModuleOtherSettings=true; dnnTabs-dnnModuleSettings=3; dnnTabs-dnnHostSettings=0; Panel-Configuration=false; .DOTNETNUKE7PEBETA=197F580A056BEFB9E793BA8629133538298764AD055A68BABD9B93BD80F15A2B8734CD12D6CCA5B2BD8154319B932286A886074B57EAF06FA1E5E8DFA89FBF4192AA0E2F099554E5220DE12A632D5D58AA0272250CE67F93DD33CD3A4A411603252D0CB2; __RequestVerificationToken_LzdQRQ2=IKW7w2KnSu53WEJR0RKvhOcb2f_tyrxeSNuxOGoKmRIyvNFHnj4V_yZsE3J4cJILVeOP15sPmFbukzCpejZL7Ltmlx_XxDFRknrN-xJ4_5cPcppIGFCrl7o0akE1; .DOTNETNUKE=A43776EA5CEDF9E63B890A79E803F54FF72FD3718F9633C80C94C60EA43990EC24A7791B354E21A3CDDDF81F6AE0602A332770B6BA2AF48CED1973061A15F72CF78E8D9A1D33ED882B8E66E3CF9588325709E287FBA83CD11D58A84D03923716EC74B0FF; authentication=DNN; Panel-Libraries=false; dnnTabs-dnnExtensions=0; Panel-Modules=true; 51D=3155378975999999999; __RequestVerificationToken_L09yaW9u0=erx2uolpjtcgKYekq_Blw9bjJTsGB78wa-HREzGMXgpNM6fKGv1MvQ5mHj2KQLfBwyUzkHR3rC6XlTgf4NlcMhm2FyInWqaiPfU9w6lBj5EQeu-Wl3YXLuQrDgM1; .ORIONNEBULA7=1B487CE9A95CC1E925AEA02D9535E3E27F7536663EF7DD451996E3D7ADD474C410352960C16D7B38E19ECF2056927C2DEB23DABE85BB90EF0CC80226D00B6D90C21D45BA77F4D62C0C58FD5303672812C1A58783A50B58D34C245CC56694C176EA8F2541; __RequestVerificationToken_L1ZlaWw1=aAOphH6E9pSOu9yjGvTGhlaXHDL-Z5RQtPcb9-aAYSOJ674286gvW65ui7tm7iBr6COrjRN2UXeI6fQQyiL7Q8ctc59K5YQ5jM2K09l3fnag-3FZ1zz3W6d6iGE1; dnnTabs-dnnSiteSettings=1; dnnTabs-tabSettingsForm=0; .VeilNebula7=7DE1D60FF03633EF8611505BBB7201942C6C236AD8C289B22FE2BE48647D2626D55DF84ACA02094C3D253A1EBBABD48C0A008538E0C3AB4DA96ABC95EFA947DC2D74FF79D9478674D0BA35D3D2EAE94E2B5CDDC43915E11B90B361CEE799F3C421ECE499; language=en-US; LastPageId=0:64; dnnTabs-smMainContent=0", "__RequestVerificationToken_L05lYnVsYQ__", "C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=")] public void MissingTokenDoesnotPassValidationTest(string cookieFormat, string cookieName, string cookieValue) { - //Arrange + // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/"); request.Headers.Add("Cookie", string.Format(cookieFormat, cookieName, cookieValue)); var config = new HttpConfiguration(); var controllerContext = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request); var actionContext = new HttpActionContext(controllerContext, new Mock().Object); - var authFilterContext = new AuthFilterContext(actionContext, ""); + var authFilterContext = new AuthFilterContext(actionContext, string.Empty); var mockAntiForgery = new Mock(); mockAntiForgery.Setup(x => x.CookieName).Returns(cookieName); AntiForgery.SetTestableInstance(mockAntiForgery.Object); - //Act, Assert + // Act, Assert var vaft = new ValidateAntiForgeryTokenAttribute(); - //Assert.IsFalse(ValidateAntiForgeryTokenAttribute.IsAuthorized(authFilterContext)); + + // Assert.IsFalse(ValidateAntiForgeryTokenAttribute.IsAuthorized(authFilterContext)); Assert.Throws(() => { vaft.OnActionExecuting(authFilterContext.ActionContext); }); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config b/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config index e57cb5d4d35..928751a9acb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config @@ -1,23 +1,23 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj index 78a529a1e64..1cb7e417df4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj @@ -1,170 +1,177 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {705708E8-6AD9-4021-9B36-EFC83AD42EE7} - Library - Properties - DotNetNuke.Tests.Web - DotNetNuke.Tests.Web - v4.7.2 - 512 - ..\..\..\..\Evoq.Content\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - 618 - 7 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - 618 - 7 - - - - False - ..\..\Library\bin\Lucene.Net.dll - - - ..\..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll - - - ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - - - ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll - - - False - ..\..\..\Packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll - - - ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - True - - - - - False - ..\..\Components\WebAPI\System.Net.Http.dll - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - - - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - - - False - ..\..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll - - - - - - - - - ..\..\..\packages\WebFormsMVP.1.4.1.0\lib\WebFormsMvp.dll - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - {3b2fa1d9-ec7d-4cec-8ff5-a7700cf5cb40} - Dnn.AuthServices.Jwt - - - {6928A9B1-F88A-4581-A132-D3EB38669BB0} - DotNetNuke.Abstractions - - - {0FCA217A-5F9A-4F5B-A31B-86D64AE65198} - DotNetNuke.DependencyInjection - - - {04f77171-0634-46e0-a95e-d7477c88712e} - DotNetNuke.Log4Net - - - {ee1329fe-fd88-4e1a-968c-345e394ef080} - DotNetNuke.Web - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {5AECE021-E449-4A7F-BF82-2FA7B236ED3E} - DotNetNuke.Tests.Utilities - - - - - - + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {705708E8-6AD9-4021-9B36-EFC83AD42EE7} + Library + Properties + DotNetNuke.Tests.Web + DotNetNuke.Tests.Web + v4.7.2 + 512 + ..\..\..\..\Evoq.Content\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 618 + 7 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 618 + 7 + + + + False + ..\..\Library\bin\Lucene.Net.dll + + + ..\..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll + + + ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + ..\..\..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll + + + False + ..\..\..\Packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + + + ..\..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + True + + + + + False + ..\..\Components\WebAPI\System.Net.Http.dll + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + + + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + + + False + ..\..\..\Packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll + + + + + + + + + ..\..\..\packages\WebFormsMVP.1.4.1.0\lib\WebFormsMvp.dll + + + + + + + + + + + + + + + + + Code + + + + + + + + + + + + stylecop.json + + + + + + + {3b2fa1d9-ec7d-4cec-8ff5-a7700cf5cb40} + Dnn.AuthServices.Jwt + + + {6928A9B1-F88A-4581-A132-D3EB38669BB0} + DotNetNuke.Abstractions + + + {0FCA217A-5F9A-4F5B-A31B-86D64AE65198} + DotNetNuke.DependencyInjection + + + {04f77171-0634-46e0-a95e-d7477c88712e} + DotNetNuke.Log4Net + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {5AECE021-E449-4A7F-BF82-2FA7B236ED3E} + DotNetNuke.Tests.Utilities + + + + + + + + + + - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + --> + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs index cdfaefd50d3..ac785903539 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs @@ -1,26 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Search.Controllers; -using DotNetNuke.Services.Search.Entities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Web.InternalServices { + using System; + + using DotNetNuke.Services.Search.Controllers; + using DotNetNuke.Services.Search.Entities; + /// - /// Search Crawler for Module Content + /// Search Crawler for Module Content. /// /// public class FakeResultController : BaseResultController - { - #region Abstract Class Implmentation - + { public override bool HasViewPermission(SearchResult searchResult) { return true; @@ -28,11 +21,9 @@ public override bool HasViewPermission(SearchResult searchResult) // Returns the URL to the first instance of the module the user has access to view public override string GetDocUrl(SearchResult searchResult) - { - return "http://www.google.com"; - } - - #endregion + { + return "http://www.google.com"; + } } public class NoPermissionFakeResultController : FakeResultController @@ -42,7 +33,7 @@ public override bool HasViewPermission(SearchResult searchResult) { // This logic tests that based on ID we give permission to test recursive // search in SearchControllerImpl.GetSecurityTrimmedResults() method. - //The logic here is all documents with AuthorUserId's 6-9, 16-19, 26-29, etc. have + // The logic here is all documents with AuthorUserId's 6-9, 16-19, 26-29, etc. have // permission, while the rest don't return (searchResult.AuthorUserId % 10) > 5; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs index c4a5aa3291e..79c6e0edc9c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs @@ -1,47 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Web.Http; -using System.Web.Http.Hosting; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Data; -using DotNetNuke.Entities.Portals.Data; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Cache; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Tests.Utilities.Mocks; -using Moq; - -using NUnit.Framework; -using Constants = DotNetNuke.Services.Search.Internals.Constants; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Web.InternalServices; -using DotNetNuke.Web.InternalServices.Views.Search; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Web.Api; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.InternalServices { + using System; + using System.Collections.Generic; + using System.Data; + using System.IO; + using System.Linq; + using System.Net.Http; + using System.Web.Http; + using System.Web.Http.Hosting; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Portals.Data; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Entities; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Tests.Utilities.Mocks; + using DotNetNuke.Web.Api; + using DotNetNuke.Web.InternalServices; + using DotNetNuke.Web.InternalServices.Views.Search; + using Moq; + using NUnit.Framework; + + using Constants = DotNetNuke.Services.Search.Internals.Constants; + /// - /// Testing grouping logic of GetGroupedBasicView and GetGroupedDetailView (SearchServiceController methods) + /// Testing grouping logic of GetGroupedBasicView and GetGroupedDetailView (SearchServiceController methods). /// [TestFixture] public class SearchServiceControllerTests - { - - #region Constants + { private const int ModuleSearchTypeId = 1; private const int TabSearchTypeId = 2; private const int UserSearchTypeId = 3; @@ -64,24 +63,19 @@ public class SearchServiceControllerTests private const int HtmlModuleId4 = 378; private const int UserId1 = 1; private const string UserName1 = "User1"; - + private const string UserSearchTypeName = "user"; private const string TabSearchTypeName = "tab"; private const string UrlSearchTypeName = "url"; private const string FakeResultControllerClass = "DotNetNuke.Tests.Web.InternalServices.FakeResultController, DotNetNuke.Tests.Web"; - + private const string CultureEnUs = "en-US"; - + private const string SearchIndexFolder = @"App_Data\SearchTests"; + private const int DefaultSearchRetryTimes = 5; + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - - private const int DefaultSearchRetryTimes = 5; - - #endregion - - #region Private Properties - private Mock _mockCBO; private Mock _mockHostController; private Mock _mockCachingProvider; @@ -93,45 +87,42 @@ public class SearchServiceControllerTests private Mock _mockTabController; private SearchServiceController _searchServiceController; private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - - #endregion - - #region Set Up + private LuceneControllerImpl _luceneController; + [SetUp] public void SetUp() { - //Arrange + // Arrange ComponentFactory.Container = new SimpleContainer(); MockComponentProvider.ResetContainer(); - _mockDataProvider = MockComponentProvider.CreateDataProvider(); - _mockLocaleController = MockComponentProvider.CreateLocaleController(); - _mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); - _mockDataService = new Mock(); - _mockUserController = new Mock(); - _mockModuleController = new Mock(); - _mockTabController = new Mock(); - _mockHostController = new Mock(); - - SetupDataProvider(); - SetupHostController(); - SetupUserController(); - SetupPortalSettings(); - SetupModuleController(); - DeleteIndexFolder(); - - TabController.SetTestableInstance(_mockTabController.Object); - _internalSearchController = InternalSearchController.Instance; - - _mockCBO = new Mock(); + this._mockDataProvider = MockComponentProvider.CreateDataProvider(); + this._mockLocaleController = MockComponentProvider.CreateLocaleController(); + this._mockCachingProvider = MockComponentProvider.CreateDataCacheProvider(); + this._mockDataService = new Mock(); + this._mockUserController = new Mock(); + this._mockModuleController = new Mock(); + this._mockTabController = new Mock(); + this._mockHostController = new Mock(); + + this.SetupDataProvider(); + this.SetupHostController(); + this.SetupUserController(); + this.SetupPortalSettings(); + this.SetupModuleController(); + this.DeleteIndexFolder(); + + TabController.SetTestableInstance(this._mockTabController.Object); + this._internalSearchController = InternalSearchController.Instance; + + this._mockCBO = new Mock(); var tabKey = string.Format("{0}-{1}", TabSearchTypeId, 0); var userKey = string.Format("{0}-{1}", UserSearchTypeId, 0); - _mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) + this._mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new Dictionary() { { tabKey, TabSearchTypeName }, { userKey, UserSearchTypeName } }); - CBO.SetTestableInstance(_mockCBO.Object); + CBO.SetTestableInstance(this._mockCBO.Object); - //create instance of the SearchServiceController + // create instance of the SearchServiceController var request = new HttpRequestMessage(); var configuration = new HttpConfiguration(); var provider = new Mock(); @@ -139,114 +130,223 @@ public void SetUp() provider.Setup(x => x.TryFindModuleInfo(request, out expectedModule)).Returns(true); configuration.AddTabAndModuleInfoProvider(provider.Object); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; - _searchServiceController = new SearchServiceController(HtmlModDefId){Request = request }; + this._searchServiceController = new SearchServiceController(HtmlModDefId) { Request = request }; - CreateNewLuceneControllerInstance(); + this.CreateNewLuceneControllerInstance(); } + [TearDown] public void TearDown() { - _luceneController.Dispose(); - DeleteIndexFolder(); + this._luceneController.Dispose(); + this.DeleteIndexFolder(); CBO.ClearInstance(); TabController.ClearInstance(); InternalSearchController.ClearInstance(); UserController.ClearInstance(); PortalController.ClearInstance(); ModuleController.ClearInstance(); + } + + [Test] + public void GetSearchResultsDetailed() + { + const string keyword = "super"; + const string moduleBody = "super content is here"; + const string userUrl = "mysite/userid/1"; + const string tabUrl1 = "mysite/Home"; + const string tabUrl2 = "mysite/AboutUs"; + + // first tab with 2 modules + var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId2, Body = moduleBody, RoleId = 731 }; + var doc3 = new SearchDocument { UniqueKey = "key03", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId1, Body = moduleBody, RoleId = 731 }; + + // second tab with 1 module + var doc4 = new SearchDocument { UniqueKey = "key04", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId0 }; + var doc5 = new SearchDocument { UniqueKey = "key05", TabId = TabId2, Title = keyword, Url = tabUrl2, SearchTypeId = ModuleSearchTypeId, ModuleDefId = HtmlModuleId, ModuleId = HtmlModuleId3, ModifiedTimeUtc = DateTime.UtcNow, Body = moduleBody, RoleId = 731 }; + + // user doc + var userdoc = new SearchDocument { UniqueKey = "key06", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId731 }; + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.AddSearchDocument(doc4); + this._internalSearchController.AddSearchDocument(doc5); + this._internalSearchController.AddSearchDocument(userdoc); + + var query = new SearchQuery + { + KeyWords = keyword, + SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, + RoleId = 731, + }; + + // Run + var search = this.GetGroupedDetailViewResults(query); + + // Assert + var groupedDetailViews = search as List ?? search.ToList(); + + // Overall 3 groups - tab1, tab2 and user + Assert.AreEqual(3, groupedDetailViews.Count()); + + // Tab 1 has 2 DetailViews + Assert.AreEqual(2, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl1).Results.Count()); + + // Tab 2 has 1 DetailViews + Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl2).Results.Count()); + + // UserUrl has 1 DetailViews + Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == userUrl).Results.Count()); } - #endregion - #region Private Methods + [Test] + public void GetSearchResultsBasic() + { + const string keyword = "awesome"; + const string userUrl = "mysite/userid/1"; + const string tabUrl1 = "mysite/Home"; + const string tabUrl2 = "mysite/AboutUs"; + + var now = DateTime.UtcNow; + var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId731 }; + var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; + var userdoc = new SearchDocument { UniqueKey = "key03", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; + + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(userdoc); + this._internalSearchController.Commit(); + + var query = new SearchQuery + { + KeyWords = keyword, + PortalIds = new List { PortalId0 }, + SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, + BeginModifiedTimeUtc = now.AddMinutes(-1), + EndModifiedTimeUtc = now.AddMinutes(+1), + PageIndex = 1, + PageSize = 15, + SortField = 0, + TitleSnippetLength = 120, + BodySnippetLength = 300, + WildCardSearch = true, + }; + + // Run + var search = this.GetGroupBasicViewResults(query); + + // Assert - overall 2 groups: tabs and users + var groupedBasicViews = search as List ?? search.ToList(); + Assert.AreEqual(2, groupedBasicViews.Count()); + + // 1 User results + Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.Count()); + + // User result should have 1 attribute(avatar) + Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.ElementAt(0).Attributes.Count()); + + // 2 Tabs results + Assert.AreEqual(2, groupedBasicViews.Single(x => x.DocumentTypeName == "tab").Results.Count()); + } + private void CreateNewLuceneControllerInstance() { - if (_luceneController != null) + if (this._luceneController != null) { LuceneController.ClearInstance(); - _luceneController.Dispose(); + this._luceneController.Dispose(); } - _luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(_luceneController); + + this._luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this._luceneController); } - private void SetupUserController() + + private void SetupUserController() { - - _mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns( - new UserInfo { UserID = UserId1, Username = UserName1, Profile = new UserProfile {} }); - UserController.SetTestableInstance(_mockUserController.Object); + this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns( + new UserInfo { UserID = UserId1, Username = UserName1, Profile = new UserProfile { } }); + UserController.SetTestableInstance(this._mockUserController.Object); } + private void SetupHostController() { - _mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns( SearchIndexFolder); - _mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())). - Returns(_readerStaleTimeSpan); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())). + Returns(this._readerStaleTimeSpan); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchTitleBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchTagBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchKeywordBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())). + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())). Returns(Constants.DefaultSearchDescriptionBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns( Constants.DefaultSearchAuthorBoost); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns( Constants.DefaultMinLen); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns( Constants.DefaultMaxLen); - _mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns( + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns( DefaultSearchRetryTimes); - HostController.RegisterInstance(_mockHostController.Object); + HostController.RegisterInstance(this._mockHostController.Object); } + private void SetupDataProvider() { - //Standard DataProvider Path for Logging - _mockDataProvider.Setup(d => d.GetProviderPath()).Returns(""); - - _mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(GetPortalsCallBack); - _mockDataProvider.Setup(d => d.GetSearchModules(It.IsAny())).Returns(GetSearchModules); - _mockDataProvider.Setup(d => d.GetModuleDefinitions()).Returns(GetModuleDefinitions); - _mockDataProvider.Setup(d => d.GetAllSearchTypes()).Returns(GetAllSearchTypes); - _mockDataProvider.Setup(d => d.GetUser(It.IsAny(), It.IsAny())).Returns(GetUser); - _mockDataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(GetTabs); - _mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(GetPortalGroups); - - DataService.RegisterInstance(_mockDataService.Object); - - + // Standard DataProvider Path for Logging + this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + this._mockDataProvider.Setup(d => d.GetSearchModules(It.IsAny())).Returns(this.GetSearchModules); + this._mockDataProvider.Setup(d => d.GetModuleDefinitions()).Returns(this.GetModuleDefinitions); + this._mockDataProvider.Setup(d => d.GetAllSearchTypes()).Returns(this.GetAllSearchTypes); + this._mockDataProvider.Setup(d => d.GetUser(It.IsAny(), It.IsAny())).Returns(this.GetUser); + this._mockDataProvider.Setup(d => d.GetTabs(It.IsAny())).Returns(this.GetTabs); + this._mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(this.GetPortalGroups); + + DataService.RegisterInstance(this._mockDataService.Object); } + private void SetupPortalSettings() { var mockPortalController = new Mock(); mockPortalController.Setup(x => x.GetPortal(It.IsAny())).Returns(new PortalInfo { PortalID = PortalId0, PortalGroupID = -1, UserTabId = TabId1, }); PortalController.SetTestableInstance(mockPortalController.Object); } + private void SetupModuleController() { - _mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId1), It.Is(p => p == PortalId0), false)).Returns( + this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId1), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId1, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle1 }); - _mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId2), It.Is(p => p == PortalId0), false)).Returns( + this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId2), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId2, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle2 }); - _mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId3), It.Is(p => p == PortalId0), false)).Returns( + this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId3), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId3, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle3 }); - _mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId4), It.Is(p => p == PortalId0), false)).Returns( + this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId4), It.Is(p => p == PortalId0), false)).Returns( new ModuleInfo { ModuleID = HtmlModuleId4, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle4 }); - ModuleController.SetTestableInstance(_mockModuleController.Object); + ModuleController.SetTestableInstance(this._mockModuleController.Object); } + private void DeleteIndexFolder() { try { - if (Directory.Exists(SearchIndexFolder)) - Directory.Delete(SearchIndexFolder, true); + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } } catch (Exception ex) { Console.WriteLine(ex); } } + private IDataReader GetUser() { var table = new DataTable("Users"); @@ -278,6 +378,7 @@ private IDataReader GetUser() -1, DateTime.Now); return table.CreateDataReader(); } + private IDataReader GetPortalGroups() { var table = new DataTable("ModuleDefinitions"); @@ -295,7 +396,8 @@ private IDataReader GetPortalGroups() table.Rows.Add(0, 0, "test", "descr", "domain", -1, DateTime.Now, -1, DateTime.Now); return table.CreateDataReader(); } - //return 2 test tabs(TabId 56 - Home, TabId 57 - AboutUs) + + // return 2 test tabs(TabId 56 - Home, TabId 57 - AboutUs) private IDataReader GetTabs() { var table = new DataTable("Tabs"); @@ -341,14 +443,14 @@ private IDataReader GetTabs() table.Columns.Add("CreatedOnDate", typeof(DateTime)); table.Columns.Add("LastModifiedByUserID", typeof(int)); table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - table.Rows.Add(56, 5, 0, "Home", null, 0, "//Home", "C3174A2E-374D-4779-BE5F-BCDFF410E097", "A111A742-C18F-495D-8A23-BD0ECC70BBFE", null, "3A34424A-3CCA-4934-AE15-B9A80EB6D259", 1, null, null, 0, null, null, null, 0, "[G]Skins/Xcillion/Inner.ascx", "[G]Containers/Xcillion/NoTitle.ascx", null, null, null, "false", null, null, 0, 0, 0.5, 86, "Home", 1, -1, null, 0, null, null, -1, DateTime.Now, -1, DateTime.Now); - table.Rows.Add(57, 13, 0, "About Us", null, 0, "//AboutUs", "26A4236F-3AAA-4E15-8908-45D35675C677", "8426D3BC-E930-49CA-BDEB-4D41F194B6AC", null, "1461572D-97E8-41F8-BB1A-916DCA48890A", 1, null, null, 0, null, null, null, 0, "[G]Skins/Xcillion/Inner.ascx", "[G]Containers/Xcillion/NoTitle.ascx", null, null, null, "true", null, null, 0, 0, 0.5, 97, "About Us", 1, -1, null, 0, null, null, -1, DateTime.Now, -1, DateTime.Now); - + table.Rows.Add(56, 5, 0, "Home", null, 0, "//Home", "C3174A2E-374D-4779-BE5F-BCDFF410E097", "A111A742-C18F-495D-8A23-BD0ECC70BBFE", null, "3A34424A-3CCA-4934-AE15-B9A80EB6D259", 1, null, null, 0, null, null, null, 0, "[G]Skins/Xcillion/Inner.ascx", "[G]Containers/Xcillion/NoTitle.ascx", null, null, null, "false", null, null, 0, 0, 0.5, 86, "Home", 1, -1, null, 0, null, null, -1, DateTime.Now, -1, DateTime.Now); + table.Rows.Add(57, 13, 0, "About Us", null, 0, "//AboutUs", "26A4236F-3AAA-4E15-8908-45D35675C677", "8426D3BC-E930-49CA-BDEB-4D41F194B6AC", null, "1461572D-97E8-41F8-BB1A-916DCA48890A", 1, null, null, 0, null, null, null, 0, "[G]Skins/Xcillion/Inner.ascx", "[G]Containers/Xcillion/NoTitle.ascx", null, null, null, "true", null, null, 0, 0, 0.5, 97, "About Us", 1, -1, null, 0, null, null, -1, DateTime.Now, -1, DateTime.Now); + return table.CreateDataReader(); } - //return 4 html modules (TabId 56 - Home: ModuleIDs:367, 368, 370 TabId 57 - AboutUs: 378//) + + // return 4 html modules (TabId 56 - Home: ModuleIDs:367, 368, 370 TabId 57 - AboutUs: 378//) private IDataReader GetSearchModules() { var table = new DataTable("SearchModules"); @@ -407,49 +509,50 @@ private IDataReader GetSearchModules() table.Columns.Add("defaultLanguageGuid", typeof(Guid)); table.Columns.Add("localizedVersionGuid", typeof(Guid)); table.Columns.Add("CultureCode", typeof(string)); - + table.Rows.Add(0, 0, 56, 57, 368, 116, 1, "contentpane", "Text/HTML", 1200, - "FileModuleCachingProvider", null, null, null, "", 0, 0, 0, null, null, null, null, + "FileModuleCachingProvider", null, null, null, string.Empty, 0, 0, 0, null, null, null, null, "[G]Containers/Xcillion/NoTitle.ascx", 1, 0, 0, 0, null, null, 0, 1, 1, 1, 74, 1200, 238, "DotNetNuke.Modules.Html.HtmlTextController, DotNetNuke.Modules.Html", 0, 7, 92, "Text/HTML", 2, null, 0, null, -1, "2014-02-18 10:39:45.170", -1, "2014-02-18 10:39:45.170", "2014-02-18 10:39:45.190", "A0B23459-676C-4DE4-BCA1-33E222F8405A", "85AF4947-EB80-475D-9D8D-0BAD6B026A2B", null, - "664BAA98-7E24-461F-8180-36527619D042", ""); + "664BAA98-7E24-461F-8180-36527619D042", string.Empty); table.Rows.Add(0, 0, 56, 56, 367, 116, 1, "contentpane", "Header Images", 1200, - "FileModuleCachingProvider", null, null, null, "", 0, 0, 0, null, null, null, null, + "FileModuleCachingProvider", null, null, null, string.Empty, 0, 0, 0, null, null, null, null, "[G]Containers/Xcillion/NoTitle.ascx", 1, 0, 0, 0, null, null, 0, 1, 1, 1, 74, 1200, 238, "DotNetNuke.Modules.Html.HtmlTextController, DotNetNuke.Modules.Html", 0, 7, 91, "Header Images", 2, null, 0, null, -1, "2014-02-18 10:39:45.170", -1, "2014-02-18 10:39:45.170", "2014-02-18 10:39:45.190", "A0B23459-676C-4DE4-BCA1-33E222F8405A", "85AF4947-EB80-475D-9D8D-0BAD6B026A2B", null, - "664BAA98-7E24-461F-8180-36527619D042", ""); + "664BAA98-7E24-461F-8180-36527619D042", string.Empty); table.Rows.Add(0, 0, 56, 59, 370, 116, 1, "contentpane", "Customer Support", 1200, - "FileModuleCachingProvider", null, null, null, "", 0, 0, 0, null, null, null, null, + "FileModuleCachingProvider", null, null, null, string.Empty, 0, 0, 0, null, null, null, null, "[G]Containers/Xcillion/NoTitle.ascx", 1, 0, 0, 0, null, null, 0, 1, 1, 1, 74, 1200, 238, "DotNetNuke.Modules.Html.HtmlTextController, DotNetNuke.Modules.Html", 0, 7, 94, "Customer Support", 2, null, 0, null, -1, "2014-02-18 10:39:45.170", -1, "2014-02-18 10:39:45.170", "2014-02-18 10:39:45.190", "A0B23459-676C-4DE4-BCA1-33E222F8405A", "85AF4947-EB80-475D-9D8D-0BAD6B026A2B", null, - "664BAA98-7E24-461F-8180-36527619D042", ""); + "664BAA98-7E24-461F-8180-36527619D042", string.Empty); table.Rows.Add(0, 0, 57, 67, 378, 116, 1, "contentpane", "About Us", 1200, - "FileModuleCachingProvider", null, null, null, "", 0, 0, 0, null, null, null, null, + "FileModuleCachingProvider", null, null, null, string.Empty, 0, 0, 0, null, null, null, null, "[G]Containers/Xcillion/NoTitle.ascx", 1, 0, 0, 0, null, null, 0, 1, 1, 1, 74, 1200, 238, "DotNetNuke.Modules.Html.HtmlTextController, DotNetNuke.Modules.Html", 0, 7, 103, "Text/HTML", 2, null, 0, null, -1, "2014-02-18 10:39:45.170", -1, "2014-02-18 10:39:45.170", "2014-02-18 10:39:45.190", "A0B23459-676C-4DE4-BCA1-33E222F8405A", "85AF4947-EB80-475D-9D8D-0BAD6B026A2B", null, - "664BAA98-7E24-461F-8180-36527619D042", ""); + "664BAA98-7E24-461F-8180-36527619D042", string.Empty); return table.CreateDataReader(); } - //returns 2 moduledefinitions - Text/HTML and Journal + + // returns 2 moduledefinitions - Text/HTML and Journal private IDataReader GetModuleDefinitions() { var table = new DataTable("ModuleDefinitions"); @@ -469,8 +572,9 @@ private IDataReader GetModuleDefinitions() return table.CreateDataReader(); } - //returns all search types - 3 SearchTypes - module, tab, user - private IDataReader GetAllSearchTypes() + + // returns all search types - 3 SearchTypes - module, tab, user + private IDataReader GetAllSearchTypes() { var table = new DataTable("SearchTypes"); var pkId = table.Columns.Add("SearchTypeId", typeof(int)); @@ -484,10 +588,12 @@ private IDataReader GetAllSearchTypes() table.Rows.Add(3, "user", FakeResultControllerClass, 0); return table.CreateDataReader(); } + private IDataReader GetPortalsCallBack(string culture) { - return GetPortalCallBack(PortalId0, CultureEnUs); + return this.GetPortalCallBack(PortalId0, CultureEnUs); } + private IDataReader GetPortalCallBack(int portalId, string culture) { DataTable table = new DataTable("Portal"); @@ -503,7 +609,7 @@ private IDataReader GetPortalCallBack(int portalId, string culture) "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", - "CultureCode" + "CultureCode", }; foreach (var col in cols) @@ -520,9 +626,8 @@ private IDataReader GetPortalCallBack(int portalId, string culture) "-1", "2011-08-25 07:34:29", culture); return table.CreateDataReader(); - } - #endregion - + } + private IEnumerable GetGroupBasicViewResults(SearchQuery query) { var userSearchContentSource = new SearchContentSource @@ -531,9 +636,9 @@ private IEnumerable GetGroupBasicViewResults(SearchQuery query SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass, LocalizedName = UserSearchTypeName, - ModuleDefinitionId = 0 + ModuleDefinitionId = 0, }; - var results = _searchServiceController.GetGroupedBasicViews(query, userSearchContentSource, PortalId0); + var results = this._searchServiceController.GetGroupedBasicViews(query, userSearchContentSource, PortalId0); return results; } @@ -541,116 +646,14 @@ private IEnumerable GetGroupedDetailViewResults(SearchQuery s { bool more = false; int totalHits = 0; - var results = _searchServiceController.GetGroupedDetailViews(searchQuery, UserSearchTypeId, out totalHits, out more); + var results = this._searchServiceController.GetGroupedDetailViews(searchQuery, UserSearchTypeId, out totalHits, out more); return results; } - [Test] - public void GetSearchResultsDetailed() - { - const string keyword = "super"; - const string moduleBody = "super content is here"; - const string userUrl = "mysite/userid/1"; - const string tabUrl1 = "mysite/Home"; - const string tabUrl2 = "mysite/AboutUs"; - - //first tab with 2 modules - var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId2, Body = moduleBody, RoleId = 731}; - var doc3 = new SearchDocument { UniqueKey = "key03", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId1, Body = moduleBody, RoleId = 731 }; - - //second tab with 1 module - var doc4 = new SearchDocument { UniqueKey = "key04", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId0 }; - var doc5 = new SearchDocument { UniqueKey = "key05", TabId = TabId2, Title = keyword, Url = tabUrl2, SearchTypeId = ModuleSearchTypeId, ModuleDefId = HtmlModuleId, ModuleId = HtmlModuleId3, ModifiedTimeUtc = DateTime.UtcNow, Body = moduleBody, RoleId = 731 }; - - //user doc - var userdoc = new SearchDocument { UniqueKey = "key06", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId731 }; - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(doc3); - _internalSearchController.AddSearchDocument(doc4); - _internalSearchController.AddSearchDocument(doc5); - _internalSearchController.AddSearchDocument(userdoc); - - var query = new SearchQuery - { - KeyWords = keyword, - SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, - RoleId = 731 - }; - - //Run - var search = GetGroupedDetailViewResults(query); - - //Assert - var groupedDetailViews = search as List ?? search.ToList(); - - //Overall 3 groups - tab1, tab2 and user - Assert.AreEqual(3, groupedDetailViews.Count()); - - //Tab 1 has 2 DetailViews - Assert.AreEqual(2, groupedDetailViews.Single(x=>x.DocumentUrl==tabUrl1).Results.Count()); - - //Tab 2 has 1 DetailViews - Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl2).Results.Count()); - - //UserUrl has 1 DetailViews - Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == userUrl).Results.Count()); - } - - [Test] - public void GetSearchResultsBasic() - { - const string keyword = "awesome"; - const string userUrl = "mysite/userid/1"; - const string tabUrl1 = "mysite/Home"; - const string tabUrl2 = "mysite/AboutUs"; - - var now = DateTime.UtcNow; - var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId731 }; - var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; - var userdoc = new SearchDocument { UniqueKey = "key03", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; - - _internalSearchController.AddSearchDocument(doc1); - _internalSearchController.AddSearchDocument(doc2); - _internalSearchController.AddSearchDocument(userdoc); - _internalSearchController.Commit(); - - var query = new SearchQuery - { - KeyWords = keyword, - PortalIds = new List { PortalId0 }, - SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, - BeginModifiedTimeUtc = now.AddMinutes(-1), - EndModifiedTimeUtc = now.AddMinutes(+1), - PageIndex = 1, - PageSize = 15, - SortField = 0, - TitleSnippetLength = 120, - BodySnippetLength = 300, - WildCardSearch = true - }; - - //Run - var search = GetGroupBasicViewResults(query); - //Assert - overall 2 groups: tabs and users - var groupedBasicViews = search as List ?? search.ToList(); - Assert.AreEqual(2, groupedBasicViews.Count()); - - //1 User results - Assert.AreEqual(1, groupedBasicViews.Single(x=>x.DocumentTypeName=="user").Results.Count()); - - //User result should have 1 attribute(avatar) - Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.ElementAt(0).Attributes.Count()); - - //2 Tabs results - Assert.AreEqual(2, groupedBasicViews.Single(x => x.DocumentTypeName == "tab").Results.Count()); - } - [Test] public void ModifyingDocumentsDoesNotCreateDuplicates() { - //Arrange + // Arrange const string tabUrl = "mysite/ContentUrl"; const string title = "content title"; const string contentBody = "content body"; @@ -670,11 +673,11 @@ public void ModifyingDocumentsDoesNotCreateDuplicates() PortalId = PortalId0, RoleId = RoleId731, Keywords = { { "description", "mycontent" } }, - NumericKeys = { {"points", 5} } + NumericKeys = { { "points", 5 } }, }; - _internalSearchController.AddSearchDocument(originalDocument); - _internalSearchController.Commit(); + this._internalSearchController.AddSearchDocument(originalDocument); + this._internalSearchController.Commit(); var modifiedDocument = new SearchDocument { @@ -688,11 +691,11 @@ public void ModifyingDocumentsDoesNotCreateDuplicates() PortalId = PortalId0, RoleId = RoleId731, Keywords = { { "description", "mycontent_modified" }, { "description2", "mycontent_modified" } }, - NumericKeys = { { "points", 8 }, {"point2", 7 } } + NumericKeys = { { "points", 8 }, { "point2", 7 } }, }; - _internalSearchController.AddSearchDocument(modifiedDocument); - _internalSearchController.Commit(); + this._internalSearchController.AddSearchDocument(modifiedDocument); + this._internalSearchController.Commit(); var query = new SearchQuery { @@ -706,13 +709,13 @@ public void ModifyingDocumentsDoesNotCreateDuplicates() SortField = 0, TitleSnippetLength = 120, BodySnippetLength = 300, - WildCardSearch = true + WildCardSearch = true, }; - //Run - var searchResults = GetGroupedDetailViewResults(query).ToList(); + // Run + var searchResults = this.GetGroupedDetailViewResults(query).ToList(); - //Assert + // Assert Assert.AreEqual(1, searchResults.Count()); Assert.AreEqual(1, searchResults.First().Results.Count); Assert.AreEqual(tabUrl, searchResults.First().Results.First().DocumentUrl); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs index 14503c46712..436e343de39 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs @@ -1,35 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; - -using NUnit.Framework; -using Moq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs.TabVersions; -using DotNetNuke.Tests.Utilities.Mocks; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Common; -using System.Collections; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.InternalServices { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Tests.Utilities.Mocks; + using Moq; + using NUnit.Framework; + [TestFixture] public class TabVersionControllerTests { - + private const int UserID = 1; + private const int TabID = 99; + + private Mock _mockCBO; + private Mock _mockUserController; + private Mock _mockHostController; + private class TabVersionControllerTestable : TabVersionController { } private class DateUtilsTestable : DateUtils { - public new static TimeZoneInfo GetDatabaseDateTimeOffset() + public static new TimeZoneInfo GetDatabaseDateTimeOffset() { var timeZoneId = "UTC"; return TimeZoneInfo.CreateCustomTimeZone(timeZoneId, new TimeSpan(0, 0, 0), timeZoneId, timeZoneId); @@ -46,31 +51,23 @@ public static IEnumerable TestCases() } } - private Mock _mockCBO; - private Mock _mockUserController; - private Mock _mockHostController; - - private const int UserID = 1; - private const int TabID = 99; - // Assuming 12:00 Aug 15, 2018 server local time private readonly DateTime ServerCreateOnDate = new DateTime(2018, 08, 15, 12, 0, 0, DateTimeKind.Unspecified); - - + [SetUp] public void Setup() { MockComponentProvider.ResetContainer(); - SetupCBO(); - SetupHostController(); + this.SetupCBO(); + this.SetupHostController(); } - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void GetTabVersions_Verify_User_Preferred_TimeZone(string userPreferredTimeZone, DateTime expectedDateTime) { - // Arrange - SetupUserController(userPreferredTimeZone); + this.SetupUserController(userPreferredTimeZone); // Act var tabVersionController = new TabVersionControllerTestable(); @@ -87,23 +84,24 @@ public void GetTabVersions_Verify_User_Preferred_TimeZone(string userPreferredTi private void SetupCBO() { - _mockCBO = new Mock(); - _mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(GetMockedTabVersions); - CBO.SetTestableInstance(_mockCBO.Object); + this._mockCBO = new Mock(); + this._mockCBO.Setup(c => c.GetCachedObject>(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(this.GetMockedTabVersions); + CBO.SetTestableInstance(this._mockCBO.Object); } private void SetupUserController(string timeZoneId) { - _mockUserController = new Mock(); - _mockUserController.Setup(userController => userController.GetCurrentUserInfo()).Returns(GetMockedUser(timeZoneId)); - UserController.SetTestableInstance(_mockUserController.Object); + this._mockUserController = new Mock(); + this._mockUserController.Setup(userController => userController.GetCurrentUserInfo()).Returns(this.GetMockedUser(timeZoneId)); + UserController.SetTestableInstance(this._mockUserController.Object); } private UserInfo GetMockedUser(string timeZoneId) { - var profile = new UserProfile() { - PreferredTimeZone = GetMockedUserTimeZone(timeZoneId) + var profile = new UserProfile() + { + PreferredTimeZone = this.GetMockedUserTimeZone(timeZoneId), }; profile.ProfileProperties.Add(new Entities.Profile.ProfilePropertyDefinition(99) @@ -112,13 +110,13 @@ private UserInfo GetMockedUser(string timeZoneId) PropertyDefinitionId = 20, PropertyCategory = "Preferences", PropertyName = "PreferredTimeZone", - PropertyValue = GetMockedUserTimeZone(timeZoneId).Id + PropertyValue = this.GetMockedUserTimeZone(timeZoneId).Id, }); var user = new UserInfo() { Profile = profile, UserID = UserID, - PortalID = 99 + PortalID = 99, }; return user; @@ -137,9 +135,9 @@ private TabVersion GetMockedTabVersion() TabId = TabID, TabVersionId = 1, Version = 1, - CreatedByUserID = UserID + CreatedByUserID = UserID, }; - tabVersion.GetType().BaseType.GetProperty("CreatedOnDate").SetValue(tabVersion, ServerCreateOnDate, null); + tabVersion.GetType().BaseType.GetProperty("CreatedOnDate").SetValue(tabVersion, this.ServerCreateOnDate, null); return tabVersion; } @@ -148,16 +146,15 @@ private List GetMockedTabVersions() { return new List() { - GetMockedTabVersion() + this.GetMockedTabVersion(), }; } private void SetupHostController() { - _mockHostController = new Mock(); - _mockHostController.Setup(c => c.GetString(It.IsRegex("PerformanceSetting"))).Returns(Globals.PerformanceSettings.LightCaching.ToString()); - HostController.RegisterInstance(_mockHostController.Object); + this._mockHostController = new Mock(); + this._mockHostController.Setup(c => c.GetString(It.IsRegex("PerformanceSetting"))).Returns(Globals.PerformanceSettings.LightCaching.ToString()); + HostController.RegisterInstance(this._mockHostController.Object); } } - } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs index 73cd3129cb3..7c01201f655 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs @@ -1,64 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Mvp; - -using Moq; - -using NUnit.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Tests.Web.Mvp { + using System; + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Mvp; + using Moq; + using NUnit.Framework; + [TestFixture] public class ModuleSettingsPresenterTests - { - #region Private Members - + { private const int _moduleSettingCount = 2; private const string _moduleSettingName = "moduleKey{0}"; private const string _moduleSettingValue = "value{0}"; private const int _tabModuleSettingCount = 3; private const string _tabModuleSettingName = "tabModuleKey{0}"; - private const string _tabModuleSettingValue = "value{0}"; - - #endregion - - #region Embedded Classes for Testing - - public class TestSettingsPresenter : ModuleSettingsPresenter, SettingsModel> - { - public TestSettingsPresenter(ISettingsView view) - : base(view) - { - - } - } - - #endregion - - #region Tests - + private const string _tabModuleSettingValue = "value{0}"; + [Test] public void ModuleSettingsPresenter_Load_Initialises_Both_Dictionaries_On_PostBack() { - //Arrange + // Arrange var view = new Mock>(); view.SetupGet(v => v.Model).Returns(new SettingsModel()); - var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = CreateModuleContext() }; + var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() }; presenter.IsPostBack = true; - //Act + // Act view.Raise(v => v.Load += null, EventArgs.Empty); - //Assert + // Assert Assert.IsInstanceOf>(view.Object.Model.ModuleSettings); Assert.AreEqual(0, view.Object.Model.ModuleSettings.Count); @@ -69,17 +48,17 @@ public void ModuleSettingsPresenter_Load_Initialises_Both_Dictionaries_On_PostBa [Test] public void ModuleSettingsPresenter_Load_Does_Not_Initialise_Dictionaries_If_Not_PostBack() { - //Arrange + // Arrange var view = new Mock>(); view.SetupGet(v => v.Model).Returns(new SettingsModel()); - var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = CreateModuleContext() }; + var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() }; presenter.IsPostBack = false; - //Act + // Act view.Raise(v => v.Load += null, EventArgs.Empty); - //Assert + // Assert Assert.IsNull(view.Object.Model.ModuleSettings); Assert.IsNull(view.Object.Model.TabModuleSettings); } @@ -87,44 +66,51 @@ public void ModuleSettingsPresenter_Load_Does_Not_Initialise_Dictionaries_If_Not [Test] public void ModuleSettingsPresenter_LoadSettings_Loads_Both_Dictionaries() { - //Arrange + // Arrange var view = new Mock>(); view.SetupGet(v => v.Model).Returns(new SettingsModel()); - var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = CreateModuleContext() }; + var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() }; presenter.IsPostBack = false; view.Raise(v => v.Load += null, EventArgs.Empty); - //Act + // Act view.Raise(v => v.OnLoadSettings += null, EventArgs.Empty); - //Assert + // Assert Assert.IsInstanceOf>(view.Object.Model.ModuleSettings); Assert.AreEqual(_moduleSettingCount, view.Object.Model.ModuleSettings.Count); Assert.IsInstanceOf>(view.Object.Model.TabModuleSettings); Assert.AreEqual(_tabModuleSettingCount, view.Object.Model.TabModuleSettings.Count); } + + public class TestSettingsPresenter : ModuleSettingsPresenter, SettingsModel> + { + public TestSettingsPresenter(ISettingsView view) + : base(view) + { + } + } [Test] public void ModuleSettingsPresenter_SaveSettings_Saves_ModuleSettings() { - //Arrange + // Arrange var view = new Mock>(); view.SetupGet(v => v.Model).Returns(new SettingsModel()); var controller = new Mock(); - - - var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = CreateModuleContext() }; + + var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() }; presenter.IsPostBack = true; view.Raise(v => v.Load += null, EventArgs.Empty); - //Act + // Act view.Raise(v => v.OnSaveSettings += null, EventArgs.Empty); - //Assert + // Assert foreach (var setting in view.Object.Model.ModuleSettings) { var key = setting.Key; @@ -136,21 +122,20 @@ public void ModuleSettingsPresenter_SaveSettings_Saves_ModuleSettings() [Test] public void ModuleSettingsPresenter_SaveSettings_Saves_TabModuleSettings() { - //Arrange + // Arrange var view = new Mock>(); view.SetupGet(v => v.Model).Returns(new SettingsModel()); var controller = new Mock(); - - - var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = CreateModuleContext() }; + + var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() }; presenter.IsPostBack = true; view.Raise(v => v.Load += null, EventArgs.Empty); - //Act + // Act view.Raise(v => v.OnSaveSettings += null, EventArgs.Empty); - //Assert + // Assert foreach (var setting in view.Object.Model.TabModuleSettings) { var key = setting.Key; @@ -161,19 +146,18 @@ public void ModuleSettingsPresenter_SaveSettings_Saves_TabModuleSettings() private ModuleInstanceContext CreateModuleContext() { - var context = new ModuleInstanceContext {Configuration = new ModuleInfo()}; + var context = new ModuleInstanceContext { Configuration = new ModuleInfo() }; for (int i = 1; i <= _moduleSettingCount; i++) { - context.Configuration.ModuleSettings.Add(String.Format(_moduleSettingName, i), String.Format(_moduleSettingValue, i)); + context.Configuration.ModuleSettings.Add(string.Format(_moduleSettingName, i), string.Format(_moduleSettingValue, i)); } + for (int i = 1; i <= _tabModuleSettingCount; i++) { - context.Configuration.TabModuleSettings.Add(String.Format(_tabModuleSettingName, i), String.Format(_tabModuleSettingValue, i)); + context.Configuration.TabModuleSettings.Add(string.Format(_tabModuleSettingName, i), string.Format(_tabModuleSettingValue, i)); } return context; - } - - #endregion + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Properties/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Properties/AssemblyInfo.cs index 7dbbe43a1db..f272d3c7806 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Properties/AssemblyInfo.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Properties/AssemblyInfo.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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("DotNetNuke.Web.Tests")] @@ -18,8 +18,8 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// 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 +// 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)] @@ -29,11 +29,11 @@ // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config index ac1084c42d4..b736bdf53e0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config @@ -1,14 +1,15 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Website/App_GlobalResources/Exceptions.resx b/DNN Platform/Website/App_GlobalResources/Exceptions.resx index 620532be696..97ed37d7fd3 100644 --- a/DNN Platform/Website/App_GlobalResources/Exceptions.resx +++ b/DNN Platform/Website/App_GlobalResources/Exceptions.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -244,7 +244,7 @@ Either Sender is null or Sender.UserID is negative. - Users doesn't allow send message to other user/group in current message settings. + Current messaging settings do not allow sending messages to other users/groups. Only Super Users, Administrators and group members can send messages to the role. @@ -394,7 +394,7 @@ Author cannot be found. Notification won't be sent. - Cannot discard on last workflow state. + Cannot discard the last workflow state. Cannot delete a state in use. diff --git a/DNN Platform/Website/App_GlobalResources/FileUpload.resx b/DNN Platform/Website/App_GlobalResources/FileUpload.resx index f9488af3099..c6f32434fd2 100644 --- a/DNN Platform/Website/App_GlobalResources/FileUpload.resx +++ b/DNN Platform/Website/App_GlobalResources/FileUpload.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/App_GlobalResources/GlobalResources.resx b/DNN Platform/Website/App_GlobalResources/GlobalResources.resx index 6dabec88f2a..75b8b707f0a 100644 --- a/DNN Platform/Website/App_GlobalResources/GlobalResources.resx +++ b/DNN Platform/Website/App_GlobalResources/GlobalResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -782,11 +782,11 @@ Thank you, <br /> Examples:<br /> - URL: http://www.domain.com/default.aspx = Domain Name: www.domain.com<br /> - URL: http://209.75.24.131/default.aspx = Domain Name: 209.75.24.131<br /> - URL: http://localhost/DotNetNuke/default.aspx = Domain Name: localhost/DotNetNuke<br /> - URL: http://www.domain.com/virtualdirectory/default.aspx = Domain Name: www.domain.com/virtualdirectory<br /> - URL: http://www.domain.com/directory/default.aspx = Domain Name: www.domain.com/directory<br /> + URL: https://www.domain.com/default.aspx = Domain Name: www.domain.com<br /> + URL: https://209.75.24.131/default.aspx = Domain Name: 209.75.24.131<br /> + URL: https://localhost/DotNetNuke/default.aspx = Domain Name: localhost/DotNetNuke<br /> + URL: https://www.domain.com/virtualdirectory/default.aspx = Domain Name: www.domain.com/virtualdirectory<br /> + URL: https://www.domain.com/directory/default.aspx = Domain Name: www.domain.com/directory<br /> <br /> </li> <li>Using the domain name, the application queries the database ( PortalAlias table - column HTTTPAlias) to locate a matching record.<br /> @@ -1129,8 +1129,8 @@ Please do not reply to this email. The submitted URL is not available. If you wish to accept the suggested alternative, please click Save. - <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style type="text/css"> diff --git a/DNN Platform/Website/App_GlobalResources/SharedResources.resx b/DNN Platform/Website/App_GlobalResources/SharedResources.resx index f9eb9598115..a75e10646b1 100644 --- a/DNN Platform/Website/App_GlobalResources/SharedResources.resx +++ b/DNN Platform/Website/App_GlobalResources/SharedResources.resx @@ -334,7 +334,7 @@ You do not have access to view this module within the site. - A critical error has occurred. Please check the Event Viewer for further details. + A critical error has occurred. Please check the Admin Logs for further details. Unhandled error loading module. diff --git a/DNN Platform/Website/App_GlobalResources/WebControls.resx b/DNN Platform/Website/App_GlobalResources/WebControls.resx index 6808c28ae43..ecb7a6f5407 100644 --- a/DNN Platform/Website/App_GlobalResources/WebControls.resx +++ b/DNN Platform/Website/App_GlobalResources/WebControls.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -232,7 +232,7 @@ File upload stopped - Enter Resource URL like http://SomeWebSite.com/Images/About.png + Enter Resource URL like https://SomeWebSite.com/Images/About.png Keep diff --git a/DNN Platform/Website/Default.aspx.cs b/DNN Platform/Website/Default.aspx.cs index baf895f1c12..46cbd57c23f 100644 --- a/DNN Platform/Website/Default.aspx.cs +++ b/DNN Platform/Website/Default.aspx.cs @@ -1,84 +1,76 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Abstractions; - -using DotNetNuke.Application; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Installer.Blocker; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; -using DotNetNuke.UI; -using DotNetNuke.UI.Internals; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Framework { - using Web.Client; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Application; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Installer.Blocker; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + using DotNetNuke.UI; + using DotNetNuke.UI.Internals; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : CDefault - /// + /// Project : DotNetNuke + /// Class : CDefault + /// /// ----------------------------------------------------------------------------- /// - /// + /// /// /// /// /// ----------------------------------------------------------------------------- public partial class DefaultPage : CDefault, IClientAPICallbackEventHandler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (DefaultPage)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DefaultPage)); - private static readonly Regex HeaderTextRegex = new Regex("])+name=('|\")robots('|\")", + private static readonly Regex HeaderTextRegex = new Regex( + "])+name=('|\")robots('|\")", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); - protected INavigationManager NavigationManager { get; } - public DefaultPage() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } - #region Properties - /// ----------------------------------------------------------------------------- /// - /// Property to allow the programmatic assigning of ScrollTop position + /// Gets or sets property to allow the programmatic assigning of ScrollTop position. /// - /// + /// + /// Property to allow the programmatic assigning of ScrollTop position + /// /// /// /// ----------------------------------------------------------------------------- @@ -87,29 +79,41 @@ public int PageScrollTop get { int pageScrollTop; - var scrollValue = ScrollTop != null ? ScrollTop.Value : ""; + var scrollValue = this.ScrollTop != null ? this.ScrollTop.Value : string.Empty; if (!int.TryParse(scrollValue, out pageScrollTop) || pageScrollTop < 0) { pageScrollTop = Null.NullInteger; } + return pageScrollTop; } - set { ScrollTop.Value = value.ToString(); } + + set { this.ScrollTop.Value = value.ToString(); } } + public string CurrentSkinPath + { + get + { + return ((PortalSettings)HttpContext.Current.Items["PortalSettings"]).ActiveTab.SkinPath; + } + } + + protected INavigationManager NavigationManager { get; } + protected string HtmlAttributeList { get { - if ((HtmlAttributes != null) && (HtmlAttributes.Count > 0)) + if ((this.HtmlAttributes != null) && (this.HtmlAttributes.Count > 0)) { var attr = new StringBuilder(); - foreach (string attributeName in HtmlAttributes.Keys) + foreach (string attributeName in this.HtmlAttributes.Keys) { - if ((!String.IsNullOrEmpty(attributeName)) && (HtmlAttributes[attributeName] != null)) + if ((!string.IsNullOrEmpty(attributeName)) && (this.HtmlAttributes[attributeName] != null)) { - string attributeValue = HtmlAttributes[attributeName]; - if ((attributeValue.IndexOf(",") > 0)) + string attributeValue = this.HtmlAttributes[attributeName]; + if (attributeValue.IndexOf(",") > 0) { var attributeValues = attributeValue.Split(','); for (var attributeCounter = 0; @@ -125,33 +129,24 @@ protected string HtmlAttributeList } } } + return attr.ToString(); } - return string.Empty; - } - } - public string CurrentSkinPath - { - get - { - return ((PortalSettings)HttpContext.Current.Items["PortalSettings"]).ActiveTab.SkinPath; + return string.Empty; } } - - #endregion - - #region IClientAPICallbackEventHandler Members public string RaiseClientAPICallbackEvent(string eventArgument) { - var dict = ParsePageCallBackArgs(eventArgument); + var dict = this.ParsePageCallBackArgs(eventArgument); if (dict.ContainsKey("type")) { if (DNNClientAPI.IsPersonalizationKeyRegistered(dict["namingcontainer"] + ClientAPI.CUSTOM_COLUMN_DELIMITER + dict["key"]) == false) { throw new Exception(string.Format("This personalization key has not been enabled ({0}:{1}). Make sure you enable it with DNNClientAPI.EnableClientPersonalization", dict["namingcontainer"], dict["key"])); } + switch ((DNNClientAPI.PageCallBackType)Enum.Parse(typeof(DNNClientAPI.PageCallBackType), dict["type"])) { case DNNClientAPI.PageCallBackType.GetPersonalization: @@ -163,12 +158,163 @@ public string RaiseClientAPICallbackEvent(string eventArgument) throw new Exception("Unknown Callback Type"); } } + return string.Empty; } - #endregion + protected bool NonProductionVersion() + { + return DotNetNukeContext.Current.Application.Status != ReleaseMode.Stable; + } + + /// ----------------------------------------------------------------------------- + /// + /// Contains the functionality to populate the Root aspx page with controls. + /// + /// + /// + /// - obtain PortalSettings from Current Context + /// - set global page settings. + /// - initialise reference paths to load the cascading style sheets + /// - add skin control placeholder. This holds all the modules and content of the page. + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + // set global page settings + this.InitializePage(); + + // load skin control and register UI js + UI.Skins.Skin ctlSkin; + if (this.PortalSettings.EnablePopUps) + { + ctlSkin = UrlUtils.InPopUp() ? UI.Skins.Skin.GetPopUpSkin(this) : UI.Skins.Skin.GetSkin(this); + + // register popup js + JavaScript.RequestRegistration(CommonJs.jQueryUI); + + var popupFilePath = HttpContext.Current.IsDebuggingEnabled + ? "~/js/Debug/dnn.modalpopup.js" + : "~/js/dnn.modalpopup.js"; + + ClientResourceManager.RegisterScript(this, popupFilePath, FileOrder.Js.DnnModalPopup); + } + else + { + ctlSkin = UI.Skins.Skin.GetSkin(this); + } + + // DataBind common paths for the client resource loader + this.ClientResourceLoader.DataBind(); + this.ClientResourceLoader.PreRender += (sender, args) => JavaScript.Register(this.Page); + + // check for and read skin package level doctype + this.SetSkinDoctype(); + + // Manage disabled pages + if (this.PortalSettings.ActiveTab.DisableLink) + { + if (TabPermissionController.CanAdminPage()) + { + var heading = Localization.GetString("PageDisabled.Header"); + var message = Localization.GetString("PageDisabled.Text"); + UI.Skins.Skin.AddPageMessage(ctlSkin, heading, message, + ModuleMessage.ModuleMessageType.YellowWarning); + } + else + { + if (this.PortalSettings.HomeTabId > 0) + { + this.Response.Redirect(this.NavigationManager.NavigateURL(this.PortalSettings.HomeTabId), true); + } + else + { + this.Response.Redirect(Globals.GetPortalDomainName(this.PortalSettings.PortalAlias.HTTPAlias, this.Request, true), true); + } + } + } + + // Manage canonical urls + if (this.PortalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.CanonicalUrl) + { + string primaryHttpAlias = null; + if (Config.GetFriendlyUrlProvider() == "advanced") // advanced mode compares on the primary alias as set during alias identification + { + if (this.PortalSettings.PrimaryAlias != null && this.PortalSettings.PortalAlias != null) + { + if (string.Compare(this.PortalSettings.PrimaryAlias.HTTPAlias, this.PortalSettings.PortalAlias.HTTPAlias, StringComparison.InvariantCulture) != 0) + { + primaryHttpAlias = this.PortalSettings.PrimaryAlias.HTTPAlias; + } + } + } + else // other modes just depend on the default alias + { + if (string.Compare(this.PortalSettings.PortalAlias.HTTPAlias, this.PortalSettings.DefaultPortalAlias, StringComparison.InvariantCulture) != 0) + { + primaryHttpAlias = this.PortalSettings.DefaultPortalAlias; + } + } + + if (primaryHttpAlias != null && string.IsNullOrEmpty(this.CanonicalLinkUrl)) // a primary http alias was identified + { + var originalurl = this.Context.Items["UrlRewrite:OriginalUrl"].ToString(); + this.CanonicalLinkUrl = originalurl.Replace(this.PortalSettings.PortalAlias.HTTPAlias, primaryHttpAlias); - #region Private Methods + if (UrlUtils.IsSecureConnectionOrSslOffload(this.Request)) + { + this.CanonicalLinkUrl = this.CanonicalLinkUrl.Replace("http://", "https://"); + } + } + } + + // check if running with known account defaults + if (this.Request.IsAuthenticated && string.IsNullOrEmpty(this.Request.QueryString["runningDefault"]) == false) + { + var userInfo = HttpContext.Current.Items["UserInfo"] as UserInfo; + var usernameLower = userInfo?.Username?.ToLowerInvariant(); + + // only show message to default users + if ("admin".Equals(usernameLower) || "host".Equals(usernameLower)) + { + var messageText = this.RenderDefaultsWarning(); + var messageTitle = Localization.GetString("InsecureDefaults.Title", Localization.GlobalResourceFile); + UI.Skins.Skin.AddPageMessage(ctlSkin, messageTitle, messageText, ModuleMessage.ModuleMessageType.RedError); + } + } + + // add CSS links + ClientResourceManager.RegisterDefaultStylesheet(this, string.Concat(Globals.ApplicationPath, "/Resources/Shared/stylesheets/dnndefault/7.0.0/default.css")); + ClientResourceManager.RegisterIEStylesheet(this, string.Concat(Globals.HostPath, "ie.css")); + + ClientResourceManager.RegisterStyleSheet(this, string.Concat(ctlSkin.SkinPath, "skin.css"), FileOrder.Css.SkinCss); + ClientResourceManager.RegisterStyleSheet(this, ctlSkin.SkinSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificSkinCss); + + // add skin to page + this.SkinPlaceHolder.Controls.Add(ctlSkin); + + ClientResourceManager.RegisterStyleSheet(this, string.Concat(this.PortalSettings.HomeDirectory, "portal.css"), FileOrder.Css.PortalCss); + + // add Favicon + this.ManageFavicon(); + + // ClientCallback Logic + ClientAPI.HandleClientAPICallbackEvent(this); + + // add viewstateuserkey to protect against CSRF attacks + if (this.User.Identity.IsAuthenticated) + { + this.ViewStateUserKey = this.User.Identity.Name; + } + + // set the async postback timeout. + if (AJAX.IsEnabled()) + { + AJAX.GetScriptManager(this).AsyncPostBackTimeout = Host.AsyncTimeout; + } + } /// ----------------------------------------------------------------------------- /// @@ -181,93 +327,97 @@ public string RaiseClientAPICallbackEvent(string eventArgument) /// - set page title and stylesheet /// - check to see if we should show the Assembly Version in Page Title /// - set the background image if there is one selected - /// - set META tags, copyright, keywords and description + /// - set META tags, copyright, keywords and description. /// /// ----------------------------------------------------------------------------- private void InitializePage() { - //There could be a pending installation/upgrade process + // There could be a pending installation/upgrade process if (InstallBlocker.Instance.IsInstallInProgress()) { Exceptions.ProcessHttpException(new HttpException(503, Localization.GetString("SiteAccessedWhileInstallationWasInProgress.Error", Localization.GlobalResourceFile))); } - //Configure the ActiveTab with Skin/Container information - PortalSettingsController.Instance().ConfigureActiveTab(PortalSettings); + // Configure the ActiveTab with Skin/Container information + PortalSettingsController.Instance().ConfigureActiveTab(this.PortalSettings); - //redirect to a specific tab based on name - if (!String.IsNullOrEmpty(Request.QueryString["tabname"])) + // redirect to a specific tab based on name + if (!string.IsNullOrEmpty(this.Request.QueryString["tabname"])) { - TabInfo tab = TabController.Instance.GetTabByName(Request.QueryString["TabName"], PortalSettings.PortalId); + TabInfo tab = TabController.Instance.GetTabByName(this.Request.QueryString["TabName"], this.PortalSettings.PortalId); if (tab != null) { - var parameters = new List(); //maximum number of elements - for (int intParam = 0; intParam <= Request.QueryString.Count - 1; intParam++) + var parameters = new List(); // maximum number of elements + for (int intParam = 0; intParam <= this.Request.QueryString.Count - 1; intParam++) { - switch (Request.QueryString.Keys[intParam].ToLowerInvariant()) + switch (this.Request.QueryString.Keys[intParam].ToLowerInvariant()) { case "tabid": case "tabname": break; default: parameters.Add( - Request.QueryString.Keys[intParam] + "=" + Request.QueryString[intParam]); + this.Request.QueryString.Keys[intParam] + "=" + this.Request.QueryString[intParam]); break; } } - Response.Redirect(NavigationManager.NavigateURL(tab.TabID, Null.NullString, parameters.ToArray()), true); + + this.Response.Redirect(this.NavigationManager.NavigateURL(tab.TabID, Null.NullString, parameters.ToArray()), true); } else { - //404 Error - Redirect to ErrorPage - Exceptions.ProcessHttpException(Request); + // 404 Error - Redirect to ErrorPage + Exceptions.ProcessHttpException(this.Request); } } - string cacheability = Request.IsAuthenticated ? Host.AuthenticatedCacheability : Host.UnauthenticatedCacheability; + + string cacheability = this.Request.IsAuthenticated ? Host.AuthenticatedCacheability : Host.UnauthenticatedCacheability; switch (cacheability) { case "0": - Response.Cache.SetCacheability(HttpCacheability.NoCache); + this.Response.Cache.SetCacheability(HttpCacheability.NoCache); break; case "1": - Response.Cache.SetCacheability(HttpCacheability.Private); + this.Response.Cache.SetCacheability(HttpCacheability.Private); break; case "2": - Response.Cache.SetCacheability(HttpCacheability.Public); + this.Response.Cache.SetCacheability(HttpCacheability.Public); break; case "3": - Response.Cache.SetCacheability(HttpCacheability.Server); + this.Response.Cache.SetCacheability(HttpCacheability.Server); break; case "4": - Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); + this.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); break; case "5": - Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate); + this.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate); break; } - //Only insert the header control if a comment is needed - if(!String.IsNullOrWhiteSpace(Comment)) - Page.Header.Controls.AddAt(0, new LiteralControl(Comment)); + // Only insert the header control if a comment is needed + if (!string.IsNullOrWhiteSpace(this.Comment)) + { + this.Page.Header.Controls.AddAt(0, new LiteralControl(this.Comment)); + } - if (PortalSettings.ActiveTab.PageHeadText != Null.NullString && !Globals.IsAdminControl()) + if (this.PortalSettings.ActiveTab.PageHeadText != Null.NullString && !Globals.IsAdminControl()) { - Page.Header.Controls.Add(new LiteralControl(PortalSettings.ActiveTab.PageHeadText)); + this.Page.Header.Controls.Add(new LiteralControl(this.PortalSettings.ActiveTab.PageHeadText)); } - if (!string.IsNullOrEmpty(PortalSettings.PageHeadText)) + if (!string.IsNullOrEmpty(this.PortalSettings.PageHeadText)) { - metaPanel.Controls.Add(new LiteralControl(PortalSettings.PageHeadText)); + this.metaPanel.Controls.Add(new LiteralControl(this.PortalSettings.PageHeadText)); } - //set page title + // set page title if (UrlUtils.InPopUp()) { - var strTitle = new StringBuilder(PortalSettings.PortalName); - var slaveModule = UIUtilities.GetSlaveModule(PortalSettings.ActiveTab.TabID); + var strTitle = new StringBuilder(this.PortalSettings.PortalName); + var slaveModule = UIUtilities.GetSlaveModule(this.PortalSettings.ActiveTab.TabID); - //Skip is popup is just a tab (no slave module) + // Skip is popup is just a tab (no slave module) if (slaveModule.DesktopModuleID != Null.NullInteger) { var control = ModuleControlFactory.CreateModuleControl(slaveModule) as IModuleControl; @@ -275,9 +425,10 @@ private void InitializePage() switch (extension) { case ".mvc": - var segments = slaveModule.ModuleControl.ControlSrc.Replace(".mvc", "").Split('/'); + var segments = slaveModule.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); - control.LocalResourceFile = String.Format("~/DesktopModules/MVC/{0}/{1}/{2}.resx", + control.LocalResourceFile = string.Format( + "~/DesktopModules/MVC/{0}/{1}/{2}.resx", slaveModule.DesktopModule.FolderName, Localization.LocalResourceDirectory, segments[0]); @@ -290,144 +441,144 @@ private void InitializePage() Path.GetFileName(slaveModule.ModuleControl.ControlSrc)); break; } + var title = Localization.LocalizeControlTitle(control); - strTitle.Append(string.Concat(" > ", PortalSettings.ActiveTab.LocalizedTabName)); + strTitle.Append(string.Concat(" > ", this.PortalSettings.ActiveTab.LocalizedTabName)); strTitle.Append(string.Concat(" > ", title)); } else { - strTitle.Append(string.Concat(" > ", PortalSettings.ActiveTab.LocalizedTabName)); + strTitle.Append(string.Concat(" > ", this.PortalSettings.ActiveTab.LocalizedTabName)); } - //Set to page - Title = strTitle.ToString(); + // Set to page + this.Title = strTitle.ToString(); } else { - //If tab is named, use that title, otherwise build it out via breadcrumbs - if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Title)) + // If tab is named, use that title, otherwise build it out via breadcrumbs + if (!string.IsNullOrEmpty(this.PortalSettings.ActiveTab.Title)) { - Title = PortalSettings.ActiveTab.Title; + this.Title = this.PortalSettings.ActiveTab.Title; } else { - //Elected for SB over true concatenation here due to potential for long nesting depth - var strTitle = new StringBuilder(PortalSettings.PortalName); - foreach (TabInfo tab in PortalSettings.ActiveTab.BreadCrumbs) + // Elected for SB over true concatenation here due to potential for long nesting depth + var strTitle = new StringBuilder(this.PortalSettings.PortalName); + foreach (TabInfo tab in this.PortalSettings.ActiveTab.BreadCrumbs) { strTitle.Append(string.Concat(" > ", tab.TabName)); } - Title = strTitle.ToString(); + + this.Title = strTitle.ToString(); } } - //set the background image if there is one selected - if (!UrlUtils.InPopUp() && FindControl("Body") != null) + // set the background image if there is one selected + if (!UrlUtils.InPopUp() && this.FindControl("Body") != null) { - if (!string.IsNullOrEmpty(PortalSettings.BackgroundFile)) + if (!string.IsNullOrEmpty(this.PortalSettings.BackgroundFile)) { - var fileInfo = GetBackgroundFileInfo(); + var fileInfo = this.GetBackgroundFileInfo(); var url = FileManager.Instance.GetUrl(fileInfo); - ((HtmlGenericControl)FindControl("Body")).Attributes["style"] = string.Concat("background-image: url('", url, "')"); + ((HtmlGenericControl)this.FindControl("Body")).Attributes["style"] = string.Concat("background-image: url('", url, "')"); } } - //META Refresh + // META Refresh // Only autorefresh the page if we are in VIEW-mode and if we aren't displaying some module's subcontrol. - if (PortalSettings.ActiveTab.RefreshInterval > 0 && this.PortalSettings.UserMode == PortalSettings.Mode.View && Request.QueryString["ctl"] == null) + if (this.PortalSettings.ActiveTab.RefreshInterval > 0 && this.PortalSettings.UserMode == PortalSettings.Mode.View && this.Request.QueryString["ctl"] == null) { - MetaRefresh.Content = PortalSettings.ActiveTab.RefreshInterval.ToString(); - MetaRefresh.Visible = true; + this.MetaRefresh.Content = this.PortalSettings.ActiveTab.RefreshInterval.ToString(); + this.MetaRefresh.Visible = true; } else { - MetaRefresh.Visible = false; + this.MetaRefresh.Visible = false; } - //META description - if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Description)) + // META description + if (!string.IsNullOrEmpty(this.PortalSettings.ActiveTab.Description)) { - Description = PortalSettings.ActiveTab.Description; + this.Description = this.PortalSettings.ActiveTab.Description; } else { - Description = PortalSettings.Description; + this.Description = this.PortalSettings.Description; } - //META keywords - if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.KeyWords)) + // META keywords + if (!string.IsNullOrEmpty(this.PortalSettings.ActiveTab.KeyWords)) { - KeyWords = PortalSettings.ActiveTab.KeyWords; + this.KeyWords = this.PortalSettings.ActiveTab.KeyWords; } else { - KeyWords = PortalSettings.KeyWords; + this.KeyWords = this.PortalSettings.KeyWords; } - //META copyright - if (!string.IsNullOrEmpty(PortalSettings.FooterText)) + // META copyright + if (!string.IsNullOrEmpty(this.PortalSettings.FooterText)) { - Copyright = PortalSettings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()); + this.Copyright = this.PortalSettings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()); } else { - Copyright = string.Concat("Copyright (c) ", DateTime.Now.Year, " by ", PortalSettings.PortalName); + this.Copyright = string.Concat("Copyright (c) ", DateTime.Now.Year, " by ", this.PortalSettings.PortalName); } - //META generator + // META generator + this.Generator = string.Empty; - Generator = ""; - - - //META Robots - hide it inside popups and if PageHeadText of current tab already contains a robots meta tag + // META Robots - hide it inside popups and if PageHeadText of current tab already contains a robots meta tag if (!UrlUtils.InPopUp() && - !(HeaderTextRegex.IsMatch(PortalSettings.ActiveTab.PageHeadText) || - HeaderTextRegex.IsMatch(PortalSettings.PageHeadText))) + !(HeaderTextRegex.IsMatch(this.PortalSettings.ActiveTab.PageHeadText) || + HeaderTextRegex.IsMatch(this.PortalSettings.PageHeadText))) { - MetaRobots.Visible = true; + this.MetaRobots.Visible = true; var allowIndex = true; - if ((PortalSettings.ActiveTab.TabSettings.ContainsKey("AllowIndex") && - bool.TryParse(PortalSettings.ActiveTab.TabSettings["AllowIndex"].ToString(), out allowIndex) && + if ((this.PortalSettings.ActiveTab.TabSettings.ContainsKey("AllowIndex") && + bool.TryParse(this.PortalSettings.ActiveTab.TabSettings["AllowIndex"].ToString(), out allowIndex) && !allowIndex) || - (Request.QueryString["ctl"] != null && - (Request.QueryString["ctl"] == "Login" || Request.QueryString["ctl"] == "Register"))) + (this.Request.QueryString["ctl"] != null && + (this.Request.QueryString["ctl"] == "Login" || this.Request.QueryString["ctl"] == "Register"))) { - MetaRobots.Content = "NOINDEX, NOFOLLOW"; + this.MetaRobots.Content = "NOINDEX, NOFOLLOW"; } else { - MetaRobots.Content = "INDEX, FOLLOW"; + this.MetaRobots.Content = "INDEX, FOLLOW"; } } - //NonProduction Label Injection - if (NonProductionVersion() && Host.DisplayBetaNotice && !UrlUtils.InPopUp()) + // NonProduction Label Injection + if (this.NonProductionVersion() && Host.DisplayBetaNotice && !UrlUtils.InPopUp()) { string versionString = string.Format(" ({0} Version: {1})", DotNetNukeContext.Current.Application.Status, DotNetNukeContext.Current.Application.Version); - Title += versionString; + this.Title += versionString; } - //register the custom stylesheet of current page - if (PortalSettings.ActiveTab.TabSettings.ContainsKey("CustomStylesheet") && !string.IsNullOrEmpty(PortalSettings.ActiveTab.TabSettings["CustomStylesheet"].ToString())) - { - var customStylesheet = Path.Combine(PortalSettings.HomeDirectory, PortalSettings.ActiveTab.TabSettings["CustomStylesheet"].ToString()); - ClientResourceManager.RegisterStyleSheet(this, customStylesheet); - } + // register the custom stylesheet of current page + if (this.PortalSettings.ActiveTab.TabSettings.ContainsKey("CustomStylesheet") && !string.IsNullOrEmpty(this.PortalSettings.ActiveTab.TabSettings["CustomStylesheet"].ToString())) + { + var customStylesheet = Path.Combine(this.PortalSettings.HomeDirectory, this.PortalSettings.ActiveTab.TabSettings["CustomStylesheet"].ToString()); + ClientResourceManager.RegisterStyleSheet(this, customStylesheet); + } // Cookie Consent - if (PortalSettings.ShowCookieConsent) + if (this.PortalSettings.ShowCookieConsent) { - ClientAPI.RegisterClientVariable(this, "cc_morelink", PortalSettings.CookieMoreLink, true); + ClientAPI.RegisterClientVariable(this, "cc_morelink", this.PortalSettings.CookieMoreLink, true); ClientAPI.RegisterClientVariable(this, "cc_message", Localization.GetString("cc_message", Localization.GlobalResourceFile), true); ClientAPI.RegisterClientVariable(this, "cc_dismiss", Localization.GetString("cc_dismiss", Localization.GlobalResourceFile), true); ClientAPI.RegisterClientVariable(this, "cc_link", Localization.GetString("cc_link", Localization.GlobalResourceFile), true); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/Components/CookieConsent/cookieconsent.min.js", FileOrder.Js.DnnControls); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/Components/CookieConsent/cookieconsent.min.css", FileOrder.Css.ResourceCss); - ClientResourceManager.RegisterScript(Page, "~/js/dnn.cookieconsent.js", FileOrder.Js.DefaultPriority); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Components/CookieConsent/cookieconsent.min.js", FileOrder.Js.DnnControls); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/Components/CookieConsent/cookieconsent.min.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterScript(this.Page, "~/js/dnn.cookieconsent.js", FileOrder.Js.DefaultPriority); } } @@ -442,43 +593,44 @@ private void InitializePage() private void SetSkinDoctype() { string strLang = CultureInfo.CurrentCulture.ToString(); - string strDocType = PortalSettings.ActiveTab.SkinDoctype; + string strDocType = this.PortalSettings.ActiveTab.SkinDoctype; if (strDocType.Contains("XHTML 1.0")) { - //XHTML 1.0 - HtmlAttributes.Add("xml:lang", strLang); - HtmlAttributes.Add("lang", strLang); - HtmlAttributes.Add("xmlns", "http://www.w3.org/1999/xhtml"); + // XHTML 1.0 + this.HtmlAttributes.Add("xml:lang", strLang); + this.HtmlAttributes.Add("lang", strLang); + this.HtmlAttributes.Add("xmlns", "http://www.w3.org/1999/xhtml"); } else if (strDocType.Contains("XHTML 1.1")) { - //XHTML 1.1 - HtmlAttributes.Add("xml:lang", strLang); - HtmlAttributes.Add("xmlns", "http://www.w3.org/1999/xhtml"); + // XHTML 1.1 + this.HtmlAttributes.Add("xml:lang", strLang); + this.HtmlAttributes.Add("xmlns", "http://www.w3.org/1999/xhtml"); } else { - //other - HtmlAttributes.Add("lang", strLang); + // other + this.HtmlAttributes.Add("lang", strLang); } - //Find the placeholder control and render the doctype - skinDocType.Text = PortalSettings.ActiveTab.SkinDoctype; - attributeList.Text = HtmlAttributeList; + + // Find the placeholder control and render the doctype + this.skinDocType.Text = this.PortalSettings.ActiveTab.SkinDoctype; + this.attributeList.Text = this.HtmlAttributeList; } private void ManageFavicon() { - string headerLink = FavIcon.GetHeaderLink(PortalSettings.PortalId); + string headerLink = FavIcon.GetHeaderLink(this.PortalSettings.PortalId); - if (!String.IsNullOrEmpty(headerLink)) + if (!string.IsNullOrEmpty(headerLink)) { - Page.Header.Controls.Add(new Literal { Text = headerLink }); + this.Page.Header.Controls.Add(new Literal { Text = headerLink }); } } - //I realize the parsing of this is rather primitive. A better solution would be to use json serialization - //unfortunately, I don't have the time to write it. When we officially adopt MS AJAX, we will get this type of - //functionality and this should be changed to utilize it for its plumbing. + // I realize the parsing of this is rather primitive. A better solution would be to use json serialization + // unfortunately, I don't have the time to write it. When we officially adopt MS AJAX, we will get this type of + // functionality and this should be changed to utilize it for its plumbing. private Dictionary ParsePageCallBackArgs(string strArg) { string[] aryVals = strArg.Split(new[] { ClientAPI.COLUMN_DELIMITER }, StringSplitOptions.None); @@ -500,17 +652,18 @@ private Dictionary ParsePageCallBackArgs(string strArg) break; } } + return objDict; } /// - /// check if a warning about account defaults needs to be rendered + /// check if a warning about account defaults needs to be rendered. /// - /// localised error message + /// localised error message. /// private string RenderDefaultsWarning() { - var warningLevel = Request.QueryString["runningDefault"]; + var warningLevel = this.Request.QueryString["runningDefault"]; var warningMessage = string.Empty; switch (warningLevel) { @@ -524,179 +677,28 @@ private string RenderDefaultsWarning() warningMessage = Localization.GetString("InsecureDefaults.Text", Localization.SharedResourceFile); break; } + return warningMessage; } private IFileInfo GetBackgroundFileInfo() { - string cacheKey = String.Format(Common.Utilities.DataCache.PortalCacheKey, PortalSettings.PortalId, "BackgroundFile"); - var file = CBO.GetCachedObject(new CacheItemArgs(cacheKey, Common.Utilities.DataCache.PortalCacheTimeOut, Common.Utilities.DataCache.PortalCachePriority), - GetBackgroundFileInfoCallBack); + string cacheKey = string.Format(Common.Utilities.DataCache.PortalCacheKey, this.PortalSettings.PortalId, "BackgroundFile"); + var file = CBO.GetCachedObject( + new CacheItemArgs(cacheKey, Common.Utilities.DataCache.PortalCacheTimeOut, Common.Utilities.DataCache.PortalCachePriority), + this.GetBackgroundFileInfoCallBack); return file; } private IFileInfo GetBackgroundFileInfoCallBack(CacheItemArgs itemArgs) { - return FileManager.Instance.GetFile(PortalSettings.PortalId, PortalSettings.BackgroundFile); - } - - #endregion - - #region Protected Methods - - protected bool NonProductionVersion() - { - return DotNetNukeContext.Current.Application.Status != ReleaseMode.Stable; + return FileManager.Instance.GetFile(this.PortalSettings.PortalId, this.PortalSettings.BackgroundFile); } /// ----------------------------------------------------------------------------- /// - /// Contains the functionality to populate the Root aspx page with controls - /// - /// - /// - /// - obtain PortalSettings from Current Context - /// - set global page settings. - /// - initialise reference paths to load the cascading style sheets - /// - add skin control placeholder. This holds all the modules and content of the page. - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - //set global page settings - InitializePage(); - - //load skin control and register UI js - UI.Skins.Skin ctlSkin; - if (PortalSettings.EnablePopUps) - { - ctlSkin = UrlUtils.InPopUp() ? UI.Skins.Skin.GetPopUpSkin(this) : UI.Skins.Skin.GetSkin(this); - - //register popup js - JavaScript.RequestRegistration(CommonJs.jQueryUI); - - var popupFilePath = HttpContext.Current.IsDebuggingEnabled - ? "~/js/Debug/dnn.modalpopup.js" - : "~/js/dnn.modalpopup.js"; - - ClientResourceManager.RegisterScript(this, popupFilePath, FileOrder.Js.DnnModalPopup); - } - else - { - ctlSkin = UI.Skins.Skin.GetSkin(this); - } - - // DataBind common paths for the client resource loader - ClientResourceLoader.DataBind(); - ClientResourceLoader.PreRender += (sender, args) => JavaScript.Register(Page); - - //check for and read skin package level doctype - SetSkinDoctype(); - - //Manage disabled pages - if (PortalSettings.ActiveTab.DisableLink) - { - if (TabPermissionController.CanAdminPage()) - { - var heading = Localization.GetString("PageDisabled.Header"); - var message = Localization.GetString("PageDisabled.Text"); - UI.Skins.Skin.AddPageMessage(ctlSkin, heading, message, - ModuleMessage.ModuleMessageType.YellowWarning); - } - else - { - if (PortalSettings.HomeTabId > 0) - { - Response.Redirect(NavigationManager.NavigateURL(PortalSettings.HomeTabId), true); - } - else - { - Response.Redirect(Globals.GetPortalDomainName(PortalSettings.PortalAlias.HTTPAlias, Request, true), true); - } - } - } - //Manage canonical urls - if (PortalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.CanonicalUrl) - { - string primaryHttpAlias = null; - if (Config.GetFriendlyUrlProvider() == "advanced") //advanced mode compares on the primary alias as set during alias identification - { - if (PortalSettings.PrimaryAlias != null && PortalSettings.PortalAlias != null) - { - if (string.Compare(PortalSettings.PrimaryAlias.HTTPAlias, PortalSettings.PortalAlias.HTTPAlias, StringComparison.InvariantCulture ) != 0) - { - primaryHttpAlias = PortalSettings.PrimaryAlias.HTTPAlias; - } - } - } - else //other modes just depend on the default alias - { - if (string.Compare(PortalSettings.PortalAlias.HTTPAlias, PortalSettings.DefaultPortalAlias, StringComparison.InvariantCulture ) != 0) - primaryHttpAlias = PortalSettings.DefaultPortalAlias; - } - if (primaryHttpAlias != null && string.IsNullOrEmpty(CanonicalLinkUrl))//a primary http alias was identified - { - var originalurl = Context.Items["UrlRewrite:OriginalUrl"].ToString(); - CanonicalLinkUrl = originalurl.Replace(PortalSettings.PortalAlias.HTTPAlias, primaryHttpAlias); - - if (UrlUtils.IsSecureConnectionOrSslOffload(Request)) - { - CanonicalLinkUrl = CanonicalLinkUrl.Replace("http://", "https://"); - } - } - } - - //check if running with known account defaults - if (Request.IsAuthenticated && string.IsNullOrEmpty(Request.QueryString["runningDefault"]) == false) - { - var userInfo = HttpContext.Current.Items["UserInfo"] as UserInfo; - var usernameLower = userInfo?.Username?.ToLowerInvariant(); - //only show message to default users - if ("admin".Equals(usernameLower) || "host".Equals(usernameLower)) - { - var messageText = RenderDefaultsWarning(); - var messageTitle = Localization.GetString("InsecureDefaults.Title", Localization.GlobalResourceFile); - UI.Skins.Skin.AddPageMessage(ctlSkin, messageTitle, messageText, ModuleMessage.ModuleMessageType.RedError); - } - } - - //add CSS links - ClientResourceManager.RegisterDefaultStylesheet(this, string.Concat(Globals.ApplicationPath, "/Resources/Shared/stylesheets/dnndefault/7.0.0/default.css")); - ClientResourceManager.RegisterIEStylesheet(this, string.Concat(Globals.HostPath, "ie.css")); - - ClientResourceManager.RegisterStyleSheet(this, string.Concat(ctlSkin.SkinPath, "skin.css"), FileOrder.Css.SkinCss); - ClientResourceManager.RegisterStyleSheet(this, ctlSkin.SkinSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificSkinCss); - - //add skin to page - SkinPlaceHolder.Controls.Add(ctlSkin); - - ClientResourceManager.RegisterStyleSheet(this, string.Concat(PortalSettings.HomeDirectory, "portal.css"), FileOrder.Css.PortalCss); - - //add Favicon - ManageFavicon(); - - //ClientCallback Logic - ClientAPI.HandleClientAPICallbackEvent(this); - - //add viewstateuserkey to protect against CSRF attacks - if (User.Identity.IsAuthenticated) - { - ViewStateUserKey = User.Identity.Name; - } - - //set the async postback timeout. - if (AJAX.IsEnabled()) - { - AJAX.GetScriptManager(this).AsyncPostBackTimeout = Host.AsyncTimeout; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Initialize the Scrolltop html control which controls the open / closed nature of each module + /// Initialize the Scrolltop html control which controls the open / closed nature of each module. /// /// /// @@ -706,12 +708,12 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - ManageInstallerFiles(); + this.ManageInstallerFiles(); - if (!String.IsNullOrEmpty(ScrollTop.Value)) + if (!string.IsNullOrEmpty(this.ScrollTop.Value)) { - DNNClientAPI.SetScrollTop(Page); - ScrollTop.Value = ScrollTop.Value; + DNNClientAPI.SetScrollTop(this.Page); + this.ScrollTop.Value = this.ScrollTop.Value; } } @@ -719,63 +721,61 @@ protected override void OnPreRender(EventArgs evt) { base.OnPreRender(evt); - //Set the Head tags - metaPanel.Visible = !UrlUtils.InPopUp(); + // Set the Head tags + this.metaPanel.Visible = !UrlUtils.InPopUp(); if (!UrlUtils.InPopUp()) { - MetaGenerator.Content = Generator; - MetaGenerator.Visible = (!String.IsNullOrEmpty(Generator)); - MetaAuthor.Content = PortalSettings.PortalName; + this.MetaGenerator.Content = this.Generator; + this.MetaGenerator.Visible = !string.IsNullOrEmpty(this.Generator); + this.MetaAuthor.Content = this.PortalSettings.PortalName; /* * Never show to be html5 compatible and stay backward compatible - * + * * MetaCopyright.Content = Copyright; * MetaCopyright.Visible = (!String.IsNullOrEmpty(Copyright)); */ - MetaKeywords.Content = KeyWords; - MetaKeywords.Visible = (!String.IsNullOrEmpty(KeyWords)); - MetaDescription.Content = Description; - MetaDescription.Visible = (!String.IsNullOrEmpty(Description)); + this.MetaKeywords.Content = this.KeyWords; + this.MetaKeywords.Visible = !string.IsNullOrEmpty(this.KeyWords); + this.MetaDescription.Content = this.Description; + this.MetaDescription.Visible = !string.IsNullOrEmpty(this.Description); } - Page.Header.Title = Title; - if (!string.IsNullOrEmpty(PortalSettings.AddCompatibleHttpHeader) && !HeaderIsWritten) + + this.Page.Header.Title = this.Title; + if (!string.IsNullOrEmpty(this.PortalSettings.AddCompatibleHttpHeader) && !this.HeaderIsWritten) { - Page.Response.AddHeader("X-UA-Compatible", PortalSettings.AddCompatibleHttpHeader); + this.Page.Response.AddHeader("X-UA-Compatible", this.PortalSettings.AddCompatibleHttpHeader); } - if (!string.IsNullOrEmpty(CanonicalLinkUrl)) - { - //Add Canonical using the primary alias - var canonicalLink = new HtmlLink(); - canonicalLink.Href = CanonicalLinkUrl; - canonicalLink.Attributes.Add("rel", "canonical"); + if (!string.IsNullOrEmpty(this.CanonicalLinkUrl)) + { + // Add Canonical using the primary alias + var canonicalLink = new HtmlLink(); + canonicalLink.Href = this.CanonicalLinkUrl; + canonicalLink.Attributes.Add("rel", "canonical"); - // Add the HtmlLink to the Head section of the page. - Page.Header.Controls.Add(canonicalLink); - } + // Add the HtmlLink to the Head section of the page. + this.Page.Header.Controls.Add(canonicalLink); + } } - protected override void Render(HtmlTextWriter writer) - { - if (PortalSettings.UserMode == PortalSettings.Mode.Edit) - { - var editClass = "dnnEditState"; - - var bodyClass = Body.Attributes["class"]; - if (!string.IsNullOrEmpty(bodyClass)) - { - Body.Attributes["class"] = string.Format("{0} {1}", bodyClass, editClass); - } - else - { - Body.Attributes["class"] = editClass; - } - } - - base.Render(writer); - } + protected override void Render(HtmlTextWriter writer) + { + if (this.PortalSettings.UserMode == PortalSettings.Mode.Edit) + { + var editClass = "dnnEditState"; - #endregion + var bodyClass = this.Body.Attributes["class"]; + if (!string.IsNullOrEmpty(bodyClass)) + { + this.Body.Attributes["class"] = string.Format("{0} {1}", bodyClass, editClass); + } + else + { + this.Body.Attributes["class"] = editClass; + } + } + base.Render(writer); + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Authentication.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Authentication.ascx.resx index 12db907e374..97588c7bda0 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Authentication.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Authentication.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Login.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Login.ascx.resx index 9040e63771d..9f76f7bd2e5 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Login.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Login.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Logoff.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Logoff.ascx.resx index 99b0eb5b4f9..a2a335e7289 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Logoff.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/App_LocalResources/Logoff.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs index 5f0153433a9..c07f32af88b 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs @@ -1,109 +1,103 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.UserControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Authentication { - - /// - /// Manages the Authentication settings - /// - /// - /// - public partial class Authentication : PortalModuleBase - { - - private readonly List _settingControls = new List(); - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cmdUpdate.Click += OnUpdateClick; - - var authSystems = AuthenticationController.GetEnabledAuthenticationServices(); - - foreach (var authSystem in authSystems) - { - //Add a Section Header - var sectionHeadControl = (SectionHeadControl) LoadControl("~/controls/SectionHeadControl.ascx"); - sectionHeadControl.IncludeRule = true; - sectionHeadControl.CssClass = "Head"; - - //Create a
        to hold the control - var container = new HtmlGenericControl(); - container.ID = authSystem.AuthenticationType; - - var authSettingsControl = (AuthenticationSettingsBase) LoadControl("~/" + authSystem.SettingsControlSrc); - - //set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - //this is necessary for the Localization in PageBase - authSettingsControl.ID = Path.GetFileNameWithoutExtension(authSystem.SettingsControlSrc) + "_" + authSystem.AuthenticationType; - - //Add Settings Control to Container - container.Controls.Add(authSettingsControl); - _settingControls.Add(authSettingsControl); - - //Add Section Head Control to Container - pnlSettings.Controls.Add(sectionHeadControl); - - //Add Container to Controls - pnlSettings.Controls.Add(container); - - //Attach Settings Control's container to Section Head Control - sectionHeadControl.Section = container.ID; - - //Get Section Head Text from the setting controls LocalResourceFile - authSettingsControl.LocalResourceFile = authSettingsControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + - Path.GetFileNameWithoutExtension(authSystem.SettingsControlSrc); - sectionHeadControl.Text = Localization.GetString("Title", authSettingsControl.LocalResourceFile); - pnlSettings.Controls.Add(new LiteralControl("
        ")); - cmdUpdate.Visible = IsEditable; - } - } - - protected void OnUpdateClick(object sender, EventArgs e) - { - foreach (var settingControl in _settingControls) - { - settingControl.UpdateSettings(); - } - - //Validate Enabled - var enabled = false; - var authSystems = AuthenticationController.GetEnabledAuthenticationServices(); - foreach (var authSystem in authSystems) - { - var authLoginControl = (AuthenticationLoginBase) LoadControl("~/" + authSystem.LoginControlSrc); - - //Check if AuthSystem is Enabled - if (authLoginControl.Enabled) - { - enabled = true; - break; - } - } - if (!enabled) - { - //Display warning - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoProvidersEnabled", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - } - } - - } + using System; + using System.Collections.Generic; + using System.IO; + using System.Web.UI; + using System.Web.UI.HtmlControls; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.UserControls; + + /// + /// Manages the Authentication settings. + /// + /// + /// + public partial class Authentication : PortalModuleBase + { + private readonly List _settingControls = new List(); + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cmdUpdate.Click += this.OnUpdateClick; + + var authSystems = AuthenticationController.GetEnabledAuthenticationServices(); + + foreach (var authSystem in authSystems) + { + // Add a Section Header + var sectionHeadControl = (SectionHeadControl)this.LoadControl("~/controls/SectionHeadControl.ascx"); + sectionHeadControl.IncludeRule = true; + sectionHeadControl.CssClass = "Head"; + + // Create a
        to hold the control + var container = new HtmlGenericControl(); + container.ID = authSystem.AuthenticationType; + + var authSettingsControl = (AuthenticationSettingsBase)this.LoadControl("~/" + authSystem.SettingsControlSrc); + + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + authSettingsControl.ID = Path.GetFileNameWithoutExtension(authSystem.SettingsControlSrc) + "_" + authSystem.AuthenticationType; + + // Add Settings Control to Container + container.Controls.Add(authSettingsControl); + this._settingControls.Add(authSettingsControl); + + // Add Section Head Control to Container + this.pnlSettings.Controls.Add(sectionHeadControl); + + // Add Container to Controls + this.pnlSettings.Controls.Add(container); + + // Attach Settings Control's container to Section Head Control + sectionHeadControl.Section = container.ID; + + // Get Section Head Text from the setting controls LocalResourceFile + authSettingsControl.LocalResourceFile = authSettingsControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + + Path.GetFileNameWithoutExtension(authSystem.SettingsControlSrc); + sectionHeadControl.Text = Localization.GetString("Title", authSettingsControl.LocalResourceFile); + this.pnlSettings.Controls.Add(new LiteralControl("
        ")); + this.cmdUpdate.Visible = this.IsEditable; + } + } + + protected void OnUpdateClick(object sender, EventArgs e) + { + foreach (var settingControl in this._settingControls) + { + settingControl.UpdateSettings(); + } + + // Validate Enabled + var enabled = false; + var authSystems = AuthenticationController.GetEnabledAuthenticationServices(); + foreach (var authSystem in authSystems) + { + var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); + + // Check if AuthSystem is Enabled + if (authLoginControl.Enabled) + { + enabled = true; + break; + } + } + + if (!enabled) + { + // Display warning + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoProvidersEnabled", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + } + } + } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs index 28914554ec0..3e129830198 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs @@ -1,120 +1,115 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Modules.Admin.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mail; -using DotNetNuke.Services.Messaging.Data; -using DotNetNuke.Services.UserRequest; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.UserControls; -using DotNetNuke.UI.WebControls; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.IO; -using System.Text.RegularExpressions; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utils; -using Microsoft.Extensions.DependencyInjection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Authentication { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.IO; + using System.Text.RegularExpressions; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Common.Utils; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.Admin.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.Messaging.Data; + using DotNetNuke.Services.UserRequest; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.UserControls; + using DotNetNuke.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + using Host = DotNetNuke.Entities.Host.Host; /// - /// The Signin UserModuleBase is used to provide a login for a registered user + /// The Signin UserModuleBase is used to provide a login for a registered user. /// /// /// public partial class Login : UserModuleBase { + private const string LOGIN_PATH = "/login"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Login)); - private readonly INavigationManager _navigationManager; - - private static readonly Regex UserLanguageRegex = new Regex("(.*)(&|\\?)(language=)([^&\\?]+)(.*)", + private static readonly Regex UserLanguageRegex = new Regex( + "(.*)(&|\\?)(language=)([^&\\?]+)(.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled); - public Login() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members + private readonly INavigationManager _navigationManager; private readonly List _loginControls = new List(); private readonly List _defaultauthLogin = new List(); private readonly List _oAuthControls = new List(); - private const string LOGIN_PATH = "/login"; - #endregion - - #region Protected Properties + public Login() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } /// - /// Gets and sets the current AuthenticationType + /// Gets or sets and sets the current AuthenticationType. /// protected string AuthenticationType { get { var authenticationType = Null.NullString; - if (ViewState["AuthenticationType"] != null) + if (this.ViewState["AuthenticationType"] != null) { - authenticationType = Convert.ToString(ViewState["AuthenticationType"]); + authenticationType = Convert.ToString(this.ViewState["AuthenticationType"]); } + return authenticationType; } + set { - ViewState["AuthenticationType"] = value; + this.ViewState["AuthenticationType"] = value; } } /// - /// Gets and sets a flag that determines whether the user should be automatically registered + /// Gets or sets a value indicating whether gets and sets a flag that determines whether the user should be automatically registered. /// protected bool AutoRegister { get { var autoRegister = Null.NullBoolean; - if (ViewState["AutoRegister"] != null) + if (this.ViewState["AutoRegister"] != null) { - autoRegister = Convert.ToBoolean(ViewState["AutoRegister"]); + autoRegister = Convert.ToBoolean(this.ViewState["AutoRegister"]); } + return autoRegister; } + set { - ViewState["AutoRegister"] = value; + this.ViewState["AutoRegister"] = value; } } @@ -123,77 +118,84 @@ protected NameValueCollection ProfileProperties get { var profile = new NameValueCollection(); - if (ViewState["ProfileProperties"] != null) + if (this.ViewState["ProfileProperties"] != null) { - profile = (NameValueCollection)ViewState["ProfileProperties"]; + profile = (NameValueCollection)this.ViewState["ProfileProperties"]; } + return profile; } + set { - ViewState["ProfileProperties"] = value; + this.ViewState["ProfileProperties"] = value; } } /// - /// Gets and sets the current Page No + /// Gets or sets and sets the current Page No. /// protected int PageNo { get { var pageNo = 0; - if (ViewState["PageNo"] != null) + if (this.ViewState["PageNo"] != null) { - pageNo = Convert.ToInt32(ViewState["PageNo"]); + pageNo = Convert.ToInt32(this.ViewState["PageNo"]); } + return pageNo; } + set { - ViewState["PageNo"] = value; + this.ViewState["PageNo"] = value; } } /// - /// Gets the Redirect URL (after successful login) + /// Gets the Redirect URL (after successful login). /// protected string RedirectURL { get { - var redirectURL = ""; + var redirectURL = string.Empty; - var setting = GetSetting(PortalId, "Redirect_AfterLogin"); + var setting = GetSetting(this.PortalId, "Redirect_AfterLogin"); - //first we need to check if there is a returnurl - if (Request.QueryString["returnurl"] != null) + // first we need to check if there is a returnurl + if (this.Request.QueryString["returnurl"] != null) { - //return to the url passed to signin - redirectURL = HttpUtility.UrlDecode(Request.QueryString["returnurl"]); + // return to the url passed to signin + redirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); - //clean the return url to avoid possible XSS attack. + // clean the return url to avoid possible XSS attack. redirectURL = UrlUtils.ValidReturnUrl(redirectURL); } - if (Request.Cookies["returnurl"] != null) + + if (this.Request.Cookies["returnurl"] != null) { - //return to the url passed to signin - redirectURL = HttpUtility.UrlDecode(Request.Cookies["returnurl"].Value); + // return to the url passed to signin + redirectURL = HttpUtility.UrlDecode(this.Request.Cookies["returnurl"].Value); - //clean the return url to avoid possible XSS attack. + // clean the return url to avoid possible XSS attack. redirectURL = UrlUtils.ValidReturnUrl(redirectURL); } - if (Request.Params["appctx"] != null) + + if (this.Request.Params["appctx"] != null) { - //HACK return to the url passed to signin (LiveID) - redirectURL = HttpUtility.UrlDecode(Request.Params["appctx"]); + // HACK return to the url passed to signin (LiveID) + redirectURL = HttpUtility.UrlDecode(this.Request.Params["appctx"]); - //clean the return url to avoid possible XSS attack. + // clean the return url to avoid possible XSS attack. redirectURL = UrlUtils.ValidReturnUrl(redirectURL); } - var alias = PortalAlias.HTTPAlias; + var alias = this.PortalAlias.HTTPAlias; var comparison = StringComparison.InvariantCultureIgnoreCase; + // we need .TrimEnd('/') because a portlalias for a specific culture will not have a trailing /, while a returnurl will. var isDefaultPage = redirectURL == "/" || (alias.Contains("/") && redirectURL.TrimEnd('/').Equals(alias.Substring(alias.IndexOf("/", comparison)), comparison)); @@ -201,115 +203,88 @@ protected string RedirectURL if (string.IsNullOrEmpty(redirectURL) || isDefaultPage) { if ( - NeedRedirectAfterLogin - && (isDefaultPage || IsRedirectingFromLoginUrl()) - && Convert.ToInt32(setting) != Null.NullInteger - ) + this.NeedRedirectAfterLogin + && (isDefaultPage || this.IsRedirectingFromLoginUrl()) + && Convert.ToInt32(setting) != Null.NullInteger) { - redirectURL = _navigationManager.NavigateURL(Convert.ToInt32(setting)); + redirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); } else { - if (PortalSettings.LoginTabId != -1 && PortalSettings.HomeTabId != -1) + if (this.PortalSettings.LoginTabId != -1 && this.PortalSettings.HomeTabId != -1) { - //redirect to portal home page specified - redirectURL = _navigationManager.NavigateURL(PortalSettings.HomeTabId); + // redirect to portal home page specified + redirectURL = this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId); } else { - //redirect to current page - redirectURL = _navigationManager.NavigateURL(); + // redirect to current page + redirectURL = this._navigationManager.NavigateURL(); } } - } - - //replace language parameter in querystring, to make sure that user will see page in correct language - if (UserId != -1 && User != null) + // replace language parameter in querystring, to make sure that user will see page in correct language + if (this.UserId != -1 && this.User != null) { - if (!String.IsNullOrEmpty(User.Profile.PreferredLocale) - && User.Profile.PreferredLocale != CultureInfo.CurrentCulture.Name - && LocaleEnabled(User.Profile.PreferredLocale)) + if (!string.IsNullOrEmpty(this.User.Profile.PreferredLocale) + && this.User.Profile.PreferredLocale != CultureInfo.CurrentCulture.Name + && this.LocaleEnabled(this.User.Profile.PreferredLocale)) { - redirectURL = ReplaceLanguage(redirectURL, CultureInfo.CurrentCulture.Name, User.Profile.PreferredLocale); + redirectURL = ReplaceLanguage(redirectURL, CultureInfo.CurrentCulture.Name, this.User.Profile.PreferredLocale); } } - //check for insecure account defaults + // check for insecure account defaults var qsDelimiter = "?"; if (redirectURL.Contains("?")) { qsDelimiter = "&"; } - if (LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD) + + if (this.LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD) { redirectURL = redirectURL + qsDelimiter + "runningDefault=1"; } - else if (LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD) + else if (this.LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD) { redirectURL = redirectURL + qsDelimiter + "runningDefault=2"; } + return redirectURL; } } - private bool IsRedirectingFromLoginUrl() - { - return Request.UrlReferrer != null && - Request.UrlReferrer.LocalPath.ToLowerInvariant().EndsWith(LOGIN_PATH); - } - - private bool NeedRedirectAfterLogin => - LoginStatus == UserLoginStatus.LOGIN_SUCCESS - || LoginStatus == UserLoginStatus.LOGIN_SUPERUSER - || LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD - || LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; - /// - /// Replaces the original language with user language - /// - /// - /// - /// - /// - private static string ReplaceLanguage(string Url, string originalLanguage, string newLanguage) - { - var returnValue = Host.UseFriendlyUrls - ? Regex.Replace(Url, "(.*)(/" + originalLanguage + "/)(.*)", "$1/" + newLanguage + "/$3", RegexOptions.IgnoreCase) - : UserLanguageRegex.Replace(Url, "$1$2$3" + newLanguage + "$5"); - return returnValue; - } - - - /// - /// Gets and sets a flag that determines whether a permanent auth cookie should be created + /// Gets or sets a value indicating whether gets and sets a flag that determines whether a permanent auth cookie should be created. /// protected bool RememberMe { get { var rememberMe = Null.NullBoolean; - if (ViewState["RememberMe"] != null) + if (this.ViewState["RememberMe"] != null) { - rememberMe = Convert.ToBoolean(ViewState["RememberMe"]); + rememberMe = Convert.ToBoolean(this.ViewState["RememberMe"]); } + return rememberMe; } + set { - ViewState["RememberMe"] = value; + this.ViewState["RememberMe"] = value; } } /// - /// Gets whether the Captcha control is used to validate the login + /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. /// protected bool UseCaptcha { get { - object setting = GetSetting(PortalId, "Security_CaptchaLogin"); + object setting = GetSetting(this.PortalId, "Security_CaptchaLogin"); return Convert.ToBoolean(setting); } } @@ -319,71 +294,233 @@ protected UserLoginStatus LoginStatus get { UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; - if (ViewState["LoginStatus"] != null) + if (this.ViewState["LoginStatus"] != null) { - loginStatus = (UserLoginStatus)ViewState["LoginStatus"]; + loginStatus = (UserLoginStatus)this.ViewState["LoginStatus"]; } + return loginStatus; } + set { - ViewState["LoginStatus"] = value; + this.ViewState["LoginStatus"] = value; } } + private bool NeedRedirectAfterLogin => + this.LoginStatus == UserLoginStatus.LOGIN_SUCCESS + || this.LoginStatus == UserLoginStatus.LOGIN_SUPERUSER + || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD + || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; + /// - /// Gets and sets the current UserToken + /// Replaces the original language with user language. + /// + /// + /// + /// + /// + private static string ReplaceLanguage(string Url, string originalLanguage, string newLanguage) + { + var returnValue = Host.UseFriendlyUrls + ? Regex.Replace(Url, "(.*)(/" + originalLanguage + "/)(.*)", "$1/" + newLanguage + "/$3", RegexOptions.IgnoreCase) + : UserLanguageRegex.Replace(Url, "$1$2$3" + newLanguage + "$5"); + return returnValue; + } + + private bool IsRedirectingFromLoginUrl() + { + return this.Request.UrlReferrer != null && + this.Request.UrlReferrer.LocalPath.ToLowerInvariant().EndsWith(LOGIN_PATH); + } + + /// + /// Gets or sets and sets the current UserToken. /// protected string UserToken { get { - var userToken = ""; - if (ViewState["UserToken"] != null) + var userToken = string.Empty; + if (this.ViewState["UserToken"] != null) { - userToken = Convert.ToString(ViewState["UserToken"]); + userToken = Convert.ToString(this.ViewState["UserToken"]); } + return userToken; } + set { - ViewState["UserToken"] = value; + this.ViewState["UserToken"] = value; } } /// - /// Gets and sets the current UserName + /// Gets or sets and sets the current UserName. /// protected string UserName { get { - var userName = ""; - if (ViewState["UserName"] != null) + var userName = string.Empty; + if (this.ViewState["UserName"] != null) { - userName = Convert.ToString(ViewState["UserName"]); + userName = Convert.ToString(this.ViewState["UserName"]); } + return userName; } + set { - ViewState["UserName"] = value; + this.ViewState["UserName"] = value; } } - #endregion + /// + /// Page_Init runs when the control is initialised. + /// + /// + /// + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.ctlPassword.PasswordUpdated += this.PasswordUpdated; + this.ctlProfile.ProfileUpdated += this.ProfileUpdated; + this.ctlUser.UserCreateCompleted += this.UserCreateCompleted; + this.ctlDataConsent.DataConsentCompleted += this.DataConsentCompleted; + + // Set the User Control Properties + this.ctlUser.ID = "User"; + + // Set the Password Control Properties + this.ctlPassword.ID = "Password"; + + // Set the Profile Control Properties + this.ctlProfile.ID = "Profile"; + + // Set the Data Consent Control Properties + this.ctlDataConsent.ID = "DataConsent"; - #region Private Methods + // Override the redirected page title if page has loaded with ctl=Login + if (this.Request.QueryString["ctl"] != null) + { + if (this.Request.QueryString["ctl"].ToLowerInvariant() == "login") + { + var myPage = (CDefault)this.Page; + if (myPage.PortalSettings.LoginTabId == this.TabId || myPage.PortalSettings.LoginTabId == -1) + { + myPage.Title = Localization.GetString("ControlTitle_login", this.LocalResourceFile); + } + } + } + } + + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cmdAssociate.Click += this.cmdAssociate_Click; + this.cmdCreateUser.Click += this.cmdCreateUser_Click; + this.cmdProceed.Click += this.cmdProceed_Click; + + // Verify if portal has a customized login page + if (!Null.IsNull(this.PortalSettings.LoginTabId) && Globals.IsAdminControl()) + { + if (Globals.ValidateLoginTabID(this.PortalSettings.LoginTabId)) + { + // login page exists and trying to access this control directly with url param -> not allowed + var parameters = new string[3]; + if (!string.IsNullOrEmpty(this.Request.QueryString["returnUrl"])) + { + parameters[0] = "returnUrl=" + HttpUtility.UrlEncode(this.Request.QueryString["returnUrl"]); + } + + if (!string.IsNullOrEmpty(this.Request.QueryString["username"])) + { + parameters[1] = "username=" + HttpUtility.UrlEncode(this.Request.QueryString["username"]); + } + + if (!string.IsNullOrEmpty(this.Request.QueryString["verificationcode"])) + { + parameters[2] = "verificationcode=" + HttpUtility.UrlEncode(this.Request.QueryString["verificationcode"]); + } + + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.LoginTabId, string.Empty, parameters)); + } + } + + if (this.Page.IsPostBack == false) + { + try + { + this.PageNo = 0; + } + catch (Exception ex) + { + // control not there + Logger.Error(ex); + } + } + + if (!this.Request.IsAuthenticated || this.UserNeedsVerification()) + { + this.ShowPanel(); + } + else // user is already authenticated + { + // if a Login Page has not been specified for the portal + if (Globals.IsAdminControl()) + { + // redirect browser + this.Response.Redirect(this.RedirectURL, true); + } + else // make module container invisible if user is not a page admin + { + var path = this.RedirectURL.Split('?')[0]; + if (this.NeedRedirectAfterLogin && path != this._navigationManager.NavigateURL() && path != this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId)) + { + this.Response.Redirect(this.RedirectURL, true); + } + + if (TabPermissionController.CanAdminPage()) + { + this.ShowPanel(); + } + else + { + this.ContainerControl.Visible = false; + } + } + } + + this.divCaptcha.Visible = this.UseCaptcha; + + if (this.UseCaptcha) + { + this.ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile); + this.ctlCaptcha.Text = Localization.GetString("CaptchaText", Localization.SharedResourceFile); + } + } private void AddLoginControlAttributes(AuthenticationLoginBase loginControl) { - //search selected authentication control for username and password fields - //and inject autocomplete=off so browsers do not remember sensitive details + // search selected authentication control for username and password fields + // and inject autocomplete=off so browsers do not remember sensitive details var username = loginControl.FindControl("txtUsername") as WebControl; if (username != null) { username.Attributes.Add("AUTOCOMPLETE", "off"); } + var password = loginControl.FindControl("txtPassword") as WebControl; if (password != null) { @@ -395,47 +532,47 @@ private void BindLogin() { List authSystems = AuthenticationController.GetEnabledAuthenticationServices(); AuthenticationLoginBase defaultLoginControl = null; - var defaultAuthProvider = PortalController.GetPortalSetting("DefaultAuthProvider", PortalId, "DNN"); + var defaultAuthProvider = PortalController.GetPortalSetting("DefaultAuthProvider", this.PortalId, "DNN"); foreach (AuthenticationInfo authSystem in authSystems) { try { - //Figure out if known Auth types are enabled (so we can improve perf and stop loading the control) + // Figure out if known Auth types are enabled (so we can improve perf and stop loading the control) bool enabled = true; if (authSystem.AuthenticationType.Equals("Facebook") || authSystem.AuthenticationType.Equals("Google") || authSystem.AuthenticationType.Equals("Live") || authSystem.AuthenticationType.Equals("Twitter")) { - enabled = AuthenticationController.IsEnabledForPortal(authSystem, PortalSettings.PortalId); + enabled = AuthenticationController.IsEnabledForPortal(authSystem, this.PortalSettings.PortalId); } if (enabled) { - var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc); - BindLoginControl(authLoginControl, authSystem); + var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); + this.BindLoginControl(authLoginControl, authSystem); if (authSystem.AuthenticationType == "DNN") { defaultLoginControl = authLoginControl; } - //Check if AuthSystem is Enabled + // Check if AuthSystem is Enabled if (authLoginControl.Enabled) { var oAuthLoginControl = authLoginControl as OAuthLoginBase; if (oAuthLoginControl != null) { - //Add Login Control to List - _oAuthControls.Add(oAuthLoginControl); + // Add Login Control to List + this._oAuthControls.Add(oAuthLoginControl); } else { if (authLoginControl.AuthenticationType == defaultAuthProvider) { - _defaultauthLogin.Add(authLoginControl); + this._defaultauthLogin.Add(authLoginControl); } else { - //Add Login Control to List - _loginControls.Add(authLoginControl); + // Add Login Control to List + this._loginControls.Add(authLoginControl); } } } @@ -446,169 +583,176 @@ private void BindLogin() Exceptions.LogException(ex); } } - int authCount = _loginControls.Count + _defaultauthLogin.Count; + + int authCount = this._loginControls.Count + this._defaultauthLogin.Count; switch (authCount) { case 0: - //No enabled controls - inject default dnn control + // No enabled controls - inject default dnn control if (defaultLoginControl == null) { - //No controls enabled for portal, and default DNN control is not enabled by host, so load system default (DNN) + // No controls enabled for portal, and default DNN control is not enabled by host, so load system default (DNN) AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN"); - var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc); - BindLoginControl(authLoginControl, authSystem); - DisplayLoginControl(authLoginControl, false, false); + var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); + this.BindLoginControl(authLoginControl, authSystem); + this.DisplayLoginControl(authLoginControl, false, false); } else { - //if there are social authprovider only - if (_oAuthControls.Count == 0) + // if there are social authprovider only + if (this._oAuthControls.Count == 0) { - //Portal has no login controls enabled so load default DNN control - DisplayLoginControl(defaultLoginControl, false, false); + // Portal has no login controls enabled so load default DNN control + this.DisplayLoginControl(defaultLoginControl, false, false); } } + break; case 1: - //We don't want the control to render with tabbed interface - DisplayLoginControl(_defaultauthLogin.Count == 1 - ? _defaultauthLogin[0] - : _loginControls.Count == 1 - ? _loginControls[0] - : _oAuthControls[0], - false, - false); + // We don't want the control to render with tabbed interface + this.DisplayLoginControl( + this._defaultauthLogin.Count == 1 + ? this._defaultauthLogin[0] + : this._loginControls.Count == 1 + ? this._loginControls[0] + : this._oAuthControls[0], + false, + false); break; default: - //make sure defaultAuth provider control is diplayed first - if (_defaultauthLogin.Count > 0) + // make sure defaultAuth provider control is diplayed first + if (this._defaultauthLogin.Count > 0) { - DisplayTabbedLoginControl(_defaultauthLogin[0], tsLogin.Tabs); + this.DisplayTabbedLoginControl(this._defaultauthLogin[0], this.tsLogin.Tabs); } - foreach (AuthenticationLoginBase authLoginControl in _loginControls) + foreach (AuthenticationLoginBase authLoginControl in this._loginControls) { - DisplayTabbedLoginControl(authLoginControl, tsLogin.Tabs); + this.DisplayTabbedLoginControl(authLoginControl, this.tsLogin.Tabs); } break; } - BindOAuthControls(); + + this.BindOAuthControls(); } private void BindOAuthControls() { - foreach (OAuthLoginBase oAuthLoginControl in _oAuthControls) + foreach (OAuthLoginBase oAuthLoginControl in this._oAuthControls) { - socialLoginControls.Controls.Add(oAuthLoginControl); + this.socialLoginControls.Controls.Add(oAuthLoginControl); } } private void BindLoginControl(AuthenticationLoginBase authLoginControl, AuthenticationInfo authSystem) { - //set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - //this is necessary for the Localization in PageBase + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase authLoginControl.AuthenticationType = authSystem.AuthenticationType; authLoginControl.ID = Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc) + "_" + authSystem.AuthenticationType; authLoginControl.LocalResourceFile = authLoginControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc); - authLoginControl.RedirectURL = RedirectURL; - authLoginControl.ModuleConfiguration = ModuleConfiguration; + authLoginControl.RedirectURL = this.RedirectURL; + authLoginControl.ModuleConfiguration = this.ModuleConfiguration; if (authSystem.AuthenticationType != "DNN") { authLoginControl.ViewStateMode = ViewStateMode.Enabled; } - //attempt to inject control attributes - AddLoginControlAttributes(authLoginControl); - authLoginControl.UserAuthenticated += UserAuthenticated; + // attempt to inject control attributes + this.AddLoginControlAttributes(authLoginControl); + authLoginControl.UserAuthenticated += this.UserAuthenticated; } private void BindRegister() { - lblType.Text = AuthenticationType; - lblToken.Text = UserToken; + this.lblType.Text = this.AuthenticationType; + this.lblToken.Text = this.UserToken; - //Verify that the current user has access to this page - if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && Request.IsAuthenticated == false) + // Verify that the current user has access to this page + if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && this.Request.IsAuthenticated == false) { - Response.Redirect(_navigationManager.NavigateURL("Access Denied"), true); + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); } - lblRegisterHelp.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS"); - switch (PortalSettings.UserRegistration) + + this.lblRegisterHelp.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS"); + switch (this.PortalSettings.UserRegistration) { case (int)Globals.PortalRegistrationType.PrivateRegistration: - lblRegisterHelp.Text += Localization.GetString("PrivateMembership", Localization.SharedResourceFile); + this.lblRegisterHelp.Text += Localization.GetString("PrivateMembership", Localization.SharedResourceFile); break; case (int)Globals.PortalRegistrationType.PublicRegistration: - lblRegisterHelp.Text += Localization.GetString("PublicMembership", Localization.SharedResourceFile); + this.lblRegisterHelp.Text += Localization.GetString("PublicMembership", Localization.SharedResourceFile); break; case (int)Globals.PortalRegistrationType.VerifiedRegistration: - lblRegisterHelp.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile); + this.lblRegisterHelp.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile); break; } - if (AutoRegister) + + if (this.AutoRegister) { - InitialiseUser(); + this.InitialiseUser(); } + bool UserValid = true; - if (string.IsNullOrEmpty(User.Username) || string.IsNullOrEmpty(User.Email) || string.IsNullOrEmpty(User.FirstName) || string.IsNullOrEmpty(User.LastName)) + if (string.IsNullOrEmpty(this.User.Username) || string.IsNullOrEmpty(this.User.Email) || string.IsNullOrEmpty(this.User.FirstName) || string.IsNullOrEmpty(this.User.LastName)) { UserValid = Null.NullBoolean; } - if (AutoRegister && UserValid) + + if (this.AutoRegister && UserValid) { - ctlUser.Visible = false; - lblRegisterTitle.Text = Localization.GetString("CreateTitle", LocalResourceFile); - cmdCreateUser.Text = Localization.GetString("cmdCreate", LocalResourceFile); + this.ctlUser.Visible = false; + this.lblRegisterTitle.Text = Localization.GetString("CreateTitle", this.LocalResourceFile); + this.cmdCreateUser.Text = Localization.GetString("cmdCreate", this.LocalResourceFile); } else { - lblRegisterHelp.Text += Localization.GetString("Required", Localization.SharedResourceFile); - lblRegisterTitle.Text = Localization.GetString("RegisterTitle", LocalResourceFile); - cmdCreateUser.Text = Localization.GetString("cmdRegister", LocalResourceFile); - ctlUser.ShowPassword = false; - ctlUser.ShowUpdate = false; - ctlUser.User = User; - ctlUser.DataBind(); + this.lblRegisterHelp.Text += Localization.GetString("Required", Localization.SharedResourceFile); + this.lblRegisterTitle.Text = Localization.GetString("RegisterTitle", this.LocalResourceFile); + this.cmdCreateUser.Text = Localization.GetString("cmdRegister", this.LocalResourceFile); + this.ctlUser.ShowPassword = false; + this.ctlUser.ShowUpdate = false; + this.ctlUser.User = this.User; + this.ctlUser.DataBind(); } } private void DisplayLoginControl(AuthenticationLoginBase authLoginControl, bool addHeader, bool addFooter) { - //Create a
        to hold the control + // Create a
        to hold the control var container = new HtmlGenericControl { TagName = "div", ID = authLoginControl.AuthenticationType, ViewStateMode = ViewStateMode.Disabled }; - //Add Settings Control to Container + // Add Settings Control to Container container.Controls.Add(authLoginControl); - //Add a Section Header + // Add a Section Header SectionHeadControl sectionHeadControl; if (addHeader) { - sectionHeadControl = (SectionHeadControl)LoadControl("~/controls/SectionHeadControl.ascx"); + sectionHeadControl = (SectionHeadControl)this.LoadControl("~/controls/SectionHeadControl.ascx"); sectionHeadControl.IncludeRule = true; sectionHeadControl.CssClass = "Head"; sectionHeadControl.Text = Localization.GetString("Title", authLoginControl.LocalResourceFile); sectionHeadControl.Section = container.ID; - //Add Section Head Control to Container - pnlLoginContainer.Controls.Add(sectionHeadControl); + // Add Section Head Control to Container + this.pnlLoginContainer.Controls.Add(sectionHeadControl); } - //Add Container to Controls - pnlLoginContainer.Controls.Add(container); + // Add Container to Controls + this.pnlLoginContainer.Controls.Add(container); - - //Add LineBreak + // Add LineBreak if (addFooter) { - pnlLoginContainer.Controls.Add(new LiteralControl("
        ")); + this.pnlLoginContainer.Controls.Add(new LiteralControl("
        ")); } - //Display the container - pnlLoginContainer.Visible = true; + // Display the container + this.pnlLoginContainer.Visible = true; } private void DisplayTabbedLoginControl(AuthenticationLoginBase authLoginControl, TabStripTabCollection Tabs) @@ -618,57 +762,58 @@ private void DisplayTabbedLoginControl(AuthenticationLoginBase authLoginControl, tab.Controls.Add(authLoginControl); Tabs.Add(tab); - tsLogin.Visible = true; + this.tsLogin.Visible = true; } private void InitialiseUser() { - //Load any Profile properties that may have been returned - UpdateProfile(User, false); + // Load any Profile properties that may have been returned + this.UpdateProfile(this.User, false); - //Set UserName to authentication Token - User.Username = GenerateUserName(); + // Set UserName to authentication Token + this.User.Username = this.GenerateUserName(); - //Set DisplayName to UserToken if null - if (string.IsNullOrEmpty(User.DisplayName)) + // Set DisplayName to UserToken if null + if (string.IsNullOrEmpty(this.User.DisplayName)) { - User.DisplayName = UserToken.Replace("http://", "").TrimEnd('/'); + this.User.DisplayName = this.UserToken.Replace("http://", string.Empty).TrimEnd('/'); } - //Parse DisplayName into FirstName/LastName - if (User.DisplayName.IndexOf(' ') > 0) + // Parse DisplayName into FirstName/LastName + if (this.User.DisplayName.IndexOf(' ') > 0) { - User.FirstName = User.DisplayName.Substring(0, User.DisplayName.IndexOf(' ')); - User.LastName = User.DisplayName.Substring(User.DisplayName.IndexOf(' ') + 1); + this.User.FirstName = this.User.DisplayName.Substring(0, this.User.DisplayName.IndexOf(' ')); + this.User.LastName = this.User.DisplayName.Substring(this.User.DisplayName.IndexOf(' ') + 1); } - //Set FirstName to Authentication Type (if null) - if (string.IsNullOrEmpty(User.FirstName)) + // Set FirstName to Authentication Type (if null) + if (string.IsNullOrEmpty(this.User.FirstName)) { - User.FirstName = AuthenticationType; + this.User.FirstName = this.AuthenticationType; } - //Set FirstName to "User" (if null) - if (string.IsNullOrEmpty(User.LastName)) + + // Set FirstName to "User" (if null) + if (string.IsNullOrEmpty(this.User.LastName)) { - User.LastName = "User"; + this.User.LastName = "User"; } } private string GenerateUserName() { - if (!string.IsNullOrEmpty(UserName)) + if (!string.IsNullOrEmpty(this.UserName)) { - return UserName; + return this.UserName; } - //Try Email prefix + // Try Email prefix var emailPrefix = string.Empty; - if (!string.IsNullOrEmpty(User.Email)) + if (!string.IsNullOrEmpty(this.User.Email)) { - if (User.Email.IndexOf("@", StringComparison.Ordinal) != -1) + if (this.User.Email.IndexOf("@", StringComparison.Ordinal) != -1) { - emailPrefix = User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal)); - var user = UserController.GetUserByName(PortalId, emailPrefix); + emailPrefix = this.User.Email.Substring(0, this.User.Email.IndexOf("@", StringComparison.Ordinal)); + var user = UserController.GetUserByName(this.PortalId, emailPrefix); if (user == null) { return emailPrefix; @@ -676,55 +821,55 @@ private string GenerateUserName() } } - //Try First Name - if (!string.IsNullOrEmpty(User.FirstName)) + // Try First Name + if (!string.IsNullOrEmpty(this.User.FirstName)) { - var user = UserController.GetUserByName(PortalId, User.FirstName); + var user = UserController.GetUserByName(this.PortalId, this.User.FirstName); if (user == null) { - return User.FirstName; + return this.User.FirstName; } } - //Try Last Name - if (!string.IsNullOrEmpty(User.LastName)) + // Try Last Name + if (!string.IsNullOrEmpty(this.User.LastName)) { - var user = UserController.GetUserByName(PortalId, User.LastName); + var user = UserController.GetUserByName(this.PortalId, this.User.LastName); if (user == null) { - return User.LastName; + return this.User.LastName; } } - //Try First Name + space + First letter last name - if (!string.IsNullOrEmpty(User.LastName) && !string.IsNullOrEmpty(User.FirstName)) + // Try First Name + space + First letter last name + if (!string.IsNullOrEmpty(this.User.LastName) && !string.IsNullOrEmpty(this.User.FirstName)) { - var newUserName = User.FirstName + " " + User.LastName.Substring(0, 1); - var user = UserController.GetUserByName(PortalId, newUserName); + var newUserName = this.User.FirstName + " " + this.User.LastName.Substring(0, 1); + var user = UserController.GetUserByName(this.PortalId, newUserName); if (user == null) { return newUserName; } } - //Try First letter of First Name + lastname - if (!string.IsNullOrEmpty(User.LastName) && !string.IsNullOrEmpty(User.FirstName)) + // Try First letter of First Name + lastname + if (!string.IsNullOrEmpty(this.User.LastName) && !string.IsNullOrEmpty(this.User.FirstName)) { - var newUserName = User.FirstName.Substring(0, 1) + User.LastName; - var user = UserController.GetUserByName(PortalId, newUserName); + var newUserName = this.User.FirstName.Substring(0, 1) + this.User.LastName; + var user = UserController.GetUserByName(this.PortalId, newUserName); if (user == null) { return newUserName; } } - //Try Email Prefix + incremental numbers until unique name found + // Try Email Prefix + incremental numbers until unique name found if (!string.IsNullOrEmpty(emailPrefix)) { for (var i = 1; i < 10000; i++) { var newUserName = emailPrefix + i; - var user = UserController.GetUserByName(PortalId, newUserName); + var user = UserController.GetUserByName(this.PortalId, newUserName); if (user == null) { return newUserName; @@ -732,103 +877,109 @@ private string GenerateUserName() } } - return UserToken.Replace("http://", "").TrimEnd('/'); + return this.UserToken.Replace("http://", string.Empty).TrimEnd('/'); } /// ----------------------------------------------------------------------------- /// - /// ShowPanel controls what "panel" is to be displayed + /// ShowPanel controls what "panel" is to be displayed. /// /// ----------------------------------------------------------------------------- private void ShowPanel() { - bool showLogin = (PageNo == 0); - bool showRegister = (PageNo == 1); - bool showPassword = (PageNo == 2); - bool showProfile = (PageNo == 3); - bool showDataConsent = (PageNo == 4); - pnlProfile.Visible = showProfile; - pnlPassword.Visible = showPassword; - pnlLogin.Visible = showLogin; - pnlRegister.Visible = showRegister; - pnlAssociate.Visible = showRegister; - pnlDataConsent.Visible = showDataConsent; - switch (PageNo) + bool showLogin = this.PageNo == 0; + bool showRegister = this.PageNo == 1; + bool showPassword = this.PageNo == 2; + bool showProfile = this.PageNo == 3; + bool showDataConsent = this.PageNo == 4; + this.pnlProfile.Visible = showProfile; + this.pnlPassword.Visible = showPassword; + this.pnlLogin.Visible = showLogin; + this.pnlRegister.Visible = showRegister; + this.pnlAssociate.Visible = showRegister; + this.pnlDataConsent.Visible = showDataConsent; + switch (this.PageNo) { case 0: - BindLogin(); + this.BindLogin(); break; case 1: - BindRegister(); + this.BindRegister(); break; case 2: - ctlPassword.UserId = UserId; - ctlPassword.DataBind(); + this.ctlPassword.UserId = this.UserId; + this.ctlPassword.DataBind(); break; case 3: - ctlProfile.UserId = UserId; - ctlProfile.DataBind(); + this.ctlProfile.UserId = this.UserId; + this.ctlProfile.DataBind(); break; case 4: - ctlDataConsent.UserId = UserId; - ctlDataConsent.DataBind(); + this.ctlDataConsent.UserId = this.UserId; + this.ctlDataConsent.DataBind(); break; } if (showProfile && UrlUtils.InPopUp()) { - ScriptManager.RegisterClientScriptBlock(this, GetType(), "ResizePopup", "if(parent.$('#iPopUp').length > 0 && parent.$('#iPopUp').dialog('isOpen')){parent.$('#iPopUp').dialog({width: 950, height: 550}).dialog({position: 'center'});};", true); + ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ResizePopup", "if(parent.$('#iPopUp').length > 0 && parent.$('#iPopUp').dialog('isOpen')){parent.$('#iPopUp').dialog({width: 950, height: 550}).dialog({position: 'center'});};", true); } } private void UpdateProfile(UserInfo objUser, bool update) { bool bUpdateUser = false; - if (ProfileProperties.Count > 0) + if (this.ProfileProperties.Count > 0) { - foreach (string key in ProfileProperties) + foreach (string key in this.ProfileProperties) { switch (key) { case "FirstName": - if (objUser.FirstName != ProfileProperties[key]) + if (objUser.FirstName != this.ProfileProperties[key]) { - objUser.FirstName = ProfileProperties[key]; + objUser.FirstName = this.ProfileProperties[key]; bUpdateUser = true; } + break; case "LastName": - if (objUser.LastName != ProfileProperties[key]) + if (objUser.LastName != this.ProfileProperties[key]) { - objUser.LastName = ProfileProperties[key]; + objUser.LastName = this.ProfileProperties[key]; bUpdateUser = true; } + break; case "Email": - if (objUser.Email != ProfileProperties[key]) + if (objUser.Email != this.ProfileProperties[key]) { - objUser.Email = ProfileProperties[key]; + objUser.Email = this.ProfileProperties[key]; bUpdateUser = true; } + break; case "DisplayName": - if (objUser.DisplayName != ProfileProperties[key]) + if (objUser.DisplayName != this.ProfileProperties[key]) { - objUser.DisplayName = ProfileProperties[key]; + objUser.DisplayName = this.ProfileProperties[key]; bUpdateUser = true; } + break; default: - objUser.Profile.SetProfileProperty(key, ProfileProperties[key]); + objUser.Profile.SetProfileProperty(key, this.ProfileProperties[key]); break; } } + if (update) { if (bUpdateUser) { - UserController.UpdateUser(PortalId, objUser); + UserController.UpdateUser(this.PortalId, objUser); } + ProfileController.UpdateUserProfile(objUser); } } @@ -837,10 +988,10 @@ private void UpdateProfile(UserInfo objUser, bool update) /// ----------------------------------------------------------------------------- /// /// ValidateUser runs when the user has been authorized by the data store. It validates for - /// things such as an expiring password, valid profile, or missing DNN User Association + /// things such as an expiring password, valid profile, or missing DNN User Association. /// - /// The logged in User - /// Ignore the situation where the password is expiring (but not yet expired) + /// The logged in User. + /// Ignore the situation where the password is expiring (but not yet expired). /// ----------------------------------------------------------------------------- private void ValidateUser(UserInfo objUser, bool ignoreExpiring) { @@ -849,128 +1000,133 @@ private void ValidateUser(UserInfo objUser, bool ignoreExpiring) DateTime expiryDate = Null.NullDate; bool okToShowPanel = true; - validStatus = UserController.ValidateUser(objUser, PortalId, ignoreExpiring); + validStatus = UserController.ValidateUser(objUser, this.PortalId, ignoreExpiring); if (PasswordConfig.PasswordExpiry > 0) { expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry); } - UserId = objUser.UserID; - //Check if the User has valid Password/Profile + this.UserId = objUser.UserID; + + // Check if the User has valid Password/Profile switch (validStatus) { case UserValidStatus.VALID: - //check if the user is an admin/host and validate their IP + // check if the user is an admin/host and validate their IP if (Host.EnableIPChecking) { - bool isAdminUser = objUser.IsSuperUser || objUser.IsInRole(PortalSettings.AdministratorRoleName); + bool isAdminUser = objUser.IsSuperUser || objUser.IsInRole(this.PortalSettings.AdministratorRoleName); if (isAdminUser) { - var clientIp = NetworkUtils.GetClientIpAddress(Request); + var clientIp = NetworkUtils.GetClientIpAddress(this.Request); if (IPFilterController.Instance.IsIPBanned(clientIp)) { PortalSecurity.Instance.SignOut(); - AddModuleMessage("IPAddressBanned", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("IPAddressBanned", ModuleMessage.ModuleMessageType.RedError, true); okToShowPanel = false; break; } } } - //Set the Page Culture(Language) based on the Users Preferred Locale - if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null) && LocaleEnabled(objUser.Profile.PreferredLocale)) + // Set the Page Culture(Language) based on the Users Preferred Locale + if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null) && this.LocaleEnabled(objUser.Profile.PreferredLocale)) { Localization.SetLanguage(objUser.Profile.PreferredLocale); } else { - Localization.SetLanguage(PortalSettings.DefaultLanguage); + Localization.SetLanguage(this.PortalSettings.DefaultLanguage); } - //Set the Authentication Type used - AuthenticationController.SetAuthenticationType(AuthenticationType); + // Set the Authentication Type used + AuthenticationController.SetAuthenticationType(this.AuthenticationType); - //Complete Login + // Complete Login var userRequestIpAddressController = UserRequestIPAddressController.Instance; - var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(Request)); - UserController.UserLogin(PortalId, objUser, PortalSettings.PortalName, ipAddress, RememberMe); + var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); + UserController.UserLogin(this.PortalId, objUser, this.PortalSettings.PortalName, ipAddress, this.RememberMe); - //check whether user request comes with IPv6 and log it to make sure admin is aware of that + // check whether user request comes with IPv6 and log it to make sure admin is aware of that if (string.IsNullOrWhiteSpace(ipAddress)) { - var ipAddressV6 = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(Request), IPAddressFamily.IPv6); + var ipAddressV6 = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request), IPAddressFamily.IPv6); if (!string.IsNullOrWhiteSpace(ipAddressV6)) { - AddEventLog(objUser.UserID, objUser.Username, PortalId, "IPv6", ipAddressV6); + this.AddEventLog(objUser.UserID, objUser.Username, this.PortalId, "IPv6", ipAddressV6); } } - //redirect browser - var redirectUrl = RedirectURL; + // redirect browser + var redirectUrl = this.RedirectURL; - //Clear the cookie - HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", "") + // Clear the cookie + HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", string.Empty) { Expires = DateTime.Now.AddDays(-1), - Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }); - Response.Redirect(redirectUrl, true); + this.Response.Redirect(redirectUrl, true); break; case UserValidStatus.PASSWORDEXPIRED: - strMessage = string.Format(Localization.GetString("PasswordExpired", LocalResourceFile), expiryDate.ToLongDateString()); - AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); - PageNo = 2; - pnlProceed.Visible = false; + strMessage = string.Format(Localization.GetString("PasswordExpired", this.LocalResourceFile), expiryDate.ToLongDateString()); + this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 2; + this.pnlProceed.Visible = false; break; case UserValidStatus.PASSWORDEXPIRING: - strMessage = string.Format(Localization.GetString("PasswordExpiring", LocalResourceFile), expiryDate.ToLongDateString()); - AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); - PageNo = 2; - pnlProceed.Visible = true; + strMessage = string.Format(Localization.GetString("PasswordExpiring", this.LocalResourceFile), expiryDate.ToLongDateString()); + this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 2; + this.pnlProceed.Visible = true; break; case UserValidStatus.UPDATEPASSWORD: - var portalAlias = Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias); + var portalAlias = Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias); if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { - UserController.ResetPasswordToken(User); + UserController.ResetPasswordToken(this.User); objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID); } + var redirTo = string.Format("{0}/default.aspx?ctl=PasswordReset&resetToken={1}&forced=true", portalAlias, objUser.PasswordResetToken); - Response.Redirect(redirTo); + this.Response.Redirect(redirTo); break; case UserValidStatus.UPDATEPROFILE: - //Save UserID in ViewState so that can update profile later. - UserId = objUser.UserID; + // Save UserID in ViewState so that can update profile later. + this.UserId = objUser.UserID; - //When the user need update its profile to complete login, we need clear the login status because if the logrin is from - //3rd party login provider, it may call UserController.UserLogin because they doesn't check this situation. + // When the user need update its profile to complete login, we need clear the login status because if the logrin is from + // 3rd party login provider, it may call UserController.UserLogin because they doesn't check this situation. PortalSecurity.Instance.SignOut(); - //Admin has forced profile update - AddModuleMessage("ProfileUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true); - PageNo = 3; + + // Admin has forced profile update + this.AddModuleMessage("ProfileUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 3; break; case UserValidStatus.MUSTAGREETOTERMS: - if (PortalSettings.DataConsentConsentRedirect == -1) + if (this.PortalSettings.DataConsentConsentRedirect == -1) { - UserId = objUser.UserID; - AddModuleMessage("MustConsent", ModuleMessage.ModuleMessageType.YellowWarning, true); - PageNo = 4; + this.UserId = objUser.UserID; + this.AddModuleMessage("MustConsent", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 4; } else { // Use the reset password token to identify the user during the redirect UserController.ResetPasswordToken(objUser); objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID); - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.DataConsentConsentRedirect, "", string.Format("token={0}", objUser.PasswordResetToken))); + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.DataConsentConsentRedirect, string.Empty, string.Format("token={0}", objUser.PasswordResetToken))); } + break; } + if (okToShowPanel) { - ShowPanel(); + this.ShowPanel(); } } @@ -979,224 +1135,95 @@ private bool UserNeedsVerification() var userInfo = UserController.Instance.GetCurrentUserInfo(); return !userInfo.IsSuperUser && userInfo.IsInRole("Unverified Users") && - PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration && - !string.IsNullOrEmpty(Request.QueryString["verificationcode"]); + this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration && + !string.IsNullOrEmpty(this.Request.QueryString["verificationcode"]); } private bool LocaleEnabled(string locale) { - return LocaleController.Instance.GetLocales(PortalSettings.PortalId).ContainsKey(locale); - } - - #endregion - - #region Event Handlers - - /// - /// Page_Init runs when the control is initialised - /// - /// - /// - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - ctlPassword.PasswordUpdated += PasswordUpdated; - ctlProfile.ProfileUpdated += ProfileUpdated; - ctlUser.UserCreateCompleted += UserCreateCompleted; - ctlDataConsent.DataConsentCompleted += DataConsentCompleted; - - //Set the User Control Properties - ctlUser.ID = "User"; - - //Set the Password Control Properties - ctlPassword.ID = "Password"; - - //Set the Profile Control Properties - ctlProfile.ID = "Profile"; - - //Set the Data Consent Control Properties - ctlDataConsent.ID = "DataConsent"; - - //Override the redirected page title if page has loaded with ctl=Login - if (Request.QueryString["ctl"] != null) - { - if (Request.QueryString["ctl"].ToLowerInvariant() == "login") - { - var myPage = (CDefault)Page; - if (myPage.PortalSettings.LoginTabId == TabId || myPage.PortalSettings.LoginTabId == -1) - { - myPage.Title = Localization.GetString("ControlTitle_login", LocalResourceFile); - } - } - } - } - - /// - /// Page_Load runs when the control is loaded - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cmdAssociate.Click += cmdAssociate_Click; - cmdCreateUser.Click += cmdCreateUser_Click; - cmdProceed.Click += cmdProceed_Click; - - //Verify if portal has a customized login page - if (!Null.IsNull(PortalSettings.LoginTabId) && Globals.IsAdminControl()) - { - if (Globals.ValidateLoginTabID(PortalSettings.LoginTabId)) - { - //login page exists and trying to access this control directly with url param -> not allowed - var parameters = new string[3]; - if (!string.IsNullOrEmpty(Request.QueryString["returnUrl"])) - { - parameters[0] = "returnUrl=" + HttpUtility.UrlEncode(Request.QueryString["returnUrl"]); - } - if (!string.IsNullOrEmpty(Request.QueryString["username"])) - { - parameters[1] = "username=" + HttpUtility.UrlEncode(Request.QueryString["username"]); - } - if (!string.IsNullOrEmpty(Request.QueryString["verificationcode"])) - { - parameters[2] = "verificationcode=" + HttpUtility.UrlEncode(Request.QueryString["verificationcode"]); - } - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.LoginTabId, "", parameters)); - } - } - if (Page.IsPostBack == false) - { - try - { - PageNo = 0; - } - catch (Exception ex) - { - //control not there - Logger.Error(ex); - } - } - if (!Request.IsAuthenticated || UserNeedsVerification()) - { - ShowPanel(); - } - else //user is already authenticated - { - //if a Login Page has not been specified for the portal - if (Globals.IsAdminControl()) - { - //redirect browser - Response.Redirect(RedirectURL, true); - } - else //make module container invisible if user is not a page admin - { - var path = RedirectURL.Split('?')[0]; - if (NeedRedirectAfterLogin && path != _navigationManager.NavigateURL() && path != _navigationManager.NavigateURL(PortalSettings.HomeTabId)) - { - Response.Redirect(RedirectURL, true); - } - - if (TabPermissionController.CanAdminPage()) - { - ShowPanel(); - } - else - { - ContainerControl.Visible = false; - } - } - } - divCaptcha.Visible = UseCaptcha; - - if (UseCaptcha) - { - ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile); - ctlCaptcha.Text = Localization.GetString("CaptchaText", Localization.SharedResourceFile); - } - + return LocaleController.Instance.GetLocales(this.PortalSettings.PortalId).ContainsKey(locale); } /// - /// cmdAssociate_Click runs when the associate button is clicked + /// cmdAssociate_Click runs when the associate button is clicked. /// /// /// protected void cmdAssociate_Click(object sender, EventArgs e) { - if ((UseCaptcha && ctlCaptcha.IsValid) || (!UseCaptcha)) + if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || (!this.UseCaptcha)) { UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; var userRequestIpAddressController = UserRequestIPAddressController.Instance; - var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(Request)); - UserInfo objUser = UserController.ValidateUser(PortalId, - txtUsername.Text, - txtPassword.Text, - "DNN", - "", - PortalSettings.PortalName, - ipAddress, - ref loginStatus); + var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); + UserInfo objUser = UserController.ValidateUser( + this.PortalId, + this.txtUsername.Text, + this.txtPassword.Text, + "DNN", + string.Empty, + this.PortalSettings.PortalName, + ipAddress, + ref loginStatus); if (loginStatus == UserLoginStatus.LOGIN_SUCCESS) { - //Assocate alternate Login with User and proceed with Login - AuthenticationController.AddUserAuthentication(objUser.UserID, AuthenticationType, UserToken); + // Assocate alternate Login with User and proceed with Login + AuthenticationController.AddUserAuthentication(objUser.UserID, this.AuthenticationType, this.UserToken); if (objUser != null) { - UpdateProfile(objUser, true); + this.UpdateProfile(objUser, true); } - ValidateUser(objUser, true); + + this.ValidateUser(objUser, true); } else { - AddModuleMessage("AssociationFailed", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("AssociationFailed", ModuleMessage.ModuleMessageType.RedError, true); } } } /// - /// cmdCreateUser runs when the register (as new user) button is clicked + /// cmdCreateUser runs when the register (as new user) button is clicked. /// /// /// protected void cmdCreateUser_Click(object sender, EventArgs e) { - User.Membership.Password = UserController.GeneratePassword(); + this.User.Membership.Password = UserController.GeneratePassword(); - if (AutoRegister) + if (this.AutoRegister) { - ctlUser.User = User; + this.ctlUser.User = this.User; - //Call the Create User method of the User control so that it can create - //the user and raise the appropriate event(s) - ctlUser.CreateUser(); + // Call the Create User method of the User control so that it can create + // the user and raise the appropriate event(s) + this.ctlUser.CreateUser(); } else { - if (ctlUser.IsValid) + if (this.ctlUser.IsValid) { - //Call the Create User method of the User control so that it can create - //the user and raise the appropriate event(s) - ctlUser.CreateUser(); + // Call the Create User method of the User control so that it can create + // the user and raise the appropriate event(s) + this.ctlUser.CreateUser(); } } } /// - /// cmdProceed_Click runs when the Proceed Anyway button is clicked + /// cmdProceed_Click runs when the Proceed Anyway button is clicked. /// /// /// protected void cmdProceed_Click(object sender, EventArgs e) { - var user = ctlPassword.User; - ValidateUser(user, true); + var user = this.ctlPassword.User; + this.ValidateUser(user, true); } /// - /// PasswordUpdated runs when the password is updated + /// PasswordUpdated runs when the password is updated. /// /// /// @@ -1205,24 +1232,24 @@ protected void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs PasswordUpdateStatus status = e.UpdateStatus; if (status == PasswordUpdateStatus.Success) { - AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); - var user = ctlPassword.User; + this.AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); + var user = this.ctlPassword.User; user.Membership.LastPasswordChangeDate = DateTime.Now; user.Membership.UpdatePassword = false; - LoginStatus = user.IsSuperUser ? UserLoginStatus.LOGIN_SUPERUSER : UserLoginStatus.LOGIN_SUCCESS; + this.LoginStatus = user.IsSuperUser ? UserLoginStatus.LOGIN_SUPERUSER : UserLoginStatus.LOGIN_SUCCESS; UserLoginStatus userstatus = UserLoginStatus.LOGIN_FAILURE; UserController.CheckInsecurePassword(user.Username, user.Membership.Password, ref userstatus); - LoginStatus = userstatus; - ValidateUser(user, true); + this.LoginStatus = userstatus; + this.ValidateUser(user, true); } else { - AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); } } /// - /// DataConsentCompleted runs after the user has gone through the data consent screen + /// DataConsentCompleted runs after the user has gone through the data consent screen. /// /// /// @@ -1231,37 +1258,37 @@ protected void DataConsentCompleted(object sender, DataConsent.DataConsentEventA switch (e.Status) { case DataConsent.DataConsentStatus.Consented: - ValidateUser(ctlDataConsent.User, true); + this.ValidateUser(this.ctlDataConsent.User, true); break; case DataConsent.DataConsentStatus.Cancelled: case DataConsent.DataConsentStatus.RemovedAccount: - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.HomeTabId), true); + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId), true); break; case DataConsent.DataConsentStatus.FailedToRemoveAccount: - AddModuleMessage("FailedToRemoveAccount", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("FailedToRemoveAccount", ModuleMessage.ModuleMessageType.RedError, true); break; } } /// - /// ProfileUpdated runs when the profile is updated + /// ProfileUpdated runs when the profile is updated. /// protected void ProfileUpdated(object sender, EventArgs e) { - //Authorize User - ValidateUser(ctlProfile.User, true); + // Authorize User + this.ValidateUser(this.ctlProfile.User, true); } /// /// UserAuthenticated runs when the user is authenticated by one of the child - /// Authentication controls + /// Authentication controls. /// protected void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) { - LoginStatus = e.LoginStatus; + this.LoginStatus = e.LoginStatus; - //Check the Login Status - switch (LoginStatus) + // Check the Login Status + switch (this.LoginStatus) { case UserLoginStatus.LOGIN_USERNOTAPPROVED: switch (e.Message) @@ -1269,134 +1296,139 @@ protected void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) case "UnverifiedUser": if (e.User != null) { - //First update the profile (if any properties have been passed) - AuthenticationType = e.AuthenticationType; - ProfileProperties = e.Profile; - RememberMe = e.RememberMe; - UpdateProfile(e.User, true); - ValidateUser(e.User, false); + // First update the profile (if any properties have been passed) + this.AuthenticationType = e.AuthenticationType; + this.ProfileProperties = e.Profile; + this.RememberMe = e.RememberMe; + this.UpdateProfile(e.User, true); + this.ValidateUser(e.User, false); } + break; case "EnterCode": - AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.YellowWarning, true); + this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.YellowWarning, true); break; case "InvalidCode": case "UserNotAuthorized": - AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); break; default: - AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); + this.AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); break; } + break; case UserLoginStatus.LOGIN_USERLOCKEDOUT: if (Host.AutoAccountUnlockDuration > 0) { - AddLocalizedModuleMessage(string.Format(Localization.GetString("UserLockedOut", LocalResourceFile), Host.AutoAccountUnlockDuration), ModuleMessage.ModuleMessageType.RedError, true); + this.AddLocalizedModuleMessage(string.Format(Localization.GetString("UserLockedOut", this.LocalResourceFile), Host.AutoAccountUnlockDuration), ModuleMessage.ModuleMessageType.RedError, true); } else { - AddLocalizedModuleMessage(Localization.GetString("UserLockedOut_ContactAdmin", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError, true); + this.AddLocalizedModuleMessage(Localization.GetString("UserLockedOut_ContactAdmin", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError, true); } - //notify administrator about account lockout ( possible hack attempt ) + + // notify administrator about account lockout ( possible hack attempt ) var Custom = new ArrayList { e.UserToken }; var message = new Message { - FromUserID = PortalSettings.AdministratorId, - ToUserID = PortalSettings.AdministratorId, - Subject = Localization.GetSystemMessage(PortalSettings, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom), - Body = Localization.GetSystemMessage(PortalSettings, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom), - Status = MessageStatusType.Unread + FromUserID = this.PortalSettings.AdministratorId, + ToUserID = this.PortalSettings.AdministratorId, + Subject = Localization.GetSystemMessage(this.PortalSettings, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom), + Body = Localization.GetSystemMessage(this.PortalSettings, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom), + Status = MessageStatusType.Unread, }; - //_messagingController.SaveMessage(_message); - Mail.SendEmail(PortalSettings.Email, PortalSettings.Email, message.Subject, message.Body); + // _messagingController.SaveMessage(_message); + Mail.SendEmail(this.PortalSettings.Email, this.PortalSettings.Email, message.Subject, message.Body); break; case UserLoginStatus.LOGIN_FAILURE: - //A Login Failure can mean one of two things: + // A Login Failure can mean one of two things: // 1 - User was authenticated by the Authentication System but is not "affiliated" with a DNN Account // 2 - User was not authenticated if (e.Authenticated) { - AutoRegister = e.AutoRegister; - AuthenticationType = e.AuthenticationType; - ProfileProperties = e.Profile; - UserToken = e.UserToken; - UserName = e.UserName; - if (AutoRegister) + this.AutoRegister = e.AutoRegister; + this.AuthenticationType = e.AuthenticationType; + this.ProfileProperties = e.Profile; + this.UserToken = e.UserToken; + this.UserName = e.UserName; + if (this.AutoRegister) { - InitialiseUser(); - User.Membership.Password = UserController.GeneratePassword(); + this.InitialiseUser(); + this.User.Membership.Password = UserController.GeneratePassword(); - ctlUser.User = User; + this.ctlUser.User = this.User; - //Call the Create User method of the User control so that it can create - //the user and raise the appropriate event(s) - ctlUser.CreateUser(); + // Call the Create User method of the User control so that it can create + // the user and raise the appropriate event(s) + this.ctlUser.CreateUser(); } else { - PageNo = 1; - ShowPanel(); + this.PageNo = 1; + this.ShowPanel(); } } else { if (string.IsNullOrEmpty(e.Message)) { - AddModuleMessage("LoginFailed", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("LoginFailed", ModuleMessage.ModuleMessageType.RedError, true); } else { - AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); + this.AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); } } + break; default: if (e.User != null) { - //First update the profile (if any properties have been passed) - AuthenticationType = e.AuthenticationType; - ProfileProperties = e.Profile; - RememberMe = e.RememberMe; - UpdateProfile(e.User, true); - ValidateUser(e.User, (e.AuthenticationType != "DNN")); + // First update the profile (if any properties have been passed) + this.AuthenticationType = e.AuthenticationType; + this.ProfileProperties = e.Profile; + this.RememberMe = e.RememberMe; + this.UpdateProfile(e.User, true); + this.ValidateUser(e.User, e.AuthenticationType != "DNN"); } + break; } } /// - /// UserCreateCompleted runs when a new user has been Created + /// UserCreateCompleted runs when a new user has been Created. /// /// /// protected void UserCreateCompleted(object sender, UserUserControlBase.UserCreatedEventArgs e) { - var strMessage = ""; + var strMessage = string.Empty; try { if (e.CreateStatus == UserCreateStatus.Success) { - //Assocate alternate Login with User and proceed with Login - AuthenticationController.AddUserAuthentication(e.NewUser.UserID, AuthenticationType, UserToken); + // Assocate alternate Login with User and proceed with Login + AuthenticationController.AddUserAuthentication(e.NewUser.UserID, this.AuthenticationType, this.UserToken); - strMessage = CompleteUserCreation(e.CreateStatus, e.NewUser, e.Notify, true); - if ((string.IsNullOrEmpty(strMessage))) + strMessage = this.CompleteUserCreation(e.CreateStatus, e.NewUser, e.Notify, true); + if (string.IsNullOrEmpty(strMessage)) { - //First update the profile (if any properties have been passed) - UpdateProfile(e.NewUser, true); + // First update the profile (if any properties have been passed) + this.UpdateProfile(e.NewUser, true); - ValidateUser(e.NewUser, true); + this.ValidateUser(e.NewUser, true); } } else { - AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); + this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -1409,13 +1441,10 @@ private void AddEventLog(int userId, string username, int portalId, string prope LogUserID = userId, LogUserName = username, LogPortalID = portalId, - LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() + LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(), }; log.AddProperty(propertyName, propertyValue); LogController.Instance.AddLog(log); } - - #endregion - } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs index 5ce17f9b4ea..2f789068b47 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs @@ -1,121 +1,107 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Threading; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Authentication { - - /// - /// The Logoff UserModuleBase is used to log off a registered user - /// - /// - /// - public partial class Logoff : UserModuleBase - { - - #region Private Methods - - private void Redirect() - { - //Redirect browser back to portal - Response.Redirect(AuthenticationController.GetLogoffRedirectURL(PortalSettings, Request), true); - } - - private void DoLogoff() - { - try - { - //Remove user from cache - if (User != null) - { - DataCache.ClearUserCache(PortalSettings.PortalId, Context.User.Identity.Name); - } - var objPortalSecurity = PortalSecurity.Instance; - objPortalSecurity.SignOut(); - } - catch (Exception exc) //Page failed to load - { - Exceptions.ProcessPageLoadException(exc); - } - } - - #endregion - - #region Event Handlers - - /// - /// Page_Load runs when the control is loaded - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - try - { - //Get the Authentication System associated with the current User - var authSystem = AuthenticationController.GetAuthenticationType(); - - if (authSystem != null && !string.IsNullOrEmpty(authSystem.LogoffControlSrc)) - { - var authLogoffControl = (AuthenticationLogoffBase) LoadControl("~/" + authSystem.LogoffControlSrc); - - //set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - //this is necessary for the Localization in PageBase - authLogoffControl.AuthenticationType = authSystem.AuthenticationType; - authLogoffControl.ID = Path.GetFileNameWithoutExtension(authSystem.LogoffControlSrc) + "_" + authSystem.AuthenticationType; - authLogoffControl.LocalResourceFile = authLogoffControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + - Path.GetFileNameWithoutExtension(authSystem.LogoffControlSrc); - authLogoffControl.ModuleConfiguration = ModuleConfiguration; - - authLogoffControl.LogOff += UserLogOff; - authLogoffControl.Redirect += UserRedirect; - - //Add Login Control to Control - pnlLogoffContainer.Controls.Add(authLogoffControl); - } - else - { - //The current auth system has no custom logoff control so LogOff - DoLogoff(); - Redirect(); - } - } - catch (ThreadAbortException) - { - //Do nothing Response.redirect - } - catch (Exception exc) //Page failed to load - { - Exceptions.ProcessPageLoadException(exc); - } - } - - protected void UserLogOff(Object sender, EventArgs e) - { - DoLogoff(); - } - - protected void UserRedirect(Object sender, EventArgs e) - { - Redirect(); - } - - #endregion - - } + using System; + using System.IO; + using System.Threading; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + + /// + /// The Logoff UserModuleBase is used to log off a registered user. + /// + /// + /// + public partial class Logoff : UserModuleBase + { + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + try + { + // Get the Authentication System associated with the current User + var authSystem = AuthenticationController.GetAuthenticationType(); + + if (authSystem != null && !string.IsNullOrEmpty(authSystem.LogoffControlSrc)) + { + var authLogoffControl = (AuthenticationLogoffBase)this.LoadControl("~/" + authSystem.LogoffControlSrc); + + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + authLogoffControl.AuthenticationType = authSystem.AuthenticationType; + authLogoffControl.ID = Path.GetFileNameWithoutExtension(authSystem.LogoffControlSrc) + "_" + authSystem.AuthenticationType; + authLogoffControl.LocalResourceFile = authLogoffControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + + Path.GetFileNameWithoutExtension(authSystem.LogoffControlSrc); + authLogoffControl.ModuleConfiguration = this.ModuleConfiguration; + + authLogoffControl.LogOff += this.UserLogOff; + authLogoffControl.Redirect += this.UserRedirect; + + // Add Login Control to Control + this.pnlLogoffContainer.Controls.Add(authLogoffControl); + } + else + { + // The current auth system has no custom logoff control so LogOff + this.DoLogoff(); + this.Redirect(); + } + } + catch (ThreadAbortException) + { + // Do nothing Response.redirect + } + catch (Exception exc) // Page failed to load + { + Exceptions.ProcessPageLoadException(exc); + } + } + + protected void UserLogOff(object sender, EventArgs e) + { + this.DoLogoff(); + } + + private void Redirect() + { + // Redirect browser back to portal + this.Response.Redirect(AuthenticationController.GetLogoffRedirectURL(this.PortalSettings, this.Request), true); + } + + private void DoLogoff() + { + try + { + // Remove user from cache + if (this.User != null) + { + DataCache.ClearUserCache(this.PortalSettings.PortalId, this.Context.User.Identity.Name); + } + + var objPortalSecurity = PortalSecurity.Instance; + objPortalSecurity.SignOut(); + } + catch (Exception exc) // Page failed to load + { + Exceptions.ProcessPageLoadException(exc); + } + } + + protected void UserRedirect(object sender, EventArgs e) + { + this.Redirect(); + } + } } diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/AuthenticationEditor.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/AuthenticationEditor.ascx.resx index 5eb9856a332..90b0f007893 100644 --- a/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/AuthenticationEditor.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/AuthenticationEditor.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/EditExtension.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/EditExtension.ascx.resx index 439707defe4..266e834e6ea 100644 --- a/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/EditExtension.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/EditExtension/App_LocalResources/EditExtension.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs index 2126cd2cda2..e71ab60b7d8 100644 --- a/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs @@ -1,25 +1,21 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.EditExtension { + using System; + using System.IO; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// - /// The AuthenticationEditor.ascx control is used to edit the Authentication Properties + /// The AuthenticationEditor.ascx control is used to edit the Authentication Properties. /// /// /// @@ -27,30 +23,25 @@ namespace DotNetNuke.Modules.Admin.EditExtension public partial class AuthenticationEditor : PackageEditorBase { private readonly INavigationManager _navigationManager; + + private AuthenticationInfo _AuthSystem; + private AuthenticationSettingsBase _SettingsControl; public AuthenticationEditor() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - #region "Private Members" - - private AuthenticationInfo _AuthSystem; - private AuthenticationSettingsBase _SettingsControl; - - #endregion - - #region "Protected Properties" - + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } + protected AuthenticationInfo AuthSystem { get { - if (_AuthSystem == null) + if (this._AuthSystem == null) { - _AuthSystem = AuthenticationController.GetAuthenticationServiceByPackageID(PackageID); + this._AuthSystem = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageID); } - return _AuthSystem; + + return this._AuthSystem; } } @@ -66,118 +57,108 @@ protected AuthenticationSettingsBase SettingsControl { get { - if (_SettingsControl == null && !string.IsNullOrEmpty(AuthSystem.SettingsControlSrc)) - { - _SettingsControl = (AuthenticationSettingsBase) LoadControl("~/" + AuthSystem.SettingsControlSrc); - } - return _SettingsControl; - } - } - - #endregion - - #region "Private Methods" - - /// ----------------------------------------------------------------------------- - /// - /// This routine Binds the Authentication System - /// - /// ----------------------------------------------------------------------------- - private void BindAuthentication() - { - if (AuthSystem != null) - { - if (AuthSystem.AuthenticationType == "DNN") - { - authenticationFormReadOnly.DataSource = AuthSystem; - authenticationFormReadOnly.DataBind(); - } - else - { - authenticationForm.DataSource = AuthSystem; - authenticationForm.DataBind(); - } - authenticationFormReadOnly.Visible = IsSuperTab && (AuthSystem.AuthenticationType == "DNN"); - authenticationForm.Visible = IsSuperTab && AuthSystem.AuthenticationType != "DNN"; - - - if (SettingsControl != null) + if (this._SettingsControl == null && !string.IsNullOrEmpty(this.AuthSystem.SettingsControlSrc)) { - //set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - //this is necessary for the Localization in PageBase - SettingsControl.ID = Path.GetFileNameWithoutExtension(AuthSystem.SettingsControlSrc); - - //Add Container to Controls - pnlSettings.Controls.AddAt(0, SettingsControl); - } - else - { - cmdUpdate.Visible = false; + this._SettingsControl = (AuthenticationSettingsBase)this.LoadControl("~/" + this.AuthSystem.SettingsControlSrc); } + + return this._SettingsControl; } - } - - #endregion - - #region "Public Methods" - + } + public override void Initialize() { - pnlSettings.Visible = !IsSuperTab; - if (IsSuperTab) + this.pnlSettings.Visible = !this.IsSuperTab; + if (this.IsSuperTab) { - lblHelp.Text = Localization.GetString("HostHelp", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("HostHelp", this.LocalResourceFile); } else { - if (SettingsControl == null) + if (this.SettingsControl == null) { - lblHelp.Text = Localization.GetString("NoSettings", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("NoSettings", this.LocalResourceFile); } else { - lblHelp.Text = Localization.GetString("AdminHelp", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("AdminHelp", this.LocalResourceFile); } } - BindAuthentication(); + + this.BindAuthentication(); } public override void UpdatePackage() { - if (authenticationForm.IsValid) + if (this.authenticationForm.IsValid) { - var authInfo = authenticationForm.DataSource as AuthenticationInfo; + var authInfo = this.authenticationForm.DataSource as AuthenticationInfo; if (authInfo != null) { AuthenticationController.UpdateAuthentication(authInfo); } } - } - - #endregion - - #region "Event Handlers" + } + + /// ----------------------------------------------------------------------------- + /// + /// This routine Binds the Authentication System. + /// + /// ----------------------------------------------------------------------------- + private void BindAuthentication() + { + if (this.AuthSystem != null) + { + if (this.AuthSystem.AuthenticationType == "DNN") + { + this.authenticationFormReadOnly.DataSource = this.AuthSystem; + this.authenticationFormReadOnly.DataBind(); + } + else + { + this.authenticationForm.DataSource = this.AuthSystem; + this.authenticationForm.DataBind(); + } + + this.authenticationFormReadOnly.Visible = this.IsSuperTab && (this.AuthSystem.AuthenticationType == "DNN"); + this.authenticationForm.Visible = this.IsSuperTab && this.AuthSystem.AuthenticationType != "DNN"; + + if (this.SettingsControl != null) + { + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + this.SettingsControl.ID = Path.GetFileNameWithoutExtension(this.AuthSystem.SettingsControlSrc); + // Add Container to Controls + this.pnlSettings.Controls.AddAt(0, this.SettingsControl); + } + else + { + this.cmdUpdate.Visible = false; + } + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdUpdate.Click += cmdUpdate_Click; - var displayMode = DisplayMode; + this.cmdUpdate.Click += this.cmdUpdate_Click; + var displayMode = this.DisplayMode; if (displayMode == "editor" || displayMode == "settings") { - AuthEditorHead.Visible = AuthEditorHead.EnableViewState = false; + this.AuthEditorHead.Visible = this.AuthEditorHead.EnableViewState = false; } } protected void cmdUpdate_Click(object sender, EventArgs e) { - SettingsControl?.UpdateSettings(); - - var displayMode = DisplayMode; - if (displayMode != "editor" && displayMode != "settings") - Response.Redirect(_navigationManager.NavigateURL(), true); - } - - #endregion + this.SettingsControl?.UpdateSettings(); + + var displayMode = this.DisplayMode; + if (displayMode != "editor" && displayMode != "settings") + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs index 11d2a7612b0..b0201888cd4 100644 --- a/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs @@ -1,38 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Web; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Installer; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Installer.Writers; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.EditExtension { + using System; + using System.IO; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Installer; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Installer.Writers; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; /// ----------------------------------------------------------------------------- /// - /// The EditExtension control is used to edit a Extension + /// The EditExtension control is used to edit a Extension. /// /// /// @@ -45,38 +39,52 @@ public partial class EditExtension : ModuleUserControlBase public EditExtension() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - protected bool IsSuperTab + public string Mode { get { - return (ModuleContext.PortalSettings.ActiveTab.IsSuperTab); + return Convert.ToString(this.ModuleContext.Settings["Extensions_Mode"]); } } - protected string ReturnUrl + public int PackageID { - get { return (string)ViewState["ReturnUrl"]; } - set { ViewState["ReturnUrl"] = value; } + get + { + var packageID = Null.NullInteger; + if (this.Request.QueryString["PackageID"] != null) + { + packageID = int.Parse(this.Request.QueryString["PackageID"]); + } + + return packageID; + } } - public string Mode + protected bool IsSuperTab { get { - return Convert.ToString(ModuleContext.Settings["Extensions_Mode"]); + return this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab; } } - protected string DisplayMode => (Request.QueryString["Display"] ?? "").ToLowerInvariant(); + protected string ReturnUrl + { + get { return (string)this.ViewState["ReturnUrl"]; } + set { this.ViewState["ReturnUrl"] = value; } + } + + protected string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); protected PackageInfo Package { get { - return _package ?? (_package = PackageID == Null.NullInteger ? new PackageInfo() : PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == PackageID, true)); + return this._package ?? (this._package = this.PackageID == Null.NullInteger ? new PackageInfo() : PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == this.PackageID, true)); } } @@ -84,231 +92,223 @@ protected IPackageEditor PackageEditor { get { - if (_control == null) + if (this._control == null) { - if (Package != null) + if (this.Package != null) { - var pkgType = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(Package.PackageType, StringComparison.OrdinalIgnoreCase)); + var pkgType = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(this.Package.PackageType, StringComparison.OrdinalIgnoreCase)); if ((pkgType != null) && (!string.IsNullOrEmpty(pkgType.EditorControlSrc))) { - _control = ControlUtilities.LoadControl(this, pkgType.EditorControlSrc); + this._control = ControlUtilities.LoadControl(this, pkgType.EditorControlSrc); } } } - return _control as IPackageEditor; + + return this._control as IPackageEditor; } } - public int PackageID + protected PropertyEditorMode ViewMode { get { - var packageID = Null.NullInteger; - if ((Request.QueryString["PackageID"] != null)) + var viewMode = PropertyEditorMode.View; + if (this.Request.IsLocal && this.IsSuperTab) { - packageID = Int32.Parse(Request.QueryString["PackageID"]); + viewMode = PropertyEditorMode.Edit; } - return packageID; + + return viewMode; } } - protected PropertyEditorMode ViewMode + protected override void OnInit(EventArgs e) { - get + base.OnInit(e); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cmdCancel.Click += this.OnCancelClick; + this.cmdDelete.Click += this.OnDeleteClick; + this.cmdPackage.Click += this.OnPackageClick; + this.cmdUpdate.Click += this.OnUpdateClick; + this.Page.PreRenderComplete += (sender, args) => + { + if (UrlUtils.InPopUp()) + { + var title = string.Format("{0} > {1}", this.Page.Title, this.Package.FriendlyName); + this.Page.Title = title; + } + }; + + this.BindData(); + + if (!this.IsPostBack) { - var viewMode = PropertyEditorMode.View; - if (Request.IsLocal && IsSuperTab) + this.ReturnUrl = this.Request.UrlReferrer != null ? this.Request.UrlReferrer.ToString() : this._navigationManager.NavigateURL(); + switch (this.DisplayMode) { - viewMode = PropertyEditorMode.Edit; + case "editor": + this.packageSettingsSection.Visible = false; + break; + case "settings": + this.extensionSection.Visible = false; + break; } - return viewMode; + } + + switch (this.DisplayMode) + { + case "editor": + this.cmdCancel.Visible = this.cmdCancel.Enabled = false; + this.cmdUpdate.Visible = this.cmdUpdate.Enabled = false; + this.cmdPackage.Visible = this.cmdPackage.Enabled = false; + this.cmdDelete.Visible = this.cmdDelete.Enabled = false; + break; + case "settings": + this.cmdCancel.Visible = this.cmdCancel.Enabled = false; + break; } } private void BindData() { - email.ValidationExpression = Globals.glbEmailRegEx; - trLanguagePackType.Visible = false; - switch (Mode) + this.email.ValidationExpression = Globals.glbEmailRegEx; + this.trLanguagePackType.Visible = false; + switch (this.Mode) { case "All": - lblHelp.Text = Localization.GetString("EditHelp", LocalResourceFile); - cmdUpdate.Text = Localization.GetString("cmdUpdate", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("EditHelp", this.LocalResourceFile); + this.cmdUpdate.Text = Localization.GetString("cmdUpdate", this.LocalResourceFile); break; case "LanguagePack": - lblHelp.Text = Localization.GetString("EditLanguageHelp", LocalResourceFile); - cmdUpdate.Text = Localization.GetString("cmdUpdateLanguage", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("EditLanguageHelp", this.LocalResourceFile); + this.cmdUpdate.Text = Localization.GetString("cmdUpdateLanguage", this.LocalResourceFile); break; case "Module": - lblHelp.Text = Localization.GetString("EditModuleHelp", LocalResourceFile); - cmdUpdate.Text = Localization.GetString("cmdUpdateModule", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("EditModuleHelp", this.LocalResourceFile); + this.cmdUpdate.Text = Localization.GetString("cmdUpdateModule", this.LocalResourceFile); break; case "Skin": - lblHelp.Text = Localization.GetString("EditSkinHelp", LocalResourceFile); - cmdUpdate.Text = Localization.GetString("cmdUpdateSkin", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("EditSkinHelp", this.LocalResourceFile); + this.cmdUpdate.Text = Localization.GetString("cmdUpdateSkin", this.LocalResourceFile); break; } - cmdPackage.Visible = IsSuperTab; - cmdUpdate.Visible = IsSuperTab; - if (Package != null) + this.cmdPackage.Visible = this.IsSuperTab; + this.cmdUpdate.Visible = this.IsSuperTab; + if (this.Package != null) { - - if (PackageEditor == null || PackageID == Null.NullInteger) + if (this.PackageEditor == null || this.PackageID == Null.NullInteger) { - extensionSection.Visible = false; + this.extensionSection.Visible = false; } else { - phEditor.Controls.Clear(); - phEditor.Controls.Add(PackageEditor as Control); - var moduleControl = PackageEditor as IModuleControl; + this.phEditor.Controls.Clear(); + this.phEditor.Controls.Add(this.PackageEditor as Control); + var moduleControl = this.PackageEditor as IModuleControl; if (moduleControl != null) { - moduleControl.ModuleContext.Configuration = ModuleContext.Configuration; + moduleControl.ModuleContext.Configuration = this.ModuleContext.Configuration; } - PackageEditor.PackageID = PackageID; - PackageEditor.Initialize(); - Package.IconFile = Util.ParsePackageIconFileName(Package); + this.PackageEditor.PackageID = this.PackageID; + this.PackageEditor.Initialize(); + + this.Package.IconFile = Util.ParsePackageIconFileName(this.Package); } - - switch (Package.PackageType) - { + + switch (this.Package.PackageType) + { case "Auth_System": case "Container": case "Module": case "Skin": - iconFile.Enabled = true; - Package.IconFile = Util.ParsePackageIconFileName(Package); + this.iconFile.Enabled = true; + this.Package.IconFile = Util.ParsePackageIconFileName(this.Package); break; default: - iconFile.Enabled = false; - Package.IconFile = "Not Available"; + this.iconFile.Enabled = false; + this.Package.IconFile = "Not Available"; break; } - - if (Mode != "All") + + if (this.Mode != "All") { - packageType.Visible = false; + this.packageType.Visible = false; } - //Determine if Package is ready for packaging - PackageWriterBase writer = PackageWriterFactory.GetWriter(Package); - cmdPackage.Visible = IsSuperTab && writer != null && Directory.Exists(Path.Combine(Globals.ApplicationMapPath, writer.BasePath)); - cmdDelete.Visible = IsSuperTab && (!Package.IsSystemPackage) && (PackageController.CanDeletePackage(Package, ModuleContext.PortalSettings)); - ctlAudit.Entity = Package; + // Determine if Package is ready for packaging + PackageWriterBase writer = PackageWriterFactory.GetWriter(this.Package); + this.cmdPackage.Visible = this.IsSuperTab && writer != null && Directory.Exists(Path.Combine(Globals.ApplicationMapPath, writer.BasePath)); - packageForm.DataSource = Package; - packageFormReadOnly.DataSource = Package; - if(!Page.IsPostBack) + this.cmdDelete.Visible = this.IsSuperTab && (!this.Package.IsSystemPackage) && PackageController.CanDeletePackage(this.Package, this.ModuleContext.PortalSettings); + this.ctlAudit.Entity = this.Package; + + this.packageForm.DataSource = this.Package; + this.packageFormReadOnly.DataSource = this.Package; + if (!this.Page.IsPostBack) { - packageForm.DataBind(); - packageFormReadOnly.DataBind(); + this.packageForm.DataBind(); + this.packageFormReadOnly.DataBind(); } - packageForm.Visible = IsSuperTab; - packageFormReadOnly.Visible = !IsSuperTab; + this.packageForm.Visible = this.IsSuperTab; + this.packageFormReadOnly.Visible = !this.IsSuperTab; } } private void UpdatePackage(bool displayMessage) { - if (packageForm.IsValid) + if (this.packageForm.IsValid) { - var package = packageForm.DataSource as PackageInfo; + var package = this.packageForm.DataSource as PackageInfo; if (package != null) { var pkgIconFile = Util.ParsePackageIconFileName(package); - package.IconFile = (pkgIconFile.Trim().Length > 0)? Util.ParsePackageIconFile(package) : null; + package.IconFile = (pkgIconFile.Trim().Length > 0) ? Util.ParsePackageIconFile(package) : null; PackageController.Instance.SaveExtensionPackage(package); } - if (displayMessage) - { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PackageUpdated", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess); - } - } - if (PackageEditor != null) - { - PackageEditor.UpdatePackage(); - } - } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cmdCancel.Click += OnCancelClick; - cmdDelete.Click += OnDeleteClick; - cmdPackage.Click += OnPackageClick; - cmdUpdate.Click += OnUpdateClick; - Page.PreRenderComplete += (sender, args) => - { - if (UrlUtils.InPopUp()) - { - var title = string.Format("{0} > {1}", Page.Title, Package.FriendlyName); - Page.Title = title; - } - }; - - BindData(); - - if (!IsPostBack) - { - ReturnUrl = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : _navigationManager.NavigateURL(); - switch (DisplayMode) + if (displayMessage) { - case "editor": - packageSettingsSection.Visible = false; - break; - case "settings": - extensionSection.Visible = false; - break; + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PackageUpdated", this.LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess); } } - switch (DisplayMode) + if (this.PackageEditor != null) { - case "editor": - cmdCancel.Visible = cmdCancel.Enabled = false; - cmdUpdate.Visible = cmdUpdate.Enabled = false; - cmdPackage.Visible = cmdPackage.Enabled = false; - cmdDelete.Visible = cmdDelete.Enabled = false; - break; - case "settings": - cmdCancel.Visible = cmdCancel.Enabled = false; - break; + this.PackageEditor.UpdatePackage(); } } protected void OnCancelClick(object sender, EventArgs e) { - Response.Redirect(ReturnUrl); + this.Response.Redirect(this.ReturnUrl); } protected void OnDeleteClick(object sender, EventArgs e) { - Response.Redirect(Util.UnInstallURL(ModuleContext.TabId, PackageID)); + this.Response.Redirect(Util.UnInstallURL(this.ModuleContext.TabId, this.PackageID)); } protected void OnPackageClick(object sender, EventArgs e) { try { - UpdatePackage(false); - Response.Redirect(Util.PackageWriterURL(ModuleContext, PackageID)); + this.UpdatePackage(false); + this.Response.Redirect(Util.PackageWriterURL(this.ModuleContext, this.PackageID)); } catch (Exception ex) { @@ -320,13 +320,12 @@ protected void OnUpdateClick(object sender, EventArgs e) { try { - UpdatePackage(true); + this.UpdatePackage(true); } catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); } } - } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Portals/portal.template.xsd b/DNN Platform/Website/DesktopModules/Admin/Portals/portal.template.xsd index cb98105b579..141b56510d1 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Portals/portal.template.xsd +++ b/DNN Platform/Website/DesktopModules/Admin/Portals/portal.template.xsd @@ -7,7 +7,6 @@ - @@ -42,8 +41,16 @@ - - + + + + + + + + + + @@ -64,18 +71,18 @@ - - - - - - - - - - - - + + + + + + + + + + + + @@ -438,7 +445,7 @@ - + @@ -576,8 +583,10 @@ - - + + + + diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/ResultsSettings.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/ResultsSettings.ascx.resx index d51cf96573d..181f0cc3216 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/ResultsSettings.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/ResultsSettings.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchResults.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchResults.ascx.resx index 4d14a6a4a23..f0671ff5b1e 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchResults.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchResults.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx b/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx index cb9935f4f9f..606556eede1 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs index 23ae31d420e..7de9f309c44 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs @@ -1,121 +1,114 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Search.Internals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.SearchResults { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Search.Internals; + public partial class ResultsSettings : ModuleSettingsBase - { - #region "Base Method Implementations" - + { public override void LoadSettings() { try { - if ((Page.IsPostBack == false)) + if (this.Page.IsPostBack == false) { - if (!String.IsNullOrEmpty(Convert.ToString(Settings["LinkTarget"]))) + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["LinkTarget"]))) { - comboBoxLinkTarget.SelectedValue = Convert.ToString(Settings["LinkTarget"]); + this.comboBoxLinkTarget.SelectedValue = Convert.ToString(this.Settings["LinkTarget"]); } - if (!string.IsNullOrEmpty(Convert.ToString(Settings["ScopeForPortals"]))) + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["ScopeForPortals"]))) { - var list = Convert.ToString(Settings["ScopeForPortals"]).Split('|').ToList(); - var portalList = LoadPortalsList().ToList(); + var list = Convert.ToString(this.Settings["ScopeForPortals"]).Split('|').ToList(); + var portalList = this.LoadPortalsList().ToList(); if (portalList.Any()) { foreach (var portal in portalList) { - var item = new ListItem(portal[0], portal[1]) {Selected = list.Contains(portal[1])}; - comboBoxPortals.Items.Add(item); + var item = new ListItem(portal[0], portal[1]) { Selected = list.Contains(portal[1]) }; + this.comboBoxPortals.Items.Add(item); } } else { - divPortalGroup.Visible = false; + this.divPortalGroup.Visible = false; } } else { - var portalList = LoadPortalsList().ToList(); + var portalList = this.LoadPortalsList().ToList(); if (portalList.Any()) { foreach (var portal in portalList) { - var item = new ListItem(portal[0], portal[1]) { Selected = PortalId.ToString() == portal[1] }; - comboBoxPortals.Items.Add(item); + var item = new ListItem(portal[0], portal[1]) { Selected = this.PortalId.ToString() == portal[1] }; + this.comboBoxPortals.Items.Add(item); } } else { - divPortalGroup.Visible = false; + this.divPortalGroup.Visible = false; } } - - - if (!string.IsNullOrEmpty(Convert.ToString(Settings["ScopeForFilters"]))) + + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["ScopeForFilters"]))) { - var list = Convert.ToString(Settings["ScopeForFilters"]).Split('|').ToList(); - var filterList = LoadSeachContentSourcesList(); + var list = Convert.ToString(this.Settings["ScopeForFilters"]).Split('|').ToList(); + var filterList = this.LoadSeachContentSourcesList(); foreach (var filter in filterList) { - var item = new ListItem(filter, filter) {Selected = list.Contains(filter)}; - comboBoxFilters.Items.Add(item); + var item = new ListItem(filter, filter) { Selected = list.Contains(filter) }; + this.comboBoxFilters.Items.Add(item); } } else { - var filterList = LoadSeachContentSourcesList(); + var filterList = this.LoadSeachContentSourcesList(); foreach (var filter in filterList) { - var item = new ListItem(filter, filter) {Selected = true}; - comboBoxFilters.Items.Add(item); + var item = new ListItem(filter, filter) { Selected = true }; + this.comboBoxFilters.Items.Add(item); } } - var scopeForRoles = - PortalController.GetPortalSetting("SearchResult_ScopeForRoles", PortalId, string.Empty) - .Split(new []{','}, StringSplitOptions.RemoveEmptyEntries); - var roles = RoleController.Instance.GetRoles(PortalId, r => !r.IsSystemRole || r.RoleName == "Registered Users"); - roles.Insert(0, new RoleInfo(){RoleName = "Superusers" }); + var scopeForRoles = + PortalController.GetPortalSetting("SearchResult_ScopeForRoles", this.PortalId, string.Empty) + .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var roles = RoleController.Instance.GetRoles(this.PortalId, r => !r.IsSystemRole || r.RoleName == "Registered Users"); + roles.Insert(0, new RoleInfo() { RoleName = "Superusers" }); foreach (var role in roles) { var item = new ListItem(role.RoleName, role.RoleName) { Selected = scopeForRoles.Length == 0 || scopeForRoles.Contains(role.RoleName) }; - comboBoxRoles.Items.Add(item); + this.comboBoxRoles.Items.Add(item); } - chkEnableWildSearch.Checked = GetBooleanSetting("EnableWildSearch", true); - chkShowDescription.Checked = GetBooleanSetting("ShowDescription", true); - chkShowFriendlyTitle.Checked = GetBooleanSetting("ShowFriendlyTitle", true); - chkShowSnippet.Checked = GetBooleanSetting("ShowSnippet", true); - chkShowLastUpdated.Checked = GetBooleanSetting("ShowLastUpdated", true); - chkShowSource.Checked = GetBooleanSetting("ShowSource", true); - chkShowTags.Checked = GetBooleanSetting("ShowTags", true); + this.chkEnableWildSearch.Checked = this.GetBooleanSetting("EnableWildSearch", true); + this.chkShowDescription.Checked = this.GetBooleanSetting("ShowDescription", true); + this.chkShowFriendlyTitle.Checked = this.GetBooleanSetting("ShowFriendlyTitle", true); + this.chkShowSnippet.Checked = this.GetBooleanSetting("ShowSnippet", true); + this.chkShowLastUpdated.Checked = this.GetBooleanSetting("ShowLastUpdated", true); + this.chkShowSource.Checked = this.GetBooleanSetting("ShowSource", true); + this.chkShowTags.Checked = this.GetBooleanSetting("ShowTags", true); - txtMaxDescriptionLength.Text = GetStringSetting("MaxDescriptionLength", "100"); + this.txtMaxDescriptionLength.Text = this.GetStringSetting("MaxDescriptionLength", "100"); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -125,35 +118,36 @@ public override void UpdateSettings() { try { - if (Page.IsValid) + if (this.Page.IsValid) { - ModuleController.Instance.UpdateModuleSetting(ModuleId, "LinkTarget", comboBoxLinkTarget.SelectedValue); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "LinkTarget", this.comboBoxLinkTarget.SelectedValue); - var selectedPortals = comboBoxPortals.Value.Replace(",", "|"); + var selectedPortals = this.comboBoxPortals.Value.Replace(",", "|"); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ScopeForPortals", selectedPortals); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ScopeForPortals", selectedPortals); - var selectedFilters = comboBoxFilters.Value.Replace(",", "|"); + var selectedFilters = this.comboBoxFilters.Value.Replace(",", "|"); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ScopeForFilters", selectedFilters.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ScopeForFilters", selectedFilters.ToString()); - var selectedRoles = comboBoxRoles.Value; - PortalController.UpdatePortalSetting(PortalId, "SearchResult_ScopeForRoles", selectedRoles); + var selectedRoles = this.comboBoxRoles.Value; + PortalController.UpdatePortalSetting(this.PortalId, "SearchResult_ScopeForRoles", selectedRoles); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "EnableWildSearch", chkEnableWildSearch.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ShowDescription", chkShowDescription.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ShowFriendlyTitle", chkShowFriendlyTitle.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ShowSnippet", chkShowSnippet.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ShowLastUpdated", chkShowLastUpdated.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ShowSource", chkShowSource.Checked.ToString()); - ModuleController.Instance.UpdateModuleSetting(ModuleId, "ShowTags", chkShowTags.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "EnableWildSearch", this.chkEnableWildSearch.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ShowDescription", this.chkShowDescription.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ShowFriendlyTitle", this.chkShowFriendlyTitle.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ShowSnippet", this.chkShowSnippet.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ShowLastUpdated", this.chkShowLastUpdated.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ShowSource", this.chkShowSource.Checked.ToString()); + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ShowTags", this.chkShowTags.Checked.ToString()); - var maxDescriptionLength = txtMaxDescriptionLength.Text; + var maxDescriptionLength = this.txtMaxDescriptionLength.Text; if (string.IsNullOrEmpty(maxDescriptionLength) || !Regex.IsMatch(maxDescriptionLength, "^\\d+$")) { maxDescriptionLength = "100"; } - ModuleController.Instance.UpdateModuleSetting(ModuleId, "MaxDescriptionLength", maxDescriptionLength); + + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "MaxDescriptionLength", maxDescriptionLength); } } catch (Exception exc) @@ -161,25 +155,23 @@ public override void UpdateSettings() Exceptions.ProcessModuleLoadException(this, exc); } - DataCache.RemoveCache(string.Format("ModuleInfos{0}", PortalSettings.PortalId)); - } - - #endregion - + DataCache.RemoveCache(string.Format("ModuleInfos{0}", this.PortalSettings.PortalId)); + } + protected IEnumerable LoadPortalsList() { var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); var mygroup = (from @group in groups select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); var result = new List(); if (mygroup != null && mygroup.Any()) { result.AddRange(mygroup.Select( - pi => new[] {pi.PortalName, pi.PortalID.ToString(CultureInfo.InvariantCulture)})); + pi => new[] { pi.PortalName, pi.PortalID.ToString(CultureInfo.InvariantCulture) })); } return result; @@ -206,14 +198,15 @@ protected IEnumerable LoadSeachContentSourcesList() } } } + return result; } private bool GetBooleanSetting(string settingName, bool defaultValue) { - if (!string.IsNullOrEmpty(Convert.ToString(Settings[settingName]))) + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings[settingName]))) { - return Convert.ToBoolean(Settings[settingName]); + return Convert.ToBoolean(this.Settings[settingName]); } return defaultValue; @@ -221,9 +214,9 @@ private bool GetBooleanSetting(string settingName, bool defaultValue) private string GetStringSetting(string settingName, string defaultValue) { - if (!string.IsNullOrEmpty(Convert.ToString(Settings[settingName]))) + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings[settingName]))) { - return Convert.ToString(Settings[settingName]); + return Convert.ToString(this.Settings[settingName]); } return defaultValue; diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs index c3b31f26319..b85dc05f0c0 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs @@ -1,77 +1,75 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using System.Web.UI.WebControls; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Search.Internals; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.SearchResults { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Web; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Search.Internals; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + public partial class SearchResults : PortalModuleBase { private const int DefaultPageIndex = 1; private const int DefaultPageSize = 15; private const int DefaultSortOption = 0; + private const string MyFileName = "SearchResults.ascx"; + private IList _searchContentSources; private IList _searchPortalIds; protected string SearchTerm { - get { return Request.QueryString["Search"] ?? string.Empty; } + get { return this.Request.QueryString["Search"] ?? string.Empty; } } protected string TagsQuery { - get { return Request.QueryString["Tag"] ?? string.Empty; } + get { return this.Request.QueryString["Tag"] ?? string.Empty; } } protected string SearchScopeParam { - get { return Request.QueryString["Scope"] ?? string.Empty; } + get { return this.Request.QueryString["Scope"] ?? string.Empty; } } - protected string [] SearchScope + protected string[] SearchScope { get { - var searchScopeParam = SearchScopeParam; + var searchScopeParam = this.SearchScopeParam; return string.IsNullOrEmpty(searchScopeParam) ? new string[0] : searchScopeParam.Split(','); } } protected string LastModifiedParam { - get { return Request.QueryString["LastModified"] ?? string.Empty; } + get { return this.Request.QueryString["LastModified"] ?? string.Empty; } } protected int PageIndex { get { - if (string.IsNullOrEmpty(Request.QueryString["Page"])) + if (string.IsNullOrEmpty(this.Request.QueryString["Page"])) { return DefaultPageIndex; } int pageIndex; - if (Int32.TryParse(Request.QueryString["Page"], out pageIndex)) + if (int.TryParse(this.Request.QueryString["Page"], out pageIndex)) { return pageIndex; } @@ -84,13 +82,13 @@ protected int PageSize { get { - if (string.IsNullOrEmpty(Request.QueryString["Size"])) + if (string.IsNullOrEmpty(this.Request.QueryString["Size"])) { return DefaultPageSize; } int pageSize; - if (Int32.TryParse(Request.QueryString["Size"], out pageSize)) + if (int.TryParse(this.Request.QueryString["Size"], out pageSize)) { return pageSize; } @@ -103,13 +101,13 @@ protected int SortOption { get { - if (string.IsNullOrEmpty(Request.QueryString["Sort"])) + if (string.IsNullOrEmpty(this.Request.QueryString["Sort"])) { return DefaultSortOption; } int sortOption; - if (Int32.TryParse(Request.QueryString["Sort"], out sortOption)) + if (int.TryParse(this.Request.QueryString["Sort"], out sortOption)) { return sortOption; } @@ -122,13 +120,14 @@ protected string CheckedExactSearch { get { - var paramExactSearch = Request.QueryString["ExactSearch"]; + var paramExactSearch = this.Request.QueryString["ExactSearch"]; if (!string.IsNullOrEmpty(paramExactSearch) && paramExactSearch.ToLowerInvariant() == "y") { return "checked=\"true\""; } - return ""; + + return string.Empty; } } @@ -136,52 +135,30 @@ protected string LinkTarget { get { - string settings = Convert.ToString(Settings["LinkTarget"]); + string settings = Convert.ToString(this.Settings["LinkTarget"]); return string.IsNullOrEmpty(settings) || settings == "0" ? string.Empty : " target=\"_blank\" "; } } - protected string ShowDescription => GetBooleanSetting("ShowDescription", true).ToString().ToLowerInvariant(); + protected string ShowDescription => this.GetBooleanSetting("ShowDescription", true).ToString().ToLowerInvariant(); - protected string ShowSnippet => GetBooleanSetting("ShowSnippet", true).ToString().ToLowerInvariant(); + protected string ShowSnippet => this.GetBooleanSetting("ShowSnippet", true).ToString().ToLowerInvariant(); - protected string ShowSource => GetBooleanSetting("ShowSource", true).ToString().ToLowerInvariant(); + protected string ShowSource => this.GetBooleanSetting("ShowSource", true).ToString().ToLowerInvariant(); - protected string ShowLastUpdated => GetBooleanSetting("ShowLastUpdated", true).ToString().ToLowerInvariant(); + protected string ShowLastUpdated => this.GetBooleanSetting("ShowLastUpdated", true).ToString().ToLowerInvariant(); - protected string ShowTags => GetBooleanSetting("ShowTags", true).ToString().ToLowerInvariant(); + protected string ShowTags => this.GetBooleanSetting("ShowTags", true).ToString().ToLowerInvariant(); - protected string MaxDescriptionLength => GetIntegerSetting("MaxDescriptionLength", 100).ToString(); - - private IList SearchPortalIds - { - get - { - if (_searchPortalIds == null) - { - _searchPortalIds = new List(); - if (!string.IsNullOrEmpty(Convert.ToString(Settings["ScopeForPortals"]))) - { - List list = Convert.ToString(Settings["ScopeForPortals"]).Split('|').ToList(); - foreach (string l in list) _searchPortalIds.Add(Convert.ToInt32(l)); - } - else - { - _searchPortalIds.Add(PortalId); // no setting, just search current portal by default - } - } - - return _searchPortalIds; - } - } + protected string MaxDescriptionLength => this.GetIntegerSetting("MaxDescriptionLength", 100).ToString(); protected IList SearchContentSources { get { - if (_searchContentSources == null) + if (this._searchContentSources == null) { - IList portalIds = SearchPortalIds; + IList portalIds = this.SearchPortalIds; var list = new List(); foreach (int portalId in portalIds) { @@ -189,7 +166,11 @@ protected IList SearchContentSources InternalSearchController.Instance.GetSearchContentSourceList(portalId); foreach (SearchContentSource src in crawlerList) { - if (src.IsPrivate) continue; + if (src.IsPrivate) + { + continue; + } + if (list.All(r => r.LocalizedName != src.LocalizedName)) { list.Add(src); @@ -199,12 +180,12 @@ protected IList SearchContentSources List configuredList = null; - if (!string.IsNullOrEmpty(Convert.ToString(Settings["ScopeForFilters"]))) + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["ScopeForFilters"]))) { - configuredList = Convert.ToString(Settings["ScopeForFilters"]).Split('|').ToList(); + configuredList = Convert.ToString(this.Settings["ScopeForFilters"]).Split('|').ToList(); } - _searchContentSources = new List(); + this._searchContentSources = new List(); // add other searchable module defs foreach (SearchContentSource contentSource in list) @@ -212,27 +193,48 @@ protected IList SearchContentSources if (configuredList == null || configuredList.Any(l => l.Equals(contentSource.LocalizedName))) { - if (!_searchContentSources.Equals(contentSource.LocalizedName)) + if (!this._searchContentSources.Equals(contentSource.LocalizedName)) { - _searchContentSources.Add(contentSource.LocalizedName); + this._searchContentSources.Add(contentSource.LocalizedName); } } } } - return _searchContentSources; + return this._searchContentSources; } } - #region localized string - - private const string MyFileName = "SearchResults.ascx"; - protected string DefaultText { get { return Localization.GetSafeJSString("DefaultText", Localization.GetResourceFile(this, MyFileName)); } } + private IList SearchPortalIds + { + get + { + if (this._searchPortalIds == null) + { + this._searchPortalIds = new List(); + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["ScopeForPortals"]))) + { + List list = Convert.ToString(this.Settings["ScopeForPortals"]).Split('|').ToList(); + foreach (string l in list) + { + this._searchPortalIds.Add(Convert.ToInt32(l)); + } + } + else + { + this._searchPortalIds.Add(this.PortalId); // no setting, just search current portal by default + } + } + + return this._searchPortalIds; + } + } + protected string NoResultsText { get { return Localization.GetSafeJSString("NoResults", Localization.GetResourceFile(this, MyFileName)); } @@ -273,7 +275,6 @@ protected string CommentsText get { return Localization.GetSafeJSString("Comments", Localization.GetResourceFile(this, MyFileName)); } } - protected string RelevanceText { get { return Localization.GetSafeJSString("Relevance", Localization.GetResourceFile(this, MyFileName)); } @@ -334,51 +335,50 @@ protected string CurrentPageIndexText protected string CultureCode { get; set; } - #endregion - protected override void OnLoad(EventArgs e) { base.OnLoad(e); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.searchBox.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnn.searchBox.css", FileOrder.Css.ModuleCss); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/admin/SearchResults/dnn.searchResult.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.searchBox.js"); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnn.searchBox.css", FileOrder.Css.ModuleCss); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/admin/SearchResults/dnn.searchResult.js"); - CultureCode = Thread.CurrentThread.CurrentCulture.ToString(); + this.CultureCode = Thread.CurrentThread.CurrentCulture.ToString(); - foreach (string o in SearchContentSources) + foreach (string o in this.SearchContentSources) { - var item = new ListItem(o, o) {Selected = CheckedScopeItem(o)}; - SearchScopeList.Items.Add(item); + var item = new ListItem(o, o) { Selected = this.CheckedScopeItem(o) }; + this.SearchScopeList.Items.Add(item); } - SearchScopeList.Options.Localization["AllItemsChecked"] = Localization.GetString("AllFeaturesSelected", + this.SearchScopeList.Options.Localization["AllItemsChecked"] = Localization.GetString( + "AllFeaturesSelected", Localization.GetResourceFile(this, MyFileName)); - var pageSizeItem = ResultsPerPageList.FindItemByValue(PageSize.ToString()); + var pageSizeItem = this.ResultsPerPageList.FindItemByValue(this.PageSize.ToString()); if (pageSizeItem != null) { pageSizeItem.Selected = true; } - SetLastModifiedFilter(); + this.SetLastModifiedFilter(); } private bool CheckedScopeItem(string scopeItemName) { - var searchScope = SearchScope; + var searchScope = this.SearchScope; return searchScope.Length == 0 || searchScope.Any(x => x == scopeItemName); } private void SetLastModifiedFilter() { - var lastModifiedParam = LastModifiedParam; + var lastModifiedParam = this.LastModifiedParam; if (!string.IsNullOrEmpty(lastModifiedParam)) { - var item = AdvnacedDatesList.Items.Cast().FirstOrDefault(x => x.Value == lastModifiedParam); + var item = this.AdvnacedDatesList.Items.Cast().FirstOrDefault(x => x.Value == lastModifiedParam); if (item != null) { item.Selected = true; @@ -388,9 +388,9 @@ private void SetLastModifiedFilter() private bool GetBooleanSetting(string settingName, bool defaultValue) { - if (Settings.ContainsKey(settingName) && !string.IsNullOrEmpty(Convert.ToString(Settings[settingName]))) + if (this.Settings.ContainsKey(settingName) && !string.IsNullOrEmpty(Convert.ToString(this.Settings[settingName]))) { - return Convert.ToBoolean(Settings[settingName]); + return Convert.ToBoolean(this.Settings[settingName]); } return defaultValue; @@ -398,7 +398,7 @@ private bool GetBooleanSetting(string settingName, bool defaultValue) private int GetIntegerSetting(string settingName, int defaultValue) { - var settingValue = Convert.ToString(Settings[settingName]); + var settingValue = Convert.ToString(this.Settings[settingName]); if (!string.IsNullOrEmpty(settingValue) && Regex.IsMatch(settingValue, "^\\d+$")) { return Convert.ToInt32(settingValue); diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/DataConsent.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/DataConsent.ascx.resx index b9b945bc648..2d572f21bb0 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/DataConsent.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/DataConsent.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditGroups.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditGroups.ascx.resx index ec90a0da163..17f401042bd 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditGroups.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditGroups.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditProfileDefinition.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditProfileDefinition.ascx.resx index f83add5a88c..3c4c3591feb 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditProfileDefinition.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditProfileDefinition.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditRoles.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditRoles.ascx.resx index 0485cbfa9d9..eb76421e35a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditRoles.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditRoles.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditUser.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditUser.ascx.resx index a95ee712e96..e759e838e6d 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditUser.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/EditUser.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ManageUsers.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ManageUsers.ascx.resx index f02fb40cbcb..797561d1739 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ManageUsers.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ManageUsers.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/MemberServices.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/MemberServices.ascx.resx index cb5ce7503b0..f286b2d8faf 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/MemberServices.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/MemberServices.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Membership.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Membership.ascx.resx index 94310dd9e71..690da78ac37 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Membership.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Membership.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Password.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Password.ascx.resx index 2c70ef4363b..a4d41ac1eae 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Password.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Password.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx.resx index 9f9be7a8adc..7492377957c 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ProfileDefinitions.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ProfileDefinitions.ascx.resx index d92799f9a56..ec83007e354 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ProfileDefinitions.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/ProfileDefinitions.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Register.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Register.ascx.resx index 97727c4bd50..ca3c827a767 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Register.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Register.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Roles.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Roles.ascx.resx index 95036149c74..4fc0a8c47aa 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Roles.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Roles.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SecurityRoles.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SecurityRoles.ascx.resx index 0ce36f00fbe..7a973334fe5 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SecurityRoles.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SecurityRoles.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SharedResources.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SharedResources.resx index df7770f164c..3bac85768be 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SharedResources.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/SharedResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/User.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/User.ascx.resx index 4407d1c5602..9e8d004c921 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/User.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/User.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/UserSettings.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/UserSettings.ascx.resx index 31fe851204c..a03114a689e 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/UserSettings.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/UserSettings.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Users.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Users.ascx.resx index cbe45529861..e955143a9d8 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Users.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/Security/App_LocalResources/Users.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs index 8452cc0d39b..0f973ea6d68 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs @@ -1,148 +1,142 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Services.Log.EventLog; -using System; -using System.Web.UI; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Services.Log.EventLog; + public partial class DataConsent : UserModuleBase { + public delegate void DataConsentEventHandler(object sender, DataConsentEventArgs e); + + public event DataConsentEventHandler DataConsentCompleted; + + public enum DataConsentStatus + { + Consented, + Cancelled, + RemovedAccount, + FailedToRemoveAccount, + } + public string DeleteMeConfirmString { get { - switch (PortalSettings.DataConsentUserDeleteAction) + switch (this.PortalSettings.DataConsentUserDeleteAction) { case PortalSettings.UserDeleteAction.Manual: - return LocalizeString("ManualDelete.Confirm"); + return this.LocalizeString("ManualDelete.Confirm"); case PortalSettings.UserDeleteAction.DelayedHardDelete: - return LocalizeString("DelayedHardDelete.Confirm"); + return this.LocalizeString("DelayedHardDelete.Confirm"); case PortalSettings.UserDeleteAction.HardDelete: - return LocalizeString("HardDelete.Confirm"); + return this.LocalizeString("HardDelete.Confirm"); } - return ""; + + return string.Empty; } - } - - #region Delegate and event - - public delegate void DataConsentEventHandler(object sender, DataConsentEventArgs e); - public event DataConsentEventHandler DataConsentCompleted; + } + public void OnDataConsentComplete(DataConsentEventArgs e) { - DataConsentCompleted?.Invoke(this, e); - } - - #endregion - + this.DataConsentCompleted?.Invoke(this, e); + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdCancel.Click += cmdCancel_Click; - cmdSubmit.Click += cmdSubmit_Click; - cmdDeleteMe.Click += cmdDeleteMe_Click; - cmdDeleteMe.Visible = PortalSettings.DataConsentUserDeleteAction != PortalSettings.UserDeleteAction.Off; - if (!Page.IsPostBack) + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdSubmit.Click += this.cmdSubmit_Click; + this.cmdDeleteMe.Click += this.cmdDeleteMe_Click; + this.cmdDeleteMe.Visible = this.PortalSettings.DataConsentUserDeleteAction != PortalSettings.UserDeleteAction.Off; + if (!this.Page.IsPostBack) { - chkAgree.Checked = false; - cmdSubmit.Enabled = false; - pnlNoAgreement.Visible = false; + this.chkAgree.Checked = false; + this.cmdSubmit.Enabled = false; + this.pnlNoAgreement.Visible = false; } - chkAgree.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled = !this.checked;", cmdSubmit.ClientID)); - cmdDeleteMe.Attributes.Add("onclick", string.Format("if (!confirm('{0}')) this.preventDefault();", DeleteMeConfirmString)); + + this.chkAgree.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled = !this.checked;", this.cmdSubmit.ClientID)); + this.cmdDeleteMe.Attributes.Add("onclick", string.Format("if (!confirm('{0}')) this.preventDefault();", this.DeleteMeConfirmString)); } + private void cmdCancel_Click(object sender, EventArgs e) { - OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.Cancelled)); + this.OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.Cancelled)); } private void cmdSubmit_Click(object sender, EventArgs e) { - if (chkAgree.Checked) + if (this.chkAgree.Checked) { - UserController.UserAgreedToTerms(User); - User.HasAgreedToTerms = true; - OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.Consented)); + UserController.UserAgreedToTerms(this.User); + this.User.HasAgreedToTerms = true; + this.OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.Consented)); } } private void cmdDeleteMe_Click(object sender, EventArgs e) { var success = false; - switch (PortalSettings.DataConsentUserDeleteAction) + switch (this.PortalSettings.DataConsentUserDeleteAction) { case PortalSettings.UserDeleteAction.Manual: - User.Membership.Approved = false; - UserController.UpdateUser(PortalSettings.PortalId, User); - UserController.UserRequestsRemoval(User, true); + this.User.Membership.Approved = false; + UserController.UpdateUser(this.PortalSettings.PortalId, this.User); + UserController.UserRequestsRemoval(this.User, true); success = true; break; case PortalSettings.UserDeleteAction.DelayedHardDelete: - var user = User; + var user = this.User; success = UserController.DeleteUser(ref user, true, false); - UserController.UserRequestsRemoval(User, true); + UserController.UserRequestsRemoval(this.User, true); break; case PortalSettings.UserDeleteAction.HardDelete: - success = UserController.RemoveUser(User); + success = UserController.RemoveUser(this.User); break; } + if (success) { PortalSecurity.Instance.SignOut(); - OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.RemovedAccount)); + this.OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.RemovedAccount)); } else { - OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.FailedToRemoveAccount)); + this.OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.FailedToRemoveAccount)); } - } - - #region DataConsentEventArgs - + } + /// ----------------------------------------------------------------------------- /// /// The DataConsentEventArgs class provides a customised EventArgs class for - /// the DataConsent Event + /// the DataConsent Event. /// public class DataConsentEventArgs - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new DataConsentEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new DataConsentEventArgs. /// - /// The Data Consent Status + /// The Data Consent Status. public DataConsentEventArgs(DataConsentStatus status) { - Status = status; + this.Status = status; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Update Status + /// Gets or sets and sets the Update Status. /// public DataConsentStatus Status { get; set; } } - - public enum DataConsentStatus - { - Consented, - Cancelled, - RemovedAccount, - FailedToRemoveAccount - } - - #endregion - } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs index 608dce5f6d6..fb9f9f69f58 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs @@ -1,40 +1,37 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Modules.Admin.Security; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mail; -using DotNetNuke.UI.Skins.Controls; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using Microsoft.Extensions.DependencyInjection; -using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Modules.Admin.Security; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mail; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + + using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; + /// ----------------------------------------------------------------------------- /// - /// The ManageUsers UserModuleBase is used to manage Users + /// The ManageUsers UserModuleBase is used to manage Users. /// /// /// @@ -45,42 +42,65 @@ public partial class EditUser : UserModuleBase public EditUser() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); } - #region Protected Members + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the current Page No. + /// + public int PageNo + { + get + { + int _PageNo = 0; + if (this.ViewState["PageNo"] != null && !this.IsPostBack) + { + _PageNo = Convert.ToInt32(this.ViewState["PageNo"]); + } + + return _PageNo; + } + + set + { + this.ViewState["PageNo"] = value; + } + } + + public bool ShowVanityUrl { get; private set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether to display the Manage Services tab + /// Gets a value indicating whether gets whether to display the Manage Services tab. /// protected bool DisplayServices { get { - object setting = GetSetting(PortalId, "Profile_ManageServices"); - return Convert.ToBoolean(setting) && !(IsEdit || User.IsSuperUser); + object setting = GetSetting(this.PortalId, "Profile_ManageServices"); + return Convert.ToBoolean(setting) && !(this.IsEdit || this.User.IsSuperUser); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Redirect URL (after successful registration) + /// Gets the Redirect URL (after successful registration). /// protected string RedirectURL { get { - string _RedirectURL = ""; + string _RedirectURL = string.Empty; - if (PortalSettings.Registration.RedirectAfterRegistration == Null.NullInteger) + if (this.PortalSettings.Registration.RedirectAfterRegistration == Null.NullInteger) { - if (Request.QueryString["returnurl"] != null) + if (this.Request.QueryString["returnurl"] != null) { - //return to the url passed to register - _RedirectURL = HttpUtility.UrlDecode(Request.QueryString["returnurl"]); + // return to the url passed to register + _RedirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); - //clean the return url to avoid possible XSS attack. + // clean the return url to avoid possible XSS attack. _RedirectURL = UrlUtils.ValidReturnUrl(_RedirectURL); if (_RedirectURL.Contains("?returnurl")) @@ -91,357 +111,326 @@ protected string RedirectURL _RedirectURL = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); } } - if (String.IsNullOrEmpty(_RedirectURL)) + + if (string.IsNullOrEmpty(_RedirectURL)) { - //redirect to current page - _RedirectURL = _navigationManager.NavigateURL(); + // redirect to current page + _RedirectURL = this._navigationManager.NavigateURL(); } } - else //redirect to after registration page + else // redirect to after registration page { - _RedirectURL = _navigationManager.NavigateURL(PortalSettings.Registration.RedirectAfterRegistration); + _RedirectURL = this._navigationManager.NavigateURL(this.PortalSettings.Registration.RedirectAfterRegistration); } + return _RedirectURL; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Return Url for the page + /// Gets the Return Url for the page. /// protected string ReturnUrl { get { - return _navigationManager.NavigateURL(TabId, "", !String.IsNullOrEmpty(UserFilter) ? UserFilter : ""); + return this._navigationManager.NavigateURL(this.TabId, string.Empty, !string.IsNullOrEmpty(this.UserFilter) ? this.UserFilter : string.Empty); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Filter to use + /// Gets and sets the Filter to use. /// protected string UserFilter { get { - string filterString = !string.IsNullOrEmpty(Request["filter"]) ? "filter=" + Request["filter"] : ""; - string filterProperty = !string.IsNullOrEmpty(Request["filterproperty"]) ? "filterproperty=" + Request["filterproperty"] : ""; - string page = !string.IsNullOrEmpty(Request["currentpage"]) ? "currentpage=" + Request["currentpage"] : ""; + string filterString = !string.IsNullOrEmpty(this.Request["filter"]) ? "filter=" + this.Request["filter"] : string.Empty; + string filterProperty = !string.IsNullOrEmpty(this.Request["filterproperty"]) ? "filterproperty=" + this.Request["filterproperty"] : string.Empty; + string page = !string.IsNullOrEmpty(this.Request["currentpage"]) ? "currentpage=" + this.Request["currentpage"] : string.Empty; if (!string.IsNullOrEmpty(filterString)) { filterString += "&"; } + if (!string.IsNullOrEmpty(filterProperty)) { filterString += filterProperty + "&"; } + if (!string.IsNullOrEmpty(page)) { filterString += page; } + return filterString; } } - #endregion + /// ----------------------------------------------------------------------------- + /// + /// Page_Init runs when the control is initialised. + /// + /// + /// + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdUpdate.Click += this.cmdUpdate_Click; + + this.ctlServices.SubscriptionUpdated += this.SubscriptionUpdated; + this.ctlProfile.ProfileUpdateCompleted += this.ProfileUpdateCompleted; + this.ctlPassword.PasswordUpdated += this.PasswordUpdated; + this.ctlPassword.PasswordQuestionAnswerUpdated += this.PasswordQuestionAnswerUpdated; + + this.email.ValidationExpression = this.PortalSettings.Registration.EmailValidator; + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.Knockout); + + // Set the Membership Control Properties + this.ctlMembership.ID = "Membership"; + this.ctlMembership.ModuleConfiguration = this.ModuleConfiguration; + this.ctlMembership.UserId = this.UserId; + + // Set the Password Control Properties + this.ctlPassword.ID = "Password"; + this.ctlPassword.ModuleConfiguration = this.ModuleConfiguration; + this.ctlPassword.UserId = this.UserId; - #region Public Properties + // Set the Profile Control Properties + this.ctlProfile.ID = "Profile"; + this.ctlProfile.ModuleConfiguration = this.ModuleConfiguration; + this.ctlProfile.UserId = this.UserId; + + // Set the Services Control Properties + this.ctlServices.ID = "MemberServices"; + this.ctlServices.ModuleConfiguration = this.ModuleConfiguration; + this.ctlServices.UserId = this.UserId; + + // Define DisplayName filed Enabled Property: + object setting = GetSetting(this.UserPortalID, "Security_DisplayNameFormat"); + if ((setting != null) && (!string.IsNullOrEmpty(Convert.ToString(setting)))) + { + this.displayName.Enabled = false; + } + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the current Page No + /// Page_Load runs when the control is loaded. /// - public int PageNo + /// + /// + protected override void OnLoad(EventArgs e) { - get + base.OnLoad(e); + + try { - int _PageNo = 0; - if (ViewState["PageNo"] != null && !IsPostBack) - { - _PageNo = Convert.ToInt32(ViewState["PageNo"]); - } - return _PageNo; + // Bind the User information to the controls + this.BindData(); } - set + catch (Exception exc) // Module failed to load { - ViewState["PageNo"] = value; + Exceptions.ProcessModuleLoadException(this, exc); } } - public bool ShowVanityUrl { get; private set; } - - #endregion - - #region Private Methods - private void BindData() { - if (User != null) + if (this.User != null) { - //If trying to add a SuperUser - check that user is a SuperUser - if (VerifyUserPermissions() == false) + // If trying to add a SuperUser - check that user is a SuperUser + if (this.VerifyUserPermissions() == false) { return; } - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - if ((Request.QueryString["pageno"] != null)) + if (this.Request.QueryString["pageno"] != null) { - PageNo = int.Parse(Request.QueryString["pageno"]); + this.PageNo = int.Parse(this.Request.QueryString["pageno"]); } else { - PageNo = 0; + this.PageNo = 0; } } - userForm.DataSource = User; + this.userForm.DataSource = this.User; // hide username field in UseEmailAsUserName mode - bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false); + bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false); if (disableUsername) { - userForm.Items[0].Visible = false; + this.userForm.Items[0].Visible = false; } - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - userForm.DataBind(); + this.userForm.DataBind(); } - ctlPassword.User = User; - ctlPassword.DataBind(); + this.ctlPassword.User = this.User; + this.ctlPassword.DataBind(); - if ((!DisplayServices)) + if (!this.DisplayServices) { - servicesTab.Visible = false; + this.servicesTab.Visible = false; } else { - ctlServices.User = User; - ctlServices.DataBind(); + this.ctlServices.User = this.User; + this.ctlServices.DataBind(); } - BindUser(); - ctlProfile.User = User; - ctlProfile.DataBind(); + this.BindUser(); + this.ctlProfile.User = this.User; + this.ctlProfile.DataBind(); - dnnServicesDetails.Visible = DisplayServices; + this.dnnServicesDetails.Visible = this.DisplayServices; - var urlSettings = new DotNetNuke.Entities.Urls.FriendlyUrlSettings(PortalSettings.PortalId); - var showVanityUrl = (Config.GetFriendlyUrlProvider() == "advanced") && !User.IsSuperUser; + var urlSettings = new DotNetNuke.Entities.Urls.FriendlyUrlSettings(this.PortalSettings.PortalId); + var showVanityUrl = (Config.GetFriendlyUrlProvider() == "advanced") && !this.User.IsSuperUser; if (showVanityUrl) { - VanityUrlRow.Visible = true; - if (String.IsNullOrEmpty(User.VanityUrl)) + this.VanityUrlRow.Visible = true; + if (string.IsNullOrEmpty(this.User.VanityUrl)) { - //Clean Display Name + // Clean Display Name bool modified; var options = UrlRewriterUtils.GetOptionsFromSettings(urlSettings); - var cleanUrl = FriendlyUrlController.CleanNameForUrl(User.DisplayName, options, out modified); - var uniqueUrl = FriendlyUrlController.ValidateUrl(cleanUrl, -1, PortalSettings, out modified).ToLowerInvariant(); + var cleanUrl = FriendlyUrlController.CleanNameForUrl(this.User.DisplayName, options, out modified); + var uniqueUrl = FriendlyUrlController.ValidateUrl(cleanUrl, -1, this.PortalSettings, out modified).ToLowerInvariant(); - VanityUrlAlias.Text = String.Format("{0}/{1}/", PortalSettings.PortalAlias.HTTPAlias, urlSettings.VanityUrlPrefix); - VanityUrlTextBox.Text = uniqueUrl; - ShowVanityUrl = true; + this.VanityUrlAlias.Text = string.Format("{0}/{1}/", this.PortalSettings.PortalAlias.HTTPAlias, urlSettings.VanityUrlPrefix); + this.VanityUrlTextBox.Text = uniqueUrl; + this.ShowVanityUrl = true; } else { - VanityUrl.Text = String.Format("{0}/{1}/{2}", PortalSettings.PortalAlias.HTTPAlias, urlSettings.VanityUrlPrefix, User.VanityUrl); - ShowVanityUrl = false; + this.VanityUrl.Text = string.Format("{0}/{1}/{2}", this.PortalSettings.PortalAlias.HTTPAlias, urlSettings.VanityUrlPrefix, this.User.VanityUrl); + this.ShowVanityUrl = false; } } } else { - AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); } } private bool VerifyUserPermissions() { - if (IsHostMenu && !UserInfo.IsSuperUser) + if (this.IsHostMenu && !this.UserInfo.IsSuperUser) { - AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } - //Check if User is a member of the Current Portal (or a member of the MasterPortal if PortalGroups enabled) - if (User.PortalID != Null.NullInteger && User.PortalID != PortalId) + // Check if User is a member of the Current Portal (or a member of the MasterPortal if PortalGroups enabled) + if (this.User.PortalID != Null.NullInteger && this.User.PortalID != this.PortalId) { - AddModuleMessage("InvalidUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("InvalidUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } - //Check if User is a SuperUser and that the current User is a SuperUser - if (User.IsSuperUser && !UserInfo.IsSuperUser) + // Check if User is a SuperUser and that the current User is a SuperUser + if (this.User.IsSuperUser && !this.UserInfo.IsSuperUser) { - AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } - if (IsEdit) + + if (this.IsEdit) { - //Check if user has admin rights - if (!IsAdmin || (User.IsInRole(PortalSettings.AdministratorRoleName) && !PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))) + // Check if user has admin rights + if (!this.IsAdmin || (this.User.IsInRole(this.PortalSettings.AdministratorRoleName) && !PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName))) { - AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } } else { - if (!IsUser) + if (!this.IsUser) { - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { - if (!PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)) + if (!PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName)) { - //Display current user's profile - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.UserTabId, "", "UserID=" + UserInfo.UserID), true); + // Display current user's profile + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.UserTabId, string.Empty, "UserID=" + this.UserInfo.UserID), true); } } else { - if ((User.UserID > Null.NullInteger)) + if (this.User.UserID > Null.NullInteger) { - AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } } } } + return true; } private void BindMembership() { - ctlMembership.User = User; - ctlMembership.DataBind(); - AddModuleMessage("UserLockedOut", ModuleMessage.ModuleMessageType.YellowWarning, ctlMembership.UserMembership.LockedOut && (!Page.IsPostBack)); + this.ctlMembership.User = this.User; + this.ctlMembership.DataBind(); + this.AddModuleMessage("UserLockedOut", ModuleMessage.ModuleMessageType.YellowWarning, this.ctlMembership.UserMembership.LockedOut && (!this.Page.IsPostBack)); } private void BindUser() { - BindMembership(); - + this.BindMembership(); } private void DisableForm() { - adminTabNav.Visible = false; - dnnProfileDetails.Visible = false; - dnnServicesDetails.Visible = false; - actionsRow.Visible = false; - ctlMembership.Visible = false; + this.adminTabNav.Visible = false; + this.dnnProfileDetails.Visible = false; + this.dnnServicesDetails.Visible = false; + this.actionsRow.Visible = false; + this.ctlMembership.Visible = false; } private void UpdateDisplayName() { - //Update DisplayName to conform to Format - if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) - { - User.UpdateDisplayName(PortalSettings.Registration.DisplayNameFormat); - } - } - - - #endregion - - #region Event Handlers - - /// ----------------------------------------------------------------------------- - /// - /// Page_Init runs when the control is initialised - /// - /// - /// - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - cmdDelete.Click += cmdDelete_Click; - cmdUpdate.Click += cmdUpdate_Click; - - ctlServices.SubscriptionUpdated += SubscriptionUpdated; - ctlProfile.ProfileUpdateCompleted += ProfileUpdateCompleted; - ctlPassword.PasswordUpdated += PasswordUpdated; - ctlPassword.PasswordQuestionAnswerUpdated += PasswordQuestionAnswerUpdated; - - email.ValidationExpression = PortalSettings.Registration.EmailValidator; - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - JavaScript.RequestRegistration(CommonJs.Knockout); - - - //Set the Membership Control Properties - ctlMembership.ID = "Membership"; - ctlMembership.ModuleConfiguration = ModuleConfiguration; - ctlMembership.UserId = UserId; - - //Set the Password Control Properties - ctlPassword.ID = "Password"; - ctlPassword.ModuleConfiguration = ModuleConfiguration; - ctlPassword.UserId = UserId; - - //Set the Profile Control Properties - ctlProfile.ID = "Profile"; - ctlProfile.ModuleConfiguration = ModuleConfiguration; - ctlProfile.UserId = UserId; - - //Set the Services Control Properties - ctlServices.ID = "MemberServices"; - ctlServices.ModuleConfiguration = ModuleConfiguration; - ctlServices.UserId = UserId; - - //Define DisplayName filed Enabled Property: - object setting = GetSetting(UserPortalID, "Security_DisplayNameFormat"); - if ((setting != null) && (!string.IsNullOrEmpty(Convert.ToString(setting)))) - { - displayName.Enabled = false; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - try - { - //Bind the User information to the controls - BindData(); - } - catch (Exception exc) //Module failed to load + // Update DisplayName to conform to Format + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) { - Exceptions.ProcessModuleLoadException(this, exc); + this.User.UpdateDisplayName(this.PortalSettings.Registration.DisplayNameFormat); } } protected void cmdDelete_Click(object sender, EventArgs e) { - UserInfo user = User; + UserInfo user = this.User; var success = false; - if (PortalSettings.DataConsentActive && user.UserID == UserInfo.UserID) + if (this.PortalSettings.DataConsentActive && user.UserID == this.UserInfo.UserID) { - switch (PortalSettings.DataConsentUserDeleteAction) + switch (this.PortalSettings.DataConsentUserDeleteAction) { case PortalSettings.UserDeleteAction.Manual: user.Membership.Approved = false; - UserController.UpdateUser(PortalSettings.PortalId, user); + UserController.UpdateUser(this.PortalSettings.PortalId, user); UserController.UserRequestsRemoval(user, true); success = true; break; @@ -461,73 +450,74 @@ protected void cmdDelete_Click(object sender, EventArgs e) { success = UserController.DeleteUser(ref user, true, false); } + if (!success) { - AddModuleMessage("UserDeleteError", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("UserDeleteError", ModuleMessage.ModuleMessageType.RedError, true); } - //DNN-26777 + // DNN-26777 PortalSecurity.Instance.SignOut(); - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.HomeTabId)); + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId)); } protected void cmdUpdate_Click(object sender, EventArgs e) { - if (userForm.IsValid && (User != null)) + if (this.userForm.IsValid && (this.User != null)) { - if (User.UserID == PortalSettings.AdministratorId) + if (this.User.UserID == this.PortalSettings.AdministratorId) { - //Clear the Portal Cache - DataCache.ClearPortalCache(UserPortalID, true); + // Clear the Portal Cache + DataCache.ClearPortalCache(this.UserPortalID, true); } + try { - //Update DisplayName to conform to Format - UpdateDisplayName(); + // Update DisplayName to conform to Format + this.UpdateDisplayName(); - //DNN-5874 Check if unique display name is required - if (PortalSettings.Registration.RequireUniqueDisplayName) + // DNN-5874 Check if unique display name is required + if (this.PortalSettings.Registration.RequireUniqueDisplayName) { - var usersWithSameDisplayName = (List)MembershipProvider.Instance().GetUsersBasicSearch(PortalId, 0, 2, "DisplayName", true, "DisplayName", User.DisplayName); - if (usersWithSameDisplayName.Any(user => user.UserID != User.UserID)) + var usersWithSameDisplayName = (List)MembershipProvider.Instance().GetUsersBasicSearch(this.PortalId, 0, 2, "DisplayName", true, "DisplayName", this.User.DisplayName); + if (usersWithSameDisplayName.Any(user => user.UserID != this.User.UserID)) { throw new Exception("Display Name must be unique"); } } - UserController.UpdateUser(UserPortalID, User); + UserController.UpdateUser(this.UserPortalID, this.User); // make sure username matches possibly changed email address - if (PortalSettings.Registration.UseEmailAsUserName) + if (this.PortalSettings.Registration.UseEmailAsUserName) { - if (User.Username.ToLower() != User.Email.ToLower()) + if (this.User.Username.ToLower() != this.User.Email.ToLower()) { - UserController.ChangeUsername(User.UserID, User.Email); + UserController.ChangeUsername(this.User.UserID, this.User.Email); - //after username changed, should redirect to login page to let user authenticate again. - var loginUrl = Globals.LoginURL(HttpUtility.UrlEncode(Request.RawUrl), false); + // after username changed, should redirect to login page to let user authenticate again. + var loginUrl = Globals.LoginURL(HttpUtility.UrlEncode(this.Request.RawUrl), false); var spliter = loginUrl.Contains("?") ? "&" : "?"; - loginUrl = $"{loginUrl}{spliter}username={User.Email}&usernameChanged=true"; - Response.Redirect(loginUrl, true); + loginUrl = $"{loginUrl}{spliter}username={this.User.Email}&usernameChanged=true"; + this.Response.Redirect(loginUrl, true); } } - Response.Redirect(Request.RawUrl); + this.Response.Redirect(this.Request.RawUrl); } catch (Exception exc) { Logger.Error(exc); if (exc.Message == "Display Name must be unique") { - AddModuleMessage("DisplayNameNotUnique", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("DisplayNameNotUnique", ModuleMessage.ModuleMessageType.RedError, true); } else { - AddModuleMessage("UserUpdatedError", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("UserUpdatedError", ModuleMessage.ModuleMessageType.RedError, true); } } } - } /// ----------------------------------------------------------------------------- @@ -538,101 +528,105 @@ protected void cmdUpdate_Click(object sender, EventArgs e) /// private void PasswordQuestionAnswerUpdated(object sender, Password.PasswordUpdatedEventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } + PasswordUpdateStatus status = e.UpdateStatus; if (status == PasswordUpdateStatus.Success) { - AddModuleMessage("PasswordQAChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.AddModuleMessage("PasswordQAChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); } else { - AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); } } /// ----------------------------------------------------------------------------- /// - /// PasswordUpdated runs when the Password has been updated or reset + /// PasswordUpdated runs when the Password has been updated or reset. /// /// /// private void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } + PasswordUpdateStatus status = e.UpdateStatus; if (status == PasswordUpdateStatus.Success) { - //Send Notification to User + // Send Notification to User try { var accessingUser = (UserInfo)HttpContext.Current.Items["UserInfo"]; - if (accessingUser.UserID != User.UserID) + if (accessingUser.UserID != this.User.UserID) { - //The password was changed by someone else - Mail.SendMail(User, MessageType.PasswordReminder, PortalSettings); + // The password was changed by someone else + Mail.SendMail(this.User, MessageType.PasswordReminder, this.PortalSettings); } else { - //The User changed his own password - Mail.SendMail(User, MessageType.UserUpdatedOwnPassword, PortalSettings); - PortalSecurity.Instance.SignIn(User, false); + // The User changed his own password + Mail.SendMail(this.User, MessageType.UserUpdatedOwnPassword, this.PortalSettings); + PortalSecurity.Instance.SignIn(this.User, false); } - AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); + + this.AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); } catch (Exception ex) { - AddModuleMessage("PasswordMailError", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.AddModuleMessage("PasswordMailError", ModuleMessage.ModuleMessageType.YellowWarning, true); Exceptions.LogException(ex); } } else { - AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); } } /// ----------------------------------------------------------------------------- /// - /// ProfileUpdateCompleted runs when the Profile has been updated + /// ProfileUpdateCompleted runs when the Profile has been updated. /// /// /// private void ProfileUpdateCompleted(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (IsUser) + + if (this.IsUser) { - //Notify the user that his/her profile was updated - Mail.SendMail(User, MessageType.ProfileUpdated, PortalSettings); + // Notify the user that his/her profile was updated + Mail.SendMail(this.User, MessageType.ProfileUpdated, this.PortalSettings); - ProfilePropertyDefinition localeProperty = User.Profile.GetProperty("PreferredLocale"); + ProfilePropertyDefinition localeProperty = this.User.Profile.GetProperty("PreferredLocale"); if (localeProperty.IsDirty) { - //store preferredlocale in cookie, if none specified set to portal default. - if (User.Profile.PreferredLocale == string.Empty) + // store preferredlocale in cookie, if none specified set to portal default. + if (this.User.Profile.PreferredLocale == string.Empty) { - Localization.SetLanguage(PortalController.GetPortalDefaultLanguage(User.PortalID)); + Localization.SetLanguage(PortalController.GetPortalDefaultLanguage(this.User.PortalID)); } else { - Localization.SetLanguage(User.Profile.PreferredLocale); + Localization.SetLanguage(this.User.Profile.PreferredLocale); } } } - //Redirect to same page (this will update all controls for any changes to profile - //and leave us at Page 0 (User Credentials) - Response.Redirect(Request.RawUrl, true); + // Redirect to same page (this will update all controls for any changes to profile + // and leave us at Page 0 (User Credentials) + this.Response.Redirect(this.Request.RawUrl, true); } private void SubscriptionUpdated(object sender, MemberServices.SubscriptionUpdatedEventArgs e) @@ -640,15 +634,14 @@ private void SubscriptionUpdated(object sender, MemberServices.SubscriptionUpdat string message; if (e.Cancel) { - message = string.Format(Localization.GetString("UserUnSubscribed", LocalResourceFile), e.RoleName); + message = string.Format(Localization.GetString("UserUnSubscribed", this.LocalResourceFile), e.RoleName); } else { - message = string.Format(Localization.GetString("UserSubscribed", LocalResourceFile), e.RoleName); + message = string.Format(Localization.GetString("UserSubscribed", this.LocalResourceFile), e.RoleName); } - AddLocalizedModuleMessage(message, ModuleMessage.ModuleMessageType.GreenSuccess, true); - } - #endregion + this.AddLocalizedModuleMessage(message, ModuleMessage.ModuleMessageType.GreenSuccess, true); + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs index 2c8a6f01c03..d70e39d9c6a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs @@ -1,84 +1,154 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Modules.Admin.Security; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Profile; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mail; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Modules.Admin.Security; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Profile; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mail; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// - /// The ManageUsers UserModuleBase is used to manage Users + /// The ManageUsers UserModuleBase is used to manage Users. /// /// /// public partial class ManageUsers : UserModuleBase, IActionable { private readonly INavigationManager _navigationManager; + public ManageUsers() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Protected Members - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the current Page No. + /// + public int PageNo + { + get + { + int _PageNo = 0; + if (this.ViewState["PageNo"] != null && !this.IsPostBack) + { + _PageNo = Convert.ToInt32(this.ViewState["PageNo"]); + } + + return _PageNo; + } + + set + { + this.ViewState["PageNo"] = value; + } + } + + public ModuleActionCollection ModuleActions + { + get + { + var Actions = new ModuleActionCollection(); + if (!this.IsProfile) + { + if (!this.AddUser && !this.IsEdit) + { + Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "add.gif", + this.EditUrl(), + false, + SecurityAccessLevel.Admin, + true, + false); + if (ProfileProviderConfig.CanEditProviderProperties) + { + Actions.Add( + this.GetNextActionID(), + Localization.GetString("ManageProfile.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "icon_profile_16px.gif", + this.EditUrl("ManageProfile"), + false, + SecurityAccessLevel.Admin, + true, + false); + } + + Actions.Add( + this.GetNextActionID(), + Localization.GetString("Cancel.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "lt.gif", + this.ReturnUrl, + false, + SecurityAccessLevel.Admin, + true, + false); + } + } + + return Actions; + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets whether to display the Manage Services tab + /// Gets a value indicating whether gets whether to display the Manage Services tab. /// protected bool DisplayServices { get { - object setting = GetSetting(PortalId, "Profile_ManageServices"); - return Convert.ToBoolean(setting) && !(IsEdit || User.IsSuperUser); + object setting = GetSetting(this.PortalId, "Profile_ManageServices"); + return Convert.ToBoolean(setting) && !(this.IsEdit || this.User.IsSuperUser); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Redirect URL (after successful registration) + /// Gets the Redirect URL (after successful registration). /// protected string RedirectURL { get { - string _RedirectURL = ""; + string _RedirectURL = string.Empty; - if (PortalSettings.Registration.RedirectAfterRegistration == Null.NullInteger) + if (this.PortalSettings.Registration.RedirectAfterRegistration == Null.NullInteger) { - if (Request.QueryString["returnurl"] != null) + if (this.Request.QueryString["returnurl"] != null) { - //return to the url passed to register - _RedirectURL = HttpUtility.UrlDecode(Request.QueryString["returnurl"]); + // return to the url passed to register + _RedirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); - //clean the return url to avoid possible XSS attack. + // clean the return url to avoid possible XSS attack. _RedirectURL = UrlUtils.ValidReturnUrl(_RedirectURL); if (_RedirectURL.Contains("?returnurl")) @@ -89,62 +159,67 @@ protected string RedirectURL _RedirectURL = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); } } - if (String.IsNullOrEmpty(_RedirectURL)) + + if (string.IsNullOrEmpty(_RedirectURL)) { - //redirect to current page - _RedirectURL = _navigationManager.NavigateURL(); + // redirect to current page + _RedirectURL = this._navigationManager.NavigateURL(); } } - else //redirect to after registration page + else // redirect to after registration page { - _RedirectURL = _navigationManager.NavigateURL(PortalSettings.Registration.RedirectAfterRegistration); + _RedirectURL = this._navigationManager.NavigateURL(this.PortalSettings.Registration.RedirectAfterRegistration); } + return _RedirectURL; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Return Url for the page + /// Gets the Return Url for the page. /// protected string ReturnUrl { get { - return _navigationManager.NavigateURL(TabId, "", !String.IsNullOrEmpty(UserFilter) ? UserFilter : ""); + return this._navigationManager.NavigateURL(this.TabId, string.Empty, !string.IsNullOrEmpty(this.UserFilter) ? this.UserFilter : string.Empty); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Filter to use + /// Gets and sets the Filter to use. /// protected string UserFilter { get { - string filterString = !string.IsNullOrEmpty(Request["filter"]) ? "filter=" + Request["filter"] : ""; - string filterProperty = !string.IsNullOrEmpty(Request["filterproperty"]) ? "filterproperty=" + Request["filterproperty"] : ""; - string page = !string.IsNullOrEmpty(Request["currentpage"]) ? "currentpage=" + Request["currentpage"] : ""; + string filterString = !string.IsNullOrEmpty(this.Request["filter"]) ? "filter=" + this.Request["filter"] : string.Empty; + string filterProperty = !string.IsNullOrEmpty(this.Request["filterproperty"]) ? "filterproperty=" + this.Request["filterproperty"] : string.Empty; + string page = !string.IsNullOrEmpty(this.Request["currentpage"]) ? "currentpage=" + this.Request["currentpage"] : string.Empty; if (!string.IsNullOrEmpty(filterString)) { filterString += "&"; } + if (!string.IsNullOrEmpty(filterProperty)) { filterString += filterProperty + "&"; } + if (!string.IsNullOrEmpty(page)) { filterString += page; } + return filterString; } } /// - /// Flag to indicate only edit profile. + /// Gets a value indicating whether flag to indicate only edit profile. /// protected bool EditProfileMode { @@ -152,478 +227,426 @@ protected bool EditProfileMode { bool editProfile; - return !string.IsNullOrEmpty(Request.QueryString["editProfile"]) - && bool.TryParse(Request["editProfile"], out editProfile) + return !string.IsNullOrEmpty(this.Request.QueryString["editProfile"]) + && bool.TryParse(this.Request["editProfile"], out editProfile) && editProfile; } - } - - #endregion - - #region Public Properties - + } + /// ----------------------------------------------------------------------------- /// - /// Gets and sets the current Page No + /// Page_Init runs when the control is initialised. /// - public int PageNo + /// + /// + protected override void OnInit(EventArgs e) { - get + base.OnInit(e); + + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdAdd.Click += this.cmdAdd_Click; + + this.ctlUser.UserCreateCompleted += this.UserCreateCompleted; + this.ctlUser.UserDeleted += this.UserDeleted; + this.ctlUser.UserRemoved += this.UserRemoved; + this.ctlUser.UserRestored += this.UserRestored; + this.ctlUser.UserUpdateCompleted += this.UserUpdateCompleted; + this.ctlUser.UserUpdateError += this.UserUpdateError; + + this.ctlProfile.ProfileUpdateCompleted += this.ProfileUpdateCompleted; + this.ctlPassword.PasswordUpdated += this.PasswordUpdated; + this.ctlPassword.PasswordQuestionAnswerUpdated += this.PasswordQuestionAnswerUpdated; + this.ctlMembership.MembershipAuthorized += this.MembershipAuthorized; + this.ctlMembership.MembershipPasswordUpdateChanged += this.MembershipPasswordUpdateChanged; + this.ctlMembership.MembershipUnAuthorized += this.MembershipUnAuthorized; + this.ctlMembership.MembershipUnLocked += this.MembershipUnLocked; + this.ctlMembership.MembershipDemoteFromSuperuser += this.MembershipDemoteFromSuperuser; + this.ctlMembership.MembershipPromoteToSuperuser += this.MembershipPromoteToSuperuser; + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + + // Set the Membership Control Properties + this.ctlMembership.ID = "Membership"; + this.ctlMembership.ModuleConfiguration = this.ModuleConfiguration; + this.ctlMembership.UserId = this.UserId; + + // Set the User Control Properties + this.ctlUser.ID = "User"; + this.ctlUser.ModuleConfiguration = this.ModuleConfiguration; + this.ctlUser.UserId = this.UserId; + + // Set the Roles Control Properties + this.ctlRoles.ID = "SecurityRoles"; + this.ctlRoles.ModuleConfiguration = this.ModuleConfiguration; + this.ctlRoles.ParentModule = this; + + // Set the Password Control Properties + this.ctlPassword.ID = "Password"; + this.ctlPassword.ModuleConfiguration = this.ModuleConfiguration; + this.ctlPassword.UserId = this.UserId; + + // Set the Profile Control Properties + this.ctlProfile.ID = "Profile"; + this.ctlProfile.ModuleConfiguration = this.ModuleConfiguration; + this.ctlProfile.UserId = this.UserId; + + // Customise the Control Title + if (this.AddUser) { - int _PageNo = 0; - if (ViewState["PageNo"] != null && !IsPostBack) + if (!this.Request.IsAuthenticated) { - _PageNo = Convert.ToInt32(ViewState["PageNo"]); + // Register + this.ModuleConfiguration.ModuleTitle = Localization.GetString("Register.Title", this.LocalResourceFile); } - return _PageNo; - } - set - { - ViewState["PageNo"] = value; + else + { + // Add User + this.ModuleConfiguration.ModuleTitle = Localization.GetString("AddUser.Title", this.LocalResourceFile); + } + + this.userContainer.CssClass += " register"; } } - #endregion - - #region IActionable Members - - public ModuleActionCollection ModuleActions + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) { - get + base.OnLoad(e); + + try { - var Actions = new ModuleActionCollection(); - if (!IsProfile) + // Add an Action Event Handler to the Skin + this.AddActionHandler(this.ModuleAction_Click); + + // Bind the User information to the controls + this.BindData(); + + this.loginLink.NavigateUrl = Globals.LoginURL(this.RedirectURL, this.Request.QueryString["override"] != null); + + if (this.PortalSettings.EnablePopUps) { - if (!AddUser && !IsEdit) - { - Actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), - ModuleActionType.AddContent, - "", - "add.gif", - EditUrl(), - false, - SecurityAccessLevel.Admin, - true, - false); - if (ProfileProviderConfig.CanEditProviderProperties) - { - Actions.Add(GetNextActionID(), - Localization.GetString("ManageProfile.Action", LocalResourceFile), - ModuleActionType.AddContent, - "", - "icon_profile_16px.gif", - EditUrl("ManageProfile"), - false, - SecurityAccessLevel.Admin, - true, - false); - } - Actions.Add(GetNextActionID(), - Localization.GetString("Cancel.Action", LocalResourceFile), - ModuleActionType.AddContent, - "", - "lt.gif", - ReturnUrl, - false, - SecurityAccessLevel.Admin, - true, - false); - } + this.loginLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(this.loginLink.NavigateUrl, this, this.PortalSettings, true, false, 300, 650)); } - return Actions; + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); } } - - #endregion - - #region Private Methods - + private void BindData() { - if (User != null) + if (this.User != null) { - //If trying to add a SuperUser - check that user is a SuperUser - if (VerifyUserPermissions()==false) + // If trying to add a SuperUser - check that user is a SuperUser + if (this.VerifyUserPermissions() == false) { return; } - if (AddUser) + if (this.AddUser) { - cmdAdd.Text = Localization.GetString("AddUser", LocalResourceFile); - lblTitle.Text = Localization.GetString("AddUser", LocalResourceFile); + this.cmdAdd.Text = Localization.GetString("AddUser", this.LocalResourceFile); + this.lblTitle.Text = Localization.GetString("AddUser", this.LocalResourceFile); } else { - if (!Request.IsAuthenticated) + if (!this.Request.IsAuthenticated) { - titleRow.Visible = false; + this.titleRow.Visible = false; } else { - if (IsProfile) + if (this.IsProfile) { - titleRow.Visible = false; + this.titleRow.Visible = false; } else { - lblTitle.Text = string.Format(Localization.GetString("UserTitle", LocalResourceFile), User.Username, User.UserID); + this.lblTitle.Text = string.Format(Localization.GetString("UserTitle", this.LocalResourceFile), this.User.Username, this.User.UserID); } } } - if (!Page.IsPostBack) + + if (!this.Page.IsPostBack) { - if ((Request.QueryString["pageno"] != null)) + if (this.Request.QueryString["pageno"] != null) { - PageNo = int.Parse(Request.QueryString["pageno"]); + this.PageNo = int.Parse(this.Request.QueryString["pageno"]); } else { - PageNo = 0; + this.PageNo = 0; } } - ShowPanel(); + + this.ShowPanel(); } else { - AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); } } private bool VerifyUserPermissions() { - if (AddUser && IsHostMenu && !UserInfo.IsSuperUser) + if (this.AddUser && this.IsHostMenu && !this.UserInfo.IsSuperUser) { - AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } - //Check if User is a member of the Current Portal (or a member of the MasterPortal if PortalGroups enabled) - if (User.PortalID != Null.NullInteger && User.PortalID != PortalId) + // Check if User is a member of the Current Portal (or a member of the MasterPortal if PortalGroups enabled) + if (this.User.PortalID != Null.NullInteger && this.User.PortalID != this.PortalId) { - AddModuleMessage("InvalidUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("InvalidUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } - //Check if User is a SuperUser and that the current User is a SuperUser - if (User.IsSuperUser && !UserInfo.IsSuperUser) + // Check if User is a SuperUser and that the current User is a SuperUser + if (this.User.IsSuperUser && !this.UserInfo.IsSuperUser) { - AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } - if (IsEdit) + + if (this.IsEdit) { - //Check if user has admin rights - if (!IsAdmin || (User.IsInRole(PortalSettings.AdministratorRoleName) && !PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))) + // Check if user has admin rights + if (!this.IsAdmin || (this.User.IsInRole(this.PortalSettings.AdministratorRoleName) && !PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName))) { - AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } } else { - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { - if (!PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) ) + if (!PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName)) { - if (HasManageUsersModulePermission() == false) + if (this.HasManageUsersModulePermission() == false) { - //Display current user's profile - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.UserTabId, "", "UserID=" + UserInfo.UserID), true); + // Display current user's profile + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.UserTabId, string.Empty, "UserID=" + this.UserInfo.UserID), true); } } } else { - if ((User.UserID > Null.NullInteger)) + if (this.User.UserID > Null.NullInteger) { - AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); - DisableForm(); + this.AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.DisableForm(); return false; } } } + return true; } private void BindMembership() { - ctlMembership.User = User; - ctlMembership.DataBind(); - AddModuleMessage("UserLockedOut", ModuleMessage.ModuleMessageType.YellowWarning, ctlMembership.UserMembership.LockedOut && (!Page.IsPostBack)); - imgLockedOut.Visible = ctlMembership.UserMembership.LockedOut; - imgOnline.Visible = ctlMembership.UserMembership.IsOnLine; + this.ctlMembership.User = this.User; + this.ctlMembership.DataBind(); + this.AddModuleMessage("UserLockedOut", ModuleMessage.ModuleMessageType.YellowWarning, this.ctlMembership.UserMembership.LockedOut && (!this.Page.IsPostBack)); + this.imgLockedOut.Visible = this.ctlMembership.UserMembership.LockedOut; + this.imgOnline.Visible = this.ctlMembership.UserMembership.IsOnLine; } private void BindUser() { - if (AddUser) + if (this.AddUser) { - ctlUser.ShowUpdate = false; - CheckQuota(); + this.ctlUser.ShowUpdate = false; + this.CheckQuota(); } - ctlUser.User = User; - ctlUser.DataBind(); + + this.ctlUser.User = this.User; + this.ctlUser.DataBind(); - //Bind the Membership - if (AddUser || (!IsAdmin)) + // Bind the Membership + if (this.AddUser || (!this.IsAdmin)) { - membershipRow.Visible = false; + this.membershipRow.Visible = false; } else { - BindMembership(); + this.BindMembership(); } } private void CheckQuota() { - if (PortalSettings.Users < PortalSettings.UserQuota || UserInfo.IsSuperUser || PortalSettings.UserQuota == 0) + if (this.PortalSettings.Users < this.PortalSettings.UserQuota || this.UserInfo.IsSuperUser || this.PortalSettings.UserQuota == 0) { - cmdAdd.Enabled = true; + this.cmdAdd.Enabled = true; } else { - cmdAdd.Enabled = false; - AddModuleMessage("ExceededUserQuota", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.cmdAdd.Enabled = false; + this.AddModuleMessage("ExceededUserQuota", ModuleMessage.ModuleMessageType.YellowWarning, true); } } private void DisableForm() { - adminTabNav.Visible = false; - dnnRoleDetails.Visible = false; - dnnPasswordDetails.Visible = false; - dnnProfileDetails.Visible = false; - actionsRow.Visible = false; - ctlMembership.Visible = false; - ctlUser.Visible = false; + this.adminTabNav.Visible = false; + this.dnnRoleDetails.Visible = false; + this.dnnPasswordDetails.Visible = false; + this.dnnProfileDetails.Visible = false; + this.actionsRow.Visible = false; + this.ctlMembership.Visible = false; + this.ctlUser.Visible = false; } private void ShowPanel() { - if (AddUser) + if (this.AddUser) { - adminTabNav.Visible = false; - if (Request.IsAuthenticated && MembershipProviderConfig.RequiresQuestionAndAnswer) + this.adminTabNav.Visible = false; + if (this.Request.IsAuthenticated && MembershipProviderConfig.RequiresQuestionAndAnswer) { - //Admin adding user - dnnManageUsers.Visible = false; - actionsRow.Visible = false; - AddModuleMessage("CannotAddUser", ModuleMessage.ModuleMessageType.YellowWarning, true); + // Admin adding user + this.dnnManageUsers.Visible = false; + this.actionsRow.Visible = false; + this.AddModuleMessage("CannotAddUser", ModuleMessage.ModuleMessageType.YellowWarning, true); } else { - dnnManageUsers.Visible = true; - actionsRow.Visible = true; + this.dnnManageUsers.Visible = true; + this.actionsRow.Visible = true; } - BindUser(); - dnnProfileDetails.Visible = false; + + this.BindUser(); + this.dnnProfileDetails.Visible = false; } else { - if ((!IsAdmin)) + if (!this.IsAdmin) { - passwordTab.Visible = false; + this.passwordTab.Visible = false; } else { - ctlPassword.User = User; - ctlPassword.DataBind(); + this.ctlPassword.User = this.User; + this.ctlPassword.DataBind(); } - if ((!IsEdit || User.IsSuperUser)) + + if (!this.IsEdit || this.User.IsSuperUser) { - rolesTab.Visible = false; + this.rolesTab.Visible = false; } else { - ctlRoles.DataBind(); + this.ctlRoles.DataBind(); } - BindUser(); - ctlProfile.User = User; - ctlProfile.DataBind(); + this.BindUser(); + this.ctlProfile.User = this.User; + this.ctlProfile.DataBind(); } - dnnRoleDetails.Visible = IsEdit && !User.IsSuperUser && !AddUser; - dnnPasswordDetails.Visible = (IsAdmin) && !AddUser; + this.dnnRoleDetails.Visible = this.IsEdit && !this.User.IsSuperUser && !this.AddUser; + this.dnnPasswordDetails.Visible = this.IsAdmin && !this.AddUser; - if(EditProfileMode) + if (this.EditProfileMode) { - adminTabNav.Visible = - dnnUserDetails.Visible = - dnnRoleDetails.Visible = - dnnPasswordDetails.Visible = - actionsRow.Visible = false; + this.adminTabNav.Visible = + this.dnnUserDetails.Visible = + this.dnnRoleDetails.Visible = + this.dnnPasswordDetails.Visible = + this.actionsRow.Visible = false; } - } + } - #endregion - - #region Event Handlers + protected void cmdCancel_Click(object sender, EventArgs e) + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } /// ----------------------------------------------------------------------------- /// - /// Page_Init runs when the control is initialised + /// cmdRegister_Click runs when the Register button is clicked. /// /// /// - protected override void OnInit(EventArgs e) + protected void cmdAdd_Click(object sender, EventArgs e) { - base.OnInit(e); - - cmdCancel.Click += cmdCancel_Click; - cmdAdd.Click += cmdAdd_Click; - - ctlUser.UserCreateCompleted += UserCreateCompleted; - ctlUser.UserDeleted += UserDeleted; - ctlUser.UserRemoved += UserRemoved; - ctlUser.UserRestored += UserRestored; - ctlUser.UserUpdateCompleted += UserUpdateCompleted; - ctlUser.UserUpdateError += UserUpdateError; - - ctlProfile.ProfileUpdateCompleted += ProfileUpdateCompleted; - ctlPassword.PasswordUpdated += PasswordUpdated; - ctlPassword.PasswordQuestionAnswerUpdated += PasswordQuestionAnswerUpdated; - ctlMembership.MembershipAuthorized += MembershipAuthorized; - ctlMembership.MembershipPasswordUpdateChanged += MembershipPasswordUpdateChanged; - ctlMembership.MembershipUnAuthorized += MembershipUnAuthorized; - ctlMembership.MembershipUnLocked += MembershipUnLocked; - ctlMembership.MembershipDemoteFromSuperuser += MembershipDemoteFromSuperuser; - ctlMembership.MembershipPromoteToSuperuser += MembershipPromoteToSuperuser; - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - - //Set the Membership Control Properties - ctlMembership.ID = "Membership"; - ctlMembership.ModuleConfiguration = ModuleConfiguration; - ctlMembership.UserId = UserId; - - //Set the User Control Properties - ctlUser.ID = "User"; - ctlUser.ModuleConfiguration = ModuleConfiguration; - ctlUser.UserId = UserId; - - //Set the Roles Control Properties - ctlRoles.ID = "SecurityRoles"; - ctlRoles.ModuleConfiguration = ModuleConfiguration; - ctlRoles.ParentModule = this; - - //Set the Password Control Properties - ctlPassword.ID = "Password"; - ctlPassword.ModuleConfiguration = ModuleConfiguration; - ctlPassword.UserId = UserId; - - //Set the Profile Control Properties - ctlProfile.ID = "Profile"; - ctlProfile.ModuleConfiguration = ModuleConfiguration; - ctlProfile.UserId = UserId; - - //Customise the Control Title - if (AddUser) + if (this.IsAdmin == false && this.HasManageUsersModulePermission() == false) { - if (!Request.IsAuthenticated) - { - //Register - ModuleConfiguration.ModuleTitle = Localization.GetString("Register.Title", LocalResourceFile); - } - else + return; + } + + if (this.ctlUser.IsValid && this.ctlProfile.IsValid) + { + this.ctlUser.CreateUser(); + } + else + { + if (this.ctlUser.CreateStatus != UserCreateStatus.AddUser) { - //Add User - ModuleConfiguration.ModuleTitle = Localization.GetString("AddUser.Title", LocalResourceFile); + this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(this.ctlUser.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); } - - userContainer.CssClass += " register"; } } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// MembershipPasswordUpdateChanged runs when the Admin has forced the User to update their password. /// /// /// - protected override void OnLoad(EventArgs e) + protected void MembershipPasswordUpdateChanged(object sender, EventArgs e) { - base.OnLoad(e); - + if (this.IsAdmin == false) + { + return; + } + try { - //Add an Action Event Handler to the Skin - AddActionHandler(ModuleAction_Click); + this.AddModuleMessage("UserPasswordUpdateChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); - //Bind the User information to the controls - BindData(); - - loginLink.NavigateUrl = Globals.LoginURL(RedirectURL, (Request.QueryString["override"] != null)); - - if (PortalSettings.EnablePopUps) - { - loginLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(loginLink.NavigateUrl, this, PortalSettings, true, false, 300, 650)); - } + this.BindMembership(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } - protected void cmdCancel_Click(object sender, EventArgs e) - { - Response.Redirect(_navigationManager.NavigateURL(), true); - } - private bool HasManageUsersModulePermission() { - return ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, "MANAGEUSER"); + return ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, "MANAGEUSER"); } /// ----------------------------------------------------------------------------- /// - /// cmdRegister_Click runs when the Register button is clicked + /// ModuleAction_Click handles all ModuleAction events raised from the skin. /// /// /// - protected void cmdAdd_Click(object sender, EventArgs e) - { - if (IsAdmin == false && HasManageUsersModulePermission() == false) - { - return; - } - if (ctlUser.IsValid && (ctlProfile.IsValid)) - { - ctlUser.CreateUser(); - } - else - { - if (ctlUser.CreateStatus != UserCreateStatus.AddUser) - { - AddLocalizedModuleMessage(UserController.GetUserCreateStatus(ctlUser.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// ModuleAction_Click handles all ModuleAction events raised from the skin - /// - /// - /// - /// The object that triggers the event - /// An ActionEventArgs object + /// The object that triggers the event. + /// An ActionEventArgs object. private void ModuleAction_Click(object sender, ActionEventArgs e) { switch (e.Action.CommandArgument) { case "ManageRoles": - //pnlRoles.Visible = true; - //pnlUser.Visible = false; + // pnlRoles.Visible = true; + // pnlUser.Visible = false; break; case "Cancel": break; @@ -640,81 +663,57 @@ private void ModuleAction_Click(object sender, ActionEventArgs e) /// ----------------------------------------------------------------------------- /// - /// MembershipAuthorized runs when the User has been unlocked + /// MembershipAuthorized runs when the User has been unlocked. /// /// /// private void MembershipAuthorized(object sender, EventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } + try { - AddModuleMessage("UserAuthorized", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.AddModuleMessage("UserAuthorized", ModuleMessage.ModuleMessageType.GreenSuccess, true); - //Send Notification to User - if (string.IsNullOrEmpty(User.Membership.Password) && !MembershipProviderConfig.RequiresQuestionAndAnswer && MembershipProviderConfig.PasswordRetrievalEnabled) + // Send Notification to User + if (string.IsNullOrEmpty(this.User.Membership.Password) && !MembershipProviderConfig.RequiresQuestionAndAnswer && MembershipProviderConfig.PasswordRetrievalEnabled) { - UserInfo user = User; - User.Membership.Password = UserController.GetPassword(ref user, ""); + UserInfo user = this.User; + this.User.Membership.Password = UserController.GetPassword(ref user, string.Empty); } - BindMembership(); + this.BindMembership(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } - + /// ----------------------------------------------------------------------------- /// - /// MembershipPasswordUpdateChanged runs when the Admin has forced the User to update their password - /// - /// - /// - protected void MembershipPasswordUpdateChanged(object sender, EventArgs e) - { - if (IsAdmin == false) - { - return; - } - try - { - AddModuleMessage("UserPasswordUpdateChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); - - BindMembership(); - } - catch (Exception exc) //Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - - - /// ----------------------------------------------------------------------------- - /// - /// MembershipPromoteToSuperuser runs when the User has been promoted to a superuser + /// MembershipPromoteToSuperuser runs when the User has been promoted to a superuser. /// /// /// /// ----------------------------------------------------------------------------- private void MembershipPromoteToSuperuser(object sender, EventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } + try { - AddModuleMessage("UserPromotedToSuperuser", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.AddModuleMessage("UserPromotedToSuperuser", ModuleMessage.ModuleMessageType.GreenSuccess, true); - BindMembership(); + this.BindMembership(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -722,24 +721,25 @@ private void MembershipPromoteToSuperuser(object sender, EventArgs e) /// ----------------------------------------------------------------------------- /// - /// MembershipDemoteFromSuperuser runs when the User has been demoted to a regular user + /// MembershipDemoteFromSuperuser runs when the User has been demoted to a regular user. /// /// /// /// ----------------------------------------------------------------------------- private void MembershipDemoteFromSuperuser(object sender, EventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } + try { - AddModuleMessage("UserDemotedFromSuperuser", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.AddModuleMessage("UserDemotedFromSuperuser", ModuleMessage.ModuleMessageType.GreenSuccess, true); - BindMembership(); + this.BindMembership(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -747,23 +747,24 @@ private void MembershipDemoteFromSuperuser(object sender, EventArgs e) /// ----------------------------------------------------------------------------- /// - /// MembershipUnAuthorized runs when the User has been unlocked + /// MembershipUnAuthorized runs when the User has been unlocked. /// /// /// private void MembershipUnAuthorized(object sender, EventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } + try { - AddModuleMessage("UserUnAuthorized", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.AddModuleMessage("UserUnAuthorized", ModuleMessage.ModuleMessageType.GreenSuccess, true); - BindMembership(); + this.BindMembership(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -771,22 +772,23 @@ private void MembershipUnAuthorized(object sender, EventArgs e) /// ----------------------------------------------------------------------------- /// - /// MembershipUnLocked runs when the User has been unlocked + /// MembershipUnLocked runs when the User has been unlocked. /// /// /// private void MembershipUnLocked(object sender, EventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } + try { - AddModuleMessage("UserUnLocked", ModuleMessage.ModuleMessageType.GreenSuccess, true); - BindMembership(); + this.AddModuleMessage("UserUnLocked", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.BindMembership(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -800,81 +802,84 @@ private void MembershipUnLocked(object sender, EventArgs e) /// private void PasswordQuestionAnswerUpdated(object sender, Password.PasswordUpdatedEventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } + PasswordUpdateStatus status = e.UpdateStatus; if (status == PasswordUpdateStatus.Success) { - AddModuleMessage("PasswordQAChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.AddModuleMessage("PasswordQAChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); } else { - AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); } } /// ----------------------------------------------------------------------------- /// - /// PasswordUpdated runs when the Password has been updated or reset + /// PasswordUpdated runs when the Password has been updated or reset. /// /// /// private void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } + PasswordUpdateStatus status = e.UpdateStatus; if (status == PasswordUpdateStatus.Success) { - //Send Notification to User + // Send Notification to User try { - var accessingUser = (UserInfo) HttpContext.Current.Items["UserInfo"]; - if (accessingUser.UserID != User.UserID) + var accessingUser = (UserInfo)HttpContext.Current.Items["UserInfo"]; + if (accessingUser.UserID != this.User.UserID) { - //The password was changed by someone else - Mail.SendMail(User, MessageType.PasswordUpdated, PortalSettings); + // The password was changed by someone else + Mail.SendMail(this.User, MessageType.PasswordUpdated, this.PortalSettings); } else { - //The User changed his own password - Mail.SendMail(User, MessageType.UserUpdatedOwnPassword, PortalSettings); + // The User changed his own password + Mail.SendMail(this.User, MessageType.UserUpdatedOwnPassword, this.PortalSettings); } - AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); + + this.AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); } catch (Exception ex) { - AddModuleMessage("PasswordMailError", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.AddModuleMessage("PasswordMailError", ModuleMessage.ModuleMessageType.YellowWarning, true); Exceptions.LogException(ex); } } else { - AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); } } /// ----------------------------------------------------------------------------- /// - /// ProfileUpdateCompleted runs when the Profile has been updated + /// ProfileUpdateCompleted runs when the Profile has been updated. /// /// /// private void ProfileUpdateCompleted(object sender, EventArgs e) { - if (IsAdmin == false) + if (this.IsAdmin == false) { return; } - //Redirect to same page (this will update all controls for any changes to profile - //and leave us at Page 0 (User Credentials) - Response.Redirect(Request.RawUrl, true); + // Redirect to same page (this will update all controls for any changes to profile + // and leave us at Page 0 (User Credentials) + this.Response.Redirect(this.Request.RawUrl, true); } private void SubscriptionUpdated(object sender, MemberServices.SubscriptionUpdatedEventArgs e) @@ -882,18 +887,19 @@ private void SubscriptionUpdated(object sender, MemberServices.SubscriptionUpdat string message = Null.NullString; if (e.Cancel) { - message = string.Format(Localization.GetString("UserUnSubscribed", LocalResourceFile), e.RoleName); + message = string.Format(Localization.GetString("UserUnSubscribed", this.LocalResourceFile), e.RoleName); } else { - message = string.Format(Localization.GetString("UserSubscribed", LocalResourceFile), e.RoleName); + message = string.Format(Localization.GetString("UserSubscribed", this.LocalResourceFile), e.RoleName); } - AddLocalizedModuleMessage(message, ModuleMessage.ModuleMessageType.GreenSuccess, true); + + this.AddLocalizedModuleMessage(message, ModuleMessage.ModuleMessageType.GreenSuccess, true); } /// ----------------------------------------------------------------------------- /// - /// UserCreateCompleted runs when a new user has been Created + /// UserCreateCompleted runs when a new user has been Created. /// /// /// @@ -903,15 +909,15 @@ private void UserCreateCompleted(object sender, UserUserControlBase.UserCreatedE { if (e.CreateStatus == UserCreateStatus.Success) { - CompleteUserCreation(e.CreateStatus, e.NewUser, e.Notify, false); - Response.Redirect(ReturnUrl, true); + this.CompleteUserCreation(e.CreateStatus, e.NewUser, e.Notify, false); + this.Response.Redirect(this.ReturnUrl, true); } else { - AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); + this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -919,7 +925,7 @@ private void UserCreateCompleted(object sender, UserUserControlBase.UserCreatedE /// ----------------------------------------------------------------------------- /// - /// UserDeleted runs when the User has been deleted + /// UserDeleted runs when the User has been deleted. /// /// /// @@ -927,9 +933,9 @@ private void UserDeleted(object sender, UserUserControlBase.UserDeletedEventArgs { try { - Response.Redirect(ReturnUrl, true); + this.Response.Redirect(this.ReturnUrl, true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -937,7 +943,7 @@ private void UserDeleted(object sender, UserUserControlBase.UserDeletedEventArgs /// ----------------------------------------------------------------------------- /// - /// UserUpdateCompleted runs when a user has been updated + /// UserUpdateCompleted runs when a user has been updated. /// /// /// @@ -945,8 +951,9 @@ private void UserRestored(object sender, UserUserControlBase.UserRestoredEventAr { try { - Response.Redirect(ReturnUrl, true); - //Module failed to load + this.Response.Redirect(this.ReturnUrl, true); + + // Module failed to load } catch (Exception exc) { @@ -958,8 +965,9 @@ private void UserRemoved(object sender, UserUserControlBase.UserRemovedEventArgs { try { - Response.Redirect(ReturnUrl, true); - //Module failed to load + this.Response.Redirect(this.ReturnUrl, true); + + // Module failed to load } catch (Exception exc) { @@ -969,21 +977,19 @@ private void UserRemoved(object sender, UserUserControlBase.UserRemovedEventArgs private void UserUpdateCompleted(object sender, EventArgs e) { - Response.Redirect(Request.RawUrl, false); + this.Response.Redirect(this.Request.RawUrl, false); HttpContext.Current.ApplicationInstance.CompleteRequest(); } /// ----------------------------------------------------------------------------- /// - /// UserUpdateError runs when there is an error updating the user + /// UserUpdateError runs when there is an error updating the user. /// /// /// private void UserUpdateError(object sender, UserUserControlBase.UserUpdateErrorArgs e) { - AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); - } - - #endregion + this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs index f8f96af4096..c7f81b6342a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs @@ -1,133 +1,79 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Web.UI.WebControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Security { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// - /// The MemberServices UserModuleBase is used to manage a User's services + /// The MemberServices UserModuleBase is used to manage a User's services. /// /// /// /// ----------------------------------------------------------------------------- public partial class MemberServices : UserModuleBase - { - #region Delegates - - public delegate void SubscriptionUpdatedEventHandler(object sender, SubscriptionUpdatedEventArgs e); - - #endregion - - #region "Events" - - public event SubscriptionUpdatedEventHandler SubscriptionUpdated; - - #endregion - - #region "Private Methods" - + { + public delegate void SubscriptionUpdatedEventHandler(object sender, SubscriptionUpdatedEventArgs e); + + public event SubscriptionUpdatedEventHandler SubscriptionUpdated; + /// ----------------------------------------------------------------------------- /// - /// FormatPrice formats the Fee amount and filters out null-values + /// DataBind binds the data to the controls. /// - /// - /// - /// The price to format - /// The correctly formatted price /// ----------------------------------------------------------------------------- - private string FormatPrice(float price) - { - string formatPrice = Null.NullString; - try - { - if (price != Null.NullSingle) - { - formatPrice = price.ToString("##0.00"); - } - else - { - formatPrice = ""; - } - } - catch (Exception exc) //Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - return formatPrice; - } - - private void Subscribe(int roleID, bool cancel) + public override void DataBind() { - RoleInfo objRole = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == roleID); - - if (objRole.IsPublic && objRole.ServiceFee == 0.0) + if (this.Request.IsAuthenticated) { - RoleController.Instance.UpdateUserRole(PortalId, UserInfo.UserID, roleID, RoleStatus.Approved, false, cancel); + Localization.LocalizeDataGrid(ref this.grdServices, this.LocalResourceFile); + this.grdServices.DataSource = RoleController.Instance.GetUserRoles(this.UserInfo, false); + this.grdServices.DataBind(); - //Raise SubscriptionUpdated Event - OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(cancel, objRole.RoleName)); + // if no service available then hide options + this.ServicesRow.Visible = this.grdServices.Items.Count > 0; } - else - { - if (!cancel) - { - Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID, true); - } - else - { - Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID + "&cancel=1", true); - } - } - } - - private void UseTrial(int roleID) + } + + /// ----------------------------------------------------------------------------- + /// + /// Raises the SubscriptionUpdated Event. + /// + /// ----------------------------------------------------------------------------- + public void OnSubscriptionUpdated(SubscriptionUpdatedEventArgs e) { - RoleInfo objRole = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == roleID); ; - - if (objRole.IsPublic && objRole.TrialFee == 0.0) + if (this.IsUserOrAdmin == false) { - RoleController.Instance.UpdateUserRole(PortalId, UserInfo.UserID, roleID, RoleStatus.Approved, false, false); - - //Raise SubscriptionUpdated Event - OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName)); + return; } - else + + if (this.SubscriptionUpdated != null) { - Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID, true); + this.SubscriptionUpdated(this, e); } - } - - #endregion - - #region "Protected Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// FormatExpiryDate formats the expiry date and filters out null-values + /// FormatExpiryDate formats the expiry date and filters out null-values. /// /// /// - /// The date to format - /// The correctly formatted date + /// The date to format. + /// The correctly formatted date. /// ----------------------------------------------------------------------------- protected string FormatExpiryDate(DateTime expiryDate) { @@ -142,27 +88,28 @@ protected string FormatExpiryDate(DateTime expiryDate) } else { - formatExpiryDate = Localization.GetString("Expired", LocalResourceFile); + formatExpiryDate = Localization.GetString("Expired", this.LocalResourceFile); } } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } + return formatExpiryDate; } /// ----------------------------------------------------------------------------- /// - /// FormatPrice formats the Fee amount and filters out null-values + /// FormatPrice formats the Fee amount and filters out null-values. /// /// /// - /// The price to format + /// The price to format. /// Period of price. /// Frenquency of price. - /// The correctly formatted price + /// The correctly formatted price. /// ----------------------------------------------------------------------------- protected string FormatPrice(float price, int period, string frequency) { @@ -173,33 +120,106 @@ protected string FormatPrice(float price, int period, string frequency) { case "N": case "": - formatPrice = Localization.GetString("NoFee", LocalResourceFile); + formatPrice = Localization.GetString("NoFee", this.LocalResourceFile); break; case "O": - formatPrice = FormatPrice(price); + formatPrice = this.FormatPrice(price); break; default: - formatPrice = string.Format(Localization.GetString("Fee", LocalResourceFile), FormatPrice(price), period, Localization.GetString("Frequency_" + frequency, LocalResourceFile)); + formatPrice = string.Format(Localization.GetString("Fee", this.LocalResourceFile), this.FormatPrice(price), period, Localization.GetString("Frequency_" + frequency, this.LocalResourceFile)); break; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } + + return formatPrice; + } + + /// ----------------------------------------------------------------------------- + /// + /// FormatPrice formats the Fee amount and filters out null-values. + /// + /// + /// + /// The price to format. + /// The correctly formatted price. + /// ----------------------------------------------------------------------------- + private string FormatPrice(float price) + { + string formatPrice = Null.NullString; + try + { + if (price != Null.NullSingle) + { + formatPrice = price.ToString("##0.00"); + } + else + { + formatPrice = string.Empty; + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + return formatPrice; } + private void Subscribe(int roleID, bool cancel) + { + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); + + if (objRole.IsPublic && objRole.ServiceFee == 0.0) + { + RoleController.Instance.UpdateUserRole(this.PortalId, this.UserInfo.UserID, roleID, RoleStatus.Approved, false, cancel); + + // Raise SubscriptionUpdated Event + this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(cancel, objRole.RoleName)); + } + else + { + if (!cancel) + { + this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID, true); + } + else + { + this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID + "&cancel=1", true); + } + } + } + + private void UseTrial(int roleID) + { + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); + + if (objRole.IsPublic && objRole.TrialFee == 0.0) + { + RoleController.Instance.UpdateUserRole(this.PortalId, this.UserInfo.UserID, roleID, RoleStatus.Approved, false, false); + + // Raise SubscriptionUpdated Event + this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName)); + } + else + { + this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID, true); + } + } + /// ----------------------------------------------------------------------------- /// - /// FormatTrial formats the Trial Fee amount and filters out null-values + /// FormatTrial formats the Trial Fee amount and filters out null-values. /// /// /// - /// The price to format + /// The price to format. /// Period of price. /// Frenquency of price. - /// The correctly formatted price + /// The correctly formatted price. /// ----------------------------------------------------------------------------- protected string FormatTrial(float price, int period, string frequency) { @@ -210,62 +230,66 @@ protected string FormatTrial(float price, int period, string frequency) { case "N": case "": - formatTrial = Localization.GetString("NoFee", LocalResourceFile); + formatTrial = Localization.GetString("NoFee", this.LocalResourceFile); break; case "O": - formatTrial = FormatPrice(price); + formatTrial = this.FormatPrice(price); break; default: - formatTrial = string.Format(Localization.GetString("TrialFee", LocalResourceFile), - FormatPrice(price), - period, - Localization.GetString("Frequency_" + frequency, LocalResourceFile)); + formatTrial = string.Format( + Localization.GetString("TrialFee", this.LocalResourceFile), + this.FormatPrice(price), + period, + Localization.GetString("Frequency_" + frequency, this.LocalResourceFile)); break; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } + return formatTrial; } /// ----------------------------------------------------------------------------- /// - /// FormatURL correctly formats a URL + /// FormatURL correctly formats a URL. /// /// /// - /// The correctly formatted url + /// The correctly formatted url. /// ----------------------------------------------------------------------------- protected string FormatURL() { string formatURL = Null.NullString; try { - string serverPath = Request.ApplicationPath; + string serverPath = this.Request.ApplicationPath; if (!serverPath.EndsWith("/")) { serverPath += "/"; } - formatURL = serverPath + "Register.aspx?tabid=" + TabId; + + formatURL = serverPath + "Register.aspx?tabid=" + this.TabId; } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } + return formatURL; } /// ----------------------------------------------------------------------------- /// - /// ServiceText gets the Service Text (Cancel or Subscribe) + /// ServiceText gets the Service Text (Cancel or Subscribe). /// /// /// - /// The service state - /// The service expiry date. - /// The correctly formatted text + /// The service state. + /// The service expiry date. + /// The correctly formatted text. /// ----------------------------------------------------------------------------- protected string ServiceText(bool subscribed, DateTime expiryDate) { @@ -274,34 +298,35 @@ protected string ServiceText(bool subscribed, DateTime expiryDate) { if (!subscribed) { - serviceText = Localization.GetString("Subscribe", LocalResourceFile); + serviceText = Localization.GetString("Subscribe", this.LocalResourceFile); } else { - serviceText = Localization.GetString("Unsubscribe", LocalResourceFile); + serviceText = Localization.GetString("Unsubscribe", this.LocalResourceFile); if (!Null.IsNull(expiryDate)) { if (expiryDate < DateTime.Today) { - serviceText = Localization.GetString("Renew", LocalResourceFile); + serviceText = Localization.GetString("Renew", this.LocalResourceFile); } } } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } + return serviceText; } protected bool ShowSubscribe(int roleID) { bool showSubscribe = Null.NullBoolean; - RoleInfo objRole = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == roleID); ; + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); if (objRole.IsPublic) { - PortalInfo objPortal = PortalController.Instance.GetPortal(PortalSettings.PortalId); + PortalInfo objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); if (objRole.ServiceFee == 0.0) { showSubscribe = true; @@ -311,200 +336,154 @@ protected bool ShowSubscribe(int roleID) showSubscribe = true; } } + return showSubscribe; } protected bool ShowTrial(int roleID) { bool showTrial = Null.NullBoolean; - RoleInfo objRole = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == roleID); ; + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); if (string.IsNullOrEmpty(objRole.TrialFrequency) || objRole.TrialFrequency == "N" || (objRole.IsPublic && objRole.ServiceFee == 0.0)) { showTrial = Null.NullBoolean; } else if (objRole.IsPublic && objRole.TrialFee == 0.0) { - //Use Trial? - UserRoleInfo objUserRole = RoleController.Instance.GetUserRole(PortalId, UserInfo.UserID, roleID); + // Use Trial? + UserRoleInfo objUserRole = RoleController.Instance.GetUserRole(this.PortalId, this.UserInfo.UserID, roleID); if ((objUserRole == null) || (!objUserRole.IsTrialUsed)) { showTrial = true; } } + return showTrial; - } - - #endregion - - #region "Public Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// DataBind binds the data to the controls + /// Page_Load runs when the control is loaded. /// + /// + /// /// ----------------------------------------------------------------------------- - public override void DataBind() + protected override void OnLoad(EventArgs e) { - if (Request.IsAuthenticated) - { - Localization.LocalizeDataGrid(ref grdServices, LocalResourceFile); - grdServices.DataSource = RoleController.Instance.GetUserRoles(UserInfo, false); - grdServices.DataBind(); + base.OnLoad(e); - //if no service available then hide options - ServicesRow.Visible = (grdServices.Items.Count > 0); - } + this.cmdRSVP.Click += this.cmdRSVP_Click; + this.grdServices.ItemCommand += this.grdServices_ItemCommand; + this.lblRSVP.Text = string.Empty; } - #endregion - - #region "Event Methods" - - /// ----------------------------------------------------------------------------- - /// - /// Raises the SubscriptionUpdated Event - /// - /// ----------------------------------------------------------------------------- - public void OnSubscriptionUpdated(SubscriptionUpdatedEventArgs e) + protected void grdServices_ItemCommand(object source, DataGridCommandEventArgs e) { - if (IsUserOrAdmin == false) + string commandName = e.CommandName; + int roleID = Convert.ToInt32(e.CommandArgument); + if (commandName == Localization.GetString("Subscribe", this.LocalResourceFile) || commandName == Localization.GetString("Renew", this.LocalResourceFile)) { - return; + // Subscribe + this.Subscribe(roleID, false); } - if (SubscriptionUpdated != null) + else if (commandName == Localization.GetString("Unsubscribe", this.LocalResourceFile)) { - SubscriptionUpdated(this, e); + // Unsubscribe + this.Subscribe(roleID, true); + } + else if (commandName == "UseTrial") + { + // Use Trial + this.UseTrial(roleID); } - } - - #endregion - - #region "Event Handlers" - - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - cmdRSVP.Click += cmdRSVP_Click; - grdServices.ItemCommand += grdServices_ItemCommand; - lblRSVP.Text = ""; - } + // Rebind Grid + this.DataBind(); + } /// ----------------------------------------------------------------------------- /// - /// cmdRSVP_Click runs when the Subscribe to RSVP Code Roles Button is clicked + /// cmdRSVP_Click runs when the Subscribe to RSVP Code Roles Button is clicked. /// /// /// /// ----------------------------------------------------------------------------- private void cmdRSVP_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - //Get the RSVP code - string code = txtRSVPCode.Text; + + // Get the RSVP code + string code = this.txtRSVPCode.Text; bool rsvpCodeExists = false; - if (!String.IsNullOrEmpty(code)) + if (!string.IsNullOrEmpty(code)) { - //Parse the roles - foreach (RoleInfo objRole in RoleController.Instance.GetRoles(PortalSettings.PortalId)) + // Parse the roles + foreach (RoleInfo objRole in RoleController.Instance.GetRoles(this.PortalSettings.PortalId)) { if (objRole.RSVPCode == code) { - RoleController.Instance.UpdateUserRole(PortalId, UserInfo.UserID, objRole.RoleID, RoleStatus.Approved, false, false); + RoleController.Instance.UpdateUserRole(this.PortalId, this.UserInfo.UserID, objRole.RoleID, RoleStatus.Approved, false, false); rsvpCodeExists = true; - //Raise SubscriptionUpdated Event - OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName)); + // Raise SubscriptionUpdated Event + this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName)); } } + if (rsvpCodeExists) { - lblRSVP.Text = Localization.GetString("RSVPSuccess", LocalResourceFile); - //Reset RSVP Code field - txtRSVPCode.Text = ""; + this.lblRSVP.Text = Localization.GetString("RSVPSuccess", this.LocalResourceFile); + + // Reset RSVP Code field + this.txtRSVPCode.Text = string.Empty; } else { - lblRSVP.Text = Localization.GetString("RSVPFailure", LocalResourceFile); + this.lblRSVP.Text = Localization.GetString("RSVPFailure", this.LocalResourceFile); } } - DataBind(); + + this.DataBind(); } - - protected void grdServices_ItemCommand(object source, DataGridCommandEventArgs e) - { - string commandName = e.CommandName; - int roleID = Convert.ToInt32(e.CommandArgument); - if (commandName == Localization.GetString("Subscribe", LocalResourceFile) || commandName == Localization.GetString("Renew", LocalResourceFile)) - { - //Subscribe - Subscribe(roleID, false); - } - else if (commandName == Localization.GetString("Unsubscribe", LocalResourceFile)) - { - //Unsubscribe - Subscribe(roleID, true); - } - else if (commandName == "UseTrial") - { - //Use Trial - UseTrial(roleID); - } - - //Rebind Grid - DataBind(); - } - - #endregion - - #region Nested type: SubscriptionUpdatedEventArgs - + /// ----------------------------------------------------------------------------- /// /// The SubscriptionUpdatedEventArgs class provides a customised EventArgs class for - /// the SubscriptionUpdated Event + /// the SubscriptionUpdated Event. /// /// ----------------------------------------------------------------------------- public class SubscriptionUpdatedEventArgs - { + { /// ----------------------------------------------------------------------------- - /// - /// Constructs a new SubscriptionUpdatedEventArgs + /// + /// Initializes a new instance of the class. + /// Constructs a new SubscriptionUpdatedEventArgs. /// - /// Whether this is a subscription cancellation + /// Whether this is a subscription cancellation. /// The role name of subscription role. /// ----------------------------------------------------------------------------- public SubscriptionUpdatedEventArgs(bool cancel, string roleName) { - Cancel = cancel; - RoleName = roleName; + this.Cancel = cancel; + this.RoleName = roleName; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether this was a cancelation + /// Gets or sets a value indicating whether gets and sets whether this was a cancelation. /// /// ----------------------------------------------------------------------------- public bool Cancel { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the RoleName that was (un)subscribed to + /// Gets or sets and sets the RoleName that was (un)subscribed to. /// /// ----------------------------------------------------------------------------- public string RoleName { get; set; } - } - - #endregion + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs index 25e70c4ea16..72d616671af 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs @@ -1,28 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Mail; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Services.Localization; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mail; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Modules.Admin.Users @@ -30,22 +26,32 @@ namespace DotNetNuke.Modules.Admin.Users /// ----------------------------------------------------------------------------- /// /// The Membership UserModuleBase is used to manage the membership aspects of a - /// User + /// User. /// /// ----------------------------------------------------------------------------- public partial class Membership : UserModuleBase { private readonly INavigationManager _navigationManager; + public Membership() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region "Public Properties" - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + /// ----------------------------------------------------------------------------- /// - /// Gets the UserMembership associated with this control + /// Raises the MembershipAuthorized Event + /// + /// ----------------------------------------------------------------------------- + public event EventHandler MembershipAuthorized; + + public event EventHandler MembershipPasswordUpdateChanged; + + public event EventHandler MembershipUnAuthorized; + + /// ----------------------------------------------------------------------------- + /// + /// Gets the UserMembership associated with this control. /// /// ----------------------------------------------------------------------------- public UserMembership UserMembership @@ -53,213 +59,199 @@ public UserMembership UserMembership get { UserMembership membership = null; - if (User != null) + if (this.User != null) { - membership = User.Membership; + membership = this.User.Membership; } + return membership; } - } - - #endregion - - #region "Events" - - /// ----------------------------------------------------------------------------- - /// - /// Raises the MembershipAuthorized Event - /// - /// ----------------------------------------------------------------------------- - - - public event EventHandler MembershipAuthorized; - public event EventHandler MembershipPasswordUpdateChanged; - public event EventHandler MembershipUnAuthorized; + } + public event EventHandler MembershipUnLocked; + public event EventHandler MembershipPromoteToSuperuser; - public event EventHandler MembershipDemoteFromSuperuser; - - #endregion - - #region "Event Methods" + + public event EventHandler MembershipDemoteFromSuperuser; + /// ----------------------------------------------------------------------------- /// - /// Raises the MembershipPromoteToSuperuser Event + /// Raises the MembershipPromoteToSuperuser Event. /// /// ----------------------------------------------------------------------------- public void OnMembershipPromoteToSuperuser(EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (MembershipPromoteToSuperuser != null) + + if (this.MembershipPromoteToSuperuser != null) { - MembershipPromoteToSuperuser(this, e); - Response.Redirect(_navigationManager.NavigateURL(), true); + this.MembershipPromoteToSuperuser(this, e); + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } } /// ----------------------------------------------------------------------------- /// - /// Raises the MembershipPromoteToSuperuser Event + /// Raises the MembershipPromoteToSuperuser Event. /// /// ----------------------------------------------------------------------------- public void OnMembershipDemoteFromSuperuser(EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (MembershipDemoteFromSuperuser != null) + + if (this.MembershipDemoteFromSuperuser != null) { - MembershipDemoteFromSuperuser(this, e); - Response.Redirect(_navigationManager.NavigateURL(), true); + this.MembershipDemoteFromSuperuser(this, e); + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } } - - + /// ----------------------------------------------------------------------------- /// - /// Raises the MembershipAuthorized Event + /// Raises the MembershipAuthorized Event. /// /// ----------------------------------------------------------------------------- public void OnMembershipAuthorized(EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (MembershipAuthorized != null) + + if (this.MembershipAuthorized != null) { - MembershipAuthorized(this, e); + this.MembershipAuthorized(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the MembershipPasswordUpdateChanged Event + /// Raises the MembershipPasswordUpdateChanged Event. /// /// ----------------------------------------------------------------------------- public void OnMembershipPasswordUpdateChanged(EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (MembershipPasswordUpdateChanged != null) + + if (this.MembershipPasswordUpdateChanged != null) { - MembershipPasswordUpdateChanged(this, e); + this.MembershipPasswordUpdateChanged(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the MembershipUnAuthorized Event + /// Raises the MembershipUnAuthorized Event. /// /// ----------------------------------------------------------------------------- public void OnMembershipUnAuthorized(EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (MembershipUnAuthorized != null) + + if (this.MembershipUnAuthorized != null) { - MembershipUnAuthorized(this, e); + this.MembershipUnAuthorized(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the MembershipUnLocked Event + /// Raises the MembershipUnLocked Event. /// /// ----------------------------------------------------------------------------- public void OnMembershipUnLocked(EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (MembershipUnLocked != null) + + if (this.MembershipUnLocked != null) { - MembershipUnLocked(this, e); + this.MembershipUnLocked(this, e); } - } - - #endregion - - #region "Public Methods" - + } + /// ----------------------------------------------------------------------------- /// - /// DataBind binds the data to the controls + /// DataBind binds the data to the controls. /// /// ----------------------------------------------------------------------------- public override void DataBind() { - //disable/enable buttons - if (UserInfo.UserID == User.UserID) + // disable/enable buttons + if (this.UserInfo.UserID == this.User.UserID) { - cmdAuthorize.Visible = false; - cmdUnAuthorize.Visible = false; - cmdUnLock.Visible = false; - cmdPassword.Visible = false; + this.cmdAuthorize.Visible = false; + this.cmdUnAuthorize.Visible = false; + this.cmdUnLock.Visible = false; + this.cmdPassword.Visible = false; } else { - cmdUnLock.Visible = UserMembership.LockedOut; - cmdUnAuthorize.Visible = UserMembership.Approved && !User.IsInRole("Unverified Users"); - cmdAuthorize.Visible = !UserMembership.Approved || User.IsInRole("Unverified Users"); - cmdPassword.Visible = !UserMembership.UpdatePassword; + this.cmdUnLock.Visible = this.UserMembership.LockedOut; + this.cmdUnAuthorize.Visible = this.UserMembership.Approved && !this.User.IsInRole("Unverified Users"); + this.cmdAuthorize.Visible = !this.UserMembership.Approved || this.User.IsInRole("Unverified Users"); + this.cmdPassword.Visible = !this.UserMembership.UpdatePassword; } - if (UserController.Instance.GetCurrentUserInfo().IsSuperUser && UserController.Instance.GetCurrentUserInfo().UserID!=User.UserID) + + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser && UserController.Instance.GetCurrentUserInfo().UserID != this.User.UserID) { - cmdToggleSuperuser.Visible = true; + this.cmdToggleSuperuser.Visible = true; - if (User.IsSuperUser) + if (this.User.IsSuperUser) { - cmdToggleSuperuser.Text = Localization.GetString("DemoteFromSuperUser", LocalResourceFile); + this.cmdToggleSuperuser.Text = Localization.GetString("DemoteFromSuperUser", this.LocalResourceFile); } else { - cmdToggleSuperuser.Text = Localization.GetString("PromoteToSuperUser", LocalResourceFile); + this.cmdToggleSuperuser.Text = Localization.GetString("PromoteToSuperUser", this.LocalResourceFile); } - if (PortalController.GetPortalsByUser(User.UserID).Count == 0) + + if (PortalController.GetPortalsByUser(this.User.UserID).Count == 0) { - cmdToggleSuperuser.Visible = false; + this.cmdToggleSuperuser.Visible = false; } } - lastLockoutDate.Value = UserMembership.LastLockoutDate.Year > 2000 - ? (object) UserMembership.LastLockoutDate - : LocalizeString("Never"); + + this.lastLockoutDate.Value = this.UserMembership.LastLockoutDate.Year > 2000 + ? (object)this.UserMembership.LastLockoutDate + : this.LocalizeString("Never"); + // ReSharper disable SpecifyACultureInStringConversionExplicitly - isOnLine.Value = LocalizeString(UserMembership.IsOnLine.ToString()); - lockedOut.Value = LocalizeString(UserMembership.LockedOut.ToString()); - approved.Value = LocalizeString(UserMembership.Approved.ToString()); - updatePassword.Value = LocalizeString(UserMembership.UpdatePassword.ToString()); - isDeleted.Value = LocalizeString(UserMembership.IsDeleted.ToString()); - - //show the user folder path without default parent folder, and only visible to admin. - userFolder.Visible = UserInfo.IsInRole(PortalSettings.AdministratorRoleName); - if (userFolder.Visible) + this.isOnLine.Value = this.LocalizeString(this.UserMembership.IsOnLine.ToString()); + this.lockedOut.Value = this.LocalizeString(this.UserMembership.LockedOut.ToString()); + this.approved.Value = this.LocalizeString(this.UserMembership.Approved.ToString()); + this.updatePassword.Value = this.LocalizeString(this.UserMembership.UpdatePassword.ToString()); + this.isDeleted.Value = this.LocalizeString(this.UserMembership.IsDeleted.ToString()); + + // show the user folder path without default parent folder, and only visible to admin. + this.userFolder.Visible = this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName); + if (this.userFolder.Visible) { - userFolder.Value = FolderManager.Instance.GetUserFolder(User).FolderPath.Substring(6); + this.userFolder.Value = FolderManager.Instance.GetUserFolder(this.User).FolderPath.Substring(6); } // ReSharper restore SpecifyACultureInStringConversionExplicitly - - membershipForm.DataSource = UserMembership; - membershipForm.DataBind(); - } - - #endregion - - #region "Event Handlers" - + this.membershipForm.DataSource = this.UserMembership; + this.membershipForm.DataBind(); + } + /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -268,159 +260,180 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdAuthorize.Click += cmdAuthorize_Click; - cmdPassword.Click += cmdPassword_Click; - cmdUnAuthorize.Click += cmdUnAuthorize_Click; - cmdUnLock.Click += cmdUnLock_Click; - cmdToggleSuperuser.Click+=cmdToggleSuperuser_Click; + this.cmdAuthorize.Click += this.cmdAuthorize_Click; + this.cmdPassword.Click += this.cmdPassword_Click; + this.cmdUnAuthorize.Click += this.cmdUnAuthorize_Click; + this.cmdUnLock.Click += this.cmdUnLock_Click; + this.cmdToggleSuperuser.Click += this.cmdToggleSuperuser_Click; } - - + /// ----------------------------------------------------------------------------- /// - /// cmdAuthorize_Click runs when the Authorize User Button is clicked + /// cmdAuthorize_Click runs when the Authorize User Button is clicked. /// /// ----------------------------------------------------------------------------- private void cmdAuthorize_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (Request.IsAuthenticated != true) return; - - //Get the Membership Information from the property editors - User.Membership = (UserMembership)membershipForm.DataSource; - - User.Membership.Approved = true; - - //Update User - UserController.UpdateUser(PortalId, User); - - //Update User Roles if needed - if (!User.IsSuperUser && User.IsInRole("Unverified Users") && PortalSettings.UserRegistration == (int)Common.Globals.PortalRegistrationType.VerifiedRegistration) + + if (this.Request.IsAuthenticated != true) + { + return; + } + + // Get the Membership Information from the property editors + this.User.Membership = (UserMembership)this.membershipForm.DataSource; + + this.User.Membership.Approved = true; + + // Update User + UserController.UpdateUser(this.PortalId, this.User); + + // Update User Roles if needed + if (!this.User.IsSuperUser && this.User.IsInRole("Unverified Users") && this.PortalSettings.UserRegistration == (int)Common.Globals.PortalRegistrationType.VerifiedRegistration) { - UserController.ApproveUser(User); + UserController.ApproveUser(this.User); } - Mail.SendMail(User, MessageType.UserAuthorized, PortalSettings); + Mail.SendMail(this.User, MessageType.UserAuthorized, this.PortalSettings); - OnMembershipAuthorized(EventArgs.Empty); + this.OnMembershipAuthorized(EventArgs.Empty); } /// ----------------------------------------------------------------------------- /// - /// cmdPassword_Click runs when the ChangePassword Button is clicked + /// cmdPassword_Click runs when the ChangePassword Button is clicked. /// /// ----------------------------------------------------------------------------- private void cmdPassword_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (Request.IsAuthenticated != true) return; - - bool canSend = Mail.SendMail(User, MessageType.PasswordReminder, PortalSettings) == string.Empty; - var message = String.Empty; + + if (this.Request.IsAuthenticated != true) + { + return; + } + + bool canSend = Mail.SendMail(this.User, MessageType.PasswordReminder, this.PortalSettings) == string.Empty; + var message = string.Empty; if (canSend) { - //Get the Membership Information from the property editors - User.Membership = (UserMembership)membershipForm.DataSource; + // Get the Membership Information from the property editors + this.User.Membership = (UserMembership)this.membershipForm.DataSource; - User.Membership.UpdatePassword = true; + this.User.Membership.UpdatePassword = true; - //Update User - UserController.UpdateUser(PortalId, User); + // Update User + UserController.UpdateUser(this.PortalId, this.User); - OnMembershipPasswordUpdateChanged(EventArgs.Empty); + this.OnMembershipPasswordUpdateChanged(EventArgs.Empty); } else { - message = Localization.GetString("OptionUnavailable", LocalResourceFile); + message = Localization.GetString("OptionUnavailable", this.LocalResourceFile); UI.Skins.Skin.AddModuleMessage(this, message, ModuleMessage.ModuleMessageType.YellowWarning); } - } /// ----------------------------------------------------------------------------- /// - /// cmdUnAuthorize_Click runs when the UnAuthorize User Button is clicked + /// cmdUnAuthorize_Click runs when the UnAuthorize User Button is clicked. /// /// ----------------------------------------------------------------------------- private void cmdUnAuthorize_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (Request.IsAuthenticated != true) return; - - //Get the Membership Information from the property editors - User.Membership = (UserMembership)membershipForm.DataSource; + + if (this.Request.IsAuthenticated != true) + { + return; + } + + // Get the Membership Information from the property editors + this.User.Membership = (UserMembership)this.membershipForm.DataSource; - User.Membership.Approved = false; + this.User.Membership.Approved = false; - //Update User - UserController.UpdateUser(PortalId, User); + // Update User + UserController.UpdateUser(this.PortalId, this.User); - OnMembershipUnAuthorized(EventArgs.Empty); + this.OnMembershipUnAuthorized(EventArgs.Empty); } + /// - /// cmdToggleSuperuser_Click runs when the toggle superuser button is clicked + /// cmdToggleSuperuser_Click runs when the toggle superuser button is clicked. /// /// /// private void cmdToggleSuperuser_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (Request.IsAuthenticated != true) return; - ////ensure only superusers can change user superuser state - if (UserController.Instance.GetCurrentUserInfo().IsSuperUser != true) return; - - var currentSuperUserState = User.IsSuperUser; - User.IsSuperUser = !currentSuperUserState; - //Update User - UserController.UpdateUser(PortalId, User); + + if (this.Request.IsAuthenticated != true) + { + return; + } + ////ensure only superusers can change user superuser state + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser != true) + { + return; + } + + var currentSuperUserState = this.User.IsSuperUser; + this.User.IsSuperUser = !currentSuperUserState; + + // Update User + UserController.UpdateUser(this.PortalId, this.User); DataCache.ClearCache(); if (currentSuperUserState) { - OnMembershipDemoteFromSuperuser(EventArgs.Empty); + this.OnMembershipDemoteFromSuperuser(EventArgs.Empty); } else { - OnMembershipPromoteToSuperuser(EventArgs.Empty); + this.OnMembershipPromoteToSuperuser(EventArgs.Empty); } - } + /// ----------------------------------------------------------------------------- /// - /// cmdUnlock_Click runs when the Unlock Account Button is clicked + /// cmdUnlock_Click runs when the Unlock Account Button is clicked. /// /// ----------------------------------------------------------------------------- - private void cmdUnLock_Click(Object sender, EventArgs e) + private void cmdUnLock_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (Request.IsAuthenticated != true) return; - - //update the user record in the database - bool isUnLocked = UserController.UnLockUser(User); + + if (this.Request.IsAuthenticated != true) + { + return; + } + + // update the user record in the database + bool isUnLocked = UserController.UnLockUser(this.User); if (isUnLocked) { - User.Membership.LockedOut = false; + this.User.Membership.LockedOut = false; - OnMembershipUnLocked(EventArgs.Empty); + this.OnMembershipUnLocked(EventArgs.Empty); } - } - - #endregion + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs index 6ca9b565acf..ae0bcfb18ab 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs @@ -1,375 +1,352 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Threading; -using System.Web.Security; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Membership; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Mail; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Threading; + using System.Web.Security; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Membership; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Mail; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls; + using Host = DotNetNuke.Entities.Host.Host; /// ----------------------------------------------------------------------------- /// - /// The Password UserModuleBase is used to manage Users Passwords + /// The Password UserModuleBase is used to manage Users Passwords. /// /// /// public partial class Password : UserModuleBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Password)); - protected bool UseCaptcha - { - get - { - return Convert.ToBoolean(GetSetting(PortalId, "Security_CaptchaChangePassword")); - } - } - #region Delegates + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Password)); public delegate void PasswordUpdatedEventHandler(object sender, PasswordUpdatedEventArgs e); - #endregion - - #region Public Properties + public event PasswordUpdatedEventHandler PasswordUpdated; + + public event PasswordUpdatedEventHandler PasswordQuestionAnswerUpdated; /// ----------------------------------------------------------------------------- /// - /// Gets the UserMembership associated with this control + /// Gets the UserMembership associated with this control. /// public UserMembership Membership { get { UserMembership _Membership = null; - if (User != null) + if (this.User != null) { - _Membership = User.Membership; + _Membership = this.User.Membership; } + return _Membership; } } - - #endregion - - #region Events - - - public event PasswordUpdatedEventHandler PasswordUpdated; - public event PasswordUpdatedEventHandler PasswordQuestionAnswerUpdated; - - #endregion - - #region Event Methods + protected bool UseCaptcha + { + get + { + return Convert.ToBoolean(GetSetting(this.PortalId, "Security_CaptchaChangePassword")); + } + } /// ----------------------------------------------------------------------------- /// - /// Raises the PasswordUpdated Event + /// Raises the PasswordUpdated Event. /// public void OnPasswordUpdated(PasswordUpdatedEventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (PasswordUpdated != null) + + if (this.PasswordUpdated != null) { - PasswordUpdated(this, e); + this.PasswordUpdated(this, e); } } /// ----------------------------------------------------------------------------- /// - /// Raises the PasswordQuestionAnswerUpdated Event + /// Raises the PasswordQuestionAnswerUpdated Event. /// public void OnPasswordQuestionAnswerUpdated(PasswordUpdatedEventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (PasswordQuestionAnswerUpdated != null) + + if (this.PasswordQuestionAnswerUpdated != null) { - PasswordQuestionAnswerUpdated(this, e); + this.PasswordQuestionAnswerUpdated(this, e); } } - #endregion - - #region Public Methods - /// ----------------------------------------------------------------------------- /// - /// DataBind binds the data to the controls + /// DataBind binds the data to the controls. /// public override void DataBind() { - lblLastChanged.Text = User.Membership.LastPasswordChangeDate.ToLongDateString(); + this.lblLastChanged.Text = this.User.Membership.LastPasswordChangeDate.ToLongDateString(); - //Set Password Expiry Label - if (User.Membership.UpdatePassword) + // Set Password Expiry Label + if (this.User.Membership.UpdatePassword) { - lblExpires.Text = Localization.GetString("ForcedExpiry", LocalResourceFile); + this.lblExpires.Text = Localization.GetString("ForcedExpiry", this.LocalResourceFile); } else { - lblExpires.Text = PasswordConfig.PasswordExpiry > 0 ? User.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry).ToLongDateString() : Localization.GetString("NoExpiry", LocalResourceFile); + this.lblExpires.Text = PasswordConfig.PasswordExpiry > 0 ? this.User.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry).ToLongDateString() : Localization.GetString("NoExpiry", this.LocalResourceFile); } - - if (((!MembershipProviderConfig.PasswordRetrievalEnabled) && IsAdmin && (!IsUser))) + + if ((!MembershipProviderConfig.PasswordRetrievalEnabled) && this.IsAdmin && (!this.IsUser)) { - pnlChange.Visible = true; - cmdUpdate.Visible = true; - oldPasswordRow.Visible = false; - lblChangeHelp.Text = Localization.GetString("AdminChangeHelp", LocalResourceFile); + this.pnlChange.Visible = true; + this.cmdUpdate.Visible = true; + this.oldPasswordRow.Visible = false; + this.lblChangeHelp.Text = Localization.GetString("AdminChangeHelp", this.LocalResourceFile); } else { - pnlChange.Visible = true; - cmdUpdate.Visible = true; - - //Set up Change Password - if (IsAdmin && !IsUser) + this.pnlChange.Visible = true; + this.cmdUpdate.Visible = true; + + // Set up Change Password + if (this.IsAdmin && !this.IsUser) { - lblChangeHelp.Text = Localization.GetString("AdminChangeHelp", LocalResourceFile); - oldPasswordRow.Visible = false; + this.lblChangeHelp.Text = Localization.GetString("AdminChangeHelp", this.LocalResourceFile); + this.oldPasswordRow.Visible = false; } else { - lblChangeHelp.Text = Localization.GetString("UserChangeHelp", LocalResourceFile); - if (Request.IsAuthenticated) + this.lblChangeHelp.Text = Localization.GetString("UserChangeHelp", this.LocalResourceFile); + if (this.Request.IsAuthenticated) { - pnlChange.Visible = true; - cmdUserReset.Visible = false; - cmdUpdate.Visible = true; + this.pnlChange.Visible = true; + this.cmdUserReset.Visible = false; + this.cmdUpdate.Visible = true; } else { - pnlChange.Visible = false; - cmdUserReset.Visible = true; - cmdUpdate.Visible = false; + this.pnlChange.Visible = false; + this.cmdUserReset.Visible = true; + this.cmdUpdate.Visible = false; } } } - - //If Password Reset is not enabled then only the Admin can reset the - //Password, a User must Update + + // If Password Reset is not enabled then only the Admin can reset the + // Password, a User must Update if (!MembershipProviderConfig.PasswordResetEnabled) { - pnlReset.Visible = false; - cmdReset.Visible = false; + this.pnlReset.Visible = false; + this.cmdReset.Visible = false; } else { - pnlReset.Visible = true; - cmdReset.Visible = true; - - //Set up Reset Password - if (IsAdmin && !IsUser) + this.pnlReset.Visible = true; + this.cmdReset.Visible = true; + + // Set up Reset Password + if (this.IsAdmin && !this.IsUser) { if (MembershipProviderConfig.RequiresQuestionAndAnswer) { - pnlReset.Visible = false; - cmdReset.Visible = false; + this.pnlReset.Visible = false; + this.cmdReset.Visible = false; } else { - lblResetHelp.Text = Localization.GetString("AdminResetHelp", LocalResourceFile); + this.lblResetHelp.Text = Localization.GetString("AdminResetHelp", this.LocalResourceFile); } - questionRow.Visible = false; - answerRow.Visible = false; + + this.questionRow.Visible = false; + this.answerRow.Visible = false; } else { - if (MembershipProviderConfig.RequiresQuestionAndAnswer && IsUser) + if (MembershipProviderConfig.RequiresQuestionAndAnswer && this.IsUser) { - lblResetHelp.Text = Localization.GetString("UserResetHelp", LocalResourceFile); - lblQuestion.Text = User.Membership.PasswordQuestion; - questionRow.Visible = true; - answerRow.Visible = true; + this.lblResetHelp.Text = Localization.GetString("UserResetHelp", this.LocalResourceFile); + this.lblQuestion.Text = this.User.Membership.PasswordQuestion; + this.questionRow.Visible = true; + this.answerRow.Visible = true; } else { - pnlReset.Visible = false; - cmdReset.Visible = false; + this.pnlReset.Visible = false; + this.cmdReset.Visible = false; } } } - - //Set up Edit Question and Answer area - if (MembershipProviderConfig.RequiresQuestionAndAnswer && IsUser) + + // Set up Edit Question and Answer area + if (MembershipProviderConfig.RequiresQuestionAndAnswer && this.IsUser) { - pnlQA.Visible = true; - cmdUpdateQA.Visible = true; + this.pnlQA.Visible = true; + this.cmdUpdateQA.Visible = true; } else { - pnlQA.Visible = false; - cmdUpdateQA.Visible = false; + this.pnlQA.Visible = false; + this.cmdUpdateQA.Visible = false; } } - #endregion - - #region Event Handlers - protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdReset.Click += cmdReset_Click; - cmdUserReset.Click += cmdUserReset_Click; - cmdUpdate.Click += cmdUpdate_Click; - cmdUpdateQA.Click += cmdUpdateQA_Click; + this.cmdReset.Click += this.cmdReset_Click; + this.cmdUserReset.Click += this.cmdUserReset_Click; + this.cmdUpdate.Click += this.cmdUpdate_Click; + this.cmdUpdateQA.Click += this.cmdUpdateQA_Click; - if (MembershipProviderConfig.RequiresQuestionAndAnswer && User.UserID != UserController.Instance.GetCurrentUserInfo().UserID) - { - pnlChange.Visible = false; - cmdUpdate.Visible = false; - CannotChangePasswordMessage.Visible = true; - } + if (MembershipProviderConfig.RequiresQuestionAndAnswer && this.User.UserID != UserController.Instance.GetCurrentUserInfo().UserID) + { + this.pnlChange.Visible = false; + this.cmdUpdate.Visible = false; + this.CannotChangePasswordMessage.Visible = true; + } - if (UseCaptcha) + if (this.UseCaptcha) { - captchaRow.Visible = true; - ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", LocalResourceFile); - ctlCaptcha.Text = Localization.GetString("CaptchaText", LocalResourceFile); + this.captchaRow.Visible = true; + this.ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", this.LocalResourceFile); + this.ctlCaptcha.Text = Localization.GetString("CaptchaText", this.LocalResourceFile); } - } - protected override void OnPreRender(EventArgs e) { - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); base.OnPreRender(e); - if (Host.EnableStrengthMeter) - { - passwordContainer.CssClass = "password-strength-container"; - txtNewPassword.CssClass = "password-strength"; - - var options = new DnnPaswordStrengthOptions(); - var optionsAsJsonString = Json.Serialize(options); - var script = string.Format("dnn.initializePasswordStrength('.{0}', {1});{2}", "password-strength", optionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "PasswordStrength", script, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "PasswordStrength", script, true); - } - } - - var confirmPasswordOptions = new DnnConfirmPasswordOptions() - { - FirstElementSelector = "#" + passwordContainer.ClientID + " input[type=password]", - SecondElementSelector = ".password-confirm", - ContainerSelector = ".dnnPassword", - UnmatchedCssClass = "unmatched", - MatchedCssClass = "matched" - }; - - var confirmOptionsAsJsonString = Json.Serialize(confirmPasswordOptions); - var confirmScript = string.Format("dnn.initializePasswordComparer({0});{1}", confirmOptionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "ConfirmPassword", confirmScript, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "ConfirmPassword", confirmScript, true); - } - } + if (Host.EnableStrengthMeter) + { + this.passwordContainer.CssClass = "password-strength-container"; + this.txtNewPassword.CssClass = "password-strength"; + var options = new DnnPaswordStrengthOptions(); + var optionsAsJsonString = Json.Serialize(options); + var script = string.Format("dnn.initializePasswordStrength('.{0}', {1});{2}", "password-strength", optionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "PasswordStrength", script, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PasswordStrength", script, true); + } + } + + var confirmPasswordOptions = new DnnConfirmPasswordOptions() + { + FirstElementSelector = "#" + this.passwordContainer.ClientID + " input[type=password]", + SecondElementSelector = ".password-confirm", + ContainerSelector = ".dnnPassword", + UnmatchedCssClass = "unmatched", + MatchedCssClass = "matched", + }; + + var confirmOptionsAsJsonString = Json.Serialize(confirmPasswordOptions); + var confirmScript = string.Format("dnn.initializePasswordComparer({0});{1}", confirmOptionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ConfirmPassword", confirmScript, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmPassword", confirmScript, true); + } + } private void cmdReset_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - string answer = ""; - if (MembershipProviderConfig.RequiresQuestionAndAnswer && !IsAdmin) + + string answer = string.Empty; + if (MembershipProviderConfig.RequiresQuestionAndAnswer && !this.IsAdmin) { - if (String.IsNullOrEmpty(txtAnswer.Text)) + if (string.IsNullOrEmpty(this.txtAnswer.Text)) { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); return; } - answer = txtAnswer.Text; + + answer = this.txtAnswer.Text; } + try { - //create resettoken - UserController.ResetPasswordToken(User, Entities.Host.Host.AdminMembershipResetLinkValidity); + // create resettoken + UserController.ResetPasswordToken(this.User, Entities.Host.Host.AdminMembershipResetLinkValidity); - bool canSend = Mail.SendMail(User, MessageType.PasswordReminder, PortalSettings) == string.Empty; - var message = String.Empty; + bool canSend = Mail.SendMail(this.User, MessageType.PasswordReminder, this.PortalSettings) == string.Empty; + var message = string.Empty; var moduleMessageType = ModuleMessage.ModuleMessageType.GreenSuccess; if (canSend) { - message = Localization.GetString("PasswordSent", LocalResourceFile); - LogSuccess(); + message = Localization.GetString("PasswordSent", this.LocalResourceFile); + this.LogSuccess(); } else { - message = Localization.GetString("OptionUnavailable", LocalResourceFile); - moduleMessageType=ModuleMessage.ModuleMessageType.RedError; - LogFailure(message); + message = Localization.GetString("OptionUnavailable", this.LocalResourceFile); + moduleMessageType = ModuleMessage.ModuleMessageType.RedError; + this.LogFailure(message); } - UI.Skins.Skin.AddModuleMessage(this, message, moduleMessageType); } catch (ArgumentException exc) { Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); } catch (Exception exc) { Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } } @@ -377,46 +354,45 @@ private void cmdUserReset_Click(object sender, EventArgs e) { try { - //send fresh resettoken copy - bool canSend = UserController.ResetPasswordToken(User,true); + // send fresh resettoken copy + bool canSend = UserController.ResetPasswordToken(this.User, true); - var message = String.Empty; + var message = string.Empty; var moduleMessageType = ModuleMessage.ModuleMessageType.GreenSuccess; if (canSend) { - message = Localization.GetString("PasswordSent", LocalResourceFile); - LogSuccess(); + message = Localization.GetString("PasswordSent", this.LocalResourceFile); + this.LogSuccess(); } else { - message = Localization.GetString("OptionUnavailable", LocalResourceFile); + message = Localization.GetString("OptionUnavailable", this.LocalResourceFile); moduleMessageType = ModuleMessage.ModuleMessageType.RedError; - LogFailure(message); + this.LogFailure(message); } - UI.Skins.Skin.AddModuleMessage(this, message, moduleMessageType); } catch (ArgumentException exc) { Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); } catch (Exception exc) { Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } } private void LogSuccess() { - LogResult(string.Empty); + this.LogResult(string.Empty); } private void LogFailure(string reason) { - LogResult(reason); + this.LogResult(reason); } private void LogResult(string message) @@ -425,10 +401,10 @@ private void LogResult(string message) var log = new LogInfo { - LogPortalID = PortalSettings.PortalId, - LogPortalName = PortalSettings.PortalName, - LogUserID = UserId, - LogUserName = portalSecurity.InputFilter(User.Username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup) + LogPortalID = this.PortalSettings.PortalId, + LogPortalName = this.PortalSettings.PortalName, + LogUserID = this.UserId, + LogUserName = portalSecurity.InputFilter(this.User.Username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup), }; if (string.IsNullOrEmpty(message)) @@ -444,120 +420,121 @@ private void LogResult(string message) LogController.Instance.AddLog(log); } - private void cmdUpdate_Click(Object sender, EventArgs e) + private void cmdUpdate_Click(object sender, EventArgs e) { - if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha) + if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || !this.UseCaptcha) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - //1. Check New Password and Confirm are the same - if (txtNewPassword.Text != txtNewConfirm.Text) + + // 1. Check New Password and Confirm are the same + if (this.txtNewPassword.Text != this.txtNewConfirm.Text) { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordMismatch)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordMismatch)); return; } - //2. Check New Password is Valid - if (!UserController.ValidatePassword(txtNewPassword.Text)) + // 2. Check New Password is Valid + if (!UserController.ValidatePassword(this.txtNewPassword.Text)) { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordInvalid)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordInvalid)); return; } - //3. Check old Password is Provided - if (!IsAdmin && String.IsNullOrEmpty(txtOldPassword.Text)) + // 3. Check old Password is Provided + if (!this.IsAdmin && string.IsNullOrEmpty(this.txtOldPassword.Text)) { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordMissing)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordMissing)); return; } - //4. Check New Password is ddifferent - if (!IsAdmin && txtNewPassword.Text == txtOldPassword.Text) + // 4. Check New Password is ddifferent + if (!this.IsAdmin && this.txtNewPassword.Text == this.txtOldPassword.Text) { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordNotDifferent)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordNotDifferent)); return; } - //5. Check New Password is not same as username or banned - var membershipPasswordController = new MembershipPasswordController(); - var settings = new MembershipPasswordSettings(User.PortalID); + + // 5. Check New Password is not same as username or banned + var membershipPasswordController = new MembershipPasswordController(); + var settings = new MembershipPasswordSettings(this.User.PortalID); if (settings.EnableBannedList) { - if (membershipPasswordController.FoundBannedPassword(txtNewPassword.Text) || User.Username == txtNewPassword.Text) + if (membershipPasswordController.FoundBannedPassword(this.txtNewPassword.Text) || this.User.Username == this.txtNewPassword.Text) { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.BannedPasswordUsed)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.BannedPasswordUsed)); return; } - } - //check new password is not in history - if (membershipPasswordController.IsPasswordInHistory(User.UserID, User.PortalID, txtNewPassword.Text, false)) - { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); - return; - } + // check new password is not in history + if (membershipPasswordController.IsPasswordInHistory(this.User.UserID, this.User.PortalID, this.txtNewPassword.Text, false)) + { + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); + return; + } - if (!IsAdmin && txtNewPassword.Text == txtOldPassword.Text) + if (!this.IsAdmin && this.txtNewPassword.Text == this.txtOldPassword.Text) { - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordNotDifferent)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordNotDifferent)); return; } - if (!IsAdmin) + if (!this.IsAdmin) { try { - OnPasswordUpdated(UserController.ChangePassword(User, txtOldPassword.Text, txtNewPassword.Text) + this.OnPasswordUpdated(UserController.ChangePassword(this.User, this.txtOldPassword.Text, this.txtNewPassword.Text) ? new PasswordUpdatedEventArgs(PasswordUpdateStatus.Success) : new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } catch (MembershipPasswordException exc) { - //Password Answer missing + // Password Answer missing Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); } catch (ThreadAbortException) { - //Do nothing we are not logging ThreadAbortxceptions caused by redirects + // Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception exc) { - //Fail + // Fail Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } } else { try { - OnPasswordUpdated(UserController.ResetAndChangePassword(User, txtNewPassword.Text) + this.OnPasswordUpdated(UserController.ResetAndChangePassword(this.User, this.txtNewPassword.Text) ? new PasswordUpdatedEventArgs(PasswordUpdateStatus.Success) : new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } catch (MembershipPasswordException exc) { - //Password Answer missing + // Password Answer missing Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); } catch (ThreadAbortException) { - //Do nothing we are not logging ThreadAbortxceptions caused by redirects + // Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception exc) { - //Fail + // Fail Logger.Error(exc); - OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); + this.OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } } } @@ -565,67 +542,65 @@ private void cmdUpdate_Click(Object sender, EventArgs e) /// ----------------------------------------------------------------------------- /// - /// cmdUpdate_Click runs when the Update Question and Answer Button is clicked + /// cmdUpdate_Click runs when the Update Question and Answer Button is clicked. /// /// /// private void cmdUpdateQA_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (String.IsNullOrEmpty(txtQAPassword.Text)) + + if (string.IsNullOrEmpty(this.txtQAPassword.Text)) { - OnPasswordQuestionAnswerUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordInvalid)); + this.OnPasswordQuestionAnswerUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordInvalid)); return; } - if (String.IsNullOrEmpty(txtEditQuestion.Text)) + + if (string.IsNullOrEmpty(this.txtEditQuestion.Text)) { - OnPasswordQuestionAnswerUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordQuestion)); + this.OnPasswordQuestionAnswerUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordQuestion)); return; } - if (String.IsNullOrEmpty(txtEditAnswer.Text)) + + if (string.IsNullOrEmpty(this.txtEditAnswer.Text)) { - OnPasswordQuestionAnswerUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); + this.OnPasswordQuestionAnswerUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); return; } - - //Try and set password Q and A - UserInfo objUser = UserController.GetUserById(PortalId, UserId); - OnPasswordQuestionAnswerUpdated(UserController.ChangePasswordQuestionAndAnswer(objUser, txtQAPassword.Text, txtEditQuestion.Text, txtEditAnswer.Text) + + // Try and set password Q and A + UserInfo objUser = UserController.GetUserById(this.PortalId, this.UserId); + this.OnPasswordQuestionAnswerUpdated(UserController.ChangePasswordQuestionAndAnswer(objUser, this.txtQAPassword.Text, this.txtEditQuestion.Text, this.txtEditAnswer.Text) ? new PasswordUpdatedEventArgs(PasswordUpdateStatus.Success) : new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } - - #endregion - - #region Nested type: PasswordUpdatedEventArgs /// ----------------------------------------------------------------------------- /// /// The PasswordUpdatedEventArgs class provides a customised EventArgs class for - /// the PasswordUpdated Event + /// the PasswordUpdated Event. /// public class PasswordUpdatedEventArgs { /// ----------------------------------------------------------------------------- /// - /// Constructs a new PasswordUpdatedEventArgs + /// Initializes a new instance of the class. + /// Constructs a new PasswordUpdatedEventArgs. /// - /// The Password Update Status + /// The Password Update Status. public PasswordUpdatedEventArgs(PasswordUpdateStatus status) { - UpdateStatus = status; + this.UpdateStatus = status; } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the Update Status + /// Gets or sets and sets the Update Status. /// public PasswordUpdateStatus UpdateStatus { get; set; } } - - #endregion } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs index b91404b2f1c..5266992810a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs @@ -1,105 +1,98 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.UI.WebControls; -using DotNetNuke.UI.Skins.Controls; -using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DesktopModules.Admin.Security { + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.WebControls; + + using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; + /// ----------------------------------------------------------------------------- /// - /// The Profile UserModuleBase is used to register Users + /// The Profile UserModuleBase is used to register Users. /// /// /// /// ----------------------------------------------------------------------------- public partial class DNNProfile : ProfileUserControlBase - { - #region Protected Properties - + { /// ----------------------------------------------------------------------------- /// - /// Gets whether to display the Visibility controls + /// Gets or sets and sets the EditorMode. /// /// ----------------------------------------------------------------------------- - protected bool ShowVisibility + public PropertyEditorMode EditorMode { get { - object setting = GetSetting(PortalId, "Profile_DisplayVisibility"); - return Convert.ToBoolean(setting) && IsUser; + return this.ProfileProperties.EditMode; + } + + set + { + this.ProfileProperties.EditMode = value; } } - #endregion - - #region Public Properties - /// ----------------------------------------------------------------------------- /// - /// Gets and sets the EditorMode + /// Gets a value indicating whether gets whether the User is valid. /// /// ----------------------------------------------------------------------------- - public PropertyEditorMode EditorMode + public bool IsValid { get { - return ProfileProperties.EditMode; - } - set - { - ProfileProperties.EditMode = value; + return this.ProfileProperties.IsValid || this.IsAdmin; } } - + /// ----------------------------------------------------------------------------- /// - /// Gets whether the User is valid + /// Gets a value indicating whether gets whether to display the Visibility controls. /// /// ----------------------------------------------------------------------------- - public bool IsValid + protected bool ShowVisibility { get { - return ProfileProperties.IsValid || IsAdmin; + object setting = GetSetting(this.PortalId, "Profile_DisplayVisibility"); + return Convert.ToBoolean(setting) && this.IsUser; } - } + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Update button + /// Gets or sets a value indicating whether gets and sets whether the Update button. /// /// ----------------------------------------------------------------------------- public bool ShowUpdate { get { - return actionsRow.Visible; + return this.actionsRow.Visible; } + set { - actionsRow.Visible = value; + this.actionsRow.Visible = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the UserProfile associated with this control + /// Gets the UserProfile associated with this control. /// /// ----------------------------------------------------------------------------- public UserProfile UserProfile @@ -107,55 +100,47 @@ public UserProfile UserProfile get { UserProfile _Profile = null; - if (User != null) + if (this.User != null) { - _Profile = User.Profile; + _Profile = this.User.Profile; } + return _Profile; } - } - - #endregion - - #region Public Methods - + } + /// ----------------------------------------------------------------------------- /// - /// DataBind binds the data to the controls + /// DataBind binds the data to the controls. /// /// ----------------------------------------------------------------------------- public override void DataBind() { - - //Before we bind the Profile to the editor we need to "update" the visible data + // Before we bind the Profile to the editor we need to "update" the visible data var properties = new ProfilePropertyDefinitionCollection(); - var imageType = new ListController().GetListEntryInfo("DataType", "Image"); - foreach (ProfilePropertyDefinition profProperty in UserProfile.ProfileProperties) + var imageType = new ListController().GetListEntryInfo("DataType", "Image"); + foreach (ProfilePropertyDefinition profProperty in this.UserProfile.ProfileProperties) { - if (IsAdmin && !IsProfile) + if (this.IsAdmin && !this.IsProfile) { profProperty.Visible = true; } - if (!profProperty.Deleted && (Request.IsAuthenticated || profProperty.DataType != imageType.EntryID)) + if (!profProperty.Deleted && (this.Request.IsAuthenticated || profProperty.DataType != imageType.EntryID)) { properties.Add(profProperty); } } - ProfileProperties.User = User; - ProfileProperties.ShowVisibility = ShowVisibility; - ProfileProperties.DataSource = properties; - ProfileProperties.DataBind(); - } - - #endregion - - #region Event Handlers - + this.ProfileProperties.User = this.User; + this.ProfileProperties.ShowVisibility = this.ShowVisibility; + this.ProfileProperties.DataSource = properties; + this.ProfileProperties.DataBind(); + } + /// ----------------------------------------------------------------------------- /// - /// Page_Init runs when the control is initialised + /// Page_Init runs when the control is initialised. /// /// /// @@ -163,21 +148,22 @@ public override void DataBind() protected override void OnInit(EventArgs e) { base.OnInit(e); - ID = "Profile.ascx"; + this.ID = "Profile.ascx"; - //Get the base Page - var basePage = Page as PageBase; + // Get the base Page + var basePage = this.Page as PageBase; if (basePage != null) { - //Check if culture is RTL - ProfileProperties.LabelMode = basePage.PageCulture.TextInfo.IsRightToLeft ? LabelMode.Right : LabelMode.Left; + // Check if culture is RTL + this.ProfileProperties.LabelMode = basePage.PageCulture.TextInfo.IsRightToLeft ? LabelMode.Right : LabelMode.Left; } - ProfileProperties.LocalResourceFile = LocalResourceFile; + + this.ProfileProperties.LocalResourceFile = this.LocalResourceFile; } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -185,62 +171,60 @@ protected override void OnInit(EventArgs e) protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdUpdate.Click += cmdUpdate_Click; + this.cmdUpdate.Click += this.cmdUpdate_Click; } /// ----------------------------------------------------------------------------- /// - /// cmdUpdate_Click runs when the Update Button is clicked + /// cmdUpdate_Click runs when the Update Button is clicked. /// /// /// /// ----------------------------------------------------------------------------- private void cmdUpdate_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false && UserId == Null.NullInteger) + if (this.IsUserOrAdmin == false && this.UserId == Null.NullInteger) { return; } - if (IsValid) + if (this.IsValid) { - if (User.UserID == PortalSettings.AdministratorId) + if (this.User.UserID == this.PortalSettings.AdministratorId) { - //Clear the Portal Cache - DataCache.ClearPortalCache(UserPortalID, true); + // Clear the Portal Cache + DataCache.ClearPortalCache(this.UserPortalID, true); } - //Update DisplayName to conform to Format - UpdateDisplayName(); + // Update DisplayName to conform to Format + this.UpdateDisplayName(); - if (PortalSettings.Registration.RequireUniqueDisplayName) + if (this.PortalSettings.Registration.RequireUniqueDisplayName) { - var usersWithSameDisplayName = (List)MembershipProvider.Instance().GetUsersBasicSearch(PortalId, 0, 2, "DisplayName", true, "DisplayName", User.DisplayName); - if (usersWithSameDisplayName.Any(user => user.UserID != User.UserID)) + var usersWithSameDisplayName = (List)MembershipProvider.Instance().GetUsersBasicSearch(this.PortalId, 0, 2, "DisplayName", true, "DisplayName", this.User.DisplayName); + if (usersWithSameDisplayName.Any(user => user.UserID != this.User.UserID)) { - AddModuleMessage("DisplayNameNotUnique", ModuleMessage.ModuleMessageType.RedError, true); + this.AddModuleMessage("DisplayNameNotUnique", ModuleMessage.ModuleMessageType.RedError, true); return; } } - var properties = (ProfilePropertyDefinitionCollection)ProfileProperties.DataSource; + var properties = (ProfilePropertyDefinitionCollection)this.ProfileProperties.DataSource; - //Update User's profile - User = ProfileController.UpdateUserProfile(User, properties); + // Update User's profile + this.User = ProfileController.UpdateUserProfile(this.User, properties); - OnProfileUpdated(EventArgs.Empty); - OnProfileUpdateCompleted(EventArgs.Empty); + this.OnProfileUpdated(EventArgs.Empty); + this.OnProfileUpdateCompleted(EventArgs.Empty); } } private void UpdateDisplayName() { - if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) { - User.UpdateDisplayName(PortalSettings.Registration.DisplayNameFormat); + this.User.UpdateDisplayName(this.PortalSettings.Registration.DisplayNameFormat); } - } - - #endregion + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs index dc939f68a61..fef019515ca 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs @@ -1,182 +1,221 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; + /// ----------------------------------------------------------------------------- /// /// The ProfileDefinitions PortalModuleBase is used to manage the Profile Properties - /// for a portal + /// for a portal. /// /// /// /// ----------------------------------------------------------------------------- public partial class ProfileDefinitions : PortalModuleBase, IActionable { - private readonly INavigationManager _navigationManager; - public ProfileDefinitions() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Constants - private const int COLUMN_REQUIRED = 11; private const int COLUMN_VISIBLE = 12; private const int COLUMN_MOVE_DOWN = 2; - private const int COLUMN_MOVE_UP = 3; - - #endregion - - #region Private Members - + + private readonly INavigationManager _navigationManager; + + public ProfileDefinitions() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + private const int COLUMN_MOVE_UP = 3; private ProfilePropertyDefinitionCollection _profileProperties; - private bool _requiredColumnHidden = false; - - #endregion - - #region Protected Members + private bool _requiredColumnHidden = false; /// ----------------------------------------------------------------------------- /// - /// Gets whether we are dealing with SuperUsers + /// Gets the Return Url for the page. /// /// ----------------------------------------------------------------------------- - protected bool IsSuperUser + public string ReturnUrl { get { - return Globals.IsHostTab(PortalSettings.ActiveTab.TabID); + string returnURL; + var filterParams = new string[string.IsNullOrEmpty(this.Request.QueryString["filterproperty"]) ? 1 : 2]; + + if (string.IsNullOrEmpty(this.Request.QueryString["filterProperty"])) + { + filterParams.SetValue("filter=" + this.Request.QueryString["filter"], 0); + } + else + { + filterParams.SetValue("filter=" + this.Request.QueryString["filter"], 0); + filterParams.SetValue("filterProperty=" + this.Request.QueryString["filterProperty"], 1); + } + + if (string.IsNullOrEmpty(this.Request.QueryString["filter"])) + { + returnURL = this._navigationManager.NavigateURL(this.TabId); + } + else + { + returnURL = this._navigationManager.NavigateURL(this.TabId, string.Empty, filterParams); + } + + return returnURL; } } - + + public ModuleActionCollection ModuleActions + { + get + { + var actions = new ModuleActionCollection(); + actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "add.gif", + this.EditUrl("EditProfileProperty"), + false, + SecurityAccessLevel.Admin, + true, + false); + actions.Add( + this.GetNextActionID(), + Localization.GetString("Cancel.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "lt.gif", + this.ReturnUrl, + false, + SecurityAccessLevel.Admin, + true, + false); + return actions; + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets the collection of Profile Proeprties + /// Gets a value indicating whether gets whether we are dealing with SuperUsers. /// /// ----------------------------------------------------------------------------- - protected ProfilePropertyDefinitionCollection ProfileProperties + protected bool IsSuperUser { get { - return _profileProperties ?? (_profileProperties = ProfileController.GetPropertyDefinitionsByPortal(UsersPortalId, false, false)); + return Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Return Url for the page + /// Gets the collection of Profile Proeprties. /// /// ----------------------------------------------------------------------------- - public string ReturnUrl + protected ProfilePropertyDefinitionCollection ProfileProperties { get { - string returnURL; - var filterParams = new string[String.IsNullOrEmpty(Request.QueryString["filterproperty"]) ? 1 : 2]; - - if (String.IsNullOrEmpty(Request.QueryString["filterProperty"])) - { - filterParams.SetValue("filter=" + Request.QueryString["filter"], 0); - } - else - { - filterParams.SetValue("filter=" + Request.QueryString["filter"], 0); - filterParams.SetValue("filterProperty=" + Request.QueryString["filterProperty"], 1); - } - if (string.IsNullOrEmpty(Request.QueryString["filter"])) - { - returnURL = _navigationManager.NavigateURL(TabId); - } - else - { - returnURL = _navigationManager.NavigateURL(TabId, "", filterParams); - } - return returnURL; + return this._profileProperties ?? (this._profileProperties = ProfileController.GetPropertyDefinitionsByPortal(this.UsersPortalId, false, false)); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Portal Id whose Users we are managing + /// Gets the Portal Id whose Users we are managing. /// /// ----------------------------------------------------------------------------- protected int UsersPortalId { get { - int intPortalId = PortalId; - if (IsSuperUser) + int intPortalId = this.PortalId; + if (this.IsSuperUser) { intPortalId = Null.NullInteger; } + return intPortalId; } + } + + public string DisplayDataType(ProfilePropertyDefinition definition) + { + string retValue = Null.NullString; + var listController = new ListController(); + ListEntryInfo definitionEntry = listController.GetListEntryInfo("DataType", definition.DataType); + if (definitionEntry != null) + { + retValue = definitionEntry.Value; + } + + return retValue; } - #endregion - - #region IActionable Members - - public ModuleActionCollection ModuleActions + public string DisplayDefaultVisibility(ProfilePropertyDefinition definition) { - get + string retValue = Null.NullString; + if (!string.IsNullOrEmpty(definition.DefaultVisibility.ToString())) { - var actions = new ModuleActionCollection(); - actions.Add(GetNextActionID(), - Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), - ModuleActionType.AddContent, - "", - "add.gif", - EditUrl("EditProfileProperty"), - false, - SecurityAccessLevel.Admin, - true, - false); - actions.Add(GetNextActionID(), - Localization.GetString("Cancel.Action", LocalResourceFile), - ModuleActionType.AddContent, - "", - "lt.gif", - ReturnUrl, - false, - SecurityAccessLevel.Admin, - true, - false); - return actions; + retValue = this.LocalizeString(definition.DefaultVisibility.ToString()) ?? definition.DefaultVisibility.ToString(); } + + return retValue; } + + protected override void LoadViewState(object savedState) + { + if (savedState != null) + { + // Load State from the array of objects that was saved with SaveViewState. + var myState = (object[])savedState; - #endregion + // Load Base Controls ViewState + if (myState[0] != null) + { + base.LoadViewState(myState[0]); + } - #region Private Methods + // Load ModuleID + if (myState[1] != null) + { + this._profileProperties = (ProfilePropertyDefinitionCollection)myState[1]; + } + } + } + + protected override object SaveViewState() + { + var allStates = new object[2]; + + // Save the Base Controls ViewState + allStates[0] = base.SaveViewState(); + allStates[1] = this.ProfileProperties; + return allStates; + } + /// ----------------------------------------------------------------------------- /// - /// Helper function that determines whether the client-side functionality is possible + /// Helper function that determines whether the client-side functionality is possible. /// /// ----------------------------------------------------------------------------- private bool SupportsRichClient() @@ -186,66 +225,66 @@ private bool SupportsRichClient() /// ----------------------------------------------------------------------------- /// - /// Deletes a property + /// Deletes a property. /// - /// The index of the Property to delete + /// The index of the Property to delete. /// ----------------------------------------------------------------------------- private void DeleteProperty(int index) { - ProfileController.DeletePropertyDefinition(ProfileProperties[index]); + ProfileController.DeletePropertyDefinition(this.ProfileProperties[index]); - RefreshGrid(); + this.RefreshGrid(); } /// ----------------------------------------------------------------------------- /// - /// Moves a property + /// Moves a property. /// - /// The index of the Property to move - /// The new index of the Property + /// The index of the Property to move. + /// The new index of the Property. /// ----------------------------------------------------------------------------- private void MoveProperty(int index, int destIndex) { - ProfilePropertyDefinition profileProperty = ProfileProperties[index]; - ProfilePropertyDefinition nextProfileProperty = ProfileProperties[destIndex]; + ProfilePropertyDefinition profileProperty = this.ProfileProperties[index]; + ProfilePropertyDefinition nextProfileProperty = this.ProfileProperties[destIndex]; int currentOrder = profileProperty.ViewOrder; int nextOrder = nextProfileProperty.ViewOrder; - //Swap ViewOrders + // Swap ViewOrders profileProperty.ViewOrder = nextOrder; nextProfileProperty.ViewOrder = currentOrder; - //Refresh Grid - ProfileProperties.Sort(); - BindGrid(); + // Refresh Grid + this.ProfileProperties.Sort(); + this.BindGrid(); } /// ----------------------------------------------------------------------------- /// - /// Moves a property down in the ViewOrder + /// Moves a property down in the ViewOrder. /// - /// The index of the Property to move + /// The index of the Property to move. /// ----------------------------------------------------------------------------- private void MovePropertyDown(int index) { - MoveProperty(index, index + 1); + this.MoveProperty(index, index + 1); } /// ----------------------------------------------------------------------------- /// - /// Moves a property up in the ViewOrder + /// Moves a property up in the ViewOrder. /// - /// The index of the Property to move + /// The index of the Property to move. /// ----------------------------------------------------------------------------- private void MovePropertyUp(int index) { - MoveProperty(index, index - 1); + this.MoveProperty(index, index - 1); } /// ----------------------------------------------------------------------------- /// - /// Binds the Property Collection to the Grid + /// Binds the Property Collection to the Grid. /// /// ----------------------------------------------------------------------------- private void BindGrid() @@ -253,69 +292,75 @@ private void BindGrid() bool allRequired = true; bool allVisible = true; - //Check whether the checkbox column headers are true or false - foreach (ProfilePropertyDefinition profProperty in ProfileProperties) + // Check whether the checkbox column headers are true or false + foreach (ProfilePropertyDefinition profProperty in this.ProfileProperties) { if (profProperty.Required == false) { allRequired = false; } + if (profProperty.Visible == false) { allVisible = false; } + if (!allRequired && !allVisible) { break; } } - foreach (DataGridColumn column in grdProfileProperties.Columns) + + foreach (DataGridColumn column in this.grdProfileProperties.Columns) { if (ReferenceEquals(column.GetType(), typeof(CheckBoxColumn))) { - //Manage CheckBox column events + // Manage CheckBox column events var checkBoxColumn = (CheckBoxColumn)column; if (checkBoxColumn.DataField == "Required") { checkBoxColumn.Checked = allRequired; } + if (checkBoxColumn.DataField == "Visible") { checkBoxColumn.Checked = allVisible; } } } - grdProfileProperties.DataSource = ProfileProperties; - grdProfileProperties.DataBind(); + + this.grdProfileProperties.DataSource = this.ProfileProperties; + this.grdProfileProperties.DataBind(); } /// ----------------------------------------------------------------------------- /// - /// Refresh the Property Collection to the Grid + /// Refresh the Property Collection to the Grid. /// /// ----------------------------------------------------------------------------- private void RefreshGrid() { - _profileProperties = null; - BindGrid(); + this._profileProperties = null; + this.BindGrid(); } /// ----------------------------------------------------------------------------- /// - /// Updates any "dirty" properties + /// Updates any "dirty" properties. /// /// ----------------------------------------------------------------------------- private void UpdateProperties() { - ProcessPostBack(); - foreach (ProfilePropertyDefinition property in ProfileProperties) + this.ProcessPostBack(); + foreach (ProfilePropertyDefinition property in this.ProfileProperties) { if (property.IsDirty) { - if (UsersPortalId == Null.NullInteger) + if (this.UsersPortalId == Null.NullInteger) { property.Required = false; } + ProfileController.UpdatePropertyDefinition(property); } } @@ -324,115 +369,49 @@ private void UpdateProperties() /// ----------------------------------------------------------------------------- /// /// This method is responsible for taking in posted information from the grid and - /// persisting it to the property definition collection + /// persisting it to the property definition collection. /// /// ----------------------------------------------------------------------------- private void ProcessPostBack() { - - string[] newOrder = ClientAPI.GetClientSideReorder(grdProfileProperties.ClientID, Page); - for (int i = 0; i <= grdProfileProperties.Items.Count - 1; i++) + string[] newOrder = ClientAPI.GetClientSideReorder(this.grdProfileProperties.ClientID, this.Page); + for (int i = 0; i <= this.grdProfileProperties.Items.Count - 1; i++) { - DataGridItem dataGridItem = grdProfileProperties.Items[i]; - ProfilePropertyDefinition profileProperty = ProfileProperties[i]; + DataGridItem dataGridItem = this.grdProfileProperties.Items[i]; + ProfilePropertyDefinition profileProperty = this.ProfileProperties[i]; CheckBox checkBox = (CheckBox)dataGridItem.Cells[COLUMN_REQUIRED].Controls[0]; profileProperty.Required = checkBox.Checked; checkBox = (CheckBox)dataGridItem.Cells[COLUMN_VISIBLE].Controls[0]; profileProperty.Visible = checkBox.Checked; } - //assign vieworder + // assign vieworder for (int i = 0; i <= newOrder.Length - 1; i++) { - ProfileProperties[Convert.ToInt32(newOrder[i])].ViewOrder = i; + this.ProfileProperties[Convert.ToInt32(newOrder[i])].ViewOrder = i; } - ProfileProperties.Sort(); - } - - #endregion - - #region Protected Methods - - protected override void LoadViewState(object savedState) - { - if (savedState != null) - { - //Load State from the array of objects that was saved with SaveViewState. - var myState = (object[])savedState; - - //Load Base Controls ViewState - if (myState[0] != null) - { - base.LoadViewState(myState[0]); - } - - //Load ModuleID - if (myState[1] != null) - { - _profileProperties = (ProfilePropertyDefinitionCollection)myState[1]; - } - } - } - - protected override object SaveViewState() - { - var allStates = new object[2]; - - //Save the Base Controls ViewState - allStates[0] = base.SaveViewState(); - allStates[1] = ProfileProperties; - - return allStates; - } - - #endregion - - #region Public Methods - - public string DisplayDataType(ProfilePropertyDefinition definition) - { - string retValue = Null.NullString; - var listController = new ListController(); - ListEntryInfo definitionEntry = listController.GetListEntryInfo("DataType", definition.DataType); - if (definitionEntry != null) - { - retValue = definitionEntry.Value; - } - return retValue; - } - - public string DisplayDefaultVisibility(ProfilePropertyDefinition definition) - { - string retValue = Null.NullString; - if (!String.IsNullOrEmpty(definition.DefaultVisibility.ToString())) - { - retValue = LocalizeString(definition.DefaultVisibility.ToString()) ?? definition.DefaultVisibility.ToString(); - } - return retValue; - } + + this.ProfileProperties.Sort(); + } public void Update() { try { - UpdateProperties(); + this.UpdateProperties(); - //Redirect to upadte page - Response.Redirect(Request.RawUrl, true); + // Redirect to upadte page + this.Response.Redirect(this.Request.RawUrl, true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - - #region Event Handlers - + } + /// ----------------------------------------------------------------------------- /// - /// Page_Init runs when the control is initialised + /// Page_Init runs when the control is initialised. /// /// /// @@ -441,45 +420,46 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - foreach (DataGridColumn column in grdProfileProperties.Columns) + foreach (DataGridColumn column in this.grdProfileProperties.Columns) { if (ReferenceEquals(column.GetType(), typeof(CheckBoxColumn))) { var checkBoxColumn = (CheckBoxColumn)column; - if (checkBoxColumn.DataField == "Required" && UsersPortalId == Null.NullInteger) + if (checkBoxColumn.DataField == "Required" && this.UsersPortalId == Null.NullInteger) { checkBoxColumn.Visible = false; - _requiredColumnHidden = true; + this._requiredColumnHidden = true; } - if (SupportsRichClient() == false) + + if (this.SupportsRichClient() == false) { - checkBoxColumn.CheckedChanged += grdProfileProperties_ItemCheckedChanged; + checkBoxColumn.CheckedChanged += this.grdProfileProperties_ItemCheckedChanged; } } else if (ReferenceEquals(column.GetType(), typeof(ImageCommandColumn))) { - //Manage Delete Confirm JS + // Manage Delete Confirm JS var imageColumn = (ImageCommandColumn)column; switch (imageColumn.CommandName) { case "Delete": imageColumn.OnClickJS = Localization.GetString("DeleteItem"); - imageColumn.Text = Localization.GetString("Delete", LocalResourceFile); + imageColumn.Text = Localization.GetString("Delete", this.LocalResourceFile); break; case "Edit": - //The Friendly URL parser does not like non-alphanumeric characters - //so first create the format string with a dummy value and then - //replace the dummy value with the FormatString place holder - string formatString = EditUrl("PropertyDefinitionID", "KEYFIELD", "EditProfileProperty"); + // The Friendly URL parser does not like non-alphanumeric characters + // so first create the format string with a dummy value and then + // replace the dummy value with the FormatString place holder + string formatString = this.EditUrl("PropertyDefinitionID", "KEYFIELD", "EditProfileProperty"); formatString = formatString.Replace("KEYFIELD", "{0}"); imageColumn.NavigateURLFormatString = formatString; - imageColumn.Text = Localization.GetString("Edit", LocalResourceFile); + imageColumn.Text = Localization.GetString("Edit", this.LocalResourceFile); break; case "MoveUp": - imageColumn.Text = Localization.GetString("MoveUp", LocalResourceFile); + imageColumn.Text = Localization.GetString("MoveUp", this.LocalResourceFile); break; case "MoveDown": - imageColumn.Text = Localization.GetString("MoveDown", LocalResourceFile); + imageColumn.Text = Localization.GetString("MoveDown", this.LocalResourceFile); break; } } @@ -490,22 +470,22 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdRefresh.Click += cmdRefresh_Click; - grdProfileProperties.ItemCommand += grdProfileProperties_ItemCommand; - grdProfileProperties.ItemCreated += grdProfileProperties_ItemCreated; - grdProfileProperties.ItemDataBound += grdProfileProperties_ItemDataBound; + this.cmdRefresh.Click += this.cmdRefresh_Click; + this.grdProfileProperties.ItemCommand += this.grdProfileProperties_ItemCommand; + this.grdProfileProperties.ItemCreated += this.grdProfileProperties_ItemCreated; + this.grdProfileProperties.ItemDataBound += this.grdProfileProperties_ItemDataBound; - cmdAdd.NavigateUrl = EditUrl("EditProfileProperty"); + this.cmdAdd.NavigateUrl = this.EditUrl("EditProfileProperty"); try { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - Localization.LocalizeDataGrid(ref grdProfileProperties, LocalResourceFile); - BindGrid(); + Localization.LocalizeDataGrid(ref this.grdProfileProperties, this.LocalResourceFile); + this.BindGrid(); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -513,20 +493,55 @@ protected override void OnLoad(EventArgs e) /// ----------------------------------------------------------------------------- /// - /// cmdRefresh_Click runs when the refresh button is clciked + /// grdProfileProperties_ItemDataBound runs when a row in the grid is bound to its data source + /// Grid. + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected void grdProfileProperties_ItemDataBound(object sender, DataGridItemEventArgs e) + { + DataGridItem item = e.Item; + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + { + Control imgColumnControl = item.Controls[1].Controls[0]; + if (imgColumnControl is ImageButton) + { + var delImage = (ImageButton)imgColumnControl; + var profProperty = (ProfilePropertyDefinition)item.DataItem; + + switch (profProperty.PropertyName.ToLowerInvariant()) + { + case "lastname": + case "firstname": + case "preferredtimezone": + case "preferredlocale": + delImage.Visible = false; + break; + default: + delImage.Visible = true; + break; + } + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// cmdRefresh_Click runs when the refresh button is clciked. /// /// /// /// ----------------------------------------------------------------------------- private void cmdRefresh_Click(object sender, EventArgs e) { - RefreshGrid(); + this.RefreshGrid(); } /// ----------------------------------------------------------------------------- /// /// grdProfileProperties_ItemCheckedChanged runs when a checkbox in the grid - /// is clicked + /// is clicked. /// /// /// @@ -538,8 +553,8 @@ private void grdProfileProperties_ItemCheckedChanged(object sender, DNNDataGridC if (e.IsAll) { - //Update All the properties - foreach (ProfilePropertyDefinition profProperty in ProfileProperties) + // Update All the properties + foreach (ProfilePropertyDefinition profProperty in this.ProfileProperties) { switch (propertyName) { @@ -554,8 +569,8 @@ private void grdProfileProperties_ItemCheckedChanged(object sender, DNNDataGridC } else { - //Update the indexed property - ProfilePropertyDefinition profileProperty = ProfileProperties[e.Item.ItemIndex]; + // Update the indexed property + ProfilePropertyDefinition profileProperty = this.ProfileProperties[e.Item.ItemIndex]; switch (propertyName) { case "Required": @@ -566,13 +581,14 @@ private void grdProfileProperties_ItemCheckedChanged(object sender, DNNDataGridC break; } } - BindGrid(); + + this.BindGrid(); } /// ----------------------------------------------------------------------------- /// /// grdProfileProperties_ItemCommand runs when a Command event is raised in the - /// Grid + /// Grid. /// /// /// @@ -584,13 +600,13 @@ private void grdProfileProperties_ItemCommand(object source, DataGridCommandEven switch (e.CommandName) { case "Delete": - DeleteProperty(index); + this.DeleteProperty(index); break; case "MoveUp": - MovePropertyUp(index); + this.MovePropertyUp(index); break; case "MoveDown": - MovePropertyDown(index); + this.MovePropertyDown(index); break; } } @@ -599,23 +615,23 @@ private void grdProfileProperties_ItemCommand(object source, DataGridCommandEven /// /// When it is determined that the client supports a rich interactivity the grdProfileProperties_ItemCreated /// event is responsible for disabling all the unneeded AutoPostBacks, along with assiging the appropriate - /// client-side script for each event handler + /// client-side script for each event handler. /// /// /// /// ----------------------------------------------------------------------------- private void grdProfileProperties_ItemCreated(object sender, DataGridItemEventArgs e) { - if (SupportsRichClient()) + if (this.SupportsRichClient()) { switch (e.Item.ItemType) { case ListItemType.Header: - //we combined the header label and checkbox in same place, so it is control 1 instead of 0 + // we combined the header label and checkbox in same place, so it is control 1 instead of 0 ((WebControl)e.Item.Cells[COLUMN_REQUIRED].Controls[1]).Attributes.Add("onclick", "dnn.util.checkallChecked(this," + COLUMN_REQUIRED + ");"); ((CheckBox)e.Item.Cells[COLUMN_REQUIRED].Controls[1]).AutoPostBack = false; - int column_visible = _requiredColumnHidden ? COLUMN_VISIBLE - 1 : COLUMN_VISIBLE; + int column_visible = this._requiredColumnHidden ? COLUMN_VISIBLE - 1 : COLUMN_VISIBLE; ((WebControl)e.Item.Cells[COLUMN_VISIBLE].Controls[1]).Attributes.Add("onclick", "dnn.util.checkallChecked(this," + column_visible + ");"); ((CheckBox)e.Item.Cells[COLUMN_VISIBLE].Controls[1]).AutoPostBack = false; break; @@ -623,48 +639,11 @@ private void grdProfileProperties_ItemCreated(object sender, DataGridItemEventAr case ListItemType.Item: ((CheckBox)e.Item.Cells[COLUMN_REQUIRED].Controls[0]).AutoPostBack = false; ((CheckBox)e.Item.Cells[COLUMN_VISIBLE].Controls[0]).AutoPostBack = false; - ClientAPI.EnableClientSideReorder(e.Item.Cells[COLUMN_MOVE_DOWN].Controls[0], Page, false, grdProfileProperties.ClientID); - ClientAPI.EnableClientSideReorder(e.Item.Cells[COLUMN_MOVE_UP].Controls[0], Page, true, grdProfileProperties.ClientID); + ClientAPI.EnableClientSideReorder(e.Item.Cells[COLUMN_MOVE_DOWN].Controls[0], this.Page, false, this.grdProfileProperties.ClientID); + ClientAPI.EnableClientSideReorder(e.Item.Cells[COLUMN_MOVE_UP].Controls[0], this.Page, true, this.grdProfileProperties.ClientID); break; } } } - - /// ----------------------------------------------------------------------------- - /// - /// grdProfileProperties_ItemDataBound runs when a row in the grid is bound to its data source - /// Grid - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected void grdProfileProperties_ItemDataBound(object sender, DataGridItemEventArgs e) - { - DataGridItem item = e.Item; - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - Control imgColumnControl = item.Controls[1].Controls[0]; - if (imgColumnControl is ImageButton) - { - var delImage = (ImageButton)imgColumnControl; - var profProperty = (ProfilePropertyDefinition)item.DataItem; - - switch (profProperty.PropertyName.ToLowerInvariant()) - { - case "lastname": - case "firstname": - case "preferredtimezone": - case "preferredlocale": - delImage.Visible = false; - break; - default: - delImage.Visible = true; - break; - } - } - } - } - - #endregion } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs index c1bf03a6ae7..8926439b32d 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs @@ -1,879 +1,876 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Web; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls; -using DotNetNuke.UI.WebControls; -using System.Web.UI.WebControls; -using DotNetNuke.Entities.Users.Membership; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Membership; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.WebControls; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + using Host = DotNetNuke.Entities.Host.Host; + + public partial class Register : UserUserControlBase + { + protected const string PasswordStrengthTextBoxCssClass = "password-strength"; + protected const string ConfirmPasswordTextBoxCssClass = "password-confirm"; - public partial class Register : UserUserControlBase - { - protected const string PasswordStrengthTextBoxCssClass = "password-strength"; - protected const string ConfirmPasswordTextBoxCssClass = "password-confirm"; - - private readonly List _loginControls = new List(); + private readonly List _loginControls = new List(); private readonly INavigationManager _navigationManager; public Register() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + + protected string AuthenticationType + { + get + { + return this.ViewState.GetValue("AuthenticationType", Null.NullString); + } + + set + { + this.ViewState.SetValue("AuthenticationType", value, Null.NullString); + } + } + + protected UserCreateStatus CreateStatus { get; set; } + + protected string ExcludeTerms + { + get + { + string regex = string.Empty; + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.ExcludeTerms)) + { + regex = @"^(?:(?!" + this.PortalSettings.Registration.ExcludeTerms.Replace(" ", string.Empty).Replace(",", "|") + @").)*$\r?\n?"; + } + + return regex; + } + } + + protected bool IsValid + { + get + { + return this.Validate(); + } + } + + protected string UserToken + { + get + { + return this.ViewState.GetValue("UserToken", string.Empty); + } + + set + { + this.ViewState.SetValue("UserToken", value, string.Empty); + } + } + + protected override bool AddUser { get; } = true; + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); + + if (this.PortalSettings.Registration.RegistrationFormType == 0) + { + // DisplayName + if (string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) + { + this.AddField("DisplayName", string.Empty, true, string.Empty, TextBoxMode.SingleLine); + } + else + { + this.AddField("FirstName", string.Empty, true, string.Empty, TextBoxMode.SingleLine); + this.AddField("LastName", string.Empty, true, string.Empty, TextBoxMode.SingleLine); + } + + // Email + this.AddField("Email", string.Empty, true, this.PortalSettings.Registration.EmailValidator, TextBoxMode.SingleLine); + + // UserName + if (!this.PortalSettings.Registration.UseEmailAsUserName) + { + this.AddField("Username", string.Empty, true, + string.IsNullOrEmpty(this.PortalSettings.Registration.UserNameValidator) ? this.ExcludeTerms : this.PortalSettings.Registration.UserNameValidator, + TextBoxMode.SingleLine); + } + + // Password + if (!this.PortalSettings.Registration.RandomPassword) + { + this.AddPasswordStrengthField("Password", "Membership", true); + + if (this.PortalSettings.Registration.RequirePasswordConfirm) + { + this.AddPasswordConfirmField("PasswordConfirm", "Membership", true); + } + } + + // Password Q&A + if (MembershipProviderConfig.RequiresQuestionAndAnswer) + { + this.AddField("PasswordQuestion", "Membership", true, string.Empty, TextBoxMode.SingleLine); + this.AddField("PasswordAnswer", "Membership", true, string.Empty, TextBoxMode.SingleLine); + } + + if (this.PortalSettings.Registration.RequireValidProfile) + { + foreach (ProfilePropertyDefinition property in this.User.Profile.ProfileProperties) + { + if (property.Required) + { + this.AddProperty(property); + } + } + } + } + else + { + var fields = this.PortalSettings.Registration.RegistrationFields.Split(',').ToList(); + + // append question/answer field when RequiresQuestionAndAnswer is enabled in config. + if (MembershipProviderConfig.RequiresQuestionAndAnswer) + { + if (!fields.Contains("PasswordQuestion")) + { + fields.Add("PasswordQuestion"); + } + + if (!fields.Contains("PasswordAnswer")) + { + fields.Add("PasswordAnswer"); + } + } + + foreach (string field in fields) + { + var trimmedField = field.Trim(); + switch (trimmedField) + { + case "Username": + this.AddField("Username", string.Empty, true, string.IsNullOrEmpty(this.PortalSettings.Registration.UserNameValidator) + ? this.ExcludeTerms : this.PortalSettings.Registration.UserNameValidator, + TextBoxMode.SingleLine); + break; + case "DisplayName": + this.AddField(trimmedField, string.Empty, true, this.ExcludeTerms, TextBoxMode.SingleLine); + break; + case "Email": + this.AddField("Email", string.Empty, true, this.PortalSettings.Registration.EmailValidator, TextBoxMode.SingleLine); + break; + case "Password": + this.AddPasswordStrengthField(trimmedField, "Membership", true); + break; + case "PasswordConfirm": + this.AddPasswordConfirmField(trimmedField, "Membership", true); + break; + case "PasswordQuestion": + case "PasswordAnswer": + this.AddField(trimmedField, "Membership", true, string.Empty, TextBoxMode.SingleLine); + break; + default: + ProfilePropertyDefinition property = this.User.Profile.GetProperty(trimmedField); + if (property != null) + { + this.AddProperty(property); + } + + break; + } + } + } + + // Verify that the current user has access to this page + if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && this.Request.IsAuthenticated == false) + { + try + { + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + } + catch (ThreadAbortException) + { + // do nothing here. + } + } + + this.cancelLink.NavigateUrl = this.closeLink.NavigateUrl = this.GetRedirectUrl(false); + this.registerButton.Click += this.registerButton_Click; + + if (this.PortalSettings.Registration.UseAuthProviders) + { + List authSystems = AuthenticationController.GetEnabledAuthenticationServices(); + foreach (AuthenticationInfo authSystem in authSystems) + { + try + { + var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); + if (authSystem.AuthenticationType != "DNN") + { + this.BindLoginControl(authLoginControl, authSystem); + + // Check if AuthSystem is Enabled + if (authLoginControl.Enabled && authLoginControl.SupportsRegistration) + { + authLoginControl.Mode = AuthMode.Register; + + // Add Login Control to List + this._loginControls.Add(authLoginControl); + } + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + } + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + if (this.Request.IsAuthenticated) + { + // if a Login Page has not been specified for the portal + if (Globals.IsAdminControl()) + { + // redirect to current page + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + else // make module container invisible if user is not a page admin + { + if (!TabPermissionController.CanAdminPage()) + { + this.ContainerControl.Visible = false; + } + } + } + + if (this.PortalSettings.Registration.UseCaptcha) + { + this.captchaRow.Visible = true; + this.ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", this.LocalResourceFile); + this.ctlCaptcha.Text = Localization.GetString("CaptchaText", this.LocalResourceFile); + } + + if (this.PortalSettings.Registration.UseAuthProviders && string.IsNullOrEmpty(this.AuthenticationType)) + { + foreach (AuthenticationLoginBase authLoginControl in this._loginControls) + { + this.socialLoginControls.Controls.Add(authLoginControl); + } + } + + // Display relevant message + this.userHelpLabel.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS"); + switch (this.PortalSettings.UserRegistration) + { + case (int)Globals.PortalRegistrationType.PrivateRegistration: + this.userHelpLabel.Text += Localization.GetString("PrivateMembership", Localization.SharedResourceFile); + break; + case (int)Globals.PortalRegistrationType.PublicRegistration: + this.userHelpLabel.Text += Localization.GetString("PublicMembership", Localization.SharedResourceFile); + break; + case (int)Globals.PortalRegistrationType.VerifiedRegistration: + this.userHelpLabel.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile); + break; + } + + this.userHelpLabel.Text += Localization.GetString("Required", this.LocalResourceFile); + this.userHelpLabel.Text += Localization.GetString("RegisterWarning", this.LocalResourceFile); + + this.userForm.DataSource = this.User; + if (!this.Page.IsPostBack) + { + this.userForm.DataBind(); + } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + var confirmPasswordOptions = new DnnConfirmPasswordOptions() + { + FirstElementSelector = "." + PasswordStrengthTextBoxCssClass, + SecondElementSelector = "." + ConfirmPasswordTextBoxCssClass, + ContainerSelector = ".dnnRegistrationForm", + UnmatchedCssClass = "unmatched", + MatchedCssClass = "matched", + }; + + var optionsAsJsonString = Json.Serialize(confirmPasswordOptions); + var script = string.Format("dnn.initializePasswordComparer({0});{1}", optionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ConfirmPassword", script, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmPassword", script, true); + } + } + + private void AddField(string dataField, string dataMember, bool required, string regexValidator, TextBoxMode textMode) + { + if (this.userForm.Items.Any(i => i.ID == dataField)) + { + return; + } + + var formItem = new DnnFormTextBoxItem + { + ID = dataField, + DataField = dataField, + DataMember = dataMember, + Visible = true, + Required = required, + TextMode = textMode, + }; + if (!string.IsNullOrEmpty(regexValidator)) + { + formItem.ValidationExpression = regexValidator; + } + + this.userForm.Items.Add(formItem); + } + + private void AddPasswordStrengthField(string dataField, string dataMember, bool required) + { + DnnFormItemBase formItem; + + if (Host.EnableStrengthMeter) + { + formItem = new DnnFormPasswordItem + { + TextBoxCssClass = PasswordStrengthTextBoxCssClass, + ContainerCssClass = "password-strength-container", + }; + } + else + { + formItem = new DnnFormTextBoxItem + { + TextMode = TextBoxMode.Password, + TextBoxCssClass = PasswordStrengthTextBoxCssClass, + }; + } + + formItem.ID = dataField; + formItem.DataField = dataField; + formItem.DataMember = dataMember; + formItem.Visible = true; + formItem.Required = required; + + this.userForm.Items.Add(formItem); + } + + private void AddPasswordConfirmField(string dataField, string dataMember, bool required) + { + var formItem = new DnnFormTextBoxItem + { + ID = dataField, + DataField = dataField, + DataMember = dataMember, + Visible = true, + Required = required, + TextMode = TextBoxMode.Password, + TextBoxCssClass = ConfirmPasswordTextBoxCssClass, + ClearContentInPasswordMode = true, + MaxLength = 39, + }; + this.userForm.Items.Add(formItem); + } + + private void AddProperty(ProfilePropertyDefinition property) + { + if (this.userForm.Items.Any(i => i.ID == property.PropertyName)) + { + return; + } + + var controller = new ListController(); + ListEntryInfo imageType = controller.GetListEntryInfo("DataType", "Image"); + if (property.DataType != imageType.EntryID) + { + DnnFormEditControlItem formItem = new DnnFormEditControlItem + { + ID = property.PropertyName, + ResourceKey = string.Format("ProfileProperties_{0}", property.PropertyName), + LocalResourceFile = "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx.resx", + ValidationMessageSuffix = ".Validation", + ControlType = EditorInfo.GetEditor(property.DataType), + DataMember = "Profile", + DataField = property.PropertyName, + Visible = property.Visible, + Required = property.Required, + }; + + // To check if the property has a deafult value + if (!string.IsNullOrEmpty(property.DefaultValue)) + { + formItem.Value = property.DefaultValue; + } + + if (!string.IsNullOrEmpty(property.ValidationExpression)) + { + formItem.ValidationExpression = property.ValidationExpression; + } + + this.userForm.Items.Add(formItem); + } + } + + private void BindLoginControl(AuthenticationLoginBase authLoginControl, AuthenticationInfo authSystem) + { + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + authLoginControl.AuthenticationType = authSystem.AuthenticationType; + authLoginControl.ID = Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc) + "_" + authSystem.AuthenticationType; + authLoginControl.LocalResourceFile = authLoginControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + + Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc); + authLoginControl.RedirectURL = this.GetRedirectUrl(); + authLoginControl.ModuleConfiguration = this.ModuleConfiguration; + + authLoginControl.UserAuthenticated += this.UserAuthenticated; } - #region Protected Properties - - protected string AuthenticationType - { - get - { - return ViewState.GetValue("AuthenticationType", Null.NullString); - } - set - { - ViewState.SetValue("AuthenticationType", value, Null.NullString); - } - } - - protected UserCreateStatus CreateStatus { get; set; } - - protected string ExcludeTerms - { - get - { - string regex = String.Empty; - if (!String.IsNullOrEmpty(PortalSettings.Registration.ExcludeTerms)) - { - regex = @"^(?:(?!" + PortalSettings.Registration.ExcludeTerms.Replace(" ", "").Replace(",", "|") + @").)*$\r?\n?"; - } - return regex; - } - } - - protected bool IsValid - { - get - { - return Validate(); - } - } - - protected string UserToken - { - get - { - return ViewState.GetValue("UserToken", string.Empty); - } - set - { - ViewState.SetValue("UserToken", value, string.Empty); - } - } - - protected override bool AddUser { get; } = true; - - #endregion - - #region Event Handlers - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); - - if (PortalSettings.Registration.RegistrationFormType == 0) - { - //DisplayName - if (String.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) - { - AddField("DisplayName", String.Empty, true, String.Empty, TextBoxMode.SingleLine); - } - else - { - AddField("FirstName", String.Empty, true, String.Empty, TextBoxMode.SingleLine); - AddField("LastName", String.Empty, true, String.Empty, TextBoxMode.SingleLine); - } - - //Email - AddField("Email", String.Empty, true, PortalSettings.Registration.EmailValidator, TextBoxMode.SingleLine); - - //UserName - if (!PortalSettings.Registration.UseEmailAsUserName) - { - - AddField("Username", String.Empty, true, - String.IsNullOrEmpty(PortalSettings.Registration.UserNameValidator) ? ExcludeTerms : PortalSettings.Registration.UserNameValidator, - TextBoxMode.SingleLine); - } - - //Password - if (!PortalSettings.Registration.RandomPassword) - { - AddPasswordStrengthField("Password", "Membership", true); - - if (PortalSettings.Registration.RequirePasswordConfirm) - { - AddPasswordConfirmField("PasswordConfirm", "Membership", true); - } - } - - //Password Q&A - if (MembershipProviderConfig.RequiresQuestionAndAnswer) - { - AddField("PasswordQuestion", "Membership", true, String.Empty, TextBoxMode.SingleLine); - AddField("PasswordAnswer", "Membership", true, String.Empty, TextBoxMode.SingleLine); - } - - if (PortalSettings.Registration.RequireValidProfile) - { - foreach (ProfilePropertyDefinition property in User.Profile.ProfileProperties) - { - if (property.Required) - { - AddProperty(property); - } - } - } - } - else - { - var fields = PortalSettings.Registration.RegistrationFields.Split(',').ToList(); - //append question/answer field when RequiresQuestionAndAnswer is enabled in config. - if (MembershipProviderConfig.RequiresQuestionAndAnswer) - { - if (!fields.Contains("PasswordQuestion")) - { - fields.Add("PasswordQuestion"); - } - if (!fields.Contains("PasswordAnswer")) - { - fields.Add("PasswordAnswer"); - } - } - - foreach (string field in fields) - { - var trimmedField = field.Trim(); - switch (trimmedField) - { - case "Username": - AddField("Username", String.Empty, true, String.IsNullOrEmpty(PortalSettings.Registration.UserNameValidator) - ? ExcludeTerms : PortalSettings.Registration.UserNameValidator, - TextBoxMode.SingleLine); - break; - case "DisplayName": - AddField(trimmedField, String.Empty, true, ExcludeTerms, TextBoxMode.SingleLine); - break; - case "Email": - AddField("Email", String.Empty, true, PortalSettings.Registration.EmailValidator, TextBoxMode.SingleLine); - break; - case "Password": - AddPasswordStrengthField(trimmedField, "Membership", true); - break; - case "PasswordConfirm": - AddPasswordConfirmField(trimmedField, "Membership", true); - break; - case "PasswordQuestion": - case "PasswordAnswer": - AddField(trimmedField, "Membership", true, String.Empty, TextBoxMode.SingleLine); - break; - default: - ProfilePropertyDefinition property = User.Profile.GetProperty(trimmedField); - if (property != null) - { - AddProperty(property); - } - break; - } - } - } - - //Verify that the current user has access to this page - if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && Request.IsAuthenticated == false) - { - try - { - Response.Redirect(_navigationManager.NavigateURL("Access Denied"), true); - } - catch (ThreadAbortException) - { - //do nothing here. - } - } - - cancelLink.NavigateUrl = closeLink.NavigateUrl = GetRedirectUrl(false); - registerButton.Click += registerButton_Click; - - if (PortalSettings.Registration.UseAuthProviders) - { - List authSystems = AuthenticationController.GetEnabledAuthenticationServices(); - foreach (AuthenticationInfo authSystem in authSystems) - { - try - { - var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc); - if (authSystem.AuthenticationType != "DNN") - { - BindLoginControl(authLoginControl, authSystem); - //Check if AuthSystem is Enabled - if (authLoginControl.Enabled && authLoginControl.SupportsRegistration) - { - authLoginControl.Mode = AuthMode.Register; - - //Add Login Control to List - _loginControls.Add(authLoginControl); - } - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - } - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - if (Request.IsAuthenticated) - { - //if a Login Page has not been specified for the portal - if (Globals.IsAdminControl()) - { - //redirect to current page - Response.Redirect(_navigationManager.NavigateURL(), true); - } - else //make module container invisible if user is not a page admin - { - if (!TabPermissionController.CanAdminPage()) - { - ContainerControl.Visible = false; - } - } - } - - if (PortalSettings.Registration.UseCaptcha) - { - captchaRow.Visible = true; - ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", LocalResourceFile); - ctlCaptcha.Text = Localization.GetString("CaptchaText", LocalResourceFile); - } - - if (PortalSettings.Registration.UseAuthProviders && String.IsNullOrEmpty(AuthenticationType)) - { - foreach (AuthenticationLoginBase authLoginControl in _loginControls) - { - socialLoginControls.Controls.Add(authLoginControl); - } - } - - //Display relevant message - userHelpLabel.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS"); - switch (PortalSettings.UserRegistration) - { - case (int)Globals.PortalRegistrationType.PrivateRegistration: - userHelpLabel.Text += Localization.GetString("PrivateMembership", Localization.SharedResourceFile); - break; - case (int)Globals.PortalRegistrationType.PublicRegistration: - userHelpLabel.Text += Localization.GetString("PublicMembership", Localization.SharedResourceFile); - break; - case (int)Globals.PortalRegistrationType.VerifiedRegistration: - userHelpLabel.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile); - break; - } - userHelpLabel.Text += Localization.GetString("Required", LocalResourceFile); - userHelpLabel.Text += Localization.GetString("RegisterWarning", LocalResourceFile); - - userForm.DataSource = User; - if (!Page.IsPostBack) - { - userForm.DataBind(); - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - var confirmPasswordOptions = new DnnConfirmPasswordOptions() - { - FirstElementSelector = "." + PasswordStrengthTextBoxCssClass, - SecondElementSelector = "." + ConfirmPasswordTextBoxCssClass, - ContainerSelector = ".dnnRegistrationForm", - UnmatchedCssClass = "unmatched", - MatchedCssClass = "matched" - }; - - var optionsAsJsonString = Json.Serialize(confirmPasswordOptions); - var script = string.Format("dnn.initializePasswordComparer({0});{1}", optionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "ConfirmPassword", script, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "ConfirmPassword", script, true); - } - - } - - #endregion - - #region Private Methods - - private void AddField(string dataField, string dataMember, bool required, string regexValidator, TextBoxMode textMode) - { - if (userForm.Items.Any(i => i.ID == dataField)) - { - return; - } - - var formItem = new DnnFormTextBoxItem - { - ID = dataField, - DataField = dataField, - DataMember = dataMember, - Visible = true, - Required = required, - TextMode = textMode - }; - if (!String.IsNullOrEmpty(regexValidator)) - { - formItem.ValidationExpression = regexValidator; - } - userForm.Items.Add(formItem); - } - - private void AddPasswordStrengthField(string dataField, string dataMember, bool required) - { - DnnFormItemBase formItem; - - if (Host.EnableStrengthMeter) - { - formItem = new DnnFormPasswordItem - { - TextBoxCssClass = PasswordStrengthTextBoxCssClass, - ContainerCssClass = "password-strength-container" - }; - } - else - { - formItem = new DnnFormTextBoxItem - { - TextMode = TextBoxMode.Password, - TextBoxCssClass = PasswordStrengthTextBoxCssClass, - }; - } - - formItem.ID = dataField; - formItem.DataField = dataField; - formItem.DataMember = dataMember; - formItem.Visible = true; - formItem.Required = required; - - userForm.Items.Add(formItem); - - } - - private void AddPasswordConfirmField(string dataField, string dataMember, bool required) - { - - var formItem = new DnnFormTextBoxItem - { - ID = dataField, - DataField = dataField, - DataMember = dataMember, - Visible = true, - Required = required, - TextMode = TextBoxMode.Password, - TextBoxCssClass = ConfirmPasswordTextBoxCssClass, - ClearContentInPasswordMode = true, - MaxLength = 39 - }; - userForm.Items.Add(formItem); - - } - - private void AddProperty(ProfilePropertyDefinition property) - { - if (userForm.Items.Any(i => i.ID == property.PropertyName)) - { - return; - } - - var controller = new ListController(); - ListEntryInfo imageType = controller.GetListEntryInfo("DataType", "Image"); - if (property.DataType != imageType.EntryID) - { - DnnFormEditControlItem formItem = new DnnFormEditControlItem - { - ID = property.PropertyName, - ResourceKey = String.Format("ProfileProperties_{0}", property.PropertyName), - LocalResourceFile = "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx.resx", - ValidationMessageSuffix = ".Validation", - ControlType = EditorInfo.GetEditor(property.DataType), - DataMember = "Profile", - DataField = property.PropertyName, - Visible = property.Visible, - Required = property.Required - }; - //To check if the property has a deafult value - if (!String.IsNullOrEmpty(property.DefaultValue)) - { - formItem.Value = property.DefaultValue; - } - if (!String.IsNullOrEmpty(property.ValidationExpression)) - { - formItem.ValidationExpression = property.ValidationExpression; - } - userForm.Items.Add(formItem); - } - - } - - private void BindLoginControl(AuthenticationLoginBase authLoginControl, AuthenticationInfo authSystem) - { - //set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - //this is necessary for the Localization in PageBase - authLoginControl.AuthenticationType = authSystem.AuthenticationType; - authLoginControl.ID = Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc) + "_" + authSystem.AuthenticationType; - authLoginControl.LocalResourceFile = authLoginControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + - Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc); - authLoginControl.RedirectURL = GetRedirectUrl(); - authLoginControl.ModuleConfiguration = ModuleConfiguration; - - authLoginControl.UserAuthenticated += UserAuthenticated; - } - - private void CreateUser() - { - //Update DisplayName to conform to Format - UpdateDisplayName(); - - User.Membership.Approved = PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration; - var user = User; - CreateStatus = UserController.CreateUser(ref user); - - DataCache.ClearPortalUserCountCache(PortalId); + private void CreateUser() + { + // Update DisplayName to conform to Format + this.UpdateDisplayName(); + + this.User.Membership.Approved = this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration; + var user = this.User; + this.CreateStatus = UserController.CreateUser(ref user); + + DataCache.ClearPortalUserCountCache(this.PortalId); try - { - if (CreateStatus == UserCreateStatus.Success) - { - //hide the succesful captcha - captchaRow.Visible = false; - - //Assocate alternate Login with User and proceed with Login - if (!String.IsNullOrEmpty(AuthenticationType)) - { - AuthenticationController.AddUserAuthentication(User.UserID, AuthenticationType, UserToken); - } - - string strMessage = CompleteUserCreation(CreateStatus, user, true, IsRegister); - - if ((string.IsNullOrEmpty(strMessage))) - { - Response.Redirect(GetRedirectUrl(), true); - } - else - { - RegistrationForm.Visible = false; - registerButton.Visible = false; - closeLink.Visible = true; - } - } - else - { - AddLocalizedModuleMessage(UserController.GetUserCreateStatus(CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); - } - } - catch (Exception exc) //Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - private void UpdateDisplayName() - { - //Update DisplayName to conform to Format - if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) - { - User.UpdateDisplayName(PortalSettings.Registration.DisplayNameFormat); - } - } - - private bool Validate() - { - if (!string.IsNullOrEmpty(gotcha.Value)) - { - return false; - } - - CreateStatus = UserCreateStatus.AddUser; - var portalSecurity = PortalSecurity.Instance; - - //Check User Editor - bool _IsValid = userForm.IsValid; - - if (_IsValid) + { + if (this.CreateStatus == UserCreateStatus.Success) + { + // hide the succesful captcha + this.captchaRow.Visible = false; + + // Assocate alternate Login with User and proceed with Login + if (!string.IsNullOrEmpty(this.AuthenticationType)) + { + AuthenticationController.AddUserAuthentication(this.User.UserID, this.AuthenticationType, this.UserToken); + } + + string strMessage = this.CompleteUserCreation(this.CreateStatus, user, true, this.IsRegister); + + if (string.IsNullOrEmpty(strMessage)) + { + this.Response.Redirect(this.GetRedirectUrl(), true); + } + else + { + this.RegistrationForm.Visible = false; + this.registerButton.Visible = false; + this.closeLink.Visible = true; + } + } + else + { + this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(this.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + private void UpdateDisplayName() + { + // Update DisplayName to conform to Format + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) + { + this.User.UpdateDisplayName(this.PortalSettings.Registration.DisplayNameFormat); + } + } + + private bool Validate() + { + if (!string.IsNullOrEmpty(this.gotcha.Value)) + { + return false; + } + + this.CreateStatus = UserCreateStatus.AddUser; + var portalSecurity = PortalSecurity.Instance; + + // Check User Editor + bool _IsValid = this.userForm.IsValid; + + if (_IsValid) { var filterFlags = PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup; - var name = User.Username ?? User.Email; + var name = this.User.Username ?? this.User.Email; var cleanUsername = PortalSecurity.Instance.InputFilter(name, filterFlags); if (!cleanUsername.Equals(name)) { - CreateStatus = UserCreateStatus.InvalidUserName; + this.CreateStatus = UserCreateStatus.InvalidUserName; } - var valid = UserController.Instance.IsValidUserName(name); + + var valid = UserController.Instance.IsValidUserName(name); if (!valid) { - CreateStatus = UserCreateStatus.InvalidUserName; - } - - var cleanEmail = PortalSecurity.Instance.InputFilter(User.Email, filterFlags); - if (!cleanEmail.Equals(User.Email)) - { - CreateStatus = UserCreateStatus.InvalidEmail; - } - - var cleanFirstName = PortalSecurity.Instance.InputFilter(User.FirstName, filterFlags); - if (!cleanFirstName.Equals(User.FirstName)) - { - CreateStatus = UserCreateStatus.InvalidFirstName; - } - - var cleanLastName = PortalSecurity.Instance.InputFilter(User.LastName, filterFlags); - if (!cleanLastName.Equals(User.LastName)) - { - CreateStatus = UserCreateStatus.InvalidLastName; - } - if (string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) - { - var cleanDisplayName = PortalSecurity.Instance.InputFilter(User.DisplayName, filterFlags); - if (!cleanDisplayName.Equals(User.DisplayName)) - { - CreateStatus = UserCreateStatus.InvalidDisplayName; - } - } - } - - if (PortalSettings.Registration.RegistrationFormType == 0) - { - //Update UserName - if (PortalSettings.Registration.UseEmailAsUserName) - { - User.Username = User.Email; - if (String.IsNullOrEmpty(User.DisplayName)) - { - User.DisplayName = User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal)); - } - } - - //Check Password is valid - if (!PortalSettings.Registration.RandomPassword) - { - //Check Password is Valid - if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(User.Membership.Password)) - { - CreateStatus = UserCreateStatus.InvalidPassword; - } - - if (PortalSettings.Registration.RequirePasswordConfirm && String.IsNullOrEmpty(AuthenticationType)) - { - if (User.Membership.Password != User.Membership.PasswordConfirm) - { - CreateStatus = UserCreateStatus.PasswordMismatch; - } - } - } - else - { - //Generate a random password for the user - User.Membership.Password = UserController.GeneratePassword(); - User.Membership.PasswordConfirm = User.Membership.Password; - } - - } - else - { - //Set Username to Email - if (String.IsNullOrEmpty(User.Username)) - { - User.Username = User.Email; - } - - //Set DisplayName - if (String.IsNullOrEmpty(User.DisplayName)) - { - User.DisplayName = String.IsNullOrEmpty(User.FirstName + " " + User.LastName) - ? User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal)) - : User.FirstName + " " + User.LastName; - } - - //Random Password - if (String.IsNullOrEmpty(User.Membership.Password)) - { - //Generate a random password for the user - User.Membership.Password = UserController.GeneratePassword(); - } - - //Password Confirm - if (!String.IsNullOrEmpty(User.Membership.PasswordConfirm)) - { - if (User.Membership.Password != User.Membership.PasswordConfirm) - { - CreateStatus = UserCreateStatus.PasswordMismatch; - } - } - } - - //Validate banned password - var settings = new MembershipPasswordSettings(User.PortalID); - - if (settings.EnableBannedList) - { - var m = new MembershipPasswordController(); - if (m.FoundBannedPassword(User.Membership.Password) || User.Username == User.Membership.Password) - { - CreateStatus = UserCreateStatus.BannedPasswordUsed; - } - - } - //Validate Profanity - if (PortalSettings.Registration.UseProfanityFilter) - { - if (!portalSecurity.ValidateInput(User.Username, PortalSecurity.FilterFlag.NoProfanity)) - { - CreateStatus = UserCreateStatus.InvalidUserName; - } - if (!String.IsNullOrEmpty(User.DisplayName)) - { - if (!portalSecurity.ValidateInput(User.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) - { - CreateStatus = UserCreateStatus.InvalidDisplayName; - } - } - } - - //Validate Unique User Name - UserInfo user = UserController.GetUserByName(PortalId, User.Username); - if (user != null) - { - if (PortalSettings.Registration.UseEmailAsUserName) - { - CreateStatus = UserCreateStatus.DuplicateEmail; - } - else - { - CreateStatus = UserCreateStatus.DuplicateUserName; - int i = 1; - string userName = null; - while (user != null) - { - userName = User.Username + "0" + i.ToString(CultureInfo.InvariantCulture); - user = UserController.GetUserByName(PortalId, userName); - i++; - } - User.Username = userName; - } - } - - //Validate Unique Display Name - if (CreateStatus == UserCreateStatus.AddUser && PortalSettings.Registration.RequireUniqueDisplayName) - { - user = UserController.Instance.GetUserByDisplayname(PortalId, User.DisplayName); - if (user != null) - { - CreateStatus = UserCreateStatus.DuplicateDisplayName; - int i = 1; - string displayName = null; - while (user != null) - { - displayName = User.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture); - user = UserController.Instance.GetUserByDisplayname(PortalId, displayName); - i++; - } - User.DisplayName = displayName; - } - } - - //Check Question/Answer - if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) - { - if (string.IsNullOrEmpty(User.Membership.PasswordQuestion)) - { - //Invalid Question - CreateStatus = UserCreateStatus.InvalidQuestion; - } - if (CreateStatus == UserCreateStatus.AddUser) - { - if (string.IsNullOrEmpty(User.Membership.PasswordAnswer)) - { - //Invalid Question - CreateStatus = UserCreateStatus.InvalidAnswer; - } - } - } - - if (CreateStatus != UserCreateStatus.AddUser) - { - _IsValid = false; - } - return _IsValid; - } + this.CreateStatus = UserCreateStatus.InvalidUserName; + } + + var cleanEmail = PortalSecurity.Instance.InputFilter(this.User.Email, filterFlags); + if (!cleanEmail.Equals(this.User.Email)) + { + this.CreateStatus = UserCreateStatus.InvalidEmail; + } + + var cleanFirstName = PortalSecurity.Instance.InputFilter(this.User.FirstName, filterFlags); + if (!cleanFirstName.Equals(this.User.FirstName)) + { + this.CreateStatus = UserCreateStatus.InvalidFirstName; + } + + var cleanLastName = PortalSecurity.Instance.InputFilter(this.User.LastName, filterFlags); + if (!cleanLastName.Equals(this.User.LastName)) + { + this.CreateStatus = UserCreateStatus.InvalidLastName; + } + + if (string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) + { + var cleanDisplayName = PortalSecurity.Instance.InputFilter(this.User.DisplayName, filterFlags); + if (!cleanDisplayName.Equals(this.User.DisplayName)) + { + this.CreateStatus = UserCreateStatus.InvalidDisplayName; + } + } + } + + if (this.PortalSettings.Registration.RegistrationFormType == 0) + { + // Update UserName + if (this.PortalSettings.Registration.UseEmailAsUserName) + { + this.User.Username = this.User.Email; + if (string.IsNullOrEmpty(this.User.DisplayName)) + { + this.User.DisplayName = this.User.Email.Substring(0, this.User.Email.IndexOf("@", StringComparison.Ordinal)); + } + } + + // Check Password is valid + if (!this.PortalSettings.Registration.RandomPassword) + { + // Check Password is Valid + if (this.CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(this.User.Membership.Password)) + { + this.CreateStatus = UserCreateStatus.InvalidPassword; + } + + if (this.PortalSettings.Registration.RequirePasswordConfirm && string.IsNullOrEmpty(this.AuthenticationType)) + { + if (this.User.Membership.Password != this.User.Membership.PasswordConfirm) + { + this.CreateStatus = UserCreateStatus.PasswordMismatch; + } + } + } + else + { + // Generate a random password for the user + this.User.Membership.Password = UserController.GeneratePassword(); + this.User.Membership.PasswordConfirm = this.User.Membership.Password; + } + } + else + { + // Set Username to Email + if (string.IsNullOrEmpty(this.User.Username)) + { + this.User.Username = this.User.Email; + } + + // Set DisplayName + if (string.IsNullOrEmpty(this.User.DisplayName)) + { + this.User.DisplayName = string.IsNullOrEmpty(this.User.FirstName + " " + this.User.LastName) + ? this.User.Email.Substring(0, this.User.Email.IndexOf("@", StringComparison.Ordinal)) + : this.User.FirstName + " " + this.User.LastName; + } + + // Random Password + if (string.IsNullOrEmpty(this.User.Membership.Password)) + { + // Generate a random password for the user + this.User.Membership.Password = UserController.GeneratePassword(); + } + + // Password Confirm + if (!string.IsNullOrEmpty(this.User.Membership.PasswordConfirm)) + { + if (this.User.Membership.Password != this.User.Membership.PasswordConfirm) + { + this.CreateStatus = UserCreateStatus.PasswordMismatch; + } + } + } + + // Validate banned password + var settings = new MembershipPasswordSettings(this.User.PortalID); + + if (settings.EnableBannedList) + { + var m = new MembershipPasswordController(); + if (m.FoundBannedPassword(this.User.Membership.Password) || this.User.Username == this.User.Membership.Password) + { + this.CreateStatus = UserCreateStatus.BannedPasswordUsed; + } + } + + // Validate Profanity + if (this.PortalSettings.Registration.UseProfanityFilter) + { + if (!portalSecurity.ValidateInput(this.User.Username, PortalSecurity.FilterFlag.NoProfanity)) + { + this.CreateStatus = UserCreateStatus.InvalidUserName; + } + + if (!string.IsNullOrEmpty(this.User.DisplayName)) + { + if (!portalSecurity.ValidateInput(this.User.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) + { + this.CreateStatus = UserCreateStatus.InvalidDisplayName; + } + } + } + + // Validate Unique User Name + UserInfo user = UserController.GetUserByName(this.PortalId, this.User.Username); + if (user != null) + { + if (this.PortalSettings.Registration.UseEmailAsUserName) + { + this.CreateStatus = UserCreateStatus.DuplicateEmail; + } + else + { + this.CreateStatus = UserCreateStatus.DuplicateUserName; + int i = 1; + string userName = null; + while (user != null) + { + userName = this.User.Username + "0" + i.ToString(CultureInfo.InvariantCulture); + user = UserController.GetUserByName(this.PortalId, userName); + i++; + } + + this.User.Username = userName; + } + } + + // Validate Unique Display Name + if (this.CreateStatus == UserCreateStatus.AddUser && this.PortalSettings.Registration.RequireUniqueDisplayName) + { + user = UserController.Instance.GetUserByDisplayname(this.PortalId, this.User.DisplayName); + if (user != null) + { + this.CreateStatus = UserCreateStatus.DuplicateDisplayName; + int i = 1; + string displayName = null; + while (user != null) + { + displayName = this.User.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture); + user = UserController.Instance.GetUserByDisplayname(this.PortalId, displayName); + i++; + } + + this.User.DisplayName = displayName; + } + } + + // Check Question/Answer + if (this.CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) + { + if (string.IsNullOrEmpty(this.User.Membership.PasswordQuestion)) + { + // Invalid Question + this.CreateStatus = UserCreateStatus.InvalidQuestion; + } + + if (this.CreateStatus == UserCreateStatus.AddUser) + { + if (string.IsNullOrEmpty(this.User.Membership.PasswordAnswer)) + { + // Invalid Question + this.CreateStatus = UserCreateStatus.InvalidAnswer; + } + } + } + + if (this.CreateStatus != UserCreateStatus.AddUser) + { + _IsValid = false; + } + + return _IsValid; + } private string GetRedirectUrl(bool checkSetting = true) - { - var redirectUrl = ""; - var redirectAfterRegistration = PortalSettings.Registration.RedirectAfterRegistration; - if (checkSetting && redirectAfterRegistration > 0) //redirect to after registration page - { - redirectUrl = _navigationManager.NavigateURL(redirectAfterRegistration); - } - else - { - if (Request.QueryString["returnurl"] != null) - { - //return to the url passed to register - redirectUrl = HttpUtility.UrlDecode(Request.QueryString["returnurl"]); - - //clean the return url to avoid possible XSS attack. + { + var redirectUrl = string.Empty; + var redirectAfterRegistration = this.PortalSettings.Registration.RedirectAfterRegistration; + if (checkSetting && redirectAfterRegistration > 0) // redirect to after registration page + { + redirectUrl = this._navigationManager.NavigateURL(redirectAfterRegistration); + } + else + { + if (this.Request.QueryString["returnurl"] != null) + { + // return to the url passed to register + redirectUrl = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); + + // clean the return url to avoid possible XSS attack. redirectUrl = UrlUtils.ValidReturnUrl(redirectUrl); if (redirectUrl.Contains("?returnurl")) - { - string baseURL = redirectUrl.Substring(0, - redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); - string returnURL = - redirectUrl.Substring(redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal) + 11); - - redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); - } - } - if (String.IsNullOrEmpty(redirectUrl)) - { - //redirect to current page - redirectUrl = _navigationManager.NavigateURL(); - } - } - - return redirectUrl; - } - - private void registerButton_Click(object sender, EventArgs e) - { - if ((PortalSettings.Registration.UseCaptcha && ctlCaptcha.IsValid) || !PortalSettings.Registration.UseCaptcha) - { - if (IsValid) - { - if (PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) { - CreateUser(); + string baseURL = redirectUrl.Substring( + 0, + redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); + string returnURL = + redirectUrl.Substring(redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal) + 11); + + redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); + } + } + + if (string.IsNullOrEmpty(redirectUrl)) + { + // redirect to current page + redirectUrl = this._navigationManager.NavigateURL(); + } + } + + return redirectUrl; + } + + private void registerButton_Click(object sender, EventArgs e) + { + if ((this.PortalSettings.Registration.UseCaptcha && this.ctlCaptcha.IsValid) || !this.PortalSettings.Registration.UseCaptcha) + { + if (this.IsValid) + { + if (this.PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) + { + this.CreateUser(); + } + } + else + { + if (this.CreateStatus != UserCreateStatus.AddUser) + { + this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(this.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); } + } + } + } + + private void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) + { + NameValueCollection profileProperties = e.Profile; + + this.User.Username = e.UserToken; + this.AuthenticationType = e.AuthenticationType; + this.UserToken = e.UserToken; + + foreach (string key in profileProperties) + { + switch (key) + { + case "FirstName": + this.User.FirstName = profileProperties[key]; + break; + case "LastName": + this.User.LastName = profileProperties[key]; + break; + case "Email": + this.User.Email = profileProperties[key]; + break; + case "DisplayName": + this.User.DisplayName = profileProperties[key]; + break; + default: + this.User.Profile.SetProfileProperty(key, profileProperties[key]); + break; + } + } - } - else - { - if (CreateStatus != UserCreateStatus.AddUser) - { - AddLocalizedModuleMessage(UserController.GetUserCreateStatus(CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); - } - } - } - } - - private void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) - { - NameValueCollection profileProperties = e.Profile; - - User.Username = e.UserToken; - AuthenticationType = e.AuthenticationType; - UserToken = e.UserToken; - - foreach (string key in profileProperties) - { - switch (key) - { - case "FirstName": - User.FirstName = profileProperties[key]; - break; - case "LastName": - User.LastName = profileProperties[key]; - break; - case "Email": - User.Email = profileProperties[key]; - break; - case "DisplayName": - User.DisplayName = profileProperties[key]; - break; - default: - User.Profile.SetProfileProperty(key, profileProperties[key]); - break; - } - } - - //Generate a random password for the user - User.Membership.Password = UserController.GeneratePassword(); - - if (!String.IsNullOrEmpty(User.Email)) - { - CreateUser(); - } - else - { - AddLocalizedModuleMessage(LocalizeString("NoEmail"), ModuleMessage.ModuleMessageType.RedError, true); - foreach (DnnFormItemBase formItem in userForm.Items) - { - formItem.Visible = formItem.DataField == "Email"; - } - userForm.DataBind(); - } - } - - #endregion - } + // Generate a random password for the user + this.User.Membership.Password = UserController.GeneratePassword(); + + if (!string.IsNullOrEmpty(this.User.Email)) + { + this.CreateUser(); + } + else + { + this.AddLocalizedModuleMessage(this.LocalizeString("NoEmail"), ModuleMessage.ModuleMessageType.RedError, true); + foreach (DnnFormItemBase formItem in this.userForm.Items) + { + formItem.Visible = formItem.DataField == "Email"; + } + + this.userForm.DataBind(); + } + } + } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs index a072c1c1b61..f84cb3a13c9 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs @@ -1,53 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Web.UI; -using System.Web.UI.WebControls; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.UI.Utilities; -using Microsoft.Extensions.DependencyInjection; - -using Calendar = DotNetNuke.Common.Utilities.Calendar; -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Security { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.UI.Utilities; + using Microsoft.Extensions.DependencyInjection; + + using Calendar = DotNetNuke.Common.Utilities.Calendar; + using Globals = DotNetNuke.Common.Globals; + /// ----------------------------------------------------------------------------- /// /// The SecurityRoles PortalModuleBase is used to manage the users and roles they - /// have + /// have. /// /// /// /// ----------------------------------------------------------------------------- public partial class SecurityRoles : PortalModuleBase, IActionable { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SecurityRoles)); - private readonly INavigationManager _navigationManager; - #region "Private Members" - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SecurityRoles)); + private readonly INavigationManager _navigationManager; private int RoleId = Null.NullInteger; private new int UserId = Null.NullInteger; private RoleInfo _Role; @@ -55,20 +49,33 @@ public partial class SecurityRoles : PortalModuleBase, IActionable private UserInfo _User; private int _totalPages = 1; - private int _totalRecords; - - #endregion - + private int _totalRecords; + public SecurityRoles() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region "Protected Members" - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the ParentModule (if one exists). + /// + /// + /// + /// ----------------------------------------------------------------------------- + public PortalModuleBase ParentModule { get; set; } + + public ModuleActionCollection ModuleActions + { + get + { + return new ModuleActionCollection(); + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets the Return Url for the page + /// Gets the Return Url for the page. /// /// ----------------------------------------------------------------------------- protected string ReturnUrl @@ -76,27 +83,29 @@ protected string ReturnUrl get { string _ReturnURL; - var FilterParams = new string[String.IsNullOrEmpty(Request.QueryString["filterproperty"]) ? 2 : 3]; + var FilterParams = new string[string.IsNullOrEmpty(this.Request.QueryString["filterproperty"]) ? 2 : 3]; - if (String.IsNullOrEmpty(Request.QueryString["filterProperty"])) + if (string.IsNullOrEmpty(this.Request.QueryString["filterProperty"])) { - FilterParams.SetValue("filter=" + Request.QueryString["filter"], 0); - FilterParams.SetValue("currentpage=" + Request.QueryString["currentpage"], 1); + FilterParams.SetValue("filter=" + this.Request.QueryString["filter"], 0); + FilterParams.SetValue("currentpage=" + this.Request.QueryString["currentpage"], 1); } else { - FilterParams.SetValue("filter=" + Request.QueryString["filter"], 0); - FilterParams.SetValue("filterProperty=" + Request.QueryString["filterProperty"], 1); - FilterParams.SetValue("currentpage=" + Request.QueryString["currentpage"], 2); + FilterParams.SetValue("filter=" + this.Request.QueryString["filter"], 0); + FilterParams.SetValue("filterProperty=" + this.Request.QueryString["filterProperty"], 1); + FilterParams.SetValue("currentpage=" + this.Request.QueryString["currentpage"], 2); } - if (string.IsNullOrEmpty(Request.QueryString["filter"])) + + if (string.IsNullOrEmpty(this.Request.QueryString["filter"])) { - _ReturnURL = _navigationManager.NavigateURL(TabId); + _ReturnURL = this._navigationManager.NavigateURL(this.TabId); } else { - _ReturnURL = _navigationManager.NavigateURL(TabId, "", FilterParams); + _ReturnURL = this._navigationManager.NavigateURL(this.TabId, string.Empty, FilterParams); } + return _ReturnURL; } } @@ -105,18 +114,19 @@ protected RoleInfo Role { get { - if (_Role == null) + if (this._Role == null) { - if (RoleId != Null.NullInteger) + if (this.RoleId != Null.NullInteger) { - _Role = RoleController.Instance.GetRole(PortalId, r => r.RoleID == RoleId); ; + this._Role = RoleController.Instance.GetRole(this.PortalId, r => r.RoleID == this.RoleId); } - else if (cboRoles.SelectedItem != null) + else if (this.cboRoles.SelectedItem != null) { - _Role = RoleController.Instance.GetRole(PortalId, r => r.RoleID == Convert.ToInt32(cboRoles.SelectedItem.Value)); + this._Role = RoleController.Instance.GetRole(this.PortalId, r => r.RoleID == Convert.ToInt32(this.cboRoles.SelectedItem.Value)); } } - return _Role; + + return this._Role; } } @@ -124,22 +134,23 @@ protected UserInfo User { get { - if (_User == null) + if (this._User == null) { - if (UserId != Null.NullInteger) + if (this.UserId != Null.NullInteger) { - _User = UserController.GetUserById(PortalId, UserId); + this._User = UserController.GetUserById(this.PortalId, this.UserId); } - else if (UsersControl == UsersControl.TextBox && !String.IsNullOrEmpty(txtUsers.Text)) + else if (this.UsersControl == UsersControl.TextBox && !string.IsNullOrEmpty(this.txtUsers.Text)) { - _User = UserController.GetUserByName(PortalId, txtUsers.Text); + this._User = UserController.GetUserByName(this.PortalId, this.txtUsers.Text); } - else if (UsersControl == UsersControl.Combo && (cboUsers.SelectedItem != null)) + else if (this.UsersControl == UsersControl.Combo && (this.cboUsers.SelectedItem != null)) { - _User = UserController.GetUserById(PortalId, Convert.ToInt32(cboUsers.SelectedItem.Value)); + this._User = UserController.GetUserById(this.PortalId, Convert.ToInt32(this.cboUsers.SelectedItem.Value)); } } - return _User; + + return this._User; } } @@ -147,24 +158,25 @@ protected int SelectedUserID { get { - return _SelectedUserID; + return this._SelectedUserID; } + set { - _SelectedUserID = value; + this._SelectedUserID = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the control should use a Combo Box or Text Box to display the users + /// Gets the control should use a Combo Box or Text Box to display the users. /// /// ----------------------------------------------------------------------------- protected UsersControl UsersControl { get { - var setting = UserModuleBase.GetSetting(PortalId, "Security_UsersControl"); + var setting = UserModuleBase.GetSetting(this.PortalId, "Security_UsersControl"); return (UsersControl)setting; } } @@ -175,172 +187,196 @@ protected int PageSize { get { - var setting = UserModuleBase.GetSetting(PortalId, "Records_PerPage"); + var setting = UserModuleBase.GetSetting(this.PortalId, "Records_PerPage"); return Convert.ToInt32(setting); } - } + } + + /// ----------------------------------------------------------------------------- + /// + /// DataBind binds the data to the controls. + /// + /// ----------------------------------------------------------------------------- + public override void DataBind() + { + if (!ModulePermissionController.CanEditModuleContent(this.ModuleConfiguration)) + { + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + } + + base.DataBind(); -#endregion + // Localize Headers + Localization.LocalizeDataGrid(ref this.grdUserRoles, this.LocalResourceFile); - #region "Public Properties" + // Bind the role data to the datalist + this.BindData(); + + this.BindGrid(); + } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ParentModule (if one exists) + /// DeleteButonVisible returns a boolean indicating if the delete button for + /// the specified UserID, RoleID pair should be shown. /// /// /// + /// The ID of the user to check delete button visibility for. + /// The ID of the role to check delete button visibility for. + /// /// ----------------------------------------------------------------------------- - public PortalModuleBase ParentModule { get; set; } - - #endregion - - #region IActionable Members - - public ModuleActionCollection ModuleActions + public bool DeleteButtonVisible(int UserID, int RoleID) { - get + // [DNN-4285] Check if the role can be removed (only handles case of Administrator and Administrator Role + bool canDelete = RoleController.CanRemoveUserFromRole(this.PortalSettings, UserID, RoleID); + if (RoleID == this.PortalSettings.AdministratorRoleId && canDelete) { - return new ModuleActionCollection(); + // User can only delete if in Admin role + canDelete = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); } + + return canDelete; } - - #endregion - - #region "Private Methods" - + /// ----------------------------------------------------------------------------- /// - /// BindData loads the controls from the Database + /// BindData loads the controls from the Database. /// /// /// /// ----------------------------------------------------------------------------- private void BindData() { - //bind all portal roles to dropdownlist - if (RoleId == Null.NullInteger) + // bind all portal roles to dropdownlist + if (this.RoleId == Null.NullInteger) { - if (cboRoles.Items.Count == 0) + if (this.cboRoles.Items.Count == 0) { - var roles = RoleController.Instance.GetRoles(PortalId, x => x.Status == RoleStatus.Approved); + var roles = RoleController.Instance.GetRoles(this.PortalId, x => x.Status == RoleStatus.Approved); - //Remove access to Admin Role if use is not a member of the role + // Remove access to Admin Role if use is not a member of the role int roleIndex = Null.NullInteger; foreach (RoleInfo tmpRole in roles) { - if (tmpRole.RoleName == PortalSettings.AdministratorRoleName) + if (tmpRole.RoleName == this.PortalSettings.AdministratorRoleName) { - if (!PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)) + if (!PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName)) { roleIndex = roles.IndexOf(tmpRole); } } + break; } + if (roleIndex > Null.NullInteger) { roles.RemoveAt(roleIndex); } - cboRoles.DataSource = roles; - cboRoles.DataBind(); + + this.cboRoles.DataSource = roles; + this.cboRoles.DataBind(); } } else { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - if (Role != null) + if (this.Role != null) { - //cboRoles.Items.Add(new ListItem(Role.RoleName, Role.RoleID.ToString())); - cboRoles.AddItem(Role.RoleName, Role.RoleID.ToString()); - cboRoles.Items[0].Selected = true; - lblTitle.Text = string.Format(Localization.GetString("RoleTitle.Text", LocalResourceFile), Role.RoleName, Role.RoleID); + // cboRoles.Items.Add(new ListItem(Role.RoleName, Role.RoleID.ToString())); + this.cboRoles.AddItem(this.Role.RoleName, this.Role.RoleID.ToString()); + this.cboRoles.Items[0].Selected = true; + this.lblTitle.Text = string.Format(Localization.GetString("RoleTitle.Text", this.LocalResourceFile), this.Role.RoleName, this.Role.RoleID); } - cboRoles.Visible = false; - plRoles.Visible = false; + + this.cboRoles.Visible = false; + this.plRoles.Visible = false; } } - //bind all portal users to dropdownlist - if (UserId == -1) + // bind all portal users to dropdownlist + if (this.UserId == -1) { - //Make sure user has enough permissions - if (Role.RoleName == PortalSettings.AdministratorRoleName && !PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)) + // Make sure user has enough permissions + if (this.Role.RoleName == this.PortalSettings.AdministratorRoleName && !PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName)) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NotAuthorized", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - pnlRoles.Visible = false; - pnlUserRoles.Visible = false; - chkNotify.Visible = false; + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NotAuthorized", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + this.pnlRoles.Visible = false; + this.pnlUserRoles.Visible = false; + this.chkNotify.Visible = false; return; } - if (UsersControl == UsersControl.Combo) + + if (this.UsersControl == UsersControl.Combo) { - if (cboUsers.Items.Count == 0) + if (this.cboUsers.Items.Count == 0) { - foreach (UserInfo objUser in UserController.GetUsers(PortalId)) + foreach (UserInfo objUser in UserController.GetUsers(this.PortalId)) { - //cboUsers.Items.Add(new ListItem(objUser.DisplayName + " (" + objUser.Username + ")", objUser.UserID.ToString())); - cboUsers.AddItem(objUser.DisplayName + " (" + objUser.Username + ")", objUser.UserID.ToString()); + // cboUsers.Items.Add(new ListItem(objUser.DisplayName + " (" + objUser.Username + ")", objUser.UserID.ToString())); + this.cboUsers.AddItem(objUser.DisplayName + " (" + objUser.Username + ")", objUser.UserID.ToString()); } } - txtUsers.Visible = false; - cboUsers.Visible = true; - cmdValidate.Visible = false; + + this.txtUsers.Visible = false; + this.cboUsers.Visible = true; + this.cmdValidate.Visible = false; } else { - txtUsers.Visible = true; - cboUsers.Visible = false; - cmdValidate.Visible = true; + this.txtUsers.Visible = true; + this.cboUsers.Visible = false; + this.cmdValidate.Visible = true; } } else { - if (User != null) + if (this.User != null) { - txtUsers.Text = User.UserID.ToString(); - lblTitle.Text = string.Format(Localization.GetString("UserTitle.Text", LocalResourceFile), User.Username, User.UserID); + this.txtUsers.Text = this.User.UserID.ToString(); + this.lblTitle.Text = string.Format(Localization.GetString("UserTitle.Text", this.LocalResourceFile), this.User.Username, this.User.UserID); } - txtUsers.Visible = false; - cboUsers.Visible = false; - cmdValidate.Visible = false; - plUsers.Visible = false; + + this.txtUsers.Visible = false; + this.cboUsers.Visible = false; + this.cmdValidate.Visible = false; + this.plUsers.Visible = false; } } /// ----------------------------------------------------------------------------- /// - /// BindGrid loads the data grid from the Database + /// BindGrid loads the data grid from the Database. /// /// /// /// ----------------------------------------------------------------------------- private void BindGrid() { - - - if (RoleId != Null.NullInteger) + if (this.RoleId != Null.NullInteger) { - cmdAdd.Text = Localization.GetString("AddUser.Text", LocalResourceFile); - grdUserRoles.DataKeyField = "UserId"; - grdUserRoles.Columns[2].Visible = false; + this.cmdAdd.Text = Localization.GetString("AddUser.Text", this.LocalResourceFile); + this.grdUserRoles.DataKeyField = "UserId"; + this.grdUserRoles.Columns[2].Visible = false; } - if (UserId != Null.NullInteger) + + if (this.UserId != Null.NullInteger) { - cmdAdd.Text = Localization.GetString("AddRole.Text", LocalResourceFile); - grdUserRoles.DataKeyField = "RoleId"; - grdUserRoles.Columns[1].Visible = false; + this.cmdAdd.Text = Localization.GetString("AddRole.Text", this.LocalResourceFile); + this.grdUserRoles.DataKeyField = "RoleId"; + this.grdUserRoles.Columns[1].Visible = false; } - grdUserRoles.DataSource = GetPagedDataSource(); - grdUserRoles.DataBind(); + this.grdUserRoles.DataSource = this.GetPagedDataSource(); + this.grdUserRoles.DataBind(); - ctlPagingControl.TotalRecords = _totalRecords; - ctlPagingControl.PageSize = PageSize; - ctlPagingControl.CurrentPage = CurrentPage; - ctlPagingControl.TabID = TabId; - ctlPagingControl.QuerystringParams = System.Web.HttpUtility.UrlDecode(string.Join("&", Request.QueryString.ToString().Split('&'). + this.ctlPagingControl.TotalRecords = this._totalRecords; + this.ctlPagingControl.PageSize = this.PageSize; + this.ctlPagingControl.CurrentPage = this.CurrentPage; + this.ctlPagingControl.TabID = this.TabId; + this.ctlPagingControl.QuerystringParams = System.Web.HttpUtility.UrlDecode(string.Join("&", this.Request.QueryString.ToString().Split('&'). ToList(). Where(s => s.StartsWith("ctl", StringComparison.OrdinalIgnoreCase) || s.StartsWith("mid", StringComparison.OrdinalIgnoreCase) @@ -352,45 +388,46 @@ private void BindGrid() private IList GetPagedDataSource() { - var roleName = RoleId != Null.NullInteger ? Role.RoleName : Null.NullString; - var userName = UserId != Null.NullInteger ? User.Username : Null.NullString; + var roleName = this.RoleId != Null.NullInteger ? this.Role.RoleName : Null.NullString; + var userName = this.UserId != Null.NullInteger ? this.User.Username : Null.NullString; - var userList = RoleController.Instance.GetUserRoles(PortalId, userName, roleName); - _totalRecords = userList.Count; - _totalPages = _totalRecords%PageSize == 0 ? _totalRecords/PageSize : _totalRecords/PageSize + 1; + var userList = RoleController.Instance.GetUserRoles(this.PortalId, userName, roleName); + this._totalRecords = userList.Count; + this._totalPages = this._totalRecords % this.PageSize == 0 ? this._totalRecords / this.PageSize : (this._totalRecords / this.PageSize) + 1; - return userList.Skip((CurrentPage - 1 )*PageSize).Take(PageSize).ToList(); + return userList.Skip((this.CurrentPage - 1) * this.PageSize).Take(this.PageSize).ToList(); } /// ----------------------------------------------------------------------------- /// - /// GetDates gets the expiry/effective Dates of a Users Role membership + /// GetDates gets the expiry/effective Dates of a Users Role membership. /// /// /// - /// The Id of the User - /// The Id of the Role + /// The Id of the User. + /// The Id of the Role. /// ----------------------------------------------------------------------------- private void GetDates(int UserId, int RoleId) { - DateTime? expiryDate = null; - DateTime? effectiveDate = null; + DateTime? expiryDate = null; + DateTime? effectiveDate = null; - UserRoleInfo objUserRole = RoleController.Instance.GetUserRole(PortalId, UserId, RoleId); + UserRoleInfo objUserRole = RoleController.Instance.GetUserRole(this.PortalId, UserId, RoleId); if (objUserRole != null) { if (Null.IsNull(objUserRole.EffectiveDate) == false) { effectiveDate = objUserRole.EffectiveDate; } + if (Null.IsNull(objUserRole.ExpiryDate) == false) { expiryDate = objUserRole.ExpiryDate; } } - else //new role assignment + else // new role assignment { - RoleInfo objRole = RoleController.Instance.GetRole(PortalId, r => r.RoleID == RoleId); + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalId, r => r.RoleID == RoleId); if (objRole.BillingPeriod > 0) { @@ -400,7 +437,7 @@ private void GetDates(int UserId, int RoleId) expiryDate = DateTime.Now.AddDays(objRole.BillingPeriod); break; case "W": - expiryDate = DateTime.Now.AddDays(objRole.BillingPeriod*7); + expiryDate = DateTime.Now.AddDays(objRole.BillingPeriod * 7); break; case "M": expiryDate = DateTime.Now.AddMonths(objRole.BillingPeriod); @@ -411,65 +448,19 @@ private void GetDates(int UserId, int RoleId) } } } - effectiveDatePicker.SelectedDate = effectiveDate; - expiryDatePicker.SelectedDate = expiryDate; - } - - #endregion - - #region "Public Methods" - - /// ----------------------------------------------------------------------------- - /// - /// DataBind binds the data to the controls - /// - /// ----------------------------------------------------------------------------- - public override void DataBind() - { - if (!ModulePermissionController.CanEditModuleContent(ModuleConfiguration)) - { - Response.Redirect(_navigationManager.NavigateURL("Access Denied"), true); - } - base.DataBind(); - - //Localize Headers - Localization.LocalizeDataGrid(ref grdUserRoles, LocalResourceFile); - - //Bind the role data to the datalist - BindData(); - - BindGrid(); - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteButonVisible returns a boolean indicating if the delete button for - /// the specified UserID, RoleID pair should be shown - /// - /// - /// - /// The ID of the user to check delete button visibility for - /// The ID of the role to check delete button visibility for - /// ----------------------------------------------------------------------------- - public bool DeleteButtonVisible(int UserID, int RoleID) - { - //[DNN-4285] Check if the role can be removed (only handles case of Administrator and Administrator Role - bool canDelete = RoleController.CanRemoveUserFromRole(PortalSettings, UserID, RoleID); - if (RoleID == PortalSettings.AdministratorRoleId && canDelete) - { - //User can only delete if in Admin role - canDelete = PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); - } - return canDelete; - } + + this.effectiveDatePicker.SelectedDate = effectiveDate; + this.expiryDatePicker.SelectedDate = expiryDate; + } /// ----------------------------------------------------------------------------- /// - /// FormatExpiryDate formats the expiry/effective date and filters out nulls + /// FormatExpiryDate formats the expiry/effective date and filters out nulls. /// /// /// - /// The Date object to format + /// The Date object to format. + /// /// ----------------------------------------------------------------------------- public string FormatDate(DateTime DateTime) { @@ -479,27 +470,52 @@ public string FormatDate(DateTime DateTime) } else { - return ""; + return string.Empty; } } /// ----------------------------------------------------------------------------- /// - /// FormatExpiryDate formats the expiry/effective date and filters out nulls - /// + /// FormatExpiryDate formats the expiry/effective date and filters out nulls. + /// + /// /// ----------------------------------------------------------------------------- public string FormatUser(int UserID, string DisplayName) { - return "" + DisplayName + ""; - } - - #endregion + return "" + DisplayName + ""; + } - #region "Event Handlers" + public void cmdDeleteUserRole_click(object sender, ImageClickEventArgs e) + { + if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) == false) + { + return; + } + + try + { + var cmdDeleteUserRole = (ImageButton)sender; + int roleId = Convert.ToInt32(cmdDeleteUserRole.Attributes["roleId"]); + int userId = Convert.ToInt32(cmdDeleteUserRole.Attributes["userId"]); + RoleInfo role = RoleController.Instance.GetRole(this.PortalId, r => r.RoleID == roleId); + if (!RoleController.DeleteUserRole(UserController.GetUserById(this.PortalId, userId), role, this.PortalSettings, this.chkNotify.Checked)) + { + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + } + + this.BindGrid(); + } + catch (Exception exc) + { + Exceptions.LogException(exc); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + } + } + /// ----------------------------------------------------------------------------- /// - /// Page_Init runs when the control is initialised + /// Page_Init runs when the control is initialised. /// /// /// @@ -508,43 +524,45 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - if ((Request.QueryString["RoleId"] != null)) + if (this.Request.QueryString["RoleId"] != null) { - RoleId = Int32.Parse(Request.QueryString["RoleId"]); + this.RoleId = int.Parse(this.Request.QueryString["RoleId"]); } - if ((Request.QueryString["UserId"] != null)) + + if (this.Request.QueryString["UserId"] != null) { int userId; + // Use Int32.MaxValue as invalid UserId - UserId = Int32.TryParse(Request.QueryString["UserId"], out userId) ? userId : Int32.MaxValue; + this.UserId = int.TryParse(this.Request.QueryString["UserId"], out userId) ? userId : int.MaxValue; } - CurrentPage = 1; - if (Request.QueryString["CurrentPage"] != null) + this.CurrentPage = 1; + if (this.Request.QueryString["CurrentPage"] != null) { var currentPage = 0; - if (int.TryParse(Request.QueryString["CurrentPage"], out currentPage) + if (int.TryParse(this.Request.QueryString["CurrentPage"], out currentPage) && currentPage > 0) { - CurrentPage = currentPage; + this.CurrentPage = currentPage; } else { - CurrentPage = 1; + this.CurrentPage = 1; } } - cboRoles.SelectedIndexChanged += cboRoles_SelectedIndexChanged; - cboUsers.SelectedIndexChanged += cboUsers_SelectedIndexChanged; - cmdAdd.Click += cmdAdd_Click; - cmdValidate.Click += cmdValidate_Click; - grdUserRoles.ItemCreated += grdUserRoles_ItemCreated; - grdUserRoles.ItemDataBound += grdUserRoles_ItemDataBound; + this.cboRoles.SelectedIndexChanged += this.cboRoles_SelectedIndexChanged; + this.cboUsers.SelectedIndexChanged += this.cboUsers_SelectedIndexChanged; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdValidate.Click += this.cmdValidate_Click; + this.grdUserRoles.ItemCreated += this.grdUserRoles_ItemCreated; + this.grdUserRoles.ItemDataBound += this.grdUserRoles_ItemDataBound; } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -555,122 +573,150 @@ protected override void OnLoad(EventArgs e) try { - cmdCancel.NavigateUrl = ReturnUrl; - if (ParentModule == null) + this.cmdCancel.NavigateUrl = this.ReturnUrl; + if (this.ParentModule == null) { - DataBind(); + this.DataBind(); } - if (Role == null) - return; - - placeIsOwner.Visible = ((Role.SecurityMode == SecurityMode.SocialGroup) || (Role.SecurityMode == SecurityMode.Both)); - placeIsOwnerHeader.Visible = ((Role.SecurityMode == SecurityMode.SocialGroup) || (Role.SecurityMode == SecurityMode.Both)); + if (this.Role == null) + { + return; + } + + this.placeIsOwner.Visible = (this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both); + this.placeIsOwnerHeader.Visible = (this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both); } - catch (ThreadAbortException exc) //Do nothing if ThreadAbort as this is caused by a redirect + catch (ThreadAbortException exc) // Do nothing if ThreadAbort as this is caused by a redirect { Logger.Debug(exc); - } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } + protected void grdUserRoles_ItemDataBound(object sender, DataGridItemEventArgs e) + { + DataGridItem item = e.Item; + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + { + var userRole = (UserRoleInfo)item.DataItem; + if (this.RoleId == Null.NullInteger) + { + if (userRole.RoleID == Convert.ToInt32(this.cboRoles.SelectedValue)) + { + this.cmdAdd.Text = Localization.GetString("UpdateRole.Text", this.LocalResourceFile); + } + } + + if (this.UserId == Null.NullInteger) + { + if (userRole.UserID == this.SelectedUserID) + { + this.cmdAdd.Text = Localization.GetString("UpdateRole.Text", this.LocalResourceFile); + } + } + } + } + /// ----------------------------------------------------------------------------- /// /// cboUsers_SelectedIndexChanged runs when the selected User is changed in the - /// Users Drop-Down + /// Users Drop-Down. /// /// /// /// ----------------------------------------------------------------------------- private void cboUsers_SelectedIndexChanged(object sender, EventArgs e) { - if ((cboUsers.SelectedItem != null) && (cboRoles.SelectedItem != null)) + if ((this.cboUsers.SelectedItem != null) && (this.cboRoles.SelectedItem != null)) { - SelectedUserID = Int32.Parse(cboUsers.SelectedItem.Value); - GetDates(SelectedUserID, Int32.Parse(cboRoles.SelectedItem.Value)); + this.SelectedUserID = int.Parse(this.cboUsers.SelectedItem.Value); + this.GetDates(this.SelectedUserID, int.Parse(this.cboRoles.SelectedItem.Value)); } - BindGrid(); + + this.BindGrid(); } /// ----------------------------------------------------------------------------- /// - /// cmdValidate_Click executes when a user selects the Validate link for a username + /// cmdValidate_Click executes when a user selects the Validate link for a username. /// /// /// /// ----------------------------------------------------------------------------- private void cmdValidate_Click(object sender, EventArgs e) { - if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) == false) + if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) == false) { return; } - if (!String.IsNullOrEmpty(txtUsers.Text)) + if (!string.IsNullOrEmpty(this.txtUsers.Text)) { - //validate username - UserInfo objUser = UserController.GetUserByName(PortalId, txtUsers.Text); + // validate username + UserInfo objUser = UserController.GetUserByName(this.PortalId, this.txtUsers.Text); if (objUser != null) { - GetDates(objUser.UserID, RoleId); - SelectedUserID = objUser.UserID; + this.GetDates(objUser.UserID, this.RoleId); + this.SelectedUserID = objUser.UserID; } else { - txtUsers.Text = ""; + this.txtUsers.Text = string.Empty; } } - BindGrid(); + + this.BindGrid(); } /// ----------------------------------------------------------------------------- /// /// cboRoles_SelectedIndexChanged runs when the selected Role is changed in the - /// Roles Drop-Down + /// Roles Drop-Down. /// /// /// /// ----------------------------------------------------------------------------- private void cboRoles_SelectedIndexChanged(object sender, EventArgs e) { - GetDates(UserId, Int32.Parse(cboRoles.SelectedItem.Value)); - BindGrid(); + this.GetDates(this.UserId, int.Parse(this.cboRoles.SelectedItem.Value)); + this.BindGrid(); } /// ----------------------------------------------------------------------------- /// - /// cmdAdd_Click runs when the Update Button is clicked + /// cmdAdd_Click runs when the Update Button is clicked. /// /// /// /// ----------------------------------------------------------------------------- - private void cmdAdd_Click(Object sender, EventArgs e) + private void cmdAdd_Click(object sender, EventArgs e) { - if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) == false) + if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) == false) { return; } + try { - if (Page.IsValid) + if (this.Page.IsValid) { - if ((Role != null) && (User != null)) + if ((this.Role != null) && (this.User != null)) { - //do not modify the portal Administrator account dates - if (User.UserID == PortalSettings.AdministratorId && Role.RoleID == PortalSettings.AdministratorRoleId) + // do not modify the portal Administrator account dates + if (this.User.UserID == this.PortalSettings.AdministratorId && this.Role.RoleID == this.PortalSettings.AdministratorRoleId) { - effectiveDatePicker.SelectedDate = null; - expiryDatePicker.SelectedDate = null; + this.effectiveDatePicker.SelectedDate = null; + this.expiryDatePicker.SelectedDate = null; } DateTime datEffectiveDate; - if (effectiveDatePicker.SelectedDate != null) + if (this.effectiveDatePicker.SelectedDate != null) { - datEffectiveDate = effectiveDatePicker.SelectedDate.Value; + datEffectiveDate = this.effectiveDatePicker.SelectedDate.Value; } else { @@ -678,62 +724,39 @@ private void cmdAdd_Click(Object sender, EventArgs e) } DateTime datExpiryDate; - if (expiryDatePicker.SelectedDate != null) + if (this.expiryDatePicker.SelectedDate != null) { - datExpiryDate = expiryDatePicker.SelectedDate.Value; + datExpiryDate = this.expiryDatePicker.SelectedDate.Value; } else { datExpiryDate = Null.NullDate; } - //Add User to Role + // Add User to Role var isOwner = false; - if(((Role.SecurityMode == SecurityMode.SocialGroup) || (Role.SecurityMode == SecurityMode.Both))) - isOwner = chkIsOwner.Checked; - - RoleController.AddUserRole(User, Role, PortalSettings, RoleStatus.Approved, datEffectiveDate, datExpiryDate, chkNotify.Checked, isOwner); - chkIsOwner.Checked = false; //reset the checkbox + if ((this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both)) + { + isOwner = this.chkIsOwner.Checked; + } + + RoleController.AddUserRole(this.User, this.Role, this.PortalSettings, RoleStatus.Approved, datEffectiveDate, datExpiryDate, this.chkNotify.Checked, isOwner); + this.chkIsOwner.Checked = false; // reset the checkbox } } - BindGrid(); + + this.BindGrid(); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } - public void cmdDeleteUserRole_click(object sender, ImageClickEventArgs e) - { - if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) == false) - { - return; - } - try - { - var cmdDeleteUserRole = (ImageButton) sender; - int roleId = Convert.ToInt32(cmdDeleteUserRole.Attributes["roleId"]); - int userId = Convert.ToInt32(cmdDeleteUserRole.Attributes["userId"]); - - RoleInfo role = RoleController.Instance.GetRole(PortalId, r => r.RoleID == roleId); - if (!RoleController.DeleteUserRole(UserController.GetUserById(PortalId, userId), role, PortalSettings, chkNotify.Checked)) - { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - } - BindGrid(); - } - catch (Exception exc) - { - Exceptions.LogException(exc); - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - } - } - /// ----------------------------------------------------------------------------- /// - /// grdUserRoles_ItemCreated runs when an item in the UserRoles Grid is created + /// grdUserRoles_ItemCreated runs when an item in the UserRoles Grid is created. /// /// /// @@ -749,50 +772,25 @@ private void grdUserRoles_ItemCreated(object sender, DataGridItemEventArgs e) if (cmdDeleteUserRole != null) { - if (RoleId == Null.NullInteger) + if (this.RoleId == Null.NullInteger) { - ClientAPI.AddButtonConfirm(cmdDeleteUserRole, String.Format(Localization.GetString("DeleteRoleFromUser.Text", LocalResourceFile), role.FullName, role.RoleName)); + ClientAPI.AddButtonConfirm(cmdDeleteUserRole, string.Format(Localization.GetString("DeleteRoleFromUser.Text", this.LocalResourceFile), role.FullName, role.RoleName)); } else { - ClientAPI.AddButtonConfirm(cmdDeleteUserRole, String.Format(Localization.GetString("DeleteUsersFromRole.Text", LocalResourceFile), role.FullName, role.RoleName)); + ClientAPI.AddButtonConfirm(cmdDeleteUserRole, string.Format(Localization.GetString("DeleteUsersFromRole.Text", this.LocalResourceFile), role.FullName, role.RoleName)); } + cmdDeleteUserRole.Attributes.Add("roleId", role.RoleID.ToString()); cmdDeleteUserRole.Attributes.Add("userId", role.UserID.ToString()); } - item.Cells[5].Visible = ((Role.SecurityMode == SecurityMode.SocialGroup) || (Role.SecurityMode == SecurityMode.Both)); - + item.Cells[5].Visible = (this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } - - protected void grdUserRoles_ItemDataBound(object sender, DataGridItemEventArgs e) - { - DataGridItem item = e.Item; - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - var userRole = (UserRoleInfo) item.DataItem; - if (RoleId == Null.NullInteger) - { - if (userRole.RoleID == Convert.ToInt32(cboRoles.SelectedValue)) - { - cmdAdd.Text = Localization.GetString("UpdateRole.Text", LocalResourceFile); - } - } - if (UserId == Null.NullInteger) - { - if (userRole.UserID == SelectedUserID) - { - cmdAdd.Text = Localization.GetString("UpdateRole.Text", LocalResourceFile); - } - } - } - } - - #endregion } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs index e0320d83206..66005777fbb 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs @@ -1,42 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Linq; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; - -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls; - -using DataCache = DotNetNuke.Common.Utilities.DataCache; -using Globals = DotNetNuke.Common.Globals; -using System.Web.UI.WebControls; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Cache; -using DotNetNuke.Web.Client; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Collections; + using System.Linq; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Cache; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls; + + using DataCache = DotNetNuke.Common.Utilities.DataCache; + using Globals = DotNetNuke.Common.Globals; using Host = DotNetNuke.Entities.Host.Host; /// ----------------------------------------------------------------------------- @@ -47,576 +40,577 @@ namespace DotNetNuke.Modules.Admin.Users /// public partial class User : UserUserControlBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (User)); - #region Public Properties + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(User)); public UserCreateStatus CreateStatus { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets whether the User is valid + /// Gets a value indicating whether gets whether the User is valid. /// public bool IsValid { get { - return Validate(); + return this.Validate(); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Password section is displayed + /// Gets or sets a value indicating whether gets and sets whether the Password section is displayed. /// public bool ShowPassword { get { - return Password.Visible; + return this.Password.Visible; } + set { - Password.Visible = value; + this.Password.Visible = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets whether the Update button + /// Gets or sets a value indicating whether gets and sets whether the Update button. /// public bool ShowUpdate { get { - return actionsRow.Visible; + return this.actionsRow.Visible; } + set { - actionsRow.Visible = value; + this.actionsRow.Visible = value; } } - /// - /// User Form's css class. - /// - public string CssClass - { - get - { - return pnlAddUser.CssClass; - } - set - { - userForm.CssClass = string.IsNullOrEmpty(userForm.CssClass) ? value : string.Format("{0} {1}", userForm.CssClass, value); - pnlAddUser.CssClass = string.IsNullOrEmpty(pnlAddUser.CssClass) ? value : string.Format("{0} {1}", pnlAddUser.CssClass, value); ; - } - } - - #endregion - - #region Private Methods - /// - /// method checks to see if its allowed to change the username - /// valid if a host, or an admin where the username is in only 1 portal + /// Gets or sets user Form's css class. /// - /// - private bool CanUpdateUsername() + public string CssClass { - //do not allow for non-logged in users - if (Request.IsAuthenticated==false || AddUser) - { - return false; - } - - //can only update username if a host/admin and account being managed is not a superuser - if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) - { - //only allow updates for non-superuser accounts - if (User.IsSuperUser==false) - { - return true; - } - } - - //if an admin, check if the user is only within this portal - if (UserController.Instance.GetCurrentUserInfo().IsInRole(PortalSettings.AdministratorRoleName)) - { - //only allow updates for non-superuser accounts - if (User.IsSuperUser) - { - return false; - } - if (PortalController.GetPortalsByUser(User.UserID).Count == 1) return true; - } - - return false; - } - - private void UpdateDisplayName() - { - //Update DisplayName to conform to Format - if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) + get { - User.UpdateDisplayName(PortalSettings.Registration.DisplayNameFormat); + return this.pnlAddUser.CssClass; } - } - /// ----------------------------------------------------------------------------- - /// - /// Validate validates the User - /// - private bool Validate() - { - //Check User Editor - bool _IsValid = userForm.IsValid; - - //Check Password is valid - if (AddUser && ShowPassword) + set { - CreateStatus = UserCreateStatus.AddUser; - if (!chkRandom.Checked) - { - //1. Check Password is Valid - if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(txtPassword.Text)) - { - CreateStatus = UserCreateStatus.InvalidPassword; - } - if (CreateStatus == UserCreateStatus.AddUser) - { - User.Membership.Password = txtPassword.Text; - } - } - else - { - //Generate a random password for the user - User.Membership.Password = UserController.GeneratePassword(); - } - - //Check Question/Answer - if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) - { - if (string.IsNullOrEmpty(txtQuestion.Text)) - { - //Invalid Question - CreateStatus = UserCreateStatus.InvalidQuestion; - } - else - { - User.Membership.PasswordQuestion = txtQuestion.Text; - } - if (CreateStatus == UserCreateStatus.AddUser) - { - if (string.IsNullOrEmpty(txtAnswer.Text)) - { - //Invalid Question - CreateStatus = UserCreateStatus.InvalidAnswer; - } - else - { - User.Membership.PasswordAnswer = txtAnswer.Text; - } - } - } - if (CreateStatus != UserCreateStatus.AddUser) - { - _IsValid = false; - } + this.userForm.CssClass = string.IsNullOrEmpty(this.userForm.CssClass) ? value : string.Format("{0} {1}", this.userForm.CssClass, value); + this.pnlAddUser.CssClass = string.IsNullOrEmpty(this.pnlAddUser.CssClass) ? value : string.Format("{0} {1}", this.pnlAddUser.CssClass, value); } - return _IsValid; } - #endregion - - #region Public Methods - /// ----------------------------------------------------------------------------- /// - /// CreateUser creates a new user in the Database + /// CreateUser creates a new user in the Database. /// public void CreateUser() { - //Update DisplayName to conform to Format - UpdateDisplayName(); + // Update DisplayName to conform to Format + this.UpdateDisplayName(); - if (IsRegister) + if (this.IsRegister) { - User.Membership.Approved = PortalSettings.UserRegistration == (int) Globals.PortalRegistrationType.PublicRegistration; + this.User.Membership.Approved = this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration; } else { - //Set the Approved status from the value in the Authorized checkbox - User.Membership.Approved = chkAuthorize.Checked; + // Set the Approved status from the value in the Authorized checkbox + this.User.Membership.Approved = this.chkAuthorize.Checked; } - var user = User; + + var user = this.User; // make sure username is set in UseEmailAsUserName" mode - if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false)) + if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false)) { - user.Username = User.Email; - User.Username = User.Email; + user.Username = this.User.Email; + this.User.Username = this.User.Email; } var createStatus = UserController.CreateUser(ref user); var args = (createStatus == UserCreateStatus.Success) - ? new UserCreatedEventArgs(User) {Notify = chkNotify.Checked} + ? new UserCreatedEventArgs(this.User) { Notify = this.chkNotify.Checked } : new UserCreatedEventArgs(null); args.CreateStatus = createStatus; - OnUserCreated(args); - OnUserCreateCompleted(args); + this.OnUserCreated(args); + this.OnUserCreateCompleted(args); } /// ----------------------------------------------------------------------------- /// - /// DataBind binds the data to the controls + /// DataBind binds the data to the controls. /// public override void DataBind() { - if (Page.IsPostBack == false) + if (this.Page.IsPostBack == false) { string confirmString = Localization.GetString("DeleteItem"); - if (IsUser) + if (this.IsUser) { - confirmString = Localization.GetString("ConfirmUnRegister", LocalResourceFile); + confirmString = Localization.GetString("ConfirmUnRegister", this.LocalResourceFile); } - ClientAPI.AddButtonConfirm(cmdDelete, confirmString); - chkRandom.Checked = false; + + ClientAPI.AddButtonConfirm(this.cmdDelete, confirmString); + this.chkRandom.Checked = false; } - cmdDelete.Visible = false; - cmdRemove.Visible = false; - cmdRestore.Visible = false; - if (!AddUser) + this.cmdDelete.Visible = false; + this.cmdRemove.Visible = false; + this.cmdRestore.Visible = false; + if (!this.AddUser) { - var deletePermitted = (User.UserID != PortalSettings.AdministratorId) && !(IsUser && User.IsSuperUser); - if ((deletePermitted)) + var deletePermitted = (this.User.UserID != this.PortalSettings.AdministratorId) && !(this.IsUser && this.User.IsSuperUser); + if (deletePermitted) { - if ((User.IsDeleted)) + if (this.User.IsDeleted) { - cmdRemove.Visible = true; - cmdRestore.Visible = true; + this.cmdRemove.Visible = true; + this.cmdRestore.Visible = true; } else { - cmdDelete.Visible = true; + this.cmdDelete.Visible = true; } } } - cmdUpdate.Text = Localization.GetString(IsUser ? "Register" : "CreateUser", LocalResourceFile); - cmdDelete.Text = Localization.GetString(IsUser ? "UnRegister" : "Delete", LocalResourceFile); - if (AddUser) + this.cmdUpdate.Text = Localization.GetString(this.IsUser ? "Register" : "CreateUser", this.LocalResourceFile); + this.cmdDelete.Text = Localization.GetString(this.IsUser ? "UnRegister" : "Delete", this.LocalResourceFile); + if (this.AddUser) { - pnlAddUser.Visible = true; - if (IsRegister) + this.pnlAddUser.Visible = true; + if (this.IsRegister) { - AuthorizeNotify.Visible = false; - randomRow.Visible = false; - if (ShowPassword) + this.AuthorizeNotify.Visible = false; + this.randomRow.Visible = false; + if (this.ShowPassword) { - questionRow.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer; - answerRow.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer; - lblPasswordHelp.Text = Localization.GetString("PasswordHelpUser", LocalResourceFile); + this.questionRow.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer; + this.answerRow.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer; + this.lblPasswordHelp.Text = Localization.GetString("PasswordHelpUser", this.LocalResourceFile); } } else { - lblPasswordHelp.Text = Localization.GetString("PasswordHelpAdmin", LocalResourceFile); + this.lblPasswordHelp.Text = Localization.GetString("PasswordHelpAdmin", this.LocalResourceFile); } - txtConfirm.Attributes.Add("value", txtConfirm.Text); - txtPassword.Attributes.Add("value", txtPassword.Text); - } + this.txtConfirm.Attributes.Add("value", this.txtConfirm.Text); + this.txtPassword.Attributes.Add("value", this.txtPassword.Text); + } - bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false); + bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false); - //only show username row once UseEmailAsUserName is disabled in site settings + // only show username row once UseEmailAsUserName is disabled in site settings if (disableUsername) { - userNameReadOnly.Visible = false; - userName.Visible = false; + this.userNameReadOnly.Visible = false; + this.userName.Visible = false; } else { - userNameReadOnly.Visible = !AddUser; - userName.Visible = AddUser; + this.userNameReadOnly.Visible = !this.AddUser; + this.userName.Visible = this.AddUser; } - if (CanUpdateUsername() && !disableUsername) + if (this.CanUpdateUsername() && !disableUsername) { - - renameUserName.Visible = true; - - userName.Visible = false; - userNameReadOnly.Visible = false; + this.renameUserName.Visible = true; + + this.userName.Visible = false; + this.userNameReadOnly.Visible = false; - ArrayList portals = PortalController.GetPortalsByUser(User.UserID); - if (portals.Count>1) + ArrayList portals = PortalController.GetPortalsByUser(this.User.UserID); + if (portals.Count > 1) { - numSites.Text=String.Format(Localization.GetString("UpdateUserName", LocalResourceFile), portals.Count.ToString()); - cboSites.Visible = true; - cboSites.DataSource = portals; - cboSites.DataTextField = "PortalName"; - cboSites.DataBind(); + this.numSites.Text = string.Format(Localization.GetString("UpdateUserName", this.LocalResourceFile), portals.Count.ToString()); + this.cboSites.Visible = true; + this.cboSites.DataSource = portals; + this.cboSites.DataTextField = "PortalName"; + this.cboSites.DataBind(); - renameUserPortals.Visible = true; + this.renameUserPortals.Visible = true; } } - if (!string.IsNullOrEmpty(PortalSettings.Registration.UserNameValidator)) + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.UserNameValidator)) { - userName.ValidationExpression = PortalSettings.Registration.UserNameValidator; + this.userName.ValidationExpression = this.PortalSettings.Registration.UserNameValidator; } - if (!string.IsNullOrEmpty(PortalSettings.Registration.EmailValidator)) + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.EmailValidator)) { - email.ValidationExpression = PortalSettings.Registration.EmailValidator; + this.email.ValidationExpression = this.PortalSettings.Registration.EmailValidator; } - if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) { - if (AddUser) + if (this.AddUser) { - displayNameReadOnly.Visible = false; - displayName.Visible = false; + this.displayNameReadOnly.Visible = false; + this.displayName.Visible = false; } else { - displayNameReadOnly.Visible = true; - displayName.Visible = false; + this.displayNameReadOnly.Visible = true; + this.displayName.Visible = false; } - firstName.Visible = true; - lastName.Visible = true; + + this.firstName.Visible = true; + this.lastName.Visible = true; } else { - displayNameReadOnly.Visible = false; - displayName.Visible = true; - firstName.Visible = false; - lastName.Visible = false; + this.displayNameReadOnly.Visible = false; + this.displayName.Visible = true; + this.firstName.Visible = false; + this.lastName.Visible = false; + } + + this.userForm.DataSource = this.User; + if (!this.Page.IsPostBack) + { + this.userForm.DataBind(); + this.renameUserName.Value = this.User.Username; + } + } + + /// + /// method checks to see if its allowed to change the username + /// valid if a host, or an admin where the username is in only 1 portal. + /// + /// + private bool CanUpdateUsername() + { + // do not allow for non-logged in users + if (this.Request.IsAuthenticated == false || this.AddUser) + { + return false; + } + + // can only update username if a host/admin and account being managed is not a superuser + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) + { + // only allow updates for non-superuser accounts + if (this.User.IsSuperUser == false) + { + return true; + } + } + + // if an admin, check if the user is only within this portal + if (UserController.Instance.GetCurrentUserInfo().IsInRole(this.PortalSettings.AdministratorRoleName)) + { + // only allow updates for non-superuser accounts + if (this.User.IsSuperUser) + { + return false; + } + + if (PortalController.GetPortalsByUser(this.User.UserID).Count == 1) + { + return true; + } } - userForm.DataSource = User; - if (!Page.IsPostBack) - { - userForm.DataBind(); - renameUserName.Value = User.Username; - } + return false; } - #endregion + private void UpdateDisplayName() + { + // Update DisplayName to conform to Format + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) + { + this.User.UpdateDisplayName(this.PortalSettings.Registration.DisplayNameFormat); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Validate validates the User. + /// + private bool Validate() + { + // Check User Editor + bool _IsValid = this.userForm.IsValid; + + // Check Password is valid + if (this.AddUser && this.ShowPassword) + { + this.CreateStatus = UserCreateStatus.AddUser; + if (!this.chkRandom.Checked) + { + // 1. Check Password is Valid + if (this.CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(this.txtPassword.Text)) + { + this.CreateStatus = UserCreateStatus.InvalidPassword; + } + + if (this.CreateStatus == UserCreateStatus.AddUser) + { + this.User.Membership.Password = this.txtPassword.Text; + } + } + else + { + // Generate a random password for the user + this.User.Membership.Password = UserController.GeneratePassword(); + } + + // Check Question/Answer + if (this.CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) + { + if (string.IsNullOrEmpty(this.txtQuestion.Text)) + { + // Invalid Question + this.CreateStatus = UserCreateStatus.InvalidQuestion; + } + else + { + this.User.Membership.PasswordQuestion = this.txtQuestion.Text; + } + + if (this.CreateStatus == UserCreateStatus.AddUser) + { + if (string.IsNullOrEmpty(this.txtAnswer.Text)) + { + // Invalid Question + this.CreateStatus = UserCreateStatus.InvalidAnswer; + } + else + { + this.User.Membership.PasswordAnswer = this.txtAnswer.Text; + } + } + } + + if (this.CreateStatus != UserCreateStatus.AddUser) + { + _IsValid = false; + } + } - #region Event Handlers + return _IsValid; + } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdDelete.Click += cmdDelete_Click; - cmdUpdate.Click += cmdUpdate_Click; - cmdRemove.Click += cmdRemove_Click; - cmdRestore.Click += cmdRestore_Click; + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdUpdate.Click += this.cmdUpdate_Click; + this.cmdRemove.Click += this.cmdRemove_Click; + this.cmdRestore.Click += this.cmdRestore_Click; } protected override void OnPreRender(EventArgs e) { - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); base.OnPreRender(e); + if (Host.EnableStrengthMeter) + { + this.passwordContainer.CssClass = "password-strength-container"; + this.txtPassword.CssClass = "password-strength"; + this.txtConfirm.CssClass = string.Format("{0} checkStength", this.txtConfirm.CssClass); - if (Host.EnableStrengthMeter) - { - passwordContainer.CssClass = "password-strength-container"; - txtPassword.CssClass = "password-strength"; - txtConfirm.CssClass = string.Format("{0} checkStength", txtConfirm.CssClass); - - var options = new DnnPaswordStrengthOptions(); - var optionsAsJsonString = Json.Serialize(options); - var passwordScript = string.Format("dnn.initializePasswordStrength('.{0}', {1});{2}", - "password-strength", optionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "PasswordStrength", passwordScript, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "PasswordStrength", passwordScript, true); - } - } - - var confirmPasswordOptions = new DnnConfirmPasswordOptions() - { - FirstElementSelector = "#" + passwordContainer.ClientID + " input[type=password]", - SecondElementSelector = ".password-confirm", - ContainerSelector = ".dnnFormPassword", - UnmatchedCssClass = "unmatched", - MatchedCssClass = "matched" - }; - - var confirmOptionsAsJsonString = Json.Serialize(confirmPasswordOptions); - var confirmScript = string.Format("dnn.initializePasswordComparer({0});{1}", confirmOptionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "ConfirmPassword", confirmScript, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "ConfirmPassword", confirmScript, true); - } - } + var options = new DnnPaswordStrengthOptions(); + var optionsAsJsonString = Json.Serialize(options); + var passwordScript = string.Format( + "dnn.initializePasswordStrength('.{0}', {1});{2}", + "password-strength", optionsAsJsonString, Environment.NewLine); + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "PasswordStrength", passwordScript, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PasswordStrength", passwordScript, true); + } + } + + var confirmPasswordOptions = new DnnConfirmPasswordOptions() + { + FirstElementSelector = "#" + this.passwordContainer.ClientID + " input[type=password]", + SecondElementSelector = ".password-confirm", + ContainerSelector = ".dnnFormPassword", + UnmatchedCssClass = "unmatched", + MatchedCssClass = "matched", + }; + + var confirmOptionsAsJsonString = Json.Serialize(confirmPasswordOptions); + var confirmScript = string.Format("dnn.initializePasswordComparer({0});{1}", confirmOptionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ConfirmPassword", confirmScript, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmPassword", confirmScript, true); + } + } /// ----------------------------------------------------------------------------- /// - /// cmdDelete_Click runs when the delete Button is clicked + /// cmdDelete_Click runs when the delete Button is clicked. /// - private void cmdDelete_Click(Object sender, EventArgs e) + private void cmdDelete_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - string name = User.Username; - int id = UserId; - UserInfo user = User; + + string name = this.User.Username; + int id = this.UserId; + UserInfo user = this.User; if (UserController.DeleteUser(ref user, true, false)) { - OnUserDeleted(new UserDeletedEventArgs(id, name)); + this.OnUserDeleted(new UserDeletedEventArgs(id, name)); } else { - OnUserDeleteError(new UserUpdateErrorArgs(id, name, "UserDeleteError")); + this.OnUserDeleteError(new UserUpdateErrorArgs(id, name, "UserDeleteError")); } } - private void cmdRestore_Click(Object sender, EventArgs e) + private void cmdRestore_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - var name = User.Username; - var id = UserId; - var userInfo = User; + var name = this.User.Username; + var id = this.UserId; + + var userInfo = this.User; if (UserController.RestoreUser(ref userInfo)) { - OnUserRestored(new UserRestoredEventArgs(id, name)); + this.OnUserRestored(new UserRestoredEventArgs(id, name)); } else { - OnUserRestoreError(new UserUpdateErrorArgs(id, name, "UserRestoreError")); + this.OnUserRestoreError(new UserUpdateErrorArgs(id, name, "UserRestoreError")); } } - private void cmdRemove_Click(Object sender, EventArgs e) + private void cmdRemove_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - var name = User.Username; - var id = UserId; - if (UserController.RemoveUser(User)) + var name = this.User.Username; + var id = this.UserId; + + if (UserController.RemoveUser(this.User)) { - OnUserRemoved(new UserRemovedEventArgs(id, name)); + this.OnUserRemoved(new UserRemovedEventArgs(id, name)); } else { - OnUserRemoveError(new UserUpdateErrorArgs(id, name, "UserRemoveError")); + this.OnUserRemoveError(new UserUpdateErrorArgs(id, name, "UserRemoveError")); } } /// ----------------------------------------------------------------------------- /// - /// cmdUpdate_Click runs when the Update Button is clicked + /// cmdUpdate_Click runs when the Update Button is clicked. /// - private void cmdUpdate_Click(Object sender, EventArgs e) + private void cmdUpdate_Click(object sender, EventArgs e) { - if (IsUserOrAdmin == false) + if (this.IsUserOrAdmin == false) { return; } - if (AddUser) + if (this.AddUser) { - if (IsValid) + if (this.IsValid) { - CreateUser(); - DataCache.ClearPortalUserCountCache(PortalId); + this.CreateUser(); + DataCache.ClearPortalUserCountCache(this.PortalId); } } else { - if (userForm.IsValid && (User != null)) + if (this.userForm.IsValid && (this.User != null)) { - if (User.UserID == PortalSettings.AdministratorId) + if (this.User.UserID == this.PortalSettings.AdministratorId) { - //Clear the Portal Cache - DataCache.ClearPortalUserCountCache(UserPortalID); + // Clear the Portal Cache + DataCache.ClearPortalUserCountCache(this.UserPortalID); } + try { - //Update DisplayName to conform to Format - UpdateDisplayName(); - //either update the username or update the user details + // Update DisplayName to conform to Format + this.UpdateDisplayName(); - if (CanUpdateUsername() && !PortalSettings.Registration.UseEmailAsUserName) + // either update the username or update the user details + if (this.CanUpdateUsername() && !this.PortalSettings.Registration.UseEmailAsUserName) { - UserController.ChangeUsername(User.UserID, renameUserName.Value.ToString()); + UserController.ChangeUsername(this.User.UserID, this.renameUserName.Value.ToString()); } - //DNN-5874 Check if unique display name is required - if (PortalSettings.Registration.RequireUniqueDisplayName) + // DNN-5874 Check if unique display name is required + if (this.PortalSettings.Registration.RequireUniqueDisplayName) { - var usersWithSameDisplayName = (System.Collections.Generic.List)MembershipProvider.Instance().GetUsersBasicSearch(PortalId, 0, 2, "DisplayName", true, "DisplayName", User.DisplayName); - if (usersWithSameDisplayName.Any(user => user.UserID != User.UserID)) + var usersWithSameDisplayName = (System.Collections.Generic.List)MembershipProvider.Instance().GetUsersBasicSearch(this.PortalId, 0, 2, "DisplayName", true, "DisplayName", this.User.DisplayName); + if (usersWithSameDisplayName.Any(user => user.UserID != this.User.UserID)) { - UI.Skins.Skin.AddModuleMessage(this, LocalizeString("DisplayNameNotUnique"), UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, this.LocalizeString("DisplayNameNotUnique"), UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError); return; } } - UserController.UpdateUser(UserPortalID, User); + UserController.UpdateUser(this.UserPortalID, this.User); - if (PortalSettings.Registration.UseEmailAsUserName && (User.Username.ToLower() != User.Email.ToLower())) + if (this.PortalSettings.Registration.UseEmailAsUserName && (this.User.Username.ToLower() != this.User.Email.ToLower())) { - UserController.ChangeUsername(User.UserID, User.Email); + UserController.ChangeUsername(this.User.UserID, this.User.Email); } - OnUserUpdated(EventArgs.Empty); - OnUserUpdateCompleted(EventArgs.Empty); + this.OnUserUpdated(EventArgs.Empty); + this.OnUserUpdateCompleted(EventArgs.Empty); } catch (Exception exc) { Logger.Error(exc); - var args = new UserUpdateErrorArgs(User.UserID, User.Username, "EmailError"); - OnUserUpdateError(args); + var args = new UserUpdateErrorArgs(this.User.UserID, this.User.Username, "EmailError"); + this.OnUserUpdateError(args); } } } } - - #endregion } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs index ef72143e269..21b52b444a5 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs @@ -1,41 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Linq; -using System.Web; -using System.Web.UI; -using System.Web.UI.HtmlControls; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; - -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls; - -using DataCache = DotNetNuke.Common.Utilities.DataCache; -using Globals = DotNetNuke.Common.Globals; -using System.Web.UI.WebControls; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Web.Client; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Collections; + using System.Linq; + using System.Web; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls; + + using DataCache = DotNetNuke.Common.Utilities.DataCache; + using Globals = DotNetNuke.Common.Globals; + /// ----------------------------------------------------------------------------- /// /// The emmpty user control used for users account page. diff --git a/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs index 98ac50ffff9..50fc2e80b8b 100644 --- a/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs @@ -1,56 +1,59 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Urls; -using DotNetNuke.UI.Modules; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.Modules.UrlManagement { + using System; + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Urls; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + public partial class ProviderSettings : ModuleUserControlBase { + private readonly INavigationManager _navigationManager; + private int _providerId; private IExtensionUrlProviderSettingsControl _providerSettingsControl; - private string DisplayMode => (Request.QueryString["Display"] ?? "").ToLowerInvariant(); - private readonly INavigationManager _navigationManager; public ProviderSettings() { - _navigationManager = Globals.DependencyProvider.GetService(); + this._navigationManager = Globals.DependencyProvider.GetService(); } + + private string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); protected override void OnInit(EventArgs e) { base.OnInit(e); - cmdUpdate.Click += cmdUpdate_Click; - cmdCancel.Click += cmdCancel_Click; + this.cmdUpdate.Click += this.cmdUpdate_Click; + this.cmdCancel.Click += this.cmdCancel_Click; - _providerId = Convert.ToInt32(Request.Params["ProviderId"]); + this._providerId = Convert.ToInt32(this.Request.Params["ProviderId"]); - var provider = ExtensionUrlProviderController.GetModuleProviders(ModuleContext.PortalId) - .SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == _providerId); + var provider = ExtensionUrlProviderController.GetModuleProviders(this.ModuleContext.PortalId) + .SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == this._providerId); if (provider != null) { var settingsControlSrc = provider.ProviderConfig.SettingsControlSrc; - var settingsControl = Page.LoadControl(settingsControlSrc); - - providerSettingsPlaceHolder.Controls.Add(settingsControl); + var settingsControl = this.Page.LoadControl(settingsControlSrc); -// ReSharper disable SuspiciousTypeConversion.Global - _providerSettingsControl = settingsControl as IExtensionUrlProviderSettingsControl; -// ReSharper restore SuspiciousTypeConversion.Global - if (_providerSettingsControl != null) + this.providerSettingsPlaceHolder.Controls.Add(settingsControl); + + // ReSharper disable SuspiciousTypeConversion.Global + this._providerSettingsControl = settingsControl as IExtensionUrlProviderSettingsControl; + + // ReSharper restore SuspiciousTypeConversion.Global + if (this._providerSettingsControl != null) { - _providerSettingsControl.Provider = provider.ProviderConfig; + this._providerSettingsControl.Provider = provider.ProviderConfig; } } } @@ -58,41 +61,41 @@ protected override void OnInit(EventArgs e) protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (_providerSettingsControl != null) + if (this._providerSettingsControl != null) { - _providerSettingsControl.LoadSettings(); + this._providerSettingsControl.LoadSettings(); } - if (DisplayMode == "editor" || DisplayMode == "settings") + if (this.DisplayMode == "editor" || this.DisplayMode == "settings") { - cmdCancel.Visible = false; + this.cmdCancel.Visible = false; } } - void cmdCancel_Click(object sender, EventArgs e) + private void cmdCancel_Click(object sender, EventArgs e) { - Response.Redirect(_navigationManager.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID)); + this.Response.Redirect(this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID)); } - void cmdUpdate_Click(object sender, EventArgs e) + private void cmdUpdate_Click(object sender, EventArgs e) { if (!this.Page.IsValid) { return; } - if (_providerSettingsControl != null) + if (this._providerSettingsControl != null) { - var settings = _providerSettingsControl.SaveSettings(); + var settings = this._providerSettingsControl.SaveSettings(); foreach (var setting in settings) { - ExtensionUrlProviderController.SaveSetting(_providerId, ModuleContext.PortalId, setting.Key, setting.Value); + ExtensionUrlProviderController.SaveSetting(this._providerId, this.ModuleContext.PortalId, setting.Key, setting.Value); } } - if (DisplayMode != "editor" && DisplayMode != "settings") + if (this.DisplayMode != "editor" && this.DisplayMode != "settings") { - Response.Redirect(_navigationManager.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID)); + this.Response.Redirect(this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID)); } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/Settings.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/Settings.ascx.resx index fbee05318bc..a3dcc9a4839 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/Settings.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/Settings.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/SharedResources.resx b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/SharedResources.resx index 7f685c91bd2..9295a95e510 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/SharedResources.resx +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/SharedResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/ViewProfile.ascx.resx b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/ViewProfile.ascx.resx index f9a19f6827d..dc50775dcff 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/ViewProfile.ascx.resx +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/App_LocalResources/ViewProfile.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx index e621edff68e..77f9fd9ee27 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx @@ -7,7 +7,7 @@
        - +
        -
        \ No newline at end of file +
        diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs index cd4637ed44a..feff0931bed 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs @@ -1,76 +1,68 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Globalization; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Globalization; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + public partial class ViewProfileSettings : ModuleSettingsBase - { - #region "Base Method Implementations" - + { public override void LoadSettings() { try { - ClientAPI.AddButtonConfirm(cmdLoadDefault, Localization.GetString("LoadDefault.Confirm", LocalResourceFile)); - cmdLoadDefault.ToolTip = Localization.GetString("LoadDefault.Help", LocalResourceFile); + ClientAPI.AddButtonConfirm(this.cmdLoadDefault, Localization.GetString("LoadDefault.Confirm", this.LocalResourceFile)); + this.cmdLoadDefault.ToolTip = Localization.GetString("LoadDefault.Help", this.LocalResourceFile); - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - if (!string.IsNullOrEmpty((string) TabModuleSettings["ProfileTemplate"])) + if (!string.IsNullOrEmpty((string)this.TabModuleSettings["ProfileTemplate"])) { - txtTemplate.Text = (string) TabModuleSettings["ProfileTemplate"]; + this.txtTemplate.Text = (string)this.TabModuleSettings["ProfileTemplate"]; } - if (Settings.ContainsKey("IncludeButton")) + + if (this.Settings.ContainsKey("IncludeButton")) { - IncludeButton.Checked = Convert.ToBoolean(Settings["IncludeButton"]); + this.IncludeButton.Checked = Convert.ToBoolean(this.Settings["IncludeButton"]); } } } catch (Exception exc) { - //Module failed to load + // Module failed to load Exceptions.ProcessModuleLoadException(this, exc); } } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - cmdLoadDefault.Click += cmdLoadDefault_Click; - } - public override void UpdateSettings() { try { - ModuleController.Instance.UpdateTabModuleSetting(TabModuleId, "ProfileTemplate", txtTemplate.Text); - ModuleController.Instance.UpdateTabModuleSetting(TabModuleId, "IncludeButton", IncludeButton.Checked.ToString(CultureInfo.InvariantCulture)); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, "ProfileTemplate", this.txtTemplate.Text); + ModuleController.Instance.UpdateTabModuleSetting(this.TabModuleId, "IncludeButton", this.IncludeButton.Checked.ToString(CultureInfo.InvariantCulture)); } catch (Exception exc) { - //Module failed to load + // Module failed to load Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion + } + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.cmdLoadDefault.Click += this.cmdLoadDefault_Click; + } + protected void cmdLoadDefault_Click(object sender, EventArgs e) { - txtTemplate.Text = Localization.GetString("DefaultTemplate", LocalResourceFile); + this.txtTemplate.Text = Localization.GetString("DefaultTemplate", this.LocalResourceFile); } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs index 3a7ed30f5d1..bae8ffe01ac 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs @@ -1,198 +1,199 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; -using System.Text; -using System.Threading; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Tokens; -using DotNetNuke.UI.Modules; -using DotNetNuke.Entities.Users.Social; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.ViewProfile { - - /// - /// The ViewProfile ProfileModuleUserControlBase is used to view a Users Profile - /// + using System; + using System.Linq; + using System.Text; + using System.Threading; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Services.Tokens; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; + + /// + /// The ViewProfile ProfileModuleUserControlBase is used to view a Users Profile. + /// public partial class ViewProfile : ProfileModuleUserControlBase - { + { private readonly INavigationManager _navigationManager; + public ViewProfile() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - public override bool DisplayModule - { - get - { - return true; - } - } + public override bool DisplayModule + { + get + { + return true; + } + } public bool IncludeButton { get { var includeButton = true; - if (ModuleContext.Settings.ContainsKey("IncludeButton")) + if (this.ModuleContext.Settings.ContainsKey("IncludeButton")) { - includeButton = Convert.ToBoolean(ModuleContext.Settings["IncludeButton"]); + includeButton = Convert.ToBoolean(this.ModuleContext.Settings["IncludeButton"]); } + return includeButton; } } - public string ProfileProperties { get; set; } - - #region Event Handlers - + public string ProfileProperties { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); - //throw 404 so that deleted profile is not reindexed - if(ProfileUser == null || ProfileUser.IsDeleted) - { - UrlUtils.Handle404Exception(Response, PortalSettings.Current); + // throw 404 so that deleted profile is not reindexed + if (this.ProfileUser == null || this.ProfileUser.IsDeleted) + { + UrlUtils.Handle404Exception(this.Response, PortalSettings.Current); } - ProcessQuerystring(); + this.ProcessQuerystring(); JavaScript.RequestRegistration(CommonJs.jQuery); JavaScript.RequestRegistration(CommonJs.jQueryMigrate); JavaScript.RequestRegistration(CommonJs.Knockout); } - /// - /// Page_Load runs when the control is loaded - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); - try - { - if(Null.IsNull(ProfileUserId)) + try + { + if (Null.IsNull(this.ProfileUserId)) { - Visible = false; + this.Visible = false; return; } - var template = Convert.ToString(ModuleContext.Settings["ProfileTemplate"]); - if(string.IsNullOrEmpty(template)) + var template = Convert.ToString(this.ModuleContext.Settings["ProfileTemplate"]); + if (string.IsNullOrEmpty(template)) { - template = Localization.GetString("DefaultTemplate", LocalResourceFile); + template = Localization.GetString("DefaultTemplate", this.LocalResourceFile); } - var editUrl = _navigationManager.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + ProfileUserId, "pageno=1"); - var profileUrl = _navigationManager.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + ProfileUserId, "pageno=2"); + + var editUrl = this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + this.ProfileUserId, "pageno=1"); + var profileUrl = this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + this.ProfileUserId, "pageno=2"); if (template.Contains("[BUTTON:EDITPROFILE]")) { - if (IncludeButton && IsUser) + if (this.IncludeButton && this.IsUser) { - string editHyperLink = String.Format("{1}", profileUrl, LocalizeString("Edit")); + string editHyperLink = string.Format("{1}", profileUrl, this.LocalizeString("Edit")); template = template.Replace("[BUTTON:EDITPROFILE]", editHyperLink); } - buttonPanel.Visible = false; + + this.buttonPanel.Visible = false; } else { - buttonPanel.Visible = IncludeButton; - editLink.NavigateUrl = editUrl; + this.buttonPanel.Visible = this.IncludeButton; + this.editLink.NavigateUrl = editUrl; } + if (template.Contains("[HYPERLINK:EDITPROFILE]")) { - if (IsUser) + if (this.IsUser) { - string editHyperLink = String.Format("{1}", profileUrl, LocalizeString("Edit")); + string editHyperLink = string.Format("{1}", profileUrl, this.LocalizeString("Edit")); template = template.Replace("[HYPERLINK:EDITPROFILE]", editHyperLink); } } + if (template.Contains("[HYPERLINK:MYACCOUNT]")) { - if (IsUser) + if (this.IsUser) { - string editHyperLink = String.Format("{1}", editUrl, LocalizeString("MyAccount")); + string editHyperLink = string.Format("{1}", editUrl, this.LocalizeString("MyAccount")); template = template.Replace("[HYPERLINK:MYACCOUNT]", editHyperLink); } - buttonPanel.Visible = false; + + this.buttonPanel.Visible = false; } - if (!IsUser && buttonPanel.Visible) + if (!this.IsUser && this.buttonPanel.Visible) { - buttonPanel.Visible = false; + this.buttonPanel.Visible = false; } - if (ProfileUser.Profile.ProfileProperties.Cast().Count(profProperty => profProperty.Visible) == 0) + if (this.ProfileUser.Profile.ProfileProperties.Cast().Count(profProperty => profProperty.Visible) == 0) { - noPropertiesLabel.Visible = true; - profileOutput.Visible = false; - pnlScripts.Visible = false; + this.noPropertiesLabel.Visible = true; + this.profileOutput.Visible = false; + this.pnlScripts.Visible = false; } else { if (template.IndexOf("[PROFILE:PHOTO]") > -1) { var profileImageHandlerBasedURL = - UserController.Instance?.GetUserProfilePictureUrl(ProfileUserId, 120, 120); + UserController.Instance?.GetUserProfilePictureUrl(this.ProfileUserId, 120, 120); template = template.Replace("[PROFILE:PHOTO]", profileImageHandlerBasedURL); } - var token = new TokenReplace { User = ProfileUser, AccessingUser = ModuleContext.PortalSettings.UserInfo }; - profileOutput.InnerHtml = token.ReplaceEnvironmentTokens(template); - noPropertiesLabel.Visible = false; - profileOutput.Visible = true; + var token = new TokenReplace { User = this.ProfileUser, AccessingUser = this.ModuleContext.PortalSettings.UserInfo }; + this.profileOutput.InnerHtml = token.ReplaceEnvironmentTokens(template); + this.noPropertiesLabel.Visible = false; + this.profileOutput.Visible = true; } - var propertyAccess = new ProfilePropertyAccess(ProfileUser); + var propertyAccess = new ProfilePropertyAccess(this.ProfileUser); StringBuilder sb = new StringBuilder(); bool propertyNotFound = false; - foreach (ProfilePropertyDefinition property in ProfileUser.Profile.ProfileProperties) + foreach (ProfilePropertyDefinition property in this.ProfileUser.Profile.ProfileProperties) { var displayDataType = ProfilePropertyAccess.DisplayDataType(property).ToLowerInvariant(); - string value = propertyAccess.GetProperty(property.PropertyName, - String.Empty, - Thread.CurrentThread.CurrentUICulture, - ModuleContext.PortalSettings.UserInfo, - Scope.DefaultSettings, - ref propertyNotFound); - - + string value = propertyAccess.GetProperty( + property.PropertyName, + string.Empty, + Thread.CurrentThread.CurrentUICulture, + this.ModuleContext.PortalSettings.UserInfo, + Scope.DefaultSettings, + ref propertyNotFound); + var clientName = Localization.GetSafeJSString(property.PropertyName); sb.Append("self['" + clientName + "'] = ko.observable("); sb.Append("\""); if (!string.IsNullOrEmpty(value)) { - value = Localization.GetSafeJSString(displayDataType == "richtext" ? value : Server.HtmlDecode(value)); + value = Localization.GetSafeJSString(displayDataType == "richtext" ? value : this.Server.HtmlDecode(value)); value = value .Replace("\r", string.Empty) .Replace("\n", " ") .Replace(";", string.Empty) - .Replace("://", ":||") //protect http protocols won't be replaced in next step + .Replace("://", ":||") // protect http protocols won't be replaced in next step .Replace("//", string.Empty) - .Replace(":||", "://"); //restore http protocols + .Replace(":||", "://"); // restore http protocols } + sb.Append(value + "\"" + ");"); sb.Append('\n'); sb.Append("self['" + clientName + "Text'] = '"); @@ -200,77 +201,71 @@ protected override void OnLoad(EventArgs e) sb.Append('\n'); } - string email = (ProfileUserId == ModuleContext.PortalSettings.UserId - || ModuleContext.PortalSettings.UserInfo.IsInRole(ModuleContext.PortalSettings.AdministratorRoleName)) - ? ProfileUser.Email - : String.Empty; + string email = (this.ProfileUserId == this.ModuleContext.PortalSettings.UserId + || this.ModuleContext.PortalSettings.UserInfo.IsInRole(this.ModuleContext.PortalSettings.AdministratorRoleName)) + ? this.ProfileUser.Email + : string.Empty; sb.Append("self.Email = ko.observable('"); - email = Localization.GetSafeJSString(Server.HtmlDecode(email)); + email = Localization.GetSafeJSString(this.Server.HtmlDecode(email)); email = email.Replace(";", string.Empty).Replace("//", string.Empty); sb.Append(email + "');"); sb.Append('\n'); sb.Append("self.EmailText = '"); - sb.Append(LocalizeString("Email") + "';"); + sb.Append(this.LocalizeString("Email") + "';"); sb.Append('\n'); + + this.ProfileProperties = sb.ToString(); + } + catch (Exception exc) + { + // Module failed to load + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + private string GetRedirectUrl() + { + // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. + var homeTabId = this.ModuleContext.PortalSettings.HomeTabId; + string redirectUrl; + if (homeTabId > Null.NullInteger) + { + redirectUrl = this._navigationManager.NavigateURL(homeTabId); + } + else + { + redirectUrl = Globals.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, this.Request, true) + + "/" + Globals.glbDefaultPage; + } - ProfileProperties = sb.ToString(); - - - } - catch (Exception exc) - { - //Module failed to load - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - #endregion - - #region Private Methods - - private string GetRedirectUrl() - { - //redirect user to default page if not specific the home tab, do this action to prevent loop redirect. - var homeTabId = ModuleContext.PortalSettings.HomeTabId; - string redirectUrl; - - if (homeTabId > Null.NullInteger) - { - redirectUrl = _navigationManager.NavigateURL(homeTabId); - } - else - { - redirectUrl = Globals.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, Request, true) + - "/" + Globals.glbDefaultPage; - } - - return redirectUrl; - } + return redirectUrl; + } private void ProcessQuerystring() { - //in case someone is being redirected to here from an e-mail link action we need to process that here - - var action = Request.QueryString["action"]; + // in case someone is being redirected to here from an e-mail link action we need to process that here + var action = this.Request.QueryString["action"]; - if (!Request.IsAuthenticated && !string.IsNullOrEmpty(action)) //action requested but not logged in. + if (!this.Request.IsAuthenticated && !string.IsNullOrEmpty(action)) // action requested but not logged in. { - string loginUrl = Common.Globals.LoginURL(Request.RawUrl, false); - Response.Redirect(loginUrl); + string loginUrl = Common.Globals.LoginURL(this.Request.RawUrl, false); + this.Response.Redirect(loginUrl); } - if (Request.IsAuthenticated && !string.IsNullOrEmpty(action) ) // only process this for authenticated requests + + if (this.Request.IsAuthenticated && !string.IsNullOrEmpty(action)) // only process this for authenticated requests { - //current user, i.e. the one that the request was for + // current user, i.e. the one that the request was for var currentUser = UserController.Instance.GetCurrentUserInfo(); + // the initiating user,i.e. the one who wanted to be friend // note that in this case here currentUser is visiting the profile of initiatingUser, most likely from a link in the notification e-mail - var initiatingUser = UserController.Instance.GetUserById(PortalSettings.Current.PortalId, Convert.ToInt32(Request.QueryString["UserID"])); + var initiatingUser = UserController.Instance.GetUserById(PortalSettings.Current.PortalId, Convert.ToInt32(this.Request.QueryString["UserID"])); if (initiatingUser.UserID == currentUser.UserID) { - return; //do not further process for users who are on their own profile page + return; // do not further process for users who are on their own profile page } var friendRelationship = RelationshipController.Instance.GetFriendRelationship(currentUser, initiatingUser); @@ -297,15 +292,13 @@ private void ProcessQuerystring() } catch { - //ignore + // ignore } } } - Response.Redirect(Common.Globals.UserProfileURL(initiatingUser.UserID)); + this.Response.Redirect(Common.Globals.UserProfileURL(initiatingUser.UserID)); } - } - - #endregion + } } } diff --git a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Login.ascx.resx b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Login.ascx.resx index 5197ccf842f..aad7bd51a74 100644 --- a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Login.ascx.resx +++ b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Login.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Settings.ascx.resx b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Settings.ascx.resx index 9ece8c674fa..6cd59793698 100644 --- a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Settings.ascx.resx +++ b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/App_LocalResources/Settings.ascx.resx @@ -59,7 +59,7 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - + diff --git a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs index ec046303f8d..35f08506e51 100644 --- a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs +++ b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs @@ -1,270 +1,295 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Authentication.DNN { + using System; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; using Host = DotNetNuke.Entities.Host.Host; - - /// - /// The Login AuthenticationLoginBase is used to provide a login for a registered user - /// portal. - /// - /// - /// - public partial class Login : AuthenticationLoginBase - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (Login)); + + /// + /// The Login AuthenticationLoginBase is used to provide a login for a registered user + /// portal. + /// + /// + /// + public partial class Login : AuthenticationLoginBase + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Login)); private readonly INavigationManager _navigationManager; public Login() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Protected Properties - - /// - /// Gets whether the Captcha control is used to validate the login - /// - protected bool UseCaptcha - { - get - { - return AuthenticationConfig.GetConfig(PortalId).UseCaptcha; - } - } - - #endregion - - #region Public Properties - - /// - /// Check if the Auth System is Enabled (for the Portal) - /// - /// - public override bool Enabled - { - get - { - return AuthenticationConfig.GetConfig(PortalId).Enabled; - } - } - - #endregion - - #region Event Handlers - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + + /// + /// Gets a value indicating whether check if the Auth System is Enabled (for the Portal). + /// + /// + public override bool Enabled + { + get + { + return AuthenticationConfig.GetConfig(this.PortalId).Enabled; + } + } + + /// + /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. + /// + protected bool UseCaptcha + { + get + { + return AuthenticationConfig.GetConfig(this.PortalId).UseCaptcha; + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); - cmdLogin.Click += OnLoginClick; + this.cmdLogin.Click += this.OnLoginClick; - cancelLink.NavigateUrl = GetRedirectUrl(false); + this.cancelLink.NavigateUrl = this.GetRedirectUrl(false); - if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) + if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) + { + this.liRegister.Visible = false; + } + + this.lblLogin.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_LOGIN_INSTRUCTIONS"); + if (string.IsNullOrEmpty(this.lblLogin.Text)) { - liRegister.Visible = false; + this.lblLogin.AssociatedControlID = string.Empty; } - lblLogin.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_LOGIN_INSTRUCTIONS"); - if (string.IsNullOrEmpty(lblLogin.Text)) - { - lblLogin.AssociatedControlID = string.Empty; - } - if (Request.QueryString["usernameChanged"] == "true") + if (this.Request.QueryString["usernameChanged"] == "true") { - DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetSystemMessage(PortalSettings, "MESSAGE_USERNAME_CHANGED_INSTRUCTIONS"), ModuleMessage.ModuleMessageType.BlueInfo); + DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_USERNAME_CHANGED_INSTRUCTIONS"), ModuleMessage.ModuleMessageType.BlueInfo); } - var returnUrl = _navigationManager.NavigateURL(); + var returnUrl = this._navigationManager.NavigateURL(); string url; - if (PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) + if (this.PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) { - if (!string.IsNullOrEmpty(UrlUtils.ValidReturnUrl(Request.QueryString["returnurl"]))) + if (!string.IsNullOrEmpty(UrlUtils.ValidReturnUrl(this.Request.QueryString["returnurl"]))) { - returnUrl = Request.QueryString["returnurl"]; + returnUrl = this.Request.QueryString["returnurl"]; } + returnUrl = HttpUtility.UrlEncode(returnUrl); url = Globals.RegisterURL(returnUrl, Null.NullString); - registerLink.NavigateUrl = url; - if (PortalSettings.EnablePopUps && PortalSettings.RegisterTabId == Null.NullInteger + this.registerLink.NavigateUrl = url; + if (this.PortalSettings.EnablePopUps && this.PortalSettings.RegisterTabId == Null.NullInteger && !AuthenticationController.HasSocialAuthenticationEnabled(this)) { - registerLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, PortalSettings, true, false, 600, 950)); + this.registerLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, this.PortalSettings, true, false, 600, 950)); } } else { - registerLink.Visible = false; + this.registerLink.Visible = false; } - //see if the portal supports persistant cookies - chkCookie.Visible = Host.RememberCheckbox; - - - + // see if the portal supports persistant cookies + this.chkCookie.Visible = Host.RememberCheckbox; + // no need to show password link if feature is disabled, let's check this first if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { - url = _navigationManager.NavigateURL("SendPassword", "returnurl=" + returnUrl); - passwordLink.NavigateUrl = url; - if (PortalSettings.EnablePopUps) + url = this._navigationManager.NavigateURL("SendPassword", "returnurl=" + returnUrl); + this.passwordLink.NavigateUrl = url; + if (this.PortalSettings.EnablePopUps) { - passwordLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, PortalSettings, true, false, 300, 650)); + this.passwordLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, this.PortalSettings, true, false, 300, 650)); } } else { - passwordLink.Visible = false; + this.passwordLink.Visible = false; } - - - if (!IsPostBack) + + if (!this.IsPostBack) { - if (!string.IsNullOrEmpty(Request.QueryString["verificationcode"]) && PortalSettings.UserRegistration == (int) Globals.PortalRegistrationType.VerifiedRegistration) + if (!string.IsNullOrEmpty(this.Request.QueryString["verificationcode"]) && this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) { - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { - Controls.Clear(); + this.Controls.Clear(); } - var verificationCode = Request.QueryString["verificationcode"]; - - + var verificationCode = this.Request.QueryString["verificationcode"]; + try { UserController.VerifyUser(verificationCode.Replace(".", "+").Replace("-", "/").Replace("_", "=")); - var redirectTabId = PortalSettings.Registration.RedirectAfterRegistration; + var redirectTabId = this.PortalSettings.Registration.RedirectAfterRegistration; - if (Request.IsAuthenticated) - { - Response.Redirect(_navigationManager.NavigateURL(redirectTabId > 0 ? redirectTabId : PortalSettings.HomeTabId, string.Empty, "VerificationSuccess=true"), true); - } - else - { + if (this.Request.IsAuthenticated) + { + this.Response.Redirect(this._navigationManager.NavigateURL(redirectTabId > 0 ? redirectTabId : this.PortalSettings.HomeTabId, string.Empty, "VerificationSuccess=true"), true); + } + else + { if (redirectTabId > 0) { - var redirectUrl = _navigationManager.NavigateURL(redirectTabId, string.Empty, "VerificationSuccess=true"); - redirectUrl = redirectUrl.Replace(Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias), string.Empty); - Response.Cookies.Add(new HttpCookie("returnurl", redirectUrl) { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }); + var redirectUrl = this._navigationManager.NavigateURL(redirectTabId, string.Empty, "VerificationSuccess=true"); + redirectUrl = redirectUrl.Replace(Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias), string.Empty); + this.Response.Cookies.Add(new HttpCookie("returnurl", redirectUrl) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); } - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("VerificationSuccess", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess); - } + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("VerificationSuccess", this.LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess); + } } catch (UserAlreadyVerifiedException) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserAlreadyVerified", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserAlreadyVerified", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); } catch (InvalidVerificationCodeException) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } catch (UserDoesNotExistException) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserDoesNotExist", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserDoesNotExist", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } catch (Exception) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } } } - if (!Request.IsAuthenticated) - { - if (!Page.IsPostBack) - { - try - { - if (Request.QueryString["username"] != null) - { - txtUsername.Text = Request.QueryString["username"]; - } - } - catch (Exception ex) - { - //control not there - Logger.Error(ex); - } - } - try - { - Globals.SetFormFocus(string.IsNullOrEmpty(txtUsername.Text) ? txtUsername : txtPassword); - } - catch (Exception ex) - { - //Not sure why this Try/Catch may be necessary, logic was there in old setFormFocus location stating the following - //control not there or error setting focus - Logger.Error(ex); - } - } + if (!this.Request.IsAuthenticated) + { + if (!this.Page.IsPostBack) + { + try + { + if (this.Request.QueryString["username"] != null) + { + this.txtUsername.Text = this.Request.QueryString["username"]; + } + } + catch (Exception ex) + { + // control not there + Logger.Error(ex); + } + } + + try + { + Globals.SetFormFocus(string.IsNullOrEmpty(this.txtUsername.Text) ? this.txtUsername : this.txtPassword); + } + catch (Exception ex) + { + // Not sure why this Try/Catch may be necessary, logic was there in old setFormFocus location stating the following + // control not there or error setting focus + Logger.Error(ex); + } + } - var registrationType = PortalSettings.Registration.RegistrationFormType; - bool useEmailAsUserName; + var registrationType = this.PortalSettings.Registration.RegistrationFormType; + bool useEmailAsUserName; if (registrationType == 0) { - useEmailAsUserName = PortalSettings.Registration.UseEmailAsUserName; + useEmailAsUserName = this.PortalSettings.Registration.UseEmailAsUserName; } else { - var registrationFields = PortalSettings.Registration.RegistrationFields; + var registrationFields = this.PortalSettings.Registration.RegistrationFields; useEmailAsUserName = !registrationFields.Contains("Username"); } - plUsername.Text = LocalizeString(useEmailAsUserName ? "Email" : "Username"); - divCaptcha1.Visible = UseCaptcha; - divCaptcha2.Visible = UseCaptcha; - } + this.plUsername.Text = this.LocalizeString(useEmailAsUserName ? "Email" : "Username"); + this.divCaptcha1.Visible = this.UseCaptcha; + this.divCaptcha2.Visible = this.UseCaptcha; + } + + protected string GetRedirectUrl(bool checkSettings = true) + { + var redirectUrl = string.Empty; + var redirectAfterLogin = this.PortalSettings.Registration.RedirectAfterLogin; + if (checkSettings && redirectAfterLogin > 0) // redirect to after registration page + { + redirectUrl = this._navigationManager.NavigateURL(redirectAfterLogin); + } + else + { + if (this.Request.QueryString["returnurl"] != null) + { + // return to the url passed to register + redirectUrl = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); + + // clean the return url to avoid possible XSS attack. + redirectUrl = UrlUtils.ValidReturnUrl(redirectUrl); + + if (redirectUrl.Contains("?returnurl")) + { + string baseURL = redirectUrl.Substring( + 0, + redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); + string returnURL = + redirectUrl.Substring(redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal) + 11); - private void OnLoginClick(object sender, EventArgs e) - { - if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha) - { - var loginStatus = UserLoginStatus.LOGIN_FAILURE; - string userName = PortalSecurity.Instance.InputFilter(txtUsername.Text, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | + redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); + } + } + + if (string.IsNullOrEmpty(redirectUrl)) + { + // redirect to current page + redirectUrl = this._navigationManager.NavigateURL(); + } + } + + return redirectUrl; + } + + private void OnLoginClick(object sender, EventArgs e) + { + if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || !this.UseCaptcha) + { + var loginStatus = UserLoginStatus.LOGIN_FAILURE; + string userName = PortalSecurity.Instance.InputFilter( + this.txtUsername.Text, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - //DNN-6093 - //check if we use email address here rather than username + // DNN-6093 + // check if we use email address here rather than username UserInfo userByEmail = null; - var emailUsedAsUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false); + var emailUsedAsUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false); if (emailUsedAsUsername) { // one additonal call to db to see if an account with that email actually exists - userByEmail = UserController.GetUserByEmail(PortalController.GetEffectivePortalId(PortalId), userName); + userByEmail = UserController.GetUserByEmail(PortalController.GetEffectivePortalId(this.PortalId), userName); if (userByEmail != null) { - //we need the username of the account in order to authenticate in the next step - userName = userByEmail.Username; + // we need the username of the account in order to authenticate in the next step + userName = userByEmail.Username; } } @@ -272,74 +297,29 @@ private void OnLoginClick(object sender, EventArgs e) if (!emailUsedAsUsername || userByEmail != null) { - objUser = UserController.ValidateUser(PortalId, userName, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus); + objUser = UserController.ValidateUser(this.PortalId, userName, this.txtPassword.Text, "DNN", string.Empty, this.PortalSettings.PortalName, this.IPAddress, ref loginStatus); } var authenticated = Null.NullBoolean; - var message = Null.NullString; - if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED) - { - message = "UserNotAuthorized"; - } - else - { - authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE); - } - - //Raise UserAuthenticated Event - var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN") - { - Authenticated = authenticated, - Message = message, - RememberMe = chkCookie.Checked - }; - OnUserAuthenticated(eventArgs); - } - } - - #endregion - - #region Private Methods - - protected string GetRedirectUrl(bool checkSettings = true) - { - var redirectUrl = ""; - var redirectAfterLogin = PortalSettings.Registration.RedirectAfterLogin; - if (checkSettings && redirectAfterLogin > 0) //redirect to after registration page - { - redirectUrl = _navigationManager.NavigateURL(redirectAfterLogin); - } - else - { - if (Request.QueryString["returnurl"] != null) - { - //return to the url passed to register - redirectUrl = HttpUtility.UrlDecode(Request.QueryString["returnurl"]); - - //clean the return url to avoid possible XSS attack. - redirectUrl = UrlUtils.ValidReturnUrl(redirectUrl); - - if (redirectUrl.Contains("?returnurl")) - { - string baseURL = redirectUrl.Substring(0, - redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); - string returnURL = - redirectUrl.Substring(redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal) + 11); - - redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); - } - } - if (String.IsNullOrEmpty(redirectUrl)) - { - //redirect to current page - redirectUrl = _navigationManager.NavigateURL(); - } - } - - return redirectUrl; - } - - #endregion + var message = Null.NullString; + if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED) + { + message = "UserNotAuthorized"; + } + else + { + authenticated = loginStatus != UserLoginStatus.LOGIN_FAILURE; + } - } + // Raise UserAuthenticated Event + var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN") + { + Authenticated = authenticated, + Message = message, + RememberMe = this.chkCookie.Checked, + }; + this.OnUserAuthenticated(eventArgs); + } + } + } } diff --git a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Settings.ascx.cs b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Settings.ascx.cs index edfc1fa3786..19d21275f14 100644 --- a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Settings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Settings.ascx.cs @@ -1,25 +1,20 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Authentication { + using System; + + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Exceptions; + public partial class Settings : AuthenticationSettingsBase { public override void UpdateSettings() { - if (SettingsEditor.IsValid && SettingsEditor.IsDirty) + if (this.SettingsEditor.IsValid && this.SettingsEditor.IsDirty) { - var config = (AuthenticationConfig) SettingsEditor.DataSource; + var config = (AuthenticationConfig)this.SettingsEditor.DataSource; AuthenticationConfig.UpdateConfig(config); } } @@ -30,9 +25,9 @@ protected override void OnLoad(EventArgs e) try { - AuthenticationConfig config = AuthenticationConfig.GetConfig(PortalId); - SettingsEditor.DataSource = config; - SettingsEditor.DataBind(); + AuthenticationConfig config = AuthenticationConfig.GetConfig(this.PortalId); + this.SettingsEditor.DataSource = config; + this.SettingsEditor.DataBind(); } catch (Exception exc) { diff --git a/DNN Platform/Website/DesktopModules/SiteExportImport/App_LocalResources/ExportImport.resx b/DNN Platform/Website/DesktopModules/SiteExportImport/App_LocalResources/ExportImport.resx index 724b0e64474..44d92d1d663 100644 --- a/DNN Platform/Website/DesktopModules/SiteExportImport/App_LocalResources/ExportImport.resx +++ b/DNN Platform/Website/DesktopModules/SiteExportImport/App_LocalResources/ExportImport.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/Documentation/Contributors.txt b/DNN Platform/Website/Documentation/Contributors.txt deleted file mode 100644 index e994c54f02b..00000000000 --- a/DNN Platform/Website/Documentation/Contributors.txt +++ /dev/null @@ -1,77 +0,0 @@ -Third Party Acknowledgements -============================================================================== - -Brian Bilbro ( bbilbro@hotmail.com ) -- Module Communicator code and architecture (http://aspalliance.com/bbilbro/DesktopDefault.aspx?tabindex=1&tabid=7&ArticleID=6 ) - -Atif Aziz -- SQLCommandGenerator - -Daniel Willmott -- Unauthenticated user - -Fredi Gertsch ( fredi@gerts.ch ) -- Tab Administrator - -Jon Henning - Solution Partners - (http://www.solpart.com) -- Solpart Menu - -John Dyer - Revjon Studios (http://www.revjon.com) -- FreeTextBox - -Robin Lilly, Vanessa Monzon, Mike Hernandez -- UTEP ADA Code Base - -Tom Trefz && Scott Willhite -- PopupCalendar.js (original by Tom, localization && Netscape by Scott) - -Richard Cox ( http://www.bydesignwebsights.com ) -- Search engine optimization at the Tab level ( Description, KeyWords, Title ) - -Dino Esposito ( http://weblogs.asp.net/despos ) -- Personalization architecture from MSDN magazine ( Cutting Edge - March 2004 ) - -Jeff Martin ( http://www.jeffmartin.com ) -- move ViewState to bottom of page for better search engine spidering - -Jonathan de Halleux ( http://www.dotnetwiki.org ) -- PA Installer - -David Haggard ( http://www.newcovenant.com ) -- function to obfuscate sensitive data to prevent collection by robots and spiders and crawlers - -Vicen?Masanas ( http://lacolla.europe.webmatrixhosting.net ) -- SMTP authentication - -Bert Corderman -- Several base classes for Exception Management in DNN 2.0 - -Joe Brinkman ( http://www.tag-software.net ) -- Module Action Menu concept - -Patrick Santry ( http://www.wwwcoder.com ) -- PayPal price checking and account checking - -M. Murali Dharan ( http://www.phpbuilder.com/columns/dhar20040217.php3 ) -- Search Engine Concepts - -Craig Dunn ( http://users.bigpond.com/conceptdevelopment/ ) -- Search Engine Concepts ( Searcharoo ) - -Stan Schultes ( http://www.csnetexpert.com ) -- RSS Generator ( Visual Studio Magazine - April 2004 ) - -James Clarkson ( http://www.blogolith.com ) -- Favicon per portal - -Scott Mitchell ( http://4guysfromrolla.com ) -- URL Rewriting - -Scott Stokes ( http://www.adverageous.com ) -- File Manager UI ( based on DNNExplorer ) - -Michael Beller ( http://www.lightshippartners.com ) -- Database model for abstraction and refactoring of the core database - -Sebastian Leupold ( http://www.gamma-concept.de ) -- German resource files diff --git a/DNN Platform/Website/Documentation/License.txt b/DNN Platform/Website/Documentation/License.txt deleted file mode 100644 index d12b262792a..00000000000 --- a/DNN Platform/Website/Documentation/License.txt +++ /dev/null @@ -1,9 +0,0 @@ -DotNetNuke - http://www.dnnsoftware.com -Copyright (c) 2002-2018 -by DNN Corporation - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/DNN Platform/Website/Documentation/Readme.txt b/DNN Platform/Website/Documentation/Readme.txt deleted file mode 100644 index 89f4f1b2919..00000000000 --- a/DNN Platform/Website/Documentation/Readme.txt +++ /dev/null @@ -1,3 +0,0 @@ -About DNN Platform -The DNN Platform Installation Guide can be found here: https://dnndocs.com/ -For DNN Community Help and Support visit https://dnncommunity.org/ diff --git a/DNN Platform/Website/Documentation/StarterKit/Documents.css b/DNN Platform/Website/Documentation/StarterKit/Documents.css deleted file mode 100644 index 62d028ea436..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/Documents.css +++ /dev/null @@ -1,82 +0,0 @@ - -Body, A -{ - font-family: Verdana, Arial, Helvetica, Sans Serif; - font-size: 10pt; - font-weight: normal; - color: black; -} - -Body -{ - background-color: white; - margin-left:25px; -} - -H1 -{ - font-size: 2.0em; - font-weight: bold; - color: #75808A; - text-decoration: underline; -} - -H2 { - font-size: 1.6em; - font-weight: bold; - color: #75808A; -} - -H3 { - font-size: 1.4em; - font-weight: bold; - color: #75808A; -} - -H4 { - font-size: 1.2em; - font-weight: bold; - color: #75808A; -} - -H5 { - font-size: 1.1em; - font-weight: bold; - color: #75808A; -} - -H6 { - font-size: 1.0em; - font-weight: bold; - color: #75808A; -} - -A:link { - font-size: 1.0em; - text-decoration: underline; - color: #0000cc; -} - -A:visited { - font-size: 1.0em; - text-decoration: underline; - color: #0000cc; -} - -A:active { - font-size: 1.0em; - text-decoration: underline; - color: #0000cc; -} - -A:hover { - font-size: 1.0em; - text-decoration: underline; - color: #cc0000; -} - -HR { - color: dimgrey; - height:1pt; - text-align:left -} diff --git a/DNN Platform/Website/Documentation/StarterKit/NTFSConfig.html b/DNN Platform/Website/Documentation/StarterKit/NTFSConfig.html deleted file mode 100644 index 9e1da57c967..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/NTFSConfig.html +++ /dev/null @@ -1,26 +0,0 @@ - - - DotNetNuke - - - - -

        Configuring NTFS File Permissions for DotNetNuke

        -

        This section includes more detailed information on how to configure NTFS - File permissions for use with DotNetNuke.

        -

        1. There are two ways in which you can configure the NTFS File permissions.  - In Internet Information Services (IIS) Manager, choose the website and select Permissions.

        -

        -

        or in File Explorer select the Physical Directory for the Website and .

        -

        -

        2. In the Security dialog select the account (NETWORK SERVICE in Windows 2003, ASPNET - in Windows 2000), and give the account Read,Write and Change permissions to the - folder..

        -

        - -

        -

        Back to Welcome page.

        -
        - - diff --git a/DNN Platform/Website/Documentation/StarterKit/SQLServer2005Config.html b/DNN Platform/Website/Documentation/StarterKit/SQLServer2005Config.html deleted file mode 100644 index 81e758adf62..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/SQLServer2005Config.html +++ /dev/null @@ -1,33 +0,0 @@ - - - DotNetNuke - - - - -

        Configuring SQL Server 2005 for DotNetNuke

        -

        This section includes more detailed information on how to create and configure a SQL Server 2005 database for use with DotNetNuke.

        -

        1. In SQL Server Management Studio, in the Object Explorer, Select Databases for - the SQL Server instance you wish to use, right-click and select the New Database - option.

        -

        -

        2. In the New Database dialog give the Database a name (in the example below the - Databse is called Website), and click OK.

        -

        -

        3. If you decide to use SQL Server Authorization then you will need to use a SQL - Server Login.  If you do not already have one created then you can create one - by selecting Logins under Security, right click and select New Login.

        -

        -

        4. Once you have created a Login you need to add that "Login" as a User for your new Database.  To do this select the Database you just created, select the - Users section, right click on Users and select the New Database User option.  - In the example shown below we are using the Database - DotNetNuke.

        -

        -

        5. Enter the Login name in the text box, or choose the login name by clicking the - elipsis button (...), make sure that the db_owner role, and Schema are selected, and click OK

        -

        -

        Your database is now ready to be installed.

        -

        Back to Welcome page.

        -
        - - diff --git a/DNN Platform/Website/Documentation/StarterKit/SQLServerConfig.html b/DNN Platform/Website/Documentation/StarterKit/SQLServerConfig.html deleted file mode 100644 index 23ee89caab9..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/SQLServerConfig.html +++ /dev/null @@ -1,31 +0,0 @@ - - - DotNetNuke - - - - -

        Configuring SQL Server 2000 for DotNetNuke

        -

        This section includes more detailed information on how to create and configure a SQL Server 2000 database for use with DotNetNuke.

        -

        1. In Enterprise Manager, Select Databases, right-click and select the New Database - option.

        -

        -

        2. In the Database Properties give the Database a name (in the example below the - Databse is called Website), and click OK.

        -

        -

        3. If you decide to use SQL Server Authorization then you will need to use a SQL - Server Login.  If you do not already have one created then you can create one - by selecting Logins under Security, right click and select New Login.

        -

        -

        4. Once you have created a Login you need to add that "Login" as a User for your new Database.  To do this select the Database you just created, select the - Users section, right click on Users and select the New Database User option.

        -

        -

        5. Select the Login name from the combo box - this will automatically populate the - User name field, make sure that the db_owner role is selected, and click OK

        -

        -

        Your database is now ready to be installed.

        -

        Back to Welcome page.

        -
        - - diff --git a/DNN Platform/Website/Documentation/StarterKit/SQLServerXpressConfig.html b/DNN Platform/Website/Documentation/StarterKit/SQLServerXpressConfig.html deleted file mode 100644 index beaf9e31970..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/SQLServerXpressConfig.html +++ /dev/null @@ -1,22 +0,0 @@ - - - DotNetNuke - - - - -

        Configuring SQL Server 2005 Express for DotNetNuke

        -

        This section includes more detailed information on how to create a SQL Server 2005 Express Database file for use with DotNetNuke.

        -

        1. In Solution Explorer select the App_Data folder, right-click on the folder and select Add New Item....

        -

        -

        2. In the Add New Item Dialog, select SQL Database, and click Add

        -

        -

        - The default database name is Database.mdf. If you decide to use a - different filename you will have to edit the connection string in web.config. -

        -

        Back to Welcome page.

        -
        - - diff --git a/DNN Platform/Website/Documentation/StarterKit/TemplateConfig.html b/DNN Platform/Website/Documentation/StarterKit/TemplateConfig.html deleted file mode 100644 index 90191ac127d..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/TemplateConfig.html +++ /dev/null @@ -1,16 +0,0 @@ - - - DotNetNuke - - - - -

        Configuring the Install Template for DotNetNuke

        -

        This section includes more detailed information on how to configure the install template - for  DotNetNuke.

        -

        1. .

        -

        Back to Welcome page.

        -
        - - diff --git a/DNN Platform/Website/Documentation/StarterKit/WebServerConfig.html b/DNN Platform/Website/Documentation/StarterKit/WebServerConfig.html deleted file mode 100644 index 7bdca84b169..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/WebServerConfig.html +++ /dev/null @@ -1,28 +0,0 @@ - - - DotNetNuke - - - - -

        Configuring Internet Information Server (IIS)

        -

        When creating a DotNetNuke website, for the most part you can use the default configuration - options.  However, if you wish to modify the configuration, this section includes more detailed information on how to configure Internet Information - Server (IIS) - for use with DotNetNuke.

        -

        1. In Internet Information Services (IIS) Manager, select Websites, right-click on - the site you wish to configure and select the Properties - option.

        -

        -

        2. In the Properties dialog, you can configure the physical directory used for this - wesbite, as well as the Application settings

        -

        -

        3. On the ASp.NET tab of the Properties dialog, you can choose the version of ASP.NET - you wish to use, as well as edit some of the web.config properties (using the Edit - Configuration button).

        -

        -

        Back to Welcome page.

        -
        - - diff --git a/DNN Platform/Website/Documentation/StarterKit/Welcome.html b/DNN Platform/Website/Documentation/StarterKit/Welcome.html deleted file mode 100644 index f97cde1693f..00000000000 --- a/DNN Platform/Website/Documentation/StarterKit/Welcome.html +++ /dev/null @@ -1,104 +0,0 @@ - - - DotNetNuke - - - - -

        DotNetNuke?Web Application Framework ($safeprojectname$)

        -

        Introduction

        -

        Congratulations! You have created your own DotNetNuke project.  Please - take a few minutes to read this document, as it will help you install and configure - your new website.

        -

        Quick Installation

        -

        In order to make your experience with DotNetNuke as productive as possible, we have optimized the number of installation steps required for web developers.

        -

        - As long as you selected the default options for creating a web project in Visual Studio 2005 - ( selected "File System" as the Location: for your website ) and want to use the default SQL Server 2005 Express database included with the application, - you simpy need to press Ctrl-F5 (ie. hold the Ctrl key down while clicking on the F5 function key) in order to complete your installation. - The application may take a few minutes to build and you may find it useful to monitor the build progress output - ( select View / Output or CTRL-ALT-O within Visual Studio 2005 ). When your web browser loads the initial Installation screen, you must choose the Auto Installation option to successfully complete the process. -

        -
        -

        Advanced Installation

        -

        For those developers are not satisfied with the default options used in the Quick Installation option above - or perhaps want a little more control over the installation process, - we have included Advanced Installation instrustions to cover the most common customizations. -

        - -

        1. Create/Configure Database

        -

        DotNetNuke is a dynamic web application; therefore, you must create/configure a Database.  The default - connection string provided assumes that you will be using a SQL Server - 2005 Express database file called Database.mdf.

        -

        Data Source=.\SQLExpress;
        - Integrated Security=True;
        - User Instance=True;
        - AttachDBFilename=|DataDirectory|Database.mdf;  

        -

        If you would like instructions on creating a SQL Server Express 2005 Database file with a different name then see SQL Server 2005 Express Configuration.

        -

        If you would like to use a standard SQL Server 2000 or SQL Server 2005 Database then - you will need to create and configure one before proceeding.  You will also need to decide on the credentials used to access the Database you created.  - You can use Integrated Security (credentials based on your Windows User Account), - or you can use SQL Server's own security.  Again, the default connection string - assumes the latter.  For more information, on setting up a SQL Server Database - see SQL Server 2000 Configuration or SQL Server 2005 Configuration.

        -

        2. Edit the Connection String in web.config

        -

        Once you have created your database you will need to hook up the connection string in - web.config. There are TWO places in web.config where you need to verify the connection string.  - In the <connectionStrings> node:

        -

         

        -

        and under the <appSettings> node

        -

         

        -

        (Note that the connection string attributes includes line-breaks to make them - more readable - the - actual string must be on one line.)

        -

        The examples shown above are for the default SQL Server 2005 Express database file - "Database.mdf".  If you used - a different filename for the database file, you need to change the AttachDBFilename=|DataDirectory|Database.mdf; section.

        -

        To use a SQL Server 2000 or 2005 database replace the whole connection string by - something similar to

        -

        Server=(local);Database=DatabaseName;uid=LoginName;pwd=LoginPassword;

        -

        3. Configure the Web Server

        -

        For the most part, you should not need to configure your web server.  It does - not matter whether you selected the File System (default) or HTTP (IIS) as the Location: for your web server. - In either case the default configurations should work.  - In fact the File System web server has no configuration options.  However, - if you would like further information on configuring IIS please see Configuring Internet Information Server (IIS).

        -

        4. Configure NTFS File Permissions

        -

        If you created your new project using the HTTP option (IIS) then you need to set - the permissions for the System Account used by ASP.NET.  This step is not neccessary - if you used the File System (default) option to create your new site.

        -

        The NETWORK SERVICE account (Windows 2003) or the ASPNET account (Windows 2000) must - be given Full Control on the Virtual Directory you are using.  For more information - see NTFS Permissions Configuration.

        -

        5. Choose a Site Template

        -

        DotNetNuke installations use a template to determine what content gets loaded when the site is first created.  - There are 4 templates available

        -
          -
        • DotNetNuke (default)
        • -
        • Personal
        • -
        • Club
        • -
        • Small Business
        • -
        -

        Under normal circumstances you do not need to do anything ( the site will install using the default template ), - but if you would like to install based on one of the alternate templates, or would - like more information on templates see Configuring the Install Template.

        -

        6. Install DotNetNuke

        -

        If you have completed the steps above, you are now ready to install your new - DotNetNuke site.  To install the site press Ctrl-F5 (ie hold the Ctrl key down while clicking on the F5 function key). The application may take a few minutes to build if this - is your first installation. In order to view the build progress you should select - View / Output ( CTRL- ALT-O ) from Visual Studio 2005.
        -   -

        -
        -

        Further Resources

        -

        The information in this page is only an overview of the DotNetNuke?Web Application Framework. For more information, visit www.dotnetnuke.com. -

        - - diff --git a/DNN Platform/Website/Documentation/StarterKit/images/AddDatabase.jpg b/DNN Platform/Website/Documentation/StarterKit/images/AddDatabase.jpg deleted file mode 100644 index b72d26d0ad5..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/AddDatabase.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/AppSetting.gif b/DNN Platform/Website/Documentation/StarterKit/images/AppSetting.gif deleted file mode 100644 index 11a1e496b0a..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/AppSetting.gif and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/App_Data.jpg b/DNN Platform/Website/Documentation/StarterKit/images/App_Data.jpg deleted file mode 100644 index 303bb4e4781..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/App_Data.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/ConnectionString.gif b/DNN Platform/Website/Documentation/StarterKit/images/ConnectionString.gif deleted file mode 100644 index 3c7f395559e..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/ConnectionString.gif and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/Database2005Properties.jpg b/DNN Platform/Website/Documentation/StarterKit/images/Database2005Properties.jpg deleted file mode 100644 index 668f2d6ee6c..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/Database2005Properties.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/DatabaseProperties.jpg b/DNN Platform/Website/Documentation/StarterKit/images/DatabaseProperties.jpg deleted file mode 100644 index a527107975c..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/DatabaseProperties.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/EditWeb.jpg b/DNN Platform/Website/Documentation/StarterKit/images/EditWeb.jpg deleted file mode 100644 index 6ba663d8690..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/EditWeb.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/FileSecurity.jpg b/DNN Platform/Website/Documentation/StarterKit/images/FileSecurity.jpg deleted file mode 100644 index f63f2130dbc..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/FileSecurity.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/IISPermissions.jpg b/DNN Platform/Website/Documentation/StarterKit/images/IISPermissions.jpg deleted file mode 100644 index c0338eb198a..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/IISPermissions.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/NTFSPermissions.jpg b/DNN Platform/Website/Documentation/StarterKit/images/NTFSPermissions.jpg deleted file mode 100644 index 6e57db9444f..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/NTFSPermissions.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/New2005Database.jpg b/DNN Platform/Website/Documentation/StarterKit/images/New2005Database.jpg deleted file mode 100644 index 23428417e9f..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/New2005Database.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/New2005Login.jpg b/DNN Platform/Website/Documentation/StarterKit/images/New2005Login.jpg deleted file mode 100644 index 28deb6bf299..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/New2005Login.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/New2005User.jpg b/DNN Platform/Website/Documentation/StarterKit/images/New2005User.jpg deleted file mode 100644 index 9a9db8484e8..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/New2005User.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/NewDatabase.jpg b/DNN Platform/Website/Documentation/StarterKit/images/NewDatabase.jpg deleted file mode 100644 index e7f1ec269a6..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/NewDatabase.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/NewLogin.jpg b/DNN Platform/Website/Documentation/StarterKit/images/NewLogin.jpg deleted file mode 100644 index 68a0296c1ac..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/NewLogin.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/NewUser.jpg b/DNN Platform/Website/Documentation/StarterKit/images/NewUser.jpg deleted file mode 100644 index 3d57b53ac75..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/NewUser.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/User2005Properties.jpg b/DNN Platform/Website/Documentation/StarterKit/images/User2005Properties.jpg deleted file mode 100644 index 3fdb954f5e7..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/User2005Properties.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/UserProperties.jpg b/DNN Platform/Website/Documentation/StarterKit/images/UserProperties.jpg deleted file mode 100644 index f7f14ec7974..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/UserProperties.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/WebProperties1.jpg b/DNN Platform/Website/Documentation/StarterKit/images/WebProperties1.jpg deleted file mode 100644 index 7f88bfb76c9..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/WebProperties1.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/WebProperties2.jpg b/DNN Platform/Website/Documentation/StarterKit/images/WebProperties2.jpg deleted file mode 100644 index 3f742d63ff8..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/WebProperties2.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/images/webconfig.jpg b/DNN Platform/Website/Documentation/StarterKit/images/webconfig.jpg deleted file mode 100644 index 50eaaa44ed2..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/images/webconfig.jpg and /dev/null differ diff --git a/DNN Platform/Website/Documentation/StarterKit/logo.gif b/DNN Platform/Website/Documentation/StarterKit/logo.gif deleted file mode 100644 index 64ab1765b65..00000000000 Binary files a/DNN Platform/Website/Documentation/StarterKit/logo.gif and /dev/null differ diff --git a/DNN Platform/Website/Documentation/TELERIK_EULA.pdf b/DNN Platform/Website/Documentation/TELERIK_EULA.pdf deleted file mode 100644 index 199299d26b2..00000000000 Binary files a/DNN Platform/Website/Documentation/TELERIK_EULA.pdf and /dev/null differ diff --git a/DNN Platform/Website/DotNetNuke.Website.csproj b/DNN Platform/Website/DotNetNuke.Website.csproj index 46163b03e22..6260b6adc69 100644 --- a/DNN Platform/Website/DotNetNuke.Website.csproj +++ b/DNN Platform/Website/DotNetNuke.Website.csproj @@ -612,6 +612,7 @@ + @@ -626,6 +627,9 @@ + + stylecop.json + AuthenticationEditor.ascx @@ -788,6 +792,13 @@ install.aspx + + InstallWizard.aspx + ASPXCodeBehind + + + InstallWizard.aspx + UpgradeWizard.aspx ASPXCodeBehind @@ -2144,7 +2155,6 @@ - @@ -2766,6 +2776,12 @@ + + Designer + + + portal.template.xsd + @@ -3326,7 +3342,11 @@ + + + + @@ -3402,6 +3422,10 @@ + + + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) diff --git a/DNN Platform/Website/ErrorPage.aspx.cs b/DNN Platform/Website/ErrorPage.aspx.cs index 86ca3f8f9af..58de87edc27 100644 --- a/DNN Platform/Website/ErrorPage.aspx.cs +++ b/DNN Platform/Website/ErrorPage.aspx.cs @@ -1,77 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.UI; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security; -using DotNetNuke.Services.FileSystem; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.Services.Exceptions + // ReSharper restore CheckNamespace { + using System; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.Services.FileSystem; + + using Localization = DotNetNuke.Services.Localization.Localization; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : ErrorPage - /// + /// Project : DotNetNuke + /// Class : ErrorPage + /// /// ----------------------------------------------------------------------------- /// - /// Trapped errors are redirected to this universal error page, resulting in a + /// Trapped errors are redirected to this universal error page, resulting in a /// graceful display. /// /// /// 'get the last server error /// 'process this error using the Exception Management Application Block /// 'add to a placeholder and place on page - /// 'catch direct access - No exception was found...you shouldn't end up here unless you go to this aspx page URL directly + /// 'catch direct access - No exception was found...you shouldn't end up here unless you go to this aspx page URL directly. /// /// ----------------------------------------------------------------------------- public partial class ErrorPage : Page { - private void ManageError(string status) - { - string errorMode = Config.GetCustomErrorMode(); - - string errorMessage = HttpUtility.HtmlEncode(Request.QueryString["error"]); - string errorMessage2 = HttpUtility.HtmlEncode(Request.QueryString["error2"]); - string localizedMessage = Localization.Localization.GetString(status + ".Error", Localization.Localization.GlobalResourceFile); - if (localizedMessage != null) - { - localizedMessage = localizedMessage.Replace("src=\"images/403-3.gif\"", "src=\"" + ResolveUrl("~/images/403-3.gif") + "\""); - - if (!string.IsNullOrEmpty(errorMessage2) && ( (errorMode=="Off") || ( (errorMode=="RemoteOnly") && (Request.IsLocal) ) )) - { - ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage2))); - } - else - { - ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage))); - } - } - - int statusCode; - Int32.TryParse(status, out statusCode); - - if (statusCode > -1) - { - Response.StatusCode = statusCode; - } - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - DefaultStylesheet.Attributes["href"] = ResolveUrl("~/Portals/_default/default.css"); - InstallStylesheet.Attributes["href"] = ResolveUrl("~/Install/install.css"); + this.DefaultStylesheet.Attributes["href"] = this.ResolveUrl("~/Portals/_default/default.css"); + this.InstallStylesheet.Attributes["href"] = this.ResolveUrl("~/Install/install.css"); } protected override void OnLoad(EventArgs e) @@ -79,56 +47,89 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (portalSettings != null && !String.IsNullOrEmpty(portalSettings.LogoFile)) + if (portalSettings != null && !string.IsNullOrEmpty(portalSettings.LogoFile)) { IFileInfo fileInfo = FileManager.Instance.GetFile(portalSettings.PortalId, portalSettings.LogoFile); if (fileInfo != null) { - headerImage.ImageUrl = FileManager.Instance.GetUrl(fileInfo); + this.headerImage.ImageUrl = FileManager.Instance.GetUrl(fileInfo); } } - headerImage.Visible = !string.IsNullOrEmpty(headerImage.ImageUrl); + + this.headerImage.Visible = !string.IsNullOrEmpty(this.headerImage.ImageUrl); string localizedMessage; var security = PortalSecurity.Instance; - var status = security.InputFilter(Request.QueryString["status"], - PortalSecurity.FilterFlag.NoScripting | + var status = security.InputFilter( + this.Request.QueryString["status"], + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoMarkup); if (!string.IsNullOrEmpty(status)) { - ManageError(status); + this.ManageError(status); } else { - //get the last server error - var exc = Server.GetLastError(); + // get the last server error + var exc = this.Server.GetLastError(); try { - if (Request.Url.LocalPath.ToLowerInvariant().EndsWith("installwizard.aspx")) + if (this.Request.Url.LocalPath.ToLowerInvariant().EndsWith("installwizard.aspx")) { - ErrorPlaceHolder.Controls.Add(new LiteralControl(HttpUtility.HtmlEncode(exc.ToString()))); + this.ErrorPlaceHolder.Controls.Add(new LiteralControl(HttpUtility.HtmlEncode(exc.ToString()))); } else { var lex = new PageLoadException(exc.Message, exc); Exceptions.LogException(lex); - localizedMessage = Localization.Localization.GetString("Error.Text", Localization.Localization.GlobalResourceFile); - ErrorPlaceHolder.Controls.Add(new ErrorContainer(portalSettings, localizedMessage, lex).Container); + localizedMessage = Localization.GetString("Error.Text", Localization.GlobalResourceFile); + this.ErrorPlaceHolder.Controls.Add(new ErrorContainer(portalSettings, localizedMessage, lex).Container); } } catch { - //No exception was found...you shouldn't end up here - //unless you go to this aspx page URL directly - localizedMessage = Localization.Localization.GetString("UnhandledError.Text", Localization.Localization.GlobalResourceFile); - ErrorPlaceHolder.Controls.Add(new LiteralControl(localizedMessage)); + // No exception was found...you shouldn't end up here + // unless you go to this aspx page URL directly + localizedMessage = Localization.GetString("UnhandledError.Text", Localization.GlobalResourceFile); + this.ErrorPlaceHolder.Controls.Add(new LiteralControl(localizedMessage)); } - Response.StatusCode = 500; + this.Response.StatusCode = 500; + } + + localizedMessage = Localization.GetString("Return.Text", Localization.GlobalResourceFile); + + this.hypReturn.Text = localizedMessage; + } + + private void ManageError(string status) + { + string errorMode = Config.GetCustomErrorMode(); + + string errorMessage = HttpUtility.HtmlEncode(this.Request.QueryString["error"]); + string errorMessage2 = HttpUtility.HtmlEncode(this.Request.QueryString["error2"]); + string localizedMessage = Localization.GetString(status + ".Error", Localization.GlobalResourceFile); + if (localizedMessage != null) + { + localizedMessage = localizedMessage.Replace("src=\"images/403-3.gif\"", "src=\"" + this.ResolveUrl("~/images/403-3.gif") + "\""); + + if (!string.IsNullOrEmpty(errorMessage2) && ((errorMode == "Off") || ((errorMode == "RemoteOnly") && this.Request.IsLocal))) + { + this.ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage2))); + } + else + { + this.ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage))); + } } - localizedMessage = Localization.Localization.GetString("Return.Text", Localization.Localization.GlobalResourceFile); - hypReturn.Text = localizedMessage; + int statusCode; + int.TryParse(status, out statusCode); + + if (statusCode > -1) + { + this.Response.StatusCode = statusCode; + } } } } diff --git a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.de-DE.resx b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.de-DE.resx index 6dcc17f0b10..16976c750bd 100644 --- a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.de-DE.resx +++ b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.de-DE.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -253,7 +253,7 @@ Produktverbesserungsprogramm - Das Produktverbesserungsprogramm ermöglicht uns, besser zu verstehen, wie wir DNN für Sie verbessern können. Die Daten helfen uns, die Nutzung zu analysieren und was für die Nutzer des Produkts wichtig ist. Alle Daten sind anonym und nur für den internen Gebrauch bestimmt. Erfahren Sie mehr über das <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Produktverbesserungsprogramm</a>. + Das Produktverbesserungsprogramm ermöglicht uns, besser zu verstehen, wie wir DNN für Sie verbessern können. Die Daten helfen uns, die Nutzung zu analysieren und was für die Nutzer des Produkts wichtig ist. Alle Daten sind anonym und nur für den internen Gebrauch bestimmt. Erfahren Sie mehr über das <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Produktverbesserungsprogramm</a>. Senden Sie anonyme Nutzungsinformationen an DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.es-ES.resx b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.es-ES.resx index 2468ad50d9d..cb24b0ea055 100644 --- a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.es-ES.resx +++ b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.es-ES.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -319,7 +319,7 @@ Utilice el Explorador de Windows para ver las carpetas de su sitio web ( {0} ). El grupo de aplicaciones de IIS tiene que ejecutarse en Modo Integrado - El programa de mejoras del producto nos permite entender mejor como mejorar DNN para usted. Los datos enviados nos ayudarán a analizar el uso y lo que es más importante para los usuarios del producto. Todos los datos enviados son anónimos y para uso interno. Ver más información sobre el <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Programa de Mejoras del Producto</a>. + El programa de mejoras del producto nos permite entender mejor como mejorar DNN para usted. Los datos enviados nos ayudarán a analizar el uso y lo que es más importante para los usuarios del producto. Todos los datos enviados son anónimos y para uso interno. Ver más información sobre el <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Programa de Mejoras del Producto</a>. Enviar información anónima de uso a DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.fr-FR.resx b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.fr-FR.resx index 1466e7a03a9..8f66e7ce7b5 100644 --- a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.fr-FR.resx +++ b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.fr-FR.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -253,7 +253,7 @@ Programme d'amélioration du produit - Le programme d'amélioration des produits nous permet de mieux comprendre comment nous pouvons améliorer DNN pour vous. Les données nous aideront à analyser l'utilisation et ce qui est important pour les personnes qui utilisent le produit. Toutes les données sont anonymes et à usage interne seulement. En savoir plus sur le <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programme d'amélioration des produits</a>. + Le programme d'amélioration des produits nous permet de mieux comprendre comment nous pouvons améliorer DNN pour vous. Les données nous aideront à analyser l'utilisation et ce qui est important pour les personnes qui utilisent le produit. Toutes les données sont anonymes et à usage interne seulement. En savoir plus sur le <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programme d'amélioration des produits</a>. Envoyer des informations d'utilisation anonymes à DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.it-IT.resx b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.it-IT.resx index 66c16906f8a..872c8c2299e 100644 --- a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.it-IT.resx +++ b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.it-IT.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -253,7 +253,7 @@ Programma di miglioramento del prodotto - Il programma di miglioramento del prodotto ci consente di capire meglio come possiamo migliorare DNN per te. I dati ci aiuteranno ad analizzare l'utilizzo e ciò che è importante per le persone che utilizzano il prodotto. Tutti i dati sono anonimi e solo per uso interno. Ulteriori informazioni sul <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programma di miglioramento del prodotto</a>. + Il programma di miglioramento del prodotto ci consente di capire meglio come possiamo migliorare DNN per te. I dati ci aiuteranno ad analizzare l'utilizzo e ciò che è importante per le persone che utilizzano il prodotto. Tutti i dati sono anonimi e solo per uso interno. Ulteriori informazioni sul <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programma di miglioramento del prodotto</a>. Invia informazioni anonime sull'uso a DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx index 75556c03326..7dc45beb330 100644 --- a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx +++ b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.nl-NL.resx @@ -1,110 +1,5 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx @@ -112,16 +7,22 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Ga akkoord met de gebruikersvoorwaarden om door te gaan. + + + Ik ga akkoord met de <a href="../Licenses/Dnn_Corp_License.pdf" target="_blank">gebruikersvoorwaarden</a> + - Vul uw Account informatie in + Vul je accountinformatie in - Vul de volgende informatie in om uw omgeving te installeren. + Vul de volgende informatie in om je DNN omgeving te installeren. Administratieve informatie @@ -130,79 +31,79 @@ Controleren van IIS configuratie - U dient een type database te selecteren + Je dient een type database te selecteren Volgende - Bevestig het wachtwoord dat in het bovenste wachtwoord veld is ingevuld. + Bevestig het wachtwoord dat in het bovenste wachtwoordveld is ingevuld. - Bevestiging wachtwoord is benodigd. + De bevestiging van het wachtwoord is vereist. - Bevestig Wachtwoord: + Bevestig het wachtwoord: - Hostgebruiker aanmaken + Applicatiebeheerdersaccount aanmaken Site aanmaken [{0}] - Hostgebruiker aanmaken + Applicatiebeheerdersaccount aanmaken Aangepast - Database Connectie Error + Databaseconnectie fout Connectie met database niet mogelijk. - Naam van database bestand. + Naam van het databasebestand. - Database bestandsnaam is benodigd. + Databasebestandsnaam is vereist. Bestandsnaam - Database Informatie + Database-informatie - Database Installatie + Database-installatie De naam van de database. - Database naam is benodigd. + De databasenaam is vereist. - Database naam + Databasenaam - Database owner + Database eigenaar - Wachtwoord van de database. + Het wachtwoord van de database - Database wachtwoord is benodigd. + Het databasewachtwoord is vereist. - Database Wachtwoord + Databasewachtwoord - Draai database als de specificeerde gebruiker. + Gebruik de database via een opgegeven databasegebruiker. - Draai database als + Gebruik de database als Het type beveiliging dat wordt gebruikt voor de database. @@ -211,19 +112,19 @@ Beveiliging - De naam van de database server. + De naam van de databaseserver. - Database server naam is benodigd. + Databaseserver naam is vereist. Server naam - Standaard of geavanceerde database setup. + Standaard of geavanceerde databasesetup. - Database setup + Databasesetup Standaard @@ -232,37 +133,43 @@ Type database dat wordt gebruikt voor de installatie. - Database type + Het type database De gebruikersnaam voor de database. - Database gebruikersnaam is benodigd. + De databasegebruikersnaam is vereist. - Database gebruikersnaam + Databasegebruikersnaam Geïntegreerd - Door gebruiker gespecificeerd + Door de gebruiker gespecificeerd - - Productverbeteringsprogramma + + Verwijderen van oudere bestanden voor - - Het productverbeteringsprogramma stelt ons in staat beter te begrijpen hoe we DNN voor u kunnen verbeteren. De gegevens zullen ons helpen het gebruik te analyseren en wat belangrijk is voor mensen die het product gebruiken. Alle gegevens zijn anoniem en alleen voor intern gebruik. Lees meer over het <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">productverbeteringsprogramma</a>. + + .Net Framework 4.7.2 of hoger is vereist. Controleer de Windows updates voordat je verder gaat. - - Verzend anonieme gebruiksinformatie naar DNN + + Vul een e-mailadres in voor deze gebruiker - - Verwijderen van oudere bestanden voor + + Het ingevulde e-mailadres is niet geldig + + + Een e-mailadres is vereist + + + E-mailadres: - Error + Fout Er heeft zich een fout voorgedaan - {0} @@ -270,20 +177,23 @@ Extensie installatie + + FcnMode toevoegen + Controle van machtiging op mappen en bestanden - <div class="permission"><img alt=afbeelding geeft de beveiligingsintellingen van de hoofdfolder van de website weer, Dit moet zijn Lezen, Schrijven en Wijzingen voor de ASPNET of NT AUTHORITY/NETWORK SERVICE accounts." src="..\403-3.gif" align="right" hspace="10"/> -<p><b><font color='red'>De website voldoet niet aan de beveiligingscheck</font></b></p> -Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Rechter muis klik op de folder en selecteer delen en beveiliging uit het popup menu. selecteer de beveiligings tab. Voeg de benodigde gebruikers toe en stel de juiste rechten in. -<br/><br/> -<h3>Bij gebruik van Windows 2000 - IIS5</h3> -<p>De ASPNET User Account moet Lees, Schrijf, en wijzing rechten hebben op de hoofdfolder van uw website</p> -<h3>Bij gebruik van Windows 2003, Windows Vista of Windows Server 2008 en IIS6 of IIS7</h3> -<p>De NT AUTHORITY\NETWORK SERVICE User Account moet lees, Schrijf, en Wijzing rechten hebben op de hoofd folder van uw website.</p> -<h3>Bij gebruik van Windows 7 of Windows Server 2008 R2 en IIS7.5</h3> -<p>Moet de IIS AppPool\DefaultAppPool User Account Lees, Schrijf, en Wijzig rechten hebben op de hoofd folder van uw website.</p><p><a class="dnnPrimaryAction" href="">Recheck</a></p></div> + &lt;div class="permission"&gt;&lt;img alt=afbeelding geeft de beveiligingsintellingen van de hoofdfolder van de website weer, Dit moet zijn Lezen, Schrijven en Wijzingen voor de ASPNET of NT AUTHORITY/NETWORK SERVICE accounts." src="..\403-3.gif" align="right" hspace="10"/&gt; +&lt;p&gt;&lt;b&gt;&lt;font color='red'&gt;De website voldoet niet aan de beveiligingscheck&lt;/font&gt;&lt;/b&gt;&lt;/p&gt; +Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Rechter muis klik op de folder en selecteer delen en beveiliging uit het popup menu. selecteer de beveiligings tab. Voeg de vereiste gebruikers toe en stel de juiste rechten in. +&lt;br/&gt;&lt;br/&gt; +&lt;h3&gt;Bij gebruik van Windows 2000 - IIS5&lt;/h3&gt; +&lt;p&gt;De ASPNET User Account moet Lees, Schrijf, en wijzing rechten hebben op de hoofdfolder van uw website&lt;/p&gt; +&lt;h3&gt;Bij gebruik van Windows 2003, Windows Vista of Windows Server 2008 en IIS6 of IIS7&lt;/h3&gt; +&lt;p&gt;De NT AUTHORITY\NETWORK SERVICE User Account moet lees, Schrijf, en Wijzing rechten hebben op de hoofd folder van uw website.&lt;/p&gt; +&lt;h3&gt;Bij gebruik van Windows 7 of Windows Server 2008 R2 en IIS7.5&lt;/h3&gt; +&lt;p&gt;Moet de IIS AppPool\DefaultAppPool User Account Lees, Schrijf, en Wijzig rechten hebben op de hoofd folder van uw website.&lt;/p&gt;&lt;p&gt;&lt;a class="dnnPrimaryAction" href=""&gt;Recheck&lt;/a&gt;&lt;/p&gt;&lt;/div&gt; Controleren van machtiging op mappen en bestanden @@ -301,34 +211,43 @@ Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Controleren van verwijderen van map - Uw hostnaam bevat illegale karacters (alleen a-Z, 0-9, - en . zijn toegestaan). U dient de gebruikersnaam aan te passen. + Uw applicatiebeheerdersnaam bevat tekens karacters (alleen a-Z, 0-9, - en . zijn toegestaan). Je moet de gebruikersnaam aanpassen. AppPool in IIS moet onder Integrated Mode draaien + + Het productverbeteringsprogramma stelt ons in staat om een beter beeld te krijgen hoe we DNNPlatform kunnen verbeteren. De gegevens helpen ons om het gebruik te analyseren en om te zien wat belangrijk is voor de mensen die DNNPlatform gebruiken. Alle data is anoniem en alleen voor intern gebruik.<br />Kijk voor meer informatie op <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">DNN Productverbeteringsprogramma</a>.<br /> + + + Stuur anonieme gebruiksinformatie naar DNN + + + Productverbeteringsprogramma + - Doorvoeren van Host instellingen + Doorvoeren van applicatiebeheerder instellingen - Het ingegeven wachtwoord voldoet niet aan de minimale wachtwoord verplichting. + Het ingegeven wachtwoord voldoet niet aan de minimale wachtwoord vereisten. - Verplichte velden niet ingevuld + De verplichte velden zijn niet ingevuld. - Door gaan met de Installatie + Doorgaan met de installatie - Installatie compleet! + De installatie is compleet! Klaar - De applicatie wordt geïnstalleerd. Een ogenblik geduld alstublieft.... + De applicatie wordt geïnstalleerd. Een ogenblik geduld alsjeblieft.... - Installeren van Database Script + Installeren van het Database Script Installeren {0} - {1} @@ -349,25 +268,25 @@ Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Installatieversie toevoegen - <a class="videoLink" href="https://www.dnnsoftware.com/Resources/Training/Training-Videos/Installation.aspx" target="new">Bekijk Installatie Video</a> + <a class="videoLink" href="https://dnncommunity.org/How-To/-Download-and-Install" target="new">Bekijk de DNN Comunity website</a> De objectqualifier moet met een letter beginnen en mag niet langer zijn dan 20 tekens - De door u opgegeven database gebruiker heeft onvoldoende rechten (dbo) om te kunnen installeren + De door jou opgegeven databasegebruiker heeft onvoldoende rechten (dbo) om te kunnen installeren - Controleren of database gebruiker in staat is om de benodigde acties uit te voeren + Controleren of databasegebruiker in staat is om de vereiste acties uit te voeren - De door u opgegeven database gebruiker heeft geen dbo rechten + De door jou opgegeven databasegebruiker heeft geen dbo rechten - DotNetNuke heeft .net 4.0 of hoger nodig om te kunnen werken + DNNPlatform heeft .net 4.0 of hoger nodig om te kunnen werken - DotNetNuke heeft SQL 2008 (Express of volledig product) nodig om te kunnen werken. + DNNPlatform heeft SQL 2008 (Express of volledig produkt) nodig om te kunnen werken. Controleren of database versie SQL 2008 (express of volledig product) of hoger is @@ -403,22 +322,22 @@ Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Dit taalpakket is ouder dan de huidige applicatie versie: - Activeren van licentie + Activeren van de licentie Er zijn geen installatie errors gelogd - Geen installatie log + Geen installatielog Installatie - Het wachtwoord voor het SuperUser account. + Het wachtwoord voor het applicatiebeheerdersaccount. - Wachtwoord is benodigd. + Het wachtwoord is vereist. Wachtwoord: @@ -430,32 +349,32 @@ Bij gebruik van Windows Explorer, browse naar de folders van uw website ( {0} ). Uitvoeren van upgrade script - Bestand of database regel is benodigd onder connectie kop binnen het DotNetNuke.Install.Config bestand + Bestand of databaseregel is vereist onder connectie kop binnen het DotNetNuke.Install.Config bestand - Probeer opnieuw + Probeer het opnieuw Bekijk Logs - Portal Alias [{0}] is al aanwezig. Deze stap wordt over geslagen. + De site alias [{0}] is al aanwezig. Deze stap wordt over geslagen. SQL server express bestand - SQL server / SQL server express database + SQL Server of - Express database - Geen geldige standaard database connectie gedetecteerd. -Standaard database installatie opties niet beschikbaar + Geen geldige standaard databaseconnectie gedetecteerd. +Standaard database-installatie opties niet beschikbaar Stap mislukt- {0} - Aanmaken van SuperUser + Aanmaken van applicatiebeheerder Lege website @@ -470,7 +389,7 @@ Standaard database installatie opties niet beschikbaar Solutions website - Controleren van database connectie + Controleren van databaseconnectie Minuten @@ -482,66 +401,45 @@ Standaard database installatie opties niet beschikbaar Bijwerken van Config voor - Upgraden van Applicatie + Upgraden van de Applicatie - Upgraden van Applicatie naar + Upgraden van de Applicatie naar - De gebruikersnaam voor het SuperUser account. + De gebruikersnaam voor het applicatiebeheerdersaccount. - Gebruikersnaam benodigd. + De gebruikersnaam is verplicht. Gebruikersnaam: - Bekijk Website + Bekijk de website - Open website + Ga naar de website Website aanmaken - Website Informatie + Website-informatie - Geef de naam in die u wilt gebruiken voor uw website + Geef de naam op die je wilt gebruiken voor je website - Website naam benodigd. + De websitenaam is verplicht. - Website Naam + Websitenaam - Het soort website dat u wilt maken. + Het soort website dat je wilt maken. - Template - - - Voer een e-mailadres in voor deze gebruiker. - - - Het ingevoerde e-mailadres is niet geldig - - - Een e-mailadres is verplicht - - - E-mailadres: - - - Accept the terms of the license agreement to continue. - - - I accept the terms of the <a href="../Licenses/Dnn_Corp_License.pdf" target="_blank">license agreement</a> - - - .Net Framework 4.7.2 is vereist, u dient deze via Windows Update te installeren voordat u verder gaat. + Sjabloon - + \ No newline at end of file diff --git a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.resx b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.resx index b97cb2ae796..c52eefbe85e 100644 --- a/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.resx +++ b/DNN Platform/Website/Install/App_LocalResources/Installwizard.aspx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -180,7 +180,7 @@ The product improvement program allows us to better understand how we can improve DNN for you. The data will help us analyze usage and what is important -for people using the product. All of the data is anonymous and for internal use only. Learn more about the <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Product Improvement Program</a>. +for people using the product. All of the data is anonymous and for internal use only. Learn more about the <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Product Improvement Program</a>. Send anonymous usage information to DNN @@ -210,7 +210,7 @@ for people using the product. All of the data is anonymous and for internal use Installation - <a class="videoLink" href="https://www.dnnsoftware.com/Resources/Training/Training-Videos/Installation.aspx" target="new">View Installation Video</a> + <a class="videoLink" href="https://dnncommunity.org/How-To/-Download-and-Install" target="new">Check DNN Comunity website</a> Checking database user has ability to perform necessary actions diff --git a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.de-DE.resx b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.de-DE.resx index b49eaa78cab..753356fbc03 100644 --- a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.de-DE.resx +++ b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.de-DE.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -172,7 +172,7 @@ Sie wenden Aktualisierungen zuerst auf eine Kopie Ihrer Website (und Datenbank) Produktverbesserungsprogramm - Das Produktverbesserungsprogramm ermöglicht uns, besser zu verstehen, wie wir DNN für Sie verbessern können. Die Daten helfen uns, die Nutzung zu analysieren und was für die Nutzer des Produkts wichtig ist. Alle Daten sind anonym und nur für den internen Gebrauch bestimmt. Erfahren Sie mehr über das <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Produktverbesserungsprogramm</a>. + Das Produktverbesserungsprogramm ermöglicht uns, besser zu verstehen, wie wir DNN für Sie verbessern können. Die Daten helfen uns, die Nutzung zu analysieren und was für die Nutzer des Produkts wichtig ist. Alle Daten sind anonym und nur für den internen Gebrauch bestimmt. Erfahren Sie mehr über das <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Produktverbesserungsprogramm</a>. Senden Sie anonyme Nutzungsinformationen an DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.es-ES.resx b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.es-ES.resx index 86b76b01b79..bd080c46fb8 100644 --- a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.es-ES.resx +++ b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.es-ES.resx @@ -45,7 +45,7 @@ Actualizando extensiones - El programa de mejoras del producto nos permite entender mejor como mejorar DNN para usted. Los datos enviados nos ayudarán a analizar el uso y lo que es más importante para los usuarios del producto. Todos los datos enviados son anónimos y para uso interno. Ver más información sobre el <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Programa de Mejoras del Producto</a>. + El programa de mejoras del producto nos permite entender mejor como mejorar DNN para usted. Los datos enviados nos ayudarán a analizar el uso y lo que es más importante para los usuarios del producto. Todos los datos enviados son anónimos y para uso interno. Ver más información sobre el <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Programa de Mejoras del Producto</a>. Enviar información anónima de uso a DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.fr-FR.resx b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.fr-FR.resx index 6ce182ffd8d..6a696e6b612 100644 --- a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.fr-FR.resx +++ b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.fr-FR.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -166,7 +166,7 @@ Programme d'amélioration du produit - Le programme d'amélioration des produits nous permet de mieux comprendre comment nous pouvons améliorer DNN pour vous. Les données nous aideront à analyser l'utilisation et ce qui est important pour les personnes qui utilisent le produit. Toutes les données sont anonymes et à usage interne seulement. En savoir plus sur le <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programme d'amélioration des produits</a>. + Le programme d'amélioration des produits nous permet de mieux comprendre comment nous pouvons améliorer DNN pour vous. Les données nous aideront à analyser l'utilisation et ce qui est important pour les personnes qui utilisent le produit. Toutes les données sont anonymes et à usage interne seulement. En savoir plus sur le <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programme d'amélioration des produits</a>. Envoyer des informations d'utilisation anonymes à DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.it-IT.resx b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.it-IT.resx index bdf526743a0..6fab80af9d1 100644 --- a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.it-IT.resx +++ b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.it-IT.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -171,7 +171,7 @@ Programma di miglioramento del prodotto - Il programma di miglioramento del prodotto ci consente di capire meglio come possiamo migliorare DNN per te. I dati ci aiuteranno ad analizzare l'utilizzo e ciò che è importante per le persone che utilizzano il prodotto. Tutti i dati sono anonimi e solo per uso interno. Ulteriori informazioni sul <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programma di miglioramento del prodotto</a>. + Il programma di miglioramento del prodotto ci consente di capire meglio come possiamo migliorare DNN per te. I dati ci aiuteranno ad analizzare l'utilizzo e ciò che è importante per le persone che utilizzano il prodotto. Tutti i dati sono anonimi e solo per uso interno. Ulteriori informazioni sul <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">programma di miglioramento del prodotto</a>. Invia informazioni anonime sull'uso a DNN diff --git a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx index b668bf0dbce..00308e59305 100644 --- a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx +++ b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.nl-NL.resx @@ -1,110 +1,5 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx @@ -112,22 +7,29 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Accept the terms of the license agreement to continue. + Accepteer de gebruikersvoorwaarden om door te gaan. - I accept the terms of the <a href="../Licenses/Dnn_Corp_License.pdf" target="_blank">license agreement</a> + Ik accepteer de <a href="../Licenses/Dnn_Corp_License.pdf" target="_blank">gebruikersvoorwaarden</a> - Account Informatie + Accountinformatie - U staat op het punt om uw website te upgraden naar een recentere versie van de applicatie. Het toepassen van upgrades op een consistente basis is de beste manier om ervoor te zorgen dat u de integriteit van uw investering en de veiligheid van uw gebruikers en bezittingen te garanderen. Voordat u verder gaat met de geautomatiseerde upgrade-proces moet u ervoor zorgen dat: <ul> <li> je hebt plannen gemaakt om dit proces eerste poging in een staging-omgeving <li> u uw huidige installatie kenmerken gedocumenteerd in onder meer het doen van onderzoek over de verenigbaarheid van een derde partij modules die u gebruikt <li> die u hebt gemaakt van de nodige back-ups van uw omgeving, zodat u in staat zal zijn om uw website te herstellen in het geval van een onverwachte upgrade mislukking. </ Ul> + Je staat op het punt om je website te upgraden naar een recentere versie van DNNPlatform. Het toepassen van upgrades op een consistente basis is de beste manier om ervoor te zorgen dat je de integriteit van de website en de veiligheid van de gebruikers garandeert <br /> +Voordat je verder gaat met het geautomatiseerde upgrade-proces moet je ervoor zorgen dat: +<ul> +<li>je de upgrade eerst test in een testogeving,</li> +<li>je de huidige installatie hebt gedocumenteerd</li> +<li>je modules van derde op compatibilietit hebt gecontroleerd</li> +<li>je een backup hebt gemaakt van de productiesite, zodat je altijd terug kan als er iets mis gaat</li> +</ ul> Huidige versie - {0} @@ -144,8 +46,17 @@ Extensies bijwerken + + Het productverbeteringsprogramma stelt ons in staat om te bepalen hoe we DNNPlatform kunnen verbeteren. De gegevens helpen ons om het gebruik te analyseren en laat ons inzien wat belangrijk is voor gebruikers van DNNPlatform. Alle gegevens zijn anoniem en alleen beschikbaar voor intern gebruik. Voor meer informatie, ga naar https://www.dnnsoftware.com/dnn-improvement-program. + + + Stuur anonieme gebruiksinformatie naar DNN + + + Programma voor productverbetering + - <p> Welkom op de DotNetNuke Upgrade Pagina.</p>De eerste stap is het kiezen van de taal die u wilt gebruiken voor de upgrade.</p> + <p>Welkom op de DNNPlatform upgradepagina.</p>De eerste stap is het kiezen van de taal die je wilt gebruiken voor de upgrade.</p> Gebruikersnaam en wachtwoord niet herkend @@ -154,23 +65,14 @@ Nu Upgraden - Geen installatie log + Geen installatielog - Het wachtwoord voor het Super User account + Het wachtwoord voor het account van de applicatiebeheerder Wachtwoord: - - Productverbeteringsprogramma - - - Het productverbeteringsprogramma stelt ons in staat beter te begrijpen hoe we DNN voor u kunnen verbeteren. De gegevens zullen ons helpen het gebruik te analyseren en wat belangrijk is voor mensen die het product gebruiken. Alle gegevens zijn anoniem en alleen voor intern gebruik. Lees meer over het <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">productverbeteringsprogramma</a>. - - - Verzend anonieme gebruiksinformatie naar DNN - Opnieuw proberen @@ -189,22 +91,31 @@ Upgrade voltooid + + Upgrade gestart om + Database bijwerken - De gebruikersnaam voor het Super User account + De gebruikersnaam van de applicatiebeheerder (host) - Host (SuperUser) Gebruikersnaam: + Applicatiebeheerder (host) gebruikersnaam: Upgrade - versie {0} + + Database en applicatie versie zijn gelijk - er is geen upgrade nodig. + + + Database en applicatie versie zijn gelijk - er is een incrementele versie voor upgrade beschikbaar. + Website weergeven Website bezoeken - + \ No newline at end of file diff --git a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.resx b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.resx index e1e3581b335..307955b3dbc 100644 --- a/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.resx +++ b/DNN Platform/Website/Install/App_LocalResources/UpgradeWizard.aspx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -177,7 +177,7 @@ The product improvement program allows us to better understand how we can improve DNN for you. The data will help us analyze usage and what is important -for people using the product. All of the data is anonymous and for internal use only. Learn more about the <a href="http://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Product Improvement Program</a>. +for people using the product. All of the data is anonymous and for internal use only. Learn more about the <a href="https://www.dnnsoftware.com/dnn-improvement-program" target="_blank">Product Improvement Program</a>. Send anonymous usage information to DNN diff --git a/DNN Platform/Website/Install/Config/09.06.02.config b/DNN Platform/Website/Install/Config/09.06.02.config new file mode 100644 index 00000000000..42add031e07 --- /dev/null +++ b/DNN Platform/Website/Install/Config/09.06.02.config @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/DNN Platform/Website/Install/Install.aspx.cs b/DNN Platform/Website/Install/Install.aspx.cs index 819287ef794..26ce9cf58f4 100644 --- a/DNN Platform/Website/Install/Install.aspx.cs +++ b/DNN Platform/Website/Install/Install.aspx.cs @@ -1,86 +1,174 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Installer.Blocker; - -#region Usings - -using System; -using System.Data; -using System.IO; -using System.Web; -using System.Web.UI; -using System.Xml; - -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Framework.Providers; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Scheduling; -using DotNetNuke.Services.Upgrade.InternalController.Steps; -using DotNetNuke.Services.Upgrade.Internals; -using DotNetNuke.Services.Upgrade.Internals.Steps; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - -// ReSharper disable once CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +// ReSharper disable once CheckNamespace namespace DotNetNuke.Services.Install { + using System; + using System.Data; + using System.IO; + using System.Web; + using System.Web.UI; + using System.Xml; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Installer.Blocker; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Scheduling; + using DotNetNuke.Services.Upgrade.InternalController.Steps; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.Steps; + using DotNetNuke.Web.Client.ClientResourceManagement; + public partial class Install : Page { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Install)); - private static readonly object installLocker = new object(); - #region Private Methods + private static readonly object installLocker = new object(); + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (Upgrade.Upgrade.UpdateNewtonsoftVersion()) + { + this.Response.Redirect(this.Request.RawUrl, true); + } + + // if previous config deleted create new empty one + string installConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Install", "DotNetNuke.install.config"); + if (!File.Exists(installConfig)) + { + File.Copy(installConfig + ".resources", installConfig); + } + } + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + Config.AddFCNMode(Config.FcnMode.Single); + + // Get current Script time-out + int scriptTimeOut = this.Server.ScriptTimeout; + + string mode = string.Empty; + if (this.Request.QueryString["mode"] != null) + { + mode = this.Request.QueryString["mode"].ToLowerInvariant(); + } + + // Disable Client side caching + this.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); + + // Check mode is not Nothing + if (mode == "none") + { + this.NoUpgrade(); + } + else + { + // Set Script timeout to MAX value + this.Server.ScriptTimeout = int.MaxValue; + + switch (Globals.Status) + { + case Globals.UpgradeStatus.Install: + this.InstallApplication(); + + // Force an App Restart + Config.Touch(); + break; + case Globals.UpgradeStatus.Upgrade: + this.UpgradeApplication(); + + // Force an App Restart + Config.Touch(); + break; + case Globals.UpgradeStatus.None: + // Check mode + switch (mode) + { + case "addportal": + this.AddPortal(); + break; + case "installresources": + this.InstallResources(); + break; + case "executescripts": + this.ExecuteScripts(); + break; + } + + break; + case Globals.UpgradeStatus.Error: + this.NoUpgrade(); + break; + } + + // restore Script timeout + this.Server.ScriptTimeout = scriptTimeOut; + } + } + + private static void RegisterInstallBegining() + { + InstallBlocker.Instance.RegisterInstallBegining(); + } + + private static void RegisterInstallEnd() + { + InstallBlocker.Instance.RegisterInstallEnd(); + } + private void ExecuteScripts() { - //Start Timer + // Start Timer Upgrade.Upgrade.StartTimer(); - //Write out Header - HtmlUtils.WriteHeader(Response, "executeScripts"); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "executeScripts"); - Response.Write("

        Execute Scripts Status Report

        "); - Response.Flush(); + this.Response.Write("

        Execute Scripts Status Report

        "); + this.Response.Flush(); string strProviderPath = DataProvider.Instance().GetProviderPath(); if (!strProviderPath.StartsWith("ERROR:")) { Upgrade.Upgrade.ExecuteScripts(strProviderPath); } - Response.Write("

        Execution Complete

        "); - Response.Flush(); - - //Write out Footer - HtmlUtils.WriteFooter(Response); + + this.Response.Write("

        Execution Complete

        "); + this.Response.Flush(); + + // Write out Footer + HtmlUtils.WriteFooter(this.Response); } private void InstallApplication() { - //the application uses a two step installation process. The first step is used to update - //the Web.config with any configuration settings - which forces an application restart. - //The second step finishes the installation process and provisions the site. - + // the application uses a two step installation process. The first step is used to update + // the Web.config with any configuration settings - which forces an application restart. + // The second step finishes the installation process and provisions the site. string installationDate = Config.GetSetting("InstallationDate"); - if (installationDate == null || String.IsNullOrEmpty(installationDate)) + if (installationDate == null || string.IsNullOrEmpty(installationDate)) { string strError = Config.UpdateMachineKey(); - if (String.IsNullOrEmpty(strError)) + if (string.IsNullOrEmpty(strError)) { - //send a new request to the application to initiate step 2 - Response.Redirect(HttpContext.Current.Request.RawUrl, true); + // send a new request to the application to initiate step 2 + this.Response.Redirect(HttpContext.Current.Request.RawUrl, true); } else { - //403-3 Error - Redirect to ErrorPage - //403.3 means directory permissions issue + // 403-3 Error - Redirect to ErrorPage + // 403.3 means directory permissions issue string strURL = "~/ErrorPage.aspx?status=403_3&error=" + strError; HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer(strURL); @@ -88,67 +176,71 @@ private void InstallApplication() } else { - try { var synchConnectionString = new SynchConnectionStringStep(); synchConnectionString.Execute(); if (synchConnectionString.Status == StepStatus.AppRestart) { - //send a new request to the application to initiate step 2 - Response.Redirect(HttpContext.Current.Request.RawUrl, true); + // send a new request to the application to initiate step 2 + this.Response.Redirect(HttpContext.Current.Request.RawUrl, true); } - //Start Timer + // Start Timer Upgrade.Upgrade.StartTimer(); - //Write out Header - HtmlUtils.WriteHeader(Response, "install"); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "install"); - //get path to script files + // get path to script files string strProviderPath = DataProvider.Instance().GetProviderPath(); if (!strProviderPath.StartsWith("ERROR:")) { - if (!CheckPermissions()) + if (!this.CheckPermissions()) { return; } - //Add the install blocker logic + + // Add the install blocker logic lock (installLocker) { if (InstallBlocker.Instance.IsInstallInProgress()) { - WriteInstallationHeader(); - WriteInstallationInProgress(); + this.WriteInstallationHeader(); + this.WriteInstallationInProgress(); return; } + RegisterInstallBegining(); } var installConfig = InstallController.Instance.GetInstallConfig(); - //Create Folder Mappings config - if (!String.IsNullOrEmpty(installConfig.FolderMappingsSettings)) + + // Create Folder Mappings config + if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) { FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); } + Upgrade.Upgrade.InstallDNN(strProviderPath); - //remove en-US from portal if installing in a different language + + // remove en-US from portal if installing in a different language if (!installConfig.InstallCulture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { var locale = LocaleController.Instance.GetLocale("en-US"); - Localization.Localization.RemoveLanguageFromPortal(0, locale.LanguageId, true); + Localization.RemoveLanguageFromPortal(0, locale.LanguageId, true); } var licenseConfig = installConfig.License; - bool IsProOrEnterprise = (File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Professional.dll")) || - File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll"))); - if (IsProOrEnterprise && licenseConfig != null && !String.IsNullOrEmpty(licenseConfig.AccountEmail) && - !String.IsNullOrEmpty(licenseConfig.InvoiceNumber)) + bool IsProOrEnterprise = File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Professional.dll")) || + File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")); + if (IsProOrEnterprise && licenseConfig != null && !string.IsNullOrEmpty(licenseConfig.AccountEmail) && + !string.IsNullOrEmpty(licenseConfig.InvoiceNumber)) { Upgrade.Upgrade.ActivateLicense(); } - //Adding ClientDependency Resources config to web.config + // Adding ClientDependency Resources config to web.config if (!ClientResourceManager.IsInstalled()) { ClientResourceManager.AddConfiguration(); @@ -157,35 +249,35 @@ private void InstallApplication() var installVersion = DataProvider.Instance().GetInstallVersion(); string strError = Config.UpdateInstallVersion(installVersion); - //Adding FCN mode to web.config + // Adding FCN mode to web.config strError += Config.AddFCNMode(Config.FcnMode.Single); if (!string.IsNullOrEmpty(strError)) { Logger.Error(strError); } - Response.Write("

        Installation Complete

        "); - Response.Write("

        Click Here To Access Your Site



        "); - Response.Flush(); + this.Response.Write("

        Installation Complete

        "); + this.Response.Write("

        Click Here To Access Your Site



        "); + this.Response.Flush(); - //remove installwizard files + // remove installwizard files Upgrade.Upgrade.DeleteInstallerFiles(); - //log APPLICATION_START event + // log APPLICATION_START event Initialize.LogStart(); - //Start Scheduler + // Start Scheduler Initialize.StartScheduler(true); } else { - //upgrade error - Response.Write("

        Upgrade Error: " + strProviderPath + "

        "); - Response.Flush(); + // upgrade error + this.Response.Write("

        Upgrade Error: " + strProviderPath + "

        "); + this.Response.Flush(); } - //Write out Footer - HtmlUtils.WriteFooter(Response); + // Write out Footer + HtmlUtils.WriteFooter(this.Response); } finally { @@ -193,103 +285,97 @@ private void InstallApplication() } } } - - private static void RegisterInstallBegining() - { - InstallBlocker.Instance.RegisterInstallBegining(); - } - private static void RegisterInstallEnd() - { - InstallBlocker.Instance.RegisterInstallEnd(); - } - private void WriteInstallationHeader() { - Response.Write("

        Version: " + Globals.FormatVersion(DotNetNukeContext.Current.Application.Version) + "

        "); - Response.Flush(); + this.Response.Write("

        Version: " + Globals.FormatVersion(DotNetNukeContext.Current.Application.Version) + "

        "); + this.Response.Flush(); - Response.Write("

        "); - Response.Write("

        Installation Status Report

        "); - Response.Flush(); + this.Response.Write("

        "); + this.Response.Write("

        Installation Status Report

        "); + this.Response.Flush(); } private void WriteInstallationInProgress() { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, - 0, - Localization.Localization.GetString("ThereIsAInstallationCurrentlyInProgress.Error", Localization.Localization.GlobalResourceFile) + "
        "); - Response.Flush(); + HtmlUtils.WriteFeedback( + HttpContext.Current.Response, + 0, + Localization.GetString("ThereIsAInstallationCurrentlyInProgress.Error", Localization.GlobalResourceFile) + "
        "); + this.Response.Flush(); } private bool CheckPermissions() { - bool verified = new FileSystemPermissionVerifier(Server.MapPath("~")).VerifyAll(); - HtmlUtils.WriteFeedback(HttpContext.Current.Response, - 0, - "Checking File and Folder permissions " + (verified ? "Success" : "Error!") + "
        "); - Response.Flush(); + bool verified = new FileSystemPermissionVerifier(this.Server.MapPath("~")).VerifyAll(); + HtmlUtils.WriteFeedback( + HttpContext.Current.Response, + 0, + "Checking File and Folder permissions " + (verified ? "Success" : "Error!") + "
        "); + this.Response.Flush(); return verified; } private void UpgradeApplication() - { + { try { if (Upgrade.Upgrade.RemoveInvalidAntiForgeryCookie()) { - Response.Redirect(Request.RawUrl, true); + this.Response.Redirect(this.Request.RawUrl, true); } var databaseVersion = DataProvider.Instance().GetVersion(); - //Start Timer + // Start Timer Upgrade.Upgrade.StartTimer(); - //Write out Header - HtmlUtils.WriteHeader(Response, "upgrade"); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "upgrade"); - //There could be an installation in progress + // There could be an installation in progress lock (installLocker) { if (InstallBlocker.Instance.IsInstallInProgress()) { - WriteInstallationHeader(); - WriteInstallationInProgress(); + this.WriteInstallationHeader(); + this.WriteInstallationInProgress(); return; } + RegisterInstallBegining(); } - Response.Write("

        Current Assembly Version: " + Globals.FormatVersion(DotNetNukeContext.Current.Application.Version) + "

        "); - Response.Flush(); + this.Response.Write("

        Current Assembly Version: " + Globals.FormatVersion(DotNetNukeContext.Current.Application.Version) + "

        "); + this.Response.Flush(); - //get path to script files + // get path to script files string strProviderPath = DataProvider.Instance().GetProviderPath(); if (!strProviderPath.StartsWith("ERROR:")) { - //get current database version + // get current database version var strDatabaseVersion = Globals.FormatVersion(databaseVersion); - Response.Write("

        Current Database Version: " + strDatabaseVersion + "

        "); - Response.Flush(); + this.Response.Write("

        Current Database Version: " + strDatabaseVersion + "

        "); + this.Response.Flush(); string ignoreWarning = Null.NullString; string strWarning = Null.NullString; if ((databaseVersion.Major == 3 && databaseVersion.Minor < 3) || (databaseVersion.Major == 4 && databaseVersion.Minor < 3)) { - //Users and profile have not been transferred - //Get the name of the data provider + // Users and profile have not been transferred + // Get the name of the data provider ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data"); - //Execute Special Script + // Execute Special Script Upgrade.Upgrade.ExecuteScript(strProviderPath + "Upgrade." + objProviderConfiguration.DefaultProvider); - if ((Request.QueryString["ignoreWarning"] != null)) + if (this.Request.QueryString["ignoreWarning"] != null) { - ignoreWarning = Request.QueryString["ignoreWarning"].ToLowerInvariant(); + ignoreWarning = this.Request.QueryString["ignoreWarning"].ToLowerInvariant(); } + strWarning = Upgrade.Upgrade.CheckUpgrade(); } else @@ -297,57 +383,59 @@ private void UpgradeApplication() ignoreWarning = "true"; } - //Check whether Upgrade is ok + // Check whether Upgrade is ok if (strWarning == Null.NullString || ignoreWarning == "true") { - Response.Write("

        "); - Response.Write("

        Upgrade Status Report

        "); - Response.Flush(); + this.Response.Write("

        "); + this.Response.Write("

        Upgrade Status Report

        "); + this.Response.Flush(); - //stop scheduler + // stop scheduler SchedulingProvider.Instance().Halt("Stopped by Upgrade Process"); Upgrade.Upgrade.UpgradeDNN(strProviderPath, databaseVersion); - //Install optional resources if present + // Install optional resources if present var packages = Upgrade.Upgrade.GetInstallPackages(); foreach (var package in packages) { Upgrade.Upgrade.InstallPackage(package.Key, package.Value.PackageType, true); } - //calling GetInstallVersion after SQL scripts exection to ensure sp GetDatabaseInstallVersion exists + // calling GetInstallVersion after SQL scripts exection to ensure sp GetDatabaseInstallVersion exists var installVersion = DataProvider.Instance().GetInstallVersion(); string strError = Config.UpdateInstallVersion(installVersion); - //Adding FCN mode to web.config + // Adding FCN mode to web.config strError += Config.AddFCNMode(Config.FcnMode.Single); if (!string.IsNullOrEmpty(strError)) { Logger.Error(strError); } - Response.Write("

        Upgrade Complete

        "); - Response.Write("

        Click Here To Access Your Site



        "); + + this.Response.Write("

        Upgrade Complete

        "); + this.Response.Write("

        Click Here To Access Your Site



        "); - //remove installwizard files + // remove installwizard files Upgrade.Upgrade.DeleteInstallerFiles(); } else { - Response.Write("

        Warning:

        " + strWarning.Replace(Environment.NewLine, "
        ")); + this.Response.Write("

        Warning:

        " + strWarning.Replace(Environment.NewLine, "
        ")); - Response.Write("

        Click Here To Proceed With The Upgrade."); + this.Response.Write("

        Click Here To Proceed With The Upgrade."); } - Response.Flush(); + + this.Response.Flush(); } else { - Response.Write("

        Upgrade Error: " + strProviderPath + "

        "); - Response.Flush(); + this.Response.Write("

        Upgrade Error: " + strProviderPath + "

        "); + this.Response.Flush(); } - //Write out Footer - HtmlUtils.WriteFooter(Response); + // Write out Footer + HtmlUtils.WriteFooter(this.Response); } finally { @@ -357,22 +445,22 @@ private void UpgradeApplication() private void AddPortal() { - //Start Timer + // Start Timer Upgrade.Upgrade.StartTimer(); - //Write out Header - HtmlUtils.WriteHeader(Response, "addPortal"); - Response.Write("

        Add Site Status Report

        "); - Response.Flush(); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "addPortal"); + this.Response.Write("

        Add Site Status Report

        "); + this.Response.Flush(); - //install new portal(s) + // install new portal(s) string strNewFile = Globals.ApplicationMapPath + "\\Install\\Portal\\Portals.resources"; if (File.Exists(strNewFile)) { XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; xmlDoc.Load(strNewFile); - //parse portal(s) if available + // parse portal(s) if available var nodes = xmlDoc.SelectNodes("//dotnetnuke/portals/portal"); if (nodes != null) { @@ -385,7 +473,7 @@ private void AddPortal() } } - //delete the file + // delete the file try { File.SetAttributes(strNewFile, FileAttributes.Normal); @@ -393,202 +481,118 @@ private void AddPortal() } catch (Exception ex) { - //error removing the file + // error removing the file Logger.Error(ex); } - Response.Write("

        Installation Complete

        "); - Response.Write("

        Click Here To Access Your Site



        "); - Response.Flush(); + this.Response.Write("

        Installation Complete

        "); + this.Response.Write("

        Click Here To Access Your Site



        "); + this.Response.Flush(); } - //Write out Footer - HtmlUtils.WriteFooter(Response); + // Write out Footer + HtmlUtils.WriteFooter(this.Response); } private void InstallResources() { - //Start Timer + // Start Timer Upgrade.Upgrade.StartTimer(); - //Write out Header - HtmlUtils.WriteHeader(Response, "installResources"); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "installResources"); - Response.Write("

        Install Resources Status Report

        "); - Response.Flush(); + this.Response.Write("

        Install Resources Status Report

        "); + this.Response.Flush(); - //install new resources(s) + // install new resources(s) var packages = Upgrade.Upgrade.GetInstallPackages(); foreach (var package in packages) { Upgrade.Upgrade.InstallPackage(package.Key, package.Value.PackageType, true); } - Response.Write("

        Installation Complete

        "); - Response.Write("

        Click Here To Access Your Site



        "); - Response.Flush(); + this.Response.Write("

        Installation Complete

        "); + this.Response.Write("

        Click Here To Access Your Site



        "); + this.Response.Flush(); - //Write out Footer - HtmlUtils.WriteFooter(Response); + // Write out Footer + HtmlUtils.WriteFooter(this.Response); } private void NoUpgrade() { - //get path to script files + // get path to script files string strProviderPath = DataProvider.Instance().GetProviderPath(); if (!strProviderPath.StartsWith("ERROR:")) { - //get current database version + // get current database version try { using (var dr = DataProvider.Instance().GetDatabaseVersion()) { if (dr.Read()) { - //Write out Header - HtmlUtils.WriteHeader(Response, "none"); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "none"); string currentAssembly = DotNetNukeContext.Current.Application.Version.ToString(3); string currentDatabase = dr["Major"] + "." + dr["Minor"] + "." + dr["Build"]; - //do not show versions if the same to stop information leakage + + // do not show versions if the same to stop information leakage if (currentAssembly == currentDatabase) { - Response.Write("

        Current Assembly Version && current Database Version are identical.

        "); + this.Response.Write("

        Current Assembly Version && current Database Version are identical.

        "); } else { - Response.Write("

        Current Assembly Version: " + currentAssembly + "

        "); - //Call Upgrade with the current DB Version to upgrade an - //existing DNN installation + this.Response.Write("

        Current Assembly Version: " + currentAssembly + "

        "); + + // Call Upgrade with the current DB Version to upgrade an + // existing DNN installation var strDatabaseVersion = ((int)dr["Major"]).ToString("00") + "." + ((int)dr["Minor"]).ToString("00") + "." + ((int)dr["Build"]).ToString("00"); - Response.Write("

        Current Database Version: " + strDatabaseVersion + "

        "); + this.Response.Write("

        Current Database Version: " + strDatabaseVersion + "

        "); } - Response.Write("

        Click Here To Upgrade DotNetNuke"); - Response.Flush(); + this.Response.Write("

        Click Here To Upgrade DotNetNuke"); + this.Response.Flush(); } else { - //Write out Header - HtmlUtils.WriteHeader(Response, "noDBVersion"); - Response.Write("

        Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "

        "); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "noDBVersion"); + this.Response.Write("

        Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "

        "); - Response.Write("

        Current Database Version: N/A

        "); - Response.Write("

        Click Here To Install DotNetNuke

        "); - Response.Flush(); + this.Response.Write("

        Current Database Version: N/A

        "); + this.Response.Write("

        Click Here To Install DotNetNuke

        "); + this.Response.Flush(); } + dr.Close(); } } catch (Exception ex) { - //Write out Header + // Write out Header Logger.Error(ex); - HtmlUtils.WriteHeader(Response, "error"); - Response.Write("

        Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "

        "); + HtmlUtils.WriteHeader(this.Response, "error"); + this.Response.Write("

        Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "

        "); - Response.Write("

        " + ex.Message + "

        "); - Response.Flush(); + this.Response.Write("

        " + ex.Message + "

        "); + this.Response.Flush(); } } else { - //Write out Header - HtmlUtils.WriteHeader(Response, "error"); - Response.Write("

        Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "

        "); - - Response.Write("

        " + strProviderPath + "

        "); - Response.Flush(); - } - - //Write out Footer - HtmlUtils.WriteFooter(Response); - } - - #endregion - - #region "Event Handlers" - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); + // Write out Header + HtmlUtils.WriteHeader(this.Response, "error"); + this.Response.Write("

        Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "

        "); - if (Upgrade.Upgrade.UpdateNewtonsoftVersion()) - { - Response.Redirect(Request.RawUrl, true); - } - - //if previous config deleted create new empty one - string installConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Install", "DotNetNuke.install.config"); - if (!File.Exists(installConfig)) - { - File.Copy(installConfig + ".resources", installConfig); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - Config.AddFCNMode(Config.FcnMode.Single); - //Get current Script time-out - int scriptTimeOut = Server.ScriptTimeout; - - string mode = ""; - if ((Request.QueryString["mode"] != null)) - { - mode = Request.QueryString["mode"].ToLowerInvariant(); + this.Response.Write("

        " + strProviderPath + "

        "); + this.Response.Flush(); } - //Disable Client side caching - Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); - - //Check mode is not Nothing - if (mode == "none") - { - NoUpgrade(); - } - else - { - //Set Script timeout to MAX value - Server.ScriptTimeout = int.MaxValue; - - switch (Globals.Status) - { - case Globals.UpgradeStatus.Install: - InstallApplication(); - - //Force an App Restart - Config.Touch(); - break; - case Globals.UpgradeStatus.Upgrade: - UpgradeApplication(); - - //Force an App Restart - Config.Touch(); - break; - case Globals.UpgradeStatus.None: - //Check mode - switch (mode) - { - case "addportal": - AddPortal(); - break; - case "installresources": - InstallResources(); - break; - case "executescripts": - ExecuteScripts(); - break; - } - break; - case Globals.UpgradeStatus.Error: - NoUpgrade(); - break; - } - - //restore Script timeout - Server.ScriptTimeout = scriptTimeOut; - } - } - #endregion + // Write out Footer + HtmlUtils.WriteFooter(this.Response); + } } } diff --git a/DNN Platform/Website/Install/InstallWizard.aspx b/DNN Platform/Website/Install/InstallWizard.aspx index e993658259c..6a4cb5f0724 100644 --- a/DNN Platform/Website/Install/InstallWizard.aspx +++ b/DNN Platform/Website/Install/InstallWizard.aspx @@ -296,7 +296,7 @@ }; this.confirmPasswords = function () { if ($('#<%= txtPassword.ClientID %>')[0].value != $('#<%= txtConfirmPassword.ClientID %>')[0].value) { - $('#<%= lblAdminInfoError.ClientID %>').text('<%= Localization.GetSafeJSString(LocalizeString("PasswordMismatch"))%>'); + $('#<%= lblAdminInfoError.ClientID %>').text('<%= DotNetNuke.Services.Localization.Localization.GetSafeJSString(LocalizeString("PasswordMismatch"))%>'); $("#continueLink").addClass('dnnDisabledAction'); } else { $('#<%= lblAdminInfoError.ClientID %>').text(''); @@ -321,7 +321,7 @@ $("#continueLink").removeClass('dnnDisabledAction'); } } else { - $('#<%= lblAdminInfoError.ClientID %>').text('<%= Localization.GetSafeJSString(LocalizeString("InputErrorInvalidPassword"))%>'); + $('#<%= lblAdminInfoError.ClientID %>').text('<%= DotNetNuke.Services.Localization.Localization.GetSafeJSString(LocalizeString("InputErrorInvalidPassword"))%>'); $("#continueLink").addClass('dnnDisabledAction'); } }); @@ -448,7 +448,7 @@ $('#<%= lblDatabaseInfoMsg.ClientID %>').removeClass("promptMessageError"); $('#<%= lblDatabaseInfoMsg.ClientID %>').addClass("promptMessage"); var i = 0; - $(".databaseCheck").html('<%= Localization.GetSafeJSString(LocalizeString("TestingDatabase"))%>'); + $(".databaseCheck").html('<%= DotNetNuke.Services.Localization.Localization.GetSafeJSString(LocalizeString("TestingDatabase"))%>'); var origtext = $(".databaseCheck").html(); var text = origtext; installWizard.loadingIntervalId = setInterval(function () { @@ -460,7 +460,7 @@ clearInterval(installWizard.checkPermissionIntervalId); $('.permissionCheck').removeClass("promptMessageError").addClass("promptMessage").parent().show(); var i = 0; - $(".permissionCheck").html('<%= Localization.GetSafeJSString(LocalizeString("FileAndFolderPermissionCheckTitle.Text"))%>'); + $(".permissionCheck").html('<%= DotNetNuke.Services.Localization.Localization.GetSafeJSString(LocalizeString("FileAndFolderPermissionCheckTitle.Text"))%>'); var origtext = $(".permissionCheck").html(); var text = origtext; installWizard.checkPermissionIntervalId = setInterval(function () { @@ -562,7 +562,7 @@ ", - ClientID, - Target); - Page.ClientScript.RegisterStartupScript(GetType(), ClientID, toggleScript); - } - - protected override void Render(HtmlTextWriter writer) - { - writer.AddAttribute("id", ClientID); - writer.AddAttribute("class", Class); - writer.RenderBeginTag("h2"); - - writer.AddAttribute("href", "#"); - writer.AddAttribute("class", "toggleHandler"); - writer.RenderBeginTag("a"); - - RenderChildren(writer); - - writer.RenderEndTag(); - writer.RenderEndTag(); - } - - #endregion - } + var toggleScript = string.Format( + "", + this.ClientID, + this.Target); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, toggleScript); + } + + protected override void Render(HtmlTextWriter writer) + { + writer.AddAttribute("id", this.ClientID); + writer.AddAttribute("class", this.Class); + writer.RenderBeginTag("h2"); + + writer.AddAttribute("href", "#"); + writer.AddAttribute("class", "toggleHandler"); + writer.RenderBeginTag("a"); + + this.RenderChildren(writer); + + writer.RenderEndTag(); + writer.RenderEndTag(); + } + } } diff --git a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs index 94b83cb5870..0ea8bc9bd8f 100644 --- a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs +++ b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs @@ -1,32 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.WebControls; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.Utilities; - -using Globals = DotNetNuke.Common.Globals; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System; + using System.Web.UI; + using System.Web.UI.WebControls; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.Utilities; + + using Globals = DotNetNuke.Common.Globals; + /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : Containers.Visibility - /// + /// Project : DotNetNuke + /// Class : Containers.Visibility + /// /// ----------------------------------------------------------------------------- /// - /// Handles the events for collapsing and expanding modules, + /// Handles the events for collapsing and expanding modules, /// Showing or hiding admin controls when preview is checked /// if personalization of the module container and title is allowed for that module. /// @@ -34,22 +29,35 @@ namespace DotNetNuke.UI.Containers /// /// ----------------------------------------------------------------------------- public partial class Visibility : SkinObjectBase - { -#region "Private Members" - + { private int _animationFrames = 5; private Panel _pnlModuleContent; + + public int AnimationFrames + { + get + { + return this._animationFrames; + } + + set + { + this._animationFrames = value; + } + } + + public string BorderWidth { get; set; } private string MinIconLoc { get { - if (!String.IsNullOrEmpty(minIcon)) + if (!string.IsNullOrEmpty(this.minIcon)) { - return ModulePath + minIcon; + return this.ModulePath + this.minIcon; } - - return Globals.ApplicationPath + "/images/min.gif"; //is ~/ the same as ApplicationPath in all cases? + + return Globals.ApplicationPath + "/images/min.gif"; // is ~/ the same as ApplicationPath in all cases? } } @@ -57,12 +65,12 @@ private string MaxIconLoc { get { - if (!String.IsNullOrEmpty(MaxIcon)) + if (!string.IsNullOrEmpty(this.MaxIcon)) { - return ModulePath + MaxIcon; + return this.ModulePath + this.MaxIcon; } - - return Globals.ApplicationPath + "/images/max.gif"; //is ~/ the same as ApplicationPath in all cases? + + return Globals.ApplicationPath + "/images/max.gif"; // is ~/ the same as ApplicationPath in all cases? } } @@ -70,15 +78,16 @@ private Panel ModuleContent { get { - if (_pnlModuleContent == null) + if (this._pnlModuleContent == null) { - Control objCtl = Parent.FindControl("ModuleContent"); + Control objCtl = this.Parent.FindControl("ModuleContent"); if (objCtl != null) { - _pnlModuleContent = (Panel) objCtl; + this._pnlModuleContent = (Panel)objCtl; } } - return _pnlModuleContent; + + return this._pnlModuleContent; } } @@ -86,60 +95,44 @@ private string ModulePath { get { - return ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1); + return this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1); } - } - - #endregion - - #region "Public Members" - - - public int AnimationFrames - { - get - { - return _animationFrames; - } - set - { - _animationFrames = value; - } - } - - public string BorderWidth { get; set; } + } public bool ContentVisible { get { - switch (ModuleControl.ModuleContext.Configuration.Visibility) + switch (this.ModuleControl.ModuleContext.Configuration.Visibility) { case VisibilityState.Maximized: case VisibilityState.Minimized: - return DNNClientAPI.MinMaxContentVisibile(cmdVisibility, - ModuleControl.ModuleContext.ModuleId, - ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, - DNNClientAPI.MinMaxPersistanceType.Cookie); + return DNNClientAPI.MinMaxContentVisibile( + this.cmdVisibility, + this.ModuleControl.ModuleContext.ModuleId, + this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, + DNNClientAPI.MinMaxPersistanceType.Cookie); default: return true; } } + set { - DNNClientAPI.MinMaxContentVisibile(cmdVisibility, - ModuleControl.ModuleContext.ModuleId, - ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, - DNNClientAPI.MinMaxPersistanceType.Cookie, - value); + DNNClientAPI.MinMaxContentVisibile( + this.cmdVisibility, + this.ModuleControl.ModuleContext.ModuleId, + this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, + DNNClientAPI.MinMaxPersistanceType.Cookie, + value); } - } - -// ReSharper disable InconsistentNaming -//TODO can this be renamed with a capital M - public string minIcon { get; set; } -// ReSharper restore InconsistentNaming - + } + + // ReSharper disable InconsistentNaming + // TODO can this be renamed with a capital M + public string minIcon { get; set; } + + // ReSharper restore InconsistentNaming public string MaxIcon { get; set; } public string ResourceFile @@ -154,69 +147,72 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdVisibility.Click += cmdVisibility_Click; + this.cmdVisibility.Click += this.cmdVisibility_Click; try { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - //public attributes - if (!String.IsNullOrEmpty(BorderWidth)) + // public attributes + if (!string.IsNullOrEmpty(this.BorderWidth)) { - cmdVisibility.BorderWidth = Unit.Parse(BorderWidth); + this.cmdVisibility.BorderWidth = Unit.Parse(this.BorderWidth); } - if (ModuleControl.ModuleContext.Configuration != null) + + if (this.ModuleControl.ModuleContext.Configuration != null) { - //check if Personalization is allowed - if (ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.None) + // check if Personalization is allowed + if (this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.None) { - cmdVisibility.Enabled = false; - cmdVisibility.Visible = false; + this.cmdVisibility.Enabled = false; + this.cmdVisibility.Visible = false; } - if (ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized) + + if (this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized) { - //if visibility is set to minimized, then the client needs to set the cookie for maximized only and delete the cookie for minimized, - //instead of the opposite. We need to notify the client of this - ClientAPI.RegisterClientVariable(Page, "__dnn_" + ModuleControl.ModuleContext.ModuleId + ":defminimized", "true", true); + // if visibility is set to minimized, then the client needs to set the cookie for maximized only and delete the cookie for minimized, + // instead of the opposite. We need to notify the client of this + ClientAPI.RegisterClientVariable(this.Page, "__dnn_" + this.ModuleControl.ModuleContext.ModuleId + ":defminimized", "true", true); } + if (!Globals.IsAdminControl()) { - if (cmdVisibility.Enabled) + if (this.cmdVisibility.Enabled) { - if (ModuleContent != null) + if (this.ModuleContent != null) { - //EnableMinMax now done in prerender + // EnableMinMax now done in prerender } else { - Visible = false; + this.Visible = false; } } } else { - Visible = false; + this.Visible = false; } } else { - Visible = false; + this.Visible = false; } } else { - //since we disabled viewstate on the cmdVisibility control we need to check to see if we need hide this on postbacks as well - if (ModuleControl.ModuleContext.Configuration != null) + // since we disabled viewstate on the cmdVisibility control we need to check to see if we need hide this on postbacks as well + if (this.ModuleControl.ModuleContext.Configuration != null) { - if (ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.None) + if (this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.None) { - cmdVisibility.Enabled = false; - cmdVisibility.Visible = false; + this.cmdVisibility.Enabled = false; + this.cmdVisibility.Visible = false; } } } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -225,47 +221,46 @@ protected override void OnLoad(EventArgs e) protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (ModuleContent != null && ModuleControl != null && !Globals.IsAdminControl()) + if (this.ModuleContent != null && this.ModuleControl != null && !Globals.IsAdminControl()) { - switch (ModuleControl.ModuleContext.Configuration.Visibility) + switch (this.ModuleControl.ModuleContext.Configuration.Visibility) { case VisibilityState.Maximized: case VisibilityState.Minimized: - DNNClientAPI.EnableMinMax(cmdVisibility, - ModuleContent, - ModuleControl.ModuleContext.ModuleId, - ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, - MinIconLoc, - MaxIconLoc, - DNNClientAPI.MinMaxPersistanceType.Cookie, - AnimationFrames); + DNNClientAPI.EnableMinMax( + this.cmdVisibility, + this.ModuleContent, + this.ModuleControl.ModuleContext.ModuleId, + this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, + this.MinIconLoc, + this.MaxIconLoc, + DNNClientAPI.MinMaxPersistanceType.Cookie, + this.AnimationFrames); break; } } } - private void cmdVisibility_Click(Object sender, EventArgs e) + private void cmdVisibility_Click(object sender, EventArgs e) { try { - if (ModuleContent != null) + if (this.ModuleContent != null) { - if (ModuleContent.Visible) + if (this.ModuleContent.Visible) { - ContentVisible = false; + this.ContentVisible = false; } else { - ContentVisible = true; + this.ContentVisible = true; } } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion + } } } diff --git a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs index 565f356ab43..e97010d15d1 100644 --- a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs +++ b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs @@ -1,38 +1,40 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Web.Script.Serialization; -using System.Web.UI; -using DotNetNuke.Collections; -using DotNetNuke.Common; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Actions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Containers; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + // ReSharper disable ConvertPropertyToExpressionBody // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace namespace DotNetNuke.Admin.Containers + // ReSharper restore CheckNamespace { + using System; + using System.Collections.Generic; + using System.Web.Script.Serialization; + using System.Web.UI; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Containers; + using DotNetNuke.UI.Modules; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + public partial class ModuleActions : ActionBase { private readonly List validIDs = new List(); - + protected string AdminActionsJSON { get; set; } protected string AdminText @@ -62,75 +64,70 @@ protected string MoveText protected bool IsShared { get; set; } + protected string ModuleTitle { get; set; } + protected string LocalizeString(string key) { return Localization.GetString(key, Localization.GlobalResourceFile); } - protected string ModuleTitle { get; set; } - protected override void OnInit(EventArgs e) { base.OnInit(e); - ID = "ModuleActions"; + this.ID = "ModuleActions"; - actionButton.Click += actionButton_Click; + this.actionButton.Click += this.actionButton_Click; JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ClientResourceManager.RegisterStyleSheet(Page, "~/admin/menus/ModuleActions/ModuleActions.css", FileOrder.Css.ModuleCss); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnnicons/css/dnnicon.min.css", FileOrder.Css.ModuleCss); - ClientResourceManager.RegisterScript(Page, "~/admin/menus/ModuleActions/ModuleActions.js"); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/admin/menus/ModuleActions/ModuleActions.css", FileOrder.Css.ModuleCss); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnnicons/css/dnnicon.min.css", FileOrder.Css.ModuleCss); + ClientResourceManager.RegisterScript(this.Page, "~/admin/menus/ModuleActions/ModuleActions.js"); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); } - void actionButton_Click(object sender, EventArgs e) - { - ProcessAction(Request.Params["__EVENTARGUMENT"]); - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); - AdminActionsJSON = "[]"; - CustomActionsJSON = "[]"; - Panes = "[]"; + this.AdminActionsJSON = "[]"; + this.CustomActionsJSON = "[]"; + this.Panes = "[]"; try { - SupportsQuickSettings = false; - DisplayQuickSettings = false; - ModuleTitle = ModuleContext.Configuration.ModuleTitle; - var moduleDefinitionId = ModuleContext.Configuration.ModuleDefID; + this.SupportsQuickSettings = false; + this.DisplayQuickSettings = false; + this.ModuleTitle = this.ModuleContext.Configuration.ModuleTitle; + var moduleDefinitionId = this.ModuleContext.Configuration.ModuleDefID; var quickSettingsControl = ModuleControlController.GetModuleControlByControlKey("QuickSettings", moduleDefinitionId); if (quickSettingsControl != null) { - SupportsQuickSettings = true; - var control = ModuleControlFactory.LoadModuleControl(Page, ModuleContext.Configuration, "QuickSettings", quickSettingsControl.ControlSrc); - control.ID += ModuleContext.ModuleId; - quickSettings.Controls.Add(control); + this.SupportsQuickSettings = true; + var control = ModuleControlFactory.LoadModuleControl(this.Page, this.ModuleContext.Configuration, "QuickSettings", quickSettingsControl.ControlSrc); + control.ID += this.ModuleContext.ModuleId; + this.quickSettings.Controls.Add(control); - DisplayQuickSettings = ModuleContext.Configuration.ModuleSettings.GetValueOrDefault("QS_FirstLoad", true); - ModuleController.Instance.UpdateModuleSetting(ModuleContext.ModuleId, "QS_FirstLoad", "False"); + this.DisplayQuickSettings = this.ModuleContext.Configuration.ModuleSettings.GetValueOrDefault("QS_FirstLoad", true); + ModuleController.Instance.UpdateModuleSetting(this.ModuleContext.ModuleId, "QS_FirstLoad", "False"); - ClientResourceManager.RegisterScript(Page, "~/admin/menus/ModuleActions/dnnQuickSettings.js"); + ClientResourceManager.RegisterScript(this.Page, "~/admin/menus/ModuleActions/dnnQuickSettings.js"); } - if (ActionRoot.Visible) + if (this.ActionRoot.Visible) { - //Add Menu Items - foreach (ModuleAction rootAction in ActionRoot.Actions) + // Add Menu Items + foreach (ModuleAction rootAction in this.ActionRoot.Actions) { - //Process Children + // Process Children var actions = new List(); foreach (ModuleAction action in rootAction.Actions) { if (action.Visible) { - if ((EditMode && Globals.IsAdminControl() == false) || + if ((this.EditMode && Globals.IsAdminControl() == false) || (action.Secure != SecurityAccessLevel.Anonymous && action.Secure != SecurityAccessLevel.View)) { if (!action.Icon.Contains("://") @@ -139,6 +136,7 @@ protected override void OnLoad(EventArgs e) { action.Icon = "~/images/" + action.Icon; } + if (action.Icon.StartsWith("~/")) { action.Icon = Globals.ResolveUrl(action.Icon); @@ -146,39 +144,39 @@ protected override void OnLoad(EventArgs e) actions.Add(action); - if(String.IsNullOrEmpty(action.Url)) + if (string.IsNullOrEmpty(action.Url)) { - validIDs.Add(action.ID); + this.validIDs.Add(action.ID); } } } - } var oSerializer = new JavaScriptSerializer(); if (rootAction.Title == Localization.GetString("ModuleGenericActions.Action", Localization.GlobalResourceFile)) { - AdminActionsJSON = oSerializer.Serialize(actions); + this.AdminActionsJSON = oSerializer.Serialize(actions); } else { if (rootAction.Title == Localization.GetString("ModuleSpecificActions.Action", Localization.GlobalResourceFile)) { - CustomActionsJSON = oSerializer.Serialize(actions); + this.CustomActionsJSON = oSerializer.Serialize(actions); } else { - SupportsMove = (actions.Count > 0); - Panes = oSerializer.Serialize(PortalSettings.ActiveTab.Panes); + this.SupportsMove = actions.Count > 0; + this.Panes = oSerializer.Serialize(this.PortalSettings.ActiveTab.Panes); } } } - IsShared = ModuleContext.Configuration.AllTabs - || PortalGroupController.Instance.IsModuleShared(ModuleContext.ModuleId, PortalController.Instance.GetPortal(PortalSettings.PortalId)) - || TabController.Instance.GetTabsByModuleID(ModuleContext.ModuleId).Count > 1; + + this.IsShared = this.ModuleContext.Configuration.AllTabs + || PortalGroupController.Instance.IsModuleShared(this.ModuleContext.ModuleId, PortalController.Instance.GetPortal(this.PortalSettings.PortalId)) + || TabController.Instance.GetTabsByModuleID(this.ModuleContext.ModuleId).Count > 1; } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -188,10 +186,15 @@ protected override void Render(HtmlTextWriter writer) { base.Render(writer); - foreach(int id in validIDs) + foreach (int id in this.validIDs) { - Page.ClientScript.RegisterForEventValidation(actionButton.UniqueID, id.ToString()); + this.Page.ClientScript.RegisterForEventValidation(this.actionButton.UniqueID, id.ToString()); } } - } + + private void actionButton_Click(object sender, EventArgs e) + { + this.ProcessAction(this.Request.Params["__EVENTARGUMENT"]); + } + } } diff --git a/DNN Platform/Website/admin/Modules/App_LocalResources/Export.ascx.resx b/DNN Platform/Website/admin/Modules/App_LocalResources/Export.ascx.resx index 5e2d9907962..d35ac90c1de 100644 --- a/DNN Platform/Website/admin/Modules/App_LocalResources/Export.ascx.resx +++ b/DNN Platform/Website/admin/Modules/App_LocalResources/Export.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Modules/App_LocalResources/Import.ascx.resx b/DNN Platform/Website/admin/Modules/App_LocalResources/Import.ascx.resx index 2fe9b3072a2..26d74a7aebc 100644 --- a/DNN Platform/Website/admin/Modules/App_LocalResources/Import.ascx.resx +++ b/DNN Platform/Website/admin/Modules/App_LocalResources/Import.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleLocalization.ascx.resx b/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleLocalization.ascx.resx index ce20ecc965b..14c57921875 100644 --- a/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleLocalization.ascx.resx +++ b/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleLocalization.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Modules/App_LocalResources/ModulePermissions.ascx.resx b/DNN Platform/Website/admin/Modules/App_LocalResources/ModulePermissions.ascx.resx index 6a2b7d842a8..90ff8293040 100644 --- a/DNN Platform/Website/admin/Modules/App_LocalResources/ModulePermissions.ascx.resx +++ b/DNN Platform/Website/admin/Modules/App_LocalResources/ModulePermissions.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleSettings.ascx.resx b/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleSettings.ascx.resx index bc0a5358180..f5e64f2e75f 100644 --- a/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleSettings.ascx.resx +++ b/DNN Platform/Website/admin/Modules/App_LocalResources/ModuleSettings.ascx.resx @@ -1,65 +1,6 @@  - - + @@ -360,15 +301,6 @@ Cache Duration (seconds) - - Clear Cache for This Tab Module - - - Clear Cache for All Tab Modules - - - Current Cache Count: {0} item(s) for this tab module. - This module has indicated a recommendation to disable caching (select NONE from the Output Cache Provider list above). Enabling caching on this module is not recommended and may cause the module to display stale data. @@ -382,10 +314,10 @@ Tags:
        - Check this box to hide the red border that shows around the module when it is only visible to Administrators. + Check this box to suppress the message at the top of the module, stating that it is only visible to administrators (if no additional permissions granted). - Hide Admin Border + Hide admin message The culture for this module. diff --git a/DNN Platform/Website/admin/Modules/App_LocalResources/ViewSource.ascx.resx b/DNN Platform/Website/admin/Modules/App_LocalResources/ViewSource.ascx.resx index 0ea71b261aa..fae36e14336 100644 --- a/DNN Platform/Website/admin/Modules/App_LocalResources/ViewSource.ascx.resx +++ b/DNN Platform/Website/admin/Modules/App_LocalResources/ViewSource.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Modules/Export.ascx.cs b/DNN Platform/Website/admin/Modules/Export.ascx.cs index 31ee0b865e6..ebdd2fc3292 100644 --- a/DNN Platform/Website/admin/Modules/Export.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Export.ascx.cs @@ -1,37 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Web.UI.WebControls; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Modules { + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Web.UI.WebControls; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// /// @@ -41,21 +37,20 @@ namespace DotNetNuke.Modules.Admin.Modules public partial class Export : PortalModuleBase { private readonly INavigationManager _navigationManager; - public Export() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members - + private new int ModuleId = -1; private ModuleInfo _module; + + public Export() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } private ModuleInfo Module { get { - return _module ?? (_module = ModuleController.Instance.GetModule(ModuleId, TabId, false)); + return this._module ?? (this._module = ModuleController.Instance.GetModule(this.ModuleId, this.TabId, false)); } } @@ -63,38 +58,94 @@ private string ReturnURL { get { - return UrlUtils.ValidReturnUrl(Request.Params["ReturnURL"]) ?? _navigationManager.NavigateURL(); + return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); + } + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (this.Request.QueryString["moduleid"] != null) + { + int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); + } + + if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EXPORT", this.Module)) + { + this.Response.Redirect(Globals.AccessDeniedURL(), true); } } - #endregion + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); - #region Private Methods + this.cmdExport.Click += this.OnExportClick; + try + { + if (this.Request.QueryString["moduleid"] != null) + { + int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); + } + + if (!this.Page.IsPostBack) + { + this.cmdCancel.NavigateUrl = this.ReturnURL; + + this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); + this.cboFolders.Services.Parameters.Add("permission", "ADD"); + if (this.Module != null) + { + this.txtFile.Text = CleanName(this.Module.ModuleTitle); + } + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + private static string CleanName(string name) + { + var strName = name; + const string strBadChars = ". ~`!@#$%^&*()-_+={[}]|\\:;<,>?/\"'"; + + int intCounter; + for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++) + { + strName = strName.Replace(strBadChars.Substring(intCounter, 1), string.Empty); + } + + return strName; + } + private string ExportModule(int moduleID, string fileName, IFolderInfo folder) { - var strMessage = ""; - if (Module != null) + var strMessage = string.Empty; + if (this.Module != null) { - if (!String.IsNullOrEmpty(Module.DesktopModule.BusinessControllerClass) && Module.DesktopModule.IsPortable) + if (!string.IsNullOrEmpty(this.Module.DesktopModule.BusinessControllerClass) && this.Module.DesktopModule.IsPortable) { try { - var objObject = Reflection.CreateObject(Module.DesktopModule.BusinessControllerClass, Module.DesktopModule.BusinessControllerClass); + var objObject = Reflection.CreateObject(this.Module.DesktopModule.BusinessControllerClass, this.Module.DesktopModule.BusinessControllerClass); - //Double-check + // Double-check if (objObject is IPortable) { XmlDocument moduleXml = new XmlDocument { XmlResolver = null }; - XmlNode moduleNode = ModuleController.SerializeModule(moduleXml, Module, true); + XmlNode moduleNode = ModuleController.SerializeModule(moduleXml, this.Module, true); - //add attributes to XML document + // add attributes to XML document XmlAttribute typeAttribute = moduleXml.CreateAttribute("type"); - typeAttribute.Value = CleanName(Module.DesktopModule.ModuleName); + typeAttribute.Value = CleanName(this.Module.DesktopModule.ModuleName); moduleNode.Attributes.Append(typeAttribute); XmlAttribute versionAttribute = moduleXml.CreateAttribute("version"); - versionAttribute.Value = Module.DesktopModule.Version; + versionAttribute.Value = this.Module.DesktopModule.Version; moduleNode.Attributes.Append(versionAttribute); // Create content from XmlNode @@ -102,18 +153,18 @@ private string ExportModule(int moduleID, string fileName, IFolderInfo folder) XmlTextWriter xw = new XmlTextWriter(sw); moduleNode.WriteTo(xw); var content = sw.ToString(); - if (!String.IsNullOrEmpty(content)) + if (!string.IsNullOrEmpty(content)) { - //remove invalid chars in content -> DNN 26810: Handled by ModuleController.SerializeModule - //content = Regex.Replace(content, _invalidCharsRegex, string.Empty); - //add attributes to XML document - //content = "" + " DNN 26810: Handled by ModuleController.SerializeModule + // content = Regex.Replace(content, _invalidCharsRegex, string.Empty); + // add attributes to XML document + // content = "" + "" + content + ""; - //First check the Portal limits will not be exceeded (this is approximate) - if (PortalController.Instance.HasSpaceAvailable(PortalId, content.Length)) + // First check the Portal limits will not be exceeded (this is approximate) + if (PortalController.Instance.HasSpaceAvailable(this.PortalId, content.Length)) { - //add file to Files table + // add file to Files table using (var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(content))) { Services.FileSystem.FileManager.Instance.AddFile(folder, fileName, fileContent, true, true, "application/octet-stream"); @@ -126,12 +177,12 @@ private string ExportModule(int moduleID, string fileName, IFolderInfo folder) } else { - strMessage = Localization.GetString("NoContent", LocalResourceFile); + strMessage = Localization.GetString("NoContent", this.LocalResourceFile); } } else { - strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); + strMessage = Localization.GetString("ExportNotSupported", this.LocalResourceFile); } } catch (Exception ex) @@ -142,96 +193,36 @@ private string ExportModule(int moduleID, string fileName, IFolderInfo folder) } else { - strMessage = Localization.GetString("Error", LocalResourceFile); + strMessage = Localization.GetString("Error", this.LocalResourceFile); } } } else { - strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); + strMessage = Localization.GetString("ExportNotSupported", this.LocalResourceFile); } } + return strMessage; } - private static string CleanName(string name) - { - var strName = name; - const string strBadChars = ". ~`!@#$%^&*()-_+={[}]|\\:;<,>?/\"'"; - - int intCounter; - for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++) - { - strName = strName.Replace(strBadChars.Substring(intCounter, 1), ""); - } - return strName; - } - - #endregion - - #region Event Handlers - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (Request.QueryString["moduleid"] != null) - { - Int32.TryParse(Request.QueryString["moduleid"], out ModuleId); - } - if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EXPORT", Module)) - { - Response.Redirect(Globals.AccessDeniedURL(), true); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cmdExport.Click += OnExportClick; - - try - { - if (Request.QueryString["moduleid"] != null) - { - Int32.TryParse(Request.QueryString["moduleid"], out ModuleId); - } - if (!Page.IsPostBack) - { - cmdCancel.NavigateUrl = ReturnURL; - - cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); - cboFolders.Services.Parameters.Add("permission", "ADD"); - if (Module != null) - { - txtFile.Text = CleanName(Module.ModuleTitle); - } - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - protected void OnExportClick(object sender, EventArgs e) { try { IFolderInfo folder = null; - if (cboFolders.SelectedItem != null && !String.IsNullOrEmpty(txtFile.Text)) + if (this.cboFolders.SelectedItem != null && !string.IsNullOrEmpty(this.txtFile.Text)) { - folder = FolderManager.Instance.GetFolder(cboFolders.SelectedItemValueAsInt); + folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); } if (folder != null) { - var strFile = "content." + CleanName(Module.DesktopModule.ModuleName) + "." + CleanName(txtFile.Text) + ".export"; - var strMessage = ExportModule(ModuleId, strFile, folder); - if (String.IsNullOrEmpty(strMessage)) + var strFile = "content." + CleanName(this.Module.DesktopModule.ModuleName) + "." + CleanName(this.txtFile.Text) + ".export"; + var strMessage = this.ExportModule(this.ModuleId, strFile, folder); + if (string.IsNullOrEmpty(strMessage)) { - Response.Redirect(ReturnURL, true); + this.Response.Redirect(this.ReturnURL, true); } else { @@ -240,16 +231,13 @@ protected void OnExportClick(object sender, EventArgs e) } else { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("Validation", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("Validation", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - + } } } diff --git a/DNN Platform/Website/admin/Modules/Import.ascx.cs b/DNN Platform/Website/admin/Modules/Import.ascx.cs index b2b3ed34289..0bda46701c1 100644 --- a/DNN Platform/Website/admin/Modules/Import.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Import.ascx.cs @@ -1,52 +1,46 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.IO; -using System.Web; -using System.Web.UI.WebControls; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Modules { + using System; + using System.Collections; + using System.IO; + using System.Web; + using System.Web.UI.WebControls; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + public partial class Import : PortalModuleBase { private readonly INavigationManager _navigationManager; - public Import() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members - + private new int ModuleId = -1; private ModuleInfo _module; + + public Import() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } private ModuleInfo Module { get { - return _module ?? (_module = ModuleController.Instance.GetModule(ModuleId, TabId, false)); + return this._module ?? (this._module = ModuleController.Instance.GetModule(this.ModuleId, this.TabId, false)); } } @@ -54,195 +48,204 @@ private string ReturnURL { get { - return UrlUtils.ValidReturnUrl(Request.Params["ReturnURL"]) ?? _navigationManager.NavigateURL(); + return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); + } + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (this.Request.QueryString["moduleid"] != null) + { + int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); + } + + // Verify that the current user has access to edit this module + if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "IMPORT", this.Module)) + { + this.Response.Redirect(Globals.AccessDeniedURL(), true); } } - #endregion + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); - #region Private Methods + this.cboFolders.SelectionChanged += this.OnFoldersIndexChanged; + this.cboFiles.SelectedIndexChanged += this.OnFilesIndexChanged; + this.cmdImport.Click += this.OnImportClick; + try + { + if (!this.Page.IsPostBack) + { + this.cmdCancel.NavigateUrl = this.ReturnURL; + this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); + this.cboFolders.Services.Parameters.Add("permission", "ADD"); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private string ImportModule() { - var strMessage = ""; - if (Module != null) + var strMessage = string.Empty; + if (this.Module != null) { - if (!String.IsNullOrEmpty(Module.DesktopModule.BusinessControllerClass) && Module.DesktopModule.IsPortable) + if (!string.IsNullOrEmpty(this.Module.DesktopModule.BusinessControllerClass) && this.Module.DesktopModule.IsPortable) { try { - var objObject = Reflection.CreateObject(Module.DesktopModule.BusinessControllerClass, Module.DesktopModule.BusinessControllerClass); + var objObject = Reflection.CreateObject(this.Module.DesktopModule.BusinessControllerClass, this.Module.DesktopModule.BusinessControllerClass); if (objObject is IPortable) { var xmlDoc = new XmlDocument { XmlResolver = null }; try { - var content = XmlUtils.RemoveInvalidXmlCharacters(txtContent.Text); + var content = XmlUtils.RemoveInvalidXmlCharacters(this.txtContent.Text); xmlDoc.LoadXml(content); } catch { - strMessage = Localization.GetString("NotValidXml", LocalResourceFile); + strMessage = Localization.GetString("NotValidXml", this.LocalResourceFile); } - if (String.IsNullOrEmpty(strMessage)) + + if (string.IsNullOrEmpty(strMessage)) { var strType = xmlDoc.DocumentElement.GetAttribute("type"); - if (strType == Globals.CleanName(Module.DesktopModule.ModuleName) || strType == Globals.CleanName(Module.DesktopModule.FriendlyName)) + if (strType == Globals.CleanName(this.Module.DesktopModule.ModuleName) || strType == Globals.CleanName(this.Module.DesktopModule.FriendlyName)) { var strVersion = xmlDoc.DocumentElement.GetAttribute("version"); + // DNN26810 if rootnode = "content", import only content(the old way) - if (xmlDoc.DocumentElement.Name.ToLowerInvariant() == "content" ) + if (xmlDoc.DocumentElement.Name.ToLowerInvariant() == "content") { - ((IPortable)objObject).ImportModule(ModuleId, xmlDoc.DocumentElement.InnerXml, strVersion, UserInfo.UserID); + ((IPortable)objObject).ImportModule(this.ModuleId, xmlDoc.DocumentElement.InnerXml, strVersion, this.UserInfo.UserID); } + // otherwise (="module") import the new way else { - ModuleController.DeserializeModule(xmlDoc.DocumentElement, Module, PortalId, TabId); + ModuleController.DeserializeModule(xmlDoc.DocumentElement, this.Module, this.PortalId, this.TabId); } - Response.Redirect(_navigationManager.NavigateURL(), true); + + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } else { - strMessage = Localization.GetString("NotCorrectType", LocalResourceFile); + strMessage = Localization.GetString("NotCorrectType", this.LocalResourceFile); } } } else { - strMessage = Localization.GetString("ImportNotSupported", LocalResourceFile); + strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile); } } catch { - strMessage = Localization.GetString("Error", LocalResourceFile); + strMessage = Localization.GetString("Error", this.LocalResourceFile); } } else { - strMessage = Localization.GetString("ImportNotSupported", LocalResourceFile); + strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile); } } + return strMessage; - } - - #endregion - - #region Event Handlers - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (Request.QueryString["moduleid"] != null) - { - Int32.TryParse(Request.QueryString["moduleid"], out ModuleId); - } - - //Verify that the current user has access to edit this module - if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "IMPORT", Module)) - { - Response.Redirect(Globals.AccessDeniedURL(), true); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cboFolders.SelectionChanged += OnFoldersIndexChanged; - cboFiles.SelectedIndexChanged += OnFilesIndexChanged; - cmdImport.Click += OnImportClick; - - try - { - if (!Page.IsPostBack) - { - cmdCancel.NavigateUrl = ReturnURL; - cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); - cboFolders.Services.Parameters.Add("permission", "ADD"); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } + } protected void OnFoldersIndexChanged(object sender, EventArgs e) { - cboFiles.Items.Clear(); - cboFiles.InsertItem(0, "<" + Localization.GetString("None_Specified") + ">", "-"); - if (cboFolders.SelectedItem == null) + this.cboFiles.Items.Clear(); + this.cboFiles.InsertItem(0, "<" + Localization.GetString("None_Specified") + ">", "-"); + if (this.cboFolders.SelectedItem == null) { return; } - if (Module == null) + + if (this.Module == null) { return; } - var folder = FolderManager.Instance.GetFolder(cboFolders.SelectedItemValueAsInt); - if (folder == null) return; - - var files = Globals.GetFileList(PortalId, "export", false, folder.FolderPath); - files.AddRange(Globals.GetFileList(PortalId, "xml", false, folder.FolderPath)); + var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); + if (folder == null) + { + return; + } + + var files = Globals.GetFileList(this.PortalId, "export", false, folder.FolderPath); + files.AddRange(Globals.GetFileList(this.PortalId, "xml", false, folder.FolderPath)); foreach (FileItem file in files) { - if (file.Text.IndexOf("content." + Globals.CleanName(Module.DesktopModule.ModuleName) + ".", System.StringComparison.Ordinal) != -1) + if (file.Text.IndexOf("content." + Globals.CleanName(this.Module.DesktopModule.ModuleName) + ".", System.StringComparison.Ordinal) != -1) { - cboFiles.AddItem(file.Text.Replace("content." + Globals.CleanName(Module.DesktopModule.ModuleName) + ".", ""), file.Value); + this.cboFiles.AddItem(file.Text.Replace("content." + Globals.CleanName(this.Module.DesktopModule.ModuleName) + ".", string.Empty), file.Value); } - //legacy support for files which used the FriendlyName - if (Globals.CleanName(Module.DesktopModule.ModuleName) == Globals.CleanName(Module.DesktopModule.FriendlyName)) + // legacy support for files which used the FriendlyName + if (Globals.CleanName(this.Module.DesktopModule.ModuleName) == Globals.CleanName(this.Module.DesktopModule.FriendlyName)) { continue; } - if (file.Text.IndexOf("content." + Globals.CleanName(Module.DesktopModule.FriendlyName) + ".", System.StringComparison.Ordinal) != -1) + if (file.Text.IndexOf("content." + Globals.CleanName(this.Module.DesktopModule.FriendlyName) + ".", System.StringComparison.Ordinal) != -1) { - cboFiles.AddItem(file.Text.Replace("content." + Globals.CleanName(Module.DesktopModule.FriendlyName) + ".", ""), file.Value); + this.cboFiles.AddItem(file.Text.Replace("content." + Globals.CleanName(this.Module.DesktopModule.FriendlyName) + ".", string.Empty), file.Value); } } } protected void OnFilesIndexChanged(object sender, EventArgs e) { - if (cboFolders.SelectedItem == null) return; - var folder = FolderManager.Instance.GetFolder(cboFolders.SelectedItemValueAsInt); - if (folder == null) return; - - if (string.IsNullOrEmpty(cboFiles.SelectedValue) || cboFiles.SelectedValue == "-") - { - txtContent.Text = string.Empty; - return; - } - try - { - var fileId = Convert.ToInt32(cboFiles.SelectedValue); - var file = DotNetNuke.Services.FileSystem.FileManager.Instance.GetFile(fileId); - using (var streamReader = new StreamReader(DotNetNuke.Services.FileSystem.FileManager.Instance.GetFileContent(file))) - { - txtContent.Text = streamReader.ReadToEnd(); - } - } - catch (Exception) - { - txtContent.Text = string.Empty; - } + if (this.cboFolders.SelectedItem == null) + { + return; + } + + var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); + if (folder == null) + { + return; + } + + if (string.IsNullOrEmpty(this.cboFiles.SelectedValue) || this.cboFiles.SelectedValue == "-") + { + this.txtContent.Text = string.Empty; + return; + } + + try + { + var fileId = Convert.ToInt32(this.cboFiles.SelectedValue); + var file = DotNetNuke.Services.FileSystem.FileManager.Instance.GetFile(fileId); + using (var streamReader = new StreamReader(DotNetNuke.Services.FileSystem.FileManager.Instance.GetFileContent(file))) + { + this.txtContent.Text = streamReader.ReadToEnd(); + } + } + catch (Exception) + { + this.txtContent.Text = string.Empty; + } } protected void OnImportClick(object sender, EventArgs e) { try { - if (Module != null) + if (this.Module != null) { - var strMessage = ImportModule(); - if (String.IsNullOrEmpty(strMessage)) + var strMessage = this.ImportModule(); + if (string.IsNullOrEmpty(strMessage)) { - Response.Redirect(ReturnURL, true); + this.Response.Redirect(this.ReturnURL, true); } else { @@ -254,9 +257,6 @@ protected void OnImportClick(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - + } } } diff --git a/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs b/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs index b07b63f88e3..1569e249e65 100644 --- a/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs +++ b/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs @@ -1,29 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using Globals = DotNetNuke.Common.Globals; -using DotNetNuke.Abstractions; - -#endregion - -// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +// ReSharper disable CheckNamespace namespace DotNetNuke.Modules.Admin.Modules + // ReSharper restore CheckNamespace { - + using System; + using System.Web.UI; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; + /// /// The ModuleSettingsPage PortalModuleBase is used to edit the settings for a /// module. @@ -33,47 +29,42 @@ namespace DotNetNuke.Modules.Admin.Modules public partial class ModulePermissions : PortalModuleBase { private readonly INavigationManager _navigationManager; - public ModulePermissions() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members - + private int _moduleId = -1; private ModuleInfo _module; + + public ModulePermissions() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } private ModuleInfo Module { - get { return _module ?? (_module = ModuleController.Instance.GetModule(_moduleId, TabId, false)); } + get { return this._module ?? (this._module = ModuleController.Instance.GetModule(this._moduleId, this.TabId, false)); } } private string ReturnURL { get { - return UrlUtils.ValidReturnUrl(Request.Params["ReturnURL"]) ?? _navigationManager.NavigateURL(); + return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } - } - - #endregion - - #region Event Handlers - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); - //get ModuleId - if ((Request.QueryString["ModuleId"] != null)) + // get ModuleId + if (this.Request.QueryString["ModuleId"] != null) { - _moduleId = Int32.Parse(Request.QueryString["ModuleId"]); + this._moduleId = int.Parse(this.Request.QueryString["ModuleId"]); } - //Verify that the current user has access to edit this module - if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.ViewPermissions, String.Empty, Module)) + // Verify that the current user has access to edit this module + if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.ViewPermissions, string.Empty, this.Module)) { - Response.Redirect(Globals.AccessDeniedURL(), true); + this.Response.Redirect(Globals.AccessDeniedURL(), true); } } @@ -81,21 +72,21 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdUpdate.Click += OnUpdateClick; + this.cmdUpdate.Click += this.OnUpdateClick; try { - cancelHyperLink.NavigateUrl = ReturnURL; + this.cancelHyperLink.NavigateUrl = this.ReturnURL; - if (Page.IsPostBack == false) + if (this.Page.IsPostBack == false) { - dgPermissions.TabId = PortalSettings.ActiveTab.TabID; - dgPermissions.ModuleID = _moduleId; + this.dgPermissions.TabId = this.PortalSettings.ActiveTab.TabID; + this.dgPermissions.ModuleID = this._moduleId; - if (Module != null) + if (this.Module != null) { - cmdUpdate.Visible = ModulePermissionController.HasModulePermission(Module.ModulePermissions, "EDIT,MANAGE") || TabPermissionController.CanAddContentToPage(); - permissionsRow.Visible = ModulePermissionController.CanAdminModule(Module) || TabPermissionController.CanAddContentToPage(); + this.cmdUpdate.Visible = ModulePermissionController.HasModulePermission(this.Module.ModulePermissions, "EDIT,MANAGE") || TabPermissionController.CanAddContentToPage(); + this.permissionsRow.Visible = ModulePermissionController.CanAdminModule(this.Module) || TabPermissionController.CanAddContentToPage(); } } } @@ -109,24 +100,21 @@ protected void OnUpdateClick(object sender, EventArgs e) { try { - if (Page.IsValid) + if (this.Page.IsValid) { - Module.ModulePermissions.Clear(); - Module.ModulePermissions.AddRange(dgPermissions.Permissions); + this.Module.ModulePermissions.Clear(); + this.Module.ModulePermissions.AddRange(this.dgPermissions.Permissions); - ModulePermissionController.SaveModulePermissions(Module); + ModulePermissionController.SaveModulePermissions(this.Module); - //Navigate back to admin page - Response.Redirect(ReturnURL, true); + // Navigate back to admin page + this.Response.Redirect(this.ReturnURL, true); } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - + } } } diff --git a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs index a3c40bf6748..9088698f048 100644 --- a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs @@ -1,42 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.ModuleCache; -using DotNetNuke.UI.Modules; -using DotNetNuke.UI.Skins; -using DotNetNuke.UI.Skins.Controls; -using Globals = DotNetNuke.Common.Globals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information // ReSharper disable CheckNamespace namespace DotNetNuke.Modules.Admin.Modules + // ReSharper restore CheckNamespace { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading; + using System.Web.UI; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.ModuleCache; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; /// /// The ModuleSettingsPage PortalModuleBase is used to edit the settings for a @@ -48,31 +44,32 @@ public partial class ModuleSettingsPage : PortalModuleBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleSettingsPage)); private readonly INavigationManager _navigationManager; + + private int _moduleId = -1; + private Control _control; + private ModuleInfo _module; + public ModuleSettingsPage() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); } - #region Private Members + private bool HideDeleteButton => this.Request.QueryString["HideDelete"] == "true"; - private int _moduleId = -1; - private Control _control; - private ModuleInfo _module; + private bool HideCancelButton => this.Request.QueryString["HideCancel"] == "true"; - private bool HideDeleteButton => Request.QueryString["HideDelete"] == "true"; - private bool HideCancelButton => Request.QueryString["HideCancel"] == "true"; - private bool DoNotRedirectOnUpdate => Request.QueryString["NoRedirectOnUpdate"] == "true"; + private bool DoNotRedirectOnUpdate => this.Request.QueryString["NoRedirectOnUpdate"] == "true"; private ModuleInfo Module { - get { return _module ?? (_module = ModuleController.Instance.GetModule(_moduleId, TabId, false)); } + get { return this._module ?? (this._module = ModuleController.Instance.GetModule(this._moduleId, this.TabId, false)); } } private ISettingsControl SettingsControl { get { - return _control as ISettingsControl; + return this._control as ISettingsControl; } } @@ -80,300 +77,301 @@ private string ReturnURL { get { - return UrlUtils.ValidReturnUrl(Request.Params["ReturnURL"]) ?? _navigationManager.NavigateURL(); + return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } } - #endregion + protected string GetInstalledOnLink(object dataItem) + { + var returnValue = new StringBuilder(); + var tab = dataItem as TabInfo; + if (tab != null) + { + var index = 0; + TabController.Instance.PopulateBreadCrumbs(ref tab); + var defaultAlias = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID) + .OrderByDescending(a => a.IsPrimary) + .FirstOrDefault(); + var portalSettings = new PortalSettings(tab.PortalID) + { + PortalAlias = defaultAlias, + }; + + var tabUrl = this._navigationManager.NavigateURL(tab.TabID, portalSettings, string.Empty); - #region Private Methods + foreach (TabInfo t in tab.BreadCrumbs) + { + if (index > 0) + { + returnValue.Append(" > "); + } + + if (tab.BreadCrumbs.Count - 1 == index) + { + returnValue.AppendFormat("{1}", tabUrl, t.LocalizedTabName); + } + else + { + returnValue.AppendFormat("{0}", t.LocalizedTabName); + } + + index = index + 1; + } + } + + return returnValue.ToString(); + } + + protected string GetInstalledOnSite(object dataItem) + { + string returnValue = string.Empty; + var tab = dataItem as TabInfo; + if (tab != null) + { + var portal = PortalController.Instance.GetPortal(tab.PortalID); + if (portal != null) + { + returnValue = portal.PortalName; + } + } + + return returnValue; + } private void BindData() { - if (Module != null) + if (this.Module != null) { - var desktopModule = DesktopModuleController.GetDesktopModule(Module.DesktopModuleID, PortalId); - dgPermissions.ResourceFile = Globals.ApplicationPath + "/DesktopModules/" + desktopModule.FolderName + "/" + Localization.LocalResourceDirectory + "/" + + var desktopModule = DesktopModuleController.GetDesktopModule(this.Module.DesktopModuleID, this.PortalId); + this.dgPermissions.ResourceFile = Globals.ApplicationPath + "/DesktopModules/" + desktopModule.FolderName + "/" + Localization.LocalResourceDirectory + "/" + Localization.LocalSharedResourceFile; - if (!Module.IsShared) + if (!this.Module.IsShared) { - chkInheritPermissions.Checked = Module.InheritViewPermissions; - dgPermissions.InheritViewPermissionsFromTab = Module.InheritViewPermissions; + this.chkInheritPermissions.Checked = this.Module.InheritViewPermissions; + this.dgPermissions.InheritViewPermissionsFromTab = this.Module.InheritViewPermissions; } - txtFriendlyName.Text = Module.DesktopModule.FriendlyName; - txtTitle.Text = Module.ModuleTitle; - ctlIcon.Url = Module.IconFile; - if (cboTab.FindItemByValue(Module.TabID.ToString()) != null) + this.txtFriendlyName.Text = this.Module.DesktopModule.FriendlyName; + this.txtTitle.Text = this.Module.ModuleTitle; + this.ctlIcon.Url = this.Module.IconFile; + + if (this.cboTab.FindItemByValue(this.Module.TabID.ToString()) != null) { - cboTab.FindItemByValue(Module.TabID.ToString()).Selected = true; + this.cboTab.FindItemByValue(this.Module.TabID.ToString()).Selected = true; } - rowTab.Visible = cboTab.Items.Count != 1; - chkAllTabs.Checked = Module.AllTabs; - trnewPages.Visible = chkAllTabs.Checked; - allowIndexRow.Visible = desktopModule.IsSearchable; - chkAllowIndex.Checked = GetBooleanSetting("AllowIndex", true); - txtMoniker.Text = (string)Settings["Moniker"] ?? ""; + this.rowTab.Visible = this.cboTab.Items.Count != 1; + this.chkAllTabs.Checked = this.Module.AllTabs; + this.trnewPages.Visible = this.chkAllTabs.Checked; + this.allowIndexRow.Visible = desktopModule.IsSearchable; + this.chkAllowIndex.Checked = this.GetBooleanSetting("AllowIndex", true); + this.txtMoniker.Text = (string)this.Settings["Moniker"] ?? string.Empty; - cboVisibility.SelectedIndex = (int)Module.Visibility; - chkAdminBorder.Checked = Settings["hideadminborder"] != null && bool.Parse(Settings["hideadminborder"].ToString()); + this.cboVisibility.SelectedIndex = (int)this.Module.Visibility; + this.chkAdminBorder.Checked = this.Settings["hideadminborder"] != null && bool.Parse(this.Settings["hideadminborder"].ToString()); - var objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(Module.ModuleDefID); + var objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(this.Module.ModuleDefID); if (objModuleDef.DefaultCacheTime == Null.NullInteger) { - cacheWarningRow.Visible = true; - txtCacheDuration.Text = Module.CacheTime.ToString(); + this.cacheWarningRow.Visible = true; + this.txtCacheDuration.Text = this.Module.CacheTime.ToString(); } else { - cacheWarningRow.Visible = false; - txtCacheDuration.Text = Module.CacheTime.ToString(); + this.cacheWarningRow.Visible = false; + this.txtCacheDuration.Text = this.Module.CacheTime.ToString(); } - BindModuleCacheProviderList(); - ShowCacheRows(); + this.BindModuleCacheProviderList(); + + this.ShowCacheRows(); - cboAlign.Items.FindByValue(Module.Alignment).Selected = true; - txtColor.Text = Module.Color; - txtBorder.Text = Module.Border; + this.cboAlign.Items.FindByValue(this.Module.Alignment).Selected = true; + this.txtColor.Text = this.Module.Color; + this.txtBorder.Text = this.Module.Border; - txtHeader.Text = Module.Header; - txtFooter.Text = Module.Footer; + this.txtHeader.Text = this.Module.Header; + this.txtFooter.Text = this.Module.Footer; - if (!Null.IsNull(Module.StartDate)) + if (!Null.IsNull(this.Module.StartDate)) { - startDatePicker.SelectedDate = Module.StartDate; + this.startDatePicker.SelectedDate = this.Module.StartDate; } - if (!Null.IsNull(Module.EndDate) && Module.EndDate <= endDatePicker.MaxDate) + + if (!Null.IsNull(this.Module.EndDate) && this.Module.EndDate <= this.endDatePicker.MaxDate) { - endDatePicker.SelectedDate = Module.EndDate; + this.endDatePicker.SelectedDate = this.Module.EndDate; } - BindContainers(); + this.BindContainers(); - chkDisplayTitle.Checked = Module.DisplayTitle; - chkDisplayPrint.Checked = Module.DisplayPrint; - chkDisplaySyndicate.Checked = Module.DisplaySyndicate; + this.chkDisplayTitle.Checked = this.Module.DisplayTitle; + this.chkDisplayPrint.Checked = this.Module.DisplayPrint; + this.chkDisplaySyndicate.Checked = this.Module.DisplaySyndicate; - chkWebSlice.Checked = Module.IsWebSlice; - webSliceTitle.Visible = Module.IsWebSlice; - webSliceExpiry.Visible = Module.IsWebSlice; - webSliceTTL.Visible = Module.IsWebSlice; + this.chkWebSlice.Checked = this.Module.IsWebSlice; + this.webSliceTitle.Visible = this.Module.IsWebSlice; + this.webSliceExpiry.Visible = this.Module.IsWebSlice; + this.webSliceTTL.Visible = this.Module.IsWebSlice; - txtWebSliceTitle.Text = Module.WebSliceTitle; - if (!Null.IsNull(Module.WebSliceExpiryDate)) + this.txtWebSliceTitle.Text = this.Module.WebSliceTitle; + if (!Null.IsNull(this.Module.WebSliceExpiryDate)) { - diWebSliceExpiry.SelectedDate = Module.WebSliceExpiryDate; + this.diWebSliceExpiry.SelectedDate = this.Module.WebSliceExpiryDate; } - if (!Null.IsNull(Module.WebSliceTTL)) + + if (!Null.IsNull(this.Module.WebSliceTTL)) { - txtWebSliceTTL.Text = Module.WebSliceTTL.ToString(); + this.txtWebSliceTTL.Text = this.Module.WebSliceTTL.ToString(); } - if (Module.ModuleID == PortalSettings.Current.DefaultModuleId && Module.TabID == PortalSettings.Current.DefaultTabId) + + if (this.Module.ModuleID == PortalSettings.Current.DefaultModuleId && this.Module.TabID == PortalSettings.Current.DefaultTabId) { - chkDefault.Checked = true; + this.chkDefault.Checked = true; } - if (!Module.IsShared && Module.DesktopModule.Shareable != ModuleSharing.Unsupported) + if (!this.Module.IsShared && this.Module.DesktopModule.Shareable != ModuleSharing.Unsupported) { - isShareableCheckBox.Checked = Module.IsShareable; - isShareableViewOnlyCheckBox.Checked = Module.IsShareableViewOnly; - isShareableRow.Visible = true; + this.isShareableCheckBox.Checked = this.Module.IsShareable; + this.isShareableViewOnlyCheckBox.Checked = this.Module.IsShareableViewOnly; + this.isShareableRow.Visible = true; - chkInheritPermissions.Visible = true; + this.chkInheritPermissions.Visible = true; } } } private void BindContainers() { - moduleContainerCombo.PortalId = PortalId; - moduleContainerCombo.RootPath = SkinController.RootContainer; - moduleContainerCombo.Scope = SkinScope.All; - moduleContainerCombo.IncludeNoneSpecificItem = true; - moduleContainerCombo.NoneSpecificText = "<" + Localization.GetString("None_Specified") + ">"; - moduleContainerCombo.SelectedValue = Module.ContainerSrc; + this.moduleContainerCombo.PortalId = this.PortalId; + this.moduleContainerCombo.RootPath = SkinController.RootContainer; + this.moduleContainerCombo.Scope = SkinScope.All; + this.moduleContainerCombo.IncludeNoneSpecificItem = true; + this.moduleContainerCombo.NoneSpecificText = "<" + Localization.GetString("None_Specified") + ">"; + this.moduleContainerCombo.SelectedValue = this.Module.ContainerSrc; } private void BindModulePages() { - var tabsByModule = TabController.Instance.GetTabsByModuleID(_moduleId); - tabsByModule.Remove(TabId); - dgOnTabs.DataSource = tabsByModule.Values; - dgOnTabs.DataBind(); + var tabsByModule = TabController.Instance.GetTabsByModuleID(this._moduleId); + tabsByModule.Remove(this.TabId); + this.dgOnTabs.DataSource = tabsByModule.Values; + this.dgOnTabs.DataBind(); } private void BindModuleCacheProviderList() { - cboCacheProvider.DataSource = GetFilteredProviders(ModuleCachingProvider.GetProviderList(), "ModuleCachingProvider"); - cboCacheProvider.DataBind(); + this.cboCacheProvider.DataSource = this.GetFilteredProviders(ModuleCachingProvider.GetProviderList(), "ModuleCachingProvider"); + this.cboCacheProvider.DataBind(); - //cboCacheProvider.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), "")); - cboCacheProvider.InsertItem(0, Localization.GetString("None_Specified"), ""); + // cboCacheProvider.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), "")); + this.cboCacheProvider.InsertItem(0, Localization.GetString("None_Specified"), string.Empty); - //if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()) != null) - if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.FindItemByValue(Module.GetEffectiveCacheMethod()) != null) + // if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()) != null) + if (!string.IsNullOrEmpty(this.Module.GetEffectiveCacheMethod()) && this.cboCacheProvider.FindItemByValue(this.Module.GetEffectiveCacheMethod()) != null) { - //cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()).Selected = true; - cboCacheProvider.FindItemByValue(Module.GetEffectiveCacheMethod()).Selected = true; + // cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()).Selected = true; + this.cboCacheProvider.FindItemByValue(this.Module.GetEffectiveCacheMethod()).Selected = true; } else { - //select the None Specified value - cboCacheProvider.Items[0].Selected = true; + // select the None Specified value + this.cboCacheProvider.Items[0].Selected = true; } - lblCacheInherited.Visible = Module.CacheMethod != Module.GetEffectiveCacheMethod(); + this.lblCacheInherited.Visible = this.Module.CacheMethod != this.Module.GetEffectiveCacheMethod(); } private IEnumerable GetFilteredProviders(Dictionary providerList, string keyFilter) { - var providers = from provider in providerList let filteredkey = provider.Key.Replace(keyFilter, String.Empty) select new { filteredkey, provider.Key }; + var providers = from provider in providerList let filteredkey = provider.Key.Replace(keyFilter, string.Empty) select new { filteredkey, provider.Key }; return providers; } private void ShowCacheRows() { - divCacheDuration.Visible = !string.IsNullOrEmpty(cboCacheProvider.SelectedValue); + this.divCacheDuration.Visible = !string.IsNullOrEmpty(this.cboCacheProvider.SelectedValue); } private bool GetBooleanSetting(string settingName, bool defaultValue) { - var value = Settings[settingName]; + var value = this.Settings[settingName]; return value == null ? defaultValue : bool.Parse(value.ToString()); } - #endregion - - #region Protected Methods - - protected string GetInstalledOnLink(object dataItem) - { - var returnValue = new StringBuilder(); - var tab = dataItem as TabInfo; - if (tab != null) - { - var index = 0; - TabController.Instance.PopulateBreadCrumbs(ref tab); - var defaultAlias = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID) - .OrderByDescending(a => a.IsPrimary) - .FirstOrDefault(); - var portalSettings = new PortalSettings(tab.PortalID) - { - PortalAlias = defaultAlias - }; - - var tabUrl = _navigationManager.NavigateURL(tab.TabID, portalSettings, string.Empty); - - foreach (TabInfo t in tab.BreadCrumbs) - { - if (index > 0) - { - returnValue.Append(" > "); - } - if (tab.BreadCrumbs.Count - 1 == index) - { - returnValue.AppendFormat("{1}", tabUrl, t.LocalizedTabName); - } - else - { - returnValue.AppendFormat("{0}", t.LocalizedTabName); - } - index = index + 1; - } - } - return returnValue.ToString(); - } - - protected string GetInstalledOnSite(object dataItem) - { - string returnValue = String.Empty; - var tab = dataItem as TabInfo; - if (tab != null) - { - var portal = PortalController.Instance.GetPortal(tab.PortalID); - if (portal != null) - { - returnValue = portal.PortalName; - } - } - return returnValue; - } - protected bool IsSharedViewOnly() { - return ModuleContext.Configuration.IsShared && ModuleContext.Configuration.IsShareableViewOnly; + return this.ModuleContext.Configuration.IsShared && this.ModuleContext.Configuration.IsShareableViewOnly; } - #endregion - - #region Event Handlers - protected override void OnInit(EventArgs e) { base.OnInit(e); try { - chkAllTabs.CheckedChanged += OnAllTabsCheckChanged; - chkInheritPermissions.CheckedChanged += OnInheritPermissionsChanged; - chkWebSlice.CheckedChanged += OnWebSliceCheckChanged; - cboCacheProvider.TextChanged += OnCacheProviderIndexChanged; - cmdDelete.Click += OnDeleteClick; - cmdUpdate.Click += OnUpdateClick; + this.chkAllTabs.CheckedChanged += this.OnAllTabsCheckChanged; + this.chkInheritPermissions.CheckedChanged += this.OnInheritPermissionsChanged; + this.chkWebSlice.CheckedChanged += this.OnWebSliceCheckChanged; + this.cboCacheProvider.TextChanged += this.OnCacheProviderIndexChanged; + this.cmdDelete.Click += this.OnDeleteClick; + this.cmdUpdate.Click += this.OnUpdateClick; - JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); - //get ModuleId - if ((Request.QueryString["ModuleId"] != null)) + // get ModuleId + if (this.Request.QueryString["ModuleId"] != null) { - _moduleId = Int32.Parse(Request.QueryString["ModuleId"]); + this._moduleId = int.Parse(this.Request.QueryString["ModuleId"]); } - if (Module.ContentItemId == Null.NullInteger && Module.ModuleID != Null.NullInteger) + + if (this.Module.ContentItemId == Null.NullInteger && this.Module.ModuleID != Null.NullInteger) { - //This tab does not have a valid ContentItem - ModuleController.Instance.CreateContentItem(Module); + // This tab does not have a valid ContentItem + ModuleController.Instance.CreateContentItem(this.Module); - ModuleController.Instance.UpdateModule(Module); + ModuleController.Instance.UpdateModule(this.Module); } - //Verify that the current user has access to edit this module - if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", Module)) + // Verify that the current user has access to edit this module + if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", this.Module)) { - if (!(IsSharedViewOnly() && TabPermissionController.CanAddContentToPage())) + if (!(this.IsSharedViewOnly() && TabPermissionController.CanAddContentToPage())) { - Response.Redirect(Globals.AccessDeniedURL(), true); + this.Response.Redirect(Globals.AccessDeniedURL(), true); } } - if (Module != null) + + if (this.Module != null) { - //get module - TabModuleId = Module.TabModuleID; + // get module + this.TabModuleId = this.Module.TabModuleID; - //get Settings Control - ModuleControlInfo moduleControlInfo = ModuleControlController.GetModuleControlByControlKey("Settings", Module.ModuleDefID); + // get Settings Control + ModuleControlInfo moduleControlInfo = ModuleControlController.GetModuleControlByControlKey("Settings", this.Module.ModuleDefID); if (moduleControlInfo != null) { + this._control = ModuleControlFactory.LoadSettingsControl(this.Page, this.Module, moduleControlInfo.ControlSrc); - _control = ModuleControlFactory.LoadSettingsControl(Page, Module, moduleControlInfo.ControlSrc); - - var settingsControl = _control as ISettingsControl; + var settingsControl = this._control as ISettingsControl; if (settingsControl != null) { - hlSpecificSettings.Text = Localization.GetString("ControlTitle_settings", + this.hlSpecificSettings.Text = Localization.GetString( + "ControlTitle_settings", settingsControl.LocalResourceFile); - if (String.IsNullOrEmpty(hlSpecificSettings.Text)) + if (string.IsNullOrEmpty(this.hlSpecificSettings.Text)) { - hlSpecificSettings.Text = - String.Format(Localization.GetString("ControlTitle_settings", LocalResourceFile), - Module.DesktopModule.FriendlyName); + this.hlSpecificSettings.Text = + string.Format( + Localization.GetString("ControlTitle_settings", this.LocalResourceFile), + this.Module.DesktopModule.FriendlyName); } - pnlSpecific.Controls.Add(_control); + + this.pnlSpecific.Controls.Add(this._control); } } } @@ -390,104 +388,109 @@ protected override void OnLoad(EventArgs e) try { - cancelHyperLink.NavigateUrl = ReturnURL; + this.cancelHyperLink.NavigateUrl = this.ReturnURL; - if (_moduleId != -1) + if (this._moduleId != -1) { - ctlAudit.Entity = Module; + this.ctlAudit.Entity = this.Module; } - if (Page.IsPostBack == false) + + if (this.Page.IsPostBack == false) { - ctlIcon.FileFilter = Globals.glbImageFileTypes; + this.ctlIcon.FileFilter = Globals.glbImageFileTypes; - dgPermissions.TabId = PortalSettings.ActiveTab.TabID; - dgPermissions.ModuleID = _moduleId; + this.dgPermissions.TabId = this.PortalSettings.ActiveTab.TabID; + this.dgPermissions.ModuleID = this._moduleId; - BindModulePages(); + this.BindModulePages(); - cboTab.DataSource = TabController.GetPortalTabs(PortalId, -1, false, Null.NullString, true, false, true, false, true); - cboTab.DataBind(); + this.cboTab.DataSource = TabController.GetPortalTabs(this.PortalId, -1, false, Null.NullString, true, false, true, false, true); + this.cboTab.DataBind(); - //if tab is a host tab, then add current tab - if (Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) + // if tab is a host tab, then add current tab + if (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) { - cboTab.InsertItem(0, PortalSettings.ActiveTab.LocalizedTabName, PortalSettings.ActiveTab.TabID.ToString()); + this.cboTab.InsertItem(0, this.PortalSettings.ActiveTab.LocalizedTabName, this.PortalSettings.ActiveTab.TabID.ToString()); } - if (Module != null) + + if (this.Module != null) { - if (cboTab.FindItemByValue(Module.TabID.ToString()) == null) + if (this.cboTab.FindItemByValue(this.Module.TabID.ToString()) == null) { - var objTab = TabController.Instance.GetTab(Module.TabID, Module.PortalID, false); - cboTab.AddItem(objTab.LocalizedTabName, objTab.TabID.ToString()); + var objTab = TabController.Instance.GetTab(this.Module.TabID, this.Module.PortalID, false); + this.cboTab.AddItem(objTab.LocalizedTabName, objTab.TabID.ToString()); } } - //only Portal Administrators can manage the visibility on all Tabs + // only Portal Administrators can manage the visibility on all Tabs var isAdmin = PermissionProvider.Instance().IsPortalEditor(); - rowAllTabs.Visible = isAdmin; - chkAllModules.Enabled = isAdmin; + this.rowAllTabs.Visible = isAdmin; + this.chkAllModules.Enabled = isAdmin; - if (HideCancelButton) + if (this.HideCancelButton) { - cancelHyperLink.Visible = false; + this.cancelHyperLink.Visible = false; } - //tab administrators can only manage their own tab + // tab administrators can only manage their own tab if (!TabPermissionController.CanAdminPage()) { - chkNewTabs.Enabled = false; - chkDefault.Enabled = false; - chkAllowIndex.Enabled = false; - cboTab.Enabled = false; + this.chkNewTabs.Enabled = false; + this.chkDefault.Enabled = false; + this.chkAllowIndex.Enabled = false; + this.cboTab.Enabled = false; } - if (_moduleId != -1) + if (this._moduleId != -1) { - BindData(); - cmdDelete.Visible = (ModulePermissionController.CanDeleteModule(Module) || - TabPermissionController.CanAddContentToPage()) && !HideDeleteButton; + this.BindData(); + this.cmdDelete.Visible = (ModulePermissionController.CanDeleteModule(this.Module) || + TabPermissionController.CanAddContentToPage()) && !this.HideDeleteButton; } else { - isShareableCheckBox.Checked = true; - isShareableViewOnlyCheckBox.Checked = true; - isShareableRow.Visible = true; + this.isShareableCheckBox.Checked = true; + this.isShareableViewOnlyCheckBox.Checked = true; + this.isShareableRow.Visible = true; - cboVisibility.SelectedIndex = 0; //maximized - chkAllTabs.Checked = false; - cmdDelete.Visible = false; + this.cboVisibility.SelectedIndex = 0; // maximized + this.chkAllTabs.Checked = false; + this.cmdDelete.Visible = false; } - if (Module != null) + + if (this.Module != null) { - cmdUpdate.Visible = ModulePermissionController.HasModulePermission(Module.ModulePermissions, "EDIT,MANAGE") || TabPermissionController.CanAddContentToPage(); - permissionsRow.Visible = ModulePermissionController.CanAdminModule(Module) || TabPermissionController.CanAddContentToPage(); + this.cmdUpdate.Visible = ModulePermissionController.HasModulePermission(this.Module.ModulePermissions, "EDIT,MANAGE") || TabPermissionController.CanAddContentToPage(); + this.permissionsRow.Visible = ModulePermissionController.CanAdminModule(this.Module) || TabPermissionController.CanAddContentToPage(); } - //Set visibility of Specific Settings - if (SettingsControl == null == false) + // Set visibility of Specific Settings + if (this.SettingsControl == null == false) { - //Get the module settings from the PortalSettings and pass the - //two settings hashtables to the sub control to process - SettingsControl.LoadSettings(); - specificSettingsTab.Visible = true; - fsSpecific.Visible = true; + // Get the module settings from the PortalSettings and pass the + // two settings hashtables to the sub control to process + this.SettingsControl.LoadSettings(); + this.specificSettingsTab.Visible = true; + this.fsSpecific.Visible = true; } else { - specificSettingsTab.Visible = false; - fsSpecific.Visible = false; + this.specificSettingsTab.Visible = false; + this.fsSpecific.Visible = false; } - if (Module != null) + if (this.Module != null) { - termsSelector.PortalId = Module.PortalID; - termsSelector.Terms = Module.Terms; + this.termsSelector.PortalId = this.Module.PortalID; + this.termsSelector.Terms = this.Module.Terms; } - termsSelector.DataBind(); + + this.termsSelector.DataBind(); } - if (Module != null) + + if (this.Module != null) { - cultureLanguageLabel.Language = Module.CultureCode; + this.cultureLanguageLabel.Language = this.Module.CultureCode; } } catch (Exception exc) @@ -498,20 +501,20 @@ protected override void OnLoad(EventArgs e) protected void OnAllTabsCheckChanged(object sender, EventArgs e) { - trnewPages.Visible = chkAllTabs.Checked; + this.trnewPages.Visible = this.chkAllTabs.Checked; } protected void OnCacheProviderIndexChanged(object sender, EventArgs e) { - ShowCacheRows(); + this.ShowCacheRows(); } - protected void OnDeleteClick(Object sender, EventArgs e) + protected void OnDeleteClick(object sender, EventArgs e) { try { - ModuleController.Instance.DeleteTabModule(TabId, _moduleId, true); - Response.Redirect(ReturnURL, true); + ModuleController.Instance.DeleteTabModule(this.TabId, this._moduleId, true); + this.Response.Redirect(this.ReturnURL, true); } catch (Exception exc) { @@ -519,146 +522,151 @@ protected void OnDeleteClick(Object sender, EventArgs e) } } - protected void OnInheritPermissionsChanged(Object sender, EventArgs e) + protected void OnInheritPermissionsChanged(object sender, EventArgs e) { - dgPermissions.InheritViewPermissionsFromTab = chkInheritPermissions.Checked; + this.dgPermissions.InheritViewPermissionsFromTab = this.chkInheritPermissions.Checked; } protected void OnUpdateClick(object sender, EventArgs e) { try { - if (Page.IsValid) + if (this.Page.IsValid) { var allTabsChanged = false; - //only Portal Administrators can manage the visibility on all Tabs - var isAdmin = PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); - chkAllModules.Enabled = isAdmin; + // only Portal Administrators can manage the visibility on all Tabs + var isAdmin = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); + this.chkAllModules.Enabled = isAdmin; - //tab administrators can only manage their own tab + // tab administrators can only manage their own tab if (!TabPermissionController.CanAdminPage()) { - chkAllTabs.Enabled = false; - chkNewTabs.Enabled = false; - chkDefault.Enabled = false; - chkAllowIndex.Enabled = false; - cboTab.Enabled = false; + this.chkAllTabs.Enabled = false; + this.chkNewTabs.Enabled = false; + this.chkDefault.Enabled = false; + this.chkAllowIndex.Enabled = false; + this.cboTab.Enabled = false; } - Module.ModuleID = _moduleId; - Module.ModuleTitle = txtTitle.Text; - Module.Alignment = cboAlign.SelectedItem.Value; - Module.Color = txtColor.Text; - Module.Border = txtBorder.Text; - Module.IconFile = ctlIcon.Url; - Module.CacheTime = !String.IsNullOrEmpty(txtCacheDuration.Text) - ? Int32.Parse(txtCacheDuration.Text) + + this.Module.ModuleID = this._moduleId; + this.Module.ModuleTitle = this.txtTitle.Text; + this.Module.Alignment = this.cboAlign.SelectedItem.Value; + this.Module.Color = this.txtColor.Text; + this.Module.Border = this.txtBorder.Text; + this.Module.IconFile = this.ctlIcon.Url; + this.Module.CacheTime = !string.IsNullOrEmpty(this.txtCacheDuration.Text) + ? int.Parse(this.txtCacheDuration.Text) : 0; - Module.CacheMethod = cboCacheProvider.SelectedValue; - Module.TabID = TabId; - if (Module.AllTabs != chkAllTabs.Checked) + this.Module.CacheMethod = this.cboCacheProvider.SelectedValue; + this.Module.TabID = this.TabId; + if (this.Module.AllTabs != this.chkAllTabs.Checked) { allTabsChanged = true; } - Module.AllTabs = chkAllTabs.Checked; + + this.Module.AllTabs = this.chkAllTabs.Checked; // collect these first as any settings update will clear the cache - var originalChecked = Settings["hideadminborder"] != null && bool.Parse(Settings["hideadminborder"].ToString()); - var allowIndex = GetBooleanSetting("AllowIndex", true); - var oldMoniker = ((string)Settings["Moniker"] ?? "").TrimToLength(100); - var newMoniker = txtMoniker.Text.TrimToLength(100); - if (!oldMoniker.Equals(txtMoniker.Text)) + var originalChecked = this.Settings["hideadminborder"] != null && bool.Parse(this.Settings["hideadminborder"].ToString()); + var allowIndex = this.GetBooleanSetting("AllowIndex", true); + var oldMoniker = ((string)this.Settings["Moniker"] ?? string.Empty).TrimToLength(100); + var newMoniker = this.txtMoniker.Text.TrimToLength(100); + if (!oldMoniker.Equals(this.txtMoniker.Text)) { var ids = TabModulesController.Instance.GetTabModuleIdsBySetting("Moniker", newMoniker); if (ids != null && ids.Count > 0) { - //Warn user - duplicate moniker value - Skin.AddModuleMessage(this, Localization.GetString("MonikerExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + // Warn user - duplicate moniker value + Skin.AddModuleMessage(this, Localization.GetString("MonikerExists", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "Moniker", newMoniker); + + ModuleController.Instance.UpdateTabModuleSetting(this.Module.TabModuleID, "Moniker", newMoniker); } - if (originalChecked != chkAdminBorder.Checked) + if (originalChecked != this.chkAdminBorder.Checked) { - ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "hideadminborder", chkAdminBorder.Checked.ToString()); + ModuleController.Instance.UpdateTabModuleSetting(this.Module.TabModuleID, "hideadminborder", this.chkAdminBorder.Checked.ToString()); } - //check whether allow index value is changed - if (allowIndex != chkAllowIndex.Checked) + // check whether allow index value is changed + if (allowIndex != this.chkAllowIndex.Checked) { - ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "AllowIndex", chkAllowIndex.Checked.ToString()); + ModuleController.Instance.UpdateTabModuleSetting(this.Module.TabModuleID, "AllowIndex", this.chkAllowIndex.Checked.ToString()); } - switch (Int32.Parse(cboVisibility.SelectedItem.Value)) + switch (int.Parse(this.cboVisibility.SelectedItem.Value)) { case 0: - Module.Visibility = VisibilityState.Maximized; + this.Module.Visibility = VisibilityState.Maximized; break; case 1: - Module.Visibility = VisibilityState.Minimized; + this.Module.Visibility = VisibilityState.Minimized; break; - //case 2: + + // case 2: default: - Module.Visibility = VisibilityState.None; + this.Module.Visibility = VisibilityState.None; break; } - Module.IsDeleted = false; - Module.Header = txtHeader.Text; - Module.Footer = txtFooter.Text; + this.Module.IsDeleted = false; + this.Module.Header = this.txtHeader.Text; + this.Module.Footer = this.txtFooter.Text; - Module.StartDate = startDatePicker.SelectedDate != null - ? startDatePicker.SelectedDate.Value + this.Module.StartDate = this.startDatePicker.SelectedDate != null + ? this.startDatePicker.SelectedDate.Value : Null.NullDate; - Module.EndDate = endDatePicker.SelectedDate != null - ? endDatePicker.SelectedDate.Value + this.Module.EndDate = this.endDatePicker.SelectedDate != null + ? this.endDatePicker.SelectedDate.Value : Null.NullDate; - Module.ContainerSrc = moduleContainerCombo.SelectedValue; - Module.ModulePermissions.Clear(); - Module.ModulePermissions.AddRange(dgPermissions.Permissions); - Module.Terms.Clear(); - Module.Terms.AddRange(termsSelector.Terms); + this.Module.ContainerSrc = this.moduleContainerCombo.SelectedValue; + this.Module.ModulePermissions.Clear(); + this.Module.ModulePermissions.AddRange(this.dgPermissions.Permissions); + this.Module.Terms.Clear(); + this.Module.Terms.AddRange(this.termsSelector.Terms); - if (!Module.IsShared) + if (!this.Module.IsShared) { - Module.InheritViewPermissions = chkInheritPermissions.Checked; - Module.IsShareable = isShareableCheckBox.Checked; - Module.IsShareableViewOnly = isShareableViewOnlyCheckBox.Checked; + this.Module.InheritViewPermissions = this.chkInheritPermissions.Checked; + this.Module.IsShareable = this.isShareableCheckBox.Checked; + this.Module.IsShareableViewOnly = this.isShareableViewOnlyCheckBox.Checked; } - Module.DisplayTitle = chkDisplayTitle.Checked; - Module.DisplayPrint = chkDisplayPrint.Checked; - Module.DisplaySyndicate = chkDisplaySyndicate.Checked; - Module.IsWebSlice = chkWebSlice.Checked; - Module.WebSliceTitle = txtWebSliceTitle.Text; + this.Module.DisplayTitle = this.chkDisplayTitle.Checked; + this.Module.DisplayPrint = this.chkDisplayPrint.Checked; + this.Module.DisplaySyndicate = this.chkDisplaySyndicate.Checked; + this.Module.IsWebSlice = this.chkWebSlice.Checked; + this.Module.WebSliceTitle = this.txtWebSliceTitle.Text; - Module.WebSliceExpiryDate = diWebSliceExpiry.SelectedDate != null - ? diWebSliceExpiry.SelectedDate.Value + this.Module.WebSliceExpiryDate = this.diWebSliceExpiry.SelectedDate != null + ? this.diWebSliceExpiry.SelectedDate.Value : Null.NullDate; - if (!string.IsNullOrEmpty(txtWebSliceTTL.Text)) + if (!string.IsNullOrEmpty(this.txtWebSliceTTL.Text)) { - Module.WebSliceTTL = Convert.ToInt32(txtWebSliceTTL.Text); + this.Module.WebSliceTTL = Convert.ToInt32(this.txtWebSliceTTL.Text); } - Module.IsDefaultModule = chkDefault.Checked; - Module.AllModules = chkAllModules.Checked; - ModuleController.Instance.UpdateModule(Module); - //Update Custom Settings - if (SettingsControl != null) + this.Module.IsDefaultModule = this.chkDefault.Checked; + this.Module.AllModules = this.chkAllModules.Checked; + ModuleController.Instance.UpdateModule(this.Module); + + // Update Custom Settings + if (this.SettingsControl != null) { try { - SettingsControl.UpdateSettings(); + this.SettingsControl.UpdateSettings(); } catch (ThreadAbortException exc) { Logger.Debug(exc); - Thread.ResetAbort(); //necessary + Thread.ResetAbort(); // necessary } catch (Exception ex) { @@ -666,43 +674,43 @@ protected void OnUpdateClick(object sender, EventArgs e) } } - //These Module Copy/Move statements must be - //at the end of the Update as the Controller code assumes all the - //Updates to the Module have been carried out. + // These Module Copy/Move statements must be + // at the end of the Update as the Controller code assumes all the + // Updates to the Module have been carried out. - //Check if the Module is to be Moved to a new Tab - if (!chkAllTabs.Checked) + // Check if the Module is to be Moved to a new Tab + if (!this.chkAllTabs.Checked) { - var newTabId = Int32.Parse(cboTab.SelectedValue); - if (TabId != newTabId) + var newTabId = int.Parse(this.cboTab.SelectedValue); + if (this.TabId != newTabId) { - //First check if there already is an instance of the module on the target page - var tmpModule = ModuleController.Instance.GetModule(_moduleId, newTabId, false); + // First check if there already is an instance of the module on the target page + var tmpModule = ModuleController.Instance.GetModule(this._moduleId, newTabId, false); if (tmpModule == null) { - //Move module - ModuleController.Instance.MoveModule(_moduleId, TabId, newTabId, Globals.glbDefaultPane); + // Move module + ModuleController.Instance.MoveModule(this._moduleId, this.TabId, newTabId, Globals.glbDefaultPane); } else { - //Warn user - Skin.AddModuleMessage(this, Localization.GetString("ModuleExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + // Warn user + Skin.AddModuleMessage(this, Localization.GetString("ModuleExists", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } } } - //Check if Module is to be Added/Removed from all Tabs + // Check if Module is to be Added/Removed from all Tabs if (allTabsChanged) { - var listTabs = TabController.GetPortalTabs(PortalSettings.PortalId, Null.NullInteger, false, true); - if (chkAllTabs.Checked) + var listTabs = TabController.GetPortalTabs(this.PortalSettings.PortalId, Null.NullInteger, false, true); + if (this.chkAllTabs.Checked) { - if (!chkNewTabs.Checked) + if (!this.chkNewTabs.Checked) { foreach (var destinationTab in listTabs) { - var module = ModuleController.Instance.GetModule(_moduleId, destinationTab.TabID, false); + var module = ModuleController.Instance.GetModule(this._moduleId, destinationTab.TabID, false); if (module != null) { if (module.IsDeleted) @@ -712,9 +720,9 @@ protected void OnUpdateClick(object sender, EventArgs e) } else { - if (!PortalSettings.ContentLocalizationEnabled || (Module.CultureCode == destinationTab.CultureCode)) + if (!this.PortalSettings.ContentLocalizationEnabled || (this.Module.CultureCode == destinationTab.CultureCode)) { - ModuleController.Instance.CopyModule(Module, destinationTab, Module.PaneName, true); + ModuleController.Instance.CopyModule(this.Module, destinationTab, this.Module.PaneName, true); } } } @@ -722,14 +730,14 @@ protected void OnUpdateClick(object sender, EventArgs e) } else { - ModuleController.Instance.DeleteAllModules(_moduleId, TabId, listTabs, true, false, false); + ModuleController.Instance.DeleteAllModules(this._moduleId, this.TabId, listTabs, true, false, false); } } - if (!DoNotRedirectOnUpdate) + if (!this.DoNotRedirectOnUpdate) { - //Navigate back to admin page - Response.Redirect(ReturnURL, true); + // Navigate back to admin page + this.Response.Redirect(this.ReturnURL, true); } } } @@ -741,17 +749,15 @@ protected void OnUpdateClick(object sender, EventArgs e) protected void OnWebSliceCheckChanged(object sender, EventArgs e) { - webSliceTitle.Visible = chkWebSlice.Checked; - webSliceExpiry.Visible = chkWebSlice.Checked; - webSliceTTL.Visible = chkWebSlice.Checked; + this.webSliceTitle.Visible = this.chkWebSlice.Checked; + this.webSliceExpiry.Visible = this.chkWebSlice.Checked; + this.webSliceTTL.Visible = this.chkWebSlice.Checked; } protected void dgOnTabs_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e) { - dgOnTabs.PageIndex = e.NewPageIndex; - BindModulePages(); + this.dgOnTabs.PageIndex = e.NewPageIndex; + this.BindModulePages(); } - - #endregion } } diff --git a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs index f7f178b9026..213e11bd8c2 100644 --- a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs +++ b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs @@ -1,40 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Modules { + using System; + using System.IO; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + public partial class ViewSource : PortalModuleBase { private readonly INavigationManager _navigationManager; + public ViewSource() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members - + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + protected bool CanEditSource { get { - return Request.IsLocal; + return this.Request.IsLocal; } } @@ -43,10 +37,11 @@ protected int ModuleControlId get { var moduleControlId = Null.NullInteger; - if ((Request.QueryString["ctlid"] != null)) + if (this.Request.QueryString["ctlid"] != null) { - moduleControlId = Int32.Parse(Request.QueryString["ctlid"]); + moduleControlId = int.Parse(this.Request.QueryString["ctlid"]); } + return moduleControlId; } } @@ -55,42 +50,76 @@ private string ReturnURL { get { - return UrlUtils.ValidReturnUrl(Request.Params["ReturnURL"]) ?? _navigationManager.NavigateURL(); + return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } - } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); - #endregion + this.cboFile.SelectedIndexChanged += this.OnFileIndexChanged; + this.cmdUpdate.Click += this.OnUpdateClick; - #region Private Methods + if (this.Page.IsPostBack == false) + { + this.cmdCancel.NavigateUrl = this.ReturnURL; + + var objModuleControl = ModuleControlController.GetModuleControl(this.ModuleControlId); + if (objModuleControl != null) + { + this.BindFiles(objModuleControl.ControlSrc); + } + + if (this.Request.UrlReferrer != null) + { + this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); + } + else + { + this.ViewState["UrlReferrer"] = string.Empty; + } + } + + this.cmdUpdate.Visible = this.CanEditSource; + this.txtSource.Enabled = this.CanEditSource; + } + protected void OnFileIndexChanged(object sender, EventArgs e) + { + this.DisplayFile(); + } + private void BindFiles(string controlSrc) { - cboFile.Items.Clear(); - //cboFile.Items.Add(new ListItem(Localization.GetString("None_Specified"), "None")); - //cboFile.Items.Add(new ListItem("User Control", "UserControl")); - cboFile.AddItem(Localization.GetString("None_Specified"), "None"); - cboFile.AddItem("User Control", "UserControl"); - - var srcPhysicalPath = Server.MapPath(controlSrc); + this.cboFile.Items.Clear(); + + // cboFile.Items.Add(new ListItem(Localization.GetString("None_Specified"), "None")); + // cboFile.Items.Add(new ListItem("User Control", "UserControl")); + this.cboFile.AddItem(Localization.GetString("None_Specified"), "None"); + this.cboFile.AddItem("User Control", "UserControl"); + + var srcPhysicalPath = this.Server.MapPath(controlSrc); if (File.Exists(srcPhysicalPath + ".vb") || File.Exists(srcPhysicalPath + ".cs")) { - //cboFile.Items.Add(new ListItem("Code File", "CodeFile")); - cboFile.AddItem("Code File", "CodeFile"); + // cboFile.Items.Add(new ListItem("Code File", "CodeFile")); + this.cboFile.AddItem("Code File", "CodeFile"); } + var fileName = Path.GetFileName(srcPhysicalPath); var folder = Path.GetDirectoryName(srcPhysicalPath); if (File.Exists(folder + "\\App_LocalResources\\" + fileName + ".resx")) { - //cboFile.Items.Add(new ListItem("Resource File", "ResourceFile")); - cboFile.AddItem("Resource File", "ResourceFile"); + // cboFile.Items.Add(new ListItem("Resource File", "ResourceFile")); + this.cboFile.AddItem("Resource File", "ResourceFile"); } } private string GetSourceFileName(string controlSrc) { - var srcPhysicalPath = Server.MapPath(controlSrc); + var srcPhysicalPath = this.Server.MapPath(controlSrc); var srcFile = Null.NullString; - switch (cboFile.SelectedValue) + switch (this.cboFile.SelectedValue) { case "UserControl": srcFile = srcPhysicalPath; @@ -104,6 +133,7 @@ private string GetSourceFileName(string controlSrc) { srcFile = srcPhysicalPath + ".cs"; } + break; case "ResourceFile": var fileName = Path.GetFileName(srcPhysicalPath); @@ -111,104 +141,66 @@ private string GetSourceFileName(string controlSrc) srcFile = folder + "\\App_LocalResources\\" + fileName + ".resx"; break; } + return srcFile; } private void DisplayFile() { - var objModuleControl = ModuleControlController.GetModuleControl(ModuleControlId); + var objModuleControl = ModuleControlController.GetModuleControl(this.ModuleControlId); if (objModuleControl != null) { var srcVirtualPath = objModuleControl.ControlSrc; var srcFile = Null.NullString; - var displaySource = cboFile.SelectedValue != "None"; + var displaySource = this.cboFile.SelectedValue != "None"; if (displaySource) { - srcFile = GetSourceFileName(srcVirtualPath); - lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", LocalResourceFile), srcFile); + srcFile = this.GetSourceFileName(srcVirtualPath); + this.lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", this.LocalResourceFile), srcFile); var objStreamReader = File.OpenText(srcFile); - txtSource.Text = objStreamReader.ReadToEnd(); + this.txtSource.Text = objStreamReader.ReadToEnd(); objStreamReader.Close(); } - lblSourceFile.Visible = displaySource; - trSource.Visible = displaySource; + + this.lblSourceFile.Visible = displaySource; + this.trSource.Visible = displaySource; } - } - - #endregion - - #region Event Handlers - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cboFile.SelectedIndexChanged += OnFileIndexChanged; - cmdUpdate.Click += OnUpdateClick; - - if (Page.IsPostBack == false) - { - cmdCancel.NavigateUrl = ReturnURL; - - var objModuleControl = ModuleControlController.GetModuleControl(ModuleControlId); - if (objModuleControl != null) - { - BindFiles(objModuleControl.ControlSrc); - } - if (Request.UrlReferrer != null) - { - ViewState["UrlReferrer"] = Convert.ToString(Request.UrlReferrer); - } - else - { - ViewState["UrlReferrer"] = ""; - } - } - cmdUpdate.Visible = CanEditSource; - txtSource.Enabled = CanEditSource; - } - - protected void OnFileIndexChanged(object sender, EventArgs e) - { - DisplayFile(); - } + } private void OnUpdateClick(object sender, EventArgs e) { try { - if (cboFile.SelectedValue == "None") + if (this.cboFile.SelectedValue == "None") { - //No file type selected - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoFileTypeSelected", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + // No file type selected + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoFileTypeSelected", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } else { - var objModuleControl = ModuleControlController.GetModuleControl(ModuleControlId); + var objModuleControl = ModuleControlController.GetModuleControl(this.ModuleControlId); if (objModuleControl != null) { var srcVirtualPath = objModuleControl.ControlSrc; - var srcPhysicalPath = GetSourceFileName(srcVirtualPath); + var srcPhysicalPath = this.GetSourceFileName(srcVirtualPath); if (File.Exists(srcPhysicalPath)) { File.SetAttributes(srcPhysicalPath, FileAttributes.Normal); var objStream = File.CreateText(srcPhysicalPath); - objStream.WriteLine(txtSource.Text); + objStream.WriteLine(this.txtSource.Text); objStream.Close(); } } - Response.Redirect(ReturnURL, true); + + this.Response.Redirect(this.ReturnURL, true); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion - + } } } diff --git a/DNN Platform/Website/admin/Portal/App_LocalResources/Privacy.ascx.resx b/DNN Platform/Website/admin/Portal/App_LocalResources/Privacy.ascx.resx index 171318c3b90..24a81a8610a 100644 --- a/DNN Platform/Website/admin/Portal/App_LocalResources/Privacy.ascx.resx +++ b/DNN Platform/Website/admin/Portal/App_LocalResources/Privacy.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Portal/App_LocalResources/Terms.ascx.resx b/DNN Platform/Website/admin/Portal/App_LocalResources/Terms.ascx.resx index 344f4b8245a..ab8137f6dec 100644 --- a/DNN Platform/Website/admin/Portal/App_LocalResources/Terms.ascx.resx +++ b/DNN Platform/Website/admin/Portal/App_LocalResources/Terms.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Portal/Message.ascx.cs b/DNN Platform/Website/admin/Portal/Message.ascx.cs index ae136884b10..65a2abae9f4 100644 --- a/DNN Platform/Website/admin/Portal/Message.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Message.ascx.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Controls { + using System; + + using DotNetNuke.Entities.Modules; + public partial class Message : PortalModuleBase { - private void InitializeComponent() - { - ID = "Message"; - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); + } + + private void InitializeComponent() + { + this.ID = "Message"; } } } diff --git a/DNN Platform/Website/admin/Portal/NoContent.ascx.cs b/DNN Platform/Website/admin/Portal/NoContent.ascx.cs index 2637491806f..efd08db0c6a 100644 --- a/DNN Platform/Website/admin/Portal/NoContent.ascx.cs +++ b/DNN Platform/Website/admin/Portal/NoContent.ascx.cs @@ -1,28 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Modules; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Controls { + using System; + + using DotNetNuke.Entities.Modules; + public partial class NoContent : PortalModuleBase { - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); + } + + private void InitializeComponent() + { } } } diff --git a/DNN Platform/Website/admin/Portal/Privacy.ascx.cs b/DNN Platform/Website/admin/Portal/Privacy.ascx.cs index bf5a7a2f334..9deb5d665e0 100644 --- a/DNN Platform/Website/admin/Portal/Privacy.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Privacy.ascx.cs @@ -1,72 +1,58 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Controls { - /// ----------------------------------------------------------------------------- - /// - /// The Privacy PortalModuleBase displays the Privacy text - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- + using System; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + + /// ----------------------------------------------------------------------------- + /// + /// The Privacy PortalModuleBase displays the Privacy text. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- public partial class Privacy : PortalModuleBase - { - #region " Web Form Designer Generated Code " - - private void InitializeComponent() - { - } - - #endregion - - #region "Event Handlers" - + { protected override void OnInit(EventArgs e) { base.OnInit(e); - //CODEGEN: This method call is required by the Web Form Designer - //Do not modify it using the code editor. - InitializeComponent(); + // CODEGEN: This method call is required by the Web Form Designer + // Do not modify it using the code editor. + this.InitializeComponent(); } - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + /// ----------------------------------------------------------------------------- protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - lblPrivacy.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_PORTAL_PRIVACY"); + this.lblPrivacy.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_PORTAL_PRIVACY"); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - #endregion + } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Portal/Terms.ascx.cs b/DNN Platform/Website/admin/Portal/Terms.ascx.cs index 6004418b2f8..3127e83a9a5 100644 --- a/DNN Platform/Website/admin/Portal/Terms.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Terms.ascx.cs @@ -1,55 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Common.Controls { + using System; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + public partial class Terms : PortalModuleBase - { - #region " Web Form Designer Generated Code " - - //This call is required by the Web Form Designer. - private void InitializeComponent() - { - } - - #endregion - + { protected override void OnInit(EventArgs e) { base.OnInit(e); - - - //CODEGEN: This method call is required by the Web Form Designer - //Do not modify it using the code editor. - InitializeComponent(); + + // CODEGEN: This method call is required by the Web Form Designer + // Do not modify it using the code editor. + this.InitializeComponent(); } - /// The Page_Load server event handler on this page is used to populate the role information for the page - protected override void OnLoad(EventArgs e) + /// The Page_Load server event handler on this page is used to populate the role information for the page. + protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { - if (!Page.IsPostBack) + if (!this.Page.IsPostBack) { - lblTerms.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_PORTAL_TERMS"); + this.lblTerms.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_PORTAL_TERMS"); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } + + // This call is required by the Web Form Designer. + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs b/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs index eba13430dcc..40166311cf9 100644 --- a/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs +++ b/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs @@ -1,43 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Net; -using System.Web; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Log.EventLog; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Sales { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Net; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; + using Host = DotNetNuke.Entities.Host.Host; - + public partial class PayPalIPN : PageBase { - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) @@ -45,23 +36,26 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - bool blnValid = true; -// string strTransactionID; + bool blnValid = true; + + // string strTransactionID; int intRoleID = 0; - int intPortalID = PortalSettings.PortalId; - int intUserID = 0; -// string strDescription; - double dblAmount = 0; -// string strEmail; + int intPortalID = this.PortalSettings.PortalId; + int intUserID = 0; + + // string strDescription; + double dblAmount = 0; + + // string strEmail; bool blnCancel = false; string strPayPalID = Null.NullString; string strPost = "cmd=_notify-validate"; - foreach (string strName in Request.Form) + foreach (string strName in this.Request.Form) { - string strValue = Request.Form[strName]; + string strValue = this.Request.Form[strName]; switch (strName) { - case "txn_type": //get the transaction type + case "txn_type": // get the transaction type string strTransactionType = strValue; switch (strTransactionType) { @@ -76,49 +70,52 @@ protected override void OnLoad(EventArgs e) blnValid = false; break; } + break; - case "payment_status": //verify the status + case "payment_status": // verify the status if (strValue != "Completed") { blnValid = false; } + break; - case "txn_id": //verify the transaction id for duplicates -// strTransactionID = strValue; + case "txn_id": // verify the transaction id for duplicates + // strTransactionID = strValue; break; - case "receiver_email": //verify the PayPalId + case "receiver_email": // verify the PayPalId strPayPalID = strValue; break; case "mc_gross": // verify the price dblAmount = double.Parse(strValue); break; - case "item_number": //get the RoleID - intRoleID = Int32.Parse(strValue); - //RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID); + case "item_number": // get the RoleID + intRoleID = int.Parse(strValue); + + // RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID); break; - case "item_name": //get the product description -// strDescription = strValue; + case "item_name": // get the product description + // strDescription = strValue; break; - case "custom": //get the UserID - intUserID = Int32.Parse(strValue); + case "custom": // get the UserID + intUserID = int.Parse(strValue); break; - case "email": //get the email -// strEmail = strValue; + case "email": // get the email + // strEmail = strValue; break; } - - //reconstruct post for postback validation - strPost += string.Format("&{0}={1}", Globals.HTTPPOSTEncode(strName), Globals.HTTPPOSTEncode(strValue)); + + // reconstruct post for postback validation + strPost += string.Format("&{0}={1}", Globals.HTTPPOSTEncode(strName), Globals.HTTPPOSTEncode(strValue)); } - - //postback to verify the source - if (blnValid) + + // postback to verify the source + if (blnValid) { - Dictionary settings = PortalController.Instance.GetPortalSettings(PortalSettings.PortalId); + Dictionary settings = PortalController.Instance.GetPortalSettings(this.PortalSettings.PortalId); string strPayPalURL; // Sandbox mode - if (settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"].Equals("true", StringComparison.InvariantCultureIgnoreCase)) + if (settings.ContainsKey("paypalsandbox") && !string.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"].Equals("true", StringComparison.InvariantCultureIgnoreCase)) { strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?"; } @@ -126,6 +123,7 @@ protected override void OnLoad(EventArgs e) { strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?"; } + var objRequest = Globals.GetExternalRequest(strPayPalURL); objRequest.Method = "POST"; objRequest.ContentLength = strPost.Length; @@ -136,23 +134,25 @@ protected override void OnLoad(EventArgs e) } string strResponse; - using (var objResponse = (HttpWebResponse) objRequest.GetResponse()) + using (var objResponse = (HttpWebResponse)objRequest.GetResponse()) { using (var sr = new StreamReader(objResponse.GetResponseStream())) { strResponse = sr.ReadToEnd(); } } + switch (strResponse) { case "VERIFIED": break; default: - //possible fraud - blnValid = false; + // possible fraud + blnValid = false; break; } } + if (blnValid) { int intAdministratorRoleId = 0; @@ -166,7 +166,7 @@ protected override void OnLoad(EventArgs e) if (intRoleID == intAdministratorRoleId) { - //admin portal renewal + // admin portal renewal strProcessorID = Host.ProcessorUserId.ToLowerInvariant(); float portalPrice = objPortalInfo.HostFee; if ((portalPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLowerInvariant()) == strProcessorID)) @@ -178,16 +178,16 @@ protected override void OnLoad(EventArgs e) var log = new LogInfo { LogPortalID = intPortalID, - LogPortalName = PortalSettings.PortalName, + LogPortalName = this.PortalSettings.PortalName, LogUserID = intUserID, - LogTypeKey = EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString() + LogTypeKey = EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString(), }; LogController.Instance.AddLog(log); } } else { - //user subscription + // user subscription RoleInfo objRoleInfo = RoleController.Instance.GetRole(intPortalID, r => r.RoleID == intRoleID); float rolePrice = objRoleInfo.ServiceFee; float trialPrice = objRoleInfo.TrialFee; @@ -200,19 +200,23 @@ protected override void OnLoad(EventArgs e) var log = new LogInfo { LogPortalID = intPortalID, - LogPortalName = PortalSettings.PortalName, + LogPortalName = this.PortalSettings.PortalName, LogUserID = intUserID, - LogTypeKey = EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString() + LogTypeKey = EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString(), }; LogController.Instance.AddLog(log); } } } } - catch (Exception exc) //Page failed to load + catch (Exception exc) // Page failed to load { Exceptions.ProcessPageLoadException(exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs b/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs index c5e6af6f7ec..3320a5bb366 100644 --- a/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs +++ b/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs @@ -1,39 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; - -using DotNetNuke.Common; -using DotNetNuke.Common.Lists; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Sales { + using System; + using System.Collections.Generic; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + public partial class PayPalSubscription : PageBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (PayPalSubscription)); - private void InitializeComponent() - { - } + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PayPalSubscription)); protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) @@ -43,7 +35,7 @@ protected override void OnLoad(EventArgs e) { UserInfo objUserInfo = null; int intUserID = -1; - if (Request.IsAuthenticated) + if (this.Request.IsAuthenticated) { objUserInfo = UserController.Instance.GetCurrentUserInfo(); if (objUserInfo != null) @@ -51,23 +43,26 @@ protected override void OnLoad(EventArgs e) intUserID = objUserInfo.UserID; } } + int intRoleId = -1; - if (Request.QueryString["roleid"] != null) + if (this.Request.QueryString["roleid"] != null) { - intRoleId = int.Parse(Request.QueryString["roleid"]); + intRoleId = int.Parse(this.Request.QueryString["roleid"]); } - string strProcessorUserId = ""; - PortalInfo objPortalInfo = PortalController.Instance.GetPortal(PortalSettings.PortalId); + + string strProcessorUserId = string.Empty; + PortalInfo objPortalInfo = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); if (objPortalInfo != null) { strProcessorUserId = objPortalInfo.ProcessorUserId; } - Dictionary settings = PortalController.Instance.GetPortalSettings(PortalSettings.PortalId); + + Dictionary settings = PortalController.Instance.GetPortalSettings(this.PortalSettings.PortalId); string strPayPalURL; - if (intUserID != -1 && intRoleId != -1 && !String.IsNullOrEmpty(strProcessorUserId)) + if (intUserID != -1 && intRoleId != -1 && !string.IsNullOrEmpty(strProcessorUserId)) { // Sandbox mode - if (settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"].ToLowerInvariant() == "true") + if (settings.ContainsKey("paypalsandbox") && !string.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"].ToLowerInvariant() == "true") { strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?"; } @@ -76,15 +71,15 @@ protected override void OnLoad(EventArgs e) strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?"; } - if (Request.QueryString["cancel"] != null) + if (this.Request.QueryString["cancel"] != null) { - //build the cancellation PayPal URL + // build the cancellation PayPal URL strPayPalURL += "cmd=_subscr-find&alias=" + Globals.HTTPPOSTEncode(strProcessorUserId); } else { strPayPalURL += "cmd=_ext-enter"; - RoleInfo objRole = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == intRoleId); + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == intRoleId); if (objRole.RoleID != -1) { int intTrialPeriod = 1; @@ -92,36 +87,37 @@ protected override void OnLoad(EventArgs e) { intTrialPeriod = objRole.TrialPeriod; } + int intBillingPeriod = 1; if (objRole.BillingPeriod != 0) { intBillingPeriod = objRole.BillingPeriod; } - - //explicitely format numbers using en-US so numbers are correctly built + + // explicitely format numbers using en-US so numbers are correctly built var enFormat = new CultureInfo("en-US"); string strService = string.Format(enFormat.NumberFormat, "{0:#####0.00}", objRole.ServiceFee); string strTrial = string.Format(enFormat.NumberFormat, "{0:#####0.00}", objRole.TrialFee); if (objRole.BillingFrequency == "O" || objRole.TrialFrequency == "O") { - //build the payment PayPal URL + // build the payment PayPal URL strPayPalURL += "&redirect_cmd=_xclick&business=" + Globals.HTTPPOSTEncode(strProcessorUserId); strPayPalURL += "&item_name=" + - Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " + - PortalSettings.Currency + " )"); + Globals.HTTPPOSTEncode(this.PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " + + this.PortalSettings.Currency + " )"); strPayPalURL += "&item_number=" + Globals.HTTPPOSTEncode(intRoleId.ToString()); strPayPalURL += "&no_shipping=1&no_note=1"; strPayPalURL += "&quantity=1"; strPayPalURL += "&amount=" + Globals.HTTPPOSTEncode(strService); - strPayPalURL += "¤cy_code=" + Globals.HTTPPOSTEncode(PortalSettings.Currency); + strPayPalURL += "¤cy_code=" + Globals.HTTPPOSTEncode(this.PortalSettings.Currency); } - else //recurring payments + else // recurring payments { - //build the subscription PayPal URL + // build the subscription PayPal URL strPayPalURL += "&redirect_cmd=_xclick-subscriptions&business=" + Globals.HTTPPOSTEncode(strProcessorUserId); strPayPalURL += "&item_name=" + - Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " + - PortalSettings.Currency + " every " + intBillingPeriod + " " + GetBillingFrequencyText(objRole.BillingFrequency) + " )"); + Globals.HTTPPOSTEncode(this.PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " + + this.PortalSettings.Currency + " every " + intBillingPeriod + " " + this.GetBillingFrequencyText(objRole.BillingFrequency) + " )"); strPayPalURL += "&item_number=" + Globals.HTTPPOSTEncode(intRoleId.ToString()); strPayPalURL += "&no_shipping=1&no_note=1"; if (objRole.TrialFrequency != "N") @@ -130,13 +126,15 @@ protected override void OnLoad(EventArgs e) strPayPalURL += "&p1=" + Globals.HTTPPOSTEncode(intTrialPeriod.ToString()); strPayPalURL += "&t1=" + Globals.HTTPPOSTEncode(objRole.TrialFrequency); } + strPayPalURL += "&a3=" + Globals.HTTPPOSTEncode(strService); strPayPalURL += "&p3=" + Globals.HTTPPOSTEncode(intBillingPeriod.ToString()); strPayPalURL += "&t3=" + Globals.HTTPPOSTEncode(objRole.BillingFrequency); strPayPalURL += "&src=1"; - strPayPalURL += "¤cy_code=" + Globals.HTTPPOSTEncode(PortalSettings.Currency); + strPayPalURL += "¤cy_code=" + Globals.HTTPPOSTEncode(this.PortalSettings.Currency); } } + var ctlList = new ListController(); strPayPalURL += "&custom=" + Globals.HTTPPOSTEncode(intUserID.ToString()); @@ -148,80 +146,85 @@ protected override void OnLoad(EventArgs e) { ListEntryInfo colList = ctlList.GetListEntryInfo("Region", objUserInfo.Profile.Region); strPayPalURL += "&address1=" + - Globals.HTTPPOSTEncode(Convert.ToString(!String.IsNullOrEmpty(objUserInfo.Profile.Unit) ? objUserInfo.Profile.Unit + " " : "") + + Globals.HTTPPOSTEncode(Convert.ToString(!string.IsNullOrEmpty(objUserInfo.Profile.Unit) ? objUserInfo.Profile.Unit + " " : string.Empty) + objUserInfo.Profile.Street); strPayPalURL += "&city=" + Globals.HTTPPOSTEncode(objUserInfo.Profile.City); strPayPalURL += "&state=" + Globals.HTTPPOSTEncode(colList.Value); strPayPalURL += "&zip=" + Globals.HTTPPOSTEncode(objUserInfo.Profile.PostalCode); } } - catch (Exception ex) - { - //issue getting user address - Logger.Error(ex); - } - - //Return URL + catch (Exception ex) + { + // issue getting user address + Logger.Error(ex); + } + + // Return URL if (settings.ContainsKey("paypalsubscriptionreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptionreturn"])) { strPayPalURL += "&return=" + Globals.HTTPPOSTEncode(settings["paypalsubscriptionreturn"]); } else { - strPayPalURL += "&return=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(Request))); + strPayPalURL += "&return=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(this.Request))); } - - //Cancellation URL + + // Cancellation URL if (settings.ContainsKey("paypalsubscriptioncancelreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptioncancelreturn"])) { strPayPalURL += "&cancel_return=" + Globals.HTTPPOSTEncode(settings["paypalsubscriptioncancelreturn"]); } else { - strPayPalURL += "&cancel_return=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(Request))); + strPayPalURL += "&cancel_return=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(this.Request))); } - - //Instant Payment Notification URL + + // Instant Payment Notification URL if (settings.ContainsKey("paypalsubscriptionnotifyurl") && !string.IsNullOrEmpty(settings["paypalsubscriptionnotifyurl"])) { strPayPalURL += "¬ify_url=" + Globals.HTTPPOSTEncode(settings["paypalsubscriptionnotifyurl"]); } else { - strPayPalURL += "¬ify_url=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(Request)) + "/admin/Sales/PayPalIPN.aspx"); + strPayPalURL += "¬ify_url=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(this.Request)) + "/admin/Sales/PayPalIPN.aspx"); } - strPayPalURL += "&sra=1"; //reattempt on failure + + strPayPalURL += "&sra=1"; // reattempt on failure } - - //redirect to PayPal - Response.Redirect(strPayPalURL, true); + + // redirect to PayPal + this.Response.Redirect(strPayPalURL, true); } else { - if ((settings.ContainsKey("paypalsubscriptioncancelreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptioncancelreturn"]))) + if (settings.ContainsKey("paypalsubscriptioncancelreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptioncancelreturn"])) { strPayPalURL = settings["paypalsubscriptioncancelreturn"]; } else { - strPayPalURL = Globals.AddHTTP(Globals.GetDomainName(Request)); + strPayPalURL = Globals.AddHTTP(Globals.GetDomainName(this.Request)); } - - //redirect to PayPal - Response.Redirect(strPayPalURL, true); + + // redirect to PayPal + this.Response.Redirect(strPayPalURL, true); } } - catch (Exception exc) //Page failed to load + catch (Exception exc) // Page failed to load { Exceptions.ProcessPageLoadException(exc); } } + + private void InitializeComponent() + { + } /// - /// This methods return the text description of the Frequency value + /// This methods return the text description of the Frequency value. /// - /// value of the Frequency - /// text of the Frequency + /// value of the Frequency. + /// text of the Frequency. private string GetBillingFrequencyText(string value) { var ctlEntry = new ListController(); diff --git a/DNN Platform/Website/admin/Sales/Purchase.ascx.cs b/DNN Platform/Website/admin/Sales/Purchase.ascx.cs index 7143df23b09..b989b870563 100644 --- a/DNN Platform/Website/admin/Sales/Purchase.ascx.cs +++ b/DNN Platform/Website/admin/Sales/Purchase.ascx.cs @@ -1,31 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Net; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Lists; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Roles; -using DotNetNuke.Security.Roles.Internal; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Sales { + using System; + using System.IO; + using System.Net; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Roles; + using DotNetNuke.Security.Roles.Internal; + using DotNetNuke.Services.Exceptions; + using Microsoft.Extensions.DependencyInjection; + using Host = DotNetNuke.Entities.Host.Host; - + public partial class Purchase : PortalModuleBase { private readonly INavigationManager _navigationManager; @@ -33,164 +28,171 @@ public partial class Purchase : PortalModuleBase public Purchase() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - private void InitializeComponent() - { + this._navigationManager = this.DependencyProvider.GetRequiredService(); } protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdPurchase.Click += cmdPurchase_Click; - cmdCancel.Click += cmdCancel_Click; + this.cmdPurchase.Click += this.cmdPurchase_Click; + this.cmdCancel.Click += this.cmdCancel_Click; try { double dblTotal; string strCurrency; - if ((Request.QueryString["RoleID"] != null)) + if (this.Request.QueryString["RoleID"] != null) { - RoleID = Int32.Parse(Request.QueryString["RoleID"]); + this.RoleID = int.Parse(this.Request.QueryString["RoleID"]); } - if (Page.IsPostBack == false) + + if (this.Page.IsPostBack == false) { - if (RoleID != -1) + if (this.RoleID != -1) { - RoleInfo objRole = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == RoleID); + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == this.RoleID); if (objRole.RoleID != -1) { - lblServiceName.Text = objRole.RoleName; + this.lblServiceName.Text = objRole.RoleName; if (!Null.IsNull(objRole.Description)) { - lblDescription.Text = objRole.Description; + this.lblDescription.Text = objRole.Description; } - if (RoleID == PortalSettings.AdministratorRoleId) + + if (this.RoleID == this.PortalSettings.AdministratorRoleId) { - if (!Null.IsNull(PortalSettings.HostFee)) + if (!Null.IsNull(this.PortalSettings.HostFee)) { - lblFee.Text = PortalSettings.HostFee.ToString("#,##0.00"); + this.lblFee.Text = this.PortalSettings.HostFee.ToString("#,##0.00"); } } else { if (!Null.IsNull(objRole.ServiceFee)) { - lblFee.Text = objRole.ServiceFee.ToString("#,##0.00"); + this.lblFee.Text = objRole.ServiceFee.ToString("#,##0.00"); } } + if (!Null.IsNull(objRole.BillingFrequency)) { var ctlEntry = new ListController(); ListEntryInfo entry = ctlEntry.GetListEntryInfo("Frequency", objRole.BillingFrequency); - lblFrequency.Text = entry.Text; + this.lblFrequency.Text = entry.Text; } - txtUnits.Text = "1"; - if (objRole.BillingFrequency == "O") //one-time fee + + this.txtUnits.Text = "1"; + if (objRole.BillingFrequency == "O") // one-time fee { - txtUnits.Enabled = false; + this.txtUnits.Enabled = false; } } - else //security violation attempt to access item not related to this Module + else // security violation attempt to access item not related to this Module { - Response.Redirect(_navigationManager.NavigateURL(), true); + this.Response.Redirect(this._navigationManager.NavigateURL(), true); } } - //Store URL Referrer to return to portal - if (Request.UrlReferrer != null) + // Store URL Referrer to return to portal + if (this.Request.UrlReferrer != null) { - ViewState["UrlReferrer"] = Convert.ToString(Request.UrlReferrer); + this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); } else { - ViewState["UrlReferrer"] = ""; + this.ViewState["UrlReferrer"] = string.Empty; } } - if (RoleID == PortalSettings.AdministratorRoleId) + + if (this.RoleID == this.PortalSettings.AdministratorRoleId) { strCurrency = Host.HostCurrency; } else { - strCurrency = PortalSettings.Currency; + strCurrency = this.PortalSettings.Currency; } - dblTotal = Convert.ToDouble(lblFee.Text)*Convert.ToDouble(txtUnits.Text); - lblTotal.Text = dblTotal.ToString("#.##"); + + dblTotal = Convert.ToDouble(this.lblFee.Text) * Convert.ToDouble(this.txtUnits.Text); + this.lblTotal.Text = dblTotal.ToString("#.##"); - lblFeeCurrency.Text = strCurrency; - lblTotalCurrency.Text = strCurrency; + this.lblFeeCurrency.Text = strCurrency; + this.lblTotalCurrency.Text = strCurrency; } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } - private void cmdPurchase_Click(Object sender, EventArgs e) + private void InitializeComponent() + { + } + + private void cmdPurchase_Click(object sender, EventArgs e) { try { - string strPaymentProcessor = ""; - string strProcessorUserId = ""; - string strProcessorPassword = ""; + string strPaymentProcessor = string.Empty; + string strProcessorUserId = string.Empty; + string strProcessorPassword = string.Empty; - if (Page.IsValid) + if (this.Page.IsValid) { - PortalInfo objPortalInfo = PortalController.Instance.GetPortal(PortalSettings.PortalId); + PortalInfo objPortalInfo = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); if (objPortalInfo != null) { strPaymentProcessor = objPortalInfo.PaymentProcessor; strProcessorUserId = objPortalInfo.ProcessorUserId; strProcessorPassword = objPortalInfo.ProcessorPassword; } + if (strPaymentProcessor == "PayPal") { - //build secure PayPal URL - string strPayPalURL = ""; + // build secure PayPal URL + string strPayPalURL = string.Empty; strPayPalURL = "https://www.paypal.com/xclick/business=" + Globals.HTTPPOSTEncode(strProcessorUserId); strPayPalURL = strPayPalURL + "&item_name=" + - Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + lblDescription.Text + " ( " + txtUnits.Text + " units @ " + lblFee.Text + " " + lblFeeCurrency.Text + - " per " + lblFrequency.Text + " )"); - strPayPalURL = strPayPalURL + "&item_number=" + Globals.HTTPPOSTEncode(Convert.ToString(RoleID)); + Globals.HTTPPOSTEncode(this.PortalSettings.PortalName + " - " + this.lblDescription.Text + " ( " + this.txtUnits.Text + " units @ " + this.lblFee.Text + " " + this.lblFeeCurrency.Text + + " per " + this.lblFrequency.Text + " )"); + strPayPalURL = strPayPalURL + "&item_number=" + Globals.HTTPPOSTEncode(Convert.ToString(this.RoleID)); strPayPalURL = strPayPalURL + "&quantity=1"; - strPayPalURL = strPayPalURL + "&custom=" + Globals.HTTPPOSTEncode(UserInfo.UserID.ToString()); - strPayPalURL = strPayPalURL + "&amount=" + Globals.HTTPPOSTEncode(lblTotal.Text); - strPayPalURL = strPayPalURL + "¤cy_code=" + Globals.HTTPPOSTEncode(lblTotalCurrency.Text); - strPayPalURL = strPayPalURL + "&return=" + Globals.HTTPPOSTEncode("http://" + Globals.GetDomainName(Request)); - strPayPalURL = strPayPalURL + "&cancel_return=" + Globals.HTTPPOSTEncode("http://" + Globals.GetDomainName(Request)); - strPayPalURL = strPayPalURL + "¬ify_url=" + Globals.HTTPPOSTEncode("http://" + Globals.GetDomainName(Request) + "/admin/Sales/PayPalIPN.aspx"); + strPayPalURL = strPayPalURL + "&custom=" + Globals.HTTPPOSTEncode(this.UserInfo.UserID.ToString()); + strPayPalURL = strPayPalURL + "&amount=" + Globals.HTTPPOSTEncode(this.lblTotal.Text); + strPayPalURL = strPayPalURL + "¤cy_code=" + Globals.HTTPPOSTEncode(this.lblTotalCurrency.Text); + strPayPalURL = strPayPalURL + "&return=" + Globals.HTTPPOSTEncode("http://" + Globals.GetDomainName(this.Request)); + strPayPalURL = strPayPalURL + "&cancel_return=" + Globals.HTTPPOSTEncode("http://" + Globals.GetDomainName(this.Request)); + strPayPalURL = strPayPalURL + "¬ify_url=" + Globals.HTTPPOSTEncode("http://" + Globals.GetDomainName(this.Request) + "/admin/Sales/PayPalIPN.aspx"); strPayPalURL = strPayPalURL + "&undefined_quantity=&no_note=1&no_shipping=1"; - //redirect to PayPal - Response.Redirect(strPayPalURL, true); + // redirect to PayPal + this.Response.Redirect(strPayPalURL, true); } } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } - private void cmdCancel_Click(Object sender, EventArgs e) + private void cmdCancel_Click(object sender, EventArgs e) { try { - Response.Redirect(Convert.ToString(ViewState["UrlReferrer"]), true); + this.Response.Redirect(Convert.ToString(this.ViewState["UrlReferrer"]), true); } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } @@ -212,9 +214,8 @@ private double ConvertCurrency(string Amount, string FromCurrency, string ToCurr objStream.Write(strPost); objStream.Close(); } - - - var objResponse = (HttpWebResponse) objRequest.GetResponse(); + + var objResponse = (HttpWebResponse)objRequest.GetResponse(); using (var sr = new StreamReader(objResponse.GetResponseStream())) { string strResponse = sr.ReadToEnd(); @@ -224,10 +225,11 @@ private double ConvertCurrency(string Amount, string FromCurrency, string ToCurr retValue = Convert.ToDouble(strResponse.Substring(intPos2 + 3, (intPos1 - intPos2) - 4)); } } - catch (Exception exc) //Module failed to load + catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } + return retValue; } } diff --git a/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs b/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs index a0a836e0d61..a14757a2e34 100644 --- a/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs +++ b/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs @@ -1,20 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Security { + using System; + using System.Web; + + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + public partial class AccessDeniedPage : PortalModuleBase { protected override void OnLoad(EventArgs e) @@ -22,14 +18,15 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); string message = null; Guid messageGuid; - var guidText = Request.QueryString["message"]; + var guidText = this.Request.QueryString["message"]; if (!string.IsNullOrEmpty(guidText) && Guid.TryParse(guidText, out messageGuid)) { message = HttpUtility.HtmlEncode(DataProvider.Instance().GetRedirectMessage(messageGuid)); } - UI.Skins.Skin.AddModuleMessage(this, - !string.IsNullOrEmpty(message) ? message : Localization.GetString("AccessDenied", LocalResourceFile), + UI.Skins.Skin.AddModuleMessage( + this, + !string.IsNullOrEmpty(message) ? message : Localization.GetString("AccessDenied", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); } } diff --git a/DNN Platform/Website/admin/Security/App_LocalResources/AccessDenied.ascx.resx b/DNN Platform/Website/admin/Security/App_LocalResources/AccessDenied.ascx.resx index cceeb95f0e3..d39c05a4e5f 100644 --- a/DNN Platform/Website/admin/Security/App_LocalResources/AccessDenied.ascx.resx +++ b/DNN Platform/Website/admin/Security/App_LocalResources/AccessDenied.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Security/App_LocalResources/PasswordReset.ascx.resx b/DNN Platform/Website/admin/Security/App_LocalResources/PasswordReset.ascx.resx index fb73171cf87..564b24ec370 100644 --- a/DNN Platform/Website/admin/Security/App_LocalResources/PasswordReset.ascx.resx +++ b/DNN Platform/Website/admin/Security/App_LocalResources/PasswordReset.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Security/App_LocalResources/SendPassword.ascx.resx b/DNN Platform/Website/admin/Security/App_LocalResources/SendPassword.ascx.resx index 398c105d5c9..09d77e2a6ab 100644 --- a/DNN Platform/Website/admin/Security/App_LocalResources/SendPassword.ascx.resx +++ b/DNN Platform/Website/admin/Security/App_LocalResources/SendPassword.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs b/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs index d0357eac501..2e6e66abb38 100644 --- a/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs +++ b/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs @@ -1,352 +1,347 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using System.Web.UI; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users.Membership; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using DotNetNuke.Web.UI.WebControls; -using DotNetNuke.Services.UserRequest; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Security { - - + using System; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Membership; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.UserRequest; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.UI.WebControls; + using Microsoft.Extensions.DependencyInjection; + public partial class PasswordReset : UserModuleBase { + private const int RedirectTimeout = 3000; + private readonly INavigationManager _navigationManager; + private string _ipAddress; + public PasswordReset() { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members - - private const int RedirectTimeout = 3000; - private string _ipAddress; + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } private string ResetToken { get { - return ViewState["ResetToken"] != null ? Request.QueryString["resetToken"] : String.Empty; + return this.ViewState["ResetToken"] != null ? this.Request.QueryString["resetToken"] : string.Empty; } + set { - ViewState.Add("ResetToken", value); + this.ViewState.Add("ResetToken", value); } - } - - #endregion - - #region Event Handlers - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - _ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(Request)); + this._ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); - ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); - if (PortalSettings.LoginTabId != -1 && PortalSettings.ActiveTab.TabID != PortalSettings.LoginTabId) + if (this.PortalSettings.LoginTabId != -1 && this.PortalSettings.ActiveTab.TabID != this.PortalSettings.LoginTabId) { - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.LoginTabId) + Request.Url.Query); + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.LoginTabId) + this.Request.Url.Query); } - cmdChangePassword.Click +=cmdChangePassword_Click; + + this.cmdChangePassword.Click += this.cmdChangePassword_Click; - hlCancel.NavigateUrl = _navigationManager.NavigateURL(); + this.hlCancel.NavigateUrl = this._navigationManager.NavigateURL(); - if (Request.QueryString["resetToken"] != null) + if (this.Request.QueryString["resetToken"] != null) { - ResetToken = Request.QueryString["resetToken"]; - txtUsername.Enabled = false; + this.ResetToken = this.Request.QueryString["resetToken"]; + this.txtUsername.Enabled = false; + } + var useEmailAsUserName = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false); + if (useEmailAsUserName) + { + this.valUsername.Text = Localization.GetString("Email.Required", this.LocalResourceFile); } + else + { + this.valUsername.Text = Localization.GetString("Username.Required", this.LocalResourceFile); + } + + if (this.Request.QueryString["forced"] == "true") + { + this.lblInfo.Text = Localization.GetString("ForcedResetInfo", this.LocalResourceFile); + } + + this.txtUsername.Attributes.Add("data-default", useEmailAsUserName ? this.LocalizeString("Email") : this.LocalizeString("Username")); + this.txtPassword.Attributes.Add("data-default", this.LocalizeString("Password")); + this.txtConfirmPassword.Attributes.Add("data-default", this.LocalizeString("Confirm")); + this.txtAnswer.Attributes.Add("data-default", this.LocalizeString("Answer")); + + if (!this.Page.IsPostBack) + { + this.LoadUserInfo(); + } + } - var useEmailAsUserName = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false); - if (useEmailAsUserName) + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + if (!string.IsNullOrEmpty(this.lblHelp.Text) || !string.IsNullOrEmpty(this.lblInfo.Text)) + { + this.resetMessages.Visible = true; + } + + var options = new DnnPaswordStrengthOptions(); + var optionsAsJsonString = Json.Serialize(options); + var script = string.Format( + "dnn.initializePasswordStrength('.{0}', {1});{2}", + "password-strength", optionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) { - valUsername.Text = Localization.GetString("Email.Required", LocalResourceFile); + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "PasswordStrength", script, true); } else { - valUsername.Text = Localization.GetString("Username.Required", LocalResourceFile); + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PasswordStrength", script, true); } - if (Request.QueryString["forced"] == "true") + var confirmPasswordOptions = new DnnConfirmPasswordOptions() { - lblInfo.Text = Localization.GetString("ForcedResetInfo", LocalResourceFile); + FirstElementSelector = ".password-strength", + SecondElementSelector = ".password-confirm", + ContainerSelector = ".dnnPasswordReset", + UnmatchedCssClass = "unmatched", + MatchedCssClass = "matched", + }; + + optionsAsJsonString = Json.Serialize(confirmPasswordOptions); + script = string.Format("dnn.initializePasswordComparer({0});{1}", optionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ConfirmPassword", script, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmPassword", script, true); } + } - txtUsername.Attributes.Add("data-default",useEmailAsUserName ? LocalizeString("Email") : LocalizeString("Username")); - txtPassword.Attributes.Add("data-default", LocalizeString("Password")); - txtConfirmPassword.Attributes.Add("data-default", LocalizeString("Confirm")); - txtAnswer.Attributes.Add("data-default", LocalizeString("Answer")); + protected void RedirectAfterLogin() + { + var redirectURL = string.Empty; - if (!Page.IsPostBack) + var setting = GetSetting(this.PortalId, "Redirect_AfterLogin"); + + if (Convert.ToInt32(setting) == Null.NullInteger) { - LoadUserInfo(); + if (this.Request.QueryString["returnurl"] != null) + { + // return to the url passed to signin + redirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); + + // clean the return url to avoid possible XSS attack. + redirectURL = UrlUtils.ValidReturnUrl(redirectURL); + } + + if (this.Request.Cookies["returnurl"] != null) + { + // return to the url passed to signin + redirectURL = HttpUtility.UrlDecode(this.Request.Cookies["returnurl"].Value); + + // clean the return url to avoid possible XSS attack. + redirectURL = UrlUtils.ValidReturnUrl(redirectURL); + } + + if (string.IsNullOrEmpty(redirectURL)) + { + if (this.PortalSettings.RegisterTabId != -1 && this.PortalSettings.HomeTabId != -1) + { + // redirect to portal home page specified + redirectURL = this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId); + } + else + { + // redirect to current page + redirectURL = this._navigationManager.NavigateURL(); + } + } + } + else // redirect to after login page + { + redirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); + } + + this.AddModuleMessage("ChangeSuccessful", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.resetMessages.Visible = this.divPassword.Visible = false; + this.lblHelp.Text = this.lblInfo.Text = string.Empty; + + // redirect page after 5 seconds + var script = string.Format("setTimeout(function(){{location.href = '{0}';}}, {1});", redirectURL, RedirectTimeout); + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ChangePasswordSuccessful", script, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ChangePasswordSuccessful", script, true); } } private void LoadUserInfo() { - var user = UserController.GetUserByPasswordResetToken(PortalId, ResetToken); + var user = UserController.GetUserByPasswordResetToken(this.PortalId, this.ResetToken); if (user == null || user.PasswordResetExpiration < DateTime.Now) { - divPassword.Visible = false; - resetMessages.Visible = true; - lblHelp.Text = Localization.GetString("ResetLinkExpired", LocalResourceFile); + this.divPassword.Visible = false; + this.resetMessages.Visible = true; + this.lblHelp.Text = Localization.GetString("ResetLinkExpired", this.LocalResourceFile); return; } - txtUsername.Text = user.Username; + this.txtUsername.Text = user.Username; if (MembershipProviderConfig.RequiresQuestionAndAnswer) { - lblQuestion.Text = user.Membership.PasswordQuestion; - divQA.Visible = true; + this.lblQuestion.Text = user.Membership.PasswordQuestion; + this.divQA.Visible = true; } } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - if (!string.IsNullOrEmpty(lblHelp.Text) || !string.IsNullOrEmpty(lblInfo.Text)) - resetMessages.Visible = true; - - var options = new DnnPaswordStrengthOptions(); - var optionsAsJsonString = Json.Serialize(options); - var script = string.Format("dnn.initializePasswordStrength('.{0}', {1});{2}", - "password-strength", optionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "PasswordStrength", script, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "PasswordStrength", script, true); - } - - var confirmPasswordOptions = new DnnConfirmPasswordOptions() - { - FirstElementSelector = ".password-strength", - SecondElementSelector = ".password-confirm", - ContainerSelector = ".dnnPasswordReset", - UnmatchedCssClass = "unmatched", - MatchedCssClass = "matched" - }; - - optionsAsJsonString = Json.Serialize(confirmPasswordOptions); - script = string.Format("dnn.initializePasswordComparer({0});{1}", optionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "ConfirmPassword", script, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "ConfirmPassword", script, true); - } - } - private void cmdChangePassword_Click(object sender, EventArgs e) { - string username = txtUsername.Text; + string username = this.txtUsername.Text; - if (MembershipProviderConfig.RequiresQuestionAndAnswer && string.IsNullOrEmpty(txtAnswer.Text)) + if (MembershipProviderConfig.RequiresQuestionAndAnswer && string.IsNullOrEmpty(this.txtAnswer.Text)) { return; } - //1. Check New Password and Confirm are the same - if (txtPassword.Text != txtConfirmPassword.Text) + // 1. Check New Password and Confirm are the same + if (this.txtPassword.Text != this.txtConfirmPassword.Text) { - resetMessages.Visible = true; + this.resetMessages.Visible = true; var failed = Localization.GetString("PasswordMismatch"); - LogFailure(failed); - lblHelp.Text = failed; + this.LogFailure(failed); + this.lblHelp.Text = failed; return; } - var newPassword = txtPassword.Text.Trim(); - if (UserController.ValidatePassword(newPassword) ==false) + var newPassword = this.txtPassword.Text.Trim(); + if (UserController.ValidatePassword(newPassword) == false) { - resetMessages.Visible = true; + this.resetMessages.Visible = true; var failed = Localization.GetString("PasswordResetFailed"); - LogFailure(failed); - lblHelp.Text = failed; + this.LogFailure(failed); + this.lblHelp.Text = failed; return; } - //Check New Password is not same as username or banned - var settings = new MembershipPasswordSettings(User.PortalID); + // Check New Password is not same as username or banned + var settings = new MembershipPasswordSettings(this.User.PortalID); if (settings.EnableBannedList) { var m = new MembershipPasswordController(); - if (m.FoundBannedPassword(newPassword) || txtUsername.Text == newPassword) + if (m.FoundBannedPassword(newPassword) || this.txtUsername.Text == newPassword) { - resetMessages.Visible = true; + this.resetMessages.Visible = true; var failed = Localization.GetString("PasswordResetFailed"); - LogFailure(failed); - lblHelp.Text = failed; + this.LogFailure(failed); + this.lblHelp.Text = failed; return; } } - if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false)) + if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false)) { - var testUser = UserController.GetUserByEmail(PortalId, username); // one additonal call to db to see if an account with that email actually exists + var testUser = UserController.GetUserByEmail(this.PortalId, username); // one additonal call to db to see if an account with that email actually exists if (testUser != null) { - username = testUser.Username; //we need the username of the account in order to change the password in the next step + username = testUser.Username; // we need the username of the account in order to change the password in the next step } } + string errorMessage; - string answer = String.Empty; + string answer = string.Empty; if (MembershipProviderConfig.RequiresQuestionAndAnswer) { - answer = txtAnswer.Text; + answer = this.txtAnswer.Text; } - if (UserController.ChangePasswordByToken(PortalSettings.PortalId, username, newPassword, answer, ResetToken, out errorMessage) == false) + if (UserController.ChangePasswordByToken(this.PortalSettings.PortalId, username, newPassword, answer, this.ResetToken, out errorMessage) == false) { - resetMessages.Visible = true; + this.resetMessages.Visible = true; var failed = errorMessage; - LogFailure(failed); - lblHelp.Text = failed; + this.LogFailure(failed); + this.lblHelp.Text = failed; } else { - //check user has a valid profile - var user = UserController.GetUserByName(PortalSettings.PortalId, username); - var validStatus = UserController.ValidateUser(user, PortalSettings.PortalId, false); + // check user has a valid profile + var user = UserController.GetUserByName(this.PortalSettings.PortalId, username); + var validStatus = UserController.ValidateUser(user, this.PortalSettings.PortalId, false); if (validStatus == UserValidStatus.UPDATEPROFILE) { - LogSuccess(); - ViewState.Add("PageNo", 3); - Response.Redirect(_navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Login")); + this.LogSuccess(); + this.ViewState.Add("PageNo", 3); + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Login")); } else { - //Log user in to site - LogSuccess(); + // Log user in to site + this.LogSuccess(); var loginStatus = UserLoginStatus.LOGIN_FAILURE; - UserController.UserLogin(PortalSettings.PortalId, username, txtPassword.Text, "", "", "", ref loginStatus, false); - RedirectAfterLogin(); - } - } - } - - protected void RedirectAfterLogin() - { - var redirectURL = ""; - - var setting = GetSetting(PortalId, "Redirect_AfterLogin"); - - if (Convert.ToInt32(setting) == Null.NullInteger) - { - if (Request.QueryString["returnurl"] != null) - { - //return to the url passed to signin - redirectURL = HttpUtility.UrlDecode(Request.QueryString["returnurl"]); - - //clean the return url to avoid possible XSS attack. - redirectURL = UrlUtils.ValidReturnUrl(redirectURL); - } - - if (Request.Cookies["returnurl"] != null) - { - //return to the url passed to signin - redirectURL = HttpUtility.UrlDecode(Request.Cookies["returnurl"].Value); - - //clean the return url to avoid possible XSS attack. - redirectURL = UrlUtils.ValidReturnUrl(redirectURL); - } - if (String.IsNullOrEmpty(redirectURL)) - { - if (PortalSettings.RegisterTabId != -1 && PortalSettings.HomeTabId != -1) - { - //redirect to portal home page specified - redirectURL = _navigationManager.NavigateURL(PortalSettings.HomeTabId); - } - else - { - //redirect to current page - redirectURL = _navigationManager.NavigateURL(); - } + UserController.UserLogin(this.PortalSettings.PortalId, username, this.txtPassword.Text, string.Empty, string.Empty, string.Empty, ref loginStatus, false); + this.RedirectAfterLogin(); } } - else //redirect to after login page - { - redirectURL = _navigationManager.NavigateURL(Convert.ToInt32(setting)); - } - - AddModuleMessage("ChangeSuccessful", ModuleMessage.ModuleMessageType.GreenSuccess, true); - resetMessages.Visible = divPassword.Visible = false; - lblHelp.Text = lblInfo.Text = string.Empty; - - //redirect page after 5 seconds - var script = string.Format("setTimeout(function(){{location.href = '{0}';}}, {1});", redirectURL, RedirectTimeout); - if (ScriptManager.GetCurrent(Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(Page, GetType(), "ChangePasswordSuccessful", script, true); - } - else - { - Page.ClientScript.RegisterStartupScript(GetType(), "ChangePasswordSuccessful", script, true); - } } private void LogSuccess() { - LogResult(string.Empty); + this.LogResult(string.Empty); } private void LogFailure(string reason) { - LogResult(reason); + this.LogResult(reason); } private void LogResult(string message) { var log = new LogInfo { - LogPortalID = PortalSettings.PortalId, - LogPortalName = PortalSettings.PortalName, - LogUserID = UserId + LogPortalID = this.PortalSettings.PortalId, + LogPortalName = this.PortalSettings.PortalName, + LogUserID = this.UserId, }; if (string.IsNullOrEmpty(message)) @@ -358,12 +353,10 @@ private void LogResult(string message) log.LogTypeKey = "PASSWORD_SENT_FAILURE"; log.LogProperties.Add(new LogDetailInfo("Cause", message)); } - log.AddProperty("IP", _ipAddress); + + log.AddProperty("IP", this._ipAddress); LogController.Instance.AddLog(log); - } - - #endregion - + } } } diff --git a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs index 4e047d4021a..cf3deabed62 100644 --- a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs +++ b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs @@ -1,211 +1,173 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections; -using System.Web; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Entities.Users.Membership; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security; -using DotNetNuke.Security.Membership; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Mail; -using DotNetNuke.UI.Skins.Controls; -using DotNetNuke.Services.UserRequest; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Security { - + using System; + using System.Collections; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users.Membership; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Mail; + using DotNetNuke.Services.UserRequest; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + using Host = DotNetNuke.Entities.Host.Host; - + /// - /// The SendPassword UserModuleBase is used to allow a user to retrieve their password + /// The SendPassword UserModuleBase is used to allow a user to retrieve their password. /// /// /// public partial class SendPassword : UserModuleBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SendPassword)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SendPassword)); private readonly INavigationManager _navigationManager; - public SendPassword() - { - _navigationManager = DependencyProvider.GetRequiredService(); - } - - #region Private Members - + private UserInfo _user; private int _userCount = Null.NullInteger; - private string _ipAddress; - - #endregion - - #region Protected Properties - + private string _ipAddress; + + public SendPassword() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } + /// - /// Gets the Redirect URL (after successful sending of password) + /// Gets the Redirect URL (after successful sending of password). /// protected string RedirectURL { get { - var _RedirectURL = ""; + var _RedirectURL = string.Empty; - object setting = GetSetting(PortalId, "Redirect_AfterRegistration"); + object setting = GetSetting(this.PortalId, "Redirect_AfterRegistration"); - if (Convert.ToInt32(setting) > 0) //redirect to after registration page + if (Convert.ToInt32(setting) > 0) // redirect to after registration page { - _RedirectURL = _navigationManager.NavigateURL(Convert.ToInt32(setting)); + _RedirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); } else - { - - if (Convert.ToInt32(setting) <= 0) - { - if (Request.QueryString["returnurl"] != null) - { - //return to the url passed to register - _RedirectURL = HttpUtility.UrlDecode(Request.QueryString["returnurl"]); - - //clean the return url to avoid possible XSS attack. - _RedirectURL = UrlUtils.ValidReturnUrl(_RedirectURL); - - if (_RedirectURL.Contains("?returnurl")) - { - string baseURL = _RedirectURL.Substring(0, - _RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal)); - string returnURL = - _RedirectURL.Substring(_RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal) + 11); - - _RedirectURL = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); - } - } - if (String.IsNullOrEmpty(_RedirectURL)) - { - //redirect to current page - _RedirectURL = _navigationManager.NavigateURL(); + { + if (Convert.ToInt32(setting) <= 0) + { + if (this.Request.QueryString["returnurl"] != null) + { + // return to the url passed to register + _RedirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); + + // clean the return url to avoid possible XSS attack. + _RedirectURL = UrlUtils.ValidReturnUrl(_RedirectURL); + + if (_RedirectURL.Contains("?returnurl")) + { + string baseURL = _RedirectURL.Substring( + 0, + _RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal)); + string returnURL = + _RedirectURL.Substring(_RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal) + 11); + + _RedirectURL = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); + } + } + + if (string.IsNullOrEmpty(_RedirectURL)) + { + // redirect to current page + _RedirectURL = this._navigationManager.NavigateURL(); + } + } + else // redirect to after registration page + { + _RedirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); } } - else //redirect to after registration page - { - _RedirectURL = _navigationManager.NavigateURL(Convert.ToInt32(setting)); - } - } return _RedirectURL; } - - } + } /// - /// Gets whether the Captcha control is used to validate the login + /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. /// protected bool UseCaptcha { get { - var setting = GetSetting(PortalId, "Security_CaptchaRetrivePassword"); + var setting = GetSetting(this.PortalId, "Security_CaptchaRetrivePassword"); return Convert.ToBoolean(setting); } } - protected bool UsernameDisabled - { - get - { - return PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false); - } - } - - private bool ShowEmailField - { - get - { - return MembershipProviderConfig.RequiresUniqueEmail || UsernameDisabled; - } - } - - #endregion - - #region Private Methods - - private void GetUser() + protected bool UsernameDisabled { - ArrayList arrUsers; - if (ShowEmailField && !String.IsNullOrEmpty(txtEmail.Text.Trim()) && (String.IsNullOrEmpty(txtUsername.Text.Trim()) || divUsername.Visible == false)) - { - arrUsers = UserController.GetUsersByEmail(PortalSettings.PortalId, txtEmail.Text, 0, Int32.MaxValue, ref _userCount); - if (arrUsers != null && arrUsers.Count == 1) - { - _user = (UserInfo)arrUsers[0]; - } - } - else + get { - _user = UserController.GetUserByName(PortalSettings.PortalId, txtUsername.Text); + return PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false); } } - #endregion - - #region Event Handlers - + private bool ShowEmailField + { + get + { + return MembershipProviderConfig.RequiresUniqueEmail || this.UsernameDisabled; + } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); var isEnabled = true; - //both retrieval and reset now use password token resets + // both retrieval and reset now use password token resets if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { - lblHelp.Text = Localization.GetString("ResetTokenHelp", LocalResourceFile); - cmdSendPassword.Text = Localization.GetString("ResetToken", LocalResourceFile); + this.lblHelp.Text = Localization.GetString("ResetTokenHelp", this.LocalResourceFile); + this.cmdSendPassword.Text = Localization.GetString("ResetToken", this.LocalResourceFile); } else { isEnabled = false; - lblHelp.Text = Localization.GetString("DisabledPasswordHelp", LocalResourceFile); - divPassword.Visible = false; + this.lblHelp.Text = Localization.GetString("DisabledPasswordHelp", this.LocalResourceFile); + this.divPassword.Visible = false; } - if (!MembershipProviderConfig.PasswordResetEnabled) + if (!MembershipProviderConfig.PasswordResetEnabled) { isEnabled = false; - lblHelp.Text = Localization.GetString("DisabledPasswordHelp", LocalResourceFile); - divPassword.Visible = false; + this.lblHelp.Text = Localization.GetString("DisabledPasswordHelp", this.LocalResourceFile); + this.divPassword.Visible = false; } - if (MembershipProviderConfig.RequiresUniqueEmail && isEnabled && !PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false)) + if (MembershipProviderConfig.RequiresUniqueEmail && isEnabled && !PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false)) { - lblHelp.Text += Localization.GetString("RequiresUniqueEmail", LocalResourceFile); + this.lblHelp.Text += Localization.GetString("RequiresUniqueEmail", this.LocalResourceFile); } if (MembershipProviderConfig.RequiresQuestionAndAnswer && isEnabled) { - lblHelp.Text += Localization.GetString("RequiresQuestionAndAnswer", LocalResourceFile); + this.lblHelp.Text += Localization.GetString("RequiresQuestionAndAnswer", this.LocalResourceFile); } - - } /// - /// Page_Load runs when the control is loaded + /// Page_Load runs when the control is loaded. /// /// /// @@ -213,93 +175,112 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdSendPassword.Click += OnSendPasswordClick; - lnkCancel.NavigateUrl = _navigationManager.NavigateURL(); + this.cmdSendPassword.Click += this.OnSendPasswordClick; + this.lnkCancel.NavigateUrl = this._navigationManager.NavigateURL(); - _ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(Request)); + this._ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); - divEmail.Visible = ShowEmailField; - divUsername.Visible = !UsernameDisabled; - divCaptcha.Visible = UseCaptcha; + this.divEmail.Visible = this.ShowEmailField; + this.divUsername.Visible = !this.UsernameDisabled; + this.divCaptcha.Visible = this.UseCaptcha; - if (UseCaptcha) + if (this.UseCaptcha) { - ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", LocalResourceFile); - ctlCaptcha.Text = Localization.GetString("CaptchaText", LocalResourceFile); + this.ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", this.LocalResourceFile); + this.ctlCaptcha.Text = Localization.GetString("CaptchaText", this.LocalResourceFile); } } + + private void GetUser() + { + ArrayList arrUsers; + if (this.ShowEmailField && !string.IsNullOrEmpty(this.txtEmail.Text.Trim()) && (string.IsNullOrEmpty(this.txtUsername.Text.Trim()) || this.divUsername.Visible == false)) + { + arrUsers = UserController.GetUsersByEmail(this.PortalSettings.PortalId, this.txtEmail.Text, 0, int.MaxValue, ref this._userCount); + if (arrUsers != null && arrUsers.Count == 1) + { + this._user = (UserInfo)arrUsers[0]; + } + } + else + { + this._user = UserController.GetUserByName(this.PortalSettings.PortalId, this.txtUsername.Text); + } + } /// - /// cmdSendPassword_Click runs when the Password Reminder button is clicked + /// cmdSendPassword_Click runs when the Password Reminder button is clicked. /// /// /// - protected void OnSendPasswordClick(Object sender, EventArgs e) + protected void OnSendPasswordClick(object sender, EventArgs e) { - //pretty much alwasy display the same message to avoid hinting on the existance of a user name - var message = Localization.GetString("PasswordSent", LocalResourceFile); + // pretty much alwasy display the same message to avoid hinting on the existance of a user name + var message = Localization.GetString("PasswordSent", this.LocalResourceFile); var moduleMessageType = ModuleMessage.ModuleMessageType.GreenSuccess; var canSend = true; - if ((UseCaptcha && ctlCaptcha.IsValid) || (!UseCaptcha)) + if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || (!this.UseCaptcha)) { - if (String.IsNullOrEmpty(txtUsername.Text.Trim())) + if (string.IsNullOrEmpty(this.txtUsername.Text.Trim())) { - //No UserName provided - if (ShowEmailField) + // No UserName provided + if (this.ShowEmailField) { - if (String.IsNullOrEmpty(txtEmail.Text.Trim())) + if (string.IsNullOrEmpty(this.txtEmail.Text.Trim())) { - //No email address either (cannot retrieve password) + // No email address either (cannot retrieve password) canSend = false; - message = Localization.GetString("EnterUsernameEmail", LocalResourceFile); + message = Localization.GetString("EnterUsernameEmail", this.LocalResourceFile); moduleMessageType = ModuleMessage.ModuleMessageType.RedError; } } else { - //Cannot retrieve password + // Cannot retrieve password canSend = false; - message = Localization.GetString("EnterUsername", LocalResourceFile); + message = Localization.GetString("EnterUsername", this.LocalResourceFile); moduleMessageType = ModuleMessage.ModuleMessageType.RedError; } } if (string.IsNullOrEmpty(Host.SMTPServer)) { - //SMTP Server is not configured + // SMTP Server is not configured canSend = false; - message = Localization.GetString("OptionUnavailable", LocalResourceFile); + message = Localization.GetString("OptionUnavailable", this.LocalResourceFile); moduleMessageType = ModuleMessage.ModuleMessageType.YellowWarning; - var logMessage = Localization.GetString("SMTPNotConfigured", LocalResourceFile); + var logMessage = Localization.GetString("SMTPNotConfigured", this.LocalResourceFile); - LogResult(logMessage); + this.LogResult(logMessage); } if (canSend) { - GetUser(); - if (_user != null) + this.GetUser(); + if (this._user != null) { - if (_user.IsDeleted) + if (this._user.IsDeleted) { canSend = false; } else { - if (_user.Membership.Approved == false) + if (this._user.Membership.Approved == false) { - Mail.SendMail(_user, MessageType.PasswordReminderUserIsNotApproved, PortalSettings); + Mail.SendMail(this._user, MessageType.PasswordReminderUserIsNotApproved, this.PortalSettings); canSend = false; } + if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { - UserController.ResetPasswordToken(_user); + UserController.ResetPasswordToken(this._user); } + if (canSend) { - if (Mail.SendMail(_user, MessageType.PasswordReminder, PortalSettings) != string.Empty) + if (Mail.SendMail(this._user, MessageType.PasswordReminder, this.PortalSettings) != string.Empty) { canSend = false; } @@ -308,9 +289,9 @@ protected void OnSendPasswordClick(Object sender, EventArgs e) } else { - if (_userCount > 1) + if (this._userCount > 1) { - message = Localization.GetString("MultipleUsers", LocalResourceFile); + message = Localization.GetString("MultipleUsers", this.LocalResourceFile); } canSend = false; @@ -318,19 +299,19 @@ protected void OnSendPasswordClick(Object sender, EventArgs e) if (canSend) { - LogSuccess(); - lnkCancel.Attributes["resourcekey"] = "cmdClose"; + this.LogSuccess(); + this.lnkCancel.Attributes["resourcekey"] = "cmdClose"; } else { - LogFailure(message); + this.LogFailure(message); } - //always hide panel so as to not reveal if username exists. - pnlRecover.Visible = false; + // always hide panel so as to not reveal if username exists. + this.pnlRecover.Visible = false; UI.Skins.Skin.AddModuleMessage(this, message, moduleMessageType); - liSend.Visible = false; - liCancel.Visible = true; + this.liSend.Visible = false; + this.liCancel.Visible = true; } else { @@ -341,24 +322,24 @@ protected void OnSendPasswordClick(Object sender, EventArgs e) private void LogSuccess() { - LogResult(string.Empty); + this.LogResult(string.Empty); } private void LogFailure(string reason) { - LogResult(reason); + this.LogResult(reason); } private void LogResult(string message) { var portalSecurity = PortalSecurity.Instance; - var log = new LogInfo + var log = new LogInfo { - LogPortalID = PortalSettings.PortalId, - LogPortalName = PortalSettings.PortalName, - LogUserID = UserId, - LogUserName = portalSecurity.InputFilter(txtUsername.Text, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup) + LogPortalID = this.PortalSettings.PortalId, + LogPortalName = this.PortalSettings.PortalName, + LogUserID = this.UserId, + LogUserName = portalSecurity.InputFilter(this.txtUsername.Text, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup), }; if (string.IsNullOrEmpty(message)) @@ -371,13 +352,9 @@ private void LogResult(string message) log.LogProperties.Add(new LogDetailInfo("Cause", message)); } - log.AddProperty("IP", _ipAddress); + log.AddProperty("IP", this._ipAddress); LogController.Instance.AddLog(log); - - } - - #endregion - + } } } diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Copyright.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Copyright.ascx.resx index 7698754b4aa..455eb7cbd93 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Copyright.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Copyright.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Language.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Language.ascx.resx index 4a6f5efe0b3..213b5d4a11a 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Language.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Language.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToFullSite.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToFullSite.ascx.resx index 50a1d8f11ba..629e2901bb8 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToFullSite.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToFullSite.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToMobileSite.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToMobileSite.ascx.resx index 568165d16a4..a3a7337688e 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToMobileSite.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToMobileSite.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToTabletSite.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToTabletSite.ascx.resx index 2451bbddff4..82de4c8fb99 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToTabletSite.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/LinkToTabletSite.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Login.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Login.ascx.resx index 133563a4ade..3e010d732e2 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Login.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Login.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Privacy.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Privacy.ascx.resx index e2ce445efeb..4b0a12a51e7 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Privacy.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Privacy.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Search.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Search.ascx.resx index 8fd75135dd5..4823aa6e12f 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Search.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Search.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -133,7 +133,7 @@ Search - http://www.google.com/custom?q=[TEXT]&sa=Search&client=pub-9770992166002654&forid=1&ie=ISO-8859-1&oe=ISO-8859-1&cof=GALT%3A%23008000%3BGL%3A1%3BDIV%3A%23336699%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A336699%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BFORID%3A1&hl=en&sitesearch=[DOMAIN] + https://www.google.com/custom?q=[TEXT]&sa=Search&client=pub-9770992166002654&forid=1&ie=ISO-8859-1&oe=ISO-8859-1&cof=GALT%3A%23008000%3BGL%3A1%3BDIV%3A%23336699%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A336699%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BFORID%3A1&hl=en&sitesearch=[DOMAIN] Select the search type diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Tags.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Tags.ascx.resx index ff7c23e9971..adae2493901 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Tags.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Tags.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Terms.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Terms.ascx.resx index 6b8a4481c8e..2116d4eceb6 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Terms.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Terms.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/Toast.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/Toast.ascx.resx index 28a6e6e6dd2..b94fe48d01e 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/Toast.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/Toast.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/TreeViewMenu.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/TreeViewMenu.ascx.resx index e3fb48a8f4d..b6a8e183bce 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/TreeViewMenu.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/TreeViewMenu.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/admin/Skins/App_LocalResources/User.ascx.resx b/DNN Platform/Website/admin/Skins/App_LocalResources/User.ascx.resx index d7e87d853f7..a58ec31c48e 100644 --- a/DNN Platform/Website/admin/Skins/App_LocalResources/User.ascx.resx +++ b/DNN Platform/Website/admin/Skins/App_LocalResources/User.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs b/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs index 1c1fd56bef8..e3bf11b5cf0 100644 --- a/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs +++ b/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Text; -using System.Text.RegularExpressions; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Text; + using System.Text.RegularExpressions; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// /// @@ -29,40 +25,42 @@ public partial class BreadCrumb : SkinObjectBase private int _rootLevel = 0; private bool _showRoot = false; private readonly StringBuilder _breadcrumb = new StringBuilder(""); - private string _homeUrl = ""; + private string _homeUrl = string.Empty; private string _homeTabName = "Root"; private readonly INavigationManager _navigationManager; + public BreadCrumb() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } // Separator between breadcrumb elements public string Separator { - get { return _separator; } - set { _separator = value; } + get { return this._separator; } + set { this._separator = value; } } public string CssClass { - get { return _cssClass; } - set { _cssClass = value; } + get { return this._cssClass; } + set { this._cssClass = value; } } // Level to begin processing breadcrumb at. // -1 means show root breadcrumb public string RootLevel { - get { return _rootLevel.ToString(); } + get { return this._rootLevel.ToString(); } + set { - _rootLevel = int.Parse(value); + this._rootLevel = int.Parse(value); - if (_rootLevel < 0) + if (this._rootLevel < 0) { - _showRoot = true; - _rootLevel = 0; + this._showRoot = true; + this._rootLevel = 0; } } } @@ -73,13 +71,13 @@ public string RootLevel // Do not show when there is no breadcrumb (only has current tab) public bool HideWithNoBreadCrumb { get; set; } - public int ProfileUserId + public int ProfileUserId { get { - return string.IsNullOrEmpty(Request.Params["UserId"]) + return string.IsNullOrEmpty(this.Request.Params["UserId"]) ? Null.NullInteger - : int.Parse(Request.Params["UserId"]); + : int.Parse(this.Request.Params["UserId"]); } } @@ -87,9 +85,9 @@ public int GroupId { get { - return string.IsNullOrEmpty(Request.Params["GroupId"]) + return string.IsNullOrEmpty(this.Request.Params["GroupId"]) ? Null.NullInteger - : int.Parse(Request.Params["GroupId"]); + : int.Parse(this.Request.Params["GroupId"]); } } @@ -100,63 +98,63 @@ protected override void OnLoad(EventArgs e) // Position in breadcrumb list var position = 1; - //resolve image path in separator content - ResolveSeparatorPaths(); + // resolve image path in separator content + this.ResolveSeparatorPaths(); // If we have enabled hiding when there are no breadcrumbs, simply return - if (HideWithNoBreadCrumb && PortalSettings.ActiveTab.BreadCrumbs.Count == (_rootLevel + 1)) + if (this.HideWithNoBreadCrumb && this.PortalSettings.ActiveTab.BreadCrumbs.Count == (this._rootLevel + 1)) { return; } // Without checking if the current tab is the home tab, we would duplicate the root tab - if (_showRoot && PortalSettings.ActiveTab.TabID != PortalSettings.HomeTabId) + if (this._showRoot && this.PortalSettings.ActiveTab.TabID != this.PortalSettings.HomeTabId) { // Add the current protocal to the current URL - _homeUrl = Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias); + this._homeUrl = Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias); // Make sure we have a home tab ID set - if (PortalSettings.HomeTabId != -1) + if (this.PortalSettings.HomeTabId != -1) { - _homeUrl = _navigationManager.NavigateURL(PortalSettings.HomeTabId); + this._homeUrl = this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId); var tc = new TabController(); - var homeTab = tc.GetTab(PortalSettings.HomeTabId, PortalSettings.PortalId, false); - _homeTabName = homeTab.LocalizedTabName; + var homeTab = tc.GetTab(this.PortalSettings.HomeTabId, this.PortalSettings.PortalId, false); + this._homeTabName = homeTab.LocalizedTabName; // Check if we should use the tab's title instead - if (UseTitle && !string.IsNullOrEmpty(homeTab.Title)) + if (this.UseTitle && !string.IsNullOrEmpty(homeTab.Title)) { - _homeTabName = homeTab.Title; + this._homeTabName = homeTab.Title; } } // Append all of the HTML for the root breadcrumb - _breadcrumb.Append(""); - _breadcrumb.Append("" + _homeTabName + ""); - _breadcrumb.Append(""); // Notice we post-increment the position variable - _breadcrumb.Append(""); + this._breadcrumb.Append(""); + this._breadcrumb.Append("" + this._homeTabName + ""); + this._breadcrumb.Append(""); // Notice we post-increment the position variable + this._breadcrumb.Append(""); // Add a separator - _breadcrumb.Append(_separator); + this._breadcrumb.Append(this._separator); } - //process bread crumbs - for (var i = _rootLevel; i < PortalSettings.ActiveTab.BreadCrumbs.Count; ++i) + // process bread crumbs + for (var i = this._rootLevel; i < this.PortalSettings.ActiveTab.BreadCrumbs.Count; ++i) { // Only add separators if we're past the root level - if (i > _rootLevel) + if (i > this._rootLevel) { - _breadcrumb.Append(_separator); + this._breadcrumb.Append(this._separator); } // Grab the current tab - var tab = (TabInfo)PortalSettings.ActiveTab.BreadCrumbs[i]; + var tab = (TabInfo)this.PortalSettings.ActiveTab.BreadCrumbs[i]; var tabName = tab.LocalizedTabName; // Determine if we should use the tab's title instead of tab name - if (UseTitle && !string.IsNullOrEmpty(tab.Title)) + if (this.UseTitle && !string.IsNullOrEmpty(tab.Title)) { tabName = tab.Title; } @@ -164,48 +162,46 @@ protected override void OnLoad(EventArgs e) // Get the absolute URL of the tab var tabUrl = tab.FullUrl; - // - if (ProfileUserId > -1) + if (this.ProfileUserId > -1) { - tabUrl = _navigationManager.NavigateURL(tab.TabID, "", "UserId=" + ProfileUserId); + tabUrl = this._navigationManager.NavigateURL(tab.TabID, string.Empty, "UserId=" + this.ProfileUserId); } - // - if (GroupId > -1) + if (this.GroupId > -1) { - tabUrl = _navigationManager.NavigateURL(tab.TabID, "", "GroupId=" + GroupId); + tabUrl = this._navigationManager.NavigateURL(tab.TabID, string.Empty, "GroupId=" + this.GroupId); } // Begin breadcrumb - _breadcrumb.Append(""); + this._breadcrumb.Append(""); // Is this tab disabled? If so, only render the text if (tab.DisableLink) { - _breadcrumb.Append("" + tabName + ""); + this._breadcrumb.Append("" + tabName + ""); } else { - _breadcrumb.Append("" + tabName + ""); + this._breadcrumb.Append("" + tabName + ""); } - _breadcrumb.Append(""); // Notice we post-increment the position variable - _breadcrumb.Append(""); + this._breadcrumb.Append(""); // Notice we post-increment the position variable + this._breadcrumb.Append(""); } - _breadcrumb.Append(""); //End of BreadcrumbList + this._breadcrumb.Append(""); // End of BreadcrumbList - lblBreadCrumb.Text = _breadcrumb.ToString(); + this.lblBreadCrumb.Text = this._breadcrumb.ToString(); } private void ResolveSeparatorPaths() { - if (string.IsNullOrEmpty(_separator)) + if (string.IsNullOrEmpty(this._separator)) { return; } - var urlMatches = Regex.Matches(_separator, UrlRegex, RegexOptions.IgnoreCase); + var urlMatches = Regex.Matches(this._separator, UrlRegex, RegexOptions.IgnoreCase); if (urlMatches.Count > 0) { foreach (Match match in urlMatches) @@ -228,22 +224,22 @@ private void ResolveSeparatorPaths() } else { - url = string.Format("{0}{1}", PortalSettings.ActiveTab.SkinPath, url); + url = string.Format("{0}{1}", this.PortalSettings.ActiveTab.SkinPath, url); changed = true; } if (changed) { - var newMatch = string.Format("{0}={1}{2}{3}", - match.Groups[1].Value, - match.Groups[2].Value, - url, - match.Groups[4].Value); - - _separator = _separator.Replace(match.Value, newMatch); + var newMatch = string.Format( + "{0}={1}{2}{3}", + match.Groups[1].Value, + match.Groups[2].Value, + url, + match.Groups[4].Value); + + this._separator = this._separator.Replace(match.Value, newMatch); } } - } } } diff --git a/DNN Platform/Website/admin/Skins/Copyright.ascx.cs b/DNN Platform/Website/admin/Skins/Copyright.ascx.cs index 721a02c7c4d..f99b5903d2d 100644 --- a/DNN Platform/Website/admin/Skins/Copyright.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Copyright.ascx.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// /// @@ -20,22 +15,24 @@ namespace DotNetNuke.UI.Skins.Controls public partial class Copyright : SkinObjectBase { private const string MyFileName = "Copyright.ascx"; + public string CssClass { get; set; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - lblCopyright.CssClass = CssClass; + this.lblCopyright.CssClass = this.CssClass; } - if (!String.IsNullOrEmpty(PortalSettings.FooterText)) + + if (!string.IsNullOrEmpty(this.PortalSettings.FooterText)) { - lblCopyright.Text = PortalSettings.FooterText.Replace("[year]", DateTime.Now.ToString("yyyy")); + this.lblCopyright.Text = this.PortalSettings.FooterText.Replace("[year]", DateTime.Now.ToString("yyyy")); } else { - lblCopyright.Text = string.Format(Localization.GetString("Copyright", Localization.GetResourceFile(this, MyFileName)), DateTime.Now.Year, PortalSettings.PortalName); + this.lblCopyright.Text = string.Format(Localization.GetString("Copyright", Localization.GetResourceFile(this, MyFileName)), DateTime.Now.Year, this.PortalSettings.PortalName); } } } diff --git a/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs b/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs index 34517292ce9..90d24fa7c1e 100644 --- a/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs +++ b/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Users; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Entities.Users; + /// ----------------------------------------------------------------------------- /// /// @@ -23,26 +18,27 @@ public partial class CurrentDate : SkinObjectBase public string DateFormat { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - lblDate.CssClass = CssClass; + this.lblDate.CssClass = this.CssClass; } + var user = UserController.Instance.GetCurrentUserInfo(); - lblDate.Text = !String.IsNullOrEmpty(DateFormat) ? user.LocalTime().ToString(DateFormat) : user.LocalTime().ToLongDateString(); + this.lblDate.Text = !string.IsNullOrEmpty(this.DateFormat) ? user.LocalTime().ToString(this.DateFormat) : user.LocalTime().ToLongDateString(); + } + + private void InitializeComponent() + { } } } diff --git a/DNN Platform/Website/admin/Skins/DnnCssExclude.ascx.cs b/DNN Platform/Website/admin/Skins/DnnCssExclude.ascx.cs index 1b0357511a4..0d822e418f5 100644 --- a/DNN Platform/Website/admin/Skins/DnnCssExclude.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnCssExclude.ascx.cs @@ -1,15 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System; -using ClientDependency.Core.Controls; -using ClientDependency.Core; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using ClientDependency.Core; + using ClientDependency.Core.Controls; + public partial class DnnCssExclude : SkinObjectBase { public string Name { get; set; } @@ -17,7 +15,7 @@ public partial class DnnCssExclude : SkinObjectBase protected override void OnLoad(EventArgs e) { base.OnLoad(e); - ctlExclude.Name = Name; + this.ctlExclude.Name = this.Name; } } } diff --git a/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs b/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs index b187f5979de..96ac8991f07 100644 --- a/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs @@ -1,41 +1,48 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System; -using ClientDependency.Core.Controls; -using ClientDependency.Core; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using ClientDependency.Core; + using ClientDependency.Core.Controls; + public partial class DnnCssInclude : SkinObjectBase { public CssMediaType CssMedia { get; set; } + public string FilePath { get; set; } + public string PathNameAlias { get; set; } + public int Priority { get; set; } + public bool AddTag { get; set; } + public string Name { get; set; } + public string Version { get; set; } + public bool ForceVersion { get; set; } + public string ForceProvider { get; set; } + public bool ForceBundle { get; set; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - ctlInclude.AddTag = AddTag; - ctlInclude.CssMedia = CssMedia; - ctlInclude.FilePath = FilePath; - ctlInclude.ForceBundle = ForceBundle; - ctlInclude.ForceProvider = ForceProvider; - ctlInclude.ForceVersion = ForceVersion; - ctlInclude.Name = Name; - ctlInclude.PathNameAlias = PathNameAlias; - ctlInclude.Priority = Priority; - ctlInclude.Version = Version; + this.ctlInclude.AddTag = this.AddTag; + this.ctlInclude.CssMedia = this.CssMedia; + this.ctlInclude.FilePath = this.FilePath; + this.ctlInclude.ForceBundle = this.ForceBundle; + this.ctlInclude.ForceProvider = this.ForceProvider; + this.ctlInclude.ForceVersion = this.ForceVersion; + this.ctlInclude.Name = this.Name; + this.ctlInclude.PathNameAlias = this.PathNameAlias; + this.ctlInclude.Priority = this.Priority; + this.ctlInclude.Version = this.Version; } } } diff --git a/DNN Platform/Website/admin/Skins/DnnJsExclude.ascx.cs b/DNN Platform/Website/admin/Skins/DnnJsExclude.ascx.cs index e267ee50792..d81cb3379cb 100644 --- a/DNN Platform/Website/admin/Skins/DnnJsExclude.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnJsExclude.ascx.cs @@ -1,15 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System; -using ClientDependency.Core.Controls; -using ClientDependency.Core; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using ClientDependency.Core; + using ClientDependency.Core.Controls; + public partial class DnnJsExclude : SkinObjectBase { public string Name { get; set; } @@ -17,7 +15,7 @@ public partial class DnnJsExclude : SkinObjectBase protected override void OnLoad(EventArgs e) { base.OnLoad(e); - ctlExclude.Name = Name; + this.ctlExclude.Name = this.Name; } } } diff --git a/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs b/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs index 079c1bbf2d3..9a774792c49 100644 --- a/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs @@ -1,39 +1,45 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings -using System; -using ClientDependency.Core.Controls; -using ClientDependency.Core; -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using ClientDependency.Core; + using ClientDependency.Core.Controls; + public partial class DnnJsInclude : SkinObjectBase { public string FilePath { get; set; } + public string PathNameAlias { get; set; } + public int Priority { get; set; } + public bool AddTag { get; set; } + public string Name { get; set; } + public string Version { get; set; } + public bool ForceVersion { get; set; } + public string ForceProvider { get; set; } + public bool ForceBundle { get; set; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - ctlInclude.AddTag = AddTag; - ctlInclude.FilePath = FilePath; - ctlInclude.ForceBundle = ForceBundle; - ctlInclude.ForceProvider = ForceProvider; - ctlInclude.ForceVersion = ForceVersion; - ctlInclude.Name = Name; - ctlInclude.PathNameAlias = PathNameAlias; - ctlInclude.Priority = Priority; - ctlInclude.Version = Version; + this.ctlInclude.AddTag = this.AddTag; + this.ctlInclude.FilePath = this.FilePath; + this.ctlInclude.ForceBundle = this.ForceBundle; + this.ctlInclude.ForceProvider = this.ForceProvider; + this.ctlInclude.ForceVersion = this.ForceVersion; + this.ctlInclude.Name = this.Name; + this.ctlInclude.PathNameAlias = this.PathNameAlias; + this.ctlInclude.Priority = this.Priority; + this.ctlInclude.Version = this.Version; } } } diff --git a/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs b/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs index 111298fcd8f..db50fd55cbb 100644 --- a/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs @@ -1,17 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web; + + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// /// @@ -20,36 +16,46 @@ namespace DotNetNuke.UI.Skins.Controls public partial class DnnLink : SkinObjectBase { private const string MyFileName = "DnnLink.ascx"; + public string CssClass { get; set; } + public string Target { get; set; } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (!string.IsNullOrEmpty(this.CssClass)) - aDnnLink.Attributes.Add("class",this.CssClass); - - if (!string.IsNullOrEmpty(Target)) - aDnnLink.Target = this.Target; - //set home page link to community URL - + if (!string.IsNullOrEmpty(this.CssClass)) + { + this.aDnnLink.Attributes.Add("class", this.CssClass); + } + + if (!string.IsNullOrEmpty(this.Target)) + { + this.aDnnLink.Target = this.Target; + } + + // set home page link to community URL string url = "http://www.dnnsoftware.com/community?utm_source=dnn-install&utm_medium=web-link&utm_content=gravity-skin-link&utm_campaign=dnn-install"; string utmTerm = "&utm_term=cms-by-dnn"; - string hostName = this.Request.Url.Host.ToLowerInvariant().Replace("www.", ""); - int charPos = 0; string linkText= "CMS by DNN"; + string hostName = this.Request.Url.Host.ToLowerInvariant().Replace("www.", string.Empty); + int charPos = 0; + string linkText = "CMS by DNN"; if (hostName.Length > 0) { - //convert first letter of hostname to int pos in alphabet + // convert first letter of hostname to int pos in alphabet charPos = char.ToUpper(hostName[0]) - 64; } - //vary link by first letter of host name + + // vary link by first letter of host name if (charPos <= 5) { - linkText = "Open Source ASP.NET CMS by DNN"; + linkText = "Open Source ASP.NET CMS by DNN"; utmTerm = "&utm_term=open+source+asp.net+by+dnn"; } + if (charPos > 5 && charPos <= 10) { - linkText = "DNN - .NET Open Source CMS"; + linkText = "DNN - .NET Open Source CMS"; utmTerm = "&utm_term=dnn+.net+open+source+cms"; } @@ -61,20 +67,18 @@ protected override void OnLoad(EventArgs e) if (charPos > 15 && charPos <= 20) { - linkText = "DNN .NET CMS"; + linkText = "DNN .NET CMS"; utmTerm = "&utm_term=dnn+.net+cms"; } if (charPos > 20 && charPos <= 25) { - linkText = "WCM by DNN"; + linkText = "WCM by DNN"; utmTerm = "&utm_term=wcm+by+dnn"; } - - - aDnnLink.InnerText = linkText; - aDnnLink.HRef = HttpUtility.HtmlEncode(url + utmTerm); - + + this.aDnnLink.InnerText = linkText; + this.aDnnLink.HRef = HttpUtility.HtmlEncode(url + utmTerm); } } } diff --git a/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs b/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs index 0b6e36d0f74..cf34edab755 100644 --- a/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs @@ -1,18 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Application; -using DotNetNuke.Entities.Host; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Application; + using DotNetNuke.Entities.Host; + /// ----------------------------------------------------------------------------- /// /// @@ -21,31 +16,31 @@ public partial class DotNetNukeControl : SkinObjectBase { public string CssClass { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - hypDotNetNuke.CssClass = CssClass; + this.hypDotNetNuke.CssClass = this.CssClass; } - - //get Product Name and Legal Copyright from constants (Medium Trust) - hypDotNetNuke.Text = DotNetNukeContext.Current.Application.LegalCopyright; - hypDotNetNuke.NavigateUrl = DotNetNukeContext.Current.Application.Url; - - //show copyright credits? - Visible = Host.DisplayCopyright; + + // get Product Name and Legal Copyright from constants (Medium Trust) + this.hypDotNetNuke.Text = DotNetNukeContext.Current.Application.LegalCopyright; + this.hypDotNetNuke.NavigateUrl = DotNetNukeContext.Current.Application.Url; + + // show copyright credits? + this.Visible = Host.DisplayCopyright; + } + + private void InitializeComponent() + { } } } diff --git a/DNN Platform/Website/admin/Skins/Help.ascx.cs b/DNN Platform/Website/admin/Skins/Help.ascx.cs index e9d4bc135c7..f03efbc321c 100644 --- a/DNN Platform/Website/admin/Skins/Help.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Help.ascx.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Entities.Host; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Entities.Host; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + /// ----------------------------------------------------------------------------- /// /// @@ -24,15 +19,11 @@ public partial class Help : SkinObjectBase { public string CssClass { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) @@ -40,23 +31,24 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - hypHelp.CssClass = CssClass; + this.hypHelp.CssClass = this.CssClass; } - if (Request.IsAuthenticated) + + if (this.Request.IsAuthenticated) { if (TabPermissionController.CanAdminPage()) { - hypHelp.Text = Localization.GetString("Help"); - hypHelp.NavigateUrl = "mailto:" + Host.HostEmail + "?subject=" + PortalSettings.PortalName + " Support Request"; - hypHelp.Visible = true; + this.hypHelp.Text = Localization.GetString("Help"); + this.hypHelp.NavigateUrl = "mailto:" + Host.HostEmail + "?subject=" + this.PortalSettings.PortalName + " Support Request"; + this.hypHelp.Visible = true; } else { - hypHelp.Text = Localization.GetString("Help"); - hypHelp.NavigateUrl = "mailto:" + PortalSettings.Email + "?subject=" + PortalSettings.PortalName + " Support Request"; - hypHelp.Visible = true; + this.hypHelp.Text = Localization.GetString("Help"); + this.hypHelp.NavigateUrl = "mailto:" + this.PortalSettings.Email + "?subject=" + this.PortalSettings.PortalName + " Support Request"; + this.hypHelp.Visible = true; } } } @@ -65,5 +57,9 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/HostName.ascx.cs b/DNN Platform/Website/admin/Skins/HostName.ascx.cs index 4b79c0b399a..ed8f381b4e4 100644 --- a/DNN Platform/Website/admin/Skins/HostName.ascx.cs +++ b/DNN Platform/Website/admin/Skins/HostName.ascx.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common; -using DotNetNuke.Entities.Host; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Host; + using DotNetNuke.Services.Exceptions; + /// ----------------------------------------------------------------------------- /// /// @@ -23,15 +18,11 @@ public partial class HostName : SkinObjectBase { public string CssClass { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) @@ -39,17 +30,22 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - hypHostName.CssClass = CssClass; + this.hypHostName.CssClass = this.CssClass; } - hypHostName.Text = Host.HostTitle; - hypHostName.NavigateUrl = Globals.AddHTTP(Host.HostURL); + + this.hypHostName.Text = Host.HostTitle; + this.hypHostName.NavigateUrl = Globals.AddHTTP(Host.HostURL); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/JavaScriptLibraryInclude.ascx.cs b/DNN Platform/Website/admin/Skins/JavaScriptLibraryInclude.ascx.cs index b74ca64dd95..2fd27587b7b 100644 --- a/DNN Platform/Website/admin/Skins/JavaScriptLibraryInclude.ascx.cs +++ b/DNN Platform/Website/admin/Skins/JavaScriptLibraryInclude.ascx.cs @@ -1,22 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Framework.JavaScriptLibraries; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { using System; + using DotNetNuke.Framework.JavaScriptLibraries; + public partial class JavaScriptLibraryInclude : SkinObjectBase { public string Name { get; set; } + public Version Version { get; set; } + public SpecificVersion? SpecificVersion { get; set; } protected override void OnInit(EventArgs e) { - if (this.Version == null) + if (this.Version == null) { JavaScript.RequestRegistration(this.Name); } diff --git a/DNN Platform/Website/admin/Skins/Language.ascx.cs b/DNN Platform/Website/admin/Skins/Language.ascx.cs index 6e8bf76effd..f557538f847 100644 --- a/DNN Platform/Website/admin/Skins/Language.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Language.ascx.cs @@ -1,35 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web.UI.WebControls; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.UI.WebControls; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + /// - /// The Language skinobject allows the visitor to select the language of the page + /// The Language skinobject allows the visitor to select the language of the page. /// /// public partial class Language : SkinObjectBase - { - #region Private Members - + { private const string MyFileName = "Language.ascx"; private string _SelectedItemTemplate; private string _alternateTemplate; @@ -41,25 +35,23 @@ public partial class Language : SkinObjectBase private string _localResourceFile; private LanguageTokenReplace _localTokenReplace; private string _separatorTemplate; - private bool _showMenu = true; - - #endregion - - #region Public Properties - + private bool _showMenu = true; + public string AlternateTemplate { get { - if (string.IsNullOrEmpty(_alternateTemplate)) + if (string.IsNullOrEmpty(this._alternateTemplate)) { - _alternateTemplate = Localization.GetString("AlternateTemplate.Default", LocalResourceFile, TemplateCulture); + this._alternateTemplate = Localization.GetString("AlternateTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _alternateTemplate; + + return this._alternateTemplate; } + set { - _alternateTemplate = value; + this._alternateTemplate = value; } } @@ -67,15 +59,17 @@ public string CommonFooterTemplate { get { - if (string.IsNullOrEmpty(_commonFooterTemplate)) + if (string.IsNullOrEmpty(this._commonFooterTemplate)) { - _commonFooterTemplate = Localization.GetString("CommonFooterTemplate.Default", LocalResourceFile, TemplateCulture); + this._commonFooterTemplate = Localization.GetString("CommonFooterTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _commonFooterTemplate; + + return this._commonFooterTemplate; } + set { - _commonFooterTemplate = value; + this._commonFooterTemplate = value; } } @@ -83,15 +77,17 @@ public string CommonHeaderTemplate { get { - if (string.IsNullOrEmpty(_commonHeaderTemplate)) + if (string.IsNullOrEmpty(this._commonHeaderTemplate)) { - _commonHeaderTemplate = Localization.GetString("CommonHeaderTemplate.Default", LocalResourceFile, TemplateCulture); + this._commonHeaderTemplate = Localization.GetString("CommonHeaderTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _commonHeaderTemplate; + + return this._commonHeaderTemplate; } + set { - _commonHeaderTemplate = value; + this._commonHeaderTemplate = value; } } @@ -101,15 +97,17 @@ public string FooterTemplate { get { - if (string.IsNullOrEmpty(_footerTemplate)) + if (string.IsNullOrEmpty(this._footerTemplate)) { - _footerTemplate = Localization.GetString("FooterTemplate.Default", LocalResourceFile, TemplateCulture); + this._footerTemplate = Localization.GetString("FooterTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _footerTemplate; + + return this._footerTemplate; } + set { - _footerTemplate = value; + this._footerTemplate = value; } } @@ -117,15 +115,17 @@ public string HeaderTemplate { get { - if (string.IsNullOrEmpty(_headerTemplate)) + if (string.IsNullOrEmpty(this._headerTemplate)) { - _headerTemplate = Localization.GetString("HeaderTemplate.Default", LocalResourceFile, TemplateCulture); + this._headerTemplate = Localization.GetString("HeaderTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _headerTemplate; + + return this._headerTemplate; } + set { - _headerTemplate = value; + this._headerTemplate = value; } } @@ -133,15 +133,17 @@ public string ItemTemplate { get { - if (string.IsNullOrEmpty(_itemTemplate)) + if (string.IsNullOrEmpty(this._itemTemplate)) { - _itemTemplate = Localization.GetString("ItemTemplate.Default", LocalResourceFile, TemplateCulture); + this._itemTemplate = Localization.GetString("ItemTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _itemTemplate; + + return this._itemTemplate; } + set { - _itemTemplate = value; + this._itemTemplate = value; } } @@ -149,15 +151,17 @@ public string SelectedItemTemplate { get { - if (string.IsNullOrEmpty(_SelectedItemTemplate)) + if (string.IsNullOrEmpty(this._SelectedItemTemplate)) { - _SelectedItemTemplate = Localization.GetString("SelectedItemTemplate.Default", LocalResourceFile, TemplateCulture); + this._SelectedItemTemplate = Localization.GetString("SelectedItemTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _SelectedItemTemplate; + + return this._SelectedItemTemplate; } + set { - _SelectedItemTemplate = value; + this._SelectedItemTemplate = value; } } @@ -165,15 +169,17 @@ public string SeparatorTemplate { get { - if (string.IsNullOrEmpty(_separatorTemplate)) + if (string.IsNullOrEmpty(this._separatorTemplate)) { - _separatorTemplate = Localization.GetString("SeparatorTemplate.Default", LocalResourceFile, TemplateCulture); + this._separatorTemplate = Localization.GetString("SeparatorTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - return _separatorTemplate; + + return this._separatorTemplate; } + set { - _separatorTemplate = value; + this._separatorTemplate = value; } } @@ -183,25 +189,23 @@ public bool ShowMenu { get { - if ((_showMenu == false) && (ShowLinks == false)) + if ((this._showMenu == false) && (this.ShowLinks == false)) { - //this is to make sure that at least one type of selector will be visible if multiple languages are enabled - _showMenu = true; + // this is to make sure that at least one type of selector will be visible if multiple languages are enabled + this._showMenu = true; } - return _showMenu; + + return this._showMenu; } + set { - _showMenu = value; + this._showMenu = value; } } - public bool UseCurrentCultureForTemplate { get; set; } - - #endregion - - #region Protected Properties - + public bool UseCurrentCultureForTemplate { get; set; } + protected string CurrentCulture { get @@ -214,20 +218,20 @@ protected string TemplateCulture { get { - return (UseCurrentCultureForTemplate) ? CurrentCulture : "en-US"; + return this.UseCurrentCultureForTemplate ? this.CurrentCulture : "en-US"; } } - - + protected string LocalResourceFile { get { - if (string.IsNullOrEmpty(_localResourceFile)) + if (string.IsNullOrEmpty(this._localResourceFile)) { - _localResourceFile = Localization.GetResourceFile(this, MyFileName); + this._localResourceFile = Localization.GetResourceFile(this, MyFileName); } - return _localResourceFile; + + return this._localResourceFile; } } @@ -235,169 +239,99 @@ protected LanguageTokenReplace LocalTokenReplace { get { - if (_localTokenReplace == null) - { - _localTokenReplace = new LanguageTokenReplace {resourceFile = LocalResourceFile}; - } - return _localTokenReplace; - } - } - - #endregion - - #region Private Methods - - private string parseTemplate(string template, string locale) - { - string strReturnValue = template; - try - { - if (!string.IsNullOrEmpty(locale)) - { - //for non data items use locale - LocalTokenReplace.Language = locale; - } - else + if (this._localTokenReplace == null) { - //for non data items use page culture - LocalTokenReplace.Language = CurrentCulture; + this._localTokenReplace = new LanguageTokenReplace { resourceFile = this.LocalResourceFile }; } - - //perform token replacements - strReturnValue = LocalTokenReplace.ReplaceEnvironmentTokens(strReturnValue); + + return this._localTokenReplace; } - catch (Exception ex) - { - Exceptions.ProcessPageLoadException(ex, Request.RawUrl); - } - return strReturnValue; - } - - private void handleCommonTemplates() - { - if (string.IsNullOrEmpty(CommonHeaderTemplate)) - { - litCommonHeaderTemplate.Visible = false; - } - else - { - litCommonHeaderTemplate.Text = parseTemplate(CommonHeaderTemplate, CurrentCulture); - } - if (string.IsNullOrEmpty(CommonFooterTemplate)) - { - litCommonFooterTemplate.Visible = false; - } - else - { - litCommonFooterTemplate.Text = parseTemplate(CommonFooterTemplate, CurrentCulture); - } - } - - private bool LocaleIsAvailable(Locale locale) - { - var tab = PortalSettings.ActiveTab; - if (tab.DefaultLanguageTab != null) - { - tab = tab.DefaultLanguageTab; - } - - var localizedTab = TabController.Instance.GetTabByCulture(tab.TabID, tab.PortalID, locale); - - return localizedTab != null && !localizedTab.IsDeleted && TabPermissionController.CanViewPage(localizedTab); - } - - #endregion - - #region Event Handlers - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - selectCulture.SelectedIndexChanged += selectCulture_SelectedIndexChanged; - rptLanguages.ItemDataBound += rptLanguages_ItemDataBound; + this.selectCulture.SelectedIndexChanged += this.selectCulture_SelectedIndexChanged; + this.rptLanguages.ItemDataBound += this.rptLanguages_ItemDataBound; try { var locales = new Dictionary(); - IEnumerable cultureListItems = DotNetNuke.Services.Localization.Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, CurrentCulture, "", false); - foreach (Locale loc in LocaleController.Instance.GetLocales(PortalSettings.PortalId).Values) + IEnumerable cultureListItems = DotNetNuke.Services.Localization.Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, this.CurrentCulture, string.Empty, false); + foreach (Locale loc in LocaleController.Instance.GetLocales(this.PortalSettings.PortalId).Values) { - string defaultRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", loc.Code), PortalSettings.PortalId, "Administrators"); - if (!PortalSettings.ContentLocalizationEnabled || - (LocaleIsAvailable(loc) && - (PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleName) || loc.IsPublished || PortalSecurity.IsInRoles(defaultRoles)))) + string defaultRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", loc.Code), this.PortalSettings.PortalId, "Administrators"); + if (!this.PortalSettings.ContentLocalizationEnabled || + (this.LocaleIsAvailable(loc) && + (PortalSecurity.IsInRoles(this.PortalSettings.AdministratorRoleName) || loc.IsPublished || PortalSecurity.IsInRoles(defaultRoles)))) { locales.Add(loc.Code, loc); foreach (var cultureItem in cultureListItems) { if (cultureItem.Value == loc.Code) { - selectCulture.Items.Add(cultureItem); + this.selectCulture.Items.Add(cultureItem); } } } } - if (ShowLinks) + + if (this.ShowLinks) { if (locales.Count > 1) { - rptLanguages.DataSource = locales.Values; - rptLanguages.DataBind(); + this.rptLanguages.DataSource = locales.Values; + this.rptLanguages.DataBind(); } else { - rptLanguages.Visible = false; + this.rptLanguages.Visible = false; } } - if (ShowMenu) + + if (this.ShowMenu) { - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - selectCulture.CssClass = CssClass; + this.selectCulture.CssClass = this.CssClass; } - if (!IsPostBack) + + if (!this.IsPostBack) { - //select the default item - if (CurrentCulture != null) + // select the default item + if (this.CurrentCulture != null) { - ListItem item = selectCulture.Items.FindByValue(CurrentCulture); + ListItem item = this.selectCulture.Items.FindByValue(this.CurrentCulture); if (item != null) { - selectCulture.SelectedIndex = -1; + this.selectCulture.SelectedIndex = -1; item.Selected = true; } } } - //only show language selector if more than one language - if (selectCulture.Items.Count <= 1) + + // only show language selector if more than one language + if (this.selectCulture.Items.Count <= 1) { - selectCulture.Visible = false; + this.selectCulture.Visible = false; } } else { - selectCulture.Visible = false; + this.selectCulture.Visible = false; } - handleCommonTemplates(); + + this.handleCommonTemplates(); } catch (Exception ex) { - Exceptions.ProcessPageLoadException(ex, Request.RawUrl); + Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); } } - private void selectCulture_SelectedIndexChanged(object sender, EventArgs e) - { - //Redirect to same page to update all controls for newly selected culture - LocalTokenReplace.Language = selectCulture.SelectedItem.Value; - //DNN-6170 ensure skin value is culture specific in case of static localization - DataCache.RemoveCache(string.Format(DataCache.PortalSettingsCacheKey, PortalSettings.PortalId, Null.NullString)); - Response.Redirect(LocalTokenReplace.ReplaceEnvironmentTokens("[URL]")); - } - /// - /// Binds data to repeater. a template is used to render the items + /// Binds data to repeater. a template is used to render the items. /// /// /// @@ -408,33 +342,35 @@ protected void rptLanguages_ItemDataBound(object sender, RepeaterItemEventArgs e var litTemplate = e.Item.FindControl("litItemTemplate") as Literal; if (litTemplate != null) { - //load proper template for this Item - string strTemplate = ""; + // load proper template for this Item + string strTemplate = string.Empty; switch (e.Item.ItemType) { case ListItemType.Item: - strTemplate = ItemTemplate; + strTemplate = this.ItemTemplate; break; case ListItemType.AlternatingItem: - if (!string.IsNullOrEmpty(AlternateTemplate)) + if (!string.IsNullOrEmpty(this.AlternateTemplate)) { - strTemplate = AlternateTemplate; + strTemplate = this.AlternateTemplate; } else { - strTemplate = ItemTemplate; + strTemplate = this.ItemTemplate; } + break; case ListItemType.Header: - strTemplate = HeaderTemplate; + strTemplate = this.HeaderTemplate; break; case ListItemType.Footer: - strTemplate = FooterTemplate; + strTemplate = this.FooterTemplate; break; case ListItemType.Separator: - strTemplate = SeparatorTemplate; + strTemplate = this.SeparatorTemplate; break; } + if (string.IsNullOrEmpty(strTemplate)) { litTemplate.Visible = false; @@ -446,27 +382,97 @@ protected void rptLanguages_ItemDataBound(object sender, RepeaterItemEventArgs e var locale = e.Item.DataItem as Locale; if (locale != null && (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)) { - if (locale.Code == CurrentCulture && !string.IsNullOrEmpty(SelectedItemTemplate)) + if (locale.Code == this.CurrentCulture && !string.IsNullOrEmpty(this.SelectedItemTemplate)) { - strTemplate = SelectedItemTemplate; + strTemplate = this.SelectedItemTemplate; } - litTemplate.Text = parseTemplate(strTemplate, locale.Code); + + litTemplate.Text = this.parseTemplate(strTemplate, locale.Code); } } else { - //for non data items use page culture - litTemplate.Text = parseTemplate(strTemplate, CurrentCulture); + // for non data items use page culture + litTemplate.Text = this.parseTemplate(strTemplate, this.CurrentCulture); } } } } catch (Exception ex) { - Exceptions.ProcessPageLoadException(ex, Request.RawUrl); + Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); + } + } + + private string parseTemplate(string template, string locale) + { + string strReturnValue = template; + try + { + if (!string.IsNullOrEmpty(locale)) + { + // for non data items use locale + this.LocalTokenReplace.Language = locale; + } + else + { + // for non data items use page culture + this.LocalTokenReplace.Language = this.CurrentCulture; + } + + // perform token replacements + strReturnValue = this.LocalTokenReplace.ReplaceEnvironmentTokens(strReturnValue); + } + catch (Exception ex) + { + Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); + } + + return strReturnValue; + } + + private void handleCommonTemplates() + { + if (string.IsNullOrEmpty(this.CommonHeaderTemplate)) + { + this.litCommonHeaderTemplate.Visible = false; + } + else + { + this.litCommonHeaderTemplate.Text = this.parseTemplate(this.CommonHeaderTemplate, this.CurrentCulture); + } + + if (string.IsNullOrEmpty(this.CommonFooterTemplate)) + { + this.litCommonFooterTemplate.Visible = false; + } + else + { + this.litCommonFooterTemplate.Text = this.parseTemplate(this.CommonFooterTemplate, this.CurrentCulture); } } - - #endregion + + private bool LocaleIsAvailable(Locale locale) + { + var tab = this.PortalSettings.ActiveTab; + if (tab.DefaultLanguageTab != null) + { + tab = tab.DefaultLanguageTab; + } + + var localizedTab = TabController.Instance.GetTabByCulture(tab.TabID, tab.PortalID, locale); + + return localizedTab != null && !localizedTab.IsDeleted && TabPermissionController.CanViewPage(localizedTab); + } + + private void selectCulture_SelectedIndexChanged(object sender, EventArgs e) + { + // Redirect to same page to update all controls for newly selected culture + this.LocalTokenReplace.Language = this.selectCulture.SelectedItem.Value; + + // DNN-6170 ensure skin value is culture specific in case of static localization + DataCache.RemoveCache(string.Format(DataCache.PortalSettingsCacheKey, this.PortalSettings.PortalId, Null.NullString)); + this.Response.Redirect(this.LocalTokenReplace.ReplaceEnvironmentTokens("[URL]")); + } } } diff --git a/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs b/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs index 96b327e2a28..ec3b6ba6e12 100644 --- a/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs +++ b/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs @@ -1,22 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + /// ----------------------------------------------------------------------------- /// /// @@ -25,6 +20,5 @@ namespace DotNetNuke.UI.Skins.Controls [Obsolete("This skin object has been expired, create empty object to compact old skin. please ask skin vendor to update the skin if it referenced to this control.. Scheduled removal in v10.0.0.")] public partial class LeftMenu : SkinObjectBase { - } } diff --git a/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs b/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs index b724365d968..7bae3bb1e4b 100644 --- a/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs +++ b/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mobile; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mobile; + using DotNetNuke.UI.Skins; + /// ----------------------------------------------------------------------------- /// Skin object of portal links between desktop and mobile portals. /// @@ -28,38 +23,36 @@ public partial class LinkToFullSite : SkinObjectBase { private const string MyFileName = "LinkToFullSite.ascx"; - private string _localResourcesFile; + private string _localResourcesFile; - private string LocalResourcesFile - { - get - { - if(string.IsNullOrEmpty(_localResourcesFile)) - { - _localResourcesFile = Localization.GetResourceFile(this, MyFileName); - } - - return _localResourcesFile; - } - } + private string LocalResourcesFile + { + get + { + if (string.IsNullOrEmpty(this._localResourcesFile)) + { + this._localResourcesFile = Localization.GetResourceFile(this, MyFileName); + } - #region "Event Handlers" + return this._localResourcesFile; + } + } + protected override void OnLoad(EventArgs e) - { + { base.OnLoad(e); var redirectionController = new RedirectionController(); var redirectUrl = redirectionController.GetFullSiteUrl(); if (!string.IsNullOrEmpty(redirectUrl)) - { - lnkPortal.NavigateUrl = redirectUrl; - lnkPortal.Text = Localization.GetString("lnkPortal", LocalResourcesFile); + { + this.lnkPortal.NavigateUrl = redirectUrl; + this.lnkPortal.Text = Localization.GetString("lnkPortal", this.LocalResourcesFile); } else { this.Visible = false; } - } - #endregion + } } } diff --git a/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs b/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs index e10cef5f486..92472771968 100644 --- a/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs +++ b/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Mobile; -using DotNetNuke.UI.Skins; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Mobile; + using DotNetNuke.UI.Skins; + /// ----------------------------------------------------------------------------- /// Skin object of portal links between desktop and mobile portals. /// @@ -28,40 +23,36 @@ public partial class LinkToMobileSite : SkinObjectBase { private const string MyFileName = "LinkToMobileSite.ascx"; - private string _localResourcesFile; - - private string LocalResourcesFile - { - get - { - if(string.IsNullOrEmpty(_localResourcesFile)) - { - _localResourcesFile = Localization.GetResourceFile(this, MyFileName); - } + private string _localResourcesFile; - return _localResourcesFile; - } - } + private string LocalResourcesFile + { + get + { + if (string.IsNullOrEmpty(this._localResourcesFile)) + { + this._localResourcesFile = Localization.GetResourceFile(this, MyFileName); + } - #region "Event Handlers" + return this._localResourcesFile; + } + } + protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); + { + base.OnLoad(e); var redirectionController = new RedirectionController(); var redirectUrl = redirectionController.GetMobileSiteUrl(); if (!string.IsNullOrEmpty(redirectUrl)) - { - lnkPortal.NavigateUrl = redirectUrl; - lnkPortal.Text = Localization.GetString("lnkPortal", LocalResourcesFile); + { + this.lnkPortal.NavigateUrl = redirectUrl; + this.lnkPortal.Text = Localization.GetString("lnkPortal", this.LocalResourcesFile); } else { - this.Visible = false; + this.Visible = false; } - } - - - #endregion + } } } diff --git a/DNN Platform/Website/admin/Skins/Links.ascx.cs b/DNN Platform/Website/admin/Skins/Links.ascx.cs index d6fb8277b43..501e5b1bbbd 100644 --- a/DNN Platform/Website/admin/Skins/Links.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Links.ascx.cs @@ -1,49 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Collections.Generic; + using System.Text; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + /// ----------------------------------------------------------------------------- /// /// /// ----------------------------------------------------------------------------- public partial class Links : SkinObjectBase { - private static readonly Regex SrcRegex = new Regex("src=[']?", RegexOptions.Compiled | RegexOptions.IgnoreCase); - - #region "Private Members" - + private static readonly Regex SrcRegex = new Regex("src=[']?", RegexOptions.Compiled | RegexOptions.IgnoreCase); private string _alignment; private bool _forceLinks = true; private bool _includeActiveTab = true; - private string _level; - - #endregion - - #region "Public Members" - + private string _level; + public string Alignment { get { - return _alignment; + return this._alignment; } + set { - _alignment = value.ToLowerInvariant(); + this._alignment = value.ToLowerInvariant(); } } @@ -53,11 +42,12 @@ public string Level { get { - return _level; + return this._level; } + set { - _level = value.ToLowerInvariant(); + this._level = value.ToLowerInvariant(); } } @@ -69,11 +59,12 @@ public bool ForceLinks { get { - return _forceLinks; + return this._forceLinks; } + set { - _forceLinks = value; + this._forceLinks = value; } } @@ -81,145 +72,147 @@ public bool IncludeActiveTab { get { - return _includeActiveTab; + return this._includeActiveTab; } + set { - _includeActiveTab = value; + this._includeActiveTab = value; } - } - - #endregion - - #region "Event Handlers" - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); string strCssClass; - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - strCssClass = CssClass; + strCssClass = this.CssClass; } else { strCssClass = "SkinObject"; } + string strSeparator = string.Empty; - if (!String.IsNullOrEmpty(Separator)) + if (!string.IsNullOrEmpty(this.Separator)) { - if (Separator.IndexOf("src=", StringComparison.Ordinal) != -1) + if (this.Separator.IndexOf("src=", StringComparison.Ordinal) != -1) { - //Add the skinpath to image paths - Separator = SrcRegex.Replace(Separator, "$&" + PortalSettings.ActiveTab.SkinPath); + // Add the skinpath to image paths + this.Separator = SrcRegex.Replace(this.Separator, "$&" + this.PortalSettings.ActiveTab.SkinPath); } - - //Wrap in a span - Separator = string.Format("{1}", strCssClass, Separator); + + // Wrap in a span + this.Separator = string.Format("{1}", strCssClass, this.Separator); } else { - Separator = " "; + this.Separator = " "; } - - //build links - string strLinks = ""; - strLinks = BuildLinks(Level, strSeparator, strCssClass); - - //Render links, even if nothing is returned with the currently set level - if (String.IsNullOrEmpty(strLinks) && ForceLinks) + // build links + string strLinks = string.Empty; + + strLinks = this.BuildLinks(this.Level, strSeparator, strCssClass); + + // Render links, even if nothing is returned with the currently set level + if (string.IsNullOrEmpty(strLinks) && this.ForceLinks) { - strLinks = BuildLinks("", strSeparator, strCssClass); + strLinks = this.BuildLinks(string.Empty, strSeparator, strCssClass); } - lblLinks.Text = strLinks; - } - - #endregion - - #region "Private Methods" - + + this.lblLinks.Text = strLinks; + } + private string BuildLinks(string strLevel, string strSeparator, string strCssClass) { var sbLinks = new StringBuilder(); - List portalTabs = TabController.GetTabsBySortOrder(PortalSettings.PortalId); + List portalTabs = TabController.GetTabsBySortOrder(this.PortalSettings.PortalId); List hostTabs = TabController.GetTabsBySortOrder(Null.NullInteger); foreach (TabInfo objTab in portalTabs) { - sbLinks.Append(ProcessLink(ProcessTab(objTab, strLevel, strCssClass), sbLinks.ToString().Length)); + sbLinks.Append(this.ProcessLink(this.ProcessTab(objTab, strLevel, strCssClass), sbLinks.ToString().Length)); } + foreach (TabInfo objTab in hostTabs) { - sbLinks.Append(ProcessLink(ProcessTab(objTab, strLevel, strCssClass), sbLinks.ToString().Length)); + sbLinks.Append(this.ProcessLink(this.ProcessTab(objTab, strLevel, strCssClass), sbLinks.ToString().Length)); } + return sbLinks.ToString(); } private string ProcessTab(TabInfo objTab, string strLevel, string strCssClass) { - if (Navigation.CanShowTab(objTab, AdminMode, ShowDisabled)) + if (Navigation.CanShowTab(objTab, this.AdminMode, this.ShowDisabled)) { switch (strLevel) { - case "same": //Render tabs on the same level as the current tab + case "same": // Render tabs on the same level as the current tab case "": - if (objTab.ParentId == PortalSettings.ActiveTab.ParentId) + if (objTab.ParentId == this.PortalSettings.ActiveTab.ParentId) { - if (IncludeActiveTab || objTab.TabID != PortalSettings.ActiveTab.TabID) + if (this.IncludeActiveTab || objTab.TabID != this.PortalSettings.ActiveTab.TabID) { - return AddLink(objTab.TabName, objTab.FullUrl, strCssClass); + return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } } + break; - case "child": //Render the current tabs child tabs - if (objTab.ParentId == PortalSettings.ActiveTab.TabID) + case "child": // Render the current tabs child tabs + if (objTab.ParentId == this.PortalSettings.ActiveTab.TabID) { - return AddLink(objTab.TabName, objTab.FullUrl, strCssClass); + return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } + break; - case "parent": //Render the current tabs parenttab - if (objTab.TabID == PortalSettings.ActiveTab.ParentId) + case "parent": // Render the current tabs parenttab + if (objTab.TabID == this.PortalSettings.ActiveTab.ParentId) { - return AddLink(objTab.TabName, objTab.FullUrl, strCssClass); + return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } + break; - case "root": //Render Root tabs + case "root": // Render Root tabs if (objTab.Level == 0) { - return AddLink(objTab.TabName, objTab.FullUrl, strCssClass); + return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } + break; } } - return ""; + + return string.Empty; } private string ProcessLink(string sLink, int iLinksLength) { - //wrap in a div if set to vertical - if (String.IsNullOrEmpty(sLink)) + // wrap in a div if set to vertical + if (string.IsNullOrEmpty(sLink)) { - return ""; + return string.Empty; } - if (Alignment == "vertical") + + if (this.Alignment == "vertical") { - sLink = string.Concat("
        ", Separator, sLink, "
        "); + sLink = string.Concat("
        ", this.Separator, sLink, "
        "); } - else if (!String.IsNullOrEmpty(Separator) && iLinksLength > 0) + else if (!string.IsNullOrEmpty(this.Separator) && iLinksLength > 0) { - //If not vertical, then render the separator - sLink = string.Concat(Separator, sLink); + // If not vertical, then render the separator + sLink = string.Concat(this.Separator, sLink); } + return sLink; } private string AddLink(string strTabName, string strURL, string strCssClass) { return string.Format("{2}", strCssClass, strURL, strTabName); - } - - #endregion + } } } diff --git a/DNN Platform/Website/admin/Skins/Login.ascx.cs b/DNN Platform/Website/admin/Skins/Login.ascx.cs index 10e37d4c9fd..70a0c0a7e1e 100644 --- a/DNN Platform/Website/admin/Skins/Login.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Login.ascx.cs @@ -1,45 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// /// /// ----------------------------------------------------------------------------- public partial class Login : SkinObjectBase { + private const string MyFileName = "Login.ascx"; + private readonly INavigationManager _navigationManager; + public Login() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); - LegacyMode = true; - } - - #region Private Members - - private const string MyFileName = "Login.ascx"; - #endregion - - #region Public Members - + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + this.LegacyMode = true; + } + public string Text { get; set; } public string CssClass { get; set; } @@ -47,126 +38,124 @@ public Login() public string LogoffText { get; set; } /// - /// Set this to false in the skin to take advantage of the enhanced markup + /// Gets or sets a value indicating whether set this to false in the skin to take advantage of the enhanced markup. /// public bool LegacyMode { get; set; } /// - /// set this to true to show in custom 404/500 page. + /// Gets or sets a value indicating whether set this to true to show in custom 404/500 page. /// - public bool ShowInErrorPage { get; set; } - - #endregion - - #region Event Handlers - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); + public bool ShowInErrorPage { get; set; } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); - Visible = (!PortalSettings.HideLoginControl || Request.IsAuthenticated) - && (!PortalSettings.InErrorPageRequest() || ShowInErrorPage); - } + this.Visible = (!this.PortalSettings.HideLoginControl || this.Request.IsAuthenticated) + && (!this.PortalSettings.InErrorPageRequest() || this.ShowInErrorPage); + } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (Visible) - { - try - { - if (LegacyMode) - { - loginLink.Visible = true; - loginGroup.Visible = false; - } - else - { - loginLink.Visible = false; - loginGroup.Visible = true; - } - - if (!String.IsNullOrEmpty(CssClass)) - { - loginLink.CssClass = CssClass; - enhancedLoginLink.CssClass = CssClass; - } - - if (Request.IsAuthenticated) - { - if (!String.IsNullOrEmpty(LogoffText)) - { - if (LogoffText.IndexOf("src=") != -1) - { - LogoffText = LogoffText.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); - } - loginLink.Text = LogoffText; - enhancedLoginLink.Text = LogoffText; - } - else - { - loginLink.Text = Localization.GetString("Logout", Localization.GetResourceFile(this, MyFileName)); - enhancedLoginLink.Text = loginLink.Text; - loginLink.ToolTip = loginLink.Text; - enhancedLoginLink.ToolTip = loginLink.Text; - } - loginLink.NavigateUrl = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Logoff"); - enhancedLoginLink.NavigateUrl = loginLink.NavigateUrl; - } - else - { - if (!String.IsNullOrEmpty(Text)) - { - if (Text.IndexOf("src=") != -1) - { - Text = Text.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); - } - loginLink.Text = Text; - enhancedLoginLink.Text = Text; - } - else - { - loginLink.Text = Localization.GetString("Login", Localization.GetResourceFile(this, MyFileName)); - enhancedLoginLink.Text = loginLink.Text; - loginLink.ToolTip = loginLink.Text; - enhancedLoginLink.ToolTip = loginLink.Text; - } - - string returnUrl = HttpContext.Current.Request.RawUrl; - if (returnUrl.IndexOf("?returnurl=") != -1) - { - returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=")); - } - returnUrl = HttpUtility.UrlEncode(returnUrl); - - loginLink.NavigateUrl = Globals.LoginURL(returnUrl, (Request.QueryString["override"] != null)); - enhancedLoginLink.NavigateUrl = loginLink.NavigateUrl; - - //avoid issues caused by multiple clicks of login link + if (this.Visible) + { + try + { + if (this.LegacyMode) + { + this.loginLink.Visible = true; + this.loginGroup.Visible = false; + } + else + { + this.loginLink.Visible = false; + this.loginGroup.Visible = true; + } + + if (!string.IsNullOrEmpty(this.CssClass)) + { + this.loginLink.CssClass = this.CssClass; + this.enhancedLoginLink.CssClass = this.CssClass; + } + + if (this.Request.IsAuthenticated) + { + if (!string.IsNullOrEmpty(this.LogoffText)) + { + if (this.LogoffText.IndexOf("src=") != -1) + { + this.LogoffText = this.LogoffText.Replace("src=\"", "src=\"" + this.PortalSettings.ActiveTab.SkinPath); + } + + this.loginLink.Text = this.LogoffText; + this.enhancedLoginLink.Text = this.LogoffText; + } + else + { + this.loginLink.Text = Localization.GetString("Logout", Localization.GetResourceFile(this, MyFileName)); + this.enhancedLoginLink.Text = this.loginLink.Text; + this.loginLink.ToolTip = this.loginLink.Text; + this.enhancedLoginLink.ToolTip = this.loginLink.Text; + } + + this.loginLink.NavigateUrl = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Logoff"); + this.enhancedLoginLink.NavigateUrl = this.loginLink.NavigateUrl; + } + else + { + if (!string.IsNullOrEmpty(this.Text)) + { + if (this.Text.IndexOf("src=") != -1) + { + this.Text = this.Text.Replace("src=\"", "src=\"" + this.PortalSettings.ActiveTab.SkinPath); + } + + this.loginLink.Text = this.Text; + this.enhancedLoginLink.Text = this.Text; + } + else + { + this.loginLink.Text = Localization.GetString("Login", Localization.GetResourceFile(this, MyFileName)); + this.enhancedLoginLink.Text = this.loginLink.Text; + this.loginLink.ToolTip = this.loginLink.Text; + this.enhancedLoginLink.ToolTip = this.loginLink.Text; + } + + string returnUrl = HttpContext.Current.Request.RawUrl; + if (returnUrl.IndexOf("?returnurl=") != -1) + { + returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=")); + } + + returnUrl = HttpUtility.UrlEncode(returnUrl); + + this.loginLink.NavigateUrl = Globals.LoginURL(returnUrl, this.Request.QueryString["override"] != null); + this.enhancedLoginLink.NavigateUrl = this.loginLink.NavigateUrl; + + // avoid issues caused by multiple clicks of login link var oneclick = "this.disabled=true;"; - if (Request.UserAgent != null && Request.UserAgent.Contains("MSIE 8.0")==false) - { - loginLink.Attributes.Add("onclick", oneclick); - enhancedLoginLink.Attributes.Add("onclick", oneclick); - } - - if (PortalSettings.EnablePopUps && PortalSettings.LoginTabId == Null.NullInteger && !AuthenticationController.HasSocialAuthenticationEnabled(this)) - { - //To avoid duplicated encodes of URL - var clickEvent = "return " + UrlUtils.PopUpUrl(HttpUtility.UrlDecode(loginLink.NavigateUrl), this, PortalSettings, true, false, 300, 650); - loginLink.Attributes.Add("onclick", clickEvent); - enhancedLoginLink.Attributes.Add("onclick", clickEvent); - } - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - } - - #endregion + if (this.Request.UserAgent != null && this.Request.UserAgent.Contains("MSIE 8.0") == false) + { + this.loginLink.Attributes.Add("onclick", oneclick); + this.enhancedLoginLink.Attributes.Add("onclick", oneclick); + } + + if (this.PortalSettings.EnablePopUps && this.PortalSettings.LoginTabId == Null.NullInteger && !AuthenticationController.HasSocialAuthenticationEnabled(this)) + { + // To avoid duplicated encodes of URL + var clickEvent = "return " + UrlUtils.PopUpUrl(HttpUtility.UrlDecode(this.loginLink.NavigateUrl), this, this.PortalSettings, true, false, 300, 650); + this.loginLink.Attributes.Add("onclick", clickEvent); + this.enhancedLoginLink.Attributes.Add("onclick", clickEvent); + } + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + } } } diff --git a/DNN Platform/Website/admin/Skins/Logo.ascx.cs b/DNN Platform/Website/admin/Skins/Logo.ascx.cs index 95196d3ae5e..a0868da4ed8 100644 --- a/DNN Platform/Website/admin/Skins/Logo.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Logo.ascx.cs @@ -1,24 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.WebControls; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web.UI.WebControls; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// /// @@ -27,56 +22,62 @@ namespace DotNetNuke.UI.Skins.Controls public partial class Logo : SkinObjectBase { private readonly INavigationManager _navigationManager; - public string BorderWidth { get; set; } - public string CssClass { get; set; } public Logo() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string BorderWidth { get; set; } + + public string CssClass { get; set; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { - if (!String.IsNullOrEmpty(BorderWidth)) + if (!string.IsNullOrEmpty(this.BorderWidth)) { - imgLogo.BorderWidth = Unit.Parse(BorderWidth); + this.imgLogo.BorderWidth = Unit.Parse(this.BorderWidth); } - if (!String.IsNullOrEmpty(CssClass)) + + if (!string.IsNullOrEmpty(this.CssClass)) { - imgLogo.CssClass = CssClass; + this.imgLogo.CssClass = this.CssClass; } + bool logoVisible = false; - if (!String.IsNullOrEmpty(PortalSettings.LogoFile)) + if (!string.IsNullOrEmpty(this.PortalSettings.LogoFile)) { - var fileInfo = GetLogoFileInfo(); + var fileInfo = this.GetLogoFileInfo(); if (fileInfo != null) { string imageUrl = FileManager.Instance.GetUrl(fileInfo); - if (!String.IsNullOrEmpty(imageUrl)) + if (!string.IsNullOrEmpty(imageUrl)) { - imgLogo.ImageUrl = imageUrl; + this.imgLogo.ImageUrl = imageUrl; logoVisible = true; } } } - imgLogo.Visible = logoVisible; - imgLogo.AlternateText = PortalSettings.PortalName; - hypLogo.ToolTip = PortalSettings.PortalName; + + this.imgLogo.Visible = logoVisible; + this.imgLogo.AlternateText = this.PortalSettings.PortalName; + this.hypLogo.ToolTip = this.PortalSettings.PortalName; - if (!imgLogo.Visible) + if (!this.imgLogo.Visible) { - hypLogo.Attributes.Add("aria-label", PortalSettings.PortalName); + this.hypLogo.Attributes.Add("aria-label", this.PortalSettings.PortalName); } - if (PortalSettings.HomeTabId != -1) + + if (this.PortalSettings.HomeTabId != -1) { - hypLogo.NavigateUrl = _navigationManager.NavigateURL(PortalSettings.HomeTabId); + this.hypLogo.NavigateUrl = this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId); } else { - hypLogo.NavigateUrl = Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias); + this.hypLogo.NavigateUrl = Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias); } } catch (Exception exc) @@ -87,16 +88,17 @@ protected override void OnLoad(EventArgs e) private IFileInfo GetLogoFileInfo() { - string cacheKey = String.Format(DataCache.PortalCacheKey, PortalSettings.PortalId, PortalSettings.CultureCode) + "LogoFile"; - var file = CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority), - GetLogoFileInfoCallBack); + string cacheKey = string.Format(DataCache.PortalCacheKey, this.PortalSettings.PortalId, this.PortalSettings.CultureCode) + "LogoFile"; + var file = CBO.GetCachedObject( + new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority), + this.GetLogoFileInfoCallBack); return file; } private IFileInfo GetLogoFileInfoCallBack(CacheItemArgs itemArgs) { - return FileManager.Instance.GetFile(PortalSettings.PortalId, PortalSettings.LogoFile); + return FileManager.Instance.GetFile(this.PortalSettings.PortalId, this.PortalSettings.LogoFile); } } } diff --git a/DNN Platform/Website/admin/Skins/Meta.ascx.cs b/DNN Platform/Website/admin/Skins/Meta.ascx.cs index f7f1ca57e1f..f6c596bb435 100644 --- a/DNN Platform/Website/admin/Skins/Meta.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Meta.ascx.cs @@ -1,21 +1,16 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI.HtmlControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web.UI.HtmlControls; + /// ----------------------------------------------------------------------------- - /// A skin object which enables adding a meta element to the head + /// A skin object which enables adding a meta element to the head. public partial class Meta : SkinObjectBase { - /// Backing field for + /// Backing field for . private readonly HttpPlaceholder http = new HttpPlaceholder(); /// @@ -25,10 +20,10 @@ public partial class Meta : SkinObjectBase /// public string Name { get; set; } - /// Gets or sets the content of the meta element + /// Gets or sets the content of the meta element. public string Content { get; set; } - /// Gets an object to set the property + /// Gets an object to set the property. public HttpPlaceholder Http { get { return this.http; } @@ -36,19 +31,19 @@ public HttpPlaceholder Http /// /// Gets or sets the http-equiv attribute of the meta element. - /// If specified, this is the name of the HTTP header that the + /// If specified, this is the name of the HTTP header that the /// meta /// The attribute is not rendered if it is not set. /// Either this or the must be set. /// - public string HttpEquiv + public string HttpEquiv { - get { return this.Http.Equiv; } - set { this.Http.Equiv = value; } + get { return this.Http.Equiv; } + set { this.Http.Equiv = value; } } /// - /// Gets or sets a value indicating whether to insert this meta + /// Gets or sets a value indicating whether to insert this meta /// element at the beginning of the head element, rather than the /// end. /// @@ -58,29 +53,37 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - //if(!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Content)) - //{ + // if(!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Content)) + // { // var metaTag = new HtmlMeta(); // metaTag.Name = Name; // metaTag.Content = Content; // Page.Header.Controls.Add(metaTag); - //} - - if ((!string.IsNullOrEmpty(Name) || !string.IsNullOrEmpty(HttpEquiv)) && !string.IsNullOrEmpty(Content)) + // } + if ((!string.IsNullOrEmpty(this.Name) || !string.IsNullOrEmpty(this.HttpEquiv)) && !string.IsNullOrEmpty(this.Content)) { var metaTag = new HtmlMeta(); - if (!string.IsNullOrEmpty(HttpEquiv)) - metaTag.HttpEquiv = HttpEquiv; - if (!string.IsNullOrEmpty(Name)) - metaTag.Name = Name; + if (!string.IsNullOrEmpty(this.HttpEquiv)) + { + metaTag.HttpEquiv = this.HttpEquiv; + } + + if (!string.IsNullOrEmpty(this.Name)) + { + metaTag.Name = this.Name; + } - metaTag.Content = Content; + metaTag.Content = this.Content; - if (InsertFirst) - Page.Header.Controls.AddAt(0, metaTag); + if (this.InsertFirst) + { + this.Page.Header.Controls.AddAt(0, metaTag); + } else - Page.Header.Controls.Add(metaTag); + { + this.Page.Header.Controls.Add(metaTag); + } } } @@ -89,11 +92,11 @@ protected override void OnPreRender(EventArgs e) /// the property via Http-Equiv syntax /// in Web Forms markup. ///
        - public class HttpPlaceholder + public class HttpPlaceholder { /// - /// Gets or sets the of the parent - /// meta element + /// Gets or sets the of the parent + /// meta element. /// public string Equiv { get; set; } } diff --git a/DNN Platform/Website/admin/Skins/Nav.ascx.cs b/DNN Platform/Website/admin/Skins/Nav.ascx.cs index 91f9f1f8955..26495940324 100644 --- a/DNN Platform/Website/admin/Skins/Nav.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Nav.ascx.cs @@ -1,163 +1,169 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Common; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.WebControls; + [Obsolete("Support was removed for SolPart & Similar Modules in DNN 8.x, this control is no-longer functional to that point. Usage of DDRMenu is suggested. Scheduled removal in v10.0.0.")] public partial class Nav : NavObjectBase { - private void InitializeComponent() - { - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { - bool blnIndicateChildren = bool.Parse(GetValue(IndicateChildren, "True")); + bool blnIndicateChildren = bool.Parse(this.GetValue(this.IndicateChildren, "True")); string strRightArrow; string strDownArrow; var objSkins = new SkinController(); - - //image for right facing arrow - if (!String.IsNullOrEmpty(IndicateChildImageSub)) + + // image for right facing arrow + if (!string.IsNullOrEmpty(this.IndicateChildImageSub)) { - strRightArrow = IndicateChildImageSub; + strRightArrow = this.IndicateChildImageSub; } else { - strRightArrow = "breadcrumb.gif"; //removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx + strRightArrow = "breadcrumb.gif"; // removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx } - - //image for down facing arrow - if (!String.IsNullOrEmpty(IndicateChildImageRoot)) + + // image for down facing arrow + if (!string.IsNullOrEmpty(this.IndicateChildImageRoot)) { - strDownArrow = IndicateChildImageRoot; + strDownArrow = this.IndicateChildImageRoot; } else { - strDownArrow = "menu_down.gif"; //removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx + strDownArrow = "menu_down.gif"; // removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx } - - //Set correct image path for all separator images - if (!String.IsNullOrEmpty(SeparatorHTML)) + + // Set correct image path for all separator images + if (!string.IsNullOrEmpty(this.SeparatorHTML)) { - SeparatorHTML = FixImagePath(SeparatorHTML); + this.SeparatorHTML = this.FixImagePath(this.SeparatorHTML); } - - if (!String.IsNullOrEmpty(SeparatorLeftHTML)) + + if (!string.IsNullOrEmpty(this.SeparatorLeftHTML)) { - SeparatorLeftHTML = FixImagePath(SeparatorLeftHTML); + this.SeparatorLeftHTML = this.FixImagePath(this.SeparatorLeftHTML); } - - if (!String.IsNullOrEmpty(SeparatorRightHTML)) + + if (!string.IsNullOrEmpty(this.SeparatorRightHTML)) { - SeparatorRightHTML = FixImagePath(SeparatorRightHTML); + this.SeparatorRightHTML = this.FixImagePath(this.SeparatorRightHTML); } - if (!String.IsNullOrEmpty(SeparatorLeftHTMLBreadCrumb)) + + if (!string.IsNullOrEmpty(this.SeparatorLeftHTMLBreadCrumb)) { - SeparatorLeftHTMLBreadCrumb = FixImagePath(SeparatorLeftHTMLBreadCrumb); + this.SeparatorLeftHTMLBreadCrumb = this.FixImagePath(this.SeparatorLeftHTMLBreadCrumb); } - - if (!String.IsNullOrEmpty(SeparatorRightHTMLBreadCrumb)) + + if (!string.IsNullOrEmpty(this.SeparatorRightHTMLBreadCrumb)) { - SeparatorRightHTMLBreadCrumb = FixImagePath(SeparatorRightHTMLBreadCrumb); + this.SeparatorRightHTMLBreadCrumb = this.FixImagePath(this.SeparatorRightHTMLBreadCrumb); } - - if (!String.IsNullOrEmpty(SeparatorLeftHTMLActive)) + + if (!string.IsNullOrEmpty(this.SeparatorLeftHTMLActive)) { - SeparatorLeftHTMLActive = FixImagePath(SeparatorLeftHTMLActive); + this.SeparatorLeftHTMLActive = this.FixImagePath(this.SeparatorLeftHTMLActive); } - - if (!String.IsNullOrEmpty(SeparatorRightHTMLActive)) + + if (!string.IsNullOrEmpty(this.SeparatorRightHTMLActive)) { - SeparatorRightHTMLActive = FixImagePath(SeparatorRightHTMLActive); + this.SeparatorRightHTMLActive = this.FixImagePath(this.SeparatorRightHTMLActive); } - - if (!String.IsNullOrEmpty(NodeLeftHTMLBreadCrumbRoot)) + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLBreadCrumbRoot)) { - NodeLeftHTMLBreadCrumbRoot = FixImagePath(NodeLeftHTMLBreadCrumbRoot); + this.NodeLeftHTMLBreadCrumbRoot = this.FixImagePath(this.NodeLeftHTMLBreadCrumbRoot); } - - if (!String.IsNullOrEmpty(NodeRightHTMLBreadCrumbRoot)) + + if (!string.IsNullOrEmpty(this.NodeRightHTMLBreadCrumbRoot)) { - NodeRightHTMLBreadCrumbRoot = FixImagePath(NodeRightHTMLBreadCrumbRoot); + this.NodeRightHTMLBreadCrumbRoot = this.FixImagePath(this.NodeRightHTMLBreadCrumbRoot); } - - if (!String.IsNullOrEmpty(NodeLeftHTMLBreadCrumbSub)) + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLBreadCrumbSub)) { - NodeLeftHTMLBreadCrumbSub = FixImagePath(NodeLeftHTMLBreadCrumbSub); + this.NodeLeftHTMLBreadCrumbSub = this.FixImagePath(this.NodeLeftHTMLBreadCrumbSub); } - - if (!String.IsNullOrEmpty(NodeRightHTMLBreadCrumbSub)) + + if (!string.IsNullOrEmpty(this.NodeRightHTMLBreadCrumbSub)) { - NodeRightHTMLBreadCrumbSub = FixImagePath(NodeRightHTMLBreadCrumbSub); + this.NodeRightHTMLBreadCrumbSub = this.FixImagePath(this.NodeRightHTMLBreadCrumbSub); } - - if (!String.IsNullOrEmpty(NodeLeftHTMLRoot)) + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLRoot)) { - NodeLeftHTMLRoot = FixImagePath(NodeLeftHTMLRoot); + this.NodeLeftHTMLRoot = this.FixImagePath(this.NodeLeftHTMLRoot); } - - if (!String.IsNullOrEmpty(NodeRightHTMLRoot)) + + if (!string.IsNullOrEmpty(this.NodeRightHTMLRoot)) { - NodeRightHTMLRoot = FixImagePath(NodeRightHTMLRoot); + this.NodeRightHTMLRoot = this.FixImagePath(this.NodeRightHTMLRoot); } - - if (!String.IsNullOrEmpty(NodeLeftHTMLSub)) + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLSub)) { - NodeLeftHTMLSub = FixImagePath(NodeLeftHTMLSub); + this.NodeLeftHTMLSub = this.FixImagePath(this.NodeLeftHTMLSub); } - - if (!String.IsNullOrEmpty(NodeRightHTMLSub)) + + if (!string.IsNullOrEmpty(this.NodeRightHTMLSub)) { - NodeRightHTMLSub = FixImagePath(NodeRightHTMLSub); + this.NodeRightHTMLSub = this.FixImagePath(this.NodeRightHTMLSub); } - - if (String.IsNullOrEmpty(PathImage)) + + if (string.IsNullOrEmpty(this.PathImage)) { - PathImage = PortalSettings.HomeDirectory; + this.PathImage = this.PortalSettings.HomeDirectory; } - + if (blnIndicateChildren) { - IndicateChildImageSub = strRightArrow; - if (ControlOrientation.ToLowerInvariant() == "vertical") + this.IndicateChildImageSub = strRightArrow; + if (this.ControlOrientation.ToLowerInvariant() == "vertical") { - IndicateChildImageRoot = strRightArrow; + this.IndicateChildImageRoot = strRightArrow; } else { - IndicateChildImageRoot = strDownArrow; + this.IndicateChildImageRoot = strDownArrow; } } else { - IndicateChildImageSub = "[APPIMAGEPATH]spacer.gif"; + this.IndicateChildImageSub = "[APPIMAGEPATH]spacer.gif"; } - - PathSystemScript = Globals.ApplicationPath + "/controls/SolpartMenu/"; - PathSystemImage = "[APPIMAGEPATH]"; - BuildNodes(null); + + this.PathSystemScript = Globals.ApplicationPath + "/controls/SolpartMenu/"; + this.PathSystemImage = "[APPIMAGEPATH]"; + this.BuildNodes(null); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } + + protected override void OnInit(EventArgs e) + { + this.InitializeNavControl(this, "SolpartMenuNavigationProvider"); + this.Control.NodeClick += this.Control_NodeClick; + this.Control.PopulateOnDemand += this.Control_PopulateOnDemand; + + base.OnInit(e); + this.InitializeComponent(); + } + + private void InitializeComponent() + { + } private string FixImagePath(string strPath) { @@ -174,37 +180,29 @@ private string FixImagePath(string strPath) private void BuildNodes(DNNNode objNode) { DNNNodeCollection objNodes; - objNodes = GetNavigationNodes(objNode); - Control.ClearNodes(); //since we always bind we need to clear the nodes for providers that maintain their state - Bind(objNodes); - } - - protected override void OnInit(EventArgs e) - { - InitializeNavControl(this, "SolpartMenuNavigationProvider"); - Control.NodeClick += Control_NodeClick; - Control.PopulateOnDemand += Control_PopulateOnDemand; - - base.OnInit(e); - InitializeComponent(); + objNodes = this.GetNavigationNodes(objNode); + this.Control.ClearNodes(); // since we always bind we need to clear the nodes for providers that maintain their state + this.Bind(objNodes); } private void Control_NodeClick(NavigationEventArgs args) { if (args.Node == null) { - args.Node = Navigation.GetNavigationNode(args.ID, Control.ID); + args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); + + this.Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); } private void Control_PopulateOnDemand(NavigationEventArgs args) { if (args.Node == null) { - args.Node = Navigation.GetNavigationNode(args.ID, Control.ID); + args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - BuildNodes(args.Node); + + this.BuildNodes(args.Node); } } } diff --git a/DNN Platform/Website/admin/Skins/Privacy.ascx.cs b/DNN Platform/Website/admin/Skins/Privacy.ascx.cs index 115fdd6e688..8532805db18 100644 --- a/DNN Platform/Website/admin/Skins/Privacy.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Privacy.ascx.cs @@ -1,21 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using System; -using Microsoft.Extensions.DependencyInjection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// /// @@ -23,26 +19,23 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- public partial class Privacy : SkinObjectBase { - private readonly INavigationManager _navigationManager; private const string MyFileName = "Privacy.ascx"; - public string Text { get; set; } - - public string CssClass { get; set; } + private readonly INavigationManager _navigationManager; public Privacy() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string Text { get; set; } - private void InitializeComponent() - { - } + public string CssClass { get; set; } protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) @@ -50,25 +43,31 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - hypPrivacy.CssClass = CssClass; + this.hypPrivacy.CssClass = this.CssClass; } - if (!String.IsNullOrEmpty(Text)) + + if (!string.IsNullOrEmpty(this.Text)) { - hypPrivacy.Text = Text; + this.hypPrivacy.Text = this.Text; } else { - hypPrivacy.Text = Localization.GetString("Privacy", Localization.GetResourceFile(this, MyFileName)); + this.hypPrivacy.Text = Localization.GetString("Privacy", Localization.GetResourceFile(this, MyFileName)); } - hypPrivacy.NavigateUrl = PortalSettings.PrivacyTabId == Null.NullInteger ? _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Privacy") : _navigationManager.NavigateURL(PortalSettings.PrivacyTabId); - hypPrivacy.Attributes["rel"] = "nofollow"; + + this.hypPrivacy.NavigateUrl = this.PortalSettings.PrivacyTabId == Null.NullInteger ? this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Privacy") : this._navigationManager.NavigateURL(this.PortalSettings.PrivacyTabId); + this.hypPrivacy.Attributes["rel"] = "nofollow"; } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/Search.ascx.cs b/DNN Platform/Website/admin/Skins/Search.ascx.cs index 82a6f3a43a6..c1b27a0bf2d 100644 --- a/DNN Platform/Website/admin/Skins/Search.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Search.ascx.cs @@ -1,39 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Icons; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Utilities; -using DotNetNuke.Web.Client; -using DotNetNuke.Web.Client.ClientResourceManagement; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections; -using Globals = DotNetNuke.Common.Globals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins.Controls { - - + using System; + using System.Collections; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Icons; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Utilities; + using DotNetNuke.Web.Client; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Microsoft.Extensions.DependencyInjection; + + using Globals = DotNetNuke.Common.Globals; + public partial class Search : SkinObjectBase { - private readonly INavigationManager _navigationManager; - public Search() - { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - #region Private Members - private const string MyFileName = "Search.ascx"; + + private readonly INavigationManager _navigationManager; private bool _showSite = true; private bool _showWeb = true; + + public Search() + { + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } private string _siteIconURL; private string _siteText; private string _siteToolTip; @@ -41,21 +40,19 @@ public Search() private string _webIconURL; private string _webText; private string _webToolTip; - private string _webURL; - - #endregion - - #region Public Members + private string _webURL; + private bool _enableWildSearch = true; + /// - /// Gets or sets the CSS class for the option buttons and search button + /// Gets or sets the CSS class for the option buttons and search button. /// /// If you are using the DropDownList option then you can style the search /// elements without requiring a custom CssClass. public string CssClass { get; set; } /// - /// Gets or sets the visibility setting for the radio button corresponding to site based searchs. + /// Gets or sets a value indicating whether gets or sets the visibility setting for the radio button corresponding to site based searchs. /// /// Set this value to false to hide the "Site" radio button. This setting has no effect /// if UseDropDownList is true. @@ -63,16 +60,17 @@ public bool ShowSite { get { - return _showSite; + return this._showSite; } + set { - _showSite = value; + this._showSite = value; } } /// - /// Gets or sets the visibility setting for the radio button corresponding to web based searchs. + /// Gets or sets a value indicating whether gets or sets the visibility setting for the radio button corresponding to web based searchs. /// /// Set this value to false to hide the "Web" radio button. This setting has no effect /// if UseDropDownList is true. @@ -80,11 +78,12 @@ public bool ShowWeb { get { - return _showWeb; + return this._showWeb; } + set { - _showWeb = value; + this._showWeb = value; } } @@ -99,15 +98,17 @@ public string SiteIconURL { get { - if (string.IsNullOrEmpty(_siteIconURL)) + if (string.IsNullOrEmpty(this._siteIconURL)) { return IconController.IconURL("DnnSearch"); } - return _siteIconURL; + + return this._siteIconURL; } + set { - _siteIconURL = value; + this._siteIconURL = value; } } @@ -153,15 +154,17 @@ public string SiteText { get { - if (string.IsNullOrEmpty(_siteText)) + if (string.IsNullOrEmpty(this._siteText)) { return Localization.GetString("Site", Localization.GetResourceFile(this, MyFileName)); } - return _siteText; + + return this._siteText; } + set { - _siteText = value; + this._siteText = value; } } @@ -175,15 +178,17 @@ public string SiteToolTip { get { - if (string.IsNullOrEmpty(_siteToolTip)) + if (string.IsNullOrEmpty(this._siteToolTip)) { return Localization.GetString("Site.ToolTip", Localization.GetResourceFile(this, MyFileName)); } - return _siteToolTip; + + return this._siteToolTip; } + set { - _siteToolTip = value; + this._siteToolTip = value; } } @@ -199,15 +204,17 @@ public string SiteURL { get { - if (string.IsNullOrEmpty(_siteURL)) + if (string.IsNullOrEmpty(this._siteURL)) { return Localization.GetString("URL", Localization.GetResourceFile(this, MyFileName)); } - return _siteURL; + + return this._siteURL; } + set { - _siteURL = value; + this._siteURL = value; } } @@ -245,15 +252,17 @@ public string WebIconURL { get { - if (string.IsNullOrEmpty(_webIconURL)) + if (string.IsNullOrEmpty(this._webIconURL)) { return IconController.IconURL("GoogleSearch"); } - return _webIconURL; + + return this._webIconURL; } + set { - _webIconURL = value; + this._webIconURL = value; } } @@ -267,15 +276,17 @@ public string WebText { get { - if (string.IsNullOrEmpty(_webText)) + if (string.IsNullOrEmpty(this._webText)) { return Localization.GetString("Web", Localization.GetResourceFile(this, MyFileName)); } - return _webText; + + return this._webText; } + set { - _webText = value; + this._webText = value; } } @@ -289,15 +300,17 @@ public string WebToolTip { get { - if (string.IsNullOrEmpty(_webToolTip)) + if (string.IsNullOrEmpty(this._webToolTip)) { return Localization.GetString("Web.ToolTip", Localization.GetResourceFile(this, MyFileName)); } - return _webToolTip; + + return this._webToolTip; } + set { - _webToolTip = value; + this._webToolTip = value; } } @@ -314,68 +327,44 @@ public string WebURL { get { - if (string.IsNullOrEmpty(_webURL)) + if (string.IsNullOrEmpty(this._webURL)) { return Localization.GetString("URL", Localization.GetResourceFile(this, MyFileName)); } - return _webURL; + + return this._webURL; } + set { - _webURL = value; + this._webURL = value; } } /// - /// minium chars required to trigger auto search + /// Gets or sets minium chars required to trigger auto search. /// public int MinCharRequired { get; set; } /// - /// The millisecond to delay trigger auto search + /// Gets or sets the millisecond to delay trigger auto search. /// public int AutoSearchDelayInMilliSecond { get; set; } - - private bool _enableWildSearch = true; + /// - /// Disable the wild search + /// Gets or sets a value indicating whether disable the wild search. /// - public bool EnableWildSearch { get { return _enableWildSearch; } set { _enableWildSearch = value; } } + public bool EnableWildSearch + { + get { return this._enableWildSearch; } + set { this._enableWildSearch = value; } + } protected int PortalId { get; set; } protected string SearchType { get; set; } - protected string CultureCode { get; set; } - - #endregion - - #region Private Methods - - private int GetSearchTabId() - { - int searchTabId = PortalSettings.SearchTabId; - if (searchTabId == Null.NullInteger) - { - ArrayList arrModules = ModuleController.Instance.GetModulesByDefinition(PortalSettings.PortalId, "Search Results"); - if (arrModules.Count > 1) - { - foreach (ModuleInfo SearchModule in arrModules) - { - if (SearchModule.CultureCode == PortalSettings.CultureCode) - { - searchTabId = SearchModule.TabID; - } - } - } - else if (arrModules.Count == 1) - { - searchTabId = ((ModuleInfo)arrModules[0]).TabID; - } - } - - return searchTabId; - } + protected string CultureCode { get; set; } /// /// Executes the search. @@ -388,12 +377,13 @@ private int GetSearchTabId() /// protected void ExecuteSearch(string searchText, string searchType) { - int searchTabId = GetSearchTabId(); + int searchTabId = this.GetSearchTabId(); if (searchTabId == Null.NullInteger) { return; } + string strURL; if (!string.IsNullOrEmpty(searchText)) { @@ -401,37 +391,39 @@ protected void ExecuteSearch(string searchText, string searchType) { case "S": // site - if (UseWebForSite) + if (this.UseWebForSite) { - strURL = SiteURL; + strURL = this.SiteURL; if (!string.IsNullOrEmpty(strURL)) { - strURL = strURL.Replace("[TEXT]", Server.UrlEncode(searchText)); - strURL = strURL.Replace("[DOMAIN]", Request.Url.Host); - UrlUtils.OpenNewWindow(Page, GetType(), strURL); + strURL = strURL.Replace("[TEXT]", this.Server.UrlEncode(searchText)); + strURL = strURL.Replace("[DOMAIN]", this.Request.Url.Host); + UrlUtils.OpenNewWindow(this.Page, this.GetType(), strURL); } } else { if (Host.UseFriendlyUrls) { - Response.Redirect(_navigationManager.NavigateURL(searchTabId) + "?Search=" + Server.UrlEncode(searchText)); + this.Response.Redirect(this._navigationManager.NavigateURL(searchTabId) + "?Search=" + this.Server.UrlEncode(searchText)); } else { - Response.Redirect(_navigationManager.NavigateURL(searchTabId) + "&Search=" + Server.UrlEncode(searchText)); + this.Response.Redirect(this._navigationManager.NavigateURL(searchTabId) + "&Search=" + this.Server.UrlEncode(searchText)); } } + break; case "W": // web - strURL = WebURL; + strURL = this.WebURL; if (!string.IsNullOrEmpty(strURL)) { - strURL = strURL.Replace("[TEXT]", Server.UrlEncode(searchText)); - strURL = strURL.Replace("[DOMAIN]", ""); - UrlUtils.OpenNewWindow(Page, GetType(), strURL); + strURL = strURL.Replace("[TEXT]", this.Server.UrlEncode(searchText)); + strURL = strURL.Replace("[DOMAIN]", string.Empty); + UrlUtils.OpenNewWindow(this.Page, this.GetType(), strURL); } + break; } } @@ -439,19 +431,15 @@ protected void ExecuteSearch(string searchText, string searchType) { if (Host.UseFriendlyUrls) { - Response.Redirect(_navigationManager.NavigateURL(searchTabId)); + this.Response.Redirect(this._navigationManager.NavigateURL(searchTabId)); } else { - Response.Redirect(_navigationManager.NavigateURL(searchTabId)); + this.Response.Redirect(this._navigationManager.NavigateURL(searchTabId)); } } - } - - #endregion - - #region Event Handlers - + } + /// /// Handles the Load event of the Page control. /// @@ -461,57 +449,71 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Search/SearchSkinObjectPreview.css", FileOrder.Css.ModuleCss); - ClientResourceManager.RegisterScript(Page, "~/Resources/Search/SearchSkinObjectPreview.js"); - - - cmdSearch.Click += CmdSearchClick; - cmdSearchNew.Click += CmdSearchNewClick; - - if (MinCharRequired == 0) MinCharRequired = 2; - if (AutoSearchDelayInMilliSecond == 0) AutoSearchDelayInMilliSecond = 400; - PortalId = PortalSettings.ActiveTab.IsSuperTab ? PortalSettings.PortalId : -1; - - if (!String.IsNullOrEmpty(Submit)) - { - if (Submit.IndexOf("src=", StringComparison.Ordinal) != -1) + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Search/SearchSkinObjectPreview.css", FileOrder.Css.ModuleCss); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Search/SearchSkinObjectPreview.js"); + + this.cmdSearch.Click += this.CmdSearchClick; + this.cmdSearchNew.Click += this.CmdSearchNewClick; + + if (this.MinCharRequired == 0) + { + this.MinCharRequired = 2; + } + + if (this.AutoSearchDelayInMilliSecond == 0) + { + this.AutoSearchDelayInMilliSecond = 400; + } + + this.PortalId = this.PortalSettings.ActiveTab.IsSuperTab ? this.PortalSettings.PortalId : -1; + + if (!string.IsNullOrEmpty(this.Submit)) + { + if (this.Submit.IndexOf("src=", StringComparison.Ordinal) != -1) { - Submit = Submit.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); - Submit = Submit.Replace("src='", "src='" + PortalSettings.ActiveTab.SkinPath); + this.Submit = this.Submit.Replace("src=\"", "src=\"" + this.PortalSettings.ActiveTab.SkinPath); + this.Submit = this.Submit.Replace("src='", "src='" + this.PortalSettings.ActiveTab.SkinPath); } } else { - Submit = Localization.GetString("Search", Localization.GetResourceFile(this, MyFileName)); + this.Submit = Localization.GetString("Search", Localization.GetResourceFile(this, MyFileName)); } - cmdSearch.Text = Submit; - cmdSearchNew.Text = Submit; - if (!String.IsNullOrEmpty(CssClass)) + + this.cmdSearch.Text = this.Submit; + this.cmdSearchNew.Text = this.Submit; + if (!string.IsNullOrEmpty(this.CssClass)) { - WebRadioButton.CssClass = CssClass; - SiteRadioButton.CssClass = CssClass; - cmdSearch.CssClass = CssClass; - cmdSearchNew.CssClass = CssClass; + this.WebRadioButton.CssClass = this.CssClass; + this.SiteRadioButton.CssClass = this.CssClass; + this.cmdSearch.CssClass = this.CssClass; + this.cmdSearchNew.CssClass = this.CssClass; } } - - /// - /// Handles the Click event of the cmdSearch control. - /// - /// The source of the event. - /// The instance containing the event data. - /// This event is only used when UseDropDownList is false. - private void CmdSearchClick(object sender, EventArgs e) + + private int GetSearchTabId() { - SearchType = "S"; - if (WebRadioButton.Visible) + int searchTabId = this.PortalSettings.SearchTabId; + if (searchTabId == Null.NullInteger) { - if (WebRadioButton.Checked) + ArrayList arrModules = ModuleController.Instance.GetModulesByDefinition(this.PortalSettings.PortalId, "Search Results"); + if (arrModules.Count > 1) + { + foreach (ModuleInfo SearchModule in arrModules) + { + if (SearchModule.CultureCode == this.PortalSettings.CultureCode) + { + searchTabId = SearchModule.TabID; + } + } + } + else if (arrModules.Count == 1) { - SearchType = "W"; + searchTabId = ((ModuleInfo)arrModules[0]).TabID; } } - ExecuteSearch(txtSearch.Text.Trim(), SearchType); + + return searchTabId; } /// @@ -522,8 +524,8 @@ private void CmdSearchClick(object sender, EventArgs e) /// This event is only used when UseDropDownList is true. protected void CmdSearchNewClick(object sender, EventArgs e) { - SearchType = ClientAPI.GetClientVariable(Page, "SearchIconSelected"); - ExecuteSearch(txtSearchNew.Text.Trim(), SearchType); + this.SearchType = ClientAPI.GetClientVariable(this.Page, "SearchIconSelected"); + this.ExecuteSearch(this.txtSearchNew.Text.Trim(), this.SearchType); } /// @@ -535,57 +537,75 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - ClassicSearch.Visible = !UseDropDownList; - DropDownSearch.Visible = UseDropDownList; - CultureCode = System.Threading.Thread.CurrentThread.CurrentCulture.ToString(); + this.ClassicSearch.Visible = !this.UseDropDownList; + this.DropDownSearch.Visible = this.UseDropDownList; + this.CultureCode = System.Threading.Thread.CurrentThread.CurrentCulture.ToString(); - if (UseDropDownList) + if (this.UseDropDownList) { - //Client Variables will survive a postback so there is no reason to register them. - if (!Page.IsPostBack) + // Client Variables will survive a postback so there is no reason to register them. + if (!this.Page.IsPostBack) { + this.downArrow.AlternateText = Localization.GetString("DropDownGlyph.AltText", Localization.GetResourceFile(this, MyFileName)); + this.downArrow.ToolTip = this.downArrow.AlternateText; - downArrow.AlternateText = Localization.GetString("DropDownGlyph.AltText", Localization.GetResourceFile(this, MyFileName)); - downArrow.ToolTip = downArrow.AlternateText; - - ClientAPI.RegisterClientVariable(Page, "SearchIconWebUrl", string.Format("url({0})", ResolveUrl(WebIconURL)), true); - ClientAPI.RegisterClientVariable(Page, "SearchIconSiteUrl", string.Format("url({0})", ResolveUrl(SiteIconURL)), true); + ClientAPI.RegisterClientVariable(this.Page, "SearchIconWebUrl", string.Format("url({0})", this.ResolveUrl(this.WebIconURL)), true); + ClientAPI.RegisterClientVariable(this.Page, "SearchIconSiteUrl", string.Format("url({0})", this.ResolveUrl(this.SiteIconURL)), true); - //We are going to use a dnn client variable to store which search option (web/site) is selected. - ClientAPI.RegisterClientVariable(Page, "SearchIconSelected", "S", true); - SearchType = "S"; + // We are going to use a dnn client variable to store which search option (web/site) is selected. + ClientAPI.RegisterClientVariable(this.Page, "SearchIconSelected", "S", true); + this.SearchType = "S"; } JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn); - ClientResourceManager.RegisterScript(Page, "~/Resources/Search/Search.js", FileOrder.Js.DefaultPriority, "DnnFormBottomProvider"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Search/Search.js", FileOrder.Js.DefaultPriority, "DnnFormBottomProvider"); - txtSearchNew.Attributes.Add("autocomplete", "off"); - txtSearchNew.Attributes.Add("placeholder", PlaceHolderText); + this.txtSearchNew.Attributes.Add("autocomplete", "off"); + this.txtSearchNew.Attributes.Add("placeholder", this.PlaceHolderText); } else { - WebRadioButton.Visible = ShowWeb; - SiteRadioButton.Visible = ShowSite; + this.WebRadioButton.Visible = this.ShowWeb; + this.SiteRadioButton.Visible = this.ShowSite; - if (WebRadioButton.Visible) + if (this.WebRadioButton.Visible) { - WebRadioButton.Checked = true; - WebRadioButton.Text = WebText; - WebRadioButton.ToolTip = WebToolTip; + this.WebRadioButton.Checked = true; + this.WebRadioButton.Text = this.WebText; + this.WebRadioButton.ToolTip = this.WebToolTip; } - if (SiteRadioButton.Visible) + + if (this.SiteRadioButton.Visible) { - SiteRadioButton.Checked = true; - SiteRadioButton.Text = SiteText; - SiteRadioButton.ToolTip = SiteToolTip; + this.SiteRadioButton.Checked = true; + this.SiteRadioButton.Text = this.SiteText; + this.SiteRadioButton.ToolTip = this.SiteToolTip; } - SearchType = "S"; - txtSearch.Attributes.Add("autocomplete", "off"); - txtSearch.Attributes.Add("placeholder", PlaceHolderText); + this.SearchType = "S"; + this.txtSearch.Attributes.Add("autocomplete", "off"); + this.txtSearch.Attributes.Add("placeholder", this.PlaceHolderText); } - } + } - #endregion + /// + /// Handles the Click event of the cmdSearch control. + /// + /// The source of the event. + /// The instance containing the event data. + /// This event is only used when UseDropDownList is false. + private void CmdSearchClick(object sender, EventArgs e) + { + this.SearchType = "S"; + if (this.WebRadioButton.Visible) + { + if (this.WebRadioButton.Checked) + { + this.SearchType = "W"; + } + } + + this.ExecuteSearch(this.txtSearch.Text.Trim(), this.SearchType); + } } } diff --git a/DNN Platform/Website/admin/Skins/Styles.ascx.cs b/DNN Platform/Website/admin/Skins/Styles.ascx.cs index 3806c81d75b..ac8ac324c77 100644 --- a/DNN Platform/Website/admin/Skins/Styles.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Styles.ascx.cs @@ -1,20 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Web.UI.WebControls; - -using DotNetNuke.Common; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Web.UI.WebControls; + + using DotNetNuke.Common; + public partial class Styles : SkinObjectBase { private bool _useSkinPath = true; @@ -31,11 +26,12 @@ public bool UseSkinPath { get { - return _useSkinPath; + return this._useSkinPath; } + set { - _useSkinPath = value; + this._useSkinPath = value; } } @@ -44,36 +40,38 @@ public bool UseSkinPath protected override void OnLoad(EventArgs e) { base.OnLoad(e); - AddStyleSheet(); + this.AddStyleSheet(); } protected void AddStyleSheet() { - //Find the placeholder control - Control objCSS = Page.FindControl("CSS"); + // Find the placeholder control + Control objCSS = this.Page.FindControl("CSS"); if (objCSS != null) { - //First see if we have already added the control - Control objCtrl = Page.Header.FindControl(ID); + // First see if we have already added the control + Control objCtrl = this.Page.Header.FindControl(this.ID); if (objCtrl == null) { string skinpath = string.Empty; - if (UseSkinPath) + if (this.UseSkinPath) { - skinpath = ((Skin) Parent).SkinPath; + skinpath = ((Skin)this.Parent).SkinPath; } + var objLink = new HtmlLink(); - objLink.ID = Globals.CreateValidID(Name); + objLink.ID = Globals.CreateValidID(this.Name); objLink.Attributes["rel"] = "stylesheet"; objLink.Attributes["type"] = "text/css"; - objLink.Href = skinpath + StyleSheet; - if (Media != "") + objLink.Href = skinpath + this.StyleSheet; + if (this.Media != string.Empty) { - objLink.Attributes["media"] = Media; //NWS: add support for "media" attribute + objLink.Attributes["media"] = this.Media; // NWS: add support for "media" attribute } - if (IsFirst) + + if (this.IsFirst) { - //Find the first HtmlLink + // Find the first HtmlLink int iLink; for (iLink = 0; iLink <= objCSS.Controls.Count - 1; iLink++) { @@ -82,11 +80,12 @@ protected void AddStyleSheet() break; } } - AddLink(objCSS, iLink, objLink); + + this.AddLink(objCSS, iLink, objLink); } else { - AddLink(objCSS, -1, objLink); + this.AddLink(objCSS, -1, objLink); } } } @@ -94,7 +93,7 @@ protected void AddStyleSheet() protected void AddLink(Control cssRoot, int InsertAt, HtmlLink link) { - if (string.IsNullOrEmpty(Condition)) + if (string.IsNullOrEmpty(this.Condition)) { if (InsertAt == -1) { @@ -108,7 +107,7 @@ protected void AddLink(Control cssRoot, int InsertAt, HtmlLink link) else { var openif = new Literal(); - openif.Text = string.Format(""; if (InsertAt == -1) @@ -119,8 +118,8 @@ protected void AddLink(Control cssRoot, int InsertAt, HtmlLink link) } else { - //Since we want to add at a specific location, we do this in reverse order - //this allows us to use the same insertion point + // Since we want to add at a specific location, we do this in reverse order + // this allows us to use the same insertion point cssRoot.Controls.AddAt(InsertAt, closeif); cssRoot.Controls.AddAt(InsertAt, link); cssRoot.Controls.AddAt(InsertAt, openif); diff --git a/DNN Platform/Website/admin/Skins/Terms.ascx.cs b/DNN Platform/Website/admin/Skins/Terms.ascx.cs index 08d7a785817..2c3603def92 100644 --- a/DNN Platform/Website/admin/Skins/Terms.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Terms.ascx.cs @@ -1,21 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using System; -using Microsoft.Extensions.DependencyInjection; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// /// @@ -23,26 +19,23 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- public partial class Terms : SkinObjectBase { - private readonly INavigationManager _navigationManager; private const string MyFileName = "Terms.ascx"; - public string Text { get; set; } - - public string CssClass { get; set; } + private readonly INavigationManager _navigationManager; public Terms() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string Text { get; set; } - private void InitializeComponent() - { - } + public string CssClass { get; set; } protected override void OnInit(EventArgs e) { base.OnInit(e); - InitializeComponent(); + this.InitializeComponent(); } protected override void OnLoad(EventArgs e) @@ -50,26 +43,32 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - if (!String.IsNullOrEmpty(CssClass)) + if (!string.IsNullOrEmpty(this.CssClass)) { - hypTerms.CssClass = CssClass; + this.hypTerms.CssClass = this.CssClass; } - if (!String.IsNullOrEmpty(Text)) + + if (!string.IsNullOrEmpty(this.Text)) { - hypTerms.Text = Text; + this.hypTerms.Text = this.Text; } else { - hypTerms.Text = Localization.GetString("Terms", Localization.GetResourceFile(this, MyFileName)); + this.hypTerms.Text = Localization.GetString("Terms", Localization.GetResourceFile(this, MyFileName)); } - hypTerms.NavigateUrl = PortalSettings.TermsTabId == Null.NullInteger ? _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Terms") : _navigationManager.NavigateURL(PortalSettings.TermsTabId); + + this.hypTerms.NavigateUrl = this.PortalSettings.TermsTabId == Null.NullInteger ? this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Terms") : this._navigationManager.NavigateURL(this.PortalSettings.TermsTabId); - hypTerms.Attributes["rel"] = "nofollow"; + this.hypTerms.Attributes["rel"] = "nofollow"; } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/Text.ascx.cs b/DNN Platform/Website/admin/Skins/Text.ascx.cs index 0c2f6d6c396..74709a348ec 100644 --- a/DNN Platform/Website/admin/Skins/Text.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Text.ascx.cs @@ -1,19 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; - -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Tokens; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.IO; + + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Tokens; + public partial class Text : SkinObjectBase { public string ShowText { get; set; } @@ -27,38 +22,39 @@ public partial class Text : SkinObjectBase protected override void OnLoad(EventArgs e) { base.OnLoad(e); - string strText = ShowText; - - //load resources - if (!String.IsNullOrEmpty(ResourceKey)) + string strText = this.ShowText; + + // load resources + if (!string.IsNullOrEmpty(this.ResourceKey)) { - //localization - string strFile = Path.GetFileName(Server.MapPath(PortalSettings.ActiveTab.SkinSrc)); - strFile = PortalSettings.ActiveTab.SkinPath + Localization.LocalResourceDirectory + "/" + strFile; - string strLocalization = Localization.GetString(ResourceKey, strFile); - if (!String.IsNullOrEmpty(strLocalization)) + // localization + string strFile = Path.GetFileName(this.Server.MapPath(this.PortalSettings.ActiveTab.SkinSrc)); + strFile = this.PortalSettings.ActiveTab.SkinPath + Localization.LocalResourceDirectory + "/" + strFile; + string strLocalization = Localization.GetString(this.ResourceKey, strFile); + if (!string.IsNullOrEmpty(strLocalization)) { strText = strLocalization; } } - - //If no value is found then use the value set the the Text attribute + + // If no value is found then use the value set the the Text attribute if (string.IsNullOrEmpty(strText)) { - strText = ShowText; + strText = this.ShowText; } - - //token replace - if (ReplaceTokens) + + // token replace + if (this.ReplaceTokens) { var tr = new TokenReplace(); - tr.AccessingUser = PortalSettings.UserInfo; + tr.AccessingUser = this.PortalSettings.UserInfo; strText = tr.ReplaceEnvironmentTokens(strText); } - lblText.Text = strText; - if (!String.IsNullOrEmpty(CssClass)) + + this.lblText.Text = strText; + if (!string.IsNullOrEmpty(this.CssClass)) { - lblText.CssClass = CssClass; + this.lblText.CssClass = this.CssClass; } } } diff --git a/DNN Platform/Website/admin/Skins/Toast.ascx.cs b/DNN Platform/Website/admin/Skins/Toast.ascx.cs index db04e09c85b..72c2a3a4483 100644 --- a/DNN Platform/Website/admin/Skins/Toast.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Toast.ascx.cs @@ -1,61 +1,57 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Client.ClientResourceManagement; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Client.ClientResourceManagement; + using Microsoft.Extensions.DependencyInjection; + public partial class Toast : SkinObjectBase { - private readonly INavigationManager _navigationManager; + private const string MyFileName = "Toast.ascx"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Toast)); private static readonly string ToastCacheKey = "DNN_Toast_Config"; + private readonly INavigationManager _navigationManager; - private const string MyFileName = "Toast.ascx"; + public Toast() + { + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } protected string ServiceModuleName { get; private set; } protected string ServiceAction { get; private set; } - public Toast() - { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); - } - public bool IsOnline() { - var userInfo = UserController.Instance.GetCurrentUserInfo(); - return userInfo.UserID != -1; + var userInfo = UserController.Instance.GetCurrentUserInfo(); + return userInfo.UserID != -1; } public string GetNotificationLink() { - return GetMessageLink() + "?view=notifications&action=notifications"; + return this.GetMessageLink() + "?view=notifications&action=notifications"; } public string GetMessageLink() { - return _navigationManager.NavigateURL(GetMessageTab(), "", string.Format("userId={0}", PortalSettings.UserId)); + return this._navigationManager.NavigateURL(this.GetMessageTab(), string.Empty, string.Format("userId={0}", this.PortalSettings.UserId)); } public string GetMessageLabel() @@ -68,30 +64,45 @@ public string GetNotificationLabel() return Localization.GetString("SeeAllNotification", Localization.GetResourceFile(this, MyFileName)); } - //This method is copied from user skin object + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + JavaScript.RequestRegistration(CommonJs.jQueryUI); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.js", DotNetNuke.Web.Client.FileOrder.Js.jQuery); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.css", DotNetNuke.Web.Client.FileOrder.Css.DefaultCss); + + this.InitializeConfig(); + } + + // This method is copied from user skin object private int GetMessageTab() { - var cacheKey = string.Format("MessageCenterTab:{0}:{1}", PortalSettings.PortalId, PortalSettings.CultureCode); + var cacheKey = string.Format("MessageCenterTab:{0}:{1}", this.PortalSettings.PortalId, this.PortalSettings.CultureCode); var messageTabId = DataCache.GetCache(cacheKey); if (messageTabId > 0) + { return messageTabId; + } - //Find the Message Tab - messageTabId = FindMessageTab(); + // Find the Message Tab + messageTabId = this.FindMessageTab(); - //save in cache - //NOTE - This cache is not being cleared. There is no easy way to clear this, except Tools->Clear Cache + // save in cache + // NOTE - This cache is not being cleared. There is no easy way to clear this, except Tools->Clear Cache DataCache.SetCache(cacheKey, messageTabId, TimeSpan.FromMinutes(20)); return messageTabId; } - //This method is copied from user skin object + // This method is copied from user skin object private int FindMessageTab() { - //On brand new install the new Message Center Module is on the child page of User Profile Page - //On Upgrade to 6.2.0, the Message Center module is on the User Profile Page - var profileTab = TabController.Instance.GetTab(PortalSettings.UserTabId, PortalSettings.PortalId, false); + // On brand new install the new Message Center Module is on the child page of User Profile Page + // On Upgrade to 6.2.0, the Message Center module is on the User Profile Page + var profileTab = TabController.Instance.GetTab(this.PortalSettings.UserTabId, this.PortalSettings.PortalId, false); if (profileTab != null) { var childTabs = TabController.Instance.GetTabsByPortal(profileTab.PortalID).DescendentsOf(profileTab.TabID); @@ -102,41 +113,28 @@ private int FindMessageTab() var module = kvp.Value; if (module.DesktopModule.FriendlyName == "Message Center") { - return tab.TabID; + return tab.TabID; } } } } - //default to User Profile Page - return PortalSettings.UserTabId; - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - JavaScript.RequestRegistration(CommonJs.jQueryUI); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - - ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.js", DotNetNuke.Web.Client.FileOrder.Js.jQuery); - ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.css", DotNetNuke.Web.Client.FileOrder.Css.DefaultCss); - - InitializeConfig(); + // default to User Profile Page + return this.PortalSettings.UserTabId; } private void InitializeConfig() { - ServiceModuleName = "InternalServices"; - ServiceAction = "NotificationsService/GetToasts"; + this.ServiceModuleName = "InternalServices"; + this.ServiceAction = "NotificationsService/GetToasts"; try { var toastConfig = DataCache.GetCache>(ToastCacheKey); if (toastConfig == null) { - var configFile = Server.MapPath(Path.Combine(TemplateSourceDirectory, "Toast.config")); - + var configFile = this.Server.MapPath(Path.Combine(this.TemplateSourceDirectory, "Toast.config")); + if (File.Exists(configFile)) { var xmlDocument = new XmlDocument { XmlResolver = null }; @@ -147,26 +145,26 @@ private void InitializeConfig() if (moduleNameNode != null && !string.IsNullOrEmpty(moduleNameNode.InnerText)) { - ServiceModuleName = moduleNameNode.InnerText; + this.ServiceModuleName = moduleNameNode.InnerText; } if (actionNode != null && !string.IsNullOrEmpty(actionNode.InnerText)) { - ServiceAction = actionNode.InnerText; + this.ServiceAction = actionNode.InnerText; } if (scriptsNode != null && !string.IsNullOrEmpty(scriptsNode.InnerText)) { - addtionalScripts.Text = scriptsNode.InnerText; - addtionalScripts.Visible = true; + this.addtionalScripts.Text = scriptsNode.InnerText; + this.addtionalScripts.Visible = true; } } var config = new Dictionary() { - {"ServiceModuleName", ServiceModuleName }, - {"ServiceAction", ServiceAction }, - {"AddtionalScripts", addtionalScripts.Text }, + { "ServiceModuleName", this.ServiceModuleName }, + { "ServiceAction", this.ServiceAction }, + { "AddtionalScripts", this.addtionalScripts.Text }, }; DataCache.SetCache(ToastCacheKey, config); } @@ -174,18 +172,18 @@ private void InitializeConfig() { if (!string.IsNullOrEmpty(toastConfig["ServiceModuleName"])) { - ServiceModuleName = toastConfig["ServiceModuleName"]; + this.ServiceModuleName = toastConfig["ServiceModuleName"]; } if (!string.IsNullOrEmpty(toastConfig["ServiceAction"])) { - ServiceAction = toastConfig["ServiceAction"]; + this.ServiceAction = toastConfig["ServiceAction"]; } if (!string.IsNullOrEmpty(toastConfig["AddtionalScripts"])) { - addtionalScripts.Text = toastConfig["AddtionalScripts"]; - addtionalScripts.Visible = true; + this.addtionalScripts.Text = toastConfig["AddtionalScripts"]; + this.addtionalScripts.Visible = true; } } } diff --git a/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs b/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs index 63f2734f1e5..3e84895408a 100644 --- a/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs +++ b/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs @@ -1,40 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; - -using DotNetNuke.Common; -using DotNetNuke.Modules.NavigationProvider; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.WebControls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { - /// ----------------------------------------------------------------------------- - /// Project : DotNetNuke - /// Class : TreeViewMenu - /// ----------------------------------------------------------------------------- - /// - /// TreeViewMenu is a Skin Object that creates a Menu using the DNN Treeview Control - /// to provide a Windows Explore like Menu. - /// - /// - /// ----------------------------------------------------------------------------- + using System; + + using DotNetNuke.Common; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.WebControls; + + /// ----------------------------------------------------------------------------- + /// Project : DotNetNuke + /// Class : TreeViewMenu + /// ----------------------------------------------------------------------------- + /// + /// TreeViewMenu is a Skin Object that creates a Menu using the DNN Treeview Control + /// to provide a Windows Explore like Menu. + /// + /// + /// ----------------------------------------------------------------------------- public partial class TreeViewMenu : NavObjectBase - { - #region "Private Members" - + { private const string MyFileName = "TreeViewMenu.ascx"; - private string _bodyCssClass = ""; - private string _cssClass = ""; - private string _headerCssClass = ""; - private string _headerText = ""; + private string _bodyCssClass = string.Empty; + private string _cssClass = string.Empty; + private string _headerCssClass = string.Empty; + private string _headerText = string.Empty; private string _headerTextCssClass = "Head"; private bool _includeHeader = true; private string _nodeChildCssClass = "Normal"; @@ -46,25 +39,30 @@ public partial class TreeViewMenu : NavObjectBase private string _nodeOpenImage = "~/images/folderopen.gif"; private string _nodeOverCssClass = "Normal"; private string _nodeSelectedCssClass = "Normal"; - private string _resourceKey = ""; - private string _treeCssClass = ""; + private string _resourceKey = string.Empty; + private string _treeCssClass = string.Empty; private string _treeGoUpImage = "~/images/folderup.gif"; private int _treeIndentWidth = 10; - private string _width = "100%"; - - #endregion - - #region "Public Properties" - + private string _width = "100%"; + + private enum eImageType + { + FolderClosed = 0, + FolderOpen = 1, + Page = 2, + GotoParent = 3, + } + public string BodyCssClass { get { - return _bodyCssClass; + return this._bodyCssClass; } + set { - _bodyCssClass = value; + this._bodyCssClass = value; } } @@ -72,11 +70,12 @@ public string CssClass { get { - return _cssClass; + return this._cssClass; } + set { - _cssClass = value; + this._cssClass = value; } } @@ -84,11 +83,12 @@ public string HeaderCssClass { get { - return _headerCssClass; + return this._headerCssClass; } + set { - _headerCssClass = value; + this._headerCssClass = value; } } @@ -96,11 +96,12 @@ public string HeaderTextCssClass { get { - return _headerTextCssClass; + return this._headerTextCssClass; } + set { - _headerTextCssClass = value; + this._headerTextCssClass = value; } } @@ -108,11 +109,12 @@ public string HeaderText { get { - return _headerText; + return this._headerText; } + set { - _headerText = value; + this._headerText = value; } } @@ -120,11 +122,12 @@ public bool IncludeHeader { get { - return _includeHeader; + return this._includeHeader; } + set { - _includeHeader = value; + this._includeHeader = value; } } @@ -132,11 +135,12 @@ public string NodeChildCssClass { get { - return _nodeChildCssClass; + return this._nodeChildCssClass; } + set { - _nodeChildCssClass = value; + this._nodeChildCssClass = value; } } @@ -144,11 +148,12 @@ public string NodeClosedImage { get { - return _nodeClosedImage; + return this._nodeClosedImage; } + set { - _nodeClosedImage = value; + this._nodeClosedImage = value; } } @@ -156,11 +161,12 @@ public string NodeCollapseImage { get { - return _nodeCollapseImage; + return this._nodeCollapseImage; } + set { - _nodeCollapseImage = value; + this._nodeCollapseImage = value; } } @@ -168,11 +174,12 @@ public string NodeCssClass { get { - return _nodeCssClass; + return this._nodeCssClass; } + set { - _nodeCssClass = value; + this._nodeCssClass = value; } } @@ -180,11 +187,12 @@ public string NodeExpandImage { get { - return _nodeExpandImage; + return this._nodeExpandImage; } + set { - _nodeExpandImage = value; + this._nodeExpandImage = value; } } @@ -192,11 +200,12 @@ public string NodeLeafImage { get { - return _nodeLeafImage; + return this._nodeLeafImage; } + set { - _nodeLeafImage = value; + this._nodeLeafImage = value; } } @@ -204,11 +213,12 @@ public string NodeOpenImage { get { - return _nodeOpenImage; + return this._nodeOpenImage; } + set { - _nodeOpenImage = value; + this._nodeOpenImage = value; } } @@ -216,11 +226,12 @@ public string NodeOverCssClass { get { - return _nodeOverCssClass; + return this._nodeOverCssClass; } + set { - _nodeOverCssClass = value; + this._nodeOverCssClass = value; } } @@ -228,11 +239,12 @@ public string NodeSelectedCssClass { get { - return _nodeSelectedCssClass; + return this._nodeSelectedCssClass; } + set { - _nodeSelectedCssClass = value; + this._nodeSelectedCssClass = value; } } @@ -242,11 +254,12 @@ public string ResourceKey { get { - return _resourceKey; + return this._resourceKey; } + set { - _resourceKey = value; + this._resourceKey = value; } } @@ -254,11 +267,12 @@ public string TreeCssClass { get { - return _treeCssClass; + return this._treeCssClass; } + set { - _treeCssClass = value; + this._treeCssClass = value; } } @@ -266,11 +280,12 @@ public string TreeGoUpImage { get { - return _treeGoUpImage; + return this._treeGoUpImage; } + set { - _treeGoUpImage = value; + this._treeGoUpImage = value; } } @@ -278,11 +293,12 @@ public int TreeIndentWidth { get { - return _treeIndentWidth; + return this._treeIndentWidth; } + set { - _treeIndentWidth = value; + this._treeIndentWidth = value; } } @@ -290,25 +306,119 @@ public string Width { get { - return _width; + return this._width; } + set { - _width = value; + this._width = value; } } - - private void InitializeComponent() + + /// ----------------------------------------------------------------------------- + /// + /// The Page_Load server event handler on this user control is used + /// to populate the tree with the Pages. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) { + base.OnLoad(e); + try + { + if (this.Page.IsPostBack == false) + { + this.BuildTree(null, false); + + // Main Table Properties + if (!string.IsNullOrEmpty(this.Width)) + { + this.tblMain.Width = this.Width; + } + + if (!string.IsNullOrEmpty(this.CssClass)) + { + this.tblMain.Attributes.Add("class", this.CssClass); + } + + // Header Properties + if (!string.IsNullOrEmpty(this.HeaderCssClass)) + { + this.cellHeader.Attributes.Add("class", this.HeaderCssClass); + } + + if (!string.IsNullOrEmpty(this.HeaderTextCssClass)) + { + this.lblHeader.CssClass = this.HeaderTextCssClass; + } + + // Header Text (if set) + if (!string.IsNullOrEmpty(this.HeaderText)) + { + this.lblHeader.Text = this.HeaderText; + } + + // ResourceKey overrides if found + if (!string.IsNullOrEmpty(this.ResourceKey)) + { + string strHeader = Localization.GetString(this.ResourceKey, Localization.GetResourceFile(this, MyFileName)); + if (!string.IsNullOrEmpty(strHeader)) + { + this.lblHeader.Text = Localization.GetString(this.ResourceKey, Localization.GetResourceFile(this, MyFileName)); + } + } + + // If still not set get default key + if (string.IsNullOrEmpty(this.lblHeader.Text)) + { + string strHeader = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); + if (!string.IsNullOrEmpty(strHeader)) + { + this.lblHeader.Text = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); + } + else + { + this.lblHeader.Text = "Site Navigation"; + } + } + + this.tblHeader.Visible = this.IncludeHeader; + + // Main Panel Properties + if (!string.IsNullOrEmpty(this.BodyCssClass)) + { + this.cellBody.Attributes.Add("class", this.BodyCssClass); + } + + this.cellBody.NoWrap = this.NoWrap; + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } } - #endregion + protected override void OnInit(EventArgs e) + { + this.InitializeTree(); + this.InitializeNavControl(this.cellBody, "DNNTreeNavigationProvider"); + this.Control.NodeClick += this.DNNTree_NodeClick; + this.Control.PopulateOnDemand += this.DNNTree_PopulateOnDemand; + base.OnInit(e); + this.InitializeComponent(); + } - #region "Private Methods" - + private void InitializeComponent() + { + } + /// ----------------------------------------------------------------------------- /// - /// The BuildTree helper method is used to build the tree + /// The BuildTree helper method is used to build the tree. /// /// /// @@ -317,13 +427,13 @@ private void BuildTree(DNNNode objNode, bool blnPODRequest) { bool blnAddUpNode = false; DNNNodeCollection objNodes; - objNodes = GetNavigationNodes(objNode); + objNodes = this.GetNavigationNodes(objNode); if (blnPODRequest == false) { - if (!string.IsNullOrEmpty(Level)) + if (!string.IsNullOrEmpty(this.Level)) { - switch (Level.ToLowerInvariant()) + switch (this.Level.ToLowerInvariant()) { case "root": break; @@ -331,42 +441,45 @@ private void BuildTree(DNNNode objNode, bool blnPODRequest) blnAddUpNode = true; break; default: - if (Level.ToLowerInvariant() != "root" && PortalSettings.ActiveTab.BreadCrumbs.Count > 1) + if (this.Level.ToLowerInvariant() != "root" && this.PortalSettings.ActiveTab.BreadCrumbs.Count > 1) { blnAddUpNode = true; } + break; } } } - - //add goto Parent node + + // add goto Parent node if (blnAddUpNode) { var objParentNode = new DNNNode(); - objParentNode.ID = PortalSettings.ActiveTab.ParentId.ToString(); + objParentNode.ID = this.PortalSettings.ActiveTab.ParentId.ToString(); objParentNode.Key = objParentNode.ID; objParentNode.Text = Localization.GetString("Parent", Localization.GetResourceFile(this, MyFileName)); objParentNode.ToolTip = Localization.GetString("GoUp", Localization.GetResourceFile(this, MyFileName)); - objParentNode.CSSClass = NodeCssClass; - objParentNode.Image = ResolveUrl(TreeGoUpImage); + objParentNode.CSSClass = this.NodeCssClass; + objParentNode.Image = this.ResolveUrl(this.TreeGoUpImage); objParentNode.ClickAction = eClickAction.PostBack; objNodes.InsertBefore(0, objParentNode); } - foreach (DNNNode objPNode in objNodes) //clean up to do in processnodes??? + + foreach (DNNNode objPNode in objNodes) // clean up to do in processnodes??? { - ProcessNodes(objPNode); + this.ProcessNodes(objPNode); } - Bind(objNodes); + + this.Bind(objNodes); - //technically this should always be a dnntree. If using dynamic controls Nav.ascx should be used. just being safe. - if (Control.NavigationControl is DnnTree) + // technically this should always be a dnntree. If using dynamic controls Nav.ascx should be used. just being safe. + if (this.Control.NavigationControl is DnnTree) { - var objTree = (DnnTree) Control.NavigationControl; + var objTree = (DnnTree)this.Control.NavigationControl; if (objTree.SelectedTreeNodes.Count > 0) { - var objTNode = (TreeNode) objTree.SelectedTreeNodes[1]; - if (objTNode.DNNNodes.Count > 0) //only expand it if nodes are not pending + var objTNode = (TreeNode)objTree.SelectedTreeNodes[1]; + if (objTNode.DNNNodes.Count > 0) // only expand it if nodes are not pending { objTNode.Expand(); } @@ -376,175 +489,98 @@ private void BuildTree(DNNNode objNode, bool blnPODRequest) private void ProcessNodes(DNNNode objParent) { - if (!String.IsNullOrEmpty(objParent.Image)) + if (!string.IsNullOrEmpty(objParent.Image)) { } - else if (objParent.HasNodes) //imagepath applied in provider... + else if (objParent.HasNodes) // imagepath applied in provider... { - objParent.Image = ResolveUrl(NodeClosedImage); + objParent.Image = this.ResolveUrl(this.NodeClosedImage); } else { - objParent.Image = ResolveUrl(NodeLeafImage); + objParent.Image = this.ResolveUrl(this.NodeLeafImage); } + foreach (DNNNode objNode in objParent.DNNNodes) { - ProcessNodes(objNode); + this.ProcessNodes(objNode); } } /// ----------------------------------------------------------------------------- /// - /// Sets common properties on DNNTree control + /// Sets common properties on DNNTree control. /// /// /// /// ----------------------------------------------------------------------------- private void InitializeTree() { - if (String.IsNullOrEmpty(PathImage)) + if (string.IsNullOrEmpty(this.PathImage)) { - PathImage = PortalSettings.HomeDirectory; + this.PathImage = this.PortalSettings.HomeDirectory; } - if (String.IsNullOrEmpty(PathSystemImage)) + + if (string.IsNullOrEmpty(this.PathSystemImage)) { - PathSystemImage = ResolveUrl("~/images/"); + this.PathSystemImage = this.ResolveUrl("~/images/"); } - if (String.IsNullOrEmpty(IndicateChildImageRoot)) + + if (string.IsNullOrEmpty(this.IndicateChildImageRoot)) { - IndicateChildImageRoot = ResolveUrl(NodeExpandImage); + this.IndicateChildImageRoot = this.ResolveUrl(this.NodeExpandImage); } - if (String.IsNullOrEmpty(IndicateChildImageSub)) + + if (string.IsNullOrEmpty(this.IndicateChildImageSub)) { - IndicateChildImageSub = ResolveUrl(NodeExpandImage); + this.IndicateChildImageSub = this.ResolveUrl(this.NodeExpandImage); } - if (String.IsNullOrEmpty(IndicateChildImageExpandedRoot)) + + if (string.IsNullOrEmpty(this.IndicateChildImageExpandedRoot)) { - IndicateChildImageExpandedRoot = ResolveUrl(NodeCollapseImage); + this.IndicateChildImageExpandedRoot = this.ResolveUrl(this.NodeCollapseImage); } - if (String.IsNullOrEmpty(IndicateChildImageExpandedSub)) + + if (string.IsNullOrEmpty(this.IndicateChildImageExpandedSub)) { - IndicateChildImageExpandedSub = ResolveUrl(NodeCollapseImage); + this.IndicateChildImageExpandedSub = this.ResolveUrl(this.NodeCollapseImage); } - if (String.IsNullOrEmpty(CSSNode)) + + if (string.IsNullOrEmpty(this.CSSNode)) { - CSSNode = NodeChildCssClass; + this.CSSNode = this.NodeChildCssClass; } - if (String.IsNullOrEmpty(CSSNodeRoot)) + + if (string.IsNullOrEmpty(this.CSSNodeRoot)) { - CSSNodeRoot = NodeCssClass; + this.CSSNodeRoot = this.NodeCssClass; } - if (String.IsNullOrEmpty(CSSNodeHover)) + + if (string.IsNullOrEmpty(this.CSSNodeHover)) { - CSSNodeHover = NodeOverCssClass; + this.CSSNodeHover = this.NodeOverCssClass; } - if (String.IsNullOrEmpty(CSSNodeSelectedRoot)) + + if (string.IsNullOrEmpty(this.CSSNodeSelectedRoot)) { - CSSNodeSelectedRoot = NodeSelectedCssClass; + this.CSSNodeSelectedRoot = this.NodeSelectedCssClass; } - if (String.IsNullOrEmpty(CSSNodeSelectedSub)) - { - CSSNodeSelectedSub = NodeSelectedCssClass; - } - if (String.IsNullOrEmpty(CSSControl)) - { - CSSControl = TreeCssClass; - } - } - - #endregion - - #region "Event Handlers" - - /// ----------------------------------------------------------------------------- - /// - /// The Page_Load server event handler on this user control is used - /// to populate the tree with the Pages. - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - try + + if (string.IsNullOrEmpty(this.CSSNodeSelectedSub)) { - if (Page.IsPostBack == false) - { - BuildTree(null, false); - - //Main Table Properties - if (!String.IsNullOrEmpty(Width)) - { - tblMain.Width = Width; - } - - if (!String.IsNullOrEmpty(CssClass)) - { - tblMain.Attributes.Add("class", CssClass); - } - - //Header Properties - if (!String.IsNullOrEmpty(HeaderCssClass)) - { - cellHeader.Attributes.Add("class", HeaderCssClass); - } - - if (!String.IsNullOrEmpty(HeaderTextCssClass)) - { - lblHeader.CssClass = HeaderTextCssClass; - } - - //Header Text (if set) - if (!String.IsNullOrEmpty(HeaderText)) - { - lblHeader.Text = HeaderText; - } - - //ResourceKey overrides if found - if (!String.IsNullOrEmpty(ResourceKey)) - { - string strHeader = Localization.GetString(ResourceKey, Localization.GetResourceFile(this, MyFileName)); - if (!String.IsNullOrEmpty(strHeader)) - { - lblHeader.Text = Localization.GetString(ResourceKey, Localization.GetResourceFile(this, MyFileName)); - } - } - - //If still not set get default key - if (String.IsNullOrEmpty(lblHeader.Text)) - { - string strHeader = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); - if (!String.IsNullOrEmpty(strHeader)) - { - lblHeader.Text = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); - } - else - { - lblHeader.Text = "Site Navigation"; - } - } - tblHeader.Visible = IncludeHeader; - - //Main Panel Properties - if (!String.IsNullOrEmpty(BodyCssClass)) - { - cellBody.Attributes.Add("class", BodyCssClass); - } - cellBody.NoWrap = NoWrap; - } + this.CSSNodeSelectedSub = this.NodeSelectedCssClass; } - catch (Exception exc) + + if (string.IsNullOrEmpty(this.CSSControl)) { - Exceptions.ProcessModuleLoadException(this, exc); + this.CSSControl = this.TreeCssClass; } - } + } /// ----------------------------------------------------------------------------- /// /// The DNNTree_NodeClick server event handler on this user control runs when a - /// Node (Page) in the TreeView is clicked + /// Node (Page) in the TreeView is clicked. /// /// The event only fires when the Node contains child nodes, as leaf nodes /// have their NavigateUrl Property set. @@ -554,42 +590,20 @@ private void DNNTree_NodeClick(NavigationEventArgs args) { if (args.Node == null) { - args.Node = Navigation.GetNavigationNode(args.ID, Control.ID); + args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); + + this.Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); } private void DNNTree_PopulateOnDemand(NavigationEventArgs args) { if (args.Node == null) { - args.Node = Navigation.GetNavigationNode(args.ID, Control.ID); + args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - BuildTree(args.Node, true); + + this.BuildTree(args.Node, true); } - - protected override void OnInit(EventArgs e) - { - InitializeTree(); - InitializeNavControl(cellBody, "DNNTreeNavigationProvider"); - Control.NodeClick += DNNTree_NodeClick; - Control.PopulateOnDemand += DNNTree_PopulateOnDemand; - base.OnInit(e); - InitializeComponent(); - } - - #endregion - - #region Nested type: eImageType - - private enum eImageType - { - FolderClosed = 0, - FolderOpen = 1, - Page = 2, - GotoParent = 3 - } - - #endregion } } diff --git a/DNN Platform/Website/admin/Skins/User.ascx.cs b/DNN Platform/Website/admin/Skins/User.ascx.cs index b4d6b5f9136..0e0727cff3d 100644 --- a/DNN Platform/Website/admin/Skins/User.ascx.cs +++ b/DNN Platform/Website/admin/Skins/User.ascx.cs @@ -1,35 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Services.Social.Messaging.Internal; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Controllers; - + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using Microsoft.Extensions.DependencyInjection; + /// ----------------------------------------------------------------------------- /// /// @@ -41,10 +35,10 @@ public partial class User : SkinObjectBase public User() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); - ShowUnreadMessages = true; - ShowAvatar = true; - LegacyMode = true; + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + this.ShowUnreadMessages = true; + this.ShowAvatar = true; + this.LegacyMode = true; } public string CssClass { get; set; } @@ -54,7 +48,7 @@ public User() public bool ShowAvatar { get; set; } /// - /// Set this to false in the skin to take advantage of the enhanced markup + /// Gets or sets a value indicating whether set this to false in the skin to take advantage of the enhanced markup. /// public bool LegacyMode { get; set; } @@ -63,7 +57,7 @@ public User() public string URL { get; set; } /// - /// set this to true to show in custom 404/500 page. + /// Gets or sets a value indicating whether set this to true to show in custom 404/500 page. /// public bool ShowInErrorPage { get; set; } @@ -71,7 +65,7 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - Visible = !PortalSettings.InErrorPageRequest() || ShowInErrorPage; + this.Visible = !this.PortalSettings.InErrorPageRequest() || this.ShowInErrorPage; } protected override void OnLoad(EventArgs e) @@ -80,70 +74,81 @@ protected override void OnLoad(EventArgs e) try { - if (LegacyMode) - registerGroup.Visible = false; - else - registerLink.Visible = false; - - if (!String.IsNullOrEmpty(CssClass)) + if (this.LegacyMode) + { + this.registerGroup.Visible = false; + } + else + { + this.registerLink.Visible = false; + } + + if (!string.IsNullOrEmpty(this.CssClass)) { - registerLink.CssClass = CssClass; - enhancedRegisterLink.CssClass = CssClass; + this.registerLink.CssClass = this.CssClass; + this.enhancedRegisterLink.CssClass = this.CssClass; } - if (Request.IsAuthenticated == false) + if (this.Request.IsAuthenticated == false) { - messageGroup.Visible = false; - notificationGroup.Visible = false; - avatarGroup.Visible = false; + this.messageGroup.Visible = false; + this.notificationGroup.Visible = false; + this.avatarGroup.Visible = false; - if (PortalSettings.UserRegistration != (int) Globals.PortalRegistrationType.NoRegistration) + if (this.PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) { - if (!String.IsNullOrEmpty(Text)) + if (!string.IsNullOrEmpty(this.Text)) { - if (Text.IndexOf("src=") != -1) + if (this.Text.IndexOf("src=") != -1) { - Text = Text.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); + this.Text = this.Text.Replace("src=\"", "src=\"" + this.PortalSettings.ActiveTab.SkinPath); } - registerLink.Text = Text; - enhancedRegisterLink.Text = Text; + + this.registerLink.Text = this.Text; + this.enhancedRegisterLink.Text = this.Text; } else { - registerLink.Text = Localization.GetString("Register", Localization.GetResourceFile(this, MyFileName)); - enhancedRegisterLink.Text = registerLink.Text; - registerLink.ToolTip = registerLink.Text; - enhancedRegisterLink.ToolTip = registerLink.Text; + this.registerLink.Text = Localization.GetString("Register", Localization.GetResourceFile(this, MyFileName)); + this.enhancedRegisterLink.Text = this.registerLink.Text; + this.registerLink.ToolTip = this.registerLink.Text; + this.enhancedRegisterLink.ToolTip = this.registerLink.Text; } - if (PortalSettings.Users < PortalSettings.UserQuota || PortalSettings.UserQuota == 0) + + if (this.PortalSettings.Users < this.PortalSettings.UserQuota || this.PortalSettings.UserQuota == 0) { - if (LegacyMode) registerLink.Visible = true; - else enhancedRegisterLink.Visible = true; + if (this.LegacyMode) + { + this.registerLink.Visible = true; + } + else + { + this.enhancedRegisterLink.Visible = true; + } } else { - registerGroup.Visible = false; - registerLink.Visible = false; + this.registerGroup.Visible = false; + this.registerLink.Visible = false; } - registerLink.NavigateUrl = !String.IsNullOrEmpty(URL) - ? URL - : Globals.RegisterURL(HttpUtility.UrlEncode(_navigationManager.NavigateURL()), Null.NullString); - enhancedRegisterLink.NavigateUrl = registerLink.NavigateUrl; + this.registerLink.NavigateUrl = !string.IsNullOrEmpty(this.URL) + ? this.URL + : Globals.RegisterURL(HttpUtility.UrlEncode(this._navigationManager.NavigateURL()), Null.NullString); + this.enhancedRegisterLink.NavigateUrl = this.registerLink.NavigateUrl; - if (PortalSettings.EnablePopUps && PortalSettings.RegisterTabId == Null.NullInteger + if (this.PortalSettings.EnablePopUps && this.PortalSettings.RegisterTabId == Null.NullInteger && !AuthenticationController.HasSocialAuthenticationEnabled(this)) { - var clickEvent = "return " + UrlUtils.PopUpUrl(registerLink.NavigateUrl, this, PortalSettings, true, false, 600, 950); - registerLink.Attributes.Add("onclick", clickEvent); - enhancedRegisterLink.Attributes.Add("onclick", clickEvent); + var clickEvent = "return " + UrlUtils.PopUpUrl(this.registerLink.NavigateUrl, this, this.PortalSettings, true, false, 600, 950); + this.registerLink.Attributes.Add("onclick", clickEvent); + this.enhancedRegisterLink.Attributes.Add("onclick", clickEvent); } - } else { - registerGroup.Visible = false; - registerLink.Visible = false; + this.registerGroup.Visible = false; + this.registerLink.Visible = false; } } else @@ -151,50 +156,50 @@ protected override void OnLoad(EventArgs e) var userInfo = UserController.Instance.GetCurrentUserInfo(); if (userInfo.UserID != -1) { - registerLink.Text = userInfo.DisplayName; - registerLink.NavigateUrl = Globals.UserProfileURL(userInfo.UserID); - registerLink.ToolTip = Localization.GetString("VisitMyProfile", Localization.GetResourceFile(this, MyFileName)); + this.registerLink.Text = userInfo.DisplayName; + this.registerLink.NavigateUrl = Globals.UserProfileURL(userInfo.UserID); + this.registerLink.ToolTip = Localization.GetString("VisitMyProfile", Localization.GetResourceFile(this, MyFileName)); - enhancedRegisterLink.Text = registerLink.Text; - enhancedRegisterLink.NavigateUrl = registerLink.NavigateUrl; - enhancedRegisterLink.ToolTip = registerLink.ToolTip; + this.enhancedRegisterLink.Text = this.registerLink.Text; + this.enhancedRegisterLink.NavigateUrl = this.registerLink.NavigateUrl; + this.enhancedRegisterLink.ToolTip = this.registerLink.ToolTip; - if (ShowUnreadMessages) + if (this.ShowUnreadMessages) { var unreadMessages = InternalMessagingController.Instance.CountUnreadMessages(userInfo.UserID, PortalController.GetEffectivePortalId(userInfo.PortalID)); var unreadAlerts = NotificationsController.Instance.CountNotifications(userInfo.UserID, PortalController.GetEffectivePortalId(userInfo.PortalID)); - messageLink.Text = unreadMessages > 0 ? string.Format(Localization.GetString("Messages", Localization.GetResourceFile(this, MyFileName)), unreadMessages) : Localization.GetString("NoMessages", Localization.GetResourceFile(this, MyFileName)); - notificationLink.Text = unreadAlerts > 0 ? string.Format(Localization.GetString("Notifications", Localization.GetResourceFile(this, MyFileName)), unreadAlerts) : Localization.GetString("NoNotifications", Localization.GetResourceFile(this, MyFileName)); + this.messageLink.Text = unreadMessages > 0 ? string.Format(Localization.GetString("Messages", Localization.GetResourceFile(this, MyFileName)), unreadMessages) : Localization.GetString("NoMessages", Localization.GetResourceFile(this, MyFileName)); + this.notificationLink.Text = unreadAlerts > 0 ? string.Format(Localization.GetString("Notifications", Localization.GetResourceFile(this, MyFileName)), unreadAlerts) : Localization.GetString("NoNotifications", Localization.GetResourceFile(this, MyFileName)); - messageLink.NavigateUrl = _navigationManager.NavigateURL(GetMessageTab(), "", string.Format("userId={0}", userInfo.UserID)); - notificationLink.NavigateUrl = _navigationManager.NavigateURL(GetMessageTab(), "", string.Format("userId={0}", userInfo.UserID),"view=notifications","action=notifications"); - notificationLink.ToolTip = Localization.GetString("CheckNotifications", Localization.GetResourceFile(this, MyFileName)); - messageLink.ToolTip = Localization.GetString("CheckMessages", Localization.GetResourceFile(this, MyFileName)); - messageGroup.Visible = true; - notificationGroup.Visible = true; + this.messageLink.NavigateUrl = this._navigationManager.NavigateURL(this.GetMessageTab(), string.Empty, string.Format("userId={0}", userInfo.UserID)); + this.notificationLink.NavigateUrl = this._navigationManager.NavigateURL(this.GetMessageTab(), string.Empty, string.Format("userId={0}", userInfo.UserID), "view=notifications", "action=notifications"); + this.notificationLink.ToolTip = Localization.GetString("CheckNotifications", Localization.GetResourceFile(this, MyFileName)); + this.messageLink.ToolTip = Localization.GetString("CheckMessages", Localization.GetResourceFile(this, MyFileName)); + this.messageGroup.Visible = true; + this.notificationGroup.Visible = true; - if (LegacyMode && unreadMessages > 0) + if (this.LegacyMode && unreadMessages > 0) { - registerLink.Text = registerLink.Text + string.Format(Localization.GetString("NewMessages", Localization.GetResourceFile(this, MyFileName)), unreadMessages); + this.registerLink.Text = this.registerLink.Text + string.Format(Localization.GetString("NewMessages", Localization.GetResourceFile(this, MyFileName)), unreadMessages); } } else { - messageGroup.Visible = false; - notificationGroup.Visible = false; + this.messageGroup.Visible = false; + this.notificationGroup.Visible = false; } - if (ShowAvatar) + if (this.ShowAvatar) { - avatar.ImageUrl = GetAvatarUrl(userInfo); - avatar.NavigateUrl = enhancedRegisterLink.NavigateUrl; - avatar.ToolTip = avatar.Text = Localization.GetString("ProfileAvatar", Localization.GetResourceFile(this, MyFileName)); - avatarGroup.Visible = true; + this.avatar.ImageUrl = this.GetAvatarUrl(userInfo); + this.avatar.NavigateUrl = this.enhancedRegisterLink.NavigateUrl; + this.avatar.ToolTip = this.avatar.Text = Localization.GetString("ProfileAvatar", Localization.GetResourceFile(this, MyFileName)); + this.avatarGroup.Visible = true; } else { - avatarGroup.Visible = false; + this.avatarGroup.Visible = false; } } } @@ -212,16 +217,18 @@ private string GetAvatarUrl(UserInfo userInfo) private int GetMessageTab() { - var cacheKey = string.Format("MessageCenterTab:{0}:{1}", PortalSettings.PortalId, PortalSettings.CultureCode); + var cacheKey = string.Format("MessageCenterTab:{0}:{1}", this.PortalSettings.PortalId, this.PortalSettings.CultureCode); var messageTabId = DataCache.GetCache(cacheKey); - if (messageTabId > 0) - return messageTabId; - - //Find the Message Tab - messageTabId = FindMessageTab(); - - //save in cache - //NOTE - This cache is not being cleared. There is no easy way to clear this, except Tools->Clear Cache + if (messageTabId > 0) + { + return messageTabId; + } + + // Find the Message Tab + messageTabId = this.FindMessageTab(); + + // save in cache + // NOTE - This cache is not being cleared. There is no easy way to clear this, except Tools->Clear Cache DataCache.SetCache(cacheKey, messageTabId, TimeSpan.FromMinutes(20)); return messageTabId; @@ -229,9 +236,9 @@ private int GetMessageTab() private int FindMessageTab() { - //On brand new install the new Message Center Module is on the child page of User Profile Page - //On Upgrade to 6.2.0, the Message Center module is on the User Profile Page - var profileTab = TabController.Instance.GetTab(PortalSettings.UserTabId, PortalSettings.PortalId, false); + // On brand new install the new Message Center Module is on the child page of User Profile Page + // On Upgrade to 6.2.0, the Message Center module is on the User Profile Page + var profileTab = TabController.Instance.GetTab(this.PortalSettings.UserTabId, this.PortalSettings.PortalId, false); if (profileTab != null) { var childTabs = TabController.Instance.GetTabsByPortal(profileTab.PortalID).DescendentsOf(profileTab.TabID); @@ -248,8 +255,8 @@ private int FindMessageTab() } } - //default to User Profile Page - return PortalSettings.UserTabId; + // default to User Profile Page + return this.PortalSettings.UserTabId; } } } diff --git a/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs b/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs index 668ea7755d2..3091051faee 100644 --- a/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs +++ b/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs @@ -1,49 +1,50 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Web; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Social.Notifications; -using DotNetNuke.Services.Social.Messaging.Internal; -using DotNetNuke.Abstractions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Web; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Social.Messaging.Internal; + using DotNetNuke.Services.Social.Notifications; + using Microsoft.Extensions.DependencyInjection; + public partial class UserAndLogin : SkinObjectBase { private const string MyFileName = "UserAndLogin.ascx"; private readonly INavigationManager _navigationManager; - protected string AvatarImageUrl => UserController.Instance.GetUserProfilePictureUrl(PortalSettings.UserId, 32, 32); - public UserAndLogin() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + /// + /// Gets or sets a value indicating whether set this to true to show in custom 404/500 page. + /// + public bool ShowInErrorPage { get; set; } + + protected string AvatarImageUrl => UserController.Instance.GetUserProfilePictureUrl(this.PortalSettings.UserId, 32, 32); + protected bool CanRegister { get { - return ((PortalSettings.UserRegistration != (int) Globals.PortalRegistrationType.NoRegistration) - && (PortalSettings.Users < PortalSettings.UserQuota || PortalSettings.UserQuota == 0)); + return (this.PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) + && (this.PortalSettings.Users < this.PortalSettings.UserQuota || this.PortalSettings.UserQuota == 0); } } @@ -51,7 +52,7 @@ protected string DisplayName { get { - return PortalSettings.UserInfo.DisplayName; + return this.PortalSettings.UserInfo.DisplayName; } } @@ -59,7 +60,7 @@ protected bool IsAuthenticated { get { - return Request.IsAuthenticated; + return this.Request.IsAuthenticated; } } @@ -72,33 +73,34 @@ protected string LoginUrl { returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=", StringComparison.Ordinal)); } + returnUrl = HttpUtility.UrlEncode(returnUrl); - return Globals.LoginURL(returnUrl, (Request.QueryString["override"] != null)); + return Globals.LoginURL(returnUrl, this.Request.QueryString["override"] != null); } } - protected string LoginUrlForClickEvent - { - get - { - var url = LoginUrl; + protected string LoginUrlForClickEvent + { + get + { + var url = this.LoginUrl; - if (UsePopUp) - { - return "return " + UrlUtils.PopUpUrl(HttpUtility.UrlDecode(LoginUrl), this, PortalSettings, true, false, 300, 650); - } + if (this.UsePopUp) + { + return "return " + UrlUtils.PopUpUrl(HttpUtility.UrlDecode(this.LoginUrl), this, this.PortalSettings, true, false, 300, 650); + } - return string.Empty; - } - } + return string.Empty; + } + } protected bool UsePopUp { get { - return PortalSettings.EnablePopUps - && PortalSettings.LoginTabId == Null.NullInteger + return this.PortalSettings.EnablePopUps + && this.PortalSettings.LoginTabId == Null.NullInteger && !AuthenticationController.HasSocialAuthenticationEnabled(this); } } @@ -107,36 +109,31 @@ protected string RegisterUrl { get { - return Globals.RegisterURL(HttpUtility.UrlEncode(_navigationManager.NavigateURL()), Null.NullString); + return Globals.RegisterURL(HttpUtility.UrlEncode(this._navigationManager.NavigateURL()), Null.NullString); } } - protected string RegisterUrlForClickEvent - { - get - { - if (UsePopUp) - { - return "return " + UrlUtils.PopUpUrl(HttpUtility.UrlDecode(RegisterUrl), this, PortalSettings, true, false, 600, 950); - } + protected string RegisterUrlForClickEvent + { + get + { + if (this.UsePopUp) + { + return "return " + UrlUtils.PopUpUrl(HttpUtility.UrlDecode(this.RegisterUrl), this, this.PortalSettings, true, false, 600, 950); + } - return string.Empty; - } - } + return string.Empty; + } + } protected string UserProfileUrl { get { - return Globals.UserProfileURL(PortalSettings.UserInfo.UserID); ; + return Globals.UserProfileURL(this.PortalSettings.UserInfo.UserID); } } - /// - /// set this to true to show in custom 404/500 page. - /// - public bool ShowInErrorPage { get; set; } - protected string LocalizeString(string key) { return Localization.GetString(key, Localization.GetResourceFile(this, MyFileName)); @@ -146,76 +143,77 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - Visible = !PortalSettings.InErrorPageRequest() || ShowInErrorPage; + this.Visible = !this.PortalSettings.InErrorPageRequest() || this.ShowInErrorPage; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); - registerLink.NavigateUrl = RegisterUrl; - loginLink.NavigateUrl = LoginUrl; + this.registerLink.NavigateUrl = this.RegisterUrl; + this.loginLink.NavigateUrl = this.LoginUrl; - if (PortalSettings.UserId > 0) + if (this.PortalSettings.UserId > 0) { - viewProfileLink.NavigateUrl = Globals.UserProfileURL(PortalSettings.UserId); - viewProfileImageLink.NavigateUrl = Globals.UserProfileURL(PortalSettings.UserId); - logoffLink.NavigateUrl = _navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Logoff"); - editProfileLink.NavigateUrl = _navigationManager.NavigateURL(PortalSettings.UserTabId, "Profile", "userId=" + PortalSettings.UserId, "pageno=2"); - accountLink.NavigateUrl = _navigationManager.NavigateURL(PortalSettings.UserTabId, "Profile", "userId=" + PortalSettings.UserId, "pageno=1"); - messagesLink.NavigateUrl = _navigationManager.NavigateURL(GetMessageTab(), "", string.Format("userId={0}", PortalSettings.UserId)); - notificationsLink.NavigateUrl = _navigationManager.NavigateURL(GetMessageTab(), "", string.Format("userId={0}", PortalSettings.UserId), "view=notifications", "action=notifications"); + this.viewProfileLink.NavigateUrl = Globals.UserProfileURL(this.PortalSettings.UserId); + this.viewProfileImageLink.NavigateUrl = Globals.UserProfileURL(this.PortalSettings.UserId); + this.logoffLink.NavigateUrl = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Logoff"); + this.editProfileLink.NavigateUrl = this._navigationManager.NavigateURL(this.PortalSettings.UserTabId, "Profile", "userId=" + this.PortalSettings.UserId, "pageno=2"); + this.accountLink.NavigateUrl = this._navigationManager.NavigateURL(this.PortalSettings.UserTabId, "Profile", "userId=" + this.PortalSettings.UserId, "pageno=1"); + this.messagesLink.NavigateUrl = this._navigationManager.NavigateURL(this.GetMessageTab(), string.Empty, string.Format("userId={0}", this.PortalSettings.UserId)); + this.notificationsLink.NavigateUrl = this._navigationManager.NavigateURL(this.GetMessageTab(), string.Empty, string.Format("userId={0}", this.PortalSettings.UserId), "view=notifications", "action=notifications"); - var unreadMessages = InternalMessagingController.Instance.CountUnreadMessages(PortalSettings.UserId, PortalSettings.PortalId); - var unreadAlerts = NotificationsController.Instance.CountNotifications(PortalSettings.UserId, PortalSettings.PortalId); + var unreadMessages = InternalMessagingController.Instance.CountUnreadMessages(this.PortalSettings.UserId, this.PortalSettings.PortalId); + var unreadAlerts = NotificationsController.Instance.CountNotifications(this.PortalSettings.UserId, this.PortalSettings.PortalId); if (unreadMessages > 0) { - messageCount.Text = unreadMessages.ToString(CultureInfo.InvariantCulture); - messageCount.Visible = true; - - messages.Text = unreadMessages.ToString(CultureInfo.InvariantCulture); - messages.ToolTip = unreadMessages == 1 - ? LocalizeString("OneMessage") - : String.Format(LocalizeString("MessageCount"), unreadMessages); - messages.Visible = true; + this.messageCount.Text = unreadMessages.ToString(CultureInfo.InvariantCulture); + this.messageCount.Visible = true; + + this.messages.Text = unreadMessages.ToString(CultureInfo.InvariantCulture); + this.messages.ToolTip = unreadMessages == 1 + ? this.LocalizeString("OneMessage") + : string.Format(this.LocalizeString("MessageCount"), unreadMessages); + this.messages.Visible = true; } if (unreadAlerts > 0) { - notificationCount.Text = unreadAlerts.ToString(CultureInfo.InvariantCulture); - notificationCount.Visible = true; + this.notificationCount.Text = unreadAlerts.ToString(CultureInfo.InvariantCulture); + this.notificationCount.Visible = true; } - profilePicture.ImageUrl = AvatarImageUrl; - profilePicture.AlternateText = Localization.GetString("ProfilePicture", Localization.GetResourceFile(this, MyFileName)); + this.profilePicture.ImageUrl = this.AvatarImageUrl; + this.profilePicture.AlternateText = Localization.GetString("ProfilePicture", Localization.GetResourceFile(this, MyFileName)); - if (AlwaysShowCount()) + if (this.AlwaysShowCount()) { - messageCount.Visible = notificationCount.Visible = true; + this.messageCount.Visible = this.notificationCount.Visible = true; } } - if (UsePopUp) + if (this.UsePopUp) { - registerLink.Attributes.Add("onclick", RegisterUrlForClickEvent); - loginLink.Attributes.Add("onclick", LoginUrlForClickEvent); + this.registerLink.Attributes.Add("onclick", this.RegisterUrlForClickEvent); + this.loginLink.Attributes.Add("onclick", this.LoginUrlForClickEvent); } - } private int GetMessageTab() { - var cacheKey = string.Format("MessageCenterTab:{0}:{1}", PortalSettings.PortalId, PortalSettings.CultureCode); + var cacheKey = string.Format("MessageCenterTab:{0}:{1}", this.PortalSettings.PortalId, this.PortalSettings.CultureCode); var messageTabId = DataCache.GetCache(cacheKey); - if (messageTabId > 0) - return messageTabId; - - //Find the Message Tab - messageTabId = FindMessageTab(); - - //save in cache - //NOTE - This cache is not being cleared. There is no easy way to clear this, except Tools->Clear Cache + if (messageTabId > 0) + { + return messageTabId; + } + + // Find the Message Tab + messageTabId = this.FindMessageTab(); + + // save in cache + // NOTE - This cache is not being cleared. There is no easy way to clear this, except Tools->Clear Cache DataCache.SetCache(cacheKey, messageTabId, TimeSpan.FromMinutes(20)); return messageTabId; @@ -223,9 +221,9 @@ private int GetMessageTab() private int FindMessageTab() { - //On brand new install the new Message Center Module is on the child page of User Profile Page - //On Upgrade to 6.2.0, the Message Center module is on the User Profile Page - var profileTab = TabController.Instance.GetTab(PortalSettings.UserTabId, PortalSettings.PortalId, false); + // On brand new install the new Message Center Module is on the child page of User Profile Page + // On Upgrade to 6.2.0, the Message Center module is on the User Profile Page + var profileTab = TabController.Instance.GetTab(this.PortalSettings.UserTabId, this.PortalSettings.PortalId, false); if (profileTab != null) { var childTabs = TabController.Instance.GetTabsByPortal(profileTab.PortalID).DescendentsOf(profileTab.TabID); @@ -242,8 +240,8 @@ private int FindMessageTab() } } - //default to User Profile Page - return PortalSettings.UserTabId; + // default to User Profile Page + return this.PortalSettings.UserTabId; } private bool AlwaysShowCount() @@ -251,7 +249,7 @@ private bool AlwaysShowCount() const string SettingKey = "UserAndLogin_AlwaysShowCount"; var alwaysShowCount = false; - var portalSetting = PortalController.GetPortalSetting(SettingKey, PortalSettings.PortalId, string.Empty); + var portalSetting = PortalController.GetPortalSetting(SettingKey, this.PortalSettings.PortalId, string.Empty); if (!string.IsNullOrEmpty(portalSetting) && bool.TryParse(portalSetting, out alwaysShowCount)) { return alwaysShowCount; diff --git a/DNN Platform/Website/admin/Skins/jQuery.ascx.cs b/DNN Platform/Website/admin/Skins/jQuery.ascx.cs index 20371004843..8a1b7249d1b 100644 --- a/DNN Platform/Website/admin/Skins/jQuery.ascx.cs +++ b/DNN Platform/Website/admin/Skins/jQuery.ascx.cs @@ -1,17 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Framework.JavaScriptLibraries; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace DotNetNuke.UI.Skins.Controls { using System; - + + using DotNetNuke.Framework.JavaScriptLibraries; + public partial class jQuery : SkinObjectBase { public bool DnnjQueryPlugins { get; set; } + public bool jQueryHoverIntent { get; set; } + public bool jQueryUI { get; set; } protected override void OnInit(EventArgs e) @@ -19,17 +21,17 @@ protected override void OnInit(EventArgs e) JavaScript.RequestRegistration(CommonJs.jQuery); JavaScript.RequestRegistration(CommonJs.jQueryMigrate); - if (jQueryUI) + if (this.jQueryUI) { JavaScript.RequestRegistration(CommonJs.jQueryUI); } - if (DnnjQueryPlugins) + if (this.DnnjQueryPlugins) { JavaScript.RequestRegistration(CommonJs.DnnPlugins); } - if (jQueryHoverIntent) + if (this.jQueryHoverIntent) { JavaScript.RequestRegistration(CommonJs.HoverIntent); } diff --git a/DNN Platform/Website/admin/Skins/tags.ascx.cs b/DNN Platform/Website/admin/Skins/tags.ascx.cs index 9f1ddbe02f2..d5418547790 100644 --- a/DNN Platform/Website/admin/Skins/tags.ascx.cs +++ b/DNN Platform/Website/admin/Skins/tags.ascx.cs @@ -1,23 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Icons; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { + using System; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Icons; + using Microsoft.Extensions.DependencyInjection; + public partial class Tags : SkinObjectBase { - private readonly INavigationManager _navigationManager; private const string MyFileName = "Tags.ascx"; + private readonly INavigationManager _navigationManager; private string _AddImageUrl = IconController.IconURL("Add"); private bool _AllowTagging = true; private string _CancelImageUrl = IconController.IconURL("Lt"); @@ -30,18 +26,19 @@ public partial class Tags : SkinObjectBase public Tags() { - _navigationManager = Globals.DependencyProvider.GetRequiredService(); + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } public string AddImageUrl { get { - return _AddImageUrl; + return this._AddImageUrl; } + set { - _AddImageUrl = value; + this._AddImageUrl = value; } } @@ -49,11 +46,12 @@ public bool AllowTagging { get { - return _AllowTagging; + return this._AllowTagging; } + set { - _AllowTagging = value; + this._AllowTagging = value; } } @@ -61,11 +59,12 @@ public string CancelImageUrl { get { - return _CancelImageUrl; + return this._CancelImageUrl; } + set { - _CancelImageUrl = value; + this._CancelImageUrl = value; } } @@ -75,11 +74,12 @@ public string ObjectType { get { - return _ObjectType; + return this._ObjectType; } + set { - _ObjectType = value; + this._ObjectType = value; } } @@ -87,11 +87,12 @@ public string RepeatDirection { get { - return _RepeatDirection; + return this._RepeatDirection; } + set { - _RepeatDirection = value; + this._RepeatDirection = value; } } @@ -99,11 +100,12 @@ public string SaveImageUrl { get { - return _SaveImageUrl; + return this._SaveImageUrl; } + set { - _SaveImageUrl = value; + this._SaveImageUrl = value; } } @@ -111,11 +113,12 @@ public string Separator { get { - return _Separator; + return this._Separator; } + set { - _Separator = value; + this._Separator = value; } } @@ -123,11 +126,12 @@ public bool ShowCategories { get { - return _ShowCategories; + return this._ShowCategories; } + set { - _ShowCategories = value; + this._ShowCategories = value; } } @@ -135,11 +139,12 @@ public bool ShowTags { get { - return _ShowTags; + return this._ShowTags; } + set { - _ShowTags = value; + this._ShowTags = value; } } @@ -147,27 +152,27 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (ObjectType == "Page") + if (this.ObjectType == "Page") { - tagsControl.ContentItem = PortalSettings.ActiveTab; + this.tagsControl.ContentItem = this.PortalSettings.ActiveTab; } else { - tagsControl.ContentItem = ModuleControl.ModuleContext.Configuration; + this.tagsControl.ContentItem = this.ModuleControl.ModuleContext.Configuration; } - tagsControl.AddImageUrl = AddImageUrl; - tagsControl.CancelImageUrl = CancelImageUrl; - tagsControl.SaveImageUrl = SaveImageUrl; + this.tagsControl.AddImageUrl = this.AddImageUrl; + this.tagsControl.CancelImageUrl = this.CancelImageUrl; + this.tagsControl.SaveImageUrl = this.SaveImageUrl; - tagsControl.CssClass = CssClass; + this.tagsControl.CssClass = this.CssClass; - tagsControl.AllowTagging = AllowTagging && Request.IsAuthenticated; - tagsControl.NavigateUrlFormatString = _navigationManager.NavigateURL(PortalSettings.SearchTabId, "", "Tag={0}"); - tagsControl.RepeatDirection = RepeatDirection; - tagsControl.Separator = Separator; - tagsControl.ShowCategories = ShowCategories; - tagsControl.ShowTags = ShowTags; + this.tagsControl.AllowTagging = this.AllowTagging && this.Request.IsAuthenticated; + this.tagsControl.NavigateUrlFormatString = this._navigationManager.NavigateURL(this.PortalSettings.SearchTabId, string.Empty, "Tag={0}"); + this.tagsControl.RepeatDirection = this.RepeatDirection; + this.tagsControl.Separator = this.Separator; + this.tagsControl.ShowCategories = this.ShowCategories; + this.tagsControl.ShowTags = this.ShowTags; } } } diff --git a/DNN Platform/Website/admin/Tabs/App_LocalResources/Export.ascx.resx b/DNN Platform/Website/admin/Tabs/App_LocalResources/Export.ascx.resx index 8302426d814..0999f50d79b 100644 --- a/DNN Platform/Website/admin/Tabs/App_LocalResources/Export.ascx.resx +++ b/DNN Platform/Website/admin/Tabs/App_LocalResources/Export.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Tabs/App_LocalResources/Import.ascx.resx b/DNN Platform/Website/admin/Tabs/App_LocalResources/Import.ascx.resx index 50407c98055..f8b4db89eb5 100644 --- a/DNN Platform/Website/admin/Tabs/App_LocalResources/Import.ascx.resx +++ b/DNN Platform/Website/admin/Tabs/App_LocalResources/Import.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Tabs/Export.ascx.cs b/DNN Platform/Website/admin/Tabs/Export.ascx.cs index 298266165bd..0c4365f55d8 100644 --- a/DNN Platform/Website/admin/Tabs/Export.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Export.ascx.cs @@ -1,32 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.IO; -using System.Text; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; - -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.FileSystem.Internal; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Tabs { - + using System; + using System.IO; + using System.Text; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.FileSystem.Internal; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + public partial class Export : PortalModuleBase { private readonly INavigationManager _navigationManager; @@ -34,44 +28,29 @@ public partial class Export : PortalModuleBase public Export() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); } public TabInfo Tab { get { - if (_tab == null) + if (this._tab == null) { - _tab = TabController.Instance.GetTab(TabId, PortalId, false); + this._tab = TabController.Instance.GetTab(this.TabId, this.PortalId, false); } - return _tab; + + return this._tab; } } - - /// ----------------------------------------------------------------------------- - /// - /// Serializes the Tab - /// - /// Reference to XmlDocument context - /// Node to add the serialized objects - /// ----------------------------------------------------------------------------- - private void SerializeTab(XmlDocument xmlTemplate, XmlNode nodeTabs) - { - var xmlTab = new XmlDocument { XmlResolver = null }; - var nodeTab = TabController.SerializeTab(xmlTab, Tab, chkContent.Checked); - nodeTabs.AppendChild(xmlTemplate.ImportNode(nodeTab, true)); - } - - #region Event Handlers - + protected override void OnInit(EventArgs e) { base.OnInit(e); if (!TabPermissionController.CanExportPage()) { - Response.Redirect(Globals.AccessDeniedURL(), true); + this.Response.Redirect(Globals.AccessDeniedURL(), true); } } @@ -79,24 +58,28 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); - cmdExport.Click += OnExportClick; + this.cmdExport.Click += this.OnExportClick; try { - if (Page.IsPostBack) return; - cmdCancel.NavigateUrl = _navigationManager.NavigateURL(); + if (this.Page.IsPostBack) + { + return; + } + + this.cmdCancel.NavigateUrl = this._navigationManager.NavigateURL(); var folderPath = "Templates/"; - var templateFolder = FolderManager.Instance.GetFolder(UserInfo.PortalID, folderPath); - cboFolders.Services.Parameters.Add("permission", "ADD"); + var templateFolder = FolderManager.Instance.GetFolder(this.UserInfo.PortalID, folderPath); + this.cboFolders.Services.Parameters.Add("permission", "ADD"); - if (templateFolder != null && IsAccessibleByUser(templateFolder)) + if (templateFolder != null && this.IsAccessibleByUser(templateFolder)) { - cboFolders.SelectedFolder = templateFolder; + this.cboFolders.SelectedFolder = templateFolder; } - if (Tab != null) + if (this.Tab != null) { - txtFile.Text = Globals.CleanName(Tab.TabName); + this.txtFile.Text = Globals.CleanName(this.Tab.TabName); } } catch (Exception exc) @@ -105,26 +88,35 @@ protected override void OnLoad(EventArgs e) } } - private bool IsAccessibleByUser(IFolderInfo folder) + /// ----------------------------------------------------------------------------- + /// + /// Serializes the Tab. + /// + /// Reference to XmlDocument context. + /// Node to add the serialized objects. + /// ----------------------------------------------------------------------------- + private void SerializeTab(XmlDocument xmlTemplate, XmlNode nodeTabs) { - return FolderPermissionController.Instance.CanAddFolder(folder); - } + var xmlTab = new XmlDocument { XmlResolver = null }; + var nodeTab = TabController.SerializeTab(xmlTab, this.Tab, this.chkContent.Checked); + nodeTabs.AppendChild(xmlTemplate.ImportNode(nodeTab, true)); + } - protected void OnExportClick(Object sender, EventArgs e) + protected void OnExportClick(object sender, EventArgs e) { try { - if (!Page.IsValid) + if (!this.Page.IsValid) { return; } - if (cboFolders.SelectedItem != null) + if (this.cboFolders.SelectedItem != null) { - var folder = FolderManager.Instance.GetFolder(cboFolders.SelectedItemValueAsInt); + var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); if (folder != null) { - var filename = folder.FolderPath + txtFile.Text + ".page.template"; + var filename = folder.FolderPath + this.txtFile.Text + ".page.template"; filename = filename.Replace("/", "\\"); var xmlTemplate = new XmlDocument { XmlResolver = null }; @@ -134,23 +126,22 @@ protected void OnExportClick(Object sender, EventArgs e) nodePortal.Attributes.Append(XmlUtils.CreateAttribute(xmlTemplate, "version", "3.0")); } - //Add template description + // Add template description XmlElement node = xmlTemplate.CreateElement("description"); - node.InnerXml = Server.HtmlEncode(txtDescription.Text); + node.InnerXml = this.Server.HtmlEncode(this.txtDescription.Text); nodePortal.AppendChild(node); - //Serialize tabs + // Serialize tabs XmlNode nodeTabs = nodePortal.AppendChild(xmlTemplate.CreateElement("tabs")); - SerializeTab(xmlTemplate, nodeTabs); + this.SerializeTab(xmlTemplate, nodeTabs); - UI.Skins.Skin.AddModuleMessage(this, "", string.Format(Localization.GetString("ExportedMessage", LocalResourceFile), filename), ModuleMessage.ModuleMessageType.BlueInfo); - - //add file to Files table - using (var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(xmlTemplate.OuterXml))) - { - Services.FileSystem.FileManager.Instance.AddFile(folder, txtFile.Text + ".page.template", fileContent, true, true, "application/octet-stream"); - } + UI.Skins.Skin.AddModuleMessage(this, string.Empty, string.Format(Localization.GetString("ExportedMessage", this.LocalResourceFile), filename), ModuleMessage.ModuleMessageType.BlueInfo); + // add file to Files table + using (var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(xmlTemplate.OuterXml))) + { + Services.FileSystem.FileManager.Instance.AddFile(folder, this.txtFile.Text + ".page.template", fileContent, true, true, "application/octet-stream"); + } } } } @@ -158,10 +149,11 @@ protected void OnExportClick(Object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } + } + private bool IsAccessibleByUser(IFolderInfo folder) + { + return FolderPermissionController.Instance.CanAddFolder(folder); } - - #endregion - } } diff --git a/DNN Platform/Website/admin/Tabs/Import.ascx.cs b/DNN Platform/Website/admin/Tabs/Import.ascx.cs index 0aa1e6a0fdb..e843961daff 100644 --- a/DNN Platform/Website/admin/Tabs/Import.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Import.ascx.cs @@ -1,180 +1,188 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Web.UI.WebControls; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.UI.Skins.Controls; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Tabs { - + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.UI.WebControls; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.UI.Skins.Controls; + using Microsoft.Extensions.DependencyInjection; + public partial class Import : PortalModuleBase { private readonly INavigationManager _navigationManager; + private TabInfo _tab; + public Import() { - _navigationManager = DependencyProvider.GetRequiredService(); + this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private TabInfo _tab; - public TabInfo Tab { get { - if (_tab == null) + if (this._tab == null) + { + this._tab = TabController.Instance.GetTab(this.TabId, this.PortalId, false); + } + + return this._tab; + } + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (!TabPermissionController.CanImportPage()) + { + this.Response.Redirect(Globals.AccessDeniedURL(), true); + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboFolders.SelectionChanged += this.OnFolderIndexChanged; + this.cmdImport.Click += this.OnImportClick; + this.cboParentTab.SelectionChanged += this.OnParentTabIndexChanged; + this.cboTemplate.SelectedIndexChanged += this.OnTemplateIndexChanged; + this.optMode.SelectedIndexChanged += this.OptModeSelectedIndexChanged; + + try + { + if (!this.Page.IsPostBack) { - _tab = TabController.Instance.GetTab(TabId, PortalId, false); + this.cmdCancel.NavigateUrl = this._navigationManager.NavigateURL(); + this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); + var folders = FolderManager.Instance.GetFolders(this.UserInfo, "BROWSE, ADD"); + var templateFolder = folders.SingleOrDefault(f => f.FolderPath == "Templates/"); + if (templateFolder != null) + { + this.cboFolders.SelectedFolder = templateFolder; + } + + this.BindFiles(); + this.BindTabControls(); + this.DisplayNewRows(); } - return _tab; + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); } } private void BindBeforeAfterTabControls() { var noneSpecified = "<" + Localization.GetString("None_Specified") + ">"; - cboParentTab.UndefinedItem = new ListItem(noneSpecified, string.Empty); - var parentTab = cboParentTab.SelectedPage; + this.cboParentTab.UndefinedItem = new ListItem(noneSpecified, string.Empty); + var parentTab = this.cboParentTab.SelectedPage; - List listTabs = parentTab != null ? TabController.Instance.GetTabsByPortal(parentTab.PortalID).WithParentId(parentTab.TabID) : TabController.Instance.GetTabsByPortal(PortalId).WithParentId(Null.NullInteger); + List listTabs = parentTab != null ? TabController.Instance.GetTabsByPortal(parentTab.PortalID).WithParentId(parentTab.TabID) : TabController.Instance.GetTabsByPortal(this.PortalId).WithParentId(Null.NullInteger); listTabs = TabController.GetPortalTabs(listTabs, Null.NullInteger, true, noneSpecified, false, false, false, false, true); - cboPositionTab.DataSource = listTabs; - cboPositionTab.DataBind(); - rbInsertPosition.Items.Clear(); - rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertBefore", LocalResourceFile), "Before")); - rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAfter", LocalResourceFile), "After")); - rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAtEnd", LocalResourceFile), "AtEnd")); - rbInsertPosition.SelectedValue = "After"; + this.cboPositionTab.DataSource = listTabs; + this.cboPositionTab.DataBind(); + this.rbInsertPosition.Items.Clear(); + this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertBefore", this.LocalResourceFile), "Before")); + this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAfter", this.LocalResourceFile), "After")); + this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAtEnd", this.LocalResourceFile), "AtEnd")); + this.rbInsertPosition.SelectedValue = "After"; } private void BindFiles() { - cboTemplate.Items.Clear(); - if (cboFolders.SelectedItem != null) + this.cboTemplate.Items.Clear(); + if (this.cboFolders.SelectedItem != null) { - var folder = FolderManager.Instance.GetFolder(cboFolders.SelectedItemValueAsInt); + var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); if (folder != null) { - //var files = Directory.GetFiles(PortalSettings.HomeDirectoryMapPath + folder.FolderPath, "*.page.template"); - var files = Globals.GetFileList(PortalId, "page.template", false, folder.FolderPath); + // var files = Directory.GetFiles(PortalSettings.HomeDirectoryMapPath + folder.FolderPath, "*.page.template"); + var files = Globals.GetFileList(this.PortalId, "page.template", false, folder.FolderPath); foreach (FileItem file in files) { - cboTemplate.AddItem(file.Text.Replace(".page.template", ""), file.Value); + this.cboTemplate.AddItem(file.Text.Replace(".page.template", string.Empty), file.Value); } - cboTemplate.InsertItem(0, "<" + Localization.GetString("None_Specified") + ">", "None_Specified"); - cboTemplate.SelectedIndex = 0; + + this.cboTemplate.InsertItem(0, "<" + Localization.GetString("None_Specified") + ">", "None_Specified"); + this.cboTemplate.SelectedIndex = 0; } - } } private void BindTabControls() { - BindBeforeAfterTabControls(); - divInsertPositionRow.Visible = cboPositionTab.Items.Count > 0; - cboParentTab.AutoPostBack = true; - if (cboPositionTab.FindItemByValue(TabId.ToString(CultureInfo.InvariantCulture)) != null) + this.BindBeforeAfterTabControls(); + this.divInsertPositionRow.Visible = this.cboPositionTab.Items.Count > 0; + this.cboParentTab.AutoPostBack = true; + if (this.cboPositionTab.FindItemByValue(this.TabId.ToString(CultureInfo.InvariantCulture)) != null) { - cboPositionTab.ClearSelection(); - cboPositionTab.FindItemByValue(TabId.ToString(CultureInfo.InvariantCulture)).Selected = true; + this.cboPositionTab.ClearSelection(); + this.cboPositionTab.FindItemByValue(this.TabId.ToString(CultureInfo.InvariantCulture)).Selected = true; } } private void DisplayNewRows() { - divTabName.Visible = (optMode.SelectedIndex == 0); - divParentTab.Visible = (optMode.SelectedIndex == 0); - divInsertPositionRow.Visible = (optMode.SelectedIndex == 0); - divInsertPositionRow.Visible = (optMode.SelectedIndex == 0); - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (!TabPermissionController.CanImportPage()) - { - Response.Redirect(Globals.AccessDeniedURL(), true); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - cboFolders.SelectionChanged += OnFolderIndexChanged; - cmdImport.Click += OnImportClick; - cboParentTab.SelectionChanged += OnParentTabIndexChanged; - cboTemplate.SelectedIndexChanged += OnTemplateIndexChanged; - optMode.SelectedIndexChanged += OptModeSelectedIndexChanged; - - try - { - if (!Page.IsPostBack) - { - cmdCancel.NavigateUrl = _navigationManager.NavigateURL(); - cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); - var folders = FolderManager.Instance.GetFolders(UserInfo, "BROWSE, ADD"); - var templateFolder = folders.SingleOrDefault(f => f.FolderPath == "Templates/"); - if (templateFolder != null) cboFolders.SelectedFolder = templateFolder; - - BindFiles(); - BindTabControls(); - DisplayNewRows(); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } + this.divTabName.Visible = this.optMode.SelectedIndex == 0; + this.divParentTab.Visible = this.optMode.SelectedIndex == 0; + this.divInsertPositionRow.Visible = this.optMode.SelectedIndex == 0; + this.divInsertPositionRow.Visible = this.optMode.SelectedIndex == 0; } protected void OnFolderIndexChanged(object sender, EventArgs e) { - BindFiles(); + this.BindFiles(); } protected void OnImportClick(object sender, EventArgs e) { try { - if (cboTemplate.SelectedItem == null || cboTemplate.SelectedValue == "None_Specified") + if (this.cboTemplate.SelectedItem == null || this.cboTemplate.SelectedValue == "None_Specified") { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyFile", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyFile", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - if (optMode.SelectedIndex == -1) + + if (this.optMode.SelectedIndex == -1) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyMode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyMode", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - if (cboFolders.SelectedItem == null) return; - var selectedFolder = FolderManager.Instance.GetFolder(cboFolders.SelectedItemValueAsInt); - if (selectedFolder == null) return; - - var selectedFile = Services.FileSystem.FileManager.Instance.GetFile(Convert.ToInt32(cboTemplate.SelectedValue)); + + if (this.cboFolders.SelectedItem == null) + { + return; + } + + var selectedFolder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); + if (selectedFolder == null) + { + return; + } + + var selectedFile = Services.FileSystem.FileManager.Instance.GetFile(Convert.ToInt32(this.cboTemplate.SelectedValue)); var xmlDoc = new XmlDocument { XmlResolver = null }; using (var content = Services.FileSystem.FileManager.Instance.GetFileContent(selectedFile)) { @@ -187,56 +195,59 @@ protected void OnImportClick(object sender, EventArgs e) { tabNodes.AddRange(selectSingleNode.ChildNodes.Cast()); } + if (tabNodes.Count == 0) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoTabsInTemplate", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoTabsInTemplate", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } TabInfo objTab; - if (optMode.SelectedValue == "ADD") + if (this.optMode.SelectedValue == "ADD") { - //Check for invalid + // Check for invalid string invalidType; - if (!TabController.IsValidTabName(txtTabName.Text, out invalidType)) + if (!TabController.IsValidTabName(this.txtTabName.Text, out invalidType)) { - var warningMessage = string.Format(Localization.GetString(invalidType, LocalResourceFile), txtTabName.Text); + var warningMessage = string.Format(Localization.GetString(invalidType, this.LocalResourceFile), this.txtTabName.Text); UI.Skins.Skin.AddModuleMessage(this, warningMessage, ModuleMessage.ModuleMessageType.RedError); return; } - //New Tab - objTab = new TabInfo { PortalID = PortalId, TabName = txtTabName.Text, IsVisible = true }; - var parentId = cboParentTab.SelectedItemValueAsInt; + // New Tab + objTab = new TabInfo { PortalID = this.PortalId, TabName = this.txtTabName.Text, IsVisible = true }; + var parentId = this.cboParentTab.SelectedItemValueAsInt; if (parentId != Null.NullInteger) { objTab.ParentId = parentId; } + objTab.TabPath = Globals.GenerateTabPath(objTab.ParentId, objTab.TabName); var tabId = TabController.GetTabByTabPath(objTab.PortalID, objTab.TabPath, Null.NullString); - //Check if tab exists + // Check if tab exists if (tabId != Null.NullInteger) { - TabInfo existingTab = TabController.Instance.GetTab(tabId, PortalId, false); + TabInfo existingTab = TabController.Instance.GetTab(tabId, this.PortalId, false); if (existingTab != null && existingTab.IsDeleted) { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabRecycled", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabRecycled", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); } else { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabExists", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } + return; } - var positionTabId = Int32.Parse(cboPositionTab.SelectedItem.Value); + var positionTabId = int.Parse(this.cboPositionTab.SelectedItem.Value); - if (rbInsertPosition.SelectedValue == "After" && positionTabId > Null.NullInteger) + if (this.rbInsertPosition.SelectedValue == "After" && positionTabId > Null.NullInteger) { objTab.TabID = TabController.Instance.AddTabAfter(objTab, positionTabId); } - else if (rbInsertPosition.SelectedValue == "Before" && positionTabId > Null.NullInteger) + else if (this.rbInsertPosition.SelectedValue == "Before" && positionTabId > Null.NullInteger) { objTab.TabID = TabController.Instance.AddTabBefore(objTab, positionTabId); } @@ -244,17 +255,19 @@ protected void OnImportClick(object sender, EventArgs e) { objTab.TabID = TabController.Instance.AddTab(objTab); } - EventLogController.Instance.AddLog(objTab, PortalSettings, UserId, "", EventLogController.EventLogType.TAB_CREATED); + + EventLogController.Instance.AddLog(objTab, this.PortalSettings, this.UserId, string.Empty, EventLogController.EventLogType.TAB_CREATED); - objTab = TabController.DeserializeTab(tabNodes[0], objTab, PortalId, PortalTemplateModuleAction.Replace); + objTab = TabController.DeserializeTab(tabNodes[0], objTab, this.PortalId, PortalTemplateModuleAction.Replace); var exceptions = string.Empty; - //Create second tabs onwards. For firs tab, we like to use tab details from text box, for rest it'll come from template + + // Create second tabs onwards. For firs tab, we like to use tab details from text box, for rest it'll come from template for (var tab = 1; tab < tabNodes.Count; tab++) { try { - TabController.DeserializeTab(tabNodes[tab], null, PortalId, PortalTemplateModuleAction.Replace); + TabController.DeserializeTab(tabNodes[tab], null, this.PortalId, PortalTemplateModuleAction.Replace); } catch (Exception ex) { @@ -262,6 +275,7 @@ protected void OnImportClick(object sender, EventArgs e) exceptions += string.Format("Template Tab # {0}. Error {1}
        ", tab + 1, ex.Message); } } + if (!string.IsNullOrEmpty(exceptions)) { UI.Skins.Skin.AddModuleMessage(this, exceptions, ModuleMessage.ModuleMessageType.RedError); @@ -270,16 +284,17 @@ protected void OnImportClick(object sender, EventArgs e) } else { - //Replace Existing Tab - objTab = TabController.DeserializeTab(tabNodes[0], Tab, PortalId, PortalTemplateModuleAction.Replace); + // Replace Existing Tab + objTab = TabController.DeserializeTab(tabNodes[0], this.Tab, this.PortalId, PortalTemplateModuleAction.Replace); } - switch (optRedirect.SelectedValue) + + switch (this.optRedirect.SelectedValue) { case "VIEW": - Response.Redirect(_navigationManager.NavigateURL(objTab.TabID), true); + this.Response.Redirect(this._navigationManager.NavigateURL(objTab.TabID), true); break; default: - Response.Redirect(_navigationManager.NavigateURL(objTab.TabID, "Tab", "action=edit"), true); + this.Response.Redirect(this._navigationManager.NavigateURL(objTab.TabID, "Tab", "action=edit"), true); break; } } @@ -291,36 +306,36 @@ protected void OnImportClick(object sender, EventArgs e) protected void OnParentTabIndexChanged(object sender, EventArgs e) { - BindBeforeAfterTabControls(); + this.BindBeforeAfterTabControls(); } - protected void OnTemplateIndexChanged(Object sender, EventArgs e) + protected void OnTemplateIndexChanged(object sender, EventArgs e) { try { - if (cboTemplate.SelectedIndex > 0 && cboFolders.SelectedItem != null) + if (this.cboTemplate.SelectedIndex > 0 && this.cboFolders.SelectedItem != null) { - var selectedFile = Services.FileSystem.FileManager.Instance.GetFile(Convert.ToInt32(cboTemplate.SelectedValue)); + var selectedFile = Services.FileSystem.FileManager.Instance.GetFile(Convert.ToInt32(this.cboTemplate.SelectedValue)); var xmldoc = new XmlDocument { XmlResolver = null }; using (var fileContent = Services.FileSystem.FileManager.Instance.GetFileContent(selectedFile)) { xmldoc.Load(fileContent); var node = xmldoc.SelectSingleNode("//portal/description"); - if (node != null && !String.IsNullOrEmpty(node.InnerXml)) + if (node != null && !string.IsNullOrEmpty(node.InnerXml)) { - lblTemplateDescription.Visible = true; - lblTemplateDescription.Text = Server.HtmlDecode(node.InnerXml); - txtTabName.Text = cboTemplate.SelectedItem.Text; + this.lblTemplateDescription.Visible = true; + this.lblTemplateDescription.Text = this.Server.HtmlDecode(node.InnerXml); + this.txtTabName.Text = this.cboTemplate.SelectedItem.Text; } else { - lblTemplateDescription.Visible = false; + this.lblTemplateDescription.Visible = false; } } } else { - lblTemplateDescription.Visible = false; + this.lblTemplateDescription.Visible = false; } } catch (Exception exc) @@ -331,8 +346,7 @@ protected void OnTemplateIndexChanged(Object sender, EventArgs e) protected void OptModeSelectedIndexChanged(object sender, EventArgs e) { - DisplayNewRows(); + this.DisplayNewRows(); } - } } diff --git a/DNN Platform/Website/admin/Users/App_LocalResources/ViewProfile.ascx.resx b/DNN Platform/Website/admin/Users/App_LocalResources/ViewProfile.ascx.resx index 9fbb03dc969..0a12da5b914 100644 --- a/DNN Platform/Website/admin/Users/App_LocalResources/ViewProfile.ascx.resx +++ b/DNN Platform/Website/admin/Users/App_LocalResources/ViewProfile.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs b/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs index 9aa60fae84a..0c010d27a4d 100644 --- a/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs +++ b/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs @@ -1,35 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Linq; - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Profile; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Exceptions; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.Admin.Users { + using System; + using System.Linq; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Profile; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Exceptions; + public partial class ViewProfile : UserModuleBase { protected override void OnInit(EventArgs e) { base.OnInit(e); - UserId = Null.NullInteger; - if (Context.Request.QueryString["userticket"] != null) + this.UserId = Null.NullInteger; + if (this.Context.Request.QueryString["userticket"] != null) { - UserId = Int32.Parse(UrlUtils.DecryptParameter(Context.Request.QueryString["userticket"])); + this.UserId = int.Parse(UrlUtils.DecryptParameter(this.Context.Request.QueryString["userticket"])); } - ctlProfile.ID = "Profile"; - ctlProfile.UserId = UserId; + + this.ctlProfile.ID = "Profile"; + this.ctlProfile.UserId = this.UserId; } protected override void OnLoad(EventArgs e) @@ -37,15 +33,16 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - if (ctlProfile.UserProfile == null) + if (this.ctlProfile.UserProfile == null) { - lblNoProperties.Visible = true; + this.lblNoProperties.Visible = true; return; } - ctlProfile.DataBind(); - if (ctlProfile.UserProfile.ProfileProperties.Cast().Count(profProperty => profProperty.Visible) == 0) + + this.ctlProfile.DataBind(); + if (this.ctlProfile.UserProfile.ProfileProperties.Cast().Count(profProperty => profProperty.Visible) == 0) { - lblNoProperties.Visible = true; + this.lblNoProperties.Visible = true; } } catch (Exception exc) diff --git a/DNN Platform/Website/controls/App_LocalResources/Address.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/Address.ascx.resx index 1e7e4d3a596..4bb41676bff 100644 --- a/DNN Platform/Website/controls/App_LocalResources/Address.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/Address.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/controls/App_LocalResources/DualListControl.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/DualListControl.ascx.resx index b31b693d5cc..9b11e7b9e44 100644 --- a/DNN Platform/Website/controls/App_LocalResources/DualListControl.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/DualListControl.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/controls/App_LocalResources/Help.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/Help.ascx.resx index 0469b7cdee8..e170dfc6e00 100644 --- a/DNN Platform/Website/controls/App_LocalResources/Help.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/Help.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/controls/App_LocalResources/LocaleSelectorControl.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/LocaleSelectorControl.ascx.resx index 2828d8c998b..bd2dc608ce6 100644 --- a/DNN Platform/Website/controls/App_LocalResources/LocaleSelectorControl.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/LocaleSelectorControl.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/controls/App_LocalResources/ModuleAuditControl.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/ModuleAuditControl.ascx.resx index c88eeb12c57..309c08c8e3c 100644 --- a/DNN Platform/Website/controls/App_LocalResources/ModuleAuditControl.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/ModuleAuditControl.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/controls/App_LocalResources/SkinControl.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/SkinControl.ascx.resx index 5cfd6f1280c..51df06e316a 100644 --- a/DNN Platform/Website/controls/App_LocalResources/SkinControl.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/SkinControl.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/controls/App_LocalResources/TextEditor.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/TextEditor.ascx.resx index b83533c6857..cfbe79f0d0c 100644 --- a/DNN Platform/Website/controls/App_LocalResources/TextEditor.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/TextEditor.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/controls/App_LocalResources/URLControl.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/URLControl.ascx.resx index aa6cb0c8707..29cce36b0b3 100644 --- a/DNN Platform/Website/controls/App_LocalResources/URLControl.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/URLControl.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/controls/App_LocalResources/UrlTrackingControl.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/UrlTrackingControl.ascx.resx index bff3dd3c683..6c216ead038 100644 --- a/DNN Platform/Website/controls/App_LocalResources/UrlTrackingControl.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/UrlTrackingControl.ascx.resx @@ -1,6 +1,6 @@  - + diff --git a/DNN Platform/Website/controls/App_LocalResources/User.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/User.ascx.resx index e32795e5518..a6990233f1e 100644 --- a/DNN Platform/Website/controls/App_LocalResources/User.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/User.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/controls/App_LocalResources/filepickeruploader.ascx.resx b/DNN Platform/Website/controls/App_LocalResources/filepickeruploader.ascx.resx index dfdab8bd98b..f1488165444 100644 --- a/DNN Platform/Website/controls/App_LocalResources/filepickeruploader.ascx.resx +++ b/DNN Platform/Website/controls/App_LocalResources/filepickeruploader.ascx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/DNN Platform/Website/images/Branding/logo.gif b/DNN Platform/Website/images/Branding/logo.gif deleted file mode 100644 index aaaa340e519..00000000000 Binary files a/DNN Platform/Website/images/Branding/logo.gif and /dev/null differ diff --git a/DNN Platform/Website/packages.config b/DNN Platform/Website/packages.config index 2a88191ad8c..06423a378eb 100644 --- a/DNN Platform/Website/packages.config +++ b/DNN Platform/Website/packages.config @@ -10,4 +10,5 @@ + \ No newline at end of file diff --git a/DNN_Platform.sln b/DNN_Platform.sln index 0cffbf15bfa..e2fb7515dc7 100644 --- a/DNN_Platform.sln +++ b/DNN_Platform.sln @@ -121,6 +121,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution README.md = README.md Packages\repositories.config = Packages\repositories.config SolutionInfo.cs = SolutionInfo.cs + stylecop.json = stylecop.json EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetNuke.Tests.Integration", "DNN Platform\Tests\DotNetNuke.Tests.Integration\DotNetNuke.Tests.Integration.csproj", "{6629A64D-58B9-48B9-B932-15AF193C2212}" diff --git a/Dnn.AdminExperience/ClientSide/AdminLogs.Web/package.json b/Dnn.AdminExperience/ClientSide/AdminLogs.Web/package.json index 6f3718db037..cb917e6456d 100644 --- a/Dnn.AdminExperience/ClientSide/AdminLogs.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/AdminLogs.Web/package.json @@ -1,6 +1,6 @@ { "name": "admin_logs", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -15,7 +15,7 @@ "@babel/plugin-transform-object-assign": "^7.0.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "2.0.4", "array.prototype.findindex": "2.0.2", "babel-loader": "8.0.6", diff --git a/Dnn.AdminExperience/ClientSide/Bundle.Web/package.json b/Dnn.AdminExperience/ClientSide/Bundle.Web/package.json index 70eadb3eb9f..90b45fdabea 100644 --- a/Dnn.AdminExperience/ClientSide/Bundle.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Bundle.Web/package.json @@ -1,6 +1,6 @@ { "name": "export-bundle", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p --progress", @@ -66,6 +66,6 @@ "webpack-dev-server": "3.1.14" }, "dependencies": { - "@dnnsoftware/dnn-react-common": "9.6.1" + "@dnnsoftware/dnn-react-common": "9.6.2" } } \ No newline at end of file diff --git a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/package.json b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/package.json index f8002fd9079..359abe9ec46 100644 --- a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/package.json +++ b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/package.json @@ -1,6 +1,6 @@ { "name": "@dnnsoftware/dnn-react-common", - "version": "9.6.1", + "version": "9.6.2", "private": false, "description": "DNN React Component Library", "main": "dist/dnn-react-common.min.js", diff --git a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/Browse/index.jsx b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/Browse/index.jsx index df35e008257..f054889884b 100644 --- a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/Browse/index.jsx +++ b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/Browse/index.jsx @@ -96,10 +96,56 @@ export default class Browse extends Component { sf.get("GetFolderDescendants", { parentId }, this.addChildFolders.bind(this, parentId), this.handleError.bind(this)); } + getExtensions(fileFormats) { + let result = ""; + + const extensions = { + "text/html": "htm,html", + "text/css": "css", + "text/xml": "xml", + "image/gif": "gif", + "image/jpeg": "jpeg,jpg", + "application/x-javascript": "js", + "text/plain": "txt", + "image/png": "png", + "image/tiff": "tif,tiff", + "image/x-icon": "ico", + "image/x-ms-bmp": "bmp", + "image/svg+xml": "svg", + "image/webp": "webp", + "application/msword": "doc", + "application/pdf": "pdf", + "application/rtf": "rtf", + "application/vnd.ms-excel": "xls", + "application.vnd.ms-powerpoint": "ppt", + "application/x-shockwave-flash": "swf", + "appliation/zip": "zip", + "audio/mpeg": "mp3", + "audio/ogg": "ogg", + "video/3gpp": "3gpp,3gp", + "video/mpeg": "mpeg,mpg", + "video/quicktime": "mov", + "video/x-flv": "flv", + "video/x-ms-wmv": "wmv", + "video/x-msvideo": "avi", + "video/mp4": "m4v,mp4", + }; + + fileFormats.map(fileFormat => { + if (extensions[fileFormat]) { + result += extensions[fileFormat] + ","; + } + else { + result += fileFormat.split("/")[1] + ","; + } + }); + return result; + } + getFiles() { const sf = this.getServiceFramework(); let parentId = this.state.selectedFolder ? this.state.selectedFolder.key : null; - const extensions = this.props.fileFormats.map(format => format.split("/")[1]).join(","); + const extensions = this.getExtensions(this.props.fileFormats); if (parentId) { sf.get("GetFiles", { parentId, filter: extensions }, this.setFiles.bind(this), this.handleError.bind(this)); } else if (this.state.selectedFolder) { @@ -111,7 +157,7 @@ export default class Browse extends Component { setFolderId(result) { const selectedFolder = result.Tree.children[0].data; - const extensions = this.props.fileFormats.map(format => format.split("/")[1]).join(","); + const extensions = this.getExtensions(this.props.fileFormats); const sf = this.getServiceFramework(); sf.get("GetFiles", { parentId: selectedFolder.key, filter: extensions }, this.setFiles.bind(this), this.handleError.bind(this)); } diff --git a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/index.jsx b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/index.jsx index 2752acc9c28..e9b964b4e69 100644 --- a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/index.jsx +++ b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/FileUpload/index.jsx @@ -263,6 +263,9 @@ export default class FileUpload extends Component { if (this.props.folderName && typeof this.props.folderName === "string") { formData.append("folder", this.props.folderName); } + if (this.props.validationCode && typeof this.props.validationCode === "string") { + formData.append("validationCode", this.props.validationCode); + } sf.postfile(`UploadFromLocal${this.props.portalId === -1 ? "" : "?portalId=" + this.props.portalId}` , formData, this.uploadComplete.bind(this), this.handleError.bind(this)); this.setState({ uploading: true, uploadComplete: false }); @@ -427,6 +430,7 @@ FileUpload.propTypes = { //---REQUIRED PROPS--- utils: PropTypes.object.isRequired, onSelectFile: PropTypes.func.isRequired, + validationCode: PropTypes.string.isRequired, //---OPTIONAL PROPS--- selectedFile: PropTypes.object, @@ -463,7 +467,6 @@ FileUpload.defaultProps = { cropImagePreview: false, portalId: -1, fileFormats: [], - browseButtonText: "Browse Filesystem", uploadButtonText: "Upload a File", linkButtonText: "Enter URL Link", diff --git a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/PersonaBarPageHeader/index.jsx b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/PersonaBarPageHeader/index.jsx index e48685e24bd..c5a3665bf29 100644 --- a/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/PersonaBarPageHeader/index.jsx +++ b/Dnn.AdminExperience/ClientSide/Dnn.React.Common/src/PersonaBarPageHeader/index.jsx @@ -19,7 +19,7 @@ const hotspotStyles = { const PersonaBarPageHeader = ({ title, children, tooltip, titleMaxWidth, titleCharLimit }) => { - titleCharLimit = titleCharLimit ? titleCharLimit : 20; + titleCharLimit = titleCharLimit ? titleCharLimit : 50; const renderTitle = () => { switch (true) { diff --git a/Dnn.AdminExperience/ClientSide/Extensions.Web/package.json b/Dnn.AdminExperience/ClientSide/Extensions.Web/package.json index cb56b979038..2881238dc77 100644 --- a/Dnn.AdminExperience/ClientSide/Extensions.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Extensions.Web/package.json @@ -1,6 +1,6 @@ { "name": "extensions", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -13,7 +13,7 @@ "@babel/core": "^7.2.0", "@babel/preset-env": "^7.2.0", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-loader": "8.0.6", "babel-plugin-transform-object-assign": "6.22.0", "babel-plugin-transform-object-rest-spread": "6.26.0", diff --git a/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/index.jsx b/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/index.jsx index 74b114b2d8a..c7d1b3b857d 100644 --- a/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/index.jsx +++ b/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/index.jsx @@ -55,8 +55,8 @@ class ExtensionDetailRow extends Component { {this.getInUseDisplay(props._package.friendlyName, props._package.packageId)} - - Update + + Update diff --git a/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/style.less b/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/style.less index bea5c486fc2..9d4a19f545b 100644 --- a/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/style.less +++ b/Dnn.AdminExperience/ClientSide/Extensions.Web/src/components/Body/InstalledExtensions/common/ExtensionDetailRow/style.less @@ -21,7 +21,7 @@ font-weight: bold; margin-bottom: 3px; } - .in-use{ + .in-use { color: @curiousBlue; cursor: pointer; } diff --git a/Dnn.AdminExperience/ClientSide/Licensing.Web/package.json b/Dnn.AdminExperience/ClientSide/Licensing.Web/package.json index b591b63b2a7..f3b21c389cb 100644 --- a/Dnn.AdminExperience/ClientSide/Licensing.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Licensing.Web/package.json @@ -1,6 +1,6 @@ { "name": "licensing", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -13,10 +13,9 @@ "@babel/core": "^7.1.6", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "2.0.4", "array.prototype.findindex": "2.0.2", - "babel-core": "6.26.3", "babel-loader": "8.0.6", "babel-plugin-transform-object-assign": "6.22.0", "babel-plugin-transform-object-rest-spread": "6.26.0", @@ -44,4 +43,4 @@ "webpack-dev-server": "^3.1.14" }, "dependencies": {} -} \ No newline at end of file +} diff --git a/Dnn.AdminExperience/ClientSide/Pages.Web/package.json b/Dnn.AdminExperience/ClientSide/Pages.Web/package.json index 47448304fbe..b553597326a 100644 --- a/Dnn.AdminExperience/ClientSide/Pages.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Pages.Web/package.json @@ -1,6 +1,6 @@ { "name": "pages", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "start": "npm run webpack", @@ -23,10 +23,9 @@ "@babel/plugin-proposal-object-rest-spread": "^7.0.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "@types/knockout": "^3.4.66", "@types/redux": "3.6.31", - "babel-core": "^7.0.0-bridge.0", "babel-eslint": "^10.0.1", "babel-jest": "^24.8.0", "babel-loader": "8.0.6", @@ -74,4 +73,4 @@ "react-day-picker": "^7.2.4", "url-parse": "^1.2.0" } -} \ No newline at end of file +} diff --git a/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageDetails.jsx b/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageDetails.jsx index d788b74c183..a89131634d4 100644 --- a/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageDetails.jsx +++ b/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageDetails.jsx @@ -23,12 +23,10 @@ class PageDetail extends Component { render() { const DetailComponent = this.getDetail(this.props.page.pageType); - - return (
        - +
        ); diff --git a/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageIcons/PageIcons.jsx b/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageIcons/PageIcons.jsx index 4916a626e2b..4dd11e6e11b 100644 --- a/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageIcons/PageIcons.jsx +++ b/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/PageDetails/PageIcons/PageIcons.jsx @@ -32,6 +32,7 @@ export default class PageIcons extends Component { selectedFile={props.page.iconFile} folderName={props.page.iconFile ? props.page.iconFile.folderName: null} fileFormats={["image/png", "image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/svg+xml"]} + validationCode={props.validationCode} browseActionText={Localization.get("BrowseAction")} // Press {save|[ENTER]} to save, or {cancel|[ESC]} to cancel browseButtonText={Localization.get("BrowseButton")} // Browse Filesystem defaultText={Localization.get("DragOver")} // Drag and Drop a File @@ -63,6 +64,7 @@ export default class PageIcons extends Component { selectedFile={props.page.iconFileLarge} folderName={props.page.iconFileLarge ? props.page.iconFileLarge.folderName : null} fileFormats={["image/png", "image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/svg+xml"]} + validationCode={props.validationCode} browseActionText={Localization.get("BrowseAction")} // Press {save|[ENTER]} to save, or {cancel|[ESC]} to cancel browseButtonText={Localization.get("BrowseButton")} // Browse Filesystem defaultText={Localization.get("DragOver")} // Drag and Drop a File @@ -91,6 +93,7 @@ export default class PageIcons extends Component { PageIcons.propTypes = { page: PropTypes.object.isRequired, + validationCode: PropTypes.string.isRequired, errors: PropTypes.object.isRequired, onChangeField: PropTypes.func.isRequired, components: PropTypes.array.isRequired diff --git a/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/Seo/PageUrls/EditUrl.jsx b/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/Seo/PageUrls/EditUrl.jsx index 6bfe58a7fb4..9e1e035e11e 100644 --- a/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/Seo/PageUrls/EditUrl.jsx +++ b/Dnn.AdminExperience/ClientSide/Pages.Web/src/components/Seo/PageUrls/EditUrl.jsx @@ -75,6 +75,10 @@ class EditUrl extends Component { const {url, saving, pageHasParent, siteAliases, primaryAliasId, isOpened, onSave, onCancel} = this.props; const aliases = this.getOptions(siteAliases); const siteAliasUsageOptions = this.getSiteAliasUsageOptions(pageHasParent); + if (!this.state.hasChanges && url.siteAlias.Key !== primaryAliasId) + { + this.props.onChange("siteAlias", primaryAliasId); + } return (
        diff --git a/Dnn.AdminExperience/ClientSide/Pages.Web/src/services/pageService.js b/Dnn.AdminExperience/ClientSide/Pages.Web/src/services/pageService.js index 3d879c85747..8d086eeb23f 100644 --- a/Dnn.AdminExperience/ClientSide/Pages.Web/src/services/pageService.js +++ b/Dnn.AdminExperience/ClientSide/Pages.Web/src/services/pageService.js @@ -115,10 +115,11 @@ const PageService = function () { }); }; - const toFrontEndPage = function (page) { + const toFrontEndPage = function (pageResult) { return { - ...page, - schedulingEnabled: page.startDate || page.endDate + ...pageResult.page, + schedulingEnabled: pageResult.page.startDate || pageResult.page.endDate, + validationCode: pageResult.ValidationCode, }; }; diff --git a/Dnn.AdminExperience/ClientSide/Prompt.Web/package.json b/Dnn.AdminExperience/ClientSide/Prompt.Web/package.json index cd0fee4db08..f6e67328a76 100644 --- a/Dnn.AdminExperience/ClientSide/Prompt.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Prompt.Web/package.json @@ -1,6 +1,6 @@ { "name": "prompt", - "version": "9.6.1", + "version": "9.6.2", "description": "DNN Prompt", "private": true, "scripts": { @@ -15,10 +15,9 @@ "@babel/core": "^7.1.6", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "2.0.4", "array.prototype.findindex": "2.0.2", - "babel-core": "^7.0.0-bridge.0", "babel-eslint": "^10.0.1", "babel-jest": "^24.8.0", "babel-loader": "^8.0.6", @@ -77,4 +76,4 @@ "dependencies": { "html-react-parser": "^0.7.0" } -} \ No newline at end of file +} diff --git a/Dnn.AdminExperience/ClientSide/Roles.Web/package.json b/Dnn.AdminExperience/ClientSide/Roles.Web/package.json index feae17aec3a..6864c5bc3f5 100644 --- a/Dnn.AdminExperience/ClientSide/Roles.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Roles.Web/package.json @@ -1,6 +1,6 @@ { "name": "roles", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -13,7 +13,7 @@ "@babel/core": "^7.1.6", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "^2.0.0", "array.prototype.findindex": "^2.0.0", "babel-loader": "^8.0.6", diff --git a/Dnn.AdminExperience/ClientSide/Security.Web/package.json b/Dnn.AdminExperience/ClientSide/Security.Web/package.json index f0606de19e4..f7ed2d379a8 100644 --- a/Dnn.AdminExperience/ClientSide/Security.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Security.Web/package.json @@ -1,6 +1,6 @@ { "name": "security_settings", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -15,7 +15,7 @@ "@babel/plugin-transform-react-jsx": "^7.2.0", "@babel/preset-env": "^7.2.0", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-loader": "8.0.6", "babel-plugin-transform-react-remove-prop-types": "0.4.24", "create-react-class": "^15.6.3", diff --git a/Dnn.AdminExperience/ClientSide/Seo.Web/package.json b/Dnn.AdminExperience/ClientSide/Seo.Web/package.json index 006d040d380..0563cfaefcf 100644 --- a/Dnn.AdminExperience/ClientSide/Seo.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Seo.Web/package.json @@ -1,6 +1,6 @@ { "name": "seo", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -14,10 +14,9 @@ "@babel/plugin-proposal-object-rest-spread": "^7.2.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "2.0.4", "array.prototype.findindex": "2.0.2", - "babel-core": "6.26.3", "babel-loader": "8.0.6", "babel-plugin-transform-object-assign": "6.22.0", "babel-plugin-transform-object-rest-spread": "6.26.0", @@ -48,4 +47,4 @@ "webpack-dev-server": "^3.1.14" }, "dependencies": {} -} \ No newline at end of file +} diff --git a/Dnn.AdminExperience/ClientSide/Servers.Web/package.json b/Dnn.AdminExperience/ClientSide/Servers.Web/package.json index b82c65e6933..fd6981af11c 100644 --- a/Dnn.AdminExperience/ClientSide/Servers.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Servers.Web/package.json @@ -1,6 +1,6 @@ { "name": "servers", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -14,9 +14,8 @@ "@babel/plugin-proposal-object-rest-spread": "^7.2.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "@types/redux": "^3.6.31", - "babel-core": "6.26.3", "babel-loader": "8.0.6", "babel-plugin-transform-object-assign": "6.22.0", "babel-plugin-transform-object-rest-spread": "6.26.0", @@ -31,6 +30,7 @@ "file-loader": "3.0.1", "less": "3.9.0", "less-loader": "5.0.0", + "moment": "^2.15.0", "prop-types": "^15.6.2", "raw-loader": "2.0.0", "react": "^16.6.3", @@ -46,4 +46,4 @@ "dependencies": { "react-custom-scrollbars": "^4.1.1" } -} \ No newline at end of file +} diff --git a/Dnn.AdminExperience/ClientSide/Servers.Web/src/actions/logsTab.js b/Dnn.AdminExperience/ClientSide/Servers.Web/src/actions/logsTab.js index 19fe511950c..c89ab359616 100644 --- a/Dnn.AdminExperience/ClientSide/Servers.Web/src/actions/logsTab.js +++ b/Dnn.AdminExperience/ClientSide/Servers.Web/src/actions/logsTab.js @@ -33,7 +33,7 @@ const logsTabActions = { return; } - const logName = log.value; + const logName = log.name; const upgradeLog = log.upgradeLog; dispatch({ type: ActionTypes.LOAD_LOG, diff --git a/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/LogFileRow/index.jsx b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/LogFileRow/index.jsx new file mode 100644 index 00000000000..82c9b62c3d7 --- /dev/null +++ b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/LogFileRow/index.jsx @@ -0,0 +1,134 @@ +import PropTypes from "prop-types"; +import React, { Component } from "react"; +import { connect } from "react-redux"; +import { Collapsible as Collapse } from "@dnnsoftware/dnn-react-common"; +import "./style.less"; +import moment from "moment"; +import { log as LogActions } from "../../../actions"; + +/*eslint-disable eqeqeq*/ +class LogFileRow extends Component { + constructor() { + super(); + this.state = { + collapsed: true, + collapsedClass: true, + repainting: false, + }; + this.timeout = 0; + this.handleClick = this.handleClick.bind(this); + } + + componentWillReceiveProps() { + this.setState({}); + } + + componentDidMount() { + document.addEventListener("click", this.handleClick); + this._isMounted = true; + } + + componentWillUnmount() { + document.removeEventListener("click", this.handleClick); + this._isMounted = false; + } + + handleClick(event) { + // Note: this workaround is needed in IE. The remove event listener in the componentWillUnmount is called + // before the handleClick handler is called, but in spite of that, the handleClick is executed. To avoid + // the "findDOMNode was called on an unmounted component." error we need to check if the component is mounted before execute this code + if (!this._isMounted) { + return; + } + + if ( + !this.node.contains(event.target) && + typeof event.target.className == "string" && + event.target.className.indexOf("do-not-close") == -1 + ) { + this.timeout = 475; + this.collapse(); + } else { + this.timeout = 0; + } + } + + uncollapse() { + setTimeout(() => { + this.setState({ + collapsed: false, + }); + }, this.timeout); + } + + collapse() { + this.setState({ + collapsed: true, + }); + } + + toggle() { + if (this.state.collapsed) { + this.uncollapse(); + this.props.onOpen(); + } else { + this.collapse(); + } + } + + render() { + const { props, state } = this; + return ( +
        (this.node = node)} + className={"collapsible-logitemdetail " + state.collapsed} + > +
        +
        +
        +
        + {this.props.typeName} +
        +
        +
        +
        + {this.props.fileName} +
        +
        +
        +
        + {moment(this.props.lastWriteTimeUtc).format("LLL")} +
        +
        +
        +
        + {this.props.size} +
        +
        +
        +
        + + {!state.collapsed && props.children} + +
        + ); + } +} + +LogFileRow.propTypes = { + fileName: PropTypes.string, + typeName: PropTypes.string, + lastWriteTimeUtc: PropTypes.string, + size: PropTypes.string, + children: PropTypes.node, + onOpen: PropTypes.func, +}; + +export default connect()(LogFileRow); diff --git a/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/LogFileRow/style.less b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/LogFileRow/style.less new file mode 100644 index 00000000000..e506ffd0f8f --- /dev/null +++ b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/LogFileRow/style.less @@ -0,0 +1,48 @@ +@import "~@dnnsoftware/dnn-react-common/styles/index"; +.collapsible-logitemdetail { + display: table; + width: 100%; + &.false { + border-top: 2px solid @curiousBlue !important; + border-bottom: 2px solid @curiousBlue !important; + position: relative; + top: -1px; + } + &:not(:last-child) { + border-bottom: 1px solid #ddd; + } + .logitem-collapsible > div { + float: left; + padding-bottom: 25px; + } + div.collapsible-logitemdetail-header { + width: 100%; + float: left; + position: relative; + padding: 15px 0 15px 0; + box-sizing: border-box; + .term-header { + cursor: pointer; + .term-label-typename { + width: 20%; + float: left; + } + .term-label-filename { + width: 35%; + float: left; + } + .term-label-modifieddate { + width: 35%; + float: left; + } + .term-label-size { + width: 10%; + float: left; + } + .term-label-wrapper { + padding: 0 5px 0 5px; + word-wrap: break-word; + } + } + } +} diff --git a/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/Logs.jsx b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/Logs.jsx index e0d8f509a5c..7f7f505a558 100644 --- a/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/Logs.jsx +++ b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/Logs.jsx @@ -1,10 +1,9 @@ import React, { Component } from "react"; import PropTypes from "prop-types"; -import { Scrollbars } from "react-custom-scrollbars"; -import { GridCell, Dropdown } from "@dnnsoftware/dnn-react-common"; import Localization from "../../localization"; import { connect } from "react-redux"; import { bindActionCreators } from "redux"; +import LogFileRow from "./LogFileRow"; import LogsTabActions from "../../actions/logsTab"; import utils from "../../utils"; @@ -27,27 +26,49 @@ class Logs extends Component { render() { const { props } = this; - return
        - - {props.logs.length > 0 && - } - -
        -
        -
        } - style={{ height: 500 }} > -
        {props.logData}
        - + return ( +
        +
        +
        +
        +
        + {Localization.get("Logs_Type.Header")} +
        +
        + {Localization.get("Logs_Name.Header")} +
        +
        + {Localization.get("Logs_Date.Header")} +
        +
        + {Localization.get("Logs_Size.Header")} +
        +
        + {props.logs.map && + props.logs.map(l => ( + { + if (this.props.selectedLog !== l.name) { + this.props.onSelectedLog(l); + } + }} + > +
        {props.logData}
        +
        + ))} +
        +
        -
        ; + ); } } @@ -78,4 +99,4 @@ function mapDispatchToProps(dispatch) { }; } -export default connect(mapStateToProps, mapDispatchToProps)(Logs); \ No newline at end of file +export default connect(mapStateToProps, mapDispatchToProps)(Logs); diff --git a/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/tabs.less b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/tabs.less index 0b1ecd4edb3..d6e164993da 100644 --- a/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/tabs.less +++ b/Dnn.AdminExperience/ClientSide/Servers.Web/src/components/Tabs/tabs.less @@ -1,204 +1,222 @@ @import "~@dnnsoftware/dnn-react-common/styles/index"; .dnn-servers-tab-panel { - .dnn-servers-info-panel { - padding: 30px 80px 45px; - display: inline-block; - } - .dnn-servers-info-panel-big { - margin: 30px 30px 45px; - display: inline-block; - width: 93%; - .dnn-switch-container { - float: right; - } + .dnn-servers-info-panel { + padding: 30px 80px 45px; + display: inline-block; + } + .dnn-servers-info-panel-big { + margin: 30px 30px 45px; + display: inline-block; + width: 93%; + .dnn-switch-container { + float: right; } - .dnn-ui-common-input-group { - padding: 0 0 32px 0; - .title label { - font-weight: bolder; - float: left; - text-transform: uppercase; - } - .dnn-single-line-input-with-error { - display: block; - } + } + .dnn-ui-common-input-group { + padding: 0 0 32px 0; + .title label { + font-weight: bolder; + float: left; + text-transform: uppercase; } - .tooltipAdjustment { - float: left; - width: 100%; - div.tooltip-text { - max-width: 320px; - word-break: normal; - } + .dnn-single-line-input-with-error { + display: block; } - .log-file-cell { - padding: 7px 0; - .dnn-dropdown { - border-right: 1px solid @alto; - .collapsible-label { - padding: 3px 0; - } - .dropdown-icon { - top: 5px; - right: 17px; - } - } + } + .tooltipAdjustment { + float: left; + width: 100%; + div.tooltip-text { + max-width: 320px; + word-break: normal; } - .leftPane { - padding-right: 30px; - border-right: 1px solid @alto; - .dnn-radio-buttons { - ul { - li { - margin: 0 15px 0 0; - label { - word-break: break-word; - } - } - } - } + } + .log-file-cell { + padding: 7px 0; + .dnn-dropdown { + border-right: 1px solid @alto; + .collapsible-label { + padding: 3px 0; + } + .dropdown-icon { + top: 5px; + right: 17px; + } } - .rightPane { - padding-left: 20px; - padding-right: 10px; - .dnn-radio-buttons { - ul { - li:first-child { - margin-left: 0; - } - } - } + } + .leftPane { + padding-right: 30px; + border-right: 1px solid @alto; + .dnn-radio-buttons { + ul { + li { + margin: 0 15px 0 0; + label { + word-break: break-word; + } + } + } } - .border-bottom { - border-bottom: 1px solid @alto; - margin-bottom: 28px; + } + .rightPane { + padding-left: 20px; + padding-right: 10px; + .dnn-radio-buttons { + ul { + li:first-child { + margin-left: 0; + } + } } - .dnn-radio-buttons ul li { - padding-top: 10px; - div.check { - margin-top: 8px; - } - label { - padding: 0px 21px 0 28px; - margin-bottom: 0px; - } + } + .border-bottom { + border-bottom: 1px solid @alto; + margin-bottom: 28px; + } + .dnn-radio-buttons ul li { + padding-top: 10px; + div.check { + margin-top: 8px; } - .buttons-panel { - text-align: center; - margin-top: 55px; - .dnn-ui-common-button { - margin-right: 10px; - } + label { + padding: 0px 21px 0 28px; + margin-bottom: 0px; + } + } + .buttons-panel { + text-align: center; + margin-top: 55px; + .dnn-ui-common-button { + margin-right: 10px; } - .dnn-servers-grid-panel { - padding: 0 30px 55px; + } + .dnn-servers-grid-panel { + padding: 0 30px 55px; + width: 100%; + .header-title label { + font-weight: bolder; + text-transform: uppercase; + margin-bottom: 10px; + } + .grid { + display: block; + float: left; + width: 100%; + margin-top: 10px; + border-left: 1px solid @alto; + border-right: 1px solid @alto; + box-sizing: border-box; + .row { + display: table; width: 100%; - .header-title label { - font-weight: bolder; - text-transform: uppercase; - margin-bottom: 10px; - } - .grid { - display: block; - float: left; - width: 100%; - margin-top: 10px; - border-left: 1px solid @alto; - border-right: 1px solid @alto; - box-sizing: border-box; - .row { - display: table; - width: 100%; - position: relative; - padding: 15px 20px; - box-sizing: border-box; - border-bottom: 1px solid @alto; - .alert-message { - text-align: center; - color: red; - font-weight: bolder; - } - } - .header { - border-top: 1px solid @alto; - text-transform: uppercase; - .dnn-grid-cell { - font-weight: bolder; - } - } - } + position: relative; + padding: 15px 20px; + box-sizing: border-box; + border-bottom: 1px solid @alto; + .alert-message { + text-align: center; + color: red; + font-weight: bolder; + } + } + .header { + border-top: 1px solid @alto; + text-transform: uppercase; + .dnn-grid-cell { + font-weight: bolder; + } + } } + } } .dnn-servers-tab-panel .dnn-servers-info-panel-big { - &.logsTab { - .log-file-display { - height:500px; - padding-right: 50px; - white-space: pre-wrap; - } + &.logsTab { + .log-file-display { + white-space: pre-wrap; + } - .track-horizontal { - display:none; - } - .dnn-label { - width: auto; - margin-top: 8px; - } - .leftPane { - margin-bottom: 15px; - } - .dnn-ui-common-input-group { - padding: 0px; - } - .dnn-ui-common-multi-line-input { - height: 400px; - overflow-y:hidden; - } - .dnn-dropdown { - width: 70%; - } - .dnn-ui-common-input-group .title label { - text-transform: none; - } + .track-horizontal { + display: none; } - &.performanceSettingTab { - .title.lowerCase label { - text-transform: none; - } - .dnn-servers-grid-panel.newSection { - padding-top: 20px; - padding-bottom: 10px; - } - .borderSeparation { - > div { - border-bottom: 1px solid @alto; - margin-top: 10px; - padding-bottom: 10px; - } - :first-child { - margin-top: 0; - } - } - .dnn-ui-common-input-group .title label { - text-transform: none; - } - .currentHostVersion .dnn-label { - width: auto; - label { - text-transform: uppercase; - } - } + .dnn-label { + width: auto; + margin-top: 8px; } - &.smtpServerSettingsTab { - .dnn-ui-common-input-group { - padding-bottom: 0; - .dnn-radio-buttons{ - margin-bottom: 28px; - } - .title label { - text-transform: none; - } - } + .leftPane { + margin-bottom: 15px; } -} \ No newline at end of file + .dnn-ui-common-input-group { + padding: 0px; + } + .dnn-ui-common-multi-line-input { + height: 400px; + overflow-y: hidden; + } + .dnn-dropdown { + width: 70%; + } + .dnn-ui-common-input-group .title label { + text-transform: none; + } + + .logHeader-wrapper { + font-weight: bold; + .logHeader-type { + width: 20%; + float: left; + } + .logHeader-filename { + width: 35%; + float: left; + } + .logHeader-date { + width: 35%; + float: left; + } + .logHeader-size { + width: 10%; + float: left; + } + } + } + &.performanceSettingTab { + .title.lowerCase label { + text-transform: none; + } + .dnn-servers-grid-panel.newSection { + padding-top: 20px; + padding-bottom: 10px; + } + .borderSeparation { + > div { + border-bottom: 1px solid @alto; + margin-top: 10px; + padding-bottom: 10px; + } + :first-child { + margin-top: 0; + } + } + .dnn-ui-common-input-group .title label { + text-transform: none; + } + .currentHostVersion .dnn-label { + width: auto; + label { + text-transform: uppercase; + } + } + } + &.smtpServerSettingsTab { + .dnn-ui-common-input-group { + padding-bottom: 0; + .dnn-radio-buttons { + margin-bottom: 28px; + } + .title label { + text-transform: none; + } + } + } +} diff --git a/Dnn.AdminExperience/ClientSide/Servers.Web/src/services/logsTabService.js b/Dnn.AdminExperience/ClientSide/Servers.Web/src/services/logsTabService.js index 904525c2a94..f36d95d62d0 100644 --- a/Dnn.AdminExperience/ClientSide/Servers.Web/src/services/logsTabService.js +++ b/Dnn.AdminExperience/ClientSide/Servers.Web/src/services/logsTabService.js @@ -1,24 +1,33 @@ +import moment from "moment"; import serviceFramework from "./serviceFramework"; const getLogs = function () { - return serviceFramework.get("ServerSettingsLogs", "GetLogs") + return serviceFramework + .get("ServerSettingsLogs", "GetLogs") .then(response => { - const logList = response.Results.LogList.map((log) => { - return { - value: log, - label: log - }; - }); + const logList = response.Results.LogList.map( + ({ Name, LastWriteTimeUtc, Size }) => { + return { + name: Name, + lastWriteTimeUtc: LastWriteTimeUtc, + size: Size, + upgradeLog: false + }; + }); - const upgradeLogList = response.Results.UpgradeLogList.map((log) => { - return { - value: log, - label: log, - upgradeLog: true - }; - }); + const upgradeLogList = response.Results.UpgradeLogList.map( + ({ Name, LastWriteTimeUtc, Size }) => { + return { + name: Name, + lastWriteTimeUtc: LastWriteTimeUtc, + size: Size, + upgradeLog: true + }; + }); - return logList.concat(upgradeLogList); + return logList + .concat(upgradeLogList) + .sort((a, b) => moment(b.lastWriteTimeUtc) - moment(a.lastWriteTimeUtc)); }); }; diff --git a/Dnn.AdminExperience/ClientSide/SiteGroups.Web/package.json b/Dnn.AdminExperience/ClientSide/SiteGroups.Web/package.json index 024071791aa..cc2c958e567 100644 --- a/Dnn.AdminExperience/ClientSide/SiteGroups.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/SiteGroups.Web/package.json @@ -1,6 +1,6 @@ { "name": "dnn-sitegroups", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -15,7 +15,7 @@ "@babel/plugin-transform-object-assign": "7.0.0", "@babel/preset-env": "7.1.6", "@babel/preset-react": "7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-loader": "8.0.6", "babel-plugin-transform-react-remove-prop-types": "0.4.24", "babel-polyfill": "6.26.0", diff --git a/Dnn.AdminExperience/ClientSide/SiteImportExport.Web/package.json b/Dnn.AdminExperience/ClientSide/SiteImportExport.Web/package.json index 1bf745016c6..6cdebde5c95 100644 --- a/Dnn.AdminExperience/ClientSide/SiteImportExport.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/SiteImportExport.Web/package.json @@ -1,6 +1,6 @@ { "name": "site_import_export", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -15,7 +15,7 @@ "@babel/plugin-transform-react-jsx": "^7.2.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-eslint": "^10.0.1", "babel-loader": "8.0.6", "babel-plugin-transform-class-properties": "^6.22.0", diff --git a/Dnn.AdminExperience/ClientSide/SiteSettings.Web/package.json b/Dnn.AdminExperience/ClientSide/SiteSettings.Web/package.json index ac05476f2f2..1422f172a6e 100644 --- a/Dnn.AdminExperience/ClientSide/SiteSettings.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/SiteSettings.Web/package.json @@ -1,6 +1,6 @@ { "name": "site_settings", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -15,7 +15,7 @@ "@babel/plugin-transform-react-jsx": "^7.2.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "2.0.4", "array.prototype.findindex": "2.0.2", "babel-loader": "^8.0.6", diff --git a/Dnn.AdminExperience/ClientSide/SiteSettings.Web/src/components/basicSettings/index.jsx b/Dnn.AdminExperience/ClientSide/SiteSettings.Web/src/components/basicSettings/index.jsx index a76e3f6111f..f310fd52a8b 100644 --- a/Dnn.AdminExperience/ClientSide/SiteSettings.Web/src/components/basicSettings/index.jsx +++ b/Dnn.AdminExperience/ClientSide/SiteSettings.Web/src/components/basicSettings/index.jsx @@ -253,6 +253,7 @@ class BasicSettingsPanelBody extends Component { portalId={props.portalId} selectedFile={state.basicSettings.LogoFile} folderName={state.basicSettings.LogoFile ? state.basicSettings.LogoFile.FolderName : null} + validationCode={state.basicSettings.ValidationCode} onSelectFile={this.onSettingChange.bind(this, "LogoFile") } fileFormats={["image/png", "image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/jpeg", "image/svg+xml"]} browseButtonText={resx.get("BrowseButton")} @@ -289,6 +290,7 @@ class BasicSettingsPanelBody extends Component { portalId={props.portalId} selectedFile={state.basicSettings.FavIcon} folderName={state.basicSettings.FavIcon ? state.basicSettings.FavIcon.FolderName : null} + validationCode={state.basicSettings.ValidationCode} onSelectFile={this.onSettingChange.bind(this, "FavIcon") } fileFormats={["image/x-icon", "image/ico"]} browseButtonText={resx.get("BrowseButton")} diff --git a/Dnn.AdminExperience/ClientSide/Sites.Web/package.json b/Dnn.AdminExperience/ClientSide/Sites.Web/package.json index 6e1330d4e7b..469c754982d 100644 --- a/Dnn.AdminExperience/ClientSide/Sites.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Sites.Web/package.json @@ -1,6 +1,6 @@ { "name": "boilerplate", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -15,7 +15,7 @@ "@babel/plugin-transform-object-assign": "7.0.0", "@babel/preset-env": "7.1.6", "@babel/preset-react": "7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-loader": "8.0.6", "babel-plugin-transform-react-remove-prop-types": "0.4.24", "babel-polyfill": "6.26.0", diff --git a/Dnn.AdminExperience/ClientSide/Sites.Web/src/_exportables/package.json b/Dnn.AdminExperience/ClientSide/Sites.Web/src/_exportables/package.json index d1331005100..b924000ab37 100644 --- a/Dnn.AdminExperience/ClientSide/Sites.Web/src/_exportables/package.json +++ b/Dnn.AdminExperience/ClientSide/Sites.Web/src/_exportables/package.json @@ -1,6 +1,6 @@ { "name": "dnn-sites-list-view", - "version": "9.6.1", + "version": "9.6.2", "description": "DNN Sites List View", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", @@ -15,7 +15,7 @@ "@babel/plugin-transform-object-assign": "7.0.0", "@babel/preset-env": "7.1.6", "@babel/preset-react": "7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-loader": "8.0.4", "babel-plugin-transform-react-remove-prop-types": "0.4.20", "babel-polyfill": "6.26.0", diff --git a/Dnn.AdminExperience/ClientSide/TaskScheduler.Web/package.json b/Dnn.AdminExperience/ClientSide/TaskScheduler.Web/package.json index 2a5dbecf530..eeee29e56a3 100644 --- a/Dnn.AdminExperience/ClientSide/TaskScheduler.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/TaskScheduler.Web/package.json @@ -1,6 +1,6 @@ { "name": "task_scheduler", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -14,10 +14,9 @@ "@babel/plugin-proposal-object-rest-spread": "^7.2.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "2.0.4", "array.prototype.findindex": "2.0.2", - "babel-core": "6.26.3", "babel-loader": "8.0.6", "babel-plugin-transform-object-assign": "6.22.0", "babel-plugin-transform-object-rest-spread": "6.26.0", @@ -47,4 +46,4 @@ "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.14" } -} \ No newline at end of file +} diff --git a/Dnn.AdminExperience/ClientSide/Themes.Web/package.json b/Dnn.AdminExperience/ClientSide/Themes.Web/package.json index bd203a8e431..2399c424737 100644 --- a/Dnn.AdminExperience/ClientSide/Themes.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Themes.Web/package.json @@ -1,6 +1,6 @@ { "name": "themes", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -14,7 +14,7 @@ "@babel/plugin-proposal-object-rest-spread": "^7.2.0", "@babel/preset-env": "^7.2.0", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-loader": "8.0.6", "babel-plugin-transform-object-assign": "6.22.0", "babel-plugin-transform-object-rest-spread": "6.26.0", diff --git a/Dnn.AdminExperience/ClientSide/Users.Web/package.json b/Dnn.AdminExperience/ClientSide/Users.Web/package.json index 8f360ed0bef..9d1fd68eda8 100644 --- a/Dnn.AdminExperience/ClientSide/Users.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Users.Web/package.json @@ -1,6 +1,6 @@ { "name": "users", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "start": "npm run webpack", @@ -51,7 +51,7 @@ "webpack-dev-server": "^3.1.14" }, "dependencies": { - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "localization": "^1.0.2", "react-widgets": "^4.4.6" } diff --git a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json index f38bc147660..8e5160b5f21 100644 --- a/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json +++ b/Dnn.AdminExperience/ClientSide/Users.Web/src/_exportables/package.json @@ -1,6 +1,6 @@ { "name": "dnn-users-exportables", - "version": "9.6.1", + "version": "9.6.2", "description": "DNN Users Exportables", "scripts": { "start": "npm run webpack", @@ -16,7 +16,7 @@ "@babel/plugin-transform-react-jsx": "^7.1.6", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "babel-loader": "8.0.6", "create-react-class": "^15.6.3", "css-loader": "2.1.1", diff --git a/Dnn.AdminExperience/ClientSide/Vocabularies.Web/package.json b/Dnn.AdminExperience/ClientSide/Vocabularies.Web/package.json index 814d2043da6..2c84059e49c 100644 --- a/Dnn.AdminExperience/ClientSide/Vocabularies.Web/package.json +++ b/Dnn.AdminExperience/ClientSide/Vocabularies.Web/package.json @@ -1,6 +1,6 @@ { "name": "taxonomy", - "version": "9.6.1", + "version": "9.6.2", "private": true, "scripts": { "build": "set NODE_ENV=production&&webpack -p", @@ -14,10 +14,9 @@ "@babel/plugin-proposal-object-rest-spread": "^7.2.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", - "@dnnsoftware/dnn-react-common": "9.6.1", + "@dnnsoftware/dnn-react-common": "9.6.2", "array.prototype.find": "2.0.4", "array.prototype.findindex": "2.0.2", - "babel-core": "6.26.3", "babel-loader": "^8.0.6", "babel-plugin-transform-object-assign": "6.22.0", "babel-plugin-transform-object-rest-spread": "6.26.0", @@ -48,4 +47,4 @@ "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.14" } -} \ No newline at end of file +} diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs index dea66ce9c76..3a5d228f829 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Library; -using System.Net; -using System.Net.Http; -using Dnn.PersonaBar.Library.Prompt.Models; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Prompt.Common { + using System.Net; + using System.Net.Http; + + using Dnn.PersonaBar.Library; + using Dnn.PersonaBar.Library.Prompt.Models; + using DotNetNuke.Services.Localization; + public abstract class ControllerBase : PersonaBarApiController { protected HttpResponseMessage OkResponse(string msg, object data = null) { - return Request.CreateResponse(HttpStatusCode.OK, new ResponseModel(false, msg, data?.ToString() ?? "")); + return this.Request.CreateResponse(HttpStatusCode.OK, new ResponseModel(false, msg, data?.ToString() ?? "")); } protected HttpResponseMessage UnauthorizedResponse(string msg = "", object data = null) @@ -28,7 +29,7 @@ protected HttpResponseMessage UnauthorizedResponse(string msg = "", object data { msg += " " + Localization.GetString("Prompt_SessionTimedOut", Components.Constants.LocalResourcesFile, true); } - return Request.CreateResponse(HttpStatusCode.Unauthorized, new ResponseModel(true, msg, data?.ToString() ?? "")); + return this.Request.CreateResponse(HttpStatusCode.Unauthorized, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage BadRequestResponse(string msg = "", object data = null) @@ -37,7 +38,7 @@ protected HttpResponseMessage BadRequestResponse(string msg = "", object data = { msg = Localization.GetString("Prompt_InvalidData", Components.Constants.LocalResourcesFile, true); } - return Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseModel(true, msg, data?.ToString() ?? "")); + return this.Request.CreateResponse(HttpStatusCode.BadRequest, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage ServerErrorResponse(string msg = "", object data = null) @@ -46,7 +47,7 @@ protected HttpResponseMessage ServerErrorResponse(string msg = "", object data = { msg = Localization.GetString("Prompt_ServerError", Components.Constants.LocalResourcesFile, true); } - return Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseModel(true, msg, data?.ToString() ?? "")); + return this.Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseModel(true, msg, data?.ToString() ?? "")); } protected HttpResponseMessage NotImplementedResponse(string msg = "", object data = null) @@ -55,7 +56,7 @@ protected HttpResponseMessage NotImplementedResponse(string msg = "", object dat { msg = Localization.GetString("Prompt_NotImplemented", Components.Constants.LocalResourcesFile, true); } - return Request.CreateResponse(HttpStatusCode.NotImplemented, new ResponseModel(true, msg, data?.ToString() ?? "")); + return this.Request.CreateResponse(HttpStatusCode.NotImplemented, new ResponseModel(true, msg, data?.ToString() ?? "")); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/PortalHelper.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/PortalHelper.cs index 45146cfe633..9599b45e80d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/PortalHelper.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/PortalHelper.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Portals; -using System.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Prompt.Common { + using System.Linq; + + using DotNetNuke.Entities.Portals; + class PortalHelper { internal static bool IsRequestForSiteGroup(int portalId, int portalIdSiteGroup) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs index 9e9950fc8ef..ad69e97b122 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs @@ -1,54 +1,55 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Net.Mail; -using System.Net.Mime; -using System.Text; -using System.Web; -using System.Xml; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Log.EventLog; -using DotNetNuke.Services.Mail; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.AdminLogs.Components { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Net.Mail; + using System.Net.Mime; + using System.Text; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Mail; + public class AdminLogsController { private Dictionary _logTypeDictionary; private PortalSettings _portalSettings; - private PortalSettings PortalSettings + protected Dictionary LogTypeDictionary { get { - _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return _portalSettings; + this._logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); + return this._logTypeDictionary; } } - protected Dictionary LogTypeDictionary + private PortalSettings PortalSettings { get { - _logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); - return _logTypeDictionary; + this._portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this._portalSettings; } } public LogTypeInfo GetMyLogType(string logTypeKey) { LogTypeInfo logType; - LogTypeDictionary.TryGetValue(logTypeKey, out logType); + this.LogTypeDictionary.TryGetValue(logTypeKey, out logType); if (logType == null) { @@ -84,7 +85,7 @@ public string GetPropertiesText(object obj) { str.Append(objLogInfo.Exception); } - str.Append("

        " + Localization.GetString("ServerName",Constants.LocalResourcesFile) + + str.Append("

        " + Localization.GetString("ServerName", Constants.LocalResourcesFile) + HttpUtility.HtmlEncode(objLogInfo.LogServerName) + "

        "); } return str.ToString(); @@ -97,7 +98,7 @@ public void ClearLog() //add entry to log recording it was cleared EventLogController.Instance.AddLog(Localization.GetString("LogCleared", Constants.LocalResourcesFile), Localization.GetString("Username", Constants.LocalResourcesFile) + ":" + UserController.Instance.GetCurrentUserInfo().Username, - PortalSettings, + this.PortalSettings, -1, EventLogController.EventLogType.ADMIN_ALERT); } @@ -212,15 +213,15 @@ public string EmailLogItems(string subject, string fromEmailAddress, string toEm { if (string.IsNullOrEmpty(subject)) { - subject = PortalSettings.PortalName + @" Exceptions"; + subject = this.PortalSettings.PortalName + @" Exceptions"; } string returnMsg; if (Globals.EmailValidatorRegex.IsMatch(fromEmailAddress)) { const string tempFileName = "errorlog.xml"; - var filePath = PortalSettings.HomeDirectoryMapPath + tempFileName; - var xmlDoc = GetExceptions(logItemIds); + var filePath = this.PortalSettings.HomeDirectoryMapPath + tempFileName; + var xmlDoc = this.GetExceptions(logItemIds); xmlDoc.Save(filePath); var attachments = new List(); @@ -250,10 +251,8 @@ public string EmailLogItems(string subject, string fromEmailAddress, string toEm error = Localization.GetString("EmailFailure", Constants.LocalResourcesFile); } return returnMsg; - } - - #region Private Methods - + } + private XmlDocument GetExceptions(IEnumerable logIds) { var objXml = new XmlDocument { XmlResolver = null }; @@ -268,8 +267,6 @@ private XmlDocument GetExceptions(IEnumerable logIds) } } return objXml; - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/Constants.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/Constants.cs index 0be3fc40619..e7cc12dfa78 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/Constants.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/Constants.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.AdminLogs.Components { public static class Constants diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs index eeb2bd72e1b..e323d57abf6 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs @@ -1,21 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; -using Dnn.PersonaBar.Library.Repository; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + + using Dnn.PersonaBar.Library.Repository; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + public class BusinessController : IUpgradeable { public string UpgradeModule(string version) @@ -23,11 +24,11 @@ public string UpgradeModule(string version) switch (version) { case "01.04.00": - UpdateMenuController(); + this.UpdateMenuController(); break; case "01.05.00": - if (TelerikAssemblyExists()) + if (this.TelerikAssemblyExists()) { UpdateTelerikEncryptionKey("Telerik.Web.UI.DialogParametersEncryptionKey"); } @@ -37,16 +38,6 @@ public string UpgradeModule(string version) return String.Empty; } - private void UpdateMenuController() - { - PersonaBarRepository.Instance.UpdateMenuController(Dnn.PersonaBar.Vocabularies.Components.Constants.MenuIdentifier, string.Empty); - } - - private bool TelerikAssemblyExists() - { - return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); - } - private static string UpdateTelerikEncryptionKey(string keyName) { var strError = ""; @@ -80,5 +71,15 @@ private static string UpdateTelerikEncryptionKey(string keyName) } return strError; } + + private void UpdateMenuController() + { + PersonaBarRepository.Instance.UpdateMenuController(Dnn.PersonaBar.Vocabularies.Components.Constants.MenuIdentifier, string.Empty); + } + + private bool TelerikAssemblyExists() + { + return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs index 2aa31425d3c..bd16eae1bf3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs @@ -1,22 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; - -#endregion - -namespace Dnn.PersonaBar.ConfigConsole.Components -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.ConfigConsole.Components +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Xml; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + public class ConfigConsoleController { public IEnumerable GetConfigFilesList() @@ -28,7 +24,7 @@ public IEnumerable GetConfigFilesList() public string GetConfigFile(string configFile) { - ValidateFilePath(configFile); + this.ValidateFilePath(configFile); var configDoc = Config.Load(configFile); using (var txtWriter = new StringWriter()) @@ -44,7 +40,7 @@ public string GetConfigFile(string configFile) public void UpdateConfigFile(string fileName, string fileContent) { - ValidateFilePath(fileName); + this.ValidateFilePath(fileName); var configDoc = new XmlDocument { XmlResolver = null }; configDoc.LoadXml(fileContent); @@ -53,7 +49,7 @@ public void UpdateConfigFile(string fileName, string fileContent) public void MergeConfigFile(string fileContent) { - if (IsValidXmlMergDocument(fileContent)) + if (this.IsValidXmlMergDocument(fileContent)) { var doc = new XmlDocument { XmlResolver = null }; doc.LoadXml(fileContent); @@ -61,10 +57,8 @@ public void MergeConfigFile(string fileContent) var merge = new DotNetNuke.Services.Installer.XmlMerge(doc, Globals.FormatVersion(app.Version), app.Description); merge.UpdateConfigs(); } - } - - #region Private Functions - + } + private bool IsValidXmlMergDocument(string mergeDocText) { if (string.IsNullOrEmpty(mergeDocText.Trim())) @@ -83,8 +77,6 @@ private void ValidateFilePath(string filePath) { throw new ArgumentException("Invalid File Path"); } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Connectors/Constants.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Connectors/Constants.cs index b0765493fe4..26eb377ed83 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Connectors/Constants.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Connectors/Constants.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Connectors.Components { public static class Constants diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs index 271acc9466f..aed4fa6fa63 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components { public enum PackageTypes diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs index 6053883f9f5..7007874d948 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs @@ -1,40 +1,36 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using Microsoft.Extensions.DependencyInjection; -using Dnn.PersonaBar.Extensions.Components.Dto; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Security; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.Installer; -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components { + using System; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Security; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Installer; + using DotNetNuke.Services.Installer.Packages; + using Microsoft.Extensions.DependencyInjection; + public class CreateModuleController : ServiceLocator, ICreateModuleController { - protected INavigationManager NavigationManager { get; } public CreateModuleController() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - protected override Func GetFactory() - { - return () => new CreateModuleController(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } /// /// create new module. @@ -51,19 +47,30 @@ public int CreateModule(CreateModuleDto createModuleDto, out string newPageUrl, switch (createModuleDto.Type) { case CreateModuleType.New: - packageId = CreateNewModule(createModuleDto, out newPageUrl, out errorMessage); + packageId = this.CreateNewModule(createModuleDto, out newPageUrl, out errorMessage); break; case CreateModuleType.Control: - packageId = CreateModuleFromControl(createModuleDto, out newPageUrl, out errorMessage); + packageId = this.CreateModuleFromControl(createModuleDto, out newPageUrl, out errorMessage); break; case CreateModuleType.Manifest: - packageId = CreateModuleFromManifest(createModuleDto, out newPageUrl, out errorMessage); + packageId = this.CreateModuleFromManifest(createModuleDto, out newPageUrl, out errorMessage); break; } return packageId; } + protected override Func GetFactory() + { + return () => new CreateModuleController(); + } + + private static bool InvalidFilename(string fileName) + { + var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]"); + return invalidFilenameChars.IsMatch(fileName); + } + private int CreateNewModule(CreateModuleDto createModuleDto, out string newPageUrl, out string errorMessage) { newPageUrl = string.Empty; @@ -121,11 +128,11 @@ private int CreateNewModule(CreateModuleDto createModuleDto, out string newPageU } //First create the control createModuleDto.FileName = controlSrc; - var message = CreateControl(createModuleDto); + var message = this.CreateControl(createModuleDto); if (string.IsNullOrEmpty(message)) { //Next import the control - return CreateModuleFromControl(createModuleDto, out newPageUrl, out errorMessage); + return this.CreateModuleFromControl(createModuleDto, out newPageUrl, out errorMessage); } return Null.NullInteger; @@ -143,7 +150,7 @@ private int CreateModuleFromControl(CreateModuleDto createModuleDto, out string try { - var folder = PathUtils.Instance.RemoveTrailingSlash(GetSourceFolder(createModuleDto)); + var folder = PathUtils.Instance.RemoveTrailingSlash(this.GetSourceFolder(createModuleDto)); var friendlyName = createModuleDto.ModuleName; var name = createModuleDto.ModuleName; var moduleControl = "DesktopModules/" + folder + "/" + createModuleDto.FileName; @@ -220,7 +227,7 @@ private int CreateModuleFromControl(CreateModuleDto createModuleDto, out string if (createModuleDto.AddPage) { - newPageUrl = CreateNewPage(moduleDefinition); + newPageUrl = this.CreateNewPage(moduleDefinition); } return package.PackageID; @@ -245,7 +252,7 @@ private int CreateModuleFromManifest(CreateModuleDto createModuleDto, out string try { - var folder = PathUtils.Instance.RemoveTrailingSlash(GetSourceFolder(createModuleDto)); + var folder = PathUtils.Instance.RemoveTrailingSlash(this.GetSourceFolder(createModuleDto)); var manifest = Path.Combine(Globals.ApplicationMapPath, "DesktopModules", folder, createModuleDto.Manifest); var installer = new Installer(manifest, Globals.ApplicationMapPath, true); @@ -266,7 +273,7 @@ private int CreateModuleFromManifest(CreateModuleDto createModuleDto, out string { var moduleDefinition = kvp.Value; - newPageUrl = CreateNewPage(moduleDefinition); + newPageUrl = this.CreateNewPage(moduleDefinition); break; } } @@ -326,26 +333,20 @@ private string CreateNewPage(ModuleDefinitionInfo moduleDefinition) objModule.AllTabs = false; ModuleController.Instance.AddModule(objModule); - return NavigationManager.NavigateURL(newTab.TabID); + return this.NavigationManager.NavigateURL(newTab.TabID); } return string.Empty; } - private static bool InvalidFilename(string fileName) - { - var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]"); - return invalidFilenameChars.IsMatch(fileName); - } - private string CreateControl(CreateModuleDto createModuleDto) { - var folder = PathUtils.Instance.RemoveTrailingSlash(GetSourceFolder(createModuleDto)); - var className = GetClassName(createModuleDto); + var folder = PathUtils.Instance.RemoveTrailingSlash(this.GetSourceFolder(createModuleDto)); + var className = this.GetClassName(createModuleDto); var moduleControlPath = Path.Combine(Globals.ApplicationMapPath, "DesktopModules/" + folder + "/" + createModuleDto.FileName); var message = Null.NullString; - var source = string.Format(LoadControlTemplate(), createModuleDto.Language, className); + var source = string.Format(this.LoadControlTemplate(), createModuleDto.Language, className); //reset attributes if (File.Exists(moduleControlPath)) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs index 22de1e214d0..7d0ec1ac3e8 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components.Dto +{ + using System.Collections.Generic; + public class AvailablePackagesDto { public string PackageType { get; set; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs index 1c77b4de576..4caac598c25 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components.Dto +{ + using Newtonsoft.Json; + [JsonObject] public class CreateModuleDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs index f69fa9f7d7e..53c98992d36 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs @@ -1,17 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - - - -#endregion - + +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Dto { public class CreatePackageDto : PackageInfoDto - { - + { + } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs index 2e45e7ebff4..19fe460e9c8 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components.Dto +{ + using Newtonsoft.Json; + [JsonObject] public class DeletePackageDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DownloadPackageDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DownloadPackageDto.cs index 1eedd8f3b2a..ad31576b565 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DownloadPackageDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DownloadPackageDto.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Dto { + using Newtonsoft.Json; + [JsonObject] public class DownloadPackageDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs index 7ed48c61d61..8a7a4e6f835 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs @@ -1,15 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class AuthSystemPackageDetailDto : PackageInfoDto { + public AuthSystemPackageDetailDto() + { + } + + public AuthSystemPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("authenticationType")] public string AuthenticationType { get; set; } @@ -37,14 +44,5 @@ public class AuthSystemPackageDetailDto : PackageInfoDto [JsonProperty("appEnabled")] public bool AppEnabled { get; set; } - - public AuthSystemPackageDetailDto() - { - } - - public AuthSystemPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs index 039fdc4af32..4d31029f0fb 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs @@ -1,16 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using System.Collections.Generic; + + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class CoreLanguagePackageDetailDto : PackageInfoDto { + public CoreLanguagePackageDetailDto() + { + } + + public CoreLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("locales")] public IEnumerable Locales { get; set; } @@ -22,15 +30,5 @@ public class CoreLanguagePackageDetailDto : PackageInfoDto [JsonProperty("packages")] public IEnumerable Packages { get; set; } - - public CoreLanguagePackageDetailDto() - { - - } - - public CoreLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs index 94628100c23..dcfc7cc3893 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs @@ -1,27 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class ExtensionLanguagePackageDetailDto : CoreLanguagePackageDetailDto { - [JsonProperty("dependentPackageId")] - public int DependentPackageId { get; set; } - public ExtensionLanguagePackageDetailDto() { - } public ExtensionLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { - } + + [JsonProperty("dependentPackageId")] + public int DependentPackageId { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs index 26d6314bda7..bfe7365723e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs @@ -1,16 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using System.Collections.Generic; + + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class JsLibraryPackageDetailDto : PackageInfoDto { + public JsLibraryPackageDetailDto() + { + } + + public JsLibraryPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("objectName")] public string ObjectName { get; set; } @@ -31,15 +39,5 @@ public class JsLibraryPackageDetailDto : PackageInfoDto [JsonProperty("usedBy")] public IEnumerable UsedBy { get; set; } - - public JsLibraryPackageDetailDto() - { - - } - - public JsLibraryPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ListItemDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ListItemDto.cs index b34ee29e3ee..1b8451787cf 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ListItemDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ListItemDto.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using Newtonsoft.Json; + [JsonObject] public class ListItemDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs index 00f03eb43b8..cca1448276f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs @@ -1,20 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors -{ +{ + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + using Newtonsoft.Json; + [JsonObject] public class ModuleControlDto { + public ModuleControlDto() + { + } + + public ModuleControlDto(ModuleControlInfo moduleControl) + { + this.Id = moduleControl.ModuleControlID; + this.DefinitionId = moduleControl.ModuleDefID; + this.Key = moduleControl.ControlKey; + this.Title = moduleControl.ControlTitle; + this.Source = moduleControl.ControlSrc; + this.Type = moduleControl.ControlType; + this.Order = moduleControl.ViewOrder; + this.Icon = moduleControl.IconFile; + this.HelpUrl = moduleControl.HelpURL; + this.SupportPopups = moduleControl.SupportsPopUps; + this.SupportPartialRendering = moduleControl.SupportsPartialRendering; + } + [JsonProperty("id")] public int Id { get; set; } @@ -30,7 +44,6 @@ public class ModuleControlDto [JsonProperty("source")] public string Source { get; set; } - [JsonProperty("type")] public SecurityAccessLevel Type { get; set; } @@ -49,41 +62,21 @@ public class ModuleControlDto [JsonProperty("supportPartialRendering")] public bool SupportPartialRendering { get; set; } - public ModuleControlDto() - { - - } - - public ModuleControlDto(ModuleControlInfo moduleControl) - { - Id = moduleControl.ModuleControlID; - DefinitionId = moduleControl.ModuleDefID; - Key = moduleControl.ControlKey; - Title = moduleControl.ControlTitle; - Source = moduleControl.ControlSrc; - Type = moduleControl.ControlType; - Order = moduleControl.ViewOrder; - Icon = moduleControl.IconFile; - HelpUrl = moduleControl.HelpURL; - SupportPopups = moduleControl.SupportsPopUps; - SupportPartialRendering = moduleControl.SupportsPartialRendering; - } - public ModuleControlInfo ToModuleControlInfo() { return new ModuleControlInfo { - ModuleControlID = Id, - ModuleDefID = DefinitionId, - ControlKey = Key, - ControlTitle = Title, - ControlSrc = Source, - ControlType = Type, - ViewOrder = Order, - IconFile = Icon, - HelpURL = HelpUrl, - SupportsPartialRendering = SupportPartialRendering, - SupportsPopUps = SupportPopups + ModuleControlID = this.Id, + ModuleDefID = this.DefinitionId, + ControlKey = this.Key, + ControlTitle = this.Title, + ControlSrc = this.Source, + ControlType = this.Type, + ViewOrder = this.Order, + IconFile = this.Icon, + HelpURL = this.HelpUrl, + SupportsPartialRendering = this.SupportPartialRendering, + SupportsPopUps = this.SupportPopups }; } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs index 7783622932f..30ddda3372a 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs @@ -1,20 +1,34 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using DotNetNuke.Entities.Modules.Definitions; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors -{ +{ + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules.Definitions; + using Newtonsoft.Json; + [JsonObject] public class ModuleDefinitionDto { + public ModuleDefinitionDto() + { + } + + public ModuleDefinitionDto(ModuleDefinitionInfo definition) + { + this.Id = definition.ModuleDefID; + this.DesktopModuleId = definition.DesktopModuleID; + this.Name = definition.DefinitionName; + this.FriendlyName = definition.FriendlyName; + this.CacheTime = definition.DefaultCacheTime; + + foreach (var moduleControlInfo in definition.ModuleControls.Values) + { + this.Controls.Add(new ModuleControlDto(moduleControlInfo)); + } + } + [JsonProperty("id")] public int Id { get; set; } @@ -33,34 +47,15 @@ public class ModuleDefinitionDto [JsonProperty("controls")] public IList Controls { get; set; } = new List(); - public ModuleDefinitionDto() - { - - } - - public ModuleDefinitionDto(ModuleDefinitionInfo definition) - { - Id = definition.ModuleDefID; - DesktopModuleId = definition.DesktopModuleID; - Name = definition.DefinitionName; - FriendlyName = definition.FriendlyName; - CacheTime = definition.DefaultCacheTime; - - foreach (var moduleControlInfo in definition.ModuleControls.Values) - { - Controls.Add(new ModuleControlDto(moduleControlInfo)); - } - } - public ModuleDefinitionInfo ToModuleDefinitionInfo() { return new ModuleDefinitionInfo { - ModuleDefID = Id, - DesktopModuleID = DesktopModuleId, - DefinitionName = Name, - FriendlyName = FriendlyName, - DefaultCacheTime = CacheTime + ModuleDefID = this.Id, + DesktopModuleID = this.DesktopModuleId, + DefinitionName = this.Name, + FriendlyName = this.FriendlyName, + DefaultCacheTime = this.CacheTime }; } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs index dc605ae70b5..a396e2946e0 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs @@ -1,25 +1,63 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + + [JsonObject] + public class ModulePackageDetailDto : ModulePackagePermissionsDto + { + public ModulePackageDetailDto() + { + } + public ModulePackageDetailDto(int portalId, PackageInfo package, DesktopModuleInfo desktopModule) : base(portalId, package) + { + this.DesktopModuleId = desktopModule.DesktopModuleID; + this.ModuleName = desktopModule.ModuleName; + this.FolderName = desktopModule.FolderName; + this.BusinessController = desktopModule.BusinessControllerClass; + this.Category = desktopModule.Category; + this.Dependencies = desktopModule.Dependencies; + this.HostPermissions = desktopModule.Permissions; + this.Portable = desktopModule.IsPortable; + this.Searchable = desktopModule.IsSearchable; + this.Upgradeable = desktopModule.IsUpgradeable; + this.PremiumModule = desktopModule.IsPremium; + this.Shareable = desktopModule.Shareable; + if (!desktopModule.IsAdmin) + { + var portalDesktopModules = + DesktopModuleController.GetPortalDesktopModulesByDesktopModuleID(desktopModule.DesktopModuleID); + foreach (var portalDesktopModuleInfo in portalDesktopModules) + { + var value = portalDesktopModuleInfo.Value; + this.AssignedPortals.Add(new ListItemDto { Id = value.PortalID, Name = value.PortalName }); + } -#endregion + var assignedIds = this.AssignedPortals.Select(p => p.Id).ToArray(); + var allPortals = PortalController.Instance.GetPortals().OfType().Where(p => !assignedIds.Contains(p.PortalID)); -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; + foreach (var portalInfo in allPortals) + { + this.UnassignedPortals.Add(new ListItemDto { Id = portalInfo.PortalID, Name = portalInfo.PortalName }); + } + } + + foreach (var moduleDefinition in desktopModule.ModuleDefinitions.Values) + { + this.ModuleDefinitions.Add(new ModuleDefinitionDto(moduleDefinition)); + } + } -namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors -{ - [JsonObject] - public class ModulePackageDetailDto : ModulePackagePermissionsDto - { [JsonProperty("moduleName")] public string ModuleName { get; set; } @@ -60,51 +98,6 @@ public class ModulePackageDetailDto : ModulePackagePermissionsDto public IList UnassignedPortals { get; set; } = new List(); [JsonProperty("moduleDefinitions")] - public IList ModuleDefinitions { get; set; } = new List(); - - public ModulePackageDetailDto() - { - - } - - public ModulePackageDetailDto(int portalId, PackageInfo package, DesktopModuleInfo desktopModule) : base(portalId, package) - { - DesktopModuleId = desktopModule.DesktopModuleID; - ModuleName = desktopModule.ModuleName; - FolderName = desktopModule.FolderName; - BusinessController = desktopModule.BusinessControllerClass; - Category = desktopModule.Category; - Dependencies = desktopModule.Dependencies; - HostPermissions = desktopModule.Permissions; - Portable = desktopModule.IsPortable; - Searchable = desktopModule.IsSearchable; - Upgradeable = desktopModule.IsUpgradeable; - PremiumModule = desktopModule.IsPremium; - Shareable = desktopModule.Shareable; - - if (!desktopModule.IsAdmin) - { - var portalDesktopModules = - DesktopModuleController.GetPortalDesktopModulesByDesktopModuleID(desktopModule.DesktopModuleID); - foreach (var portalDesktopModuleInfo in portalDesktopModules) - { - var value = portalDesktopModuleInfo.Value; - AssignedPortals.Add(new ListItemDto { Id = value.PortalID, Name = value.PortalName }); - } - - var assignedIds = AssignedPortals.Select(p => p.Id).ToArray(); - var allPortals = PortalController.Instance.GetPortals().OfType().Where(p => !assignedIds.Contains(p.PortalID)); - - foreach (var portalInfo in allPortals) - { - UnassignedPortals.Add(new ListItemDto { Id = portalInfo.PortalID, Name = portalInfo.PortalName }); - } - } - - foreach (var moduleDefinition in desktopModule.ModuleDefinitions.Values) - { - ModuleDefinitions.Add(new ModuleDefinitionDto(moduleDefinition)); - } - } + public IList ModuleDefinitions { get; set; } = new List(); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs index 6669fb3d8f7..ce8ca37ed29 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs @@ -1,36 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - - - -#endregion - -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors -{ +{ + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class ModulePackagePermissionsDto : PackageInfoDto { - [JsonProperty("desktopModuleId")] - public int DesktopModuleId { get; set; } - - - [JsonProperty("permissions")] - public PermissionsDto Permissions { get; set; } - public ModulePackagePermissionsDto() - { - + { } public ModulePackagePermissionsDto(int portalId, PackageInfo package) : base(portalId, package) - { - + { } + + [JsonProperty("desktopModuleId")] + public int DesktopModuleId { get; set; } + + [JsonProperty("permissions")] + public PermissionsDto Permissions { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/PermissionsDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/PermissionsDto.cs index 588271a1911..dfa62df0187 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/PermissionsDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/PermissionsDto.cs @@ -1,15 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Library.DTO; -using Dnn.PersonaBar.Library.Helper; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Security.Permissions; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using Dnn.PersonaBar.Library.DTO; + using Dnn.PersonaBar.Library.Helper; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security.Permissions; + using Newtonsoft.Json; + [JsonObject] public class PermissionsDto : Permissions { @@ -28,7 +28,7 @@ protected override void LoadPermissionDefinitions() { foreach (PermissionInfo permission in PermissionController.GetPermissionsByPortalDesktopModule()) { - PermissionDefinitions.Add(new Permission() + this.PermissionDefinitions.Add(new Permission() { PermissionId = permission.PermissionID, PermissionName = permission.PermissionName, diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs index 552b4ff3db5..a908f5e8214 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs @@ -1,15 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class SkinObjectPackageDetailDto : PackageInfoDto { + public SkinObjectPackageDetailDto() + { + } + + public SkinObjectPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("controlKey")] public string ControlKey { get; set; } @@ -18,15 +25,5 @@ public class SkinObjectPackageDetailDto : PackageInfoDto [JsonProperty("supportsPartialRendering")] public bool SupportsPartialRendering { get; set; } - - public SkinObjectPackageDetailDto() - { - - } - - public SkinObjectPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs index 85189442b42..9c3154799e8 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs @@ -1,26 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class SkinPackageDetailDto : PackageInfoDto { - [JsonProperty("themePackageName")] - public string ThemePackageName { get; set; } - public SkinPackageDetailDto() { - } public SkinPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { - } + + [JsonProperty("themePackageName")] + public string ThemePackageName { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/UsedByPackage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/UsedByPackage.cs index a32cd61ff21..69333d2504c 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/UsedByPackage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/UsedByPackage.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors { + using Newtonsoft.Json; + [JsonObject] public class UsedByPackage { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs index 40b4c71e2c1..fa7507d9ff4 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs @@ -1,18 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Services.Installer.Log; -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components.Dto +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Services.Installer.Log; + using Newtonsoft.Json; + [JsonObject] public class InstallResultDto { @@ -30,19 +26,19 @@ public class InstallResultDto public void Failed(string message) { - Success = false; - Message = message; + this.Success = false; + this.Message = message; } public void Succeed() { - Success = true; - Message = string.Empty; + this.Success = true; + this.Message = string.Empty; } public void AddLogs(IEnumerable logs) { - Logs = logs?.Select( + this.Logs = logs?.Select( l => new InstallerLogEntry { Type = l.Type.ToString(), diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallerLogEntry.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallerLogEntry.cs index 5617d75fe7c..6beef9bf91d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallerLogEntry.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallerLogEntry.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Services.Installer.Log; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Dto { + using DotNetNuke.Services.Installer.Log; + using Newtonsoft.Json; + [JsonObject] public class InstallerLogEntry { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs index c2de860eb0e..79c46f05b3c 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs @@ -1,15 +1,10 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components.Dto +{ + using Newtonsoft.Json; + [JsonObject] public class ModuleFolderDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageFilesQueryDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageFilesQueryDto.cs index 270ae7d4d26..8aa46d253ed 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageFilesQueryDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageFilesQueryDto.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Dto { + using Newtonsoft.Json; + [JsonObject] public class PackageFilesQueryDto : PackageInfoDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs index 737a2af1c6e..0c3200b6eeb 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs @@ -1,29 +1,67 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Linq; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Components.Controllers.Models; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +{ + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Components.Controllers.Models; + using Microsoft.Extensions.DependencyInjection; + using Newtonsoft.Json; + [JsonObject] public class PackageInfoDto { + public PackageInfoDto() + { + } + + public PackageInfoDto(int portalId, PackageInfo package) + { + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + + this.PackageType = package.PackageType; + this.FriendlyName = package.FriendlyName; + this.Name = package.Name; + this.PackageId = package.PackageID; + this.Description = package.Description; + this.IsInUse = ExtensionsController.IsPackageInUse(package, portalId); + this.Version = package.Version.ToString(3); + this.UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); + this.UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); + this.PackageIcon = ExtensionsController.GetPackageIcon(package); + this.License = package.License; + this.ReleaseNotes = package.ReleaseNotes; + this.Owner = package.Owner; + this.Organization = package.Organization; + this.Url = package.Url; + this.Email = package.Email; + this.CanDelete = !package.IsSystemPackage && + package.PackageID > 0 && + PackageController.CanDeletePackage(package, PortalSettings.Current); + + var authService = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageId); + this.ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var tabId = portalSettings.ActiveTab.TabID; + this.SiteSettingsLink = this.NavigationManager.NavigateURL(tabId, "EditExtension", + new[] + { + $"packageid={this.PackageId}", + "Display=editor", + "popUp=true", + }); + } + [JsonProperty("packageId")] public int PackageId { get; set; } @@ -83,69 +121,26 @@ public class PackageInfoDto protected INavigationManager NavigationManager { get; } - public PackageInfoDto() - { - - } - - public PackageInfoDto(int portalId, PackageInfo package) - { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); - - PackageType = package.PackageType; - FriendlyName = package.FriendlyName; - Name = package.Name; - PackageId = package.PackageID; - Description = package.Description; - IsInUse = ExtensionsController.IsPackageInUse(package, portalId); - Version = package.Version.ToString(3); - UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); - UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); - PackageIcon = ExtensionsController.GetPackageIcon(package); - License = package.License; - ReleaseNotes = package.ReleaseNotes; - Owner = package.Owner; - Organization = package.Organization; - Url = package.Url; - Email = package.Email; - CanDelete = !package.IsSystemPackage && - package.PackageID > 0 && - PackageController.CanDeletePackage(package, PortalSettings.Current); - - var authService = AuthenticationController.GetAuthenticationServiceByPackageID(PackageId); - ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var tabId = portalSettings.ActiveTab.TabID; - SiteSettingsLink = NavigationManager.NavigateURL(tabId, "EditExtension", - new[] - { - $"packageid={PackageId}", - "Display=editor", - "popUp=true", - }); - } - public PackageInfo ToPackageInfo() { System.Version ver; - System.Version.TryParse(Version, out ver); + System.Version.TryParse(this.Version, out ver); return new PackageInfo { - PackageType = PackageType, - FriendlyName = FriendlyName, - Name = Name, - PackageID = PackageId, - Description = Description, + PackageType = this.PackageType, + FriendlyName = this.FriendlyName, + Name = this.Name, + PackageID = this.PackageId, + Description = this.Description, Version = ver, - License = License, - ReleaseNotes = ReleaseNotes, - Owner = Owner, - Organization = Organization, - Url = Url, - Email = Email, - IconFile = PackageIcon, + License = this.License, + ReleaseNotes = this.ReleaseNotes, + Owner = this.Owner, + Organization = this.Organization, + Url = this.Url, + Email = this.Email, + IconFile = this.PackageIcon, }; } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs index 654c57d71f4..dafde6aecd6 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs @@ -1,22 +1,43 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto { + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class PackageInfoSlimDto { + public PackageInfoSlimDto() + { + } + + public PackageInfoSlimDto(int portalId, PackageInfo package) + { + this.PackageId = package.PackageID; + this.FriendlyName = package.FriendlyName; + this.Name = package.Name; + this.FileName = package.FileName; + this.Description = package.Description; + this.Version = package.Version.ToString(3); + this.IsInUse = ExtensionsController.IsPackageInUse(package, portalId); + this.UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); + this.UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); + this.PackageIcon = ExtensionsController.GetPackageIcon(package); + this.Url = package.Url; + this.CanDelete = package.PackageID != Null.NullInteger && !package.IsSystemPackage && PackageController.CanDeletePackage(package, PortalSettings.Current); + + if (package.PackageID != Null.NullInteger) + { + var authService = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageId); + this.ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; + } + } + [JsonProperty("packageId")] public int PackageId { get; set; } @@ -47,36 +68,13 @@ public class PackageInfoSlimDto [JsonProperty("packageIcon")] public string PackageIcon { get; set; } + [JsonProperty("url")] + public string Url { get; set; } + [JsonProperty("canDelete")] public bool CanDelete { get; set; } [JsonProperty("readOnly")] public bool ReadOnly { get; set; } - - public PackageInfoSlimDto() - { - - } - - public PackageInfoSlimDto(int portalId, PackageInfo package) - { - PackageId = package.PackageID; - FriendlyName = package.FriendlyName; - Name = package.Name; - FileName = package.FileName; - Description = package.Description; - Version = package.Version.ToString(3); - IsInUse = ExtensionsController.IsPackageInUse(package, portalId); - UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); - UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); - PackageIcon = ExtensionsController.GetPackageIcon(package); - CanDelete = package.PackageID != Null.NullInteger && !package.IsSystemPackage && PackageController.CanDeletePackage(package, PortalSettings.Current); - - if (package.PackageID != Null.NullInteger) - { - var authService = AuthenticationController.GetAuthenticationServiceByPackageID(PackageId); - ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; - } - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs index 47084dbe153..e299ae884bd 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs @@ -1,16 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto { + using System.Collections.Generic; + + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class PackageManifestDto : PackageInfoDto { + public PackageManifestDto() + { + } + + public PackageManifestDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("archiveName")] public string ArchiveName { get; set; } @@ -21,22 +29,12 @@ public class PackageManifestDto : PackageInfoDto public string BasePath { get; set; } [JsonProperty("manifests")] - public IDictionary Manifests { get; set; } = new Dictionary(); + public IDictionary Manifests { get; set; } = new Dictionary(); [JsonProperty("assemblies")] public IList Assemblies { get; set; } = new List(); [JsonProperty("files")] public IList Files { get; set; } = new List(); - - public PackageManifestDto() - { - - } - - public PackageManifestDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs index 2b8e09af790..aaed1077c83 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs @@ -1,16 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components.Dto +{ + using System.Collections.Generic; + + using Newtonsoft.Json; + [JsonObject] public class PackageSettingsDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs index 19e3b366823..e3dc21a2531 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs @@ -1,25 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Collections; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using Newtonsoft.Json; - -#endregion - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Extensions.Components.Dto -{ +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Collections; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using Newtonsoft.Json; + [JsonObject] public class ParseResultDto : PackageInfoDto { + public ParseResultDto() + { + } + + public ParseResultDto(PackageInfo package) : base(Null.NullInteger, package) + { + } + [JsonProperty("success")] public bool Success { get; set; } = true; @@ -50,56 +54,46 @@ public class ParseResultDto : PackageInfoDto [JsonProperty("logs")] public IList Logs { get; set; } - public ParseResultDto() - { - - } - - public ParseResultDto(PackageInfo package) : base(Null.NullInteger, package) - { - - } - public void Failed(string message, IList logs = null) { - Success = false; - Message = Localization.GetString(message, Constants.SharedResources) ?? message; - AddLogs(logs); + this.Success = false; + this.Message = Localization.GetString(message, Constants.SharedResources) ?? message; + this.AddLogs(logs); // UI devs asked for these to be non-null empty for moving to next step - Description = Description ?? ""; - Email = Email ?? ""; - FriendlyName = FriendlyName ?? ""; - IsInUse = IsInUse ?? ""; - License = License ?? ""; - Name = Name ?? ""; - Organization = Organization ?? ""; - Owner = Owner ?? ""; - PackageIcon = PackageIcon ?? ""; - PackageType = PackageType ?? ""; - ReleaseNotes = ReleaseNotes ?? ""; - SiteSettingsLink = SiteSettingsLink ?? ""; - UpgradeIndicator = UpgradeIndicator ?? ""; - UpgradeUrl = UpgradeUrl ?? ""; - Url = Url ?? ""; - Version = Version ?? ""; - - LegacyError = LegacyError ?? ""; - Message = Message ?? ""; + this.Description = this.Description ?? ""; + this.Email = this.Email ?? ""; + this.FriendlyName = this.FriendlyName ?? ""; + this.IsInUse = this.IsInUse ?? ""; + this.License = this.License ?? ""; + this.Name = this.Name ?? ""; + this.Organization = this.Organization ?? ""; + this.Owner = this.Owner ?? ""; + this.PackageIcon = this.PackageIcon ?? ""; + this.PackageType = this.PackageType ?? ""; + this.ReleaseNotes = this.ReleaseNotes ?? ""; + this.SiteSettingsLink = this.SiteSettingsLink ?? ""; + this.UpgradeIndicator = this.UpgradeIndicator ?? ""; + this.UpgradeUrl = this.UpgradeUrl ?? ""; + this.Url = this.Url ?? ""; + this.Version = this.Version ?? ""; + + this.LegacyError = this.LegacyError ?? ""; + this.Message = this.Message ?? ""; } public void Succeed(IList logs) { - Success = true; - Message = string.Empty; - AddLogs(logs); + this.Success = true; + this.Message = string.Empty; + this.AddLogs(logs); } public void AddLogs(IEnumerable logs) { if (logs == null) - Logs = new List(); + this.Logs = new List(); else - Logs = logs.Select(l => new InstallerLogEntry { Type = l.Type.ToString(), Description = l.Description }).ToList(); + this.Logs = logs.Select(l => new InstallerLogEntry { Type = l.Type.ToString(), Description = l.Description }).ToList(); } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs index df0e2e020af..79901e44950 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs @@ -1,28 +1,28 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Microsoft.Extensions.DependencyInjection; -using Dnn.PersonaBar.Extensions.Components.Dto; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Authentication.OAuth; -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Authentication.OAuth; + using DotNetNuke.Services.Installer.Packages; + using Microsoft.Extensions.DependencyInjection; + public class AuthSystemPackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthSystemPackageEditor)); - private static readonly INavigationManager NavigationManager = Globals.DependencyProvider.GetRequiredService(); - #region IPackageEditor Implementation - + private static readonly INavigationManager NavigationManager = Globals.DependencyProvider.GetRequiredService(); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); @@ -93,12 +93,8 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion - - #region Private Methods - + } + private static string GetSettingUrl(int portalId, int authSystemPackageId) { return NavigationManager.NavigateURL(PortalSettings.Current.ActiveTab.TabID, PortalSettings.Current, "EditExtension", @@ -174,8 +170,6 @@ private static void SaveCustomSettings(PackageSettingsDto packageSettings) break; } } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs index 7256a5eedcd..f97f17ef188 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs @@ -1,29 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Microsoft.Extensions.DependencyInjection; -using Dnn.PersonaBar.Extensions.Components.Dto; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + public class CoreLanguagePackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); - protected INavigationManager NavigationManager { get; } public CoreLanguagePackageEditor() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { @@ -34,7 +35,7 @@ public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { Locales = Utility.GetAllLanguagesList(), LanguageId = languagePack.LanguageID, - EditUrlFormat = NavigationManager.NavigateURL(languagesTab, "", "Locale={0}") + EditUrlFormat = this.NavigationManager.NavigateURL(languagesTab, "", "Locale={0}") }; if (languagePack.PackageType == LanguagePackType.Extension) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs index 266f5b5d7d6..fabb3230d98 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs @@ -1,30 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.PersonaBar.Extensions.Components.Dto; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using Microsoft.Extensions.DependencyInjection; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using Microsoft.Extensions.DependencyInjection; + public class ExtensionLanguagePackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); - protected INavigationManager NavigationManager { get; } - public ExtensionLanguagePackageEditor() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + + protected INavigationManager NavigationManager { get; } public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { @@ -36,7 +37,7 @@ public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) Locales = Utility.GetAllLanguagesList(), LanguageId = languagePack.LanguageID, DependentPackageId = languagePack.DependentPackageID, - EditUrlFormat = NavigationManager.NavigateURL(languagesTab, "", "Locale={0}") + EditUrlFormat = this.NavigationManager.NavigateURL(languagesTab, "", "Locale={0}") }; if (languagePack.PackageType == LanguagePackType.Extension) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/IPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/IPackageEditor.cs index ca6b7a778c9..b99c5c8c12d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/IPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/IPackageEditor.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Extensions.Components.Dto; -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using Dnn.PersonaBar.Extensions.Components.Dto; + using DotNetNuke.Services.Installer.Packages; + public interface IPackageEditor { PackageInfoDto GetPackageDetail(int portalId, PackageInfo package); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs index 897244a28cb..8d0b62d7473 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs @@ -1,27 +1,26 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using Dnn.PersonaBar.Extensions.Components.Dto; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using DotNetNuke.Entities.Controllers; -using DotNetNuke.Framework.JavaScriptLibraries; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + using System.Linq; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Packages; + public class JsLibraryPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { - var usedBy = PackageController.Instance.GetPackageDependencies(d => + var usedBy = PackageController.Instance.GetPackageDependencies(d => d.PackageName.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && d.Version <= package.Version).Select(d => d.PackageId); @@ -73,8 +72,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs index bd750a48859..a88d43efdb3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs @@ -1,48 +1,47 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Linq; -using Dnn.PersonaBar.Extensions.Components.Dto; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using Dnn.PersonaBar.Library.Helper; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Modules.Definitions; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + using System.Collections.Generic; + using System.Linq; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using Dnn.PersonaBar.Library.Helper; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Definitions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + public class ModulePackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); - if(desktopModule == null) + if (desktopModule == null) { return new PackageInfoDto(portalId, package); - } - + } + var isHostUser = UserController.Instance.GetCurrentUserInfo().IsSuperUser; var detail = isHostUser ? new ModulePackageDetailDto(portalId, package, desktopModule) : new ModulePackagePermissionsDto(portalId, package); detail.DesktopModuleId = desktopModule.DesktopModuleID; - detail.Permissions = GetPermissionsData(portalId, desktopModule.DesktopModuleID); + detail.Permissions = this.GetPermissionsData(portalId, desktopModule.DesktopModuleID); return detail; } @@ -62,9 +61,9 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e var isHostUser = UserController.Instance.GetCurrentUserInfo().IsSuperUser; - UpdatePermissions(desktopModule, packageSettings); + this.UpdatePermissions(desktopModule, packageSettings); - if(isHostUser) + if (isHostUser) { foreach (var settingName in packageSettings.EditorActions.Keys) { @@ -91,7 +90,7 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e desktopModule.IsPremium = Convert.ToBoolean(settingValue); break; case "shareable": - desktopModule.Shareable = (ModuleSharing) Convert.ToInt32(settingValue); + desktopModule.Shareable = (ModuleSharing)Convert.ToInt32(settingValue); break; case "assignportal": AssignPortals(desktopModule, JsonConvert.DeserializeObject>(settingValue)); @@ -126,12 +125,16 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion - - #region Private Methods + } + private static void UnassignPortals(DesktopModuleInfo desktopModule, IList portals) + { + foreach (var portal in portals) + { + DesktopModuleController.RemoveDesktopModuleFromPortal(portal.Id, desktopModule.DesktopModuleID, true); + } + } + private PermissionsDto GetPermissionsData(int portalId, int desktopModuleId) { var permissions = new PermissionsDto(true); @@ -224,8 +227,7 @@ private void UpdatePermissions(DesktopModuleInfo desktopModule, PackageSettingsD } } } - - + //add user permissions if (permissions.UserPermissions != null) { @@ -260,17 +262,9 @@ private void UpdatePermissions(DesktopModuleInfo desktopModule, PackageSettingsD DataCache.RemoveCache(string.Format(DataCache.PortalDesktopModuleCacheKey, portalSettings.PortalId)); } - private static void UnassignPortals(DesktopModuleInfo desktopModule, IList portals) - { - foreach (var portal in portals) - { - DesktopModuleController.RemoveDesktopModuleFromPortal(portal.Id, desktopModule.DesktopModuleID, true); - } - } - private static void AssignPortals(DesktopModuleInfo desktopModule, IList portals) { - foreach(var portal in portals) + foreach (var portal in portals) { DesktopModuleController.AddDesktopModuleToPortal(portal.Id, desktopModule.DesktopModuleID, true, true); } @@ -296,10 +290,6 @@ private static void SaveModuleControl(ModuleControlDto moduleControlDto) private static void DeleteModuleControl(int controlId) { ModuleControlController.DeleteModuleControl(controlId); - } - - - #endregion - + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/PackageEditorFactory.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/PackageEditorFactory.cs index a190706b78f..05213f9d592 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/PackageEditorFactory.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/PackageEditorFactory.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + public sealed class PackageEditorFactory { public static IPackageEditor GetPackageEditor(string packageType) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs index ff6ce723cd6..96441b935ac 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs @@ -1,23 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.PersonaBar.Extensions.Components.Dto; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Packages; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Packages; + public class SkinObjectPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinObjectPackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinObjectPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var skinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); @@ -27,8 +26,8 @@ public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) detail.ControlKey = skinControl.ControlKey; detail.ControlSrc = skinControl.ControlSrc; detail.SupportsPartialRendering = skinControl.SupportsPartialRendering; - detail.ReadOnly |= !isHostUser; - + detail.ReadOnly |= !isHostUser; + return detail; } @@ -68,8 +67,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs index a835a0bf25d..e495362bcb3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs @@ -1,23 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using Dnn.PersonaBar.Extensions.Components.Dto; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using DotNetNuke.Entities.Users; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.UI.Skins; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components.Editors { + using System; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using DotNetNuke.Entities.Users; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.UI.Skins; + public class SkinPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinPackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var isHostUser = UserController.Instance.GetCurrentUserInfo().IsSuperUser; @@ -60,8 +59,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs index f21082f2d67..c51115e76dc 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs @@ -1,42 +1,38 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; -using Dnn.PersonaBar.Extensions.Components.Dto; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Upgrade; -using DotNetNuke.Services.Upgrade.Internals; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components -{ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.PersonaBar.Extensions.Components +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + using System.Xml; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Upgrade; + using DotNetNuke.Services.Upgrade.Internals; + using Microsoft.Extensions.DependencyInjection; + public class ExtensionsController { private const string OwnerUpdateService = "DotNetNuke Update Service"; - protected INavigationManager NavigationManager { get; } public ExtensionsController() { - NavigationManager = Globals.DependencyProvider.GetRequiredService(); + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } public IDictionary GetPackageTypes() { @@ -124,7 +120,7 @@ public List GetAvailablePackages(string packageType) { var packages = new List(); string packagePath; - if (HasAvailablePackage(packageType, out packagePath)) + if (this.HasAvailablePackage(packageType, out packagePath)) { var validpackages = new Dictionary(); var invalidPackages = new List(); @@ -139,7 +135,7 @@ public List GetAvailablePackages(string packageType) if (packageType.ToLowerInvariant() == "corelanguagepack") { - GetAvaialableLanguagePacks(validpackages); + this.GetAvaialableLanguagePacks(validpackages); } packages.Add(new AvailablePackagesDto() @@ -152,6 +148,16 @@ public List GetAvailablePackages(string packageType) return packages; } + public List GetPackageUsage(int portalId, int packageId) + { + IDictionary tabs = BuildData(portalId, packageId); + if (tabs != null && tabs.Count > 0) + { + return tabs.Values.ToList(); + } + return null; + } + private void GetAvaialableLanguagePacks(IDictionary validPackages) { try @@ -226,16 +232,6 @@ private void GetAvaialableLanguagePacks(IDictionary validPa } } - public List GetPackageUsage(int portalId, int packageId) - { - IDictionary tabs = BuildData(portalId, packageId); - if (tabs != null && tabs.Count > 0) - { - return tabs.Values.ToList(); - } - return null; - } - public string GetFormattedTabLink(int portalId, TabInfo tab) { var returnValue = new StringBuilder(); @@ -260,26 +256,14 @@ public string GetFormattedTabLink(int portalId, TabInfo tab) : PortalAliasController.Instance.GetPortalAliasesByPortalId(t.PortalID) .OrderBy(pa => pa.IsPrimary ? 0 : 1) .First(); - var url = NavigationManager.NavigateURL(t.TabID, new PortalSettings(t.PortalID, alias), string.Empty); + var url = this.NavigationManager.NavigateURL(t.TabID, new PortalSettings(t.PortalID, alias), string.Empty); returnValue.AppendFormat("{1}", url, t.LocalizedTabName); } index = index + 1; } return returnValue.ToString(); - } - - #region Private Functions - - private static void AddModulesToList(int portalId, List packages) - { - Dictionary portalModules = DesktopModuleController.GetPortalDesktopModulesByPortalID(portalId); - packages.AddRange(from modulePackage in PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "Module") - let desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(modulePackage.PackageID) - from portalModule in portalModules.Values - where desktopModule != null && portalModule.DesktopModuleID == desktopModule.DesktopModuleID - select modulePackage); - } + } internal static string IsPackageInUse(PackageInfo packageInfo, int portalId) { @@ -301,6 +285,16 @@ internal static string IsPackageInUse(PackageInfo packageInfo, int portalId) } return string.Empty; } + + private static void AddModulesToList(int portalId, List packages) + { + Dictionary portalModules = DesktopModuleController.GetPortalDesktopModulesByPortalID(portalId); + packages.AddRange(from modulePackage in PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "Module") + let desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(modulePackage.PackageID) + from portalModule in portalModules.Values + where desktopModule != null && portalModule.DesktopModuleID == desktopModule.DesktopModuleID + select modulePackage); + } internal static string UpgradeRedirect(Version version, string packageType, string packageName) { @@ -333,7 +327,7 @@ internal static string GetPackageIcon(PackageInfo package) return IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultAuthenicationImage; case "corelanguagepack": case "extensionlanguagepack": - return package.IconFile != "N\\A" && IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultLanguageImage; + return package.IconFile != "N\\A" && IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultLanguageImage; case "provider": return IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultProviderImage; case "widget": @@ -347,6 +341,11 @@ internal static string GetPackageIcon(PackageInfo package) } } + internal static IDictionary GetPackagesInUse(bool forHost) + { + return PackageController.GetModulePackagesInUse(PortalController.Instance.GetCurrentPortalSettings().PortalId, forHost); + } + private static string FixIconUrl(string url) { return !string.IsNullOrEmpty(Globals.ApplicationPath) @@ -354,11 +353,6 @@ private static string FixIconUrl(string url) : url; } - internal static IDictionary GetPackagesInUse(bool forHost) - { - return PackageController.GetModulePackagesInUse(PortalController.Instance.GetCurrentPortalSettings().PortalId, forHost); - } - private static IDictionary BuildData(int portalId, int packageId) { IDictionary tabsWithModule = TabController.Instance.GetTabsByPackageID(portalId, packageId, false); @@ -404,8 +398,6 @@ private static bool IconExists(string imagePath) return false; } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ICreateModuleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ICreateModuleController.cs index 060f5c9f64d..3b8e91411b9 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ICreateModuleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ICreateModuleController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Extensions.Components.Dto; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components { + using Dnn.PersonaBar.Extensions.Components.Dto; + public interface ICreateModuleController { int CreateModule(CreateModuleDto createModuleDto, out string newPageUrl, out string errorMessage); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/IInstallController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/IInstallController.cs index 3c15b514df1..e004ab141a0 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/IInstallController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/IInstallController.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; -using Dnn.PersonaBar.Extensions.Components.Dto; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components { + using System.IO; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + public interface IInstallController { InstallResultDto InstallPackage(PortalSettings portalSettings, UserInfo user, string legacySkin, string fileName, diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs index 2336bcfa8db..1431b4dbbc5 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs @@ -1,35 +1,31 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Data; -using System.IO; -using System.Linq; -using System.Xml; -using Dnn.PersonaBar.Extensions.Components.Dto; -using DotNetNuke.Common; -using DotNetNuke.Data; -using DotNetNuke.Data.PetaPoco; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Installer; -using DotNetNuke.Common.Utilities; -using ICSharpCode.SharpZipLib; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components { + using System; + using System.Data; + using System.IO; + using System.Linq; + using System.Xml; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Data.PetaPoco; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Installer; + using ICSharpCode.SharpZipLib; + public class InstallController : ServiceLocator, IInstallController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InstallController)); - protected override Func GetFactory() - { - return () => new InstallController(); - } - public ParseResultDto ParsePackage(PortalSettings portalSettings, UserInfo user, string filePath, Stream stream) { var parseResult = new ParseResultDto(); @@ -93,6 +89,11 @@ public ParseResultDto ParsePackage(PortalSettings portalSettings, UserInfo user, return parseResult; } + protected override Func GetFactory() + { + return () => new InstallController(); + } + public InstallResultDto InstallPackage(PortalSettings portalSettings, UserInfo user, string legacySkin, string filePath, Stream stream, bool isPortalPackage = false) { var installResult = new InstallResultDto(); @@ -170,7 +171,7 @@ private static Installer GetInstaller(Stream stream, string fileName, int portal // We always assume we are installing from //Host/Extensions (in the previous releases) // This will not work when we try to install a skin/container under a specific portal. - installer.InstallerInfo.PortalID = isPortalPackage ? portalId: Null.NullInteger; + installer.InstallerInfo.PortalID = isPortalPackage ? portalId : Null.NullInteger; //Read the manifest if (installer.InstallerInfo.ManifestFile != null) @@ -225,9 +226,9 @@ private static void DeleteInstallFile(string installerFile) try { if (File.Exists(installerFile)) - { - File.SetAttributes(installerFile, FileAttributes.Normal); - File.Delete(installerFile); + { + File.SetAttributes(installerFile, FileAttributes.Normal); + File.Delete(installerFile); } } catch (Exception ex) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs index 7b34bf11517..612ce37ed8a 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs @@ -1,23 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using Dnn.PersonaBar.Extensions.Components.Dto.Editors; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Extensions.Components { + using System.Collections.Generic; + using System.Linq; + + using Dnn.PersonaBar.Extensions.Components.Dto.Editors; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + public static class Utility { public static IEnumerable GetAllLanguagesList() { var locales = LocaleController.Instance.GetLocales(Null.NullInteger).Values; - return locales.Select(l => new ListItemDto {Id = l.LanguageId, Name = l.EnglishName}); + return locales.Select(l => new ListItemDto { Id = l.LanguageId, Name = l.EnglishName }); } public static IEnumerable GetAllPackagesListExceptLangPacks() diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs index 55b83ab3f91..d18a9995b8d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs @@ -1,31 +1,33 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Text.RegularExpressions; -using System.Xml; -using Dnn.PersonaBar.Pages.Components.Exceptions; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.UI; -using TermHelper = DotNetNuke.Entities.Content.Taxonomy.TermHelper; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Text.RegularExpressions; + using System.Xml; + + using Dnn.PersonaBar.Pages.Components.Exceptions; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.UI; + + using TermHelper = DotNetNuke.Entities.Content.Taxonomy.TermHelper; + public class BulkPagesController : ServiceLocator, IBulkPagesController { - private static readonly Regex TabNameRegex = new Regex(">*(.*)", RegexOptions.Compiled); private const string DefaultPageTemplate = "Default.page.template"; + private static readonly Regex TabNameRegex = new Regex(">*(.*)", RegexOptions.Compiled); public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) { @@ -54,14 +56,14 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) foreach (var strLine in pages) { - var tab = new TabInfo - { - TabName = TabNameRegex.Replace(strLine, "${1}"), - Level = strLine.LastIndexOf(">", StringComparison.Ordinal) + 1, - KeyWords = page.Keywords, - StartDate = page.StartDate ?? Null.NullDate, - EndDate = page.EndDate ?? Null.NullDate, - IsVisible = page.IncludeInMenu + var tab = new TabInfo + { + TabName = TabNameRegex.Replace(strLine, "${1}"), + Level = strLine.LastIndexOf(">", StringComparison.Ordinal) + 1, + KeyWords = page.Keywords, + StartDate = page.StartDate ?? Null.NullDate, + EndDate = page.EndDate ?? Null.NullDate, + IsVisible = page.IncludeInMenu }; tab.Terms.AddRange(TermHelper.ToTabTerms(page.Tags, portalId)); tabs.Add(tab); @@ -78,7 +80,7 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) string errorMessage = null; if (oTab.Level == 0) { - oTab.TabID = CreateTabFromParent(portalSettings, rootTab, oTab, parentId, validateOnly, out errorMessage); + oTab.TabID = this.CreateTabFromParent(portalSettings, rootTab, oTab, parentId, validateOnly, out errorMessage); } else if (validateOnly) { @@ -89,7 +91,7 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) var parentTabId = GetParentTabId(tabs, currentIndex, oTab.Level - 1); if (parentTabId != Null.NullInteger) { - oTab.TabID = CreateTabFromParent(portalSettings, rootTab, oTab, parentTabId, validateOnly, out errorMessage); + oTab.TabID = this.CreateTabFromParent(portalSettings, rootTab, oTab, parentTabId, validateOnly, out errorMessage); } } bulkPageItems.Add(ToBulkPageResponseItem(oTab, errorMessage)); @@ -104,6 +106,11 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) return response; } + protected override Func GetFactory() + { + return () => new BulkPagesController(); + } + private static BulkPageResponseItem ToBulkPageResponseItem(TabInfo tab, string error) { return new BulkPageResponseItem @@ -115,6 +122,25 @@ private static BulkPageResponseItem ToBulkPageResponseItem(TabInfo tab, string e }; } + private static int GetParentTabId(List lstTabs, int currentIndex, int parentLevel) + { + var oParent = lstTabs[0]; + + for (var i = 0; i < lstTabs.Count; i++) + { + if (i == currentIndex) + { + return oParent.TabID; + } + if (lstTabs[i].Level == parentLevel) + { + oParent = lstTabs[i]; + } + } + + return Null.NullInteger; + } + private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, TabInfo oTab, int parentId, bool validateOnly, out string errorMessage) { var tab = new TabInfo @@ -179,7 +205,7 @@ private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, } //Validate Tab Path - if (!IsValidTabPath(tab, tab.TabPath, out errorMessage)) + if (!this.IsValidTabPath(tab, tab.TabPath, out errorMessage)) { return Null.NullInteger; } @@ -227,7 +253,7 @@ private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, return -1; tab.TabID = TabController.Instance.AddTab(tab); - ApplyDefaultTabTemplate(tab); + this.ApplyDefaultTabTemplate(tab); //create localized tabs if content localization is enabled if (portalSettings.ContentLocalizationEnabled) @@ -238,25 +264,6 @@ private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, return tab.TabID; } - private static int GetParentTabId(List lstTabs, int currentIndex, int parentLevel) - { - var oParent = lstTabs[0]; - - for (var i = 0; i < lstTabs.Count; i++) - { - if (i == currentIndex) - { - return oParent.TabID; - } - if (lstTabs[i].Level == parentLevel) - { - oParent = lstTabs[i]; - } - } - - return Null.NullInteger; - } - private void ApplyDefaultTabTemplate(TabInfo tab) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -314,10 +321,5 @@ private bool IsValidTabPath(TabInfo tab, string newTabPath, out string errorMess return valid; } - - protected override Func GetFactory() - { - return () => new BulkPagesController(); - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs index 3388a815fa8..fde30aeeeee 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs @@ -1,26 +1,27 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Threading; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + using System.Threading; + + using DotNetNuke.Framework; + public class CloneModuleExecutionContext : ServiceLocator, ICloneModuleExecutionContext { private const string CloneModuleSlotName = "CloneModuleContext"; - protected override Func GetFactory() - { - return () => new CloneModuleExecutionContext(); - } - public void SetCloneModuleContext(bool cloneModule) { var slot = Thread.GetNamedDataSlot(CloneModuleSlotName); Thread.SetData(slot, cloneModule ? bool.TrueString : bool.FalseString); } + + protected override Func GetFactory() + { + return () => new CloneModuleExecutionContext(); + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs index da415a11100..3056596d308 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { public class Constants { - internal const string LocalResourceFile = Library.Constants.PersonaBarRelativePath + "Modules/Dnn.Pages/App_LocalResources/Pages.resx"; public const string PagesCategory = "Prompt_PagesCategory"; + internal const string LocalResourceFile = Library.Constants.PersonaBarRelativePath + "Modules/Dnn.Pages/App_LocalResources/Pages.resx"; } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs index 1567acf4745..a12b3e1108f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs @@ -1,29 +1,30 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Data; -using System.Globalization; -using System.Linq; -using Microsoft.Extensions.DependencyInjection; -using Dnn.PersonaBar.Pages.Components.Security; -using Dnn.PersonaBar.Pages.Services.Dto; -using Dnn.PersonaBar.Themes.Components; -using Dnn.PersonaBar.Themes.Components.DTO; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Security; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + + using Dnn.PersonaBar.Pages.Components.Security; + using Dnn.PersonaBar.Pages.Services.Dto; + using Dnn.PersonaBar.Themes.Components; + using Dnn.PersonaBar.Themes.Components.DTO; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem; + using Microsoft.Extensions.DependencyInjection; + public static class Converters { private static readonly INavigationManager _navigationManager = Globals.DependencyProvider.GetRequiredService(); @@ -69,29 +70,6 @@ public static class Converters AllTabs = module.AllTabs }; - private static string GetModuleEditSettingUrl(ModuleInfo module) - { - var parameters = new List { "ModuleId=" + module.ModuleID, "popUp=true" }; - return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, "Module", parameters.ToArray()); - } - - private static string GetModuleEditContentUrl(ModuleInfo module) - { - var moduleControl = ModuleControlController.GetModuleControlByControlKey("Edit", module.ModuleDefID); - if(moduleControl != null && moduleControl.ControlType == SecurityAccessLevel.Edit && !string.IsNullOrEmpty(moduleControl.ControlTitle)) - { - var parameters = new List{ "mid=" + module.ModuleID }; - if (moduleControl.SupportsPopUps) - { - parameters.Add("popUp=true"); - } - - return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, moduleControl.ControlKey, parameters.ToArray()); - } - - return string.Empty; - } - public static T ConvertToPageSettings(TabInfo tab) where T : PageSettings, new() { if (tab == null) @@ -162,6 +140,29 @@ private static string GetModuleEditContentUrl(ModuleInfo module) }; } + private static string GetModuleEditSettingUrl(ModuleInfo module) + { + var parameters = new List { "ModuleId=" + module.ModuleID, "popUp=true" }; + return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, "Module", parameters.ToArray()); + } + + private static string GetModuleEditContentUrl(ModuleInfo module) + { + var moduleControl = ModuleControlController.GetModuleControlByControlKey("Edit", module.ModuleDefID); + if (moduleControl != null && moduleControl.ControlType == SecurityAccessLevel.Edit && !string.IsNullOrEmpty(moduleControl.ControlTitle)) + { + var parameters = new List { "mid=" + module.ModuleID }; + if (moduleControl.SupportsPopUps) + { + parameters.Add("popUp=true"); + } + + return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, moduleControl.ControlKey, parameters.ToArray()); + } + + return string.Empty; + } + private static ThemeFileInfo GetThemeFileFromSkinSrc(string skinSrc) { if (string.IsNullOrWhiteSpace(skinSrc)) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/DefaultPortalThemeController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/DefaultPortalThemeController.cs index a4d11eb0da2..5b01551677d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/DefaultPortalThemeController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/DefaultPortalThemeController.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Entities.Host; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + public class DefaultPortalThemeController : ServiceLocator, IDefaultPortalThemeController { public string GetDefaultPortalContainer() diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/PageUrlResult.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/PageUrlResult.cs index cea865be7bd..24957583152 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/PageUrlResult.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/PageUrlResult.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Dto { public class PageUrlResult diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/Template.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/Template.cs index d0149c565d9..0bad254bf54 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/Template.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/Template.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Dto { public class Template diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/UrlIdDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/UrlIdDto.cs index 0c2deffd9af..a49dbdff5f1 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/UrlIdDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Dto/UrlIdDto.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Dto { public class UrlIdDto diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs index 33650f12bd3..8b8092f0fce 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Exceptions { + using System; + public class BulkPagesException : Exception { - public string Field { get; set; } - public BulkPagesException(string field, string message) : base(message) { - Field = field; + this.Field = field; } + + public string Field { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs index 963554a2641..670aef2ec0e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Exceptions { + using System; + public class PageException : Exception { - public PageException(string message): base(message) + public PageException(string message) : base(message) { } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageModuleNotFoundException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageModuleNotFoundException.cs index 1a760970cc6..02c8d081b82 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageModuleNotFoundException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageModuleNotFoundException.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Exceptions { + using System; + public class PageModuleNotFoundException : Exception { } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs index 1f3781f7358..747fc2a21bb 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Exceptions { + using System; + public class PageNotFoundException : Exception { } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs index 055588bdb7e..1a99c6cef95 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs @@ -1,18 +1,18 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Exceptions { + using System; + public class PageValidationException : Exception { - public string Field { get; set; } - public PageValidationException(string field, string message) : base(message) { - Field = field; + this.Field = field; } + + public string Field { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs index 95ad0bac91a..0116910b5db 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Exceptions { + using System; + public class TemplateException : Exception { - public TemplateException(string message): base(message) + public TemplateException(string message) : base(message) { } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs index 5017b1ca4a1..c1e210691f7 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs @@ -1,19 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Urls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Urls; + public class FriendlyUrlWrapper : IFriendlyUrlWrapper { public string CleanNameForUrl(string urlPath, FriendlyUrlOptions options, out bool modified) { return FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); - } - + } + public void ValidateUrl(string urlPath, int tabld, PortalSettings portalSettings, out bool modified) { FriendlyUrlController.ValidateUrl(urlPath, tabld, portalSettings, out modified); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IBulkPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IBulkPagesController.cs index 1515b59d79e..52fb985c34d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IBulkPagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IBulkPagesController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Pages.Services.Dto; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using Dnn.PersonaBar.Pages.Services.Dto; + public interface IBulkPagesController { BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs index d6d58e945d3..7054e6cf1c3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs @@ -1,12 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { /// - /// Provides an abstraction over the current context of the Clone Module thread + /// Provides an abstraction over the current context of the Clone Module thread. /// public interface ICloneModuleExecutionContext { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs index 6aab2517ebc..639dea864d2 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs @@ -1,22 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { /// - /// Theme controller + /// Theme controller. /// public interface IDefaultPortalThemeController { /// - /// Returns the default current portal container + /// Returns the default current portal container. /// /// string GetDefaultPortalContainer(); /// - /// Returns the default current portal layout + /// Returns the default current portal layout. /// /// string GetDefaultPortalLayout(); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IFriendlyUrlWrapper.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IFriendlyUrlWrapper.cs index b5500eeeb39..208eb06c0f3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IFriendlyUrlWrapper.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IFriendlyUrlWrapper.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Urls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Urls; + public interface IFriendlyUrlWrapper { string CleanNameForUrl(string urlPath, FriendlyUrlOptions options, out bool modified); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs index ad5b98d318d..55e91e9da0b 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Tabs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using DotNetNuke.Entities.Tabs; + public interface IPageManagementController { string GetCreatedInfo(TabInfo tab); @@ -14,11 +14,9 @@ public interface IPageManagementController string GetTabUrl(TabInfo tab); - /// - /// Returns true if tab has children, false otherwise - /// - /// Tab info object - /// Returns true if tab has children, false otherwise + /// Gets a value indicating whether the given has children. + /// Tab info object. + /// Returns true if tab has children, false otherwise. bool TabHasChildren(TabInfo tabInfo); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageUrlsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageUrlsController.cs index 3953eb8e10f..b73c0b7ea6e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageUrlsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageUrlsController.cs @@ -1,16 +1,17 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using Dnn.PersonaBar.Pages.Components.Dto; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System.Collections.Generic; + + using Dnn.PersonaBar.Pages.Components.Dto; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + public interface IPageUrlsController { IEnumerable GetPageUrls(TabInfo tab, int portalId); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs index 24bbf4eb171..a818e69be8f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs @@ -1,22 +1,23 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using Dnn.PersonaBar.Pages.Components.Dto; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System.Collections.Generic; + + using Dnn.PersonaBar.Pages.Components.Dto; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + public interface IPagesController { bool IsValidTabPath(TabInfo tab, string newTabPath, string newTabName, out string errorMessage); - IEnumerable GetPageList(PortalSettings portalSettings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false); - + IEnumerable GetPageList(PortalSettings portalSettings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false); + IEnumerable GetPageList(PortalSettings portalSettings, bool? deleted, string tabName, string tabTitle, string tabPath, string tabSkin, bool? visible, int parentId, out int total, string searchKey = "", int pageIndex = -1, int pageSize = 10, bool includeSubpages = false); @@ -42,23 +43,23 @@ IEnumerable SearchPages(out int totalRecords, string searchKey = "", st void DeleteTabModule(int pageId, int moduleId); /// - /// Returns a clean tab relative url based on Advanced Management Url settings + /// Returns a clean tab relative url based on Advanced Management Url settings. /// - /// Url not cleaned, this could containes blank space or invalid characters - /// Cleaned Url + /// Url not cleaned, this could containes blank space or invalid characters. + /// Cleaned Url. string CleanTabUrl(string url); /// - /// Copy the given theme to all descendant pages + /// Copy the given theme to all descendant pages. /// - /// page identifier - /// Theme + /// page identifier. + /// Theme. void CopyThemeToDescendantPages(int pageId, Theme theme); /// - /// Copy the current page permissions to all descendant pages + /// Copy the current page permissions to all descendant pages. /// - /// page identifier + /// page identifier. void CopyPermissionsToDescendantPages(int pageId); IEnumerable GetPageUrls(int tabId); @@ -66,6 +67,6 @@ IEnumerable SearchPages(out int totalRecords, string searchKey = "", st PageUrlResult CreateCustomUrl(SeoUrl dto); PageUrlResult UpdateCustomUrl(SeoUrl dto); PageUrlResult DeleteCustomUrl(UrlIdDto dto); - PagePermissions GetPermissionsData(int pageId); + PagePermissions GetPermissionsData(int pageId); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs index 9f697f14f55..a2cba37bfe1 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs @@ -1,14 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using Dnn.PersonaBar.Pages.Components.Dto; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Entities.Tabs; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System.Collections.Generic; + + using Dnn.PersonaBar.Pages.Components.Dto; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Entities.Tabs; + public interface ITemplateController { string SaveAsTemplate(PageTemplate template); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IUrlRewriterUtilsWrapper.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IUrlRewriterUtilsWrapper.cs index 8b13adf72d0..b521d61fd1a 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IUrlRewriterUtilsWrapper.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IUrlRewriterUtilsWrapper.cs @@ -1,12 +1,12 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Urls; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Urls; + public interface IUrlRewriterUtilsWrapper { FriendlyUrlOptions GetExtendOptionsForURLs(int portalId); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Localization.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Localization.cs index b6fc2ffe3aa..b7f546b9bea 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Localization.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Localization.cs @@ -1,11 +1,11 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.IO; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System.IO; + public class Localization { private static string LocalResourcesFile => Path.Combine(Library.Constants.PersonaBarRelativePath, "Modules/Dnn.Pages/App_LocalResources/Pages.resx"); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs index 176b691920f..9b0f46888a6 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs @@ -1,18 +1,19 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Linq; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + using System.Linq; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Framework; + public class PageManagementController : ServiceLocator, IPageManagementController { public static string PageDateTimeFormat = "yyyy-MM-dd hh:mm tt"; @@ -20,12 +21,9 @@ public class PageManagementController : ServiceLocator ", from t in tab.BreadCrumbs.Cast().Take(tab.BreadCrumbs.Count - 1) select t.LocalizedTabName); } @@ -85,9 +83,8 @@ public string GetTabUrl(TabInfo tab) } return url; - } - #endregion - + } + protected override Func GetFactory() { return () => new PageManagementController(); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs index c48010abd3d..ee31b7bdd07 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs @@ -1,34 +1,52 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Dnn.PersonaBar.Pages.Components.Dto; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Services.Localization; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using Dnn.PersonaBar.Pages.Components.Dto; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Services.Localization; + public class PageUrlsController : ServiceLocator, IPageUrlsController { - private enum SortingFields { None = 0, Url, Locale, Status }; + private enum SortingFields + { + None = 0, + Url, + Locale, + Status, + } - public IEnumerable GetPageUrls(TabInfo tab, int portalId) + protected IEnumerable> StatusCodes { - + get + { + return new[] + { + new KeyValuePair(200, "Active (200)"), + new KeyValuePair(301, "Redirect (301)") + }; + } + } + + public IEnumerable GetPageUrls(TabInfo tab, int portalId) + { var locales = new Lazy>(() => LocaleController.Instance.GetLocales(portalId)); - var customUrls = GetSortedUrls(tab, portalId, locales, 1, true, false); - var automaticUrls = GetSortedUrls(tab, portalId, locales, 1, true, true).ToList(); + var customUrls = this.GetSortedUrls(tab, portalId, locales, 1, true, false); + var automaticUrls = this.GetSortedUrls(tab, portalId, locales, 1, true, true).ToList(); automaticUrls.AddRange(customUrls); return automaticUrls.OrderBy(url => url.StatusCode, new KeyValuePairComparer()).ThenBy(url => url.Path); @@ -46,7 +64,7 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) Success = false, ErrorMessage = Localization.GetString("CustomUrlPortalAlias.Error"), SuggestedUrlPath = String.Empty - }; + }; } var urlPath = dto.Path.ValueOrEmpty().TrimStart('/'); @@ -57,7 +75,8 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) urlPath = FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); if (modified) { - return new PageUrlResult { + return new PageUrlResult + { Success = false, ErrorMessage = Localization.GetString("CustomUrlPathCleaned.Error"), SuggestedUrlPath = "/" + urlPath @@ -68,7 +87,8 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) urlPath = FriendlyUrlController.ValidateUrl(urlPath, -1, portalSettings, out modified); if (modified) { - return new PageUrlResult { + return new PageUrlResult + { Success = false, ErrorMessage = Localization.GetString("UrlPathNotUnique.Error"), SuggestedUrlPath = "/" + urlPath @@ -78,7 +98,8 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) if (tab.TabUrls.Any(u => u.Url.ToLowerInvariant() == dto.Path.ValueOrEmpty().ToLowerInvariant() && (u.PortalAliasId == dto.SiteAliasKey || u.PortalAliasId == -1))) { - return new PageUrlResult { + return new PageUrlResult + { Success = false, ErrorMessage = Localization.GetString("DuplicateUrl.Error") }; @@ -264,8 +285,7 @@ public PageUrlResult UpdateCustomUrl(SaveUrlDto dto, TabInfo tab) TabController.Instance.SaveTabUrl(tabUrl, portalSettings.PortalId, true); } } - - + return new PageUrlResult { Success = true @@ -285,6 +305,11 @@ public PageUrlResult DeleteCustomUrl(int id, TabInfo tab) }; } + protected override Func GetFactory() + { + return () => new PageUrlsController(); + } + private IEnumerable GetSortedUrls(TabInfo tab, int portalId, Lazy> locales, int sortColumn, bool sortOrder, bool isSystem) { var friendlyUrlSettings = new FriendlyUrlSettings(tab.PortalID); @@ -339,7 +364,7 @@ private IEnumerable GetSortedUrls(TabInfo tab, int portalId, Lazy GetSortedUrls(TabInfo tab, int portalId, Lazy GetSortedUrls(TabInfo tab, int portalId, Lazy GetSortedUrls(TabInfo tab, int portalId, Lazy p.CultureCode == url.CultureCode); if (alias == null) { - //if no primary alias just get first in list, need to use something - alias = aliases.FirstOrDefault(a => a.PortalID == portalId); + // check primary when no culture code is defined + alias = aliases.FirstOrDefault(primary => primary.IsPrimary == true); + if (alias == null) + { + //if no primary alias just get first in list, need to use something + alias = aliases.FirstOrDefault(a => a.PortalID == portalId); + } } if (alias != null) { var urlLocale = locales.Value.Values.FirstOrDefault(local => local.Code == alias.CultureCode); - AddUrlToList(tabs, portalId, url.SeqNum, alias, urlLocale, url.Url, url.QueryString, statusCode, isSystem, friendlyUrlSettings, url.LastModifiedByUserId); + this.AddUrlToList(tabs, portalId, url.SeqNum, alias, urlLocale, url.Url, url.QueryString, statusCode, isSystem, friendlyUrlSettings, url.LastModifiedByUserId); } } else @@ -401,7 +431,7 @@ private IEnumerable GetSortedUrls(TabInfo tab, int portalId, Lazy p.PortalAliasID == url.PortalAliasId); if (alias != null) { - AddUrlToList(tabs, portalId, url.SeqNum, alias, urlLocale, url.Url, url.QueryString, statusCode, isSystem, friendlyUrlSettings, url.LastModifiedByUserId); + this.AddUrlToList(tabs, portalId, url.SeqNum, alias, urlLocale, url.Url, url.QueryString, statusCode, isSystem, friendlyUrlSettings, url.LastModifiedByUserId); } } } @@ -442,28 +472,16 @@ private void AddUrlToList(List tabs, int portalId, int id, PortalAliasInfo Id = id, SiteAlias = new KeyValuePair(alias.KeyID, alias.HTTPAlias), Path = path, - PathWithNoExtension = GetCleanPath(path, friendlyUrlSettings), + PathWithNoExtension = this.GetCleanPath(path, friendlyUrlSettings), QueryString = queryString, Locale = (urlLocale != null) ? new KeyValuePair(urlLocale.KeyID, urlLocale.EnglishName) : new KeyValuePair(-1, ""), - StatusCode = StatusCodes.SingleOrDefault(kv => kv.Key == statusCode), + StatusCode = this.StatusCodes.SingleOrDefault(kv => kv.Key == statusCode), SiteAliasUsage = (int)PortalAliasUsageType.ChildPagesInherit, IsSystem = isSystem, UserName = userName }); } - - protected IEnumerable> StatusCodes - { - get - { - return new[] - { - new KeyValuePair(200, "Active (200)"), - new KeyValuePair(301, "Redirect (301)") - }; - } - } private string GetCleanPath(string path, FriendlyUrlSettings friendlyUrlSettings) { if (string.IsNullOrEmpty(path)) @@ -483,10 +501,5 @@ public int Compare(KeyValuePair pair1, KeyValuePair pa return String.Compare(pair1.Value, pair2.Value, StringComparison.OrdinalIgnoreCase); } } - - protected override Func GetFactory() - { - return () => new PageUrlsController(); - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesController.cs index ff900d05e5b..87b612e4a6b 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesController.cs @@ -1,12 +1,13 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using DotNetNuke.Framework; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + + using DotNetNuke.Framework; + public class PagesController : ServiceLocator { protected override Func GetFactory() diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs index 587086b135f..a210d9ace2e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs @@ -1,41 +1,44 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; -using Dnn.PersonaBar.Library.DTO; -using Dnn.PersonaBar.Library.Helper; -using Dnn.PersonaBar.Pages.Components.Dto; -using Dnn.PersonaBar.Pages.Components.Exceptions; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Content; -using DotNetNuke.Entities.Content.Common; -using DotNetNuke.Entities.Content.Taxonomy; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Urls; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.Exceptions; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Personalization; -using PermissionsNotMetException = DotNetNuke.Entities.Tabs.PermissionsNotMetException; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.Pages.Components { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + + using Dnn.PersonaBar.Library.DTO; + using Dnn.PersonaBar.Library.Helper; + using Dnn.PersonaBar.Pages.Components.Dto; + using Dnn.PersonaBar.Pages.Components.Exceptions; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + + using PermissionsNotMetException = DotNetNuke.Entities.Tabs.PermissionsNotMetException; + public class PagesControllerImpl : IPagesController { + public const string PageTagsVocabulary = "PageTags"; + private readonly ITabController _tabController; private readonly IModuleController _moduleController; private readonly IPageUrlsController _pageUrlsController; @@ -46,11 +49,7 @@ public class PagesControllerImpl : IPagesController private readonly IFriendlyUrlWrapper _friendlyUrlWrapper; private readonly IContentVerifier _contentVerifier; private readonly IPortalController _portalController; - - public const string PageTagsVocabulary = "PageTags"; - private static readonly IList TabSettingKeys = new List { "CustomStylesheet" }; - - private PortalSettings PortalSettings { get; set; } + private static readonly IList TabSettingKeys = new List { "CustomStylesheet" }; public PagesControllerImpl() : this( @@ -80,22 +79,23 @@ public PagesControllerImpl( IContentVerifier contentVerifier, IPortalController portalController) { - _tabController = tabController; - _moduleController = moduleController; - _pageUrlsController = pageUrlsController; - _templateController = templateController; - _defaultPortalThemeController = defaultPortalThemeController; - _cloneModuleExecutionContext = cloneModuleExecutionContext; - _urlRewriterUtilsWrapper = urlRewriterUtilsWrapper; - _friendlyUrlWrapper = friendlyUrlWrapper; - _contentVerifier = contentVerifier; - _portalController = portalController; - } - + this._tabController = tabController; + this._moduleController = moduleController; + this._pageUrlsController = pageUrlsController; + this._templateController = templateController; + this._defaultPortalThemeController = defaultPortalThemeController; + this._cloneModuleExecutionContext = cloneModuleExecutionContext; + this._urlRewriterUtilsWrapper = urlRewriterUtilsWrapper; + this._friendlyUrlWrapper = friendlyUrlWrapper; + this._contentVerifier = contentVerifier; + this._portalController = portalController; + } + private PortalSettings PortalSettings { get; set; } + public bool IsValidTabPath(TabInfo tab, string newTabPath, string newTabName, out string errorMessage) { - var portalSettings = PortalSettings ?? PortalController.Instance.GetCurrentPortalSettings(); + var portalSettings = this.PortalSettings ?? PortalController.Instance.GetCurrentPortalSettings(); var valid = true; errorMessage = string.Empty; @@ -110,7 +110,7 @@ public bool IsValidTabPath(TabInfo tab, string newTabPath, string newTabName, ou var tabId = TabController.GetTabByTabPath(portalSettings.PortalId, newTabPath, cultureCode); if (tabId != Null.NullInteger && (tab == null || tabId != tab.TabID)) { - var existingTab = _tabController.GetTab(tabId, portalSettings.PortalId, false); + var existingTab = this._tabController.GetTab(tabId, portalSettings.PortalId, false); if (existingTab != null && existingTab.IsDeleted) { errorMessage = Localization.GetString("TabRecycled"); @@ -166,8 +166,7 @@ public List GetPageHierarchy(int pageId) return paths; } - - + public TabInfo MovePage(PageMoveRequest request) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -181,7 +180,7 @@ public TabInfo MovePage(PageMoveRequest request) { string errorMessage; - if (!IsValidTabPath(tab, Globals.GenerateTabPath(request.ParentId, tab.TabName), tab.TabName, out errorMessage)) + if (!this.IsValidTabPath(tab, Globals.GenerateTabPath(request.ParentId, tab.TabName), tab.TabName, out errorMessage)) { throw new PageException(errorMessage); } @@ -195,7 +194,7 @@ public TabInfo MovePage(PageMoveRequest request) } string errorMessage; - if (tab.ParentId != relatedTab.ParentId && !IsValidTabPath(tab, Globals.GenerateTabPath(relatedTab.ParentId, tab.TabName), tab.TabName, out errorMessage)) + if (tab.ParentId != relatedTab.ParentId && !this.IsValidTabPath(tab, Globals.GenerateTabPath(relatedTab.ParentId, tab.TabName), tab.TabName, out errorMessage)) { throw new PageException(errorMessage); } @@ -211,7 +210,7 @@ public TabInfo MovePage(PageMoveRequest request) break; case "parent": //avoid move tab into its child page - if (IsChild(portalSettings.PortalId, tab.TabID, request.ParentId)) + if (this.IsChild(portalSettings.PortalId, tab.TabID, request.ParentId)) { throw new PageException("DragInvalid"); } @@ -226,7 +225,7 @@ public TabInfo MovePage(PageMoveRequest request) public void DeletePage(PageItem page, PortalSettings portalSettings = null) { - DeletePage(page, false, portalSettings); + this.DeletePage(page, false, portalSettings); } public void DeletePage(PageItem page, bool hardDelete, PortalSettings portalSettings = null) @@ -246,7 +245,7 @@ public void DeletePage(PageItem page, bool hardDelete, PortalSettings portalSett } else { - if (_contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, currentPortal)) + if (this._contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, currentPortal)) { if (hardDelete) { @@ -290,11 +289,11 @@ public void EditModeForPage(int pageId, int userId) public TabInfo SavePageDetails(PortalSettings settings, PageSettings pageSettings) { - PortalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); + this.PortalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); TabInfo tab = null; if (pageSettings.TabId > 0) { - tab = TabController.Instance.GetTab(pageSettings.TabId, PortalSettings.PortalId); + tab = TabController.Instance.GetTab(pageSettings.TabId, this.PortalSettings.PortalId); if (tab == null) { throw new PageNotFoundException(); @@ -303,16 +302,34 @@ public TabInfo SavePageDetails(PortalSettings settings, PageSettings pageSetting string errorMessage; string field; - if (!ValidatePageSettingsData(PortalSettings, pageSettings, tab, out field, out errorMessage)) + if (!this.ValidatePageSettingsData(this.PortalSettings, pageSettings, tab, out field, out errorMessage)) { throw new PageValidationException(field, errorMessage); } var tabId = pageSettings.TabId <= 0 - ? AddTab(PortalSettings, pageSettings) - : UpdateTab(tab, pageSettings); + ? this.AddTab(this.PortalSettings, pageSettings) + : this.UpdateTab(tab, pageSettings); - return TabController.Instance.GetTab(tabId, PortalSettings.PortalId); + return TabController.Instance.GetTab(tabId, this.PortalSettings.PortalId); + } + + public IEnumerable GetPageList(PortalSettings settings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false) + { + var portalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); + var adminTabId = portalSettings.AdminTabId; + + var tabs = TabController.GetPortalTabs(portalSettings.PortalId, adminTabId, false, includeHidden, includeDeleted, true); + var pages = from t in tabs + where (t.ParentId != adminTabId || t.ParentId == Null.NullInteger) && + !t.IsSystem && + ((string.IsNullOrEmpty(searchKey) && (includeSubpages || t.ParentId == parentId)) + || (!string.IsNullOrEmpty(searchKey) && + (t.TabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger + || t.LocalizedTabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger))) + select t; + + return includeSubpages ? pages.OrderBy(x => x.ParentId > -1 ? x.ParentId : x.TabID).ThenBy(x => x.TabID) : pages; } private bool IsChild(int portalId, int tabId, int parentId) @@ -341,30 +358,12 @@ private bool IsChild(int portalId, int tabId, int parentId) return false; } - public IEnumerable GetPageList(PortalSettings settings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false) - { - var portalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); - var adminTabId = portalSettings.AdminTabId; - - var tabs = TabController.GetPortalTabs(portalSettings.PortalId, adminTabId, false, includeHidden, includeDeleted, true); - var pages = from t in tabs - where (t.ParentId != adminTabId || t.ParentId == Null.NullInteger) && - !t.IsSystem && - ((string.IsNullOrEmpty(searchKey) && (includeSubpages || t.ParentId == parentId)) - || (!string.IsNullOrEmpty(searchKey) && - (t.TabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger - || t.LocalizedTabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger))) - select t; - - return includeSubpages ? pages.OrderBy(x => x.ParentId > -1 ? x.ParentId : x.TabID).ThenBy(x => x.TabID) : pages; - } - public IEnumerable GetPageList(PortalSettings portalSettings, bool? deleted, string tabName, string tabTitle, string tabPath, string tabSkin, bool? visible, int parentId, out int total, string searchKey = "", int pageIndex = -1, int pageSize = 10, bool includeSubpages = false) { pageIndex = pageIndex <= 0 ? 0 : pageIndex; pageSize = pageSize > 0 && pageSize <= 100 ? pageSize : 10; - var tabs = GetPageList(portalSettings, parentId, searchKey, true, deleted ?? false, includeSubpages); + var tabs = this.GetPageList(portalSettings, parentId, searchKey, true, deleted ?? false, includeSubpages); var finalList = new List(); if (deleted.HasValue) tabs = tabs.Where(tab => tab.IsDeleted == deleted); @@ -388,7 +387,7 @@ public IEnumerable GetPageList(PortalSettings portalSettings, bool? del Regex.IsMatch(tab.TabPath, tabPath.Replace("*", ".*"), RegexOptions.IgnoreCase); if (!string.IsNullOrEmpty(tabSkin)) { - var escapedString = Regex.Replace(tabSkin, "([^\\w^\\*\\s]+)+", @"\$1", RegexOptions.Compiled|RegexOptions.ECMAScript|RegexOptions.IgnoreCase|RegexOptions.Multiline); + var escapedString = Regex.Replace(tabSkin, "([^\\w^\\*\\s]+)+", @"\$1", RegexOptions.Compiled | RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline); bIsMatch = bIsMatch & Regex.IsMatch(tab.SkinSrc, escapedString.Replace("*", ".*"), RegexOptions.IgnoreCase); } @@ -466,10 +465,49 @@ public IEnumerable SearchPages(out int totalRecords, string searchKey = return pageIndex == -1 || pageSize == -1 ? pages : pages.Skip(pageIndex * pageSize).Take(pageSize); } + public IEnumerable GetModules(int pageId) + { + var tabModules = this._moduleController.GetTabModules(pageId); + return tabModules.Values.Where(m => !m.IsDeleted); + } + + public bool ValidatePageUrlSettings(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, ref string invalidField, ref string errorMessage) + { + var urlPath = pageSettings.Url; + + if (string.IsNullOrEmpty(urlPath)) + { + return true; + } + + bool modified; + //Clean Url + var options = this._urlRewriterUtilsWrapper.GetExtendOptionsForURLs(portalSettings.PortalId); + urlPath = this.GetLocalPath(urlPath); + urlPath = this._friendlyUrlWrapper.CleanNameForUrl(urlPath, options, out modified); + if (modified) + { + errorMessage = Localization.GetString("UrlPathCleaned"); + invalidField = "url"; + return false; + } + + //Validate for uniqueness + this._friendlyUrlWrapper.ValidateUrl(urlPath, tab?.TabID ?? Null.NullInteger, portalSettings, out modified); + if (modified) + { + errorMessage = Localization.GetString("UrlPathNotUnique"); + invalidField = "url"; + return false; + } + + return true; + } + private TabInfo GetPageDetails(int pageId) { - var portalSettings = _portalController.GetCurrentPortalSettings(); - var tab = _tabController.GetTab(pageId, portalSettings.PortalId); + var portalSettings = this._portalController.GetCurrentPortalSettings(); + var tab = this._tabController.GetTab(pageId, portalSettings.PortalId); if (tab == null) { throw new PageNotFoundException(); @@ -478,12 +516,6 @@ private TabInfo GetPageDetails(int pageId) return tab; } - public IEnumerable GetModules(int pageId) - { - var tabModules = _moduleController.GetTabModules(pageId); - return tabModules.Values.Where(m => !m.IsDeleted); - } - protected virtual bool ValidatePageSettingsData(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, out string invalidField, out string errorMessage) { errorMessage = string.Empty; @@ -512,10 +544,10 @@ protected virtual bool ValidatePageSettingsData(PortalSettings portalSettings, P if (pageSettings.PageType == "template") { - parentId = GetTemplateParentId(tab?.PortalID ?? portalSettings.PortalId); + parentId = this.GetTemplateParentId(tab?.PortalID ?? portalSettings.PortalId); } - isValid = IsValidTabPath(tab, Globals.GenerateTabPath(parentId, pageSettings.Name), pageSettings.Name, out errorMessage); + isValid = this.IsValidTabPath(tab, Globals.GenerateTabPath(parentId, pageSettings.Name), pageSettings.Name, out errorMessage); if (!isValid) { invalidField = pageSettings.PageType == "template" ? "templateName" : "name"; @@ -568,7 +600,7 @@ protected virtual bool ValidatePageSettingsData(PortalSettings portalSettings, P break; } - return ValidatePageUrlSettings(portalSettings, pageSettings, tab, ref invalidField, ref errorMessage); + return this.ValidatePageUrlSettings(portalSettings, pageSettings, tab, ref invalidField, ref errorMessage); } protected virtual int GetTemplateParentId(int portalId) @@ -576,96 +608,141 @@ protected virtual int GetTemplateParentId(int portalId) return Null.NullInteger; } - public bool ValidatePageUrlSettings(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, ref string invalidField, ref string errorMessage) - { - var urlPath = pageSettings.Url; - - if (string.IsNullOrEmpty(urlPath)) - { - return true; - } - - bool modified; - //Clean Url - var options = _urlRewriterUtilsWrapper.GetExtendOptionsForURLs(portalSettings.PortalId); - urlPath = GetLocalPath(urlPath); - urlPath = _friendlyUrlWrapper.CleanNameForUrl(urlPath, options, out modified); - if (modified) - { - errorMessage = Localization.GetString("UrlPathCleaned"); - invalidField = "url"; - return false; - } - - //Validate for uniqueness - _friendlyUrlWrapper.ValidateUrl(urlPath, tab?.TabID ?? Null.NullInteger, portalSettings, out modified); - if (modified) - { - errorMessage = Localization.GetString("UrlPathNotUnique"); - invalidField = "url"; - return false; - } - - return true; - } - public virtual int AddTab(PortalSettings settings, PageSettings pageSettings) { var portalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); var portalId = portalSettings.PortalId; var tab = new TabInfo { PortalID = portalId, ParentId = pageSettings.ParentId ?? Null.NullInteger }; - UpdateTabInfoFromPageSettings(tab, pageSettings); + this.UpdateTabInfoFromPageSettings(tab, pageSettings); if (portalSettings.ContentLocalizationEnabled) { tab.CultureCode = portalSettings.CultureCode; } - SavePagePermissions(tab, pageSettings.Permissions); + this.SavePagePermissions(tab, pageSettings.Permissions); - var tabId = _tabController.AddTab(tab); - tab = _tabController.GetTab(tabId, portalId); + var tabId = this._tabController.AddTab(tab); + tab = this._tabController.GetTab(tabId, portalId); - CreateOrUpdateContentItem(tab); + this.CreateOrUpdateContentItem(tab); if (pageSettings.TemplateTabId > 0) { - CopyContentFromSourceTab(tab, pageSettings.TemplateTabId, pageSettings.Modules); + this.CopyContentFromSourceTab(tab, pageSettings.TemplateTabId, pageSettings.Modules); } if (pageSettings.TemplateId > 0) { try { - _templateController.CreatePageFromTemplate(pageSettings.TemplateId, tab, portalId); + this._templateController.CreatePageFromTemplate(pageSettings.TemplateId, tab, portalId); } catch (PageException) { - _tabController.DeleteTab(tab.TabID, portalId); + this._tabController.DeleteTab(tab.TabID, portalId); throw; } } - SaveTabUrl(tab, pageSettings); + this.SaveTabUrl(tab, pageSettings); - MovePageIfNeeded(pageSettings, tab); + this.MovePageIfNeeded(pageSettings, tab); - _tabController.ClearCache(portalId); + this._tabController.ClearCache(portalId); return tab.TabID; } - private void MovePageIfNeeded(PageSettings pageSettings, TabInfo tab) + public void SaveTabUrl(TabInfo tab, PageSettings pageSettings) { - if (pageSettings.ParentId.HasValue && pageSettings.ParentId.Value != tab.ParentId) + if (!pageSettings.CustomUrlEnabled) { - var request = new PageMoveRequest + return; + } + + if (tab.IsSuperTab) + { + return; + } + + var url = pageSettings.Url; + var tabUrl = tab.TabUrls.SingleOrDefault(t => t.IsSystem + && t.HttpStatus == "200" + && t.SeqNum == 0); + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (!String.IsNullOrEmpty(url) && url != "/") + { + url = this.CleanTabUrl(url); + + string currentUrl = String.Empty; + var friendlyUrlSettings = new FriendlyUrlSettings(portalSettings.PortalId); + if (tab.TabID > -1) { - Action = "parent", - PageId = tab.TabID, - ParentId = pageSettings.ParentId.Value - }; + var baseUrl = Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias) + "/Default.aspx?TabId=" + tab.TabID; + var path = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, + baseUrl, + Globals.glbDefaultPage, + portalSettings.PortalAlias.HTTPAlias, + false, + friendlyUrlSettings, + Guid.Empty); + + currentUrl = path.Replace(Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias), ""); + } + + if (url == currentUrl) + { + return; + } - MovePage(request); + if (tabUrl == null) + { + //Add new custom url + tabUrl = new TabUrlInfo + { + TabId = tab.TabID, + SeqNum = 0, + PortalAliasId = -1, + PortalAliasUsage = PortalAliasUsageType.Default, + QueryString = String.Empty, + Url = url, + HttpStatus = "200", + CultureCode = String.Empty, + IsSystem = true + }; + //Save url + this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); + } + else + { + //Change the original 200 url to a redirect + tabUrl.HttpStatus = "301"; + tabUrl.SeqNum = tab.TabUrls.Max(t => t.SeqNum) + 1; + this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); + + //Add new custom url + tabUrl.Url = url; + tabUrl.HttpStatus = "200"; + tabUrl.SeqNum = 0; + this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); + } + + //Delete any redirects to the same url + foreach (var redirecturl in this._tabController.GetTabUrls(tab.TabID, tab.PortalID)) + { + if (redirecturl.Url == url && redirecturl.HttpStatus != "200") + { + this._tabController.DeleteTabUrl(redirecturl, tab.PortalID, true); + } + } + } + else + { + if (url == "/" && tabUrl != null) + { + this._tabController.DeleteTabUrl(tabUrl, portalSettings.PortalId, true); + } } } @@ -674,8 +751,8 @@ protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings p tab.TabName = pageSettings.Name; tab.TabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); tab.Title = pageSettings.Title; - tab.Description = GetTabDescription(pageSettings); - tab.KeyWords = GetKeyWords(pageSettings); + tab.Description = this.GetTabDescription(pageSettings); + tab.KeyWords = this.GetKeyWords(pageSettings); tab.IsVisible = pageSettings.IncludeInMenu; tab.DisableLink = pageSettings.DisableLink; @@ -689,7 +766,7 @@ protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings p tab.PageHeadText = pageSettings.PageHeadText; tab.PermanentRedirect = pageSettings.PermanentRedirect; - tab.Url = GetInternalUrl(pageSettings); + tab.Url = this.GetInternalUrl(pageSettings); tab.TabSettings["CacheProvider"] = pageSettings.CacheProvider; if (pageSettings.CacheProvider != null) @@ -726,12 +803,12 @@ protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings p tab.TabSettings["CustomStylesheet"] = pageSettings.PageStyleSheet; // Tab Skin - tab.SkinSrc = GetSkinSrc(pageSettings); - tab.ContainerSrc = GetContainerSrc(pageSettings); + tab.SkinSrc = this.GetSkinSrc(pageSettings); + tab.ContainerSrc = this.GetContainerSrc(pageSettings); if (pageSettings.PageType == "template") { - tab.ParentId = GetTemplateParentId(tab.PortalID); + tab.ParentId = this.GetTemplateParentId(tab.PortalID); tab.IsSystem = true; } @@ -809,13 +886,38 @@ protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings p else { tab.IconFileLarge = null; + } + + } + + private static string GetExternalUrlRedirection(string url) + { + if (url == null) + { + return null; + } + + return url.ToLower() == "http://" ? "" : Globals.AddHTTP(url); + } + + private void MovePageIfNeeded(PageSettings pageSettings, TabInfo tab) + { + if (pageSettings.ParentId.HasValue && pageSettings.ParentId.Value != tab.ParentId) + { + var request = new PageMoveRequest + { + Action = "parent", + PageId = tab.TabID, + ParentId = pageSettings.ParentId.Value + }; + + this.MovePage(request); } - } private string GetContainerSrc(PageSettings pageSettings) { - var defaultContainer = _defaultPortalThemeController.GetDefaultPortalContainer(); + var defaultContainer = this._defaultPortalThemeController.GetDefaultPortalContainer(); if (pageSettings.ContainerSrc != null && pageSettings.ContainerSrc.Equals(defaultContainer, StringComparison.OrdinalIgnoreCase)) @@ -827,7 +929,7 @@ private string GetContainerSrc(PageSettings pageSettings) private string GetSkinSrc(PageSettings pageSettings) { - var defaultSkin = _defaultPortalThemeController.GetDefaultPortalLayout(); + var defaultSkin = this._defaultPortalThemeController.GetDefaultPortalLayout(); if (pageSettings.SkinSrc != null && pageSettings.SkinSrc.Equals(defaultSkin, StringComparison.OrdinalIgnoreCase)) @@ -852,22 +954,12 @@ private string GetInternalUrl(PageSettings pageSettings) } } - private static string GetExternalUrlRedirection(string url) - { - if (url == null) - { - return null; - } - - return url.ToLower() == "http://" ? "" : Globals.AddHTTP(url); - } - /// /// If the tab description is equal to the portal description - /// we store null so the system will serve the portal description instead + /// we store null so the system will serve the portal description instead. /// /// - /// Tab Description value to be stored + /// Tab Description value to be stored. private string GetTabDescription(PageSettings pageSettings) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -877,10 +969,10 @@ private string GetTabDescription(PageSettings pageSettings) /// /// If the tab keywords is equal to the portal keywords - /// we store null so the system will serve the portal keywords instead + /// we store null so the system will serve the portal keywords instead. /// /// - /// Tab Keywords value to be stored + /// Tab Keywords value to be stored. private string GetKeyWords(PageSettings pageSettings) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -888,100 +980,6 @@ private string GetKeyWords(PageSettings pageSettings) ? pageSettings.Keywords : null; } - public void SaveTabUrl(TabInfo tab, PageSettings pageSettings) - { - if (!pageSettings.CustomUrlEnabled) - { - return; - } - - if (tab.IsSuperTab) - { - return; - } - - var url = pageSettings.Url; - var tabUrl = tab.TabUrls.SingleOrDefault(t => t.IsSystem - && t.HttpStatus == "200" - && t.SeqNum == 0); - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (!String.IsNullOrEmpty(url) && url != "/") - { - url = CleanTabUrl(url); - - string currentUrl = String.Empty; - var friendlyUrlSettings = new FriendlyUrlSettings(portalSettings.PortalId); - if (tab.TabID > -1) - { - var baseUrl = Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias) + "/Default.aspx?TabId=" + tab.TabID; - var path = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - baseUrl, - Globals.glbDefaultPage, - portalSettings.PortalAlias.HTTPAlias, - false, - friendlyUrlSettings, - Guid.Empty); - - currentUrl = path.Replace(Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias), ""); - } - - if (url == currentUrl) - { - return; - } - - if (tabUrl == null) - { - //Add new custom url - tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = 0, - PortalAliasId = -1, - PortalAliasUsage = PortalAliasUsageType.Default, - QueryString = String.Empty, - Url = url, - HttpStatus = "200", - CultureCode = String.Empty, - IsSystem = true - }; - //Save url - _tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); - } - else - { - //Change the original 200 url to a redirect - tabUrl.HttpStatus = "301"; - tabUrl.SeqNum = tab.TabUrls.Max(t => t.SeqNum) + 1; - _tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); - - //Add new custom url - tabUrl.Url = url; - tabUrl.HttpStatus = "200"; - tabUrl.SeqNum = 0; - _tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); - } - - - //Delete any redirects to the same url - foreach (var redirecturl in _tabController.GetTabUrls(tab.TabID, tab.PortalID)) - { - if (redirecturl.Url == url && redirecturl.HttpStatus != "200") - { - _tabController.DeleteTabUrl(redirecturl, tab.PortalID, true); - } - } - } - else - { - if (url == "/" && tabUrl != null) - { - _tabController.DeleteTabUrl(tabUrl, portalSettings.PortalId, true); - } - } - } - public string CleanTabUrl(string url) { if (string.IsNullOrEmpty(url)) @@ -1007,7 +1005,7 @@ public void CopyThemeToDescendantPages(int pageId, Theme theme) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var portalId = portalSettings.PortalId; - var tab = _tabController.GetTab(pageId, portalId, false); + var tab = this._tabController.GetTab(pageId, portalId, false); if (tab == null) { throw new PageNotFoundException(); @@ -1020,7 +1018,7 @@ public void CopyPermissionsToDescendantPages(int pageId) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var portalId = portalSettings.PortalId; - var tab = _tabController.GetTab(pageId, portalId, false); + var tab = this._tabController.GetTab(pageId, portalId, false); if (tab == null) { throw new PageNotFoundException(); @@ -1036,35 +1034,36 @@ public void CopyPermissionsToDescendantPages(int pageId) public IEnumerable GetPageUrls(int tabId) { - var tab = GetPageDetails(tabId); + var tab = this.GetPageDetails(tabId); var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var portalId = portalSettings.PortalId; - return _pageUrlsController.GetPageUrls(tab, portalId); + return this._pageUrlsController.GetPageUrls(tab, portalId); } public PageSettings GetPageSettings(int pageId, PortalSettings requestPortalSettings = null) { - var tab = GetPageDetails(pageId); + var tab = this.GetPageDetails(pageId); - var portalSettings = requestPortalSettings ?? _portalController.GetCurrentPortalSettings(); + var portalSettings = requestPortalSettings ?? this._portalController.GetCurrentPortalSettings(); - if (!_contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, portalSettings)) + if (!this._contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, portalSettings)) { throw new PageNotFoundException(); - } - + } + var page = Converters.ConvertToPageSettings(tab); - page.Modules = GetModules(page.TabId).Select(Converters.ConvertToModuleItem); - page.PageUrls = GetPageUrls(page.TabId); - page.Permissions = GetPermissionsData(pageId); - page.SiteAliases = GetSiteAliases(portalSettings.PortalId); - page.PrimaryAliasId = GetPrimaryAliasId(portalSettings.PortalId, portalSettings.CultureCode); - page.Locales = GetLocales(portalSettings.PortalId); + page.Modules = this.GetModules(page.TabId).Select(Converters.ConvertToModuleItem); + page.PageUrls = this.GetPageUrls(page.TabId); + page.Permissions = this.GetPermissionsData(pageId); + page.SiteAliases = this.GetSiteAliases(portalSettings.PortalId); + page.PrimaryAliasId = this.GetPrimaryAliasId(portalSettings.PortalId, portalSettings.CultureCode); + page.Locales = this.GetLocales(portalSettings.PortalId); page.HasParent = tab.ParentId > -1; // icons var iconFile = string.IsNullOrEmpty(tab.IconFile) ? null : FileManager.Instance.GetFile(tab.PortalID, tab.IconFileRaw); - if (iconFile != null) { + if (iconFile != null) + { page.IconFile = new FileDto { fileId = iconFile.FileId, @@ -1091,41 +1090,20 @@ public PageSettings GetPageSettings(int pageId, PortalSettings requestPortalSett public PageUrlResult CreateCustomUrl(SeoUrl dto) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return _pageUrlsController.CreateCustomUrl(dto.SaveUrl, _tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); + return this._pageUrlsController.CreateCustomUrl(dto.SaveUrl, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); } public PageUrlResult UpdateCustomUrl(SeoUrl dto) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return _pageUrlsController.UpdateCustomUrl(dto.SaveUrl, _tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); + return this._pageUrlsController.UpdateCustomUrl(dto.SaveUrl, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); } public PageUrlResult DeleteCustomUrl(UrlIdDto dto) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return _pageUrlsController.DeleteCustomUrl(dto.Id, _tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); - } - protected IOrderedEnumerable> GetLocales(int portalId) - { - var locales = new Lazy>(() => LocaleController.Instance.GetLocales(portalId)); - return locales.Value.Values.Select(local => new KeyValuePair(local.KeyID, local.EnglishName)).OrderBy(x => x.Value); - } - protected IEnumerable> GetSiteAliases(int portalId) - { - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); - return aliases.Select(alias => new KeyValuePair(alias.KeyID, alias.HTTPAlias)).OrderBy(x => x.Value); + return this._pageUrlsController.DeleteCustomUrl(dto.Id, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); } - - protected int? GetPrimaryAliasId(int portalId, string cultureCode) - { - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); - var primary = aliases.Where(a => a.IsPrimary - && (a.CultureCode == cultureCode || String.IsNullOrEmpty(a.CultureCode))) - .OrderByDescending(a => a.CultureCode) - .FirstOrDefault(); - return primary == null ? (int?)null : primary.KeyID; - } - public void CreateOrUpdateContentItem(TabInfo tab) { var contentController = Util.GetContentController(); @@ -1143,27 +1121,47 @@ public void CreateOrUpdateContentItem(TabInfo tab) (from t in typeController.GetContentTypes() where t.ContentType == "Tab" select t).SingleOrDefault(); - - + if (contentType != null) { tab.ContentTypeId = contentType.ContentTypeId; } contentController.AddContentItem(tab); } + + protected IOrderedEnumerable> GetLocales(int portalId) + { + var locales = new Lazy>(() => LocaleController.Instance.GetLocales(portalId)); + return locales.Value.Values.Select(local => new KeyValuePair(local.KeyID, local.EnglishName)).OrderBy(x => x.Value); + } + protected IEnumerable> GetSiteAliases(int portalId) + { + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); + return aliases.Select(alias => new KeyValuePair(alias.KeyID, alias.HTTPAlias)).OrderBy(x => x.Value); + } + + protected int? GetPrimaryAliasId(int portalId, string cultureCode) + { + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); + var primary = aliases.Where(a => a.IsPrimary + && (a.CultureCode == cultureCode || String.IsNullOrEmpty(a.CultureCode))) + .OrderByDescending(a => a.CultureCode) + .FirstOrDefault(); + return primary == null ? (int?)null : primary.KeyID; + } public int UpdateTab(TabInfo tab, PageSettings pageSettings) { - UpdateTabInfoFromPageSettings(tab, pageSettings); - SavePagePermissions(tab, pageSettings.Permissions); + this.UpdateTabInfoFromPageSettings(tab, pageSettings); + this.SavePagePermissions(tab, pageSettings.Permissions); - _tabController.UpdateTab(tab); + this._tabController.UpdateTab(tab); - CreateOrUpdateContentItem(tab); + this.CreateOrUpdateContentItem(tab); - SaveTabUrl(tab, pageSettings); + this.SaveTabUrl(tab, pageSettings); - MovePageIfNeeded(pageSettings, tab); + this.MovePageIfNeeded(pageSettings, tab); return tab.TabID; } @@ -1213,8 +1211,7 @@ public void SavePagePermissions(TabInfo tab, PagePermissions permissions) } } } - - + //add user permissions if (permissions.UserPermissions != null) { @@ -1240,29 +1237,15 @@ public void SavePagePermissions(TabInfo tab, PagePermissions permissions) } } - private static Func NoLocked() - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return r => !(r.Locked && r.RoleId != portalSettings.AdministratorRoleId); - } - - private static bool HasAdminPermissions(PagePermissions permissions) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return permissions.RolePermissions != null && (bool)permissions.RolePermissions?.Any(permission => - permission.RoleId == portalSettings.AdministratorRoleId && - permission.Permissions.Count != 0); - } - public virtual PageSettings GetDefaultSettings(int pageId = 0) { var pageSettings = new PageSettings { - Templates = _templateController.GetTemplates(), - Permissions = GetPermissionsData(pageId) + Templates = this._templateController.GetTemplates(), + Permissions = this.GetPermissionsData(pageId) }; - pageSettings.TemplateId = _templateController.GetDefaultTemplateId(pageSettings.Templates); + pageSettings.TemplateId = this._templateController.GetDefaultTemplateId(pageSettings.Templates); var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (PortalController.GetPortalSettingAsBoolean("SSLEnabled", portalSettings.PortalId, false) && @@ -1274,6 +1257,20 @@ public virtual PageSettings GetDefaultSettings(int pageId = 0) return pageSettings; } + private static Func NoLocked() + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return r => !(r.Locked && r.RoleId != portalSettings.AdministratorRoleId); + } + + private static bool HasAdminPermissions(PagePermissions permissions) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return permissions.RolePermissions != null && (bool)permissions.RolePermissions?.Any(permission => + permission.RoleId == portalSettings.AdministratorRoleId && + permission.Permissions.Count != 0); + } + public PagePermissions GetPermissionsData(int pageId) { var permissions = new PagePermissions(true); @@ -1310,13 +1307,13 @@ public PagePermissions GetPermissionsData(int pageId) public void DeleteTabModule(int pageId, int moduleId) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var tab = _tabController.GetTab(pageId, portalSettings.PortalId); + var tab = this._tabController.GetTab(pageId, portalSettings.PortalId); if (tab == null) { throw new PageModuleNotFoundException(); } - var tabModule = _moduleController.GetModule(moduleId, pageId, false); + var tabModule = this._moduleController.GetModule(moduleId, pageId, false); if (tabModule == null) { throw new PageModuleNotFoundException(); @@ -1327,23 +1324,27 @@ public void DeleteTabModule(int pageId, int moduleId) throw new SecurityException("You do not have permission to delete module on this page"); } - _moduleController.DeleteTabModule(pageId, moduleId, true); - _moduleController.ClearCache(pageId); + this._moduleController.DeleteTabModule(pageId, moduleId, true); + this._moduleController.ClearCache(pageId); } - - + public void CopyContentFromSourceTab(TabInfo tab, int sourceTabId, IEnumerable includedModules) { - var sourceTab = _tabController.GetTab(sourceTabId, tab.PortalID); + var sourceTab = this._tabController.GetTab(sourceTabId, tab.PortalID); if (sourceTab == null || sourceTab.IsDeleted) { return; } //Copy Properties - CopySourceTabProperties(tab, sourceTab); + this.CopySourceTabProperties(tab, sourceTab); //Copy Modules - CopyModulesFromSourceTab(tab, sourceTab, includedModules); + this.CopyModulesFromSourceTab(tab, sourceTab, includedModules); + } + + private static bool HasTags(string tags, IEnumerable terms) + { + return tags.Split(',').All(tag => terms.Any(t => string.Compare(t.Name, tag, StringComparison.CurrentCultureIgnoreCase) == 0)); } private string GetLocalPath(string url) @@ -1364,14 +1365,14 @@ private void CopySourceTabProperties(TabInfo tab, TabInfo sourceTab) tab.PageHeadText = sourceTab.PageHeadText; tab.RefreshInterval = sourceTab.RefreshInterval; tab.IsSecure = sourceTab.IsSecure; - _tabController.UpdateTab(tab); + this._tabController.UpdateTab(tab); //update need tab settings. foreach (var key in TabSettingKeys) { if (sourceTab.TabSettings.ContainsKey(key)) { - _tabController.UpdateTabSetting(tab.TabID, key, Convert.ToString(sourceTab.TabSettings[key])); + this._tabController.UpdateTabSetting(tab.TabID, key, Convert.ToString(sourceTab.TabSettings[key])); } } } @@ -1434,7 +1435,7 @@ private void CopyModulesFromSourceTab(TabInfo tab, TabInfo sourceTab, IEnumerabl { try { - _cloneModuleExecutionContext.SetCloneModuleContext(true); + this._cloneModuleExecutionContext.SetCloneModuleContext(true); var content = Convert.ToString(o.ExportModule(module.Id)); if (!string.IsNullOrEmpty(content)) { @@ -1443,7 +1444,7 @@ private void CopyModulesFromSourceTab(TabInfo tab, TabInfo sourceTab, IEnumerabl } finally { - _cloneModuleExecutionContext.SetCloneModuleContext(false); + this._cloneModuleExecutionContext.SetCloneModuleContext(false); } } } @@ -1469,10 +1470,5 @@ private void CopyModulesFromSourceTab(TabInfo tab, TabInfo sourceTab, IEnumerabl } } } - - private static bool HasTags(string tags, IEnumerable terms) - { - return tags.Split(',').All(tag => terms.Any(t => string.Compare(t.Name, tag, StringComparison.CurrentCultureIgnoreCase) == 0)); - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs index 6dcf73f87bc..11756291362 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs @@ -1,71 +1,74 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Library.Prompt; -using Dnn.PersonaBar.Library.Prompt.Attributes; -using Dnn.PersonaBar.Library.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Exceptions; -using Dnn.PersonaBar.Pages.Components.Security; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands { + using Dnn.PersonaBar.Library.Prompt; + using Dnn.PersonaBar.Library.Prompt.Attributes; + using Dnn.PersonaBar.Library.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Exceptions; + using Dnn.PersonaBar.Pages.Components.Security; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + [ConsoleCommand("delete-page", Constants.PagesCategory, "Prompt_DeletePage_Description")] public class DeletePage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("name", "Prompt_DeletePage_FlagName", "String")] private const string FlagName = "name"; + [FlagParameter("id", "Prompt_DeletePage_FlagId", "Integer")] private const string FlagId = "id"; + [FlagParameter("parentid", "Prompt_DeletePage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; + public override string LocalResourceFile => Constants.LocalResourceFile; + private int PageId { get; set; } = -1; + private string PageName { get; set; } + private int ParentId { get; set; } = -1; public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - - PageId = GetFlagValue(FlagId, "Page Id", -1, false, true); - PageName = GetFlagValue(FlagName, "Page Name", string.Empty); - ParentId = GetFlagValue(FlagParentId, "Parent Id", -1); + { + this.PageId = this.GetFlagValue(FlagId, "Page Id", -1, false, true); + this.PageName = this.GetFlagValue(FlagName, "Page Name", string.Empty); + this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", -1); - if (PageId == -1 && string.IsNullOrEmpty(PageName)) + if (this.PageId == -1 && string.IsNullOrEmpty(this.PageName)) { - AddMessage(LocalizeString("Prompt_ParameterRequired")); + this.AddMessage(this.LocalizeString("Prompt_ParameterRequired")); } } public override ConsoleResultModel Run() { - PageId = PageId != -1 - ? PageId - : (ParentId > 0 ? TabController.Instance.GetTabByName(PageName, PortalId, ParentId) : TabController.Instance.GetTabByName(PageName, PortalId))?.TabID ?? -1; + this.PageId = this.PageId != -1 + ? this.PageId + : (this.ParentId > 0 ? TabController.Instance.GetTabByName(this.PageName, this.PortalId, this.ParentId) : TabController.Instance.GetTabByName(this.PageName, this.PortalId))?.TabID ?? -1; - if (PageId == -1) + if (this.PageId == -1) { - return new ConsoleErrorResultModel(LocalizeString("Prompt_PageNotFound")); + return new ConsoleErrorResultModel(this.LocalizeString("Prompt_PageNotFound")); } - if (!SecurityService.Instance.CanDeletePage(PageId)) + if (!SecurityService.Instance.CanDeletePage(this.PageId)) { - return new ConsoleErrorResultModel(LocalizeString("MethodPermissionDenied")); + return new ConsoleErrorResultModel(this.LocalizeString("MethodPermissionDenied")); } try { - PagesController.Instance.DeletePage(new PageItem { Id = PageId }, PortalSettings); + PagesController.Instance.DeletePage(new PageItem { Id = this.PageId }, this.PortalSettings); } catch (PageNotFoundException) { - return new ConsoleErrorResultModel(LocalizeString("Prompt_PageNotFound")); + return new ConsoleErrorResultModel(this.LocalizeString("Prompt_PageNotFound")); } - return new ConsoleResultModel(LocalizeString("PageDeletedMessage")) { Records = 1 }; + return new ConsoleResultModel(this.LocalizeString("PageDeletedMessage")) { Records = 1 }; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs index 2beef84bb4a..187acec3242 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using Dnn.PersonaBar.Library.Prompt; -using Dnn.PersonaBar.Library.Prompt.Attributes; -using Dnn.PersonaBar.Library.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Security; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using Dnn.PersonaBar.Library.Helper; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands { + using System.Collections.Generic; + + using Dnn.PersonaBar.Library.Helper; + using Dnn.PersonaBar.Library.Prompt; + using Dnn.PersonaBar.Library.Prompt.Attributes; + using Dnn.PersonaBar.Library.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Security; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + [ConsoleCommand("get-page", Constants.PagesCategory, "Prompt_GetPage_Description")] public class GetPage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("name", "Prompt_GetPage_FlagName", "String")] private const string FlagName = "name"; [FlagParameter("id", "Prompt_GetPage_FlagId", "Integer")] @@ -27,19 +26,20 @@ public class GetPage : ConsoleCommandBase [FlagParameter("parentid", "Prompt_GetPage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; + public override string LocalResourceFile => Constants.LocalResourceFile; private readonly ITabController _tabController; private readonly ISecurityService _securityService; private readonly IContentVerifier _contentVerifier; - private int PageId { get; set; } = -1; - private string PageName { get; set; } - private int ParentId { get; set; } = -1; - public GetPage() : this(TabController.Instance, SecurityService.Instance, new ContentVerifier()) { } + private int PageId { get; set; } = -1; + private string PageName { get; set; } + private int ParentId { get; set; } = -1; + public GetPage( ITabController tabController, ISecurityService securityService, @@ -54,39 +54,39 @@ IContentVerifier contentVerifier public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) { - PageId = GetFlagValue(FlagId, "Page Id", -1, false, true); - PageName = GetFlagValue(FlagName, "Page Name", string.Empty); - ParentId = GetFlagValue(FlagParentId, "Parent Id", -1); - if (PageId == -1 && string.IsNullOrEmpty(PageName)) + this.PageId = this.GetFlagValue(FlagId, "Page Id", -1, false, true); + this.PageName = this.GetFlagValue(FlagName, "Page Name", string.Empty); + this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", -1); + if (this.PageId == -1 && string.IsNullOrEmpty(this.PageName)) { - AddMessage(LocalizeString("Prompt_ParameterRequired")); + this.AddMessage(this.LocalizeString("Prompt_ParameterRequired")); } } public override ConsoleResultModel Run() { var lst = new List(); - var tab = PageId != -1 - ? _tabController.GetTab(PageId, PortalId) - : (ParentId > 0 - ? _tabController.GetTabByName(PageName, PortalId, ParentId) - : _tabController.GetTabByName(PageName, PortalId)); + var tab = this.PageId != -1 + ? this._tabController.GetTab(this.PageId, this.PortalId) + : (this.ParentId > 0 + ? this._tabController.GetTabByName(this.PageName, this.PortalId, this.ParentId) + : this._tabController.GetTabByName(this.PageName, this.PortalId)); if (tab != null) { - if (!_securityService.CanManagePage(PageId)) + if (!this._securityService.CanManagePage(this.PageId)) { - return new ConsoleErrorResultModel(LocalizeString("MethodPermissionDenied")); + return new ConsoleErrorResultModel(this.LocalizeString("MethodPermissionDenied")); } - if (_contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, PortalSettings)) + if (this._contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, this.PortalSettings)) { lst.Add(new PageModel(tab)); - return new ConsoleResultModel { Data = lst, Records = lst.Count, Output = LocalizeString("Prompt_PageFound") }; + return new ConsoleResultModel { Data = lst, Records = lst.Count, Output = this.LocalizeString("Prompt_PageFound") }; } } - return new ConsoleErrorResultModel(LocalizeString("Prompt_PageNotFound")); + return new ConsoleErrorResultModel(this.LocalizeString("Prompt_PageNotFound")); } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs new file mode 100644 index 00000000000..7a9297c9617 --- /dev/null +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs @@ -0,0 +1,62 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands +{ + using Dnn.PersonaBar.Library.Prompt; + using Dnn.PersonaBar.Library.Prompt.Attributes; + using Dnn.PersonaBar.Library.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Security; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + + [ConsoleCommand("goto", Constants.PagesCategory, "Prompt_Goto_Description")] + public class Goto : ConsoleCommandBase + { + [FlagParameter("name", "Prompt_Goto_FlagName", "String")] + private const string FlagName = "name"; + [FlagParameter("id", "Prompt_Goto_FlagId", "Integer")] + private const string FlagId = "id"; + [FlagParameter("parentid", "Prompt_Goto_FlagParentId", "Integer")] + private const string FlagParentId = "parentid"; + + public override string LocalResourceFile => Constants.LocalResourceFile; + private int PageId { get; set; } = -1; + private string PageName { get; set; } + private int ParentId { get; set; } = -1; + + public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) + { + + this.PageId = this.GetFlagValue(FlagId, "Page Id", -1, false, true); + this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", -1); + this.PageName = this.GetFlagValue(FlagName, "Page Name", string.Empty); + + if (this.PageId == -1 && string.IsNullOrEmpty(this.PageName)) + { + this.AddMessage(this.LocalizeString("Prompt_ParameterRequired")); + } + } + + public override ConsoleResultModel Run() + { + var tab = this.PageId > 0 + ? TabController.Instance.GetTab(this.PageId, this.PortalId) + : (this.ParentId > 0 + ? TabController.Instance.GetTabByName(this.PageName, this.PortalId, this.ParentId) + : TabController.Instance.GetTabByName(this.PageName, this.PortalId)); + + if (tab == null) + { + return new ConsoleErrorResultModel(this.LocalizeString("Prompt_PageNotFound")); + } + if (!SecurityService.Instance.CanManagePage(this.PageId)) + { + return new ConsoleErrorResultModel(this.LocalizeString("MethodPermissionDenied")); + } + return new ConsoleResultModel(tab.FullUrl) { MustReload = true }; + } + } +} diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GotoPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GotoPage.cs deleted file mode 100644 index 53dac158fdd..00000000000 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GotoPage.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Library.Prompt; -using Dnn.PersonaBar.Library.Prompt.Attributes; -using Dnn.PersonaBar.Library.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Security; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; - -namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands -{ - [ConsoleCommand("goto", Constants.PagesCategory, "Prompt_Goto_Description")] - public class Goto : ConsoleCommandBase - { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("name", "Prompt_Goto_FlagName", "String")] - private const string FlagName = "name"; - [FlagParameter("id", "Prompt_Goto_FlagId", "Integer")] - private const string FlagId = "id"; - [FlagParameter("parentid", "Prompt_Goto_FlagParentId", "Integer")] - private const string FlagParentId = "parentid"; - - private int PageId { get; set; } = -1; - private string PageName { get; set; } - private int ParentId { get; set; } = -1; - - public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - - PageId = GetFlagValue(FlagId, "Page Id", -1, false, true); - ParentId = GetFlagValue(FlagParentId, "Parent Id", -1); - PageName = GetFlagValue(FlagName, "Page Name", string.Empty); - - if (PageId == -1 && string.IsNullOrEmpty(PageName)) - { - AddMessage(LocalizeString("Prompt_ParameterRequired")); - } - } - - public override ConsoleResultModel Run() - { - var tab = PageId > 0 - ? TabController.Instance.GetTab(PageId, PortalId) - : (ParentId > 0 - ? TabController.Instance.GetTabByName(PageName, PortalId, ParentId) - : TabController.Instance.GetTabByName(PageName, PortalId)); - - if (tab == null) - { - return new ConsoleErrorResultModel(LocalizeString("Prompt_PageNotFound")); - } - if (!SecurityService.Instance.CanManagePage(PageId)) - { - return new ConsoleErrorResultModel(LocalizeString("MethodPermissionDenied")); - } - return new ConsoleResultModel(tab.FullUrl) {MustReload = true}; - } - } -} diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs index 42732a3e366..7ad3fd39cbe 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs @@ -1,23 +1,22 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using System.Linq; -using Dnn.PersonaBar.Library.Prompt; -using Dnn.PersonaBar.Library.Prompt.Attributes; -using Dnn.PersonaBar.Library.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Prompt.Models; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands { + using System.Collections.Generic; + using System.Linq; + + using Dnn.PersonaBar.Library.Prompt; + using Dnn.PersonaBar.Library.Prompt.Attributes; + using Dnn.PersonaBar.Library.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Prompt.Models; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + [ConsoleCommand("list-pages", Constants.PagesCategory, "Prompt_ListPages_Description")] public class ListPages : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("parentid", "Prompt_ListPages_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; @@ -44,6 +43,8 @@ public class ListPages : ConsoleCommandBase [FlagParameter("max", "Prompt_ListRoles_FlagMax", "Integer", "10")] private const string FlagMax = "max"; + + public override string LocalResourceFile => Constants.LocalResourceFile; private int? ParentId { get; set; } = -1; private bool? Deleted { get; set; } @@ -58,20 +59,20 @@ public class ListPages : ConsoleCommandBase public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) { - ParentId = GetFlagValue(FlagParentId, "Parent Id", null, false, true, true); - Deleted = GetFlagValue(FlagDeleted, "Deleted", null); - PageVisible = GetFlagValue(FlagVisible, "Page Visible", null); - PageName = GetFlagValue(FlagName, "Page Name", string.Empty); - PageTitle = GetFlagValue(FlagTitle, "Page Title", string.Empty); - PagePath = GetFlagValue(FlagPath, "Page Path", string.Empty); - PageSkin = GetFlagValue(FlagSkin, "Page Skin", string.Empty); - Page = GetFlagValue(FlagPage, "Page", 1); - Max = GetFlagValue(FlagMax, "Max", 10); + this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", null, false, true, true); + this.Deleted = this.GetFlagValue(FlagDeleted, "Deleted", null); + this.PageVisible = this.GetFlagValue(FlagVisible, "Page Visible", null); + this.PageName = this.GetFlagValue(FlagName, "Page Name", string.Empty); + this.PageTitle = this.GetFlagValue(FlagTitle, "Page Title", string.Empty); + this.PagePath = this.GetFlagValue(FlagPath, "Page Path", string.Empty); + this.PageSkin = this.GetFlagValue(FlagSkin, "Page Skin", string.Empty); + this.Page = this.GetFlagValue(FlagPage, "Page", 1); + this.Max = this.GetFlagValue(FlagMax, "Max", 10); } public override ConsoleResultModel Run() { - var max = Max <= 0 ? 10 : (Max > 500 ? 500 : Max); + var max = this.Max <= 0 ? 10 : (this.Max > 500 ? 500 : this.Max); var lstOut = new List(); @@ -79,9 +80,9 @@ public override ConsoleResultModel Run() IEnumerable lstTabs; - lstTabs = PagesController.Instance.GetPageList(PortalSettings, Deleted, PageName, PageTitle, PagePath, PageSkin, PageVisible, ParentId ?? -1, out total, string.Empty, Page > 0 ? Page - 1 : 0, max, ParentId == null); + lstTabs = PagesController.Instance.GetPageList(this.PortalSettings, this.Deleted, this.PageName, this.PageTitle, this.PagePath, this.PageSkin, this.PageVisible, this.ParentId ?? -1, out total, string.Empty, this.Page > 0 ? this.Page - 1 : 0, max, this.ParentId == null); var totalPages = total / max + (total % max == 0 ? 0 : 1); - var pageNo = Page > 0 ? Page : 1; + var pageNo = this.Page > 0 ? this.Page : 1; lstOut.AddRange(lstTabs.Select(tab => new PageModelBase(tab))); return new ConsoleResultModel { @@ -93,7 +94,7 @@ public override ConsoleResultModel Run() PageSize = max }, Records = lstOut.Count, - Output = lstOut.Count == 0 ? LocalizeString("Prompt_NoPages") : "", + Output = lstOut.Count == 0 ? this.LocalizeString("Prompt_NoPages") : "", FieldOrder = new[] { "TabId", "ParentId", "Name", "Title", "Skin", "Path", "IncludeInMenu", "IsDeleted" diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs index 0b9b8432534..5fbe6fbf6a0 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System.Collections.Generic; -using Dnn.PersonaBar.Library.Prompt; -using Dnn.PersonaBar.Library.Prompt.Attributes; -using Dnn.PersonaBar.Library.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Exceptions; -using Dnn.PersonaBar.Pages.Components.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Security; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands { + using System.Collections.Generic; + + using Dnn.PersonaBar.Library.Prompt; + using Dnn.PersonaBar.Library.Prompt.Attributes; + using Dnn.PersonaBar.Library.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Exceptions; + using Dnn.PersonaBar.Pages.Components.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Security; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + [ConsoleCommand("new-page", Constants.PagesCategory, "Prompt_NewPage_Description")] public class NewPage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("parentid", "Prompt_NewPage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; @@ -40,6 +39,8 @@ public class NewPage : ConsoleCommandBase [FlagParameter("visible", "Prompt_NewPage_FlagVisible", "Boolean", "true")] private const string FlagVisible = "visible"; + + public override string LocalResourceFile => Constants.LocalResourceFile; private string Title { get; set; } private string Name { get; set; } @@ -50,22 +51,22 @@ public class NewPage : ConsoleCommandBase private bool? Visible { get; set; } public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - - ParentId = GetFlagValue(FlagParentId, "Parent Id", null, false, false, true); - Title = GetFlagValue(FlagTitle, "Title", string.Empty); - Name = GetFlagValue(FlagName, "Page Name", string.Empty, true, true); - Url = GetFlagValue(FlagUrl, "Url", string.Empty); - Description = GetFlagValue(FlagDescription, "Description", string.Empty); - Keywords = GetFlagValue(FlagKeywords, "Keywords", string.Empty); - Visible = GetFlagValue(FlagVisible, "Visible", true); + { + + this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", null, false, false, true); + this.Title = this.GetFlagValue(FlagTitle, "Title", string.Empty); + this.Name = this.GetFlagValue(FlagName, "Page Name", string.Empty, true, true); + this.Url = this.GetFlagValue(FlagUrl, "Url", string.Empty); + this.Description = this.GetFlagValue(FlagDescription, "Description", string.Empty); + this.Keywords = this.GetFlagValue(FlagKeywords, "Keywords", string.Empty); + this.Visible = this.GetFlagValue(FlagVisible, "Visible", true); // validate that parent ID is a valid ID, if it has been passed - if (!ParentId.HasValue) return; - var testTab = TabController.Instance.GetTab((int)ParentId, PortalId); + if (!this.ParentId.HasValue) return; + var testTab = TabController.Instance.GetTab((int)this.ParentId, this.PortalId); if (testTab == null) { - AddMessage(string.Format(LocalizeString("Prompt_UnableToFindSpecified"), FlagParentId, ParentId)); + this.AddMessage(string.Format(this.LocalizeString("Prompt_UnableToFindSpecified"), FlagParentId, this.ParentId)); } } @@ -75,15 +76,15 @@ public override ConsoleResultModel Run() try { var pageSettings = PagesController.Instance.GetDefaultSettings(); - pageSettings.Name = !string.IsNullOrEmpty(Name) ? Name : pageSettings.Name; - pageSettings.Title = !string.IsNullOrEmpty(Title) ? Title : pageSettings.Title; - pageSettings.Url = !string.IsNullOrEmpty(Url) ? Url : pageSettings.Url; - pageSettings.Description = !string.IsNullOrEmpty(Description) ? Description : pageSettings.Description; - pageSettings.Keywords = !string.IsNullOrEmpty(Keywords) ? Keywords : pageSettings.Keywords; - pageSettings.ParentId = ParentId.HasValue ? ParentId : pageSettings.ParentId; - pageSettings.HasParent = ParentId.HasValue; - pageSettings.IncludeInMenu = Visible ?? pageSettings.IncludeInMenu; - pageSettings.IncludeInMenu = Visible ?? true; + pageSettings.Name = !string.IsNullOrEmpty(this.Name) ? this.Name : pageSettings.Name; + pageSettings.Title = !string.IsNullOrEmpty(this.Title) ? this.Title : pageSettings.Title; + pageSettings.Url = !string.IsNullOrEmpty(this.Url) ? this.Url : pageSettings.Url; + pageSettings.Description = !string.IsNullOrEmpty(this.Description) ? this.Description : pageSettings.Description; + pageSettings.Keywords = !string.IsNullOrEmpty(this.Keywords) ? this.Keywords : pageSettings.Keywords; + pageSettings.ParentId = this.ParentId.HasValue ? this.ParentId : pageSettings.ParentId; + pageSettings.HasParent = this.ParentId.HasValue; + pageSettings.IncludeInMenu = this.Visible ?? pageSettings.IncludeInMenu; + pageSettings.IncludeInMenu = this.Visible ?? true; if (pageSettings.ParentId != null) { var parentTab = PagesController.Instance.GetPageSettings(pageSettings.ParentId.Value); @@ -95,9 +96,9 @@ public override ConsoleResultModel Run() if (!SecurityService.Instance.CanSavePageDetails(pageSettings)) { - return new ConsoleErrorResultModel(LocalizeString("MethodPermissionDenied")); + return new ConsoleErrorResultModel(this.LocalizeString("MethodPermissionDenied")); } - var newTab = PagesController.Instance.SavePageDetails(PortalSettings, pageSettings); + var newTab = PagesController.Instance.SavePageDetails(this.PortalSettings, pageSettings); // create the tab var lstResults = new List(); @@ -107,14 +108,14 @@ public override ConsoleResultModel Run() } else { - return new ConsoleErrorResultModel(LocalizeString("Prompt_PageCreateFailed")); + return new ConsoleErrorResultModel(this.LocalizeString("Prompt_PageCreateFailed")); } - return new ConsoleResultModel(LocalizeString("Prompt_PageCreated")) { Data = lstResults, Records = lstResults.Count }; + return new ConsoleResultModel(this.LocalizeString("Prompt_PageCreated")) { Data = lstResults, Records = lstResults.Count }; } catch (PageNotFoundException) { - return new ConsoleErrorResultModel(LocalizeString("PageNotFound")); + return new ConsoleErrorResultModel(this.LocalizeString("PageNotFound")); } catch (PageValidationException ex) { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs index 703fe9c40df..74d013d24ce 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs @@ -1,25 +1,24 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections.Generic; -using Dnn.PersonaBar.Library.Prompt; -using Dnn.PersonaBar.Library.Prompt.Attributes; -using Dnn.PersonaBar.Library.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Exceptions; -using Dnn.PersonaBar.Pages.Components.Prompt.Models; -using Dnn.PersonaBar.Pages.Components.Security; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Users; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands { + using System; + using System.Collections.Generic; + + using Dnn.PersonaBar.Library.Prompt; + using Dnn.PersonaBar.Library.Prompt.Attributes; + using Dnn.PersonaBar.Library.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Exceptions; + using Dnn.PersonaBar.Pages.Components.Prompt.Models; + using Dnn.PersonaBar.Pages.Components.Security; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + [ConsoleCommand("set-page", Constants.PagesCategory, "Prompt_SetPage_Description")] public class SetPage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("id", "Prompt_SetPage_FlagId", "Integer", true)] private const string FlagId = "id"; @@ -43,6 +42,8 @@ public class SetPage : ConsoleCommandBase [FlagParameter("parentid", "Prompt_SetPage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; + + public override string LocalResourceFile => Constants.LocalResourceFile; private int PageId { get; set; } private int? ParentId { get; set; } @@ -54,19 +55,19 @@ public class SetPage : ConsoleCommandBase private bool? Visible { get; set; } public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - - PageId = GetFlagValue(FlagId, "Page Id", -1, true, true, true); - ParentId = GetFlagValue(FlagParentId, "Parent Id", null); - Title = GetFlagValue(FlagTitle, "Title", string.Empty); - Name = GetFlagValue(FlagName, "Page Name", string.Empty); - Url = GetFlagValue(FlagUrl, "Url", string.Empty); - Description = GetFlagValue(FlagDescription, "Description", string.Empty); - Keywords = GetFlagValue(FlagKeywords, "Keywords", string.Empty); - Visible = GetFlagValue(FlagVisible, "Visible", null); - if (string.IsNullOrEmpty(Title) && string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Description) && string.IsNullOrEmpty(Keywords) && string.IsNullOrEmpty(Url) && !ParentId.HasValue && !Visible.HasValue) + { + + this.PageId = this.GetFlagValue(FlagId, "Page Id", -1, true, true, true); + this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", null); + this.Title = this.GetFlagValue(FlagTitle, "Title", string.Empty); + this.Name = this.GetFlagValue(FlagName, "Page Name", string.Empty); + this.Url = this.GetFlagValue(FlagUrl, "Url", string.Empty); + this.Description = this.GetFlagValue(FlagDescription, "Description", string.Empty); + this.Keywords = this.GetFlagValue(FlagKeywords, "Keywords", string.Empty); + this.Visible = this.GetFlagValue(FlagVisible, "Visible", null); + if (string.IsNullOrEmpty(this.Title) && string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.Description) && string.IsNullOrEmpty(this.Keywords) && string.IsNullOrEmpty(this.Url) && !this.ParentId.HasValue && !this.Visible.HasValue) { - AddMessage(string.Format(LocalizeString("Prompt_NothingToUpdate"), FlagTitle, FlagDescription, FlagName, FlagVisible)); + this.AddMessage(string.Format(this.LocalizeString("Prompt_NothingToUpdate"), FlagTitle, FlagDescription, FlagName, FlagVisible)); } } @@ -74,35 +75,35 @@ public override ConsoleResultModel Run() { try { - var pageSettings = PagesController.Instance.GetPageSettings(PageId, PortalSettings); + var pageSettings = PagesController.Instance.GetPageSettings(this.PageId, this.PortalSettings); if (pageSettings == null) { - return new ConsoleErrorResultModel(LocalizeString("PageNotFound")); + return new ConsoleErrorResultModel(this.LocalizeString("PageNotFound")); } - pageSettings.Name = !string.IsNullOrEmpty(Name) ? Name : pageSettings.Name; - pageSettings.Title = !string.IsNullOrEmpty(Title) ? Title : pageSettings.Title; - pageSettings.Url = !string.IsNullOrEmpty(Url) ? Url : pageSettings.Url; - pageSettings.Description = !string.IsNullOrEmpty(Description) ? Description : pageSettings.Description; - pageSettings.Keywords = !string.IsNullOrEmpty(Keywords) ? Keywords : pageSettings.Keywords; - pageSettings.ParentId = ParentId.HasValue ? ParentId : pageSettings.ParentId; - pageSettings.IncludeInMenu = Visible ?? pageSettings.IncludeInMenu; + pageSettings.Name = !string.IsNullOrEmpty(this.Name) ? this.Name : pageSettings.Name; + pageSettings.Title = !string.IsNullOrEmpty(this.Title) ? this.Title : pageSettings.Title; + pageSettings.Url = !string.IsNullOrEmpty(this.Url) ? this.Url : pageSettings.Url; + pageSettings.Description = !string.IsNullOrEmpty(this.Description) ? this.Description : pageSettings.Description; + pageSettings.Keywords = !string.IsNullOrEmpty(this.Keywords) ? this.Keywords : pageSettings.Keywords; + pageSettings.ParentId = this.ParentId.HasValue ? this.ParentId : pageSettings.ParentId; + pageSettings.IncludeInMenu = this.Visible ?? pageSettings.IncludeInMenu; if (!SecurityService.Instance.CanSavePageDetails(pageSettings)) { - return new ConsoleErrorResultModel(LocalizeString("MethodPermissionDenied")); + return new ConsoleErrorResultModel(this.LocalizeString("MethodPermissionDenied")); } - var updatedTab = PagesController.Instance.SavePageDetails(PortalSettings, pageSettings); + var updatedTab = PagesController.Instance.SavePageDetails(this.PortalSettings, pageSettings); var lstResults = new List { new PageModel(updatedTab) }; - return new ConsoleResultModel(LocalizeString("PageUpdatedMessage")) { Data = lstResults, Records = lstResults.Count }; + return new ConsoleResultModel(this.LocalizeString("PageUpdatedMessage")) { Data = lstResults, Records = lstResults.Count }; } catch (PageNotFoundException) { - return new ConsoleErrorResultModel(LocalizeString("PageNotFound")); + return new ConsoleErrorResultModel(this.LocalizeString("PageNotFound")); } catch (PageValidationException ex) { return new ConsoleErrorResultModel(ex.Message); } - } + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs index 9946267ac54..af7ed662341 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs @@ -1,25 +1,25 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Prompt.Models { public class PageModel : PageModelBase { - public string Container { get; set; } - public string Url { get; set; } - public string Keywords { get; set; } - public string Description { get; set; } - public PageModel() { } - public PageModel(DotNetNuke.Entities.Tabs.TabInfo tab): base(tab) + + public PageModel(DotNetNuke.Entities.Tabs.TabInfo tab) : base(tab) { - Container = tab.ContainerSrc; - Url = tab.Url; - Keywords = tab.KeyWords; - Description = tab.Description; + this.Container = tab.ContainerSrc; + this.Url = tab.Url; + this.Keywords = tab.KeyWords; + this.Description = tab.Description; } + public string Container { get; set; } + public string Url { get; set; } + public string Keywords { get; set; } + public string Description { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs index 1b7bb99e9cb..a4b489f9b42 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs @@ -1,11 +1,15 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Prompt.Models { public class PageModelBase { + public PageModelBase() + { + } + public int TabId { get; set; } public string Name { get; set; } public string Title { get; set; } @@ -13,34 +17,25 @@ public class PageModelBase public string Skin { get; set; } public string Path { get; set; } public bool IncludeInMenu { get; set; } - public bool IsDeleted { get; set; } - - #region Command Links - public string __TabId => $"get-page {TabId}"; - - public string __ParentId => $"list-pages --parentid {ParentId}"; + public bool IsDeleted { get; set; } + + public string __TabId => $"get-page {this.TabId}"; - public string __IncludeInMenu => $"list-pages --visible{(IncludeInMenu ? "" : " false")}"; + public string __ParentId => $"list-pages --parentid {this.ParentId}"; - public string __IsDeleted => $"list-pages --deleted{(IsDeleted ? "" : " false")}"; + public string __IncludeInMenu => $"list-pages --visible{(this.IncludeInMenu ? "" : " false")}"; - #endregion - - #region constructors - public PageModelBase() - { - } + public string __IsDeleted => $"list-pages --deleted{(this.IsDeleted ? "" : " false")}"; public PageModelBase(DotNetNuke.Entities.Tabs.TabInfo tab) { - Name = tab.TabName; - ParentId = tab.ParentId; - Path = tab.TabPath; - TabId = tab.TabID; - Skin = tab.SkinSrc; - Title = tab.Title; - IncludeInMenu = tab.IsVisible; - IsDeleted = tab.IsDeleted; - } - #endregion + this.Name = tab.TabName; + this.ParentId = tab.ParentId; + this.Path = tab.TabPath; + this.TabId = tab.TabID; + this.Skin = tab.SkinSrc; + this.Title = tab.Title; + this.IncludeInMenu = tab.IsVisible; + this.IsDeleted = tab.IsDeleted; + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PublishStatus.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PublishStatus.cs index 0b905ba6194..a98a0b3268f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PublishStatus.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PublishStatus.cs @@ -1,7 +1,7 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { public enum PublishStatus diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/ISecurityService.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/ISecurityService.cs index bf8f7be9f47..3bb37597d80 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/ISecurityService.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/ISecurityService.cs @@ -1,14 +1,14 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using Dnn.PersonaBar.Library.Model; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Entities.Tabs; -using Newtonsoft.Json.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Security { + using Dnn.PersonaBar.Library.Model; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Entities.Tabs; + using Newtonsoft.Json.Linq; + public interface ISecurityService { bool IsVisible(MenuItem menuItem); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs index 8bc05d7de65..df330e9705d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs @@ -1,31 +1,32 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Security.Permissions; -using Dnn.PersonaBar.Library.Model; -using Dnn.PersonaBar.Library.Permissions; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Common.Utilities; -using DotNetNuke.ComponentModel; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Entities.Users; -using DotNetNuke.Framework; -using DotNetNuke.Security.Permissions; -using DotNetNuke.Services.FileSystem; -using Newtonsoft.Json.Linq; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components.Security { + using System; + using System.Security.Permissions; + + using Dnn.PersonaBar.Library.Model; + using Dnn.PersonaBar.Library.Permissions; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Services.FileSystem; + using Newtonsoft.Json.Linq; + public class SecurityService : ISecurityService { private readonly ITabController _tabController; public SecurityService() { - _tabController = TabController.Instance; + this._tabController = TabController.Instance; } public static ISecurityService Instance @@ -50,19 +51,7 @@ public virtual bool IsPageAdminUser() public virtual bool IsVisible(MenuItem menuItem) { - return IsPageAdminUser() || CanViewPageList(menuItem.MenuId); - } - - private bool IsPageAdmin() - { - return //TabPermissionController.CanAddContentToPage() || - TabPermissionController.CanAddPage() - || TabPermissionController.CanAdminPage() - || TabPermissionController.CanCopyPage() - || TabPermissionController.CanDeletePage() - || TabPermissionController.CanExportPage() - || TabPermissionController.CanImportPage() - || TabPermissionController.CanManagePage(); + return this.IsPageAdminUser() || this.CanViewPageList(menuItem.MenuId); } public virtual JObject GetCurrentPagePermissions() @@ -82,6 +71,18 @@ public virtual JObject GetCurrentPagePermissions() return permissions; } + private bool IsPageAdmin() + { + return //TabPermissionController.CanAddContentToPage() || + TabPermissionController.CanAddPage() + || TabPermissionController.CanAdminPage() + || TabPermissionController.CanCopyPage() + || TabPermissionController.CanDeletePage() + || TabPermissionController.CanExportPage() + || TabPermissionController.CanImportPage() + || TabPermissionController.CanManagePage(); + } + public virtual JObject GetPagePermissions(TabInfo tab) { var permissions = new JObject @@ -101,38 +102,38 @@ public virtual JObject GetPagePermissions(TabInfo tab) public virtual bool CanAdminPage(int tabId) { - return IsPageAdminUser() || TabPermissionController.CanAdminPage(GetTabById(tabId)); + return this.IsPageAdminUser() || TabPermissionController.CanAdminPage(this.GetTabById(tabId)); } public virtual bool CanManagePage(int tabId) { - return CanAdminPage(tabId) || TabPermissionController.CanManagePage(GetTabById(tabId)); + return this.CanAdminPage(tabId) || TabPermissionController.CanManagePage(this.GetTabById(tabId)); } public virtual bool CanDeletePage(int tabId) { - return CanAdminPage(tabId) || TabPermissionController.CanDeletePage(GetTabById(tabId)); + return this.CanAdminPage(tabId) || TabPermissionController.CanDeletePage(this.GetTabById(tabId)); } public virtual bool CanAddPage(int tabId) { - return CanAdminPage(tabId) || TabPermissionController.CanAddPage(GetTabById(tabId)); + return this.CanAdminPage(tabId) || TabPermissionController.CanAddPage(this.GetTabById(tabId)); } public virtual bool CanCopyPage(int tabId) { - return CanAdminPage(tabId) || TabPermissionController.CanCopyPage(GetTabById(tabId)); + return this.CanAdminPage(tabId) || TabPermissionController.CanCopyPage(this.GetTabById(tabId)); } public virtual bool CanExportPage(int tabId) { - return CanAdminPage(tabId) || TabPermissionController.CanExportPage(GetTabById(tabId)); + return this.CanAdminPage(tabId) || TabPermissionController.CanExportPage(this.GetTabById(tabId)); } public virtual bool CanViewPageList(int menuId) { var permissions = MenuPermissionController.GetMenuPermissions(PortalSettings.Current.PortalId, menuId); - return MenuPermissionController.HasMenuPermission(new MenuPermissionCollection(permissions), "VIEW_PAGE_LIST") || IsPageAdmin(); + return MenuPermissionController.HasMenuPermission(new MenuPermissionCollection(permissions), "VIEW_PAGE_LIST") || this.IsPageAdmin(); } public virtual bool CanSavePageDetails(PageSettings pageSettings) @@ -155,12 +156,12 @@ public virtual bool CanSavePageDetails(PageSettings pageSettings) } return ( - IsPageAdminUser() || - creatingPage && CanAddPage(parentId) && !creatingTemplate || - creatingTemplate && CanExportPage(pageSettings.TemplateTabId) || - updatingPage && CanManagePage(tabId) && !updatingParentPage || - updatingParentPage && CanManagePage(tabId) && CanAddPage(parentId) || - duplicatingPage && CanCopyPage(pageSettings.TemplateTabId) && CanAddPage(parentId) + this.IsPageAdminUser() || + creatingPage && this.CanAddPage(parentId) && !creatingTemplate || + creatingTemplate && this.CanExportPage(pageSettings.TemplateTabId) || + updatingPage && this.CanManagePage(tabId) && !updatingParentPage || + updatingParentPage && this.CanManagePage(tabId) && this.CanAddPage(parentId) || + duplicatingPage && this.CanCopyPage(pageSettings.TemplateTabId) && this.CanAddPage(parentId) ); } @@ -173,7 +174,7 @@ public virtual bool IsAdminHostSystemPage() private TabInfo GetTabById(int pageId) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return pageId <= 0 ? new TabInfo() : _tabController.GetTab(pageId, portalSettings.PortalId, false); + return pageId <= 0 ? new TabInfo() : this._tabController.GetTab(pageId, portalSettings.PortalId, false); } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs index 08687ff5168..2fdf72b23be 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs @@ -1,28 +1,29 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; -using System.Xml; -using Dnn.PersonaBar.Pages.Components.Dto; -using Dnn.PersonaBar.Pages.Components.Exceptions; -using Dnn.PersonaBar.Pages.Services.Dto; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Framework; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Web.UI; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + namespace Dnn.PersonaBar.Pages.Components { + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + using System.Xml; + + using Dnn.PersonaBar.Pages.Components.Dto; + using Dnn.PersonaBar.Pages.Components.Exceptions; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Framework; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Web.UI; + public class TemplateController : ServiceLocator, ITemplateController { private const string TemplatesFolderPath = "Templates/"; @@ -31,13 +32,14 @@ public class TemplateController : ServiceLocator GetTemplates() + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var templateFolder = FolderManager.Instance.GetFolder(portalSettings.PortalId, TemplatesFolderPath); + + return this.LoadTemplates(portalSettings.PortalId, templateFolder); + } + + public int GetDefaultTemplateId(IEnumerable